Source code for crystod.spin_basis

"""
Symmetry-adapted spin (magnetic) basis workflow for crystod.

Treats the spins on the sites of a selected element as axial-vector degrees
of freedom, decomposes them into irreps of the space group at a q-point by
projection (SALC), separates ferromagnetic (net-moment) from
antiferromagnetic (net-zero) combinations, assigns cluster-multipole ranks
(dipole, octupole, ...), and exports each basis vector as a VESTA file with
spin arrows.

The method follows the cluster multipole / symmetry-adapted multipole moment
(SAMM) framework of M.-T. Suzuki et al., Phys. Rev. B 95, 094406 (2017) and
Phys. Rev. B 99, 174407 (2019).
"""

from __future__ import annotations

from argparse import (
    ArgumentDefaultsHelpFormatter,
    ArgumentParser,
    RawDescriptionHelpFormatter,
    RawTextHelpFormatter,
)
import contextlib
import io
import os
import re
import sys
import warnings
from dataclasses import dataclass, field as dataclass_field
from fractions import Fraction

import numpy as np
from numpy.typing import NDArray

from .spglib_compat import ensure_spglib_compat

ensure_spglib_compat()

from .runtime_compat import get_spacegroup_irreps_from_primitive_symmetry
from spgrep.representation import project_to_irrep

from .phonon_vector import _find_intertwiner, reduced_formula, write_vesta_with_arrows
from .vibration_modes import SymmetryOnlyVibrations


class MyHelpFormatter(
    RawTextHelpFormatter,
    RawDescriptionHelpFormatter,
    ArgumentDefaultsHelpFormatter,
):
    pass


desc = """
Construct symmetry-adapted spin bases (cluster multipoles / SAMM) for the
sites of a selected element: the 3N-dimensional axial-vector (spin) space is
decomposed into space-group irreps at a q-point, ferromagnetic (dipole) and
antiferromagnetic (net moment = 0) combinations are separated, and each basis
vector is exported as a VESTA file with spin arrows.

# Command Examples:
crystod-mag -c 221_PPOSCAR_AlNi3 --element Ni --qpoint 0 0 0
crystod-mag -c 221_PPOSCAR_AlNi3 --element Ni --qpoint GM --format qe
"""

#: Names of the magnetic multipole ranks used in the ``crystod-mag`` output
#: (rank ``p`` -> ``2**p``-pole): ``{1: "dipole", 3: "octupole", ...}``.
MULTIPOLE_NAMES = {
    0: "monopole",
    1: "dipole",
    2: "quadrupole",
    3: "octupole",
    4: "hexadecapole",
    5: "32pole",
    6: "64pole",
}


def build_parser() -> ArgumentParser:
    parser = ArgumentParser(description=desc, formatter_class=MyHelpFormatter)
    parser.add_argument("--poscar", default="POSCAR", help="POSCAR path.")
    parser.add_argument(
        "--element",
        required=True,
        nargs="+",
        help="Magnetic element whose sites carry the spins, e.g. Ni; several elements "
        "(Al Ni) take the direct sum of their spin representations.",
    )
    parser.add_argument(
        "--qpoint",
        nargs="+",
        default=None,
        help="Either a high-symmetry label such as GM/X/M/R or three primitive reciprocal coordinates. "
        "When omitted, the spin-multipole irreps at all special k points are listed (as in --salc).",
    )
    parser.add_argument(
        "--show-spin-direction",
        action="store_true",
        help="Print the spin direction [x, y, z] of every atom for each basis vector "
        "(with a noncollinear magnetization input in the selected --format).",
    )
    parser.add_argument(
        "--format",
        choices=["vasp", "qe"],
        default="vasp",
        help="Format of the noncollinear magnetization input printed with "
        "--show-spin-direction: vasp = MAGMOM line, qe = Quantum ESPRESSO "
        "starting_magnetization/angle1/angle2 (&SYSTEM).",
    )
    parser.add_argument(
        "--amplitude",
        type=float,
        default=1.5,
        help="Arrow length in Angstroms given to the largest spin of each basis vector.",
    )
    parser.add_argument(
        "--tolerance",
        type=float,
        default=1e-5,
        help="Symmetry tolerance, a distance in Angstrom (spglib and site matching).",
    )
    parser.add_argument(
        "--conventional",
        action="store_true",
        help="Export the spin structures in the conventional cell instead of the "
        "primitive cell (primitive-to-conventional matrix from the detected "
        "centring, as in crystod-phonon --vector).",
    )
    parser.add_argument(
        "--classify-only",
        action="store_true",
        help="Print the structure, the decomposition and the table of magnetic "
        "groups and collinear classes only (no VESTA files, no spin listings, "
        "no SPOSCAR; the printed report is saved as "
        "samm_<formula>_<element>_<q>_classify).",
    )
    parser.add_argument(
        "--no-files",
        dest="no_files",
        action="store_true",
        help="Survey and --classify-only: print only, without saving the report "
        "(samm_<formula>_<element>_survey, samm_<formula>_<element>_<q>_classify).",
    )
    parser.add_argument(
        "--show-operations",
        action="store_true",
        help="List, for every component, the operations of the paramagnetic group "
        "(G + theta G) that the arrangement keeps and those it breaks, as Seitz "
        "symbols {R|t} and {R|t}' = theta{R|t}.",
    )
    parser.add_argument(
        "--subgroup-poscar",
        dest="subgroup_poscar",
        default=None,
        metavar="CHILD",
        help="A low-symmetry structure of the same compound whose cell is a magnetic "
        "cell of q (q != 0): the bases placed on it and aligned with its structural "
        "domain (the transformation of crystod-group --correlate).",
    )
    parser.add_argument(
        "--phonon-angular-momentum",
        dest="phonon_angular_momentum",
        action="store_true",
        help="The phonon angular momentum texture l(q) near GM that the magnetic point "
        "group of every component allows (lowest-degree q-polynomial of each Cartesian "
        "component, its wave letter and enforced nodal planes); with --classify-only, "
        "a table with the paramagnetic crystal in the first row.",
    )
    parser.add_argument(
        "--superpose",
        nargs="+",
        type=int,
        default=None,
        metavar="N",
        help="Superpose listed bases by their numbers (the rows of the table of magnetic "
        "groups, counted from 1; printed as [N] with several elements), of any irreps "
        "and elements, with the coefficients of --coefficients.",
    )
    parser.add_argument(
        "--coefficients",
        nargs="+",
        type=float,
        default=None,
        metavar="C",
        help="Coefficients of the bases of --superpose (default 1 each).",
    )
    return parser


def _parse_coordinate(value: str) -> float:
    try:
        return float(Fraction(value))
    except ValueError:
        return float(value)


# ---------------------------------------------------------------------------
# Axial-vector (spin) representation on the selected sites
# ---------------------------------------------------------------------------

#: Fractional tolerance of the site matching before ``--tolerance`` was
#: threaded into it; a site within it still matches whatever the tolerance.
_SITE_MATCH_FRACTIONAL = 1e-5


def _match_site(transformed, candidates, lattice, tolerance: float) -> int | None:
    """Index into ``candidates`` of the site that ``transformed`` lands on, or None.

    The site nearest to ``transformed`` modulo lattice translations
    (Cartesian distance, the metric of spglib's ``symprec``), accepted when
    it lies within ``tolerance`` Angstrom of it or, as before ``--tolerance``
    reached the site matching, within ``_SITE_MATCH_FRACTIONAL`` in every
    fractional coordinate.
    """
    diff = np.asarray(candidates, dtype=float) - np.asarray(transformed, dtype=float)[None, :]
    residual = diff - np.rint(diff)
    distances = np.linalg.norm(residual @ np.asarray(lattice, dtype=float), axis=1)
    nearest = int(np.argmin(distances))
    if distances[nearest] <= tolerance or (
        np.abs(residual[nearest]) < _SITE_MATCH_FRACTIONAL
    ).all():
        return nearest
    return None


def _symmetrized_site_positions(vibrations: SymmetryOnlyVibrations, site_indices: list[int],
                                symprec: float | None = None) -> NDArray[np.float64]:
    """Fractional positions of the selected sites, symmetrized by the space group.

    Each site is replaced by the average of its preimages under all the
    operations (``x_a - mean_g R^-1 eps_g``, ``eps_g`` the mismatch of the
    image of site a on its matched site), the structure that the operations
    map exactly onto itself. The Bloch phases of the spin representation and
    the lattice gauge are built from these positions, so a structure within
    ``--tolerance`` of its ideal positions gives the representation, bases
    and spin fields of the ideal structure. The input positions are returned
    unchanged when the operations already map them onto each other (every
    mismatch below 1e-10) or when a site has no image within the tolerance.
    """
    positions = np.asarray(vibrations.primitive_cell.scaled_positions, dtype=float)[site_indices]
    lattice = np.asarray(vibrations.primitive_cell.cell, dtype=float)
    if symprec is None:
        symprec = float(getattr(vibrations, "symprec", 1e-5))
    shifts = np.zeros_like(positions)
    off_ideal = False
    rotations = np.asarray(vibrations.rotations)
    translations = np.asarray(vibrations.translations, dtype=float)
    for rotation, translation in zip(rotations, translations):
        inverse = np.linalg.inv(rotation)
        for a, position in enumerate(positions):
            transformed = rotation @ position + translation
            b = _match_site(transformed, positions, lattice, symprec)
            if b is None:
                return positions
            mismatch = transformed - positions[b]
            mismatch = mismatch - np.rint(mismatch)
            off_ideal = off_ideal or bool(np.abs(mismatch).max() > 1e-10)
            shifts[a] += inverse @ mismatch
    if not off_ideal:
        return positions
    return positions - shifts / len(rotations)


