Coverage for dynasor/modes/mode_projector.py: 100%

210 statements  

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

1from __future__ import annotations 

2from typing import Optional 

3 

4import numpy as np 

5import warnings 

6import pickle 

7 

8from ase.calculators.singlepoint import SinglePointCalculator 

9from ase.units import fs 

10from ase import Atoms 

11from numpy.typing import NDArray 

12 

13from dynasor.units import radians_per_fs_to_THz 

14from dynasor.tools.structures import get_displacements 

15from .tools import (get_dynamical_matrix, group_eigvals, mode_coordinates, mode_forces, 

16 mode_momenta, symmetrize_eigenvectors) 

17from .qpoint import QPoint 

18from .atoms import Prim, Supercell 

19from ..qpoints.lattice import Lattice 

20 

21 

22class ModeProjector: 

23 """ 

24 The :class:`ModeProjector` maps between real atomic displacements `u` and 

25 complex mode coordinates `Q`. 

26 

27 Some special python methods are implemented. The `__str__` and `__repr__` 

28 provides useful info. :class:`QPoint <dynasor.modes.qpoint.QPoint>` objects are 

29 representations of a single q-point and associated information and can be accessed either by 

30 call providing a reduced wavevector 

31 

32 >>> mp((1/2, 0, 0)) # doctest: +SKIP 

33 

34 or by index corresponding to reduced q-point accessible from 

35 :attr:`~ModeProjector.q_reduced` 

36 

37 >>> mp[2] # doctest: +SKIP 

38 

39 In addition to mode coordinates `Q` the class can also map the atomic 

40 velocities `v` to mode momenta `P` as well as atomic forces `f` to mode 

41 forces `F`. The class can also map back. This mapping is done using 

42 getters and setters. Internally only Q, P and F are stored 

43 

44 >>> Q = mp.get_Q() # doctest: +SKIP 

45 >>> mp.set_u(u) # doctest: +SKIP 

46 

47 In addition, the forces corresponding to the harmonic forces can be 

48 accessed by :meth:`~ModeProjector.get_f_harmonic()` and 

49 :meth:`~ModeProjector.get_F_harmonic()`. For ASE Atoms objects the 

50 displacements etc. can be updated and applied by 

51 

52 >>> mp.update_from_atoms(atoms) # doctest: +SKIP 

53 >>> atoms = mp.get_atoms(harmonic_forces=False) # doctest: +SKIP 

54 

55 The shapes for each property uses the following variables 

56 

57 * `N`: Number of atoms in supercell 

58 * `Nu`: unit cells (`N/Np`) 

59 * `Np`: primitive basis atoms (`N/Nu`) 

60 * `Nb`: bands (`Np*3`) 

61 * `Nq`: q-points (`Nu`) 

62 

63 Please consult the documentation or the specific getters and setters to see 

64 the exact transformations used. 

65 

66 The dynamical matrix is built from the first supercell atom of each primitive 

67 basis site, so the force constants must be translationally invariant. 

68 

69 Use :class:`ModeProjector` to explore and manipulate individual modes 

70 interactively; use :func:`~dynasor.project_modes` to project a long 

71 trajectory. The two connect via :attr:`eigenmodes`, which 

72 :func:`~dynasor.project_modes` takes as input. 

73 

74 .. rubric:: Units 

75 

76 The internal units in dynasor are Å, fs and eV. All frequencies are angular 

77 (a.k.a. the "physicist's convention" with 2π included). These are the units 

78 dynasor will expect and return. In, e.g., print functions conventional units 

79 such fs, Å, THz, Da, meV are commonly used. 

80 

81 **Mass:** 

82 The internal unit choice (eV, Å, fs) means that the mass unit is not Dalton 

83 but rather 0.009648533290731906 Da. 

84 We refer to this unit as the "dynasor mass unit" (dmu), 

85 i.e., 1 Da = 103.64269572045423 dmu. 

86 As a user you will only see this unit in the output of :class:`ModeProjector` objects. 

87 Masses provided via, e.g., ASE Atoms objects are converted internally. 

88 

89 **Waves:** 

90 dynasor reports and expects spatial (angular) frequencies in rad/Å and temporal (angular) 

91 frequencies in rad/fs. This follows the often-used convention in physics to include the 

92 factor of 2π in the wave vectors. For instance the wavelength is given by λ=2π/q. 

93 

94 **Mode amplitudes:** 

95 Mode amplitudes are reported in Å√dmu = fs√eV. 

96 

97 **Velocities:** 

98 For modes the momenta are reported in Å√dmu/fs or just √eV 

99 while atomic velocities are reported in Å/fs. 

100 

101 **Mode forces:** 

102 The force is defined as the derivative of the momenta with respect to time 

103 so the unit used when reporting mode forces is Å√dmu/fs² (or √eV/fs). 

104 

105 .. rubric:: Internal arrays 

106 

107 For the curious, the internal data arrays are 

108 

109 * :attr:`primitive`, :attr:`supercell`, :attr:`force_constants` (input) 

110 * :attr:`_q`, :attr:`q_minus` (reduced q-points and which q-points are related by inversion) 

111 * :attr:`_D`, :attr:`_w2`, :attr:`_W` 

112 (dynamical matrices, frequencies (ev/Ų/Da), polarization vectors) 

113 * :attr:`_X` (eigenmodes which are mass weighted "polarization vectors" in the supercell) 

114 

115 Parameters 

116 ---------- 

117 primitive 

118 Primitive cell. Note that the masses are stored internally as 

119 Dalton in ASE but will be converted to the internal dynasor 

120 mass unit (dmu). 

121 supercell 

122 Ideal supercell corresponding to the force constants. 

123 force_constants 

124 Force constants for the supercell in eV/Ų as a `(N, N, 3, 3)` array 

125 where `N` is `len(supercell)`. They are assumed to be in units of eV/Ų 

126 as returned from phonopy; be careful about the permutations when working 

127 with force constants and atoms objects from different codes. 

128 """ 

