Coverage for ase/dft/kpoints.py: 86.80%

341 statements  

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

1from __future__ import annotations 

2 

3import re 

4import warnings 

5from typing import TYPE_CHECKING 

6 

7import numpy as np 

8 

9from ase import Atoms 

10from ase.cell import Cell 

11from ase.utils import jsonable 

12 

13if TYPE_CHECKING: 

14 from ase.spectrum.band_structure import BandStructure 

15 

16 

17def monkhorst_pack(size): 

18 """Construct a uniform sampling of k-space of given size.""" 

19 if np.less_equal(size, 0).any(): 

20 raise ValueError(f'Illegal size: {list(size)}') 

21 kpts = np.indices(size).transpose((1, 2, 3, 0)).reshape((-1, 3)) 

22 return (kpts + 0.5) / size - 0.5 

23 

24 

25def get_monkhorst_pack_size_and_offset(kpts): 

26 """Find Monkhorst-Pack size and offset. 

27 

28 Returns (size, offset), where:: 

29 

30 kpts = monkhorst_pack(size) + offset. 

31 

32 The set of k-points must not have been symmetry reduced.""" 

33 

34 if len(kpts) == 1: 

35 return np.ones(3, int), np.array(kpts[0], dtype=float) 

36 

37 size = np.zeros(3, int) 

38 for c in range(3): 

39 # Determine increment between k-points along current axis 

40 delta = max(np.diff(np.sort(kpts[:, c]))) 

41 

42 # Determine number of k-points as inverse of distance between kpoints 

43 if delta > 1e-8: 

44 size[c] = int(round(1.0 / delta)) 

45 else: 

46 size[c] = 1 

47 

48 if size.prod() == len(kpts): 

49 kpts0 = monkhorst_pack(size) 

50 offsets = kpts - kpts0 

51 

52 # All offsets must be identical: 

53 if (np.ptp(offsets, axis=0) < 1e-9).all(): 

54 return size, offsets[0].copy() 

55 

56 raise ValueError('Not an ASE-style Monkhorst-Pack grid!') 

57 

58 

59def mindistance2monkhorstpack(atoms, *, min_distance, maxperdim=16, even=True): 

60 """Find a Monkhorst-Pack grid (nx, ny, nz) with lowest number of 

61 k-points in the *reducible* Brillouin zone, which still satisfying 

62 a given minimum distance (`min_distance`) condition in real space 

63 (nx, ny, nz)-supercell. 

64 

65 Compared to ase.calculators.calculator kptdensity2monkhorstpack 

66 routine, this metric is based on a physical quantity (real space 

67 distance), and it doesn't depend on non-physical quantities, such as 

68 the cell vectors, since basis vectors can be always transformed 

69 with integer determinant one matrices. In other words, it is 

70 invariant to particular choice of cell representations. 

71 

72 On orthogonal cells, min_distance = 2 * np.pi * kptdensity. 

73 """ 

74 return _mindistance2monkhorstpack( 

75 atoms.cell, atoms.pbc, min_distance, maxperdim, even 

76 ) 

77 

78 

79def _mindistance2monkhorstpack(cell, pbc_c, min_distance, maxperdim, even): 

80 from ase.neighborlist import NeighborList 

81 

82 step = 2 if even else 1 

83 nl = NeighborList( 

84 [min_distance / 2], skin=0.0, self_interaction=False, bothways=False 

85 ) 

86 

87 def check(nkpts_c): 

88 nl.update(Atoms('H', cell=cell @ np.diag(nkpts_c), pbc=pbc_c)) 

89 return len(nl.get_neighbors(0)[1]) == 0 

90 

91 def generate_mpgrids(): 

92 ranges = [ 

93 range(step, maxperdim + 1, step) if pbc else range(1, 2) 

94 for pbc in pbc_c 

95 ] 

96 nkpts_nc = np.column_stack([*map(np.ravel, np.meshgrid(*ranges))]) 

97 yield from sorted(nkpts_nc, key=np.prod) 

98 

99 try: 

100 return next(filter(check, generate_mpgrids())) 

101 except StopIteration: 

102 raise ValueError( 

103 'Could not find a proper k-point grid for the system.' 

104 ' Try running with a larger maxperdim.' 

105 ) 

106 

107 

108def get_monkhorst_shape(kpts): 

109 warnings.warn('Use get_monkhorst_pack_size_and_offset()[0] instead.') 

110 return get_monkhorst_pack_size_and_offset(kpts)[0] 

111 

112 

113def kpoint_convert(cell_cv, skpts_kc=None, ckpts_kv=None): 

114 """Convert k-points between scaled and cartesian coordinates. 

115 

116 Given the atomic unit cell, and either the scaled or cartesian k-point 

117 coordinates, the other is determined. 

118 

119 The k-point arrays can be either a single point, or a list of points, 

120 i.e. the dimension k can be empty or multidimensional. 

121 """ 

122 if ckpts_kv is None: 

123 icell_cv = 2 * np.pi * np.linalg.pinv(cell_cv).T 

124 return np.dot(skpts_kc, icell_cv) 

125 elif skpts_kc is None: 

126 return np.dot(ckpts_kv, cell_cv.T) / (2 * np.pi) 

127 else: 

128 raise KeyError('Either scaled or cartesian coordinates must be given.') 

129 

130 

131def parse_path_string(s): 

132 """Parse compact string representation of BZ path. 

133 

134 A path string can have several non-connected sections separated by 

135 commas. The return value is a list of sections where each section is a 

136 list of labels. 

137 

138 Examples 

139 -------- 

140 

141 >>> parse_path_string('GX') 

142 [['G', 'X']] 

143 >>> parse_path_string('GX,M1A') 

144 [['G', 'X'], ['M1', 'A']] 

145 """ 

146 paths = [] 

147 for path in s.split(','): 

148 names = [name for name in re.split(r'([A-Z][a-z0-9]*)', path) if name] 

149 paths.append(names) 

150 return paths 

151 

152 

153def resolve_kpt_path_string(path, special_points): 

