/
base.py
2315 lines (2070 loc) · 87.5 KB
/
base.py
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
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
from __future__ import print_function
import os
import posixpath
import subprocess
import numpy as np
from pyiron.dft.job.generic import GenericDFTJob
from pyiron.vasp.potential import VaspPotential, VaspPotentialFile, VaspPotentialSetter, Potcar
from pyiron.atomistics.structure.atoms import Atoms, CrystalStructure
from pyiron.base.settings.generic import Settings
from pyiron.base.generic.parameters import GenericParameters
from pyiron.atomistics.md_analysis.trajectory_analysis import unwrap_coordinates
from pyiron.vasp.outcar import Outcar
from pyiron.vasp.procar import Procar
from pyiron.vasp.structure import read_atoms, write_poscar, vasp_sorter
from pyiron.vasp.vasprun import Vasprun as Vr
from pyiron.vasp.vasprun import VasprunError
from pyiron.vasp.volumetric_data import VaspVolumetricData
from pyiron.vasp.potential import get_enmax_among_species
from pyiron.dft.waves.electronic import ElectronicStructure
from pyiron.dft.waves.bandstructure import Bandstructure
import warnings
__author__ = "Sudarsan Surendralal"
__copyright__ = (
"Copyright 2019, Max-Planck-Institut für Eisenforschung GmbH - "
"Computational Materials Design (CM) Department"
)
__version__ = "1.0"
__maintainer__ = "Sudarsan Surendralal"
__email__ = "surendralal@mpie.de"
__status__ = "production"
__date__ = "Sep 1, 2017"
s = Settings()
class VaspBase(GenericDFTJob):
"""
Class to setup and run and analyze VASP simulations which is a derivative of pyiron.objects.job.generic.GenericJob.
The functions in these modules are written in such the function names and attributes are very generic
(get_structure(), molecular_dynamics(), version) but the functions are written to handle VASP specific input/output.
Args:
project (pyiron.project.Project instance): Specifies the project path among other attributes
job_name (str): Name of the job
Attributes:
input (pyiron.vasp.vasp.Input): Instance which handles the input
Examples:
Let's say you need to run a vasp simulation where you would like to control the input parameters manually. To
set up a static dft run with Gaussian smearing and a k-point MP mesh of [6, 6, 6]. You would have to set it up
as shown below:
>>> ham = VaspBase(job_name="trial_job")
>>> ham.input.incar[IBRION] = -1
>>> ham.input.incar[ISMEAR] = 0
>>> ham.input.kpoints.set(size_of_mesh=[6, 6, 6])
However, the according to pyiron's philosophy, it is recommended to avoid using code specific tags like IBRION,
ISMEAR etc. Therefore the recommended way to set this calculation is as follows:
>>> ham = VaspBase(job_name="trial_job")
>>> ham.calc_static()
>>> ham.set_occupancy_smearing(smearing="gaussian")
>>> ham.set_kpoints(mesh=[6, 6, 6])
The exact same tags as in the first examples are set automatically.
"""
def __init__(self, project, job_name):
super(VaspBase, self).__init__(project, job_name)
self._sorted_indices = None
self.input = Input()
self.input.incar["SYSTEM"] = self.job_name
self._output_parser = Output()
self._potential = VaspPotentialSetter([])
self._compress_by_default = True
self.get_enmax_among_species = get_enmax_among_species
s.publication_add(self.publication)
@property
def structure(self):
"""
Returns:
"""
return GenericDFTJob.structure.fget(self)
@structure.setter
def structure(self, structure):
"""
Args:
structure:
Returns:
"""
GenericDFTJob.structure.fset(self, structure)
if structure is not None:
self._potential = VaspPotentialSetter(
element_lst=structure.get_species_symbols().tolist()
)
@property
def potential(self):
return self._potential
@property
def plane_wave_cutoff(self):
"""
Plane wave energy cutoff in eV
"""
return self.input.incar["ENCUT"]
@plane_wave_cutoff.setter
def plane_wave_cutoff(self, val):
self.input.incar["ENCUT"] = val
@property
def exchange_correlation_functional(self):
"""
The exchange correlation functional used (LDA or GGA)
"""
return self.input.potcar["xc"]
@exchange_correlation_functional.setter
def exchange_correlation_functional(self, val):
if val in ["PBE", "pbe", "GGA", "gga"]:
self.input.potcar["xc"] = "PBE"
elif val in ["LDA", "lda"]:
self.input.potcar["xc"] = "LDA"
else:
self.input.potcar["xc"] = val
@property
def spin_constraints(self):
"""
Returns True if the calculation is spin polarized
"""
if "I_CONSTRAINED_M" in self.input.incar._dataset["Parameter"]:
return (
self.input.incar["I_CONSTRAINED_M"] == 1
or self.input.incar["I_CONSTRAINED_M"] == 2
)
else:
return False
@spin_constraints.setter
def spin_constraints(self, val):
self.input.incar["I_CONSTRAINED_M"] = val
@property
def write_electrostatic_potential(self):
"""
True if the local potential or electrostatic potential LOCPOT file is/should be written
"""
return bool(self.input.incar["LVTOT"])
@write_electrostatic_potential.setter
def write_electrostatic_potential(self, val):
self.input.incar["LVTOT"] = bool(val)
if bool(val):
self.input.incar["LVHAR"] = True
@property
def write_charge_density(self):
"""
True if the charge density file CHGCAR file is/should be written
"""
return bool(self.input.incar["LCHARG"])
@write_charge_density.setter
def write_charge_density(self, val):
self.input.incar["LCHARG"] = bool(val)
@property
def write_wave_funct(self):
"""
True if the wave function file WAVECAR file is/should be written
"""
return self.input.incar["LWAVE"]
@write_wave_funct.setter
def write_wave_funct(self, write_wave):
if not isinstance(write_wave, bool):
raise ValueError("write_wave_funct, can either be True or False.")
self.input.incar["LWAVE"] = write_wave
@property
def write_resolved_dos(self):
"""
True if the resolved DOS should be written (in the vasprun.xml file)
"""
return self.input.incar["LORBIT"]
@write_resolved_dos.setter
def write_resolved_dos(self, resolved_dos):
if not isinstance(resolved_dos, bool) and not isinstance(resolved_dos, int):
raise ValueError(
"write_resolved_dos, can either be True, False or 0, 1, 2, 5, 10, 11, 12."
)
self.input.incar["LORBIT"] = resolved_dos
@property
def sorted_indices(self):
"""
How the original atom indices are ordered in the vasp format (species by species)
"""
if self._sorted_indices is None:
self._sorted_indices = vasp_sorter(self.structure)
return self._sorted_indices
@sorted_indices.setter
def sorted_indices(self, val):
"""
Setter for the sorted indices
"""
self._sorted_indices = val
@property
def fix_spin_constraint(self):
"""
bool: Tells if the type of constraints the spins have for this calculation
"""
return self.spin_constraints
@fix_spin_constraint.setter
def fix_spin_constraint(self, boolean):
raise NotImplementedError(
"The fix_spin_constraint property is not implemented for this code. "
"Instead use ham.spin_constraints - I_CONSTRAINED_M."
)
@property
def fix_symmetry(self):
if "ISYM" in self.input.incar._dataset["Parameter"]:
return (
self.input.incar["ISYM"] == 1
or self.input.incar["ISYM"] == 2
or self.input.incar["ISYM"] == 3
)
else:
return True
@fix_symmetry.setter
def fix_symmetry(self, boolean):
raise NotImplementedError(
"The fix_symmetry property is not implemented for this code. "
"Instead use ham.input.incar['ISYM']."
)
@property
def potential_available(self):
if self.structure is not None:
return VaspPotential(
selected_atoms=self.structure.get_species_symbols().tolist()
)
else:
return VaspPotential()
@property
def potential_view(self):
if self.structure is None:
raise ValueError("Can't list potentials unless a structure is set")
else:
return VaspPotentialFile(xc=self.input.potcar["xc"]).find(
self.structure.get_species_symbols().tolist()
)
@property
def potential_list(self):
if self.structure is None:
raise ValueError("Can't list potentials unless a structure is set")
else:
df = VaspPotentialFile(xc=self.input.potcar["xc"]).find(
self.structure.get_species_symbols().tolist()
)
if len(df) != 0:
return df["Name"]
else:
return []
@property
def publication(self):
return {
"vasp": {
"Kresse1993": {
"title": "Ab initio molecular dynamics for liquid metals",
"author": ["Kresse, G.", "Hafner, J."],
"journal": "Phys. Rev. B",
"volume": "47",
"issue": "1",
"pages": "558--561",
"numpages": "0",
"month": "jan",
"publisher": "American Physical Society",
"doi": "10.1103/PhysRevB.47.558",
"url": "https://link.aps.org/doi/10.1103/PhysRevB.47.558",
},
"Kresse1996a": {
"title": "Efficiency of ab-initio total energy calculations for metals and "
"semiconductors using a plane-wave basis set",
"journal": "Computational Materials Science",
"volume": "6",
"number": "1",
"pages": "15-50",
"year": "1996",
"issn": "0927-0256",
"doi": "10.1016/0927-0256(96)00008-0",
"url": "http://www.sciencedirect.com/science/article/pii/0927025696000080",
"author": ["Kresse, G.", "Furthmüller, J."],
},
"Kresse1996b": {
"title": "Efficient iterative schemes for ab initio total-energy calculations "
"using a plane-wave basis set",
"author": ["Kresse, G.", "Furthmüller, J."],
"journal": "Phys. Rev. B",
"volume": "54",
"issue": "16",
"pages": "11169--11186",
"numpages": "0",
"year": "1996",
"month": "oct",
"publisher": "American Physical Society",
"doi": "10.1103/PhysRevB.54.11169",
"url": "https://link.aps.org/doi/10.1103/PhysRevB.54.11169",
},
}
}
def set_input_to_read_only(self):
"""
This function enforces read-only mode for the input classes, but it has to be implement in the individual
classes.
"""
super(VaspBase, self).set_input_to_read_only()
self.input.incar.read_only = True
self.input.kpoints.read_only = True
self.input.potcar.read_only = True
# Compatibility functions
def write_input(self):
"""
Call routines that generate the INCAR, POTCAR, KPOINTS and POSCAR input files
"""
if self.input.incar["SYSTEM"] == "pyiron_jobname":
self.input.incar["SYSTEM"] = self.job_name
modified_elements = {
key: value
for key, value in self._potential.to_dict().items()
if value is not None
}
self.write_magmoms()
self.set_coulomb_interactions()
if "CONTCAR" in self.restart_file_dict.keys():
if self.restart_file_dict["CONTCAR"] == "POSCAR":
if self.server.run_mode.modal:
warnings.warn(
"The POSCAR file will be overwritten by the CONTCAR file specified in restart_file_list."
)
else:
self.logger.info(
"The POSCAR file will be overwritten by the CONTCAR file specified in restart_file_list."
)
self.input.write(
structure=self.structure,
directory=self.working_directory,
modified_elements=modified_elements,
)
# define routines that collect all output files
def collect_output(self):
"""
Collects the outputs and stores them to the hdf file
"""
if self.structure is None or len(self.structure) == 0:
try:
self.structure = self.get_final_structure_from_file(filename="CONTCAR")
except IOError:
self.structure = self.get_final_structure_from_file(filename="POSCAR")
self.sorted_indices = np.array(range(len(self.structure)))
self._output_parser.structure = self.structure.copy()
try:
self._output_parser.collect(
directory=self.working_directory, sorted_indices=self.sorted_indices
)
except VaspCollectError:
self.status.aborted = True
return
self._output_parser.to_hdf(self._hdf5)
if len(self._exclude_groups_hdf) > 0 or len(self._exclude_nodes_hdf) > 0:
self.project_hdf5.rewrite_hdf5(
job_name=self.job_name,
exclude_groups=self._exclude_groups_hdf,
exclude_nodes=self._exclude_nodes_hdf,
)
def convergence_check(self):
if "IBRION" in self["input/incar/data_dict"]["Parameter"]:
ind = self["input/incar/data_dict"]["Parameter"].index("IBRION")
ibrion = int(self["input/incar/data_dict"]["Value"][ind])
else:
ibrion = 0
if "NELM" in self["input/incar/data_dict"]["Parameter"]:
ind = self["input/incar/data_dict"]["Parameter"].index("NELM")
max_e_steps = int(self["input/incar/data_dict"]["Value"][ind])
else:
max_e_steps = 60
if "NSW" in self["input/incar/data_dict"]["Parameter"]:
ind = self["input/incar/data_dict"]["Parameter"].index("NSW")
max_i_steps = int(self["input/incar/data_dict"]["Value"][ind])
else:
max_i_steps = 0
scf_energies = self["output/generic/dft/scf_energy_free"]
if scf_energies is None:
scf_energies = self["output/outcar/scf_energies"]
e_steps_converged = [len(step) < max_e_steps for step in scf_energies]
# For calc_md() we do not care about convergence.
if ibrion == 0 and max_i_steps != 0:
return True
# For calc_static only the electronic convergence matters.
elif max_i_steps == 0 and np.all(e_steps_converged):
return True
# For calc_minimize only the last ionic step has to be converged!
elif (
0 < max_i_steps
and len(scf_energies) < max_i_steps
and e_steps_converged[-1]
):
return True
else:
return False
def cleanup(self, files_to_remove=("WAVECAR", "CHGCAR", "CHG", "vasprun.xml")):
"""
Removes excess files (by default: WAVECAR, CHGCAR, CHG)
"""
list_files = self.list_files()
for file in list_files:
if file in files_to_remove:
abs_file_path = os.path.join(self.working_directory, file)
os.remove(abs_file_path)
def collect_logfiles(self):
"""
Collect errors and warnings.
"""
self.collect_errors()
self.collect_warnings()
def collect_warnings(self):
"""
Collects warnings from the VASP run
"""
# TODO: implement for VASP
self._logger.info("collect_warnings() is not yet implemented for VASP")
def collect_errors(self):
"""
Collects errors from the VASP run
"""
num_eddrmm, snap = self._get_eddrmm_info()
if not snap is None:
if self.get_eddrmm_handling() == "ignore":
self._logger.warning(
"EDDRMM warnings are ignored. EDDRMM occures {} times, first in ionic step {}"
.format(num_eddrmm, snap)
)
elif self.get_eddrmm_handling() == "not_converged":
self.status.not_converged = True
self._logger.warning(
"EDDRMM warning occurred {} times first in ionic step {}. Status is switched to 'not_converged'."
.format(num_eddrmm, snap)
)
elif self.get_eddrmm_handling() == "restart":
self.status.not_converged = True
self._logger.warning(
"EDDRMM warning occurred {} times first in ionic step {}. Status is switched to 'not_converged'."
.format(num_eddrmm, snap)
)
if not self.input.incar["ALGO"].lower() == "normal":
ham_new = self.copy_hamiltonian(self.name + "_normal")
ham_new.input.incar["ALGO"] = "Normal"
ham_new.set_eddrmm_handling()
ham_new.run()
self._logger.info("Job was restarted with 'ALGO' = 'Normal' to avoid EDDRMM warning.")
def copy_hamiltonian(self, job_name):
"""
Copies a job to new one with a different name.
Args:
job_name (str): Job name
Returns:
pyiron.vasp.vasp.Vasp: New job
"""
ham_new = self.restart(snapshot=0, job_name=job_name)
ham_new.structure = self.structure
return ham_new
@staticmethod
def _decompress_files_in_directory(directory):
files = os.listdir(directory)
for file_compressed, file, mode in [
["OUTCAR.gz", "OUTCAR", "gzip"],
["vasprun.xml.bz2", "vasprun.xml", "bzip2"],
["vasprun.xml.gz", "vasprun.xml", "gzip"],
]:
if file_compressed in files and file not in files:
_ = subprocess.check_output(
[mode, "-d", file_compressed],
cwd=directory,
shell=False,
universal_newlines=True,
)
files = os.listdir(directory)
return files
def _get_eddrmm_info(self):
"""
Counts the number of EDDRMM warnings and first ionic step of occurrence.
Returns:
int: number of EDDRMM warning
int/None: number of ionic step where it occurs
"""
num_eddrmm = 0
snap = None
file_name = os.path.join(self.working_directory, "error.out")
if os.path.exists(file_name):
with open(file_name, "r") as f:
lines = f.readlines()
# If the wrong convergence algorithm is chosen, we get the following error.
# https://cms.mpi.univie.ac.at/vasp-forum/viewtopic.php?f=4&t=17071
warn_str = "WARNING in EDDRMM: call to ZHEGV failed, returncode ="
lines_where = np.argwhere([warn_str in l for l in lines]).flatten()
num_eddrmm = len(lines_where)
if num_eddrmm > 0:
snap = len(np.argwhere(["E0=" in l for l in lines[:lines_where[0]]]).flatten())
return num_eddrmm, snap
def from_directory(self, directory):
"""
The Vasp instance is created by parsing the input and output from the specified directory
Args:
directory (str): Path to the directory
"""
if not self.status.finished:
# _ = s.top_path(directory)
files = self._decompress_files_in_directory(directory)
vp_new = Vr()
try:
if not ("OUTCAR" in files or "vasprun.xml" in files):
raise IOError("This file isn't present")
# raise AssertionError("OUTCAR/vasprun.xml should be present in order to import from directory")
if "vasprun.xml" in files:
vp_new.from_file(filename=posixpath.join(directory, "vasprun.xml"))
self.structure = vp_new.get_initial_structure()
except (IOError, VasprunError): # except AssertionError:
pass
# raise AssertionError("OUTCAR/vasprun.xml should be present in order to import from directory")
if "INCAR" in files:
try:
self.input.incar.read_input(
posixpath.join(directory, "INCAR"), ignore_trigger="!"
)
except (IndexError, TypeError, ValueError):
pass
if "KPOINTS" in files:
try:
self.input.kpoints.read_input(
posixpath.join(directory, "KPOINTS"), ignore_trigger="!"
)
except (IndexError, TypeError, ValueError):
pass
if "POSCAR" in files and "POTCAR" in files:
structure = read_atoms(
posixpath.join(directory, "POSCAR"), species_from_potcar=True
)
else:
structure = vp_new.get_initial_structure()
self.structure = structure
# Read initial magnetic moments from the INCAR file and set it to the structure
magmom_loc = np.array(self.input.incar._dataset["Parameter"]) == "MAGMOM"
if any(magmom_loc):
init_moments = list()
try:
value = np.array(self.input.incar._dataset["Value"])[magmom_loc][0]
if "*" not in value:
init_moments = np.array([float(val) for val in value.split()])
else:
# Values given in "number_of_atoms*value" format
init_moments = np.hstack(
(
[
int(val.split("*")[0]) * [float(val.split("*")[1])]
for val in value.split()
]
)
)
except (ValueError, IndexError, TypeError):
self.logger.warning(
"Unable to parse initial magnetic moments from the INCAR file"
)
if len(init_moments) == len(self.structure):
self.structure.set_initial_magnetic_moments(init_moments)
else:
self.logger.warning(
"Inconsistency during parsing initial magnetic moments from the INCAR file"
)
self._write_chemical_formular_to_database()
self._import_directory = directory
self.status.collect = True
# self.to_hdf()
self.collect_output()
self.to_hdf()
self.status.finished = True
else:
return
def stop_calculation(self, next_electronic_step=False):
"""
Call to stop the VASP calculation
Args:
next_electronic_step (bool): True if the next electronic step should be calculated
"""
filename = os.path.join(self.working_directory, "STOPCAR")
with open(filename, "w") as f:
if not next_electronic_step:
f.write("LSTOP = .TRUE.\n")
else:
f.write("LABORT =.TRUE.\n")
def to_hdf(self, hdf=None, group_name=None):
"""
Stores the instance attributes into the hdf5 file
Args:
hdf (pyiron.base.generic.hdfio.ProjectHDFio): The HDF file/path to write the data to
group_name (str): The name of the group under which the data must be stored as
"""
super(VaspBase, self).to_hdf(hdf=hdf, group_name=group_name)
self._structure_to_hdf()
self.input.to_hdf(self._hdf5)
self._output_parser.to_hdf(self._hdf5)
def from_hdf(self, hdf=None, group_name=None):
"""
Recreates instance from the hdf5 file
Args:
hdf (pyiron.base.generic.hdfio.ProjectHDFio): The HDF file/path to read the data from
group_name (str): The name of the group under which the data must be stored as
"""
super(VaspBase, self).from_hdf(hdf=hdf, group_name=group_name)
self._structure_from_hdf()
self.input.from_hdf(self._hdf5)
if (
"output" in self.project_hdf5.list_groups()
and "structure" in self["output"].list_groups()
):
self._output_parser.from_hdf(self._hdf5)
def reset_output(self):
"""
Resets the output instance
"""
self._output_parser = Output()
def get_final_structure_from_file(self, filename="CONTCAR"):
"""
Get the final structure of the simulation usually from the CONTCAR file
Args:
filename (str): Path to the CONTCAR file in VASP
Returns:
pyiron.atomistics.structure.atoms.Atoms: The final structure
"""
filename = posixpath.join(self.working_directory, filename)
if self.structure is None:
try:
output_structure = read_atoms(filename=filename)
input_structure = output_structure.copy()
except (IndexError, ValueError, IOError):
raise IOError("Unable to read output structure")
else:
input_structure = self.structure.copy()
try:
output_structure = read_atoms(
filename=filename,
species_list=input_structure.get_parent_elements(),
)
input_structure.cell = output_structure.cell.copy()
input_structure.positions[
self.sorted_indices
] = output_structure.positions
except (IndexError, ValueError, IOError):
raise IOError("Unable to read output structure")
return input_structure
def write_magmoms(self):
"""
Write the magnetic moments in INCAR from that assigned to the species
"""
if any(self.structure.get_initial_magnetic_moments().flatten()):
final_cmd = " ".join(
[
" ".join([str(spinmom) for spinmom in spin])
if isinstance(spin, list) or isinstance(spin, np.ndarray)
else str(spin)
for spin in self.structure.get_initial_magnetic_moments()[
self.sorted_indices
]
]
)
s.logger.debug("Magnetic Moments are: {0}".format(final_cmd))
if "MAGMOM" not in self.input.incar._dataset["Parameter"]:
self.input.incar["MAGMOM"] = final_cmd
if "ISPIN" not in self.input.incar._dataset["Parameter"]:
self.input.incar["ISPIN"] = 2
if any(
[
True
if isinstance(spin, list) or isinstance(spin, np.ndarray)
else False
for spin in self.structure.get_initial_magnetic_moments()
]
):
self.input.incar["LNONCOLLINEAR"] = True
if (
self.spin_constraints
and "M_CONSTR" not in self.input.incar._dataset["Parameter"]
):
self.input.incar["M_CONSTR"] = final_cmd
if (
self.spin_constraints
or "M_CONSTR" in self.input.incar._dataset["Parameter"]
):
if "ISYM" not in self.input.incar._dataset["Parameter"]:
self.input.incar["ISYM"] = 0
if (
self.spin_constraints
and "LAMBDA" not in self.input.incar._dataset["Parameter"]
):
raise ValueError(
"LAMBDA is not specified but it is necessary for non collinear calculations."
)
if (
self.spin_constraints
and "RWIGS" not in self.input.incar._dataset["Parameter"]
):
raise ValueError(
"Parameter RWIGS has to be set for spin constraint calculations"
)
if self.spin_constraints and not self.input.incar["LNONCOLLINEAR"]:
raise ValueError(
"Spin constraints are only avilable for non collinear calculations."
)
else:
s.logger.debug("No magnetic moments")
def set_eddrmm_handling(self, status="not_converged"):
"""
Sets the way, how EDDRMM warning is handled.
Args:
status (str): new status of EDDRMM handling (can be 'not_converged', 'ignore', or 'restart')
"""
if status == "not_converged" or status == "ignore" or status == "restart":
self.input._eddrmm = status
else:
raise ValueError
def get_eddrmm_handling(self):
"""
Returns:
str: status of EDDRMM handling
"""
return self.input._eddrmm
def set_coulomb_interactions(self, interaction_type=2, ldau_print=True):
"""
Write the on-site Coulomb interactions in the INCAR file
Args:
interaction_type (int): Type of Coulombic interaction
1 - Asimov method
2 - Dudarev method
ldau_print (boolean): True/False
"""
obj_lst = self.structure.get_species_objects()
ldaul = []
ldauu = []
ldauj = []
needed = False
for el_obj in obj_lst:
conditions = []
if isinstance(el_obj.tags, dict):
for tag in ["ldauu", "ldaul", "ldauj"]:
conditions.append(tag in el_obj.tags.keys())
if not any(conditions):
ldaul.append("-1")
ldauu.append("0")
ldauj.append("0")
if any(conditions) and not all(conditions):
raise ValueError(
"All three tags ldauu,ldauj and ldaul have to be specified"
)
if all(conditions):
needed = True
ldaul.append(str(el_obj.tags["ldaul"]))
ldauu.append(str(el_obj.tags["ldauu"]))
ldauj.append(str(el_obj.tags["ldauj"]))
if needed:
self.input.incar["LDAU"] = True
self.input.incar["LDAUTYPE"] = interaction_type
self.input.incar["LDAUL"] = " ".join(ldaul)
self.input.incar["LDAUU"] = " ".join(ldauu)
self.input.incar["LDAUJ"] = " ".join(ldauj)
if ldau_print:
self.input.incar["LDAUPRINT"] = 2
else:
s.logger.debug("No on site coulomb interactions")
def set_algorithm(self, algorithm="Fast", ialgo=None):
"""
Sets the type of electronic minimization algorithm
Args:
algorithm (str): Algorithm defined by VASP (Fast, Normal etc.)
ialgo (int): Sets the IALGO tag in VASP. If not none, this overwrites algorithm
"""
algorithm_list = ["Fast", "Accurate", "Normal", "Very Fast"]
if ialgo is not None:
self.input.incar["IALGO"] = int(ialgo)
else:
self.input.incar["ALGO"] = str(algorithm)
if algorithm not in algorithm_list:
s.logger.warning(
msg="Algorithm {} is unusual for VASP. "
"I hope you know what you are up to".format(algorithm)
)
def calc_minimize(
self,
electronic_steps=400,
ionic_steps=100,
max_iter=None,
pressure=None,
algorithm=None,
retain_charge_density=False,
retain_electrostatic_potential=False,
ionic_energy=None,
ionic_forces=None,
volume_only=False,
):
"""
Function to setup the hamiltonian to perform ionic relaxations using DFT. The ISIF tag has to be supplied
separately.
Args:
electronic_steps (int): Maximum number of electronic steps
ionic_steps (int): Maximum number of ionic
max_iter (int): Maximum number of iterations
pressure (float): External pressure to be applied
algorithm (str): Type of VASP algorithm to be used "Fast"/"Accurate"
retain_charge_density (bool): True if the charge density should be written
retain_electrostatic_potential (boolean): True if the electrostatic potential should be written
ionic_energy (float): Ionic energy convergence criteria (eV)
ionic_forces (float): Ionic forces convergence criteria (overwrites ionic energy) (ev/A)
volume_only (bool): Option to relax only the volume (keeping the relative coordinates fixed
"""
super(VaspBase, self).calc_minimize(
electronic_steps=electronic_steps,
ionic_steps=ionic_steps,
max_iter=max_iter,
pressure=pressure,
algorithm=algorithm,
retain_charge_density=retain_charge_density,
retain_electrostatic_potential=retain_electrostatic_potential,
ionic_energy=ionic_energy,
ionic_forces=ionic_forces,
volume_only=volume_only,
)
if volume_only:
self.input.incar["ISIF"] = 7
else:
if pressure == 0.0:
self.input.incar["ISIF"] = 3
else:
self.input.incar["ISIF"] = 2
if max_iter:
electronic_steps = max_iter
ionic_steps = max_iter
self.input.incar["IBRION"] = 2
self.input.incar["NELM"] = electronic_steps
self.input.incar["NSW"] = ionic_steps
if algorithm is not None:
self.set_algorithm(algorithm=algorithm)
if retain_charge_density:
self.write_charge_density = retain_charge_density
if retain_electrostatic_potential:
self.write_electrostatic_potential = retain_electrostatic_potential
return
def calc_static(
self,
electronic_steps=400,
algorithm=None,
retain_charge_density=False,
retain_electrostatic_potential=False,
):
"""
Function to setup the hamiltonian to perform static SCF DFT runs.
Args:
electronic_steps (int): Maximum number of electronic steps
algorithm (str): Type of VASP algorithm to be used "Fast"/"Accurate"
retain_charge_density (bool): True if
retain_electrostatic_potential (bool): True/False
"""
super(VaspBase, self).calc_static(
electronic_steps=electronic_steps,
algorithm=algorithm,
retain_charge_density=retain_charge_density,
retain_electrostatic_potential=retain_electrostatic_potential,
)
self.input.incar["IBRION"] = -1
self.input.incar["NELM"] = electronic_steps
if algorithm is not None:
if algorithm is not None:
self.set_algorithm(algorithm=algorithm)
if retain_charge_density:
self.write_charge_density = retain_charge_density
if retain_electrostatic_potential:
self.write_electrostatic_potential = retain_electrostatic_potential
def calc_md(
self,
temperature=None,
n_ionic_steps=1000,
n_print=1,
time_step=1.0,
retain_charge_density=False,
retain_electrostatic_potential=False,
**kwargs
):
"""
Sets appropriate tags for molecular dynamics in VASP
Args:
temperature (int/float/list): Temperature/ range of temperatures in Kelvin
n_ionic_steps (int): Maximum number of ionic steps
n_print (int): Prints outputs every n_print steps
time_step (float): time step (fs)
retain_charge_density (bool): True id the charge density should be written
retain_electrostatic_potential (bool): True if the electrostatic potential should be written
"""
super(VaspBase, self).calc_md(
temperature=temperature,
n_ionic_steps=n_ionic_steps,
n_print=n_print,
time_step=time_step,
retain_charge_density=retain_charge_density,
retain_electrostatic_potential=retain_electrostatic_potential,
**kwargs
)
if temperature is not None:
# NVT ensemble
self.input.incar["SMASS"] = 3
if isinstance(temperature, (int, float)):
self.input.incar["TEBEG"] = temperature
else:
self.input.incar["TEBEG"] = temperature[0]
self.input.incar["TEEND"] = temperature[-1]
else:
# NVE ensemble
self.input.incar["SMASS"] = -3
self.input.incar["NSW"] = n_ionic_steps
self.input.incar["NBLOCK"] = int(n_print)
self.input.incar["POTIM"] = time_step