129 def __init__(self, primitive: Atoms, supercell: Atoms, force_constants: NDArray[float]): 

130 if len(primitive) == len(supercell): 

131 warnings.warn('Primitive and supercell have the same size') 

132 elif len(primitive) > len(supercell): 

133 raise ValueError('Primitive cell larger than supercell') 

134 elif not (len(supercell) / len(primitive)).is_integer(): 

135 raise ValueError('supercell size is not multiple of primitive size') 

136 

137 if len(supercell) != len(force_constants): 

138 raise ValueError('force constants shape is not compatible with supercell size') 

139 

140 if force_constants.shape != (len(supercell), len(supercell), 3, 3): 

141 raise ValueError('force constants shape should be (N, N, 3, 3)') 

142 

143 self.primitive = Prim(primitive) 

144 self.supercell = Supercell(supercell, primitive) 

145 self.force_constants = force_constants 

146 

147 # q-points commensurate with the supercell, and their -q partners 

148 self._q = self.supercell.lattice.q_reduced.astype(float) 

149 self._q_minus = self.supercell.lattice.q_minus 

150 

151 # Construct dynamical matrix and diagonalize at each q-point 

152 self._D, self._w2, self._W = [], [], [] 

153 for qi, q in enumerate(self._q): 

154 

155 D = get_dynamical_matrix( 

156 self.force_constants, self.supercell.offsets, self.supercell.indices, q) 

157 

158 if qi == self._q_minus[qi]: 

159 assert np.allclose(D.imag, 0) 

160 D = D.real 

161 

162 D = np.einsum('ijab,i,j->ijab', 

163 D, self.primitive.masses**-0.5, self.primitive.masses**-0.5) 

164 D_matrix = D.transpose(0, 2, 1, 3).reshape(-1, self.primitive.n_atoms * 3) 

165 assert np.allclose(D_matrix, D_matrix.T.conj()) 

166 w2, W = np.linalg.eigh(D_matrix) 

167 W = W.T.reshape(-1, self.primitive.n_atoms, 3) 

168 

169 self._D.append(D) 

170 self._w2.append(w2) 

171 self._W.append(W) 

172 

173 self._D = np.array(self._D) 

174 self._w2 = np.array(self._w2) 

175 self._W = np.array(self._W) 

176 

177 # Post check basic symmetries, group eigenvalues and try to make degenerate modes nicer 

