Source code for crystod.magnetic_isotropy

"""Magnetic isotropy subgroups of a paramagnetic parent (crystod-mag --parent).

The magnetic counterpart of ``crystod-group --parent``: given a space group G
and a k point (or one irrep), every magnetic order that transforms as one
irrep lowers the paramagnetic (grey) group G1' = G + theta G to its magnetic
isotropy subgroup

    H(eta) = { g in G : D(g) eta = eta } + { theta g : D(g) eta = -eta },

where D is the full (induced, real) representation and eta the order
parameter.  A magnetic moment is odd under time reversal, so theta acts as -1
on the order parameter of a magnetic irrep (ISOTROPY's ``mGM4+``, printed
here, as in the rest of ``crystod-mag``, without the ``m``): the group acting
on the order parameter is D(G) together with -D(G), and the order-parameter
directions are the strata of that larger matrix group.  They include the
directions of ``crystod-group --parent`` for the same irrep and, where -D(g)
fixes a vector that no D(g) fixes, more: the moments of a cubic
ferromagnet in a (100) or (110) plane, ``GM4+(0,a,b)`` P2'/m' and
``GM4+(a,a,b)`` C2'/m', which are the general direction ``GM4+(a,b,c)`` P-1
of the structural table.

Each subgroup is identified with spglib (``get_magnetic_symmetry_dataset``
through :func:`crystod.magnetic_group.magnetic_space_group`) on a generic
magnetic structure built from its operations, and the number of operations
spglib finds is checked against the stabilizer (a mismatch is an error, not
a silent supergroup): BNS number and symbol, type (I: no operation with
theta; III: half the point operations primed; IV: anti-translations, a
black-white lattice), the UNI symbol (B. J. Campbell, H. T. Stokes,
J. M. Perez-Mato and J. Rodriguez-Carvajal, Acta Cryst. A78, 99 (2022)), the
unitary subgroup, the cell size ``size`` (the lattice of the translations
without theta, in parent primitive cells) and the index ``index`` = [G1' : H],
the number of magnetic domains.

The enumeration and the direction labels are those of
:mod:`crystod.isotropy_subgroup` (the order-parameter components refer to the
same real irrep basis from spgrep, which may differ from ISOTROPY's by an
orthogonal change); only the matrix group is extended by -D(G).

Validation: for every special k point of the 230 space groups, the multiset
of (BNS number, free parameters) of every irrep equals that of the magnetic
isotropy subgroups tabulated by the ISOTROPY Software Suite
(``data_magnetic.txt``: 16721 subgroups of 4777 irreps), up to the
enantiomorphic representative of a stratum (28 irreps) and to the spelling of
a complex pair whose partner lies at -k (``P1PA1`` here, ``P1P1`` there).
Three type IV groups (37.184-37.186) are named from their unitary and family
groups, spglib being unable to (:func:`crystod.magnetic_group.magnetic_space_group`).

Example:
    >>> from crystod import mag
    >>> rows = mag.magnetic_isotropy_subgroups("Pm-3m", "GM4+")
    >>> [(r.direction, r.bns_number, r.bns_symbol, r.index) for r in rows[:3]]
    [('(0,0,a)', '123.345', "P4/mm'm'", 6), ('(a,a,a)', '166.101', "R-3m'", 8), ('(0,a,a)', '65.486', "Cmm'm'", 12)]
"""

from __future__ import annotations

import argparse
import contextlib
import io
from dataclasses import dataclass

import numpy as np

from .isotropy_subgroup import (
    ENANTIOMORPHIC_PAIRS,
    InducedRepresentation,
    IsotropyAnalyzer,
    _failure_reason,
    _format_k,
    _orth_basis,
    _rep_cache,
    resolve_special_kpoint,
)
from .spacegroup_product import DEN, SpaceGroupIrrepAlgebra

