/
base.py
1794 lines (1616 loc) · 66.2 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
###############################
# This file is part of PyLaDa.
#
# Copyright (C) 2013 National Renewable Energy Lab
#
# PyLaDa is a high throughput computational platform for Physics. It aims to make it easier to submit
# large numbers of jobs on supercomputers. It provides a python interface to physical input, such as
# crystal structures, as well as to a number of DFT (VASP, CRYSTAL) and atomic potential programs. It
# is able to organise and launch computational jobs on PBS and SLURM.
#
# PyLaDa is free software: you can redistribute it and/or modify it under the terms of the GNU General
# Public License as published by the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# PyLaDa is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
# the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along with PyLaDa. If not, see
# <http://www.gnu.org/licenses/>.
###############################
""" Subpackage containing extraction methods for VASP. """
__docformat__ = 'restructuredtext en'
__all__ = ['ExtractBase']
from quantities import g, cm, eV
from ...tools import make_cached
from ...tools.extract import search_factory
from ...error import GrepError
OutcarSearchMixin = search_factory('OutcarSearchMixin', 'OUTCAR', __name__)
class ExtractBase(object):
""" Implementation class for extracting data from VASP output """
def __init__(self):
""" Initializes the extraction class. """
super(ExtractBase, self).__init__()
@property
@make_cached
def ialgo(self):
""" Returns the kind of algorithms. """
# Look for line like: IALGO = 68 algorithm
result = self._find_first_OUTCAR(r"""^\s*IALGO\s*=\s*(\d+)\s*""")
return int(result.group(1))
@property
@make_cached
def algo(self):
""" Returns the kind of algorithms. """
# This could be gotten in OUTCAR: use the 1 occurance of:
# ALGO = Fast
return {68: 'Fast', 38: 'Normal', 48: 'Very Fast', 58: 'Conjugate',
53: 'Damped', 4: 'Subrot', 90: 'Exact', 2: 'Nothing'}[self.ialgo]
@property
def is_dft(self):
""" True if this is a DFT calculation, as opposed to GW. """
try:
return self.algo not in ['gw', 'gw0', 'chi', 'scgw', 'scgw0']
except:
return False
# fixmod:
# Caution: I don't think the following will work,
# as self.algo, as set by algo() above, will never be *gw*.
@property
def is_gw(self):
""" True if this is a GW calculation, as opposed to DFT. """
try:
return self.algo in ['gw', 'gw0', 'chi', 'scgw', 'scgw0']
except:
return False
@property
def encut(self):
""" Energy cutoff. """
# OUTCAR: use the first occurance of:
# ENCUT = 252.0 eV 18.52 Ry ...
return float(self._find_first_OUTCAR(r"ENCUT\s*=\s*(\S+)").group(1)) * eV
@property
@make_cached
def functional(self):
""" Returns vasp functional used for calculation.
The vasp functional is the python object used to generate the OUTCAR
over which this extraction object acts. Pylada pastes a representation
of the functional at the end of the OUTCAR. This is what is extracted.
Hence this attribute will work only on OUTCAR's generated by Pylada.
"""
import os
from .. import Vasp
from .. import exec_input
# nomodoutcar
# regex = compile('#+ FUNCTIONAL #+\n((.|\n)*)\n#+ END FUNCTIONAL #+')
#with self.__outcar__() as file: result = regex.search(file.read())
# if result is None: return None
funPath = os.path.join(self.directory, 'pylada.FUNCTIONAL')
with open(funPath) as fin:
result = fin.read()
# Bad hack. Some derived object will have different names...
# Hopefully, there shouldn't be too many objects and this should be fairly
# fast.
input = exec_input(result)
for name in dir(input):
if isinstance(getattr(input, name), Vasp):
return getattr(input, name)
# otherwise, just try the objvious. but it really should fail at this
# point.
return input.vasp
@property
def success(self):
""" Checks that VASP run has completed.
At this point, checks for the existence of OUTCAR.
Then checks that timing stuff is present at end of OUTCAR.
"""
regex = r"""General\s+timing\s+and\s+accounting\s+informations\s+for\s+this\s+job"""
try:
return self._find_last_OUTCAR(regex) is not None
except:
return False
@property
def iterTimes(self):
""" Returns a list of pairs: [[cpuTime,realTime], ...]
from lines like::
LOOP+: cpu time 22.49: real time 24.43
or sometimes like::
LOOP+: VPU time 42.93: CPU time 43.04
In this case "CPU" is wall time, and "VPU" is CPU.
See: http://cms.mpi.univie.ac.at/vasp-forum/forum_viewtopic.php?3.336
"""
import re
regex = re.compile(
r'^\s*LOOP\+:\s+\w+\s+time\s+([.0-9]+):\s+\w+\s+time\s+([.0-9]+)\s*$')
tlist = []
with self.__outcar__() as file:
lines = file.readlines()
for line in lines:
mat = re.match(regex, line)
if mat != None:
cpuTime = float(mat.group(1))
realTime = float(mat.group(2))
tlist.append([cpuTime, realTime])
return tlist
@property
@make_cached
def datetime(self):
""" Greps execution date and time. """
from datetime import datetime
regex = r"""executed on .*\n"""
result = self._find_first_OUTCAR(regex)
if result is None:
return
result = result.group(0)
result = result[result.find('date') + 4:].rstrip().lstrip()
return datetime.strptime(result, '%Y.%m.%d %H:%M:%S')
@property
def initial_structure(self):
""" Structure at start of calculations. """
from six import next
from re import compile
from numpy import array, dot
from numpy.linalg import inv
from ...crystal import Structure
result = Structure()
with self.__outcar__() as file:
cell_re = compile(r"""^\s*direct\s+lattice\s+vectors\s+""")
atom_re = compile(r"""^\s*position\s+of\s+ions\s+in\s+fractional\s+coordinates""")
for line in file:
if cell_re.search(line) is not None:
break
data = []
for i in range(3):
data.append(next(file).split())
try:
for i in range(3):
result.cell[:, i] = array(data[i][:3], dtype='float64')
except:
for i in range(3):
result.cell[i,:] = array(data[i][-3:], dtype='float64')
result.cell = inv(result.cell)
for line in file:
if atom_re.search(line) is not None:
break
for specie, n in zip(self.species, self.stoichiometry):
for i, line in zip(list(range(n)), file):
data = line.split()
result.add_atom(pos=dot(result.cell, array(data, dtype='float64')), type=specie)
return result
# nomodoutcar
#@property
# def _catted_contcar(self):
# """ Returns contcar found at end of OUTCAR. """
# from re import compile
# from StringIO import StringIO
# from ...crystal import read
# with self.__outcar__() as file: lines = file.readlines()
# begin_contcar_re = compile(r"""#+\s+CONTCAR\s+#+""")
# end_contcar_re = compile(r"""#+\s+END\s+CONTCAR\s+#+""")
# start, end = None, None
# for i, line in enumerate(lines[::-1]):
# if begin_contcar_re.match(line) is not None: start = -i; break;
# if end_contcar_re.match(line) is not None: end = -i
# if start is None or end is None:
# raise IOError("Could not find catted contcar.")
# stringio = StringIO("".join(lines[start:end if end != 0 else -1]))
# return read.poscar(stringio, self.species)
@property
@make_cached
def _grep_structure(self):
""" Greps cell and positions from OUTCAR. """
from re import compile
from ...crystal import Structure
from numpy.linalg import inv
from numpy import array
with self.__outcar__() as file:
lines = file.readlines()
atom_index, cell_index = None, None
atom_re = compile(r"""^\s*POSITION\s+""")
cell_re = compile(r"""^\s*direct\s+lattice\s+vectors\s+""")
for index, line in enumerate(lines[::-1]):
if atom_re.search(line) is not None:
atom_index = index - 1
if cell_re.search(line) is not None:
cell_index = index
break
if atom_index is None or cell_index is None:
raise GrepError("Could not find structure description in OUTCAR.")
result = Structure()
try:
for i in range(3):
result.cell[:, i] = array(lines[-cell_index + i].split()[:3], dtype="float64")
except:
for i in range(3):
result.cell[i,:] = array(lines[-cell_index + i].split()[-3:], dtype="float64")
result.cell = inv(result.cell)
# Get list like ['S', 'S', 'S', 'S', 'S', 'S', 'Fe', 'Fe']
species = [type for type, n in zip(self.species, self.stoichiometry) for i in range(n)]
while atom_index > 0 and len(lines[-atom_index].split()) == 6:
result.add_atom(pos=array(lines[-atom_index].split()[:3], dtype="float64"),
type=species.pop(-1))
atom_index -= 1
return result
@property
@make_cached
def structure(self):
""" Greps structure and total energy from OUTCAR. """
if self.nsw == 0 or self.ibrion == -1:
return self.initial_structure
try:
result = self._contcar_structure
except:
result = self._grep_structure
# tries to find adequate name for structure.
try:
name = self.system
except GrepError:
name = ''
if len(name) == 0 or name == 'POSCAR created by SUPERPOSCAR':
try:
title = self.system
except GrepError:
title = ''
if len(title) != 0:
result.name = title
else:
result.name = name
if self.is_dft:
result.energy = self.total_energy
try:
initial = self.initial_structure
except:
pass
else:
for key, value in initial.__dict__.items():
if not hasattr(result, key):
setattr(result, key, value)
for a, b in zip(result, initial):
for key, value in b.__dict__.items():
if not hasattr(a, key):
setattr(a, key, value)
# adds magnetization.
try:
magnetization = self.magnetization
except:
pass
else:
if magnetization is not None:
for atom, mag in zip(result, magnetization):
atom.magmom = sum(mag)
# adds stress.
try:
result.stress = self.stress
except:
pass
# adds forces.
try:
forces = self.forces
except:
pass
else:
for force, atom in zip(forces, result):
atom.force = force
return result
@property
@make_cached
def LDAUType(self):
""" Type of LDA+U performed. """
type = self._find_first_OUTCAR(r"""LDAUTYPE\s*=\s*(\d+)""")
if type == None:
return None
type = int(type.group(1))
if type == 1:
return "liechtenstein"
elif type == 2:
return "dudarev"
return type
@property
@make_cached
def HubbardU_NLEP(self):
""" Hubbard U/NLEP parameters. """
from ..specie import U as ldaU, nlep
from re import M
type = self._find_first_OUTCAR(r"""LDAUTYPE\s*=\s*(\d+)""")
if type == None:
return {}
type = int(type.group(1))
species = tuple([ u.group(1) for u in self._search_OUTCAR(r"""VRHFIN\s*=\s*(\S+)\s*:""") ])
# first look for standard VASP parameters.
groups = r"""\s*((?:(?:\+|-)?\d+(?:\.\d+)?\s*)+)\s*\n"""
regex = r"""\s*angular\s+momentum\s+for\s+each\s+species\s+LDAUL\s+=""" + groups \
+ r"""\s*U\s+\(eV\)\s+for\s+each\s+species\s+LDAUU\s+=""" + groups \
+ r"""\s*J\s+\(eV\)\s+for\s+each\s+species\s+LDAUJ\s+=""" + groups
result = {}
for k in species:
result[k] = []
for found in self._search_OUTCAR(regex, M):
moment = found.group(1).split()
LDAU = found.group(2).split()
LDAJ = found.group(3).split()
for specie, m, U, J in zip(species, moment, LDAU, LDAJ):
if int(m) != -1:
result[specie].append(ldaU(type, int(m), float(U), float(J)))
for key in result.keys():
if len(result[key]) == 0:
del result[key]
if len(result) != 0:
return result
# then look for nlep parameters.
regex = r"""\s*angular\s+momentum\s+for\s+each\s+species,\s+LDAU#\s*(?:\d+)\s*:\s*L\s*=""" + groups \
+ r"""\s*U\s+\(eV\)\s+for\s+each\s+species,\s+LDAU\#\s*(?:\d+)\s*:\s*U\s*=""" + groups \
+ r"""\s*J\s+\(eV\)\s+for\s+each\s+species,\s+LDAU\#\s*(?:\d+)\s*:\s*J\s*=""" + groups \
+ r"""\s*nlep\s+for\s+each\s+species,\s+LDAU\#\s*(?:\d+)\s*:\s*O\s*=""" + groups
result = {}
for k in species:
result[k] = []
for found in self._search_OUTCAR(regex, M):
moment = found.group(1).split()
LDAU = found.group(2).split()
LDAJ = found.group(3).split()
funcs = found.group(4).split()
for specie, m, U, J, func in zip(species, moment, LDAU, LDAJ, funcs):
if int(m) == -1:
continue
if int(func) == 1:
result[specie].append(ldaU(type, int(m), float(U), float(J)))
else:
result[specie].append(nlep(type, int(m), float(U), float(J)))
for key in result.keys():
if len(result[key]) == 0:
del result[key]
return result
@property
@make_cached
def pseudopotential(self):
""" Title of the first POTCAR. """
return self._find_first_OUTCAR(r"""POTCAR:.*""").group(0).split()[1]
@property
@make_cached
def volume(self):
""" Unit-cell volume. """
from numpy import abs
from numpy.linalg import det
from quantities import angstrom
return abs(det(self.structure.scale * self.structure.cell)) * angstrom**3
@property
@make_cached
def reciprocal_volume(self):
""" Reciprocal space volume (including 2pi). """
from numpy import abs, pi
from numpy.linalg import det, inv
from quantities import angstrom
return abs(det(inv(self.structure.scale * self.structure.cell))) * (2e0 * pi / angstrom)**3
@property
@make_cached
def density(self):
""" Computes density of the material. """
from quantities import atomic_mass_unit as amu
from ... import periodic_table as pt
result = 0e0 * amu
for atom, n in zip(self.species, self.stoichiometry):
if atom not in pt.__dict__:
return None
result += pt.__dict__[atom].atomic_weight * float(n) * amu
return (result / self.volume).rescale(g / cm**3)
@property
@make_cached
def _contcar_structure(self):
""" Greps structure from CONTCAR. """
from ...crystal import read
from quantities import eV
result = read.poscar(self.__contcar__(), self.species)
result.energy = float(self.total_energy.rescale(eV)) if self.is_dft else 0e0
return result
@property
@make_cached
def stoichiometry(self):
""" Stoichiometry of the compound. """
# Find line like: ions per type = 2 4
result = self._find_first_OUTCAR(r"""\s*ions\s+per\s+type\s*=.*$""")
if result is None:
return None
return [int(u) for u in result.group(0).split()[4:]]
@property
def ions_per_specie(self):
""" Alias for stoichiometry. """
return self.stoichiometry
@property
@make_cached
def species(self):
""" Greps species from OUTCAR. """
return [ u.group(1) for u in self._search_OUTCAR(r"""VRHFIN\s*=\s*(\S+)\s*:""") ]
@property
@make_cached
def isif(self):
""" Greps ISIF from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*ISIF\s*=\s*(-?\d+)\s+""")
if result is None:
return None
return int(result.group(1))
@property
@make_cached
def nsw(self):
""" Greps NSW from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*NSW\s*=\s*(-?\d+)\s+""")
if result is None:
return None
return int(result.group(1))
@property
@make_cached
def ismear(self):
""" Greps smearing function from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*ISMEAR\s*=\s*(\d+);""")
if result is None:
return None
return int(result.group(1))
@property
@make_cached
def sigma(self):
""" Greps smearing function from OUTCAR. """
from numpy import array
from quantities import eV
result = self._find_first_OUTCAR(r"""\s*ISMEAR\s*=\s*(?:\d+)\s*;\s*SIGMA\s*=\s+(.*)\s+br""")
if result is None:
return None
result = result.group(1).rstrip().lstrip().split()
if len(result) == 1:
return float(result[0]) * eV
return array(result, dtype="float64") * eV
@property
def relaxation(self):
""" Returns the kind of relaxation performed in this calculation. """
from ..keywords import Relaxation
return Relaxation().__get__(self)
@property
@make_cached
def ibrion(self):
""" Greps IBRION from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*IBRION\s*=\s*(-?\d+)\s+""")
if result is None:
return None
return int(result.group(1))
@property
@make_cached
def potim(self):
""" Greps POTIM from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*POTIM\s*=\s*(-?\S+)\s+""")
if result is None:
return None
return float(result.group(1))
@property
@make_cached
def lorbit(self):
""" Greps LORBIT from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*LORBIT\s*=\s*(\d+)\s+""")
if result is None:
return None
return int(result.group(1))
@property
@make_cached
def isym(self):
""" Greps ISYM from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*ISYM\s*=\s*(\d+)\s+""")
if result is None:
return None
return int(result.group(1))
@property
@make_cached
def nupdown(self):
""" Greps NUPDOWN from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*NUPDOWN\s*=\s*(\S+)\s+""")
if result is None:
return None
return float(result.group(1))
@property
@make_cached
def lmaxmix(self):
""" Greps LMAXMIX from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*LMAXMIX\s*=\s*(\d+)\s+""")
if result is None:
return None
return int(result.group(1))
@property
@make_cached
def lvhar(self):
""" Greps LVHAR from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*LVHAR\s*=\s*(\d+)\s+""")
if result is None:
return None
return int(result.group(1))
@property
@make_cached
def istart(self):
""" Greps ISTART from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*ISTART\s*=\s*(\d+)\s+""")
if result is None:
return None
return int(result.group(1))
@property
@make_cached
def icharg(self):
""" Greps ICHARG from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*ICHARG\s*=\s*(\d+)\s+""")
if result is None:
return None
return int(result.group(1))
@property
@make_cached
def precision(self):
""" Greps PREC from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*PREC\s*=\s*(\S*)\s+""")
if result is None:
return None
if result.group(1) == "accura":
return "accurate"
return result.group(1)
@property
@make_cached
def ediff(self):
""" Greps EDIFF from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*EDIFF\s*=\s*(\S+)\s+""")
if result is None:
return None
return float(result.group(1))
@property
@make_cached
def ediffg(self):
""" Greps EDIFFG from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*EDIFFG\s*=\s*(\S+)\s+""")
if result is None:
return None
return float(result.group(1))
@property
@make_cached
def lsorbit(self):
""" Greps LSORBIT from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*LSORBIT\s*=\s*(T|F)\s+""")
if result is None:
return None
return result.group(1) == 'T'
@property
@make_cached
def lasph(self):
""" Greps LASPH from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*LASPH\s*=\s*(T|F)\s+""")
if result is None:
return None
return result.group(1) == 'T'
@property
@make_cached
def metagga(self):
""" Greps METAGGA from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*METAGGA\s*=\s*(T|F)\s+""")
if result is None:
return None
return result.group(1) == 'T'
@property
@make_cached
def lreal(self):
""" Greps LREAL from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*LREAL\s*=\s*(T|F)\s+""")
if result is None:
return None
return result.group(1) == 'T'
@property
@make_cached
def lcompat(self):
""" Greps LCOMPAT from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*LCOMPAT\s*=\s*(T|F)\s+""")
if result is None:
return None
return result.group(1) == 'T'
@property
@make_cached
def lreal_compat(self):
""" Greps LREAL_COMPAT from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*LREAL_COMPAT\s*=\s*(T|F)\s+""")
if result is None:
return None
return result.group(1) == 'T'
@property
@make_cached
def lgga_compat(self):
""" Greps LGGA_COMPAT from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*LGGA_COMPAT\s*=\s*(T|F)\s+""")
if result is None:
return None
return result.group(1) == 'T'
@property
@make_cached
def lcorr(self):
""" Greps LCORR from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*LCORR\s*=\s*(T|F)\s+""")
if result is None:
return None
return result.group(1) == 'T'
@property
@make_cached
def ldiag(self):
""" Greps LDIAG from OUTCAR. """
result = self._find_first_OUTCAR(r"""\s*LDIAG\s*=\s*(T|F)\s+""")
if result is None:
return None
return result.group(1) == 'T'
@property
@make_cached
def kpoints(self):
""" Greps k-points from OUTCAR.
Numpy array where each row is a k-vector in cartesian units.
"""
from re import compile
from numpy import array
result = []
found_generated = compile(r"""Found\s+(\d+)\s+irreducible\s+k-points""")
found_read = compile(r"""k-points in units of 2pi/SCALE and weight""")
with self.__outcar__() as file:
found = 0
for line in file:
if found_generated.search(line) is not None:
found = 1
break
elif found_read.search(line) is not None:
found = 2
break
if found == 1:
found = compile(r"""Following\s+cartesian\s+coordinates:""")
for line in file:
if found.search(line) is not None:
break
next(file)
for line in file:
data = line.split()
if len(data) != 4:
break
result.append(data[:3])
return array(result, dtype="float64")
if found == 2:
for line in file:
data = line.split()
if len(data) == 0:
break
result.append(data[:3])
return array(result, dtype="float64")
@property
@make_cached
def multiplicity(self):
""" Greps multiplicity of each k-point from OUTCAR. """
# If generated kpoints,
# get the "weight" field from the cartesion part of a section like:
# Found 10 irreducible k-points:
# Following reciprocal coordinates:
# Coordinates Weight
# 0.000000 0.000000 0.000000 1.000000
# 0.250000 0.000000 0.000000 2.000000
# ...
# Following cartesian coordinates:
# Coordinates Weight
# 0.000000 0.000000 0.000000 1.000000
# 0.079365 0.045821 0.000000 2.000000
# ...
# If specified kpoints,
# get the "weight" field from a section like:
# k-points in units of 2pi/SCALE and weight: Automatic mesh
# 0.00000000 0.00000000 0.00000000 0.016
# 0.00000000 0.25000000 0.25000000 0.188
# ...
from re import compile
from numpy import array
result = []
# case where kpoints where generated by vasp.
found_generated = compile(r"""Found\s+(\d+)\s+irreducible\s+k-points""")
# case where kpoints where given by hand.
found_read = compile(r"""k-points in units of 2pi/SCALE and weight""")
with self.__outcar__() as file:
found = 0
for line in file:
if found_generated.search(line) is not None:
found = 1
break
elif found_read.search(line) is not None:
found = 2
break
if found == 1:
found = compile(r"""Following\s+cartesian\s+coordinates:""")
for line in file:
if found.search(line) is not None:
break
next(file)
for line in file:
data = line.split()
if len(data) != 4:
break
result.append(data[-1])
return array(result, dtype="float64")
elif found == 2:
for line in file:
data = line.split()
if len(data) == 0:
break
result.append(float(data[3]))
return array([round(r * float(len(result))) for r in result], dtype="float64")
@property
@make_cached
def ispin(self):
""" Greps ISPIN from OUTCAR. """
result = self._find_first_OUTCAR(r"""^\s*ISPIN\s*=\s*(1|2)\s+""")
if result is None:
raise GrepError("Could not extract ISPIN from OUTCAR.")
return int(result.group(1))
@property
@make_cached
def name(self):
""" Greps POSCAR title from OUTCAR. """
result = self._find_first_OUTCAR(r"""^\s*POSCAR\s*=.*$""")
if result is None:
raise GrepError("Could not extract POSCAR title from OUTCAR.")
result = result.group(0)
result = result[result.index('=') + 1:]
return result.rstrip().lstrip()
@property
@make_cached
def system(self):
""" Greps system title from OUTCAR. """
result = self._find_first_OUTCAR(r"""^\s*SYSTEM\s*=.*$""")
if result is None:
raise GrepError("Could not extract SYSTEM title from OUTCAR.")
result = result.group(0)
result = result[result.index('=') + 1:].rstrip().lstrip()
if result[0] == '"':
result = result[1:]
if result[-1] == '"':
result = result[:-1]
return result
def _unpolarized_values(self, which):
""" Returns spin-unpolarized eigenvalues and occupations. """
# which = 1: select eigenvalues
# which = 2: select occupations
from re import compile, finditer
import re
with self.__outcar__() as file:
lines = file.readlines()
# Finds last first kpoint.
spin_comp1_re = compile(r"\s*k-point\s+1\s*:\s*(\S+)\s+(\S+)\s+(\S+)\s*")
found = None
for i, line in enumerate(lines[::-1]):
found = spin_comp1_re.match(line)
if found is not None:
break
if found is None:
raise GrepError("Could not extract eigenvalues/occupation from OUTCAR.")
# Here i is the distance from file end of the last line like:
# k-point 1 : 0.0000 0.0000 0.0000
# now greps actual results.
if self.is_dft:
kp_re = r"\s*k-point\s+(?:(?:\d|\*)+)\s*:\s*(?:\S+)\s*(?:\S+)\s*(?:\S+)\n"\
r"\s*band\s+No\.\s+band\s+energies\s+occupation\s*\n"\
r"(\s*(?:\d+)\s+(?:\S+)\s+(?:\S+)\s*\n)+"
skip, cols = 2, 3
else:
kp_re = r"\s*k-point\s+(?:(?:\d|\*)+)\s*:\s*(?:\S+)\s*(?:\S+)\s*(?:\S+)\n"\
r"\s*band\s+No\.\s+.*\n\n"\
r"(\s*(?:\d+)\s+(?:\S+)\s+(?:\S+)\s+(?:\S+)\s+(?:\S+)"\
r"\s+(?:\S+)\s+(?:\S+)\s+(?:\S+)\s*\n)+"
skip, cols = 3, 8
results = []
for kp in finditer(kp_re, "".join(lines[-i - 1:]), re.M):
# Each iteration is a k-point.
# dummy is a list of sublists, one sublist per OUTCAR line, like:
# [['1', '-30.5498', '2.00000'],
# ['2', '-30.5497', '2.00000'],
# ['3', '-30.3889', '2.00000'],
# ['4', '-30.3889', '2.00000'],
# ['5', '-30.3857', '2.00000'],
# ...
# ['28', '7.5661', '0.00000'],
# [], []]
# We only process those elements having len == cols (here, 3).
# We append the "which" column value to results.
dummy = [u.split() for u in kp.group(0).split('\n')[skip:]]
results.append([float(u[which]) for u in dummy if len(u) == cols])
# results is a list of sublists, one sublist per k-point,
# containing the band energies:
# [[-30.5498, -30.5497, -30.3889, -30.3889, ...],
# [-30.5371, -30.5371, -30.4543, -30.4542, ...],
# ...
# [-30.6596, -30.6596, -30.4905, -30.4905, ...],
# [-30.6604, -30.6603, -30.4906, -30.4906, ...]]
return results
def _spin_polarized_values(self, which):
""" Returns spin-polarized eigenvalues and occupations. """
from re import compile, finditer
import re
with self.__outcar__() as file:
lines = file.readlines()
# Finds last spin components.
spin_comp1_re = compile(r"""\s*spin\s+component\s+(1|2)\s*$""")
spins = [None, None]
for i, line in enumerate(lines[::-1]):
found = spin_comp1_re.match(line)
if found is None:
continue
if found.group(1) == '1':
if spins[1] is None:
raise GrepError("Could not find two spin components in OUTCAR.")
spins[0] = i
break
else:
spins[1] = i
if spins[0] is None or spins[1] is None:
raise GrepError("Could not extract eigenvalues/occupation from OUTCAR.")
# now greps actual results.
if self.is_dft:
kp_re = r"\s*k-point\s+(?:(?:\d|\*)+)\s*:\s*(?:\S+)\s*(?:\S+)\s*(?:\S+)\n"\
r"\s*band\s+No\.\s+band\s+energies\s+occupation\s*\n"\
r"(\s*(?:\d+)\s+(?:\S+)\s+(?:\S+)\s*\n)+"
skip, cols = 2, 3
else:
kp_re = r"\s*k-point\s+(?:(?:\d|\*)+)\s*:\s*(?:\S+)\s*(?:\S+)\s*(?:\S+)\n"\
r"\s*band\s+No\.\s+.*\n\n"\
r"(\s*(?:\d+)\s+(?:\S+)\s+(?:\S+)\s+(?:\S+)\s+(?:\S+)"\
r"\s+(?:\S+)\s+(?:\S+)\s+(?:\S+)\s*\n)+"
skip, cols = 3, 8
results = [[], []]
for kp in finditer(kp_re, "".join(lines[-spins[0]:-spins[1]]), re.M):
dummy = [u.split() for u in kp.group(0).split('\n')[skip:]]
results[0].append([float(u[which]) for u in dummy if len(u) == cols])
for kp in finditer(kp_re, "".join(lines[-spins[1]:]), re.M):
dummy = [u.split() for u in kp.group(0).split('\n')[skip:]]
results[1].append([u[which] for u in dummy if len(u) == cols])
return results
@property
@make_cached
def ionic_charges(self):
""" Greps ionic_charges from OUTCAR."""
# Line like: ZVAL = 12.00 6.00
regex = r"""^\s*ZVAL\s*=\s*(.*)$"""
result = self._find_last_OUTCAR(regex)
if result is None:
raise GrepError("Could not find ionic_charges in OUTCAR")
return [float(u) for u in result.group(1).split()]
@property
@make_cached
def valence(self):
""" Greps number of valence bands from OUTCAR."""
ionic = self.ionic_charges
species = self.species
atoms = [u.type for u in self.structure]
result = 0
# ionic is like: [12.0, 6.0]
# species is like: ['Mo', 'S']
for c, s in zip(ionic, species):
result += c * atoms.count(s)
return result
@property
@make_cached
def nelect(self):
""" Greps nelect from OUTCAR."""
# Find line like: NELECT = 48.0000 total number of electrons
regex = r"^\s*NELECT\s*=\s*(\S+)\s+total\s+number\s+of\s+electrons\s*$"
result = self._find_last_OUTCAR(regex)
if result is None:
raise GrepError("Could not find energy in OUTCAR")
return float(result.group(1))
@property
def extraelectron(self):
""" Returns charge state of the system. """
return self.nelect - self.valence
@property