feat: finalize corrected-route planning and Rerun recording review
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
"""Project recorded acquisition ownership without moving or changing captures."""
|
||||
|
||||
import json
|
||||
from uuid import UUID
|
||||
|
||||
|
||||
def reconcile_planning_captures(root, record_capture):
|
||||
"""Backfill only explicit live-run bindings, including failed/deleted studies.
|
||||
|
||||
Recorded comparisons do not change the origin of an existing independent
|
||||
survey. Project deletion is a presentation tombstone; its binding survives.
|
||||
"""
|
||||
for path in root.glob("*/report.json"):
|
||||
doc = json.loads(path.read_text())
|
||||
if doc.get("schema_version") != "missioncore.planning-live-test/v1":
|
||||
continue
|
||||
if doc.get("profile") != "planning" or not doc.get("query_session_id"):
|
||||
continue
|
||||
run_id = str(UUID(doc["id"]))
|
||||
if path.parent.name != run_id:
|
||||
raise ValueError("Planning capture report identity mismatch")
|
||||
session_id = doc["query_session_id"]
|
||||
if session_id in {doc["draft"]["zone"]["session_id"], doc.get("baseline_session_id")}:
|
||||
raise ValueError("Planning capture cannot own its reference or baseline")
|
||||
record_capture(session_id, run_id)
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Resolve new references by session default, existing studies by pinned version."""
|
||||
|
||||
from .versioned_sources import VersionedPlanningSources
|
||||
|
||||
|
||||
class DefaultPlanningSources:
|
||||
def __init__(self, original, versions):
|
||||
self.original, self.versions = original, versions
|
||||
self.store, self.root = original.store, original.root
|
||||
|
||||
def get(self, session_id):
|
||||
version = self.versions.selected(session_id)
|
||||
return (
|
||||
self.original.get(session_id)
|
||||
if version is None
|
||||
else self.bound(session_id, version.generation)
|
||||
)
|
||||
|
||||
def _reader(self, session_id, generation):
|
||||
version = self.versions.version(session_id, generation)
|
||||
if version is None:
|
||||
return self.original
|
||||
return VersionedPlanningSources(self.original, version, self.root / "map-snapshots")
|
||||
|
||||
def bound(self, session_id, generation):
|
||||
doc = self._reader(session_id, generation).bound(session_id, generation)
|
||||
# The catalog identity/name describes the physical session, not its revision.
|
||||
return {**doc, "label": self.original.get(session_id)["label"]}
|
||||
|
||||
def verify(self, session_id, generation):
|
||||
return self._reader(session_id, generation).verify(session_id, generation)
|
||||
|
||||
def prepared_submaps(self, session_id, generation, **options):
|
||||
return self._reader(session_id, generation).prepared_submaps(
|
||||
session_id, generation, **options
|
||||
)
|
||||
|
||||
def submap(self, session_id, generation, start, end, **options):
|
||||
return self._reader(session_id, generation).submap(
|
||||
session_id, generation, start, end, **options
|
||||
)
|
||||
|
||||
def reference_map(self, session_id, generation, start, end, **options):
|
||||
return self._reader(session_id, generation).reference_map(
|
||||
session_id, generation, start, end, **options
|
||||
)
|
||||
|
||||
def scene_reference_map(self, session_id, generation, start, end, **options):
|
||||
return self._reader(session_id, generation).scene_reference_map(
|
||||
session_id, generation, start, end, **options
|
||||
)
|
||||
@@ -53,7 +53,13 @@ class MissionDrafts:
|
||||
|
||||
def save(self, request):
|
||||
source = self.sources.bound(request.session_id, request.generation)
|
||||
route = route_from_source(source, request.start_index, request.end_index, request.direction)
|
||||
if getattr(request, 'whole_recording', False):
|
||||
start, end = 0, len(source['poses']) - 1
|
||||
else:
|
||||
start, end = request.start_index, request.end_index
|
||||
if start is None or end is None:
|
||||
raise ValueError('Выберите полную запись эталона.')
|
||||
route = route_from_source(source, start, end, request.direction)
|
||||
id = str(request.id or uuid4())
|
||||
body = {'schema_version': 'missioncore.mission-draft/v1', 'name': request.name.strip(),
|
||||
'vehicle_id': None, 'status': 'draft', 'zone': {key: source[key] for key in
|
||||
|
||||
@@ -195,6 +195,7 @@ def acquire_entry(
|
||||
fitter=None,
|
||||
clock=time.monotonic,
|
||||
policy=ENTRY_POLICY,
|
||||
progress=None,
|
||||
):
|
||||
reference, query, initial = cloud(reference), cloud(query), rigid(initial)
|
||||
started = clock()
|
||||
@@ -207,7 +208,9 @@ def acquire_entry(
|
||||
|
||||
attempts = []
|
||||
for seed in entry_seeds(initial, query_entry, reference_forward, policy=policy):
|
||||
if clock() - started >= policy["deadline_s"]:
|
||||
if progress is not None:
|
||||
progress(dict(stage="dense-start", completed_fits=len(attempts)))
|
||||
if policy["deadline_s"] is not None and clock() - started >= policy["deadline_s"]:
|
||||
break
|
||||
matrix = seed.pop("matrix")
|
||||
result = fitter(reference, query, matrix)
|
||||
@@ -217,7 +220,7 @@ def acquire_entry(
|
||||
attempts,
|
||||
initial,
|
||||
query_entry,
|
||||
complete=elapsed <= policy["deadline_s"],
|
||||
complete=policy["deadline_s"] is None or elapsed <= policy["deadline_s"],
|
||||
policy=policy,
|
||||
)
|
||||
result["initialization"]["elapsed_s"] = elapsed
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""One admission and termination policy for a selected live route."""
|
||||
"""Reference admission is independent from the lifetime of a live pass."""
|
||||
|
||||
import math
|
||||
|
||||
LIVE_ROUTE_POLICY = dict(
|
||||
version="selected-live-route/v1",
|
||||
version="selected-live-route/v2",
|
||||
minimum_m=3.0,
|
||||
maximum_m=None,
|
||||
maximum_seconds=None,
|
||||
@@ -16,6 +16,8 @@ def live_route_limits(length_m):
|
||||
raise ValueError("Для привязки выберите участок длиной не менее 3 м.")
|
||||
return dict(
|
||||
route_policy=LIVE_ROUTE_POLICY.copy(),
|
||||
maximum_distance_m=length,
|
||||
# Reference length describes map coverage, never a travel budget.
|
||||
# Keep null in the wire contract (and do not rewrite historical runs).
|
||||
maximum_distance_m=None,
|
||||
maximum_seconds=None,
|
||||
)
|
||||
|
||||
@@ -37,10 +37,15 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PlanningLiveTests:
|
||||
def __init__(self, drafts, sources, compute_lock):
|
||||
def __init__(self, drafts, sources, compute_lock, *, capture_recorder=None):
|
||||
self.drafts, self.sources, self.compute_lock = drafts, sources, compute_lock
|
||||
self.root = drafts.database.parent / "live-tests"
|
||||
self.root.mkdir(exist_ok=True)
|
||||
self.capture_recorder = capture_recorder
|
||||
if capture_recorder is not None:
|
||||
from .capture_catalog import reconcile_planning_captures
|
||||
|
||||
reconcile_planning_captures(self.root, capture_recorder)
|
||||
self.lock = threading.RLock()
|
||||
self.run = None
|
||||
self.sample = None
|
||||
@@ -177,6 +182,9 @@ class PlanningLiveTests:
|
||||
|
||||
def update(self, **values):
|
||||
with self.lock:
|
||||
capture = values.get("query_session_id")
|
||||
if capture and self.capture_recorder is not None:
|
||||
self.capture_recorder(capture, self.run["id"])
|
||||
self.run.update(values)
|
||||
self.revision += 1
|
||||
self.persist()
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
"""Staged stationary localisation before the normal fresh-data tracking gate.
|
||||
|
||||
A known start is the reliable laboratory path, so it first receives a dense
|
||||
multi-start fit. Only its honest rejection permits retrieval over the entire
|
||||
selected route. That preserves a repeatable start while retaining an auditable
|
||||
recovery path for a restarted rover that must look for *where it is*.
|
||||
A known start first receives a dense multi-start fit, but it cannot shortcut
|
||||
comparison with the entire selected route. A finite queue, not elapsed wall
|
||||
time, defines completeness. The process owner handles cancellation and stalls.
|
||||
|
||||
Neither stage grants tracking or vehicle authority: both only produce a
|
||||
provisional hypothesis for the separate, disjoint fresh-data gate.
|
||||
@@ -13,7 +12,6 @@ from __future__ import annotations
|
||||
|
||||
import math
|
||||
import time
|
||||
from copy import deepcopy
|
||||
from dataclasses import dataclass
|
||||
from itertools import product
|
||||
|
||||
@@ -21,15 +19,17 @@ import numpy as np
|
||||
|
||||
from .entry_acquisition import acquire_entry
|
||||
from .observation_profiles import TRACKING_INPUT
|
||||
from .reference_window import reference_window
|
||||
from .reference_window import ReferenceCoverageError, reference_window
|
||||
from .registration import POLICY as TRACKING_POLICY
|
||||
from .registration import PreparedReference, angle_deg, cloud, rigid, transform
|
||||
from .stationary_entry import STATIONARY_POLICY
|
||||
|
||||
ROUTE_RELOCALIZATION_POLICY = dict(
|
||||
version="route-relocalization/v6",
|
||||
version="route-relocalization/v7",
|
||||
scope="selected-route",
|
||||
strategy="dense-start-first-then-route-recovery/v1",
|
||||
strategy="dense-start-and-complete-route-comparison/v2",
|
||||
hypothesis_freshness="stationary-receipts-and-disjoint-confirmation/v1",
|
||||
seed_modes=["pose-anchor", "cloud-median"],
|
||||
# Local geometry is independent of the 80-m presentation envelope.
|
||||
query_radius_m=TRACKING_INPUT["radius_m"],
|
||||
anchor_spacing_m=5.0,
|
||||
@@ -54,13 +54,9 @@ ROUTE_RELOCALIZATION_POLICY = dict(
|
||||
cluster_rotation_deg=8.0,
|
||||
ambiguity_overlap_margin=0.05,
|
||||
ambiguity_rmse_margin_m=0.03,
|
||||
# Keep the stationary prefix younger than the bootstrap's 40-s source-age
|
||||
# fence. A late exhaustive calculation is an explicit incomplete search,
|
||||
# never a stale provisional position.
|
||||
deadline_s=30.0,
|
||||
maximum_search_wall_s=35.0,
|
||||
# This is a numerical convergence envelope, not an operator start-radius
|
||||
# admission rule. Reaching its wall deadline is reported as incomplete.
|
||||
# No overall search timer: every admitted place must be compared. A child
|
||||
# that makes NO progress is separately stopped, never called a map mismatch.
|
||||
worker_stall_s=60.0,
|
||||
registration_policy={
|
||||
**TRACKING_POLICY,
|
||||
"version": "route-relocalization-gicp/v1",
|
||||
@@ -257,7 +253,8 @@ class RouteCandidate:
|
||||
|
||||
|
||||
def rank_route_candidates(
|
||||
reference, reference_path, query, *, policy=ROUTE_RELOCALIZATION_POLICY, grid=None
|
||||
reference, reference_path, query, *, policy=ROUTE_RELOCALIZATION_POLICY, grid=None,
|
||||
on_progress=None,
|
||||
):
|
||||
"""Rank every resampled route position against the stationary query cloud."""
|
||||
reference, query = route_reference_cloud(reference), cloud(query)
|
||||
@@ -267,6 +264,9 @@ def rank_route_candidates(
|
||||
query_descriptor = radial_height_descriptor(query, query_center, policy=policy)
|
||||
ranked = []
|
||||
for index, (position, distance) in enumerate(zip(anchors, progress, strict=True)):
|
||||
if on_progress is not None:
|
||||
on_progress(dict(stage="route-index", completed_anchors=index,
|
||||
total_anchors=len(anchors)))
|
||||
target = local_submap(
|
||||
grid,
|
||||
position,
|
||||
@@ -454,6 +454,8 @@ def relocalize_route(
|
||||
*,
|
||||
clock=time.monotonic,
|
||||
policy=ROUTE_RELOCALIZATION_POLICY,
|
||||
on_progress=None,
|
||||
additional_hypotheses=(),
|
||||
):
|
||||
"""Run complete candidate retrieval and qualification against a selected route."""
|
||||
started = clock()
|
||||
@@ -461,7 +463,7 @@ def relocalize_route(
|
||||
query_entry = np.asarray(query_entry, dtype=float).reshape(3)
|
||||
grid = ReferenceGrid(reference, cell_m=policy["spatial_cell_m"])
|
||||
ranked, coverage = rank_route_candidates(
|
||||
reference, reference_path, query, policy=policy, grid=grid
|
||||
reference, reference_path, query, policy=policy, grid=grid, on_progress=on_progress
|
||||
)
|
||||
attempts, evaluated, batches = [], [], []
|
||||
query_center = np.median(query, axis=0)
|
||||
@@ -470,11 +472,10 @@ def relocalize_route(
|
||||
float(np.linalg.norm(query - query_center, axis=1).max())
|
||||
+ policy["target_context_margin_m"],
|
||||
)
|
||||
expected = len(ranked) * policy["yaw_candidates_per_place"]
|
||||
fits_per_place = policy["yaw_candidates_per_place"] * len(policy["seed_modes"])
|
||||
expected = len(ranked) * fits_per_place
|
||||
batch_size = policy["candidate_batch_size"]
|
||||
for candidate in ranked:
|
||||
if clock() - started > policy["deadline_s"]:
|
||||
break
|
||||
if len(evaluated) % batch_size == 0:
|
||||
batches.append([])
|
||||
target = local_submap(
|
||||
@@ -487,12 +488,18 @@ def relocalize_route(
|
||||
target_center = np.median(target, axis=0)
|
||||
count_before = len(attempts)
|
||||
prepared = None
|
||||
for yaw_deg in _yaw_candidates(
|
||||
query, target, query_center, target_center, policy=policy
|
||||
for yaw_deg, seed_mode in product(
|
||||
_yaw_candidates(query, target, query_center, target_center, policy=policy),
|
||||
policy["seed_modes"],
|
||||
):
|
||||
if clock() - started > policy["deadline_s"]:
|
||||
break
|
||||
initial = _seed(query_center, target_center, yaw_deg)
|
||||
if on_progress is not None:
|
||||
on_progress(dict(stage="route-search", completed_fits=len(attempts),
|
||||
total_fits=expected, candidate_index=candidate.index))
|
||||
# The sensor pose is the spatial origin of this hypothesis. Cloud
|
||||
# medians shift with occlusion/vegetation and are not scanner poses.
|
||||
initial = (_seed(query_entry, candidate.position, yaw_deg)
|
||||
if seed_mode == "pose-anchor"
|
||||
else _seed(query_center, target_center, yaw_deg))
|
||||
try:
|
||||
# Target preprocessing is independent of yaw. Keep one tree
|
||||
# per place; all seeds and all eligibility checks stay intact.
|
||||
@@ -512,15 +519,21 @@ def relocalize_route(
|
||||
descriptor_distance=candidate.descriptor_distance,
|
||||
),
|
||||
yaw_deg=yaw_deg,
|
||||
seed_mode=seed_mode,
|
||||
result=result,
|
||||
)
|
||||
)
|
||||
if len(attempts) - count_before != policy["yaw_candidates_per_place"]:
|
||||
if len(attempts) - count_before != fits_per_place:
|
||||
break
|
||||
evaluated.append(candidate.index)
|
||||
batches[-1].append(candidate.index)
|
||||
complete = len(evaluated) == len(ranked) and clock() - started <= policy["deadline_s"]
|
||||
result = choose_route_location(attempts, query_entry, complete=complete, policy=policy)
|
||||
complete = len(evaluated) == len(ranked)
|
||||
result = choose_route_location(
|
||||
[*attempts, *additional_hypotheses], query_entry, complete=complete, policy=policy
|
||||
)
|
||||
# Dense-start evidence is accounted for by the caller, not counted twice as
|
||||
# one extra route seed. It nevertheless participates in spatial ambiguity.
|
||||
result["initialization"]["attempts"] = result["initialization"]["attempts"][:len(attempts)]
|
||||
result["initialization"].update(
|
||||
coverage,
|
||||
elapsed_s=clock() - started,
|
||||
@@ -644,23 +657,26 @@ def relocalize_start_then_route(
|
||||
policy=ROUTE_RELOCALIZATION_POLICY,
|
||||
reference_position=None,
|
||||
route_only=False,
|
||||
on_progress=None,
|
||||
):
|
||||
"""Use the proven start-area fit first, then a bounded route fallback.
|
||||
|
||||
This is deliberately not a looser acceptance rule. The dense start fit
|
||||
runs every stationary multi-start seed against its high-resolution local
|
||||
target. Only an honest rejection enters whole-route retrieval, whose
|
||||
result remains provisional until the existing fresh-data gate confirms it.
|
||||
"""
|
||||
"""Compare the proven dense start with every route place before deciding."""
|
||||
started = clock()
|
||||
if route_only:
|
||||
# A dense-start prior failed fresh confirmation. Recollect first, then
|
||||
# search the route without repeatedly retrying that unconfirmed start.
|
||||
return relocalize_route(reference, reference_path, query, query_entry,
|
||||
clock=clock, policy=policy)
|
||||
target, query, initial, entry, forward, window = _route_start_context(
|
||||
reference, reference_path, query, query_entry, reference_position
|
||||
)
|
||||
clock=clock, policy=policy, on_progress=on_progress)
|
||||
try:
|
||||
target, query, initial, entry, forward, window = _route_start_context(
|
||||
reference, reference_path, query, query_entry, reference_position
|
||||
)
|
||||
except ReferenceCoverageError as exc:
|
||||
# A sparse start patch is not proof that the whole known route is
|
||||
# unusable. Keep the ordinary global proof and fresh confirmation.
|
||||
result = relocalize_route(reference, reference_path, query, query_entry,
|
||||
clock=clock, policy=policy, on_progress=on_progress)
|
||||
result["initialization"]["dense_start_unavailable"] = str(exc)
|
||||
return result
|
||||
start_result = acquire_entry(
|
||||
target,
|
||||
query,
|
||||
@@ -668,7 +684,8 @@ def relocalize_start_then_route(
|
||||
entry,
|
||||
forward,
|
||||
clock=clock,
|
||||
policy=STATIONARY_POLICY,
|
||||
policy={**STATIONARY_POLICY, "deadline_s": None},
|
||||
progress=on_progress,
|
||||
)
|
||||
start_result["initialization"].update(
|
||||
scope=policy["scope"],
|
||||
@@ -686,35 +703,26 @@ def relocalize_start_then_route(
|
||||
]
|
||||
),
|
||||
)
|
||||
if start_result["status"] == "candidate":
|
||||
start_result["initialization"] = _hybrid_initialization(policy, start_result)
|
||||
return start_result
|
||||
if not start_result["initialization"].get("complete"):
|
||||
# Compute exhaustion is not evidence that this place did not match.
|
||||
start_result["initialization"] = _hybrid_initialization(policy, start_result)
|
||||
return start_result
|
||||
|
||||
# A failed standard start may still be a valid mid-route or recovery
|
||||
# position. Give retrieval only the fresh-prefix time remaining: it must
|
||||
# never turn a late calculation into an apparently usable prior.
|
||||
remaining = policy["maximum_search_wall_s"] - (clock() - started)
|
||||
if remaining <= 0:
|
||||
route_result = choose_route_location([], entry, complete=False, policy=policy)
|
||||
route_result["initialization"].update(
|
||||
elapsed_s=0.0, worker_timeout_reason="start-stage-timeout"
|
||||
)
|
||||
else:
|
||||
recovery_policy = deepcopy(policy)
|
||||
recovery_policy["deadline_s"] = min(policy["deadline_s"], remaining)
|
||||
route_result = relocalize_route(
|
||||
reference,
|
||||
reference_path,
|
||||
query,
|
||||
entry,
|
||||
clock=clock,
|
||||
policy=recovery_policy,
|
||||
)
|
||||
additional = []
|
||||
if start_result["status"] == "candidate":
|
||||
additional.append(dict(
|
||||
candidate=dict(index=-1, position=start_result["initialization"]["reference_position"],
|
||||
progress_m=start_result["initialization"]["route_progress_m"],
|
||||
descriptor_distance=0.0),
|
||||
yaw_deg=0.0,
|
||||
result={key: value for key, value in start_result.items() if key != "initialization"},
|
||||
))
|
||||
route_result = relocalize_route(
|
||||
reference, reference_path, query, entry, clock=clock, policy=policy,
|
||||
on_progress=on_progress, additional_hypotheses=additional,
|
||||
)
|
||||
route_result["initialization"] = _hybrid_initialization(policy, start_result, route_result)
|
||||
route_result["initialization"]["elapsed_s"] = clock() - started
|
||||
route_result["registration_seconds"] = start_result.get(
|
||||
"registration_seconds", 0.0
|
||||
) + route_result.get("registration_seconds", 0.0)
|
||||
|
||||
@@ -4,6 +4,8 @@ import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
@@ -38,9 +40,13 @@ def incomplete_result(reason):
|
||||
def run_route_relocalization(
|
||||
directory, reference, reference_path, query, query_entry, *, reference_position=None,
|
||||
route_only=False,
|
||||
cancel_event=None,
|
||||
):
|
||||
source = directory / "route-relocalization-input.npz"
|
||||
destination = directory / "route-relocalization-result.json"
|
||||
progress_path = directory / "route-relocalization-progress.json"
|
||||
if cancel_event is not None and cancel_event.is_set():
|
||||
return incomplete_result("worker-cancelled")
|
||||
np.savez_compressed(
|
||||
source,
|
||||
reference=reference,
|
||||
@@ -57,8 +63,7 @@ def run_route_relocalization(
|
||||
"VECLIB_MAXIMUM_THREADS": "1",
|
||||
}
|
||||
with (directory / "calculation.log").open("wb") as log:
|
||||
try:
|
||||
subprocess.run(
|
||||
with subprocess.Popen(
|
||||
[
|
||||
sys.executable,
|
||||
"-m",
|
||||
@@ -69,20 +74,70 @@ def run_route_relocalization(
|
||||
env=environment,
|
||||
stdout=log,
|
||||
stderr=log,
|
||||
timeout=ROUTE_RELOCALIZATION_POLICY["maximum_search_wall_s"] + 5,
|
||||
check=True,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
# A process timeout says nothing about whether the scanner is at a
|
||||
# known place. Return a normal, persisted incomplete-search result
|
||||
# so the UI can distinguish it from a geometric rejection.
|
||||
destination.write_text(json.dumps(incomplete_result("worker-timeout"), allow_nan=False))
|
||||
) as process:
|
||||
reason = supervise_search(process, progress_path, cancel_event=cancel_event)
|
||||
if reason is not None:
|
||||
destination.write_text(json.dumps(incomplete_result(reason), allow_nan=False))
|
||||
return json.loads(destination.read_text())
|
||||
|
||||
|
||||
def supervise_search(process, progress_path, *, cancel_event=None, clock=time.monotonic,
|
||||
stall_s=ROUTE_RELOCALIZATION_POLICY["worker_stall_s"]):
|
||||
"""Only inactivity is timed. Advancing a finite queue may take any duration.
|
||||
|
||||
Cancellation owns this exact child, never other workers or the scanner.
|
||||
Reap it before returning so a retry cannot overlap the previous search.
|
||||
"""
|
||||
try:
|
||||
return _supervise_search(process, progress_path, cancel_event=cancel_event,
|
||||
clock=clock, stall_s=stall_s)
|
||||
finally:
|
||||
# An unexpected supervisor/file error must not leave a finite but long
|
||||
# numerical job running outside the planner's lifetime either.
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=2)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait()
|
||||
|
||||
|
||||
def _supervise_search(process, progress_path, *, cancel_event, clock, stall_s):
|
||||
last_progress = clock()
|
||||
signature = None
|
||||
while process.poll() is None:
|
||||
try:
|
||||
current = progress_path.stat().st_mtime_ns
|
||||
except FileNotFoundError:
|
||||
current = None
|
||||
if current != signature:
|
||||
last_progress, signature = clock(), current
|
||||
reason = (
|
||||
"worker-cancelled" if cancel_event is not None and cancel_event.is_set()
|
||||
else "worker-stalled" if clock() - last_progress > stall_s else None
|
||||
)
|
||||
if reason:
|
||||
return reason
|
||||
with suppress(subprocess.TimeoutExpired):
|
||||
process.wait(timeout=0.1)
|
||||
if process.returncode:
|
||||
raise subprocess.CalledProcessError(process.returncode, process.args)
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
from .route_relocalization import relocalize_start_then_route
|
||||
|
||||
destination = Path(sys.argv[2])
|
||||
progress_path = destination.with_name("route-relocalization-progress.json")
|
||||
|
||||
def progress(value):
|
||||
temporary = progress_path.with_suffix(".tmp")
|
||||
temporary.write_text(json.dumps({**value, "monotonic_ns": time.monotonic_ns()}))
|
||||
temporary.replace(progress_path)
|
||||
|
||||
progress(dict(stage="loading"))
|
||||
with np.load(Path(sys.argv[1]), allow_pickle=False) as data:
|
||||
result = relocalize_start_then_route(
|
||||
data["reference"],
|
||||
@@ -91,8 +146,10 @@ def main():
|
||||
data["query_entry"],
|
||||
reference_position=data.get("reference_position"),
|
||||
route_only=bool(data.get("route_only", False)),
|
||||
on_progress=progress,
|
||||
)
|
||||
Path(sys.argv[2]).write_text(json.dumps(result, allow_nan=False))
|
||||
progress(dict(stage="complete"))
|
||||
destination.write_text(json.dumps(result, allow_nan=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -6,13 +6,13 @@ not prove SLAM frame continuity; this remains a laboratory-only protocol.
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .causal_tracking import CausalTracking
|
||||
from .causal_tracking import TRACKING_POLICY, CausalTracking
|
||||
from .live_buffer import LiveCloudBuffer
|
||||
from .registration import rigid
|
||||
from .stationary_entry import STATIONARY_POLICY, StationaryPrefix
|
||||
|
||||
BOOTSTRAP_POLICY = dict(
|
||||
version="stationary-fresh-bootstrap/v3",
|
||||
version="stationary-fresh-bootstrap/v4",
|
||||
prefix_seconds=10.0,
|
||||
maximum_motion_m=0.10,
|
||||
maximum_search_wall_s=30.0,
|
||||
@@ -58,6 +58,15 @@ class StationaryBootstrap:
|
||||
self.candidate_index = None
|
||||
self.dense_start_prior = False
|
||||
self.retry_route_search = False
|
||||
self.last_pose_ns = None
|
||||
self.last_cloud_ns = None
|
||||
self.search_continuity_proven = False
|
||||
|
||||
@property
|
||||
def continuous_search(self):
|
||||
return self.initialization_policy.get("hypothesis_freshness") == (
|
||||
"stationary-receipts-and-disjoint-confirmation/v1"
|
||||
)
|
||||
|
||||
def stop(self, reason):
|
||||
self.prior = None
|
||||
@@ -66,6 +75,7 @@ class StationaryBootstrap:
|
||||
self.candidate_queue = []
|
||||
self.retry_route_search = False
|
||||
self.gate.clear(reason)
|
||||
self.search_continuity_proven = False
|
||||
self.phase = "lost"
|
||||
self.reason = reason
|
||||
|
||||
@@ -82,6 +92,16 @@ class StationaryBootstrap:
|
||||
self.stop("source-order-changed")
|
||||
raise ValueError("Source sequence or receipt clock regressed.")
|
||||
self.last_event_ns, self.last_sequence = event.monotonic_ns, event.sequence
|
||||
if event.kind == "pose":
|
||||
self.last_pose_ns = event.monotonic_ns
|
||||
if self.phase == "searching" and self.continuous_search:
|
||||
motion = float(np.linalg.norm(
|
||||
np.asarray(event.position) - self.prefix.first_position
|
||||
))
|
||||
if not np.isfinite(motion) or motion > BOOTSTRAP_POLICY["maximum_motion_m"]:
|
||||
self.stop("search-motion")
|
||||
elif event.kind == "points":
|
||||
self.last_cloud_ns = event.monotonic_ns
|
||||
if segment != self.segment:
|
||||
# Worker completion is not a data receipt. A gap straddling that
|
||||
# instant may finish before the first fresh cloud. No validation has
|
||||
@@ -99,7 +119,9 @@ class StationaryBootstrap:
|
||||
if awaiting_first_cloud:
|
||||
self.segment = segment
|
||||
self._reset_fresh(self.floor_ns)
|
||||
elif self.phase in {"refreshing", "validating", "tracking"}:
|
||||
elif self.phase in {"refreshing", "validating", "tracking"} or (
|
||||
self.phase == "searching" and self.continuous_search
|
||||
):
|
||||
self.stop("receipt-gap")
|
||||
self.segment = segment
|
||||
if self.phase == "collecting":
|
||||
@@ -109,6 +131,16 @@ class StationaryBootstrap:
|
||||
|
||||
def tick(self, now_ns, segment):
|
||||
self.gate.tick(now_ns, segment)
|
||||
if self.phase == "searching" and self.continuous_search:
|
||||
# Old geometry may propose a place only while the live scanner is
|
||||
# still stationary in the same receipt segment. Neither a cloud-only
|
||||
# nor a pose-only stream can keep a long search alive.
|
||||
if segment != self.initialization_sample["segment"]:
|
||||
self.stop("receipt-gap")
|
||||
elif any(stamp is None or not 0 <= (now_ns - stamp) / 1e9
|
||||
<= TRACKING_POLICY["maximum_age_s"]
|
||||
for stamp in (self.last_pose_ns, self.last_cloud_ns)):
|
||||
self.stop("search-source-stale")
|
||||
if self.phase in {"validating", "tracking"} and self.gate.reason == "stale":
|
||||
self.stop("stale")
|
||||
if self.phase == "refreshing" and (
|
||||
@@ -129,8 +161,10 @@ class StationaryBootstrap:
|
||||
return sample, initial, forward, meta
|
||||
|
||||
def offer_prior(self, result, now_ns, segment):
|
||||
self.tick(now_ns, segment)
|
||||
if self.phase != "searching":
|
||||
return dict(accepted=False, reason="inactive-initialization", provisional=False)
|
||||
return dict(accepted=False, reason=self.reason if self.phase == "lost"
|
||||
else "inactive-initialization", provisional=False)
|
||||
sample = self.initialization_sample
|
||||
age = (now_ns - sample["monotonic_ns"]) / 1e9
|
||||
initialization = result.get("initialization", {})
|
||||
@@ -158,11 +192,14 @@ class StationaryBootstrap:
|
||||
or initialization.get("expected_attempts") != len(initialization.get("attempts", []))
|
||||
):
|
||||
reason = "initialization-incomplete"
|
||||
elif not 0 <= (now_ns - self.search_started_ns) / 1e9 <= self.initialization_policy.get(
|
||||
"maximum_search_wall_s", BOOTSTRAP_POLICY["maximum_search_wall_s"]
|
||||
elif not self.continuous_search and not (
|
||||
0 <= (now_ns - self.search_started_ns) / 1e9 <= self.initialization_policy.get(
|
||||
"maximum_search_wall_s", BOOTSTRAP_POLICY["maximum_search_wall_s"]
|
||||
)
|
||||
):
|
||||
reason = "initialization-expired"
|
||||
elif not 0 <= age <= BOOTSTRAP_POLICY["maximum_prior_source_age_s"]:
|
||||
elif age < 0 or (not self.continuous_search
|
||||
and age > BOOTSTRAP_POLICY["maximum_prior_source_age_s"]):
|
||||
reason = "prior-source-expired"
|
||||
elif not 0 <= segment - sample["segment"] <= BOOTSTRAP_POLICY["maximum_pre_ready_gaps"]:
|
||||
reason = "too-many-receipt-gaps"
|
||||
@@ -178,6 +215,7 @@ class StationaryBootstrap:
|
||||
self.stop("initialization-incomplete")
|
||||
return dict(accepted=False, reason=self.reason, provisional=False, age_s=age)
|
||||
self.candidate_queue = [dict(item) for item in queue[1:]]
|
||||
self.search_continuity_proven = self.continuous_search
|
||||
self.candidate_trial = 1
|
||||
self.candidate_index = initialization.get("selected_candidate_index")
|
||||
stages = initialization.get("stages", [])
|
||||
@@ -196,6 +234,7 @@ class StationaryBootstrap:
|
||||
provisional=True,
|
||||
source_segment=sample["segment"],
|
||||
validation_segment=segment,
|
||||
stationary_search_continuity=self.search_continuity_proven,
|
||||
)
|
||||
|
||||
def _reset_fresh(self, floor_ns):
|
||||
@@ -208,10 +247,13 @@ class StationaryBootstrap:
|
||||
|
||||
This is available only before tracking. Once tracking is established,
|
||||
loss must use the ordinary last-confirmed-place recovery instead.
|
||||
The original prefix's source-age fence is never extended by retries.
|
||||
The legacy local protocol retains its source-age fence. Whole-route
|
||||
hypotheses have proved stationary receipt continuity and still need a
|
||||
new, disjoint current-data trial for EACH candidate.
|
||||
"""
|
||||
age = (now_ns - self.initialization_sample["monotonic_ns"]) / 1e9
|
||||
if not 0 <= age <= BOOTSTRAP_POLICY["maximum_prior_source_age_s"]:
|
||||
if age < 0 or (not self.search_continuity_proven
|
||||
and age > BOOTSTRAP_POLICY["maximum_prior_source_age_s"]):
|
||||
self.stop("prior-source-expired")
|
||||
return
|
||||
candidate = self.candidate_queue.pop(0)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
|
||||
import numpy as np
|
||||
|
||||
@@ -17,8 +18,7 @@ PHASE_MESSAGE = {
|
||||
"waiting-cloud": "Ожидание облака точек после подготовки сканера.",
|
||||
"collecting": "Накопление данных. Сканер должен оставаться неподвижным.",
|
||||
"searching": (
|
||||
"Точная привязка у стартовой зоны; при честном отказе — поиск по выбранному "
|
||||
"маршруту. Ожидание на месте."
|
||||
"Поиск по всему выбранному маршруту. Оставайтесь на месте до подтверждения привязки."
|
||||
),
|
||||
"refreshing": "Подтверждение привязки по новым кадрам. Ожидание на месте.",
|
||||
"validating": "Подтверждение привязки по новым кадрам. Ожидание на месте.",
|
||||
@@ -42,9 +42,15 @@ def phase_message(boot):
|
||||
)
|
||||
if boot.reason in {"initialization-incomplete", "initialization-expired"}:
|
||||
return (
|
||||
"Синхронизация маршрута не завершилась. Остановите устройство и запись, "
|
||||
"затем начните новое исследование и дождитесь неподвижной калибровки."
|
||||
"Поиск не завершён. Оставьте сканер неподвижно и нажмите "
|
||||
"«Переинициализировать». Запись продолжается."
|
||||
)
|
||||
if boot.reason == "search-motion":
|
||||
return ("Сканер перемещён во время поиска. "
|
||||
"Остановитесь и нажмите «Переинициализировать».")
|
||||
if boot.reason == "search-source-stale":
|
||||
return ("Данные сканера перестали поступать. "
|
||||
"Проверьте поток и нажмите «Переинициализировать».")
|
||||
return (
|
||||
"Синхронизация маршрута не выполнена. Убедитесь, что сканер находится "
|
||||
"у исследованного участка; можно выбрать другую различимую точку, остановиться "
|
||||
@@ -74,6 +80,8 @@ def run_stationary_live(service, source, run_id, executor, clock, initialize, ca
|
||||
recovery_attempt = 0
|
||||
recovery_position = None
|
||||
route_search_only = False
|
||||
search_cancel = threading.Event()
|
||||
requested_retry = None
|
||||
|
||||
def begin_recovery(reason):
|
||||
# Retain only the last confirmed place as a SEARCH HINT. Neither the
|
||||
@@ -360,18 +368,20 @@ def run_stationary_live(service, source, run_id, executor, clock, initialize, ca
|
||||
else "input-ended"
|
||||
)
|
||||
break
|
||||
retry_attempt = service.consume_reinitialization(run_id)
|
||||
if retry_attempt is not None:
|
||||
requested_retry = service.consume_reinitialization(run_id) or requested_retry
|
||||
if requested_retry is not None:
|
||||
if future is not None:
|
||||
# The public operation admits only a terminal initial
|
||||
# failure. Keep this fence in case a caller races an
|
||||
# internal state update.
|
||||
raise RuntimeError("Нельзя переинициализировать во время расчёта привязки.")
|
||||
reset_initialization(retry_attempt)
|
||||
continue
|
||||
search_cancel.set()
|
||||
finish(active=False)
|
||||
if future is None:
|
||||
reset_initialization(requested_retry)
|
||||
requested_retry = None
|
||||
continue
|
||||
now = clock.monotonic()
|
||||
if boot is not None:
|
||||
boot.tick(clock.monotonic_ns(), buffer.segment)
|
||||
if boot.phase == "lost":
|
||||
search_cancel.set()
|
||||
finish()
|
||||
current = source.snapshot()
|
||||
if not current["active"] or current.get("spatial_stop_requested", False):
|
||||
@@ -510,12 +520,9 @@ def run_stationary_live(service, source, run_id, executor, clock, initialize, ca
|
||||
receipt_gaps=sample["gaps"],
|
||||
)
|
||||
last_snapshot = now
|
||||
if buffer.distance >= service.run["maximum_distance_m"]:
|
||||
# A pose can reach the limit before the next cloud snapshot.
|
||||
service.update_sample(buffer.snapshot(), clock.monotonic_ns())
|
||||
service.update(distance_m=buffer.distance)
|
||||
end_reason = "distance-limit"
|
||||
break
|
||||
# Travel is telemetry, not completion. Detours and additional
|
||||
# laps must keep consuming the same capture and confirming the
|
||||
# same reference, even if an older run carried a distance cap.
|
||||
if boot is None or future is not None:
|
||||
continue
|
||||
# Do not freeze ahead of an already queued prefix receipt.
|
||||
@@ -548,6 +555,7 @@ def run_stationary_live(service, source, run_id, executor, clock, initialize, ca
|
||||
"initialization_policy": ROUTE_RELOCALIZATION_POLICY,
|
||||
},
|
||||
)
|
||||
search_cancel = threading.Event()
|
||||
future = executor.submit(
|
||||
initialize,
|
||||
target,
|
||||
@@ -557,6 +565,7 @@ def run_stationary_live(service, source, run_id, executor, clock, initialize, ca
|
||||
sample["path"][0],
|
||||
**({"reference_position": recovery_position} if recovering else {}),
|
||||
**({"route_only": True} if route_search_only else {}),
|
||||
cancel_event=search_cancel,
|
||||
)
|
||||
publish_phase()
|
||||
continue
|
||||
@@ -588,6 +597,7 @@ def run_stationary_live(service, source, run_id, executor, clock, initialize, ca
|
||||
sample, "fresh-validation", {"reference_window": window}
|
||||
)
|
||||
future = executor.submit(calculate, target, reference, sample["points"], hint)
|
||||
search_cancel.set()
|
||||
if boot is not None:
|
||||
boot.stop(end_reason)
|
||||
with service.lock:
|
||||
@@ -600,12 +610,7 @@ def run_stationary_live(service, source, run_id, executor, clock, initialize, ca
|
||||
tracking_state="lost",
|
||||
tracking_reason=end_reason,
|
||||
termination_reason=end_reason,
|
||||
message=(
|
||||
"Достигнут предел проверочного прохода. "
|
||||
"Запись управляется штатными кнопками сканера."
|
||||
if end_reason == "distance-limit"
|
||||
else "Исследование завершено. Запись управляется штатными кнопками сканера."
|
||||
),
|
||||
message="Исследование завершено. Запись управляется штатными кнопками сканера.",
|
||||
finished_at_utc=utc_now_iso(),
|
||||
)
|
||||
# Publish ended before waiting for an already-running bounded fit.
|
||||
@@ -627,3 +632,5 @@ def run_stationary_live(service, source, run_id, executor, clock, initialize, ca
|
||||
"Завершите проход и начните повторную проверку."
|
||||
) from exc
|
||||
raise
|
||||
finally:
|
||||
search_cancel.set()
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
"""Explicit offline bridge from a pinned map candidate to existing planning APIs.
|
||||
|
||||
Not installed in the web composition. The original source remains the default;
|
||||
only an explicitly pinned derivative generation selects corrected geometry.
|
||||
"""
|
||||
|
||||
import shutil
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
import numpy as np
|
||||
|
||||
from k1link.reconstruction.map_version import POINTS, MapVersion
|
||||
|
||||
EXTRACTION = dict(
|
||||
version="map-version-submap/v1",
|
||||
max_frames=120,
|
||||
voxel_m=0.25,
|
||||
radius_m=20.0,
|
||||
height_relative_m=[-3.0, 6.0],
|
||||
)
|
||||
|
||||
|
||||
class VersionedPlanningSources:
|
||||
def __init__(self, original, version, scratch):
|
||||
self.original, self.version = original, version
|
||||
self.scratch = Path(scratch)
|
||||
self.scratch.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def get(self, session_id):
|
||||
# No implicit promotion and no changes to existing consumers.
|
||||
return self.original.get(session_id)
|
||||
|
||||
def bound(self, session_id, generation):
|
||||
if generation != self.version.generation:
|
||||
return self.original.bound(session_id, generation)
|
||||
parent = self.version.document["source"]
|
||||
if session_id != parent["session_id"]:
|
||||
raise ValueError("Map candidate belongs to another session.")
|
||||
source = self.original.verify(session_id, parent["generation"])
|
||||
return self.version.planning_source(source)
|
||||
|
||||
def verify(self, session_id, generation):
|
||||
if generation != self.version.generation:
|
||||
return self.original.verify(session_id, generation)
|
||||
return self.bound(session_id, generation)
|
||||
|
||||
@contextmanager
|
||||
def prepared_submaps(self, session_id, generation, *, presentation=False, cancel_event=None):
|
||||
if generation != self.version.generation:
|
||||
with self.original.prepared_submaps(
|
||||
session_id, generation, presentation=presentation, cancel_event=cancel_event
|
||||
) as extract:
|
||||
yield extract
|
||||
return
|
||||
|
||||
def cancelled():
|
||||
if cancel_event is not None and cancel_event.is_set():
|
||||
raise InterruptedError("Map version preparation cancelled.")
|
||||
|
||||
cancelled()
|
||||
doc = self.verify(session_id, generation)
|
||||
with TemporaryDirectory(prefix=".map-snapshot-", dir=self.scratch) as temporary:
|
||||
stage = Path(temporary)
|
||||
for path in self.version.directory.iterdir():
|
||||
if path.name == "manifest.json" or path.name in self.version.document["artifacts"]:
|
||||
cancelled()
|
||||
shutil.copyfile(path, stage / path.name)
|
||||
snapshot = MapVersion(stage, generation)
|
||||
snapshot.verify()
|
||||
arrays = snapshot.arrays()
|
||||
|
||||
def extract(start, end):
|
||||
cancelled()
|
||||
return _extract(snapshot, arrays, doc, start, end, presentation=presentation)
|
||||
|
||||
yield extract
|
||||
cancelled()
|
||||
# A changed parent or derivative invalidates the complete preparation.
|
||||
self.verify(session_id, generation)
|
||||
|
||||
def submap(self, session_id, generation, start, end, *, presentation=False):
|
||||
with self.prepared_submaps(session_id, generation, presentation=presentation) as extract:
|
||||
return extract(start, end)
|
||||
|
||||
def reference_map(self, session_id, generation, start, end, **options):
|
||||
from .reference_map import build_reference_map
|
||||
|
||||
return build_reference_map(self, session_id, generation, start, end, **options)
|
||||
|
||||
def scene_reference_map(self, session_id, generation, start, end, **options):
|
||||
from .reference_map import build_reference_map
|
||||
|
||||
return build_reference_map(
|
||||
self, session_id, generation, start, end, presentation=True, **options
|
||||
)
|
||||
|
||||
|
||||
def _extract(version, arrays, doc, start, end, *, presentation):
|
||||
poses, frames = arrays["positions"], arrays["frames"]
|
||||
t = arrays["receipt_time_s"]
|
||||
if not 0 <= start < end < len(poses):
|
||||
raise ValueError("Invalid map interval.")
|
||||
eligible = np.flatnonzero((frames[:, 0] >= t[start]) & (frames[:, 0] <= t[end]))
|
||||
if not len(eligible):
|
||||
raise ValueError("No cloud frames in the selected map interval.")
|
||||
selected = eligible[
|
||||
np.linspace(0, len(eligible) - 1, min(len(eligible), EXTRACTION["max_frames"]), dtype=int)
|
||||
]
|
||||
profile = {
|
||||
**EXTRACTION,
|
||||
**(dict(radius_m=80.0, height_relative_m=None) if presentation else {}),
|
||||
}
|
||||
# A frame uses the interpolated corrected sensor position only for cropping;
|
||||
# the stored cloud already is in map coordinates and is never transformed twice.
|
||||
centers = np.column_stack(
|
||||
[np.interp(frames[selected, 0], t, poses[:, axis]) for axis in range(3)]
|
||||
)
|
||||
chunks, provenance, raw_count, retained_count = [], [], 0, 0
|
||||
with (version.directory / POINTS).open("rb") as stream:
|
||||
for index, center in zip(selected, centers, strict=True):
|
||||
_, sequence, offset, count = frames[index]
|
||||
stream.seek(int(offset) * 12)
|
||||
chunk = np.frombuffer(stream.read(int(count) * 12), dtype="<f4").reshape(-1, 3)
|
||||
if len(chunk) != count or not np.isfinite(chunk).all():
|
||||
raise ValueError("Invalid map frame payload.")
|
||||
delta = chunk - center
|
||||
keep = np.linalg.norm(delta, axis=1) <= profile["radius_m"]
|
||||
if profile["height_relative_m"] is not None:
|
||||
low, high = profile["height_relative_m"]
|
||||
keep &= (delta[:, 2] >= low) & (delta[:, 2] <= high)
|
||||
raw_count += len(chunk)
|
||||
retained_count += int(keep.sum())
|
||||
chunks.append(chunk[keep])
|
||||
provenance.append(
|
||||
dict(
|
||||
frame_index=int(index),
|
||||
sequence=int(sequence),
|
||||
receipt_time_s=float(frames[index, 0]),
|
||||
source_distance_m=float(arrays["frame_source_distance_m"][index]),
|
||||
)
|
||||
)
|
||||
points = np.concatenate(chunks)
|
||||
_, indices = np.unique(
|
||||
np.floor(points / profile["voxel_m"]).astype(np.int64), axis=0, return_index=True
|
||||
)
|
||||
points = points[np.sort(indices)]
|
||||
return points, {
|
||||
**{
|
||||
key: doc[key]
|
||||
for key in ("session_id", "generation", "label", "frame_id", "units", "source_digests")
|
||||
},
|
||||
"reference_version": doc["reference_version"],
|
||||
"extraction": profile,
|
||||
"start_index": start,
|
||||
"end_index": end,
|
||||
"available_frames": len(eligible),
|
||||
"frames": provenance,
|
||||
"raw_points": raw_count,
|
||||
"retained_points": retained_count,
|
||||
"voxel_points": len(points),
|
||||
}
|
||||
Reference in New Issue
Block a user