"""Magnetic arrangements of given irreps on a crystal (crystod-mag -c POSCAR --element EL --irrep IR).
``crystod-mag --parent SG --irrep IR [IR2 ...]`` lists the magnetic isotropy
subgroups of a paramagnetic parent G1' = G + theta G, one row per
order-parameter direction eta, from the real, physically irreducible
full-star matrices D(g) of every irrep (:class:`crystod.isotropy_subgroup.InducedRepresentation`).
This module places every row on the sites of a real crystal: it builds, for
every irrep nu, spin modes on the magnetic sites of a supercell S that
transform with exactly these matrices, and sums them with the components of
eta as coefficients.
Spin modes. The spins of the sites in S span W_S (dimension 3 N_S); an
operation g = {R|t} of G acts as (O(g) S)(g r) = det(R) R S(r), time reversal
theta as -1. The modes of irrep nu are the columns of an intertwiner Psi
(3 N_S x d_nu), O(g) Psi = Psi D(g) for every g, obtained from the projection
X_phi = (1 / |G/T_S|) sum_{g in G/T_S} O(g) phi e_1^T D(g)^T,
(X_phi)_{:, j} = (1 / |G/T_S|) sum_g D_j1(g) O(g) phi,
which maps any field phi onto the intertwiner space Hom_G(D, O) (the
orthogonal projector in the Frobenius metric, O and D being orthogonal); for
a real-type irrep this is (1/d) P_j1 phi with the projection operators
P_ij = (d / |G/T_S|) sum_g D_ij(g) O(g). The space has dimension m e, m the
multiplicity of nu in O (character formula, and the decomposition of the
survey of crystod-mag at the k point as an independent check) and e = 1, 2,
4 the dimension of the commutant of D (real, complex, quaternionic type).
One intertwiner per copy is kept (any other one of the copy is Psi E, E in
the commutant, with the same stabilizers). The copies are split by element,
then by Wyckoff orbit, then, at q = 0, into the ferromagnetic combination
(the cluster dipole: the intertwiners orthogonal to those of zero net
moment) and the antiferromagnetic ones, named by the multipole ranks as the
``--qpoint`` report names them (dipole, octupole, ...).
Arrangement of a row. For a table row with order parameter eta (a generic
representative of the stratum, the vector the table identifies its group
from) the arrangement is
S = sum_nu c_nu (Psi_nu eta_nu) / max |Psi_nu eta_nu|
with the coefficients c_nu of ``--coefficients`` (default 1). eta -> S is
linear, injective and equivariant (theta -> -1 on every part), so the
stabilizer of S in G1' is the stabilizer of eta: the magnetic isotropy
subgroup of the row. The label, BNS group, size and index come from the
table by construction; the group of every arrangement is nevertheless
identified again from the structure (supercell, all atoms, moments) with
spglib (:func:`crystod.magnetic_group.magnetic_space_group`), and the numbers
of operations fixing S and fixing eta are compared over G1'/T_S.
Frames. The matrices D(g) are defined in the ISO-IR setting of
:class:`crystod.spacegroup_product.SpaceGroupIrrepAlgebra`; the POSCAR's
primitive cell is mapped onto it through the ISO-IR frame that names the
irreps of every ``crystod-mag`` report (``vibrations._get_isoir_labeler()``,
:func:`crystod.isoir.get_cached_labeler`: x_conv = P x + origin), so that a
label such as R4- means the irrep the survey calls R4-. The map is checked
operation by operation, and the multiplicity of every irrep is checked
against the survey's decomposition.
Example:
>>> from phonopy.interface.vasp import read_vasp
>>> from crystod import mag
>>> cell = read_vasp("example/05-02_spin_basis/Mn3GaN_Pm-3m/POSCAR_Mn3GaN_Pm-3m")
>>> result = mag.magnetic_irrep_arrangements(cell, ["Mn"], ["R4-"])
>>> [(a.number, a.row.label, a.row.bns_number, a.check) for a in result.arrangements][:2]
[(1, 'R4-(0,0,a)', '139.540', 'same'), (2, 'R4-(a,a,a)', '166.102', 'same')]
"""
from __future__ import annotations
import contextlib
import io
import itertools
import re
from dataclasses import dataclass, field as dataclass_field
import numpy as np
#: Largest number of primitive cells of the common magnetic cell of a run.
MAX_CELLS = 64
#: Largest multiple of the primitive cell along one axis.
MAX_MULTIPLE = 12
#: Tolerance of the intertwining relation O(g) Psi = Psi D(g).
INTERTWINING_TOLERANCE = 1e-8
#: Decimals of the written moments (MAGMOM lines, spin listings, VESTA files);
#: the check of every arrangement is made on the moments rounded to them.
MOMENT_DECIMALS = 4
#: Tolerance on the written moments (largest moment 1) when their group is
#: identified: rounding to MOMENT_DECIMALS moves a component by at most 5e-5,
#: and the image of a rounded moment under a rotation by at most 1.4e-4.
MOMENT_TOLERANCE = 3e-4
#: Smallest weight of an irrep's part relative to the largest one that the
#: written moments still resolve.
MIN_RELATIVE_WEIGHT = 1e-3
#: Choices of copies exported per row by default (``--copies`` selects one).
MAX_COPY_CHOICES = 6
# ----------------------------------------------------------------- data classes
[docs]
@dataclass(eq=False)
class IrrepCopy:
"""One copy of an irrep in the spin representation of the chosen sites.
Attributes:
irrep: The irrep label as the tables print it (``"GM4+"``).
number: The copy number within the irrep, from 1.
element: The element whose sites carry the copy.
orbit: The element, with the Wyckoff position when the element has
more than one orbit (``"La(4e)"``).
kind: ``"FM"`` (the cluster dipole at q = 0), ``"AFM"`` (net moment
zero at q = 0) or ``"AFM (q != 0)"``.
rank_name: The multipole name at q = 0 (``"dipole"``,
``"octupole"``), as the ``--qpoint`` report names the bases;
None at q != 0.
intertwiner: The spin modes, shape ``(n_cells, n_sites, 3, d)``:
column j is the field of the j-th order-parameter component,
``O(g) Psi = Psi D(g)``, ``Psi^T Psi`` proportional to 1.
"""
irrep: str
number: int
element: str
orbit: str
kind: str
rank_name: str | None
intertwiner: np.ndarray = dataclass_field(repr=False)
@property
def text(self) -> str:
"""``"Mn [FM, dipole]"``: the description printed for the copy."""
details = self.kind if self.rank_name is None else f"{self.kind}, {self.rank_name}"
return f"{self.orbit} [{details}]"
[docs]
@dataclass(eq=False)
class MagneticArrangement:
"""The magnetic arrangement of one table row (one choice of copies).
Attributes:
number: The row number of the table, from 1.
row: The table row (:class:`crystod.magnetic_isotropy_coupled.CoupledMagneticIsotropySubgroup`
or :class:`crystod.magnetic_isotropy.MagneticIsotropySubgroup`).
copies: One :class:`IrrepCopy` per irrep.
tag: ``""`` when every irrep has one copy, else the copy numbers
(``"c1"``, ``"c2-1"``).
order_parameter: The order parameter used (the irreps' parts
concatenated), the table's generic representative.
letters: ``{letter: value}`` of the free parameters in that vector
(least squares on the printed direction label).
coefficients: The weight of every irrep's part (``--coefficients``).
field: The spins on the magnetic sites of the diagonal magnetic
cell (``supercell_sizes``), ``(n_cells, n_sites, 3)``, largest
moment 1, rounded as written.
magmoms: The moments of every atom of the written cell (POSCAR
order of the written supercell; with ``conventional`` the
conventional cell, the field re-tiled).
net_moment: The sum of the moments over the written cell.
group: The magnetic space group found by spglib on the structure
(:class:`crystod.magnetic_group.MagneticGroupInfo`), or None.
responses: The responses allowed by its magnetic point group.
collinear: Its collinear class.
check: ``"same"`` (spglib finds the row's BNS group),
``"enantiomorph"`` (the partner type), ``"different"`` or
``"not identified"``.
note: A NOTE for the row, or None.
n_fixing_field, n_fixing_order_parameter: Elements of G1'/T_S that
fix the field and the order parameter (equal by construction).
moment_text: The line on the sizes of the moments.
vesta_name: The VESTA file name.
fixing_translations: The translations of the written cell that
fix the written moments (fractional, written cell).
"""
number: int
row: object
copies: tuple
tag: str
order_parameter: np.ndarray = dataclass_field(repr=False)
letters: dict = dataclass_field(default_factory=dict)
coefficients: tuple = ()
field: np.ndarray = dataclass_field(default=None, repr=False)
magmoms: np.ndarray = dataclass_field(default=None, repr=False)
net_moment: np.ndarray = dataclass_field(default=None, repr=False)
group: object = None
responses: object = None
collinear: object = None
check: str = ""
note: str | None = None
n_fixing_field: int = 0
n_fixing_order_parameter: int = 0
moment_text: str = ""
vesta_name: str = ""
fixing_translations: list = dataclass_field(default_factory=list, repr=False)
weight_reason: str | None = None
reproduce: np.ndarray = dataclass_field(default=None, repr=False)
@property
def check_text(self) -> str:
"""The check column: the BNS number found on the structure and the
verdict (``"139.540 same"``)."""
if self.group is None or not getattr(self.group, "identified", False):
return "not identified"
return f"{self.group.bns_number} {self.check}"
[docs]
@dataclass(eq=False)
class MagneticIrrepAnalysis:
"""The magnetic arrangements of given irreps on a crystal
(``crystod-mag -c POSCAR --element EL --irrep IR [IR2 ...]``).
Attributes:
formula: Reduced formula of the primitive cell.
elements: The magnetic elements, in the order given.
space_group: International symbol; ``space_group_number`` its number.
irreps: The irrep labels as the tables print them.
dimensions: The order-parameter dimension of every irrep.
kpoints: ``{irrep: (k name, q)}``, q one arm in the primitive
reciprocal basis of the POSCAR.
decompositions: ``{k name: [(element or "total", text), ...]}``, the
survey's decomposition at the k points of the irreps.
multiplicities: ``{irrep: {element: m}}``.
copies: ``{irrep: [IrrepCopy, ...]}``.
singles: ``{irrep: [rows]}``, the table of every irrep alone (only
with several irreps; not exported).
rows: The rows exported (the coupled table with several irreps).
arrangements: One :class:`MagneticArrangement` per row and choice
of copies, in table order.
coefficients: The weight of every irrep.
cell_matrix, cell_translations: The written cell (rows in primitive
units) and its primitive translations, common to every row: the
diagonal magnetic cell ``diag(supercell_sizes)``, or with
``conventional`` the conventional cell times
``conventional_multiples``.
supercell_sizes: The diagonal magnetic cell in which the spin modes,
the weights and the counts of G1'/T_S are computed (primitive
cells along each axis); ``internal_cell_translations`` its
translations, in the order of the first axis of
:attr:`MagneticArrangement.field`.
supercell_lattice, supercell_symbols, supercell_positions: The
atoms of the written cell, atom-major (phonopy's SPOSCAR order).
supercell_site_of_atom, supercell_cell_of_atom: Magnetic-site index
(or None) and index in ``cell_translations`` of every atom.
conventional_centring: The centring letter with ``conventional``
(``"I"``), else None.
conventional_multiples: Conventional cells along each axis of the
written cell with ``conventional``, else None.
conventional_note: With ``conventional``, the NOTE of
:func:`crystod.spin_basis.conventional_cell_note` when the
written cell is not the conventional cell (an input primitive
cell off the standard primitive setting); else None.
site_indices: The magnetic sites in the primitive cell (element by
element).
site_elements: The element of every magnetic site.
residuals: The largest ``|O(g) Psi - Psi D(g)|`` over all copies
and elements (``"intertwining"``) and the largest deviation of
``Psi^T Psi / c`` from the unit matrix (``"orthonormality"``).
order_parameter_input: The tokens of ``--order-parameter``, or None.
stratum: With ``--order-parameter``, the number of the table row
whose stratum (G1'-orbit of directions) holds the given vector.
"""
formula: str
elements: list
space_group: str
space_group_number: int
irreps: list
dimensions: list
kpoints: dict
decompositions: dict
multiplicities: dict
copies: dict
singles: dict
rows: list
arrangements: list
coefficients: tuple
cell_matrix: np.ndarray
supercell_sizes: np.ndarray
cell_translations: list
supercell_lattice: np.ndarray
supercell_symbols: list
supercell_positions: np.ndarray
supercell_site_of_atom: list
supercell_cell_of_atom: list
site_indices: list
site_elements: list
residuals: dict = dataclass_field(default_factory=dict)
order_parameter_input: list | None = None
stratum: int | None = None
copy_note: str | None = None
unlabelled_kpoints: list = dataclass_field(default_factory=list)
parts: list = dataclass_field(default_factory=list, repr=False)
conventional_centring: str | None = None
conventional_multiples: np.ndarray | None = None
internal_cell_translations: list = dataclass_field(default_factory=list, repr=False)
conventional_note: str | None = None
@property
def n_cells(self) -> int:
"""Number of primitive cells of the written cell."""
return len(self.cell_translations)
# ------------------------------------------------------------------ the frame
class _Frame:
"""The map from the POSCAR's primitive cell onto the primitive setting of
the ISO-IR algebra: ``x_alg = F x + f`` (``F`` unimodular), and every
operation of the POSCAR as an element ``(i, t)`` of the algebra."""
def __init__(self, vibrations, algebra):
from .spacegroup_product import DEN
labeler = vibrations._get_isoir_labeler()
if labeler is None:
raise ValueError("the ISO-IR setting of the structure could not be determined "
"(the irrep labels of crystod-mag are unavailable for it).")
M = np.asarray(algebra.primitive_matrix, dtype=float)
F = np.linalg.inv(M) @ np.asarray(labeler.P, dtype=float)
F_int = np.rint(F)
if not np.allclose(F, F_int, atol=1e-6) or abs(round(np.linalg.det(F_int))) != 1:
raise ValueError("the primitive cell of the structure is not a primitive cell of the "
"ISO-IR setting (please report this case).")
self.F = F_int.astype(np.int64)
self.F_inv = np.rint(np.linalg.inv(F_int)).astype(np.int64)
self.f = np.linalg.inv(M) @ np.asarray(labeler.origin_shift, dtype=float)
self.algebra = algebra
# the translations of a structure off its ideal positions are off by
# about the tolerance spglib found them with (fractional units)
lengths = np.linalg.norm(np.asarray(vibrations.primitive_cell.cell, dtype=float), axis=1)
symprec = float(getattr(vibrations, "symprec", 1e-5))
atol = max(1e-5, 2.0 * symprec / float(lengths.min()))
elements = []
for R, v in zip(vibrations.rotations, vibrations.translations):
W = self.F @ np.asarray(R, dtype=np.int64) @ self.F_inv
key = algebra._key(W)
if key not in algebra._rotation_index:
raise ValueError("an operation of the structure is not an operation of the ISO-IR "
"setting (please report this case).")
i = algebra._rotation_index[key]
va = self.F @ np.asarray(v, dtype=float) + self.f - W @ self.f
t = va - np.asarray(algebra.translations[i], dtype=float) / DEN
t_int = np.rint(t)
if not np.allclose(t, t_int, atol=atol):
raise ValueError("the translations of the structure do not match the ISO-IR "
"setting (please report this case).")
elements.append((i, t_int.astype(np.int64)))
if len({i for i, _ in elements}) != algebra.n_ops or len(elements) != algebra.n_ops:
raise ValueError("the operations of the structure do not cover the space group of "
"the ISO-IR setting (please report this case).")
self.elements = elements
def kpoint(self, k_int) -> np.ndarray:
"""An arm k (algebra primitive basis, units of 1/DEN) in the
reciprocal basis of the POSCAR's primitive cell: k . x_alg = k_p . x."""
from .spacegroup_product import DEN
k = self.F.T @ (np.asarray(k_int, dtype=float) / DEN)
k = np.mod(np.round(k * DEN) / DEN, 1.0)
return k + 0.0
# ---------------------------------------------------------- the supercell action
class _SupercellAction:
"""G/T_S acting on the spins of the magnetic sites of a diagonal supercell.
The elements are ``(k, T)``: the operation k of the POSCAR's primitive
cell followed by the cell translation T; a field is an array
``(n_cells, n_sites, 3, ...)``."""
def __init__(self, vibrations, site_indices, sizes, frame, axial: bool = True):
# axial=False: polar vectors (displacements, crystod-phonon --irrep),
# O(g) u = R u without the factor det(R)
from .magnetic_group import magnetic_cell_translations
from .spin_basis import _match_site, _symmetrized_site_positions
axial_vectors = axial
self.frame = frame
self.sizes = np.asarray(sizes, dtype=np.int64)
self.cell_matrix = np.diag(self.sizes)
self.cell_translations = magnetic_cell_translations(self.cell_matrix)
self.translations_int = [np.rint(t).astype(np.int64) for t in self.cell_translations]
self.cell_index = {tuple(np.mod(t, self.sizes)): c
for c, t in enumerate(self.translations_int)}
n_cells = len(self.cell_translations)
n_sites = len(site_indices)
self.n_cells, self.n_sites = n_cells, n_sites
lattice = np.asarray(vibrations.primitive_cell.cell, dtype=float)
ideal = _symmetrized_site_positions(vibrations, list(site_indices))
symprec = float(getattr(vibrations, "symprec", 1e-5))
lattice_t = lattice.T
lattice_t_inv = np.linalg.inv(lattice_t)
self.operations = [] # (k, T index, destination of every point, axial A, algebra (i, t))
for k, (R, v) in enumerate(zip(vibrations.rotations, vibrations.translations)):
R = np.asarray(R, dtype=np.int64)
cartesian = lattice_t @ R @ lattice_t_inv
axial = np.linalg.det(cartesian) * cartesian if axial_vectors else cartesian
targets = []
for s in range(n_sites):
image = R @ ideal[s] + np.asarray(v, dtype=float)
b = _match_site(image, ideal, lattice, symprec)
if b is None:
raise ValueError("an operation does not map the magnetic sites onto each "
"other (please report this case).")
shift = np.rint(image - ideal[b]).astype(np.int64)
targets.append((b, shift))
i_alg, t_alg = frame.elements[k]
for g_cell, T in enumerate(self.translations_int):
destination = np.empty(n_cells * n_sites, dtype=np.int64)
for c, Tc in enumerate(self.translations_int):
moved = R @ Tc + T
for s, (b, shift) in enumerate(targets):
c_new = self.cell_index[tuple(np.mod(moved + shift, self.sizes))]
destination[c * n_sites + s] = c_new * n_sites + b
self.operations.append(
(k, g_cell, destination, axial, (i_alg, t_alg + frame.F @ T)))
self.order = len(self.operations)
self.identity_index = next(
k for k, R in enumerate(vibrations.rotations)
if np.array_equal(np.asarray(R), np.eye(3, dtype=int))
and np.allclose(np.mod(np.asarray(vibrations.translations[k], dtype=float) + 1e-9, 1.0),
0.0, atol=1e-6))
def apply(self, index: int, fields: np.ndarray) -> np.ndarray:
"""O(g) on fields ``(n_points, 3, r)`` (points = cell * n_sites + site)."""
_, _, destination, axial, _ = self.operations[index]
out = np.empty_like(fields)
out[destination] = np.einsum("ij,pjr->pir", axial, fields)
return out
def character(self, index: int, mask: np.ndarray | None = None) -> float:
"""Trace of O(g), restricted to the points of ``mask`` (a boolean
array over the points) when given."""
_, _, destination, axial, _ = self.operations[index]
fixed = destination == np.arange(len(destination))
if mask is not None:
fixed &= mask
return float(np.count_nonzero(fixed) * np.trace(axial))
# ------------------------------------------------------------ irrep matrices
class _IrrepPart:
"""One irrep: its real matrices on the elements of G/T_S."""
def __init__(self, label, representation, action):
from .spacegroup_product import DEN # noqa: F401
self.label = label
self.representation = representation
n = int(representation.grid_n)
lookup = {}
for i, t, matrix in representation.image_elements():
lookup[(int(i), tuple(int(x) % n for x in t))] = np.asarray(matrix, dtype=float)
self.dimension = int(representation.dimension)
self.matrices = []
for _, _, _, _, (i, t) in action.operations:
key = (int(i), tuple(int(x) % n for x in t))
if key not in lookup:
raise ValueError(f"{label}: an element of the magnetic cell is missing from the "
"irrep matrices (please report this case).")
self.matrices.append(lookup[key])
self.matrices = np.array(self.matrices)
# the translations of the magnetic cell (its lattice T_S) must be
# represented by 1, so that D is a representation of G/T_S
identity = int(representation.algebra._rotation_index[
representation.algebra._key(np.eye(3, dtype=np.int64))])
for axis in range(3):
t = action.frame.F @ (action.sizes[axis] * np.eye(3, dtype=np.int64)[axis])
matrix = lookup.get((identity, tuple(int(x) % n for x in t)))
if matrix is None or not np.allclose(matrix, np.eye(self.dimension), atol=1e-8):
raise ValueError(f"{label}: the magnetic cell is not commensurate with the "
"irrep (please report this case).")
characters = np.einsum("gii->g", self.matrices)
self.characters = characters
self.endomorphism_dim = int(round(float(np.mean(characters * characters))))
def multiplicity(self, action, mask=None) -> int:
"""Multiplicity of the irrep in the spin representation (on the
points of ``mask``)."""
chi_o = np.array([action.character(g, mask) for g in range(action.order)])
value = float(np.dot(chi_o, self.characters)) / (action.order * self.endomorphism_dim)
return int(round(value))
def intertwiners(self, action, fields: np.ndarray) -> np.ndarray:
"""``X_phi`` for every column phi of ``fields`` ``(n_points, 3, r)``:
shape ``(r, n_points, 3, d)``."""
d = self.dimension
n_points, _, r = fields.shape
out = np.zeros((d, n_points, 3, r))
for g in range(action.order):
moved = action.apply(g, fields)
out += self.matrices[g][:, 0][:, None, None, None] * moved[None]
out /= action.order
return np.transpose(out, (3, 1, 2, 0))
def commutant(self) -> list:
"""An orthonormal basis of the matrices commuting with every D(g)."""
d = self.dimension
rng = np.random.default_rng(11)
samples = []
for _ in range(self.endomorphism_dim + 3):
A = rng.normal(size=(d, d))
samples.append(np.einsum("gij,jk,glk->il", self.matrices, A, self.matrices).ravel()
/ len(self.matrices))
u, s, vt = np.linalg.svd(np.array(samples), full_matrices=False)
keep = vt[: self.endomorphism_dim]
return [row.reshape(d, d) * np.sqrt(d) for row in keep]
def _orthonormal_rows(vectors: np.ndarray, tol: float = 1e-8) -> np.ndarray:
"""An orthonormal basis (rows) of the span of the rows."""
if len(vectors) == 0:
return np.zeros((0, 0))
u, s, vt = np.linalg.svd(np.asarray(vectors), full_matrices=False)
if s.size == 0 or s[0] < tol:
return np.zeros((0, vectors.shape[1]))
return vt[s > tol * max(1.0, s[0])]
def _sign_fixed(vector: np.ndarray) -> np.ndarray:
"""The vector with its first entry of largest magnitude positive."""
flat = vector.ravel()
largest = np.max(np.abs(flat))
pivot = int(np.argmax(np.abs(flat) > largest - 1e-9))
return vector if flat[pivot] > 0 else -vector
# --------------------------------------------------------------- the copies
def _wyckoff_text(vibrations, atom: int) -> str:
dataset = vibrations.spglib_dataset
try:
wyckoffs = dataset["wyckoffs"]
equivalent = list(dataset["equivalent_atoms"])
letter = wyckoffs[atom]
count = equivalent.count(equivalent[atom])
centring = {"P": 1, "A": 2, "B": 2, "C": 2, "I": 2, "F": 4, "R": 3}.get(
str(dataset["international"])[0], 1)
return f"{count * centring}{letter}"
except Exception:
return f"orbit of atom {atom + 1}"
def _orbits(vibrations, site_indices, site_elements):
"""``[(element, orbit name, mask over the sites)]`` element by element,
the orbits of an element in the order of their first atom."""
try:
equivalent = list(vibrations.spglib_dataset["equivalent_atoms"])
except Exception:
equivalent = None
result = []
for element in dict.fromkeys(site_elements):
members = [s for s, e in enumerate(site_elements) if e == element]
groups: dict = {}
for s in members:
key = equivalent[site_indices[s]] if equivalent is not None else element
groups.setdefault(key, []).append(s)
letters = [_wyckoff_text(vibrations, site_indices[sites[0]]) for sites in groups.values()]
seen: dict = {}
for (key, sites), letter in zip(groups.items(), letters):
if letters.count(letter) > 1:
# two orbits on the same Wyckoff position: a running number
seen[letter] = seen.get(letter, 0) + 1
letter = f"{letter},{seen[letter]}"
name = element if len(groups) == 1 else f"{element}({letter})"
mask = np.zeros(len(site_indices), dtype=bool)
mask[sites] = True
result.append((element, name, mask))
return result
def _rank_names(part, action, vibrations, frame) -> list:
"""The multipole ranks (dipole, octupole, ...) at which the irrep (at
GM) occurs in the magnetic multipole representations, as the
``--qpoint`` report names its bases."""
from .spin_basis import MULTIPOLE_NAMES
names = []
lattice_t = np.asarray(vibrations.primitive_cell.cell, dtype=float).T
lattice_t_inv = np.linalg.inv(lattice_t)
chi_nu, chi_p = [], {p: [] for p in range(1, 10)}
for g, (k, g_cell, _, _, _) in enumerate(action.operations):
if g_cell != 0:
continue
chi_nu.append(part.characters[g])
operation = lattice_t @ np.asarray(vibrations.rotations[k], dtype=float) @ lattice_t_inv
determinant = float(np.sign(np.linalg.det(operation)))
proper = operation * determinant
cos_theta = np.clip((np.trace(proper) - 1.0) / 2.0, -1.0, 1.0)
theta = float(np.arccos(cos_theta))
for p in chi_p:
base = 2 * p + 1 if theta < 1e-8 else np.sin((p + 0.5) * theta) / np.sin(theta / 2.0)
parity = ((-1) ** (p + 1)) if determinant < 0 else 1
chi_p[p].append(parity * base)
chi_nu = np.array(chi_nu)
for p, values in chi_p.items():
count = int(round(float(np.dot(values, chi_nu)) / (len(chi_nu) * part.endomorphism_dim)))
names.extend([MULTIPOLE_NAMES.get(p, f"rank{p}")] * max(count, 0))
return names
def _split_copies(part, action, subspace, at_gamma):
"""Split an intertwiner subspace (orthonormal rows of vec(X)) into
copies: at q = 0 the ferromagnetic combination first, then the
antiferromagnetic ones; one intertwiner per copy. Returns
``[(kind, X), ...]`` with ``X`` of shape ``(n_points, 3, d)``."""
d = part.dimension
n_points = action.n_cells * action.n_sites
commutant = part.commutant()
e = part.endomorphism_dim
def pick(space):
copies = []
space = np.array(space)
while len(space) >= e and len(space) > 0:
X = space[0].reshape(n_points, 3, d)
orbit = np.array([(X @ E).ravel() for E in commutant])
orbit = _orthonormal_rows(orbit)
copies.append(_sign_fixed(X))
space = space - (space @ orbit.T) @ orbit
space = _orthonormal_rows(space)
return copies
if not at_gamma:
return [("AFM (q != 0)", X) for X in pick(subspace)]
nets = np.array([row.reshape(n_points, 3, d).sum(axis=0).ravel() for row in subspace])
if np.abs(nets).max() < 1e-8:
return [("AFM", X) for X in pick(subspace)]
# coefficient vectors with zero net moment: the antiferromagnetic copies
u, s, vt = np.linalg.svd(nets.T, full_matrices=True)
rank = int(np.sum(s > 1e-8 * s[0]))
ferro = vt[:rank] @ subspace
afm = vt[rank:] @ subspace
return ([("FM", X) for X in pick(_orthonormal_rows(ferro))]
+ [("AFM", X) for X in pick(_orthonormal_rows(afm))])
def _copies_of(part, action, vibrations, frame, orbits, at_gamma, element_order,
multipoles: bool = True):
"""The copies of one irrep, orbit by orbit, with the multiplicity of
every element; also the largest residuals of the intertwining relation
and of the orthonormality. ``multipoles=False`` (displacements) names
no magnetic multipole ranks (``rank_name`` None)."""
rng = np.random.default_rng(2026)
n_points = action.n_cells * action.n_sites
d = part.dimension
e = part.endomorphism_dim
rank_names = (_rank_names(part, action, vibrations, frame)
if at_gamma and multipoles else [])
copies, multiplicities = [], {element: 0 for element in element_order}
worst_intertwining = worst_orthonormality = 0.0
for element, name, site_mask in orbits:
point_mask = np.tile(site_mask, action.n_cells)
m = part.multiplicity(action, point_mask)
if m <= 0:
continue
multiplicities[element] += m
trial = rng.normal(size=(n_points, 3, m * e + 3))
trial[~point_mask] = 0.0
candidates = part.intertwiners(action, trial).reshape(m * e + 3, -1)
subspace = _orthonormal_rows(candidates, tol=1e-7)
if len(subspace) != m * e:
raise ValueError(f"{part.label}: the intertwiners on {name} span {len(subspace)} "
f"dimensions, not {m} x {e} (please report this case).")
split = _split_copies(part, action, subspace, at_gamma)
if len(split) != m:
raise ValueError(f"{part.label}: {len(split)} copies found on {name}, the character "
f"formula gives {m} (please report this case).")
position = 0
for kind, X in split:
# residuals: the intertwining relation and Psi^T Psi = c 1
for g in range(action.order):
moved = action.apply(g, X)
residual = np.abs(moved - X @ part.matrices[g]).max()
worst_intertwining = max(worst_intertwining, float(residual))
gram = np.einsum("pij,pik->jk", X, X)
scale = np.trace(gram) / d
worst_orthonormality = max(worst_orthonormality,
float(np.abs(gram / scale - np.eye(d)).max()))
rank_name = None
if at_gamma and multipoles:
rank_name = rank_names[position] if position < len(rank_names) else "multipole"
position += 1
copies.append(IrrepCopy(irrep=part.label, number=len(copies) + 1, element=element,
orbit=name, kind=kind, rank_name=rank_name,
intertwiner=X.reshape(action.n_cells, action.n_sites, 3, d)))
return copies, multiplicities, worst_intertwining, worst_orthonormality
# ----------------------------------------------------------- decomposition
def _decomposition(vibrations, site_indices, q, polar: bool = False):
"""The survey's decomposition at q: ``(text, entries)`` with entries
``[(names, count, paired)]``; ``names`` the member irrep names.
``polar=True``: of the displacement (polar-vector) representation, the
spin representation times det(R) of every operation."""
from .runtime_compat import get_character
from .spin_basis import _conjugate_pairs, _pair_label, get_spin_representation
irreps, spin_rep, mapping = get_spin_representation(vibrations, site_indices, q)
labels = vibrations.get_irrep_labels(q, irreps, mapping)
characters_rep = np.array([np.trace(matrix) for matrix in spin_rep])
if polar:
determinants = np.array([round(np.linalg.det(np.asarray(vibrations.rotations[m],
dtype=float)))
for m in mapping])
characters_rep = characters_rep * determinants
counts = {}
for index, irrep in enumerate(irreps):
characters = np.array(get_character(irrep), dtype=complex)
count = int(round(float(np.real(np.dot(characters_rep, np.conj(characters))))
/ len(spin_rep)))
if count > 0:
counts[index] = count
pairs = (_conjugate_pairs(irreps, labels, set(counts))
if np.allclose(2.0 * np.asarray(q), np.rint(2.0 * np.asarray(q))) else {})
seconds = set(pairs.values())
terms, entries = [], []
for index, count in counts.items():
if index in seconds:
continue
label = labels[index]
names = {label.split("(")[0]}
if index in pairs:
names.add(labels[pairs[index]].split("(")[0])
label = _pair_label(label, labels[pairs[index]])
terms.append(f"{count}.0 [{label}]")
entries.append((names, count, index in pairs))
return " + ".join(terms), entries
def _expected_multiplicity(representation, entries) -> int:
"""The real multiplicity the survey's decomposition implies."""
name = representation.irrep.name
for names, count, paired in entries:
if name in names:
if getattr(representation, "doubled", False) and not paired and \
getattr(representation, "fs_type", "") == "pseudoreal":
return count // 2
return count
return 0
# --------------------------------------------------------------- the tables
def _single_table(algebra_label, parent):
"""Rows and generic order parameters of one irrep (the rows of
``crystod-mag --parent SG --irrep IR``, in its order)."""
from .isotropy_subgroup import _orth_basis, _rep_cache
from .magnetic_isotropy import MagneticIsotropyAnalyzer, MagneticIsotropySubgroup
analyzer = MagneticIsotropyAnalyzer(parent, algebra_label)
representation = analyzer.representation
cache = _rep_cache(representation, analyzer.elements)
records = []
for projector, _ in analyzer.enumerate_directions():
direction, generic = analyzer.direction_label(projector)
members = [
(analyzer.elements[g][0], analyzer.elements[g][1])
for g in np.nonzero(cache.vector_stabilizer_mask(generic))[0]
]
group, size, index, n_operations = analyzer.magnetic_subgroup_of(members)
unitary = analyzer.subgroup_of(members)[0]
row = MagneticIsotropySubgroup(
irrep=representation.label, direction=direction, bns_number=group.bns_number,
bns_symbol=group.bns_symbol, msg_type=group.msg_type, uni_symbol=group.uni_symbol,
og_number=group.og_number, magnetic_point_group=group.magnetic_point_group,
unitary_number=int(unitary.number), unitary_symbol=str(unitary.international_short),
size=size, index=index, n_free=_orth_basis(projector).shape[1],
n_operations=n_operations)
records.append((row, np.asarray(generic, dtype=float), projector))
records.sort(key=lambda r: (r[0].n_free, r[0].index,
*(int(x) for x in r[0].bns_number.split("."))))
return analyzer, records
def _coupled_tables(parent, irreps):
"""Singles (as ``--parent`` prints them) and the coupled rows with their
generic order parameters, in the order of the coupled table."""
from .isotropy_subgroup import _rep_cache
from .magnetic_isotropy_coupled import (
CoupledMagneticIsotropyAnalyzer,
ParityRepresentation,
_LabelledPart,
_row,
_split_label,
coupled_magnetic_analyzer,
single_rows,
)
analyzer, parts, parities, labels = coupled_magnetic_analyzer(parent, irreps, None)
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))
singles[label] = single_rows(sub, label, offset)
offset += part.dimension
representation = analyzer.representation
bounds = np.cumsum([0] + list(representation.dims))
records = []
_rep_cache(representation, analyzer.elements)
for projector, _ in analyzer.enumerate_directions():
label, generic = analyzer.direction_label(projector)
if not all(np.linalg.norm(generic[bounds[j]: bounds[j + 1]]) > 1e-8
for j in range(len(labels))):
continue
row = _row(analyzer, projector, generic, label, labels, _split_label(label, labels))
records.append((row, np.asarray(generic, dtype=float), projector))
records.sort(key=lambda r: (r[0].n_free, r[0].index,
*(int(x) for x in r[0].bns_number.split("."))))
return analyzer, parts, labels, singles, records
# ------------------------------------------------------------ letter values
_TERM = re.compile(r"([+-]?)(\d+(?:\.\d+)?(?:/\d+)?)?([a-z])")
def _component_coefficients(token: str) -> dict:
"""``{letter: factor}`` of one printed component (``-0.974a``, ``a+b``)."""
token = token.strip()
result = {}
if token in ("", "0"):
return result
for sign, number, letter in _TERM.findall(token):
if number:
if "/" in number:
num, den = number.split("/")
value = float(num) / float(den)
else:
value = float(number)
else:
value = 1.0
result[letter] = result.get(letter, 0.0) + (-value if sign == "-" else value)
return result
def _letter_values(components, order_parameter) -> dict:
"""Least-squares values of the letters of the printed direction."""
tokens = []
for component in components:
inner = component.strip()
if inner.startswith("(") and inner.endswith(")"):
inner = inner[1:-1]
tokens.extend(re.split(r"[;,]", inner))
if len(tokens) != len(order_parameter):
return {}
letters: dict = {}
for slot, token in enumerate(tokens):
for letter, factor in _component_coefficients(token).items():
letters.setdefault(letter, np.zeros(len(tokens)))[slot] += factor
if not letters:
return {}
names = sorted(letters)
matrix = np.array([letters[name] for name in names]).T
values, *_ = np.linalg.lstsq(matrix, order_parameter, rcond=None)
return {name: float(value) for name, value in zip(names, values)}
# ------------------------------------------------------------------ helpers
def _moment_text(field, site_elements, untouched=None, irreps=(), quantity="|m|",
noun="moment") -> str:
"""One line on the sizes of the moments, element by element.
``untouched`` (``(n_cells, n_sites)`` booleans) marks the sites that no
irrep's part reaches; the other zero moments cancel between the parts.
``quantity`` and ``noun`` name the vectors (``"|u|"``, ``"displacement"``
for crystod-phonon --irrep)."""
pieces = []
norms = np.linalg.norm(field, axis=2) # (n_cells, n_sites)
if untouched is None:
untouched = norms < 1e-6
for element in dict.fromkeys(site_elements):
columns = [s for s, e in enumerate(site_elements) if e == element]
values = norms[:, columns].ravel()
free = np.asarray(untouched)[:, columns].ravel()
n = len(values)
zero = values < 1e-6
nonzero = np.sort(values[~zero])[::-1]
distinct = []
for value in nonzero:
if not distinct or abs(distinct[-1][0] - value) > 1e-6:
distinct.append([value, 1])
else:
distinct[-1][1] += 1
zero_text = []
if (zero & free).any():
zero_text.append(f"zero on {int((zero & free).sum())} sites (no {noun} in "
f"{', '.join(irreps) or 'the irreps'})")
if (zero & ~free).any():
zero_text.append(f"cancelled on {int((zero & ~free).sum())} sites by the weights")
tail = ("; " + "; ".join(zero_text)) if zero_text else ""
if not distinct:
pieces.append(f"zero on all {n} {element} sites")
elif len(distinct) == 1:
text = f"{quantity} = {distinct[0][0]:.4f}"
if zero.any():
pieces.append(f"{text} on {distinct[0][1]} of {n} {element} sites{tail}")
else:
pieces.append(f"equal on all {n} {element} sites ({text})")
else:
listed = ", ".join(f"{value:.4f} (x{count})" for value, count in distinct)
pieces.append(f"{len(distinct)} distinct magnitudes on {n} {element} sites: "
f"{listed}{tail}")
return "; ".join(pieces)
def _fixing_counts(action, matrix_list, field_points, eta,
time_reversal: bool = True) -> tuple[int, int, list]:
"""Elements of G1'/T_S (G and theta G) fixing the field and fixing eta,
and the cell translations (fractional, magnetic cell) fixing the field.
``time_reversal=False`` (displacements): the elements of G/T_S only."""
n_field = n_eta = 0
translations = []
inverse_cell = np.linalg.inv(np.asarray(action.cell_matrix, dtype=float))
flat = field_points[:, :, None]
for g in range(action.order):
moved = action.apply(g, flat)[:, :, 0]
D = matrix_list[g]
image = D @ eta
scale = MOMENT_TOLERANCE * max(1.0, float(np.abs(field_points).max()))
if np.abs(moved - field_points).max() < scale:
n_field += 1
k, g_cell, _, axial, _ = action.operations[g]
if k == action.identity_index:
translations.append(action.translations_int[g_cell] @ inverse_cell)
if time_reversal and np.abs(moved + field_points).max() < scale:
n_field += 1
if np.abs(image - eta).max() < 1e-6:
n_eta += 1
if time_reversal and np.abs(image + eta).max() < 1e-6:
n_eta += 1
return n_field, n_eta, translations
def _verdict(row_bns: str, group) -> tuple[str, str | None]:
from .isotropy_subgroup import ENANTIOMORPHIC_PAIRS
if group is None or not getattr(group, "identified", False):
return "not identified", ("NOTE: spglib could not identify the magnetic space group of "
"this arrangement; the table's group is the stabilizer of the "
"order parameter.")
if group.bns_number == row_bns:
return "same", None
found, wanted = int(group.bns_number.split(".")[0]), int(row_bns.split(".")[0])
if ENANTIOMORPHIC_PAIRS.get(wanted) == found:
return "enantiomorph", (f"NOTE: spglib finds {group.bns_number} {group.bns_symbol}, the "
f"enantiomorphic partner type of {row_bns}: the mirror-image "
"order parameter of the same stratum.")
return "different", (f"NOTE: spglib finds {group.bns_number} {group.bns_symbol} on the "
f"structure, not the table's {row_bns}; please report this case.")
def _resolve_irreps(algebra, irreps):
"""The labels with ``m`` removed, every invalid one reported at once."""
from .isotropy_subgroup import InducedRepresentation
from .magnetic_isotropy import _strip_magnetic_prefix
labels, problems, representations = [], [], []
available = []
for label in irreps:
stripped = _strip_magnetic_prefix(algebra, str(label))
try:
with contextlib.redirect_stdout(io.StringIO()):
representation = InducedRepresentation(algebra, stripped)
except SystemExit as exc:
text = str(exc).removeprefix("ERROR: ")
lines = text.split("\n")
problems.append(lines[0])
if len(lines) > 1:
available = lines[1:]
continue
labels.append(stripped)
representations.append(representation)
names = [r.label for r in representations]
duplicates = sorted({n for n in names if names.count(n) > 1})
if duplicates:
problems.append(f"irrep {', '.join(duplicates)} is given twice.")
keep = [names.index(n) for n in dict.fromkeys(names)]
labels = [labels[i] for i in keep]
representations = [representations[i] for i in keep]
problems.extend(available)
return labels, representations, problems
# ---------------------------------------------------------------------- API
[docs]
def magnetic_irrep_arrangements(
cell=None,
elements=(),
irreps=(),
*,
symprec: float = 1e-5,
coefficients=None,
classify: bool = True,
vibrations=None,
order_parameter=None,
copies=None,
conventional: bool = False,
) -> MagneticIrrepAnalysis:
"""The magnetic arrangements of given irreps on a crystal.
The computation behind ``crystod-mag -c POSCAR --element EL [EL2 ...]
--irrep IR [IR2 ...]``: for every row of the table of ``crystod-mag
--parent SG --irrep IR [IR2 ...]`` (one irrep: its table; several: the
coupled table, every irrep condensed) the arrangement of moments on the
sites of the chosen elements that the row's order parameter describes
(see the module docstring), with its magnetic space group identified
again from the structure.
Args:
cell: The crystal (phonopy ``PhonopyAtoms``, a primitive cell); not
needed when ``vibrations`` is given.
elements: The magnetic elements (``["Mn"]``, ``["Al", "Ni"]``).
irreps: ISO-IR labels (``["R4-"]``, ``["R4-", "M3-"]``; ``mR4-`` and
pair labels ``GM3+GM4+`` accepted, as with ``--parent``).
symprec: Symmetry tolerance (spglib, Angstrom).
coefficients: The weight of every irrep's part (each part has its
largest moment 1 before weighting); default 1 each.
classify: Identify the magnetic group, the responses and the
collinear class of every arrangement.
vibrations: A prebuilt ``SymmetryOnlyVibrations(cell,
standardize=False)``.
order_parameter: ``--order-parameter`` tokens (irrep after irrep);
then one arrangement, of that vector, is built instead of one per
row (:attr:`MagneticIrrepAnalysis.stratum` names its row). The
numbers are amplitudes: the field is sum_j c_j s_j Psi_j eta_j,
s_j scaling one unit component of a copy to rms moment 1 over its
sites, then scaled to largest moment 1.
copies: One copy number (from 1) per irrep (``--copies``): only that
choice of copies is exported. By default every choice while
there are at most ``MAX_COPY_CHOICES`` per row, else the first.
conventional: Write the arrangements in the conventional cell
(``--conventional``): the cell of
:func:`crystod.phonon_vector.get_conventional_matrix` for the
centring letter of the space group, as ``crystod-mag --qpoint
--conventional`` uses it, times the smallest multiples along its
axes commensurate with every arm. The spin modes, weights and
counts stay on the diagonal magnetic cell; the written moments
are the field re-tiled onto the conventional cell (exact: the
field is periodic under every translation T with k . T an
integer for every arm), and the group check is made on them.
Returns:
A :class:`MagneticIrrepAnalysis`.
Raises:
ValueError: An element not in the cell, an unknown or repeated
irrep, an irrep the spin representation of the elements does not
contain (the message lists the decomposition at its k point), a
magnetic cell larger than ``MAX_CELLS`` primitive cells (with
``conventional``: a conventional cell of more than
``MAX_MULTIPLE`` cells along one axis or ``4 * MAX_CELLS``
primitive cells), a cell that is not primitive, a wrong
``--order-parameter``.
"""
from .phonon_vector import reduced_formula
from .spacegroup_product import DEN, SpaceGroupIrrepAlgebra
from .spin_basis import _require_primitive
from .vibration_modes import SymmetryOnlyVibrations
elements = list(elements)
irreps = list(irreps)
if not elements:
raise ValueError("at least one element is needed.")
if not irreps:
raise ValueError("at least one irrep is needed.")
if len(set(elements)) != len(elements):
raise ValueError(f"an element is given twice: {' '.join(elements)}")
if vibrations is None:
vibrations = SymmetryOnlyVibrations(cell=cell, symprec=symprec, standardize=False,
quiet=True)
_require_primitive(vibrations)
primitive = vibrations.primitive_cell
symbols = list(primitive.symbols)
missing = [e for e in elements if e not in symbols]
if missing:
available = ", ".join(sorted(set(symbols)))
raise ValueError(f"element '{missing[0]}' is not in this POSCAR ({available}).")
site_lists = [[i for i, s in enumerate(symbols) if s == e] for e in elements]
site_indices = [i for sites in site_lists for i in sites]
site_elements = [e for e, sites in zip(elements, site_lists) for _ in sites]
number = int(vibrations.spglib_dataset["number"])
parent = str(number)
with contextlib.redirect_stdout(io.StringIO()):
algebra = SpaceGroupIrrepAlgebra(parent)
labels, representations, problems = _resolve_irreps(algebra, irreps)
user_weights = coefficients is not None
if coefficients is not None:
coefficients = [float(c) for c in coefficients]
if len(coefficients) != len(irreps):
raise ValueError(f"--coefficients needs one value per irrep ({len(irreps)}), not "
f"{len(coefficients)}.")
bad = [c for c in coefficients if not np.isfinite(c) or c == 0.0]
if bad:
raise ValueError("--coefficients must be finite and nonzero (a negative value is "
"allowed: the other domain of that irrep); got "
+ " ".join(f"{c:g}" for c in coefficients) + ".")
largest_weight = max(abs(c) for c in coefficients)
small = [c for c in coefficients if abs(c) < MIN_RELATIVE_WEIGHT * largest_weight]
if small:
raise ValueError(
f"--coefficients {' '.join(f'{c:g}' for c in coefficients)}: a weight below "
f"{MIN_RELATIVE_WEIGHT:g} of the largest vanishes in the written moments "
f"({MOMENT_DECIMALS} decimals); the file would not carry that irrep.")
else:
coefficients = [1.0] * len(irreps)
if copies is not None:
copies = [int(c) for c in copies]
if len(copies) != len(irreps):
raise ValueError(f"--copies needs one copy number per irrep ({len(irreps)}), not "
f"{len(copies)}.")
frame = _Frame(vibrations, algebra)
# the k points: one arm per irrep in the POSCAR frame, and the survey's
# decomposition there; an irrep the elements do not carry is refused
kpoints, decompositions, absent = {}, {}, []
unlabelled_k: set = set()
survey_entries = {}
for representation in representations:
kname = representation.irrep.kpname
q = frame.kpoint(representation.k)
q = [float(x) + 0.0 for x in np.round(q, 10)]
kpoints[representation.label] = (kname, q)
if kname not in decompositions:
lines = []
entries_total = None
for element, sites in zip(elements, site_lists):
text, entries = _decomposition(vibrations, sites, q)
lines.append((element, text))
if len(elements) > 1:
text, entries_total = _decomposition(vibrations, site_indices, q)
lines.append(("total", text))
else:
entries_total = _decomposition(vibrations, site_indices, q)[1]
decompositions[kname] = lines
survey_entries[kname] = entries_total
expected = _expected_multiplicity(representation, survey_entries[kname])
unlabelled = any(name.startswith("irrep_") for names, _, _ in survey_entries[kname]
for name in names)
if unlabelled:
# the survey's labeller failed (a structure off its ideal
# positions); the multiplicity comes from the irrep matrices
unlabelled_k.add(kname)
elif expected == 0:
absent.append(representation)
if absent or problems:
messages = list(problems)
for representation in absent:
kname, q = kpoints[representation.label]
listed = "; ".join(f"{name}: {text}" if len(elements) > 1 or name == "total"
else text for name, text in decompositions[kname])
messages.append(
f"{representation.label} is not contained in the spin representation of "
f"{', '.join(elements)} at {kname} {np.round(q, 6).tolist()}; the "
f"decomposition there is {listed}")
raise ValueError("\n".join(messages))
# the common magnetic cell: diagonal, commensurate with every arm
sizes = np.ones(3, dtype=np.int64)
for representation in representations:
for arm in representation.arms:
k = frame.kpoint(arm)
for axis in range(3):
from fractions import Fraction
denominator = Fraction(float(k[axis])).limit_denominator(DEN).denominator
sizes[axis] = int(np.lcm(sizes[axis], denominator))
if sizes.max() > MAX_MULTIPLE or int(np.prod(sizes)) > MAX_CELLS:
raise ValueError(
f"the magnetic cell common to every arm of {', '.join(r.label for r in representations)}"
f" is {sizes[0]}x{sizes[1]}x{sizes[2]} primitive cells ({int(np.prod(sizes))}); "
f"at most {MAX_CELLS} cells and {MAX_MULTIPLE} along one axis are supported.")
action = _SupercellAction(vibrations, site_indices, sizes, frame)
# the written cell: the diagonal magnetic cell, or the conventional one
if conventional:
centring, multiples, out_matrix, out_translations, internal_of = _display_cell(
vibrations, representations, frame, action)
from .spin_basis import conventional_cell_note
conventional_note = conventional_cell_note(
vibrations, centring, np.asarray(out_matrix) // multiples[:, None],
len(out_translations))
else:
centring, multiples, conventional_note = None, None, None
out_matrix, out_translations = action.cell_matrix, action.cell_translations
internal_of = np.arange(len(action.cell_translations))
# the tables (and the representations their rows refer to)
with contextlib.redirect_stdout(io.StringIO()):
try:
if len(labels) == 1:
analyzer, records = _single_table(labels[0], parent)
table_parts = [analyzer.representation.base]
table_labels = [analyzer.representation.label]
singles = {}
else:
analyzer, table_parts, table_labels, singles, records = _coupled_tables(
parent, labels)
except SystemExit as exc:
raise ValueError(str(exc).removeprefix("ERROR: ")) from None
parts = []
for label, representation in zip(table_labels, table_parts):
base = getattr(representation, "base", representation)
parts.append(_IrrepPart(label, base, action))
# the copies of every irrep, checked against the survey
orbits = _orbits(vibrations, site_indices, site_elements)
found_copies, multiplicities = {}, {}
worst = {"intertwining": 0.0, "orthonormality": 0.0}
for part, representation in zip(parts, representations):
at_gamma = not np.any(np.asarray(representation.k) % DEN)
found, counts, w_int, w_orth = _copies_of(part, action, vibrations, frame, orbits,
at_gamma, elements)
kname = representation.irrep.kpname
expected = _expected_multiplicity(representation, survey_entries[kname])
if kname in unlabelled_k:
if not found:
raise ValueError(
f"{part.label} is not contained in the spin representation of "
f"{', '.join(elements)} at {kname} (from the irrep matrices; the irreps of "
f"the survey could not be labelled at this tolerance, {symprec:g} A).")
expected = len(found)
if len(found) != expected:
raise ValueError(
f"{part.label}: {len(found)} copies on the sites, the decomposition at {kname} "
f"gives {expected}: the irrep matrices and the labels of the survey do not "
"refer to the same setting (please report this case).")
if w_int > INTERTWINING_TOLERANCE:
raise ValueError(f"{part.label}: the spin modes do not transform with the irrep "
f"matrices (residual {w_int:.2e}; please report this case).")
worst["intertwining"] = max(worst["intertwining"], w_int)
worst["orthonormality"] = max(worst["orthonormality"], w_orth)
found_copies[part.label] = found
multiplicities[part.label] = counts
# the written cell (atom-major, as the SPOSCAR of the --qpoint runs)
lattice = np.asarray(primitive.cell, dtype=float)
positions = np.asarray(primitive.scaled_positions, dtype=float)
inverse_cell = np.linalg.inv(np.asarray(out_matrix, dtype=float))
supercell_symbols, supercell_positions = [], []
supercell_site_of_atom, supercell_cell_of_atom = [], []
for i, symbol in enumerate(symbols):
for c, translation in enumerate(out_translations):
supercell_symbols.append(symbol)
frac = (positions[i] + translation) @ inverse_cell
supercell_positions.append(frac - np.floor(frac))
supercell_site_of_atom.append(site_indices.index(i) if i in site_indices else None)
supercell_cell_of_atom.append(c)
supercell_positions = np.array(supercell_positions)
supercell_lattice = np.asarray(out_matrix, dtype=float) @ lattice
types = {s: n + 1 for n, s in enumerate(dict.fromkeys(supercell_symbols))}
numbers = [types[s] for s in supercell_symbols]
analysis = MagneticIrrepAnalysis(
formula=reduced_formula(symbols), elements=elements,
space_group=str(vibrations.spglib_dataset["international"]),
space_group_number=number, irreps=[p.label for p in parts],
dimensions=[p.dimension for p in parts], kpoints=kpoints,
decompositions=decompositions, multiplicities=multiplicities, copies=found_copies,
singles=singles, rows=[r[0] for r in records], arrangements=[],
coefficients=tuple(coefficients), cell_matrix=np.asarray(out_matrix),
supercell_sizes=sizes, cell_translations=out_translations,
supercell_lattice=supercell_lattice, supercell_symbols=supercell_symbols,
supercell_positions=supercell_positions, supercell_site_of_atom=supercell_site_of_atom,
supercell_cell_of_atom=supercell_cell_of_atom, site_indices=site_indices,
site_elements=site_elements, residuals=worst, parts=parts,
unlabelled_kpoints=sorted(unlabelled_k),
conventional_centring=centring, conventional_multiples=multiples,
internal_cell_translations=action.cell_translations,
conventional_note=conventional_note,
)
bounds = np.cumsum([0] + [p.dimension for p in parts])
combined = np.array([
_block_diagonal([part.matrices[g] for part in parts]) for g in range(action.order)
])
if order_parameter is not None:
targets = _order_parameter_target(analyzer, parent, labels, records, order_parameter)
analysis.order_parameter_input = list(order_parameter)
row, eta, stratum = targets
analysis.stratum = stratum
work = [(stratum if stratum is not None else 0, row, eta)]
else:
work = [(n + 1, row, eta) for n, (row, eta, _) in enumerate(records)]
copy_lists = [found_copies[p.label] for p in parts]
several = any(len(listed) > 1 for listed in copy_lists)
copy_choices = list(itertools.product(*copy_lists))
if copies is not None:
wrong = [f"{p.label} has {len(listed)} cop{'y' if len(listed) == 1 else 'ies'}"
for p, listed, n in zip(parts, copy_lists, copies)
if not 1 <= n <= len(listed)]
if wrong:
raise ValueError(f"--copies {' '.join(str(n) for n in copies)}: "
+ "; ".join(wrong) + ".")
copy_choices = [tuple(listed[n - 1] for listed, n in zip(copy_lists, copies))]
elif len(copy_choices) > MAX_COPY_CHOICES:
analysis.copy_note = (
f"NOTE: {len(copy_choices)} choices of copies per row; only the first (c"
+ "-".join("1" for _ in parts) + ") is exported. --copies "
+ " ".join("i" for _ in parts) + " (one copy number per irrep, as listed under "
"* Copies in the spin representation *) exports another one.")
copy_choices = copy_choices[:1]
scales = {}
for listed, part in zip(copy_lists, parts):
for copy in listed:
X = copy.intertwiner
carrying = np.count_nonzero(np.linalg.norm(X, axis=(2, 3)) > 1e-10)
scales[id(copy)] = float(np.sqrt(carrying * part.dimension
/ max(np.sum(X * X), 1e-300)))
irrep_labels = [p.label for p in parts]
for number_, row, eta in work:
components = getattr(row, "components", None) or (row.direction,)
eta = np.array(eta, dtype=float)
letters = {}
for j, component in enumerate(components):
own = _letter_values([component], eta[bounds[j]: bounds[j + 1]])
if own and order_parameter is None:
# a positive scale of every irrep's part (same stabilizer):
# its largest letter 1
scale = max(abs(value) for value in own.values())
if scale > 1e-12:
eta[bounds[j]: bounds[j + 1]] /= scale
own = {name: value / scale for name, value in own.items()}
letters.update(own)
for choice in copy_choices:
tag = "c" + "-".join(str(copy.number) for copy in choice) if several else ""
pieces = [copy.intertwiner @ eta[bounds[j]: bounds[j + 1]]
for j, copy in enumerate(choice)]
if order_parameter is not None:
units = [coefficients[j] * scales[id(copy)] for j, copy in enumerate(choice)]
weights, reason = list(coefficients), None
else:
largest_parts = [float(np.max(np.linalg.norm(piece, axis=2)))
for piece in pieces]
normalized = [piece / largest if largest > 1e-12 else piece * 0.0
for piece, largest in zip(pieces, largest_parts)]
if user_weights:
weights, reason = list(coefficients), None
else:
weights, reason = _default_weights(normalized)
if conventional:
# the same choice on the written cell (the same
# moments, re-tiled); the reason counts its sites
written_weights, reason = _default_weights(
[piece[internal_of] for piece in normalized])
if written_weights != weights:
raise ValueError(f"{row.label}: the default weights differ between "
"the magnetic cell and the conventional cell "
"(please report this case).")
units = [w / largest if largest > 1e-12 else 0.0
for w, largest in zip(weights, largest_parts)]
contributions = [unit * piece for unit, piece in zip(units, pieces)]
raw = np.sum(contributions, axis=0)
largest = float(np.max(np.linalg.norm(raw, axis=2)))
if largest < 1e-12:
raise ValueError(f"the moments of {row.label} vanish for these weights.")
for j, contribution in enumerate(contributions):
own_largest = float(np.max(np.linalg.norm(contribution, axis=2)))
if 0 < own_largest < MIN_RELATIVE_WEIGHT * largest:
raise ValueError(
f"{row.label}: the part of {parts[j].label} is {own_largest / largest:.1e}"
f" of the largest moment, below {MIN_RELATIVE_WEIGHT:g}: it vanishes in "
f"the written moments ({MOMENT_DECIMALS} decimals).")
# the moments as written (MAGMOM, listings, VESTA): every check
# below is made on them
field = np.round(raw / largest, MOMENT_DECIMALS) + 0.0
reached = np.any([np.linalg.norm(c, axis=2) > 1e-6 * largest
for c in contributions], axis=0)
reproduce = np.concatenate([
unit * eta[bounds[j]: bounds[j + 1]] / (scales[id(copy)] * largest)
for j, (unit, copy) in enumerate(zip(units, choice))])
# the written cell: the field re-tiled (the identity without
# --conventional); the field is periodic under every translation
# T with k . T an integer for every arm
written = field[internal_of]
magmoms = np.zeros((len(supercell_symbols), 3))
for atom, site in enumerate(supercell_site_of_atom):
if site is not None:
magmoms[atom] = written[supercell_cell_of_atom[atom], site]
arrangement = MagneticArrangement(
number=number_, row=row, copies=tuple(choice), tag=tag,
order_parameter=eta, letters=letters, coefficients=tuple(weights),
field=field, magmoms=magmoms, net_moment=written.sum(axis=(0, 1)),
moment_text=_moment_text(written, site_elements, (~reached)[internal_of],
irrep_labels))
arrangement.weight_reason = reason
arrangement.reproduce = reproduce
n_field, n_eta, arrangement.fixing_translations = _fixing_counts(
action, combined, field.reshape(-1, 3), eta)
if conventional:
arrangement.fixing_translations = _written_translations(
out_matrix, out_translations, written)
arrangement.n_fixing_field, arrangement.n_fixing_order_parameter = n_field, n_eta
if classify:
_classify(arrangement, vibrations, out_matrix, written, site_indices,
supercell_lattice, supercell_positions, numbers, symprec,
grid=48 if not conventional else int(np.lcm(48, len(out_translations))))
if n_field != n_eta:
extra = (f"NOTE: {n_field} elements of G1'/T_S fix the written moments and "
f"{n_eta} fix the order parameter.")
arrangement.note = extra if arrangement.note is None else (
arrangement.note + " " + extra)
analysis.arrangements.append(arrangement)
_name_files(analysis)
return analysis
def _display_cell(vibrations, representations, frame, action):
"""The conventional cell of ``--conventional``.
The base is the cell of :func:`crystod.phonon_vector.get_conventional_matrix`
for the centring letter of the space group (rows in primitive units), as
``crystod-mag --qpoint --conventional`` uses it; each of its axes T_i is
multiplied by the smallest n_i with k . T_i n_i an integer for every arm
k of every irrep. The field of the diagonal magnetic cell is periodic
under these translations, so every atom of the conventional cell takes
the moment of the site it is a lattice image of.
Returns:
``(centring, multiples, cell_matrix, translations, internal_of)``:
``internal_of[c]`` is the cell of the diagonal magnetic cell that
translation c of the conventional cell falls on.
Raises:
ValueError: A centring without a conventional matrix, a cell that
is not commensurate with an arm, or one larger than
``MAX_MULTIPLE`` conventional cells along an axis or
``4 * MAX_CELLS`` primitive cells.
"""
from fractions import Fraction
from .magnetic_group import magnetic_cell_translations
from .phonon_vector import get_conventional_matrix
from .spacegroup_product import DEN
centring = str(vibrations.spglib_dataset["international"])[0]
try:
base = np.asarray(get_conventional_matrix(centring), dtype=np.int64)
except ValueError as exc:
raise ValueError(f"--conventional: no conventional cell for the centring "
f"'{centring}' ({exc}); run without --conventional.") from None
arms = [frame.kpoint(arm) for representation in representations
for arm in representation.arms]
multiples = np.ones(3, dtype=np.int64)
for k in arms:
for axis, value in enumerate(base @ k):
denominator = Fraction(float(value)).limit_denominator(DEN).denominator
multiples[axis] = int(np.lcm(multiples[axis], denominator))
cell_matrix = np.diag(multiples) @ base
n_cells = int(round(abs(np.linalg.det(cell_matrix))))
sizes = action.sizes
if multiples.max() > MAX_MULTIPLE or n_cells > 4 * MAX_CELLS:
raise ValueError(
f"the conventional cell ({centring} centring) commensurate with every arm is "
f"{multiples[0]}x{multiples[1]}x{multiples[2]} conventional cells ({n_cells} "
f"primitive cells); with --conventional at most {MAX_MULTIPLE} conventional cells "
f"along one axis and {4 * MAX_CELLS} primitive cells are supported. Run without "
f"--conventional (the {sizes[0]}x{sizes[1]}x{sizes[2]} primitive supercell).")
for k in arms:
products = cell_matrix @ k
if np.abs(products - np.rint(products)).max() > 1e-6:
raise ValueError(
f"the conventional cell {multiples[0]}x{multiples[1]}x{multiples[2]} "
f"({centring} centring) is not commensurate with the arm "
f"{np.round(k, 6).tolist()} (k . T = {np.round(products, 6).tolist()}); "
"run without --conventional (please report this case).")
translations = magnetic_cell_translations(cell_matrix)
internal_of = np.array([
action.cell_index[tuple(np.mod(np.rint(t).astype(np.int64), sizes))]
for t in translations])
return centring, multiples, cell_matrix, translations, internal_of
def _written_translations(cell_matrix, translations, written) -> list:
"""The primitive translations of the written cell that map the written
moments ``(n_cells, n_sites, 3)`` onto themselves (fractional, written
cell), the identity included."""
cell_matrix = np.asarray(cell_matrix, dtype=float)
inverse = np.linalg.inv(cell_matrix)
n = int(round(abs(np.linalg.det(cell_matrix))))
def key(t):
return tuple(np.mod(np.rint(np.asarray(t, dtype=float) @ inverse * n).astype(np.int64), n))
index = {key(t): c for c, t in enumerate(translations)}
scale = MOMENT_TOLERANCE * max(1.0, float(np.abs(written).max()))
fixing = []
for T in translations:
target = np.array([index[key(np.asarray(t) + np.asarray(T))] for t in translations])
moved = np.empty_like(written)
moved[target] = written
if np.abs(moved - written).max() < scale:
fixing.append(np.asarray(T, dtype=float) @ inverse)
return fixing
def _weight_candidates(n: int):
"""Weight sets tried in turn for the parts of a coupled row: all 1 first."""
yield (1.0,) * n
for rest in itertools.product((1.0, 0.5, 0.75, 0.25, 0.6, 0.4), repeat=n - 1):
if any(value != 1.0 for value in rest):
yield (1.0,) + rest
def _cancelled_sites(normalized, weights) -> int:
"""Sites that some part reaches and where the weighted sum vanishes
(below 1e-3 of the largest moment)."""
total = np.sum([w * piece for w, piece in zip(weights, normalized)], axis=0)
norms = np.linalg.norm(total, axis=2)
reached = np.any([np.linalg.norm(piece, axis=2) > 1e-6 for piece in normalized], axis=0)
largest = max(float(norms.max()), 1e-300)
return int(np.count_nonzero(reached & (norms < 1e-3 * largest)))
def _default_weights(normalized):
"""The first weight set (all 1 first) under which no site that a part
reaches has a vanishing moment, and the reason when it is not all 1."""
n = len(normalized)
first = None
for weights in _weight_candidates(n):
cancelled = _cancelled_sites(normalized, weights)
if first is None:
first = cancelled
if cancelled == 0:
if weights == (1.0,) * n:
return list(weights), None
ones = " : ".join("1" for _ in range(n))
return list(weights), f"{ones} would cancel the moments on {first} sites"
return [1.0] * n, None
def _block_diagonal(blocks):
size = sum(block.shape[0] for block in blocks)
out = np.zeros((size, size))
start = 0
for block in blocks:
n = block.shape[0]
out[start:start + n, start:start + n] = block
start += n
return out
def _classify(arrangement, vibrations, cell_matrix, field, site_indices, lattice, positions,
numbers, symprec, grid=48):
"""The group, responses, collinear class and check of one arrangement,
all from the written cell (``cell_matrix``, rows in primitive units)
and the written moments (``arrangement.magmoms``; ``field`` the same
moments by cell and site)."""
from .magnetic_group import classify_collinear, macroscopic_responses, magnetic_space_group
# the structure in the cell of its translations without time reversal
# (the magnetic cell of the arrangement, at most the common cell): spglib
# names the group there faster, and it fails to name some groups in
# supercells of monoclinic and orthorhombic cells; the common magnetic
# cell is the fallback
group = None
reduced = _unitary_cell(lattice, positions, numbers, arrangement.magmoms,
arrangement.fixing_translations, grid=grid)
cells = ([reduced] if reduced is not None else []) + [
(lattice, positions, numbers, arrangement.magmoms)]
for candidate in cells:
try:
found = magnetic_space_group(*candidate, symprec=symprec,
mag_symprec=MOMENT_TOLERANCE)
except SystemExit:
found = None
if found is not None and (group is None or found.identified):
group = found
if group is not None and group.identified:
break
arrangement.group = group
if group is not None and getattr(group, "identified", False):
arrangement.responses = macroscopic_responses(group)
try:
arrangement.collinear = classify_collinear(
vibrations.rotations, vibrations.translations,
vibrations.primitive_cell.scaled_positions, site_indices, cell_matrix,
field, np.asarray(vibrations.primitive_cell.cell, dtype=float),
symprec=vibrations.symprec)
except Exception:
arrangement.collinear = None
arrangement.check, arrangement.note = _verdict(arrangement.row.bns_number, group)
def _unitary_cell(lattice, positions, numbers, magmoms, translations, grid=48):
"""The structure in the cell of its translations without time reversal,
or None (:func:`crystod.magnetic_group.unitary_cell` with the moment
tolerance of the written moments, ``MOMENT_TOLERANCE``)."""
from .magnetic_group import unitary_cell
return unitary_cell(lattice, positions, numbers, magmoms, translations, grid=grid,
moment_tolerance=MOMENT_TOLERANCE)
def _name_files(analysis: MagneticIrrepAnalysis) -> None:
"""VESTA names: POSCAR_<formula>_spin_[<elements>_]<IR1>_<IR2>_<NN>_<BNS>[_<copies>][_conv].vesta."""
from .cli.common import file_name_tag
width = max(2, len(str(len(analysis.rows))))
elements = "" if len(analysis.elements) == 1 else "-".join(analysis.elements) + "_"
irreps = "_".join(file_name_tag(label) for label in analysis.irreps)
for arrangement in analysis.arrangements:
stem = (f"POSCAR_{analysis.formula}_spin_{elements}{irreps}_"
f"{arrangement.number:0{width}d}_{arrangement.row.bns_number}")
if analysis.order_parameter_input is not None:
stem = (f"POSCAR_{analysis.formula}_spin_{elements}{irreps}_op_"
f"{arrangement.row.bns_number}")
if arrangement.tag:
stem += f"_{arrangement.tag}"
arrangement.vesta_name = stem + _conv_suffix(analysis) + ".vesta"
def _conv_suffix(analysis: MagneticIrrepAnalysis) -> str:
"""``"_conv"`` for a conventional written cell, as the ``--qpoint`` names."""
return "_conv" if analysis.conventional_centring is not None else ""
def _order_parameter_target(analyzer, parent, labels, records, tokens):
"""``(row, eta, stratum)`` of an ``--order-parameter`` vector: the row of
its exact stabilizer as ``--parent --irrep ... --order-parameter``
builds it, the vector in the basis of the table, and the number of the
table row whose stratum (G1'-orbit of directions) holds it (None when no
row does: an irrep with a zero part, not a row of the coupled table)."""
from .isotropy_subgroup import _projector, _rep_cache
from .magnetic_isotropy_coupled import _order_parameter
tokens = [str(token).strip() for token in tokens]
try:
with contextlib.redirect_stdout(io.StringIO()):
record = _order_parameter(parent, list(labels), tokens, None)
eta = np.asarray(analyzer.resolve_direction(tokens), dtype=float)
except SystemExit as exc:
raise ValueError(str(exc).removeprefix("ERROR: ")) from None
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]
]
projector = _projector(analyzer.fixed_space(members))
representative = analyzer.canonical_projector(projector)
stratum = None
for number, (_, _, row_projector) in enumerate(records, start=1):
if row_projector.shape == representative.shape and np.allclose(
row_projector, representative, atol=1e-6):
stratum = number
break
return record.row, eta, stratum
def report_file_name(analysis: MagneticIrrepAnalysis) -> str:
"""``samm_<formula>_<elements>_<IR1>[_<IR2>...][_conv]`` (``file_name_tag``
rules; ``--classify-only`` and ``--order-parameter`` append ``_classify``
and ``_op`` after ``_conv``)."""
from .cli.common import file_name_tag
return (f"samm_{analysis.formula}_{'-'.join(analysis.elements)}_"
+ "_".join(file_name_tag(label) for label in analysis.irreps)
+ _conv_suffix(analysis))
def supercell_poscar_name(analysis: MagneticIrrepAnalysis, poscar_path: str) -> str:
"""``S<basename of the POSCAR>_<IR1>[_<IR2>...][_conv]``."""
import os
from .cli.common import file_name_tag
return (f"S{os.path.basename(poscar_path)}_"
+ "_".join(file_name_tag(label) for label in analysis.irreps)
+ _conv_suffix(analysis))
# --------------------------------------------------------------------- report
def _row_check_text(analysis: MagneticIrrepAnalysis, number: int) -> str:
"""The check column of one table row (all its copy choices)."""
own = [a for a in analysis.arrangements if a.number == number]
if not own:
return "-"
texts = {a.check_text for a in own}
if len(texts) == 1:
text = texts.pop()
return text if len(own) == 1 else f"{text} (x{len(own)})"
return "; ".join(f"{a.tag}: {a.check_text}" for a in own)
def format_table(analysis: MagneticIrrepAnalysis) -> list[str]:
"""The table of the exported rows: the columns of ``crystod-mag --parent``
after a row number, and the group spglib finds on every arrangement."""
rows = analysis.rows
numbers = list(range(1, len(rows) + 1))
width = max([20] + [len(row.label) + 1 for row in rows])
group_width = max([18] + [len(row.subgroup) + 1 for row in rows])
lines = [f"{'No.':<4} {'irrep':<{width}} {'subgroup':<{group_width}} {'size':<5} "
f"{'index':<5} structure"]
for number, row in zip(numbers, rows):
lines.append(f"{number:<4} {row.label:<{width}} {row.subgroup:<{group_width}} "
f"{row.size:<5} {row.index:<5} {_row_check_text(analysis, number)}")
return lines
def _print_notes(analysis: MagneticIrrepAnalysis, algebra_symbol: str) -> None:
"""The notes of ``--parent`` under the tables, then the check column."""
from .magnetic_isotropy_coupled import CoupledMagneticIsotropySubgroups
from .magnetic_isotropy_coupled import _print_notes as coupled_notes
every = [row for rows in analysis.singles.values() for row in rows] + list(analysis.rows)
result = CoupledMagneticIsotropySubgroups(
parent=algebra_symbol, parent_number=analysis.space_group_number,
irreps=list(analysis.irreps), parities=[-1] * len(analysis.irreps),
dimensions=list(analysis.dimensions), singles=analysis.singles, coupled=analysis.rows)
coupled_notes(result, every)
print()
print("The components of a direction refer to the irrep basis of the table (as with")
print("--parent), not to the axes of the POSCAR; the spin listings give the moments.")
print()
print("structure = the BNS group spglib finds on the arrangement exported for the row")
if analysis.conventional_centring is not None:
print("(conventional cell as written, all atoms, moments), compared with the table:")
print("same, enantiomorph (the partner type), different; (xN) for N choices of copies.")
return
print("(magnetic cell, all atoms, moments), compared with the table: same, enantiomorph")
print("(the partner type), different; (xN) for N choices of copies.")
def _magmom_lines(analysis: MagneticIrrepAnalysis, arrangement: MagneticArrangement,
fmt: str) -> None:
from .spin_basis import _print_qe_noncollinear
symbols = analysis.supercell_symbols
sizes = analysis.supercell_sizes.tolist()
note = "" if analysis.n_cells == 1 else f" ({sizes} magnetic supercell)"
if analysis.conventional_centring is not None:
m = analysis.conventional_multiples
note = f" (conventional cell, {m[0]}x{m[1]}x{m[2]} cells)"
print(f" spin directions (magnetic atoms, numbered as in the MAGMOM line){note}:")
parts = []
for atom, site in enumerate(analysis.supercell_site_of_atom):
s = arrangement.magmoms[atom]
text = "0 0 0" if site is None else f"{s[0]:.4f} {s[1]:.4f} {s[2]:.4f}"
parts.append(text)
if site is not None:
print(f" {symbols[atom]}{atom + 1}: [{text.replace(' ', ', ')}]")
if fmt == "qe":
for element in analysis.elements:
spins = [np.asarray(s) if symbols[a] == element else np.zeros(3)
for a, s in enumerate(arrangement.magmoms)]
_print_qe_noncollinear(symbols, spins, element)
else:
print(f" MAGMOM = {' '.join(parts)}")
def _format_value(value: float) -> str:
text = f"{value:.4f}".rstrip("0").rstrip(".")
return "0" if text in ("-0", "") else text
def _number_text(value: float) -> str:
"""A component of the reproduce line: 6 significant digits."""
if abs(value) < 5e-13:
return "0"
text = f"{value:.6g}"
return "0" if text in ("-0", "0") else text
def _reproduce_text(analysis: MagneticIrrepAnalysis, arrangement: MagneticArrangement) -> str:
"""The options that rebuild the arrangement through --order-parameter."""
vector = " ".join(_number_text(v) for v in arrangement.reproduce)
text = f'--order-parameter "{vector}"'
if any(len(analysis.copies[label]) > 1 for label in analysis.irreps):
text += " --copies " + " ".join(str(copy.number) for copy in arrangement.copies)
if analysis.conventional_centring is not None:
text += " --conventional"
return text
def print_arrangement(analysis: MagneticIrrepAnalysis, arrangement: MagneticArrangement,
fmt: str = "vasp") -> None:
"""The block of one exported arrangement."""
from .magnetic_group import (
format_magnetic_group,
format_magnetic_point_group,
format_unified_symbols,
unconfirmed_note,
)
row = arrangement.row
tag = f" {arrangement.tag}" if arrangement.tag else ""
title = f"{arrangement.number}{tag}"
if analysis.order_parameter_input is not None:
title = f"order parameter{tag}"
print(f"\n* {title}: {row.label} -> {row.subgroup} *")
if analysis.order_parameter_input is not None:
vector = ", ".join(_format_value(v) for v in arrangement.order_parameter)
given = " ".join(analysis.order_parameter_input)
letters_note = (" (letters: generic distinct values)"
if re.search(r"[a-z]", given) else "")
print(f" order parameter vector: ({vector}){letters_note}")
if analysis.stratum is not None:
print(f" stratum: row {analysis.stratum} of the table "
f"({analysis.rows[analysis.stratum - 1].label})")
else:
print(" stratum: not a row of the "
+ ("coupled table (an irrep has a zero part)" if len(analysis.irreps) > 1
else "table"))
if len(analysis.irreps) > 1 or any(len(analysis.copies[label]) > 1
for label in analysis.irreps):
print(" copies: " + "; ".join(
f"{copy.irrep} " + (f"c{copy.number} = " if len(analysis.copies[copy.irrep]) > 1
else "") + copy.text
for copy in arrangement.copies))
if arrangement.letters:
pieces = []
components = getattr(row, "components", None) or (row.direction,)
for label, component in zip(analysis.irreps, components):
names = sorted(set(re.findall(r"[a-z]", component)))
values = ", ".join(f"{name} = {_format_value(arrangement.letters[name])}"
for name in names if name in arrangement.letters)
values = values or "0"
pieces.append(f"{label}: {values}" if len(analysis.irreps) > 1 else values)
print(f" order parameter: {'; '.join(pieces)}")
n_free = len(arrangement.letters)
if len(analysis.irreps) > 1 and analysis.order_parameter_input is None:
weights = " : ".join(_format_value(c) for c in arrangement.coefficients)
print(f" parts: {' : '.join(analysis.irreps)} = {weights} (each part scaled to "
"largest moment 1, then weighted)")
if arrangement.weight_reason:
print(f" weights: {arrangement.weight_reason}")
elif analysis.order_parameter_input is not None:
weights = "" if all(c == 1.0 for c in arrangement.coefficients) else (
"; weights " + ", ".join(f"{label} x {_format_value(c)}" for label, c in
zip(analysis.irreps, arrangement.coefficients)))
print(" amplitudes: the components of the vector (unit: the rms moment of one unit")
print(f" component over the sites of its copy){weights}; largest moment then 1")
if n_free > 1 or len(analysis.irreps) > 1:
print(" the relative amplitudes are not fixed by symmetry: other nonzero values that")
print(" keep the pattern of the label (no new zero or equal components) give the")
print(" same group")
print(f" reproduce: {_reproduce_text(analysis, arrangement)}")
print(f" moments: {arrangement.moment_text}")
where = "conventional" if analysis.conventional_centring is not None else "magnetic"
print(f" net moment over the {where} cell: "
f"{(np.round(arrangement.net_moment, 6) + 0.0).tolist()}")
group = arrangement.group
if group is None:
print(" magnetic space group: not identified by spglib")
else:
print(f" magnetic space group: {format_magnetic_group(group)}")
if unconfirmed_note(group):
print(f" {unconfirmed_note(group)}")
print(f" magnetic point group: {format_magnetic_point_group(group)}")
unified = format_unified_symbols(group)
if unified is not None:
print(f" UNI symbol: {unified}")
print(f" check (on the written moments): table {row.bns_number}, structure "
f"{arrangement.check_text}; {arrangement.n_fixing_field} elements of G1'/T_S fix "
f"the moments, {arrangement.n_fixing_order_parameter} the order parameter")
if arrangement.note:
print(f" {arrangement.note}")
if arrangement.responses is not None:
print(f" allowed by symmetry: {arrangement.responses.summary()}")
if arrangement.collinear is not None:
print(f" collinear order: {arrangement.collinear.text()}")
_magmom_lines(analysis, arrangement, fmt)
def write_arrangement_vesta(analysis: MagneticIrrepAnalysis, arrangement: MagneticArrangement,
amplitude: float = 1.5) -> str:
"""Write the VESTA file of one arrangement; returns its name."""
from .phonon_vector import write_vesta_with_arrows
write_vesta_with_arrows(
filepath=arrangement.vesta_name,
lattice=analysis.supercell_lattice,
scaled_positions=analysis.supercell_positions,
symbols=analysis.supercell_symbols,
arrows_cartesian=arrangement.magmoms * amplitude,
title=f"{analysis.formula} {arrangement.row.label} {arrangement.row.bns_number}",
)
return arrangement.vesta_name
def write_supercell(analysis: MagneticIrrepAnalysis, path: str, poscar_path: str) -> None:
"""The magnetic cell as a VASP 5 POSCAR, atom order of the MAGMOM lines."""
import os
from itertools import groupby
from .vasp_io import format_poscar
species, counts = [], []
for symbol, run in groupby(analysis.supercell_symbols):
species.append(str(symbol))
counts.append(len(list(run)))
sizes = analysis.supercell_sizes
cells = f"{sizes[0]}x{sizes[1]}x{sizes[2]} primitive cells"
if analysis.conventional_centring is not None:
m = analysis.conventional_multiples
cells = (f"conventional ({analysis.conventional_centring} centring), "
f"{m[0]}x{m[1]}x{m[2]} cells ({analysis.n_cells} primitive cells)")
comment = (f"{analysis.formula} magnetic cell of {os.path.basename(poscar_path)} for "
f"{' '.join(analysis.irreps)}, {cells} "
"(crystod-mag; atom order of the MAGMOM lines)")
with open(path, "w") as handle:
handle.write(format_poscar(comment, analysis.supercell_lattice, species, counts,
analysis.supercell_positions))
def _component_axes(copy: IrrepCopy):
"""``["z", "x", "y"]`` when every unit component of a copy puts all its
moments along one Cartesian axis, else None."""
axes = []
for j in range(copy.intertwiner.shape[-1]):
moments = copy.intertwiner[..., j].reshape(-1, 3)
moments = moments[np.linalg.norm(moments, axis=1) > 1e-8]
if len(moments) == 0:
return None
used = [axis for axis in range(3) if np.abs(moments[:, axis]).max() > 1e-8]
if len(used) != 1:
return None
axes.append("xyz"[used[0]])
return axes
def print_report(analysis: MagneticIrrepAnalysis, *, symbol: str, positions, part_lines,
classify_only: bool = False, fmt: str = "vasp") -> None:
"""Everything up to the blocks of the arrangements."""
print("\n* Structure *")
print(f" Space group: {analysis.space_group} (#{analysis.space_group_number})")
counts = {e: analysis.site_elements.count(e) for e in analysis.elements}
print(" Magnetic sites: " + ", ".join(f"{e} x {n}" for e, n in counts.items()))
for element in analysis.elements:
k = 0
for site, e in zip(analysis.site_indices, analysis.site_elements):
if e == element:
k += 1
print(f" {element}{k}: {np.round(positions[site], 6).tolist()}")
print(f"\n* Spin (axial-vector) representation of "
f"{', '.join(analysis.elements)} sites at the k points of the irreps *")
shown = set()
for label in analysis.irreps:
kname, q = analysis.kpoints[label]
if kname in shown:
continue
shown.add(kname)
print(f" k point (primitive): {kname} {np.round(q, 6).tolist()}")
for name, text in analysis.decompositions[kname]:
print(f" {name}: {text}" if len(analysis.elements) > 1 else f" {text}")
if kname in analysis.unlabelled_kpoints:
print(f" NOTE: the irreps at {kname} could not be labelled at this tolerance "
"(irrep_N above; the structure is off its ideal positions): the copies come "
"from the irrep matrices alone, and every arrangement is checked on the "
"written moments below. Symmetrize the structure for the labelled "
"decomposition.")
print()
print("* Coupled irreps *" if len(analysis.irreps) > 1 else "* Irrep *")
for line in part_lines:
print(line)
if len(analysis.irreps) > 1:
print(f"coupled order parameter dimension {sum(analysis.dimensions)} "
f"({' + '.join(str(d) for d in analysis.dimensions)})")
print("\n* Copies in the spin representation *")
for label in analysis.irreps:
copies = analysis.copies[label]
listed = ", ".join((f"c{copy.number} = " if len(copies) > 1 else "") + copy.text
for copy in copies)
print(f" {label}: {len(copies)} cop{'y' if len(copies) == 1 else 'ies'}: {listed}")
for label in analysis.irreps:
for copy in analysis.copies[label]:
axes = _component_axes(copy)
if axes is not None:
name = f"{label} c{copy.number}" if len(analysis.copies[label]) > 1 else label
numbers = ", ".join(str(j + 1) for j in range(len(axes)))
word = "component" if len(axes) == 1 else "components"
print(f" {name}: {word} {numbers} = moments along {', '.join(axes)}")
if any(len(analysis.copies[label]) > 1 for label in analysis.irreps):
print(" one arrangement per choice of copies; any mixture of the copies of an irrep")
print(" with the same order parameter has the same magnetic group")
if analysis.copy_note:
print(f" {analysis.copy_note}")
sizes = analysis.supercell_sizes
n_atoms = len(analysis.supercell_symbols)
print("\n* Magnetic cell *")
if analysis.conventional_centring is None:
print(f" Magnetic (commensurate) supercell: {sizes[0]}x{sizes[1]}x{sizes[2]} "
f"({analysis.n_cells} primitive cell{'s' if analysis.n_cells > 1 else ''}, "
f"{n_atoms} atoms), common to every arm of {', '.join(analysis.irreps)}")
else:
n_internal = len(analysis.internal_cell_translations)
m = analysis.conventional_multiples
print(f" Magnetic (commensurate) supercell: {sizes[0]}x{sizes[1]}x{sizes[2]} "
f"({n_internal} primitive cell{'s' if n_internal > 1 else ''}), common to every "
f"arm of {', '.join(analysis.irreps)}: the cell of the spin modes and of the "
"counts over G1'/T_S")
print(f" Display cell: conventional ({analysis.conventional_centring} centring), "
f"{m[0]}x{m[1]}x{m[2]} cells ({analysis.n_cells} primitive "
f"cell{'s' if analysis.n_cells > 1 else ''}, {n_atoms} atoms): the cell of the "
"spin listings, MAGMOM lines, files and the structure check")
if analysis.conventional_note:
print(f" {analysis.conventional_note}")
print(f" spin modes: |O(g) Psi - Psi D(g)| <= "
f"{analysis.residuals['intertwining']:.1e} over the elements of G/T_S, "
f"Psi^T Psi = c 1 within {analysis.residuals['orthonormality']:.1e}")
if analysis.order_parameter_input is None:
print()
if len(analysis.irreps) > 1:
from .magnetic_isotropy_coupled import _print_table
for label, rows in analysis.singles.items():
print(f"* Order parameter directions and isotropy subgroups ({label} alone) *")
_print_table(rows)
print()
print("* Order parameter directions and isotropy subgroups (coupled) *")
else:
print("* Order parameter directions and isotropy subgroups *")
print("\n".join(format_table(analysis)))
_print_notes(analysis, symbol)
if len(analysis.irreps) > 1 and not classify_only:
print()
print("Arrangements are exported for the coupled rows; crystod-mag --irrep "
f"{analysis.irreps[0]} alone exports those of one irrep.")
def run(args) -> MagneticIrrepAnalysis:
"""``crystod-mag -c POSCAR --element EL [...] --irrep IR [...]`` (dispatched
by :mod:`crystod.cli.mag`): prints the report, writes the files."""
from .cli.common import SavedReport
from .isotropy_subgroup import _order_parameter_tokens
from .magnetic_group import ALTERMAGNET_REFERENCE
from .magnetic_isotropy_coupled import _part_line
from .star_of_k import read_poscar_or_exit
from .vibration_modes import SymmetryOnlyVibrations
try:
cell = read_poscar_or_exit(args.cell)
except SystemExit:
raise
except Exception as exc: # noqa: BLE001 - any reader failure is the file's
raise SystemExit(f"ERROR: could not read {args.cell} as a VASP POSCAR "
f"({type(exc).__name__}: {' '.join(str(exc).split())[:200]}); "
"-c takes a POSCAR (primitive cell) in this mode.") from None
tolerance = 1e-5 if args.tolerance is None else float(args.tolerance)
try:
with contextlib.redirect_stdout(io.StringIO()):
vibrations = SymmetryOnlyVibrations(cell=cell, symprec=tolerance, standardize=False)
except SystemExit:
raise
except Exception as exc: # noqa: BLE001
raise SystemExit(f"ERROR: could not analyse the symmetry of {args.cell} "
f"({type(exc).__name__}: {' '.join(str(exc).split())[:200]}).") from None
try:
analysis = magnetic_irrep_arrangements(
elements=list(args.element), irreps=list(args.irrep), symprec=tolerance,
coefficients=args.coefficients, classify=True, vibrations=vibrations,
order_parameter=(None if args.order_parameter is None
else _order_parameter_tokens(args.order_parameter)),
copies=getattr(args, "copies", None),
conventional=bool(getattr(args, "conventional", False)))
except ValueError as exc:
raise SystemExit("ERROR: " + str(exc)) from None
amplitude = 1.5 if args.amplitude is None else float(args.amplitude)
symbol = str(vibrations.spglib_dataset["international"])
with contextlib.redirect_stdout(io.StringIO()):
from .spacegroup_product import SpaceGroupIrrepAlgebra
symbol = str(SpaceGroupIrrepAlgebra(str(analysis.space_group_number))
.sg_type.international_short)
part_lines = [_part_line(part.representation, -1, False) for part in analysis.parts]
part_lines = [line.replace(part.representation.label, part.label, 1)
for line, part in zip(part_lines, analysis.parts)]
enabled = not args.no_files
with SavedReport(enabled=enabled, announce=False) as saved:
print_report(analysis, symbol=symbol,
positions=vibrations.primitive_cell.scaled_positions,
part_lines=part_lines, classify_only=args.classify_only, fmt=args.format)
written = []
if not args.classify_only:
for arrangement in analysis.arrangements:
print_arrangement(analysis, arrangement, args.format)
if enabled:
written.append(write_arrangement_vesta(analysis, arrangement, amplitude))
supercell = None
if enabled and not args.classify_only:
supercell = supercell_poscar_name(analysis, args.cell)
write_supercell(analysis, supercell, args.cell)
saved.name = (report_file_name(analysis) + ("_classify" if args.classify_only else "")
+ ("_op" if analysis.order_parameter_input is not None else ""))
if written or supercell or saved.active:
print("\n* Output files *")
for name in written:
print(f" Spin arrangement written to: {name}")
if supercell:
order_of = "spin listings" if args.format == "qe" else "MAGMOM lines"
print(f" Supercell POSCAR written to: {supercell} (atom order of the {order_of})")
if saved.active:
print(saved.line())
print()
print("Reference: H. T. Stokes, D. M. Hatch and B. J. Campbell, ISOTROPY Software Suite,")
print("https://iso.byu.edu (magnetic isotropy subgroups); M.-T. Suzuki et al., PRB 95,")
print("094406 (2017) (cluster multipoles).")
print(f"Reference (collinear classes): {ALTERMAGNET_REFERENCE}.")
return analysis