vibe-sketcherDocumentation

Source code for vibesketcher.document.subgroup_distortion

"""Distorting a structure described in a subgroup along the freed parameters (#199).

After :func:`vibesketcher.document.symmetry_ops.descend` describes a crystal
in a subgroup H of its group G, the atoms are still where G puts them. Every
H orbit has a site-symmetry group, the operations of H that leave its
representative in place; a displacement u keeps H exactly when u is left
invariant by every one of them, u M = u (ITA Vol. A, 6th ed., Section 1.4.4:
the free coordinates of a Wyckoff position). The invariant subspace of the H
site symmetry is split into the part the detected group G already leaves
free (the parent's own free parameters: moving along it keeps G) and the
part the descent freed (moving along it lowers the symmetry towards H).

:func:`distort` takes one Cartesian displacement per H orbit, stated on the
orbit's representative site, refuses it unless it lies in that invariant
subspace, and carries it to every other member of the orbit by the operation
of H that maps the representative there (u_m = u M_g). The result is checked:
every operation of H must still map the structure onto itself, and spglib
must detect them. Cell parameters are kept; a strain H allows is not applied.

In a polar subgroup (one whose rotations leave a direction fixed, such as
P4mm with c) an equal displacement of every atom along the polar axis is a
rigid shift of the origin, not a distortion; the modes report the polar
directions so such a shift can be recognised.

Nothing here infers which distortion is physical: amplitudes are stated, and
the record lists them by orbit, split into freed and parent-free parts.
"""

from __future__ import annotations

import math
from typing import Any

import numpy as np

from vibesketcher.document import crystal
from vibesketcher.document.model import PeriodicStructure

__all__ = ["distort", "distortion_modes", "preview_distort"]

ITA_WYCKOFF = "International Tables for Crystallography Vol. A, 6th ed. (2016), Section 1.4.4"
_FIXED = 1e-6
#: The largest displacement one orbit may be given, angstrom.
MAX_DISPLACEMENT = 2.0


def _subgroup(structure: PeriodicStructure) -> tuple[dict[str, Any], list[tuple[Any, Any]]]:
    """The recorded subgroup and its operations in the structure's own basis."""
    from vibesketcher.document.spacegroups import find
    from vibesketcher.document.symmetry_ops import _float_ops, _guard

    _guard(structure, "a subgroup distortion")
    builder = crystal._builder(structure)
    if builder.get("kind") not in ("subgroup_descent", "subgroup_distortion"):
        raise ValueError(
            f"{structure.id} is not described in a subgroup: descend it first "
            "(solid descend), then distort along the parameters the descent freed"
        )
    group = builder.get("space_group")
    orbits = builder.get("orbit_of_site")
    if not isinstance(group, dict) or not isinstance(orbits, dict):
        raise ValueError(f"{structure.id} has no subgroup record to distort in")
    target = find(str(group["hall"]))
    return builder, _float_ops(target.operations())


def _maps(
    rotation: np.ndarray, translation: np.ndarray, a: np.ndarray, b: np.ndarray, tolerance: float
) -> bool:
    delta = rotation @ a + translation - b
    return bool(np.max(np.abs(delta - np.rint(delta))) < tolerance)


def _cartesian(rotation: np.ndarray, lattice: np.ndarray) -> np.ndarray:
    """M with u' = u M for a Cartesian row vector u, given R acting on fractional columns."""
    return np.asarray(np.linalg.inv(lattice) @ rotation.T @ lattice)


def _invariant(matrices: list[np.ndarray]) -> np.ndarray:
    """An orthonormal basis (rows) of the vectors u with u M = u for every M."""
    if not matrices:
        return np.eye(3)
    stacked = np.vstack([(m - np.eye(3)).T for m in matrices])
    _, singular, vt = np.linalg.svd(stacked)
    rank = int(np.sum(singular > _FIXED))
    return np.asarray(vt[rank:])


def _complement(inside: np.ndarray, kept: np.ndarray) -> np.ndarray:
    """An orthonormal basis of the part of span(inside) orthogonal to span(kept)."""
    if len(inside) == 0:
        return np.zeros((0, 3))
    projected = inside - (inside @ kept.T) @ kept if len(kept) else inside
    u, singular, _ = np.linalg.svd(projected.T, full_matrices=False)
    rank = int(np.sum(singular > _FIXED))
    return np.asarray(u[:, :rank].T)


def _site_symmetry(
    ops: list[tuple[np.ndarray, np.ndarray]],
    position: np.ndarray,
    lattice: np.ndarray,
    tolerance: float,
) -> list[np.ndarray]:
    return [_cartesian(r, lattice) for r, t in ops if _maps(r, t, position, position, tolerance)]


