vibe-sketcherDocumentation
Source code for vibesketcher.document.kpath
"""High-symmetry k-points and band paths of the first Brillouin zone (#189).
The points, their labels and the paths are those of W. Setyawan and
S. Curtarolo, "High-throughput electronic band structure calculations:
Challenges and tools", Comput. Mater. Sci. 49, 299-312 (2010),
doi:10.1016/j.commatsci.2010.05.010 (arXiv:1004.2974), Appendix A: the 14
Bravais lattices in 25 variants. Fractions in the paper refer to the
reciprocal vectors of its *standard primitive* cell, which is built here from
the conventional cell with the paper's axis orderings (a < b < c for the
orthorhombic lattices, a < b for C-centred orthorhombic, the unique axis
first with alpha < 90 degrees for monoclinic). For triclinic lattices the
paper chooses the primitive cell whose reciprocal vectors cross the centres
of the first zone's Bragg planes; that is the Niggli-reduced reciprocal
basis here (I. Krivy and B. Gruber, Acta Cryst. A32, 297 (1976), through
spglib), all-acute (TRI1b) or all-obtuse (TRI1a, TRI2a when k_gamma is 90).
The lattice is classified on its own (one lattice point per cell, at the
length tolerance ``symprec``), because the labels belong to the zone that is
drawn: the Wigner-Seitz cell of the stored cell's reciprocal lattice. The
result says when the crystal's point group is lower than the lattice's, or
when the stored cell holds more than one primitive cell (the zone is then a
folded one); both are reported, never corrected.
Every point is checked to lie in the first zone before it is returned, within
the strain the tolerance admits (a lattice accepted at ``symprec`` may be
that far from ideal), so a convention that does not fit the cell is refused,
not drawn. Needs the
optional symmetry extra (spglib).
The paper gives no plane lattices. A slab (two periodic directions) is
labelled on the section k_perp = 0 of the zone of its *prism lattice*: the
plane lattice stacked along its normal at a spacing longer than every reduced
in-plane vector, so the stacking adds a mirror and nothing else. That prism is
TET, ORC, ORCC, HEX or MCL (unique axis along the normal) for the square,
rectangular, centred rectangular, hexagonal and oblique plane lattices, and
its zone is the plane zone times a k_perp interval, so the in-plane points of
the paper's table are the plane zone's points, under the paper's labels. The
``ase.lattice`` module of ASE (A. H. Larsen et al., J. Phys.: Condens. Matter 29,
273002 (2017)) uses the same labels for its square, rectangular, hexagonal and
oblique lattices. The
plane path is the paper's path restricted to the plane (TET, ORC, HEX), and for
ORCC and MCL, whose restricted paths are disconnected, the closed boundary of
the irreducible wedge through the same points, as drawn for all five lattices
by D. Röhlig et al., Phys. Rev. B 113, 144319 (2026), doi:10.1103/9ql7-t9rh,
Fig. 7 (who rename some of the points). Wires are refused.
"""
from __future__ import annotations
import itertools
import math
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
import numpy as np
from vibesketcher.document import crystal, symmetry
from vibesketcher.document.model import PeriodicStructure
from vibesketcher.elements import ATOMIC_NUMBER
REFERENCE = (
"W. Setyawan and S. Curtarolo, Comput. Mater. Sci. 49, 299-312 (2010), "
"doi:10.1016/j.commatsci.2010.05.010"
)
CONVENTION = (
"k = f1 b1 + f2 b2 + f3 b3 with b_i . a_j = 2 pi delta_ij; fractional coordinates refer "
"to the reciprocal basis of this structure's own cell"
)
PLANE_REFERENCE = (
f"{REFERENCE}, in-plane section of the prism lattice's zone; wedge paths as in "
"D. Röhlig et al., Phys. Rev. B 113, 144319 (2026), doi:10.1103/9ql7-t9rh"
)
PLANE_CONVENTION = (
"k = f_i b_i + f_j b_j over the two periodic axes i, j, with b_i . a_j = 2 pi delta_ij and "
"b_i in the periodic plane; the fraction along the non-periodic axis is 0"
)
#: Prism lattice -> (plane lattice, name, plane Bravais symbol, path). The paths
#: are the paper's own in-plane loops for TET, ORC and HEX; for ORCC and MCL they
#: close the paper's in-plane segments (Γ-X-S, Γ-Y-X1; Γ-Y-H-C, X-H1) along the
#: boundary of the irreducible wedge.
_PLANE = {
"TET": ("SQR", "square", "tp", "Γ-X-M-Γ"),
"ORC": ("RECT", "rectangular", "op", "Γ-X-S-Y-Γ"),
"ORCC": ("CRECT", "centred rectangular", "oc", "Γ-X-S-X1-Y-Γ"),
"HEX": ("HEX2D", "hexagonal", "hp", "Γ-M-K-Γ"),
"MCL": ("OBL", "oblique", "mp", "Γ-Y-H-C-H1-X-H2-Y1-Γ"),
}
#: Space group of a single lattice point (the holohedry) -> Pearson lattice symbol.
_HOLOHEDRY = {
2: "aP", 10: "mP", 12: "mS", 47: "oP", 65: "oS", 69: "oF", 71: "oI",
123: "tP", 139: "tI", 166: "hR", 191: "hP", 221: "cP", 225: "cF", 229: "cI",
} # fmt: skip
#: Relative tolerance for the paper's equalities (ORCF3, MCLC2, MCLC4, TRI2).
_EQUAL = 1e-6
_H = 0.5
[docs]
class KPathRefused(ValueError):
"""This structure has no Setyawan-Curtarolo path, or it does not fit the cell."""
@dataclass(frozen=True)
class _Zone:
"""A lattice's convention: names, table values, Cartesian points (1/A) and path."""
name: str
variant: str
pearson: str
values: dict[str, float]
points: dict[str, np.ndarray]
boundary: dict[str, bool]
path: str
order: int
Points = dict[str, tuple[float, float, float]]
def _cubic(variant: str, **_: float) -> tuple[dict[str, float], Points, str]:
if variant == "CUB":
return (
{},
{"Γ": (0, 0, 0), "M": (_H, _H, 0), "R": (_H, _H, _H), "X": (0, _H, 0)},
"Γ-X-M-Γ-R-X|M-R",
)
if variant == "FCC":
points: Points = {
"Γ": (0, 0, 0), "K": (3 / 8, 3 / 8, 3 / 4), "L": (_H, _H, _H),
"U": (5 / 8, 1 / 4, 5 / 8), "W": (_H, 1 / 4, 3 / 4), "X": (_H, 0, _H),
} # fmt: skip
return {}, points, "Γ-X-W-K-Γ-L-U-W-L-K|U-X"
points = {"Γ": (0, 0, 0), "H": (_H, -_H, _H), "P": (1 / 4, 1 / 4, 1 / 4), "N": (0, 0, _H)}
return {}, points, "Γ-H-N-Γ-P-H|P-N"
def _tetragonal(
variant: str, a: float, c: float, **_: float
) -> tuple[dict[str, float], Points, str]:
if variant == "TET":
points: Points = {
"Γ": (0, 0, 0), "A": (_H, _H, _H), "M": (_H, _H, 0), "R": (0, _H, _H),
"X": (0, _H, 0), "Z": (0, 0, _H),
} # fmt: skip
return {}, points, "Γ-X-M-Γ-Z-R-A-Z|X-R|M-A"
if variant == "BCT1":
eta = (1 + c**2 / a**2) / 4
points = {
"Γ": (0, 0, 0), "M": (-_H, _H, _H), "N": (0, _H, 0), "P": (1 / 4, 1 / 4, 1 / 4),
"X": (0, 0, _H), "Z": (eta, eta, -eta), "Z1": (-eta, 1 - eta, eta),
} # fmt: skip
return {"eta": eta}, points, "Γ-X-M-Γ-Z-P-N-Z1-M|X-P"
eta = (1 + a**2 / c**2) / 4
zeta = a**2 / (2 * c**2)
points = {
"Γ": (0, 0, 0), "N": (0, _H, 0), "P": (1 / 4, 1 / 4, 1 / 4), "Σ": (-eta, eta, eta),
"Σ1": (eta, 1 - eta, -eta), "X": (0, 0, _H), "Y": (-zeta, zeta, _H),
"Y1": (_H, _H, -zeta), "Z": (_H, _H, -_H),
} # fmt: skip
return {"eta": eta, "zeta": zeta}, points, "Γ-X-Y-Σ-Γ-Z-Σ1-N-P-Y1-Z|X-P"
def _orthorhombic(
variant: str, a: float, b: float, c: float, **_: float
) -> tuple[dict[str, float], Points, str]:
if variant == "ORC":
points: Points = {
"Γ": (0, 0, 0), "R": (_H, _H, _H), "S": (_H, _H, 0), "T": (0, _H, _H),
"U": (_H, 0, _H), "X": (_H, 0, 0), "Y": (0, _H, 0), "Z": (0, 0, _H),
} # fmt: skip
return {}, points, "Γ-X-S-Y-Γ-Z-U-R-T-Z|Y-T|U-X|S-R"
if variant in ("ORCF1", "ORCF3"):
zeta = (1 + a**2 / b**2 - a**2 / c**2) / 4
eta = (1 + a**2 / b**2 + a**2 / c**2) / 4
points = {
"Γ": (0, 0, 0), "A": (_H, _H + zeta, zeta), "A1": (_H, _H - zeta, 1 - zeta),
"L": (_H, _H, _H), "T": (1, _H, _H), "X": (0, eta, eta),
"X1": (1, 1 - eta, 1 - eta), "Y": (_H, 0, _H), "Z": (_H, _H, 0),
} # fmt: skip
path = (
"Γ-Y-T-Z-Γ-X-A1-Y|T-X1|X-A-Z|L-Γ"
if variant == "ORCF1"
else "Γ-Y-T-Z-Γ-X-A1-Y|X-A-Z|L-Γ"
)
return {"zeta": zeta, "eta": eta}, points, path
if variant == "ORCF2":
eta = (1 + a**2 / b**2 - a**2 / c**2) / 4
phi = (1 + c**2 / b**2 - c**2 / a**2) / 4
delta = (1 + b**2 / a**2 - b**2 / c**2) / 4
points = {
"Γ": (0, 0, 0), "C": (_H, _H - eta, 1 - eta), "C1": (_H, _H + eta, eta),
"D": (_H - delta, _H, 1 - delta), "D1": (_H + delta, _H, delta), "L": (_H, _H, _H),
"H": (1 - phi, _H - phi, _H), "H1": (phi, _H + phi, _H), "X": (0, _H, _H),
"Y": (_H, 0, _H), "Z": (_H, _H, 0),
} # fmt: skip
return (
{"eta": eta, "phi": phi, "delta": delta},
points,
"Γ-Y-C-D-X-Γ-Z-D1-H-C|C1-Z|X-H1|H-Y|L-Γ",
)
if variant == "ORCI":
zeta = (1 + a**2 / c**2) / 4
eta = (1 + b**2 / c**2) / 4
delta = (b**2 - a**2) / (4 * c**2)
mu = (a**2 + b**2) / (4 * c**2)
points = {
"Γ": (0, 0, 0), "L": (-mu, mu, _H - delta), "L1": (mu, -mu, _H + delta),
"L2": (_H - delta, _H + delta, -mu), "R": (0, _H, 0), "S": (_H, 0, 0),
"T": (0, 0, _H), "W": (1 / 4, 1 / 4, 1 / 4), "X": (-zeta, zeta, zeta),
"X1": (zeta, 1 - zeta, -zeta), "Y": (eta, -eta, eta), "Y1": (1 - eta, eta, -eta),
"Z": (_H, _H, -_H),
} # fmt: skip
return (
{"zeta": zeta, "eta": eta, "delta": delta, "mu": mu},
points,
"Γ-X-L-T-W-R-X1-Z-Γ-Y-S-W|L1-Y|Y1-Z",
)
zeta = (1 + a**2 / b**2) / 4
points = {
"Γ": (0, 0, 0), "A": (zeta, zeta, _H), "A1": (-zeta, 1 - zeta, _H), "R": (0, _H, _H),
"S": (0, _H, 0), "T": (-_H, _H, _H), "X": (zeta, zeta, 0), "X1": (-zeta, 1 - zeta, 0),
"Y": (-_H, _H, 0), "Z": (0, 0, _H),
} # fmt: skip
return {"zeta": zeta}, points, "Γ-X-S-R-A-Z-Γ-Y-X1-A1-T-Y|Z-T"
def _hexagonal(variant: str, alpha: float, **_: float) -> tuple[dict[str, float], Points, str]:
if variant == "HEX":
points: Points = {
"Γ": (0, 0, 0), "A": (0, 0, _H), "H": (1 / 3, 1 / 3, _H), "K": (1 / 3, 1 / 3, 0),
"L": (_H, 0, _H), "M": (_H, 0, 0),
} # fmt: skip
return {}, points, "Γ-M-K-Γ-A-L-H-A|L-M|K-H"
if variant == "RHL1":
eta = (1 + 4 * math.cos(alpha)) / (2 + 4 * math.cos(alpha))
nu = 3 / 4 - eta / 2
points = {
"Γ": (0, 0, 0), "B": (eta, _H, 1 - eta), "B1": (_H, 1 - eta, eta - 1),
"F": (_H, _H, 0), "L": (_H, 0, 0), "L1": (0, 0, -_H), "P": (eta, nu, nu),
"P1": (1 - nu, 1 - nu, 1 - eta), "P2": (nu, nu, eta - 1), "Q": (1 - nu, nu, 0),
"X": (nu, 0, -nu), "Z": (_H, _H, _H),
} # fmt: skip
return {"eta": eta, "nu": nu}, points, "Γ-L-B1|B-Z-Γ-X|Q-F-P1-Z|L-P"
eta = 1 / (2 * math.tan(alpha / 2) ** 2)
nu = 3 / 4 - eta / 2
points = {
"Γ": (0, 0, 0), "F": (_H, -_H, 0), "L": (_H, 0, 0), "P": (1 - nu, -nu, 1 - nu),
"P1": (nu, nu - 1, nu - 1), "Q": (eta, eta, eta), "Q1": (1 - eta, -eta, -eta),
"Z": (_H, -_H, _H),
} # fmt: skip
return {"eta": eta, "nu": nu}, points, "Γ-P-Z-Q-Γ-F-P1-Q1-L-Z"
def _monoclinic(
variant: str, a: float, b: float, c: float, alpha: float, **_: float
) -> tuple[dict[str, float], Points, str]:
cos, sin2 = math.cos(alpha), math.sin(alpha) ** 2
if variant == "MCL":
eta = (1 - b * cos / c) / (2 * sin2)
nu = _H - eta * c * cos / b
points: Points = {
"Γ": (0, 0, 0), "A": (_H, _H, 0), "C": (0, _H, _H), "D": (_H, 0, _H),
"D1": (_H, 0, -_H), "E": (_H, _H, _H), "H": (0, eta, 1 - nu), "H1": (0, 1 - eta, nu),
"H2": (0, eta, -nu), "M": (_H, eta, 1 - nu), "M1": (_H, 1 - eta, nu),
"M2": (_H, eta, -nu), "X": (0, _H, 0), "Y": (0, 0, _H), "Y1": (0, 0, -_H),
"Z": (_H, 0, 0),
} # fmt: skip
return {"eta": eta, "nu": nu}, points, "Γ-Y-H-C-E-M1-A-X-H1|M-D-Z|Y-D"
if variant in ("MCLC1", "MCLC2"):
zeta = (2 - b * cos / c) / (4 * sin2)
eta = _H + 2 * zeta * c * cos / b
psi = 3 / 4 - a**2 / (4 * b**2 * sin2)
phi = psi + (3 / 4 - psi) * b * cos / c
points = {
"Γ": (0, 0, 0), "N": (_H, 0, 0), "N1": (0, -_H, 0),
"F": (1 - zeta, 1 - zeta, 1 - eta), "F1": (zeta, zeta, eta),
"F2": (-zeta, -zeta, 1 - eta), "F3": (1 - zeta, -zeta, 1 - eta),
"I": (phi, 1 - phi, _H), "I1": (1 - phi, phi - 1, _H), "L": (_H, _H, _H),
"M": (_H, 0, _H), "X": (1 - psi, psi - 1, 0), "X1": (psi, 1 - psi, 0),
"X2": (psi - 1, -psi, 0), "Y": (_H, _H, 0), "Y1": (-_H, -_H, 0), "Z": (0, 0, _H),
} # fmt: skip
path = (
"Γ-Y-F-L-I|I1-Z-F1|Y-X1|X-Γ-N|M-Γ" if variant == "MCLC1" else "Γ-Y-F-L-I|I1-Z-F1|N-Γ-M"
)
if variant == "MCLC1":
# The paper's table lists F3 for MCLC1 and MCLC2 together, but with
# k_gamma > 90 degrees F3 lies outside the first zone (the zone check
# refuses it); it is off the path, and kept for MCLC2 only, as pymatgen does.
del points["F3"]
return {"zeta": zeta, "eta": eta, "psi": psi, "phi": phi}, points, path
if variant in ("MCLC3", "MCLC4"):
mu = (1 + b**2 / a**2) / 4
delta = b * c * cos / (2 * a**2)
zeta = mu - 1 / 4 + (1 - b * cos / c) / (4 * sin2)
eta = _H + 2 * zeta * c * cos / b
phi = 1 + zeta - 2 * mu
psi = eta - 2 * delta
points = {
"Γ": (0, 0, 0), "F": (1 - phi, 1 - phi, 1 - psi), "F1": (phi, phi - 1, psi),
"F2": (1 - phi, -phi, 1 - psi), "H": (zeta, zeta, eta),
"H1": (1 - zeta, -zeta, 1 - eta),
"H2": (-zeta, -zeta, 1 - eta), "I": (_H, -_H, _H), "M": (_H, 0, _H), "N": (_H, 0, 0),
"N1": (0, -_H, 0), "X": (_H, -_H, 0), "Y": (mu, mu, delta), "Y1": (1 - mu, -mu, -delta),
"Y2": (-mu, -mu, -delta), "Y3": (mu, mu - 1, delta), "Z": (0, 0, _H),
} # fmt: skip
path = (
"Γ-Y-F-H-Z-I-F1|H1-Y1-X-Γ-N|M-Γ"
if variant == "MCLC3"
else "Γ-Y-F-H-Z-I|H1-Y1-X-Γ-N|M-Γ"
)
params = {"mu": mu, "delta": delta, "zeta": zeta, "eta": eta, "phi": phi, "psi": psi}
return params, points, path
zeta = (b**2 / a**2 + (1 - b * cos / c) / sin2) / 4
eta = _H + 2 * zeta * c * cos / b
mu = eta / 2 + b**2 / (4 * a**2) - b * c * cos / (2 * a**2)
nu = 2 * mu - zeta
omega = (4 * nu - 1 - b**2 * sin2 / a**2) * c / (2 * b * cos)
delta = zeta * c * cos / b + omega / 2 - 1 / 4
rho = 1 - zeta * a**2 / b**2
points = {
"Γ": (0, 0, 0), "F": (nu, nu, omega), "F1": (1 - nu, 1 - nu, 1 - omega),
"F2": (nu, nu - 1, omega), "H": (zeta, zeta, eta), "H1": (1 - zeta, -zeta, 1 - eta),
"H2": (-zeta, -zeta, 1 - eta), "I": (rho, 1 - rho, _H), "I1": (1 - rho, rho - 1, _H),
"L": (_H, _H, _H), "M": (_H, 0, _H), "N": (_H, 0, 0), "N1": (0, -_H, 0),
"X": (_H, -_H, 0), "Y": (mu, mu, delta), "Y1": (1 - mu, -mu, -delta),
"Y2": (-mu, -mu, -delta), "Y3": (mu, mu - 1, delta), "Z": (0, 0, _H),
} # fmt: skip
params = {"zeta": zeta, "eta": eta, "mu": mu, "nu": nu, "omega": omega, "delta": delta,
"rho": rho} # fmt: skip
return params, points, "Γ-Y-F-L-I|I1-Z-H-F1|H1-Y1-X-Γ-N|M-Γ"
def _triclinic(variant: str, **_: float) -> tuple[dict[str, float], Points, str]:
if variant in ("TRI1a", "TRI2a"):
points: Points = {
"Γ": (0, 0, 0), "L": (_H, _H, 0), "M": (0, _H, _H), "N": (_H, 0, _H),
"R": (_H, _H, _H), "X": (_H, 0, 0), "Y": (0, _H, 0), "Z": (0, 0, _H),
} # fmt: skip
else:
points = {
"Γ": (0, 0, 0), "L": (_H, -_H, 0), "M": (0, 0, _H), "N": (-_H, -_H, _H),
"R": (0, -_H, _H), "X": (0, -_H, 0), "Y": (_H, 0, 0), "Z": (-_H, 0, _H),
} # fmt: skip
return {}, points, "X-Γ-Y|L-Γ-Z|N-Γ-M|R-Γ"
_TABLES: dict[str, Callable[..., tuple[dict[str, float], Points, str]]] = {
"c": _cubic, "t": _tetragonal, "o": _orthorhombic, "h": _hexagonal, "m": _monoclinic,
"a": _triclinic,
} # fmt: skip
_NAMES = {
"CUB": "simple cubic", "FCC": "face-centred cubic", "BCC": "body-centred cubic",
"TET": "simple tetragonal", "BCT": "body-centred tetragonal",
"ORC": "simple orthorhombic", "ORCF": "face-centred orthorhombic",
"ORCI": "body-centred orthorhombic", "ORCC": "C-centred orthorhombic",
"HEX": "hexagonal", "RHL": "rhombohedral", "MCL": "simple monoclinic",
"MCLC": "C-centred monoclinic", "TRI": "triclinic",
} # fmt: skip
def _angle(u: np.ndarray, v: np.ndarray) -> float:
cosine = float(u @ v) / float(np.linalg.norm(u) * np.linalg.norm(v))
return math.acos(max(-1.0, min(1.0, cosine)))
def _close(x: float, y: float) -> bool:
return abs(x - y) <= _EQUAL * max(1.0, abs(x), abs(y))
def _gauss_reduce(u: np.ndarray, v: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""A reduced basis of the plane lattice spanned by u and v (Lagrange-Gauss)."""
if u @ u > v @ v:
u, v = v, u
for _ in range(100):
m = round(float(u @ v) / float(u @ u))
if m == 0:
break
v = v - m * u
if v @ v < u @ u:
u, v = v, u
return u, v
def _standard(pearson: str, conventional: np.ndarray) -> tuple[str, np.ndarray, dict[str, float]]:
"""The Setyawan-Curtarolo lattice name, primitive rows and conventional parameters."""
A, B, C = conventional
if pearson in ("oP", "oF", "oI"):
A, B, C = sorted(conventional, key=lambda r: float(r @ r))
elif pearson == "oS":
A, B = sorted((A, B), key=lambda r: float(r @ r))
elif pearson in ("mP", "mS"):
# spglib's standard settings are b-unique; the paper puts the unique axis first.
unique, u, v = B, A, C
if pearson == "mP":
u, v = _gauss_reduce(u, v)
if u @ v < 0:
v = -v
A, B, C = unique, u, v
lengths = {"a": float(np.linalg.norm(A)), "b": float(np.linalg.norm(B)),
"c": float(np.linalg.norm(C))} # fmt: skip
half = 0.5
if pearson in ("cF", "oF"):
primitive = np.asarray([(B + C) * half, (A + C) * half, (A + B) * half])
elif pearson in ("cI", "tI", "oI"):
primitive = np.asarray([(-A + B + C) * half, (A - B + C) * half, (A + B - C) * half])
elif pearson == "oS":
primitive = np.asarray([(A - B) * half, (A + B) * half, C])
elif pearson == "mS":
primitive = np.asarray([(A + B) * half, (-A + B) * half, C])
elif pearson == "hR":
primitive = np.asarray([(2 * A + B + C) / 3, (-A + B + C) / 3, (-A - 2 * B + C) / 3])
lengths = {"a": float(np.linalg.norm(primitive[0]))}
else:
primitive = np.asarray([A, B, C])
alpha = _angle(primitive[1], primitive[2]) if pearson == "hR" else _angle(B, C)
params = {**lengths, "alpha": alpha}
name = {"cP": "CUB", "cF": "FCC", "cI": "BCC", "tP": "TET", "tI": "BCT", "oP": "ORC",
"oF": "ORCF", "oI": "ORCI", "oS": "ORCC", "hP": "HEX", "hR": "RHL", "mP": "MCL",
"mS": "MCLC", "aP": "TRI"}[pearson] # fmt: skip
return name, primitive, params
def _variant(name: str, primitive: np.ndarray, params: dict[str, float]) -> str:
a, b, c, alpha = params["a"], params.get("b", 0.0), params.get("c", 0.0), params["alpha"]
if name == "BCT":
if _close(a, c):
raise KPathRefused("a body-centred tetragonal cell with c = a is cubic")
return "BCT1" if c < a else "BCT2"
if name == "ORCF":
lhs, rhs = 1 / a**2, 1 / b**2 + 1 / c**2
return "ORCF3" if _close(lhs, rhs) else ("ORCF1" if lhs > rhs else "ORCF2")
if name == "RHL":
if _close(alpha, math.pi / 2):
raise KPathRefused("a rhombohedral cell with alpha = 90 degrees is cubic")
return "RHL1" if alpha < math.pi / 2 else "RHL2"
if name == "MCLC":
k = 2 * math.pi * np.linalg.inv(primitive).T
k_gamma = _angle(k[0], k[1])
if _close(k_gamma, math.pi / 2):
return "MCLC2"
if k_gamma > math.pi / 2:
return "MCLC1"
value = b * math.cos(alpha) / c + b**2 * math.sin(alpha) ** 2 / a**2
return "MCLC4" if _close(value, 1.0) else ("MCLC3" if value < 1 else "MCLC5")
return name
def _triclinic_basis(lattice: np.ndarray, spglib: Any) -> tuple[str, np.ndarray]:
"""Variant and primitive rows from the Niggli-reduced reciprocal basis."""
reduced = spglib.niggli_reduce(2 * math.pi * np.linalg.inv(lattice).T)
if reduced is None: # pragma: no cover - spglib reduces every nonsingular basis
raise KPathRefused("spglib could not reduce the reciprocal lattice")
k = np.asarray(reduced, dtype=float)
right = math.pi / 2
def angles(rows: np.ndarray) -> tuple[float, float, float]:
return _angle(rows[1], rows[2]), _angle(rows[0], rows[2]), _angle(rows[0], rows[1])
k_alpha, k_beta, _k_gamma = angles(k)
if _close(k_alpha, right):
k = k[[1, 2, 0]]
elif _close(k_beta, right):
k = k[[2, 0, 1]]
k_alpha, k_beta, k_gamma = angles(k)
if _close(k_gamma, right):
variant = (
"TRI2a"
if k_alpha > right and k_beta > right
else ("TRI2b" if k_alpha < right and k_beta < right else "")
)
elif all(x > right for x in (k_alpha, k_beta, k_gamma)):
variant = "TRI1a"
elif all(x < right for x in (k_alpha, k_beta, k_gamma)):
# The TRI1b points use b1, b2, b3, b1 - b2, b3 - b1, b3 - b2 and b3 - b1 - b2: the
# Voronoi-relevant vectors of the superbase {b1, -b2, b3 - b1, b2 - b3}, which is
# obtuse (Conway and Sloane, ch. 21) when b1 . b2 is the smallest of the three
# products of a Niggli-reduced acute basis. Order the basis that way.
dots = [float(k[1] @ k[2]), float(k[0] @ k[2]), float(k[0] @ k[1])]
last = int(np.argmin(dots)) # the vector outside the least-overlapping pair
k = k[[i for i in range(3) if i != last] + [last]]
variant = "TRI1b"
else:
variant = ""
if not variant: # pragma: no cover - a Niggli-reduced basis is all-acute or all-obtuse
raise KPathRefused("the reduced reciprocal basis is neither all-acute nor all-obtuse")
return variant, 2 * math.pi * np.linalg.inv(k).T
def _rotations(dataset: Any) -> int:
return len({tuple(np.asarray(r, dtype=int).ravel()) for r in dataset.rotations})
def _notes(
structure: PeriodicStructure, lattice_order: int, spglib: Any, symprec: float
) -> tuple[list[str], int | None]:
"""Caveats from the crystal (atoms included), and its primitive cells in the stored cell."""
try:
cell = symmetry._cell(structure)
except ValueError as error:
return [f"crystal symmetry not compared: {error}"], None
notes = []
dataset = spglib.get_symmetry_dataset(cell, symprec=symprec)
if dataset is not None and _rotations(dataset) < lattice_order:
notes.append(
f"the crystal's point group {str(dataset.pointgroup).strip()} (order "
f"{_rotations(dataset)}) is lower than the lattice's (order {lattice_order}): points "
"the lattice makes equivalent can differ in this crystal, and its band path may need "
"segments the lattice path omits"
)
primitive = spglib.find_primitive(cell, symprec=symprec)
count = 1 if primitive is None else max(1, len(structure.sites) // len(primitive[2]))
if count > 1:
notes.append(
f"the stored cell holds {count} primitive cells of the crystal: this is the zone of "
"the stored cell, so bands drawn on it are folded; reduce the cell to its primitive "
"first for the crystal's own zone"
)
return notes, count
[docs]
def high_symmetry_path(structure: PeriodicStructure, *, symprec: float = 1e-3) -> dict[str, Any]:
"""The lattice type, special points and band path of the stored cell's first zone.
A crystal gets one of the paper's 25 variants; a slab gets one of the five
plane lattices (see the module docstring). ``symprec`` is the length
tolerance (angstrom) for classifying the lattice. Read-only; needs the
symmetry extra.
"""
if not 0 < symprec <= 1:
raise ValueError("symprec is a length tolerance between 0 and 1 angstrom")
periodic = [i for i in range(3) if structure.pbc[i]]
if len(periodic) == 1:
raise KPathRefused(
"k-paths cover the 14 space lattices and the 5 plane lattices of slabs; this "
"structure is periodic in one direction only"
)
spglib = symmetry._spglib()
if len(periodic) == 2:
return _plane_path(structure, periodic, symprec, spglib)
lattice = crystal.lattice_rows(structure)
zone = _lattice_zone(lattice, symprec, spglib)
notes, primitive_cells = _notes(structure, zone.order, spglib, symprec)
return {
"dimension": 3,
"lattice": zone.name,
"variant": zone.variant,
"name": _NAMES[zone.name],
"pearson": zone.pearson,
**_points(zone, zone.points, zone.path, lattice),
"lattice_point_group_order": zone.order,
"primitive_cells": primitive_cells,
"symprec_angstrom": symprec,
"convention": CONVENTION,
"notes": notes,
"reference": REFERENCE,
}
[docs]
def reciprocal_rows(structure: PeriodicStructure) -> np.ndarray:
"""Rows b_i (1/A) with b_i . a_j = 2 pi delta_ij; periodic b_i lie in the periodic span.
A non-periodic cell vector is first replaced by its component normal to the
periodic vectors (the determinant is unchanged), so a vacuum vector that is
tilted does not tilt a slab's zone out of its plane.
"""
return np.asarray(2 * math.pi * np.linalg.inv(_upright(structure)).T)
def _upright(structure: PeriodicStructure) -> np.ndarray:
lattice = np.array(crystal.lattice_rows(structure), dtype=float)
periodic = [i for i in range(3) if structure.pbc[i]]
if len(periodic) < 3:
span, _ = np.linalg.qr(lattice[periodic].T) # orthonormal columns
for i in range(3):
if not structure.pbc[i]:
lattice[i] = lattice[i] - span @ (span.T @ lattice[i])
return lattice
def _lattice_zone(lattice: np.ndarray, symprec: float, spglib: Any) -> _Zone:
"""Classify a 3-D lattice and place the paper's points in Cartesian 1/A."""
dataset = spglib.get_symmetry_dataset((lattice, [[0.0, 0.0, 0.0]], [1]), symprec=symprec)
if dataset is None or int(dataset.number) not in _HOLOHEDRY:
raise KPathRefused(f"spglib could not classify the lattice at symprec {symprec} A")
pearson = _HOLOHEDRY[int(dataset.number)]
params: dict[str, float] = {}
if pearson == "aP":
variant, primitive = _triclinic_basis(lattice, spglib)
name = "TRI"
else:
# spglib: (a_s b_s c_s) = (a b c) P^-1, so the conventional rows are P^-T rows.
p_matrix = np.asarray(dataset.transformation_matrix, dtype=float)
conventional = np.linalg.inv(p_matrix).T @ lattice
name, primitive, params = _standard(pearson, conventional)
variant = _variant(name, primitive, params)
table = _TABLES[pearson[0]]
values, points, path = table(variant, **params)
transform = primitive @ np.linalg.inv(lattice)
if not np.allclose(transform, np.round(transform), atol=1e-6) or not _close(
abs(float(np.linalg.det(transform))), 1.0
): # pragma: no cover - a primitive cell of the lattice always is
raise KPathRefused("the standard primitive cell is not a basis of this lattice")
reciprocal = 2 * math.pi * np.linalg.inv(primitive).T
cartesian = {label: np.asarray(f, dtype=float) @ reciprocal for label, f in points.items()}
# Strain a lattice accepted at symprec can carry, relative to its shortest vector.
shortest = float(np.linalg.norm(spglib.niggli_reduce(lattice), axis=1).min())
boundary = _zone_check(lattice, cartesian, variant, min(1e-2, 4 * symprec / shortest))
return _Zone(name, variant, pearson, values, cartesian, boundary, path, _rotations(dataset))
def _points(
zone: _Zone, points: dict[str, np.ndarray], path: str, frame: np.ndarray
) -> dict[str, Any]:
"""The report's parameters, points and path; fractions refer to the rows of ``frame``."""
to_stored = frame.T / (2 * math.pi)
segments = [segment.split("-") for segment in path.split("|")]
on_path = {label for segment in segments for label in segment}
return {
"parameters": {key: round(float(v), 12) for key, v in zone.values.items()},
"points": [
{
"label": label,
"fractional": [round(float(x), 12) + 0.0 for x in k @ to_stored],
"cartesian_inverse_angstrom": [round(float(x), 12) + 0.0 for x in k],
"on_path": label in on_path,
"on_zone_boundary": zone.boundary[label],
}
for label, k in points.items()
],
"path": segments,
"path_text": path,
}
def _plane_path(
structure: PeriodicStructure, periodic: list[int], symprec: float, spglib: Any
) -> dict[str, Any]:
"""A slab's plane lattice, labelled on the in-plane section of its prism lattice's zone."""
frame = _upright(structure)
rows = frame[periodic]
normal = np.cross(rows[0], rows[1])
normal /= np.linalg.norm(normal)
# Lattice vectors off the plane are at least the stacking long; with every reduced
# in-plane vector shorter, a lattice symmetry keeps the plane, and the prism's
# holohedry is the plane's times the mirror in the plane.
longest = float(max(np.linalg.norm(v) for v in _gauss_reduce(rows[0], rows[1])))
prism = np.vstack([rows, (2 * longest + 1.0) * normal])
zone = _lattice_zone(prism, symprec, spglib)
if zone.variant not in _PLANE: # pragma: no cover - a stacked plane lattice is one of five
raise KPathRefused(f"the prism lattice of this slab classified as {zone.variant}")
plane, name, symbol, path = _PLANE[zone.variant]
scale = max(float(np.linalg.norm(k)) for k in zone.points.values())
section = {
label: k for label, k in zone.points.items() if abs(float(k @ normal)) <= 1e-9 * scale
}
order = zone.order // 2
notes, primitive_cells = _plane_notes(structure, rows, normal, order, spglib, symprec)
return {
"dimension": 2,
"lattice": plane,
"variant": plane,
"name": name,
"pearson": symbol,
"section_of": zone.variant,
**_points(zone, section, path, frame),
"lattice_point_group_order": order,
"primitive_cells": primitive_cells,
"symprec_angstrom": symprec,
"convention": PLANE_CONVENTION,
"notes": notes,
"reference": PLANE_REFERENCE,
}
def _plane_notes(
structure: PeriodicStructure,
rows: np.ndarray,
normal: np.ndarray,
plane_order: int,
spglib: Any,
symprec: float,
) -> tuple[list[str], int | None]:
"""The slab's in-plane point group and its primitive cells in the stored cell.
The slab is stacked along its normal with a vacuum gap longer than every
reduced in-plane vector. Each period then holds one slab, so an operation
of the stack maps the slab onto itself up to a lattice translation: the
stack's rotations restricted to the plane, and its translations, are the
slab's. (Its full layer group is not reported.)
"""
if any(site.occupancy != 1 for site in structure.sites):
return [
"slab symmetry not compared: partially occupied sites have no single layer group; "
"resolve disorder"
], None
cartesian = np.asarray([s.fractional for s in structure.sites], dtype=float) @ (
crystal.lattice_rows(structure)
)
longest = float(max(np.linalg.norm(v) for v in _gauss_reduce(rows[0], rows[1])))
heights = cartesian @ normal
stacking = float(heights.max() - heights.min()) + 2 * longest + 10.0
padded = np.vstack([rows, stacking * normal])
cell = (
padded,
cartesian @ np.linalg.inv(padded),
[ATOMIC_NUMBER[s.symbol] for s in structure.sites],
)
notes = []
dataset = spglib.get_symmetry_dataset(cell, symprec=symprec)
if dataset is None:
notes.append("slab symmetry not compared: spglib found none at this tolerance")
else:
plane, _ = np.linalg.qr(rows.T) # orthonormal in-plane columns
to_cartesian, to_fractional = padded.T, np.linalg.inv(padded.T)
actions = {
tuple(
(np.round(plane.T @ to_cartesian @ np.asarray(r, float) @ to_fractional @ plane, 6)
+ 0.0).ravel()
)
for r in dataset.rotations
} # fmt: skip
if len(actions) < plane_order:
notes.append(
f"the slab's in-plane point group (order {len(actions)}) is lower than the plane "
f"lattice's (order {plane_order}): points the lattice makes equivalent can differ "
"in this slab, and its band path may need segments the lattice path omits"
)
primitive = spglib.find_primitive(cell, symprec=symprec)
count = 1 if primitive is None else max(1, len(structure.sites) // len(primitive[2]))
if count > 1:
notes.append(
f"the stored cell holds {count} primitive cells of the slab: this is the zone of the "
"stored surface cell, so bands drawn on it are folded; use the primitive surface "
"cell for the slab's own zone"
)
return notes, count
def _zone_check(
lattice: np.ndarray, points: dict[str, np.ndarray], variant: str, strain: float = 0.0
) -> dict[str, bool]:
"""Refuse points outside the first zone; say which lie on its boundary.
``strain`` widens both tests for lattices that are ideal only within a
tolerance; points of a mismatched convention miss by far more (several
per cent of the zone).
"""
reciprocal = 2 * math.pi * np.linalg.inv(lattice).T
reduced = np.asarray(symmetry._spglib().niggli_reduce(reciprocal), dtype=float)
shells = (
np.asarray([n for n in itertools.product(range(-2, 3), repeat=3) if any(n)], dtype=float)
@ reduced
)
scale = float(np.linalg.norm(reduced, axis=1).max()) ** 2
slack = max(1e-7, strain) * scale
out = {}
for label, k in points.items():
# |k - G|^2 - |k|^2 >= 0 for every G inside or on the zone; 0 on a Bragg plane.
margins = np.einsum("ij,ij->i", shells, shells) - 2 * shells @ k
if float(margins.min()) < -slack:
raise KPathRefused(
f"{variant} point {label} lies outside the first Brillouin zone of this cell; "
"the lattice does not fit the Setyawan-Curtarolo convention at this tolerance"
)
out[label] = label != "Γ" and float(margins.min()) <= slack
return out