Coverage for ase/lattice/__init__.py: 96.74%

767 statements  

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

1from abc import ABC, abstractmethod 

2from dataclasses import dataclass 

3from functools import cached_property 

4 

5import numpy as np 

6 

7from ase.cell import Cell 

8from ase.dft.kpoints import BandPath, parse_path_string, sc_special_points 

9from ase.utils import pbc2pbc 

10 

11_degrees = np.pi / 180 

12 

13 

14def lattice_attr(name): 

15 def getter(self): 

16 try: 

17 return self._parameters[name] 

18 except KeyError: 

19 raise AttributeError(name) from None 

20 

21 getter.__name__ = name 

22 return property(getter) 

23 

24 

25class BravaisLattice(ABC): 

26 """Represent Bravais lattices and data related to the Brillouin zone. 

27 

28 There are 14 3D Bravais classes: CUB, FCC, BCC, ..., and TRI, and 

29 five 2D classes. 

30 

31 Each class stores basic static information: 

32 

33 >>> from ase.lattice import FCC, MCL 

34 >>> FCC.name 

35 'FCC' 

36 >>> FCC.longname 

37 'face-centred cubic' 

38 >>> FCC.pearson_symbol 

39 'cF' 

40 >>> MCL.parameters 

41 ('a', 'b', 'c', 'alpha') 

42 

43 Each class can be instantiated with the specific lattice parameters 

44 that apply to that lattice: 

45 

46 >>> MCL(3, 4, 5, 80) 

47 MCL(a=3, b=4, c=5, alpha=80) 

48 

49 """ 

50 

51 # These parameters can be set by the @bravais decorator for a subclass. 

52 # (We could also use metaclasses to do this, but that's more abstract) 

53 # 

54 # We have to fight mypy so now we actually set initial values that are 

55 # not None, unfortunately. 

56 name: str = '' # e.g. 'CUB', 'BCT', 'ORCF', ... 

57 longname: str = '' # e.g. 'cubic', 'body-centred tetragonal', ... 

58 parameters: tuple = tuple() # e.g. ('a', 'c') 

59 variants: dict | None = None # e.g. {'BCT1': <variant object>, 

60 # 'BCT2': <variant object>} 

61 ndim: int = 0 

62 conventional_cls: str | None = None 

63 

64 def __init__(self, **kwargs): 

65 p = {} 

66 eps = kwargs.pop('eps', 2e-4) 

67 for k, v in kwargs.items(): 

68 p[k] = float(v) 

69 assert set(p) == set(self.parameters) 

70 self._parameters = p 

71 self._eps = eps 

72 

73 if len(self.variants) == 1: 

74 # If there's only one it has the same name as the lattice type 

75 self._variant = self.variants[self.name] 

76 else: 

77 name = self._variant_name(**self._parameters) 

78 self._variant = self.variants[name] 

79 

80 @property 

81 def variant(self) -> str: 

82 """Return name of lattice variant. 

83 

84 >>> from ase.lattice import BCT 

85 

86 >>> BCT(3, 5).variant 

87 'BCT2' 

88 """ 

89 return self._variant.name 

90 

91 def vars(self) -> dict[str, float]: 

92 """Get parameter names and values of this lattice as a dictionary.""" 

93 return dict(self._parameters) 

94 

95 def conventional(self) -> 'BravaisLattice': 

96 """Get the conventional cell corresponding to this lattice.""" 

97 assert self.conventional_cls is not None 

98 cls = bravais_lattices[self.conventional_cls] 

99 return cls(**self._parameters) 

100 

101 def tocell(self) -> Cell: 

102 """Return this lattice as a :class:`~ase.cell.Cell` object.""" 

103 cell = self._cell(**self._parameters) 

104 return Cell(cell) 

105 

106 def cellpar(self) -> np.ndarray: 

107 """Get cell lengths and angles as array of length 6. 

108 

109 See :func:`ase.geometry.Cell.cellpar`.""" 

110 # (Just a brute-force implementation) 

111 cell = self.tocell() 

112 return cell.cellpar() 

113 

114 @property 

115 def special_path(self) -> str: 

116 """Get default special k-point path for this lattice as a string. 

117 

118 >>> BCT(3, 5).special_path 

119 'GXYSGZS1NPY1Z,XP' 

120 """ 

121 return self._variant.special_path 

122 

123 @property 

124 def special_point_names(self) -> list[str]: 

125 """Return all special point names as a list of strings. 

126 

127 >>> from ase.lattice import BCT 

128 

129 >>> BCT(3, 5).special_point_names 

130 ['G', 'N', 'P', 'S', 'S1', 'X', 'Y', 'Y1', 'Z'] 

131 """ 

132 labels = parse_path_string(self._variant.special_point_names) 

133 assert len(labels) == 1 # list of lists 

134 return labels[0] 

135 

136 def get_special_points_array(self) -> np.ndarray: 

137 """Return all special points for this lattice as an array. 

138 

139 Ordering is consistent with special_point_names.""" 

140 if self._variant.special_points is not None: 

141 # Fixed dictionary of special points 

142 d = self.get_special_points() 

143 labels = self.special_point_names 

144 assert len(d) == len(labels) 

145 points = np.empty((len(d), 3)) 

146 for i, label in enumerate(labels): 

147 points[i] = d[label] 

148 return points 

149 

150 # Special points depend on lattice parameters: 

151 points = self._special_points(variant=self._variant, **self._parameters) 

152 assert len(points) == len(self.special_point_names) 

153 return np.array(points) 

154 

155 def get_special_points(self) -> dict[str, np.ndarray]: 

156 """Return a dictionary of named special k-points for this lattice.""" 

157 if self._variant.special_points is not None: 

158 return self._variant.special_points 

159 

160 labels = self.special_point_names 

161 points = self.get_special_points_array() 

162 

163 return dict(zip(labels, points)) 

164 

165 def plot_bz(self, path=None, special_points=None, **plotkwargs): 

166 """Plot the reciprocal cell and default bandpath.""" 

167 # Create a generic bandpath (no interpolated kpoints): 

168 bandpath = self.bandpath( 

169 path=path, special_points=special_points, npoints=0 

170 ) 

171 return bandpath.plot(dimension=self.ndim, **plotkwargs) 

172 

173 def bandpath( 

174 self, path=None, npoints=None, special_points=None, density=None 

175 ) -> BandPath: 

176 """Return a :class:`~ase.dft.kpoints.BandPath` for this lattice. 

177 

178 See :meth:`ase.cell.Cell.bandpath` for description of parameters. 

179 

180 >>> from ase.lattice import BCT 

181 

182 >>> BCT(3, 5).bandpath() 

183 BandPath(path='GXYSGZS1NPY1Z,XP', cell=[3x3], \ 

184special_points={GNPSS1XYY1Z}, kpts=[51x3]) 

185 

186 .. note:: This produces the standard band path following AFlow 

187 conventions. If your cell does not follow this convention, 

188 you will need :meth:`ase.cell.Cell.bandpath` instead or 

189 the kpoints may not correspond to your particular cell. 

190 

191 """ 

192 if special_points is None: 

193 special_points = self.get_special_points() 

194 

195 if path is None: 

196 path = self._variant.special_path 

197 elif not isinstance(path, str): 

198 from ase.dft.kpoints import resolve_custom_points 

199 

200 path, special_points = resolve_custom_points( 

201 path, special_points, self._eps 

202 ) 

203 

204 cell = self.tocell() 

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

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

207 

208 @abstractmethod 

209 def _cell(self, **kwargs): 

210 """Return a Cell object from this Bravais lattice. 

211 

212 Arguments are the dictionary of Bravais parameters.""" 

213 

214 def _special_points(self, **kwargs): 

215 """Return the special point coordinates as an npoints x 3 sequence. 

216 

217 Subclasses typically return a nested list. 

218 

219 Ordering must be same as kpoint labels. 

220 

221 Arguments are the dictionary of Bravais parameters and the variant.""" 

222 raise NotImplementedError 

223 

224 def _variant_name(self, **kwargs): 

225 """Return the name (e.g. 'ORCF3') of variant. 

226 

227 Arguments will be the dictionary of Bravais parameters.""" 

228 raise NotImplementedError 

229 

230 def __format__(self, spec): 

231 tokens = [] 

232 if not spec: 

233 spec = '.6g' 

234 template = f'{{}}={{:{spec}}}' 

235 

236 for name in self.parameters: 

237 value = self._parameters[name] 

238 tokens.append(template.format(name, value)) 

239 return '{}({})'.format(self.name, ', '.join(tokens)) 

240 

241 def __str__(self) -> str: 

242 return self.__format__('') 

243 

244 def __repr__(self) -> str: 

245 return self.__format__('.20g') 

246 

247 def description(self) -> str: 

248 """Return complete description of lattice and Brillouin zone.""" 

249 points = self.get_special_points() 

250 labels = self.special_point_names 

251 

252 coordstring = '\n'.join( 

253 [ 

254 ' {:2s} {:7.4f} {:7.4f} {:7.4f}'.format( 

255 label, *points[label] 

256 ) 

257 for label in labels 

258 ] 

259 ) 

260 

261 string = """\ 

262{repr} 

263 {variant} 

264 Special point coordinates: 

265{special_points} 

266""".format(repr=str(self), variant=self._variant, special_points=coordstring) 

267 return string 

268 

269 @classmethod 

270 def type_description(cls): 

271 """Return complete description of this Bravais lattice type.""" 

272 desc = """\ 

273Lattice name: {name} 

274 Long name: {longname} 

275 Parameters: {parameters} 

276""".format(**vars(cls)) 

277 

278 chunks = [desc] 

279 for name in cls.variant_names: 

280 var = cls.variants[name] 

281 txt = str(var) 

282 lines = [' ' + L for L in txt.splitlines()] 

283 lines.append('') 

284 chunks.extend(lines) 

285 

286 return '\n'.join(chunks) 

287 

288 

289class Variant: 

290 variant_desc = """\ 

291Variant name: {name} 

292 Special point names: {special_point_names} 

293 Default path: {special_path} 

294""" 

295 

296 def __init__( 

297 self, name, special_point_names, special_path, special_points=None 

298 ): 

299 self.name = name 

300 self.special_point_names = special_point_names 

301 self.special_path = special_path 

302 if special_points is not None: 

303 special_points = dict(special_points) 

304 for key, value in special_points.items(): 

305 special_points[key] = np.array(value) 

306 self.special_points = special_points 

307 # XXX Should make special_points available as a single array as well 

308 # (easier to transform that way) 

309 

310 def __str__(self) -> str: 

311 return self.variant_desc.format(**vars(self)) 

312 

313 

314bravais_names: list[str] = [] 

315bravais_lattices: dict[str, type] = {} 

316bravais_classes: dict[str, type] = {} 

317 

318 

319def bravaisclass( 

320 longname, 

321 crystal_family, 

322 lattice_system, 

323 pearson_symbol, 

324 parameters, 

325 variants, 

326 ndim=3, 

327): 

328 """Decorator for Bravais lattice classes. 

329 

330 This sets a number of class variables and processes the information 

331 about different variants into a list of Variant objects.""" 

332 

333 def decorate(cls): 

334 btype = cls.__name__ 

335 cls.name = btype 

336 cls.longname = longname 

337 cls.crystal_family = crystal_family 

338 cls.lattice_system = lattice_system 

339 cls.pearson_symbol = pearson_symbol 

340 cls.parameters = tuple(parameters) 

341 cls.variant_names = [] 

342 cls.variants = {} 

343 cls.ndim = ndim 

344 

345 for parameter in parameters: 

346 setattr(cls, parameter, lattice_attr(parameter)) 

347 

348 for [ 

349 name, 

350 special_point_names, 

351 special_path, 

352 special_points, 

353 ] in variants: 

354 cls.variant_names.append(name) 

355 cls.variants[name] = Variant( 

356 name, special_point_names, special_path, special_points 

357 ) 

358 

359 # Register in global list and dictionary 

360 bravais_names.append(btype) 

361 bravais_lattices[btype] = cls 

362 bravais_classes[pearson_symbol] = cls 

363 return cls 

364 

365 return decorate 

366 

367 

368# Common mappings of primitive to conventional cells: 

369_identity = np.identity(3, int) 

370_fcc_map = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]) 

371_bcc_map = np.array([[-1, 1, 1], [1, -1, 1], [1, 1, -1]]) 

372 

373 

374class UnconventionalLattice(ValueError): 

375 pass 

376 

377 

378class Cubic(BravaisLattice): 

379 """Abstract class for cubic lattices.""" 

380 

381 conventional_cls = 'CUB' 

382 

383 def __init__(self, a): 

384 super().__init__(a=a) 

385 

386 

387@bravaisclass( 

388 'primitive cubic', 

389 'cubic', 

390 'cubic', 

391 'cP', 

392 'a', 

393 [['CUB', 'GXRM', 'GXMGRX,MR', sc_special_points['cubic']]], 

394) 

395class CUB(Cubic): 

396 conventional_cellmap = _identity 

397 

398 def _cell(self, a): 

399 return a * np.eye(3) 

400 

401 

402@bravaisclass( 

403 'face-centred cubic', 

404 'cubic', 

405 'cubic', 

406 'cF', 

407 'a', 

408 [['FCC', 'GKLUWX', 'GXWKGLUWLK,UX', sc_special_points['fcc']]], 

409) 

410class FCC(Cubic): 

411 conventional_cellmap = _bcc_map 

412 

413 def _cell(self, a): 

414 return 0.5 * np.array([[0.0, a, a], [a, 0, a], [a, a, 0]]) 

415 

416 

417@bravaisclass( 

418 'body-centred cubic', 

419 'cubic', 

420 'cubic', 

421 'cI', 

422 'a', 

423 [['BCC', 'GHPN', 'GHNGPH,PN', sc_special_points['bcc']]], 

424) 

425class BCC(Cubic): 

426 conventional_cellmap = _fcc_map 

427 

428 def _cell(self, a): 

429 return 0.5 * np.array([[-a, a, a], [a, -a, a], [a, a, -a]]) 

430 

431 

432@bravaisclass( 

433 'primitive tetragonal', 

434 'tetragonal', 

435 'tetragonal', 

436 'tP', 

437 'ac', 

438 [['TET', 'GAMRXZ', 'GXMGZRAZ,XR,MA', sc_special_points['tetragonal']]], 

439) 

440class TET(BravaisLattice): 

441 conventional_cls = 'TET' 

442 conventional_cellmap = _identity 

443 

444 def __init__(self, a, c): 

445 super().__init__(a=a, c=c) 

446 

447 def _cell(self, a, c): 

448 return np.diag(np.array([a, a, c])) 

449 

450 

451# XXX in BCT2 we use S for Sigma. 

452# Also in other places I think 

453@bravaisclass( 

454 'body-centred tetragonal', 

455 'tetragonal', 

456 'tetragonal', 

457 'tI', 

458 'ac', 

459 [ 

460 ['BCT1', 'GMNPXZZ1', 'GXMGZPNZ1M,XP', None], 

461 ['BCT2', 'GNPSS1XYY1Z', 'GXYSGZS1NPY1Z,XP', None], 

462 ], 

463) 

464class BCT(BravaisLattice): 

465 conventional_cls = 'TET' 

466 conventional_cellmap = _fcc_map 

467 

468 def __init__(self, a, c): 

469 super().__init__(a=a, c=c) 

470 

471 def _cell(self, a, c): 

472 return 0.5 * np.array([[-a, a, c], [a, -a, c], [a, a, -c]]) 

473 

474 def _variant_name(self, a, c): 

475 return 'BCT1' if c < a else 'BCT2' 

476 

477 def _special_points(self, a, c, variant): 

478 a2 = a * a 

479 c2 = c * c 

480 

481 assert variant.name in self.variants 

482 

483 if variant.name == 'BCT1': 

484 eta = 0.25 * (1 + c2 / a2) 

485 points = [ 

486 [0, 0, 0], 

487 [-0.5, 0.5, 0.5], 

488 [0.0, 0.5, 0.0], 

489 [0.25, 0.25, 0.25], 

490 [0.0, 0.0, 0.5], 

491 [eta, eta, -eta], 

492 [-eta, 1 - eta, eta], 

493 ] 

494 else: 

495 eta = 0.25 * (1 + a2 / c2) # Not same eta as BCT1! 

496 zeta = 0.5 * a2 / c2 

497 points = [ 

498 [0.0, 0.0, 0.0], 

499 [0.0, 0.5, 0.0], 

500 [0.25, 0.25, 0.25], 

501 [-eta, eta, eta], 

502 [eta, 1 - eta, -eta], 

503 [0.0, 0.0, 0.5], 

504 [-zeta, zeta, 0.5], 

505 [0.5, 0.5, -zeta], 

506 [0.5, 0.5, -0.5], 

507 ] 

508 return points 

509 

510 

511def check_orc(a, b, c): 

512 if not a < b < c: 

513 raise UnconventionalLattice( 

514 'Expected a < b < c, got {}, {}, {}'.format(a, b, c) 

515 ) 

516 

517 

518class Orthorhombic(BravaisLattice): 

