File size: 16,439 Bytes
883e092 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 | #!/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()
|