merge: dev into feat/series4-sfm-parity -- v0.32.0, #42, #47/#49, #44/#45, the S3 decode checker

Brings the branch up to dev (41 commits) before the 1c bench fixes, which
touch code dev changed: the histogram reader (#47/#49, bench finding #2), the
v0.32.0 event-time rules, the Blastware file's setup-block fields (#44/#45),
and the decode checker for verifying stored S3 downloads.

One conflict: the top of the Series-III reference's change table -- both sides
added rows; kept all, in date order, CRLF preserved.  CLAUDE.md, README,
blastware_file.py, models.py and database.py merged cleanly.  Suite: the known
16 failures only (15 test_bw_ascii_report, test_save_imported_bw_without_report_
works_unchanged, which also fails on dev); 1237 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-10-29 22:51:42 -04:00
commit 342c69602d
54 files changed
+22279 -264

No files matched your search

+96
View File
@@ -41,6 +41,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")
@@ -519,6 +520,12 @@ class SeismoDb:
existing row so a re-download via the live endpoint refreshes the
file metadata.
An event whose stored file already has a row under a different time is
the same event re-stored with a corrected time (the waveform event-time
fix moved Series-3 waveforms from the session start to the trigger):
that row is moved to the new time in place, keeping its id and review,
rather than duplicated. See ``_restamp_by_file``.
``device_family`` (optional): "series3" (MiniMate Plus / Blastware) or
"series4" (Micromate / Thor). Drives per-family UI rendering — most
importantly the mic-unit convention (psi vs dB(L)). Set on every
@@ -547,6 +554,21 @@ class SeismoDb:
pi = ev.project_info
rec = wave_recs.get(key) or {}
if getattr(ev, "timestamp_source", None) == "estimate":
# No validated event record: the time may be a second off,
# so it is never allowed to move, merge into or duplicate
# a row (_estimate_guard). The file is already stored.
why = self._estimate_guard(conn, serial, rec.get("filename"), ts)
if why:
log.warning("insert_events: %s %s: %s", serial,
rec.get("filename") or key, why)
skipped += 1
continue
elif rec.get("filename") and ts and \
self._restamp_by_file(conn, serial, rec["filename"], ts) is False:
skipped += 1
continue
try:
conn.execute(
"""
@@ -704,6 +726,80 @@ class SeismoDb:
serial, inserted, skipped)
return inserted, skipped
@staticmethod
def _estimate_guard(conn: sqlite3.Connection, serial: str, filename: Optional[str],
ts: Optional[str]) -> Optional[str]:
"""Why an event whose time is only an estimate must not be written, or None.
An estimate (the decoder found no validated event record) may be a
second off, and (serial, timestamp) is the table's key. So it never
moves a row, never lands on another event's row, and never adds a second
row for an event already stored -- each refusal is logged by the caller,
and the event's file and sidecar are already in the store. Its own
row at the same second is refreshed as before; a free second is stored.
"""
named = filename if filename and blastware_filename_time(filename) is not None else None
if named:
own = [r[0] for r in conn.execute(
"SELECT timestamp FROM events WHERE serial = ? AND blastware_filename = ?",
(serial, named))]
if own and ts not in own:
return (f"already stored under {', '.join(str(t) for t in own)}; its estimated "
f"time {ts} does not move or duplicate it")
holder = conn.execute(
"SELECT blastware_filename FROM events WHERE serial = ? AND timestamp = ?",
(serial, ts)).fetchone()
if holder is not None and (named is None or holder[0] != named):
return (f"its estimated time {ts} is held by {holder[0] or 'another event'}; "
"not merged into it")
return None
@staticmethod
def _restamp_by_file(conn: sqlite3.Connection, serial: str, filename: str,
ts: str) -> Optional[bool]:
"""Move this file's row to `ts` when it sits under another time.
The events table is unique on (serial, timestamp), so an event re-stored
with a corrected time -- every Series-3 waveform after the event-time fix,
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. 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
`ts`), so the caller goes on as before; False when a different stored
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 COALESCE(false_trigger, 0) DESC, timestamp IS NULL, rowid LIMIT 1",
(serial, filename, ts),
).fetchone()
if mine is None:
return None
holder = conn.execute(
"SELECT id, blastware_filename FROM events WHERE serial = ? AND timestamp = ?",
(serial, ts),
).fetchone()
if holder is None:
conn.execute("UPDATE events SET timestamp = ? WHERE id = ?", (ts, mine[0]))
log.info("insert_events: %s %s moved from %s to %s (corrected event time)",
serial, filename, mine[1], ts)
return True
if holder[1] in (None, filename):
return None
log.warning("insert_events: %s %s decodes to %s, which %s already holds -- "
"row %s left at %s, nothing stored", serial, filename, ts, holder[1],
mine[0], mine[1])
return False
def get_event(self, event_id: str) -> Optional[dict]:
"""Return one event row by id, or None."""
with self._connect() as conn:
+16 -3
View File
@@ -139,17 +139,23 @@ def _ts_iso(ts) -> str:
def _samples_to_float(
samples_int16: list[int],
full_scale: float,
*,
ips_per_count: Optional[float] = None,
) -> np.ndarray:
"""Convert int16 ADC counts → float32 physical units.
Uses _GEO_INT16_FS=32000 (see the constant's rationale): one decoder
unit (16 ADC counts) is exactly 0.005 in/s, so full scale is 32000
counts, not 32768.
counts, not 32768. That is the MiniMate body codec's count; a source
with a different count scale passes ``ips_per_count`` instead (Thor:
``micromate.idf_file._GEO_LSB_IPS``).
"""
if not samples_int16:
return np.array([], dtype=np.float32)
if ips_per_count is None:
ips_per_count = full_scale / _GEO_INT16_FS
arr = np.asarray(samples_int16, dtype=np.int32) # int32 to avoid overflow during scale
return (arr.astype(np.float32) * (full_scale / _GEO_INT16_FS)).astype(np.float32)
return (arr.astype(np.float32) * ips_per_count).astype(np.float32)
def _mic_scale_factor(
@@ -179,10 +185,15 @@ def write_event_hdf5(
tool_version: Optional[str] = None,
captured_at: Optional[datetime.datetime] = None,
include_int16: bool = True,
geo_ips_per_count: Optional[float] = None,
) -> dict:
"""
Persist a decoded Event as an HDF5 file with samples in physical units.
``geo_ips_per_count`` overrides the range-derived MiniMate count scale
for sources whose counts differ — Thor IDF imports pass
``micromate.idf_file._GEO_LSB_IPS`` (issue #42).
Returns a small summary dict suitable for logging:
{"path": Path, "n_samples": int, "geo_full_scale_ips": float}
"""
@@ -199,7 +210,9 @@ def write_event_hdf5(
# Per-channel float32 arrays in physical units.
geo_arrays = {}
for ch in ("Tran", "Vert", "Long"):
geo_arrays[ch] = _samples_to_float(raw.get(ch, []), geo_fs)
geo_arrays[ch] = _samples_to_float(
raw.get(ch, []), geo_fs, ips_per_count=geo_ips_per_count,
)
# Mic channel — the per-count factor is resolved from the device-reported
# peak when available so the plot peaks the BW value exactly.
+9 -29
View File
@@ -323,29 +323,9 @@ class WaveformStore:
Returns (event, record_dict) so callers can both insert into
SeismoDb and surface the parsed Event.
"""
# Stash the bytes to a temp path so read_blastware_file (path-based)
# can parse without us duplicating its logic.
import tempfile
with tempfile.NamedTemporaryFile(suffix=".bw", delete=False) as tmp:
tmp.write(bw_bytes)
tmp_path = Path(tmp.name)
try:
ev = event_file_io.read_blastware_file(tmp_path)
finally:
try:
tmp_path.unlink()
except FileNotFoundError:
pass
# read_blastware_file derives record_type from its path arg, but
# that arg is the tmp file (suffix ".bw") — so override with the
# original filename's encoded type (H/W/M/E/C in the BW AB0T
# scheme). Without this override every BW-imported event lands
# in the DB with record_type="Waveform" regardless of the actual
# type (Histogram, Manual, etc.).
ev.record_type = event_file_io.derive_record_type_from_filename(
source_path.name
)
# Decode the bytes directly; the name only labels the record type and
# cross-checks the decoded time (event_file_io.decode_blastware_bytes).
ev = event_file_io.decode_blastware_bytes(bw_bytes, name=source_path.name)
# Parse the BW ASCII report if one was supplied. Failures here
# are non-fatal: we still write the binary + sidecar without the
@@ -653,11 +633,9 @@ class WaveformStore:
# caveats of this bridge (mic units, missing fields → sidecar).
ev = idf_event.to_minimateplus_event(waveform_key)
# Attach the decoded sample arrays. Thor's decoder counts use
# LSB = 0.0003 in/s for geo (vs BW's 16-count units at 0.005 in/s)
# — the .h5 writer's geo_range="normal" yields LSB = 10/32768
# ≈ 0.000305 in/s, so plotted samples come out ~1.7% high.
# Acceptable known offset; refine with a Thor-aware h5 path later.
# Attach the decoded sample arrays. These are raw Thor counts at
# _GEO_LSB_IPS = 0.000310308 in/s, not the MiniMate's 10/32000;
# the .h5 write below passes that scale explicitly (issue #42).
if idf_samples is not None:
ev.raw_samples = idf_samples
n_samples = max((len(idf_samples.get(ch, [])) for ch in ("Tran", "Vert", "Long", "MicL")), default=0)
@@ -673,7 +651,7 @@ class WaveformStore:
# a 1-sample-per-interval array so the existing h5+renderer pipeline
# (which groups samples down to ``n_intervals`` bars via max-per-group)
# produces a non-blank histogram chart. Each "sample" is the peak ADC
# count for that interval, so the h5 writer's ``count × geo_fs/32768``
# count for that interval, so the h5 writer's ``count × _GEO_LSB_IPS``
# conversion yields the right physical value for the bar height.
if is_histogram and idf_intervals:
hist_samples = {
@@ -692,11 +670,13 @@ class WaveformStore:
if ev.raw_samples:
hdf5_path = self.hdf5_path_for(serial, filename)
try:
from micromate.idf_file import _GEO_LSB_IPS
event_hdf5.write_event_hdf5(
hdf5_path, ev,
serial=serial,
geo_range="normal", # Thor's geo full scale is also 10 in/s (Normal)
source_kind="idf-import",
geo_ips_per_count=_GEO_LSB_IPS,
)
hdf5_filename = hdf5_path.name
except Exception as exc: