Coverage for ase/spacegroup/spacegroup.py: 91.98%

424 statements  

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

1# Copyright (C) 2010, Jesper Friis 

2# (see accompanying license files for details). 

3"""Definition of the Spacegroup class. 

4 

5This module only depends on NumPy and the space group database. 

6""" 

7 

8import os 

9import warnings 

10from functools import lru_cache, total_ordering 

11from types import SimpleNamespace 

12from typing import Union 

13 

14import numpy as np 

15 

16from ase.utils import deprecated, spglib_new_errorhandling 

17 

18__all__ = ['Spacegroup'] 

19 

20 

21class SpacegroupError(Exception): 

22 """Base exception for the spacegroup module.""" 

23 

24 

25class SpacegroupNotFoundError(SpacegroupError): 

26 """Raised when given space group cannot be found in data base.""" 

27 

28 

29class SpacegroupValueError(SpacegroupError): 

30 """Raised when arguments have invalid value.""" 

31 

32 

33# Type alias 

34_SPACEGROUP = Union[int, str, 'Spacegroup'] 

35 

36 

37@total_ordering 

38class Spacegroup: 

39 """A space group class. 

40 

41 The instances of Spacegroup describes the symmetry operations for 

42 the given space group. 

43 

44 Example: 

45 

46 >>> from ase.spacegroup import Spacegroup 

47 >>> 

48 >>> sg = Spacegroup(225) 

49 >>> print('Space group', sg.no, sg.symbol) 

50 Space group 225 F m -3 m 

51 >>> sg.scaled_primitive_cell 

52 array([[0. , 0.5, 0.5], 

53 [0.5, 0. , 0.5], 

54 [0.5, 0.5, 0. ]]) 

55 >>> sites, kinds = sg.equivalent_sites([[0,0,0]]) 

56 >>> sites 

57 array([[0. , 0. , 0. ], 

58 [0. , 0.5, 0.5], 

59 [0.5, 0. , 0.5], 

60 [0.5, 0.5, 0. ]]) 

61 """ 

62 

63 @property 

64 def no(self): 

65 """Space group number in International Tables of Crystallography.""" 

66 return self._no 

67 

68 @property 

69 def symbol(self): 

70 """Hermann-Mauguin (or international) symbol for the space group.""" 

71 return self._symbol 

72 

73 @property 

74 def setting(self): 

75 """Space group setting. Either one or two.""" 

76 return self._setting 

77 

78 @property 

79 def lattice(self): 

80 """Lattice type. 

81 

82 P primitive 

83 I body centering, h+k+l=2n 

84 F face centering, h,k,l all odd or even 

85 A,B,C single face centering, k+l=2n, h+l=2n, h+k=2n 

86 R rhombohedral centering, -h+k+l=3n (obverse); h-k+l=3n (reverse) 

87 """ 

88 return self._symbol[0] 

89 

90 @property 

91 def centrosymmetric(self): 

92 """Whether a center of symmetry exists.""" 

93 return self._centrosymmetric 

94 

95 @property 

96 def scaled_primitive_cell(self): 

97 """Primitive cell in scaled coordinates. 

98 

99 Matrix with the primitive vectors along the rows. 

100 """ 

101 return self._scaled_primitive_cell 

102 

103 @property 

104 def reciprocal_cell(self): 

105 """ 

106 

107 Tree Miller indices that span all kinematically non-forbidden 

108 reflections as a matrix with the Miller indices along the rows. 

109 """ 

110 return self._reciprocal_cell 

111 

112 @property 

113 def nsubtrans(self): 

114 """Number of cell-subtranslation vectors.""" 

115 return len(self._subtrans) 

116 

117 @property 

118 def nsymop(self): 

119 """Total number of symmetry operations.""" 

120 scale = 2 if self.centrosymmetric else 1 

121 return scale * len(self._rotations) * len(self._subtrans) 

122 

123 @property 

124 def subtrans(self): 

125 """Translations vectors belonging to cell-sub-translations.""" 

126 return self._subtrans 

127 

128 @property 

129 def rotations(self): 

130 """Symmetry rotation matrices. 

131 

132 The invertions are not included for centrosymmetrical crystals. 

133 """ 

134 return self._rotations 

135 

136 @property 

137 def translations(self): 

138 """Symmetry translations. 

139 

140 The invertions are not included for centrosymmetrical crystals. 

141 """ 

142 return self._translations 

143 

144 def __init__(self, spacegroup: _SPACEGROUP, setting=1, datafile=None): 

145 """Returns a new Spacegroup instance. 

146 

147 Parameters 

148 ---------- 

149 

150 spacegroup : int | string | Spacegroup instance 

151 The space group number in International Tables of 

152 Crystallography or its Hermann-Mauguin symbol. E.g. 

153 spacegroup=225 and spacegroup='F m -3 m' are equivalent. 

154 setting : 1 | 2 

155 Some space groups have more than one setting. `setting` 

156 determines Which of these should be used. 

157 datafile : None | string 

158 Path to database file. If `None`, the the default database 

159 will be used. 

160 """ 