178 for q, q_minus in enumerate(self._q_minus): 

179 assert np.allclose(self._D[q], self._D[q_minus].conj()) 

180 assert np.allclose(self._w2[q], self._w2[q_minus]) 

181 

182 # tolerances for grouping and sorting eigenvalues and eigenvectors 

183 group_decimals = 12 

184 tolerance = 10**(-group_decimals) 

185 # Keep sorting coarser than the convergence tolerance so tiny SVD 

186 # roundoff cannot change the order of equivalent modes. 

187 sort_decimals = 10 

188 

189 for group in group_eigvals(self._w2[q], tolerance**0.5): 

190 W = symmetrize_eigenvectors(self._W[q, group]) 

191 

192 # Try to order them 

193 W_sort = W.copy().transpose(0, 2, 1).reshape(len(W), -1) 

194 # abs is because we want to consider the magnitude 

195 # - (minus) basically reverts the sort order to place largest first 

196 # T is just because how lexsort works, we want to consider each 

197 # atom and direction as a key for the bands 

198 # -1 is because we want to make the x-direction of the first 

199 # atom the most significant key 

200 # At the end the first band should have the largest magnitude 

201 # for the first atom in x 

202 # Suppress numerical noise in the mode signatures before sorting. 

203 # Keep this precision deliberately below the factor-analysis 

204 # convergence noise so tiny SVD/BLAS differences cannot permute 

205 # otherwise equivalent degenerate modes. 

206 argsort = np.lexsort(np.round(-np.abs(W_sort).T[::-1], sort_decimals)) 

207 self._W[q, group] = W[argsort] 

208 

209 self._W[q_minus] = self._W[q].conj() 

210 

211 # Construct supercell projection matrix: q_ks = X_ksna u_na. 

212 # phase and mass depend only on (q, index), so compute once and 

213 # broadcast against a gather of self._W. 

214 indices = self.supercell.indices 

215 

216 phase = np.exp(-1j * 2*np.pi * self._q @ self.supercell.offsets.T) # (n_q, n_super) 

217 mass_sqrt = self.primitive.masses[indices]**0.5 # (n_super,) 

218 # Build _X in place to avoid extra full-size temporaries (halves peak 

219 # memory). astype pins the dtype (no-op unless _W is real, e.g. Gamma). 

220 self._X = self._W[:, :, indices, :].astype(np.complex128, copy=False) 

221 np.conjugate(self._X, out=self._X) 

222 self._X *= phase[:, None, :, None] 

223 self._X *= mass_sqrt[None, None, :, None] 

224 self._X /= (self.supercell.n_atoms / self.primitive.n_atoms)**0.5 

225 

226 # Init arrays to hold Q, P and F 

227 self._Q = np.zeros((len(self._q), self.primitive.n_atoms*3), dtype=np.complex128) 

228 self._P = np.zeros_like(self._Q) 

229 self._F = np.zeros_like(self._Q) 

230 

231 def __str__(self): 

232 strings = ['### ModeProjector ###'] 

233 strings += [f'{self.supercell}'] 

234 strings += [f'{self.primitive}'] 

235 string = '\n'.join(strings) 

236 

237 # ASCII DOS! 

238 width = 80 

239 height = 24 

240 dos = np.full((height, width), ' ') 

241 

242 THz = self.omegas * radians_per_fs_to_THz 

243 

244 hist, bins = np.histogram(THz.flat, bins=width) 

245 

246 for i, h in enumerate(hist): 

247 dos[np.round(h * (height - 1) / hist.max()).astype(int), i] = '+' # '·' or 'x' 

248 

249 dos = dos[::-1] 

250 dos[-1, dos[-1] == ' '] = '-' 

251 dos = '\n'.join([''.join(d) for d in dos]) 

252 

253 string += f'\n{dos}' 

254 string += f'\n|{THz.min():<10.2f} THz' + ' '*(width - 26) + f'{THz.max():>10.2f}|' 

255 

256 return string 

257 

258 def __repr__(self): 

259 return str(self) 

260 

261 def __getitem__(self, q) -> QPoint: 

262 """Returns the q-point object based on its index""" 

263 if q < 0 or q >= len(self._q): 

