Files
seismo-relay/minimateplus/bw_xml_report.py
T
serversdownandClaude Opus 5.5 52809a5310 feat(codec): parse Blastware's _XML.XML event report
The reference for the Series 3 decode checker: scalars and value units,
channels, the job number, the user notes in order under their
operator-edited labels, waveform rows as printed (ragged where channels
end at different lengths) and histogram intervals.  Seven real DL2
events as fixtures, each covering a case the comparison must handle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-10-29 19:23:43 -04:00

134 lines
5.0 KiB
Python

"""
minimateplus/bw_xml_report.py — parse Blastware's `_XML.XML` event report.
Blastware's ACH keeps, in `Sent/`, a full XML report beside each event binary:
`<stem>_<ext>_XML.XML` for `<stem>.<ext>`. It carries every field of the event
report plus every waveform sample or histogram interval, and DL2's backup holds
one for 70,042 Series 3 events back to 2016 (its ASCII reports start in 2025).
SFM uses it only to check its own decode, never as data.
The small `<stem>_<ext>.XML` summary beside it writes decimal commas and is not
this file.
Layout (FileVersion 8.0), as the parser reads it:
- top-level simple elements, e.g. ``<SampleRate>1024 sps</SampleRate>``
- value elements, e.g. ``<TranPPV><Value>0.015</Value><Units>in/s</Units></TranPPV>``
- ``<Channels><Channel>Tran</Channel>...</Channels>``
- the job number and up to four user notes, between the top-level
``<Units>`` and ``<GeoRange>``; each note is tagged with its
operator-editable label (``Project``, ``Location``, ``Seis.Loc`` ...) and
an empty note is omitted
- waveform: ``WaveformDataChannels/Data/Row/Cell``. A row holds only the
channels still running: where channels end at different lengths, the last
rows have fewer cells
- histogram: ``HistogramData`` with ``HistogramDataColumnTitle/ColumnTitle``
and ``HistogramDataIntervals``, alternating ``Time`` and ``Row``
Cell and value text is kept exactly as printed (``">100"``, ``"N/A"``,
``"OORANGE"``, ``"6.7 Volts"``); interpreting it is the comparison's job.
Pure: no I/O beyond reading the file passed to `parse_xml_report_file`.
"""
from __future__ import annotations
import xml.etree.ElementTree as ET
from dataclasses import dataclass
from pathlib import Path
from typing import Optional, Union
@dataclass
class XmlReport:
scalars: dict[str, str]
units: dict[str, str]
event_units: Optional[str]
channels: list[str]
job_number: Optional[str]
notes: list[tuple[str, str]]
sample_rows: Optional[list[list[str]]]
interval_columns: Optional[list[str]]
intervals: Optional[list[tuple[str, list[str]]]]
def _text(el: ET.Element) -> str:
return (el.text or "").strip()
def _cells(row: ET.Element) -> list[str]:
return [_text(c) for c in row.findall("Cell")]
def parse_xml_report(data: bytes) -> XmlReport:
"""Parse the bytes of an `_XML.XML` event report. Raises ValueError when
they are not well-formed XML (a truncated file, for one)."""
try:
root = ET.fromstring(data)
except ET.ParseError as exc:
raise ValueError(f"not a well-formed XML report: {exc}") from exc
scalars: dict[str, str] = {}
units: dict[str, str] = {}
event_units: Optional[str] = None
channels: list[str] = []
job_number: Optional[str] = None
notes: list[tuple[str, str]] = []
sample_rows: Optional[list[list[str]]] = None
interval_columns: Optional[list[str]] = None
intervals: Optional[list[tuple[str, list[str]]]] = None
in_notes = False
for el in root:
tag = el.tag
if tag == "Units" and len(el) == 0:
event_units = _text(el)
scalars[tag] = event_units
in_notes = True
continue
if tag == "GeoRange":
in_notes = False
if in_notes and len(el) == 0:
# Job number and user notes: never scalars, so the comparison
# scores each once.
if tag == "JobNumber":
job_number = _text(el)
elif _text(el):
notes.append((tag, _text(el)))
continue
if tag == "Channels":
channels = [_text(c) for c in el.findall("Channel")]
elif tag == "WaveformDataChannels":
data_el = el.find("Data")
if data_el is not None:
sample_rows = [_cells(r) for r in data_el.findall("Row")]
elif tag == "HistogramData":
titles = el.find("HistogramDataColumnTitle")
interval_columns = ([" ".join(_text(t).split()) for t in titles.findall("ColumnTitle")]
if titles is not None else [])
body = el.find("HistogramDataIntervals")
intervals = []
time: Optional[str] = None
for child in (body if body is not None else []):
if child.tag == "Time":
time = _text(child)
elif child.tag == "Row":
intervals.append((time or "", _cells(child)))
time = None
elif el.find("Value") is not None:
scalars[tag] = _text(el.find("Value"))
u = el.find("Units")
if u is not None:
units[tag] = _text(u)
elif len(el) == 0:
scalars[tag] = _text(el)
return XmlReport(
scalars=scalars, units=units, event_units=event_units, channels=channels,
job_number=job_number, notes=notes, sample_rows=sample_rows,
interval_columns=interval_columns, intervals=intervals,
)
def parse_xml_report_file(path: Union[str, Path]) -> XmlReport:
return parse_xml_report(Path(path).read_bytes())