Add vector infrastructure maps and persistent location experience
This commit is contained in:
@@ -0,0 +1,246 @@
|
||||
"""Bounded location experience. Observations and soft preferences, never occupancy.
|
||||
|
||||
Coordinates cannot migrate between world/collider/robot revisions. Runtime sensor
|
||||
memory remains separate. Persistent records are summaries, not raw telemetry.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
|
||||
SCHEMA = "missioncore.spatial-experience/v1"
|
||||
MAX_VISITS, MAX_ATTEMPTS = 20000, 1000
|
||||
FAILURES = {
|
||||
"no-path",
|
||||
"footprint",
|
||||
"observed-unsafe-support",
|
||||
"forbidden-surface-sweep",
|
||||
"detected-object-sweep",
|
||||
"no-permitted-goal",
|
||||
}
|
||||
|
||||
|
||||
def source_key(source):
|
||||
if (
|
||||
not isinstance(source, dict)
|
||||
or set(source) != {"world_sha256", "collider_sha256", "robot_sha256"}
|
||||
or any(
|
||||
not isinstance(v, str) or len(v) != 64 or any(c not in "0123456789abcdef" for c in v)
|
||||
for v in source.values()
|
||||
)
|
||||
):
|
||||
raise ValueError("Invalid spatial experience revision")
|
||||
return hashlib.sha256(json.dumps(source, sort_keys=True).encode()).hexdigest()
|
||||
|
||||
|
||||
def valid_xyz(value):
|
||||
return (
|
||||
isinstance(value, list)
|
||||
and len(value) == 3
|
||||
and all(type(v) in (float, int) and math.isfinite(v) and abs(v) < 1e6 for v in value)
|
||||
)
|
||||
|
||||
|
||||
def validate(document, source=None):
|
||||
if not isinstance(document, dict) or document.get("schema_version") != SCHEMA:
|
||||
raise ValueError("Invalid location experience")
|
||||
source_key(document.get("source", {}))
|
||||
if source is not None and source != document["source"]:
|
||||
raise ValueError("Location revision mismatch")
|
||||
if document.get("authority") != "experience-only":
|
||||
raise ValueError("Experience cannot grant motion")
|
||||
for field, limit in [("visits", MAX_VISITS), ("attempts", MAX_ATTEMPTS)]:
|
||||
items = document.get(field)
|
||||
if not isinstance(items, list) or len(items) > limit:
|
||||
raise ValueError("Experience exceeds bounds")
|
||||
ids = set()
|
||||
for item in items:
|
||||
if not isinstance(item, dict) or not valid_xyz(item.get("xyz")):
|
||||
raise ValueError("Invalid experience point")
|
||||
key = item.get("id")
|
||||
if not isinstance(key, str) or len(key) > 80 or key in ids:
|
||||
raise ValueError("Invalid experience identity")
|
||||
ids.add(key)
|
||||
for name in ["first_seen", "last_seen"]:
|
||||
v = item.get(name)
|
||||
if type(v) not in (int, float) or not math.isfinite(v) or v < 0:
|
||||
raise ValueError("Invalid experience time")
|
||||
if type(item.get("count")) is not int or not 1 <= item["count"] <= 1000000:
|
||||
raise ValueError("Invalid experience count")
|
||||
if field == "attempts":
|
||||
if not valid_xyz(item.get("origin")) or item.get("reason") not in FAILURES:
|
||||
raise ValueError("Invalid attempt")
|
||||
if item.get("status") not in {"unresolved", "revisited-successfully"}:
|
||||
raise ValueError("Invalid attempt state")
|
||||
if not isinstance(item.get("run_id"), str) or len(item["run_id"]) > 80:
|
||||
raise ValueError("Invalid attempt source")
|
||||
if (
|
||||
not isinstance(item.get("observation_id"), str)
|
||||
or len(item["observation_id"]) > 120
|
||||
):
|
||||
raise ValueError("Invalid attempt observation")
|
||||
return document
|
||||
|
||||
|
||||
class LocationExperience:
|
||||
def __init__(self, source, document=None):
|
||||
source_key(source)
|
||||
self.source = source
|
||||
self.revision = 0
|
||||
self.previous = None
|
||||
self.blockage = None
|
||||
self.latched = None
|
||||
doc = validate(document, source) if document is not None else {"visits": [], "attempts": []}
|
||||
self.visits = {r["id"]: dict(r) for r in doc["visits"]}
|
||||
self.attempts = {r["id"]: dict(r) for r in doc["attempts"]}
|
||||
|
||||
def document(self):
|
||||
return dict(
|
||||
schema_version=SCHEMA,
|
||||
source=self.source,
|
||||
authority="experience-only",
|
||||
visits=list(self.visits.values()),
|
||||
attempts=list(self.attempts.values()),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def trim(items, limit):
|
||||
while len(items) > limit:
|
||||
del items[min(items, key=lambda key: items[key]["last_seen"])]
|
||||
|
||||
def observe(
|
||||
self,
|
||||
xyz,
|
||||
goal,
|
||||
navigation,
|
||||
simulation_seconds,
|
||||
now,
|
||||
run_id,
|
||||
observation_id,
|
||||
execution_sha,
|
||||
pose,
|
||||
):
|
||||
"""Require matched current navigation evidence; transport failures are not places."""
|
||||
xyz = [float(v) for v in xyz]
|
||||
if not valid_xyz(xyz):
|
||||
return
|
||||
moved = self.previous is not None and math.dist(xyz, self.previous) >= 0.2
|
||||
if self.previous is None or moved:
|
||||
old = self.previous
|
||||
self.previous = xyz
|
||||
key = ",".join(str(math.floor(v / 0.5)) for v in xyz[:2])
|
||||
entry = self.visits.get(key)
|
||||
self.visits[key] = dict(
|
||||
id=key,
|
||||
xyz=xyz,
|
||||
first_seen=entry["first_seen"] if entry else now,
|
||||
last_seen=now,
|
||||
count=min(1000000, (entry["count"] if entry else 0) + 1),
|
||||
)
|
||||
self.trim(self.visits, MAX_VISITS)
|
||||
self.revision += 1
|
||||
if moved:
|
||||
self.latched = None
|
||||
for item in self.attempts.values():
|
||||
if item["status"] != "unresolved" or math.dist(xyz, item["xyz"]) > 0.4:
|
||||
continue
|
||||
direction = [item["xyz"][i] - item["origin"][i] for i in range(2)]
|
||||
if sum(direction[i] * (xyz[i] - old[i]) for i in range(2)) > 0:
|
||||
item["status"] = "revisited-successfully"
|
||||
item["resolved_at"] = now
|
||||
self.revision += 1
|
||||
failure = navigation.get("diagnostic", {}).get("failure")
|
||||
expected = dict(
|
||||
pose=list(pose),
|
||||
simulation_time_seconds=simulation_seconds,
|
||||
execution_inputs_sha256=execution_sha,
|
||||
)
|
||||
bound = navigation.get("route_observation", {}).get("observation") == expected
|
||||
if goal is None and failure == "no-permitted-goal":
|
||||
goal = xyz
|
||||
if (
|
||||
not bound
|
||||
or failure not in FAILURES
|
||||
or navigation.get("status") != "blocked"
|
||||
or abs(navigation.get("speed_mps", 0)) + abs(navigation.get("yaw_rate_rps", 0)) > 1e-5
|
||||
or goal is None
|
||||
or not valid_xyz(list(goal))
|
||||
):
|
||||
self.blockage = None
|
||||
return
|
||||
delta = [goal[i] - xyz[i] for i in range(2)]
|
||||
sector = round(math.atan2(delta[1], delta[0]) / (math.pi / 4)) % 8
|
||||
key = ",".join(
|
||||
map(str, [math.floor(xyz[0] / 0.5), math.floor(xyz[1] / 0.5), sector, failure])
|
||||
)
|
||||
if (
|
||||
self.blockage is None
|
||||
or self.blockage[0] != key
|
||||
or simulation_seconds < self.blockage[1]
|
||||
):
|
||||
self.blockage = (key, simulation_seconds)
|
||||
return
|
||||
if simulation_seconds - self.blockage[1] < 0.5 or self.latched == key:
|
||||
return
|
||||
self.latched = key
|
||||
entry = self.attempts.get(key)
|
||||
self.attempts[key] = dict(
|
||||
id=key,
|
||||
xyz=list(goal),
|
||||
origin=xyz,
|
||||
reason=failure,
|
||||
status="unresolved",
|
||||
first_seen=entry["first_seen"] if entry else now,
|
||||
last_seen=now,
|
||||
count=min(1000000, (entry["count"] if entry else 0) + 1),
|
||||
run_id=run_id,
|
||||
observation_id=observation_id,
|
||||
)
|
||||
self.trim(self.attempts, MAX_ATTEMPTS)
|
||||
self.revision += 1
|
||||
|
||||
def costs(self, origin, candidates, now):
|
||||
"""Only rank already-admissible recovery intentions from the same approach.
|
||||
|
||||
Temporary failures fade in ten minutes; records remain for inspection.
|
||||
A cost never removes a candidate or bypasses current collision checks.
|
||||
"""
|
||||
result = []
|
||||
nearby = [
|
||||
a
|
||||
for a in self.attempts.values()
|
||||
if a["status"] == "unresolved"
|
||||
and 0 <= now - a["last_seen"] < 600
|
||||
and math.dist(origin[:2], a["origin"][:2]) <= 1.5
|
||||
]
|
||||
for point in candidates:
|
||||
cost = 0.0
|
||||
for a in nearby:
|
||||
u = [point[i] - origin[i] for i in range(2)]
|
||||
v = [a["xyz"][i] - a["origin"][i] for i in range(2)]
|
||||
norm = math.hypot(*u) * math.hypot(*v)
|
||||
if (
|
||||
norm > 0
|
||||
and sum(u[i] * v[i] for i in range(2)) / norm > 0.8
|
||||
and math.dist(point[:2], a["xyz"][:2]) < 1.0
|
||||
):
|
||||
cost = max(cost, 2.0 * (1 - (now - a["last_seen"]) / 600))
|
||||
result.append(cost)
|
||||
return result
|
||||
|
||||
|
||||
def read(path, source=None):
|
||||
if path.stat().st_size > 8 * 1024**2:
|
||||
raise ValueError("Experience exceeds size limit")
|
||||
return validate(json.loads(path.read_text()), source)
|
||||
|
||||
|
||||
def save(path, document):
|
||||
validate(document)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
data = json.dumps(document, allow_nan=False, separators=(",", ":"))
|
||||
if len(data.encode()) > 8 * 1024**2:
|
||||
raise ValueError("Experience exceeds size limit")
|
||||
temp = path.with_suffix(".tmp")
|
||||
temp.write_text(data)
|
||||
temp.replace(path)
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Derived infrastructure observations, bound to the exact simulation world."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.simulation.ai_polygon.worlds import write_json
|
||||
|
||||
CLASSES = {
|
||||
"curb",
|
||||
"bike_lane",
|
||||
"crosswalk_area",
|
||||
"curb_cut",
|
||||
"parking",
|
||||
"pedestrian_area",
|
||||
"carriageway",
|
||||
"service_lane",
|
||||
"sidewalk",
|
||||
"crosswalk_marking",
|
||||
"road_marking",
|
||||
}
|
||||
|
||||
|
||||
def validate_map(document: dict, world: dict) -> dict:
|
||||
if not isinstance(document, dict):
|
||||
raise ValueError("Infrastructure map must be an object")
|
||||
if (
|
||||
document.get("schema_version")
|
||||
not in {"missioncore.urban-map/v1", "missioncore.urban-map/v2"}
|
||||
or document.get("type") != "FeatureCollection"
|
||||
):
|
||||
raise ValueError("Unsupported infrastructure map")
|
||||
if document.get("coordinate_system") != {
|
||||
"frame": "scene-local",
|
||||
"units": "metres",
|
||||
"up": "Z",
|
||||
"georeferenced": False,
|
||||
}:
|
||||
raise ValueError("Infrastructure map coordinate frame mismatch")
|
||||
source = document.get("source", {})
|
||||
if not isinstance(source, dict):
|
||||
raise ValueError("Invalid infrastructure source")
|
||||
if source.get("world_sha256") != world["sha256"] or source.get("collider_sha256") != world.get(
|
||||
"collider_sha256"
|
||||
):
|
||||
raise ValueError("Infrastructure map belongs to a different scene revision")
|
||||
coverage = document.get("coverage")
|
||||
if not isinstance(coverage, dict):
|
||||
raise ValueError("Missing infrastructure coverage")
|
||||
cell, cells = coverage.get("cell_m"), coverage.get("accepted_cells")
|
||||
if type(cell) not in (int, float) or not math.isfinite(cell) or not 0.02 <= cell <= 1:
|
||||
raise ValueError("Invalid infrastructure sampling resolution")
|
||||
if type(cells) is not int or not 0 <= cells <= 1_000_000:
|
||||
raise ValueError("Invalid infrastructure coverage count")
|
||||
features = document.get("features")
|
||||
if not isinstance(features, list) or len(features) > 20000:
|
||||
raise ValueError("Invalid infrastructure feature count")
|
||||
vertices = 0
|
||||
identifiers = set()
|
||||
for feature in features:
|
||||
if not isinstance(feature, dict) or feature.get("type") != "Feature":
|
||||
raise ValueError("Invalid infrastructure feature")
|
||||
prop, geo = feature.get("properties", {}), feature.get("geometry", {})
|
||||
if not isinstance(prop, dict) or not isinstance(geo, dict):
|
||||
raise ValueError("Invalid infrastructure feature")
|
||||
if (
|
||||
not isinstance(prop.get("class"), str)
|
||||
or prop.get("class") not in CLASSES
|
||||
or prop.get("authority") != "observation-only"
|
||||
or prop.get("route_permission") != "unassigned"
|
||||
):
|
||||
raise ValueError("Infrastructure observations cannot grant route permissions")
|
||||
vector = document["schema_version"] == "missioncore.urban-map/v2"
|
||||
if vector:
|
||||
identifier = feature.get("id")
|
||||
score = prop.get("confidence")
|
||||
if (
|
||||
not isinstance(identifier, str)
|
||||
or not re.fullmatch("[a-zA-Z0-9_-]{1,80}", identifier)
|
||||
or identifier in identifiers
|
||||
):
|
||||
raise ValueError("Invalid or duplicate infrastructure identity")
|
||||
identifiers.add(identifier)
|
||||
if type(score) not in (int, float) or not math.isfinite(score) or not 0 <= score <= 1:
|
||||
raise ValueError("Invalid infrastructure confidence")
|
||||
if prop.get("review_status") not in {"unreviewed", "accepted", "rejected"}:
|
||||
raise ValueError("Invalid infrastructure review state")
|
||||
kind, coordinates = geo.get("type"), geo.get("coordinates")
|
||||
if (
|
||||
kind not in ({"Polygon", "LineString"} if vector else {"Polygon"})
|
||||
or not isinstance(coordinates, list)
|
||||
or not coordinates
|
||||
):
|
||||
raise ValueError("Invalid infrastructure geometry")
|
||||
paths = coordinates if kind == "Polygon" else [coordinates]
|
||||
for ring in paths:
|
||||
if not isinstance(ring, list) or len(ring) < (4 if kind == "Polygon" else 2):
|
||||
raise ValueError("Invalid infrastructure path")
|
||||
if kind == "Polygon" and ring[0] != ring[-1]:
|
||||
raise ValueError("Infrastructure ring must be closed")
|
||||
vertices += len(ring)
|
||||
for point in ring:
|
||||
if (
|
||||
not isinstance(point, list)
|
||||
or len(point) != 3
|
||||
or any(
|
||||
type(v) not in (int, float) or not math.isfinite(v) or abs(v) > 1e6
|
||||
for v in point
|
||||
)
|
||||
):
|
||||
raise ValueError("Invalid infrastructure XYZ")
|
||||
if vertices > 300000:
|
||||
raise ValueError("Infrastructure map exceeds vertex limit")
|
||||
return document
|
||||
|
||||
|
||||
class UrbanMapStore:
|
||||
def __init__(self, data_dir: Path):
|
||||
self.root = data_dir / "ai-polygon" / "urban-maps"
|
||||
|
||||
def directory(self, world):
|
||||
key = world["sha256"]
|
||||
if not re.fullmatch("[0-9a-f]{64}", key):
|
||||
raise ValueError("Invalid world identity")
|
||||
return self.root / key
|
||||
|
||||
def save(self, world, document):
|
||||
validate_map(document, world)
|
||||
raw = json.dumps(document, sort_keys=True, ensure_ascii=False, allow_nan=False).encode()
|
||||
if len(raw) > 12 * 1024**2:
|
||||
raise ValueError("Infrastructure map exceeds size limit")
|
||||
sha = hashlib.sha256(raw).hexdigest()
|
||||
directory = self.directory(world)
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
write_json(directory / (sha + ".json"), document)
|
||||
write_json(directory / "latest.json", {"sha256": sha})
|
||||
return {"sha256": sha, "features": len(document["features"])}
|
||||
|
||||
def get(self, world):
|
||||
directory = self.directory(world)
|
||||
sha = json.loads((directory / "latest.json").read_text())["sha256"]
|
||||
if not re.fullmatch("[0-9a-f]{64}", sha):
|
||||
raise ValueError("Invalid infrastructure identity")
|
||||
document = json.loads((directory / (sha + ".json")).read_text())
|
||||
raw = json.dumps(document, sort_keys=True, ensure_ascii=False, allow_nan=False).encode()
|
||||
if hashlib.sha256(raw).hexdigest() != sha:
|
||||
raise ValueError("Infrastructure content changed")
|
||||
return validate_map(document, world)
|
||||
Reference in New Issue
Block a user