Source code for crystod.multi_element

"""Spin bases on the sites of several elements at once (``crystod-mag --element A B``).

The spins on the sites of two or more elements (two or more Wyckoff orbits)
form the direct sum of the axial-vector representations of the elements:
every element is analysed on its own (:func:`crystod.spin_basis.analyze_spin_basis`,
the element-pure bases, exactly the single-element runs), and then

- the copies of one irrep found on different elements are compared: the
  representation matrices of the operations of the crystal (with the
  translations of the magnetic cell) on the basis rows of each copy, and the
  map that intertwines them (:class:`CopyRelation`; the identity when the
  copies share the same matrices on their rows);
- along every order-parameter direction the listing of one copy uses (the
  exported components: x, y, z, 110, 111, comp<N>, dir<k> ...), one copy per
  element is combined with the relative signs (+,+), (+,-), ... of the
  printed moments, every element normalized as its own bases (largest moment
  1), and each combination is classified as any other basis
  (:class:`CombinedArrangement`: magnetic space group, responses, collinear
  class);
- any listed bases, of any irreps and elements, can be superposed with given
  coefficients (:func:`superpose_bases`, ``crystod-mag --superpose N ...
  --coefficients c ...``).

Completeness: all copies of one irrep transform with the same matrices (up
to the intertwining map, which is checked), so a real superposition of copies
along the same order-parameter direction, with any nonzero amplitudes, has the
stabilizer of that direction, i.e. the magnetic space group of each copy
alone. The table "irrep x direction -> magnetic space group" of the
single-element runs is therefore complete as far as symmetry goes; the
relative amplitudes of the copies are free parameters that symmetry does not
fix. Two different elements are never exchanged by an operation, so a pattern
that looks like one antiferromagnet on two sites is classified differently
when the two sites carry different elements (the Lieb lattice: P4'/mm'm with
one element, Pm'm'm with two).
"""

from __future__ import annotations

import itertools
import sys
from dataclasses import dataclass, field as dataclass_field

import numpy as np
from numpy.typing import NDArray

#: Combined arrangements written as VESTA files at most (the table stays complete).
COMBINED_FILE_CAP = 48


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


