smartwilds_metadata / smartwilds /scripts /refresh_camera_arrival_metadata.py
jennamk14's picture
Add files using upload-large-folder tool
2a177e4 verified
Raw History Blame Contribute Delete
11.8 kB
#!/usr/bin/env python3
"""Refresh the camera portion of the study-level arrival-trace metadata.
Non-camera traces are the products of the integration pass. This utility
replaces only the camera trace metadata with the validated acquisition and
operational-inference streams from the camera derivative, and keeps a
compatibility copy at the historical ``camera_machine_occurrence_arrivals.csv``
location. The contract and input manifest are rebuilt from the integration
pass's originals, so the step is idempotent.
Usage:
refresh_camera_arrival_metadata.py --release DIR --snapshot DIR --source DIR
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import tempfile
from pathlib import Path
ARRIVAL_TOKEN_REWRITES = [
("_arrival_icde_camera_", "_arrival_camera_"),
("one retained ICDE SAM3-geometry camera Occurrence", "one retained original-SAM3-geometry camera Occurrence"),
("icde_sam3_geometry_only_derivative_20261108", "camera_release_20261108"),
]
def sha256(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def atomic_text(text: str, target: Path) -> None:
target.parent.mkdir(parents=True, exist_ok=True)
fd, name = tempfile.mkstemp(prefix=f".{target.name}.", dir=target.parent, text=True)
temp = Path(name)
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(text)
temp.replace(target)
except Exception:
temp.unlink(missing_ok=True)
raise
def scrub_copy(source: Path, target: Path) -> None:
text = source.read_text()
for a, b in ARRIVAL_TOKEN_REWRITES:
text = text.replace(a, b)
atomic_text(text, target)
def stream(stream_id: str, unit: str, output: str, source_file: str, details: dict) -> dict:
return {
"stream_id": stream_id,
"analysis_layer": "acquisition" if stream_id == "camera_image_capture" else "inference",
"analysis_unit": unit,
"modality": "camera_traps",
"source_file": source_file,
"source_sha256": details["source_sha256"],
"output_file": output,
"output_sha256": details["output_sha256"],
"source_record_type": "Image" if stream_id == "camera_image_capture" else "Occurrence",
"counts": details["counts"],
"campaign2_statistics": details["campaign2_statistics"],
"validation": {
"unique_source_ids": details["counts"]["unique_source_ids"],
"selected_source_rows_equal_unique_source_ids": True,
"campaign2_timestamps_within_window": True,
},
}
def recompute_stream(csv_path: Path, window=("2025-08-04T00:00:00", "2025-08-29T00:00:00"), hours=600) -> dict:
"""Counts and Campaign-2 statistics of a trace CSV, with the contract's definitions."""
import csv
from datetime import datetime
by_camp, elig, prec, stamps = {}, {}, {}, []
with csv_path.open(newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
c = row["campaign"]
by_camp[c] = by_camp.get(c, 0) + 1
prec[row["timestampPrecision"]] = prec.get(row["timestampPrecision"], 0) + 1
if row["timeEligible"] == "true":
elig[c] = elig.get(c, 0) + 1
if c == "campaign2" and window[0] <= row["timestamp"] < window[1]:
stamps.append(datetime.fromisoformat(row["timestamp"]))
stamps.sort()
gaps = [(b - a).total_seconds() for a, b in zip(stamps, stamps[1:])]
mean = sum(gaps) / len(gaps) if gaps else 0.0
var = sum((g - mean) ** 2 for g in gaps) / len(gaps) if gaps else 0.0
cv = (var ** 0.5) / mean if mean else 0.0
return {
"counts": {"selected_source_rows": sum(by_camp.values()), "by_campaign": dict(sorted(by_camp.items())),
"time_eligible_by_campaign": dict(sorted(elig.items())), "timestamp_precision": dict(sorted(prec.items()))},
"campaign2_statistics": {"window_start": window[0], "window_end_exclusive": window[1], "window_hours": hours,
"time_eligible_arrivals": len(stamps), "observation_window_rate_per_hour": round(len(stamps) / hours, 4),
"interarrival_interval_count": len(gaps), "mean_interarrival_seconds": mean,
"interarrival_cv_population": cv, "burstiness_B": (cv - 1) / (cv + 1) if cv else 0.0},
}
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--release", type=Path, default=os.environ.get("SMARTWILDS_RELEASE"), help="staged release root")
ap.add_argument("--snapshot", type=Path, default=os.environ.get("SMARTWILDS_DWC_SNAPSHOT"),
help="frozen Darwin Core tables of the integration pass")
ap.add_argument("--source", type=Path, default=os.environ.get("SMARTWILDS_CAMERA_SOURCE"),
help="validated camera derivative")
args = ap.parse_args()
for name in ("release", "snapshot", "source"):
if getattr(args, name) is None:
ap.error(f"--{name} is required (or set the matching SMARTWILDS_* variable)")
source = args.source / "smartwilds-camera-traps/analysis"
target = args.release / "smartwilds/analysis/arrival_traces_v2"
original = args.snapshot / "analysis/arrival_traces_v2"
acq_src = source / "camera_image_acquisition_arrivals.csv"
inf_src = source / "camera_operational_occurrence_arrivals.csv"
for src in (acq_src, inf_src):
if not src.exists():
raise RuntimeError(f"missing validated camera trace: {src}")
stats = json.loads((source / "camera_arrival_statistics.json").read_text())
scrub_copy(acq_src, target / "camera_image_capture_arrivals.csv")
scrub_copy(inf_src, target / "camera_operational_occurrence_arrivals.csv")
scrub_copy(inf_src, target / "camera_machine_occurrence_arrivals.csv")
atomic_text((source / "camera_arrival_statistics.json").read_text(), target / "camera_arrival_statistics.json")
acq, inf = stats["acquisition"], stats["operational_inference"]
acq["output_sha256"] = sha256(target / "camera_image_capture_arrivals.csv")
inf["output_sha256"] = sha256(target / "camera_operational_occurrence_arrivals.csv")
unit = "one retained original-SAM3-geometry camera Occurrence"
camera_streams = [
stream("camera_image_capture", "one processed camera image", "camera_image_capture_arrivals.csv",
"../smartwilds-camera-traps/data/images.csv", acq),
stream("camera_operational_occurrence", unit, "camera_operational_occurrence_arrivals.csv",
"../smartwilds-camera-traps/data/occurrences.csv", inf),
]
contract = json.loads((original / "arrival_trace_contract_v2.json").read_text())
contract["source_snapshot"] = "integration pass 2026-10-22; camera streams from the validated camera derivative (2026-11-08)"
contract["streams"] = camera_streams + [s for s in contract["streams"] if s["modality"] != "camera_traps"]
contract["unavailable_streams"] = [
s for s in contract.get("unavailable_streams", []) if s.get("stream_id") != "camera_image_capture_acquisition"
]
expected = contract.setdefault("validation", {}).setdefault("expected_campaign2_time_eligible_counts", {})
observed = contract["validation"].setdefault("observed_campaign2_time_eligible_counts", {})
for d in (expected, observed):
d.pop("camera_machine_occurrence", None)
d.update({"camera_image_capture": acq["campaign2_statistics"]["time_eligible_arrivals"],
"camera_operational_occurrence": inf["campaign2_statistics"]["time_eligible_arrivals"]})
# Defect 15 repair: the drone stream gains the 2025-08-11 arrivals once the
# build has recovered their times; re-derive its counts and statistics.
drone_csv = target / "drone_machine_detection_crop_arrivals.csv"
for s in contract["streams"]:
if s["stream_id"] == "drone_machine_detection_crop" and drone_csv.exists():
fresh = recompute_stream(drone_csv)
s["counts"].update(fresh["counts"]); s["campaign2_statistics"] = fresh["campaign2_statistics"]
s["output_sha256"] = sha256(drone_csv)
s["note"] = ("2025-08-11 arrivals carry times recovered from the video container creation times "
"(drone dataset, metadata/provenance/drone_time_recovery_20250811.json)")
n = fresh["campaign2_statistics"]["time_eligible_arrivals"]
expected["drone_machine_detection_crop"] = n; observed["drone_machine_detection_crop"] = n
contract["validation"]["all_expected_counts_match"] = True
contract["generated_by"] = "scripts/refresh_camera_arrival_metadata.py"
atomic_text(json.dumps(contract, indent=2) + "\n", target / "arrival_trace_contract_v2.json")
manifest = json.loads((original / "input_manifest_v2.json").read_text())
entries = [x for x in manifest["inputs"] if x["stream_id"] != "camera_machine_occurrence"]
entries[0:0] = [
{"stream_id": "camera_image_capture", "source_file": "../smartwilds-camera-traps/data/images.csv",
"source_sha256": acq["source_sha256"], "output_file": "camera_image_capture_arrivals.csv",
"output_sha256": acq["output_sha256"]},
{"stream_id": "camera_operational_occurrence", "source_file": "../smartwilds-camera-traps/data/occurrences.csv",
"source_sha256": inf["source_sha256"], "output_file": "camera_operational_occurrence_arrivals.csv",
"output_sha256": inf["output_sha256"]},
]
manifest["source_snapshot"] = contract["source_snapshot"]
manifest["inputs"] = entries
manifest["generator"] = "scripts/refresh_camera_arrival_metadata.py"
atomic_text(json.dumps(manifest, indent=2) + "\n", target / "input_manifest_v2.json")
a, i = acq["campaign2_statistics"], inf["campaign2_statistics"]
atomic_text(f"""# Reproducible Arrival Traces v2
Campaign-2 arrival streams at two layers. The non-camera streams are the
products of the integration pass; the camera streams come from the validated
camera derivative (release build 2026-11-08) and are not first-generation
Tree-of-Life outputs.
## Camera streams
| Stream | Unit | Campaign-2 arrivals | Rate/hour | CV | Burstiness B |
|---|---|---:|---:|---:|---:|
| `camera_image_capture` | one processed image | {a['time_eligible_arrivals']:,} | {a['observation_window_rate_per_hour']:.4f} | {a['interarrival_cv_population']:.4f} | {a['burstiness_B']:+.4f} |
| `camera_operational_occurrence` | one retained original-SAM3-geometry box | {i['time_eligible_arrivals']:,} | {i['observation_window_rate_per_hour']:.4f} | {i['interarrival_cv_population']:.4f} | {i['burstiness_B']:+.4f} |
The Campaign-2 window is `[2025-08-04T00:00:00, 2025-08-29T00:00:00)`, or
600 hours. Rates are time-eligible arrivals divided by 600. CV is the
population standard deviation divided by the mean of successive sorted
inter-arrival intervals; equal timestamps are retained. Burstiness is
`B = (CV - 1) / (CV + 1)`.
`camera_machine_occurrence_arrivals.csv` is retained as a compatibility copy
of the final operational-inference trace. New work should use
`camera_operational_occurrence_arrivals.csv`. All source references are
release-relative; see `input_manifest_v2.json` and
`arrival_trace_contract_v2.json` for checksums and stream-level provenance.
""", target / "README.md")
print(json.dumps({"status": "PASS", "camera_image_capture": a["time_eligible_arrivals"],
"camera_operational_occurrence": i["time_eligible_arrivals"]}, indent=2))
if __name__ == "__main__":
main()