vibe-sketcherDocumentation
Source code for vibesketcher.document.symmetry_ops
"""Adopting detected symmetry, enantiomorphs and subgroup descent (#199).
Three edits on fully ordered, non-magnetic 3-D crystals, each previewed
first and recorded so it can be undone:
* :func:`adopt` records the space group spglib detects at a stated length
tolerance as the structure's adopted symmetry. By default nothing moves (no
snapping); the preview reports how far symmetrisation would move every atom
and cell vector, which orbits merge or split against the previously
recorded orbits, and sites near a special position at a looser diagnostic
tolerance. ``idealize=True`` applies the symmetrisation explicitly: atom
positions are projected onto the group (the Reynolds average over the
operations) and the metric tensor is averaged, G' = <R^T G R>, keeping the
cell's orientation (W. Kabsch, Acta Cryst. A32, 922 (1976)).
* :func:`enantiomorph` inverts a chiral structure through the origin and
transforms its group: (R, t) -> (R, -t). The 11 enantiomorphic pairs of
space-group types (P3_1 21 <-> P3_2 21, ...) change type; the other Sohncke
groups keep theirs. Achiral structures, and structures that are achiral
within the diagnostic tolerance (ambiguous handedness), are refused.
* :func:`descend` re-describes a structure in a subgroup H of its group G
given an explicit setting transformation (P, p) and H's Hall symbol. Every
operation of H must map the structure in the new basis onto itself, and
spglib must detect each of them; the index, its translationengleiche and
klassengleiche parts and the splitting of every Wyckoff orbit are reported.
By Hermann's theorem a maximal subgroup is either t or k, so a descent
that is neither is refused; automatic enumeration of the maximal subgroups
is a later stage and is refused.
Settings, subgroups and normalisers follow International Tables for
Crystallography Vol. A (6th ed., 2016), Sections 1.5 (transformations of the
coordinate system), 1.7 (subgroups; Hermann's theorem) and 3.5 (Euclidean
normalisers, enantiomorphic pairs).
Measured anisotropic displacement tensors, when a structure carries them in
``provenance["displacement_parameters"]``, are co-transformed: U_cart ->
R_c U_cart R_c^T (R. W. Grosse-Kunstleve and P. D. Adams, J. Appl. Cryst. 35,
477 (2002)). A convention that cannot be converted, or a tensor that cannot
be carried (e.g. equivalent atoms with and without one), is refused, never
dropped.
"""
from __future__ import annotations
import math
import re
from fractions import Fraction
from typing import Any
import numpy as np
from vibesketcher.document import crystal
from vibesketcher.document.model import Document, PeriodicBond, PeriodicStructure
ITA = "International Tables for Crystallography Vol. A, 6th ed. (2016), Sections 1.5, 1.7 and 3.5"
KABSCH = "W. Kabsch, Acta Cryst. A32, 922 (1976)"
ADP_REFERENCE = "R. W. Grosse-Kunstleve and P. D. Adams, J. Appl. Cryst. 35, 477 (2002)"
ADP_KEY = "displacement_parameters"
RECORD = "symmetry_edit"
MAX_SITES = 3000
#: The 11 enantiomorphic pairs of space-group types (ITA Vol. A, Section 3.5).
ENANTIOMORPHS: dict[int, int] = {}
for _a, _b in ((76, 78), (91, 95), (92, 96), (144, 145), (151, 153), (152, 154), (169, 170),
(171, 172), (178, 179), (180, 181), (212, 213)): # fmt: skip
ENANTIOMORPHS[_a], ENANTIOMORPHS[_b] = _b, _a
#: Displacement-tensor conventions that can be converted to Cartesian U.
CONVENTIONS = ("U_cart", "U_cif", "B_cif", "U_star", "beta")
_MAGNETIC_CIF = re.compile(
r"_(atom_site_moment|space_group_magn|space_group_symop_magn|parent_space_group|"
r"atom_site_magnetic)",
re.IGNORECASE,
)
# --- guards -------------------------------------------------------------------------
def _guard(structure: PeriodicStructure, what: str) -> None:
if structure.pbc != (True, True, True):
raise ValueError(f"{what} applies to three-dimensional crystals")
unresolved = [s.id for s in structure.sites if s.occupancy != 1 or s.disorder_group]
if unresolved:
raise ValueError(
f"{what} needs an ordered crystal; unresolved disorder on "
f"{', '.join(unresolved[:8])}: resolve it first (CIF import disorder policy)"
)
if len(structure.sites) > MAX_SITES:
raise ValueError(f"{what} is limited to {MAX_SITES} sites")
if _magnetic(structure):
raise ValueError(
f"{what} refuses magnetic structures: magnetic (Shubnikov) symmetry is not "
"modelled, and a crystallographic operation would drop or mis-transform the moments"
)
def _magnetic(structure: PeriodicStructure) -> bool:
keys = set(structure.provenance) | set(crystal._builder(structure))
if any(k.lower().startswith("magnetic") or k.lower() in ("moments", "spins") for k in keys):
return True
return bool(structure.source_cif and _MAGNETIC_CIF.search(structure.source_cif))
# --- displacement tensors -----------------------------------------------------------
def _basis(lattice: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""A (columns a, b, c) and N = diag(|a*|, |b*|, |c*|)."""
a = lattice.T
reciprocal = np.linalg.inv(lattice).T # rows a*, b*, c* with a_i . a*_j = delta_ij
return a, np.diag(np.linalg.norm(reciprocal, axis=1))
def _tensor(value: Any, site: str) -> np.ndarray:
array = np.asarray(value, dtype=float)
if array.shape == (6,):
u11, u22, u33, u12, u13, u23 = array
array = np.asarray([[u11, u12, u13], [u12, u22, u23], [u13, u23, u33]])
if array.shape != (3, 3) or not np.isfinite(array).all():
raise ValueError(f"displacement tensor of {site} must be 6 numbers (U11 U22 U33 U12 U13 "
"U23) or a 3x3 matrix") # fmt: skip
if not np.allclose(array, array.T, atol=1e-12):
raise ValueError(f"displacement tensor of {site} is not symmetric")
return array
[docs]
def to_cartesian(tensor: np.ndarray, convention: str, lattice: np.ndarray) -> np.ndarray:
"""U_cart (angstrom^2) of one tensor in ``convention`` for rows ``lattice``."""
a, n = _basis(lattice)
if convention == "U_cart":
return tensor
if convention in ("U_cif", "B_cif"):
u_cif = tensor / (8 * math.pi**2) if convention == "B_cif" else tensor
return np.asarray(a @ n @ u_cif @ n @ a.T)
if convention in ("U_star", "beta"):
u_star = tensor / (2 * math.pi**2) if convention == "beta" else tensor
return np.asarray(a @ u_star @ a.T)
raise ValueError(
f"displacement convention {convention!r} cannot be transformed; use one of "
f"{', '.join(CONVENTIONS)}"
)
[docs]
def from_cartesian(tensor: np.ndarray, convention: str, lattice: np.ndarray) -> np.ndarray:
a, n = _basis(lattice)
u_star = np.linalg.inv(a) @ tensor @ np.linalg.inv(a).T
if convention == "U_cart":
return tensor
if convention == "U_star":
return np.asarray(u_star)
if convention == "beta":
return np.asarray(2 * math.pi**2 * u_star)
u_cif = np.linalg.inv(n) @ u_star @ np.linalg.inv(n)
return np.asarray(8 * math.pi**2 * u_cif if convention == "B_cif" else u_cif)
[docs]
def displacement_tensors(structure: PeriodicStructure) -> tuple[str, dict[str, np.ndarray]] | None:
"""(convention, {site: U_cart}) of the structure's recorded tensors, or None."""
record = structure.provenance.get(ADP_KEY)
if record is None:
return None
sites = record.get("sites") if isinstance(record, dict) else None
if not isinstance(record, dict) or not isinstance(sites, dict):
raise ValueError(f"provenance {ADP_KEY!r} needs 'convention' and a 'sites' object")
convention = str(record.get("convention", ""))
if convention not in CONVENTIONS:
raise ValueError(
f"displacement convention {convention!r} cannot be transformed; refused rather "
f"than dropped (use one of {', '.join(CONVENTIONS)})"
)
ids = {s.id for s in structure.sites}
lattice = crystal.lattice_rows(structure)
out = {}
for site, value in sites.items():
if site not in ids:
raise ValueError(f"displacement tensor for unknown site {site!r}")
out[site] = to_cartesian(_tensor(value, site), convention, lattice)
return convention, out
def _six(tensor: np.ndarray) -> list[float]:
t = tensor
return [crystal._clean(float(x)) for x in (t[0, 0], t[1, 1], t[2, 2], t[0, 1], t[0, 2],
t[1, 2])] # fmt: skip
def _adp_record(
structure: PeriodicStructure, convention: str, tensors: dict[str, np.ndarray], how: str
) -> dict[str, Any]:
previous = structure.provenance.get(ADP_KEY)
base: dict[str, Any] = dict(previous) if isinstance(previous, dict) else {}
lattice = crystal.lattice_rows(structure)
base.update(
convention=convention,
sites={k: _six(from_cartesian(v, convention, lattice)) for k, v in tensors.items()},
transformed=how,
reference=ADP_REFERENCE,
cell_angstrom=[[float(x) for x in row] for row in lattice],
)
return crystal._json(base) # type: ignore[no-any-return]
def _cartesian_rotation(rotation: np.ndarray, lattice: np.ndarray) -> np.ndarray:
a = lattice.T
return np.asarray(a @ rotation @ np.linalg.inv(a))
# --- operations and mappings --------------------------------------------------------
def _wrap(delta: np.ndarray) -> np.ndarray:
return np.asarray(delta - np.round(delta))
def _permutation(
frac: np.ndarray, symbols: list[str], lattice: np.ndarray,
rotation: np.ndarray, translation: np.ndarray, tolerance: float,
) -> tuple[np.ndarray, np.ndarray] | None: # fmt: skip
"""j and the lift x_j + n nearest g(x_i) for every i, or None if g is not a symmetry."""
images = frac @ rotation.T + translation
targets = np.empty_like(images)
perm = np.empty(len(frac), dtype=int)
by_element: dict[str, np.ndarray] = {}
for symbol in set(symbols):
by_element[symbol] = np.asarray([k for k, s in enumerate(symbols) if s == symbol])
for i, image in enumerate(images):
candidates = by_element[symbols[i]]
delta = _wrap(frac[candidates] - image)
distance = np.linalg.norm(delta @ lattice, axis=1)
best = int(np.argmin(distance))
if distance[best] > tolerance:
return None
perm[i] = candidates[best]
targets[i] = image + delta[best]
return perm, targets
def _float_ops(operations: list[Any]) -> list[tuple[np.ndarray, np.ndarray]]:
return [(np.asarray(op.rotation, dtype=float),
np.asarray([float(x) for x in op.translation])) for op in operations] # fmt: skip
def _as_operation(rotation: np.ndarray, translation: np.ndarray) -> Any:
from vibesketcher.document.spacegroups import Operation
r = tuple(tuple(int(round(x)) for x in row) for row in rotation)
t = tuple(Fraction(float(x)).limit_denominator(48) % 1 for x in translation)
return Operation(r, t) # type: ignore[arg-type]
def _tabulated_setting(number: int, operations: list[Any]) -> Any:
"""The tabulated Hall setting whose operations equal these (same basis), if any."""
from vibesketcher.document.spacegroups import settings
wanted = {op.key() for op in operations}
for setting in settings():
if setting.number == number and {o.key() for o in setting.operations()} == wanted:
return setting
return None
def _orbits_from(perms: list[np.ndarray], count: int) -> list[int]:
"""Representative (smallest index) of every site's orbit."""
parent = list(range(count))
def root(i: int) -> int:
while parent[i] != i:
parent[i] = parent[parent[i]]
i = parent[i]
return i
for perm in perms:
for i, j in enumerate(perm):
a, b = root(i), root(int(j))
if a != b:
parent[max(a, b)] = min(a, b)
return [root(i) for i in range(count)]
def _previous_orbits(structure: PeriodicStructure) -> tuple[str, dict[str, str]]:
"""The orbits the structure records already: an adopted group, a builder's orbits or P1."""
record = structure.provenance.get(RECORD)
recorded = record.get("orbit_of_site") if isinstance(record, dict) else None
if isinstance(recorded, dict):
return "adopted symmetry", {str(k): str(v) for k, v in recorded.items()}
builder = crystal._builder(structure)
orbit_of = builder.get("orbit_of_site")
ids = [s.id for s in structure.sites]
if isinstance(orbit_of, dict) and set(orbit_of) == set(ids):
return "builder orbits", {str(k): str(v) for k, v in orbit_of.items()}
return "P1 (no recorded orbits)", {i: i for i in ids}
def _group_by(mapping: dict[str, str]) -> dict[str, set[str]]:
groups: dict[str, set[str]] = {}
for site, orbit in mapping.items():
groups.setdefault(orbit, set()).add(site)
return groups
# --- adoption -----------------------------------------------------------------------
def _symmetrised(
structure: PeriodicStructure, symprec: float
) -> tuple[dict[str, Any], np.ndarray, np.ndarray, list[np.ndarray], list[tuple[Any, Any]]]:
from vibesketcher.document import symmetry
ops = symmetry.operations(structure, symprec=symprec)
lattice = crystal.lattice_rows(structure)
frac = np.asarray([s.fractional for s in structure.sites], dtype=float)
symbols = [s.symbol for s in structure.sites]
perms, estimates = [], []
for rotation, translation in ops:
found = _permutation(frac, symbols, lattice, rotation, translation, 3 * symprec + 1e-9)
if found is None: # pragma: no cover - spglib accepted the operation at symprec
raise ValueError("a detected operation does not map the atoms; lower symprec")
perms.append(found[0])
# g^-1 applied to the lift of x_perm(i) nearest g(x_i) estimates x_i (Reynolds average).
estimates.append((found[1] - translation) @ np.linalg.inv(rotation).T)
ideal_frac = np.mean(estimates, axis=0)
metric = lattice @ lattice.T
ideal_metric = np.mean([r.T @ metric @ r for r, _t in ops], axis=0)
detected = symmetry.detect(structure, symprec=symprec)
return detected, ideal_frac, _oriented(ideal_metric, lattice), perms, ops
def _oriented(metric: np.ndarray, lattice: np.ndarray) -> np.ndarray:
"""Rows with this metric, rotated onto ``lattice`` (Kabsch 1976)."""
rows = np.linalg.cholesky(metric)
u, _s, vt = np.linalg.svd(rows.T @ lattice)
d = np.sign(np.linalg.det(u @ vt))
q = u @ np.diag([1.0, 1.0, d]) @ vt
return np.asarray(rows @ q)
[docs]
def preview_adopt(
structure: PeriodicStructure,
*,
symprec: float = 1e-3,
idealize: bool = False,
diagnostic_symprec: float = 0.1,
) -> dict[str, Any]:
"""What adopting the detected group would record and move; changes nothing."""
from vibesketcher.document import symmetry
from vibesketcher.document.periodic_prepare import content_digest
_guard(structure, "adopting symmetry")
if not 0 < symprec < diagnostic_symprec <= 1:
raise ValueError("need 0 < symprec < diagnostic_symprec <= 1 angstrom")
detected, ideal_frac, ideal_lattice, perms, ops = _symmetrised(structure, symprec)
lattice = crystal.lattice_rows(structure)
frac = np.asarray([s.fractional for s in structure.sites], dtype=float)
ids = [s.id for s in structure.sites]
moved = ideal_frac @ ideal_lattice - frac @ lattice
moved -= moved.mean(axis=0) # a rigid translation is not a displacement
displacement = np.linalg.norm(moved, axis=1)
roots = _orbits_from(perms, len(ids))
orbit_of = {ids[i]: ids[r] for i, r in enumerate(roots)}
detected_sites = {s["site"]: s for s in detected["sites"]}
orbits = []
for root, members in sorted(_group_by(orbit_of).items(), key=lambda kv: ids.index(kv[0])):
info = detected_sites[root]
orbits.append({"orbit": root, "element": info["symbol"], "wyckoff": info["wyckoff"],
"site_symmetry": info["site_symmetry"],
"sites": sorted(members, key=ids.index)}) # fmt: skip
source, previous = _previous_orbits(structure)
merges, splits = _merges_and_splits(previous, orbit_of, ids)
# Near-special positions: the site symmetry grows at the looser tolerance.
near: list[dict[str, Any]] = []
loose_group: dict[str, Any] | None = None
try:
loose = symmetry.detect(structure, symprec=diagnostic_symprec)
except ValueError: # pragma: no cover
loose = None
if loose is not None:
loose_sites = {s["site"]: s for s in loose["sites"]}
for sid in ids:
tight = detected_sites[sid]["site_symmetry"]
wide = loose_sites[sid]["site_symmetry"]
if tight != wide:
near.append({"site": sid, "site_symmetry": tight,
"site_symmetry_at_diagnostic_tolerance": wide,
"snapped": False}) # fmt: skip
if loose["number"] != detected["number"]:
loose_group = {"number": loose["number"], "international": loose["international"],
"symprec_angstrom": diagnostic_symprec} # fmt: skip
as_ops = [_as_operation(r, t) for r, t in ops]
tabulated = _tabulated_setting(int(detected["number"]), as_ops)
params_before = _parameters(lattice)
params_after = _parameters(ideal_lattice)
tensors = displacement_tensors(structure)
if tensors is not None and idealize:
_symmetrise_tensors(structure, tensors[1], perms, ops) # refuses if it cannot
return {
"structure": structure.id,
"source_sha256": content_digest(structure),
"space_group": {
k: detected[k]
for k in (
"number",
"international",
"hall",
"hall_number",
"choice",
"point_group",
"crystal_system",
)
},
"setting": {
"tabulated": tabulated.symbol if tabulated else None,
"hall": tabulated.hall if tabulated else None,
"to_standard": {
"P": detected["transformation_matrix"],
"p": detected["origin_shift"],
"convention": "spglib: x_s = P x + p",
},
}, # fmt: skip
"operations": [op.triplet() for op in as_ops],
"symprec_angstrom": symprec,
"orbits": orbits,
"independent_sites": {
"before": len(set(previous.values())),
"after": len(orbits),
"previous_orbits_from": source,
}, # fmt: skip
"merges": merges,
"splits": splits,
"idealize": idealize,
"displacements_angstrom": {
sid: float(d) for sid, d in zip(ids, displacement, strict=True)
}, # fmt: skip
"largest_displacement_angstrom": float(displacement.max()),
"cell_change": {
"before": params_before,
"after": params_after,
"largest_vector_change_angstrom": float(
np.max(np.linalg.norm(ideal_lattice - lattice, axis=1))
),
},
"applied_displacement_angstrom": float(displacement.max()) if idealize else 0.0,
"near_special_positions": near,
"diagnostic_symprec_angstrom": diagnostic_symprec,
"higher_group_at_diagnostic_tolerance": loose_group,
"displacement_tensors": "none"
if tensors is None
else ("symmetrised" if idealize else "kept"),
"references": [symmetry.REFERENCE, ITA, KABSCH],
}
def _parameters(lattice: np.ndarray) -> dict[str, float]:
from vibesketcher.document.bilbao import crystal_parameters
probe = PeriodicStructure.model_validate(
{"id": "probe", "lattice_angstrom": lattice.tolist(),
"sites": [{"id": "X1", "symbol": "H", "fractional": (0.0, 0.0, 0.0)}]}
) # fmt: skip
values = crystal_parameters(probe)
return dict(zip(("a", "b", "c", "alpha", "beta", "gamma"), values, strict=True))
def _merges_and_splits(
previous: dict[str, str], current: dict[str, str], ids: list[str]
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
merges = []
for orbit, members in sorted(_group_by(current).items(), key=lambda kv: ids.index(kv[0])):
parents = sorted({previous[m] for m in members})
if len(parents) > 1:
merges.append({"orbit": orbit, "from": parents})
splits = []
for orbit, members in sorted(_group_by(previous).items()):
children = sorted({current[m] for m in members}, key=ids.index)
if len(children) > 1:
splits.append({"orbit": orbit, "into": children})
return merges, splits
def _symmetrise_tensors(
structure: PeriodicStructure, tensors: dict[str, np.ndarray],
perms: list[np.ndarray], ops: list[tuple[Any, Any]],
) -> dict[str, np.ndarray]: # fmt: skip
lattice = crystal.lattice_rows(structure)
ids = [s.id for s in structure.sites]
out = {}
for i, sid in enumerate(ids):
images = [ids[int(perm[i])] for perm in perms]
have = [s in tensors for s in images]
if not any(have) and sid not in tensors:
continue
if not all(have):
missing = sorted({s for s, h in zip(images, have, strict=True) if not h})
raise ValueError(
f"cannot symmetrise displacement tensors: {sid} is equivalent to "
f"{', '.join(missing)}, which carry none; refused rather than dropped"
)
estimates = []
for (rotation, _t), perm in zip(ops, perms, strict=True):
rc_inverse = np.linalg.inv(_cartesian_rotation(rotation, lattice))
estimates.append(rc_inverse @ tensors[ids[int(perm[i])]] @ rc_inverse.T)
out[sid] = np.mean(estimates, axis=0)
return out
[docs]
def adopt(
structure: PeriodicStructure,
*,
symprec: float = 1e-3,
idealize: bool = False,
diagnostic_symprec: float = 0.1,
source_sha256: str | None = None,
) -> PeriodicStructure:
"""The structure with the detected group recorded as adopted; same ID, undoable.
Without ``idealize`` no coordinate changes. ``source_sha256`` (from the
preview) refuses the adoption when the structure changed since.
"""
from vibesketcher.document.periodic_prepare import content_digest
if source_sha256 is not None and source_sha256 != content_digest(structure):
raise ValueError("the structure changed since the preview; preview again")
report = preview_adopt(structure, symprec=symprec, idealize=idealize,
diagnostic_symprec=diagnostic_symprec) # fmt: skip
data = structure.model_dump(mode="json", exclude_none=True)
provenance = dict(structure.provenance)
before: dict[str, Any] = {"symmetry_edit": provenance.get(RECORD), ADP_KEY: provenance.get(
ADP_KEY)} # fmt: skip
if idealize:
detected, ideal_frac, ideal_lattice, perms, ops = _symmetrised(structure, symprec)
before["lattice_angstrom"] = [list(r) for r in structure.lattice_angstrom]
before["fractional"] = {s.id: list(s.fractional) for s in structure.sites}
data["lattice_angstrom"] = [[float(x) for x in row] for row in ideal_lattice]
for site, f in zip(data["sites"], ideal_frac, strict=True):
site["fractional"] = [crystal._clean(x) for x in f]
tensors = displacement_tensors(structure)
if tensors is not None:
symmetrised = _symmetrise_tensors(structure, tensors[1], perms, ops)
probe = PeriodicStructure.model_validate({**data, "provenance": {}})
provenance[ADP_KEY] = _adp_record(probe, tensors[0], {**tensors[1], **symmetrised},
"symmetrised over the adopted group") # fmt: skip
orbit_of = {s: o["orbit"] for o in report["orbits"] for s in o["sites"]}
record = {
"kind": "adopted",
**{k: report[k] for k in ("space_group", "setting", "operations", "symprec_angstrom",
"idealize", "merges", "splits", "near_special_positions",
"largest_displacement_angstrom", "applied_displacement_angstrom",
"references")},
"orbits": report["orbits"],
"orbit_of_site": orbit_of,
"before": before,
} # fmt: skip
provenance[RECORD] = record
data["provenance"] = provenance
adopted = PeriodicStructure.model_validate(data)
record["result_sha256"] = content_digest(adopted)
provenance[RECORD] = crystal._json(record)
return adopted.model_copy(update={"provenance": provenance})
# --- enantiomorph -------------------------------------------------------------------
def _group_info(structure: PeriodicStructure, symprec: float) -> dict[str, Any]:
from vibesketcher.document import symmetry
report = symmetry.detect(structure, symprec=symprec)
return {k: report[k] for k in ("number", "international", "hall", "point_group")}
[docs]
def preview_enantiomorph(
structure: PeriodicStructure, *, symprec: float = 1e-3, diagnostic_symprec: float = 0.1
) -> dict[str, Any]:
"""The inverted structure's group and record, or a refusal (ValueError)."""
record, _inverted = _enantiomorph(structure, "preview", symprec, diagnostic_symprec)
return record
[docs]
def enantiomorph(
structure: PeriodicStructure,
*,
identifier: str,
symprec: float = 1e-3,
diagnostic_symprec: float = 0.1,
) -> PeriodicStructure:
"""The mirror-image crystal (inversion through the origin) with its group transformed."""
_record, inverted = _enantiomorph(structure, identifier, symprec, diagnostic_symprec)
return stamp(inverted)
def _enantiomorph(
structure: PeriodicStructure, identifier: str, symprec: float, diagnostic_symprec: float
) -> tuple[dict[str, Any], PeriodicStructure]:
from vibesketcher.document import symmetry
from vibesketcher.document.periodic_prepare import content_digest
_guard(structure, "changing the enantiomorph")
if not 0 < symprec < diagnostic_symprec <= 1:
raise ValueError("need 0 < symprec < diagnostic_symprec <= 1 angstrom")
ops = symmetry.operations(structure, symprec=symprec)
before = _group_info(structure, symprec)
if any(np.linalg.det(r) < 0 for r, _t in ops):
raise ValueError(
f"{structure.id} is achiral ({before['international']} contains improper "
"operations): inversion gives the same structure, so it has no handedness to change"
)
loose_ops = symmetry.operations(structure, symprec=diagnostic_symprec)
if any(np.linalg.det(r) < 0 for r, _t in loose_ops):
loose = _group_info(structure, diagnostic_symprec)
raise ValueError(
f"the handedness of {structure.id} is ambiguous: within {diagnostic_symprec:g} A "
f"it is achiral ({loose['international']}); idealise or check the structure first"
)
frac = np.asarray([s.fractional for s in structure.sites], dtype=float)
new_frac = (-frac) % 1.0
new_frac[np.isclose(new_frac, 1.0, atol=1e-12)] = 0.0
shift = np.rint(new_frac + frac).astype(int) # x' = -x + k
index = {s.id: i for i, s in enumerate(structure.sites)}
data = structure.model_dump(mode="json", exclude_none=True)
data["id"] = identifier
for site, f in zip(data["sites"], new_frac, strict=True):
site["fractional"] = [crystal._clean(x) for x in f]
site.pop("parent_site", None)
site.pop("image", None)
for bond in data["bonds"]:
n = np.asarray(bond.get("image", (0, 0, 0)), dtype=int)
new = -n - shift[index[bond["b"]]] + shift[index[bond["a"]]]
bond["image"] = [int(x) for x in new]
data.pop("parent", None)
data.pop("supercell_matrix", None)
transformed = [(r, (-t) % 1.0) for r, t in ops]
expected = ENANTIOMORPHS.get(int(before["number"]), int(before["number"]))
builder = {
"kind": "enantiomorph",
"source": structure.id,
"source_sha256": content_digest(structure),
"operation": "inversion through the origin, x -> -x",
"space_group_before": before,
"operations_after": [_as_operation(r, t).triplet() for r, t in transformed],
"enantiomorphic_pair": int(before["number"]) in ENANTIOMORPHS,
"site_map": {s.id: s.id for s in structure.sites},
"symprec_angstrom": symprec,
"notes": ["the absolute structure is reversed: a Flack parameter of the source no "
"longer applies"],
"references": [ITA],
} # fmt: skip
provenance: dict[str, Any] = {"builder": builder}
for key in ("format", "cif_label_of_site"):
if key in structure.provenance:
provenance[key] = structure.provenance[key]
tensors = displacement_tensors(structure)
data["provenance"] = {}
data.pop("source_cif", None)
data.pop("source_model_sha256", None)
inverted = PeriodicStructure.model_validate(data)
if tensors is not None:
# Inversion: R_c = -1, so U_cart -> (-1) U (-1)^T = U.
provenance[ADP_KEY] = _adp_record(inverted, tensors[0], tensors[1],
"inversion (U unchanged)") # fmt: skip
after = _group_info(inverted, symprec)
if after["number"] != expected: # pragma: no cover - a group-theoretical identity
raise ValueError(f"inversion gave {after['international']}, expected No. {expected}")
detected = {(tuple(np.rint(r).astype(int).ravel()), tuple(np.round(t % 1.0, 4) % 1.0))
for r, t in symmetry.operations(inverted, symprec=symprec)} # fmt: skip
claimed = {(tuple(np.rint(r).astype(int).ravel()), tuple(np.round(t % 1.0, 4) % 1.0))
for r, t in transformed} # fmt: skip
builder["space_group_after"] = after
builder["operations_verified_by_detection"] = claimed == detected
provenance["builder"] = crystal._json(builder)
result = inverted.model_copy(update={"provenance": provenance})
record = {**builder, "identifier": identifier, "sites": len(result.sites)}
return crystal._json(record), result
# --- subgroup descent ---------------------------------------------------------------
[docs]
def enumerate_maximal_subgroups(*_args: Any, **_kwargs: Any) -> None:
"""Refused: automatic enumeration of maximal subgroups is a later stage (#199)."""
raise ValueError(
"automatic enumeration of maximal subgroups is not qualified yet (a later stage); "
"give the transformation (P, p) and the subgroup's Hall symbol, e.g. from ITA Vol. A1 "
"or the Bilbao Crystallographic Server's MAXSUB listing"
)
def _source_map(
source: PeriodicStructure, new: PeriodicStructure, tolerance: float
) -> list[tuple[int, np.ndarray]]:
"""Each new site's source site and the source-lattice translation between them."""
lattice = crystal.lattice_rows(source)
inverse = np.linalg.inv(lattice)
frac = np.asarray([s.fractional for s in source.sites], dtype=float)
symbols = [s.symbol for s in source.sites]
out = []
for site, r in zip(new.sites, crystal.cartesian(new), strict=True):
f = r @ inverse
delta = _wrap(frac - f)
distance = np.linalg.norm(delta @ lattice, axis=1)
distance[[s != site.symbol for s in symbols]] = np.inf
best = int(np.argmin(distance))
if distance[best] > tolerance: # pragma: no cover - transform_setting kept the atoms
raise ValueError(f"new site {site.id} has no source atom")
out.append((best, np.rint(f - frac[best])))
return out
def _carry_bonds(
source: PeriodicStructure, new: PeriodicStructure, mapping: list[tuple[int, np.ndarray]],
tolerance: float,
) -> list[dict[str, Any]]: # fmt: skip
"""The source's bonds on the new sites, each once."""
if not source.bonds:
return []
src_lattice = crystal.lattice_rows(source)
new_lattice = crystal.lattice_rows(new)
new_inverse = np.linalg.inv(new_lattice)
src_frac = np.asarray([s.fractional for s in source.sites], dtype=float)
new_frac = np.asarray([s.fractional for s in new.sites], dtype=float)
src_ids = [s.id for s in source.sites]
by_source: dict[int, list[tuple[PeriodicBond, int, np.ndarray]]] = {}
for bond in source.bonds:
a, b = src_ids.index(bond.a), src_ids.index(bond.b)
n = np.asarray(bond.image, dtype=float)
by_source.setdefault(a, []).append((bond, b, n))
by_source.setdefault(b, []).append((bond, a, -n))
seen: set[tuple[str, str, tuple[int, ...]]] = set()
out = []
for i, (src, _shift) in enumerate(mapping):
start = new_frac[i] @ new_lattice
for bond, partner, n in by_source.get(src, []):
vector = (src_frac[partner] + n - src_frac[src]) @ src_lattice
target = (start + vector) @ new_inverse
delta = _wrap(new_frac - target)
distance = np.linalg.norm(delta @ new_lattice, axis=1)
j = int(np.argmin(distance))
if distance[j] > tolerance: # pragma: no cover
raise ValueError(f"bond {bond.a}-{bond.b} has no partner in the new cell")
image = np.rint(target - new_frac[j]).astype(int)
key = (new.sites[i].id, new.sites[j].id, tuple(int(x) for x in image))
reverse = (key[1], key[0], tuple(-x for x in key[2]))
if key in seen or reverse in seen:
continue
seen.add(key)
data = bond.model_dump(mode="json", exclude_none=True)
data.update(a=key[0], b=key[1], image=list(key[2]))
out.append(data)
return out
[docs]
def descend(
structure: PeriodicStructure,
*,
transformation: str,
subgroup: str,
identifier: str,
symprec: float = 1e-3,
) -> PeriodicStructure:
"""The structure described in subgroup ``subgroup`` of its group in basis (a,b,c)P, origin p."""
_record, result = _descend(structure, transformation, subgroup, identifier, symprec)
return stamp(result)
[docs]
def preview_descend(
structure: PeriodicStructure, *, transformation: str, subgroup: str, symprec: float = 1e-3
) -> dict[str, Any]:
record, _result = _descend(structure, transformation, subgroup, "preview", symprec)
return record
def _descend(
structure: PeriodicStructure, transformation: str, subgroup: str, identifier: str,
symprec: float,
) -> tuple[dict[str, Any], PeriodicStructure]: # fmt: skip
from vibesketcher.document import symmetry, wyckoff
from vibesketcher.document.bilbao import parse_transformation, transform_setting
from vibesketcher.document.periodic_prepare import content_digest
from vibesketcher.document.spacegroups import find
_guard(structure, "subgroup descent")
if not 0 < symprec <= 1:
raise ValueError("symprec is a length tolerance between 0 and 1 angstrom")
target = find(subgroup)
p_matrix, p_shift = parse_transformation(transformation)
parent_report = symmetry.detect(structure, symprec=symprec)
parent_ops = symmetry.operations(structure, symprec=symprec)
described = transform_setting(structure, transformation, identifier=identifier,
tolerance=symprec) # fmt: skip
lattice = crystal.lattice_rows(described)
frac = np.asarray([s.fractional for s in described.sites], dtype=float)
symbols = [s.symbol for s in described.sites]
h_ops = _float_ops(target.operations())
perms = []
refused = []
for (rotation, translation), op in zip(h_ops, target.operations(), strict=True):
found = _permutation(frac, symbols, lattice, rotation, translation, symprec)
if found is None:
refused.append(op.triplet())
else:
perms.append(found[0])
if refused:
raise ValueError(
f"{target.symbol} in the setting {transformation!r} is not a subgroup of "
f"{parent_report['international']} for this structure: "
f"{len(refused)} of its operations ({', '.join(refused[:4])}) are not symmetries"
)
# Verified by detection: spglib finds every operation of H in the new basis.
detected_ops = symmetry.operations(described, symprec=symprec)
for rotation, translation in h_ops:
if not any(np.allclose(rotation, r) and np.max(np.abs(_wrap(translation - t))) < 1e-3
for r, t in detected_ops): # fmt: skip
raise ValueError( # pragma: no cover - the permutation check above passed
"spglib does not detect an operation of the subgroup; lower symprec"
)
det = float(np.linalg.det(p_matrix))
index_value = len(parent_ops) * det / len(h_ops)
index = int(round(index_value))
if abs(index_value - index) > 1e-6 or index < 1:
raise ValueError(f"the index |G|/|H| = {index_value:g} is not an integer")
if index == 1:
raise ValueError(
f"{target.symbol} is the full group of this structure in that setting, not a proper "
"subgroup; use a setting transformation instead"
)
t_index_value = len({tuple(r.ravel()) for r, _t in parent_ops}) / len(
{tuple(r.ravel()) for r, _t in h_ops}
)
t_index = int(round(t_index_value))
k_index = index // t_index if t_index else 0
if t_index * k_index != index: # pragma: no cover
raise ValueError("inconsistent t and k indices")
if t_index > 1 and k_index > 1:
raise ValueError(
f"{target.symbol} is a general subgroup of index {index} (t {t_index}, k {k_index}); "
"by Hermann's theorem a maximal subgroup is either translationengleiche or "
"klassengleiche: descend in maximal steps"
)
kind = "translationengleiche" if k_index == 1 else "klassengleiche"
maximal = "yes (prime index)" if _prime(index) else (
"not verified (composite index: check ITA Vol. A1)") # fmt: skip
# Orbits under H in the new cell, against the parent orbits.
mapping = _source_map(structure, described, symprec)
parent_sites = {s["site"]: s for s in parent_report["sites"]}
source_ids = [s.id for s in structure.sites]
new_ids = [s.id for s in described.sites]
roots = _orbits_from(perms, len(new_ids))
orbit_members: dict[int, list[int]] = {}
for i, r in enumerate(roots):
orbit_members.setdefault(r, []).append(i)
tabulated = wyckoff.has_positions(target)
frac_tolerance = symprec / float(np.linalg.norm(lattice, axis=1).min())
orbits = []
for root, members in sorted(orbit_members.items()):
orbit: dict[str, Any] = {
"site": new_ids[root], "element": symbols[root], "fractional": frac[root].tolist(),
"multiplicity": len(members), "site_symmetry_order": len(h_ops) // len(members),
"sites": [new_ids[m] for m in members],
"parent_orbit": parent_sites[source_ids[mapping[root][0]]]["equivalent_to"],
} # fmt: skip
if tabulated:
try:
found_position, values = wyckoff.identify(
target, (frac[root][0], frac[root][1], frac[root][2]), max(frac_tolerance,
1e-6)) # fmt: skip
except ValueError as error: # pragma: no cover
orbit["warning"] = str(error)
else:
orbit.update(wyckoff=found_position.label,
site_symmetry=found_position.site_symmetry,
wyckoff_parameters=values) # fmt: skip
orbits.append(orbit)
splitting = []
for parent_orbit in dict.fromkeys(s["equivalent_to"] for s in parent_report["sites"]):
info = parent_sites[parent_orbit]
children = [o for o in orbits if o["parent_orbit"] == parent_orbit]
splitting.append({
"parent_orbit": parent_orbit, "element": info["symbol"],
"parent_wyckoff": info["wyckoff"], "parent_site_symmetry": info["site_symmetry"],
"into": [{"site": o["site"], "wyckoff": o.get("wyckoff"),
"multiplicity": o["multiplicity"]} for o in children],
"split": len(children) > 1,
}) # fmt: skip
group = {"number": target.number, "hm": target.hm, "extension": target.extension,
"hall": target.hall, "operations": len(h_ops)} # fmt: skip
descent = {
"parent": {k: parent_report[k] for k in ("number", "international", "hall")},
"parent_operations": len(parent_ops),
"subgroup": group,
"transformation": transformation,
"P": p_matrix.tolist(),
"p": p_shift.tolist(),
"index": index,
"t_index": t_index,
"k_index": k_index,
"type": kind,
"maximal": maximal,
"verified_by_detection": True,
"independent_sites": {"parent": len(splitting), "subgroup": len(orbits)},
"changed_independent_sites": [s["parent_orbit"] for s in splitting if s["split"]],
"splitting": splitting,
"site_map": {
new_ids[i]: {"site": source_ids[s], "translation": t.astype(int).tolist()}
for i, (s, t) in enumerate(mapping)
}, # fmt: skip
"symprec_angstrom": symprec,
"source": structure.id,
"source_sha256": content_digest(structure),
"references": [ITA],
}
builder = {
"kind": "subgroup_descent",
"space_group": group,
"crystal_system": target.crystal_system,
"asymmetric_unit": [{k: o[k] for k in o if k != "sites"} for o in orbits],
"orbit_of_site": {s: o["site"] for o in orbits for s in o["sites"]},
"cell": "conventional",
"descent": descent,
}
data = described.model_dump(mode="json", exclude_none=True)
data["bonds"] = _carry_bonds(structure, described, mapping, symprec)
data["cell_setting"] = "conventional"
count = len(described.sites)
if structure.charge is not None:
charge = structure.charge * count / len(structure.sites)
data["charge"] = int(round(charge)) if abs(charge - round(charge)) < 1e-9 else None
if structure.multiplicity is not None and count == len(structure.sites):
data["multiplicity"] = structure.multiplicity
provenance: dict[str, Any] = {"builder": crystal._json(builder)}
data["provenance"] = {}
result = PeriodicStructure.model_validate({k: v for k, v in data.items() if v is not None})
tensors = displacement_tensors(structure)
if tensors is not None:
# The basis change keeps the Cartesian frame, so U_cart is copied to every image.
carried = {new_ids[i]: tensors[1][source_ids[s]] for i, (s, _t) in enumerate(mapping)
if source_ids[s] in tensors[1]} # fmt: skip
provenance[ADP_KEY] = _adp_record(
result, tensors[0], carried, "copied to the subgroup cell (Cartesian frame kept)"
)
result = result.model_copy(update={"provenance": provenance})
record = {**descent, "identifier": identifier, "sites": count,
"orbits": [{k: o[k] for k in o if k != "sites"} for o in orbits]} # fmt: skip
return crystal._json(record), result
def _prime(n: int) -> bool:
return n > 1 and all(n % k for k in range(2, int(math.isqrt(n)) + 1))
# --- documents and undo -------------------------------------------------------------
def _find(document: Document, structure: str) -> PeriodicStructure:
found = {s.id: s for s in document.periodic_structures}
if structure not in found:
raise ValueError(f"periodic structure {structure!r} not found")
return found[structure]
[docs]
def adopt_in_document(document: Document, structure: str, **options: Any) -> Document:
from vibesketcher.document.periodic import with_periodic
return with_periodic(document, adopt(_find(document, structure), **options))
[docs]
def add_derived(document: Document, derived: PeriodicStructure) -> Document:
from vibesketcher.document.periodic import with_periodic
if any(s.id == derived.id for s in document.periodic_structures):
raise ValueError(f"periodic structure {derived.id!r} already exists")
return with_periodic(document, derived)
[docs]
def undo(document: Document, structure: str) -> Document:
"""Undo the last adoption of ``structure``, or remove an unchanged derived structure."""
from vibesketcher.document.periodic import with_periodic
from vibesketcher.document.periodic_prepare import content_digest
target = _find(document, structure)
record = target.provenance.get(RECORD)
builder = crystal._builder(target)
if isinstance(record, dict) and record.get("kind") == "adopted":
if record.get("result_sha256") != content_digest(target):
raise ValueError(f"{structure} changed after the adoption; undo refused")
before = record.get("before")
assert isinstance(before, dict)
data = target.model_dump(mode="json", exclude_none=True)
provenance = dict(target.provenance)
for key in (RECORD, ADP_KEY):
if before.get(key) is None:
provenance.pop(key, None)
else:
provenance[key] = before[key]
if "lattice_angstrom" in before:
data["lattice_angstrom"] = before["lattice_angstrom"]
positions = before["fractional"]
assert isinstance(positions, dict)
for site in data["sites"]:
site["fractional"] = positions[site["id"]]
data["provenance"] = provenance
return with_periodic(document, PeriodicStructure.model_validate(data))
if builder.get("kind") in ("enantiomorph", "subgroup_descent"):
if content_digest(target) != _derived_digest(target):
raise ValueError(f"{structure} changed after it was derived; undo refused")
data = document.to_json_data()
data["periodic_structures"] = [
s.model_dump(mode="json", exclude_none=True)
for s in document.periodic_structures
if s.id != structure
]
return Document.model_validate(data)
raise ValueError(f"{structure} has no symmetry edit to undo")
def _derived_digest(structure: PeriodicStructure) -> str:
recorded = structure.provenance.get("derived_sha256")
return str(recorded) if recorded else ""
[docs]
def stamp(structure: PeriodicStructure) -> PeriodicStructure:
"""Record the derived structure's own digest so undo can refuse after later edits."""
from vibesketcher.document.periodic_prepare import content_digest
return structure.model_copy(
update={"provenance": {**structure.provenance, "derived_sha256": content_digest(structure)}}
)