[docs] @dataclass(eq=False) class CopyRelation: """How the basis rows of one copy of an irrep relate to those of the representative copy (the first element that has the irrep). Attributes: label: The irrep label (``"GM4+(3)"``). reference: ``(element, header)`` of the representative copy. copy: ``(element, header)`` of this copy. map: The ``(d, d)`` matrix T with ``D_copy(g) T = T D_reference(g)`` for every operation (``c -> T c`` takes the coefficients of a direction in the rows of the reference to those in the rows of this copy), normalized to the largest entry 1; None when no intertwining map was found. identity: True when the copy has the same matrices on its rows (T is the identity). residual: Largest deviation of ``D_copy T - T D_reference`` (and of the row spans from being invariant). """ label: str reference: tuple copy: tuple map: NDArray[np.float64] | None identity: bool residual: float
[docs] def text(self) -> str: """``"same matrices on the rows"`` or ``"rows mapped by (x, y, -z)"``.""" if self.map is None: return "no intertwining map found (not combined)" if self.identity: return "same matrices on the rows" return "rows mapped by " + _map_text(self.map)
[docs] @dataclass(eq=False) class CombinedArrangement: """One copy per element of one irrep, along one order-parameter direction, with relative signs. Attributes: label: The irrep label. copies: ``(element, header)`` of the copy of every element. tag: The direction: the tag of the component of the representative copy it follows (``"x"``, ``"111"``, ``"comp1"``, ``"dir2"``). signs: +1 / -1 of every element's copy (the first +1). magmoms: Moments of every atom of the magnetic cell, ``(n_atoms, 3)`` (each element's part with largest moment 1, times its sign). field: The same on the selected sites, ``(n_cells, n_sites, 3)`` (sites in the order of :attr:`MultiElementAnalysis.site_indices`). net_moment: Net moment over the magnetic cell. group: :class:`crystod.magnetic_group.MagneticGroupInfo` or None. responses: :class:`crystod.magnetic_group.MagneticResponses` or None. collinear: :class:`crystod.magnetic_group.CollinearClass` or None. direction_label: ISOTROPY's label of the direction at q != 0 (that of the representative component), else None. vesta_name: The VESTA file written, empty when none (beyond :data:`COMBINED_FILE_CAP`). """ label: str copies: tuple tag: str signs: tuple magmoms: NDArray[np.float64] field: NDArray[np.float64] net_moment: NDArray[np.float64] group: object = None responses: object = None collinear: object = None direction_label: str | None = None vesta_name: str = "" @property def sign_text(self) -> str: """``"(+,-)"``.""" return "(" + ",".join("+" if s > 0 else "-" for s in self.signs) + ")" @property def elements_text(self) -> str: """``"Al+Ni"``.""" return "+".join(element for element, _ in self.copies) @property def header(self) -> str: """``"GM4+(3) [Al FM, dipole + Ni AFM, octupole]"``.""" parts = [] for element, header in self.copies: inner = header[header.index("[") + 1: header.rindex("]")] if "[" in header else "" parts.append(f"{element} {inner}".strip()) return f"{self.label} [{' + '.join(parts)}]" @property def component_text(self) -> str: """``"x (+,-)"``.""" return f"{self.tag} {self.sign_text}"
[docs] @dataclass(eq=False) class Superposition: """A superposition of listed bases (``crystod-mag --superpose``). Attributes: numbers: The numbers of the bases (1-based, as listed). coefficients: Their coefficients. parts: ``(number, element, header, tag, coefficient)`` of every term. magmoms: Moments of every atom of the magnetic cell (largest 1). field: The same on the selected sites. net_moment: Net moment over the magnetic cell. irrep_content: ``(element, basis header, weight)``: the squared projection on the space of every basis (weights sum to 1). group, responses, collinear: As for a basis. vesta_name: The VESTA file name. """ numbers: tuple coefficients: tuple parts: list magmoms: NDArray[np.float64] field: NDArray[np.float64] net_moment: NDArray[np.float64] irrep_content: list = dataclass_field(default_factory=list) group: object = None responses: object = None collinear: object = None vesta_name: str = ""
[docs] def irrep_text(self) -> str: """``"Al GM4+(3) [FM, dipole] 0.500 + Ni GM5+(3) [AFM, octupole] 0.500"``.""" return " + ".join(f"{element} {header} {weight:.3f}".strip() for element, header, weight in self.irrep_content if weight > 5e-4)
[docs] @dataclass(eq=False) class MultiElementAnalysis: """The spin bases of several elements at one q point. Attributes: elements: The elements, in the order given. analyses: One :class:`crystod.spin_basis.SpinBasisAnalysis` per element (the element-pure bases, as the single-element runs). site_indices: The selected sites of the primitive cell (all elements), in increasing order. decomposition: ``{irrep label: multiplicity}`` of the direct sum. relations: :class:`CopyRelation` of every copy of an irrep that occurs on two or more elements. combined: The :class:`CombinedArrangement` list. numbered: ``(element, component)`` of every listed basis in the order of its number (1-based). notes: NOTE lines. """ elements: list analyses: list site_indices: list decomposition: dict relations: list = dataclass_field(default_factory=list) combined: list = dataclass_field(default_factory=list) numbered: list = dataclass_field(default_factory=list) notes: list = dataclass_field(default_factory=list) @property def base(self): """The analysis of the first element (the magnetic cell, the q point and the crystal are those of every element).""" return self.analyses[0]
[docs] def analysis_of(self, element: str): """The analysis of one element.""" return self.analyses[self.elements.index(element)]
# ------------------------------------------------------------ helpers def _map_text(matrix: NDArray[np.float64]) -> str: """A signed permutation as ``(x, -z, y)`` (rows in terms of the reference rows ``r1, r2, ...``), any other map as its rounded rows.""" k = matrix.shape[0] names = ["x", "y", "z"] if k == 3 else [f"r{i + 1}" for i in range(k)] rounded = np.round(matrix, 6) if all(np.count_nonzero(row) == 1 and abs(abs(row[row != 0][0]) - 1) < 1e-6 for row in rounded): parts = [] for row in rounded: j = int(np.flatnonzero(row)[0]) parts.append(("-" if row[j] < 0 else "") + names[j]) return "(" + ", ".join(parts) + ")" return "[" + "; ".join(" ".join(f"{v:.3g}" for v in row) for row in rounded) + "]"
[docs] def component_magmoms(analysis, component) -> NDArray[np.float64]: """Moments of every atom of the magnetic cell for one component of an analysis (zero on the atoms that are not its sites), ``(n_atoms, 3)``.""" magmoms = np.zeros((len(analysis.supercell_symbols), 3)) if component.field is None: return magmoms for atom, site in enumerate(analysis.supercell_site_of_atom): if site is not None: magmoms[atom] = component.field[analysis.supercell_cell_of_atom[atom], site] return magmoms
def _entry_rows(analysis, entry_index: int): """The components that are the basis rows of one entry (the first d of its components), or None when one of them has no field.""" own = [c for c in analysis.components if c.entry_index == entry_index] d = analysis.entries[entry_index][3].shape[0] rows = own[:d] if len(rows) < d or any(c.field is None for c in rows): return None return rows def _supercell_operations(analysis, vibrations, tolerance: float): """``(target, axial)`` of every operation of the crystal combined with every translation of the magnetic cell: atom i goes to atom target[i] and its moment s to ``axial @ s`` (``axial = det(R) R``, Cartesian).""" cell_matrix = np.asarray(analysis.cell_matrix, dtype=float) inverse_cell = np.linalg.inv(cell_matrix) positions = np.asarray(analysis.supercell_positions, dtype=float) primitive = positions @ cell_matrix lattice = np.asarray(analysis.supercell_lattice, dtype=float) symbols = list(analysis.supercell_symbols) operations = [] for rotation, translation, cartesian in zip(vibrations.rotations, vibrations.translations, analysis.parent_rotations): axial = float(np.linalg.det(cartesian)) * np.asarray(cartesian, dtype=float) for shift in analysis.cell_translations: moved = (primitive @ np.asarray(rotation, dtype=float).T + translation + np.asarray(shift, dtype=float)) @ inverse_cell difference = moved[:, None, :] - positions[None, :, :] difference -= np.rint(difference) distance = np.linalg.norm(difference @ lattice, axis=2) target = np.argmin(distance, axis=1) if (np.max(distance[np.arange(len(target)), target]) > tolerance or len(set(target.tolist())) != len(target) or any(symbols[i] != symbols[j] for i, j in enumerate(target))): continue operations.append((target, axial)) return operations def _act(operation, magmoms: NDArray[np.float64]) -> NDArray[np.float64]: target, axial = operation moved = np.zeros_like(magmoms) moved[target] = magmoms @ axial.T return moved def _row_matrices(rows: NDArray[np.float64], operations): """``D(g)`` on the coefficient vectors of the rows (``g . sum_k c_k r_k = sum_k (D c)_k r_k``) and the largest residual of the row span.""" basis = rows.reshape(len(rows), -1).T # (3 N, d) matrices, residual = [], 0.0 scale = max(1.0, float(np.max(np.abs(basis)))) for operation in operations: moved = np.array([_act(operation, row).ravel() for row in rows]).T matrix, *_ = np.linalg.lstsq(basis, moved, rcond=None) residual = max(residual, float(np.max(np.abs(basis @ matrix - moved))) / scale) matrices.append(matrix) return matrices, residual def _intertwiner(reference, copy): """T with ``copy(g) T = T reference(g)`` closest to the identity (the identity when the matrices agree), largest entry 1; None if none.""" d = reference[0].shape[0] identity = np.eye(d) blocks = [np.kron(b, identity) - np.kron(identity, a.T) for a, b in zip(reference, copy)] _, singular, vt = np.linalg.svd(np.vstack(blocks)) rank = int(np.sum(singular > 1e-6 * max(1.0, float(singular[0])))) null = vt[rank:] if len(null) == 0: return None, float(singular[-1]) coefficients = null @ identity.ravel() matrix = (coefficients @ null).reshape(d, d) if np.linalg.norm(matrix) < 1e-6: matrix = null[0].reshape(d, d) flat = matrix.ravel() if flat[int(np.argmax(np.abs(flat)))] < 0: matrix = -matrix matrix = matrix / float(np.max(np.abs(matrix))) residual = max(float(np.max(np.abs(b @ matrix - matrix @ a))) for a, b in zip(reference, copy)) return matrix, residual def _classify(base, vibrations, magmoms, site_indices, numbers): """Magnetic space group, responses and collinear class of a field given on the atoms of the magnetic cell.""" from .magnetic_group import classify_collinear, macroscopic_responses, magnetic_space_group field = _site_field(base, magmoms, site_indices) try: group = magnetic_space_group(base.supercell_lattice, base.supercell_positions, numbers, magmoms, symprec=vibrations.symprec) except SystemExit: group = None responses = macroscopic_responses(group) if group is not None else None positions = vibrations.primitive_cell.scaled_positions collinear = classify_collinear(vibrations.rotations, vibrations.translations, positions, site_indices, base.cell_matrix, field, base.primitive_lattice, symprec=vibrations.symprec) return group, responses, collinear, field def _site_field(base, magmoms, site_indices) -> NDArray[np.float64]: """The moments of the atoms of the magnetic cell on the selected sites, ``(n_cells, n_sites, 3)`` (atom-major cell: atom = site * n_cells + cell).""" n_cells = len(base.cell_translations) field = np.zeros((n_cells, len(site_indices), 3)) for k, site in enumerate(site_indices): for cell in range(n_cells): field[cell, k] = magmoms[site * n_cells + cell] return field def _normalized(magmoms: NDArray[np.float64]) -> NDArray[np.float64]: largest = float(np.max(np.linalg.norm(magmoms, axis=1))) return magmoms / largest if largest > 1e-12 else magmoms def _numbers(base) -> list[int]: types = {symbol: n + 1 for n, symbol in enumerate(dict.fromkeys(base.supercell_symbols))} return [types[symbol] for symbol in base.supercell_symbols] def numbered_components(analyses, elements) -> list: """``(element, component)`` of every listed basis, numbered from 1 in this order: the rows of the table of magnetic groups of every element (the components with a field and a classification), element by element.""" listed = [] for element, analysis in zip(elements, analyses): for component in analysis.components: if component.field is None or component.collinear is None: continue listed.append((element, component)) return listed # ------------------------------------------------------------ analysis
[docs] def analyze_multi_element(cell=None, elements=(), qpoint=("GM",), *, symprec: float = 1e-5, conventional: bool = False, classify: bool = True, vibrations=None) -> MultiElementAnalysis: """Spin bases on the sites of several elements at one q point. Args: cell: The crystal (phonopy ``PhonopyAtoms``); not needed with ``vibrations``. elements: Two or more elements (``["Al", "Ni"]``). qpoint: As in :func:`crystod.spin_basis.analyze_spin_basis`. symprec: Symmetry tolerance (Angstrom). conventional: Use the conventional cell as the magnetic cell. classify: Classify the bases and the combined arrangements. vibrations: A prebuilt ``SymmetryOnlyVibrations(cell, standardize=False)``. Returns: A :class:`MultiElementAnalysis`. Raises: SystemExit: An element not in the cell (``ValueError`` through ``crystod.mag``). ValueError: An element given twice, or as in ``analyze_spin_basis``. Example: >>> from phonopy.interface.vasp import read_vasp >>> from crystod import mag >>> multi = mag.analyze_multi_element(read_vasp("221_PPOSCAR_AlNi3"), ["Al", "Ni"], "GM") >>> multi.decomposition {'GM4+(3)': 3, 'GM5+(3)': 1} """ from .spin_basis import analyze_spin_basis from .vibration_modes import SymmetryOnlyVibrations elements = [str(e) for e in elements] if len(set(elements)) != len(elements): raise ValueError(f"an element is given twice: {' '.join(elements)}") if vibrations is None: vibrations = SymmetryOnlyVibrations(cell=cell, symprec=symprec, standardize=False) analyses = [analyze_spin_basis(element=element, qpoint=qpoint, symprec=symprec, conventional=conventional, classify=classify, vibrations=vibrations) for element in elements] base = analyses[0] site_indices = sorted(i for analysis in analyses for i in analysis.site_indices) decomposition: dict[str, int] = {} for analysis in analyses: for label, count in analysis.decomposition.items(): decomposition[label] = decomposition.get(label, 0) + count # the element in the VESTA names of the element-pure bases for element, analysis in zip(elements, analyses): for component in analysis.components: if component.vesta_name: component.vesta_name = component.vesta_name.replace( "_spin_", f"_spin_{element}_", 1) multi = MultiElementAnalysis(elements=elements, analyses=analyses, site_indices=site_indices, decomposition=decomposition) multi.numbered = numbered_components(analyses, elements) tolerance = max(10.0 * float(vibrations.symprec), 1e-3) operations = _supercell_operations(base, vibrations, tolerance) numbers = _numbers(base) # copies of every irrep, element by element: (element, analysis, entry, rows) copies: dict[str, list] = {} for element, analysis in zip(elements, analyses): for entry_index, entry in enumerate(analysis.entries): copies.setdefault(entry[0], []).append((element, analysis, entry_index)) for label, members in copies.items(): if len({element for element, _, _ in members}) < 2: continue prepared = [] for element, analysis, entry_index in members: rows = _entry_rows(analysis, entry_index) if rows is None: multi.notes.append(f"{element} {label}: a basis row has no real field; " "its copy is not combined.") continue magmoms = np.array([component_magmoms(analysis, c) for c in rows]) matrices, span_residual = _row_matrices(magmoms, operations) header = analysis.components[[c.entry_index for c in analysis.components] .index(entry_index)].header prepared.append(dict(element=element, analysis=analysis, entry=entry_index, rows=magmoms, matrices=matrices, header=header, span_residual=span_residual)) if len({p["element"] for p in prepared}) < 2: continue reference = prepared[0] for member in prepared: if member is reference: member["map"] = np.eye(len(reference["rows"])) continue matrix, residual = _intertwiner(reference["matrices"], member["matrices"]) residual = max(residual, member["span_residual"], reference["span_residual"]) identity = matrix is not None and np.allclose(matrix, np.eye(len(matrix)), atol=1e-6) member["map"] = matrix multi.relations.append(CopyRelation( label=label, reference=(reference["element"], reference["header"]), copy=(member["element"], member["header"]), map=matrix, identity=identity, residual=residual)) # one copy per element, the representative from the first element by_element: dict[str, list] = {} for member in prepared: if member.get("map") is not None: by_element.setdefault(member["element"], []).append(member) groups = [by_element[e] for e in elements if e in by_element] if len(groups) < 2: continue for choice in itertools.product(*groups): first = choice[0] basis = first["rows"].reshape(len(first["rows"]), -1).T own = [c for c in first["analysis"].components if c.entry_index == first["entry"]] # the coefficients of the reference copy's rows in the reference # rows themselves (the first element's copy need not be the reference) to_first = first["map"] for component in own: if component.field is None: continue target = component_magmoms(first["analysis"], component).ravel() coefficients, *_ = np.linalg.lstsq(basis, target, rcond=None) if np.max(np.abs(basis @ coefficients - target)) > 1e-6: continue # back to the reference rows, then to every copy reference_coefficients = np.linalg.lstsq(to_first, coefficients, rcond=None)[0] parts = [] for member in choice: c = member["map"] @ reference_coefficients rows = member["rows"] part = _normalized(np.tensordot(c, rows, axes=1)) # the sign of the listed component of this copy along the # same direction, where there is one (the signs then refer # to the components as listed) for listed in member["analysis"].components: if listed.entry_index != member["entry"] or listed.field is None: continue other = component_magmoms(member["analysis"], listed) if np.allclose(other, -part, atol=1e-6): part = -part break if np.allclose(other, part, atol=1e-6): break parts.append(part) for tail in itertools.product((1, -1), repeat=len(choice) - 1): signs = (1,) + tail magmoms = sum(s * p for s, p in zip(signs, parts)) arrangement = CombinedArrangement( label=label, copies=tuple((m["element"], m["header"]) for m in choice), tag=component.file_tag or component.tag, signs=signs, magmoms=magmoms, field=_site_field(base, magmoms, site_indices), net_moment=np.sum(magmoms, axis=0), direction_label=component.direction_label, ) if classify: (arrangement.group, arrangement.responses, arrangement.collinear, _) = _classify(base, vibrations, magmoms, site_indices, numbers) multi.combined.append(arrangement) # VESTA names of the combined arrangements, up to the cap formula = base.formula conv_tag = "_conv" if conventional else "" used: set[str] = set() for index, arrangement in enumerate(multi.combined): if index >= COMBINED_FILE_CAP: break kinds = "-".join(_kind_tag(header) for _, header in arrangement.copies) signs = "".join("p" if s > 0 else "m" for s in arrangement.signs) short = arrangement.label.split("(")[0] stem = (f"POSCAR_{formula}_spin_{arrangement.elements_text.replace('+', '-')}_{short}_" f"{kinds}_{arrangement.tag}_{signs}{conv_tag}") name, suffix = f"{stem}.vesta", 2 while name in used: name, suffix = f"{stem}_{suffix}.vesta", suffix + 1 used.add(name) arrangement.vesta_name = name if len(multi.combined) > COMBINED_FILE_CAP: multi.notes.append( f"{len(multi.combined)} combined arrangements; VESTA files are written for the first " f"{COMBINED_FILE_CAP} only (all are in the table): use --superpose N N " "--coefficients a b for any other one.") return multi
def _kind_tag(header: str) -> str: """``"dipole"`` from ``"GM4+(3) [FM, dipole]"``, ``"AFM"`` from ``"X5+(2) [AFM (q != 0)]"``.""" inner = header[header.index("[") + 1: header.rindex("]")] if "[" in header else header parts = [p.strip() for p in inner.split(",")] return parts[-1] if len(parts) > 1 else parts[0].split()[0]
[docs] def superpose_bases(listed, numbers, coefficients=None, *, vibrations=None, classify: bool = True) -> Superposition: """Superpose listed bases with given coefficients. Args: listed: A :class:`MultiElementAnalysis`, or a single :class:`crystod.spin_basis.SpinBasisAnalysis` (its bases numbered as the rows of its table of magnetic groups). numbers: The numbers of the bases (1-based). coefficients: One coefficient per number (default 1 each); every basis enters as listed (largest moment 1). vibrations: The ``SymmetryOnlyVibrations`` of the crystal (needed to classify). classify: Compute the magnetic space group, responses and class. Returns: A :class:`Superposition` (moments scaled to largest 1). Raises: ValueError: A number out of range, a number given twice, a count of coefficients that differs from the count of numbers, or a vanishing superposition. """ if isinstance(listed, MultiElementAnalysis): analyses, elements = listed.analyses, listed.elements numbered = listed.numbered site_indices = listed.site_indices else: analyses, elements = [listed], [listed.element] numbered = numbered_components(analyses, elements) site_indices = list(listed.site_indices) base = analyses[0] numbers = [int(n) for n in numbers] if coefficients is None: coefficients = [1.0] * len(numbers) coefficients = [float(c) for c in coefficients] if len(coefficients) != len(numbers): raise ValueError(f"--coefficients needs one value per basis of --superpose " f"({len(numbers)} bases, {len(coefficients)} coefficients)") if len(set(numbers)) != len(numbers): raise ValueError("a basis number is given twice in --superpose") bad = [n for n in numbers if not 1 <= n <= len(numbered)] if bad: raise ValueError(f"basis number(s) {bad} not listed (1-{len(numbered)})") magmoms = np.zeros((len(base.supercell_symbols), 3)) parts = [] for number, coefficient in zip(numbers, coefficients): element, component = numbered[number - 1] analysis = analyses[elements.index(element)] magmoms = magmoms + coefficient * component_magmoms(analysis, component) parts.append((number, element, component.header, component.file_tag or component.tag, coefficient)) norm = float(np.sum(magmoms * magmoms)) if norm < 1e-20: raise ValueError("the superposition vanishes") content = [] for element, analysis in zip(elements, analyses): for entry_index in range(len(analysis.entries)): rows = _entry_rows(analysis, entry_index) if rows is None: continue basis = np.array([component_magmoms(analysis, c).ravel() for c in rows]).T projected = basis @ np.linalg.lstsq(basis, magmoms.ravel(), rcond=None)[0] weight = float(projected @ projected) / norm if weight > 1e-8: content.append((element if len(elements) > 1 else "", rows[0].header, weight)) magmoms = _normalized(magmoms) result = Superposition(numbers=tuple(numbers), coefficients=tuple(coefficients), parts=parts, magmoms=magmoms, field=_site_field(base, magmoms, site_indices), net_moment=np.sum(magmoms, axis=0), irrep_content=content) if classify and vibrations is not None: result.group, result.responses, result.collinear, _ = _classify( base, vibrations, magmoms, site_indices, _numbers(base)) conv_tag = "_conv" if base.conventional_centring is not None else "" from .spin_basis import _qpoint_file_tag tag = "_".join(str(n) for n in numbers) result.vesta_name = (f"POSCAR_{base.formula}_spin_superposition_{tag}_" f"{_qpoint_file_tag(base).replace('_conv', '')}{conv_tag}.vesta") return result
# ------------------------------------------------------------ text def multi_report_name(multi: MultiElementAnalysis, classify_only: bool = False) -> str: """``samm_<formula>_<El1>-<El2>_<q>`` (``_classify`` with ``--classify-only``), e.g. ``"samm_AlNi3_Al-Ni_GM"``.""" from .spin_basis import _qpoint_file_tag name = f"samm_{multi.base.formula}_{'-'.join(multi.elements)}_{_qpoint_file_tag(multi.base)}" return name + ("_classify" if classify_only else "") MULTI_SUMMARY_HEADERS = ( "no.", "element", "basis", "component", "MSG (BNS)", "type", "MPG", "net magnetization", "class", "MSG (UNI)", ) def _group_cells(group, responses, collinear): if group is not None and group.identified: cells = (f"{group.bns_symbol} ({group.bns_number})", group.type_name, str(group.magnetic_point_group)) uni = group.uni_symbol or "-" else: cells, uni = ("-", "-", "-"), "-" magnetization = responses.magnetization_direction if responses is not None else "-" klass = collinear.short_name if collinear is not None else "-" return cells, magnetization, klass, uni
[docs] def multi_summary_rows(multi: MultiElementAnalysis) -> list[tuple[str, ...]]: """Rows of the table of magnetic groups of a multi-element run: every listed basis (numbered) and every combined arrangement (``-``).""" rows = [] for number, (element, component) in enumerate(multi.numbered, start=1): cells, magnetization, klass, uni = _group_cells(component.group, component.responses, component.collinear) rows.append((str(number), element, component.header, component.file_tag or component.tag, *cells, magnetization, klass, uni)) for arrangement in multi.combined: cells, magnetization, klass, uni = _group_cells(arrangement.group, arrangement.responses, arrangement.collinear) rows.append(("-", arrangement.elements_text, arrangement.header, arrangement.component_text, *cells, magnetization, klass, uni)) return rows
def _table(rows) -> list[str]: widths = [max(len(row[c]) for row in rows) for c in range(len(rows[0]))] return [" ".join(cell.ljust(width) for cell, width in zip(row, widths)).rstrip() for row in rows]
[docs] def format_multi_summary(multi: MultiElementAnalysis) -> list[str]: """The ``* Magnetic groups and collinear classes *`` block of a multi-element run (table and notes).""" from .spin_basis import magnetic_summary_notes lines = ["* Magnetic groups and collinear classes *"] lines += _table([MULTI_SUMMARY_HEADERS] + multi_summary_rows(multi)) notes = [] for analysis in multi.analyses: for note in magnetic_summary_notes(analysis): if note not in notes: notes.append(note) notes += [ "no.: the number of a listed basis for --superpose; element: the element whose sites " "carry the moments (A+B: a combined arrangement, one copy per element);", "(+,-): the relative signs of the printed moments of each element's copy (the sign of " "a basis vector is a convention), each copy with largest moment 1.", ] return lines + [""] + notes
[docs] def format_copy_relations(multi: MultiElementAnalysis) -> list[str]: """The ``* Copies of one irrep on several elements *`` block.""" lines = ["* Copies of one irrep on several elements *"] labels = list(dict.fromkeys(r.label for r in multi.relations)) if not labels: lines.append(" no irrep occurs on two or more of the elements: no combined " "arrangements") return lines for label in labels: relations = [r for r in multi.relations if r.label == label] reference = relations[0].reference lines.append(f" {label}: reference {reference[0]} {reference[1]}") for relation in relations: lines.append(f" {relation.copy[0]} {relation.copy[1]}: {relation.text()}") n_combined = len(multi.combined) lines += [ " Every copy of one irrep transforms with the same irrep matrices (on its rows, or " "through the map given), so a real superposition of copies along the same " "order-parameter direction, with any nonzero amplitudes, has the magnetic space group " "of each copy alone: the table irrep x direction -> magnetic space group is complete; " "the relative amplitudes of the copies are free parameters that symmetry does not fix.", f" {n_combined} combined arrangements below: one copy per element along every " "direction of the first element's copy, each copy with largest moment 1, with the " "relative signs (+,+), (+,-), ... of the printed moments (the sign of a basis vector " "is a convention).", ] lines += [f" NOTE: {note}" for note in multi.notes] return lines
def format_superposition(result: Superposition, phonon_angular_momentum: bool = False, sites=None) -> list[str]: """The ``* Superposition *`` block of ``--superpose``.""" lines = ["* Superposition *"] for number, element, header, tag, coefficient in result.parts: who = f"{element} " if element else "" lines.append(f" [{number}] {who}{header} {tag}: coefficient {coefficient:g}") lines.append(f" irrep content (squared weights): {result.irrep_text()}") for name, spin in (sites or []): lines.append(f" {name}: S = [{spin[0]: .4f}, {spin[1]: .4f}, {spin[2]: .4f}]") lines.append(f" net moment over the magnetic cell: {np.round(result.net_moment, 6).tolist()}") lines += _classification_lines(result, phonon_angular_momentum, " ") return lines def _classification_lines(item, phonon_angular_momentum: bool, indent: str) -> list[str]: from .magnetic_group import ( format_magnetic_group, format_magnetic_point_group, format_unified_symbols, phonon_angular_momentum as pam, unconfirmed_note, ) lines = [] if item.group is None: lines.append(f"{indent}magnetic space group: not identified by spglib") else: lines.append(f"{indent}magnetic space group: {format_magnetic_group(item.group)}") if unconfirmed_note(item.group): lines.append(f"{indent}{unconfirmed_note(item.group)}") lines.append(f"{indent}magnetic point group: {format_magnetic_point_group(item.group)}") unified = format_unified_symbols(item.group) if unified is not None: lines.append(f"{indent}UNI symbol: {unified}") if item.responses is not None: lines.append(f"{indent}allowed by symmetry: {item.responses.summary()}") if item.collinear is not None: lines.append(f"{indent}collinear order: {item.collinear.text()}") if phonon_angular_momentum: text = (pam(item.group).text() if item.group is not None else "magnetic point group not determined") lines.append(f"{indent}phonon angular momentum: {text}") return lines def _site_names(multi_or_analysis, field) -> list: """``(name, spin)`` of the selected sites of cell 0: ``Al1``, ``Ni1``, ...""" if isinstance(multi_or_analysis, MultiElementAnalysis): symbols = list(multi_or_analysis.base.symbols) sites = multi_or_analysis.site_indices else: symbols = list(multi_or_analysis.symbols) sites = list(multi_or_analysis.site_indices) counters: dict[str, int] = {} names = [] for k, site in enumerate(sites): symbol = symbols[site] counters[symbol] = counters.get(symbol, 0) + 1 names.append((f"{symbol}{counters[symbol]}", field[0, k])) return names _MAGNETIC_SYMBOLS: dict = {} def _magnetic_symbols(base) -> set: return _MAGNETIC_SYMBOLS.get(id(base), set()) def write_moments_vesta(base, magmoms, name: str, title: str, amplitude: float) -> None: """A VESTA file of the magnetic cell with the moments as arrows.""" from .phonon_vector import write_vesta_with_arrows write_vesta_with_arrows(filepath=name, lattice=base.supercell_lattice, scaled_positions=base.supercell_positions, symbols=base.supercell_symbols, arrows_cartesian=np.asarray(magmoms) * amplitude, title=title) # ------------------------------------------------------------ the command def print_multi_analysis(multi: MultiElementAnalysis, args) -> list[str]: """Print the q-point report of a multi-element run (``crystod-mag --element A B --qpoint q``); returns the files written.""" from .spin_basis import ( _direction_line, _print_qe_noncollinear, format_direction_table, format_parent_operations, format_phonon_angular_momentum, paramagnetic_point_group, ) base = multi.base _MAGNETIC_SYMBOLS[id(base)] = set(multi.elements) pam_flag = getattr(args, "phonon_angular_momentum", False) show_operations = getattr(args, "show_operations", False) print("\n* Selected Q point *") print(f" Selected q-point: {base.qpoint_label} = {base.qpoint}") print("\n* Spin (axial-vector) representation *") total = sum(3 * a.n_sites for a in multi.analyses) print(f" Spin (axial-vector) representation on {', '.join(multi.elements)} sites: " f"{total} dimensions") def decomposition_text(decomposition): return " + ".join((f"{count} x {label}" if count > 1 else label) for label, count in decomposition.items()) for element, analysis in zip(multi.elements, multi.analyses): print(f" Decomposition ({element}, {3 * analysis.n_sites} dimensions): " f"{decomposition_text(analysis.decomposition)}") print(f" Decomposition (total): {decomposition_text(multi.decomposition)}") print("\n* Symmetry-adapted spin bases *") for element, analysis in zip(multi.elements, multi.analyses): for label, kind, rank_name, space in analysis.entries: rank_text = f", {rank_name}" if rank_name else "" print(f" {element} {label}: dim {space.shape[0]} [{kind}{rank_text}]") if not base.is_gamma or base.conventional_centring is not None: print("\n* Magnetic cell *") if not base.is_gamma: sizes = base.supercell_sizes print(f" Magnetic (commensurate) supercell: {sizes[0]}x{sizes[1]}x{sizes[2]}") if base.conventional_centring is not None: multiples = base.conventional_multiples print(f" Display cell: conventional ({base.conventional_centring} centring), " f"{multiples[0]}x{multiples[1]}x{multiples[2]} cells") if base.conventional_note: print(f" {base.conventional_note}") if not base.is_gamma: for element, analysis in zip(multi.elements, multi.analyses): lines = format_direction_table(analysis) if lines: lines[0] = lines[0].replace("* Order-parameter directions *", f"* Order-parameter directions ({element}) *") print() print("\n".join(lines)) print() print("\n".join(format_copy_relations(multi))) written: list[str] = [] numbers = {id(component): n for n, (_, component) in enumerate(multi.numbered, start=1)} if not args.classify_only: for element, analysis in zip(multi.elements, multi.analyses): for entry_index, (label, kind, rank_name, _) in enumerate(analysis.entries): header = f"{label} [{kind}" + (f", {rank_name}]" if rank_name else "]") print(f"\n* {element}: {header} *") for component in analysis.components: if component.entry_index != entry_index: continue if component.field is None: print(f" component {component.tag}: vanishing real spin field; skipped.") continue number = numbers.get(id(component)) suffix = f" [{number}]" if number else "" print(f" component {component.tag}{suffix}:") for k in range(analysis.n_sites): s = component.field[0, k] print(f" {element}{k + 1}: S = [{s[0]: .4f}, {s[1]: .4f}, {s[2]: .4f}]") net = component.net_moment where = "" if base.is_gamma else " over the magnetic supercell" print(f" net moment{where}: {np.round(net, 6).tolist()}") if not base.is_gamma: line = _direction_line(component) if line: print(f" {line}") if component.collinear is not None: print("\n".join(_classification_lines(component, pam_flag, " "))) if show_operations: print("\n".join(format_parent_operations(analysis, component))) magmoms = component_magmoms(analysis, component) _print_moments(base, magmoms, args, element) write_moments_vesta(base, magmoms, component.vesta_name, f"{base.formula} spin basis: {element} {label} " f"{component.tag}", args.amplitude) written.append(component.vesta_name) for arrangement in multi.combined: print(f"\n* {arrangement.elements_text}: {arrangement.header} " f"{arrangement.component_text} *") for name, spin in _site_names(multi, arrangement.field): print(f" {name}: S = [{spin[0]: .4f}, {spin[1]: .4f}, {spin[2]: .4f}]") where = "" if base.is_gamma else " over the magnetic supercell" print(f" net moment{where}: {np.round(arrangement.net_moment, 6).tolist()}") if arrangement.direction_label: print(f" order-parameter direction: {arrangement.direction_label}") print("\n".join(_classification_lines(arrangement, pam_flag, " "))) if show_operations: print("\n".join(format_parent_operations(base, arrangement))) if arrangement.vesta_name: _print_moments(base, arrangement.magmoms, args, multi.elements[0]) write_moments_vesta(base, arrangement.magmoms, arrangement.vesta_name, f"{base.formula} combined: {arrangement.header} " f"{arrangement.component_text}", args.amplitude) written.append(arrangement.vesta_name) print() print("\n".join(format_multi_summary(multi))) if args.classify_only and pam_flag: symbol, rotations, flags = paramagnetic_point_group(base) from .magnetic_group import phonon_angular_momentum as pam rows = [("paramagnetic", "-", symbol, pam(rotations, flags))] for number, (element, component) in enumerate(multi.numbered, start=1): group = component.group symbol = (str(group.magnetic_point_group) if group is not None and group.identified else "-") rows.append((f"[{number}] {element} {component.header}", component.file_tag or component.tag, symbol, pam(group) if group is not None else None)) for arrangement in multi.combined: group = arrangement.group symbol = (str(group.magnetic_point_group) if group is not None and group.identified else "-") rows.append((f"{arrangement.elements_text} {arrangement.header}", arrangement.component_text, symbol, pam(group) if group is not None else None)) print() print("\n".join(format_phonon_angular_momentum(base, rows=rows))) if args.classify_only and show_operations: print("\n* Symmetry operations kept and broken *") for number, (element, component) in enumerate(multi.numbered, start=1): print(f"[{number}] {element} {component.header} {component.file_tag or component.tag}:") print("\n".join(format_parent_operations(multi.analysis_of(element), component, indent=" "))) for arrangement in multi.combined: print(f"{arrangement.elements_text} {arrangement.header} " f"{arrangement.component_text}:") print("\n".join(format_parent_operations(base, arrangement, indent=" "))) return written def _print_moments(base, magmoms, args, element: str) -> None: """The spin directions of all atoms and the MAGMOM line (or the Quantum ESPRESSO input) of one field.""" from .spin_basis import _print_qe_noncollinear symbols = base.supercell_symbols magnetic = _magnetic_symbols(base) if args.conventional: note = " (conventional cell)" if base.is_gamma else " (conventional magnetic cell)" else: note = "" if base.is_gamma else f" ({base.supercell_sizes.tolist()} magnetic supercell)" print(f" spin directions (all atoms, POSCAR order){note}:") parts = [] for atom, s in enumerate(magmoms): if symbols[atom] in magnetic: text = f"{s[0]:.4f} {s[1]:.4f} {s[2]:.4f}" else: text = "0 0 0" parts.append(text) print(f" {symbols[atom]}{atom + 1}: [{text.replace(' ', ', ')}]") if getattr(args, "format", "vasp") == "qe": for name in sorted(magnetic): _print_qe_noncollinear(symbols, [np.asarray(s) if symbols[a] == name else np.zeros(3) for a, s in enumerate(magmoms)], name) else: print(f" MAGMOM = {' '.join(parts)}") def print_superposition(listed, result: Superposition, args) -> list[str]: """Print the ``* Superposition *`` block and its moments; write its VESTA file (not with ``--classify-only``); returns the files written.""" base = listed.base if isinstance(listed, MultiElementAnalysis) else listed if isinstance(listed, MultiElementAnalysis): _MAGNETIC_SYMBOLS[id(base)] = set(listed.elements) else: _MAGNETIC_SYMBOLS[id(base)] = {listed.element} print() print("\n".join(format_superposition(result, getattr(args, "phonon_angular_momentum", False), _site_names(listed, result.field)))) if args.classify_only: return [] _print_moments(base, result.magmoms, args, "") title = "superposition " + " + ".join(f"{c:g} [{n}]" for n, c in zip(result.numbers, result.coefficients)) write_moments_vesta(base, result.magmoms, result.vesta_name, f"{base.formula} {title}", args.amplitude) return [result.vesta_name] def survey_lines(vibrations, elements, site_lists, q_names, q_list) -> list[str]: """The survey (no ``--qpoint``) of several elements: the decomposition of every element and of the total at every special k point.""" from .runtime_compat import get_character from .spin_basis import _conjugate_pairs, _pair_label, get_spin_representation def terms(site_indices, q): irreps, spin_rep, mapping = get_spin_representation(vibrations, site_indices, q) labels = vibrations.get_irrep_labels(q, irreps, mapping) characters_rep = np.array([np.trace(matrix) for matrix in spin_rep]) counts = {} for index, irrep in enumerate(irreps): characters = np.array(get_character(irrep), dtype=complex) count = int(round(float(np.real(np.dot(characters_rep, np.conj(characters)))) / len(spin_rep))) if count > 0: counts[index] = count pairs = (_conjugate_pairs(irreps, labels, set(counts)) if np.allclose(2.0 * np.asarray(q), np.rint(2.0 * np.asarray(q))) else {}) seconds = set(pairs.values()) out = [] 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]]) out.append(f"{count}.0 [{label}]") return " + ".join(out) lines = [] union = sorted(i for sites in site_lists for i in sites) for name, q in zip(q_names, q_list): lines.append(f" k point (primitive): {name} {np.round(q, 6).tolist()}") for element, sites in zip(elements, site_lists): lines.append(f" {element}: {terms(sites, q)}") lines.append(f" total: {terms(union, q)}") return lines __all__ = [ "COMBINED_FILE_CAP", "CopyRelation", "CombinedArrangement", "Superposition", "MultiElementAnalysis", "analyze_multi_element", "superpose_bases", "numbered_components", "component_magmoms", "multi_summary_rows", "format_multi_summary", "format_copy_relations", "format_superposition", "multi_report_name", "print_multi_analysis", "print_superposition", "survey_lines", "run_multi_element", ] def run_multi_element(args) -> None: """``crystod-mag -c POSCAR --element A B [...]``: the survey or the q-point report of several elements, saved as the single-element runs save theirs (``samm_<formula>_<A>-<B>_<q>``, ``..._classify``, ``samm_<formula>_<A>-<B>_survey``).""" import contextlib from .cli.common import SavedReport from .spin_basis import _Tee if args.qpoint is None or args.classify_only: enabled = not args.no_files and getattr(args, "subgroup_poscar", None) is None with SavedReport(enabled=enabled, announce=not args.classify_only) as saved: args.saved_report = saved _run_multi(args) return tee = _Tee(sys.stdout) with contextlib.redirect_stdout(tee): multi = _run_multi(args) with open(multi_report_name(multi), "w", encoding="utf-8") as handle: handle.write(tee.copy.getvalue()) def _run_multi(args): """The body of :func:`run_multi_element`: returns the analysis of a q-point run, None for the survey.""" from .magnetic_group import ALTERMAGNET_REFERENCE, PHONON_ANGULAR_MOMENTUM_REFERENCE from .phonon_vector import reduced_formula from .spin_basis import ( _require_primitive, supercell_poscar_name, write_supercell_poscar, ) from .star_of_k import read_poscar_or_exit from .vibration_modes import SymmetryOnlyVibrations if getattr(args, "subgroup_poscar", None) is not None: raise SystemExit("ERROR: --subgroup-poscar takes one element.") elements = list(args.elements) if len(set(elements)) != len(elements): raise SystemExit(f"ERROR: an element is given twice: {' '.join(elements)}") cell = read_poscar_or_exit(args.poscar) vibrations = SymmetryOnlyVibrations(cell=cell, symprec=args.tolerance, standardize=False) try: _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 missing = [e for e in elements if e not in symbols] if missing: available = ", ".join(sorted(set(symbols))) raise SystemExit(f"ERROR: element '{missing[0]}' is not in this POSCAR ({available}).") site_lists = [[i for i, s in enumerate(symbols) if s == e] for e in elements] print("\n* Structure *") print(f" Space group: {vibrations.spglib_dataset['international']} " f"(#{vibrations.spglib_dataset['number']})") print(" Magnetic sites: " + ", ".join(f"{e} x {len(s)}" for e, s in zip(elements, site_lists))) for element, sites in zip(elements, site_lists): for k, index in enumerate(sites): print(f" {element}{k + 1}: {np.round(positions[index], 6).tolist()}") if args.qpoint is None: from phonopy.structure.cells import get_primitive_matrix_by_centring from .irreptables_compat import load_irreptables from .phonon_irreps import get_irt_special_points IrrepTable, _ = load_irreptables() dataset = vibrations.spglib_dataset irt_table = IrrepTable(dataset["number"], spinor=False) primitive_matrix = get_primitive_matrix_by_centring(dataset["international"][0]) 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 " f"{', '.join(elements)} sites *") print("\n".join(survey_lines(vibrations, elements, site_lists, q_names, q_list))) 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 = f"samm_{reduced_formula(symbols)}_{'-'.join(elements)}_survey" return None try: multi = analyze_multi_element(elements=elements, qpoint=args.qpoint, symprec=args.tolerance, conventional=args.conventional, vibrations=vibrations) except ValueError as exc: raise SystemExit(f"ERROR: {' '.join(str(exc).split())}") from None written = print_multi_analysis(multi, args) if getattr(args, "superpose", None) is not None: try: result = superpose_bases(multi, args.superpose, args.coefficients, vibrations=vibrations) except ValueError as exc: raise SystemExit(f"ERROR: {exc}") from None written += print_superposition(multi, result, args) base = multi.base report = None if args.classify_only else multi_report_name(multi) supercell_poscar = None if report: supercell_poscar = supercell_poscar_name(base, args.poscar) write_supercell_poscar(base, supercell_poscar, args.poscar) if written or report: print("\n* Output files *") for name in written: print(f" Spin basis written to: {name}") 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 report: print(f" Report written to: {report} (this output)") saved = getattr(args, "saved_report", None) if args.classify_only else None if saved is not None and saved.active: saved.name = multi_report_name(multi, classify_only=True) print("\n* Output files *") print(saved.line()) print() 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): print(f"Reference (phonon angular momentum): {PHONON_ANGULAR_MOMENTUM_REFERENCE}.") return multi