Coverage for ase/io/cp2k.py: 89.68%
155 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"""
2Reader for CP2Ks DCD_ALIGNED_CELL format and restart files.
4Based on [pwtools](https://github.com/elcorto/pwtools).
5All information about the dcd format is taken from there.
6The way of reading it is also copied from pwtools.
7Thanks to Steve for agreeing to this.
9Some information also comes directly from the CP2K source,
10so if they decide to change anything this here might break.
12Some parts are adapted from the extxyz reader.
14Contributed by Patrick Melix <chemistry@melix.me>
15"""
17import os
18from itertools import islice
20import numpy as np
22from ase.atoms import Atom, Atoms
23from ase.cell import Cell
24from ase.data import atomic_numbers
25from ase.io.formats import index2range
27__all__ = ['read_cp2k_dcd', 'iread_cp2k_dcd', 'read_cp2k_restart']
29# DCD file header
30# (name, dtype, shape)
31# numpy dtypes:
32# i4 = int32
33# f4 = float32 (single precision)
34# f8 = float64 (double precision)
35# S80 = string of length 80 (80 chars)
36_HEADER_TYPES = [
37 ('blk0-0', 'i4'), # 84 (start of first block, size=84 bytes)
38 ('hdr', 'S4'), # 'CORD'
39 ('9int', ('i4', 9)), # 9 ints, mostly 0
40 ('timestep', 'f4'), # timestep (float32)
41 ('10int', ('i4', 10)), # 10 ints, mostly 0, last is 24
42 ('blk0-1', 'i4'), # 84
43 ('blk1-0', 'i4'), # 164
44 ('ntitle', 'i4'), # 2
45 ('remark1', 'S80'), # remark1
46 ('remark2', 'S80'), # remark2
47 ('blk1-1', 'i4'), # 164
48 ('blk2-0', 'i4'), # 4 (4 bytes = int32)
49 ('natoms', 'i4'), # natoms (int32)
50 ('blk2-1', 'i4'), # 4
51]
53_HEADER_DTYPE = np.dtype(_HEADER_TYPES)
56def _bytes_per_timestep(natoms):
57 return 4 + 6 * 8 + 7 * 4 + 3 * 4 * natoms
60def _read_metainfo(fileobj):
61 if not hasattr(fileobj, 'seek'):
62 raise TypeError(
63 'You should have passed a fileobject opened in binary '
64 'mode, it seems you did not.'
65 )
66 fileobj.seek(0)
67 header = np.fromfile(fileobj, _HEADER_DTYPE, 1)[0]
68 natoms = header['natoms']
69 remark1 = str(header['remark1']) # taken from CP2Ks source/motion_utils.F
70 if 'CP2K' not in remark1:
71 raise ValueError(
72 'Header should contain mention of CP2K, are you sure '
73 'this file was created by CP2K?'
74 )
76 # dtype for fromfile: nStep times dtype of a timestep data block
77 dtype = np.dtype(
78 [
79 ('x0', 'i4'),
80 ('x1', 'f8', (6,)),
81 ('x2', 'i4', (2,)),
82 ('x3', 'f4', (natoms,)),
83 ('x4', 'i4', (2,)),
84 ('x5', 'f4', (natoms,)),
85 ('x6', 'i4', (2,)),
86 ('x7', 'f4', (natoms,)),
87 ('x8', 'i4'),
88 ]
89 )
91 fd_pos = fileobj.tell()
92 header_end = fd_pos
93 # seek to end
94 fileobj.seek(0, os.SEEK_END)
95 # number of bytes between fd_pos and end
96 fd_rest = fileobj.tell() - fd_pos
97 # reset to pos after header
98 fileobj.seek(fd_pos)
99 # calculate nstep: fd_rest / bytes_per_timestep
100 # 4 - initial 48
101 # 6*8 - cryst_const_dcd
102 # 7*4 - markers between x,y,z and at the end of the block
103 # 3*4*natoms - float32 cartesian coords
104 nsteps = fd_rest / _bytes_per_timestep(natoms)
105 if fd_rest % _bytes_per_timestep(natoms) != 0:
106 raise ValueError(
107 'Calculated number of steps is not int, cannot read file'
108 )
109 nsteps = int(nsteps)
110 return dtype, natoms, nsteps, header_end
113class DCDChunk:
114 def __init__(self, chunk, dtype, natoms, symbols, aligned):
115 self.chunk = chunk
116 self.dtype = dtype
117 self.natoms = natoms
118 self.symbols = symbols
119 self.aligned = aligned
121 def build(self):
122 """Convert unprocessed chunk into Atoms."""
123 return _read_cp2k_dcd_frame(
124 self.chunk, self.dtype, self.natoms, self.symbols, self.aligned
125 )
128def idcdchunks(fd, ref_atoms, aligned):
129 """Yield unprocessed chunks for each image."""
130 if ref_atoms:
131 symbols = ref_atoms.get_chemical_symbols()
132 else:
133 symbols = None
134 dtype, natoms, nsteps, header_end = _read_metainfo(fd)
135 bytes_per_step = _bytes_per_timestep(natoms)
136 fd.seek(header_end)
137 for i in range(nsteps):
138 fd.seek(bytes_per_step * i + header_end)
139 yield DCDChunk(fd, dtype, natoms, symbols, aligned)
142class DCDImageIterator:
143 """"""
145 def __init__(self, ichunks):
146 self.ichunks = ichunks
148 def __call__(self, fd, indices=-1, ref_atoms=None, aligned=False):
149 self.ref_atoms = ref_atoms
150 self.aligned = aligned
151 if not hasattr(indices, 'start'):
152 if indices < 0:
153 indices = slice(indices - 1, indices)
154 else:
155 indices = slice(indices, indices + 1)
157 for chunk in self._getslice(fd, indices):
158 yield chunk.build()
160 def _getslice(self, fd, indices):
161 try:
162 iterator = islice(
163 self.ichunks(fd, self.ref_atoms, self.aligned),
164 indices.start,
165 indices.stop,
166 indices.step,
167 )
168 except ValueError:
169 # Negative indices. Adjust slice to positive numbers.
170 _dtype, _natoms, nsteps, _header_end = _read_metainfo(fd)
171 indices_tuple = indices.indices(nsteps + 1)
172 iterator = islice(
173 self.ichunks(fd, self.ref_atoms, self.aligned), *indices_tuple
174 )
175 return iterator
178iread_cp2k_dcd = DCDImageIterator(idcdchunks)
181def read_cp2k_dcd(fileobj, index=-1, ref_atoms=None, aligned=False):
182 """Read a DCD file created by CP2K.
184 To yield one Atoms object at a time use ``iread_cp2k_dcd``.
186 Note: Other programs use other formats, they are probably not compatible.
188 If ref_atoms is not given, all atoms will have symbol 'X'.
190 To make sure that this is a dcd file generated with the *DCD_ALIGNED_CELL* key
191 in the CP2K input, you need to set ``aligned`` to *True* to get cell information.
192 Make sure you do not set it otherwise, the cell will not match the atomic coordinates!
193 See the following url for details:
194 https://groups.google.com/forum/#!searchin/cp2k/Outputting$20cell$20information$20and$20fractional$20coordinates%7Csort:relevance/cp2k/72MhYykrSrQ/5c9Jaw7S9yQJ.
195 """ # noqa: E501
196 dtype, natoms, nsteps, header_end = _read_metainfo(fileobj)
197 bytes_per_timestep = _bytes_per_timestep(natoms)
198 if ref_atoms:
199 symbols = ref_atoms.get_chemical_symbols()
200 else:
201 symbols = ['X' for _ in range(natoms)]
202 if natoms != len(symbols):
203 raise ValueError(
204 'Length of ref_atoms does not match natoms from dcd file'
205 )
206 trbl = index2range(index, nsteps)
208 for index in trbl:
209 frame_pos = int(header_end + index * bytes_per_timestep)
210 fileobj.seek(frame_pos)
211 yield _read_cp2k_dcd_frame(
212 fileobj, dtype, natoms, symbols, aligned=aligned
213 )
216def _read_cp2k_dcd_frame(fileobj, dtype, natoms, symbols, aligned=False):
217 arr = np.fromfile(fileobj, dtype, 1)
218 cryst_const = np.empty(6, dtype=np.float64)
219 cryst_const[0] = arr['x1'][0, 0]
220 cryst_const[1] = arr['x1'][0, 2]
221 cryst_const[2] = arr['x1'][0, 5]
222 cryst_const[3] = arr['x1'][0, 4]
223 cryst_const[4] = arr['x1'][0, 3]
224 cryst_const[5] = arr['x1'][0, 1]
225 coords = np.empty((natoms, 3), dtype=np.float32)
226 coords[..., 0] = arr['x3'][0, ...]
227 coords[..., 1] = arr['x5'][0, ...]
228 coords[..., 2] = arr['x7'][0, ...]
229 assert len(coords) == len(symbols)
230 if aligned:
231 # convention of the cell is (see cp2ks src/particle_methods.F):
232 # A is in x
233 # B lies in xy plane
234 # luckily this is also the ASE convention for Atoms.set_cell()
235 atoms = Atoms(symbols, coords, cell=cryst_const, pbc=True)
236 else:
237 atoms = Atoms(symbols, coords)
238 return atoms
241def read_cp2k_restart(fileobj):
242 """Read Atoms and Cell from Restart File.
244 Reads the elements, coordinates and cell information from the
245 '&SUBSYS' section of a CP2K restart file.
247 Tries to convert atom names to elements, if this fails element is set to X.
249 Returns an Atoms object.
250 """
252 def _parse_section(inp):
253 """Helper to parse structure to nested dict"""
254 ret = {'content': []}
255 while inp:
256 line = inp.readline().strip()
257 if line.startswith('&END'):
258 return ret
259 elif line.startswith('&'):
260 key = line.replace('&', '')
261 ret[key] = _parse_section(inp)
262 else:
263 ret['content'].append(line)
264 return ret
266 def _fast_forward_to(fileobj, section_header):
267 """Helper to forward to a section"""
268 found = False
269 while fileobj:
270 line = fileobj.readline()
271 if section_header in line:
272 found = True
273 break
274 if not found:
275 raise RuntimeError(f'No {section_header} section found!')
277 def _read_cell(data):
278 """Helper to read cell data, returns cell and pbc"""
279 cell = None
280 pbc = [False, False, False]
281 if 'CELL' in data:
282 content = data['CELL']['content']
283 cell = Cell([[0, 0, 0] for i in range(3)])
284 char2idx = {'A ': 0, 'B ': 1, 'C ': 2}
285 for line in content:
286 # lines starting with A/B/C<whitespace> have cell
287 if line[:2] in char2idx:
288 idx = char2idx[line[:2]]
289 cell[idx] = [float(x) for x in line.split()[1:]]
290 pbc[idx] = True
291 if {len(v) for v in cell} != {3}:
292 raise RuntimeError('Bad Cell Definition found.')
293 return cell, pbc
295 def _read_geometry(content):
296 """Helper to read geometry, returns a list of Atoms"""
297 atom_list = []
298 for entry in content:
299 entry = entry.split()
300 # Get letters for element symbol
301 el = [char.lower() for char in entry[0] if char.isalpha()]
302 el = ''.join(el).capitalize()
303 # Get positions
304 pos = [float(x) for x in entry[1:4]]
305 if el in atomic_numbers.keys():
306 atom_list.append(Atom(el, pos))
307 else:
308 atom_list.append(Atom('X', pos))
309 return atom_list
311 # fast forward to &SUBSYS section
312 _fast_forward_to(fileobj, '&SUBSYS')
313 # parse sections into dictionary
314 data = _parse_section(fileobj)
315 # look for &CELL
316 cell, pbc = _read_cell(data)
317 # get the atoms
318 atom_list = _read_geometry(data['COORD']['content'])
319 return Atoms(atom_list, cell=cell, pbc=pbc)