Source code for crystod.crystal_orbital_spgrep

"""
__author__ = "Hiroki Koiso, Yasuhide Mochizuki"
__copyright__ = "Copyright 2026, Mochizuki group"
__version__ = "3.1"
__maintainer__ = "Yasuhide Mochizuki"
__email__ = "mochizuki@rs.tus.ac.jp"
__status__ = "Development"
__released_date__ = "May 20, 2024"
__last_update__= "June 29, 2026"
"""

from __future__ import annotations

from .spglib_compat import ensure_spglib_compat

ensure_spglib_compat()

from phonopy.structure.atoms import PhonopyAtoms
from phonopy.interface.calculator import read_crystal_structure
from phonopy.structure.symmetry import Symmetry
from spglib import get_spacegroup_type_from_symmetry, standardize_cell
from .irreptables_compat import load_irreptables
from .runtime_compat import (
    get_character,
    get_chemical_symbols,
    get_little_group,
    get_scaled_positions,
    get_symmetry_dataset,
)
from .operations import (
    characterize_rotation,
    conjugated_little_group_map,
    find_star_arm,
    get_seitz_symbol,
)
from argparse import ArgumentParser, RawTextHelpFormatter, RawDescriptionHelpFormatter, ArgumentDefaultsHelpFormatter
import numpy as np
from numpy.typing import NDArray
from typing import Optional
import itertools
import re
import warnings
from collections import Counter
from fractions import Fraction

IrrepTable, Irrep = load_irreptables()

### PARSER STRUCTURE ###
class MyHelpFormatter(RawTextHelpFormatter, RawDescriptionHelpFormatter, ArgumentDefaultsHelpFormatter):
    pass
desc = """
This program calculates the irreducible representations of elemental's crystal orbitals.

# Command Example:
python3 crystal_orbital.py --poscar POSCAR_ScF3_Pm-3m --element F --orbital p
"""
### --------------- ###


def build_parser() -> ArgumentParser:
    parser = ArgumentParser(description=desc, formatter_class=MyHelpFormatter)
    parser.add_argument("--poscar", "-poscar", dest="poscar", type=str, default="POSCAR",
                        help="POSCAR.")
    parser.add_argument("--element", "-element", dest="element", required=True, type=str, default=None,
                        help="Element.")
    parser.add_argument("--orbital", "-orbital", dest="orbital", type=str, default=None,
                        help="Orbital. You can choose from following; s, p, d, f, g, h, i.")
    parser.add_argument("--axial", "-axial", dest="axial", action="store_true",
                        help="Axial-vector basis (Rx, Ry, Rz) on the sites instead of an orbital\n"
                        "shell: the irreps of the magnetic (spin) configurations.")
    parser.add_argument("--kpoint", "-kpoint", dest="kpoint", type=float, nargs=3, required=False,
                        help="k-point, kx, ky, kz.")
    parser.add_argument("--spinor", "-spinor", dest="spinor", action="store_true",
                        help="Calculate double space group representations.")
    parser.add_argument("--tolerance", "-tolerance", dest="tolerance", type=float, default=0.00001,
                        help="Symmetry tolerance to search primitive cell.")
    parser.add_argument("--show-irrep-table", "-show-table", dest="table", action="store_true",
                        help="Show table of irreps.")
    return parser


def similarity_transformation(rot: NDArray[np.float64], mat: NDArray[np.float64]) -> NDArray[np.float64]:
    """Similarity transformation by R x M x R^-1."""
    return rot @ mat @ np.linalg.inv(rot)


def _canonicalize_component(value: float, tol: float = 1e-6, max_denominator: int = 48) -> float:
    """Snap a float to a nearby simple rational when possible."""
    nearest_integer = round(value)
    if abs(value - nearest_integer) < tol:
        return float(nearest_integer)

    fraction = Fraction(value).limit_denominator(max_denominator)
    snapped = float(fraction)
    if abs(value - snapped) < tol:
        return snapped

    return float(value)


def canonicalize_kpoint(kpoint: list[float], tol: float = 1e-6, max_denominator: int = 48) -> list[float]:
    """Normalize k-point coordinates to stable simple fractions."""
    normalized = [_canonicalize_component(float(value), tol=tol, max_denominator=max_denominator) for value in kpoint]
    return [0.0 if abs(value) < tol else value for value in normalized]


def format_kpoint(kpoint: list[float], decimals: int = 2) -> list[float]:
    """Format a k-point for display using plain Python floats."""
    return [float(np.round(float(value), decimals)) for value in kpoint]


def irrep_label_sort_key(label: str) -> tuple:
    """Natural ordering for physical irrep labels."""
    pattern = re.compile(
        r"^(?P<spinor>-?)(?P<kpoint>[A-Z]+)(?P<index>\d+)(?P<parity>[+-]?)(?:\((?P<dim>\d+)\))$"
    )
    match = pattern.match(label)
    if not match:
        return (label, 10**9, 10**9, 10**9, label)

    spinor = 0 if match.group("spinor") == "-" else 1
    kpoint = match.group("kpoint")
    index = int(match.group("index"))
    parity = match.group("parity")
    dim = int(match.group("dim"))
    parity_order = {"+": 0, "-": 1, "": 2}.get(parity, 3)
    return (kpoint, spinor, index, parity_order, dim, label)


def get_label_overrides(
    space_group_number: int,
    kpoint_name: Optional[str],
    spinor: bool,
) -> dict[str, str]:
    """Return manual label overrides for known naming mismatches in the ISO-IR tables."""
    return {}


# The remark printed under "* Spinor *" (crystod and crystod --atomic-orbital)
SPINOR_NAME_NOTE = (
    " (Double-valued irreps: overbar as a leading '-', index after the single-valued irreps, parity suffix;\n"
    "  Bradley & Cracknell (1972) Table 6.5 (Koster) numbering, except that the 2-D irrep of 32, 3m, -3m\n"
    "  is last (Miller & Love order) and complex pairs of cyclic co-groups follow ISO-IR labels; see the manual.)"
)

# --axial: the pseudo-shell of one axial vector (a magnetic moment) per site.
# Its rotation character is that of the p shell times det(R): the same on a
# proper rotation, unchanged sign on an improper one (inversion keeps a spin).
AXIAL_ORBITAL = "axial"
# the "* Basis *" line of crystod --element EL --axial
AXIAL_BASIS_LABEL = "Rx, Ry, Rz"

_SPINOR_NAME_RE = re.compile(r"^-(?P<k>[A-Za-z_]*?)(?P<n>\d+)(?P<p>[+-]?)$")


class _Unnamed(Exception):
    """Why the double-valued irreps at a k point keep their generic keys."""


def _first_line(exc: Exception) -> str:
    text = str(exc).strip()
    return text.splitlines()[0] if text else type(exc).__name__


