"""Magnetic isotropy subgroups of several coupled irreps (crystod-mag --parent SG --irrep A B).
The coupled counterpart of :mod:`crystod.magnetic_isotropy`, as the coupled
table of ``crystod-group --parent SG --irrep A B`` is that of the
single-irrep table: an order that condenses several irreps at once lowers the
paramagnetic (grey) group G1' = G + theta G to the stabilizer of the vector
of the direct sum,
H(eta_1, eta_2, ...) = { g in G : D_j(g) eta_j = eta_j for every j }
+ { theta g : s_j D_j(g) eta_j = eta_j for every j },
where every irrep carries a time-reversal parity: ``s_j = -1`` for a
time-odd (magnetic) irrep, the default of every irrep in ``crystod-mag``
(ISOTROPY's ``mGM4+``), and ``s_j = +1`` for a time-even (structural) irrep
(ISOTROPY's ``GM4+``), so that a distortion and a magnetic order can be
combined. The group acting on the order parameter is the block-diagonal
matrix group of D(G) together with diag(s_j D_j(G)); its strata are the
coupled order-parameter directions.
The enumeration is that of the structural coupled table
(:func:`crystod.isotropy_subgroup._direction_records`): every stratum of the
direct sum, one per orbit under G1' (the isotropy subgroups of one orbit are
conjugate in G1'), keeping only the directions in which every irrep has a
nonzero amplitude; the directions with a zero part are those of the
single-irrep tables printed before the coupled one. Every irrep keeps its
own letters (``R4+(a,0,0) M3+(d;0;0)``), as in ``crystod-group``. The
subgroups are identified exactly as in the single-irrep magnetic table
(:meth:`crystod.magnetic_isotropy.MagneticIsotropyAnalyzer.magnetic_subgroup_of`);
the single-irrep table of a time-even irrep holds grey groups (type II: the
stabilizer contains theta), identified on a structure without moments.
Labels: when every irrep is time-odd they are printed without the ``m``, as
in the rest of ``crystod-mag``; when the parities are mixed, the time-odd
ones carry ISOTROPY's ``m`` (``mGM4+``) and the time-even ones none
(``R4+``), so that the two kinds can be told apart.
Example:
>>> from crystod.magnetic_isotropy_coupled import coupled_magnetic_isotropy_subgroups
>>> result = coupled_magnetic_isotropy_subgroups("Pm-3m", ["R4+", "M3+"])
>>> len(result.coupled) > 0
True
"""
from __future__ import annotations
import contextlib
import io
from dataclasses import dataclass, field
import numpy as np
from .isotropy_subgroup import (
ENANTIOMORPHIC_PAIRS,
CoupledRepresentation,
InducedRepresentation,
_orth_basis,
_PARAMETER_NAMES,
_rep_cache,
)
from .magnetic_isotropy import (
_GENERIC_SITES,
MagneticIsotropyAnalyzer,
MagneticRepresentation,
_strip_magnetic_prefix,
)
from .spacegroup_product import DEN, SpaceGroupIrrepAlgebra
#: Accepted spellings of the time-reversal parity of an irrep.
_ODD = {"odd", "-", "-1", "m", "magnetic", "time-odd"}
_EVEN = {"even", "+", "+1", "1", "s", "structural", "time-even"}
[docs]
@dataclass(frozen=True)
class CoupledMagneticIsotropySubgroup:
"""One row of a coupled (or single-irrep) magnetic table.
Attributes:
irreps: The labels of the irreps, as printed (``("R4+", "M3+")``;
one label for a single-irrep row).
direction: The full direction label (``"R4+(0,0,a) M3+(d;0;0)"``;
a single-irrep row ``"GM4+(0,0,a)"``).
components: The direction of every irrep (``("(0,0,a)",
"(d;0;0)")``), in the order of ``irreps``.
bns_number, bns_symbol, msg_type, uni_symbol, og_number,
magnetic_point_group, unitary_number, unitary_symbol, size, index,
n_free, n_operations: As in
:class:`crystod.magnetic_isotropy.MagneticIsotropySubgroup`
(``msg_type`` 2, a grey group, only in the table of a time-even
irrep alone).
"""
irreps: tuple
direction: str
components: tuple
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:
"""The first column of the table (the direction label)."""
return self.direction
@property
def subgroup(self) -> str:
"""``"127.394 P4/m'bm"``, 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."""
return {1: "I", 2: "II", 3: "III", 4: "IV"}[self.msg_type]
[docs]
@dataclass
class CoupledMagneticIsotropySubgroups:
"""The result of :func:`coupled_magnetic_isotropy_subgroups`.
Attributes:
parent: Short symbol of the parent space group.
parent_number: Its number.
irreps: The irrep labels as printed (with ``m`` for the time-odd
ones when the parities are mixed).
parities: ``-1`` (time-odd) or ``+1`` (time-even) per irrep.
dimensions: The order-parameter dimension of every irrep.
singles: ``{label: [rows]}``, the table of every irrep alone (letters
shifted so that every irrep keeps its own range).
coupled: The rows of the coupled table (every irrep condensed); for
one irrep, its single table.
parts: The representations of the irreps (for the report).
"""
parent: str
parent_number: int
irreps: list
parities: list
dimensions: list
singles: dict
coupled: list
parts: list = field(default_factory=list, repr=False)
# ------------------------------------------------------------ representations
def _parity_value(value) -> int:
"""``-1`` (time-odd) or ``+1`` (time-even) from a flag or a word."""
if value is None:
return -1
if isinstance(value, bool):
return -1 if value else 1
if isinstance(value, (int, np.integer)):
if int(value) in (-1, 1):
return int(value)
raise ValueError(f"time-reversal parity must be -1 or +1, not {value}")
text = str(value).strip().lower()
if text in _ODD:
return -1
if text in _EVEN:
return 1
raise ValueError(f'unknown time-reversal parity "{value}" (use "odd" or "even")')
class _LabelledPart:
"""An ``InducedRepresentation`` printed under another label (``mGM4+``)."""
def __init__(self, base, label: str):
self.base = base
self.label = label
def __getattr__(self, name):
if name.startswith("__"):
raise AttributeError(name)
return getattr(self.base, name)
class ParityRepresentation(MagneticRepresentation):
"""One irrep of G as a representation of G1' with a given parity.
``theta (i, t)`` acts by ``parity * D``: the
:class:`crystod.magnetic_isotropy.MagneticRepresentation` for a time-odd
irrep (parity -1, identical elements), the structural irrep extended
trivially by theta for a time-even one (parity +1).
"""
def __init__(self, base, parity: int = -1):
self.base = base
self.parity = int(parity)
n_ops = base.algebra.n_ops
self.elements = list(base.image_elements()) + [
(i + n_ops, t, self.parity * matrix) for i, t, matrix in base.image_elements()
]
class MagneticCoupledRepresentation(CoupledRepresentation):
"""Direct sum of irreps of G as a representation of the grey group G1'.
The :class:`crystod.isotropy_subgroup.CoupledRepresentation` of the parts
(block-diagonal matrices, irrep by irrep and arm by arm), extended by the
elements ``theta (i, t)``, encoded as ``i + n_ops``, with the matrices
``diag(s_j D_j(i, t))``: ``s_j = -1`` for a time-odd irrep, ``+1`` for
a time-even one. Being a ``CoupledRepresentation``, it is labelled and
sampled by :class:`crystod.isotropy_subgroup.IsotropyAnalyzer` irrep by
irrep (own letters, generic in every part).
Args:
algebra: The ``SpaceGroupIrrepAlgebra`` of the parent.
parts: ``InducedRepresentation`` objects (possibly relabelled).
parities: ``-1`` or ``+1`` per part.
"""
def __init__(self, algebra: SpaceGroupIrrepAlgebra, parts: list, parities: list):
self.parities = [int(p) for p in parities]
self._assemble(algebra, list(parts))
n_ops = algebra.n_ops
signs = np.concatenate([
np.full(dim, float(parity)) for dim, parity in zip(self.dims, self.parities)
])
self.elements = list(self.elements) + [
(i + n_ops, t, signs[:, None] * matrix) for i, t, matrix in self.elements
]
# ------------------------------------------------------------------- analyzer
class CoupledMagneticIsotropyAnalyzer(MagneticIsotropyAnalyzer):
"""The :class:`MagneticIsotropyAnalyzer` over a representation of G1'
with given parities (:class:`MagneticCoupledRepresentation` or
:class:`ParityRepresentation`), which also identifies the grey groups of
a time-even irrep alone."""
@classmethod
def over(cls, algebra, representation):
"""Analyzer over an already-built representation of G1'."""
analyzer = cls.__new__(cls)
analyzer.algebra = algebra
analyzer.representation = representation
analyzer.elements = representation.image_elements()
return analyzer
def magnetic_subgroup_of(self, members):
"""As :meth:`MagneticIsotropyAnalyzer.magnetic_subgroup_of`; a
stabilizer that holds theta itself (a time-even order parameter) is
the grey group of its unitary part, identified on the generic
structure of the unitary operations without moments."""
algebra = self.algebra
n_ops = algebra.n_ops
identity = algebra._rotation_index[algebra._key(np.eye(3))]
grey = any(i == identity + n_ops and not np.any(np.asarray(t) % self.representation.grid_n)
for i, t in members)
if not grey:
return super().magnetic_subgroup_of(members)
return self._grey_subgroup_of(members)
def _grey_subgroup_of(self, members):
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
size = abs(int(round(np.linalg.det(B))))
chosen: dict[int, np.ndarray] = {}
for i, t in members:
if i < n_ops:
chosen.setdefault(i, np.asarray(t, dtype=np.int64))
B_inv_T = np.linalg.inv(B.T)
lattice = B @ self._invariant_lattice()
positions, numbers = [], []
operations = []
for i, t in chosen.items():
W = B_inv_T @ algebra.rotations[i] @ B.T
W_int = np.rint(W).astype(np.int64)
if not np.allclose(W, W_int, atol=1e-8):
raise SystemExit("ERROR: subgroup operation is incompatible with its lattice.")
v = B_inv_T @ (np.array(algebra.translations[i], dtype=float) / DEN + t)
operations.append((W_int, np.mod(v, 1.0)))
for species, (x0, _) in enumerate(_GENERIC_SITES):
for W, v in operations:
positions.append(np.mod(W @ x0 + v, 1.0))
numbers.append(species + 1)
group = magnetic_space_group(lattice, positions, numbers, np.zeros((len(positions), 3)))
if not group.identified:
raise SystemExit("ERROR: spglib could not identify the magnetic subgroup.")
n_operations = 2 * len(operations)
if group.n_operations != n_operations:
raise SystemExit(
f"ERROR: spglib finds {group.n_operations} magnetic operations where the "
f"stabilizer has {n_operations}; please report this case.")
index = 2 * n_ops * size // n_operations
return group, size, index, n_operations
# ----------------------------------------------------------------------- rows
def _row(analyzer, projector, generic, label, irreps, components):
cache = _rep_cache(analyzer.representation, analyzer.elements)
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]
return CoupledMagneticIsotropySubgroup(
irreps=tuple(irreps),
direction=label,
components=tuple(components),
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,
)
def _sort(rows):
rows.sort(key=lambda r: (r.n_free, r.index, *(int(x) for x in r.bns_number.split("."))))
return rows
def single_rows(analyzer, label: str, letter_offset: int = 0) -> list:
"""The rows of one irrep alone (a :class:`ParityRepresentation`), with
its letters shifted by ``letter_offset``; for a time-odd irrep and no
offset, the rows of ``crystod-mag --parent SG --irrep IR``."""
rows = []
for projector, _ in analyzer.enumerate_directions():
direction, generic = analyzer.direction_label(projector, letter_offset)
rows.append(_row(analyzer, projector, generic, label + direction, [label], [direction]))
return _sort(rows)
def _split_label(label: str, labels: list) -> list:
"""``"R4+(0,0,a) M3+(d;0;0)"`` -> ``["(0,0,a)", "(d;0;0)"]``."""
pieces, rest = [], label
for j, name in enumerate(labels):
rest = rest.removeprefix(name)
if j + 1 < len(labels):
cut = rest.index(") " + labels[j + 1] + "(") + 1
pieces.append(rest[:cut])
rest = rest[cut + 1:]
else:
pieces.append(rest)
return pieces
def coupled_rows(analyzer, *, condensed_only: bool = True) -> list:
"""The rows of the coupled table of a
:class:`MagneticCoupledRepresentation`: one per stratum of the direct
sum (one per G1' orbit), keeping only the directions where every irrep
condenses (``condensed_only=False`` keeps all, the check that the
directions with one nonzero part are the single-irrep rows)."""
representation = analyzer.representation
labels = [part.label for part in representation.parts]
bounds = np.cumsum([0] + list(representation.dims))
rows = []
for projector, _ in analyzer.enumerate_directions():
label, generic = analyzer.direction_label(projector)
condensed = [
np.linalg.norm(generic[bounds[j]: bounds[j + 1]]) > 1e-8
for j in range(len(labels))
]
if condensed_only and not all(condensed):
continue
rows.append(_row(analyzer, projector, generic, label, labels,
_split_label(label, labels)))
return _sort(rows)
# ------------------------------------------------------------------------ API
def _build_parts(algebra, irreps, parities):
labels = [_strip_magnetic_prefix(algebra, str(label)) for label in irreps]
if parities is None:
parities = [-1] * len(labels)
parities = [_parity_value(p) for p in parities]
if len(parities) != len(labels):
raise SystemExit("ERROR: one time-reversal parity per irrep is needed.")
bases = [InducedRepresentation(algebra, label) for label in labels]
mixed = len(set(parities)) > 1
printed = [
("m" + base.label if mixed and parity < 0 else base.label)
for base, parity in zip(bases, parities)
]
if len(set(printed)) != len(printed):
raise SystemExit("ERROR: an irrep is given twice with the same parity.")
parts = [
_LabelledPart(base, name) if name != base.label else base
for base, name in zip(bases, printed)
]
return parts, parities, printed
def coupled_magnetic_analyzer(parent: str, irreps: list, parities=None):
"""The analyzer of the coupled order parameter, its parts and labels.
Args:
parent: Symbol or number of the parent space group.
irreps: ISO-IR labels (``mGM4+`` accepted for a time-odd one).
parities: ``-1``/``"odd"`` (time-odd, magnetic) or ``+1``/``"even"``
(time-even, structural) per irrep; None = all time-odd.
Returns:
``(analyzer, parts, parities, labels)``.
Raises:
SystemExit: Unknown space group or irrep, wrong parity list.
"""
algebra = SpaceGroupIrrepAlgebra(str(parent))
parts, parities, labels = _build_parts(algebra, irreps, parities)
representation = MagneticCoupledRepresentation(algebra, parts, parities)
return CoupledMagneticIsotropyAnalyzer.over(algebra, representation), parts, parities, labels
def _coupled_result(parent, irreps, parities) -> CoupledMagneticIsotropySubgroups:
analyzer, parts, parities, labels = coupled_magnetic_analyzer(parent, irreps, parities)
algebra = analyzer.algebra
singles = {}
offset = 0
for part, parity, label in zip(parts, parities, labels):
base = part.base if isinstance(part, _LabelledPart) else part
sub = CoupledMagneticIsotropyAnalyzer.over(algebra, ParityRepresentation(base, parity))
letter_offset = offset if len(parts) > 1 else 0
singles[label] = single_rows(sub, label, letter_offset)
offset += part.dimension
if len(parts) == 1:
coupled = list(singles[labels[0]])
else:
coupled = coupled_rows(analyzer)
return CoupledMagneticIsotropySubgroups(
parent=str(algebra.sg_type.international_short),
parent_number=int(algebra.sg_type.number),
irreps=labels,
parities=parities,
dimensions=[part.dimension for part in parts],
singles=singles,
coupled=coupled,
parts=parts,
)
[docs]
def coupled_magnetic_isotropy_subgroups(parent: str, irreps: list,
parities=None) -> CoupledMagneticIsotropySubgroups:
"""Magnetic isotropy subgroups of several coupled irreps
(``crystod-mag --parent SG --irrep A B ...``).
Args:
parent: Symbol or number of the parent space group (``"Pm-3m"``);
the paramagnetic parent is its grey group.
irreps: ISO-IR labels (``["R4+", "M3+"]``; ``mR4+`` and pair labels
``GM3+GM4+`` accepted).
parities: Time-reversal parity of every irrep: ``-1`` / ``"odd"``
(magnetic, the default) or ``+1`` / ``"even"`` (structural).
Returns:
A :class:`CoupledMagneticIsotropySubgroups` with the table of every
irrep alone and the coupled table (every irrep condensed).
Raises:
ValueError: Unknown space group or irrep, or a wrong parity.
"""
try:
with contextlib.redirect_stdout(io.StringIO()):
return _coupled_result(parent, list(irreps), parities)
except SystemExit as exc:
raise ValueError(str(exc).removeprefix("ERROR: ")) from None
[docs]
@dataclass
class CoupledMagneticOrderParameter:
"""The magnetic isotropy subgroup of one given (coupled) direction.
Attributes:
direction: The direction as given, in the table's layout.
row: The :class:`CoupledMagneticIsotropySubgroup` of the exact
stabilizer of the direction (``n_free`` = number of distinct
parameters given).
basis: The basis of the translations without theta, rows, in parent
primitive units.
"""
direction: str
row: CoupledMagneticIsotropySubgroup
basis: np.ndarray
def _arm_join(piece, arm_chunks) -> str:
arms, start = [], 0
for size in arm_chunks:
arms.append(",".join(piece[start: start + size]))
start += size
return ";".join(arms)
def _order_parameter(parent, irreps, tokens, parities) -> CoupledMagneticOrderParameter:
analyzer, parts, parities, labels = coupled_magnetic_analyzer(parent, irreps, parities)
eta = analyzer.resolve_direction(list(tokens))
cache = _rep_cache(analyzer.representation, analyzer.elements)
members = [
(analyzer.elements[g][0], analyzer.elements[g][1])
for g in np.nonzero(cache.vector_stabilizer_mask(eta))[0]
]
group, size, index, n_operations = analyzer.magnetic_subgroup_of(members)
unitary, _, _, B, *_ = analyzer.subgroup_of(members)
pieces, start = [], 0
for part in parts:
pieces.append("(" + _arm_join(list(tokens[start: start + part.dimension]),
part.arm_chunks) + ")")
start += part.dimension
direction = " ".join(f"{label}{piece}" for label, piece in zip(labels, pieces))
letters = {ch for token in tokens for ch in token if ch.isalpha()}
row = CoupledMagneticIsotropySubgroup(
irreps=tuple(labels), direction=direction, components=tuple(pieces),
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=len(letters), n_operations=n_operations,
)
return CoupledMagneticOrderParameter(direction=direction, row=row, basis=np.asarray(B))
[docs]
def coupled_magnetic_order_parameter(parent: str, irreps: list, tokens: list,
parities=None) -> CoupledMagneticOrderParameter:
"""The magnetic isotropy subgroup of one coupled direction
(``crystod-mag --parent SG --irrep A B --order-parameter ...``).
Args:
parent: Symbol or number of the parent space group.
irreps: ISO-IR labels.
tokens: One component per order-parameter slot, irrep after irrep
(the spellings of ``crystod-group --order-parameter``: ``a``,
``-a``, ``2a``, ``a+b``, ``0``); zero parts are allowed.
parities: As in :func:`coupled_magnetic_isotropy_subgroups`.
Returns:
A :class:`CoupledMagneticOrderParameter`.
Raises:
ValueError: Unknown group or irrep, wrong number of components, a
zero order parameter.
"""
try:
with contextlib.redirect_stdout(io.StringIO()):
return _order_parameter(parent, list(irreps), list(tokens), parities)
except SystemExit as exc:
raise ValueError(str(exc).removeprefix("ERROR: ")) from None
# --------------------------------------------------------------------- report
def _print_table(rows) -> 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 _part_line(part, parity: int, mixed: bool) -> str:
if part.doubled:
note = (f" (star of {part.n_arms} arm(s) x small dim {part.dim_small} x 2;"
f" {part.fs_type}-type irrep -> physically irreducible real form)")
elif part.n_arms > 1:
note = f" (star of {part.n_arms} arm(s) x small dim {part.dim_small})"
else:
note = ""
kind = ""
if mixed:
kind = ", time-odd (magnetic)" if parity < 0 else ", time-even (structural)"
return f"{part.label}: order parameter dimension {part.dimension}{kind}{note}"
def _print_notes(result: CoupledMagneticIsotropySubgroups, rows) -> 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 = result.parent
mixed = len(set(result.parities)) > 1
print()
if len(result.irreps) > 1:
ranges, offset = [], 0
for label, dim in zip(result.irreps, result.dimensions):
ranges.append(f"{label}: {', '.join(_PARAMETER_NAMES[offset: offset + dim])}")
offset += dim
print("Every irrep of the coupled table condenses with a nonzero")
print("amplitude; every irrep keeps its own independent free")
print(f"parameters ({'; '.join(ranges)}).")
print()
if mixed:
print(f"Irreps of the paramagnetic group {symbol}1': mIR (ISOTROPY's spelling) is")
print("time-odd (magnetic order), IR without m time-even (a distortion);")
else:
ours = ", ".join(result.irreps)
theirs = ", ".join("m" + label for label in result.irreps)
print(f"Magnetic (time-odd) irreps of the paramagnetic group {symbol}1': {ours}")
print(f"= ISOTROPY's {theirs};")
print("subgroup = BNS number and symbol; size = cell of the translations without")
print("time reversal, in parent primitive cells;")
print(f"index = [{symbol}1' : H], the number of domains.")
print()
print("Conventions: the magnetic isotropy subgroups of the ISOTROPY Software Suite")
print("(H. T. Stokes, D. M. Hatch and B. J. Campbell, https://iso.byu.edu); BNS numbers")
print("and symbols of ISO-MAG (H. T. Stokes and B. J. Campbell, 2010).")
def report(parent: str, irreps: list, parities=None) -> CoupledMagneticIsotropySubgroups:
"""The ``crystod-mag --parent SG --irrep A B ...`` report (stdout)."""
with contextlib.redirect_stdout(io.StringIO()):
result = _coupled_result(parent, list(irreps), parities)
mixed = len(set(result.parities)) > 1
print()
print("* Supergroup *")
print(f"{result.parent} (No. {result.parent_number})")
print()
coupled = len(result.irreps) > 1
print("* Coupled irreps *" if coupled else "* Irrep *")
for part, parity in zip(result.parts, result.parities):
print(_part_line(part, parity, mixed))
if coupled:
print(f"coupled order parameter dimension {sum(result.dimensions)} "
f"({' + '.join(str(d) for d in result.dimensions)})")
print()
every = []
if coupled:
for label, rows in result.singles.items():
print(f"* Order parameter directions and isotropy subgroups ({label} alone) *")
_print_table(rows)
print()
every += rows
print("* Order parameter directions and isotropy subgroups (coupled) *")
else:
print("* Order parameter directions and isotropy subgroups *")
_print_table(result.coupled)
every += result.coupled
_print_notes(result, every)
return result
def report_order_parameter(parent: str, irreps: list, tokens: list,
parities=None) -> CoupledMagneticOrderParameter:
"""The ``--order-parameter`` report of one (coupled) direction."""
with contextlib.redirect_stdout(io.StringIO()):
record = _order_parameter(parent, list(irreps), list(tokens), parities)
algebra = SpaceGroupIrrepAlgebra(str(parent))
row = record.row
print()
print("* Supergroup *")
print(f"{algebra.sg_type.international_short} (No. {algebra.sg_type.number})")
print()
print("* Magnetic isotropy subgroup *")
print(f"{row.direction} -> {row.bns_number} {row.bns_symbol} (BNS), type {row.type_name}")
print(f"UNI symbol: {row.uni_symbol}; magnetic point group {row.magnetic_point_group}")
print(f"unitary subgroup: {row.unitary_symbol} (No. {row.unitary_number})")
print(f"cell size {row.size}, index {row.index}")
basis_rows = ", ".join("(" + ",".join(str(int(x)) for x in b) + ")" for b in record.basis)
print(f"sublattice basis (parent primitive units): {basis_rows}")
return record