161 if isinstance(spacegroup, Spacegroup): 

162 for k, v in spacegroup.__dict__.items(): 

163 setattr(self, k, v) 

164 return 

165 if not datafile: 

166 datafile = get_datafile() 

167 namespace = _read_datafile(spacegroup, setting, datafile) 

168 self._no = namespace._no 

169 self._symbol = namespace._symbol 

170 self._setting = namespace._setting 

171 self._centrosymmetric = namespace._centrosymmetric 

172 self._scaled_primitive_cell = namespace._scaled_primitive_cell 

173 self._reciprocal_cell = namespace._reciprocal_cell 

174 self._subtrans = namespace._subtrans 

175 self._rotations = namespace._rotations 

176 self._translations = namespace._translations 

177 

178 def __repr__(self): 

179 return 'Spacegroup(%d, setting=%d)' % (self.no, self.setting) 

180 

181 def todict(self): 

182 return {'number': self.no, 'setting': self.setting} 

183 

184 def __str__(self): 

185 """Return a string representation of the space group data in 

186 the same format as found the database.""" 

187 retval = [] 

188 # no, symbol 

189 retval.append('%-3d %s\n' % (self.no, self.symbol)) 

190 # setting 

191 retval.append(' setting %d\n' % (self.setting)) 

192 # centrosymmetric 

193 retval.append(' centrosymmetric %d\n' % (self.centrosymmetric)) 

194 # primitive vectors 

195 retval.append(' primitive vectors\n') 

196 for i in range(3): 

197 retval.append(' ') 

198 for j in range(3): 

199 retval.append(' %13.10f' % (self.scaled_primitive_cell[i, j])) 

200 retval.append('\n') 

201 # primitive reciprocal vectors 

202 retval.append(' reciprocal vectors\n') 

203 for i in range(3): 

204 retval.append(' ') 

205 for j in range(3): 

206 retval.append(' %3d' % (self.reciprocal_cell[i, j])) 

207 retval.append('\n') 

208 # sublattice 

209 retval.append(' %d subtranslations\n' % self.nsubtrans) 

210 for i in range(self.nsubtrans): 

211 retval.append(' ') 

212 for j in range(3): 

213 retval.append(' %13.10f' % (self.subtrans[i, j])) 

214 retval.append('\n') 

215 # symmetry operations 

216 nrot = len(self.rotations) 

217 retval.append(' %d symmetry operations (rot+trans)\n' % nrot) 

218 for i in range(nrot): 

219 retval.append(' ') 

220 for j in range(3): 

221 retval.append(' ') 

222 for k in range(3): 

223 retval.append(' %2d' % (self.rotations[i, j, k])) 

224 retval.append(' ') 

225 for j in range(3): 

226 retval.append(' %13.10f' % self.translations[i, j]) 

227 retval.append('\n') 

228 retval.append('\n') 

229 return ''.join(retval) 

230 

231 def __eq__(self, other): 

232 return self.no == other.no and self.setting == other.setting 

233 

234 def __ne__(self, other): 

235 return not self.__eq__(other) 

236 

237 def __lt__(self, other): 

238 return self.no < other.no or ( 

239 self.no == other.no and self.setting < other.setting 

240 ) 

241 

242 def __index__(self): 

243 return self.no 

244 

245 __int__ = __index__ 

246 

247 def get_symop(self): 

248 """Returns all symmetry operations (including inversions and 

249 subtranslations) as a sequence of (rotation, translation) 

250 tuples.""" 

251 symop = [] 

252 parities = [1] 

253 if self.centrosymmetric: 

254 parities.append(-1) 

255 for parity in parities: 

256 for subtrans in self.subtrans: 

257 for rot, trans in zip(self.rotations, self.translations): 

258 newtrans = np.mod(trans + subtrans, 1) 

259 symop.append((parity * rot, newtrans)) 

260 return symop 

261 

262 def get_op(self): 

263 """Returns all symmetry operations (including inversions and 

264 subtranslations), but unlike get_symop(), they are returned as 

265 two ndarrays.""" 

266 if self.centrosymmetric: 

267 rot = np.tile( 

268 np.vstack((self.rotations, -self.rotations)), 

269 (self.nsubtrans, 1, 1), 

270 ) 

271 trans = np.tile( 

272 np.vstack((self.translations, -self.translations)), 

273 (self.nsubtrans, 1), 

274 ) 

275 trans += np.repeat(self.subtrans, 2 * len(self.rotations), axis=0) 

276 trans = np.mod(trans, 1) 

277 else: 

278 rot = np.tile(self.rotations, (self.nsubtrans, 1, 1)) 

279 trans = np.tile(self.translations, (self.nsubtrans, 1)) 

280 trans += np.repeat(self.subtrans, len(self.rotations), axis=0) 

281 trans = np.mod(trans, 1) 

