vibe-sketcherDocumentation

Source code for vibesketcher.document.wyckoff

"""Wyckoff positions of the space-group settings (#229).

A Wyckoff position is a class of points whose site-symmetry groups are
conjugate in the space group; its multiplicity is the number of points of one
orbit in the conventional cell, the order of G over that of the site group
(International Tables for
Crystallography, Vol. A, sections 1.4.4 and 2.1.3.11). The letters (``a`` for
the most special position, the general position last, and ``A`` for the 27th
position of P m m m, which the Tables write as alpha), the oriented site-symmetry
symbols and the first coordinate triplet of each position come from
``data/wyckoff_positions.json``, generated from spglib's database by
``scripts/generate_wyckoff_table.py``.

Nothing here trusts the table. :func:`check_setting` recomputes the
site-symmetry orbits from the setting's operations (``spacegroups``): every
multiplicity must equal the orbit size of a generic point on its triplet, and
every point of a 1/24 grid of the cell (which holds every fixed special
position) must belong to exactly one listed position. A point ``p`` lies on
the representative of a position with triplet ``x -> R x + t`` when
``R g p + t - g p`` is a lattice vector for some operation ``g`` and its site
group has the position's order, the test spglib uses (A. Togo, K. Shinohara
and I. Tanaka, Sci. Technol. Adv. Mater. Meth. 4, 2384822 (2024)).
"""

from __future__ import annotations

import json
import re
from dataclasses import dataclass
from fractions import Fraction
from functools import cache
from importlib import resources
from typing import Any

import numpy as np

from vibesketcher.document.spacegroups import Operation, Setting, find

#: Position letters in the order of the International Tables (``A`` stands for alpha).
LETTERS = "abcdefghijklmnopqrstuvwxyzA"
_VARIABLES = "xyz"
_TERM = re.compile(r"([+-]?)(\d*/?\d*)([xyz]?)")
#: Generic values for free parameters when a test point must avoid special values.
_GENERIC = (0.1174, 0.2391, 0.3313)

IntMatrix = tuple[tuple[int, int, int], tuple[int, int, int], tuple[int, int, int]]
FracVector = tuple[Fraction, Fraction, Fraction]