#: Generic points and generic axial moments of the two species of the
#: structure that identifies a subgroup (no extra symmetry of their own).
_GENERIC_SITES = (
    (np.array([0.1234, 0.2345, 0.3178]), np.array([0.31, -0.57, 0.76])),
    (np.array([0.4321, 0.0567, 0.1873]), np.array([-0.42, 0.18, 0.65])),
)


[docs] @dataclass(frozen=True) class MagneticIsotropySubgroup: """One row of ``crystod-mag --parent``: a magnetic isotropy subgroup. Attributes: irrep: The irrep label (``"GM4+"``; the pair label of a complex irrep and its conjugate, ``"GM3+GM4+"``). direction: The order-parameter direction (``"(0,0,a)"``, ``;`` between the arms of the star). bns_number: BNS number (``"123.345"``). bns_symbol: BNS symbol (``"P4/mm'm'"``; type IV with the lattice subscript, ``"I_c4/mcm"``). msg_type: 1, 3 or 4 (a magnetic isotropy subgroup is never a grey group, type II). uni_symbol: The UNI symbol (``"P4/mm'm'"``, ``"Pm-3m.1"``, ``"I4/mcm.1'_c[P4/mmm]"``). og_number: Opechowski-Guccione number. magnetic_point_group: Its magnetic point group (``"4/mm'm'"``). unitary_number: Space-group number of the unitary subgroup (the operations without theta), the stabilizer of the order parameter in G. unitary_symbol: Its short Hermann-Mauguin symbol. size: Volume of the primitive cell of the unitary translations, in parent primitive cells. index: [G1' : H], the number of domains. n_free: Free parameters of the direction. n_operations: Operations of H modulo its unitary translations (as many with theta as without for types III and IV). """ irrep: str direction: str bns_number: str bns_symbol: str msg_type: int uni_symbol: str og_number: str magnetic_point_group: str unitary_number: int unitary_symbol: str size: int index: int n_free: int n_operations: int @property def label(self) -> str: """``"GM4+(0,0,a)"``, the first column of the table.""" return self.irrep + self.direction @property def subgroup(self) -> str: """``"123.345 P4/mm'm'"``, the second column of the table.""" return f"{self.bns_number} {self.bns_symbol}" @property def type_name(self) -> str: """The type as a Roman numeral (``"III"``).""" return {1: "I", 2: "II", 3: "III", 4: "IV"}[self.msg_type]
class MagneticRepresentation: """The time-odd representation of G1' on the order parameter of an irrep. Wraps a real (physically irreducible) representation of G -- an ``InducedRepresentation`` -- and adds, for every element ``(i, t, D)``, the element ``theta (i, t)`` with the matrix ``-D``, encoded as the index ``i + n_ops`` (``n_ops`` the coset representatives of G). Everything else (label, dimension, arms, translation grid) is that of the wrapped representation. """ _rep_cache_data = None def __init__(self, base): self.base = base n_ops = base.algebra.n_ops self.elements = list(base.image_elements()) + [ (i + n_ops, t, -matrix) for i, t, matrix in base.image_elements() ] def __getattr__(self, name): if name.startswith("__"): raise AttributeError(name) return getattr(self.base, name) def image_elements(self): """All elements of G1' as ``(i, t, matrix)`` (``i >= n_ops``: with theta).""" return self.elements
[docs] class MagneticIsotropyAnalyzer(IsotropyAnalyzer): """Magnetic isotropy subgroups of one irrep of a space group. The machinery behind ``crystod-mag --parent SG --irrep IR`` (and, irrep by irrep, ``--qpoint K``): the :class:`IsotropyAnalyzer` of ``crystod-group --parent`` over the time-odd representation (:class:`MagneticRepresentation`), whose strata are the magnetic order-parameter directions, with :meth:`magnetic_subgroup_of` in place of the space-group identification. The stabilizer members are ``(i, t)`` pairs where ``i >= algebra.n_ops`` marks theta. Args: space_group: Symbol (``"Pm-3m"``) or number of the parent. irrep_label: ISO-IR label (``"GM4+"``), a pair label (``"GM3+GM4+"``), or the magnetic spelling of either with a leading ``m`` (``"mGM4+"``). """ def __init__(self, space_group: str, irrep_label: str): self.algebra = SpaceGroupIrrepAlgebra(space_group) base = InducedRepresentation(self.algebra, _strip_magnetic_prefix(self.algebra, irrep_label)) self.representation = MagneticRepresentation(base) self.elements = self.representation.image_elements()
[docs] @classmethod def from_representation(cls, algebra, representation): """Analyzer over an already-built representation of G (wrapped in a :class:`MagneticRepresentation` unless it is one).""" analyzer = cls.__new__(cls) analyzer.algebra = algebra if not isinstance(representation, MagneticRepresentation): representation = MagneticRepresentation(representation) analyzer.representation = representation analyzer.elements = representation.image_elements() return analyzer
[docs] def subgroup_of(self, members): """The unitary part (the members without theta) as :meth:`IsotropyAnalyzer.subgroup_of` identifies it.""" n_ops = self.algebra.n_ops return super().subgroup_of([(i, t) for i, t in members if i < n_ops])
[docs] def magnetic_subgroup_of(self, members): """Magnetic space group of the stabilizer ``members``. The translations without theta span the lattice of the subgroup; the operations, one per (coset representative, theta), are expressed in that basis (an anti-translation is the identity with theta and its translation) and identified by spglib on a structure of two generic orbits carrying generic axial moments (moment ``(-1)^theta det(R) R m``). Args: members: ``(i, t)`` pairs of the stabilizer (``i >= n_ops``: with theta). Returns: ``(group, size, index, n_operations)``: the :class:`crystod.magnetic_group.MagneticGroupInfo`, the cell size, [G1' : H] and the number of operations modulo the unitary translations. Raises: SystemExit: spglib finds more or fewer operations than the stabilizer has, or cannot identify the group. """ from sympy import Matrix from sympy.matrices.normalforms import hermite_normal_form from .magnetic_group import magnetic_space_group algebra = self.algebra n_ops = algebra.n_ops identity = algebra._rotation_index[algebra._key(np.eye(3))] pure = [t for i, t in members if i == identity] or [np.zeros(3, dtype=np.int64)] grid_n = self.representation.grid_n generators = list(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: basis of the unitary translations, parent primitive units size = abs(int(round(np.linalg.det(B)))) chosen: dict[int, np.ndarray] = {} for i, t in members: chosen.setdefault(i, np.asarray(t, dtype=np.int64)) B_inv_T = np.linalg.inv(B.T) lattice = B @ self._invariant_lattice() to_cartesian = lattice.T from_cartesian = np.linalg.inv(lattice.T) operations = [] for i, t in chosen.items(): rotation, theta = i % n_ops, i // n_ops W = B_inv_T @ algebra.rotations[rotation] @ 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.") v = B_inv_T @ (np.array(algebra.translations[rotation], dtype=float) / DEN + t) operations.append((W_int, np.mod(v, 1.0), theta)) positions, numbers, moments = [], [], [] for species, (x0, m0) in enumerate(_GENERIC_SITES): for W, v, theta in operations: R = to_cartesian @ W @ from_cartesian positions.append(np.mod(W @ x0 + v, 1.0)) numbers.append(species + 1) moments.append((-1) ** theta * np.linalg.det(R) * (R @ m0)) group = magnetic_space_group(lattice, positions, numbers, moments) if not group.identified: raise SystemExit("ERROR: spglib could not identify the magnetic subgroup.") if group.n_operations != len(operations): raise SystemExit( f"ERROR: spglib finds {group.n_operations} magnetic operations where the " f"stabilizer has {len(operations)}; please report this case.") index = 2 * n_ops * size // len(operations) return group, size, index, len(operations)
def _strip_magnetic_prefix(algebra: SpaceGroupIrrepAlgebra, label: str) -> str: """``mGM4+`` -> ``GM4+`` (ISOTROPY's spelling of the time-odd irrep); any other label unchanged.""" if label.startswith("m") and len(label) > 1 and label[1].isupper(): names = {irrep.name for irreps in algebra.irreps_by_kname.values() for irrep in irreps} rest = label[1:] if rest in names or any(rest.startswith(name) for name in names): return rest return label def _magnetic_rows(analyzer: MagneticIsotropyAnalyzer) -> list[MagneticIsotropySubgroup]: """The rows of one irrep, sorted as ``crystod-group --parent`` sorts (free parameters, then index, then the BNS number).""" representation = analyzer.representation cache = _rep_cache(representation, analyzer.elements) rows = [] for projector, _ in analyzer.enumerate_directions(): direction, generic = analyzer.direction_label(projector) members = [ (analyzer.elements[g][0], analyzer.elements[g][1]) for g in np.nonzero(cache.vector_stabilizer_mask(generic))[0] ] group, size, index, n_operations = analyzer.magnetic_subgroup_of(members) unitary = analyzer.subgroup_of(members)[0] rows.append(MagneticIsotropySubgroup( irrep=representation.label, direction=direction, bns_number=group.bns_number, bns_symbol=group.bns_symbol, msg_type=group.msg_type, uni_symbol=group.uni_symbol, og_number=group.og_number, magnetic_point_group=group.magnetic_point_group, unitary_number=int(unitary.number), unitary_symbol=str(unitary.international_short), size=size, index=index, n_free=_orth_basis(projector).shape[1], n_operations=n_operations, )) rows.sort(key=lambda r: (r.n_free, r.index, *(int(x) for x in r.bns_number.split(".")))) return rows
[docs] def magnetic_isotropy_subgroups(parent: str, irrep: str) -> list[MagneticIsotropySubgroup]: """Magnetic isotropy subgroups of one irrep (``crystod-mag --parent SG --irrep IR``). Args: parent: Symbol or number of the parent space group (``"Pm-3m"``); the paramagnetic parent is its grey group (``Pm-3m1'``). irrep: ISO-IR label (``"GM4+"``, a pair label ``"GM3+GM4+"``, or ``"mGM4+"``). Returns: One :class:`MagneticIsotropySubgroup` per order-parameter direction, in the order of the table. Raises: ValueError: Unknown space group or irrep (the command's message). """ try: with contextlib.redirect_stdout(io.StringIO()): analyzer = MagneticIsotropyAnalyzer(str(parent), irrep) return _magnetic_rows(analyzer) except SystemExit as exc: raise ValueError(str(exc).removeprefix("ERROR: ")) from None
def kpoint_magnetic_tables(algebra: SpaceGroupIrrepAlgebra, kname: str): """``(tables, errors)`` of every irrep at one k point: the loop of :func:`crystod.isotropy_subgroup.kpoint_irrep_tables` (a complex irrep and its conjugate listed once, under the pair label; an irrep that fails does not stop the others) with the magnetic rows.""" from .isotropy_subgroup import kpoint_irrep_tables return kpoint_irrep_tables( algebra, kname, lambda analyzer: _magnetic_rows( MagneticIsotropyAnalyzer.from_representation(algebra, analyzer.representation)), )
[docs] def magnetic_isotropy_subgroups_at_kpoint(parent: str, kpoint) -> dict: """Magnetic isotropy subgroups of every irrep of one k point (``crystod-mag --parent SG --qpoint K``). Args: parent: Symbol or number of the parent space group. kpoint: Special-point name (``"R"``, ``"GM"``) or three primitive coordinates. Returns: ``{irrep label: [MagneticIsotropySubgroup, ...]}`` in table order. Raises: ValueError: Unknown space group or k point, or an irrep that could not be enumerated (its reason). """ try: with contextlib.redirect_stdout(io.StringIO()): algebra = SpaceGroupIrrepAlgebra(str(parent)) kname = resolve_special_kpoint(algebra, kpoint) tables, errors = kpoint_magnetic_tables(algebra, kname) except SystemExit as exc: raise ValueError(str(exc).removeprefix("ERROR: ")) from None if errors: raise ValueError("; ".join(f"{label}: {reason}" for label, reason in errors.items())) return tables
# --------------------------------------------------------------------- report def _print_table(rows: list[MagneticIsotropySubgroup]) -> None: width = max([20] + [len(row.label) + 1 for row in rows]) group_width = max([18] + [len(row.subgroup) + 1 for row in rows]) print(f"{'irrep':<{width}} {'subgroup':<{group_width}} {'size':<5} {'index':<5}") for row in rows: print(f"{row.label:<{width}} {row.subgroup:<{group_width}} {row.size:<5} {row.index:<5}") def _print_notes(algebra: SpaceGroupIrrepAlgebra, rows: list[MagneticIsotropySubgroup]) -> None: numbers = {int(row.bns_number.split(".")[0]) for row in rows} pairs = sorted({tuple(sorted((n, ENANTIOMORPHIC_PAIRS[n]))) for n in numbers if n in ENANTIOMORPHIC_PAIRS}) if pairs: text = ", ".join(f"{a} <-> {b}" for a, b in pairs) print() print(f"note: {text} are enantiomorphic partner types: the mirror-image") print("order parameter of the same stratum gives the partner, so another") print("listing may show either one.") symbol = algebra.sg_type.international_short first = rows[0].irrep if rows else "GM1+" print() print(f"Magnetic (time-odd) irreps of the paramagnetic group {symbol}1': the label") print(f"{first} is ISOTROPY's m{first}; subgroup = BNS number and symbol; size = cell of") print("the translations without time reversal, in parent primitive cells;") print(f"index = [{symbol}1' : H], the number of magnetic domains.") print() print("Conventions and validation: the magnetic isotropy subgroups of the ISOTROPY") print("Software Suite (H. T. Stokes, D. M. Hatch and B. J. Campbell, https://iso.byu.edu),") print("whose table they reproduce at every special k point of the 230 space groups;") print("BNS numbers and symbols of ISO-MAG (H. T. Stokes and B. J. Campbell, 2010).") def _print_supergroup(algebra: SpaceGroupIrrepAlgebra) -> None: print() print("* Supergroup *") print(f"{algebra.sg_type.international_short} (No. {algebra.sg_type.number})") print() def report_kpoint(parent: str, kpoint) -> None: """The ``--qpoint`` report: one table over every irrep of the k point.""" algebra = SpaceGroupIrrepAlgebra(parent) kname = resolve_special_kpoint(algebra, kpoint) arms, _ = algebra.star(kname) _print_supergroup(algebra) 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_magnetic_tables(algebra, kname) 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}") rows = [row for table in tables.values() for row in table] print("* Order parameter directions and isotropy subgroups *") _print_table(rows) if errors: print() for label, reason in errors.items(): print(f"note: {label}: not enumerated ({reason})") _print_notes(algebra, rows) def report_irrep(parent: str, irrep: str) -> None: """The ``--irrep`` report: the table of one irrep.""" analyzer = MagneticIsotropyAnalyzer(parent, irrep) representation = analyzer.representation _print_supergroup(analyzer.algebra) print("* Irrep *") print(f"{representation.label}: order parameter dimension {representation.dimension}") print() rows = _magnetic_rows(analyzer) print("* Order parameter directions and isotropy subgroups *") _print_table(rows) _print_notes(analyzer.algebra, rows) def main(argv: list[str] | None = None) -> None: """``crystod-mag --parent SG (--qpoint K | --irrep IR)`` (dispatched by :mod:`crystod.cli.mag`).""" parser = argparse.ArgumentParser(prog="crystod-mag --parent") parser.add_argument("--parent", required=True) parser.add_argument("--qpoint", nargs="+", default=None) parser.add_argument("--irrep", default=None) args = parser.parse_args(argv) if args.irrep is not None: report_irrep(args.parent, args.irrep) else: report_kpoint(args.parent, args.qpoint)