[docs] def get_spin_representation( vibrations: SymmetryOnlyVibrations, site_indices: list[int], qpoint: list[float], *, symprec: float | None = None, ): """Irreps and the axial-vector (spin) representation on selected sites at q. This is the first step of ``crystod-mag`` (at the ``--qpoint`` given, or at every special k point in survey mode): the spins of the ``site_indices`` atoms of the primitive cell are treated as axial vectors, and the little group of ``qpoint`` acts on the 3N-dimensional spin space by the same construction as the vibration (polar-vector) representation of ``crystod-phonon``, with the Cartesian rotation ``R`` replaced by ``det(R) * R`` and the site permutation restricted to the selected sites. The Bloch-phase convention is that of spgrep, so the returned matrices can be projected onto the returned irreps directly with ``spgrep.representation.project_to_irrep``. Args: vibrations: Symmetry container of the primitive cell (``crystod.phonon.SymmetryOnlyVibrations``); its ``rotations``, ``translations`` and ``primitive_cell`` define the space group. site_indices: Indices (into ``vibrations.primitive_cell``) of the N atoms that carry a spin, e.g. every atom of the magnetic element. qpoint: The q point in primitive reciprocal coordinates, e.g. ``[0, 0, 0]`` or ``[0.5, 0.5, 0.5]``. symprec: Distance tolerance (Angstrom) within which an operation must map a site onto a site; None (default) takes the tolerance the space group was found with (``vibrations.symprec``, the ``--tolerance`` of ``crystod-mag``), so that every operation spglib accepts permutes the sites. Sites within 1e-5 in every fractional coordinate always match. The Bloch phases are built from the site positions symmetrized by the space group, so a structure off its ideal positions within the tolerance gives the representation of the ideal structure (for a structure at its ideal positions they are the input positions). Returns: tuple: ``(irreps, spin_rep, mapping)``. ``irreps`` is the list of spgrep irreps of the little group at ``qpoint`` (each an array of shape ``(order, dim, dim)``); ``spin_rep`` is the complex array of shape ``(order, 3N, 3N)`` holding the spin-representation matrix of every little-group operation, in the order of the irrep matrices; ``mapping`` is the integer array that indexes those operations in ``vibrations.rotations`` (what ``get_irrep_labels`` and ``get_multipole_rank_lists`` expect). Example: >>> from phonopy.interface.vasp import read_vasp >>> from crystod import mag, phonon >>> from crystod.examples import example_path >>> cell = read_vasp(example_path("221_PPOSCAR_SrTiO3")) >>> vib = phonon.SymmetryOnlyVibrations(cell, standardize=False) >>> symbols = vib.primitive_cell.symbols >>> sites = [i for i, s in enumerate(symbols) if s == "O"] # 3 sites >>> q = [0, 0, 0] >>> irreps, spin_rep, mapping = mag.get_spin_representation(vib, sites, q) >>> spin_rep.shape (48, 9, 9) >>> vib.get_irrep_labels(q, irreps, mapping)[6] 'GM4+(3)' """ positions = vibrations.primitive_cell.scaled_positions lattice = np.asarray(vibrations.primitive_cell.cell, dtype=float) if symprec is None: symprec = float(getattr(vibrations, "symprec", 1e-5)) irreps, mapping = get_spacegroup_irreps_from_primitive_symmetry( rotations=vibrations.rotations, translations=vibrations.translations, kpoint=qpoint, ) little_rotations = vibrations.rotations[mapping] little_translations = vibrations.translations[mapping] n_sites = len(site_indices) site_positions = np.asarray(positions, dtype=float)[site_indices] # the Bloch phases from the symmetrized positions (the input positions # for a structure at its ideal positions) ideal = _symmetrized_site_positions(vibrations, site_indices, symprec) representation = [] for rotation, translation in zip(little_rotations, little_translations): permutation = np.zeros((n_sites, n_sites), dtype=complex) for a, index_a in enumerate(site_indices): transformed = rotation @ positions[index_a] + translation b = _match_site(transformed, site_positions, lattice, symprec) if b is None: continue phase = np.dot( qpoint, np.dot(np.linalg.inv(rotation), ideal[b] - translation) - ideal[b], ) permutation[b, a] = np.exp(2j * np.pi * phase) representation.append(permutation) # Cartesian axial part per little-group operation lattice_t = np.transpose(vibrations.primitive_cell.cell) lattice_t_inv = np.linalg.inv(lattice_t) spin_rep = [] for op_index, rotation in enumerate(little_rotations): cartesian = lattice_t @ rotation @ lattice_t_inv axial = np.linalg.det(cartesian) * cartesian spin_rep.append(np.kron(representation[op_index], axial)) return irreps, np.array(spin_rep, dtype=complex), mapping
# --------------------------------------------------------------------------- # Magnetic multipole ranks per irrep (Suzuki PRB 95, Table III logic) # ---------------------------------------------------------------------------
[docs] def get_multipole_rank_lists( vibrations: SymmetryOnlyVibrations, little_rotations: NDArray[np.int_], irreps, max_rank: int = 9, ) -> list[list[int]]: """Ranks at which each irrep occurs in the magnetic multipole representations. ``crystod-mag`` uses these lists at q = 0 to name the symmetry-adapted spin bases: the spaces of an irrep are named in the order of the ranks in its list, so the ferromagnetic combination (cluster dipole, rank 1) comes first and the antiferromagnetic ones follow as octupole, ... (the logic of Table III of M.-T. Suzuki et al., Phys. Rev. B 95, 094406). The rank-``p`` magnetic (time-odd, axial) multipole transforms as the angular-momentum- ``p`` representation with parity ``(-1)**(p + 1)`` under inversion: the dipole (``p = 1``) and octupole (``p = 3``) are parity-even, the magnetic quadrupole (``p = 2``) is parity-odd, and so on. The multiplicity of every irrep is obtained by character orthogonality against the rotation characters ``sin((p + 1/2) theta) / sin(theta / 2)`` of the proper part of every little-group operation. Args: vibrations: Symmetry container of the primitive cell (``crystod.phonon.SymmetryOnlyVibrations``); its lattice converts the integer rotations to Cartesian form. little_rotations: Integer rotation matrices of the little-group operations, in the order of the irrep matrices: normally ``vibrations.rotations[mapping]`` with the ``mapping`` returned by ``get_spin_representation``. irreps: The spgrep irreps of the little group, as returned by ``get_spin_representation``. max_rank: Highest rank ``p`` included in the search. Returns: One list per irrep (same order as ``irreps``), holding the ranks ``1 <= p <= max_rank`` at which the irrep appears in the rank-``p`` magnetic multipole representation, in increasing order and repeated according to the multiplicity. ``MULTIPOLE_NAMES`` translates ranks to names. Example: >>> # vib, sites, q: see get_spin_representation (O sites of SrTiO3) >>> irreps, spin_rep, mapping = mag.get_spin_representation(vib, sites, q) >>> labels = vib.get_irrep_labels(q, irreps, mapping) >>> rotations = vib.rotations[mapping] >>> ranks = mag.get_multipole_rank_lists(vib, rotations, irreps) >>> dict(zip(labels, ranks))["GM4+(3)"] [1, 3, 5, 5, 7, 7, 9, 9, 9] """ from .runtime_compat import get_character lattice_t = np.transpose(vibrations.primitive_cell.cell) lattice_t_inv = np.linalg.inv(lattice_t) operations = [lattice_t @ rotation @ lattice_t_inv for rotation in little_rotations] characters = [np.array(get_character(irrep), dtype=complex) for irrep in irreps] order = len(operations) rank_lists: list[list[int]] = [[] for _ in irreps] for p in range(1, max_rank + 1): chi_p = [] for operation in operations: 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)) if theta < 1e-8: base = 2 * p + 1 else: base = np.sin((p + 0.5) * theta) / np.sin(theta / 2.0) parity = ((-1) ** (p + 1)) if determinant < 0 else 1 chi_p.append(parity * base) chi_p = np.array(chi_p) for index, character in enumerate(characters): count = int(round(float(np.real(np.dot(chi_p, np.conj(character)))) / order)) rank_lists[index].extend([p] * max(count, 0)) return rank_lists
# --------------------------------------------------------------------------- # Basis post-processing # --------------------------------------------------------------------------- def _realify(space: NDArray[np.complex128]) -> NDArray[np.float64] | None: """Return a real orthonormal basis of the row space, or None when the space is genuinely complex. First each row is rotated by a global phase. When that fails (e.g. the circular-basis partners (x + iy, x - iy) of a 2-dim irrep), the rows are recombined unitarily: Gram-Schmidt over the real and imaginary parts gives a real basis whenever the space is closed under complex conjugation. Collapsing such a space with np.real instead would fold both partners onto the same vector and lose a dimension. """ rows = [] for row in space: pivot = row[np.argmax(np.abs(row))] aligned = row * np.exp(-1j * np.angle(pivot)) if np.abs(aligned.imag).max() > 1e-8: rows = None break rows.append(aligned.real) if rows is not None: return np.array(rows) dim = space.shape[0] basis: list[NDArray[np.float64]] = [] for row in space: for part in (np.real(row), np.imag(row)): residual = np.array(part, dtype=float) for vector in basis: residual -= np.dot(vector, residual) * vector norm = np.linalg.norm(residual) if norm > 1e-6: basis.append(residual / norm) if len(basis) == dim: break if len(basis) == dim: break if len(basis) < dim: return None candidate = np.array(basis) # the real basis must span the same complex space (closure under conjugation) projection = space @ candidate.T @ candidate if np.abs(projection - np.asarray(space)).max() > 1e-6: return None return candidate def _net_moments(space: NDArray[np.float64], n_sites: int) -> NDArray[np.float64]: return np.array( [np.sum(space[c].reshape(n_sites, 3), axis=0) for c in range(space.shape[0])] )
[docs] def separate_ferro_combination( spaces: list[NDArray[np.float64]], representation: NDArray[np.complex128], n_sites: int, realify_aligned: bool = True, ) -> tuple[NDArray[np.float64] | None, list[NDArray[np.float64]]]: """Split the ferromagnetic combination off the spaces of one irrep. At q = 0 an irrep can occur several times in the spin representation (``2 x GM4+`` for the three Ni sites of AlNi3); ``crystod-mag`` calls this function once per irrep label with all of its projected spaces. The spaces are first aligned to a common partner basis (an intertwiner with ``representation`` is found for every space, and complex circular bases are recombined into real ones), then the net moments ``sum_i S_i`` of the aligned spaces are combined into one unit vector: its unitary completion gives the unique combination that carries a net moment (the cluster dipole, printed as ``FM``) and the orthogonal combinations with ``sum_i S_i = 0`` (``AFM``, net moment zero). ``crystod-mag`` names the AFM combinations by the remaining entries of the irrep's rank list (``get_multipole_rank_lists``): octupole, ... for an irrep even under the inversion, quadrupole, hexadecapole, ... for an odd one (Cr2O3, Cr: GM1- quadrupole, GM2- hexadecapole). When no space carries a net moment, or the completion does not separate cleanly, the aligned spaces are returned unchanged as antiferromagnetic. Args: spaces: Real basis arrays of shape ``(dim, 3N)`` (one row per partner of the irrep; ``3N`` = three Cartesian components of N spins) that all carry the same irrep, e.g. the output of ``spgrep.representation.project_to_irrep`` for one irrep. representation: The spin-representation matrices of shape ``(order, 3N, 3N)`` returned by ``get_spin_representation``; used to align the spaces to a common basis. n_sites: The number N of spin-carrying sites. realify_aligned: Rotate every aligned row by its own phase to make it real (needed for complex spaces). Pass False for spaces that are already real and transform with one set of real matrices, where a per-row phase would flip the sign of single partners. Returns: tuple: ``(ferro, afm)``. ``ferro`` is the basis array of shape ``(dim, 3N)`` with a net moment (``None`` when no combination has one) and ``afm`` is the list of the remaining net-zero basis arrays; together they span the same space as the input. Example: >>> # spin_rep, irreps, sites: see get_spin_representation (SrTiO3, O) >>> import numpy as np >>> from spgrep.representation import project_to_irrep >>> gm4p = irreps[6] # GM4+, twice >>> spaces = [np.real(s) for s in project_to_irrep(spin_rep, gm4p)] >>> ferro, afm = mag.separate_ferro_combination(spaces, spin_rep, 3) >>> ferro.shape, len(afm) ((3, 9), 1) >>> bool(np.abs(afm[0].reshape(3, 3, 3).sum(axis=1)).max() < 1e-8) True """ if len(spaces) == 1: nets = _net_moments(spaces[0], n_sites) if np.abs(nets).max() < 1e-8: return None, [spaces[0]] return spaces[0], [] aligned = [spaces[0]] for space in spaces[1:]: intertwiner = _find_intertwiner(representation, space, spaces[0]) if intertwiner is None: aligned.append(space) elif not realify_aligned: aligned.append(np.real(intertwiner.conj().T @ space)) else: realified = _realify(intertwiner.conj().T @ space) aligned.append(realified if realified is not None else space) # net-moment magnitude of each space (same per component after alignment) net_vectors = np.array([_net_moments(space, n_sites)[0] for space in aligned]) norms = np.linalg.norm(net_vectors, axis=1) if norms.max() < 1e-8: return None, aligned reference = net_vectors[np.argmax(norms)] / norms.max() coefficients = net_vectors @ reference # signed magnitudes coefficients = coefficients / np.linalg.norm(coefficients) # unitary completion: first row = FM combination, others = AFM matrix = np.eye(len(aligned)) matrix[0] = coefficients q_matrix, _ = np.linalg.qr(matrix.T) q_matrix = q_matrix.T if np.dot(q_matrix[0], coefficients) < 0: q_matrix[0] *= -1 combos = [ np.array([sum(q_matrix[m, a] * aligned[a][c] for a in range(len(aligned))) for c in range(aligned[0].shape[0])]) for m in range(len(aligned)) ] ferro = combos[0] afm = [] for combo in combos[1:]: if np.abs(_net_moments(combo, n_sites)).max() > 1e-6: # could not cleanly separate; keep as-is return None, aligned afm.append(combo) return ferro, afm
def _direction_tag(space_component: NDArray[np.float64], n_sites: int) -> tuple[str, float] | None: """(tag, sign) with an x/y/z/111-style tag when all spins of the component are collinear; sign canonicalizes the basis vector so that the common axis has its first nonzero Cartesian component positive.""" vectors = space_component.reshape(n_sites, 3) norms = np.linalg.norm(vectors, axis=1) active = vectors[norms > 1e-8] if len(active) == 0: return None axis = active[0] / np.linalg.norm(active[0]) for vector in active[1:]: cross = np.linalg.norm(np.cross(axis, vector / np.linalg.norm(vector))) if cross > 1e-6: return None # canonical sign: first nonzero component of the axis positive sign = 1.0 for value in axis: if abs(value) > 1e-8: if value < 0: sign = -1.0 axis = -axis break tag = _axis_tag(axis) return None if tag is None else (tag, sign) def _axis_tag(axis: NDArray[np.float64]) -> str | None: """``x``, ``y``, ``z`` or the small integer direction (``110``, ``1m10``, ``2m1m1``) of an axis whose first nonzero Cartesian component is positive; None when the direction has no such indices.""" scaled = axis / np.max(np.abs(axis)) integers = [] for value in scaled: fraction = Fraction(float(value)).limit_denominator(6) if abs(float(fraction) - value) > 1e-6: return None integers.append(fraction) denominator = np.lcm.reduce([f.denominator for f in integers]) integers = [int(f * denominator) for f in integers] if integers == [1, 0, 0]: return "x" if integers == [0, 1, 0]: return "y" if integers == [0, 0, 1]: return "z" return "".join(str(v) for v in integers).replace("-", "m") def _tag_axis(tag: str) -> NDArray[np.float64] | None: """The unit Cartesian axis of a direction tag (inverse of :func:`_axis_tag`).""" named = {"x": (1.0, 0.0, 0.0), "y": (0.0, 1.0, 0.0), "z": (0.0, 0.0, 1.0)} if tag in named: return np.array(named[tag]) digits = re.findall(r"m?\d", tag) if len(digits) != 3 or "".join(digits) != tag: return None axis = np.array([-float(d[1:]) if d.startswith("m") else float(d) for d in digits]) return axis / np.linalg.norm(axis) def _singled_out(vector, basis, representation, tolerance: float = 1e-6) -> bool: """True when the symmetry of the arrangement ``vector`` fixes no other direction of the space spanned by ``basis``: the order-parameter direction of ``vector`` is an isotropy direction of its own. The operations g with G(g) v = +-v (with time reversal for -) are the unitary part of the magnetic group of v; v is singled out when the vectors of the space they all fix, s_g G(g) u = u, are the multiples of v. (a,a) of a tetragonal E irrep and (a,a,0) of a cubic T1 irrep of m-3m are; (a,a) of a hexagonal E irrep and (a,a,0) of m-3 or 23 are not (their symmetry fixes the whole (a,b) plane). Args: vector: The arrangement, a vector of the spin space (lattice gauge). basis: The basis vectors of the space (rows). representation: The spin representation of the little group of q in the same gauge, shape ``(order, 3N, 3N)``. tolerance: Of G(g) v = +-v and of the singular values. """ vector = np.asarray(vector, dtype=complex) vector = vector / np.linalg.norm(vector) columns = np.asarray(basis, dtype=complex).T blocks = [] for matrix in representation: image = matrix @ vector for sign in (1.0, -1.0): if np.linalg.norm(sign * image - vector) < tolerance: blocks.append(sign * (matrix @ columns) - columns) break if not blocks: return False singular = np.linalg.svd(np.vstack(blocks), compute_uv=False) return columns.shape[1] - int(np.sum(singular > tolerance)) == 1 def _combined_components(tags: list[str], vectors: list, representation) -> list[tuple[str, NDArray]]: """The equal-weight combinations of the components of one basis that are exported next to them: the (a,a) / (a,a,0) and (a,a,a) directions of the order parameter, where symmetry singles them out (:func:`_singled_out`). A two-dimensional basis gets c1 + c2 (else c1 - c2) when singled out: the (a,a) arrangement of a tetragonal E irrep (Eg of I4/mmm: ``x`` and ``y`` give ``110``; the ``1m10`` and ``110`` partners of P4_2/mnm give ``x``), none of a hexagonal or trigonal one, whose two components are already its two special directions, nor of a complex pair of 4, -4 or 4/m (every in-plane direction has the same symmetry there). A three-dimensional basis gets the first singled-out pair (x + y for an ``x``/``y``/``z`` basis: ``110`` in m-3m, -43m and 432; none in m-3 and 23, where the symmetry of x + y fixes the whole (a,b,0) plane) and the sum of the three (``111``, always for an ``x``/``y``/``z`` basis, else when singled out). A combination is named after the sum of its component directions (the spin direction of a dipole) when the components have direction tags and the sum is not one of them, else in the order-parameter notation over the components in their order: ``aa``, ``a-a``, ``aa0``, ``a0a``, ``0aa``, ``aaa`` (two components along ``z``, or ``comp<N>`` components; the same arrangement in a rotated input cell). Args: tags: The component tags of the basis (``comp<N>`` when untagged). vectors: The sign-canonical component vectors (lattice gauge). representation: The spin representation in the same gauge. Returns: ``(tag, vector)`` pairs, the vectors at unit norm. """ dim = len(tags) if dim not in (2, 3): return [] vectors = [np.asarray(vector) for vector in vectors] xyz = dim == 3 and sorted(tags) == ["x", "y", "z"] order = [tags.index(axis) for axis in "xyz"] if xyz else list(range(dim)) axes = [_tag_axis(tag) for tag in tags] def name(weights: dict[int, float]) -> str: if all(axes[k] is not None for k in weights): axis = sum(weight * axes[k] for k, weight in weights.items()) if np.linalg.norm(axis) > 1e-8: nonzero = axis[np.abs(axis) > 1e-8] tag = _axis_tag(axis if nonzero[0] > 0 else -axis) if tag is not None and tag not in tags: return tag return "".join( "0" if k not in weights else ("a" if weights[k] > 0 else "-a") for k in order ) combined = [] pairs = [(order[0], order[1])] if dim == 2 else [ (order[0], order[1]), (order[0], order[2]), (order[1], order[2]) ] for first, second in pairs: found = None for sign in (1.0, -1.0): vector = (vectors[first] + sign * vectors[second]) / np.sqrt(2) if _singled_out(vector, vectors, representation): found = (name({first: 1.0, second: sign}), vector) break if found is not None: combined.append(found) break if dim == 3: vector = np.sum(vectors, axis=0) / np.sqrt(3) if xyz or _singled_out(vector, vectors, representation): combined.append((name({k: 1.0 for k in range(3)}), vector)) return combined # --------------------------------------------------------------------------- # Main # --------------------------------------------------------------------------- def _print_qe_noncollinear(symbols: list[str], atom_spins: list, element: str) -> None: """Print pw.x noncollinear magnetization lines (&SYSTEM) for one basis vector. Quantum ESPRESSO specifies noncollinear moments per atom TYPE via starting_magnetization / angle1 / angle2, so the magnetic element is split into one type per distinct spin direction and the atom membership of each type is printed as a comment. """ type_keys: list[tuple] = [] type_of_atom: list[int] = [] for symbol, spin in zip(symbols, atom_spins): if symbol == element: key = (symbol, tuple(np.round(spin, 4))) else: key = (symbol,) if key not in type_keys: type_keys.append(key) type_of_atom.append(type_keys.index(key) + 1) labels = [] magnetic_counter = 0 for key in type_keys: if len(key) == 2: magnetic_counter += 1 labels.append(f"{element}{magnetic_counter}") else: labels.append(key[0]) print(" Quantum ESPRESSO noncollinear magnetization (&SYSTEM):") print(" noncolin = .true.") for type_index, key in enumerate(type_keys, start=1): label = labels[type_index - 1] members = [ f"{symbols[i]}{i + 1}" for i, atom_type in enumerate(type_of_atom) if atom_type == type_index ] if len(key) == 1: print(f" ! type {type_index} ({label}): {' '.join(members)} -- non-magnetic") continue spin = np.array(key[1], dtype=float) magnitude = float(np.linalg.norm(spin)) if magnitude < 1e-8: theta = phi = 0.0 else: theta = float(np.degrees(np.arccos(np.clip(spin[2] / magnitude, -1.0, 1.0)))) phi = float(np.degrees(np.arctan2(spin[1], spin[0]))) print( f" ! type {type_index} ({label}): {' '.join(members)} " f"S = [{spin[0]:.4f}, {spin[1]:.4f}, {spin[2]:.4f}]" ) print(f" starting_magnetization({type_index}) = {magnitude:.4f}") print(f" angle1({type_index}) = {theta:.4f}") print(f" angle2({type_index}) = {phi:.4f}") print( " ! angle1 = polar angle from the z axis (deg); " "angle2 = azimuth from the x axis in the xy plane (deg)." ) print( f" ! Split {element} into the types above in ATOMIC_SPECIES / " "ATOMIC_POSITIONS to realize this spin arrangement." ) class _Tee(io.TextIOBase): """A text stream that writes to another one and keeps a copy: the report of ``crystod-mag --qpoint``, printed and saved as it is printed.""" def __init__(self, stream) -> None: super().__init__() self.stream = stream self.copy = io.StringIO() def writable(self) -> bool: return True def write(self, text: str) -> int: self.stream.write(text) self.copy.write(text) return len(text) def flush(self) -> None: self.stream.flush() def report_file_name(analysis: "SpinBasisAnalysis") -> str: """The file ``crystod-mag --qpoint`` saves its printed report in. ``samm_<formula>_<element>_<q>`` in the current directory, next to the VESTA files: the reduced formula of the primitive cell and the q-point name (``GM`` for GAMMA, as in the irrep labels), with ``_conv`` for a conventional display cell as in the VESTA names; a character of the q name other than a letter, a digit, ``+`` or ``-`` becomes ``_``. Args: analysis: The :class:`SpinBasisAnalysis` of the run. Returns: The file name, e.g. ``"samm_AlNi3_Ni_GM"``, ``"samm_AlNi3_Ni_R"``, ``"samm_Y2Ir2O7_Ir_GM_conv"``. """ return f"samm_{analysis.formula}_{analysis.element}_{_qpoint_file_tag(analysis)}" def _qpoint_file_tag(analysis: "SpinBasisAnalysis") -> str: """The q part of the output file names: ``GM`` for GAMMA, a character other than a letter, a digit, ``+`` or ``-`` replaced by ``_``, and ``_conv`` for a conventional display cell (``"R"``, ``"X_conv"``).""" label = "GM" if analysis.qpoint_label == "GAMMA" else analysis.qpoint_label label = re.sub(r"[^A-Za-z0-9+-]", "_", label) suffix = "_conv" if analysis.conventional_centring is not None else "" return f"{label}{suffix}" def survey_report_file_name(formula: str, element: str) -> str: """The file the survey of ``crystod-mag`` (no ``--qpoint``) saves its printed report in: ``samm_<formula>_<element>_survey`` (the reduced formula of the primitive cell, as in :func:`report_file_name`), e.g. ``"samm_AlNi3_Ni_survey"``.""" return f"samm_{formula}_{element}_survey" def classify_report_file_name(analysis: "SpinBasisAnalysis") -> str: """The file ``crystod-mag --qpoint Q --classify-only`` saves its printed report in: the name of :func:`report_file_name` with ``_classify`` appended, e.g. ``"samm_AlNi3_Ni_GM_classify"``, ``"samm_TiO2_Ti_GM_conv_classify"``.""" return f"{report_file_name(analysis)}_classify" def supercell_poscar_name(analysis: "SpinBasisAnalysis", poscar_path: str) -> str: """The file ``crystod-mag --qpoint`` writes the magnetic cell to. ``S<basename of the input POSCAR>_<q>`` in the current directory: the q part is that of :func:`report_file_name` (``GM`` for GAMMA, ``_conv`` for a conventional display cell). The cell and its atom order are those of the printed ``MAGMOM`` lines and the VESTA files. Args: analysis: The :class:`SpinBasisAnalysis` of the run. poscar_path: The ``-c`` file of the run (its directory is dropped). Returns: The file name, e.g. ``"SPOSCAR_VO2_P42mnm_A"`` for ``-c POSCAR_VO2_P42mnm --qpoint A``, ``"SPOSCAR_GM"`` for ``-c POSCAR --qpoint GM``, ``"S139_PPOSCAR_La3Ni2O7_X_conv"`` for ``-c ../139_PPOSCAR_La3Ni2O7 --qpoint 0 0 0.5 --conventional``. """ return f"S{os.path.basename(poscar_path)}_{_qpoint_file_tag(analysis)}" def write_supercell_poscar(analysis: "SpinBasisAnalysis", path: str, poscar_path: str) -> None: """Write the magnetic cell of an analysis as a POSCAR (VASP 5, direct). The lattice, positions and atom order are those of ``analysis.supercell_lattice``, ``supercell_positions`` and ``supercell_symbols``, i.e. of the ``MAGMOM`` lines and the VESTA files, so a printed ``MAGMOM`` goes into the INCAR of a noncollinear run on this cell as it is. The atoms are atom-major, so the species of the input stay in consecutive blocks (``V O``, ``16 32``). Args: analysis: The :class:`SpinBasisAnalysis` of the run. path: The file to write (overwritten). poscar_path: The ``-c`` file of the run (named in the comment line). """ from itertools import groupby from .vasp_io import format_poscar species: list[str] = [] counts: list[int] = [] for symbol, run in groupby(analysis.supercell_symbols): species.append(str(symbol)) counts.append(len(list(run))) qpoint = [round(float(value), 6) for value in analysis.qpoint] if analysis.conventional_centring is not None: multiples = analysis.conventional_multiples cells = (f"conventional ({analysis.conventional_centring} centring), " f"{multiples[0]}x{multiples[1]}x{multiples[2]} cells") else: sizes = analysis.supercell_sizes cells = f"{sizes[0]}x{sizes[1]}x{sizes[2]} primitive cells" comment = (f"{analysis.formula} magnetic cell of {os.path.basename(poscar_path)}, " f"q = {analysis.qpoint_label} {qpoint}, {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 main(argv: list[str] | None = None) -> None: args = build_parser().parse_args(argv) # one element: the single-element run as before; several: the direct sum args.elements = list(args.element) args.element = args.elements[0] if getattr(args, "coefficients", None) is not None and getattr(args, "superpose", None) is None: raise SystemExit("ERROR: --coefficients is only used with --superpose.") if getattr(args, "superpose", None) is not None and args.qpoint is None: raise SystemExit("ERROR: --superpose needs --qpoint.") if len(args.elements) > 1: from .multi_element import run_multi_element run_multi_element(args) return if args.classify_only and args.qpoint is None: raise SystemExit("ERROR: --classify-only needs --qpoint.") if getattr(args, "phonon_angular_momentum", False) and args.qpoint is None: raise SystemExit("ERROR: --phonon-angular-momentum needs --qpoint.") if args.no_files and args.qpoint is not None and not args.classify_only: raise SystemExit("ERROR: --no-files is only used with the survey (no --qpoint) and " "--classify-only.") if args.qpoint is None or args.classify_only: # the survey and --classify-only write no VESTA files or SPOSCAR; their # report is saved as samm_<formula>_<element>_survey or # samm_<formula>_<element>_<q>_classify (not with --no-files or # CRYSTOD_NO_REPORT; --classify-only with --subgroup-poscar saves none) from .cli.common import SavedReport enabled = not args.no_files and getattr(args, "subgroup_poscar", None) is None # the survey closes with the * Output files * block of SavedReport; # --classify-only prints it before its references, as the q-point report with SavedReport(enabled=enabled, announce=not args.classify_only) as saved: args.saved_report = saved _run(args) return # a --qpoint run: the report goes to the terminal and, word for word, to # samm_<formula>_<element>_<q> (the name needs the analysis, so the # copy is kept and written at the end; an ERROR exit writes no file) tee = _Tee(sys.stdout) with contextlib.redirect_stdout(tee): analysis = _run(args) with open(report_file_name(analysis), "w", encoding="utf-8") as handle: handle.write(tee.copy.getvalue()) def _run(args) -> "SpinBasisAnalysis | None": """The body of :func:`main`: the survey (returns None) or the q-point report (returns its analysis).""" from .star_of_k import read_poscar_or_exit cell = read_poscar_or_exit(args.poscar) vibrations = SymmetryOnlyVibrations(cell=cell, symprec=args.tolerance, standardize=False) try: # survey and --qpoint alike (spgrep refuses the operations of a # conventional cell or a supercell) _require_primitive(vibrations) except ValueError as exc: raise SystemExit(f"ERROR: {exc}") from None primitive = vibrations.primitive_cell symbols = list(primitive.symbols) positions = primitive.scaled_positions site_indices = [i for i, s in enumerate(symbols) if s == args.element] if not site_indices: available = ", ".join(sorted(set(symbols))) raise SystemExit(f"ERROR: element '{args.element}' is not in this POSCAR ({available}).") n_sites = len(site_indices) print("\n* Structure *") print(f" Space group: {vibrations.spglib_dataset['international']} " f"(#{vibrations.spglib_dataset['number']})") print(f" Magnetic sites: {args.element} x {n_sites}") for k, index in enumerate(site_indices): print(f" {args.element}{k + 1}: {np.round(positions[index], 6).tolist()}") if args.qpoint is None: # survey mode (as in --salc without --kpoint): spin-multipole irreps # at every special k point of the space group from phonopy.structure.cells import get_primitive_matrix_by_centring from .irreptables_compat import load_irreptables from .phonon_irreps import get_irt_special_points from .runtime_compat import get_character IrrepTable, _ = load_irreptables() dataset = vibrations.spglib_dataset irt_table = IrrepTable(dataset["number"], spinor=False) primitive_matrix = get_primitive_matrix_by_centring(dataset["international"][0]) # named in the frame of the labels, the table's own basis being spglib's q_names, q_list = vibrations._special_points_in_label_frame( *get_irt_special_points(irt_table, primitive_matrix) ) print(f"\n* Spin (axial-vector) Irreducible Representations of {args.element} sites *") for name, q in zip(q_names, q_list): irreps, spin_rep, mapping = get_spin_representation(vibrations, site_indices, q) labels = vibrations.get_irrep_labels(q, irreps, mapping) rep_characters = np.array([np.trace(matrix) for matrix in spin_rep]) counts = {} for index, irrep in enumerate(irreps): characters = np.array(get_character(irrep), dtype=complex) count = int(round(float(np.real(np.dot(rep_characters, np.conj(characters)))) / len(spin_rep))) if count > 0: counts[index] = count # a complex irrep and its conjugate at a time-reversal-invariant # point: one physically irreducible space, under the pair label # (as with --qpoint) 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 = [] for index, count in counts.items(): if index in seconds: continue label = labels[index] if index in pairs: label = _pair_label(label, labels[pairs[index]]) terms.append(f"{count}.0 [{label}]") print(f" k point (primitive): {name} {np.round(q, 6).tolist()}") print(f" {' + '.join(terms)}") print("\nUse --qpoint to obtain the symmetry-adapted spin bases, MAGMOM lines, and VESTA files at one k point.") saved = getattr(args, "saved_report", None) if saved is not None: saved.name = survey_report_file_name(reduced_formula(symbols), args.element) return None args.vibrations = vibrations try: analysis = analyze_spin_basis( element=args.element, qpoint=args.qpoint, symprec=args.tolerance, conventional=args.conventional, vibrations=vibrations, subgroup_poscar=getattr(args, "subgroup_poscar", None), ) except ValueError as exc: raise SystemExit(f"ERROR: {' '.join(str(exc).split())}") from None _print_analysis(analysis, args) return analysis def _print_analysis(analysis: "SpinBasisAnalysis", args) -> None: """Print the q-point part of the crystod-mag report from an analysis.""" from .magnetic_group import ( ALTERMAGNET_REFERENCE, format_magnetic_group, format_magnetic_point_group, format_unified_symbols, unconfirmed_note, ) element = analysis.element n_sites = analysis.n_sites is_gamma = analysis.is_gamma print("\n* Selected Q point *") print(f" Selected q-point: {analysis.qpoint_label} = {analysis.qpoint}") print("\n* Spin (axial-vector) representation *") print(f" Spin (axial-vector) representation on {element} sites: " f"{3 * n_sites} dimensions") print(" Decomposition: " + " + ".join( (f"{count} x {label}" if count > 1 else label) for label, count in analysis.decomposition.items() )) if analysis.total_dim != 3 * n_sites: print(f" WARNING: projected dimensions ({analysis.total_dim}) do not span the full space.") print("\n* Symmetry-adapted spin bases *") for label, kind, rank_name, space in analysis.entries: rank_text = f", {rank_name}" if rank_name else "" print(f" {label}: dim {space.shape[0]} [{kind}{rank_text}]") supercell_sizes = analysis.supercell_sizes if not is_gamma: print("\n* Magnetic cell *") print( f" Magnetic (commensurate) supercell: " f"{supercell_sizes[0]}x{supercell_sizes[1]}x{supercell_sizes[2]}" ) if analysis.conventional_centring is not None: multiples = analysis.conventional_multiples if is_gamma: print("\n* Magnetic cell *") print( f" Display cell: conventional ({analysis.conventional_centring} centring), " f"{multiples[0]}x{multiples[1]}x{multiples[2]} cells" ) if analysis.conventional_note: print(f" {analysis.conventional_note}") if not is_gamma: qpoint = np.asarray(analysis.qpoint, dtype=float) if np.allclose(2.0 * qpoint, np.rint(2.0 * qpoint)): print(" the components of each basis span its real order-parameter space; its " "one-parameter directions and their magnetic isotropy subgroups are listed " "under * Order-parameter directions *") else: print(" q is not time-reversal invariant: the order parameter of a d-dimensional " "basis is complex, and its 2d components (comp1..comp<2d> or axis tags: the " "rows w and i w, the phase turned by 90 degrees) span its real " "order-parameter space; its one-parameter " "directions and their magnetic isotropy subgroups are listed under " "* Order-parameter directions *") lines = format_direction_table(analysis) if lines: print() print("\n".join(lines)) supercell_symbols = analysis.supercell_symbols formula = analysis.formula written: list[str] = [] for entry_index, (label, kind, rank_name, space) in enumerate(analysis.entries): if args.classify_only: break header = f"{label} [{kind}" + (f", {rank_name}]" if rank_name else "]") print(f"\n* {header} *") for component in analysis.components: if component.entry_index != entry_index: continue tag = component.tag field = component.field if field is None: print(f" component {tag}: vanishing real spin field; skipped.") continue print(f" component {tag}:") for k in range(n_sites): s = field[0, k] print(f" {element}{k + 1}: S = [{s[0]: .4f}, {s[1]: .4f}, {s[2]: .4f}]") net = component.net_moment if is_gamma: print(f" net moment: {np.round(net, 6).tolist()}") else: print(f" net moment over the magnetic supercell: {np.round(net, 6).tolist()}") line = _direction_line(component) if line: print(f" {line}") if component.collinear is not None: group = component.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}") if component.responses is not None: print(f" allowed by symmetry: {component.responses.summary()}") print(f" collinear order: {component.collinear.text()}") if getattr(args, "phonon_angular_momentum", False): print(f" phonon angular momentum: {_phonon_angular_momentum_text(component)}") if getattr(args, "show_operations", False): print("\n".join(format_parent_operations(analysis, component))) if args.show_spin_direction: magmom_parts = [] atom_spins = [] for atom_index, site in enumerate(analysis.supercell_site_of_atom): if site is None: magmom_parts.append("0 0 0") atom_spins.append(np.zeros(3)) else: cell_index = analysis.supercell_cell_of_atom[atom_index] s = field[cell_index, site] magmom_parts.append(f"{s[0]:.4f} {s[1]:.4f} {s[2]:.4f}") atom_spins.append(np.array(s, dtype=float)) if args.conventional: cell_note = " (conventional cell)" if is_gamma else " (conventional magnetic cell)" else: cell_note = "" if is_gamma else f" ({supercell_sizes.tolist()} magnetic supercell)" print(f" spin directions (all atoms, POSCAR order){cell_note}:") for atom_index, s_text in enumerate(magmom_parts): print(f" {supercell_symbols[atom_index]}{atom_index + 1}: " f"[{s_text.replace(' ', ', ')}]") if args.format == "qe": _print_qe_noncollinear(supercell_symbols, atom_spins, element) else: print(f" MAGMOM = {' '.join(magmom_parts)}") # VESTA export (file name fixed by analyze_spin_basis) rank_tag = rank_name if rank_name else ("FM" if kind == "FM" else analysis.qpoint_label) name = component.vesta_name arrows = np.zeros((len(supercell_symbols), 3)) for atom_index, site in enumerate(analysis.supercell_site_of_atom): if site is not None: cell_index = analysis.supercell_cell_of_atom[atom_index] arrows[atom_index] = field[cell_index, site] * args.amplitude write_vesta_with_arrows( filepath=name, lattice=analysis.supercell_lattice, scaled_positions=analysis.supercell_positions, symbols=supercell_symbols, arrows_cartesian=arrows, title=f"{formula} spin basis: {label} {rank_tag} {tag}", ) written.append(name) print() print("\n".join(format_magnetic_summary(analysis))) if args.classify_only and getattr(args, "phonon_angular_momentum", False): print() print("\n".join(format_phonon_angular_momentum(analysis))) if args.classify_only and getattr(args, "show_operations", False): print("\n* Symmetry operations kept and broken *") for component in analysis.components: if component.field is None: continue print(f"{component.header} {component.file_tag or component.tag}:") print("\n".join(format_parent_operations(analysis, component, indent=" "))) aligned_written: list[str] = [] if analysis.subgroup is not None: print() print("\n".join(format_subgroup_alignment(analysis))) if not args.classify_only: aligned_written = _print_subgroup_fields(analysis, args) if getattr(args, "superpose", None) is not None: from .multi_element import print_superposition, superpose_bases try: superposed = superpose_bases(analysis, args.superpose, args.coefficients, vibrations=getattr(args, "vibrations", None)) except ValueError as exc: raise SystemExit(f"ERROR: {exc}") from None written += print_superposition(analysis, superposed, args) report = None if args.classify_only else report_file_name(analysis) supercell_poscar = None subgroup_poscar = None if report: supercell_poscar = supercell_poscar_name(analysis, args.poscar) write_supercell_poscar(analysis, supercell_poscar, args.poscar) if analysis.subgroup is not None: subgroup_poscar = subgroup_poscar_name(analysis) write_subgroup_poscar(analysis, subgroup_poscar) if written or report: print("\n* Output files *") for name in written: print(f" Spin basis written to: {name}") for name in aligned_written: print(f" Aligned spin field (subgroup structure) written to: {name}") # the QE input has no MAGMOM line; the listings share the order order_of = "spin listings" if args.format == "qe" else "MAGMOM lines" if supercell_poscar: print(f" Supercell POSCAR written to: {supercell_poscar} " f"(atom order of the {order_of})") if subgroup_poscar: print(f" Subgroup structure POSCAR written to: {subgroup_poscar} " f"(atom order of the {order_of} of the aligned fields)") if report: print(f" Report written to: {report} (this output)") # --classify-only: its report is saved by main() (SavedReport) as # samm_<formula>_<element>_<q>_classify, announced in the same place saved = getattr(args, "saved_report", None) if args.classify_only else None if saved is not None and saved.active: saved.name = classify_report_file_name(analysis) print("\n* Output files *") print(saved.line()) print() afm_net_zero = all( np.linalg.norm(c.net_moment) < 1e-6 for c in analysis.components if c.kind == "AFM" and c.field is not None ) if is_gamma and afm_net_zero: print("All AFM bases satisfy sum_i S_i = 0; FM entries carry the cluster dipole moment.") print("Reference: M.-T. Suzuki et al., PRB 95, 094406 (2017); PRB 99, 174407 (2019).") print(f"Reference (collinear classes): {ALTERMAGNET_REFERENCE}.") if getattr(args, "phonon_angular_momentum", False): from .magnetic_group import PHONON_ANGULAR_MOMENTUM_REFERENCE print(f"Reference (phonon angular momentum): {PHONON_ANGULAR_MOMENTUM_REFERENCE}.") def _phonon_angular_momentum_text(component: "SpinBasisComponent") -> str: """The text after ``phonon angular momentum:`` for one component.""" from .magnetic_group import phonon_angular_momentum if component.group is None: return "magnetic point group not determined" return phonon_angular_momentum(component.group).text() def _print_subgroup_fields(analysis: "SpinBasisAnalysis", args) -> list[str]: """Print the aligned spin fields on the subgroup structure, one block per basis (spins of the magnetic sites, magnetic groups, the listing of all atoms and the MAGMOM line or QE input), and write their VESTA files in its cell. Returns the VESTA file names.""" from .magnetic_group import ( format_magnetic_group, format_magnetic_point_group, format_unified_symbols, macroscopic_responses, unconfirmed_note, ) alignment = analysis.subgroup name = os.path.basename(alignment.child_file) element = analysis.element written: list[str] = [] for entry_index, (label, kind, rank_name, _) in enumerate(analysis.entries): rows = [row for row in alignment.rows if row.kind == "aligned" and row.entry_index == entry_index] if not rows: continue header = f"{label} [{kind}" + (f", {rank_name}]" if rank_name else "]") print(f"\n* {header} on {name} *") for row in rows: irrep = row.child_irreps[0][0] symbol = alignment.mulliken.get(irrep) irrep_text = f"{irrep} [{symbol}]" if symbol else irrep angle = f"{row.angle:.1f}".rstrip("0").rstrip(".") print(f" component {row.tag} ({_direction_text(row.direction)}, {irrep_text} of " f"{alignment.child_symbol}; {angle} degrees from {row.reference}):") for k, atom in enumerate(alignment.site_atoms): s = row.spins[atom] print(f" {element}{k + 1}: S = [{s[0]: .4f}, {s[1]: .4f}, {s[2]: .4f}]") group = row.group if group is not None: if not group.identified: print(" magnetic space group: not identified by spglib") if unconfirmed_note(group): print(f" {unconfirmed_note(group)}") 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" allowed by symmetry: {macroscopic_responses(group).summary()}") if args.show_spin_direction: parts = [] for atom in range(len(alignment.symbols)): if atom in alignment.site_atoms: s = row.spins[atom] parts.append(f"{s[0]:.4f} {s[1]:.4f} {s[2]:.4f}") else: parts.append("0 0 0") print(f" spin directions (all atoms, POSCAR order) ({name}):") for atom, text in enumerate(parts): print(f" {alignment.symbols[atom]}{atom + 1}: [{text.replace(' ', ', ')}]") if args.format == "qe": _print_qe_noncollinear(alignment.symbols, list(row.spins), element) else: print(f" MAGMOM = {' '.join(parts)}") write_vesta_with_arrows( filepath=row.vesta_name, lattice=alignment.lattice, scaled_positions=alignment.positions, symbols=alignment.symbols, arrows_cartesian=row.spins * args.amplitude, title=f"{analysis.formula} spin basis on {name}: {label} {row.tag}", ) written.append(row.vesta_name) return written # --------------------------------------------------------------------------- # Data layer: the q-point analysis as data (CLI, API and MCP tool) # --------------------------------------------------------------------------- def _all_finite(ferro, afm_list) -> bool: arrays = ([] if ferro is None else [ferro]) + list(afm_list) return all(np.all(np.isfinite(np.asarray(array))) for array in arrays) _PARTNER_TOLERANCE = 1e-6 def _separation_consistent(ferro, afm_list, n_sites: int) -> bool: """Finite bases, a net moment on every FM row and none on any AFM row.""" if not _all_finite(ferro, afm_list): return False if any(np.abs(_net_moments(np.real(afm), n_sites)).max() > _PARTNER_TOLERANCE for afm in afm_list): return False if ferro is not None: nets = _net_moments(np.real(ferro), n_sites) if (np.linalg.norm(nets, axis=1) < _PARTNER_TOLERANCE).any(): return False return True def _partner_matrices(space, representation) -> NDArray[np.float64]: """Real matrices ``S G(g) S^T`` of the operations on the partners (rows) of ``space``. The rows are taken at unit norm (the partners of one copy are orthogonal with a common norm, which a combination of non-orthogonal copies of the irrep need not make 1). """ space = np.real(np.asarray(space)) norms = np.linalg.norm(space, axis=1) space = space / np.where(norms > 1e-12, norms, 1.0)[:, None] return np.einsum("ui,gij,vj->guv", space, np.real(representation), space) def _partners_fixed_by_symmetry(space, representation) -> bool: """True when every partner of a real space lies along a direction symmetry fixes. A partner (row) qualifies when some operation maps it onto plus or minus itself without acting as a multiple of the identity on the whole space (a two-fold axis or a mirror of a hexagonal E irrep, the four-fold axis of a cubic E irrep); the partners of a 45-degree mixture of such directions do not. One-dimensional spaces always qualify. """ space = np.asarray(space) dim = space.shape[0] if dim < 2: return True if np.abs(np.imag(space)).max() > 1e-8: return False tolerance = _PARTNER_TOLERANCE identity = np.eye(dim) matrices = [ matrix for matrix in _partner_matrices(space, representation) if np.abs(matrix - matrix[0, 0] * identity).max() > tolerance ] for partner in range(dim): if not any( abs(abs(matrix[partner, partner]) - 1.0) < tolerance and np.abs(np.delete(matrix[:, partner], partner)).max() < tolerance for matrix in matrices ): return False return True def _is_signed_permutation(matrix: NDArray[np.float64]) -> bool: """True when ``matrix`` only reorders and negates (to round-off).""" magnitudes = np.abs(np.asarray(matrix)) snapped = np.rint(magnitudes) return bool( np.abs(magnitudes - snapped).max() < 1e-6 and np.array_equal(snapped @ snapped.T, np.eye(len(snapped))) ) def _separation_clean(ferro, afm_list, representation, n_sites: int) -> bool: """A consistent FM/AFM separation whose partners all lie along symmetry-fixed directions.""" if not _separation_consistent(ferro, afm_list, n_sites): return False spaces = ([] if ferro is None else [ferro]) + list(afm_list) return all(_partners_fixed_by_symmetry(space, representation) for space in spaces) def _conventional_rows(vibrations: SymmetryOnlyVibrations) -> NDArray[np.float64]: """spglib's conventional lattice vectors (rows) in the basis of the input cell. In a trigonal or hexagonal crystal the three in-plane lattice vectors a, b and -a-b (six of them in a hexagonal lattice) are equivalent, and which of them spglib calls a depends on round-off in the input, so on a rigid rotation of the cell. Here the choice is made from the input basis alone: among the rotations about c that map the lattice onto itself, the one whose a has the fewest nonzero input indices, then the lexicographically largest ones, is taken -- the input a of a hexagonal cell, a - b of a rhombohedral primitive cell in the obverse setting (the a axis of the standard hexagonal cell of both). Other crystal systems keep spglib's axes. """ import itertools dataset = vibrations.spglib_dataset transformation = np.asarray(dataset["transformation_matrix"], dtype=float) rows = np.linalg.inv(transformation).T if not 143 <= int(dataset["number"]) <= 194: return rows conventional = rows @ np.asarray(vibrations.primitive_cell.cell, dtype=float) metric = conventional @ conventional.T tolerance = 1e-3 * np.abs(metric).max() inverse_rows = np.linalg.inv(rows) best = None for entries in itertools.product((-1, 0, 1), repeat=4): turn = np.array([[entries[0], entries[1], 0], [entries[2], entries[3], 0], [0, 0, 1]]) if round(np.linalg.det(turn)) != 1: continue if np.abs(turn @ metric @ turn.T - metric).max() > tolerance: continue # not a rotation of the lattice about c in_primitive = inverse_rows @ turn @ rows if np.abs(in_primitive - np.rint(in_primitive)).max() > 1e-6: continue # a symmetry of the hexagonal net, not of the (rhombohedral) lattice candidate = turn @ rows first = np.rint(candidate[0]).astype(int) key = (int(np.count_nonzero(first)), tuple(-first)) if best is None or key < best[0]: best = (key, candidate) return rows if best is None else best[1] def conventional_cell_note(vibrations: SymmetryOnlyVibrations, centring: str, base_matrix, n_cells: int) -> str | None: """A NOTE when ``--conventional`` does not write the conventional cell. The base cell of ``--conventional`` is ``base_matrix`` (rows, units of the input cell: :func:`crystod.phonon_vector.get_conventional_matrix`), which is the conventional cell only for the standard primitive setting of the centring. It is accepted when it spans the lattice of spglib's conventional cell (:func:`_conventional_rows`; ``B R_s^-1`` integral and unimodular) and has its shape up to a relabelling of the axes (a signed permutation ``S`` with ``S G_B S^T = G_s`` for the metric tensors, the lengths within twice the symmetry tolerance). A P lattice is not tested. Args: vibrations: The input cell (``standardize=False``). centring: The centring letter (``"I"``). base_matrix: The base cell, rows in units of the input cell. n_cells: Primitive cells of the written cell (for the message). Returns: None when the base cell is the conventional cell (or on a P lattice), else the NOTE line. """ import itertools if centring == "P": return None base = np.asarray(base_matrix, dtype=float) rows = _conventional_rows(vibrations) lattice = np.asarray(vibrations.primitive_cell.cell, dtype=float) change = base @ np.linalg.inv(rows) same = (np.allclose(change, np.rint(change), atol=1e-6) and abs(round(abs(np.linalg.det(np.rint(change))))) == 1) if same: cell_b, cell_s = base @ lattice, rows @ lattice metric_b, metric_s = cell_b @ cell_b.T, cell_s @ cell_s.T length = 2.0 * max(float(getattr(vibrations, "symprec", 1e-5)), 1e-5) longest = float(np.sqrt(max(metric_b.max(), metric_s.max()))) tolerance = 2.0 * longest * length + length * length same = False for order in itertools.permutations(range(3)): for signs in itertools.product((1, -1), repeat=3): S = np.zeros((3, 3)) S[range(3), order] = signs if np.abs(S @ metric_b @ S.T - metric_s).max() <= tolerance: same = True break if same: break if same: return None return (f"NOTE: the primitive cell of the input is not in the standard primitive setting " f"of the {centring} centring (the PPOSCAR of phonopy --symmetry is); the cell " f"written with --conventional is a cell of {n_cells} primitive cells but not the " "conventional cell. The spin structures and their groups hold for the cell as " "written; give the standard primitive cell to get the conventional cell.") def _spin_little_group(vibrations: SymmetryOnlyVibrations, mapping, site_indices: list[int]): """The little group of q = 0 on the magnetic sites, for the partner conventions. A ``crystod.symmetry_adapted_modes._LittleGroup`` built as ``crystod-phonon --vibration`` builds it, with the positions of the magnetic sites only (the spin vectors have three components per site), on the conventional axes of :func:`_conventional_rows`. Returns: ``(group, conventional)``: the little group, and the conventional lattice vectors (rows, in the input's Cartesian frame). """ from .symmetry_adapted_modes import _LittleGroup rows = _conventional_rows(vibrations) # (a_s, b_s, c_s) = (a, b, c) P^-1 as in _conventional_axes, not idealized conventional = rows @ np.asarray(vibrations.primitive_cell.cell, dtype=float) axes = conventional / np.linalg.norm(conventional, axis=1)[:, None] positions = np.asarray(vibrations.primitive_cell.scaled_positions, dtype=float)[site_indices] group = _LittleGroup.at( np.zeros(3), np.asarray(vibrations.rotations)[mapping], np.asarray(vibrations.translations)[mapping], vibrations.primitive_cell.cell, vibrations.symprec, np.linalg.inv(rows.T), np.linalg.inv(axes), positions, ) return group, conventional def _partner_frame(conventional: NDArray[np.float64]) -> NDArray[np.float64]: """Orthonormal frame (rows) of the partner conventions. The conventional a axis, the in-plane direction perpendicular to it (along ``c x a``: Cartesian y of a standard hexagonal cell, b of an orthogonal one) and the third direction, in the input's Cartesian frame. """ first = conventional[0] / np.linalg.norm(conventional[0]) second = np.cross(conventional[2], first) second /= np.linalg.norm(second) return np.array([first, second, np.cross(first, second)]) def _canonical_spin_partners(space, representation, group, conventional) -> NDArray[np.float64]: """Orthogonal rotation of the partners of a real space onto symmetry-fixed directions. Adapted from ``crystod.symmetry_adapted_modes._canonical_partner_basis`` (the partner choice of ``crystod-phonon --vibration``): the joint eigenvectors of a maximal set of commuting involutions (operations with ``R^2 = 1`` whose matrix on the partners is symmetric and not a multiple of the identity) whose joint eigenspaces are all one-dimensional, so every partner is fixed up to sign by those operations. Bases the group permutes up to sign come first (the x, y, z partners of a cubic T irrep), then the bases whose partners have the most symmetric isotropy subgroups (``_isotropy_key``), as in the source. Two changes for spins: among sets that tie on those keys (the three equivalent two-fold axes of a trigonal crystal, the three mirror pairs of a hexagonal one), the set holding the operation whose axis (mirror normal) lies closest to the conventional a axis, to the in-plane direction perpendicular to it (``c x a``) or to the third direction of that orthonormal frame is taken, in this order (then the face diagonals), so that the partners of an in-plane E irrep point along the a axis and perpendicular to it in the 321 and the 312 settings alike; and the partners are ordered first by the direction of that frame their moments point along the most (along a before perpendicular to it), then by their isotropy subgroups and the further keys of the source. Only the matrices of the operations on the partners and the moments of ``space`` enter, so every copy of the irrep that transforms with the same matrices gets the same rotation. Args: space: Real orthonormal partners (rows) of one copy of the irrep, shape ``(dim, 3N)``. representation: The spin representation ``(order, 3N, 3N)`` at q = 0. group: The little group from :func:`_spin_little_group`. conventional: The conventional lattice vectors (rows, Cartesian) from :func:`_spin_little_group`. Returns: The orthogonal ``(dim, dim)`` matrix whose columns are the new partners in the coordinates of the old ones (``basis.T @ space`` are the new rows); a signed permutation is returned exactly. """ from functools import cmp_to_key from .symmetry_adapted_modes import ( _compare_descriptors, _integer_kernel_vector, _isotropy_key, _maximal_cliques, _partner_descriptor, _partner_signs, _split_by_displacements, ) vectors = np.real(np.asarray(space)).T # (3N, dim), columns dim = vectors.shape[1] if dim < 2: return np.eye(dim) tolerance = _PARTNER_TOLERANCE rotations = group.setting_rotations matrices = list(_partner_matrices(space, representation)) identity = np.eye(3, dtype=int) frame = _partner_frame(conventional) def operation_axis(index: int) -> NDArray[np.int_] | None: """Rotation axis, or mirror normal, of an operation in the conventional basis.""" rotation = np.asarray(rotations[index], dtype=int) determinant = int(round(np.linalg.det(rotation))) if np.array_equal(rotation, determinant * identity): return None return _integer_kernel_vector(rotation - determinant * identity) def axis_rank(index: int) -> tuple: # how closely the axis (mirror normal) lies along the a axis, the # in-plane direction perpendicular to it or the third direction of # ``frame`` (Cartesian, so the [120] two-fold of a 312 setting counts # as perpendicular to a), then which of them, then the indices axis = operation_axis(index) if axis is None: return (4.0,) direction = axis @ conventional direction = direction / np.linalg.norm(direction) overlaps = np.abs(frame @ direction) along = int(np.argmax(overlaps)) return ( round(1.0 - float(overlaps[along]), 6), along, int(np.count_nonzero(axis)), tuple(-abs(int(value)) for value in axis), ) order = sorted( range(len(rotations)), key=lambda index: tuple(np.asarray(rotations[index]).ravel()) ) keys: list[tuple[int, ...]] = [] members_of: list[list[int]] = [] # operations giving each involution (up to sign) involutions: list[NDArray[np.float64]] = [] for index in order: rotation = np.asarray(rotations[index], dtype=int) matrix = matrices[index] if np.array_equal(rotation, identity) or not np.array_equal(rotation @ rotation, identity): continue if np.abs(matrix - matrix.T).max() > tolerance: continue if np.abs(matrix - np.trace(matrix) / dim * np.eye(dim)).max() < tolerance: continue duplicate = next( ( position for position, other in enumerate(involutions) if min(np.abs(matrix - other).max(), np.abs(matrix + other).max()) < tolerance ), None, ) if duplicate is not None: members_of[duplicate].append(index) continue keys.append(tuple(rotation.ravel())) members_of.append([index]) involutions.append(matrix) def commute(first: NDArray[np.float64], second: NDArray[np.float64]) -> bool: return bool(np.abs(first @ second - second @ first).max() < tolerance) adjacency = [ { other for other in range(len(involutions)) if other != vertex and commute(involutions[vertex], involutions[other]) } for vertex in range(len(involutions)) ] best = None partial = None for clique in _maximal_cliques(adjacency) if involutions else []: members = sorted(clique) combined = sum(np.sqrt(2.0 + member) * involutions[member] for member in members) values, basis = np.linalg.eigh(0.5 * (combined + combined.T)) if np.min(np.diff(values)) < tolerance: breaks = np.flatnonzero(np.diff(values) >= tolerance) + 1 blocks = np.split(np.arange(dim), breaks) rank = (-len(blocks), tuple(sorted(keys[member] for member in members))) if partial is None or rank < partial[0]: partial = (rank, [basis[:, block] for block in blocks]) continue in_basis = [basis.T @ matrix @ basis for matrix in matrices] monomial = all( np.all(np.minimum(np.abs(matrix), np.abs(np.abs(matrix) - 1.0)) <= tolerance) for matrix in in_basis ) partner_keys = [ _isotropy_key(_partner_signs(in_basis, column, tolerance), group) for column in range(dim) ] axes = min(axis_rank(index) for member in members for index in members_of[member]) rank = ( not monomial, tuple(sorted(partner_keys)), axes, tuple(sorted(keys[member] for member in members)), ) if best is None or rank < best[0]: best = (rank, basis, partner_keys, in_basis) if best is None: blocks = partial[1] if partial is not None else [np.eye(dim)] basis = np.hstack([ block @ _split_by_displacements(vectors @ block, group) for block in blocks ]) in_basis = [basis.T @ matrix @ basis for matrix in matrices] partner_keys = [ _isotropy_key(_partner_signs(in_basis, column, tolerance), group) for column in range(dim) ] else: _, basis, partner_keys, in_basis = best def stabilizer(column: int) -> list[int]: signs = _partner_signs(in_basis, column, tolerance) return [index for index, sign in enumerate(signs) if sign > 0] def axis_key(column: int) -> tuple[int, int]: best_key = (0, 3) for index in stabilizer(column): rotation = rotations[index] if round(np.linalg.det(rotation)) != 1 or np.array_equal(rotation, identity): continue axis = _integer_kernel_vector(rotation - identity) if axis is None or np.count_nonzero(axis) != 1: continue period = next( n for n in range(2, 7) if np.array_equal(np.linalg.matrix_power(rotation, n), identity) ) best_key = min(best_key, (-period, int(np.flatnonzero(axis)[0]))) return best_key def direction_key(column: int) -> int: # the direction of ``frame`` the moments of the partner point along # the most (3 when two directions tie) components = (basis[:, column] @ vectors.T).reshape(-1, 3) @ frame.T weights = np.sum(components**2, axis=0) first, second = np.argsort(-weights, kind="stable")[:2] if weights[first] - weights[second] <= 1e-6 * weights[first]: return 3 return int(first) def stabilizer_key(column: int) -> tuple: return tuple(sorted(tuple(rotations[index].ravel()) for index in stabilizer(column))) keys_by_column = [ (direction_key(column), partner_keys[column], axis_key(column), stabilizer_key(column)) for column in range(dim) ] descriptors: dict[int, NDArray[np.float64]] = {} def descriptor(column: int) -> NDArray[np.float64]: if column not in descriptors: descriptors[column] = _partner_descriptor(basis[:, column] @ vectors.T, group) return descriptors[column] def compare(first: int, second: int) -> int: if keys_by_column[first] != keys_by_column[second]: return -1 if keys_by_column[first] < keys_by_column[second] else 1 return _compare_descriptors(descriptor(first), descriptor(second)) basis = basis[:, sorted(range(dim), key=cmp_to_key(compare))] snapped = np.rint(basis) if np.abs(basis - snapped).max() < 1e-8 and np.array_equal( np.abs(snapped) @ np.abs(snapped).T, np.eye(dim) ): basis = snapped # a signed permutation: exact, the values are only reordered return basis def _canonical_spin_spaces(spin_rep, irrep, n_sites: int, group, conventional, pairs): """FM/AFM-separated spin bases of one irrep at q = 0 with canonical partners. The route taken when the copies of an irrep, made real one by one, do not separate cleanly (spgrep gives the E irreps of trigonal and hexagonal groups, and of rutile, in a complex basis; each copy then gets its own arbitrary real basis). The irrep is brought to a real form (``crystod.symmetry_adapted_modes._real_form``) and the spin representation projected onto it; the copies are made real together (``_real_occurrences``), so that every copy transforms with the same real matrices and :func:`separate_ferro_combination` can combine them partner by partner. Two or more AFM copies are then replaced by the basis that the moments fix (``_canonical_occurrences``: the sites each copy lives on, the moments along the crystal axes, the products of the moments of neighbouring sites), and the partners of all copies are turned by one common rotation onto the directions symmetry fixes (:func:`_canonical_spin_partners`); each partner is signed so that its largest moment component along the crystal axes is positive. Returns: ``(ferro, afm)`` as :func:`separate_ferro_combination`, or None when the irrep has no real form or the copies cannot be made real. """ from .symmetry_adapted_modes import ( _axes_sign, _canonical_occurrences, _real_form, _real_occurrences, ) irrep = np.asarray(irrep) root = _real_form(irrep) if root is None: return None real_irrep = np.einsum("ji,gjk,kl->gil", root.conj(), irrep, root) occurrences = _real_occurrences( [np.asarray(space) for space in project_to_irrep(spin_rep, real_irrep)] ) if occurrences is None: return None occurrences = [np.real(occurrence) for occurrence in occurrences] with warnings.catch_warnings(), np.errstate(all="ignore"): warnings.simplefilter("ignore") ferro, afm_list = separate_ferro_combination( occurrences, spin_rep, n_sites, realify_aligned=False ) if not _all_finite(ferro, afm_list): return None afm_list = [np.real(afm) for afm in afm_list] if len(afm_list) > 1: try: afm_list = [ np.real(space) for space in _canonical_occurrences( [afm + 0j for afm in afm_list], np.zeros(3), group.positions, group.inverse_axes, pairs, real=True, ) ] except RuntimeError: return None reference = np.real(ferro) if ferro is not None else afm_list[0] basis = _canonical_spin_partners(reference, spin_rep, group, conventional) permutation = None if np.array_equal(np.abs(basis) @ np.abs(basis).T, np.eye(len(basis))) and np.array_equal( basis, np.rint(basis) ): # a signed permutation: reorder and negate rows, which keeps every # value (and the sign of every zero) exact permutation = [int(np.flatnonzero(basis[:, column])[0]) for column in range(len(basis))] def turned(space: NDArray[np.float64]) -> NDArray[np.float64]: space = np.real(space) if permutation is not None: rows = np.array([ space[row] if basis[row, column] > 0 else -space[row] for column, row in enumerate(permutation) ]) else: rows = basis.T @ space return np.array([row * _axes_sign(row, group.inverse_axes) for row in rows]) return (None if ferro is None else turned(ferro)), [turned(afm) for afm in afm_list] def _natural_key(label: str) -> tuple: """Sort key that orders the digits of a label as numbers (GM2 before GM10).""" import re return tuple(int(part) if part.isdigit() else part for part in re.split(r"(\d+)", label)) def _conjugate_pairs(irreps, labels: list[str], present: set[int]) -> dict[int, int]: """The complex-type irreps present in the spin representation, with their conjugates. A complex-type irrep (complex characters) and the irrep with the conjugate characters, which time reversal joins into one physically irreducible real representation; the pair is recognized from the characters, not from the labels. Returns: ``{first: second}`` (indices into ``irreps``), ``first`` the member whose label sorts first in the natural order (as in ``crystod-phonon --vibration``, whose first half of the shared real partners belongs to that member). """ from .runtime_compat import get_character characters = {index: np.array(get_character(irreps[index]), dtype=complex) for index in present} pairs: dict[int, int] = {} used: set[int] = set() for index in sorted(present): if index in used or np.abs(characters[index].imag).max() < 1e-6: continue partner = next( (other for other in sorted(present) if other != index and other not in used and np.allclose(characters[other], characters[index].conj(), atol=1e-6)), None, ) if partner is None: continue used |= {index, partner} first, second = sorted( (index, partner), key=lambda i: _natural_key(labels[i].split("(")[0]) ) pairs[first] = second return pairs def _pair_label(label: str, partner: str) -> str: """``GM3+GM4+(2)``: the ISOTROPY pair label of a complex irrep and its conjugate (natural order, as ``crystod-group --parent`` and ``crystod-phonon`` write it) with the real dimension of the pair.""" names = sorted((label.split("(")[0], partner.split("(")[0]), key=_natural_key) def dimension(text: str) -> int: return int(text.split("(")[1].rstrip(")")) if "(" in text else 1 return f"{names[0]}{names[1]}({dimension(label) + dimension(partner)})" def _frame_phase(row: NDArray[np.complex128], n_sites: int, frame: NDArray[np.float64], ferro: bool) -> complex | None: """Unit phase that turns the real part of a complex copy onto the axes of ``frame``. The copy ``row`` of a complex one-dimensional irrep W spans, with its real and imaginary parts, a real two-dimensional space on which every operation acts as a rotation (W(g) is a phase), so no symmetry element singles out a direction in it; the convention fixes the phase instead. With a net moment (``ferro``), the net moment of the real part points along the first axis of ``frame`` it has a component on (along +a: the conventional a axis, then ``c x a``, then the third direction). Without one, the real part carries as much of the moments along the first axis of ``frame`` as it can (the sum over the sites of the squared moment components along that axis is largest), the next axis deciding when the moments along an axis are circular. None when no axis decides. """ moments = row.reshape(n_sites, 3) @ np.asarray(frame).T # components along the axes if ferro: net = moments.sum(axis=0) scale = np.linalg.norm(net) for axis in range(3): if scale > 1e-12 and abs(net[axis]) > 1e-6 * scale: return np.conj(net[axis]) / abs(net[axis]) squares = (moments**2).sum(axis=0) weights = (np.abs(moments) ** 2).sum(axis=0) total = weights.sum() for axis in range(3): if weights[axis] > 1e-6 * total and abs(squares[axis]) > 1e-4 * weights[axis]: return np.exp(-0.5j * np.angle(squares[axis])) # every site's moment turns on a circle as the phase changes: the first # site (in site order) with the largest moment gets its moment along the # first axis it has a component on norms = np.linalg.norm(moments, axis=1) if norms.max() < 1e-12: return None site = int(np.flatnonzero(norms >= norms.max() * (1.0 - 1e-6))[0]) for axis in range(3): if abs(moments[site, axis]) > 1e-6 * norms[site]: return np.conj(moments[site, axis]) / abs(moments[site, axis]) return None def _real_pair_space(row: NDArray[np.complex128], n_sites: int, frame: NDArray[np.float64], inverse_axes: NDArray[np.float64], ferro: bool) -> NDArray[np.float64]: """The real two-dimensional space ``sqrt(2) [Re w, Im w]`` of one complex copy ``w``. The global phase of ``w`` is fixed by :func:`_frame_phase` (else by ``symmetry_adapted_modes._bloch_phase``), and each of the two partners is signed with its largest moment component along the crystal axes positive (``_axes_sign``). """ from .symmetry_adapted_modes import _axes_sign, _bloch_phase row = np.asarray(row, dtype=complex) row = row / np.linalg.norm(row) phase = _frame_phase(row, n_sites, frame, ferro) row = row * (phase if phase is not None else _bloch_phase(row, inverse_axes)) space = np.sqrt(2.0) * np.array([row.real, row.imag]) return np.array([part * _axes_sign(part, inverse_axes) for part in space]) def _real_pair_rows(space: NDArray[np.complex128], n_sites: int, frame: NDArray[np.float64], inverse_axes: NDArray[np.float64]) -> NDArray[np.float64]: """The real space of one copy of a complex irrep and its conjugate at q != 0. At a time-reversal-invariant q the representation is real in the lattice gauge, so the conjugate of a copy W of a ``d``-dimensional complex irrep is a copy of the conjugate irrep, and the two span one real ``2d``-dimensional space, listed under the pair label: ``sqrt(2) [Re w_1, ..., Re w_d, Im w_1, ..., Im w_d]`` (the merged partners of ``crystod-phonon --vibration``, the first half for the first member of the pair). The irrep matrices fix the relative phases of the rows, so one global phase is chosen, from the first row as in :func:`_real_pair_space`, and each partner is signed with its largest moment component along the crystal axes positive. A one-dimensional copy gives :func:`_real_pair_space`. """ from .symmetry_adapted_modes import _axes_sign, _bloch_phase space = np.asarray(space, dtype=complex) if space.shape[0] == 1: return _real_pair_space(space[0], n_sites, frame, inverse_axes, False) first = space[0] / np.linalg.norm(space[0]) phase = _frame_phase(first, n_sites, frame, False) rows = space * (phase if phase is not None else _bloch_phase(first, inverse_axes)) real = np.sqrt(2.0) * np.vstack([rows.real, rows.imag]) return np.array([part * _axes_sign(part, inverse_axes) for part in real]) def _merged_pair_spaces(copies, n_sites: int, group, conventional, pairs): """FM/AFM-separated real spin bases of a complex irrep and its conjugate at q = 0. A complex-type irrep W and its conjugate carry the same real spin arrangements: the real and imaginary parts of a copy span one real two-dimensional space, the partners of the physically irreducible representation (``sqrt(2) [Re W, Im W]``, the real partners that ``crystod-phonon --vibration`` gives the two members of the pair). The net moments are separated on the complex copies of W, where every complex combination of copies is again a copy: the combinations with a net moment (one for a one-dimensional irrep, the cluster dipole) span the complement of those without, the AFM ones, which are replaced by the basis that the moments fix (``_canonical_occurrences``, as for repeated irreps elsewhere). Every copy is then made real (:func:`_real_pair_space`): every operation acts on the two partners as the same rotation whatever the phase of the copy, and no symmetry element fixes a direction in the space, so the phase is a convention -- the net moment of the first partner of an FM copy along the conventional a axis, the moments of the first partner of an AFM copy along it as much as possible (:func:`_frame_phase`). Args: copies: The complex copies of W (``project_to_irrep``), each of shape ``(1, 3N)``. n_sites: The number N of spin-carrying sites. group, conventional: From :func:`_spin_little_group`. pairs: The neighbour-pair callback of ``_canonical_occurrences``. Returns: ``(ferro_list, afm_list)``: the real ``(2, 3N)`` spaces with and without a net moment, or None when a copy is not one-dimensional. """ from .symmetry_adapted_modes import _canonical_occurrences copies = [np.asarray(copy, dtype=complex) for copy in copies] if any(copy.shape[0] != 1 for copy in copies): return None rows = np.array([copy[0] for copy in copies]) orthonormal, _ = np.linalg.qr(rows.T) rows = orthonormal.T nets = rows.reshape(len(rows), n_sites, 3).sum(axis=1) _, values, right = np.linalg.svd(nets.T) rank = int(np.sum(values > 1e-6)) combinations = right.conj() @ rows # row k: sum_a conj(right[k, a]) rows[a] ferro_rows = list(combinations[:rank]) afm_rows = list(combinations[rank:]) if len(afm_rows) > 1: afm_rows = [ occurrence[0] for occurrence in _canonical_occurrences( [row[None, :] for row in afm_rows], np.zeros(3), group.positions, group.inverse_axes, pairs, real=False, ) ] frame = _partner_frame(conventional) return ( [_real_pair_space(row, n_sites, frame, group.inverse_axes, True) for row in ferro_rows], [_real_pair_space(row, n_sites, frame, group.inverse_axes, False) for row in afm_rows], ) def _uniform_moment_spaces(spaces, n_sites: int, frame, group, pairs): """FM/AFM separation of the copies of one irrep from the uniform moments. The route for an irrep whose copies do not separate into one FM copy and net-zero AFM copies, because the irrep occurs more than once in a single moment (the moments perpendicular to the two-fold axis of a monoclinic crystal, any moment of a triclinic one): the arrangements with a net moment are the projections onto the isotypic space of the uniform moments along the axes of ``frame`` (taken in that order and made orthonormal; each has its net moment along its own axis), and the AFM ones are the rest of the space, whose net moments vanish because they are orthogonal to every uniform moment. For a one-dimensional irrep the space is first split into the moments along each axis of ``frame`` when symmetry keeps them apart (the two-fold axis of a monoclinic crystal and the axes perpendicular to it), so every arrangement keeps its moments along one axis; two or more AFM arrangements of one part are replaced by the basis that the moments fix (``_canonical_occurrences``) and signed with their largest moment component along the crystal axes positive. Returns: A list of ``(kind, space)`` pairs (FM first): one space per arrangement for a one-dimensional irrep; for a larger irrep one FM space with every FM arrangement and the AFM rest in parts of the irrep dimension. None when the copies do not span a real space. """ from .symmetry_adapted_modes import _axes_sign, _canonical_occurrences spaces = [np.asarray(space) for space in spaces] dim = spaces[0].shape[0] total = sum(space.shape[0] for space in spaces) stacked = np.vstack([part for space in spaces for part in (space.real, space.imag)]) _, values, right = np.linalg.svd(stacked, full_matrices=False) if len(values) < total or values[total - 1] < 1e-8 or ( len(values) > total and values[total] > 1e-6 ): return None basis = right[:total] def separate(space: NDArray[np.float64], directions) -> tuple[list, list]: """FM rows (projected uniform moments) and the orthonormal rest of ``space``.""" ferro_rows: list[NDArray[np.float64]] = [] for direction in directions: vector = space.T @ (space @ np.tile(direction, n_sites)) for row in ferro_rows: vector = vector - (row @ vector) * row norm = np.linalg.norm(vector) if norm > 1e-6: ferro_rows.append(vector / norm) rest = space if ferro_rows: ferro = np.array(ferro_rows) rest = space - (space @ ferro.T) @ ferro _, _, right = np.linalg.svd(rest, full_matrices=False) return ferro_rows, list(right[: len(space) - len(ferro_rows)]) if dim > 1: ferro_rows, afm_rows = separate(basis, frame) ordered = [("FM", np.array(ferro_rows))] if ferro_rows else [] ordered += [("AFM", np.array(afm_rows[start:start + dim])) for start in range(0, len(afm_rows), dim)] return ordered # a one-dimensional irrep: every operation acts on the moments along an # axis of ``frame`` alone when it maps that axis onto +-itself (the # two-fold axis of a monoclinic crystal and the plane perpendicular to # it), and the space then splits into the moments along each axis parts = [] for axis in frame: along = np.kron(np.eye(n_sites), np.outer(axis, axis)) projected = basis @ along if np.abs(projected - projected @ basis.T @ basis).max() > 1e-6: parts = [] break _, values, right = np.linalg.svd(projected, full_matrices=False) rank = int(np.sum(values > 1e-6)) if rank: parts.append((axis, right[:rank])) if sum(len(part) for _, part in parts) != total: parts = [(None, basis)] ferro_rows, afm_rows = [], [] for axis, part in parts: ferro_part, afm_part = separate(part, frame if axis is None else [axis]) ferro_rows += ferro_part if len(afm_part) > 1: afm_part = [ np.real(occurrence[0]) for occurrence in _canonical_occurrences( [row[None, :] + 0j for row in afm_part], np.zeros(3), group.positions, group.inverse_axes, pairs, real=True, ) ] afm_rows += [row * _axes_sign(row, group.inverse_axes) for row in afm_part] return ([("FM", row[None, :]) for row in ferro_rows] + [("AFM", row[None, :]) for row in afm_rows]) def _require_primitive(vibrations: SymmetryOnlyVibrations) -> None: """Refuse a cell that is not primitive. ``crystod-mag`` analyses the cell as given (``standardize=False``: the spin listings and MAGMOM follow its atom order), and the irreps of the little groups need the operations of a primitive cell; a conventional cell or a supercell has pure translations among its operations. Raises: ValueError: The space group of the cell holds pure translations. """ rotations = np.asarray(vibrations.rotations) n_lattice = int(np.sum(np.all(rotations == np.eye(3, dtype=int), axis=(1, 2)))) if n_lattice > 1: n_atoms = len(vibrations.primitive_cell.symbols) raise ValueError( f"the input cell is not primitive ({n_atoms} atoms, the primitive cell has " f"{n_atoms // n_lattice}); crystod-mag uses the cell as given (the spin listings " "and MAGMOM follow its atom order) and needs a primitive cell, such as the " "PPOSCAR of phonopy --symmetry (--conventional then exports the spin structures " "in the conventional cell)." ) #: Largest multiple of a cell along one axis in the magnetic cell at q != 0. _MAX_CELL_MULTIPLE = 12 #: Tolerance on q . T being an integer for a translation T of the magnetic cell. _COMMENSURATE_TOLERANCE = 1e-6 def _commensurability_error(qpoint, cell_matrix, conventional: bool) -> str | None: """Why the magnetic cell ``cell_matrix`` does not fit q, or None when it does. The cell is commensurate when ``q . T`` is an integer for each of its vectors ``T`` (rows of ``cell_matrix``, primitive units), so that the Bloch phase is the same in every copy of the cell. The cell is built from the denominators of q up to ``_MAX_CELL_MULTIPLE``; a q with a larger denominator (``0.15 = 3/20``) or none does not fit, and the message names the smallest commensurate supercell of the primitive cell. """ qpoint = np.asarray(qpoint, dtype=float) products = np.asarray(cell_matrix, dtype=float) @ qpoint if np.abs(products - np.rint(products)).max() < _COMMENSURATE_TOLERANCE: return None sizes = [] for value in qpoint: size = Fraction(float(value)).limit_denominator(1000).denominator product = size * float(value) sizes.append(size if abs(product - round(product)) < _COMMENSURATE_TOLERANCE else None) kind = "conventional" if conventional else "primitive" text = (f"q-point {np.round(qpoint, 6).tolist()} is not commensurate with a magnetic " f"cell of at most {_MAX_CELL_MULTIPLE} {kind} cells along each axis") advice = (f" Choose q with fractional coordinates of denominators up to " f"{_MAX_CELL_MULTIPLE}.") if None in sizes: return text + "; no supercell of up to 1000 primitive cells along each axis is " \ "commensurate." + advice smallest = "x".join(str(size) for size in sizes) if conventional and max(sizes) <= _MAX_CELL_MULTIPLE: return text + f"; the {smallest} primitive supercell is commensurate (run without " \ "--conventional)." return text + "; the smallest commensurate supercell along the primitive axes is " \ f"{smallest}." + advice
[docs] @dataclass(eq=False) class SpinBasisComponent: """One exported component of a symmetry-adapted spin basis. Attributes: entry_index: Index of the basis in ``SpinBasisAnalysis.entries``. label: The ISO-IR irrep label (``"GM4+(3)"``). kind: ``"FM"``, ``"AFM"`` or ``"AFM (q != 0)"``. rank_name: Multipole name at q = 0 (``"dipole"``), else None. tag: Component name as in the VESTA file name: ``"x"``, ``"y"``, ``"z"``, ``"111"``, ``"1m10"`` for collinear components, else ``"comp<N>"`` (the N-th basis vector of the space, counted from 1); a combination of the components of a two- or three-dimensional space is exported next to them (:func:`_combined_components`): its (a,a) or (a,a,0) direction where symmetry singles it out (``"110"`` for ``x`` and ``y``, ``"x"`` for ``1m10`` and ``110``, ``"aa"`` for two ``z`` components, ``"aa0"`` for ``comp1`` and ``comp2``), and the (a,a,a) direction (``"111"`` for x + y + z, ``"aaa"``). At a q that is not time-reversal invariant a d-dimensional copy has 2d basis components: the d rows w_k and their partners i w_k (the phase of the complex order parameter turned by 90 degrees), ``comp1 .. comp<2d>`` (a partner of a collinear row has its axis tag). ``"dir<k>"``: a one-parameter order-parameter direction at q != 0 that none of the other components lies on (k counted per basis). field: Real spin field ``(n_cells, N, 3)`` over the magnetic cell, largest moment 1; None when the real field vanishes. net_moment: Net moment over the magnetic cell. group: :class:`crystod.magnetic_group.MagneticGroupInfo` of the arrangement (None without classification; its ``identified`` is False when spglib finds the operations but cannot name the group). responses: :class:`crystod.magnetic_group.MagneticResponses`. collinear: :class:`crystod.magnetic_group.CollinearClass`. file_tag: The tag made unique within the analysis as in the VESTA file name (``"z"``, ``"z_2"`` for the second ``z`` of the same irrep and multipole); empty when the field vanishes. vesta_name: The VESTA file name ``crystod-mag`` writes for this component; empty when the field vanishes. direction_label: At q != 0, ISOTROPY's label of the one-parameter order-parameter direction the component lies on (``"K3(a;0.974a)"``), when the q point has a table and a row matches; else None. direction_subgroup: The magnetic isotropy subgroup of that direction (``"193.255 P6_3/m'cm"``, BNS number and symbol of the spin field), None when the component is not on a one-parameter direction or has no identified group. direction: The :class:`OrderParameterDirection` (stratum) the component lies in at q != 0 (also when it has more than one free parameter), else None. """ entry_index: int label: str kind: str rank_name: str | None tag: str field: NDArray[np.float64] | None net_moment: NDArray[np.float64] | None = None group: object = None responses: object = None collinear: object = None file_tag: str = "" vesta_name: str = "" direction_label: str | None = None direction_subgroup: str | None = None direction: object = None stratum: int | None = dataclass_field(default=None, repr=False) @property def header(self) -> str: """``"GM4+(3) [FM, dipole]"`` -- the block title of ``crystod-mag``.""" return f"{self.label} [{self.kind}" + (f", {self.rank_name}]" if self.rank_name else "]")
[docs] @dataclass(eq=False) class SpinBasisAnalysis: """The symmetry-adapted spin bases at one q point, with their magnetic groups and collinear classes (what ``crystod-mag --qpoint`` prints). Attributes: element: The magnetic element. space_group: International symbol of the space group. space_group_number: Its number. site_indices: Indices of the magnetic sites in the primitive cell. site_positions: Their fractional positions. qpoint_label: Name of the q point (``"GAMMA"``, ``"X"``). qpoint: Its primitive reciprocal coordinates. is_gamma: True at q = 0. decomposition: ``{irrep label: multiplicity}`` of the spin representation, in the order of the irreps; at a time-reversal-invariant q a complex irrep and its conjugate count once under their pair label (``"GM3+GM4+(2)"``). total_dim: Sum of the projected dimensions (``3 N`` normally). entries: The bases: ``(label, kind, rank_name, space)`` with the basis array ``space`` of shape ``(dim, 3 N)``. supercell_sizes: Diagonal of the commensurate magnetic supercell. cell_matrix: The magnetic (display) cell in primitive units, rows. conventional_centring: The centring letter with ``conventional``, else None. conventional_multiples: Conventional cells along each axis, or None. cell_translations: Primitive translations inside the magnetic cell. supercell_lattice: Lattice of the magnetic cell (rows, Angstrom). supercell_symbols: Symbols of the atoms of the magnetic cell. supercell_positions: Their fractional positions. supercell_site_of_atom: Magnetic-site index of every atom, or None. components: The exported components (:class:`SpinBasisComponent`), in output order. formula: Reduced formula (file names). symbols: Symbols of the primitive cell. pair_labels: The labels of the complex irreps merged with their conjugates (``"GM3+GM4+(2)"``, ``"Z3+Z4+(2)"``) that have a basis. primitive_lattice: Lattice of the primitive cell (rows, Angstrom). conventional_lattice: Lattice of its conventional cell (rows), the frame of the operation symbols of :func:`parent_operations`. parent_rotations: Cartesian rotations of the space group of the crystal, one per coset of its translations. parent_translations: Their Cartesian translations (Angstrom). supercell_cell_of_atom: Index into ``cell_translations`` of the cell of every atom of the magnetic cell. The atoms are atom-major (phonopy's ``SPOSCAR`` order): each atom of the primitive cell followed by its images in the other cells. directions: At q != 0, the order-parameter directions (strata) of every basis in the magnetic cell (:class:`OrderParameterDirection`), with ISOTROPY's labels at a special point, followed for each irrep by the table rows the magnetic cell does not realize; empty at q = 0. direction_notes: Bases whose directions could not be enumerated. subgroup: With a subgroup structure (``crystod-mag --subgroup-poscar CHILD``, ``analyze_spin_basis(..., subgroup_poscar=CHILD)``), the bases placed on it and aligned with its structural domain (:class:`SubgroupAlignment`); else None. conventional_note: With ``conventional``, the NOTE of :func:`conventional_cell_note` when the written cell is not the conventional cell (an input primitive cell off the standard primitive setting); else None. """ element: str space_group: str space_group_number: int site_indices: list site_positions: NDArray[np.float64] qpoint_label: str qpoint: list is_gamma: bool decomposition: dict total_dim: int entries: list supercell_sizes: NDArray[np.int_] cell_matrix: NDArray[np.int_] conventional_centring: str | None conventional_multiples: NDArray[np.int_] | None cell_translations: list supercell_lattice: NDArray[np.float64] supercell_symbols: list supercell_positions: NDArray[np.float64] supercell_site_of_atom: list components: list = dataclass_field(default_factory=list) formula: str = "" symbols: list = dataclass_field(default_factory=list) pair_labels: list = dataclass_field(default_factory=list) primitive_lattice: NDArray[np.float64] | None = None conventional_lattice: NDArray[np.float64] | None = None parent_rotations: NDArray[np.float64] | None = None parent_translations: NDArray[np.float64] | None = None supercell_cell_of_atom: list = dataclass_field(default_factory=list) directions: list = dataclass_field(default_factory=list) direction_notes: list = dataclass_field(default_factory=list) subgroup: object = None conventional_note: str | None = None @property def n_sites(self) -> int: """Number of magnetic sites in the primitive cell.""" return len(self.site_indices)
[docs] def analyze_spin_basis( cell=None, element: str = "", qpoint=("GM",), *, symprec: float = 1e-5, conventional: bool = False, classify: bool = True, vibrations: SymmetryOnlyVibrations | None = None, subgroup_poscar: str | None = None, ) -> SpinBasisAnalysis: """Symmetry-adapted spin bases at one q point, classified. The computation behind ``crystod-mag --qpoint``: the spin representation is projected onto the irreps of the little group, the FM/AFM combinations are separated at q = 0 (copies of an irrep that do not separate cleanly when made real one by one, or whose partners do not lie along directions symmetry fixes -- in a trigonal or hexagonal crystal: not along the a axis of the input cell and perpendicular to it, :func:`_canonical_spin_partners` -- are redone through the real form of the irrep with canonical partners: :func:`_canonical_spin_spaces`; an irrep that occurs more than once in a single moment is separated by the uniform moments, :func:`_uniform_moment_spaces`; a complex irrep and its conjugate are merged into one real two-dimensional space under their pair label, :func:`_merged_pair_spaces`, and so at the other time-reversal-invariant q points, where a pair of d-dimensional irreps gives a real 2d-dimensional space, :func:`_real_pair_rows`), every basis vector is resolved into its exported components (x/y/z/110/..., or comp<N>, with the (a,a) / (a,a,0) combination where symmetry singles it out and x+y+z of an x/y/z space: :func:`_combined_components`), the real spin field of each component over the magnetic cell is built (lattice gauge: the spin of site j in the cell at T is ``Re(w_j exp(2 pi i q.T))``; global phase as in the VESTA export, largest moment 1), and with ``classify`` every component gets its magnetic space group (:func:`crystod.magnetic_group.magnetic_space_group`), the responses its magnetic point group allows (:func:`crystod.magnetic_group.macroscopic_responses`) and its collinear class (:func:`crystod.magnetic_group.classify_collinear`). At a q that is not time-reversal invariant the order parameter of a d-dimensional copy is complex (the field Re[eta w exp(2 pi i q.T)] depends on the phase of eta), so a copy has 2d basis rows, w_1 .. w_d and i w_1 .. i w_d (``comp1 .. comp<2d>``; the global phase is fixed once per copy, from its first row, so the fields of the rows w_k are those of before, and each partner is signed with its largest moment component along the crystal axes positive); copies of an irrep that occurs more than once are first chosen so that the operations taking q to -q keep each of them (:func:`_resplit_copies`). At every q != 0 the order-parameter directions (strata) of every basis are enumerated in the magnetic cell: the operations of the crystal with the cell translations and time reversal act on the real span of the basis fields, and the strata of that matrix group are found as ``crystod-mag --parent`` finds them (``IsotropyAnalyzer.enumerate_directions``). Every component is assigned to its stratum; a one-parameter direction that no component lies on is exported as ``dir<k>``; at a special point the directions get ISOTROPY's labels from :func:`crystod.magnetic_isotropy.magnetic_isotropy_subgroups_at_kpoint` (matched by BNS number, index, free parameters and size), and the rows of the table that the magnetic cell does not realize are listed (:attr:`SpinBasisAnalysis.directions`). Args: cell: The crystal (phonopy ``PhonopyAtoms``, e.g. from ``phonopy.interface.vasp.read_vasp``); not needed when ``vibrations`` is given. element: Element whose sites carry the spins (``"Ni"``). qpoint: ``--qpoint`` tokens: one label (``"GM"``, ``"X"``) or three coordinates in the primitive reciprocal basis (fractions such as ``"1/2"`` allowed); a single string is one label. symprec: Symmetry tolerance (spglib, Angstrom); the sites are matched within the tolerance of ``vibrations`` (this one when the cell is given). conventional: Build the magnetic cell from the conventional cell (``crystod-mag --conventional``). classify: Compute the magnetic groups, responses and classes. vibrations: A prebuilt ``SymmetryOnlyVibrations(cell, standardize=False)`` (the CLI passes its own). subgroup_poscar: A low-symmetry structure of the same compound (POSCAR or CIF, a primitive cell) whose cell is a magnetic cell of q (``crystod-mag --subgroup-poscar CHILD``): the bases are placed on it through the transformation of ``crystod-group --correlate --supergroup-poscar --subgroup-poscar`` and aligned with its structural domain (:func:`_align_with_subgroup`, :attr:`SpinBasisAnalysis.subgroup`). q != 0 only. Returns: A :class:`SpinBasisAnalysis`. Raises: SystemExit: The element is not in the cell (``ValueError`` through ``crystod.mag``); the subgroup structure cannot be read or mapped onto the crystal. ValueError: Unknown q-point label; the cell is not primitive; q is not commensurate with a magnetic cell of at most 12 cells along each axis (the message names the smallest commensurate supercell); a subgroup structure at q = 0, one that is not primitive, or one whose cell q does not fold onto Gamma of. Example: >>> from phonopy.interface.vasp import read_vasp >>> from crystod import mag >>> cell = read_vasp("example/test_POSCARs/136_PPOSCAR_TiO2") >>> result = mag.analyze_spin_basis(cell, "Ti", "GM") >>> [(c.header, c.tag, c.collinear.short_name) for c in result.components][-1] ('GM2+(1) [AFM, octupole]', 'z', 'altermagnet (d-wave)') """ from .magnetic_group import ( classify_collinear, macroscopic_responses, magnetic_cell_translations, magnetic_space_group, ) if vibrations is None: vibrations = SymmetryOnlyVibrations(cell=cell, symprec=symprec, standardize=False) _require_primitive(vibrations) primitive = vibrations.primitive_cell symbols = list(primitive.symbols) positions = primitive.scaled_positions lattice = np.array(primitive.cell) site_indices = [i for i, s in enumerate(symbols) if s == element] if not site_indices: available = ", ".join(sorted(set(symbols))) raise SystemExit(f"ERROR: element '{element}' is not in this POSCAR ({available}).") n_sites = len(site_indices) tokens = [qpoint] if isinstance(qpoint, str) else [str(token) for token in qpoint] qpoint_label, qpoint = vibrations.resolve_qpoint(tokens) is_gamma = np.allclose(qpoint, 0.0) if subgroup_poscar is not None: if is_gamma: raise ValueError("--subgroup-poscar aligns the bases at q != 0 with a subgroup " "structure; at GM run crystod-mag on that structure itself.") if not os.path.isfile(str(subgroup_poscar)): raise SystemExit(f"ERROR: subgroup structure not found: {subgroup_poscar}") irreps, spin_rep, mapping = get_spin_representation(vibrations, site_indices, qpoint) irrep_labels = vibrations.get_irrep_labels(qpoint, irreps, mapping) # the projected rows carry the Bloch factor of each site's position # (spgrep's convention, as phonopy's eigenvectors); the spin of site j in # the cell at lattice translation T is Re(w_j exp(2 pi i q.T)) with # w_j = v_j exp(2 pi i q.x_j), the lattice gauge, real at a # time-reversal-invariant q for the irreps of real type (x_j symmetrized # as in get_spin_representation: the input positions of a structure at # its ideal positions) ideal_positions = _symmetrized_site_positions(vibrations, site_indices) gauge = np.repeat(np.exp(2j * np.pi * (ideal_positions @ np.asarray(qpoint))), 3) raw_spaces: list[NDArray] = [] raw_labels: list[str] = [] raw_irrep_indices: list[int] = [] raw_copies: dict[int, list[NDArray]] = {} for irrep_index, (irrep, label) in enumerate(zip(irreps, irrep_labels)): for space in project_to_irrep(spin_rep, irrep): space = np.asarray(space, dtype=complex) * gauge[None, :] raw_copies.setdefault(irrep_index, []).append(space) realified = _realify(space) raw_spaces.append(realified if realified is not None else space) raw_labels.append(label) raw_irrep_indices.append(irrep_index) total_dim = sum(space.shape[0] for space in raw_spaces) # at a time-reversal-invariant q (q = 0 and the other points with 2q a # reciprocal lattice vector) a complex irrep and its conjugate form one # physically irreducible real space, listed once under their pair label time_reversal_invariant = np.allclose(2.0 * np.asarray(qpoint), np.rint(2.0 * np.asarray(qpoint))) conjugate_pairs = ( _conjugate_pairs(irreps, irrep_labels, set(raw_irrep_indices)) if time_reversal_invariant else {} ) second_members = {second: first for first, second in conjugate_pairs.items()} def display_label(irrep_index: int) -> str: first = second_members.get(irrep_index, irrep_index) if first in conjugate_pairs: return _pair_label(irrep_labels[first], irrep_labels[conjugate_pairs[first]]) return irrep_labels[irrep_index] counted: dict[str, int] = {} for label, irrep_index in zip(raw_labels, raw_irrep_indices): if irrep_index in second_members: continue name = display_label(irrep_index) counted[name] = counted.get(name, 0) + 1 # FM/AFM separation (Gamma only) and multipole-rank naming entries = [] # (label, kind, rank_name, space) partner_entries: dict[int, int] = {} # entry index -> d, rows d..2d-1 are i w_k if is_gamma: rank_lists = get_multipole_rank_lists( vibrations, vibrations.rotations[mapping], irreps ) label_to_irrep_index: dict[str, int] = {} for label, irrep_index in zip(raw_labels, raw_irrep_indices): label_to_irrep_index.setdefault(label, irrep_index) little_group = None conventional_lattice = None hexagonal_family = 143 <= int(vibrations.spglib_dataset["number"]) <= 194 nearest: list = [] def pairs(): from .symmetry_adapted_modes import _nearest_images if not nearest: nearest.append(_nearest_images( little_group.positions, lattice, little_group.inverse_axes )) return nearest[0] def add_entries(label: str, irrep_index: int, ordered) -> None: # multipole ranks of this irrep in increasing order # (FM = lowest rank = dipole, then octupole, ...) ranks = rank_lists[irrep_index] for position, (kind, space) in enumerate(ordered): rank = ranks[position] if position < len(ranks) else None rank_name = MULTIPOLE_NAMES.get(rank, f"rank{rank}") if rank else "multipole" entries.append((label, kind, rank_name, space)) for label in dict.fromkeys(raw_labels): irrep_index = label_to_irrep_index[label] if irrep_index in second_members: continue # listed with the first member of its pair if irrep_index in conjugate_pairs: if little_group is None: little_group, conventional_lattice = _spin_little_group( vibrations, mapping, site_indices ) merged = _merged_pair_spaces( raw_copies[irrep_index], n_sites, little_group, conventional_lattice, pairs, ) if merged is not None: ferro_list, afm_list = merged add_entries(display_label(irrep_index), irrep_index, [("FM", space) for space in ferro_list] + [("AFM", space) for space in afm_list]) continue group = [space for space, l in zip(raw_spaces, raw_labels) if l == label] with warnings.catch_warnings(), np.errstate(all="ignore"): warnings.simplefilter("ignore") ferro, afm_list = separate_ferro_combination(group, spin_rep, n_sites) clean = _separation_clean(ferro, afm_list, spin_rep, n_sites) if clean and hexagonal_family and group[0].shape[0] > 1: # symmetry-fixed partners, but possibly not the canonical ones: # which of the equivalent in-plane axes (a, b, a+b and the # directions perpendicular to them) the copies made real one # by one pick depends on the orientation of the input cell; # kept only when the canonical choice merely reorders or # negates them (other crystal systems keep them as they are) if little_group is None: little_group, conventional_lattice = _spin_little_group( vibrations, mapping, site_indices ) reference = np.real(ferro if ferro is not None else afm_list[0]) reference = reference / np.linalg.norm(reference, axis=1)[:, None] clean = _is_signed_permutation(_canonical_spin_partners( reference, spin_rep, little_group, conventional_lattice )) if not clean: # the copies made real one by one are not aligned or not along # the canonical symmetry-fixed directions (2-dim irreps that # spgrep gives in a complex basis: E of trigonal and hexagonal # groups, rutile GM5+): project onto the real form of the # irrep, separate the copies partner by partner and turn the # partners onto the directions symmetry fixes if little_group is None: little_group, conventional_lattice = _spin_little_group( vibrations, mapping, site_indices ) canonical = _canonical_spin_spaces( spin_rep, irreps[label_to_irrep_index[label]], n_sites, little_group, conventional_lattice, pairs, ) if canonical is not None: n_copies = len(canonical[1]) + (canonical[0] is not None) better = (_separation_consistent(*canonical, n_sites) or not _all_finite(ferro, afm_list)) if n_copies == len(group) and better: ferro, afm_list = canonical ordered = [] if ferro is not None: ordered.append(("FM", np.real(ferro))) ordered.extend(("AFM", np.real(afm)) for afm in afm_list) if not _separation_consistent(ferro, afm_list, n_sites): # the irrep occurs more than once in a single moment (more # than one FM combination: monoclinic and triclinic crystals) if little_group is None: little_group, conventional_lattice = _spin_little_group( vibrations, mapping, site_indices ) # the frame of the partner conventions; a triclinic crystal # has no preferred axes, and the Cartesian axes are taken triclinic = int(vibrations.spglib_dataset["number"]) <= 2 frame = np.eye(3) if triclinic else _partner_frame(conventional_lattice) uniform = _uniform_moment_spaces(group, n_sites, frame, little_group, pairs) if uniform is not None: ordered = uniform add_entries(label, irrep_index, ordered) else: frame = inverse_axes = None if conjugate_pairs: pair_group, conventional_lattice = _spin_little_group( vibrations, mapping, site_indices ) frame = _partner_frame(conventional_lattice) inverse_axes = pair_group.inverse_axes for label, space, irrep_index in zip(raw_labels, raw_spaces, raw_irrep_indices): if irrep_index in second_members: continue # listed with the first member of its pair if irrep_index in conjugate_pairs: # the real and imaginary parts of the copy (lattice gauge, # where the representation is real) span one real space of # twice the dimension, as at q = 0, under the pair label of # the decomposition space = _real_pair_rows(np.asarray(space), n_sites, frame, inverse_axes) label = display_label(irrep_index) elif not time_reversal_invariant: # the order parameter of a copy at a q that is not # time-reversal invariant is complex: the field of i w (its # phase turned by 90 degrees) is as physical as that of w, # and the d rows w_k and the d rows i w_k span the real # 2d-dimensional order-parameter space space = np.asarray(space, dtype=complex) partner_entries[len(entries)] = space.shape[0] space = np.vstack([space, 1j * space]) entries.append((label, "AFM (q != 0)", None, space)) # commensurate (magnetic) supercell for q != 0 if is_gamma: supercell_sizes = np.array([1, 1, 1], dtype=int) else: supercell_sizes = np.array( [ 1 if abs(component) < 1e-10 else Fraction(float(component)).limit_denominator(_MAX_CELL_MULTIPLE).denominator for component in qpoint ], dtype=int, ) # Display cell for the VESTA/MAGMOM output: rows of cell_matrix are the # display-cell lattice vectors in primitive units. With --conventional the # conventional cell is used (times commensurate multiples for q != 0); # wrapping an atom by a display-cell vector leaves its Bloch phase # unchanged because q . S_row is an integer by construction. centring = None multiples = None if conventional: from .phonon_vector import get_commensurate_supercell_matrix, get_conventional_matrix centring = vibrations.spglib_dataset["international"][0] base_matrix = get_conventional_matrix(centring) cell_matrix = np.array(get_commensurate_supercell_matrix(qpoint, base_matrix), dtype=int) multiples = np.rint( np.diag(cell_matrix @ np.linalg.inv(np.array(base_matrix, dtype=float))) ).astype(int) conventional_note = conventional_cell_note( vibrations, centring, base_matrix, int(round(abs(np.linalg.det(cell_matrix))))) else: cell_matrix = np.diag(supercell_sizes) # the sizes come from the denominators of q up to _MAX_CELL_MULTIPLE: a q # that does not fit (0.15 = 3/20 in a 1x1x7 cell) would leave a slice of # the modulation, with a spurious net moment, MSG and class problem = _commensurability_error(qpoint, cell_matrix, conventional) if problem is not None: raise ValueError(problem) inverse_cell = np.linalg.inv(np.array(cell_matrix, dtype=float)) cell_translations = magnetic_cell_translations(cell_matrix) supercell_lattice = np.array(cell_matrix, dtype=float) @ lattice supercell_symbols: list[str] = [] supercell_positions: list[NDArray[np.float64]] = [] supercell_site_of_atom: list[int | None] = [] # magnetic-site index or None supercell_cell_of_atom: list[int] = [] # index into cell_translations # atom-major order (phonopy's SPOSCAR): every atom of the primitive cell # is followed by its images in the other cells, so the species blocks of # the input stay grouped (one POTCAR block per species) for i, symbol in enumerate(symbols): for t_index, translation in enumerate(cell_translations): supercell_symbols.append(symbol) frac_cell = (positions[i] + translation) @ inverse_cell supercell_positions.append(frac_cell - np.floor(frac_cell)) supercell_site_of_atom.append(site_indices.index(i) if i in site_indices else None) supercell_cell_of_atom.append(t_index) supercell_positions = np.array(supercell_positions) cell_phases = [np.exp(2j * np.pi * np.dot(qpoint, t)) for t in cell_translations] type_numbers = {symbol: n + 1 for n, symbol in enumerate(dict.fromkeys(supercell_symbols))} numbers = [type_numbers[symbol] for symbol in supercell_symbols] # the spin representation acting on the lattice-gauge vectors of the spaces lattice_representation = gauge[None, :, None] * spin_rep * np.conj(gauge)[None, None, :] from .symmetry_adapted_modes import _axes_sign action = None if not is_gamma: action = _MagneticCellAction(vibrations, site_indices, qpoint, cell_matrix, cell_translations, lattice) if partner_entries: entries = _resplit_copies(action, entries, partner_entries, cell_phases, n_sites) axes_cache: list = [] def inverse_axes_of() -> NDArray[np.float64]: # the unit conventional axes of _conventional_rows, as the partner # conventions use them if not axes_cache: conventional_rows = _conventional_rows(vibrations) @ lattice axes = conventional_rows / np.linalg.norm(conventional_rows, axis=1)[:, None] axes_cache.append(np.linalg.inv(axes)) return axes_cache[0] components: list[SpinBasisComponent] = [] entry_component_counts: list[int] = [] # basis rows of every entry for entry_index, (label, kind, rank_name, space) in enumerate(entries): half = partner_entries.get(entry_index) component_tags = [] component_vectors = [] for c in range(space.shape[0]): vector = np.asarray(space[c]) # a partner i w_k is named after w_k (its field is along the same # axes): the axis tag of a collinear w_k, else comp<N> named = vector if half is None or c < half else -1j * vector result = _direction_tag(np.real(named), n_sites) if np.abs(np.imag(named)).max() < 1e-8 else None if result is None: component_tags.append(f"comp{c + 1}") component_vectors.append(vector) else: tag, sign = result component_tags.append(tag) component_vectors.append(vector if named is not vector else sign * vector) export_list = list(zip(component_tags, component_vectors)) entry_component_counts.append(len(export_list)) # the (a,a) / (a,a,0) direction of the order parameter where symmetry # singles it out, and (a,a,a) of an x/y/z basis (in Pm-3m, GM4+ gives # Cmm'm' and R-3m' besides P4/mm'm'; in I4/mmm, GM5+ gives Fm'm'm # besides Im'm'm); of the rows w_k only where they come with partners n_named = len(component_tags) if half is None else half export_list.extend( _combined_components(component_tags[:n_named], component_vectors[:n_named], lattice_representation) ) shared_phase = None for position, (tag, vector) in enumerate(export_list): # spin field over the magnetic supercell: S_i(T) = Re(S_i exp(2 pi i q.T)) field = np.array( [ np.asarray(vector).reshape(n_sites, 3) * phase for phase in cell_phases ] ) # (n_cells, n_sites, 3) if half is None: sum_of_squares = np.sum(field * field) if abs(sum_of_squares) > 1e-12: field = field * np.exp(-0.5j * np.angle(sum_of_squares)) else: # one global phase for the whole copy, from its first row as # for the other bases, so that i w_k stays the partner of w_k # (a phase fixed component by component would turn it back); # at a q that is not time-reversal invariant the sum over the # cells of exp(4 pi i q.T) vanishes and the phase is kept if shared_phase is None: sum_of_squares = np.sum(field * field) shared_phase = (np.exp(-0.5j * np.angle(sum_of_squares)) if abs(sum_of_squares) > 1e-12 else 1.0) field = field * shared_phase field = np.real(field) if half is not None and half <= position < 2 * half: # the partner signed with its largest moment component along # the crystal axes positive field = field * _axes_sign(field, inverse_axes_of()) max_norm = float(np.max(np.linalg.norm(field, axis=2))) if max_norm < 1e-12: components.append(SpinBasisComponent(entry_index, label, kind, rank_name, tag, None)) continue field = field / max_norm net = np.sum(field[0], axis=0) if is_gamma else np.sum(field, axis=(0, 1)) components.append( SpinBasisComponent(entry_index, label, kind, rank_name, tag, field, net) ) # the order-parameter directions (strata) of every basis at q != 0, in # the magnetic cell, and a component for every one-parameter direction # that no exported component lies in directions: list[OrderParameterDirection] = [] direction_notes: list[str] = [] direction_spaces: list[_DirectionSpace] = [] generic_of: list = [] # (direction with n_free >= 2, a generic field of it) if not is_gamma: extended: list[SpinBasisComponent] = [] for members in _invariant_entry_groups(action, components, entry_component_counts): entry_index = members[0] label, kind, rank_name, _ = entries[entry_index] if len(members) > 1: # the space of one basis is not kept by the operations that # take q to -q (a copy of an irrep that occurs more than once, # or an irrep paired with another one): the directions of the # joint space of the bases label = " + ".join(entries[m][0] for m in members) own = [c for m in members for c in components if c.entry_index == m] basis = [c for m in members for c in [c for c in components if c.entry_index == m][ : entry_component_counts[m]]] found = None if all(c.field is not None for c in basis): found = _entry_directions(action, entry_index, label, basis, own, inverse_axes_of()) if found is None: direction_notes.append( f"{label}: the order-parameter directions were not enumerated (the " "fields of the basis do not span a space the operations keep).") extended.extend(own) continue entry_directions, assigned, new_fields, generic_fields, space = found space.components = own direction_spaces.append(space) generic_of.extend((entry_directions[s], field) for s, field in generic_fields) for component, s in zip(own, assigned): component.stratum = s for k, (s, field) in enumerate(new_fields): tag = f"dir{k + 1}" net = np.sum(field, axis=(0, 1)) component = SpinBasisComponent(entry_index, entries[entry_index][0], kind, rank_name, tag, field, net) component.stratum = s entry_directions[s].component = tag entry_directions[s]._source = component own.append(component) for component in own: if component.stratum is not None: component.direction = entry_directions[component.stratum] extended.extend(own) directions.extend(entry_directions) # in the order of the bases, the dir<k> components after the others components = sorted(extended, key=lambda c: c.entry_index) def group_of(field: NDArray[np.float64]): # spglib cell of the magnetic cell: the spins on the magnetic sites, # zero on the other atoms magmoms = np.zeros((len(supercell_symbols), 3)) for atom_index, site in enumerate(supercell_site_of_atom): if site is not None: magmoms[atom_index] = field[supercell_cell_of_atom[atom_index], site] try: return magnetic_space_group( supercell_lattice, supercell_positions, numbers, magmoms, symprec=symprec ) except SystemExit: return None for component in components: field = component.field if not classify or field is None: continue if not np.all(np.isfinite(field)): continue component.group = group_of(field) if component.group is not None: component.responses = macroscopic_responses(component.group) component.collinear = classify_collinear( vibrations.rotations, vibrations.translations, positions, site_indices, cell_matrix, field, lattice, symprec=vibrations.symprec, ) if classify: for direction, field in generic_of: group = group_of(field) if group is not None and group.identified: direction.bns_number = group.bns_number direction.bns_symbol = group.bns_symbol if directions: table = _isotropy_table(int(vibrations.spglib_dataset["number"]), qpoint_label) directions, label_notes = _label_directions(directions, table) direction_notes.extend(label_notes) for component in components: direction = component.direction if direction is None or direction.n_free != 1: continue component.direction_label = direction.direction_label group = component.group if group is not None and group.identified: component.direction_subgroup = f"{group.bns_number} {group.bns_symbol}" # the dir<k> components numbered in the order of the table reordered: list[SpinBasisComponent] = [] for entry_index in range(len(entries)): own = [c for c in components if c.entry_index == entry_index] added = [getattr(d, "_source", None) for d in directions if d.entry_index == entry_index and d.realized] added = [c for c in added if c is not None and c.tag.startswith("dir")] for k, component in enumerate(added): component.tag = f"dir{k + 1}" reordered.extend([c for c in own if not c.tag.startswith("dir")] + added) components = reordered # VESTA file names (and the tags made unique the same way) formula = reduced_formula(symbols) conv_tag = "_conv" if conventional else "" used_names: set[str] = set() for component in components: if component.field is None: continue short_label = component.label.split("(")[0].strip() rank_tag = component.rank_name if component.rank_name else ( "FM" if component.kind == "FM" else qpoint_label) name = f"POSCAR_{formula}_spin_{short_label}_{rank_tag}_{component.tag}{conv_tag}.vesta" file_tag = component.tag if name in used_names: stem = name[: -len(".vesta")] suffix = 2 while f"{stem}_{suffix}.vesta" in used_names: suffix += 1 name = f"{stem}_{suffix}.vesta" file_tag = f"{component.tag}_{suffix}" used_names.add(name) component.vesta_name = name component.file_tag = file_tag for direction in directions: # the direction names its component by the unique tag (z_2) source = getattr(direction, "_source", None) if source is not None: direction.component = source.file_tag or source.tag dataset = vibrations.spglib_dataset analysis = SpinBasisAnalysis( element=element, space_group=str(dataset["international"]), space_group_number=int(dataset["number"]), site_indices=site_indices, site_positions=np.array([positions[i] for i in site_indices]), qpoint_label=qpoint_label, qpoint=qpoint, is_gamma=bool(is_gamma), decomposition=counted, total_dim=total_dim, entries=entries, supercell_sizes=supercell_sizes, cell_matrix=np.asarray(cell_matrix, dtype=int), conventional_centring=centring, conventional_multiples=multiples, conventional_note=conventional_note if conventional else None, cell_translations=cell_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, components=components, formula=formula, symbols=symbols, pair_labels=[display_label(first) for first in conjugate_pairs], primitive_lattice=lattice, conventional_lattice=_conventional_rows_of(dataset) @ lattice, parent_rotations=np.array([lattice.T @ rotation @ np.linalg.inv(lattice.T) for rotation in vibrations.rotations]), parent_translations=np.array([translation @ lattice for translation in vibrations.translations]), directions=directions, direction_notes=direction_notes, ) # the order-parameter spaces with the group acting on them (the strata # and their domains), for the alignment with a subgroup structure analysis._direction_spaces = direction_spaces if subgroup_poscar is not None: analysis.subgroup = _align_with_subgroup( analysis, primitive, str(subgroup_poscar), tolerance=max(float(vibrations.symprec), _SUBGROUP_TOLERANCE), classify=classify) return analysis
def _conventional_rows_of(dataset) -> NDArray[np.float64]: """Rows of the conventional cell in the primitive basis (the matrix of ``--conventional``; the unit matrix for a P lattice).""" from .phonon_vector import get_conventional_matrix return np.array(get_conventional_matrix(str(dataset["international"])[0]), dtype=float) # --------------------------------------------------------------------------- # Order-parameter directions at q != 0 (the strata of the real order-parameter # space of one basis, in the magnetic cell) # ---------------------------------------------------------------------------
[docs] @dataclass(eq=False) class OrderParameterDirection: """One order-parameter direction (stratum) of a spin basis at q != 0. The rows of the ``* Order-parameter directions *`` block of ``crystod-mag --qpoint`` (:attr:`SpinBasisAnalysis.directions`). Attributes: entry_index: Index of the basis in ``SpinBasisAnalysis.entries`` (the first basis of the irrep for a table row that the magnetic cell does not realize). label: The irrep label of the basis (``"K3(1)"``). direction_label: ISOTROPY's label of the direction (``"K3(a;0.974a)"``, several joined by ``" or "`` when the cell cannot tell them apart), or None when the q point has no table or no row matches. bns_number: BNS number of the magnetic isotropy subgroup (``"193.255"``): of the spin field of the exported component, or of the table row for a direction that is not exported; None for a direction with more than one free parameter that the table does not name, and without classification. bns_symbol: Its BNS symbol (``"P6_3/m'cm"``), or None. size: Volume of the lattice of the translations (without time reversal) that keep the direction, in primitive cells. index: Number of domains, [G1' : H] (the whole paramagnetic group G1', not only the operations that keep the star arm). n_free: Free parameters of the direction. component: Tag (``file_tag``) of the exported component in this stratum (``"comp1"``, ``"aa0"``, ``"dir1"``), else None (a direction with more than one free parameter, or a table row the magnetic cell does not realize). coefficients: Coefficients of the one-parameter direction in the basis of the exported basis components (``comp1 .. comp<n>`` or ``x``/``y``/``z``, as printed in the listing and the ``MAGMOM`` lines: spin field = sum_k c_k field_k), unit length; None for ``n_free >= 2``. realized: False for a table row that no direction of the magnetic cell realizes (a direction over several star arms whose arms are not all in the cell). """ entry_index: int label: str direction_label: str | None bns_number: str | None bns_symbol: str | None size: int | None index: int | None n_free: int component: str | None = None coefficients: NDArray[np.float64] | None = None realized: bool = True @property def subgroup(self) -> str | None: """``"193.255 P6_3/m'cm"`` or None.""" if self.bns_number is None: return None return f"{self.bns_number} {self.bns_symbol}"
class _CellRepresentation: """The representation of G1' on the real order-parameter space of one basis over the magnetic cell, in the shape :class:`IsotropyAnalyzer` enumerates (``image_elements``, ``dimension``, ``arm_chunks``, ``grid_n``, ``algebra.n_ops``); the elements are ``(i, c, D)`` with ``i`` the coset representative (``i + n_ops``: with time reversal, ``-D``) and ``c`` the class of cell translations that act alike.""" def __init__(self, elements, dimension: int, n_ops: int): from types import SimpleNamespace self.elements = elements self.dimension = dimension self.arm_chunks = [dimension] self.grid_n = 1 self.label = "" self.algebra = SimpleNamespace(n_ops=n_ops) def image_elements(self): return self.elements class _MagneticCellAction: """The space group of the crystal acting on real spin fields over the magnetic cell. An operation {R|t} takes the spin S of the site at x to ``det(R) R S`` on the site at ``R x + t``, found modulo the magnetic cell; the operations kept are those that map q onto +q or -q (the others take a field of the star arm to another arm, outside the space of one basis). The cell translations are composed from the three primitive translations. """ def __init__(self, vibrations: SymmetryOnlyVibrations, site_indices: list[int], qpoint, cell_matrix, cell_translations: list, lattice: NDArray[np.float64]): positions = np.asarray(vibrations.primitive_cell.scaled_positions, dtype=float) sites = positions[list(site_indices)] self.n_sites = len(site_indices) self.n_cells = len(cell_translations) self.n_ops = len(vibrations.rotations) cell_matrix = np.asarray(cell_matrix, dtype=float) self.cell_translations = np.rint(np.array(cell_translations)).astype(int) adjugate_scale = int(round(abs(np.linalg.det(cell_matrix)))) inverse_cell = np.linalg.inv(cell_matrix) self._scale = adjugate_scale self._inverse_cell = inverse_cell self._cell_index = {self._key(t): c for c, t in enumerate(self.cell_translations)} lattice = np.asarray(lattice, dtype=float) tolerance = float(vibrations.symprec) q = np.asarray(qpoint, dtype=float) self.operations = [] # (coset index, destination (n_cells * n_sites), Cartesian) self.identity = None for i, (rotation, translation) in enumerate(zip(vibrations.rotations, vibrations.translations)): rotation = np.asarray(rotation, dtype=float) image_q = q @ np.linalg.inv(rotation) if not (np.allclose(image_q - q, np.rint(image_q - q), atol=1e-6) or np.allclose(image_q + q, np.rint(image_q + q), atol=1e-6)): continue moved = sites @ rotation.T + np.asarray(translation, dtype=float) permutation, shifts = [], [] for point in moved: diff = point[None, :] - sites residual = diff - np.rint(diff) distances = np.linalg.norm(residual @ lattice, axis=1) site = int(np.argmin(distances)) if distances[site] > max(tolerance, 1e-5): break permutation.append(site) shifts.append(np.rint(diff[site]).astype(int)) else: images = self.cell_translations @ np.rint(rotation).astype(int).T cartesian = lattice.T @ rotation @ np.linalg.inv(lattice.T) cartesian = cartesian * np.linalg.det(cartesian) if (np.allclose(rotation, np.eye(3)) and np.allclose(np.asarray(translation) - np.rint(translation), 0.0, atol=1e-6)): self.identity = i # where site j of cell c goes (R (x_j + T_c) + t = x_p(j) + # L_j + R T_c), as an index cell * n_sites + site source = np.empty((self.n_cells, self.n_sites), dtype=int) for j in range(self.n_sites): cells = [self._cell_index[self._key(t)] for t in images + shifts[j]] source[:, j] = np.array(cells) * self.n_sites + permutation[j] self.operations.append((i, source.ravel(), cartesian)) self.generators = [] for axis in range(3): step = np.eye(3, dtype=int)[axis] target = np.array([self._cell_index[self._key(t + step)] for t in self.cell_translations]) source = (target[:, None] * self.n_sites + np.arange(self.n_sites)[None, :]) self.generators.append(source.ravel()) def _key(self, translation) -> tuple: fraction = np.asarray(translation, dtype=float) @ self._inverse_cell scaled = np.rint(fraction * self._scale).astype(int) % self._scale return tuple(int(value) for value in scaled) @staticmethod def _apply(fields: NDArray[np.float64], target: NDArray[np.int_], cartesian: NDArray[np.float64] | None) -> NDArray[np.float64]: """Images of fields ``(k, n_cells * n_sites, 3)``: the spin of (cell, site) number ``a`` goes to number ``target[a]``.""" image = np.empty_like(fields) image[:, target] = fields if cartesian is None else fields @ cartesian.T return image def outside(self, basis: NDArray[np.float64]) -> NDArray[np.float64] | None: """The parts of the images of orthonormal fields (columns) that leave their span, as columns, or None when the span is invariant.""" n = basis.shape[1] fields = basis.T.reshape(n, self.n_cells * self.n_sites, 3) images = [self._apply(fields, target, cartesian).reshape(n, -1) for _, target, cartesian in self.operations] images += [self._apply(fields, target, None).reshape(n, -1) for target in self.generators] stacked = np.vstack(images).T residual = stacked - basis @ (basis.T @ stacked) if np.abs(residual).max() < 1e-6: return None return residual def representation(self, basis: NDArray[np.float64]): """The matrices of the group on the span of orthonormal fields. Args: basis: Orthonormal fields as columns, ``(n_cells * n_sites * 3, n)``. Returns: ``(elements, counts)``: the ``(i, c, D)`` list of :class:`_CellRepresentation` (with time reversal) and the number of cell translations of every class ``c``; None when the span is not invariant. """ n = basis.shape[1] fields = basis.T.reshape(n, self.n_cells * self.n_sites, 3) def matrix(target, cartesian): image = self._apply(fields, target, cartesian).reshape(n, -1) return basis.T @ image.T def orthogonal(D): return np.allclose(D @ D.T, np.eye(n), atol=1e-6) rotations = [(i, matrix(target, cartesian)) for i, target, cartesian in self.operations] steps = [matrix(target, None) for target in self.generators] if not all(orthogonal(D) for _, D in rotations) or not all(orthogonal(D) for D in steps): return None classes: dict[bytes, int] = {} class_matrices: list = [] counts: list[int] = [] for translation in self.cell_translations: D = np.eye(n) for axis in range(3): D = D @ np.linalg.matrix_power(steps[axis], int(translation[axis])) key = np.round(D, 6).tobytes() if key not in classes: classes[key] = len(class_matrices) class_matrices.append(D) counts.append(0) counts[classes[key]] += 1 elements = [] for theta in (0, 1): for i, D_rotation in rotations: for c, D_translation in enumerate(class_matrices): D = D_translation @ D_rotation elements.append((i + theta * self.n_ops, c, -D if theta else D)) return elements, counts def _resplit_copies(action: _MagneticCellAction, entries: list, partner_entries: dict, cell_phases, n_sites: int) -> list: """Copies of a complex irrep chosen so that every one is kept by the operations that take q to -q. At a q that is not time-reversal invariant an irrep that occurs m > 1 times is projected out by spgrep in m copies chosen without regard to the operations that take q to -q, which mix them; the real order-parameter space of one copy is then not a space of its own. The operations of the crystal (with the cell translations) and the turn of the phase by 90 degrees (J: the field of w to that of i w) act on the joint space of the copies; the eigenspaces of a generic symmetric matrix that commutes with all of them (a fixed pseudo-random one averaged over the group) are irreducible and kept by J, i.e. the real spaces of new copies; each new copy is the projection of the old copy it overlaps most, so its rows keep the irrep matrices. Irreps that occur once, or whose copies are already kept, are left as they are, as are the copies of an irrep paired with another one (a joint space of twice the dimension). Returns the entries with the new rows. """ phases = np.asarray(cell_phases) n_cells = len(phases) def fields(rows: NDArray[np.complex128]) -> NDArray[np.float64]: values = rows.reshape(len(rows), 1, n_sites, 3) * phases[None, :, None, None] return np.real(values).reshape(len(rows), -1).T def orthonormal(columns: NDArray[np.float64]) -> NDArray[np.float64]: u, sing, _ = np.linalg.svd(columns, full_matrices=False) return u[:, sing > 1e-8 * sing.max()] by_label: dict[str, list[int]] = {} for entry_index in sorted(partner_entries): by_label.setdefault(entries[entry_index][0], []).append(entry_index) entries = list(entries) for members in by_label.values(): if len(members) < 2: continue d = partner_entries[members[0]] if all(action.outside(orthonormal(fields(entries[e][3]))) is None for e in members): continue rows = np.vstack([np.asarray(entries[e][3])[:d] for e in members]) value_fields, partner_fields = fields(rows), fields(1j * rows) both = np.hstack([value_fields, partner_fields]) Q = orthonormal(both) n = Q.shape[1] if n != 2 * len(rows): continue result = action.representation(Q) if result is None: continue coordinates = Q.T @ both turned = Q.T @ np.hstack([partner_fields, -value_fields]) J = turned @ np.linalg.inv(coordinates) S = np.random.default_rng(20261109).standard_normal((n, n)) S = S + S.T S = S + J @ S @ J.T X = sum(D @ S @ D.T for i, _, D in result[0] if i < action.n_ops) values, vectors = np.linalg.eigh((X + X.T) / 2.0) scale = max(float(np.abs(values).max()), 1e-300) clusters = [[0]] for k in range(1, n): if values[k] - values[clusters[-1][-1]] < 1e-6 * scale: clusters[-1].append(k) else: clusters.append([k]) if any(len(cluster) != 2 * d for cluster in clusters): continue new_spaces = [] for cluster in clusters: field_values = (Q @ vectors[:, cluster]).T.reshape(len(cluster), n_cells, n_sites, 3) # the row of a field: v = (2 / n_cells) sum_T field(T) exp(-2 pi i q.T) row_values = (2.0 / n_cells) * np.einsum("rcsx,c->rsx", field_values, np.conj(phases)) _, _, vh = np.linalg.svd(row_values.reshape(len(cluster), -1), full_matrices=False) span = vh[:d] best = None for e in members: old = np.asarray(entries[e][3])[:d] projected = old @ span.conj().T @ span weight = float(np.linalg.norm(projected)) if best is None or weight > best[0] + 1e-9: best = (weight, projected) projected = best[1] / np.linalg.norm(best[1][0]) new_spaces.append(np.vstack([projected, 1j * projected])) for e, space in zip(members, new_spaces): label, kind, rank_name, _ = entries[e] entries[e] = (label, kind, rank_name, space) return entries def _invariant_entry_groups(action: _MagneticCellAction, components: list, counts: list[int]) -> list[list[int]]: """The bases grouped into spaces the operations keep. Every basis whose fields span a space that the operations of the crystal keep stands alone (always at a time-reversal-invariant q, and for a copy of a complex irrep that occurs once); otherwise the bases the images of its fields reach are joined to it until the joint space is kept. Returns the groups as lists of entry indices, in entry order (a basis with a vanishing field stands alone). """ fields_of = {} for entry_index, count in enumerate(counts): own = [c for c in components if c.entry_index == entry_index][:count] if own and all(c.field is not None for c in own): fields_of[entry_index] = np.array([c.field.reshape(-1) for c in own]).T def orthonormal(columns: NDArray[np.float64]) -> NDArray[np.float64]: u, sing, _ = np.linalg.svd(columns, full_matrices=False) return u[:, sing > 1e-8 * sing.max()] pending = list(range(len(counts))) groups = [] while pending: members = [pending.pop(0)] while all(m in fields_of for m in members): basis = orthonormal(np.hstack([fields_of[m] for m in members])) residual = action.outside(basis) if residual is None: break added = [] for other in pending: if other not in fields_of: continue span = orthonormal(fields_of[other]) if np.abs(span.T @ residual).max() > 1e-6: added.append(other) if not added: break members += added pending = [p for p in pending if p not in added] groups.append(sorted(members)) return groups def _format_direction_coefficients(coefficients) -> str: """``(1,0)``, ``(0.866,0.5)``: the coefficients to three decimals.""" texts = [] for value in coefficients: text = f"{value:.3f}".rstrip("0").rstrip(".") texts.append("0" if text in ("-0", "") else text) return "(" + ",".join(texts) + ")" @dataclass(eq=False) class _DirectionSpace: """The real order-parameter space V of one basis (or of the joint space of several bases) at q != 0 with the action of the group on it, as :func:`_entry_directions` enumerated its strata (kept on the analysis for ``--subgroup-poscar``, :func:`align_with_subgroup`). Attributes: entry_index: The (first) basis, index into ``SpinBasisAnalysis.entries``. label: Its irrep label (``"K3(1)"``, ``"SM2(1) + SM2(1)"`` for a joint space). basis: The exported components whose fields span V (comp1 ..). raw: Their fields as rows, ``(n, n_cells * n_sites * 3)``. Q: Orthonormal fields spanning V as columns (QR of ``raw``). cache: The ``_RepCache`` of the group on V (in the coordinates of Q). analyzer: The ``IsotropyAnalyzer`` of that representation. strata: ``(projector, images)`` of every stratum: the projector onto its fixed space and the distinct images of that projector under the group (the domains of a one-parameter direction). directions: The :class:`OrderParameterDirection` of every stratum, in the order of ``strata``. shape: Shape of one field, ``(n_cells, n_sites, 3)``. inverse_axes: The unit conventional axes of the partner sign convention (inverted). components: Every component of the bases (``dir<k>`` included), filled in by :func:`analyze_spin_basis`. """ entry_index: int label: str basis: list raw: NDArray[np.float64] Q: NDArray[np.float64] cache: object analyzer: object strata: list directions: list shape: tuple inverse_axes: NDArray[np.float64] components: list = dataclass_field(default_factory=list) def stratum_of(self, vector: NDArray[np.float64]) -> int | None: """The stratum (index into ``strata``) of a vector of V (Q coordinates): the one whose orbit holds the fixed space of the vector's stabilizer, or None.""" from .isotropy_subgroup import _nullspace n = self.Q.shape[1] vector = vector / np.linalg.norm(vector) mask = self.cache.vector_stabilizer_mask(vector) stack = (self.cache.E[mask] - np.eye(n)[None]).reshape(-1, n) fixed = _nullspace(stack) if len(stack) else np.eye(n) fixed_projector = fixed @ fixed.T for s, (_, images) in enumerate(self.strata): if any(np.allclose(fixed_projector, image, atol=1e-6) for image in images): return s return None def coefficients_of(self, field: NDArray[np.float64]) -> NDArray[np.float64]: """Unit coefficients of a field of V in the basis components.""" c, *_ = np.linalg.lstsq(self.raw.T, np.asarray(field).reshape(-1), rcond=None) c = c / np.linalg.norm(c) c[np.abs(c) < 1e-9] = 0.0 return c def _entry_directions(action: _MagneticCellAction, entry_index: int, label: str, basis_components: list, entry_components: list, inverse_axes: NDArray[np.float64]): """The order-parameter directions of one basis in the magnetic cell. The real fields of the exported basis components span the real order-parameter space V of the basis; the group of the crystal (with the cell translations and time reversal, -1 on V) acts on V by orthogonal matrices, and the strata of that matrix group are the order-parameter directions (``IsotropyAnalyzer.enumerate_directions``). Every exported component is assigned to its stratum (the orbit holding the fixed space of its stabilizer); a one-parameter stratum without a component gets a new field (its representative direction). Returns: ``(directions, assigned, new_fields, generic_fields, space)``: the :class:`OrderParameterDirection` list (labels not set yet), the stratum index of every component of ``entry_components`` (None when not found), ``(stratum index, field)`` of the one-parameter strata that need a component, ``(stratum index, field)`` with a generic field of every stratum with more free parameters, and the :class:`_DirectionSpace`; None when the fields do not span an invariant space. """ from .isotropy_subgroup import IsotropyAnalyzer, _orth_basis, _rep_cache from .symmetry_adapted_modes import _axes_sign if not basis_components: return None raw = np.array([component.field.reshape(-1) for component in basis_components]) n = raw.shape[0] Q, R = np.linalg.qr(raw.T) signs = np.sign(np.diag(R)) signs[signs == 0] = 1.0 Q = Q * signs[None, :] if np.min(np.abs(np.diag(R))) < 1e-8 * np.max(np.abs(np.diag(R))): return None result = action.representation(Q) if result is None: return None elements, counts = result representation = _CellRepresentation(elements, n, action.n_ops) analyzer = IsotropyAnalyzer.from_representation(representation.algebra, representation) strata = analyzer.enumerate_directions() cache = _rep_cache(representation, analyzer.elements) n_group = 2 * action.n_ops * action.n_cells directions = [] orbits = [] for projector, members in strata: order = sum(counts[c] for _, c in members) kept_translations = sum(counts[c] for i, c in members if i == action.identity) n_free = _orth_basis(projector).shape[1] directions.append(OrderParameterDirection( entry_index=entry_index, label=label, direction_label=None, bns_number=None, bns_symbol=None, size=action.n_cells // max(kept_translations, 1), index=n_group // max(order, 1), n_free=n_free, )) orbits.append((projector, list(cache.orbit(projector).values()))) space = _DirectionSpace( entry_index=entry_index, label=label, basis=list(basis_components), raw=raw, Q=Q, cache=cache, analyzer=analyzer, strata=orbits, directions=directions, shape=basis_components[0].field.shape, inverse_axes=inverse_axes, ) stratum_of = space.stratum_of coefficients_of = space.coefficients_of assigned = [] for component in entry_components: if component.field is None: assigned.append(None) continue s = stratum_of(Q.T @ component.field.reshape(-1)) assigned.append(s) if s is not None and directions[s].n_free == 1 and directions[s].component is None: directions[s].component = component.tag directions[s]._source = component directions[s].coefficients = coefficients_of(component.field) new_fields = [] generic_fields = [] shape = basis_components[0].field.shape for s, (projector, _) in enumerate(orbits): if directions[s].n_free > 1: # a generic field of the stratum, for its magnetic space group generic = analyzer.direction_label(projector)[1] generic_fields.append((s, (Q @ generic).reshape(shape))) continue if directions[s].component is not None: continue field = (Q @ _orth_basis(projector)[:, 0]).reshape(shape) field = field * _axes_sign(field, inverse_axes) field = field / float(np.max(np.linalg.norm(field, axis=-1))) directions[s].coefficients = coefficients_of(field) new_fields.append((s, field)) return directions, assigned, new_fields, generic_fields, space _TABLE_CACHE: dict = {} def _isotropy_table(space_group_number: int, qpoint_label: str) -> dict | None: """``crystod-mag --parent`` rows at a special point (cached), or None.""" key = (int(space_group_number), str(qpoint_label)) if key not in _TABLE_CACHE: from .magnetic_isotropy import magnetic_isotropy_subgroups_at_kpoint try: _TABLE_CACHE[key] = magnetic_isotropy_subgroups_at_kpoint(*key) except (ValueError, SystemExit): _TABLE_CACHE[key] = None return _TABLE_CACHE[key] def _label_directions(directions: list, table: dict | None) -> list: """Name the directions after the rows of the ISOTROPY table and list the rows the magnetic cell does not realize. A direction is matched by (BNS number of its field -- of a generic field for more than one free parameter --, index, free parameters), the size deciding a tie; without classification by (index, free parameters). A direction whose group is the enantiomorphic partner type of a row's (the mirror image of the table's direction) is matched to that row, with a note. Returns ``(directions, notes)``: the directions of every basis sorted as the table sorts them (free parameters, index, BNS number), with the unrealized rows of an irrep after its last basis. """ from .isotropy_subgroup import ENANTIOMORPHIC_PAIRS for direction in directions: component = getattr(direction, "_source", None) group = component.group if component is not None else None if group is not None and group.identified: direction.bns_number = group.bns_number direction.bns_symbol = group.bns_symbol def bns_key(number: str | None) -> tuple: return tuple(int(x) for x in number.split(".")) if number else (10**6,) directions = sorted(directions, key=lambda d: (d.entry_index, d.n_free, d.index, bns_key(d.bns_number))) notes: list[str] = [] if not table: return directions, notes matched: set[tuple[str, int]] = set() for direction in directions: if " + " in direction.label: continue # the joint space of several bases has no row of its own rows = table.get(direction.label.split("(")[0].strip()) if not rows: continue candidates = [ (k, row) for k, row in enumerate(rows) if row.n_free == direction.n_free and row.index == direction.index and (direction.bns_number is None or row.bns_number == direction.bns_number) ] if not candidates and direction.bns_number is not None: # the mirror image of a direction of the same stratum gives the # enantiomorphic partner type (P4_32_12 for P4_12_12), and the # table lists one of the two family = int(direction.bns_number.split(".")[0]) partner = ENANTIOMORPHIC_PAIRS.get(family) candidates = [ (k, row) for k, row in enumerate(rows) if row.n_free == direction.n_free and row.index == direction.index and int(row.bns_number.split(".")[0]) == partner ] if candidates: notes.append( f"{direction.label.split('(')[0].strip()}: {direction.bns_number} " f"{direction.bns_symbol} is the enantiomorphic partner of the table's " f"{' or '.join(row.bns_number for _, row in candidates)} (the mirror-image " "direction of the same stratum).") if len(candidates) > 1: sized = [(k, row) for k, row in candidates if row.size == direction.size] candidates = sized or candidates if not candidates: continue direction.direction_label = " or ".join(row.label for _, row in candidates) if len(candidates) == 1 and direction.bns_number is None: direction.bns_number = candidates[0][1].bns_number direction.bns_symbol = candidates[0][1].bns_symbol matched.update((rows[0].irrep, k) for k, _ in candidates) result = list(directions) for irrep, rows in table.items(): own = [d for d in directions if " + " not in d.label and d.label.split("(")[0].strip() == irrep] if not own: continue missing = [ OrderParameterDirection( entry_index=own[0].entry_index, label=own[0].label, direction_label=row.label, bns_number=row.bns_number, bns_symbol=row.bns_symbol, size=row.size, index=row.index, n_free=row.n_free, realized=False, ) for k, row in enumerate(rows) if (rows[0].irrep, k) not in matched ] if missing: position = max(result.index(d) for d in own) + 1 result[position:position] = missing return result, notes @dataclass(eq=False) class ParentOperation: """One operation of the space group of the crystal and what an arrangement keeps of it (:func:`parent_operations`). Attributes: symbol: Seitz symbol ``{R|t}`` in the notation of Bradley and Cracknell (``"{C4z|0}"``, ``"{IC2[1-10]|0}"``, ``"{C4z|1/2,1/2,1/2}"``): E, I, C_n about the axis with the power for a turn of more than one step (``C4z^3``), I C_n for the improper operations; the axis is ``x``, ``y``, ``z`` along the axes of an orthogonal conventional cell (``z`` for c when c is perpendicular to a and b), else ``[uvw]`` in the conventional cell; t is the translation in the conventional cell, the simplest of the coset modulo the centring. rotation: Cartesian rotation matrix. translation: Cartesian translation (Angstrom). kept: The arrangement is invariant under {R|t} (with a translation of the magnetic cell where q != 0). kept_primed: It is invariant under {R|t}' = theta {R|t}, time reversal included (with an anti-translation where q != 0 and ``kept``). """ symbol: str rotation: NDArray[np.float64] translation: NDArray[np.float64] kept: bool kept_primed: bool def _lattice_direction(axis: NDArray[np.float64], conventional: NDArray[np.float64]): """Smallest integer indices [uvw] of a Cartesian direction in the conventional cell, first nonzero index positive; None when they exceed 6.""" indices = axis @ np.linalg.inv(conventional) indices = indices / np.max(np.abs(indices)) fractions = [Fraction(float(value)).limit_denominator(6) for value in indices] if any(abs(float(f) - value) > 1e-4 for f, value in zip(fractions, indices)): return None denominator = int(np.lcm.reduce([f.denominator for f in fractions])) integers = [int(f * denominator) for f in fractions] divisor = int(np.gcd.reduce([abs(i) for i in integers if i != 0])) integers = [i // divisor for i in integers] if next(i for i in integers if i != 0) < 0: integers = [-i for i in integers] return tuple(integers) def _rotation_symbol(rotation: NDArray[np.float64], conventional: NDArray[np.float64]): """Bradley-Cracknell name of a Cartesian rotation (``C4z^3``, ``IC2[110]``) and its sort key (proper operations first, the identity, then the turns about z, x, y and the other axes; by angle about each).""" determinant = int(round(np.linalg.det(rotation))) proper = rotation * determinant prefix = "I" if determinant < 0 else "" if np.allclose(proper, np.eye(3), atol=1e-6): return ("I" if determinant < 0 else "E"), (determinant < 0, 0, (), 0.0) values, vectors = np.linalg.eig(proper) axis = np.real(vectors[:, int(np.argmin(np.abs(values - 1.0)))]) indices = _lattice_direction(axis, conventional) cartesian = np.asarray(indices, dtype=float) @ conventional if indices is not None else axis cartesian = cartesian / np.linalg.norm(cartesian) cosine = np.clip((np.trace(proper) - 1.0) / 2.0, -1.0, 1.0) sine = 0.5 * np.dot(cartesian, [proper[2, 1] - proper[1, 2], proper[0, 2] - proper[2, 0], proper[1, 0] - proper[0, 1]]) angle = np.arctan2(sine, cosine) % (2.0 * np.pi) order = int(round(2.0 * np.pi / min(angle, 2.0 * np.pi - angle))) power = int(round(angle / (2.0 * np.pi / order))) % order lengths = np.linalg.norm(conventional, axis=1) cosines = [abs(np.dot(conventional[i], conventional[j])) / (lengths[i] * lengths[j]) for i, j in ((0, 1), (0, 2), (1, 2))] orthogonal = max(cosines) < 1e-6 c_normal = cosines[1] < 1e-6 and cosines[2] < 1e-6 names = {} if orthogonal: names = {(1, 0, 0): "x", (0, 1, 0): "y", (0, 0, 1): "z"} elif c_normal: names = {(0, 0, 1): "z"} if indices is None: axis_name = "[" + ",".join(f"{value:.3f}" for value in cartesian) + "]" rank = (9, ()) else: axis_name = names.get(indices, "[" + "".join(str(i) for i in indices) + "]") rank = {"z": (1, ()), "x": (2, ()), "y": (3, ())}.get( axis_name, (4, (sum(abs(i) for i in indices), tuple(-i for i in indices)))) symbol = f"{prefix}C{order}{axis_name}" + (f"^{power}" if power > 1 else "") return symbol, (determinant < 0, rank[0], rank[1], power / order) def _translation_text(translation: NDArray[np.float64], primitive: NDArray[np.float64], conventional: NDArray[np.float64]) -> str: """The translation in the conventional cell, the simplest representative modulo the primitive lattice: ``0`` or ``1/2,1/2,0``.""" inverse = np.linalg.inv(conventional) steps = primitive @ inverse # primitive vectors in conventional coordinates multiplicity = int(round(abs(np.linalg.det(conventional) / np.linalg.det(primitive)))) candidates = [] for i in range(multiplicity): for j in range(multiplicity): for k in range(multiplicity): shift = translation @ inverse + i * steps[0] + j * steps[1] + k * steps[2] shift = shift - np.floor(shift + 1e-6) shift[np.abs(shift) < 1e-6] = 0.0 candidates.append(shift) best = min(candidates, key=lambda c: (int(np.count_nonzero(np.abs(c) > 1e-6)), float(np.sum(c)))) if np.all(np.abs(best) < 1e-6): return "0" return ",".join(str(Fraction(float(value)).limit_denominator(12)) for value in best) def parent_operations(analysis: SpinBasisAnalysis, component: SpinBasisComponent): """The operations of the paramagnetic group G + theta G of the crystal, one per coset of the lattice translations, and which of {R|t} and {R|t}' = theta {R|t} an arrangement keeps. The kept operations are those of the magnetic space group of the arrangement (spglib, :attr:`SpinBasisComponent.group`), each matched to the operation of the crystal with the same rotation and a translation that differs by a lattice vector of the primitive cell. For CeRu2Si2 (I4/mmm) with the Ce moments along z (GM3+, I4/mm'm') the kept ones are {E|0}, {C4z|0}, {C2z|0}, {C4z^3|0}, {I|0}, {IC4z|0}, {IC2z|0}, {IC4z^3|0} and {C2x|0}', {C2y|0}', {C2[110]|0}', {C2[1-10]|0}' and their products with I: the elements where the time-odd irrep mGM3+ is +1. Args: analysis: The :class:`SpinBasisAnalysis`. component: One of its components. Returns: :class:`ParentOperation` list in the order E, the turns about z, x, y and the other axes, then the same times I; None when the component has no magnetic space group (vanishing field, spglib failure) or the analysis has no operations of the crystal. """ group = component.group if group is None or component.field is None or analysis.parent_rotations is None: return None primitive = analysis.primitive_lattice conventional = analysis.conventional_lattice inverse_primitive = np.linalg.inv(primitive) flags: list[set] = [set() for _ in analysis.parent_rotations] for rotation, translation, reversed_time in zip( group.rotations, group.translations, group.time_reversals ): shift = np.asarray(translation, dtype=float) @ analysis.supercell_lattice for index, (parent_rotation, parent_translation) in enumerate( zip(analysis.parent_rotations, analysis.parent_translations) ): if not np.allclose(rotation, parent_rotation, atol=1e-5): continue difference = (shift - parent_translation) @ inverse_primitive if np.abs(difference - np.rint(difference)).max() < 1e-3: flags[index].add(bool(reversed_time)) break operations = [] for index, (rotation, translation) in enumerate( zip(analysis.parent_rotations, analysis.parent_translations) ): name, key = _rotation_symbol(rotation, conventional) symbol = "{" + name + "|" + _translation_text(translation, primitive, conventional) + "}" operations.append((key, ParentOperation(symbol, rotation, translation, False in flags[index], True in flags[index]))) operations.sort(key=lambda item: item[0]) return [operation for _, operation in operations] def format_parent_operations(analysis: SpinBasisAnalysis, component: SpinBasisComponent, indent: str = " ", per_line: int = 8) -> list[str]: """The lines of ``crystod-mag --show-operations`` for one component: the operations of the paramagnetic group (``I4/mmm1'``) the arrangement keeps and those it breaks, ``{R|t}`` first and then ``{R|t}'``. Args: analysis: The :class:`SpinBasisAnalysis`. component: One of its components. indent: Leading blanks of every line. per_line: Operations per line. Returns: The lines (no trailing newline). """ operations = parent_operations(analysis, component) if operations is None: return [f"{indent}operations: not available (no magnetic space group)"] kept = ([op.symbol for op in operations if op.kept] + [op.symbol + "'" for op in operations if op.kept_primed]) broken = ([op.symbol for op in operations if not op.kept] + [op.symbol + "'" for op in operations if not op.kept_primed]) count = len(operations) lines = [f"{indent}operations of the paramagnetic group {analysis.space_group}1' " f"({count} {{R|t}} and {count} {{R|t}}' = theta{{R|t}}, one per coset; " "t in the conventional cell):"] for title, symbols in ((f"kept ({len(kept)}):", kept), (f"broken ({len(broken)}):", broken)): width = max(len(f"kept ({len(kept)}):"), len(f"broken ({len(broken)}):")) + 1 if not symbols: lines.append(f"{indent} {title:<{width}}none") continue for start in range(0, len(symbols), per_line): head = title if start == 0 else "" lines.append(f"{indent} {head:<{width}}" + " ".join(symbols[start:start + per_line])) if any(op.kept and op.kept_primed for op in operations): lines.append(f"{indent} ({{R|t}} and {{R|t}}' both kept: the one with a translation " "of the magnetic cell, the other with an anti-translation)") return lines def _direction_text(direction: OrderParameterDirection) -> str: """The first column of the direction table: ISOTROPY's label, else the irrep with the coefficients in the basis components (one free parameter) or the number of free parameters.""" if direction.direction_label: return direction.direction_label irrep = re.sub(r"\(\d+\)", "", direction.label).strip() if direction.n_free == 1 and direction.coefficients is not None: return f"{irrep} {_format_direction_coefficients(direction.coefficients)}" return f"{irrep} ({direction.n_free} free parameters)" def _direction_line(component: SpinBasisComponent) -> str | None: """``order-parameter direction: K3(a;0.974a), magnetic isotropy subgroup 193.255 P6_3/m'cm`` for a component at q != 0, else None.""" direction = component.direction if direction is None: return None if direction.n_free > 1: where = (f"the stratum {direction.direction_label}" if direction.direction_label else "a stratum") text = (f"order-parameter direction: none of one parameter (in {where} with " f"{direction.n_free} free parameters") if direction.subgroup: text += f", magnetic isotropy subgroup {direction.subgroup}" return text + ")" text = f"order-parameter direction: {_direction_text(direction)}" if component.direction_subgroup: text += f", magnetic isotropy subgroup {component.direction_subgroup}" return text DIRECTION_TABLE_HEADERS = ( "irrep direction", "in comp basis", "subgroup (BNS)", "size", "index", "component", )
[docs] def direction_table_rows(analysis: SpinBasisAnalysis) -> list[tuple[str, ...]]: """Rows of the ``* Order-parameter directions *`` block. Args: analysis: A :class:`SpinBasisAnalysis` at q != 0. Returns: One tuple per direction of :attr:`SpinBasisAnalysis.directions`: ``(direction, coefficients, subgroup, size, index, component)``, e.g. ``("K3(a;0.974a)", "(1,0)", "193.255 P6_3/m'cm", "3", "6", "comp1")``; the component is ``"free (2 parameters)"`` for a direction with more than one free parameter and ``"not in this magnetic cell"`` for a table row that the cell does not realize. """ rows = [] for direction in analysis.directions: if not direction.realized: component = "not in this magnetic cell" elif direction.n_free > 1: component = f"free ({direction.n_free} parameters)" else: component = direction.component or "-" coefficients = ("-" if direction.coefficients is None else _format_direction_coefficients(direction.coefficients)) rows.append(( _direction_text(direction), coefficients, direction.subgroup or "-", "-" if direction.size is None else str(direction.size), "-" if direction.index is None else str(direction.index), component, )) return rows
[docs] def format_direction_table(analysis: SpinBasisAnalysis) -> list[str]: """The ``* Order-parameter directions *`` block of ``crystod-mag --qpoint`` at q != 0 (no lines at q = 0). Args: analysis: A :class:`SpinBasisAnalysis`. Returns: The block as lines: title, the table (:func:`direction_table_rows`) and the notes. """ if analysis.is_gamma or not (analysis.directions or analysis.direction_notes): return [] rows = [DIRECTION_TABLE_HEADERS] + direction_table_rows(analysis) widths = [max(len(row[c]) for row in rows) for c in range(len(rows[0]))] lines = ["* Order-parameter directions *"] lines += [" " + " ".join(cell.ljust(width) for cell, width in zip(row, widths)).rstrip() for row in rows] labeled = any(d.direction_label for d in analysis.directions) lines.append("") if labeled: q_name = "GM" if analysis.qpoint_label == "GAMMA" else analysis.qpoint_label lines.append(" irrep direction: ISOTROPY's label, as crystod-mag --parent " f"{analysis.space_group_number} --qpoint {q_name} lists it") else: lines.append(" irrep direction: no table at this q; the coefficients in the basis " "components name the direction") lines += [ " in comp basis: spin field = sum_k c_k (field of the k-th basis component, as " "listed), unit length", " size: cell of the translations without time reversal, in primitive cells; " "index: number of domains", ] if any(c.tag.startswith("dir") for c in analysis.components): lines.append(" dir<k>: a one-parameter direction that no other component lies on, " "exported as a component of its own") lines += [f" NOTE: {note}" for note in analysis.direction_notes] return lines
# --------------------------------------------------------------------------- # The bases on a subgroup structure (crystod-mag --subgroup-poscar CHILD) # --------------------------------------------------------------------------- #: Tolerance (Angstrom) with which a subgroup structure is mapped onto the #: crystal and its magnetic groups are found: the default of ``crystod-group #: --correlate``, or ``--tolerance`` when that is larger. _SUBGROUP_TOLERANCE = 0.01 #: Largest distance (Angstrom) between a magnetic site of the subgroup #: structure and the site of the crystal it is mapped onto (the pairing limit #: of ``crystod-group --supergroup-cif``). _SUBGROUP_MAX_DISTANCE = 1.8
[docs] @dataclass(eq=False) class SubgroupSpinField: """One spin field of a basis on the subgroup structure: a row of the ``* Spin bases on the subgroup structure *`` block of ``crystod-mag --qpoint K --subgroup-poscar CHILD``. Attributes: entry_index: Index of the basis in ``SpinBasisAnalysis.entries``. label: Its irrep label (``"K3(1)"``). kind: ``"component"``: an exported component as it is; ``"aligned"``: the domain of a one-parameter direction whose field is one irrep of the subgroup structure at GM; ``"generic"``: a generic field of a stratum, inside one irrep of the subgroup structure or over the whole basis; ``"none"``: no domain of the one-parameter direction is one such irrep. direction: The :class:`OrderParameterDirection` (stratum) of the field, or None. tag: ``"comp1"`` (the component, its ``file_tag``), ``"comp2_GM4"`` (aligned: the component of the direction and the irrep it is turned into, unique as in the VESTA file name), ``"generic"`` or ``"-"``. child_irreps: ``[(label, weight)]``: the irreps of the subgroup structure at GM the field is made of, with the squared norms of its parts on the subgroup structure (sum 1; None for the generic rows, whose weights are arbitrary), e.g. ``[("GM1", 0.25), ("GM4", 0.75)]``. reference: The exported component an aligned row is turned from (the one on its direction), else None. group: :class:`crystod.magnetic_group.MagneticGroupInfo` of the field on the subgroup structure (spglib on its cell with these moments), None without classification. angle: Degrees between an aligned field and ``reference`` in the real order-parameter space (the phase of the order parameter at a q that is not time-reversal invariant), else None. coefficients: Coefficients in the basis components (comp1 .. comp<n>, as in :attr:`OrderParameterDirection.coefficients`), unit length; None for the generic rows. field: The spin field over the magnetic cell of the crystal (largest moment 1) of an aligned row, else None. spins: Moments on every atom of the subgroup structure (Cartesian, zero on the other atoms, largest 1) of an aligned row, else None. vesta_name: The VESTA file of an aligned row (in the cell of the subgroup structure), else empty. """ entry_index: int label: str kind: str direction: object tag: str child_irreps: list reference: str | None = None group: object = None angle: float | None = None coefficients: NDArray[np.float64] | None = None field: NDArray[np.float64] | None = None spins: NDArray[np.float64] | None = None vesta_name: str = "" @property def subgroup(self) -> str | None: """``"185.200 P6_3'cm'"`` (BNS number and symbol) or None.""" group = self.group if group is None or not getattr(group, "identified", False): return None return f"{group.bns_number} {group.bns_symbol}" @property def child_irrep_text(self) -> str: """``"GM4"``, ``"0.25 GM1 + 0.75 GM4"``, ``"GM1 + GM4"`` (generic).""" if not self.child_irreps: return "no single irrep" if len(self.child_irreps) == 1 or all(w is None for _, w in self.child_irreps): return " + ".join(label for label, _ in self.child_irreps) texts = [] for label, weight in self.child_irreps: value = f"{weight:.3f}".rstrip("0").rstrip(".") texts.append(f"{value} {label}") return " + ".join(texts)
[docs] @dataclass(eq=False) class SubgroupAlignment: """The spin bases of a q != 0 analysis placed on a subgroup structure (:attr:`SpinBasisAnalysis.subgroup`, ``crystod-mag --subgroup-poscar``). Attributes: child_file: The subgroup structure file as given. child_symbol: Its space group (``"P6_3cm"``); ``child_number`` the number. transformation: The ``SettingTransformation`` (P, p) of ``crystod-group --correlate --supergroup-poscar --subgroup-poscar``: x_parent = P x_child + p between the fractional coordinates of the two input cells. size: Primitive cells of the crystal in the cell of the subgroup structure (``|det P|``). lattice: Lattice of the subgroup structure (rows, Angstrom); ``symbols`` and ``positions`` its atoms (as the file gives them). site_atoms: Indices of its atoms of the magnetic element. site_sources: ``(site, cell)`` of each: the magnetic site of the crystal and the index into ``SpinBasisAnalysis.cell_translations`` of the cell it sits in. spin_matrix: The 3x3 map of the Cartesian spins of the crystal onto those of the subgroup structure (through the fractional components, S_parent = P S_child). folding: ``[(basis label, [irrep labels])]``: the irreps of the subgroup structure at GM that the fields of each basis are made of (``("K3(1)", ["GM1", "GM4"])``). identity_irrep: The label of its identity irrep (``"GM1"``). mulliken: Mulliken symbols of its GM irreps (``{"GM1": "A1"}``). rows: The :class:`SubgroupSpinField` rows, in the order of the directions of :attr:`SpinBasisAnalysis.directions`. notes: NOTE lines (without ``NOTE:``). """ child_file: str child_symbol: str child_number: int transformation: object size: int lattice: NDArray[np.float64] symbols: list positions: NDArray[np.float64] site_atoms: list site_sources: list spin_matrix: NDArray[np.float64] folding: list = dataclass_field(default_factory=list) identity_irrep: str | None = None mulliken: dict = dataclass_field(default_factory=dict) rows: list = dataclass_field(default_factory=list) notes: list = dataclass_field(default_factory=list)
[docs] def child_spins(self, field: NDArray[np.float64]) -> NDArray[np.float64]: """The moments a spin field of the magnetic cell of the crystal, ``(n_cells, n_sites, 3)``, puts on the atoms of the subgroup structure (Cartesian, zero on the other atoms, not normalized).""" spins = np.zeros((len(self.symbols), 3)) for atom, (site, cell) in zip(self.site_atoms, self.site_sources): spins[atom] = self.spin_matrix @ np.asarray(field)[cell, site] return spins
def _write_parent_poscar(primitive, path: str) -> None: """The primitive cell of the analysis as a POSCAR (species in runs).""" from itertools import groupby from .vasp_io import format_poscar species: list[str] = [] counts: list[int] = [] for symbol, run in groupby(list(primitive.symbols)): species.append(str(symbol)) counts.append(len(list(run))) with open(path, "w") as handle: handle.write(format_poscar("crystod-mag --subgroup-poscar: the crystal", np.asarray(primitive.cell), species, counts, np.asarray(primitive.scaled_positions))) def _align_with_subgroup(analysis: SpinBasisAnalysis, primitive, child_file: str, *, tolerance: float = _SUBGROUP_TOLERANCE, classify: bool = True) -> SubgroupAlignment: """Place the bases of a q != 0 analysis on a subgroup structure and align their directions with its structural domain. The subgroup structure (a distorted structure of the same compound whose cell is a magnetic cell of q, e.g. P6_3cm YMnO3 for the K point of P6_3/mmc) is mapped onto the crystal as ``crystod-group --correlate --supergroup-poscar --subgroup-poscar`` maps it (``SymmetryModeAnalysis``, x_parent = P x_child + p between the input cells); each of its magnetic atoms takes the spin of the site and cell of the magnetic cell it lands on, carried through the fractional components (S_parent = P S_child). For every basis (real order-parameter space V, :class:`_DirectionSpace`) the fields that are one irrep of the subgroup structure at GM form the subspaces U of V (the folding, 2 x K3 -> GM1 + GM4 of P6_3cm). For every one-parameter direction the domains (images under the group of the crystal with time reversal) that lie in one U are aligned fields: one row per irrep and magnetic space group on the subgroup structure, the domain nearest to the exported component of the direction, with the angle between them. A generic field of each U of more than one dimension, and of the whole basis, gives the remaining rows; every exported component is listed as it is, with the weights of its irreps. Args: analysis: The analysis at q != 0 (``_direction_spaces`` set). primitive: Its primitive cell (``PhonopyAtoms``, the cell as given). child_file: The subgroup structure (POSCAR or CIF, primitive). tolerance: Symmetry and mapping tolerance (Angstrom). classify: Find the magnetic space groups on the subgroup structure. Returns: A :class:`SubgroupAlignment`. Raises: SystemExit: The file is missing or unreadable, or it cannot be mapped onto the crystal (``SymmetryModeAnalysis``). ValueError: It is not primitive, has another number of magnetic atoms, or q does not fold onto GM of its cell. """ import tempfile import warnings from phonopy.structure.atoms import PhonopyAtoms from .isotropy_subgroup import _nullspace, _orth_basis from .magnetic_group import magnetic_space_group from .symmetry_adapted_modes import _axes_sign from .symmetry_mode import SymmetryModeAnalysis, read_structure_cell if not os.path.isfile(child_file): raise SystemExit(f"ERROR: subgroup structure not found: {child_file}") with tempfile.TemporaryDirectory() as tmp: parent_path = os.path.join(tmp, "POSCAR") _write_parent_poscar(primitive, parent_path) mode = SymmetryModeAnalysis(parent_path, child_file, float(tolerance)) transformation = mode.setting_transformation() name = os.path.basename(child_file) if transformation.frame != "input": raise ValueError(f"the subgroup structure {name} could not be related to the cell of " "the crystal as the files give them (spglib gave no setting of one " "of the two cells).") P = np.asarray(transformation.matrix, dtype=float) p = np.asarray(transformation.origin, dtype=float) if not np.allclose(P, np.rint(P), atol=1e-6): raise ValueError(f"the cell of the subgroup structure {name} is not a supercell of the " "primitive cell of the crystal (the transformation matrix is not " "integral); give its primitive cell.") P = np.rint(P) size = int(round(abs(np.linalg.det(P)))) q = np.asarray(analysis.qpoint, dtype=float) products = q @ P q_name = "GM" if analysis.qpoint_label == "GAMMA" else analysis.qpoint_label if np.abs(products - np.rint(products)).max() > 1e-6: raise ValueError( f"q = {q_name} {np.round(q, 6).tolist()} does not fold onto GM of the subgroup " f"structure {name} (q . a', q . b', q . c' = {np.round(products, 6).tolist()} are " "not integers): its cell is not a magnetic cell of q.") lattice_c, positions_c, numbers_c = read_structure_cell(child_file) lattice_c = np.asarray(lattice_c, dtype=float) positions_c = np.asarray(positions_c, dtype=float) child_atoms = PhonopyAtoms(numbers=list(numbers_c), cell=lattice_c, scaled_positions=positions_c) symbols_c = list(child_atoms.symbols) child_vib = SymmetryOnlyVibrations(cell=child_atoms, symprec=float(tolerance), standardize=False) lattice_ops = int(np.sum(np.all(np.asarray(child_vib.rotations) == np.eye(3, dtype=int), axis=(1, 2)))) if lattice_ops > 1: raise ValueError( f"the subgroup structure {name} is not a primitive cell ({len(symbols_c)} atoms, " f"the primitive cell has {len(symbols_c) // lattice_ops}); --subgroup-poscar needs " "its primitive cell, such as the PPOSCAR of phonopy --symmetry.") dataset = child_vib.spglib_dataset child_symbol = str(dataset["international"]) child_number = int(dataset["number"]) element = analysis.element site_atoms = [i for i, s in enumerate(symbols_c) if s == element] if len(site_atoms) != analysis.n_sites * size: raise ValueError( f"the subgroup structure {name} has {len(site_atoms)} {element} atoms, not " f"{analysis.n_sites * size} ({analysis.n_sites} per primitive cell of the crystal, " f"{size} cells).") # the magnetic atoms of the subgroup structure on the sites and cells of # the magnetic cell of the crystal lattice_p = np.asarray(analysis.primitive_lattice, dtype=float) sites_p = np.asarray(analysis.site_positions, dtype=float) cell_matrix = np.asarray(analysis.cell_matrix, dtype=float) inverse_cell = np.linalg.inv(cell_matrix) cells = int(round(abs(np.linalg.det(cell_matrix)))) def cell_key(translation) -> tuple: fraction = np.asarray(translation, dtype=float) @ inverse_cell return tuple(int(v) for v in np.rint(fraction * cells).astype(int) % cells) cell_index = {cell_key(t): c for c, t in enumerate(np.rint( np.asarray(analysis.cell_translations, dtype=float)).astype(int))} P_inverse = np.linalg.inv(P) sources: list[tuple[int, int]] = [] seen: set = set() for atom in site_atoms: image = P @ positions_c[atom] + p diff = image[None, :] - sites_p shifts = np.rint(diff) distances = np.linalg.norm((diff - shifts) @ lattice_p, axis=1) site = int(np.argmin(distances)) if distances[site] > _SUBGROUP_MAX_DISTANCE: raise ValueError( f"{element} atom {atom + 1} of the subgroup structure {name} lies " f"{distances[site]:.2f} A from the nearest {element} site of the crystal " "(more than 1.8 A) in the cell relation found.") translation = shifts[site].astype(int) # the same site in the same cell of the subgroup structure twice within = tuple(int(v) for v in np.rint(P_inverse @ translation * size).astype(int) % size) if (site, within) in seen: raise ValueError(f"two {element} atoms of the subgroup structure {name} land on " "the same site of the crystal in the cell relation found.") seen.add((site, within)) sources.append((site, cell_index[cell_key(translation)])) spin_matrix = lattice_c.T @ P_inverse @ np.linalg.inv(lattice_p.T) # the irreps of the subgroup structure at GM on its magnetic sites irreps, spin_rep, mapping = get_spin_representation(child_vib, site_atoms, [0.0, 0.0, 0.0]) labels = child_vib.get_irrep_labels([0.0, 0.0, 0.0], irreps, mapping) order = len(spin_rep) projectors = [] identity_irrep = None for irrep, label in zip(irreps, labels): characters = np.array([np.trace(matrix) for matrix in irrep]) projectors.append(irrep.shape[1] / order * np.einsum("g,gab->ab", np.conj(characters), spin_rep)) if irrep.shape[1] == 1 and np.allclose(characters, 1.0): identity_irrep = label.split("(")[0].strip() present = {i for i, projector in enumerate(projectors) if abs(np.trace(projector)) > 0.5} pairs = _conjugate_pairs(irreps, labels, present) seconds = set(pairs.values()) child_irreps: list[tuple[str, NDArray[np.float64]]] = [] for i in sorted(present, key=lambda k: _natural_key(labels[k])): if i in seconds: continue if i in pairs: label = _pair_label(labels[i], labels[pairs[i]]) projector = projectors[i] + projectors[pairs[i]] else: label, projector = labels[i], projectors[i] child_irreps.append((label.split("(")[0].strip(), np.real(projector))) mulliken: dict = {} try: from .phonon_activity import mulliken_symbols with warnings.catch_warnings(): warnings.simplefilter("ignore") mulliken = dict(mulliken_symbols(child_vib, symprec=float(tolerance))) except Exception: mulliken = {} result = SubgroupAlignment( child_file=str(child_file), child_symbol=child_symbol, child_number=child_number, transformation=transformation, size=size, lattice=lattice_c, symbols=symbols_c, positions=positions_c, site_atoms=site_atoms, site_sources=sources, spin_matrix=spin_matrix, identity_irrep=identity_irrep, mulliken=mulliken, ) def child_vector(field) -> NDArray[np.float64]: return result.child_spins(field)[site_atoms].reshape(-1) def weights_of(field) -> list: vector = child_vector(field) total = float(vector @ vector) weights = [] for label, projector in child_irreps: part = projector @ vector weight = float(part @ part) / total if total > 0 else 0.0 if weight > 1e-6: weights.append((label, weight)) return weights def classified(field): spins = result.child_spins(field) largest = float(np.max(np.linalg.norm(spins, axis=1))) spins = spins / largest if largest > 1e-12 else spins spins[np.abs(spins) < 1e-10] = 0.0 # no -0.0000 in the listings if not classify: return None, spins try: group = magnetic_space_group(lattice_c, positions_c, list(numbers_c), spins, symprec=float(tolerance)) except SystemExit: group = None return group, spins def unit_field(vector, space) -> NDArray[np.float64]: field = (space.Q @ vector).reshape(space.shape) return field / float(np.max(np.linalg.norm(field, axis=-1))) def bns_key(group) -> tuple: if group is None or not getattr(group, "identified", False): return (10**6,) return tuple(int(x) for x in group.bns_number.split(".")) rng = np.random.default_rng(20261109) rows: list[SubgroupSpinField] = [] for space in getattr(analysis, "_direction_spaces", []): n = space.Q.shape[1] columns = np.column_stack([child_vector(space.Q[:, k].reshape(space.shape)) for k in range(n)]) scale = max(float(np.linalg.norm(columns)), 1.0) parts = [] # (label, orthonormal basis of U in Q coordinates) for label, projector in child_irreps: null = _nullspace(columns - projector @ columns, 1e-6 * scale) if null.shape[1]: u, sing, _ = np.linalg.svd(np.real(null), full_matrices=False) parts.append((label, u[:, sing > 1e-8])) result.folding.append((space.label, [label for label, _ in parts])) if sum(U.shape[1] for _, U in parts) != n: result.notes.append( f"{space.label}: not every field of the basis is a sum of fields of single " f"irreps of {child_symbol} (an operation of the subgroup structure takes q to " "another arm of its star); only the directions inside one irrep are aligned.") position_of = {id(d): s for s, d in enumerate(space.directions)} rows_of: dict = {} def add(s, row) -> None: rows_of.setdefault(s, []).append(row) entry_label = analysis.entries[space.entry_index][0] for component in space.components: if component.field is None: continue group, _ = classified(component.field) add(component.stratum, SubgroupSpinField( entry_index=component.entry_index, label=component.label, kind="component", direction=component.direction, tag=component.file_tag or component.tag, child_irreps=weights_of(component.field), group=group, coefficients=space.coefficients_of(component.field))) for s, (_, images) in enumerate(space.strata): direction = space.directions[s] source = getattr(direction, "_source", None) if direction.n_free != 1 or source is None or source.field is None: continue # the exported components on the direction (the direction's own # first); an aligned field is measured from the nearest of them references = [source] + [c for c in space.components if c is not source and c.stratum == s and c.field is not None] reference_vectors = [] for component in references: vector = space.Q.T @ component.field.reshape(-1) reference_vectors.append(vector / np.linalg.norm(vector)) lines = [_orth_basis(image)[:, 0] for image in images] found = False for label, U in parts: best: dict = {} for v in lines: if np.linalg.norm(v - U @ (U.T @ v)) > 1e-6: continue overlaps = [float(v @ r) for r in reference_vectors] nearest = int(np.argmax(np.abs(overlaps) - 1e-9 * np.arange(len(overlaps)))) overlap = overlaps[nearest] if overlap < -1e-9 or (abs(overlap) <= 1e-9 and _axes_sign( (space.Q @ v).reshape(space.shape), space.inverse_axes) < 0): v = -v field = unit_field(v, space) group, spins = classified(field) key = bns_key(group) # nearest first; on a tie, the earlier component score = (round(abs(overlap), 9), -nearest) if key not in best or score > best[key][0]: best[key] = (score, abs(overlap), references[nearest], field, group, spins) for key in sorted(best): _, overlap, reference, field, group, spins = best[key] found = True reference_tag = reference.file_tag or reference.tag add(s, SubgroupSpinField( entry_index=source.entry_index, label=source.label, kind="aligned", direction=direction, tag=f"{reference_tag}_{label}", child_irreps=[(label, 1.0)], reference=reference_tag, group=group, angle=float(np.degrees(np.arccos(min(1.0, overlap)))), coefficients=space.coefficients_of(field), field=field, spins=spins)) if not found: add(s, SubgroupSpinField( entry_index=source.entry_index, label=source.label, kind="none", direction=direction, tag="-", child_irreps=[], reference=source.file_tag or source.tag)) generic_strata = set() for label, U in parts: if U.shape[1] < 2: continue v = U @ rng.standard_normal(U.shape[1]) v = v / np.linalg.norm(v) s = space.stratum_of(v) generic_strata.add(s) group, _ = classified(unit_field(v, space)) add(s, SubgroupSpinField( entry_index=space.entry_index, label=entry_label, kind="generic", direction=space.directions[s] if s is not None else None, tag="generic", child_irreps=[(label, None)], group=group)) top = [s for s, d in enumerate(space.directions) if d.n_free == n] if (len(parts) > 1 or sum(U.shape[1] for _, U in parts) != n) and top \ and top[0] not in generic_strata: s = top[0] generic = space.analyzer.direction_label(space.strata[s][0])[1] group, _ = classified(unit_field(np.real(generic), space)) add(s, SubgroupSpinField( entry_index=space.entry_index, label=entry_label, kind="generic", direction=space.directions[s], tag="generic", child_irreps=[(label, None) for label, _ in parts], group=group)) kind_order = {"component": 0, "aligned": 1, "none": 2, "generic": 3} ordered_strata = [position_of[id(d)] for d in analysis.directions if id(d) in position_of] ordered_strata += [s for s in rows_of if s not in ordered_strata] for s in ordered_strata: rows.extend(sorted(rows_of.get(s, []), key=lambda r: kind_order[r.kind])) result.rows = rows # VESTA names of the aligned fields, unique next to those of the crystal used = {c.vesta_name for c in analysis.components if c.vesta_name} q_tag = re.sub(r"[^A-Za-z0-9+-]", "_", q_name) for row in rows: if row.kind != "aligned": continue short_label = row.label.split("(")[0].strip() stem = f"POSCAR_{analysis.formula}_spin_{short_label}_{q_tag}_{row.tag}" tag, suffix = row.tag, 2 while f"{stem}.vesta" in used: stem = f"POSCAR_{analysis.formula}_spin_{short_label}_{q_tag}_{row.tag}_{suffix}" tag = f"{row.tag}_{suffix}" suffix += 1 used.add(f"{stem}.vesta") row.tag = tag row.vesta_name = f"{stem}.vesta" return result def subgroup_poscar_name(analysis: SpinBasisAnalysis) -> str: """The file ``crystod-mag --subgroup-poscar CHILD`` writes the subgroup structure to: ``S<basename of CHILD>_<q>`` (``S185_PPOSCAR_YMnO3_K``), its cell and atoms as read, in the atom order of the ``MAGMOM`` lines of the aligned fields.""" q_name = "GM" if analysis.qpoint_label == "GAMMA" else analysis.qpoint_label q_tag = re.sub(r"[^A-Za-z0-9+-]", "_", q_name) return f"S{os.path.basename(analysis.subgroup.child_file)}_{q_tag}" def write_subgroup_poscar(analysis: SpinBasisAnalysis, path: str) -> None: """Write the subgroup structure of an analysis as a POSCAR (VASP 5, direct) in the atom order of the aligned ``MAGMOM`` lines.""" from itertools import groupby from .vasp_io import format_poscar alignment = analysis.subgroup species: list[str] = [] counts: list[int] = [] for symbol, run in groupby(alignment.symbols): species.append(str(symbol)) counts.append(len(list(run))) q_name = "GM" if analysis.qpoint_label == "GAMMA" else analysis.qpoint_label comment = (f"{analysis.formula} {os.path.basename(alignment.child_file)} " f"({alignment.child_symbol}), magnetic cell of q = {q_name} " "(crystod-mag --subgroup-poscar; atom order of the MAGMOM lines)") with open(path, "w") as handle: handle.write(format_poscar(comment, alignment.lattice, species, counts, alignment.positions)) SUBGROUP_TABLE_HEADERS = ( "irrep direction", "field", "child irrep", "MSG on the child (BNS)", "angle", "in comp basis", )
[docs] def subgroup_table_rows(analysis: SpinBasisAnalysis) -> list[tuple[str, ...]]: """Rows of the ``* Spin bases on the subgroup structure *`` block. Args: analysis: A :class:`SpinBasisAnalysis` with a subgroup structure. Returns: One tuple per :class:`SubgroupSpinField`: ``(direction, field, child irreps, MSG on the child, angle, coefficients)``, e.g. ``("K3(0.282a;a)", "comp2_GM4", "GM4", "185.200 P6_3'cm'", "60", "(-0.866,0.5)")``; empty without a subgroup structure. """ alignment = analysis.subgroup if alignment is None: return [] rows = [] for row in alignment.rows: if row.direction is not None: text = _direction_text(row.direction) else: text = re.sub(r"\(\d+\)", "", row.label).strip() angle = "-" if row.angle is None else f"{row.angle:.1f}".rstrip("0").rstrip(".") coefficients = ("-" if row.coefficients is None else _format_direction_coefficients(row.coefficients)) rows.append((text, row.tag, row.child_irrep_text, row.subgroup or "-", angle, coefficients)) return rows
def _fraction_text(values) -> str: """``(-1/3, 2/3, 0)``.""" texts = [] for value in values: fraction = Fraction(float(value)).limit_denominator(48) texts.append(str(fraction) if abs(float(fraction) - value) < 1e-6 else f"{value:.4f}") return "(" + ", ".join(texts) + ")"
[docs] def format_subgroup_alignment(analysis: SpinBasisAnalysis) -> list[str]: """The blocks ``* Subgroup structure *``, ``* Transformation matrix (parent -> child) *`` and ``* Spin bases on the subgroup structure *`` of ``crystod-mag --qpoint K --subgroup-poscar CHILD`` (no lines without a subgroup structure). Args: analysis: A :class:`SpinBasisAnalysis`. Returns: The blocks as lines, separated by blank lines. """ alignment = analysis.subgroup if alignment is None: return [] name = os.path.basename(alignment.child_file) child = f"{alignment.child_symbol} (No. {alignment.child_number})" parent = f"{analysis.space_group} (No. {analysis.space_group_number})" q_name = "GM" if analysis.qpoint_label == "GAMMA" else analysis.qpoint_label def with_symbol(label: str) -> str: symbol = alignment.mulliken.get(label) return f"{label} [{symbol}]" if symbol else label lines = ["* Subgroup structure *", f" Subgroup structure: {name}, {child}", f" Magnetic sites: {analysis.element} x {len(alignment.site_atoms)} " f"({alignment.size} primitive cells of {analysis.space_group})", f" q = {q_name} {_fraction_text(analysis.qpoint)} folds onto GM of " f"{alignment.child_symbol}; the fields of each basis are made of:"] for label, irreps in alignment.folding: lines.append(f" {label} -> " + (" + ".join(with_symbol(x) for x in irreps) if irreps else "no single irrep")) transformation = alignment.transformation.lines(parent, child) transformation[1] = f"{parent} -> {child}, the cells of the input files" lines += [""] + transformation lines.append("(spins through the fractional components, S_parent = P S_child)") table = [SUBGROUP_TABLE_HEADERS] + subgroup_table_rows(analysis) widths = [max(len(row[c]) for row in table) for c in range(len(table[0]))] lines += ["", "* Spin bases on the subgroup structure *"] lines += [" " + " ".join(cell.ljust(width) for cell, width in zip(row, widths)).rstrip() for row in table] identity = alignment.identity_irrep lines += [ "", f" child irrep: the irreps of {alignment.child_symbol} at GM the field is made of on " f"{name}, with the squared norms of their parts", " <component>_<irrep>: the domain of the direction (an image under the operations " f"of {analysis.space_group}1') whose field is that one irrep, named after the " "nearest component on the direction; angle: degrees it is turned from that " "component in the order-parameter space (the phase of the order parameter at a q " "that is not time-reversal invariant)", ] if identity and any(identity in irreps for _, irreps in alignment.folding): lines.append( f" {identity}: the field keeps every operation of the subgroup structure (for an " "irrep of its distortion, the direction of its structural order parameter); the " "other irreps of a basis are orthogonal to it") lines += [ " generic: a generic field of the stratum, of one irrep or of the whole basis; " "no single irrep: no domain of the direction is one irrep of the subgroup structure", " in comp basis: as in * Order-parameter directions *; MSG on the child: spglib on " f"{name} with these moments", ] lines += [f" NOTE: {note}" for note in alignment.notes] return lines
[docs] def magnetic_summary_rows(analysis: SpinBasisAnalysis) -> list[tuple[str, ...]]: """Rows of the table of magnetic groups and collinear classes. Args: analysis: A classified :class:`SpinBasisAnalysis`. Returns: One tuple per exported component with a nonvanishing field: ``(basis, component, MSG (BNS), type, MPG, net magnetization, class, MSG (UNI))``, e.g. ``("GM2+(1) [AFM, octupole]", "z", "P4_2'/mnm' (136.499)", "III", "4'/mmm'", "none", "altermagnet (d-wave)", "P4_2'/mnm'")``; the last cell is the unified symbol of B. J. Campbell et al., Acta Cryst. A78, 99 (2022) (``"P4/mnc.1'_I[I4/mmm]"`` for a type IV group). The component is the tag of the VESTA file name (``"z_2"`` for the second ``z`` of the same basis). A group that spglib cannot identify, and an unclassified component (FM/AFM separation failed), give ``"-"`` in the cells concerned; no component is left out. """ rows = [] for component in analysis.components: if component.field is None or component.collinear is None: continue group = component.group if group is not None and group.identified: msg_cells = (f"{group.bns_symbol} ({group.bns_number})", group.type_name, str(group.magnetic_point_group)) uni_cell = group.uni_symbol or "-" else: msg_cells = ("-", "-", "-") uni_cell = "-" if component.responses is not None: magnetization = component.responses.magnetization_direction else: magnetization = "-" rows.append(( component.header, component.file_tag or component.tag, *msg_cells, magnetization, component.collinear.short_name, uni_cell, )) return rows
MAGNETIC_SUMMARY_HEADERS = ( "basis", "component", "MSG (BNS)", "type", "MPG", "net magnetization", "class", "MSG (UNI)", )
[docs] def magnetic_summary_notes(analysis: SpinBasisAnalysis) -> list[str]: """The notes under the summary table (frames, tags, warnings). Args: analysis: A classified :class:`SpinBasisAnalysis`. Returns: Note lines, unindented: how to read the columns, the frames of the symbols and directions, the pair labels of complex irreps merged with their conjugates, and a line when spglib could not identify a group. """ lines = [ "MSG: magnetic space group from the moment directions (BNS number, type I-IV);", "MPG: magnetic point group; net magnetization: the direction allowed by symmetry;", "class: from the signs of the moments along their common axis only (nonrelativistic).", "MSG and MPG symbols are in the standard BNS setting; directions are in the " "Cartesian axes of the input cell.", "MSG (UNI): unified symbol (Campbell et al., Acta Cryst. A78, 99 (2022)), the BNS " "symbol with .1 (type I) or .1' (II); type IV: .1'_t[F], t the anti-translation, " "F the family space group.", ] if any(c.field is not None and c.tag.startswith("comp") for c in analysis.components): lines.append("component: the tag of the listing and of the VESTA file name " "(comp<N>: the N-th basis vector of its space).") qpoint = np.asarray(analysis.qpoint, dtype=float) if not analysis.is_gamma and not np.allclose(2.0 * qpoint, np.rint(2.0 * qpoint)): lines.append("q is not time-reversal invariant: a d-dimensional basis has the components " "of its rows w and of their partners i w (comp<d+1>..comp<2d>).") if any(c.field is not None and c.tag.startswith("dir") for c in analysis.components): lines.append("dir<k>: a one-parameter order-parameter direction exported on its own " "(* Order-parameter directions *).") for pair in analysis.pair_labels: lines.append(f"{pair}: a complex irrep and its conjugate, merged into one real " "space (the physically irreducible representation).") if any(c.collinear is not None and c.group is not None and not c.group.identified for c in analysis.components): lines.append("MSG '-': spglib returned the operations but did not identify the group; " "the responses come from the operations.") return lines
def format_magnetic_summary(analysis: SpinBasisAnalysis) -> list[str]: """The ``* Magnetic groups and collinear classes *`` block of crystod-mag. Args: analysis: A classified :class:`SpinBasisAnalysis`. Returns: The block as lines: title, unindented table, and the notes (:func:`magnetic_summary_notes`). """ rows = [MAGNETIC_SUMMARY_HEADERS] + magnetic_summary_rows(analysis) widths = [max(len(row[c]) for row in rows) for c in range(len(rows[0]))] lines = ["* Magnetic groups and collinear classes *"] lines += [" ".join(cell.ljust(width) for cell, width in zip(row, widths)).rstrip() for row in rows] lines += [""] + magnetic_summary_notes(analysis) return lines
[docs] def paramagnetic_point_group(analysis: SpinBasisAnalysis): """The grey magnetic point group of the crystal without spins. Args: analysis: A :class:`SpinBasisAnalysis`. Returns: ``(symbol, rotations, time_reversals)``: the symbol (``"4/mmm1'"``, ``"-"`` when the symbol derived from the space group does not match the operations) and every distinct Cartesian rotation of the crystal once without and once with time reversal. """ from .magnetic_group import ( _unique_operations, check_point_group_symbol, magnetic_point_group_symbol, ) rotations = _unique_operations(analysis.parent_rotations, [False] * len(analysis.parent_rotations))[0] rotations = np.concatenate([rotations, rotations]) flags = [False] * (len(rotations) // 2) + [True] * (len(rotations) // 2) symbol = magnetic_point_group_symbol(analysis.space_group, 2) if not check_point_group_symbol(symbol, rotations, flags): symbol = "-" return symbol, rotations, flags
[docs] def phonon_angular_momentum_rows(analysis: SpinBasisAnalysis) -> list[tuple]: """Rows of the ``* Phonon angular momentum allowed by symmetry *`` block. Args: analysis: A classified :class:`SpinBasisAnalysis`. Returns: ``(basis, component, MPG, result)`` with the :class:`crystod.magnetic_group.PhononAngularMomentum` of the magnetic point group (None when it is not known): first the paramagnetic crystal (``"paramagnetic"``, ``"-"``, its grey group), then every exported component of the table of magnetic groups, in its order. """ from .magnetic_group import phonon_angular_momentum symbol, rotations, flags = paramagnetic_point_group(analysis) rows = [("paramagnetic", "-", symbol, phonon_angular_momentum(rotations, flags))] for component in analysis.components: if component.field is None or component.collinear is None: continue group = component.group if group is None: rows.append((component.header, component.file_tag or component.tag, "-", None)) continue symbol = str(group.magnetic_point_group) if group.identified else "-" rows.append((component.header, component.file_tag or component.tag, symbol, phonon_angular_momentum(group))) return rows
PHONON_ANGULAR_MOMENTUM_HEADERS = ( "basis", "component", "MPG", "l_x", "l_x ~", "planes", "l_y", "l_y ~", "planes", "l_z", "l_z ~", "planes", )
[docs] def format_phonon_angular_momentum(analysis: SpinBasisAnalysis, rows=None) -> list[str]: """The ``* Phonon angular momentum allowed by symmetry *`` block of ``crystod-mag --classify-only --phonon-angular-momentum``. Args: analysis: A classified :class:`SpinBasisAnalysis`. rows: The rows instead of :func:`phonon_angular_momentum_rows` (``(basis, component, MPG, result)``; the multi-element run). Returns: The block as lines: title, unindented table (one row per :func:`phonon_angular_momentum_rows`; a second polynomial of a component goes on a continuation line) and the legend. """ table = [PHONON_ANGULAR_MOMENTUM_HEADERS] for basis, tag, symbol, result in (phonon_angular_momentum_rows(analysis) if rows is None else rows): if result is None: table.append((basis, tag, symbol) + ("-",) * 9) continue columns = [] for component in result.components: if component.degree is None: columns.append(([component.letter], [component.short_name], ["-"])) else: columns.append(([component.letter], list(component.forms), [str(component.n_nodal)])) height = max(len(forms) for _, forms, _ in columns) for line in range(height): cells = [basis, tag, symbol] if line == 0 else ["", "", ""] for letter, forms, planes in columns: first = line == 0 cells += [letter[0] if first else "", forms[line] if line < len(forms) else "", planes[0] if first else ""] table.append(tuple(cells)) widths = [max(len(row[c]) for row in table) for c in range(len(table[0]))] lines = ["* Phonon angular momentum allowed by symmetry *"] lines += [" ".join(cell.ljust(width) for cell, width in zip(row, widths)).rstrip() for row in table] lines += [ "", "l_i: component i of the phonon angular momentum l(q) of a branch near GM (an axial " "vector, odd under time reversal), from l(A q) = B l(q) with A = s R, " "B = s det(R) R (s = -1 with time reversal);", "its column: the wave of the lowest degree n of a q-polynomial allowed for it " "(s, p, d, f, g, h, i, j for n = 0..7, the number beyond); l_i ~: the polynomials of " "that degree (a second one on the next line);", "planes: only the nodal planes through GM pinned by a single operation (a mirror " "without time reversal containing e_i, a 2' along the normal when e_i is along it); " "fewer than n: the other nodes are not fixed in position by symmetry;", "none (P T): P T makes l vanish at every q; s: a constant, the net magnetization.", "Symmetry fixes the forms, not the magnitudes. paramagnetic: the grey group of the " "crystal, what ordinary (time-reversal-even) force constants give (odd degrees " "only, l(-q) = -l(q));", "the even-degree textures of a magnet, and every form beyond the paramagnetic row, " "need a time-reversal-odd term in the lattice dynamics (e.g. spin-phonon coupling).", "MPG as in the table above; q and l in the Cartesian axes of the input cell, the " "components read one at a time.", ] return lines
if __name__ == "__main__": main()