Source code for crystod.vasp_symmetry

"""Symmetry check of the response tensors of a VASP run (``crystod --check-symmetry``).

``crystod-group --tensor`` gives the form a property tensor must take in a
point group (Neumann's principle).  This module goes the other way: it reads
the tensors a VASP run computed -- Born effective charges Z*, the electronic
and ionic dielectric tensors, the piezoelectric tensor e, the elastic moduli
and the internal-strain tensors -- and compares each with its projection
onto the symmetry-allowed form:

- the projection is the group average ``T_sym = (1/|G|) sum_g g.T`` over the
  point group of the structure (site tensors: over the site-symmetry group,
  made consistent over each orbit by the space group), done in the Cartesian
  frame of the input file and combined with the intrinsic index symmetry of
  the tensor kind; it is the orthogonal projection in the Frobenius metric;
- the values of the independent components (the names of
  ``crystod-group --tensor``: ``eps11``, ``c44``, ``e15``, ...) are read off
  in the tensor axes of that command (``tensor_form.PointGroupSetting``:
  x || a, z || c of the standard conventional cell; the rotation from the
  input frame is ``PointGroupSetting.input_axes``);
- the residual ``||T - T_sym|| / ||T||`` (Frobenius norm of the full
  Cartesian tensor, so that every shear component carries its true weight)
  measures how far the numbers break the symmetry of the structure.

A small residual does not prove a tensor right: with ``ISYM > 0`` VASP
symmetrizes Z*, the dielectric tensors and the forces itself, so their
residuals sit at the printed digits whatever their accuracy, while quantities
VASP does not symmetrize (the ionic-relaxation elastic moduli and the shear
part of the internal-strain tensors of a linear-response run) can break the
symmetry at the 1e-4 to 1e-2 level.

The files are read by :func:`crystod.vasp_io.read_vasprun_response` and
:func:`crystod.vasp_io.read_outcar_response` (no pymatgen or phonopy reader).
VASP writes six-component tables in the column order ``XX YY ZZ XY YZ ZX``;
here they are converted to full tensors, and every printed independent
component uses Nye's matrix notation (L = 1..6 for 11, 22, 33, 23, 13, 12).
The piezoelectric tensor is VASP's e (stress type, ``e_iL = e_ijk``), i.e. the
kind ``piezoelectric-e`` of ``crystod-group --tensor``, not Nye's d.

Example:
    >>> from crystod import group
    >>> report = group.vasp_symmetry_report("DFPT/vasprun.xml", outcar="DFPT/OUTCAR")
    >>> print(group.format_vasp_symmetry(report))   # doctest: +SKIP
"""

from __future__ import annotations

import argparse
import os
from dataclasses import dataclass, field

import numpy as np

#: The tensor groups ``--only`` selects from, in the order they are printed.
ONLY_CHOICES = ("born", "dielectric", "piezo", "elastic", "strain")

_KBAR_TO_GPA = 0.1


# ===================================================================== cells
@dataclass(frozen=True, eq=False)
class _Cell:
    """A crystal as spglib reads it (the attributes of ``PhonopyAtoms``)."""

    cell: np.ndarray
    scaled_positions: np.ndarray
    numbers: np.ndarray
    symbols: tuple


def _species_numbers(symbols) -> np.ndarray:
    ids: dict = {}
    return np.array([ids.setdefault(s, len(ids) + 1) for s in symbols], dtype=int)


def _as_cell(cell) -> _Cell:
    """A :class:`_Cell` from a POSCAR path, a ``PhonopyAtoms`` or a
    ``(lattice, positions, symbols)`` tuple."""
    if isinstance(cell, _Cell):
        return cell
    if isinstance(cell, (str, bytes)) or hasattr(cell, "__fspath__"):
        from .vasp_io import read_poscar_cell

        path = os.fspath(cell)
        try:
            atoms = read_poscar_cell(path)
        except (OSError, ValueError) as exc:
            raise ValueError(f"cannot read the structure {path}: {exc}") from None
        cell = atoms
    if isinstance(cell, tuple) and len(cell) == 3:
        lattice, positions, symbols = cell
        symbols = tuple(str(s) for s in symbols)
        return _Cell(np.asarray(lattice, dtype=float), np.asarray(positions, dtype=float),
                     _species_numbers(symbols), symbols)
    try:
        symbols = tuple(cell.symbols)
        return _Cell(np.asarray(cell.cell, dtype=float),
                     np.asarray(cell.scaled_positions, dtype=float),
                     np.asarray(cell.numbers, dtype=int), symbols)
    except AttributeError:
        raise ValueError("the structure must be a POSCAR path, a PhonopyAtoms or a "
                         "(lattice, positions, symbols) tuple") from None


@dataclass(frozen=True, eq=False)
class CrystalSymmetry:
    """The space-group operations of a cell in the Cartesian frame of its file.

    Attributes:
        lattice: Rows a, b, c (Angstrom).
        positions: Fractional coordinates.
        symbols: Chemical symbol of every atom.
        symprec: spglib tolerance (Angstrom).
        space_group: Hermann-Mauguin symbol (``"I4/mcm"``).
        number: Space-group number.
        setting: The point group in the tensor axes of ``crystod-group
            --tensor -c`` (a ``tensor_form.PointGroupSetting``).
        rotations: Every operation's rotation as an orthogonal Cartesian
            matrix in the input frame, ``(n_ops, 3, 3)``: the standard-setting
            matrix rotated by ``setting.input_axes`` (exactly orthogonal).
        point_rotations: The distinct rotations (the point group).
        mapping: ``mapping[k, i]`` is the atom operation k sends atom i to.
        site_operations: For every atom the indices of the operations that
            fix it (its site-symmetry group).
        wyckoffs: Wyckoff position of every atom (``"4b"``).
        site_symmetries: Site-symmetry symbol of every atom (``"-42m"``).
        orbits: Orbit number of every atom (1-based, in order of first
            appearance).
        lattice_deviation: Largest ``|R_cell - R|`` over the operations, where
            ``R_cell = L^T W L^-T`` is the rotation the cell's own lattice
            gives: 0 up to round-off for an ideal cell, of the order of the
            tolerance for a cell distorted within it.
    """

    lattice: np.ndarray
    positions: np.ndarray
    symbols: tuple
    symprec: float
    space_group: str
    number: int
    setting: object
    rotations: np.ndarray
    point_rotations: np.ndarray
    mapping: np.ndarray
    site_operations: tuple
    wyckoffs: tuple
    site_symmetries: tuple
    orbits: tuple
    lattice_deviation: float

    @property
    def axes(self) -> np.ndarray:
        """The tensor axes x, y, z as rows in the input frame."""
        return self.setting.input_axes

    @property
    def n_atoms(self) -> int:
        """Number of atoms of the cell."""
        return len(self.symbols)


