Coverage for ase/phonons.py: 95.27%
317 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"""Module for calculating phonons of periodic systems."""
3import warnings
4from math import pi, sqrt
5from pathlib import Path
7import numpy as np
8import numpy.fft as fft
9import numpy.linalg as la
11from ase import Atoms, units
12from ase.dft import monkhorst_pack
13from ase.io.trajectory import Trajectory
14from ase.parallel import world
15from ase.utils import deprecated
16from ase.utils.filecache import MultiFileJSONCache
19class Displacement:
20 """Abstract base class for phonon and el-ph supercell calculations.
22 Both phonons and the electron-phonon interaction in periodic systems can be
23 calculated with the so-called finite-displacement method where the
24 derivatives of the total energy and effective potential are obtained from
25 finite-difference approximations, i.e. by displacing the atoms. This class
26 provides the required functionality for carrying out the calculations for
27 the different displacements in its ``run`` member function.
29 Derived classes must overwrite the ``__call__`` member function which is
30 called for each atomic displacement.
32 """
34 def __init__(
35 self,
36 atoms: Atoms,
37 calc,
38 supercell: tuple[int, int, int],
39 select_atoms: list[str] | list[int] | None,
40 name: str,
41 delta: float,
42 center_refcell: bool,
43 comm,
44 ):
45 # Store atoms and calculator
46 self.atoms = atoms
47 self.natoms = len(atoms)
48 self.calc = calc
50 # Specify indices of which atoms to vibrate
51 self.set_atoms(select_atoms, _warn=False)
53 self.name = name
54 self.delta = delta
56 assert len(supercell) == 3
57 self.supercell = supercell
58 self.ncells = np.prod(supercell)
59 if not center_refcell:
60 self.refcell_offset = 0
61 else:
62 self.refcell_offset = (
63 supercell[0] // 2 * (supercell[1] * supercell[2])
64 + supercell[1] // 2 * supercell[2]
65 + supercell[2] // 2
66 )
68 self.lattice_vectors_array = self.get_lattice_vectors()
70 if comm is None:
71 comm = world
72 self.comm = comm
74 self.cache = MultiFileJSONCache(self.name, comm=comm)
76 @deprecated('Please use get_lattice_vectors() instead')
77 def compute_lattice_vectors(self):
78 """Deprecated version of get_lattice_vectors,
79 can safely be removed by summer 2027"""
80 return self.get_lattice_vectors().T
82 def get_lattice_vectors(self):
83 """Return lattice vectors for cells in the supercell.
85 These are the integer indices of each cell within the supercell.
86 The ordering is as illustrated in Phonons class docstring"""
88 # First, lattice vectors relevative to the corner unit cell
89 R_Nc = np.indices(self.supercell).reshape(3, self.ncells).T
91 N_c = np.array(self.supercell)
92 if self.refcell_offset == 0:
93 R_Nc += N_c // 2
94 R_Nc %= N_c
95 R_Nc -= N_c // 2
97 return R_Nc
99 def __call__(self, *args, **kwargs):
100 """Member function called in the ``run`` function."""
102 raise NotImplementedError('Implement in derived classes!.')
104 def set_atoms(
105 self, select_atoms: list[str] | list[int] | None, _warn: bool = True
106 ):
107 """Specify which atoms to vibrate.
109 Parameters
110 ----------
111 select_atoms:
112 List of atomic indices or atomic types.
113 If None, all atoms are set to vibrate.
115 """
117 if _warn:
118 warnings.warn(
119 'Please specify which atoms to vibrate using the select_atoms '
120 'keyword during initialization instead of using '
121 'Displacements.set_atoms(...)',
122 FutureWarning,
123 )
124 # This method can safely be moved inside the __init__ and deleted
125 # roughly by summer 2027.
127 atoms = self.atoms
129 match select_atoms:
130 case None:
131 self.nindices = len(atoms)
132 self.indices = np.arange(self.nindices)
133 case [*atomlist]:
134 indices: list[int]
135 assert len(atomlist) == len(set(atomlist))
136 assert len(atomlist) <= len(atoms)
137 assert all(type(atom) is type(atomlist[0]) for atom in atomlist)
138 if isinstance(atomlist[0], str):
139 indices = atoms.symbols.search(atomlist)
140 elif isinstance(atomlist[0], int):
141 indices = atomlist
142 self.indices = np.array(indices)
143 self.nindices = len(indices)
144 case _:
145 raise TypeError(
146 'Bad input type for keyword "select_atoms"; '
147 'should be either list[str] or list[int]!'
148 )
150 def _eq_disp(self):
151 return self._disp(0, 0, 0)
153 def _disp(self, a, i: int, step):
154 from ase.vibrations.vibrations import Displacement as VDisplacement
156 return VDisplacement(a, i, np.sign(step), abs(step), self)
158 def run(self):
159 """Run the calculations for the required displacements.
161 This will do a calculation for 6 displacements per atom, +-x, +-y, and
162 +-z. Only those calculations that are not already done will be
163 started. Be aware that an interrupted calculation may produce an empty
164 file (ending with .json), which must be deleted before restarting the
165 job. Otherwise the calculation for that displacement will not be done.
167 """
169 # Atoms in the supercell -- repeated in the lattice vector directions
170 # beginning with the last
171 atoms_N = self.atoms * self.supercell
173 # Set calculator if provided
174 assert self.calc is not None, 'Provide calculator in __init__ method'
175 atoms_N.calc = self.calc
177 # Do calculation on equilibrium structure
178 eq_disp = self._eq_disp()
179 with self.cache.lock(eq_disp.name) as handle:
180 if handle is not None:
181 output = self.calculate(atoms_N, eq_disp)
182 handle.save(output)
184 # Positions of atoms to be displaced in the reference cell
185 natoms = len(self.atoms)
186 offset = natoms * self.refcell_offset
187 pos_av = atoms_N.positions[offset : offset + natoms].copy()
189 # Loop over all displacements
190 for a in self.indices:
191 for i in range(3):
192 for sign in [-1, 1]:
193 disp = self._disp(a, i, sign)
194 with self.cache.lock(disp.name) as handle:
195 if handle is None:
196 continue
197 try:
198 atoms_N.positions[offset + a, i] = (
199 pos_av[a, i] + sign * self.delta
200 )
202 result = self.calculate(atoms_N, disp)
203 handle.save(result)
204 finally:
205 # Return to initial positions
206 atoms_N.positions[offset + a, i] = pos_av[a, i]
208 self.comm.barrier()
210 def clean(self):
211 """Delete generated files."""
212 if self.comm.rank == 0:
213 nfiles = self._clean()
214 else:
215 nfiles = 0
216 self.comm.barrier()
217 return nfiles
219 def _clean(self):
220 name = Path(self.name)
222 nfiles = 0
223 if name.is_dir():
224 for fname in name.iterdir():
225 fname.unlink()
226 nfiles += 1
227 name.rmdir()
228 return nfiles
231class Phonons(Displacement):
232 r"""Class for calculating phonon modes using the finite displacement method.
234 The matrix of force constants is calculated from the finite difference
235 approximation to the first-order derivative of the atomic forces as::
237 2 nbj nbj
238 nbj d E F- - F+
239 C = ------------ ~ ------------- ,
240 mai dR dR 2 * delta
241 mai nbj
243 where F+/F- denotes the force in direction j on atom nb when atom ma is
244 displaced in direction +i/-i. The force constants are related by various
245 symmetry relations. From the definition of the force constants it must
246 be symmetric in the three indices mai::
248 nbj mai bj ai
249 C = C -> C (R ) = C (-R ) .
250 mai nbj ai n bj n
252 As the force constants can only depend on the difference between the m and
253 n indices, this symmetry is more conveniently expressed as shown on the
254 right hand-side.
256 The acoustic sum-rule::
258 _ _
259 aj \ bj
260 C (R ) = - ) C (R )
261 ai 0 /__ ai m
262 (m, b)
263 !=
264 (0, a)
266 Ordering of the unit cells illustrated here for a 1-dimensional system (in
267 case ``center_refcell=False`` in constructor!):
269 ::
271 m = 0 m = 1 m = -2 m = -1
272 -----------------------------------------------------
273 | | | | |
274 | * b | * | * | * |
275 | | | | |
276 | * a | * | * | * |
277 | | | | |
278 -----------------------------------------------------
280 Examples
281 --------
282 >>> from ase.build import bulk
283 >>> from ase.phonons import Phonons
284 >>> from ase.calculators.emt import EMT
286 >>> atoms = bulk('Al', 'fcc', a=4.05)
287 >>> calc = EMT()
288 >>> ph = Phonons(
289 ... atoms,
290 ... calc,
291 ... supercell=(5, 5, 5),
292 ... delta=0.05,
293 ... use_mean_minimum_images=True
294 ... )
295 >>> ph.run()
296 >>> ph.read()
297 >>> path = atoms.cell.bandpath('GXULGK', npoints=100)
298 >>> bs = ph.get_band_structure(path, verbose=False)
299 >>> dos = ph.get_dos(kpts=(12, 12, 12)).sample_grid(npts=100, width=1e-3)
301 """
303 def __init__(
304 self,
305 atoms: Atoms,
306 calc=None,
307 supercell: tuple[int, int, int] = (1, 1, 1),
308 select_atoms: list[int] | list[str] | None = None,
309 name: str = 'phonon',
310 delta: float = 0.01,
311 center_refcell: bool = False,
312 use_mean_minimum_images: bool | None = None,
313 minimum_image_tol: float = 1e-5,
314 comm=None,
315 ):
316 """Init with an instance of :class:`~ase.Atoms` and a calculator.
318 Parameters
319 ----------
320 atoms:
321 The atoms to work on.
322 calc:
323 Calculator for the supercell calculation.
324 supercell:
325 Size of supercell given by the number of repetitions (n1, n2, n3) of
326 the small unit cell in each direction.
327 select_atoms:
328 Select which atoms to generate displacements for.
329 By default, displacements are generated for all atoms.
330 name:
331 Base name to use for files.
332 delta:
333 Magnitude of displacement in Ang.
334 center_refcell:
335 Reference cell in which the atoms will be displaced. If False, then
336 corner cell in supercell is used. If True, then cell in the center
337 of the supercell is used.
338 use_mean_minimum_images:
339 Use averaged phase factor of all the shortest atom-to-atom image
340 vectors. This will be the default in the future and is strongly
341 recommended as it requires smaller supercells to converge
342 the phonon energies.
343 minimum_image_tol:
344 Tolerance (in Å) for finding equivalent atoms when using
345 mean minimum image phase factors.
346 comm:
347 MPI communicator for the phonon calculation.
348 Default is to use world.
349 """
351 super().__init__(
352 atoms=atoms,
353 calc=calc,
354 supercell=supercell,
355 select_atoms=select_atoms,
356 name=name,
357 delta=delta,
358 center_refcell=center_refcell,
359 comm=comm,
360 )
362 if use_mean_minimum_images is None:
363 warnings.warn(
364 'The "use_mean_minimum_images" parameter is new to the '
365 'Phonons class and in the future it will be True by default. '
366 'For now, it will be set to False to ensure consistency with '
367 'previous behaviour. Please explicitly set the '
368 '"use_mean_minimum_images" keyword to True / False '
369 'to ensure consistent behaviour with future versions.',
370 FutureWarning,
371 )
372 use_mean_minimum_images = False
374 self.use_mean_minimum_images = use_mean_minimum_images
375 self.atom2atom_vectors = self._get_atom2atom_vectors(minimum_image_tol)
377 self.C_avNav: np.ndarray | None = None # in units of eV / Ang**2
379 def __call__(self, atoms_N: Atoms):
380 """Calculate forces on atoms in supercell."""
381 return atoms_N.get_forces()
383 def calculate(self, atoms_N: Atoms, disp) -> dict[str, np.ndarray]:
384 forces = self(atoms_N)
385 return {'forces': forces}
387 def check_eq_forces(self):
388 """Check maximum size of forces in the equilibrium structure."""
390 eq_disp = self._eq_disp()
391 feq_av = self.cache[eq_disp.name]['forces']
393 fmin = feq_av.min()
394 fmax = feq_av.max()
395 i_min = np.where(feq_av == fmin)
396 i_max = np.where(feq_av == fmax)
398 return fmin, fmax, i_min, i_max
400 def _get_atom2atom_vectors(self, minimum_image_tol: float) -> np.ndarray:
401 """Calculate all atom-to-atom vectors, i.e. all vectors that go from
402 atom a1 in the reference unit cell to atom a2 in cell N in the
403 supercell.
405 If the phonons class was initialized with use_mean_minimum_images=True,
406 all the shortest atom-to-atom vectors are calculated by also checking
407 the periodic images of atom2 in cell N. Furthermore, the keyword
408 minimum_image_tol can be supplied to the Phonons class which controls
409 the tolerance when detecting minimum image vectors.
410 """
412 R_Nc = self.lattice_vectors_array
413 relpos_ac = self.atoms.get_scaled_positions(wrap=True)[self.indices]
414 vectors_aNac = (
415 relpos_ac[np.newaxis, np.newaxis]
416 + R_Nc[np.newaxis, :, np.newaxis]
417 - relpos_ac[:, np.newaxis, np.newaxis]
418 )
420 if not self.use_mean_minimum_images:
421 return vectors_aNac
423 supercellshifts_Sc = (
424 np.indices((3, 3, 3)).reshape(3, -1).T - 1
425 ) * self.supercell
426 bools_L = np.logical_or(supercellshifts_Sc == 0, self.atoms.pbc).all(
427 axis=1
428 )
429 supercellshifts_Sc = supercellshifts_Sc[bools_L]
430 cell_cv = self.atoms.cell.array
432 vectors_aNaSc = np.empty(vectors_aNac.shape[0:3], dtype=object)
434 for a1, vectors_Nac in enumerate(vectors_aNac):
435 for N, vectors_ac in enumerate(vectors_Nac):
436 for a2, vector_c in enumerate(vectors_ac):
437 images_Sc = vector_c + supercellshifts_Sc
438 lengths_S = np.linalg.norm(images_Sc @ cell_cv, axis=1)
439 bools_S = np.isclose(
440 lengths_S,
441 lengths_S.min(),
442 rtol=0.0,
443 atol=minimum_image_tol,
444 )
445 vectors_aNaSc[a1, N, a2] = images_Sc[bools_S]
447 return vectors_aNaSc
449 @deprecated(
450 'Implementation of non-analytical correction has remained untested '
451 'for many years and was likely incorrect, see '
452 'https://gitlab.com/ase/ase/-/work_items/941 '
453 )
454 def read_born_charges(self, name='born', neutrality=True):
455 r"""Read Born charges and dieletric tensor from JSON file.
457 The charge neutrality sum-rule::
459 _ _
460 \ a
461 ) Z = 0
462 /__ ij
463 a
465 .. deprecated:: 3.22.1
466 Current implementation of non-analytical correction is likely
467 incorrect, see :issue:`941`
469 Parameters
470 ----------
472 neutrality: bool
473 Restore charge neutrality condition on calculated Born effective
474 charges.
475 name: str
476 Key used to identify the file with Born charges for the unit cell
477 in the JSON cache.
478 """
480 # Load file with Born charges and dielectric tensor for atoms in the
481 # unit cell
482 Z_avv, eps_vv = self.cache[name]
484 # Neutrality sum-rule
485 if neutrality:
486 Z_mean = Z_avv.sum(0) / len(Z_avv)
487 Z_avv -= Z_mean
489 self.Z_avv = Z_avv[self.indices]
490 self.eps_vv = eps_vv
492 def read(
493 self,
494 method: str = 'Frederiksen',
495 symmetrize: int = 3,
496 acoustic: bool = True,
497 cutoff: float | None = None,
498 ):
499 """Read forces from json files and calculate force constants.
501 Parameters
502 ----------
503 method:
504 Specify method for evaluating the atomic forces,
505 method='Frederiksen' imposes momentum conservation.
506 symmetrize:
507 Symmetrize force constants (see doc string at top) when
508 ``symmetrize != 0`` (default: 3). Since restoring the acoustic sum
509 rule breaks the symmetry, the symmetrization must be repeated a few
510 times until the changes a insignificant. The integer gives the
511 number of iterations that will be carried out.
512 acoustic:
513 Restore the acoustic sum rule on the force constants.
514 cutoff:
515 Zero elements in the dynamical matrix between atoms with an
516 interatomic distance larger than the cutoff.
517 """
519 method = method.lower()
520 assert method in ['standard', 'frederiksen']
521 if cutoff is not None:
522 cutoff = float(cutoff)
524 cache = self.cache
525 natoms = self.natoms
526 nindices = self.nindices
527 ncells = self.ncells
528 refcell_offset = self.refcell_offset
529 # Matrix of force constants in units eV / Ang**2 with five
530 # indices (a1, v1) and (N, a2, v2), i.e. these constants
531 # couple the harmonic motion of atom a1 in the reference
532 # unit cell moving along Cartesian direction v1 with the
533 # force on atom a2 in unit cell N pointing along direction v2.
534 C_avNav = np.empty((nindices, 3, ncells, nindices, 3), dtype=float)
536 # Loop over all atomic displacements and calculate force constants
537 for a, C_vNav in zip(self.indices, C_avNav):
538 for v, C_Nav in zip('xyz', C_vNav):
539 # Atomic forces for a displacement of atom a in direction v
540 # basename = '%s.%d%s' % (self.name, a, v)
541 basename = f'{a}{v}'
542 C_raw_Nav = (
543 cache[basename + '-']['forces']
544 - cache[basename + '+']['forces']
545 ).reshape(ncells, natoms, 3)
546 C_raw_Nav /= 2 * self.delta
548 if method == 'frederiksen':
549 C_raw_Nav[refcell_offset, a] -= C_raw_Nav.sum((0, 1))
551 # Slice out included atoms
552 C_Nav[:] = C_raw_Nav[:, self.indices]
554 # Apply cutoff before symmetry and acoustic sum rule are imposed
555 if cutoff is not None:
556 self.apply_cutoff(C_avNav, cutoff)
558 # Symmetrize force constants
559 if symmetrize:
560 for _ in range(symmetrize):
561 # Symmetrize
562 C_avNav = self.symmetrize(C_avNav)
563 # Restore acoustic sum-rule
564 if acoustic:
565 self.acoustic(C_avNav)
566 else:
567 break
569 # Store force constants
570 self.C_avNav = C_avNav
572 def symmetrize(self, C_avNav: np.ndarray) -> np.ndarray:
573 """Symmetrize force constant matrix."""
575 supercell = self.supercell
576 nindices = self.nindices
577 ncells = self.ncells
579 C_Navav = np.moveaxis(C_avNav, (0, 1, 2), (1, 2, 0))
581 # Reshape force constants to (n, n, n) cell indices
582 C_nnnXX = C_Navav.reshape(supercell + (3 * nindices, 3 * nindices))
584 # Shift reference cell to center index (if it isn't already)
585 if self.refcell_offset == 0:
586 C_nnnXX = fft.fftshift(C_nnnXX, axes=(0, 1, 2)).copy()
587 # Make force constants symmetric in indices -- in case of an even
588 # number of unit cells don't include the first cell
589 n1, n2, n3 = 1 - np.asarray(supercell) % 2
590 C_nnnXX[n1:, n2:, n3:] *= 0.5
591 C_nnnXX[n1:, n2:, n3:] += (
592 (C_nnnXX[n1:, n2:, n3:][::-1, ::-1, ::-1])
593 .transpose(0, 1, 2, 4, 3)
594 .copy()
595 )
596 if self.refcell_offset == 0:
597 C_nnnXX = fft.ifftshift(C_nnnXX, axes=(0, 1, 2)).copy()
599 # Change to single unit cell index shape
600 C_Navav = C_nnnXX.reshape((ncells, nindices, 3, nindices, 3))
602 return np.moveaxis(C_Navav, (0, 1, 2), (2, 0, 1))
604 def acoustic(self, C_avNav: np.ndarray) -> None:
605 """Restore acoustic sumrule on force constants."""
606 # There may be better performing methods for
607 # restoring the acoustic sum rule
609 for a, C_vNav in enumerate(C_avNav):
610 for C_Nav in C_vNav:
611 C_Nav[self.refcell_offset, a] -= C_Nav.sum(axis=(0, 1))
613 def apply_cutoff(self, C_avNav: np.ndarray, r_c: float) -> None:
614 """Zero elements for interatomic distances larger than the cutoff.
616 Parameters
617 ----------
618 C_avNav: ndarray
619 Matrix of force constants.
620 r_c: float
621 Cutoff radius in Ångstrom.
622 """
624 R_Nc = self.lattice_vectors_array
625 cell_cv = self.atoms.cell
626 R_Nv = R_Nc @ cell_cv
627 pos_av = self.atoms.get_positions()[self.indices]
629 # Maybe calculate mean minimum image vector here instead..
630 vectors_aNav = (
631 pos_av[np.newaxis, np.newaxis]
632 + R_Nv[np.newaxis, :, np.newaxis]
633 - pos_av[:, np.newaxis, np.newaxis]
634 )
636 dist_aNa = np.linalg.norm(vectors_aNav, axis=-1)
637 bools_aNa = dist_aNa <= r_c
639 C_avNav *= bools_aNa[:, np.newaxis, :, :, np.newaxis]
641 @deprecated('Please use get_force_constants() instead')
642 def get_force_constant(self) -> np.ndarray:
643 """Deprecated version of get_force_constants,
644 can safely be removed by summer 2027
646 .. note::
647 Please use get_force_constants().
649 """
651 C_avNav = self.get_force_constants()
652 C_Navav = np.moveaxis(C_avNav, (0, 1, 2), (1, 2, 0))
653 return C_Navav.reshape(
654 (C_Navav.shape[0],) + (3 * self.nindices, 3 * self.nindices)
655 )
657 def get_force_constants(self) -> np.ndarray:
658 """Return matrix of force constants."""
660 assert self.C_avNav is not None
661 return self.C_avNav
663 def get_band_structure(
664 self,
665 path,
666 modes: bool = False,
667 verbose: bool = True,
668 ):
669 r"""Calculate and return the phonon band structure.
671 This method computes the phonon band structure for a given path
672 in reciprocal space. It is a wrapper around the internal
673 :meth:`~Phonons.band_structure` method of the :class:`Phonons` class.
674 The method can optionally calculate and return phonon modes.
676 Frequencies and modes are in units of eV and
677 :math:`1/\sqrt{\mathrm{amu}}`, respectively.
679 Parameters
680 ----------
681 path : BandPath object
682 The BandPath object defining the path in the reciprocal
683 space over which the phonon band structure is calculated.
684 modes : bool, optional
685 If True, phonon modes will also be calculated and returned.
686 Defaults to False.
687 verbose : bool, optional
688 If True, enables verbose output during the calculation.
689 Defaults to True.
691 Returns
692 -------
693 BandStructure or tuple of (BandStructure, ndarray)
694 If ``modes`` is False, returns a ``BandStructure`` object
695 containing the phonon band structure. If ``modes`` is True,
696 returns a tuple, where the first element is the
697 ``BandStructure`` object and the second element is an ndarray
698 of phonon modes.
700 If modes are returned, the array is of shape
701 (k-point, bands, atoms, 3) and the norm-squared of the mode
702 is `1 / m_{eff}`, where `m_{eff}` is the effective mass of the
703 mode.
705 """
706 result = self.band_structure(path.kpts, modes=modes, verbose=verbose)
707 if modes:
708 omega_kl, omega_modes = result
709 else:
710 omega_kl = result
712 from ase.spectrum.band_structure import BandStructure
714 bs = BandStructure(path, energies=omega_kl[None])
716 # Return based on the modes flag
717 return (bs, omega_modes) if modes else bs
719 @deprecated('Please use calculate_dynamical_matrix() instead')
720 def compute_dynamical_matrix(
721 self, q_scaled: np.ndarray, D_N: np.ndarray
722 ) -> np.ndarray:
723 """Computation of the dynamical matrix in momentum space D_ab(q).
724 This is a Fourier transform from real-space dynamical matrix D_N
725 for a given momentum vector q.
727 .. note::
728 Deprecated. Please use calculate_dynamical_matrix().
730 Parameters
731 ----------
732 q_scaled : np.ndarray
733 q vector in scaled coordinates.
734 D_N : np.ndarray
735 Dynamical matrix in real-space.
737 Returns
738 -------
739 D_q : np.ndarray
740 2D complex-valued array D(q) with shape=(3 * natoms, 3 * natoms).
742 """
744 # Evaluate fourier sum
745 R_cN = self.compute_lattice_vectors()
746 phase_N = np.exp(-2.0j * pi * np.dot(q_scaled, R_cN))
747 D_q = np.sum(phase_N[:, np.newaxis, np.newaxis] * D_N, axis=0)
748 return D_q
750 def calculate_dynamical_matrix(
751 self, q_c: np.ndarray, D_avNav: np.ndarray
752 ) -> np.ndarray:
753 """Computation of the dynamical matrix in momentum space D_XX(q).
754 This is a Fourier transform from real-space force constants
755 for a given momentum vector q.
757 If the phonons class was initialized with use_mean_minimum_images=True,
758 the q-dependent phase factor for a given set of atoms a1 and (N, a2) is
759 averaged over all the shortest atom-to-atom vectors from atom1 to a
760 periodic image of atom (N, a2).
762 Parameters
763 ----------
764 q_c:
765 Phonon wave vector in scaled coordinates.
766 D_avNav:
767 Force constant matrix scaled by atom masses.
769 Returns
770 -------
771 D_XX: np.ndarray
772 Dynamical matrix, a complex-valued array D(q)
773 with shape=(3 * natoms, 3 * natoms).
774 """
776 if not self.use_mean_minimum_images:
777 atom2atom_aNac = self.atom2atom_vectors
778 phase_aNa = np.exp(2.0j * np.pi * np.dot(atom2atom_aNac, q_c))
779 else:
780 atom2atom_aNaSc = self.atom2atom_vectors
781 # In this case, atom2atom is an ndarray with 3 indexes of ndarrays
782 # with 2 indexes so some code might look unintuitive
783 phase_aNa = np.zeros(atom2atom_aNaSc.shape, dtype=complex)
784 for (a1, N, a2), atom2atom_Sc in np.ndenumerate(atom2atom_aNaSc):
785 phase_aNa[a1, N, a2] = np.exp(
786 2.0j * np.pi * np.dot(atom2atom_Sc, q_c)
787 ).mean()
789 D_avav = np.einsum('avNbw,aNb->avbw', D_avNav, phase_aNa)
791 return D_avav.reshape(3 * self.nindices, 3 * self.nindices)
793 def band_structure(self, path_kc, modes=False, verbose=True):
794 """Calculate phonon dispersion along a path in the Brillouin zone.
796 The dynamical matrix at arbitrary q-vectors is obtained by Fourier
797 transforming the real-space force constants. In case of negative
798 eigenvalues (squared frequency), the corresponding negative frequency
799 is returned.
801 Frequencies and modes are in units of eV and 1/sqrt(amu),
802 respectively.
804 Parameters
805 ----------
806 path_kc: ndarray
807 List of k-point coordinates (in units of the reciprocal lattice
808 vectors) specifying the path in the Brillouin zone for which the
809 dynamical matrix will be calculated.
810 modes: bool
811 Returns both frequencies and modes when True.
812 verbose: bool
813 Print warnings when imaginary frequncies are detected.
815 Returns
816 -------
817 omega_kl: np.ndarray
818 Phonon band energies.
819 u_klav: np.ndarray
820 Eigenvectors (only when ``modes`` is ``True``).
821 """
823 nindices = self.nindices
825 # Force constant matrices
826 assert self.C_avNav is not None, print(
827 'Make sure you have .read() your force constant matrices!'
828 )
829 C_avNav = self.C_avNav
831 # Multiply by mass prefactor
832 m_inv_a = self.atoms.get_masses()[self.indices] ** -0.5
833 m_inv_aa = np.outer(m_inv_a, m_inv_a)
835 D_avNav = C_avNav * m_inv_aa[:, np.newaxis, np.newaxis, :, np.newaxis]
837 # Lists for frequencies and modes along path
838 nk = path_kc.shape[0]
839 omega_kl = np.zeros((nk, 3 * nindices))
840 u_klav = np.zeros((nk, 3 * nindices, nindices, 3), dtype=complex)
842 for q_index, q_c in enumerate(path_kc):
843 # Evaluate Fourier sum
844 D_XX = self.calculate_dynamical_matrix(q_c, D_avNav)
846 if modes:
847 omega2_l, u_Xl = la.eigh(D_XX, UPLO='U')
848 # Sort eigenmodes according to eigenvalues and reshape
849 u_lav = u_Xl.T[omega2_l.argsort()].reshape(
850 3 * nindices, nindices, 3
851 )
852 # Multiply with mass prefactor. This gives the eigenmode
853 # (which is now not normalized!) in units of 1/sqrt(amu).
854 u_klav[q_index] = u_lav * m_inv_a[np.newaxis, :, np.newaxis]
855 else:
856 omega2_l = la.eigvalsh(D_XX, UPLO='U')
858 # Sort eigenvalues in increasing order
859 omega2_l.sort()
860 # Use dtype=complex to handle negative eigenvalues
861 omega_l = np.sqrt(omega2_l.astype(complex))
863 # Take care of imaginary frequencies
864 if not np.all(omega2_l >= 0.0):
865 complex_indices = np.where(omega2_l < 0)[0]
867 if verbose:
868 print(
869 'WARNING, %i imaginary frequencies at '
870 'q = (% 5.2f, % 5.2f, % 5.2f) ; (omega_q =% 5.3e*i)'
871 % (
872 len(complex_indices),
873 q_c[0],
874 q_c[1],
875 q_c[2],
876 omega_l[complex_indices][0].imag,
877 )
878 )
880 omega_l[complex_indices] = -1 * np.sqrt(
881 np.abs(omega2_l[complex_indices].real)
882 )
884 omega_kl[q_index] = omega_l.real
886 # Conversion factor: sqrt(eV / Ang^2 / amu) -> eV
887 omega_kl *= units._hbar * 1e10 / sqrt(units._e * units._amu)
889 if modes:
890 return omega_kl, u_klav
891 return omega_kl
893 def get_dos(
894 self,
895 kpts: tuple[int, int, int] = (10, 10, 10),
896 indices: list | None = None,
897 verbose: bool = True,
898 ):
899 """Return a phonon density of states.
901 Parameters
902 ----------
903 kpts: tuple
904 Shape of Monkhorst-Pack grid for sampling the Brillouin zone.
905 indices: list
906 If indices is not None, the amplitude-weighted atomic-partial
907 DOS for the specified atoms will be calculated.
908 verbose: bool
909 Print warnings when imaginary frequncies are detected.
911 Returns
912 -------
913 RawDOSData
914 Density of states.
916 """
917 from ase.spectrum.dosdata import RawDOSData
919 # dos = self.dos(kpts, npts, delta, indices)
920 kpts_kc = monkhorst_pack(kpts)
921 if indices is None:
922 # Return the total DOS
923 omega_w = self.band_structure(kpts_kc, verbose=verbose)
924 assert omega_w.ndim == 2
925 n_kpt = omega_w.shape[0]
926 omega_w = omega_w.ravel()
927 dos = RawDOSData(omega_w, np.ones_like(omega_w) / n_kpt)
928 else:
929 # Return a partial DOS
930 omegas, amplitudes = self.band_structure(
931 kpts_kc, modes=True, verbose=verbose
932 )
933 # omegas.shape = (k-points, bands)
934 # amplitudes.shape = (k-points, bands, atoms, 3)
935 ampl_sq = (np.abs(amplitudes) ** 2).sum(axis=3)
936 assert ampl_sq.ndim == 3
937 assert ampl_sq.shape == omegas.shape + (len(self.indices),)
938 weights = ampl_sq[:, :, indices].sum(axis=2) / ampl_sq.sum(axis=2)
939 dos = RawDOSData(omegas.ravel(), weights.ravel() / omegas.shape[0])
940 return dos
942 def write_modes(
943 self,
944 q_c,
945 branches=0,
946 kT: float = units.kB * 300,
947 repeat: tuple[int, int, int] = (1, 1, 1),
948 nimages: int = 30,
949 center: bool = False,
950 ) -> None:
951 """Write modes to trajectory file.
953 .. note::
954 To exaggerate the amplitudes for better visualization, multiply
955 kT by the square of the desired factor.
957 Parameters
958 ----------
959 q_c: ndarray of shape (3,)
960 q-vector of the modes.
961 branches: int or list
962 Branch index of modes.
963 kT: float
964 Temperature in units of eV. Determines the amplitude of the atomic
965 displacements in the modes.
966 repeat: tuple
967 Repeat atoms (l, m, n) times in the directions of the lattice
968 vectors. Displacements of atoms in repeated cells carry a Bloch
969 phase factor given by the q-vector and the cell lattice vector R_m.
970 nimages: int
971 Number of images in an oscillation.
972 center: bool
973 Center atoms in unit cell if True (default: False).
974 """
976 if isinstance(branches, int):
977 branch_l = [branches]
978 else:
979 branch_l = list(branches)
981 # Calculate modes
982 omega_l, u_l = self.band_structure(
983 q_c[np.newaxis, :],
984 modes=True,
985 )
986 # Repeat atoms
987 atoms = self.atoms * repeat
988 # Center
989 if center:
990 atoms.center()
992 # Here ``Na`` refers to a composite unit cell/atom dimension
993 pos_Nav = atoms.get_positions()
994 # Total number of unit cells
995 N = np.prod(repeat)
997 # Corresponding lattice vectors R_m
998 R_cN = np.indices(repeat).reshape(3, -1)
999 # Bloch phase
1000 phase_N = np.exp(2.0j * pi * np.dot(q_c, R_cN))
1001 phase_Na = phase_N.repeat(len(self.atoms))
1003 hbar = units._hbar * units.J * units.second
1004 for lval in branch_l:
1005 omega = omega_l[0, lval]
1006 u_av = u_l[0, lval]
1007 assert u_av.ndim == 2
1009 # For a classical harmonic oscillator, <x^2> = k T / m omega^2
1010 # and <x^2> = 1/2 u^2 where u is the amplitude and m is the
1011 # effective mass of the mode.
1012 # The reciprocal mass is already included in the normalization
1013 # of the modes. The variable omega is actually hbar*omega (it
1014 # is in eV, not reciprocal ASE time units).
1015 u_av *= hbar * sqrt(2 * kT) / abs(omega)
1017 mode_av = np.zeros((len(self.atoms), 3), dtype=complex)
1018 # Insert slice with atomic displacements for the included atoms
1019 mode_av[self.indices] = u_av
1020 # Repeat and multiply by Bloch phase factor
1021 mode_Nav = np.vstack(N * [mode_av]) * phase_Na[:, np.newaxis]
1023 with Trajectory('%s.mode.%d.traj' % (self.name, lval), 'w') as traj:
1024 for x in np.linspace(0, 2 * pi, nimages, endpoint=False):
1025 atoms.set_positions(
1026 (pos_Nav + np.exp(1.0j * x) * mode_Nav).real
1027 )
1028 traj.write(atoms)