-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathst_trans.py
More file actions
2070 lines (1743 loc) · 107 KB
/
st_trans.py
File metadata and controls
2070 lines (1743 loc) · 107 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 streamlit as st
import io
import numpy as np
import random
from helpers import *
import time
import matplotlib.pyplot as plt
from pymatgen.core import Structure, Element, Lattice
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
from pymatgen.io.cif import CifWriter
import py3Dmol
import pandas as pd
from mp_api.client import MPRester
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
import io
import re
from atat_module import *
from ase import Atoms
from ase.build import make_supercell
from pymatgen.io.ase import AseAtomsAdaptor
from ase.io import write
import logging
import threading
import queue
import re
import plotly.graph_objects as go
from plotly.subplots import make_subplots
MP_API_KEY = "UtfGa1BUI3RlWYVwfpMco2jVt8ApHOye"
if "previous_generation_mode" not in st.session_state:
st.session_state.previous_generation_mode = "Single Run"
def create_bulk_download_zip_fixed(results, download_format, options=None):
import zipfile
from io import BytesIO
import time
if options is None:
options = {}
try:
with st.spinner(f"Creating ZIP with {len(results)} {download_format} files..."):
zip_buffer = BytesIO()
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
for result in results:
try:
file_content = generate_structure_file_content_with_options(
result['structure'],
download_format,
options
)
file_extension = get_file_extension(download_format)
filename = f"SQS_run_{result['run_number']}_seed_{result['seed']}.{file_extension}"
zip_file.writestr(filename, file_content)
except Exception as e:
error_filename = f"ERROR_run_{result['run_number']}_seed_{result['seed']}.txt"
error_content = f"Error generating {download_format} file: {str(e)}"
zip_file.writestr(error_filename, error_content)
zip_buffer.seek(0)
timestamp = int(time.time())
zip_filename = f"SQS_multi_run_{download_format}_{timestamp}.zip"
st.download_button(
label=f"📥 Download ZIP ({len(results)} files)",
data=zip_buffer.getvalue(),
file_name=zip_filename,
mime="application/zip",
type="primary",
key=f"zip_download_{timestamp}",
help=f"Download ZIP file containing all {len(results)} SQS structures in {download_format} format"
)
st.success(f"✅ ZIP file with {len(results)} {download_format} structures ready!")
except Exception as e:
st.error(f"Error creating ZIP file: {e}")
st.error("Please try again or check your structure files.")
def get_file_extension(file_format):
extensions = {
"CIF": "cif",
"VASP": "poscar",
"LAMMPS": "lmp",
"XYZ": "xyz"
}
return extensions.get(file_format, "txt")
def generate_structure_file_content_with_options(structure, file_format, options=None):
if options is None:
options = {}
try:
if file_format == "CIF":
from pymatgen.io.cif import CifWriter
cif_writer = CifWriter(structure)
return cif_writer.__str__()
elif file_format == "VASP":
from pymatgen.io.ase import AseAtomsAdaptor
from ase.io import write
from ase.constraints import FixAtoms
from io import StringIO
ase_structure = AseAtomsAdaptor.get_atoms(structure)
use_fractional = options.get('use_fractional', True)
use_selective_dynamics = options.get('use_selective_dynamics', False)
if use_selective_dynamics:
constraint = FixAtoms(indices=[])
ase_structure.set_constraint(constraint)
out = StringIO()
write(out, ase_structure, format="vasp", direct=use_fractional, sort=True)
return out.getvalue()
elif file_format == "LAMMPS":
from pymatgen.io.ase import AseAtomsAdaptor
from ase.io import write
from io import StringIO
ase_structure = AseAtomsAdaptor.get_atoms(structure)
atom_style = options.get('atom_style', 'atomic')
units = options.get('units', 'metal')
include_masses = options.get('include_masses', True)
force_skew = options.get('force_skew', False)
out = StringIO()
write(
out,
ase_structure,
format="lammps-data",
atom_style=atom_style,
units=units,
masses=include_masses,
force_skew=force_skew
)
return out.getvalue()
elif file_format == "XYZ":
from pymatgen.io.ase import AseAtomsAdaptor
from ase.io import write
from io import StringIO
ase_structure = AseAtomsAdaptor.get_atoms(structure)
out = StringIO()
write(out, ase_structure, format="xyz")
return out.getvalue()
else:
return f"Unsupported format: {file_format}"
except Exception as e:
return f"Error generating {file_format}: {str(e)}"
def create_bulk_download_zip(results, download_format, options=None):
import zipfile
from io import BytesIO
if options is None:
options = {}
try:
zip_buffer = BytesIO()
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
for result in results:
try:
file_content = generate_structure_file_content_with_options(
result['structure'],
download_format,
options
)
file_extension = get_file_extension(download_format)
filename = f"SQS_run_{result['run_number']}_seed_{result['seed']}.{file_extension}"
zip_file.writestr(filename, file_content)
except Exception as e:
error_filename = f"ERROR_run_{result['run_number']}_seed_{result['seed']}.txt"
error_content = f"Error generating {download_format} file: {str(e)}"
zip_file.writestr(error_filename, error_content)
zip_buffer.seek(0)
timestamp = int(time.time())
options_str = ""
if download_format == "VASP" and options:
coord_type = "frac" if options.get('use_fractional', True) else "cart"
sd_type = "sd" if options.get('use_selective_dynamics', False) else "nosd"
options_str = f"_{coord_type}_{sd_type}"
elif download_format == "LAMMPS" and options:
atom_style = options.get('atom_style', 'atomic')
units = options.get('units', 'metal')
options_str = f"_{atom_style}_{units}"
zip_filename = f"SQS_multi_run_{download_format}{options_str}_{timestamp}.zip"
zip_key = f"zip_download_bulk_{download_format}_{timestamp}"
st.download_button(
label=f"📥 Download {download_format} ZIP ({len(results)} files)",
data=zip_buffer.getvalue(),
file_name=zip_filename,
mime="application/zip",
type="primary",
key=zip_key,
help=f"Download ZIP file containing all {len(results)} successful SQS structures in {download_format} format"
)
st.success(f"✅ ZIP file with {len(results)} {download_format} structures ready for download!")
except Exception as e:
st.error(f"Error creating ZIP file: {e}")
st.error("Please try again or contact support if the problem persists.")
def display_multi_run_results(all_results=None, download_format="CIF"):
import numpy as np
if all_results is None:
if "multi_run_results" in st.session_state and st.session_state.multi_run_results:
all_results = st.session_state.multi_run_results
else:
return
if not all_results:
return
results_data = []
valid_results = [r for r in all_results if r.get('best_score') is not None]
for result in all_results:
if result.get('best_score') is not None:
results_data.append({
"Run": result['run_number'],
"Seed": result['seed'],
"Best Score": f"{result['best_score']:.4f}",
"Time (s)": f"{result['elapsed_time']:.1f}",
"Atoms": len(result['structure']) if result.get('structure') else 0,
"Status": "✅ Success"
})
else:
results_data.append({
"Run": result['run_number'],
"Seed": result['seed'],
"Best Score": "Failed",
"Time (s)": f"{result.get('elapsed_time', 0):.1f}",
"Atoms": 0,
"Status": "❌ Error"
})
if results_data:
results_df = pd.DataFrame(results_data)
st.dataframe(results_df, width='stretch')
if valid_results:
best_result = min(valid_results, key=lambda x: x['best_score'])
st.success(f"🥇 **Best Result:** Run {best_result['run_number']} with score {best_result['best_score']:.4f}")
scores = [r['best_score'] for r in valid_results]
if len(scores) > 1:
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Best Score", f"{min(scores):.4f}")
with col2:
st.metric("Worst Score", f"{max(scores):.4f}")
with col3:
st.metric("Average Score", f"{np.mean(scores):.4f}")
with col4:
st.metric("Std Dev", f"{np.std(scores):.4f}")
st.subheader("📥 Download Individual Structures")
col_format, col_options = st.columns([1, 2])
with col_format:
selected_format = st.selectbox(
"Select format:",
["CIF", "VASP", "LAMMPS", "XYZ"],
index=0,
key="multi_run_individual_format"
)
format_options = {}
with col_options:
if selected_format == "VASP":
st.write("**VASP Options:**")
col_vasp1, col_vasp2 = st.columns(2)
with col_vasp1:
format_options['use_fractional'] = st.checkbox(
"Fractional coordinates",
value=True,
key="multi_vasp_fractional"
)
with col_vasp2:
format_options['use_selective_dynamics'] = st.checkbox(
"Selective dynamics",
value=False,
key="multi_vasp_selective"
)
elif selected_format == "LAMMPS":
st.write("**LAMMPS Options:**")
col_lmp1, col_lmp2 = st.columns(2)
with col_lmp1:
format_options['atom_style'] = st.selectbox(
"Atom style:",
["atomic", "charge", "full"],
index=0,
key="multi_lammps_atom_style"
)
format_options['units'] = st.selectbox(
"Units:",
["metal", "real", "si"],
index=0,
key="multi_lammps_units"
)
with col_lmp2:
format_options['include_masses'] = st.checkbox(
"Include masses",
value=True,
key="multi_lammps_masses"
)
format_options['force_skew'] = st.checkbox(
"Force triclinic",
value=False,
key="multi_lammps_skew"
)
else:
st.write("")
successful_results = [r for r in all_results if r.get('structure') is not None]
if successful_results:
best_run_number = min(successful_results, key=lambda x: x.get('best_score', float('inf'))).get('run_number')
num_cols = min(4, len(successful_results))
cols = st.columns(num_cols)
for idx, result in enumerate(successful_results):
with cols[idx % num_cols]:
is_best = (result['run_number'] == best_run_number)
button_type = "primary" if is_best else "secondary"
label = f"📥 Run {result['run_number']}" + (" 🥇" if is_best else "")
label += f"\nScore: {result['best_score']:.4f}"
try:
file_content = generate_structure_file_content_with_options(
result['structure'],
selected_format,
format_options
)
file_extension = get_file_extension(selected_format)
filename = f"SQS_run_{result['run_number']}_seed_{result['seed']}.{file_extension}"
unique_key = f"download_run_{result['run_number']}_{result['seed']}_{selected_format}_{hash(str(format_options))}"
st.download_button(
label=label,
data=file_content,
file_name=filename,
mime="text/plain",
type=button_type,
key=unique_key,
help=f"Download {selected_format} structure from run {result['run_number']}"
)
except Exception as e:
st.error(f"Error: {e}")
else:
st.warning("No successful runs are available for download.")
if valid_results:
best_result = min(valid_results, key=lambda x: x['best_score'])
st.subheader("🏆 Best Structure Analysis")
colp1, colp2 = st.columns([1, 1])
with colp2:
# with st.expander(f"📊 Structure Details for Best Run {best_result['run_number']}", expanded=False):
st.markdown(f"📊 Structure Details for Best Run {best_result['run_number']}")
col_info1, col_info2 = st.columns(2)
with col_info1:
st.write("**Structure Information:**")
best_structure = best_result['structure']
comp = best_structure.composition
comp_data = []
for el, amt in comp.items():
actual_frac = amt / comp.num_atoms
comp_data.append({
"Element": el.symbol,
"Count": int(amt),
"Fraction": f"{actual_frac:.4f}"
})
comp_df = pd.DataFrame(comp_data)
st.dataframe(comp_df, width='stretch')
with col_info2:
st.write("**Lattice Parameters:**")
lattice = best_structure.lattice
st.write(f"a = {lattice.a:.4f} Å")
st.write(f"b = {lattice.b:.4f} Å")
st.write(f"c = {lattice.c:.4f} Å")
st.write(f"α = {lattice.alpha:.2f}°")
st.write(f"β = {lattice.beta:.2f}°")
st.write(f"γ = {lattice.gamma:.2f}°")
st.write(f"Volume = {lattice.volume:.2f} Ų")
with colp1:
st.write("**3D Structure Visualization:**")
try:
from io import StringIO
import py3Dmol
from pymatgen.io.ase import AseAtomsAdaptor
from ase.io import write
import numpy as np
jmol_colors = {
"H": "#FFFFFF",
"He": "#D9FFFF",
"Li": "#CC80FF",
"Be": "#C2FF00",
"B": "#FFB5B5",
"C": "#909090",
"N": "#3050F8",
"O": "#FF0D0D",
"F": "#90E050",
"Ne": "#B3E3F5",
"Na": "#AB5CF2",
"Mg": "#8AFF00",
"Al": "#BFA6A6",
"Si": "#F0C8A0",
"P": "#FF8000",
"S": "#FFFF30",
"Cl": "#1FF01F",
"Ar": "#80D1E3",
"K": "#8F40D4",
"Ca": "#3DFF00",
"Sc": "#E6E6E6",
"Ti": "#BFC2C7",
"V": "#A6A6AB",
"Cr": "#8A99C7",
"Mn": "#9C7AC7",
"Fe": "#E06633",
"Co": "#F090A0",
"Ni": "#50D050",
"Cu": "#C88033",
"Zn": "#7D80B0",
"Ga": "#C28F8F",
"Ge": "#668F8F",
"As": "#BD80E3",
"Se": "#FFA100",
"Br": "#A62929",
"Kr": "#5CB8D1",
"Rb": "#702EB0",
"Sr": "#00FF00",
"Y": "#94FFFF",
"Zr": "#94E0E0",
"Nb": "#73C2C9",
"Mo": "#54B5B5",
"Tc": "#3B9E9E",
"Ru": "#248F8F",
"Rh": "#0A7D8C",
"Pd": "#006985",
"Ag": "#C0C0C0",
"Cd": "#FFD98F",
"In": "#A67573",
"Sn": "#668080",
"Sb": "#9E63B5",
"Te": "#D47A00",
"I": "#940094",
"Xe": "#429EB0",
"Cs": "#57178F",
"Ba": "#00C900",
"La": "#70D4FF",
"Ce": "#FFFFC7",
"Pr": "#D9FFC7",
"Nd": "#C7FFC7",
"Pm": "#A3FFC7",
"Sm": "#8FFFC7",
"Eu": "#61FFC7",
"Gd": "#45FFC7",
"Tb": "#30FFC7",
"Dy": "#1FFFC7",
"Ho": "#00FF9C",
"Er": "#00E675",
"Tm": "#00D452",
"Yb": "#00BF38",
"Lu": "#00AB24",
"Hf": "#4DC2FF",
"Ta": "#4DA6FF",
"W": "#2194D6",
"Re": "#267DAB",
"Os": "#266696",
"Ir": "#175487",
"Pt": "#D0D0E0",
"Au": "#FFD123",
"Hg": "#B8B8D0",
"Tl": "#A6544D",
"Pb": "#575961",
"Bi": "#9E4FB5",
"Po": "#AB5C00",
"At": "#754F45",
"Rn": "#428296",
"Fr": "#420066",
"Ra": "#007D00",
"Ac": "#70ABFA",
"Th": "#00BAFF",
"Pa": "#00A1FF",
"U": "#008FFF",
"Np": "#0080FF",
"Pu": "#006BFF",
"Am": "#545CF2",
"Cm": "#785CE3",
"Bk": "#8A4FE3",
"Cf": "#A136D4",
"Es": "#B31FD4",
"Fm": "#B31FBA",
"Md": "#B30DA6",
"No": "#BD0D87",
"Lr": "#C70066",
"Rf": "#CC0059",
"Db": "#D1004F",
"Sg": "#D90045",
"Bh": "#E00038",
"Hs": "#E6002E",
"Mt": "#EB0026"
}
def add_box(view, cell, color='black', linewidth=2):
vertices = np.array([
[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0],
[0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]
])
edges = [
[0, 1], [1, 2], [2, 3], [3, 0],
[4, 5], [5, 6], [6, 7], [7, 4],
[0, 4], [1, 5], [2, 6], [3, 7]
]
cart_vertices = np.dot(vertices, cell)
for edge in edges:
start, end = cart_vertices[edge[0]], cart_vertices[edge[1]]
view.addCylinder({
'start': {'x': start[0], 'y': start[1], 'z': start[2]},
'end': {'x': end[0], 'y': end[1], 'z': end[2]},
'radius': 0.05,
'color': color
})
structure_ase = AseAtomsAdaptor.get_atoms(best_structure)
xyz_io = StringIO()
write(xyz_io, structure_ase, format="xyz")
xyz_str = xyz_io.getvalue()
view = py3Dmol.view(width=600, height=400)
view.addModel(xyz_str, "xyz")
view.setStyle({'model': 0}, {"sphere": {"radius": 0.3, "colorscheme": "Jmol"}})
cell = structure_ase.get_cell()
add_box(view, cell, color='black', linewidth=2)
view.zoomTo()
view.zoom(1.2)
html_string = view._make_html()
st.iframe(html_string, height=420, width=620)
unique_elements = sorted(set(structure_ase.get_chemical_symbols()))
legend_html = "<div style='display: flex; flex-wrap: wrap; align-items: center; justify-content: center; margin-top: 10px;'>"
for elem in unique_elements:
color = jmol_colors.get(elem, "#CCCCCC")
legend_html += (
f"<div style='margin-right: 15px; display: flex; align-items: center;'>"
f"<div style='width: 20px; height: 20px; background-color: {color}; margin-right: 5px; border: 1px solid black; border-radius: 50%;'></div>"
f"<span style='font-weight: bold;'>{elem}</span></div>"
)
legend_html += "</div>"
st.markdown(legend_html, unsafe_allow_html=True)
except Exception as e:
st.error(f"Error visualizing best structure: {e}")
st.write("**PRDF Analysis:**")
try:
prdf_cutoff = st.session_state.get('sqs_prdf_cutoff', 10.0)
prdf_bin_size = st.session_state.get('sqs_prdf_bin_size', 0.1)
calculate_and_display_sqs_prdf(best_structure, cutoff=prdf_cutoff, bin_size=prdf_bin_size)
except Exception as e:
st.error(f"Error calculating PRDF for best structure: {e}")
st.info("PRDF analysis could not be completed for the best structure.")
if successful_results:
st.subheader("📦 Bulk Download")
col_bulk_format, col_bulk_options = st.columns([1, 2])
with col_bulk_format:
bulk_format = st.selectbox(
"Bulk format:",
["CIF", "VASP", "LAMMPS", "XYZ"],
index=0,
key="bulk_format_selector"
)
bulk_options = {}
with col_bulk_options:
if bulk_format == "VASP":
st.write("**VASP Bulk Options:**")
col_bulk_vasp1, col_bulk_vasp2 = st.columns(2)
with col_bulk_vasp1:
bulk_options['use_fractional'] = st.checkbox(
"Fractional coordinates",
value=True,
key="bulk_vasp_fractional"
)
with col_bulk_vasp2:
bulk_options['use_selective_dynamics'] = st.checkbox(
"Selective dynamics",
value=False,
key="bulk_vasp_selective"
)
elif bulk_format == "LAMMPS":
st.write("**LAMMPS Bulk Options:**")
col_bulk_lmp1, col_bulk_lmp2 = st.columns(2)
with col_bulk_lmp1:
bulk_options['atom_style'] = st.selectbox(
"Atom style:",
["atomic", "charge", "full"],
index=0,
key="bulk_lammps_atom_style"
)
bulk_options['units'] = st.selectbox(
"Units:",
["metal", "real", "si"],
index=0,
key="bulk_lammps_units"
)
with col_bulk_lmp2:
bulk_options['include_masses'] = st.checkbox(
"Include masses",
value=True,
key="bulk_lammps_masses"
)
bulk_options['force_skew'] = st.checkbox(
"Force triclinic",
value=False,
key="bulk_lammps_skew"
)
if st.button("📥 Download all structures as ZIP", type="primary", key="bulk_download_button"):
create_bulk_download_zip_fixed(successful_results, bulk_format, bulk_options)
def ase_to_pymatgen(atoms):
symbols = atoms.get_chemical_symbols()
positions = atoms.get_positions()
cell = atoms.get_cell()
lattice = Lattice(cell)
return Structure(lattice, symbols, positions, coords_are_cartesian=True)
if "persistent_prdf_data" not in st.session_state:
st.session_state.persistent_prdf_data = None
if "prdf_structure_key" not in st.session_state:
st.session_state.prdf_structure_key = None
def render_sqs_module():
st.markdown(
"""
<h1 style="display: flex; align-items: center; gap: 10px; color: #1E3D7B;">
🎲
<span style="color:#2E86C1; font-weight:bold;">SimplySQS</span>
<span style="
background-color: #2E86C1;
color: white;
font-size: 12px;
padding: 4px 8px;
border-radius: 12px;
">
v0.7.1 • 4/11/2026
</span>
</h1>
<h3 style='text-align: left; color: #444444; font-weight: normal;'>
Generate input and analyze output files for
<b><span style='color:#1A7F5D;'>ATAT mcsqs</span></b>
to create <b><em>special quasirandom structures (SQS)</em></b>
</h3>
""",
unsafe_allow_html=True
)
st.markdown(
"""
<hr style="border: none; height: 6px; background-color: #3399ff; border-radius: 8px; margin: 20px 0;">
""",
unsafe_allow_html=True
)
cl1, cl2,cl3 = st.columns(3)
with cl1:
how_cite = st.checkbox(f"📚 How to **cite**")
if how_cite:
with st.expander("How to cite", icon="📚", expanded=True):
st.markdown("""
Please cite the following sources
- **SimplySQS interface** - [LEBEDA, Miroslav, et al. SimplySQS: An Automated and reproducible workflow for special quasirandom structure generation with ATAT. Journal of Computational Science, 2026](https://doi.org/10.1016/j.jocs.2026.102846).
- **ATAT mcsqs method** - [VAN DE WALLE, Axel, et al. Efficient stochastic generation of special quasirandom structures. Calphad, 2013](https://www.sciencedirect.com/science/article/pii/S0364591613000540?casa_token=i1iog7eW3lQAAAAA:wxlTn-9Twj38XFx1lMfSazPb6r0JrDV7NPxeums5-2qFXHWItT2ZVu9E-IfuBjRsr7f1BEzcSw).
- **ATAT** - [VAN DE WALLE, Axel; ASTA, Mark; CEDER, Gerbrand. The alloy theoretic automated toolkit: A user guide. Calphad, 2002](https://www.sciencedirect.com/science/article/abs/pii/S0364591602800062).
""")
with cl2:
read_more = st.checkbox(f"📖 Read **more** about **SQS**, **ATAT**, and how to **compile it**"
)
if read_more:
with st.expander("Read more", icon="📖", expanded=True):
st.markdown("""
### Read More About SQS and ATAT
Please see the following useful resources
- [User guide how to compile ATAT mcsqs by Implant team (see also the compilation steps below)](https://implant.fs.cvut.cz/atat-mcsqs/).
- [Tutorial explaining how to use SQS for disordered materials and generate them using ATAT mcsqs](https://cniu.me/2017/08/05/SQS.html#generate-sqs).
- [Tutorial explaining how to generate SQS using ATAT mcsqs](https://github.com/CMSLabIITK/SQS_generation).
- [User guide for ATAT](https://axelvandewalle.github.io/www-avdw//atat/manual.pdf).
- [User guide specifically for ATAT mcsqs](https://axelvandewalle.github.io/www-avdw//atat/manual/node48.html).
- [ATAT forum](https://matsci.org/c/atat/67).
- [C++ code for converting bestsqs.out into POSCAR format](https://github.com/c-niu/sqs2poscar).
- [Python code for converting bestsqs.out into POSCAR format](https://github.com/JianboHIT/sqs2vasp).
### 🛠️ ATAT Installation Tutorial
#### 🎥 Video Tutorial
**Watch the complete compilation process:** [ATAT Compilation Video Tutorial](https://youtu.be/d5PceJoL1tw?si=akSMQ76_hKHaTKcB)
#### 📝 Written Tutorial
---
#### Prerequisites (Ubuntu/WSL2)
First, update your system and install required packages:
```bash
sudo apt-get upgrade
sudo apt-get install tcsh make g++
```
#### Download and Compile ATAT
1. **Download ATAT toolkit:**
```bash
wget http://alum.mit.edu/www/avdw/atat/atat3_36.tar.gz
```
2. **Extract and prepare build directory:**
```bash
tar xvzf atat3_36.tar.gz
cd atat
mkdir build
```
3. **Configure installation path:**
```bash
nano makefile
```
Change the first line from `BINDIR=...` to use the current directory path. You can get your current path with:
```bash
pwd
```
Then edit the makefile to set:
```
BINDIR=/full/path/from/pwd/command/build
```
For example, if `pwd` shows `/home/username/atat`, then set:
```
BINDIR=/home/username/atat/build
```
Save (Ctrl+S) and exit (Ctrl+X).
4. **Compile ATAT:**
```bash
make -j 10
make install
```
5. **Add to PATH:**
```bash
cd build
pwd # Note this path
nano ~/.bashrc
```
Add this line at the bottom of ~/.bashrc (replace the path with your actual build directory path):
```bash
export PATH=$(pwd)/build:$PATH
```
Save, exit, and refresh:
```bash
source ~/.bashrc
```
6. **Test installation:**
```bash
mcsqs
```
This should display the list of mcsqs parameters if the compilation was successful.
""")
# -------------- DATABASE ----------
with cl3:
show_database_search = st.checkbox("🗃️ Enable **database search** (MP, AFLOW, COD, MC3D)",
value=False,
help="🗃️ Enable to search in Materials Project, AFLOW, and COD databases")
st.markdown("""
<style>
div.stButton > button[kind="primary"] {
background-color: #0099ff; color: white; font-size: 16px; font-weight: bold;
padding: 0.5em 1em; border: none; border-radius: 5px; height: 3em; width: 100%;
}
div.stButton > button[kind="primary"]:active, div.stButton > button[kind="primary"]:focus {
background-color: #007acc !important; color: white !important; box-shadow: none !important;
}
div.stButton > button[kind="secondary"] {
background-color: #dc3545; color: white; font-size: 16px; font-weight: bold;
padding: 0.5em 1em; border: none; border-radius: 5px; height: 3em; width: 100%;
}
div.stButton > button[kind="secondary"]:active, div.stButton > button[kind="secondary"]:focus {
background-color: #c82333 !important; color: white !important; box-shadow: none !important;
}
div.stButton > button[kind="tertiary"] {
background-color: #6f42c1; color: white; font-size: 16px; font-weight: bold;
padding: 0.5em 1em; border: none; border-radius: 5px; height: 3em; width: 100%;
}
div.stButton > button[kind="tertiary"]:active, div.stButton > button[kind="tertiary"]:focus {
background-color: #5a2d91 !important; color: white !important; box-shadow: none !important;
}
div[data-testid="stDataFrameContainer"] table td { font-size: 16px !important; }
#MainMenu {visibility: hidden;} footer {visibility: hidden;} header {visibility: hidden;}
</style>
""", unsafe_allow_html=True)
def get_space_group_info(number):
symbol = SPACE_GROUP_SYMBOLS.get(number, f"SG#{number}")
return symbol
if show_database_search:
css = '''
<style>
.stTabs [data-baseweb="tab-list"] button [data-testid="stMarkdownContainer"] p {
font-size: 1.15rem !important;
color: #1e3a8a !important;
font-weight: 600 !important;
margin: 0 !important;
}
.stTabs [data-baseweb="tab-list"] {
gap: 20px !important;
}
.stTabs [data-baseweb="tab-list"] button {
background-color: #f0f4ff !important;
border-radius: 12px !important;
padding: 8px 16px !important;
transition: all 0.3s ease !important;
border: none !important;
color: #1e3a8a !important;
}
.stTabs [data-baseweb="tab-list"] button:hover {
background-color: #dbe5ff !important;
cursor: pointer;
}
.stTabs [data-baseweb="tab-list"] button[aria-selected="true"] {
background-color: #e0e7ff !important;
color: #1e3a8a !important;
font-weight: 700 !important;
box-shadow: 0 2px 6px rgba(30, 58, 138, 0.3) !important;
/* Added underline (thicker) */
border-bottom: 4px solid #1e3a8a !important;
border-radius: 12px 12px 0 0 !important; /* keep rounded only on top */
}
.stTabs [data-baseweb="tab-list"] button:focus {
outline: none !important;
}
</style>
'''
st.markdown(css, unsafe_allow_html=True)
with st.expander("Search for Structures Online in Databases", icon="🔍", expanded=True):
cols, cols2, cols3 = st.columns([1.5, 1.5, 3.5])
with cols:
db_choices = st.multiselect(
"Select Database(s)",
options=["Materials Project", "AFLOW", "COD", "MC3D"],
default=["Materials Project", "COD", "MC3D"],
help="Choose which databases to search for structures. You can select multiple databases."
)
if not db_choices:
st.warning("Please select at least one database to search.")
st.markdown(
"**Maximum number of structures to be found in each database (for improving performance):**")
col_limits = st.columns(4)
search_limits = {}
if "Materials Project" in db_choices:
with col_limits[0]:
search_limits["Materials Project"] = st.number_input(
"MP Limit:", min_value=1, max_value=2000, value=300, step=10,
help="Maximum results from Materials Project"
)
if "AFLOW" in db_choices:
with col_limits[1]:
search_limits["AFLOW"] = st.number_input(
"AFLOW Limit:", min_value=1, max_value=2000, value=300, step=10,
help="Maximum results from AFLOW"
)
if "COD" in db_choices:
with col_limits[2]:
search_limits["COD"] = st.number_input(
"COD Limit:", min_value=1, max_value=2000, value=300, step=10,
help="Maximum results from COD"
)
if "MC3D" in db_choices:
with col_limits[3]:
search_limits["MC3D"] = st.number_input(
"MC3D Limit:", min_value=1, max_value=2000, value=300, step=10,
help="Maximum results from MC3D"
)
with cols2:
search_mode = st.radio(
"Search by:",
options=["Elements", "Structure ID", "Space Group + Elements", "Formula", "Search Mineral"],
help="Choose your search strategy"
)
if search_mode == "Elements":
selected_elements = st.multiselect(
"Select elements for search:",
options=ELEMENTS,
default=["Na", "Cl"],
help="Choose one or more chemical elements"
)
search_query = " ".join(selected_elements) if selected_elements else ""
elif search_mode == "Structure ID":
structure_ids = st.text_area(
"Enter Structure IDs (one per line):",
value="mp-5229\ncod_1512124\naflow:010158cb2b41a1a5\nmc3d-667864",
help="Enter structure IDs. Examples:\n- Materials Project: mp-5229\n- COD: cod_1512124 (with cod_ prefix)\n- AFLOW: aflow:010158cb2b41a1a5 (AUID format)"
)
elif search_mode == "Space Group + Elements":
selected_space_group = st.selectbox(
"Select Space Group:",
options=SPACE_GROUP_OPTIONS,
index=224, #
help="Start typing to search by number or symbol",
key="db_search_space_group"
)
space_group_number = extract_space_group_number(selected_space_group)
space_group_symbol = selected_space_group.split('(')[1][:-1] if selected_space_group else ""
# st.info(f"Selected: **{space_group_number}** ({space_group_symbol})")
selected_elements = st.multiselect(
"Select elements for search:",
options=ELEMENTS,
default=["Na", "Cl"],
help="Choose one or more chemical elements"
)