Coverage for dynasor/modes/project_modes.py: 97%

53 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-09 14:30 +0000

1from typing import Optional 

2 

3import numpy as np 

4 

5from ase import Atoms 

6from numpy.typing import NDArray 

7 

8from dynasor.logging_tools import logger 

9from dynasor.modes.atoms import DynasorAtoms 

10from dynasor.modes.tools import mode_coordinates, mode_forces, mode_momenta 

11from dynasor.trajectory import Trajectory 

12from dynasor.tools.structures import get_displacements_from_u 

13 

14 

15def _validated_masses(ideal_supercell: Atoms) -> NDArray[float]: 

16 """Returns the masses of the supercell in dmu, checking that every one of them can be 

17 divided by.""" 

18 masses = DynasorAtoms(ideal_supercell).masses 

19 bad = np.flatnonzero(~np.isfinite(masses) | (masses <= 0)) 

20 if len(bad) > 0: 

21 raise ValueError( 

22 'Projecting forces requires a positive and finite mass for every atom of ' 

23 f'ideal_supercell, but the masses of atoms {bad.tolist()} are not.') 

24 return masses 

25 

26 

27def project_modes( 

28 traj: Trajectory, 

29 modes: NDArray[float], 

30 ideal_supercell: Atoms, 

31 check_mic: Optional[bool] = True, 

32 logging_interval: Optional[int] = 1000, 

33) -> tuple[NDArray[complex], NDArray[complex], NDArray[complex]]: 

34 r"""Projects an atomic trajectory onto set of phonon modes. 

35 

36 The projection follows the conventions of :class:`ModeProjector 

37 <dynasor.ModeProjector>`, 

38 

39 .. math:: 

40 

41 Q = X u, \quad P = X^* v, \quad F = X^* f / m 

42 

43 where :math:`X` are the modes, :math:`u` the displacements, :math:`v` the velocities, 

44 :math:`f` the forces and :math:`m` the atomic masses. 

45 The mode forces are conjugate to the mode coordinates, meaning 

46 :math:`F = -\partial V / \partial Q`, so the virial energy of a mode is :math:`-QF/2`. 

47 See :attr:`ModeProjector.virial_energies <dynasor.ModeProjector.virial_energies>` for that 

48 quantity and for how its imaginary parts behave. 

49 

50 This is the path for long trajectories; use :class:`~dynasor.ModeProjector` to 

51 explore individual modes interactively. Its 

52 :attr:`~dynasor.ModeProjector.eigenmodes` can be passed directly as :attr:`modes`. 

53 

54 Parameters 

55 ---------- 

56 traj 

57 Input trajectory. 

58 modes 

59 Modes to project on, as an array with shape ``(..., N, 3)`` where ``N`` is the 

60 number of atoms in the supercell and the leading dimensions define the output shape. 

61 ideal_supercell 

62 Ideal supercell used to find atomic displacements and to provide the atomic masses. 

63 The masses have to be the ones that :attr:`modes` was built with, which for modes from 

64 a :class:`ModeProjector <dynasor.ModeProjector>` are the supercell masses of that 

65 projector. 

66 Neither the atom ordering nor the masses are checked, and a mismatch changes `F` per 

67 atom instead of by an overall factor. 

68 The atom count is checked against :attr:`traj`, and a mismatched cell only triggers a 

69 warning, since some thermal expansion relative to the reference structure is normal. 

70 check_mic 

71 Whether to wrap the displacements or not, faster if no wrap. 

72 logging_interval 

73 Log progress at ``INFO`` level every this many frames. Set to ``0`` to disable 

74 progress logging. 

75 

76 Returns 

77 ------- 

78 A tuple comprising `(Q, P, F)` where `Q` are the mode coordinates in Å√dmu, `P` are 

79 the mode momenta in √eV and `F` are the mode forces in eV/Å√dmu. 

80 Each array has shape ``(n_frames, *modes.shape[:-2])``, where ``n_frames`` is the 

81 number of frames read from :attr:`traj`. 

82 `P` is all zeros if :attr:`traj` provides no velocities, and `F` is all zeros if it 

83 provides no forces. 

84 

85 Raises 

86 ------ 

87 ValueError 

88 If :attr:`traj` provides no positions, if :attr:`modes` does not have shape 

89 ``(..., N, 3)``, if :attr:`ideal_supercell` and :attr:`traj` disagree on the number of 

90 atoms, if a frame past the first provides no positions, velocities or forces, or if 

91 :attr:`traj` provides forces while :attr:`ideal_supercell` gives an atom a mass that 

92 is not positive and finite. 

93 

94 Examples 

95 -------- 

96 The mode forces give the virial energy of every mode along a trajectory:: 

97 

98 >>> Q, P, F = project_modes(traj, mp.eigenmodes, mp.supercell.to_ase()) # doctest: +SKIP 

99 >>> virial_energies = (-Q * F / 2).real # doctest: +SKIP 

100 

101 """ 

