/
base.py
1870 lines (1723 loc) · 72.4 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, division
import numpy as np
import os
import posixpath
import re
from shutil import copyfile
import scipy.constants
import subprocess
from ase import io
from pyiron.atomistics.structure.atoms import ase_to_pyiron
import warnings
import json
from collections import OrderedDict as odict
from collections import defaultdict
from pyiron.dft.job.generic import GenericDFTJob
from pyiron.vasp.potential import VaspPotentialFile, find_potential_file
from pyiron.base.settings.generic import Settings
from pyiron.base.generic.parameters import GenericParameters
__author__ = "Osamu Waseda, Jan Janssen"
__copyright__ = (
"Copyright 2019, Max-Planck-Institut für Eisenforschung GmbH - "
"Computational Materials Design (CM) Department"
)
__version__ = "1.0"
__maintainer__ = "Jan Janssen"
__email__ = "janssen@mpie.de"
__status__ = "development"
__date__ = "Sep 1, 2017"
s = Settings()
BOHR_TO_ANGSTROM = (
scipy.constants.physical_constants["Bohr radius"][0] / scipy.constants.angstrom
)
HARTREE_TO_EV = scipy.constants.physical_constants["Hartree energy in eV"][0]
HARTREE_OVER_BOHR_TO_EV_OVER_ANGSTROM = HARTREE_TO_EV / BOHR_TO_ANGSTROM
class SphinxBase(GenericDFTJob):
"""
Class to setup and run Sphinx simulations which is a derivative of pyiron_atomistics.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 Sphinx specific input and
output.
Args:
project: Project object (defines path where job will be created and stored)
job_name (str): name of the job (must be unique within this project path)
"""
def __init__(self, project, job_name):
super(SphinxBase, self).__init__(project, job_name)
self.input = Input()
self._main_str = None
self._species_str = None
self._structure_str = None
self._basis_str = None
self._hamilston_str = None
self._guess_str = None
self._spins_str = None
self._save_memory = False
self._output_parser = Output(self)
self.input_writer = InputWriter()
@property
def id_pyi_to_spx(self):
if self.input_writer.id_pyi_to_spx is None:
self.input_writer.structure = self.structure
return self.input_writer.id_pyi_to_spx
@property
def id_spx_to_pyi(self):
if self.input_writer.id_spx_to_pyi is None:
self.input_writer.structure = self.structure
return self.input_writer.id_spx_to_pyi
@property
def plane_wave_cutoff(self):
return self.input["EnCut"]
@property
def fix_spin_constraint(self):
return self._generic_input["fix_spin_constraint"]
@fix_spin_constraint.setter
def fix_spin_constraint(self, boolean):
if not isinstance(boolean, bool):
raise ValueError("fix_spin_constraint has to be a boolean")
self._generic_input["fix_spin_constraint"] = boolean
self.structure.add_tag(spin_constraint=boolean)
@plane_wave_cutoff.setter
def plane_wave_cutoff(self, val):
"""
Function to setup the energy cut-off for the Sphinx job in eV.
Args:
encut (int): energy cut-off in eV
"""
if val <= 0:
raise ValueError("Cutoff radius value not valid")
self.input["EnCut"] = val
@property
def exchange_correlation_functional(self):
return self.input["Xcorr"]
@exchange_correlation_functional.setter
def exchange_correlation_functional(self, val):
"""
Args:
exchange_correlation_functional:
Returns:
"""
if val.upper() in ["PBE", "LDA"]:
self.input["Xcorr"] = val.upper()
else:
warnings.warn(
"Exchange correlation function not recognized (recommended: PBE or LDA)",
SyntaxWarning,
)
self.input["Xcorr"] = val
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(SphinxBase, self).set_input_to_read_only()
self.input.read_only = True
def _input_control_scf_string(
self, maxSteps=None, keepRhoFixed=False, dEnergy=None, algorithm="blockCCG"
):
"""
scf control string setting for SPHInX
for all args refer to calc_static or calc_minimize
"""
if algorithm.upper() == "CCG":
algorithm = "CCG"
else:
if algorithm.upper() != "BLOCKCCG":
warnings.warn(
"Algorithm not recognized -> setting to blockCCG. Alternatively, choose algorithm=CCG",
SyntaxWarning,
)
algorithm = "blockCCG"
control_str = odict()
if keepRhoFixed:
control_str["keepRhoFixed"] = None
else:
control_str["rhoMixing"] = str(self.input["rhoMixing"])
control_str["spinMixing"] = str(self.input["spinMixing"])
if self.input["nPulaySteps"] is not None:
control_str["nPulaySteps"] = str(self.input["nPulaySteps"])
if dEnergy is None:
control_str["dEnergy"] = "Ediff/" + str(HARTREE_TO_EV)
else:
control_str["dEnergy"] = str(dEnergy)
if maxSteps is None:
control_str["maxSteps"] = str(self.input["Estep"])
else:
control_str["maxSteps"] = str(maxSteps)
if self.input["preconditioner"] is not None:
control_str["preconditioner"] = odict(
[("type", self.input["preconditioner"])]
)
control_str[algorithm] = odict()
if self.input["WriteWaves"] is False:
control_str["noWavesStorage"] = None
return control_str
@property
def _control_str(self):
control_str = odict()
control_str.setdefault("scfDiag", [])
if len(self.restart_file_list) != 0:
control_str["scfDiag"].append(
self._input_control_scf_string(
maxSteps=10, keepRhoFixed=True, dEnergy=1.0e-4
)
)
if self.input["Istep"] is not None:
control_str["linQN"] = odict()
control_str["linQN"]["maxSteps"] = str(self.input["Istep"])
if self.input["dE"] is None and self.input["dF"] is None:
self.input["dE"] = 1e-3
if self.input["dE"] is not None:
control_str["linQN"]["dEnergy"] = str(self.input["dE"] / HARTREE_TO_EV)
if self.input["dF"] is not None:
control_str["linQN"]["dF"] = str(
self.input["dF"] / HARTREE_OVER_BOHR_TO_EV_OVER_ANGSTROM
)
control_str["linQN"]["bornOppenheimer"] = odict(
[("scfDiag", self._input_control_scf_string())]
)
else:
control_str["scfDiag"].append(self._input_control_scf_string())
if self.executable.version is not None:
vers_num = [
int(vv) for vv in self.executable.version.split("_")[0].split(".")
]
if vers_num[0] > 2 or (vers_num[0] == 2 and vers_num[1] > 5):
control_str["evalForces"] = odict([("file", '"relaxHist.sx"')])
else:
warnings.warn("executable version could not be identified")
return control_str
def calc_static(
self,
electronic_steps=None,
algorithm=None,
retain_charge_density=False,
retain_electrostatic_potential=False,
):
"""
Function to setup the hamiltonian to perform static SCF DFT runs
Args:
retain_electrostatic_potential:
retain_charge_density:
algorithm (str): CCG or blockCCG (not implemented)
electronic_steps (int): maximum number of electronic steps, which can be used
to achieve convergence
"""
if electronic_steps is not None:
self.input["Estep"] = electronic_steps
for arg in ["Istep", "dF", "dE"]:
if self.input[arg] is not None:
del self.input[arg]
super(SphinxBase, self).calc_static(
electronic_steps=electronic_steps,
algorithm=algorithm,
retain_charge_density=retain_charge_density,
retain_electrostatic_potential=retain_electrostatic_potential,
)
def calc_minimize(
self,
electronic_steps=None,
ionic_steps=None,
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 convergence goal can be set using
either the iconic_energy as an limit for fluctuations in energy or the iconic_forces.
Args:
retain_electrostatic_potential:
retain_charge_density:
algorithm:
pressure:
max_iter:
electronic_steps (int): maximum number of electronic steps per electronic convergence
ionic_steps (int): maximum number of ionic steps
ionic_energy (float): convergence goal in terms of energy (optional)
ionic_forces (float): convergence goal in terms of forces (optional)
"""
if pressure is not None:
raise NotImplementedError(
"pressure minimization is not implemented in SPHInX"
)
if electronic_steps is not None:
self.input["Estep"] = electronic_steps
if ionic_steps is not None:
self.input["Istep"] = ionic_steps
elif self.input["Istep"] is None:
self.input["Istep"] = 100
if ionic_forces is not None:
if ionic_forces < 0:
raise ValueError("ionic_forces must be a positive integer")
self.input["dF"] = float(ionic_forces)
if ionic_energy is not None:
if ionic_energy < 0:
raise ValueError("ionic_forces must be a positive integer")
self.input["dE"] = float(ionic_energy)
super(SphinxBase, 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,
)
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
):
raise NotImplementedError("calc_md() not implemented in SPHInX.")
def restart_from_charge_density(self, job_name=None):
"""
Restart a new job created from an existing Vasp calculation by reading the charge density.
Args:
job_name (str): Job name (full path required)
Returns:
None (currently the SPHInX implementation does not allow for a restart via return value)
"""
self.restart_file_list.append(job_name)
return None
def restart(
self,
snapshot=-1,
job_name=None,
job_type=None,
from_charge_density=True,
from_wave_functions=True,
):
new_job = super(SphinxBase, self).restart(
snapshot=snapshot, job_name=job_name, job_type=job_type
)
if from_charge_density and os.path.isfile(
posixpath.join(self.working_directory, "rho.sxb")
):
new_job.restart_file_list.append(
posixpath.join(self.working_directory, "rho.sxb")
)
elif from_charge_density:
self._logger.warn(
msg="A charge density from job: {} is not generated and therefore it can't be read.".format(
self.job_name
)
)
if from_wave_functions and os.path.isfile(
posixpath.join(self.working_directory, "waves.sxb")
):
new_job.restart_file_list.append(
posixpath.join(self.working_directory, "waves.sxb")
)
elif from_wave_functions:
self._logger.warn(
msg="A WAVECAR from job: {} is not generated and therefore it can't be read.".format(
self.job_name
)
)
return new_job
def to_hdf(self, hdf=None, group_name=None):
"""
Stores the instance attributes into the hdf5 file
Args:
hdf (str): Path to the hdf5 file
group_name (str): Name of the group which contains the object
"""
super(SphinxBase, 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 (str): Path to the hdf5 file
group_name (str): Name of the group which contains the object
"""
super(SphinxBase, self).from_hdf(hdf=hdf, group_name=group_name)
self._structure_from_hdf()
self.input.from_hdf(self._hdf5)
if self.status.finished:
self._output_parser.from_hdf(self._hdf5)
def from_directory(self, directory):
try:
if not self.status.finished:
subprocess.call(
"module load sphinx && sx2aims", cwd=directory, shell=True
)
# self._output_parser.to_hdf(self._hdf5)
if directory[-1] == "/":
directory = directory[:-1]
if os.path.isfile(directory + "/geometry.in"):
self.structure = ase_to_pyiron(
io.read(filename=directory + "/geometry.in")
)
else:
print(
"WARNING: input structure not found: "
+ directory
+ "/geometry.in"
)
subprocess.call(
"rm " + directory + "/geometry.in", cwd=directory, shell=True
)
self._output_parser.collect(directory=directory)
self.to_hdf(self._hdf5)
else:
self._output_parser.from_hdf(self._hdf5)
self.status.finished = True
except Exception as err:
print(err)
self.status.aborted = True
def set_check_overlap(self, check_overlap=True):
"""
Args:
check_overlap (bool): Whether to check overlap
Comments:
Certain PAW-pseudo-potentials have an intrinsic pathology: their PAW overlap
operator is not generally positive definite (i.e., the PAW-corrected
norm of a wavefunction could become negative). SPHInX usually refuses to
use such problematic potentials. This behavior can be overridden by setting
check_overlap to False.
"""
if not isinstance(check_overlap, bool):
raise ValueError("check_overlap has to be a boolean")
if self.executable.version != "2.5.1" and not check_overlap:
vers_num = [
int(vv) for vv in self.executable.version.split("_")[0].split(".")
]
if (
vers_num[0] < 2
or vers_num[1] < 5
or (vers_num[0] <= 2 and sum(vers_num[1:]) <= 5)
):
warnings.warn(
"SPHInX executable version has to be 2.5.1 or above in order for the overlap to be considered. "
+ "Change it via job.executable.version"
)
self.input["CheckOverlap"] = check_overlap
def set_mixing_parameters(
self,
method=None,
n_pulay_steps=None,
density_mixing_parameter=None,
spin_mixing_parameter=None,
):
"""
args:
method ('PULAY' or 'LINEAR'): mixing method (default: PULAY)
n_pulay_steps (int): number of previous densities to use for the Pulay mixing (default: 7)
density_mixing_parameter (float): mixing proportion m defined by rho^n = (m-1)*rho^(n-1)+m*preconditioner*rho_(opt) (default: 1)
spin_mixing_parameter (float): linear mixing parameter for spin densities (default: 1)
comments:
A low value of density mixing parameter may lead to a more stable convergence,
but will slow down the calculation if set too low.
Further information can be found on the website: https://sxrepo.mpie.de
"""
method_list = ["PULAY", "LINEAR"]
assert (
method is None or method.upper() in method_list
), "Mixing method has to be PULAY or LINEAR"
assert n_pulay_steps is None or isinstance(
n_pulay_steps, int
), "n_pulay_steps has to be an integer"
if density_mixing_parameter is not None and (
density_mixing_parameter > 1.0 or density_mixing_parameter < 0
):
raise ValueError(
"density_mixing_parameter has to be between 0 and 1 (default value is 1)"
)
if spin_mixing_parameter is not None and (
spin_mixing_parameter > 1.0 or spin_mixing_parameter < 0
):
raise ValueError(
"spin_mixing_parameter has to be between 0 and 1 (default value is 1)"
)
if method is not None:
self.input["mixingMethod"] = method.upper()
if n_pulay_steps is not None:
self.input["nPulaySteps"] = n_pulay_steps
if density_mixing_parameter is not None:
self.input["rhoMixing"] = density_mixing_parameter
if spin_mixing_parameter is not None:
self.input["spinMixing"] = spin_mixing_parameter
def set_occupancy_smearing(self, smearing=None, width=None):
"""
Set how the finite temperature smearing is applied in determining partial occupancies
Args:
smearing (str): Type of smearing (only fermi si implemented anything else will be ignored)
width (float): Smearing width (eV) (default: 0.2)
"""
if smearing is not None and not isinstance(smearing, str):
raise ValueError(
"Smearing must be a string (only fermi is supported in SPHInX)"
)
if width is not None and width < 0:
raise ValueError("Smearing value must be a float >= 0")
if width is not None:
self.input["Sigma"] = width
def set_convergence_precision(
self, ionic_energy=None, electronic_energy=None, ionic_forces=None
):
"""
Sets the electronic and ionic convergence precision. For ionic convergence either the energy or the force
precision is required
Args:
ionic_energy (float): Ionic energy convergence precision (eV)
electronic_energy (float): Electronic energy convergence precision (eV)
ionic_forces (float): Ionic force convergence precision (eV/A)
"""
assert (
ionic_energy is None or ionic_energy > 0
), "ionic_energy must be a positive float"
assert (
ionic_forces is None or ionic_forces > 0
), "ionic_forces must be a positive float"
assert (
electronic_energy is None or electronic_energy > 0
), "electronic_energy must be a positive float"
if ionic_energy is not None or ionic_forces is not None:
print("Setting calc_minimize")
self.calc_minimize(ionic_energy=ionic_energy, ionic_forces=ionic_forces)
if electronic_energy is not None:
self.input["Ediff"] = electronic_energy
def set_empty_states(self, n_empty_states=None):
"""
Function to set the number of empty states.
Args:
n_empty_states (int or 'auto'): Number of empty states. 'auto' if the default value is to be used.
Comments:
If this number is too low, the algorithm will not be able to able to swap wave functions
near the chemical potential. If the number is too high, computation time will be wasted
for the higher energy states and potentially lead to a memory problem.
In contrast to VASP, this function sets only the number of empty states and not the number of
total states.
The default value is 0.5*NIONS+3 for non-magnetic systems and 1.5*NIONS+3 for magnetic systems
"""
if n_empty_states is not None or n_empty_states < 0:
raise ValueError("Number of empty states must be greater than 0")
if n_empty_states is not None:
self.input["EmptyStates"] = n_empty_states
def _set_kpoints(
self,
mesh=None,
scheme="MP",
center_shift=None,
symmetry_reduction=True,
manual_kpoints=None,
weights=None,
reciprocal=True,
):
"""
Function to setup the k-points for the Sphinx job
Args:
reciprocal (bool): Tells if the supplied values are in reciprocal (direct)
or cartesian coordinates (in reciprocal space) (not implemented)
weights (list): Manually supplied weights to each k-point in case of the manual mode (not implemented)
manual_kpoints (list): Manual list of k-points (not implemented)
symmetry_reduction (bool): Tells if the symmetry reduction is to be applied to the k-points
scheme (str): Type of k-point generation scheme (only 'MP' implemented)
mesh (list): Size of the mesh (in the MP scheme)
center_shift (list): Shifts the center of the mesh from the gamma point by the given vector
"""
if not isinstance(symmetry_reduction, bool):
raise ValueError("symmetry_reduction has to be a boolean")
if manual_kpoints is not None:
raise ValueError("manual_kpoints is not implemented in SPHInX yet")
if weights is not None:
raise ValueError("manual weights are not implmented in SPHInX yet")
if scheme != "MP":
raise ValueError("only Monkhorst-Pack mesh is implemented in SPHInX")
if mesh is not None:
self.input["KpointFolding"] = (
"[" + str(mesh[0]) + ", " + str(mesh[1]) + ", " + str(mesh[2]) + "]"
)
if center_shift is not None:
self.input["KpointCoords"] = (
"["
+ str(center_shift[0])
+ ", "
+ str(center_shift[1])
+ ", "
+ str(center_shift[2])
+ "]"
)
def write_input(self):
"""
The write_input function is called when the job is executed to generate all the required input files for the
calculation of the Sphinx job.
"""
self._coarse_run = self.input["CoarseRun"]
if self.input["EmptyStates"] == "auto":
self.input["EmptyStates"] = int(len(self.structure) + 3)
if np.any(self.structure.get_initial_magnetic_moments() != None):
self.input["EmptyStates"] = int(1.5 * len(self.structure) + 3)
self.input_writer.structure = self.structure
write_waves = self.input["WriteWaves"]
save_memory = self.input["SaveMemory"]
check_overlap = self.input["CheckOverlap"]
enable_kjxc = self.input["KJxc"]
if self._main_str is None:
self.input_writer.write_potentials(
file_name="potentials.sx",
cwd=self.working_directory,
species_str=self._species_str,
check_overlap=check_overlap,
xc=self.input["Xcorr"],
)
self.input_writer.write_guess(
file_name="guess.sx",
cwd=self.working_directory,
guess_str=self._guess_str,
restart_file_str=self.restart_file_list,
write_waves=write_waves,
)
self.input_writer.write_structure(
file_name="structure.sx",
cwd=self.working_directory,
structure_str=self._structure_str,
symmetry_enabled=self._generic_input["fix_symmetry"],
)
self.input_writer.write_control(
file_name="control.sx",
cwd=self.working_directory,
control_str=self._control_str,
)
self.input_writer.write_basis(
file_name="basis.sx",
cwd=self.working_directory,
basis_str=self._basis_str,
save_memory=save_memory,
)
self.input_writer.write_hamilton(
file_name="hamilton.sx",
cwd=self.working_directory,
hamilston_str=self._hamilston_str,
)
if self._generic_input["fix_spin_constraint"]:
self.input_writer.write_spins_constraints(
file_name="spins.in",
cwd=self.working_directory,
spins_str=self._spins_str,
)
self.input.write_file(file_name="userparameters.sx", cwd=self.working_directory)
self.input_writer.write_main(
file_name="input.sx",
cwd=self.working_directory,
main_str=self._main_str,
spin_constraint_enabled=self._generic_input["fix_spin_constraint"],
enable_kjxc=enable_kjxc,
job_name=self.job_name,
)
def collect_output(self, force_update=False):
"""
Collects the outputs and stores them to the hdf file
"""
self._output_parser.collect(directory=self.working_directory)
self._output_parser.to_hdf(self._hdf5, force_update=force_update)
def convergence_check(self):
if (
self._generic_input["calc_mode"] == "minimize"
and self._output_parser._parse_dict["scf_convergence"][-1]
):
return True
elif self._generic_input["calc_mode"] == "static" and np.all(
self._output_parser._parse_dict["scf_convergence"]
):
return True
else:
return False
def collect_logfiles(self):
"""
Collect errors and warnings.
"""
self.collect_errors()
self.collect_warnings()
def collect_warnings(self):
"""
Collects warnings from the Sphinx run
"""
# TODO: implement for Sphinx
self._logger.info("collect_warnings() is not yet implemented for Sphinx")
def collect_errors(self):
"""
Collects errors from the Sphinx run
"""
# TODO: implement for Sphinx
self._logger.info("collect_errors() is not yet implemented for Sphinx")
def get_n_ir_reciprocal_points(
self, is_time_reversal=True, symprec=1e-5, ignore_magmoms=False
):
from phonopy.structure import spglib
lattice = self.structure.cell
positions = self.structure.get_scaled_positions()
numbers = self.structure.get_atomic_numbers()
magmoms = self.structure.get_initial_magnetic_moments()
if np.all(magmoms == None) or ignore_magmoms:
magmoms = np.zeros(len(magmoms))
mag_num = np.array(list(zip(magmoms, numbers)))
satz = np.unique(mag_num, axis=0)
numbers = []
for nn in np.all(satz == mag_num[:, np.newaxis], axis=-1):
numbers.append(np.arange(len(satz))[nn][0])
mapping, _ = spglib.get_ir_reciprocal_mesh(
mesh=[int(k) for k in self.input["KpointFolding"]],
cell=(lattice, positions, numbers),
is_shift=np.dot(self.structure.cell, np.array(self.input["KpointCoords"])),
is_time_reversal=is_time_reversal,
symprec=symprec,
)
return len(np.unique(mapping))
def check_setup(self):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
if (
not (
isinstance(self.input["EnCut"], int)
or isinstance(self.input["EnCut"], float)
)
or self.input["EnCut"] == 340
):
warnings.warn(
"Energy cut-off value wrong or not modified from default 340 eV; change it via job.set_encut()"
)
if not (
isinstance(self.input["KpointCoords"], list)
or len(self.input["KpointCoords"]) != 3
):
warnings.warn("K point coordinates seem to be inappropriate")
if (
not (
isinstance(self.input["Sigma"], int)
or isinstance(self.input["Sigma"], float)
)
or self.input["Sigma"] == 0.2
):
warnings.warn(
"Fermi smearing value wrong or not modified from default 0.2 eV; change it via job.set_occupancy_smearing()"
)
if not (
isinstance(self.input["KpointFolding"], list)
or len(self.input["KpointFolding"]) != 3
) or self.input["KpointFolding"] == [4, 4, 4]:
warnings.warn(
"K point folding wrong or not modified from default [4,4,4]; change it via job.set_kpoints()"
)
if self.get_n_ir_reciprocal_points() < self.server.cores:
warnings.warn(
"Number of cores exceed number of irreducible reciprocal points: "
+ str(self.get_n_ir_reciprocal_points())
)
if self.input["EmptyStates"] == "auto":
if any(self.structure.get_initial_magnetic_moments() != None):
warnings.warn(
"Number of empty states was not specified. Default: NIONS*1.5 for magnetic systems. "
)
else:
warnings.warn(
"Number of empty states was not specified. Default: NIONS for non-magnetic systems"
)
if len(w) > 0:
print("WARNING:")
for ww in w:
print(ww.message)
return False
else:
return True
def validate_ready_to_run(self):
"""
Checks whether parameters are set appropriately. It does not mean the simulation won't run even if it returns False
"""
if self._control_str is None:
self.calc_static()
if self.structure is None:
raise AssertionError(
"Structure not set; set it via job.structure = Project().create_structure()"
)
if self._control_str is None:
raise AssertionError(
"Control string not set; set it e.g. via job.calc_static()"
)
if self.input["THREADS"] > self.server.cores:
raise AssertionError(
"Number of cores cannot be smaller than the number of OpenMP threads"
)
if self.input["EmptyStates"] != "auto" and self.input["EmptyStates"] < 0:
raise AssertionError("Number of empty states not valid")
def compress(self, files_to_compress=None):
"""
Compress the output files of a job object.
Args:
files_to_compress (list): A list of files to compress (optional)
"""
if files_to_compress is None:
files_to_compress = [
f for f in list(self.list_files()) if f not in ["rho.sxb", "waves.sxb"]
]
# delete empty files
for f in list(self.list_files()):
filename = os.path.join(self.working_directory, f)
if (
f not in files_to_compress
and os.path.exists(filename)
and os.stat(filename).st_size == 0
):
os.remove(filename)
super(SphinxBase, self).compress(files_to_compress=files_to_compress)
class InputWriter(object):
"""
The Sphinx Input writer is called to write the Sphinx specific input files.
"""
pot_path_dict = {"PBE": "paw-gga-pbe", "LDA": "paw-lda"}
def __init__(self):
self.structure = None
self._spin_enabled = False
self._id_pyi_to_spx = []
self._id_spx_to_pyi = []
self.file_dict = {}
def _odict_to_spx_input(self, element, level=0):
"""
Convert collections.OrderedDict containing SPHInX input
hierarchy to string.
If the item contains:
- no value -> considered as flag -> output format: flag;
- value is odict
-> considered as a group
-> output format: group { ...recursive... }
- else
-> considered as parameter and value
-> output format: parameter = value;
"""
line = ""
for k, v in element.items():
if type(v) != list:
v = [v]
for vv in v:
if vv is None:
line += level * "\t" + str(k) + ";\n"
elif type(vv) == odict:
if len(vv) == 0:
line += level * "\t" + k + " {}\n"
else:
line += (
level * "\t"
+ k
+ " {\n"
+ self._odict_to_spx_input(vv, level + 1)
+ level * "\t"
+ "}\n"
)
else:
line += level * "\t" + k + " = " + str(vv) + ";\n"
return line
def write_main(
self,
file_name="input.sx",
cwd=None,
main_str=None,
spin_constraint_enabled=False,
enable_kjxc=False,
job_name=None,
):
"""
Write the main Sphinx script named input.sx.
Args:
file_name (str): name of the file to be written (optional)
cwd (str): the current working directory (optinal)
main_str (str): the input to write;
if no input is given,
the default input will be written. (optinal)
"""
if main_str is None:
self.file_dict['input'] = self.get_main(enable_kjxc=enable_kjxc,
spin_constraint_enabled=spin_constraint_enabled,
job_name=job_name)
else:
self.file_dict['input'] = main_str
if cwd is not None:
file_name = posixpath.join(cwd, file_name)
with open(file_name, "w") as f:
f.write(self._odict_to_spx_input(self.file_dict['input']))
@staticmethod
def get_main(enable_kjxc=False, spin_constraint_enabled=False, job_name=None):
line = odict(
[
("//" + str(job_name), None),
("//SPHinX input file generated by pyiron", None),
("format paw", None),
("include <parameters.sx>", None),
("include <userparameters.sx>", None),
]
)
if enable_kjxc:
line["pawPot"] = odict(
[("include <potentials.sx>", None), ("kjxc", None)]
)
else:
line["pawPot"] = odict([("include <potentials.sx>", None)])
line["structure"] = odict([("include <structure.sx>", None)])
line["basis"] = odict([("include <basis.sx>", None)])
line["PAWHamiltonian"] = odict([("include <hamilton.sx>", None)])
line["initialGuess"] = odict([("include <guess.sx>", None)])
if spin_constraint_enabled:
line["spinConstraint"] = odict([("file", '"spins.in"')])
line["main"] = odict([("include <control.sx>", None)])
return line
@property
def id_spx_to_pyi(self):
if self.structure is None:
return None
if len(self._id_spx_to_pyi) == 0:
self._initialize_order()
return self._id_spx_to_pyi
@property
def id_pyi_to_spx(self):
if self.structure is None:
return None
if len(self._id_pyi_to_spx) == 0:
self._initialize_order()
return self._id_pyi_to_spx
def _initialize_order(self):
for elm_species in self.structure.get_species_objects():
self._id_pyi_to_spx.append(
np.arange(len(self.structure))[
self.structure.get_chemical_symbols() == elm_species.Abbreviation
]
)
self._id_pyi_to_spx = np.array(
[ooo for oo in self._id_pyi_to_spx for ooo in oo]
)
self._id_spx_to_pyi = np.array([0] * len(self._id_pyi_to_spx))
for i, p in enumerate(self._id_pyi_to_spx):
self._id_spx_to_pyi[p] = i
def write_potentials(
self,
file_name="potentials.sx",
cwd=None,
species_str=None,
check_overlap=True,
xc=None,
):
"""
Write the Sphinx potential configuration named potentials.sx.
Args:
file_name (str): name of the file to be written (optional)