Coverage for dynasor/qpoints/lattice.py: 100%

85 statements  

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

1"""The relation between a primitive cell and a supercell, and the q-points it implies. 

2 

3:class:`Lattice` bundles the integer repetition matrix `P` with the 

4commensurate q-points it defines. :func:`get_P_matrix` and 

5:func:`get_supercell_qpoints_along_path` are the standalone entry points. 

6""" 

7 

8import warnings 

9from fractions import Fraction 

10from functools import cached_property 

11 

12import numpy as np 

13from numpy.typing import NDArray 

14 

15from dynasor.qpoints.tools import exact_inverse, _find_on_line, _get_commensurate_points 

16 

17 

18class Lattice: 

19 r"""Relates a primitive cell to a supercell and provides the commensurate q-points. 

20 

21 The class serves two purposes: it holds the integer repetition matrix `P` 

22 connecting the two cells, and it hands out the q-points that a simulation in 

23 that supercell can actually resolve, via :attr:`q_reduced`, :attr:`q_cartesian` 

24 and :meth:`make_path`. 

25 

26 The supercell `S` is given by the primitive cell `p` and a repetition 

27 matrix `P` such that: 

28 

29 dot(P, p) = S 

30 

31 In this convention the cell vectors are row vectors of `p` and `S` as in 

32 ASE. An inverse cell is defined as: 

33 

34 c_inv = inv(c).T 

35 

36 and the reciprocal cell is defined as: 

37 

38 c_rec = 2*pi*inv(c).T 

39 

40 Notice that the inverse cell here is defined with the transpose so that 

41 the lattice vectors of the inverse/reciprocal lattice are also row 

42 vectors. The above also implies: 

43 

44 dot(P.T, S_inv) = p_inv 

45 

46 The inverse supercell S_inv defines a new lattice in reciprocal space. 

47 Those inverse lattice points which reside inside the inverse primitive 

48 cell p_inv are called commensurate lattice points. These are typically 

49 the only points of interest in MD simulations from a crystallographic 

50 and lattice dynamics point of view. 

51 

52 The convention taken here is that the reciprocal cell carries the 2pi 

53 factor onto the cartesian q-points. This is consistent with e.g. 

54 Kittel. The reduced coordinates are always with respect to the 

55 reciprocal primitive cell. 

56 

57 Parameters 

58 ---------- 

59 primitive_cell 

60 Cell metric of the primitive cell with lattice vectors as rows. 

61 supercell_cell 

62 Cell metric of the supercell with lattice vectors as rows. 

63 

64 Example 

65 ------- 

66 >>> from ase.build import bulk 

67 >>> from dynasor.qpoints import Lattice 

68 >>> prim = bulk('Al', 'fcc', a=4.0) 

69 >>> lattice = Lattice(prim.cell, prim.repeat(2).cell) 

70 >>> len(lattice.q_cartesian) 

71 8 

72 """ 

73 

74 def __init__(self, primitive_cell: NDArray[float], supercell_cell: NDArray[float]): 

75 self._primitive_cell = np.array(primitive_cell) 

76 self._supercell_cell = np.array(supercell_cell) 

77 

78 self._P = get_P_matrix(self._primitive_cell, self._supercell_cell) 

79 

80 # The q-points are computed on first use, since callers that only want a path 

81 # through the Brillouin zone need nothing but P. 

82 @cached_property 

83 def _q_reduced(self) -> NDArray[Fraction]: 

84 # As stated in the doc the P matrix relating the inverse cells are just P.T 

85 return _get_commensurate_points(self._P.T) 

86 

87 @cached_property 

88 def _q_minus(self) -> NDArray[int]: 

89 # exact fractions, so the -q partner is found by an exact tuple match 

90 index = {tuple(q): i for i, q in enumerate(self._q_reduced)} 

91 return np.array([index[tuple((-q) % 1)] for q in self._q_reduced]) 

92 

93 @property 

94 def primitive_cell(self) -> NDArray[float]: 

95 """Returns the primitive cell with lattice vectors as rows""" 

96 return self._primitive_cell.copy() 

97 

98 @property 

99 def supercell_cell(self) -> NDArray[float]: 

100 """Returns the supercell with lattice vectors as rows""" 

101 return self._supercell_cell.copy() 

102 

103 @property 

104 def reciprocal_primitive_cell(self) -> NDArray[float]: 

105 """Returns 2*pi*inv(primitive_cell).T so that the rows are the inverse lattice vectors""" 

106 return 2*np.pi * np.linalg.inv(self._primitive_cell.T) 

107 

108 @property 