102 # logger 

103 logger.info('Running mode projection') 

104 if not traj.has_positions: 104 ↛ 105line 104 didn't jump to line 105 because the condition on line 104 was never true

105 raise ValueError('project_modes requires positions to be available in the trajectory, ' 

106 'but traj does not provide positions.') 

107 has_velocities = traj.has_velocities 

108 has_forces = traj.has_forces 

109 if not has_velocities: 

110 logger.info('traj does not provide velocities; P will be returned as zeros') 

111 if not has_forces: 

112 logger.info('traj does not provide forces; F will be returned as zeros') 

113 

114 modes = np.asarray(modes) 

115 

116 if modes.ndim < 2 or modes.shape[-1] != 3 or modes.shape[-2] != traj.n_atoms: 

117 raise ValueError( 

118 f'modes must have shape (..., N, 3), where N = {traj.n_atoms} is the number of ' 

119 f'atoms in the trajectory, but has shape {modes.shape}.') 

120 if traj.n_atoms != len(ideal_supercell): 

121 raise ValueError('ideal_supercell must contain the same number of atoms as the trajectory.') 

122 if not np.allclose(traj.cell, ideal_supercell.cell, atol=1e-5, rtol=0.0): 

123 logger.warning('ideal_supercell cell does not match the trajectory cell.') 

124 

125 if has_forces: 

126 masses = _validated_masses(ideal_supercell) 

127 

128 Q_traj, P_traj, F_traj = [], [], [] 

129 atomic_indices = traj.atomic_indices 

130 

131 for it, frame in enumerate(traj): 

132 if logging_interval and it % logging_interval == 0: 

133 traj._log_progress(frame.frame_index) 

134 

135 # Make positions into displacements 

136 x = frame.get_positions_as_array(atomic_indices) 

137 u = x - ideal_supercell.positions 

138 

139 # Calculate Q 

140 u = get_displacements_from_u(u, ideal_supercell.cell, check_mic=check_mic) 

141 Q_traj.append(mode_coordinates(modes, u)) 

142 

143 # Calculate P 

144 if has_velocities: 

145 v = frame.get_velocities_as_array(atomic_indices) 

146 P_traj.append(mode_momenta(modes, v)) 

147 

148 # Calculate F 

149 if has_forces: 

150 f = frame.get_forces_as_array(atomic_indices) 

151 F_traj.append(mode_forces(modes, f, masses)) 

152 

153 # The reshape only acts on a trajectory of no frames, which would otherwise lose the 

154 # leading mode dimensions. 

155 Q_traj = np.array(Q_traj).reshape((-1, *modes.shape[:-2])) 

156 P_traj = np.array(P_traj).reshape(Q_traj.shape) if has_velocities else np.zeros_like(Q_traj) 

157 F_traj = np.array(F_traj).reshape(Q_traj.shape) if has_forces else np.zeros_like(Q_traj) 

158 

159 return Q_traj, P_traj, F_traj