Release v0.34.0 — Series-4 parity, and most of Blastware's report from the event file alone #59

Merged
serversdown merged 245 commits from dev into main 2026-11-04 18:19:24 -05:00
31 changed files with 9577 additions and 127 deletions
Showing only changes of commit f24913189b - Show all commits

No files matched your search

+136
View File
@@ -7,6 +7,49 @@ All notable changes to seismo-relay are documented here.
## Unreleased
### Fixed
- ✅ **#51: events are identified by unit + time + type, and histograms take
Blastware's times.**
- **The new key.** The events table was `UNIQUE(serial, timestamp)`, one
event per unit per second. A waveform and its histogram share a second
legitimately: 209 times in prod's 2026-09-30 store. The key is now
`UNIQUE(serial, timestamp, record_type)` (agreed with Brian 2026-11-03).
- **Migration 3** rebuilds the table from its own definition with only the
key swapped, in one transaction. Every column, row and id is kept, and
the indexes are recreated.
- **Lookups:** the upsert, the estimate guard and the restamp match on
type. The restamp also re-types a file's own row in place. An untyped
event still dedups against an untyped row.
- **Histogram times.** A histogram's start and stop now come from its own
event record (lead `00 28 05 00`, source `04 00`, marker `fe f5`). That is
Blastware's Histogram Start and Stop on 63,490 / 63,490 DL2 histograms; the
footer's start was a second early on 97%. Without a validated record, the
footer stands and the decoder logs a decode problem.
- **Interval times and peak times follow:**
- each interval's printed time is its end, start + (i + 1) × interval,
capped at the stop (2,308,524 / 2,308,524 rows; `interval_times`)
- each peak's date and time is its interval's
- **Decode checker:** 760,410 comparisons fixed, 0 regressions, **47 of 88**
fields fully match (was 34). Histogram start and stop times, interval
times and the ten peak date/time fields match every DL2 histogram.
- **Rehearsed on a copy of prod's 2026-09-30 snapshot (15,432 events):**
- The migration kept every row identical, rebuilt the indexes and passed
the integrity check, in 0.27 s.
- `backfill_sidecars.py`: 11,944 files, 0 errors. 9,852 Series-3
histograms moved +1 s in place, with no id lost and review state
untouched. The 209 same-second pairs coexist, and 0 collisions were
refused. (It also created 341 rows for store files that never had one:
the known one-time behaviour, not duplicates.)
- `backfill_event_shape.py`: exit 0, `cleared_stale` 0.
- ⚠ **Schema migration + codec change.** SFM migrates the events table by
itself on first start: back up `seismo_relay.db` first. The release
backfill (`backfill_sidecars.py` then `backfill_event_shape.py`) moves
every Series-3 histogram's stored time by one second, in place.
- Terra-View pairs twins by peak values and reads rows by id: no change
needed there.
- Note for Terra-View's changelog: Series-3 histograms move forward one
second, so an event can cross a deployment-window edge.
- Three tests that pinned the old footer start now pin the record's. The
estimate-guard test's neighbour is now the same type.
- **A Blastware file's geophone range comes from its setup, so Sensitive
events no longer read 8× high.**
- **Where it is:** in the setup's channel blocks, the byte 29 after each
@@ -92,6 +135,76 @@ All notable changes to seismo-relay are documented here.
change.
### Added
- **A histogram's interval detail: frequencies, vector sums, interval size and
stop** (group B of the file-only decode). Measured on DL2 2026-11-03.
- **Frequency** = (sample rate / 2) / half-period: 527,915 / 527,915 cells
at 1024 sps and 1,725 / 1,725 at 2048.
- ✅ **Fixes #50.** `half_period_to_hz` used a fixed 512 and halved every
2048-sps frequency. It now takes the rate (default 1024).
- Blastware prints "N/A" for a half-period of 0, ">100" (">200" at 2048)
at 5 samples or fewer, and "<1.0" below 1 Hz.
- **Each interval's vector sum**, √PVS² at the event's range.
- **Interval size:** uint16 seconds at `k − 40` (Series IV `[8:10]`).
- **Stop time:** the footer's.
- **`Event` gains** `histogram_interval_sec`, `interval_half_periods`,
`interval_pvs` and `stop_time`.
- **The `.h5` gains** `/intervals/half_period/<ch>` and `/intervals/pvs_ips`,
plus a `histogram_interval_sec` attribute.
- **Decoder:** a histogram is now walked once
(`histogram_codec.channels_from_records`).
- **Decode checker:** 508,080 comparisons fixed, 0 regressions, 34 of 88
fields fully match (was 28).
- Frequencies on all four channels, interval size and stop date match
every DL2 histogram.
- Interval vector sum: 63,497 match, plus 17 clipped intervals now under
the saturation carve-out. Blastware prints OORANGE when the sum exceeds
the range in an interval where it clamped a channel (17 / 17).
- 4 cells sit 4e-6 past a rounding boundary and stay mismatches.
- 58 stop times are Blastware a second earlier, part of #51.
- ⚠ **Codec change:** it rides the next release's `TOOL_VERSION` bump and
backfill. The `.h5` additions are additive. No schema change.
- **A Blastware file's identity, battery and trigger settings** (group A of the
file-only decode). Every field is matched against every DL2 report
(2026-11-03).
- **Identity block** before the setup name: what the live read gets from
SUB FE.
- serial `k − 202`, firmware `k − 147`, DSP version `k − 138`, firmware
minor `k − 193`
- calibration date `k − 132` and "by" `k − 128`
- manufacturer `k − 94`, model `k − 72`
- Filled into `Event.device_info`; `DeviceInfo` gains `calibration_date` /
`calibrated_by`.
- Serial, Version and Calibration match 70,042 / 70,042.
- **Battery:** uint16 hundredths of a volt at `k − 190`
(`Event.battery_volts`), 70,042 / 70,042. Blastware rounds half up
(6.25 → "6.3 Volts").
- **Trigger source:** the two bytes between the embedded event record's lead
and `fe 80`, a bitmask (`0x01` Tran, `0x02` Vert, `0x04` Long, `0x08`
MicL, `0x200` Manual). 6,524 / 6,524 (`Event.triggered_by`).
- **Trigger settings,** in Series IV's `0x1A` layout:
- the sources bitmask at `k − 19`
- the stop mode at `k − 31` (0 = Fixed)
- each channel's float32 level at label + 30 (geo in/s, mic psi)
- the mic type code at MicL + 4 (2 = Linear Weighting)
Blastware prints a level when its channel is a trigger source and the
event wasn't Manual. Geo level 6,484 / 6,484, mic level 4,412 / 4,412
(its dB uses 6895 Pa/psi).
- **`.h5`:** all of them as attributes (additive).
- **Decode checker:** 444,188 comparisons fixed, 0 regressions, 28 of 88
fields fully match (was 18).
- A mic level is now compared in the unit it is printed in: K441LA17.IN0W
prints dB under psi Units.
- New carve-out `units-is-a-display-preference` (3,532 events). dB or psi
in a Blastware report is that PC's Blastware preference when it wrote the
report (Blastware manual §4, Preferences → Units and Channel), not the
unit's Microphone Units setting (MiniMate Plus manual §3.9.7). DL2's
reports switch fleet-wide in 61 clean runs by write time, and no byte of
the file separates them.
- Single-value fields are proven for that value only: Version `10.72-8.17`,
stop mode Fixed, mic type Linear.
- ⚠ **Codec change:** it rides the next release's `TOOL_VERSION` bump and
backfill. No schema change.
- **A Blastware file's job number, and whether Blastware shows it.**
- **Where it is:** the setup block has Series IV's `0x1A` layout here too.
The report flags sit at 9 bytes before the setup name, with bit `0x02`
@@ -114,6 +227,29 @@ All notable changes to seismo-relay are documented here.
`.h5` attributes are additive. No schema change, no migration.
### Protocol / Documentation
- **Histogram timing in the protocol reference (D.6.10):**
- the histogram's own event record
- the interval-time and peak-time rules
- "histograms stay on ts1" retracted in place
- CLAUDE.md records the unit + time + type key
- Docs only.
- **Group B in the protocol reference (D.6.9):**
- interval size, the stop, and per-interval frequency, with Blastware's
words (`N/A`, `>100` / `>200`, `<1.0`)
- each interval's vector sum, with its OORANGE rule
- #50's fixed-512 formula is retracted in place
- CLAUDE.md and the README roadmap follow
- Docs only.
- **Group A in the protocol reference, and the three meanings of mic
"units".**
- **D.6.8:** the identity block, the trigger-source bitmask and the trigger
settings.
- **D.6.6:** recorded data vs report units vs unit peaks, with the
MiniMate Plus and Blastware manual sections. CLAUDE.md carries the same
glossary.
- 🔶 Inferred: the histogram "terminal tail" `9c 06 00 42` is `9c 06 00`
plus the serial's `B`.
- Docs only: no code change, no migration.
- **Where file-only decoding stands, and that prod's ASCII overlay is
scaffolding.**
- **CLAUDE.md "Where things stand"** now says plainly that a paired
+34 -11
View File
@@ -45,13 +45,40 @@ Read this first when picking the project back up.
- **Byte layouts** of every field read from the file:
`docs/instantel_protocol_reference.md` Appendix **D.6**.
**Where the decoder stands on `dev`** (2026-11-03, run `20261103-121047`):
**18 of 88 fields match on every event**, up from about 6 before v0.33.0.
The four `dev` fixes below share one release and one backfill.
**Where the decoder stands on `dev`** (2026-11-03, run `20261103-213557`):
**47 of 88 fields match on every event**, up from about 6 before v0.33.0.
Everything below on `dev` shares one release and one backfill. Groups A, B
and C are done, which also fixed #50 and #51.
- 🔑 **Events are keyed unit + time + type:** `UNIQUE(serial, timestamp,
record_type)` (#51, Migration 3 in `sfm/database.py`, `dev`).
- A waveform and its histogram may share a second: 209 times in prod's
2026-09-30 store.
- Any lookup "by event" must include the type.
- An untyped event still dedups against an untyped row.
- Rehearsed on a copy of the prod snapshot: rows and ids kept, 9,852
histograms moved +1 s in place.
- ✅ **Match on every event:**
- sample rate, record time, pre-trigger, notes and event type (v0.33.0)
- geophone range, job number, event times (6,524 / 6,524) and histogram
start dates (63,518 / 63,518) — `dev`
- group A (`dev`, reference D.6.8): serial, version, calibration, battery,
trigger source, geo and mic trigger levels, stop mode, mic type
- group B (`dev`, D.6.9): interval frequencies, vector sums, size, stop
- group C (`dev`, D.6.10): histogram start and stop from the histogram's
own event record, interval times, and the peak dates and times
- 🔑 **"Units" means three different things — keep them apart** (reference
D.6.6):
- **Recorded data:** the mic samples and interval peaks in the file, as
raw counts with no unit.
- **Report units:** dB(L) or psi(L) in a report.
- A Blastware report uses that PC's Blastware preference at the moment
it wrote the report; carve-out `units-is-a-display-preference`.
- SFM's report uses SFM's own fixed choice.
- **Unit peaks:** the unit's own summary, in its keypad Microphone Units
setting. Shown on its screen, in Blastware's event list, and in the 0C
record.
- Where the unit stores that setting is not measured yet; a keypad test
on a bench unit would show it.
- ✅ **Geophone samples** are exact on **6,524 / 6,524** waveforms in every
year (`dev`; v0.33.0 had 6,491, its 33 others being Sensitive-range events
read 8× high).
@@ -65,18 +92,14 @@ Read this first when picking the project back up.
- ✅ **Histogram PVS** = the stored per-interval PVS²: 69,989 / 70,042.
**Mic:** one count = 0.25 Pa, dB offset 81.9384; a few dozen stragglers.
- ❌ **Open:**
- histogram start times are 1 s early (#51; fixing it moves every stored
histogram by 1 s, and the event key is (serial, time), so it needs a
decision first)
- the mic stragglers: ~20 one-minute histograms with an interval or two off
- Blastware prints `OORANGE` when the vector sum alone exceeds the range
(a carve-out to prove)
- ⬜ **Not read yet, in the order proposed** (2026-11-03):
- **A. Setup fields:** trigger source and levels, stop mode, mic type,
display units, firmware version, serial number, calibration, battery.
- **B. Histogram interval detail:** per-interval frequencies (#50: they
assume 1024 sps), per-interval PVS, interval size, stop time.
- **C. #51 timing:** start time, per-interval times, peak times.
- ~~**A. Setup fields**~~ ✅ done on `dev`.
- ~~**B. Histogram interval detail**~~ ✅ done on `dev`. Frequencies (#50),
per-interval PVS, interval size, stop.
- ~~**C. #51 timing**~~ ✅ done on `dev`.
- **D. Blastware's waveform calculations:** ZC frequency, acceleration,
displacement, time of peak.
- **E. Sensor check results.**
+5 -4
View File
@@ -647,18 +647,19 @@ Implementation steps (concrete):
3. flip ingest so reports are kept only for checking (retire the overlay)
4. stop the watchers forwarding reports
**Done so far: 18 of 88 report fields match on every DL2 event.**
**Done so far: 47 of 88 report fields match on every DL2 event.**
- In v0.33.0: setup fields, notes, event type, histogram PVS, mic.
- On `dev`:
- the geophone range
- the job number
- histograms that decoded wrongly
- the footer: no more day-late histograms; every waveform time exact
- serial, version, calibration, battery, trigger source and levels, stop mode, mic type
- histogram interval detail: frequencies (#50 fixed), per-interval PVS, interval size, stop
- histogram start, stop, interval and peak times (#51 fixed); events keyed unit + time + type
- A Blastware report's dB/psi is its PC's preference, not anything in the event file: a carve-out.
**Next:**
- setup fields still unread: trigger, stop mode, units, serial, calibration, battery
- histogram interval detail: frequencies (#50), per-interval PVS, interval size, stop time
- histogram start times (#51)
- the values Blastware computes itself: ZC frequency, acceleration, displacement, time of peak
- the sensor check results
- the monitor log
+141 -10
View File
@@ -11,7 +11,10 @@
| Date | Section | Change |
|---|---|---|
| 2026-11-03 | SUB 1A / 71 / 69 (settings read and write) | **The settings block, read and written as content (measured, BE9441's 10-26 recording and BE11529's 2026-04-20 captures).** **Read:** unescape each 1A data frame and take `data[11:]`; every frame but the last starts with one `00` that is not content; dropped, the frames join into **2,090 bytes headed by N = 2090: Series IV's `0x1A` content layout** (12 / 12 reads, Blastware's 4 × 512 + 42 and SFM's 1024 + 1024 + 42). The old "stable anchor" `be 80 00 00 00 00` is content `[12:18]` (pre-trigger −0.25 + stop mode Fixed). **Round trip:** the read after each of Blastware's two 10-26 writes equals the image it had just written, all 2,090 bytes (2 / 2). While monitoring, the read returns the device-info block (`0e 'BE9441' …`, 5 / 5). **`[26:28]`:** Blastware writes `00 00` on all 11 writes; the unit reads `01 7f` after a monitoring session (BE9441 10-26, BE11529 4-20 15:19) and sets it by itself; meaning unknown. **The two bytes after the block** (`[2090:2092]` of the 0x71 image) are Blastware's own per-unit constant -- `7c ea` on all nine of BE11529's writes, `0c e9` on both of BE9441's -- not the block's CRC-16/AUG, and in no reply of BE9441's three-hour session; SFM sends `00 00`. **`0x09` `[200:202]`:** Blastware echoed the unit's `8c 76` on all nine April writes; on 10-26 it read `17 17` and wrote `78 76` (read back so); meaning unknown. **Blastware re-renders the mic trigger level:** on BE11529's first write (4-20 15:19) the unit read 0.005 and 0.01 psi in its two `MicL` channel blocks (3 and 7; Series 3 carries 8 channel blocks of 48 bytes from `[1708]`, the second four prefixed `0x32`) and Blastware wrote 0.004983 and 0.010058 -- the same levels to its 0.1 dB; every other write left them alone. **Every one of the 11 Blastware writes reproduces** from the block before it with only the fields Blastware changed (plus that re-render and, on 10-26, the mic bit of `[25]`). Code: `minimateplus.protocol.assemble_compliance_content`, `read_compliance_content`, `micromate.setup_fields`; tests `tests/test_s3_settings_read.py`, `tests/test_setup_fields.py`. |
| 2026-11-03 (5) | SUB 1A / 71 / 69 (settings read and write) | **The settings block, read and written as content (measured, BE9441's 10-26 recording and BE11529's 2026-04-20 captures).** **Read:** unescape each 1A data frame and take `data[11:]`; every frame but the last starts with one `00` that is not content; dropped, the frames join into **2,090 bytes headed by N = 2090: Series IV's `0x1A` content layout** (12 / 12 reads, Blastware's 4 × 512 + 42 and SFM's 1024 + 1024 + 42). The old "stable anchor" `be 80 00 00 00 00` is content `[12:18]` (pre-trigger −0.25 + stop mode Fixed). **Round trip:** the read after each of Blastware's two 10-26 writes equals the image it had just written, all 2,090 bytes (2 / 2). While monitoring, the read returns the device-info block (`0e 'BE9441' …`, 5 / 5). **`[26:28]`:** Blastware writes `00 00` on all 11 writes; the unit reads `01 7f` after a monitoring session (BE9441 10-26, BE11529 4-20 15:19) and sets it by itself; meaning unknown. **The two bytes after the block** (`[2090:2092]` of the 0x71 image) are Blastware's own per-unit constant -- `7c ea` on all nine of BE11529's writes, `0c e9` on both of BE9441's -- not the block's CRC-16/AUG, and in no reply of BE9441's three-hour session; SFM sends `00 00`. **`0x09` `[200:202]`:** Blastware echoed the unit's `8c 76` on all nine April writes; on 10-26 it read `17 17` and wrote `78 76` (read back so); meaning unknown. **Blastware re-renders the mic trigger level:** on BE11529's first write (4-20 15:19) the unit read 0.005 and 0.01 psi in its two `MicL` channel blocks (3 and 7; Series 3 carries 8 channel blocks of 48 bytes from `[1708]`, the second four prefixed `0x32`) and Blastware wrote 0.004983 and 0.010058 -- the same levels to its 0.1 dB; every other write left them alone. **Every one of the 11 Blastware writes reproduces** from the block before it with only the fields Blastware changed (plus that re-render and, on 10-26, the mic bit of `[25]`). Code: `minimateplus.protocol.assemble_compliance_content`, `read_compliance_content`, `micromate.setup_fields`; tests `tests/test_s3_settings_read.py`, `tests/test_setup_fields.py`. |
| 2026-11-03 (4) | Appendix D.6.10 (NEW), D.6.11 | ✅ **Histogram timing from its own event record (#51).** `00 28 05 00` `04 00` `fe f5` [start][stop]: Blastware's Histogram Start and Stop on 63,490 / 63,490 each; exactly one per histogram, start 0–1 s after the footer's ts1. Interval time = its end (start + (i + 1) × interval, capped at the stop), 2,308,524 / 2,308,524 rows; a peak's date/time = its interval's. Retracted: "histograms stay on ts1" (it held only while SFM's events were unique on serial + time; now unit + time + type). 47 of 88 report fields match on every DL2 event. |
| 2026-11-03 (3) | Appendix D.6.9 (NEW), D.6.10 | ✅ **Histogram interval detail.** Interval size = uint16 seconds at `k − 40`; stop = footer ts2. Frequency = (sample rate / 2) / half-period, 527,915 / 527,915 cells at 1024 sps and 1,725 / 1,725 at 2048 — **#50 retracted** (a fixed 512 halved 2048-sps frequencies). Blastware's words: `N/A` (half-period 0), `>100` / `>200` (≤ 5 samples), `<1.0`. Per-interval vector sum √PVS²: 63,497 histograms; `OORANGE` when over range with a clamped channel, 17 / 17. 34 of 88 report fields now match on every DL2 event. |
| 2026-11-03 (2) | Appendix D.6.6, D.6.8 (NEW), D.6.9 | ✅ **Identity, battery and trigger, from the file.** **D.6.8:** the identity block before the setup name is SUB FE's (serial `k − 202`, firmware `k − 147`, DSP `k − 138`, calibration `k − 132` + by `k − 128`, model `k − 72`; battery uint16 /100 at `k − 190`); all 70,042 / 70,042. The embedded event record's two unknown bytes are the **trigger source** bitmask (6,524 / 6,524). Trigger sources `k − 19`, stop mode `k − 31`, per-channel trigger level float32 at label + 30, mic type at MicL + 4 (Series IV's code). **D.6.6:** recorded data vs report units vs unit peaks, with the manual sections; a Blastware report's dB/psi is the PC's preference. 🔶 `9c 06 00 42` (the histogram "terminal tail") looks like `9c 06 00` + the serial's `B`. 28 of 88 report fields now match on every DL2 event. |
| 2026-11-03 | Appendix D.3.3, D.6.1, D.6.3, D.6.5, D.6.7, §8 | ✅ **File-only decode, second pass (on `dev`).** **D.3.3:** the footer is the file's last 26 bytes (70,041 / 70,041); an earlier stop-time record fooled the first-match search on 14 files, making histograms a day late. Its `[18:24]` is **not** fixed (retracted). **D.6.1:** STRT[18] now picks the codec; the waveform codec had claimed 2018 5 s histograms. **D.6.3:** the job number (flags `k − 9` bit `0x02`, uint16 at `k − 8`; 2,997 / 2,997). **D.6.5:** the PVS² high word is non-zero above 1.28 in/s (retracted "reads 0000"), so the layout check now uses peak ≤ PVS ≤ √3·peak (34,502,955 / 34,502,955); Blastware's "Number of Intervals" is the monitoring time ÷ the interval. **§8:** where the 1995 default-clock events come from. 18 of 88 report fields now match on every DL2 event. |
| 2026-11-03 | call home (SUB 2C / 7E / 7F) | **SFM's call-home write, measured both ways.** SFM's 0x7E image (`write_image` of the 0x2C read with byte 5 set, framed ONCE) and its 0x7F confirm reproduce Blastware's 2026-04-20 enable and disable writes byte for byte (BE11529; `tests/test_s3_call_home_bw_frames.py`). Live on BE9441, idle: a no-op, on and off were all acked (0x81 / 0x80) and read back, and the unit's menu agreed. Only byte 5 changes: no unit-maintained field, unlike Series 4's `[118:120]`. Byte 5 is read from the UNESCAPED block. ⚠ Unescaping is not idempotent, so a built image must never pass through `write_image` again: a call-in time of 16:02-16:04 is `10 02`-`10 04` in the image. ⚠ **While monitoring, the unit answers the 0x2C read with its DEVICE-INFO block** ('Instantel', 'MiniMate Plus', its serial), as it answers 1A. Idle again, minutes later, it returns the call-home block. So a monitoring unit's call-home cannot be read-modify-written; SFM refuses with 'stop monitoring first'. A blind write while monitoring stays untested on purpose. |
| 2026-11-02 | Appendix D.3.1, D.6 (NEW), §15 | ✅ **Event fields SFM reads from the file alone (v0.33.0, plus the range on `dev`).** New D.6 records the bytes and the DL2 verification for each field: the record type `STRT[18]`, the recording-setup block (sample rate, pre-trigger, record time, the four notes), the geophone range (label + 29 in the setup's channel blocks), each histogram interval's PVS², and the mic scale (one count = 0.25 Pa). **Retracted in place:** D.3.1's `STRT[20]` = record time (it is `00` on every DL2 file; the "70 s" SFM used to report was `STRT[18]`, the record-type byte), and the 2026-08-26 reading of sub-minute histogram records as little-endian (big-endian from byte 5 since v0.32.0, #47/#49). **For #48:** the file's copy of the block puts the pre-trigger where the 1A "stable anchor" `be 80 00 00 00 00` sits. In the file, though, it is each event's own pre-trigger, which varies on the same unit on the same day (253–256 samples at 1024 sps), and Blastware reports it per event. So the file says little about whether the live 1A loses its anchor, and #48 stays open. |
@@ -3800,28 +3803,156 @@ Each interval stores its peak vector sum **squared**:
- **Verified:** interval psi mismatches fell from 42,783 to 26, and mic peak mismatches from 345
to 40.
#### D.6.7 Not read from the file yet
**Three things share the word "units". Keep them apart** (2026-11-03):
*Updated 2026-11-03. 18 of 88 report fields now match on every DL2 event.*
| Name | What it is | Its units are set by | Where it shows |
|---|---|---|---|
| **Recorded data** | the mic samples and interval peaks in the event file | nothing: they are raw counts | the event file |
| **Report units** | dB(L) or psi(L) in a report | Blastware's report: the PC's preference (Blastware manual 714U0301 Rev 22 §4, Preferences → Units and Channel). SFM's report: SFM's own fixed choice (PDF PSPL in dB(L), plot in psi) | a Blastware report, an SFM report |
| **Unit peaks** | the peaks the unit works out for its own summary | the unit's Microphone Units setting: psi(L), dB(L) or Pa(L), on the keypad (Right Arrow + Setups) or from Compliance Setup → Special Setups (MiniMate Plus manual 716U0101 Rev 15 §3.9.7) | the unit's screen, Blastware's event list, the 0C record on a live download |
- A Blastware report converts the recorded counts in its PC's preference. That is why DL2's
reports flip dB ↔ psi fleet-wide, in 61 clean runs by report-write time. The decode checker's
`units-is-a-display-preference` carve-out covers it.
- 🔶 **Where the unit stores its own setting, and its unit peaks, is not measured.** Blastware's
event list must read the unit peaks from somewhere, so they are probably in the event file,
perhaps near the embedded event record.
- **To settle it (proposed, not done):** on a bench unit, change Microphone Units on the keypad,
then diff a read-only `1A` read and a short recorded event.
#### D.6.8 Identity, battery and trigger ✅ 2026-11-03
**The identity block** sits before the setup name. It is what the live read gets from SUB FE
(`DeviceInfo`); offsets are from `k`:
| Offset | Content | DL2 |
|---|---|---|
| `k − 202` | serial number, NUL-terminated | 70,042 / 70,042 |
| `k − 193` | firmware minor (`0x11` = 17), as SUB EA | — |
| `k − 190` | battery, uint16 BE, hundredths of a volt | 70,042 / 70,042 (Blastware rounds half up: 6.25 → "6.3 Volts") |
| `k − 147` | firmware, `"S338.17"` | |
| `k − 138` | DSP version, `"10.72"` | Version 70,042 / 70,042 as `V {DSP}-{firmware after "S33"} {model}`; only `10.72-8.17` occurs, so the rule is proven for that alone |
| `k − 132` | calibration date, `dd mm yyyy` (BE year) | Calibration 70,042 / 70,042 as `{Month} {d}, {yyyy} by {k − 128}` |
| `k − 128` | calibrated by, `"Instantel"` | |
| `k − 94` | manufacturer, `"Instantel"` | |
| `k − 72` | model, `"MiniMate Plus"` / `"BlastMate III"` | |
- `k − 180 … k − 149` hold eight float32s (1.0, 8.0, then 1.0s). Not identified.
- 🔶 **Inferred, not measured:** the three bytes before the serial are `9c 06 00`. With the
serial's `B` (0x42) that makes `9c 06 00 42`, the histogram codec's "terminal tail". It looks
like the start of this record rather than the end of a block. Every serial starts with B
(BE… / BA…).
**The trigger source** is in the embedded event record (§7.8.9). The two bytes between its lead
`00 28 05 00` and `fe 80`, a uint16 BE bitmask, were "unknown" until now:
| Value | Blastware's Trigger |
|---|---|
| `0x0001` | Tran |
| `0x0002` | Vert |
| `0x0004` | Long |
| `0x0008` | MicL |
| `0x0200` | Manual |
That holds on 6,524 / 6,524 waveforms.
**Trigger settings,** in Series IV's `0x1A` layout:
| Offset | Content | DL2 |
|---|---|---|
| `k − 19` | trigger sources: `0x07` geophones, `0x08` mic (`0x80` seen once, not identified) | — |
| `k − 23` | active sensors, `0x0f` (all four) | 69,975, `0x07` on 8 mic-less files |
| `k − 31` | stop mode: 0 = Fixed | 6,524 / 6,524, the only value in DL2 |
| channel label + 30 | float32 trigger level: geophones in/s, mic psi | geo 6,484 / 6,484, mic 4,412 / 4,412 |
| MicL + 4 | mic type code: 2 = Linear Weighting, as Series IV | 70,034 / 70,034, the only value |
- **Blastware prints a trigger level only when its channel is a trigger source** and the event
was not Manual.
- **For the mic level in dB, Blastware converts with 6895 Pa per psi.** That gives 4,272 / 4,272;
the exact 6894.757 gives 4,271, failing one boundary case (0.01 psi → "130.8 dB(L)").
- **The file's channel block is the 1A's, 4 bytes earlier.** Compare the 1A's scale constant at
+28 and range at +33 with the file's +24 and +29.
#### D.6.9 Histogram interval detail ✅ 2026-11-03
**Interval size** is a uint16 count of seconds at `k − 40` (Series IV `[8:10]`): 2, 5, 15, 60 or
300. It matches Blastware's IntervalSize ("1 minute", "5 seconds", …) on 63,518 / 63,518 DL2
histograms. **The stop** is the footer's ts2: 63,460 / 63,518. The other 58 are Blastware a
second earlier, the #51 family.
**Each interval's frequency** comes from its half-period in samples:
`frequency = (sample rate / 2) / half-period`. That matches 527,915 / 527,915 printed cells at
1024 sps and 1,725 / 1,725 at 2048.
- ⚠ **RETRACTED (#50):** "frequency = 512 / half-period". 512 is half the sample rate at
1024 sps only; at 2048 sps it halved every frequency.
Blastware prints these words instead of a number, on ~3.1 M DL2 cells:
| half-period / frequency | printed |
|---|---|
| half-period 0 | `N/A` |
| half-period ≤ 5 samples | `>100` at 1024 sps, `>200` at 2048 |
| below 1 Hz | `<1.0` |
| below 10 Hz (20 at 2048) | one decimal |
| otherwise | a whole number |
All four channels match every DL2 histogram.
**Each interval's vector sum** is √PVS² (D.6.5) at the event's range: 63,497 histograms match.
- Blastware prints `OORANGE` for an interval's vector sum above the range when it also clamped
a channel in that interval: 17 / 17 cells. The decode checker's saturation carve-out covers
it.
- 4 cells sit about 4e-6 past a rounding boundary. Blastware's arithmetic is a hair lower; they
stay counted as mismatches.
#### D.6.10 Histogram timing — the histogram's own event record ✅ 2026-11-03 (#51)
**A histogram carries an embedded event record like a waveform's** (§7.8.9):
00 28 05 00 04 00 fe f5 [start 8 B] [stop 8 B]
lead source marker dd mm yyyy 00 hh mm ss (as the footer)
- **Source `04 00`** sits where a waveform's trigger-source bitmask goes (D.6.8).
- **The start is Blastware's Histogram Start Time** on 63,490 / 63,490 DL2 histograms, and the
stop is its Stop Time on 63,490 / 63,490.
- On all 63,500 there is exactly one such record. Its start is 0 or 1 s after the footer's ts1
(1 s on 61,645), and its stop 0 or 1 s before the footer's ts2 (1 s on 57).
- That makes the footer's start a second early on 97%. #51 had read it as SFM's error; it is
the footer's own convention.
**What follows from the start:**
| Field | Blastware's rule | DL2 sample |
|---|---|---|
| Each interval's printed time | its end: start + (i + 1) × interval, capped at the stop | 2,308,524 / 2,308,524 rows |
| Each peak's date and time (Tran, Vert, Long, vector sum, mic) | those of the interval holding its first maximum | 2,000 / 2,000 each |
> ⚠ **RETRACTED 2026-11-03:** "histograms stay on ts1". That held only while SFM's events
> table was unique on (serial, timestamp). A waveform and its histogram share a second in
> Blastware's timing (209 times in prod's 2026-09-30 store). SFM's events are now keyed on
> unit + time + type.
#### D.6.11 Not read from the file yet
*Updated 2026-11-03. 47 of 88 report fields now match on every DL2 event.*
- **Fields not read yet:**
- trigger source and levels, stop mode, mic type, display units, firmware version, serial
number, calibration, battery
- per-interval frequencies (#50: they assume 1024 sps), per-interval PVS, interval size,
histogram stop time
- extended notes
- the values Blastware computes: ZC frequency, acceleration, displacement, time of peak
- sensor check results
- monitor log
- **Open cases:**
- histogram start times are 1 s early (#51)
- about 20 one-minute histograms with a mic peak an interval or two off
- Blastware prints `OORANGE` when the vector sum alone exceeds the range (a carve-out still to
prove)
- Blastware prints `OORANGE` when an event's vector sum alone exceeds the range, with no
clamped channel (a carve-out still to prove; the interval version is proven, D.6.9)
- **Resolved on `dev`, 2026-11-02 → 03:**
- the 37 histograms that decoded wrongly (D.6.1, D.6.5)
- the 26 histogram start dates a day off (D.3.3; 17 of them were the same 5 s files, timed
as waveforms)
- the job number (D.6.3)
- identity, battery, trigger source and trigger settings (D.6.8); Units is Blastware's
preference (D.6.6)
- histogram interval detail: frequencies (#50), vector sums, interval size, stop (D.6.9)
- histogram start, stop, interval and peak times (#51, D.6.10)
---
+132 -16
View File
@@ -13,13 +13,16 @@ Pure: no I/O, and no import from `sfm/`.
"""
from __future__ import annotations
import datetime
import math
import re
from dataclasses import dataclass
from dataclasses import dataclass, field
from typing import Callable, Optional, Sequence
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)
from .histogram_codec import half_period_to_hz
from .models import Event
from .waveform_codec import mic_count_to_db
@@ -30,6 +33,50 @@ GEO_IPS_PER_COUNT: float = _GEO_NORMAL_FS_INS / _GEO_INT16_FS
_CHANNELS = ("Tran", "Vert", "Long", "MicL")
_EVENT_TYPE = {"Waveform": "Full Waveform", "Histogram": "Full Histogram"}
# How Blastware prints the setup fields SFM reads (measured 2026-11-03).
_MONTHS = ("January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December")
_TRIGGERED_BY = {0x0001: "Tran", 0x0002: "Vert", 0x0004: "Long", 0x0008: "MicL", 0x0200: "Manual"}
_STOP_MODES = {0: "Fixed"}
_MIC_TYPES = {2: "Linear Weighting"}
_GEO_TRIGGERS, _MIC_TRIGGER = 0x07, 0x08
# Blastware turns the mic trigger level from psi to dB with 6895 Pa per psi, not
# 6894.757: 4,272 / 4,272 DL2 levels against 4,271 (the odd one 0.01 psi,
# printed 130.8 dB(L), is 130.7498 at the exact constant).
_TRIGGER_PA_PER_PSI = 6895.0
def _setup_values(ev: Event) -> dict[str, object]:
out: dict[str, object] = {}
di = ev.device_info
if di is not None:
out["SerialNumber"] = di.serial
fw = di.firmware_version or ""
if di.dsp_version and fw.startswith("S33") and di.model:
# "V 10.72-8.17 MiniMate Plus" from "10.72", "S338.17" and the model --
# the only version in DL2, so the rule is proven for it alone.
out["Version"] = f"V {di.dsp_version}-{fw[3:]} {di.model}"
if di.calibration_date and di.calibrated_by:
c = di.calibration_date
out["Calibration"] = f"{_MONTHS[c.month - 1]} {c.day}, {c.year} by {di.calibrated_by}"
out["BatteryLevel"] = ev.battery_volts
out["Trigger"] = _TRIGGERED_BY.get(ev.triggered_by)
out["RecordStopMode"] = _STOP_MODES.get(ev.record_stop_mode)
out["Microphone"] = _MIC_TYPES.get(ev.mic_type)
# dB or psi is Blastware's preference, not the unit's (carve-out
# units-is-a-display-preference); SFM reports dB, the default.
out["Units"] = "in/s and dB(L)" if ev.mic_type is not None else "in/s"
# Blastware prints a trigger level only for a channel that is a trigger
# source, and none for a Manual trigger.
src, manual = ev.trigger_sources or 0, ev.triggered_by == 0x0200
if src & _GEO_TRIGGERS and not manual:
out["GeoTriggerLevel"] = ev.trigger_level_geo
if src & _MIC_TRIGGER and not manual and ev.trigger_level_mic_psi:
psi = ev.trigger_level_mic_psi
out["MicTriggerLevel psi(L)"] = psi
out["MicTriggerLevel dB(L)"] = 20 * math.log10(psi * _TRIGGER_PA_PER_PSI / 2e-5)
return out
@dataclass
class SfmSide:
@@ -40,6 +87,27 @@ class SfmSide:
channels: list[str] # channels with decoded data, in Tran/Vert/Long/MicL order
counts: dict[str, list[int]] # waveform samples or histogram interval peaks
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_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:
"""An interval's frequency as Blastware prints it: "N/A" for a half-period
of 0, ">100" (">200" at 2048 sps) at 5 samples or fewer, "<1.0" below 1 Hz,
else (sample rate / 2) / half-period in Hz. Measured on ~3.1 M DL2 cells,
2026-11-03 (#50: the rate, not a fixed 512)."""
if halfp == 0:
return "N/A"
hz = half_period_to_hz(halfp, sample_rate)
if hz is None:
return f">{round(100 * sample_rate / 1024)}"
return "<1.0" if hz < 1.0 else hz
def _interval_size(seconds: int) -> str:
n, unit = (seconds // 60, "minute") if seconds % 60 == 0 else (seconds, "second")
return f"{n} {unit}{'' if n == 1 else 's'}"
def sfm_side(raw: bytes) -> SfmSide:
@@ -72,6 +140,32 @@ def sfm_side(raw: bytes) -> SfmSide:
if counts["MicL"]:
values["MicLPSPL dB(L)"] = mic_count_to_db(max(abs(c) for c in counts["MicL"]))
values["MicLPSPL psi(L)"] = pv.micl if pv is not None else None
values.update(_setup_values(ev))
if ev.stop_time is not None:
values.update(HistogramStopDate=ev.stop_time.strftime("%Y-%m-%d"),
HistogramStopTime=ev.stop_time.strftime("%H:%M:%S"))
if ev.histogram_interval_sec:
values["IntervalSize"] = _interval_size(ev.histogram_interval_sec)
interval_values: dict[str, list[object]] = {}
if ev.interval_half_periods and ev.sample_rate:
for ch, hps in ev.interval_half_periods.items():
interval_values[f"{ch} Freq Hz"] = [interval_frequency(h, ev.sample_rate) for h in hps]
if 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(
event=ev,
@@ -82,6 +176,8 @@ def sfm_side(raw: bytes) -> SfmSide:
channels=[ch for ch in _CHANNELS if counts[ch]],
counts=counts,
geo_ips_per_count=_GEO_FS_BY_RANGE.get(ev.geo_range, _GEO_NORMAL_FS_INS) / _GEO_INT16_FS,
interval_values=interval_values,
interval_times=times,
)
@@ -144,10 +240,12 @@ def _mic_converter(ref: XmlReport) -> Optional[Callable[[int], float]]:
def _compare_scalar(tag: str, printed: str, sfm: SfmSide, ref: XmlReport) -> FieldResult:
if not printed.strip() or printed.strip() == "N/A":
return FieldResult(tag, "no_reference", printed, None)
if tag == "MicLPSPL":
units = ref.event_units or ""
key = ("MicLPSPL dB(L)" if "dB(L)" in units else
"MicLPSPL psi(L)" if "psi(L)" in units else None)
if tag in ("MicLPSPL", "MicTriggerLevel"):
# A printed value that states its unit is compared in that unit:
# K441LA17.IN0W's Units say psi(L), its MicTriggerLevel "125.0 dB(L)".
units = printed if ("dB(L)" in printed or "psi(L)" in printed) else (ref.event_units or "")
key = (f"{tag} dB(L)" if "dB(L)" in units else
f"{tag} psi(L)" if "psi(L)" in units else None)
value = sfm.values.get(key) if key else None
else:
value = sfm.values.get(tag)
@@ -166,9 +264,11 @@ def _compare_scalar(tag: str, printed: str, sfm: SfmSide, ref: XmlReport) -> Fie
return FieldResult(tag, "match" if ok else "mismatch", printed, _render(value, printed))
def _cell_diff(value: float, printed: str) -> Optional[float]:
def _cell_diff(value: object, printed: str) -> Optional[float]:
"""|value - printed| when the cell disagrees, else None; inf for a cell that
is not a number."""
is not a number. A word on SFM's side (">100", "N/A") must be printed."""
if isinstance(value, str):
return None if _same_text(value, printed) else float("inf")
p = _printed_number(printed)
if p is None:
return float("inf")
@@ -237,14 +337,19 @@ def series_pairs(sfm: SfmSide, ref: XmlReport,
if field.startswith("intervals."):
title = field[len("intervals."):]
columns = ref.interval_columns or []
convert = _interval_converter(title, sfm)
counts = sfm.counts.get(title.partition(" ")[0], [])
if convert is None or not counts or title not in columns:
if title not in columns:
return None
i = columns.index(title)
cells = [row[i] if i < len(row) else "" for _, row in (ref.intervals or [])]
pairs = [(j, cell, convert(c)) for j, (cell, c) in enumerate(zip(cells, counts))]
return pairs, abs(len(cells) - len(counts))
values = sfm.interval_values.get(title)
if values is None:
convert = _interval_converter(title, sfm)
counts = sfm.counts.get(title.partition(" ")[0], [])
if convert is None or not counts:
return None
values = [convert(c) for c in counts]
pairs = [(j, cell, v) for j, (cell, v) in enumerate(zip(cells, values))]
return pairs, abs(len(cells) - len(values))
return None
@@ -254,7 +359,9 @@ def _compare_series(field: str, n_bw: int, sfm: SfmSide, ref: XmlReport) -> Fiel
return FieldResult(field, "sfm_blank", f"{n_bw} rows", None)
pairs, row_len = got
diffs = [(j, d) for j, cell, v in pairs if (d := _cell_diff(v, cell)) is not None]
n_sfm = len(sfm.counts.get(field.split(".", 1)[1].partition(" ")[0], []))
title = field.split(".", 1)[1]
n_sfm = (len(sfm.interval_values[title]) if title in sfm.interval_values
else len(sfm.counts.get(title.partition(" ")[0], [])))
return _series_result(field, n_bw, n_sfm, diffs, row_len)
@@ -265,12 +372,21 @@ def _compare_samples(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 [])
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 []])
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]:
"""Every field Blastware's report carries, set against what SFM produced.
A mismatch a carve-out covers and applies to becomes `accepted`."""
+46 -3
View File
@@ -68,6 +68,21 @@ def _saturation(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool:
got = series_pairs(sfm, ref, res.field)
if got is None or got[1]:
return False
if res.field == "intervals.Geo PVS in/s":
# Per interval, as PeakVectorSum: an OORANGE vector sum, SFM's sum within
# three channels at the ceiling, and a channel Blastware itself clamped in
# that interval. 17 / 17 DL2 cells, SFM 10.01 .. 17.33 (2026-11-03).
cols = ref.interval_columns or []
peaks = [cols.index(c) for c in ("Tran Peak in/s", "Vert Peak in/s", "Long Peak in/s")
if c in cols]
rows = ref.intervals or []
differing = [(j, cell, v) for j, cell, v in got[0]
if isinstance(v, str) or not matches_printed(v, cell)]
return bool(differing) and all(
cell.strip() == "OORANGE" and not isinstance(v, str)
and r - _TOL <= v <= 3 ** 0.5 * r * 1.01
and any(_clamped(rows[j][1][p], r) for p in peaks if p < len(rows[j][1]))
for j, cell, v in differing)
differing = [(cell, v) for _, cell, v in got[0] if not matches_printed(v, cell)]
return bool(differing) and all(
_clamped(cell, r) and _at_ceiling(v, r)
@@ -79,10 +94,13 @@ SATURATION = Carveout(
id="saturation",
fields=("TranPPV", "VertPPV", "LongPPV", "PeakVectorSum",
"samples.Tran", "samples.Vert", "samples.Long",
"intervals.Tran Peak in/s", "intervals.Vert Peak in/s", "intervals.Long Peak in/s"),
"intervals.Tran Peak in/s", "intervals.Vert Peak in/s", "intervals.Long Peak in/s",
"intervals.Geo PVS in/s"),
evidence=("Blastware clamps a clipped channel to the range maximum and prints OORANGE; "
"the file holds counts past full scale (32016 counts = 10.005 in/s observed). "
"scratch/verify_against_ascii.py, 2026-08-28."),
"scratch/verify_against_ascii.py, 2026-08-28. An interval's vector sum prints "
"OORANGE when it exceeds the range in an interval with a clamped channel: 17 / 17 "
"DL2 cells, 2026-11-03."),
applies=_saturation,
)
@@ -106,4 +124,29 @@ INTERVAL_COUNT_IS_DURATION = Carveout(
applies=_interval_count_is_duration,
)
CARVEOUTS: tuple[Carveout, ...] = (SATURATION, INTERVAL_COUNT_IS_DURATION)
_MIC_UNITS = ("in/s and dB(L)", "in/s and psi(L)")
def _units_is_a_display_preference(sfm: SfmSide, ref: XmlReport, res: FieldResult) -> bool:
"""Both sides say the event has a mic; they differ only in dB against psi."""
return (" ".join((res.bw or "").split()) in _MIC_UNITS
and sfm.values.get("Units") in _MIC_UNITS)
UNITS_IS_A_DISPLAY_PREFERENCE = Carveout(
id="units-is-a-display-preference",
fields=("Units",),
evidence=("dB(L) or psi(L) is Blastware's display preference on the PC when it wrote the "
"report, not the unit's: in report-write order (the _XML.XML mtimes) DL2's 70,034 "
"reports switch fleet-wide in 61 clean runs, every unit at once, and no byte or "
"bit of the event file separates the two (k-240 .. k+520, nor the 1.2 KB before "
"the footer). Instantel documents both settings: the unit's own Microphone "
"Units (MiniMate Plus manual 716U0101 Rev 15 §3.9.7: psi(L), dB(L) or Pa(L), "
"keypad Right Arrow + Setups) and Blastware's report preference (Blastware "
"manual 714U0301 Rev 22 §4, Preferences > Units and Channel: Show Mic in dB / "
"in Linear Units). 2026-11-03."),
applies=_units_is_a_display_preference,
)
CARVEOUTS: tuple[Carveout, ...] = (SATURATION, INTERVAL_COUNT_IS_DURATION,
UNITS_IS_A_DISPLAY_PREFERENCE)
+195 -27
View File
@@ -19,18 +19,19 @@ import datetime
import hashlib
import json
import logging
import math
import os
import re
import struct
from pathlib import Path
from typing import Optional, Union
from .models import Event, PeakValues, ProjectInfo, Timestamp
from .models import DeviceInfo, Event, PeakValues, ProjectInfo, Timestamp
from . import blastware_file as _bw # avoid circular reference at module load
from .bw_ascii_report import BwAsciiReport
from . import waveform_codec as _wc
from .waveform_codec import decode_waveform_v2, decoded_to_adc_counts
from .histogram_codec import decode_histogram_body, interval_pvs
from .histogram_codec import channels_from_records, decode_histogram_body, decode_histogram_body_full
# Reference pressure for dB(L) → psi conversion (20 µPa expressed in psi).
# Same constant as sfm/sfm_webapp.html so server-side and browser-side
@@ -862,6 +863,7 @@ _RECTIME_OFFSET_BEFORE_MARKER = 30
# 2026-10-29). Offsets are from the first byte of the name.
_SETUP_NAME_RE = re.compile(rb"\x1c\x08([\x20-\x7e]{1,40})\x00")
_SAMPLE_RATE_BEFORE_NAME = 42 # uint16 BE, samples per second
_INTERVAL_BEFORE_NAME = 40 # uint16 BE, histogram interval in seconds (2 / 5 / 15 / 60 / 300)
_PRETRIG_BEFORE_NAME = 36 # float32 BE, seconds, negative (-0.25, -0.0625 ...)
_RECTIME_BEFORE_NAME = 30 # float32 BE, seconds (the marker's offset above)
_SAMPLE_RATES = (1024, 2048, 4096)
@@ -895,17 +897,22 @@ def _ts8(b: bytes) -> Optional[datetime.datetime]:
def _embedded_event_record(
raw: bytes, end: int, start: Optional[datetime.datetime],
stop: Optional[datetime.datetime], record_time: Optional[float],
) -> tuple[Optional[datetime.datetime], str]:
"""The trigger time from the instrument's embedded event record, or (None, why).
) -> tuple[Optional[datetime.datetime], str, Optional[int]]:
"""The trigger time and trigger source from the instrument's embedded event
record, or (None, why, None).
Every `fe 80` before `end` (the footer) is a candidate. One counts only if
its lead bytes match, both its times are well formed, the footer's session
start <= trigger <= its stop, its stop is the footer's stop or a second
before it, and its length agrees with the record time. Exactly one may
pass: none, or more than one, is reported rather than guessed between.
The two bytes between the lead and `fe 80` are the trigger source, a uint16
BE bitmask: 0x01 Tran, 0x02 Vert, 0x04 Long, 0x08 MicL, 0x200 Manual --
Blastware's Trigger on 6,493 / 6,493 DL2 waveforms (2026-11-03).
"""
if start is None or stop is None:
return None, "the footer has no start and stop to check one against"
return None, "the footer has no start and stop to check one against", None
found, rejected = [], 0
i = raw.find(_EVENT_RECORD_MARKER, 6)
while 0 <= i and i + 18 <= end:
@@ -921,15 +928,62 @@ def _embedded_event_record(
<= _EVENT_RECORD_SLACK_S[1])
)
if valid:
found.append(trig)
found.append((trig, int.from_bytes(raw[i - 2:i], "big")))
else:
rejected += 1
i = raw.find(_EVENT_RECORD_MARKER, i + 1)
if len(found) == 1:
return found[0], ""
return found[0][0], "", found[0][1]
if found:
return None, f"{len(found)} candidates validate"
return None, (f"{rejected} candidate(s), none valid" if rejected else "no candidate")
return None, f"{len(found)} candidates validate", 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]:
@@ -1047,6 +1101,83 @@ def _setup_geo_range(raw: bytes) -> tuple[Optional[int], Optional[str]]:
return None, f"geophone range not read: channel range bytes {found}"
# The identity block before the setup: what the live read gets from SUB FE
# (DeviceInfo). Offsets back from k, the setup name; matched against every DL2
# report 2026-11-03 -- serial, version and calibration 69,983 / 69,983, the
# battery 69,729 plus 254 that Blastware rounds half up (6.25 -> "6.3 Volts").
_SERIAL_BEFORE_NAME = 202 # ASCII, NUL-terminated
_BATTERY_BEFORE_NAME = 190 # uint16 BE, hundredths of a volt
_FIRMWARE_MINOR_BEFORE_NAME = 193 # 0x11 = 17 for S338.17, as SUB EA
_FIRMWARE_BEFORE_NAME = 147 # "S338.17"
_DSP_BEFORE_NAME = 138 # "10.72"
_CALIBRATION_BEFORE_NAME = 132 # dd mm yyyy (BE)
_CALIBRATED_BY_BEFORE_NAME = 128 # "Instantel"
_MANUFACTURER_BEFORE_NAME = 94 # "Instantel"
_MODEL_BEFORE_NAME = 72 # "MiniMate Plus" / "BlastMate III"
def _cstr(raw: bytes, i: int, limit: int = 40) -> Optional[str]:
if i < 0:
return None
j = raw.find(b"\x00", i, i + limit)
s = raw[i:j if j >= 0 else i + limit].decode("ascii", errors="replace").strip()
return s or None
def _setup_identity(raw: bytes, k: int) -> tuple[Optional[DeviceInfo], Optional[float]]:
"""(the unit's identity, the battery in volts) from the block before the
setup name at k."""
if k < _SERIAL_BEFORE_NAME:
return None, None
serial = _cstr(raw, k - _SERIAL_BEFORE_NAME, 16)
if not serial:
return None, None
c = k - _CALIBRATION_BEFORE_NAME
try:
cal = datetime.date(int.from_bytes(raw[c + 2:c + 4], "big"), raw[c + 1], raw[c])
except ValueError:
cal = None
info = DeviceInfo(
serial=serial,
firmware_minor=raw[k - _FIRMWARE_MINOR_BEFORE_NAME],
firmware_version=_cstr(raw, k - _FIRMWARE_BEFORE_NAME, 9),
dsp_version=_cstr(raw, k - _DSP_BEFORE_NAME, 6),
manufacturer=_cstr(raw, k - _MANUFACTURER_BEFORE_NAME),
model=_cstr(raw, k - _MODEL_BEFORE_NAME),
calibration_date=cal,
calibrated_by=_cstr(raw, k - _CALIBRATED_BY_BEFORE_NAME, 32),
)
b = k - _BATTERY_BEFORE_NAME
return info, int.from_bytes(raw[b:b + 2], "big") / 100
# Trigger settings, in Series IV's 0x1A layout again: the trigger-source bitmask
# at k - 19 ([29]: 0x07 geophones, 0x08 mic), the stop mode at k - 31 ([17],
# 0 = Fixed), and each channel block's trigger level, a float32 at label + 30 --
# in/s for a geophone, psi for the mic. The mic block's type code at label + 4
# is Series IV's (2 = linear). Against every DL2 waveform (2026-11-03): the geo
# level 6,447 / 6,447, the mic level 4,403 / 4,403, and Blastware prints a level
# exactly when its channel is a trigger source and the event was not Manual.
_TRIGGER_SOURCES_BEFORE_NAME = 19
_STOP_MODE_BEFORE_NAME = 31
_TRIGGER_LEVEL_AFTER_LABEL = 30
_MIC_TYPE_AFTER_LABEL = 4
def _setup_trigger(raw: bytes, k: int) -> dict:
out = {"trigger_sources": raw[k - _TRIGGER_SOURCES_BEFORE_NAME],
"record_stop_mode": raw[k - _STOP_MODE_BEFORE_NAME]}
t = raw.find(b"\x00\x00\x01Tran", k, k + _CHANNEL_BLOCK_SPAN)
if t >= 0:
p = t + 3 + _TRIGGER_LEVEL_AFTER_LABEL
out["trigger_level_geo"] = struct.unpack_from(">f", raw, p)[0]
m = raw.find(b"MicL", k, k + _CHANNEL_BLOCK_SPAN)
if m >= 0:
out["trigger_level_mic_psi"] = struct.unpack_from(">f", raw, m + _TRIGGER_LEVEL_AFTER_LABEL)[0]
out["mic_type"] = int.from_bytes(raw[m + _MIC_TYPE_AFTER_LABEL:m + _MIC_TYPE_AFTER_LABEL + 4], "big")
return out
def read_blastware_file(path: Union[str, Path], *, name: Optional[str] = None) -> Event:
"""Parse a Blastware event file into an Event: `decode_blastware_bytes` on its
bytes, `name` defaulting to the file's own (see there -- never a time source)."""
@@ -1195,8 +1326,10 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
problems = []
if record_type is None:
problems.append(f"unknown record type byte 0x{type_byte:02x} at STRT[18]")
hist_records = None
if record_type == "Histogram":
decoded = decode_histogram_body(body)
hist_records = decode_histogram_body_full(body)
decoded = channels_from_records(hist_records)
is_waveform_body = False
elif record_type == "Waveform":
decoded = decode_waveform_v2(body)
@@ -1205,7 +1338,8 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
decoded = decode_waveform_v2(body)
is_waveform_body = decoded is not None
if decoded is None:
decoded = decode_histogram_body(body)
hist_records = decode_histogram_body_full(body)
decoded = channels_from_records(hist_records)
if decoded is None:
log.warning(
"%s: body codec failed to decode (body starts %s) — "
@@ -1236,6 +1370,11 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
ev.geo_range, range_problem = _setup_geo_range(raw)
if range_problem:
ev.decode_problems.append(range_problem + "; peaks assume the Normal range")
k = _setup_name_at(raw)
if k is not None:
ev.device_info, ev.battery_volts = _setup_identity(raw, k)
for attr, value in _setup_trigger(raw, k).items():
setattr(ev, attr, value)
if is_waveform_body:
ev.rectime_seconds = _setup_record_time(raw)
ev.total_samples = len(samples["Tran"]) or None
@@ -1266,17 +1405,19 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
# 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
# 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
# record, marker fe f5, holds the exact start): 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) -- #51.
# A histogram's footer start runs a second early on 97%. Its own event
# record (marker fe f5) holds Blastware's exact start and stop, so it takes
# them from there (#51); events are keyed unit + time + type, so a waveform
# 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:
_stop = datetime.datetime(ts2.year, ts2.month, ts2.day,
ts2.hour, ts2.minute, ts2.second)
_rt = _parse_record_time_seconds(raw)
_start = (datetime.datetime(ts1.year, ts1.month, ts1.day, ts1.hour, ts1.minute, ts1.second)
if ts1 is not None else None)
_trig, _why = _embedded_event_record(raw, footer_pos, _start, _stop, _rt)
_trig, _why, ev.triggered_by = _embedded_event_record(raw, footer_pos, _start, _stop, _rt)
if _trig is not None:
ev.timestamp_source = "event_record"
else:
@@ -1298,13 +1439,25 @@ def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
hour=_trig.hour, minute=_trig.minute, second=_trig.second,
)
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(
raw=footer[2:10],
flag=0x10,
year=ts1.year, unknown_byte=0, month=ts1.month, day=ts1.day,
hour=ts1.hour, minute=ts1.minute, second=ts1.second,
year=_start.year, unknown_byte=0, month=_start.month, day=_start.day,
hour=_start.hour, minute=_start.minute, second=_start.second,
)
ev.timestamp_source = "footer"
ev.project_info = _setup_notes(raw)
ev.raw_samples = samples
@@ -1327,14 +1480,29 @@ 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.
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
if not is_waveform_body and ev.peak_values is not None:
# A histogram stores each interval's vector sum (squared); the event's
# is the largest. Combining the channel peaks instead read high on 86%
# of DL2's histograms -- they can come from different moments.
pvs = interval_pvs(body)
if pvs:
ev.peak_values.peak_vector_sum = (
max(pvs) * _HIST_GEO_COUNTS_PER_UNIT * geo_fs / _GEO_INT16_FS)
if ev.stop_time is None: # a histogram's record stop, else the footer's
ev.stop_time = ts2
if hist_records:
# A histogram stores each interval's vector sum (squared), and each
# channel's half-period: Blastware's per-interval Geo PVS (771,354 /
# 771,354 DL2 cells) and frequency, (sample rate / 2) / half-period.
unit_ins = _HIST_GEO_COUNTS_PER_UNIT * geo_fs / _GEO_INT16_FS
ev.interval_pvs = [math.sqrt(r["pvs_sq"]) * unit_ins for r in hist_records]
ev.interval_half_periods = {
ch: [r[key] for r in hist_records if r[key] is not None]
for ch, key in (("Tran", "t_halfp"), ("Vert", "v_halfp"),
("Long", "l_halfp"), ("MicL", "m_halfp"))}
if not ev.interval_half_periods["MicL"]:
del ev.interval_half_periods["MicL"]
k = _setup_name_at(raw)
if k is not None and k >= _INTERVAL_BEFORE_NAME:
ev.histogram_interval_sec = int.from_bytes(
raw[k - _INTERVAL_BEFORE_NAME:k - _INTERVAL_BEFORE_NAME + 2], "big") or None
if not is_waveform_body and ev.peak_values is not None and ev.interval_pvs:
# The event's vector sum is the largest interval's. Combining the
# channel peaks instead read high on 86% of DL2's histograms -- they
# can come from different moments.
ev.peak_values.peak_vector_sum = max(ev.interval_pvs)
ev._a5_frames = None # not recoverable from BW file
return ev
+18 -11
View File
@@ -156,10 +156,11 @@ _BLOCK_MARKER = 10
# 16-count-unit output (1 unit = 0.005 in/s = 16 ADC counts).
_GEO_LSB_INS = 0.005
# Frequency formula: freq_Hz = _FREQ_NUMERATOR / half_period_samples.
# Empirically determined to be 512 (= sample_rate / 2, where sample rate
# is 1024 sps for the standard MiniMate Plus configuration).
_FREQ_NUMERATOR = 512
# Frequency formula: freq_Hz = (sample_rate / 2) / half_period_samples.
# ⚠ RETRACTED 2026-11-03 (#50): "a fixed numerator of 512". 512 is sample_rate
# / 2 at 1024 sps only; at 2048 sps it halved every frequency. Measured on DL2:
# 527,915 / 527,915 cells at 1024 sps and 1,725 / 1,725 at 2048.
_FREQ_NUMERATOR = 512 # sample_rate / 2 at the default 1024 sps
def _is_data_block(block: bytes) -> bool:
@@ -300,7 +301,11 @@ def decode_histogram_body(body: bytes) -> Optional[dict]:
to get 1-count ADC values, then ``count / 32767 * 10.0`` for in/s)
- Mic channel: use ``waveform_codec.mic_count_to_db(count)``
"""
records = _walk_auto(body)
return channels_from_records(_walk_auto(body))
def channels_from_records(records: Optional[List[dict]]) -> Optional[dict]:
"""``decode_histogram_body``'s per-channel peaks, from records already walked."""
if not records:
return None
return {
@@ -338,17 +343,19 @@ def interval_pvs(body: bytes) -> Optional[List[float]]:
return [math.sqrt(r["pvs_sq"]) for r in records] if records else None
def half_period_to_hz(halfp: int) -> Optional[float]:
"""Convert a half-period in samples to frequency in Hz.
def half_period_to_hz(halfp: int, sample_rate: int = 1024) -> Optional[float]:
"""Convert a half-period in samples to frequency in Hz:
``(sample_rate / 2) / halfp``.
Returns ``None`` for half-period ≤ 5 — the device emits values in
that range when the measured zero-crossing rate exceeds 100 Hz
(the BW display reports `>100 Hz` for such cases). Callers can
treat ``None`` as the `>100 Hz` sentinel.
that range when the measured zero-crossing rate exceeds 100 Hz at
1024 sps (the BW display reports `>100`, `>200` at 2048 sps). Callers
can treat ``None`` as that sentinel. A half-period of 0 is Blastware's
"N/A"; it also returns None.
"""
if halfp <= 5:
return None
return _FREQ_NUMERATOR / halfp
return (sample_rate / 2) / halfp
def geo_count_to_ins(count: int) -> float:
+18
View File
@@ -300,6 +300,10 @@ class DeviceInfo:
# ── From SUB 08 (EVENT_INDEX_RESPONSE) ────────────────────────────────────
event_count: Optional[int] = None # stored event count from F7 response 🔶
# ── From a Blastware event file's identity block (2026-11-03) ─────────────
calibration_date: Optional[datetime.date] = None # e.g. 2019-02-20 ✅
calibrated_by: Optional[str] = None # e.g. "Instantel" ✅
def __str__(self) -> str:
fw = self.firmware_version or f"?.{self.firmware_minor}"
mdl = self.model or "MiniMate Plus"
@@ -548,6 +552,20 @@ class Event:
# Geophone range from the recording setup, as ComplianceConfig.geo_range:
# 0 Normal (10 in/s full scale), 1 Sensitive (1.25 in/s). None: not read.
geo_range: Optional[int] = None
# From a Blastware event file (2026-11-03); None when not read.
device_info: Optional["DeviceInfo"] = None # the unit, as SUB FE reports it
battery_volts: Optional[float] = None # at the event
triggered_by: Optional[int] = None # 0x01 Tran 0x02 Vert 0x04 Long 0x08 MicL 0x200 Manual
trigger_sources: Optional[int] = None # setup bitmask: 0x07 geophones, 0x08 mic
trigger_level_geo: Optional[float] = None # in/s, as ComplianceConfig.trigger_level_geo
trigger_level_mic_psi: Optional[float] = None
record_stop_mode: Optional[int] = None # 0 = Fixed
mic_type: Optional[int] = None # 2 = Linear Weighting (as Series IV)
stop_time: Optional[datetime.datetime] = None # the footer's stop
# A histogram's per-interval detail (2026-11-03); None for a waveform.
histogram_interval_sec: Optional[int] = None # as ComplianceConfig.histogram_interval_sec
interval_half_periods: Optional[dict] = None # channel -> half-period per interval, samples
interval_pvs: Optional[list] = None # each interval's vector sum, in/s
# Sensor self-check traces keyed by channel label — the short diagnostic
# waveforms the unit records when it pulses each sensor before monitoring
+5 -4
View File
@@ -73,7 +73,7 @@ def main(argv: list[str] | None = None) -> int:
conn.row_factory = sqlite3.Row
rows = list(conn.execute(
"SELECT id, serial, timestamp, blastware_filename "
"SELECT id, serial, timestamp, record_type, blastware_filename "
" FROM events "
" WHERE serial = 'UNKNOWN' "
" ORDER BY timestamp",
@@ -98,10 +98,11 @@ def main(argv: list[str] | None = None) -> int:
unresolved += 1
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(
"SELECT id FROM events WHERE serial = ? AND timestamp = ?",
(new_serial, ts),
"SELECT id FROM events WHERE serial = ? AND timestamp = ? AND record_type IS ?",
(new_serial, ts, row["record_type"]),
).fetchone()
action: str
if existing is None:
+65 -19
View File
@@ -36,6 +36,7 @@ from __future__ import annotations
import datetime
import json
import logging
import re
import sqlite3
import uuid
from pathlib import Path
@@ -107,7 +108,7 @@ CREATE TABLE IF NOT EXISTS events (
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
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_timestamp ON events(timestamp);
@@ -194,7 +195,7 @@ class SeismoDb:
row = conn.execute(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='events'"
).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)")
conn.executescript("""
ALTER TABLE events RENAME TO events_old;
@@ -348,6 +349,33 @@ class SeismoDb:
""")
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
def _iso(dt: Optional[datetime.datetime]) -> Optional[str]:
return dt.isoformat() if dt is not None else None
@@ -507,7 +535,8 @@ class SeismoDb:
device_family: Optional[str] = None,
) -> 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).
``waveform_records`` (optional): dict keyed by event waveform_key (hex)
@@ -515,7 +544,7 @@ class SeismoDb:
{"filename": str, "filesize": int, "a5_pickle_filename": str}
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
existing row so a re-download via the live endpoint refreshes the
file metadata.
@@ -558,18 +587,27 @@ class SeismoDb:
# 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)
why = self._estimate_guard(conn, serial, rec.get("filename"), ts,
ev.record_type)
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:
self._restamp_by_file(conn, serial, rec["filename"], ts,
ev.record_type) is False:
skipped += 1
continue
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(
"""
INSERT INTO events
@@ -629,7 +667,7 @@ class SeismoDb:
inserted += 1
except sqlite3.IntegrityError:
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
# the new data so that a re-import with better data (e.g.
# a watcher re-forward where the previous attempt missed
@@ -682,7 +720,7 @@ class SeismoDb:
shape_offset_axis = COALESCE(?, shape_offset_axis),
shape_offset_pre = COALESCE(?, shape_offset_pre),
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,
@@ -719,6 +757,7 @@ class SeismoDb:
rec.get("shape_offset_spread") if rec else None,
serial,
ts,
ev.record_type,
),
)
@@ -728,11 +767,11 @@ class SeismoDb:
@staticmethod
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.
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
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
@@ -747,8 +786,8 @@ class SeismoDb:
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()
"SELECT blastware_filename FROM events WHERE serial = ? AND timestamp = ? "
"AND record_type IS ?", (serial, ts, record_type)).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")
@@ -756,8 +795,9 @@ class SeismoDb:
@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.
ts: str, record_type: Optional[str] = None) -> Optional[bool]:
"""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
with a corrected time -- every Series-3 waveform after the event-time fix,
@@ -768,6 +808,10 @@ class SeismoDb:
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.
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
(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
@@ -778,18 +822,20 @@ class SeismoDb:
return None
mine = conn.execute(
"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",
(serial, filename, ts),
(serial, filename, ts, record_type),
).fetchone()
if mine is None:
return None
holder = conn.execute(
"SELECT id, blastware_filename FROM events WHERE serial = ? AND timestamp = ?",
(serial, ts),
"SELECT id, blastware_filename FROM events WHERE serial = ? AND timestamp = ? "
"AND record_type IS ?",
(serial, ts, record_type),
).fetchone()
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)",
serial, filename, mine[1], ts)
return True
+42
View File
@@ -34,6 +34,14 @@ Layout written to `<filename>.h5`:
sensor_location str
job_number int (only when read; kept while not shown)
job_number_enabled bool (Blastware prints the job number)
battery_volts, triggered_by, trigger_sources, trigger_level_geo_ips,
trigger_level_mic_psi, firmware_version, dsp_version, model,
calibration_date (ISO), calibrated_by
(each only when read from the event file)
histogram_interval_sec int (histograms)
/intervals (histograms, when read)
half_period/<ch> uint16 samples per interval; Hz = (sample rate / 2) / it
pvs_ips float32 each interval's vector sum, in/s
peak_tran_ips float (from 0C; authoritative)
peak_vert_ips float
peak_long_ips float
@@ -262,6 +270,24 @@ def write_event_hdf5(
if pi is not None and getattr(pi, "job_number", None) is not None:
attrs["job_number"] = int(pi.job_number)
attrs["job_number_enabled"] = bool(pi.job_number_enabled)
# Read from a Blastware file's identity and setup blocks; absent when not read.
for attr, value in (
("battery_volts", getattr(event, "battery_volts", None)),
("triggered_by", getattr(event, "triggered_by", None)),
("trigger_sources", getattr(event, "trigger_sources", None)),
("trigger_level_geo_ips", getattr(event, "trigger_level_geo", None)),
("trigger_level_mic_psi", getattr(event, "trigger_level_mic_psi", None)),
("histogram_interval_sec", getattr(event, "histogram_interval_sec", None)),
):
if value is not None:
attrs[attr] = value
di = getattr(event, "device_info", None)
if di is not None:
for attr in ("firmware_version", "dsp_version", "model", "calibrated_by"):
if getattr(di, attr, None):
attrs[attr] = getattr(di, attr)
if getattr(di, "calibration_date", None) is not None:
attrs["calibration_date"] = di.calibration_date.isoformat()
attrs["peak_tran_ips"] = float(pv.tran if pv and pv.tran is not None else 0.0)
attrs["peak_vert_ips"] = float(pv.vert if pv and pv.vert is not None else 0.0)
attrs["peak_long_ips"] = float(pv.long if pv and pv.long is not None else 0.0)
@@ -283,6 +309,22 @@ def write_event_hdf5(
compression="gzip", compression_opts=4, shuffle=True,
)
# /intervals — a histogram's per-interval detail as the file holds it:
# each channel's half-period in samples (frequency = (sample rate / 2)
# / half-period; 0 is Blastware's "N/A") and each interval's vector sum.
half_periods = getattr(event, "interval_half_periods", None)
interval_pvs = getattr(event, "interval_pvs", None)
if half_periods or interval_pvs:
igrp_iv = f.create_group("intervals")
if half_periods:
hgrp = igrp_iv.create_group("half_period")
for ch, hps in half_periods.items():
hgrp.create_dataset(ch, data=np.asarray(hps, dtype="uint16"),
compression="gzip", compression_opts=4, shuffle=True)
if interval_pvs:
igrp_iv.create_dataset("pvs_ips", data=np.asarray(interval_pvs, dtype="float32"),
compression="gzip", compression_opts=4, shuffle=True)
# /samples_int16 — optional raw ADC counts (preserved for analysis
# tools that want pre-conversion data). Cheap to include.
if include_int16:
Binary file not shown.
+116
View File
@@ -0,0 +1,116 @@
<?xml version="1.0" encoding="UTF-8"?>
<Event>
<FileVersion>8.0</FileVersion>
<EventType>Full Histogram</EventType>
<SerialNumber>BE18190</SerialNumber>
<Version>V 10.72-8.17 MiniMate Plus</Version>
<FileName>T190LD42.T00H</FileName>
<HistogramStartTime>13:29:24</HistogramStartTime>
<HistogramStartDate>2025-12-08</HistogramStartDate>
<HistogramStopTime>13:29:37</HistogramStopTime>
<HistogramStopDate>2025-12-08</HistogramStopDate>
<Channels>
<Channel>Tran</Channel>
<Channel>Vert</Channel>
<Channel>Long</Channel>
<Channel>MicL</Channel>
</Channels>
<NumberofIntervals>1.00</NumberofIntervals>
<IntervalSize>1 minute</IntervalSize>
<SampleRate>2048 sps</SampleRate>
<BatteryLevel>6.7 Volts</BatteryLevel>
<Calibration>June 13, 2025 by Instantel</Calibration>
<Units>in/s and dB(L)</Units>
<Project>I-80-North Fork-Area 3-462Richardsvilel</Project>
<Client>Fay Company</Client>
<UserName>Terra-Mechanics Inc.- Harrison</UserName>
<SeisLoc>Loc #8 - Area 3- 462 Richardsville Road</SeisLoc>
<GeoRange>
<Value>10.000</Value>
<Units>in/s</Units>
</GeoRange>
<TranPPV>
<Value>1.280</Value>
<Units>in/s</Units>
</TranPPV>
<VertPPV>
<Value>2.615</Value>
<Units>in/s</Units>
</VertPPV>
<LongPPV>
<Value>1.120</Value>
<Units>in/s</Units>
</LongPPV>
<TranZCFreq>
<Value>15.5</Value>
<Units>Hz</Units>
</TranZCFreq>
<VertZCFreq>
<Value>64</Value>
<Units>Hz</Units>
</VertZCFreq>
<LongZCFreq>
<Value>17.7</Value>
<Units>Hz</Units>
</LongZCFreq>
<TranPeakTime>13:29:37</TranPeakTime>
<TranPeakDate>2025-12-08</TranPeakDate>
<VertPeakTime>13:29:37</VertPeakTime>
<VertPeakDate>2025-12-08</VertPeakDate>
<LongPeakTime>13:29:37</LongPeakTime>
<LongPeakDate>2025-12-08</LongPeakDate>
<PeakVectorSum>
<Value>2.644</Value>
<Units>in/s</Units>
</PeakVectorSum>
<PeakVectorSumTime>13:29:37</PeakVectorSumTime>
<PeakVectorSumDate>2025-12-08</PeakVectorSumDate>
<Microphone>Linear Weighting</Microphone>
<MicLPSPL>
<Value>107.0</Value>
<Units>dB(L)</Units>
</MicLPSPL>
<MicLTime>13:29:37</MicLTime>
<MicLDate>2025-12-08</MicLDate>
<MicLZCFreq>
<Value>51</Value>
<Units>Hz</Units>
</MicLZCFreq>
<TranTestFreq>7.4 Hz.</TranTestFreq>
<TranTestRatio>4.2</TranTestRatio>
<TranTestResults>Passed</TranTestResults>
<VertTestFreq>7.6 Hz.</VertTestFreq>
<VertTestRatio>3.4</VertTestRatio>
<VertTestResults>Passed</VertTestResults>
<LongTestFreq>7.3 Hz.</LongTestFreq>
<LongTestRatio>3.7</LongTestRatio>
<LongTestResults>Passed</LongTestResults>
<MicLTestFreq>0.0 Hz.</MicLTestFreq>
<MicLTestAmplitude>0 mv</MicLTestAmplitude>
<MicLTestResults>Check</MicLTestResults>
<UsbSummaryChannels>
</UsbSummaryChannels>
<MonitorLog>2025-12-08 13:29:23 - 2025-12-08 13:29:37 &quot;Event Recorded Modem Exit&quot;</MonitorLog>
<HistogramData>
<HistogramDataColumnTitle>
<ColumnTitle> Tran Peak in/s </ColumnTitle>
<ColumnTitle> Tran Freq Hz </ColumnTitle>
<ColumnTitle> Vert Peak in/s </ColumnTitle>
<ColumnTitle> Vert Freq Hz </ColumnTitle>
<ColumnTitle> Long Peak in/s </ColumnTitle>
<ColumnTitle> Long Freq Hz </ColumnTitle>
<ColumnTitle> Geo PVS in/s </ColumnTitle>
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
<ColumnTitle> MicL Freq Hz </ColumnTitle>
</HistogramDataColumnTitle>
<HistogramDataIntervals>
<Time>2025-12-08 13:29:37</Time>
<Row>
<Cell>1.280</Cell><Cell>15.5</Cell><Cell>2.615</Cell><Cell>64</Cell><Cell>1.120</Cell><Cell>17.7</Cell><Cell>2.644</Cell><Cell>0.001</Cell><Cell>107.0</Cell><Cell>51</Cell></Row>
</HistogramDataIntervals>
</HistogramData>
<HistogramDataUsbChannels>
</HistogramDataUsbChannels>
</Event>
Binary file not shown.
+116
View File
@@ -0,0 +1,116 @@
<?xml version="1.0" encoding="UTF-8"?>
<Event>
<FileVersion>8.0</FileVersion>
<EventType>Full Histogram</EventType>
<SerialNumber>BE18190</SerialNumber>
<Version>V 10.72-8.17 MiniMate Plus</Version>
<FileName>T190LD5Q.LD0H</FileName>
<HistogramStartTime>11:00:49</HistogramStartTime>
<HistogramStartDate>2025-12-09</HistogramStartDate>
<HistogramStopTime>11:00:59</HistogramStopTime>
<HistogramStopDate>2025-12-09</HistogramStopDate>
<Channels>
<Channel>Tran</Channel>
<Channel>Vert</Channel>
<Channel>Long</Channel>
<Channel>MicL</Channel>
</Channels>
<NumberofIntervals>1.00</NumberofIntervals>
<IntervalSize>1 minute</IntervalSize>
<SampleRate>1024 sps</SampleRate>
<BatteryLevel>6.9 Volts</BatteryLevel>
<Calibration>June 13, 2025 by Instantel</Calibration>
<Units>in/s and dB(L)</Units>
<Project>I-80-North Fork-Area 3-462Richardsvilel</Project>
<Client>Fay Company</Client>
<UserName>Terra-Mechanics Inc.- Harrison</UserName>
<SeisLoc>Loc #8 - Area 3- 462 Richardsville Road</SeisLoc>
<GeoRange>
<Value>10.000</Value>
<Units>in/s</Units>
</GeoRange>
<TranPPV>
<Value>2.140</Value>
<Units>in/s</Units>
</TranPPV>
<VertPPV>
<Value>OORANGE</Value>
<Units>in/s</Units>
</VertPPV>
<LongPPV>
<Value>2.830</Value>
<Units>in/s</Units>
</LongPPV>
<TranZCFreq>
<Value>&gt;100</Value>
<Units>Hz</Units>
</TranZCFreq>
<VertZCFreq>
<Value>85</Value>
<Units>Hz</Units>
</VertZCFreq>
<LongZCFreq>
<Value>34</Value>
<Units>Hz</Units>
</LongZCFreq>
<TranPeakTime>11:00:59</TranPeakTime>
<TranPeakDate>2025-12-09</TranPeakDate>
<VertPeakTime>11:00:59</VertPeakTime>
<VertPeakDate>2025-12-09</VertPeakDate>
<LongPeakTime>11:00:59</LongPeakTime>
<LongPeakDate>2025-12-09</LongPeakDate>
<PeakVectorSum>
<Value>OORANGE</Value>
<Units>in/s</Units>
</PeakVectorSum>
<PeakVectorSumTime>11:00:59</PeakVectorSumTime>
<PeakVectorSumDate>2025-12-09</PeakVectorSumDate>
<Microphone>Linear Weighting</Microphone>
<MicLPSPL>
<Value>106.0</Value>
<Units>dB(L)</Units>
</MicLPSPL>
<MicLTime>11:00:59</MicLTime>
<MicLDate>2025-12-09</MicLDate>
<MicLZCFreq>
<Value>85</Value>
<Units>Hz</Units>
</MicLZCFreq>
<TranTestFreq>7.4 Hz.</TranTestFreq>
<TranTestRatio>4.4</TranTestRatio>
<TranTestResults>Passed</TranTestResults>
<VertTestFreq>7.6 Hz.</VertTestFreq>
<VertTestRatio>3.5</VertTestRatio>
<VertTestResults>Passed</VertTestResults>
<LongTestFreq>7.3 Hz.</LongTestFreq>
<LongTestRatio>3.9</LongTestRatio>
<LongTestResults>Passed</LongTestResults>
<MicLTestFreq>20.5 Hz.</MicLTestFreq>
<MicLTestAmplitude>691 mv</MicLTestAmplitude>
<MicLTestResults>Passed</MicLTestResults>
<UsbSummaryChannels>
</UsbSummaryChannels>
<MonitorLog>2025-12-09 11:00:48 - 2025-12-09 11:00:59 &quot;Event Recorded Modem Exit&quot;</MonitorLog>
<HistogramData>
<HistogramDataColumnTitle>
<ColumnTitle> Tran Peak in/s </ColumnTitle>
<ColumnTitle> Tran Freq Hz </ColumnTitle>
<ColumnTitle> Vert Peak in/s </ColumnTitle>
<ColumnTitle> Vert Freq Hz </ColumnTitle>
<ColumnTitle> Long Peak in/s </ColumnTitle>
<ColumnTitle> Long Freq Hz </ColumnTitle>
<ColumnTitle> Geo PVS in/s </ColumnTitle>
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
<ColumnTitle> MicL Freq Hz </ColumnTitle>
</HistogramDataColumnTitle>
<HistogramDataIntervals>
<Time>2025-12-09 11:00:59</Time>
<Row>
<Cell>2.140</Cell><Cell>&gt;100</Cell><Cell>OORANGE</Cell><Cell>85</Cell><Cell>2.830</Cell><Cell>34</Cell><Cell>OORANGE</Cell><Cell>0.001</Cell><Cell>106.0</Cell><Cell>85</Cell></Row>
</HistogramDataIntervals>
</HistogramData>
<HistogramDataUsbChannels>
</HistogramDataUsbChannels>
</Event>
Binary file not shown.
+116
View File
@@ -0,0 +1,116 @@
<?xml version="1.0" encoding="UTF-8"?>
<Event>
<FileVersion>8.0</FileVersion>
<EventType>Full Histogram</EventType>
<SerialNumber>BE9558</SerialNumber>
<Version>V 10.72-8.17 MiniMate Plus</Version>
<FileName>K558L4KY.440H</FileName>
<HistogramStartTime>17:04:52</HistogramStartTime>
<HistogramStartDate>2025-06-25</HistogramStartDate>
<HistogramStopTime>17:05:39</HistogramStopTime>
<HistogramStopDate>2025-06-25</HistogramStopDate>
<Channels>
<Channel>Tran</Channel>
<Channel>Vert</Channel>
<Channel>Long</Channel>
<Channel>MicL</Channel>
</Channels>
<NumberofIntervals>1.00</NumberofIntervals>
<IntervalSize>5 minutes</IntervalSize>
<SampleRate>1024 sps</SampleRate>
<BatteryLevel>6.3 Volts</BatteryLevel>
<Calibration>June 13, 2025 by Instantel</Calibration>
<Units>in/s and dB(L)</Units>
<Project>Fay - Locks &amp; Dam No3 -Loc 5 Synthomer</Project>
<Client>Fay Company</Client>
<UserName>Terra-Mechanics Inc - Harrison</UserName>
<Seis.Loc>Location #5 Sythomer Plant</Seis.Loc>
<GeoRange>
<Value>10.000</Value>
<Units>in/s</Units>
</GeoRange>
<TranPPV>
<Value>2.315</Value>
<Units>in/s</Units>
</TranPPV>
<VertPPV>
<Value>2.715</Value>
<Units>in/s</Units>
</VertPPV>
<LongPPV>
<Value>5.115</Value>
<Units>in/s</Units>
</LongPPV>
<TranZCFreq>
<Value>10</Value>
<Units>Hz</Units>
</TranZCFreq>
<VertZCFreq>
<Value>85</Value>
<Units>Hz</Units>
</VertZCFreq>
<LongZCFreq>
<Value>19</Value>
<Units>Hz</Units>
</LongZCFreq>
<TranPeakTime>17:05:39</TranPeakTime>
<TranPeakDate>2025-06-25</TranPeakDate>
<VertPeakTime>17:05:39</VertPeakTime>
<VertPeakDate>2025-06-25</VertPeakDate>
<LongPeakTime>17:05:39</LongPeakTime>
<LongPeakDate>2025-06-25</LongPeakDate>
<PeakVectorSum>
<Value>5.559</Value>
<Units>in/s</Units>
</PeakVectorSum>
<PeakVectorSumTime>17:05:39</PeakVectorSumTime>
<PeakVectorSumDate>2025-06-25</PeakVectorSumDate>
<Microphone>Linear Weighting</Microphone>
<MicLPSPL>
<Value>111.8</Value>
<Units>dB(L)</Units>
</MicLPSPL>
<MicLTime>17:05:39</MicLTime>
<MicLDate>2025-06-25</MicLDate>
<MicLZCFreq>
<Value>43</Value>
<Units>Hz</Units>
</MicLZCFreq>
<TranTestFreq>7.7 Hz.</TranTestFreq>
<TranTestRatio>3.9</TranTestRatio>
<TranTestResults>Passed</TranTestResults>
<VertTestFreq>7.5 Hz.</VertTestFreq>
<VertTestRatio>3.8</VertTestRatio>
<VertTestResults>Passed</VertTestResults>
<LongTestFreq>7.5 Hz.</LongTestFreq>
<LongTestRatio>3.7</LongTestRatio>
<LongTestResults>Passed</LongTestResults>
<MicLTestFreq>0.0 Hz.</MicLTestFreq>
<MicLTestAmplitude>0 mv</MicLTestAmplitude>
<MicLTestResults>Check</MicLTestResults>
<UsbSummaryChannels>
</UsbSummaryChannels>
<MonitorLog>2025-06-25 17:04:51 - 2025-06-25 17:05:39 &quot;Event Recorded Modem Exit&quot;</MonitorLog>
<HistogramData>
<HistogramDataColumnTitle>
<ColumnTitle> Tran Peak in/s </ColumnTitle>
<ColumnTitle> Tran Freq Hz </ColumnTitle>
<ColumnTitle> Vert Peak in/s </ColumnTitle>
<ColumnTitle> Vert Freq Hz </ColumnTitle>
<ColumnTitle> Long Peak in/s </ColumnTitle>
<ColumnTitle> Long Freq Hz </ColumnTitle>
<ColumnTitle> Geo PVS in/s </ColumnTitle>
<ColumnTitle> MicL Peak psi(L) </ColumnTitle>
<ColumnTitle> MicL Peak dB(L) </ColumnTitle>
<ColumnTitle> MicL Freq Hz </ColumnTitle>
</HistogramDataColumnTitle>
<HistogramDataIntervals>
<Time>2025-06-25 17:05:39</Time>
<Row>
<Cell>2.315</Cell><Cell>10</Cell><Cell>2.715</Cell><Cell>85</Cell><Cell>5.115</Cell><Cell>19</Cell><Cell>5.559</Cell><Cell>0.001</Cell><Cell>111.8</Cell><Cell>43</Cell></Row>
</HistogramDataIntervals>
</HistogramData>
<HistogramDataUsbChannels>
</HistogramDataUsbChannels>
</Event>
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large. Load diff
Binary file not shown.
File diff suppressed because it is too large. Load diff
+36 -6
View File
@@ -141,10 +141,12 @@ def test_a_report_fills_in_when_the_record_is_missing():
assert (_dt(ev.timestamp), ev.timestamp_source) == (TRIGGER, "report")
def test_a_histogram_keeps_its_footer_start_for_now():
# Its record (marker fe f5) also holds Blastware's start -- that change is #51.
def test_a_histogram_takes_its_event_records_start():
# #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)
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():
@@ -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.waveform_store import WaveformStore
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,
hour=14, minute=23, second=43)
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)
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
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)
with sqlite3.connect(str(db.db_path)) as c:
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 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"
+130
View File
@@ -365,3 +365,133 @@ def test_a_waveform_with_the_early_record_is_timed_from_its_trigger():
# Blastware: 2019-09-26 11:14:08, record time 4 s (SFM read the stop, 11:14:12)
assert (ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second) == (2019, 9, 26, 11, 14, 8)
assert ev.timestamp_source in ("event_record", "estimate")
# ── Group A: identity, battery, trigger ─────────────────────────────────────
# The identity block before the setup name is what the live read gets from
# SUB FE (DeviceInfo): serial k-202, firmware k-147, DSP version k-138,
# calibration date k-132 and "by" k-128, manufacturer k-94, model k-72; the
# battery is a uint16 of hundredths of a volt at k-190. Measured against every
# DL2 report 2026-11-03 (serial, version, calibration 69,983 / 69,983).
import datetime as _dt # noqa: E402
_SF = "setup-fields-11-03-26"
def test_the_identity_block_is_read():
# Blastware: BE18189, "V 10.72-8.17 MiniMate Plus",
# "February 20, 2019 by Instantel", "6.8 Volts"
ev = read_blastware_file(_FIX / _SF / "T189HUD6.QE0W")
di = ev.device_info
assert (di.serial, di.firmware_version, di.dsp_version, di.manufacturer, di.model) == (
"BE18189", "S338.17", "10.72", "Instantel", "MiniMate Plus")
assert di.firmware_minor == 17
assert (di.calibration_date, di.calibrated_by) == (_dt.date(2019, 2, 20), "Instantel")
assert abs(ev.battery_volts - 6.8) <= 0.05 + 1e-9
def test_the_battery_is_kept_exact():
# Blastware prints "6.3 Volts" for a stored 6.25: it rounds half up.
assert read_blastware_file(_FIX / _SF / "K558L4KY.440H").battery_volts == 6.25
# (file, Blastware's Trigger as the event record's bitmask, geo level in/s,
# mic level psi or None, mic a trigger source)
@pytest.mark.parametrize("rel,by,geo,mic_psi,mic_src", [
(f"{_SF}/T189HUD6.QE0W", 0x0008, 0.050, 0.0072, True), # MicL, 128.0 dB(L)
(f"{_SF}/T438L713.RY0W", 0x0002, 0.500, 0.0100, True), # Vert, 130.8 dB(L)
(f"{_SF}/M529I6LG.3Y0W", 0x0004, 0.050, 0.005, True), # Long, 0.005 psi(L)
("bw-import-fields-10-29-26/R352HIUI.F40W", 0x0001, 0.400, None, False), # Tran
("decode-checker-10-29-26/T1905KDW.5F0W", 0x0200, None, None, None), # Manual
])
def test_the_trigger_comes_from_the_file(rel, by, geo, mic_psi, mic_src):
ev = read_blastware_file(_FIX / rel)
assert ev.triggered_by == by
if geo is not None:
assert abs(ev.trigger_level_geo - geo) <= 0.0005 + 1e-9
if mic_psi is not None:
assert abs(ev.trigger_level_mic_psi - mic_psi) <= 0.0005 + 1e-9 # psi to 3 places, as printed
if mic_src is not None:
assert bool(ev.trigger_sources & 0x08) == mic_src
assert (ev.record_stop_mode, ev.mic_type) == (0, 2) # Fixed, Linear Weighting
def test_the_h5_carries_the_setup_fields(tmp_path):
import h5py
from sfm import event_hdf5
ev = read_blastware_file(_FIX / _SF / "T189HUD6.QE0W")
event_hdf5.write_event_hdf5(tmp_path / "e.h5", ev, serial="BE18189")
with h5py.File(tmp_path / "e.h5", "r") as f:
a = f.attrs
assert abs(float(a["battery_volts"]) - 6.8) <= 0.05 + 1e-9
assert (int(a["triggered_by"]), int(a["trigger_sources"])) == (0x0008, ev.trigger_sources)
assert abs(float(a["trigger_level_geo_ips"]) - 0.050) <= 0.0005 + 1e-9
assert abs(float(a["trigger_level_mic_psi"]) - ev.trigger_level_mic_psi) < 1e-9
assert (str(a["firmware_version"]), str(a["dsp_version"]), str(a["calibration_date"])) == (
"S338.17", "10.72", "2019-02-20")
# ── Group B: histogram interval detail ──────────────────────────────────────
# Interval size is the setup's uint16 seconds at k - 40 (Series IV [8:10]); the
# stop is the footer's. Each interval keeps its half-periods and its vector sum
# (PVS^2). Frequency = (sample rate / 2) / half-period: 527,915 / 527,915 cells
# at 1024 sps and 1,725 / 1,725 at 2048 (#50: the old fixed 512 halved every
# 2048-sps frequency). Measured 2026-11-03.
from minimateplus.histogram_codec import half_period_to_hz # noqa: E402
_HB = "histogram-intervals-11-03-26"
@pytest.mark.parametrize("rel,sr,freqs,pvs,stop", [
# Blastware: 1 minute; Tran 32, Vert 47, Long 14, MicL 47 Hz; PVS 1.358; stop 12:49:33
("decode-checker-10-29-26/T004JTRF.ME0H", 1024,
{"Tran": 32, "Vert": 47, "Long": 14, "MicL": 47}, 1.358, (2022, 12, 28, 12, 49, 33)),
# Blastware: 1 minute at 2048 sps; Tran 15.5, Vert 64, Long 17.7, MicL 51 Hz; PVS 2.644
(f"{_HB}/T190LD42.T00H", 2048,
{"Tran": 15.5, "Vert": 64, "Long": 17.7, "MicL": 51}, 2.644, (2025, 12, 8, 13, 29, 37)),
])
def test_histogram_interval_detail_comes_from_the_file(rel, sr, freqs, pvs, stop):
ev = read_blastware_file(_FIX / rel)
assert (ev.sample_rate, ev.histogram_interval_sec) == (sr, 60)
for ch, hz in freqs.items():
got = half_period_to_hz(ev.interval_half_periods[ch][0], ev.sample_rate)
d = 1 if isinstance(hz, float) else 0
assert abs(got - hz) <= 0.5 * 10 ** -d + 1e-9, (ch, got, hz)
assert abs(ev.interval_pvs[0] - pvs) <= 0.0005 + 1e-9
t = ev.stop_time
assert (t.year, t.month, t.day, t.hour, t.minute, t.second) == stop
def test_the_h5_carries_the_interval_detail(tmp_path):
import h5py
from sfm import event_hdf5
ev = read_blastware_file(_FIX / _HB / "T190LD42.T00H")
event_hdf5.write_event_hdf5(tmp_path / "e.h5", ev, serial="BE18190")
with h5py.File(tmp_path / "e.h5", "r") as f:
assert int(f.attrs["histogram_interval_sec"]) == 60
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
# ── #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)
+6 -3
View File
@@ -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)
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_a_histogram_now_agrees_with_its_filename():
# #51: the start comes from the histogram's own event record, which is
# 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):
+125 -3
View File
@@ -39,7 +39,8 @@ def test_event_type_comes_from_the_bytes():
def test_report_fields_stay_blank():
s = sfm_side((FIX / "T1905KDW.5F0W").read_bytes())
for tag in ("TranZCFreq", "TranPeakAcceleration", "BatteryLevel", "Calibration", "TranTestResults"):
# (BatteryLevel and Calibration are read since 2026-11-03: test_the_setup_fields_match_blastware)
for tag in ("TranZCFreq", "TranPeakAcceleration", "TranTestResults"):
assert s.values.get(tag) is None
@@ -66,7 +67,7 @@ def test_full_waveform_row_verdicts():
"notes", "samples.Tran", "samples.Vert", "samples.Long"):
assert res[f].verdict == "match", (f, res[f])
assert res["TranZCFreq"].verdict in ("sfm_blank", "no_reference")
assert res["BatteryLevel"].verdict == "sfm_blank"
assert res["BatteryLevel"].verdict == "match" # 6.72 V, printed "6.7 Volts"
assert "FileName" not in res
@@ -95,7 +96,7 @@ def test_zc_frequency_na_and_above_range():
def test_mic_units_pick_the_conversion():
res = _results("T004JTRF.ME0H") # psi(L)
assert res["intervals.MicL Peak dB(L)"].verdict in ("match", "mismatch")
assert res["intervals.Tran Freq Hz"].verdict == "sfm_blank"
assert res["intervals.Tran Freq Hz"].verdict == "match" # read since 2026-11-03
fields = set(_results("R352HFZ7.530H")) # no mic
assert not any(f.startswith(("samples.MicL", "intervals.MicL")) for f in fields)
@@ -221,3 +222,124 @@ def test_blastware_counting_the_monitoring_time_is_accepted():
def test_the_count_carveout_needs_blastwares_own_table_to_agree_with_sfm():
assert _count_case(30, drop_rows=1).verdict == "mismatch"
_GROUP_A = ("SerialNumber", "Version", "Calibration", "BatteryLevel", "Trigger",
"GeoTriggerLevel", "MicTriggerLevel", "RecordStopMode", "Microphone", "Units")
@pytest.mark.parametrize("stem,printed", [
("T189HUD6.QE0W", set(_GROUP_A)),
("T438L713.RY0W", set(_GROUP_A)), # 130.8 dB(L): 0.01 psi at 6895 Pa/psi
("K558L4KY.440H", {"SerialNumber", "Version", "Calibration", "BatteryLevel",
"Microphone", "Units"}), # histogram; battery 6.25 -> "6.3"
])
def test_the_setup_fields_match_blastware(stem, printed):
sf = FIX.parent / "setup-fields-11-03-26"
res = {r.field: r for r in compare(sfm_side((sf / stem).read_bytes()),
parse_xml_report_file(sf / (stem.replace(".", "_", 1) + "_XML.XML")),
CARVEOUTS)}
assert printed <= set(res)
for f in printed:
assert res[f].verdict == "match", (f, res[f])
def test_a_manual_trigger_matches():
res = _results("T1905KDW.5F0W", CARVEOUTS)
assert res["Trigger"].verdict == "match"
def _units_case(sfm_units):
sf = FIX.parent / "setup-fields-11-03-26"
ref = parse_xml_report_file(sf / "T189HUD6_QE0W_XML.XML")
ref.scalars["Units"] = "in/s and psi(L)"
side = sfm_side((sf / "T189HUD6.QE0W").read_bytes())
if sfm_units is not None:
side.values["Units"] = sfm_units
return {r.field: r for r in compare(side, ref, CARVEOUTS)}["Units"]
def test_dB_or_psi_is_blastwares_display_preference():
# Blastware writes its report in its PC's current preference; DL2's reports
# switch fleet-wide in 61 clean runs by write time, and no byte in the file
# tells them apart.
r = _units_case(None)
assert (r.verdict, r.carveout) == ("accepted", "units-is-a-display-preference")
def test_the_units_carveout_still_needs_the_mic():
assert _units_case("in/s").verdict == "mismatch"
def test_a_mic_trigger_level_is_read_in_the_unit_it_is_printed_in():
# K441LA17.IN0W: Units "in/s and psi(L)", yet MicTriggerLevel "125.0 dB(L)".
# The printed value states its own unit; that is the one to compare in.
sf = FIX.parent / "setup-fields-11-03-26"
ref = parse_xml_report_file(sf / "T189HUD6_QE0W_XML.XML") # 128.0 dB(L)
ref.event_units = "in/s and psi(L)"
res = {r.field: r for r in compare(sfm_side((sf / "T189HUD6.QE0W").read_bytes()), ref, CARVEOUTS)}
assert res["MicTriggerLevel"].verdict == "match", res["MicTriggerLevel"]
@pytest.mark.parametrize("path", [FIX / "T004JTRF.ME0H",
FIX.parent / "histogram-intervals-11-03-26" / "T190LD42.T00H"])
def test_histogram_interval_detail_matches_blastware(path):
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 ("IntervalSize", "HistogramStopDate", "HistogramStopTime", "intervals.Tran Freq Hz",
"intervals.Vert Freq Hz", "intervals.Long Freq Hz", "intervals.MicL Freq Hz",
"intervals.Geo PVS in/s"):
assert res[f].verdict == "match", (f, res[f])
@pytest.mark.parametrize("halfp,sr,want", [
(0, 1024, "N/A"), (5, 1024, ">100"), (5, 2048, ">200"), (1024, 1024, "<1.0"),
])
def test_blastwares_interval_frequency_words(halfp, sr, want):
# N/A for a half-period of 0, ">100" / ">200" at 5 samples or fewer, "<1.0"
# below 1 Hz -- on ~3.1 M DL2 cells, 2026-11-03.
from minimateplus.decode_check import interval_frequency
assert interval_frequency(halfp, sr) == want
def _pvs_oorange(unclamp=False):
hb = FIX.parent / "histogram-intervals-11-03-26"
ref = parse_xml_report_file(hb / "T190LD5Q_LD0H_XML.XML") # Geo PVS OORANGE, Vert OORANGE
if unclamp:
cols = ref.interval_columns
t, row = ref.intervals[0]
row = list(row)
row[cols.index("Vert Peak in/s")] = "0.500"
ref.intervals[0] = (t, row)
res = {r.field: r for r in compare(sfm_side((hb / "T190LD5Q.LD0H").read_bytes()), ref, CARVEOUTS)}
return res["intervals.Geo PVS in/s"]
def test_an_oorange_interval_vector_sum_is_saturation():
# Blastware prints OORANGE for an interval's vector sum above the range when
# it clamped a channel in that interval: 17 / 17 DL2 cells, SFM's sum
# 10.01 .. 17.33 (= sqrt 3 x 10.005).
r = _pvs_oorange()
assert (r.verdict, r.carveout) == ("accepted", "saturation")
def test_an_oorange_vector_sum_needs_a_clamped_channel_in_that_interval():
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])
+7 -6
View File
@@ -426,11 +426,12 @@ def test_the_units_range_reaches_the_store(tmp_path):
assert store.geo_range == 1
# Review finding (2026-10-29): a histogram's row is stored at its file's time,
# a second before the unit's 0C time on most histograms (#51) -- K441LTOK.QZ0
# decodes to 16:06:34, its 0C says 16:06:35 -- so a pre-check on the 0C time
# alone missed it, and a live download overwrote the watcher's row and sidecar.
# The Blastware name encodes the event's own second and does not miss.
# Review finding (2026-10-29): a histogram's row was stored at its file's time,
# a second before the unit's 0C time (#51) -- K441LTOK.QZ0 decoded to 16:06:34,
# its 0C says 16:06:35 -- so a pre-check on the 0C time alone missed it, and a
# live download overwrote the watcher's row and sidecar. Since #51 (dev,
# 2026-11-03) the file decodes the event's own second, so the time matches too;
# the Blastware name, which encodes that second, stays as the second guard.
@pytest.mark.parametrize("stored_as", ["K441LTOK.QZ0", "K441LTOK.QZ0H"]) # direct / call-in name
def test_a_live_histogram_the_watcher_already_stored_writes_nothing(sdm, stored_as):
@@ -442,7 +443,7 @@ def test_a_live_histogram_the_watcher_already_stored_writes_nothing(sdm, stored_
db.insert_events([ev], serial="BE9441", waveform_records={ev._waveform_key.hex(): rec},
device_family="series3") # as the import route (server.py) does
[row0] = db.query_events(serial="BE9441")
assert row0["timestamp"] != "2026-10-26T16:06:35" # the case: the row sits a second off
assert row0["timestamp"] == "2026-10-26T16:06:35" # #51: the event's own second
assert row0["blastware_filename"] == stored_as
out = persist_download(_hist_download("K441LTOK.QZ0", "01110000",
datetime.datetime(2026, 10, 26, 16, 6, 35)), store=store, db=db)
+123
View File
@@ -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)
+5 -4
View File
@@ -22,7 +22,7 @@ from minimateplus.models import Event
FIX = Path(__file__).parent / "fixtures"
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):
@@ -39,9 +39,10 @@ def test_waveform_timestamp_is_exact_trigger_from_binary():
def test_histogram_timestamp_is_window_start_unchanged():
ev = read_blastware_file(HISTOGRAM)
# Histogram event time = the window start (ts1); must NOT get the waveform
# ts2 treatment (that would land ~24 h off).
assert _tuple(ev.timestamp) == (2026, 5, 10, 19, 4, 50), _tuple(ev.timestamp)
# Histogram event time = the window start, from its own event record (#51;
# the footer's ts1 is a second earlier); must NOT get the waveform ts2
# 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():
+7
View File
@@ -695,3 +695,10 @@ def test_third_block_still_rejects_a_mismatched_counter():
+ _mk_multi_block(ivs, ctr=257)
+ _mk_multi_block(ivs, ctr=999)) # counter jumps — not consecutive
assert detect_multi_interval_stride(body) != 12 + 20 * 4
def test_half_period_to_hz_follows_the_sample_rate():
"""#50: (sample rate / 2) / half-period, measured on 1,725 / 1,725 cells at
2048 sps; the old fixed 512 halved them."""
assert half_period_to_hz(6, 2048) == pytest.approx(1024 / 6)
assert half_period_to_hz(6) == pytest.approx(512 / 6) # 1024 sps by default