264 raise IndexError 

265 return QPoint(q, self) 

266 

267 def __call__(self, qpoint) -> QPoint: 

268 """Tries to find a matching q-point based on reduced coordinate""" 

269 qpoint = np.array(qpoint).astype(np.float64) % 1 

270 for q, qpoint2 in enumerate(self._q): 

271 if np.allclose(qpoint, qpoint2): 

272 return QPoint(q, self) 

273 raise ValueError('qpoint not compatible, check mp.q_reduced') 

274 

275 # Getters ans setters for internal mutable arrays 

276 def get_Q(self) -> NDArray[complex]: 

277 """Return the mode coordinates as a ``(Nq, Nb)`` complex array in Å√dmu.""" 

278 return self._Q.copy() 

279 

280 def get_P(self) -> NDArray[complex]: 

281 """Return the mode momenta as a ``(Nq, Nb)`` complex array in √eV.""" 

282 return self._P.copy() 

283 

284 def get_F(self) -> NDArray[complex]: 

285 """Return the mode forces as a ``(Nq, Nb)`` complex array in eV/Å√dmu.""" 

286 return self._F.copy() 

287 

288 def get_F_harmonic(self) -> NDArray[complex]: 

289 r"""Return the harmonic mode forces as a ``(Nq, Nb)`` complex array in eV/Å√dmu. 

290 

291 Computed as :math:`-\omega^2 Q^*`. The conjugate follows the convention 

292 :math:`F = X^* f / m` used by :meth:`set_f`, in which :math:`F` is the force 

293 conjugate to :math:`Q`, i.e. :math:`-\partial V/\partial Q`. Note that 

294 :math:`Q` and :math:`Q^*` coincide only at self-conjugate q-points. 

295 """ 

296 return -self._w2 * self.get_Q().conj() 

297 

298 def set_Q(self, Q: NDArray[complex]) -> None: 

299 """Sets the internal mode coordinates :math:`Q`. 

300 

301 The function ensures :math:`Q(-q)=Q^*(q)`. 

302 """ 

303 # This ensures that stuff like mp.set_Q(0) works while not updating the 

304 # array until the assert 

305 Q_new = self.get_Q() 

306 Q_new[:] = Q 

307 if not np.allclose(np.conjugate(Q_new), Q_new[self.q_minus]): 

308 raise ValueError('Supplied Q does not fulfill Q(-q) = Q(q)*') 

309 self._Q[:] = Q_new 

310 

311 def set_P(self, P: NDArray[complex]) -> None: 

312 """Sets the internal mode momenta :math:`P`. 

313 

314 The function ensures :math:`P(-q)=P^*(q)`. 

315 """ 

316 P_new = self.get_P() 

317 P_new[:] = P 

318 if not np.allclose(np.conjugate(P_new), P_new[self.q_minus]): 

319 raise ValueError('Supplied P does not fulfill P(-q) = P(q)*') 

320 self._P[:] = P_new 

321 

322 def set_F(self, F: NDArray[complex]) -> None: 

323 """Sets the internal mode forces :math:`F`. 

324 

325 The function ensures :math:`F(-q)=F^*(q)`. 

326 """ 

327 F_new = self.get_F() 

328 F_new[:] = F 

329 if not np.allclose(np.conjugate(F_new), F_new[self.q_minus]): 

330 raise ValueError('Supplied F does not fulfill F(-q) = F(q)*') 

331 self._F[:] = F_new 

332 

333 def get_u(self) -> NDArray[float]: 

334 """Return the atomic displacements as a ``(N, 3)`` array in Å.""" 

335 u = np.einsum('ksna,ks,n->na', self._X.conj(), self._Q, 1 / self.supercell.masses) 

336 assert np.allclose(u.imag, 0) 

337 return u.real 

338 

339 def get_v(self) -> NDArray[float]: 

340 """Return the atomic velocities as a ``(N, 3)`` array in Å/fs.""" 

341 v = np.einsum('ksna,ks,n->na', self._X, self._P, 1 / self.supercell.masses) 

342 assert np.allclose(v.imag, 0) 

343 return v.real 

344 

345 def get_f(self) -> NDArray[float]: 

