Coverage for ase/io/netcdftrajectory.py: 83.01%
359 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"""
2netcdftrajectory - I/O trajectory files in the AMBER NetCDF convention
4More information on the AMBER NetCDF conventions can be found at
5http://ambermd.org/netcdf/. This module supports extensions to
6these conventions, such as writing of additional fields and writing to
7HDF5 (NetCDF-4) files.
9A netCDF4-python is required by this module:
11 netCDF4-python - https://github.com/Unidata/netcdf4-python
13NetCDF files can be directly visualized using the libAtoms flavor of
14AtomEye (http://www.libatoms.org/),
15VMD (http://www.ks.uiuc.edu/Research/vmd/)
16or Ovito (http://www.ovito.org/, starting with version 2.3).
17"""
19import collections
20import os
21import warnings
22from functools import reduce
24import numpy as np
26import ase
27from ase.data import atomic_masses
28from ase.geometry import cellpar_to_cell
31class NetCDFTrajectory:
32 """
33 Reads/writes Atoms objects into an AMBER-style .nc trajectory file.
34 """
36 # Default dimension names
37 _frame_dim = 'frame'
38 _spatial_dim = 'spatial'
39 _atom_dim = 'atom'
40 _cell_spatial_dim = 'cell_spatial'
41 _cell_angular_dim = 'cell_angular'
42 _label_dim = 'label'
43 _Voigt_dim = 'Voigt' # For stress/strain tensors
45 # Default field names. If it is a list, check for any of these names upon
46 # opening. Upon writing, use the first name.
47 _spatial_var = 'spatial'
48 _cell_spatial_var = 'cell_spatial'
49 _cell_angular_var = 'cell_angular'
50 _time_var = 'time'
51 _numbers_var = ['atom_types', 'type', 'Z']
52 _positions_var = 'coordinates'
53 _velocities_var = 'velocities'
54 _cell_origin_var = 'cell_origin'
55 _cell_lengths_var = 'cell_lengths'
56 _cell_angles_var = 'cell_angles'
58 _default_vars = reduce(
59 lambda x, y: x + y,
60 [
61 _numbers_var,
62 [_positions_var],
63 [_velocities_var],
64 [_cell_origin_var],
65 [_cell_lengths_var],
66 [_cell_angles_var],
67 ],
68 )
70 def __init__(
71 self,
72 filename,
73 mode='r',
74 atoms=None,
75 types_to_numbers=None,
76 double=True,
77 netcdf_format='NETCDF3_CLASSIC',
78 keep_open=True,
79 index_var='id',
80 chunk_size=1000000,
81 ):
82 """
83 A NetCDFTrajectory can be created in read, write or append mode.
85 Parameters
86 ----------
88 filename:
89 The name of the parameter file. Should end in .nc.
91 mode='r':
92 The mode.
94 'r' is read mode, the file should already exist, and no atoms
95 argument should be specified.
97 'w' is write mode. The atoms argument specifies the Atoms object
98 to be written to the file, if not given it must instead be given
99 as an argument to the write() method.
101 'a' is append mode. It acts a write mode, except that data is
102 appended to a preexisting file.
104 atoms=None:
105 The Atoms object to be written in write or append mode.
107 types_to_numbers=None:
108 Dictionary or list for conversion of atom types to atomic numbers
109 when reading a trajectory file.
111 double=True:
112 Create new variable in double precision.
114 netcdf_format='NETCDF3_CLASSIC':
115 Format string for the underlying NetCDF file format. Only relevant
116 if a new file is created. More information can be found at
117 https://www.unidata.ucar.edu/software/netcdf/docs/netcdf/File-Format.html
119 'NETCDF3_CLASSIC' is the original binary format.
121 'NETCDF3_64BIT' can be used to write larger files.
123 'NETCDF4_CLASSIC' is HDF5 with some NetCDF limitations.
125 'NETCDF4' is HDF5.
127 keep_open=True:
128 Keep the file open during consecutive read/write operations.
129 Set to false if you experience data corruption. This will close the
130 file after each read/write operation by comes with serious
131 performance penalty.
133 index_var='id':
134 Name of variable containing the atom indices. Atoms are reordered
135 by this index upon reading if this variable is present. Default
136 value is for LAMMPS output. None switches atom indices off.
138 chunk_size=1000000:
139 Maximum size of consecutive number of records (along the 'atom')
140 dimension read when reading from a NetCDF file. This is used to
141 reduce the memory footprint of a read operation on very large files.
142 """
143 self.nc = None
144 self.chunk_size = chunk_size
146 self.numbers = None
147 self.pre_observers = [] # Callback functions before write
148 self.post_observers = [] # Callback functions after write are called
150 self.has_header = False
151 self._set_atoms(atoms)
153 self.types_to_numbers = None
154 if isinstance(types_to_numbers, list):
155 types_to_numbers = {x: y for x, y in enumerate(types_to_numbers)}
156 if types_to_numbers is not None:
157 self.types_to_numbers = types_to_numbers
159 self.index_var = index_var
161 if self.index_var is not None:
162 self._default_vars += [self.index_var]
164 # 'l' should be a valid type according to the netcdf4-python
165 # documentation, but does not appear to work.
166 self.dtype_conv = {'l': 'i'}
167 if not double:
168 self.dtype_conv.update(dict(d='f'))
170 self.extra_per_frame_vars = []
171 self.extra_per_file_vars = []
172 # per frame atts are global quantities, not quantities stored for each
173 # atom
174 self.extra_per_frame_atts = []
176 self.mode = mode
177 self.netcdf_format = netcdf_format
179 if atoms:
180 self.n_atoms = len(atoms)
181 else:
182 self.n_atoms = None
184 self.filename = filename
185 if keep_open is None:
186 # Only netCDF4-python supports append to files
187 self.keep_open = self.mode == 'r'
188 else:
189 self.keep_open = keep_open
191 def __del__(self):
192 self.close()
194 def _open(self):
195 """
196 Opens the file.
198 For internal use only.
199 """
200 import netCDF4
202 if self.nc is not None:
203 return
204 if self.mode == 'a' and not os.path.exists(self.filename):
205 self.mode = 'w'
206 self.nc = netCDF4.Dataset(
207 self.filename, self.mode, format=self.netcdf_format
208 )
210 self.frame = 0
211 if self.mode == 'r' or self.mode == 'a':
212 self._read_header()
213 self.frame = self._len()
215 def _set_atoms(self, atoms=None):
216 """
217 Associate an Atoms object with the trajectory.
219 For internal use only.
220 """
221 if atoms is not None and not hasattr(atoms, 'get_positions'):
222 raise TypeError('"atoms" argument is not an Atoms object.')
223 self.atoms = atoms
225 def _read_header(self):
226 if not self.n_atoms:
227 self.n_atoms = len(self.nc.dimensions[self._atom_dim])
229 for name, var in self.nc.variables.items():
230 # This can be unicode which confuses ASE
231 name = str(name)
232 # _default_vars is taken care of already
233 if name not in self._default_vars:
234 if len(var.dimensions) >= 2:
235 if var.dimensions[0] == self._frame_dim:
236 if var.dimensions[1] == self._atom_dim:
237 self.extra_per_frame_vars += [name]
238 else:
239 self.extra_per_frame_atts += [name]
241 elif len(var.dimensions) == 1:
242 if var.dimensions[0] == self._atom_dim:
243 self.extra_per_file_vars += [name]
244 elif var.dimensions[0] == self._frame_dim:
245 self.extra_per_frame_atts += [name]
247 self.has_header = True
249 def write(self, atoms=None, frame=None, arrays=None, time=None):
250 """
251 Write the atoms to the file.
253 If the atoms argument is not given, the atoms object specified
254 when creating the trajectory object is used.
255 """
256 self._open()
257 self._call_observers(self.pre_observers)
258 if atoms is None:
259 atoms = self.atoms
261 if hasattr(atoms, 'interpolate'):
262 # seems to be a NEB
263 neb = atoms
264 assert not neb.parallel
265 try:
266 neb.get_energies_and_forces(all=True)
267 except AttributeError:
268 pass
269 for image in neb.images:
270 self.write(image)
271 return
273 if not self.has_header:
274 self._define_file_structure(atoms)
275 else:
276 if len(atoms) != self.n_atoms:
277 raise ValueError('Bad number of atoms!')
279 if frame is None:
280 i = self.frame
281 else:
282 i = frame
284 # Number can be per file variable
285 numbers = self._get_variable(self._numbers_var)
286 if numbers.dimensions[0] == self._frame_dim:
287 numbers[i] = atoms.get_atomic_numbers()
288 else:
289 if np.any(numbers != atoms.get_atomic_numbers()):
290 raise ValueError('Atomic numbers do not match!')
291 self._get_variable(self._positions_var)[i] = atoms.get_positions()
292 if atoms.has('momenta'):
293 self._add_velocities()
294 self._get_variable(self._velocities_var)[i] = (
295 atoms.get_momenta() / atoms.get_masses().reshape(-1, 1)
296 )
297 a, b, c, alpha, beta, gamma = atoms.cell.cellpar()
298 if np.any(np.logical_not(atoms.pbc)):
299 warnings.warn(
300 'Atoms have nonperiodic directions. Cell lengths in '
301 'these directions are lost and will be '
302 'shrink-wrapped when reading the NetCDF file.'
303 )
304 cell_lengths = np.array([a, b, c]) * atoms.pbc
305 self._get_variable(self._cell_lengths_var)[i] = cell_lengths
306 self._get_variable(self._cell_angles_var)[i] = [alpha, beta, gamma]
307 self._get_variable(self._cell_origin_var)[i] = (
308 atoms.get_celldisp().reshape(3)
309 )
310 if arrays is not None:
311 for array in arrays:
312 data = atoms.get_array(array)
313 if array in self.extra_per_file_vars:
314 # This field exists but is per file data. Check that the
315 # data remains consistent.
316 if np.any(self._get_variable(array) != data):
317 raise ValueError(
318 'Trying to write Atoms object with '
319 'incompatible data for the {} '
320 'array.'.format(array)
321 )
322 else:
323 self._add_array(atoms, array, data.dtype, data.shape)
324 self._get_variable(array)[i] = data
325 if time is not None:
326 self._add_time()
327 self._get_variable(self._time_var)[i] = time
329 self.sync()
331 self._call_observers(self.post_observers)
332 self.frame += 1
333 self._close()
335 def write_arrays(self, atoms, frame, arrays):
336 self._open()
337 self._call_observers(self.pre_observers)
338 for array in arrays:
339 data = atoms.get_array(array)
340 if array in self.extra_per_file_vars:
341 # This field exists but is per file data. Check that the
342 # data remains consistent.
343 if np.any(self._get_variable(array) != data):
344 raise ValueError(
345 'Trying to write Atoms object with '
346 'incompatible data for the {} '
347 'array.'.format(array)
348 )
349 else:
350 self._add_array(atoms, array, data.dtype, data.shape)
351 self._get_variable(array)[frame] = data
352 self._call_observers(self.post_observers)
353 self._close()
355 def _define_file_structure(self, atoms):
356 self.nc.Conventions = 'AMBER'
357 self.nc.ConventionVersion = '1.0'
358 self.nc.program = 'ASE'
359 self.nc.programVersion = ase.__version__
360 self.nc.title = 'MOL'
362 if self._frame_dim not in self.nc.dimensions:
363 self.nc.createDimension(self._frame_dim, None)
364 if self._spatial_dim not in self.nc.dimensions:
365 self.nc.createDimension(self._spatial_dim, 3)
366 if self._atom_dim not in self.nc.dimensions:
367 self.nc.createDimension(self._atom_dim, len(atoms))
368 if self._cell_spatial_dim not in self.nc.dimensions:
369 self.nc.createDimension(self._cell_spatial_dim, 3)
370 if self._cell_angular_dim not in self.nc.dimensions:
371 self.nc.createDimension(self._cell_angular_dim, 3)
372 if self._label_dim not in self.nc.dimensions:
373 self.nc.createDimension(self._label_dim, 5)
375 # Self-describing variables from AMBER convention
376 if not self._has_variable(self._spatial_var):
377 self.nc.createVariable(
378 self._spatial_var, 'S1', (self._spatial_dim,)
379 )
380 self.nc.variables[self._spatial_var][:] = ['x', 'y', 'z']
381 if not self._has_variable(self._cell_spatial_var):
382 self.nc.createVariable(
383 self._cell_spatial_dim, 'S1', (self._cell_spatial_dim,)
384 )
385 self.nc.variables[self._cell_spatial_var][:] = ['a', 'b', 'c']
386 if not self._has_variable(self._cell_angular_var):
387 self.nc.createVariable(
388 self._cell_angular_var,
389 'S1',
390 (
391 self._cell_angular_dim,
392 self._label_dim,
393 ),
394 )
395 self.nc.variables[self._cell_angular_var][0] = [x for x in 'alpha']
396 self.nc.variables[self._cell_angular_var][1] = [x for x in 'beta ']
397 self.nc.variables[self._cell_angular_var][2] = [x for x in 'gamma']
399 if not self._has_variable(self._numbers_var):
400 self.nc.createVariable(
401 self._numbers_var[0],
402 'i',
403 (
404 self._frame_dim,
405 self._atom_dim,
406 ),
407 )
408 if not self._has_variable(self._positions_var):
409 self.nc.createVariable(
410 self._positions_var,
411 'f4',
412 (self._frame_dim, self._atom_dim, self._spatial_dim),
413 )
414 self.nc.variables[self._positions_var].units = 'Angstrom'
415 self.nc.variables[self._positions_var].scale_factor = 1.0
416 if not self._has_variable(self._cell_lengths_var):
417 self.nc.createVariable(
418 self._cell_lengths_var,
419 'd',
420 (self._frame_dim, self._cell_spatial_dim),
421 )
422 self.nc.variables[self._cell_lengths_var].units = 'Angstrom'
423 self.nc.variables[self._cell_lengths_var].scale_factor = 1.0
424 if not self._has_variable(self._cell_angles_var):
425 self.nc.createVariable(
426 self._cell_angles_var,
427 'd',
428 (self._frame_dim, self._cell_angular_dim),
429 )
430 self.nc.variables[self._cell_angles_var].units = 'degree'
431 if not self._has_variable(self._cell_origin_var):
432 self.nc.createVariable(
433 self._cell_origin_var,
434 'd',
435 (self._frame_dim, self._cell_spatial_dim),
436 )
437 self.nc.variables[self._cell_origin_var].units = 'Angstrom'
438 self.nc.variables[self._cell_origin_var].scale_factor = 1.0
440 def _add_time(self):
441 if not self._has_variable(self._time_var):
442 self.nc.createVariable(self._time_var, 'f8', (self._frame_dim,))
444 def _add_velocities(self):
445 if not self._has_variable(self._velocities_var):
446 self.nc.createVariable(
447 self._velocities_var,
448 'f4',
449 (self._frame_dim, self._atom_dim, self._spatial_dim),
450 )
451 self.nc.variables[
452 self._positions_var
453 ].units = 'Angstrom/Femtosecond'
454 self.nc.variables[self._positions_var].scale_factor = 1.0
456 def _add_array(self, atoms, array_name, type, shape):
457 if not self._has_variable(array_name):
458 dims = [self._frame_dim]
459 for i in shape:
460 if i == len(atoms):
461 dims += [self._atom_dim]
462 elif i == 3:
463 dims += [self._spatial_dim]
464 elif i == 6:
465 # This can only be stress/strain tensor in Voigt notation
466 if self._Voigt_dim not in self.nc.dimensions:
467 self.nc.createDimension(self._Voigt_dim, 6)
468 dims += [self._Voigt_dim]
469 else:
470 raise TypeError(
471 "Don't know how to dump array of shape {}"
472 ' into NetCDF trajectory.'.format(shape)
473 )
474 if hasattr(type, 'char'):
475 t = self.dtype_conv.get(type.char, type)
476 else:
477 t = type
478 self.nc.createVariable(array_name, t, dims)
480 def _get_variable(self, name, exc=True):
481 if isinstance(name, list):
482 for n in name:
483 if n in self.nc.variables:
484 return self.nc.variables[n]
485 if exc:
486 raise RuntimeError(
487 'None of the variables {} was found in the '
488 'NetCDF trajectory.'.format(', '.join(name))
489 )
490 else:
491 if name in self.nc.variables:
492 return self.nc.variables[name]
493 if exc:
494 raise RuntimeError(
495 'Variables {} was found in the NetCDF trajectory.'.format(
496 name
497 )
498 )
499 return None
501 def _has_variable(self, name):
502 if isinstance(name, list):
503 for n in name:
504 if n in self.nc.variables:
505 return True
506 return False
507 else:
508 return name in self.nc.variables
510 def _get_data(self, name, frame, index, exc=True):
511 var = self._get_variable(name, exc=exc)
512 if var is None:
513 return None
514 if var.dimensions[0] == self._frame_dim:
515 data = np.zeros(var.shape[1:], dtype=var.dtype)
516 s = var.shape[1]
517 if s < self.chunk_size:
518 data[index] = var[frame]
519 else:
520 # If this is a large data set, only read chunks from it to
521 # reduce memory footprint of the NetCDFTrajectory reader.
522 for i in range((s - 1) // self.chunk_size + 1):
523 sl = slice(
524 i * self.chunk_size, min((i + 1) * self.chunk_size, s)
525 )
526 data[index[sl]] = var[frame, sl]
527 else:
528 data = np.zeros(var.shape, dtype=var.dtype)
529 s = var.shape[0]
530 if s < self.chunk_size:
531 data[index] = var[...]
532 else:
533 # If this is a large data set, only read chunks from it to
534 # reduce memory footprint of the NetCDFTrajectory reader.
535 for i in range((s - 1) // self.chunk_size + 1):
536 sl = slice(
537 i * self.chunk_size, min((i + 1) * self.chunk_size, s)
538 )
539 data[index[sl]] = var[sl]
540 return data
542 def __enter__(self):
543 return self
545 def __exit__(self, *args):
546 self.close()
548 def close(self):
549 """Close the trajectory file."""
550 if self.nc is not None:
551 self.nc.close()
552 self.nc = None
554 def _close(self):
555 if not self.keep_open:
556 self.close()
557 if self.mode == 'w':
558 self.mode = 'a'
560 def sync(self):
561 self.nc.sync()
563 def __getitem__(self, i=-1):
564 self._open()
566 if isinstance(i, slice):
567 return [self[j] for j in range(*i.indices(self._len()))]
569 N = self._len()
570 if 0 <= i < N:
571 # Non-periodic boundaries have cell_length == 0.0
572 cell_lengths = np.array(
573 self.nc.variables[self._cell_lengths_var][i][:]
574 )
575 pbc = np.abs(cell_lengths > 1e-6)
577 # Do we have a cell origin?
578 if self._has_variable(self._cell_origin_var):
579 origin = np.array(
580 self.nc.variables[self._cell_origin_var][i][:]
581 )
582 else:
583 origin = np.zeros([3], dtype=float)
585 # Do we have an index variable?
586 if self.index_var is not None and self._has_variable(
587 self.index_var
588 ):
589 index = np.array(self.nc.variables[self.index_var][i][:])
590 # The index variable can be non-consecutive, we here construct
591 # a consecutive one.
592 consecutive_index = np.zeros_like(index)
593 consecutive_index[np.argsort(index)] = np.arange(self.n_atoms)
594 else:
595 consecutive_index = np.arange(self.n_atoms)
597 # Read element numbers
598 self.numbers = self._get_data(
599 self._numbers_var, i, consecutive_index, exc=False
600 )
601 if self.numbers is None:
602 self.numbers = np.ones(self.n_atoms, dtype=int)
603 if self.types_to_numbers is not None:
604 d = set(self.numbers).difference(self.types_to_numbers.keys())
605 if len(d) > 0:
606 self.types_to_numbers.update({num: num for num in d})
607 func = np.vectorize(self.types_to_numbers.get)
608 self.numbers = func(self.numbers)
609 self.masses = atomic_masses[self.numbers]
611 # Read positions
612 positions = self._get_data(
613 self._positions_var, i, consecutive_index
614 )
616 # Determine cell size for non-periodic directions from shrink
617 # wrapped cell.
618 for dim in np.arange(3)[np.logical_not(pbc)]:
619 origin[dim] = positions[:, dim].min()
620 cell_lengths[dim] = positions[:, dim].max() - origin[dim]
622 # Construct cell shape from cell lengths and angles
623 cell = cellpar_to_cell(
624 list(cell_lengths)
625 + list(self.nc.variables[self._cell_angles_var][i])
626 )
628 # Compute momenta from velocities (if present)
629 momenta = self._get_data(
630 self._velocities_var, i, consecutive_index, exc=False
631 )
632 if momenta is not None:
633 momenta *= self.masses.reshape(-1, 1)
635 info = {
636 name: np.array(self.nc.variables[name][i])
637 for name in self.extra_per_frame_atts
638 }
639 # Create atoms object
640 atoms = ase.Atoms(
641 positions=positions,
642 numbers=self.numbers,
643 cell=cell,
644 celldisp=origin,
645 momenta=momenta,
646 masses=self.masses,
647 pbc=pbc,
648 info=info,
649 )
651 # Attach additional arrays found in the NetCDF file
652 for name in self.extra_per_frame_vars:
653 atoms.set_array(
654 name, self._get_data(name, i, consecutive_index)
655 )
656 for name in self.extra_per_file_vars:
657 atoms.set_array(
658 name, self._get_data(name, i, consecutive_index)
659 )
660 self._close()
661 return atoms
663 i = N + i
664 if i < 0 or i >= N:
665 self._close()
666 raise IndexError('Trajectory index out of range.')
667 return self[i]
669 def _len(self):
670 if self._frame_dim in self.nc.dimensions:
671 return int(self._get_variable(self._positions_var).shape[0])
672 else:
673 return 0
675 def __len__(self):
676 self._open()
677 n_frames = self._len()
678 self._close()
679 return n_frames
681 def pre_write_attach(self, function, interval=1, *args, **kwargs):
682 """
683 Attach a function to be called before writing begins.
685 function: The function or callable object to be called.
687 interval: How often the function is called. Default: every time (1).
689 All other arguments are stored, and passed to the function.
690 """
691 if not isinstance(function, collections.abc.Callable):
692 raise ValueError('Callback object must be callable.')
693 self.pre_observers.append((function, interval, args, kwargs))
695 def post_write_attach(self, function, interval=1, *args, **kwargs):
696 """
697 Attach a function to be called after writing ends.
699 function: The function or callable object to be called.
701 interval: How often the function is called. Default: every time (1).
703 All other arguments are stored, and passed to the function.
704 """
705 if not isinstance(function, collections.abc.Callable):
706 raise ValueError('Callback object must be callable.')
707 self.post_observers.append((function, interval, args, kwargs))
709 def _call_observers(self, obs):
710 """Call pre/post write observers."""
711 for function, interval, args, kwargs in obs:
712 if self.write_counter % interval == 0:
713 function(*args, **kwargs)
716def read_netcdftrajectory(filename, index=-1):
717 with NetCDFTrajectory(filename, mode='r') as traj:
718 return traj[index]
721def write_netcdftrajectory(filename, images):
722 if hasattr(images, 'get_positions'):
723 images = [images]
725 with NetCDFTrajectory(filename, mode='w') as traj:
726 for atoms in images:
727 traj.write(atoms)