519 """Abstract class for orthorhombic types.""" 

520 

521 def __init__(self, a, b, c): 

522 check_orc(a, b, c) 

523 super().__init__(a=a, b=b, c=c) 

524 

525 

526@bravaisclass( 

527 'primitive orthorhombic', 

528 'orthorhombic', 

529 'orthorhombic', 

530 'oP', 

531 'abc', 

532 [ 

533 [ 

534 'ORC', 

535 'GRSTUXYZ', 

536 'GXSYGZURTZ,YT,UX,SR', 

537 sc_special_points['orthorhombic'], 

538 ] 

539 ], 

540) 

541class ORC(Orthorhombic): 

542 conventional_cls = 'ORC' 

543 conventional_cellmap = _identity 

544 

545 def _cell(self, a, b, c): 

546 return np.diag([a, b, c]).astype(float) 

547 

548 

549@bravaisclass( 

550 'face-centred orthorhombic', 

551 'orthorhombic', 

552 'orthorhombic', 

553 'oF', 

554 'abc', 

555 [ 

556 ['ORCF1', 'GAA1LTXX1YZ', 'GYTZGXA1Y,TX1,XAZ,LG', None], 

557 ['ORCF2', 'GCC1DD1LHH1XYZ', 'GYCDXGZD1HC,C1Z,XH1,HY,LG', None], 

558 ['ORCF3', 'GAA1LTXX1YZ', 'GYTZGXA1Y,XAZ,LG', None], 

559 ], 

560) 

561class ORCF(Orthorhombic): 

562 conventional_cls = 'ORC' 

563 conventional_cellmap = _bcc_map 

564 

565 def _cell(self, a, b, c): 

566 return 0.5 * np.array([[0, b, c], [a, 0, c], [a, b, 0]]) 

567 

568 def _special_points(self, a, b, c, variant): 

569 a2 = a * a 

570 b2 = b * b 

571 c2 = c * c 

572 xminus = 0.25 * (1 + a2 / b2 - a2 / c2) 

573 xplus = 0.25 * (1 + a2 / b2 + a2 / c2) 

574 

575 if variant.name == 'ORCF1' or variant.name == 'ORCF3': 

576 zeta = xminus 

577 eta = xplus 

578 

579 points = [ 

580 [0, 0, 0], 

581 [0.5, 0.5 + zeta, zeta], 

582 [0.5, 0.5 - zeta, 1 - zeta], 

583 [0.5, 0.5, 0.5], 

584 [1.0, 0.5, 0.5], 

585 [0.0, eta, eta], 

586 [1.0, 1 - eta, 1 - eta], 

587 [0.5, 0, 0.5], 

588 [0.5, 0.5, 0], 

589 ] 

590 else: 

591 assert variant.name == 'ORCF2' 

592 phi = 0.25 * (1 + c2 / b2 - c2 / a2) 

593 delta = 0.25 * (1 + b2 / a2 - b2 / c2) 

594 eta = xminus 

595 

596 points = [ 

597 [0, 0, 0], 

598 [0.5, 0.5 - eta, 1 - eta], 

599 [0.5, 0.5 + eta, eta], 

600 [0.5 - delta, 0.5, 1 - delta], 

601 [0.5 + delta, 0.5, delta], 

602 [0.5, 0.5, 0.5], 

603 [1 - phi, 0.5 - phi, 0.5], 

604 [phi, 0.5 + phi, 0.5], 

605 [0.0, 0.5, 0.5], 

606 [0.5, 0.0, 0.5], 

607 [0.5, 0.5, 0.0], 

608 ] 

609 

610 return points 

611 

612 def _variant_name(self, a, b, c): 

613 diff = 1.0 / (a * a) - 1.0 / (b * b) - 1.0 / (c * c) 

614 if abs(diff) < self._eps: 

615 return 'ORCF3' 

616 return 'ORCF1' if diff > 0 else 'ORCF2' 

617 

618 

619@bravaisclass( 

620 'body-centred orthorhombic', 

621 'orthorhombic', 

622 'orthorhombic', 

623 'oI', 

624 'abc', 

625 [['ORCI', 'GLL1L2RSTWXX1YY1Z', 'GXLTWRX1ZGYSW,L1Y,Y1Z', None]], 

626) 

627class ORCI(Orthorhombic): 

628 conventional_cls = 'ORC' 

629 conventional_cellmap = _fcc_map 

630 

631 def _cell(self, a, b, c): 

632 return 0.5 * np.array([[-a, b, c], [a, -b, c], [a, b, -c]]) 

633 

634 def _special_points(self, a, b, c, variant): 

635 a2 = a**2 

636 b2 = b**2 

637 c2 = c**2 

638 

639 zeta = 0.25 * (1 + a2 / c2) 

640 eta = 0.25 * (1 + b2 / c2) 

641 delta = 0.25 * (b2 - a2) / c2 

642 mu = 0.25 * (a2 + b2) / c2 

643 

644 points = [ 

645 [0.0, 0.0, 0.0], 

646 [-mu, mu, 0.5 - delta], 

647 [mu, -mu, 0.5 + delta], 

648 [0.5 - delta, 0.5 + delta, -mu], 

649 [0, 0.5, 0], 

650 [0.5, 0, 0], 

651 [0.0, 0.0, 0.5], 

652 [0.25, 0.25, 0.25], 

653 [-zeta, zeta, zeta], 

654 [zeta, 1 - zeta, -zeta], 

655 [eta, -eta, eta], 

656 [1 - eta, eta, -eta], 

657 [0.5, 0.5, -0.5], 

658 ] 

659 return points 

660 

661 

662@bravaisclass( 

663 'base-centred orthorhombic', 

664 'orthorhombic', 

665 'orthorhombic', 

666 'oC', 

667 'abc', 

668 [['ORCC', 'GAA1RSTXX1YZ', 'GXSRAZGYX1A1TY,ZT', None]], 

669) 

670class ORCC(BravaisLattice): 

671 conventional_cls = 'ORC' 

672 conventional_cellmap = np.array([[1, 1, 0], [-1, 1, 0], [0, 0, 1]]) 

673 

674 def __init__(self, a, b, c): 

675 # ORCC is the only ORCx lattice with a<b and not a<b<c 

676 if a >= b: 

677 raise UnconventionalLattice(f'Expected a < b, got a={a}, b={b}') 

678 super().__init__(a=a, b=b, c=c) 

679 

680 def _cell(self, a, b, c): 

681 return np.array( 

682 [[0.5 * a, -0.5 * b, 0], [0.5 * a, 0.5 * b, 0], [0, 0, c]] 

683 ) 

684 

685 def _special_points(self, a, b, c, variant): 

686 zeta = 0.25 * (1 + a * a / (b * b)) 

687 points = [ 

688 [0, 0, 0], 

689 [zeta, zeta, 0.5], 

690 [-zeta, 1 - zeta, 0.5], 

691 [0, 0.5, 0.5], 

692 [0, 0.5, 0], 

693 [-0.5, 0.5, 0.5], 

694 [zeta, zeta, 0], 

695 [-zeta, 1 - zeta, 0], 

696 [-0.5, 0.5, 0], 

697 [0, 0, 0.5], 

698 ] 

699 return points 

700 

701 

702@bravaisclass( 

703 'primitive hexagonal', 

704 'hexagonal', 

705 'hexagonal', 

706 'hP', 

707 'ac', 

708 [['HEX', 'GMKALH', 'GMKGALHA,LM,KH', sc_special_points['hexagonal']]], 

709) 

710class HEX(BravaisLattice): 

711 conventional_cls = 'HEX' 

712 conventional_cellmap = _identity 

713 

714 def __init__(self, a, c): 

715 super().__init__(a=a, c=c) 

716 

717 def _cell(self, a, c): 

718 x = 0.5 * np.sqrt(3) 

719 return np.array( 

720 [[0.5 * a, -x * a, 0], [0.5 * a, x * a, 0], [0.0, 0.0, c]] 

721 ) 

722 

723 

724@bravaisclass( 

725 'primitive rhombohedral', 

726 'hexagonal', 

727 'rhombohedral', 

728 'hR', 

729 ('a', 'alpha'), 

730 [ 

731 ['RHL1', 'GBB1FLL1PP1P2QXZ', 'GLB1,BZGX,QFP1Z,LP', None], 

732 ['RHL2', 'GFLPP1QQ1Z', 'GPZQGFP1Q1LZ', None], 

733 ], 

734) 

735class RHL(BravaisLattice): 

736 conventional_cls = 'RHL' 

737 conventional_cellmap = _identity 

738 

739 def __init__(self, a, alpha): 

740 if alpha >= 120: 