282 return rot, trans 

283 

284 def get_rotations(self): 

285 """Return all rotations, including inversions for 

286 centrosymmetric crystals.""" 

287 if self.centrosymmetric: 

288 return np.vstack((self.rotations, -self.rotations)) 

289 else: 

290 return self.rotations 

291 

292 def equivalent_reflections(self, hkl): 

293 """Return all equivalent reflections to the list of Miller indices 

294 in hkl. 

295 

296 Example: 

297 

298 >>> from ase.spacegroup import Spacegroup 

299 >>> sg = Spacegroup(225) # fcc 

300 >>> sg.equivalent_reflections([[0, 0, 2]]) 

301 array([[ 0, 0, -2], 

302 [ 0, -2, 0], 

303 [-2, 0, 0], 

304 [ 2, 0, 0], 

305 [ 0, 2, 0], 

306 [ 0, 0, 2]]) 

307 """ 

308 hkl = np.array(hkl, dtype='int', ndmin=2) 

309 rot = self.get_rotations() 

310 n, nrot = len(hkl), len(rot) 

311 R = rot.transpose(0, 2, 1).reshape((3 * nrot, 3)).T 

312 refl = np.dot(hkl, R).reshape((n * nrot, 3)) 

313 ind = np.lexsort(refl.T) 

314 refl = refl[ind] 

315 diff = np.diff(refl, axis=0) 

316 mask = np.any(diff, axis=1) 

317 return np.vstack((refl[:-1][mask], refl[-1, :])) 

318 

319 def equivalent_lattice_points(self, uvw): 

320 """Return all lattice points equivalent to any of the lattice points 

321 in `uvw` with respect to rotations only. 

322 

323 Only equivalent lattice points that conserves the distance to 

324 origo are included in the output (making this a kind of real 

325 space version of the equivalent_reflections() method). 

326 

327 Example: 

328 

329 >>> from ase.spacegroup import Spacegroup 

330 >>> sg = Spacegroup(225) # fcc 

331 >>> sg.equivalent_lattice_points([[0, 0, 2]]) 

332 array([[ 0, 0, -2], 

333 [ 0, -2, 0], 

334 [-2, 0, 0], 

335 [ 2, 0, 0], 

336 [ 0, 2, 0], 

337 [ 0, 0, 2]]) 

338 

339 """ 

340 uvw = np.array(uvw, ndmin=2) 

341 rot = self.get_rotations() 

342 n, nrot = len(uvw), len(rot) 

343 directions = np.dot(uvw, rot).reshape((n * nrot, 3)) 

344 ind = np.lexsort(directions.T) 

345 directions = directions[ind] 

346 diff = np.diff(directions, axis=0) 

347 mask = np.any(diff, axis=1) 

348 return np.vstack((directions[:-1][mask], directions[-1:])) 

349 

350 def symmetry_normalised_reflections(self, hkl): 

351 """Returns an array of same size as *hkl*, containing the 

352 corresponding symmetry-equivalent reflections of lowest 

353 indices. 

354 

355 Example: 

356 

357 >>> from ase.spacegroup import Spacegroup 

358 >>> sg = Spacegroup(225) # fcc 

359 >>> sg.symmetry_normalised_reflections([[2, 0, 0], [0, 2, 0]]) 

360 array([[ 0, 0, -2], 

361 [ 0, 0, -2]]) 

362 """ 

363 hkl = np.array(hkl, dtype=int, ndmin=2) 

364 normalised = np.empty(hkl.shape, int) 

365 R = self.get_rotations().transpose(0, 2, 1) 

366 for i, g in enumerate(hkl): 

367 gsym = np.dot(R, g) 

368 j = np.lexsort(gsym.T)[0] 

369 normalised[i, :] = gsym[j] 

370 return normalised 

371 

372 def unique_reflections(self, hkl): 

373 """Returns a subset *hkl* containing only the symmetry-unique 

374 reflections. 

375 

376 Example: 

377 

378 >>> from ase.spacegroup import Spacegroup 

379 >>> sg = Spacegroup(225) # fcc 

380 >>> sg.unique_reflections([[ 2, 0, 0], 

381 ... [ 0, -2, 0], 

382 ... [ 2, 2, 0], 

383 ... [ 0, -2, -2]]) 

384 array([[2, 0, 0], 

385 [2, 2, 0]]) 

386 """ 

387 hkl = np.array(hkl, dtype=int, ndmin=2) 

388 hklnorm = self.symmetry_normalised_reflections(hkl) 

389 perm = np.lexsort(hklnorm.T) 

390 iperm = perm.argsort() 

391 xmask = np.abs(np.diff(hklnorm[perm], axis=0)).any(axis=1) 

392 mask = np.concatenate(([True], xmask)) 

393 imask = mask[iperm] 

394 return hkl[imask] 

395 

396 def equivalent_sites( 

397 self, 

398 scaled_positions, 

399 onduplicates='error', 

400 symprec=1e-3, 

401 occupancies=None, 

402 ): 

