Coverage for ase/io/dlp4.py: 89.19%
148 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"""Read/Write DL_POLY_4 CONFIG files"""
3import itertools
4import re
5from collections.abc import Generator, Iterable
6from typing import IO
8import numpy as np
10from ase.atoms import Atoms
11from ase.calculators.singlepoint import SinglePointCalculator
12from ase.data import chemical_symbols
13from ase.units import _amu, _auf, _auv
14from ase.utils import reader, writer
16__all__ = ['read_dlp4', 'write_dlp4']
18# dlp4 labels will be registered in atoms.arrays[DLP4_LABELS_KEY]
19DLP4_LABELS_KEY = 'dlp4_labels'
20DLP4_DISP_KEY = 'dlp4_displacements'
21DLP_F_SI = 1.0e-10 * _amu / (1.0e-12 * 1.0e-12) # Å*Da/ps^2
22DLP_F_ASE = DLP_F_SI / _auf
23DLP_V_SI = 1.0e-10 / 1.0e-12 # Å/ps
24DLP_V_ASE = DLP_V_SI / _auv
27def _get_frame_positions(fd: IO) -> tuple[int, int, int, list[int]]:
28 """Get positions of frames in HISTORY file."""
29 init_pos = fd.tell()
31 fd.seek(0)
33 record_len = len(fd.readline()) # system name, and record size
35 items = fd.readline().strip().split()
37 if len(items) not in (3, 5):
38 raise RuntimeError('Cannot determine version of HISTORY file format.')
40 levcfg, imcon, natoms = map(int, items[0:3])
42 if len(items) == 3: # DLPoly classic
43 # we have to iterate over the entire file
44 pos = [fd.tell() for line in fd if 'timestep' in line]
45 else:
46 nframes = int(items[3])
47 pos = [
48 ((natoms * (levcfg + 2) + 4) * i + 3) * record_len
49 for i in range(nframes)
50 ]
52 fd.seek(init_pos)
53 return levcfg, imcon, natoms, pos
56@reader
57def read_dlp_history(
58 fd: IO, index: int | slice | None = None, symbols: list[str] | None = None
59) -> list[Atoms]:
60 """Read a HISTORY file.
62 Compatible with DLP4 and DLP_CLASSIC.
64 *Index* can be integer or a slice.
66 Provide a list of element strings to symbols to ignore naming
67 from the HISTORY file.
68 """
69 return list(iread_dlp_history(fd, index, symbols))
72@reader
73def iread_dlp_history(
74 fd: IO, index: int | slice | None = None, symbols: list[str] | None = None
75) -> Generator[Atoms, None, None]:
76 """Generator version of read_dlp_history
78 Compatible with DLP4 and DLP_CLASSIC.
80 *Index* can be integer or a slice.
82 Provide a list of element strings to symbols to ignore naming
83 from the HISTORY file.
84 """
85 levcfg, imcon, natoms, pos = _get_frame_positions(fd)
87 positions: Iterable[int] = ()
88 if index is None:
89 positions = pos
90 elif isinstance(index, int):
91 positions = (pos[index],)
92 elif isinstance(index, slice):
93 positions = itertools.islice(pos, index.start, index.stop, index.step)
95 for pos_i in positions:
96 fd.seek(pos_i + 1)
97 yield read_single_image(
98 fd, levcfg, imcon, natoms, is_trajectory=True, symbols=symbols
99 )
102@reader
103def read_dlp4(fd: IO, symbols: list[str] | None = None) -> Atoms:
104 """Read a DL_POLY_4 config/revcon file.
106 Typically used indirectly through read("filename", atoms, format="dlp4").
108 Can be unforgiving with custom chemical element names.
109 Please complain to alin@elena.space for bugs."""
111 fd.readline()
112 levcfg, imcon = map(int, fd.readline().split()[0:2])
114 position = fd.tell()
115 is_trajectory = fd.readline().split()[0] == 'timestep'
117 if not is_trajectory:
118 # Difficult to distinguish between trajectory and non-trajectory
119 # formats without reading one line too many.
120 fd.seek(position)
122 natoms = int(fd.readline().split()[2]) if is_trajectory else None
123 return read_single_image(fd, levcfg, imcon, natoms, is_trajectory, symbols)
126def read_single_image(
127 fd: IO,
128 levcfg: int,
129 imcon: int,
130 natoms: int | None,
131 is_trajectory: bool,
132 symbols: list[str] | None = None,
133) -> Atoms:
134 """Read a DLP frame"""
135 sym = symbols if symbols else []
136 positions = []
137 velocities = []
138 forces = []
139 charges = []
140 masses = []
141 disps: list[float | None] = []
142 labels = []
144 is_pbc = imcon > 0
146 cell = np.zeros((3, 3), dtype=np.float64)
147 if is_pbc or is_trajectory:
148 for j, line in enumerate(itertools.islice(fd, 3)):
149 cell[j, :] = np.array(line.split(), dtype=np.float64)
151 i = 0
152 for i, line in enumerate(itertools.islice(fd, natoms), 1):
153 match = re.match(r'\s*([A-Za-z][a-z]?)(\S*)', line)
154 if not match:
155 raise OSError(f'Line {line} does not match valid format.')
157 symbol, label = match.group(1, 2)
158 symbol = symbol.capitalize()
160 if is_trajectory:
161 mass, charge, *disp = map(float, line.split()[2:])
162 charges.append(charge)
163 masses.append(mass)
164 disps.extend(disp if disp else [None]) # type: ignore[list-item]
166 if not symbols:
167 if symbol not in chemical_symbols:
168 raise ValueError(
169 f"Symbol '{symbol}' not found in chemical symbols table"
170 )
171 sym.append(symbol)
173 # make sure label is not empty
174 labels.append(label if label else '')
176 positions.append([float(x) for x in next(fd).split()[:3]])
177 if levcfg > 0:
178 velocities.append(
179 [float(x) * DLP_V_ASE for x in next(fd).split()[:3]]
180 )
181 if levcfg > 1:
182 forces.append([float(x) * DLP_F_ASE for x in next(fd).split()[:3]])
184 if symbols and (i != len(symbols)):
185 raise ValueError(
186 f'Counter is at {i} but {len(symbols)} symbols provided.'
187 )
189 if imcon == 0:
190 pbc = (False, False, False)
191 elif imcon in (1, 2, 3):
192 pbc = (True, True, True)
193 elif imcon == 6:
194 pbc = (True, True, False)
195 elif imcon in (4, 5):
196 raise ValueError(f'Unsupported imcon: {imcon}')
197 else:
198 raise ValueError(f'Invalid imcon: {imcon}')
200 atoms = Atoms(
201 positions=positions,
202 symbols=sym,
203 cell=cell,
204 pbc=pbc,
205 # Cell is centered around (0, 0, 0) in dlp4:
206 celldisp=-cell.sum(axis=0) / 2,
207 )
209 if is_trajectory:
210 atoms.set_masses(masses)
211 atoms.set_array(DLP4_DISP_KEY, disps, float)
212 atoms.set_initial_charges(charges)
214 atoms.set_array(DLP4_LABELS_KEY, labels, str)
215 if levcfg > 0:
216 atoms.set_velocities(velocities)
217 if levcfg > 1:
218 atoms.calc = SinglePointCalculator(atoms, forces=forces)
220 return atoms
223@writer
224def write_dlp4(
225 fd: IO,
226 atoms: Atoms,
227 levcfg: int = 0,
228 title: str = 'CONFIG generated by ASE',
229):
230 """Write a DL_POLY_4 config file.
232 Typically used indirectly through write("filename", atoms, format="dlp4").
234 Can be unforgiven with custom chemical element names.
235 Please complain to alin@elena.space in case of bugs"""
237 def float_format(flt):
238 return format(flt, '20.10f')
240 natoms = len(atoms)
242 if tuple(atoms.pbc) == (False, False, False):
243 imcon = 0
244 elif tuple(atoms.pbc) == (True, True, True):
245 imcon = 3
246 elif tuple(atoms.pbc) == (True, True, False):
247 imcon = 6
248 else:
249 raise ValueError(
250 f'Unsupported pbc: {atoms.pbc}. '
251 'Supported pbc are 000, 110, and 111.'
252 )
254 print(f'{title:72s}', file=fd)
255 print(f'{levcfg:10d}{imcon:10d} {natoms}', file=fd)
257 if imcon > 0:
258 for row in atoms.get_cell():
259 print(''.join(map(float_format, row)), file=fd)
261 vels = atoms.get_velocities() / DLP_V_ASE if levcfg > 0 else None
262 forces = atoms.get_forces() / DLP_F_ASE if levcfg > 1 else None
264 labels = atoms.arrays.get(DLP4_LABELS_KEY)
266 for i, atom in enumerate(atoms):
267 sym = atom.symbol
268 if labels is not None:
269 sym += labels[i]
271 print(f'{sym:8s}{atom.index + 1:10d}', file=fd)
273 to_write = (atom.x, atom.y, atom.z)
274 print(''.join(map(float_format, to_write)), file=fd)
276 if levcfg > 0:
277 to_write = (
278 vels[atom.index, :] if vels is not None else (0.0, 0.0, 0.0)
279 )
280 print(''.join(map(float_format, to_write)), file=fd)
282 if levcfg > 1:
283 to_write = (
284 forces[atom.index, :] if forces is not None else (0.0, 0.0, 0.0)
285 )
286 print(''.join(map(float_format, to_write)), file=fd)