741 raise UnconventionalLattice( 

742 'Need alpha < 120 degrees, got {}'.format(alpha) 

743 ) 

744 super().__init__(a=a, alpha=alpha) 

745 

746 def _cell(self, a, alpha): 

747 alpha *= np.pi / 180 

748 acosa = a * np.cos(alpha) 

749 acosa2 = a * np.cos(0.5 * alpha) 

750 asina2 = a * np.sin(0.5 * alpha) 

751 acosfrac = acosa / acosa2 

752 xx = 1 - acosfrac**2 

753 assert xx > 0.0 

754 return np.array( 

755 [ 

756 [acosa2, -asina2, 0], 

757 [acosa2, asina2, 0], 

758 [a * acosfrac, 0, a * xx**0.5], 

759 ] 

760 ) 

761 

762 def _variant_name(self, a, alpha): 

763 return 'RHL1' if alpha < 90 else 'RHL2' 

764 

765 def _special_points(self, a, alpha, variant): 

766 if variant.name == 'RHL1': 

767 cosa = np.cos(alpha * _degrees) 

768 eta = (1 + 4 * cosa) / (2 + 4 * cosa) 

769 nu = 0.75 - 0.5 * eta 

770 points = [ 

771 [0, 0, 0], 

772 [eta, 0.5, 1 - eta], 

773 [0.5, 1 - eta, eta - 1], 

774 [0.5, 0.5, 0], 

775 [0.5, 0, 0], 

776 [0, 0, -0.5], 

777 [eta, nu, nu], 

778 [1 - nu, 1 - nu, 1 - eta], 

779 [nu, nu, eta - 1], 

780 [1 - nu, nu, 0], 

781 [nu, 0, -nu], 

782 [0.5, 0.5, 0.5], 

783 ] 

784 else: 

785 eta = 1 / (2 * np.tan(alpha * _degrees / 2) ** 2) 

786 nu = 0.75 - 0.5 * eta 

787 points = [ 

788 [0, 0, 0], 

789 [0.5, -0.5, 0], 

790 [0.5, 0, 0], 

791 [1 - nu, -nu, 1 - nu], 

792 [nu, nu - 1, nu - 1], 

793 [eta, eta, eta], 

794 [1 - eta, -eta, -eta], 

795 [0.5, -0.5, 0.5], 

796 ] 

797 return points 

798 

799 

800def check_mcl(a, b, c, alpha): 

801 if b > c or alpha >= 90: 

802 raise UnconventionalLattice( 

803 'Expected b <= c, alpha < 90; ' 

804 'got a={}, b={}, c={}, alpha={}'.format(a, b, c, alpha) 

805 ) 

806 

807 

808@bravaisclass( 

809 'primitive monoclinic', 

810 'monoclinic', 

811 'monoclinic', 

812 'mP', 

813 ('a', 'b', 'c', 'alpha'), 

814 [['MCL', 'GACDD1EHH1H2MM1M2XYY1Z', 'GYHCEM1AXH1,MDZ,YD', None]], 

815) 

816class MCL(BravaisLattice): 

817 conventional_cls = 'MCL' 

818 conventional_cellmap = _identity 

819 

820 def __init__(self, a, b, c, alpha): 

821 check_mcl(a, b, c, alpha) 

822 super().__init__(a=a, b=b, c=c, alpha=alpha) 

823 

824 def _cell(self, a, b, c, alpha): 

825 alpha *= _degrees 

826 return np.array( 

827 [[a, 0, 0], [0, b, 0], [0, c * np.cos(alpha), c * np.sin(alpha)]] 

828 ) 

829 

830 def _special_points(self, a, b, c, alpha, variant): 

831 cosa = np.cos(alpha * _degrees) 

832 eta = (1 - b * cosa / c) / (2 * np.sin(alpha * _degrees) ** 2) 

833 nu = 0.5 - eta * c * cosa / b 

834 

835 points = [ 

836 [0, 0, 0], 

837 [0.5, 0.5, 0], 

838 [0, 0.5, 0.5], 

839 [0.5, 0, 0.5], 

840 [0.5, 0, -0.5], 

841 [0.5, 0.5, 0.5], 

842 [0, eta, 1 - nu], 

843 [0, 1 - eta, nu], 

844 [0, eta, -nu], 

845 [0.5, eta, 1 - nu], 

846 [0.5, 1 - eta, nu], 

847 [0.5, eta, -nu], 

848 [0, 0.5, 0], 

849 [0, 0, 0.5], 

850 [0, 0, -0.5], 

851 [0.5, 0, 0], 

852 ] 

853 return points 

854 

855 def _variant_name(self, a, b, c, alpha): 

856 check_mcl(a, b, c, alpha) 

857 return 'MCL' 

858 

859 

860@bravaisclass( 

861 'base-centred monoclinic', 

862 'monoclinic', 

863 'monoclinic', 

864 'mC', 

865 ('a', 'b', 'c', 'alpha'), 

866 [ 

867 ['MCLC1', 'GNN1FF1F2F3II1LMXX1X2YY1Z', 'GYFLI,I1ZF1,YX1,XGN,MG', None], 

868 ['MCLC2', 'GNN1FF1F2F3II1LMXX1X2YY1Z', 'GYFLI,I1ZF1,NGM', None], 

869 ['MCLC3', 'GFF1F2HH1H2IMNN1XYY1Y2Y3Z', 'GYFHZIF1,H1Y1XGN,MG', None], 

870 ['MCLC4', 'GFF1F2HH1H2IMNN1XYY1Y2Y3Z', 'GYFHZI,H1Y1XGN,MG', None], 

871 [ 

872 'MCLC5', 

873 'GFF1F2HH1H2II1LMNN1XYY1Y2Y3Z', 

874 'GYFLI,I1ZHF1,H1Y1XGN,MG', 

875 None, 

876 ], 

877 ], 

878) 

879class MCLC(BravaisLattice): 

880 conventional_cls = 'MCL' 

881 conventional_cellmap = np.array([[1, -1, 0], [1, 1, 0], [0, 0, 1]]) 

882 

883 def __init__(self, a, b, c, alpha): 

884 check_mcl(a, b, c, alpha) 

885 super().__init__(a=a, b=b, c=c, alpha=alpha) 

886 

887 def _cell(self, a, b, c, alpha): 

888 alpha *= np.pi / 180 

889 return np.array( 

890 [ 

891 [0.5 * a, 0.5 * b, 0], 

892 [-0.5 * a, 0.5 * b, 0], 

893 [0, c * np.cos(alpha), c * np.sin(alpha)], 

894 ] 

895 ) 

896 

897 def _variant_name(self, a, b, c, alpha): 

898 # from ase.geometry.cell import mclc 

899 # okay, this is a bit hacky 

900 

901 # We need the same parameters here as when determining the points. 

902 # Right now we just repeat the code: 

903 check_mcl(a, b, c, alpha) 

904 

905 a2 = a * a 

906 b2 = b * b 

907 cosa = np.cos(alpha * _degrees) 

908 sina = np.sin(alpha * _degrees) 

909 sina2 = sina**2 

910 

911 cell = self.tocell() 

912 lengths_angles = Cell(cell.reciprocal()).cellpar() 

913 

914 kgamma = lengths_angles[-1] 

915 

916 eps = self._eps 

917 # We should not compare angles in degrees versus lengths with 

918 # the same precision. 

919 if abs(kgamma - 90) < eps: 

920 variant = 2 

921 elif kgamma > 90: 

922 variant = 1 

923 elif kgamma < 90: 

924 num = b * cosa / c + b2 * sina2 / a2 

925 if abs(num - 1) < eps: 

926 variant = 4 

927 elif num < 1: 

928 variant = 3 

929 else: 

930 variant = 5 

931 variant = 'MCLC' + str(variant) 

932 return variant 

933 

934 def _special_points(self, a, b, c, alpha, variant): 

935 variant = int(variant.name[-1]) 

936 

937 a2 = a * a 

938 b2 = b * b 

939 # c2 = c * c 

940 cosa = np.cos(alpha * _degrees) 

941 sina = np.sin(alpha * _degrees) 

942 sina2 = sina**2 

943 

944 if variant == 1 or variant == 2: 

945 zeta = (2 - b * cosa / c) / (4 * sina2) 

946 eta = 0.5 + 2 * zeta * c * cosa / b 

947 psi = 0.75 - a2 / (4 * b2 * sina * sina) 

948 phi = psi + (0.75 - psi) * b * cosa / c 

949 

