Coverage for ase/calculators/lammps/coordinatetransform.py: 95.83%

72 statements  

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

1"""Prism""" 

2 

3import warnings 

4from collections.abc import Sequence 

5 

6import numpy as np 

7 

8from ase.geometry import wrap_positions 

9 

10 

11def calc_box_parameters(cell: np.ndarray) -> np.ndarray: 

12 """Calculate box parameters 

13 

14 https://docs.lammps.org/Howto_triclinic.html 

15 """ 

16 ax = np.sqrt(cell[0] @ cell[0]) 

17 bx = cell[0] @ cell[1] / ax 

18 by = np.sqrt(cell[1] @ cell[1] - bx**2) 

19 cx = cell[0] @ cell[2] / ax 

20 cy = (cell[1] @ cell[2] - bx * cx) / by 

21 cz = np.sqrt(cell[2] @ cell[2] - cx**2 - cy**2) 

22 return np.array((ax, by, cz, bx, cx, cy)) 

23 

24 

25def calc_rotated_cell(cell: np.ndarray) -> np.ndarray: 

26 """Calculate rotated cell in LAMMPS coordinates 

27 

28 Parameters 

29 ---------- 

30 cell : np.ndarray 

31 Cell to be rotated. 

32 

33 Returns 

34 ------- 

35 rotated_cell : np.ndarray 

36 Rotated cell represented by a lower triangular matrix. 

37 """ 

38 ax, by, cz, bx, cx, cy = calc_box_parameters(cell) 

39 return np.array(((ax, 0.0, 0.0), (bx, by, 0.0), (cx, cy, cz))) 

40 

41 

42def calc_reduced_cell( 

43 cell: np.ndarray, 

44 pbc: np.ndarray | Sequence[bool], 

45) -> np.ndarray: 

46 """Calculate LAMMPS cell with short lattice basis vectors 

47 

48 The lengths of the second and the third lattice basis vectors, b and c, are 

49 shortened with keeping the same periodicity of the system. b is modified by 

50 adding multiple a vectors, and c is modified by adding first multiple b 

51 vectors and then multiple a vectors. 

52 

53 Parameters 

54 ---------- 

55 cell : np.ndarray 

56 Cell to be reduced. This must be already a lower triangular matrix. 

57 pbc : Sequence[bool] 

58 True if the system is periodic along the corresponding direction. 

59 

60 Returns 

61 ------- 

62 reduced_cell : np.ndarray 

63 Reduced cell. `xx`, `yy`, `zz` are the same as the original cell, 

64 and `abs(xy) <= xx`, `abs(xz) <= xx`, `abs(yz) <= yy`. 

65 """ 

66 # cell 1 (reduced) <- cell 2 (original) 

67 # o-----------------------------/==o-----------------------------/--o 

68 # \ /--/ \ /--/ 

69 # \ /--/ \ /--/ 

70 # \ 1 /--/ \ 2 /--/ 

71 # \ /--/ \ /--/ 

72 # \ /--/ \ /--/ 

73 # o==/-----------------------------o--/ 

74 reduced_cell = cell.copy() 

75 # Order in which off-diagonal elements are checked for strong tilt 

76 # yz is updated before xz so that the latter does not affect the former 

77 flip_order = ((1, 0), (2, 1), (2, 0)) 

78 for i, j in flip_order: 

79 if not pbc[j]: 

80 continue 

81 ratio = reduced_cell[i, j] / reduced_cell[j, j] 

82 if abs(ratio) > 0.5: 

83 reduced_cell[i] -= reduced_cell[j] * np.round(ratio) 

84 return reduced_cell 

85 

86 

87class Prism: 