154 paths = parse_path_string(path) 

155 coords = [ 

156 np.array([special_points[sym] for sym in subpath]).reshape(-1, 3) 

157 for subpath in paths 

158 ] 

159 return paths, coords 

160 

161 

162def resolve_custom_points(pathspec, special_points, eps): 

163 """Resolve a path specification into a string. 

164 

165 The path specification is a list path segments, each segment being a kpoint 

166 label or kpoint coordinate, or a single such segment. 

167 

168 Return a string representing the same path. Generic kpoint labels 

169 are generated dynamically as necessary, updating the special_point 

170 dictionary if necessary. The tolerance eps is used to see whether 

171 coordinates are close enough to a special point to deserve being 

172 labelled as such.""" 

173 # This should really run on Cartesian coordinates but we'll probably 

174 # be lazy and call it on scaled ones. 

175 

176 # We may add new points below so take a copy of the input: 

177 special_points = dict(special_points) 

178 

179 if len(pathspec) == 0: 

180 return '', special_points 

181 

182 if isinstance(pathspec, str): 

183 pathspec = parse_path_string(pathspec) 

184 

185 def looks_like_single_kpoint(obj): 

186 if isinstance(obj, str): 

187 return True 

188 try: 

189 arr = np.asarray(obj, float) 

190 except ValueError: 

191 return False 

192 else: 

193 return arr.shape == (3,) 

194 

195 # We accept inputs that are either 

196 # 1) string notation 

197 # 2) list of kpoints (each either a string or three floats) 

198 # 3) list of list of kpoints; each toplevel list is a contiguous subpath 

199 # Here we detect form 2 and normalize to form 3: 

200 for thing in pathspec: 

201 if looks_like_single_kpoint(thing): 

202 pathspec = [pathspec] 

203 break 

204 

205 def name_generator(): 

206 counter = 0 

207 while True: 

208 name = f'Kpt{counter}' 

209 yield name 

210 counter += 1 

211 

212 custom_names = name_generator() 

213 

214 labelseq = [] 

215 for subpath in pathspec: 

216 for kpt in subpath: 

217 if isinstance(kpt, str): 

218 if kpt not in special_points: 

219 raise KeyError( 

220 'No kpoint "{}" among "{}"'.format( 

221 kpt, ''.join(special_points) 

222 ) 

223 ) 

224 labelseq.append(kpt) 

225 continue 

226 

227 kpt = np.asarray(kpt, float) 

228 if kpt.shape != (3,): 

229 raise ValueError(f'Not a valid kpoint: {kpt}') 

230 

231 for key, val in special_points.items(): 

232 if np.abs(kpt - val).max() < eps: 

233 labelseq.append(key) 

234 break # Already present 

235 else: 

236 # New special point - search for name we haven't used yet: 

237 name = next(custom_names) 

238 while name in special_points: 

239 name = next(custom_names) 

240 special_points[name] = kpt 

241 labelseq.append(name) 

242 labelseq.append(',') 

243 

244 last = labelseq.pop() 

245 assert last == ',' 

246 return ''.join(labelseq), special_points 

247 

248 

249def normalize_special_points(special_points): 

250 dct = {} 

251 for name, value in special_points.items(): 

252 if not isinstance(name, str): 

253 raise TypeError('Expected name to be a string') 

254 if np.shape(value) != (3,): 

255 raise ValueError('Expected 3 kpoint coordinates') 

256 dct[name] = np.asarray(value, float) 

257 return dct 

258 

259 

260@jsonable('bandpath') 

261class BandPath: 

262 """Represents a Brillouin zone path or bandpath. 

263 

264 A band path has a unit cell, a path specification, special points, 

265 and interpolated k-points. Band paths are typically created 

266 indirectly using the :class:`~ase.geometry.Cell` or 

267 :class:`~ase.lattice.BravaisLattice` classes: 

268 

269 >>> from ase.lattice import CUB 

270 >>> path = CUB(3).bandpath() 

271 >>> path 

272 BandPath(path='GXMGRX,MR', cell=[3x3], special_points={GMRX}, kpts=[40x3]) 

273 

274 Band paths support JSON I/O: 

275 

276 >>> from ase.io.jsonio import read_json 

277 >>> path.write('mybandpath.json') 

278 >>> read_json('mybandpath.json') 

279 BandPath(path='GXMGRX,MR', cell=[3x3], special_points={GMRX}, kpts=[40x3]) 

280 

281 """ 

282 

283 def __init__(self, cell, kpts=None, special_points=None, path=None): 

284 if kpts is None: 

285 kpts = np.empty((0, 3)) 

286 

287 if special_points is None: 

288 special_points = {} 

289 else: 

290 special_points = normalize_special_points(special_points) 

291 

292 if path is None: 

293 path = '' 

294 

295 cell = Cell(cell) 

296 self._cell = cell 

297 kpts = np.asarray(kpts) 

298 assert kpts.ndim == 2 and kpts.shape[1] == 3 and kpts.dtype == float 

299 self._icell = self.cell.reciprocal() 

300 self._kpts = kpts 

301 self._special_points = special_points 

302 if not isinstance(path, str): 

303 raise TypeError(f'path must be a string; was {path!r}') 

304 self._path = path 

305 

306 @property 

307 def cell(self) -> Cell: 

308 """The :class:`~ase.cell.Cell` of this BandPath.""" 

309 return self._cell 

310 

311 @property 

312 def icell(self) -> Cell: 

313 """Reciprocal cell of this BandPath as a :class:`~ase.cell.Cell`.""" 

314 return self._icell 

315 

316 @property 

317 def kpts(self) -> np.ndarray: 

318 """The kpoints of this BandPath as an array of shape (nkpts, 3). 

319 

320 The kpoints are given in units of the reciprocal cell.""" 

321 return self._kpts 

322 

323 @property 

324 def special_points(self) -> dict[str, np.ndarray]: 

