Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Prototype accounted finite-grid decision evidence (#9)
Cinna Davis4bdc1fd144ad
diff --git a/docs/FINITE_SEARCH_DECISION.md b/docs/FINITE_SEARCH_DECISION.mdnew file mode 100644index 0000000..a9481c4--- /dev/null+++ b/docs/FINITE_SEARCH_DECISION.md@@ -0,0 +1,89 @@+# Proposed finite-search decision evidence++This additive consumer is a proposal for W2/W4/W5 agreement in+[the finite-search topic](https://github.com/1337isnot1337/DOPPLERGEIST/discussions/39#discussioncomment-19363838).+W2 owns computing search/retention evidence, W5 owns stable mode mappings and+actual assessment completion, and W4 owns this interpretation. It does not change+the version-one request/candidate/JobResult contract or flip the old exhaustion+flag. Existing runs remain frozen.++The distinction is deliberate: the complete evaluated grid and its recorded+refinements can support a qualified finite-search estimate. They do not prove+uniqueness across continuous space or calibrated coverage. The normal residual,+clock, input-coverage, association, actual-radius, all-supported-event and full+sensitivity checks still apply.++## Producer object++W5 forwards W2's object verbatim as `matching_diagnostics.finite_search_evidence`:++```json+{+ "schema_version": 1,+ "scope": "evaluated_finite_grid",+ "complete": true,+ "score_kind": "matched_group_support_minus_normalized_residual",+ "spacing_m": 1000.0,+ "refine_spacing_m": 100.0,+ "max_event_groups": 4,+ "retained_modes": [{"mode_id": "stable-mode-id", "score": 3.8, "event_groups": 4}],+ "discarded_count": 0,+ "best_discarded_score": null,+ "pruning_accounted_for": true,+ "limitations": ["Evaluated grids and refinements only; continuous-space uniqueness is not established."]+}+```++Every retained spatial/clock/association seed has one unique stable ID. Preserve+that ID through its refinement. `event_groups` counts independent flyovers,+including all supported later events; harmonics/fragments count once.+`max_event_groups` bounds every retained or discarded evaluated hypothesis.++`complete` requires the declared finite work to finish without unresolved budgets+or missing scope. `pruning_accounted_for` requires every pruning/retention step to+have recorded its limits. `discarded_count` covers all scored retention drops,+including tile, global, coarse and fine merges; `best_discarded_score` is their+maximum higher-is-better score. It is null exactly when no candidate was discarded.+Exact duplicate stable IDs merged while retaining their highest score are not+competing retention drops. Count deduplications separately if needed; association-+only or approximate spatial collapse cannot be treated as exact duplication.+It bounds evaluated parameter points only, not unvisited positions or unperformed+refinements. Missing accounting cannot become zero discards or complete evidence.++## Assessment mappings++W5 also supplies `assessed_mode_ids` for actual completed comparable assessments,+and `candidate_mode_ids` parallel to the returned candidate array. Raw and refined+representations may share a stable ID. Association-only deduplication cannot drop+a distant spatial or clock mode. Failed or unvisited modes remain unassessed.++Every retained mode must be assessed and represented in the candidate array; all+candidate mappings must resolve. Group counts must agree. At least one returned+representation must retain or improve each mode's original score, within numerical+tolerance. These checks prevent a mapping or normalization error from hiding a+better original grid hypothesis.++## Decision interpretation++A supplied finite object takes precedence over an optimistic legacy boolean.+Incomplete scope, lost pruning accounting, omitted modes, inconsistent mappings or+an unbounded near-tied discard yield explicit inconclusive outcomes. Malformed+producer metadata yields `failed / invalid_evidence`.++For a nonempty discard set, the normalized gap is+`(best_final_score - best_discarded_score) / max_event_groups`. It must exceed the+predeclared policy margin: 0.2 support units for the subset score, or 0.5 Hz for+the declared raw robust loss. These engineering margins are not probabilities or+empirical calibration. Score kinds must agree. Every retained candidate also+undergoes the existing position/association near-tie checks against the actual+returned radius. Full measurement/model sensitivity and optimizer/boundary guards+remain mandatory.++An accepted finite object records its grid resolutions, counts, bound, limitations+and `continuous_space_uniqueness: not established` in the decision artifact. A+passing result supports only these declared assumptions. There is no new claim+that an uncalibrated radius guarantees the 1,000 m benchmark target.++Without the new object, the existing compatibility gate stays in force. No old+inconclusive result is silently promoted. Producer agreement and actual integrated+execution remain required before this proposal is considered deployed.diff --git a/src/aircraft_geoloc/confidence.py b/src/aircraft_geoloc/confidence.pyindex 92a5938..5ed0d67 100644--- a/src/aircraft_geoloc/confidence.py+++ b/src/aircraft_geoloc/confidence.py@@ -34,6 +34,80 @@ class DecisionPolicy:raise ValueError(f"{name} must lie in [0, 1]")+def _finite_search(evidence, diagnostics, candidates, group_counts, policy):+ """Check producer-accounted evaluated modes, without a continuous-space claim."""+ if not isinstance(evidence, dict) or type(evidence.get("schema_version")) is not int or evidence["schema_version"] != 1:+ raise ValueError("Unsupported finite-search evidence")+ if evidence.get("scope") != "evaluated_finite_grid":+ return "finite_search_scope_unsupported", {}+ if any(type(evidence.get(name)) is not bool for name in ("complete", "pruning_accounted_for")):+ raise ValueError("Finite-search completion/accounting flags must be boolean")+ if evidence.get("complete") is not True or evidence.get("pruning_accounted_for") is not True:+ return "finite_search_incomplete", {}+ if evidence.get("score_kind") != candidates[0]["score_kind"]:+ return "incomparable_candidates", {}+ for name in ("spacing_m", "refine_spacing_m"):+ value = evidence.get(name)+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:+ raise ValueError("Finite-search resolutions must be positive finite metres")+ maximum = evidence.get("max_event_groups")+ if type(maximum) is not int or maximum < max(group_counts):+ raise ValueError("Finite-search group bound is inconsistent")+ modes = evidence.get("retained_modes")+ if not isinstance(modes, list) or not modes:+ raise ValueError("Finite search must identify retained modes")+ ids = []+ for mode in modes:+ if not isinstance(mode, dict) or not isinstance(mode.get("mode_id"), str) or not mode["mode_id"].strip():+ raise ValueError("Retained modes need stable identifiers")+ score, count = mode.get("score"), mode.get("event_groups")+ if isinstance(score, bool) or not isinstance(score, (int, float)) or not math.isfinite(score):+ raise ValueError("Retained-mode scores must be finite")+ if type(count) is not int or not 1 <= count <= maximum:+ raise ValueError("Retained-mode event counts are inconsistent")+ ids.append(mode["mode_id"])+ if len(set(ids)) != len(ids):+ raise ValueError("Retained-mode IDs must be unique")+ assessed, mapped = diagnostics.get("assessed_mode_ids"), diagnostics.get("candidate_mode_ids")+ if not all(isinstance(values, list) and all(isinstance(v, str) for v in values) for values in (assessed, mapped)):+ return "finite_modes_not_assessed", {}+ if len(mapped) != len(candidates) or not set(ids) <= set(mapped) or set(mapped) - set(ids):+ return "finite_candidate_mapping_incomplete", {}+ by_id = {mode["mode_id"]: mode for mode in modes}+ if any(by_id[identity]["event_groups"] != count for identity, count in zip(mapped, group_counts)):+ return "finite_candidate_mapping_incomplete", {}+ returned_scores = {}+ for candidate, identity in zip(candidates, mapped):+ returned_scores[identity] = max(returned_scores.get(identity, -math.inf), candidate["score"])+ if any(mode["score"] > returned_scores[mode["mode_id"]]+1e-6 for mode in modes):+ return "finite_candidate_scores_inconsistent", {}+ if not set(ids) <= set(assessed):+ return "finite_modes_not_assessed", {}+ discarded, bound = evidence.get("discarded_count"), evidence.get("best_discarded_score")+ if type(discarded) is not int or discarded < 0:+ raise ValueError("Discarded count must be a nonnegative integer")+ if discarded:+ if isinstance(bound, bool) or not isinstance(bound, (int, float)) or not math.isfinite(bound):+ raise ValueError("Discarded candidates require a finite upper score bound")+ elif bound is not None:+ raise ValueError("No discarded candidates must have a null score bound")+ limits = evidence.get("limitations")+ if not isinstance(limits, list) or not all(isinstance(v, str) and v.strip() for v in limits):+ raise ValueError("Finite-search limitations must be a list of descriptions")+ details = {"scope": "evaluated_finite_grid", "spacing_m": evidence["spacing_m"],+ "refine_spacing_m": evidence["refine_spacing_m"], "retained_modes": len(ids),+ "discarded_count": discarded, "best_discarded_score": bound,+ "limitations": limits, "continuous_space_uniqueness": "not established"}+ if discarded:+ gap = (candidates[0]["score"]-bound)/maximum+ threshold = (policy.near_tie_support_per_group if candidates[0]["score_kind"] ==+ "matched_group_support_minus_normalized_residual" else policy.near_tie_loss_per_event_hz)+ details["discarded_score_gap_per_group"] = gap+ if gap <= threshold:+ return "retention_may_hide_alternatives", details+ return None, details++def decide_location(events, candidates, coverage, *, matching_diagnostics=None, policy=None):"""Return status/reason_code/message/diagnostics without modifying inputs.@@ -177,7 +251,19 @@ def decide_location(events, candidates, coverage, *, matching_diagnostics=None,"same_flight_association": same_flights, "checked_radius_m": ambiguity_radius_m}return result("ambiguous_locations" if separation > ambiguity_radius_m else "ambiguous_flight_match","Competing hypotheses fit nearly as well; no unique precise location is supported.")- if evidence.get("alternatives_evaluated") is not True:+ finite = evidence.get("finite_search_evidence")+ if finite is not None:+ try:+ counts = [len({lookup[key].get("harmonic_group_id", key) for key in candidate["event_ids"]}) for candidate in candidates]+ reason, details = _finite_search(finite, evidence, candidates, counts, policy)+ except ValueError as exc:+ diagnostics["validation_error"] = str(exc)+ return result("invalid_evidence", "The finite-search evidence is malformed.", "failed")+ diagnostics["finite_search"] = details+ if reason:+ return result(reason, "The finite search does not yet exclude unassessed or discarded competing hypotheses.")+ diagnostics["limitations"].append("Only the declared finite grids/refinements were compared; continuous-space uniqueness is not established.")+ elif evidence.get("alternatives_evaluated") is not True:return result("alternatives_not_assessed", "The retained competing hypotheses have not all been assessed.")sensitivity = evidence.get("sensitivity", {})if not isinstance(sensitivity, dict):diff --git a/tests/test_confidence.py b/tests/test_confidence.pyindex ae49cb3..e4ca8a1 100644--- a/tests/test_confidence.py+++ b/tests/test_confidence.py@@ -171,3 +171,66 @@ def test_all_four_independent_flyovers_are_checked():assert decide((events, candidates, coverage, diag))["status"] == "succeeded"diag["e3"]["rmse_hz"] = 8assert decide((events, candidates, coverage, diag))["reason_code"] == "inconsistent_event_match"+++def finite_evidence():+ events, candidates, coverage, diag = evidence()+ candidates.append(dict(candidates[0], lat=45., score=-4.))+ diag.update(alternatives_evaluated=False, assessed_mode_ids=["a", "b"], candidate_mode_ids=["a", "b"],+ finite_search_evidence={"schema_version": 1, "scope": "evaluated_finite_grid", "complete": True,+ "score_kind": candidates[0]["score_kind"], "spacing_m": 1000., "refine_spacing_m": 100.,+ "max_event_groups": 2, "retained_modes": [{"mode_id": "a", "score": -1., "event_groups": 2},+ {"mode_id": "b", "score": -4., "event_groups": 2}],+ "discarded_count": 7, "best_discarded_score": -5., "pruning_accounted_for": True,+ "limitations": ["Evaluated grids only; no continuous-space uniqueness."]})+ return events, candidates, coverage, diag+++def test_finite_search_can_pass_without_claiming_continuous_exhaustion():+ bundle = finite_evidence()+ result = decide(bundle)+ assert result["status"] == "succeeded"+ assert result["diagnostics"]["finite_search"]["continuous_space_uniqueness"] == "not established"+ bundle[3]["sensitivity"]["sources"] = ["altitude"]+ assert decide(bundle)["reason_code"] == "uncertainty_not_established"++[email protected]("kind,reason", [("discard", "retention_may_hide_alternatives"),+ ("complete", "finite_search_incomplete"), ("pruning", "finite_search_incomplete"),+ ("assessed", "finite_modes_not_assessed"), ("mapping", "finite_candidate_mapping_incomplete"),+ ("lost_score", "finite_candidate_scores_inconsistent")])+def test_finite_search_cannot_hide_omitted_or_near_tied_modes(kind, reason):+ bundle = finite_evidence()+ diag = bundle[3]+ finite = diag["finite_search_evidence"]+ diag["alternatives_evaluated"] = True # Optimistic legacy flag cannot override evidence.+ if kind == "discard": finite["best_discarded_score"] = -1.2+ elif kind == "complete": finite["complete"] = False+ elif kind == "pruning": finite["pruning_accounted_for"] = False+ elif kind == "assessed": diag["assessed_mode_ids"] = ["a"]+ elif kind == "mapping": diag["candidate_mode_ids"] = ["a", "a"]+ elif kind == "lost_score": finite["retained_modes"][1]["score"] = 0.+ result = decide(bundle)+ assert result["status"] == "inconclusive"+ assert result["reason_code"] == reason+++def test_finite_retention_bound_uses_declared_subset_units():+ events, candidates, coverage, diag = finite_evidence()+ kind = "matched_group_support_minus_normalized_residual"+ candidates[0].update(score=1.8, score_kind=kind)+ candidates[1].update(score=0.1, score_kind=kind)+ finite = diag["finite_search_evidence"]+ finite.update(score_kind=kind, best_discarded_score=1.5)+ for mode, score in zip(finite["retained_modes"], (1.8, 0.1)): mode["score"] = score+ assert decide((events, candidates, coverage, diag))["reason_code"] == "retention_may_hide_alternatives"+ finite["best_discarded_score"] = 1.2+ assert decide((events, candidates, coverage, diag))["status"] == "succeeded"+++def test_malformed_finite_flags_fail_instead_of_looking_like_insufficient_data():+ bundle = finite_evidence()+ bundle[3]["finite_search_evidence"]["complete"] = 1+ result = decide(bundle)+ assert result["status"] == "failed"+ assert result["reason_code"] == "invalid_evidence"