346 """Return the atomic forces as a ``(N, 3)`` array in eV/Å.""" 

347 f = np.einsum('ksna,ks->na', self._X, self._F) 

348 assert np.allclose(f.imag, 0) 

349 return f.real 

350 

351 def get_f_harmonic(self) -> NDArray[float]: 

352 """Return the harmonic atomic forces for the current displacements 

353 as a ``(N, 3)`` array in eV/Å. 

354 """ 

355 F_harmonic = self.get_F_harmonic() 

356 f_harmonic = np.einsum('ksna,ks->na', self._X, F_harmonic) 

357 assert np.allclose(f_harmonic.imag, 0) 

358 return f_harmonic.real 

359 

360 def set_u(self, u: NDArray[float]) -> None: 

361 """Sets the internal mode coordinates :math:`Q` given the atomic displacements :math:`u`. 

362 

363 .. math:: 

364 

365 Q = X u 

366 

367 Parameters 

368 ---------- 

369 u 

370 The atomic displacements in Å. 

371 """ 

372 Q = mode_coordinates(self._X, u) 

373 self.set_Q(Q) 

374 

375 def set_v(self, v: NDArray[float]) -> None: 

376 """Sets the internal mode momenta :math:`P` given the atomic velocities :math:`v`. 

377 

378 .. math:: 

379 

380 P = X^* * v 

381 

382 Parameters 

383 ---------- 

384 v 

385 The atomic velocities in Å/fs. 

386 """ 

387 P = mode_momenta(self._X, v) 

388 self.set_P(P) 

389 

390 def set_f(self, f: NDArray[float]) -> None: 

391 """Sets the internal mode forces :math:`F` given the atomic forces :math:`f`. 

392 

393 .. math:: 

394 

395 F = X^* * f / m 

396 

397 Parameters 

398 ---------- 

399 f 

400 The atomic forces in eV/Å. 

401 """ 

402 F = mode_forces(self._X, f, self.supercell.masses) 

403 self.set_F(F) 

404 

405 # Convenience functions to handle ASE Atoms objects 

406 def get_atoms(self, harmonic_forces: Optional[bool] = False) -> Atoms: 

407 r"""Returns ASE :class:`~ase.Atoms` object with displacement, 

408 velocities, forces, and harmonic energies. 

409 

410 Parameters 

411 ---------- 

412 harmonic_forces 

413 Whether the forces should be taken from the internal `F` or via `-\omega^2 Q`. 

414 """ 

415 atoms = self.supercell.to_ase() 

416 atoms.positions += self.get_u() 

417 atoms.set_velocities(self.get_v() / fs) 

418 E = self.potential_energies.sum() 

419 f = self.get_f_harmonic() if harmonic_forces else self.get_f() 

420 

421 atoms.calc = SinglePointCalculator( 

422 energy=E, forces=f, stress=None, magmoms=None, atoms=atoms) 

423 

424 return atoms 

425 

426 def update_from_atoms(self, atoms: Atoms) -> None: 

427 """Updates the :class:`ModeProjector` objects with displacements, velocities, 

428 and forces from an ASE :class:`~ase.Atoms` object. 

429 

430 Checks for an attached calculator in the first place and next for a forces array. 

431 

432 If no data sets corresponding array to zeros. 

433 

434 The velocities are converted to dynasor units internally. Note that 

435 :attr:`atoms`'s masses are not used; masses are fixed from the 

436 ``primitive``/``supercell`` structures given at construction, since the 

437 dynamical matrix and mode eigenvectors already depend on them. 

438 """ 

439 

440 u = get_displacements(atoms, self.supercell) 

441 if np.max(np.abs(u)) > 2.0: 

442 warnings.warn('Displacements larger than 2Å. Is the atoms object permuted?') 

443 self.set_u(u) 

444 self.set_v(atoms.get_velocities() * fs) 

445 try: 

446 self.set_f(atoms.get_forces()) 

447 except RuntimeError: 

448 if 'forces' in atoms.arrays: 

449 self.set_f(atoms.arrays['forces']) 

450 else: 

451 self.set_f(np.zeros_like(atoms.positions)) 

452 

453 # properties 

454 @property 

455 def lattice(self) -> Lattice: 