88 """The representation of the unit cell in LAMMPS 

89 

90 The main purpose of the prism-object is to create suitable string 

91 representations of prism limits and atom positions within the prism. 

92 

93 Parameters 

94 ---------- 

95 cell : np.ndarray 

96 Cell in ASE coordinate system. 

97 pbc : one or three bool 

98 Periodic boundary conditions flags. 

99 reduce_cell : bool 

100 If True, the LAMMPS cell is reduced for short lattice basis vectors. 

101 The atomic positions are always wraped into the reduced cell, 

102 regardress of `wrap` in `vector_to_lammps` and `vector_to_ase`. 

103 tolerance : float 

104 Precision for skewness test. 

105 

106 Methods 

107 ------- 

108 vector_to_lammps 

109 Rotate vectors from ASE to LAMMPS coordinates. 

110 Positions can be further wrapped into the LAMMPS cell by `wrap=True`. 

111 

112 vector_to_ase 

113 Rotate vectors from LAMMPS to ASE coordinates. 

114 Positions can be further wrapped into the LAMMPS cell by `wrap=True`. 

115 

116 Notes 

117 ----- 

118 LAMMPS prefers triangular matrixes without a strong tilt. 

119 Therefore the 'Prism'-object contains three coordinate systems: 

120 

121 - ase_cell (the simulated system in the ASE coordination system) 

122 - lammps_tilt (ase-cell rotated to be an lower triangular matrix) 

123 - lammps_cell (same volume as tilted cell, but reduce edge length) 

124 

125 The translation between 'ase_cell' and 'lammps_tilt' is done with a 

126 rotation matrix 'rot_mat'. (Mathematically this is a QR decomposition.) 

127 

128 The transformation between 'lammps_tilt' and 'lammps_cell' is done by 

129 changing the off-diagonal elements. 

130 

131 Depending on the option `reduce`, vectors in ASE coordinates are 

132 transformed either `lammps_tilt` or `lammps_cell`. 

133 

134 The vector conversion can fail as depending on the simulation run LAMMPS 

135 might have changed the simulation box significantly. This is for example a 

136 problem with hexagonal cells. LAMMPS might also wrap atoms across periodic 

137 boundaries, which can lead to problems for example NEB calculations. 

138 """ 

139 

140 # !TODO: derive tolerance from cell-dimensions 

141 def __init__( 

142 self, 

143 cell: np.ndarray, 

144 pbc: bool | np.ndarray = True, 

145 reduce_cell: bool = False, 

146 tolerance: float = 1.0e-8, 

147 ): 

148 # rot_mat * lammps_tilt^T = ase_cell^T 

149 # => lammps_tilt * rot_mat^T = ase_cell 

150 # => lammps_tilt = ase_cell * rot_mat 

151 # LAMMPS requires positive diagonal elements of the triangular matrix. 

152 # The diagonals of `lammps_tilt` are always positive by construction. 

153 self.lammps_tilt = calc_rotated_cell(cell) 

154 self.rot_mat = np.linalg.solve(self.lammps_tilt, cell).T 

155 self.ase_cell = cell 

156 self.tolerance = tolerance 

157 self.pbc = tuple(np.zeros(3, bool) + pbc) 

158 self.lammps_cell = calc_reduced_cell(self.lammps_tilt, self.pbc) 

159 self.is_reduced = reduce_cell 

160 

161 @property 

162 def cell(self) -> np.ndarray: 

163 return self.lammps_cell if self.is_reduced else self.lammps_tilt 

164 

165 def get_lammps_prism(self) -> np.ndarray: 

166 """Return box parameters of the rotated cell in LAMMPS coordinates 

167 

168 Returns 

169 ------- 

170 np.ndarray 

171 xhi - xlo, yhi - ylo, zhi - zlo, xy, xz, yz 

172 """ 

173 return self.cell[(0, 1, 2, 1, 2, 2), (0, 1, 2, 0, 0, 1)] 

174 

175 def update_cell(self, lammps_cell: np.ndarray) -> np.ndarray: 

176 """Rotate new LAMMPS cell into ASE coordinate system 

177 

178 Parameters 

179 ---------- 

180 lammps_cell : np.ndarray 

181 New Cell in LAMMPS coordinates received after executing LAMMPS 

182 

183 Returns 

184 ------- 

185 np.ndarray 

186 New cell in ASE coordinates 

187 """ 

188 # Transformation: integer matrix 

189 # lammps_cell * transformation = lammps_tilt 

190 transformation = np.linalg.solve(self.lammps_cell, self.lammps_tilt) 

191 

192 if self.is_reduced: 

193 self.lammps_cell = lammps_cell 

194 self.lammps_tilt = lammps_cell @ transformation 