109 def reciprocal_supercell_cell(self) -> NDArray[float]: 

110 """Returns 2*pi*inv(supercell_cell).T so that the rows are the inverse lattice vectors""" 

111 return 2*np.pi * np.linalg.inv(self._supercell_cell.T) 

112 

113 @property 

114 def P(self) -> NDArray[int]: 

115 """The P-matrix for this system, P @ primitive_cell = supercell_cell""" 

116 return self._P.copy() 

117 

118 @property 

119 def P_inv(self) -> NDArray[Fraction]: 

120 """Inverse of :attr:`P` as exact :class:`fractions.Fraction` values.""" 

121 return exact_inverse(self._P) 

122 

123 @property 

124 def q_reduced(self) -> NDArray[Fraction]: 

125 """The commensurate q-points in reduced coordinates, as exact fractions. 

126 

127 This is an object array, so it is not a drop-in numerical array; 

128 ``np.allclose``, ``np.isfinite`` and ``np.round`` raise :class:`TypeError` 

129 on it, while ``.astype(float)``, arithmetic and ``np.sort`` work. 

130 """ 

131 return self._q_reduced.copy() 

132 

133 @property 

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

135 """The commensurate q-points in Cartesian coordinates with unit of rad/Å.""" 

136 return self.reduced_to_cartesian(self._q_reduced) 

137 

138 @property 

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

140 """For each q-point, the index of the q-point corresponding to :math:`-q`.""" 

141 return self._q_minus.copy() 

142 

143 def __repr__(self) -> str: 

144 rep = (f'{self.__class__.__name__}(' 

145 f'primitive_cell={self._primitive_cell.tolist()}, ' 

146 f'supercell_cell={self._supercell_cell.tolist()})') 

147 return rep 

148 

149 def reduced_to_cartesian(self, qpoints: NDArray[float]) -> NDArray[float]: 

150 """Convert from reduced to cartesian coordinates. 

151 

152 Accepts the exact fractions returned by :attr:`q_reduced` as well as floats. 

153 """ 

154 return np.asarray(qpoints, dtype=float) @ self.reciprocal_primitive_cell 

155 

156 def cartesian_to_reduced(self, qpoints: NDArray[float]) -> NDArray[float]: 

157 """Convert from Cartesian to reduced coordinates.""" 

158 qpoints = np.asarray(qpoints, dtype=float) 

159 return np.linalg.solve(self.reciprocal_primitive_cell.T, qpoints.T).T 

160 

161 def make_path( 

162 self, 

163 start: NDArray[float], 

164 stop: NDArray[float], 

165 ) -> tuple[NDArray[float], NDArray[float]]: 

166 """Takes qpoints in reduced coordinates and returns all points in between 

167 

168 Parameters 

169 ---------- 

170 start 

171 Coordinate of starting point in reduced inverse coordinates. 

172 For example, a zone mode is given as (0.5, 0, 0), (0,0,0) == (1,0,0) etc. 

173 stop 

174 Stop position. 

175 

176 Returns 

177 ------- 

178 Tuple of the coordinates of commensurate points along path in Cartesian 

179 reciprocals and the fractional distances along the path. 

180 """ 

181 # float, since integer input gives Fractions with unhashable numpy numerators 

182 start = np.asarray(start, dtype=float) 

183 stop = np.asarray(stop, dtype=float) 

184 fracs = _find_on_line(start, stop, self._P.T) 

185 if not len(fracs): 

186 warnings.warn('No q-points along path!') 

187 return np.zeros(shape=(0, 3)), np.zeros(shape=(0,)) 

188 points = np.array([start + float(f) * (stop - start) for f in fracs]) 

189 qpoints = self.reduced_to_cartesian(points) 

190 dists = np.array([float(f) for f in fracs]) 

191 return qpoints, dists 

192 

193 

194def get_P_matrix( 

195 c: NDArray[float], 

196 S: NDArray[float], 

197) -> NDArray[int]: 

198 """Returns the P matrix, i.e., the `3x3` integer matrix :math:`P` that satisfies 

199 

200 .. math:: 

201 

202 P c = S 

203 

204 Here, :math:`c` is the primitive cell metric and :math:`S` is the 

205 supercell metric as row vectors. Note that the above condition is 

206 equivalent to: 

207 

208 .. math:: 

209 

210 c^T P^T = S^T 

211 

212 Parameters 

213 ---------- 

214 c 

215 Cell metric of the primitive structure. 

216 S 

217 Cell metric of the supercell. 

218 """ 

219 PT = np.linalg.solve(np.asarray(c).T, np.asarray(S).T) 

