Coverage for ase/io/runner/runneratoms.py: 93.01%

143 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1"""Implementation of ASE Atom mimic for temporary fast I/O.""" 

2 

3from __future__ import annotations 

4 

5from collections import defaultdict 

6from dataclasses import dataclass, field 

7from enum import Enum 

8from numbers import Real 

9 

10import numpy as np 

11 

12from ase.atoms import Atoms 

13from ase.calculators.singlepoint import SinglePointCalculator 

14from ase.data import chemical_symbols 

15from ase.units import Bohr, Hartree 

16 

17vector_ndim = 2 

18# Arrays that may be stored in ase.Atoms.arrays but that we treat separately. 

19SKIPPED_ARRAYS = [ 

20 'numbers', 

21 'positions', 

22 'position', 

23 'element', 

24 'elements', 

25 'force', 

26 'forces', 

27] 

28 

29# Translation of property names to clean keys for internal storage. 

30PROP_NAME_DICT = { 

31 'positions': 'position', 

32 'forces': 'force', 

33 'initial_charges': 'charge', 

34 'initial_charge': 'charge', 

35 'charges': 'charge', 

36 'magnetic_moments': 'magmom', 

37 'magnetic_moment': 'magmom', 

38 'initial_magmoms': 'magmom', 

39 'magmoms': 'magmom', 

40 'elements': 'element', 

41 'symbols': 'element', 

42 'symbol': 'element', 

43 'hirshfeld_volumes': 'hirshv', 

44 'hirshfeld_volume': 'hirshv', 

45} 

46 

47# Translation of internal keys back to ASE-specific names. 

48TO_ASE_DICT = {'charge': 'initial_charges', 'magmom': 'initial_magmoms'} 

49 

50 

51DEFAULT_ATOM_LAYOUT = [('charge', 1), ('atom_energy', 1), ('force', 3)] 

52# The first four columns in an atom line are always position(3) and element. 

53ATOM_LAYOUT_OFFSET = 4 

54 

55CHEMICAL_SYMBOLS_SET = set(chemical_symbols) 

56 

57 

58class Units(Enum): 

59 ATOMIC = 'atomic' # (Ha, Bohr) 

60 ASE = 'ase' # (eV, Å) 

61 

62 

63@dataclass(slots=True) 

64class RuNNerAtoms: 

65 """Container for storing data about one atomic structure. 

66 

67 This class is intended for fast I/O of structural data. It is required as 

68 the builtin ASE `Atoms` and `Atom` classes are a bottleneck for large data 

69 files. This is mostly because adding an `Atom` to an `Atoms` object over 

70 and over again comes with a lot of overhead because the attached arrays 

71 have to be checked and copied. 

72 In constrast, it is very efficient to store atomic positions, symbols, etc. 

73 in long lists and simply create one ASE `Atoms` object once all atoms have 

74 been collected. In summary, `RuNNerAtoms` is simply a container to hold all 

75 these lists in one convenient place. 

76 """ 

77 

78 # Keep track of the units used to fill the internal storage. 

79 input_units: Units = Units.ASE 

80 # Store the length of each property in `self.atom_arrays`. 

81 atom_layout: list[tuple[str, int]] = field(default_factory=list) 

82 # Store the total number of columns specified by `atom_layout`. 

83 num_atom_columns: int = 0 

84 

85 # Mandatory arrays. 

86 positions: list[list[float]] = field(default_factory=list) 

87 symbols: list[str] = field(default_factory=list) 

88 cell: list[list[float]] = field(default_factory=list) 

89 

90 # Properties that end up in the attached SinglePointCalculator. 

91 energy: float | None = None 

92 forces: list[list[float]] | None = None 

93 

94 # Properties that end up in atoms.arrays 

95 atom_arrays: dict[str, list[float | list[float]]] = field( 

96 default_factory=lambda: defaultdict(list) 

97 ) 

98 

99 # Properties that end up in atoms.info 

100 total_charge: float = 0.0 

101 

102 def to_ase_atoms(self) -> Atoms: 

103 """Convert the object to an ASE Atoms object.""" 

104 

105 atoms = Atoms( 

106 positions=self.positions, 

107 symbols=self.symbols, 

108 ) 

109 

110 if self.cell: 

111 if len(self.cell) != 3: 

112 raise ValueError( 

113 'RuNNer requires the specification of 3 lattice vectors.' 

114 ) 

115 

116 atoms.set_cell(self.cell) 

117 atoms.pbc = True 

118 

119 for name, arr in self.atom_arrays.items(): 

120 if name in SKIPPED_ARRAYS: 

121 continue 

122 

123 name = TO_ASE_DICT.get(name, name) 

124 atoms.set_array(name, arr, dtype=np.float64) 

125 

126 atoms.info['total_charge'] = self.total_charge 

127 

128 atoms.calc = SinglePointCalculator( 

129 atoms, 

130 energy=self.energy, 

131 forces=self.forces, 

132 ) 

133 

134 return atoms 

135 

136 def _validate_atom_arrays(self) -> None: 

137 for name, arr in self.atom_arrays.items(): 

138 if len(arr) != len(self.positions): 

139 raise ValueError( 

140 f'The count ({len(arr)}) of custom property "{name}"', 

141 ' is not equal to the number of atoms', 

142 f' ({len(self.positions)}) in this structure', 

143 ) 

144 self.num_atom_columns = ( 

145 sum([i for _, i in self.atom_layout]) + ATOM_LAYOUT_OFFSET 

146 ) 

147 

148 # This type-hint is not quite correct for inherited classes: 

149 # from Python 3.11 use -> typing.Self 

150 @classmethod 

