Source code for crystod.band_unfold

"""Electronic band unfolding of two ordinary VASP band runs.

The engine of ``crystod --unfold``.  A low-symmetry *child* run (e.g. SrTiO3
I4/mcm, 10 atoms) and a high-symmetry *parent* run (SrTiO3 Pm-3m, 5 atoms),
each an ordinary band-structure calculation with its own path, are compared
without any new VASP run: the plane-wave coefficients of the child WAVECAR
are split into the N cosets of the child reciprocal lattice modulo the parent
reciprocal lattice, which gives the spectral weight of every child Bloch state
on the N parent k points it unfolds onto (Popescu and Zunger, Phys. Rev. B
85, 085201 (2012); the fold2Bloch scheme of Rubel et al., Phys. Rev. B 90,
115202 (2014)).  The setting between the two cells is that of
``crystod-group --supergroup-cif PARENT --subgroup-cif CHILD``
(:func:`crystod.phonon_unfold.find_parent_mapping`, the setting search of
``crystod-phonon --unfold``).  The figure is drawn by
:mod:`crystod.band_unfold_plot`.

Conventions (those of :mod:`crystod.phonon_unfold`)
--------------------------------------------------
* Lattice matrices hold the lattice vectors as rows (Angstrom);
  ``A_child = M @ A_parent`` with M an integer matrix, ``N = det M``.
* Fractional k as columns: ``K_child = M k_parent``, ``k_parent = M^-1 K``.
  The N coset offsets g_i are the parent k points with ``M g_i`` integer
  (:func:`crystod.phonon_unfold._parent_kpoints_folding_to_gamma`, Gamma
  first).
* A child plane wave ``K + G`` (G an integer triple of the child reciprocal
  basis, as the WAVECAR lists it) lies on the parent k point
  ``M^-1 (K + G) = M^-1 K + g_i`` with ``g_i = M^-1 G mod 1``, so the weight
  of child band n on image i is::

      w_i(n) = sum_{G in coset i} sum_spinor |C_n(G)|^2 / sum_G sum_spinor |C_n(G)|^2

  The WAVECAR holds the PAW pseudo coefficients, whose norm is not 1; every
  band is normalised, the one-centre augmentation part is neglected (the
  standard practice of plane-wave unfolding codes).  ``sum_i w_i(n) = 1``.
* Degenerate levels (bands within ``degeneracy_tol`` eV, single linkage) carry
  the level weight ``W_i = Re Tr(S^-1 P_i)`` with ``S = C C^H`` and
  ``P_i = C Pi_i C^H`` (C the d rows of plane-wave coefficients of the level,
  Pi_i the coset mask of image i): ``sum_i W_i = d``, ``W_i = w_i`` for a
  single band, the sum of the per-band weights when the rows are orthogonal,
  and invariant under any mixing of the degenerate bands (the per-band weights
  inside a level are not).  Shares printed in the tables are ``W_i / deg``.
* Symmetry transport: when ``K' = R K`` for an operation R of the child point
  group (reciprocal action ``R = inv(W).T`` of the real-space rotation W,
  time reversal ``-R``), the weight of the parent point ``k_p`` at K equals
  the weight of ``M^-1 R M k_p`` at K'.  This is how a parent path point is
  served by a child k point that the child run lists only on another arm.
* Energies are in eV; ``energy`` columns are ``E - zero`` with one common
  zero (the child's reference) unless ``separate_zero``.

Everything runs on the CPU: the job is integer coset arithmetic and sums of
``|C|^2`` (well under a second for a 350 MB WAVECAR).
"""

from __future__ import annotations

import argparse
import contextlib
import io
import os
import re
import time
import warnings
from dataclasses import dataclass, field

import numpy as np

from .phonon_unfold import (
    OUTPUT_WIDTH,
    _commas,
    _display_path,
    _fill,
    _frac_text,
    _kv,
    _legend,
    _matrix_text,
    _note,
    _parent_kpoints_folding_to_gamma,
    _reduce_half,
    _snap_rational,
    _space_group,
    _vec,
    degenerate_groups,
)

__all__ = [
    "WEIGHT_MIN",
    "DEGENERACY_TOL",
    "KPath",
    "VaspBandRun",
    "KUnfolded",
    "BandUnfolding",
    "KpointsUnfold",
    "coset_indices",
    "coset_weights",
    "level_weights",
    "image_kpoints",
    "reciprocal_rotations",
    "transport_image",
    "match_image",
    "find_equivalent",
    "make_kpath",
    "unfold_bands",
    "unfold_kpoints",
    "format_band_unfolding",
    "main",
]

# ---------------------------------------------------------------------------
# constants
# ---------------------------------------------------------------------------
WEIGHT_MIN = 0.02  # default of --weight-min: level shares below are not drawn
DEGENERACY_TOL = 1e-3  # eV, default of --degeneracy-tol
MAPPING_TOLERANCE = 0.01  # Angstrom, default of --tolerance (the setting search)
SYMPREC = 1e-5  # spglib on the run cells
SUM_RULE_TOLERANCE = 1e-10  # |sum_i w_i(n) - 1| above this: internal error
KPOINTS_TOLERANCE = 1e-6  # a KPOINTS point against the WAVECAR k list
MATCH_TOLERANCE = 1e-5  # k points of two runs (7-decimal files) modulo the lattice
PURE = 0.9  # a level share at or above this is 'pure' (alignment statistics, parent column)
MIXED = (0.1, 0.9)  # a level is mixed when an image share lies strictly inside
BLOCK_GAP = 2.0  # eV: a gap this wide ends the valence block containing the zero
FIGURE_MARGIN = 1.0  # eV below the block bottom and above the completeness limit (figure)
TABLE_MARGIN = 0.5  # eV below the block bottom (vertex tables)
TABLE_TOP = 6.0  # eV above the zero: the default top of the vertex tables
WINDOW_STEP = 0.5  # eV: the default ranges are rounded outward to this
MAX_FIGURE_IMAGES = 24  # more images than this: no figure
TABLE_CHUNK = 4  # image columns per sub-table when N >= 5
ZERO_ALIASES = {"vbm": "vbm", "efermi": "efermi", "fermi": "efermi", "raw": "raw", "none": "raw"}
SPIN_CHOICES = ("up", "down", "both")
_OCCUPIED = 0.5  # occupation above which a band is occupied (the --extract-irrep rule)
_PARTIAL = (0.01, 0.99)
_PURPOSE = "crystod --unfold"
_ZERO_TEXT = {"vbm": "E - E_VBM", "efermi": "E - E_F", "raw": "E", "value": "E - E0"}


# ---------------------------------------------------------------------------
# pure functions: cosets, images, symmetry transport, matching
# ---------------------------------------------------------------------------
def _integer_matrix(M) -> tuple:
    """``(M int64, N = det M, adj = N M^-1 int64)``; det M > 0 is required."""
    Mf = np.asarray(M, dtype=float).reshape(3, 3)
    Mi = np.rint(Mf).astype(np.int64)
    if np.abs(Mf - Mi).max() > 1e-6:
        raise ValueError("M must be an integer matrix")
    N = int(round(np.linalg.det(Mi)))
    if N <= 0:
        raise ValueError(f"det M must be positive, got {N}")
    adj = np.rint(N * np.linalg.inv(Mi.astype(float))).astype(np.int64)
    if not np.array_equal(Mi @ adj, N * np.eye(3, dtype=np.int64)):
        raise ValueError("internal error: adj(M) is not N M^-1")
    return Mi, N, adj


def coset_indices(gvecs, M, offsets=None) -> np.ndarray:
    """The coset of every child G vector: index i of the offset g_i with ``M^-1 G = g_i mod 1``.

    Exact integer arithmetic: ``N M^-1 G = adj(M) G`` is an integer triple, taken modulo N.

    Args:
        gvecs: ``(n_G, 3)`` integer G vectors (child reciprocal basis).
        M: ``A_child = M @ A_parent`` (integer, det > 0).
        offsets: ``(N, 3)`` parent fractional g_i (any representatives modulo 1);
            default :func:`crystod.phonon_unfold._parent_kpoints_folding_to_gamma`.

    Returns:
        ``(n_G,)`` int array of indices into ``offsets``.

    Raises:
        ValueError: An offset that is not a coset of M, or a G in no listed coset.
    """
    Mi, N, adj = _integer_matrix(M)
    if offsets is None:
        offsets = _parent_kpoints_folding_to_gamma(Mi)
    offsets = np.asarray(offsets, dtype=float).reshape(-1, 3)
    numerators = np.rint(offsets * N)
    if np.abs(offsets * N - numerators).max() > 1e-6:
        raise ValueError("an offset g_i is not of the form n / det M")
    off_codes = np.mod(numerators.astype(np.int64), N)
    off_codes = (off_codes[:, 0] * N + off_codes[:, 1]) * N + off_codes[:, 2]
    if len(set(off_codes.tolist())) != len(off_codes):
        raise ValueError("two offsets g_i are the same coset")
    g = np.asarray(gvecs, dtype=np.int64).reshape(-1, 3)
    codes = np.mod(g @ adj.T, N)
    codes = (codes[:, 0] * N + codes[:, 1]) * N + codes[:, 2]
    order = np.argsort(off_codes)
    pos = np.searchsorted(off_codes[order], codes)
    pos = np.clip(pos, 0, len(order) - 1)
    found = off_codes[order][pos] == codes
    if not np.all(found):
        raise ValueError(f"{int(np.sum(~found))} G vectors lie in no listed coset")
    return order[pos]


def coset_weights(gvecs, coeffs, M, offsets=None) -> tuple:
    """Unfolding weights of the bands of one child k point.

    Args:
        gvecs: ``(n_G, 3)`` integer G vectors (``Wavecar.bands``).
        coeffs: ``(n_bands, n_spinor, n_G)`` or ``(n_bands, n_G)`` plane-wave
            coefficients; both spinor components are summed.
        M: ``A_child = M @ A_parent``.
        offsets: The coset offsets g_i (default: Gamma first, as
            :func:`coset_indices`).

    Returns:
        ``(weights, norms)``: ``(n_bands, N)`` normalised weights
        (``sum_i w_i = 1``) and ``(n_bands,)`` the pseudo norms
        ``sum |C|^2`` before normalisation.

    Raises:
        ValueError: A band of zero norm, or the errors of :func:`coset_indices`.
    """
    _, N, _ = _integer_matrix(M)
    c = np.asarray(coeffs)
    if c.ndim == 2:
        c = c[:, None, :]
    p2 = np.einsum("bsg->bg", (c.real.astype(float) ** 2 + c.imag.astype(float) ** 2))
    index = coset_indices(gvecs, M, offsets)
    n_images = N if offsets is None else len(np.asarray(offsets).reshape(-1, 3))
    onehot = np.zeros((len(index), n_images))
    onehot[np.arange(len(index)), index] = 1.0
    raw = p2 @ onehot
    norms = p2.sum(axis=1)
    if np.any(norms <= 0):
        raise ValueError("a band has zero plane-wave norm")
    return raw / norms[:, None], norms


def level_weights(gvecs, coeffs, M, groups, offsets=None, weights=None) -> np.ndarray:
    """Gauge-invariant weights of the levels (degenerate band groups) of one child k point.

    For a level of d bands with coefficient rows C (``d x (n_spinor n_G)``),
    ``S = C C^H`` and ``P_i = C Pi_i C^H`` with Pi_i the coset mask of image i,
    the level weight is ``W_i = Re Tr(S^-1 P_i)``.  ``sum_i W_i = d``; a single
    band gives its weight ``w_i``; orthogonal rows give the sum of the per-band
    weights; any mixing ``C -> U C`` of the level leaves ``W_i`` unchanged.

    Args:
        gvecs, coeffs, M, offsets: As :func:`coset_weights`.
        groups: Band index arrays of the levels.
        weights: The per-band weights of :func:`coset_weights` (computed when None).

    Returns:
        ``(n_levels, N)`` level weights.
    """
    c = np.asarray(coeffs)
    if c.ndim == 2:
        c = c[:, None, :]
    if weights is None:
        weights, _norms = coset_weights(gvecs, c, M, offsets)
    index = coset_indices(gvecs, M, offsets)
    n_images = weights.shape[1]
    masks = [index == i for i in range(n_images)]
    out = np.zeros((len(groups), n_images))
    for lv, g in enumerate(groups):
        g = np.asarray(g, dtype=int)
        if len(g) == 1:
            out[lv] = weights[g[0]]
            continue
        C = c[g].astype(np.complex128)
        P = []
        for mask in masks:
            Ci = C[:, :, mask].reshape(len(g), -1)
            P.append(Ci @ Ci.conj().T)
        S = np.sum(P, axis=0)
        if np.linalg.cond(S) < 1e12:
            out[lv] = [float(np.trace(np.linalg.solve(S, Pi)).real) for Pi in P]
        else:  # linearly dependent rows (cannot happen for eigenvectors): pseudo-inverse
            Sp = np.linalg.pinv(S)
            out[lv] = [float(np.trace(Sp @ Pi).real) for Pi in P]
    return out


def image_kpoints(K, M, offsets) -> np.ndarray:
    """The N parent k points ``M^-1 K + g_i`` of a child K, reduced into (-1/2, 1/2]."""
    Minv = np.linalg.inv(np.asarray(M, dtype=float))
    base = Minv @ np.asarray(K, dtype=float).reshape(3)
    return np.array(
        [_snap_rational(_reduce_half(base + g)) for g in np.asarray(offsets, dtype=float)]
    )


def reciprocal_rotations(rotations, time_reversal: bool = True) -> np.ndarray:
    """Reciprocal action ``R = inv(W).T`` of real-space rotations W (fractional), identity
    first, followed by ``-R`` for time reversal; duplicates removed."""
    out = [np.eye(3, dtype=np.int64)]
    for W in np.asarray(rotations):
        R = np.rint(np.linalg.inv(np.asarray(W, dtype=float)).T).astype(np.int64)
        out.append(R)
    if time_reversal:
        out += [-R for R in list(out)]
    unique = []
    for R in out:
        if not any(np.array_equal(R, U) for U in unique):
            unique.append(R)
    return np.array(unique, dtype=np.int64)