def _clean(vectors: np.ndarray) -> list[list[float]]:
    out = []
    for v in vectors:
        v = np.where(np.abs(v) < 1e-12, 0.0, v)
        # A deterministic sign: the first clearly nonzero component positive.
        lead = next(x for x in v if abs(x) > 1e-9)
        out.append([float(x) + 0.0 for x in (v if lead > 0 else -v)])  # no -0.0
    return out


[docs] def distortion_modes(structure: PeriodicStructure, *, symprec: float = 1e-3) -> dict[str, Any]: """Per H orbit, the displacement directions that keep H, split into freed and parent-free.""" from vibesketcher.document import symmetry builder, h_ops = _subgroup(structure) lattice = crystal.lattice_rows(structure) tolerance = symprec / float(np.linalg.norm(lattice, axis=1).min()) g_ops = symmetry.operations(structure, symprec=symprec) detected = symmetry.detect(structure, symprec=symprec) by_id = {s.id: s for s in structure.sites} roots = dict.fromkeys(builder["orbit_of_site"].values()) wyckoff = {o["site"]: o for o in builder.get("asymmetric_unit", [])} orbits = [] for root in roots: position = np.asarray(by_id[root].fractional, dtype=float) free = _invariant(_site_symmetry(h_ops, position, lattice, tolerance)) kept = _invariant(_site_symmetry(g_ops, position, lattice, tolerance)) freed = _complement(free, kept) info = wyckoff.get(root, {}) orbits.append( { "site": root, "element": by_id[root].symbol, "wyckoff": info.get("wyckoff"), "site_symmetry": info.get("site_symmetry"), "multiplicity": sum(1 for r in builder["orbit_of_site"].values() if r == root), "free_directions": _clean(free), "freed_directions": _clean(freed), "parent_free_directions": _clean(kept), } ) polar = _invariant([_cartesian(r, lattice) for r, _t in h_ops]) group = builder["space_group"] return { "structure": structure.id, "subgroup": {k: group[k] for k in ("number", "hm", "hall")}, "detected": {"number": detected["number"], "international": detected["international"]}, "orbits": orbits, "polar_directions": _clean(polar), "notes": ( [ "the subgroup is polar: an equal displacement of every atom along " + ", ".join(str([round(x, 6) for x in v]) for v in _clean(polar)) + " is a rigid shift of the origin, not a distortion" ] if len(polar) else [] ), "units": "Cartesian unit vectors (angstrom frame of the stored cell)", "references": [ITA_WYCKOFF], }
def _distort( structure: PeriodicStructure, displacements: dict[str, Any], identifier: str, symprec: float, min_distance: float, ) -> tuple[dict[str, Any], PeriodicStructure]: from vibesketcher.chem.periodic_geometry import BuildRefused, neighbour_pairs from vibesketcher.document import symmetry from vibesketcher.document.periodic_prepare import content_digest from vibesketcher.document.symmetry_ops import _permutation modes = distortion_modes(structure, symprec=symprec) builder, h_ops = _subgroup(structure) lattice = crystal.lattice_rows(structure) tolerance = symprec / float(np.linalg.norm(lattice, axis=1).min()) by_orbit = {o["site"]: o for o in modes["orbits"]} unknown = [s for s in displacements if s not in by_orbit] if unknown: raise ValueError( f"displace orbit representatives only: {', '.join(unknown)} " f"{'is' if len(unknown) == 1 else 'are'} not one of {', '.join(by_orbit)}" ) if not displacements: raise ValueError("state at least one displacement") sites = {s.id: s for s in structure.sites} positions = {s.id: np.asarray(s.fractional, dtype=float) for s in structure.sites} inverse = np.linalg.inv(lattice) rows = [] for root, raw in displacements.items(): u = np.asarray(raw, dtype=float) if u.shape != (3,) or not np.all(np.isfinite(u)): raise ValueError(f"{root}: a displacement is three finite numbers in angstrom") length = float(np.linalg.norm(u)) if length > MAX_DISPLACEMENT: raise ValueError(f"{root}: {length:.3f} angstrom exceeds the {MAX_DISPLACEMENT} limit") orbit = by_orbit[root] free = np.asarray(orbit["free_directions"]).reshape(-1, 3) inside = (u @ free.T) @ free if len(free) else np.zeros(3) if float(np.linalg.norm(u - inside)) > 1e-6: allowed = ( "along " + " and ".join(str([round(float(x), 4) for x in v]) for v in free) if len(free) else "none: the site is fixed by its site symmetry" ) raise ValueError( f"{root} ({orbit['wyckoff'] or 'its orbit'}, site symmetry " f"{orbit['site_symmetry'] or '?'}): this displacement would break " f"{modes['subgroup']['hm']}; allowed displacements: {allowed}" ) freed = np.asarray(orbit["freed_directions"]).reshape(-1, 3) kept = np.asarray(orbit["parent_free_directions"]).reshape(-1, 3) origin = np.asarray(sites[root].fractional, dtype=float) members = [s for s, r in builder["orbit_of_site"].items() if r == root] for member in members: target = np.asarray(sites[member].fractional, dtype=float) op = next(((r, t) for r, t in h_ops if _maps(r, t, origin, target, tolerance)), None) if op is None: # pragma: no cover - the descent recorded the orbit raise ValueError(f"no operation maps {root} onto {member}") moved = u @ _cartesian(op[0], lattice) positions[member] = positions[member] + moved @ inverse rows.append( { "site": root, "sites": members, "displacement_angstrom": [float(x) for x in u], "length_angstrom": length, "freed_amplitudes": [float(x) for x in (u @ freed.T)] if len(freed) else [], "parent_free_amplitudes": [float(x) for x in (u @ kept.T)] if len(kept) else [], } ) data = structure.model_dump(mode="json", exclude_none=True) data["id"] = identifier for site in data["sites"]: site["fractional"] = [float(x) for x in positions[site["id"]]] moved_structure = PeriodicStructure.model_validate(data) cartesian = np.asarray([moved_structure.cartesian(s) for s in moved_structure.sites]) close = neighbour_pairs( cartesian, lattice, moved_structure.pbc, min(min_distance, 0.49 * float(np.linalg.norm(lattice, axis=1).min())), ) if close: i, j, _, distance = close[0] raise BuildRefused( f"the displaced atoms {moved_structure.sites[i].id} and " f"{moved_structure.sites[j].id} would be {distance:.3f} angstrom apart" ) frac = np.asarray([s.fractional for s in moved_structure.sites], dtype=float) symbols = [s.symbol for s in moved_structure.sites] for rotation, translation in h_ops: # still a symmetry of the result if _permutation(frac, symbols, lattice, rotation, translation, symprec) is None: raise ValueError("internal: the displaced structure lost an operation of H") after = symmetry.detect(moved_structure, symprec=symprec) detected_ops = symmetry.operations(moved_structure, symprec=symprec) for rotation, translation in h_ops: if not any( np.allclose(rotation, r) and np.max(np.abs(translation - t - np.rint(translation - t))) < 1e-3 for r, t in detected_ops ): raise ValueError( # pragma: no cover - the permutation check above passed "spglib does not detect an operation of H after the distortion; lower symprec" ) lowered = len(detected_ops) < len(symmetry.operations(structure, symprec=symprec)) record = { "kind": "subgroup_distortion", "source": structure.id, "source_sha256": content_digest(structure), "subgroup": modes["subgroup"], "detected_before": modes["detected"], "detected_after": {"number": after["number"], "international": after["international"]}, "symmetry_lowered": lowered, "orbits": rows, "cell": "kept; a strain the subgroup allows is not applied", "verified_by_detection": True, "symprec_angstrom": symprec, "notes": ( [] if lowered else [ "the displacements keep the detected group: they move only along the parent's " "own free parameters" ] ) + modes["notes"], "references": [ITA_WYCKOFF], } distorted_builder = { **builder, "kind": "subgroup_distortion", "distortion": record, "asymmetric_unit": [ {**o, "fractional": [float(x) for x in positions[o["site"]]]} for o in builder.get("asymmetric_unit", []) ], } provenance = {k: v for k, v in structure.provenance.items() if k != "derived_sha256"} provenance["builder"] = crystal._json(distorted_builder) result = moved_structure.model_copy(update={"provenance": provenance}) return crystal._json({**record, "identifier": identifier}), result
[docs] def preview_distort( structure: PeriodicStructure, *, displacements: dict[str, Any], symprec: float = 1e-3, min_distance: float = 0.7, ) -> dict[str, Any]: """The distortion record, the detected group after it, or a refusal; nothing stored.""" record, _ = _distort(structure, displacements, "preview", symprec, min_distance) return record
[docs] def distort( structure: PeriodicStructure, *, displacements: dict[str, Any], identifier: str, symprec: float = 1e-3, min_distance: float = 0.7, ) -> PeriodicStructure: """A new structure: ``structure`` with each stated orbit displaced, keeping H.""" from vibesketcher.document.symmetry_ops import stamp if not math.isfinite(symprec) or not 0 < symprec <= 1: raise ValueError("symprec is a length tolerance between 0 and 1 angstrom") _, result = _distort(structure, displacements, identifier, symprec, min_distance) return stamp(result)