-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhelpers.py
More file actions
1727 lines (1535 loc) · 58.4 KB
/
helpers.py
File metadata and controls
1727 lines (1535 loc) · 58.4 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
#import pkg_resources
#import streamlit as st
#installed_packages = sorted([(d.project_name, d.version) for d in pkg_resources.working_set])
#st.subheader("Installed Python Modules")
#for package, version in installed_packages:
# st.write(f"{package}=={version}")
import numpy as np
import matplotlib.pyplot as plt
from ase.io import read, write
from matminer.featurizers.structure import PartialRadialDistributionFunction
from pymatgen.io.ase import AseAtomsAdaptor
from pymatgen.analysis.diffraction.xrd import XRDCalculator
from pymatgen.analysis.diffraction.neutron import NDCalculator
from collections import defaultdict
from itertools import combinations
import streamlit.components.v1 as components
import py3Dmol
from io import StringIO
import pandas as pd
import plotly.graph_objs as go
from streamlit_plotly_events import plotly_events
from pymatgen.core import Structure as PmgStructure
import matplotlib.colors as mcolors
import streamlit as st
from mp_api.client import MPRester
from pymatgen.io.cif import CifWriter
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
from math import cos, radians, sqrt
import io
import re
import spglib
from pymatgen.core import Structure
from aflow import search, K
from aflow import search # ensure your file is not named aflow.py!
import aflow.keywords as AFLOW_K
import requests
from PIL import Image
# import aflow.keywords as K
from pymatgen.io.cif import CifWriter
from pymatgen.ext.optimade import OptimadeRester
def search_mc3d_optimade(query_params, limit=300):
import requests
from pymatgen.core import Structure, Lattice, Composition
import streamlit as st
# st.write("=" * 50)
# st.write("🔍 **MC3D SEARCH DEBUG INFO**")
# st.write(f"📝 Query parameters: {query_params}")
# st.write(f"🔢 Limit: {limit}")
endpoints = [
"https://optimade.materialscloud.org/main/mc3d-pbesol-v2/v1/structures",
"https://optimade.materialscloud.org/main/mc3d-pbe-v1/v1/structures",
]
filter_parts = []
strict_elements = None
target_composition = None
check_composition = False
if 'elements' in query_params:
elements = query_params['elements']
strict_elements = set(elements)
# st.write(f"🧪 Searching for elements: {elements} (STRICT - only these elements)")
for el in elements:
filter_parts.append(f'elements HAS "{el}"')
if 'formula' in query_params:
formula_input = query_params['formula'].replace(' ', '')
# st.write(f"⚗️ Formula input from user: {formula_input}")
try:
target_composition = Composition(formula_input)
check_composition = True
elements_from_formula = sorted([str(el) for el in target_composition.elements])
# st.write(f"✨ User's formula: {formula_input}")
# st.write(f"✨ Pymatgen reduced formula: {target_composition.reduced_formula}")
# st.write(f"✨ MC3D likely stores as: {''.join([el + str(int(target_composition[el])) if target_composition[el] != 1 else el for el in elements_from_formula])}")
# st.write(f"🧪 Searching by elements: {elements_from_formula} (order-independent)")
for el in elements_from_formula:
filter_parts.append(f'elements HAS "{el}"')
strict_elements = set(elements_from_formula)
except Exception as e:
st.warning(f"⚠️ Could not parse formula: {e}")
filter_str = " AND ".join(filter_parts) if filter_parts else None
params = {
'page_limit': min(limit, 100)
}
if filter_str:
params['filter'] = filter_str
# st.write(f"🔍 **OPTIMADE Filter**: `{filter_str}`")
# else:
# st.write("⚠️ No filter applied - fetching first results")
for idx, endpoint in enumerate(endpoints):
# st.write("-" * 50)
# st.write(f"🌐 **Endpoint {idx + 1}/{len(endpoints)}**: {endpoint}")
try:
# st.write(f"📤 Sending request with params: {params}")
response = requests.get(endpoint, params=params, timeout=30)
# st.write(f"📡 **Response Status Code**: {response.status_code}")
if response.status_code == 200:
data = response.json()
# st.write(f"📦 Response keys: {list(data.keys())}")
entries = data.get('data', [])
# st.write(f"📊 **Number of entries in response**: {len(entries)}")
if not entries:
# st.warning(f"⚠️ No entries returned from this endpoint")
# if 'meta' in data:
# st.write(f"ℹ️ Meta info: {data['meta']}")
continue
# if entries:
# st.write(f"🔬 First entry ID: {entries[0].get('id', 'N/A')}")
# st.write(f"🔬 First entry attributes keys: {list(entries[0].get('attributes', {}).keys())}")
structures = []
parse_errors = 0
filtered_out = 0
for entry_idx, entry in enumerate(entries[:limit]):
try:
attrs = entry['attributes']
entry_id = attrs.get('_mcloud_mc3d_id', entry['id'])
lattice_vectors = attrs.get('lattice_vectors')
if not lattice_vectors:
parse_errors += 1
continue
lattice = Lattice(lattice_vectors)
species = attrs.get('species_at_sites', [])
if not species:
parse_errors += 1
continue
if 'cartesian_site_positions' in attrs:
coords = attrs['cartesian_site_positions']
coords_are_cartesian = True
elif 'fractional_site_positions' in attrs:
coords = attrs['fractional_site_positions']
coords_are_cartesian = False
else:
parse_errors += 1
continue
structure = Structure(
lattice,
species,
coords,
coords_are_cartesian=coords_are_cartesian
)
if strict_elements:
structure_elements = set([str(el) for el in structure.composition.elements])
if structure_elements != strict_elements:
filtered_out += 1
continue
if check_composition and target_composition:
structure_comp = structure.composition.reduced_composition
target_comp = target_composition.reduced_composition
# if entry_idx < 3:
# st.write(f"🔬 Entry #{entry_idx + 1} - {entry_id}:")
# st.write(f" - Target composition: {target_comp}")
# st.write(f" - Structure composition: {structure_comp}")
# st.write(f" - Match: {structure_comp == target_comp}")
if structure_comp != target_comp:
filtered_out += 1
continue
formula = attrs.get('chemical_formula_reduced', structure.composition.reduced_formula)
structures.append({
'id': entry_id,
'structure': structure,
'formula': formula
})
# if (entry_idx + 1) % 10 == 0:
# st.write(f"✅ Parsed {entry_idx + 1}/{len(entries[:limit])} entries...")
except Exception as e:
parse_errors += 1
continue
# st.write(f"📈 **Parsing Summary**:")
# st.write(f" - Successfully parsed: {len(structures)}")
# st.write(f" - Failed to parse: {parse_errors}")
# if strict_elements:
# st.write(f" - Filtered out (wrong elements): {filtered_out}")
if structures:
#st.success(f"✅ Found {len(structures)} structures in MC3D via OPTIMADE.")
# st.write("=" * 50)
return structures
# else:
# st.error("❌ No structures could be parsed from this endpoint")
# elif response.status_code == 404:
# st.warning(f"⚠️ Endpoint not found (404)")
# elif response.status_code == 500:
# st.error(f"❌ Server error (500)")
# try:
# error_data = response.json()
# st.write(f"Error details: {error_data}")
# except:
# st.write(f"Raw response: {response.text[:500]}")
# else:
# st.warning(f"⚠️ Unexpected status code: {response.status_code}")
# st.write(f"Response text: {response.text[:500]}")
except requests.exceptions.Timeout:
st.error(f"⏱️ Request timed out for {endpoint}")
except requests.exceptions.ConnectionError:
st.error(f"🔌 Connection error for {endpoint}")
except Exception as e:
st.error(f"❌ Unexpected error with endpoint {endpoint}: {str(e)}")
import traceback
st.write(f"Traceback: {traceback.format_exc()}")
continue
st.error("❌ Could not retrieve structures from any MC3D endpoint")
return []
def get_mc3d_structure_by_id(mc3d_id):
import requests
from pymatgen.core import Structure, Lattice
import streamlit as st
endpoints = [
"https://optimade.materialscloud.org/main/mc3d-pbesol-v2/v1/structures",
"https://optimade.materialscloud.org/main/mc3d-pbe-v1/v1/structures",
]
params = {
'filter': f'_mcloud_mc3d_id="{mc3d_id}"'
}
for endpoint in endpoints:
try:
response = requests.get(endpoint, params=params, timeout=30)
if response.status_code == 200:
data = response.json()
entries = data.get('data', [])
if not entries:
continue
entry = entries[0]
attrs = entry['attributes']
lattice_vectors = attrs.get('lattice_vectors')
if not lattice_vectors:
continue
lattice = Lattice(lattice_vectors)
species = attrs.get('species_at_sites', [])
if not species:
continue
if 'cartesian_site_positions' in attrs:
coords = attrs['cartesian_site_positions']
coords_are_cartesian = True
elif 'fractional_site_positions' in attrs:
coords = attrs['fractional_site_positions']
coords_are_cartesian = False
else:
continue
structure = Structure(
lattice,
species,
coords,
coords_are_cartesian=coords_are_cartesian
)
return structure
except Exception as e:
continue
st.warning(f"Could not fetch structure {mc3d_id} from MC3D")
return None
ELEMENTS = [
'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',
'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', 'Ds',
'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og'
]
def get_formula_type(formula):
elements = []
counts = []
import re
matches = re.findall(r'([A-Z][a-z]*)(\d*)', formula)
for element, count in matches:
elements.append(element)
counts.append(int(count) if count else 1)
if len(elements) == 1:
return "A"
elif len(elements) == 2:
# Binary compounds
if counts[0] == 1 and counts[1] == 1:
return "AB"
elif counts[0] == 1 and counts[1] == 2:
return "AB2"
elif counts[0] == 2 and counts[1] == 1:
return "A2B"
elif counts[0] == 1 and counts[1] == 3:
return "AB3"
elif counts[0] == 3 and counts[1] == 1:
return "A3B"
elif counts[0] == 1 and counts[1] == 4:
return "AB4"
elif counts[0] == 4 and counts[1] == 1:
return "A4B"
elif counts[0] == 1 and counts[1] == 5:
return "AB5"
elif counts[0] == 5 and counts[1] == 1:
return "A5B"
elif counts[0] == 1 and counts[1] == 6:
return "AB6"
elif counts[0] == 6 and counts[1] == 1:
return "A6B"
elif counts[0] == 2 and counts[1] == 3:
return "A2B3"
elif counts[0] == 3 and counts[1] == 2:
return "A3B2"
elif counts[0] == 2 and counts[1] == 5:
return "A2B5"
elif counts[0] == 5 and counts[1] == 2:
return "A5B2"
elif counts[0] == 1 and counts[1] == 12:
return "AB12"
elif counts[0] == 12 and counts[1] == 1:
return "A12B"
elif counts[0] == 2 and counts[1] == 17:
return "A2B17"
elif counts[0] == 17 and counts[1] == 2:
return "A17B2"
elif counts[0] == 3 and counts[1] == 4:
return "A3B4"
else:
return f"A{counts[0]}B{counts[1]}"
elif len(elements) == 3:
# Ternary compounds
if counts[0] == 1 and counts[1] == 1 and counts[2] == 1:
return "ABC"
elif counts[0] == 1 and counts[1] == 1 and counts[2] == 3:
return "ABC3"
elif counts[0] == 1 and counts[1] == 3 and counts[2] == 1:
return "AB3C"
elif counts[0] == 3 and counts[1] == 1 and counts[2] == 1:
return "A3BC"
elif counts[0] == 1 and counts[1] == 2 and counts[2] == 4:
return "AB2C4"
elif counts[0] == 2 and counts[1] == 1 and counts[2] == 4:
return "A2BC4"
elif counts[0] == 1 and counts[1] == 4 and counts[2] == 2:
return "AB4C2"
elif counts[0] == 2 and counts[1] == 4 and counts[2] == 1:
return "A2B4C"
elif counts[0] == 4 and counts[1] == 1 and counts[2] == 2:
return "A4BC2"
elif counts[0] == 4 and counts[1] == 2 and counts[2] == 1:
return "A4B2C"
elif counts[0] == 1 and counts[1] == 2 and counts[2] == 1:
return "AB2C"
elif counts[0] == 2 and counts[1] == 1 and counts[2] == 1:
return "A2BC"
elif counts[0] == 1 and counts[1] == 1 and counts[2] == 2:
return "ABC2"
elif counts[0] == 1 and counts[1] == 1 and counts[2] == 4:
return "ABC4"
elif counts[0] == 1 and counts[1] == 4 and counts[2] == 1:
return "AB4C"
elif counts[0] == 4 and counts[1] == 1 and counts[2] == 1:
return "A4BC"
elif counts[0] == 1 and counts[1] == 1 and counts[2] == 5:
return "ABC5"
elif counts[0] == 1 and counts[1] == 5 and counts[2] == 1:
return "AB5C"
elif counts[0] == 5 and counts[1] == 1 and counts[2] == 1:
return "A5BC"
elif counts[0] == 1 and counts[1] == 1 and counts[2] == 6:
return "ABC6"
elif counts[0] == 1 and counts[1] == 6 and counts[2] == 1:
return "AB6C"
elif counts[0] == 6 and counts[1] == 1 and counts[2] == 1:
return "A6BC"
elif counts[0] == 2 and counts[1] == 2 and counts[2] == 1:
return "A2B2C"
elif counts[0] == 2 and counts[1] == 1 and counts[2] == 2:
return "A2BC2"
elif counts[0] == 1 and counts[1] == 2 and counts[2] == 2:
return "AB2C2"
elif counts[0] == 3 and counts[1] == 2 and counts[2] == 1:
return "A3B2C"
elif counts[0] == 3 and counts[1] == 1 and counts[2] == 2:
return "A3BC2"
elif counts[0] == 1 and counts[1] == 3 and counts[2] == 2:
return "AB3C2"
elif counts[0] == 2 and counts[1] == 3 and counts[2] == 1:
return "A2B3C"
elif counts[0] == 2 and counts[1] == 1 and counts[2] == 3:
return "A2BC3"
elif counts[0] == 1 and counts[1] == 2 and counts[2] == 3:
return "AB2C3"
elif counts[0] == 3 and counts[1] == 3 and counts[2] == 1:
return "A3B3C"
elif counts[0] == 3 and counts[1] == 1 and counts[2] == 3:
return "A3BC3"
elif counts[0] == 1 and counts[1] == 3 and counts[2] == 3:
return "AB3C3"
elif counts[0] == 4 and counts[1] == 3 and counts[2] == 1:
return "A4B3C"
elif counts[0] == 4 and counts[1] == 1 and counts[2] == 3:
return "A4BC3"
elif counts[0] == 1 and counts[1] == 4 and counts[2] == 3:
return "AB4C3"
elif counts[0] == 3 and counts[1] == 4 and counts[2] == 1:
return "A3B4C"
elif counts[0] == 3 and counts[1] == 1 and counts[2] == 4:
return "A3BC4"
elif counts[0] == 1 and counts[1] == 3 and counts[2] == 4:
return "AB3C4"
elif counts[0] == 1 and counts[1] == 3 and counts[2] == 4:
return "ABC6"
elif counts[0] == 2 and counts[1] == 2 and counts[2] == 7:
return "A2B2C7"
else:
return f"A{counts[0]}B{counts[1]}C{counts[2]}"
elif len(elements) == 4:
# Quaternary compounds
if counts[0] == 1 and counts[1] == 1 and counts[2] == 1 and counts[3] == 1:
return "ABCD"
elif counts[0] == 1 and counts[1] == 1 and counts[2] == 1 and counts[3] == 3:
return "ABCD3"
elif counts[0] == 1 and counts[1] == 1 and counts[2] == 3 and counts[3] == 1:
return "ABC3D"
elif counts[0] == 1 and counts[1] == 3 and counts[2] == 1 and counts[3] == 1:
return "AB3CD"
elif counts[0] == 3 and counts[1] == 1 and counts[2] == 1 and counts[3] == 1:
return "A3BCD"
elif counts[0] == 1 and counts[1] == 1 and counts[2] == 1 and counts[3] == 4:
return "ABCD4"
elif counts[0] == 1 and counts[1] == 1 and counts[2] == 4 and counts[3] == 1:
return "ABC4D"
elif counts[0] == 1 and counts[1] == 4 and counts[2] == 1 and counts[3] == 1:
return "AB4CD"
elif counts[0] == 4 and counts[1] == 1 and counts[2] == 1 and counts[3] == 1:
return "A4BCD"
elif counts[0] == 1 and counts[1] == 2 and counts[2] == 1 and counts[3] == 4:
return "AB2CD4"
elif counts[0] == 2 and counts[1] == 1 and counts[2] == 1 and counts[3] == 4:
return "A2BCD4"
elif counts[0] == 1 and counts[1] == 1 and counts[2] == 2 and counts[3] == 4:
return "ABC2D4"
elif counts[0] == 1 and counts[1] == 2 and counts[2] == 4 and counts[3] == 1:
return "AB2C4D"
elif counts[0] == 2 and counts[1] == 1 and counts[2] == 4 and counts[3] == 1:
return "A2BC4D"
elif counts[0] == 2 and counts[1] == 4 and counts[2] == 1 and counts[3] == 1:
return "A2B4CD"
elif counts[0] == 2 and counts[1] == 1 and counts[2] == 1 and counts[3] == 1:
return "A2BCD"
elif counts[0] == 1 and counts[1] == 2 and counts[2] == 1 and counts[3] == 1:
return "AB2CD"
elif counts[0] == 1 and counts[1] == 1 and counts[2] == 2 and counts[3] == 1:
return "ABC2D"
elif counts[0] == 1 and counts[1] == 1 and counts[2] == 1 and counts[3] == 2:
return "ABCD2"
elif counts[0] == 3 and counts[1] == 2 and counts[2] == 1 and counts[3] == 1:
return "A3B2CD"
elif counts[0] == 3 and counts[1] == 1 and counts[2] == 2 and counts[3] == 1:
return "A3BC2D"
elif counts[0] == 3 and counts[1] == 1 and counts[2] == 1 and counts[3] == 2:
return "A3BCD2"
elif counts[0] == 1 and counts[1] == 3 and counts[2] == 2 and counts[3] == 1:
return "AB3C2D"
elif counts[0] == 1 and counts[1] == 3 and counts[2] == 1 and counts[3] == 2:
return "AB3CD2"
elif counts[0] == 1 and counts[1] == 1 and counts[2] == 3 and counts[3] == 2:
return "ABC3D2"
elif counts[0] == 2 and counts[1] == 3 and counts[2] == 1 and counts[3] == 1:
return "A2B3CD"
elif counts[0] == 2 and counts[1] == 1 and counts[2] == 3 and counts[3] == 1:
return "A2BC3D"
elif counts[0] == 2 and counts[1] == 1 and counts[2] == 1 and counts[3] == 3:
return "A2BCD3"
elif counts[0] == 1 and counts[1] == 2 and counts[2] == 3 and counts[3] == 1:
return "AB2C3D"
elif counts[0] == 1 and counts[1] == 2 and counts[2] == 1 and counts[3] == 3:
return "AB2CD3"
elif counts[0] == 1 and counts[1] == 1 and counts[2] == 2 and counts[3] == 3:
return "ABC2D3"
elif counts[0] == 1 and counts[1] == 4 and counts[2] == 1 and counts[3] == 6:
return "A1B4C1D6"
elif counts[0] == 5 and counts[1] == 3 and counts[2] == 1 and counts[3] == 13:
return "A5B3C1D13"
elif counts[0] == 2 and counts[1] == 2 and counts[2] == 4 and counts[3] == 9:
return "A2B2C4D9"
elif counts == [3, 2, 1, 4]: # Garnet-like: Ca3Al2Si3O12
return "A3B2C1D4"
else:
return f"A{counts[0]}B{counts[1]}C{counts[2]}D{counts[3]}"
elif len(elements) == 5:
# Five-element compounds (complex minerals like apatite)
if counts == [1, 1, 1, 1, 1]:
return "ABCDE"
elif counts == [10, 6, 2, 31, 1]: # Apatite-like: Ca10(PO4)6(OH)2
return "A10B6C2D31E"
elif counts == [5, 3, 13, 1, 1]: # Simplified apatite: Ca5(PO4)3OH
return "A5B3C13DE"
elif counts == [5, 3, 13, 1, 1]: # Simplified apatite: Ca5(PO4)3OH
return "A5B3C13"
elif counts == [3, 2, 3, 12, 1]: # Garnet-like: Ca3Al2Si3O12
return "A3B2C3D12E"
else:
return f"A{counts[0]}B{counts[1]}C{counts[2]}D{counts[3]}E{counts[4]}"
elif len(elements) == 6:
# Six-element compounds (very complex minerals)
if counts == [1, 1, 1, 1, 1, 1]:
return "ABCDEF"
elif counts == [1, 1, 2, 6, 1, 1]: # Complex silicate-like
return "ABC2D6EF"
else:
# For 6+ elements, use a more compact notation
element_count_pairs = []
for i, count in enumerate(counts):
element_letter = chr(65 + i) # A, B, C, D, E, F, ...
if count == 1:
element_count_pairs.append(element_letter)
else:
element_count_pairs.append(f"{element_letter}{count}")
return "".join(element_count_pairs)
else:
if len(elements) <= 10:
element_count_pairs = []
for i, count in enumerate(counts):
element_letter = chr(65 + i) # A, B, C, D, E, F, G, H, I, J
if count == 1:
element_count_pairs.append(element_letter)
else:
element_count_pairs.append(f"{element_letter}{count}")
return "".join(element_count_pairs)
else:
return "Complex"
import time
def check_structure_size_and_warn(structure, structure_name="structure"):
n_atoms = len(structure)
if n_atoms > 75:
st.info(f"ℹ️ **Structure Notice**: {structure_name} contains a large number of **{n_atoms} atoms**. "
f"Calculations may take longer depending on selected parameters. Please be careful to "
f"not consume much memory, we are hosted on a free server. 😊")
return "moderate"
else:
return "small"
SPACE_GROUP_SYMBOLS = {
1: "P1", 2: "P-1", 3: "P2", 4: "P21", 5: "C2", 6: "Pm", 7: "Pc", 8: "Cm", 9: "Cc", 10: "P2/m",
11: "P21/m", 12: "C2/m", 13: "P2/c", 14: "P21/c", 15: "C2/c", 16: "P222", 17: "P2221", 18: "P21212", 19: "P212121", 20: "C2221",
21: "C222", 22: "F222", 23: "I222", 24: "I212121", 25: "Pmm2", 26: "Pmc21", 27: "Pcc2", 28: "Pma2", 29: "Pca21", 30: "Pnc2",
31: "Pmn21", 32: "Pba2", 33: "Pna21", 34: "Pnn2", 35: "Cmm2", 36: "Cmc21", 37: "Ccc2", 38: "Amm2", 39: "Aem2", 40: "Ama2",
41: "Aea2", 42: "Fmm2", 43: "Fdd2", 44: "Imm2", 45: "Iba2", 46: "Ima2", 47: "Pmmm", 48: "Pnnn", 49: "Pccm", 50: "Pban",
51: "Pmma", 52: "Pnna", 53: "Pmna", 54: "Pcca", 55: "Pbam", 56: "Pccn", 57: "Pbcm", 58: "Pnnm", 59: "Pmmn", 60: "Pbcn",
61: "Pbca", 62: "Pnma", 63: "Cmcm", 64: "Cmca", 65: "Cmmm", 66: "Cccm", 67: "Cmma", 68: "Ccca", 69: "Fmmm", 70: "Fddd",
71: "Immm", 72: "Ibam", 73: "Ibca", 74: "Imma", 75: "P4", 76: "P41", 77: "P42", 78: "P43", 79: "I4", 80: "I41",
81: "P-4", 82: "I-4", 83: "P4/m", 84: "P42/m", 85: "P4/n", 86: "P42/n", 87: "I4/m", 88: "I41/a", 89: "P422", 90: "P4212",
91: "P4122", 92: "P41212", 93: "P4222", 94: "P42212", 95: "P4322", 96: "P43212", 97: "I422", 98: "I4122", 99: "P4mm", 100: "P4bm",
101: "P42cm", 102: "P42nm", 103: "P4cc", 104: "P4nc", 105: "P42mc", 106: "P42bc", 107: "P42mm", 108: "P42cm", 109: "I4mm", 110: "I4cm",
111: "I41md", 112: "I41cd", 113: "P-42m", 114: "P-42c", 115: "P-421m", 116: "P-421c", 117: "P-4m2", 118: "P-4c2", 119: "P-4b2", 120: "P-4n2",
121: "I-4m2", 122: "I-4c2", 123: "I-42m", 124: "I-42d", 125: "P4/mmm", 126: "P4/mcc", 127: "P4/nbm", 128: "P4/nnc", 129: "P4/mbm", 130: "P4/mnc",
131: "P4/nmm", 132: "P4/ncc", 133: "P42/mmc", 134: "P42/mcm", 135: "P42/nbc", 136: "P42/mnm", 137: "P42/mbc", 138: "P42/mnm", 139: "I4/mmm", 140: "I4/mcm",
141: "I41/amd", 142: "I41/acd", 143: "P3", 144: "P31", 145: "P32", 146: "R3", 147: "P-3", 148: "R-3", 149: "P312", 150: "P321",
151: "P3112", 152: "P3121", 153: "P3212", 154: "P3221", 155: "R32", 156: "P3m1", 157: "P31m", 158: "P3c1", 159: "P31c", 160: "R3m",
161: "R3c", 162: "P-31m", 163: "P-31c", 164: "P-3m1", 165: "P-3c1", 166: "R-3m", 167: "R-3c", 168: "P6", 169: "P61", 170: "P65",
171: "P62", 172: "P64", 173: "P63", 174: "P-6", 175: "P6/m", 176: "P63/m", 177: "P622", 178: "P6122", 179: "P6522", 180: "P6222",
181: "P6422", 182: "P6322", 183: "P6mm", 184: "P6cc", 185: "P63cm", 186: "P63mc", 187: "P-6m2", 188: "P-6c2", 189: "P-62m", 190: "P-62c",
191: "P6/mmm", 192: "P6/mcc", 193: "P63/mcm", 194: "P63/mmc", 195: "P23", 196: "F23", 197: "I23", 198: "P213", 199: "I213", 200: "Pm-3",
201: "Pn-3", 202: "Fm-3", 203: "Fd-3", 204: "Im-3", 205: "Pa-3", 206: "Ia-3", 207: "P432", 208: "P4232", 209: "F432", 210: "F4132",
211: "I432", 212: "P4332", 213: "P4132", 214: "I4132", 215: "P-43m", 216: "F-43m", 217: "I-43m", 218: "P-43n", 219: "F-43c", 220: "I-43d",
221: "Pm-3m", 222: "Pn-3n", 223: "Pm-3n", 224: "Pn-3m", 225: "Fm-3m", 226: "Fm-3c", 227: "Fd-3m", 228: "Fd-3c", 229: "Im-3m", 230: "Ia-3d"
}
def identify_structure_type(structure):
try:
analyzer = SpacegroupAnalyzer(structure)
spg_symbol = analyzer.get_space_group_symbol()
spg_number = analyzer.get_space_group_number()
crystal_system = analyzer.get_crystal_system()
formula = structure.composition.reduced_formula
formula_type = get_formula_type(formula)
# print("------")
print(formula)
# print(formula_type)
#print(spg_number)
if spg_number in STRUCTURE_TYPES and spg_number == 62 and formula_type in STRUCTURE_TYPES[spg_number] and formula == "CaCO3":
# print("YES")
# print(spg_number)
# print(formula_type)
#structure_type = STRUCTURE_TYPES[spg_number][formula_type]
return f"**Aragonite (CaCO3)**"
elif spg_number in STRUCTURE_TYPES and spg_number ==167 and formula_type in STRUCTURE_TYPES[spg_number] and formula == "CaCO3":
# print("YES")
# print(spg_number)
# print(formula_type)
#structure_type = STRUCTURE_TYPES[spg_number][formula_type]
return f"**Calcite (CaCO3)**"
elif spg_number in STRUCTURE_TYPES and spg_number ==227 and formula_type in STRUCTURE_TYPES[spg_number] and formula == "SiO2":
# print("YES")
# print(spg_number)
# print(formula_type)
#structure_type = STRUCTURE_TYPES[spg_number][formula_type]
return f"**β - Cristobalite (SiO2)**"
elif formula == "C" and spg_number in STRUCTURE_TYPES and spg_number ==194 :
print("YES")
print(spg_number)
print(formula_type)
#structure_type = STRUCTURE_TYPES[spg_number][formula_type]
return f"**Graphite**"
elif formula == "MoS2" and spg_number in STRUCTURE_TYPES and spg_number ==194 :
print("YES")
print(spg_number)
print(formula_type)
#structure_type = STRUCTURE_TYPES[spg_number][formula_type]
return f"**MoS2 Type**"
elif formula == "NiAs" and spg_number in STRUCTURE_TYPES and spg_number ==194 :
print("YES")
print(spg_number)
print(formula_type)
#structure_type = STRUCTURE_TYPES[spg_number][formula_type]
return f"**Nickeline (NiAs)**"
elif formula == "ReO3" and spg_number in STRUCTURE_TYPES and spg_number ==221 :
print("YES")
print(spg_number)
print(formula_type)
#structure_type = STRUCTURE_TYPES[spg_number][formula_type]
return f"**ReO3 type**"
elif formula == "TlI" and spg_number in STRUCTURE_TYPES and spg_number ==63 :
print("YES")
print(spg_number)
print(formula_type)
#structure_type = STRUCTURE_TYPES[spg_number][formula_type]
return f"**TlI structure**"
elif spg_number in STRUCTURE_TYPES and formula_type in STRUCTURE_TYPES[
spg_number]:
# print("YES")
structure_type = STRUCTURE_TYPES[spg_number][formula_type]
return f"**{structure_type}**"
pearson = f"{crystal_system[0]}{structure.num_sites}"
return f"**{crystal_system.capitalize()}** (Formula: {formula_type}, Pearson: {pearson})"
except Exception as e:
return f"Error identifying structure: {str(e)}"
STRUCTURE_TYPES = {
# Cubic Structures
225: { # Fm-3m
"A": "FCC (Face-centered cubic)",
"AB": "Rock Salt (NaCl)",
"AB2": "Fluorite (CaF2)",
"A2B": "Anti-Fluorite",
"AB3": "Cu3Au (L1₂)",
"A3B": "AuCu3 type",
"ABC": "Half-Heusler (C1b)",
"AB6": "K2PtCl6 (cubic antifluorite)",
},
92: {
"AB2": "α-Cristobalite (SiO2)"
},
229: { # Im-3m
"A": "BCC (Body-centered cubic)",
"AB12": "NaZn13 type",
"AB": "Tungsten carbide (WC)"
},
221: { # Pm-3m
"A": "Simple cubic (SC)",
"AB": "Cesium Chloride (CsCl)",
"ABC3": "Perovskite (Cubic, ABO3)",
"AB3": "Cu3Au type",
"A3B": "Cr3Si (A15)",
#"AB6": "ReO3 type"
},
227: { # Fd-3m
"A": "Diamond cubic",
"AB2": "Fluorite-like",
"AB2C4": "Normal spinel",
"A3B4": "Inverse spinel",
"AB2C4": "Spinel",
"A8B": "Gamma-brass",
"AB2": "β - Cristobalite (SiO2)",
"A2B2C7": "Pyrochlore"
},
55: { # Pbca
"AB2": "Brookite (TiO₂ polymorph)"
},
216: { # F-43m
"AB": "Zinc Blende (Sphalerite)",
"A2B": "Antifluorite"
},
215: { # P-43m
"ABC3": "Inverse-perovskite",
"AB4": "Half-anti-fluorite"
},
223: { # Pm-3n
"AB": "α-Mn structure",
"A3B": "Cr3Si-type"
},
230: { # Ia-3d
"A3B2C1D4": "Garnet structure ((Ca,Mg,Fe)3(Al,Fe)2(SiO4)3)",
"AB2": "Pyrochlore"
},
217: { # I-43m
"A12B": "α-Mn structure"
},
219: { # F-43c
"AB": "Sodium thallide"
},
205: { # Pa-3
"A2B": "Cuprite (Cu2O)",
"AB6": "ReO3 structure",
"AB2": "Pyrite (FeS2)",
},
156: {
"AB2": "CdI2 type",
},
# Hexagonal Structures
194: { # P6_3/mmc
"AB": "Wurtzite (high-T)",
"AB2": "AlB2 type (hexagonal)",
"A3B": "Ni3Sn type",
"A3B": "DO19 structure (Ni3Sn-type)",
"A": "Graphite (hexagonal)",
"A": "HCP (Hexagonal close-packed)",
#"AB2": "MoS2 type",
},
186: { # P6_3mc
"AB": "Wurtzite (ZnS)",
},
191: { # P6/mmm
"AB2": "AlB2 type",
"AB5": "CaCu5 type",
"A2B17": "Th2Ni17 type"
},
193: { # P6_3/mcm
"A3B": "Na3As structure",
"ABC": "ZrBeSi structure"
},
# 187: { # P-6m2
#
# },
164: { # P-3m1
"AB2": "CdI2 type",
"A": "Graphene layers"
},
166: { # R-3m
"A": "Rhombohedral",
"A2B3": "α-Al2O3 type",
"ABC2": "Delafossite (CuAlO2)"
},
160: { # R3m
"A2B3": "Binary tetradymite",
"AB2": "Delafossite"
},
# Tetragonal Structures
139: { # I4/mmm
"A": "Body-centered tetragonal",
"AB": "β-Tin",
"A2B": "MoSi2 type",
"A3B": "Ni3Ti structure"
},
136: { # P4_2/mnm
"AB2": "Rutile (TiO2)"
},
123: { # P4/mmm
"AB": "γ-CuTi",
"AB": "CuAu (L10)"
},
140: { # I4/mcm
"AB2": "Anatase (TiO2)",
"A": "β-W structure"
},
141: { # I41/amd
"AB2": "Anatase (TiO₂)",
"A": "α-Sn structure",
"ABC4": "Zircon (ZrSiO₄)"
},
122: { # P-4m2
"ABC2": "Chalcopyrite (CuFeS2)"
},
129: { # P4/nmm
"AB": "PbO structure"
},
# Orthorhombic Structures
62: { # Pnma
"ABC3": "Aragonite (CaCO₃)",
"AB2": "Cotunnite (PbCl2)",
"ABC3": "Perovskite (orthorhombic)",
"A2B": "Fe2P type",
"ABC3": "GdFeO3-type distorted perovskite",
"A2BC4": "Olivine ((Mg,Fe)2SiO4)",
"ABC4": "Barite (BaSO₄)"
},
63: { # Cmcm
"A": "α-U structure",
"AB": "CrB structure",
"AB2": "HgBr2 type"
},
74: { # Imma
"AB": "TlI structure",
},
64: { # Cmca
"A": "α-Ga structure"
},
65: { # Cmmm
"A2B": "η-Fe2C structure"
},
70: { # Fddd
"A": "Orthorhombic unit cell"
},
# Monoclinic Structures
14: { # P21/c
"AB": "Monoclinic structure",
"AB2": "Baddeleyite (ZrO2)",
"ABC4": "Monazite (CePO4)"
},
12: { # C2/m
"A2B2C7": "Thortveitite (Sc2Si2O7)"
},
15: { # C2/c
"A1B4C1D6": "Gypsum (CaH4O6S)",
"ABC6": "Gypsum (CaH4O6S)",
"ABC4": "Scheelite (CaWO₄)",
"ABC5": "Sphene (CaTiSiO₅)"
},
1: {
"A2B2C4D9": "Kaolinite"
},
# Triclinic Structures
2: { # P-1
"AB": "Triclinic structure",
"ABC3": "Wollastonite (CaSiO3)",
},
# Other important structures
99: { # P4mm
"ABCD3": "Tetragonal perovskite"
},
167: { # R-3c
"ABC3": "Calcite (CaCO3)",
"A2B3": "Corundum (Al2O3)"
},
176: { # P6_3/m
"A10B6C2D31E": "Apatite (Ca10(PO4)6(OH)2)",
"A5B3C1D13": "Apatite (Ca5(PO4)3OH",
"A5B3C13": "Apatite (Ca5(PO4)3OH"
},
58: { # Pnnm
"AB2": "Marcasite (FeS2)"
},
11: { # P21/m
"A2B": "ThSi2 type"
},
72: { # Ibam
"AB2": "MoSi2 type"
},
198: { # P213
"AB": "FeSi structure",
"A12": "β-Mn structure"
},
88: { # I41/a
"ABC4": "Scheelite (CaWO4)"
},
33: { # Pna21
"AB": "FeAs structure"
},
130: { # P4/ncc
"AB2": "Cristobalite (SiO2)"
},
152: { # P3121
"AB2": "Quartz (SiO2)"
},
200: { # Pm-3
"A3B3C": "Fe3W3C"
},
224: { # Pn-3m
"AB": "Pyrochlore-related",
"A2B": "Cuprite (Cu2O)"
},
127: { # P4/mbm
"AB": "σ-phase structure",
"AB5": "CaCu5 type"
},
148: { # R-3
"ABC3": "Calcite (CaCO₃)",
"ABC3": "Ilmenite (FeTiO₃)",
"ABCD3": "Dolomite",
},
69: { # Fmmm
"A": "β-W structure"
},
128: { # P4/mnc
"A3B": "Cr3Si (A15)"
},
206: { # Ia-3
"AB2": "Pyrite derivative",
"AB2": "Pyrochlore (defective)",
"A2B3": "Bixbyite"
},
212: { # P4_3 32
"A4B3": "Mn4Si3 type"
},
180: {
"AB2": "β-quartz (SiO2)",
},
226: { # Fm-3c
"AB2": "BiF3 type"
},
196: { # F23
"AB2": "FeS2 type"
},
96: {
"AB2": "α-Cristobalite (SiO2)"
}
}
def get_full_conventional_structure_diffra(structure, symprec=1e-3):
lattice = structure.lattice.matrix
positions = structure.frac_coords
species_list = [site.species for site in structure]
species_to_type = {}
type_to_species = {}
type_index = 1
types = []
for sp in species_list:
sp_tuple = tuple(sorted(sp.items())) # make it hashable
if sp_tuple not in species_to_type:
species_to_type[sp_tuple] = type_index
type_to_species[type_index] = sp
type_index += 1