151 def from_ase_atoms( 

152 cls, 

153 atoms: Atoms, 

154 input_units: Units = Units.ASE, 

155 ) -> RuNNerAtoms: 

156 """Convert an ASE Atoms object to this class.""" 

157 # Construct the `atom_layout` for mapping arbitrary arrays. 

158 atom_layout = [] 

159 for name, arr in atoms.arrays.items(): 

160 if name in SKIPPED_ARRAYS: 

161 continue 

162 

163 name = PROP_NAME_DICT.get(name, name) 

164 

165 if arr.ndim == 1: 

166 length = 1 

167 elif arr.ndim == vector_ndim: 

168 length = arr.shape[1] 

169 else: 

170 raise ValueError( 

171 f'{arr.ndim - 1}-dimensional custom properties not', 

172 'supported by the input.data format.', 

173 ) 

174 

175 atom_layout.append((name, length)) 

176 

177 temp_atoms = cls( 

178 positions=atoms.positions.tolist(), 

179 symbols=list(atoms.symbols), 

180 input_units=input_units, 

181 atom_layout=atom_layout, 

182 ) 

183 

184 if any(atoms.pbc): 

185 temp_atoms.cell = atoms.cell 

186 

187 for name, arr in atoms.arrays.items(): 

188 if name not in SKIPPED_ARRAYS and issubclass(arr.dtype.type, Real): 

189 name = PROP_NAME_DICT.get(name, name) 

190 temp_atoms.atom_arrays[name] = arr.tolist() 

191 

192 temp_atoms._validate_atom_arrays() 

193 

194 if atoms.calc is not None: 

195 if 'energy' in atoms.calc.results: 

196 temp_atoms.energy = atoms.calc.results['energy'] 

197 if 'forces' in atoms.calc.results: 

198 temp_atoms.forces = atoms.calc.results['forces'].tolist() 

199 

200 if 'total_charge' in atoms.info: 

201 temp_atoms.total_charge = atoms.info['total_charge'] 

202 

203 return temp_atoms 

204 

205 def convert(self, output_units: Units) -> None: 

206 """Convert values in-place from `self.input_units` to `output_units`.""" 

207 if self.input_units is output_units: 

208 return 

209 

210 if self.input_units is Units.ATOMIC and output_units is Units.ASE: 

211 length_factor = Bohr 

212 energy_factor = Hartree 

213 force_factor = Hartree / Bohr 

214 elif self.input_units is Units.ASE and output_units is Units.ATOMIC: 

215 length_factor = 1.0 / Bohr 

216 energy_factor = 1.0 / Hartree 

217 force_factor = Bohr / Hartree 

218 else: 

219 raise ValueError( 

220 f'Unsupported conversion: {self.input_units} -> {output_units}' 

221 ) 

222 

223 if self.positions is not None: 

224 self.positions = [ 

225 [i * length_factor for i in xyz] for xyz in self.positions 

226 ] 

227 

228 if self.cell is not None: 

229 self.cell = [[i * length_factor for i in xyz] for xyz in self.cell] 

230 

231 if self.energy is not None: 

232 self.energy *= energy_factor 

233 

234 if self.forces is not None: 

235 self.forces = [ 

236 [i * force_factor for i in xyz] for xyz in self.forces 

237 ] 

238 

239 self.input_units = output_units 

240 

241 def add_atom(self, values: list[str]): 

242 """Add information from a single atom line to storage.""" 

243 offset = ATOM_LAYOUT_OFFSET # start in the field after the element. 

244 

245 # Input validation. 

246 if values[3] not in CHEMICAL_SYMBOLS_SET: 

247 raise ValueError(f"Unknown element '{values[3]}'.") 

248 

249 if len(values) != self.num_atom_columns: 

250 raise ValueError( 

251 f'Wrong format of atom line. Expected {self.num_atom_columns} ' 

252 f'columns after the atom statement but got {len(values)}.' 

253 ) 

254 

255 self.positions.append([float(v) for v in values[0:3]]) 

256 self.symbols.append(values[3]) 

257 

258 for name, length in self.atom_layout: 

259 if length == 1: 

260 prop_vals: float | list[float] = float(values[offset]) 

261 else: 

262 prop_vals = [float(v) for v in values[offset : offset + length]] 

263 

264 match name: 

265 case 'force': 

266 # Forces are treated separately since they are stored on the 

267 # calculator and not in the ase.Atoms.arrays dictionary. 

268 if self.forces is None: 

269 self.forces = [] 

270 self.forces.append( 

271 [float(v) for v in values[offset : offset + length]] 

272 ) 

273 case _: 

274 self.atom_arrays[name].append(prop_vals) 

275 

276 offset += length 

277 

278 def add_lattice_vector(self, values: list[str]): 

279 """Add a single lattice vector to storage.""" 

280 if len(values) != 3: 

281 raise ValueError( 

282 'Lattice vectors must be exactly 3 components long.' 

283 ) 

284 

285 if len(self.cell) == 3: 

286 raise ValueError('Cannot store more than three lattice vectors.') 

287 

288 self.cell.append([float(v) for v in values]) 

289 

290 def parse_line(self, line: str) -> None: 

291 """Parse a single line from input.data.""" 

292 line = line.strip() 

293 if not line or line.startswith('#'): 

294 return 

295 

296 fields = line.split() 

297 keyword, values = fields[0], fields[1:] 

298 

299 match keyword: 

300 case 'atom': 

301 self.add_atom(values) 

302 

303 case 'lattice': 

304 self.add_lattice_vector(values) 

305 

306 case 'energy': 

307 self.energy = float(values[0]) 

308 

309 case 'charge': 

310 self.total_charge = float(values[0])