-
Notifications
You must be signed in to change notification settings - Fork 102
/
handlers.py
1848 lines (1593 loc) · 84.6 KB
/
handlers.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
"""
This module implements specific error handlers for VASP runs. These handlers
try to detect common errors in vasp runs and attempt to fix them on the fly
by modifying the input files.
"""
from __future__ import annotations
import datetime
import logging
import multiprocessing
import os
import re
import shutil
import time
import warnings
from collections import Counter
from math import prod
from typing import ClassVar
import numpy as np
from monty.dev import deprecated
from monty.io import zopen
from monty.os.path import zpath
from monty.serialization import loadfn
from pymatgen.core.structure import Structure
from pymatgen.io.vasp.inputs import Incar, Kpoints, Poscar, VaspInput
from pymatgen.io.vasp.outputs import Oszicar
from pymatgen.io.vasp.sets import MPScanRelaxSet
from pymatgen.transformations.standard_transformations import SupercellTransformation
from custodian.ansible.actions import FileActions
from custodian.ansible.interpreter import Modder
from custodian.custodian import ErrorHandler
from custodian.utils import backup
from custodian.vasp.interpreter import VaspModder
from custodian.vasp.io import load_outcar, load_vasprun
__author__ = (
"Shyue Ping Ong, William Davidson Richards, Anubhav Jain, Wei Chen, "
"Stephen Dacek, Andrew Rosen, Janosh Riebesell"
)
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "ongsp@ucsd.edu"
__status__ = "Beta"
__date__ = "2/4/13"
VASP_BACKUP_FILES = {
"INCAR",
"KPOINTS",
"POSCAR",
"OUTCAR",
"CONTCAR",
"OSZICAR",
"vasprun.xml",
"vasp.out",
"std_err.txt",
}
class VaspErrorHandler(ErrorHandler):
"""
Master VaspErrorHandler class that handles a number of common errors
that occur during VASP runs.
"""
is_monitor = True
error_msgs: ClassVar = {
"tet": [
"Tetrahedron method fails",
"tetrahedron method fails",
"Fatal error detecting k-mesh",
"Fatal error: unable to match k-point",
"Routine TETIRR needs special values",
"Tetrahedron method fails (number of k-points < 4)",
"BZINTS",
],
"inv_rot_mat": ["rotation matrix was not found (increase SYMPREC)"],
"brmix": ["BRMIX: very serious problems"],
"subspacematrix": ["WARNING: Sub-Space-Matrix is not hermitian in DAV"],
"tetirr": ["Routine TETIRR needs special values"],
"incorrect_shift": ["Could not get correct shifts"],
"real_optlay": ["REAL_OPTLAY: internal error", "REAL_OPT: internal ERROR"],
"rspher": ["ERROR RSPHER"],
"dentet": ["DENTET"], # reason for this warning is that the Fermi level cannot be determined accurately
# enough by the tetrahedron method
# https://vasp.at/forum/viewtopic.php?f=3&t=416&p=4047&hilit=dentet#p4047
"too_few_bands": ["TOO FEW BANDS"],
"triple_product": ["ERROR: the triple product of the basis vectors"],
"rot_matrix": ["Found some non-integer element in rotation matrix", "SGRCON"],
"brions": ["BRIONS problems: POTIM should be increased"],
"pricel": ["internal error in subroutine PRICEL"],
"zpotrf": ["LAPACK: Routine ZPOTRF failed", "Routine ZPOTRF ZTRTRI"],
"amin": ["One of the lattice vectors is very long (>50 A), but AMIN"],
"zbrent": ["ZBRENT: fatal internal in", "ZBRENT: fatal error in bracketing"],
# Note that PSSYEVX and PDSYEVX errors are identical up to LAPACK routine:
# P<prec>SYEVX uses <prec> = S(ingle) or D(ouble) precision
"pssyevx": ["ERROR in subspace rotation PSSYEVX"],
"pdsyevx": ["ERROR in subspace rotation PDSYEVX"],
"eddrmm": ["WARNING in EDDRMM: call to ZHEGV failed"],
"edddav": ["Error EDDDAV: Call to ZHEGV failed"],
"algo_tet": ["ALGO=A and IALGO=5X tend to fail"],
"grad_not_orth": ["EDWAV: internal error, the gradient is not orthogonal"],
"nicht_konv": ["ERROR: SBESSELITER : nicht konvergent"],
"zheev": ["ERROR EDDIAG: Call to routine ZHEEV failed!"],
"eddiag": ["ERROR in EDDIAG: call to ZHEEV/ZHEEVX/DSYEV/DSYEVX failed"],
"elf_kpar": ["ELF: KPAR>1 not implemented"],
"elf_ncl": ["WARNING: ELF not implemented for non collinear case"],
"rhosyg": ["RHOSYG"],
"posmap": ["POSMAP"],
"point_group": ["group operation missing"],
"pricelv": ["PRICELV: current lattice and primitive lattice are incommensurate"],
"symprec_noise": ["determination of the symmetry of your systems shows a strong"],
"dfpt_ncore": ["PEAD routines do not work for NCORE", "remove the tag NPAR from the INCAR file"],
"bravais": ["Inconsistent Bravais lattice"],
"nbands_not_sufficient": ["number of bands is not sufficient"],
"hnform": ["HNFORM: k-point generating"],
"coef": ["while reading plane", "while reading WAVECAR"],
"set_core_wf": ["internal error in SET_CORE_WF"],
"read_error": ["Error reading item", "Error code was IERR= 5"],
}
def __init__(
self,
output_filename="vasp.out",
errors_subset_to_catch=None,
vtst_fixes=False,
**kwargs,
) -> None:
"""Initialize the handler with the output file to check.
Args:
output_filename (str): This is the file where the stdout for vasp
is being redirected. The error messages that are checked are
present in the stdout. Defaults to "vasp.out", which is the
default redirect used by :class:`custodian.vasp.jobs.VaspJob`.
errors_subset_to_catch (list): A subset of errors to catch. The
default is None, which means all supported errors are detected.
Use this to catch only a subset of supported errors.
E.g., ["eddrmm", "zheev"] will only catch the eddrmm and zheev
errors, and not others. If you wish to only exclude one or
two of the errors, you can create this list by the following lines:
subset = list(VaspErrorHandler().error_msgs)
subset.remove("eddrmm")
handler = VaspErrorHandler(errors_subset_to_catch=subset)
vtst_fixes (bool): Whether to consider VTST optimizers. Defaults to
False for compatibility purposes, but if you have VTST, you
would likely benefit from setting this to True.
**kwargs: Ignored. Added to increase signature flexibility.
"""
self.output_filename = output_filename
self.errors: set[str] = set()
self.error_count: Counter[str] = Counter()
self.errors_subset_to_catch = errors_subset_to_catch or list(VaspErrorHandler.error_msgs)
self.vtst_fixes = vtst_fixes
self.logger = logging.getLogger(type(self).__name__)
def check(self, directory="./"):
"""Check for error."""
incar = Incar.from_file(os.path.join(directory, "INCAR"))
self.errors = set()
error_msgs = set()
with zopen(os.path.join(directory, self.output_filename), mode="rt") as file:
text = file.read()
# Check for errors
for err in self.errors_subset_to_catch:
for msg in self.error_msgs[err]:
if text.find(msg) != -1:
# this checks if we want to run a charged
# computation (e.g., defects) if yes we don't
# want to kill it because there is a change in
# e-density (brmix error)
if err == "brmix" and "NELECT" in incar:
continue
self.errors.add(err)
error_msgs.add(msg)
for msg in error_msgs:
self.logger.error(msg, extra={"incar": incar.as_dict()})
return len(self.errors) > 0
def correct(self, directory="./"):
"""Perform corrections."""
backup(VASP_BACKUP_FILES | {self.output_filename}, directory=directory)
actions = []
vi = VaspInput.from_directory(directory)
if self.errors.intersection(["tet", "dentet"]):
# follow advice in this thread
# https://vasp.at/forum/viewtopic.php?f=3&t=416&p=4047&hilit=dentet#p4047
err_type = "tet" if "tet" in self.errors else "dentet"
if self.error_count[err_type] == 0:
if vi["INCAR"].get("KSPACING"):
# decrease KSPACING by 20% in each direction (approximately double no. of kpoints)
action = {"_set": {"KSPACING": vi["INCAR"].get("KSPACING") * 0.8}}
actions.append({"dict": "INCAR", "action": action})
elif vi["KPOINTS"] and vi["KPOINTS"].num_kpts < 1:
# increase KPOINTS by 20% in each direction (approximately double no. of kpoints)
new_kpts = tuple(int(round(num * 1.2, 0)) for num in vi["KPOINTS"].kpts[0])
actions.append({"dict": "KPOINTS", "action": {"_set": {"kpoints": (new_kpts,)}}})
elif vi["KPOINTS"] and vi["KPOINTS"].num_kpts >= 1:
n_kpts = vi["KPOINTS"].num_kpts * 1.2
new_kpts = tuple([int(round(n_kpts**1 / 3, 0))] * 3)
actions.append(
{"dict": "KPOINTS", "action": {"_set": {"generation_style": "Gamma", "kpoints": (new_kpts,)}}}
)
else:
actions.append({"dict": "INCAR", "action": {"_set": {"ISMEAR": 0, "SIGMA": 0.05}}})
self.error_count[err_type] += 1
# Missing AMIN error handler:
# previously, custodian would kill the job without letting it run if AMIN was flagged
if "amin" in self.errors and vi["INCAR"].get("AMIN", 0.1) > 0.01:
actions.append({"dict": "INCAR", "action": {"_set": {"AMIN": 0.01}}})
if "inv_rot_mat" in self.errors and vi["INCAR"].get("SYMPREC", 1e-5) > 1e-8:
actions.append({"dict": "INCAR", "action": {"_set": {"SYMPREC": 1e-8}}})
if "brmix" in self.errors:
# If there is not a valid OUTCAR already, increment
# error count to 1 to skip first fix
if self.error_count["brmix"] == 0:
try:
assert load_outcar(zpath(os.path.join(directory, "OUTCAR"))).is_stopped is False
except Exception:
self.error_count["brmix"] += 1
if self.error_count["brmix"] == 0:
# Valid OUTCAR - simply rerun the job and increment
# error count for next time
actions.append({"dict": "INCAR", "action": {"_set": {"ISTART": 1}}})
self.error_count["brmix"] += 1
elif self.error_count["brmix"] == 1 and vi["INCAR"].get("IMIX", 4) != 1:
# Use Kerker mixing w/ default values for other parameters
actions.append({"dict": "INCAR", "action": {"_set": {"IMIX": 1}}})
self.error_count["brmix"] += 1
elif (
self.error_count["brmix"] == 2
and vi["KPOINTS"]
and vi["KPOINTS"].style == Kpoints.supported_modes.Gamma
):
actions.append(
{
"dict": "KPOINTS",
"action": {"_set": {"generation_style": "Monkhorst"}},
}
)
if "IMIX" in vi["INCAR"]:
actions.append({"dict": "INCAR", "action": {"_unset": {"IMIX": 1}}})
self.error_count["brmix"] += 1
elif (
self.error_count["brmix"] in {2, 3}
and vi["KPOINTS"]
and vi["KPOINTS"].style == Kpoints.supported_modes.Monkhorst
):
actions.append({"dict": "KPOINTS", "action": {"_set": {"generation_style": "Gamma"}}})
if "IMIX" in vi["INCAR"]:
actions.append({"dict": "INCAR", "action": {"_unset": {"IMIX": 1}}})
self.error_count["brmix"] += 1
if vi["KPOINTS"] and vi["KPOINTS"].num_kpts < 1 and all(n % 2 == 0 for n in vi["KPOINTS"].kpts[0]):
new_kpts = (tuple(n + 1 for n in vi["KPOINTS"].kpts[0]),)
actions.append(
{
"dict": "KPOINTS",
"action": {"_set": {"kpoints": new_kpts}},
}
)
elif self.error_count["brmix"] in {2, 3} and vi["INCAR"].get("KSPACING"):
actions.append({"dict": "INCAR", "action": {"_set": {"KGAMMA": True}}})
else:
if vi["INCAR"].get("ISYM", 2) > 0:
actions.append({"dict": "INCAR", "action": {"_set": {"ISYM": 0}}})
if vi["KPOINTS"] and vi["KPOINTS"].style == Kpoints.supported_modes.Monkhorst:
actions.append(
{
"dict": "KPOINTS",
"action": {"_set": {"generation_style": "Gamma"}},
}
)
if vi["KPOINTS"] and vi["KPOINTS"].style == Kpoints.supported_modes.Monkhorst:
actions.append(
{
"dict": "KPOINTS",
"action": {"_set": {"generation_style": "Gamma"}},
}
)
# Based on VASP forum's recommendation, you should delete the
# CHGCAR and WAVECAR when dealing with this error.
# A.S.R.: Then why only delete them now?
if vi["INCAR"].get("ICHARG", 0) < 10:
actions += [
{"file": "CHGCAR", "action": {"_file_delete": {"mode": "actual"}}},
{"file": "WAVECAR", "action": {"_file_delete": {"mode": "actual"}}},
]
self.error_count["brmix"] += 1
if "zpotrf" in self.errors:
# Usually caused by short bond distances. If on the first step,
# volume needs to be increased. Otherwise, it was due to a step
# being too big and POTIM should be decreased. If a static run
# try turning off symmetry. This also happens if NCORE or NPAR
# is set to a large value for a small structure.
try:
oszicar = Oszicar(os.path.join(directory, "OSZICAR"))
nsteps = len(oszicar.ionic_steps)
except Exception:
nsteps = 0
if vi["INCAR"].get("ISYM", 2) > 0:
actions.append({"dict": "INCAR", "action": {"_set": {"ISYM": 0}}})
# The natoms of 5 was chosen somewhat arbitrarily. Could be worth revisiting to fine-tune.
if len(vi["POSCAR"].structure) < 5 and (vi["INCAR"].get("NCORE", 1) > 1 or vi["INCAR"].get("NPAR", 1) > 1):
actions.append({"dict": "INCAR", "action": {"_set": {"NCORE": 1}}})
if vi["INCAR"].get("NPAR", 1) > 1:
actions.append({"dict": "INCAR", "action": {"_unset": {"NPAR": 1}}})
elif vi["INCAR"].get("NSW", 0) > 0:
if nsteps == 0:
s = vi["POSCAR"].structure
s.apply_strain(0.2)
actions.append({"dict": "POSCAR", "action": {"_set": {"structure": s.as_dict()}}})
else:
potim = round(vi["INCAR"].get("POTIM", 0.5) / 2.0, 2)
actions.append({"dict": "INCAR", "action": {"_set": {"POTIM": potim}}})
if self.errors.intersection(["subspacematrix"]):
if self.error_count["subspacematrix"] == 0 and vi["INCAR"].get("LREAL", False) is not False:
actions.append({"dict": "INCAR", "action": {"_set": {"LREAL": False}}})
elif self.error_count["subspacematrix"] == 1 and vi["INCAR"].get("PREC", "Normal") != "Accurate":
actions.append({"dict": "INCAR", "action": {"_set": {"PREC": "Accurate"}}})
self.error_count["subspacematrix"] += 1
if (
self.errors.intersection(["rspher", "real_optlay", "nicht_konv"])
and vi["INCAR"].get("LREAL", False) is not False
):
actions.append({"dict": "INCAR", "action": {"_set": {"LREAL": False}}})
if (
self.errors.intersection(["tetirr", "incorrect_shift"])
and vi["KPOINTS"]
and vi["KPOINTS"].style == Kpoints.supported_modes.Monkhorst
):
actions.append(
{
"dict": "KPOINTS",
"action": {"_set": {"generation_style": "Gamma"}},
}
)
if "rot_matrix" in self.errors:
if vi["KPOINTS"] and vi["KPOINTS"].style == Kpoints.supported_modes.Monkhorst:
action = {"_set": {"generation_style": "Gamma"}}
actions.append({"dict": "KPOINTS", "action": action})
elif vi["INCAR"].get("ISYM", 2) > 0:
actions.append({"dict": "INCAR", "action": {"_set": {"ISYM": 0}}})
if "triple_product" in self.errors:
s = vi["POSCAR"].structure
trans = SupercellTransformation(((1, 0, 0), (0, 0, 1), (0, 1, 0)))
new_s = trans.apply_transformation(s)
actions.append(
{
"dict": "POSCAR",
"action": {"_set": {"structure": new_s.as_dict()}},
"transformation": trans.as_dict(),
}
)
if "pricel" in self.errors and vi["INCAR"].get("SYMPREC", 1e-5) > 1e-8:
actions.append({"dict": "INCAR", "action": {"_set": {"SYMPREC": 1e-8, "ISYM": 0}}})
if "coef" in self.errors:
actions.append({"file": "WAVECAR", "action": {"_file_delete": {"mode": "actual"}}})
if "brions" in self.errors:
# Copy CONTCAR to POSCAR so we do not lose our progress.
actions.append({"file": "CONTCAR", "action": {"_file_copy": {"dest": "POSCAR"}}})
# By default, increase POTIM per the VASP error message. But if that does not work,
# we should try IBRION = 2 since it is less sensitive to POTIM.
potim = round(vi["INCAR"].get("POTIM", 0.5) + 0.1, 2)
if self.error_count["brions"] == 1 and vi["INCAR"].get("IBRION", 0) == 1:
# Reset POTIM to default value and switch to IBRION = 2
actions.append({"dict": "INCAR", "action": {"_set": {"IBRION": 2, "POTIM": 0.5}}})
else:
# Increase POTIM
actions.append({"dict": "INCAR", "action": {"_set": {"POTIM": potim}}})
self.error_count["brions"] += 1
if "zbrent" in self.errors:
# ZBRENT is caused by numerical noise in the forces, often near the PES minimum
# This is often a severe problem for systems with many atoms, flexible
# structures (e.g. zeolites, MOFs), and surfaces with adsorbates present. It is
# a tricky one to resolve and generally occurs with IBRION = 2, which is otherwise
# a fairly robust optimization algorithm.
#
# VASP recommends moving CONTCAR to POSCAR and tightening EDIFF to improve the forces.
# That is our first option, along with setting NELMIN to 8 to ensure the forces are
# high quality. Our backup option if this does not help is to switch to IBRION = 1.
#
# If the user has specified vtst_fixes = True, we instead switch right away to FIRE, which is known
# to be much more robust near the PES minimum. It is not the default because it requires
# VTST to be installed.
ediff = vi["INCAR"].get("EDIFF", 1e-4)
# Copy CONTCAR to POSCAR. This should always be done so we don't lose our progress.
actions.append({"file": "CONTCAR", "action": {"_file_copy": {"dest": "POSCAR"}}})
# Tighten EDIFF per the VASP warning message. We tighten it by a factor of 10 unless
# it is > 1e-6 (in which case we set it to 1e-6) or 1e-8 in which case we stop tightening
if ediff > 1e-8:
if ediff > 1e-6:
actions.append({"dict": "INCAR", "action": {"_set": {"EDIFF": 1e-6}}})
else:
actions.append({"dict": "INCAR", "action": {"_set": {"EDIFF": ediff / 10}}})
# Set NELMIN to 8 to further ensure we have accurate forces. NELMIN of 4 to 8 is also
# recommended if IBRION = 1 is set anyway.
if vi["INCAR"].get("NELMIN", 2) < 8:
actions.append({"dict": "INCAR", "action": {"_set": {"NELMIN": 8}}})
# FIRE almost always resolves this issue but requires VTST to be installed. We provide
# it as a non-default option for the user. It is also not very sensitive to POTIM, unlike
# IBRION = 1. FIRE requires accurate forces but is unlikely to run into the zbrent issue.
# Since accurate forces are required for FIRE, we also need EDIFF to be tight and NELMIN
# to be set, e.g. to 8. This was already done above.
if self.vtst_fixes:
if vi["INCAR"].get("IOPT", 0) != 7:
actions.append({"dict": "INCAR", "action": {"_set": {"IOPT": 7, "IBRION": 3, "POTIM": 0}}})
else:
# By default, we change IBRION to 1 if the first CONTCAR to POSCAR swap did not work.
# We do not do this right away because IBRION = 1 is very sensitive to POTIM, which may
# cause a brions error downstream. We want to avoid the loop condition of zbrent -->
# switch to IBRION = 1 --> brions --> increase POTIM --> brions --> switch back to IBRION = 2
# --> zbrent --> and so on. The best way to avoid this is trying to get it to converge in the
# first place without switching IBRION to 1.
if self.error_count["zbrent"] == 1:
actions.append({"dict": "INCAR", "action": {"_set": {"IBRION": 1}}})
self.error_count["zbrent"] += 1
if "too_few_bands" in self.errors:
nbands = None
if "NBANDS" in vi["INCAR"]:
nbands = vi["INCAR"]["NBANDS"]
else:
with open(os.path.join(directory, "OUTCAR")) as file:
for line in file:
# Have to take the last NBANDS line since sometimes VASP
# updates it automatically even if the user specifies it.
# The last one is marked by NBANDS= (no space).
if "NBANDS=" in line:
try:
d = line.split("=")
nbands = int(d[-1].strip())
break
except (IndexError, ValueError):
pass
if nbands:
new_nbands = max(int(1.1 * nbands), nbands + 1) # This handles the case when nbands is too low (< 8).
actions.append({"dict": "INCAR", "action": {"_set": {"NBANDS": new_nbands}}})
if self.errors & {"pssyevx", "pdsyevx"} and vi["INCAR"].get("ALGO", "Normal").lower() != "normal":
actions.append({"dict": "INCAR", "action": {"_set": {"ALGO": "Normal"}}})
if "eddrmm" in self.errors:
# RMM algorithm is not stable for this calculation
# Copy CONTCAR to POSCAR if CONTCAR has already been populated.
try:
is_contcar = Poscar.from_file(os.path.join(directory, "CONTCAR"))
except Exception:
is_contcar = False
if is_contcar:
actions.append({"file": "CONTCAR", "action": {"_file_copy": {"dest": "POSCAR"}}})
if vi["INCAR"].get("ALGO", "Normal").lower() in {"fast", "veryfast"}:
actions.append({"dict": "INCAR", "action": {"_set": {"ALGO": "Normal"}}})
else:
potim = round(vi["INCAR"].get("POTIM", 0.5) / 2.0, 2)
actions.append({"dict": "INCAR", "action": {"_set": {"POTIM": potim}}})
if vi["INCAR"].get("ICHARG", 0) < 10:
actions += [
{"file": "CHGCAR", "action": {"_file_delete": {"mode": "actual"}}},
{"file": "WAVECAR", "action": {"_file_delete": {"mode": "actual"}}},
]
self.error_count["eddrmm"] += 1
if "edddav" in self.errors:
# Copy CONTCAR to POSCAR if CONTCAR has already been populated.
try:
is_contcar = Poscar.from_file(os.path.join(directory, "CONTCAR"))
except Exception:
is_contcar = False
if is_contcar:
actions.append({"file": "CONTCAR", "action": {"_file_copy": {"dest": "POSCAR"}}})
if vi["INCAR"].get("ICHARG", 0) < 10:
actions.append({"file": "CHGCAR", "action": {"_file_delete": {"mode": "actual"}}})
# This sometimes comes up with ALGO = Fast. We will switch the ALGO.
if vi["INCAR"].get("ALGO", "Normal").lower() != "all":
actions.append({"dict": "INCAR", "action": {"_set": {"ALGO": "All"}}})
# This can sometimes be due to load-balancing issues for small systems.
# See bottom of https://www.vasp.at/wiki/index.php/NCORE. A.S.R. ran some
# tests and found: 1) Changing LPLANE and NSIM does not help. 2) The suggestion
# of NCORE = # cores is not robust for KNL (too high). 3) Setting NPAR = sqrt(# cores)
# does not always resolve the issue. The best solution, aside from requesting fewer
# resources, seems to be to just increase NCORE slightly. That's what I do here.
nprocs = multiprocessing.cpu_count()
try:
nelect = load_outcar(os.path.join(directory, "OUTCAR")).nelect
except Exception:
nelect = 1 # dummy value
if nelect < nprocs:
actions.append({"dict": "INCAR", "action": {"_set": {"NCORE": vi["INCAR"].get("NCORE", 1) * 2}}})
if "grad_not_orth" in self.errors:
# Often coincides with algo_tet, in which the algo_tet error handler will also resolve grad_not_orth.
# When not present alongside algo_tet, the grad_not_orth error is due to how VASP is compiled.
# Depending on the optimization flag and choice of compiler, the ALGO = All and Damped algorithms
# may not work. The only fix is either to change ALGO or to recompile VASP. Since meta-GGAs/hybrids
# are often used with ALGO = All (and hybrids are incompatible with ALGO = VeryFast/Fast and slow with
# ALGO = Normal), we do not adjust ALGO in these cases.
if vi["INCAR"].get("METAGGA", "none") == "none" and not vi["INCAR"].get("LHFCALC", False):
if vi["INCAR"].get("ALGO", "Normal").lower() in {"all", "damped"}:
actions.append({"dict": "INCAR", "action": {"_set": {"ALGO": "Fast"}}})
elif 53 <= vi["INCAR"].get("IALGO", 38) <= 58:
actions.append({"dict": "INCAR", "action": {"_set": {"ALGO": "Fast"}, "_unset": {"IALGO": 38}}})
if "algo_tet" not in self.errors:
warnings.warn(
"EDWAV error reported by VASP without a simultaneous algo_tet error. You may wish to consider "
"recompiling VASP with the -O1 optimization if you used -O2 and this error keeps cropping up.",
UserWarning,
)
if self.errors & {"zheev", "eddiag"}:
# Copy CONTCAR to POSCAR if CONTCAR has already been populated.
try:
is_contcar = Poscar.from_file(os.path.join(directory, "CONTCAR"))
except Exception:
is_contcar = False
if is_contcar:
actions.append({"file": "CONTCAR", "action": {"_file_copy": {"dest": "POSCAR"}}})
if vi["INCAR"].get("ALGO", "Normal").lower() == "fast":
actions.append({"dict": "INCAR", "action": {"_set": {"ALGO": "Normal"}}})
elif vi["INCAR"].get("ALGO", "Normal").lower() == "normal":
actions.append({"dict": "INCAR", "action": {"_set": {"ALGO": "exact"}}})
if "elf_kpar" in self.errors and vi["INCAR"].get("KPAR", 1) != 1:
actions.append({"dict": "INCAR", "action": {"_set": {"KPAR": 1}}})
if "rhosyg" in self.errors:
if vi["INCAR"].get("SYMPREC", 1e-5) < 1e-4:
actions.append({"dict": "INCAR", "action": {"_set": {"SYMPREC": 1e-4}}})
else:
actions.append({"dict": "INCAR", "action": {"_set": {"ISYM": 0}}})
if symprec_errors := self.errors & {"posmap", "pricelv"}:
# VASP advises to decrease or increase SYMPREC by an order of magnitude
# the default SYMPREC value is 1e-5
# For PRICELV, see https://www.vasp.at/forum/viewtopic.php?p=25608
if all(self.error_count[key] == 0 for key in symprec_errors):
# first, reduce by 10x
orig_symprec = vi["INCAR"].get("SYMPREC", 1e-5)
actions.append({"dict": "INCAR", "action": {"_set": {"SYMPREC": orig_symprec / 10}}})
elif all(self.error_count[key] <= 1 for key in symprec_errors):
# next, increase by 100x (10x the original)
orig_symprec = vi["INCAR"].get("SYMPREC", 1e-6)
actions.append({"dict": "INCAR", "action": {"_set": {"SYMPREC": orig_symprec * 100}}})
elif any(self.error_count[key] > 1 for key in symprec_errors) and vi["INCAR"].get("ISYM", 2) > 0:
# Failing that, disable symmetry altogether
actions.append({"dict": "INCAR", "action": {"_set": {"ISYM": 0}}})
for key in symprec_errors:
self.error_count[key] += 1
if "point_group" in self.errors and vi["INCAR"].get("ISYM", 2) > 0:
actions.append({"dict": "INCAR", "action": {"_set": {"ISYM": 0}}})
if "symprec_noise" in self.errors and vi["INCAR"].get("ISYM", 2) > 0:
if vi["INCAR"].get("SYMPREC", 1e-5) > 1e-6:
actions.append({"dict": "INCAR", "action": {"_set": {"SYMPREC": 1e-6}}})
else:
actions.append({"dict": "INCAR", "action": {"_set": {"ISYM": 0}}})
if "dfpt_ncore" in self.errors:
# note that when using "_unset" action, the value is ignored
if "NCORE" in vi["INCAR"]:
actions.append({"dict": "INCAR", "action": {"_unset": {"NCORE": 0}}})
if "NPAR" in vi["INCAR"]:
actions.append({"dict": "INCAR", "action": {"_unset": {"NPAR": 0}}})
if "bravais" in self.errors:
# VASP recommends refining the lattice parameters or changing SYMPREC.
# Appears to occur when SYMPREC is very low, so we change it to
# the default if it's not already. If it's the default, we x10.
vasp_recommended_symprec = 1e-6 # https://www.vasp.at/forum/viewtopic.php?f=3&t=19109
symprec = vi["INCAR"].get("SYMPREC", vasp_recommended_symprec)
if symprec < vasp_recommended_symprec:
actions.append({"dict": "INCAR", "action": {"_set": {"SYMPREC": vasp_recommended_symprec}}})
elif symprec < 1e-4:
# try 10xing symprec twice, then set ISYM=0 to not impose potentially artificial symmetry from
# too loose symprec on charge density
actions.append({"dict": "INCAR", "action": {"_set": {"SYMPREC": symprec * 10}}})
else:
actions.append({"dict": "INCAR", "action": {"_set": {"ISYM": 0}}})
self.error_count["bravais"] += 1
if "nbands_not_sufficient" in self.errors:
# There is something very wrong about the value of NBANDS. We don't make
# any updates to NBANDS though because it's likely the user screwed something
# up pretty badly during setup. For instance, this has happened to me if
# MAGMOM = 2*nan or something similar.
# Unfixable error. Just return None for actions.
warnings.warn("Double-check your INCAR. Something is potentially wrong.", UserWarning)
return {"errors": ["nbands_not_sufficient"], "actions": None}
if "set_core_wf" in self.errors:
# Unfixable error where the solution is to update the POTCARs
warnings.warn(
"We suggest using a new version of the POTCAR files to resolve the SET_CORE_WF error.", UserWarning
)
return {"errors": ["set_core_wf"], "actions": None}
if "read_error" in self.errors:
# Unfixable error --- the user made a mistake in the INCAR
warnings.warn("Looks like you made a typo in the INCAR. Please double-check it.", UserWarning)
return {"errors": ["read_error"], "actions": None}
if "hnform" in self.errors and vi["INCAR"].get("ISYM", 2) > 0:
# The only solution is to change your k-point grid or disable symmetry
# For internal calculation compatibility's sake, we do the latter
actions.append({"dict": "INCAR", "action": {"_set": {"ISYM": 0}}})
if "algo_tet" in self.errors:
# NOTE: This is the algo_tet handler response.
algo = vi["INCAR"].get("ALGO", "Normal").lower()
# ALGO=All/Damped / IALGO=5X often fails with ISMEAR < 0. There are two options VASP
# suggests: 1) Use ISMEAR = 0 (and a small sigma) to get the SCF to converge.
# 2) Use ALGO = Damped but only *after* an ISMEAR = 0 run where the wavefunction
# has been stored and read in for the subsequent run.
if (
(algo in {"all", "damped"} or (50 <= vi["INCAR"].get("IALGO", 38) <= 59))
and vi["INCAR"].get("ISMEAR", 1) < 0
and self.error_count["algo_tet"] == 0
):
# first recovery attempt is to set ALGO to fast. Could fail again in which
# case we end up here again if some other handler switches algo back to all/damped.
# This time try the recovery below.
actions.append({"dict": "INCAR", "action": {"_set": {"ALGO": "Fast"}}})
#
# We will only hit the 2nd algo_tet error if the ALGO was changed back from Fast to All/Damped
# by e.g. NonConvergingErrorHandler
# NOTE this relies on self.errors being reset on empty set on every .check call
if self.error_count["algo_tet"] > 0:
actions.append({"dict": "INCAR", "action": {"_set": {"ISMEAR": 0, "SIGMA": 0.05}}})
if vi["INCAR"].get("NEDOS") or vi["INCAR"].get("EMIN") or vi["INCAR"].get("EMAX"):
warnings.warn(
"This looks like a DOS run. You may want to follow-up this job with ALGO = Damped"
" and ISMEAR = -5, using the wavefunction from the current job.",
UserWarning,
)
self.error_count["algo_tet"] += 1
VaspModder(vi=vi, directory=directory).apply_actions(actions)
return {"errors": list(self.errors), "actions": actions}
class LrfCommutatorHandler(ErrorHandler):
"""
Corrects LRF_COMMUTATOR errors by setting LPEAD=True if not already set.
Note that switching LPEAD=T can slightly change results versus the
default due to numerical evaluation of derivatives.
"""
is_monitor = True
error_msgs: ClassVar = {"lrf_comm": ["LRF_COMMUTATOR internal error"]}
def __init__(self, output_filename: str = "std_err.txt") -> None:
"""Initialize the handler with the output file to check.
Args:
output_filename (str): This is the file where the stderr for vasp
is being redirected. The error messages that are checked are
present in the stderr. Defaults to "std_err.txt", which is the
default redirect used by :class:`custodian.vasp.jobs.VaspJob`.
"""
self.output_filename = output_filename
self.errors: set[str] = set()
self.error_count: Counter = Counter()
def check(self, directory="./"):
"""Check for error."""
self.errors = set()
with open(os.path.join(directory, self.output_filename)) as file:
for line in file:
line = line.strip()
for err, msgs in LrfCommutatorHandler.error_msgs.items():
for msg in msgs:
if line.find(msg) != -1:
self.errors.add(err)
return len(self.errors) > 0
def correct(self, directory="./"):
"""Perform corrections."""
backup(VASP_BACKUP_FILES | {self.output_filename}, directory=directory)
actions = []
vi = VaspInput.from_directory(directory)
if (
"lrf_comm" in self.errors
and load_outcar(zpath(os.path.join(directory, "OUTCAR"))).is_stopped is False
and not vi["INCAR"].get("LPEAD")
):
actions.append({"dict": "INCAR", "action": {"_set": {"LPEAD": True}}})
VaspModder(vi=vi, directory=directory).apply_actions(actions)
return {"errors": list(self.errors), "actions": actions}
class StdErrHandler(ErrorHandler):
"""
Master StdErr class that handles a number of common errors
that occur during VASP runs with error messages only in
the standard error.
"""
is_monitor = True
error_msgs: ClassVar = {
"kpoints_trans": ["internal error in GENERATE_KPOINTS_TRANS: number of G-vector changed in star"],
"out_of_memory": ["Allocation would exceed memory limit"],
}
def __init__(self, output_filename: str = "std_err.txt") -> None:
"""Initialize the handler with the output file to check.
Args:
output_filename (str): This is the file where the stderr for vasp
is being redirected. The error messages that are checked are
present in the stderr. Defaults to "std_err.txt", which is the
default redirect used by :class:`custodian.vasp.jobs.VaspJob`.
"""
self.output_filename = output_filename
self.errors: set[str] = set()
self.error_count: Counter = Counter()
def check(self, directory="./"):
"""Check for error."""
self.errors = set()
with open(os.path.join(directory, self.output_filename)) as file:
for line in file:
line = line.strip()
for err, msgs in StdErrHandler.error_msgs.items():
for msg in msgs:
if line.find(msg) != -1:
self.errors.add(err)
return len(self.errors) > 0
def correct(self, directory="./"):
"""Perform corrections."""
backup(VASP_BACKUP_FILES | {self.output_filename}, directory=directory)
actions = []
vi = VaspInput.from_directory(directory)
if "kpoints_trans" in self.errors and self.error_count["kpoints_trans"] == 0:
m = prod(vi["KPOINTS"].kpts[0])
m = max(int(round(m ** (1 / 3))), 1)
if vi["KPOINTS"] and vi["KPOINTS"].style.name.lower().startswith("m"):
m += m % 2
actions.append({"dict": "KPOINTS", "action": {"_set": {"kpoints": [[m] * 3]}}})
self.error_count["kpoints_trans"] += 1
if "out_of_memory" in self.errors and vi["INCAR"].get("KPAR", 1) > 1:
reduced_kpar = max(vi["INCAR"].get("KPAR", 1) // 2, 1)
actions.append({"dict": "INCAR", "action": {"_set": {"KPAR": reduced_kpar}}})
VaspModder(vi=vi, directory=directory).apply_actions(actions)
return {"errors": list(self.errors), "actions": actions}
class AliasingErrorHandler(ErrorHandler):
"""
Master VaspErrorHandler class that handles a number of common errors
that occur during VASP runs.
"""
is_monitor = True
error_msgs: ClassVar = {
"aliasing": ["WARNING: small aliasing (wrap around) errors must be expected"],
"aliasing_incar": ["Your FFT grids (NGX,NGY,NGZ) are not sufficient for an accurate"],
}
def __init__(self, output_filename: str = "vasp.out") -> None:
"""Initialize the handler with the output file to check.
Args:
output_filename (str): This is the file where the stdout for vasp
is being redirected. The error messages that are checked are
present in the stdout. Defaults to "vasp.out", which is the
default redirect used by :class:`custodian.vasp.jobs.VaspJob`.
"""
self.output_filename = output_filename
self.errors: set[str] = set()
def check(self, directory="./"):
"""Check for error."""
incar = Incar.from_file(os.path.join(directory, "INCAR"))
self.errors = set()
with open(os.path.join(directory, self.output_filename)) as file:
for line in file:
line = line.strip()
for err, msgs in AliasingErrorHandler.error_msgs.items():
for msg in msgs:
if line.find(msg) != -1:
# this checks if we want to run a charged
# computation (e.g., defects) if yes we don't
# want to kill it because there is a change in e-
# density (brmix error)
if err == "brmix" and "NELECT" in incar:
continue
self.errors.add(err)
return len(self.errors) > 0
def correct(self, directory="./"):
"""Perform corrections."""
backup(VASP_BACKUP_FILES | {self.output_filename}, directory=directory)
actions = []
vi = VaspInput.from_directory(directory)
if "aliasing" in self.errors:
with open(os.path.join(directory, "OUTCAR")) as file:
grid_adjusted = False
changes_dict = {}
r = re.compile(r".+aliasing errors.*(NG.)\s*to\s*(\d+)")
for line in file:
m = r.match(line)
if m:
changes_dict[m.group(1)] = int(m.group(2))
grid_adjusted = True
# Ensure that all NGX, NGY, NGZ have been checked
if grid_adjusted and "NGZ" in line:
actions.append({"dict": "INCAR", "action": {"_set": changes_dict}})
if vi["INCAR"].get("ICHARG", 0) < 10:
delete_chgcar = {"file": "CHGCAR", "action": {"_file_delete": {"mode": "actual"}}}
delete_wavecar = {"file": "WAVECAR", "action": {"_file_delete": {"mode": "actual"}}}
actions += [delete_chgcar, delete_wavecar]
break
if "aliasing_incar" in self.errors:
# vasp seems to give different warnings depending on whether the
# aliasing error was caused by user supplied inputs
dct = {k: 1 for k in ("NGX", "NGY", "NGZ") if k in vi["INCAR"]}
actions.append({"dict": "INCAR", "action": {"_unset": dct}})
if vi["INCAR"].get("ICHARG", 0) < 10:
actions += [
{
"file": "CHGCAR",
"action": {"_file_delete": {"mode": "actual"}},
},
{
"file": "WAVECAR",
"action": {"_file_delete": {"mode": "actual"}},
},
]
VaspModder(vi=vi, directory=directory).apply_actions(actions)
return {"errors": list(self.errors), "actions": actions}
class DriftErrorHandler(ErrorHandler):
"""Corrects for total drift exceeding the force convergence criteria."""
def __init__(self, max_drift=None, to_average=3, enaug_multiply=2) -> None:
"""Initialize the handler with max drift
Args:
max_drift (float): This defines the max drift. Leaving this at the default of None gets the max_drift from
EDFIFFG.
"""
self.max_drift = max_drift
self.to_average = int(to_average)
self.enaug_multiply = enaug_multiply
def check(self, directory="./"):
"""Check for error."""
incar = Incar.from_file(os.path.join(directory, "INCAR"))
if incar.get("EDIFFG", 0.1) >= 0 or incar.get("NSW", 0) <= 1:
# Only activate when force relaxing and ionic steps
# NSW check prevents accidental effects when running DFPT
return False
if not self.max_drift:
self.max_drift = incar["EDIFFG"] * -1
try:
outcar = load_outcar(os.path.join(directory, "OUTCAR"))
except Exception:
# Can't perform check if Outcar not valid
return False
if len(outcar.data.get("drift", [])) < self.to_average:
# Ensure enough steps to get average drift
return False
curr_drift = outcar.data.get("drift", [])[::-1][: self.to_average]
curr_drift = np.average([np.linalg.norm(dct) for dct in curr_drift])
return curr_drift > self.max_drift
def correct(self, directory="./"):
"""Perform corrections."""
backup(VASP_BACKUP_FILES, directory=directory)
actions = []
vi = VaspInput.from_directory(directory)
incar = vi["INCAR"]
outcar = load_outcar(os.path.join(directory, "OUTCAR"))
# Move CONTCAR to POSCAR
actions.append({"file": "CONTCAR", "action": {"_file_copy": {"dest": "POSCAR"}}})
# Set PREC to High so ENAUG can be used to control Augmentation Grid Size
if incar.get("PREC", "Accurate").lower() != "high":
actions += [
{"dict": "INCAR", "action": {"_set": {"PREC": "High"}}},
{"dict": "INCAR", "action": {"_set": {"ENAUG": incar.get("ENCUT", 520) * 2}}},
]
# PREC is already high and ENAUG set so just increase it
else:
actions.append(
{
"dict": "INCAR",
"action": {"_set": {"ENAUG": int(incar.get("ENAUG", 1040) * self.enaug_multiply)}},
}
)
curr_drift = outcar.data.get("drift", [])[::-1][: self.to_average]
curr_drift = np.average([np.linalg.norm(dct) for dct in curr_drift])
VaspModder(vi=vi, directory=directory).apply_actions(actions)
return {
"errors": f"Excessive drift {curr_drift} > {self.max_drift}",
"actions": actions,
}
class MeshSymmetryErrorHandler(ErrorHandler):
"""
Corrects the mesh symmetry error in VASP. This error is sometimes
non-fatal. So this error handler only checks at the end of the run,
and if the run has converged, no error is recorded.
"""
is_monitor = False
def __init__(self, output_filename: str = "vasp.out", output_vasprun="vasprun.xml") -> None:
"""Initialize the handler with the output files to check.
Args:
output_filename (str): This is the file where the stdout for vasp
is being redirected. The error messages that are checked are
present in the stdout. Defaults to "vasp.out", which is the
default redirect used by :class:`custodian.vasp.jobs.VaspJob`.
output_vasprun (str): Filename for the vasprun.xml file. Change
this only if it is different from the default (unlikely).
"""
self.output_filename = output_filename
self.output_vasprun = output_vasprun
def check(self, directory="./") -> bool:
"""Check for error."""
msg = "Reciprocal lattice and k-lattice belong to different class of lattices."
vi = VaspInput.from_directory(directory)
# disregard this error if KSPACING is set and no KPOINTS file is generated
if vi["INCAR"].get("KSPACING", False):
return False
# According to VASP admins, you can disregard this error
# if symmetry is off (i.e. ISYM = -1 or 0)
# Also disregard if automatic KPOINT generation is used
if vi["INCAR"].get("ISYM", 2) <= 0 or (
vi["KPOINTS"] and vi["KPOINTS"].style == Kpoints.supported_modes.Automatic
):
return False