def _direct_spinor_names(k, double_characters, dims, spin_rotations, rotations,
                         translations, mapping, lattice, labeler):
    """CrystOD's names of the double-valued irreps at k, taken at k itself.

    The single-valued small irreps at k (spgrep) are labelled by ``labeler``
    and :func:`crystod.wavecar_irreps.double_valued_names` names the
    double-valued ones by their decomposition into those labels.

    Returns:
        ``(names, k_label, single_rotations, single_translations,
        single_characters)``, the last three being the single-valued little
        group and characters the labels were matched with.

    Raises:
        _Unnamed: with the reason, when the irreps cannot be named.
    """
    from .runtime_compat import get_spacegroup_irreps_from_primitive_symmetry
    from .wavecar_irreps import double_valued_names

    try:
        single, single_mapping = get_spacegroup_irreps_from_primitive_symmetry(
            rotations=rotations, translations=translations, kpoint=k)
        single_mapping = np.asarray(single_mapping, dtype=int)
        position = {int(op): i for i, op in enumerate(single_mapping)}
        if sorted(position) != sorted(int(op) for op in mapping):
            raise _Unnamed("single- and double-valued little groups differ")
        single_characters = [np.asarray(get_character(rep)) for rep in single]
        matched = labeler.label_characters(
            k, list(rotations[single_mapping]), list(translations[single_mapping]),
            single_characters)
    except _Unnamed:
        raise
    except Exception as exc:  # spgrep or the labeller failed: keep the keys
        raise _Unnamed(f"single-valued irreps not labelled ({_first_line(exc)})") from exc
    if matched is None:
        raise _Unnamed("no ISO-IR labels for the single-valued irreps")
    single_labels, k_label = matched
    reorder = [position[int(op)] for op in mapping]
    try:
        names, _ = double_valued_names(
            double_characters, spin_rotations, k,
            np.array(single_characters)[:, reorder],
            [single_labels[i] for i in range(len(single))], k_label,
            rotations=rotations[mapping], translations=translations[mapping],
            lattice=lattice, frame=labeler, dims=dims)
    except Exception as exc:  # inconsistent inputs: keep the keys, never crash
        raise _Unnamed(_first_line(exc)) from exc
    return (names, k_label, rotations[single_mapping], translations[single_mapping],
            single_characters)


def _transported_spinor_names(k, names, k_label, double_characters, spin_rotations,
                              rotations, translations, mapping, lattice, labeler, single):
    """The names at k carried over from the representative arm of its star.

    ``labeler.representative_k`` gives the arm k0 that the ISO-IR table lists
    first; the irreps at k0 are named there (:func:`_direct_spinor_names`)
    and carried to k by conjugation
    (:func:`crystod.wavecar_irreps.transport_double_valued_names`), so that
    an irrep has the same name on every arm of a star and at k + G.  Returns
    None at k0 itself and wherever the transport is not possible (the names
    taken at k are kept).
    """
    from spgrep.spinor import get_spinor_factor_system

    from .wavecar_irreps import _spinor_irreps, transport_double_valued_names

    single_rotations, single_translations, single_characters = single
    found = labeler.representative_k(k, list(single_rotations), list(single_translations),
                                     single_characters)
    if found is None:
        return None
    k0, conjugate = found
    k0 = np.asarray(canonicalize_kpoint(list(k0)), dtype=float)
    if np.allclose(k0, np.asarray(k, dtype=float), atol=1e-8):
        return None
    irreps0, unitary0, mapping0 = _spinor_irreps(lattice, rotations, translations, k0)
    mapping0 = np.asarray(mapping0, dtype=int)
    characters0 = np.array([get_character(rep) for rep in irreps0])
    base_names = _direct_spinor_names(
        k0, characters0, [rep.shape[1] for rep in irreps0], unitary0, rotations,
        translations, mapping0, lattice, labeler)[0]
    _, group_unitary = get_spinor_factor_system(lattice, rotations)
    carried = transport_double_valued_names(
        rotations[mapping0], translations[mapping0], unitary0, characters0, base_names, k0,
        rotations[mapping], translations[mapping], spin_rotations, double_characters, k,
        rotations, translations, group_unitary, conjugate=conjugate, k_label=k_label)
    if carried is None or sorted(carried) != sorted(names):
        return None
    return carried


def _proper_parts(rotations) -> list:
    """The distinct proper parts det(R) R of the rotations."""
    parts: list = []
    for R in rotations:
        R = np.rint(np.asarray(R, dtype=float)).astype(int)
        proper = R * (1 if np.linalg.det(R) > 0 else -1)
        if not any(np.array_equal(proper, other) for other in parts):
            parts.append(proper)
    return parts


def _rotation_order(R) -> int:
    identity = np.eye(3, dtype=int)
    power, order = np.array(R, dtype=int), 1
    while not np.array_equal(power, identity) and order <= 12:
        power, order = power @ R, order + 1
    return order


def spinor_numbering_notes(names, dims, little_rotations, characters=None) -> list:
    """The NOTE lines that say where the double-valued names at a k point
    differ from Bradley & Cracknell (1972).

    * proper parts of the little co-group 32 (32, 3m and -3m) with, per
      parity, two one-dimensional irreps and one two-dimensional irrep:
      B&C (Table 6.5, Koster's numbering) number the two-dimensional irrep
      first, CrystOD last (dimension first, the order of Miller & Love);
    * proper parts a cyclic group of order 3, 4 or 6 (3, -3, 4, -4, 4/m, 6,
      -6, 6/m) and a complex-conjugate pair among the irreps at k (with
      ``characters``; at K of P3, whose conjugates live at -K, there is
      none): the complex-conjugate pairs are ordered after the single-valued
      ISO-IR labels, because B&C's Tables 6.5 and 6.14 number them
      inconsistently.

    Args:
        names: The double-valued names at k (``-GM4+``), one per irrep.
        dims: Their dimensions.
        little_rotations: Rotations of the little group of k.
        characters: Their characters, one row per irrep, on the operations
            of ``little_rotations``; without them the second note only asks
            for a one-dimensional irrep.

    Returns:
        The lines, without the ``NOTE:`` prefix (empty when the names follow
        B&C or cannot be read).
    """
    parsed = [_SPINOR_NAME_RE.match(str(name)) for name in names]
    if not parsed or any(match is None for match in parsed):
        return []
    parts = _proper_parts(little_rotations)
    order = len(parts)
    cyclic = max(_rotation_order(R) for R in parts) == order
    notes = []
    if order == 6 and not cyclic:
        by_parity: dict = {}
        for match, dim in zip(parsed, dims):
            by_parity.setdefault(match["p"], []).append((int(dim), int(match["n"])))
        classes = [sorted(members) for members in by_parity.values()]
        letters = {match["k"] for match in parsed}
        if (len(letters) == 1 and all(len(c) == 3 and [d for d, _ in c] == [1, 1, 2]
                                      for c in classes)
                and all(c == classes[0] for c in classes)):
            (_, i1), (_, i2), (_, i3) = classes[0]
            if i1 < i2 < i3:
                k = letters.pop()
                suffix = "".join(sorted(by_parity, key=lambda p: {"+": 0, "-": 1}.get(p, 2)))
                notes.append(
                    f"Bradley & Cracknell (1972) number the two-dimensional irrep {k}{i1}{suffix} "
                    f"and the pair {k}{i2}{suffix}, {k}{i3}{suffix} (Table 6.5); here the pair is "
                    f"-{k}{i1}{suffix}, -{k}{i2}{suffix} and the two-dimensional irrep "
                    f"-{k}{i3}{suffix}")
    if characters is not None:
        rows = [np.asarray(row, dtype=complex) for row in characters]
        paired = any(np.max(np.abs(a.imag)) > 1e-6 and np.allclose(a, np.conj(b), atol=1e-6)
                     for i, a in enumerate(rows) for b in rows[i + 1:])
    else:
        paired = any(int(dim) == 1 for dim in dims)
    if order in (3, 4, 6) and cyclic and paired:
        notes.append("the complex-conjugate pairs are ordered after the single-valued ISO-IR "
                     "labels; Bradley & Cracknell (1972) Tables 6.5 and 6.14 number them "
                     "inconsistently")
    return notes