950 points = [ 

951 [0, 0, 0], 

952 [0.5, 0, 0], 

953 [0, -0.5, 0], 

954 [1 - zeta, 1 - zeta, 1 - eta], 

955 [zeta, zeta, eta], 

956 [-zeta, -zeta, 1 - eta], 

957 [1 - zeta, -zeta, 1 - eta], 

958 [phi, 1 - phi, 0.5], 

959 [1 - phi, phi - 1, 0.5], 

960 [0.5, 0.5, 0.5], 

961 [0.5, 0, 0.5], 

962 [1 - psi, psi - 1, 0], 

963 [psi, 1 - psi, 0], 

964 [psi - 1, -psi, 0], 

965 [0.5, 0.5, 0], 

966 [-0.5, -0.5, 0], 

967 [0, 0, 0.5], 

968 ] 

969 elif variant == 3 or variant == 4: 

970 mu = 0.25 * (1 + b2 / a2) 

971 delta = b * c * cosa / (2 * a2) 

972 zeta = mu - 0.25 + (1 - b * cosa / c) / (4 * sina2) 

973 eta = 0.5 + 2 * zeta * c * cosa / b 

974 phi = 1 + zeta - 2 * mu 

975 psi = eta - 2 * delta 

976 

977 points = [ 

978 [0, 0, 0], 

979 [1 - phi, 1 - phi, 1 - psi], 

980 [phi, phi - 1, psi], 

981 [1 - phi, -phi, 1 - psi], 

982 [zeta, zeta, eta], 

983 [1 - zeta, -zeta, 1 - eta], 

984 [-zeta, -zeta, 1 - eta], 

985 [0.5, -0.5, 0.5], 

986 [0.5, 0, 0.5], 

987 [0.5, 0, 0], 

988 [0, -0.5, 0], 

989 [0.5, -0.5, 0], 

990 [mu, mu, delta], 

991 [1 - mu, -mu, -delta], 

992 [-mu, -mu, -delta], 

993 [mu, mu - 1, delta], 

994 [0, 0, 0.5], 

995 ] 

996 elif variant == 5: 

997 zeta = 0.25 * (b2 / a2 + (1 - b * cosa / c) / sina2) 

998 eta = 0.5 + 2 * zeta * c * cosa / b 

999 mu = 0.5 * eta + b2 / (4 * a2) - b * c * cosa / (2 * a2) 

1000 nu = 2 * mu - zeta 

1001 omega = (4 * nu - 1 - b2 * sina2 / a2) * c / (2 * b * cosa) 

1002 delta = zeta * c * cosa / b + omega / 2 - 0.25 

1003 rho = 1 - zeta * a2 / b2 

1004 

1005 points = [ 

1006 [0, 0, 0], 

1007 [nu, nu, omega], 

1008 [1 - nu, 1 - nu, 1 - omega], 

1009 [nu, nu - 1, omega], 

1010 [zeta, zeta, eta], 

1011 [1 - zeta, -zeta, 1 - eta], 

1012 [-zeta, -zeta, 1 - eta], 

1013 [rho, 1 - rho, 0.5], 

1014 [1 - rho, rho - 1, 0.5], 

1015 [0.5, 0.5, 0.5], 

1016 [0.5, 0, 0.5], 

1017 [0.5, 0, 0], 

1018 [0, -0.5, 0], 

1019 [0.5, -0.5, 0], 

1020 [mu, mu, delta], 

1021 [1 - mu, -mu, -delta], 

1022 [-mu, -mu, -delta], 

1023 [mu, mu - 1, delta], 

1024 [0, 0, 0.5], 

1025 ] 

1026 

1027 return points 

1028 

1029 

1030tri_angles_explanation = """\ 

1031Angles kalpha, kbeta and kgamma of TRI lattice must be 1) all greater \ 

1032than 90 degrees with kgamma being the smallest, or 2) all smaller than \ 

103390 with kgamma being the largest, or 3) kgamma=90 being the \ 

1034smallest of the three, or 4) kgamma=90 being the largest of the three. \ 

1035Angles of reciprocal lattice are kalpha={}, kbeta={}, kgamma={}. \ 

1036If you don't care, please use Cell.fromcellpar() instead.""" 

1037 

1038# XXX labels, paths, are all the same. 

1039 

1040 

1041@bravaisclass( 

1042 'primitive triclinic', 

1043 'triclinic', 

1044 'triclinic', 

1045 'aP', 

1046 ('a', 'b', 'c', 'alpha', 'beta', 'gamma'), 

1047 [ 

1048 ['TRI1a', 'GLMNRXYZ', 'XGY,LGZ,NGM,RG', None], 

1049 ['TRI2a', 'GLMNRXYZ', 'XGY,LGZ,NGM,RG', None], 

1050 ['TRI1b', 'GLMNRXYZ', 'XGY,LGZ,NGM,RG', None], 

1051 ['TRI2b', 'GLMNRXYZ', 'XGY,LGZ,NGM,RG', None], 

1052 ], 

1053) 

1054class TRI(BravaisLattice): 

1055 conventional_cls = 'TRI' 

1056 conventional_cellmap = _identity 

1057 

1058 def __init__(self, a, b, c, alpha, beta, gamma): 

1059 super().__init__(a=a, b=b, c=c, alpha=alpha, beta=beta, gamma=gamma) 

1060 

1061 def _cell(self, a, b, c, alpha, beta, gamma): 

1062 alpha, beta, gamma = np.array([alpha, beta, gamma]) 

1063 singamma = np.sin(gamma * _degrees) 

1064 cosgamma = np.cos(gamma * _degrees) 

1065 cosbeta = np.cos(beta * _degrees) 

1066 cosalpha = np.cos(alpha * _degrees) 

1067 a3x = c * cosbeta 

1068 a3y = c / singamma * (cosalpha - cosbeta * cosgamma) 

1069 a3z = ( 

1070 c 

1071 / singamma 

1072 * np.sqrt( 

1073 singamma**2 

1074 - cosalpha**2 

1075 - cosbeta**2 

1076 + 2 * cosalpha * cosbeta * cosgamma 

1077 ) 

1078 ) 

1079 return np.array( 

1080 [[a, 0, 0], [b * cosgamma, b * singamma, 0], [a3x, a3y, a3z]] 

1081 ) 

1082 

1083 def _variant_name(self, a, b, c, alpha, beta, gamma): 

1084 cell = Cell.new([a, b, c, alpha, beta, gamma]) 

1085 icellpar = Cell(cell.reciprocal()).cellpar() 

1086 kangles = kalpha, kbeta, kgamma = icellpar[3:] 

1087 

1088 def raise_unconventional(): 

1089 raise UnconventionalLattice(tri_angles_explanation.format(*kangles)) 

1090 

1091 eps = self._eps 

1092 if abs(kgamma - 90) < eps: 

1093 if kalpha > 90 and kbeta > 90: 

1094 var = '2a' 

1095 elif kalpha < 90 and kbeta < 90: 

1096 var = '2b' 

1097 else: 

1098 # Is this possible? Maybe due to epsilon 

1099 raise_unconventional() 

1100 elif all(kangles > 90): 

1101 if kgamma > min(kangles): 

1102 raise_unconventional() 

1103 var = '1a' 

1104 elif all(kangles < 90): # and kgamma > max(kalpha, kbeta): 

1105 if kgamma < max(kangles): 

1106 raise_unconventional() 

1107 var = '1b' 

1108 else: 

1109 raise_unconventional() 

1110 

1111 return 'TRI' + var 

1112 

1113 def _special_points(self, a, b, c, alpha, beta, gamma, variant): 

1114 # (None of the points actually depend on any parameters) 

1115 # (We should store the points openly on the variant objects) 

1116 if variant.name == 'TRI1a' or variant.name == 'TRI2a': 

1117 points = [ 

1118 [0.0, 0.0, 0.0], 

1119 [0.5, 0.5, 0], 

1120 [0, 0.5, 0.5], 

1121 [0.5, 0, 0.5], 

1122 [0.5, 0.5, 0.5], 

1123 [0.5, 0, 0], 

1124 [0, 0.5, 0], 

1125 [0, 0, 0.5], 

1126 ] 

1127 else: 

1128 points = [ 

1129 [0, 0, 0], 

1130 [0.5, -0.5, 0], 

1131 [0, 0, 0.5], 

1132 [-0.5, -0.5, 0.5], 

1133 [0, -0.5, 0.5], 

1134 [0, -0.5, 0], 

1135 [0.5, 0, 0], 

1136 [-0.5, 0, 0.5], 

1137 ] 

1138 

1139 return points 

1140 

1141 

1142def get_subset_points(names, points): 

1143 newpoints = {name: points[name] for name in names} 

1144 return newpoints 

1145 

1146 

