Coverage for ase/cell.py: 99.35%

154 statements  

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

1"""Cell.""" 

2 

3from collections.abc import Mapping, Sequence 

4 

5import numpy as np 

6 

7import ase 

8from ase.utils import pbc2pbc 

9from ase.utils.arraywrapper import arraylike 

10 

11__all__ = ['Cell'] 

12 

13 

14@arraylike 

15class Cell: 

16 """Parallel epipedal unit cell of up to three dimensions. 

17 

18 This object resembles a 3x3 array whose [i, j]-th element is the jth 

19 Cartesian coordinate of the ith unit vector. 

20 

21 Cells of less than three dimensions are represented by placeholder 

22 unit vectors that are zero.""" 

23 

24 ase_objtype = 'cell' # For JSON'ing 

25 

26 def __init__(self, array): 

27 """Create cell. 

28 

29 Parameters 

30 ---------- 

31 array: 3x3 arraylike object 

32 The three cell vectors: cell[0], cell[1], and cell[2]. 

33 """ 

34 array = np.asarray(array, dtype=float) 

35 assert array.shape == (3, 3) 

36 self.array = array 

37 

38 def cellpar(self, radians=False): 

39 """Get unit cell parameters. Sequence of 6 numbers. 

40 

41 First three are unit cell vector lengths and second three 

42 are angles between them:: 

43 

44 [len(a), len(b), len(c), angle(b,c), angle(a,c), angle(a,b)] 

45 

46 in degrees. 

47 

48 See also :func:`ase.geometry.cell.cell_to_cellpar`.""" 

49 from ase.geometry.cell import cell_to_cellpar 

50 

51 return cell_to_cellpar(self.array, radians) 

52 

53 def todict(self): 

54 return dict(array=self.array) 

55 

56 @classmethod 

57 def ascell(cls, cell): 

58 """Return argument as a Cell object. See :meth:`ase.cell.Cell.new`. 

59 

60 A new Cell object is created if necessary.""" 

61 if isinstance(cell, cls): 

62 return cell 

63 return cls.new(cell) 

64 

65 @classmethod 

66 def new(cls, cell=None): 

67 """Create new cell from any parameters. 

68 

69 If cell is three numbers, assume three lengths with right angles. 

70 

71 If cell is six numbers, assume three lengths, then three angles. 

72 

73 If cell is 3x3, assume three cell vectors.""" 

74 

75 if cell is None: 

76 cell = np.zeros((3, 3)) 

77 

78 cell = np.array(cell, float) 

79 

80 if cell.shape == (3,): 

81 cell = np.diag(cell) 

82 elif cell.shape == (6,): 

83 from ase.geometry.cell import cellpar_to_cell 

84 

85 cell = cellpar_to_cell(cell) 

86 elif cell.shape != (3, 3): 

87 raise ValueError( 

88 'Cell must be length 3 sequence, length 6 ' 

89 'sequence or 3x3 matrix!' 

90 ) 

91 

92 cellobj = cls(cell) 

93 return cellobj 

94 

95 @classmethod 

96 def fromcellpar(cls, cellpar, ab_normal=(0, 0, 1), a_direction=None): 

97 """Return new Cell from cell lengths and angles. 

98 

99 See also :func:`~ase.geometry.cell.cellpar_to_cell()`.""" 

100 from ase.geometry.cell import cellpar_to_cell 

101 

102 cell = cellpar_to_cell(cellpar, ab_normal, a_direction) 

103 return cls(cell) 

104 

105 def get_bravais_lattice(self, eps=2e-4, *, pbc=True): 