325 """Special points of this BandPath as a dictionary. 

326 

327 The dictionary maps names (such as `'G'`) to kpoint coordinates 

328 in units of the reciprocal cell as a 3-element numpy array. 

329 

330 It's unwise to edit this dictionary directly. If you need that, 

331 consider deepcopying it.""" 

332 return self._special_points 

333 

334 @property 

335 def path(self) -> str: 

336 """The string specification of this band path. 

337 

338 This is a specification of the form `'GXWKGLUWLK,UX'`. 

339 

340 Comma marks a discontinuous jump: K is not connected to U.""" 

341 return self._path 

342 

343 def transform(self, op: np.ndarray) -> BandPath: 

344 """Apply 3x3 matrix to this BandPath and return new BandPath. 

345 

346 This is useful for converting the band path to another cell. 

347 The operation will typically be a permutation/flipping 

348 established by a function such as Niggli reduction.""" 

349 # XXX acceptable operations are probably only those 

350 # who come from Niggli reductions (permutations etc.) 

351 # 

352 # We should insert a check. 

353 # I wonder which operations are valid? They won't be valid 

354 # if they change lengths, volume etc. 

355 special_points = { 

356 name: value @ op for name, value in self.special_points.items() 

357 } 

358 return BandPath( 

359 op.T @ self.cell, 

360 kpts=self.kpts @ op, 

361 special_points=special_points, 

362 path=self.path, 

363 ) 

364 

365 def todict(self): 

366 return { 

367 'kpts': self.kpts, 

368 'special_points': self.special_points, 

369 'labelseq': self.path, 

370 'cell': self.cell, 

371 } 

372 

373 def interpolate( 

374 self, 

375 path: str | None = None, 

376 npoints: int | None = None, 

377 special_points: dict[str, np.ndarray] | None = None, 

378 density: float | None = None, 

379 ) -> BandPath: 

380 """Create new bandpath, (re-)interpolating kpoints from this one.""" 

381 if path is None: 

382 path = self.path 

383 

384 if special_points is None: 

385 special_points = self.special_points 

386 

387 _pathnames, pathcoords = resolve_kpt_path_string(path, special_points) 

388 kpts, _x, _X = paths2kpts(pathcoords, self.cell, npoints, density) 

389 return BandPath( 

390 self.cell, kpts, path=path, special_points=special_points 

391 ) 

392 

393 def _scale(self, coords): 

394 return np.dot(coords, self.icell) 

395 

396 def __repr__(self): 

397 return ( 

398 '{}(path={}, cell=[3x3], special_points={{{}}}, kpts=[{}x3])' 

399 ).format( 

400 self.__class__.__name__, 

401 repr(self.path), 

402 ''.join(sorted(self.special_points)), 

403 len(self.kpts), 

404 ) 

405 

406 def cartesian_kpts(self) -> np.ndarray: 

407 """Get Cartesian kpoints from this bandpath.""" 

408 return self._scale(self.kpts) 

409 

410 def __iter__(self): 

411 """XXX Compatibility hack for bandpath() function. 

412 

413 bandpath() now returns a BandPath object, which is a Good 

414 Thing. However it used to return a tuple of (kpts, x_axis, 

415 special_x_coords), and people would use tuple unpacking for 

416 those. 

417 

418 This function makes tuple unpacking work in the same way. 

419 It will be removed in the future. 

420 

421 """ 

422 warnings.warn( 

423 'Please do not use (kpts, x, X) = bandpath(...). ' 

424 'Use path = bandpath(...) and then kpts = path.kpts and ' 

425 '(x, X, labels) = path.get_linear_kpoint_axis().' 

426 ) 

427 yield self.kpts 

428 

429 x, xspecial, _ = self.get_linear_kpoint_axis() 

430 yield x 

431 yield xspecial 

432 

433 def __getitem__(self, index): 

434 # Temp compatibility stuff, see __iter__ 

435 return tuple(self)[index] 

436 

437 def get_linear_kpoint_axis(self, eps=1e-5): 

438 """Define x axis suitable for plotting a band structure. 

439 

440 See :func:`ase.dft.kpoints.labels_from_kpts`.""" 

441 

442 index2name = self._find_special_point_indices(eps) 

443 indices = sorted(index2name) 

444 labels = [index2name[index] for index in indices] 

445 xcoords, special_xcoords = indices_to_axis_coords( 

446 indices, self.kpts, self.cell 

447 ) 

448 return xcoords, special_xcoords, labels 

449 

450 def _find_special_point_indices(self, eps): 

451 """Find indices of kpoints which are close to special points. 

452 

453 The result is returned as a dictionary mapping indices to labels.""" 

454 # XXX must work in Cartesian coordinates for comparison to eps 

455 # to fully make sense! 

456 index2name = {} 

457 nkpts = len(self.kpts) 

458 

459 for name, kpt in self.special_points.items(): 

460 displacements = self.kpts - kpt[np.newaxis, :] 

461 distances = np.linalg.norm(displacements, axis=1) 

462 args = np.argwhere(distances < eps) 

463 for arg in args.flat: 

464 dist = distances[arg] 

465 # Check if an adjacent point exists and is even closer: 

466 neighbours = distances[ 

467 max(arg - 1, 0) : min(arg + 1, nkpts - 1) 

468 ] 

469 if not any(neighbours < dist): 

470 index2name[arg] = name 

471 

472 return index2name 

473 

474 def plot(self, **plotkwargs): 

475 """Visualize this bandpath. 

476 

477 Plots the irreducible Brillouin zone and this bandpath.""" 

478 import ase.dft.bz as bz 

479 

480 # We previously had a "dimension=3" argument which is now unused. 

481 plotkwargs.pop('dimension', None) 

482 

483 special_points = self.special_points 

484 labelseq, coords = resolve_kpt_path_string(self.path, special_points) 

485 

486 paths = [] 

487 points_already_plotted = set() 

488 for subpath_labels, subpath_coords in zip(labelseq, coords): 

489 subpath_coords = np.array(subpath_coords) 

490 points_already_plotted.update(subpath_labels) 