1147@bravaisclass( 

1148 'primitive oblique', 

1149 'monoclinic', 

1150 None, 

1151 'mp', 

1152 ('a', 'b', 'alpha'), 

1153 [['OBL', 'GYHCH1X', 'GYHCH1XG', None]], 

1154 ndim=2, 

1155) 

1156class OBL(BravaisLattice): 

1157 def __init__(self, a, b, alpha, **kwargs): 

1158 check_rect(a, b) 

1159 if alpha >= 90: 

1160 raise UnconventionalLattice( 

1161 f'Expected alpha < 90, got alpha={alpha}' 

1162 ) 

1163 super().__init__(a=a, b=b, alpha=alpha, **kwargs) 

1164 

1165 def _cell(self, a, b, alpha): 

1166 cosa = np.cos(alpha * _degrees) 

1167 sina = np.sin(alpha * _degrees) 

1168 

1169 return np.array([[a, 0, 0], [b * cosa, b * sina, 0], [0.0, 0.0, 0.0]]) 

1170 

1171 def _special_points(self, a, b, alpha, variant): 

1172 cosa = np.cos(alpha * _degrees) 

1173 eta = (1 - a * cosa / b) / (2 * np.sin(alpha * _degrees) ** 2) 

1174 nu = 0.5 - eta * b * cosa / a 

1175 

1176 points = [ 

1177 [0, 0, 0], 

1178 [0, 0.5, 0], 

1179 [eta, 1 - nu, 0], 

1180 [0.5, 0.5, 0], 

1181 [1 - eta, nu, 0], 

1182 [0.5, 0, 0], 

1183 ] 

1184 

1185 return points 

1186 

1187 

1188@bravaisclass( 

1189 'primitive hexagonal', 

1190 'hexagonal', 

1191 None, 

1192 'hp', 

1193 'a', 

1194 [ 

1195 [ 

1196 'HEX2D', 

1197 'GMK', 

1198 'GMKG', 

1199 get_subset_points('GMK', sc_special_points['hexagonal']), 

1200 ] 

1201 ], 

1202 ndim=2, 

1203) 

1204class HEX2D(BravaisLattice): 

1205 def __init__(self, a, **kwargs): 

1206 super().__init__(a=a, **kwargs) 

1207 

1208 def _cell(self, a): 

1209 x = 0.5 * np.sqrt(3) 

1210 return np.array([[a, 0, 0], [-0.5 * a, x * a, 0], [0.0, 0.0, 0.0]]) 

1211 

1212 

1213def check_rect(a, b): 

1214 if a >= b: 

1215 raise UnconventionalLattice(f'Expected a < b, got a={a}, b={b}') 

1216 

1217 

1218@bravaisclass( 

1219 'primitive rectangular', 

1220 'orthorhombic', 

1221 None, 

1222 'op', 

1223 'ab', 

1224 [ 

1225 [ 

1226 'RECT', 

1227 'GXSY', 

1228 'GXSYGS', 

1229 get_subset_points('GXSY', sc_special_points['orthorhombic']), 

1230 ] 

1231 ], 

1232 ndim=2, 

1233) 

1234class RECT(BravaisLattice): 

1235 def __init__(self, a, b, **kwargs): 

1236 check_rect(a, b) 

1237 super().__init__(a=a, b=b, **kwargs) 

1238 

1239 def _cell(self, a, b): 

1240 return np.array([[a, 0, 0], [0, b, 0], [0, 0, 0.0]]) 

1241 

1242 

1243@bravaisclass( 

1244 'centred rectangular', 

1245 'orthorhombic', 

1246 None, 

1247 'oc', 

1248 ('a', 'alpha'), 

1249 [['CRECT', 'GXA1Y', 'GXA1YG', None]], 

1250 ndim=2, 

1251) 

1252class CRECT(BravaisLattice): 

1253 def __init__(self, a, alpha, **kwargs): 

1254 # It would probably be better to define the CRECT cell 

1255 # by (a, b) rather than (a, alpha). Then we can require a < b 

1256 # like in ordinary RECT. 

1257 # 

1258 # In 3D, all lattices in the same family generally take 

1259 # identical parameters. 

1260 if alpha >= 90: 

1261 raise UnconventionalLattice( 

1262 f'Expected alpha < 90. Got alpha={alpha}' 

1263 ) 

1264 super().__init__(a=a, alpha=alpha, **kwargs) 

1265 

1266 def _cell(self, a, alpha): 

1267 x = np.cos(alpha * _degrees) 

1268 y = np.sin(alpha * _degrees) 

1269 return np.array([[a, 0, 0], [a * x, a * y, 0], [0, 0, 0.0]]) 

1270 

1271 def _special_points(self, a, alpha, variant): 

1272 sina2 = np.sin(alpha / 2 * _degrees) ** 2 

1273 sina = np.sin(alpha * _degrees) ** 2 

1274 eta = sina2 / sina 

1275 cosa = np.cos(alpha * _degrees) 

1276 xi = eta * cosa 

1277 

1278 points = [ 

1279 [0, 0, 0], 

1280 [eta, -eta, 0], 

1281 [0.5 + xi, 0.5 - xi, 0], 

1282 [0.5, 0.5, 0], 

1283 ] 

1284 

1285 return points 

1286 

1287 

1288@bravaisclass( 

1289 'primitive square', 

1290 'tetragonal', 

1291 None, 

1292 'tp', 

1293 ('a',), 

1294 [ 

1295 [ 

1296 'SQR', 

1297 'GMX', 

1298 'MGXM', 

1299 get_subset_points('GMX', sc_special_points['tetragonal']), 

1300 ] 

1301 ], 

1302 ndim=2, 

1303) 

1304class SQR(BravaisLattice): 

1305 def __init__(self, a, **kwargs): 

1306 super().__init__(a=a, **kwargs) 

1307 

1308 def _cell(self, a): 

1309 return np.array([[a, 0, 0], [0, a, 0], [0, 0, 0.0]]) 

1310 

1311 

1312@bravaisclass( 

1313 'primitive line', 

1314 'line', 

1315 None, 

1316 '?', 

1317 ('a',), 

1318 [['LINE', 'GX', 'GX', {'G': [0, 0, 0], 'X': [0.5, 0, 0]}]], 

1319 ndim=1, 

1320) 

1321class LINE(BravaisLattice): 

1322 def __init__(self, a, **kwargs): 

1323 super().__init__(a=a, **kwargs) 

1324 

1325 def _cell(self, a): 