195 else: 

196 self.lammps_tilt = lammps_cell 

197 self.lammps_cell = calc_reduced_cell(self.lammps_tilt, self.pbc) 

198 

199 # try to detect potential flips in lammps 

200 # (lammps minimizes the cell-vector lengths) 

201 new_ase_cell = self.lammps_tilt @ self.rot_mat.T 

202 # assuming the cell changes are mostly isotropic 

203 new_vol = np.linalg.det(new_ase_cell) 

204 old_vol = np.linalg.det(self.ase_cell) 

205 test_residual = self.ase_cell.copy() 

206 test_residual *= (new_vol / old_vol) ** (1.0 / 3.0) 

207 test_residual -= new_ase_cell 

208 if any( 

209 np.linalg.norm(test_residual, axis=1) 

210 > 0.5 * np.linalg.norm(self.ase_cell, axis=1) 

211 ): 

212 warnings.warn( 

213 'Significant simulation cell changes from LAMMPS detected. ' 

214 'Backtransformation to ASE might fail!' 

215 ) 

216 return new_ase_cell 

217 

218 def vector_to_lammps( 

219 self, 

220 vec: np.ndarray, 

221 wrap: bool = False, 

222 ) -> np.ndarray: 

223 """Rotate vectors from ASE to LAMMPS coordinates 

224 

225 Parameters 

226 ---------- 

227 vec : np.ndarray 

228 Vectors in ASE coordinates to be rotated into LAMMPS coordinates 

229 wrap : bool 

230 If True, the vectors are wrapped into the cell 

231 

232 Returns 

233 ------- 

234 np.array 

235 Vectors in LAMMPS coordinates 

236 """ 

237 # !TODO: right eps-limit 

238 # lammps might not like atoms outside the cell 

239 if wrap or self.is_reduced: 

240 return wrap_positions( 

241 vec @ self.rot_mat, 

242 cell=self.cell, 

243 pbc=self.pbc, 

244 eps=1e-18, 

245 ) 

246 return vec @ self.rot_mat 

247 

248 def vector_to_ase( 

249 self, 

250 vec: np.ndarray, 

251 wrap: bool = False, 

252 ) -> np.ndarray: 

253 """Rotate vectors from LAMMPS to ASE coordinates 

254 

255 Parameters 

256 ---------- 

257 vec : np.ndarray 

258 Vectors in LAMMPS coordinates to be rotated into ASE coordinates 

259 wrap : bool 

260 If True, the vectors are wrapped into the cell 

261 

262 Returns 

263 ------- 

264 np.ndarray 

265 Vectors in ASE coordinates 

266 """ 

267 if wrap or self.is_reduced: 

268 # fractional in `lammps_tilt` (the same shape as ASE cell) 

269 fractional = np.linalg.solve(self.lammps_tilt.T, vec.T).T 

270 # wrap into 0 to 1 for periodic directions 

271 fractional -= np.floor(fractional) * self.pbc 

272 # Cartesian coordinates wrapped into `lammps_tilt` 

273 vec = fractional @ self.lammps_tilt 

274 # rotate back to the ASE cell 

275 return vec @ self.rot_mat.T 

276 

277 def tensor2_to_ase(self, tensor: np.ndarray) -> np.ndarray: 

278 """Rotate a second order tensor from LAMMPS to ASE coordinates 

279 

280 Parameters 

281 ---------- 

282 tensor : np.ndarray 

283 Tensor in LAMMPS coordinates to be rotated into ASE coordinates 

284 

285 Returns 

286 ------- 

287 np.ndarray 

288 Tensor in ASE coordinates 

289 """ 

290 return self.rot_mat @ tensor @ self.rot_mat.T 

291 

292 def is_skewed(self) -> bool: 

293 """Test if the lammps cell is skewed, i.e., monoclinic or triclinic. 

294 

295 Returns 

296 ------- 

297 bool 

298 True if the lammps cell is skewed. 

299 """ 

300 cell_sq = self.cell**2 

301 on_diag = np.sum(np.diag(cell_sq)) 

302 off_diag = np.sum(np.tril(cell_sq, -1)) 

303 return off_diag / on_diag > self.tolerance