Coverage for ase/vibrations/data.py: 98.90%
182 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"""Storage and analysis for vibrational data"""
3import collections
4from collections.abc import Iterator, Sequence
5from functools import cached_property
6from math import pi, sin, sqrt
7from numbers import Integral, Real
8from typing import Any, TypeVar
10import numpy as np
12import ase.io
13import ase.units as units
14from ase.atoms import Atoms
15from ase.calculators.singlepoint import SinglePointCalculator
16from ase.constraints import FixAtoms, FixCartesian, constrained_indices
17from ase.spectrum.doscollection import DOSCollection
18from ase.spectrum.dosdata import RawDOSData
19from ase.utils import jsonable
21RealSequence4D = Sequence[Sequence[Sequence[Sequence[Real]]]]
22VD = TypeVar('VD', bound='VibrationsData')
25@jsonable('vibrationsdata')
26class VibrationsData:
27 """Class for storing and analyzing vibrational data (i.e. Atoms + Hessian)
29 This class is not responsible for calculating Hessians; the Hessian should
30 be computed by a Calculator or some other algorithm.
31 Once :class:`VibrationsData` has been constructed, this class provides some
32 common processing options; frequency calculation, mode animation, DOS etc.
34 If the Atoms object is a periodic supercell, :class:`VibrationsData` may be
35 converted to a PhononData using the VibrationsData.to_phonondata() method.
36 This provides access to q-point-dependent analyses such as phonon
37 dispersion plotting.
39 If the Atoms object has :class:`~ase.constraints.FixAtoms` or
40 :class:`~.ase.constraints.FixCartesian` constraints,
41 these will be respected and the Hessian should be sized accordingly.
43 Parameters
44 ----------
45 atoms : :class:`~ase.Atoms`
46 Equilibrium geometry of vibrating system.
47 This will be stored as a full copy.
49 hessian : np.ndarray
50 Second-derivative in energy with respect to Cartesian nuclear movements
51 as an (N, 3, N, 3) array.
53 indices : Sequence[int] | np.ndarray | None, default: None
54 Indices of atoms which are included in Hessian.
55 By default, it includes all freely moving atoms (i.e. not fixed ones).
56 Leave at None if constraints should be determined automatically from
57 the atoms object.
59 """
61 def __init__(
62 self,
63 atoms: Atoms,
64 hessian: RealSequence4D | np.ndarray,
65 indices: Sequence[int] | np.ndarray | None = None,
66 ) -> None:
67 if indices is None:
68 indices = np.asarray(
69 self.indices_from_constraints(atoms), dtype=int
70 )
72 self._indices = np.array(indices, dtype=int)
74 n_atoms = self._check_dimensions(
75 atoms, np.asarray(hessian), indices=self._indices
76 )
77 self._atoms = atoms.copy()
79 self._hessian2d = (
80 np.asarray(hessian).reshape(3 * n_atoms, 3 * n_atoms).copy()
81 )
83 _setter_error = (
84 'VibrationsData properties cannot be modified: construct '
85 'a new VibrationsData with consistent atoms, Hessian and '
86 '(optionally) indices/mask.'
87 )
89 @classmethod
90 def from_2d(
91 cls,
92 atoms: Atoms,
93 hessian_2d: Sequence[Sequence[Real]] | np.ndarray,
94 indices: Sequence[int] | None = None,
95 ) -> 'VibrationsData':
96 """Instantiate VibrationsData when the Hessian is in a 3Nx3N format
98 Parameters
99 ----------
100 atoms : :class:`~ase.Atoms`
101 Equilibrium geometry of vibrating system.
103 hessian : Sequence[Sequence[Real]] | np.ndarray
104 Second-derivative in energy with respect to Cartesian nuclear
105 movements as a (3N, 3N) array.
107 indices : Sequence[int] | None, default: None
108 Indices of (non-frozen) atoms included in Hessian.
110 """
111 if indices is None:
112 indices = range(len(atoms))
113 assert indices is not None # Show Mypy that indices is now a sequence
115 hessian_2d_array = np.asarray(hessian_2d)
116 n_atoms = cls._check_dimensions(
117 atoms, hessian_2d_array, indices=indices, two_d=True
118 )
120 return cls(
121 atoms,
122 hessian_2d_array.reshape(n_atoms, 3, n_atoms, 3),
123 indices=indices,
124 )
126 @staticmethod
127 def indices_from_constraints(atoms: Atoms) -> list[int]:
128 """Indices corresponding to Atoms Constraints
130 Deduces the freely moving atoms from the constraints set on the
131 atoms object. :class:`VibrationsData` only supports:
133 - :class:`~ase.constraints.FixCartesian`
134 - :class:`~ase.constraints.FixAtoms`
136 All others are neglected.
138 Parameters
139 ----------
140 atoms : :class:`~ase.Atoms`
142 Returns
143 -------
144 list[int]
145 Indices of free atoms.
147 """
148 # Only fully fixed atoms supported by VibrationsData
149 const_indices = constrained_indices(
150 atoms, only_include=(FixCartesian, FixAtoms)
151 )
152 # Invert the selection to get free atoms
153 indices = np.setdiff1d(
154 np.array(range(len(atoms))), const_indices
155 ).astype(int)
156 # TODO: use numpy.typing to resolve this error.
157 return indices.tolist() # type: ignore[return-value]
159 @staticmethod
160 def indices_from_mask(
161 mask: Sequence[bool] | np.ndarray,
162 ) -> list[int]:
163 """Indices corresponding to boolean mask
165 This is provided as a convenience for instantiating
166 :class:`VibrationsData` with a boolean mask.
167 For example, if the Hessian data includes only the H
168 atoms in a structure::
170 h_mask = atoms.get_chemical_symbols() == 'H'
171 vib_data = VibrationsData(atoms, hessian,
172 VibrationsData.indices_from_mask(h_mask))
174 Take care to ensure that the length of the mask corresponds to the full
175 number of atoms; this function is only aware of the mask it has been
176 given.
178 Parameters
179 ----------
180 mask: Sequence[bool] | np.ndarray
181 Sequence of boolean values.
183 Returns
184 -------
185 list[int]
186 Indices of :obj:`True` elements.
188 """
189 # TODO: use numpy.typing to resolve this error.
190 return np.where(mask)[0].tolist() # type: ignore[return-value]
192 @staticmethod
193 def _check_dimensions(
194 atoms: Atoms,
195 hessian: np.ndarray,
196 indices: np.ndarray | Sequence[int],
197 two_d: bool = False,
198 ) -> int:
199 """Sanity check on array shapes from input data
201 Parameters
202 ----------
203 atoms : :class:`~ase.Atoms`
204 hessian : np.ndarray
205 Proposed Hessian array.
206 indices : np.ndarray | Sequence[int]
207 Indices of atoms used in Hessian.
209 Returns
210 -------
211 Number of atoms contributing to Hessian.
213 Raises
214 ------
215 ValueError
216 If Hessian dimensions are not (N, 3, N, 3).
218 """
220 n_atoms = len(atoms[indices])
222 if two_d:
223 ref_shape = [n_atoms * 3, n_atoms * 3]
224 ref_shape_txt = '{n:d}x{n:d}'.format(n=(n_atoms * 3))
226 else:
227 ref_shape = [n_atoms, 3, n_atoms, 3]
228 ref_shape_txt = '{n:d}x3x{n:d}x3'.format(n=n_atoms)
230 if isinstance(hessian, np.ndarray) and hessian.shape == tuple(
231 ref_shape
232 ):
233 return n_atoms
234 else:
235 raise ValueError(
236 'Hessian for these atoms should be a {} numpy array.'.format(
237 ref_shape_txt
238 )
239 )
241 def get_atoms(self) -> Atoms:
242 return self._atoms.copy()
244 def get_indices(self) -> np.ndarray:
245 return self._indices.copy()
247 def get_mask(self) -> np.ndarray:
248 """Boolean mask of atoms selected by indices"""
249 return self._mask_from_indices(self._atoms, self.get_indices())
251 @staticmethod
252 def _mask_from_indices(
253 atoms: Atoms,
254 indices: Sequence[int] | np.ndarray | None,
255 ) -> np.ndarray:
256 """Boolean mask of atoms selected by indices"""
257 natoms = len(atoms)
259 # Wrap indices to allow negative values
260 indices = np.asarray(indices) % natoms
262 mask = np.full(natoms, False, dtype=bool)
263 mask[indices] = True
264 return mask
266 def get_hessian(self) -> np.ndarray:
267 """The Hessian; second derivative of energy wrt positions
269 This format is preferred for iteration over atoms and when
270 addressing specific elements of the Hessian.
272 Returns
273 -------
274 np.ndarray
275 Array with shape (n_atoms, 3, n_atoms, 3) where
277 - the first and third indices identify atoms in self.get_atoms()
279 - the second and fourth indices cover the corresponding
280 Cartesian movements in x, y, z
282 e.g. the element h[0, 2, 1, 0] gives a harmonic force exerted on
283 atoms[1] in the x-direction in response to a movement in the
284 z-direction of atoms[0]
285 """
286 n_atoms = int(self._hessian2d.shape[0] / 3)
287 return self._hessian2d.reshape(n_atoms, 3, n_atoms, 3).copy()
289 def get_hessian_2d(self) -> np.ndarray:
290 """Get the Hessian as a 2-D array
292 This format may be preferred for use with standard linear algebra
293 functions
295 Returns
296 -------
297 np.ndarray
298 Array with shape (n_atoms * 3, n_atoms * 3) where the elements are
299 ordered by atom and Cartesian direction::
301 >> [[at1x_at1x, at1x_at1y, at1x_at1z, at1x_at2x, ...],
302 >> [at1y_at1x, at1y_at1y, at1y_at1z, at1y_at2x, ...],
303 >> [at1z_at1x, at1z_at1y, at1z_at1z, at1z_at2x, ...],
304 >> [at2x_at1x, at2x_at1y, at2x_at1z, at2x_at2x, ...],
305 >> ...]
308 e.g. the element h[2, 3] gives a harmonic force exerted on
309 atoms[1] in the x-direction in response to a movement in the
310 z-direction of atoms[0]
311 """
312 return self._hessian2d.copy()
314 def todict(self) -> dict[str, Any]:
315 unconstrained_indices = self.indices_from_constraints(self._atoms)
316 if (
317 len(self._indices) == len(unconstrained_indices)
318 and (self._indices == unconstrained_indices).all()
319 ):
320 indices = None
321 else:
322 indices = self.get_indices()
324 return {
325 'atoms': self.get_atoms(),
326 'hessian': self.get_hessian(),
327 'indices': indices,
328 }
330 @classmethod
331 def fromdict(cls, data: dict[str, Any]) -> 'VibrationsData':
332 # mypy is understandably suspicious of data coming from a dict that
333 # holds mixed types, but it can see if we sanity-check with 'assert'
334 assert isinstance(data['atoms'], Atoms)
335 assert isinstance(
336 data['hessian'], (collections.abc.Sequence, np.ndarray)
337 )
338 if data['indices'] is not None:
339 assert isinstance(
340 data['indices'], (collections.abc.Sequence, np.ndarray)
341 )
342 for index in data['indices']:
343 assert isinstance(index, Integral)
345 return cls(data['atoms'], data['hessian'], indices=data['indices'])
347 @cached_property
348 def _energies_and_modes(self) -> tuple[np.ndarray, np.ndarray]:
349 """Diagonalise the Hessian to obtain harmonic modes
351 This method is an internal implementation of get_energies_and_modes(),
352 see the docstring of that method for more information.
354 """
355 active_atoms = self._atoms[self.get_mask()]
356 n_atoms = len(active_atoms)
357 masses = active_atoms.get_masses()
359 if not np.all(masses):
360 raise ValueError(
361 'Zero mass encountered in one or more of '
362 'the vibrated atoms. Use Atoms.set_masses()'
363 ' to set all masses to non-zero values.'
364 )
365 mass_weights = np.repeat(masses**-0.5, 3)
367 omega2, vectors = np.linalg.eigh(
368 mass_weights * self.get_hessian_2d() * mass_weights[:, np.newaxis]
369 )
371 unit_conversion = units._hbar * units.m / sqrt(units._e * units._amu)
372 energies = unit_conversion * omega2.astype(complex) ** 0.5
374 modes = vectors.T.reshape(n_atoms * 3, n_atoms, 3)
375 modes = modes * masses[np.newaxis, :, np.newaxis] ** -0.5
377 return (energies, modes)
379 def get_energies_and_modes(
380 self,
381 all_atoms: bool = False,
382 ) -> tuple[np.ndarray, np.ndarray]:
383 """Diagonalise the Hessian to obtain harmonic modes
385 Results are cached so diagonalization will only be performed once for
386 this object instance.
388 Parameters
389 ----------
390 all_atoms : bool
391 If True, return modes as (3N, [N + N_frozen], 3) array where
392 the second axis corresponds to the full list of atoms in the
393 attached atoms object. Atoms that were not included in the
394 Hessian will have displacement vectors of (0, 0, 0).
396 Returns
397 -------
398 tuple[np.ndarray, np.ndarray]
400 Tuple of (energies, modes).
402 Energies are given in units of eV. (To convert these to frequencies
403 in cm-1, divide by ase.units.invcm.)
405 Modes are given in Cartesian coordinates as a (3N, N, 3) array
406 where indices correspond to the (mode_index, atom, direction).
408 """
410 energies, modes_from_hessian = self._energies_and_modes
412 if all_atoms:
413 n_active_atoms = len(self.get_indices())
414 n_all_atoms = len(self._atoms)
415 modes = np.zeros((3 * n_active_atoms, n_all_atoms, 3))
416 modes[:, self.get_mask(), :] = modes_from_hessian
417 else:
418 modes = modes_from_hessian.copy()
420 return (energies.copy(), modes)
422 def get_modes(self, all_atoms: bool = False) -> np.ndarray:
423 """Diagonalise the Hessian to obtain harmonic modes
425 Results are cached so diagonalization will only be performed once for
426 this object instance.
428 Parameters
429 ----------
430 all_atoms : bool
431 If True, return modes as (3N, [N + N_frozen], 3) array where
432 the second axis corresponds to the full list of atoms in the
433 attached atoms object. Atoms that were not included in the
434 Hessian will have displacement vectors of (0, 0, 0).
436 Returns
437 -------
438 np.ndarray
439 Modes in Cartesian coordinates as a (3N, N, 3) array where indices
440 correspond to the (mode_index, atom, direction).
442 """
443 return self.get_energies_and_modes(all_atoms=all_atoms)[1]
445 def get_energies(self) -> np.ndarray:
446 """Diagonalise the Hessian to obtain eigenvalues
448 Results are cached so diagonalization will only be performed once for
449 this object instance.
451 Returns
452 -------
453 np.ndarray
454 Harmonic mode energies in units of eV.
456 """
457 return self.get_energies_and_modes()[0]
459 def get_frequencies(self) -> np.ndarray:
460 """Diagonalise the Hessian to obtain frequencies in cm^-1
462 Results are cached so diagonalization will only be performed once for
463 this object instance.
465 Returns
466 -------
467 Harmonic mode frequencies in units of cm^-1.
469 """
471 return self.get_energies() / units.invcm
473 def get_zero_point_energy(self) -> float:
474 """Diagonalise the Hessian and sum hw/2 to obtain zero-point energy
476 Returns
477 -------
478 float
479 Zero-point energy in eV.
481 """
482 return self._calculate_zero_point_energy(self.get_energies())
484 @staticmethod
485 def _calculate_zero_point_energy(
486 energies: Sequence[complex] | np.ndarray,
487 ) -> float:
488 return 0.5 * np.asarray(energies).real.sum()
490 def tabulate(self, im_tol: float = 1e-8) -> str:
491 """Get a summary of the vibrational frequencies.
493 Parameters
494 ----------
495 im_tol : float
496 Tolerance for imaginary frequency in eV.
497 If frequency has a larger imaginary component than im_tol,
498 the imaginary component is shown in the summary table.
500 Returns
501 -------
502 str
503 Summary table as formatted text.
505 """
507 energies = self.get_energies()
509 return (
510 '\n'.join(self._tabulate_from_energies(energies, im_tol=im_tol))
511 + '\n'
512 )
514 @classmethod
515 def _tabulate_from_energies(
516 cls,
517 energies: Sequence[complex] | np.ndarray,
518 im_tol: float = 1e-8,
519 ) -> list[str]:
520 summary_lines = [
521 '---------------------',
522 ' # meV cm^-1',
523 '---------------------',
524 ]
526 for n, e in enumerate(energies):
527 if abs(e.imag) > im_tol:
528 c = 'i'
529 e = e.imag
530 else:
531 c = ''
532 e = e.real
534 summary_lines.append(
535 '{index:3d} {mev:6.1f}{im:1s} {cm:7.1f}{im}'.format(
536 index=n, mev=(e * 1e3), cm=(e / units.invcm), im=c
537 )
538 )
539 summary_lines.append('---------------------')
540 summary_lines.append(
541 'Zero-point energy: {:.3f} eV'.format(
542 cls._calculate_zero_point_energy(energies=energies)
543 )
544 )
546 return summary_lines
548 def iter_animated_mode(
549 self,
550 mode_index: int,
551 temperature: float = units.kB * 300.0,
552 frames: int = 30,
553 ) -> Iterator[Atoms]:
554 """Obtain animated mode as a series of Atoms
556 Parameters
557 ----------
558 mode_index : int
559 Selection of mode to animate.
560 temperature : float
561 Temperature in energy units - use ``units.kB * T_IN_KELVIN``
562 frames : int
563 Number of image frames in animation.
565 Yields
566 ------
567 :class:`~ase.Atoms`
568 Displaced atoms following vibrational mode.
570 """
572 mode = self.get_modes(all_atoms=True)[mode_index] * sqrt(
573 temperature / abs(self.get_energies()[mode_index])
574 )
576 for phase in np.linspace(0, 2 * pi, frames, endpoint=False):
577 atoms = self.get_atoms()
578 atoms.positions += sin(phase) * mode
580 yield atoms
582 def show_as_force(
583 self,
584 mode: int,
585 scale: float = 0.2,
586 show: bool = True,
587 ) -> Atoms:
588 """Illustrate mode as "forces" on atoms
590 Parameters
591 ----------
592 mode : int
593 Mode index.
594 scale : float
595 Scale factor.
596 show : bool
597 If True, open the ASE GUI and show atoms.
599 Returns
600 -------
601 :class:`~ase.Atoms`
602 Atoms with scaled forces corresponding to mode eigenvectors (using
603 attached SinglePointCalculator).
605 """
607 atoms = self.get_atoms()
608 mode = self.get_modes(all_atoms=True)[mode] * len(atoms) * 3 * scale
609 atoms.calc = SinglePointCalculator(atoms, forces=mode)
610 if show:
611 atoms.edit()
613 return atoms
615 def write_jmol(
616 self,
617 filename: str = 'vib.xyz',
618 ir_intensities: Sequence[float] | np.ndarray | None = None,
619 ) -> None:
620 """Writes file for viewing of the modes with jmol.
622 This is an extended XYZ file with eigenvectors given as extra columns
623 and metadata given in the label/comment line for each image. The format
624 is not quite human-friendly, but has the advantage that it can be
625 imported back into ASE with ase.io.read.
627 Parameters
628 ----------
629 filename : str
630 Path for output file.
631 ir_intensities :
632 If available, IR intensities can be included in the header lines.
633 This does not affect the visualisation but may be convenient when
634 comparing to experimental data.
636 """
638 all_images = list(
639 self._get_jmol_images(
640 atoms=self.get_atoms(),
641 energies=self.get_energies(),
642 modes=self.get_modes(all_atoms=True),
643 ir_intensities=ir_intensities,
644 )
645 )
646 ase.io.write(filename, all_images, format='extxyz')
648 @staticmethod
649 def _get_jmol_images(
650 atoms: Atoms,
651 energies: np.ndarray,
652 modes: np.ndarray,
653 ir_intensities: Sequence[float] | np.ndarray | None = None,
654 ) -> Iterator[Atoms]:
655 """Get vibrational modes as a series of Atoms with attached data
657 For each image (Atoms object):
659 - eigenvalues are attached to image.arrays['mode']
660 - "mode#" and "frequency_cm-1" are set in image.info
661 - "IR_intensity" is set if provided in ir_intensities
662 - "masses" is removed
664 This is intended to set up the object for JMOL-compatible export using
665 ase.io.extxyz.
667 Parameters
668 ----------
669 atoms : :class:`~ase.Atoms`
670 The base atoms object; all images have the same positions
671 energies : np.ndarray
672 Complex vibrational energies in eV.
673 modes : np.ndarray
674 Eigenvectors array corresponding to atoms and energies.
675 This should cover the full set of atoms (i.e. modes =
676 vib.get_modes(all_atoms=True)).
677 ir_intensities: Sequence[float] | np.ndarray | None = None
678 If available, IR intensities can be included in the header lines.
679 This does not affect the visualisation but may be convenient when
680 comparing to experimental data.
682 Returns
683 -------
684 Iterator[Atoms]
686 """
687 for i, (energy, mode) in enumerate(zip(energies, modes)):
688 # write imaginary frequencies as negative numbers
689 if energy.imag > energy.real:
690 energy = float(-energy.imag)
691 else:
692 energy = energy.real
694 image = atoms.copy()
695 image.info.update(
696 {
697 'mode#': str(i),
698 'frequency_cm-1': energy / units.invcm,
699 }
700 )
701 image.arrays['mode'] = mode
703 # Custom masses are quite useful in vibration analysis, but will
704 # show up in the xyz file unless we remove them
705 if image.has('masses'):
706 del image.arrays['masses']
708 if ir_intensities is not None:
709 image.info['IR_intensity'] = float(ir_intensities[i])
711 yield image
713 def get_dos(self) -> RawDOSData:
714 """Total phonon DOS"""
715 energies = self.get_energies()
716 return RawDOSData(energies, np.ones_like(energies))
718 def get_pdos(self) -> DOSCollection:
719 """Phonon DOS, including atomic contributions"""
720 energies = self.get_energies()
721 masses = self._atoms[self.get_mask()].get_masses()
723 # Get weights as N_moving_atoms x N_modes array
724 vectors = self.get_modes() / masses[np.newaxis, :, np.newaxis] ** -0.5
725 all_weights = (np.linalg.norm(vectors, axis=-1) ** 2).T
727 mask = self.get_mask()
728 all_info = [
729 {'index': i, 'symbol': a.symbol}
730 for i, a in enumerate(self._atoms)
731 if mask[i]
732 ]
734 return DOSCollection(
735 [
736 RawDOSData(energies, weights, info=info)
737 for weights, info in zip(all_weights, all_info)
738 ]
739 )
741 def with_new_masses(
742 self: VD,
743 masses: Sequence[float] | np.ndarray,
744 ) -> VD:
745 """Get a copy of vibrations with modified masses and the same Hessian
747 Parameters
748 ----------
749 masses: Sequence[float] | np.ndarray
750 New sequence of masses corresponding to the atom order in
751 ``self.get_atoms()``.
753 Returns
754 -------
755 :class:`VibrationalData`
756 A copy of the data with new masses for the same Hessian.
758 """
760 new_atoms = self.get_atoms()
761 new_atoms.set_masses(masses)
762 return self.__class__(
763 new_atoms, self.get_hessian(), indices=self.get_indices()
764 )