-
Notifications
You must be signed in to change notification settings - Fork 838
/
test_sets.py
1830 lines (1546 loc) · 72.1 KB
/
test_sets.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
from __future__ import annotations
import hashlib
import os
from glob import glob
from pathlib import Path
from zipfile import ZipFile
import numpy as np
import pytest
from _pytest.monkeypatch import MonkeyPatch
from monty.json import MontyDecoder
from monty.serialization import loadfn
from numpy.testing import assert_allclose
from pytest import approx, mark
import pymatgen
from pymatgen.analysis.structure_matcher import StructureMatcher
from pymatgen.core import SETTINGS, Lattice, Species, Structure
from pymatgen.core.surface import SlabGenerator
from pymatgen.core.units import FloatWithUnit
from pymatgen.io.vasp.inputs import Incar, Kpoints, Poscar
from pymatgen.io.vasp.outputs import Vasprun
from pymatgen.io.vasp.sets import (
BadInputSetWarning,
DictSet,
LobsterSet,
MatPESStaticSet,
MITMDSet,
MITNEBSet,
MITRelaxSet,
MPAbsorptionSet,
MPHSEBSSet,
MPHSERelaxSet,
MPMetalRelaxSet,
MPNMRSet,
MPNonSCFSet,
MPRelaxSet,
MPScanRelaxSet,
MPScanStaticSet,
MPSOCSet,
MPStaticSet,
MVLElasticSet,
MVLGBSet,
MVLGWSet,
MVLNPTMDSet,
MVLRelax52Set,
MVLScanRelaxSet,
MVLSlabSet,
VaspInputSet,
batch_write_input,
get_structure_from_prev_run,
get_valid_magmom_struct,
)
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest
MODULE_DIR = Path(pymatgen.io.vasp.__file__).parent
dec = MontyDecoder()
NO_PSP_DIR = SETTINGS.get("PMG_VASP_PSP_DIR") is None
skip_if_no_psp_dir = mark.skipif(NO_PSP_DIR, reason="PMG_VASP_PSP_DIR is not set.")
dummy_structure = Structure(
[1, 0, 0, 0, 1, 0, 0, 0, 1],
["I"],
[[0, 0, 0]],
site_properties={"magmom": [[0, 0, 1]]},
)
@pytest.mark.parametrize(
"input_set",
[MPRelaxSet, MPHSERelaxSet, MVLRelax52Set, MPAbsorptionSet],
)
def test_Yb_2_warning(input_set: VaspInputSet) -> None:
# https://github.com/materialsproject/pymatgen/pull/2972
structure = Structure(
lattice=Lattice.cubic(5),
species=("Yb", "O"),
coords=((0, 0, 0), (0.5, 0.5, 0.5)),
)
with pytest.warns(BadInputSetWarning) as record:
input_set(structure)
expected = "The structure contains Ytterbium (Yb) and this InputSet uses the Yb_2"
assert expected in str(record[0].message)
class TestSetChangeCheck(PymatgenTest):
def test_sets_changed(self):
msg = (
"WARNING! These tests will fail when you change an input set. They are included "
"as a sanity check: if you want to change an input set, please make sure to "
"notify the users for that set. For sets starting with 'MVL' this is @shyuep, for "
"sets starting with 'MP' this is @shyuep and @mkhorton. "
)
input_sets = glob(f"{MODULE_DIR}/*.yaml")
hashes = {}
for input_set in input_sets:
with open(input_set) as file:
text = file.read().encode("utf-8")
name = os.path.basename(input_set)
hashes[name] = hashlib.sha1(text).hexdigest()
known_hashes = {
"MVLGWSet.yaml": "104ae93c3b3be19a13b0ee46ebdd0f40ceb96597",
"MVLRelax52Set.yaml": "4cfc6b1bd0548e45da3bde4a9c65b3249da13ecd",
"MPHSERelaxSet.yaml": "0d0d96a620461071cfd416ec9d5d6a8d2dfd0855",
"VASPIncarBase.yaml": "19762515f8deefb970f2968fca48a0d67f7964d4",
"MPSCANRelaxSet.yaml": "2d31ee637cb5d4d96f2e0aba3772a52cbcceb348",
"MPRelaxSet.yaml": "f2949cdc5dc8cd0bee6d39a5df0d6a6b7c144821",
"MITRelaxSet.yaml": "1a0970f8cad9417ec810f7ab349dc854eaa67010",
"vdW_parameters.yaml": "04bb09bb563d159565bcceac6a11e8bdf0152b79",
"MPAbsorptionSet.yaml": "5931e1cb3cf8ba809b3d4f4a5960d728c682adf1",
"MatPESStaticSet.yaml": "6c4e529649e39925cc316d90ff03bd30b4504684",
"PBE54Base.yaml": "ec317781a7f344beb54c17a228db790c0eb49282",
}
assert hashes == known_hashes, msg
for input_set in hashes:
assert hashes[input_set] == known_hashes[input_set], msg
class TestDictSet(PymatgenTest):
@classmethod
def setUpClass(cls):
filepath = f"{TEST_FILES_DIR}/POSCAR"
poscar = Poscar.from_file(filepath)
cls.structure = poscar.structure
def test_as_dict(self):
# https://github.com/materialsproject/pymatgen/pull/3031
dict_set = DictSet(self.structure, config_dict={"INCAR": {}}, user_potcar_functional="PBE_54")
assert {*dict_set.as_dict()} >= {
"structure",
"config_dict",
"user_incar_settings",
"user_kpoints_settings",
"user_potcar_settings",
}
assert dict_set.potcar_functional == dict_set.user_potcar_functional
class TestMITMPRelaxSet(PymatgenTest):
@classmethod
def setUpClass(cls):
cls.set = MITRelaxSet
cls.mp_set = MPRelaxSet
cls.monkeypatch = MonkeyPatch()
filepath = f"{TEST_FILES_DIR}/POSCAR"
poscar = Poscar.from_file(filepath)
cls.structure = poscar.structure
cls.coords = [[0, 0, 0], [0.75, 0.5, 0.75]]
cls.lattice = Lattice([[3.8401979337, 0, 0], [1.9200989668, 3.3257101909, 0], [0, -2.2171384943, 3.1355090603]])
cls.mit_set = cls.set(cls.structure)
cls.mit_set_unsorted = cls.set(cls.structure, sort_structure=False)
cls.mp_set = MPRelaxSet(cls.structure)
def test_metal_check(self):
structure = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3), ["Cu"], [[0, 0, 0]])
with pytest.warns(
BadInputSetWarning,
match="Relaxation of likely metal with ISMEAR < 1 detected. See VASP recommendations on ISMEAR for metals.",
) as warns:
vis = self.set(structure)
_ = vis.incar
assert len(warns) == 1
def test_poscar(self):
structure = Structure(self.lattice, ["Fe", "Mn"], self.coords)
mit_param_set = self.set(structure, sort_structure=False)
s_unsorted = mit_param_set.poscar.structure
mit_param_set = self.set(structure, sort_structure=True)
s_sorted = mit_param_set.poscar.structure
assert s_unsorted[0].specie.symbol == "Fe"
assert s_sorted[0].specie.symbol == "Mn"
def test_potcar_symbols(self):
coords = []
coords.append([0, 0, 0])
coords.append([0.75, 0.5, 0.75])
coords.append([0.75, 0.25, 0.75])
lattice = Lattice([[3.8401979337, 0, 0], [1.9200989668, 3.3257101909, 0], [0, -2.2171384943, 3.1355090603]])
structure = Structure(lattice, ["P", "Fe", "O"], coords)
mit_param_set = self.set(structure)
syms = mit_param_set.potcar_symbols
assert syms == ["Fe", "P", "O"]
param_set = MPRelaxSet(structure, sort_structure=False)
syms = param_set.potcar_symbols
assert syms == ["P", "Fe_pv", "O"]
def test_potcar_validation(self):
structure = Structure(self.lattice, ["P", "Fe"], self.coords)
# Use pytest's monkeypatch to temporarily point pymatgen to a directory
# containing the wrong POTCARs (LDA potcars in a PBE directory)
with self.monkeypatch.context() as m:
m.setitem(SETTINGS, "PMG_VASP_PSP_DIR", str(f"{TEST_FILES_DIR}/wrong_potcars"))
with pytest.warns(BadInputSetWarning, match="not known by pymatgen"):
_ = self.set(structure).potcar
def test_potcar_special_defaults(self):
# https://github.com/materialsproject/pymatgen/pull/3022
for user_potcar_settings in [{"Fe": "Fe_pv"}, {"W": "W_pv"}, None]:
for species in [("W", "W"), ("Fe", "W"), ("Fe", "Fe")]:
struct = Structure(lattice=Lattice.cubic(3), species=species, coords=[[0, 0, 0], [0.5, 0.5, 0.5]])
relax_set = MPRelaxSet(
structure=struct, user_potcar_functional="PBE_54", user_potcar_settings=user_potcar_settings
)
expected = { # noqa: SIM222
**({"W": "W_sv"} if "W" in struct.symbol_set else {}),
**(user_potcar_settings or {}),
} or None
assert relax_set.user_potcar_settings == expected
@skip_if_no_psp_dir
def test_lda_potcar(self):
structure = Structure(self.lattice, ["P", "Fe"], self.coords)
p = self.set(structure, user_potcar_functional="LDA").potcar
assert p.functional == "LDA"
@skip_if_no_psp_dir
def test_nelect(self):
coords = [[0] * 3, [0.5] * 3, [0.75] * 3]
lattice = Lattice.cubic(4)
struct = Structure(lattice, ["Si", "Si", "Fe"], coords)
assert self.set(struct).nelect == 16
# Check that it works even when oxidation states are present. Was a bug
# previously.
struct = Structure(lattice, ["Si4+", "Si4+", "Fe2+"], coords)
assert self.set(struct).nelect == 16
assert MPRelaxSet(struct).nelect == 22
# Check that it works for disordered structure. Was a bug previously
struct = Structure(lattice, ["Si4+", "Fe2+", "Si4+"], coords)
assert self.set(struct).nelect == 16
assert MPRelaxSet(struct).nelect == 22
@skip_if_no_psp_dir
def test_estimate_nbands(self):
# estimate_nbands is a function of n_elect, n_ions, magmom, non-collinearity of magnetism, and n_par
coords = [[0] * 3, [0.5] * 3, [0.75] * 3]
lattice = Lattice.cubic(4)
# pure Si
struct = Structure(lattice, ["Si", "Si", "Si"], coords)
assert self.set(struct).estimate_nbands() == 11
assert MPRelaxSet(struct).estimate_nbands() == 11
# Si + Fe
struct = Structure(lattice, ["Si", "Si", "Fe"], coords)
assert self.set(struct).estimate_nbands() == 15
assert MPRelaxSet(struct).estimate_nbands() == 18
# Si + Fe with NPAR = 4
uis = {"NPAR": 4}
assert self.set(struct, user_incar_settings=uis).estimate_nbands() == approx(16)
assert MPRelaxSet(struct, user_incar_settings=uis).estimate_nbands() == approx(20)
# Si + Fe with noncollinear magnetism turned on
uis = {"LNONCOLLINEAR": True}
assert self.set(struct, user_incar_settings=uis).estimate_nbands() == approx(30)
assert MPRelaxSet(struct, user_incar_settings=uis).estimate_nbands() == approx(36)
@skip_if_no_psp_dir
def test_get_incar(self):
incar = self.mp_set.incar
assert incar["LDAUU"] == [5.3, 0, 0]
assert incar["EDIFF"] == approx(0.0012)
incar = self.mit_set.incar
assert incar["LDAUU"] == [4.0, 0, 0]
assert incar["EDIFF"] == approx(1e-5)
si = 14
coords = []
coords.append(np.array([0, 0, 0]))
coords.append(np.array([0.75, 0.5, 0.75]))
# Silicon structure for testing.
lattice = Lattice(
[[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]
)
struct = Structure(lattice, [si, si], coords)
incar = MPRelaxSet(struct).incar
assert "LDAU" not in incar
coords = []
coords.append([0, 0, 0])
coords.append([0.75, 0.5, 0.75])
lattice = Lattice(
[[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]
)
struct = Structure(lattice, ["Fe", "Mn"], coords)
incar = MPRelaxSet(struct).incar
assert "LDAU" not in incar
# check fluorides
struct = Structure(lattice, ["Fe", "F"], coords)
incar = MPRelaxSet(struct).incar
assert incar["LDAUU"] == [5.3, 0]
assert incar["MAGMOM"] == [5, 0.6]
struct = Structure(lattice, ["Fe", "F"], coords)
incar = self.set(struct).incar
assert incar["LDAUU"] == [4.0, 0]
# This seems counterintuitive at first, but even if the prior INCAR has a MAGMOM flag,
# because the structure has no site properties, the default MAGMOM is assigned from the
# config dictionary.
struct = Structure(lattice, ["Fe", "F"], coords)
incar = MPStaticSet(struct, prev_incar=f"{TEST_FILES_DIR}/INCAR").incar
assert incar["MAGMOM"] == [5, 0.6]
# Make sure this works with species.
struct = Structure(lattice, ["Fe2+", "O2-"], coords)
incar = MPRelaxSet(struct).incar
assert incar["LDAUU"] == [5.3, 0]
struct = Structure(lattice, ["Fe", "Mn"], coords, site_properties={"magmom": (5.2, -4.5)})
incar = MPRelaxSet(struct).incar
assert incar["MAGMOM"] == [-4.5, 5.2]
incar = self.set(struct, sort_structure=False).incar
assert incar["MAGMOM"] == [5.2, -4.5]
struct = Structure(lattice, [Species("Fe2+", spin=4.1), "Mn"], coords)
incar = MPRelaxSet(struct).incar
assert incar["MAGMOM"] == [5, 4.1]
struct = Structure(lattice, ["Mn3+", "Mn4+"], coords)
incar = self.set(struct).incar
assert incar["MAGMOM"] == [4, 3]
user_set = MPRelaxSet(struct, user_incar_settings={"MAGMOM": {"Fe": 10, "S": -5, "Mn3+": 100}})
assert user_set.incar["MAGMOM"] == [100, 0.6]
no_encut_set = MPRelaxSet(struct, user_incar_settings={"ENCUT": None})
assert "ENCUT" not in no_encut_set.incar
# sulfide vs sulfate test
coords = []
coords.append([0, 0, 0])
coords.append([0.75, 0.5, 0.75])
coords.append([0.25, 0.5, 0])
struct = Structure(lattice, ["Fe", "Fe", "S"], coords)
incar = self.set(struct).incar
assert incar["LDAUU"] == [1.9, 0]
# Make sure MP sulfides are ok.
assert "LDAUU" not in MPRelaxSet(struct).incar
struct = Structure(lattice, ["Fe", "S", "O"], coords)
incar = self.set(struct).incar
assert incar["LDAUU"] == [4.0, 0, 0]
# Make sure MP sulfates are ok.
assert MPRelaxSet(struct).incar["LDAUU"] == [5.3, 0, 0]
# test for default LDAUU value
user_set_ldauu_fallback = MPRelaxSet(struct, user_incar_settings={"LDAUU": {"Fe": 5.0, "S": 0}})
assert user_set_ldauu_fallback.incar["LDAUU"] == [5.0, 0, 0]
# Expected to be oxide (O is the most electronegative atom)
struct = Structure(lattice, ["Fe", "O", "S"], coords)
incar = self.set(struct).incar
assert incar["LDAUU"] == [4.0, 0, 0]
# Expected to be chloride (Cl is the most electronegative atom)
struct = Structure(lattice, ["Fe", "Cl", "S"], coords)
incar = self.set(struct, user_incar_settings={"LDAU": True}).incar
assert "LDAUU" not in incar # LDAU = False
# User set a compound to be sulfide by specifying values of "LDAUL" etc.
struct = Structure(lattice, ["Fe", "Cl", "S"], coords)
incar = self.set(
struct,
user_incar_settings={"LDAU": True, "LDAUL": {"Fe": 3}, "LDAUU": {"Fe": 1.8}},
).incar
assert incar["LDAUL"] == [3.0, 0, 0]
assert incar["LDAUU"] == [1.8, 0, 0]
# test that van-der-Waals parameters are parsed correctly
incar = self.set(struct, vdw="optB86b").incar
assert incar["GGA"] == "Mk"
assert incar["LUSE_VDW"]
assert incar["PARAM1"] == 0.1234
# Test that NELECT is updated when a charge is present
si = 14
coords = []
coords.append(np.array([0, 0, 0]))
coords.append(np.array([0.75, 0.5, 0.75]))
# Silicon structure for testing.
lattice = Lattice(
[[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]
)
struct = Structure(lattice, [si, si], coords, charge=1)
mpr = MPRelaxSet(struct, use_structure_charge=True)
assert mpr.incar["NELECT"] == 7, "NELECT not properly set for nonzero charge"
# test that NELECT does not get set when use_structure_charge = False
mpr = MPRelaxSet(struct, use_structure_charge=False)
assert "NELECT" not in mpr.incar, "NELECT should not be set when use_structure_charge is False"
struct = Structure(lattice, ["Co", "O"], coords)
mpr = MPRelaxSet(struct)
assert mpr.incar["MAGMOM"] == [0.6, 0.6]
struct = Structure(lattice, ["Co4+", "O"], coords)
mpr = MPRelaxSet(struct)
assert mpr.incar["MAGMOM"] == [1, 0.6]
# test passing user_incar_settings and user_kpoint_settings of None
for set_cls in [MPRelaxSet, MPStaticSet, MPNonSCFSet]:
mp_set = set_cls(struct, user_incar_settings=None, user_kpoints_settings=None)
assert mp_set.kpoints is not None
assert mp_set.incar is not None
def test_get_kpoints(self):
kpoints = MPRelaxSet(self.structure).kpoints
assert kpoints.kpts == [[2, 4, 5]]
assert kpoints.style == Kpoints.supported_modes.Gamma
kpoints = MPRelaxSet(self.structure, user_kpoints_settings={"reciprocal_density": 1000}).kpoints
assert kpoints.kpts == [[6, 10, 13]]
assert kpoints.style == Kpoints.supported_modes.Gamma
kpoints_obj = Kpoints(kpts=[[3, 3, 3]])
kpoints_return = MPRelaxSet(self.structure, user_kpoints_settings=kpoints_obj).kpoints
assert kpoints_return.kpts == [[3, 3, 3]]
kpoints = self.mit_set.kpoints
assert kpoints.kpts == [[25]]
assert kpoints.style == Kpoints.supported_modes.Automatic
recip_param_set = MPRelaxSet(self.structure, force_gamma=True)
recip_param_set.kpoints_settings = {"reciprocal_density": 40}
kpoints = recip_param_set.kpoints
assert kpoints.kpts == [[2, 4, 5]]
assert kpoints.style == Kpoints.supported_modes.Gamma
@skip_if_no_psp_dir
def test_get_vasp_input(self):
d = self.mit_set.get_vasp_input()
assert d["INCAR"]["ISMEAR"] == -5
struct = self.structure.copy()
struct.make_supercell(4)
paramset = MPRelaxSet(struct)
d = paramset.get_vasp_input()
assert d["INCAR"]["ISMEAR"] == 0
def test_MPMetalRelaxSet(self):
mp_metal_set = MPMetalRelaxSet(self.get_structure("Sn"))
incar = mp_metal_set.incar
assert incar["ISMEAR"] == 1
assert incar["SIGMA"] == 0.2
kpoints = mp_metal_set.kpoints
assert_allclose(kpoints.kpts[0], [5, 5, 5])
def test_as_from_dict(self):
mit_set = self.set(self.structure)
mp_set = MPRelaxSet(self.structure)
mp_user_set = MPRelaxSet(
self.structure,
user_incar_settings={"MAGMOM": {"Fe": 10, "S": -5, "Mn3+": 100}},
)
dct = mit_set.as_dict()
val = dec.process_decoded(dct)
assert val._config_dict["INCAR"]["LDAUU"]["O"]["Fe"] == 4
dct = mp_set.as_dict()
val = dec.process_decoded(dct)
assert val._config_dict["INCAR"]["LDAUU"]["O"]["Fe"] == 5.3
dct = mp_user_set.as_dict()
val = dec.process_decoded(dct)
# assert isinstance(val, MPVaspInputSet)
assert val.user_incar_settings["MAGMOM"] == {"Fe": 10, "S": -5, "Mn3+": 100}
def test_hubbard_off_and_ediff_override(self):
input_set = MPRelaxSet(self.structure, user_incar_settings={"LDAU": False, "EDIFF": 1e-10})
assert "LDAUU" not in input_set.incar
assert input_set.incar["EDIFF"] == 1e-10
# after testing, we have determined LMAXMIX should still be 4 for d-block
# even if U is turned off (thanks Andrew Rosen for reporting)
assert input_set.incar["LMAXMIX"] == 4
def test_incar_lmaxmix(self):
# https://github.com/materialsproject/pymatgen/issues/3040
# structure containing neither f- nor d-electrons
structure_f = self.get_structure("Si")
assert "LMAXMIX" not in MPRelaxSet(structure_f).incar
# structure containing d-electrons but no f-electrons
structure_d = self.get_structure("LiFePO4")
assert MPRelaxSet(structure_d).incar["LMAXMIX"] == 4
# structure containing f-electrons but no d-electrons
structure_f = structure_d.copy()
structure_f.replace_species({"Fe": "La"})
assert MPRelaxSet(structure_f).incar["LMAXMIX"] == 6
# structure containing f- and d-electrons
structure_f_and_d = structure_d.copy()
structure_f_and_d.replace_species({"P": "Ce"})
assert MPRelaxSet(structure_f_and_d).incar["LMAXMIX"] == 6
# explicit LMAXMIX in settings overrides automatic selection
structure_override = Structure(
lattice=Lattice.cubic(3),
species=("Fe", "Fe"),
coords=((0, 0, 0), (0.5, 0.5, 0.5)),
)
set_override = MPRelaxSet(structure_override, user_incar_settings={"LMAXMIX": 3})
assert set_override.incar["LMAXMIX"] == 3
@skip_if_no_psp_dir
def test_write_input(self):
vasp_files = {"INCAR", "KPOINTS", "POSCAR", "POTCAR"}
self.mit_set.write_input(self.tmp_path)
assert {*os.listdir(self.tmp_path)} == vasp_files
self.mit_set.write_input(self.tmp_path, include_cif=True)
assert {*os.listdir(self.tmp_path)} == {*vasp_files, "Fe4P4O16.cif"}
@skip_if_no_psp_dir
def test_write_input_potcar_spec(self):
self.mit_set.write_input(self.tmp_path, potcar_spec=True)
assert {*os.listdir(self.tmp_path)} == {"INCAR", "KPOINTS", "POSCAR", "POTCAR.spec"}
@skip_if_no_psp_dir
def test_user_potcar_settings(self):
vis = MPRelaxSet(self.structure, user_potcar_settings={"Fe": "Fe"})
potcar = vis.potcar
assert potcar.symbols == ["Fe", "P", "O"]
@skip_if_no_psp_dir
def test_valid_magmom_struct(self):
# First test the helper function
struct = self.structure.copy()
get_valid_magmom_struct(structure=struct, inplace=True, spin_mode="v")
props = [site.properties for site in struct]
assert props == [{"magmom": [1.0, 1.0, 1.0]}] * len(props)
struct = self.structure.copy()
get_valid_magmom_struct(structure=struct, inplace=True, spin_mode="s")
props = [site.properties for site in struct]
assert props == [{"magmom": 1.0}] * len(props)
struct.insert(0, "Li", [0, 0, 0])
get_valid_magmom_struct(structure=struct, inplace=True, spin_mode="a")
props = [site.properties for site in struct]
assert props == [{"magmom": 1.0}] * len(props)
struct = self.structure.copy()
get_valid_magmom_struct(structure=struct, inplace=True, spin_mode="v")
struct.insert(0, "Li", [0, 0, 0], properties={"magmom": 10.0})
with pytest.raises(TypeError) as exc:
get_valid_magmom_struct(structure=struct, inplace=True, spin_mode="a")
assert "Magmom type conflict" in str(exc.value)
# Test the behavior of MPRelaxSet to automatically fill in the missing magmom
struct = self.structure.copy()
get_valid_magmom_struct(structure=struct, inplace=True, spin_mode="s")
struct.insert(0, "Li", [0, 0, 0])
vis = MPRelaxSet(struct, user_potcar_settings={"Fe": "Fe"}, validate_magmom=False)
with pytest.raises(TypeError, match=r"float\(\) argument must be a string or a (real )?number, not 'NoneType'"):
print(vis.get_vasp_input())
vis = MPRelaxSet(struct, user_potcar_settings={"Fe": "Fe"}, validate_magmom=True)
assert vis.get_vasp_input()["INCAR"]["MAGMOM"] == [1.0] * len(struct)
# Test the behavior of constraining the net magnetic moment with a non-integer
struct = self.structure.copy()
with pytest.warns(UserWarning, match="constrain_total_magmom"):
vis = MPRelaxSet(
struct,
user_incar_settings={"MAGMOM": {"Fe": 5.1}},
user_potcar_settings={"Fe": "Fe"},
constrain_total_magmom=True,
)
vis.incar.items()
class TestMPStaticSet(PymatgenTest):
def setUp(self):
self.set = MPStaticSet
def test_init(self):
prev_run = f"{TEST_FILES_DIR}/relaxation"
vis = self.set.from_prev_calc(prev_calc_dir=prev_run)
assert vis.incar["NSW"] == 0
# Check that the ENCUT has been inherited.
assert vis.incar["ENCUT"] == 600
assert vis.kpoints.style == Kpoints.supported_modes.Monkhorst
# Check as from dict.
vis = self.set.from_dict(vis.as_dict())
assert vis.incar["NSW"] == 0
# Check that the ENCUT has been inherited.
assert vis.incar["ENCUT"] == 600
assert vis.kpoints.style == Kpoints.supported_modes.Monkhorst
non_prev_vis = self.set(vis.structure, user_incar_settings={"LORBIT": 12, "LWAVE": True})
assert non_prev_vis.incar["NSW"] == 0
# Check that the ENCUT and Kpoints style has NOT been inherited.
assert non_prev_vis.incar["ENCUT"] == 520
# Check that user incar settings are applied.
assert non_prev_vis.incar["LORBIT"] == 12
assert non_prev_vis.incar["LWAVE"]
assert non_prev_vis.kpoints.style == Kpoints.supported_modes.Gamma
v2 = self.set.from_dict(non_prev_vis.as_dict())
assert v2.incar["ENCUT"] == 520
# Check that user incar settings are applied.
assert v2.incar["LORBIT"] == 12
leps_vis = self.set.from_prev_calc(prev_calc_dir=prev_run, lepsilon=True)
assert leps_vis.incar["LEPSILON"]
assert leps_vis.incar["IBRION"] == 8
assert leps_vis.incar["EDIFF"] == 1e-5
assert "NPAR" not in leps_vis.incar
assert "NSW" not in leps_vis.incar
assert non_prev_vis.kpoints.kpts == [[11, 10, 10]]
non_prev_vis = self.set(vis.structure, reciprocal_density=200)
assert non_prev_vis.kpoints.kpts == [[14, 12, 12]]
# Check LCALCPOL flag
lcalc_pol_vis = self.set.from_prev_calc(prev_calc_dir=prev_run, lcalcpol=True)
assert lcalc_pol_vis.incar["LCALCPOL"]
# Check warning if LASPH is set to False for meta-GGAs/hybrids/+U/vdW
with pytest.warns(BadInputSetWarning, match=r"LASPH"):
vis = self.set(vis.structure, user_incar_settings={"METAGGA": "M06L", "LASPH": False})
vis.incar.items()
with pytest.warns(BadInputSetWarning, match=r"LASPH"):
vis = self.set(vis.structure, user_incar_settings={"LHFCALC": True, "LASPH": False})
vis.incar.items()
with pytest.warns(BadInputSetWarning, match=r"LASPH"):
vis = self.set(vis.structure, user_incar_settings={"LUSE_VDW": True, "LASPH": False})
vis.incar.items()
with pytest.warns(BadInputSetWarning, match=r"LASPH"):
dummy_struc = Structure(
lattice=[[0, 2, 2], [2, 0, 2], [2, 2, 0]],
species=["Fe", "O"],
coords=[[0, 0, 0], [0.5, 0.5, 0.5]],
)
vis = self.set(dummy_struc, user_incar_settings={"LDAU": True, "LASPH": False})
vis.incar.items()
def test_user_incar_kspacing(self):
# Make sure user KSPACING settings properly overrides KPOINTS.
si = self.get_structure("Si")
vis = self.set(si, user_incar_settings={"KSPACING": 0.22})
assert vis.incar["KSPACING"] == 0.22
assert vis.kpoints is None
def test_kspacing_override(self):
# If KSPACING is set and user_kpoints_settings are given,
# make sure the user_kpoints_settings override KSPACING
si = self.get_structure("Si")
vis = self.set(
si,
user_incar_settings={"KSPACING": 0.22},
user_kpoints_settings={"reciprocal_density": 1000},
)
assert vis.incar.get("KSPACING") is None
assert isinstance(vis.kpoints, Kpoints)
def test_override_from_prev_calc(self):
# test override_from_prev
prev_run = f"{TEST_FILES_DIR}/relaxation"
vis = self.set(dummy_structure)
vis.override_from_prev_calc(prev_calc_dir=prev_run)
assert vis.incar["NSW"] == 0
assert vis.incar["ENCUT"] == 600
assert vis.kpoints.style == Kpoints.supported_modes.Monkhorst
# Check LCALCPOL flag
lcalcpol_vis = self.set(dummy_structure, lcalcpol=True)
lcalcpol_vis = lcalcpol_vis.override_from_prev_calc(prev_calc_dir=prev_run)
assert lcalcpol_vis.incar["LCALCPOL"]
def test_standardize_structure(self):
sga = SpacegroupAnalyzer(self.get_structure("Si"))
original_structure = sga.get_conventional_standard_structure()
sm = StructureMatcher(primitive_cell=False, scale=False)
vis = self.set(original_structure)
assert sm.fit(vis.structure, original_structure)
vis = self.set(original_structure, standardize=True)
assert not sm.fit(vis.structure, original_structure)
def test_write_input_zipped(self):
vis = self.set(self.get_structure("Si"))
vis.write_input(output_dir=self.tmp_path, potcar_spec=True, zip_output=True)
assert os.path.isfile(f"{self.tmp_path}/MPStaticSet.zip")
with ZipFile(f"{self.tmp_path}/MPStaticSet.zip", "r") as zip:
contents = zip.namelist()
assert set(contents).issuperset({"INCAR", "POSCAR", "POTCAR.spec", "KPOINTS"})
spec = zip.open("POTCAR.spec", "r").read().decode()
assert spec == "Si"
def test_grid_size_from_struct(self):
# TODO grab a bunch_of_calculations store as a list of tuples
# (structure, ngx, ..., ngxf, ...) where all the grid size values are generated by vasp
# check that the code produces the same grid sizes
fname = f"{TEST_FILES_DIR}/grid_data_files/vasp_inputs_for_grid_check.json"
parsed_vasp_data = loadfn(fname)
for tt in parsed_vasp_data:
ng = [tt["input"]["parameters"][ik] for ik in ["NGX", "NGY", "NGZ"]]
ngf = [tt["input"]["parameters"][ik] for ik in ["NGXF", "NGYF", "NGZF"]]
struct = tt["input"]["structure"]
static_set = self.set(struct)
matched = static_set.calculate_ng() == (ng, ngf)
assert matched
class TestMatPESStaticSet(PymatgenTest):
def setUp(self):
self.struct = Structure.from_file(f"{TEST_FILES_DIR}/POSCAR")
self.prev_incar = Incar.from_file(f"{TEST_FILES_DIR}/INCAR")
def test_init_default(self):
default = MatPESStaticSet(self.struct)
incar = default.incar
assert incar["ALGO"] == "Normal"
assert incar["EDIFF"] == 1.0e-05
assert incar["ENAUG"] == 1360
assert incar["ENCUT"] == 680
assert incar["GGA"] == "Pe"
assert incar["ISMEAR"] == 0
assert incar["ISPIN"] == 2
assert incar["KSPACING"] == 0.22
assert incar["LAECHG"]
assert incar["LASPH"]
assert incar["LCHARG"]
assert incar["LMIXTAU"]
assert incar.get("LDAU") is None
assert incar["LORBIT"] == 11
assert incar["LREAL"] == "Auto"
assert not incar["LWAVE"]
assert incar["NELM"] == 200
assert incar["NSW"] == 0
assert incar["PREC"] == "Accurate"
assert incar["SIGMA"] == 0.05
# test POTCAR files are default PBE_54 PSPs and functional
assert default.potcar_symbols == ["Fe_pv", "P", "O"]
assert default.potcar.functional == "PBE_54"
assert default.kpoints is None
def test_init_with_prev_incar(self):
default_prev = MatPESStaticSet(structure=self.struct, prev_incar=self.prev_incar)
incar = default_prev.incar
# test if prev_incar is used.
assert incar["NPAR"] == 8
assert not incar["LSCALU"]
# test if default in MatPESStaticSet is prioritized.
assert incar["ALGO"] == "Normal"
assert incar["EDIFF"] == 1.0e-05
assert incar["ENAUG"] == 1360
assert incar["ENCUT"] == 680
assert incar["GGA"] == "Pe"
assert incar["ISMEAR"] == 0
assert incar["ISPIN"] == 2
assert incar["KSPACING"] == 0.22
assert incar["LAECHG"]
assert incar["LASPH"]
assert incar["LCHARG"]
assert incar["LMIXTAU"]
assert incar.get("LDAU") is None
assert incar["LORBIT"] == 11
assert incar["LREAL"] == "Auto"
assert not incar["LWAVE"]
assert incar["NELM"] == 200
assert incar["NSW"] == 0
assert incar["PREC"] == "Accurate"
assert incar["SIGMA"] == 0.05
# test POTCAR files are default PBE_54 PSPs and functional
assert default_prev.potcar_symbols == ["Fe_pv", "P", "O"]
assert default_prev.potcar.functional == "PBE_54"
assert default_prev.kpoints is None
def test_init_r2scan(self):
scan = MatPESStaticSet(self.struct, functional="R2SCAN")
incar_scan = scan.incar
assert incar_scan["METAGGA"] == "R2scan"
assert incar_scan.get("GGA") is None
assert incar_scan["ALGO"] == "All"
assert incar_scan.get("LDAU") is None
# test POTCAR files are default PBE_54 PSPs and functional
assert scan.potcar_symbols == ["Fe_pv", "P", "O"]
assert scan.potcar.functional == "PBE_54"
assert scan.kpoints is None
def test_potcar(self):
default = MatPESStaticSet(self.struct)
default_prev = MatPESStaticSet(structure=self.struct, prev_incar=self.prev_incar)
scan = MatPESStaticSet(self.struct, functional="R2SCAN")
assert default.potcar.functional == "PBE_54"
assert default_prev.potcar.functional == "PBE_54"
assert scan.potcar.functional == "PBE_54"
functional = "LDA"
with pytest.raises(
Warning, match=f"{functional} is not supported. The supported functionals are PBE_54 and R2SCAN."
):
MatPESStaticSet(self.struct, functional=functional)
class TestMPNonSCFSet(PymatgenTest):
def setUp(self):
self.set = MPNonSCFSet
@skip_if_no_psp_dir
def test_init(self):
prev_run = f"{TEST_FILES_DIR}/relaxation"
# check boltztrap mode
vis = self.set.from_prev_calc(prev_calc_dir=prev_run, mode="Boltztrap")
assert vis.incar["ISMEAR"] == 0
# check uniform mode
vis = self.set.from_prev_calc(prev_calc_dir=prev_run, mode="Uniform")
assert vis.incar["ISMEAR"] == -5
assert vis.incar["ISYM"] == 2
# check uniform mode with automatic nedos
vis = self.set.from_prev_calc(prev_calc_dir=prev_run, mode="Uniform", nedos=0)
assert vis.incar["NEDOS"] == 12217
# test line mode
vis = self.set.from_prev_calc(
prev_calc_dir=prev_run,
mode="Line",
copy_chgcar=False,
user_incar_settings={"SIGMA": 0.025},
)
assert vis.incar["NSW"] == 0
# Check that the ENCUT has been inherited.
assert vis.incar["ENCUT"] == 600
# Check that the user_incar_settings works
assert vis.incar["SIGMA"] == 0.025
assert vis.kpoints.style == Kpoints.supported_modes.Reciprocal
# Check as from dict.
vis = self.set.from_dict(vis.as_dict())
assert vis.incar["NSW"] == 0
# Check that the ENCUT has been inherited.
assert vis.incar["ENCUT"] == 600
assert vis.kpoints.style == Kpoints.supported_modes.Reciprocal
vis.write_input(self.tmp_path)
assert not os.path.isfile(f"{self.tmp_path}/CHGCAR")
vis = self.set.from_prev_calc(prev_calc_dir=prev_run, mode="Line", copy_chgcar=True)
# check ISMEAR set correctly for line mode
assert vis.incar["ISMEAR"] == 0
vis.write_input(self.tmp_path)
assert os.path.isfile(f"{self.tmp_path}/CHGCAR")
os.remove(f"{self.tmp_path}/CHGCAR")
vis = self.set.from_prev_calc(prev_calc_dir=prev_run, standardize=True, mode="Line", copy_chgcar=True)
vis.write_input(self.tmp_path)
assert not os.path.isfile(f"{self.tmp_path}/CHGCAR")
@skip_if_no_psp_dir
def test_override_from_prev(self):
prev_run = f"{TEST_FILES_DIR}/relaxation"
# test override_from_prev
vis = self.set(dummy_structure, mode="Boltztrap")
vis.override_from_prev_calc(prev_calc_dir=prev_run)
assert vis.incar["ISMEAR"] == 0
vis = self.set(dummy_structure, mode="Uniform")
vis.override_from_prev_calc(prev_calc_dir=prev_run)
assert vis.incar["ISMEAR"] == -5
assert vis.incar["ISYM"] == 2
vis = self.set(dummy_structure, mode="Uniform", nedos=0)
vis.override_from_prev_calc(prev_calc_dir=prev_run)
assert vis.incar["NEDOS"] == 12217
# test line mode
vis = self.set(
dummy_structure,
mode="Line",
copy_chgcar=False,
user_incar_settings={"SIGMA": 0.025},
)
vis.override_from_prev_calc(prev_calc_dir=prev_run)
assert vis.incar["NSW"] == 0
assert vis.incar["ENCUT"] == 600
assert vis.incar["SIGMA"] == 0.025
assert vis.kpoints.style == Kpoints.supported_modes.Reciprocal
vis = self.set(dummy_structure, mode="Line", copy_chgcar=True)
vis.override_from_prev_calc(prev_calc_dir=prev_run)
assert vis.incar["ISMEAR"] == 0
vis.write_input(self.tmp_path)
assert os.path.isfile(f"{self.tmp_path}/CHGCAR")
os.remove(f"{self.tmp_path}/CHGCAR")
vis = self.set(dummy_structure, standardize=True, mode="Line", copy_chgcar=True)
vis.override_from_prev_calc(prev_calc_dir=prev_run)
vis.write_input(self.tmp_path)
assert not os.path.isfile(f"{self.tmp_path}/CHGCAR")
def test_kpoints(self):
# test k-points are generated in the correct format
prev_run = f"{TEST_FILES_DIR}/relaxation"
vis = self.set.from_prev_calc(prev_calc_dir=prev_run, mode="Uniform", copy_chgcar=False)
assert np.array(vis.kpoints.kpts).shape == (1, 3)
vis = self.set.from_prev_calc(prev_calc_dir=prev_run, mode="Line", copy_chgcar=False)
assert np.array(vis.kpoints.kpts).shape != (1, 3)
vis = self.set.from_prev_calc(prev_calc_dir=prev_run, mode="Boltztrap", copy_chgcar=False)
assert np.array(vis.kpoints.kpts).shape != (1, 3)
def test_optics(self):
prev_run = f"{TEST_FILES_DIR}/relaxation"
vis = self.set.from_prev_calc(
prev_calc_dir=prev_run,
copy_chgcar=False,
optics=True,
mode="Uniform",
nedos=2001,
)
assert vis.incar["NSW"] == 0
# Check that the ENCUT has been inherited.
assert vis.incar["ENCUT"] == 600
# check NEDOS and ISMEAR set correctly
assert vis.incar["NEDOS"] == 2001
assert vis.incar["ISMEAR"] == -5
assert vis.incar["ISYM"] == 2
assert vis.incar["LOPTICS"]
assert vis.kpoints.style == Kpoints.supported_modes.Gamma
def test_user_kpoint_override(self):
user_kpoints_override = Kpoints(
style=Kpoints.supported_modes.Gamma, kpts=((1, 1, 1),)
) # the default kpoints style is reciprocal
prev_run = f"{TEST_FILES_DIR}/relaxation"
vis = self.set.from_prev_calc(
prev_calc_dir=prev_run,
copy_chgcar=False,
optics=True,
mode="Uniform",
nedos=2001,
user_kpoints_settings=user_kpoints_override,
)
assert vis.kpoints.style == Kpoints.supported_modes.Gamma
class TestMagmomLdau(PymatgenTest):
def test_structure_from_prev_run(self):
vrun = Vasprun(f"{TEST_FILES_DIR}/vasprun.xml.magmom_ldau")
structure = vrun.final_structure
poscar = Poscar(structure)
structure_decorated = get_structure_from_prev_run(vrun)
ldau_ans = {"LDAUU": [5.3, 0.0], "LDAUL": [2, 0], "LDAUJ": [0.0, 0.0]}
magmom_ans = [5.0, 5.0, 5.0, 5.0, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6]
ldau_dict = {}
for key in ("LDAUU", "LDAUJ", "LDAUL"):
if hasattr(structure_decorated[0], key.lower()):
m = {site.specie.symbol: getattr(site, key.lower()) for site in structure_decorated}
ldau_dict[key] = [m[sym] for sym in poscar.site_symbols]
magmom = [site.magmom for site in structure_decorated]
assert ldau_dict == ldau_ans
assert magmom == magmom_ans
def test_ln_magmom(self):
YAML_PATH = MODULE_DIR / "VASPIncarBase.yaml"
MAGMOM_SETTING = loadfn(YAML_PATH)["INCAR"]["MAGMOM"]
structure = Structure.from_file(f"{TEST_FILES_DIR}/La4Fe4O12.cif")