vibe-sketcherDocumentation

Source code for vibesketcher.document.measured_xrdml

"""PANalytical / Malvern Panalytical XRDML measured patterns, read fail-closed (#278).

Written from the published XML schemas, XRDMeasurement 1.0 to 2.4 (Malvern
Panalytical, Data Collector download; T. Degen, NOBUGS 2002, arXiv:physics/0210067).
No third-party reader is used and the schema files are not bundled. The evaluation
and the maintainer's approval are in docs/powder_formats.md and #273.

What is read, with the element names of the schema:

- the namespace ``http://www.xrdml.com/XRDMeasurement/<version>``, which must be a
  published version;
- one ``xrdMeasurement`` with ``measurementType`` ``Scan`` or ``Repeated scan`` and
  one ``scan`` chosen by index when there are several, whose ``scanAxis`` is
  ``2Theta`` or ``Gonio``. The ``status`` of the file, the measurement and the scan
  must all be ``Completed``;
- ``usedWavelength`` (``kAlpha1``, ``kAlpha2``, ``kBeta``, ``ratioKAlpha2KAlpha1`` and
  the ``intended`` line). The schema makes it optional; a 2theta pattern without it
  is refused. The intended line (K-Alpha 1, K-Alpha 2, K-Beta, or K-Alpha for the
  unresolved doublet, recorded at Kalpha1) gives the recorded wavelength;
- the ``positions`` of ``axis="2Theta"`` in degrees, as ``startPosition``/``endPosition``
  (constant steps: step = (end - start) / (points - 1)) or ``listPositions``;
- the data: ``intensities`` (schema 1.x: already multiplied by the beam-attenuation
  factor) or ``counts`` (2.0 onward: "not yet corrected for beam attenuator- or
  divergence factors"). Counts are read only when every attenuation factor and
  divergence correction is 1, or absent; otherwise the file is refused rather than
  corrected by a guess;
- the counting time (``commonCountingTime`` or ``countingTimes``), the tube
  (``anodeMaterial``, ``tension``, ``current``), the scan ``mode``, the header's
  ``source`` and ``startTimeStamp``, and comment entries, kept as given.

Any document type declaration or entity declaration is refused before parsing, so
the parse stays bounded.
"""

from __future__ import annotations

import math
import re
import xml.etree.ElementTree as ET
from typing import Any

#: Published schema versions (XRDMeasurement*.xsd in the Data Collector download).
VERSIONS = (
    "1.0",
    "1.1",
    "1.2",
    "1.3",
    "1.4",
    "1.5",
    "1.6",
    "1.7",
    "2.0",
    "2.1",
    "2.2",
    "2.3",
    "2.4",
)
NAMESPACE = "http://www.xrdml.com/XRDMeasurement/"
SCAN_AXES = ("2Theta", "Gonio")
MEASUREMENT_TYPES = ("Scan", "Repeated scan")
#: The intended line -> the usedWavelength element that is the recorded wavelength.
INTENDED = {"K-Alpha 1": "kAlpha1", "K-Alpha": "kAlpha1", "K-Alpha 2": "kAlpha2", "K-Beta": "kBeta"}