491 paths.append((subpath_labels, self._scale(subpath_coords))) 

492 

493 # Add each special point as a single-point subpath if they were 

494 # not plotted already: 

495 for label, point in special_points.items(): 

496 if label not in points_already_plotted: 

497 paths.append(([label], [self._scale(point)])) 

498 

499 kw = {'vectors': True, 'pointstyle': {'marker': '.'}} 

500 

501 kw.update(plotkwargs) 

502 return bz.bz_plot( 

503 self.cell, paths=paths, points=self.cartesian_kpts(), **kw 

504 ) 

505 

506 def free_electron_band_structure(self, **kwargs) -> BandStructure: 

507 """Return band structure of free electrons for this bandpath. 

508 

509 Keyword arguments are passed to 

510 :class:`~ase.calculators.test.FreeElectrons`. 

511 

512 This is for mostly testing and visualization.""" 

513 from ase.calculators.test import FreeElectrons 

514 from ase.spectrum.band_structure import calculate_band_structure 

515 

516 atoms = Atoms(cell=self.cell, pbc=True) 

517 atoms.calc = FreeElectrons(**kwargs) 

518 bs = calculate_band_structure(atoms, path=self) 

519 return bs 

520 

521 

522def bandpath( 

523 path, cell, npoints=None, density=None, special_points=None, eps=2e-4 

524): 

525 """Make a list of kpoints defining the path between the given points. 

526 

527 path: list or str 

528 Can be: 

529 

530 * a string that parse_path_string() understands: 'GXL' 

531 * a list of BZ points: [(0, 0, 0), (0.5, 0, 0)] 

532 * or several lists of BZ points if the the path is not continuous. 

533 cell: 3x3 

534 Unit cell of the atoms. 

535 npoints: int 

536 Length of the output kpts list. If too small, at least the beginning 

537 and ending point of each path segment will be used. If None (default), 

538 it will be calculated using the supplied density or a default one. 

539 density: float 

540 k-points per 1/A on the output kpts list. If npoints is None, 

541 the number of k-points in the output list will be: 

542 npoints = density * path total length (in Angstroms). 

543 If density is None (default), use 5 k-points per A⁻¹. 

544 If the calculated npoints value is less than 50, a minimum value of 50 

545 will be used. 

546 special_points: dict or None 

547 Dictionary mapping names to special points. If None, the special 

548 points will be derived from the cell. 

549 eps: float 

550 Precision used to identify Bravais lattice, deducing special points. 

551 

552 You may define npoints or density but not both. 

553 

554 Return a :class:`~ase.dft.kpoints.BandPath` object.""" 

555 

556 cell = Cell.ascell(cell) 

557 return cell.bandpath( 

558 path, 

559 npoints=npoints, 

560 density=density, 

561 special_points=special_points, 

562 eps=eps, 

563 ) 

564 

565 

566DEFAULT_KPTS_DENSITY = 5 # points per 1/Angstrom 

567 

568 

569def paths2kpts(paths, cell, npoints=None, density=None): 

570 if npoints is not None and density is not None: 

571 raise ValueError('You may define npoints or density, but not both.') 

572 points = np.concatenate(paths) 

573 dists = points[1:] - points[:-1] 

574 lengths = [np.linalg.norm(d) for d in kpoint_convert(cell, skpts_kc=dists)] 

575 

576 i = 0 

577 for path in paths[:-1]: 

578 i += len(path) 

579 lengths[i - 1] = 0 

580 

581 length = sum(lengths) 

582 

583 if npoints is None: 

584 if density is None: 

585 density = DEFAULT_KPTS_DENSITY 

586 # Set npoints using the length of the path 

587 npoints = int(round(length * density)) 

588 

589 kpts = [] 

590 x0 = 0 

591 x = [] 

592 X = [0] 

593 for P, d, L in zip(points[:-1], dists, lengths): 

594 diff = length - x0 

595 if abs(diff) < 1e-6: 

596 n = 0 

597 else: 

598 n = max(2, int(round(L * (npoints - len(x)) / diff))) 

599 

600 for t in np.linspace(0, 1, n)[:-1]: 

601 kpts.append(P + t * d) 

602 x.append(x0 + t * L) 

603 x0 += L 

604 X.append(x0) 

605 if len(points): 

606 kpts.append(points[-1]) 

607 x.append(x0) 

608 

609 if len(kpts) == 0: 

610 kpts = np.empty((0, 3)) 

611 

612 return np.array(kpts), np.array(x), np.array(X) 

613 

614 

615get_bandpath = bandpath # old name 

616 

617 

618def find_bandpath_kinks(cell, kpts, eps=1e-5): 

619 """Find indices of those kpoints that are not interior to a line segment.""" 

620 # XXX Should use the Cartesian kpoints. 

621 # Else comparison to eps will be anisotropic and hence arbitrary. 

622 diffs = kpts[1:] - kpts[:-1] 

623 kinks = abs(diffs[1:] - diffs[:-1]).sum(1) > eps 

624 N = len(kpts) 

625 indices = [] 

626 if N > 0: 

627 indices.append(0) 

628 indices.extend(np.arange(1, N - 1)[kinks]) 

629 indices.append(N - 1) 

630 return indices 

631 

632 

633def labels_from_kpts(kpts, cell, eps=1e-5, special_points=None): 

634 """Get an x-axis to be used when plotting a band structure. 

635 

636 The first of the returned lists can be used as a x-axis when plotting 

637 the band structure. The second list can be used as xticks, and the third 

638 as xticklabels. 

639 

640 Parameters 

641 ---------- 

642 

643 kpts: list 

644 List of scaled k-points. 

645 

646 cell: list 

647 Unit cell of the atomic structure. 

648 

649 Returns 

650 ------- 

651 

652 Three arrays; the first is a list of cumulative distances between k-points, 

653 the second is x coordinates of the special points, 

654 the third is the special points as strings. 

655 """ 

656 

657 if special_points is None: 

658 special_points = get_special_points(cell) 

659 points = np.asarray(kpts) 

