Coverage for dynasor/modes/tools.py: 100%
47 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-09 14:30 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-09 14:30 +0000
1from typing import Optional
2import numba
3import numpy as np
4from numpy.typing import NDArray
7# Mode projections
8def mode_coordinates(X: NDArray[complex], u: NDArray[float]) -> NDArray[complex]:
9 r"""Projects atomic displacements onto modes, :math:`Q = X u`.
11 Parameters
12 ----------
13 X
14 Modes with shape ``(..., N, 3)``, where the leading dimensions define the output shape.
15 u
16 Atomic displacements in Å.
18 Returns
19 -------
20 The mode coordinates in Å√dmu, with shape ``X.shape[:-2]``.
21 """
22 return np.einsum('...na,na->...', X, u, optimize=True)
25def mode_momenta(X: NDArray[complex], v: NDArray[float]) -> NDArray[complex]:
26 r"""Projects atomic velocities onto modes, :math:`P = X^* v`.
28 Parameters
29 ----------
30 X
31 Modes with shape ``(..., N, 3)``, where the leading dimensions define the output shape.
32 v
33 Atomic velocities in Å/fs.
35 Returns
36 -------
37 The mode momenta in √eV, with shape ``X.shape[:-2]``.
38 """
39 return np.einsum('...na,na->...', X.conj(), v, optimize=True)
42def mode_forces(
43 X: NDArray[complex],
44 f: NDArray[float],
45 masses: NDArray[float],
46) -> NDArray[complex]:
47 r"""Projects atomic forces onto modes, :math:`F = X^* f / m`.
49 Parameters
50 ----------
51 X
52 Modes with shape ``(..., N, 3)``, where the leading dimensions define the output shape.
53 f
54 Atomic forces in eV/Å.
55 masses
56 Atomic masses in dmu, one per atom.
58 Returns
59 -------
60 The mode forces in eV/Å√dmu, with shape ``X.shape[:-2]``.
61 """
62 # The mass divides the forces rather than the modes, since f is the smaller array.
63 return np.einsum('...na,na->...', X.conj(), f / masses[:, None], optimize=True)
66def symmetrize_eigenvectors(
67 eigenvectors: NDArray[float],
68 cell: Optional[NDArray[float]] = None,
69 max_iter: Optional[int] = 1000,
70 method: Optional[str] = 'varimax',
71 tol: float = 1e-12,
72) -> NDArray[float]:
73 """Takes a set of vectors and tries to make them nice
75 Parameters
76 ----------
77 eigenvectors
78 If there are n degenerate eigenvectors and m atoms in the basis the
79 array should be `(n,m,3)`.
80 cell
81 If default `None` nothing is done to the cartesian directions but a cell
82 can be provided so the directions are in scaled coordinates instead.
83 max_iter
84 Maximum number of iterations in the symmetrization procedure (safety cap).
85 method
86 Can be `'varimax'` or `'quartimax'` or a parameter between `0: quartimax` and
87 `1: varimax`. Depending on the choice one obtains, e.g., Equamax, Parsimax, etc.
88 tol
89 Convergence tolerance passed to :func:`factor_analysis`; iteration stops
90 early once the rotation matrix has converged. Set `tol=0` to always run
91 `max_iter` iterations.
93 """
95 if cell is None:
96 cell = np.eye(3)
98 # s = band, i = basis, a = axis
99 eigenvectors = np.einsum('sia,ab->sib', eigenvectors, np.linalg.inv(cell))
101 components = eigenvectors.reshape(len(eigenvectors), -1).T
103 rotation_matrix = factor_analysis(components, iterations=max_iter, method=method, tol=tol)
105 new_eigenvectors = np.dot(components, rotation_matrix).T
107 new_eigenvectors = new_eigenvectors.reshape(len(new_eigenvectors), -1, 3)
109 new_eigenvectors = np.einsum('sia,ab->sib', new_eigenvectors, cell)
111 return new_eigenvectors
114def factor_analysis(
115 L: NDArray[float],
116 iterations: Optional[int] = 1000,
117 method: Optional[str] = 'varimax',
118 tol: float = 1e-12,
119) -> NDArray[float]:
120 """Performs factor analysis on `L` finding rotation matrix `R` such that `L @ R = L'` is simple.
122 In the future consider using the scikit learn methods directly but beware
123 the changes need to accommodate complex numbers.
125 Parameters
126 ----------
127 L
128 Matrix whose columns are rotated.
129 iterations
130 Maximum number of iterations (safety cap).
131 method
132 Can be `'varimax'` or `'quartimax'` or a parameter between `0: quartimax`
133 and `1: varimax`.
134 tol
135 Convergence tolerance: iteration stops once the rotation matrix `R`
136 stops changing, i.e. once ``max|R - R_prev| < tol`` between two
137 successive sweeps, with `iterations` as a safety cap.
139 References:
140 * *Sparse Modeling of Landmark and Texture Variability using the Orthomax Criterion*
141 Mikkel B. Stegmann, Karl Sjöstrand, Rasmus Larsen
142 http://www2.imm.dtu.dk/pubdb/edoc/imm4041.pdf
144 * http://www.cs.ucl.ac.uk/staff/d.barber/brml
146 * https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.FactorAnalysis.html # noqa
148 * https://stats.stackexchange.com/questions/185216/factor-rotation-methods-varimax-quartimax-oblimin-etc-what-do-the-names # noqa
150 """
152 nrow, ncol = L.shape
153 R = np.eye(ncol)
155 if method == 'varimax':
156 gamma = 1
157 elif method == 'quartimax':
158 gamma = 0
159 else:
160 gamma = method
162 for _ in range(iterations):
163 LR = np.dot(L, R)
164 grad = LR * (np.abs(LR)**2 - gamma * np.mean(np.abs(LR)**2, axis=0))
165 G = L.T.conj() @ grad
166 u, s, vh = np.linalg.svd(G)
167 R_new = u @ vh
168 change = np.abs(R_new - R).max()
169 R = R_new
170 if change < tol:
171 break
173 return R
176def group_eigvals(
177 vals: NDArray[float],
178 tol: Optional[float] = 1e-6,
179) -> list[list[int]]:
180 assert sorted(vals) == list(vals), vals
182 groups = [[0]]
183 for i in range(1, len(vals)):
184 if np.abs(vals[i] - vals[i-1]) < tol:
185 groups[-1].append(i)
186 else:
187 groups.append([i])
188 return groups
191@numba.njit # pragma: no cover
192def get_dynamical_matrix(fc, offsets, indices, q):
193 """Dynamical matrix at `q` from the force constants of a supercell.
195 Only the first supercell atom of each primitive basis site is used, so the
196 force constants must be translationally invariant; otherwise the result
197 depends on the atom ordering.
198 """
200 n = indices.max() + 1
201 N = len(fc)
202 D = np.zeros(shape=(n, n, 3, 3), dtype=np.complex128)
203 for ia in range(n):
204 for a in range(N):
205 if ia != indices[a]:
206 continue
207 na = offsets[a]
208 for b in range(N):
209 ib = indices[b]
210 nb = offsets[b]
211 dn = (nb - na).astype(np.float64)
212 D[ia, ib] += fc[a, b] * np.exp(2j*np.pi * np.dot(dn, q))
213 break
214 return D