403 """Returns the scaled positions and all their equivalent sites. 

404 

405 Parameters 

406 ---------- 

407 

408 scaled_positions: list | array 

409 List of non-equivalent sites given in unit cell coordinates. 

410 

411 occupancies: list | array, optional (default=None) 

412 List of occupancies corresponding to the respective sites. 

413 

414 onduplicates : 'keep' | 'replace' | 'warn' | 'error' 

415 Action if `scaled_positions` contain symmetry-equivalent 

416 positions of full occupancy: 

417 

418 'keep' 

419 ignore additional symmetry-equivalent positions 

420 'replace' 

421 replace 

422 'warn' 

423 like 'keep', but issue an UserWarning 

424 'error' 

425 raises a SpacegroupValueError 

426 

427 symprec: float 

428 Minimum "distance" betweed two sites in scaled coordinates 

429 before they are counted as the same site. 

430 

431 Returns 

432 ------- 

433 

434 sites: array 

435 A NumPy array of equivalent sites. 

436 kinds: list 

437 A list of integer indices specifying which input site is 

438 equivalent to the corresponding returned site. 

439 

440 Example: 

441 

442 >>> from ase.spacegroup import Spacegroup 

443 >>> sg = Spacegroup(225) # fcc 

444 >>> sites, kinds = sg.equivalent_sites([[0, 0, 0], [0.5, 0.0, 0.0]]) 

445 >>> sites 

446 array([[0. , 0. , 0. ], 

447 [0. , 0.5, 0.5], 

448 [0.5, 0. , 0.5], 

449 [0.5, 0.5, 0. ], 

450 [0.5, 0. , 0. ], 

451 [0. , 0.5, 0. ], 

452 [0. , 0. , 0.5], 

453 [0.5, 0.5, 0.5]]) 

454 >>> kinds 

455 [0, 0, 0, 0, 1, 1, 1, 1] 

456 """ 

457 if onduplicates not in ('keep', 'replace', 'warn', 'error'): 

458 raise SpacegroupValueError( 

459 'Argument "onduplicates" must be one of: ' 

460 '"keep", "replace", "warn" or "error".' 

461 ) 

462 

463 scaled = np.array(scaled_positions, ndmin=2) 

464 rotations, translations = zip(*self.get_symop()) 

465 rotations = np.array(rotations) 

466 translations = np.array(translations) 

467 

468 def find_orbit(point: np.ndarray) -> np.ndarray: 

469 """Find crystallographic orbit of the given point.""" 

470 candidates = ((rotations @ point) + translations % 1.0) % 1.0 

471 orbit = [candidates[0]] 

472 for member in candidates[1:]: 

473 diff = member - orbit 

474 diff -= np.rint(diff) 

475 if not np.any(np.all(np.abs(diff) < symprec, axis=1)): 

476 orbit.append(member) 

477 return np.array(orbit) 

478 

479 orbits = [] 

480 for kind, pos in enumerate(scaled): 

481 for i, (kind0, positions0) in enumerate(orbits): 

482 diff = pos - positions0 

483 diff -= np.rint(diff) 

484 if np.any(np.all(np.abs(diff) < symprec, axis=1)): 

485 if onduplicates == 'keep': 

486 pass 

487 elif onduplicates == 'replace': 

488 orbits[i] = (kind, positions0) 

489 elif onduplicates == 'warn': 

490 warnings.warn( 

491 'scaled_positions %d and %d are equivalent' 

492 % (kind0, kind) 

493 ) 

494 elif onduplicates == 'error': 

495 raise SpacegroupValueError( 

496 'scaled_positions %d and %d are equivalent' 

497 % (kind0, kind) 

498 ) 

499 break 

500 else: 

501 orbits.append((kind, find_orbit(pos))) 

502 

503 kinds = [] 

504 sites = [] 

505 for kind, orbit in orbits: 

506 kinds.extend(len(orbit) * [kind]) 

507 sites.append(orbit) 

508 

509 return np.concatenate(sites, axis=0), kinds 

510 

511 def symmetry_normalised_sites(self, scaled_positions, map_to_unitcell=True): 

512 """Returns an array of same size as *scaled_positions*, 

513 containing the corresponding symmetry-equivalent sites of 

514 lowest indices. 

515 

516 If *map_to_unitcell* is true, the returned positions are all 

517 mapped into the unit cell, i.e. lattice translations are 

518 included as symmetry operator. 

519 

520 Example: 

521 

522 >>> from ase.spacegroup import Spacegroup 

523 >>> sg = Spacegroup(225) # fcc 

524 >>> sg.symmetry_normalised_sites([[0.0, 0.5, 0.5], [1.0, 1.0, 0.0]]) 

525 array([[0., 0., 0.], 

526 [0., 0., 0.]]) 

527 """ 

528 scaled = np.array(scaled_positions, ndmin=2) 