660 # XXX Due to this mechanism, we are blind to special points 

661 # that lie on straight segments such as [K, G, -K]. 

662 indices = find_bandpath_kinks(cell, kpts, eps=1e-5) 

663 

664 labels = [] 

665 for kpt in points[indices]: 

666 for label, k in special_points.items(): 

667 if abs(kpt - k).sum() < eps: 

668 break 

669 else: 

670 # No exact match. Try modulus 1: 

671 for label, k in special_points.items(): 

672 if abs((kpt - k) % 1).sum() < eps: 

673 break 

674 else: 

675 label = '?' 

676 labels.append(label) 

677 

678 xcoords, ixcoords = indices_to_axis_coords(indices, points, cell) 

679 return xcoords, ixcoords, labels 

680 

681 

682def indices_to_axis_coords(indices, points, cell): 

683 jump = False # marks a discontinuity in the path 

684 xcoords = [0] 

685 for i1, i2 in zip(indices[:-1], indices[1:]): 

686 if not jump and i1 + 1 == i2: 

687 length = 0 

688 jump = True # we don't want two jumps in a row 

689 else: 

690 diff = points[i2] - points[i1] 

691 length = np.linalg.norm(kpoint_convert(cell, skpts_kc=diff)) 

692 jump = False 

693 xcoords.extend(np.linspace(0, length, i2 - i1 + 1)[1:] + xcoords[-1]) 

694 

695 xcoords = np.array(xcoords) 

696 return xcoords, xcoords[indices] 

697 

698 

699special_paths = { 

700 'cubic': 'GXMGRX,MR', 

701 'fcc': 'GXWKGLUWLK,UX', 

702 'bcc': 'GHNGPH,PN', 

703 'tetragonal': 'GXMGZRAZXR,MA', 

704 'orthorhombic': 'GXSYGZURTZ,YT,UX,SR', 

705 'hexagonal': 'GMKGALHA,LM,KH', 

706 'monoclinic': 'GYHCEM1AXH1,MDZ,YD', 

707 'rhombohedral type 1': 'GLB1,BZGX,QFP1Z,LP', 

708 'rhombohedral type 2': 'GPZQGFP1Q1LZ', 

709} 

710 

711 

712def get_special_points(cell, lattice=None, eps=2e-4): 

713 """Return dict of special points. 

714 

715 The definitions are from a paper by Wahyu Setyawana and Stefano 

716 Curtarolo:: 

717 

718 https://doi.org/10.1016/j.commatsci.2010.05.010 

719 

720 cell: 3x3 ndarray 

721 Unit cell. 

722 lattice: str 

723 Optionally check that the cell is one of the following: cubic, fcc, 

724 bcc, orthorhombic, tetragonal, hexagonal or monoclinic. 

725 eps: float 

726 Tolerance for cell-check. 

727 """ 

728 

729 if isinstance(cell, str): 

730 warnings.warn( 

731 'Please call this function with cell as the first argument' 

732 ) 

733 lattice, cell = cell, lattice 

734 

735 cell = Cell.ascell(cell) 

736 # We create the bandpath because we want to transform the kpoints too, 

737 # from the canonical cell to the given one. 

738 # 

739 # Note that this function is missing a tolerance, epsilon. 

740 path = cell.bandpath(npoints=0) 

741 return path.special_points 

742 

743 

744def monkhorst_pack_interpolate( 

745 path, values, icell, bz2ibz, size, offset=(0, 0, 0), pad_width=2 

746): 

747 """Interpolate values from Monkhorst-Pack sampling. 

748 

749 `monkhorst_pack_interpolate` takes a set of `values`, for example 

750 eigenvalues, that are resolved on a Monkhorst Pack k-point grid given by 

751 `size` and `offset` and interpolates the values onto the k-points 

752 in `path`. 

753 

754 Note 

755 ---- 

756 For the interpolation to work, path has to lie inside the domain 

757 that is spanned by the MP kpoint grid given by size and offset. 

758 

759 To try to ensure this we expand the domain slightly by adding additional 

760 entries along the edges and sides of the domain with values determined by 

761 wrapping the values to the opposite side of the domain. In this way we 

762 assume that the function to be interpolated is a periodic function in 

763 k-space. The padding width is determined by the `pad_width` parameter. 

764 

765 Parameters 

766 ---------- 

767 path: (nk, 3) array-like 

768 Desired path in units of reciprocal lattice vectors. 

769 values: (nibz, ...) array-like 

770 Values on Monkhorst-Pack grid. 

771 icell: (3, 3) array-like 

772 Reciprocal lattice vectors. 

773 bz2ibz: (nbz,) array-like of int 

774 Map from nbz points in BZ to nibz reduced points in IBZ. 

775 size: (3,) array-like of int 

776 Size of Monkhorst-Pack grid. 

777 offset: (3,) array-like 

778 Offset of Monkhorst-Pack grid. 

779 pad_width: int 

780 Padding width to aid interpolation 

781 

782 Returns 

783 ------- 

784 (nbz,) array-like 

785 *values* interpolated to *path*. 

786 """ 

787 from scipy.interpolate import LinearNDInterpolator 

788 

789 path = (np.asarray(path) + 0.5) % 1 - 0.5 

790 path = np.dot(path, icell) 

791 

792 # Fold out values from IBZ to BZ: 

793 v = np.asarray(values)[bz2ibz] 

794 v = v.reshape(tuple(size) + v.shape[1:]) 

795 

796 # Create padded Monkhorst-Pack grid: 

797 size = np.asarray(size) 

798 i = ( 

799 np.indices(size + 2 * pad_width) 

800 .transpose((1, 2, 3, 0)) 

801 .reshape((-1, 3)) 

802 ) 

803 k = (i - pad_width + 0.5) / size - 0.5 + offset 

804 k = np.dot(k, icell) 

805 

806 # Fill in boundary values: 

807 V = np.pad( 

808 v, [(pad_width, pad_width)] * 3 + [(0, 0)] * (v.ndim - 3), mode='wrap' 

809 ) 

