Coverage for ase/io/zmatrix.py: 95.42%
131 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
1import re
2from collections import namedtuple
3from numbers import Real
4from string import digits
6import numpy as np
8from ase import Atoms
9from ase.units import Angstrom, Bohr, nm
11# split on newlines or semicolons
12_re_linesplit = re.compile(r'\n|;')
13# split definitions on whitespace or on "=" (possibly also with whitespace)
14_re_defs = re.compile(r'\s*=\s*|\s+')
17_ZMatrixRow = namedtuple(
18 '_ZMatrixRow',
19 'ind1 dist ind2 a_bend ind3 a_dihedral',
20)
23ThreeFloats = tuple[float, float, float] | np.ndarray
26def require(condition):
27 # (This is not good error handling, but it replaces assertions.)
28 if not condition:
29 raise RuntimeError('Internal requirement violated')
32class _ZMatrixToAtoms:
33 known_units = dict(
34 distance={'angstrom': Angstrom, 'bohr': Bohr, 'au': Bohr, 'nm': nm},
35 angle={'radians': 1.0, 'degrees': np.pi / 180},
36 )
38 def __init__(
39 self,
40 dconv: str | Real,
41 aconv: str | Real,
42 defs: dict[str, float] | str | list[str] | None = None,
43 ) -> None:
44 self.dconv = self.get_units('distance', dconv) # type: float
45 self.aconv = self.get_units('angle', aconv) # type: float
46 self.set_defs(defs)
47 self.name_to_index: dict[str, int] | None = {}
48 self.symbols: list[str] = []
49 self.positions: list[ThreeFloats] = []
51 @property
52 def nrows(self):
53 return len(self.symbols)
55 def get_units(self, kind: str, value: str | Real) -> float:
56 if isinstance(value, Real):
57 return float(value)
58 out = self.known_units[kind].get(value.lower())
59 if out is None:
60 raise ValueError('Unknown {} units: {}'.format(kind, value))
61 return out
63 def set_defs(self, defs: dict[str, float] | str | list[str] | None) -> None:
64 self.defs = {} # type: dict[str, float]
65 if defs is None:
66 return
68 if isinstance(defs, dict):
69 self.defs.update(**defs)
70 return
72 if isinstance(defs, str):
73 defs = _re_linesplit.split(defs.strip())
75 for row in defs:
76 key, val = _re_defs.split(row)
77 self.defs[key] = self.get_var(val)
79 def get_var(self, val: str) -> float:
80 try:
81 return float(val)
82 except ValueError as e:
83 val_out = self.defs.get(val.lstrip('+-'))
84 if val_out is None:
85 raise ValueError(
86 'Invalid value encountered in Z-matrix: {}'.format(val)
87 ) from e
88 return val_out * (-1 if val.startswith('-') else 1)
90 def get_index(self, name: str) -> int:
91 """Find index for a given atom name"""
92 try:
93 return int(name) - 1
94 except ValueError as e:
95 if self.name_to_index is None or name not in self.name_to_index:
96 raise ValueError(
97 'Failed to determine index for name "{}"'.format(name)
98 ) from e
99 return self.name_to_index[name]
101 def set_index(self, name: str) -> None:
102 """Assign index to a given atom name for name -> index lookup"""
103 if self.name_to_index is None:
104 return
106 if name in self.name_to_index:
107 # "name" has been encountered before, so name_to_index is no
108 # longer meaningful. Destroy the map.
109 self.name_to_index = None
110 return
112 self.name_to_index[name] = self.nrows
114 # Use typehint *indices: str from python3.11+
115 def validate_indices(self, *indices) -> None:
116 """Raises an error if indices in a Z-matrix row are invalid."""
117 if any(np.array(indices) >= self.nrows):
118 raise ValueError(
119 'An invalid Z-matrix was provided! Row {} refers '
120 'to atom indices {}, at least one of which '
121 "hasn't been defined yet!".format(self.nrows, indices)
122 )
124 if len(indices) != len(set(indices)):
125 raise ValueError(
126 'An atom index has been used more than once a '
127 'row of the Z-matrix! Row numbers {}, '
128 'referred indices: {}'.format(self.nrows, indices)
129 )
131 def parse_row(
132 self, row: str
133 ) -> tuple[
134 str,
135 _ZMatrixRow | ThreeFloats,
136 ]:
137 tokens = row.split()
138 name = tokens[0]
139 self.set_index(name)
140 if len(tokens) == 1:
141 require(self.nrows == 0)
142 return name, np.zeros(3, dtype=float)
144 ind1 = self.get_index(tokens[1])
145 if ind1 == -1:
146 require(len(tokens) == 5)
147 return name, np.array(
148 list(map(self.get_var, tokens[2:])), dtype=float
149 )
151 dist = self.dconv * self.get_var(tokens[2])
153 if len(tokens) == 3:
154 require(self.nrows == 1)
155 self.validate_indices(ind1)
156 return name, np.array([dist, 0, 0], dtype=float)
158 ind2 = self.get_index(tokens[3])
159 a_bend = self.aconv * self.get_var(tokens[4])
161 if len(tokens) == 5:
162 require(self.nrows == 2)
163 self.validate_indices(ind1, ind2)
164 return name, _ZMatrixRow(ind1, dist, ind2, a_bend, None, None)
166 ind3 = self.get_index(tokens[5])
167 a_dihedral = self.aconv * self.get_var(tokens[6])
168 self.validate_indices(ind1, ind2, ind3)
169 return name, _ZMatrixRow(ind1, dist, ind2, a_bend, ind3, a_dihedral)
171 def add_atom(self, name: str, pos: ThreeFloats) -> None:
172 """Sets the symbol and position of an atom."""
173 self.symbols.append(
174 ''.join([c for c in name if c not in digits]).capitalize()
175 )
176 self.positions.append(pos)
178 def add_row(self, row: str) -> None:
179 name, zrow = self.parse_row(row)
181 if not isinstance(zrow, _ZMatrixRow):
182 self.add_atom(name, zrow)
183 return
185 if zrow.ind3 is None:
186 # This is the third atom, so only a bond distance and an angle
187 # have been provided.
188 pos = self.positions[zrow.ind1].copy()
189 pos[0] += zrow.dist * np.cos(zrow.a_bend) * (zrow.ind2 - zrow.ind1)
190 pos[1] += zrow.dist * np.sin(zrow.a_bend)
191 self.add_atom(name, pos)
192 return
194 # ax1 is the dihedral axis, which is defined by the bond vector
195 # between the two inner atoms in the dihedral, ind1 and ind2
196 ax1 = self.positions[zrow.ind2] - self.positions[zrow.ind1]
197 ax1 /= np.linalg.norm(ax1)
199 # ax2 lies within the 1-2-3 plane, and it is perpendicular
200 # to the dihedral axis
201 ax2 = self.positions[zrow.ind2] - self.positions[zrow.ind3]
202 ax2 -= ax1 * (ax2 @ ax1)
203 ax2 /= np.linalg.norm(ax2)
205 # ax3 is a vector that forms the appropriate dihedral angle, though
206 # the bending angle is 90 degrees, rather than a_bend. It is formed
207 # from a linear combination of ax2 and (ax2 x ax1)
208 ax3 = ax2 * np.cos(zrow.a_dihedral) + np.cross(ax2, ax1) * np.sin(
209 zrow.a_dihedral
210 )
212 # The final position vector is a linear combination of ax1 and ax3.
213 pos = ax1 * np.cos(zrow.a_bend) - ax3 * np.sin(zrow.a_bend)
214 pos *= zrow.dist / np.linalg.norm(pos)
215 pos += self.positions[zrow.ind1]
216 self.add_atom(name, pos)
218 def to_atoms(self) -> Atoms:
219 return Atoms(self.symbols, self.positions)
222def parse_zmatrix(
223 zmat: str | list[str],
224 distance_units: str | Real = 'angstrom',
225 angle_units: str | Real = 'degrees',
226 defs: dict[str, float] | str | list[str] | None = None,
227) -> Atoms:
228 """Converts a Z-matrix into an Atoms object.
230 Parameters
231 ----------
233 zmat: Iterable or str
234 The Z-matrix to be parsed. Iteration over `zmat` should yield the rows
235 of the Z-matrix. If `zmat` is a str, it will be automatically split
236 into a list at newlines.
237 distance_units: str or float, optional
238 The units of distance in the provided Z-matrix.
239 Defaults to Angstrom.
240 angle_units: str or float, optional
241 The units for angles in the provided Z-matrix.
242 Defaults to degrees.
243 defs: dict or str, optional
244 If `zmat` contains symbols for bond distances, bending angles, and/or
245 dihedral angles instead of numeric values, then the definition of
246 those symbols should be passed to this function using this keyword
247 argument.
248 Note: The symbol definitions are typically printed adjacent to the
249 Z-matrix itself, but this function will not automatically separate
250 the symbol definitions from the Z-matrix.
252 Returns
253 -------
255 atoms: Atoms object
256 """
257 zmatrix = _ZMatrixToAtoms(distance_units, angle_units, defs=defs)
259 # zmat should be a list containing the rows of the z-matrix.
260 # for convenience, allow block strings and split at newlines.
261 if isinstance(zmat, str):
262 zmat = _re_linesplit.split(zmat.strip())
264 for row in zmat:
265 zmatrix.add_row(row)
267 return zmatrix.to_atoms()