SeismicX-Cont-mini / essd_scripts /audit_waveform_quality.py
cangyeone's picture
Upload mini release files
883e092 verified
Raw
History Blame Contribute Delete
16.4 kB
#!/usr/bin/env python3
"""Audit waveform-index integrity and a deterministic stratified HDF5 sample.
The index-level checks cover every released segment. Sample-value diagnostics
read short windows from a reproducible subset stratified by period, network,
and seismic channel family; they are not presented as a full-sample scan.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import sqlite3
from collections import Counter, defaultdict
from datetime import datetime
from pathlib import Path
from typing import Any, Iterable
import h5py
import numpy as np
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_DB = ROOT / "data" / "index" / "waveform_index.sqlite"
DEFAULT_OUTPUT = ROOT / "essd_scripts" / "outputs" / "waveform_quality_audit.json"
SEISMIC_FAMILIES = {"HH", "BH", "EH", "HN"}
def parse_time(value: Any) -> float:
text = str(value).strip().replace("Z", "+00:00")
return datetime.fromisoformat(text).timestamp()
def percentile_summary(values: Iterable[float]) -> dict[str, float | None]:
array = np.asarray(list(values), dtype=float)
if not array.size:
return {"median": None, "p90": None, "p99": None, "maximum": None}
return {
"median": float(np.percentile(array, 50)),
"p90": float(np.percentile(array, 90)),
"p99": float(np.percentile(array, 99)),
"maximum": float(np.max(array)),
}
def longest_true_run(mask: np.ndarray) -> int:
if not mask.size or not np.any(mask):
return 0
padded = np.concatenate(([False], mask, [False])).astype(np.int8)
edges = np.diff(padded)
starts = np.flatnonzero(edges == 1)
ends = np.flatnonzero(edges == -1)
return int(np.max(ends - starts))
def resolve_release_path(path_text: str) -> Path:
path = Path(path_text)
return path if path.is_absolute() else ROOT / path
def display_release_path(path: Path) -> str:
resolved = path.expanduser().resolve()
try:
return resolved.relative_to(ROOT.resolve()).as_posix()
except ValueError:
return str(resolved)
def load_rows(db_path: Path) -> list[dict[str, Any]]:
connection = sqlite3.connect(db_path)
connection.row_factory = sqlite3.Row
rows = [dict(row) for row in connection.execute(
"""
SELECT id, h5_file, dataset_path, network, station, location, channel,
starttime, endtime, start_epoch, end_epoch, sampling_rate,
delta, npts, dtype, source_file, latitude, longitude
FROM waveform_segments
ORDER BY network, station, COALESCE(location, ''), channel, start_epoch, id
"""
)]
connection.close()
return rows
def audit_index(rows: list[dict[str, Any]]) -> dict[str, Any]:
missing = Counter()
timing_mismatch = 0
invalid_sampling = 0
duplicate_keys = Counter()
groups: dict[tuple[str, str, str, str, str], list[dict[str, Any]]] = defaultdict(list)
for row in rows:
for field in (
"h5_file", "dataset_path", "network", "station", "channel",
"starttime", "endtime", "start_epoch", "end_epoch",
"sampling_rate", "delta", "npts", "dtype", "source_file",
):
if row.get(field) in (None, ""):
missing[field] += 1
sampling_rate = float(row["sampling_rate"] or 0.0)
delta = float(row["delta"] or 0.0)
npts = int(row["npts"] or 0)
if sampling_rate <= 0.0 or delta <= 0.0 or npts <= 0:
invalid_sampling += 1
else:
expected_end = float(row["start_epoch"]) + (npts - 1) / sampling_rate
tolerance = max(1.0e-5, delta * 0.05)
if abs(expected_end - float(row["end_epoch"])) > tolerance:
timing_mismatch += 1
duplicate_keys[
(
row["h5_file"], row["dataset_path"], row["start_epoch"],
row["end_epoch"], row["npts"],
)
] += 1
period = str(row["starttime"])[:4]
groups[
(
period, str(row["network"]), str(row["station"]),
str(row["location"] or ""), str(row["channel"]),
)
].append(row)
gaps: list[float] = []
overlaps: list[float] = []
gap_by_network: Counter[str] = Counter()
gap_by_family: Counter[str] = Counter()
overlap_by_network: Counter[str] = Counter()
overlap_by_family: Counter[str] = Counter()
for group_key, group_rows in groups.items():
_, network, _, _, channel = group_key
family = channel[:2]
previous_end: float | None = None
previous_delta: float | None = None
for row in group_rows:
start = float(row["start_epoch"])
end = float(row["end_epoch"])
delta = float(row["delta"] or 0.0)
if previous_end is not None:
adjacency = max(delta, previous_delta or 0.0)
separation = start - previous_end
if separation > 1.5 * adjacency:
gaps.append(max(0.0, separation - adjacency))
gap_by_network[network] += 1
gap_by_family[family] += 1
elif separation < -1.5 * adjacency:
overlaps.append(-separation)
overlap_by_network[network] += 1
overlap_by_family[family] += 1
if previous_end is None or end > previous_end:
previous_end = end
previous_delta = delta
return {
"scope": "all waveform_segments rows",
"segment_rows": len(rows),
"missing_required_field_counts": dict(sorted(missing.items())),
"invalid_sampling_rows": invalid_sampling,
"end_time_formula_mismatch_rows": timing_mismatch,
"duplicate_segment_key_rows_beyond_first": int(
sum(count - 1 for count in duplicate_keys.values() if count > 1)
),
"exact_nslc_gap_count_within_selected_periods": len(gaps),
"exact_nslc_gap_count_by_network": dict(sorted(gap_by_network.items())),
"exact_nslc_gap_count_by_channel_family": dict(sorted(gap_by_family.items())),
"exact_nslc_gap_duration_s": percentile_summary(gaps),
"exact_nslc_overlap_count_within_selected_periods": len(overlaps),
"exact_nslc_overlap_count_by_network": dict(sorted(overlap_by_network.items())),
"exact_nslc_overlap_count_by_channel_family": dict(sorted(overlap_by_family.items())),
"exact_nslc_overlap_duration_s": percentile_summary(overlaps),
"missing_coordinate_rows": int(
sum(row["latitude"] is None or row["longitude"] is None for row in rows)
),
}
def select_sample(
rows: list[dict[str, Any]], sample_per_stratum: int
) -> list[dict[str, Any]]:
strata: dict[tuple[str, str, str], list[dict[str, Any]]] = defaultdict(list)
for row in rows:
family = str(row["channel"])[:2]
if family not in SEISMIC_FAMILIES:
continue
period = str(row["starttime"])[:4]
strata[(period, str(row["network"]), family)].append(row)
selected: list[dict[str, Any]] = []
for key in sorted(strata):
ordered = sorted(
strata[key],
key=lambda row: hashlib.sha256(
f"{row['h5_file']}::{row['dataset_path']}".encode("utf-8")
).hexdigest(),
)
selected.extend(ordered[:sample_per_stratum])
return selected
def audit_hdf5_sample(
rows: list[dict[str, Any]], sample_per_stratum: int, window_seconds: float
) -> dict[str, Any]:
selected = select_sample(rows, sample_per_stratum)
by_file: dict[Path, list[dict[str, Any]]] = defaultdict(list)
for row in selected:
by_file[resolve_release_path(str(row["h5_file"]))].append(row)
counters = Counter()
mismatch_examples: list[dict[str, Any]] = []
sample_flag_examples: list[dict[str, Any]] = []
longest_zero_run_s = 0.0
total_values = 0
zero_values = 0
dtype_extreme_values = 0
nonfinite_values = 0
large_difference_values = 0
def mismatch(row: dict[str, Any], field: str, index_value: Any, hdf5_value: Any) -> None:
counters[f"{field}_mismatch"] += 1
if len(mismatch_examples) < 20:
mismatch_examples.append(
{
"dataset_path": row["dataset_path"],
"field": field,
"index": index_value,
"hdf5": hdf5_value,
}
)
for h5_path, file_rows in sorted(by_file.items(), key=lambda item: str(item[0])):
if not h5_path.exists():
counters["missing_hdf5_file"] += len(file_rows)
continue
with h5py.File(h5_path, "r") as handle:
for row in file_rows:
dataset_path = str(row["dataset_path"])
if dataset_path not in handle:
counters["missing_dataset"] += 1
continue
dataset = handle[dataset_path]
counters["datasets_opened"] += 1
if dataset.ndim != 1 or dataset.shape[0] != int(row["npts"]):
mismatch(row, "shape", row["npts"], dataset.shape)
if np.dtype(dataset.dtype).name != np.dtype(str(row["dtype"])).name:
mismatch(row, "dtype", row["dtype"], str(dataset.dtype))
attrs = dataset.attrs
for field in ("network", "station", "channel"):
if str(attrs.get(field, "")) != str(row[field]):
mismatch(row, field, row[field], attrs.get(field))
if str(attrs.get("location", "")) != str(row["location"] or ""):
mismatch(row, "location", row["location"], attrs.get("location"))
for field in ("sampling_rate", "delta"):
if not math.isclose(
float(attrs.get(field, math.nan)),
float(row[field]),
rel_tol=0.0,
abs_tol=1.0e-9,
):
mismatch(row, field, row[field], attrs.get(field))
if int(attrs.get("npts", -1)) != int(row["npts"]):
mismatch(row, "npts", row["npts"], attrs.get("npts"))
if str(attrs.get("mseed_source_file", "")) != str(row["source_file"]):
mismatch(
row, "source_file", row["source_file"], attrs.get("mseed_source_file")
)
for attr_name, index_name in (
("starttime", "start_epoch"), ("endtime", "end_epoch")
):
try:
attr_epoch = parse_time(attrs[attr_name])
except (KeyError, TypeError, ValueError):
mismatch(row, attr_name, row[index_name], attrs.get(attr_name))
else:
tolerance = max(1.0e-5, float(row["delta"] or 0.0) * 0.05)
if abs(attr_epoch - float(row[index_name])) > tolerance:
mismatch(row, attr_name, row[index_name], attrs.get(attr_name))
npts = int(dataset.shape[0])
sample_rate = float(row["sampling_rate"])
window_npts = min(npts, max(1, int(round(window_seconds * sample_rate))))
starts = sorted({0, max(0, (npts - window_npts) // 2), max(0, npts - window_npts)})
for start in starts:
values = np.asarray(dataset[start : start + window_npts])
counters["sample_windows_read"] += 1
total_values += int(values.size)
zero_mask = values == 0
zero_values += int(np.count_nonzero(zero_mask))
longest_zero_run_s = max(
longest_zero_run_s,
longest_true_run(zero_mask) / sample_rate,
)
if values.size and np.all(values == values.flat[0]):
counters["constant_sample_windows"] += 1
if len(sample_flag_examples) < 20:
sample_flag_examples.append(
{
"dataset_path": dataset_path,
"sample_start_index": start,
"flag": "constant_window",
}
)
if np.issubdtype(values.dtype, np.integer):
limits = np.iinfo(values.dtype)
dtype_extreme_values += int(
np.count_nonzero((values == limits.min) | (values == limits.max))
)
else:
n_nonfinite = int(np.count_nonzero(~np.isfinite(values)))
nonfinite_values += n_nonfinite
if n_nonfinite and len(sample_flag_examples) < 20:
sample_flag_examples.append(
{
"dataset_path": dataset_path,
"sample_start_index": start,
"flag": "nonfinite_values",
"count": n_nonfinite,
}
)
differences = np.diff(values.astype(np.float64, copy=False))
if differences.size:
median = float(np.median(differences))
mad = float(np.median(np.abs(differences - median)))
if mad > 0.0:
threshold = 20.0 * 1.4826 * mad
large_difference_values += int(
np.count_nonzero(np.abs(differences - median) > threshold)
)
return {
"scope": (
"deterministic SHA-256-ordered sample stratified by period, network, "
"and HH/BH/EH/HN channel family"
),
"sample_per_stratum": sample_per_stratum,
"selected_segments": len(selected),
"sample_window_seconds": window_seconds,
"counters": dict(sorted(counters.items())),
"metadata_mismatch_examples": mismatch_examples,
"sample_flag_examples": sample_flag_examples,
"sample_values_examined": total_values,
"zero_value_fraction": zero_values / total_values if total_values else None,
"longest_zero_run_s_in_sample_windows": longest_zero_run_s,
"dtype_extreme_value_count": dtype_extreme_values,
"nonfinite_value_count": nonfinite_values,
"large_first_difference_count_20mad": large_difference_values,
"large_first_difference_note": (
"Diagnostic flag only; large first differences can be genuine seismic signals."
),
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--waveform-db", type=Path, default=DEFAULT_DB)
parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
parser.add_argument("--sample-per-stratum", type=int, default=10)
parser.add_argument("--sample-window-seconds", type=float, default=30.0)
args = parser.parse_args()
if args.sample_per_stratum < 1:
parser.error("--sample-per-stratum must be at least 1")
if args.sample_window_seconds <= 0:
parser.error("--sample-window-seconds must be positive")
rows = load_rows(args.waveform_db)
report = {
"waveform_index": display_release_path(args.waveform_db),
"index_audit": audit_index(rows),
"hdf5_sample_audit": audit_hdf5_sample(
rows, args.sample_per_stratum, args.sample_window_seconds
),
"interpretation": (
"Index checks cover every segment row. Sample-value diagnostics do not "
"replace a full-array scan or comparison with upstream MiniSEED samples."
),
}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2), encoding="utf-8")
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()