[docs] def parse_triplet(text: str) -> tuple[IntMatrix, FracVector]: """``"x,2x,1/4"`` as the affine map (R, t) of the free coordinates x, y, z.""" parts = text.replace(" ", "").strip("()").split(",") if len(parts) != 3: raise ValueError(f"a coordinate triplet has three parts, not {text!r}") rows: list[tuple[int, int, int]] = [] shifts: list[Fraction] = [] for part in parts: row = [0, 0, 0] shift = Fraction(0) position = 0 if not part: raise ValueError(f"an empty component in {text!r}") while position < len(part): match = _TERM.match(part, position) if match is None or match.end() == position: raise ValueError(f"cannot read {part!r} in {text!r}") sign, number, variable = match.groups() factor = -1 if sign == "-" else 1 if variable: if "/" in number: raise ValueError(f"fractional coefficients are not used: {text!r}") row[_VARIABLES.index(variable)] += factor * int(number or 1) elif number: shift += factor * Fraction(number) else: raise ValueError(f"cannot read {part!r} in {text!r}") position = match.end() rows.append((row[0], row[1], row[2])) shifts.append(shift % 1) return (rows[0], rows[1], rows[2]), (shifts[0], shifts[1], shifts[2])
def _format(rotation: IntMatrix, translation: FracVector) -> str: return Operation(rotation, translation).triplet()
[docs] def normalise_triplet(text: str) -> tuple[IntMatrix, FracVector]: """A triplet's (R, t) with t reduced to [0, 1): equal keys name the same points.""" return parse_triplet(text)
[docs] @dataclass(frozen=True) class WyckoffPosition: """One Wyckoff position of a setting: ``12c`` with site symmetry ``3.`` at ``0,0,z``.""" letter: str multiplicity: int site_symmetry: str triplet: str
[docs] @property def label(self) -> str: return f"{self.multiplicity}{self.letter}"
[docs] @property def affine(self) -> tuple[IntMatrix, FracVector]: return parse_triplet(self.triplet)
[docs] @property def free(self) -> tuple[str, ...]: """The free parameters, in x, y, z order (empty for a fixed position).""" rotation, _ = self.affine return tuple(v for j, v in enumerate(_VARIABLES) if any(row[j] for row in rotation))
[docs] def coordinate(self, values: dict[str, float] | None = None) -> tuple[float, float, float]: """The representative point for the given free parameters (every one required).""" given = dict(values or {}) unknown = sorted(set(given) - set(self.free)) if unknown: fixed = f"takes {', '.join(self.free)}" if self.free else "has no free parameter" raise ValueError(f"Wyckoff position {self.label} {fixed}; got {', '.join(unknown)}") missing = [v for v in self.free if v not in given] if missing: raise ValueError( f"Wyckoff position {self.label} ({self.triplet}) needs {', '.join(missing)}" ) rotation, translation = self.affine point = [given.get(v, 0.0) for v in _VARIABLES] if not all(np.isfinite(point)): raise ValueError("Wyckoff parameters must be finite") return tuple( # type: ignore[return-value] sum(rotation[i][j] * point[j] for j in range(3)) + float(translation[i]) for i in range(3) )
[docs] def describe(self) -> dict[str, Any]: return { "letter": self.letter, "multiplicity": self.multiplicity, "label": self.label, "site_symmetry": self.site_symmetry, "coordinates": self.triplet, "free": list(self.free), }
@cache def _table() -> dict[str, Any]: text = resources.files("vibesketcher.document").joinpath("data/wyckoff_positions.json") data: dict[str, Any] = json.loads(text.read_text()) return data
[docs] def reset_cache() -> None: """Forget the loaded table (the generator rewrites it).""" _table.cache_clear() _positions.cache_clear()
def _setting(symbol: str | int | Setting) -> Setting: return symbol if isinstance(symbol, Setting) else find(symbol) @cache def _positions(key: str) -> tuple[WyckoffPosition, ...]: rows = _table()["settings"].get(key) if rows is None: return () return tuple(WyckoffPosition(r[0], int(r[1]), r[2], r[3]) for r in rows)
[docs] def has_positions(symbol: str | int | Setting) -> bool: return bool(_positions(_setting(symbol).symbol))
[docs] def positions(symbol: str | int | Setting) -> list[WyckoffPosition]: """The Wyckoff positions of a setting, from ``a`` to the general position.""" setting = _setting(symbol) found = _positions(setting.symbol) if not found: raise ValueError( f"no Wyckoff table for {setting.symbol} ({setting.hall}); the table covers the " "settings of the International Tables, Vol. A; give free coordinates instead" ) return list(found)
[docs] def position(symbol: str | int | Setting, letter: str) -> WyckoffPosition: """A position by letter, ``c``, or by multiplicity and letter, ``12c``.""" setting = _setting(symbol) match = re.fullmatch(r"\s*(\d*)\s*([A-Za-z])\s*", letter) if match is None: raise ValueError(f"a Wyckoff position looks like 12c or c, not {letter!r}") multiplicity, name = match.groups() for candidate in positions(setting): if candidate.letter == name: if multiplicity and int(multiplicity) != candidate.multiplicity: raise ValueError( f"{setting.symbol} has {candidate.label}, not {multiplicity}{name}" ) return candidate letters = ", ".join(p.label for p in positions(setting)) raise ValueError(f"{setting.symbol} has no Wyckoff position {letter!r} (it has {letters})")
[docs] def site( symbol: str | int | Setting, letter: str, values: dict[str, float] | None = None ) -> tuple[float, float, float]: """Fractional coordinates of a Wyckoff site, e.g. ``site("R-3c", "12c", {"z": 0.352})``.""" return position(symbol, letter).coordinate(values)
@cache def _operations(hall: str) -> tuple[Operation, ...]: from vibesketcher.document.spacegroups import operations_from_hall return tuple(operations_from_hall(hall)) @cache def _arrays(setting: Setting) -> tuple[np.ndarray, np.ndarray]: ops = _operations(setting.hall) rotations = np.array([op.rotation for op in ops], dtype=float) translations = np.array([[float(x) for x in op.translation] for op in ops]) return rotations, translations def _wrap(delta: np.ndarray) -> np.ndarray: return delta - np.round(delta)
[docs] def orbit( symbol: str | int | Setting, point: tuple[float, float, float], tolerance: float = 1e-4 ) -> list[tuple[float, float, float]]: """The distinct images of a point in the conventional cell, wrapped into [0, 1).""" rotations, translations = _arrays(_setting(symbol)) images = np.einsum("nij,j->ni", rotations, np.asarray(point, dtype=float)) + translations images -= np.floor(images + 1e-12) kept: list[np.ndarray] = [] for image in images: if all(np.max(np.abs(_wrap(image - other))) > tolerance for other in kept): kept.append(image) return [(float(x), float(y), float(z)) for x, y, z in kept]
[docs] def orbit_triplets(symbol: str | int | Setting, triplet: str) -> set[tuple[IntMatrix, FracVector]]: """The symbolic orbit of a coordinate triplet under every operation (with centring).""" rotation, translation = parse_triplet(triplet) out = set() for op in _operations(_setting(symbol).hall): image_r = tuple( tuple(sum(op.rotation[i][k] * rotation[k][j] for k in range(3)) for j in range(3)) for i in range(3) ) image_t = tuple( (sum((op.rotation[i][k] * translation[k] for k in range(3)), Fraction(0)) + op.translation[i]) % 1 for i in range(3) ) # fmt: skip out.add((image_r, image_t)) return out # type: ignore[return-value]
[docs] def identify( symbol: str | int | Setting, point: tuple[float, float, float], tolerance: float = 1e-4 ) -> tuple[WyckoffPosition, dict[str, float]]: """The Wyckoff position of a point and its free parameters on the representative. ``tolerance`` is in fractional coordinates. The parameters are those of the first orbit image that lies on the position's coordinate triplet. """ setting = _setting(symbol) table = positions(setting) rotations, translations = _arrays(setting) p = np.asarray(point, dtype=float) images = np.einsum("nij,j->ni", rotations, p) + translations stabiliser = int(np.sum(np.max(np.abs(_wrap(images - p)), axis=1) < tolerance)) multiplicity = len(images) // stabiliser for candidate in table: if candidate.multiplicity != multiplicity: continue r, t = candidate.affine rm = np.asarray(r, dtype=float) tv = np.asarray([float(x) for x in t]) on = images @ rm.T + tv hits = np.max(np.abs(_wrap(on - images)), axis=1) < tolerance if hits.any(): representative = on[int(np.argmax(hits))] values = {v: float(representative[_VARIABLES.index(v)]) % 1.0 for v in candidate.free} return candidate, {k: (0.0 if abs(x - 1) < 1e-12 else x) for k, x in values.items()} raise ValueError( f"the point {tuple(point)} matches no Wyckoff position of {setting.symbol} " f"(multiplicity {multiplicity}); loosen the tolerance or check the coordinates" )
[docs] def free_cell_parameters(symbol: str | int | Setting) -> list[str]: """The lattice parameters a crystal of this setting takes; the system fixes the rest.""" setting = _setting(symbol) system = setting.crystal_system if setting.extension == "R": return ["a", "alpha"] if system == "monoclinic": unique = setting.qualifier[:1] or "b" return ["a", "b", "c", {"a": "alpha", "b": "beta", "c": "gamma"}[unique]] return { "triclinic": ["a", "b", "c", "alpha", "beta", "gamma"], "orthorhombic": ["a", "b", "c"], "tetragonal": ["a", "c"], "trigonal": ["a", "c"], "hexagonal": ["a", "c"], "cubic": ["a"], }[system]
[docs] def describe(symbol: str | int | Setting) -> dict[str, Any]: """A setting and its Wyckoff positions, for the SDK, CLI, REST and MCP.""" setting = _setting(symbol) return { "number": setting.number, "symbol": setting.symbol, "hm": setting.hm, "hall": setting.hall, "crystal_system": setting.crystal_system, "cell_parameters": free_cell_parameters(setting), "operations": len(_operations(setting.hall)), "positions": [p.describe() for p in positions(setting)], "source": _table()["source"], }
[docs] def check_setting(symbol: str | int | Setting) -> list[str]: """Problems found when the table is compared with the computed orbits (empty: none). Exact integer arithmetic on the 1/24 grid: operations and triplets are scaled by 24, so every comparison is modulo 24. """ setting = _setting(symbol) table = positions(setting) ops = _operations(setting.hall) n = len(ops) w = np.array([op.rotation for op in ops], dtype=np.int64) s = np.array([[int(x * 24) for x in op.translation] for op in ops], dtype=np.int64) problems: list[str] = [] letters = [p.letter for p in table] if letters != list(LETTERS[: len(table)]): problems.append(f"letters run {''.join(letters)}") affines = [] for entry in table: r, t = entry.affine rm = np.asarray(r, dtype=np.int64) tv = np.asarray([int(x * 24) for x in t], dtype=np.int64) if not np.array_equal(rm @ rm, rm) or np.any((rm @ tv) % 24): problems.append(f"{entry.label}: the triplet {entry.triplet} is not a projection") affines.append((entry, rm, tv)) generic = entry.coordinate({v: _GENERIC[_VARIABLES.index(v)] for v in entry.free}) size = len(orbit(setting, generic, 1e-6)) if size != entry.multiplicity: problems.append(f"{entry.label}: a generic point has an orbit of {size}") try: same = identify(setting, generic, 1e-6)[0] == entry except ValueError as error: problems.append(f"{entry.label}: {error}") continue if not same: problems.append(f"{entry.label}: a generic point is identified as another position") grid = np.stack(np.meshgrid(*(np.arange(24),) * 3, indexing="ij"), axis=-1).reshape(-1, 3) images = (np.einsum("nij,mj->nmi", w, grid) + s[:, None, :]) % 24 keys = images[..., 0] * 576 + images[..., 1] * 24 + images[..., 2] own = grid[:, 0] * 576 + grid[:, 1] * 24 + grid[:, 2] stabiliser = np.sum(keys == own[None, :], axis=0) canonical = keys.min(axis=0) _, first = np.unique(canonical, return_index=True) multiplicity = n // stabiliser[first] y = images[:, first, :] matches = np.zeros((len(affines), len(first)), dtype=bool) for row, (entry, rm, tv) in enumerate(affines): on = np.all((np.einsum("ij,nrj->nri", rm, y) + tv - y) % 24 == 0, axis=2).any(axis=0) matches[row] = on & (multiplicity == entry.multiplicity) for column in np.flatnonzero(matches.sum(axis=0) != 1)[:20]: where = ",".join(f"{int(x)}/24" for x in grid[first[column]]) matched = [affines[r][0].label for r in np.flatnonzero(matches[:, column])] problems.append(f"the grid point ({where}) of multiplicity {multiplicity[column]} " f"matches {matched or 'no position'}") # fmt: skip return problems
[docs] def analyse_sites( symbol: str | int | Setting, sites: list[dict[str, Any]], tolerance: float = 1e-4, ) -> dict[str, Any]: """Each site's Wyckoff position, free parameters and orbit, for previews (#229). A site is ``{"position": "12c", "parameters": {"z": 0.35}}`` or ``{"fractional": [x, y, z]}``; ``element`` is carried through. """ setting = _setting(symbol) out = [] for index, given in enumerate(sites): if not isinstance(given, dict): raise ValueError(f"site {index + 1} must be an object") unknown = sorted(set(given) - {"element", "position", "parameters", "fractional"}) if unknown: raise ValueError(f"site {index + 1}: unknown fields {', '.join(unknown)}") if ("position" in given) == ("fractional" in given): raise ValueError(f"site {index + 1}: give a Wyckoff position or fractional coordinates") if "position" in given: parameters = given.get("parameters") or {} if not isinstance(parameters, dict): raise ValueError(f"site {index + 1}: parameters must be an object") point = site(setting, str(given["position"]), {str(k): float(v) for k, v in parameters.items()}) # fmt: skip else: values = [float(x) for x in given["fractional"]] if len(values) != 3 or not all(np.isfinite(values)): raise ValueError(f"site {index + 1}: fractional takes three finite numbers") point = (values[0], values[1], values[2]) found, free = identify(setting, point, tolerance) row: dict[str, Any] = { "fractional": list(point), "wyckoff": found.label, "letter": found.letter, "multiplicity": found.multiplicity, "site_symmetry": found.site_symmetry, "coordinates": found.triplet, "parameters": free, "orbit": [list(p) for p in orbit(setting, point, tolerance)], } if "element" in given: row["element"] = given["element"] if "position" in given and position(setting, str(given["position"])) != found: row["warning"] = (f"given on {position(setting, str(given['position'])).label}, " f"but the parameters put it on {found.label}") # fmt: skip out.append(row) return {"number": setting.number, "symbol": setting.symbol, "hall": setting.hall, "operations": len(_operations(setting.hall)), "sites": out} # fmt: skip