Source code for crystod.isotropy_subgroup

"""Isotropy subgroups of space-group irreps (crystod-group --parent).

Given a space group G and one of its irreps (ISO-IR label), a distortion that
transforms as that irrep reduces the symmetry to the isotropy subgroup

    H(eta) = { g in G : D(g) eta = eta }

where D is the full (induced) representation and eta the order parameter.
Distinct order-parameter directions (a,0,0), (a,a,0), ... give distinct
isotropy subgroups; this module enumerates all of them (the strata of the
representation), or resolves a user-given direction, and identifies each
subgroup with spglib (symbol, number, cell size, index, and the basis /
origin of its conventional cell in the parent convention).  With --kpoint
in place of --irrep, the enumeration runs over every irrep of one special
k point and is printed as a single table.  With --invariants, the invariant
polynomials of the irrep or of a direct sum (the Landau free-energy terms
and the lowest coupling term) are listed instead, computed by
``crystod.invariants``; with --secondary, the secondary order parameters of
a direction (``crystod.secondary_order_parameter``).  These free-energy
modes (--invariants, --degree, --order-parameter, --secondary) also report
the Landau and Lifshitz conditions of every irrep.

This is the offline counterpart of the ISOSUBGROUP tool of the ISOTROPY
Software Suite (https://iso.byu.edu), and is validated against its output.
If you use this feature, please cite: H. T. Stokes, S. van Orden and
B. J. Campbell, "Tool for Generating Isotropy Subgroups of Crystallographic
Space Groups", J. Appl. Cryst. 49, 1849-1853 (2016).

The order-parameter components refer to the real irrep basis produced by
spgrep; for multi-arm stars the components are grouped arm by arm. The basis
may differ from ISOTROPY's by an orthogonal change (direction labels can be
permuted/rotated relative to the ISOSUBGROUP listing), but the resulting
subgroups are convention-independent.
"""

from __future__ import annotations

import argparse
import re
from fractions import Fraction

import numpy as np

from .spacegroup_product import DEN, SIGMA, SpaceGroupIrrepAlgebra, _format_fraction

_PARAMETER_NAMES = "abcdefghijklmnopqrstuvwx"

# an order-parameter component "factor x parameter" (2a, 0.5a, 1/2a, 2*a);
# the sign is taken off before matching
_SCALED_PARAMETER = re.compile(
    r"(\d+/\d+|\d+(?:\.\d*)?|\.\d+)\*?([A-Za-z_][A-Za-z0-9_]*)"
)

# one signed term of a multi-term component (a+b-c-d, 2a-1/2b, -a+3*b)
_COMPONENT_TERM = re.compile(
    r"([+-])(\d+/\d+|\d+(?:\.\d*)?|\.\d+)?\*?([A-Za-z_][A-Za-z0-9_]*)"
)

# space-group types that exist as enantiomorphic pairs: the stabilizers of
# the mirror-image order parameters of one stratum are of partner types, so
# either member may appear as the representative of the stratum
ENANTIOMORPHIC_PAIRS = {
    76: 78, 78: 76, 91: 95, 95: 91, 92: 96, 96: 92, 144: 145, 145: 144,
    151: 153, 153: 151, 152: 154, 154: 152, 169: 170, 170: 169, 171: 172,
    172: 171, 178: 179, 179: 178, 180: 181, 181: 180, 212: 213, 213: 212,
}


# --------------------------------------------------------------- representation


def _irrep_or_pair_member(algebra: SpaceGroupIrrepAlgebra, label: str):
    """The tabulated irrep record behind an ``--irrep`` label.

    Besides the ISO-IR labels this accepts the pair labels that the tables
    print for complex-type irreps (``H1H2``, ``P1PA1``, ``M1+M4+``): a pair
    label is split into two tabulated names, and the member listed first in
    the ISO-IR tables is returned -- the member ``kpoint_irrep_tables``
    builds the pair from, so the order-parameter components read the same.

    Args:
        algebra: The ``SpaceGroupIrrepAlgebra`` of the space group.
        label: The label as given.

    Returns:
        ``(irrep, pair)``: the irrep record, and ``None`` for a tabulated
        label or the two member names of a pair label.  Whether the two
        members are complex-conjugate partners is decided by the caller,
        once the representation is built.

    Raises:
        SystemExit: The label is neither tabulated nor two tabulated names
            joined (the message of ``find_irrep``).
    """
    try:
        return algebra.find_irrep(label), None
    except SystemExit as missing:
        names = [
            irrep.name for irreps in algebra.irreps_by_kname.values() for irrep in irreps
        ]
        for cut in range(1, len(label)):
            first, second = label[:cut], label[cut:]
            if first != second and first in names and second in names:
                member = min(first, second, key=names.index)
                return algebra.find_irrep(member), (first, second)
        raise missing


