Coverage for ase/geometry/minkowski_reduction.py: 96.95%

131 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1import itertools 

2 

3import numpy as np 

4 

5from ase.cell import Cell 

6from ase.utils import pbc2pbc 

7 

8TOL = 1e-12 

9MAX_IT = 100000 # in practice this is not exceeded 

10 

11 

12class CycleChecker: 

13 def __init__(self, d): 

14 assert d in [2, 3] 

15 

16 # worst case is the hexagonal cell in 2D and the fcc cell in 3D 

17 n = {2: 6, 3: 12}[d] 

18 

19 # max cycle length is total number of primtive cell descriptions 

20 max_cycle_length = np.prod([n - i for i in range(d)]) * np.prod(d) 

21 self.visited = np.zeros((max_cycle_length, 3 * d), dtype=int) 

22 

23 def add_site(self, H): 

24 # flatten array for simplicity 

25 H = H.ravel() 

26 

27 # check if site exists 

28 found = (self.visited == H).all(axis=1).any() 

29 

30 # shift all visited sites down and place current site at the top 

31 self.visited = np.roll(self.visited, 1, axis=0) 

32 self.visited[0] = H 

33 return found 

34 

35 

36def reduction_gauss(B, hu, hv): 

37 """Calculate a Gauss-reduced lattice basis (2D reduction).""" 

38 cycle_checker = CycleChecker(d=2) 

39 u = hu @ B 

40 v = hv @ B 

41 

42 for _ in range(MAX_IT): 

43 x = int(round(np.dot(u, v) / np.dot(u, u))) 

44 hu, hv = hv - x * hu, hu 

45 u = hu @ B 

46 v = hv @ B 

47 site = np.array([hu, hv]) 

48 if np.dot(u, u) >= np.dot(v, v) or cycle_checker.add_site(site): 

49 return hv, hu 

50 

51 raise RuntimeError(f'Gaussian basis not found after {MAX_IT} iterations') 

52 

53 

54def relevant_vectors_2D(u, v): 

55 cs = np.array([e for e in itertools.product([-1, 0, 1], repeat=2)]) 

56 vs = cs @ [u, v] 

57 indices = np.argsort(np.linalg.norm(vs, axis=1))[:7] 

58 return vs[indices], cs[indices] 

59 

60 

61def closest_vector(t0, u, v): 

62 t = t0 

63 a = np.zeros(2, dtype=int) 

64 rs, cs = relevant_vectors_2D(u, v) 

65 

66 dprev = float('inf') 

67 for _ in range(MAX_IT): 

68 ds = np.linalg.norm(rs + t, axis=1) 

69 index = np.argmin(ds) 

70 if index == 0 or ds[index] >= dprev: 

71 return a 

72 

73 dprev = ds[index] 

74 r = rs[index] 

75 kopt = int(round(-np.dot(t, r) / np.dot(r, r))) 

76 a += kopt * cs[index] 

77 t = t0 + a[0] * u + a[1] * v 

78 

79 raise RuntimeError(f'Closest vector not found after {MAX_IT} iterations') 

80 

81 

82def reduction_full(B): 

83 """Calculate a Minkowski-reduced lattice basis (3D reduction).""" 

84 cycle_checker = CycleChecker(d=3) 

85 H = np.eye(3, dtype=int) 

86 norms = np.linalg.norm(B, axis=1) 

87 

88 for _ in range(MAX_IT): 

89 # Sort vectors by norm 

90 H = H[np.argsort(norms, kind='merge')] 

91 

92 # Gauss-reduce smallest two vectors 

93 hw = H[2] 

94 hu, hv = reduction_gauss(B, H[0], H[1]) 

95 H = np.array([hu, hv, hw]) 

96 R = H @ B 

97 

98 # Orthogonalize vectors using Gram-Schmidt 

99 u, v, _ = R 

100 X = u / np.linalg.norm(u) 

101 Y = v - X * np.dot(v, X) 

102 Y /= np.linalg.norm(Y) 

103 

104 # Find closest vector to last element of R 

105 pu, pv, pw = R @ np.array([X, Y]).T 

106 nb = closest_vector(pw, pu, pv) 

107 

108 # Update basis 

109 H[2] = [nb[0], nb[1], 1] @ H 

110 R = H @ B 

111 

112 norms = np.linalg.norm(R, axis=1) 

113 if norms[2] >= norms[1] or cycle_checker.add_site(H): 

114 return R, H 

115 

116 raise RuntimeError(f'Reduced basis not found after {MAX_IT} iterations') 

117 

118 

119def is_minkowski_reduced(cell, pbc=True): 

120 """Tests if a cell is Minkowski-reduced. 

121 

122 Parameters 

123 ---------- 

124 

125 cell: array 

126 The lattice basis to test (in row-vector format). 

127 pbc: array, optional 

128 The periodic boundary conditions of the cell (Default `True`). 

129 If `pbc` is provided, only periodic cell vectors are tested. 

130 

131 Returns 

132 ------- 

133 

134 is_reduced: bool 

135 True if cell is Minkowski-reduced, False otherwise. 

136 """ 

137 