106 """Return :class:`~ase.lattice.BravaisLattice` for this cell: 

107 

108 >>> from ase.cell import Cell 

109 

110 >>> cell = Cell.fromcellpar([4, 4, 4, 60, 60, 60]) 

111 >>> print(cell.get_bravais_lattice()) 

112 FCC(a=5.65685) 

113 

114 .. note:: The Bravais lattice object follows the AFlow 

115 conventions. ``cell.get_bravais_lattice().tocell()`` may 

116 differ from the original cell by a permutation or other 

117 operation which maps it to the AFlow convention. For 

118 example, the orthorhombic lattice enforces a < b < c. 

119 

120 To build a bandpath for a particular cell, use 

121 :meth:`ase.cell.Cell.bandpath` instead of this method. 

122 This maps the kpoints back to the original input cell. 

123 

124 """ 

125 from ase.lattice import identify_lattice 

126 

127 pbc = self.mask() & pbc2pbc(pbc) 

128 lat, _op = identify_lattice(self, eps=eps, pbc=pbc) 

129 return lat 

130 

131 def bandpath( 

132 self, 

133 path: str | None = None, 

134 npoints: int | None = None, 

135 *, 

136 density: float | None = None, 

137 special_points: Mapping[str, Sequence[float]] | None = None, 

138 eps: float = 2e-4, 

139 pbc: bool | Sequence[bool] = True, 

140 ) -> 'ase.dft.kpoints.BandPath': 

141 """Build a :class:`~ase.dft.kpoints.BandPath` for this cell. 

142 

143 If special points are None, determine the Bravais lattice of 

144 this cell and return a suitable Brillouin zone path with 

145 standard special points. 

146 

147 If special special points are given, interpolate the path 

148 directly from the available data. 

149 

150 Parameters 

151 ---------- 

152 path: string 

153 String of special point names defining the path, e.g. 'GXL'. 

154 npoints: int 

155 Number of points in total. Note that at least one point 

156 is added for each special point in the path. 

157 density: float 

158 density of kpoints along the path in Å⁻¹. 

159 special_points: dict 

160 Dictionary mapping special points to scaled kpoint coordinates. 

161 For example ``{'G': [0, 0, 0], 'X': [1, 0, 0]}``. 

162 eps: float 

163 Tolerance for determining Bravais lattice. 

164 pbc: three bools 

165 Whether cell is periodic in each direction. Normally not 

166 necessary. If cell has three nonzero cell vectors, use 

167 e.g. pbc=[1, 1, 0] to request a 2D bandpath nevertheless. 

168 

169 Example 

170 ------- 

171 

172 >>> from ase.cell import Cell 

173 

174 >>> cell = Cell.fromcellpar([4, 4, 4, 60, 60, 60]) 

175 >>> cell.bandpath('GXW', npoints=20) 

176 BandPath(path='GXW', cell=[3x3], special_points={GKLUWX}, kpts=[20x3]) 

177 

178 """ 

179 # TODO: Combine with the rotation transformation from bandpath() 

180 

181 cell = self.uncomplete(pbc) 

182 

183 if special_points is None: 

184 from ase.lattice import identify_lattice 

185 

186 lat, op = identify_lattice(cell, eps=eps) 

187 bandpath = lat.bandpath(path, npoints=npoints, density=density) 

188 return bandpath.transform(op) 

189 else: 

190 from ase.dft.kpoints import BandPath, resolve_custom_points 

191 

192 path, special_points = resolve_custom_points( 

193 path, special_points, eps=eps 

194 ) 

195 bandpath = BandPath(cell, path=path, special_points=special_points) 

196 return bandpath.interpolate(npoints=npoints, density=density) 

197 

198 def uncomplete(self, pbc): 

199 """Return new cell, zeroing cell vectors where not periodic.""" 

200 _pbc = np.empty(3, bool) 

201 _pbc[:] = pbc 

202 cell = self.copy() 

203 cell[~_pbc] = 0 

204 return cell 

205 

206 def complete(self): 

207 """Convert missing cell vectors into orthogonal unit vectors.""" 

208 from ase.geometry.cell import complete_cell 

209 

210 return Cell(complete_cell(self.array)) 

211 

212 def copy(self): 

213 """Return a copy of this cell.""" 