def crystal_symmetry(cell, symprec: float = 1e-5) -> CrystalSymmetry:
    """Space-group operations, site groups and orbits of a structure.

    Args:
        cell: A POSCAR path, a ``PhonopyAtoms`` or a ``(lattice, positions,
            symbols)`` tuple (rows a, b, c in Angstrom, fractional
            coordinates).
        symprec: spglib tolerance (Angstrom).

    Returns:
        A :class:`CrystalSymmetry`.

    Raises:
        ValueError: The structure cannot be read, spglib finds no symmetry,
            or the operations of the cell do not match the standard setting.
    """
    import spglib

    from .tensor_form import _structure_setting

    atoms = _as_cell(cell)
    lattice, positions, numbers = atoms.cell, atoms.scaled_positions, atoms.numbers
    dataset = spglib.get_symmetry_dataset((lattice, positions, numbers), symprec=symprec)
    if dataset is None:
        raise ValueError(f"spglib found no symmetry for the structure (tolerance {symprec:g})")
    setting = _structure_setting(atoms, symprec)
    axes = setting.input_axes
    basis = setting.lattice_basis
    basis_inverse = np.linalg.inv(basis)
    transformation = np.asarray(dataset.transformation_matrix, dtype=float)
    transformation_inverse = np.linalg.inv(transformation)
    lattice_inverse_t = np.linalg.inv(lattice.T)
    rotations, deviation = [], 0.0
    for integer in dataset.rotations:
        standard = np.rint(transformation @ integer @ transformation_inverse)
        exact = axes.T @ (basis @ standard @ basis_inverse) @ axes
        own = lattice.T @ integer @ lattice_inverse_t
        deviation = max(deviation, float(np.abs(exact - own).max()))
        rotations.append(exact)
    rotations = np.array(rotations)
    if deviation > 0.05:
        raise ValueError(
            f"the rotations of the cell do not match the standard setting (deviation "
            f"{deviation:.2g}); a left-handed lattice is not supported")
    # atom mapping of every operation
    n_atoms = len(positions)
    mapping = np.zeros((len(rotations), n_atoms), dtype=int)
    for k, (integer, translation) in enumerate(zip(dataset.rotations, dataset.translations)):
        image = positions @ np.asarray(integer, dtype=float).T + translation
        diff = image[:, None, :] - positions[None, :, :]
        diff -= np.rint(diff)
        distance = np.linalg.norm(diff @ lattice, axis=2)
        distance[numbers[:, None] != numbers[None, :]] = np.inf
        target = np.argmin(distance, axis=1)
        if (distance[np.arange(n_atoms), target].max() > 10 * symprec + 1e-6
                or len(set(target.tolist())) != n_atoms):
            raise ValueError("an operation of spglib does not map the atoms onto each other")
        mapping[k] = target
    site_operations = tuple(tuple(int(k) for k in np.nonzero(mapping[:, i] == i)[0])
                            for i in range(n_atoms))
    unique, seen = [], set()
    for rotation in rotations:
        key = tuple(np.round(rotation, 6).ravel())
        if key not in seen:
            seen.add(key)
            unique.append(rotation)
    equivalent = list(dataset.equivalent_atoms)
    determinant = float(np.linalg.det(transformation))
    wyckoffs, orbit_numbers, order = [], [], {}
    for i in range(n_atoms):
        count = equivalent.count(equivalent[i])
        multiplicity = int(round(count / determinant))
        wyckoffs.append(f"{multiplicity}{dataset.wyckoffs[i]}")
        orbit_numbers.append(order.setdefault(equivalent[i], len(order) + 1))
    return CrystalSymmetry(
        lattice=lattice, positions=positions, symbols=atoms.symbols, symprec=symprec,
        space_group=str(dataset.international), number=int(dataset.number),
        setting=setting, rotations=rotations, point_rotations=np.array(unique),
        mapping=mapping, site_operations=site_operations, wyckoffs=tuple(wyckoffs),
        site_symmetries=tuple(str(s) for s in dataset.site_symmetry_symbols),
        orbits=tuple(orbit_numbers), lattice_deviation=deviation)


# ============================================================ group averages
def _jahn(kind: str):
    from .tensor_form import _resolve_kind, parse_jahn

    name, spec = _resolve_kind(kind)
    return name, parse_jahn(spec.jahn)


def _intrinsic(tensor: np.ndarray, jahn) -> np.ndarray:
    from .tensor_form import _symmetrizer

    shape = tensor.shape
    rank = jahn.rank
    flat = tensor.reshape(-1, 3 ** rank)
    return (flat @ _symmetrizer(jahn).T).reshape(shape)


def _rotate_stack(tensors: np.ndarray, rotation: np.ndarray, rank: int) -> np.ndarray:
    """``R x R x ... x R`` applied to the last ``rank`` axes."""
    out = tensors
    first = tensors.ndim - rank
    for axis in range(first, tensors.ndim):
        out = np.moveaxis(np.tensordot(rotation, out, axes=([1], [axis])), 0, axis)
    return out


def _sign(jahn, rotation) -> float:
    return float(np.sign(np.linalg.det(rotation))) if jahn.axial else 1.0


def _average(tensor: np.ndarray, jahn, rotations) -> np.ndarray:
    """Group average of one tensor (intrinsic symmetry included)."""
    base = _intrinsic(np.asarray(tensor, dtype=float), jahn)
    if jahn.time_odd:
        return np.zeros_like(base)
    total = np.zeros_like(base)
    for rotation in rotations:
        total += _sign(jahn, rotation) * _rotate_stack(base, rotation, jahn.rank)
    return total / len(rotations)


def _average_field(field_: np.ndarray, jahn, symmetry: CrystalSymmetry) -> np.ndarray:
    """Space-group average of one tensor per atom: ``T'[g(i)] = D(g) T[i]``
    summed over g; equivalent atoms become images of each other."""
    base = _intrinsic(np.asarray(field_, dtype=float), jahn)
    if jahn.time_odd:
        return np.zeros_like(base)
    total = np.zeros_like(base)
    for rotation, images in zip(symmetry.rotations, symmetry.mapping):
        total[images] += _sign(jahn, rotation) * _rotate_stack(base, rotation, jahn.rank)
    return total / len(symmetry.rotations)


def _setting_rotations(setting) -> np.ndarray:
    rotations = np.asarray(setting.rotations, dtype=float)
    axes = getattr(setting, "input_axes", None)
    if axes is None:
        return rotations
    return np.array([axes.T @ r @ axes for r in rotations])