810 

811 interpolate = LinearNDInterpolator(k, V.reshape((-1,) + V.shape[3:])) 

812 interpolated_points = interpolate(path) 

813 

814 # NaN values indicate points outside interpolation domain, if fail 

815 # try increasing padding 

816 assert not np.isnan(interpolated_points).any(), ( 

817 'Points outside interpolation domain. Try increasing pad_width.' 

818 ) 

819 

820 return interpolated_points 

821 

822 

823# ChadiCohen k point grids. The k point grids are given in units of the 

824# reciprocal unit cell. The variables are named after the following 

825# convention: cc+'<Nkpoints>'+_+'shape'. For example an 18 k point 

826# sq(3)xsq(3) is named 'cc18_sq3xsq3'. 

827 

828# fmt: off 

829 

830cc6_1x1 = np.array([ 

831 1, 1, 0, 1, 0, 0, 0, -1, 0, -1, -1, 0, -1, 0, 0, 

832 0, 1, 0]).reshape((6, 3)) / 3.0 

833 

834cc12_2x3 = np.array([ 

835 3, 4, 0, 3, 10, 0, 6, 8, 0, 3, -2, 0, 6, -4, 0, 

836 6, 2, 0, -3, 8, 0, -3, 2, 0, -3, -4, 0, -6, 4, 0, -6, -2, 0, -6, 

837 -8, 0]).reshape((12, 3)) / 18.0 

838 

839cc18_sq3xsq3 = np.array([ 

840 2, 2, 0, 4, 4, 0, 8, 2, 0, 4, -2, 0, 8, -4, 

841 0, 10, -2, 0, 10, -8, 0, 8, -10, 0, 2, -10, 0, 4, -8, 0, -2, -8, 

842 0, 2, -4, 0, -4, -4, 0, -2, -2, 0, -4, 2, 0, -2, 4, 0, -8, 4, 0, 

843 -4, 8, 0]).reshape((18, 3)) / 18.0 

844 

845cc18_1x1 = np.array([ 

846 2, 4, 0, 2, 10, 0, 4, 8, 0, 8, 4, 0, 8, 10, 0, 

847 10, 8, 0, 2, -2, 0, 4, -4, 0, 4, 2, 0, -2, 8, 0, -2, 2, 0, -2, -4, 

848 0, -4, 4, 0, -4, -2, 0, -4, -8, 0, -8, 2, 0, -8, -4, 0, -10, -2, 

849 0]).reshape((18, 3)) / 18.0 

850 

851cc54_sq3xsq3 = np.array([ 

852 4, -10, 0, 6, -10, 0, 0, -8, 0, 2, -8, 0, 6, 

853 -8, 0, 8, -8, 0, -4, -6, 0, -2, -6, 0, 2, -6, 0, 4, -6, 0, 8, -6, 

854 0, 10, -6, 0, -6, -4, 0, -2, -4, 0, 0, -4, 0, 4, -4, 0, 6, -4, 0, 

855 10, -4, 0, -6, -2, 0, -4, -2, 0, 0, -2, 0, 2, -2, 0, 6, -2, 0, 8, 

856 -2, 0, -8, 0, 0, -4, 0, 0, -2, 0, 0, 2, 0, 0, 4, 0, 0, 8, 0, 0, 

857 -8, 2, 0, -6, 2, 0, -2, 2, 0, 0, 2, 0, 4, 2, 0, 6, 2, 0, -10, 4, 

858 0, -6, 4, 0, -4, 4, 0, 0, 4, 0, 2, 4, 0, 6, 4, 0, -10, 6, 0, -8, 

859 6, 0, -4, 6, 0, -2, 6, 0, 2, 6, 0, 4, 6, 0, -8, 8, 0, -6, 8, 0, 

860 -2, 8, 0, 0, 8, 0, -6, 10, 0, -4, 10, 0]).reshape((54, 3)) / 18.0 

861 

862cc54_1x1 = np.array([ 

863 2, 2, 0, 4, 4, 0, 8, 8, 0, 6, 8, 0, 4, 6, 0, 6, 

864 10, 0, 4, 10, 0, 2, 6, 0, 2, 8, 0, 0, 2, 0, 0, 4, 0, 0, 8, 0, -2, 

865 6, 0, -2, 4, 0, -4, 6, 0, -6, 4, 0, -4, 2, 0, -6, 2, 0, -2, 0, 0, 

866 -4, 0, 0, -8, 0, 0, -8, -2, 0, -6, -2, 0, -10, -4, 0, -10, -6, 0, 

867 -6, -4, 0, -8, -6, 0, -2, -2, 0, -4, -4, 0, -8, -8, 0, 4, -2, 0, 

868 6, -2, 0, 6, -4, 0, 2, 0, 0, 4, 0, 0, 6, 2, 0, 6, 4, 0, 8, 6, 0, 

869 8, 0, 0, 8, 2, 0, 10, 4, 0, 10, 6, 0, 2, -4, 0, 2, -6, 0, 4, -6, 

870 0, 0, -2, 0, 0, -4, 0, -2, -6, 0, -4, -6, 0, -6, -8, 0, 0, -8, 0, 

871 -2, -8, 0, -4, -10, 0, -6, -10, 0]).reshape((54, 3)) / 18.0 

872 