214 return Cell(self.array.copy()) 

215 

216 def mask(self): 

217 """Boolean mask of which cell vectors are nonzero.""" 

218 return self.any(1) 

219 

220 @property 

221 def rank(self) -> int: 

222 """Return the dimension of the cell. 

223 

224 Equal to the number of nonzero lattice vectors.""" 

225 # The name ndim clashes with ndarray.ndim 

226 return sum(self.mask()) 

227 

228 @property 

229 def orthorhombic(self) -> bool: 

230 """Return whether this cell is represented by a diagonal matrix.""" 

231 from ase.geometry.cell import is_orthorhombic 

232 

233 return is_orthorhombic(self) 

234 

235 def lengths(self): 

236 """Return the length of each lattice vector as an array.""" 

237 return np.linalg.norm(self, axis=1) 

238 

239 def angles(self): 

240 """Return an array with the three angles alpha, beta, and gamma.""" 

241 return self.cellpar()[3:].copy() 

242 

243 def __array__(self, dtype=None, copy=False): 

244 return np.array(self.array, dtype=dtype, copy=copy) 

245 

246 def __bool__(self): 

247 return bool(self.any()) # need to convert from np.bool_ 

248 

249 @property 

250 def volume(self) -> float: 

251 """Get the volume of this cell. 

252 

253 If there are less than 3 lattice vectors, return 0.""" 

254 # Fail or 0 for <3D cells? 

255 # Definitely 0 since this is currently a property. 

256 # I think normally it is more convenient just to get zero 

257 return np.abs(np.linalg.det(self)) 

258 

259 @property 

260 def handedness(self) -> int: 

261 """Sign of the determinant of the matrix of cell vectors. 

262 

263 1 for right-handed cells, -1 for left, and 0 for cells that 

264 do not span three dimensions.""" 

265 return int(np.sign(np.linalg.det(self))) 

266 

267 def scaled_positions(self, positions) -> np.ndarray: 

268 """Calculate scaled positions from Cartesian positions. 

269 

270 The scaled positions are the positions given in the basis 

271 of the cell vectors. For the purpose of defining the basis, cell 

272 vectors that are zero will be replaced by unit vectors as per 

273 :meth:`~ase.cell.Cell.complete`.""" 

274 return np.linalg.solve(self.complete().T, np.transpose(positions)).T 

275 

276 def cartesian_positions(self, scaled_positions) -> np.ndarray: 

277 """Calculate Cartesian positions from scaled positions.""" 

278 return scaled_positions @ self.complete() 

279 

280 def reciprocal(self) -> 'Cell': 

281 """Get reciprocal lattice as a Cell object. 

282 

283 The reciprocal cell is defined such that 

284 

285 cell.reciprocal() @ cell.T == np.diag(cell.mask()) 

286 

287 within machine precision. 

288 

289 Does not include factor of 2 pi.""" 

290 icell = Cell(np.linalg.pinv(self).transpose()) 

291 icell[~self.mask()] = 0.0 # type: ignore[index] 

292 return icell 

293 

294 def normal(self, i): 

295 """Normal vector of the two vectors with index different from i. 

296 

297 This is the cross product of those vectors in cyclic order from i.""" 

298 return np.cross(self[i - 2], self[i - 1]) 

299 

300 def normals(self): 

301 """Normal vectors of each axis as a 3x3 matrix.""" 

302 return np.array([self.normal(i) for i in range(3)]) 

303 

304 def area(self, i): 

305 """Area spanned by the two vectors with index different from i.""" 

306 return np.linalg.norm(self.normal(i)) 

307 

308 def areas(self): 

309 """Areas spanned by cell vector pairs (1, 2), (2, 0), and (0, 1).""" 

310 return np.linalg.norm(self.normals(), axis=1) 

311 

312 def _tostring(self, fmt='g'): 

313 

314 def joinlist(tokens): 

315 text = ', '.join(tokens) 

316 return f'[{text}]' 

