Coverage for ase/io/vasp_parsers/vasp_outcar_parsers.py: 94.64%
466 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1"""
2Module for parsing OUTCAR files.
3"""
5import re
6from abc import ABC, abstractmethod
7from collections.abc import Iterator, Sequence
8from pathlib import Path, PurePath
9from typing import Any, TextIO
10from warnings import warn
12import numpy as np
14import ase
15from ase import Atoms
16from ase.calculators.singlepoint import (
17 SinglePointDFTCalculator,
18 SinglePointKPoint,
19)
20from ase.data import atomic_numbers
21from ase.io import ParseError, read
22from ase.io.utils import ImageChunk
24# Denotes end of Ionic step for OUTCAR reading
25_OUTCAR_SCF_DELIM = 'FREE ENERGIE OF THE ION-ELECTRON SYSTEM'
27# Some type aliases
28_HEADER = dict[str, Any]
29_CURSOR = int
30_CHUNK = Sequence[str]
31_RESULT = dict[str, Any]
34class NoNonEmptyLines(Exception):
35 """No more non-empty lines were left in the provided chunck"""
38class UnableToLocateDelimiter(Exception):
39 """Did not find the provided delimiter"""
41 def __init__(self, delimiter, msg):
42 self.delimiter = delimiter
43 super().__init__(msg)
46def _check_line(line: str) -> str:
47 """Auxiliary check line function for OUTCAR numeric formatting.
48 See issue #179, https://gitlab.com/ase/ase/issues/179
49 Only call in cases we need the numeric values
50 """
51 if re.search('[0-9]-[0-9]', line):
52 line = re.sub('([0-9])-([0-9])', r'\1 -\2', line)
53 return line
56def find_next_non_empty_line(cursor: _CURSOR, lines: _CHUNK) -> _CURSOR:
57 """Fast-forward the cursor from the current position to the next
58 line which is non-empty.
59 Returns the new cursor position on the next non-empty line.
60 """
61 for line in lines[cursor:]:
62 if line.strip():
63 # Line was non-empty
64 return cursor
65 # Empty line, increment the cursor position
66 cursor += 1
67 # There was no non-empty line
68 raise NoNonEmptyLines('Did not find a next line which was not empty')
71def search_lines(delim: str, cursor: _CURSOR, lines: _CHUNK) -> _CURSOR:
72 """Search through a chunk of lines starting at the cursor position for
73 a given delimiter. The new position of the cursor is returned."""
74 for line in lines[cursor:]:
75 if delim in line:
76 # The cursor should be on the line with the delimiter now
77 assert delim in lines[cursor]
78 return cursor
79 # We didn't find the delimiter
80 cursor += 1
81 raise UnableToLocateDelimiter(
82 delim, f'Did not find starting point for delimiter {delim}'
83 )
86def convert_vasp_outcar_stress(stress: Sequence):
87 """Helper function to convert the stress line in an OUTCAR to the
88 expected units in ASE"""
89 stress_arr = -np.array(stress)
90 shape = stress_arr.shape
91 if shape != (6,):
92 raise ValueError(
93 f'Stress has the wrong shape. Expected (6,), got {shape}'
94 )
95 stress_arr = stress_arr[[0, 1, 2, 4, 5, 3]] * 1e-1 * ase.units.GPa
96 return stress_arr
99def read_constraints_from_file(directory: str | Path) -> Sequence[str] | None:
100 directory = Path(directory)
101 constraint = None
102 for filename in ('CONTCAR', 'POSCAR'):
103 path = directory / filename
104 if path.is_file() and path.stat().st_size > 0:
105 atoms = read(path, format='vasp', parallel=False)
106 if isinstance(atoms, Atoms):
107 constraint = atoms.constraints
108 break
109 return constraint
112class VaspPropertyParser(ABC):
113 NAME: str | None = None
115 @classmethod
116 def get_name(cls):
117 """Name of parser. Override the NAME constant in the class to
118 specify a custom name,
119 otherwise the class name is used"""
120 return cls.NAME or cls.__name__
122 @abstractmethod
123 def has_property(self, cursor: _CURSOR, lines: _CHUNK) -> bool:
124 """Function which checks if a property can be derived from a given
125 cursor position"""
127 @staticmethod
128 def get_line(cursor: _CURSOR, lines: _CHUNK) -> str:
129 """Helper function to get a line, and apply the check_line function"""
130 return _check_line(lines[cursor])
132 @abstractmethod
133 def parse(self, cursor: _CURSOR, lines: _CHUNK) -> _RESULT:
134 """Extract a property from the cursor position.
135 Assumes that "has_property" would evaluate to True
136 from cursor position"""
139class SimpleProperty(VaspPropertyParser, ABC):
140 LINE_DELIMITER: str | None = None
142 def __init__(self):
143 super().__init__()
144 if self.LINE_DELIMITER is None:
145 raise ValueError('Must specify a line delimiter.')
147 def has_property(self, cursor, lines) -> bool:
148 line = lines[cursor]
149 return self.LINE_DELIMITER in line
152class VaspChunkPropertyParser(VaspPropertyParser, ABC):
153 """Base class for parsing a chunk of the OUTCAR.
154 The base assumption is that only a chunk of lines is passed"""
156 def __init__(self, header: _HEADER | None = None):
157 super().__init__()
158 header = header or {}
159 self.header = header
161 def get_from_header(self, key: str) -> Any:
162 """Get a key from the header, and raise a ParseError
163 if that key doesn't exist"""
164 try:
165 return self.header[key]
166 except KeyError:
167 raise ParseError(
168 'Parser requested unavailable key "{}" from header'.format(key)
169 )
172class VaspHeaderPropertyParser(VaspPropertyParser, ABC):
173 """Base class for parsing the header of an OUTCAR"""
176class SimpleVaspChunkParser(VaspChunkPropertyParser, SimpleProperty, ABC):
177 """Class for properties in a chunk can be
178 determined to exist from 1 line"""
181class SimpleVaspHeaderParser(VaspHeaderPropertyParser, SimpleProperty, ABC):
182 """Class for properties in the header
183 which can be determined to exist from 1 line"""
186class Spinpol(SimpleVaspHeaderParser):
187 """Parse if the calculation is spin-polarized.
189 Example line:
190 " ISPIN = 2 spin polarized calculation?"
192 """
194 LINE_DELIMITER = 'ISPIN'
196 def parse(self, cursor: _CURSOR, lines: _CHUNK) -> _RESULT:
197 line = lines[cursor].strip()
198 parts = line.split()
199 ispin = int(parts[2])
200 # ISPIN 2 = spinpolarized, otherwise no
201 # ISPIN 1 = non-spinpolarized
202 spinpol = ispin == 2
203 return {'spinpol': spinpol}
206class SpeciesTypes(SimpleVaspHeaderParser):
207 """Parse species types.
209 Example line:
210 " POTCAR: PAW_PBE Ni 02Aug2007"
212 We must parse this multiple times, as it's scattered in the header.
213 So this class has to simply parse the entire header.
214 """
216 LINE_DELIMITER = 'POTCAR:'
218 def __init__(self, *args, **kwargs):
219 self._species = [] # Store species as we find them
220 # We count the number of times we found the line,
221 # as we only want to parse every second,
222 # due to repeated entries in the OUTCAR
223 super().__init__(*args, **kwargs)
225 @property
226 def species(self) -> list[str]:
227 """Internal storage of each found line.
228 Will contain the double counting.
229 Use the get_species() method to get the un-doubled list."""
230 return self._species
232 def get_species(self) -> list[str]:
233 """The OUTCAR will contain two 'POTCAR:' entries per species.
234 This method only returns the first half,
235 effectively removing the double counting.
236 """
237 # Get the index of the first half
238 # In case we have an odd number, we round up (for testing purposes)
239 # Tests like to just add species 1-by-1
240 # Having an odd number should never happen in a real OUTCAR
241 # For even length lists, this is just equivalent to idx =
242 # len(self.species) // 2
243 idx = sum(divmod(len(self.species), 2))
244 # Make a copy
245 return list(self.species[:idx])
247 def _make_returnval(self) -> _RESULT:
248 """Construct the return value for the "parse" method"""
249 return {'species': self.get_species()}
251 def parse(self, cursor: _CURSOR, lines: _CHUNK) -> _RESULT:
252 line = lines[cursor].strip()
254 parts = line.split()
255 # Determine in what position we'd expect to find the symbol
256 if '1/r potential' in line:
257 # This denotes an AE potential
258 # Currently only H_AE
259 # " H 1/r potential "
260 idx = 1
261 else:
262 # Regular PAW potential, e.g.
263 # "PAW_PBE H1.25 07Sep2000" or
264 # "PAW_PBE Fe_pv 02Aug2007"
265 idx = 2
267 sym = parts[idx]
268 # remove "_h", "_GW", "_3" tags etc.
269 sym = sym.split('_')[0]
270 # in the case of the "H1.25" potentials etc.,
271 # remove any non-alphabetic characters
272 sym = ''.join([s for s in sym if s.isalpha()])
274 if sym not in atomic_numbers:
275 # Check that we have properly parsed the symbol, and we found
276 # an element
277 raise ParseError(f'Found an unexpected symbol {sym} in line {line}')
279 self.species.append(sym)
281 return self._make_returnval()
284class IonsPerSpecies(SimpleVaspHeaderParser):
285 """Example line:
287 " ions per type = 32 31 2"
288 """
290 LINE_DELIMITER = 'ions per type'
292 def parse(self, cursor: _CURSOR, lines: _CHUNK) -> _RESULT:
293 line = lines[cursor].strip()
294 parts = line.split()
295 ion_types = list(map(int, parts[4:]))
296 return {'ion_types': ion_types}
299class KpointHeader(VaspHeaderPropertyParser):
300 """Reads nkpts and nbands from the line delimiter.
301 Then it also searches for the ibzkpts and kpt_weights"""
303 def has_property(self, cursor: _CURSOR, lines: _CHUNK) -> bool:
304 line = lines[cursor]
305 return 'NKPTS' in line and 'NBANDS' in line
307 def parse(self, cursor: _CURSOR, lines: _CHUNK) -> _RESULT:
308 line = lines[cursor].strip()
309 parts = line.split()
310 nkpts = int(parts[3])
311 nbands = int(parts[-1])
313 results: dict[str, Any] = {'nkpts': nkpts, 'nbands': nbands}
314 # We also now get the k-point weights etc.,
315 # because we need to know how many k-points we have
316 # for parsing that
317 # Move cursor down to next delimiter
318 delim2 = 'k-points in reciprocal lattice and weights'
319 for offset, line in enumerate(lines[cursor:], start=0):
320 line = line.strip()
321 if delim2 in line:
322 # build k-points
323 ibzkpts = np.zeros((nkpts, 3))
324 kpt_weights = np.zeros(nkpts)
325 for nk in range(nkpts):
326 # Offset by 1, as k-points starts on the next line
327 line = lines[cursor + offset + nk + 1].strip()
328 parts = line.split()
329 ibzkpts[nk] = list(map(float, parts[:3]))
330 kpt_weights[nk] = float(parts[-1])
331 results['ibzkpts'] = ibzkpts
332 results['kpt_weights'] = kpt_weights
333 break
334 else:
335 raise ParseError('Did not find the K-points in the OUTCAR')
337 return results
340class Stress(SimpleVaspChunkParser):
341 """Process the stress from an OUTCAR"""
343 LINE_DELIMITER = 'in kB '
345 def parse(self, cursor: _CURSOR, lines: _CHUNK) -> _RESULT:
346 line = self.get_line(cursor, lines)
347 result: Sequence[float] | None = None
348 try:
349 stress = [float(a) for a in line.split()[2:]]
350 except ValueError:
351 # Vasp FORTRAN string formatting issues, can happen with
352 # some bad geometry steps Alternatively, we can re-raise
353 # as a ParseError?
354 warn('Found badly formatted stress line. Setting stress to None.')
355 else:
356 result = convert_vasp_outcar_stress(stress)
357 return {'stress': result}
360class Cell(SimpleVaspChunkParser):
361 LINE_DELIMITER = 'direct lattice vectors'
363 def parse(self, cursor: _CURSOR, lines: _CHUNK) -> _RESULT:
364 nskip = 1
365 cell = np.zeros((3, 3))
366 for i in range(3):
367 line = self.get_line(cursor + i + nskip, lines)
368 parts = line.split()
369 cell[i, :] = list(map(float, parts[0:3]))
370 return {'cell': cell}
373class PositionsAndForces(SimpleVaspChunkParser):
374 """Positions and forces are written in the same block.
375 We parse both simultaneously"""
377 LINE_DELIMITER = 'POSITION '
379 def parse(self, cursor: _CURSOR, lines: _CHUNK) -> _RESULT:
380 nskip = 2
381 natoms = self.get_from_header('natoms')
382 positions = np.zeros((natoms, 3))
383 forces = np.zeros((natoms, 3))
385 for i in range(natoms):
386 line = self.get_line(cursor + i + nskip, lines)
387 parts = list(map(float, line.split()))
388 positions[i] = parts[0:3]
389 forces[i] = parts[3:6]
390 return {'positions': positions, 'forces': forces}
393class Magmom(VaspChunkPropertyParser):
394 def has_property(self, cursor: _CURSOR, lines: _CHUNK) -> bool:
395 """We need to check for two separate delimiter strings,
396 to ensure we are at the right place"""
397 line = lines[cursor]
398 if 'number of electron' in line:
399 parts = line.split()
400 if len(parts) > 5 and parts[0].strip() != 'NELECT':
401 return True
402 return False
404 def parse(self, cursor: _CURSOR, lines: _CHUNK) -> _RESULT:
405 line = self.get_line(cursor, lines)
406 parts = line.split()
407 idx = parts.index('magnetization') + 1
408 magmom_lst = parts[idx:]
409 if len(magmom_lst) != 1:
410 magmom: np.ndarray | float = np.array(list(map(float, magmom_lst)))
411 else:
412 magmom = float(magmom_lst[0])
413 return {'magmom': magmom}
416class Magmoms(VaspChunkPropertyParser):
417 def has_property(self, cursor: _CURSOR, lines: _CHUNK) -> bool:
418 line = lines[cursor]
419 if 'magnetization (x)' in line:
420 natoms = self.get_from_header('natoms')
421 self.non_collinear = False
422 if cursor + natoms + 9 < len(lines):
423 line_y = self.get_line(cursor + natoms + 9, lines)
424 if 'magnetization (y)' in line_y:
425 self.non_collinear = True
426 return True
427 return False
429 def parse(self, cursor: _CURSOR, lines: _CHUNK) -> _RESULT:
431 natoms = self.get_from_header('natoms')
432 if self.non_collinear:
433 magmoms = np.zeros((natoms, 3))
434 nskip = 4 # Skip some lines
435 for i in range(natoms):
436 line = self.get_line(cursor + i + nskip, lines)
437 magmoms[i, 0] = float(line.split()[-1])
438 nskip = natoms + 13 # Skip some lines
439 for i in range(natoms):
440 line = self.get_line(cursor + i + nskip, lines)
441 magmoms[i, 1] = float(line.split()[-1])
442 nskip = 2 * natoms + 22 # Skip some lines
443 for i in range(natoms):
444 line = self.get_line(cursor + i + nskip, lines)
445 magmoms[i, 2] = float(line.split()[-1])
446 else:
447 magmoms = np.zeros(natoms)
448 nskip = 4 # Skip some lines
449 for i in range(natoms):
450 line = self.get_line(cursor + i + nskip, lines)
451 magmoms[i] = float(line.split()[-1])
453 return {'magmoms': magmoms}
456class EFermi(SimpleVaspChunkParser):
457 LINE_DELIMITER = 'E-fermi :'
459 def parse(self, cursor: _CURSOR, lines: _CHUNK) -> _RESULT:
460 line = self.get_line(cursor, lines)
461 parts = line.split()
462 efermi = float(parts[2])
463 return {'efermi': efermi}
466class Energy(SimpleVaspChunkParser):
467 LINE_DELIMITER = _OUTCAR_SCF_DELIM
469 def parse(self, cursor: _CURSOR, lines: _CHUNK) -> _RESULT:
470 nskip = 2
471 line = self.get_line(cursor + nskip, lines)
472 parts = line.strip().split()
473 energy_free = float(parts[4]) # Force consistent
475 nskip = 4
476 line = self.get_line(cursor + nskip, lines)
477 parts = line.strip().split()
478 energy_zero = float(parts[6]) # Extrapolated to 0 K
480 return {'free_energy': energy_free, 'energy': energy_zero}
483class Kpoints(VaspChunkPropertyParser):
484 def has_property(self, cursor: _CURSOR, lines: _CHUNK) -> bool:
485 line = lines[cursor]
486 # Example line:
487 # " spin component 1" or " spin component 2"
488 # We only check spin up, as if we are spin-polarized, we'll parse that
489 # as well
490 if 'spin component 1' in line:
491 parts = line.strip().split()
492 # This string is repeated elsewhere, but not with this exact shape
493 if len(parts) == 3:
494 try:
495 # The last part of te line should be an integer, denoting
496 # spin-up or spin-down
497 int(parts[-1])
498 except ValueError:
499 pass
500 else:
501 return True
502 return False
504 def parse(self, cursor: _CURSOR, lines: _CHUNK) -> _RESULT:
505 nkpts = self.get_from_header('nkpts')
506 nbands = self.get_from_header('nbands')
507 weights = self.get_from_header('kpt_weights')
508 spinpol = self.get_from_header('spinpol')
509 nspins = 2 if spinpol else 1
511 kpts = []
512 for spin in range(nspins):
513 # for Vasp 6, they added some extra information after the
514 # spin components. so we might need to seek the spin
515 # component line
516 cursor = search_lines(f'spin component {spin + 1}', cursor, lines)
518 cursor += 2 # Skip two lines
519 for _ in range(nkpts):
520 # Skip empty lines
521 cursor = find_next_non_empty_line(cursor, lines)
523 line = self.get_line(cursor, lines)
524 # Example line:
525 # "k-point 1 : 0.0000 0.0000 0.0000"
526 parts = line.strip().split()
527 ikpt = int(parts[1]) - 1 # Make kpt idx start from 0
528 weight = weights[ikpt]
530 cursor += 2 # Move down two
531 eigenvalues = np.zeros(nbands)
532 occupations = np.zeros(nbands)
533 for n in range(nbands):
534 # Example line:
535 # " 1 -9.9948 1.00000"
536 parts = lines[cursor].strip().split()
537 eps_n, f_n = map(float, parts[1:])
538 occupations[n] = f_n
539 eigenvalues[n] = eps_n
540 cursor += 1
541 kpt = SinglePointKPoint(
542 weight, spin, ikpt, eps_n=eigenvalues, f_n=occupations
543 )
544 kpts.append(kpt)
546 return {'kpts': kpts}
549class DefaultParsersContainer:
550 """Container for the default OUTCAR parsers.
551 Allows for modification of the global default parsers.
553 Takes in an arbitrary number of parsers.
554 The parsers should be uninitialized,
555 as they are created on request.
556 """
558 def __init__(self, *parsers_cls):
559 self._parsers_dct = {}
560 for parser in parsers_cls:
561 self.add_parser(parser)
563 @property
564 def parsers_dct(self) -> dict:
565 return self._parsers_dct
567 def make_parsers(self):
568 """Return a copy of the internally stored parsers.
569 Parsers are created upon request."""
570 return [parser() for parser in self.parsers_dct.values()]
572 def remove_parser(self, name: str):
573 """Remove a parser based on the name.
574 The name must match the parser name exactly."""
575 self.parsers_dct.pop(name)
577 def add_parser(self, parser) -> None:
578 """Add a parser"""
579 self.parsers_dct[parser.get_name()] = parser
582class TypeParser(ABC):
583 """Base class for parsing a type, e.g. header or chunk,
584 by applying the internal attached parsers"""
586 def __init__(self, parsers):
587 self.parsers = parsers
589 @property
590 def parsers(self):
591 return self._parsers
593 @parsers.setter
594 def parsers(self, new_parsers) -> None:
595 self._check_parsers(new_parsers)
596 self._parsers = new_parsers
598 @abstractmethod
599 def _check_parsers(self, parsers) -> None:
600 """Check the parsers are of correct type"""
602 def parse(self, lines) -> _RESULT:
603 """Execute the attached paresers, and return the parsed properties"""
604 properties = {}
605 for cursor, _ in enumerate(lines):
606 for parser in self.parsers:
607 # Check if any of the parsers can extract a property
608 # from this line Note: This will override any existing
609 # properties we found, if we found it previously. This
610 # is usually correct, as some VASP settings can cause
611 # certain pieces of information to be written multiple
612 # times during SCF. We are only interested in the
613 # final values within a given chunk.
614 if parser.has_property(cursor, lines):
615 prop = parser.parse(cursor, lines)
616 properties.update(prop)
617 return properties
620class ChunkParser(TypeParser, ABC):
621 def __init__(self, parsers, header=None):
622 super().__init__(parsers)
623 self.header = header
625 @property
626 def header(self) -> _HEADER:
627 return self._header
629 @header.setter
630 def header(self, value: _HEADER | None) -> None:
631 self._header = value or {}
632 self.update_parser_headers()
634 def update_parser_headers(self) -> None:
635 """Apply the header to all available parsers"""
636 for parser in self.parsers:
637 parser.header = self.header
639 def _check_parsers(
640 self, parsers: Sequence[VaspChunkPropertyParser]
641 ) -> None:
642 """Check the parsers are of correct type 'VaspChunkPropertyParser'"""
643 if not all(
644 isinstance(parser, VaspChunkPropertyParser) for parser in parsers
645 ):
646 raise TypeError(
647 'All parsers must be of type VaspChunkPropertyParser'
648 )
650 @abstractmethod
651 def build(self, lines: _CHUNK) -> Atoms:
652 """Construct an atoms object of the chunk from the parsed results"""
655class HeaderParser(TypeParser, ABC):
656 def _check_parsers(
657 self, parsers: Sequence[VaspHeaderPropertyParser]
658 ) -> None:
659 """Check the parsers are of correct type 'VaspHeaderPropertyParser'"""
660 if not all(
661 isinstance(parser, VaspHeaderPropertyParser) for parser in parsers
662 ):
663 raise TypeError(
664 'All parsers must be of type VaspHeaderPropertyParser'
665 )
667 @abstractmethod
668 def build(self, lines: _CHUNK) -> _HEADER:
669 """Construct the header object from the parsed results"""
672class OutcarChunkParser(ChunkParser):
673 """Class for parsing a chunk of an OUTCAR."""
675 def __init__(
676 self,
677 header: _HEADER | None = None,
678 parsers: Sequence[VaspChunkPropertyParser] | None = None,
679 ):
680 global default_chunk_parsers
681 parsers = parsers or default_chunk_parsers.make_parsers()
682 super().__init__(parsers, header=header)
684 def build(self, lines: _CHUNK) -> Atoms:
685 """Apply outcar chunk parsers, and build an atoms object"""
686 self.update_parser_headers() # Ensure header is in sync
688 results = self.parse(lines)
689 symbols = self.header['symbols']
690 constraint = self.header.get('constraint', None)
692 atoms_kwargs = dict(symbols=symbols, constraint=constraint, pbc=True)
694 # Find some required properties in the parsed results.
695 # Raise ParseError if they are not present
696 for prop in ('positions', 'cell'):
697 try:
698 atoms_kwargs[prop] = results.pop(prop)
699 except KeyError:
700 raise ParseError(
701 'Did not find required property {} during parse.'.format(
702 prop
703 )
704 )
705 atoms = Atoms(**atoms_kwargs)
707 kpts = results.pop('kpts', None)
708 calc = SinglePointDFTCalculator(atoms, **results)
709 if kpts is not None:
710 calc.kpts = kpts
711 calc.name = 'vasp'
712 atoms.calc = calc
713 return atoms
716class OutcarHeaderParser(HeaderParser):
717 """Class for parsing a chunk of an OUTCAR."""
719 def __init__(
720 self,
721 parsers: Sequence[VaspHeaderPropertyParser] | None = None,
722 workdir: str | PurePath | None = None,
723 ):
724 global default_header_parsers
725 parsers = parsers or default_header_parsers.make_parsers()
726 super().__init__(parsers)
727 self.workdir = workdir
729 @property
730 def workdir(self):
731 return self._workdir
733 @workdir.setter
734 def workdir(self, value):
735 if value is not None:
736 value = Path(value)
737 self._workdir = value
739 def _build_symbols(self, results: _RESULT) -> Sequence[str]:
740 if 'symbols' in results:
741 # Safeguard, in case a different parser already
742 # did this. Not currently available in a default parser
743 return results.pop('symbols')
745 # Build the symbols of the atoms
746 for required_key in ('ion_types', 'species'):
747 if required_key not in results:
748 raise ParseError(
749 'Did not find required key "{}" in parsed header '
750 'results.'.format(required_key)
751 )
753 ion_types = results.pop('ion_types')
754 species = results.pop('species')
755 if len(ion_types) != len(species):
756 raise ParseError(
757 (
758 'Expected length of ion_types to be same as species, '
759 'but got ion_types={} and species={}'
760 ).format(len(ion_types), len(species))
761 )
763 # Expand the symbols list
764 symbols = []
765 for n, sym in zip(ion_types, species):
766 symbols.extend(n * [sym])
767 return symbols
769 def _get_constraint(self):
770 """Try and get the constraints from the POSCAR of CONTCAR
771 since they aren't located in the OUTCAR, and thus we cannot construct an
772 OUTCAR parser which does this.
773 """
774 constraint = None
775 if self.workdir is not None:
776 constraint = read_constraints_from_file(self.workdir)
777 return constraint
779 def build(self, lines: _CHUNK) -> _RESULT:
780 """Apply the header parsers, and build the header"""
781 results = self.parse(lines)
783 # Get the symbols from the parsed results
784 # will pop the keys which we use for that purpose
785 symbols = self._build_symbols(results)
786 natoms = len(symbols)
788 constraint = self._get_constraint()
790 # Remaining results from the parse goes into the header
791 header = dict(
792 symbols=symbols, natoms=natoms, constraint=constraint, **results
793 )
794 return header
797class OUTCARChunk(ImageChunk):
798 """Container class for a chunk of the OUTCAR which consists of a
799 self-contained SCF step, i.e. and image. Also contains the header_data
800 """
802 def __init__(
803 self, lines: _CHUNK, header: _HEADER, parser: ChunkParser | None = None
804 ):
805 super().__init__()
806 self.lines = lines
807 self.header = header
808 self.parser = parser or OutcarChunkParser()
810 def build(self):
811 self.parser.header = self.header # Ensure header is syncronized
812 return self.parser.build(self.lines)
815def build_header(fd: TextIO) -> _CHUNK:
816 """Build a chunk containing the header data"""
817 lines = []
818 for line in fd:
819 lines.append(line)
820 if 'Iteration' in line:
821 # Start of SCF cycle
822 return lines
824 # We never found the SCF delimiter, so the OUTCAR must be incomplete
825 raise ParseError('Incomplete OUTCAR')
828def build_chunk(fd: TextIO) -> _CHUNK:
829 """Build chunk which contains 1 complete atoms object"""
830 lines = []
831 while True:
832 line = next(fd)
833 lines.append(line)
834 if _OUTCAR_SCF_DELIM in line:
835 # Add 4 more lines to include energy
836 for _ in range(4):
837 lines.append(next(fd))
838 break
839 return lines
842def outcarchunks(
843 fd: TextIO,
844 chunk_parser: ChunkParser | None = None,
845 header_parser: HeaderParser | None = None,
846) -> Iterator[OUTCARChunk]:
847 """Function to build chunks of OUTCAR from a file stream"""
848 name = Path(fd.name)
849 workdir = name.parent
851 # First we get header info
852 # pass in the workdir from the fd, so we can try and get the constraints
853 header_parser = header_parser or OutcarHeaderParser(workdir=workdir)
855 lines = build_header(fd)
856 header = header_parser.build(lines)
857 assert isinstance(header, dict)
859 chunk_parser = chunk_parser or OutcarChunkParser()
861 while True:
862 try:
863 lines = build_chunk(fd)
864 except StopIteration:
865 # End of file
866 return
867 yield OUTCARChunk(lines, header, parser=chunk_parser)
870# Create the default chunk parsers
871default_chunk_parsers = DefaultParsersContainer(
872 Cell,
873 PositionsAndForces,
874 Stress,
875 Magmoms,
876 Magmom,
877 EFermi,
878 Kpoints,
879 Energy,
880)
882# Create the default header parsers
883default_header_parsers = DefaultParsersContainer(
884 SpeciesTypes,
885 IonsPerSpecies,
886 Spinpol,
887 KpointHeader,
888)