873cc162_sq3xsq3 = np.array([ 

874 -8, 16, 0, -10, 14, 0, -7, 14, 0, -4, 14, 

875 0, -11, 13, 0, -8, 13, 0, -5, 13, 0, -2, 13, 0, -13, 11, 0, -10, 

876 11, 0, -7, 11, 0, -4, 11, 0, -1, 11, 0, 2, 11, 0, -14, 10, 0, -11, 

877 10, 0, -8, 10, 0, -5, 10, 0, -2, 10, 0, 1, 10, 0, 4, 10, 0, -16, 

878 8, 0, -13, 8, 0, -10, 8, 0, -7, 8, 0, -4, 8, 0, -1, 8, 0, 2, 8, 0, 

879 5, 8, 0, 8, 8, 0, -14, 7, 0, -11, 7, 0, -8, 7, 0, -5, 7, 0, -2, 7, 

880 0, 1, 7, 0, 4, 7, 0, 7, 7, 0, 10, 7, 0, -13, 5, 0, -10, 5, 0, -7, 

881 5, 0, -4, 5, 0, -1, 5, 0, 2, 5, 0, 5, 5, 0, 8, 5, 0, 11, 5, 0, 

882 -14, 4, 0, -11, 4, 0, -8, 4, 0, -5, 4, 0, -2, 4, 0, 1, 4, 0, 4, 4, 

883 0, 7, 4, 0, 10, 4, 0, -13, 2, 0, -10, 2, 0, -7, 2, 0, -4, 2, 0, 

884 -1, 2, 0, 2, 2, 0, 5, 2, 0, 8, 2, 0, 11, 2, 0, -11, 1, 0, -8, 1, 

885 0, -5, 1, 0, -2, 1, 0, 1, 1, 0, 4, 1, 0, 7, 1, 0, 10, 1, 0, 13, 1, 

886 0, -10, -1, 0, -7, -1, 0, -4, -1, 0, -1, -1, 0, 2, -1, 0, 5, -1, 

887 0, 8, -1, 0, 11, -1, 0, 14, -1, 0, -11, -2, 0, -8, -2, 0, -5, -2, 

888 0, -2, -2, 0, 1, -2, 0, 4, -2, 0, 7, -2, 0, 10, -2, 0, 13, -2, 0, 

889 -10, -4, 0, -7, -4, 0, -4, -4, 0, -1, -4, 0, 2, -4, 0, 5, -4, 0, 

890 8, -4, 0, 11, -4, 0, 14, -4, 0, -8, -5, 0, -5, -5, 0, -2, -5, 0, 

891 1, -5, 0, 4, -5, 0, 7, -5, 0, 10, -5, 0, 13, -5, 0, 16, -5, 0, -7, 

892 -7, 0, -4, -7, 0, -1, -7, 0, 2, -7, 0, 5, -7, 0, 8, -7, 0, 11, -7, 

893 0, 14, -7, 0, 17, -7, 0, -8, -8, 0, -5, -8, 0, -2, -8, 0, 1, -8, 

894 0, 4, -8, 0, 7, -8, 0, 10, -8, 0, 13, -8, 0, 16, -8, 0, -7, -10, 

895 0, -4, -10, 0, -1, -10, 0, 2, -10, 0, 5, -10, 0, 8, -10, 0, 11, 

896 -10, 0, 14, -10, 0, 17, -10, 0, -5, -11, 0, -2, -11, 0, 1, -11, 0, 

897 4, -11, 0, 7, -11, 0, 10, -11, 0, 13, -11, 0, 16, -11, 0, -1, -13, 

898 0, 2, -13, 0, 5, -13, 0, 8, -13, 0, 11, -13, 0, 14, -13, 0, 1, 

899 -14, 0, 4, -14, 0, 7, -14, 0, 10, -14, 0, 13, -14, 0, 5, -16, 0, 

900 8, -16, 0, 11, -16, 0, 7, -17, 0, 10, -17, 0]).reshape((162, 3)) / 27.0 

901 

902cc162_1x1 = np.array([ 

903 -8, -16, 0, -10, -14, 0, -7, -14, 0, -4, -14, 

904 0, -11, -13, 0, -8, -13, 0, -5, -13, 0, -2, -13, 0, -13, -11, 0, 

905 -10, -11, 0, -7, -11, 0, -4, -11, 0, -1, -11, 0, 2, -11, 0, -14, 

906 -10, 0, -11, -10, 0, -8, -10, 0, -5, -10, 0, -2, -10, 0, 1, -10, 

907 0, 4, -10, 0, -16, -8, 0, -13, -8, 0, -10, -8, 0, -7, -8, 0, -4, 

908 -8, 0, -1, -8, 0, 2, -8, 0, 5, -8, 0, 8, -8, 0, -14, -7, 0, -11, 

909 -7, 0, -8, -7, 0, -5, -7, 0, -2, -7, 0, 1, -7, 0, 4, -7, 0, 7, -7, 

910 0, 10, -7, 0, -13, -5, 0, -10, -5, 0, -7, -5, 0, -4, -5, 0, -1, 

911 -5, 0, 2, -5, 0, 5, -5, 0, 8, -5, 0, 11, -5, 0, -14, -4, 0, -11, 

912 -4, 0, -8, -4, 0, -5, -4, 0, -2, -4, 0, 1, -4, 0, 4, -4, 0, 7, -4, 

913 0, 10, -4, 0, -13, -2, 0, -10, -2, 0, -7, -2, 0, -4, -2, 0, -1, 

914 -2, 0, 2, -2, 0, 5, -2, 0, 8, -2, 0, 11, -2, 0, -11, -1, 0, -8, 

915 -1, 0, -5, -1, 0, -2, -1, 0, 1, -1, 0, 4, -1, 0, 7, -1, 0, 10, -1, 

916 0, 13, -1, 0, -10, 1, 0, -7, 1, 0, -4, 1, 0, -1, 1, 0, 2, 1, 0, 5, 

917 1, 0, 8, 1, 0, 11, 1, 0, 14, 1, 0, -11, 2, 0, -8, 2, 0, -5, 2, 0, 

918 -2, 2, 0, 1, 2, 0, 4, 2, 0, 7, 2, 0, 10, 2, 0, 13, 2, 0, -10, 4, 

919 0, -7, 4, 0, -4, 4, 0, -1, 4, 0, 2, 4, 0, 5, 4, 0, 8, 4, 0, 11, 4, 

920 0, 14, 4, 0, -8, 5, 0, -5, 5, 0, -2, 5, 0, 1, 5, 0, 4, 5, 0, 7, 5, 

921 0, 10, 5, 0, 13, 5, 0, 16, 5, 0, -7, 7, 0, -4, 7, 0, -1, 7, 0, 2, 

922 7, 0, 5, 7, 0, 8, 7, 0, 11, 7, 0, 14, 7, 0, 17, 7, 0, -8, 8, 0, 

923 -5, 8, 0, -2, 8, 0, 1, 8, 0, 4, 8, 0, 7, 8, 0, 10, 8, 0, 13, 8, 0, 

924 16, 8, 0, -7, 10, 0, -4, 10, 0, -1, 10, 0, 2, 10, 0, 5, 10, 0, 8, 

925 10, 0, 11, 10, 0, 14, 10, 0, 17, 10, 0, -5, 11, 0, -2, 11, 0, 1, 

926 11, 0, 4, 11, 0, 7, 11, 0, 10, 11, 0, 13, 11, 0, 16, 11, 0, -1, 

927 13, 0, 2, 13, 0, 5, 13, 0, 8, 13, 0, 11, 13, 0, 14, 13, 0, 1, 14, 

928 0, 4, 14, 0, 7, 14, 0, 10, 14, 0, 13, 14, 0, 5, 16, 0, 8, 16, 0, 

929 11, 16, 0, 7, 17, 0, 10, 17, 0]).reshape((162, 3)) / 27.0 

