vibe-sketcherDocumentation

Source code for vibesketcher.document.measured_gsas

"""GSAS standard powder data files, constant-wavelength banks, read fail-closed (#279).

Written from the GSAS manual, "GSAS Standard Powder Data File" (A. C. Larson and
R. B. Von Dreele, General Structure Analysis System, Los Alamos National Laboratory
Report LAUR 86-748, technical manual pp. 217-220). No third-party reader is used.
The evaluation and the maintainer's approval are in docs/powder_formats.md and #273.

Only ``BINTYP`` ``CONS`` banks are read, as 2theta in centidegrees when the caller
states ``two_theta_deg``. Layouts ``STD``, ``ESD``, ``FXY`` and ``FXYE`` are
accepted; ``TIME_MAP``, other binnings, ``ALT``, bank 0, and mismatched counts are
refused with a coded :class:`GsasRefused`. The wavelength is taken only as the
caller states it (it lives in the instrument parameter file, not the data file).
"""

from __future__ import annotations

import math
from typing import Any

#: The one binning type read: constant steps.
BINNING = "CONS"
#: Every binning type the manual defines, for a precise refusal.
KNOWN_BINNINGS = ("CONS", "COND", "CONQ", "EDS", "LOG6", "LPSD", "RALF", "SLOG", "TIME_MAP")
LAYOUTS = ("STD", "ESD", "FXY", "FXYE")
RECORD_LENGTH = 80


