-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstarrydata_utils.py
More file actions
2270 lines (1905 loc) · 80.8 KB
/
starrydata_utils.py
File metadata and controls
2270 lines (1905 loc) · 80.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
starrydata_utils.py - Consolidated utility functions for Starrydata analysis
Extracted from notebook-derived Python files (2017-2026).
Each function is the latest working version from the most recent notebook.
Sections:
1. Constants (element list, physical constants)
2. Composition functions (comp2dict, comp2vec, vec2comp, contains)
3. Data processing (flatten_dict, r, weighted_mobility, parse_array_string)
4. Data loading (load_curves, load_samples)
5. Interpolation (spline_interpolate_curves)
6. Derived properties (calculate_derived_properties)
7. Material family classification (classify_material_families)
8. Sample selection (selectsamples)
9. PCA & clustering (pca2, generate_rainbow_colors)
10. Plotting - matplotlib (TEplot4, TEplot6)
11. Plotting - plotly (plotly_2d, plotly3, plotly_pca3)
"""
import numpy as np
import pandas as pd
import math
from pymatgen.core.composition import Composition
# =============================================================================
# 1. Constants
# =============================================================================
# 100 elements from H to Fm (used as composition vector indices)
L_ELEMENT = [
'H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne',
'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca',
'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn',
'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr',
'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn',
'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd',
'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb',
'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg',
'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th',
'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm',
]
# Physical constants
PI = 3.141592653
E_CHARGE = 1.602176634e-19 # elementary charge [C]
M_ELECTRON = 9.1093837015e-31 # electron mass [kg]
K_BOLTZMANN = 1.380649e-23 # Boltzmann constant [J/K]
LORENZ = PI**2 / 3 * (K_BOLTZMANN / E_CHARGE)**2 # Lorenz number [W Omega / K^2]
# Standard thermoelectric property names in Starrydata
TE_PROPERTIES = [
'Electrical resistivity', 'Electrical conductivity',
'Seebeck coefficient', 'Thermal conductivity',
'Power factor', 'ZT', 'Carrier mobility', 'Hall coefficient',
]
# Derived property column names
DERIVED_PROPERTIES = [
'log10(Electrical conductivity)', 'Lattice thermal conductivity',
'Z', 'Weighted mobility',
]
# Standard parent compound list for TE materials
L_PARENTS = [
'PbTe', 'PbSe', 'PbS', 'SnTe', 'SnSe', 'SnS', 'GeTe', 'GeSe', 'GeS',
'Bi2Te3', 'Sb2Te3', 'Bi2Se3', 'Sb2Se3', 'Bi2S3', 'Sb2S3',
'CoSb3', 'CeFe4Sb12',
'TiNiSn', 'ZrNiSn', 'HfNiSn', 'TiCoSb', 'ZrCoSb', 'HfCoSb',
'VFeSb', 'NbFeSb', 'TaFeSb',
'Mg2Si', 'Mg2Ge', 'Mg2Sn', 'Mg3Sb2',
'Cu2Se', 'Cu2S', 'Cu2Te', 'Ag2Se', 'Ag2S', 'Ag2Te',
'Ba8Ga16Ge30', 'Ba8Al16Ge30', 'Sr8Ga16Ge30',
'SrTiO3', 'CaMnO3', 'ZnO', 'Ca3Co4O9', 'NaCoO2',
'Zn4Sb3', 'YbZn2Sb2', 'Yb14MnSb11', 'MgAgSb',
'Si', 'Ge', 'MnSi1.7',
'YbAl3', 'CeCoIn5',
]
# =============================================================================
# 2. Composition functions
# =============================================================================
def comp2dict(str_comp):
"""Convert composition string to element-fraction dictionary (100 elements).
Source: 250603_TEfamilies.py (latest)
Parameters:
str_comp (str): Chemical formula, e.g. 'PbTe', 'Bi0.5Sb1.5Te3'
Returns:
dict: {element: atomic_fraction} for all 100 elements
"""
d_comp = {}
try:
comp = Composition(str_comp)
for element in L_ELEMENT:
d_comp[element] = np.round(comp.get_atomic_fraction(element), 5)
except Exception:
pass
return d_comp
def comp2vec(str_comp):
"""Convert composition string to 100-element numpy vector.
Source: 210712_TEcompositions.py
Parameters:
str_comp (str): Chemical formula
Returns:
np.ndarray: Length-100 vector of atomic fractions (H to Fm)
"""
vec = np.zeros(100)
try:
comp = Composition(str_comp)
for i, element in enumerate(L_ELEMENT):
vec[i] = comp.get_atomic_fraction(element)
except Exception:
pass
return vec
def vec2comp(vec, dp=4):
"""Convert composition vector back to pymatgen Composition.
Source: 210712_TEcompositions.py
Parameters:
vec (np.ndarray): Length-100 atomic fraction vector
dp (int): Decimal precision for rounding
Returns:
Composition or None: pymatgen Composition object
"""
str_comp = ''
for i in range(len(vec)):
if vec[i] > 0:
str_comp += L_ELEMENT[i] + str(round(vec[i], dp))
try:
return Composition(str_comp)
except Exception:
return None
def contains(d_comp, l_elements, min_amount, d=0.0001):
"""Check if composition contains specified elements above threshold.
Source: 260128_alldataplots.py
Parameters:
d_comp (dict): Composition dictionary from comp2dict()
l_elements (list): Element symbols to check, e.g. ['Pb', 'Sn']
min_amount (float): Minimum total atomic fraction
d (float): Small offset to avoid zero-division
Returns:
bool: True if total fraction of specified elements exceeds min_amount
"""
amount = d
for element in l_elements:
amount += d_comp.get(element, 0)
return amount > min_amount
# =============================================================================
# 3. Data processing utilities
# =============================================================================
def flatten_dict(str_d_si, parent_key='', sep='.', result=''):
"""Convert sample_info JSON string to readable short string.
Source: 250603_TEfamilies.py (latest)
Parameters:
str_d_si (str): JSON string from sample_info column
Returns:
str: Formatted string like 'key1:category1 (comment1) | key2:category2'
"""
str_si = ''
try:
d_si = eval(str_d_si)
except Exception:
return str_si
try:
for key, d_cc in d_si.items():
if d_cc != '':
delimiter = '' if str_si == '' else ' | '
if d_cc['category'] != '':
if d_cc['comment'] != '':
str_si += f"{delimiter}{key}:{d_cc['category']} ({d_cc['comment']})"
else:
str_si += f"{delimiter}{key}:{d_cc['category']}"
except Exception:
pass
return str_si
def r(value, precision=5):
"""Round float to scientific notation with given precision.
Source: 250603_TEfamilies.py
Parameters:
value (float): Number to round
precision (int): Significant digits
Returns:
float: Rounded value
"""
try:
return float(np.format_float_scientific(value, precision))
except Exception:
return float('nan')
def weighted_mobility(S_SI, rho_SI, T):
"""Calculate weighted mobility from Seebeck coefficient and resistivity.
Based on Snyder's quality factor formalism.
Source: 250603_TEfamilies.py (latest)
Parameters:
S_SI (float): Seebeck coefficient [V/K]
rho_SI (float): Electrical resistivity [Ohm*m]
T (float): Temperature [K]
Returns:
float: Weighted mobility [cm^2/Vs]
"""
S = S_SI * 1e6 # V/K -> uV/K
rho = rho_SI * 1e5 # Ohm*m -> mOhm*cm
A = np.abs(S) / (K_BOLTZMANN / E_CHARGE * 1e6)
# Clip exponent arguments to prevent overflow (exp(709) ~ 1e308 = float64 max)
A_clip = np.clip(A, -500, 500)
exp_A2 = np.exp(np.clip(A_clip - 2, -500, 500))
exp_neg5 = np.exp(np.clip(-5 * (A_clip - 1), -500, 500))
exp_pos5 = np.exp(np.clip(5 * (A_clip - 1), -500, 500))
try:
muw = (331e-4 / rho * (T / 300)**(-1.5)
* (exp_A2 / (1 + exp_neg5)
+ (3 / PI**2) * A_clip / (1 + exp_pos5)))
except Exception:
muw = 0
return r(muw)
def parse_array_string(array_string):
"""Convert string representation of array to numpy array.
Source: 260128_alldataplots.py
Parameters:
array_string (str): String like '[1.0, 2.0, 3.0]'
Returns:
np.ndarray: Numeric array
"""
import ast
array_list = ast.literal_eval(array_string)
return np.array(array_list, dtype=float)
# =============================================================================
# 4. Data loading
# =============================================================================
def download_dataset(file_id, output_dir='./starrydata_dataset', quiet=False):
"""Download and extract Starrydata dataset from Google Drive.
Source: 241216_starrydata_analysis_basic.py
Requires: pip install gdown
Parameters:
file_id (str): Google Drive file ID for the ZIP archive.
Find the latest ID from the Starrydata website or
use the known ID: '1py40fDLkTW2kcGx-ie7xHxG2Iqisfcuk'
output_dir (str): Directory to extract dataset into
quiet (bool): Suppress download progress output
Returns:
str: Path to the extracted dataset directory
Example:
>>> datapath = download_dataset('1py40fDLkTW2kcGx-ie7xHxG2Iqisfcuk')
>>> df_curves = load_curves(datapath)
>>> df_samples = load_samples(datapath)
"""
import gdown
import zipfile
import os
import tempfile
# Download ZIP from Google Drive
zip_path = os.path.join(tempfile.gettempdir(), 'starrydata_dataset.zip')
url = f'https://drive.google.com/uc?id={file_id}'
print(f'Downloading from Google Drive (file_id={file_id})...')
gdown.download(url, zip_path, quiet=quiet)
# Extract
os.makedirs(output_dir, exist_ok=True)
print(f'Extracting to {output_dir}...')
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(output_dir)
# Show contents and timestamp
files = os.listdir(output_dir)
print(f'Extracted files: {files}')
snapshot_path = os.path.join(output_dir, 'db_snapshot.txt')
if os.path.exists(snapshot_path):
with open(snapshot_path, 'r') as f:
print(f'Dataset timestamp: {f.read().strip()}')
# Clean up ZIP
os.remove(zip_path)
return output_dir
def load_curves(datapath):
"""Load Starrydata curves CSV file.
Supports both naming conventions:
- starrydata_curves.csv (2025+ format)
- all_curves.csv (2024 format)
Parameters:
datapath (str): Path to dataset directory (with trailing slash)
Returns:
pd.DataFrame: Curves dataframe
"""
import os
for filename in ['starrydata_curves.csv', 'all_curves.csv']:
filepath = os.path.join(datapath, filename)
if os.path.exists(filepath):
print(f'Loading curves from {filepath}')
return pd.read_csv(filepath)
raise FileNotFoundError(f'No curves CSV found in {datapath}')
def load_samples(datapath):
"""Load Starrydata samples CSV file and convert compositions.
Supports both naming conventions:
- starrydata_samples.csv (2025+ format)
- all_samples.csv (2024 format)
Parameters:
datapath (str): Path to dataset directory (with trailing slash)
Returns:
pd.DataFrame: Samples dataframe with element columns (H to Fm)
"""
import os
import tqdm
for filename in ['starrydata_samples.csv', 'all_samples.csv']:
filepath = os.path.join(datapath, filename)
if os.path.exists(filepath):
print(f'Loading samples from {filepath}')
df_samples = pd.read_csv(filepath, engine='c')
break
else:
raise FileNotFoundError(f'No samples CSV found in {datapath}')
# Convert compositions to element dictionaries
d_comp = {}
for i in tqdm.tqdm(df_samples.index, desc='Parsing compositions'):
str_comp = df_samples.at[i, 'composition']
try:
if '_' in str(str_comp):
str_comp = str_comp[:str_comp.index('_')]
d_comp_i = comp2dict(str_comp)
d_comp[i] = d_comp_i
df_samples.at[i, 'd_comp'] = d_comp_i
except Exception:
pass
# Merge element columns
df_comp = pd.DataFrame(d_comp).T
df_samples = pd.merge(df_samples, df_comp, left_index=True, right_index=True, how='left')
# Calculate sum_elements for validation
index_H = df_samples.columns.get_loc('H')
df_samples['sum_elements'] = df_samples.iloc[:, index_H:index_H + 100].sum(axis=1)
return df_samples
# =============================================================================
# 5. Interpolation
# =============================================================================
def spline_interpolate_curves(df_curves_t, x_btm=100, x_top=1000, dx=100):
"""Perform cubic spline interpolation on temperature-dependent curves.
Source: 251112_starrydata_exotic.py / 250603_TEfamilies.py (latest)
Parameters:
df_curves_t (pd.DataFrame): Curves filtered for prop_x='Temperature'
x_btm (int): Minimum temperature for interpolation [K]
x_top (int): Maximum temperature for interpolation [K]
dx (int): Temperature step [K]
Returns:
pd.DataFrame: df_curves_t with added columns y_{T}K for each temperature
"""
from scipy.interpolate import interp1d
import tqdm
a_xint = np.arange(x_btm, x_top + dx, dx)
for i in tqdm.tqdm(df_curves_t.index, desc='Spline interpolation'):
try:
a_x = np.array(eval(df_curves_t.at[i, 'x']))
a_y = np.array(eval(df_curves_t.at[i, 'y']))
x_min, x_max = min(a_x), max(a_x)
# Remove duplicate x values (average y for duplicates)
unique_x = np.unique(a_x)
unique_y = []
for uv in unique_x:
mean_y = np.mean(a_y[a_x == uv])
unique_y.append(mean_y)
if len(unique_x) < 4:
continue
spline = interp1d(unique_x, unique_y, kind='cubic')
for x in a_xint:
if x_min <= x <= x_max:
df_curves_t.at[i, f'y_{x}K'] = np.format_float_scientific(
spline(x), precision=5)
except Exception:
pass
return df_curves_t
# =============================================================================
# 6. Derived properties calculation
# =============================================================================
def calculate_derived_properties(df_int_T, T):
"""Calculate derived thermoelectric properties at a given temperature.
Computes: log10(sigma), lattice thermal conductivity, Z, weighted mobility,
and fills in missing sigma/rho from each other.
Source: 251112_starrydata_exotic.py (latest)
Parameters:
df_int_T (pd.DataFrame): Interpolated data at temperature T
T (float): Temperature [K]
Returns:
pd.DataFrame: Updated dataframe with derived property columns
"""
import tqdm
for i in tqdm.tqdm(df_int_T.index, desc=f'Calculating properties at {T}K'):
S = df_int_T.at[i, 'Seebeck coefficient']
rho = df_int_T.at[i, 'Electrical resistivity']
sigma = df_int_T.at[i, 'Electrical conductivity']
kappa = df_int_T.at[i, 'Thermal conductivity']
ZT = df_int_T.at[i, 'ZT']
# sigma <-> rho conversion
if rho > 0:
sigma = 1 / rho
df_int_T.at[i, 'Electrical conductivity'] = sigma
df_int_T.at[i, 'log10(Electrical conductivity)'] = np.log10(sigma)
elif sigma > 0:
rho = 1 / sigma
df_int_T.at[i, 'Electrical resistivity'] = rho
df_int_T.at[i, 'log10(Electrical conductivity)'] = np.log10(sigma)
# Lattice thermal conductivity
if kappa > 0 and sigma > 0:
kappaL = kappa - LORENZ * sigma * T
df_int_T.at[i, 'Lattice thermal conductivity'] = kappaL
# Z from ZT
if ZT > 0:
df_int_T.at[i, 'Z'] = ZT / T
# Weighted mobility
if (not math.isnan(S)) and rho > 0:
muw = weighted_mobility(S, rho, T)
df_int_T.at[i, 'Weighted mobility'] = muw
return df_int_T
# =============================================================================
# 7. Material family classification
# =============================================================================
# Default classification rules. Copy and modify before calling
# classify_material_families() to customise the classification.
#
# Rule types:
# 'general' – element-sum threshold (applied first, can be overwritten)
# elements: list of element symbols
# threshold: minimum sum to trigger classification
#
# 'specific' – stoichiometric ratio check (overwrites general)
# groups: list of element-group lists (ordered left→right in periodic table)
# stoichiometry: tuple of expected atom counts matching each group
# label: (optional) mf_if label if different from dict key
# extra_total: (optional) extra elements included in the total-sum check
# sum_base: (optional) total threshold = sum_base - cr (default 1.0)
#
# For 'specific' rules the function checks, for each group i > 0:
# |g[0]/g[i] - s[0]/s[i]| < cr * s[0]/s[i]
# and that the total sum of all groups (+ extra_total) > sum_base - cr.
DEFAULT_FAMILY_RULES = {
# --- General classifications (applied first, overwritten by specific) ---
'Oxide': {
'type': 'general',
'elements': ['O'],
'threshold': 0.2,
},
'Silicide': {
'type': 'general',
'elements': ['Si', 'Ge'],
'threshold': 0.2,
},
'Sulfide-Selenide': {
'type': 'general',
'elements': ['S', 'Se'],
'threshold': 0.2,
},
'Telluride': {
'type': 'general',
'elements': ['Te'],
'threshold': 0.2,
},
'Antimonide': {
'type': 'general',
'elements': ['Sb'],
'threshold': 0.2,
},
# --- Specific classifications (overwrite general) ---
'PbTe': {
'type': 'specific',
'groups': [
['Ca', 'Sr', 'Ba', 'Ge', 'Sn', 'Pb'], # IV-B / II-A site
['S', 'Se', 'Te'], # VI-A site
],
'stoichiometry': (1, 1),
},
'Bi2Te3': {
'type': 'specific',
'groups': [
['As', 'Sb', 'Bi'], # V-A site
['S', 'Se', 'Te'], # VI-A site
],
'stoichiometry': (2, 3),
},
'Mg2Si': {
'type': 'specific',
'groups': [
['Mg', 'Al'], # II-A / III-A site
['Si', 'Ge', 'Sn'], # IV-A site
],
'stoichiometry': (2, 1),
},
'Cu2Se': {
'type': 'specific',
'groups': [
['Cu', 'Ag'], # I-B site
['S', 'Se', 'Te'], # VI-A site
],
'stoichiometry': (2, 1),
},
'Skutterudite': {
'type': 'specific',
'groups': [
['Mn', 'Re', 'Fe', 'Co', 'Ni',
'Ru', 'Rh', 'Pd', 'Os', 'Ir', 'Pt'], # TM site
['P', 'As', 'Sb', 'Bi'], # Pnictogen site
],
'stoichiometry': (1, 3),
'extra_total': [
'Y', 'La', 'Ce', 'Pr', 'Nd', 'Sm', 'Eu', 'Gd',
'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu',
],
},
'Half-Heusler': {
'type': 'specific',
'label': 'Heusler',
'groups': [
['Ti', 'Zr', 'Hf', 'V', 'Nb', 'Ta'], # IV-B / V-B site
['Fe', 'Co', 'Ni', 'Ru', 'Rh', 'Pd', 'Os', 'Ir', 'Pt'], # VIII-B site
['Sn', 'P', 'As', 'Sb', 'Bi', 'Te'], # main-group site
],
'stoichiometry': (1, 1, 1),
},
'Full-Heusler': {
'type': 'specific',
'label': 'Heusler',
'groups': [
['Ti', 'Zr', 'Hf', 'V', 'Nb', 'Ta'], # IV-B / V-B site
['Mn', 'Fe', 'Co', 'Ni', 'Ru', 'Rh', 'Pd', 'Os', 'Ir', 'Pt'], # VIII-B site
['Al', 'Ga', 'In', 'Ge', 'Sn', 'Sb'], # III-A / IV-A site
],
'stoichiometry': (1, 2, 1),
},
'Clathrate': {
'type': 'specific',
'groups': [
['Na', 'K', 'Rb', 'Cs', 'Ca', 'Sr', 'Ba'], # guest site
['Al', 'Ga', 'In', 'Si', 'Ge', 'Sn'], # framework site
],
'stoichiometry': (8, 46),
},
'Perovskite': {
'type': 'specific',
'groups': [
['Ti', 'Zr', 'Hf', 'V', 'Nb', 'Ta', 'Cr', 'Mo', 'W',
'Mn', 'Re', 'Fe', 'Ru', 'Os', 'Co', 'Rh', 'Ir',
'Ni', 'Pd', 'Pt'], # B site
['O'], # anion site
],
'stoichiometry': (1, 3),
'sum_base': 0.8,
},
}
def classify_material_families(df_samples, cr=0.2, d=0.0001,
family_rules=None):
"""Heuristic material family classification based on composition.
Assigns 'mf_if' column using rules from ``family_rules`` dictionary.
General rules are applied first; specific rules overwrite them.
Source: 250603_TEfamilies.py (latest), refactored to dictionary-driven.
Parameters:
df_samples (pd.DataFrame): Samples with 'd_comp' column
cr (float): Composition tolerance range
d (float): Small offset to avoid zero-division
family_rules (dict or None): Classification rules. If None, uses
DEFAULT_FAMILY_RULES. See the module-level dictionary for
the expected format.
Returns:
pd.DataFrame: Updated with 'mf_if' column
"""
import tqdm
if family_rules is None:
family_rules = DEFAULT_FAMILY_RULES
# Separate general and specific rules (preserve dict order)
general_rules = {k: v for k, v in family_rules.items()
if v.get('type') == 'general'}
specific_rules = {k: v for k, v in family_rules.items()
if v.get('type') != 'general'}
df_samples['mf_if'] = ''
for i in tqdm.tqdm(df_samples.index,
desc='Classifying material families'):
dc = df_samples.at[i, 'd_comp']
if not isinstance(dc, dict):
continue
# --- General classifications ---
for name, rule in general_rules.items():
try:
el_sum = sum(dc.get(el, 0) for el in rule['elements']) + d
if el_sum > rule.get('threshold', 0.2):
df_samples.at[i, 'mf_if'] = name
except Exception:
pass
# --- Specific classifications (overwrite general) ---
for name, rule in specific_rules.items():
label = rule.get('label', name)
groups = rule['groups']
stoich = rule['stoichiometry']
sum_base = rule.get('sum_base', 1.0)
try:
# Compute group sums
g = [sum(dc.get(el, 0) for el in grp) + d
for grp in groups]
# Check stoichiometric ratios: g[0]/g[i] ≈ s[0]/s[i]
all_match = True
for j in range(1, len(groups)):
target = stoich[0] / stoich[j]
tol = cr * target
if np.abs(g[0] / g[j] - target) >= tol:
all_match = False
break
if not all_match:
continue
# Total-sum check
total = sum(g)
if 'extra_total' in rule:
total += (sum(dc.get(el, 0)
for el in rule['extra_total']) + d)
if total > sum_base - cr:
df_samples.at[i, 'mf_if'] = label
except Exception:
pass
return df_samples
# =============================================================================
# 8. Sample selection
# =============================================================================
def selectsamples(df_s, parent, threshold=0.1):
"""Filter samples by composition distance to a parent compound.
Source: 200818_Jonkerplot.py / 210212_ijp_ztcalc.py
Parameters:
df_s (pd.DataFrame): Sample dataframe (must have composition column
or 'parent' column)
parent (str): Parent compound formula (e.g. 'PbTe')
threshold (float): Maximum L2 distance in composition space
Returns:
pd.DataFrame: Filtered samples
"""
if 'parent' in df_s.columns:
# Simple parent-label based selection
df_ss = df_s[df_s['parent'] == parent]
else:
# Distance-based selection using composition vectors
vec_parent = comp2vec(parent)
nsamples = len(df_s)
a_dist = np.empty(nsamples)
for idx, (i, row) in enumerate(df_s.iterrows()):
try:
vec_sample = comp2vec(row['composition'])
a_dist[idx] = np.linalg.norm(vec_sample - vec_parent)
except Exception:
a_dist[idx] = 999
df_ss = df_s[a_dist < threshold]
print(f'{len(df_ss)} samples found for {parent}.')
return df_ss
# =============================================================================
# 9. PCA & Clustering
# =============================================================================
def generate_rainbow_colors(num_colors):
"""Generate a list of rainbow colors in HTML hex format.
Source: 251114_TEfamilyplot4.py
Parameters:
num_colors (int): Number of colors to generate
Returns:
list[str]: Color codes like '#ff0000'
"""
colors = []
increment = 360 / num_colors
for i in range(num_colors):
hue = int(i * increment)
rgb = _hsl_to_rgb(hue, 100, 50)
colors.append("#{:02x}{:02x}{:02x}".format(*rgb))
return colors
def _hsl_to_rgb(h, s, l):
"""Convert HSL to RGB tuple."""
h /= 360
s /= 100
l /= 100
if s == 0:
r = g = b = l
else:
def hue_to_rgb(p, q, t):
if t < 0: t += 1
if t > 1: t -= 1
if t < 1/6: return p + (q - p) * 6 * t
if t < 1/2: return q
if t < 2/3: return p + (q - p) * (2/3 - t) * 6
return p
q = l * (1 + s) if l < 0.5 else l + s - l * s
p = 2 * l - q
r = hue_to_rgb(p, q, h + 1/3)
g = hue_to_rgb(p, q, h)
b = hue_to_rgb(p, q, h - 1/3)
return int(r * 255), int(g * 255), int(b * 255)
def pca2(df_sample, n_clusters):
"""PCA analysis + K-means clustering on elemental composition data.
Source: 251114_TEfamilyplot4.py (latest, documented in CLAUDE.md)
Parameters:
df_sample (pd.DataFrame): Samples with element columns ('H' to 'Fm')
n_clusters (int): Number of K-means clusters
Returns:
pd.DataFrame: With PCA1, PCA2, cluster, color, n_elements, len_composition
"""
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
pca_features = df_sample.loc[:, 'H':'Fm']
n_elements = (pca_features != 0).sum(axis=1)
pca = PCA(n_components=2)
pca_result = pca.fit_transform(pca_features)
kmeans = KMeans(n_clusters=n_clusters, n_init=10, random_state=0)
clusters = kmeans.fit_predict(pca_result)
l_color = generate_rainbow_colors(n_clusters)
d_color = {i: l_color[i] for i in range(n_clusters)}
df_sample = df_sample.copy()
df_sample['PCA1'] = pca_result[:, 0]
df_sample['PCA2'] = pca_result[:, 1]
df_sample['cluster'] = clusters
df_sample['color'] = df_sample['cluster'].map(d_color)
df_sample['n_elements'] = n_elements
df_sample['len_composition'] = df_sample['composition'].apply(lambda x: len(str(x)))
# Print candidate parent compounds (no decimal points in formula)
df_parent = (
df_sample[~df_sample['composition'].str.contains(r'\.', regex=True, na=True)]
.sort_values('len_composition')
.drop_duplicates(subset=['composition'])
)
print("Candidate parent compounds:")
print(list(df_parent['composition']))
return df_sample[['sample_id', 'composition', 'PCA1', 'PCA2',
'cluster', 'color', 'n_elements', 'len_composition']]
# =============================================================================
# 10. Plotting - matplotlib (multi-panel TE plots)
# =============================================================================
# ---------------------------------------------------------------------------
# Property registry
# ---------------------------------------------------------------------------
# Each entry maps a short key to:
# column : column name in df_int
# si_range : default plot range in SI units [min, max]
# units : dict of {unit_label: (factor, offset)}
# converted_value = original_SI_value * factor + offset
# default_unit : which unit label to use when none is specified
# symbol : LaTeX symbol for axis labels
#
# Source: 01_Sample_Explorer.py (d_plotrange, d_unit_options)
PROPERTY_REGISTRY = {
'S': {
'column': 'Seebeck coefficient',
'si_range': [-1e-3, 1e-3],
'units': {
'V/K': (1.0, 0),
'uV/K': (1e6, 0),
'mV/K': (1e3, 0),
},
'default_unit': 'uV/K',
'symbol': r'Seebeck coefficient, $S$',
},
'sigma': {
'column': 'Electrical conductivity',
'si_range': [0, 1e6],
'units': {
'S/m': (1.0, 0),
'S/cm': (1e-2, 0),
'10^5 S/m': (1e-5, 0),
},
'default_unit': 'S/m',
'symbol': r'Electrical conductivity, $\sigma$',
},
'log_sigma': {
'column': 'log10(Electrical conductivity)',
'si_range': [-2, 8],
'units': {
'log10(S/m)': (1.0, 0),
'log10(S/cm)': (1.0, -2),
},
'default_unit': 'log10(S/m)',
'symbol': r'log(Electrical conductivity, $\sigma$)',
},
'rho': {
'column': 'Electrical resistivity',
'si_range': [0, 1e-3],
'units': {
'Ohm m': (1.0, 0),
'mOhm cm': (1e5, 0),
'uOhm cm': (1e8, 0),
'Ohm cm': (1e2, 0),
},
'default_unit': 'Ohm m',
'symbol': r'Electrical resistivity, $\rho$',
},
'kappa': {
'column': 'Thermal conductivity',
'si_range': [0, 30],
'units': {
'W/(m K)': (1.0, 0),
'W/(cm K)': (1e-2, 0),
},
'default_unit': 'W/(m K)',
'symbol': r'Thermal conductivity, $\kappa$',
},
'kappaL': {
'column': 'Lattice thermal conductivity',
'si_range': [0, 30],
'units': {
'W/(m K)': (1.0, 0),
'W/(cm K)': (1e-2, 0),
},
'default_unit': 'W/(m K)',
'symbol': r'Lattice thermal conductivity, $\kappa_L$',
},
'ZT': {
'column': 'ZT',
'si_range': [0, 1.5],
'units': {'': (1.0, 0)},
'default_unit': '',
'symbol': r'$ZT$',
},
'Z': {
'column': 'Z',
'si_range': [0, 0.01],
'units': {
'1/K': (1.0, 0),
'10^-3 /K': (1e3, 0),
},
'default_unit': '1/K',
'symbol': r'$Z$',
},
'PF': {
'column': 'Power factor',
'si_range': [0, 1e-2],
'units': {
'W/(m K^2)': (1.0, 0),
'uW/(cm K^2)': (1e4, 0),
'mW/(m K^2)': (1e3, 0),
},
'default_unit': 'W/(m K^2)',
'symbol': r'Power factor, $S^2 \sigma$',
},
'muw': {
'column': 'Weighted mobility',
'si_range': [0, 0.1],
'units': {
'm^2/(V s)': (1.0, 0),
'cm^2/(V s)': (1e4, 0),
},
'default_unit': 'cm^2/(V s)',
'symbol': r'Weighted mobility, $\mu_w$',
},
'mu': {
'column': 'Carrier mobility',
'si_range': [0, 0.1],
'units': {
'm^2/(V s)': (1.0, 0),
'cm^2/(V s)': (1e4, 0),
},
'default_unit': 'cm^2/(V s)',
'symbol': r'Carrier mobility, $\mu$',
},
'RH': {
'column': 'Hall coefficient',
'si_range': [-1e-6, 1e-6],
'units': {
'm^3/C': (1.0, 0),
'cm^3/C': (1e6, 0),
},
'default_unit': 'm^3/C',
'symbol': r'Hall coefficient, $R_H$',