"""Displacement patterns of given irreps on a crystal (crystod-phonon -c POSCAR --element EL --irrep IR).
``crystod-group --parent SG --irrep IR [IR2 ...]`` lists the isotropy
subgroups of a space group G, one row per order-parameter direction eta, from
the real, physically irreducible full-star matrices D(g) of every irrep
(:class:`crystod.isotropy_subgroup.InducedRepresentation`). This module
places every row on the atoms of a real crystal: it builds, for every irrep
nu, displacement modes on the atoms of the chosen elements in a supercell S
that transform with exactly these matrices, and sums them with the components
of eta as coefficients. It is the displacement (polar-vector, time-even)
counterpart of :mod:`crystod.magnetic_arrangements` (``crystod-mag -c POSCAR
--element EL --irrep IR``) and reuses its machinery.
Displacement modes. The displacements of the chosen atoms of S span W_S
(dimension 3 N_S); an operation g = {R|t} of G acts as (O(g) u)(g r) = R u(r)
(no factor det(R), no time reversal): Gamma_disp(k) = Gamma_perm(k) x
Gamma_vector. The modes of irrep nu are the columns of an intertwiner Psi
(3 N_S x d_nu), O(g) Psi = Psi D(g) for every g of G/T_S, obtained by the
projection (Reynolds average) of :mod:`crystod.magnetic_arrangements`; the
multiplicity m of nu (character formula) is checked against the decomposition
of the displacement representation at the k point. One intertwiner per copy
is kept; the copies are split by element, then by Wyckoff orbit, then, at
q = 0, into the combination with a net shift of the orbit and those without.
Pattern of a row. For a table row with order parameter eta (the generic
representative the table identifies its group from) the pattern is
u = sum_nu c_nu (Psi_nu eta_nu) / max |Psi_nu eta_nu|,
scaled to the largest displacement ``amplitude``. eta -> u is linear,
injective and equivariant, so the stabilizer of u in G is the stabilizer of
eta: the isotropy subgroup of the row. Its number, symbol, size and index
come from the table by construction; the space group of the displaced
structure as written (all atoms) is nevertheless identified again with spglib
and compared with the row. These are symmetry-adapted displacement patterns,
not eigenvectors of a dynamical matrix: a real distortion of the row's
symmetry is a combination of the copies of the irreps with amplitudes that
only a force calculation fixes.
Example:
>>> from phonopy.interface.vasp import read_vasp
>>> from crystod import phonon
>>> cell = read_vasp("example/04-01_phonon_irrep/La3Ni2O7/PPOSCAR_La3Ni2O7_I4mmm")
>>> result = phonon.displacement_irrep_arrangements(cell, ["O"], ["X3-"])
>>> sorted({(a.number, a.row.label, a.row.number, a.check) for a in result.arrangements})
[(1, 'X3-(0;a)', 63, 'same'), (2, 'X3-(a;a)', 136, 'same'), (3, 'X3-(a;b)', 58, 'same')]
>>> [copy.text for copy in result.copies["X3-"]]
['O(8g)', 'O(4e)', 'O(2a)']
"""
from __future__ import annotations
import contextlib
import io
import itertools
import os
import re
from dataclasses import dataclass, field as dataclass_field
import numpy as np
from .magnetic_arrangements import (
MAX_CELLS,
MAX_COPY_CHOICES,
MAX_MULTIPLE,
MIN_RELATIVE_WEIGHT,
INTERTWINING_TOLERANCE,
IrrepCopy,
_block_diagonal,
_component_axes,
_copies_of,
_decomposition,
_default_weights,
_display_cell,
_expected_multiplicity,
_fixing_counts,
_format_value,
_Frame,
_IrrepPart,
_letter_values,
_moment_text,
_number_text,
_orbits,
_SupercellAction,
_written_translations,
)
#: Default largest displacement of the written structures (Angstrom).
DEFAULT_AMPLITUDE = 0.1
#: Length of the largest arrow of the VESTA files (Angstrom), independent of
#: the amplitude.
ARROW_LENGTH = 1.5
#: The amplitude and the smallest nonzero displacement of every pattern must
#: be at least this many times the symmetry tolerance, or the check on the
#: displaced structure could not see the distortion.
CHECK_FACTOR = 20.0
#: Decimals of the printed displacements (Angstrom).
DISPLACEMENT_DECIMALS = 4
_POINT_GROUP_ORDER = {
"1": 1, "-1": 2, "2": 2, "m": 2, "2/m": 4, "222": 4, "mm2": 4, "mmm": 8,
"4": 4, "-4": 4, "4/m": 8, "422": 8, "4mm": 8, "-42m": 8, "4/mmm": 16,
"3": 3, "-3": 6, "32": 6, "3m": 6, "-3m": 12, "6": 6, "-6": 6, "6/m": 12,
"622": 12, "6mm": 12, "-6m2": 12, "6/mmm": 24, "23": 12, "m-3": 24, "432": 24,
"-43m": 24, "m-3m": 48,
}
_POLAR = {"1", "2", "m", "mm2", "4", "4mm", "3", "3m", "6", "6mm"}
_CENTROSYMMETRIC = {"-1", "2/m", "mmm", "4/m", "4/mmm", "-3", "-3m", "6/m", "6/mmm", "m-3",
"m-3m"}
_PROPER = {"1", "2", "222", "4", "422", "3", "32", "6", "622", "23", "432"}
# ----------------------------------------------------------------- data classes
@dataclass(eq=False)
class DisplacementCopy(IrrepCopy):
"""One copy of an irrep in the displacement representation of the chosen
atoms (:class:`crystod.magnetic_arrangements.IrrepCopy` with the kinds
``"net shift"`` and ``"no net shift"`` at q = 0 and ``""`` at q != 0;
``intertwiner`` holds Cartesian displacements)."""
@property
def text(self) -> str:
"""``"O(4e) [net shift]"``: the description printed for the copy."""
return self.orbit if not self.kind else f"{self.orbit} [{self.kind}]"
@dataclass(eq=False)
class DisplacementRow:
"""One row of the table of ``crystod-group --parent SG --irrep ...``.
Attributes:
label: The direction label (``"X3-(0;a)"``, ``"X3-(0;a) X2+(0;c)"``).
components: The direction of every irrep (``("(0;a)", "(0;c)")``).
number, symbol: The isotropy subgroup (``63``, ``"Cmcm"``).
size: Primitive cells of the parent per primitive cell of the subgroup.
index: The index [G : H].
n_free: The number of free parameters of the direction.
"""
label: str
components: tuple
number: int
symbol: str
size: int
index: int
n_free: int
@property
def subgroup(self) -> str:
"""``"63 Cmcm"``."""
return f"{self.number} {self.symbol}"
[docs]
@dataclass(eq=False)
class DisplacementArrangement:
"""The displacement pattern of one table row (one choice of copies).
Attributes:
number: The row number of the table, from 1.
row: The :class:`DisplacementRow`.
copies: One :class:`DisplacementCopy` per irrep.
tag: ``""`` when every irrep has one copy, else the copy numbers
(``"c1-2"``).
order_parameter: The order parameter used (the irreps' parts
concatenated).
letters: ``{letter: value}`` of the free parameters.
coefficients: The weight of every irrep's part.
field: The displacements on the chosen atoms of the diagonal cell,
``(n_cells, n_sites, 3)``, Cartesian, largest 1 (not rounded).
displacements: The displacement of every atom of the written cell
(Angstrom, Cartesian, largest ``amplitude``), POSCAR order of the
written supercell.
displaced_positions: The fractional positions of the displaced
structure (written cell).
group_number, group_symbol: The space group spglib finds on the
displaced structure as written (None when not identified).
point_group: Its point group (spglib's symbol).
found_size, found_index: Size and index found on the structure.
check: ``"same"``, ``"enantiomorph"``, ``"different"`` or
``"not identified"``.
note: A NOTE for the row, or None.
n_fixing_field, n_fixing_order_parameter: Elements of G/T_S that fix
the displacements and the order parameter (equal by construction).
displacement_text: The line on the sizes of the displacements.
polar_axes: An orthonormal basis (rows, Cartesian) of the vectors
fixed by the operations of G/T_S that fix the pattern (the
directions a polarization may take).
vesta_name, poscar_name: The file names.
"""
number: int
row: DisplacementRow
copies: tuple
tag: str
order_parameter: np.ndarray = dataclass_field(repr=False)
letters: dict = dataclass_field(default_factory=dict)
coefficients: tuple = ()
field: np.ndarray = dataclass_field(default=None, repr=False)
displacements: np.ndarray = dataclass_field(default=None, repr=False)
displaced_positions: np.ndarray = dataclass_field(default=None, repr=False)
group_number: int | None = None
group_symbol: str | None = None
point_group: str | None = None
found_size: int | None = None
found_index: int | None = None
check: str = ""
note: str | None = None
n_fixing_field: int = 0
n_fixing_order_parameter: int = 0
displacement_text: str = ""
polar_axes: np.ndarray = dataclass_field(default=None, repr=False)
vesta_name: str = ""
poscar_name: str = ""
weight_reason: str | None = None
reproduce: np.ndarray = dataclass_field(default=None, repr=False)
fixing_translations: list = dataclass_field(default_factory=list, repr=False)
@property
def check_text(self) -> str:
"""The check column (``"63 Cmcm same"``)."""
if self.group_number is None:
return "not identified"
return f"{self.group_number} {self.group_symbol} {self.check}"
[docs]
@dataclass(eq=False)
class DisplacementIrrepAnalysis:
"""The displacement patterns of given irreps on a crystal
(``crystod-phonon -c POSCAR --element EL --irrep IR [IR2 ...]``).
The attributes parallel :class:`crystod.magnetic_arrangements.MagneticIrrepAnalysis`
(``kpoints``, ``decompositions``, ``multiplicities``, ``copies``,
``singles``, ``rows``, ``arrangements``, the written cell and the
diagonal cell); ``amplitude`` is the largest displacement in Angstrom,
``check_symprec`` the spglib tolerance of the check, ``singles`` maps
the label of every irrep of a coupled run to the rows of its own table
(as ``crystod-group --parent`` prints them).
"""
formula: str
elements: list
space_group: str
space_group_number: int
irreps: list
dimensions: list
kpoints: dict
decompositions: dict
multiplicities: dict
copies: dict
singles: dict
rows: list
arrangements: list
coefficients: tuple
amplitude: float
check_symprec: float
cell_matrix: np.ndarray
supercell_sizes: np.ndarray
cell_translations: list
supercell_lattice: np.ndarray
supercell_symbols: list
supercell_positions: np.ndarray
supercell_site_of_atom: list
supercell_cell_of_atom: list
site_indices: list
site_elements: list
residuals: dict = dataclass_field(default_factory=dict)
order_parameter_input: list | None = None
stratum: int | None = None
copy_note: str | None = None
unlabelled_kpoints: list = dataclass_field(default_factory=list)
parts: list = dataclass_field(default_factory=list, repr=False)
conventional_centring: str | None = None
conventional_multiples: np.ndarray | None = None
internal_cell_translations: list = dataclass_field(default_factory=list, repr=False)
conventional_note: str | None = None
symbol: str = ""
poscar_basename: str = "POSCAR"
@property
def n_cells(self) -> int:
"""Number of primitive cells of the written cell."""
return len(self.cell_translations)
# ------------------------------------------------------------------ the tables
def _row_components(label: str, n_parts: int) -> tuple:
"""``("(0;a)", "(0;c)")`` of ``"X3-(0;a) X2+(0;c)"``."""
pieces = re.findall(r"\S+?(\([^)]*\))", label)
if len(pieces) != n_parts:
raise ValueError(f"internal error: the direction label {label!r} has {len(pieces)} "
f"parts, not {n_parts} (please report this case).")
return tuple(pieces)
def _rows_of(records, n_parts):
rows = []
for index, n_free, label, info, size, extra in records:
row = DisplacementRow(label=label, components=_row_components(label, n_parts),
number=int(info.number), symbol=str(info.international_short),
size=int(size), index=int(index), n_free=int(n_free))
rows.append((row, np.asarray(extra["generic"], dtype=float), extra["projector"]))
return rows
def _tables(parent: str, labels: list):
"""The analyzer, its parts (``InducedRepresentation``), the singles (with
several irreps, each table as ``--parent`` prints it) and the rows with
their generic order parameters and projectors, in the order of
``crystod-group --parent SG --irrep ...``."""
from .isotropy_subgroup import IsotropyAnalyzer, _direction_records, _direction_results
analyzer = IsotropyAnalyzer(parent, labels if len(labels) > 1 else labels[0])
representation = analyzer.representation
if len(labels) == 1:
parts = [representation]
singles = {}
else:
parts = list(representation.parts)
singles, offset = {}, 0
for part in parts:
sub = IsotropyAnalyzer.from_representation(analyzer.algebra, part)
singles[part.label] = _direction_results(sub, letter_offset=offset)
offset += part.dimension
records = _rows_of(_direction_records(analyzer), len(parts))
return analyzer, parts, singles, records
def _resolve_irreps(algebra, irreps):
"""The representations of the labels, every invalid one reported at once."""
from .isotropy_subgroup import InducedRepresentation
labels, problems, representations = [], [], []
available = []
for label in irreps:
try:
with contextlib.redirect_stdout(io.StringIO()):
representation = InducedRepresentation(algebra, str(label))
except SystemExit as exc:
text = str(exc).removeprefix("ERROR: ")
lines = text.split("\n")
problems.append(lines[0])
if len(lines) > 1:
available = lines[1:]
continue
labels.append(str(label))
representations.append(representation)
names = [r.label for r in representations]
duplicates = sorted({n for n in names if names.count(n) > 1})
if duplicates:
problems.append(f"irrep {', '.join(duplicates)} is given twice.")
keep = [names.index(n) for n in dict.fromkeys(names)]
labels = [labels[i] for i in keep]
representations = [representations[i] for i in keep]
problems.extend(available)
return labels, representations, problems
def _order_parameter_target(analyzer, parts, records, tokens):
"""``(row, eta, stratum)`` of an ``--order-parameter`` vector: the row of
its exact stabilizer (as ``crystod-group --parent SG --irrep ...
--order-parameter`` identifies it), the vector, and the number of the
table row whose stratum holds it (None when no row does)."""
from .isotropy_subgroup import _arm_join, _projector, _rep_cache, _resolve_stratum
tokens = [str(token).strip() for token in tokens]
try:
with contextlib.redirect_stdout(io.StringIO()):
eta = np.asarray(analyzer.resolve_direction(tokens), dtype=float)
members, info, size, index, *_ = _resolve_stratum(analyzer, tokens)
except SystemExit as exc:
raise ValueError(str(exc).removeprefix("ERROR: ")) from None
cache = _rep_cache(analyzer.representation, analyzer.elements)
exact = [(analyzer.elements[g][0], analyzer.elements[g][1])
for g in np.nonzero(cache.vector_stabilizer_mask(eta))[0]]
projector = _projector(analyzer.fixed_space(exact))
representative = analyzer.canonical_projector(projector)
stratum = None
for number, (_, _, row_projector) in enumerate(records, start=1):
if row_projector.shape == representative.shape and np.allclose(
row_projector, representative, atol=1e-6):
stratum = number
break
components, start = [], 0
for part in parts:
piece = tokens[start:start + part.dimension]
components.append("(" + _arm_join(piece, part.arm_chunks) + ")")
start += part.dimension
label = " ".join(f"{part.label}{component}" for part, component in zip(parts, components))
row = DisplacementRow(label=label, components=tuple(components), number=int(info.number),
symbol=str(info.international_short), size=int(size),
index=int(index), n_free=0)
return row, eta, stratum
# ------------------------------------------------------------------ the check
def _file_symbol(symbol: str) -> str:
"""A space-group symbol made file-name safe the way the MPOSCAR names of
``--modulation``/``--subgroup --modulate`` do it (``/`` and blanks
dropped: ``P4_2/mnm`` -> ``P4_2mnm``)."""
return str(symbol).replace("/", "").replace(" ", "")
def _poscar_text(analysis, positions, comment):
from itertools import groupby
from .vasp_io import format_poscar
species, counts = [], []
for symbol, run in groupby(analysis.supercell_symbols):
species.append(str(symbol))
counts.append(len(list(run)))
return format_poscar(comment, analysis.supercell_lattice, species, counts, positions)
def _identify(text, symprec, parent_atoms, parent_point_order):
"""``(number, symbol, point group, size, index)`` of the structure of a
POSCAR text (spglib; the size from the atoms of the primitive cell, the
index from the point-group order), or None."""
import spglib
from .vasp_io import poscar_geometry
lines = text.splitlines()
geometry = poscar_geometry(lines, "the displaced structure")
species = lines[geometry.species_line].split()
kinds = {name: number for number, name in enumerate(dict.fromkeys(species), start=1)}
numbers = [kinds[name] for name, count in zip(species, geometry.counts)
for _ in range(count)]
triple = (geometry.lattice, geometry.positions, np.asarray(numbers))
try:
dataset = spglib.get_symmetry_dataset(triple, symprec=symprec)
except Exception: # noqa: BLE001 - spglib failure = not identified
dataset = None
if dataset is None:
return None
number = int(dataset.number)
symbol = str(dataset.international)
point_group = str(dataset.pointgroup)
primitive = spglib.find_primitive(triple, symprec=symprec)
if primitive is None:
return number, symbol, point_group, None, None
n_primitive = len(primitive[2])
size = n_primitive // parent_atoms if n_primitive % parent_atoms == 0 else None
order = _POINT_GROUP_ORDER.get(point_group)
index = (parent_point_order * size // order) if (size and order) else None
return number, symbol, point_group, size, index
def _verdict(row: DisplacementRow, found):
from .isotropy_subgroup import ENANTIOMORPHIC_PAIRS
if found is None:
return "not identified", ("NOTE: spglib could not identify the space group of the "
"displaced structure; the table's group is the stabilizer of "
"the order parameter.")
number, symbol, _, size, index = found
if number == row.number and size == row.size and index == row.index:
return "same", None
if ENANTIOMORPHIC_PAIRS.get(row.number) == number and size == row.size \
and index == row.index:
return "enantiomorph", (f"NOTE: spglib finds {number} {symbol} on the structure as "
f"written, the enantiomorphic partner type of the table's "
f"{row.subgroup}: the mirror-image order parameter of the "
"same stratum.")
return "different", (f"NOTE: spglib finds {number} {symbol} (size {size}, index {index}) on "
f"the displaced structure, not the table's {row.subgroup} (size "
f"{row.size}, index {row.index}); please report this case.")
def _polar_axes(action, field_points, inverse_cell=None):
"""The Cartesian vectors fixed by the operations of G/T_S that fix the
pattern: an orthonormal basis (rows)."""
from .magnetic_arrangements import MOMENT_TOLERANCE
flat = field_points[:, :, None]
scale = MOMENT_TOLERANCE * max(1.0, float(np.abs(field_points).max()))
stack = []
seen = set()
for g in range(action.order):
k = action.operations[g][0]
if k in seen:
continue
moved = action.apply(g, flat)[:, :, 0]
if np.abs(moved - field_points).max() < scale:
seen.add(k)
stack.append(action.operations[g][3] - np.eye(3))
if not stack:
return np.eye(3)
u, s, vt = np.linalg.svd(np.vstack(stack))
rank = int(np.sum(s > 1e-8))
return vt[rank:]
def _vector_text(vector) -> str:
vector = np.asarray(vector, dtype=float)
vector = vector / np.abs(vector).max()
pivot = int(np.argmax(np.abs(vector) > 1e-8))
if vector[pivot] < 0:
vector = -vector
return "[" + ", ".join(_format_value(v) for v in vector) + "]"
def allowed_text(arrangement: DisplacementArrangement) -> str | None:
"""``allowed by symmetry:`` line from the point group of the pattern."""
point_group = arrangement.point_group
if point_group is None:
return None
pieces = []
axes = arrangement.polar_axes
if point_group in _POLAR:
if axes is not None and len(axes) == 1:
pieces.append("electric polarization along "
f"{_vector_text(axes[0])} (Cartesian, POSCAR axes; polar point group "
f"{point_group})")
elif axes is not None and len(axes) == 2:
normal = np.cross(axes[0], axes[1])
pieces.append(f"electric polarization in the plane normal to {_vector_text(normal)} "
f"(Cartesian, POSCAR axes; polar point group {point_group})")
else:
pieces.append(f"electric polarization in any direction (point group {point_group})")
else:
pieces.append(f"no electric polarization (non-polar point group {point_group})")
pieces.append("inversion kept" if point_group in _CENTROSYMMETRIC else "inversion broken")
if point_group in _PROPER:
pieces.append("chiral (no improper operation)")
return "; ".join(pieces)
def _smallest_breaking(action, field_points) -> float:
"""min over the elements g of G/T_S that do not fix the pattern of
max over the atoms |(O(g) u - u)(r)| (largest displacement 1): how far
the least broken operation moves an atom off its image, the quantity
spglib has to resolve; inf when every element fixes the pattern."""
from .magnetic_arrangements import MOMENT_TOLERANCE
flat = field_points[:, :, None]
scale = MOMENT_TOLERANCE * max(1.0, float(np.abs(field_points).max()))
smallest = np.inf
for g in range(action.order):
moved = action.apply(g, flat)[:, :, 0]
difference = float(np.linalg.norm(moved - field_points, axis=1).max())
if difference >= scale:
smallest = min(smallest, difference)
return smallest
def _tolerance_text(what: str, amplitude: float, symprec: float) -> str:
return (f"{what} is below {CHECK_FACTOR:g} times the symmetry tolerance "
f"{float(symprec):g} A: spglib would not see that distortion, so the check on "
"the displaced structure would mean nothing. Give a larger --amplitude (now "
f"{amplitude:g} A) or a smaller --tolerance.")
def _require_primitive(vibrations) -> None:
""":func:`crystod.spin_basis._require_primitive` with the wording of
this mode."""
from .spin_basis import _require_primitive as require
try:
require(vibrations)
except ValueError as exc:
text = str(exc).replace(
"crystod-mag uses the cell as given (the spin listings and MAGMOM follow its atom "
"order)", "crystod-phonon --irrep uses the cell as given (the displacement listings "
"follow its atom order)").replace("the spin structures", "the displacement patterns")
raise ValueError(text) from None
# ---------------------------------------------------------------------- API
[docs]
def displacement_irrep_arrangements(
cell=None,
elements=(),
irreps=(),
*,
symprec: float = 1e-5,
coefficients=None,
classify: bool = True,
vibrations=None,
order_parameter=None,
copies=None,
conventional: bool = False,
amplitude: float = DEFAULT_AMPLITUDE,
poscar_name: str = "POSCAR",
) -> DisplacementIrrepAnalysis:
"""The displacement patterns of given irreps on a crystal.
The computation behind ``crystod-phonon -c POSCAR --element EL [EL2 ...]
--irrep IR [IR2 ...]``: for every row of the table of ``crystod-group
--parent SG --irrep IR [IR2 ...]`` (one irrep: its table; several: the
coupled table, every irrep condensed) the displacement pattern of the
atoms of the chosen elements that the row's order parameter describes
(see the module docstring), with the space group of the displaced
structure identified again with spglib. The patterns are symmetry
adapted, not eigenvectors of a dynamical matrix.
Args:
cell: The crystal (phonopy ``PhonopyAtoms``, a primitive cell); not
needed when ``vibrations`` is given.
elements: The elements whose atoms move (``["O"]``, ``["La", "O"]``).
irreps: ISO-IR labels (``["X3-"]``, ``["X3-", "X2+"]``; pair labels
such as ``GM2+GM3+`` accepted, as with ``--parent``).
symprec: Symmetry tolerance (spglib, Angstrom); also the tolerance of
the check on the displaced structure.
coefficients: The weight of every irrep's part (each part has its
largest displacement 1 before weighting); default per row 1 each,
or the first of 1 : 0.5, 1 : 0.75, ... under which no displacement
cancels between the parts.
classify: Identify the space group of every displaced structure.
vibrations: A prebuilt ``SymmetryOnlyVibrations(cell,
standardize=False)``.
order_parameter: ``--order-parameter`` tokens (irrep after irrep);
one pattern, of that vector, instead of one per row.
copies: One copy number (from 1) per irrep (``--copies``).
conventional: Write the patterns in the conventional cell (the cell
of ``crystod-mag --irrep --conventional``).
amplitude: The largest displacement of the written structures
(Angstrom).
poscar_name: The name of the input POSCAR (the base of the file
names ``M<name>_...`` and ``S<name>_...``).
Returns:
A :class:`DisplacementIrrepAnalysis`.
Raises:
ValueError: An element not in the cell, an unknown or repeated irrep,
an irrep the displacement representation of the elements does not
contain (the message lists the decomposition at its k point), a
supercell larger than the limits of the magnetic mode, a cell
that is not primitive, a wrong ``--order-parameter``, a zero,
nan or too small weight, a non-positive amplitude.
"""
from .phonon_vector import reduced_formula
from .spacegroup_product import DEN, SpaceGroupIrrepAlgebra
from .vibration_modes import SymmetryOnlyVibrations
elements = list(elements)
irreps = list(irreps)
if not elements:
raise ValueError("at least one element is needed.")
if not irreps:
raise ValueError("at least one irrep is needed.")
if len(set(elements)) != len(elements):
raise ValueError(f"an element is given twice: {' '.join(elements)}")
amplitude = float(amplitude)
if not np.isfinite(amplitude) or amplitude <= 0.0:
raise ValueError(f"--amplitude must be a positive number of Angstrom, not {amplitude:g}.")
if amplitude < CHECK_FACTOR * float(symprec):
raise ValueError(_tolerance_text(f"--amplitude {amplitude:g} A", amplitude, symprec))
if vibrations is None:
vibrations = SymmetryOnlyVibrations(cell=cell, symprec=symprec, standardize=False,
quiet=True)
_require_primitive(vibrations)
primitive = vibrations.primitive_cell
symbols = list(primitive.symbols)
missing = [e for e in elements if e not in symbols]
if missing:
available = ", ".join(sorted(set(symbols)))
raise ValueError(f"element '{missing[0]}' is not in this POSCAR ({available}).")
site_lists = [[i for i, s in enumerate(symbols) if s == e] for e in elements]
site_indices = [i for sites in site_lists for i in sites]
site_elements = [e for e, sites in zip(elements, site_lists) for _ in sites]
number = int(vibrations.spglib_dataset["number"])
parent = str(number)
with contextlib.redirect_stdout(io.StringIO()):
algebra = SpaceGroupIrrepAlgebra(parent)
labels, representations, problems = _resolve_irreps(algebra, irreps)
user_weights = coefficients is not None
if coefficients is not None:
coefficients = [float(c) for c in coefficients]
if len(coefficients) != len(irreps):
raise ValueError(f"--coefficients needs one value per irrep ({len(irreps)}), not "
f"{len(coefficients)}.")
bad = [c for c in coefficients if not np.isfinite(c) or c == 0.0]
if bad:
raise ValueError("--coefficients must be finite and nonzero (a negative value is "
"allowed: the other domain of that irrep); got "
+ " ".join(f"{c:g}" for c in coefficients) + ".")
largest_weight = max(abs(c) for c in coefficients)
small = [c for c in coefficients if abs(c) < MIN_RELATIVE_WEIGHT * largest_weight]
if small:
raise ValueError(
f"--coefficients {' '.join(f'{c:g}' for c in coefficients)}: a weight below "
f"{MIN_RELATIVE_WEIGHT:g} of the largest is not resolved in the displaced "
"structure.")
else:
coefficients = [1.0] * len(irreps)
if copies is not None:
copies = [int(c) for c in copies]
if len(copies) != len(irreps):
raise ValueError(f"--copies needs one copy number per irrep ({len(irreps)}), not "
f"{len(copies)}.")
frame = _Frame(vibrations, algebra)
# the k points, the decomposition of the displacement representation
# there; an irrep the atoms of the elements do not carry is refused
kpoints, decompositions, absent = {}, {}, []
unlabelled_k: set = set()
survey_entries = {}
for representation in representations:
kname = representation.irrep.kpname
q = frame.kpoint(representation.k)
q = [float(x) + 0.0 for x in np.round(q, 10)]
kpoints[representation.label] = (kname, q)
if kname not in decompositions:
lines = []
for element, sites in zip(elements, site_lists):
text, _ = _decomposition(vibrations, sites, q, polar=True)
lines.append((element, text))
if len(elements) > 1:
text, entries_total = _decomposition(vibrations, site_indices, q, polar=True)
lines.append(("total", text))
else:
entries_total = _decomposition(vibrations, site_indices, q, polar=True)[1]
decompositions[kname] = lines
survey_entries[kname] = entries_total
expected = _expected_multiplicity(representation, survey_entries[kname])
unlabelled = any(name.startswith("irrep_") for names, _, _ in survey_entries[kname]
for name in names)
if unlabelled:
unlabelled_k.add(kname)
elif expected == 0:
absent.append(representation)
if absent or problems:
messages = list(problems)
for representation in absent:
kname, q = kpoints[representation.label]
listed = "; ".join(f"{name}: {text}" if len(elements) > 1 or name == "total"
else text for name, text in decompositions[kname])
messages.append(
f"{representation.label} is not contained in the displacement representation "
f"of {', '.join(elements)} at {kname} {np.round(q, 6).tolist()}; the "
f"decomposition there is {listed}")
raise ValueError("\n".join(messages))
# the common supercell: diagonal, commensurate with every arm
from fractions import Fraction
sizes = np.ones(3, dtype=np.int64)
for representation in representations:
for arm in representation.arms:
k = frame.kpoint(arm)
for axis in range(3):
denominator = Fraction(float(k[axis])).limit_denominator(DEN).denominator
sizes[axis] = int(np.lcm(sizes[axis], denominator))
if sizes.max() > MAX_MULTIPLE or int(np.prod(sizes)) > MAX_CELLS:
raise ValueError(
f"the supercell common to every arm of {', '.join(r.label for r in representations)}"
f" is {sizes[0]}x{sizes[1]}x{sizes[2]} primitive cells ({int(np.prod(sizes))}); "
f"at most {MAX_CELLS} cells and {MAX_MULTIPLE} along one axis are supported.")
action = _SupercellAction(vibrations, site_indices, sizes, frame, axial=False)
if conventional:
centring, multiples, out_matrix, out_translations, internal_of = _display_cell(
vibrations, representations, frame, action)
from .spin_basis import conventional_cell_note
conventional_note = conventional_cell_note(
vibrations, centring, np.asarray(out_matrix) // multiples[:, None],
len(out_translations))
if conventional_note:
conventional_note = conventional_note.replace("The spin structures and their groups",
"The displacement patterns and their "
"groups")
else:
centring, multiples, conventional_note = None, None, None
out_matrix, out_translations = action.cell_matrix, action.cell_translations
internal_of = np.arange(len(action.cell_translations))
with contextlib.redirect_stdout(io.StringIO()):
try:
analyzer, table_parts, singles, records = _tables(parent, labels)
except SystemExit as exc:
raise ValueError(str(exc).removeprefix("ERROR: ")) from None
parts = [_IrrepPart(representation.label, representation, action)
for representation in table_parts]
orbits = _orbits(vibrations, site_indices, site_elements)
found_copies, multiplicities = {}, {}
worst = {"intertwining": 0.0, "orthonormality": 0.0}
for part, representation in zip(parts, representations):
at_gamma = not np.any(np.asarray(representation.k) % DEN)
found, counts, w_int, w_orth = _copies_of(part, action, vibrations, frame, orbits,
at_gamma, elements, multipoles=False)
found = [DisplacementCopy(
irrep=copy.irrep, number=copy.number, element=copy.element, orbit=copy.orbit,
kind={"FM": "net shift", "AFM": "no net shift"}.get(copy.kind, ""),
rank_name=None, intertwiner=copy.intertwiner) for copy in found]
kname = representation.irrep.kpname
expected = _expected_multiplicity(representation, survey_entries[kname])
if kname in unlabelled_k:
if not found:
raise ValueError(
f"{part.label} is not contained in the displacement representation of "
f"{', '.join(elements)} at {kname} (from the irrep matrices; the irreps of "
f"the decomposition could not be labelled at this tolerance, {symprec:g} A).")
expected = len(found)
if len(found) != expected:
raise ValueError(
f"{part.label}: {len(found)} copies on the atoms, the decomposition at {kname} "
f"gives {expected}: the irrep matrices and the labels of the decomposition do "
"not refer to the same setting (please report this case).")
if w_int > INTERTWINING_TOLERANCE:
raise ValueError(f"{part.label}: the displacement modes do not transform with the "
f"irrep matrices (residual {w_int:.2e}; please report this case).")
worst["intertwining"] = max(worst["intertwining"], w_int)
worst["orthonormality"] = max(worst["orthonormality"], w_orth)
found_copies[part.label] = found
multiplicities[part.label] = counts
# the written cell (atom-major, as phonopy's SPOSCAR)
lattice = np.asarray(primitive.cell, dtype=float)
positions = np.asarray(primitive.scaled_positions, dtype=float)
inverse_cell = np.linalg.inv(np.asarray(out_matrix, dtype=float))
supercell_symbols, supercell_positions = [], []
supercell_site_of_atom, supercell_cell_of_atom = [], []
for i, symbol in enumerate(symbols):
for c, translation in enumerate(out_translations):
supercell_symbols.append(symbol)
frac = (positions[i] + translation) @ inverse_cell
supercell_positions.append(frac - np.floor(frac))
supercell_site_of_atom.append(site_indices.index(i) if i in site_indices else None)
supercell_cell_of_atom.append(c)
supercell_positions = np.array(supercell_positions)
supercell_lattice = np.asarray(out_matrix, dtype=float) @ lattice
with contextlib.redirect_stdout(io.StringIO()):
symbol = str(algebra.sg_type.international_short)
analysis = DisplacementIrrepAnalysis(
formula=reduced_formula(symbols), elements=elements,
space_group=str(vibrations.spglib_dataset["international"]),
space_group_number=number, irreps=[p.label for p in parts],
dimensions=[p.dimension for p in parts], kpoints=kpoints,
decompositions=decompositions, multiplicities=multiplicities, copies=found_copies,
singles=singles, rows=[r[0] for r in records], arrangements=[],
coefficients=tuple(coefficients), amplitude=amplitude, check_symprec=float(symprec),
cell_matrix=np.asarray(out_matrix), supercell_sizes=sizes,
cell_translations=out_translations, supercell_lattice=supercell_lattice,
supercell_symbols=supercell_symbols, supercell_positions=supercell_positions,
supercell_site_of_atom=supercell_site_of_atom,
supercell_cell_of_atom=supercell_cell_of_atom, site_indices=site_indices,
site_elements=site_elements, residuals=worst, parts=parts,
unlabelled_kpoints=sorted(unlabelled_k), conventional_centring=centring,
conventional_multiples=multiples, internal_cell_translations=action.cell_translations,
conventional_note=conventional_note, symbol=symbol,
poscar_basename=os.path.basename(str(poscar_name)),
)
analysis._primitive_positions = positions
bounds = np.cumsum([0] + [p.dimension for p in parts])
combined = np.array([
_block_diagonal([part.matrices[g] for part in parts]) for g in range(action.order)
])
if order_parameter is not None:
row, eta, stratum = _order_parameter_target(analyzer, table_parts, records,
order_parameter)
analysis.order_parameter_input = list(order_parameter)
analysis.stratum = stratum
work = [(stratum if stratum is not None else 0, row, eta)]
else:
work = [(n + 1, row, eta) for n, (row, eta, _) in enumerate(records)]
copy_lists = [found_copies[p.label] for p in parts]
several = any(len(listed) > 1 for listed in copy_lists)
copy_choices = list(itertools.product(*copy_lists))
if copies is not None:
wrong = [f"{p.label} has {len(listed)} cop{'y' if len(listed) == 1 else 'ies'}"
for p, listed, n in zip(parts, copy_lists, copies)
if not 1 <= n <= len(listed)]
if wrong:
raise ValueError(f"--copies {' '.join(str(n) for n in copies)}: "
+ "; ".join(wrong) + ".")
copy_choices = [tuple(listed[n - 1] for listed, n in zip(copy_lists, copies))]
elif len(copy_choices) > MAX_COPY_CHOICES:
analysis.copy_note = (
f"NOTE: {len(copy_choices)} choices of copies per row; only the first (c"
+ "-".join("1" for _ in parts) + ") is exported. --copies "
+ " ".join("i" for _ in parts) + " (one copy number per irrep, as listed under "
"* Copies in the displacement representation *) exports another one.")
copy_choices = copy_choices[:1]
scales = {}
for listed, part in zip(copy_lists, parts):
for copy in listed:
X = copy.intertwiner
carrying = np.count_nonzero(np.linalg.norm(X, axis=(2, 3)) > 1e-10)
scales[id(copy)] = float(np.sqrt(carrying * part.dimension
/ max(np.sum(X * X), 1e-300)))
irrep_labels = [p.label for p in parts]
parent_atoms = len(symbols)
parent_point_order = len({tuple(np.asarray(R).ravel()) for R in vibrations.rotations})
for number_, row, eta in work:
eta = np.array(eta, dtype=float)
letters = {}
for j, component in enumerate(row.components):
own = _letter_values([component], eta[bounds[j]: bounds[j + 1]])
if own and order_parameter is None:
scale = max(abs(value) for value in own.values())
if scale > 1e-12:
eta[bounds[j]: bounds[j + 1]] /= scale
own = {name: value / scale for name, value in own.items()}
letters.update(own)
for choice in copy_choices:
tag = "c" + "-".join(str(copy.number) for copy in choice) if several else ""
pieces = [copy.intertwiner @ eta[bounds[j]: bounds[j + 1]]
for j, copy in enumerate(choice)]
if order_parameter is not None:
units = [coefficients[j] * scales[id(copy)] for j, copy in enumerate(choice)]
weights, reason = list(coefficients), None
else:
largest_parts = [float(np.max(np.linalg.norm(piece, axis=2)))
for piece in pieces]
normalized = [piece / largest if largest > 1e-12 else piece * 0.0
for piece, largest in zip(pieces, largest_parts)]
if user_weights:
weights, reason = list(coefficients), None
else:
weights, reason = _default_weights(normalized)
if reason:
reason = reason.replace("the moments", "the displacements")
if conventional:
written_weights, reason = _default_weights(
[piece[internal_of] for piece in normalized])
if reason:
reason = reason.replace("the moments", "the displacements")
if written_weights != weights:
raise ValueError(f"{row.label}: the default weights differ between "
"the supercell and the conventional cell "
"(please report this case).")
units = [w / largest if largest > 1e-12 else 0.0
for w, largest in zip(weights, largest_parts)]
contributions = [unit * piece for unit, piece in zip(units, pieces)]
raw = np.sum(contributions, axis=0)
largest = float(np.max(np.linalg.norm(raw, axis=2)))
if largest < 1e-12:
raise ValueError(f"the displacements of {row.label} vanish for these weights.")
for j, contribution in enumerate(contributions):
own_largest = float(np.max(np.linalg.norm(contribution, axis=2)))
if 0 < own_largest < MIN_RELATIVE_WEIGHT * largest:
raise ValueError(
f"{row.label}: the part of {parts[j].label} is {own_largest / largest:.1e}"
f" of the largest displacement, below {MIN_RELATIVE_WEIGHT:g}: it is not "
"resolved in the displaced structure.")
field = raw / largest
smallest = amplitude * _smallest_breaking(action, field.reshape(-1, 3))
if smallest < CHECK_FACTOR * float(symprec):
raise ValueError(_tolerance_text(
f"{row.label}: the smallest symmetry-breaking displacement of the pattern "
f"(the least an operation of the parent group that the pattern breaks "
f"moves an atom off its image), {smallest:.2g} A at --amplitude "
f"{amplitude:g} A,", amplitude, symprec))
reached = np.any([np.linalg.norm(c, axis=2) > 1e-6 * largest
for c in contributions], axis=0)
reproduce = np.concatenate([
unit * eta[bounds[j]: bounds[j + 1]] / (scales[id(copy)] * largest)
for j, (unit, copy) in enumerate(zip(units, choice))])
written = field[internal_of]
displacements = np.zeros((len(supercell_symbols), 3))
for atom, site in enumerate(supercell_site_of_atom):
if site is not None:
displacements[atom] = amplitude * written[supercell_cell_of_atom[atom], site]
displaced = supercell_positions + displacements @ np.linalg.inv(supercell_lattice)
arrangement = DisplacementArrangement(
number=number_, row=row, copies=tuple(choice), tag=tag,
order_parameter=eta, letters=letters, coefficients=tuple(weights),
field=field, displacements=displacements, displaced_positions=displaced,
displacement_text=_moment_text(amplitude * written, site_elements,
(~reached)[internal_of], irrep_labels,
quantity="|u|", noun="displacement")
.replace(" sites", " atoms"))
arrangement.weight_reason = reason
arrangement.reproduce = reproduce
n_field, n_eta, arrangement.fixing_translations = _fixing_counts(
action, combined, field.reshape(-1, 3), eta, time_reversal=False)
if conventional:
arrangement.fixing_translations = _written_translations(
out_matrix, out_translations, written)
arrangement.n_fixing_field, arrangement.n_fixing_order_parameter = n_field, n_eta
arrangement.polar_axes = _polar_axes(action, field.reshape(-1, 3))
if classify:
text = _poscar_text(analysis, displaced, "check")
found = _identify(text, symprec, parent_atoms, parent_point_order)
if found is not None:
(arrangement.group_number, arrangement.group_symbol, arrangement.point_group,
arrangement.found_size, arrangement.found_index) = found
arrangement.check, arrangement.note = _verdict(row, found)
if n_field != n_eta:
extra = (f"NOTE: {n_field} elements of G/T_S fix the displacements and "
f"{n_eta} fix the order parameter.")
arrangement.note = extra if arrangement.note is None else (
arrangement.note + " " + extra)
analysis.arrangements.append(arrangement)
_name_files(analysis)
return analysis
# ------------------------------------------------------------------ the names
def _conv_suffix(analysis) -> str:
return "_conv" if analysis.conventional_centring is not None else ""
def _name_files(analysis: DisplacementIrrepAnalysis) -> None:
"""``POSCAR_<formula>_disp_[<elements>_]<IR1>_<IR2>_<NN>_<number>_<symbol>[_<copies>][_conv].vesta``
and ``M<POSCAR name>_[<elements>_]<IR1>_<IR2>_<NN>_<number>_<symbol>[_<copies>][_conv]``."""
from .cli.common import file_name_tag
width = max(2, len(str(len(analysis.rows))))
elements = "" if len(analysis.elements) == 1 else "-".join(analysis.elements) + "_"
irreps = "_".join(file_name_tag(label) for label in analysis.irreps)
for arrangement in analysis.arrangements:
group = f"{arrangement.row.number}_{_file_symbol(arrangement.row.symbol)}"
middle = f"{elements}{irreps}_{arrangement.number:0{width}d}_{group}"
if analysis.order_parameter_input is not None:
middle = f"{elements}{irreps}_op_{group}"
if arrangement.tag:
middle += f"_{arrangement.tag}"
suffix = _conv_suffix(analysis)
arrangement.vesta_name = f"POSCAR_{analysis.formula}_disp_{middle}{suffix}.vesta"
arrangement.poscar_name = f"M{analysis.poscar_basename}_{middle}{suffix}"
def report_file_name(analysis: DisplacementIrrepAnalysis) -> str:
"""``saad_<formula>_<elements>_<IR1>[_<IR2>...][_conv]``."""
from .cli.common import file_name_tag
return (f"saad_{analysis.formula}_{'-'.join(analysis.elements)}_"
+ "_".join(file_name_tag(label) for label in analysis.irreps)
+ _conv_suffix(analysis))
def supercell_poscar_name(analysis: DisplacementIrrepAnalysis, tag: str | None = None) -> str:
"""``S<POSCAR name>_<IR1>[_<IR2>...][_conv]`` (``tag`` in place of the irreps)."""
from .cli.common import file_name_tag
if tag is None:
tag = "_".join(file_name_tag(label) for label in analysis.irreps)
return f"S{analysis.poscar_basename}_{tag}{_conv_suffix(analysis)}"
# ------------------------------------------------------------------ the files
def _cells_text(analysis) -> str:
sizes = analysis.supercell_sizes
if analysis.conventional_centring is not None:
m = analysis.conventional_multiples
return (f"conventional ({analysis.conventional_centring} centring), "
f"{m[0]}x{m[1]}x{m[2]} cells ({analysis.n_cells} primitive cells)")
return f"{sizes[0]}x{sizes[1]}x{sizes[2]} primitive cells"
def write_supercell(analysis: DisplacementIrrepAnalysis, path: str, irreps_text=None) -> None:
"""The undistorted supercell as a VASP 5 POSCAR (atom order of the
displacement listings and of the displaced structures)."""
comment = (f"{analysis.formula} supercell of {analysis.poscar_basename} for "
f"{irreps_text or ' '.join(analysis.irreps)}, {_cells_text(analysis)} "
"(crystod-phonon; atom order of the displacement listings)")
with open(path, "w") as handle:
handle.write(_poscar_text(analysis, analysis.supercell_positions, comment))
def write_displaced_poscar(analysis: DisplacementIrrepAnalysis,
arrangement: DisplacementArrangement) -> str:
"""The displaced structure of one pattern (``M<POSCAR name>_...``)."""
comment = (f"{analysis.formula} {arrangement.row.label} -> {arrangement.row.subgroup}, "
f"largest displacement {analysis.amplitude:g} A, {_cells_text(analysis)} "
"(crystod-phonon)")
with open(arrangement.poscar_name, "w") as handle:
handle.write(_poscar_text(analysis, arrangement.displaced_positions, comment))
return arrangement.poscar_name
def write_arrangement_vesta(analysis: DisplacementIrrepAnalysis,
arrangement: DisplacementArrangement) -> str:
"""The VESTA file of one pattern: the undistorted cell with one arrow per
moving atom, the largest ``ARROW_LENGTH`` Angstrom."""
from .phonon_vector import write_vesta_with_arrows
write_vesta_with_arrows(
filepath=arrangement.vesta_name,
lattice=analysis.supercell_lattice,
scaled_positions=analysis.supercell_positions,
symbols=analysis.supercell_symbols,
arrows_cartesian=arrangement.displacements * (ARROW_LENGTH / analysis.amplitude),
title=f"{analysis.formula} {arrangement.row.label} {arrangement.row.subgroup}",
)
return arrangement.vesta_name
# --------------------------------------------------------------------- report
def _part_line(part) -> str:
"""The line of ``crystod-group --parent`` under ``* Irrep *``."""
if part.doubled:
note = (f" (star of {part.n_arms} arm(s) x small dim {part.dim_small} x 2;"
f" {part.fs_type}-type irrep -> physically irreducible real form)")
elif part.n_arms > 1:
note = f" (star of {part.n_arms} arm(s) x small dim {part.dim_small})"
else:
note = ""
return f"{part.label}: order parameter dimension {part.dimension}{note}"
def _row_check_text(analysis, number: int) -> str:
own = [a for a in analysis.arrangements if a.number == number]
if not own:
return "-"
texts = {a.check_text for a in own}
if len(texts) == 1:
text = texts.pop()
return text if len(own) == 1 else f"{text} (x{len(own)})"
return "; ".join(f"{a.tag}: {a.check_text}" for a in own)
def format_table(analysis: DisplacementIrrepAnalysis) -> list[str]:
"""The table: a row number, the columns of ``crystod-group --parent``,
and the space group spglib finds on every displaced structure."""
rows = analysis.rows
width = max([20] + [len(row.label) + 1 for row in rows])
lines = [f"{'No.':<4} {'irrep':<{width}} {'subgroup':<18} {'size':<5} {'index':<5} "
"structure"]
for number, row in enumerate(rows, start=1):
lines.append(f"{number:<4} {row.label:<{width}} {row.subgroup:<18} {row.size:<5} "
f"{row.index:<5} {_row_check_text(analysis, number)}")
return lines
def _print_tables(analysis, classify_only: bool) -> None:
from .isotropy_subgroup import _PARAMETER_NAMES, _enantiomorph_note, _print_direction_table
print()
numbers = []
if len(analysis.irreps) > 1:
for label, results in analysis.singles.items():
print(f"* Order parameter directions and isotropy subgroups ({label} alone) *")
_print_direction_table(results)
print()
numbers += [info.number for _, _, _, info, _ in results]
print("* Order parameter directions and isotropy subgroups (coupled) *")
else:
print("* Order parameter directions and isotropy subgroups *")
print("\n".join(format_table(analysis)))
numbers += [row.number for row in analysis.rows]
_enantiomorph_note(numbers)
if len(analysis.irreps) > 1:
print()
ranges, offset = [], 0
for part in analysis.parts:
letters = _PARAMETER_NAMES[offset: offset + part.dimension]
ranges.append(f"{part.label}: {', '.join(letters)}")
offset += part.dimension
print("Every irrep of the coupled table condenses with a nonzero")
print("amplitude; every irrep keeps its own independent free")
print(f"parameters ({'; '.join(ranges)}).")
print()
print("The components of a direction refer to the irrep basis of the table (as with")
print("crystod-group --parent), not to the axes of the POSCAR; the displacement")
print("listings give the Cartesian displacements.")
print()
print("structure = the space group spglib finds on the displaced structure exported for")
where = "conventional cell" if analysis.conventional_centring is not None else "supercell"
print(f"the row ({where} as written, all atoms, tolerance {analysis.check_symprec:g} A),")
print("compared with the table (number, size, index): same, enantiomorph (the partner")
print("type), different; (xN) for N choices of copies.")
if len(analysis.irreps) > 1 and not classify_only:
print()
print("Displacement patterns are exported for the coupled rows; crystod-phonon --irrep "
f"{analysis.irreps[0]} alone exports those of one irrep.")
def _reproduce_text(analysis, arrangement) -> str:
vector = " ".join(_number_text(v) for v in arrangement.reproduce)
text = f'--order-parameter "{vector}"'
if any(len(analysis.copies[label]) > 1 for label in analysis.irreps):
text += " --copies " + " ".join(str(copy.number) for copy in arrangement.copies)
if analysis.conventional_centring is not None:
text += " --conventional"
return text
def print_arrangement(analysis: DisplacementIrrepAnalysis,
arrangement: DisplacementArrangement) -> None:
"""The block of one exported pattern."""
row = arrangement.row
tag = f" {arrangement.tag}" if arrangement.tag else ""
title = f"{arrangement.number}{tag}"
if analysis.order_parameter_input is not None:
title = f"order parameter{tag}"
print(f"\n* {title}: {row.label} -> {row.subgroup} *")
if analysis.order_parameter_input is not None:
vector = ", ".join(_format_value(v) for v in arrangement.order_parameter)
given = " ".join(analysis.order_parameter_input)
letters_note = (" (letters: generic distinct values)"
if re.search(r"[a-z]", given) else "")
print(f" order parameter vector: ({vector}){letters_note}")
if analysis.stratum is not None:
print(f" stratum: row {analysis.stratum} of the table "
f"({analysis.rows[analysis.stratum - 1].label})")
else:
print(" stratum: not a row of the "
+ ("coupled table (an irrep has a zero part)" if len(analysis.irreps) > 1
else "table"))
if len(analysis.irreps) > 1 or any(len(analysis.copies[label]) > 1
for label in analysis.irreps):
print(" copies: " + "; ".join(
f"{copy.irrep} " + (f"c{copy.number} = " if len(analysis.copies[copy.irrep]) > 1
else "") + copy.text
for copy in arrangement.copies))
if arrangement.letters:
pieces = []
for label, component in zip(analysis.irreps, row.components):
names = sorted(set(re.findall(r"[a-z]", component)))
values = ", ".join(f"{name} = {_format_value(arrangement.letters[name])}"
for name in names if name in arrangement.letters)
values = values or "0"
pieces.append(f"{label}: {values}" if len(analysis.irreps) > 1 else values)
print(f" order parameter: {'; '.join(pieces)}")
n_free = len(arrangement.letters)
if len(analysis.irreps) > 1 and analysis.order_parameter_input is None:
weights = " : ".join(_format_value(c) for c in arrangement.coefficients)
print(f" parts: {' : '.join(analysis.irreps)} = {weights} (each part scaled to "
"largest displacement 1, then weighted)")
if arrangement.weight_reason:
print(f" weights: {arrangement.weight_reason}")
elif analysis.order_parameter_input is not None:
weights = "" if all(c == 1.0 for c in arrangement.coefficients) else (
"; weights " + ", ".join(f"{label} x {_format_value(c)}" for label, c in
zip(analysis.irreps, arrangement.coefficients)))
print(" amplitudes: the components of the vector (unit: the rms displacement of one")
print(f" unit component over the atoms of its copy){weights}; then scaled to the "
"amplitude")
if n_free > 1 or len(analysis.irreps) > 1:
print(" the relative amplitudes are not fixed by symmetry: other nonzero values that")
print(" keep the pattern of the label (no new zero or equal components) give the")
print(" same group")
print(f" reproduce: {_reproduce_text(analysis, arrangement)}")
print(f" displacements: {arrangement.displacement_text}")
if arrangement.group_number is None:
print(" space group (displaced structure): not identified by spglib")
else:
print(f" space group (displaced structure): {arrangement.group_number} "
f"{arrangement.group_symbol}, point group {arrangement.point_group}, size "
f"{arrangement.found_size}, index {arrangement.found_index}")
print(f" check (on the displaced structure as written): table {row.subgroup} (size "
f"{row.size}, index {row.index}), structure {arrangement.check_text}; "
f"{arrangement.n_fixing_field} elements of G/T_S fix the displacements, "
f"{arrangement.n_fixing_order_parameter} the order parameter")
if arrangement.note:
print(f" {arrangement.note}")
allowed = allowed_text(arrangement)
if allowed:
print(f" allowed by symmetry: {allowed}")
_displacement_lines(analysis, arrangement)
def _displacement_lines(analysis, arrangement) -> None:
symbols = analysis.supercell_symbols
note = "" if analysis.n_cells == 1 else (
f" ({analysis.supercell_sizes.tolist()} supercell)")
if analysis.conventional_centring is not None:
m = analysis.conventional_multiples
note = f" (conventional cell, {m[0]}x{m[1]}x{m[2]} cells)"
moving, resting = [], 0
for atom, site in enumerate(analysis.supercell_site_of_atom):
if site is None:
continue
u = np.round(arrangement.displacements[atom], DISPLACEMENT_DECIMALS) + 0.0
if np.linalg.norm(arrangement.displacements[atom]) < 1e-9:
resting += 1
continue
moving.append((atom, u))
selected = ", ".join(analysis.elements)
print(f" displacements in Angstrom (Cartesian, POSCAR axes; atoms numbered as in the "
f"supercell POSCAR){note}: {len(moving)} {selected} atoms move, {resting} stay")
for atom, u in moving:
print(f" {symbols[atom]}{atom + 1}: [{u[0]:.4f}, {u[1]:.4f}, {u[2]:.4f}]")
def _print_structure(analysis, positions) -> None:
"""The ``* Structure *`` block of every form (``analysis``: a
:class:`DisplacementIrrepAnalysis` or a :class:`DisplacementSurvey`;
``positions``: the fractional positions of the primitive cell)."""
print("\n* Structure *")
print(f" Space group: {analysis.space_group} (#{analysis.space_group_number})")
counts = {e: analysis.site_elements.count(e) for e in analysis.elements}
print(" Displaced atoms: " + ", ".join(f"{e} x {n}" for e, n in counts.items()))
for element in analysis.elements:
k = 0
for site, e in zip(analysis.site_indices, analysis.site_elements):
if e == element:
k += 1
print(f" {element}{k}: {np.round(positions[site], 6).tolist()}")
def print_report(analysis: DisplacementIrrepAnalysis, *, part_lines=None,
classify_only: bool = False, structure: bool = True,
decomposition: bool = True) -> None:
"""Everything up to the blocks of the patterns."""
if structure:
_print_structure(analysis, analysis._primitive_positions)
if decomposition:
print(f"\n* Displacement (polar-vector) representation of "
f"{', '.join(analysis.elements)} atoms at the k points of the irreps *")
shown = set()
for label in analysis.irreps:
kname, q = analysis.kpoints[label]
if kname in shown:
continue
shown.add(kname)
print(f" k point (primitive): {kname} {np.round(q, 6).tolist()}")
for name, text in analysis.decompositions[kname]:
print(f" {name}: {text}" if len(analysis.elements) > 1 else f" {text}")
if kname in analysis.unlabelled_kpoints:
print(f" NOTE: the irreps at {kname} could not be labelled at this tolerance "
"(irrep_N above; the structure is off its ideal positions): the copies "
"come from the irrep matrices alone, and every pattern is checked on "
"the displaced structure below. Symmetrize the structure for the "
"labelled decomposition.")
print()
print("* Coupled irreps *" if len(analysis.irreps) > 1 else "* Irrep *")
for line in part_lines or [_part_line(part.representation) for part in analysis.parts]:
print(line)
if len(analysis.irreps) > 1:
print(f"coupled order parameter dimension {sum(analysis.dimensions)} "
f"({' + '.join(str(d) for d in analysis.dimensions)})")
print("\n* Copies in the displacement representation *")
for label in analysis.irreps:
copies = analysis.copies[label]
listed = ", ".join((f"c{copy.number} = " if len(copies) > 1 else "") + copy.text
for copy in copies)
print(f" {label}: {len(copies)} cop{'y' if len(copies) == 1 else 'ies'}: {listed}")
for label in analysis.irreps:
for copy in analysis.copies[label]:
axes = _component_axes(copy)
if axes is not None:
name = f"{label} c{copy.number}" if len(analysis.copies[label]) > 1 else label
numbers = ", ".join(str(j + 1) for j in range(len(axes)))
word = "component" if len(axes) == 1 else "components"
print(f" {name}: {word} {numbers} = displacements along {', '.join(axes)}")
if any(len(analysis.copies[label]) > 1 for label in analysis.irreps):
print(" one pattern per choice of copies; any mixture of the copies of an irrep with")
print(" the same order parameter has the same space group")
if analysis.copy_note:
print(f" {analysis.copy_note}")
print(" These are symmetry-adapted displacement patterns, not eigenvectors of a")
print(" dynamical matrix: a real distortion of a row's symmetry combines the copies of")
print(" its irreps with amplitudes that only a force calculation fixes.")
sizes = analysis.supercell_sizes
n_atoms = len(analysis.supercell_symbols)
print("\n* Supercell *")
if analysis.conventional_centring is None:
print(f" Commensurate supercell: {sizes[0]}x{sizes[1]}x{sizes[2]} "
f"({analysis.n_cells} primitive cell{'s' if analysis.n_cells > 1 else ''}, "
f"{n_atoms} atoms), common to every arm of {', '.join(analysis.irreps)}")
else:
n_internal = len(analysis.internal_cell_translations)
m = analysis.conventional_multiples
print(f" Commensurate supercell: {sizes[0]}x{sizes[1]}x{sizes[2]} "
f"({n_internal} primitive cell{'s' if n_internal > 1 else ''}), common to every "
f"arm of {', '.join(analysis.irreps)}: the cell of the displacement modes and of "
"the counts over G/T_S")
print(f" Display cell: conventional ({analysis.conventional_centring} centring), "
f"{m[0]}x{m[1]}x{m[2]} cells ({analysis.n_cells} primitive "
f"cell{'s' if analysis.n_cells > 1 else ''}, {n_atoms} atoms): the cell of the "
"displacement listings, files and the structure check")
if analysis.conventional_note:
print(f" {analysis.conventional_note}")
print(f" displacement modes: |O(g) Psi - Psi D(g)| <= "
f"{analysis.residuals['intertwining']:.1e} over the elements of G/T_S, "
f"Psi^T Psi = c 1 within {analysis.residuals['orthonormality']:.1e}")
print(f" amplitude: largest displacement {analysis.amplitude:g} A in every displaced "
"structure (--amplitude); VESTA arrows scaled to a largest length of "
f"{ARROW_LENGTH:g} A")
if analysis.order_parameter_input is None:
_print_tables(analysis, classify_only)
def _print_references() -> None:
print()
print("Reference: H. T. Stokes, S. van Orden and B. J. Campbell, J. Appl. Cryst. 49,")
print("1849-1853 (2016) (ISOSUBGROUP, isotropy subgroups); H. T. Stokes, D. M. Hatch and")
print("B. J. Campbell, ISOTROPY Software Suite, https://iso.byu.edu.")
def _read_structure(args):
from .star_of_k import read_poscar_or_exit
from .vibration_modes import SymmetryOnlyVibrations
try:
cell = read_poscar_or_exit(args.cell)
except SystemExit:
raise
except Exception as exc: # noqa: BLE001 - any reader failure is the file's
raise SystemExit(f"ERROR: could not read {args.cell} as a VASP POSCAR "
f"({type(exc).__name__}: {' '.join(str(exc).split())[:200]}); "
"-c takes a POSCAR (primitive cell) in this mode.") from None
tolerance = 1e-5 if args.tolerance is None else float(args.tolerance)
try:
with contextlib.redirect_stdout(io.StringIO()):
vibrations = SymmetryOnlyVibrations(cell=cell, symprec=tolerance, standardize=False)
except SystemExit:
raise
except Exception as exc: # noqa: BLE001
raise SystemExit(f"ERROR: could not analyse the symmetry of {args.cell} "
f"({type(exc).__name__}: {' '.join(str(exc).split())[:200]}).") from None
return vibrations, tolerance
def _amplitude(args) -> float:
if args.amplitude is None:
return DEFAULT_AMPLITUDE
if len(args.amplitude) != 1:
raise SystemExit("ERROR: --amplitude takes one value with --irrep/--qpoint (the largest "
"displacement, Angstrom).")
return float(args.amplitude[0])
def _export(analysis, enabled, classify_only, written):
if classify_only:
return
for arrangement in analysis.arrangements:
print_arrangement(analysis, arrangement)
if enabled:
written.append((write_arrangement_vesta(analysis, arrangement),
write_displaced_poscar(analysis, arrangement)))
def _print_output_files(written, supercell, saved) -> None:
if written or supercell or saved.active:
print("\n* Output files *")
for vesta, poscar in written:
print(f" Displacement pattern written to: {vesta}; displaced structure: {poscar}")
if supercell:
print(f" Supercell POSCAR written to: {supercell} (atom order of the displacement "
"listings)")
if saved.active:
print(saved.line())
def run(args) -> DisplacementIrrepAnalysis:
"""``crystod-phonon -c POSCAR --element EL [...] --irrep IR [...]``
(dispatched by :mod:`crystod.cli.phonon`): prints the report, writes
the files."""
from .cli.common import SavedReport
from .isotropy_subgroup import _order_parameter_tokens
vibrations, tolerance = _read_structure(args)
try:
analysis = displacement_irrep_arrangements(
elements=list(args.element), irreps=list(args.irrep), symprec=tolerance,
coefficients=args.coefficients, classify=True, vibrations=vibrations,
order_parameter=(None if args.order_parameter is None
else _order_parameter_tokens(args.order_parameter)),
copies=args.copies, conventional=bool(args.conventional),
amplitude=_amplitude(args), poscar_name=args.cell)
except ValueError as exc:
raise SystemExit("ERROR: " + str(exc)) from None
enabled = not args.no_files
with SavedReport(enabled=enabled, announce=False) as saved:
print_report(analysis, classify_only=args.classify_only)
written = []
_export(analysis, enabled, args.classify_only, written)
supercell = None
if enabled and not args.classify_only:
supercell = supercell_poscar_name(analysis)
write_supercell(analysis, supercell)
saved.name = (report_file_name(analysis) + ("_classify" if args.classify_only else "")
+ ("_op" if analysis.order_parameter_input is not None else ""))
_print_output_files(written, supercell, saved)
_print_references()
return analysis
# ------------------------------------------------------------- --qpoint form
def kpoint_irreps(vibrations, elements, q, algebra=None):
"""The irreps (labels, in table order; a complex pair once, by its pair
label) that the displacement representation of the elements contains at
the special point q (POSCAR primitive basis), with the ISO-IR name of q
and the decomposition lines.
Raises:
ValueError: q is not a tabulated special point of the space group.
"""
from .isotropy_subgroup import InducedRepresentation
from .spacegroup_product import SpaceGroupIrrepAlgebra
if algebra is None:
with contextlib.redirect_stdout(io.StringIO()):
algebra = SpaceGroupIrrepAlgebra(str(int(vibrations.spglib_dataset["number"])))
frame = _Frame(vibrations, algebra)
q = np.mod(np.asarray(q, dtype=float), 1.0)
kname = None
for name in algebra.k_by_kname:
arms, _ = algebra.star(name)
for arm in arms:
k = frame.kpoint(arm)
difference = k - q
if np.allclose(difference, np.rint(difference), atol=1e-6):
kname = name
break
if kname is not None:
break
if kname is None:
raise ValueError(_not_special_text(algebra, frame, q))
symbols = list(vibrations.primitive_cell.symbols)
site_indices = [i for e in elements for i, s in enumerate(symbols) if s == e]
arm_q = None
labels, listed = [], []
entries = None
for irrep in algebra.irreps_by_kname[kname]:
try:
with contextlib.redirect_stdout(io.StringIO()):
representation = InducedRepresentation(algebra, irrep.name)
except SystemExit:
continue
character = np.array([np.trace(matrix) for _, _, matrix in representation.elements])
if representation.doubled and any(np.allclose(character, other, atol=1e-6)
for other in listed):
continue
listed.append(character)
if entries is None:
arm_q = frame.kpoint(representation.k)
arm_q = [float(x) + 0.0 for x in np.round(arm_q, 10)]
entries = _decomposition(vibrations, site_indices, arm_q, polar=True)[1]
if _expected_multiplicity(representation, entries) > 0:
labels.append(representation.label)
return kname, arm_q, labels
def _not_special_text(algebra, frame, q) -> str:
"""The message of ``crystod-group --parent SG --kpoint K`` for a k point
that is not tabulated (:func:`crystod.isotropy_subgroup.resolve_special_kpoint`,
q handed over in the primitive basis of the tables), with the special
points in the primitive basis of the POSCAR when that basis differs."""
from fractions import Fraction
from .isotropy_subgroup import _format_k, resolve_special_kpoint
from .spacegroup_product import DEN
k_tables = np.linalg.inv(np.asarray(frame.F, dtype=float).T) @ np.asarray(q, dtype=float)
tokens = [str(Fraction(float(x)).limit_denominator(48)) for x in k_tables]
try:
with contextlib.redirect_stdout(io.StringIO()):
resolve_special_kpoint(algebra, tokens)
except SystemExit as exc:
text = str(exc).removeprefix("ERROR: ")
else: # pragma: no cover - the caller found no arm
text = f"k = ({', '.join(tokens)}) is not a special k point of the space group."
if not np.array_equal(np.asarray(frame.F), np.eye(3, dtype=np.int64)):
listed = ", ".join(
f"{name} {_format_k(np.rint(frame.kpoint(k) * DEN).astype(np.int64))}"
for name, k in algebra.k_by_kname.items())
text += ("\nNOTE: the coordinates above refer to the primitive basis of the ISO-IR "
"tables; in the primitive reciprocal basis of the POSCAR the special points are: "
+ listed)
return text
def run_qpoint(args) -> list:
"""``crystod-phonon -c POSCAR --element EL [...] --qpoint K``: every irrep
of the displacement representation of the elements at K, each with its
whole table, as ``--irrep`` treats it."""
from .cli.common import SavedReport, file_name_tag
vibrations, tolerance = _read_structure(args)
try:
_require_primitive(vibrations)
except ValueError as exc:
raise SystemExit(f"ERROR: {exc}") from None
tokens = [str(token).strip() for token in args.qpoint]
try:
name, q = vibrations.resolve_special_qpoint(tokens)
except ValueError as exc:
raise SystemExit(f"ERROR: {exc}") from None
elements = list(args.element)
symbols = list(vibrations.primitive_cell.symbols)
missing = [e for e in elements if e not in symbols]
if missing:
raise SystemExit(f"ERROR: element '{missing[0]}' is not in this POSCAR "
f"({', '.join(sorted(set(symbols)))}).")
try:
kname, _, labels = kpoint_irreps(vibrations, elements, q)
except ValueError as exc:
raise SystemExit(f"ERROR: {exc}") from None
if not labels:
raise SystemExit(f"ERROR: the displacement representation of {', '.join(elements)} has "
f"no tabulated irrep at {kname}.")
amplitude = _amplitude(args)
analyses = []
for label in labels:
try:
analysis = displacement_irrep_arrangements(
elements=elements, irreps=[label], symprec=tolerance, classify=True,
vibrations=vibrations, conventional=bool(args.conventional),
amplitude=amplitude, poscar_name=args.cell)
except ValueError as exc:
raise SystemExit(f"ERROR: {label}: {exc}") from None
analyses.append(analysis)
enabled = not args.no_files
first = analyses[0]
with SavedReport(enabled=enabled, announce=False) as saved:
print_report_header(first, kname, q, tokens, labels)
written = []
for analysis in analyses:
print(f"\n* Irrep {analysis.irreps[0]} ({labels.index(analysis.irreps[0]) + 1} of "
f"{len(labels)}) *")
print_report(analysis, classify_only=args.classify_only, structure=False,
decomposition=False)
_export(analysis, enabled, args.classify_only, written)
print("\n* Summary *")
total = sum(len(a.arrangements) for a in analyses)
verdicts = {}
for analysis in analyses:
for arrangement in analysis.arrangements:
verdicts[arrangement.check] = verdicts.get(arrangement.check, 0) + 1
print(f" {len(labels)} irreps at {kname}, {total} displacement patterns; structure: "
+ ", ".join(f"{count} {verdict}" for verdict, count in verdicts.items()))
supercell = None
if enabled and not args.classify_only:
supercell = supercell_poscar_name(first, file_name_tag(kname))
write_supercell(first, supercell, irreps_text=f"the irreps at {kname}")
saved.name = (f"saad_{first.formula}_{'-'.join(elements)}_{file_name_tag(kname)}"
+ _conv_suffix(first) + ("_classify" if args.classify_only else ""))
_print_output_files(written, supercell, saved)
_print_references()
return analyses
def print_report_header(analysis, kname, q, tokens, labels) -> None:
"""Structure and decomposition of the ``--qpoint`` form."""
from .vibration_modes import format_fraction_vector
_print_structure(analysis, analysis._primitive_positions)
print("\n* Selected Q point *")
print(f" --qpoint {' '.join(tokens)}: {kname} {format_fraction_vector(q)} (primitive "
"reciprocal basis of the POSCAR)")
print(f"\n* Displacement (polar-vector) representation of {', '.join(analysis.elements)} "
f"atoms at {kname} *")
for name, text in analysis.decompositions[analysis.kpoints[analysis.irreps[0]][0]]:
print(f" {name}: {text}" if len(analysis.elements) > 1 else f" {text}")
print(f" irreps treated (each with its whole table): {', '.join(labels)}")
# ------------------------------------------------------------- the survey
[docs]
@dataclass(eq=False)
class DisplacementSurvey:
"""The irreps of the displacement (polar-vector) representation of the
atoms of given elements at every special k point
(``crystod-phonon -c POSCAR --element EL [EL2 ...]``, no ``--irrep`` or
``--qpoint``).
``kpoints`` lists ``(name, q, lines)`` per special point, in the order
of the tables: q in the primitive reciprocal basis of the POSCAR,
``lines`` the ``(element, text)`` decompositions, one per element and,
for several elements, ``("total", text)`` (the text of the header of
the ``--irrep``/``--qpoint`` forms, complex pairs under their pair
label). ``unlabelled_kpoints`` names the points whose irreps could not
be labelled at the tolerance (``irrep_N`` in the text).
"""
formula: str
elements: list
space_group: str
space_group_number: int
site_indices: list
site_elements: list
positions: np.ndarray
kpoints: list
unlabelled_kpoints: list = dataclass_field(default_factory=list)
@property
def report_name(self) -> str:
"""``saad_<formula>_<El>[-<El2>...]_survey``."""
return f"saad_{self.formula}_{'-'.join(self.elements)}_survey"
[docs]
def displacement_irrep_survey(cell=None, elements=(), *, symprec: float = 1e-5,
vibrations=None) -> DisplacementSurvey:
"""The irreps of the atomic displacements at every special k point.
The computation behind ``crystod-phonon -c POSCAR --element EL [EL2 ...]``
(no ``--irrep``, no ``--qpoint``): the decomposition of the displacement
(polar-vector) representation of the atoms of the elements at every
special k point of the irrep tables (the points the ``crystod-mag``
survey and ``crystod --orbital p`` list), by the function the headers of
the ``--irrep`` and ``--qpoint`` forms use. p orbitals transform as
polar vectors, so every line equals ``crystod -c POSCAR --element EL
--orbital p`` up to the order of the terms, except that a complex irrep
and its conjugate at a time-reversal-invariant point are one term under
their pair label (``A1A3(2)`` for ``A1(1)`` + ``A3(1)``, as in the
headers and the ``crystod-mag`` survey), where ``crystod`` lists both.
Args:
cell: The crystal (phonopy ``PhonopyAtoms``, a primitive cell); not
needed when ``vibrations`` is given.
elements: The elements whose atoms move.
symprec: Symmetry tolerance (spglib, Angstrom).
vibrations: A prebuilt ``SymmetryOnlyVibrations(cell,
standardize=False)``.
Returns:
A :class:`DisplacementSurvey`.
Raises:
ValueError: No element, an element given twice or not in the cell, a
cell that is not primitive.
Example:
>>> from phonopy.interface.vasp import read_vasp
>>> from crystod import phonon
>>> cell = read_vasp("example/04-01_phonon_irrep/La3Ni2O7/PPOSCAR_La3Ni2O7_I4mmm")
>>> survey = phonon.displacement_irrep_survey(cell, ["O"])
>>> [name for name, _, _ in survey.kpoints]
['GM', 'X', 'M', 'N', 'P']
"""
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 .phonon_vector import reduced_formula
from .vibration_modes import SymmetryOnlyVibrations
elements = list(elements)
if not elements:
raise ValueError("at least one element is needed.")
if len(set(elements)) != len(elements):
raise ValueError(f"an element is given twice: {' '.join(elements)}")
if vibrations is None:
vibrations = SymmetryOnlyVibrations(cell=cell, symprec=symprec, standardize=False,
quiet=True)
_require_primitive(vibrations)
primitive = vibrations.primitive_cell
symbols = list(primitive.symbols)
missing = [e for e in elements if e not in symbols]
if missing:
available = ", ".join(sorted(set(symbols)))
raise ValueError(f"element '{missing[0]}' is not in this POSCAR ({available}).")
site_lists = [[i for i, s in enumerate(symbols) if s == e] for e in elements]
site_indices = [i for sites in site_lists for i in sites]
site_elements = [e for e, sites in zip(elements, site_lists) for _ in sites]
dataset = vibrations.spglib_dataset
# the special points of the crystod-mag survey (and of crystod --orbital p),
# named in the frame of the labels
IrrepTable, _ = load_irreptables()
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))
kpoints, unlabelled = [], []
for name, q in zip(q_names, q_list):
q = [float(x) + 0.0 for x in np.asarray(q, dtype=float)]
lines, entries = [], []
for element, sites in zip(elements, site_lists):
text, found = _decomposition(vibrations, sites, q, polar=True)
lines.append((element, text))
entries.extend(found)
if len(elements) > 1:
text, found = _decomposition(vibrations, site_indices, q, polar=True)
lines.append(("total", text))
entries.extend(found)
if any(n.startswith("irrep_") for names, _, _ in entries for n in names):
unlabelled.append(name)
kpoints.append((name, q, lines))
return DisplacementSurvey(
formula=reduced_formula(symbols), elements=elements,
space_group=str(dataset["international"]), space_group_number=int(dataset["number"]),
site_indices=site_indices, site_elements=site_elements,
positions=np.asarray(primitive.scaled_positions, dtype=float), kpoints=kpoints,
unlabelled_kpoints=unlabelled)
def print_survey(survey: DisplacementSurvey) -> None:
"""The report of the survey (without the ``* Output files *`` block)."""
_print_structure(survey, survey.positions)
print(f"\n* Displacement (polar-vector) Irreducible Representations of "
f"{', '.join(survey.elements)} sites *")
for name, q, lines in survey.kpoints:
print(f" k point (primitive): {name} {np.round(q, 6).tolist()}")
for element, text in lines:
print(f" {element}: {text}" if len(survey.elements) > 1 else f" {text}")
if survey.unlabelled_kpoints:
print(f" NOTE: the irreps at {', '.join(survey.unlabelled_kpoints)} could not be "
"labelled at this tolerance (irrep_N above; the structure is off its ideal "
"positions). Symmetrize the structure for the labelled decomposition.")
print("\nUse --qpoint K for the displacement patterns of every irrep at one k point, "
"--irrep IR [IR2 ...] for those of given irreps (VESTA files with arrows and "
"displaced POSCARs).")
def run_survey(args) -> DisplacementSurvey:
"""``crystod-phonon -c POSCAR --element EL [...]`` (no ``--irrep``, no
``--qpoint``; dispatched by :mod:`crystod.cli.phonon`): prints the
survey and saves it as ``saad_<formula>_<El>[-<El2>...]_survey``."""
from .cli.common import SavedReport
vibrations, tolerance = _read_structure(args)
try:
survey = displacement_irrep_survey(elements=list(args.element), symprec=tolerance,
vibrations=vibrations)
except ValueError as exc:
raise SystemExit("ERROR: " + str(exc)) from None
with SavedReport(enabled=not args.no_files) as saved:
print_survey(survey)
saved.name = survey.report_name
return survey