def label_spinor_irreps(
    k,
    irreps,
    rotations,
    translations,
    mapping_little_group,
    lattice,
    labeler,
    spin_rotations=None,
) -> tuple[dict[str, str], Optional[str], Optional[str]]:
    """CrystOD's names of spgrep's double-valued small irreps at a k point.

    The SALC route of ``--spinor`` (``crystod --element/--orbital`` and
    ``crystod --atomic-orbital``).  The single-valued small irreps at k are
    labelled by ``labeler`` -- the ISO-IR labeller of the input cell, the one
    behind the labels the command prints without ``--spinor`` -- and
    :func:`crystod.wavecar_irreps.double_valued_names` names every
    double-valued irrep by the decomposition of D x D(1/2) into those labels
    (``-GM8+``, ``-R6-``; the rule, the tie-break of conjugate pairs and the
    lift convention are documented there).  The names are fixed at the
    representative arm k0 of the star of k (arm 0 of the ISO-IR family,
    :meth:`crystod.isoir.IsoIRLabeler.representative_k`) and carried to k by
    conjugation (:func:`crystod.wavecar_irreps.transport_double_valued_names`),
    so that they do not depend on the arm or on the copy k + G; where that
    is not possible they are taken at k itself.

    Args:
        k: Three primitive reciprocal coordinates.
        irreps: spgrep's double-valued small irreps at k, arrays of shape
            ``(little_group_order, dim, dim)``.
        rotations: All rotations of the space group in the primitive basis.
        translations: Their translations.
        mapping_little_group: Indices into ``rotations`` of the little-group
            operations, in the order of the irrep matrices.
        lattice: Primitive cell vectors as rows (Angstrom).
        labeler: The :class:`crystod.isoir.IsoIRLabeler` of the labels, or
            None when the ISO-IR data are unavailable.
        spin_rotations: The SU(2) matrices U_g of the little-group operations
            the irreps were built with (spgrep's ``little_unitary_rotations``);
            recomputed with spgrep when omitted.

    Returns:
        ``(label_map, k_label, note)``: ``{"irrep_i(dim)": "-K<n><p>(dim)"}``
        for every irrep (an irrep that cannot be named keeps its generic key
        as its label), the ISO-IR k label of the single-valued irreps (None
        when there is none), and the NOTE lines of this k point joined by
        newlines (None when there are none): the reason when some irrep kept
        its generic key, or else where the names differ from Bradley &
        Cracknell (1972) (:func:`spinor_numbering_notes`).  Never raises.
    """
    generic = [f"irrep_{i + 1}({irrep.shape[1]})" for i, irrep in enumerate(irreps)]
    label_map = {key: key for key in generic}

    def unnamed(reason: str) -> tuple[dict[str, str], Optional[str], Optional[str]]:
        return label_map, None, f"all double-valued irreps keep generic names: {reason}"

    if labeler is None:
        return unnamed("no ISO-IR data for the single-valued labels")
    rotations = np.asarray(rotations)
    translations = np.asarray(translations, dtype=float)
    mapping = np.asarray(mapping_little_group, dtype=int)
    lattice = np.asarray(lattice, dtype=float)
    try:
        if spin_rotations is None:
            from spgrep.spinor import get_spinor_factor_system

            _, spin_rotations = get_spinor_factor_system(lattice, rotations[mapping])
        double_characters = np.array([get_character(rep) for rep in irreps])
        dims = [rep.shape[1] for rep in irreps]
    except Exception as exc:  # spgrep failed: keep the keys
        return unnamed(f"single-valued irreps not labelled ({_first_line(exc)})")
    try:
        names, k_label, *single = _direct_spinor_names(
            k, double_characters, dims, spin_rotations, rotations, translations, mapping,
            lattice, labeler)
    except _Unnamed as exc:
        return unnamed(str(exc))
    except Exception as exc:  # never crash
        return unnamed(_first_line(exc))
    try:
        carried = _transported_spinor_names(
            k, names, k_label, double_characters, spin_rotations, rotations, translations,
            mapping, lattice, labeler, single)
    except Exception:  # the names taken at k stay
        carried = None
    if carried is not None:
        names = carried
    repeated = Counter(names)
    kept = []
    for key, name, irrep in zip(generic, names, irreps):
        if name and repeated[name] == 1:
            label_map[key] = f"{name}({irrep.shape[1]})"
        else:
            kept.append(key)
    if kept:
        return label_map, k_label, (f"{', '.join(kept)} kept generic: "
                                    "the double-valued names are not unique here")
    try:
        lines = spinor_numbering_notes(names, dims, rotations[mapping], double_characters)
    except Exception:
        lines = []
    return label_map, k_label, "\n".join(lines) if lines else None


