Coverage for ase/io/eon.py: 89.81%
108 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# Copyright (C) 2012-2023, Jesper Friis, SINTEF
2# Copyright (C) 2024, Rohit Goswami, UI
3# (see accompanying license files for ASE).
4"""Module to read and write atoms EON reactant.con files.
6See http://theory.cm.utexas.edu/eon/index.html for a description of EON.
7"""
9from dataclasses import dataclass
10from warnings import warn
12import numpy as np
14from ase.atoms import Atoms
15from ase.constraints import FixAtoms
16from ase.geometry import cell_to_cellpar, cellpar_to_cell
17from ase.utils import reader, writer
19ISOTOPE_TOL = 1e-8
22@dataclass
23class EONHeader:
24 """
25 A data class for storing header information of an EON file.
27 Attributes
28 ----------
29 header_lines : List[str]
30 The first two comment lines from the EON file header.
31 cell_lengths : Tuple[float, float, float]
32 The lengths of the cell vectors.
33 cell_angles : Tuple[float, float, float]
34 The angles between the cell vectors.
35 Ncomponent : int
36 The number of distinct atom types.
37 component_counts : List[int]
38 A list containing the count of atoms for each type.
39 masses : List[float]
40 A list containing the atomic masses for each type.
41 """
43 header_lines: list[str]
44 # Actually these are float float float but.. mypy complains
45 cell_lengths: tuple[float, ...]
46 cell_angles: tuple[float, ...]
47 Ncomponent: int
48 component_counts: list[int]
49 masses: list[float]
52def process_header(lines: list[str]) -> EONHeader:
53 """
54 Processes the header lines from an EON file and returns an EONHeader object.
56 This function parses the first 9 lines of an EON file, extracting
57 information about the simulation cell, the number of atom types, their
58 counts, and masses, and encapsulates this information in an EONHeader
59 object.
61 Parameters
62 ----------
63 lines : List[str]
64 The first 9 lines of an EON file containing header information.
66 Returns
67 -------
68 EONHeader
69 An object containing the parsed header information.
70 """
71 header_lines = lines[:2]
73 # Parse cell lengths and angles
74 cell_lengths = tuple(map(float, lines[2].split()))
75 cell_angles = tuple(map(float, lines[3].split()))
76 if len(cell_lengths) != 3 or len(cell_angles) != 3:
77 raise ValueError(
78 'Cell lengths and angles must each contain exactly three values.'
79 )
81 Ncomponent = int(lines[6])
82 component_counts = list(map(int, lines[7].split()))
83 masses = list(map(float, lines[8].split()))
85 return EONHeader(
86 header_lines=header_lines,
87 cell_lengths=cell_lengths,
88 cell_angles=cell_angles,
89 Ncomponent=Ncomponent,
90 component_counts=component_counts,
91 masses=masses,
92 )
95def make_atoms(coordblock, header):
96 """
97 Creates an Atoms object from coordinate blocks and header information.
99 This function takes a list of coordinate blocks and the associated header
100 information, constructs the cell, sets the atomic positions, masses, and
101 optionally applies FixAtoms constraints based on the header information, and
102 returns an ASE Atoms object.
104 Parameters
105 ----------
106 coordblock : list of str
107 The lines from an EON file representing atom coordinates and types.
108 header : EONHeader
109 The parsed header information.
111 Returns
112 -------
113 Atoms
114 An ASE Atoms object constructed from the given coordinate blocks and
115 header.
116 """
117 symbols = []
118 coords = []
119 masses = []
120 fixed = []
121 # Ordering follows the EON convention
122 # (alpha, beta, gamma)
123 cell_angles = (
124 header.cell_angles[0],
125 header.cell_angles[1],
126 header.cell_angles[2],
127 )
128 cellpar = [x for x in header.cell_lengths + cell_angles]
129 for idx, nblock in enumerate(header.component_counts):
130 elem_block = coordblock[: (nblock + 2)]
131 symb = elem_block[0]
132 symbols.extend(nblock * [symb])
133 mass = header.masses[idx]
134 masses.extend(nblock * [mass])
135 for eline in elem_block[2:]:
136 tokens = eline.split()
137 coords.append([float(x) for x in tokens[:3]])
138 fixed.append(bool(int(tokens[3])))
139 coordblock = coordblock[(nblock + 2) :]
140 return Atoms(
141 symbols=symbols,
142 positions=coords,
143 masses=masses,
144 cell=cellpar_to_cell(cellpar),
145 constraint=FixAtoms(mask=fixed),
146 )
149@reader
150def read_eon(fileobj, index=-1):
151 """
152 Reads an EON file or directory and returns one or more Atoms objects.
154 This function handles single EON files, in both single image and multi-image
155 variants. It returns either a single Atoms object, a list of Atoms objects,
156 or a specific Atoms object indexed from the file or directory.
158 Parameters
159 ----------
160 fileobj : str or Path or file-like object
161 The path to the EON file or directory, or an open file-like object.
162 index : int, optional
163 The index of the Atoms object to return. If -1 (default), returns all
164 objects or a single object if only one is present.
166 Returns
167 -------
168 Atoms or List[Atoms]
169 Depending on the `index` parameter and the content of the fileobj,
170 returns either a single Atoms object or a list of Atoms objects.
171 """
172 images = []
173 while True:
174 # Read and process headers if they exist
175 try:
176 lines = [next(fileobj).strip() for _ in range(9)]
177 except StopIteration:
178 break # End of file
179 header = process_header(lines)
180 num_blocklines = (header.Ncomponent * 2) + sum(header.component_counts)
181 coordblocks = [next(fileobj).strip() for _ in range(num_blocklines)]
182 atoms = make_atoms(coordblocks, header)
183 images.append(atoms)
185 # XXX: I really don't like this since there should be a consistent return
186 if index == -1:
187 return images if len(images) > 1 else images[0]
188 else:
189 return images[index]
192@writer
193def write_eon(fileobj, images, comment='Generated by ASE'):
194 """
195 Writes structures to an EON trajectory file, allowing for multiple
196 snapshots.
198 This function iterates over all provided images, converting each one into a
199 text format compatible with EON trajectory files. It handles the conversion
200 of the cell parameters, chemical symbols, atomic masses, and atomic
201 constraints. Only FixAtoms constraints are supported; any other constraints
202 will generate a warning and be skipped. Arbitrary masses will raise an
203 error, since EON will not accept them, i.e. no Duterium and Hydrogen.
205 Parameters
206 ----------
207 fileobj : file object
208 An opened, writable file or file-like object to which the EON trajectory
209 information will be written.
210 images : list of Atoms
211 A list of ASE Atoms objects representing the images (atomic structures)
212 to be written into the EON trajectory file. Each Atoms object should
213 have a cell attribute and may have a constraints attribute. If the
214 constraints attribute is not a FixAtoms object, a warning will be
215 issued.
216 comment : str
217 An additional comment statement which will be written out as the first
218 header
220 Raises
221 ------
222 Warning
223 If any constraint in an Atoms object is not an instance of FixAtoms.
224 RuntimeError
225 If the masses for the species are not the default ones, i.e. if isotopes
226 are present
228 Returns
229 -------
230 None
231 The function writes directly to the provided file object.
233 See Also
234 --------
235 ase.io.utils.segment_list : for segmenting the list of images.
237 Examples
238 --------
239 >>> from ase.io import Trajectory
240 >>> from ase.io.utils import segment_list
241 >>> traj = Trajectory("neb.traj")
242 >>> n_images = 10 # Segment size, i.e. number of images in the NEB
243 >>> for idx, pth in enumerate(segment_list(traj, n_images)):
244 ... with open(f"outputs/neb_path_{idx:03d}.con", "w") as fobj:
245 ... write_eon_traj(fobj, pth)
246 """
248 for idx, atoms in enumerate(images):
249 out = []
250 if idx == 0:
251 out.append(comment)
252 else:
253 out.append(f'\n{comment}')
254 out.append('preBox_header_2') # ??
256 a, b, c, alpha, beta, gamma = cell_to_cellpar(atoms.cell)
257 out.append('%-10.6f %-10.6f %-10.6f' % (a, b, c))
258 out.append('%-10.6f %-10.6f %-10.6f' % (alpha, beta, gamma))
260 out.append('postBox_header_1') # ??
261 out.append('postBox_header_2') # ??
263 symbol_indices = atoms.symbols.indices()
264 natoms = [len(x) for x in symbol_indices.values()]
265 masslist = atoms.get_masses()
266 species_masses = []
267 for symbol, indices in symbol_indices.items():
268 masses_for_symb = masslist[indices]
269 if np.ptp(masses_for_symb) > ISOTOPE_TOL:
270 raise RuntimeError(
271 'Isotopes cannot be handled by EON'
272 ', ensure uniform masses for symbols'
273 )
274 species_masses.append(masses_for_symb[0])
276 out.append(str(len(symbol_indices)))
277 out.append(' '.join([str(n) for n in natoms]))
278 out.append(' '.join([str(n) for n in species_masses]))
280 atom_id = 0
281 for cid, (species, indices) in enumerate(symbol_indices.items()):
282 fixed = np.array([False] * len(atoms))
283 out.append(species)
284 out.append('Coordinates of Component %d' % (cid + 1))
285 atom = atoms[indices]
286 coords = atom.positions
287 for constraint in atom.constraints:
288 if not isinstance(constraint, FixAtoms):
289 warn(
290 'Only FixAtoms constraints are supported'
291 'by con files. Dropping %r',
292 constraint,
293 )
294 continue
295 if constraint.index.dtype.kind == 'b':
296 fixed = np.array(constraint.index, dtype=int)
297 else:
298 fixed = np.zeros((natoms[cid],), dtype=int)
299 for i in constraint.index:
300 fixed[i] = 1
301 for xyz, fix in zip(coords, fixed):
302 line_fmt = '{:>22.17f} {:>22.17f} {:>22.17f} {:d} {:4d}'
303 line = line_fmt.format(*xyz, int(fix), atom_id)
304 out.append(line)
305 atom_id += 1
306 fileobj.write('\n'.join(out))