forked from AMaRaNTA-code/AMaRaNTA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkchain_AmarantaTemplate_18dec_debugged.py
More file actions
executable file
·2124 lines (1616 loc) · 81 KB
/
Copy pathWorkchain_AmarantaTemplate_18dec_debugged.py
File metadata and controls
executable file
·2124 lines (1616 loc) · 81 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 sys, math
import numpy as np
import subprocess
from aiida.orm import StructureData, Code, Str, Float, Int, Dict, List, KpointsData
from aiida.common.extendeddicts import AttributeDict
from aiida.plugins import WorkflowFactory, DataFactory
from aiida.engine import calcfunction, WorkChain, ToContext, append_, submit, while_, if_
from aiida_vasp.utils.workchains import prepare_process_inputs
from ase.build import make_supercell, sort
from ase.io import read, write
SingleFileData = DataFactory('core.singlefile')
FolderData = DataFactory('core.folder')
class AmarantaWorkChain(WorkChain):
_next_workchain_string = 'vasp.vasp'
_next_workchain = WorkflowFactory(_next_workchain_string)
@classmethod
def define(cls, spec):
super(AmarantaWorkChain, cls).define(spec)
spec.expose_inputs(cls._next_workchain, exclude=['parameters','kpoints','settings'])
spec.expose_inputs(SubWorkChain, exclude=['structure_sub','kpoints_sub','magmom_sub','magatom_sub','spin_sub','which_incar','which_label'])
spec.output('supercell_1NN', valid_type=StructureData, help='Minimal supercell 1NN')
spec.output('supercell_2NN', valid_type=StructureData, help='Minimal supercell 2NN')
spec.output('supercell_3NN', valid_type=StructureData, help='Minimal supercell 3NN')
spec.output('couples', valid_type=Dict, help='couples')
spec.output('kmesh_1NN', valid_type=KpointsData, help='K-mesh 1NN')
spec.output('kmesh_2NN', valid_type=KpointsData, help='K-mesh 2NN')
spec.output('kmesh_3NN', valid_type=KpointsData, help='K-mesh 3NN')
spec.output('spin', valid_type=Float, help='Spin modulus')
spec.output('J_dict', valid_type=Dict, help='J_dict')
spec.output('M_dict', valid_type=Dict, help='M_dict')
spec.output('units', valid_type=Dict, help='units')
spec.outline(
cls.print_welcome,
cls.run_ASE,
if_(cls.run_full_wc)(
cls.print_run_for_spin,
cls.init_aiida_for_spin,
cls.run_aiida_for_spin,
cls.elaborate_results_aiida_for_spin,
cls.print_run_main,
cls.init_main,
while_(cls.index_is_less_than_number_of_J)(
if_(cls.index_is_within_selected)(
cls.init_run_subwc,
cls.retrieve_J
),
cls.increment_index_by_one,
),
cls.finalize_dict,
cls.print_goodbye
)
)
def print_welcome(self):
str_log = '\n'
str_log += ('\n************************************************************************************')
str_log += ('\n* *')
str_log += ('\n* AMaRaNTA *')
str_log += ('\n* Automating MAgnetic paRAmeters iN a Tensorial Approach *')
str_log += ('\n* *')
str_log += ('\n************************************************************************************')
str_log += '\n'
self.report(str_log)
def run_ASE(self):
#### executes "run_ase_calculation" calcfunction in order to
#### build supercells, k-meshes and magmom sets
#### safety_distance is the parameter governing supercell size
input_structure = self.inputs.structure
safety_distance = 10
self.ctx.ase_results = run_ase_calculation(input_structure, safety_distance)
self.out("supercell_1NN", self.ctx.ase_results["final_structure_1"])
self.out("supercell_2NN", self.ctx.ase_results["final_structure_2"])
self.out("supercell_3NN", self.ctx.ase_results["final_structure_3"])
self.out("couples", self.ctx.ase_results["couples"])
self.out("kmesh_1NN", self.ctx.ase_results["kmesh_1"])
self.out("kmesh_2NN", self.ctx.ase_results["kmesh_2"])
self.out("kmesh_3NN", self.ctx.ase_results["kmesh_3"])
self.ctx.magmom_unitcell = self.ctx.ase_results["magmom_uc"]
self.ctx.n_magatoms = self.ctx.ase_results["n_magatoms"]
self.ctx.magatom = self.ctx.ase_results["magatom"]
self.report(self.ctx.ase_results["str_out"].value)
def run_full_wc(self):
#### if True, whole workchain executed
#### if False, only executes ASE step...
#### ...good for debugging, to see if workchain starts in pathological cases
return False
def print_run_for_spin(self):
str_log = '\n'
str_log += ('\n==============================================================')
str_log += ('\n PRELIMINARY RUN --- for spin modulus only ')
str_log += ('\n==============================================================')
str_log += ('\n')
self.report(str_log)
def init_aiida_for_spin(self):
self.ctx.inputs = AttributeDict()
self.ctx.inputs.update(self.exposed_inputs(self._next_workchain))
#### ENMAX and RWIGS values read from PARAMS dict; ENCUT = 1.3*max(ENMAX)
encut_list = []
rwigs_list = []
ldaul_list = [2]
ldauu_list = [2.80]
ldauj_list = [0.80]
pseudolist = dict(self.inputs.potential_mapping)
self.ctx.inputs.potential_mapping = Dict(pseudolist)
pseudolist = dict(sorted(pseudolist.items()))
#### here I have to reorder, forcing magnetic species to appear as 1st
magatom = self.ctx.magatom.value
ordered_dict = {magatom: pseudolist.get(magatom)}
for key, value in pseudolist.items():
if key != magatom:
ordered_dict[key] = value
for elem in ordered_dict.values():
RWIGS, ENMAX = PARAMS_dict[elem]
encut_list.append(ENMAX)
rwigs_list.append(RWIGS)
elist = np.array(encut_list)
rwigslist = np.array(rwigs_list)
encut = 1.3*np.max(elist)
rwigs = np.array2string(rwigslist)
rwigs = rwigs.replace("[", "").replace("]", "")
magmom_unitcell = self.ctx.magmom_unitcell
magmom_values_str = ' '.join(map(str, self.ctx.magmom_unitcell.get_dict()['magmom_uc']))
magmom_values_str = f"'{magmom_values_str}'"
magmom_values_str = magmom_values_str.replace("'", "")
#### U flags
st = self.inputs.structure.get_ase()
species = st.get_chemical_symbols()
species = set(species)
n_species = len(species)
n_eff = n_species-1
for k in range(0,n_eff):
ldaul_list.append(-1)
ldauu_list.append(0.00)
ldauj_list.append(0.00)
ldaul = np.array(ldaul_list)
ldaul = np.array2string(ldaul)
ldaul = ldaul.replace("[", "").replace("]", "")
ldauu = np.array(ldauu_list)
ldauu = np.array2string(ldauu)
ldauu = ldauu.replace("[", "").replace("]", "")
ldauj = np.array(ldauj_list)
ldauj = np.array2string(ldauj)
ldauj = ldauj.replace("[", "").replace("]", "")
incar = {'incar': {'NPAR': 4, 'KPAR': 4, 'ENCUT': encut, 'ISMEAR': 0, 'SIGMA': 0.05, 'ISYM': -1, 'EDIFF': 1E-6, 'NELM': 200, 'PREC': 'ACCURATE', 'ISTART': 0, 'ICHARG': 2, 'LWAVE': 'FALSE', 'LREAL': 'AUTO', 'IBRION': -1, 'AMIX': 0.2, 'BMIX': 0.00001, 'AMIX_MAG': 0.8, 'BMIX_MAG': 0.00001, 'ISPIN': 2, 'LNONCOLLINEAR': '.FALSE.', 'LSORBIT':'.FALSE.', 'LORBIT': 11, 'MAGMOM' : magmom_values_str, 'RWIGS': rwigs, 'LDAU' : '.TRUE.', 'LDAUTYPE': 1, 'LDAUL' : ldaul, 'LDAUU' : ldauu, 'LDAUJ' : ldauj, 'LDAUPRINT' : '0', 'LMAXMIX' : '4'}}
self.ctx.inputs.parameters = Dict(incar)
kpoints = KpointsData()
kpoints.set_kpoints_mesh([12, 12, 1])
self.ctx.inputs.kpoints = kpoints
settings = AttributeDict()
settings.parser_settings = {'output_params': ['total_energies', 'maximum_force']}
settings.parser_settings = {'add_site_magnetization':True, 'add_kpoints':True, 'add_structure':True}
self.ctx.inputs.settings = Dict(settings)
self.ctx.inputs = prepare_process_inputs(self.ctx.inputs, namespaces=['dynamics','verify'])
def run_aiida_for_spin(self):
inputs = self.ctx.inputs
running = self.submit(self._next_workchain, **inputs)
self.report('launching {}<{}> '.format(self._next_workchain.__name__, running.pk))
return self.to_context(workchains=append_(running))
def elaborate_results_aiida_for_spin(self):
workchain = self.ctx.workchains[-1]
site_magnetization = workchain.outputs.site_magnetization.get_dict()
spin = Float(round(site_magnetization['site_magnetization']['full_cell'][0]))
spin = spin/self.ctx.n_magatoms
spin.store()
self.report("SPIN = " + str(spin.value) + "\n")
self.out("spin", spin)
self.ctx.spin = spin
def print_run_main(self):
str_log = '\n'
str_log += ('\n==============================================================')
str_log += ('\n MAIN RUN --- compute J parameters ')
str_log += ('\n==============================================================')
str_log += '\n'
self.report(str_log)
def init_main(self):
#### self.ctx.selected_indices controls how many elements (and which) are calculated
#### self.ctx.index not to be touched
self.ctx.index = 0
#### run all
self.ctx.selected_indices = [i for i in range(12)]
#### run only selected
#self.ctx.selected_indices = [9]
#### order:
#### 0 = "J_xx"
#### 1 = "J_yy"
#### 2 = "J_zz"
#### 3 = "J_xy"
#### 4 = "J_yx"
#### 5 = "J_yz"
#### 6 = "J_zy"
#### 7 = "J_xz"
#### 8 = "J_zx"
#### 9 = "J_scalar_2NN"
#### 10 = "J_scalar_3NN"
#### 11 = "A_scalar"
self.ctx.J_dict = {}
self.ctx.M_dict = {}
def index_is_less_than_number_of_J(self):
return self.ctx.index < 12
def index_is_within_selected(self):
return self.ctx.index in self.ctx.selected_indices
def increment_index_by_one(self):
self.ctx.index += 1
def init_run_subwc(self):
self.ctx.inputs = AttributeDict()
self.ctx.inputs.update(self.exposed_inputs(SubWorkChain))
#### depending of which calculation is run (J1, J2, J3, SIA)
#### provide correct POSCAR, KPOINTS, INCAR (collinear or not)
if self.ctx.index <= 8:
self.ctx.inputs.structure_sub = self.ctx.ase_results["final_structure_1"]
self.ctx.inputs.kpoints_sub = self.ctx.ase_results["kmesh_1"]
self.ctx.inputs.which_incar = Int(2)
elif self.ctx.index == 9:
self.ctx.inputs.structure_sub = self.ctx.ase_results["final_structure_2"]
self.ctx.inputs.kpoints_sub = self.ctx.ase_results["kmesh_2"]
self.ctx.inputs.which_incar = Int(1)
elif self.ctx.index == 10:
self.ctx.inputs.structure_sub = self.ctx.ase_results["final_structure_3"]
self.ctx.inputs.kpoints_sub = self.ctx.ase_results["kmesh_3"]
self.ctx.inputs.which_incar = Int(1)
elif self.ctx.index > 10:
self.ctx.inputs.structure_sub = self.ctx.ase_results["final_structure_1"]
self.ctx.inputs.kpoints_sub = self.ctx.ase_results["kmesh_1"]
self.ctx.inputs.which_incar = Int(2)
#### this specifies in which order parameters are computed
#### do not touch!!! use method "init_main" if you want to
#### compute specific parameters only
keys = ["J_xx", "J_yy", "J_zz", "J_xy", "J_yx", "J_yz", "J_zy", "J_xz", "J_zx", "J_scalar_2NN", "J_scalar_3NN", "A_scalar"]
selected_key = keys[self.ctx.index]
self.ctx.selected_key = selected_key
self.ctx.inputs.magmom_sub = List(self.ctx.ase_results["magmom_all"][selected_key])
self.ctx.inputs.magatom_sub = self.ctx.magatom
self.ctx.inputs.which_label = Str(selected_key)
self.ctx.inputs.spin_sub = self.ctx.spin
#### if you want to speed things up and skip the computation of spin
#### (for instance because you already know its value...)
#### use this line below instead, but do remember you are using it!!!!
#self.ctx.inputs.spin_sub = Float(2.0)
self.report('\n \n==============================================================' + "\nindex: " + str(self.ctx.index) + " parameter to compute: " + str(selected_key) + '\n==============================================================\n')
inputs = self.ctx.inputs
running = self.submit(SubWorkChain, **inputs)
self.to_context(**{'test': running})
return ToContext(child = running)
def retrieve_J(self):
J = self.ctx.child.outputs.J_parameter
self.ctx.J_dict[self.ctx.selected_key] = J
M = self.ctx.child.outputs.magnetizations
self.ctx.M_dict[self.ctx.selected_key] = M
def finalize_dict(self):
J_dict_final = Dict(self.ctx.J_dict)
J_dict_final.store()
self.out("J_dict", J_dict_final)
M_dict_final = Dict(self.ctx.M_dict)
M_dict_final.store()
self.out("M_dict", M_dict_final)
units_dict = Dict(dict(distances = "Angstrom", J_parameters = "meV (not divided by S^2)", magnetizations = "Bohr magneton", coordinates = "cartesian, Angstrom"))
units_dict.store()
self.out("units", units_dict)
def print_goodbye(self):
str_log = '\n'
str_log += ('\n==============================================================')
str_log += ('\n Job done ')
str_log += ('\n==============================================================')
str_log += '\n'
self.report(str_log)
class SubWorkChain(WorkChain):
_next_workchain_string = 'vasp.vasp'
_next_workchain = WorkflowFactory(_next_workchain_string)
@classmethod
def define(cls, spec):
super(SubWorkChain, cls).define(spec)
spec.expose_inputs(cls._next_workchain, exclude=['structure','parameters','kpoints','settings'])
spec.input('structure_sub',valid_type=StructureData, help='Minimal supercell')
spec.input('kpoints_sub',valid_type=KpointsData, help='K points')
spec.input('magmom_sub',valid_type=List, help='magmom')
spec.input('magatom_sub',valid_type=Str, help='magatom')
spec.input('spin_sub',valid_type=Float, help='spin')
spec.input('which_incar',valid_type=Int, help='which incar')
spec.input('which_label',valid_type=Str, help='which label')
spec.output('J_parameter', valid_type=Float, help='J_parameter')
spec.output('magnetizations', valid_type=List, help='magnetizations')
spec.output('txtfile',valid_type=SingleFileData, help='txtfile')
spec.outline(
cls.initialize,
while_(cls.n_is_less_than_four)(
cls.init_run_aiida_main,
cls.elaborate_results_main,
cls.increment_n_by_one
),
cls.finalize
)
def initialize(self):
self.ctx.n = 0
self.ctx.total_energies = []
self.ctx.magnetizations = []
def n_is_less_than_four(self):
return self.ctx.n < 4
def increment_n_by_one(self):
self.ctx.n += 1
def init_run_aiida_main(self):
self.ctx.inputs = AttributeDict()
self.ctx.inputs.update(self.exposed_inputs(self._next_workchain))
self.ctx.inputs.structure = self.inputs.structure_sub
self.ctx.inputs.kpoints = self.inputs.kpoints_sub
incar_flag = int(self.inputs.which_incar)
magmom_sub = self.inputs.magmom_sub
S = float(self.inputs.spin_sub)
encut_list = []
rwigs_list = []
ldaul_list = [2]
ldauu_list = [2.80]
ldauj_list = [0.80]
pseudolist = dict(self.inputs.potential_mapping)
self.ctx.inputs.potential_mapping = Dict(pseudolist)
pseudolist = dict(sorted(pseudolist.items()))
#### here I have to reorder, forcing magnetic species to appear as 1st
magatom = self.inputs.magatom_sub.value
ordered_dict = {magatom: pseudolist.get(magatom)}
for key, value in pseudolist.items():
if key != magatom:
ordered_dict[key] = value
for elem in ordered_dict.values():
RWIGS, ENMAX = PARAMS_dict[elem]
encut_list.append(ENMAX)
rwigs_list.append(RWIGS)
elist = np.array(encut_list)
rwigslist = np.array(rwigs_list)
encut = 1.3*np.max(elist)
rwigs = np.array2string(rwigslist)
rwigs = rwigs.replace("[", "").replace("]", "")
settings = AttributeDict()
settings.parser_settings = {'output_params': ['total_energies', 'maximum_force']}
settings.parser_settings = {'add_site_magnetization':True, 'add_kpoints':True, 'add_structure':True}
self.ctx.inputs.settings = Dict(settings)
i = self.ctx.n
rescaled_magmom = [[value * S for value in sub_array] for sub_array in magmom_sub]
magmom_values_str = str(rescaled_magmom[i]).replace("[", "").replace("]", "").replace(",", "")
#### U flags
st = self.ctx.inputs.structure.get_ase()
species = st.get_chemical_symbols()
species = set(species)
n_species = len(species)
n_eff = n_species-1
for k in range(0,n_eff):
ldaul_list.append(-1)
ldauu_list.append(0.00)
ldauj_list.append(0.00)
ldaul = np.array(ldaul_list)
ldaul = np.array2string(ldaul)
ldaul = ldaul.replace("[", "").replace("]", "")
ldauu = np.array(ldauu_list)
ldauu = np.array2string(ldauu)
ldauu = ldauu.replace("[", "").replace("]", "")
ldauj = np.array(ldauj_list)
ldauj = np.array2string(ldauj)
ldauj = ldauj.replace("[", "").replace("]", "")
self.report("\nMAGMOM " +str(magmom_values_str))
INCAR_COLL = {'incar': {'NPAR': 8, 'KPAR': 4, 'ENCUT': encut, 'ISMEAR': 0, 'SIGMA': 0.05, 'ISYM': -1, 'EDIFF': 1E-6, 'NELM': 200, 'PREC': 'ACCURATE', 'ISTART': 0, 'ICHARG': 2, 'LWAVE': 'FALSE', 'LCHARG' : 'FALSE', 'LREAL': 'AUTO', 'AMIX': 0.1, 'BMIX': 0.00001, 'ISPIN': 2, 'LNONCOLLINEAR': '.FALSE.', 'LSORBIT':'.FALSE.', 'LORBIT': 11, 'MAGMOM' : magmom_values_str, 'RWIGS': rwigs, 'LDAU' : '.TRUE.', 'LDAUTYPE': 1, 'LDAUL' : ldaul, 'LDAUU' : ldauu, 'LDAUJ' : ldauj, 'LDAUPRINT' : '0', 'LMAXMIX' : '4' }}
INCAR_NONCOLL = {'incar': {'NPAR': 8, 'KPAR': 4, 'ENCUT': encut, 'ISMEAR': 0, 'SIGMA': 0.05, 'ISYM': -1, 'EDIFF': 1E-6, 'NELM': 200, 'PREC': 'ACCURATE', 'ISTART': 0, 'ICHARG': 2, 'LWAVE': 'FALSE', 'LCHARG' : 'FALSE', 'LREAL': 'AUTO', 'AMIX': 0.1, 'BMIX': 0.00001, 'ISPIN': 2, 'LNONCOLLINEAR': '.TRUE.', 'LSORBIT':'.TRUE.', 'LORBIT': 11, 'MAGMOM' : magmom_values_str, 'M_CONSTR' : magmom_values_str, 'I_CONSTRAINED_M' : 1, 'LAMBDA': 10, 'RWIGS': rwigs, 'SAXIS' : '0.0000 0.0000 1.0000', 'LDAU' : '.TRUE.', 'LDAUTYPE': 1, 'LDAUL' : ldaul, 'LDAUU' : ldauu, 'LDAUJ' : ldauj, 'LDAUPRINT' : '0', 'LMAXMIX' : '4' }}
if incar_flag == 1:
self.ctx.inputs.parameters = Dict(INCAR_COLL)
else:
self.ctx.inputs.parameters = Dict(INCAR_NONCOLL)
self.ctx.inputs = prepare_process_inputs(self.ctx.inputs, namespaces=['dynamics','verify'])
inputs = self.ctx.inputs
running = self.submit(self._next_workchain, **inputs)
self.to_context(workchains=append_(running))
workchain = self.ctx.workchains[-1]
def elaborate_results_main(self):
workchain = self.ctx.workchains[-1]
misc = workchain.outputs.misc.get_dict()
total_energy = Float(misc['total_energies']['energy_extrapolated'])
total_energy.store()
self.ctx.total_energies.append(total_energy)
self.report("ENERGY: " + str(total_energy.value) + " eV \n \n")
site_mag = workchain.outputs.site_magnetization.get_dict()
mags = site_mag['site_magnetization']['sphere']
ase_struct = self.ctx.inputs.structure.get_ase()
atom_species_dict = {(atom.index+1): atom.symbol for atom in ase_struct}
for key in ['x', 'y', 'z']:
for atom_number, atom_data in mags[key]['site_moment'].items():
atom_data['species'] = atom_species_dict[int(atom_number)]
self.ctx.magnetizations.append(mags)
def finalize(self):
total_energies = self.ctx.total_energies
J_parameter = find_energy_four_state(total_energies)
label = self.inputs.which_label
self.report(str(label.value) + ": " + str(J_parameter.value) + " meV \n \n")
J_parameter.store()
self.out('J_parameter', J_parameter)
magnetizations = self.ctx.magnetizations
magnetizations = List(magnetizations)
magnetizations.store()
self.out('magnetizations',magnetizations)
incar_flag = int(self.inputs.which_incar)
if incar_flag == 1:
coll = True
else:
coll = False
filename = Str('/home/federico/Amaranta_txt_files/' + label.value + '.txt')
save_info(total_energies, J_parameter, magnetizations, filename, coll)
file = create_singlefile(filename)
self.out('txtfile', file)
this_struct = self.inputs.structure_sub.get_ase()
chem_symb = this_struct.get_chemical_symbols()
N_magatoms = Int(sum(1 for symbol in chem_symb if symbol == self.inputs.magatom_sub.value))
printed_info = print_info(N_magatoms, total_energies, J_parameter, magnetizations, coll)
self.report(printed_info.value)
@calcfunction
def find_energy_four_state(list_of_energies):
#### implements 4-state formula
energy = 1000*(list_of_energies[0]-list_of_energies[1]-list_of_energies[2]+list_of_energies[3])/4
return Float(energy)
@calcfunction
def save_info(total_energies,J_parameter,magnetization_results, filename, coll):
filename = str(filename.value)
with open(filename, 'w') as f:
f.write(f"ENERGIES \n")
for item in total_energies:
f.write(str(item) + "\n")
f.write("\n")
J_parameter = float(J_parameter)
f.write(f"J PARAMETER = {J_parameter} \n")
f.write("\n \n \n \n")
if bool(coll) == False:
count_state = 1
for direction_data in magnetization_results: #loops over each of 4 dicts in list
f.write(f"STATE {count_state} \n")
f.write('========================================== \n')
for direction, data in direction_data.items(): #loops over x,y,z
f.write(f" magnetization ({direction})\n")
f.write("# of ion s p d tot\n")
f.write("------------------------------------------\n")
# Iterate over site-wise moment data
for site, moment_data in data["site_moment"].items():
s, p, d, tot = moment_data["s"], moment_data["p"], moment_data["d"], moment_data["tot"]
f.write(f"{site:<13}{s:<8}{p:<8}{d:<8}{tot:<8}\n")
f.write("------------------------------------------\n")
f.write(f"\n \n \n")
count_state += 1
else:
count_state = 1
for direction_data in magnetization_results: #loops over each of 4 dicts in list
f.write(f"STATE {count_state} \n")
f.write('========================================== \n')
f.write(f" magnetization (x)\n")
f.write("# of ion s p d tot\n")
f.write("------------------------------------------\n")
# Iterate over site-wise moment data
for site, moment_data in direction_data["x"]["site_moment"].items():
s, p, d, tot = moment_data["s"], moment_data["p"], moment_data["d"], moment_data["tot"]
f.write(f"{site:<13}{s:<8}{p:<8}{d:<8}{tot:<8}\n")
f.write("------------------------------------------\n")
f.write(f"\n \n \n")
count_state += 1
@calcfunction
def create_singlefile(filename):
path = str(filename.value)
singlefile = SingleFileData(path)
return singlefile
@calcfunction
def print_info(N_magatoms,total_energies,J_parameter,magnetization_results, coll):
str_out = '\n \n'
if bool(coll) == False:
count_state = 1
for data in magnetization_results: #loops over each of 4 dicts in list
str_out += (f"STATE {count_state}" + "\n")
str_out += ('===========================================\n')
str_out += ("Atom M Mx/M My/M Mz/M\n")
for atom_num, atom_data in data['x']['site_moment'].items():
if int(atom_num) <= N_magatoms:
Mx = data['x']['site_moment'][atom_num]['tot']
My = data['y']['site_moment'][atom_num]['tot']
Mz = data['z']['site_moment'][atom_num]['tot']
M = math.sqrt(Mx**2+My**2+Mz**2)
str_out += (f"{atom_num:<13}{round(M,3):<9}{round(Mx/M,3):<8}{round(My/M,3):<8}{round(Mz/M,3):<8}\n")
else:
Mx = data['x']['site_moment'][atom_num]['tot']
My = data['y']['site_moment'][atom_num]['tot']
Mz = data['z']['site_moment'][atom_num]['tot']
M = math.sqrt(Mx**2+My**2+Mz**2)
if M>0.2:
str_out += (f"{atom_num:<13}{round(M,3):<9}{round(Mx/M,3):<8}{round(My/M,3):<8}{round(Mz/M,3):<8} !!!!!!!\n")
str_out += '\n'
count_state += 1
else:
count_state = 1
for data in magnetization_results: #loops over each of 4 dicts in list
str_out += (f"STATE {count_state}" + "\n")
str_out += ('==============\n')
str_out += ("Atom M\n")
for atom_num, atom_data in data['x']['site_moment'].items():
if int(atom_num) <= N_magatoms:
M = data['x']['site_moment'][atom_num]['tot']
str_out += (f"{atom_num:<13}{round(M,3):<9}\n")
else:
M = data['x']['site_moment'][atom_num]['tot']
if M>0.2:
str_out += (f"{atom_num:<13}{round(M,3):<9} !!!!!!!\n")
str_out += '\n'
count_state += 1
str_out = Str(str_out)
return str_out
@calcfunction
def run_ase_calculation(initial_structure, safety_distance):
str_out = ''
atoms = initial_structure.get_ase()
structure = sort(atoms) #in case input files is not ordered VASP-like (NB this sort orders alphabetically)
### loop over chemical symbols to identify magnetic species (from Va to Ni). Ansatz: one magnetic species only!
counter = 0
for atom in structure:
if 22 < atom.number < 29:
magatom = atom.symbol
counter += 1
break
if counter==0:
str_out += ('No magnetism found!' + '\n')
sys.exit()
n_magatoms = len(structure[[atom.index for atom in structure if atom.symbol==magatom]])
n_tot_atoms = len(structure)
str_out += '\n \n' + 'Material is ' + str(structure.symbols) + '\n'
item = np.array([])
item = np.append(item, np.ones(n_magatoms))
item = np.append(item, np.zeros(n_tot_atoms-n_magatoms))
magmom_dict_unitcell = {
"magmom_uc": item,
}
magmom_uc = Dict(magmom_dict_unitcell)
######################################### SELECTION OF PAIRS
### trick to place magnetic atoms on top: call them Ac, create supercell, sort and then call them back the right way
for atom in structure:
if atom.symbol == magatom:
atom.symbol = 'Ac'
superstructure = sort(structure.repeat([5,5,1])) #here: take this SC large enough (e.g. 4x4 not enough for small unit cells such as NiI2)
#MIC true in the following: to interpret more easily, choose odd mesh
for atom in superstructure:
if atom.symbol == 'Ac':
atom.symbol = magatom
##################### OLD WAY!!!!!!!!!!!!!!!!!! atom 0 is selected automatically as first in the couple
### atom 0 is selected automatically as the closest magnetic atom to the centre of 5x5 supercell
### get distances between that and the other magnetic atoms, identify 1st, 2nd and 3rd nn's and select first of them as partner in the couple
### distances rounded because atoms belonging to the same shell of neighbours can actually have slightly different distances wrt to atom 0 for numerical reasons
### Compute the supercell center using fractional coordinates
cell = superstructure.get_cell() # Get lattice vectors (3x3 matrix)
center_fractional = np.array([0.5, 0.5, 0.5]) # Center in fractional coordinates
supercell_center = np.dot(center_fractional, cell) # Convert to Cartesian coordinates
# Reduce center to xy-plane
supercell_center_xy = supercell_center[:2] # Take only x and y components
### Find the magnetic atom closest to the supercell center in the xy-plane
magnetic_atoms_indices = [atom.index for atom in superstructure if atom.symbol == magatom]
distances_to_center_xy = [
np.linalg.norm(superstructure[index].position[:2] - supercell_center_xy) for index in magnetic_atoms_indices
]
s0 = magnetic_atoms_indices[np.argmin(distances_to_center_xy)]
s0_position = superstructure[s0].position
#####################s0 = 0
#####################for atom in superstructure:
distances_original = superstructure.get_distances(s0,magnetic_atoms_indices,mic=True)
distances = distances_original
for i in range(len(distances)): #at first I tried to just round to 2nd digit, but this is safer, remember pathological case of CrISe...
for j in range(len(distances)):
x = distances[i]
y = distances[j]
if (abs(x-y)/(y + 0.00001)) < 0.01:
distances[j] = distances[i]
nn1_dist = np.min(distances[distances != 0])
nn1_indexes = np.flatnonzero(distances == nn1_dist)
nn1_number = len(nn1_indexes)
s1 = nn1_indexes[0]
s1_position = superstructure[s1].position
nn2_dist = np.min(distances[distances > nn1_dist])
nn2_indexes = np.flatnonzero(distances == nn2_dist)
nn2_number = len(nn2_indexes)
s2 = nn2_indexes[0]
s2_position = superstructure[s2].position
nn3_dist = np.min(distances[distances > nn2_dist])
nn3_indexes = np.flatnonzero(distances == nn3_dist)
nn3_number = len(nn3_indexes)
s3 = nn3_indexes[0]
s3_position = superstructure[s3].position
str_out += '\n'
str_out += ('--------------------------------------------------- s0 is: ' + str(np.around(s0_position,3)))
str_out += ('\n' + 'The 1nn couple is: ' + str(s0) + ',' + str(s1) + ' with distance: ' + str(round(nn1_dist,4)) + ' ---- s1 is: ' + str(np.around(s1_position,3)))
str_out += ('\n' + 'The 2nn couple is: ' + str(s0) + ',' + str(s2) + ' with distance: ' + str(round(nn2_dist,4)) + ' ---- s2 is: ' + str(np.around(s2_position,3)))
str_out += ('\n' + 'The 3nn couple is: ' + str(s0) + ',' + str(s3) + ' with distance: ' + str(round(nn3_dist,4)) + ' ---- s3 is: ' + str(np.around(s3_position,3)))
str_out += '\n'
couples_dict = {
"1NN couple": [np.around(s0_position,3), np.around(s1_position,3)],
"2NN couple": [np.around(s0_position,3), np.around(s2_position,3)],
"3NN couple": [np.around(s0_position,3), np.around(s3_position,3)],
}
couples = Dict(couples_dict)
f = open("/home/federico/Amaranta_txt_files/NN_list.txt","w")
f.write("### NN order, number, distance\n")
n1 = (1,nn1_number,round(nn1_dist,4))
n2 = (2,nn2_number,round(nn2_dist,4))
n3 = (3,nn3_number,round(nn3_dist,4))
for item in n1:
f.write(str(item)+" ")
f.write("\n")
for item in n2:
f.write(str(item)+" ")
f.write("\n")
for item in n3:
f.write(str(item)+" ")
f.write("\n")
f.close()
safe_dist = int(safety_distance) # minimum distance accepted between original pair of neighbours and replicas
str_out += ('\n'+'Safety distance chosen: ' + str(safe_dist) + ' Ang' + '\n \n')
######################################### OPTIMAL SC FOR 1st NN
for j in range(2,10):
for k in range (2,j+1):
for atom in structure:
if atom.symbol == magatom:
atom.symbol = 'Ac'
candidate_SC_nn1 = sort(structure.repeat([j,k,1]))
for atom in candidate_SC_nn1:
if atom.symbol == 'Ac':
atom.symbol = magatom
s0_found = False
s1_found = False
#for atom in candidate_SC_nn1:
#if np.allclose(atom.position, s1_position, atol=1e-6):
#s1 = atom.index
#s1_found = True
#break
for atom in candidate_SC_nn1:
if not s0_found and np.allclose(atom.position, s0_position, atol=1e-6):
s0 = atom.index
s0_found = True
elif not s1_found and np.allclose(atom.position, s1_position, atol=1e-6):
s1 = atom.index
s1_found = True
if s0_found and s1_found:
break
#very important to define dist_min = 0 here AND = 100 just after the continue statement
#if s1 not found, the continue will correctly skip rest of k-loop
#but before incrementing j, "dist_min > safe_dist" is evaluated
#and this may cause the j-loop to be aborted as well, undesirably
#if s1 is found, then dist_min must be set large enough for the rest of code in k-loop
dist_min = 0
#if not s1_found:
if not (s0_found and s1_found):
continue
super_superstructure = candidate_SC_nn1.repeat([2,2,1])
dist_min = 100
dist_min_vec = np.array([100,100,100,100])
for m in range (1,4):
s0_img = s0+m*len(candidate_SC_nn1)
s1_img = s1+m*len(candidate_SC_nn1)
d_0_0img = float(super_superstructure.get_distances(s0,s0_img))
d_0_1img = float(super_superstructure.get_distances(s0,s1_img))
d_1_0img = float(super_superstructure.get_distances(s1,s0_img))
d_1_1img = float(super_superstructure.get_distances(s1,s1_img))
dist_couple_img = np.array([d_0_0img,d_0_1img,d_1_0img,d_1_1img])
if dist_min > dist_couple_img.min():
dist_min = dist_couple_img.min()
dist_min_vec = dist_couple_img
if dist_min > safe_dist:
opt_j_nn1_direct = j
opt_k_nn1_direct = k
break
if dist_min > safe_dist:
break
s0 = None
s1 = None
for k in range(2,10):
for j in range (2,k+1):
for atom in structure:
if atom.symbol == magatom:
atom.symbol = 'Ac'
candidate_SC_nn1 = sort(structure.repeat([j,k,1]))
for atom in candidate_SC_nn1:
if atom.symbol == 'Ac':
atom.symbol = magatom
s0_found = False
s1_found = False
#for atom in candidate_SC_nn1:
#if np.allclose(atom.position, s1_position, atol=1e-6):