PageRenderTime 77ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/ase/io/zmatrix.py

https://gitlab.com/oschuett/ase
Python | 247 lines | 209 code | 30 blank | 8 comment | 23 complexity | 8212ab4aabe44e9f9733765bc20bbb4b MD5 | raw file
  1. from typing import Dict, List, Tuple, Union, Optional
  2. from numbers import Real
  3. from collections import namedtuple
  4. import re
  5. from string import digits
  6. import numpy as np
  7. from ase import Atoms
  8. from ase.units import Angstrom, Bohr, nm
  9. # split on newlines or semicolons
  10. _re_linesplit = re.compile(r'\n|;')
  11. # split definitions on whitespace or on "=" (possibly also with whitespace)
  12. _re_defs = re.compile(r'\s*=\s*|\s+')
  13. _ZMatrixRow = namedtuple(
  14. '_ZMatrixRow', 'ind1 dist ind2 a_bend ind3 a_dihedral',
  15. )
  16. ThreeFloats = Union[Tuple[float, float, float], np.ndarray]
  17. class _ZMatrixToAtoms:
  18. known_units = dict(
  19. distance={'angstrom': Angstrom, 'bohr': Bohr, 'au': Bohr, 'nm': nm},
  20. angle={'radians': 1., 'degrees': np.pi / 180},
  21. )
  22. def __init__(self, dconv: Union[str, Real], aconv: Union[str, Real],
  23. defs: Optional[Union[Dict[str, float],
  24. str, List[str]]] = None) -> None:
  25. self.dconv = self.get_units('distance', dconv) # type: float
  26. self.aconv = self.get_units('angle', aconv) # type: float
  27. self.set_defs(defs)
  28. self.name_to_index: Optional[Dict[str, int]] = dict()
  29. self.symbols: List[str] = []
  30. self.positions: List[ThreeFloats] = []
  31. @property
  32. def nrows(self):
  33. return len(self.symbols)
  34. def get_units(self, kind: str, value: Union[str, Real]) -> float:
  35. if isinstance(value, Real):
  36. return float(value)
  37. out = self.known_units[kind].get(value.lower())
  38. if out is None:
  39. raise ValueError("Unknown {} units: {}"
  40. .format(kind, value))
  41. return out
  42. def set_defs(self, defs: Union[Dict[str, float], str,
  43. List[str], None]) -> None:
  44. self.defs = dict() # type: Dict[str, float]
  45. if defs is None:
  46. return
  47. if isinstance(defs, dict):
  48. self.defs.update(**defs)
  49. return
  50. if isinstance(defs, str):
  51. defs = _re_linesplit.split(defs.strip())
  52. for row in defs:
  53. key, val = _re_defs.split(row)
  54. self.defs[key] = self.get_var(val)
  55. def get_var(self, val: str) -> float:
  56. try:
  57. return float(val)
  58. except ValueError as e:
  59. val_out = self.defs.get(val.lstrip('+-'))
  60. if val_out is None:
  61. raise ValueError('Invalid value encountered in Z-matrix: {}'
  62. .format(val)) from e
  63. return val_out * (-1 if val.startswith('-') else 1)
  64. def get_index(self, name: str) -> int:
  65. """Find index for a given atom name"""
  66. try:
  67. return int(name) - 1
  68. except ValueError as e:
  69. if self.name_to_index is None or name not in self.name_to_index:
  70. raise ValueError('Failed to determine index for name "{}"'
  71. .format(name)) from e
  72. return self.name_to_index[name]
  73. def set_index(self, name: str) -> None:
  74. """Assign index to a given atom name for name -> index lookup"""
  75. if self.name_to_index is None:
  76. return
  77. if name in self.name_to_index:
  78. # "name" has been encountered before, so name_to_index is no
  79. # longer meaningful. Destroy the map.
  80. self.name_to_index = None
  81. return
  82. self.name_to_index[name] = self.nrows
  83. def validate_indices(self, *indices: int) -> None:
  84. """Raises an error if indices in a Z-matrix row are invalid."""
  85. if any(np.array(indices) >= self.nrows):
  86. raise ValueError('An invalid Z-matrix was provided! Row {} refers '
  87. 'to atom indices {}, at least one of which '
  88. "hasn't been defined yet!"
  89. .format(self.nrows, indices))
  90. if len(indices) != len(set(indices)):
  91. raise ValueError('An atom index has been used more than once a '
  92. 'row of the Z-matrix! Row numbers {}, '
  93. 'referred indices: {}'
  94. .format(self.nrows, indices))
  95. def parse_row(self, row: str) -> Tuple[
  96. str, Union[_ZMatrixRow, ThreeFloats],
  97. ]:
  98. tokens = row.split()
  99. name = tokens[0]
  100. self.set_index(name)
  101. if len(tokens) == 1:
  102. assert self.nrows == 0
  103. return name, np.zeros(3, dtype=float)
  104. ind1 = self.get_index(tokens[1])
  105. if ind1 == -1:
  106. assert len(tokens) == 5
  107. return name, np.array(list(map(self.get_var, tokens[2:])),
  108. dtype=float)
  109. dist = self.dconv * self.get_var(tokens[2])
  110. if len(tokens) == 3:
  111. assert self.nrows == 1
  112. self.validate_indices(ind1)
  113. return name, np.array([dist, 0, 0], dtype=float)
  114. ind2 = self.get_index(tokens[3])
  115. a_bend = self.aconv * self.get_var(tokens[4])
  116. if len(tokens) == 5:
  117. assert self.nrows == 2
  118. self.validate_indices(ind1, ind2)
  119. return name, _ZMatrixRow(ind1, dist, ind2, a_bend, None, None)
  120. ind3 = self.get_index(tokens[5])
  121. a_dihedral = self.aconv * self.get_var(tokens[6])
  122. self.validate_indices(ind1, ind2, ind3)
  123. return name, _ZMatrixRow(ind1, dist, ind2, a_bend, ind3,
  124. a_dihedral)
  125. def add_atom(self, name: str, pos: ThreeFloats) -> None:
  126. """Sets the symbol and position of an atom."""
  127. self.symbols.append(
  128. ''.join([c for c in name if c not in digits]).capitalize()
  129. )
  130. self.positions.append(pos)
  131. def add_row(self, row: str) -> None:
  132. name, zrow = self.parse_row(row)
  133. if not isinstance(zrow, _ZMatrixRow):
  134. self.add_atom(name, zrow)
  135. return
  136. if zrow.ind3 is None:
  137. # This is the third atom, so only a bond distance and an angle
  138. # have been provided.
  139. pos = self.positions[zrow.ind1].copy()
  140. pos[0] += zrow.dist * np.cos(zrow.a_bend) * (zrow.ind2 - zrow.ind1)
  141. pos[1] += zrow.dist * np.sin(zrow.a_bend)
  142. self.add_atom(name, pos)
  143. return
  144. # ax1 is the dihedral axis, which is defined by the bond vector
  145. # between the two inner atoms in the dihedral, ind1 and ind2
  146. ax1 = self.positions[zrow.ind2] - self.positions[zrow.ind1]
  147. ax1 /= np.linalg.norm(ax1)
  148. # ax2 lies within the 1-2-3 plane, and it is perpendicular
  149. # to the dihedral axis
  150. ax2 = self.positions[zrow.ind2] - self.positions[zrow.ind3]
  151. ax2 -= ax1 * (ax2 @ ax1)
  152. ax2 /= np.linalg.norm(ax2)
  153. # ax3 is a vector that forms the appropriate dihedral angle, though
  154. # the bending angle is 90 degrees, rather than a_bend. It is formed
  155. # from a linear combination of ax2 and (ax2 x ax1)
  156. ax3 = (ax2 * np.cos(zrow.a_dihedral)
  157. + np.cross(ax2, ax1) * np.sin(zrow.a_dihedral))
  158. # The final position vector is a linear combination of ax1 and ax3.
  159. pos = ax1 * np.cos(zrow.a_bend) - ax3 * np.sin(zrow.a_bend)
  160. pos *= zrow.dist / np.linalg.norm(pos)
  161. pos += self.positions[zrow.ind1]
  162. self.add_atom(name, pos)
  163. def to_atoms(self) -> Atoms:
  164. return Atoms(self.symbols, self.positions)
  165. def parse_zmatrix(zmat: Union[str, List[str]],
  166. distance_units: Union[str, Real] = 'angstrom',
  167. angle_units: Union[str, Real] = 'degrees',
  168. defs: Optional[Union[Dict[str, float], str,
  169. List[str]]] = None) -> Atoms:
  170. """Converts a Z-matrix into an Atoms object.
  171. Parameters:
  172. zmat: Iterable or str
  173. The Z-matrix to be parsed. Iteration over `zmat` should yield the rows
  174. of the Z-matrix. If `zmat` is a str, it will be automatically split
  175. into a list at newlines.
  176. distance_units: str or float, optional
  177. The units of distance in the provided Z-matrix.
  178. Defaults to Angstrom.
  179. angle_units: str or float, optional
  180. The units for angles in the provided Z-matrix.
  181. Defaults to degrees.
  182. defs: dict or str, optional
  183. If `zmat` contains symbols for bond distances, bending angles, and/or
  184. dihedral angles instead of numeric values, then the definition of
  185. those symbols should be passed to this function using this keyword
  186. argument.
  187. Note: The symbol definitions are typically printed adjacent to the
  188. Z-matrix itself, but this function will not automatically separate
  189. the symbol definitions from the Z-matrix.
  190. Returns:
  191. atoms: Atoms object
  192. """
  193. zmatrix = _ZMatrixToAtoms(distance_units, angle_units, defs=defs)
  194. # zmat should be a list containing the rows of the z-matrix.
  195. # for convenience, allow block strings and split at newlines.
  196. if isinstance(zmat, str):
  197. zmat = _re_linesplit.split(zmat.strip())
  198. for row in zmat:
  199. zmatrix.add_row(row)
  200. return zmatrix.to_atoms()