vibe-sketcherDocumentation
Source code for vibesketcher.document.diffraction
"""Calculated X-ray powder patterns of periodic structures (#207).
A kinematic powder pattern from a validated three-dimensional cell: every
reflection with ``d >= lambda / (2 sin theta_max)`` is generated from the
reciprocal lattice (rows ``b_i`` with ``a_i . b_j = delta_ij``, so
``1/d = |h b1 + k b2 + l b3|``), and its structure factor is
F(hkl) = sum_j occ_j f0_j(s) exp(-B_j s^2) exp(2 pi i (h x_j + k y_j + l z_j)),
with ``s = sin(theta)/lambda = 1/(2d)``, neutral-atom form factors ``f0``
from the Waasmaier-Kirfel parametrisation (D. Waasmaier and A. Kirfel,
Acta Cryst. A51, 416 (1995), doi:10.1107/S0108767394013292) and the
isotropic Debye-Waller factor with ``B = 8 pi^2 U_iso`` (International
Tables for Crystallography Vol. C (2006), Sections 6.1.1 and 6.1.1.3).
Reflections that coincide in ``d`` and ``abs(F)^2`` are merged into one family
whose multiplicity is the number of ``hkl`` counted over the full sphere,
so no point group has to be assumed. The integrated intensity is
I = m abs(F)^2 Lp(theta), Lp = (1 + K cos^2 2theta) / ((1 + K) sin^2 theta cos theta),
the Bragg-Brentano Lorentz-polarisation factor for an unpolarised beam
(``K = 1``) or with a crystal monochromator at ``2theta_M``
(``K = cos^2 2theta_M``); International Tables Vol. C, Section 6.2.
Preferred orientation is optional. It uses the March-Dollase function
(A. March, Z. Kristallogr. 81, 285 (1932); W. A. Dollase, J. Appl. Cryst. 19,
267 (1986), doi:10.1107/S0021889886089458):
P(alpha) = (r^2 cos^2 alpha + sin^2 alpha / r)^(-3/2),
where alpha is the angle between a reflection's scattering vector and the
stated preferred-orientation direction, a reciprocal-lattice vector ``(hkl)*``
of the same cell, normal to the platelets or along the needles. ``r = 1`` is
a random powder, ``r < 1`` plates lying in the sample surface and ``r > 1``
needles. The function averages to 1 over the sphere, so the total intensity is
kept. The members of one family can make different angles with the direction,
so a family's intensity is ``m abs(F)^2 Lp <P>``, with ``<P>`` the mean over its
members, and ``<P>`` is reported with the family. It describes symmetric
reflection with cylindrical texture about the sample normal; it is not a
texture analysis.
Anomalous dispersion (``f'``, ``f''``), absorption, extinction and
microabsorption are not modelled and every result says so.
Anisotropic displacement parameters are refused, not reduced to ``U_iso``;
an element without tabulated coefficients is refused, never dropped. This is
a planning aid for comparing a model with a measurement, not a refinement:
agreement of a profile does not prove a structure unique.
"""
from __future__ import annotations
import hashlib
import json
import math
from dataclasses import dataclass
from typing import Any, Literal
import numpy as np
from pydantic import BaseModel, ConfigDict, Field, model_validator
from vibesketcher.document._xray_form_factors import COEFFICIENTS
from vibesketcher.document.model import PeriodicStructure
#: Named characteristic lines (angstrom): G. Hoelzer et al., Phys. Rev. A 56,
#: 4554 (1997), as tabulated in International Tables Vol. C, Table 4.2.2.1.
WAVELENGTHS: dict[str, float] = {"CuKa1": 1.5405929, "MoKa1": 0.7093171}
FORM_FACTOR_SOURCE = (
"D. Waasmaier and A. Kirfel, Acta Cryst. A51, 416 (1995), doi:10.1107/S0108767394013292 "
"(neutral atoms; fitted to International Tables Vol. C, Table 6.1.1.1)"
)
REFERENCES = (
FORM_FACTOR_SOURCE,
"International Tables for Crystallography Vol. C (2006), Sections 6.1.1 (form factors, "
"Debye-Waller factor) and 6.2 (Lorentz-polarisation)",
"G. Hoelzer et al., Phys. Rev. A 56, 4554 (1997) (Cu Ka1, Mo Ka1 wavelengths)",
)
PREFERRED_ORIENTATION_REFERENCES = (
"A. March, Z. Kristallogr. 81, 285 (1932) (March function)",
"W. A. Dollase, J. Appl. Cryst. 19, 267 (1986), doi:10.1107/S0021889886089458 "
"(March-Dollase preferred-orientation correction)",
)
ASSUMPTIONS = (
"kinematic scattering; neutral-atom form factors (ion charges ignored)",
"no anomalous dispersion (f', f''), absorption, extinction or microabsorption",
"Bragg-Brentano Lorentz-polarisation; reflections overlapping in d are separate entries",
)
#: Bounded work: reflections generated before merging, and profile points.
MAX_REFLECTIONS = 200_000
MAX_PROFILE_POINTS = 200_000
#: abs(F)^2 below this fraction of the largest is a systematic absence.
_EXTINCT = 1e-9
[docs]
class Profile(BaseModel):
"""A peak shape for a continuous calculated curve (drawing and overlays only)."""
model_config = ConfigDict(extra="forbid")
shape: Literal["gaussian", "lorentzian", "pseudo_voigt"] = "pseudo_voigt"
#: Constant full width at half maximum (degrees 2theta), or Caglioti U, V, W.
fwhm_deg: float | None = Field(default=None, gt=0, le=10)
caglioti: tuple[float, float, float] | None = None
#: Lorentzian fraction of a pseudo-Voigt.
eta: float = Field(default=0.5, ge=0, le=1)
step_deg: float = Field(default=0.02, gt=0, le=1)
@model_validator(mode="after")
def _width(self) -> Profile:
if (self.fwhm_deg is None) == (self.caglioti is None):
raise ValueError("give the profile width: fwhm_deg or caglioti (U, V, W), not both")
if self.caglioti is not None and not all(math.isfinite(x) for x in self.caglioti):
raise ValueError("Caglioti U, V, W must be finite")
return self
[docs]
class PreferredOrientation(BaseModel):
"""March-Dollase preferred orientation along a reciprocal-lattice direction."""
model_config = ConfigDict(extra="forbid")
model: Literal["march_dollase"] = "march_dollase"
#: The direction ``(hkl)*`` in the stated cell's reciprocal basis: the platelet normal
#: or the needle axis. Only its direction counts.
hkl: tuple[int, int, int]
#: March parameter: 1 random, below 1 platelets, above 1 needles.
r: float = Field(gt=0, le=10, allow_inf_nan=False)
@model_validator(mode="after")
def _direction(self) -> PreferredOrientation:
if self.hkl == (0, 0, 0):
raise ValueError("the preferred-orientation direction (hkl) must not be 0 0 0")
if any(abs(i) > 100 for i in self.hkl):
raise ValueError("preferred-orientation indices must be between -100 and 100")
return self
[docs]
def march_dollase(cos_alpha: np.ndarray, r: float) -> np.ndarray:
"""The March-Dollase weight (Dollase 1986): ``(r^2 cos^2 + sin^2 / r)^(-3/2)``."""
c2 = np.clip(np.asarray(cos_alpha, dtype=float) ** 2, 0.0, 1.0)
weight: np.ndarray = (r * r * c2 + (1.0 - c2) / r) ** -1.5
return weight
[docs]
class PatternSettings(BaseModel):
"""Every choice of a calculated powder pattern; nothing is inferred."""
model_config = ConfigDict(extra="forbid")
radiation: Literal["xray"] = "xray"
#: A named line (CuKa1, MoKa1) or a wavelength in angstrom.
wavelength: float | Literal["CuKa1", "MoKa1"] = "CuKa1"
two_theta_min: float = Field(default=5.0, ge=0, lt=180)
two_theta_max: float = Field(default=90.0, gt=0, lt=180)
#: Isotropic displacement parameters by site ID, CIF label or element (angstrom^2).
b_iso: dict[str, float] = Field(default_factory=dict, max_length=25000)
u_iso: dict[str, float] = Field(default_factory=dict, max_length=25000)
#: Used for a site with no stated B or U (0 = static lattice, recorded).
default_b_iso: float = Field(default=0.0, ge=0, le=100)
#: Occupancy overrides by site ID, CIF label or element.
occupancy: dict[str, float] = Field(default_factory=dict, max_length=25000)
#: 2theta of a crystal monochromator (degrees); none for an unpolarised beam.
monochromator_two_theta: float | None = Field(default=None, ge=0, lt=180)
#: Optional March-Dollase preferred orientation (none: a random powder).
preferred_orientation: PreferredOrientation | None = None
profile: Profile | None = None
@model_validator(mode="before")
@classmethod
def _refuse_anisotropic(cls, data: Any) -> Any:
if isinstance(data, dict):
aniso = [k for k in data if k in ("u_aniso", "b_aniso", "beta_aniso", "anisotropic")]
if aniso:
raise ValueError(
f"anisotropic displacement parameters ({', '.join(aniso)}) are not "
"supported; give isotropic b_iso or u_iso"
)
return data
@model_validator(mode="after")
def _ranges(self) -> PatternSettings:
if self.two_theta_min >= self.two_theta_max:
raise ValueError("two_theta_min must be below two_theta_max")
if isinstance(self.wavelength, float | int) and not 0.01 <= self.wavelength <= 100:
raise ValueError("wavelength must be between 0.01 and 100 angstrom")
both = sorted(set(self.b_iso) & set(self.u_iso))
if both:
raise ValueError(f"give B or U for a site, not both: {', '.join(both[:8])}")
for name, table, high in (("b_iso", self.b_iso, 100.0), ("u_iso", self.u_iso, 1.5),
("occupancy", self.occupancy, 1.0)): # fmt: skip
for key, value in table.items():
if not math.isfinite(value) or not 0 <= value <= high:
raise ValueError(f"{name}[{key!r}] = {value} is outside [0, {high}]")
return self
[docs]
def wavelength_angstrom(self) -> float:
if isinstance(self.wavelength, str):
return WAVELENGTHS[self.wavelength]
return float(self.wavelength)
[docs]
@dataclass(frozen=True)
class Scatterer:
"""One atom of the cell: identity, fractional position, occupancy and B (angstrom^2)."""
label: str
element: str
fractional: tuple[float, float, float]
occupancy: float
b_iso: float
b_from: str
[docs]
def form_factor(element: str, s: np.ndarray) -> np.ndarray:
"""Waasmaier-Kirfel f0 at ``s = sin(theta)/lambda`` (1/angstrom); unknown elements refused."""
if element not in COEFFICIENTS:
raise ValueError(f"no X-ray form factor for {element!r}; it is not dropped, so the "
"pattern is refused") # fmt: skip
a, b, c = COEFFICIENTS[element]
s2 = np.asarray(s, dtype=float) ** 2
return np.asarray(c + sum(ai * np.exp(-bi * s2) for ai, bi in zip(a, b, strict=True)))
[docs]
def lorentz_polarisation(two_theta_deg: np.ndarray, monochromator_deg: float | None) -> np.ndarray:
"""Bragg-Brentano Lp (International Tables Vol. C, Section 6.2)."""
tt = np.radians(np.asarray(two_theta_deg, dtype=float))
k = 1.0 if monochromator_deg is None else math.cos(math.radians(monochromator_deg)) ** 2
th = tt / 2
return np.asarray((1 + k * np.cos(tt) ** 2) / ((1 + k) * np.sin(th) ** 2 * np.cos(th)))
def _lookup(table: dict[str, float], *keys: str) -> tuple[float, str] | None:
for key in keys:
if key in table:
return table[key], key
return None
def _displacement(settings: PatternSettings, *keys: str) -> tuple[float, str]:
found = _lookup(settings.b_iso, *keys)
if found is not None:
return found[0], f"b_iso[{found[1]}]"
found = _lookup(settings.u_iso, *keys)
if found is not None:
return 8 * math.pi**2 * found[0], f"u_iso[{found[1]}]"
return settings.default_b_iso, "default_b_iso"
[docs]
def scatterers_of(structure: PeriodicStructure, settings: PatternSettings) -> list[Scatterer]:
"""The structure's sites with occupancies and B (overrides by site ID, then element)."""
out = []
for site in structure.sites:
occ = _lookup(settings.occupancy, site.id, site.symbol)
b, source = _displacement(settings, site.id, site.symbol)
out.append(Scatterer(site.id, site.symbol, site.fractional,
occ[0] if occ else site.occupancy, b, source)) # fmt: skip
_unused(settings, {k for s in structure.sites for k in (s.id, s.symbol)})
return out
def _unused(settings: PatternSettings, keys: set[str]) -> None:
for name in ("b_iso", "u_iso", "occupancy"):
stray = sorted(set(getattr(settings, name)) - keys)
if stray:
raise ValueError(f"{name} names no site or element of the structure: "
f"{', '.join(stray[:8])}") # fmt: skip
def _digest(value: Any) -> str:
text = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
return hashlib.sha256(text.encode("ascii")).hexdigest()
def _canonical(hkls: np.ndarray) -> list[int]:
"""A representative hkl of an equivalent set: most non-negative, then largest."""
best = max(hkls.tolist(), key=lambda h: (sum(x >= 0 for x in h), h))
return [int(x) for x in best]
[docs]
def calculate_pattern(
lattice: np.ndarray, scatterers: list[Scatterer], settings: PatternSettings
) -> dict[str, Any]:
"""Reflections (and an optional profile) of a 3D cell; see the module docstring."""
lattice = np.asarray(lattice, dtype=float)
if not scatterers:
raise ValueError("the cell has no atoms")
for atom in scatterers:
form_factor(atom.element, np.zeros(1)) # refuse unknown elements up front
wavelength = settings.wavelength_angstrom()
tt_max = settings.two_theta_max
d_min = wavelength / (2 * math.sin(math.radians(tt_max / 2)))
reciprocal = np.linalg.inv(lattice).T # rows b_i, a_i . b_j = delta_ij (no 2 pi)
limits = [int(math.floor(float(np.linalg.norm(lattice[i])) / d_min)) for i in range(3)]
volume = abs(float(np.linalg.det(lattice)))
estimate = 4 / 3 * math.pi * volume / d_min**3
if estimate > MAX_REFLECTIONS:
raise ValueError(
f"about {estimate:.0f} reflections up to 2theta = {tt_max:g} deg exceed the "
f"bound of {MAX_REFLECTIONS}; lower two_theta_max or use a longer wavelength"
)
if math.prod(2 * n + 1 for n in limits) > 8 * MAX_REFLECTIONS:
raise ValueError("the cell is too oblique for the reflection bound; reduce it first")
ranges = [np.arange(-n, n + 1) for n in limits]
grid = np.stack(np.meshgrid(*ranges, indexing="ij"), axis=-1).reshape(-1, 3)
grid = grid[np.any(grid != 0, axis=1)]
inv_d = np.linalg.norm(grid @ reciprocal, axis=1)
keep = inv_d <= 1 / d_min * (1 + 1e-12)
grid, inv_d = grid[keep], inv_d[keep]
sin_theta = np.clip(wavelength * inv_d / 2, 0, 1)
two_theta = np.degrees(2 * np.arcsin(sin_theta))
keep = (two_theta >= settings.two_theta_min) & (two_theta <= tt_max)
grid, inv_d, two_theta = grid[keep], inv_d[keep], two_theta[keep]
s = inv_d / 2
frac = np.array([x.fractional for x in scatterers], dtype=float)
occ = np.array([x.occupancy for x in scatterers], dtype=float)
b = np.array([x.b_iso for x in scatterers], dtype=float)
elements = sorted({x.element for x in scatterers})
f0 = {e: form_factor(e, s) for e in elements}
structure_factor = np.zeros(len(grid), dtype=complex)
chunk = max(1, 2_000_000 // max(1, len(scatterers)))
for start in range(0, len(grid), chunk):
part = slice(start, start + chunk)
phase = np.exp(2j * np.pi * (grid[part] @ frac.T)) # (M, N)
weight = occ[None, :] * np.exp(-b[None, :] * s[part, None] ** 2)
fj = np.stack([f0[x.element][part] for x in scatterers], axis=1)
structure_factor[part] = np.sum(fj * weight * phase, axis=1)
f2 = np.abs(structure_factor) ** 2
largest = float(f2.max()) if len(f2) else 0.0
present = f2 > _EXTINCT * max(largest, 1e-300)
extinct = int(np.count_nonzero(~present))
# Families: equal d and |F|^2 (rounded), counted over the full sphere.
families: dict[tuple[float, float], list[int]] = {}
for index in np.nonzero(present)[0]:
key = (round(1 / float(inv_d[index]), 6), float(f"{f2[index]:.6e}"))
families.setdefault(key, []).append(int(index))
lp_all = lorentz_polarisation(two_theta, settings.monochromator_two_theta)
texture = settings.preferred_orientation
weights = np.ones(len(grid))
if texture is not None:
axis = np.asarray(texture.hkl, dtype=float) @ reciprocal
g = grid @ reciprocal
cos_alpha = (g @ axis) / (np.linalg.norm(g, axis=1) * float(np.linalg.norm(axis)))
weights = march_dollase(cos_alpha, texture.r)
reflections: list[dict[str, Any]] = []
for members in families.values():
i = members[0]
m = len(members)
po = float(np.mean(weights[members]))
intensity = m * float(f2[i]) * float(lp_all[i]) * po
d = 1 / float(inv_d[i])
entry = {
"hkl": _canonical(grid[members]), "multiplicity": m, "d_angstrom": d,
"two_theta_deg": float(two_theta[i]), "q_inv_angstrom": 2 * math.pi / d,
"f_squared": float(f2[i]), "lp": float(lp_all[i]), "intensity": intensity,
} # fmt: skip
if texture is not None:
entry["preferred_orientation"] = po
reflections.append(entry)
reflections.sort(key=lambda r: (r["two_theta_deg"], r["hkl"]))
top = max((r["intensity"] for r in reflections), default=0.0)
for r in reflections:
r["relative_intensity"] = 100 * r["intensity"] / top if top else 0.0
result: dict[str, Any] = {
"kind": "calculated_powder_pattern",
"radiation": settings.radiation,
"wavelength_angstrom": wavelength,
"wavelength_source": settings.wavelength if isinstance(settings.wavelength, str)
else "explicit",
"two_theta_range_deg": [settings.two_theta_min, tt_max],
"d_min_angstrom": d_min,
"polarisation": "unpolarised" if settings.monochromator_two_theta is None
else f"monochromator 2theta = {settings.monochromator_two_theta:g} deg",
"reflections": reflections,
"extinct": extinct,
"scatterers": [
{"label": x.label, "element": x.element, "occupancy": x.occupancy,
"b_iso": x.b_iso, "b_from": x.b_from} for x in scatterers
],
"form_factors": FORM_FACTOR_SOURCE,
"assumptions": list(ASSUMPTIONS)
+ (["no displacement stated for some sites: B = default_b_iso "
f"({settings.default_b_iso:g} A^2)"]
if any(x.b_from == "default_b_iso" for x in scatterers) else [])
+ ([_texture_text(texture)] if texture is not None
else ["no preferred orientation (a random powder)"]),
"references": list(REFERENCES)
+ (list(PREFERRED_ORIENTATION_REFERENCES) if texture is not None else []),
"settings": settings.model_dump(mode="json"),
} # fmt: skip
if settings.profile is not None:
result["profile"] = profile_curve(reflections, settings)
return result
def _texture_text(texture: PreferredOrientation) -> str:
h, k, l_ = texture.hkl
return (
f"March-Dollase preferred orientation along ({h} {k} {l_})* with r = {texture.r:g}: "
"symmetric reflection, cylindrical texture about the sample normal; each family "
"weighted by the mean over its members"
)
def _fwhm(profile: Profile, two_theta: float) -> float:
if profile.fwhm_deg is not None:
return profile.fwhm_deg
assert profile.caglioti is not None
u, v, w = profile.caglioti
t = math.tan(math.radians(two_theta / 2))
# G. Caglioti, A. Paoletti, F. P. Ricci, Nucl. Instrum. 3, 223 (1958).
value = u * t * t + v * t + w
if value <= 0:
raise ValueError(f"Caglioti U, V, W give FWHM^2 = {value:.3g} <= 0 at 2theta = "
f"{two_theta:.2f} deg") # fmt: skip
return math.sqrt(value)
[docs]
def profile_curve(reflections: list[dict[str, Any]], settings: PatternSettings) -> dict[str, Any]:
"""Peaks of unit area times their intensity on a regular 2theta grid (no background)."""
profile = settings.profile
assert profile is not None
lo, hi = settings.two_theta_min, settings.two_theta_max
count = int(math.floor((hi - lo) / profile.step_deg)) + 1
if count > MAX_PROFILE_POINTS:
raise ValueError(f"{count} profile points exceed {MAX_PROFILE_POINTS}; use a larger step")
x = lo + profile.step_deg * np.arange(count)
y = np.zeros(count)
for r in reflections:
centre = r["two_theta_deg"]
h = _fwhm(profile, centre)
dx = x - centre
window = np.abs(dx) <= 40 * h
dxw = dx[window]
ln2 = math.log(2)
gauss = (2 / h) * math.sqrt(ln2 / math.pi) * np.exp(-4 * ln2 * dxw**2 / h**2)
lorentz = (2 / (math.pi * h)) / (1 + 4 * dxw**2 / h**2)
eta = {"gaussian": 0.0, "lorentzian": 1.0}.get(profile.shape, profile.eta)
y[window] += r["intensity"] * (eta * lorentz + (1 - eta) * gauss)
top = float(y.max()) if len(y) else 0.0
return {
"two_theta_deg": x.tolist(),
"intensity": (100 * y / top).tolist() if top else y.tolist(),
"normalised": "maximum = 100",
"shape": profile.shape,
"background": "none",
}
[docs]
def calculate(
structure: PeriodicStructure, settings: PatternSettings | None = None
) -> dict[str, Any]:
"""The calculated powder pattern of a document's periodic structure."""
settings = settings or PatternSettings()
if not all(structure.pbc):
raise ValueError("a powder pattern needs a 3D periodic cell; this structure has "
f"PBC {list(structure.pbc)}") # fmt: skip
lattice = np.asarray(structure.lattice_angstrom, dtype=float)
result = calculate_pattern(lattice, scatterers_of(structure, settings), settings)
result["source"] = {"kind": "periodic_structure", "structure": structure.id,
"structure_sha256": structure_digest(structure)} # fmt: skip
return result
[docs]
def structure_digest(structure: PeriodicStructure) -> str:
"""The digest a calculated pattern records: the structure without its provenance."""
return _digest(structure.model_dump(mode="json", exclude={"provenance", "source_cif"}))
# --- CIF with occupancies and U_iso / B_iso -----------------------------------------
[docs]
def cif_scatterers(
text: str,
settings: PatternSettings,
*,
block: str | None = None,
setting: str | None = None,
merge_tolerance: float = 0.01,
) -> tuple[np.ndarray, list[Scatterer], dict[str, Any]]:
"""Lattice, expanded scatterers and a record from a CIF, keeping partial occupancies.
Mixed and partially occupied sites keep their stated occupancy (they are what
the pattern needs); U_iso or B_iso come from ``_atom_site_U_iso_or_equiv`` /
``_atom_site_B_iso_or_equiv``. A site whose ADP type is ``Uani``/``Bani`` or
which appears in an ``_atom_site_aniso`` loop is refused.
"""
from vibesketcher.document import crystal
from vibesketcher.document.cif_import import _sites, _symmetry, number, parse
from vibesketcher.limits import check_size
check_size(text, "CIF")
blocks = parse(text)
if block is not None:
chosen = [b for b in blocks if b.name.lower() == block.lower()]
if not chosen:
raise ValueError(f"CIF data block {block!r} not found")
data = chosen[0]
else:
with_sites = [b for b in blocks if b.column("_atom_site_fract_x") is not None]
if len(with_sites) != 1:
raise ValueError(f"the CIF has {len(with_sites)} structure blocks; choose one")
data = with_sites[0]
aniso = data.column("_atom_site_aniso_label")
if aniso is not None or any(t.startswith(("_atom_site_aniso_u_", "_atom_site_aniso_b_"))
for loop in data.loops for t in loop): # fmt: skip
labels = ", ".join((aniso[1] if aniso else [])[:8])
raise ValueError(
"the CIF gives anisotropic displacement parameters"
+ (f" ({labels})" if labels else "")
+ "; they are not reduced to U_iso. Give isotropic values (b_iso/u_iso) in a CIF "
"without the aniso loop"
)
cell = [number(data.value(f"_cell_{k}"), f"_cell_{k}")[0]
for k in ("length_a", "length_b", "length_c", "angle_alpha", "angle_beta",
"angle_gamma")] # fmt: skip
lattice = crystal.cell_from_parameters(*cell)
operations, symmetry = _symmetry(data, setting)
sites = _sites(data)
found = data.column("_atom_site_fract_x")
assert found is not None
loop = found[0]
flags = loop.get("_atom_site_calc_flag")
keep = [i for i in range(len(found[1])) if not (flags and flags[i].lower() == "dum")]
def column(tag: str) -> list[str | None]:
values = loop.get(tag)
return [values[i] if values else None for i in keep]
adp_types, u_values, b_values = (column("_atom_site_adp_type"),
column("_atom_site_u_iso_or_equiv"),
column("_atom_site_b_iso_or_equiv")) # fmt: skip
out: list[Scatterer] = []
used: set[str] = set()
for site, adp, u, b in zip(sites, adp_types, u_values, b_values, strict=True):
if adp and adp.lower() in ("uani", "bani"):
raise ValueError(f"CIF site {site.label} is anisotropic ({adp}); refused, not "
"reduced to U_iso") # fmt: skip
used.update((site.label, site.element))
override = _lookup(settings.b_iso, site.label, site.element) or _lookup(
settings.u_iso, site.label, site.element
)
if override is not None:
b_iso, source = _displacement(settings, site.label, site.element)
elif b and b not in ("?", "."):
b_iso, source = number(b, f"B_iso of {site.label}")[0], "cif B_iso"
elif u and u not in ("?", "."):
b_iso, source = 8 * math.pi**2 * number(u, f"U_iso of {site.label}")[0], "cif U_iso"
else:
b_iso, source = settings.default_b_iso, "default_b_iso"
if not 0 <= b_iso <= 100:
raise ValueError(f"CIF site {site.label} has B = {b_iso:g} A^2")
occ = _lookup(settings.occupancy, site.label, site.element)
occupancy = occ[0] if occ else site.occupancy
images: list[np.ndarray] = []
for op in operations:
point = np.asarray(op.apply(tuple(site.fractional)), dtype=float) % 1.0
if not any(_distance(point, q, lattice) < merge_tolerance for q in images):
images.append(point)
for n, p in enumerate(images):
out.append(Scatterer(f"{site.label}_{n + 1}", site.element,
(float(p[0]), float(p[1]), float(p[2])), occupancy, b_iso,
source)) # fmt: skip
_unused(settings, used)
record = {"kind": "cif", "block": data.name, "symmetry": symmetry,
"asymmetric_sites": len(sites), "cell_sites": len(out),
"cif_sha256": hashlib.sha256(text.encode("utf-8")).hexdigest()} # fmt: skip
return lattice, out, record
def _distance(a: np.ndarray, b: np.ndarray, lattice: np.ndarray) -> float:
delta = (a - b + 0.5) % 1.0 - 0.5
return float(np.linalg.norm(delta @ lattice))
[docs]
def calculate_from_cif(
text: str,
settings: PatternSettings | None = None,
*,
block: str | None = None,
setting: str | None = None,
) -> dict[str, Any]:
"""The calculated powder pattern of a CIF block, with its occupancies and U_iso/B_iso."""
settings = settings or PatternSettings()
lattice, scatterers, record = cif_scatterers(text, settings, block=block, setting=setting)
result = calculate_pattern(lattice, scatterers, settings)
result["source"] = record
return result
[docs]
def parse_settings(data: dict[str, Any] | None) -> PatternSettings:
"""Validated settings from JSON (raises pydantic.ValidationError or ValueError)."""
return PatternSettings.model_validate(data or {})
[docs]
def reflections_csv(result: dict[str, Any]) -> str:
"""The reflection list as CSV with a provenance header."""
texture = (result.get("settings") or {}).get("preferred_orientation")
lines = [
f"# calculated powder pattern; wavelength {result['wavelength_angstrom']:.7f} A "
f"({result['wavelength_source']}); {result['polarisation']}",
f"# source {json.dumps(result.get('source', {}), sort_keys=True)}",
f"# form factors: {result['form_factors']}",
]
if texture:
lines.append(f"# {_texture_text(PreferredOrientation.model_validate(texture))}")
lines.append(
"h,k,l,multiplicity,d_angstrom,two_theta_deg,q_inv_angstrom,f_squared,lp,intensity,"
"relative_intensity" + (",preferred_orientation" if texture else "")
)
for r in result["reflections"]:
h, k, l_ = r["hkl"]
lines.append(
f"{h},{k},{l_},{r['multiplicity']},{r['d_angstrom']:.6f},{r['two_theta_deg']:.4f},"
f"{r['q_inv_angstrom']:.6f},{r['f_squared']:.6g},{r['lp']:.6g},"
f"{r['intensity']:.6g},{r['relative_intensity']:.4f}"
+ (f",{r['preferred_orientation']:.6g}" if texture else "")
)
return "\n".join(lines) + "\n"