[docs] def symmetrize_tensor(tensor, kind: str, cell, site=None, *, symprec: float = 1e-5): """Project a tensor onto its symmetry-allowed form (group average). The average ``(1/|G|) sum_g g.T`` (with the intrinsic index symmetry of ``kind``) is the orthogonal projection onto the allowed tensors in the Frobenius metric, so ``T - symmetrize_tensor(T)`` is the part of ``T`` that breaks the symmetry. The tensor is given, and returned, as a full Cartesian array in the frame of ``cell``. Args: tensor: The tensor, shape ``(3,) * rank``; or one tensor per atom of the cell, shape ``(n_atoms,) + (3,) * rank`` (Born effective charges, internal-strain tensors), averaged over the space group with the atoms mapped by every operation. kind: A kind of ``crystod-group --tensor`` (``dielectric``, ``piezoelectric-e``, ``elastic``, ...) or a Jahn symbol (``V2``, ``V[V2]``, ``[[V2]2]``; prefix ``e`` axial). A time-odd kind (prefix ``a``) vanishes: the group of a non-magnetic crystal contains time reversal. cell: A POSCAR path, a ``PhonopyAtoms``, a ``(lattice, positions, symbols)`` tuple, or a ``tensor_form.PointGroupSetting`` (the point group alone, e.g. ``point_group_setting("6mm")``; the tensor is then in its axes, or in the input frame of a setting made from a structure). site: None for a crystal tensor; an atom index (0-based) to average one site tensor over the site-symmetry group of that atom. symprec: spglib tolerance (Angstrom) for a structure. Returns: The symmetrized tensor, same shape as ``tensor``. Raises: ValueError: The shape does not fit the kind, or the structure cannot be analysed (``SystemExit`` for an unknown kind is reported as ``ValueError`` through ``crystod.group``). Example: >>> import numpy as np >>> from crystod.tensor_form import point_group_setting >>> from crystod.vasp_symmetry import symmetrize_tensor >>> eps = np.array([[2.0, 0.1, 0.0], [0.1, 2.2, 0.0], [0.0, 0.0, 3.0]]) >>> symmetrize_tensor(eps, "dielectric", point_group_setting("4/mmm")).round(3) array([[2.1, 0. , 0. ], [0. , 2.1, 0. ], [0. , 0. , 3. ]]) """ from .tensor_form import PointGroupSetting _, jahn = _jahn(kind) array = np.asarray(tensor, dtype=float) rank = jahn.rank single = (3,) * rank if isinstance(cell, PointGroupSetting): if site is not None: raise ValueError("site= needs a structure, not a point group") if array.shape != single: raise ValueError(f"a {jahn.symbol} tensor has the shape {single}, not " f"{array.shape}") return _average(array, jahn, _setting_rotations(cell)) symmetry = crystal_symmetry(cell, symprec) if array.ndim == rank + 1: if site is not None: raise ValueError("give one site tensor of shape " f"{single} with site=, or all of them without it") if array.shape != (symmetry.n_atoms,) + single: raise ValueError(f"one {jahn.symbol} tensor per atom has the shape " f"{(symmetry.n_atoms,) + single}, not {array.shape}") return _average_field(array, jahn, symmetry) if array.shape != single: raise ValueError(f"a {jahn.symbol} tensor has the shape {single}, not {array.shape}") if site is None: return _average(array, jahn, symmetry.point_rotations) index = int(site) if not 0 <= index < symmetry.n_atoms: raise ValueError(f"site {site}: the cell has atoms 0..{symmetry.n_atoms - 1}") operations = symmetry.rotations[list(symmetry.site_operations[index])] return _average(array, jahn, operations)
# ================================================================ results @dataclass(frozen=True, eq=False) class TensorCheck: """One crystal tensor against its allowed form. Attributes: key: Identifier (``"epsilon_inf"``, ``"piezo_ionic"``, ``"elastic_ionic"``, ...). label: Printed name (``"epsilon_inf"``). description: What the tensor is (``"electronic, clamped ions"``). source: The file and block it was read from. kind: Its ``crystod-group --tensor`` kind. unit: Unit of the values. raw: The tensor as read, full Cartesian array in the input frame. symmetrized: Its projection onto the allowed form (input frame). form: The allowed form (``tensor_form.TensorForm``) in the tensor axes. values: ``(name, raw, symmetrized)`` for every independent component, in the tensor axes. residual: ``||raw - symmetrized||`` (Frobenius, full tensor). relative_residual: ``residual / ||raw||`` (0 for a zero tensor). max_difference: Largest ``|raw - symmetrized|`` of a component. max_component: The matrix-notation name of that component (tensor axes), or ``""``. """ key: str label: str description: str source: str kind: str unit: str raw: np.ndarray symmetrized: np.ndarray form: object values: tuple residual: float relative_residual: float max_difference: float max_component: str @dataclass(frozen=True, eq=False) class SiteTensor: """One site tensor (one atom) of a :class:`SiteTensorCheck`. Attributes: site: Atom index (0-based; printed 1-based). element: Chemical symbol. wyckoff: Wyckoff position (``"8h"``). site_symmetry: Site-symmetry symbol (``"m.2m"``). orbit: Orbit number (1-based). form: The form the site group allows (tensor axes). raw: The tensor as read (input frame). site_symmetrized: Its average over the site-symmetry group. symmetrized: The space-group average (site group plus the orbit). values: ``(name, raw, symmetrized)`` of the independent components of ``form``, in the tensor axes. site_residual: ``||raw - site_symmetrized|| / ||raw||`` (the part the site group alone removes). orbit_residual: ``||site_symmetrized - symmetrized|| / ||raw||`` (the disagreement with the equivalent atoms of the orbit). relative_residual: ``||raw - symmetrized|| / ||raw||``. antisymmetric: For a second-rank tensor the antisymmetric part ``(A23, A31, A12)``, ``A_ij = (T_ij - T_ji) / 2`` of the raw tensor in the tensor axes; None otherwise. antisymmetric_allowed: True when the site group allows an antisymmetric part (second rank only). isotropic: ``tr(symmetrized) / 3`` for a second-rank tensor. """ site: int element: str wyckoff: str site_symmetry: str orbit: int form: object raw: np.ndarray site_symmetrized: np.ndarray symmetrized: np.ndarray values: tuple site_residual: float orbit_residual: float relative_residual: float antisymmetric: tuple | None = None antisymmetric_allowed: bool | None = None isotropic: float | None = None @dataclass(frozen=True, eq=False) class SiteTensorCheck: """One tensor per atom (Born effective charges, internal strain). Attributes: key: Identifier (``"born"``, ``"strain"``). label: Printed name (``"Z*"``, ``"Lambda"``). description: What the tensors are. source: The file and block they were read from. kind: The ``crystod-group --tensor`` kind of one site tensor (``"V2"``, ``"V[V2]"``). unit: Unit of the values. sites: One :class:`SiteTensor` per atom. raw: ``(n_atoms, 3, ...)`` as read (input frame). symmetrized: The space-group average (input frame). residual: ``||raw - symmetrized||`` over all atoms. relative_residual: ``residual / ||raw||``. max_difference: Largest ``|raw - symmetrized|`` of a component. max_site: The atom (0-based) of that component. max_component: Its name in the tensor axes. sum_rule: ``sum_k raw_k`` (input frame): zero for the acoustic sum rule of Z* and for the internal strain. sum_rule_symmetrized: ``sum_k symmetrized_k``. agreement: Largest difference from the same tensors in the other file (vasprun.xml against OUTCAR), or None. """ key: str label: str description: str source: str kind: str unit: str sites: tuple raw: np.ndarray symmetrized: np.ndarray residual: float relative_residual: float max_difference: float max_site: int max_component: str sum_rule: np.ndarray sum_rule_symmetrized: np.ndarray agreement: float | None = None
[docs] @dataclass(frozen=True, eq=False) class VaspSymmetryReport: """Every tensor of a VASP run against the symmetry of its structure. Attributes: vasprun: Path of the ``vasprun.xml`` read, or None. outcar: Path of the ``OUTCAR`` read, or None. structure: Where the structure came from. formula: Formula of the cell (``"Sr2Ti2O6"``). reduced_formula: Reduced formula (``"SrTiO3"``), used in the YAML file name. run: Run parameters (``IBRION``, ``ISIF``, ``NSW``, ``LEPSILON``, ``ISPIN``, ``LNONCOLLINEAR``, ``ISYM``, ``SYMPREC``) and VASP's own symmetry (``n_operations``, ``point_group``) where the files give them. symmetry: The :class:`CrystalSymmetry` of the structure. tensors: :class:`TensorCheck` and :class:`SiteTensorCheck` records in the printed order. missing: ``(quantity, reason)`` for every selected quantity that the files do not hold. notes: Extra lines for the run block. """ vasprun: str | None outcar: str | None structure: str formula: str reduced_formula: str run: dict symmetry: CrystalSymmetry tensors: tuple missing: tuple = () notes: tuple = field(default=())
[docs] def tensor(self, key: str): """The record with this key (``"born"``, ``"epsilon_inf"``, ...), or None.""" for record in self.tensors: if record.key == key: return record return None
[docs] def to_dict(self) -> dict: """The content of the YAML file as plain Python data (floats rounded to 10 significant digits).""" return _report_dict(self)
# ============================================================ tensor checks def _component_cells(form): """``[(name, index tuple, factor)]`` of every display cell of a form.""" from .tensor_form import _cell_factor, _cell_name, _cells cells = [] for row, column, indices in _cells(form.layout, form.jahn.rank): name = _cell_name(form.letter, form.layout, row, column, indices) cells.append((name, tuple(indices), _cell_factor(form.voigt, form.layout, row, column))) return cells def _independent_values(form, raw_axes: np.ndarray, sym_axes: np.ndarray) -> tuple: """``(name, raw, symmetrized)`` of the independent components. The symmetrized value is the coefficient of ``form.tensors[k]`` in the least-squares expansion of the symmetrized tensor; since that tensor is in the allowed space and ``tensors[k]`` is the allowed tensor with component k equal to 1 and the other independent ones 0, the coefficient is the (matrix-notation) component itself, read here without the round-off of a numerical solve. """ cells = {name: (indices, factor) for name, indices, factor in _component_cells(form)} values = [] for name in form.independent: indices, factor = cells[name] values.append((name, float(factor * raw_axes[indices]), float(factor * sym_axes[indices]))) return tuple(values) def _largest_difference(form, difference_axes: np.ndarray) -> tuple[float, str]: best, where = 0.0, "" for name, indices, factor in _component_cells(form): value = abs(factor * difference_axes[indices]) if value > best + 1e-300: best, where = float(value), name return best, where def _norm(array) -> float: return float(np.linalg.norm(np.asarray(array).ravel())) def _relative(numerator: float, denominator: float) -> float: return numerator / denominator if denominator > 0 else 0.0 def _crystal_check(key, label, description, source, kind, unit, raw, symmetry: CrystalSymmetry) -> TensorCheck: from .tensor_form import _rotate, tensor_form_of_operations _, jahn = _jahn(kind) form = tensor_form_of_operations(symmetry.setting.rotations, kind, setting=symmetry.setting) symmetrized = _average(raw, jahn, symmetry.point_rotations) axes = symmetry.axes raw_axes, sym_axes = _rotate(raw, axes), _rotate(symmetrized, axes) residual = _norm(raw - symmetrized) max_difference, where = _largest_difference(form, raw_axes - sym_axes) return TensorCheck( key=key, label=label, description=description, source=source, kind=kind, unit=unit, raw=raw, symmetrized=symmetrized, form=form, values=_independent_values(form, raw_axes, sym_axes), residual=residual, relative_residual=_relative(residual, _norm(raw)), max_difference=max_difference, max_component=where) def _site_check(key, label, description, source, kind, unit, raw, symmetry: CrystalSymmetry, agreement=None) -> SiteTensorCheck: from .tensor_form import _rotate, tensor_form_of_operations _, jahn = _jahn(kind) axes = symmetry.axes symmetrized = _average_field(raw, jahn, symmetry) forms: dict = {} sites = [] best, best_site, best_name = 0.0, 0, "" for i in range(symmetry.n_atoms): operations = symmetry.rotations[list(symmetry.site_operations[i])] in_axes = np.array([axes @ r @ axes.T for r in operations]) cache_key = tuple(sorted(tuple(np.round(r, 6).ravel()) for r in in_axes)) if cache_key not in forms: forms[cache_key] = tensor_form_of_operations(in_axes, kind) form = forms[cache_key] site_average = _average(raw[i], jahn, operations) raw_axes = _rotate(raw[i], axes) sym_axes = _rotate(symmetrized[i], axes) size = _norm(raw[i]) difference, where = _largest_difference(form, raw_axes - sym_axes) if difference > best: best, best_site, best_name = difference, i, where antisymmetric = allowed = isotropic = None if jahn.rank == 2: part = (raw_axes - raw_axes.T) / 2.0 antisymmetric = (float(part[1, 2]), float(part[2, 0]), float(part[0, 1])) allowed = any(_norm(t - t.T) > 1e-9 for t in form.tensors) isotropic = float(np.trace(symmetrized[i]) / 3.0) sites.append(SiteTensor( site=i, element=symmetry.symbols[i], wyckoff=symmetry.wyckoffs[i], site_symmetry=symmetry.site_symmetries[i], orbit=symmetry.orbits[i], form=form, raw=raw[i], site_symmetrized=site_average, symmetrized=symmetrized[i], values=_independent_values(form, raw_axes, sym_axes), site_residual=_relative(_norm(raw[i] - site_average), size), orbit_residual=_relative(_norm(site_average - symmetrized[i]), size), relative_residual=_relative(_norm(raw[i] - symmetrized[i]), size), antisymmetric=antisymmetric, antisymmetric_allowed=allowed, isotropic=isotropic)) residual = _norm(raw - symmetrized) return SiteTensorCheck( key=key, label=label, description=description, source=source, kind=kind, unit=unit, sites=tuple(sites), raw=raw, symmetrized=symmetrized, residual=residual, relative_residual=_relative(residual, _norm(raw)), max_difference=best, max_site=best_site, max_component=best_name, sum_rule=raw.sum(axis=0), sum_rule_symmetrized=symmetrized.sum(axis=0), agreement=agreement) def _vasp_pairs_full(table: np.ndarray, rank: int) -> np.ndarray: """A VASP six-column table (``XX YY ZZ XY YZ ZX``) as a full tensor: ``(3, 6) -> (3, 3, 3)`` or ``(6, 6) -> (3, 3, 3, 3)``, no factors.""" from .vasp_io import VASP_PAIRS table = np.asarray(table, dtype=float) if rank == 3: full = np.zeros((3, 3, 3)) for i in range(3): for column, (j, k) in enumerate(VASP_PAIRS): full[i, j, k] = full[i, k, j] = table[i, column] return full full = np.zeros((3, 3, 3, 3)) for row, (i, j) in enumerate(VASP_PAIRS): for column, (k, l) in enumerate(VASP_PAIRS): value = table[row, column] for a, b in ((i, j), (j, i)): for c, d in ((k, l), (l, k)): full[a, b, c, d] = value return full def _strain_full(tables: np.ndarray) -> np.ndarray: return np.array([_vasp_pairs_full(t, 3) for t in tables]) # ================================================================== files def _file_kind(path: str) -> str: from .vasp_io import open_vasp_file with open_vasp_file(path) as handle: head = handle.read(512) stripped = head.lstrip() if stripped.startswith("<?xml") or stripped.startswith("<modeling"): return "vasprun" if "vasp." in head[:200]: return "outcar" raise SystemExit(f"ERROR: {path} is neither a vasprun.xml nor an OUTCAR.") def _cell_formula(symbols) -> str: counts: dict = {} for symbol in symbols: counts[symbol] = counts.get(symbol, 0) + 1 return "".join(f"{s}{n if n > 1 else ''}" for s, n in counts.items()) def _reduced_formula(symbols) -> str: import math counts: dict = {} for symbol in symbols: counts[symbol] = counts.get(symbol, 0) + 1 divisor = 0 for n in counts.values(): divisor = math.gcd(divisor, n) return "".join(f"{s}{n // divisor if n // divisor > 1 else ''}" for s, n in counts.items()) def _parse_only(only) -> tuple: if only is None: return ONLY_CHOICES tokens = [only] if isinstance(only, str) else list(only) wanted = [] for token in tokens: for name in str(token).replace(",", " ").split(): name = name.strip().lower() if name not in ONLY_CHOICES: raise SystemExit(f"ERROR: --only {name}: choose from {', '.join(ONLY_CHOICES)} " "(comma separated).") if name not in wanted: wanted.append(name) if not wanted: raise SystemExit(f"ERROR: --only needs one of {', '.join(ONLY_CHOICES)}.") return tuple(name for name in ONLY_CHOICES if name in wanted)
[docs] def vasp_symmetry_report(path: str, *, outcar: str | None = None, cell=None, only=None, symprec: float = 1e-5) -> VaspSymmetryReport: """Check the response tensors of a VASP run against the symmetry of its structure. Args: path: The ``vasprun.xml`` or the ``OUTCAR`` of the run (either may be gzipped). ``vasprun.xml`` holds Z* and the dielectric tensors; the piezoelectric, elastic and internal-strain tensors are only in the ``OUTCAR``. outcar: The ``OUTCAR`` that completes a ``vasprun.xml`` (its Z* and dielectric tensors are compared with those of the ``vasprun.xml``, which win). cell: The structure: a POSCAR path or a ``PhonopyAtoms`` with the atoms in the order of the run. Default: the initial structure of the ``vasprun.xml``, or the ``POSCAR`` next to the ``OUTCAR``. only: Tensor groups to check, any of ``born``, ``dielectric``, ``piezo``, ``elastic``, ``strain`` (a list or a comma-separated string; default all). symprec: spglib tolerance (Angstrom). Returns: A :class:`VaspSymmetryReport`. Raises: SystemExit: Missing or unreadable files, a structure that does not match the run, or none of the selected tensors in the files (``ValueError`` through ``crystod.group``). """ from .vasp_io import read_outcar_response, read_vasprun_response, resolve_vasp_file selected = _parse_only(only) resolved = resolve_vasp_file(path) if not resolved: raise SystemExit(f"ERROR: no file {path} (give the vasprun.xml or the OUTCAR of the run).") kind = _file_kind(resolved) vasprun = outcar_data = None if kind == "vasprun": vasprun = read_vasprun_response(resolved) else: if outcar is not None: raise SystemExit("ERROR: --outcar completes a vasprun.xml; the main file is already " f"an OUTCAR ({resolved}).") outcar_data = read_outcar_response(resolved) if outcar is not None: resolved_outcar = resolve_vasp_file(outcar) if not resolved_outcar: raise SystemExit(f"ERROR: no OUTCAR at {outcar}.") if _file_kind(resolved_outcar) != "outcar": raise SystemExit(f"ERROR: --outcar {outcar} is not an OUTCAR.") outcar_data = read_outcar_response(resolved_outcar) # ---- structure if cell is not None: atoms = _as_cell(cell) structure = os.fspath(cell) if isinstance(cell, (str, os.PathLike)) else "the given cell" elif vasprun is not None and vasprun.lattice is not None: atoms = _as_cell((vasprun.lattice, vasprun.positions, vasprun.elements)) structure = f"{os.path.basename(vasprun.path)}, initial positions" else: poscar = os.path.join(os.path.dirname(resolved), "POSCAR") if not os.path.isfile(poscar): raise SystemExit(f"ERROR: no POSCAR next to {resolved}: give the structure with " "-c POSCAR (the atoms in the order of the run).") atoms = _as_cell(poscar) structure = poscar n_atoms = len(atoms.symbols) for source, count in ((vasprun, None if vasprun is None else len(vasprun.elements)), (outcar_data, None if outcar_data is None else outcar_data.facts.get("NIONS"))): if source is not None and count is not None and count != n_atoms: raise SystemExit(f"ERROR: the structure has {n_atoms} atoms, the run " f"{source.path} {count}.") if vasprun is not None and vasprun.elements and cell is not None: if [s.strip() for s in vasprun.elements] != list(atoms.symbols): raise SystemExit("ERROR: the elements of -c are not those of the run, atom by atom " f"({_cell_formula(atoms.symbols)} vs " f"{_cell_formula(vasprun.elements)}).") try: symmetry = crystal_symmetry(atoms, symprec) except ValueError as exc: raise SystemExit(f"ERROR: {exc}") from None # ---- run facts run: dict = {} if outcar_data is not None: run.update(outcar_data.facts) if vasprun is not None: for name in ("IBRION", "ISIF", "NSW", "LEPSILON", "LCALCEPS", "ISPIN", "LNONCOLLINEAR", "LSORBIT", "ISYM", "SYMPREC"): if name in vasprun.parameters: run[name] = vasprun.parameters[name] run.pop("MAGMOM", None) vasprun_name = "vasprun.xml" outcar_name = "OUTCAR" tensors: list = [] missing: list = [] notes: list = [] if "born" in selected: born = agreement = None if vasprun is not None and vasprun.born_charges is not None: born, source = vasprun.born_charges, f"{vasprun_name} born_charges" if outcar_data is not None and outcar_data.born_charges is not None \ and outcar_data.born_charges.shape == born.shape: agreement = float(np.abs(outcar_data.born_charges - born).max()) elif outcar_data is not None and outcar_data.born_charges is not None: born, source = outcar_data.born_charges, f"{outcar_name} BORN EFFECTIVE CHARGES" if born is None: missing.append(("Born effective charges", "not in the files (a LEPSILON or " "LCALCEPS run writes them)")) elif born.shape != (n_atoms, 3, 3): raise SystemExit(f"ERROR: {born.shape[0]} Born charges for {n_atoms} atoms.") else: tensors.append(_site_check( "born", "Z*", "Born effective charges", source, "V2", "|e|", born, symmetry, agreement)) if "dielectric" in selected: found = {} for name, attribute in (("epsilon_inf", "epsilon"), ("epsilon_ion", "epsilon_ion")): if vasprun is not None and getattr(vasprun, attribute) is not None: found[name] = (getattr(vasprun, attribute), f"{vasprun_name} {attribute}") elif outcar_data is not None and getattr(outcar_data, attribute) is not None: found[name] = (getattr(outcar_data, attribute), f"{outcar_name} {outcar_data.headings[attribute]}") if not found: missing.append(("dielectric tensor", "not in the files (a LEPSILON or LCALCEPS " "run writes it)")) texts = {"epsilon_inf": "electronic (clamped ions)", "epsilon_ion": "ionic contribution"} for name, (value, source) in found.items(): tensors.append(_crystal_check(name, name, texts[name], source, "dielectric", "", np.asarray(value, dtype=float), symmetry)) if len(found) == 2: total = found["epsilon_inf"][0] + found["epsilon_ion"][0] tensors.append(_crystal_check("epsilon_0", "epsilon_0", "static, epsilon_inf + epsilon_ion", "sum of the two", "dielectric", "", total, symmetry)) if "piezo" in selected: parts = [] if outcar_data is not None: for name, attribute, text in ( ("piezo_electronic", "piezo_electronic", "electronic (clamped ions)"), ("piezo_ionic", "piezo_ionic", "ionic contribution")): table = getattr(outcar_data, attribute) if table is not None: parts.append((name, text, f"{outcar_name} {outcar_data.headings[attribute]}", _vasp_pairs_full(table, 3))) if not parts: missing.append(("piezoelectric tensor", "not in vasprun.xml: give --outcar OUTCAR" if outcar_data is None else "not in the OUTCAR")) for name, text, source, full in parts: tensors.append(_crystal_check(name, name.replace("piezo_", "e_"), text, source, "piezoelectric-e", "C/m^2", full, symmetry)) if len(parts) == 2: tensors.append(_crystal_check("piezo_total", "e_total", "electronic + ionic", "sum of the two", "piezoelectric-e", "C/m^2", parts[0][3] + parts[1][3], symmetry)) if "elastic" in selected: tables = outcar_data.elastic if outcar_data is not None else {} texts = {"clamped": "clamped ions", "symmetrized": "clamped ions, symmetrized by VASP", "ionic": "ionic relaxation contribution", "total": "total"} if not tables: missing.append(("elastic tensor", "not in vasprun.xml: give --outcar OUTCAR" if outcar_data is None else "not in the OUTCAR (IBRION = 5-8 with ISIF >= 3 writes it)")) for name in ("clamped", "symmetrized", "ionic", "total"): if name in tables: full = _vasp_pairs_full(tables[name], 4) * _KBAR_TO_GPA tensors.append(_crystal_check( f"elastic_{name}", f"C_{name}", texts[name], f"{outcar_name} {outcar_data.headings['elastic:' + name]} / 10", "elastic", "GPa", full, symmetry)) if "strain" in selected: tables = outcar_data.internal_strain if outcar_data is not None else None if tables is None: missing.append(("internal-strain tensor", "not in vasprun.xml: give --outcar OUTCAR" if outcar_data is None else "not in the OUTCAR")) elif tables.shape[0] != n_atoms: raise SystemExit(f"ERROR: {tables.shape[0]} internal-strain tensors for " f"{n_atoms} atoms.") else: tensors.append(_site_check( "strain", "Lambda", "internal-strain tensors (force per strain)", f"{outcar_name} {outcar_data.headings['internal_strain']}", "V[V2]", "eV/Angstrom", _strain_full(tables), symmetry)) if not tensors: reasons = "; ".join(f"{q}: {r}" for q, r in missing) raise SystemExit(f"ERROR: none of the selected tensors is in the files ({reasons}).") vasp_ops = run.get("n_operations") if vasp_ops is not None and vasp_ops != len(symmetry.rotations): notes.append(f"VASP found {vasp_ops} space-group operations, spglib " f"{len(symmetry.rotations)} at tolerance {symprec:g} Angstrom: the run used " "another symmetry than the one the tensors are checked against") return VaspSymmetryReport( vasprun=None if vasprun is None else vasprun.path, outcar=None if outcar_data is None else outcar_data.path, structure=structure, formula=_cell_formula(atoms.symbols), reduced_formula=_reduced_formula(atoms.symbols), run=run, symmetry=symmetry, tensors=tuple(tensors), missing=tuple(missing), notes=tuple(notes))
# ================================================================= output _TITLES = {"born": "Born effective charges", "dielectric": "Dielectric tensor", "piezo": "Piezoelectric tensor", "elastic": "Elastic tensor", "strain": "Internal strain"} _GROUP_OF = {"born": "born", "epsilon_inf": "dielectric", "epsilon_ion": "dielectric", "epsilon_0": "dielectric", "piezo_electronic": "piezo", "piezo_ionic": "piezo", "piezo_total": "piezo", "elastic_clamped": "elastic", "elastic_symmetrized": "elastic", "elastic_ionic": "elastic", "elastic_total": "elastic", "strain": "strain"} _NOTATION = ("matrix notation (Nye): L = 1..6 for the index pairs 11, 22, 33, 23, 13, 12, " "no factors (VASP prints the columns XX YY ZZ XY YZ ZX, i.e. L = 1 2 3 6 4 5)") def _number(value: float) -> str: return f"{float(value) + 0.0:.6f}" def _small(value: float) -> str: return f"{float(value) + 0.0:.1e}" def _size_text(path: str) -> str: try: return f"{os.path.getsize(path) / 1e6:.1f} MB" except OSError: return "?" def _flag(value) -> str: if isinstance(value, bool): return "T" if value else "F" if isinstance(value, float): return f"{value:g}" return str(value) def _table(rows: list) -> list: 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] def _relations_text(form) -> str: if not form.independent: return "every component is zero" parts = list(form.relations) n_zero = sum(1 for c in range(len(form.components)) if not np.any(np.abs(form.basis[:, c]) > 1e-10)) if n_zero: parts.append("every other component is zero") return "; ".join(parts) if parts else "none (the nonzero components are independent)" def _ranges(indices) -> str: """``[0, 1, 4, 5, 6] -> "1-2, 5-7"`` (1-based).""" numbers = sorted(i + 1 for i in indices) groups, start, previous = [], None, None for n in numbers: if start is None: start = previous = n elif n == previous + 1: previous = n else: groups.append((start, previous)) start = previous = n if start is not None: groups.append((start, previous)) return ", ".join(f"{a}" if a == b else f"{a}-{b}" for a, b in groups) def _vector_text(vector) -> str: return "(" + ", ".join(f"{round(float(v), 4) + 0.0:.4f}" for v in vector) + ")" def _run_lines(report: VaspSymmetryReport) -> list: run = report.run lines = ["* VASP run *"] if report.vasprun: lines.append(f" vasprun.xml {report.vasprun} ({_size_text(report.vasprun)})") if report.outcar: lines.append(f" OUTCAR {report.outcar} ({_size_text(report.outcar)})") lines.append(f" structure {report.structure} ({report.formula}, " f"{report.symmetry.n_atoms} atoms)") tags = [f"{name} {_flag(run[name])}" for name in ("IBRION", "ISIF", "NSW", "LEPSILON", "LCALCEPS", "ISPIN", "LNONCOLLINEAR") if name in run] if tags: lines.append(" parameters " + ", ".join(tags)) symmetry = [] if "ISYM" in run: symmetry.append(f"ISYM {_flag(run['ISYM'])}") if "SYMPREC" in run: symmetry.append(f"SYMPREC {_flag(run['SYMPREC'])}") if "n_operations" in run: text = f"{run['n_operations']} space-group operations" if "point_group" in run: text += f" (point group of the space group {run['point_group']})" symmetry.append(text) if symmetry: lines.append(" VASP " + ", ".join(symmetry)) read = [] names = {"born": "Born effective charges", "dielectric": "dielectric", "piezo": "piezoelectric", "elastic": "elastic", "strain": "internal strain"} for group in ONLY_CHOICES: labels = [t.label for t in report.tensors if _GROUP_OF[t.key] == group] if labels: read.append(f"{names[group]} ({', '.join(labels)})") lines.append(" read " + "; ".join(read)) for quantity, reason in report.missing: lines.append(f" not read {quantity}: {reason}") for note in report.notes: lines.append(f" NOTE: {note}") return lines def _space_group_lines(report: VaspSymmetryReport) -> list: symmetry = report.symmetry setting = symmetry.setting lines = ["* Space group *", f" {symmetry.space_group} (No. {symmetry.number}), point group {setting.symbol} " f"({setting.schoenflies}); {len(symmetry.rotations)} operations in the cell " f"(spglib, tolerance {symmetry.symprec:g} Angstrom)", f" tensor axes: {setting.axes} (the axes of crystod-group --tensor -c)", " tensor axes in the Cartesian frame of the input file: " + ", ".join(f"{name} = {_vector_text(v)}" for name, v in zip("xyz", symmetry.axes)), f" largest deviation of the cell's rotations from the ideal setting: " f"{_small(symmetry.lattice_deviation)}"] rows = [["site", "element", "Wyckoff", "site symmetry", "orbit"]] for i in range(symmetry.n_atoms): rows.append([str(i + 1), symmetry.symbols[i], symmetry.wyckoffs[i], symmetry.site_symmetries[i], str(symmetry.orbits[i])]) return lines + _table(rows) def _header(check) -> str: unit = f", {check.unit}" if check.unit else "" return f" {check.label}: {check.description}{unit}; {check.source}" def _crystal_lines(check: TensorCheck) -> list: lines = [_header(check)] if not check.values: lines.append(f" every component is zero by symmetry; max |raw| = " f"{_small(np.abs(check.raw).max())}") return lines rows = [["component", "raw", "symmetrized", "difference"]] for name, raw, sym in check.values: rows.append([name, _number(raw), _number(sym), _small(raw - sym)]) lines += _table(rows) where = f" ({check.max_component})" if check.max_component else "" lines.append(f" relative residual {_small(check.relative_residual)}, max |raw - " f"symmetrized| {_small(check.max_difference)}{where}") lines.append(f" relations: {_relations_text(check.form)}") return lines def _site_lines(check: SiteTensorCheck) -> list: lines = [_header(check), " each site averaged over its site-symmetry group, the orbits made consistent " "by the space group"] rows = [["site", "element", "site symmetry", "component", "raw", "symmetrized", "difference", "rel. residual"]] for site in check.sites: first = True values = site.values or (("-", 0.0, 0.0),) for name, raw, sym in values: rows.append([str(site.site + 1) if first else "", site.element if first else "", site.site_symmetry if first else "", name, _number(raw) if site.values else "-", _number(sym) if site.values else "-", _small(raw - sym) if site.values else "-", _small(site.relative_residual) if first else ""]) first = False lines += _table(rows) worst = max(check.sites, key=lambda s: s.relative_residual) where = (f" (site {check.max_site + 1}, {check.max_component})" if check.max_component else "") lines.append(f" relative residual {_small(check.relative_residual)} (all sites), largest " f"{_small(worst.relative_residual)} (site {worst.site + 1}); max |raw - " f"symmetrized| {_small(check.max_difference)}{where}") lines.append(f" of which the site groups alone " f"{_small(max(s.site_residual for s in check.sites))}, the consistency over " f"the orbits {_small(max(s.orbit_residual for s in check.sites))} " "(largest relative values)") # relations, grouped over consecutive sites with the same text groups: list = [] for site in check.sites: text = _relations_text(site.form) if groups and groups[-1][1] == site.site_symmetry and groups[-1][2] == text: groups[-1][0].append(site.site) else: groups.append(([site.site], site.site_symmetry, text)) lines.append(" relations (site group, tensor axes):") for members, symbol, text in groups: noun = "site" if len(members) == 1 else "sites" lines.append(f" {noun} {_ranges(members)} ({symbol}): {text}") if check.sites and check.sites[0].antisymmetric is not None: lines.append(" isotropic part tr(Z*)/3 and antisymmetric part A_ij = (Z_ij - Z_ji)/2 " "of the raw tensors (tensor axes):") rows = [["site", "element", "isotropic", "A23", "A31", "A12", "allowed"]] for site in check.sites: rows.append([str(site.site + 1), site.element, _number(site.isotropic)] + [_number(a) for a in site.antisymmetric] + ["yes" if site.antisymmetric_allowed else "no"]) lines += _table(rows) rule = "acoustic sum rule" if check.key == "born" else "sum rule" lines.append(f" {rule}: max |sum_k {check.label}_k| = {_small(np.abs(check.sum_rule).max())} " f"(raw), {_small(np.abs(check.sum_rule_symmetrized).max())} (symmetrized; not " "imposed here)") if check.agreement is not None: lines.append(f" the OUTCAR values agree with vasprun.xml within " f"{_small(check.agreement)} (printed digits)") return lines _WIDTH = 100 def _wrap(lines: list) -> list: """Text lines (indented) wrapped at 100 columns with a hanging indent; table rows (unindented) are kept as they are.""" import re import textwrap out = [] for line in lines: if len(line) <= _WIDTH or not line.startswith(" "): out.append(line) continue label = re.match(r"^( \S+(?: \S+)?\s{2,})\S", line) lead = len(line) - len(line.lstrip(" ")) hanging = " " * (len(label.group(1)) if label else lead + 2) out.extend(textwrap.wrap(line.lstrip(" "), width=_WIDTH, initial_indent=" " * lead, subsequent_indent=hanging, break_long_words=False, break_on_hyphens=False) if not label else textwrap.wrap(line[len(label.group(1)):], width=_WIDTH, initial_indent=label.group(1), subsequent_indent=hanging, break_long_words=False, break_on_hyphens=False)) return out
[docs] def format_vasp_symmetry(report: VaspSymmetryReport) -> str: """The report ``crystod --check-symmetry`` prints. Args: report: A :class:`VaspSymmetryReport`. Returns: The ``* Title *`` blocks ``VASP run``, ``Space group`` and one block per tensor group read: ``Born effective charges``, ``Dielectric tensor``, ``Piezoelectric tensor``, ``Elastic tensor``, ``Internal strain``. Independent components are named and valued in the tensor axes of ``crystod-group --tensor -c``; residuals are Frobenius norms of the full Cartesian tensors. """ lines = [""] + _run_lines(report) + [""] + _space_group_lines(report) for group in ONLY_CHOICES: records = [t for t in report.tensors if _GROUP_OF[t.key] == group] if not records: continue lines += ["", f"* {_TITLES[group]} *"] if group in ("piezo", "elastic", "strain"): lines.append(f" {_NOTATION}") for record in records: if isinstance(record, SiteTensorCheck): lines += _site_lines(record) else: lines += _crystal_lines(record) return "\n".join(_wrap(lines))
# ==================================================================== YAML def _round(value, digits: int = 10): value = float(value) if value == 0.0 or not np.isfinite(value): return value + 0.0 return float(f"{value:.{digits}g}") + 0.0 def _rounded(array) -> list: array = np.asarray(array, dtype=float) if array.ndim == 0: return _round(array) return [_rounded(a) for a in array] def _voigt(full: np.ndarray, rank: int) -> np.ndarray: """Full tensor -> Voigt matrix (3x3 kept, 3x6 or 6x6, no factors).""" pairs = ((0, 0), (1, 1), (2, 2), (1, 2), (2, 0), (0, 1)) if rank == 2: return full if rank == 3: return np.array([[full[i, j, k] for j, k in pairs] for i in range(3)]) return np.array([[full[i, j, k, l] for k, l in pairs] for i, j in pairs]) def _values_dict(values) -> dict: return {"independent": [name for name, _, _ in values], "raw": [_round(raw) for _, raw, _ in values], "symmetrized": [_round(sym) for _, _, sym in values]} def _report_dict(report: VaspSymmetryReport) -> dict: from . import __version__ symmetry = report.symmetry run = {"vasprun": report.vasprun, "outcar": report.outcar, "structure": report.structure, "formula": report.formula} for name, value in report.run.items(): run[name] = value if not isinstance(value, float) else _round(value) data = {"crystod_version": __version__, "mode": "check-symmetry", "run": run, "space_group": symmetry.space_group, "space_group_number": symmetry.number, "point_group": symmetry.setting.symbol, "symprec": symmetry.symprec, "tensor_axes": _rounded(symmetry.axes), "sites": [{"site": i + 1, "element": symmetry.symbols[i], "wyckoff": symmetry.wyckoffs[i], "site_symmetry": symmetry.site_symmetries[i], "orbit": symmetry.orbits[i]} for i in range(symmetry.n_atoms)], "tensors": [], "missing": [{"quantity": q, "reason": r} for q, r in report.missing]} for record in report.tensors: rank = record.form.jahn.rank if isinstance(record, TensorCheck) \ else record.sites[0].form.jahn.rank entry = {"name": record.key, "label": record.label, "description": record.description, "kind": record.kind, "unit": record.unit, "source": record.source} if isinstance(record, TensorCheck): entry.update(_values_dict(record.values)) entry["relations"] = list(record.form.relations) entry["relative_residual"] = _round(record.relative_residual) entry["max_difference"] = _round(record.max_difference) entry["raw_matrix"] = _rounded(_voigt(record.raw, rank)) entry["symmetrized_matrix"] = _rounded(_voigt(record.symmetrized, rank)) else: entry["relative_residual"] = _round(record.relative_residual) entry["max_difference"] = _round(record.max_difference) entry["sum_rule_max"] = _round(np.abs(record.sum_rule).max()) if record.agreement is not None: entry["agreement_with_outcar"] = _round(record.agreement) entry["sites"] = [] for site in record.sites: item = {"site": site.site + 1, "element": site.element, "site_symmetry": site.site_symmetry} item.update(_values_dict(site.values)) item["relations"] = list(site.form.relations) item["relative_residual"] = _round(site.relative_residual) item["site_residual"] = _round(site.site_residual) item["orbit_residual"] = _round(site.orbit_residual) if site.antisymmetric is not None: item["isotropic"] = _round(site.isotropic) item["antisymmetric"] = [_round(a) for a in site.antisymmetric] item["antisymmetric_allowed"] = bool(site.antisymmetric_allowed) item["raw_matrix"] = _rounded(_voigt(site.raw, rank)) item["symmetrized_matrix"] = _rounded(_voigt(site.symmetrized, rank)) entry["sites"].append(item) data["tensors"].append(entry) return data def write_vasp_symmetry_yaml(report: VaspSymmetryReport, path: str) -> str: """Write the YAML file of ``crystod --check-symmetry``. The layout follows ``crystod --extract-irrep -o``: run metadata, the space group and the sites, then one entry per tensor with the independent components (``raw`` and ``symmetrized``, tensor axes), the relations, the residuals and the full matrices in the Cartesian frame of the input file (``raw_matrix``, ``symmetrized_matrix``; Voigt order ``xx yy zz yz zx xy`` for the 3x6 and 6x6 forms, no factors). Site tensors carry one such entry per atom. Returns: ``path``. """ from .extract_irrep import _yaml_lines data = _report_dict(report) lines = ["# crystod --check-symmetry: response tensors of a VASP run against the " "symmetry of its structure"] blocks = [("crystod_version", "mode", "run"), ("space_group", "space_group_number", "point_group", "symprec", "tensor_axes", "sites"), ("tensors", "missing")] for keys in blocks: lines.extend(_yaml_lines({key: data[key] for key in keys})) lines.append("") with open(path, "w") as handle: handle.write("\n".join(lines)) return path # ===================================================================== CLI def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="crystod --check-symmetry", description="Response tensors of a VASP run (Born effective charges, dielectric, " "piezoelectric, elastic and internal-strain tensors) against the " "symmetry of its structure.") parser.add_argument("path", help="vasprun.xml or OUTCAR of the run") parser.add_argument("--outcar", default=None, metavar="OUTCAR", help="OUTCAR completing a vasprun.xml (piezoelectric, elastic, " "internal strain)") parser.add_argument("-c", "--cell", "--poscar", dest="cell", default=None, metavar="FILE", help="structure (default: the run's own)") parser.add_argument("--only", default=None, metavar="LIST", help=f"comma-separated subset of {','.join(ONLY_CHOICES)}") parser.add_argument("--tolerance", type=float, default=1e-5, help="spglib tolerance in Angstrom (default 1e-5)") parser.add_argument("-o", "--output", default=None, metavar="FILE", help="YAML file (default vasp_symmetry_<formula>.yaml)") return parser def main(argv=None) -> int: """``crystod --check-symmetry`` (also ``python -m crystod.vasp_symmetry``). Args: argv: Argument list (default: ``sys.argv[1:]``). Returns: Exit status 0; every user error exits with one ``ERROR:`` line. """ import sys args = build_parser().parse_args(sys.argv[1:] if argv is None else argv) if args.tolerance <= 0: raise SystemExit("ERROR: --tolerance must be positive.") report = vasp_symmetry_report(args.path, outcar=args.outcar, cell=args.cell, only=args.only, symprec=args.tolerance) print(format_vasp_symmetry(report)) output = args.output or f"vasp_symmetry_{report.reduced_formula}.yaml" existed = os.path.isfile(output) write_vasp_symmetry_yaml(report, output) print("") print("* Output files *") print(f" YAML {'OVERWRITTEN' if existed else 'written'}: {output}") return 0 if __name__ == "__main__": raise SystemExit(main())