930 

931 

932# The following is a list of the critical points in the 1st Brillouin zone 

933# for some typical crystal structures following the conventions of Setyawan 

934# and Curtarolo [https://doi.org/10.1016/j.commatsci.2010.05.010]. 

935# 

936# In units of the reciprocal basis vectors. 

937# 

938# See http://en.wikipedia.org/wiki/Brillouin_zone 

939sc_special_points = { 

940 'cubic': {'G': [0, 0, 0], 

941 'M': [1 / 2, 1 / 2, 0], 

942 'R': [1 / 2, 1 / 2, 1 / 2], 

943 'X': [0, 1 / 2, 0]}, 

944 'fcc': {'G': [0, 0, 0], 

945 'K': [3 / 8, 3 / 8, 3 / 4], 

946 'L': [1 / 2, 1 / 2, 1 / 2], 

947 'U': [5 / 8, 1 / 4, 5 / 8], 

948 'W': [1 / 2, 1 / 4, 3 / 4], 

949 'X': [1 / 2, 0, 1 / 2]}, 

950 'bcc': {'G': [0, 0, 0], 

951 'H': [1 / 2, -1 / 2, 1 / 2], 

952 'P': [1 / 4, 1 / 4, 1 / 4], 

953 'N': [0, 0, 1 / 2]}, 

954 'tetragonal': {'G': [0, 0, 0], 

955 'A': [1 / 2, 1 / 2, 1 / 2], 

956 'M': [1 / 2, 1 / 2, 0], 

957 'R': [0, 1 / 2, 1 / 2], 

958 'X': [0, 1 / 2, 0], 

959 'Z': [0, 0, 1 / 2]}, 

960 'orthorhombic': {'G': [0, 0, 0], 

961 'R': [1 / 2, 1 / 2, 1 / 2], 

962 'S': [1 / 2, 1 / 2, 0], 

963 'T': [0, 1 / 2, 1 / 2], 

964 'U': [1 / 2, 0, 1 / 2], 

965 'X': [1 / 2, 0, 0], 

966 'Y': [0, 1 / 2, 0], 

967 'Z': [0, 0, 1 / 2]}, 

968 'hexagonal': {'G': [0, 0, 0], 

969 'A': [0, 0, 1 / 2], 

970 'H': [1 / 3, 1 / 3, 1 / 2], 

971 'K': [1 / 3, 1 / 3, 0], 

972 'L': [1 / 2, 0, 1 / 2], 

973 'M': [1 / 2, 0, 0]}} 

974 

975 

976# Old version of dictionary kept for backwards compatibility. 

977# Not for ordinary use. 

978ibz_points = {'cubic': {'Gamma': [0, 0, 0], 

979 'X': [0, 0 / 2, 1 / 2], 

980 'R': [1 / 2, 1 / 2, 1 / 2], 

981 'M': [0 / 2, 1 / 2, 1 / 2]}, 

982 'fcc': {'Gamma': [0, 0, 0], 

983 'X': [1 / 2, 0, 1 / 2], 

984 'W': [1 / 2, 1 / 4, 3 / 4], 

985 'K': [3 / 8, 3 / 8, 3 / 4], 

986 'U': [5 / 8, 1 / 4, 5 / 8], 

987 'L': [1 / 2, 1 / 2, 1 / 2]}, 

988 'bcc': {'Gamma': [0, 0, 0], 

989 'H': [1 / 2, -1 / 2, 1 / 2], 

990 'N': [0, 0, 1 / 2], 

991 'P': [1 / 4, 1 / 4, 1 / 4]}, 

992 'hexagonal': {'Gamma': [0, 0, 0], 

993 'M': [0, 1 / 2, 0], 

994 'K': [-1 / 3, 1 / 3, 0], 

995 'A': [0, 0, 1 / 2], 

996 'L': [0, 1 / 2, 1 / 2], 

997 'H': [-1 / 3, 1 / 3, 1 / 2]}, 

998 'tetragonal': {'Gamma': [0, 0, 0], 

999 'X': [1 / 2, 0, 0], 

1000 'M': [1 / 2, 1 / 2, 0], 

1001 'Z': [0, 0, 1 / 2], 

1002 'R': [1 / 2, 0, 1 / 2], 

1003 'A': [1 / 2, 1 / 2, 1 / 2]}, 

1004 'orthorhombic': {'Gamma': [0, 0, 0], 

1005 'R': [1 / 2, 1 / 2, 1 / 2], 

1006 'S': [1 / 2, 1 / 2, 0], 

1007 'T': [0, 1 / 2, 1 / 2], 

1008 'U': [1 / 2, 0, 1 / 2], 

1009 'X': [1 / 2, 0, 0], 

1010 'Y': [0, 1 / 2, 0], 

1011 'Z': [0, 0, 1 / 2]}}