diff --git a/minimateplus/blastware_file.py b/minimateplus/blastware_file.py index 2784040..8ca5c9a 100644 --- a/minimateplus/blastware_file.py +++ b/minimateplus/blastware_file.py @@ -152,6 +152,7 @@ from __future__ import annotations import datetime import logging +import re import struct from pathlib import Path from typing import Optional, Union @@ -416,6 +417,31 @@ def _make_stem(ts_local: datetime.datetime) -> str: return s +_BW_NAME = re.compile(r"^[B-Z]\d{3}([0-9A-Z]{4})\.([0-9A-Z]{2})0[WH]?$") + + +def blastware_filename_time(name: str) -> Optional[datetime.datetime]: + """The event time a Blastware filename encodes, or None for any other name. + + The inverse of `blastware_filename`: `.0[W|H]`, + time = 1985-01-01 + stem*1296 + AB seconds. This is Blastware's own time + to the second -- it equals the report's Event Time on 1,330/1,330 + report-paired waveforms (81 prod-store, 1,249 DL2) and the report's + Histogram Start Time on 13,089/13,089 histograms (measured 2026-10-26). + Only the V10.72 `AB0` form is decoded; anything else gives None. + """ + m = _BW_NAME.match((name or "").upper()) + if not m: + return None + stem = 0 + for c in m.group(1): + stem = stem * 36 + _STEM_CHARS.index(c) + ab = _STEM_CHARS.index(m.group(2)[0]) * 36 + _STEM_CHARS.index(m.group(2)[1]) + if ab >= _STEM_UNIT_SEC: + return None + return _INSTANTEL_EPOCH + datetime.timedelta(seconds=stem * _STEM_UNIT_SEC + ab) + + def blastware_filename(event: Event, serial: str, ach: bool = False) -> str: """ Return the correct Blastware filename for an event. diff --git a/minimateplus/event_file_io.py b/minimateplus/event_file_io.py index 37d2b46..0b0aa14 100644 --- a/minimateplus/event_file_io.py +++ b/minimateplus/event_file_io.py @@ -859,14 +859,18 @@ def _parse_record_time_seconds(raw: bytes) -> Optional[float]: return rt if 0.05 <= rt <= 600.0 else None -def read_blastware_file(path: Union[str, Path]) -> Event: +def read_blastware_file(path: Union[str, Path], *, name: Optional[str] = None) -> Event: """ Parse a Blastware waveform file into an Event. + `name` is the file's real Blastware name when `path` is not (an upload + stashed under a temp name); it defaults to `path.name`. A waveform's time + comes from it when it is one (see the timestamp block below). + Recovers: - waveform_key, rectime_seconds, total_samples, pretrig_samples (from the STRT record) - - timestamp (from the footer's start-time field) + - timestamp (a waveform's from its Blastware filename, else the footer) - project_info (from ASCII labels embedded in the body) - raw_samples (Tran/Vert/Long/MicL int16 lists) - peak_values (computed from raw_samples; approximate — see notes @@ -878,6 +882,7 @@ def read_blastware_file(path: Union[str, Path]) -> Event: not possible — the on-disk BW file IS the byte-for-byte source. """ path = Path(path) + name = name or path.name raw = path.read_bytes() if len(raw) < _bw._WAVEFORM_HEADER_SIZE + 21 + 26: raise ValueError(f"{path}: file too short ({len(raw)} bytes) to be a BW event") @@ -998,7 +1003,7 @@ def read_blastware_file(path: Union[str, Path]) -> Event: # ".bw" suffix, so the derivation falls back to "Waveform" and the # caller overrides ev.record_type using the original filename — see # waveform_store.save_imported_bw. - ev.record_type = derive_record_type_from_filename(path.name) + ev.record_type = derive_record_type_from_filename(name) ev.rectime_seconds = strt_fields.get("rectime_seconds") ev.total_samples = strt_fields.get("total_samples") ev.pretrig_samples = strt_fields.get("pretrig_samples") @@ -1016,11 +1021,21 @@ def read_blastware_file(path: Union[str, Path]) -> Event: # * Histogram / undecodable: ts1 = the window start, which IS the event # time — keep it. # Discriminate by ``is_waveform_body`` (the codec), not the filename. + # + # ⚠ 2026-10-26 (measured): ts2 - record time is a second off on 260 of + # prod's 1,394 waveforms (199 late, 61 early). A Blastware filename + # carries Blastware's own time -- equal to the report's Event Time on + # 1,330/1,330 -- so a waveform takes it when `name` is one, and ts2 - + # record time only otherwise. Histograms stay on ts1 although it runs a + # second early on 97%: in Blastware's timing a waveform and its histogram + # share a second 209 times in prod's store, and events is unique on + # (serial, timestamp). if is_waveform_body and ts2 is not None: _stop = datetime.datetime(ts2.year, ts2.month, ts2.day, ts2.hour, ts2.minute, ts2.second) _rt = _parse_record_time_seconds(raw) _trig = _stop - datetime.timedelta(seconds=_rt) if _rt is not None else _stop + _trig = _bw.blastware_filename_time(name) or _trig ev.timestamp = Timestamp( raw=footer[10:18], flag=0x10, diff --git a/sfm/database.py b/sfm/database.py index 89b3141..12c5aa3 100644 --- a/sfm/database.py +++ b/sfm/database.py @@ -40,6 +40,7 @@ import uuid from pathlib import Path from typing import Optional +from minimateplus.blastware_file import blastware_filename_time from minimateplus.models import Event, MonitorLogEntry log = logging.getLogger("sfm.database") @@ -603,7 +604,9 @@ class SeismoDb: through the release backfill or a watcher re-forward -- matched nothing and was inserted a second time (measured 2026-10-26). The same stored file is the same event: a Blastware name encodes the serial and the time - to the second. + to the second. Any other name says nothing -- every unnamed upload is + stored as "imported.bw" -- so only a Blastware name is matched. Of + several rows for one file, a reviewed one with a time moves first. Returns True when the row was moved; None when there was nothing to move (no row for this file elsewhere, or this file's own row already holds @@ -611,9 +614,12 @@ class SeismoDb: file holds `ts` -- moving would collide, and the old upsert would write this event over that one -- so the caller must store nothing. """ + if blastware_filename_time(filename) is None: + return None mine = conn.execute( "SELECT id, timestamp FROM events WHERE serial = ? AND blastware_filename = ? " - "AND (timestamp IS NULL OR timestamp != ?) ORDER BY rowid LIMIT 1", + "AND (timestamp IS NULL OR timestamp != ?) " + "ORDER BY COALESCE(false_trigger, 0) DESC, timestamp IS NULL, rowid LIMIT 1", (serial, filename, ts), ).fetchone() if mine is None: diff --git a/sfm/waveform_store.py b/sfm/waveform_store.py index 01f6d66..7b26682 100644 --- a/sfm/waveform_store.py +++ b/sfm/waveform_store.py @@ -330,7 +330,7 @@ class WaveformStore: tmp.write(bw_bytes) tmp_path = Path(tmp.name) try: - ev = event_file_io.read_blastware_file(tmp_path) + ev = event_file_io.read_blastware_file(tmp_path, name=source_path.name) finally: try: tmp_path.unlink() diff --git a/tests/fixtures/minimate-bench-10-26-26-blastware/blastware/K441LTOF.ZI0 b/tests/fixtures/minimate-bench-10-26-26-blastware/blastware/K441LTOF.ZI0 new file mode 100644 index 0000000..8630f0f Binary files /dev/null and b/tests/fixtures/minimate-bench-10-26-26-blastware/blastware/K441LTOF.ZI0 differ diff --git a/tests/test_bw_filename_time.py b/tests/test_bw_filename_time.py new file mode 100644 index 0000000..244b8ee --- /dev/null +++ b/tests/test_bw_filename_time.py @@ -0,0 +1,105 @@ +"""A Series-3 waveform's time comes from its Blastware filename, which is Blastware's own. + +A Blastware name encodes the event time to the second (stem + AB, see +`blastware_filename`). Measured 2026-10-26: + + * name == the report's Event Time on 81/81 prod-snapshot and 1,249/1,249 DL2 + report-paired waveforms; + * the binary's trigger (ts2 - record time) is a second off on 260 of prod's + 1,394 waveforms (199 late, 61 early). On BE9558 the 61 early ones land on + their histogram twin's second, and events is unique on (serial, timestamp): + a fresh import wrote each waveform over its histogram's row. + +Histograms keep the binary's ts1. Their name is Blastware's start time too (13,089/13,089), +and ts1 runs a second early on 97% of them -- but in Blastware's timing a +waveform and its histogram share a second 209 times in prod's store, which a +(serial, timestamp) key cannot hold. That correction needs the key changed. +""" +from __future__ import annotations + +import datetime +import os +import sqlite3 +import sys +from pathlib import Path + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from minimateplus.blastware_file import blastware_filename, blastware_filename_time # noqa: E402 +from minimateplus.event_file_io import read_blastware_file # noqa: E402 +from minimateplus.models import Event, PeakValues, Timestamp # noqa: E402 +from sfm.database import SeismoDb # noqa: E402 +from sfm.waveform_store import WaveformStore # noqa: E402 + +FIX = Path(__file__).parent / "fixtures" +ZI0 = FIX / "minimate-bench-10-26-26-blastware" / "blastware" / "K441LTOF.ZI0" +HISTOGRAM = FIX / "ts-fix" / "K441LKZU.C30H" + + +def _dt(ts): + return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second) + + +def test_names_decode_to_the_documented_times(): + # the three S353L4H0 events the encoder was verified against, plus an H + assert blastware_filename_time("S353L4H0.3M0W") == datetime.datetime(2025, 6, 23, 13, 57, 22) + assert blastware_filename_time("S353L4H0.8S0H") == datetime.datetime(2025, 6, 23, 14, 0, 28) + assert blastware_filename_time("S353L4H0.9X0W") == datetime.datetime(2025, 6, 23, 14, 1, 9) + assert blastware_filename_time("P036L318.C80H") == datetime.datetime(2025, 5, 26, 15, 0, 8) + assert blastware_filename_time("K441LTOF.ZI0") == datetime.datetime(2026, 10, 26, 14, 23, 42) + assert blastware_filename_time("k441ltof.zi0") == datetime.datetime(2026, 10, 26, 14, 23, 42) + + +def test_the_decoder_inverts_the_encoder(): + for t in (datetime.datetime(2018, 1, 2, 3, 4, 5), datetime.datetime(2026, 10, 26, 23, 59, 59), + datetime.datetime(2026, 2, 28, 0, 0, 0)): + ev = Event(index=0) + ev.timestamp = Timestamp(raw=b"", flag=0x10, year=t.year, unknown_byte=0, month=t.month, + day=t.day, hour=t.hour, minute=t.minute, second=t.second) + assert blastware_filename_time(blastware_filename(ev, "BE9441")) == t + assert blastware_filename_time(blastware_filename(ev, "BE9441", ach=True)) == t + + +def test_other_names_give_nothing(): + for name in ("imported.bw", "UM12947_20260406130113.IDFW", "K441LTOF.ZI1", "K441LTOF.ZI0X", + "K441LTO.ZI0", "K441LTOF.Z!0", "", "BE9441.MLG"): + assert blastware_filename_time(name) is None, name + + +def test_a_waveform_takes_its_names_time_not_the_binarys(): + # BE9441, 2026-10-26: the binary says 14:23:43, Blastware (and the name) 14:23:42 + assert _dt(read_blastware_file(ZI0).timestamp) == datetime.datetime(2026, 10, 26, 14, 23, 42) + + +def test_a_waveform_read_under_another_name_is_told_its_real_one(tmp_path): + tmp = tmp_path / "upload.bw" + tmp.write_bytes(ZI0.read_bytes()) + assert _dt(read_blastware_file(tmp).timestamp) == datetime.datetime(2026, 10, 26, 14, 23, 43) + assert _dt(read_blastware_file(tmp, name=ZI0.name).timestamp) == \ + datetime.datetime(2026, 10, 26, 14, 23, 42) + + +def test_a_histogram_keeps_the_binarys_window_start(): + assert blastware_filename_time(HISTOGRAM.name) != datetime.datetime(2026, 5, 10, 19, 4, 50) + assert _dt(read_blastware_file(HISTOGRAM).timestamp) == datetime.datetime(2026, 5, 10, 19, 4, 50) + + +def test_an_import_no_longer_lands_a_waveform_on_its_histogram_twins_row(tmp_path): + """BE9558's 61: the binary's second was the histogram twin's. Built here from + BE9441's ZI0: a histogram row at the binary's 14:23:43, then the waveform.""" + store, db = WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo_relay.db") + hist = Event(index=0) + hist.timestamp = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=10, day=26, + hour=14, minute=23, second=43) + hist._waveform_key = bytes.fromhex("01110000") + hist.peak_values = PeakValues(tran=0.01, vert=0.02, long=0.03, peak_vector_sum=0.04, micl=None) + db.insert_events([hist], serial="BE9441", device_family="series3", + waveform_records={"01110000": {"filename": "K441LTOF.ZJ0H"}}) + + ev, rec = store.save_imported_bw(ZI0.read_bytes(), source_path=Path(ZI0.name)) + db.insert_events([ev], serial="BE9441", device_family="series3", + waveform_records={ev._waveform_key.hex(): rec}) + + with sqlite3.connect(str(db.db_path)) as c: + rows = c.execute("SELECT blastware_filename, timestamp FROM events ORDER BY timestamp").fetchall() + assert rows == [("K441LTOF.ZI0", "2026-10-26T14:23:42"), ("K441LTOF.ZJ0H", "2026-10-26T14:23:43")] diff --git a/tests/test_event_restamp.py b/tests/test_event_restamp.py index 3e1b2ab..98b7013 100644 --- a/tests/test_event_restamp.py +++ b/tests/test_event_restamp.py @@ -130,3 +130,29 @@ def test_the_release_backfill_corrects_a_v031_row_in_place(tmp_path): (row,) = _rows(db) assert (row["id"], row["timestamp"], row["false_trigger"]) == (old["id"], NEW_TIME, 1) + + +def test_a_generic_upload_name_is_not_one_event(tmp_path): + # Unnamed uploads are all stored as "imported.bw": two different events can + # share it. Only a Blastware name says which event a row is. + db = SeismoDb(tmp_path / "seismo_relay.db") + _store(db, _event(OLD_TIME), filename="imported.bw") + _store(db, _event(NEW_TIME, key="01118a2c"), filename="imported.bw") + assert [r["timestamp"] for r in _rows(db)] == [OLD_TIME, NEW_TIME] + + +def test_of_two_copies_the_reviewed_one_with_a_time_is_the_one_moved(tmp_path): + db = SeismoDb(tmp_path / "seismo_relay.db") + db.insert_events([_event(OLD_TIME)], serial="BE12844", device_family="series3", + waveform_records={"0111646a": {"filename": "N844LQHB.ZT0W"}}) + with sqlite3.connect(str(db.db_path)) as c: # an older copy with no time + c.execute("INSERT INTO events (id, serial, waveform_key, timestamp, blastware_filename) " + "VALUES ('untimed', 'BE12844', '0111646a', NULL, 'N844LQHB.ZT0W')") + c.execute("UPDATE events SET rowid = 0 WHERE id = 'untimed'") + reviewed = next(r["id"] for r in _rows(db) if r["timestamp"] == OLD_TIME) + db.set_false_trigger(reviewed, True) + + _store(db, _event(NEW_TIME)) + + moved = {r["id"]: r["timestamp"] for r in _rows(db)} + assert moved[reviewed] == NEW_TIME and moved["untimed"] is None