Coverage for ase/io/runner/reader.py: 100.00%
37 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"""RuNNer input.data support
3Read files in RuNNer's input.data file format.
5Contains
6--------
7* `read_runnerdata`: Read structures from a RuNNer input.data file.
9Reference
10---------
11* [The online documentation of RuNNer 2.0](https://runner-suite.gitlab.io/runner2)
13Contributors
14------------
15* Maintainer and Author: [Alexander Knoll](mailto:alexander.knoll@rub.de)
16* Author: [Redouan El Haouari](mailto:redouan.elhaouari@rub.de)
17"""
19import re
20from collections.abc import Iterator
21from typing import TextIO
23from ase.atoms import Atoms
24from ase.utils import reader
26from .runneratoms import (
27 DEFAULT_ATOM_LAYOUT,
28 PROP_NAME_DICT,
29 RuNNerAtoms,
30 Units,
31)
33# Regex pattern for vector properties like "forces(3)"
34_vector_pattern = re.compile(r'([\w\-]+)\((\d+)\)')
37def _parse_begin(begin_line: str) -> list[tuple[str, int]]:
38 """Parse the begin line to determine per-atom property layout.
40 Returns a list of (name, length) for all properties (vector or scalar).
41 Scalars have length 1.
43 The two default fields "positions" and "element" are skipped.
44 """
45 fields = begin_line.strip().split()[1:]
46 layout: list[tuple[str, int]] = []
48 if len(fields) == 0:
49 return DEFAULT_ATOM_LAYOUT
51 # skip the first two fields (position, element), since they are fixed.
52 for field in fields[2:]:
53 match = _vector_pattern.fullmatch(field)
54 if match:
55 name, length = match.group(1), int(match.group(2))
56 else:
57 name = field
58 length = 1
60 # Normalize property names by replacing them with the defaults defined
61 # in the dictionary PROP_NAME_DICT.
62 name = PROP_NAME_DICT.get(name, name)
64 layout.append((name, length))
66 return layout
69def _parse_chunk(
70 chunk: str, begin_line: str, input_units: Units
71) -> RuNNerAtoms:
72 """Parse a single chunk into a RuNNerAtoms object."""
73 atom_layout = _parse_begin(begin_line)
75 runneratoms = RuNNerAtoms(
76 atom_layout=atom_layout,
77 input_units=input_units,
78 num_atom_columns=sum([i for _, i in atom_layout]) + 4,
79 )
81 for line in chunk.splitlines():
82 runneratoms.parse_line(line)
84 return runneratoms
87@reader
88def read_runnerdata(
89 infile: TextIO,
90 index: int | slice = -1,
91 input_units: Units = Units.ATOMIC,
92 output_units: Units = Units.ASE,
93) -> Iterator[Atoms]:
94 """Parse all structures within a RuNNer input.data file.
96 input.data files contain all structural information needed to train a
97 Behler-Parrinello-type neural network potential, e.g. Cart. coordinates,
98 atomic forces, and energies. This function reads the file object `infile`
99 and returns the slice of structures given by `index`. All structures will
100 be converted to ASE units by default.
102 Parameters
103 ----------
104 infile:
105 Python fileobj with the target input.data file.
106 index:
107 The slice of structures which should be returned. Returns only the last
108 structure by default.
109 input_units:
110 The given input units. Can be 'Units.ASE' or 'Units.ATOMIC'.
111 output_units:
112 The desired output units. Can be 'Units.ASE' or 'Units.ATOMIC'.
114 Yields
115 ------
116 images:
117 All information about the structures within `index` of `infile`,
118 including symbols, positions, atomic charges, and cell lattice. Every
119 `Atoms` object has a `RunnerSinglePointCalculator` attached with
120 additional information on the total energy, atomic forces, and total
121 charge.
123 """
124 # First, split input.data into separate structure "chunks".
125 read_infile = infile.read()
126 # First chunk is discarded because it is the data before the
127 # first "begin".
128 begin_pattern = re.compile(r'begin.*\n')
129 chunks = begin_pattern.split(read_infile)[1:]
130 begin_lines = begin_pattern.findall(read_infile)
132 # Second, only parse the chunks which the user asked for.
133 for begin_line, chunk in zip(begin_lines[index], chunks[index]):
134 runneratoms = _parse_chunk(chunk, begin_line, input_units)
136 runneratoms.convert(output_units)
137 yield runneratoms.to_ase_atoms()