def transport_image(k_parent, R, M) -> np.ndarray:
    """``M^-1 R M k_p``: where the weight of ``k_p`` at K goes when K is carried to ``R K``.

    Raises:
        ValueError: ``M^-1 R M`` is not an integer matrix (R is no parent operation).
    """
    Mf = np.asarray(M, dtype=float)
    Rp = np.linalg.solve(Mf, np.asarray(R, dtype=float) @ Mf)
    if np.abs(Rp - np.rint(Rp)).max() > 1e-8:
        raise ValueError("M^-1 R M is not an integer matrix")
    return np.rint(Rp) @ np.asarray(k_parent, dtype=float)


def match_image(q, K, M, offsets, tol: float = MATCH_TOLERANCE) -> int | None:
    """Index i with ``M^-1 K + g_i = q`` modulo the parent reciprocal lattice, or None."""
    images = image_kpoints(K, M, offsets)
    d = images - np.asarray(q, dtype=float)[None, :]
    hit = np.flatnonzero(np.abs(d - np.rint(d)).max(axis=1) < tol)
    return int(hit[0]) if len(hit) else None


def find_equivalent(k, klist, operations, tol: float = MATCH_TOLERANCE, candidates=None):
    """The first k point of a list equal to ``R k`` modulo the lattice.

    The operations are tried in order (identity first), the list entries in the
    order of ``candidates`` (default: the whole list in order).

    Args:
        k: ``(3,)`` fractional k.
        klist: ``(n, 3)`` fractional k points.
        operations: ``(n_op, 3, 3)`` integer reciprocal operations
            (:func:`reciprocal_rotations`).
        tol: Coordinate tolerance.
        candidates: Indices into ``klist`` to search, in order of preference.

    Returns:
        ``(index, R)`` or ``(None, None)``.
    """
    klist = np.asarray(klist, dtype=float)
    candidates = np.arange(len(klist)) if candidates is None else np.asarray(candidates, int)
    if not len(candidates):
        return None, None
    sub = klist[candidates]
    images = np.einsum("oij,j->oi", np.asarray(operations, dtype=float), np.asarray(k, float))
    d = sub[None, :, :] - images[:, None, :]
    ok = np.abs(d - np.rint(d)).max(axis=2) < tol
    for o in range(len(images)):
        hit = np.flatnonzero(ok[o])
        if len(hit):
            return int(candidates[hit[0]]), np.asarray(operations[o])
    return None, None


def _is_special(k, rotations, tol: float = 1e-6) -> bool:
    """True when k is an isolated point of its little co-group (no free parameter).

    ``rotations``: reciprocal operations (fractional).  The fixed space of the
    operations that leave k invariant modulo the lattice is {0}.
    """
    k = np.asarray(k, dtype=float)
    blocks = []
    for R in np.asarray(rotations, dtype=float):
        d = R @ k - k
        if np.abs(d - np.rint(d)).max() < tol:
            blocks.append(R - np.eye(3))
    if not blocks:
        return False
    rank = np.linalg.matrix_rank(np.vstack(blocks), tol=1e-8)
    return rank == 3


def _compact(k) -> str:
    return "(" + ",".join(_frac_text(v) for v in k) + ")"


# ---------------------------------------------------------------------------
# the band path of a run
# ---------------------------------------------------------------------------
@dataclass
class KPath:
    """The band path of a run (its zero-weight k points in file order).

    Attributes:
        indices: ``(n,)`` 0-based indices into the run's k list.
        kpoints: ``(n, 3)`` fractional k (the run's reciprocal basis).
        distances: ``(n,)`` 1/Angstrom without 2 pi, the run's reciprocal
            metric; no advance across a break.
        labels: Label of every path point (``None`` between vertices).
        separators: ``'-'``, ``'|'`` or ``None`` of every point.
        legs: ``[(start, end, label_start, label_end), ...]`` path positions.
        tick_positions, tick_labels: One tick per vertex, ``'S|S0'`` at a break.
        path_text: ``'GM-X-P-N-GM-M-S|S0-GM|X-R|G-M'``.
        source: Where the labels come from.
    """

    indices: np.ndarray
    kpoints: np.ndarray
    distances: np.ndarray
    labels: list
    separators: list
    legs: list
    tick_positions: np.ndarray
    tick_labels: list
    path_text: str
    source: str

    @property
    def vertices(self) -> list:
        """Path positions of the labelled points."""
        return [i for i, label in enumerate(self.labels) if label]


def _derive_vertices(kpoints, reciprocal) -> tuple:
    """Vertices and breaks of an unlabelled path: first and last point, turns, repeated
    points and jumps.  A step is a jump (a break) only when it is an isolated outlier, longer
    than 2.5 times both neighbouring (nonzero) steps, and the path turns at both of its ends;
    a leg sampled more coarsely than the others is not a break."""
    n = len(kpoints)
    labels, seps = [None] * n, [None] * n
    if n == 0:
        return labels, seps
    steps = np.diff(kpoints, axis=0) @ reciprocal
    lengths = np.linalg.norm(steps, axis=1)
    moving = lengths > 1e-9
    vertex = np.zeros(n, dtype=bool)
    vertex[0] = vertex[-1] = True
    breaks = np.zeros(n, dtype=bool)

    def turn(a: int, b: int) -> bool:
        """The direction changes from step a to step b (both nonzero)."""
        cos = float(steps[a] @ steps[b]) / (lengths[a] * lengths[b])
        return cos < 1 - 1e-8

    for i in range(1, n - 1):
        if moving[i - 1] and moving[i] and turn(i - 1, i):
            vertex[i] = True
    for i in range(n - 1):
        if not moving[i]:
            vertex[i] = vertex[i + 1] = True
            continue
        before = [j for j in range(i - 1, -1, -1) if moving[j]][:1]
        after = [j for j in range(i + 1, n - 1) if moving[j]][:1]
        if not before or not after:
            continue
        a, b = before[0], after[0]
        if lengths[i] > 2.5 * max(lengths[a], lengths[b]) and turn(a, i) and turn(i, b):
            vertex[i] = vertex[i + 1] = True
            breaks[i] = True
    for i in np.flatnonzero(vertex):
        labels[i] = ""
        seps[i] = "|" if breaks[i] else ("-" if i < n - 1 else None)
    return labels, seps


def make_kpath(kpoints, labels, separators, lattice, *, indices=None, namer=None,
               source: str = "KPOINTS labels") -> KPath:
    """Build a :class:`KPath` from path points and their labels.

    Args:
        kpoints: ``(n, 3)`` fractional path points in order.
        labels, separators: Per point (see :class:`crystod.vasp_io.KpointsFile`);
            all ``None``: the vertices are derived from turns, repeated points
            and jumps and named by ``namer``.
        lattice: ``(3, 3)`` lattice of the run (rows, Angstrom).
        indices: Indices of the points in the run's k list (default 0..n-1).
        namer: ``namer(k) -> str`` for derived vertices.
        source: Text for the report.
    """
    kpoints = np.asarray(kpoints, dtype=float).reshape(-1, 3)
    n = len(kpoints)
    reciprocal = np.linalg.inv(np.asarray(lattice, dtype=float)).T
    labels = list(labels) if labels is not None else [None] * n
    separators = list(separators) if separators is not None else [None] * n
    if not any(labels):
        labels, separators = _derive_vertices(kpoints, reciprocal)
        source = "vertices derived from the path (no labels in KPOINTS)"
        for i, label in enumerate(labels):
            if label == "":
                labels[i] = namer(kpoints[i]) if namer else _compact(kpoints[i])
    distances = np.zeros(n)
    last_sep = None
    for i in range(1, n):
        if labels[i - 1]:
            last_sep = separators[i - 1]
        step = float(np.linalg.norm((kpoints[i] - kpoints[i - 1]) @ reciprocal))
        broken = labels[i - 1] and last_sep == "|"
        distances[i] = distances[i - 1] + (0.0 if broken else step)
    vertices = [i for i, label in enumerate(labels) if label]
    ticks, tick_labels = [], []
    for i in vertices:
        if ticks and abs(distances[i] - ticks[-1]) < 1e-9:
            parts = tick_labels[-1].split("|")
            if labels[i] != parts[-1]:
                tick_labels[-1] = "|".join(parts + [labels[i]])
        else:
            ticks.append(float(distances[i]))
            tick_labels.append(labels[i])
    legs = []
    for a, b in zip(vertices[:-1], vertices[1:]):
        if separators[a] == "|" or distances[b] - distances[a] < 1e-9:
            continue
        legs.append((a, b, labels[a], labels[b]))
    if not ticks:
        ticks, tick_labels = [0.0], [""]
    path_text = "-".join(tick_labels)
    return KPath(
        indices=np.arange(n) if indices is None else np.asarray(indices, dtype=int),
        kpoints=kpoints,
        distances=distances,
        labels=labels,
        separators=separators,
        legs=legs,
        tick_positions=np.array(ticks),
        tick_labels=tick_labels,
        path_text=path_text,
        source=source,
    )


# ---------------------------------------------------------------------------
# one VASP run
# ---------------------------------------------------------------------------
@dataclass
class VaspBandRun:
    """What ``crystod --unfold`` reads of one run (child or parent)."""

    role: str
    directory: str
    wavecar: str | None
    poscar: str
    cell: object
    symbols: list
    formula: str
    space_group: str
    space_group_number: int
    primitive: bool
    lattice: np.ndarray
    nk: int = 0
    nbands: int = 0
    ispin: int = 1
    spinor: bool = False
    encut: float = 0.0
    precision: str = ""
    kpoints: np.ndarray | None = None
    eigenvalues: np.ndarray | None = None  # (nspin, nk, nbands), raw eV
    occupations: np.ndarray | None = None
    weights: np.ndarray | None = None
    path: KPath | None = None
    kpoints_source: str = ""
    kpoints_file: str | None = None
    efermi: float | None = None
    efermi_source: str = ""
    vbm: float | None = None
    vbm_at: tuple | None = None
    cbm: float | None = None
    cbm_at: tuple | None = None
    metallic: bool = False
    notes: list = field(default_factory=list)

    @property
    def gap(self) -> float | None:
        if self.vbm is None or self.cbm is None or self.metallic:
            return None
        return self.cbm - self.vbm


def _resolve_run(path: str, role: str, need_wavecar: bool = True) -> tuple:
    """``(run directory, WAVECAR path or None)``: :func:`crystod.extract_irrep._resolve_run`
    with the messages of ``--ROLE-wavecar``."""
    from .extract_irrep import _resolve_run as resolve

    return resolve(path, role=role, purpose=_PURPOSE, need_wavecar=need_wavecar)


def _read_cell(directory: str, poscar: str | None, role: str, lattice=None):
    """``(PhonopyAtoms, path)`` of the run's structure, checked against the WAVECAR lattice."""
    from .vasp_io import read_poscar_cell

    option = f"--{role}-poscar"
    if poscar is None:
        path = os.path.join(directory, "POSCAR")
        if not os.path.isfile(path):
            raise SystemExit(
                f"ERROR: no POSCAR in {directory}: the {role} structure is needed (give it with "
                f"{option} FILE; CONTCAR is not used)."
            )
    else:
        path = os.path.expanduser(poscar)
        if not os.path.isfile(path):
            raise SystemExit(f"ERROR: {option} {poscar}: no such file.")
    try:
        cell = read_poscar_cell(path)
    except (OSError, ValueError, IndexError, KeyError) as exc:
        raise SystemExit(f"ERROR: could not read {path}: {' '.join(str(exc).split())}") from None
    if lattice is not None and not np.allclose(
        np.asarray(cell.cell, float), np.asarray(lattice, float), atol=1e-4
    ):
        raise SystemExit(
            f"ERROR: the cell of {path} is not the cell of the {role} WAVECAR (lattice vectors "
            "differ by more than 1e-4 A): the plane-wave coefficients refer to the cell the run "
            "was done with."
        )
    return cell, os.path.abspath(path)


def _poscar_scale(path: str) -> float:
    """The scale line of a POSCAR (1 when it is not a single positive factor)."""
    try:
        with open(path) as handle:
            handle.readline()
            value = handle.readline().split()
        return float(value[0]) if len(value) == 1 and float(value[0]) > 0 else 1.0
    except (OSError, ValueError, IndexError):
        return 1.0