529 normalised = np.empty(scaled.shape, float) 

530 rot, trans = self.get_op() 

531 for i, pos in enumerate(scaled): 

532 sympos = np.dot(rot, pos) + trans 

533 if map_to_unitcell: 

534 # Must be done twice, see the scaled_positions.py test 

535 sympos %= 1.0 

536 sympos %= 1.0 

537 j = np.lexsort(sympos.T)[0] 

538 normalised[i, :] = sympos[j] 

539 return normalised 

540 

541 def unique_sites( 

542 self, 

543 scaled_positions, 

544 symprec=1e-3, 

545 output_mask=False, 

546 map_to_unitcell=True, 

547 ): 

548 """Returns a subset of *scaled_positions* containing only the 

549 symmetry-unique positions. If *output_mask* is True, a boolean 

550 array masking the subset is also returned. 

551 

552 If *map_to_unitcell* is true, all sites are first mapped into 

553 the unit cell making e.g. [0, 0, 0] and [1, 0, 0] equivalent. 

554 

555 Example: 

556 

557 >>> from ase.spacegroup import Spacegroup 

558 >>> sg = Spacegroup(225) # fcc 

559 >>> sg.unique_sites([[0.0, 0.0, 0.0], 

560 ... [0.5, 0.5, 0.0], 

561 ... [1.0, 0.0, 0.0], 

562 ... [0.5, 0.0, 0.0]]) 

563 array([[0. , 0. , 0. ], 

564 [0.5, 0. , 0. ]]) 

565 """ 

566 scaled = np.array(scaled_positions, ndmin=2) 

567 symnorm = self.symmetry_normalised_sites(scaled, map_to_unitcell) 

568 perm = np.lexsort(symnorm.T) 

569 iperm = perm.argsort() 

570 xmask = np.abs(np.diff(symnorm[perm], axis=0)).max(axis=1) > symprec 

571 mask = np.concatenate(([True], xmask)) 

572 imask = mask[iperm] 

573 if output_mask: 

574 return scaled[imask], imask 

575 else: 

576 return scaled[imask] 

577 

578 def tag_sites(self, scaled_positions, symprec=1e-3): 

579 """Returns an integer array of the same length as *scaled_positions*, 

580 tagging all equivalent atoms with the same index. 

581 

582 Example: 

583 

584 >>> from ase.spacegroup import Spacegroup 

585 >>> sg = Spacegroup(225) # fcc 

586 >>> sg.tag_sites([[0.0, 0.0, 0.0], 

587 ... [0.5, 0.5, 0.0], 

588 ... [1.0, 0.0, 0.0], 

589 ... [0.5, 0.0, 0.0]]) 

590 array([0, 0, 0, 1]) 

591 """ 

592 scaled = np.array(scaled_positions, ndmin=2) 

593 scaled %= 1.0 

594 scaled %= 1.0 

595 tags = -np.ones((len(scaled),), dtype=int) 

596 mask = np.ones((len(scaled),), dtype=bool) 

597 rot, trans = self.get_op() 

598 i = 0 

599 while mask.any(): 

600 pos = scaled[mask][0] 

601 sympos = np.dot(rot, pos) + trans 

602 # Must be done twice, see the scaled_positions.py test 

603 sympos %= 1.0 

604 sympos %= 1.0 

605 m = ~np.all( 

606 np.any( 

607 np.abs(scaled[np.newaxis, :, :] - sympos[:, np.newaxis, :]) 

608 > symprec, 

609 axis=2, 

610 ), 

611 axis=0, 

612 ) 

613 assert not np.any((~mask) & m) 

614 tags[m] = i 

615 mask &= ~m 

616 i += 1 

617 return tags 

618 

619 

620def get_datafile(): 

621 """Return default path to datafile.""" 

622 return os.path.join(os.path.dirname(__file__), 'spacegroup.dat') 

623 

624 

625def format_symbol(symbol): 

626 """Returns well formatted Hermann-Mauguin symbol as extected by 

627 the database, by correcting the case and adding missing or 

628 removing dublicated spaces.""" 

629 fixed = [] 

630 s = symbol.strip() 

631 s = s[0].upper() + s[1:].lower() 

632 for c in s: 

633 if c.isalpha(): 

634 if len(fixed) and fixed[-1] == '/': 

635 fixed.append(c) 

636 else: 

637 fixed.append(' ' + c + ' ') 

638 elif c.isspace(): 

639 fixed.append(' ') 

640 elif c.isdigit(): 

641 fixed.append(c) 

642 elif c == '-': 

643 fixed.append(' ' + c) 

644 elif c == '/': 

645 fixed.append(c) 

646 s = ''.join(fixed).strip() 

647 return ' '.join(s.split()) 

648 

649 

650# Functions for parsing the database. They are moved outside the 

651# Spacegroup class in order to make it easier to later implement 

652# caching to avoid reading the database each time a new Spacegroup 

653# instance is created. 

654 

655 

