Source code for crystod.magnetic_group

"""Magnetic space groups, symmetry-allowed responses and collinear classes.

This module adds four analyses to the spin bases of ``crystod-mag``:

- :func:`magnetic_space_group`: the magnetic space group (MSG) of a spin
  arrangement from spglib (``get_magnetic_symmetry_dataset`` with axial
  moments), with its BNS number and symbol, its OG number, its type (I-IV),
  the magnetic point group (MPG) derived from the BNS symbol and checked
  against the operations, the unified (UNI) symbols of both (B. J. Campbell
  et al., Acta Cryst. A78, 99 (2022)), and the operations themselves;
- :func:`macroscopic_responses`: the macroscopic responses the magnetic point
  group allows by symmetry: a net magnetization (time-odd axial vector,
  Jahn ``aeV``), an electric polarization (time-even polar vector, ``V``:
  allowed when the point group of the spatial parts is polar, so ``-1'``
  forbids it; marked when the crystal without spins is not polar or allows
  fewer components), the linear magnetoelectric tensor (``aeV2``) and the
  piezomagnetic tensor (``aeV[V2]``), through
  :func:`crystod.tensor_form.tensor_form_of_operations` with the
  time-reversal flag of every operation;
- :func:`classify_collinear`: the nonrelativistic class of a collinear
  arrangement from the sign pattern of its moments alone: ferromagnet,
  ferrimagnet, conventional antiferromagnet (a translation or the inversion
  exchanges the two sublattices), altermagnet (only rotations, proper or
  improper, exchange them), with the d-, g- or i-wave type, the lowest-order
  form of the spin splitting allowed by symmetry and the spin-degenerate
  planes and lines of an
  altermagnet (L. Smejkal, J. Sinova and T. Jungwirth, Phys. Rev. X 12,
  031042 (2022));
- :func:`phonon_angular_momentum`: the texture of the phonon angular
  momentum near Gamma that the magnetic point group allows, component by
  component (lowest-degree q-polynomial, s- to j-wave, enforced nodal
  planes), after L. Zhang and Q. Niu, Phys. Rev. Lett. 112, 085503 (2014).

The magnetic space group uses the moment directions (relativistic: spin and
lattice rotate together); the collinear class uses only the signs of the
moments along their common axis (spin and lattice decoupled). The two can
therefore differ in how they treat two arrangements: the moments along z
and along x of a rutile altermagnet have different magnetic space groups
and the same class.

Example:
    >>> import numpy as np
    >>> from crystod import mag
    >>> lattice = np.eye(3) * 2.87                      # bcc Fe cell, AFM pair
    >>> positions = [[0, 0, 0], [0.5, 0.5, 0.5]]
    >>> group = mag.magnetic_space_group(lattice, positions, [26, 26],
    ...                                  [[0, 0, 1], [0, 0, -1]])
    >>> group.bns_symbol, group.bns_number, group.type_name
    ('P_I4/mnc', '128.410', 'IV')
    >>> group.magnetic_point_group
    "4/mmm1'"
    >>> group.uni_symbol, group.uni_point_group
    ("P4/mnc.1'_I[I4/mmm]", "4/mmm.1'")
"""

from __future__ import annotations

import contextlib
import functools
import math
import os
import re
from collections import Counter
from dataclasses import dataclass
from fractions import Fraction

import numpy as np

#: Roman numerals of the magnetic space-group types.
MSG_TYPE_NAMES = {1: "I", 2: "II", 3: "III", 4: "IV"}

#: Reference of the altermagnet classification.
ALTERMAGNET_REFERENCE = (
    "L. Smejkal, J. Sinova and T. Jungwirth, Phys. Rev. X 12, 031042 (2022)"
)

_WAVE_NAMES = {2: "d-wave", 4: "g-wave", 6: "i-wave"}

CLASS_FERROMAGNET = "ferromagnet"
CLASS_FERRIMAGNET = "ferrimagnet"
CLASS_COMPENSATED = "compensated, sublattices not related by symmetry"
CLASS_AFM_TRANSLATION = (
    "antiferromagnet (conventional: a translation exchanges the sublattices, T tau)"
)
CLASS_AFM_INVERSION = (
    "antiferromagnet (conventional: inversion exchanges the sublattices, P T)"
)
CLASS_ALTERMAGNET = "altermagnet"
CLASS_NONCOLLINEAR = "noncollinear (not classified)"

_SHORT_CLASS = {
    CLASS_AFM_TRANSLATION: "antiferromagnet (T tau)",
    CLASS_AFM_INVERSION: "antiferromagnet (P T)",
    CLASS_COMPENSATED: "compensated (unrelated sublattices)",
    CLASS_NONCOLLINEAR: "noncollinear",
}


# ------------------------------------------------------------ dataclasses