[docs] class XrdmlRefused(ValueError): """The XRDML file cannot be read faithfully; ``code`` says why.""" def __init__(self, message: str, code: str = "diffraction.xrdml_refused") -> None: super().__init__(message) self.code = code
def _floats(text: str | None, what: str) -> list[float]: try: values = [float(v) for v in (text or "").split()] except ValueError: raise XrdmlRefused(f"{what} holds a value that is not a number") from None if not all(math.isfinite(v) for v in values): raise XrdmlRefused(f"{what} holds a value that is not finite") return values
[docs] def read_xrdml(data: bytes, name: str, scan: int | None = None) -> dict[str, Any]: """The 2theta points, intensities and file metadata of one XRDML scan. Returns ``{"x", "intensity", "wavelength_angstrom", "metadata", "header", "intensity_unit"}``; refuses with a coded :class:`XrdmlRefused`. """ head = data[:65536].lower() if b"<!doctype" in head or b"<!entity" in data.lower(): raise XrdmlRefused( f"{name}: document type or entity declarations are refused", "diffraction.xrdml_declaration", ) try: root = ET.fromstring(data) except ET.ParseError as error: raise XrdmlRefused(f"{name}: not well-formed XML ({error})") from None match = re.fullmatch(r"\{" + re.escape(NAMESPACE) + r"(\d\.\d)\}xrdMeasurements", root.tag) if match is None or match.group(1) not in VERSIONS: raise XrdmlRefused( f"{name}: not an XRDML document of a published schema version " f"({', '.join(VERSIONS)}); root {root.tag!r}", "diffraction.xrdml_version", ) version = match.group(1) ns = {"x": f"{NAMESPACE}{version}"} def status(element: ET.Element, what: str) -> None: if element.get("status") != "Completed": raise XrdmlRefused( f"{name}: the {what} status is {element.get('status')!r}, not 'Completed'", "diffraction.xrdml_incomplete", ) status(root, "file") measurements = root.findall("x:xrdMeasurement", ns) if len(measurements) != 1: raise XrdmlRefused( f"{name}: {len(measurements)} measurements; one is read", "diffraction.xrdml_scan" ) (measurement,) = measurements status(measurement, "measurement") kind = measurement.get("measurementType") if kind not in MEASUREMENT_TYPES: raise XrdmlRefused( f"{name}: measurement type {kind!r} is not a powder scan " f"({', '.join(MEASUREMENT_TYPES)})", "diffraction.xrdml_scan", ) scans = measurement.findall("x:scan", ns) if not scans: raise XrdmlRefused(f"{name}: the measurement has no scan", "diffraction.xrdml_scan") if scan is None and len(scans) > 1: raise XrdmlRefused( f"{name}: {len(scans)} scans; choose one by index (0 to {len(scans) - 1})", "diffraction.xrdml_scan", ) index = scan or 0 if not 0 <= index < len(scans): raise XrdmlRefused( f"{name}: scan index {index} is not in 0 to {len(scans) - 1}", "diffraction.xrdml_scan" ) chosen = scans[index] status(chosen, "scan") axis = chosen.get("scanAxis") if axis not in SCAN_AXES: raise XrdmlRefused( f"{name}: scan axis {axis!r} is not a 2theta powder scan ({', '.join(SCAN_AXES)})", "diffraction.unknown_axis", ) used = measurement.find("x:usedWavelength", ns) if used is None: raise XrdmlRefused( f"{name}: the file states no usedWavelength; a 2theta pattern needs it", "diffraction.wavelength_unstated", ) lines: dict[str, float] = {} for line in ("kAlpha1", "kAlpha2", "kBeta", "ratioKAlpha2KAlpha1"): found = used.find(f"x:{line}", ns) if found is not None: (value,) = _floats(found.text, line) or [math.nan] lines[line] = value intended = used.get("intended") if intended not in INTENDED or INTENDED[intended] not in lines: raise XrdmlRefused( f"{name}: intended wavelength {intended!r} is not stated with its value", "diffraction.wavelength_unstated", ) wavelength = lines[INTENDED[intended]] if not 0.01 < wavelength <= 100: raise XrdmlRefused(f"{name}: wavelength {wavelength} A is out of range") points = chosen.find("x:dataPoints", ns) if points is None: raise XrdmlRefused(f"{name}: the scan has no dataPoints") data_element = points.find("x:counts" if version >= "2" else "x:intensities", ns) if data_element is None: data_element = points.find("x:intensities", ns) if data_element is None: raise XrdmlRefused(f"{name}: the scan has no counts or intensities") values = _floats(data_element.text, data_element.tag.split("}")[1]) if len(values) < 2: raise XrdmlRefused(f"{name}: fewer than two data points") raw = data_element.tag.endswith("}counts") corrections: dict[str, str] = {} for common, per_point in ( ("commonBeamAttenuationFactor", "beamAttenuationFactors"), ("commonDivergenceCorrection", "divergenceCorrections"), ): found = points.find(f"x:{common}", ns) factors = _floats(found.text, common) if found is not None else [] listed = points.find(f"x:{per_point}", ns) if listed is not None: factors = _floats(listed.text, per_point) if len(factors) != len(values): raise XrdmlRefused( f"{name}: {per_point} has {len(factors)} values for {len(values)} points" ) if factors: corrections[common] = "1" if all(f == 1 for f in factors) else "varies" if raw and any(f != 1 for f in factors): raise XrdmlRefused( f"{name}: the counts are not corrected for {common.removeprefix('common')} " "factors other than 1 (schema 2.x); they are refused rather than corrected here", "diffraction.xrdml_uncorrected", ) two_theta = None for positions in points.findall("x:positions", ns): if positions.get("axis") != "2Theta": continue if positions.get("unit") != "deg": raise XrdmlRefused( f"{name}: 2Theta positions are in {positions.get('unit')!r}, not degrees" ) listed = positions.find("x:listPositions", ns) start, end = positions.find("x:startPosition", ns), positions.find("x:endPosition", ns) if listed is not None: two_theta = _floats(listed.text, "listPositions") elif start is not None and end is not None: (lo,), (hi,) = _floats(start.text, "startPosition"), _floats(end.text, "endPosition") step = (hi - lo) / (len(values) - 1) two_theta = [lo + i * step for i in range(len(values))] else: raise XrdmlRefused(f"{name}: the 2Theta positions are a common position, not a scan") if two_theta is None: raise XrdmlRefused(f"{name}: the scan has no 2Theta positions", "diffraction.unknown_axis") if len(two_theta) != len(values): raise XrdmlRefused(f"{name}: {len(two_theta)} positions for {len(values)} data points") metadata: dict[str, str] = { "format": "XRDML", "schema_version": version, "measurement_type": str(kind), "scan_index": str(index), "scans": str(len(scans)), "scan_axis": str(axis), "scan_mode": str(chosen.get("mode")), "intended_wavelength": str(intended), "data": "counts (raw)" if raw else "intensities (attenuation applied)", } for key, value in lines.items(): metadata[key] = repr(value) for key, path in ( ("anode", "x:incidentBeamPath/x:xRayTube/x:anodeMaterial"), ("tension", "x:incidentBeamPath/x:xRayTube/x:tension"), ("current", "x:incidentBeamPath/x:xRayTube/x:current"), ): found = measurement.find(path, ns) if found is not None and found.text: unit = found.get("unit") metadata[key] = found.text.strip() + (f" {unit}" if unit else "") timing = points.find("x:commonCountingTime", ns) if timing is not None and timing.text: metadata["counting_time_s"] = timing.text.strip() elif points.find("x:countingTimes", ns) is not None: metadata["counting_time_s"] = "per point" metadata.update(corrections) header = chosen.find("x:header", ns) if header is not None: for key, path in ( ("start_time", "x:startTimeStamp"), ("application", "x:source/x:applicationSoftware"), ): found = header.find(path, ns) if found is not None and found.text: metadata[key] = found.text.strip() comments = [ e.text.strip() for e in root.iterfind(".//x:comment/x:entry", ns) if e.text and e.text.strip() ][:200] return { "x": two_theta, "intensity": values, "wavelength_angstrom": wavelength, "metadata": {k: v[:500] for k, v in metadata.items()}, "header": [c[:500] for c in comments], "intensity_unit": "counts", }