def _formula(symbols) -> str:
    from math import gcd

    counts: dict = {}
    for s in symbols:
        counts[s] = counts.get(s, 0) + 1
    divisor = 0
    for n in counts.values():
        divisor = gcd(divisor, n)
    return "".join(f"{s}{n // divisor}" if n // divisor != 1 else s for s, n in counts.items())


def _is_primitive(cell, symprec: float) -> bool:
    from phonopy.structure.cells import guess_primitive_matrix

    try:
        matrix = np.asarray(guess_primitive_matrix(cell, symprec=symprec), dtype=float)
    except Exception:  # an annotation only
        return True
    return bool(abs(abs(np.linalg.det(matrix)) - 1.0) < 1e-8)


def _vasprun_weights(directory: str) -> np.ndarray | None:
    """The k weights of ``vasprun.xml`` (``<varray name="weights">``), or None."""
    from .vasp_io import open_vasp_file, resolve_vasp_file

    path = resolve_vasp_file(os.path.join(directory, "vasprun.xml"))
    if not path:
        return None
    values, inside = [], False
    try:
        with open_vasp_file(path) as handle:
            for line in handle:
                if not inside and 'name="weights"' in line and "<varray" in line:
                    inside = True
                    continue
                if inside:
                    if "</varray>" in line:
                        break
                    match = re.search(r"<v>\s*([-+0-9.eE]+)\s*</v>", line)
                    if match:
                        values.append(float(match.group(1)))
    except (OSError, ValueError, UnicodeDecodeError):
        return None
    return np.array(values) if values else None


def _same_k(a, b, tol: float) -> np.ndarray:
    d = np.asarray(a, float) - np.asarray(b, float)
    return np.abs(d - np.rint(d)).max(axis=-1) < tol


def _kpoint_namer(cell, symprec: float):
    """``namer(k)``: the ISO-IR name of a special point of the cell, else fractions."""
    from .phonon_unfold import _isoir_name, point_rotations

    number = _space_group(cell, symprec)[1]
    ops = reciprocal_rotations(point_rotations(cell, symprec))

    def namer(k):
        if _is_special(k, ops):
            name = _isoir_name(number, cell, cell, k)
            if name:
                return name
        return _compact(k)

    return namer


def _read_path(run: VaspBandRun, symprec: float) -> None:
    """The k weights and the labelled band path of a run: KPOINTS, else EIGENVAL/vasprun.xml.

    A Cartesian KPOINTS is converted with the scale of the run's own POSCAR (the
    ``--ROLE-poscar`` file only when the run directory has none) and matched with a tolerance
    that grows with the cell (7 written decimals of 2 pi / scale).  When the KPOINTS gives no
    path, one NOTE says why and where the k weights come from instead.
    """
    from .vasp_io import read_eigenval, read_kpoints, resolve_vasp_file

    kp_path = os.path.join(run.directory, "KPOINTS")
    shown = _display_path(kp_path)
    problem = None  # why the KPOINTS gives no path ("missing": there is none)
    kfile = None
    path_mask = labels = separators = None
    resolved = resolve_vasp_file(kp_path)
    own_poscar = os.path.join(run.directory, "POSCAR")
    scale = _poscar_scale(own_poscar if os.path.isfile(own_poscar) else run.poscar)
    if not resolved:
        problem = "missing"
    else:
        try:
            kfile = read_kpoints(kp_path, lattice=run.lattice, scale=scale)
        except (ValueError, SystemExit) as exc:
            text = " ".join(str(exc).split()).removeprefix("ERROR: ")
            for prefix in (f"{kp_path}: ", f"{resolved}: "):
                text = text.removeprefix(prefix)
            problem = f"the KPOINTS file {shown} is not readable as a k list ({text.rstrip('.')})"
    if kfile is not None and kfile.mode == "automatic":
        problem = f"the KPOINTS file {shown} is an automatic mesh"
    elif kfile is not None:
        tol = KPOINTS_TOLERANCE
        if kfile.coordinates == "cartesian":
            longest = float(np.linalg.norm(np.asarray(run.lattice, float), axis=1).max())
            tol = max(KPOINTS_TOLERANCE, 1e-7 * longest / scale)
        if len(kfile.kpoints) == run.nk and np.all(_same_k(kfile.kpoints, run.kpoints, tol)):
            run.weights = kfile.weights.copy()
            path_mask = kfile.path_mask
            labels = [kfile.labels[i] for i in np.flatnonzero(path_mask)]
            separators = [kfile.separators[i] for i in np.flatnonzero(path_mask)]
            run.kpoints_source = f"{shown} ({kfile.mode})"
            run.kpoints_file = os.path.abspath(resolved)
        else:
            problem = (f"the points of {shown} are not the {run.nk} k points of the {run.role} "
                       "WAVECAR in order")
    derived = path_mask is None
    if derived:
        weights = None
        source = ""
        if run.ispin == 1 and resolve_vasp_file(os.path.join(run.directory, "EIGENVAL")):
            try:
                ek, ew, _e, _o = read_eigenval(os.path.join(run.directory, "EIGENVAL"))
                if len(ek) == run.nk and np.all(_same_k(ek, run.kpoints, KPOINTS_TOLERANCE)):
                    weights, source = ew, "EIGENVAL weights"
            except (SystemExit, ValueError, IndexError, OSError):
                weights = None
        if weights is None:
            vw = _vasprun_weights(run.directory)
            if vw is not None and len(vw) == run.nk:
                weights, source = vw, "vasprun.xml weights"
        if weights is None:
            weights = np.zeros(run.nk)
            source = "no weights found: every k point is a path point"
            weight_text = ("no k weights were found (no matching EIGENVAL or vasprun.xml), so "
                           "every k point of the WAVECAR is a path point")
        else:
            weight_text = f"the k weights are those of {source.split()[0]}"
        if problem == "missing":
            note = (f"NOTE: no KPOINTS in {_display_path(run.directory)}; vertices derived from "
                    f"the k list; {weight_text}.")
        else:
            note = (f"NOTE: {problem}; the band path is the WAVECAR k list (vertices derived "
                    f"from the k list); {weight_text}.")
        run.notes.append(note)
        run.weights = np.asarray(weights, float)
        zero = run.weights == 0.0
        path_mask = zero if np.any(zero) else np.ones(run.nk, dtype=bool)
        run.kpoints_source = f"WAVECAR k list ({source})"
    indices = np.flatnonzero(path_mask)
    namer = _kpoint_namer(run.cell, symprec)
    run.path = make_kpath(
        run.kpoints[indices],
        labels,
        separators,
        run.lattice,
        indices=indices,
        namer=namer,
        source="KPOINTS labels",
    )
    if derived:
        run.path.source = "vertices derived from the k list"


def read_band_run(path: str, role: str, poscar: str | None = None, *,
                  symprec: float = SYMPREC, need_wavecar: bool = True) -> VaspBandRun:
    """Read the WAVECAR header, structure, k weights and band path of one run.

    Args:
        path: WAVECAR file or run directory.
        role: ``'child'`` or ``'parent'`` (for the messages).
        poscar: Structure file in place of the run's POSCAR.
        symprec: spglib tolerance on the run cell.
        need_wavecar: False for ``--unfold-kpoints`` (only the run's files).

    Raises:
        SystemExit: Missing or unreadable files, a POSCAR that is not the run's cell.
    """
    from .vasp_wavecar import Wavecar

    directory, wavecar = _resolve_run(path, role, need_wavecar)
    lattice = None
    wav = None
    if wavecar is not None:
        try:
            wav = Wavecar(wavecar, allow_spin_polarized=True, purpose=_PURPOSE)
        except (ValueError, IndexError, OSError) as exc:
            raise SystemExit(f"ERROR: {wavecar}: unreadable WAVECAR ({exc}).") from None
        lattice = wav.lattice
    cell, poscar_path = _read_cell(directory, poscar, role, lattice)
    symbol, number = _space_group(cell, symprec)
    symbols = list(cell.symbols)
    run = VaspBandRun(
        role=role,
        directory=directory,
        wavecar=wavecar,
        poscar=poscar_path,
        cell=cell,
        symbols=symbols,
        formula=_formula(symbols),
        space_group=f"{symbol} (No. {number})",
        space_group_number=int(number),
        primitive=_is_primitive(cell, symprec),
        lattice=np.asarray(cell.cell, float),
    )
    if wav is None:
        return run
    with wav:
        try:
            run.nk, run.nbands, run.ispin = wav.nk, wav.nb, wav.nspin
            run.spinor = bool(wav.spinor)
            run.encut = float(wav.encut)
            run.precision = np.dtype(wav.cdtype).name
            run.kpoints = wav.kpoints()
            headers = [[wav.header(ik, isp) for ik in range(wav.nk)] for isp in range(wav.nspin)]
        except (ValueError, IndexError, OSError) as exc:
            raise SystemExit(f"ERROR: {wavecar}: unreadable WAVECAR ({exc}).") from None
        header_efermi = wav.efermi
    run.eigenvalues = np.array([[h[2] for h in channel] for channel in headers])
    run.occupations = np.array([[h[3] for h in channel] for channel in headers])
    from .extract_irrep import _read_efermi

    run.efermi, run.efermi_source = _read_efermi(directory, header_efermi)
    occupied = run.occupations > _OCCUPIED
    if np.any(occupied):
        run.vbm = float(np.max(np.where(occupied, run.eigenvalues, -np.inf)))
        isp, ik, ib = np.unravel_index(
            np.argmax(np.where(occupied, run.eigenvalues, -np.inf)), run.eigenvalues.shape
        )
        run.vbm_at = (int(ik) + 1, int(ib) + 1, int(isp))
    if np.any(~occupied):
        run.cbm = float(np.min(np.where(~occupied, run.eigenvalues, np.inf)))
        isp, ik, ib = np.unravel_index(
            np.argmin(np.where(~occupied, run.eigenvalues, np.inf)), run.eigenvalues.shape
        )
        run.cbm_at = (int(ik) + 1, int(ib) + 1, int(isp))
    partial = bool(np.any((run.occupations > _PARTIAL[0]) & (run.occupations < _PARTIAL[1])))
    run.metallic = partial or (run.vbm is not None and run.cbm is not None and run.cbm < run.vbm)
    _read_path(run, symprec)
    return run


# ---------------------------------------------------------------------------
# results
# ---------------------------------------------------------------------------
@dataclass
class KUnfolded:
    """One child k point (one spin channel) unfolded.

    Attributes:
        index: 0-based index in the child WAVECAR.
        spin: Spin channel (0, or 1 = down).
        K: ``(3,)`` child fractional k.
        images: ``(N, 3)`` parent k ``M^-1 K + g_i`` reduced into (-1/2, 1/2].
        energies: ``(n_bands,)`` raw eigenvalues (eV).
        weights: ``(n_bands, N)`` per-band weights.
        norms: ``(n_bands,)`` pseudo norms before normalisation.
        groups: Band index arrays of the levels (ascending energy).
        group_weights: ``(n_levels, N)`` level weights ``W_i = Re Tr(S^-1 P_i)``
            (:func:`level_weights`; invariant under any mixing of the degenerate bands).
    """

    index: int
    spin: int
    K: np.ndarray
    images: np.ndarray
    energies: np.ndarray
    weights: np.ndarray
    norms: np.ndarray
    groups: list
    group_weights: np.ndarray

    @property
    def level_energies(self) -> np.ndarray:
        return np.array([float(np.mean(self.energies[g])) for g in self.groups])

    @property
    def level_sizes(self) -> np.ndarray:
        return np.array([len(g) for g in self.groups])

    def band_level(self) -> np.ndarray:
        """Level index of every band."""
        out = np.zeros(len(self.energies), dtype=int)
        for i, g in enumerate(self.groups):
            out[g] = i
        return out


[docs] @dataclass class BandUnfolding: """The result of :func:`unfold_bands` (``crystod --unfold``). Attributes: child, parent: :class:`VaspBandRun` (``parent`` without WAVECAR when only ``parent_cell`` was given). mapping: :class:`crystod.phonon_unfold.ParentMapping`. M, N: ``A_child = M A_parent``, ``N = det M``. offsets: ``(N, 3)`` coset offsets g_i (parent fractional, Gamma first). image_names: ISO-IR names of the g_i in the parent. zero, zero_energy, parent_zero_energy: Energy reference (mode, the value subtracted from child and parent eigenvalues). spins: Spin channels analysed. unfolded: ``{(spin, index): KUnfolded}``. child_matches: ``{(index, i): parent k index}`` parent k points (any arm, time reversal) equal to image i of child k ``index``. parent_view: per spin: ``[(path position, parent index, child index, image i, R), ...]`` for the covered parent path points. coverage: ``[(leg text, covered, total, positions), ...]`` per parent leg; ``positions`` are the covered points as 0-based offsets along the leg. alignment: Statistics of ``E_child - E_parent`` over pure matched levels (each distinct child K once). checks: The numerical checks of the summary. notes: NOTE lines (setup block). symmetry_notes: NOTE lines of the Parent path coverage block. child_ops: Reciprocal child operations used to relate child k points (point group and time reversal; only E and -E for an ISPIN = 2 child). setting_coverage: The best-covering equivalent setting when it covers more parent path points than this one (``{'M', 'coverage', 'covered', 'total'}``), else None. """ child: VaspBandRun parent: VaspBandRun | None mapping: object M: np.ndarray N: int offsets: np.ndarray image_names: list zero: str zero_energy: float parent_zero_energy: float | None separate_zero: bool spins: list degeneracy_tol: float weight_min: float window: tuple | None all_kpoints: bool unfolded: dict child_matches: dict parent_view: dict coverage: list alignment: dict checks: dict top_complete: float notes: list = field(default_factory=list) timings: dict = field(default_factory=dict) files: dict = field(default_factory=dict) command: str = "" parent_poscar: str = "" alignment_all: dict = field(default_factory=dict) symmetry_notes: list = field(default_factory=list) child_ops: np.ndarray | None = None setting_coverage: dict | None = None figure_error: str | None = None # -- helpers -----------------------------------------------------------
[docs] def path_entries(self, spin: int) -> list: """The :class:`KUnfolded` of the child path points in path order.""" return [self.unfolded[(spin, int(ik))] for ik in self.child.path.indices]
[docs] def parent_energies(self, index: int, spin: int) -> np.ndarray: """Parent eigenvalues (relative to the parent zero) at parent k ``index``.""" channel = min(spin, self.parent.ispin - 1) return self.parent.eigenvalues[channel, index] - self.parent_zero_energy
[docs] def nearest_parent(self, ik: int, image: int, energy: float, spin: int): """``(parent index, parent energy)`` of the parent level nearest to ``energy`` (relative) at the parent k equal to image ``image`` of child k ``ik``; ``(None, None)`` without.""" j = self.child_matches.get((ik, image)) if j is None or self.parent is None or self.parent.eigenvalues is None: return None, None energies = self.parent_energies(j, spin) return j, float(energies[np.argmin(np.abs(energies - energy))])
@property def zero_text(self) -> str: return _ZERO_TEXT.get(self.zero, "E - E0")
[docs] def distinct_path_entries(self, spin: int) -> list: """:meth:`path_entries` with every child K once (modulo the child reciprocal lattice): a K repeated on the path (the child Gamma at three vertices) counts once.""" out, seen = [], [] for entry in self.path_entries(spin): if any(_same_k(entry.K, k, MATCH_TOLERANCE) for k in seen): continue seen.append(entry.K) out.append(entry) return out
[docs] def default_window(self) -> dict: """The default energy ranges (eV relative to the zero) of the figure and the tables. The child path levels are sorted; from the highest level at or below the zero the walk goes down while consecutive levels are closer than 2 eV: that is the valence block containing the zero. Figure: from its bottom - 1 eV to min(completeness limit + 1 eV, child maximum + 0.3 eV); tables: from its bottom - 0.5 eV to 6 eV (not above the figure's top); all rounded outward to 0.5 eV. Returns: ``{'figure': (lo, hi), 'table': (lo, hi), 'block_bottom': E, 'whole': (lo, hi)}`` (``whole``: integer limits that hold the whole child spectrum). """ import math cached = getattr(self, "_default_window", None) if cached is not None: return cached idx = self.child.path.indices e = np.sort(np.concatenate([self.child.eigenvalues[isp][idx].ravel() for isp in self.spins]) - self.zero_energy) below = np.flatnonzero(e <= 0.0) i = int(below[-1]) if len(below) else 0 while i > 0 and e[i] - e[i - 1] < BLOCK_GAP: i -= 1 bottom = float(e[i]) step = WINDOW_STEP lo = math.floor((bottom - FIGURE_MARGIN) / step + 1e-9) * step top = min(self.top_complete + FIGURE_MARGIN, float(e[-1]) + 0.3) hi = math.ceil(top / step - 1e-9) * step if hi <= lo: hi = lo + step t_lo = math.floor((bottom - TABLE_MARGIN) / step + 1e-9) * step t_hi = min(TABLE_TOP, hi) if t_hi <= t_lo: t_hi = hi whole = (math.floor(float(e[0]) - 1.0), math.ceil(float(e[-1]) + 1.0)) out = {"figure": (float(lo), float(hi)), "table": (float(t_lo), float(t_hi)), "block_bottom": bottom, "whole": (int(whole[0]), int(whole[1]))} self._default_window = out return out
@property def figure_window(self) -> tuple: """``--window``, else the default figure range (both pages).""" return tuple(self.window) if self.window is not None else self.default_window()["figure"] @property def table_window(self) -> tuple: """``--window``, else the default range of the vertex tables.""" return tuple(self.window) if self.window is not None else self.default_window()["table"]
[docs] def to_dict(self) -> dict: return _result_dict(self)
[docs] def write_dat(self, path: str) -> str: return write_dat(self, path)
[docs] def write_yaml(self, path: str) -> str: return write_yaml(self, path)
[docs] def plot(self, path: str) -> int: from .band_unfold_plot import plot_band_unfolding return plot_band_unfolding(path, self)
# --------------------------------------------------------------------------- # the engine # --------------------------------------------------------------------------- def _zero_reference(run: VaspBandRun, zero: str, value: float | None) -> float: if zero == "value": return float(value) if zero == "raw": return 0.0 if zero == "efermi": return float(run.efermi) if run.vbm is None: raise SystemExit( f"ERROR: no occupied band in the {run.role} WAVECAR: --zero vbm needs one (use " "--zero efermi or raw)." ) return float(run.vbm) def _parse_zero(zero) -> tuple: """``(mode, value)``: ``vbm``, ``efermi`` (``fermi``), ``raw`` (``none``) or a finite number.""" if isinstance(zero, (int, float, np.integer, np.floating)) and not isinstance(zero, bool): value = float(zero) else: text = str(zero).strip().lower() if text in ZERO_ALIASES: return ZERO_ALIASES[text], None try: value = float(text) except ValueError: raise SystemExit( f"ERROR: --zero {zero}: choose vbm, efermi (fermi), raw (none) or an energy in eV." ) from None if not np.isfinite(value): raise SystemExit(f"ERROR: --zero {zero}: the energy must be a finite number of eV.") return "value", value _TRANS_MAT_ERROR = "ERROR: --trans-mat takes nine integers (rows of T, A_child = T A_parent)." def _trans_mat_matrix(trans_mat) -> np.ndarray | None: """``(3, 3)`` int of ``--trans-mat`` (nine integers, numbers or integer strings), or None. Raises: SystemExit: Not nine integers (the same text for every caller). """ if trans_mat is None: return None try: values = np.asarray(trans_mat, dtype=float).reshape(-1) except (TypeError, ValueError): raise SystemExit(_TRANS_MAT_ERROR) from None if values.size != 9 or not np.all(np.isfinite(values)) or \ np.abs(values - np.rint(values)).max() > 1e-9: raise SystemExit(_TRANS_MAT_ERROR) return np.rint(values).astype(int).reshape(3, 3) def _symmetry_ops(cell, spin_polarized: bool, symprec: float) -> np.ndarray: """Reciprocal operations that relate k points of a run: its point group and time reversal, or only E and -E for a spin-polarized (ISPIN = 2) run, whose spin density need not have the symmetry of its POSCAR.""" from .phonon_unfold import point_rotations if spin_polarized: return reciprocal_rotations(np.eye(3, dtype=int)[None]) return reciprocal_rotations(point_rotations(cell, symprec)) def _check_mapping_compatible(child: VaspBandRun, parent_cell) -> list: notes = [] if not _is_primitive(parent_cell, SYMPREC): notes.append( "NOTE: the parent run cell is not primitive; the unfolding is onto the zone of the " "parent run cell as given (what the parent run computed), so some images are " "equivalent points of the primitive zone." ) if not child.primitive: notes.append( "NOTE: the child run cell is not primitive; it is unfolded as given (the G vectors " "and k points of the WAVECAR refer to it)." ) return notes def _parent_rotations(child_ops, M) -> list: """``[(R, M^-1 R M or None), ...]`` for the child operations: the action of R on the parent images (None when it is not an operation of the parent lattice in this setting).""" Mf = np.asarray(M, dtype=float) out = [] for R in np.asarray(child_ops): Rp = np.linalg.solve(Mf, np.asarray(R, dtype=float) @ Mf) out.append((R, np.rint(Rp) if np.abs(Rp - np.rint(Rp)).max() < 1e-8 else None)) return out def _image_permutation(images_a, images_b, Rp) -> list | None: """``perm[i] = j``: image i of K (``images_a``) carried by ``Rp = M^-1 R M`` is image j of ``R K`` (``images_b``); None when an image has no partner.""" perm = [] for q in np.asarray(images_a, float): d = np.asarray(images_b, float) - (Rp @ q)[None, :] hit = np.flatnonzero(np.abs(d - np.rint(d)).max(axis=1) < MATCH_TOLERANCE) if not len(hit): return None perm.append(int(hit[0])) return perm if len(set(perm)) == len(perm) else None def _image_classes(entry: KUnfolded, rotations) -> list: """Classes of images of a child K that an operation of its little co-group (or time reversal) exchanges: ``[[i, j, ...], ...]`` (singletons included, ascending).""" n = len(entry.images) parent = list(range(n)) def root(i): while parent[i] != i: parent[i] = parent[parent[i]] i = parent[i] return i for R, Rp in rotations: if Rp is None: continue d = np.asarray(R, float) @ entry.K - entry.K if np.abs(d - np.rint(d)).max() >= MATCH_TOLERANCE: continue perm = _image_permutation(entry.images, entry.images, Rp) if perm is None: continue for i, j in enumerate(perm): a, b = root(i), root(j) if a != b: parent[max(a, b)] = min(a, b) classes: dict = {} for i in range(n): classes.setdefault(root(i), []).append(i) return sorted(classes.values()) def _leg_coverage(path: KPath, covered) -> list: """``[(leg text, covered, total, positions along the leg), ...]`` of a covered position set.""" out = [] for a, b, la, lb in path.legs: positions = [p - a for p in range(a, b + 1) if p in covered] out.append((f"{la}-{lb}", len(positions), b - a + 1, positions)) return out def _settings_coverage(settings, parent_path: KPath, child_kpoints, child_ops) -> list: """Covered parent path positions in every equivalent setting: ``[(M, set), ...]``. Pure k-point matching (no WAVECAR): ``M k_p`` against the child k list and its images under the child operations, modulo the child reciprocal lattice (a periodic k-d tree). """ from scipy.spatial import cKDTree def wrap(points): points = np.mod(np.asarray(points, float), 1.0) points[points >= 1.0] -= 1.0 return points orbit = np.einsum("oij,kj->oki", np.asarray(child_ops, float), np.asarray(child_kpoints, float)).reshape(-1, 3) tree = cKDTree(wrap(orbit), boxsize=1.0) out = [] for Ms in settings: K = wrap(np.asarray(parent_path.kpoints, float) @ np.asarray(Ms, float).T) dist, _ = tree.query(K, k=1, p=np.inf, distance_upper_bound=MATCH_TOLERANCE) out.append((np.asarray(Ms, dtype=int), set(np.flatnonzero(np.isfinite(dist)).tolist()))) return out
[docs] def unfold_bands( child, parent=None, *, child_cell: str | None = None, parent_cell: str | None = None, trans_mat=None, zero="vbm", separate_zero: bool = False, spin: str = "both", degeneracy_tol: float = DEGENERACY_TOL, all_kpoints: bool = False, weight_min: float = WEIGHT_MIN, symprec: float = SYMPREC, window=None, tolerance: float = MAPPING_TOLERANCE, ) -> BandUnfolding: """Unfold the bands of a child VASP run onto the zone of its parent. The Python form of ``crystod --unfold --child-wavecar C --parent-wavecar P``. Args: child: Child WAVECAR or run directory (with its POSCAR and KPOINTS). parent: Parent WAVECAR or run directory; ``None`` with ``parent_cell`` (no parent eigenvalues: no overlay, no parent-path view). child_cell, parent_cell: Structure files in place of the runs' POSCARs (the same cells as the WAVECARs). trans_mat: Nine integers, ``A_child = T A_parent``: one of the equivalent settings (default: crystod-group's). zero: ``'vbm'``, ``'efermi'`` (``'fermi'``), ``'raw'`` (``'none'``) or an energy in eV, taken from the child and applied to both runs. separate_zero: Each run at its own reference (``vbm`` or ``efermi``). spin: ``'up'``, ``'down'`` or ``'both'`` (ISPIN = 2 runs). degeneracy_tol: Bands closer than this (eV, single linkage) form a level. all_kpoints: Unfold the weighted (mesh) k points too. weight_min: Level shares below this are not drawn. symprec: spglib tolerance on the run cells. window: ``(emin, emax)`` eV relative to the zero for the figure and tables (default: :meth:`BandUnfolding.default_window`). tolerance: Tolerance of the setting search (Angstrom, crystod-group's 0.01). Returns: :class:`BandUnfolding`. Raises: SystemExit: Every user error as one ``ERROR:`` line (``ValueError`` through ``crystod.salc``). """ from .phonon_unfold import find_parent_mapping from .vasp_wavecar import Wavecar timings = {} t_start = time.perf_counter() zero_mode, zero_value = _parse_zero(zero) if separate_zero and zero_mode not in ("vbm", "efermi"): raise SystemExit("ERROR: --separate-zero needs --zero vbm or --zero efermi.") if spin not in SPIN_CHOICES: raise SystemExit(f"ERROR: --spin {spin}: choose one of {', '.join(SPIN_CHOICES)}.") degeneracy_tol = float(DEGENERACY_TOL if degeneracy_tol is None else degeneracy_tol) if not degeneracy_tol > 0: raise SystemExit("ERROR: --degeneracy-tol takes a positive energy in eV.") weight_min = float(WEIGHT_MIN if weight_min is None else weight_min) if not 0.0 <= weight_min < 1.0: raise SystemExit("ERROR: --weight-min takes a share in [0, 1).") if window is not None: window = (float(window[0]), float(window[1])) if not window[0] < window[1]: raise SystemExit("ERROR: --window takes EMIN < EMAX (eV relative to the zero).") if parent is None and parent_cell is None: raise SystemExit( "ERROR: crystod --unfold needs the parent: --parent-wavecar (run directory or " "WAVECAR) or at least --parent-poscar FILE." ) trans_mat = _trans_mat_matrix(trans_mat) t0 = time.perf_counter() child_run = read_band_run(child, "child", child_cell, symprec=symprec) parent_run = None if parent is not None: parent_run = read_band_run(parent, "parent", parent_cell, symprec=symprec) timings["read"] = time.perf_counter() - t0 if child_run.ispin == 1 and spin != "both": raise SystemExit(f"ERROR: --spin {spin}: the child run is not spin-polarized (ISPIN = 1).") if parent_run is not None and child_run.ispin == 1 and parent_run.ispin == 2: raise SystemExit("ERROR: child ISPIN = 1, parent ISPIN = 2: a spin-polarized parent " "needs a spin-polarized child.") if parent_run is not None and parent_run.spinor != child_run.spinor: raise SystemExit( "ERROR: one run is a spin-orbit (vasp_ncl) run and the other is not: the two runs " "must treat the spin alike." ) parent_poscar = parent_run.poscar if parent_run is not None else os.path.abspath(parent_cell) if parent_run is None: if not os.path.isfile(parent_poscar): raise SystemExit(f"ERROR: --parent-poscar {parent_cell}: no such file.") p_cell, _ = _read_cell(os.path.dirname(parent_poscar), parent_poscar, "parent") else: p_cell = parent_run.cell t0 = time.perf_counter() try: with contextlib.redirect_stdout(io.StringIO()), warnings.catch_warnings(): warnings.simplefilter("ignore") mapping = find_parent_mapping( child_run.poscar, parent_poscar, child_cell=child_run.cell, parent_cell=p_cell, trans_mat=trans_mat, tolerance=tolerance, ) except SystemExit: raise # the setting search words its own ERROR lines (crystod-phonon --unfold's) except Exception as exc: # noqa: BLE001 - the mapping engine's own failures: one line raise SystemExit( "ERROR: the child and parent structures cannot be related: " f"{type(exc).__name__}: {' '.join(str(exc).split())}" ) from None timings["mapping"] = time.perf_counter() - t0 M = np.asarray(mapping.M, dtype=np.int64) N = int(mapping.N) offsets = np.asarray(mapping.folding_kpoints, dtype=float) names = list(mapping.folding_names) notes = list(mapping.notes) + _check_mapping_compatible(child_run, p_cell) notes += child_run.notes + (parent_run.notes if parent_run is not None else []) if parent_run is not None and child_run.ispin == 2 and parent_run.ispin == 1: notes.append("NOTE: the parent run is not spin-polarized (ISPIN = 1): its eigenvalues " "are overlaid on both spin channels of the child.") # energy zero: the child reference for both runs unless separate_zero zero_energy = _zero_reference(child_run, zero_mode, zero_value) parent_zero = None if parent_run is not None: parent_zero = ( _zero_reference(parent_run, zero_mode, zero_value) if separate_zero else zero_energy ) if zero_mode == "efermi" and not child_run.metallic: notes.append( "NOTE: --zero efermi on an insulator: VASP puts E_fermi anywhere in the gap " "(the smearing midpoint), so this zero is arbitrary within the gap." ) spins = list(range(child_run.ispin)) if child_run.ispin == 2 and spin != "both": spins = [0 if spin == "up" else 1] # symmetry: the child's point group and time reversal; only E and -E when spin-polarized symmetry_notes = [] child_ops = _symmetry_ops(child_run.cell, child_run.ispin == 2, symprec) parent_ops = _symmetry_ops(p_cell, parent_run is not None and parent_run.ispin == 2, symprec) if child_run.ispin == 2: symmetry_notes.append( "NOTE: the child run is spin-polarized (ISPIN = 2): the POSCAR symmetry need not be " "a symmetry of the spin density, so only K and -K are used to relate child k points " "(parent path view, overlay, symmetry checks)." ) elif child_run.spinor: symmetry_notes.append( "NOTE: the child is a spin-orbit (vasp_ncl) run: the child point group and time " "reversal are used to relate k points, which assumes a non-magnetic, " "time-reversal-symmetric run; for a magnetic vasp_ncl run read only the child path " "view (page 1 of the figure)." ) # which child k points are unfolded path_idx = [int(i) for i in child_run.path.indices] wanted = list(path_idx) if all_kpoints: wanted = list(range(child_run.nk)) # copies of every vertex K (modulo the lattice, any index) for the copy check copies = {} for pos in child_run.path.vertices: ik = path_idx[pos] if any(ik in members for members in copies.values()): continue same = np.flatnonzero(_same_k(child_run.kpoints, child_run.kpoints[ik], MATCH_TOLERANCE)) copies[ik] = [int(j) for j in same] wanted += copies[ik] # the parent path view: child k for every parent path point view_hits = [] if parent_run is not None: Mf = M.astype(float) preference = list(dict.fromkeys(path_idx + list(range(child_run.nk)))) for pos, kp in enumerate(parent_run.path.kpoints): K = Mf @ kp j, R = find_equivalent(K, child_run.kpoints, child_ops, candidates=preference) view_hits.append((pos, j, R)) if j is not None: wanted.append(j) wanted = sorted(set(wanted)) t0 = time.perf_counter() unfolded = {} max_sum_dev = 0.0 norm_range = [np.inf, -np.inf] with Wavecar(child_run.wavecar, allow_spin_polarized=True, purpose=_PURPOSE) as wav: for isp in spins: for ik in wanted: try: gvecs, coeffs, eps, _occ, kvec = wav.bands(ik, isp) weights, norms = coset_weights(gvecs, coeffs, M, offsets) groups = degenerate_groups(eps, degeneracy_tol) gw = level_weights(gvecs, coeffs, M, groups, offsets, weights) except ValueError as exc: raise SystemExit( f"ERROR: unfolding child k#{ik + 1}: {' '.join(str(exc).split())}." ) from None max_sum_dev = max(max_sum_dev, float(np.abs(weights.sum(axis=1) - 1.0).max())) norm_range = [min(norm_range[0], float(norms.min())), max(norm_range[1], float(norms.max()))] unfolded[(isp, ik)] = KUnfolded( index=ik, spin=isp, K=np.asarray(kvec, float), images=image_kpoints(kvec, M, offsets), energies=np.asarray(eps, float), weights=weights, norms=norms, groups=groups, group_weights=gw) if max_sum_dev > SUM_RULE_TOLERANCE: raise SystemExit( f"ERROR: internal error: the unfolding weights of a band add up to 1 only within " f"{max_sum_dev:.2e} (> {SUM_RULE_TOLERANCE:g})." ) timings["unfolding"] = time.perf_counter() - t0 # parent matches of the images of every unfolded child k (exact k, any arm, time reversal) t0 = time.perf_counter() child_matches = {} if parent_run is not None: for ik in wanted: for i, q in enumerate(image_kpoints(child_run.kpoints[ik], M, offsets)): j, _R = find_equivalent(q, parent_run.kpoints, parent_ops) if j is not None: child_matches[(ik, i)] = j # the parent path view parent_view = {} coverage = [] setting_coverage = None if parent_run is not None: for isp in spins: rows = [] for pos, j, R in view_hits: if j is None: continue try: q = transport_image(parent_run.path.kpoints[pos], R, M) except ValueError: raise SystemExit( "ERROR: internal error: a child point operation is not an operation of " "the parent in this setting." ) from None i = match_image(q, child_run.kpoints[j], M, offsets) if i is None: raise SystemExit( "ERROR: internal error: a transported parent k point is no image of " f"child k#{j + 1}." ) rows.append((pos, int(parent_run.path.indices[pos]), j, i, R)) parent_view[isp] = rows covered = {pos for pos, j, _R in view_hits if j is not None} coverage = _leg_coverage(parent_run.path, covered) # the other equivalent settings (domain orientations) sample other parent legs settings = list(mapping.equivalent_settings or [M]) if len(settings) > 1: t1 = time.perf_counter() per_setting = _settings_coverage(settings, parent_run.path, child_run.kpoints, child_ops) best_M, best = max(per_setting, key=lambda item: len(item[1])) if len(best) > len(covered): setting_coverage = { "M": best_M, "coverage": _leg_coverage(parent_run.path, best), "covered": len(best), "total": len(parent_run.path.indices), "this_setting": len(covered), } timings["settings"] = time.perf_counter() - t1 timings["matching"] = time.perf_counter() - t0 # completeness: above the lowest top band of the child the spectrum is incomplete tops = child_run.eigenvalues[spins][:, path_idx, -1] top_complete = float(tops.min()) - zero_energy result = BandUnfolding( child=child_run, parent=parent_run, mapping=mapping, M=M, N=N, offsets=offsets, image_names=names, zero=zero_mode, zero_energy=float(zero_energy), parent_zero_energy=None if parent_zero is None else float(parent_zero), separate_zero=bool(separate_zero), spins=spins, degeneracy_tol=degeneracy_tol, weight_min=weight_min, window=window, all_kpoints=bool(all_kpoints), unfolded=unfolded, child_matches=child_matches, parent_view=parent_view, coverage=coverage, alignment={}, checks={}, top_complete=top_complete, notes=notes, timings=timings, parent_poscar=parent_poscar, symmetry_notes=symmetry_notes, child_ops=child_ops, setting_coverage=setting_coverage, ) result.alignment = _alignment(result, result.table_window) result.alignment_all = _alignment(result) result.checks = _checks(result, max_sum_dev, norm_range, copies, child_ops) timings["total"] = time.perf_counter() - t_start return result
def _alignment(result: BandUnfolding, window=None) -> dict: """``E_child - E_parent`` over the pure levels (share >= 0.9) of the child path points whose image is a parent k point of the parent run, below the completeness limit and inside ``window`` (eV relative to the zero; None: every level); every distinct child K once.""" if result.parent is None: return {} diffs = [] for isp in result.spins: for entry in result.distinct_path_entries(isp): energies = entry.level_energies - result.zero_energy shares = entry.group_weights / entry.level_sizes[:, None] for lv, energy in enumerate(energies): if energy > result.top_complete: continue if window is not None and not window[0] <= energy <= window[1]: continue for i in np.flatnonzero(shares[lv] >= PURE): _j, e_par = result.nearest_parent(entry.index, int(i), float(energy), isp) if e_par is not None: diffs.append(energy - e_par) if not diffs: return {"n": 0, "window": None if window is None else [float(v) for v in window]} d = np.array(diffs) return { "window": None if window is None else [float(window[0]), float(window[1])], "n": int(len(d)), "median": float(np.median(d)), "mean": float(np.mean(d)), "rms": float(np.sqrt(np.mean(d**2))), "max_abs": float(np.abs(d).max()), } def _group_signature(entry: KUnfolded) -> tuple: return tuple(len(g) for g in entry.groups) def _equivalent_places(result: BandUnfolding, positions: set) -> list: """Where the path points of ``positions`` lie: whole legs (``'P-N leg'``) and vertices.""" path = result.child.path places, used = [], set() for a, b, la, lb in path.legs: span = set(range(a, b + 1)) if span <= positions: places.append(f"{la}-{lb} leg") used |= span for pos in path.vertices: label = path.labels[pos] if pos in positions: used.add(pos) if label not in places: places.append(label) rest = len(positions - used) if rest: places.append(f"{rest} other point{'s' if rest != 1 else ''}") return places def _checks(result: BandUnfolding, max_sum_dev, norm_range, copies, child_ops) -> dict: """Sum rule, copies of a k point, symmetry transport between equivalent path points, mixed levels (each distinct K once).""" checks = { "sum_rule_max_deviation": float(max_sum_dev), "norm_min": float(norm_range[0]), "norm_max": float(norm_range[1]), } Mf = result.M.astype(float) # copies of the same K (also K + G0): the level weights must agree once the image columns # are matched (for K + G0 the images come in another order) worst_copy, n_copy = 0.0, 0 for isp in result.spins: for ik, same in copies.items(): ref = result.unfolded[(isp, ik)] for j in same: if j == ik: continue other = result.unfolded[(isp, j)] if _group_signature(other) != _group_signature(ref): continue perm = [match_image(ref.images[i], other.K, Mf, result.offsets) for i in range(result.N)] if any(p is None for p in perm) or len(set(perm)) != result.N: if not np.allclose(other.K, ref.K, atol=MATCH_TOLERANCE): continue perm = list(range(result.N)) n_copy += 1 worst_copy = max(worst_copy, float(np.abs(other.group_weights[:, perm] - ref.group_weights).max())) checks["copies_compared"] = n_copy checks["copies_max_deviation"] = worst_copy # symmetry transport between distinct equivalent path points path_idx = [int(i) for i in result.child.path.indices] kpts = result.child.kpoints worst, pairs = 0.0, 0 seen = set() pk = kpts[path_idx] for a in path_idx: targets = np.einsum("oij,j->oi", child_ops[1:].astype(float), kpts[a]) equal = _same_k(pk[None, :, :], targets[:, None, :], MATCH_TOLERANCE) # (op, path) copy = _same_k(pk, kpts[a], MATCH_TOLERANCE) for o in np.flatnonzero(np.any(equal & ~copy[None, :], axis=1)): R = child_ops[1 + o] hits = [path_idx[b] for b in np.flatnonzero(equal[o] & ~copy)] for b in hits[:1]: key = (min(a, b), max(a, b)) if key in seen: continue seen.add(key) for isp in result.spins: ea, eb = result.unfolded[(isp, a)], result.unfolded[(isp, b)] if _group_signature(ea) != _group_signature(eb): continue perm = [] for i in range(result.N): try: q = transport_image(ea.images[i], R, Mf) except ValueError: perm.append(None) continue perm.append(match_image(q, kpts[b], Mf, result.offsets)) if any(p is None for p in perm): continue pairs += 1 worst = max(worst, float(np.abs(eb.group_weights[:, perm] - ea.group_weights).max())) checks["transport_pairs"] = pairs checks["transport_max_deviation"] = worst # mixed levels: every distinct K once; those at k points whose images are exchanged by a # child operation (or time reversal) have shares fixed by symmetry rotations = _parent_rotations(child_ops, result.M) mixed = total = mixed_equivalent = 0 equivalent_k = [] one_class = True for isp in result.spins: for entry in result.distinct_path_entries(isp): shares = entry.group_weights / entry.level_sizes[:, None] is_mixed = np.any((shares > MIXED[0]) & (shares < MIXED[1]), axis=1) total += len(shares) mixed += int(np.sum(is_mixed)) classes = _image_classes(entry, rotations) if any(len(c) > 1 for c in classes): mixed_equivalent += int(np.sum(is_mixed)) one_class = one_class and len(classes) == 1 if isp == result.spins[0]: equivalent_k.append(entry.K) positions = {p for p, k in enumerate(result.child.path.kpoints) if any(_same_k(k, e, MATCH_TOLERANCE) for e in equivalent_k)} checks["levels"] = total checks["mixed_levels"] = mixed checks["mixed_levels_equivalent"] = mixed_equivalent checks["equivalent_places"] = _equivalent_places(result, positions) checks["equivalent_all_images"] = bool(one_class) return checks # --------------------------------------------------------------------------- # terminal output # --------------------------------------------------------------------------- def _energy(value: float) -> str: return f"{round(float(value), 3) + 0.0:.3f}" def _bands_text(bands) -> str: bands = [int(b) + 1 for b in bands] if len(bands) == 1: return str(bands[0]) if bands == list(range(bands[0], bands[-1] + 1)): return f"{bands[0]}-{bands[-1]}" return ",".join(str(b) for b in bands) def _image_text(result: BandUnfolding, k) -> str: """ISO-IR name of a parent k (special points), else its fractions.""" from .phonon_unfold import _parent_point_name, point_rotations ops = getattr(result, "_parent_ops", None) if ops is None: ops = reciprocal_rotations(point_rotations(result.mapping.parent_cell)) result._parent_ops = ops if _is_special(k, ops): name = _parent_point_name(result.mapping, k) if name: return name return _compact(k) def _run_rows(run: VaspBandRun, label: str) -> list: lines = [] shown = _display_path(run.wavecar or run.poscar) pieces = [f"{run.formula},", f"{run.space_group},", f"{len(run.symbols)} atoms,", "primitive cell" if run.primitive else "NOT a primitive cell"] if 15 + len(shown) + 1 > OUTPUT_WIDTH: # a long path stands alone on its own line lines += _kv(label, ["WAVECAR" if run.wavecar else "POSCAR", "(path below):"] + pieces) lines.append(" " * 15 + shown) else: lines += _kv(label, [f"{shown}:"] + pieces) if run.wavecar is None: return lines spin = ("spin-orbit (vasp_ncl)" if run.spinor else "ISPIN = 2" if run.ispin == 2 else "ISPIN = 1") lines += _kv("", [f"{spin},", f"NBANDS = {run.nbands},", f"ENCUT = {run.encut:g} eV,", f"{run.nk} k points ({len(run.path.indices)} on the path),", f"{run.precision}"]) gap = run.gap edges = [f"VBM {run.vbm:.4f}" if run.vbm is not None else "VBM -", f"CBM {run.cbm:.4f}" if run.cbm is not None else "CBM -", "metallic" if run.metallic else f"gap {gap:.4f} eV" if gap is not None else "gap -", f"E_fermi {run.efermi:.4f} eV ({run.efermi_source})"] lines += _kv("", _commas(edges)) return lines def _setup_lines(result: BandUnfolding) -> list: m = result.mapping lines = ["", "* Unfolding setup *"] lines += _run_rows(result.child, "child") if result.parent is not None: lines += _run_rows(result.parent, "parent") else: lines += _kv("parent", ["structure only (--parent-poscar):", f"{_formula(list(m.parent_cell.symbols))},", f"{m.parent_space_group}", "(no parent eigenvalues: no overlay, no parent-path view)"]) n_eq = len(m.equivalent_settings) parent_file = result.parent_poscar or None if m.source == "--trans-mat": W, w = m.parent_operation lines += _kv("setting", [f"--trans-mat {_matrix_text(m.M)}:", "the crystod-group setting", _matrix_text(m.equivalent_settings[0])]) lines += _kv("", ["transformed by the parent operation", f"W = {_matrix_text(W)},", f"w = {_vec(w)}", f"({n_eq} equivalent settings)"]) else: lines += _kv("setting", ["crystod-group", "--supergroup-cif", _display_path(parent_file) if parent_file else "PARENT", "--subgroup-cif", _display_path(result.child.poscar), f"(1 of {n_eq} equivalent settings)"]) lines += _kv("M (rows)", [_matrix_text(result.M), f"(det M = N = {result.N};", "A_child = M A_parent, k_child = M k_parent;", "the form --trans-mat takes)"]) lines += _kv("origin shift", [f"p = {_vec(m.origin_shift)}", "(parent fractional; the weights do not depend on it)"]) st = m.strain lines += _kv("strain", ["lengths " + " ".join(f"{v:.2f}" for v in st["length_strain_percent"]) + " %,", f"volume {st['volume_strain_percent']:.2f} %", "(pseudo-parent cell inv(M) A_child against the parent);", f"frame rotation {st['rotation_deg']:.1f} deg"]) images = [f"g{i} = {name} {_vec(k)}" for i, (name, k) in enumerate(zip(result.image_names, result.offsets))] lines += _kv("images", _commas(images) + ["(child K unfolds onto k = M^-1 K + g_i)"]) zero_name = {"vbm": "the child VBM", "efermi": "the child E_fermi", "raw": "none (raw eigenvalues)", "value": "a given energy"}[result.zero] if result.parent is not None and result.separate_zero: word = {"vbm": "VBM", "efermi": "E_fermi"}.get(result.zero, "reference") pieces = [f"the child {word} = {result.zero_energy:.4f} eV for the child,", f"the parent {word} = {result.parent_zero_energy:.4f} eV for the parent", "(--separate-zero: no common zero)"] elif result.zero == "raw": pieces = ["none: raw eigenvalues" + (" for both runs" if result.parent is not None else "")] if result.parent is not None: pieces += ["(the child-parent offsets are the raw ones)"] else: pieces = [f"{zero_name} = {result.zero_energy:.4f} eV"] if result.parent is not None: pieces += ["for both runs (one common zero,", "so the child-parent offsets are" " the raw ones)"] lines += _kv("energy zero", pieces) if result.parent is not None and result.child.vbm is not None and result.parent.vbm is not \ None: d_vbm = result.child.vbm - result.parent.vbm d_ef = result.child.efermi - result.parent.efermi lines += _kv("", [f"raw offsets child - parent: VBM {d_vbm:+.4f} eV,", f"E_fermi {d_ef:+.4f} eV"]) lines += _kv("k points", ["child:"] + result.child.kpoints_source.rsplit(" (", 1)[:1] + [ "(" + result.child.kpoints_source.rsplit(" (", 1)[1]] if " (" in result.child.kpoints_source else ["child:", result.child.kpoints_source]) if result.parent is not None: text = result.parent.kpoints_source lines += _kv("", ["parent:"] + ([text.rsplit(" (", 1)[0], "(" + text.rsplit(" (", 1)[1]] if " (" in text else [text])) for note in result.notes: lines += _note(note) if result.parent is None: for note in result.symmetry_notes: lines += _note(note) return lines def _path_rows(key: str, text: str, tail: list) -> list: """A path text such as ``GM-X-P|N-M`` as block rows, broken after a ``-`` or ``|`` when it is longer than one row; ``tail`` (pieces) follows it.""" room = OUTPUT_WIDTH - 15 tokens, token, depth = [], "", 0 for char in text: # break points: a '-' or '|' outside the parentheses of a coordinate token += char depth += (char == "(") - (char == ")") if depth == 0 and char in "-|": tokens.append(token) token = "" tokens.append(token) chunks, current = [], "" for token in tokens: if current and len(current) + len(token) > room: chunks.append(current) current = token else: current += token chunks.append(current) lines = [] for n, chunk in enumerate(chunks[:-1]): lines += _kv(key if n == 0 else "", chunk) lines += _kv(key if len(chunks) == 1 else "", [chunks[-1]] + list(tail)) return lines def _vertex_groups(result: BandUnfolding) -> list: """Distinct child path vertices ``[(label, path positions), ...]`` in path order.""" path = result.child.path groups = [] for pos in path.vertices: label = path.labels[pos] for entry in groups: if entry[0] == label and _same_k(path.kpoints[entry[1][0]], path.kpoints[pos], MATCH_TOLERANCE): entry[1].append(pos) break else: groups.append((label, [pos])) return groups def _path_lines(result: BandUnfolding) -> list: path = result.child.path lines = ["", "* Child path *"] lines += _path_rows("path", path.path_text, [f"({path.source},", f"{len(path.indices)} points,", f"{len(path.legs)} legs)"]) lines += _kv("distances", "1/A without 2 pi, child reciprocal metric; no advance across '|'") rows = [] for a, b, la, lb in path.legs: rows.append((f"{la}-{lb}", str(b - a + 1), _vec(path.kpoints[a]), _vec(path.kpoints[b]))) w0 = max([8] + [len(r[0]) + 2 for r in rows]) w2 = max([22] + [len(r[2]) + 2 for r in rows]) lines.append(f"{'leg':<{w0}}{'points':>6} {'from (child)':<{w2}}to (child)") for leg, n, ka, kb in rows: lines.append(f"{leg:<{w0}}{n:>6} {ka:<{w2}}{kb}") lines.append("") vrows = [] for label, positions in _vertex_groups(result): K = path.kpoints[positions[0]] images = image_kpoints(K, result.M, result.offsets) names = [_image_text(result, k) for k in images] vrows.append((label, _vec(K), names, images)) w0 = max([8] + [len(r[0]) + 2 for r in vrows]) w1 = max([22] + [len(r[1]) + 2 for r in vrows]) lines.append(f"{'vertex':<{w0}}{'K (child)':<{w1}}parent images k = M^-1 K + g_i") for label, K_text, names, images in vrows: pieces = _commas([f"{n} {_vec(k)}" if not n.startswith("(") else _vec(k) for n, k in zip(names, images)]) lines += _fill(pieces, f"{label:<{w0}}{K_text:<{w1}}", " " * (w0 + w1)) named = [r for r in vrows if not any(n.startswith("(") for n in r[2])] if named: lines += _legend("special points: " + "; ".join(f"{r[0]} -> {', '.join(r[2])}" for r in named)) return lines def _coverage_lines(result: BandUnfolding) -> list: lines = ["", "* Parent path coverage *"] path = result.parent.path lines += _path_rows("parent path", path.path_text, [f"({path.source},", f"{len(path.indices)} points)"]) pieces = _commas([f"{leg} {c}/{n}" for leg, c, n, _pos in result.coverage]) lines += _kv("covered", pieces) images = ("its time-reversed -K (ISPIN = 2: no other child operation)" if result.child.ispin == 2 else "an image of it under the child point group or time reversal") lines += _legend( f"a parent path point k_p is covered when K = M k_p, or {images}, is a k point of the " "child run; covered points are exact (page 2 of the figure), the others are not sampled " "by the child run" ) for note in result.symmetry_notes: lines += _note(note) best = result.setting_coverage if best is not None: legs = ", ".join(f"{leg} {c}/{n}" for leg, c, n, _pos in best["coverage"]) lines += _note( f"another equivalent setting, --trans-mat {_matrix_text(best['M'])}, covers {legs} " f"({best['covered']} of {best['total']} parent path points, against " f"{best['this_setting']} in this setting); the images and weights are the same in " "every setting (the settings are orientation domains of the child, which sample " "different parent arms)." ) if any(c < n for _leg, c, n, _pos in result.coverage): lines += _note( "crystod --unfold-kpoints --parent-wavecar P --child-wavecar C writes a child KPOINTS " "(the child SCF mesh plus K = M k_p of the parent path) whose band run covers the " "whole parent path." ) return lines def _column_names(names: list) -> tuple: """``(column names, image texts)`` of a vertex table: the ISO-IR name of an image, or ``g<i>`` when the name is a fraction, long, or shared by another image.""" columns, texts = [], [] for i, name in enumerate(names): if name.startswith("(") or len(name) > 6 or names.count(name) > 1: columns.append(f"g{i}") texts.append(f"g{i} = {name}") else: columns.append(name) texts.append(name) return columns, texts def _chunks(n: int) -> list: """Image indices of the sub-tables: one table up to 4 images, else chunks of at most 4.""" if n <= TABLE_CHUNK: return [list(range(n))] count = -(-n // TABLE_CHUNK) size = -(-n // count) return [list(range(a, min(n, a + size))) for a in range(0, n, size)] def _cycles_text(perm: list) -> str: """``[1, 0]`` -> ``'g0 <-> g1'``; longer cycles ``'g0 -> g1 -> g2 -> g0'``.""" done, parts = set(), [] for start in range(len(perm)): if start in done or perm[start] == start: continue cycle, i = [start], perm[start] while i != start: cycle.append(i) i = perm[i] done |= set(cycle) if len(cycle) == 2: parts.append(f"g{cycle[0]} <-> g{cycle[1]}") else: parts.append(" -> ".join(f"g{i}" for i in cycle + [start])) return "images permuted " + ", ".join(parts) if parts else "images in the same order" def _equivalent_vertex(result: BandUnfolding, rotations, earlier: list, entry: KUnfolded): """``(label, permutation text)`` of an earlier vertex whose K is carried onto this one by a child operation or time reversal (K and K + G0 too), else None.""" for label, other in earlier: for R, Rp in rotations: if Rp is None: continue d = np.asarray(R, float) @ other.K - entry.K if np.abs(d - np.rint(d)).max() >= MATCH_TOLERANCE: continue perm = _image_permutation(other.images, entry.images, Rp) if perm is not None: return label, _cycles_text(perm) return None def _table_lines(result: BandUnfolding) -> list: lines = ["", "* Unfolded levels at the child path vertices *"] lo, hi = result.table_window rotations = _parent_rotations(result.child_ops if result.child_ops is not None else reciprocal_rotations(np.zeros((0, 3, 3))), result.M) parent_on = result.parent is not None for isp in result.spins: if result.child.ispin == 2: lines.append(f" spin {'up' if isp == 0 else 'down'}") earlier = [] for label, positions in _vertex_groups(result): ik = int(result.child.path.indices[positions[0]]) entry = result.unfolded[(isp, ik)] same = _equivalent_vertex(result, rotations, earlier, entry) if same is not None: lines.append("") lines += _fill([f"child {label} (k#{ik + 1}):", f"equivalent to {same[0]}", f"({same[1]});", "see the summary"], " ", " ") continue earlier.append((label, entry)) copies = [int(result.child.path.indices[p]) + 1 for p in positions[1:]] names = [_image_text(result, k) for k in entry.images] columns, images = _column_names(names) head = [f"child {label} {_vec(entry.K)}", f"(k#{ik + 1}" + ( f", copies k#{', '.join(str(c) for c in copies)})" if copies else ")") + ";", "images"] + _commas(images) lines.append("") lines += _fill(head, " ", " ") energies = entry.level_energies - result.zero_energy shares = entry.group_weights / entry.level_sizes[:, None] chunks = _chunks(result.N) for n_chunk, shown in enumerate(chunks): last = n_chunk == len(chunks) - 1 if n_chunk: lines.append("") header = f" {result.zero_text + ' (eV)':>13}{'deg':>5} {'bands':<9}" for i in shown: header += f"{'w(' + columns[i] + ')':>10}" if parent_on and last: header += f" {'parent':>9}{'E_par':>9}{'dE':>8}" lines.append(header) for lv, energy in enumerate(energies): if not lo <= energy <= hi: continue row = (f" {_energy(energy):>13}{entry.level_sizes[lv]:>5} " f"{_bands_text(entry.groups[lv]):<9}") for i in shown: row += f"{shares[lv, i]:>10.3f}" if parent_on and last: pure = np.flatnonzero(shares[lv] >= PURE) j, e_par = (None, None) if len(pure): j, e_par = result.nearest_parent(ik, int(pure[0]), float(energy), isp) if e_par is not None: row += f" {columns[int(pure[0])]:>9}{_energy(e_par):>9}" row += f"{energy - e_par:>+8.3f}" else: row += f" {'-':>9}{'-':>9}{'-':>8}" lines.append(row) classes = _image_classes(entry, rotations) if any(len(c) > 1 for c in classes): if len(classes) == 1: text = (f"the images are exchanged by a child operation (or time reversal) " f"at this K, so every share is 1/{result.N}") else: groups = "; ".join(", ".join(f"g{i}" for i in c) for c in classes if len(c) > 1) text = (f"the images {groups} are exchanged by a child operation (or time " "reversal) at this K, so their shares are equal") spread = max(float(np.ptp(shares[:, c], axis=1).max()) for c in classes) if spread > 0.01: text += ("; a level that shows other shares is one band of a degenerate pair " "split by more than --degeneracy-tol, which a larger " "--degeneracy-tol joins") lines += _legend(text) lines.append("") text = (f"levels with {lo:g} <= {result.zero_text} <= {hi:g} eV; w(k) = W_k / deg, the share " "of the level's spectral weight on the parent image k (the level carries deg x w; " "W = Re Tr(S^-1 P_k) over the deg bands, invariant under any mixing of the " "degenerate bands); ") if result.parent is not None: text += ("parent: the image (share >= 0.9) whose k is a k point of the parent run (any " "arm, time reversal), E_par its nearest parent level, dE = E - E_par") lines += _legend(text.rstrip("; ")) if result.window is None: top = (f"up to {TABLE_TOP:g} eV" if hi >= TABLE_TOP else f"up to the figure's top, below {TABLE_TOP:g} eV") lines += _note(f"the tables list {lo:g} .. {hi:g} eV around the zero (from just below the " f"valence block at or below the zero, {top}); --window EMIN EMAX chooses " "the range (and the figure's).") return lines def _summary_lines(result: BandUnfolding, pages: int | None) -> list: c = result.checks lines = ["", "* Unfolding summary *"] n_path = len(result.child.path.indices) n_all = len({ik for (_s, ik) in result.unfolded}) lines += _kv("k points", [f"{n_all} child k points unfolded ({n_path} on the path" + (", the weighted mesh too" if result.all_kpoints else "") + f"), {len(result.spins)} spin channel" + ("s" if len(result.spins) != 1 else "")]) lines += _kv("sum rule", [f"max |sum_i w_i - 1| = {c['sum_rule_max_deviation']:.1e}", f"(<= {SUM_RULE_TOLERANCE:g});", f"pseudo norms sum |C|^2 {c['norm_min']:.3f} .. {c['norm_max']:.3f}", "(each band normalised; PAW one-centre part neglected)"]) if c["copies_compared"]: n_copy = c["copies_compared"] lines += _kv("copies", [f"{n_copy} repeated k point{'s' if n_copy != 1 else ''} " "(same K or K + G,", "other index; image columns matched):", f"max |dW| = {c['copies_max_deviation']:.1e}"]) else: lines += _kv("copies", "none on the path") if c["transport_pairs"]: lines += _kv("symmetry", [f"{c['transport_pairs']} pairs of equivalent child path points", "(K' = R K, R a child operation or time reversal):", f"max |W(K') - W_transported(K)| = " f"{c['transport_max_deviation']:.1e}"]) else: lines += _kv("symmetry", ["pairs of equivalent child path points", "(K' = R K, R a child operation or time reversal):", "none on the path"]) share = c["mixed_levels"] / c["levels"] if c["levels"] else 0.0 pieces = [f"{c['mixed_levels']} of {c['levels']} path levels", f"({100 * share:.1f} %) have an image share in (0.1, 0.9)", "(repeated k points counted once)"] if c.get("mixed_levels_equivalent"): fixed = (f"shares fixed at 1/{result.N} there" if c.get("equivalent_all_images") else "shares equal within each class of exchanged images there") pieces[-1] += ";" pieces += [f"{c['mixed_levels_equivalent']} of them at k points whose images are", "equivalent under the child symmetry", f"({fixed}: {', '.join(c['equivalent_places'])})"] lines += _kv("mixed levels", pieces) a = result.alignment if result.parent is not None: if a.get("n"): lo, hi = a["window"] lines += _kv("alignment", [f"E_child - E_parent over {a['n']} pure levels", "(share >= 0.9, image a parent k point,", "repeated k points counted once)", f"in {lo:g} .. {hi:g} eV:", f"median {a['median']:+.4f},", f"rms {a['rms']:.4f},", f"max |dE| {a['max_abs']:.4f} eV"]) b = result.alignment_all if b.get("n"): lines += _kv("", [f"all {b['n']} such levels below the completeness limit:", f"median {b['median']:+.4f},", f"rms {b['rms']:.4f},", f"max |dE| {b['max_abs']:.4f} eV"]) else: lines += _kv("alignment", "no pure child level at a k point of the parent run") nb_c = result.child.nbands lines += _kv("completeness", [f"{nb_c} child bands = {nb_c / result.N:g} bands per parent " "cell;", "the unfolded spectrum is complete below", f"{result.zero_text} = {result.top_complete:.3f} eV", "(the lowest top band of the child path)"]) t = result.timings pieces = [f"read {t.get('read', 0):.2f} s,", f"setting {t.get('mapping', 0):.2f} s,", f"unfolding {t.get('unfolding', 0):.2f} s,", f"matching {t.get('matching', 0):.2f} s"] if "output" in t: pieces[-1] += "," pieces.append(f"files {t['output']:.2f} s") lines += _kv("timings", pieces) lo, hi = result.figure_window drawn = not result.figure_error and pages != 0 # pages None: the caller draws it if result.window is None and drawn: w0, w1 = result.default_window()["whole"] lines += _note(f"the figure shows {lo:g} .. {hi:g} eV (the valence block at or below the " "zero and the complete range above it; the .dat and .yaml files hold " "every level); --window EMIN EMAX draws another range, e.g. --window " f"{w0} {w1} the whole spectrum.") if hi > result.top_complete: lines += _note(f"above {result.zero_text} = {result.top_complete:.3f} eV the child run " "has fewer than N times the parent's bands at some k, so the unfolded " "spectrum there is incomplete" + ("; the figure shades that region." if drawn else ".")) if result.figure_error: lines += _note(f"the figure was not drawn ({result.figure_error}).") elif pages == 0 and result.N > MAX_FIGURE_IMAGES: lines += _note(f"no figure: {result.N} images (> {MAX_FIGURE_IMAGES}) do not fit a page.") return lines
[docs] def format_band_unfolding(result: BandUnfolding, pages: int | None = None) -> list: """The terminal report of ``crystod --unfold`` (lines of at most 100 ASCII columns).""" lines = _setup_lines(result) + _path_lines(result) if result.parent is not None: lines += _coverage_lines(result) lines += _table_lines(result) + _summary_lines(result, pages) return lines
# --------------------------------------------------------------------------- # files # --------------------------------------------------------------------------- def _nan(value) -> str: return "nan" if value is None else f"{value:.6f}" def write_dat(result: BandUnfolding, path: str) -> str: """gnuplot-friendly table: one dataset per (spin,) image, then the parent-path view. Dataset ``index i`` (separated by two blank lines) holds image g_i: columns ``k_index distance kx ky kz pkx pky pkz band energy weight group_weight level_size parent_energy``, a blank line after every k point. The last dataset(s) hold the parent path view. """ r = result M = r.M head = [ "# crystod --unfold: electronic band unfolding (Popescu-Zunger spectral weights of the " "child plane-wave coefficients)", f"# child {r.child.wavecar} {r.child.formula} {r.child.space_group}", ] if r.parent is not None: head.append(f"# parent {r.parent.wavecar} {r.parent.formula} {r.parent.space_group}") head += [ f"# M (rows) {_matrix_text(M)} (A_child = M A_parent, k_child = M k_parent), N = {r.N}", "# images: " + " ".join(f"{i} {n} {_vec(k)}" for i, (n, k) in enumerate(zip(r.image_names, r.offsets))) + " (k = M^-1 K + g_i)", f"# energy zero: {r.zero} = {r.zero_energy:.6f} eV (child)" + ("" if r.parent is None else f"; parent energies relative to {r.parent_zero_energy:.6f} eV"), f"# degeneracy tolerance {r.degeneracy_tol:g} eV; weight = per-band w_i (gauge dependent " "inside a degenerate level), group_weight = level weight W_i = Re Tr(S^-1 P_i) " "(0..level_size; invariant under any mixing of the degenerate bands)", "# columns: k_index distance kx ky kz pkx pky pkz band energy weight group_weight " "level_size parent_energy", "# k_index 1-based in the child WAVECAR; distance along the child path (1/A without " "2 pi; nan off the path); kx..kz child fractional; pkx..pkz the image (parent " "fractional, reduced); energy = E - zero (eV); parent_energy: nearest parent level at " "the image k when it is a parent k point (any arm), else nan", ] spins = r.spins order = [(isp, i) for isp in spins for i in range(r.N)] head.append("# datasets (gnuplot index): " + ", ".join( f"{d} = image {r.image_names[i]}" + (f" spin {'up' if isp == 0 else 'down'}" if r.child.ispin == 2 else "") for d, (isp, i) in enumerate(order))) if r.parent is not None: head.append( f"# datasets {len(order)}.. : parent path view (one per spin channel), columns: " "pk_index distance pkx pky pkz child_k_index Kx Ky Kz band energy weight " "group_weight level_size image") out = list(head) cpath = r.child.path dist = {int(ik): float(d) for ik, d in zip(cpath.indices, cpath.distances)} ks = list(cpath.indices) if not r.all_kpoints else ( list(cpath.indices) + [ik for ik in range(r.child.nk) if ik not in dist]) for d, (isp, i) in enumerate(order): if d: out.append("") # with the blank line after the last k: two, the end of a dataset out.append(f"# image {i} {r.image_names[i]}" + (f" spin {'up' if isp == 0 else 'down'}" if r.child.ispin == 2 else "")) for ik in ks: e = r.unfolded[(isp, int(ik))] level = e.band_level() energies = e.energies - r.zero_energy lev_e = e.level_energies - r.zero_energy j = r.child_matches.get((int(ik), i)) par = r.parent_energies(j, isp) if j is not None else None for b in range(len(energies)): lv = level[b] pe = None if par is not None: pe = float(par[np.argmin(np.abs(par - lev_e[lv]))]) d = dist.get(int(ik)) out.append( f"{int(ik) + 1:5d} {('nan' if d is None else f'{d:.6f}'):>10} " f"{e.K[0]:10.7f} {e.K[1]:10.7f} {e.K[2]:10.7f} " f"{e.images[i][0]:10.7f} {e.images[i][1]:10.7f} {e.images[i][2]:10.7f} " f"{b + 1:4d} {energies[b]:11.5f} {e.weights[b, i]:9.6f} " f"{e.group_weights[lv, i]:9.6f} {len(e.groups[lv]):3d} {_nan(pe):>11}" ) out.append("") if r.parent is not None: ppath = r.parent.path for isp in spins: out += ["", "# parent path view" + ( f" spin {'up' if isp == 0 else 'down'}" if r.child.ispin == 2 else "")] for pos, pj, j, i, _R in r.parent_view[isp]: e = r.unfolded[(isp, j)] level = e.band_level() energies = e.energies - r.zero_energy kp = ppath.kpoints[pos] for b in range(len(energies)): lv = level[b] out.append( f"{pj + 1:5d} {ppath.distances[pos]:10.6f} {kp[0]:10.7f} {kp[1]:10.7f} " f"{kp[2]:10.7f} {j + 1:5d} {e.K[0]:10.7f} {e.K[1]:10.7f} {e.K[2]:10.7f} " f"{b + 1:4d} {energies[b]:11.5f} {e.weights[b, i]:9.6f} " f"{e.group_weights[lv, i]:9.6f} {len(e.groups[lv]):3d} {i:3d}" ) out.append("") with open(path, "w") as handle: handle.write("\n".join(out) + "\n") return path def _r(value, digits: int = 6): return None if value is None else round(float(value), digits) + 0.0 def _run_dict(run: VaspBandRun | None) -> dict | None: if run is None: return None data = { "directory": run.directory, "wavecar": run.wavecar, "poscar": run.poscar, "formula": run.formula, "space_group": run.space_group, "primitive": run.primitive, "n_atoms": len(run.symbols), } if run.wavecar is not None: data.update({ "nkpts": run.nk, "nbands": run.nbands, "ispin": run.ispin, "spinor": run.spinor, "encut": run.encut, "vbm": _r(run.vbm), "cbm": _r(run.cbm), "gap": _r(run.gap), "metallic": run.metallic, "efermi": _r(run.efermi), "efermi_source": run.efermi_source, "kpoints_file": run.kpoints_file, "kpoints_source": run.kpoints_source if run.kpoints_file is None else f"{run.kpoints_file} ({run.kpoints_source.rsplit('(', 1)[-1]}", "path": run.path.path_text, "path_labels": [{"index": int(run.path.indices[p]) + 1, "label": run.path.labels[p], "k": [_r(v, 7) for v in run.path.kpoints[p]]} for p in run.path.vertices], }) return data def _result_dict(r: BandUnfolding) -> dict: from . import __version__ m = r.mapping data = { "crystod_version": __version__, "mode": "crystod --unfold (electronic band unfolding)", "child": _run_dict(r.child), "parent": _run_dict(r.parent), "setting": { "M": [[int(v) for v in row] for row in r.M], "N": r.N, "origin_shift": [_r(v) for v in m.origin_shift], "source": m.source, "equivalent_settings": len(m.equivalent_settings), "frame_rotation_deg": _r(m.strain["rotation_deg"], 4), "volume_strain_percent": _r(m.strain["volume_strain_percent"], 4), }, "images": [{"index": i, "name": n, "g": [_r(v) for v in k]} for i, (n, k) in enumerate(zip(r.image_names, r.offsets))], "energy_zero": r.zero, "zero_energy": _r(r.zero_energy), "parent_zero_energy": _r(r.parent_zero_energy), "separate_zero": r.separate_zero, "degeneracy_tol": r.degeneracy_tol, "weight_min": r.weight_min, "window": list(r.window) if r.window else None, "figure_window": [float(v) for v in r.figure_window], "table_window": [float(v) for v in r.table_window], "complete_below": _r(r.top_complete), "kpoints": [], "coverage": [{"leg": leg, "covered": c, "points": n, "positions": list(pos)} for leg, c, n, pos in r.coverage], "best_setting": None if r.setting_coverage is None else { "M": [[int(v) for v in row] for row in r.setting_coverage["M"]], "covered": r.setting_coverage["covered"], "points": r.setting_coverage["total"], "coverage": [{"leg": leg, "covered": c, "points": n} for leg, c, n, _pos in r.setting_coverage["coverage"]]}, "alignment": {k: (_r(v) if isinstance(v, float) else v) for k, v in r.alignment.items()}, "alignment_all_levels": {k: (_r(v) if isinstance(v, float) else v) for k, v in r.alignment_all.items()}, "checks": {k: (float(f"{v:.3e}") if isinstance(v, float) else v) for k, v in r.checks.items()}, } path = r.child.path dist = {int(ik): float(d) for ik, d in zip(path.indices, path.distances)} for (isp, ik), e in sorted(r.unfolded.items(), key=lambda kv: (kv[0][0], kv[0][1])): lev_e = e.level_energies - r.zero_energy entry = { "k_index": ik + 1, "spin": (["up", "down"][isp] if r.child.ispin == 2 else None), "k": [_r(v, 7) for v in e.K], "on_path": ik in dist, "distance": _r(dist.get(ik)), "images": {n: [_r(v) for v in k] for n, k in zip(r.image_names, e.images)}, "parent_k_index": {r.image_names[i]: (r.child_matches[(ik, i)] + 1 if (ik, i) in r.child_matches else None) for i in range(r.N)}, "energies": [_r(v, 5) for v in e.energies - r.zero_energy], "weights": {n: [_r(v) for v in e.weights[:, i]] for i, n in enumerate(r.image_names)}, "levels": { "first_band": [int(g[0]) + 1 for g in e.groups], "size": [len(g) for g in e.groups], "energy": [_r(v, 5) for v in lev_e], "group_weights": {n: [_r(v) for v in e.group_weights[:, i]] for i, n in enumerate(r.image_names)}, }, } data["kpoints"].append(entry) if r.parent is not None: data["parent_view"] = [ {"spin": (["up", "down"][isp] if r.child.ispin == 2 else None), "parent_k_index": pj + 1, "distance": _r(r.parent.path.distances[pos]), "child_k_index": j + 1, "image": r.image_names[i], "operation": [[int(v) for v in row] for row in R]} for isp in r.spins for pos, pj, j, i, R in r.parent_view[isp] ] return data def write_yaml(result: BandUnfolding, path: str) -> str: """Write the YAML file (the layout of :meth:`BandUnfolding.to_dict`).""" from .extract_irrep import _yaml_lines data = result.to_dict() lines = ["# crystod --unfold: electronic band unfolding (energies in eV relative to " "energy_zero; weights are shares of the band's plane-wave norm)"] for keys in (("crystod_version", "mode"), ("child", "parent"), ("setting", "images"), ("energy_zero", "zero_energy", "parent_zero_energy", "separate_zero", "degeneracy_tol", "weight_min", "window", "figure_window", "table_window", "complete_below"), ("coverage", "best_setting", "alignment", "alignment_all_levels", "checks"), ("kpoints",), ("parent_view",)): block = {k: data[k] for k in keys if k in data} if block: lines.extend(_yaml_lines(block)) lines.append("") with open(path, "w") as handle: handle.write("\n".join(lines)) return path # --------------------------------------------------------------------------- # --unfold-kpoints # --------------------------------------------------------------------------- @dataclass class KpointsUnfold: """A child KPOINTS whose band run covers the parent path (:func:`unfold_kpoints`).""" path: str lines: list mesh_points: int path_points: int legs: list parent_path: str source: str mapping: object notes: list = field(default_factory=list) def _label_for_file(label: str) -> str: return "Gamma" if label == "GM" else label
[docs] def unfold_kpoints( child, parent, *, child_cell: str | None = None, parent_cell: str | None = None, trans_mat=None, npoints: int = 51, output: str = "KPOINTS_unfold", tolerance: float = MAPPING_TOLERANCE, symprec: float = SYMPREC, write: bool = True, ) -> KpointsUnfold: """A child KPOINTS with the parent path mapped to K = M k_p. The child's weighted SCF points are copied verbatim (from its KPOINTS, else its IBZKPT), then the parent path (the zero-weight labelled points of the parent KPOINTS; without them seekpath's path with ``npoints`` points per leg) follows as zero-weight points with ``! K.n LABEL SEP`` comments carrying the parent labels. Raises: SystemExit: Every user error as one ``ERROR:`` line. """ from .phonon_unfold import find_parent_mapping, make_parent_path from .vasp_io import read_kpoints, resolve_vasp_file child_dir, _ = _resolve_run(child, "child", need_wavecar=False) parent_dir, _ = _resolve_run(parent, "parent", need_wavecar=False) trans_mat = _trans_mat_matrix(trans_mat) c_cell, c_poscar = _read_cell(child_dir, child_cell, "child") p_cell, p_poscar = _read_cell(parent_dir, parent_cell, "parent") def scale_of(directory, poscar): own = os.path.join(directory, "POSCAR") return _poscar_scale(own if os.path.isfile(own) else poscar) try: with contextlib.redirect_stdout(io.StringIO()), warnings.catch_warnings(): warnings.simplefilter("ignore") mapping = find_parent_mapping(c_poscar, p_poscar, child_cell=c_cell, parent_cell=p_cell, trans_mat=trans_mat, tolerance=tolerance) except SystemExit: raise except Exception as exc: # noqa: BLE001 raise SystemExit("ERROR: the child and parent structures cannot be related: " f"{type(exc).__name__}: {' '.join(str(exc).split())}") from None notes = [] M = mapping.M.astype(float) # the parent path p_kpoints = os.path.join(parent_dir, "KPOINTS") kfile = None if resolve_vasp_file(p_kpoints): try: kfile = read_kpoints(p_kpoints, lattice=np.asarray(p_cell.cell, float), scale=scale_of(parent_dir, p_poscar)) except ValueError: kfile = None points = labels = seps = None if kfile is not None and kfile.mode != "automatic": mask = kfile.path_mask sel = np.flatnonzero(mask) if any(kfile.labels[i] for i in sel) or kfile.mode == "line": points = kfile.kpoints[sel] labels = [kfile.labels[i] for i in sel] seps = [kfile.separators[i] for i in sel] source = [_display_path(p_kpoints), "(zero-weight labelled points)" if len(sel) < len(mask) else f"(labelled points, {kfile.mode})"] if points is None: ppath = make_parent_path(mapping, npoints=npoints) points = ppath.kpoints labels = [None] * len(points) seps = [None] * len(points) starts = np.flatnonzero(np.r_[True, np.diff(ppath.segment_index) != 0]) ends = np.r_[starts[1:] - 1, len(points) - 1] for seg, (a, b) in enumerate(zip(starts, ends)): leg_a, leg_b = ppath.leg_labels[seg] labels[a], labels[b] = leg_a, leg_b seps[a] = "-" seps[b] = None if b == len(points) - 1 else ( "-" if ppath.connections[seg] else "|") source = ["seekpath path of the parent", f"({npoints} points per leg)"] notes.append("NOTE: the parent KPOINTS has no labelled path; the seekpath path of the " "parent primitive cell is used.") # the child's weighted points, verbatim mesh_lines = [] c_kpoints = os.path.join(child_dir, "KPOINTS") ckfile = None if resolve_vasp_file(c_kpoints): try: ckfile = read_kpoints(c_kpoints, lattice=np.asarray(c_cell.cell, float), scale=scale_of(child_dir, c_poscar)) except ValueError: ckfile = None if ckfile is not None and ckfile.mode == "explicit" and ckfile.coordinates == "reciprocal": mesh_lines = [line.rstrip() for line, w in zip(ckfile.lines, ckfile.weights) if w != 0] mesh_source = _display_path(c_kpoints) else: ibz = os.path.join(child_dir, "IBZKPT") ibzfile = None if os.path.isfile(ibz): try: ibzfile = read_kpoints(ibz) except ValueError: ibzfile = None if ibzfile is not None and ibzfile.mode == "explicit" and \ ibzfile.coordinates == "reciprocal": mesh_lines = [line.rstrip() for line, w in zip(ibzfile.lines, ibzfile.weights) if w != 0] mesh_source = _display_path(ibz) else: mesh_source = None if not mesh_lines: notes.append("NOTE: no weighted SCF points in the child KPOINTS or IBZKPT: the file " "lists the path only (weight 1 each), for a non-self-consistent ICHARG = 11 " "run on the child's CHGCAR.") # the mapped path path_lines = [] count = 0 legs = [] last_label = last_sep = last_k = None for k, label, sep in zip(points, labels, seps): K = _snap_rational(M @ np.asarray(k, float)) K = np.where(np.abs(K) < 5e-8, 0.0, K) line = f"{K[0]:10.7f} {K[1]:10.7f} {K[2]:10.7f} {0 if mesh_lines else 1}" if label: count += 1 line += f" ! K.{count} {_label_for_file(label)} {sep if sep else 'X'}" repeated = (last_label == label and last_k is not None and np.allclose(last_k, k, atol=1e-8)) if last_label is not None and not repeated: # a zero-length leg is no leg legs.append(last_label + ("|" if last_sep == "|" else "-") + label) last_label, last_sep, last_k = label, sep, np.asarray(k, float) path_lines.append(line) if path_lines and labels[-1] is None: path_lines[-1] += " ! end X" total = len(mesh_lines) + len(path_lines) text = [f"crystod --unfold-kpoints: child mesh + parent path K = M k_p, M = " f"{_matrix_text(mapping.M)}", f"\t{total}", "Reciprocal lattice"] text += mesh_lines + path_lines if write: folder = os.path.dirname(output) if folder and not os.path.isdir(folder): raise SystemExit(f"ERROR: the directory '{folder}' of -o does not exist.") with open(output, "w") as handle: handle.write("\n".join(text) + "\n") path_text = "-".join(lab for lab in labels if lab) result = KpointsUnfold(path=output, lines=text, mesh_points=len(mesh_lines), path_points=len(path_lines), legs=legs, parent_path=path_text, source=source, mapping=mapping, notes=notes) result.mesh_source = mesh_source return result
def format_kpoints_unfold(result: KpointsUnfold, existed: bool) -> list: m = result.mapping lines = ["", "* Child KPOINTS for unfolding *"] lines += _kv("setting", [f"M = {_matrix_text(m.M)}", f"(det {m.N}; {m.child_space_group} " f"child, {m.parent_space_group} parent;", f"{m.source}, 1 of {len(m.equivalent_settings)} equivalent " "settings)"]) lines += _kv("parent path", list(result.source)) legs = [leg for leg in result.legs if "|" not in leg] lines += _kv("legs", _commas(legs) if legs else ["-"]) mesh = ([f"{result.mesh_points} weighted SCF point{'s' if result.mesh_points != 1 else ''}" " copied from", f"{result.mesh_source},"] if result.mesh_points else ["no weighted points,"]) weight = "zero-weight points" if result.mesh_points else "points (weight 1)" lines += _kv("points", mesh + [f"{result.path_points} {weight} K = M k_p", "(labels: the parent's)"]) for note in result.notes: lines += _note(note) lines += ["", "* Output files *"] lines += _fill([f"Child KPOINTS {'OVERWRITTEN' if existed else 'written'}:", result.path], " ", " ") lines += _note("run the child band calculation with this KPOINTS (same INCAR, LWAVE = " ".TRUE.); crystod --unfold on that run then covers the whole parent path.") return lines # --------------------------------------------------------------------------- # command line (the dispatch target of crystod --unfold) # --------------------------------------------------------------------------- def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="crystod --unfold", description="Electronic band unfolding of a child VASP run onto the zone of its parent " "run, from the two WAVECARs.", ) parser.add_argument("--child-wavecar", required=True, metavar="PATH") parser.add_argument("--parent-wavecar", default=None, metavar="PATH") parser.add_argument("--child-poscar", default=None, metavar="FILE") parser.add_argument("--parent-poscar", default=None, metavar="FILE") parser.add_argument("--trans-mat", nargs=9, default=None, metavar="T") parser.add_argument("--zero", default="vbm") parser.add_argument("--separate-zero", action="store_true") parser.add_argument("--spin", choices=SPIN_CHOICES, default="both") parser.add_argument("--window", nargs=2, type=float, default=None) parser.add_argument("--degeneracy-tol", type=float, default=None) parser.add_argument("--weight-min", type=float, default=None) parser.add_argument("--all-kpoints", action="store_true") parser.add_argument("--tolerance", type=float, default=None) parser.add_argument("--kpoints-only", action="store_true") parser.add_argument("--npoints", type=int, default=51) parser.add_argument("--output", default=None) return parser def main(argv=None) -> int: """``crystod --unfold`` / ``crystod --unfold-kpoints`` (argv built by crystod.cli.main).""" import sys args = build_parser().parse_args(list(sys.argv[1:] if argv is None else argv)) tolerance = MAPPING_TOLERANCE if args.tolerance is None else float(args.tolerance) trans_mat = _trans_mat_matrix(args.trans_mat) if args.kpoints_only: if args.parent_wavecar is None: raise SystemExit("ERROR: --unfold-kpoints needs --parent-wavecar (the parent run " "directory, whose KPOINTS path is mapped).") output = args.output or "KPOINTS_unfold" if os.path.isdir(output): output = os.path.join(output, "KPOINTS_unfold") existed = os.path.isfile(output) result = unfold_kpoints(args.child_wavecar, args.parent_wavecar, child_cell=args.child_poscar, parent_cell=args.parent_poscar, trans_mat=trans_mat, npoints=args.npoints, output=output, tolerance=tolerance) print("\n".join(format_kpoints_unfold(result, existed))) return 0 from .phonon_unfold import _output_prefix prefix = _output_prefix(args.output, "band_unfold", (".pdf", ".dat", ".yaml")) folder = os.path.dirname(prefix) if folder and not os.path.isdir(folder): raise SystemExit(f"ERROR: the directory '{folder}' of -o does not exist.") result = unfold_bands( args.child_wavecar, args.parent_wavecar, child_cell=args.child_poscar, parent_cell=args.parent_poscar, trans_mat=trans_mat, zero=args.zero, separate_zero=args.separate_zero, spin=args.spin, degeneracy_tol=args.degeneracy_tol, all_kpoints=args.all_kpoints, weight_min=args.weight_min, window=args.window, tolerance=tolerance, ) files = {"pdf": f"{prefix}.pdf", "dat": f"{prefix}.dat", "yaml": f"{prefix}.yaml"} existed = {key: os.path.isfile(path) for key, path in files.items()} t0 = time.perf_counter() try: result.write_dat(files["dat"]) result.write_yaml(files["yaml"]) except OSError as exc: raise SystemExit(f"ERROR: could not write the output files: {exc}") from None pages = 0 if result.N <= MAX_FIGURE_IMAGES: try: pages = result.plot(files["pdf"]) except Exception as exc: # noqa: BLE001 - the report and the files stand without it pages = 0 result.figure_error = f"{type(exc).__name__}: {' '.join(str(exc).split())}" with contextlib.suppress(OSError): # no half-written PDF is left behind os.remove(files["pdf"]) result.timings["output"] = time.perf_counter() - t0 result.files = files for line in format_band_unfolding(result, pages): print(line) lines = ["", "* Output files *"] for key, label in (("pdf", f"Band unfolding ({pages} page{'s' if pages != 1 else ''})"), ("dat", "Band unfolding (gnuplot table)"), ("yaml", "Band unfolding (YAML)")): if key == "pdf" and pages == 0: continue lines += _fill([f"{label} {'OVERWRITTEN' if existed[key] else 'written'}:", files[key]], " ", " ") print("\n".join(lines)) return 0 if __name__ == "__main__": raise SystemExit(main())