656def _skip_to_blank(f, spacegroup, setting): 

657 """Read lines from f until a blank line is encountered.""" 

658 while True: 

659 line = f.readline() 

660 if not line: 

661 raise SpacegroupNotFoundError( 

662 f'invalid spacegroup `{spacegroup}`, setting `{setting}` not ' 

663 'found in data base' 

664 ) 

665 if not line.strip(): 

666 break 

667 

668 

669def _skip_to_nonblank(f, spacegroup, setting): 

670 """Read lines from f until a nonblank line not starting with a 

671 hash (#) is encountered and returns this and the next line.""" 

672 while True: 

673 line1 = f.readline() 

674 if not line1: 

675 raise SpacegroupNotFoundError( 

676 'invalid spacegroup %s, setting %i not found in data base' 

677 % (spacegroup, setting) 

678 ) 

679 line1.strip() 

680 if line1 and not line1.startswith('#'): 

681 line2 = f.readline() 

682 break 

683 return line1, line2 

684 

685 

686def _read_datafile_entry(spg, no, symbol, setting, f): 

687 """Read space group data from f to spg.""" 

688 

689 floats = {'0.0': 0.0, '1.0': 1.0, '0': 0.0, '1': 1.0, '-1': -1.0} 

690 for n, d in [(1, 2), (1, 3), (2, 3), (1, 4), (3, 4), (1, 6), (5, 6)]: 

691 floats[f'{n}/{d}'] = n / d 

692 floats[f'-{n}/{d}'] = -n / d 

693 

694 spg._no = no 

695 spg._symbol = symbol.strip() 

696 spg._setting = setting 

697 spg._centrosymmetric = bool(int(f.readline().split()[1])) 

698 # primitive vectors 

699 f.readline() 

700 spg._scaled_primitive_cell = np.array( 

701 [ 

702 [float(floats.get(s, s)) for s in f.readline().split()] 

703 for _ in range(3) 

704 ], 

705 dtype=float, 

706 ) 

707 # primitive reciprocal vectors 

708 f.readline() 

709 spg._reciprocal_cell = np.array( 

710 [[int(i) for i in f.readline().split()] for i in range(3)], dtype=int 

711 ) 

712 # subtranslations 

713 nsubtrans = int(f.readline().split()[0]) 

714 spg._subtrans = np.array( 

715 [ 

716 [float(floats.get(t, t)) for t in f.readline().split()] 

717 for _ in range(nsubtrans) 

718 ], 

719 dtype=float, 

720 ) 

721 # symmetry operations 

722 nsym = int(f.readline().split()[0]) 

723 symop = np.array( 

724 [ 

725 [float(floats.get(s, s)) for s in f.readline().split()] 

726 for _ in range(nsym) 

727 ], 

728 dtype=float, 

729 ) 

730 spg._rotations = np.array(symop[:, :9].reshape((nsym, 3, 3)), dtype=int) 

731 spg._translations = symop[:, 9:] 

732 

733 

734@lru_cache 

735def _read_datafile(spacegroup, setting, datafile): 

736 with open(datafile, encoding='utf-8') as fd: 

737 return _read_f(spacegroup, setting, fd) 

738 

739 

740def _read_f(spacegroup, setting, f): 

741 if isinstance(spacegroup, int): 

742 pass 

743 elif isinstance(spacegroup, str): 

744 spacegroup = ' '.join(spacegroup.strip().split()) 

745 compact_spacegroup = ''.join(spacegroup.split()) 

746 else: 

747 raise SpacegroupValueError('`spacegroup` must be of type int or str') 

748 while True: 

749 line1, line2 = _skip_to_nonblank(f, spacegroup, setting) 

750 _no, _symbol = line1.strip().split(None, 1) 

751 _symbol = format_symbol(_symbol) 

752 compact_symbol = ''.join(_symbol.split()) 

753 _setting = int(line2.strip().split()[1]) 

754 _no = int(_no) 

755 

756 condition = ( 

757 ( 

758 isinstance(spacegroup, int) 

759 and _no == spacegroup 

760 and _setting == setting 

761 ) 

762 or ( 

763 isinstance(spacegroup, str) 

764 and compact_symbol == compact_spacegroup 

765 ) 

766 and (setting is None or _setting == setting) 

767 ) 

768 

769 if condition: 

770 namespace = SimpleNamespace() 

771 _read_datafile_entry(namespace, _no, _symbol, _setting, f) 

772 return namespace 

773 else: 

774 _skip_to_blank(f, spacegroup, setting) 

775 

776 

777def parse_sitesym_element(element): 