456 """The lattice relating the primitive cell and the supercell. 

457 

458 Gives access to the exact q-points, the `P`-matrix and 

459 :meth:`~dynasor.qpoints.Lattice.make_path`. 

460 """ 

461 return self.supercell.lattice 

462 

463 @property 

464 def q_minus(self) -> NDArray[int]: 

465 """The index of the corresponding counter-propagating mode (:math:`-q`).""" 

466 return self._q_minus.copy() 

467 

468 @property 

469 def q_reduced(self) -> NDArray[float]: 

470 """The q-points in reduced coordinates. 

471 

472 For example a zone boundary mode would be (1/2, 0, 0). 

473 The same points as exact fractions are available via :attr:`lattice`. 

474 """ 

475 return self._q.copy() 

476 

477 @property 

478 def q_cartesian(self) -> NDArray[float]: 

479 """The q-points in cartesian coordinates with unit of rad/Å (2π included).""" 

480 return self.supercell.lattice.q_cartesian 

481 

482 @property 

483 def omegas(self) -> NDArray[float]: 

484 """The frequencies of each mode in rad/fs. 

485 

486 Following convention, negative values indicate imaginary frequencies. 

487 """ 

488 return np.sign(self._w2) * np.sqrt(np.abs(self._w2)) 

489 

490 @property 

491 def polarizations(self) -> NDArray[float]: 

492 """The polarization vectors for each mode `(Nq, Nb, Np, 3)`.""" 

493 return self._W 

494 

495 @property 

496 def eigenmodes(self) -> NDArray[float]: 

497 """The eigenmodes in the supercell as `(Nq, Nb, N, 3)`-array 

498 

499 The eigenmodes include the masses such that :math:`Q = X u` 

500 where :math:`u` are the supercell displacements. 

501 """ 

502 return self._X 

503 

504 @property 

505 def potential_energies(self) -> NDArray[float]: 

506 r"""Potential energy per mode as `(Nq, Nb)`-array. 

507 

508 The potential energies are defined as :math:`1/2 \omega^2 Q Q^*` and should equal 

509 :math:`1/2 k_B T` in equilibrium for a harmonic system. 

510 """ 

511 return 1 / 2 * np.abs(self._Q) ** 2 * self._w2 

512 

513 @property 

514 def kinetic_energies(self) -> NDArray[float]: 

515 """Kinetic energy per mode as `(Nq, Nb)`-array. 

516 

517 The kinetic energies are defined as :math:`1/2 P P^*`. Should equal 

518 :math:`1/2 k_B T` in equilibrium. 

519 """ 

520 return 1 / 2 * np.abs(self._P)**2 

521 

522 @property 

523 def virial_energies(self) -> NDArray[complex]: 

524 r"""The virial energies per mode as `(Nq, Nb)`-array. 

525 

526 The virial energies are defined here as :math:`-1/2 Q F`, which should have an 

527 expectation value of :math:`1/2 k_B T` per mode in equilibrium. For a harmonic 

528 system this is simply equal to the potential energy. This means that 

529 the virial energy can be used to monitor the anharmonicity or 

530 define a measure of the potential energy. 

531 

532 Note that while :math:`Q F` is in general complex the virial energy 

533 obeys :math:`E(-\boldsymbol{q}) = E^*(\boldsymbol{q})`, meaning the 

534 imaginary parts cancel between :math:`\boldsymbol{q}` and 

535 :math:`-\boldsymbol{q}` and the total is real. Take the real part to 

536 obtain per-mode energies; this leaves the sum unchanged. 

537 """ 

538 return -1 / 2 * self._Q * self._F 

539 

540 def write(self, file_name: str) -> None: 

541 """Uses pickle to write mode projector to file.""" 

542 with open(file_name, 'wb') as f: 

543 pickle.dump(self, f) 

544 

545 @classmethod 

546 def read(cls, file_name: str) -> ModeProjector: 

547 """Return :class:`ModeProjector` instance from pickle file 

548 that was saved using :func:`~ModeProjector.write`. 

549 

550 Pickles written by dynasor 2.4 or earlier are not supported. 

551 """ 

552 with open(file_name, 'rb') as f: 

553 mp = pickle.load(f) 

554 return mp