Coverage for local_installation/dynasor/trajectory/trajectory.py: 95%
153 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-11-30 21:04 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-11-30 21:04 +0000
1__all__ = ['Trajectory', 'WindowIterator']
3import numpy as np
5from collections import deque
6from itertools import islice, chain
7from os.path import isfile
8from typing import Callable, Dict, Union, List
10from dynasor.trajectory.atomic_indices import parse_gromacs_index_file
11from dynasor.trajectory.ase_trajectory_reader import ASETrajectoryReader
12from dynasor.trajectory.extxyz_trajectory_reader import ExtxyzTrajectoryReader
13from dynasor.trajectory.lammps_trajectory_reader import LammpsTrajectoryReader
14from dynasor.trajectory.mdanalysis_trajectory_reader import MDAnalysisTrajectoryReader
15from dynasor.trajectory.trajectory_frame import TrajectoryFrame
16from dynasor.logging_tools import logger
19class Trajectory:
20 """Instances of this class hold trajectories in a format suitable for
21 the computation of correlation functions. They behave as
22 iterators, where each step returns the next frame as a
23 :class:`TrajectoryFrame` object. The latter hold information
24 regarding atomic positions, types, and velocities.
26 Parameters
27 ----------
28 filename
29 Name of input file
30 trajectory_format
31 Type of trajectory. Possible values are:
32 ``'lammps_internal'``, ``'extxyz'`` or one of the formats supported by
33 `MDAnalysis <https://www.mdanalysis.org/>`_ (except for ``'lammpsdump'``,
34 which can be called by specifying ``'lammps_mdanalysis'`` to avoid ambiguity)
35 atomic_indices
36 Specify which indices belong to which atom type. Can be
37 (1) a dictionary where the keys specicy species and the values are list of atomic indices,
38 (2) ``'read_from_trajectory'``, in which case the species are read from the trajectory or
39 (3) the path to an index file.
40 length_unit
41 Length unit of trajectory. Necessary for correct conversion to internal dynasor units if
42 the trajectory file does not contain unit information. For available options see
43 `MDAnalysis <https://docs.mdanalysis.org/stable/documentation_pages/units.html>`__.
44 time_unit
45 Time unit of trajectory. Necessary for correct conversion to internal dynasor units if
46 the trajectory file does not contain unit information. For available options see
47 `MDAnalysis <https://docs.mdanalysis.org/stable/documentation_pages/units.html>`__.
48 frame_start
49 First frame to read; must be larger or equal ``0``.
50 frame_stop
51 Last frame to read. By default (``None``) the entire trajectory is read.
52 frame_step
53 Read every :attr:`frame_step`-th step of the input trajectory.
54 By default (``1``) every frame is read. Must be larger than ``0``.
56 """
57 def __init__(
58 self,
59 filename: str,
60 trajectory_format: str,
61 atomic_indices: Union[str, Dict[str, List[int]]] = None,
62 length_unit: str = None,
63 time_unit: str = None,
64 frame_start: int = 0,
65 frame_stop: int = None,
66 frame_step: int = 1
67 ):
69 if frame_start < 0:
70 raise ValueError('frame_start should be positive')
71 if frame_step < 0:
72 raise ValueError('frame_step should be positive')
74 self._frame_number = frame_start
75 self._frame_step = frame_step
76 self._frame_stop = frame_stop
78 # setup trajectory reader
79 if not isfile(filename):
80 raise IOError(f'File {filename} does not exist')
81 self._filename = filename
83 if trajectory_format == 'lammps_internal':
84 reader = LammpsTrajectoryReader
85 elif trajectory_format == 'extxyz':
86 reader = ExtxyzTrajectoryReader
87 elif trajectory_format == 'lammps_mdanalysis':
88 reader = MDAnalysisTrajectoryReader
89 trajectory_format = 'lammpsdump'
90 elif trajectory_format == 'ase': 90 ↛ 91line 90 didn't jump to line 91, because the condition on line 90 was never true
91 reader = ASETrajectoryReader
92 elif trajectory_format == 'lammps':
93 raise IOError('Ambiguous trajectory format, '
94 'did you mean lammps_internal or lammps_mdanalysis?')
95 else:
96 reader = MDAnalysisTrajectoryReader
98 logger.debug(f'Using trajectory reader: {reader.__name__}')
99 if reader == MDAnalysisTrajectoryReader:
100 self._reader_obj = reader(self._filename, trajectory_format,
101 length_unit=length_unit, time_unit=time_unit)
102 else:
103 self._reader_obj = reader(self._filename, length_unit=length_unit, time_unit=time_unit)
105 # Get two frames to set cell etc.
106 frame0 = next(self._reader_obj)
107 frame1 = next(self._reader_obj)
108 self._cell = frame0.cell
109 self._n_atoms = frame0.n_atoms
111 # Make sure cell is not changed during consecutive frames
112 if not np.allclose(frame0.cell, frame1.cell):
113 raise ValueError('The cell changes between the first and second frame. '
114 'The concept of q-points becomes muddy if the simulation cell is '
115 'changing, such as during NPT MD simulations, so trajectories where '
116 'the cell changes are not supported by dynasor.')
118 # setup iterator slice (reuse frame0 and frame1 via chain)
119 self.number_of_frames_read = 0
120 self._reader_obj = islice(chain([frame0, frame1], self._reader_obj),
121 frame_start, self._frame_stop, self._frame_step)
123 # setup atomic indices
124 if atomic_indices is None: # Default behaviour
125 atomic_indices = {'X': np.arange(0, self.n_atoms)}
126 elif isinstance(atomic_indices, str): # Str input
127 if atomic_indices == 'read_from_trajectory':
128 if frame0.atom_types is None:
129 raise ValueError('Could not read atomic indices from the trajectory.')
130 else:
131 uniques = np.unique(frame0.atom_types)
132 atomic_indices = {uniques[i]: (frame0.atom_types == uniques[i]).nonzero()[0]
133 for i in range(len(uniques))}
134 else:
135 atomic_indices = parse_gromacs_index_file(atomic_indices)
136 elif isinstance(atomic_indices, dict): # Dict input
137 pass
138 else:
139 raise ValueError('Could not understand atomic_indices.')
140 self._atomic_indices = atomic_indices
142 # sanity checks for atomic_indices
143 for key, indices in self._atomic_indices.items():
144 if np.max(indices) > self.n_atoms:
145 raise ValueError('maximum index in atomic_indices exceeds number of atoms')
146 if np.min(indices) < 0:
147 raise ValueError('minimum index in atomic_indices is negative')
148 if '_' in key:
149 # Since '_' is what we use to distinguish atom types in the results, e.g. Sqw_Cs_Pb
150 raise ValueError('The char "_" is not allowed in atomic_indices.')
152 # log info on trajectory and atom types etc
153 logger.info(f'Trajectory file: {self.filename}')
154 logger.info(f'Total number of particles: {self.n_atoms}')
155 logger.info(f'Number of atom types: {len(self.atom_types)}')
156 for atom_type, indices in self._atomic_indices.items():
157 logger.info(f'Number of atoms of type {atom_type}: {len(indices)}')
158 logger.info(f'Simulation cell (in Angstrom):\n{str(self._cell)}')
160 def __iter__(self):
161 return self
163 def __next__(self):
164 frame = next(self._reader_obj)
165 new_frame = TrajectoryFrame(self.atomic_indices, frame.frame_index, frame.positions,
166 frame.velocities)
167 self.number_of_frames_read += 1
168 return new_frame
170 def __str__(self) -> str:
171 s = ['Trajectory']
172 s += ['{:12} : {}'.format('filename', self.filename)]
173 s += ['{:12} : {}'.format('natoms', self.n_atoms)]
174 s += ['{:12} : {}'.format('frame_step', self.frame_step)]
175 s += ['{:12} : [{}\n {}\n {}]'
176 .format('cell', self.cell[0], self.cell[1], self.cell[2])]
177 return '\n'.join(s)
179 def _repr_html_(self) -> str:
180 s = [f'<h3>{self.__class__.__name__}</h3>']
181 s += ['<table border="1" class="dataframe">']
182 s += ['<thead><tr><th style="text-align: left;">Field</th><th>Value</th></tr></thead>']
183 s += ['<tbody>']
184 s += [f'<tr"><td style="text-align: left;">File name</td><td>{self.filename}</td></tr>']
185 s += [f'<tr><td style="text-align: left;">Number of atoms</td><td>{self.n_atoms}</td></tr>']
186 s += [f'<tr><td style="text-align: left;">Cell metric</td><td>{self.cell}</td></tr>']
187 s += [f'<tr><td style="text-align: left;">Frame step</td><td>{self.frame_step}</td></tr>']
188 s += [f'<tr><td style="text-align: left;">Atom types</td><td>{self.atom_types}</td></tr>']
189 s += ['</tbody>']
190 s += ['</table>']
191 return '\n'.join(s)
193 @property
194 def cell(self):
195 """ Simulation cell """
196 return self._cell
198 @property
199 def n_atoms(self):
200 """ Number of atoms """
201 return self._n_atoms
203 @property
204 def filename(self):
205 """ The trajectory filename """
206 return self._filename
208 @property
209 def atomic_indices(self):
210 """ Return copy of index arrays """
211 atomic_indices = dict()
212 for name, inds in self._atomic_indices.items():
213 atomic_indices[name] = inds.copy()
214 return atomic_indices
216 @property
217 def atom_types(self) -> List[str]:
218 return sorted(self._atomic_indices.keys())
220 @property
221 def frame_step(self):
222 """ Frame to access, trajectory will return every :attr:`frame_step`-th snapshot """
223 return self._frame_step
226def consume(iterator, n):
227 """ Advance the iterator by :attr:`n` steps. If :attr:`n` is ``None``, consume entirely. """
228 # From the python.org
229 if n is None: 229 ↛ 230line 229 didn't jump to line 230, because the condition on line 229 was never true
230 deque(iterator, maxlen=0)
231 else:
232 next(islice(iterator, n, n), None)
235class WindowIterator:
236 """Sliding window iterator.
238 Returns consecutive windows (a window is represented as a list
239 of objects), created from an input iterator.
241 Parameters
242 ----------
243 itraj
244 Trajectory object
245 width
246 Length of window (``window_size`` + 1)
247 window_step
248 Distance between the start of two consecutive window frames
249 element_processor
250 Enables processing each non-discarded object; useful if ``window_step >
251 width`` and ``map_item`` is expensive (as compared to directly passing
252 ``map(fun, itraj)`` as ``itraj``); if ``window_step < width``, you could as
253 well directly pass ``map(fun, itraj)``.
254 """
255 def __init__(self,
256 itraj: Trajectory,
257 width: int,
258 window_step: int = 1,
259 element_processor: Callable = None):
261 self._raw_it = itraj
262 if element_processor:
263 self._it = map(element_processor, self._raw_it)
264 else:
265 self._it = self._raw_it
266 assert window_step >= 1
267 assert width >= 1
268 self.width = width
269 self.window_step = window_step
270 self._window = None
272 def __iter__(self):
273 return self
275 def __next__(self):
276 """ Returns next element in sequence. """
277 if self._window is None:
278 self._window = deque(islice(self._it, self.width), self.width)
279 else:
280 if self.window_step >= self.width:
281 self._window.clear()
282 consume(self._raw_it, self.window_step - self.width)
283 else:
284 for _ in range(min((self.window_step, len(self._window)))):
285 self._window.popleft()
286 for f in islice(self._it, min((self.window_step, self.width))):
287 self._window.append(f)
289 if len(self._window) == 0:
290 raise StopIteration
292 return list(self._window)