[docs] class CrystalOrbital: """Irreps of the crystal orbitals built from one atomic shell (``crystod``). The Bloch sums of one element's ``s``, ``p``, ``d``, ``f``, ``g``, ``h`` or ``i`` shell at a k point span a (reducible) representation of the little group of ``k`` -- the site-symmetry induced representation, or band representation, of that shell. Its character is the product of the permutation character of the element's sites (with the Bloch phases of ``k``) and the rotation character of the shell, and its decomposition into the irreps of the little group is what ``crystod -c POSCAR --element EL --orbital ORB [--kpoint K]`` prints: with ``--spinor`` the double-valued (spin-orbit) irreps, without ``--kpoint`` every special point of the space group. The shell ``"axial"`` (:data:`AXIAL_ORBITAL`) is one axial vector (Rx, Ry, Rz) per site, the magnetic representation of ``crystod --element EL --axial``: the irreps of the spin configurations of the element's sites. The spgrep irreps are labelled with the ISO-IR (Miller-Love) names, ``GM3+(2)``, ``X5-(2)`` and so on, the number in parentheses being the dimension. The ISO-IR tables hold single-valued irreps only; the double-valued irreps of ``--spinor`` are named ``-GM7+(2)``, ``-R8-(4)`` (:func:`crystod.wavecar_irreps.double_valued_names`, built on the ISO-IR labels of the single-valued irreps at the same k, numbered as in Bradley & Cracknell (1972) Table 6.5 except in 32, 3m, -3m and the cyclic co-groups, and the same on every arm of a star), the names of ``crystod --extract-irrep``, not the Bilbao numbering. The input cell is reduced to the spglib primitive cell, and the symmetry operations are reordered to match the ISO-IR tables (a ``ValueError`` is raised when that fails). Args: cell: The crystal structure as ``phonopy.structure.atoms.PhonopyAtoms`` (any setting; it is converted to the primitive cell). symprec: Symmetry tolerance handed to spglib. spinor: ``True`` for the double-valued (spinor) irreps (default: single-valued). spior: Deprecated misspelling of ``spinor``, still accepted (with a ``DeprecationWarning``); it applies only when ``spinor`` is not given. Attributes: primitive_cell: The standardized primitive ``PhonopyAtoms`` cell that every k point and atom index refers to. spglib_dataset: The spglib symmetry dataset of the primitive cell (``"international"``, ``"number"``, ``"wyckoffs"``, ``"site_symmetry_symbols"``, ...). transformation_matrix: The spglib transformation matrix of the primitive cell; it carries the ISO-IR k vectors and rotations, tabulated in the conventional setting, onto the primitive basis. rotations: Integer rotation matrices in the primitive basis, in the ISO-IR table order. translations: The matching fractional translations. seitz_symbols: The Seitz symbol of every operation, same order. spinor: Whether double-valued irreps are used. symprec: The symmetry tolerance in use. irt_character_table: The ISO-IR table of the space group (empty with ``spinor``: the bundled ISO-IR data hold single-valued irreps only). irt_kpoint_table: The single-valued ISO-IR table the special k points are enumerated from. labels_from_isoir: Set by :meth:`get_irrep_labels` at a k point the table does not list: whether the labels came from the full ISO-IR k-vector data. spinor_label_note: Set by :meth:`get_irrep_labels` with ``spinor``: the NOTE lines of the last k point, joined by newlines -- why some double-valued irreps kept their generic ``irrep_i(dim)`` keys, or else where the names differ from Bradley & Cracknell (1972) (:func:`spinor_numbering_notes`) -- or ``None``. Example: >>> from phonopy.interface.calculator import read_crystal_structure >>> from crystod import salc >>> from crystod.examples import example_path >>> cell, _ = read_crystal_structure( ... str(example_path("221_PPOSCAR_ScF3")), interface_mode="vasp") >>> co = salc.CrystalOrbital(cell) >>> co.get_irt_special_points()[0] ['GM', 'R', 'X', 'M'] >>> _, _, counts, labels = co.irreducible_decomposition( ... [0, 0, 0], "Sc", "d") >>> {labels[key]: int(n) for key, n in counts.items() if n > 0} {'GM3+(2)': 1, 'GM5+(3)': 1} """ def __init__( self, cell: PhonopyAtoms, symprec: float = 0.00001, spinor: Optional[bool] = None, *, spior: Optional[bool] = None, ): if spior is not None: warnings.warn("CrystalOrbital(spior=...) is deprecated; use spinor=...", DeprecationWarning, stacklevel=2) if spinor is None: # an explicit spinor= wins over the old spelling spinor = spior self._inputed_cell = cell # Convert inputed cell to primitive cell. (primitive_lattice, primitive_pos, primitive_numbers) = standardize_cell(cell.totuple(), to_primitive=True, symprec=symprec) self.primitive_cell = PhonopyAtoms(numbers=primitive_numbers, scaled_positions=primitive_pos, cell=primitive_lattice) print("\n ### Inputed cell was converted into primitive cell. ###") self.spinor = bool(spinor) # None (not given): False self.symprec = symprec self.spinor_label_note: Optional[str] = None # Get symmetry informations symmetry = Symmetry(self.primitive_cell) dataset = get_symmetry_dataset(symmetry) self.spglib_dataset = dataset self._spglib_rotations = dataset['rotations'] self._spglib_translations = dataset['translations'] self.transformation_matrix = dataset['transformation_matrix'] # primitive matrix self.irt_character_table = IrrepTable(dataset['number'], self.spinor) # Special k-point names/coordinates do not depend on spinor; the # bundled ISO-IR tables carry single-valued irreps only (the spinor # table has no irreps), so enumerate special points from the # single-valued table. self.irt_kpoint_table = ( self.irt_character_table if not self.spinor else IrrepTable(dataset['number'], False) ) self.rotations, self.translations = self._sort_symmetry_operations_in_order_of_irt( self._spglib_rotations, self._spglib_translations, ) self.seitz_symbols = [get_seitz_symbol(r, self.transformation_matrix) for r in self.rotations] def _sort_symmetry_operations_in_order_of_irt( self, spglib_R: NDArray[np.int_], spglib_t: NDArray[np.float64], ) -> tuple[NDArray[np.int_], NDArray[np.float64]]: """Sort symmetry operations found by spglib in the ISO-IR table order.""" irt_conv_R = np.array([sym.R for sym in self.irt_character_table.symmetries], dtype=float) irt_prim_R = similarity_transformation(np.linalg.inv(self.transformation_matrix), irt_conv_R) sorted_R = [] sorted_t = [] used_indices = set() for irt_R in np.rint(irt_prim_R).astype(int): found = False for i, R in enumerate(spglib_R): if i in used_indices: continue if (irt_R == R).all(): sorted_R.append(R) sorted_t.append(spglib_t[i]) used_indices.add(i) found = True break if not found: raise ValueError("Failed to sort symmetry operations in ISO-IR table order.") return np.array(sorted_R), np.array(sorted_t)
[docs] def get_irt_irreps_at_k(self, k: list[float]) -> list[Irrep]: """Tabulated ISO-IR irreps at a k point. Args: k: Three primitive reciprocal coordinates. Returns: The ISO-IR irrep records whose k vector equals ``k`` -- each with ``kpname``, ``k`` and its characters -- or an empty list when the point is not tabulated as given (a non-tabulated arm of a star, or no special point at all). """ k = canonicalize_kpoint(k) trans_inv = np.linalg.inv(self.transformation_matrix) conventional_k = np.array(k) @ trans_inv irreps_at_k = [] for irrep_at_k in self.irt_character_table.irreps: if np.allclose(irrep_at_k.k, conventional_k, atol=1e-6): irreps_at_k.append(irrep_at_k) return irreps_at_k
[docs] def get_kpoint_name(self, k: list[float]) -> Optional[str]: """Name of a k point (``GM``, ``X``, ``M``, ...), or ``None``. The ISO-IR k-vector type of k in the frame of the labels (the ISO-IR frame of the input cell): any arm of a special-point star gets the star's name, a line, plane or generic k its type letters (``DT``, ``GP``, ...), and the partner of a star tabulated only through -k the 'A' name (``PA`` of I-4). The special-point table is the fallback where the ISO-IR data give nothing. Args: k: Three primitive reciprocal coordinates. Returns: The name, or ``None`` when nothing matches. """ k = canonicalize_kpoint(k) # the labeller first: the table below is in spglib's basis, which # differs from the frame of the labels for an input outside the # ISO-IR setting (it would name P what the labels call PA) labeler = self._get_isoir_labeler() if labeler is not None: try: name = labeler.kpoint_name(k) except Exception: name = None if name is not None: return name irreps_at_k = self.get_irt_irreps_at_k(k) if irreps_at_k: return irreps_at_k[0].kpname arm = self._find_irt_star_arm(k) if arm is not None: irreps_at_rep = self.get_irt_irreps_at_k(arm[1]) if irreps_at_rep: return irreps_at_rep[0].kpname return None
def _find_irt_star_arm(self, k: list[float]) -> Optional[tuple[int, list[float]]]: """(g_index, k_rep) mapping k onto the tabulated arm of its star, or None. The operations are sorted in the ISO-IR table order, so g_index doubles as the ISO-IR table operation index. """ _, special_points = self.get_irt_special_points() return find_star_arm(k, self.rotations, special_points) def _conjugated_character_indices( self, g_index: int, k_rep: list[float], mapping_little_group: NDArray[np.int_], ) -> Optional[tuple[list[int], NDArray[np.complex128]]]: """Character transport h -> g^-1 h g onto the little group of k_rep.""" return conjugated_little_group_map( self.rotations, self.translations, g_index, k_rep, mapping_little_group )
[docs] def get_irt_special_points(self) -> tuple[list[str], list[list[float]]]: """Special k points of the space group from the ISO-IR tables. Returns: ``(names, kpoints)``: the tabulated names (``GM``, ``R``, ``X``, ``M`` for Pm-3m) and their primitive reciprocal coordinates, one entry per distinct point, in table order. The coordinates are the table's own, carried by spglib's transformation matrix, as the direct character comparison needs them; the points ``crystod`` analyzes and prints are :meth:`get_special_points`. """ primitive_kpoints = [] kpoint_names = [] for irrep in self.irt_kpoint_table.irreps: primitive_k = canonicalize_kpoint(list(np.array(irrep.k) @ self.transformation_matrix)) if primitive_k not in primitive_kpoints: primitive_kpoints.append(primitive_k) kpoint_names.append(irrep.kpname) return kpoint_names, primitive_kpoints
[docs] def get_special_points(self) -> tuple[list[str], list[list[float]]]: """Special k points named in the frame of the labels. The points of :meth:`get_irt_special_points` passed through ``crystod.isoir.special_points_in_frame``: every point is named by the ISO-IR labeller of the input cell, and a point that is the -k partner of a tabulated type is replaced by -k, so that each name is the letters of the labels printed at its point. The two lists differ only when the frame of the labels is not spglib's (an input outside the ISO-IR setting). These are the points ``crystod`` analyzes when ``--kpoint`` is omitted, and the names ``--kpoint`` accepts. Returns: ``(names, kpoints)``, one entry per distinct point, in table order. """ from .isoir import special_points_in_frame names, kpoints = self.get_irt_special_points() return special_points_in_frame( names, kpoints, self._get_isoir_labeler(), canonical=canonicalize_kpoint )
def _get_isoir_labeler(self): """Lazily construct the ISO-IR labeler (None if data unavailable).""" if not hasattr(self, "_isoir_labeler"): from .isoir import get_cached_labeler # the frame of the labels is that of the cell as given, not of # the standardized primitive cell derived from it self._isoir_labeler = get_cached_labeler( self.spglib_dataset['number'], self.primitive_cell.totuple(), self.symprec, input_cell=self._inputed_cell.totuple(), ) return self._isoir_labeler def _get_isoir_labels( self, k: list[float], irreps, mapping_little_group: NDArray[np.int_], ) -> Optional[dict[str, str]]: """Label spgrep irreps with ISO-IR (Miller-Love) labels, or None. The ISO-IR tables contain single-valued irreps only; the spinor path names its double-valued irreps with :func:`label_spinor_irreps` instead (from the ISO-IR labels of the single-valued irreps). """ self.labels_from_isoir = False if self.spinor: return None labeler = self._get_isoir_labeler() if labeler is None: return None little_rotations = [self.rotations[idx] for idx in mapping_little_group] little_translations = [self.translations[idx] for idx in mapping_little_group] spgrep_characters = [get_character(irrep) for irrep in irreps] try: matched = labeler.label_characters( k, little_rotations, little_translations, spgrep_characters ) except Exception: return None if matched is None: return None label_map, kpoint_name = matched self.labels_from_isoir = True self.isoir_kpoint_name = kpoint_name return { f"irrep_{i+1}({irrep.shape[1]})": f"{label_map[i]}({irrep.shape[1]})" for i, irrep in enumerate(irreps) }
[docs] def get_irrep_labels( self, k: list[float], irreps, mapping_little_group: NDArray[np.int_], spin_rotations=None, ) -> dict[str, str]: """Map spgrep irreps at ``k`` to ISO-IR labels. The ISO-IR labeller (``crystod.isoir``) names the irreps at any k, in the ISO-IR frame of the input cell; a k point tabulated only through its -k partner gets the 'A' names (``PA1``). The direct comparison of characters with the special-point table is the fallback where the labeller gives nothing. With :attr:`spinor` the double-valued irreps are named by :func:`label_spinor_irreps` (``-GM8+(4)``, from the ISO-IR labels of the single-valued irreps at k in the same frame, fixed at the representative arm of the star of k). Args: k: Three primitive reciprocal coordinates. irreps: The spgrep irreps at ``k`` (arrays of shape ``(little_group_order, dim, dim)``), as returned by :meth:`irreducible_decomposition`. mapping_little_group: Indices into :attr:`rotations` of the little-group operations, in the order of the irrep matrices. spin_rotations: With :attr:`spinor`, the SU(2) matrices U_g the double-valued irreps were built with (spgrep's ``little_unitary_rotations``), same order; recomputed with spgrep when omitted. Returns: ``{generic: label}`` with the generic key ``"irrep_i(dim)"`` of every irrep and its ISO-IR label such as ``"GM3+(2)"`` (with :attr:`spinor`: ``"-GM8+(4)"``). In the fallback, a k point the table does not list is first mapped onto the tabulated arm of its star (characters transported by conjugation); an irrep that finds no match on either route keeps its generic key as the label, and so does a double-valued irrep that cannot be named (the reason is left in :attr:`spinor_label_note`). """ k = canonicalize_kpoint(k) if self.spinor: label_map, kpoint_name, note = label_spinor_irreps( k, irreps, self.rotations, self.translations, mapping_little_group, self.primitive_cell.cell, self._get_isoir_labeler(), spin_rotations=spin_rotations, ) self.labels_from_isoir = False if kpoint_name is not None: self.isoir_kpoint_name = kpoint_name self.spinor_label_note = note return label_map irt_irreps = self.get_irt_irreps_at_k(k) char_indices: list[int] = list(mapping_little_group) char_phases = np.ones(len(char_indices), dtype=complex) if not irt_irreps: # k may be a non-tabulated arm of a special-point star: map it onto # the tabulated arm and transport the characters by conjugation. arm = self._find_irt_star_arm(k) if arm is not None: conjugated = self._conjugated_character_indices(arm[0], arm[1], mapping_little_group) if conjugated is not None: candidate_irreps = self.get_irt_irreps_at_k(arm[1]) if candidate_irreps and all( (index + 1) in candidate_irreps[0].characters for index in conjugated[0] ): irt_irreps = candidate_irreps char_indices, char_phases = conjugated # The ISO-IR labeller is the label authority at every k: it compares # in the ISO-IR setting, at the exact translations and with the # conjugate phase convention. The direct special-point comparison # below ignores all three and names a physically different irrep at # some points (H/K of the hexagonal groups, P of I4/mcm, Y/T of # Ccce, ...); it is kept as a fallback. isoir_labels = self._get_isoir_labels(k, irreps, mapping_little_group) if irt_irreps and isoir_labels is not None: # the flag keeps its meaning "k is not a tabulated point" self.labels_from_isoir = False return isoir_labels if not irt_irreps: # Not among the tabulated special-point irreps (e.g. a symmetry # line/plane or generic k): only the full ISO-IR (ISOTROPY) # labeler covers it. Labels then follow the Miller-Love # convention. if isoir_labels is not None: return isoir_labels return { f"irrep_{i+1}({irrep.shape[1]})": f"irrep_{i+1}({irrep.shape[1]})" for i, irrep in enumerate(irreps) } def match_direct( lhs: NDArray[np.complex128], rhs: NDArray[np.complex128], atol: float = 1e-5, ) -> Optional[NDArray[np.complex128]]: if np.allclose(lhs, rhs, atol=atol): return rhs return None irt_character_map = {} for irt_irrep in irt_irreps: irt_label = f"{irt_irrep.name}({irt_irrep.dim})" irt_character_map[irt_label] = ( np.array( [irt_irrep.characters[idx + 1] for idx in char_indices], dtype=complex, ) * char_phases ) spgrep_character_map = {} label_map = {} matched_character_map = {} used_labels = set() for i, irrep in enumerate(irreps): generic_label = f"irrep_{i+1}({irrep.shape[1]})" spgrep_character_map[generic_label] = np.array(get_character(irrep), dtype=complex) label_map[generic_label] = generic_label ordered_spgrep_labels = sorted( spgrep_character_map.keys(), key=lambda label: int(label.split("(")[1][:-1]), reverse=True, ) # First, try strict direct character matching without conjugation. for generic_label in ordered_spgrep_labels: spgrep_chars = spgrep_character_map[generic_label] spgrep_dim = int(generic_label.split("(")[1][:-1]) matched_candidates = [] for irt_label, irt_chars in irt_character_map.items(): if irt_label in used_labels: continue irt_dim = int(irt_label.split("(")[1][:-1]) if irt_dim != spgrep_dim: continue transformed_chars = match_direct(spgrep_chars, irt_chars) if transformed_chars is not None: matched_candidates.append((irt_label, transformed_chars)) if len(matched_candidates) == 1: irt_label, transformed_chars = matched_candidates[0] label_map[generic_label] = irt_label matched_character_map[generic_label] = transformed_chars used_labels.add(irt_label) progress = True while progress: progress = False unresolved_labels = [ label for label in ordered_spgrep_labels if label_map[label] == label ] if not unresolved_labels: break unresolved_dims = sorted( {int(label.split("(")[1][:-1]) for label in unresolved_labels}, reverse=True, ) for irrep_dim in unresolved_dims: group_generic = [ label for label in unresolved_labels if int(label.split("(")[1][:-1]) == irrep_dim ] group_physical = [ label for label in sorted(irt_character_map.keys()) if label not in used_labels and int(label.split("(")[1][:-1]) == irrep_dim ] if len(group_generic) != len(group_physical) or not group_generic or len(group_generic) > 6: continue solutions = [] for perm in itertools.permutations(group_physical): transformed = { generic_label: irt_character_map[irt_label] for generic_label, irt_label in zip(group_generic, perm) } is_consistent = True for generic_label in group_generic: for reference_label, reference_chars in matched_character_map.items(): spgrep_invariant = ( spgrep_character_map[generic_label] * np.conj(spgrep_character_map[reference_label]) ) irt_invariant = ( transformed[generic_label] * np.conj(reference_chars) ) if not np.allclose(spgrep_invariant, irt_invariant, atol=1e-5): is_consistent = False break if not is_consistent: break if not is_consistent: continue for i, left_label in enumerate(group_generic): for right_label in group_generic[i + 1:]: spgrep_invariant = ( spgrep_character_map[left_label] * np.conj(spgrep_character_map[right_label]) ) irt_invariant = ( transformed[left_label] * np.conj(transformed[right_label]) ) if not np.allclose(spgrep_invariant, irt_invariant, atol=1e-5): is_consistent = False break if not is_consistent: break if is_consistent: solutions.append((perm, transformed)) if not solutions: continue solutions.sort(key=lambda item: item[0]) perm, transformed = solutions[0] for generic_label, irt_label in zip(group_generic, perm): label_map[generic_label] = irt_label matched_character_map[generic_label] = transformed[generic_label] used_labels.add(irt_label) progress = True kpoint_name = self.get_kpoint_name(k) overrides = get_label_overrides( space_group_number=self.spglib_dataset["number"], kpoint_name=kpoint_name, spinor=self.spinor, ) if overrides: label_map = { generic_label: overrides.get(resolved_label, resolved_label) for generic_label, resolved_label in label_map.items() } unresolved_generic = [ label for label in ordered_spgrep_labels if label_map[label] == label ] unresolved_physical = sorted( [label for label in irt_character_map.keys() if label not in used_labels], key=irrep_label_sort_key, ) if unresolved_generic and len(unresolved_generic) == len(unresolved_physical): unresolved_generic = sorted( unresolved_generic, key=lambda label: ( int(label.split("(")[1][:-1]), int(label.split("_")[1].split("(")[0]), ), ) for generic_label, physical_label in zip(unresolved_generic, unresolved_physical): label_map[generic_label] = physical_label return label_map
[docs] def get_target_element_positions(self, element: str) -> list[int]: """Indices of the atoms of ``element`` in the primitive cell. Args: element: Chemical symbol, e.g. ``"Sc"``. Returns: The atom indices in cell order. They need not be contiguous: spglib keeps the atom order of the input, so a POSCAR whose species line repeats an element (``O Ti O Sr O``) gives ``[0, 2, 4]`` for O. Index with this list, never with the range from its first to its last entry. Raises: ValueError: The element is not in the cell. """ all_chemical_symbols = get_chemical_symbols(self.primitive_cell) if not element in all_chemical_symbols: raise ValueError( f"Element \"{element}\" is not in the inputed cell." ) species = np.array(all_chemical_symbols) return [int(i) for i in np.flatnonzero(species == element)]
def _get_rotations_at_k( self, rotations: NDArray[np.int_], translations: NDArray[np.float64], k: list[float], ) -> tuple[NDArray[np.int_], NDArray[np.float64]]: """Get little-group operations using a stable integer-lattice test.""" k = canonicalize_kpoint(k) rotations_at_k = [] translations_at_k = [] for rotation, translation in zip(rotations, translations): diff = np.dot(k, rotation) - k if (abs(diff - np.rint(diff)) < 1e-5).all(): rotations_at_k.append(rotation) normalized_translation = np.array(translation, dtype=float).copy() for i in range(3): if abs(normalized_translation[i] - 1.0) < 1e-5: normalized_translation[i] = 0.0 translations_at_k.append(normalized_translation) return np.array(rotations_at_k), np.array(translations_at_k)
[docs] def get_modified_permutation_rep(self, r: NDArray[np.int_], t: NDArray[np.float64], k: list[float, float, float] ) -> NDArray[np.complex128]: """Bloch-phased permutation matrix of one operation at ``k``. Args: r: Integer rotation matrix in the primitive basis. t: Its fractional translation. k: Three primitive reciprocal coordinates. Returns: Complex array of shape ``(n_atoms, n_atoms)`` whose entry ``[j, i]`` is the Bloch phase ``exp(2 pi i k . (R^-1 (x_j - t) - x_j))`` when the operation sends atom ``i`` onto atom ``j`` (modulo lattice translations), and 0 elsewhere. """ pos = get_scaled_positions(self.primitive_cell) num_atom = len(pos) matrix = np.zeros((num_atom, num_atom), dtype=complex) for i, p1 in enumerate(pos): p_rot = np.dot(r, p1) + t # i -> j for j, p2 in enumerate(pos): diff = p_rot - p2 # Rx_i + t - x_j if (abs(diff - np.rint(diff)) < 1e-5).all(): phase_factor = np.dot( k, np.dot(np.linalg.inv(r), p2 - t) - p2 ) matrix[j, i] = np.exp(2j * np.pi * phase_factor) return matrix
[docs] def get_permutation_reps_at_k(self, little_rotations, little_translations, k: list[float] ) -> tuple[NDArray[np.int_], NDArray[np.float64], NDArray[np.complex128]]: """Permutation matrices of the little-group operations at ``k``. Args: little_rotations: Rotations of the little group of ``k``, shape ``(order, 3, 3)``. little_translations: Their fractional translations, shape ``(order, 3)``. k: Three primitive reciprocal coordinates. Returns: Complex array of shape ``(order, n_atoms, n_atoms)``: one :meth:`get_modified_permutation_rep` matrix per operation. """ permutation_matrices = [] for r, t in zip(little_rotations, little_translations): permutation_matrix = self.get_modified_permutation_rep(r, t, k) permutation_matrices.append(permutation_matrix) permutation_matrices = np.array(permutation_matrices) return permutation_matrices
[docs] def get_little_group(self, k: list[float]): """Little group of ``k``: the operations that leave ``k`` invariant. Args: k: Three primitive reciprocal coordinates. Returns: ``(little_rotations, little_translations)`` in the ISO-IR operation order (spgrep's ``get_little_group`` without the index mapping, which :meth:`irreducible_decomposition` returns). """ k = canonicalize_kpoint(k) little_rotations, little_translations, mapping_little_group = get_little_group( rotations=self.rotations, translations=self.translations, kpoint=k ) return little_rotations, little_translations
[docs] def get_little_group_symbol(self, k: list[float] ) -> str: """Space-group-type symbol of the little group of ``k``. Args: k: Three primitive reciprocal coordinates. Returns: The short Hermann-Mauguin symbol and number spglib assigns to the little-group operations, e.g. ``"Pm-3m (221)"`` at Gamma or ``"P4/mmm (123)"`` at X of a cubic perovskite. """ little_rotations, little_translations = self._get_rotations_at_k(self.rotations, self.translations, k) site_sym_k = get_spacegroup_type_from_symmetry(little_rotations, little_translations) if hasattr(site_sym_k, "international_short"): international_short = site_sym_k.international_short else: international_short = site_sym_k["international_short"] if hasattr(site_sym_k, "number"): number = site_sym_k.number else: number = site_sym_k["number"] return f"{international_short} ({number})"
[docs] def get_atomic_orbital_characters(self, rotations: NDArray[np.int_], orbital: str, spin_traces=None, ) -> NDArray[np.float64]: """Rotation characters of one atomic shell. The character of a proper rotation by ``alpha`` on the ``2l+1`` orbitals of shell ``l`` is ``sin((l + 1/2) alpha) / sin(alpha / 2)`` (``2l+1`` for the identity); an improper operation multiplies it by ``(-1)^l``. With :attr:`spinor` the spin factor tr U_g is included, U_g being the SU(2) matrix spgrep assigns to the operation (angle in [0, pi], U(-R) = U(R); tr U_g = 2 cos(alpha / 2)), so that the reducible character and spgrep's double-valued irreps share one lift. Args: rotations: Integer rotation matrices, shape ``(n, 3, 3)``. orbital: Shell letter ``"s"``, ``"p"``, ``"d"``, ``"f"``, ``"g"``, ``"h"`` or ``"i"``, or :data:`AXIAL_ORBITAL` (``"axial"``): one axial vector (Rx, Ry, Rz), the character ``det(R) chi_p(R)`` -- the p-shell value with no sign change on improper operations. spin_traces: With :attr:`spinor`, tr U_g of the ``n`` operations as the double-valued irreps were built with (the traces of spgrep's ``little_unitary_rotations``); computed with spgrep's own map from the rotation to U_g when omitted. Returns: Real array of the ``n`` characters. Raises: ValueError: An unknown shell letter, or the axial basis with :attr:`spinor` (a magnetic moment is single-valued). """ # azimuthal number (l) orbital_azimuthal_num = {"s" : 0, "p" : 1, "d" : 2, "f" : 3, "g" : 4, "h" : 5, "i" : 6} axial = orbital == AXIAL_ORBITAL if axial and self.spinor: raise ValueError( "The axial-vector basis (Rx, Ry, Rz) is single-valued: it does " "not take double-valued (spinor) irreps." ) if not axial and not orbital in orbital_azimuthal_num.keys(): raise ValueError( f"Orbital \"{orbital}\" cannot be analyzed" ) characters = [] l = 1 if axial else orbital_azimuthal_num[orbital] for r in rotations: is_proper, rot_order = characterize_rotation(r) alpha = 2 * np.pi / rot_order if rot_order == 1: character = 2 * l + 1 else: character = np.sin((l + 1/2) * alpha) / np.sin(alpha / 2) if not is_proper and not axial: # polar shell: parity (-1)^l; axial vector: det(R) (-1)^1 = +1 character = character * (-1) ** l characters.append(character) characters = np.array(characters) if self.spinor: # spin factor tr U_g of the SU(2) lift spgrep builds its irreps with if spin_traces is None: from spgrep.spinor import get_spinor_unitary_rotation spin_traces = [ np.real(np.trace(get_spinor_unitary_rotation(self.primitive_cell.cell, r))) for r in rotations ] characters = characters * np.asarray(spin_traces, dtype=float) return characters
[docs] def get_permutation_characters(self, element: str, permutation_matrices: NDArray[np.complex128] ) -> NDArray[np.complex128]: """Permutation characters restricted to the atoms of one element. Args: element: Chemical symbol. permutation_matrices: Output of :meth:`get_permutation_reps_at_k`. Returns: Complex array with the trace of every matrix over the rows and columns of the element's atoms (the index list of :meth:`get_target_element_positions`, contiguous or not). """ element_positions = self.get_target_element_positions(element) block = np.ix_(element_positions, element_positions) permutation_characters = [] for i in range(permutation_matrices.shape[0]): rep = permutation_matrices[i][block] character = np.trace(rep) permutation_characters.append(character) return np.array(permutation_characters, dtype=complex)
[docs] def calc_reducible_characters(self, k: list[float], element: str, orbital: str, mapping_little_group: NDArray[np.int_], spin_traces=None, ) -> NDArray[np.complex128]: """Characters of the crystal-orbital representation at ``k``. Args: k: Three primitive reciprocal coordinates. element: Chemical symbol. orbital: Shell letter (``"s"`` to ``"i"``), or ``"axial"`` (:data:`AXIAL_ORBITAL`). mapping_little_group: Indices into :attr:`rotations` of the little-group operations. spin_traces: With :attr:`spinor`, tr U_g of those operations (see :meth:`get_atomic_orbital_characters`). Returns: Complex array, one entry per little-group operation: the product of the permutation character of the element's atoms (:meth:`get_permutation_characters`) and the rotation character of the shell (:meth:`get_atomic_orbital_characters`). """ k = canonicalize_kpoint(k) little_rotations = self.rotations[mapping_little_group] little_translations = self.translations[mapping_little_group] permutation_matrices = self.get_permutation_reps_at_k(little_rotations, little_translations, k) a_o_charac = self.get_atomic_orbital_characters(little_rotations, orbital, spin_traces=spin_traces) perm_charac = self.get_permutation_characters(element, permutation_matrices) reducible_characters = perm_charac * a_o_charac return reducible_characters
[docs] def irreducible_decomposition(self, k: list[float, float, float], element: str, orbital: str ) -> tuple[NDArray[np.int_], object, dict[str, float], dict[str, str]]: """Decompose the crystal orbitals of one shell at ``k`` into irreps. The calculation behind every line ``crystod`` prints: the irreps of the little group of ``k`` from spgrep (double-valued with :attr:`spinor`, with the SU(2) matrices U_g spgrep built them with also giving the spin factor tr U_g of the reducible characters), the reducible characters from :meth:`calc_reducible_characters`, and the multiplicities from the character inner product. Args: k: Three primitive reciprocal coordinates. element: Chemical symbol, e.g. ``"Sc"``. orbital: Shell letter ``"s"`` to ``"i"``, e.g. ``"d"``, or ``"axial"`` (:data:`AXIAL_ORBITAL`) for one axial vector (Rx, Ry, Rz) per site -- the magnetic representation of ``crystod --element EL --axial``, whose irreps classify the spin configurations of the element's sites. Returns: ``(mapping_little_group, irreps, counts, labels)``: ``mapping_little_group`` are the indices into :attr:`rotations` of the little-group operations, ``irreps`` the spgrep irrep matrices, ``counts`` maps the generic key ``"irrep_i(dim)"`` of every irrep to its multiplicity (rounded to two decimals), and ``labels`` maps the same keys to the ISO-IR labels, or to CrystOD's double-valued names with :attr:`spinor` (:meth:`get_irrep_labels`). Raises: ValueError: An element that is not in the cell, an unknown shell letter, or ``"axial"`` with :attr:`spinor`. """ if orbital == AXIAL_ORBITAL and self.spinor: raise ValueError( "The axial-vector basis (Rx, Ry, Rz) is single-valued: it does " "not take double-valued (spinor) irreps." ) k = canonicalize_kpoint(k) # get irreps little_unitary_rotations = None spin_traces = None if self.spinor: # spgrep's spinor small irreps, with the rebuild of # crystod.wavecar_irreps for spgrep's spurious "not irreducible" # error at 2k != 0 from .wavecar_irreps import _spinor_irreps irreps, little_unitary_rotations, mapping_little_group = _spinor_irreps( self.primitive_cell.cell, self.rotations, self.translations, np.asarray(k, dtype=float), ) spin_traces = np.real(np.trace(little_unitary_rotations, axis1=1, axis2=2)) else: from .runtime_compat import get_spacegroup_irreps_from_primitive_symmetry irreps, mapping_little_group = get_spacegroup_irreps_from_primitive_symmetry( rotations=self.rotations, translations=self.translations, kpoint=k ) reducible_characters = self.calc_reducible_characters( k=k, element=element, orbital=orbital, mapping_little_group=mapping_little_group, spin_traces=spin_traces, ) # irreducible decomposition result = {} for i, irrep in enumerate(irreps): irrep_characters = get_character(irrep) num = np.dot( reducible_characters, np.conj(irrep_characters) ) / irrep.shape[0] result[f'irrep_{i+1}({irrep.shape[1]})'] = np.round(num.real, 2) irrep_labels = self.get_irrep_labels(k, irreps, mapping_little_group, spin_rotations=little_unitary_rotations) return mapping_little_group, irreps, result, irrep_labels
def make_irrep_table(crystal_orbital, irreps, mapping_little_group, irrep_labels): from pandas import DataFrame, set_option set_option('display.max_columns', 50) set_option('display.width', 1000) little_r_symbol = [crystal_orbital.seitz_symbols[idx] for idx in mapping_little_group] irrep_table = DataFrame(columns=little_r_symbol) for i, irrep in enumerate(irreps): generic_label = f"irrep_{i+1}({irrep.shape[1]})" resolved_label = irrep_labels[generic_label] row_label = generic_label if resolved_label == generic_label else f"{generic_label} = {resolved_label}" irrep_table.loc[row_label] = list(np.round(get_character(irrep), 4)) #irrep_table.to_csv("irrep_table.csv") irrep_table.to_excel("irrep_table.xlsx") print(irrep_table) def axial_irrep_items(bandreps, irreps, irrep_labels, k) -> list[tuple[str, float]]: """``(label, multiplicity)`` of the ``--axial`` report line at ``k``. The spin configurations are real, so at a time-reversal-invariant k point (2k a lattice vector) a complex-type irrep and the irrep with the conjugate characters form one physically irreducible space: they are printed once, under the ISOTROPY pair label with the real dimension (``GM3+GM4+(2)``), as in the survey of ``crystod-mag`` (whose helpers find the pairs, from the characters). Every other irrep is printed as in the orbital SALC. Sorted as :func:`sort_irrep_items` sorts, a pair by its first member. Args: bandreps: ``{"irrep_i(dim)": multiplicity}`` of :meth:`CrystalOrbital.irreducible_decomposition`, in irrep order. irreps: The spgrep irreps of the same call. irrep_labels: Its ``{"irrep_i(dim)": label}``. k: The k point, primitive reciprocal coordinates. """ keys = list(bandreps) labels = [irrep_labels[key] for key in keys] present = {index for index, key in enumerate(keys) if bandreps[key] > 0} pairs = {} if np.allclose(2.0 * np.asarray(k, dtype=float), np.rint(2.0 * np.asarray(k, dtype=float))): from .spin_basis import _conjugate_pairs pairs = _conjugate_pairs(irreps, labels, present) if pairs: from .spin_basis import _pair_label seconds = set(pairs.values()) items = [] for index in sorted(present): if index in seconds: continue label = labels[index] if index in pairs: label = _pair_label(label, labels[pairs[index]]) items.append((irrep_label_sort_key(labels[index]), label, bandreps[keys[index]])) return [(label, value) for _, label, value in sorted(items)] def sort_irrep_items(items): """Sort irrep labels by index, then parity (+ before -), then dimension.""" def sort_key(item): label, _ = item return irrep_label_sort_key(label) return sorted(items, key=sort_key) def main(argv: Optional[list[str]] = None) -> None: parser = build_parser() args = parser.parse_args(argv) if args.axial == (args.orbital is not None): parser.error("give one of --orbital ORB (an orbital shell) or --axial " "(the axial-vector basis Rx, Ry, Rz).") if args.axial and args.spinor: parser.error("--axial does not take --spinor: the axial-vector basis " "(a magnetic moment) is single-valued.") if args.orbital == AXIAL_ORBITAL: parser.error("--orbital takes a shell letter (s, p, d, f, g, h, i); the axial " "vector Rx, Ry, Rz is --axial.") orbital = AXIAL_ORBITAL if args.axial else args.orbital from .star_of_k import read_poscar_or_exit cell = read_poscar_or_exit(args.poscar) crystal_orbital = CrystalOrbital(cell=cell, symprec=args.tolerance, spinor=args.spinor) element_positions = crystal_orbital.get_target_element_positions(args.element) wyckoff_letters = [crystal_orbital.spglib_dataset['wyckoffs'][i] for i in element_positions] site_symmetry_symbols = [crystal_orbital.spglib_dataset['site_symmetry_symbols'][i] for i in element_positions] if args.kpoint is None: print(f"\n* Space group *\n {crystal_orbital.spglib_dataset['international']} ({crystal_orbital.spglib_dataset['number']})\n") print(f"* Element (number of atoms) *\n {args.element} ({len(wyckoff_letters)})\n") print(f"* Wyckoff letters and site symmetry letters *") print(f" {wyckoff_letters}\n {site_symmetry_symbols}\n") if args.axial: print(f"* Basis *\n {AXIAL_BASIS_LABEL}\n") else: print(f"* Atomic Orbital *\n {args.orbital}\n") if args.spinor: print(SPINOR_NAME_NOTE + "\n") print("* Crystal Orbitals *") kpoint_names, kpoints = crystal_orbital.get_special_points() for kpoint_name, kpoint in zip(kpoint_names, kpoints): try: mapping_little_group, irreps, bandreps, irrep_labels = crystal_orbital.irreducible_decomposition( k=kpoint, element=args.element, orbital=orbital, ) except Exception as error: print(f"ERROR at {kpoint_name} {kpoint}") print(f"{error}\n") continue if args.axial: sorted_bandreps = axial_irrep_items(bandreps, irreps, irrep_labels, kpoint) else: display_bandreps = {irrep_labels[key]: value for key, value in bandreps.items()} sorted_bandreps = sort_irrep_items( [(key, value) for key, value in display_bandreps.items() if value > 0] ) irreps_result = "+".join([f" {value} [{key}] " for key, value in sorted_bandreps]) little_group = crystal_orbital.get_little_group_symbol(kpoint) rounded_kpoint = format_kpoint(kpoint) print(f" k point (primitive): {kpoint_name} {rounded_kpoint}") print(f" little group of k : {little_group}") print(f" irreps : {irreps_result}") if crystal_orbital.spinor_label_note: for line in crystal_orbital.spinor_label_note.splitlines(): print(f" NOTE: {line}") print("") return print(f"\n* Space group *\n {crystal_orbital.spglib_dataset['international']} ({crystal_orbital.spglib_dataset['number']})\n") if args.axial: print(f"* Element (number of atoms) *\n {args.element} ({len(wyckoff_letters)})\n") else: print(f"* Orbital (number of atoms) *\n {args.element}_{args.orbital} ({len(wyckoff_letters)})\n") print(f"* Position *") print(f" wyckoff letters : {wyckoff_letters}") print(f" site symmetry letters: {site_symmetry_symbols}\n") if args.axial: print(f"* Basis *\n {AXIAL_BASIS_LABEL}\n") else: print(f"* Spinor *\n {args.spinor}\n") if args.spinor: print(SPINOR_NAME_NOTE + "\n") mapping_little_group, irreps, bandreps, irrep_labels = crystal_orbital.irreducible_decomposition( k=args.kpoint, element=args.element, orbital=orbital, ) display_bandreps = {irrep_labels[key]: value for key, value in bandreps.items()} kpoint_name = crystal_orbital.get_kpoint_name(args.kpoint) formatted_input_kpoint = format_kpoint(args.kpoint) if kpoint_name is None: print(f"* k point (primitive) *\n {formatted_input_kpoint}\n") else: print(f"* k point (primitive) *\n {kpoint_name} {formatted_input_kpoint}\n") if args.table: little_group = crystal_orbital.get_little_group_symbol(args.kpoint) print("* IrRep Table *") print(f" little group: {little_group}") print(" table:") make_irrep_table(crystal_orbital, irreps, mapping_little_group, irrep_labels) print("") print("* Atomic Band Irreducible Representations *") if args.axial: sorted_bandreps = axial_irrep_items(bandreps, irreps, irrep_labels, canonicalize_kpoint(args.kpoint)) else: sorted_bandreps = sort_irrep_items( [(key, value) for key, value in display_bandreps.items() if value > 0] ) irreps_result = "+".join([f" {value} [{key}] " for key, value in sorted_bandreps]) print(irreps_result) if crystal_orbital.spinor_label_note: for line in crystal_orbital.spinor_label_note.splitlines(): print(f" NOTE: {line}") print("") if __name__ == "__main__": main()