317 

318 if self.orthorhombic: 

319 text = joinlist(format(x, fmt) for x in self.lengths()) 

320 else: 

321 text = joinlist( 

322 joinlist(format(x, fmt) for x in v) for v in self.tolist() 

323 ) 

324 

325 return f'Cell({text})' 

326 

327 def __str__(self) -> str: 

328 return self._tostring() 

329 

330 def __repr__(self) -> str: 

331 return self._tostring('') 

332 

333 def niggli_reduce(self, eps=1e-5): 

334 """Niggli reduce this cell, returning a new cell and mapping. 

335 

336 See also :func:`ase.build.tools.niggli_reduce_cell`.""" 

337 from ase.build.tools import niggli_reduce_cell 

338 

339 cell, op = niggli_reduce_cell(self, epsfactor=eps) 

340 result = Cell(cell) 

341 return result, op 

342 

343 def minkowski_reduce(self): 

344 """Minkowski-reduce this cell, returning new cell and mapping. 

345 

346 See also :func:`ase.geometry.minkowski_reduction.minkowski_reduce`.""" 

347 from ase.geometry.minkowski_reduction import minkowski_reduce 

348 

349 cell, op = minkowski_reduce(self, self.mask()) 

350 result = Cell(cell) 

351 return result, op 

352 

353 def permute_axes(self, permutation): 

354 """Permute axes of cell. 

355 

356 Examples 

357 -------- 

358 

359 >>> from ase.cell import Cell 

360 

361 >>> cell = Cell.fromcellpar([2.0, 3.0, 4.0]) 

362 >>> cell 

363 Cell([2.0, 3.0, 4.0]) 

364 >>> cell.permute_axes([0, 2, 1]) 

365 Cell([2.0, 4.0, 3.0]) 

366 """ 

367 assert (np.sort(permutation) == np.arange(3)).all() 

368 permuted = Cell(self[permutation][:, permutation]) 

369 return permuted 

370 

371 def standard_form(self, form='lower'): 

372 """Rotate axes such that unit cell is lower/upper triangular. The cell 

373 handedness is preserved. 

374 

375 A lower-triangular cell with positive diagonal entries is a canonical 

376 (i.e. unique) description. For a left-handed cell the diagonal entries 

377 are negative. 

378 

379 Parameters 

380 ---------- 

381 form: str 

382 'lower' or 'upper' triangular form. The default is 'lower'. 

383 

384 Returns 

385 ------- 

386 rcell: the standardized cell object 

387 

388 Q: ndarray 

389 The orthogonal transformation. Here, rcell @ Q = cell, where cell 

390 is the input cell and rcell is the lower triangular (output) cell. 

391 """ 

392 

393 sign = self.handedness 

394 if sign == 0: 

395 sign = 1 

396 

397 # LQ decomposition provides an axis-aligned description of the cell. 

398 # Q is an orthogonal matrix and L is a lower triangular matrix. The 

399 # decomposition is a unique description if the diagonal elements are 

400 # all positive (negative for a left-handed cell). 

401 if form == 'lower': 

402 Q, L = np.linalg.qr(self.T) 

403 Q = Q.T 

404 L = L.T 

405 elif form == 'upper': 

406 Q, L = np.linalg.qr(self.T[::-1, ::-1]) 

407 Q = Q.T[::-1, ::-1] 

408 L = L.T[::-1, ::-1] 

409 else: 

410 raise ValueError('form must be either "lower" or "upper"') 

411 

412 # correct the signs of the diagonal elements 

413 signs = np.sign(np.diag(L)) 

414 indices = np.where(signs == 0)[0] 

415 signs[indices] = 1 

416 indices = np.where(signs != sign)[0] 

417 L[:, indices] *= -1 

418 Q[indices] *= -1 

419 return Cell(L), Q 

420 

421 # XXX We want a reduction function that brings the cell into 

422 # standard form as defined by Setyawan and Curtarolo.