merge: events are identified by unit + time + type, and histograms take Blastware's times (#51)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
This commit is contained in:
commit
074c98823f
10 files changed
+381
-47
No files matched your search
@@ -13,13 +13,14 @@ Pure: no I/O, and no import from `sfm/`.
|
|||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import datetime
|
||||||
import math
|
import math
|
||||||
import re
|
import re
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import Callable, Optional, Sequence
|
from typing import Callable, Optional, Sequence
|
||||||
|
|
||||||
from .bw_xml_report import XmlReport
|
from .bw_xml_report import XmlReport
|
||||||
from .event_file_io import (_GEO_FS_BY_RANGE, _GEO_INT16_FS, _GEO_NORMAL_FS_INS, _MIC_PSI_PER_COUNT,
|
from .event_file_io import (interval_times, _GEO_FS_BY_RANGE, _GEO_INT16_FS, _GEO_NORMAL_FS_INS, _MIC_PSI_PER_COUNT,
|
||||||
decode_blastware_bytes)
|
decode_blastware_bytes)
|
||||||
from .histogram_codec import half_period_to_hz
|
from .histogram_codec import half_period_to_hz
|
||||||
from .models import Event
|
from .models import Event
|
||||||
@@ -88,6 +89,7 @@ class SfmSide:
|
|||||||
geo_ips_per_count: float = GEO_IPS_PER_COUNT # at the event's range, as SFM read it
|
geo_ips_per_count: float = GEO_IPS_PER_COUNT # at the event's range, as SFM read it
|
||||||
# interval column -> SFM's value per interval (a number, or Blastware's word)
|
# interval column -> SFM's value per interval (a number, or Blastware's word)
|
||||||
interval_values: dict[str, list[object]] = field(default_factory=dict)
|
interval_values: dict[str, list[object]] = field(default_factory=dict)
|
||||||
|
interval_times: Optional[list[str]] = None # each interval's printed time
|
||||||
|
|
||||||
|
|
||||||
def interval_frequency(halfp: int, sample_rate: int) -> object:
|
def interval_frequency(halfp: int, sample_rate: int) -> object:
|
||||||
@@ -150,6 +152,20 @@ def sfm_side(raw: bytes) -> SfmSide:
|
|||||||
interval_values[f"{ch} Freq Hz"] = [interval_frequency(h, ev.sample_rate) for h in hps]
|
interval_values[f"{ch} Freq Hz"] = [interval_frequency(h, ev.sample_rate) for h in hps]
|
||||||
if ev.interval_pvs:
|
if ev.interval_pvs:
|
||||||
interval_values["Geo PVS in/s"] = list(ev.interval_pvs)
|
interval_values["Geo PVS in/s"] = list(ev.interval_pvs)
|
||||||
|
times = None
|
||||||
|
n = len(counts["Tran"])
|
||||||
|
if ev.record_type == "Histogram" and ts is not None and ev.histogram_interval_sec and n:
|
||||||
|
start = datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
|
||||||
|
ends = interval_times(start, ev.histogram_interval_sec, ev.stop_time, n)
|
||||||
|
times = [t.strftime("%Y-%m-%d %H:%M:%S") for t in ends]
|
||||||
|
# A peak's date and time are those of the interval holding it (first).
|
||||||
|
for tag, series in (("TranPeak", counts["Tran"]), ("VertPeak", counts["Vert"]),
|
||||||
|
("LongPeak", counts["Long"]), ("MicL", counts["MicL"]),
|
||||||
|
("PeakVectorSum", ev.interval_pvs)):
|
||||||
|
if series and len(series) == n:
|
||||||
|
j = max(range(n), key=lambda q: abs(series[q]))
|
||||||
|
values[f"{tag}Date"] = ends[j].strftime("%Y-%m-%d")
|
||||||
|
values[f"{tag}Time"] = ends[j].strftime("%H:%M:%S")
|
||||||
|
|
||||||
return SfmSide(
|
return SfmSide(
|
||||||
event=ev,
|
event=ev,
|
||||||
@@ -161,6 +177,7 @@ def sfm_side(raw: bytes) -> SfmSide:
|
|||||||
counts=counts,
|
counts=counts,
|
||||||
geo_ips_per_count=_GEO_FS_BY_RANGE.get(ev.geo_range, _GEO_NORMAL_FS_INS) / _GEO_INT16_FS,
|
geo_ips_per_count=_GEO_FS_BY_RANGE.get(ev.geo_range, _GEO_NORMAL_FS_INS) / _GEO_INT16_FS,
|
||||||
interval_values=interval_values,
|
interval_values=interval_values,
|
||||||
|
interval_times=times,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -355,12 +372,21 @@ def _compare_samples(sfm: SfmSide, ref: XmlReport) -> list[FieldResult]:
|
|||||||
|
|
||||||
|
|
||||||
def _compare_intervals(sfm: SfmSide, ref: XmlReport) -> list[FieldResult]:
|
def _compare_intervals(sfm: SfmSide, ref: XmlReport) -> list[FieldResult]:
|
||||||
"""One result per column, plus the interval times, which SFM does not keep."""
|
"""One result per column, plus the interval times."""
|
||||||
n = len(ref.intervals or [])
|
n = len(ref.intervals or [])
|
||||||
return ([FieldResult("intervals.Time", "sfm_blank", f"{n} rows", None)]
|
return ([_compare_interval_times(sfm, ref, n)]
|
||||||
+ [_compare_series(f"intervals.{t}", n, sfm, ref) for t in ref.interval_columns or []])
|
+ [_compare_series(f"intervals.{t}", n, sfm, ref) for t in ref.interval_columns or []])
|
||||||
|
|
||||||
|
|
||||||
|
def _compare_interval_times(sfm: SfmSide, ref: XmlReport, n: int) -> FieldResult:
|
||||||
|
if sfm.interval_times is None:
|
||||||
|
return FieldResult("intervals.Time", "sfm_blank", f"{n} rows", None)
|
||||||
|
diffs = [(j, float("inf")) for j, ((t, _), s) in enumerate(zip(ref.intervals or [], sfm.interval_times))
|
||||||
|
if not _same_text(s, t)]
|
||||||
|
return _series_result("intervals.Time", n, len(sfm.interval_times), diffs,
|
||||||
|
abs(n - len(sfm.interval_times)))
|
||||||
|
|
||||||
|
|
||||||
def compare(sfm: SfmSide, ref: XmlReport, carveouts: Sequence["Carveout"] = ()) -> list[FieldResult]:
|
def compare(sfm: SfmSide, ref: XmlReport, carveouts: Sequence["Carveout"] = ()) -> list[FieldResult]:
|
||||||
"""Every field Blastware's report carries, set against what SFM produced.
|
"""Every field Blastware's report carries, set against what SFM produced.
|
||||||
A mismatch a carve-out covers and applies to becomes `accepted`."""
|
A mismatch a carve-out covers and applies to becomes `accepted`."""
|
||||||
|
|||||||
@@ -939,6 +939,53 @@ def _embedded_event_record(
|
|||||||
return None, (f"{rejected} candidate(s), none valid" if rejected else "no candidate"), None
|
return None, (f"{rejected} candidate(s), none valid" if rejected else "no candidate"), None
|
||||||
|
|
||||||
|
|
||||||
|
# A histogram's event record: the same lead, the source 0x0400, marker fe f5,
|
||||||
|
# then its start and stop -- Blastware's Histogram Start / Stop on 63,490 /
|
||||||
|
# 63,490 DL2 histograms. On all 63,500 its start is 0 or 1 s after the footer's
|
||||||
|
# start and its stop 0 or 1 s before the footer's stop (2026-11-03).
|
||||||
|
_HISTOGRAM_RECORD_MARKER = b"\xfe\xf5"
|
||||||
|
_HISTOGRAM_RECORD_SOURCE = b"\x04\x00"
|
||||||
|
|
||||||
|
|
||||||
|
def interval_times(start: datetime.datetime, interval_sec: int,
|
||||||
|
stop: Optional[datetime.datetime], n: int) -> list[datetime.datetime]:
|
||||||
|
"""Each histogram interval's time as Blastware prints it: the interval's
|
||||||
|
end, start + (i + 1) x interval, capped at the stop. 2,308,524 / 2,308,524
|
||||||
|
DL2 rows; and an event's peak date and time are its interval's (2026-11-03)."""
|
||||||
|
out = []
|
||||||
|
for i in range(n):
|
||||||
|
t = start + datetime.timedelta(seconds=interval_sec * (i + 1))
|
||||||
|
out.append(min(t, stop) if stop is not None else t)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _histogram_event_record(
|
||||||
|
raw: bytes, end: int, start: Optional[datetime.datetime],
|
||||||
|
stop: Optional[datetime.datetime],
|
||||||
|
) -> tuple[Optional[datetime.datetime], Optional[datetime.datetime], str]:
|
||||||
|
"""(start, stop) from a histogram's own event record, or (None, None, why).
|
||||||
|
Exactly one record may validate against the footer's start and stop."""
|
||||||
|
if start is None or stop is None:
|
||||||
|
return None, None, "the footer has no start and stop to check one against"
|
||||||
|
found, rejected = [], 0
|
||||||
|
i = raw.find(_HISTOGRAM_RECORD_MARKER, 6)
|
||||||
|
while 0 <= i and i + 18 <= end:
|
||||||
|
a, b = _ts8(raw[i + 2:i + 10]), _ts8(raw[i + 10:i + 18])
|
||||||
|
if (raw[i - 6:i - 2] == _EVENT_RECORD_LEAD and raw[i - 2:i] == _HISTOGRAM_RECORD_SOURCE
|
||||||
|
and a is not None and b is not None and a <= b
|
||||||
|
and 0 <= (a - start).total_seconds() <= 1
|
||||||
|
and 0 <= (stop - b).total_seconds() <= 1):
|
||||||
|
found.append((a, b))
|
||||||
|
elif raw[i - 6:i - 2] == _EVENT_RECORD_LEAD:
|
||||||
|
rejected += 1
|
||||||
|
i = raw.find(_HISTOGRAM_RECORD_MARKER, i + 1)
|
||||||
|
if len(found) == 1:
|
||||||
|
return found[0][0], found[0][1], ""
|
||||||
|
if found:
|
||||||
|
return None, None, f"{len(found)} candidates validate"
|
||||||
|
return None, None, (f"{rejected} candidate(s), none valid" if rejected else "no candidate")
|
||||||
|
|
||||||
|
|
||||||
def _parse_record_time_seconds(raw: bytes) -> Optional[float]:
|
def _parse_record_time_seconds(raw: bytes) -> Optional[float]:
|
||||||
"""The configured post-trigger record time in seconds, from the recording-
|
"""The configured post-trigger record time in seconds, from the recording-
|
||||||
setup config block, or None when absent / implausible."""
|
setup config block, or None when absent / implausible."""
|
||||||
@@ -1358,10 +1405,12 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
|||||||
# embedded in the 5A stream (_embedded_event_record), so a waveform takes
|
# embedded in the 5A stream (_embedded_event_record), so a waveform takes
|
||||||
# it from there. Without a validated one the estimate stands, reported as a
|
# it from there. Without a validated one the estimate stands, reported as a
|
||||||
# decode problem -- never a filename's time, which is only a cross-check.
|
# decode problem -- never a filename's time, which is only a cross-check.
|
||||||
# Histograms stay on ts1 although it runs a second early on 97% (their
|
# A histogram's footer start runs a second early on 97%. Its own event
|
||||||
# record, marker fe f5, holds the exact start): in Blastware's timing a
|
# record (marker fe f5) holds Blastware's exact start and stop, so it takes
|
||||||
# waveform and its histogram share a second 209 times in prod's store, and
|
# them from there (#51); events are keyed unit + time + type, so a waveform
|
||||||
# events is unique on (serial, timestamp) -- #51.
|
# and its histogram may share a second.
|
||||||
|
# ⚠ RETRACTED 2026-11-03: "histograms stay on ts1" -- that held only while
|
||||||
|
# events were unique on (serial, timestamp).
|
||||||
if is_waveform_body and ts2 is not None:
|
if is_waveform_body and ts2 is not None:
|
||||||
_stop = datetime.datetime(ts2.year, ts2.month, ts2.day,
|
_stop = datetime.datetime(ts2.year, ts2.month, ts2.day,
|
||||||
ts2.hour, ts2.minute, ts2.second)
|
ts2.hour, ts2.minute, ts2.second)
|
||||||
@@ -1390,13 +1439,25 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
|||||||
hour=_trig.hour, minute=_trig.minute, second=_trig.second,
|
hour=_trig.hour, minute=_trig.minute, second=_trig.second,
|
||||||
)
|
)
|
||||||
elif ts1 is not None:
|
elif ts1 is not None:
|
||||||
|
_start, _hstop, _why = (_histogram_event_record(raw, footer_pos, ts1, ts2)
|
||||||
|
if record_type == "Histogram" else (None, None, ""))
|
||||||
|
if _start is not None:
|
||||||
|
ev.timestamp_source = "event_record"
|
||||||
|
ev.stop_time = _hstop
|
||||||
|
else:
|
||||||
|
_start = ts1
|
||||||
|
ev.timestamp_source = "footer"
|
||||||
|
if record_type == "Histogram":
|
||||||
|
_problem = (f"no validated histogram event record ({_why}); the start is the "
|
||||||
|
"footer's, a second early on 97% of measured files")
|
||||||
|
ev.decode_problems.append(_problem)
|
||||||
|
log.warning("%s: %s", label, _problem)
|
||||||
ev.timestamp = Timestamp(
|
ev.timestamp = Timestamp(
|
||||||
raw=footer[2:10],
|
raw=footer[2:10],
|
||||||
flag=0x10,
|
flag=0x10,
|
||||||
year=ts1.year, unknown_byte=0, month=ts1.month, day=ts1.day,
|
year=_start.year, unknown_byte=0, month=_start.month, day=_start.day,
|
||||||
hour=ts1.hour, minute=ts1.minute, second=ts1.second,
|
hour=_start.hour, minute=_start.minute, second=_start.second,
|
||||||
)
|
)
|
||||||
ev.timestamp_source = "footer"
|
|
||||||
|
|
||||||
ev.project_info = _setup_notes(raw)
|
ev.project_info = _setup_notes(raw)
|
||||||
ev.raw_samples = samples
|
ev.raw_samples = samples
|
||||||
@@ -1419,7 +1480,8 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
|
|||||||
# The geophone full scale is the file's range; Normal when it wasn't read.
|
# The geophone full scale is the file's range; Normal when it wasn't read.
|
||||||
geo_fs = _GEO_FS_BY_RANGE.get(ev.geo_range, _GEO_NORMAL_FS_INS)
|
geo_fs = _GEO_FS_BY_RANGE.get(ev.geo_range, _GEO_NORMAL_FS_INS)
|
||||||
ev.peak_values = _peaks_from_samples(samples, geo_fs) if has_samples else None
|
ev.peak_values = _peaks_from_samples(samples, geo_fs) if has_samples else None
|
||||||
ev.stop_time = ts2
|
if ev.stop_time is None: # a histogram's record stop, else the footer's
|
||||||
|
ev.stop_time = ts2
|
||||||
if hist_records:
|
if hist_records:
|
||||||
# A histogram stores each interval's vector sum (squared), and each
|
# A histogram stores each interval's vector sum (squared), and each
|
||||||
# channel's half-period: Blastware's per-interval Geo PVS (771,354 /
|
# channel's half-period: Blastware's per-interval Geo PVS (771,354 /
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ def main(argv: list[str] | None = None) -> int:
|
|||||||
conn.row_factory = sqlite3.Row
|
conn.row_factory = sqlite3.Row
|
||||||
|
|
||||||
rows = list(conn.execute(
|
rows = list(conn.execute(
|
||||||
"SELECT id, serial, timestamp, blastware_filename "
|
"SELECT id, serial, timestamp, record_type, blastware_filename "
|
||||||
" FROM events "
|
" FROM events "
|
||||||
" WHERE serial = 'UNKNOWN' "
|
" WHERE serial = 'UNKNOWN' "
|
||||||
" ORDER BY timestamp",
|
" ORDER BY timestamp",
|
||||||
@@ -98,10 +98,11 @@ def main(argv: list[str] | None = None) -> int:
|
|||||||
unresolved += 1
|
unresolved += 1
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Check for an existing row at the target (serial, timestamp).
|
# Check for an existing row at the target key (serial, timestamp,
|
||||||
|
# record_type -- #51).
|
||||||
existing = conn.execute(
|
existing = conn.execute(
|
||||||
"SELECT id FROM events WHERE serial = ? AND timestamp = ?",
|
"SELECT id FROM events WHERE serial = ? AND timestamp = ? AND record_type IS ?",
|
||||||
(new_serial, ts),
|
(new_serial, ts, row["record_type"]),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
action: str
|
action: str
|
||||||
if existing is None:
|
if existing is None:
|
||||||
|
|||||||
+65
-19
@@ -35,6 +35,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import datetime
|
import datetime
|
||||||
import logging
|
import logging
|
||||||
|
import re
|
||||||
import sqlite3
|
import sqlite3
|
||||||
import uuid
|
import uuid
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -106,7 +107,7 @@ CREATE TABLE IF NOT EXISTS events (
|
|||||||
shape_offset_pre REAL, -- pre-trigger baseline median (in/s)
|
shape_offset_pre REAL, -- pre-trigger baseline median (in/s)
|
||||||
shape_offset_spread REAL, -- max(pre,mid,end) - min(...) in in/s; small = constant/DC
|
shape_offset_spread REAL, -- max(pre,mid,end) - min(...) in in/s; small = constant/DC
|
||||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||||||
UNIQUE(serial, timestamp)
|
UNIQUE(serial, timestamp, record_type) -- unit + time + type (#51); see Migration 3
|
||||||
);
|
);
|
||||||
CREATE INDEX IF NOT EXISTS idx_events_serial ON events(serial);
|
CREATE INDEX IF NOT EXISTS idx_events_serial ON events(serial);
|
||||||
CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);
|
CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);
|
||||||
@@ -172,7 +173,7 @@ class SeismoDb:
|
|||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"SELECT sql FROM sqlite_master WHERE type='table' AND name='events'"
|
"SELECT sql FROM sqlite_master WHERE type='table' AND name='events'"
|
||||||
).fetchone()
|
).fetchone()
|
||||||
if row and "UNIQUE(serial, timestamp)" not in row[0]:
|
if row and "UNIQUE(serial, timestamp" not in row[0]: # neither key form yet
|
||||||
log.info("_migrate: rebuilding events table — UNIQUE(serial, timestamp)")
|
log.info("_migrate: rebuilding events table — UNIQUE(serial, timestamp)")
|
||||||
conn.executescript("""
|
conn.executescript("""
|
||||||
ALTER TABLE events RENAME TO events_old;
|
ALTER TABLE events RENAME TO events_old;
|
||||||
@@ -315,6 +316,33 @@ class SeismoDb:
|
|||||||
""")
|
""")
|
||||||
log.info("_migrate: monitor_log table rebuilt OK")
|
log.info("_migrate: monitor_log table rebuilt OK")
|
||||||
|
|
||||||
|
# Migration 3 (#51, 2026-11-03): events UNIQUE (serial, timestamp) ->
|
||||||
|
# (serial, timestamp, record_type). A unit records a waveform and a
|
||||||
|
# histogram in the same second legitimately -- 209 times in prod's
|
||||||
|
# 2026-09-30 store once histograms carry Blastware's start -- and the old
|
||||||
|
# key could hold only one. The table is rebuilt from its own current
|
||||||
|
# definition with only the key swapped, so every column added by the
|
||||||
|
# migrations above, every row and every id is kept (Terra-View reads
|
||||||
|
# rows by id); its indexes are recreated. One transaction.
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT sql FROM sqlite_master WHERE type='table' AND name='events'"
|
||||||
|
).fetchone()
|
||||||
|
if row and "UNIQUE(serial, timestamp)" in row[0]:
|
||||||
|
log.info("_migrate: rebuilding events table — UNIQUE(serial, timestamp, record_type)")
|
||||||
|
indexes = [r[0] for r in conn.execute(
|
||||||
|
"SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name='events' "
|
||||||
|
"AND sql IS NOT NULL")]
|
||||||
|
table = re.sub(r'^CREATE TABLE\s+("?)events\1', "CREATE TABLE events_rekeyed",
|
||||||
|
row[0].replace("UNIQUE(serial, timestamp)",
|
||||||
|
"UNIQUE(serial, timestamp, record_type)", 1))
|
||||||
|
conn.executescript("BEGIN;\n" + table + ";\n"
|
||||||
|
"INSERT INTO events_rekeyed SELECT * FROM events;\n"
|
||||||
|
"DROP TABLE events;\n"
|
||||||
|
"ALTER TABLE events_rekeyed RENAME TO events;\n"
|
||||||
|
+ "".join(sql + ";\n" for sql in indexes)
|
||||||
|
+ "COMMIT;")
|
||||||
|
log.info("_migrate: events table re-keyed OK (%d indexes recreated)", len(indexes))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _iso(dt: Optional[datetime.datetime]) -> Optional[str]:
|
def _iso(dt: Optional[datetime.datetime]) -> Optional[str]:
|
||||||
return dt.isoformat() if dt is not None else None
|
return dt.isoformat() if dt is not None else None
|
||||||
@@ -385,7 +413,8 @@ class SeismoDb:
|
|||||||
device_family: Optional[str] = None,
|
device_family: Optional[str] = None,
|
||||||
) -> tuple[int, int]:
|
) -> tuple[int, int]:
|
||||||
"""
|
"""
|
||||||
Insert triggered events. Silently skips duplicates (serial+timestamp).
|
Insert triggered events. Silently skips duplicates (serial + timestamp +
|
||||||
|
record_type: a waveform and a histogram may share a second, #51).
|
||||||
Returns (inserted, skipped).
|
Returns (inserted, skipped).
|
||||||
|
|
||||||
``waveform_records`` (optional): dict keyed by event waveform_key (hex)
|
``waveform_records`` (optional): dict keyed by event waveform_key (hex)
|
||||||
@@ -393,7 +422,7 @@ class SeismoDb:
|
|||||||
{"filename": str, "filesize": int, "a5_pickle_filename": str}
|
{"filename": str, "filesize": int, "a5_pickle_filename": str}
|
||||||
|
|
||||||
For events whose key is in this dict, the matching columns are
|
For events whose key is in this dict, the matching columns are
|
||||||
populated. If a row with the same (serial, timestamp) already exists
|
populated. If a row with the same (serial, timestamp, record_type) already exists
|
||||||
(dedup hit), the matching waveform record is upserted onto the
|
(dedup hit), the matching waveform record is upserted onto the
|
||||||
existing row so a re-download via the live endpoint refreshes the
|
existing row so a re-download via the live endpoint refreshes the
|
||||||
file metadata.
|
file metadata.
|
||||||
@@ -436,18 +465,27 @@ class SeismoDb:
|
|||||||
# No validated event record: the time may be a second off,
|
# No validated event record: the time may be a second off,
|
||||||
# so it is never allowed to move, merge into or duplicate
|
# so it is never allowed to move, merge into or duplicate
|
||||||
# a row (_estimate_guard). The file is already stored.
|
# a row (_estimate_guard). The file is already stored.
|
||||||
why = self._estimate_guard(conn, serial, rec.get("filename"), ts)
|
why = self._estimate_guard(conn, serial, rec.get("filename"), ts,
|
||||||
|
ev.record_type)
|
||||||
if why:
|
if why:
|
||||||
log.warning("insert_events: %s %s: %s", serial,
|
log.warning("insert_events: %s %s: %s", serial,
|
||||||
rec.get("filename") or key, why)
|
rec.get("filename") or key, why)
|
||||||
skipped += 1
|
skipped += 1
|
||||||
continue
|
continue
|
||||||
elif rec.get("filename") and ts and \
|
elif rec.get("filename") and ts and \
|
||||||
self._restamp_by_file(conn, serial, rec["filename"], ts) is False:
|
self._restamp_by_file(conn, serial, rec["filename"], ts,
|
||||||
|
ev.record_type) is False:
|
||||||
skipped += 1
|
skipped += 1
|
||||||
continue
|
continue
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
if ev.record_type is None and conn.execute(
|
||||||
|
"SELECT 1 FROM events WHERE serial = ? AND timestamp = ? "
|
||||||
|
"AND record_type IS NULL", (serial, ts)).fetchone():
|
||||||
|
# A UNIQUE key treats NULLs as distinct, so an untyped
|
||||||
|
# event would never collide: it still refreshes the
|
||||||
|
# untyped row at its second, as under the old key.
|
||||||
|
raise sqlite3.IntegrityError("untyped event already stored")
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO events
|
INSERT INTO events
|
||||||
@@ -507,7 +545,7 @@ class SeismoDb:
|
|||||||
inserted += 1
|
inserted += 1
|
||||||
except sqlite3.IntegrityError:
|
except sqlite3.IntegrityError:
|
||||||
skipped += 1
|
skipped += 1
|
||||||
# UPSERT path: a row for this (serial, timestamp) already
|
# UPSERT path: a row for this (serial, timestamp, record_type) already
|
||||||
# exists. Refresh every device-authoritative field from
|
# exists. Refresh every device-authoritative field from
|
||||||
# the new data so that a re-import with better data (e.g.
|
# the new data so that a re-import with better data (e.g.
|
||||||
# a watcher re-forward where the previous attempt missed
|
# a watcher re-forward where the previous attempt missed
|
||||||
@@ -560,7 +598,7 @@ class SeismoDb:
|
|||||||
shape_offset_axis = COALESCE(?, shape_offset_axis),
|
shape_offset_axis = COALESCE(?, shape_offset_axis),
|
||||||
shape_offset_pre = COALESCE(?, shape_offset_pre),
|
shape_offset_pre = COALESCE(?, shape_offset_pre),
|
||||||
shape_offset_spread = COALESCE(?, shape_offset_spread)
|
shape_offset_spread = COALESCE(?, shape_offset_spread)
|
||||||
WHERE serial = ? AND timestamp = ?
|
WHERE serial = ? AND timestamp = ? AND record_type IS ?
|
||||||
""",
|
""",
|
||||||
(
|
(
|
||||||
pv.tran if pv else None,
|
pv.tran if pv else None,
|
||||||
@@ -597,6 +635,7 @@ class SeismoDb:
|
|||||||
rec.get("shape_offset_spread") if rec else None,
|
rec.get("shape_offset_spread") if rec else None,
|
||||||
serial,
|
serial,
|
||||||
ts,
|
ts,
|
||||||
|
ev.record_type,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -606,11 +645,11 @@ class SeismoDb:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _estimate_guard(conn: sqlite3.Connection, serial: str, filename: Optional[str],
|
def _estimate_guard(conn: sqlite3.Connection, serial: str, filename: Optional[str],
|
||||||
ts: Optional[str]) -> Optional[str]:
|
ts: Optional[str], record_type: Optional[str] = None) -> Optional[str]:
|
||||||
"""Why an event whose time is only an estimate must not be written, or None.
|
"""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
|
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
|
second off, and (serial, timestamp, record_type) is the table's key. So it never
|
||||||
moves a row, never lands on another event's row, and never adds a second
|
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,
|
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
|
and the event's file and sidecar are already in the store. Its own
|
||||||
@@ -625,8 +664,8 @@ class SeismoDb:
|
|||||||
return (f"already stored under {', '.join(str(t) for t in own)}; its estimated "
|
return (f"already stored under {', '.join(str(t) for t in own)}; its estimated "
|
||||||
f"time {ts} does not move or duplicate it")
|
f"time {ts} does not move or duplicate it")
|
||||||
holder = conn.execute(
|
holder = conn.execute(
|
||||||
"SELECT blastware_filename FROM events WHERE serial = ? AND timestamp = ?",
|
"SELECT blastware_filename FROM events WHERE serial = ? AND timestamp = ? "
|
||||||
(serial, ts)).fetchone()
|
"AND record_type IS ?", (serial, ts, record_type)).fetchone()
|
||||||
if holder is not None and (named is None or holder[0] != named):
|
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'}; "
|
return (f"its estimated time {ts} is held by {holder[0] or 'another event'}; "
|
||||||
"not merged into it")
|
"not merged into it")
|
||||||
@@ -634,8 +673,9 @@ class SeismoDb:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _restamp_by_file(conn: sqlite3.Connection, serial: str, filename: str,
|
def _restamp_by_file(conn: sqlite3.Connection, serial: str, filename: str,
|
||||||
ts: str) -> Optional[bool]:
|
ts: str, record_type: Optional[str] = None) -> Optional[bool]:
|
||||||
"""Move this file's row to `ts` when it sits under another time.
|
"""Move this file's row to `ts` (and `record_type`) when it sits under
|
||||||
|
another time or type.
|
||||||
|
|
||||||
The events table is unique on (serial, timestamp), so an event re-stored
|
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,
|
with a corrected time -- every Series-3 waveform after the event-time fix,
|
||||||
@@ -646,6 +686,10 @@ class SeismoDb:
|
|||||||
stored as "imported.bw" -- so only a Blastware name is matched. Of
|
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.
|
several rows for one file, a reviewed one with a time moves first.
|
||||||
|
|
||||||
|
The type moves the same way: before v0.33.0 a row's type came from the
|
||||||
|
filename, and with the type in the key (#51) a re-import under the file's
|
||||||
|
own type would otherwise add a second row.
|
||||||
|
|
||||||
Returns True when the row was moved; None when there was nothing to move
|
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
|
(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
|
`ts`), so the caller goes on as before; False when a different stored
|
||||||
@@ -656,18 +700,20 @@ class SeismoDb:
|
|||||||
return None
|
return None
|
||||||
mine = conn.execute(
|
mine = conn.execute(
|
||||||
"SELECT id, timestamp FROM events WHERE serial = ? AND blastware_filename = ? "
|
"SELECT id, timestamp FROM events WHERE serial = ? AND blastware_filename = ? "
|
||||||
"AND (timestamp IS NULL OR timestamp != ?) "
|
"AND (timestamp IS NULL OR timestamp != ? OR record_type IS NOT ?) "
|
||||||
"ORDER BY COALESCE(false_trigger, 0) DESC, timestamp IS NULL, rowid LIMIT 1",
|
"ORDER BY COALESCE(false_trigger, 0) DESC, timestamp IS NULL, rowid LIMIT 1",
|
||||||
(serial, filename, ts),
|
(serial, filename, ts, record_type),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
if mine is None:
|
if mine is None:
|
||||||
return None
|
return None
|
||||||
holder = conn.execute(
|
holder = conn.execute(
|
||||||
"SELECT id, blastware_filename FROM events WHERE serial = ? AND timestamp = ?",
|
"SELECT id, blastware_filename FROM events WHERE serial = ? AND timestamp = ? "
|
||||||
(serial, ts),
|
"AND record_type IS ?",
|
||||||
|
(serial, ts, record_type),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
if holder is None:
|
if holder is None:
|
||||||
conn.execute("UPDATE events SET timestamp = ? WHERE id = ?", (ts, mine[0]))
|
conn.execute("UPDATE events SET timestamp = ?, record_type = ? WHERE id = ?",
|
||||||
|
(ts, record_type, mine[0]))
|
||||||
log.info("insert_events: %s %s moved from %s to %s (corrected event time)",
|
log.info("insert_events: %s %s moved from %s to %s (corrected event time)",
|
||||||
serial, filename, mine[1], ts)
|
serial, filename, mine[1], ts)
|
||||||
return True
|
return True
|
||||||
|
|||||||
@@ -141,10 +141,12 @@ def test_a_report_fills_in_when_the_record_is_missing():
|
|||||||
assert (_dt(ev.timestamp), ev.timestamp_source) == (TRIGGER, "report")
|
assert (_dt(ev.timestamp), ev.timestamp_source) == (TRIGGER, "report")
|
||||||
|
|
||||||
|
|
||||||
def test_a_histogram_keeps_its_footer_start_for_now():
|
def test_a_histogram_takes_its_event_records_start():
|
||||||
# Its record (marker fe f5) also holds Blastware's start -- that change is #51.
|
# #51: its record (marker fe f5) holds Blastware's start; the footer's
|
||||||
|
# 19:04:50 is a second early.
|
||||||
ev = read_blastware_file(HISTOGRAM)
|
ev = read_blastware_file(HISTOGRAM)
|
||||||
assert (_dt(ev.timestamp), ev.timestamp_source) == (datetime.datetime(2026, 5, 10, 19, 4, 50), "footer")
|
assert (_dt(ev.timestamp), ev.timestamp_source) == (datetime.datetime(2026, 5, 10, 19, 4, 51),
|
||||||
|
"event_record")
|
||||||
|
|
||||||
|
|
||||||
def test_the_sidecar_keeps_the_instruments_time_and_says_where_it_came_from():
|
def test_the_sidecar_keeps_the_instruments_time_and_says_where_it_came_from():
|
||||||
@@ -173,13 +175,16 @@ def test_an_imported_event_with_only_an_estimate_does_not_overwrite_its_neighbou
|
|||||||
from sfm.database import SeismoDb
|
from sfm.database import SeismoDb
|
||||||
from sfm.waveform_store import WaveformStore
|
from sfm.waveform_store import WaveformStore
|
||||||
store, db = WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo_relay.db")
|
store, db = WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo_relay.db")
|
||||||
other = Event(index=0) # a different event at 14:23:43
|
# A different waveform at 14:23:43. The key is unit + time + type (#51), so
|
||||||
|
# "its neighbour" is an event of the same type at the same second.
|
||||||
|
other = Event(index=0)
|
||||||
other.timestamp = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=10, day=26,
|
other.timestamp = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=10, day=26,
|
||||||
hour=14, minute=23, second=43)
|
hour=14, minute=23, second=43)
|
||||||
other._waveform_key = bytes.fromhex("01110000")
|
other._waveform_key = bytes.fromhex("01110000")
|
||||||
|
other.record_type = "Waveform"
|
||||||
other.peak_values = PeakValues(tran=0.01, vert=0.02, long=0.03, peak_vector_sum=0.04, micl=None)
|
other.peak_values = PeakValues(tran=0.01, vert=0.02, long=0.03, peak_vector_sum=0.04, micl=None)
|
||||||
db.insert_events([other], serial="BE9441", device_family="series3",
|
db.insert_events([other], serial="BE9441", device_family="series3",
|
||||||
waveform_records={"01110000": {"filename": "K441LTOF.ZJ0H"}})
|
waveform_records={"01110000": {"filename": "K441LTOF.ZJ0W"}})
|
||||||
|
|
||||||
broken = bytes(_broken(lambda r, i: r.__setitem__(i + 1, 0x81))) # no validated record
|
broken = bytes(_broken(lambda r, i: r.__setitem__(i + 1, 0x81))) # no validated record
|
||||||
ev, rec = store.save_imported_bw(broken, source_path=Path(ZI0.name))
|
ev, rec = store.save_imported_bw(broken, source_path=Path(ZI0.name))
|
||||||
@@ -189,6 +194,31 @@ def test_an_imported_event_with_only_an_estimate_does_not_overwrite_its_neighbou
|
|||||||
waveform_records={ev._waveform_key.hex(): rec}) == (0, 1)
|
waveform_records={ev._waveform_key.hex(): rec}) == (0, 1)
|
||||||
with sqlite3.connect(str(db.db_path)) as c:
|
with sqlite3.connect(str(db.db_path)) as c:
|
||||||
assert c.execute("SELECT blastware_filename, peak_vector_sum FROM events").fetchall() == \
|
assert c.execute("SELECT blastware_filename, peak_vector_sum FROM events").fetchall() == \
|
||||||
[("K441LTOF.ZJ0H", 0.04)]
|
[("K441LTOF.ZJ0W", 0.04)]
|
||||||
assert (tmp_path / "waveforms" / "BE9441" / "K441LTOF.ZI0").exists() # the data is kept
|
assert (tmp_path / "waveforms" / "BE9441" / "K441LTOF.ZI0").exists() # the data is kept
|
||||||
assert any("not merged" in r.message for r in caplog.records)
|
assert any("not merged" in r.message for r in caplog.records)
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_estimate_beside_a_histogram_at_its_second_is_stored_alongside(tmp_path):
|
||||||
|
# A waveform and a histogram may share a second (#51): the estimate is its
|
||||||
|
# own row, and the histogram is untouched.
|
||||||
|
import sqlite3
|
||||||
|
from minimateplus.models import Event, PeakValues, Timestamp
|
||||||
|
from sfm.database import SeismoDb
|
||||||
|
from sfm.waveform_store import WaveformStore
|
||||||
|
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.record_type = "Histogram"
|
||||||
|
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"}})
|
||||||
|
broken = bytes(_broken(lambda r, i: r.__setitem__(i + 1, 0x81))) # no validated record
|
||||||
|
ev, rec = store.save_imported_bw(broken, source_path=Path(ZI0.name))
|
||||||
|
assert db.insert_events([ev], serial="BE9441", device_family="series3",
|
||||||
|
waveform_records={ev._waveform_key.hex(): rec}) == (1, 0)
|
||||||
|
with sqlite3.connect(str(db.db_path)) as c:
|
||||||
|
rows = c.execute("SELECT record_type, peak_vector_sum FROM events ORDER BY record_type").fetchall()
|
||||||
|
assert rows[0] == ("Histogram", 0.04) and rows[1][0] == "Waveform"
|
||||||
@@ -471,3 +471,27 @@ def test_the_h5_carries_the_interval_detail(tmp_path):
|
|||||||
assert int(f.attrs["histogram_interval_sec"]) == 60
|
assert int(f.attrs["histogram_interval_sec"]) == 60
|
||||||
assert list(f["intervals/half_period/Vert"][:]) == ev.interval_half_periods["Vert"]
|
assert list(f["intervals/half_period/Vert"][:]) == ev.interval_half_periods["Vert"]
|
||||||
assert abs(float(f["intervals/pvs_ips"][0]) - 2.644) <= 0.0005 + 1e-9
|
assert abs(float(f["intervals/pvs_ips"][0]) - 2.644) <= 0.0005 + 1e-9
|
||||||
|
|
||||||
|
|
||||||
|
# ── #51: a histogram's start and stop from its own event record ─────────────
|
||||||
|
# The footer's start runs a second early on 97%. The histogram's event record
|
||||||
|
# (lead 00 28 05 00, source 04 00, marker fe f5) holds Blastware's start and
|
||||||
|
# stop: 63,490 / 63,490 DL2 histograms each (2026-11-03).
|
||||||
|
|
||||||
|
def test_a_histogram_starts_at_its_event_records_start():
|
||||||
|
ev = read_blastware_file(_FIX / "decode-checker-10-29-26/T004JTRF.ME0H")
|
||||||
|
t, s = ev.timestamp, ev.stop_time
|
||||||
|
# Blastware: start 2022-12-28 12:49:26, stop 12:49:33
|
||||||
|
assert (t.year, t.month, t.day, t.hour, t.minute, t.second) == (2022, 12, 28, 12, 49, 26)
|
||||||
|
assert (s.hour, s.minute, s.second) == (12, 49, 33)
|
||||||
|
assert ev.timestamp_source == "event_record"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_histogram_without_its_record_falls_back_to_the_footer_and_says_so():
|
||||||
|
raw = bytearray((_FIX / "decode-checker-10-29-26/T004JTRF.ME0H").read_bytes())
|
||||||
|
i = raw.find(b"\xfe\xf5")
|
||||||
|
raw[i] = 0x00 # break the record's marker
|
||||||
|
ev = decode_blastware_bytes(bytes(raw), name=None)
|
||||||
|
assert ev.timestamp_source == "footer"
|
||||||
|
assert ev.timestamp.second == 25 # the footer's start, a second early
|
||||||
|
assert any("histogram event record" in p for p in ev.decode_problems)
|
||||||
@@ -83,9 +83,12 @@ def test_a_waveform_read_under_another_name_keeps_its_time(tmp_path):
|
|||||||
datetime.datetime(2026, 10, 26, 14, 23, 42)
|
datetime.datetime(2026, 10, 26, 14, 23, 42)
|
||||||
|
|
||||||
|
|
||||||
def test_a_histogram_keeps_the_binarys_window_start():
|
def test_a_histogram_now_agrees_with_its_filename():
|
||||||
assert blastware_filename_time(HISTOGRAM.name) != datetime.datetime(2026, 5, 10, 19, 4, 50)
|
# #51: the start comes from the histogram's own event record, which is
|
||||||
assert _dt(read_blastware_file(HISTOGRAM).timestamp) == datetime.datetime(2026, 5, 10, 19, 4, 50)
|
# Blastware's -- and so the filename's. The footer's window start (19:04:50)
|
||||||
|
# was a second early.
|
||||||
|
assert blastware_filename_time(HISTOGRAM.name) == datetime.datetime(2026, 5, 10, 19, 4, 51)
|
||||||
|
assert _dt(read_blastware_file(HISTOGRAM).timestamp) == datetime.datetime(2026, 5, 10, 19, 4, 51)
|
||||||
|
|
||||||
|
|
||||||
def test_an_import_no_longer_lands_a_waveform_on_its_histogram_twins_row(tmp_path):
|
def test_an_import_no_longer_lands_a_waveform_on_its_histogram_twins_row(tmp_path):
|
||||||
|
|||||||
@@ -325,3 +325,21 @@ def test_an_oorange_interval_vector_sum_is_saturation():
|
|||||||
|
|
||||||
def test_an_oorange_vector_sum_needs_a_clamped_channel_in_that_interval():
|
def test_an_oorange_vector_sum_needs_a_clamped_channel_in_that_interval():
|
||||||
assert _pvs_oorange(unclamp=True).verdict == "mismatch"
|
assert _pvs_oorange(unclamp=True).verdict == "mismatch"
|
||||||
|
|
||||||
|
|
||||||
|
_PEAK_TIMES = ("TranPeakDate", "TranPeakTime", "VertPeakDate", "VertPeakTime", "LongPeakDate",
|
||||||
|
"LongPeakTime", "PeakVectorSumDate", "PeakVectorSumTime", "MicLDate", "MicLTime")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("path", [FIX / "T004JTRF.ME0H", # 1 interval
|
||||||
|
FIX.parent / "footer-11-03-26" / "T003LCYV.JD0H", # 145
|
||||||
|
FIX.parent / "histogram-decode-11-02-26" / "K440HA3C.JM0H"]) # 8 x 5 s
|
||||||
|
def test_histogram_times_match_blastware(path):
|
||||||
|
# #51: an interval's printed time is its end -- start + (n + 1) x interval,
|
||||||
|
# capped at the stop -- and each peak's date and time are its interval's:
|
||||||
|
# 2,308,524 / 2,308,524 rows and 2,000 / 2,000 peaks each on a DL2 sample.
|
||||||
|
ref = parse_xml_report_file(path.with_name(path.name.replace(".", "_", 1) + "_XML.XML"))
|
||||||
|
res = {r.field: r for r in compare(sfm_side(path.read_bytes()), ref, CARVEOUTS)}
|
||||||
|
for f in (("HistogramStartDate", "HistogramStartTime", "HistogramStopTime", "intervals.Time")
|
||||||
|
+ tuple(t for t in _PEAK_TIMES if t in ref.scalars)):
|
||||||
|
assert res[f].verdict == "match", (f, res[f])
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
"""An event is identified by unit + time + type (#51).
|
||||||
|
|
||||||
|
The events table was unique on (serial, timestamp): one event per unit per
|
||||||
|
second. A unit records a waveform and a histogram in the same second
|
||||||
|
legitimately -- 209 times in prod's 2026-09-30 store once histograms carry
|
||||||
|
Blastware's start -- so the key is now (serial, timestamp, record_type).
|
||||||
|
Agreed with Brian 2026-11-03.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
|
from minimateplus.models import Event, PeakValues, Timestamp # noqa: E402
|
||||||
|
from sfm.database import SeismoDb # noqa: E402
|
||||||
|
|
||||||
|
T = "2026-08-25T10:33:29"
|
||||||
|
T_EARLY = "2026-08-25T10:33:28"
|
||||||
|
|
||||||
|
|
||||||
|
def _event(when: str, rtype: str, key: str = "0111646a", pvs: float = 0.5) -> Event:
|
||||||
|
t = datetime.datetime.fromisoformat(when)
|
||||||
|
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)
|
||||||
|
ev._waveform_key = bytes.fromhex(key)
|
||||||
|
ev.record_type = rtype
|
||||||
|
ev.peak_values = PeakValues(tran=0.1, vert=0.2, long=0.3, peak_vector_sum=pvs, micl=None)
|
||||||
|
return ev
|
||||||
|
|
||||||
|
|
||||||
|
def _store(db: SeismoDb, ev: Event, filename: str) -> tuple:
|
||||||
|
return db.insert_events([ev], serial="BE12844", device_family="series3",
|
||||||
|
waveform_records={ev._waveform_key.hex(): {"filename": filename}})
|
||||||
|
|
||||||
|
|
||||||
|
def _rows(db: SeismoDb) -> list:
|
||||||
|
with sqlite3.connect(str(db.db_path)) as c:
|
||||||
|
c.row_factory = sqlite3.Row
|
||||||
|
return [dict(r) for r in c.execute(
|
||||||
|
"SELECT * FROM events ORDER BY timestamp, record_type")]
|
||||||
|
|
||||||
|
|
||||||
|
def _key_sql(db: SeismoDb) -> str:
|
||||||
|
with sqlite3.connect(str(db.db_path)) as c:
|
||||||
|
return c.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name='events'"
|
||||||
|
).fetchone()[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_waveform_and_a_histogram_can_share_a_second(tmp_path):
|
||||||
|
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||||
|
assert _store(db, _event(T, "Waveform"), "N844LQHB.ZT0W") == (1, 0)
|
||||||
|
assert _store(db, _event(T, "Histogram", key="0111700a"), "N844LQHB.ZT0H") == (1, 0)
|
||||||
|
assert [(r["timestamp"], r["record_type"]) for r in _rows(db)] == [
|
||||||
|
(T, "Histogram"), (T, "Waveform")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_same_event_twice_is_still_one_row(tmp_path):
|
||||||
|
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||||
|
_store(db, _event(T, "Histogram"), "N844LQHB.ZT0H")
|
||||||
|
assert _store(db, _event(T, "Histogram", pvs=0.8), "N844LQHB.ZT0H") == (0, 1)
|
||||||
|
(row,) = _rows(db)
|
||||||
|
assert row["peak_vector_sum"] == 0.8 # the upsert refreshed it
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_histogram_moves_onto_its_waveforms_second(tmp_path):
|
||||||
|
# What the release backfill does: the histogram was stored a second early;
|
||||||
|
# its corrected start is the waveform's second. The row moves in place.
|
||||||
|
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||||
|
_store(db, _event(T, "Waveform"), "N844LQHB.ZT0W")
|
||||||
|
_store(db, _event(T_EARLY, "Histogram", key="0111700a"), "N844LQHB.ZS0H")
|
||||||
|
(before,) = [r for r in _rows(db) if r["record_type"] == "Histogram"]
|
||||||
|
assert _store(db, _event(T, "Histogram", key="0111700a"), "N844LQHB.ZS0H") == (0, 1)
|
||||||
|
rows = _rows(db)
|
||||||
|
assert [(r["timestamp"], r["record_type"]) for r in rows] == [(T, "Histogram"), (T, "Waveform")]
|
||||||
|
assert [r["id"] for r in rows if r["record_type"] == "Histogram"] == [before["id"]]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_re_typed_event_is_corrected_in_place(tmp_path):
|
||||||
|
# Before v0.33.0 the type came from the filename; a re-import with the
|
||||||
|
# file's own type must correct that row, not add a second one.
|
||||||
|
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||||
|
_store(db, _event(T, "Waveform"), "N844LQHB.ZT0H")
|
||||||
|
(before,) = _rows(db)
|
||||||
|
_store(db, _event(T, "Histogram"), "N844LQHB.ZT0H")
|
||||||
|
(row,) = _rows(db)
|
||||||
|
assert (row["id"], row["record_type"]) == (before["id"], "Histogram")
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_old_database_is_migrated_keeping_every_row_and_id(tmp_path):
|
||||||
|
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||||
|
_store(db, _event(T, "Waveform"), "N844LQHB.ZT0W")
|
||||||
|
_store(db, _event(T_EARLY, "Histogram", key="0111700a"), "N844LQHB.ZS0H")
|
||||||
|
old_rows = _rows(db)
|
||||||
|
with sqlite3.connect(str(db.db_path)) as c: # put the old key back
|
||||||
|
sql = _key_sql(db).replace("UNIQUE(serial, timestamp, record_type)",
|
||||||
|
"UNIQUE(serial, timestamp)")
|
||||||
|
c.executescript(f"""
|
||||||
|
ALTER TABLE events RENAME TO events_new_key;
|
||||||
|
{sql};
|
||||||
|
INSERT INTO events SELECT * FROM events_new_key;
|
||||||
|
DROP TABLE events_new_key;
|
||||||
|
""")
|
||||||
|
assert "UNIQUE(serial, timestamp)" in _key_sql(db)
|
||||||
|
|
||||||
|
db = SeismoDb(tmp_path / "seismo_relay.db") # opening migrates
|
||||||
|
assert "UNIQUE(serial, timestamp, record_type)" in _key_sql(db)
|
||||||
|
assert _rows(db) == old_rows
|
||||||
|
assert _store(db, _event(T, "Histogram", key="0111700b"), "N844LQHC.ZT0H") == (1, 0)
|
||||||
|
with sqlite3.connect(str(db.db_path)) as c:
|
||||||
|
names = {r[0] for r in c.execute(
|
||||||
|
"SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='events'")}
|
||||||
|
assert {"idx_events_serial", "idx_events_timestamp"} <= names
|
||||||
|
|
||||||
|
|
||||||
|
def test_reopening_keeps_the_new_key(tmp_path):
|
||||||
|
SeismoDb(tmp_path / "seismo_relay.db")
|
||||||
|
db = SeismoDb(tmp_path / "seismo_relay.db")
|
||||||
|
assert "UNIQUE(serial, timestamp, record_type)" in _key_sql(db)
|
||||||
@@ -22,7 +22,7 @@ from minimateplus.models import Event
|
|||||||
|
|
||||||
FIX = Path(__file__).parent / "fixtures"
|
FIX = Path(__file__).parent / "fixtures"
|
||||||
WAVEFORM = FIX / "fft-oracle-2026-09-14" / "N844LQHB.ZT0W" # footer ts2 = 2026-08-25 10:33:32
|
WAVEFORM = FIX / "fft-oracle-2026-09-14" / "N844LQHB.ZT0W" # footer ts2 = 2026-08-25 10:33:32
|
||||||
HISTOGRAM = FIX / "ts-fix" / "K441LKZU.C30H" # window start 2026-05-10 19:04:50
|
HISTOGRAM = FIX / "ts-fix" / "K441LKZU.C30H" # start 2026-05-10 19:04:51 (#51)
|
||||||
|
|
||||||
|
|
||||||
def _tuple(ts):
|
def _tuple(ts):
|
||||||
@@ -39,9 +39,10 @@ def test_waveform_timestamp_is_exact_trigger_from_binary():
|
|||||||
|
|
||||||
def test_histogram_timestamp_is_window_start_unchanged():
|
def test_histogram_timestamp_is_window_start_unchanged():
|
||||||
ev = read_blastware_file(HISTOGRAM)
|
ev = read_blastware_file(HISTOGRAM)
|
||||||
# Histogram event time = the window start (ts1); must NOT get the waveform
|
# Histogram event time = the window start, from its own event record (#51;
|
||||||
# ts2 treatment (that would land ~24 h off).
|
# the footer's ts1 is a second earlier); must NOT get the waveform ts2
|
||||||
assert _tuple(ev.timestamp) == (2026, 5, 10, 19, 4, 50), _tuple(ev.timestamp)
|
# treatment (that would land ~24 h off).
|
||||||
|
assert _tuple(ev.timestamp) == (2026, 5, 10, 19, 4, 51), _tuple(ev.timestamp)
|
||||||
|
|
||||||
|
|
||||||
def test_a_report_does_not_override_the_instruments_event_record():
|
def test_a_report_does_not_override_the_instruments_event_record():
|
||||||
|
|||||||
Reference in new issue
Block a user