778 """Parses one element from a single site symmetry in the form used 

779 by the International Tables. 

780 

781 Examples 

782 -------- 

783 

784 >>> parse_sitesym_element("x") 

785 ([(0, 1)], 0.0) 

786 >>> parse_sitesym_element("-1/2-y") 

787 ([(1, -1)], -0.5) 

788 >>> parse_sitesym_element("z+0.25") 

789 ([(2, 1)], 0.25) 

790 >>> parse_sitesym_element("x-z+0.5") 

791 ([(0, 1), (2, -1)], 0.5) 

792 

793 

794 

795 Parameters 

796 ---------- 

797 

798 element: str 

799 Site symmetry like "x" or "-y+1/4" or "0.5+z". 

800 

801 

802 Returns 

803 ------- 

804 

805 list[tuple[int, int]] 

806 Rotation information in the form '(index, sign)' where index is 

807 0 for "x", 1 for "y" and 2 for "z" and sign is '1' for a positive 

808 entry and '-1' for a negative entry. E.g. "x" is '(0, 1)' and 

809 "-z" is (2, -1). 

810 

811 float 

812 Translation information in fractional space. E.g. "-1/4" is 

813 '-0.25' and "1/2" is '0.5' and "0.75" is '0.75'. 

814 

815 

816 """ 

817 element = element.lower() 

818 is_positive = True 

819 is_frac = False 

820 sng_trans = None 

821 fst_trans = [] 

822 snd_trans = [] 

823 rot = [] 

824 

825 for char in element: 

826 if char == '+': 

827 is_positive = True 

828 elif char == '-': 

829 is_positive = False 

830 elif char == '/': 

831 is_frac = True 

832 elif char in 'xyz': 

833 rot.append((ord(char) - ord('x'), 1 if is_positive else -1)) 

834 elif char.isdigit() or char == '.': 

835 if sng_trans is None: 

836 sng_trans = 1.0 if is_positive else -1.0 

837 if is_frac: 

838 snd_trans.append(char) 

839 else: 

840 fst_trans.append(char) 

841 

842 trans = 0.0 if not fst_trans else (sng_trans * float(''.join(fst_trans))) 

843 if is_frac: 

844 trans /= float(''.join(snd_trans)) 

845 

846 return rot, trans 

847 

848 

849def parse_sitesym_single( 

850 sym, out_rot, out_trans, sep=',', force_positive_translation=False 

851): 

852 """Parses a single site symmetry in the form used by International 

853 Tables and overwrites 'out_rot' and 'out_trans' with data. 

854 

855 Parameters 

856 ---------- 

857 

858 sym: str 

859 Site symmetry in the form used by International Tables 

860 (e.g. "x,y,z", "y-1/2,x,-z"). 

861 

862 out_rot: np.array 

863 A 3x3-integer array representing rotations (changes are made inplace). 

864 

865 out_rot: np.array 

866 A 3-float array representing translations (changes are made inplace). 

867 

868 sep: str 

869 String separator ("," in "x,y,z"). 

870 

871 force_positive_translation: bool 

872 Forces fractional translations to be between 0 and 1 (otherwise 

873 negative values might be accepted). Defaults to 'False'. 

874 

875 

876 Returns 

877 ------- 

878 

879 Nothing is returned: 'out_rot' and 'out_trans' are changed inplace. 

880 

881 

882 """ 

883 out_rot[:] = 0.0 

884 out_trans[:] = 0.0 

885 

886 for i, element in enumerate(sym.split(sep)): 

887 e_rot_list, e_trans = parse_sitesym_element(element) 

888 for rot_idx, rot_sgn in e_rot_list: 

889 out_rot[i][rot_idx] = rot_sgn 

890 out_trans[i] = ( 

891 (e_trans % 1.0) if force_positive_translation else e_trans 

892 ) 

893 

894 

895def parse_sitesym(symlist, sep=',', force_positive_translation=False): 

896 """Parses a sequence of site symmetries in the form used by 

897 International Tables and returns corresponding rotation and 

898 translation arrays. 

899 

900 Example: 

901 

902 >>> symlist = [ 

903 ... 'x,y,z', 

904 ... '-y+1/2,x+1/2,z', 

905 ... '-y,-x,-z', 

906 ... 'x-1/4, y-1/4, -z' 

907 ... ] 

908 >>> rot, trans = parse_sitesym(symlist) 

909 >>> rot 

910 array([[[ 1, 0, 0], 

911 [ 0, 1, 0], 

912 [ 0, 0, 1]], 

913 <BLANKLINE> 

914 [[ 0, -1, 0], 

915 [ 1, 0, 0], 

916 [ 0, 0, 1]], 

917 <BLANKLINE> 

918 [[ 0, -1, 0], 

919 [-1, 0, 0], 

920 [ 0, 0, -1]], 

921 <BLANKLINE> 

922 [[ 1, 0, 0], 

923 [ 0, 1, 0], 

924 [ 0, 0, -1]]]) 

925 >>> trans 

926 array([[ 0. , 0. , 0. ], 

927 [ 0.5 , 0.5 , 0. ], 

928 [ 0. , 0. , 0. ], 

929 [-0.25, -0.25, 0. ]]) 

930 """ 

931 

932 nsym = len(symlist) 

933 rot = np.zeros((nsym, 3, 3), dtype='int') 