1326 return np.array([[a, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]) 

1327 

1328 

1329def celldiff(cell1, cell2): 

1330 """Return a unitless measure of the difference between two cells.""" 

1331 cell1 = Cell.ascell(cell1).complete() 

1332 cell2 = Cell.ascell(cell2).complete() 

1333 v1v2 = cell1.volume * cell2.volume 

1334 if v1v2 < 1e-10: 

1335 # (Proposed cell may be linearly dependent) 

1336 return np.inf 

1337 

1338 scale = v1v2 ** (-1.0 / 3.0) # --> 1/Ang^2 

1339 x1 = cell1 @ cell1.T 

1340 x2 = cell2 @ cell2.T 

1341 dev = scale * np.abs(x2 - x1).max() 

1342 return dev 

1343 

1344 

1345def get_lattice_from_canonical_cell(cell, eps=2e-4): 

1346 """Return a Bravais lattice representing the given cell. 

1347 

1348 This works only for cells that are derived from the standard form 

1349 (as generated by lat.tocell()) or rotations thereof. 

1350 

1351 If the given cell does not resemble the known form of a Bravais 

1352 lattice, raise RuntimeError.""" 

1353 return NormalizedLatticeMatcher(cell, eps).match() 

1354 

1355 

1356class LatticeMatcher: 

1357 def __init__(self, cell, pbc=None, *, eps, niggli_eps=None): 

1358 self.orig_cell = cell 

1359 if pbc is None: 

1360 pbc = cell.mask() 

1361 self.pbc = cell.any(1) & pbc2pbc(pbc) 

1362 self.cell = cell.uncomplete(pbc) 

1363 self.eps = eps 

1364 if niggli_eps is None: 

1365 niggli_eps = eps 

1366 self.niggli_cell, self.niggli_op = self.cell.niggli_reduce( 

1367 eps=niggli_eps 

1368 ) 

1369 

1370 # We tabulate the cell's Niggli-mapped versions so we don't need to 

1371 # redo any work when the same Niggli-operation appears multiple times 

1372 # in the table: 

1373 self.memory = {} 

1374 

1375 def match(self, latname, operations): 

1376 matches = [] 

1377 

1378 for op_key in operations: 

1379 checker_and_op = self.memory.get(op_key) 

1380 if checker_and_op is None: 

1381 # op_3x3 is the 3x3 form of the operation that maps 

1382 # Niggli cell to AFlow form. 

1383 op_3x3 = np.array(op_key).reshape(3, 3) 

1384 candidate = Cell(np.linalg.inv(op_3x3.T) @ self.niggli_cell) 

1385 checker = NormalizedLatticeMatcher(candidate, eps=self.eps) 

1386 self.memory[op_key] = (checker, op_3x3) 

1387 else: 

1388 checker, op_3x3 = checker_and_op 

1389 

1390 lat, error = checker.query(latname) 

1391 if lat is None or error > self.eps: 

1392 continue 

1393 

1394 # This is the full operation encompassing 

1395 # both Niggli reduction of user input and mapping the 

1396 # Niggli reduced form to standard (AFlow) form. 

1397 op = op_3x3 @ np.linalg.inv(self.niggli_op) 

1398 matches.append(Match(lat, op, error)) 

1399 

1400 return matches 

1401 

1402 

1403@dataclass 

1404class Match: 

1405 lat: BravaisLattice 

1406 op: np.ndarray 

1407 error: float 

1408 

1409 @cached_property 

1410 def orthogonality_defect(self) -> float: 

1411 cell = self.lat.tocell().complete() 

1412 return np.prod(cell.lengths()) / cell.volume 

1413 

1414 

1415def identify_lattice(cell, eps=2e-4, *, pbc=True): 

1416 """Find Bravais lattice representing this cell. 

1417 

1418 Returns Bravais lattice object representing the cell along with 

1419 an operation that, applied to the cell, yields the same lengths 

1420 and angles as the Bravais lattice object.""" 

1421 from ase.geometry.bravais_type_engine import niggli_op_table 

1422 

1423 matcher = LatticeMatcher(cell, pbc, eps=eps) 

1424 

1425 # We loop through the most symmetric kinds (CUB etc.) and return 

1426 # the first one we find: 

1427 for latname in lattice_check_orders[matcher.cell.rank]: 

1428 # There may be multiple Niggli operations that produce valid 

1429 # lattices, at least for MCL. In that case we will pick the 

1430 # one whose angle is closest to 90, but it means we cannot 

1431 # just return the first one we find so we must remember them: 

1432 matches = matcher.match(latname, niggli_op_table[latname]) 

1433 

1434 if not matches: 

1435 continue # Move to next Bravais lattice 

1436 

1437 best = min(matches, key=lambda match: match.orthogonality_defect) 

1438 

1439 if matcher.cell.rank == 2 and best.op[2, 2] < 0: 

1440 best.op = flip_2d_handedness(best.op) 

1441 

1442 return best.lat, best.op 

1443 

1444 raise RuntimeError('Failed to recognize lattice') 

1445 

1446 

1447def flip_2d_handedness(op): 

1448 # The 3x3 operation may flip the z axis, but then the x/y 

1449 # components are necessarily also left-handed which 

1450 # means a defacto left-handed 2D bandpath. 

1451 # 

1452 # We repair this by applying an operation that unflips the 

1453 # z axis and interchanges x/y: 

1454 repair_op = np.array([[0, 1, 0], [1, 0, 0], [0, 0, -1]]) 

1455 return repair_op @ op 

1456 

1457 

1458# Map of number of dimensions to order in which to check lattices. 

1459# We check most symmetric lattices first, so we can terminate early 

1460# when a match is found. 

1461# 

1462# The check order is slightly different than elsewhere listed order, 

1463# as we need to check HEX/RHL before the ORCx family. 

1464lattice_check_orders = { 

1465 1: ['LINE'], 

1466 2: ['SQR', 'RECT', 'HEX2D', 'CRECT', 'OBL'], 

1467 3: [ 

1468 'CUB', 

1469 'FCC', 

1470 'BCC', 

1471 'TET', 

1472 'BCT', 

1473 'HEX', 

1474 'RHL', 

1475 'ORC', 

1476 'ORCF', 

1477 'ORCI', 

1478 'ORCC', 

1479 'MCL', 

1480 'MCLC', 

1481 'TRI', 

1482 ], 

1483} 

1484 

1485 

1486class NormalizedLatticeMatcher: 

1487 # This class checks that a candidate cell matches the normalized 

1488 # form of a Bravais lattice. It's used internally by the LatticeMatcher. 

1489 

1490 def __init__(self, cell, eps=2e-4): 

1491 """Generate Bravais lattices that look (or not) like the given cell. 

1492 

1493 The cell must be reduced to canonical form, i.e., it must 

1494 be possible to produce a cell with the same lengths and angles 

1495 by directly through one of the Bravais lattice classes. 

1496 

1497 Generally for internal use (this module). 

1498 

1499 For each of the 14 Bravais lattices, this object can produce 

1500 a lattice object which represents the same cell, or None if 

1501 the tolerance eps is not met.""" 

1502 self.cell = cell 

1503 self.eps = eps 

1504 

1505 self.cellpar = cell.cellpar() 

1506 self.lengths = self.A, self.B, self.C = self.cellpar[:3] 

1507 self.angles = self.cellpar[3:] 

1508 

1509 # Use a 'neutral' length for checking cubic lattices 

1510 self.A0 = self.lengths.mean() 

1511 

1512 # Vector of the diagonal and then off-diagonal dot products: 

1513 # [a1 · a1, a2 · a2, a3 · a3, a2 · a3, a3 · a1, a1 · a2] 

1514 self.prods = (cell @ cell.T).flat[[0, 4, 8, 5, 2, 1]] 

1515 

1516 def _check(self, latcls, *args): 

1517 if any(arg <= 0 for arg in args): 

1518 return None 

1519 

1520 try: 

1521 return latcls(*args) 

1522 except UnconventionalLattice: 

1523 return None 

1524 

1525 def match(self): 

1526 """Match cell against all lattices, returning most symmetric match. 

1527 

1528 Returns the lattice object. Raises RuntimeError on failure.""" 

1529 for name in lattice_check_orders[self.cell.rank]: 

1530 lat, err = self.query(name) 

1531 if lat and err < self.eps: 

1532 return lat 

1533 

1534 raise RuntimeError( 

1535 'Could not find lattice type for cell ' 

1536 'with lengths and angles {}'.format(self.cell.cellpar().tolist()) 

1537 ) 

1538 

1539 def query(self, latname): 

1540 """Match cell against named Bravais lattice. 

1541 

1542 Return lattice object on success, None on failure.""" 

1543 meth = getattr(self, latname) 

1544 

1545 lat = meth() 

1546 if lat is None: 

1547 return None, None 

1548 

1549 newcell = lat.tocell() 

1550 err = celldiff(self.cell, newcell) 

1551 return lat, err 

1552 

1553 def LINE(self): 

1554 return self._check(LINE, self.lengths[0]) 

1555 

1556 def SQR(self): 

1557 return self._check(SQR, self.lengths[0]) 

1558 

1559 def RECT(self): 

1560 return self._check(RECT, *self.lengths[:2]) 

1561 

1562 def CRECT(self): 

1563 return self._check(CRECT, self.lengths[0], self.angles[2]) 

1564 

1565 def HEX2D(self): 

1566 return self._check(HEX2D, self.lengths[0]) 

1567 

1568 def OBL(self): 

1569 return self._check(OBL, *self.lengths[:2], self.angles[2]) 

1570 

1571 def CUB(self): 

1572 # These methods (CUB, FCC, ...) all return a lattice object if 

1573 # it matches, else None. 

1574 return self._check(CUB, self.A0) 

1575 

1576 def FCC(self): 

1577 return self._check(FCC, np.sqrt(2) * self.A0) 

1578 

1579 def BCC(self): 

1580 return self._check(BCC, 2.0 * self.A0 / np.sqrt(3)) 

1581 

1582 def TET(self): 

1583 return self._check(TET, self.A, self.C) 

1584 

1585 def _bct_orci_lengths(self): 

1586 # Coordinate-system independent relation for BCT and ORCI 

1587 # standard cells: 

1588 # a1 · a1 + a2 · a3 == a² / 2 

1589 # a2 · a2 + a3 · a1 == a² / 2 (BCT) 

1590 # == b² / 2 (ORCI) 

1591 # a3 · a3 + a1 · a2 == c² / 2 

1592 # We use these to get a, b, and c in those cases. 

1593 prods = self.prods 

1594 lengthsqr = 2.0 * (prods[:3] + prods[3:]) 

1595 if any(lengthsqr < 0): 

1596 return None 

1597 return np.sqrt(lengthsqr) 

1598 

1599 def BCT(self): 

1600 lengths = self._bct_orci_lengths() 

1601 if lengths is None: 

1602 return None 

1603 return self._check(BCT, lengths[0], lengths[2]) 

1604 

1605 def HEX(self): 

1606 return self._check(HEX, self.A, self.C) 

1607 

1608 def RHL(self): 

1609 return self._check(RHL, self.A, self.angles[0]) 

1610 

1611 def ORC(self): 

1612 return self._check(ORC, *self.lengths) 

1613 

1614 def ORCF(self): 

1615 # ORCF standard cell: 

1616 # a2 · a3 = a²/4 

1617 # a3 · a1 = b²/4 

1618 # a1 · a2 = c²/4 

1619 prods = self.prods 

1620 if all(prods[3:] > 0): 

1621 orcf_abc = 2 * np.sqrt(prods[3:]) 

1622 return self._check(ORCF, *orcf_abc) 

1623 

1624 def ORCI(self): 

1625 lengths = self._bct_orci_lengths() 

1626 if lengths is None: 

1627 return None 

1628 return self._check(ORCI, *lengths) 

1629 

1630 def _orcc_ab(self): 

1631 # ORCC: a1 · a1 + a2 · a3 = a²/2 

1632 # a2 · a2 - a2 · a3 = b²/2 

1633 prods = self.prods 

1634 orcc_sqr_ab = np.empty(2) 

1635 orcc_sqr_ab[0] = 2.0 * (prods[0] + prods[5]) 

1636 orcc_sqr_ab[1] = 2.0 * (prods[1] - prods[5]) 

1637 if all(orcc_sqr_ab > 0): 

1638 return np.sqrt(orcc_sqr_ab) 

1639 

1640 def ORCC(self): 

1641 orcc_lengths_ab = self._orcc_ab() 

1642 if orcc_lengths_ab is None: 

1643 return None 

1644 return self._check(ORCC, *orcc_lengths_ab, self.C) 

1645 

1646 def MCL(self): 

1647 return self._check(MCL, *self.lengths, self.angles[0]) 

1648 

1649 def MCLC(self): 

1650 # MCLC is similar to ORCC: 

1651 orcc_ab = self._orcc_ab() 

1652 if orcc_ab is None: 

1653 return None 

1654 

1655 prods = self.prods 

1656 C = self.C 

1657 mclc_a, mclc_b = orcc_ab[::-1] # a, b reversed wrt. ORCC 

1658 mclc_cosa = 2.0 * prods[3] / (mclc_b * C) 

1659 if -1 < mclc_cosa < 1: 

1660 mclc_alpha = np.arccos(mclc_cosa) * 180 / np.pi 

1661 if mclc_b > C: 

1662 # XXX Temporary fix for certain otherwise 

1663 # unrecognizable lattices. 

1664 # 

1665 # This error could happen if the input lattice maps to 

1666 # something just outside the domain of conventional 

1667 # lattices (less than the tolerance). Our solution is to 

1668 # propose a nearby conventional lattice instead, which 

1669 # will then be accepted if it's close enough. 

1670 mclc_b = 0.5 * (mclc_b + C) 

1671 C = mclc_b 

1672 return self._check(MCLC, mclc_a, mclc_b, C, mclc_alpha) 

1673 

1674 def TRI(self): 

1675 return self._check(TRI, *self.cellpar) 

1676 

1677 

1678def match_to_lattice(cell, latname: str, pbc=None) -> list[Match]: 

1679 """Match cell to a particular Bravais lattice. 

1680 

1681 For a given input cell, attempt to represent it as a particular 

1682 lattice, such as 'FCC', 'ORC', 'ORCI', etc. Return a list of 

1683 :class:`ase.lattice.Match` objects which can be compared 

1684 so as to get the best match according to metric tensor error 

1685 with respect to the input cell or orthogonality defect. 

1686 """ 

1687 from ase.geometry.bravais_type_engine import niggli_op_table 

1688 

1689 cell = Cell.ascell(cell) 

1690 matcher = LatticeMatcher( 

1691 cell=cell, 

1692 pbc=pbc, 

1693 eps=1e6, # We want all candidates and apply eps in our own way 

1694 niggli_eps=1e-5, 

1695 ) 

1696 

1697 # We should probably sort the matches by "quality". 

1698 # Quality must optimize both fitting error and 

1699 # orthogonality defect, so some weighting scheme is necessary, 

1700 # e.g. minimize one after filtering out the other. 

1701 # 

1702 # best = min(matches, key=lambda match: match.orthogonality_defect) 

1703 # 

1704 # Maybe we should take a key callable as argument. 

1705 return matcher.match(latname, niggli_op_table[latname]) 

1706 

1707 

1708def all_variants(): 

1709 """For testing and examples; yield all variants of all lattices.""" 

1710 a, b, c = 3.0, 4.0, 5.0 

1711 alpha = 55.0 

1712 yield CUB(a) 

1713 yield FCC(a) 

1714 yield BCC(a) 

1715 yield TET(a, c) 

1716 bct1 = BCT(2 * a, c) 

1717 bct2 = BCT(a, c) 

1718 assert bct1.variant == 'BCT1' 

1719 assert bct2.variant == 'BCT2' 

1720 

1721 yield bct1 

1722 yield bct2 

1723 

1724 yield ORC(a, b, c) 

1725 

1726 a0 = np.sqrt(1.0 / (1 / b**2 + 1 / c**2)) 

1727 orcf1 = ORCF(0.5 * a0, b, c) 

1728 orcf2 = ORCF(1.2 * a0, b, c) 

1729 orcf3 = ORCF(a0, b, c) 

1730 assert orcf1.variant == 'ORCF1' 

1731 assert orcf2.variant == 'ORCF2' 

1732 assert orcf3.variant == 'ORCF3' 

1733 yield orcf1 

1734 yield orcf2 

1735 yield orcf3 

1736 

1737 yield ORCI(a, b, c) 

1738 yield ORCC(a, b, c) 

1739 

1740 yield HEX(a, c) 

1741 

1742 rhl1 = RHL(a, alpha=55.0) 

1743 assert rhl1.variant == 'RHL1' 

1744 yield rhl1 

1745 

1746 rhl2 = RHL(a, alpha=105.0) 

1747 assert rhl2.variant == 'RHL2' 

1748 yield rhl2 

1749 

1750 # With these lengths, alpha < 65 (or so) would result in a lattice that 

1751 # could also be represented with alpha > 65, which is more conventional. 

1752 yield MCL(a, b, c, alpha=70.0) 

1753 

1754 mclc1 = MCLC(a, b, c, 80) 

1755 assert mclc1.variant == 'MCLC1' 

1756 yield mclc1 

1757 # mclc2 has same special points as mclc1 

1758 

1759 mclc3 = MCLC(1.8 * a, b, c * 2, 80) 

1760 assert mclc3.variant == 'MCLC3' 

1761 yield mclc3 

1762 # mclc4 has same special points as mclc3 

1763 

1764 # XXX We should add MCLC2 and MCLC4 as well. 

1765 

1766 mclc5 = MCLC(b, b, 1.1 * b, 70) 

1767 assert mclc5.variant == 'MCLC5' 

1768 yield mclc5 

1769 

1770 def get_tri(kcellpar): 

1771 # We build the TRI lattices from cellpars of reciprocal cell 

1772 icell = Cell.fromcellpar(kcellpar) 

1773 cellpar = Cell(4 * icell.reciprocal()).cellpar() 

1774 return TRI(*cellpar) 

1775 

1776 tri1a = get_tri([1.0, 1.2, 1.4, 120.0, 110.0, 100.0]) 

1777 assert tri1a.variant == 'TRI1a' 

1778 yield tri1a 

1779 

1780 tri1b = get_tri([1.0, 1.2, 1.4, 50.0, 60.0, 70.0]) 

1781 assert tri1b.variant == 'TRI1b' 

1782 yield tri1b 

1783 

1784 tri2a = get_tri([1.0, 1.2, 1.4, 120.0, 110.0, 90.0]) 

1785 assert tri2a.variant == 'TRI2a' 

1786 yield tri2a 

1787 tri2b = get_tri([1.0, 1.2, 1.4, 50.0, 60.0, 90.0]) 

1788 assert tri2b.variant == 'TRI2b' 

1789 yield tri2b 

1790 

1791 # Choose an OBL lattice that round-trip-converts to itself. 

1792 # The default a/b/alpha parameters result in another representation 

1793 # of the same lattice. 

1794 yield OBL(a=3.0, b=3.35, alpha=77.85) 

1795 yield RECT(a, b) 

1796 yield CRECT(a, alpha=alpha) 

1797 yield HEX2D(a) 

1798 yield SQR(a) 

1799 yield LINE(a)