Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .claude/skills/verify-pyprocar/features/fermi3d.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Build isosurfaces of E(k)=E_F on a full k-mesh inside the Brillouin zone. They c

- Plain surface with the BZ: `FermiPlotter.plot(fs, show_brillouin_zone=True)`. It returns a dict of meshes keyed by `(band, spin)`.
- Scalar coloring: compute the scalar first with `fs.get_property("projected_sum", atoms=, orbitals=, spins=)`, then pass `scalars_data="projected_sum"`, or pass a `Property`.
- Vector arrows (spin texture): `vectors_data=...`. Use the `non-colinear` fixture. Not driven.
- Vector arrows (spin texture): `vectors_data=...`. Use the `non-colinear` fixture. `vectors_data="fermi_velocity"` was driven on `van-alphen` (#286): the longest arrow is 0.1 times the zone's largest extent, 0.0509 of 0.5086 1/A. The arrow actors are named `vectors_<band>_<spin>`.
- Band selection: `fs.select_bands([(band, spin), ...])` returns a new surface with only those sheets. On `fermi3d/non-spin-polarized` at E_F = 5.3017, `select_bands([(17, 0)])` keeps the 270 points of band 17, and its V d `projected_sum` spans about 0.794 to 0.803. `select_bands([])` gives an empty surface whose projections have shape `(0, n_bands, n_spins)`.
- Box and plane widgets: `FermiHandler.plot_fermi_cross_section_box_widget(mode=..., show=False, off_screen=True)`, or `FermiPlotter.add_box_slicer(fs, show_cross_section_area=True)`. The cross-section text is the `area_text` actor; read it with `p.actors["area_text"].GetText(2)`. `save_2d=` writes a screenshot of the 3D view (the handler then renders off screen and does not show), and `save_2d_slice=` writes the cross section as a matplotlib plot through `FermiPlotter.save_slice_2d`.
- Isovalue GIF: `add_isovalue_gif(e_surfaces, save_gif, ...)`. Not driven.
Expand Down Expand Up @@ -39,5 +39,6 @@ The proven end state (SrVO3, non-spin-polarized, d6d4aaa7):
## Gotchas

- `FermiHandler` re-parses from `dirname` on every `plot_fermi_surface` call, so the calc dir must still exist at plot time.
- Since #286 the drawn zone (`BrillouinZone`, `BrillouinZone2D`) and the cross-section zone come from the Delaunay-reduced basis. A sheared reciprocal basis of the same lattice, such as b2' = b2 + 3 b1, gives the zone of volume |det B|, and `BrillouinZone.points` holds only the zone's vertices. Its cross-section orbits grow up to 16 cells of the given basis, so an orbit near that limit on a heavily sheared basis can come back as an open curve where the reduced basis closes it, as on dev (#302). They also differ from the reduced cell's by the marching-cubes mesh of the sheared grid, which on a coarse DFT grid can be large (Au with b2 + 3 b1 gave 0.41 against 0.55) and adds orbits below 1e-3. The drawn Fermi surface on a sheared basis is still incomplete: `ebs.pad` adds `padding` grid points in fractional coordinates, which do not cover the zone, so pieces are missing or `from_ebs` raises `Surface is empty after clipping`.
- Offscreen VTK works here, but it prints a `vtkEGLRenderWindow ... OpenGL 3.2` WARN line. Ignore it. Check the screenshot is not blank: about 1 distinct color means blank.
- `FermiPlotter` subclasses `pv.Plotter`, so pass `off_screen=True` to it. `PYVISTA_OFF_SCREEN=true` is set by the harness as a backstop.
79 changes: 45 additions & 34 deletions pyprocar/core/brillouin_zone.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,54 @@
import itertools
import logging
import warnings

import numpy as np
import pyvista as pv
import spglib
from scipy.spatial import Voronoi

logger = logging.getLogger(__name__)

_FACE_CANDIDATES = np.array([s for s in itertools.product(range(-2, 3), repeat=3) if any(s)])
_NEIGHBOURS = np.array(list(itertools.product(range(-1, 2), repeat=3)))
_ORIGIN = len(_NEIGHBOURS) // 2


def zone_face_steps(reciprocal_lattice: np.ndarray) -> np.ndarray:
"""Integer coefficients, in the rows of ``reciprocal_lattice``, of the lattice vectors
whose bisector planes bound the first Brillouin zone.

The candidates are the 5^3 block of the Delaunay-reduced basis, whatever basis is given.
The face vectors are the 7 pairs of an obtuse superbase and the reduced basis is 3 of
them, so each face vector has coefficients -2 to 2 in it. A candidate is dropped when its
midpoint lies on or beyond the bisector plane of another.
"""
lattice = np.asarray(reciprocal_lattice, dtype=np.float64)
unit = lattice / abs(np.linalg.det(lattice)) ** (1 / 3)
with warnings.catch_warnings():
# spglib warns on every call while its process-wide OLD_ERROR_HANDLING is on; the
# None return below is the error check it asks for.
warnings.filterwarnings("ignore", "Set OLD_ERROR_HANDLING", DeprecationWarning)
reduced = spglib.delaunay_reduce(unit)
if reduced is None:
raise ValueError(f"spglib cannot Delaunay-reduce the reciprocal lattice {lattice.tolist()}")
candidates = _FACE_CANDIDATES @ np.rint(reduced @ np.linalg.inv(unit)).astype(int)
zone = candidates @ lattice
beyond = zone @ zone.T >= (zone * zone).sum(axis=1)[:, None] * (1 - 1e-9)
np.fill_diagonal(beyond, False)
return candidates[~beyond.any(axis=0)]


def _wigner_seitz(reciprocal_lattice: np.ndarray) -> tuple[np.ndarray, list[list[int]]]:
"""Vertices and faces of the origin's Voronoi cell."""
lattice = np.asarray(reciprocal_lattice, dtype=np.float64)
face_steps = zone_face_steps(lattice)
steps = np.vstack([_NEIGHBOURS, face_steps[np.abs(face_steps).max(axis=1) > 1]])
brill = Voronoi(steps @ lattice)
cell = [brill.ridge_dict[pair] for pair in brill.ridge_dict if _ORIGIN in pair]
used = np.unique(np.concatenate(cell))
return brill.vertices[used], [np.searchsorted(used, face).tolist() for face in cell]


class BrillouinZone(pv.PolyData):
"""
Expand Down Expand Up @@ -93,23 +136,7 @@ def wigner_seitz(self):
Returns the wigner Seitz cell in the form of a tuple containing the verts and faces of the cell
"""
logger.info("___Calculating Wigner Seitz cell___")

kpoints = []
for i in range(-1, 2):
for j in range(-1, 2):
for k in range(-1, 2):
vec = i * self.reciprocal[0] + j * self.reciprocal[1] + k * self.reciprocal[2]
kpoints.append(vec)
# print(kpoints, self.reciprocal)
brill = Voronoi(np.array(kpoints))
faces = []
for idict in brill.ridge_dict:
if idict[0] == 13 or idict[1] == 13:
faces.append(brill.ridge_dict[idict])

verts = brill.vertices

return np.array(verts, dtype=float), faces
return _wigner_seitz(self.reciprocal)

def _fix_normals_direction(self):
"""
Expand Down Expand Up @@ -230,23 +257,7 @@ def wigner_seitz(self):
Tuple(n_verts,n_faces)
Returns the wigner Seitz cell in the form of a tuple containing the verts and faces of the cell
"""

kpoints = []
for i in range(-1, 2):
for j in range(-1, 2):
for k in range(-1, 2):
vec = i * self.reciprocal[0] + j * self.reciprocal[1] + k * self.reciprocal[2]
kpoints.append(vec)
# print(kpoints, self.reciprocal)
brill = Voronoi(np.array(kpoints))
faces = []
for idict in brill.ridge_dict:
if idict[0] == 13 or idict[1] == 13:
faces.append(brill.ridge_dict[idict])

verts = brill.vertices

return np.array(verts, dtype=float), faces
return _wigner_seitz(self.reciprocal)

def _fix_normals_direction(self):
"""
Expand Down
38 changes: 26 additions & 12 deletions pyprocar/plotter/_periodic_cut.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ class (its two vertex classes and their relative cell) and the cell of its lower
import pyvista as pv
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import connected_components
from scipy.spatial import HalfspaceIntersection

from pyprocar.core.brillouin_zone import zone_face_steps

MAX_REACH = 16
"""Cells from the origin within which an orbit through the zone must close."""
Expand All @@ -38,7 +41,6 @@ class (its two vertex classes and their relative cell) and the cell of its lower
The triangles at the vertex are in the translates 0 or 1 below; one more on each side
lets a curve grow two cells per round (0.6 s instead of 1.2 s on Au at 60^3)."""
_START_STEPS = np.array(list(itertools.product(range(-2, 3), repeat=3)))
_ZONE_STEPS = np.array([s for s in itertools.product(range(-2, 3), repeat=3) if any(s)], float)
_SLOTS = ((0, 1), (1, 2), (2, 0))
_PACK = 64
_PACK_OFFSET = 32
Expand Down Expand Up @@ -278,13 +280,27 @@ def _curves(found: list[tuple[np.ndarray, ...]]) -> _Curves:
return _Curves(names, a, b, q1, q2, degree, label, meets_region, is_open)


def _band_curves(cut: _BandCut, region: tuple[np.ndarray, np.ndarray]) -> _Curves | None:
"""Curves of the cut through the translates that can hold the zone, extended through the
translates at the open ends of curves that meet the region until those close or reach
MAX_REACH cells."""
def _start_steps(zone: np.ndarray, half: np.ndarray, inverse: np.ndarray) -> np.ndarray:
"""_START_STEPS, then the other translates whose period meets the zone's bounding box in
fractional coordinates, which a sheared basis stretches beyond two cells."""
halfspaces = np.column_stack([zone, -half])
corners = HalfspaceIntersection(halfspaces, np.zeros(3)).intersections @ inverse
low = np.floor(corners.min(axis=0)).astype(int) - 1
high = np.floor(corners.max(axis=0)).astype(int)
if max(-low.min(), high.max()) > MAX_REACH:
raise ValueError(f"the first zone spans more than {MAX_REACH} cells of this basis")
window = np.array(list(itertools.product(*map(range, low, high + 1))))
return np.vstack([_START_STEPS, window[np.abs(window).max(axis=1) > 2]])


def _band_curves(
cut: _BandCut, region: tuple[np.ndarray, np.ndarray], start: np.ndarray
) -> _Curves | None:
"""Curves of the cut through the ``start`` translates, extended through the translates at
the open ends of curves that meet the region until those close or reach MAX_REACH cells."""
found: list[tuple[np.ndarray, ...]] = []
done = np.empty(0, dtype=np.int64)
steps = _START_STEPS
steps = start
while True:
pieces = cut.segments(steps)
if pieces is not None:
Expand Down Expand Up @@ -319,19 +335,17 @@ def plane_orbits(
lattice = np.asarray(lattice, dtype=np.float64)
normal = np.asarray(normal, dtype=np.float64) / np.linalg.norm(normal)
d = float(np.asarray(origin, dtype=np.float64) @ normal)
zone = _ZONE_STEPS @ lattice
zone = zone_face_steps(lattice) @ lattice
half = 0.5 * (zone * zone).sum(axis=1)
beyond = zone @ zone.T >= 2 * half[:, None] * (1 - 1e-9)
np.fill_diagonal(beyond, False)
faces = ~beyond.any(axis=0)
region = (zone[faces], half[faces] * (1 + 2e-9))
region = (zone, half * (1 + 2e-9))
if box is not None:
region = (np.vstack([region[0], box[0]]), np.concatenate([region[1], box[1]]))
inverse = np.linalg.inv(lattice)
start = _start_steps(zone, half, inverse)
areas: list[float] = []
n_open = 0
for band in bands:
curves = _band_curves(_BandCut(band, lattice, normal, d), region)
curves = _band_curves(_BandCut(band, lattice, normal, d), region, start)
if curves is None:
continue
n_comp = len(curves.meets_region)
Expand Down
92 changes: 92 additions & 0 deletions tests/pyprocar/core/test_brillouin_zone.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@
and BrillouinZone2D classes.
"""

import itertools
import warnings

import numpy as np
import pytest
from scipy.spatial import ConvexHull, Voronoi

from pyprocar.core.brillouin_zone import BrillouinZone, BrillouinZone2D

Expand Down Expand Up @@ -332,3 +336,91 @@ def test_brillouin_zone_2d_different_lattices(
)
assert bz2d.n_cells > 0
assert bz2d.n_points > 0


MONOCLINIC = np.array([[1.0, 0.0, 0.0], [0.0, 1.3, 0.0], [0.4, 0.0, 0.9]])
TRICLINIC = np.array([[1.0, 0.1, 0.05], [0.3, 1.2, 0.0], [0.2, 0.35, 0.8]])
SHEARS = {
"unsheared": np.eye(3, dtype=int),
"b2+3b1": np.array([[1, 0, 0], [3, 1, 0], [0, 0, 1]]),
"b2+3b1,b3-2b1+2b2": np.array([[1, 0, 0], [3, 1, 0], [-2, 2, 1]]),
}
SHEARED_CELLS = [
pytest.param(cell, shear, id=f"{name}-{shear_name}")
for name, cell in [("monoclinic", MONOCLINIC), ("triclinic", TRICLINIC)]
for shear_name, shear in SHEARS.items()
]


def _voronoi_reference(cell: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Face vectors and vertices of the Voronoi cell of the origin among the 7^3 block of
lattice points of ``cell``, from scipy.spatial.Voronoi."""
steps = np.array(list(itertools.product(range(-3, 4), repeat=3)))
origin = len(steps) // 2
voronoi = Voronoi(steps @ cell)
pairs = voronoi.ridge_points[(voronoi.ridge_points == origin).any(axis=1)]
neighbours = pairs.sum(axis=1) - origin
vertices = voronoi.vertices[voronoi.regions[voronoi.point_region[origin]]]
return voronoi.points[neighbours], vertices


def _sorted_rows(points: np.ndarray) -> np.ndarray:
rounded = np.round(points, 9) + 0.0
return rounded[np.lexsort(rounded.T[::-1])]


@pytest.mark.parametrize(("cell", "shear"), SHEARED_CELLS)
def test_zone_faces_match_voronoi_for_any_basis_of_the_lattice(cell, shear):
from pyprocar.core.brillouin_zone import zone_face_steps

basis = shear @ cell
faces, _ = _voronoi_reference(cell)

found = zone_face_steps(basis) @ basis

np.testing.assert_allclose(_sorted_rows(found), _sorted_rows(faces), atol=1e-9)


@pytest.mark.parametrize(("cell", "shear"), SHEARED_CELLS)
def test_brillouin_zone_matches_voronoi_for_any_basis_of_the_lattice(cell, shear):
basis = shear @ cell
_, vertices = _voronoi_reference(cell)

zone = BrillouinZone(basis)

assert ConvexHull(zone.points).volume == pytest.approx(abs(np.linalg.det(cell)), rel=1e-9)
np.testing.assert_allclose(_sorted_rows(zone.points), _sorted_rows(vertices), atol=1e-9)


@pytest.mark.parametrize(
"shear", [SHEARS["unsheared"], SHEARS["b2+3b1"]], ids=["unsheared", "b2+3b1"]
)
def test_2d_brillouin_zone_is_the_hexagonal_prism_for_any_basis(
hexagonal_reciprocal_lattice, shear
):
"""The zone of a hexagonal reciprocal lattice with |b1| = |b2| = b is a regular hexagon
of circumradius b / sqrt(3) and area |b1 x b2|; BrillouinZone2D stretches it from
e_min to e_max."""
b1, b2, _ = hexagonal_reciprocal_lattice

zone = BrillouinZone2D(
e_min=-1.0, e_max=1.0, reciprocal_lattice=shear @ hexagonal_reciprocal_lattice
).clean()

hexagon = np.linalg.norm(np.cross(b1, b2))
assert ConvexHull(zone.points).volume == pytest.approx(2.0 * hexagon, rel=1e-9)
assert np.linalg.norm(zone.points[:, :2], axis=1) == pytest.approx(
np.full(zone.n_points, np.linalg.norm(b1) / np.sqrt(3)), rel=1e-9
)


@pytest.mark.guards_existing_behaviour(
reason="dev builds the zone without spglib; this guards the delaunay_reduce call this PR adds"
)
def test_building_a_zone_emits_no_warnings():
lattice = np.array([[1.0, 0.0, 0.0], [3.0, 1.0, 0.0], [-2.0, 2.0, 1.0]])
with warnings.catch_warnings(record=True) as record:
warnings.simplefilter("always")
BrillouinZone(lattice)

assert [str(w.message) for w in record] == []
Loading
Loading