934 trans = np.zeros((nsym, 3)) 

935 

936 for i, sym in enumerate(symlist): 

937 parse_sitesym_single( 

938 sym, 

939 rot[i], 

940 trans[i], 

941 sep=sep, 

942 force_positive_translation=force_positive_translation, 

943 ) 

944 

945 return rot, trans 

946 

947 

948def spacegroup_from_data( 

949 no=None, 

950 symbol=None, 

951 setting=None, 

952 centrosymmetric=None, 

953 scaled_primitive_cell=None, 

954 reciprocal_cell=None, 

955 subtrans=None, 

956 sitesym=None, 

957 rotations=None, 

958 translations=None, 

959 datafile=None, 

960): 

961 """Manually create a new space group instance. This might be 

962 useful when reading crystal data with its own spacegroup 

963 definitions.""" 

964 if no is not None and setting is not None: 

965 spg = Spacegroup(no, setting, datafile) 

966 elif symbol is not None: 

967 spg = Spacegroup(symbol, None, datafile) 

968 else: 

969 raise SpacegroupValueError( 

970 'either *no* and *setting* or *symbol* must be given' 

971 ) 

972 if not isinstance(sitesym, list): 

973 raise TypeError('sitesym must be a list') 

974 

975 have_sym = False 

976 if centrosymmetric is not None: 

977 spg._centrosymmetric = bool(centrosymmetric) 

978 if scaled_primitive_cell is not None: 

979 spg._scaled_primitive_cell = np.array(scaled_primitive_cell) 

980 if reciprocal_cell is not None: 

981 spg._reciprocal_cell = np.array(reciprocal_cell) 

982 if subtrans is not None: 

983 spg._subtrans = np.atleast_2d(subtrans) 

984 if sitesym is not None: 

985 spg._rotations, spg._translations = parse_sitesym(sitesym) 

986 have_sym = True 

987 if rotations is not None: 

988 spg._rotations = np.atleast_3d(rotations) 

989 have_sym = True 

990 if translations is not None: 

991 spg._translations = np.atleast_2d(translations) 

992 have_sym = True 

993 if have_sym: 

994 if spg._rotations.shape[0] != spg._translations.shape[0]: 

995 raise SpacegroupValueError( 

996 'inconsistent number of rotations and translations' 

997 ) 

998 return spg 

999 

1000 

1001@deprecated( 

1002 '`get_spacegroup` has been deprecated due to its misleading output. ' 

1003 'The returned `Spacegroup` object has symmetry operations for a ' 

1004 'standard setting regardress of the given `Atoms` object. ' 

1005 'See https://gitlab.com/ase/ase/-/issues/1534 for details. ' 

1006 'Please use `ase.spacegroup.symmetrize.check_symmetry` or `spglib` ' 

1007 'directly to get the symmetry operations for the given `Atoms` object.' 

1008) 

1009def get_spacegroup(atoms, symprec=1e-5): 

1010 """Determine the spacegroup to which belongs the Atoms object. 

1011 

1012 This requires spglib: https://atztogo.github.io/spglib/ . 

1013 

1014 .. warning:: 

1015 The returned ``Spacegroup`` object has symmetry operations for a 

1016 standard setting regardless of the given ``Atoms`` object. 

1017 See https://gitlab.com/ase/ase/-/issues/1534 for details. 

1018 

1019 .. deprecated:: 3.24.0 

1020 Please use ``ase.spacegroup.symmetrize.check_symmetry`` or ``spglib`` 

1021 directly to get the symmetry operations for the given ``Atoms`` object. 

1022 

1023 Parameters 

1024 ---------- 

1025 

1026 atoms: Atoms object 

1027 Types, positions and unit-cell. 

1028 symprec: float 

1029 Symmetry tolerance, i.e. distance tolerance in Cartesian 

1030 coordinates to find crystal symmetry. 

1031 

1032 The Spacegroup object is returned. 

1033 """ 

1034 

1035 # Example: 

1036 # (We don't include the example in docstring to appease doctests 

1037 # when import fails) 

1038 # >>> from ase.build import bulk 

1039 # >>> atoms = bulk("Cu", "fcc", a=3.6, cubic=True) 

1040 # >>> sg = get_spacegroup(atoms) 

1041 # >>> sg 

1042 # Spacegroup(225, setting=1) 

1043 # >>> sg.no 

1044 # 225 

1045 

1046 import spglib 

1047 

1048 sg = spglib_new_errorhandling(spglib.get_spacegroup)( 

1049 ( 

1050 atoms.get_cell(), 

1051 atoms.get_scaled_positions(), 

1052 atoms.get_atomic_numbers(), 

1053 ), 

1054 symprec=symprec, 

1055 ) 

1056 if sg is None: 

1057 raise RuntimeError('Spacegroup not found') 

1058 sg_no = int(sg[sg.find('(') + 1 : sg.find(')')]) 

1059 return Spacegroup(sg_no)