[docs] class InducedRepresentation: """Full (induced) irrep of a space group as explicit real matrices. The representation of the order parameter of one ISO-IR irrep, used by ``crystod-group --parent`` (through ``IsotropyAnalyzer``) and by the symmetry-mode analysis. The basis index is ``(arm a, small-irrep row p)`` and the group elements are parametrized as (coset representative ``i``, lattice translation ``t``):: D(g_i + t) = T(t) B_i, T(t) = diag_a exp(SIGMA*2j*pi q_a.t) (x) 1_d The small-irrep matrices come from spgrep and are matched to the tabulated ISO-IR characters (with an origin-shift search where the conventions differ); the induced blocks are verified against the independently induced characters. The matrices are finally brought to the real, physically irreducible form: real-type irreps by a similarity transform, complex- and pseudoreal-type irreps as the doubled real form of ``D + D*`` (the paired ISOTROPY entries such as ``P1P2``). Args: algebra: The ``SpaceGroupIrrepAlgebra`` of the space group. irrep_label: ISO-IR irrep label, e.g. ``"R4+"``, or the pair label of a complex-type irrep as the tables print it (``"H1H2"``, ``"P1PA1"``): an alias of the doubled real form, built from the member listed first in the ISO-IR tables (the member the ``--kpoint`` table builds the pair from). Attributes: algebra: The algebra the representation was built from. irrep: The tabulated irrep record (``name``, ``dim``, ``kpname``); for a pair label, the record of the member it was built from. k: k vector of the irrep (primitive basis, units of ``1/DEN``). arms: Star arms, shape ``(n_arms, 3)``; ``representatives`` holds the coset-representative index generating each arm. n_arms: Number of star arms. dim_small: Dimension of the small irrep. dimension: Dimension of the order parameter (``n_arms * dim_small``, doubled for complex- and pseudoreal-type irreps). blocks: The matrices ``B_i`` of the coset representatives, before realification. elements: All distinct group elements as ``(i, t, matrix)`` with the real matrix of ``D(g_i + t)``; ``t`` runs over the translation grid of period ``grid_n``. doubled: ``True`` when the physically irreducible form is ``D + D*``; ``fs_type`` then names the type (``"complex"`` or ``"pseudoreal"``). grid_n: Period of the lattice-translation grid on which the matrices are distinct. Raises: SystemExit: Unknown irrep label, a pair label whose two members are not complex-conjugate partners, or a tabulated entry that cannot be matched to any spgrep small irrep. Example: >>> from crystod import group >>> algebra = group.SpaceGroupIrrepAlgebra("Pm-3m") >>> rep = group.InducedRepresentation(algebra, "R4+") >>> rep.dimension, rep.n_arms, rep.dim_small, rep.label, rep.doubled (3, 1, 3, 'R4+', False) """ def __init__(self, algebra: SpaceGroupIrrepAlgebra, irrep_label: str): self.algebra = algebra self.irrep, pair = _irrep_or_pair_member(algebra, irrep_label) kpname = self.irrep.kpname if kpname not in algebra.k_by_kname: raise SystemExit(f"ERROR: unknown k point for irrep {irrep_label}.") self.k = algebra.k_by_kname[kpname] self.arms, self.representatives = algebra.star(kpname) self.n_arms = len(self.arms) small_matrices, little = self._small_matrices() self.little = little self.dim_small = small_matrices[next(iter(small_matrices))].shape[0] self.dimension = self.n_arms * self.dim_small self.blocks = self._induce(small_matrices) self._verify() # materialize all distinct elements (coset rep i, lattice translation t) self.elements = [ (i, t, self.translation_phases(t)[:, None] * self.blocks[i]) for i in range(algebra.n_ops) for t in self._translation_grid() ] self._realify() # a pair label names a complex-conjugate pair, in either order; the # pair is recognized by the representation, as in --kpoint if pair is not None and self.label != "".join(sorted(pair)): sg = algebra.sg_type raise SystemExit( f'ERROR: irrep "{irrep_label}" is not tabulated for space group ' f"{sg.international_short} (No. {sg.number}): {pair[0]} and " f"{pair[1]} are not a complex-conjugate pair (the order " f"parameter of {self.irrep.name} is {self.label})." ) # -- small irrep matrices matched to the ISO-IR label def _small_matrices(self): algebra, irrep = self.algebra, self.irrep from .runtime_compat import get_spacegroup_irreps_from_primitive_symmetry try: irreps, mapping = get_spacegroup_irreps_from_primitive_symmetry( rotations=algebra.rotations, translations=np.array(algebra.translations, dtype=float) / DEN, kpoint=np.array(self.k, dtype=float) / DEN, ) except Exception as exc: raise SystemExit( f"ERROR: spgrep could not compute the small irreps at " f"{irrep.kpname}: {exc}" ) from exc mapping = [int(m) for m in np.asarray(mapping).ravel()] # reference characters of the requested irrep (spgrep-refined) table = {int(key) - 1: complex(v) for key, v in irrep.characters.items()} try: refined = algebra._refine_small_characters(np.asarray(self.k), table) except SystemExit: refined = None if refined is None: # defensive fallback: the same conj+wrap identification as # _refine_small_characters, extended by an origin-shift gauge # e^(2 pi i k.(W-1)x0) (not expected to be needed with the ISO-IR # tables, whose asymmetric points are resolved inside # _refine_small_characters) refined = self._match_with_origin_shift(table) if refined is None: raise SystemExit( f"ERROR: the tabulated characters of {irrep.name} are not those " "of a single allowed small irrep; isotropy-subgroup analysis is " "not available for this entry." ) matches = [] for matrices in irreps: matrices = np.asarray(matrices) chi = {op: complex(np.trace(matrices[j])) for j, op in enumerate(mapping)} if set(chi) == set(refined) and all( abs(chi[op] - refined[op]) < 1e-3 for op in refined ): matches.append(matrices) if len(matches) != 1: raise SystemExit( f"ERROR: could not match {irrep.name} to a unique computed small " f"irrep ({len(matches)} candidates); possibly a paired (physically " "combined) irrep, which is not supported yet." ) matrices = matches[0] small = {op: np.asarray(matrices[j]) for j, op in enumerate(mapping)} # when 2k = 0 (mod reciprocal lattice) the translation phases are # real, so a real small irrep gives a real induced rep in the natural # arm-blocked basis (nice, arm-grouped order-parameter components) if np.all((2 * np.asarray(self.k)) % DEN == 0): small = _realify_matrix_set(small) or small return small, sorted(mapping) def _match_with_origin_shift(self, table: dict) -> dict | None: """Identify the tabulated small irrep among the spgrep candidates up to an origin-shift gauge. The tabulated ISO-IR characters and the spgrep candidates are related by the conj+wrap rule of ``SpaceGroupIrrepAlgebra._refine_small_characters``:: chi_spgrep(op) exp(2 pi i k.((W - 1) x0)) = conj(chi_table(op)) exp(2 pi i k.delta_op) where ``delta_op`` is the wrapped-away lattice translation and ``x0`` an origin shift on the 1/8 grid (``x0 = 0`` first, where the rule reduces to ``_refine_small_characters``). For each shift only a unique matching candidate is accepted. A match found only at ``x0 != 0`` is accepted with a warning (``warnings.warn``) naming the shift and the label, since an origin shift can map the characters of one irrep onto those of another. Args: table: Tabulated ISO-IR small characters ``{op_index: chi}``. Returns: The matched candidate's exact (gauge-consistent) spgrep characters, or ``None`` when no shift gives a unique match. """ algebra = self.algebra k_int = np.asarray(self.k) k = np.asarray(self.k, dtype=float) / DEN try: candidates = algebra.computed_irreps_at(k_int) except SystemExit: return None candidates = [c for c in candidates if set(c["chi"]) == set(table)] if not candidates: return None reference = { op: np.conj(value) * algebra._wrap_phase(k_int, op) for op, value in table.items() } shifts = [ np.array([x1, x2, x3]) / 8.0 for x1 in range(8) for x2 in range(8) for x3 in range(8) ] for x0 in shifts: matched = [] for candidate in candidates: chi = candidate["chi"] ok = True for op, value in reference.items(): W = algebra.rotations[op] gauge = np.exp(2j * np.pi * float(k @ ((W - np.eye(3)) @ x0))) if abs(chi[op] * gauge - value) > 5e-3: ok = False break if ok: matched.append(chi) if len(matched) == 1: if np.any(x0): # an origin shift can turn one irrep's characters into # another's, so a match away from x0 = 0 is reported import warnings warnings.warn( f"{self.irrep.name}: the tabulated characters were " "matched to a spgrep small irrep only after an origin " f"shift x0 = ({', '.join(str(Fraction(v).limit_denominator(8)) for v in x0)}); " "check that the label refers to the intended irrep.", stacklevel=2, ) return {op: complex(v) for op, v in matched[0].items()} return None def _induce(self, small: dict) -> list[np.ndarray]: algebra = self.algebra d, m = self.dim_small, self.n_arms arm_index = {tuple(arm): a for a, arm in enumerate(self.arms)} blocks = [] for i in range(algebra.n_ops): matrix = np.zeros((m * d, m * d), dtype=np.complex128) for b, s_b in enumerate(self.representatives): # row arm: q_a = q_b . W_i^{-1} q_a = tuple((self.arms[b] @ algebra.inverse_rotations[i]) % DEN) a = arm_index[q_a] s_a = self.representatives[a] W_sa_inv = algebra.inverse_rotations[s_a] v_sa_inv = -W_sa_inv @ algebra.translations[s_a] # h = s_a^{-1} (g_i s_b) W_gs = algebra.rotations[i] @ algebra.rotations[s_b] v_gs = algebra.rotations[i] @ algebra.translations[s_b] + algebra.translations[i] W_h = W_sa_inv @ W_gs tau_h = W_sa_inv @ v_gs + v_sa_inv mindex = algebra._rotation_index[algebra._key(W_h)] if mindex not in small: raise SystemExit("ERROR: broken induction bookkeeping.") t_extra = tau_h - algebra.translations[mindex] if np.any(t_extra % DEN != 0): raise SystemExit("ERROR: non-lattice residue in induction.") phase = np.exp( SIGMA * 2j * np.pi * float(self.k @ (t_extra // DEN)) / DEN ) matrix[a * d : (a + 1) * d, b * d : (b + 1) * d] = phase * small[mindex] blocks.append(matrix) return blocks
[docs] def translation_phases(self, t: np.ndarray) -> np.ndarray: """Diagonal of ``T(t)`` for a lattice translation. Args: t: Lattice translation, integer vector in primitive units. Returns: The phases ``exp(SIGMA * 2j * pi * q_a . t)``, one entry per (arm, small-irrep row) in the basis order of ``blocks``. """ phases = np.exp( SIGMA * 2j * np.pi * (self.arms @ np.asarray(t, dtype=np.int64)) / DEN ) return np.repeat(phases, self.dim_small)
def _realify(self) -> None: """Transform to the real physically irreducible form. Real-type irreps get a similarity transform to real matrices; complex- and pseudoreal-type irreps (Frobenius-Schur indicator 0 / -1, e.g. at non-symmorphic zone-boundary points) get the doubled real form of D + D* -- the representation of the physical (real) order parameter, matching the paired entries of ISOTROPY (P1P2, ...).""" self.doubled = False if all(np.allclose(matrix.imag, 0, atol=1e-8) for _, _, matrix in self.elements): self.elements = [ (i, t, matrix.real.copy()) for i, t, matrix in self.elements ] return # Frobenius-Schur indicator over the finite factor group: # +1 real type, 0 complex type, -1 pseudoreal type fs = float( np.mean([np.trace(matrix @ matrix) for _, _, matrix in self.elements]).real ) if fs < 0.5: # complex or pseudoreal type: realification (Re v, Im v), i.e. # the real form of D + D* (physically irreducible, dimension 2n); # permuted to arm-major component order (arm 1: Re rows, Im rows; # arm 2: ...) so the direction labels keep the arm grouping n = self.dimension d, m = self.dim_small, self.n_arms perm = np.zeros((2 * n, 2 * n)) slot = 0 for a in range(m): for p in range(d): perm[slot, a * d + p] = 1.0 # Re(arm a, row p) slot += 1 for p in range(d): perm[slot, n + a * d + p] = 1.0 # Im(arm a, row p) slot += 1 self.elements = [ ( i, t, perm
[docs] @ np.block( [[matrix.real, -matrix.imag], [matrix.imag, matrix.real]] ) @ perm.T, ) for i, t, matrix in self.elements ] self.doubled = True self.fs_type = "complex" if abs(fs) < 0.5 else "pseudoreal" self.dimension *= 2 return # real (orthogonal) form via an antilinear real structure: with the # intertwiner S (D* S = S D, from the group average), J v = S* v* # commutes with every D(g) (conjugate the intertwining relation); # for a real-type irrep S S* = c > 0, so J^2 = 1 after normalization, # and the fixed points of J span a real basis in which every D(g) is # real. (J v = S v* would only work when S^2 is a scalar.) rng = np.random.default_rng(7) n = self.dimension A = rng.normal(size=(n, n)) + 1j * rng.normal(size=(n, n)) S = np.zeros((n, n), dtype=np.complex128) for _, _, D in self.elements: S += np.conj(D) @ A @ D.conj().T if np.linalg.norm(S) < 1e-8 * len(self.elements) * np.linalg.norm(A): raise SystemExit( f"ERROR: could not realify {self.irrep.name} (internal: the " "Frobenius-Schur indicator says real type, but the averaged " "intertwiner vanishes)." ) c_matrix = S @ np.conj(S) c = c_matrix[0, 0] if not np.allclose(c_matrix, c * np.eye(n), atol=1e-6 * max(1, abs(c))) or c.real <= 0: raise SystemExit( f"ERROR: could not realify {self.irrep.name} (internal bug: " "the Frobenius-Schur indicator says real type)." ) S_bar = np.conj(S) / np.sqrt(c.real) # real basis: orthonormalize J-fixed vectors v + S* v*. Standard # basis vectors (and i x them) are tried first, so the real basis # stays adapted to the (arm, row) channels -- sparse direction labels trials = [ vec for j in range(n) for vec in (np.eye(n)[j] + 0j, 1j * np.eye(n)[j]) ] + [rng.normal(size=n) + 1j * rng.normal(size=n) for _ in range(20 * n)] basis: list[np.ndarray] = [] for v in trials: if len(basis) == n: break w = v + S_bar @ np.conj(v) for prior in basis: w = w - prior * np.real(np.vdot(prior, w)) norm = np.linalg.norm(w) if norm > 1e-3: basis.append(w / norm) if len(basis) < n: raise SystemExit(f"ERROR: could not realify {self.irrep.name}.") T = np.column_stack(basis) if not np.allclose(T.conj().T @ T, np.eye(n), atol=1e-6): raise SystemExit( f"ERROR: could not realify {self.irrep.name} (the real basis " "is not unitary)." ) T_inv = np.linalg.inv(T) new_elements = [] for i, t, matrix in self.elements: transformed = T_inv @ matrix @ T if not np.allclose(transformed.imag, 0, atol=1e-6): raise SystemExit(f"ERROR: could not realify {self.irrep.name}.") new_elements.append((i, t, transformed.real.copy())) self.elements = new_elements def conjugate_partner(self) -> str | None: """ISO-IR label of the complex-conjugate partner irrep. The partner lives at the same k star, or at the -k star for +-k pairs such as P/PA; it is the other tabulated irrep with the same physically irreducible real form ``D + D*``, i.e. the same real part of the character on every group element, lattice translations included. (The characters of the coset representatives alone do not decide it: at H of P6_3/m, P of I4/mcm or K of P3 several irreps share them and differ only on the translations.) Returns: The partner label, or ``None`` when the irrep is self-conjugate or no partner is tabulated. """ if "_conjugate_partner" not in self.__dict__: self._conjugate_partner = self._find_conjugate_partner() return self._conjugate_partner
def _real_character(self, arms: np.ndarray, per_arm: np.ndarray) -> np.ndarray: """Re chi(g_i + t) on the translation grid, from the arm-resolved characters ``per_arm[i, a]`` of the coset representatives.""" grid = np.array(self._translation_grid(), dtype=np.int64) phases = np.exp(SIGMA * 2j * np.pi * (grid @ np.asarray(arms).T) / DEN) return (per_arm @ phases.T).real def _find_conjugate_partner(self) -> str | None: d = self.dim_small own = self._real_character( self.arms, np.array([ [np.trace(block[a * d : (a + 1) * d, a * d : (a + 1) * d]) for a in range(self.n_arms)] for block in self.blocks ]), ) knames = [self.irrep.kpname] + [ kname for kname in self.algebra.irreps_by_kname if kname != self.irrep.kpname and np.array_equal( (-np.asarray(self.algebra.k_by_kname[self.irrep.kpname])) % DEN, np.asarray(self.algebra.k_by_kname[kname]) % DEN, ) ] unresolved = [] for kname in knames: for other in self.algebra.irreps_by_kname[kname]: if other.name == self.irrep.name: continue try: arms_other, C_other = self.algebra.induced_characters(other) except SystemExit: unresolved.append(other) continue # the real part is blind to the orientation, so a tabulated # entry matched in the conjugate gauge needs no second test if np.allclose( self._real_character(arms_other, C_other), own, atol=1e-6 ): return other.name # fallback (conjugate-gauge tabulations, e.g. P/PA of I-42d): compare # the tabulated small characters directly table_self = { int(key) - 1: complex(v) for key, v in self.irrep.characters.items() } for other in unresolved: table_other = { int(key) - 1: complex(v) for key, v in other.characters.items() } if set(table_other) == set(table_self) and all( abs(table_other[op] - np.conj(table_self[op])) < 1e-3 for op in table_self ): return other.name return None @property def label(self) -> str: """Irrep label; the ISOTROPY-style pair label (``P1P2``) when doubled.""" if self.doubled: partner = self.conjugate_partner() if partner is not None and self.fs_type == "complex": return "".join(sorted([self.irrep.name, partner])) return self.irrep.name @property def arm_chunks(self) -> list[int]: """Number of order-parameter components per star arm. ISOTROPY separates arms by ``;`` and components within one arm by ``,`` in the direction labels. """ per_arm = self.dim_small * (2 if self.doubled else 1) return [per_arm] * self.n_arms def _translation_grid(self) -> list[np.ndarray]: denominators = [int(DEN // np.gcd(int(v), DEN)) if v else 1 for v in self.k] N = 1 for d in denominators: N = int(np.lcm(N, d)) self.grid_n = N return [ np.array([t1, t2, t3], dtype=np.int64) for t1 in range(N) for t2 in range(N) for t3 in range(N) ] def _verify(self) -> None: """Traces must reproduce the validated induced characters.""" try: arms, C = self.algebra.induced_characters(self.irrep) except SystemExit: # conjugate-gauge tabulation (P/PA pairs): the tabulated induced # characters are unavailable; the induction itself is exact return for i in (0, min(3, self.algebra.n_ops - 1), self.algebra.n_ops - 1): expected = np.sum(C[i]) actual = np.trace(self.blocks[i]) if abs(expected - actual) > 1e-6: raise SystemExit( "ERROR: induced-matrix construction disagrees with the " "validated induced characters (internal bug)." ) # -- group elements of the image, with bookkeeping
[docs] def image_elements(self): """All group elements of the representation. Returns: The ``elements`` list, one ``(i, t, matrix)`` triple per group element (coset-representative index, lattice translation, real matrix). """ return self.elements
@property def rep_cache(self) -> _RepCache: """The element matrices as arrays (built on first use, then kept).""" return _rep_cache(self)
class _ComputedIrrepInfo: """Shim irrep record for a representation at a non-tabulated k point.""" def __init__(self, name: str, kpname: str, dim: int): self.name = name self.kpname = kpname self.dim = dim class ComputedInducedRepresentation(InducedRepresentation): """Full induced irrep at a NON-tabulated k point (symmetry line, plane or general point on the 1/24 grid). The small-irrep matrices come from spgrep at the exact k (an entry of ``SpaceGroupIrrepAlgebra.computed_irreps_at``), the ISO-IR (Miller-Love) name from the line-labeling machinery. Everything downstream of the small matrices -- induction over the star, the translation grid, the physically-irreducible realification -- is inherited unchanged. """ def __init__(self, algebra: SpaceGroupIrrepAlgebra, k_int, small: dict, name: str, kpname: str, partner_name: str | None = None): self.algebra = algebra self.k = np.mod(np.asarray(k_int, dtype=np.int64), DEN) self.arms, self.representatives = algebra._star_of_vector(self.k) self.n_arms = len(self.arms) self.irrep = _ComputedIrrepInfo(name, kpname, int(small["dim"])) self._partner_name = partner_name self._small_chi = dict(small["chi"]) matrices = {op: np.asarray(m) for op, m in small["small"].items()} if np.all((2 * self.k) % DEN == 0): matrices = _realify_matrix_set(matrices) or matrices self.little = sorted(matrices) self.dim_small = matrices[next(iter(matrices))].shape[0] self.dimension = self.n_arms * self.dim_small self.blocks = self._induce(matrices) self._verify() self.elements = [ (i, t, self.translation_phases(t)[:, None] * self.blocks[i]) for i in range(algebra.n_ops) for t in self._translation_grid() ] self._realify() def _verify(self) -> None: """Traces must reproduce the characters induced from the same small irrep through the independent character-only route.""" arms, C = self.algebra.induced_characters_at( self.k, {"chi": self._small_chi} ) for i in (0, min(3, self.algebra.n_ops - 1), self.algebra.n_ops - 1): if abs(np.sum(C[i]) - np.trace(self.blocks[i])) > 1e-6: raise SystemExit( "ERROR: induced-matrix construction at a non-tabulated " "k point disagrees with the induced characters " "(internal bug)." ) def conjugate_partner(self) -> str | None: return self._partner_name @classmethod def from_isoir(cls, algebra: SpaceGroupIrrepAlgebra, k_int, small: dict, name: str, kpname: str, partner_name: str | None = None): """Build the representation from the bundled ISO-IR matrices. The CIR tables store, for every line irrep, the full-star matrices with parametrized k vectors, so the order-parameter basis is the ISOTROPY one (up to the phase gauge of the realification) and the arm order is the tabulated one -- deterministic across spgrep versions. Raises LookupError when the entry cannot be used (the caller falls back to the spgrep-basis construction). """ from .isoir import load_isoir_irreps, minus_k_base minus = False base = name tabulated_base = minus_k_base(name, algebra.sg_type.number) if tabulated_base is not None: # the -k partner of a tabulated star (PA1, LE1, DU6): the # tabulated entry sits at the -k star minus = True base = tabulated_base entries = [ ir for ir in load_isoir_irreps(algebra.sg_type.number) if ir.label == base and not ir.special ] if not entries: raise LookupError(f"no ISO-IR entry for {name}") entry = entries[0] M = algebra.primitive_matrix M_inv = np.linalg.inv(M) sign = -1 if minus else 1 arms_star, _ = algebra._star_of_vector( np.mod(np.asarray(k_int, dtype=np.int64), DEN) ) fit = None for arm in arms_star: k_conv = sign * (np.asarray(arm, dtype=float) / DEN) @ M_inv matched = entry.match_k(k_conv) if matched is not None and matched[0] == 0: fit = matched[1] break if fit is None: raise LookupError(f"no ISO-IR parametrization for {name}") karms_conv = np.array( [entry.arm_k(a, fit) for a in range(entry.narms)] ) arms_scaled = sign * (karms_conv @ M) * DEN arms = np.rint(arms_scaled).astype(np.int64) if not np.allclose(arms_scaled, arms, atol=1e-6): raise LookupError(f"ISO-IR arms of {name} leave the 1/{DEN} grid") arms = np.mod(arms, DEN) arm_set = {tuple(int(v) for v in a) for a in arms} if arm_set != {tuple(int(v) % DEN for v in a) for a in arms_star}: raise LookupError(f"ISO-IR star of {name} disagrees") # conventional operations in the algebra's operation order table_R = [ np.rint(np.asarray(sym.R, dtype=float)).astype(np.int64) for sym in algebra.table.symmetries ] if not all( np.array_equal(table_R[i], algebra.rotations[i]) for i in range(algebra.n_ops) ): raise LookupError("conventional-table order mismatch") blocks = [] for i in range(algebra.n_ops): j = entry.find_operator(table_R[i]) if j is None: raise LookupError(f"operator missing from ISO-IR {name}") v_conv = M @ (np.array(algebra.translations[i], dtype=float) / DEN) dt = v_conv - entry.translations[j] phases = np.exp(2j * np.pi * karms_conv @ (dt + entry.irtrans[j])) if entry.small_dim > 1 and len(phases) > 1: # Several arms with a multi-dimensional small irrep: the # bundled matrices carry six digits, which is not enough for # the realification of some of these stars (DT of the # hexagonal groups), so the spgrep basis is kept for all of # them (the callers fall back on LookupError). raise LookupError( f"ISO-IR matrices of {name} are not used for a " "multi-arm star with a multi-dimensional small irrep" ) block = phases[:, None] * entry.matrices[j] # ISO-IR phase convention exp(+2 pi i k.t) is the conjugate of # the spgrep convention this machinery uses throughout blocks.append(np.conj(block) if not minus else block) rep = cls.__new__(cls) rep.algebra = algebra rep.k = arms[0].copy() rep.arms = arms rep.n_arms = len(arms) rep.representatives = None rep.irrep = _ComputedIrrepInfo(name, kpname, int(small["dim"])) rep._partner_name = partner_name rep._small_chi = dict(small["chi"]) rep.dim_small = entry.small_dim rep.dimension = entry.dim rep.blocks = blocks try: rep._verify() except SystemExit: raise LookupError( f"ISO-IR matrices of {name} disagree with the computed " "characters" ) rep.elements = [ (i, t, rep.translation_phases(t)[:, None] * rep.blocks[i]) for i in range(algebra.n_ops) for t in rep._translation_grid() ] rep._realify() return rep
[docs] class CoupledRepresentation: """Direct sum of several induced irreps (coupled order parameters). A distortion condensing several irreps simultaneously transforms as this reducible representation; its isotropy subgroups are the stabilizers of the coupled order parameter ``(eta_1, eta_2, ...)``. This is what ``crystod-group --parent SG --irrep X3- X2+`` analyzes. The components group irrep by irrep (then arm by arm within each irrep), and because the matrices are block diagonal every fixed subspace is a direct sum of per-irrep subspaces: the amplitudes of different irreps are always independent free parameters. Args: algebra: The ``SpaceGroupIrrepAlgebra`` of the space group. irrep_labels: ISO-IR labels of the coupled irreps, e.g. ``["X3-", "X2+"]``. Attributes: parts: The ``InducedRepresentation`` of every irrep, in input order. dims: Dimension of every part; ``dimension`` is their sum. name: The combined label, e.g. ``"X3- + X2+"``. grid_n: Period of the common lattice-translation grid (least common multiple of the parts' periods). elements: All distinct group elements as ``(i, t, matrix)`` with the block-diagonal real matrix. Raises: SystemExit: A label is not tabulated for this space group. """ def __init__(self, algebra: SpaceGroupIrrepAlgebra, irrep_labels: list[str]): self._assemble( algebra, [InducedRepresentation(algebra, label) for label in irrep_labels] )
[docs] @classmethod def from_parts(cls, algebra: SpaceGroupIrrepAlgebra, parts: list): """Direct sum of already-built representations. Args: algebra: The ``SpaceGroupIrrepAlgebra`` the parts were built from. parts: ``InducedRepresentation`` objects (or anything with ``elements``, ``dimension``, ``grid_n`` and ``label``). Returns: A ``CoupledRepresentation`` identical to the one built from the parts' labels (``InducedRepresentation`` is deterministic). """ coupled = cls.__new__(cls) coupled._assemble(algebra, list(parts)) return coupled
def _assemble(self, algebra: SpaceGroupIrrepAlgebra, parts: list) -> None: self.algebra = algebra self.parts = parts self.dims = [part.dimension for part in self.parts] self.dimension = sum(self.dims) self.name = " + ".join(part.label for part in self.parts) # combined translation grid: lcm of the parts' grids (each part's # matrices are periodic in t with its own grid period) N = 1 for part in self.parts: N = int(np.lcm(N, part.grid_n)) self.grid_n = N lookups = [ {(i, tuple(int(x) for x in t)): matrix for i, t, matrix in part.elements} for part in self.parts ] self.elements = [] for i in range(algebra.n_ops): for t1 in range(N): for t2 in range(N): for t3 in range(N): t = np.array([t1, t2, t3], dtype=np.int64) blocks = [ lookups[j][(i, tuple(int(x) for x in t % part.grid_n))] for j, part in enumerate(self.parts) ] self.elements.append((i, t, _block_diag(blocks)))
[docs] def image_elements(self): """All group elements of the coupled representation. Returns: The ``elements`` list of ``(i, t, matrix)`` triples. """ return self.elements
@property def rep_cache(self) -> _RepCache: """The element matrices as arrays (built on first use, then kept).""" return _rep_cache(self)
class _RepCache: """The element matrices of one real representation as arrays. Built once per representation (``rep_cache`` of ``InducedRepresentation`` and ``CoupledRepresentation``) and shared by the fast stratum enumeration, the orbit and the stabilizer computations. Attributes: elements: The ``(i, t, matrix)`` list the arrays were built from. E: All element matrices, shape ``(G, n, n)``, in ``elements`` order. distinct: Index (into ``E``) of the first element of every distinct matrix, in order of first occurrence. Ed: ``E[distinct]``. n: The dimension of the representation. """ def __init__(self, elements): self.elements = elements self.E = np.array([matrix for _, _, matrix in elements], dtype=float) self.n = self.E.shape[1] seen: dict[bytes, int] = {} for g, matrix in enumerate(self.E): seen.setdefault(_projector_key(matrix), g) self.distinct = np.array(sorted(seen.values()), dtype=np.int64) self.Ed = self.E[self.distinct] def fixes(self, basis: np.ndarray, distinct: bool = False) -> np.ndarray: """Mask of the elements fixing every column of ``basis`` (1e-6).""" E = self.Ed if distinct else self.E D = np.einsum("gab,br->gar", E, basis) - basis[None] return np.max(np.abs(D), axis=(1, 2)) < 1e-6 def stabilizer_mask(self, projector: np.ndarray) -> np.ndarray: """``np.allclose(matrix @ projector, projector, atol=1e-6)`` for every element (the test of ``IsotropyAnalyzer.stabilizer_of``).""" tolerance = 1e-6 + 1e-5 * np.abs(projector) return np.all( np.abs(self.E @ projector - projector[None]) <= tolerance[None], axis=(1, 2), ) def vector_stabilizer_mask(self, vector: np.ndarray) -> np.ndarray: """``np.allclose(matrix @ vector, vector, atol=1e-6)`` for every element.""" tolerance = 1e-6 + 1e-5 * np.abs(vector) return np.all(np.abs(self.E @ vector - vector[None]) <= tolerance[None], axis=1) def orbit(self, projector: np.ndarray) -> dict[bytes, np.ndarray]: """The distinct images ``g P g^T`` (key -> projector), in the order of the elements.""" images = np.einsum("gab,bc,gdc->gad", self.Ed, projector, self.Ed) orbit: dict[bytes, np.ndarray] = {} for image in images: orbit.setdefault(_projector_key(image), image) return orbit def _rep_cache(representation, elements=None) -> _RepCache: """The ``_RepCache`` of a representation, built on first use and kept on the object (rebuilt when its ``elements`` list was replaced).""" if elements is None: elements = representation.image_elements() cache = getattr(representation, "_rep_cache_data", None) if cache is None or cache.elements is not elements or len(cache.E) != len(elements): cache = _RepCache(elements) try: representation._rep_cache_data = cache except AttributeError: # an object without attribute storage pass return cache def _block_diag(blocks: list[np.ndarray]) -> np.ndarray: n = sum(b.shape[0] for b in blocks) matrix = np.zeros((n, n)) row = 0 for b in blocks: matrix[row : row + b.shape[0], row : row + b.shape[1]] = b row += b.shape[0] return matrix # ------------------------------------------------------------------ stabilizers def _nullspace(matrix: np.ndarray, tol: float = 1e-8) -> np.ndarray: _, sing, Vh = np.linalg.svd(matrix) rank = int(np.sum(sing > tol)) if len(sing) else 0 return Vh[rank:].T.conj() def _projector(basis: np.ndarray) -> np.ndarray: if basis.shape[1] == 0: return np.zeros((basis.shape[0], basis.shape[0])) Q, _ = np.linalg.qr(basis) return Q @ Q.T.conj() def invariant_parent_lattice(algebra: SpaceGroupIrrepAlgebra) -> np.ndarray: """A primitive lattice (rows) of the group of ``algebra`` with its full point symmetry (the average metric of a generic one over the rotations).""" g0 = np.diag([1.0, 1.07, 1.13]) g = np.zeros((3, 3)) for W in algebra.rotations: g += W.T @ g0 @ W g /= algebra.n_ops # rows a_i with a_i . a_j = g_ij: the lower-triangular Cholesky # factor itself (L L^T = g), NOT its transpose return np.linalg.cholesky(g) def sublattice_operations(algebra: SpaceGroupIrrepAlgebra, B, chosen): """Parent operations re-expressed in the basis of a sublattice. Shared by ``IsotropyAnalyzer.subgroup_of`` and the group-subgroup correlation of ``crystod.correlation`` (``crystod-group --correlate --supergroup-poscar``). Args: algebra: The ``SpaceGroupIrrepAlgebra`` of the parent. B: Sublattice basis (rows, parent primitive units, integers). chosen: ``(i, t)`` pairs, one per operation: coset-representative index ``i`` and lattice translation ``t`` (parent primitive units). Returns: ``(rotations, translations, parent_translations)``: ``W = B^-T R_i B^T`` (integers), ``v = B^-T (tau_i / DEN + t)`` reduced into ``[0, 1)``, and the lattice translations ``t'`` (parent primitive units, ``t`` shifted by a lattice vector of the sublattice) for which ``B^-T (tau_i / DEN + t')`` is exactly that reduced ``v``. Raises: SystemExit: An operation does not map the sublattice onto itself. """ B = np.asarray(B, dtype=np.int64) B_inv_T = np.linalg.inv(B.T.astype(float)) rotations, translations, parent_translations = [], [], [] for i, t in chosen: W = B_inv_T @ algebra.rotations[i] @ B.T W_int = np.rint(W).astype(np.int64) if not np.allclose(W, W_int, atol=1e-8): raise SystemExit("ERROR: subgroup operation is incompatible with its lattice.") t = np.asarray(t, dtype=np.int64) v_full = B_inv_T @ (np.array(algebra.translations[i], dtype=float) / DEN + t) v = np.mod(v_full, 1.0) shift = np.rint(v_full - v).astype(np.int64) rotations.append(W_int) translations.append(v) parent_translations.append(t - B.T @ shift) return rotations, translations, parent_translations
[docs] class IsotropyAnalyzer: """Isotropy subgroups of a space-group irrep (or of coupled irreps). The machinery behind ``crystod-group --parent SG --irrep IR``: it builds the real induced representation of the order parameter, enumerates the order-parameter directions (the strata of the representation), finds the stabilizer of any direction, and identifies the resulting space group with spglib, including the conventional basis and origin of the subgroup in the parent convention. The data-level function ``crystod.group.isotropy_subgroups`` returns the same results as ``IsotropySubgroup`` records; use this class when the matrices, the subgroup elements or a custom direction are needed. Args: space_group: International short symbol (``"Pm-3m"``) or number (``"221"``) of the parent space group. irrep_labels: One ISO-IR label (``"R4+"``) or a list of labels for coupled order parameters (``["X3-", "X2+"]``). Attributes: algebra: The ``SpaceGroupIrrepAlgebra`` of the parent space group. representation: The ``InducedRepresentation`` (one label) or ``CoupledRepresentation`` (several labels) of the order parameter. elements: The group elements ``(i, t, matrix)`` of the representation (``representation.image_elements()``). Raises: SystemExit: Unknown space group, or an irrep label that is not tabulated for it (the labels of symmetry lines and planes, e.g. ``DT5``, have no entries in the tables). Example: >>> from crystod import group >>> analyzer = group.IsotropyAnalyzer("Pm-3m", "R4+") >>> for projector, members in analyzer.enumerate_directions(): ... label, _ = analyzer.direction_label(projector) ... info, size, index, *_ = analyzer.subgroup_of(members) ... print(label, info.number, info.international_short, size, index) (a,b,c) 2 P-1 2 48 (0,0,a) 140 I4/mcm 2 6 (0,a,b) 12 C2/m 2 24 (a,a,a) 167 R-3c 2 8 (0,a,a) 74 Imma 2 12 (a,a,b) 15 C2/c 2 24 """ def __init__(self, space_group: str, irrep_labels: str | list[str]): if isinstance(irrep_labels, str): irrep_labels = [irrep_labels] self.algebra = SpaceGroupIrrepAlgebra(space_group) if len(irrep_labels) == 1: self.representation = InducedRepresentation(self.algebra, irrep_labels[0]) else: self.representation = CoupledRepresentation(self.algebra, irrep_labels) self.elements = self.representation.image_elements()
[docs] @classmethod def from_representation(cls, algebra, representation): """Analyzer over an already-built representation. Args: algebra: The ``SpaceGroupIrrepAlgebra`` the representation was built from. representation: An ``InducedRepresentation`` or ``CoupledRepresentation`` (anything with ``image_elements()``, ``dimension`` and ``grid_n``). Returns: A new ``IsotropyAnalyzer`` sharing the algebra. """ analyzer = cls.__new__(cls) analyzer.algebra = algebra analyzer.representation = representation analyzer.elements = representation.image_elements() return analyzer
# -- stabilizer of a direction (subspace)
[docs] def stabilizer_of(self, projector: np.ndarray): """Group elements acting as the identity on a subspace. Args: projector: Orthogonal projector onto the subspace of order parameters, shape ``(dimension, dimension)``. Returns: The ``(i, t)`` pairs (coset-representative index, lattice translation) whose matrices fix every vector of the subspace. """ return [ (i, t) for i, t, matrix in self.elements if np.allclose(matrix @ projector, projector, atol=1e-6) ]
[docs] def fixed_space(self, members) -> np.ndarray: """Common fixed subspace of a set of group elements. Args: members: ``(i, t)`` pairs as returned by ``stabilizer_of``. Returns: An orthonormal basis of the fixed subspace as columns, shape ``(dimension, n_free)``; the identity when ``members`` is empty. """ n = self.representation.dimension stack = [] member_keys = {(i, tuple(t)) for i, t in members} for i, t, matrix in self.elements: if (i, tuple(t)) in member_keys: stack.append(matrix - np.eye(n)) if not stack: return np.eye(n) return _nullspace(np.vstack(stack))
# -- representative of a stratum (the direction the tables name)
[docs] def canonical_projector(self, projector: np.ndarray) -> np.ndarray: """The representative of the group orbit of a subspace. The images ``g P g^T`` of a subspace under the group are the domain-equivalent directions of one stratum; the representative is the image with the simplest direction label, the rule by which ``enumerate_directions`` names every stratum (the row of ``crystod-group --parent SG --irrep IR``). The decomposition of a structure (``crystod-group --supergroup-cif``) applies the same rule (``_orbit_representative``, on the orbits it has already built): it shows its largest mode with domain-equivalent directions on the representative, so that both commands print the same label for that stratum, and names the representative of every other mode's stratum in a note when the domain shown puts the mode on another image. Args: projector: Orthogonal projector onto the subspace, shape ``(dimension, dimension)``. Returns: The orthogonal projector onto the representative subspace (the input itself, up to rounding, when it is the representative). """ cache = _rep_cache(self.representation, self.elements) return self._orbit_representative(cache.orbit(projector).values())
def _orbit_representative(self, projectors): """The member of an orbit with the simplest direction label (``_label_rank``); among equal labels the first one in the order given. The one rule of ``canonical_projector`` and of both enumerators.""" return min( projectors, key=lambda P: _label_rank(self._direction_pattern(P)[0]), ) # -- enumerate strata (order-parameter direction types)
[docs] def enumerate_directions(self, method: str = "fast"): """Enumerate the order-parameter direction types (strata). Seeds the search with the fixed spaces of every group element and closes the set under pairwise intersection; keeps the isotropy subspaces (``V == Fix(Stab(V))``) and one representative per group orbit (the one with the simplest direction label, ``canonical_projector``). This is the listing of ``crystod-group --parent`` without ``--order-parameter``. The default enumerator intersects every new subspace with the seeds only (every member of the closure is an intersection of seeds), with batched SVDs over the cached element matrices (``representation.rep_cache``); the strata are then visited in the order in which the pairwise closure discovers them, so that the result, including the order and the representative of every stratum, equals that of the pairwise closure (``method="legacy"``, kept for comparison). Args: method: ``"fast"`` (default) or ``"legacy"`` (the original pairwise closure, slower by a factor of 5-50 on large representations). Returns: A list of ``(projector, members)`` pairs, one per stratum, with the orthogonal projector onto the subspace of the stratum and the ``(i, t)`` elements of its stabilizer (the isotropy subgroup). Raises: ValueError: An unknown ``method``. """ if method == "legacy": return self._enumerate_directions_legacy() if method != "fast": raise ValueError(f'unknown method "{method}" (use "fast" or "legacy")') cache = _rep_cache(self.representation, self.elements) n = cache.n eye = np.eye(n) Ed = cache.Ed # seed: fixed spaces of every distinct element (the identity gives # the full space first), as orthonormal bases keys: list[bytes] = [] bases: list[np.ndarray] = [] index: dict[bytes, int] = {} complements = [] _, sing, vh = np.linalg.svd(Ed - eye[None]) ranks = np.sum(sing > 1e-8, axis=1) for g in range(len(Ed)): basis = vh[g, ranks[g]:].T if basis.shape[1] == 0: continue projector = basis @ basis.T key = _projector_key(projector) if key not in index: index[key] = len(keys) keys.append(key) bases.append(basis) complements.append(eye - projector) key = _projector_key(eye) if key not in index: index[key] = len(keys) keys.append(key) bases.append(eye.copy()) n_seeds = len(keys) # closure: intersect every new subspace with every seed IQ = np.array(complements) if complements else np.zeros((0, n, n)) frontier = list(range(n_seeds)) while frontier and len(IQ): new = [] for u in frontier: basis = bases[u] r = basis.shape[1] A = np.einsum("sab,br->sar", IQ, basis) _, sing, vh = np.linalg.svd(A) rank = np.sum(sing > 1e-8, axis=1) for j in np.nonzero((rank > 0) & (rank < r))[0]: meet = _orth_columns(basis @ vh[j, rank[j]:].T) if meet.shape[1] == 0: continue key = _projector_key(meet @ meet.T) if key not in index: index[key] = len(keys) keys.append(key) bases.append(meet) new.append(index[key]) frontier = new order = _pairwise_closure_order(bases, n_seeds) # keep isotropy subspaces: V == Fix(Stab(V)); dedupe by group orbit strata = [] used: set[bytes] = set() for u in order: if keys[u] in used: continue basis = bases[u] mask = cache.fixes(basis, distinct=True) stack = (Ed[mask] - eye[None]).reshape(-1, n) sing = np.linalg.svd(stack, compute_uv=False) if n - int(np.sum(sing > 1e-8)) != basis.shape[1]: continue orbit = cache.orbit(basis @ basis.T) if used.intersection(orbit): continue used.update(orbit) best = self._orbit_representative(orbit.values()) members = [ (self.elements[g][0], self.elements[g][1]) for g in np.nonzero(cache.stabilizer_mask(best))[0] ] strata.append((best, members)) return strata
def _enumerate_directions_legacy(self): """The original pairwise-closure enumerator (``method="legacy"``).""" n = self.representation.dimension seen: dict[bytes, np.ndarray] = {} def add(basis: np.ndarray): if basis.shape[1] == 0: return None projector = _projector(basis) key = _projector_key(projector) if key not in seen: seen[key] = projector return projector return None # seed: fixed spaces of every group element, and the full space seeds = [] for _, _, matrix in self.elements: basis = _nullspace(matrix - np.eye(n)) if add(basis) is not None: seeds.append(_projector(basis)) add(np.eye(n)) # closure under pairwise intersection frontier = list(seen.values()) while frontier: new = [] for P in frontier: for Q in list(seen.values()): intersection = _nullspace( np.vstack([P - np.eye(n), Q - np.eye(n)]) ) result = add(intersection) if result is not None: new.append(result) frontier = new # keep isotropy subspaces: V == Fix(Stab(V)); dedupe by group orbit strata = [] used = set() for key, projector in seen.items(): if key in used: continue members = self.stabilizer_of(projector) fixed = self.fixed_space(members) if not np.allclose(_projector(fixed), projector, atol=1e-6): continue # orbit dedup; keep the orbit member with the prettiest label orbit_keys = set() orbit_projectors = [] for _, _, matrix in self.elements: image = np.real_if_close(matrix @ projector @ matrix.T.conj()) image_key = _projector_key(image) if image_key not in orbit_keys: orbit_keys.add(image_key) orbit_projectors.append(image) if orbit_keys & used: continue used |= orbit_keys best = self._orbit_representative(orbit_projectors) strata.append((best, self.stabilizer_of(best))) return strata # -- subgroup identification
[docs] def subgroup_of(self, members): """Space-group type of the isotropy subgroup with the given elements. The pure lattice translations among the members span the sublattice of the subgroup; the operations are re-expressed in that sublattice basis and identified with spglib through a generic-orbit structure. Args: members: ``(i, t)`` pairs of the subgroup (from ``stabilizer_of`` or ``enumerate_directions``). Returns: ``(info, size, index, B, rotations, translations, lattice)``: the spglib space-group type of the subgroup (``number``, ``international_short``, ...), the primitive-cell multiplication ``size``, the index of the subgroup in the parent, the sublattice basis ``B`` (rows, parent primitive units), the subgroup operations in that basis, and the sublattice vectors (rows, Cartesian, in an invariant parent lattice). Raises: SystemExit: spglib could not identify the subgroup. """ import spglib from sympy import Matrix from sympy.matrices.normalforms import hermite_normal_form algebra = self.algebra # translation lattice: t with T(t) acting as identity on eta happens # exactly for members with i == identity identity_index = algebra._rotation_index[algebra._key(np.eye(3))] pure = [t for i, t in members if i == identity_index and not np.any( algebra.translations[identity_index])] or [np.zeros(3, dtype=np.int64)] grid_n = self.representation.grid_n generators = [t for t in pure] + [grid_n * e for e in np.eye(3, dtype=np.int64)] H = np.array( hermite_normal_form(Matrix(np.array(generators, dtype=np.int64).T)) ).astype(np.int64) B = H.T # rows = sublattice basis in parent primitive units size = abs(int(round(np.linalg.det(B)))) # one representative (W, v + t) per coset-rep index chosen: dict[int, np.ndarray] = {} for i, t in members: if i not in chosen: chosen[i] = np.asarray(t, dtype=np.int64) rotations, translations, _ = sublattice_operations(algebra, B, chosen.items()) lattice_parent = self._invariant_lattice() lattice = B @ lattice_parent info = self._identify_type(rotations, translations, lattice) n_point = len({algebra._key(np.rint(r).astype(np.int64)) for r in rotations}) index = algebra.n_ops * size // n_point return info, size, index, B, rotations, translations, lattice
def _identify_type(self, rotations, translations, lattice): """Space-group type of the operation set, via a generic-orbit structure standardized by spglib. Identification through a structure is much more robust than spglib.get_spacegroup_type_from_symmetry, which fails to detect the centring when the subgroup axes lie along diagonals of the sublattice cell (e.g. several isotropy subgroups of the L and W irreps of Fd-3c). """ import spglib from .runtime_compat import get_spacegroup_type positions = [] numbers = [] for species, x0 in enumerate( (np.array([0.1234, 0.2345, 0.3178]), np.array([0.4321, 0.0567, 0.1873])) ): orbit = [] for W, v in zip(rotations, translations): x = np.mod(W @ x0 + v, 1.0) if not any(np.allclose(x, p, atol=1e-6) for p in orbit): orbit.append(x) positions.extend(orbit) numbers.extend([species + 1] * len(orbit)) dataset = spglib.get_symmetry_dataset( (lattice, np.array(positions), numbers), symprec=1e-4 ) hall = None if dataset is not None: if isinstance(dataset, dict): hall = dataset.get("hall_number") else: hall = getattr(dataset, "hall_number", None) if hall: try: return get_spacegroup_type(spglib.get_spacegroup_type(hall_number=hall)) except Exception: pass # fallback: direct identification from the operations try: info = spglib.get_spacegroup_type_from_symmetry( np.array(rotations), np.array(translations), lattice=lattice, symprec=1e-5, ) except Exception as exc: raise SystemExit(f"ERROR: spglib could not identify the subgroup: {exc}") if info is None: raise SystemExit("ERROR: spglib could not identify the subgroup.") return get_spacegroup_type(info)
[docs] def conventional_setting(self, B, rotations, translations, lattice, info): """Conventional basis and origin of the subgroup (parent convention). Built from a generic-orbit structure with exactly the subgroup symmetry, standardized by spglib. Args: B: Sublattice basis from ``subgroup_of``. rotations: Subgroup rotations from ``subgroup_of``. translations: Subgroup translations from ``subgroup_of``. lattice: Sublattice vectors from ``subgroup_of``. info: Space-group type from ``subgroup_of``. Returns: ``(basis, origin)`` rounded to six decimals: the rows of the child conventional basis and its origin, both in parent conventional units (as printed by ``--order-parameter``); ``None`` when spglib could not standardize the subgroup. """ import spglib positions = [] numbers = [] for species, x0 in enumerate( (np.array([0.1234, 0.2345, 0.3178]), np.array([0.4321, 0.0567, 0.1873])) ): orbit = [] for W, v in zip(rotations, translations): x = np.mod(W @ x0 + v, 1.0) if not any(np.allclose(x, p, atol=1e-6) for p in orbit): orbit.append(x) positions.extend(orbit) numbers.extend([species + 1] * len(orbit)) dataset = spglib.get_symmetry_dataset( (lattice, np.array(positions), numbers), symprec=1e-4 ) def field(name): # spglib < 2.4 returns a dict, >= 2.4 an object if dataset is None: return None if isinstance(dataset, dict): return dataset.get(name) return getattr(dataset, name, None) if dataset is None or field("number") != info.number: return None P = np.array(field("transformation_matrix"), dtype=float) shift = np.array(field("origin_shift"), dtype=float) # child conventional lattice rows in cartesian: L_c = (P^-1)^T L_input L_child_conv = np.linalg.inv(P).T @ lattice # parent conventional lattice rows: A_p = M^T A_c (phonopy convention) M = self.algebra.primitive_matrix L_parent_prim = self._invariant_lattice() L_parent_conv = np.linalg.inv(M).T @ L_parent_prim basis = L_child_conv @ np.linalg.inv(L_parent_conv) # child origin: x_std = P x + p -> the child cell origin (x_std = 0) # sits at x = -P^-1 p (input = subgroup-primitive coords) origin_sub = -np.linalg.inv(P) @ shift origin_cart = origin_sub @ lattice origin = origin_cart @ np.linalg.inv(L_parent_conv) return np.round(basis, 6), np.round(origin, 6)
def _invariant_lattice(self) -> np.ndarray: """A parent primitive lattice (rows) with the full point symmetry.""" return invariant_parent_lattice(self.algebra) # -- direction formatting / parsing
[docs] def direction_label( self, projector: np.ndarray, letter_offset: int = 0 ) -> tuple[str, np.ndarray]: """Direction label of a stratum and a generic representative. Args: projector: Orthogonal projector onto the subspace of the stratum. letter_offset: Shift of the free-parameter letters (used for the single-irrep tables of a coupled run, so that every irrep keeps its own letters: ``X3-(a,b) + X2-(c,d)``). Returns: ``(label, generic)``: the ISOTROPY-style pattern such as ``"(a,a,0)"`` (``;`` separates star arms, ``,`` components within one arm; coupled runs give ``"X3-(a,b) X2-(c,d)"``) and a generic order-parameter vector inside the stratum: its stabilizer is the group of elements fixing the whole subspace, and for coupled irreps the part of every irrep is generic in the same sense for that irrep's share of the subspace (the ``(d;d;e)`` part of ``L1+(a;a;b) L1-(d;d;e)`` has no extra symmetry of its own). The label depends on the subspace only, never on the vector. Raises: RuntimeError: No trial vector is generic (an internal error). """ label, rows = self._direction_pattern(projector, letter_offset) return label, self._generic_vector(rows)
def _direction_pattern( self, projector: np.ndarray, letter_offset: int = 0 ) -> tuple[str, list[np.ndarray]]: """The direction label of a stratum and the orthonormal RREF rows of its subspace it is built from (``direction_label`` without the representative vector).""" basis = _orth_basis(projector) n_free = basis.shape[1] # RREF + integer prettification (same style as the molecular SALCs) from .molecular_salc import _pretty_coefficients, _rref_orthogonal rows = _rref_orthogonal([basis[:, j] for j in range(n_free)]) pretty_rows = [] for row in rows: row = np.asarray(row, dtype=float) coefficients, _ = _pretty_coefficients(row) coefficients = np.asarray(coefficients, dtype=float) # the integers must be the row itself: the SALC tolerance (2e-3, # for XYZ geometries) also takes irrational ratios such as the # 1 : 0.7504 of 214 P1 for 4 : 3, and that pattern, passed back to # --order-parameter, is a different direction scale = (coefficients @ row) / (coefficients @ coefficients) if (np.max(np.abs(coefficients)) > 6.5 or not np.allclose(scale * coefficients, row, rtol=0, atol=1e-6)): # spurious rationalization (large integers, or integers that # are not the row) of an arbitrary basis angle -- show # normalized decimals instead coefficients = np.asarray(row, dtype=float) coefficients = coefficients / np.max(np.abs(coefficients)) coefficients[np.abs(coefficients) < 1e-8] = 0.0 pretty_rows.append(coefficients) # parameter letters: every irrep keeps its own letter range (offset = # total dimension of the preceding irreps), so a coupled direction # reads X3-(a,b) X2-(c,d) -- the amplitudes of different irreps are # independent (the RREF rows never mix chunks, since every fixed # space is a direct sum of per-irrep subspaces) if isinstance(self.representation, CoupledRepresentation): bounds = np.cumsum([0] + list(self.representation.dims)) counters = [0] * len(self.representation.dims) letters = [] for row in pretty_rows: first = int(np.argmax(np.abs(row) > 1e-8)) chunk = int(np.searchsorted(bounds, first, side="right") - 1) letters.append(_PARAMETER_NAMES[int(bounds[chunk]) + counters[chunk]]) counters[chunk] += 1 else: letters = [ _PARAMETER_NAMES[letter_offset + j] for j in range(len(pretty_rows)) ] components = [] for slot in range(self.representation.dimension): terms = [] for j, row in enumerate(pretty_rows): value = row[slot] if abs(value) < 1e-8: continue terms.append(_format_coefficient(value) + letters[j]) components.append("+".join(terms).replace("+-", "-") if terms else "0") def arm_join(piece, arm_chunks): # ISOTROPY separators: ';' between star arms, ',' within one arm arms = [] start = 0 for size in arm_chunks: arms.append(",".join(piece[start : start + size])) start += size return ";".join(arms) if isinstance(self.representation, CoupledRepresentation): chunks = [] start = 0 for part in self.representation.parts: piece = components[start : start + part.dimension] chunks.append(f"{part.label}({arm_join(piece, part.arm_chunks)})") start += part.dimension return " ".join(chunks), rows return ( "(" + arm_join(components, self.representation.arm_chunks) + ")", rows, ) def _generic_vector( self, rows: list[np.ndarray], offset: np.ndarray | None = None ) -> np.ndarray: """A representative of the stratum spanned by ``rows`` that is generic as a whole and in every irrep part. ``sum_j m_j rows[j]`` for the first magnitude set ``m`` of ``_generic_magnitude_sets`` that passes the test: the stabilizer of the vector equals the pointwise stabilizer of the subspace, and for every part of a coupled representation the stabilizer of its slice (under that part's block of the matrices) equals the pointwise stabilizer of the part's slice of the subspace. The tolerances are those of the stabilizer tests of the callers. A nonzero ``offset`` (the literal numbers of an ``--order-parameter`` direction) is added to every trial vector and counts as one more row to be fixed. """ n = self.representation.dimension if not rows: return np.zeros(n) if offset is None else np.asarray(offset, dtype=float) R = np.array(rows, dtype=float) anchors = R if offset is not None and np.any(offset): anchors = np.vstack([R, offset]) else: offset = np.zeros(n) stack = getattr(self, "_matrix_stack", None) if stack is None or stack.shape[0] != len(self.elements): stack = np.array([matrix for _, _, matrix in self.elements], dtype=float) self._matrix_stack = stack if isinstance(self.representation, CoupledRepresentation): bounds = np.cumsum([0] + list(self.representation.dims)) slices = [(0, n)] + [ (int(bounds[j]), int(bounds[j + 1])) for j in range(len(self.representation.dims)) ] else: slices = [(0, n)] def fixed(block, target): # per element: np.allclose(matrix @ target, target, atol=1e-6) return np.all( np.abs(block @ target - target) <= 1e-6 + 1e-5 * np.abs(target), axis=tuple(range(1, 1 + target.ndim)), ) pointwise = [fixed(stack[:, a:b, a:b], anchors[:, a:b].T) for a, b in slices] for magnitudes in _generic_magnitude_sets(len(rows)): generic = np.asarray(magnitudes) @ R + offset if all( np.array_equal(fixed(stack[:, a:b, a:b], generic[a:b]), target) for (a, b), target in zip(slices, pointwise) ): return generic name = ( self.representation.name if isinstance(self.representation, CoupledRepresentation) else self.representation.label ) raise RuntimeError( "internal error: no generic representative found for a " f"{len(rows)}-parameter stratum of {name}; please report this case." )
[docs] def resolve_direction(self, tokens: list[str]) -> np.ndarray: """Order parameter from ``--order-parameter`` tokens. Args: tokens: One token per component, e.g. ``["0", "0", "a"]`` or ``["a", "-a", "0"]``; letters are free parameters (equal letters mean equal components), numbers and fractions are taken literally, a leading ``-`` flips the sign, an exact rational factor scales a parameter (``2a``, ``-0.5a``, ``1/2a``), and a component may be a sum of such terms (``a+b-c-d``, ``2a-1/2b``), as the tables print them. Returns: A representative order-parameter vector of length ``dimension``: a generic point of the direction (its stabilizer fixes every parameter's coefficient vector, see ``_generic_vector``). Raises: SystemExit: Wrong number of components, an all-zero order parameter, a parameter factor that is a rounded decimal (``0.282a``, ``-0.4g+0.917h``: the tables print irrational factors as rounded decimals, and the rounded value is a different direction), or a component that cannot be read. """ n = self.representation.dimension if len(tokens) != n: name = ( self.representation.name if isinstance(self.representation, CoupledRepresentation) else self.representation.label ) raise SystemExit( f"ERROR: --order-parameter needs {n} components for " f"{name} (dim {n})." ) constant = np.zeros(n) coefficients: dict[str, np.ndarray] = {} for slot, token in enumerate(tokens): value, terms = _component_terms(token) if value is not None: constant[slot] = float(value) for name, factor in terms.items(): coefficients.setdefault(name, np.zeros(n))[slot] += float(factor) # one distinct magnitude per parameter, in order of appearance; the # magnitudes are tested like those of the tables' representatives: # the first set that is generic for the parameters' coefficient # vectors (it used to be taken untested, and a sum such as a+b-c-d # was read as one more independent parameter, which gave 230 P1 # (2a,2b,2c,2d;a+b-c-d,...) the P1 of the generic direction instead # of its C2) rows = [row for row in coefficients.values() if np.any(row)] values = self._generic_vector(rows, constant) if not np.any(values): raise SystemExit("ERROR: the order parameter must not be zero.") return values
def _realify_matrix_set(matrices: dict) -> dict | None: """Similarity-transform a set of unitary matrices to real form, when a real form exists (real-type rep); returns None otherwise (complex or pseudoreal type: the averaged antilinear intertwiner vanishes or is not a real structure), and the caller keeps the complex matrices.""" keys = list(matrices) if all(np.allclose(np.asarray(matrices[key]).imag, 0, atol=1e-8) for key in keys): return {key: np.asarray(matrices[key]).real.copy() for key in keys} rng = np.random.default_rng(7) n = np.asarray(matrices[keys[0]]).shape[0] A = rng.normal(size=(n, n)) + 1j * rng.normal(size=(n, n)) S = np.zeros((n, n), dtype=np.complex128) for key in keys: D = np.asarray(matrices[key]) S += np.conj(D) @ A @ D.conj().T # Schur: S vanishes for a complex-type rep (D and D* inequivalent), so # what the average returns there is rounding noise (~1e-15); it would # pass the absolute tolerance of the scalar test below and be # normalized to an O(1) garbage S_bar if np.linalg.norm(S) < 1e-8 * len(keys) * np.linalg.norm(A): return None c_matrix = S @ np.conj(S) c = c_matrix[0, 0] if not np.allclose(c_matrix, c * np.eye(n), atol=1e-6 * max(1, abs(c))) or c.real <= 0: return None S_bar = np.conj(S) / np.sqrt(c.real) # standard basis vectors first, so the real basis stays adapted to the # tabulated components (no arbitrary rotation angle in the labels) trials = [ vec for j in range(n) for vec in (np.eye(n)[j] + 0j, 1j * np.eye(n)[j]) ] + [rng.normal(size=n) + 1j * rng.normal(size=n) for _ in range(20 * n)] basis: list[np.ndarray] = [] for v in trials: if len(basis) == n: break w = v + S_bar @ np.conj(v) for prior in basis: w = w - prior * np.real(np.vdot(prior, w)) norm = np.linalg.norm(w) if norm > 1e-3: basis.append(w / norm) if len(basis) < n: return None T = np.column_stack(basis) # J-fixed vectors have real mutual inner products, so the real # Gram-Schmidt above gives a unitary T whenever J is a genuine real # structure; anything else is not a real form (and may be singular) if not np.allclose(T.conj().T @ T, np.eye(n), atol=1e-6): return None T_inv = np.linalg.inv(T) result = {} for key in keys: transformed = T_inv @ np.asarray(matrices[key]) @ T if not np.allclose(transformed.imag, 0, atol=1e-6): return None result[key] = transformed.real.copy() # canonicalize the (rotation-ambiguous) real basis: align it with the # eigenvectors of a reflection-like element (symmetric, traceless), so # the matrices become signed permutations and the order-parameter # direction labels stay clean (no arbitrary rotation angle) for key in keys: M = result[key] if ( np.allclose(M, M.T, atol=1e-8) and abs(np.trace(M)) < 1e-6 and not np.allclose(M, np.eye(n), atol=1e-8) ): values, vectors = np.linalg.eigh(M) order = np.argsort(-values) O = vectors[:, order] for j in range(O.shape[1]): pivot = np.argmax(np.abs(O[:, j])) if O[pivot, j] < 0: O[:, j] = -O[:, j] result = {k: O.T @ result[k] @ O for k in keys} break return result # magnitudes of the representative vector of a stratum, one per RREF row. # The first set is the historical one; it is kept wherever it is generic, # so the vectors (and every table built from them) do not move. It is not # safe everywhere: 0.4142.../sqrt(2) == 0.2928..., so the rows (1,1,0)/sqrt2 # and (0,0,1) give 0.2929 (1,1,1). _LEGACY_MAGNITUDES = [ 1.0, 0.6180339887, 0.4142135624, 0.2928932188, 0.2360679775, 0.1926, 0.1573, 0.1235, 0.1044, 0.0862, 0.0715, 0.0593, ] + [0.05 * float(np.exp(-0.4811 * j)) for j in range(12)] def _generic_magnitude_sets(count: int): """Magnitude sets tried, in order, for a representative of ``count`` free parameters: the legacy set (when long enough), then ``1 / (1 + j / x)`` for transcendental ``x`` (pi, e, 1/ln 2, pi^2). The fallbacks have no algebraic relation among themselves (distinct poles in ``x``), so no ratio or signed sum of them can match the algebraic coefficients of the rows and matrices exactly; they stay above 0.02 for up to 48 parameters, well clear of the 1e-6 tolerance.""" if count <= len(_LEGACY_MAGNITUDES): yield _LEGACY_MAGNITUDES[:count] for x in (np.pi, np.e, 1.0 / np.log(2.0), np.pi**2): yield [1.0 / (1.0 + j / x) for j in range(count)] def _exact_factor(component: str, text: str) -> Fraction: """The factor of a parameter in an ``--order-parameter`` component, refused when it is a rounded decimal (``0.282`` of ``0.282a``): the tables print irrational factors rounded, and the rounded direction has a different isotropy subgroup.""" factor = Fraction(text) if factor.limit_denominator(24) != factor: raise SystemExit( f"ERROR: order-parameter component {component!r}: the " f"factor {text} is not an exact fraction. " "The tables print irrational factors as rounded decimals, " "and the rounded direction has a different " "isotropy subgroup; read that entry from the listing " "without --order-parameter." ) return factor def _component_terms(token: str) -> tuple[Fraction | None, dict[str, Fraction]]: """Read one ``--order-parameter`` component. A component is a number (``0``, ``1/2``, ``-0.5``: taken literally), a parameter with an optional exact factor (``a``, ``-a``, ``2a``, ``1/2a``, ``-0.5a``), or a sum of such terms joined by ``+`` and ``-`` (``a+b-c-d``, ``2a-1/2b``), as the direction tables print them. Args: token: The component as given. Returns: ``(value, terms)``: for a number, ``value`` is that number and ``terms`` is empty; otherwise ``value`` is ``None`` and ``terms`` maps every parameter name, in order of appearance, to its exact coefficient (repeated names are added up, ``a+a`` is ``2a``). Raises: SystemExit: A factor that is a rounded decimal (``0.282a``, ``-0.4g+0.917h``), or a sum that is not made of parameter terms (``a+1``, ``a++b``). """ component = token.strip() body = component sign = Fraction(1) if body.startswith("-"): sign, body = Fraction(-1), body[1:] if body in ("", "0", "0.0"): return Fraction(0), {} try: return sign * Fraction(body), {} except ValueError: pass if "+" not in body and "-" not in body: scaled = _SCALED_PARAMETER.fullmatch(body) if scaled is None: return None, {body: sign} # a bare parameter name of any spelling return None, {scaled.group(2): sign * _exact_factor(component, scaled.group(1))} # a sum: every term is [+-][exact factor]parameter; before, the whole # sum was read as one new independent parameter (a too generic direction) text = ("-" if sign < 0 else "+") + body terms: dict[str, Fraction] = {} position = 0 while position < len(text): term = _COMPONENT_TERM.match(text, position) if term is None: raise SystemExit( f"ERROR: order-parameter component {component!r} cannot be read: " "a component is a number, or parameters with exact factors " "joined by + and - (a, -2a, a+b-c-d, 2a-1/2b)." ) factor = Fraction(1) if term.group(2) is not None: factor = _exact_factor(component, term.group(2)) name = term.group(3) terms[name] = terms.get(name, Fraction(0)) + ( factor if term.group(1) == "+" else -factor ) position = term.end() return None, terms def _orth_basis(projector: np.ndarray) -> np.ndarray: values, vectors = np.linalg.eigh((projector + projector.T.conj()) / 2) return np.real_if_close(vectors[:, values > 0.5]) def _orth_columns(basis: np.ndarray) -> np.ndarray: """Orthonormal basis of the column span (SVD, tolerance 1e-8).""" if basis.shape[1] == 0: return basis u, sing, _ = np.linalg.svd(basis, full_matrices=False) return u[:, sing > 1e-8] def _pairwise_closure_order(bases: list[np.ndarray], n_seeds: int) -> list[int]: """The order in which the pairwise closure discovers the subspaces. ``bases`` is the complete intersection closure (orthonormal columns), with the seeds first. The original enumerator added, round by round, the intersection of every frontier subspace with every subspace seen so far (in insertion order); its insertion order fixes the order and the representative choice of the strata. The closure is a lattice under intersection, so the meet of two members is the largest member contained in both: with ``down[p]`` the bit set of the members contained in ``p`` (bits sorted by decreasing dimension), the meet is the lowest set bit of ``down[p] & down[q]``, which replays the original loop without a single SVD. Returns: The indices of ``bases`` in discovery order. """ m = len(bases) dims = np.array([basis.shape[1] for basis in bases]) flat = np.array([(basis @ basis.T).ravel() for basis in bases]) # u is contained in p <=> tr(P_u P_p) == dim u contain = np.abs(dims[:, None] - flat @ flat.T) < 1e-6 # [u, p] perm = np.argsort(-dims, kind="stable") down = contain[perm, :].T # [p, bit] n_bits = ((m + 63) // 64) * 64 padded = np.zeros((m, n_bits), dtype=bool) padded[:, :m] = down words = np.ascontiguousarray( np.packbits(padded, axis=1, bitorder="little") ).view(np.uint64) seen = list(range(n_seeds)) in_seen = np.zeros(m, dtype=bool) in_seen[:n_seeds] = True frontier = list(seen) one = np.uint64(1) while frontier: new = [] for p in frontier: meets = words[p][None, :] & words[np.array(seen)] nonzero = meets != 0 found = nonzero.any(axis=1) word_index = np.argmax(nonzero, axis=1)[found] word = meets[np.nonzero(found)[0], word_index] lowest = word & (~word + one) _, exponent = np.frexp(lowest.astype(np.float64)) result = perm[word_index * 64 + exponent - 1] result = result[~in_seen[result]] if len(result): _, first = np.unique(result, return_index=True) for r in result[np.sort(first)]: in_seen[r] = True seen.append(int(r)) new.append(int(r)) frontier = new if len(seen) != m: # the closure was not complete: keep the given order return list(range(m)) return seen def _projector_key(projector: np.ndarray) -> bytes: rounded = np.round(np.real(projector), 6) + 0.0 # normalize -0.0 return rounded.tobytes() def _label_rank(label: str) -> tuple: """Ordering that prefers simple direction labels ((a,a,0) over (a,-b,b)).""" return (label.count("."), label.count("-"), len(label), label) def _format_setting_value(value: float) -> str: fraction = Fraction(float(value)).limit_denominator(12) if abs(float(fraction) - float(value)) < 1e-4: if fraction.denominator == 1: return str(fraction.numerator) return f"{fraction.numerator}/{fraction.denominator}" return f"{float(value):.4g}" def _format_coefficient(value: float) -> str: """A factor of a direction pattern: three significant digits, more when the three-digit text would read as an exact fraction that the value is not (0.7504 is printed ``0.7504``, not ``0.75`` = 3/4), so that ``--order-parameter`` refuses a rounded factor instead of taking it for a different direction (``_exact_factor``).""" if abs(value - 1.0) < 1e-6: return "" if abs(value + 1.0) < 1e-6: return "-" for digits in range(3, 10): text = f"{value:.{digits}g}" factor = Fraction(text) if factor.limit_denominator(24) != factor or abs(float(factor) - value) < 1e-6: return text return text # ---------------------------------------------------------------------- report def format_subgroup_line(analyzer, label, info, size, index) -> str: return ( f"{label:<18} {info.number:>4} {info.international_short:<10} " f"size {size} index {index}" ) def _direction_results(analyzer: IsotropyAnalyzer, letter_offset: int = 0): """(index, n_free, label, info, size) per direction type, sorted; for a coupled representation only the directions condensing every irrep.""" return [record[:5] for record in _direction_records(analyzer, letter_offset)] def _direction_records(analyzer: IsotropyAnalyzer, letter_offset: int = 0): """The rows of ``_direction_results`` with the data behind them: ``(index, n_free, label, info, size, extra)``, where ``extra`` holds the ``projector`` and ``generic`` vector of the stratum, its exact stabilizer ``members`` and the ``subgroup`` tuple of ``subgroup_of`` (``info, size, index, B, rotations, translations, lattice``).""" representation = analyzer.representation coupled = isinstance(representation, CoupledRepresentation) results = [] for projector, members in analyzer.enumerate_directions(): label, generic = analyzer.direction_label(projector, letter_offset) if not coupled: label = representation.label + label if coupled: # a zero chunk means that irrep does not condense at all -- # those are the single-irrep tables, not coupled directions bounds = np.cumsum([0] + list(representation.dims)) if any( np.linalg.norm(generic[bounds[j] : bounds[j + 1]]) < 1e-8 for j in range(len(representation.dims)) ): continue cache = _rep_cache(representation, analyzer.elements) exact_members = [ (analyzer.elements[g][0], analyzer.elements[g][1]) for g in np.nonzero(cache.vector_stabilizer_mask(generic))[0] ] subgroup = analyzer.subgroup_of(exact_members) info, size, index = subgroup[:3] n_free = _orth_basis(projector).shape[1] extra = { "projector": projector, "generic": generic, "members": exact_members, "subgroup": subgroup, } results.append((index, n_free, label, info, size, extra)) results.sort(key=lambda r: (r[1], r[0], r[3].number)) return results def _print_direction_table(results) -> None: width = max([20] + [len(label) + 1 for _, _, label, _, _ in results]) print(f"{'irrep':<{width}} {'subgroup':<18} {'size':<5} {'index':<5}") for index, n_free, label, info, size in results: subgroup = f"{info.number} {info.international_short}" print(f"{label:<{width}} {subgroup:<18} {size:<5} {index:<5}") def _enantiomorph_note(numbers) -> None: pairs = sorted({ tuple(sorted((n, ENANTIOMORPHIC_PAIRS[n]))) for n in numbers if n in ENANTIOMORPHIC_PAIRS }) if not pairs: return print() text = ", ".join(f"{a} <-> {b}" for a, b in pairs) print(f"note: {text} are enantiomorphic partner types: the mirror-image") print("order parameter of the same stratum gives the partner, so the") print("ISOTROPY listing may show either one.") def _print_citation() -> None: print() print("Conventions and validation: ISOSUBGROUP (https://iso.byu.edu):") print('H. T. Stokes, S. van Orden and B. J. Campbell, "Tool for Generating') print('Isotropy Subgroups of Crystallographic Space Groups",') print("J. Appl. Cryst. 49, 1849-1853 (2016).") # ------------------------------------------------------- every irrep of a k point # spellings of the zone centre accepted next to the tabulated name GM, the # same ones crystod-phonon --qpoint takes (phonon_vector.GAMMA_ALIASES); no # space group has a k point named G or GAMMA in the ISO-IR tables _GAMMA_ALIASES = {"G", "GAMMA", "Γ"} def _format_k(k_int) -> str: return "(" + ", ".join(_format_fraction(v) for v in np.asarray(k_int)) + ")" def _available_kpoints(algebra: SpaceGroupIrrepAlgebra) -> str: """The tabulated k points of the space group, for the error messages.""" return ", ".join( f"{kname} {_format_k(k)}" for kname, k in algebra.k_by_kname.items() ) def resolve_special_kpoint(algebra: SpaceGroupIrrepAlgebra, kpoint) -> str: """Name of the tabulated special k point a ``--kpoint`` value refers to. Args: algebra: The ``SpaceGroupIrrepAlgebra`` of the space group. kpoint: Either the ISO-IR name of a special point (``"R"``; the case is ignored, and ``G``/``GAMMA`` mean ``GM``), or three coordinates in the primitive reciprocal basis (numbers, or strings such as ``"1/2"``; a decimal within 0.0005 of a special point is taken for it, so ``0.333`` means 1/3). A name may also come as a one-element sequence, the way the command line passes it. Coordinates are matched modulo reciprocal lattice vectors against every arm of every tabulated star, so any arm and any ``q + G`` spelling of a special point is recognized. Returns: The k-point name, a key of ``algebra.irreps_by_kname``. Raises: SystemExit: An unknown name, a value that is neither one name nor three coordinates, or coordinates that are not a tabulated special point (a symmetry line or plane, or a general point); the message lists the k points of the space group. """ sg_type = algebra.sg_type group_text = f"space group {sg_type.international_short} (No. {sg_type.number})" available = ( f"Available k points (primitive basis): {_available_kpoints(algebra)}" ) if isinstance(kpoint, str): tokens = kpoint.replace(",", " ").split() else: try: values = list(kpoint) except TypeError: values = [kpoint] tokens = [ piece for value in values for piece in ( value.replace(",", " ").split() if isinstance(value, str) else [value] ) ] # one token is a name unless it starts like a number (-0.5, .5, +1/2) if ( len(tokens) == 1 and isinstance(tokens[0], str) and not (tokens[0][:1].isdigit() or tokens[0][:1] in "+-.") ): requested = tokens[0].upper() by_upper = {kname.upper(): kname for kname in algebra.k_by_kname} if requested not in by_upper and requested in _GAMMA_ALIASES: requested = "GM" if requested in by_upper: return by_upper[requested] for irreps in algebra.irreps_by_kname.values(): for irrep in irreps: if irrep.name.upper() == requested: raise SystemExit( f'ERROR: "{tokens[0]}" is an irrep label of {group_text}, ' f"not a k point; its k point is {irrep.kpname} (for this " f"irrep alone use --irrep {irrep.name}).\n" f"{available}" ) raise SystemExit( f'ERROR: k point "{tokens[0]}" is not tabulated for {group_text}; ' "only the special points are (not symmetry lines, planes or " "general points).\n" f"{available}" ) if len(tokens) != 3: raise SystemExit( "ERROR: the k point must be either one name (e.g. GM) or three " "coordinates in the primitive basis (e.g. 1/2 1/2 1/2).\n" f"{available}" ) try: coordinates = [ Fraction(token) if isinstance(token, str) else float(token) for token in tokens ] except (TypeError, ValueError, ZeroDivisionError): raise SystemExit( "ERROR: the k point must be either one name (e.g. GM) or three " f"coordinates in the primitive basis; got {' '.join(map(str, tokens))}.\n" f"{available}" ) from None shown = "(" + ", ".join( token if isinstance(token, str) else f"{float(token):g}" for token in tokens ) + ")" scaled = np.array([float(c) for c in coordinates]) * DEN # the special points sit on the 1/DEN grid; three decimals (0.333 for # 1/3) are enough to name one if np.allclose(scaled, np.rint(scaled), rtol=0, atol=5e-4 * DEN): k = np.mod(np.rint(scaled).astype(np.int64), DEN) for kname in algebra.k_by_kname: arms, _ = algebra.star(kname) if any(np.array_equal(arm % DEN, k) for arm in arms): return kname raise SystemExit( f"ERROR: k = {shown} is not a special k point of {group_text}; only " "the tabulated special points have isotropy subgroups in the tables " "(not symmetry lines, planes or general points).\n" f"{available}" ) def _failure_reason(exc: BaseException) -> str: text = " ".join(str(exc).split()) if isinstance(exc, SystemExit): return text.removeprefix("ERROR: ").rstrip(".") or "failed" return f"{type(exc).__name__}: {text}" if text else type(exc).__name__ def kpoint_irrep_tables(algebra: SpaceGroupIrrepAlgebra, kname: str, rows_of): """Enumerate the isotropy subgroups of every irrep of one k point. The loop behind ``crystod-group --parent SG --kpoint K`` and ``crystod.group.isotropy_subgroups_at_kpoint``: the irreps are taken in table order and each one is analyzed on its own, exactly as ``--irrep`` does. The two members of a complex-conjugate pair at the same k point share one physically irreducible order parameter (e.g. ``GM2+GM3+`` of Pm-3) and are listed once, at the first member: the block is that member's ``--irrep`` table, and its order-parameter components refer to the basis built from that member (the partner spans the same subgroups in a different basis). A pair whose partner sits at the -k point (``K2KA2`` of P3) has one member here and is listed under the pair label as well. An irrep whose analysis fails does not stop the others. Args: algebra: The ``SpaceGroupIrrepAlgebra`` of the parent space group. kname: k-point name, a key of ``algebra.irreps_by_kname`` (see ``resolve_special_kpoint``). rows_of: Callable turning the ``IsotropyAnalyzer`` of one irrep into its rows. Returns: ``(tables, errors)``: ``tables`` maps the label of every analyzed irrep to ``rows_of(analyzer)``, in table order; ``errors`` maps the label of every irrep that could not be analyzed to a one-line reason. """ tables: dict[str, object] = {} errors: dict[str, str] = {} listed: list[np.ndarray] = [] # characters of the order parameters taken for irrep in algebra.irreps_by_kname[kname]: label = irrep.name try: representation = InducedRepresentation(algebra, irrep.name) # the pair is recognized by the representation itself (equal # characters of the real form), not by its label character = np.array( [np.trace(matrix) for _, _, matrix in representation.elements] ) if representation.doubled and any( np.allclose(character, other, atol=1e-6) for other in listed ): continue # conjugate partner of a pair that is already listed listed.append(character) label = representation.label if label in tables or label in errors: label = irrep.name # never drop an inequivalent irrep analyzer = IsotropyAnalyzer.from_representation(algebra, representation) tables[label] = rows_of(analyzer) except (SystemExit, Exception) as exc: errors[label] = _failure_reason(exc) return tables, errors def _report_kpoint(parent: str, kpoint: list[str]) -> None: """The --kpoint report: one table over every irrep of the k point.""" import textwrap algebra = SpaceGroupIrrepAlgebra(parent) kname = resolve_special_kpoint(algebra, kpoint) arms, _ = algebra.star(kname) print() print("* Supergroup *") print(f"{algebra.sg_type.international_short} (No. {algebra.sg_type.number})") print() print("* Kpoint *") print(kname) print(f"k = {_format_k(algebra.k_by_kname[kname])} in the primitive basis, " f"star of {len(arms)} arm(s)") print() tables, errors = kpoint_irrep_tables(algebra, kname, _direction_results) if not tables: reasons = "\n".join(f" {label}: {reason}" for label, reason in errors.items()) raise SystemExit( f"ERROR: no irrep at {kname} could be enumerated:\n{reasons}" ) results = [row for rows in tables.values() for row in rows] print("* Order parameter directions and isotropy subgroups *") _print_direction_table(results) _enantiomorph_note([info.number for _, _, _, info, _ in results]) if errors: print() for label, reason in errors.items(): print(f"note: {label}: not enumerated ({reason})") _print_citation() def _arm_join(piece, arm_chunks) -> str: """Components joined the ISOTROPY way: ',' within an arm, ';' between.""" arms, start = [], 0 for size in arm_chunks: arms.append(",".join(piece[start : start + size])) start += size return ";".join(arms) def _resolve_stratum(analyzer: IsotropyAnalyzer, tokens: list[str]): """The isotropy subgroup of an ``--order-parameter`` direction: ``(members, info, size, index, B, rotations, translations, lattice)`` with the exact stabilizer of the direction as ``members``.""" eta = analyzer.resolve_direction(tokens) # the direction may be non-generic in its own fixed space; use the # exact stabilizer of eta itself members = [ (i, t) for i, t, matrix in analyzer.elements if np.allclose(matrix @ eta, eta, atol=1e-6) ] return (members, *analyzer.subgroup_of(members)) def _print_secondary(analyzer: IsotropyAnalyzer, stratum, max_degree: int) -> None: """The ``--secondary`` table of a resolved direction.""" from .secondary_order_parameter import analyze_secondary, format_secondary import warnings members, info, size, index, B, *_ = stratum def show(message, category, *_args, **_kwargs): print(f"WARNING: {message}", flush=True) try: with warnings.catch_warnings(): warnings.simplefilter("always", UserWarning) warnings.showwarning = show result = analyze_secondary( analyzer.algebra, analyzer.representation, members, B, max_degree ) except ValueError as exc: raise SystemExit( f"ERROR: secondary order parameters: {exc}; lower --degree." ) from None except RuntimeError as exc: raise SystemExit(f"ERROR: secondary order parameters: {exc}") from exc print(format_secondary( result, f"H = {info.international_short} ({info.number}), index {index}", max_degree, )) def _protect_component_values(argv: list[str]) -> list[str]: """Keep the --order-parameter components that start with '-' (-a, -0.5a, -1/2) as values: argparse takes them for options, so a leading space marks them (``_order_parameter_tokens`` strips it). Every token up to the next ``--option`` is a component.""" protected: list[str] = [] inside = False for token in argv: if token.startswith("--"): name = token.split("=", 1)[0] inside = len(name) > 3 and "--order-parameter".startswith(name) elif inside and token.startswith("-"): token = " " + token protected.append(token) return protected def _order_parameter_tokens(values: list[str]) -> list[str]: """The components of --order-parameter: separate words, or one string in any of the spellings of the tables ("a -a 0", "a;-a;0", "a,-a,0", "(a;-a;0)") -- ';' and ',' separate components like spaces.""" text = " ".join(values) for separator in "();,": text = text.replace(separator, " ") return text.split() def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser( description="Isotropy subgroups of a space-group irrep." ) parser.add_argument( "--parent", "--supergroup", dest="parent", required=True, help='parent space group, e.g. "Pm-3m" or 221 (--supergroup is an alias).', ) target = parser.add_mutually_exclusive_group(required=True) target.add_argument( "--irrep", nargs="+", help="ISO-IR irrep label(s), e.g. GM4-, or the pair label of a complex " "irrep as --kpoint prints it (H1H2); several labels (e.g. X3- X2+) " "enumerate the isotropy subgroups of the coupled order parameters.", ) target.add_argument( "--kpoint", nargs="+", help="list every irrep of one special k point: its ISO-IR name (GM, R, " "X, ...) or three coordinates in the primitive basis.", ) parser.add_argument( "--order-parameter", nargs="+", default=None, help='components, e.g. "0 0 a" or "a -a 0" (symbols = free parameters, ' '2a or 1/2a = a multiple, a+b-c = a sum; also one string "a -a 0", ' '"a;-a;0" or "a,-a,0").', ) parser.add_argument( "--invariants", action="store_true", help="list the invariant polynomials of the irrep, or of the direct sum " "of several irreps (Landau free-energy terms and coupling terms), up to " "--degree, instead of the isotropy subgroups; with --order-parameter " "also the free energy restricted to that direction.", ) parser.add_argument( "--secondary", action="store_true", help="with --order-parameter: list the secondary order parameters " "(irreps with a component fixed by the isotropy subgroup).", ) parser.add_argument( "--degree", type=int, default=None, help="highest degree of the invariant polynomials and of the coupling " "terms of --secondary (default 4).", ) if argv is None: import sys argv = sys.argv[1:] args = parser.parse_args(_protect_component_values(list(argv))) if args.kpoint and args.order_parameter: parser.error("--order-parameter needs --irrep; it is not used with --kpoint.") if args.degree is not None and not (args.invariants or args.secondary): parser.error("--degree is only used with --invariants or --secondary.") if args.invariants and args.kpoint: parser.error("--invariants needs --irrep; it is not used with --kpoint.") if args.secondary: if args.kpoint: parser.error("--secondary needs --irrep and --order-parameter; it is not " "used with --kpoint.") if not args.order_parameter: parser.error("--secondary requires --order-parameter (the direction " "whose isotropy subgroup is analyzed).") if args.invariants or args.secondary: if args.degree is None: args.degree = 4 if not 1 <= args.degree <= 12: parser.error("--degree must be between 1 and 12.") if args.secondary and args.degree < 2: parser.error("--secondary needs --degree 2 or higher (a coupling term " "has degree >= 2).") if args.order_parameter: args.order_parameter = _order_parameter_tokens(args.order_parameter) import spglib spglib_version = tuple(int(x) for x in spglib.__version__.split(".")[:2]) if spglib_version < (2, 4): print( "WARNING: spglib >= 2.4 is recommended for reliable subgroup " f"identification (found {spglib.__version__}).", ) if args.kpoint: _report_kpoint(args.parent, args.kpoint) return analyzer = IsotropyAnalyzer(args.parent, args.irrep) representation = analyzer.representation algebra = analyzer.algebra coupled = isinstance(representation, CoupledRepresentation) parts = representation.parts if coupled else [representation] irrep_name = representation.name if coupled else representation.label print() print("* Supergroup *") print(f"{algebra.sg_type.international_short} (No. {algebra.sg_type.number})") print() # The Landau/Lifshitz lines belong to the free-energy modes only. extended = bool( args.invariants or args.order_parameter or args.secondary or args.degree is not None ) print("* Irrep *" if not coupled else "* Coupled irreps *") for part in parts: if part.doubled: star_note = ( f" (star of {part.n_arms} arm(s) x small dim {part.dim_small} x 2;" f" {part.fs_type}-type irrep -> physically irreducible real form)" ) elif part.n_arms > 1: star_note = ( f" (star of {part.n_arms} arm(s) x small dim {part.dim_small})" ) else: star_note = "" print(f"{part.label}: order parameter dimension {part.dimension}{star_note}") if extended: from .invariants import landau_lifshitz_lines, landau_lifshitz_of_elements record = landau_lifshitz_of_elements(part.elements, algebra.rotations) for line in landau_lifshitz_lines(record): print(f" {line}") if coupled: print( f"coupled order parameter dimension {representation.dimension} " f"({' + '.join(str(d) for d in representation.dims)})" ) print() stratum = None if args.order_parameter: stratum = _resolve_stratum(analyzer, args.order_parameter) if coupled: chunks, start = [], 0 for part in parts: piece = args.order_parameter[start : start + part.dimension] chunks.append(f"{part.label}({_arm_join(piece, part.arm_chunks)})") start += part.dimension direction = " ".join(chunks) header = direction else: direction = ( "(" + _arm_join(args.order_parameter, representation.arm_chunks) + ")" ) header = f"{irrep_name}{direction}" if args.invariants: from .invariants import ( INVARIANTS_CITATION, MONOMIAL_WARNING, check_monomial_count, format_invariants, format_restricted, invariants_of_representation, restricted_invariants, ) try: largest = check_monomial_count([part.dimension for part in parts], args.degree) except ValueError as exc: raise SystemExit(f"ERROR: {str(exc).removesuffix('; lower the degree.')}; " "lower --degree.") from None if largest > MONOMIAL_WARNING: print(f"WARNING: {largest} monomials in one (multi)degree; this may " "take long (lower it with --degree).") import warnings try: with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) basis = invariants_of_representation(algebra, representation, args.degree) except RuntimeError as exc: raise SystemExit(f"ERROR: invariant polynomials of {irrep_name}: {exc}") from exc print(format_invariants(basis)) if stratum is not None: info = stratum[1] print() print(format_restricted( restricted_invariants(basis, args.order_parameter), f"{direction} [{info.international_short} ({info.number})]", )) if args.secondary: print() _print_secondary(analyzer, stratum, args.degree) print() print(INVARIANTS_CITATION) return if args.order_parameter: members, info, size, index, B, rotations, translations, lattice = stratum print("* Isotropy subgroup *") print(f"{header} -> {info.international_short} (No. {info.number})") print(f"cell size {size}, index {index}") basis_rows = ", ".join("(" + ",".join(str(int(x)) for x in row) + ")" for row in B) print(f"sublattice basis (parent primitive units): {basis_rows}") setting = analyzer.conventional_setting(B, rotations, translations, lattice, info) if setting is not None: basis, origin = setting rows = ", ".join( "(" + ",".join(_format_setting_value(x) for x in row) + ")" for row in basis ) origin_text = "(" + ",".join(_format_setting_value(x) for x in origin) + ")" print(f"conventional basis (parent conventional units): {rows}") print(f"origin: {origin_text}") _enantiomorph_note([info.number]) if args.secondary: print() _print_secondary(analyzer, stratum, args.degree) else: if coupled: offset = 0 all_numbers = [] for part in parts: sub = IsotropyAnalyzer.from_representation(algebra, part) print("* Order parameter directions and isotropy subgroups " f"({part.label} alone) *") part_results = _direction_results(sub, letter_offset=offset) _print_direction_table(part_results) print() offset += part.dimension all_numbers += [info.number for _, _, _, info, _ in part_results] print("* Order parameter directions and isotropy subgroups (coupled) *") coupled_results = _direction_results(analyzer) _print_direction_table(coupled_results) all_numbers += [info.number for _, _, _, info, _ in coupled_results] _enantiomorph_note(all_numbers) print() ranges = [] offset = 0 for part in parts: letters = _PARAMETER_NAMES[offset : offset + part.dimension] ranges.append(f"{part.label}: {', '.join(letters)}") offset += part.dimension print("Every irrep of the coupled table condenses with a nonzero") print("amplitude; every irrep keeps its own independent free") print(f"parameters ({'; '.join(ranges)}).") else: print("* Order parameter directions and isotropy subgroups *") results = _direction_results(analyzer) _print_direction_table(results) _enantiomorph_note([info.number for _, _, _, info, _ in results]) _print_citation() if __name__ == "__main__": main()