[docs] @dataclass(frozen=True, eq=False) class MagneticGroupInfo: """The magnetic space group of a spin arrangement. Attributes: uni_number: spglib's serial number of the MSG (1-1651). bns_number: BNS number, ``"136.499"``. bns_symbol: BNS symbol from pymatgen, ``"P4_2'/mnm'"`` (a type IV symbol carries the lattice subscript, ``"P_I4/mnc"``). og_number: Opechowski-Guccione number, ``"136.5.1161"``. msg_type: 1-4 (type I: no operation with time reversal; II: grey group; III: half of the operations with time reversal, no pure antitranslation; IV: black-white lattice). parent_number: The space-group number of the type that spglib reports (for types I, II and III the space group of the unprimed and primed operations together; for type IV the family space group of the BNS symbol). magnetic_point_group: The MPG symbol derived from the BNS symbol; followed by ``"?"`` when it disagrees with the operations. ``uni_number``, ``bns_number``, ``bns_symbol``, ``og_number``, ``msg_type``, ``parent_number`` and ``magnetic_point_group`` are None when spglib finds the operations but cannot identify the group (:attr:`identified` False). point_group_checked: True when the derived symbol generates the same rotations, with the same time-reversal flags, as the operations. n_operations: Number of operations in the cell given (centring and magnetic-cell translations counted). n_primed: Number of those operations combined with time reversal. rotations: Cartesian rotation matrices, ``(n_operations, 3, 3)``, in the frame of the lattice given. translations: Fractional translations in the cell given. time_reversals: Boolean time-reversal flag of every operation. uni_symbol: The unified (UNI) symbol of B. J. Campbell et al., Acta Cryst. A78, 99 (2022), in the same standard BNS setting: ``"P4_2'/mnm'"`` (type III, as BNS), ``"Pnma.1"`` (type I), ``"Pnma.1'"`` (type II), ``"P4/mnc.1'_I[I4/mmm]"`` (type IV: the anti-translation ``(1/2,1/2,1/2)'`` and the family space group). Unrelated to :attr:`uni_number`, spglib's serial number. uni_point_group: The UNI symbol of the MPG (``"4/mmm.1'"``, ``"mmm.1"``, ``"4'/mmm'"``). crystal_rotations: Distinct Cartesian rotations of the point group of the same structure without moments (same tolerance), or None when unknown; :func:`macroscopic_responses` compares the electric polarization with it. confirmed: False when the lattice of the cell given is not invariant under the point group of the crystal and the group could not be identified again in the cell of the translations without time reversal (:func:`magnetic_space_group`): it can then be a subgroup of the true group (:func:`unconfirmed_note`). """ uni_number: int | None bns_number: str | None bns_symbol: str | None og_number: str | None msg_type: int | None parent_number: int | None magnetic_point_group: str | None point_group_checked: bool n_operations: int n_primed: int rotations: np.ndarray translations: np.ndarray time_reversals: np.ndarray uni_symbol: str | None = None uni_point_group: str | None = None crystal_rotations: np.ndarray | None = None confirmed: bool = True @property def identified(self) -> bool: """False when spglib returned the operations but could not name the group (the identification fields are then None).""" return self.uni_number is not None @property def type_name(self) -> str: """The type as a Roman numeral (``"III"``), ``"-"`` when the group is not identified.""" if self.msg_type is None: return "-" return MSG_TYPE_NAMES.get(self.msg_type, str(self.msg_type)) @property def n_point_operations(self) -> int: """Order of the magnetic point group: the distinct (rotation, time-reversal) pairs of the operations.""" return len(_unique_operations(self.rotations, self.time_reversals)[1]) @property def n_point_primed(self) -> int: """Primed elements of the magnetic point group.""" return int(sum(_unique_operations(self.rotations, self.time_reversals)[1]))
[docs] @dataclass(frozen=True, eq=False) class MagneticResponses: """Macroscopic responses allowed by a magnetic point group. Attributes: magnetization: :class:`crystod.tensor_form.TensorForm` of the net magnetization (Jahn ``aeV``). magnetoelectric: Form of the linear magnetoelectric tensor ``P_i = alpha_ij H_j`` (Jahn ``aeV2``). piezomagnetic: Form of the piezomagnetic tensor ``M_i = Lambda_ijk sigma_jk`` (Jahn ``aeV[V2]``). magnetization_direction: ``"none"``, ``"along z"``, ``"in the xy plane"``, ``"any direction"`` (directions in the Cartesian axes of the cell given). polarization: Form of the electric polarization (Jahn ``V``, time-even: allowed when the point group of the spatial parts is polar); None when not computed. polarization_direction: Its direction, in the words of :attr:`magnetization_direction`. polarization_note: ``" (induced by the spin order)"`` when the crystal without spins allows no polarization, ``" (the crystal without spins: along z)"`` when it allows fewer components, else empty (also when the crystal is not known). """ magnetization: object magnetoelectric: object piezomagnetic: object magnetization_direction: str polarization: object = None polarization_direction: str = "none" polarization_note: str = "" @property def n_polarization(self) -> int: """Independent components of the electric polarization.""" return 0 if self.polarization is None else self.polarization.n_independent @property def n_magnetization(self) -> int: """Independent components of the net magnetization.""" return self.magnetization.n_independent @property def n_magnetoelectric(self) -> int: """Independent components of the linear magnetoelectric tensor.""" return self.magnetoelectric.n_independent @property def n_piezomagnetic(self) -> int: """Independent components of the piezomagnetic tensor.""" return self.piezomagnetic.n_independent
[docs] def summary(self) -> str: """One-line summary: ``"net magnetization along z; electric polarization none; linear magnetoelectric effect none; piezomagnetism 2 components"``.""" return (f"net magnetization {self.magnetization_direction}; " f"electric polarization {self.polarization_direction}" f"{self.polarization_note}; " f"linear magnetoelectric effect {_count_text(self.n_magnetoelectric)}; " f"piezomagnetism {_count_text(self.n_piezomagnetic)}")
[docs] @dataclass(frozen=True, eq=False) class CollinearClass: """Nonrelativistic class of a collinear spin arrangement. Attributes: name: One of ``"ferromagnet"``, ``"ferrimagnet"``, ``"compensated, sublattices not related by symmetry"``, ``"antiferromagnet (conventional: a translation exchanges the sublattices, T tau)"``, ``"antiferromagnet (conventional: inversion exchanges the sublattices, P T)"``, ``"altermagnet"`` or ``"noncollinear (not classified)"``. wave: ``"d-wave"``, ``"g-wave"`` or ``"i-wave"`` for an altermagnet, else None. order: The even degree ``l`` of the wave (2, 4, 6) or None. spin_splitting: The lowest-order polynomials in ``(k_x, k_y, k_z)`` that symmetry allows for the spin splitting of an altermagnet, in the Cartesian axes of the cell given (``("k_x k_y",)``). degenerate_planes: Normals of the spin-degenerate planes of an altermagnet as Cartesian directions (``("[100]", "[010]")``). degenerate_lines: Spin-degenerate lines that do not lie in one of the planes, as Cartesian directions. axis: The common spin axis (unit Cartesian vector) or None. n_preserving: Number of space-group operations (in the magnetic cell) that keep the sign pattern. n_swapping: Number of operations that reverse it (exchange the sublattices). net_moment: The net moment over the magnetic cell. """ name: str wave: str | None = None order: int | None = None spin_splitting: tuple = () degenerate_planes: tuple = () degenerate_lines: tuple = () axis: np.ndarray | None = None n_preserving: int = 0 n_swapping: int = 0 net_moment: np.ndarray | None = None @property def short_name(self) -> str: """Short form for tables: ``"altermagnet (d-wave)"``, ``"antiferromagnet (P T)"``, ``"ferromagnet"``.""" if self.name == CLASS_ALTERMAGNET and self.wave: return f"altermagnet ({self.wave})" return _SHORT_CLASS.get(self.name, self.name)
[docs] def text(self) -> str: """The description printed after ``collinear order:``. Example: ``"altermagnet (d-wave; spin splitting allowed by symmetry ~ k_x k_y; spin-degenerate planes perpendicular to [100], [010])"``. """ if self.name != CLASS_ALTERMAGNET: return self.name parts = [self.wave or "wave type not found"] if self.spin_splitting: parts.append("spin splitting allowed by symmetry ~ " + ", ".join(self.spin_splitting)) if self.degenerate_planes: parts.append("spin-degenerate planes perpendicular to " + ", ".join(self.degenerate_planes)) if self.degenerate_lines: parts.append("spin-degenerate lines along " + ", ".join(self.degenerate_lines)) return f"altermagnet ({'; '.join(parts)})"
# ------------------------------------------------------------ small helpers def _count_text(count: int) -> str: if count == 0: return "none" return f"{count} component" + ("s" if count != 1 else "") def _cartesian(rotation, lattice) -> np.ndarray: """Cartesian matrix of an integer rotation acting on fractional coordinates of the lattice whose rows are the lattice vectors.""" lattice_t = np.transpose(np.asarray(lattice, dtype=float)) return lattice_t @ np.asarray(rotation, dtype=float) @ np.linalg.inv(lattice_t) def _direction_text(vector) -> str: """Cartesian direction as ``[100]``, ``[1-10]`` or ``[0.577 0.577 0.577]``.""" vector = np.asarray(vector, dtype=float) vector = vector / np.max(np.abs(vector)) for value in vector: # first nonzero component positive if abs(value) > 1e-8: if value < 0: vector = -vector break vector[np.abs(vector) < 1e-8] = 0.0 fractions = [Fraction(float(v)).limit_denominator(12) for v in vector] if all(abs(float(f) - v) < 1e-6 for f, v in zip(fractions, vector)): denominator = math.lcm(*[f.denominator for f in fractions]) integers = [int(f * denominator) for f in fractions] if all(abs(i) < 10 for i in integers): return "[" + "".join(str(i) for i in integers) + "]" return "[" + " ".join(str(i) for i in integers) + "]" # hexagonal axes: components that are rational multiples of 1 or sqrt(3) root3 = math.sqrt(3.0) smallest = min(abs(v) for v in vector if abs(v) > 1e-8) terms = [] for value in vector / smallest: plain = Fraction(float(value)).limit_denominator(12) surd = Fraction(float(value / root3)).limit_denominator(12) if abs(float(plain) - value) < 1e-6: terms.append((plain, "")) elif abs(float(surd) * root3 - value) < 1e-6: terms.append((surd, "sqrt3")) else: terms = [] break if terms: denominator = math.lcm(*[f.denominator for f, _ in terms]) texts = [] for fraction, unit in terms: number = int(fraction * denominator) if unit and abs(number) == 1: texts.append(("-" if number < 0 else "") + unit) else: texts.append(f"{number}{unit}") return "[" + " ".join(texts) + "]" unit = vector / np.linalg.norm(vector) return "[" + " ".join(f"{v:.3f}" for v in unit) + "]" def _axis_name(vector) -> str | None: vector = np.asarray(vector, dtype=float) vector = vector / np.linalg.norm(vector) for index, name in enumerate("xyz"): if abs(abs(vector[index]) - 1.0) < 1e-6: return name return None def _unique_operations(rotations, time_reversals) -> tuple[np.ndarray, list[bool]]: """Distinct (Cartesian rotation, time-reversal flag) pairs.""" seen: dict = {} for rotation, flag in zip(np.asarray(rotations, dtype=float), time_reversals): key = (tuple(np.round(rotation, 6).ravel()), bool(flag)) seen.setdefault(key, rotation) keys = list(seen) return np.array([seen[k] for k in keys]), [k[1] for k in keys] # ------------------------------------------------------------ magnetic point group def _strip_lattice(symbol: str) -> str: body = symbol[1:] if body.startswith("_"): body = body[2:] # BNS lattice subscripts are one letter return body
[docs] def magnetic_point_group_symbol(bns_symbol: str, msg_type: int) -> str: """Magnetic point-group symbol derived from a BNS space-group symbol. The lattice letter and its subscript are dropped, glide letters (``a, b, c, n, d, e``) become ``m``, screw axes become plain rotations (``4_2 -> 4``) and every prime is kept; a type II or type IV group gives the non-magnetic point group followed by ``1'``. Args: bns_symbol: BNS symbol in pymatgen's spelling (``"P4_2'/mnm'"``, ``"P_I4/mnc"``, ``"Pm-3m1'"``). msg_type: The type (1-4). Returns: The MPG symbol, e.g. ``"4'/mmm'"`` or ``"4/mmm1'"``. Example: >>> from crystod.magnetic_group import magnetic_point_group_symbol >>> magnetic_point_group_symbol("Pn'ma'", 3) "m'mm'" """ body = _strip_lattice(bns_symbol) body = re.sub(r"([1-6])_[1-5]", r"\1", body) body = re.sub(r"[abcnde]", "m", body) if msg_type == 2 and body.endswith("1'"): body = body[:-2] if msg_type in (2, 4): body = body.replace("'", "") + "1'" return body
_TOKEN = re.compile(r"-?[1-6]'?(?:/m'?)?|m'?") def _rotation_matrix(axis, order: int) -> np.ndarray: axis = np.asarray(axis, dtype=float) axis = axis / np.linalg.norm(axis) theta = 2.0 * np.pi / order k = np.array([[0, -axis[2], axis[1]], [axis[2], 0, -axis[0]], [-axis[1], axis[0], 0]]) return np.eye(3) + np.sin(theta) * k + (1 - np.cos(theta)) * (k @ k) def _mirror(normal) -> np.ndarray: normal = np.asarray(normal, dtype=float) normal = normal / np.linalg.norm(normal) return np.eye(3) - 2.0 * np.outer(normal, normal) def _symbol_generators(symbol: str) -> list[tuple[np.ndarray, bool]] | None: """Generators (Cartesian matrix, primed) of an MPG symbol, or None when the symbol cannot be parsed.""" body, grey = symbol, False if body.endswith("1'") and len(body) > 2 and body[-3] != "-": # a trailing 1' marks a grey group (types II and IV); -1' is not one body, grey = body[:-2], True tokens = [] position = 0 while position < len(body): match = _TOKEN.match(body, position) if match is None: return None tokens.append(match.group(0)) position = match.end() if not tokens: return None def rotation_order(token: str) -> int: digits = re.match(r"-?([1-6])", token) return int(digits.group(1)) if digits else 0 z, x, y = (0, 0, 1), (1, 0, 0), (0, 1, 0) first = rotation_order(tokens[0]) if len(tokens) >= 2 and rotation_order(tokens[1]) == 3: axes = [z, (1, 1, 1), (1, -1, 0)][: len(tokens)] # cubic elif first in (3, 6): axes = [z, x, y][: len(tokens)] # hexagonal axes elif first == 4: axes = [z, x, (1, 1, 0)][: len(tokens)] elif len(tokens) == 1: axes = [z] elif len(tokens) == 3: axes = [x, y, z] else: return None generators = [] for token, axis in zip(tokens, axes): if token.startswith("m"): generators.append((_mirror(axis), token.endswith("'"))) continue rotation_part, _, mirror_part = token.partition("/") order = rotation_order(rotation_part) matrix = _rotation_matrix(axis, order) if rotation_part.startswith("-"): matrix = -matrix generators.append((matrix, rotation_part.endswith("'"))) if mirror_part: generators.append((_mirror(axis), mirror_part.endswith("'"))) if grey: generators.append((np.eye(3), True)) return generators def _closure(generators) -> list[tuple[np.ndarray, bool]] | None: elements = {(tuple(np.round(np.eye(3), 6).ravel()), False): np.eye(3)} frontier = [(np.eye(3), False)] while frontier: new = [] for matrix, flag in frontier: for generator, gflag in generators: product = matrix @ generator pflag = flag ^ gflag key = (tuple(np.round(product, 6).ravel()), pflag) if key not in elements: elements[key] = product new.append((product, pflag)) if len(elements) > 96: return None frontier = new return [(matrix, key[1]) for key, matrix in elements.items()] def _signature(pairs) -> Counter: """Frame-independent multiset of (det, trace, primed) over (R, flag).""" return Counter( (int(round(float(np.linalg.det(r)))), int(round(float(np.trace(r)))), bool(f)) for r, f in pairs ) def check_point_group_symbol(symbol: str, rotations, time_reversals) -> bool: """Whether an MPG symbol matches the rotation parts of the operations. The group generated from the symbol (standard axes per crystal system) and the distinct (rotation, time-reversal) pairs of the operations must have the same order and the same multiset of (det, trace, primed); a group in which a rotation occurs with both flags (a grey group) needs the trailing ``1'``. Args: symbol: MPG symbol (``"4'/mmm'"``). rotations: Rotation matrices of the operations (integer or Cartesian: determinant and trace do not depend on the frame). time_reversals: Time-reversal flags of the operations. Returns: True when they match. """ generators = _symbol_generators(symbol) if generators is None: return False group = _closure(generators) if group is None: return False rotations = np.asarray(rotations, dtype=float) seen: dict = {} for rotation, flag in zip(rotations, time_reversals): seen.setdefault((tuple(np.round(rotation, 6).ravel()), bool(flag)), rotation) pairs = [(rotation, key[1]) for key, rotation in seen.items()] return _signature(group) == _signature(pairs) @functools.lru_cache(maxsize=None) def bns_symbol(bns_number: str) -> str: """BNS symbol of a BNS number from pymatgen's table. Args: bns_number: ``"136.499"``. Returns: ``"P4_2'/mnm'"``. """ # pymatgen.core first: pymatgen 2025.10.7 (the last release for Python # 3.10) fails with a circular import when maggroups is imported before it import pymatgen.core # noqa: F401 from pymatgen.symmetry.maggroups import MagneticSpaceGroup number, minor = (int(part) for part in bns_number.split(".")) return str(MagneticSpaceGroup([number, minor]).sg_symbol) # ------------------------------------------------------------ unified (UNI) symbols #: The bundled table of UNI symbols (1651 lines ``<BNS number> <UNI symbol>``). UNIFIED_SYMBOL_FILE = "magnetic_unified.txt" #: The paper that introduced the UNI symbols. UNIFIED_SYMBOL_REFERENCE = ( "B. J. Campbell, H. T. Stokes, J. M. Perez-Mato and J. Rodriguez-Carvajal, " "Acta Cryst. A78, 99 (2022)" ) @functools.lru_cache(maxsize=1) def _unified_symbols() -> dict[str, str]: path = os.path.join(os.path.dirname(__file__), UNIFIED_SYMBOL_FILE) table = {} with open(path, encoding="utf-8") as handle: for line in handle: if line.startswith("#") or not line.strip(): continue number, symbol = line.split() table[number] = symbol return table
[docs] def unified_symbol(bns_number: str) -> str: """Unified (UNI) symbol of a magnetic space group from its BNS number. The UNI symbol (B. J. Campbell, H. T. Stokes, J. M. Perez-Mato and J. Rodriguez-Carvajal, Acta Cryst. A78, 99 (2022)) is the BNS symbol in the standard BNS setting with the generator of {1, 1'} after a period: ``.1`` for type I, ``.1'`` for type II, nothing for type III; a type IV group carries the anti-translation as the subscript of ``1'`` and its family space group, oriented along the BNS axes, in brackets. Table from the ISOTROPY Software Suite (``data_magnetic.txt``), identical to Table S2 of the paper. Args: bns_number: ``"128.410"``. Returns: ``"P4/mnc.1'_I[I4/mmm]"``. Raises: KeyError: ``bns_number`` is not one of the 1651 BNS numbers. Example: >>> from crystod.magnetic_group import unified_symbol >>> unified_symbol("62.448"), unified_symbol("2.7") ("Pn'ma'", "P-1.1'_c[P-1]") """ return _unified_symbols()[str(bns_number).strip()]
[docs] def unified_point_group_symbol(point_group: str, msg_type: int) -> str: """UNI symbol of a magnetic point group from its usual symbol. Type I appends ``.1`` (``mmm`` -> ``mmm.1``), types II and IV put a period before the final ``1'`` (``4/mmm1'`` -> ``4/mmm.1'``), type III is unchanged. A trailing ``"?"`` (a symbol that disagreed with the operations) is kept. Args: point_group: The MPG symbol of :func:`magnetic_point_group_symbol`. msg_type: The type (1-4) of the magnetic space group. Returns: The UNI symbol of the MPG. Example: >>> from crystod.magnetic_group import unified_point_group_symbol >>> unified_point_group_symbol("4/mmm1'", 4) "4/mmm.1'" """ body, mark = (point_group[:-1], "?") if point_group.endswith("?") else (point_group, "") if msg_type == 1: body += ".1" elif msg_type in (2, 4) and body.endswith("1'"): body = body[:-2] + ".1'" return body + mark
def _unidentified(rotations, translations, flags, used_lattice, lattice, crystal_rotations=None) -> MagneticGroupInfo: """The operations without a name (spglib's name contradicts them).""" return MagneticGroupInfo( uni_number=None, bns_number=None, bns_symbol=None, og_number=None, msg_type=None, parent_number=None, magnetic_point_group=None, point_group_checked=False, n_operations=len(flags), n_primed=int(np.sum(flags)), rotations=np.array([_cartesian(r, used_lattice) for r in rotations]), translations=np.asarray(translations, dtype=float) @ used_lattice @ np.linalg.inv(lattice), time_reversals=np.asarray(flags, dtype=bool), crystal_rotations=crystal_rotations, ) def _named_group(bns_number: str, rotations, translations, flags, lattice, crystal_rotations=None) -> MagneticGroupInfo: """A :class:`MagneticGroupInfo` for operations (in the basis of ``lattice``) that spglib could not name, under the BNS number found from their type, unitary and family groups (:data:`_SPGLIB_UNNAMED`).""" import spglib uni = _SPGLIB_UNI_NUMBERS[bns_number] group_type = spglib.get_magnetic_spacegroup_type(uni) symbol = bns_symbol(bns_number) integer_rotations = np.rint(np.asarray(rotations)).astype(int) flags = np.asarray(flags, dtype=bool) point_group = magnetic_point_group_symbol(symbol, int(group_type.type)) checked = check_point_group_symbol(point_group, integer_rotations, flags) if not checked: point_group += "?" return MagneticGroupInfo( uni_number=uni, bns_number=bns_number, bns_symbol=symbol, og_number=str(group_type.og_number), msg_type=int(group_type.type), parent_number=int(group_type.number), magnetic_point_group=point_group, point_group_checked=checked, n_operations=len(integer_rotations), n_primed=int(flags.sum()), rotations=np.array([_cartesian(r, lattice) for r in integer_rotations]), translations=np.asarray(translations, dtype=float), time_reversals=flags, uni_symbol=unified_symbol(bns_number), uni_point_group=unified_point_group_symbol(point_group, int(group_type.type)), crystal_rotations=crystal_rotations, ) def _crystal_rotations(lattice, positions, numbers, symprec) -> np.ndarray | None: """Distinct Cartesian rotations of the space group of the structure without moments (spglib), None when spglib finds none.""" import spglib try: symmetry = spglib.get_symmetry((lattice, positions, numbers), symprec=symprec) except Exception: # noqa: BLE001 - spglib reports a failed search as its own error type return None if symmetry is None or len(symmetry["rotations"]) == 0: return None rotations = [_cartesian(r, lattice) for r in symmetry["rotations"]] return _unique_operations(rotations, [False] * len(rotations))[0]
[docs] def magnetic_space_group(lattice, positions, numbers, magmoms, symprec: float = 1e-5, mag_symprec: float | None = None) -> MagneticGroupInfo: """The magnetic space group of a spin arrangement (spglib). spglib returns only the operations whose rotation maps the lattice of the cell given onto itself. When that lattice is not invariant under the point group of the crystal (a primitive cell off the standard setting taken with ``--conventional``, a 2x1x1 cell of a cubic crystal), the group found directly can be a subgroup of the true one. The structure is then also identified in the cell of its translations without time reversal, T_U (built by :func:`unitary_cell` from the pure translations among the direct operations), whose lattice is invariant under every rotation of the magnetic group: the direct result is kept when it is complete (its number of operations is that of the T_U cell times the number of T_U cells in the cell given), else the result found in the T_U cell is returned, with its operations repeated over the translations of T_U in the cell given (Cartesian rotations, translations in the fractional coordinates of the cell given), so that the counts keep the convention of the cell given. :attr:`MagneticGroupInfo.crystal_rotations` then come from a primitive cell of the structure without moments. On a cell whose lattice is invariant under the point group of the crystal (every standard cell) the direct result is returned unchanged. Args: lattice: Lattice vectors as rows, ``(3, 3)`` in Angstrom. positions: Fractional coordinates, ``(n_atoms, 3)``. numbers: Atomic numbers (or any type labels), ``(n_atoms,)``. magmoms: Moments as Cartesian axial vectors, ``(n_atoms, 3)`` (zero on the non-magnetic atoms). symprec: Distance tolerance of spglib. mag_symprec: Tolerance on the moments (spglib's ``mag_symprec``; None uses ``symprec``). Returns: A :class:`MagneticGroupInfo`. Raises: SystemExit: spglib finds no magnetic symmetry operations at all (``ValueError`` through ``crystod.mag``). Example: >>> import numpy as np >>> from crystod import mag >>> # a ferromagnet on a simple cubic lattice, given in a 2x1x1 cell >>> group = mag.magnetic_space_group(np.diag([5.74, 2.87, 2.87]), ... [[0, 0, 0], [0.5, 0, 0]], [26, 26], [[0, 0, 1], [0, 0, 1]]) >>> group.bns_number, group.n_operations ('123.345', 32) """ import dataclasses group = _magnetic_space_group_direct(lattice, positions, numbers, magmoms, symprec, mag_symprec) lattice = np.asarray(lattice, dtype=float) point = _point_group_of_structure(lattice, positions, numbers, symprec) if point is None or _lattice_invariant(lattice, point): return group # the lattice of the cell is not invariant under the point group of the # crystal: the cell of the translations without time reversal pure = [np.asarray(t, dtype=float) for R, t, flag in zip(group.rotations, group.translations, group.time_reversals) if not flag and np.allclose(R, np.eye(3), atol=1e-6)] reduced = None if len(pure) > 1: snapped = _snapped_translations(pure) if snapped is not None: grid, translations = snapped moment_tolerance = symprec if mag_symprec is None else float(mag_symprec) reduced = unitary_cell(lattice, positions, numbers, magmoms, translations, grid=grid, moment_tolerance=max(moment_tolerance, 1e-6)) if reduced is None: # one cell of T_U (its lattice is invariant under the rotations of # the group: the direct result is complete), or no reduced cell return dataclasses.replace(group, crystal_rotations=point, confirmed=len(pure) <= 1) reduced_lattice = reduced[0] index = int(round(abs(np.linalg.det(lattice) / np.linalg.det(reduced_lattice)))) try: inner = _magnetic_space_group_direct(*reduced, symprec, mag_symprec) except SystemExit: return dataclasses.replace(group, crystal_rotations=point, confirmed=False) if inner.n_operations * index == group.n_operations and ( group.identified or not inner.identified): return dataclasses.replace(group, crystal_rotations=point) # the operations of the T_U cell, repeated over its translations in the # cell given (fractional coordinates of the cell given) to_given = reduced_lattice @ np.linalg.inv(lattice) rotations, translations, flags = [], [], [] for R, t, flag in zip(inner.rotations, inner.translations, inner.time_reversals): base = np.asarray(t, dtype=float) @ to_given for tau in pure: rotations.append(R) moved = base + tau translations.append(moved - np.floor(moved + 1e-9)) flags.append(bool(flag)) flags = np.asarray(flags, dtype=bool) return dataclasses.replace( inner, n_operations=len(flags), n_primed=int(flags.sum()), rotations=np.asarray(rotations), translations=np.asarray(translations), time_reversals=flags, crystal_rotations=point)
def _snapped_translations(translations): """``(grid, translations)``: the fractional translations on a common grid (denominators up to 240), or None when one does not fit it.""" denominators = [] snapped = [] for t in translations: row = [] for value in np.asarray(t, dtype=float): fraction = Fraction(float(value)).limit_denominator(240) if abs(float(fraction) - value) > 1e-4: return None row.append(fraction) denominators.append(fraction.denominator) snapped.append(row) grid = 1 for d in denominators: grid = grid * d // math.gcd(grid, d) return grid, [np.array([float(x) for x in row]) for row in snapped] def _lattice_invariant(lattice, rotations) -> bool: """Whether every Cartesian rotation maps the lattice (rows) onto itself.""" lattice = np.asarray(lattice, dtype=float) inverse = np.linalg.inv(lattice) for R in rotations: change = lattice @ np.asarray(R, dtype=float).T @ inverse if not np.allclose(change, np.rint(change), atol=1e-4): return False return True _POINT_GROUP_CACHE: dict = {} def _point_group_of_structure(lattice, positions, numbers, symprec): """Distinct Cartesian rotations of the point group of the structure without moments, from a primitive cell of it (spglib, no idealization: the axes of the input), or None; cached per structure.""" import spglib lattice = np.asarray(lattice, dtype=float) positions = np.asarray(positions, dtype=float) key = (lattice.tobytes(), positions.tobytes(), tuple(numbers), float(symprec)) if key in _POINT_GROUP_CACHE: return _POINT_GROUP_CACHE[key] result = None try: with _quiet_spglib(): primitive = spglib.standardize_cell((lattice, positions, list(numbers)), to_primitive=True, no_idealize=True, symprec=symprec) if primitive is not None: symmetry = spglib.get_symmetry(primitive, symprec=symprec) if symmetry is not None and len(symmetry["rotations"]): rotations = [_cartesian(r, primitive[0]) for r in symmetry["rotations"]] result = _unique_operations(rotations, [False] * len(rotations))[0] except Exception: # noqa: BLE001 - spglib reports a failed search as its own error type result = None if len(_POINT_GROUP_CACHE) > 64: _POINT_GROUP_CACHE.clear() _POINT_GROUP_CACHE[key] = result return result def unitary_cell(lattice, positions, numbers, magmoms, translations, grid=48, moment_tolerance: float = 3e-4): """The structure in the cell of its translations without time reversal, or None. Args: lattice, positions, numbers, magmoms: The structure (rows, fractional coordinates, type labels, Cartesian moments). translations: The pure translations (fractional, in the cell given) that map the moments onto themselves, the identity included. grid: A common denominator of their fractional coordinates. moment_tolerance: Moments of two atoms the translations identify must agree within it. Returns: ``(lattice, positions, numbers, magmoms)`` of the smaller cell, or None (the translations are the lattice of the cell itself, are off the grid, or do not map the moments onto themselves). """ from sympy import Matrix from sympy.matrices.normalforms import hermite_normal_form generators = [grid * e for e in np.eye(3, dtype=np.int64)] for t in translations: scaled = np.asarray(t, dtype=float) * grid if not np.allclose(scaled, np.rint(scaled), atol=1e-6): return None generators.append(np.rint(scaled).astype(np.int64)) H = np.array(hermite_normal_form(Matrix(np.array(generators, dtype=np.int64).T))) basis = H.astype(float).T / grid # rows, in the fractional units of the cell if abs(np.linalg.det(basis)) > 1 - 1e-9: return None # a right-handed basis for spglib (the Hermite normal form has a positive # diagonal, so this flips only when the cell given is left-handed): a # left-handed one would name the enantiomorphic partner group if np.linalg.det(basis @ np.asarray(lattice, dtype=float)) < 0: basis[2] = -basis[2] magmoms = np.asarray(magmoms, dtype=float) new_positions = np.asarray(positions, dtype=float) @ np.linalg.inv(basis) new_positions -= np.floor(new_positions) keys = np.rint(new_positions * 1e5).astype(np.int64) % 100000 kept: dict = {} for index, (key, number) in enumerate(zip(map(tuple, keys), numbers)): previous = kept.get((key, number)) if previous is None: kept[(key, number)] = index elif not np.allclose(magmoms[previous], magmoms[index], atol=moment_tolerance): return None # not a translation of the moments order = sorted(kept.values()) if len(order) * round(1 / abs(np.linalg.det(basis))) != len(positions): return None return (basis @ np.asarray(lattice, dtype=float), new_positions[order], [numbers[i] for i in order], np.asarray(magmoms)[order]) def _magnetic_space_group_direct(lattice, positions, numbers, magmoms, symprec: float = 1e-5, mag_symprec: float | None = None) -> MagneticGroupInfo: """The magnetic space group that spglib finds on the cell given (the direct route of :func:`magnetic_space_group`). The point group of the same structure without moments (same ``symprec``) is kept as :attr:`MagneticGroupInfo.crystal_rotations`. Args: lattice: Lattice vectors as rows, ``(3, 3)`` in Angstrom. positions: Fractional coordinates, ``(n_atoms, 3)``. numbers: Atomic numbers (or any type labels), ``(n_atoms,)``. magmoms: Moments as Cartesian axial vectors, ``(n_atoms, 3)`` (zero on the non-magnetic atoms). symprec: Distance tolerance of spglib. mag_symprec: Tolerance on the moments (spglib's ``mag_symprec``; None uses ``symprec``). Returns: A :class:`MagneticGroupInfo`. Raises: SystemExit: spglib finds no magnetic symmetry operations at all (``ValueError`` through ``crystod.mag``). Note: spglib's identification of the group sometimes fails for one choice of the cell and succeeds for an equivalent one (the bcc H-point arrangement with the moments along x). The cell is then re-expressed by its Niggli-reduced, its Delaunay-reduced and a few sheared bases (the same lattice and the same atoms) until one is identified. When none is, the operations of ``spglib.get_magnetic_symmetry`` are returned with the identification fields set to None (:attr:`MagneticGroupInfo.identified` False), so that :func:`macroscopic_responses` still applies. spglib's name is checked against the operations it returns: the type (I-IV, from the operations), the space group of the unitary operations and that of all operations without time reversal (the family) must fit the BNS number, whose first part is the family group for types I-III and the unitary group for type IV. spglib 2.x names the three type IV groups 37.184, 37.185 and 37.186 (unitary group Ccc2) wrongly or not at all, because its database holds operations of type Cmc2_1 for two of them; they are named here from their unitary and family groups (:data:`_SPGLIB_UNNAMED`). Any other contradiction leaves the group unidentified. Example: >>> import numpy as np >>> from crystod import mag >>> group = mag.magnetic_space_group(np.eye(3) * 2.87, ... [[0, 0, 0], [0.5, 0.5, 0.5]], [26, 26], [[0, 0, 1], [0, 0, -1]]) >>> group.uni_number, group.msg_type (1070, 4) """ import spglib lattice = np.asarray(lattice, dtype=float) positions = np.asarray(positions, dtype=float) magmoms = np.asarray(magmoms, dtype=float) numbers = list(numbers) tolerance = -1.0 if mag_symprec is None else float(mag_symprec) if not (np.all(np.isfinite(magmoms)) and np.all(np.isfinite(positions))): raise SystemExit("ERROR: the spin arrangement holds non-finite values; " "no magnetic space group.") dataset, used_lattice = None, lattice with _quiet_spglib(): for candidate in _equivalent_lattices(lattice): moved = positions @ lattice @ np.linalg.inv(candidate) cell = (candidate, moved - np.floor(moved), numbers, magmoms) try: dataset = spglib.get_magnetic_symmetry_dataset( cell, is_axial=True, symprec=symprec, mag_symprec=tolerance) except Exception: # noqa: BLE001 - spglib reports a failed search as its own error type dataset = None if dataset is not None: used_lattice = candidate break if dataset is None: try: operations = spglib.get_magnetic_symmetry( (lattice, positions, numbers, magmoms), is_axial=True, symprec=symprec, mag_symprec=tolerance) except Exception: # noqa: BLE001 operations = None crystal = _crystal_rotations(lattice, positions, numbers, symprec) if dataset is None: if operations is None or len(operations["rotations"]) == 0: raise SystemExit("ERROR: spglib found no magnetic space group for this spin " "arrangement; try another --tolerance.") flags = np.asarray(operations["time_reversals"], dtype=bool) signature = _group_signature(operations["rotations"], operations["translations"], flags, lattice) if signature in _SPGLIB_UNNAMED: return _named_group(_SPGLIB_UNNAMED[signature], operations["rotations"], operations["translations"], flags, lattice, crystal_rotations=crystal) return MagneticGroupInfo( uni_number=None, bns_number=None, bns_symbol=None, og_number=None, msg_type=None, parent_number=None, magnetic_point_group=None, point_group_checked=False, n_operations=len(flags), n_primed=int(flags.sum()), rotations=np.array([_cartesian(r, lattice) for r in operations["rotations"]]), translations=np.asarray(operations["translations"], dtype=float), time_reversals=flags, crystal_rotations=crystal, ) integer_rotations = np.asarray(dataset.rotations) flags = np.asarray(dataset.time_reversals, dtype=bool) # spglib's name is checked against the type, unitary and family groups of # its own operations; the three groups it cannot name are named here signature = _group_signature(integer_rotations, dataset.translations, flags, used_lattice) group_type = spglib.get_magnetic_spacegroup_type(dataset.uni_number) if not _signature_agrees(group_type.bns_number, signature): corrected = _SPGLIB_UNNAMED.get(signature) if corrected is None: return _unidentified(integer_rotations, dataset.translations, flags, used_lattice, lattice, crystal_rotations=crystal) group_type = spglib.get_magnetic_spacegroup_type(_SPGLIB_UNI_NUMBERS[corrected]) uni_number = int(_SPGLIB_UNI_NUMBERS.get(str(group_type.bns_number), dataset.uni_number)) symbol = bns_symbol(group_type.bns_number) point_group = magnetic_point_group_symbol(symbol, int(group_type.type)) checked = check_point_group_symbol(point_group, integer_rotations, flags) if not checked: point_group += "?" # translations back in the fractional coordinates of the cell given translations = np.asarray(dataset.translations, dtype=float) @ used_lattice @ np.linalg.inv(lattice) return MagneticGroupInfo( uni_number=uni_number, bns_number=str(group_type.bns_number), bns_symbol=symbol, og_number=str(group_type.og_number), msg_type=int(group_type.type), parent_number=int(group_type.number), magnetic_point_group=point_group, point_group_checked=checked, n_operations=len(integer_rotations), n_primed=int(flags.sum()), rotations=np.array([_cartesian(r, used_lattice) for r in integer_rotations]), translations=translations, time_reversals=flags, uni_symbol=unified_symbol(group_type.bns_number), uni_point_group=unified_point_group_symbol(point_group, int(group_type.type)), crystal_rotations=crystal, ) # ------------------------------------------------- checking spglib's identification #: Type IV groups that spglib (2.x) cannot name: the operations its database #: holds for 37.184 and 37.186 have a unitary subgroup of type Cmc2_1 (36), not #: Ccc2 (37), so that spglib returns 36.177 / 36.179 for them, and 37.185 is #: not identified at all. ``(type, unitary space group, family space group)`` #: -> BNS number, from the UNI symbols ``Ccc2.1'_c[Cmm2]``, ``Ccc2.1'_a[Pcc2]`` #: and ``Ccc2.1'_A[Fmm2]`` (ISO-MAG), checked against the magnetic isotropy #: subgroups of ISOTROPY's ``data_magnetic.txt``. _SPGLIB_UNNAMED = {(4, 37, 35): "37.184", (4, 37, 27): "37.185", (4, 37, 42): "37.186"} #: spglib's serial (UNI) numbers of those BNS numbers. _SPGLIB_UNI_NUMBERS = {"37.184": 282, "37.185": 283, "37.186": 284} def _space_group_number(rotations, translations, lattice) -> int | None: """Space-group type generated by the operations ``(W, v)`` (in the basis of ``lattice``), from a structure of two generic orbits.""" 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(np.asarray(W) @ x0 + np.asarray(v, dtype=float), 1.0) if not any(np.allclose(((x - q + 0.5) % 1.0) - 0.5, 0.0, atol=1e-6) for q 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) if dataset is None: return None return int(dataset["number"] if isinstance(dataset, dict) else dataset.number) def _group_signature(rotations, translations, time_reversals, lattice): """``(type, unitary space group, family space group)`` of magnetic operations given in the basis of ``lattice`` (integer rotations). The type follows from the operations: II when the identity with time reversal and no translation is one of them, IV when the identity with time reversal comes with a translation (an anti-translation), III when any other operation carries time reversal, I when none does. """ rotations = np.rint(np.asarray(rotations)).astype(int) translations = np.asarray(translations, dtype=float) flags = np.asarray(time_reversals, dtype=bool) identity = np.all(rotations == np.eye(3, dtype=int), axis=(1, 2)) wrapped = ((translations + 0.5) % 1.0) - 0.5 pure = np.all(np.abs(wrapped) < 1e-6, axis=1) if np.any(identity & flags & pure): msg_type = 2 elif np.any(identity & flags): msg_type = 4 elif np.any(flags): msg_type = 3 else: msg_type = 1 unitary = _space_group_number(rotations[~flags], translations[~flags], lattice) family = _space_group_number(rotations, translations, lattice) return msg_type, unitary, family def _signature_agrees(bns_number: str, signature) -> bool: """Whether a BNS number fits the type, unitary and family groups of the operations: the BNS number starts with the family space group for types I-III (the unitary one for type I, the same group) and with the unitary space group for type IV.""" msg_type, unitary, family = signature major = int(str(bns_number).split(".")[0]) if msg_type == 4: return major == unitary if msg_type == 1: return major == unitary == family return major == family @contextlib.contextmanager def _quiet_spglib(): """Silence spglib's C-level warnings (``spglib: Failed to match with UNI number!``) for the duration of the block; the previous setting of ``SPGLIB_WARNING`` is restored.""" previous = os.environ.get("SPGLIB_WARNING") os.environ["SPGLIB_WARNING"] = "OFF" try: yield finally: if previous is None: os.environ.pop("SPGLIB_WARNING", None) else: os.environ["SPGLIB_WARNING"] = previous _SHEARS = tuple( np.array(matrix, dtype=int) for matrix in ( [[1, 1, 0], [0, 1, 0], [0, 0, 1]], [[1, 0, 0], [0, 1, 1], [0, 0, 1]], [[1, 0, 1], [0, 1, 0], [0, 0, 1]], [[1, 0, 0], [1, 1, 0], [0, 0, 1]], [[1, 0, 0], [0, 1, 0], [0, 1, 1]], [[1, 0, 0], [0, 1, 0], [1, 0, 1]], ) ) def _equivalent_lattices(lattice: np.ndarray): """The lattice given, then its Niggli- and Delaunay-reduced bases and a few sheared bases: the same lattice (unimodular changes of basis).""" import spglib yield lattice seen = [lattice] reduced = [] for reduce in (spglib.niggli_reduce, spglib.delaunay_reduce): try: candidate = reduce(lattice) except Exception: # noqa: BLE001 candidate = None if candidate is not None: reduced.append(np.asarray(candidate, dtype=float)) for candidate in reduced + [shear @ lattice for shear in _SHEARS]: change = candidate @ np.linalg.inv(lattice) if not (np.allclose(change, np.rint(change), atol=1e-6) and abs(abs(np.linalg.det(change)) - 1.0) < 1e-6): continue if any(np.allclose(candidate, other, atol=1e-8) for other in seen): continue seen.append(candidate) yield candidate def unconfirmed_note(group) -> str | None: """The NOTE printed under the magnetic space group when :attr:`MagneticGroupInfo.confirmed` is False, else None.""" if group is None or getattr(group, "confirmed", True): return None return ("NOTE: the lattice of this cell is not invariant under the point group of the " "crystal and the group could not be confirmed on a reduced cell; it can be a " "subgroup of the true group.") def format_magnetic_group(group: MagneticGroupInfo) -> str: """``"P4_2'/mnm' (BNS 136.499, type III), 16 operations, 8 with time reversal"``; ``"not identified by spglib (128 operations, 64 with time reversal)"`` when spglib cannot name the group.""" if not group.identified: return (f"not identified by spglib ({group.n_operations} operations, " f"{group.n_primed} with time reversal)") return (f"{group.bns_symbol} (BNS {group.bns_number}, type {group.type_name}), " f"{group.n_operations} operations, {group.n_primed} with time reversal") def format_magnetic_point_group(group: MagneticGroupInfo) -> str: """``"4'/mmm'"``; ``"not identified (32 elements, 16 with time reversal)"`` when spglib cannot name the group.""" if not group.identified: return (f"not identified ({group.n_point_operations} elements, " f"{group.n_point_primed} with time reversal)") return str(group.magnetic_point_group) def format_unified_symbols(group: MagneticGroupInfo) -> str | None: """``"P4/mnc.1'_I[I4/mmm]; point group 4/mmm.1'"``: the UNI symbols of the MSG and the MPG; None when the group is not identified.""" if not group.identified or group.uni_symbol is None: return None return f"{group.uni_symbol}; point group {group.uni_point_group}" # ------------------------------------------------------------ responses def _vector_direction(form) -> str: """Direction of an allowed vector form: ``"none"``, ``"along z"``, ``"in the xy plane"``, ``"any direction"`` (Cartesian axes).""" tensors = np.asarray(form.tensors, dtype=float).reshape(-1, 3) count = len(tensors) if count == 0: return "none" if count >= 3: return "any direction" if count == 1: vector = tensors[0] name = _axis_name(vector) return f"along {name}" if name else f"along {_direction_text(vector)}" normal = np.cross(tensors[0], tensors[1]) name = _axis_name(normal) if name is not None: plane = {"x": "yz", "y": "xz", "z": "xy"}[name] return f"in the {plane} plane" return f"in the plane perpendicular to {_direction_text(normal)}" #: The former name of :func:`_vector_direction`. _magnetization_direction = _vector_direction def _polarization_note(polarization, crystal_rotations) -> str: """The marker after the polarization: induced by the spin order, the direction the crystal without spins allows, or nothing.""" from .tensor_form import tensor_form_of_operations if crystal_rotations is None or not polarization.n_independent: return "" unique = _unique_operations(crystal_rotations, [False] * len(crystal_rotations))[0] crystal = tensor_form_of_operations(unique, "V") if crystal.n_independent == 0: return " (induced by the spin order)" if polarization.n_independent > crystal.n_independent: return f" (the crystal without spins: {_vector_direction(crystal)})" return ""
[docs] def macroscopic_responses(group_or_rotations, time_reversals=None, *, crystal_rotations=None) -> MagneticResponses: """Responses that a magnetic point group allows by symmetry. Args: group_or_rotations: A :class:`MagneticGroupInfo`, or Cartesian rotation matrices ``(n, 3, 3)`` of the operations. time_reversals: The time-reversal flags (needed with rotations). crystal_rotations: Cartesian rotations of the point group of the crystal without spins, for the note on the electric polarization (with a :class:`MagneticGroupInfo`, its :attr:`~MagneticGroupInfo.crystal_rotations` are used when this is None). Returns: A :class:`MagneticResponses` with the forms of the net magnetization (``aeV``), the electric polarization (``V``), the linear magnetoelectric tensor (``aeV2``) and the piezomagnetic tensor (``aeV[V2]``). Raises: ValueError: Rotations given without flags. Example: >>> responses = mag.macroscopic_responses(group) # see magnetic_space_group >>> responses.summary() 'net magnetization none; electric polarization none; linear magnetoelectric effect none; piezomagnetism none' """ from .tensor_form import tensor_form_of_operations if isinstance(group_or_rotations, MagneticGroupInfo): rotations = group_or_rotations.rotations time_reversals = group_or_rotations.time_reversals if crystal_rotations is None: crystal_rotations = group_or_rotations.crystal_rotations else: rotations = group_or_rotations if time_reversals is None: raise ValueError("time_reversals are needed with explicit rotations") unique, flags = _unique_operations(rotations, time_reversals) magnetization = tensor_form_of_operations(unique, "aeV", time_reversal=flags) polarization = tensor_form_of_operations(unique, "V", time_reversal=flags) magnetoelectric = tensor_form_of_operations(unique, "aeV2", time_reversal=flags) piezomagnetic = tensor_form_of_operations(unique, "aeV[V2]", time_reversal=flags) return MagneticResponses( magnetization=magnetization, magnetoelectric=magnetoelectric, piezomagnetic=piezomagnetic, magnetization_direction=_vector_direction(magnetization), polarization=polarization, polarization_direction=_vector_direction(polarization), polarization_note=_polarization_note(polarization, crystal_rotations), )
def _matrix_lines(form, letter: str) -> list[str]: from .tensor_form import _table n_columns = len(form.matrix[0]) rows = [[letter] + [str(c + 1) for c in range(n_columns)]] rows += [[str(r + 1)] + [entry.replace("T", letter) for entry in row] for r, row in enumerate(form.matrix)] return [" " + line for line in _table(rows)]
[docs] def format_magnetic_responses(responses: MagneticResponses, forms: bool = True) -> list[str]: """Lines describing the responses, in the wording "allowed by symmetry". Args: responses: A :class:`MagneticResponses`. forms: Also give the matrix forms of the allowed tensors (the magnetoelectric tensor as ``alpha``, the piezomagnetic one in the 3x6 matrix notation as ``L``). Returns: Lines indented by two spaces. """ lines = [] if responses.n_magnetization: lines.append(f" net magnetization: allowed by symmetry " f"{responses.magnetization_direction}") else: lines.append(" net magnetization: forbidden by symmetry") if responses.n_polarization: lines.append(f" electric polarization: allowed by symmetry " f"{responses.polarization_direction}{responses.polarization_note}") else: lines.append(" electric polarization: forbidden by symmetry") for name, form, letter in ( ("linear magnetoelectric effect", responses.magnetoelectric, "alpha"), ("piezomagnetism", responses.piezomagnetic, "L"), ): count = form.n_independent if not count: lines.append(f" {name}: forbidden by symmetry") continue lines.append(f" {name}: allowed by symmetry, {count} independent " f"component{'s' if count != 1 else ''}") if forms: lines += _matrix_lines(form, letter) return lines
# ------------------------------------------------------------ collinear classes def magnetic_cell_translations(cell_matrix) -> list[np.ndarray]: """Lattice translations of the primitive cell inside a magnetic cell. Args: cell_matrix: Integer ``(3, 3)`` matrix whose rows are the magnetic cell vectors in units of the primitive lattice vectors. Returns: The translations ``T`` (primitive fractional coordinates, one per primitive cell of the magnetic cell) in the order ``crystod-mag`` lays out the spin field ``field[cell, site]``. """ cell_matrix = np.asarray(cell_matrix, dtype=float) inverse_cell = np.linalg.inv(cell_matrix) corner_shifts = [np.zeros(3)] for axis in range(3): corner_shifts = corner_shifts + [shift + cell_matrix[axis] for shift in corner_shifts] corner_array = np.array(corner_shifts, dtype=float) t_low = np.floor(corner_array.min(axis=0)).astype(int) - 1 t_high = np.ceil(corner_array.max(axis=0)).astype(int) + 1 coset_eps = 1e-8 translations = [] for t1 in range(t_low[0], t_high[0] + 1): for t2 in range(t_low[1], t_high[1] + 1): for t3 in range(t_low[2], t_high[2] + 1): translation = np.array([t1, t2, t3], dtype=float) frac = translation @ inverse_cell if np.all(frac > -coset_eps) and np.all(frac < 1 - coset_eps): translations.append(translation) return translations def _chi_l(rotation: np.ndarray, degree: int) -> float: proper = rotation * float(np.sign(np.linalg.det(rotation))) cos_theta = np.clip((np.trace(proper) - 1.0) / 2.0, -1.0, 1.0) theta = float(np.arccos(cos_theta)) if theta < 1e-8: return float(2 * degree + 1) return float(np.sin((degree + 0.5) * theta) / np.sin(theta / 2.0)) def _monomials(degree: int) -> list[tuple[int, int, int]]: return sorted( ((a, b, degree - a - b) for a in range(degree + 1) for b in range(degree + 1 - a)), reverse=True, ) def _evaluate(points: np.ndarray, exponents) -> np.ndarray: return np.array([np.prod(points ** np.array(e), axis=1) for e in exponents]).T def _monomial_text(exponent) -> str: parts = [] for name, power in zip(("k_x", "k_y", "k_z"), exponent): if power == 1: parts.append(name) elif power > 1: parts.append(f"{name}^{power}") return " ".join(parts) def _surd_coefficients(values) -> list[tuple[int, str]] | None: """Integer multiples of 1 and sqrt(3) proportional to ``values`` (hexagonal axes), e.g. ``[(3, ""), (-2, "sqrt3"), (-3, "")]``; the scaling with the fewest sqrt3 terms is chosen. None when the values are not of that form.""" root3 = math.sqrt(3.0) smallest = min(abs(v) for v in values if abs(v) > 1e-12) best = None for factor in (1.0, root3, 1.0 / root3): terms = [] for value in np.asarray(values, dtype=float) / smallest * factor: plain = Fraction(float(value)).limit_denominator(12) surd = Fraction(float(value / root3)).limit_denominator(12) if abs(float(plain) - value) < 1e-6: terms.append((plain, "")) elif abs(float(surd) * root3 - value) < 1e-6: terms.append((surd, "sqrt3")) else: terms = None break if terms is None: continue denominator = math.lcm(*[f.denominator for f, _ in terms]) integers = [int(f * denominator) for f, _ in terms] divisor = math.gcd(*integers) candidate = [(i // divisor, unit) for i, (_, unit) in zip(integers, terms)] key = (sum(1 for _, unit in candidate if unit), max(abs(i) for i, _ in candidate)) if best is None or key < best[0]: best = (key, candidate) return None if best is None else best[1] def _polynomial_text(coefficients, exponents) -> str: terms = [(c, e) for c, e in zip(coefficients, exponents) if abs(c) > 1e-9] if not terms: return "0" exact = [] for value, _ in terms: fraction = Fraction(float(value)).limit_denominator(1000) exact.append(fraction if abs(float(fraction) - value) < 1e-8 else None) surds = None if all(f is not None for f in exact): denominator = math.lcm(*[f.denominator for f in exact]) integers = [int(f * denominator) for f in exact] divisor = math.gcd(*integers) values: list = [i // divisor for i in integers] else: surds = _surd_coefficients([v for v, _ in terms]) if surds is not None: values = [number for number, _ in surds] else: scale = max(abs(v) for v, _ in terms) values = [v / scale for v, _ in terms] if values[0] < 0: values = [-v for v in values] common = tuple(min(e[i] for _, e in terms) for i in range(3)) reduced = [tuple(p - c for p, c in zip(e, common)) for _, e in terms] pieces = [] for index, (value, exponent) in enumerate(zip(values, reduced)): magnitude = abs(value) body = _monomial_text(exponent) unit = surds[index][1] if surds is not None else "" if unit: coefficient = unit if magnitude == 1 else f"{magnitude}{unit}" elif isinstance(magnitude, int): coefficient = "" if magnitude == 1 and body else str(magnitude) else: coefficient = f"{magnitude:.4f}" text = " ".join(part for part in (coefficient, body) if part) if not pieces: pieces.append(("-" if value < 0 else "") + text) else: pieces.append(("- " if value < 0 else "+ ") + text) inner = " ".join(pieces) prefix = _monomial_text(common) if len(terms) == 1: return prefix return f"{prefix} ({inner})" if prefix else inner def spin_splitting_forms(rotations, characters, degree: int) -> tuple[str, ...]: """Polynomials ``p`` of one degree in ``(k_x, k_y, k_z)`` with ``p(R k) = chi(R) p(k)`` for every rotation ``R``. Args: rotations: Cartesian rotation matrices of a point group. characters: The one-dimensional character (+1 or -1) of each. degree: The polynomial degree. Returns: The polynomials as text (``"k_x k_y"``), one per basis vector of the reduced row-echelon basis. """ from .invariants import _rref exponents = _monomials(degree) rng = np.random.default_rng(20221) points = rng.normal(size=(3 * len(exponents) + 6, 3)) blocks = [] base = _evaluate(points, exponents) for rotation, character in zip(rotations, characters): moved = _evaluate(points @ np.asarray(rotation, dtype=float).T, exponents) blocks.append(moved - character * base) matrix = np.vstack(blocks) _, singular, vt = np.linalg.svd(matrix) tolerance = 1e-8 * max(1.0, float(singular[0])) rank = int(np.sum(singular > tolerance)) null = vt[rank:] if len(null) == 0: return () reduced, _ = _rref(null) return tuple(_polynomial_text(row, exponents) for row in reduced) def _rotation_axis(rotation: np.ndarray) -> np.ndarray: values, vectors = np.linalg.eig(rotation) index = int(np.argmin(np.abs(values - 1.0))) axis = np.real(vectors[:, index]) return axis / np.linalg.norm(axis) def _degenerate_sets(swapping_rotations) -> tuple[list[np.ndarray], list[np.ndarray]]: """Normals of the spin-degenerate planes and directions of the lines. A sublattice-exchanging rotation part ``R`` keeps the two spin channels degenerate at every k with ``R k = k`` and, because the nonrelativistic bands satisfy ``E(k) = E(-k)``, at every k with ``R k = -k``: a mirror or a two-fold rotation gives a plane, a proper rotation (or the proper part of an improper one) gives its axis. """ planes: list[np.ndarray] = [] lines: list[np.ndarray] = [] def add(collection, vector): vector = vector / np.linalg.norm(vector) if not any(abs(abs(np.dot(vector, other)) - 1.0) < 1e-6 for other in collection): collection.append(vector) for rotation in swapping_rotations: proper = rotation * float(np.sign(np.linalg.det(rotation))) if np.allclose(proper, np.eye(3), atol=1e-6): continue axis = _rotation_axis(proper) if abs(np.trace(proper) + 1.0) < 1e-6: # two-fold proper part add(planes, axis) add(lines, axis) lines = [line for line in lines if not any(abs(np.dot(line, normal)) < 1e-6 for normal in planes)] return planes, lines
[docs] def classify_collinear(rotations, translations, positions, site_indices, cell_matrix, field, lattice, *, symprec: float | None = None) -> CollinearClass: """Nonrelativistic class of one collinear spin arrangement. The arrangement is reduced to its sign pattern ``s = +1 / -1 / 0`` along the common spin axis (with the magnitudes); the space-group operations of the non-magnetic crystal, combined with every primitive translation inside the magnetic cell, are sorted into those that keep the pattern (``H``) and those that reverse every sign (``A``, the operations that exchange the two sublattices). Net moment nonzero: ferromagnet or ferrimagnet; ``A`` empty: compensated arrangement whose sublattices are not related by symmetry; ``A`` holding a pure translation or the inversion: conventional antiferromagnet; otherwise an altermagnet, whose wave type is the lowest even ``l`` at which the character ``chi_A`` (+1 on the rotation parts of ``H``, -1 on those of ``A``) occurs in the angular-momentum representation ``D_l`` (2: d-wave, 4: g-wave, 6: i-wave), after Smejkal, Sinova and Jungwirth, Phys. Rev. X 12, 031042 (2022). Args: rotations: Integer rotations of the space group of the primitive cell (``SymmetryOnlyVibrations.rotations``). translations: Their fractional translations. positions: Fractional positions of the primitive cell. site_indices: Indices of the N magnetic sites. cell_matrix: Integer ``(3, 3)`` magnetic cell in primitive units (rows). field: The real spin field ``(n_cells, N, 3)`` over the magnetic cell, cells in the order of :func:`magnetic_cell_translations`. lattice: Primitive lattice vectors as rows (for the Cartesian rotations and directions). symprec: Distance tolerance (Angstrom) of the position matching: an image of a site matches the nearest site within it (the tolerance the operations were found with, ``--tolerance`` of ``crystod-mag``). Sites within 1e-5 in every fractional coordinate always match; None (default) matches those only. Returns: A :class:`CollinearClass`. Example: >>> # bcc cell with a +z / -z pair: the body-centring translation >>> # exchanges the two sublattices >>> import numpy as np, spglib >>> from crystod import mag >>> lattice = np.eye(3) * 2.87 >>> positions = [[0, 0, 0], [0.5, 0.5, 0.5]] >>> sym = spglib.get_symmetry_dataset((lattice, positions, [26, 26])) >>> field = np.array([[[0, 0, 1], [0, 0, -1]]], dtype=float) >>> klass = mag.classify_collinear(sym.rotations, sym.translations, positions, ... [0, 1], np.eye(3, dtype=int), field, lattice) >>> klass.name 'antiferromagnet (conventional: a translation exchanges the sublattices, T tau)' """ field = np.asarray(field, dtype=float) n_cells, n_sites, _ = field.shape flat = field.reshape(-1, 3) norms = np.linalg.norm(flat, axis=1) scale = max(float(norms.max()), 1e-300) nonzero = norms > 1e-8 * scale net = flat.sum(axis=0) if not nonzero.any(): return CollinearClass(name=CLASS_NONCOLLINEAR, net_moment=net) axis = flat[np.argmax(nonzero)] / norms[np.argmax(nonzero)] for vector, norm in zip(flat[nonzero], norms[nonzero]): if np.linalg.norm(np.cross(axis, vector / norm)) > 1e-6: return CollinearClass(name=CLASS_NONCOLLINEAR, net_moment=net) for value in axis: # canonical axis: first nonzero component positive if abs(value) > 1e-8: if value < 0: axis = -axis break projected = flat @ axis / scale projected[~nonzero] = 0.0 if np.linalg.norm(net) > 1e-6 * scale: signs = np.sign(projected[nonzero]) name = CLASS_FERROMAGNET if np.all(signs == signs[0]) else CLASS_FERRIMAGNET return CollinearClass(name=name, axis=axis, net_moment=net) positions = np.asarray(positions, dtype=float) site_positions = positions[list(site_indices)] cell_translations = np.array(magnetic_cell_translations(cell_matrix)) inverse_cell = np.linalg.inv(np.asarray(cell_matrix, dtype=float)) # (cell, site) -> fractional position sites = (cell_translations[:, None, :] + site_positions[None, :, :]).reshape(-1, 3) metric_lattice = np.asarray(lattice, dtype=float) distance_tolerance = -1.0 if symprec is None else float(symprec) def locate(points: np.ndarray) -> np.ndarray | None: """Index (cell * N + site) of every point, modulo the magnetic cell.""" result = np.empty(len(points), dtype=int) for p, point in enumerate(points): diff = point[None, :] - site_positions residual = diff - np.rint(diff) match = np.where(np.all(np.abs(residual) < 1e-5, axis=1))[0] if len(match) == 0 and distance_tolerance >= 0.0: # off-ideal positions: the nearest site within the tolerance distances = np.linalg.norm(residual @ metric_lattice, axis=1) nearest = int(np.argmin(distances)) if distances[nearest] <= distance_tolerance: match = np.array([nearest]) if len(match) == 0: return None site = int(match[0]) shift = np.rint(diff[site]) relative = (shift[None, :] - cell_translations) @ inverse_cell cell = np.where(np.all(np.abs(relative - np.rint(relative)) < 1e-6, axis=1))[0] if len(cell) == 0: return None result[p] = int(cell[0]) * n_sites + site return result lattice = np.asarray(lattice, dtype=float) preserving, swapping = [], [] for rotation, translation in zip(np.asarray(rotations), np.asarray(translations)): moved = sites @ np.asarray(rotation, dtype=float).T + translation for shift in cell_translations: image = locate(moved + shift) if image is None: continue target = projected[image] if np.allclose(target, projected, atol=1e-6): preserving.append((rotation, shift + translation)) elif np.allclose(target, -projected, atol=1e-6): swapping.append((rotation, shift + translation)) common = dict(axis=axis, n_preserving=len(preserving), n_swapping=len(swapping), net_moment=net) if not swapping: return CollinearClass(name=CLASS_COMPENSATED, **common) identity = np.eye(3, dtype=int) if any(np.array_equal(np.asarray(r), identity) for r, _ in swapping): return CollinearClass(name=CLASS_AFM_TRANSLATION, **common) if any(np.array_equal(np.asarray(r), -identity) for r, _ in swapping): return CollinearClass(name=CLASS_AFM_INVERSION, **common) def distinct(operations): found: dict = {} for rotation, _ in operations: found.setdefault(tuple(np.asarray(rotation).ravel()), rotation) return [_cartesian(r, lattice) for r in found.values()] kept = distinct(preserving) exchanged = distinct(swapping) for a in kept: if any(np.allclose(a, b, atol=1e-6) for b in exchanged): raise RuntimeError("a rotation part both keeps and reverses the sign pattern") group = kept + exchanged characters = [1.0] * len(kept) + [-1.0] * len(exchanged) order = None for degree in (2, 4, 6): multiplicity = sum(c * _chi_l(r, degree) for r, c in zip(group, characters)) / len(group) if multiplicity > 0.5: order = degree break forms = spin_splitting_forms(group, characters, order) if order else () planes, lines = _degenerate_sets(exchanged) return CollinearClass( name=CLASS_ALTERMAGNET, wave=_WAVE_NAMES.get(order), order=order, spin_splitting=forms, degenerate_planes=tuple(sorted(_direction_text(v) for v in planes)[::-1]), degenerate_lines=tuple(sorted(_direction_text(v) for v in lines)[::-1]), **common, )
# ------------------------------------------------------------ phonon angular momentum #: References of the phonon angular momentum classification. PHONON_ANGULAR_MOMENTUM_REFERENCE = ( "L. Zhang and Q. Niu, Phys. Rev. Lett. 112, 085503 (2014)" ) _PAM_WAVE_LETTERS = "spdfghij"
[docs] @dataclass(frozen=True, eq=False) class AngularMomentumComponent: """One Cartesian component ``l_i(q)`` of the phonon angular momentum near Gamma, as a magnetic point group allows it. Attributes: axis: ``"x"``, ``"y"`` or ``"z"`` (Cartesian axes of the operations). degree: The lowest degree ``n`` of a homogeneous polynomial in ``q`` that symmetry allows for this component, or None when it vanishes (or no form exists up to the degree searched). forms: The polynomials of that degree, one per basis vector of the reduced row-echelon basis of the space of i-th components (``("q_x q_y",)``; ``("const",)`` at degree 0). nodal: Unit vectors of the nodes symmetry enforces through Gamma: the normals of the planes (three dimensions) or the directions of the lines (two dimensions), as Cartesian directions (``("[100]", "[010]")``). zero_reason: Why the component vanishes at every q: ``"P T"``, or in two dimensions ``"the mirror of the layer"`` / ``"2' along the layer normal"``; empty when it does not vanish. two_dimensional: True when ``q`` is restricted to a plane. max_degree: The highest degree searched. """ axis: str degree: int | None = None forms: tuple = () nodal: tuple = () zero_reason: str = "" two_dimensional: bool = False max_degree: int = 9 @property def letter(self) -> str: """The wave letter (``"s"`` .. ``"j"``), the degree as a number beyond ``j`` (``"8"``), ``"-"`` when the component vanishes.""" if self.degree is None: return "-" if self.degree < len(_PAM_WAVE_LETTERS): return _PAM_WAVE_LETTERS[self.degree] return str(self.degree) @property def short_name(self) -> str: """``"d-wave"``, ``"degree 8"``, ``"none (P T)"`` or ``"none up to degree 9"``.""" if self.degree is None: if self.zero_reason: return f"none ({self.zero_reason})" return f"none up to degree {self.max_degree}" if self.degree < len(_PAM_WAVE_LETTERS): return f"{self.letter}-wave" return f"degree {self.degree}" @property def n_nodal(self) -> int: """Number of enforced nodal planes (lines in two dimensions).""" return len(self.nodal)
[docs] def nodal_text(self) -> str: """``"zero on the planes perpendicular to [100], [010]"`` (``"zero on the lines along ..."`` in two dimensions), empty without nodes.""" if not self.nodal: return "" many = len(self.nodal) > 1 if self.two_dimensional: kind = "lines along" if many else "line along" else: kind = "planes perpendicular to" if many else "plane perpendicular to" return f"zero on the {kind} " + ", ".join(self.nodal)
[docs] def text(self) -> str: """``"l_z ~ q_x q_y (d-wave; zero on the planes perpendicular to [100], [010])"``, ``"l_x = 0 (P T)"``.""" if self.degree is None: reason = self.zero_reason or f"no form up to degree {self.max_degree}" return f"l_{self.axis} = 0 ({reason})" parts = [self.short_name] nodes = self.nodal_text() if nodes: parts.append(nodes) return f"l_{self.axis} ~ {', '.join(self.forms)} ({'; '.join(parts)})"
[docs] @dataclass(frozen=True, eq=False) class PhononAngularMomentum: """The phonon angular momentum ``l(q)`` near Gamma allowed by a magnetic point group, component by component (:func:`phonon_angular_momentum`). Attributes: components: Three :class:`AngularMomentumComponent` (``l_x``, ``l_y``, ``l_z``). pt_symmetric: True when the group contains ``P T`` (``l = 0`` at every q). plane_normal: The normal of the plane ``q`` is restricted to (two dimensions), or None. in_plane: The names and Cartesian unit vectors of the two in-plane coordinates in two dimensions (``(("q_x", [1, 0, 0]), ...)``), else empty. max_degree: The highest degree searched. """ components: tuple pt_symmetric: bool plane_normal: np.ndarray | None = None in_plane: tuple = () max_degree: int = 9
[docs] def component(self, axis: str) -> AngularMomentumComponent: """The component ``"x"``, ``"y"`` or ``"z"``.""" return self.components["xyz".index(axis)]
[docs] def text(self) -> str: """The three components joined by ``"; "`` (the line ``phonon angular momentum:`` of ``crystod-mag``).""" return "; ".join(component.text() for component in self.components)
def _pam_operations(group_or_rotations, time_reversals): """Distinct (Cartesian rotation, time-reversal flag) pairs, idealized.""" if isinstance(group_or_rotations, MagneticGroupInfo): rotations = group_or_rotations.rotations time_reversals = group_or_rotations.time_reversals else: rotations = group_or_rotations if time_reversals is None: raise ValueError("time_reversals are needed with explicit rotations") rotations = np.asarray(rotations, dtype=float).reshape(-1, 3, 3) if len(rotations) != len(time_reversals): raise ValueError("one time-reversal flag is needed per rotation") unique, flags = _unique_operations(rotations, [bool(f) for f in time_reversals]) return _idealized_rotations(unique), flags def _idealized_rotations(rotations: np.ndarray) -> np.ndarray: """The nearest orthogonal matrices; entries within 1e-4 of 0, +-1/2, +-sqrt(3)/2 or +-1 snapped to them when the snapped set stays orthogonal (cells in a standard orientation), so that the forms come out with exact coefficients.""" orthogonal = [] for rotation in rotations: u, _, vt = np.linalg.svd(rotation) orthogonal.append(u @ vt) orthogonal = np.array(orthogonal) ideal = np.array([0.0, 0.5, math.sqrt(3.0) / 2.0, 1.0]) magnitude = np.abs(orthogonal) nearest = ideal[np.argmin(np.abs(magnitude[..., None] - ideal), axis=-1)] snapped = np.sign(orthogonal) * nearest if (np.max(np.abs(snapped - orthogonal)) < 1e-4 and all(np.allclose(r @ r.T, np.eye(3), atol=1e-12) for r in snapped)): return snapped return orthogonal def _pam_frame(plane_normal, rotations, flags): """Coordinate frame of ``q``: rows ``u, v, n`` and the names of the coordinates. Three dimensions: the Cartesian axes; two dimensions: two in-plane axes (Cartesian axes when the normal is one) and the normal.""" if plane_normal is None: return np.eye(3), ("x", "y", "z"), [0, 1, 2] normal = np.asarray(plane_normal, dtype=float).reshape(3) if np.linalg.norm(normal) < 1e-12: raise ValueError("plane_normal must be a nonzero vector") normal = normal / np.linalg.norm(normal) for rotation, flag in zip(rotations, flags): image = (-rotation if flag else rotation) @ normal if abs(abs(float(image @ normal)) - 1.0) > 1e-6: raise ValueError( f"an operation does not map the plane normal {_direction_text(normal)} to " "plus or minus itself: the group is not a layer group of that plane") name = _axis_name(normal) if name is not None: u_index, v_index = {"x": (1, 2), "y": (0, 2), "z": (0, 1)}[name] frame = np.zeros((3, 3)) frame[0, u_index] = frame[1, v_index] = 1.0 frame[2] = normal return frame, ("xyz"[u_index], "xyz"[v_index], None), [u_index, v_index, None] seed = np.eye(3)[int(np.argmin(np.abs(normal)))] u = seed - (seed @ normal) * normal u = u / np.linalg.norm(u) v = np.cross(normal, u) return np.array([u, v, normal]), ("u", "v", None), None def _pam_exponents(degree: int, two_dimensional: bool) -> list[tuple[int, int, int]]: exponents = _monomials(degree) if two_dimensional: exponents = [e for e in exponents if e[2] == 0] return exponents def _substitution_polynomials(matrix: np.ndarray, max_degree: int) -> dict: """``{m: c}`` with the coefficient array ``c[a, b, c]`` of the monomial ``(M q)^m`` (``M q`` substituted for ``q``) for every exponent ``m`` up to ``max_degree``.""" size = max_degree + 1 polynomials = {(0, 0, 0): np.zeros((size, size, size))} polynomials[(0, 0, 0)][0, 0, 0] = 1.0 for degree in range(1, max_degree + 1): for exponent in _monomials(degree): axis = next(j for j in range(3) if exponent[j] > 0) lower = list(exponent) lower[axis] -= 1 base = polynomials[tuple(lower)] product = np.zeros_like(base) product[1:, :, :] += matrix[axis, 0] * base[:-1, :, :] product[:, 1:, :] += matrix[axis, 1] * base[:, :-1, :] product[:, :, 1:] += matrix[axis, 2] * base[:, :, :-1] polynomials[exponent] = product return polynomials def _bombieri_weights(exponents) -> np.ndarray: """``sqrt(n! / (a! b! c!))``: the monomials times these weights are orthonormal for the inner product that orthogonal substitutions keep.""" return np.array([math.sqrt(math.factorial(sum(e)) / math.prod(math.factorial(p) for p in e)) for e in exponents]) def _equivariant_fields(substitutions, actions, exponents) -> np.ndarray: """Basis ``(k, 3, N)`` (monomial coefficients) of the homogeneous vector fields ``F`` over ``exponents`` with ``F(A q) = B F(q)`` for every pair of a substitution table (of ``A``) and an action ``B``.""" count = len(exponents) weights = _bombieri_weights(exponents) blocks = [] for table, action in zip(substitutions, actions): substitution = np.array([[table[m][e] for e in exponents] for m in exponents]) # orthonormal coordinates: the substitution is an orthogonal matrix orthonormal = (weights[:, None] * substitution) / weights[None, :] blocks.append(np.kron(np.eye(3), orthonormal.T) - np.kron(action, np.eye(count))) matrix = np.vstack(blocks) _, singular, vt = np.linalg.svd(matrix) # the nonzero singular values of the stacked differences of orthogonal # matrices are of order one; noise of slightly distorted cells stays far below rank = int(np.sum(singular > 1e-6 * max(1.0, float(singular[0])))) return vt[rank:].reshape(-1, 3, count) def _component_forms(null: np.ndarray, index: int, exponents, frame_axes) -> tuple[str, ...]: """Text of the space of i-th components of the fields ``null``.""" from .invariants import _rref if len(null) == 0: return () block = null[:, index, :] _, singular, vt = np.linalg.svd(block, full_matrices=False) rank = int(np.sum(singular > 1e-6)) if rank == 0: return () rows = vt[:rank] * _bombieri_weights(exponents)[None, :] reduced, _ = _rref(rows) if sum(exponents[0]) == 0: return ("const",) if frame_axes is not None: # the in-plane coordinates in their Cartesian positions cartesian = [] for exponent in exponents: powers = [0, 0, 0] for position, axis in enumerate(frame_axes): if axis is not None: powers[axis] += exponent[position] cartesian.append(tuple(powers)) return tuple(_polynomial_text(row, cartesian).replace("k_", "q_") for row in reduced) return tuple(_polynomial_text(row, exponents).replace("k_x", "q_u").replace("k_y", "q_v") for row in reduced) def _pam_nodes(operations, index: int, frame: np.ndarray, two_dimensional: bool) -> tuple: """Cartesian directions of the enforced nodes of component ``index``: an operation whose action on ``q`` is a reflection (in the plane of ``q`` in two dimensions) and whose action on ``l`` reverses ``e_i``.""" found: list[np.ndarray] = [] target = np.eye(3)[index] for on_q, on_l in operations: if not np.allclose(on_l @ target, -target, atol=1e-6): continue if two_dimensional: block = (frame @ on_q @ frame.T)[:2, :2] if abs(np.linalg.det(block) + 1.0) > 1e-6 or abs(np.trace(block)) > 1e-6: continue values, vectors = np.linalg.eigh(block) in_plane = vectors[:, int(np.argmax(values))] vector = in_plane[0] * frame[0] + in_plane[1] * frame[1] else: if abs(np.linalg.det(on_q) + 1.0) > 1e-6 or abs(np.trace(on_q) - 1.0) > 1e-6: continue values, vectors = np.linalg.eigh(on_q) vector = vectors[:, int(np.argmin(values))] vector = vector / np.linalg.norm(vector) if not any(abs(abs(float(vector @ other)) - 1.0) < 1e-6 for other in found): found.append(vector) return tuple(sorted((_direction_text(v) for v in found))[::-1]) def _pam_zero_reason(operations, index: int, frame: np.ndarray, two_dimensional: bool, pt_symmetric: bool) -> str: """Why component ``index`` vanishes identically: an operation that acts as the identity on ``q`` and reverses ``e_i``.""" if pt_symmetric: return "P T" if not two_dimensional: return "" target = np.eye(3)[index] for on_q, on_l in operations: block = (frame @ on_q @ frame.T)[:2, :2] if np.allclose(block, np.eye(2), atol=1e-6) and np.allclose(on_l @ target, -target, atol=1e-6): # the mirror of the layer (no time reversal) keeps l along the # normal, a 2' along the normal reverses it (on_q is diag(1, 1, -1) # in the frame for both, so its determinant does not tell them apart) if np.allclose(on_l @ frame[2], frame[2], atol=1e-6): return "the mirror of the layer" return "2' along the layer normal" return "" def _pam_setup(group_or_rotations, time_reversals, plane_normal): rotations, flags = _pam_operations(group_or_rotations, time_reversals) frame, _, frame_axes = _pam_frame(plane_normal, rotations, flags) operations = [] for rotation, flag in zip(rotations, flags): sign = -1.0 if flag else 1.0 operations.append((sign * rotation, sign * float(np.linalg.det(rotation)) * rotation)) pt_symmetric = any(flag and np.allclose(rotation, -np.eye(3), atol=1e-6) for rotation, flag in zip(rotations, flags)) return operations, frame, frame_axes, pt_symmetric def _pam_null_spaces(operations, frame, two_dimensional: bool, max_degree: int): """Yield ``(degree, exponents, null)`` for degree 0 .. max_degree.""" substitutions = [_substitution_polynomials(frame @ on_q @ frame.T, max_degree) for on_q, _ in operations] actions = [on_l for _, on_l in operations] for degree in range(max_degree + 1): exponents = _pam_exponents(degree, two_dimensional) yield degree, exponents, _equivariant_fields(substitutions, actions, exponents)
[docs] def phonon_angular_momentum(group_or_rotations, time_reversals=None, *, plane_normal=None, max_degree: int = 9) -> PhononAngularMomentum: """The phonon angular momentum texture near Gamma that a magnetic point group allows, component by component. The angular momentum ``l(q)`` of a phonon branch is a real axial vector, odd under time reversal. An operation ``g = (R, t)`` (``t``: combined with time reversal, ``s = -1`` if ``t`` else ``+1``) acts on the wavevector by ``A = s R`` and on ``l`` by ``B = s det(R) R``, and symmetry demands ``l(A q) = B l(q)``. For every degree ``n`` the homogeneous polynomial vector fields of degree ``n`` that obey this for all operations are found as a null space (in coordinates in which every substitution ``q -> A q`` is an orthogonal matrix). For each Cartesian component ``l_i`` the result holds the lowest degree with a nonzero i-th component (s, p, d, f, g, h, i, j for 0..7), the polynomials of that degree, and the nodal planes through Gamma that single operations enforce: those whose ``A`` is the reflection in the plane and whose ``B`` reverses ``e_i`` (a mirror without time reversal whose plane contains ``e_i``; a ``2'`` along the normal when ``e_i`` is along it). The number of planes can be smaller than the degree (``4'``: ``l_z ~ q_z``, no plane), so both are given. ``P T`` makes every component vanish; degree 0 is the net magnetization. When the planes pinned by single operations are fewer than the degree, the other nodes are not fixed in position by symmetry. Phonon angular momentum after L. Zhang and Q. Niu, Phys. Rev. Lett. 112, 085503 (2014). Args: group_or_rotations: A :class:`MagneticGroupInfo`, or Cartesian rotation matrices ``(n, 3, 3)`` of the operations of the magnetic point group. time_reversals: The time-reversal flags (needed with rotations). plane_normal: For a two-dimensional system (a layer), the normal (Cartesian) of the plane ``q`` is restricted to: the polynomials are in the two in-plane coordinates (``q_x, q_y`` for the normal along z; ``q_u, q_v`` for a normal along no Cartesian axis, see :attr:`PhononAngularMomentum.in_plane`) and the nodes are lines. max_degree: The highest degree searched (default 9). Returns: A :class:`PhononAngularMomentum`. Raises: ValueError: Rotations given without flags, or an operation that does not map ``plane_normal`` to plus or minus itself. Example: >>> import numpy as np >>> from crystod import mag >>> c4 = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]], dtype=float) >>> rotations = [np.eye(3), c4, c4 @ c4, c4.T] # the group 4' >>> result = mag.phonon_angular_momentum(rotations, [False, True, False, True]) >>> result.component("z").text() 'l_z ~ q_z (p-wave)' """ operations, frame, frame_axes, pt_symmetric = _pam_setup( group_or_rotations, time_reversals, plane_normal) two_dimensional = plane_normal is not None found: dict[int, tuple[int, tuple]] = {} reasons = {i: _pam_zero_reason(operations, i, frame, two_dimensional, pt_symmetric) for i in range(3)} if not all(reasons.values()): for degree, exponents, null in _pam_null_spaces(operations, frame, two_dimensional, max_degree): for index in range(3): if index in found or reasons[index]: continue forms = _component_forms(null, index, exponents, frame_axes) if forms: found[index] = (degree, forms) if all(i in found or reasons[i] for i in range(3)): break components = [] for index, axis in enumerate("xyz"): degree, forms = found.get(index, (None, ())) components.append(AngularMomentumComponent( axis=axis, degree=degree, forms=forms, nodal=(_pam_nodes(operations, index, frame, two_dimensional) if degree is not None else ()), zero_reason=reasons[index], two_dimensional=two_dimensional, max_degree=max_degree, )) in_plane = () if two_dimensional: names = (("q_" + "xyz"[frame_axes[0]], "q_" + "xyz"[frame_axes[1]]) if frame_axes is not None else ("q_u", "q_v")) in_plane = ((names[0], frame[0].copy()), (names[1], frame[1].copy())) return PhononAngularMomentum( components=tuple(components), pt_symmetric=pt_symmetric, plane_normal=None if plane_normal is None else frame[2].copy(), in_plane=in_plane, max_degree=max_degree, )
[docs] def phonon_angular_momentum_degrees(group_or_rotations, time_reversals=None, *, component: str = "z", max_degree: int = 9, plane_normal=None) -> tuple[int, ...]: """The degrees ``n <= max_degree`` at which component ``l_i`` of the phonon angular momentum has a nonzero form allowed by symmetry (all of them, not only the lowest). The N-th order response of an angular-momentum current to a temperature gradient, ``J ~ (grad T)^N``, is allowed by symmetry exactly when the degree ``N + 1`` is in this list (the current weights ``l(q)`` with the N-th power of the group velocity, one more power of ``q`` per order). Once a degree ``n`` occurs, ``n + 2, n + 4, ...`` occur too (times ``|q|^2``). Args: group_or_rotations: As in :func:`phonon_angular_momentum`. time_reversals: As in :func:`phonon_angular_momentum`. component: ``"x"``, ``"y"`` or ``"z"``. max_degree: The highest degree tested. plane_normal: As in :func:`phonon_angular_momentum`. Returns: The degrees in increasing order (empty when the component vanishes). Example: >>> mag.phonon_angular_momentum_degrees(rotations, [False, True, False, True]) (1, 2, 3, 4, 5, 6, 7, 8, 9) """ if component not in ("x", "y", "z"): raise ValueError(f"component must be 'x', 'y' or 'z', not {component!r}") operations, frame, frame_axes, pt_symmetric = _pam_setup( group_or_rotations, time_reversals, plane_normal) index = "xyz".index(component) two_dimensional = plane_normal is not None if _pam_zero_reason(operations, index, frame, two_dimensional, pt_symmetric): return () degrees = [] for degree, exponents, null in _pam_null_spaces(operations, frame, two_dimensional, max_degree): if _component_forms(null, index, exponents, frame_axes): degrees.append(degree) return tuple(degrees)