-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathatat_module.py
More file actions
6405 lines (5343 loc) · 265 KB
/
atat_module.py
File metadata and controls
6405 lines (5343 loc) · 265 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 pandas as pd
import numpy as np
from pymatgen.core import Structure
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
from ase.build import make_supercell
from helpers import *
from parallel_analysis import *
def render_concentration_sweep_section(chemical_symbols, target_concentrations, transformation_matrix,
primitive_structure, cutoffs, total_atoms_in_supercell):
if not target_concentrations:
return
is_binary = False
sweep_element = None
complement_element = None
selected_sublattice = None
if isinstance(target_concentrations, dict):
first_value = next(iter(target_concentrations.values()))
if isinstance(first_value, dict):
binary_sublattices = []
for sublattice_letter, concentrations in target_concentrations.items():
if len(concentrations) == 2:
elements = list(concentrations.keys())
binary_sublattices.append((sublattice_letter, elements))
if len(binary_sublattices) == 0:
return
elif len(binary_sublattices) == 1:
is_binary = True
selected_sublattice, elements = binary_sublattices[0]
sweep_element = elements[0]
complement_element = elements[1]
else:
st.markdown("---")
st.subheader("🔄 Concentration Sweep Mode")
st.info("Multiple binary sublattices detected. Please select one for concentration sweep:")
st.info(f"You can generate a script to automatically run the mcsqs search across concentration range.")
sublattice_options = []
for sublattice_letter, elements in binary_sublattices:
sublattice_options.append(f"Sublattice {sublattice_letter}: {elements[0]} + {elements[1]}")
selected_option = st.selectbox(
"Choose sublattice for concentration sweep:",
options=sublattice_options,
index=0
)
if selected_option:
selected_idx = sublattice_options.index(selected_option)
selected_sublattice, elements = binary_sublattices[selected_idx]
is_binary = True
sweep_element = elements[0]
complement_element = elements[1]
else:
return
else:
if len(target_concentrations) == 2:
is_binary = True
elements = list(target_concentrations.keys())
sweep_element = elements[0]
complement_element = elements[1]
if not is_binary:
return
st.markdown("---")
st.subheader("🔄 Concentration Sweep Mode")
if selected_sublattice:
st.info(f"**Binary sublattice {selected_sublattice} detected:** {sweep_element} + {complement_element}")
st.info(f"You can generate a script to automatically run the mcsqs search across concentration range.")
else:
st.info(f"**Binary system detected:** {sweep_element} + {complement_element}")
st.info(f"You can generate a script to automatically run the mcsqs search across concentration range.")
enable_sweep = st.checkbox(
f"Enable concentration sweep for {sweep_element}",
value=False,
help=f"Generate bash script to automatically test multiple achievable concentrations of {sweep_element}"
)
if not enable_sweep:
return
supercell_factor = calculate_supercell_factor(transformation_matrix)
if selected_sublattice:
sublattice_sites = 0
sublattice_elements = set([sweep_element, complement_element])
for i, site_elements in enumerate(chemical_symbols):
if isinstance(site_elements, list) and len(site_elements) > 1:
if set(site_elements) == sublattice_elements:
sublattice_sites += 1
total_sites_for_sublattice = sublattice_sites * supercell_factor
st.write(f"**Sites for sublattice {selected_sublattice} in initial unit cell:** {sublattice_sites}")
st.write(f"**Total sites for sublattice {selected_sublattice} in supercell:** {total_sites_for_sublattice}")
possible_concentrations = []
for i in range(1, total_sites_for_sublattice):
conc = i / total_sites_for_sublattice
possible_concentrations.append(round(conc, 6))
else:
st.write(f"**Supercell multiplicity:** {supercell_factor}")
st.write(f"**Minimum concentration step:** 1/{supercell_factor} = {1 / supercell_factor:.6f}")
st.info("**Global Mode:** Each concentration applies to ALL atomic sites equally")
possible_concentrations = []
for i in range(1, supercell_factor):
conc = i / supercell_factor
possible_concentrations.append(round(conc, 6))
atoms = pymatgen_to_ase(primitive_structure)
total_sites_for_sublattice = len(atoms) * supercell_factor
col1, col2 = st.columns(2)
with col1:
if selected_sublattice:
st.write(
f"**Available {sweep_element} concentrations for sublattice {selected_sublattice}:** {len(possible_concentrations)}")
else:
st.write(f"**Available {sweep_element} concentrations:** {len(possible_concentrations)}")
st.write("**Valid concentrations:** " + ", ".join([f"{c:.3f}" for c in possible_concentrations]))
st.write("**Concentration Sampling:**")
col_sample1, col_sample2 = st.columns(2)
with col_sample1:
sample_every_nth = st.number_input(
"Sample every nth concentration:",
min_value=1,
max_value=len(possible_concentrations),
value=1,
step=1,
help="Select every nth concentration (1 = all, 2 = every other, 3 = every third, etc.)",
key="sample_every_nth"
)
with col_sample2:
start_from = st.number_input(
"Start from index:",
min_value=0,
max_value=len(possible_concentrations) - 1,
value=0,
step=1,
help="Starting index for sampling (0 = first concentration)",
key="start_from_index"
)
sampled_indices = list(range(start_from, len(possible_concentrations), sample_every_nth))
default_concentrations = [possible_concentrations[i] for i in sampled_indices]
if sample_every_nth > 1 or start_from > 0:
st.info(
f"📊 Sampling: {len(default_concentrations)} concentrations selected (every {sample_every_nth} starting from index {start_from})")
selected_concentrations = st.multiselect(
f"Select {sweep_element} concentrations for SQS generation:",
options=possible_concentrations,
default=default_concentrations,
help="Choose from achievable concentrations" + (
" based on sublattice size" if selected_sublattice else " (multiples of 1/supercell_multiplicity)")
)
with col2:
mcsqs_mode = st.radio(
"Choose MCSQS mode:",
options=["Supercell Mode", "Atom Count Mode"],
index=0,
help="Supercell mode (-rc): Uses predefined supercell transformation\nAtom Count mode (-n): Searches for optimal supercell with specified atom count",
key="concentration_sweep_mcsqs_mode"
)
if mcsqs_mode == "Supercell Mode":
mode_description = "Uses -rc flag (predefined supercell)"
else:
mode_description = f"Uses -n flag (optimize for total of {total_atoms_in_supercell} atoms)"
st.caption(mode_description)
time_per_conc = st.number_input(
"Time per concentration (minutes)",
min_value=0.1,
max_value=14400.0,
value=30.0,
step=0.5,
help="How long to run mcsqs for each concentration"
)
max_parallel = st.number_input(
"Maximum parallel jobs",
min_value=1,
max_value=200,
value=4,
step=1,
help="Number of parallel mcsqs processes"
)
parallel_runs_per_conc = st.number_input(
"Parallel runs per concentration",
min_value=1,
max_value=200,
value=5,
step=1,
help="Number of parallel mcsqs instances to run for each concentration"
)
progress_update_interval = st.number_input(
"Progress update interval (seconds)",
min_value=1,
max_value=6000,
value=10,
step=1,
help="How often to print the progress update to the console in seconds"
)
if not selected_concentrations:
st.warning("Please select at least one concentration for SQS generation.")
return
st.write(f"**Selected concentrations:** {selected_concentrations}")
st.write(f"**Total estimated time:** {len(selected_concentrations) * time_per_conc:.1f} minutes")
if st.button("Generate Concentration Sweep Script", type="primary"):
if selected_sublattice:
filtered_target_concentrations = {
selected_sublattice: target_concentrations[selected_sublattice]
}
else:
filtered_target_concentrations = target_concentrations
script_content = generate_concentration_sweep_script(
sweep_element,
complement_element,
selected_concentrations,
time_per_conc,
max_parallel,
parallel_runs_per_conc,
#filtered_target_concentrations,
target_concentrations,
chemical_symbols,
transformation_matrix,
primitive_structure,
cutoffs,
total_sites_for_sublattice,
progress_update_interval,
mcsqs_mode, total_atoms_in_supercell
)
st.download_button(
label="📥 Download Concentration Sweep Script",
data=script_content,
file_name="concentration_sweep.sh",
mime="text/plain",
type="primary"
)
st.success(
"Concentration sweep script generated! Make sure to have these prerequisites: **`ATAT mcsqs`**, **`NumPy module in Python`**")
with st.expander("Script Preview", expanded=False):
st.code(script_content, language="bash")
def generate_concentration_sweep_script(sweep_element, complement_element, selected_concentrations,
time_per_conc, max_parallel, parallel_runs_per_conc,
target_concentrations, chemical_symbols, transformation_matrix,
primitive_structure, cutoffs, total_sites, progress_update_interval, mcsqs_mode,
total_atoms_in_supercell):
corrdump_cmd = "corrdump -l=rndstr.in -ro -noe -nop -clus"
if len(cutoffs) >= 1 and cutoffs[0] is not None:
corrdump_cmd += f" -2={cutoffs[0]}"
if len(cutoffs) >= 2 and cutoffs[1] is not None:
corrdump_cmd += f" -3={cutoffs[1]}"
if len(cutoffs) >= 3 and cutoffs[2] is not None:
corrdump_cmd += f" -4={cutoffs[2]}"
atoms = pymatgen_to_ase(primitive_structure)
original_lattice = primitive_structure.lattice
max_param = max(original_lattice.a, original_lattice.b, original_lattice.c)
if mcsqs_mode == "Supercell Mode":
mcsqs_base_cmd = "mcsqs -rc"
mode_description = "supercell mode (-rc)"
else:
mcsqs_base_cmd = f"mcsqs -n {total_atoms_in_supercell}"
mode_description = f"atom count mode (-n {total_atoms_in_supercell})"
script_lines = [
"#!/bin/bash",
"",
f"# Concentration sweep script for {sweep_element}-{complement_element} system",
f"# Generated by SimplySQS",
f"# Corrdump command: {corrdump_cmd}",
f"# Total sites in supercell: {total_sites}",
f"# Parallel runs per concentration: {parallel_runs_per_conc}",
f"# Maximum concurrent jobs: {max_parallel}",
f"# Concentrations: {selected_concentrations}",
f"# Total estimated time: {len(selected_concentrations) * time_per_conc} minutes",
"",
"set -e",
"",
f'SWEEP_ELEMENT="{sweep_element}"',
f'COMPLEMENT_ELEMENT="{complement_element}"',
f"TIME_PER_CONC_DEFAULT={time_per_conc}",
f"MAX_PARALLEL={max_parallel}",
f"PARALLEL_RUNS_PER_CONC_DEFAULT={parallel_runs_per_conc}",
f'CORRDUMP_CMD="{corrdump_cmd}"',
f'MCSQS_BASE_CMD="{mcsqs_base_cmd}"',
f'MCSQS_MODE="{mcsqs_mode}"',
f"PROGRESS_UPDATE_INTERVAL={progress_update_interval}",
"",
'TOTAL_TIME_SECONDS=$(echo "$TIME_PER_CONC_DEFAULT * 60" | bc | xargs printf "%.0f")',
"",
"GLOBAL_START_TIME=$(date +%s)",
"declare -A CONC_START_TIMES",
"declare -A CONC_BEST_SCORES",
"declare -A CONC_BEST_RUNS",
"",
'echo "🚀 Starting concentration sweep..."',
'echo "🔬 Sweep element: $SWEEP_ELEMENT"',
'echo "🔬 Complement element: $COMPLEMENT_ELEMENT"',
'echo "🧪 Corrdump command: $CORRDUMP_CMD"',
'echo "⚙️ MCSQS mode: $MCSQS_MODE"',
'echo "⚙️ MCSQS command: $MCSQS_BASE_CMD"',
'echo "⏱️ Default time per concentration: $TIME_PER_CONC_DEFAULT minutes"',
f'echo "⚙️ Default parallel runs per concentration: $PARALLEL_RUNS_PER_CONC_DEFAULT"',
f'echo "🔍 Concentrations to be searched: {selected_concentrations}"',
"",
'mkdir -p best_poscars',
'echo "📂 Created folder best_poscars to store the best structures from each concentration."',
"",
"cleanup() {",
' echo "🧹 Cleaning up background processes..."',
' pkill -9 -f "mcsqs" 2>/dev/null || true',
' pkill -9 -f "monitor_progress" 2>/dev/null || true',
' jobs -p | xargs -r kill -9 2>/dev/null || true',
" wait 2>/dev/null || true",
' echo "✅ Cleanup complete."',
"}",
"",
"trap cleanup EXIT INT TERM SIGINT SIGTERM",
"",
"format_elapsed_time() {",
" local elapsed=$1",
" local days=$((elapsed / 86400))",
" local hours=$(((elapsed % 86400) / 3600))",
" local minutes=$(((elapsed % 3600) / 60))",
" local seconds=$((elapsed % 60))",
" printf '%02d:%02d:%02d:%02d' $days $hours $minutes $seconds",
"}",
"",
"extract_latest_objective() {",
' grep "Objective_function=" "$1" | tail -1 | sed "s/.*= *//" 2>/dev/null || echo ""',
"}",
"",
"extract_latest_step() {",
' grep -c "Objective_function=" "$1" 2>/dev/null || echo "0"',
"}",
"",
"get_best_objective_and_run() {",
" local best_obj=\"N/A\"",
" local best_run=\"N/A\"",
" local parallel_runs_per_conc=$1",
" ",
" if [ $parallel_runs_per_conc -gt 1 ]; then",
" for ((i=1; i<=parallel_runs_per_conc; i++)); do",
" if [ -f \"mcsqs$i.log\" ]; then",
" local current_obj=$(extract_latest_objective \"mcsqs$i.log\")",
" if [ -n \"$current_obj\" ] && [ \"$current_obj\" != \"N/A\" ] && [ \"$current_obj\" != \"\" ]; then",
" if [ \"$best_obj\" = \"N/A\" ] || awk \"BEGIN {exit !($current_obj < $best_obj)}\" 2>/dev/null; then",
" best_obj=\"$current_obj\"",
" best_run=\"$i\"",
" fi",
" fi",
" fi",
" done",
" else",
" if [ -f \"mcsqs.log\" ]; then",
" local current_obj=$(extract_latest_objective \"mcsqs.log\")",
" if [ -n \"$current_obj\" ] && [ \"$current_obj\" != \"N/A\" ] && [ \"$current_obj\" != \"\" ]; then",
" best_obj=\"$current_obj\"",
" best_run=\"1\"",
" fi",
" fi",
" fi",
" ",
" echo \"$best_obj,$best_run\"",
"}",
"",
"initialize_concentration_csv() {",
" local conc=$1",
" local parallel_runs_per_conc=$2",
" local csv_file=\"optimization_data_${conc}.csv\"",
" ",
" # Create CSV header",
" if [ $parallel_runs_per_conc -gt 1 ]; then",
" header=\"Minute,Timestamp,Best_Objective,Best_Run\"",
" for ((i=1; i<=parallel_runs_per_conc; i++)); do",
" header=\"$header,Run${i}_Steps,Run${i}_Objective,Run${i}_Status\"",
" done",
" else",
" header=\"Minute,Timestamp,Steps,Objective_Function,Status\"",
" fi",
" ",
" echo \"$header\" > \"$csv_file\"",
" echo \"$csv_file\"",
"}",
"",
# NEW FUNCTION: Log data to CSV
"log_to_csv() {",
" local csv_file=$1",
" local conc=$2",
" local parallel_runs_per_conc=$3",
" local elapsed_minutes=$4",
" ",
" local current_time=$(date +'%Y-%m-%d %H:%M:%S')",
" local result=$(get_best_objective_and_run $parallel_runs_per_conc)",
" local best_obj=$(echo $result | cut -d',' -f1)",
" local best_run=$(echo $result | cut -d',' -f2)",
" ",
" if [ $parallel_runs_per_conc -gt 1 ]; then",
" # Parallel runs: log all runs data",
" row_data=\"$elapsed_minutes,$current_time,$best_obj,$best_run\"",
" ",
" for ((i=1; i<=parallel_runs_per_conc; i++)); do",
" local log_file=\"mcsqs$i.log\"",
" local steps=\"0\"",
" local objective=\"N/A\"",
" local status=\"STOPPED\"",
" ",
" if pgrep -f \"mcsqs.*-ip=$i\" > /dev/null; then",
" status=\"RUNNING\"",
" fi",
" ",
" if [ -f \"$log_file\" ]; then",
" steps=$(extract_latest_step \"$log_file\")",
" objective=$(extract_latest_objective \"$log_file\")",
" steps=${steps:-\"0\"}",
" objective=${objective:-\"N/A\"}",
" fi",
" ",
" row_data=\"$row_data,$steps,$objective,$status\"",
" done",
" else",
" # Single run: log single run data",
" local steps=\"0\"",
" local objective=\"N/A\"",
" local status=\"STOPPED\"",
" ",
" if pgrep -f \"mcsqs\" > /dev/null; then",
" status=\"RUNNING\"",
" fi",
" ",
" if [ -f \"mcsqs.log\" ]; then",
" steps=$(extract_latest_step \"mcsqs.log\")",
" objective=$(extract_latest_objective \"mcsqs.log\")",
" steps=${steps:-\"0\"}",
" objective=${objective:-\"N/A\"}",
" fi",
" ",
" row_data=\"$elapsed_minutes,$current_time,$steps,$objective,$status\"",
" fi",
" ",
" echo \"$row_data\" >> \"$csv_file\"",
"}",
"",
"convert_bestsqs_to_poscar() {",
" local bestsqs_file=$1",
" local poscar_file=$2",
" local conc=$3",
" ",
" if [ ! -f \"$bestsqs_file\" ]; then",
' echo "⚠️ Warning: $bestsqs_file not found"',
" return 1",
" fi",
" ",
' echo "🔄 Converting $bestsqs_file to $poscar_file..."',
" ",
" python3 << EOF",
"import sys",
"import numpy as np",
"try:",
" def parse_bestsqs(filename):",
" with open(filename, 'r') as f:",
" lines = f.readlines()",
" ",
" A = np.array([[float(x) for x in lines[i].split()] for i in range(3)])",
" B = np.array([[float(x) for x in lines[i].split()] for i in range(3, 6)])",
" ",
f" A_scaled = A * {max_param:.6f}",
" final_lattice = np.dot(B, A_scaled)",
" ",
" atoms = []",
" atoms = []",
" for i in range(6, len(lines)):",
" line = lines[i].strip()",
" if line:",
" parts = line.split()",
" if len(parts) >= 4:",
" x, y, z, element = float(parts[0]), float(parts[1]), float(parts[2]), parts[3]",
" if element.lower() in ['vac', \"'vac\", 'vacancy', 'x']:",
" continue",
" cart_pos = np.dot([x, y, z], A_scaled)",
" atoms.append((element, cart_pos))",
" ",
" return final_lattice, atoms",
"",
" def write_poscar(lattice, atoms, filename, comment):",
" from collections import defaultdict",
" element_groups = defaultdict(list)",
" for element, pos in atoms:",
" element_groups[element].append(pos)",
" ",
" elements = sorted(element_groups.keys())",
" ",
" with open(filename, 'w') as f:",
" f.write(f'{comment}\\n')",
" f.write('1.0\\n')",
" ",
" for vec in lattice:",
" f.write(f' {vec[0]:15.9f} {vec[1]:15.9f} {vec[2]:15.9f}\\n')",
" ",
" f.write(' '.join(elements) + '\\n')",
" f.write(' '.join(str(len(element_groups[el])) for el in elements) + '\\n')",
" ",
" f.write('Direct\\n')",
" inv_lattice = np.linalg.inv(lattice)",
" for element in elements:",
" for cart_pos in element_groups[element]:",
" frac_pos = np.dot(cart_pos, inv_lattice)",
" f.write(f' {frac_pos[0]:15.9f} {frac_pos[1]:15.9f} {frac_pos[2]:15.9f}\\n')",
"",
f' comment = "SQS {sweep_element}{complement_element} conc=$conc from $bestsqs_file"',
f' lattice, atoms = parse_bestsqs("$bestsqs_file")',
f' write_poscar(lattice, atoms, "$poscar_file", comment)',
f' print(f"Successfully converted $bestsqs_file to $poscar_file")',
"except Exception as e:",
' print(f"Python script failed with error: {e}")',
" import traceback",
" traceback.print_exc()",
" sys.exit(1)",
"EOF",
" ",
" local python_exit_code=$?",
" return $python_exit_code",
"}",
"",
"monitor_progress() {",
" local conc=$1",
" local parallel_runs_per_conc=$2",
" local total_time_seconds=$3",
" local csv_file=$4",
" local elapsed_seconds=0",
" ",
" while [ $elapsed_seconds -lt $total_time_seconds ]; do",
" sleep $PROGRESS_UPDATE_INTERVAL",
" elapsed_seconds=$((elapsed_seconds + PROGRESS_UPDATE_INTERVAL))",
" ",
" local current_time=$(date +%s)",
" local global_elapsed=$((current_time - GLOBAL_START_TIME))",
" local conc_elapsed=$((current_time - CONC_START_TIMES[$conc]))",
" local elapsed_minutes=$((conc_elapsed / 60))",
" ",
" local result=$(get_best_objective_and_run $parallel_runs_per_conc)",
" local best_obj=$(echo $result | cut -d',' -f1)",
" local best_run=$(echo $result | cut -d',' -f2)",
" ",
" CONC_BEST_SCORES[$conc]=\"$best_obj\"",
" CONC_BEST_RUNS[$conc]=\"$best_run\"",
" ",
" log_to_csv \"$csv_file\" \"$conc\" \"$parallel_runs_per_conc\" \"$elapsed_minutes\"",
" ",
" local global_time_str=$(format_elapsed_time $global_elapsed)",
" local conc_time_str=$(format_elapsed_time $conc_elapsed)",
" ",
" if [ \"$best_run\" != \"N/A\" ] && [ $parallel_runs_per_conc -gt 1 ]; then",
" printf \"[Conc %s] [%s] Global: %s | Conc %s: %s (sec %d/%d) | Best obj: %s (run %s)\\n\" \\",
" \"$conc\" \"$(date +'%H:%M:%S')\" \"$global_time_str\" \"$conc\" \"$conc_time_str\" \\",
" \"$elapsed_seconds\" \"$total_time_seconds\" \"$best_obj\" \"$best_run\"",
" else",
" printf \"[Conc %s] [%s] Global: %s | Conc %s: %s (sec %d/%d) | Best obj: %s\\n\" \\",
" \"$conc\" \"$(date +'%H:%M:%S')\" \"$global_time_str\" \"$conc\" \"$conc_time_str\" \\",
" \"$elapsed_seconds\" \"$total_time_seconds\" \"$best_obj\"",
" fi",
" done",
"}",
"",
"run_concentration() {",
" local conc=$1",
" local current_run=$2",
" local total_runs=$3",
f' local sweep_atoms=$(printf "%.0f" $(echo "$conc * {total_sites}" | bc))',
f' local comp_atoms=$(echo "{total_sites} - $sweep_atoms" | bc)',
' local folder="conc_${SWEEP_ELEMENT}_${conc}"',
' local comp_conc=$(echo "1.0 - $conc" | bc -l)',
" ",
" local time_per_conc_current=$TIME_PER_CONC_DEFAULT",
" local parallel_runs_per_conc_current=$PARALLEL_RUNS_PER_CONC_DEFAULT",
" ",
" if [ \"$sweep_atoms\" -le 1 ] || [ \"$comp_atoms\" -le 1 ]; then",
" time_per_conc_current=0.1",
" parallel_runs_per_conc_current=1",
' echo ""',
' echo "ℹ️ Note: Single atom detected. Reducing time to $time_per_conc_current min and parallel runs to $parallel_runs_per_conc_current."',
" fi",
" ",
" local total_time_seconds_current=$(echo \"$time_per_conc_current * 60\" | bc | xargs printf \"%.0f\")",
" ",
" CONC_START_TIMES[$conc]=$(date +%s)",
" ",
' echo ""',
' echo "=========================================="',
' echo "($current_run/$total_runs) 🔬 Starting concentration $conc for $SWEEP_ELEMENT"',
' ' 'echo "🔢 Target atoms: $sweep_atoms $SWEEP_ELEMENT + $comp_atoms $COMPLEMENT_ELEMENT"',
' echo "🏃 Running $parallel_runs_per_conc_current parallel instances for $time_per_conc_current minutes"',
' echo "=========================================="',
' mkdir -p "$folder"',
' cd "$folder"',
" ",
" local csv_file=$(initialize_concentration_csv \"$conc\" \"$parallel_runs_per_conc_current\")",
' echo "📊 CSV logging initialized: $csv_file"',
" ",
" cat > rndstr.in << EOF",
f"{original_lattice.a / max_param:.6f} {original_lattice.b / max_param:.6f} {original_lattice.c / max_param:.6f} {original_lattice.alpha:.2f} {original_lattice.beta:.2f} {original_lattice.gamma:.2f}",
"1 0 0",
"0 1 0",
"0 0 1"
]
for i, site in enumerate(primitive_structure):
coord_str = f"{site.frac_coords[0]:.6f} {site.frac_coords[1]:.6f} {site.frac_coords[2]:.6f}"
if chemical_symbols is None:
script_lines.append(f"{coord_str} ${{SWEEP_ELEMENT}}=$conc,${{COMPLEMENT_ELEMENT}}=$comp_conc")
else:
site_elements = chemical_symbols[i]
if isinstance(site_elements, list) and len(site_elements) > 1:
if set(site_elements) == {sweep_element, complement_element}:
script_lines.append(f"{coord_str} ${{SWEEP_ELEMENT}}=$conc,${{COMPLEMENT_ELEMENT}}=$comp_conc")
else:
fixed_conc_str = None
if isinstance(target_concentrations, dict):
first_val = next(iter(target_concentrations.values()), None)
if isinstance(first_val, dict):
for sublat_letter, concs in target_concentrations.items():
if isinstance(concs, dict) and set(concs.keys()) == set(site_elements):
conc_parts = [f"{el}={concs[el]:.6f}" for el in sorted(concs.keys()) if
concs[el] > 1e-6]
fixed_conc_str = ','.join(conc_parts)
break
if fixed_conc_str:
script_lines.append(f"{coord_str} {fixed_conc_str}")
else:
script_lines.append(f"{coord_str} {','.join(sorted(site_elements))}")
else:
element = site_elements[0] if isinstance(site_elements, list) else str(site.specie)
script_lines.append(f"{coord_str} {element}")
script_lines.extend([
"EOF",
"",
" cat > sqscell.out << EOF",
f"1",
f"",
f"{transformation_matrix[0][0]} {transformation_matrix[0][1]} {transformation_matrix[0][2]}",
f"{transformation_matrix[1][0]} {transformation_matrix[1][1]} {transformation_matrix[1][2]}",
f"{transformation_matrix[2][0]} {transformation_matrix[2][1]} {transformation_matrix[2][2]}",
"EOF",
"",
' echo "✨ Generating clusters with corrdump..."',
" eval $CORRDUMP_CMD",
" if [ $? -ne 0 ]; then",
' echo "❌ ERROR: corrdump failed for concentration $conc"',
" cd ..",
" return 1",
" fi",
"",
' echo "✨ Starting $parallel_runs_per_conc_current parallel mcsqs instances..."',
" ",
" local pids=()",
" if [ $parallel_runs_per_conc_current -gt 1 ]; then",
' for ((i=1; i<=parallel_runs_per_conc_current; i++)); do',
' timeout ${total_time_seconds_current}s $MCSQS_BASE_CMD -ip=$i > mcsqs$i.log 2>&1 || true &',
" pids+=($!)",
' echo " ✅ Started mcsqs run $i for concentration $conc (PID: $!)"',
" done",
" else",
' timeout ${total_time_seconds_current}s $MCSQS_BASE_CMD > mcsqs.log 2>&1 || true &',
" pids+=($!)",
' echo " ✅ Started single mcsqs run for concentration $conc (PID: $!)"',
" fi",
" ",
" monitor_progress $conc $parallel_runs_per_conc_current $total_time_seconds_current \"$csv_file\" &",
" local monitor_pid=$!",
" ",
" for pid in \"${pids[@]}\"; do",
" wait $pid || true",
" done",
" ",
" kill $monitor_pid 2>/dev/null || true",
" wait $monitor_pid 2>/dev/null || true",
" ",
" local final_elapsed_minutes=$(echo \"scale=1; $time_per_conc_current\" | bc)",
" log_to_csv \"$csv_file\" \"$conc\" \"$parallel_runs_per_conc_current\" \"$final_elapsed_minutes\"",
' echo "📊 Final optimization data logged to $csv_file"',
" ",
' echo ""',
' echo "=========================================="',
' echo "📄 Processing results and converting to POSCAR format for concentration $conc..."',
' echo "=========================================="',
" ",
" declare -a successful_runs",
" declare -a run_scores",
" ",
" if [ $parallel_runs_per_conc_current -gt 1 ]; then",
" for ((i=1; i<=parallel_runs_per_conc_current; i++)); do",
" if [ -f \"bestsqs$i.out\" ]; then",
' local score=$(extract_latest_objective "mcsqs$i.log")',
" if [ -n \"$score\" ] && [ \"$score\" != \"N/A\" ] && [ \"$score\" != \"\" ]; then",
" successful_runs+=($i)",
' run_scores+=("$score")',
" fi",
" fi",
" done",
" else",
" if [ -f \"bestsqs.out\" ]; then",
' local score=$(extract_latest_objective "mcsqs.log")',
" if [ -n \"$score\" ] && [ \"$score\" != \"N/A\" ] && [ \"$score\" != \"\" ]; then",
" successful_runs+=(1)",
' run_scores+=("$score")',
" fi",
" fi",
" fi",
" ",
" if [ ${#successful_runs[@]} -eq 0 ]; then",
' echo "❌ No successful runs for concentration $conc"',
" cd ..",
" return 1",
" fi",
" ",
'echo "Found ${#successful_runs[@]} successful runs"',
" ",
" local sorted_indices=()",
" for ((i=0; i<${#successful_runs[@]}; i++)); do",
" sorted_indices+=($i)",
" done",
" ",
" for ((i=0; i<${#sorted_indices[@]}; i++)); do",
" for ((j=i+1; j<${#sorted_indices[@]}; j++)); do",
" local idx_i=${sorted_indices[i]}",
" local idx_j=${sorted_indices[j]}",
" local score_i=${run_scores[idx_i]}",
" local score_j=${run_scores[idx_j]}",
' if awk "BEGIN {exit !($score_j < $score_i)}" 2>/dev/null; then',
" local temp=${sorted_indices[i]}",
" sorted_indices[i]=${sorted_indices[j]}",
" sorted_indices[j]=$temp",
" fi",
" done",
" done",
" ",
' echo "Converting ${#successful_runs[@]} successful runs to POSCAR format:"',
" local best_run_found=false",
" local best_poscar_filename=\"\"",
" ",
" for ((rank=0; rank<${#sorted_indices[@]}; rank++)); do",
" local idx=${sorted_indices[rank]}",
" local run_num=${successful_runs[idx]}",
" local score=${run_scores[idx]}",
" ",
" local bestsqs_filename",
" local poscar_filename",
" if [ $parallel_runs_per_conc_current -gt 1 ]; then",
" bestsqs_filename=\"bestsqs${run_num}.out\"",
" poscar_filename=\"POSCAR_$((rank + 1))\"",
" else",
" bestsqs_filename=\"bestsqs.out\"",
" poscar_filename=\"POSCAR\"",
" fi",
" ",
" if convert_bestsqs_to_poscar \"$bestsqs_filename\" \"$poscar_filename\" \"$conc\"; then",
" if [ $parallel_runs_per_conc_current -gt 1 ]; then",
' echo " ✔️ POSCAR_$((rank + 1)): Run $run_num (score: $score)"',
" else",
' echo " ✔️ POSCAR: Run 1 (score: $score)"',
" fi",
" ",
" if [ $rank -eq 0 ]; then",
" best_run_found=true",
" best_poscar_filename=\"$poscar_filename\"",
" if [ $parallel_runs_per_conc_current -gt 1 ]; then",
" cp \"POSCAR_1\" \"POSCAR\"",
' echo " 🏆 → Best result: POSCAR_1 (also saved as POSCAR)"',
" else",
' echo " 🏆 → Best result: POSCAR"',
" fi",
" fi",
" else",
" if [ $parallel_runs_per_conc_current -gt 1 ]; then",
' echo " ❌ Failed to convert run $run_num to POSCAR"',
" else",
' echo " ❌ Failed to convert single run to POSCAR"',
" fi",
" fi",
" done",
" ",
" if [ \"$best_run_found\" = true ]; then",
" local best_idx=${sorted_indices[0]}",
" local best_score=${run_scores[best_idx]}",
' echo ""',
' echo "✅ Concentration $conc completed successfully"',
' echo "✨ Best result has score: $best_score"',
" if [ $parallel_runs_per_conc_current -gt 1 ]; then",
' echo "📂 Generated ${#successful_runs[@]} POSCAR files (POSCAR_1 to POSCAR_${#successful_runs[@]})"',
" else",
' echo "📂 Generated POSCAR file"',
" fi",
" ",
' local file_prefix="$2"',
' cp "POSCAR" "../best_poscars/${file_prefix}_POSCAR-${conc}"',
' echo "📁 Copied best POSCAR to ../best_poscars/${file_prefix}_POSCAR-${conc}"',
" ",
" else",
' echo "❌ Failed to convert any results for concentration $conc"',
" fi",
" ",
" cd ..",
"}",
"",
"export -f run_concentration",
"export -f monitor_progress",
"export -f format_elapsed_time",
"export -f get_best_objective_and_run",
"export -f convert_bestsqs_to_poscar",
"export -f extract_latest_objective",
"export -f extract_latest_objective",
"export -f extract_latest_step",
"export -f initialize_concentration_csv",
"export -f log_to_csv",
"",
"concentrations=("
])
for conc in selected_concentrations:
script_lines.append(f" {conc}")
script_lines.extend([
")",
"",
'echo "Will process ${#concentrations[@]} concentrations with a default of $PARALLEL_RUNS_PER_CONC_DEFAULT parallel runs each"',
'echo "Total estimated time: $(echo "${#concentrations[@]} * $TIME_PER_CONC_DEFAULT" | bc -l | xargs printf "%.1f") minutes"',
'echo "Maximum concurrent jobs: $MAX_PARALLEL"',
'echo ""',
"",
"total_concentrations=${#concentrations[@]}",
'for ((i=0; i<total_concentrations; i++)); do',
" while [ $(jobs -r | wc -l) -ge $MAX_PARALLEL ]; do",
" sleep 5",
" done",
" ",
' run_concentration "${concentrations[i]}" "$((i+1))" "$total_concentrations" &',
"done",
"",
"wait",
"",
'pkill -9 -f "mcsqs" 2>/dev/null || true',
'sleep 2',
"",
'echo ""',
'echo "========================================"',
'echo "🏁 All concentrations completed!"',
'echo "========================================"',
"",
'echo "📋 Summary of generated files:"',
'echo "- 📁 Each concentration folder contains POSCAR_1, POSCAR_2, etc. (ordered by objective function)"',
'echo "- 📁 A copy of each best POSCAR is saved in the best_poscars folder"',
"",
'echo "✅ Concentration sweep completed successfully!"'
])
return '\n'.join(script_lines)
def calculate_first_six_nn_atat_aware(structure, chem_symbols=None, use_sublattice_mode=False):
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
original_lattice = structure.lattice
a, b, c = original_lattice.abc
max_param = max(a, b, c)
from pymatgen.core.lattice import Lattice
normalized_lattice = Lattice.from_parameters(
a / max_param, b / max_param, c / max_param,
original_lattice.alpha, original_lattice.beta, original_lattice.gamma
)
normalized_structure = structure.copy()
normalized_structure.lattice = normalized_lattice
sga = SpacegroupAnalyzer(normalized_structure)
wyckoff_symbols = sga.get_symmetry_dataset().wyckoffs
active_sites = []
if use_sublattice_mode and chem_symbols:
mixed_occupancy_sites = []
for i, site_elements in enumerate(chem_symbols):
if len(site_elements) >= 2:
mixed_occupancy_sites.append(i)
if not mixed_occupancy_sites:
return {
'overall': [],
'message': "No mixed-occupancy sites found. ATAT requires at least 2 elements per site for cluster calculations."
}
wyckoff_to_sites = {}
for i, wyckoff_symbol in enumerate(wyckoff_symbols):
if wyckoff_symbol not in wyckoff_to_sites:
wyckoff_to_sites[wyckoff_symbol] = []
wyckoff_to_sites[wyckoff_symbol].append(i)
wyckoff_positions_processed = set()
for site_idx in mixed_occupancy_sites:
wyckoff_symbol = wyckoff_symbols[site_idx]
if wyckoff_symbol not in wyckoff_positions_processed:
sites_with_same_wyckoff = wyckoff_to_sites[wyckoff_symbol]
mixed_sites_with_same_wyckoff = []
for equiv_site in sites_with_same_wyckoff:
if equiv_site in mixed_occupancy_sites:
mixed_sites_with_same_wyckoff.append(equiv_site)
for equiv_site in mixed_sites_with_same_wyckoff:
if equiv_site not in active_sites:
active_sites.append(equiv_site)
wyckoff_positions_processed.add(wyckoff_symbol)
if not active_sites:
return {
'overall': [],
'message': "No active sites found after Wyckoff analysis."
}
else:
active_sites = list(range(len(normalized_structure.sites)))
for i, site_idx in enumerate(active_sites):
site = normalized_structure[site_idx]
active_lattice = normalized_structure.lattice
active_species = []
active_coords = []
for site_idx in active_sites:
site = normalized_structure[site_idx]
active_species.append(site.specie)
active_coords.append(site.frac_coords)
if not active_species:
return {'overall': [], 'message': "No active sites found."}
from pymatgen.core import Structure
active_structure = Structure(
lattice=active_lattice,
species=active_species,
coords=active_coords,
coords_are_cartesian=False
)
active_supercell = active_structure * (5, 5, 5)
original_active_sites = len(active_structure)
center_cell_start = 62 * original_active_sites
center_cell_end = center_cell_start + original_active_sites
overall_distances = []
for i in range(center_cell_start, center_cell_end):
center_site = active_supercell[i]
for j, target_site in enumerate(active_supercell):
if i == j:
continue
distance = center_site.distance(target_site)
if distance > 0.001:
overall_distances.append(distance)
original_distances = overall_distances.copy()
base_distances = []