Skip to content

Commit

Permalink
Merge pull request #242 from SCM-NV/pressure
Browse files Browse the repository at this point in the history
BUG: Fixed an issue where reading pressures could fail for cp2k <8.0
  • Loading branch information
BvB93 committed Mar 4, 2021
2 parents a1111ba + 139ec50 commit 8824a9b
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 8 deletions.
4 changes: 4 additions & 0 deletions src/qmflows/data/dictionaries/propertiesCP2K.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,7 @@ lattice:
column_start: 2
column_stop: 11
row_start: 1
pressure:
file_ext: out
function: read_cp2k_pressure
parser: cp2KParser
7 changes: 2 additions & 5 deletions src/qmflows/data/dictionaries/propertiesCP2KMM.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,5 @@ lattice:
row_start: 1
pressure:
file_ext: out
function: extract_line_values
kwargs:
pattern: MD| Pressure
pos: 3
parser: generic_parsers
function: read_cp2k_pressure
parser: cp2KParser
53 changes: 52 additions & 1 deletion src/qmflows/parsers/cp2KParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from io import TextIOBase
from itertools import islice, chain
from pathlib import Path
from typing import Any, Dict, FrozenSet, Generator, Iterable, List
from typing import Any, Dict, FrozenSet, Generator, Iterable, List, IO
from typing import Optional as Optional_
from typing import Sequence, Tuple, Type, TypeVar, Union, overload, Iterator

Expand Down Expand Up @@ -636,3 +636,54 @@ def read_cp2k_table_slc(
ret = np.fromiter(flat_iter, dtype=dtype)
ret.shape = shape
return ret


def _get_pressure_iter(major: int, f: IO[str]) -> Generator[str, None, None]:
"""Helper function for :func:`read_cp2k_pressure`."""
# NOTE: CP2K 8.* changed the strucure of its `.out` files,
# hence the different prefix
prefix1 = " MD_PAR| Pressure" if major >= 8 else " MD| Pressure"
prefix2 = " MD| Pressure" if major >= 8 else " PRESSURE"

# Read the initial pressure
for i in f:
if i.startswith(prefix1):
yield i.split()[-1]
break
else:
raise RuntimeError("Failed to identify the initial pressure")

# Read all subsequent pressures
for i in f:
if i.startswith(prefix2):
yield i.split()[-2]


def read_cp2k_pressure(
path: PathLike,
start: Optional_[int] = None,
stop: Optional_[int] = None,
step: Optional_[int] = None,
dtype: Any = np.float64,
) -> np.ndarray:
"""Return all pressures from the passed cp2k ``.out`` file as an array."""
# Identify the CP2K version
major = 0
with open(path, 'r') as f:
for i in f:
if i.startswith(" CP2K| version string:"):
version_str = i.split()[-1]
major_str = version_str.split(".")[0]

# if an error is encoutered here then we must be dealing with
# a very old CP2K version; fall back to `major = 0` in such case
try:
major = int(major_str)
except ValueError:
pass
break

# Read the pressures
with open(path, 'r') as f:
iterator = _get_pressure_iter(major, f)
return np.fromiter(islice(iterator, start, stop, step), dtype=dtype)
4 changes: 2 additions & 2 deletions src/qmflows/type_hints.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"""

from typing import (Mapping, Dict, Type, Callable, Optional, MutableMapping, Union,
Sequence, Any, AnyStr, TYPE_CHECKING)
Sequence, Any, TYPE_CHECKING)

from .common import ParseWarning
from .backports import Literal, T, Final
Expand Down Expand Up @@ -83,7 +83,7 @@

#: An alias for all path-like objects.
#: Includes the likes of :class:`str`, :class:`bytes` and :class:`pathlib.Path`.
PathLike = Union[AnyStr, _PathLike]
PathLike = Union[str, bytes, _PathLike]

#: An rdkit or PLAMS molecule.
MolType = Union[Mol, Molecule]
Expand Down
Binary file modified test/test_files/pressure.npy
Binary file not shown.

0 comments on commit 8824a9b

Please sign in to comment.