138 """These conditions are due to Minkowski, but a nice description in English 

139 can be found in the thesis of Carine Jaber: "Algorithmic approaches to 

140 Siegel's fundamental domain", https://www.theses.fr/2017UBFCK006.pdf 

141 This is also good background reading for Minkowski reduction. 

142 

143 0D and 1D cells are trivially reduced. For 2D cells, the conditions which 

144 an already-reduced basis fulfil are: 

145 |b1| ≤ |b2| 

146 |b2| ≤ |b1 - b2| 

147 |b2| ≤ |b1 + b2| 

148 

149 For 3D cells, the conditions which an already-reduced basis fulfil are: 

150 |b1| ≤ |b2| ≤ |b3| 

151 

152 |b1 + b2| ≥ |b2| 

153 |b1 + b3| ≥ |b3| 

154 |b2 + b3| ≥ |b3| 

155 |b1 - b2| ≥ |b2| 

156 |b1 - b3| ≥ |b3| 

157 |b2 - b3| ≥ |b3| 

158 |b1 + b2 + b3| ≥ |b3| 

159 |b1 - b2 + b3| ≥ |b3| 

160 |b1 + b2 - b3| ≥ |b3| 

161 |b1 - b2 - b3| ≥ |b3| 

162 """ 

163 pbc = pbc2pbc(pbc) 

164 dim = pbc.sum() 

165 if dim <= 1: 

166 return True 

167 

168 if dim == 2: 

169 # reorder cell vectors to [shortest, longest, aperiodic] 

170 cell = cell.copy() 

171 cell[np.argmin(pbc)] = 0 

172 norms = np.linalg.norm(cell, axis=1) 

173 cell = cell[np.argsort(norms)[[1, 2, 0]]] 

174 

175 A = [[0, 1, 0], [1, -1, 0], [1, 1, 0]] 

176 lhs = np.linalg.norm(A @ cell, axis=1) 

177 norms = np.linalg.norm(cell, axis=1) 

178 rhs = norms[[0, 1, 1]] 

179 else: 

180 A = [ 

181 [0, 1, 0], 

182 [0, 0, 1], 

183 [1, 1, 0], 

184 [1, 0, 1], 

185 [0, 1, 1], 

186 [1, -1, 0], 

187 [1, 0, -1], 

188 [0, 1, -1], 

189 [1, 1, 1], 

190 [1, -1, 1], 

191 [1, 1, -1], 

192 [1, -1, -1], 

193 ] 

194 lhs = np.linalg.norm(A @ cell, axis=1) 

195 norms = np.linalg.norm(cell, axis=1) 

196 rhs = norms[[0, 1, 1, 2, 2, 1, 2, 2, 2, 2, 2, 2]] 

197 return (lhs >= rhs - TOL).all() 

198 

199 

200def minkowski_reduce(cell, pbc=True): 

201 """Calculate a Minkowski-reduced lattice basis. The reduced basis 

202 has the shortest possible vector lengths and has 

203 norm(a) <= norm(b) <= norm(c). 

204 

205 Implements the method described in: 

206 

207 Low-dimensional Lattice Basis Reduction Revisited 

208 Nguyen, Phong Q. and Stehlé, Damien, 

209 ACM Trans. Algorithms 5(4) 46:1--46:48, 2009 

210 :doi:`10.1145/1597036.1597050` 

211 

212 Parameters 

213 ---------- 

214 

215 cell: array 

216 The lattice basis to reduce (in row-vector format). 

217 pbc: array, optional 

218 The periodic boundary conditions of the cell (Default `True`). 

219 If `pbc` is provided, only periodic cell vectors are reduced. 

220 

221 Returns 

222 ------- 

223 

224 rcell: array 

225 The reduced lattice basis. 

226 op: array 

227 The unimodular matrix transformation (rcell = op @ cell). 

228 """ 

229 cell = Cell(cell) 

230 pbc = pbc2pbc(pbc) 

231 dim = pbc.sum() 

232 op = np.eye(3, dtype=int) 

233 if is_minkowski_reduced(cell, pbc): 

234 return cell, op 

235 

236 if dim == 2: 

237 # permute cell so that first two vectors are the periodic ones 

238 perm = np.argsort(pbc, kind='merge')[::-1] # stable sort 

239 pcell = cell[perm][:, perm] 

240 

241 # perform gauss reduction 

242 norms = np.linalg.norm(pcell, axis=1) 

243 norms[2] = float('inf') 

244 indices = np.argsort(norms) 

245 op = op[indices] 

246 hu, hv = reduction_gauss(pcell, op[0], op[1]) 

247 op[0] = hu 

248 op[1] = hv 

249 

250 # undo above permutation 

251 invperm = np.argsort(perm) 

252 op = op[invperm][:, invperm] 

253 

254 # maintain cell handedness 

255 index = np.argmin(pbc) 

256 normal = np.cross(cell[index - 2], cell[index - 1]) 

257 normal /= np.linalg.norm(normal) 

258 

259 _cell = cell.copy() 

260 _cell[index] = normal 

261 _rcell = op @ cell 

262 _rcell[index] = normal 

263 if _cell.handedness != Cell(_rcell).handedness: 

264 op[index - 1] *= -1 

265 

266 elif dim == 3: 

267 _, op = reduction_full(cell) 

268 # maintain cell handedness 

269 if cell.handedness != Cell(op @ cell).handedness: 

270 op = -op 

271 

272 norms1 = np.sort(np.linalg.norm(cell, axis=1)) 

273 norms2 = np.sort(np.linalg.norm(op @ cell, axis=1)) 

274 if (norms2 > norms1 + TOL).any(): 

275 raise RuntimeError('Minkowski reduction failed') 

276 return op @ cell, op