220 P_float = PT.T 

221 P = np.round(P_float).astype(int) 

222 if not np.allclose(P_float, P) or not np.allclose(P @ c, S): 

223 raise ValueError( 

224 f'Please check that the supercell metric ({S}) is related to the' 

225 f' primitive cell {c} by an integer transformation matrix.') 

226 return P 

227 

228 

229def get_supercell_qpoints_along_path( 

230 path: list[tuple[str, str]], 

231 coordinates: dict[str, NDArray[float]], 

232 primitive_cell: NDArray[float], 

233 supercell_cell: NDArray[float]) -> list[NDArray[float]]: 

234 r""" 

235 Returns the q-points commensurate with the given supercell along the specific path. 

236 

237 Parameters 

238 ---------- 

239 path 

240 List of pairs of q-point labels. 

241 coordinates 

242 Dict with q-point labels and coordinates as keys and values, respectively; 

243 there must be one entry for each q-point label used in :attr:`path`. 

244 primitive_cell 

245 Cell metric of the primitive cell with lattice vectors as rows. 

246 supercell_cell 

247 Cell metric of the supercell with lattice vectors as rows. 

248 

249 Returns 

250 ------- 

251 A list of the accessible q-point coordinates along the specified segment. 

252 

253 Example 

254 ------- 

255 The following example illustrates how to retrieve the q-points that 

256 can be sampled using a supercell comprising :math:`6 \times 6 \times 6` 

257 conventional (4-atom) unit cells of FCC Al along the path X-:math:`\Gamma`-L. 

258 

259 >>> import numpy as np 

260 >>> from ase.build import bulk 

261 >>> from dynasor.qpoints import get_supercell_qpoints_along_path 

262 >>> prim = bulk('Al', 'fcc', a=4.0) 

263 >>> supercell = bulk('Al', 'fcc', a=4.0, cubic=True).repeat(6) 

264 >>> path = [('X', 'G'), ('G', 'L'), ('L', 'W')] 

265 >>> coordinates = dict(X=[0.5, 0.5, 0], G=[0, 0, 0], 

266 ... L=[0.5, 0.5, 0.5], W=[0.5, 0.25, 0.75]) 

267 >>> qpoints = get_supercell_qpoints_along_path( 

268 ... path, coordinates, prim.cell, supercell.cell) 

269 

270 """ 

271 for lbl in np.array(path).flatten(): 

272 if lbl not in coordinates: 

273 raise ValueError(f'Unknown point in path: {lbl}') 

274 

275 lattice = Lattice(primitive_cell, supercell_cell) 

276 

277 # build the segments 

278 supercell_paths = [] 

279 for l1, l2 in path: 

280 q1 = np.array(coordinates[l1], dtype=float) 

281 q2 = np.array(coordinates[l2], dtype=float) 

282 dynasor_path, _ = lattice.make_path(q1, q2) 

283 supercell_paths.append(dynasor_path) 

284 return supercell_paths 

285 

286 

287def is_qpoint_commensurate( 

288 q_point: NDArray[float], 

289 cell: NDArray[float], 

290 atol: float = 1e-5, 

291) -> bool: 

292 r"""Return whether a single q-point is commensurate with a periodic cell. 

293 

294 A q-point is commensurate with the cell when it is a reciprocal-lattice 

295 vector of that cell, i.e. when its reduced coordinates 

296 :math:`m_i = \mathbf{q}\cdot\mathbf{a}_i / 2\pi` are all integers, where the 

297 :math:`\mathbf{a}_i` are the cell vectors (rows of :attr:`cell`). Only then 

298 is :math:`\rho(\mathbf{q}) = \sum_j e^{i\mathbf{q}\cdot\mathbf{r}_j}` 

299 independent of which periodic image is chosen for each atom; at other 

300 q-points the correlation functions can contain artifacts. 

301 

302 The reduced coordinates are formed with the full cell matrix, so the test is 

303 correct for non-orthogonal cells (a per-axis check would not be). 

304 

305 Parameters 

306 ---------- 

307 q_point 

308 A single q-point ``(3,)`` in Cartesian coordinates (rad/Å). 

309 cell 

310 Cell metric with lattice vectors as rows (Å). 

311 atol 

312 Absolute tolerance on the reduced coordinates when testing for integers. 

313 """ 

314 q_point = np.asarray(q_point, dtype=float) 

315 cell = np.asarray(cell, dtype=float) 

316 reduced = q_point @ cell.T / (2 * np.pi) # m_i = q . a_i / 2pi 

317 return bool(np.all(np.abs(reduced - np.rint(reduced)) < atol))