[docs] class GsasRefused(ValueError): """The GSAS file cannot be read faithfully; ``code`` says why.""" def __init__(self, message: str, code: str = "diffraction.gsas_refused") -> None: super().__init__(message) self.code = code
def _number(text: str, what: str) -> float: try: value = float(text) except ValueError: raise GsasRefused(f"{what}: {text.strip()!r} is not a number") from None if not math.isfinite(value): raise GsasRefused(f"{what}: {text.strip()!r} is not finite") return value def _fields(record: str, width: int, count: int) -> list[str]: padded = record.ljust(RECORD_LENGTH) return [padded[i * width : (i + 1) * width] for i in range(count)]
[docs] def read_gsas(data: bytes, name: str, bank: int | None = None) -> dict[str, Any]: """The 2theta points, intensities, esds and header of one constant-step GSAS bank. Returns ``{"x", "intensity", "esd", "header", "metadata"}``; refuses with a coded :class:`GsasRefused`. """ try: text = data.decode("ascii") except UnicodeDecodeError: raise GsasRefused(f"{name}: GSAS records are ASCII") from None records = text.replace("\r\n", "\n").replace("\r", "\n").split("\n") if records and records[-1] == "": records.pop() long_records = [i + 1 for i, r in enumerate(records) if len(r) > RECORD_LENGTH] if long_records: raise GsasRefused( f"{name}: record {long_records[0]} is longer than {RECORD_LENGTH} characters; " "GSAS records are 80 characters", "diffraction.gsas_layout", ) if not records: raise GsasRefused(f"{name}: an empty file") title = records[0].rstrip() header = [f"title: {title}"] if title else [] instrument = None blocks: list[tuple[int, list[str], list[str]]] = [] comments: list[str] = [] i = 1 while i < len(records): record = records[i] if i == 1 and record.startswith("Instrument parameter"): instrument = record[20:].strip() elif record.startswith("#"): comments.append(record[1:].strip()) elif record.startswith("TIME_MAP"): raise GsasRefused( f"{name}: a TIME_MAP block (time-of-flight data) is not read", "diffraction.gsas_binning", ) elif record.startswith("BANK"): blocks.append((i, record.split(), comments)) comments = [] elif blocks: pass # a data record of the current block elif record.strip(): raise GsasRefused( f"{name}: record {i + 1} comes before any BANK record", "diffraction.gsas_layout" ) i += 1 if not blocks: raise GsasRefused(f"{name}: no BANK record", "diffraction.gsas_layout") numbers = [] for _, fields, _ in blocks: if len(fields) < 2: raise GsasRefused( f"{name}: a BANK record without its bank number", "diffraction.gsas_layout" ) numbers.append(int(_number(fields[1], "IBANK"))) if len(set(numbers)) != len(numbers): raise GsasRefused(f"{name}: bank numbers repeat ({numbers})", "diffraction.gsas_layout") if bank is None: if len(blocks) > 1: raise GsasRefused( f"{name}: {len(blocks)} banks ({', '.join(map(str, numbers))}); choose one", "diffraction.gsas_bank", ) chosen = 0 elif bank in numbers: chosen = numbers.index(bank) else: raise GsasRefused( f"{name}: no bank {bank} (banks {', '.join(map(str, numbers))})", "diffraction.gsas_bank", ) start, fields, notes = blocks[chosen] end = ( blocks[chosen + 1][0] - len(blocks[chosen + 1][2]) if chosen + 1 < len(blocks) else len(records) ) if numbers[chosen] == 0: raise GsasRefused( f"{name}: bank 0 is the incident beam monitor, not a pattern", "diffraction.gsas_bank" ) if len(fields) < 9: raise GsasRefused( f"{name}: the BANK record has {len(fields)} fields; it needs IBANK, " "NCHAN, NREC, BINTYP and four coefficients", "diffraction.gsas_layout", ) nchan = int(_number(fields[2], "NCHAN")) nrec = int(_number(fields[3], "NREC")) binning = fields[4] coefficients = [_number(f, f"BCOEF({k + 1})") for k, f in enumerate(fields[5:9])] layout = fields[9] if len(fields) > 9 else "STD" if binning != BINNING: known = "a binning the manual defines" if binning in KNOWN_BINNINGS else "unknown" raise GsasRefused( f"{name}: BINTYP {binning} ({known}) is not read; only constant-step CONS banks are", "diffraction.gsas_binning", ) if layout not in LAYOUTS: raise GsasRefused( f"{name}: data type {layout} is not read ({', '.join(LAYOUTS)})", "diffraction.gsas_layout", ) if nchan < 2: raise GsasRefused(f"{name}: fewer than two data points") data_records = [r for r in records[start + 1 : end] if not r.startswith("#")] per_record = {"STD": 10, "ESD": 5, "FXY": 1, "FXYE": 1}[layout] expected = -(-nchan // per_record) if nrec != expected or len(data_records) < nrec: raise GsasRefused( f"{name}: bank {numbers[chosen]} states {nrec} records for {nchan} {layout} points; " f"{expected} are needed and {len(data_records)} follow", "diffraction.gsas_layout", ) data_records = data_records[:nrec] intensity: list[float] = [] esd: list[float] | None = None x: list[float] if layout == "STD": for record in data_records: for field in _fields(record, 8, 10): if not field.strip(): continue counters = field[:2].strip() if counters not in ("", "0", "1"): raise GsasRefused( f"{name}: {counters} counters at a step; the counts per counter are not " "rescaled here", "diffraction.gsas_layout", ) intensity.append(_number(field[2:], "YO")) x = [(coefficients[0] + k * coefficients[1]) / 100 for k in range(nchan)] elif layout == "ESD": esd = [] for record in data_records: for pair in range(5): value, error = _fields(record, 8, 10)[2 * pair : 2 * pair + 2] if not value.strip(): continue intensity.append(_number(value, "YOT")) esd.append(_number(error, "YE")) x = [(coefficients[0] + k * coefficients[1]) / 100 for k in range(nchan)] else: esd = [] if layout == "FXYE" else None x = [] for record in data_records: values = record.split() if len(values) < (3 if layout == "FXYE" else 2): raise GsasRefused( f"{name}: an {layout} record needs position, intensity" + (" and esd" if layout == "FXYE" else ""), "diffraction.gsas_layout", ) x.append(_number(values[0], "position") / 100) intensity.append(_number(values[1], "intensity")) if esd is not None: esd.append(_number(values[2], "esd")) if len(intensity) != nchan or (esd is not None and len(esd) != nchan): raise GsasRefused( f"{name}: bank {numbers[chosen]} states {nchan} points and {len(intensity)} are given", "diffraction.gsas_layout", ) if not all(0 < v < 180 for v in x): raise GsasRefused( f"{name}: positions run from {min(x):g} to {max(x):g} degrees, outside (0, 180); a " "CONS bank in microseconds or keV is not a 2theta pattern", "diffraction.unknown_axis", ) metadata = { "format": "GSAS standard powder data", "bank": str(numbers[chosen]), "banks": str(len(blocks)), "nchan": str(nchan), "binning": binning, "layout": layout, "start_centideg": repr(coefficients[0]), "step_centideg": repr(coefficients[1]), } if instrument: metadata["instrument_parameter_file"] = instrument return { "x": x, "intensity": intensity, "esd": esd, "header": [*header, *(f"# {c}" for c in notes)][:200], "metadata": {k: v[:500] for k, v in metadata.items()}, }