Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
@@ -17,6 +17,12 @@ files = sorted(
|
||||
for p in folder.rglob("*")
|
||||
if p.is_file() and not p.is_symlink() and "__pycache__" not in p.parts
|
||||
)
|
||||
files.extend((root / "apps/control-station/public/vendor/playcanvas/draco/1.5.7").glob("*"))
|
||||
# The canonical Rover 006 asset is shared with PlayCanvas, not a second model.
|
||||
for profile in (root / "simulation/ai-polygon/robots").glob("*.json"):
|
||||
asset = root / json.loads(profile.read_text())["visual"]["source"]
|
||||
if asset not in files:
|
||||
files.append(asset)
|
||||
manifest = {
|
||||
p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() for p in files
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"repository": "CIDAS/clipseg-rd64-refined",
|
||||
"revision": "999e0328d9e10b484360c477313983f9afdd7050",
|
||||
"asset_directory": "clipseg-rd64-refined",
|
||||
"qualification_only": true,
|
||||
"files": {
|
||||
"config.json": "c023375966d31b3b1392764f7bd91df47098ce19f62f11b0263d8eedcf708bcd",
|
||||
"preprocessor_config.json": "4fb09ebcfd7651205ca8299b993c30088e5535ef350a72d46c5c4580eeac0440",
|
||||
"tokenizer_config.json": "4c75d57fd9bd0be8478ad2d6f8b9cebdd4a45338eb108547329c2b6333476ca6",
|
||||
"special_tokens_map.json": "c4864a9376a8401918425bed71fc14fc0e81f9b59ec45c1cf96cccb2df508eac",
|
||||
"vocab.json": "e089ad92ba36837a0d31433e555c8f45fe601ab5c221d4f607ded32d9f7a4349",
|
||||
"merges.txt": "9fd691f7c8039210e0fced15865466c65820d09b63988b0174bfe25de299051a",
|
||||
"README.md": "c1e26ac022542015a04d804460bdc1159d753c4349b628e086f127475d2fcf25",
|
||||
"pytorch_model.bin": "dd9308225b8314bb7236f207e6ea72b22db5d90dba03fe3dc7d654f54dcfd08a"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Prepare only the pinned optional research model; no host packages or services."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def sha(path):
|
||||
with path.open("rb") as stream:
|
||||
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--root", type=Path, default=Path("D:/NDC_MISSIONCORE/runtime/simulation"))
|
||||
args = parser.parse_args()
|
||||
descriptor = json.loads(Path(__file__).with_name("model.json").read_text())
|
||||
output = args.root / "assets" / descriptor["asset_directory"] / descriptor["revision"]
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
for name, expected in descriptor["files"].items():
|
||||
path = output / name
|
||||
if not path.exists():
|
||||
part = path.with_name(name + f".{os.getpid()}.part")
|
||||
url = f'https://huggingface.co/{descriptor["repository"]}/resolve/{descriptor["revision"]}/{name}'
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=60) as response, part.open("xb") as stream:
|
||||
while chunk := response.read(1024 * 1024):
|
||||
stream.write(chunk)
|
||||
if sha(part) != expected:
|
||||
raise ValueError("Downloaded model checksum mismatch: " + name)
|
||||
part.replace(path)
|
||||
finally:
|
||||
part.unlink(missing_ok=True)
|
||||
if sha(path) != expected:
|
||||
raise ValueError("Existing model checksum mismatch: " + name)
|
||||
receipt = dict(schema_version="missioncore.optional-model-preparation/v1",
|
||||
descriptor=descriptor, utc=datetime.now(UTC).isoformat(),
|
||||
assets=str(output), scope="offline simulation qualification",
|
||||
rollback="Remove this optional qualification asset; no active model was changed")
|
||||
(output / "installation.json").write_text(json.dumps(receipt, indent=2))
|
||||
print(json.dumps(receipt))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Text-conditioned segmentation qualification, with no navigation authority."""
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
from transformers import CLIPSegConfig, CLIPSegForImageSegmentation, CLIPSegProcessor
|
||||
|
||||
PROMPTS = ['sidewalk', 'road', 'crosswalk', 'building', 'wall', 'vegetation', 'stairs']
|
||||
|
||||
|
||||
def sha(path):
|
||||
digest = hashlib.sha256()
|
||||
with path.open('rb') as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def main():
|
||||
torch.set_num_threads(3)
|
||||
root = Path('/assets')
|
||||
descriptor = json.loads(Path('/adapter/model.json').read_text())
|
||||
for name, expected in descriptor['files'].items():
|
||||
assert sha(root / name) == expected, name
|
||||
processor = CLIPSegProcessor.from_pretrained(root, local_files_only=True)
|
||||
model = CLIPSegForImageSegmentation(CLIPSegConfig.from_pretrained(root, local_files_only=True))
|
||||
state = torch.load(root / 'pytorch_model.bin', weights_only=True, map_location='cpu')
|
||||
# Legacy Transformers saved these deterministic buffers; current versions
|
||||
# regenerate them. Verify equality before removing only those extra keys.
|
||||
for key in ('clip.text_model.embeddings.position_ids', 'clip.vision_model.embeddings.position_ids'):
|
||||
if key in state and key not in model.state_dict():
|
||||
assert torch.equal(state.pop(key), model.get_buffer(key)), key
|
||||
model.load_state_dict(state, strict=True)
|
||||
del state
|
||||
model.cuda().eval()
|
||||
rows = []
|
||||
output = Path('/evidence')
|
||||
for source in json.loads(Path('/inputs/manifest.json').read_text()):
|
||||
path = Path('/inputs') / source['file']
|
||||
assert sha(path) == source['sha256']
|
||||
image = Image.open(path).convert('RGB')
|
||||
inputs = processor(text=PROMPTS, images=[image] * len(PROMPTS), padding=True, return_tensors='pt').to('cuda')
|
||||
torch.cuda.synchronize()
|
||||
begin = time.monotonic()
|
||||
with torch.inference_mode():
|
||||
logits = model(**inputs).logits
|
||||
logits = torch.nn.functional.interpolate(logits[:,None], size=(image.height,image.width), mode='bilinear', align_corners=False)[:,0]
|
||||
scores = logits.sigmoid().cpu().numpy()
|
||||
torch.cuda.synchronize()
|
||||
elapsed = time.monotonic() - begin
|
||||
# Scores for separate prompts are diagnostic similarities, not calibrated probabilities.
|
||||
labels = scores.argmax(axis=0)
|
||||
known = scores.max(axis=0) >= .5
|
||||
colors = np.zeros((*labels.shape,3), dtype=np.uint8)
|
||||
for label,color in [(0,[20,220,170]),(1,[220,40,50]),(2,[240,200,20])]:
|
||||
colors[(labels==label)&known] = color
|
||||
Image.blend(image,Image.fromarray(colors),.45).save(output/(path.stem+'.jpg'))
|
||||
np.savez_compressed(output/(path.stem+'.npz'),scores=scores.astype(np.float16),prompts=np.array(PROMPTS))
|
||||
row=dict(source=source,utc=datetime.now(timezone.utc).isoformat(),monotonic=time.monotonic(),inference_seconds=elapsed,
|
||||
fractions={prompt:float(((labels==i)&known).mean()) for i,prompt in enumerate(PROMPTS)},
|
||||
max_scores={prompt:float(scores[i].max()) for i,prompt in enumerate(PROMPTS)})
|
||||
rows.append(row)
|
||||
(output/'results.json').write_text(json.dumps(rows,indent=2))
|
||||
print(json.dumps(row),flush=True)
|
||||
(output/'artifact-sha256.json').write_text(json.dumps({p.name:sha(p) for p in output.iterdir() if p.is_file()},indent=2))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,57 @@
|
||||
"""One offline GPU job under a Core simulation reservation, with exact cleanup."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--reservation", type=Path, required=True)
|
||||
parser.add_argument("--inputs", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--root", type=Path, default=Path("D:/NDC_MISSIONCORE/runtime/simulation"))
|
||||
args = parser.parse_args()
|
||||
receipt = json.loads(args.reservation.read_text())
|
||||
assert receipt["state"] == "reserved" and receipt["owner_id"].startswith("airun-")
|
||||
assert not (args.root / "state/active.json").exists(), "A rover run is active"
|
||||
assert 0 <= (datetime.now(UTC) - datetime.fromisoformat(receipt["utc"])).total_seconds() < 900
|
||||
adapter = Path(__file__).parent.resolve()
|
||||
descriptor = json.loads((adapter / "model.json").read_text())
|
||||
assets = args.root / "assets" / descriptor["asset_directory"] / descriptor["revision"]
|
||||
assert (assets / "installation.json").is_file()
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
identity = None
|
||||
begin = time.monotonic()
|
||||
try:
|
||||
identity = subprocess.check_output([
|
||||
"docker", "run", "-d", "--name", "ndc-clipseg-qualification-" + receipt["owner_id"][-8:],
|
||||
"--gpus", "all", "--cpus", "3", "--memory", "6g",
|
||||
"--label", "com.nodedc.product=mission-core", "--label", "com.nodedc.stack=ai-polygon-qualification",
|
||||
"--label", "com.nodedc.role=qualification", "--label", "com.nodedc.managed-by=ai-polygon-qualification",
|
||||
"--mount", f"type=bind,source={adapter},target=/adapter,readonly",
|
||||
"--mount", f"type=bind,source={assets},target=/assets,readonly",
|
||||
"--mount", f"type=bind,source={args.inputs.resolve()},target=/inputs,readonly",
|
||||
"--mount", f"type=bind,source={args.output.resolve()},target=/evidence",
|
||||
"--entrypoint", "/opt/conda/envs/goose/bin/python",
|
||||
"sha256:f37681beb9feecee991e71a60a68259f15b56b168c939db3c3cb259c322e9536",
|
||||
"-B", "/adapter/qualify.py",
|
||||
], text=True).strip()
|
||||
result = subprocess.check_output(["docker", "wait", identity], timeout=240, text=True).strip()
|
||||
logs = subprocess.check_output(["docker", "logs", identity], stderr=subprocess.STDOUT, text=True)
|
||||
(args.output / "execution.log").write_text(logs)
|
||||
print(logs[-14000:])
|
||||
assert result == "0", "Model qualification failed: exit " + result
|
||||
finally:
|
||||
released = identity is None or subprocess.run(["docker", "rm", "-f", identity], capture_output=True).returncode == 0
|
||||
(args.output / "cleanup.json").write_text(json.dumps(dict(
|
||||
owner_id=receipt["owner_id"], released=released, utc=datetime.now(UTC).isoformat(),
|
||||
elapsed_seconds=time.monotonic() - begin)))
|
||||
assert released
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,5 +1,28 @@
|
||||
name: ndc-ai-polygon-models
|
||||
services:
|
||||
sam3:
|
||||
image: sha256:727ff5ab1a9eec1704ec15f9bef1b4ae5c47912aa9e1eff622f90a1dc3045cff
|
||||
pull_policy: never
|
||||
container_name: ndc-ai-polygon-sam3
|
||||
restart: "no"
|
||||
gpus: all
|
||||
cpus: 3
|
||||
mem_limit: 12g
|
||||
ports: ["127.0.0.1:18091:8010"]
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ../..
|
||||
target: /adapter
|
||||
read_only: true
|
||||
- type: bind
|
||||
source: D:/NDC_MISSIONCORE/runtime/simulation/assets/sam3-litetext-s1/85b05896928f974e308f889d7ccb2eefc069de98
|
||||
target: /assets
|
||||
read_only: true
|
||||
labels:
|
||||
com.nodedc.product: mission-core
|
||||
com.nodedc.stack: ai-polygon
|
||||
com.nodedc.role: segmentation
|
||||
com.nodedc.managed-by: ai-polygon-worker
|
||||
segformer:
|
||||
image: sha256:f37681beb9feecee991e71a60a68259f15b56b168c939db3c3cb259c322e9536
|
||||
pull_policy: never
|
||||
@@ -23,6 +46,55 @@ services:
|
||||
com.nodedc.stack: ai-polygon
|
||||
com.nodedc.role: segmentation
|
||||
com.nodedc.managed-by: ai-polygon-worker
|
||||
cityscapes:
|
||||
image: sha256:f37681beb9feecee991e71a60a68259f15b56b168c939db3c3cb259c322e9536
|
||||
pull_policy: never
|
||||
container_name: ndc-ai-polygon-cityscapes
|
||||
environment:
|
||||
MISSIONCORE_SEGFORMER_PROFILE: cityscapes
|
||||
restart: "no"
|
||||
gpus: all
|
||||
cpus: 3
|
||||
mem_limit: 4g
|
||||
ports: ["127.0.0.1:18091:8010"]
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ./segformer
|
||||
target: /adapter/segformer
|
||||
read_only: true
|
||||
- type: bind
|
||||
source: D:/NDC_MISSIONCORE/runtime/simulation/assets/segformer-b2-cityscapes/d633b2072669ca68d8f8e309de9b52bfdbf6bf72
|
||||
target: /assets
|
||||
read_only: true
|
||||
labels:
|
||||
com.nodedc.product: mission-core
|
||||
com.nodedc.stack: ai-polygon
|
||||
com.nodedc.role: segmentation
|
||||
com.nodedc.managed-by: ai-polygon-worker
|
||||
mapillary:
|
||||
image: sha256:f37681beb9feecee991e71a60a68259f15b56b168c939db3c3cb259c322e9536
|
||||
pull_policy: never
|
||||
container_name: ndc-ai-polygon-mapillary
|
||||
entrypoint: ["/opt/conda/envs/goose/bin/python", "-B", "/adapter/mapillary/server.py"]
|
||||
restart: "no"
|
||||
gpus: all
|
||||
cpus: 3
|
||||
mem_limit: 6g
|
||||
ports: ["127.0.0.1:18091:8010"]
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ./mapillary
|
||||
target: /adapter/mapillary
|
||||
read_only: true
|
||||
- type: bind
|
||||
source: D:/NDC_MISSIONCORE/runtime/simulation/assets/mask2former-mapillary/2cc022513f0012ff47d4438516284fd0946a196a
|
||||
target: /assets
|
||||
read_only: true
|
||||
labels:
|
||||
com.nodedc.product: mission-core
|
||||
com.nodedc.stack: ai-polygon
|
||||
com.nodedc.role: segmentation
|
||||
com.nodedc.managed-by: ai-polygon-worker
|
||||
ddrnet:
|
||||
image: sha256:a3b7d22f5d3bfdf2d84444b936c8b01abf8243be652387d7e2024ba7bda587f5
|
||||
pull_policy: never
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
"""Independent camera and range stages of the installed composition.
|
||||
|
||||
Neural results carry capture-pose/time and are projected once at that pose.
|
||||
Navigation consumes the latest range packet and the observed semantic map.
|
||||
Neither camera sector selection nor preview publication drives the controller.
|
||||
"""
|
||||
|
||||
import math
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
|
||||
from navigation_client import ComposedInference, permitted_surface, project
|
||||
from urban_crossing import MarkedCrossing
|
||||
from k1link.simulation.ai_polygon.camera_optics import axes
|
||||
from k1link.simulation.ai_polygon.source_projection import source_for_rig
|
||||
|
||||
|
||||
class ContinuousComposition(ComposedInference):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.camera_source = source_for_rig(self.inputs["sensors"])
|
||||
self.supplement_yaw = None
|
||||
self.recovery_view_request = None
|
||||
self.recovery_detection_view = None
|
||||
self.last_supplement = -math.inf
|
||||
self.crossing = MarkedCrossing(self.geometry)
|
||||
|
||||
def reset(self):
|
||||
super().reset()
|
||||
self.crossing = MarkedCrossing(self.geometry)
|
||||
self.recovery_view_request = None
|
||||
self.recovery_detection_view = None
|
||||
|
||||
def perceive_view(self, observation, frame_id, yaw, *, pitch=-20, detect=True):
|
||||
started = time.monotonic()
|
||||
selected = axes(yaw, pitch)
|
||||
calibration = dict(observation["calibration"])
|
||||
body_axes = np.asarray(calibration["lens_axes"])[0] @ self.optics.lens_axes[0].T
|
||||
calibration.update(
|
||||
rotation=(body_axes @ selected).reshape(-1).tolist(),
|
||||
projection="dual-origin-rectilinear/v1", captured_at=observation["captured_at"],
|
||||
view_role="task" if yaw == 0 and pitch == -20 else "supplement",
|
||||
view_yaw_degrees=yaw, view_pitch_degrees=pitch,
|
||||
)
|
||||
sources = observation["camera_sources"]
|
||||
rgb, valid = self.optics.rectify_forward(
|
||||
[sources["insta360_left"], sources["insta360_right"]], selected,
|
||||
[800, 600], calibration["intrinsics"],
|
||||
)
|
||||
view = {**observation, "calibration": calibration, "camera_valid": valid,
|
||||
"inference_rgb": rgb, "rectified_body_axes": selected}
|
||||
|
||||
def timed(call):
|
||||
begin = time.monotonic()
|
||||
result = call(rgb)
|
||||
return result, (time.monotonic() - begin) * 1000
|
||||
|
||||
segmentation = self.pool.submit(timed, self.models.surface)
|
||||
detection = self.pool.submit(timed, self.models.detect_observations) if detect else None
|
||||
values, segment_ms = segmentation.result()
|
||||
objects, detector_ms = detection.result() if detection else ([], 0.0)
|
||||
boxes = [tuple(item["box"]) for item in objects]
|
||||
values = {**values, "detection.boxes": boxes, "detection.objects": objects,
|
||||
"source.lidar": observation["points"], "source.pose": observation["pose"]}
|
||||
self.camera_source.lens_depths = observation["lens_depths"]
|
||||
points = observation["points"]
|
||||
_, u, v, visible = project(points, calibration, self.camera_source)
|
||||
indices = self.camera_source.indices(u[visible], v[visible])
|
||||
crossing_mask=np.zeros((512,512),dtype=bool)
|
||||
crossing={"state":"disabled","admitted":False}
|
||||
if self.environment == "urban" and self.segmenter_id == "simulation-sam3-surfaces":
|
||||
crossing_mask,crossing=self.crossing.observe(values["segmentation.labels"],
|
||||
points[visible],indices,observation["pose"],observation["captured_at"],
|
||||
advance=(yaw == 0 and pitch == -20))
|
||||
values["source.crossing-mask"]=crossing_mask
|
||||
values["source.crossing-admission"]=crossing
|
||||
permitted = permitted_surface(values["segmentation.labels"],
|
||||
values["segmentation.surface"], self.environment,
|
||||
self.segmenter_id, self.models.labels)
|
||||
permissions = permitted_surface(values["segmentation.labels"],
|
||||
np.ones_like(permitted, dtype=bool), self.environment,
|
||||
self.segmenter_id, self.models.labels)
|
||||
permissions |= crossing_mask
|
||||
permitted |= crossing_mask & values["segmentation.surface"]
|
||||
values["navigation.surface"] = permitted
|
||||
allowed = permissions[indices]
|
||||
known = values["segmentation.known"][indices] & (permitted[indices] | ~allowed)
|
||||
known &= self.camera_source.semantic_pixels(u[visible], v[visible])
|
||||
sample = {
|
||||
"samples": np.column_stack((points[visible][known], allowed[known].astype(int))).tolist(),
|
||||
"captured_at": observation["captured_at"], "pose": observation["pose"],
|
||||
"frame_id": f"{frame_id}:{yaw}:{pitch}", "capture_id": str(frame_id),
|
||||
}
|
||||
return dict(rgb=rgb, values=values, observation=view, frame_id=frame_id,
|
||||
samples=sample, completed_at=time.monotonic(),
|
||||
processing_ms=(time.monotonic() - started) * 1000,
|
||||
module_ms={self.segmenter_id: segment_ms, "simulation-rf-detr": detector_ms})
|
||||
|
||||
def perceive(self, observation, frame_id):
|
||||
request = getattr(self, "recovery_view_request", None)
|
||||
front = self.perceive_view(observation, frame_id, 0)
|
||||
front["semantic_observations"] = [front["samples"]]
|
||||
front["detection_views"] = [front.copy()]
|
||||
yaw = request["yaw_degrees"] if request else self.supplement_yaw
|
||||
if request and yaw == 0:
|
||||
front["recovery_view"] = request
|
||||
yaw = None
|
||||
changed = request and request != getattr(self, "last_recovery_view_request", None)
|
||||
if yaw is not None and (changed or time.monotonic() - self.last_supplement >= 1):
|
||||
# One bounded supplementary crop, never a full panorama inference.
|
||||
# Keep the same perspective distribution as the task view. A
|
||||
# down-looking crop requires separate model qualification.
|
||||
self.last_supplement = time.monotonic()
|
||||
self.last_recovery_view_request = request
|
||||
extra = self.perceive_view(observation, frame_id, yaw, detect=bool(request))
|
||||
front["semantic_observations"].append(extra["samples"])
|
||||
front["supplement"] = extra
|
||||
if request:
|
||||
self.recovery_detection_view = extra
|
||||
front["recovery_view"] = request
|
||||
extra = getattr(self, "recovery_detection_view", None)
|
||||
if extra and time.monotonic()-extra["observation"]["captured_at"] <= 2:
|
||||
front["detection_views"].append(extra)
|
||||
return front
|
||||
|
||||
def navigate_latest(self, observation, perception, observation_id):
|
||||
camera = perception["observation"]
|
||||
recovery = self.mission.recovery
|
||||
recovery.observe_view(perception.get("recovery_view"), camera["pose"],
|
||||
camera["simulation_time_ns"] / 1e9)
|
||||
self.source.lens_depths = camera["lens_depths"]
|
||||
values = {
|
||||
**self.static_values, **perception["values"],
|
||||
"source.execution-inputs": self.inputs,
|
||||
"source.camera.rgb": perception["rgb"],
|
||||
"source.camera.calibration": camera["calibration"],
|
||||
"source.lidar": observation["points"],
|
||||
"source.range-rays": observation.get("range_rays", {}),
|
||||
"source.pose": observation["pose"],
|
||||
"source.simulation-time": observation["simulation_time_ns"] / 1e9,
|
||||
"source.semantic-observation": perception["semantic_observations"],
|
||||
"source.detection-views": [
|
||||
dict(calibration=view["observation"]["calibration"],
|
||||
boxes=view["values"]["detection.boxes"],
|
||||
objects=view["values"].get("detection.objects", []),
|
||||
surface=view["values"]["navigation.surface"])
|
||||
for view in perception["detection_views"]
|
||||
],
|
||||
"source.range-captured-at": observation["captured_at"],
|
||||
"source.observation-id": observation_id,
|
||||
}
|
||||
started, cpu_started = time.monotonic(), time.thread_time()
|
||||
values.update(self.plan_mission(values))
|
||||
mission_ms = (time.monotonic() - started) * 1000
|
||||
mission_cpu_ms = (time.thread_time() - cpu_started) * 1000
|
||||
started, cpu_started = time.monotonic(), time.thread_time()
|
||||
values.update(self.navigate(values))
|
||||
navigation_ms = (time.monotonic() - started) * 1000
|
||||
navigation_cpu_ms = (time.thread_time() - cpu_started) * 1000
|
||||
target = getattr(self.mission, "perception_target", self.mission.orientation_target)()
|
||||
self.supplement_yaw = None
|
||||
self.recovery_view_request = recovery.view_request(
|
||||
observation["pose"], observation["simulation_time_ns"] / 1e9) if recovery.active else None
|
||||
if target is not None:
|
||||
pose = observation["pose"]
|
||||
qx, qy, qz, qw = pose[3:]
|
||||
heading = math.atan2(2 * (qw*qz + qx*qy), 1 - 2 * (qy*qy + qz*qz))
|
||||
delta = np.asarray(target["xy"]) - pose[:2]
|
||||
yaw = math.atan2(delta[1], delta[0]) - heading
|
||||
yaw = math.degrees(math.atan2(math.sin(yaw), math.cos(yaw)))
|
||||
if abs(yaw) > 45:
|
||||
self.supplement_yaw = round(yaw / 90) * 90
|
||||
return values["motion.command"], {
|
||||
**self.navigation_evidence, "goal": self.goal, "path": values["motion.path"],
|
||||
"composition_sha256": self.graph.sha256,
|
||||
"module_ms": {**perception["module_ms"], "simulation-waypoint-mission": mission_ms,
|
||||
next(node.module.module_id for node in self.graph.nodes
|
||||
if node.module.group == "motion"): navigation_ms},
|
||||
"module_thread_ms": {"mission": mission_cpu_ms, "navigation": navigation_cpu_ms},
|
||||
"perception_frame_id": perception["frame_id"],
|
||||
"perception_captured_at": camera["captured_at"],
|
||||
"range_points": len(observation["points"]),
|
||||
"spatial_goal": self.observed_goals.evidence,
|
||||
"crossing": values.get("source.crossing-admission"),
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
"""Bounded multi-rate perception, navigation and live-odometry control.
|
||||
|
||||
One latest camera slot, one latest range slot, one latest pose slot. Slow image
|
||||
inference/evidence cannot serialize the controller. All epochs fence pause and
|
||||
resume, and each stage records the original observation identity and age.
|
||||
"""
|
||||
|
||||
import json
|
||||
import http.client
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
from navigation_client import NavigationClient
|
||||
from realtime_ai import EvidenceWriter
|
||||
|
||||
|
||||
class ContinuousPipeline:
|
||||
def __init__(self, factory, directory, clock=time.monotonic):
|
||||
self.factory, self.directory, self.clock = factory, Path(directory), clock
|
||||
self.condition = threading.Condition()
|
||||
self.enabled = self.closed = self.ready = self.ever_ready = False
|
||||
self.epoch = self.count = self.dropped = 0
|
||||
self.result = self.error = self.sensor = self.perception = self.pose = self.control = None
|
||||
self.failure = None
|
||||
self.intent_revision = 0
|
||||
self.intent_key = None
|
||||
self.perception_revision = 0
|
||||
self.model = None
|
||||
self.route_guard = None
|
||||
self.writer_closed = False
|
||||
self.threads = []
|
||||
self.model_ready = threading.Event()
|
||||
self.mission_lock = threading.Lock()
|
||||
|
||||
def start(self):
|
||||
self.directory.mkdir(parents=True, exist_ok=True)
|
||||
self.writer = EvidenceWriter(self.fail)
|
||||
for name, run in (("perception", self.perceive), ("navigation", self.navigate),
|
||||
("control", self.control_loop)):
|
||||
def guarded(run=run, name=name):
|
||||
try:
|
||||
run()
|
||||
except Exception as exc:
|
||||
self.fail(name, exc)
|
||||
thread = threading.Thread(target=guarded, name="continuous-"+name, daemon=True)
|
||||
thread.start()
|
||||
self.threads.append(thread)
|
||||
|
||||
def fail(self, frame, exc):
|
||||
with self.condition:
|
||||
if self.failure is None:
|
||||
self.failure = dict(stage=frame if isinstance(frame, str) else "evidence",
|
||||
frame_id=frame if isinstance(frame, int) else None,
|
||||
type=type(exc).__name__, message=str(exc), monotonic=self.clock())
|
||||
self.error = self.failure["type"]
|
||||
self.ready = False
|
||||
self.control = None
|
||||
self.condition.notify_all()
|
||||
try:
|
||||
with (self.directory / "errors.jsonl").open("a") as stream:
|
||||
stream.write(json.dumps(dict(frame=frame, error=str(exc),
|
||||
traceback=traceback.format_exc(), monotonic=self.clock()))+"\n")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def terminal_failure(self):
|
||||
with self.condition:
|
||||
return None if self.failure is None else dict(self.failure)
|
||||
|
||||
def enable(self, enabled, *, epoch=None):
|
||||
with self.condition:
|
||||
if epoch is not None and (type(epoch) is not int or epoch < self.epoch):
|
||||
raise ValueError("Invalid pipeline epoch")
|
||||
if enabled != self.enabled or (epoch is not None and epoch != self.epoch):
|
||||
self.enabled = enabled
|
||||
self.epoch = self.epoch + 1 if epoch is None else epoch
|
||||
self.sensor = self.perception = self.result = self.control = None
|
||||
self.ready = False
|
||||
self.intent_key = None
|
||||
self.intent_revision += 1
|
||||
self.condition.notify_all()
|
||||
|
||||
def submit(self, rgb, frame_id, captured_at, simulation_time_ns, observation=None):
|
||||
with self.condition:
|
||||
if not self.enabled or self.closed or self.error:
|
||||
return
|
||||
self.sensor = (self.epoch, frame_id, {**observation, "captured_at": captured_at,
|
||||
"simulation_time_ns": simulation_time_ns})
|
||||
self.condition.notify_all()
|
||||
|
||||
def observe_pose(self, pose, speed, captured_at, *, measured_twist=None):
|
||||
# Called from the physics callback: only an in-memory bounded publish.
|
||||
if measured_twist is not None and (len(measured_twist) != 3 or
|
||||
not all(math.isfinite(value) for value in measured_twist)):
|
||||
raise ValueError('Invalid measured planar twist')
|
||||
with self.condition:
|
||||
self.pose = (list(pose), float(speed), captured_at)
|
||||
self.pose_twist = None if measured_twist is None else (tuple(measured_twist), captured_at)
|
||||
|
||||
def current(self, epoch):
|
||||
return not self.closed and self.enabled and self.epoch == epoch and not self.error
|
||||
|
||||
@staticmethod
|
||||
def mission_intent_key(record):
|
||||
"""Fence task changes without treating each sensor refresh as a new task."""
|
||||
mission = record.get("mission") or {}
|
||||
recovery = mission.get("recovery") or {}
|
||||
selected = recovery.get("selected") or {}
|
||||
request = recovery.get("request") or {}
|
||||
key = {name: mission.get(name) for name in (
|
||||
"global_route_sha256", "active_route_sha256", "route_revision",
|
||||
"route_segment", "waypoint", "recovery_attempt", "state")}
|
||||
key["recovery"] = dict(phase=recovery.get("phase"), option=recovery.get("option"),
|
||||
request_key=request.get("key"),
|
||||
selected={name: selected.get(name) for name in ("goal", "reverse", "kind")})
|
||||
key["motion_enabled"] = record["decision"]["reason"] in {"road", "replanning"}
|
||||
return json.dumps(key, sort_keys=True, separators=(",", ":"), allow_nan=False)
|
||||
|
||||
def publish_navigation(self, epoch, record, guard):
|
||||
key = self.mission_intent_key(record)
|
||||
with self.condition:
|
||||
if not self.current(epoch):
|
||||
return None
|
||||
if key != self.intent_key:
|
||||
self.intent_key = key
|
||||
self.intent_revision += 1
|
||||
self.control = None
|
||||
record = {**record, "intent_revision": self.intent_revision}
|
||||
self.result, self.route_guard = record, guard
|
||||
self.count += 1
|
||||
self.ready = self.ever_ready = True
|
||||
self.condition.notify_all()
|
||||
return record
|
||||
|
||||
def wait_sensor(self, previous):
|
||||
with self.condition:
|
||||
self.condition.wait_for(lambda: self.closed or self.error or
|
||||
(self.enabled and self.sensor is not None and self.sensor[:2] != previous))
|
||||
return None if self.closed or self.error else self.sensor
|
||||
|
||||
def wait_navigation(self, previous):
|
||||
"""A completed neural result can update an unchanged range sample."""
|
||||
with self.condition:
|
||||
def available():
|
||||
return (self.enabled and self.sensor is not None and self.perception is not None
|
||||
and self.sensor[0] == self.perception[0] == self.epoch
|
||||
and (*self.sensor[:2], self.perception_revision) != previous)
|
||||
self.condition.wait_for(lambda: self.closed or self.error or available())
|
||||
if self.closed or self.error:
|
||||
return None
|
||||
return ((*self.sensor[:2], self.perception_revision), self.sensor, self.perception)
|
||||
|
||||
def perceive(self):
|
||||
# The first sensor packet is admitted only after the worker's complete
|
||||
# model-stack readiness barrier. Do not race startup on a partial stack.
|
||||
if self.wait_sensor(None) is None:
|
||||
return
|
||||
self.model = self.factory()
|
||||
self.model.ready()
|
||||
self.model_ready.set()
|
||||
previous = None
|
||||
with (self.directory / "perception.jsonl").open("a") as journal:
|
||||
while (packet := self.wait_sensor(previous)) is not None:
|
||||
epoch, frame, observation = packet
|
||||
if previous and previous[0] == epoch:
|
||||
self.dropped += max(0, frame-previous[1]-1)
|
||||
previous = packet[:2]
|
||||
started = self.clock()
|
||||
result = self.model.perceive(observation, frame)
|
||||
with self.condition:
|
||||
if not self.current(epoch):
|
||||
continue
|
||||
self.perception = (epoch, result)
|
||||
self.perception_revision += 1
|
||||
self.condition.notify_all()
|
||||
|
||||
def archive(result=result, observation=observation, frame=frame, started=started):
|
||||
now = self.clock()
|
||||
self.model.archive_observation((result["rgb"], result["values"],
|
||||
result["observation"], frame))
|
||||
from PIL import Image
|
||||
Image.fromarray(result["rgb"]).save(self.directory/f"{frame:08d}.jpg", quality=90)
|
||||
extra = result.get("supplement")
|
||||
if extra is not None:
|
||||
Image.fromarray(extra["rgb"]).save(
|
||||
self.directory/f"{frame:08d}.supplement.jpg", quality=90)
|
||||
journal.write(json.dumps(dict(frame_id=frame, captured_at=observation["captured_at"],
|
||||
completed_at=result["completed_at"], started_at=started,
|
||||
module_ms=result["module_ms"], semantic_observations=result["semantic_observations"],
|
||||
detection_views=[dict(captured_at=view["observation"]["captured_at"],
|
||||
frame_id=view["samples"]["frame_id"],
|
||||
objects=view["values"].get("detection.objects", []))
|
||||
for view in result.get("detection_views", [])],
|
||||
sensor_timing_ms=observation.get("sensor_timing_ms"),
|
||||
acquisition_age_ms=(started-observation["captured_at"])*1000,
|
||||
archive_ms=(self.clock()-now)*1000, view="body-forward"))+"\n")
|
||||
journal.flush()
|
||||
self.writer.submit(frame, archive)
|
||||
# The writer owns this stream until the final outstanding packet.
|
||||
self.writer.close()
|
||||
self.writer_closed = True
|
||||
|
||||
def await_model(self):
|
||||
while not self.closed and not self.error:
|
||||
if self.model_ready.wait(0.1):
|
||||
return True
|
||||
return False
|
||||
|
||||
def navigate(self):
|
||||
if not self.await_model():
|
||||
return
|
||||
previous = None
|
||||
active_epoch = None
|
||||
with (self.directory / "decisions.jsonl").open("a") as journal:
|
||||
while (snapshot := self.wait_navigation(previous)) is not None:
|
||||
signature, packet, perception = snapshot
|
||||
epoch, frame, observation = packet
|
||||
previous = signature
|
||||
with self.mission_lock:
|
||||
if active_epoch is not None and active_epoch != epoch:
|
||||
self.model.reset()
|
||||
active_epoch = epoch
|
||||
started = self.clock()
|
||||
identifier = f"{epoch}:{frame}:{signature[2]}"
|
||||
decision, evidence = self.model.navigate_latest(observation, perception[1], identifier)
|
||||
guard = None
|
||||
if hasattr(self.model.mission, "motion_corridors"):
|
||||
from k1link.simulation.ai_polygon.corridor_control import CorridorControl
|
||||
guard = CorridorControl(self.model.mission.motion_corridors(),
|
||||
self.model.mission.global_route["no_go"])
|
||||
completed = self.clock()
|
||||
record = dict(frame_id=frame, observation_id=identifier, captured_at=observation["captured_at"],
|
||||
completed_at=completed, started_at=started, simulation_time_ns=observation["simulation_time_ns"],
|
||||
inference_ms=perception[1].get("processing_ms", 0.0),
|
||||
navigation_ms=(completed-started)*1000, decision=decision, **evidence)
|
||||
record = self.publish_navigation(epoch, record, guard)
|
||||
if record is None:
|
||||
continue
|
||||
journal.write(json.dumps(record, allow_nan=False)+"\n")
|
||||
journal.flush()
|
||||
|
||||
def control_loop(self):
|
||||
if not self.await_model():
|
||||
return
|
||||
connection = NavigationClient()
|
||||
connection_epoch = None
|
||||
delivered_range = None
|
||||
try:
|
||||
with (self.directory / "controller.jsonl").open("a") as journal:
|
||||
while not self.closed and not self.error:
|
||||
started = self.clock()
|
||||
with self.condition:
|
||||
epoch, pose, result, perception = self.epoch, self.pose, self.result, self.perception
|
||||
guard = self.route_guard
|
||||
sensor = self.sensor
|
||||
measured_twist = getattr(self, 'pose_twist', None)
|
||||
enabled = self.enabled and self.ready
|
||||
intent_revision = self.intent_revision
|
||||
if connection_epoch != epoch:
|
||||
connection.close()
|
||||
connection = NavigationClient()
|
||||
connection_epoch = epoch
|
||||
delivered_range = None
|
||||
if pose is not None and result is not None and perception is not None and enabled:
|
||||
payload = dict(execution_inputs_sha256=self.model.inputs["sha256"],
|
||||
pose=pose[0], speed_mps=pose[1], pose_age_seconds=max(0, started-pose[2]),
|
||||
perception_age_seconds=max(0, started-perception[1]["observation"]["captured_at"]),
|
||||
observation_id=result["observation_id"],
|
||||
enabled=result["decision"]["reason"] in {"road", "replanning"})
|
||||
if measured_twist is not None and measured_twist[1] == pose[2]:
|
||||
payload['measured_twist'] = list(measured_twist[0])
|
||||
range_identity = sensor[:2] if sensor is not None else None
|
||||
if sensor is not None and sensor[0] == epoch and range_identity != delivered_range:
|
||||
payload["range_observation"] = {
|
||||
"range_sequence": list(range_identity),
|
||||
"geometry_age_seconds": max(0, started-sensor[2]["captured_at"]),
|
||||
"points": sensor[2]["points"].tolist(),
|
||||
}
|
||||
try:
|
||||
response = connection.request("/control", payload)
|
||||
if "range_observation" in payload:
|
||||
delivered_range = range_identity
|
||||
except (OSError, http.client.HTTPException) as exc:
|
||||
# A reset replaces the native service and closes
|
||||
# keep-alive sockets. Drop authority before reconnect;
|
||||
# never replay a command or renew its observation age.
|
||||
with self.condition:
|
||||
self.control = None
|
||||
connection.close()
|
||||
connection = NavigationClient()
|
||||
delivered_range = None
|
||||
journal.write(json.dumps(dict(started_at=started,
|
||||
completed_at=self.clock(), reason="control-transport-error",
|
||||
error=type(exc).__name__, speed_mps=0, yaw_rate_rps=0))+"\n")
|
||||
journal.flush()
|
||||
with self.condition:
|
||||
self.condition.wait(timeout=.05)
|
||||
continue
|
||||
# Corridor policy still owns its full-body veto at the
|
||||
# live pose. A route revision cannot reuse old authority.
|
||||
if guard is not None and response["reason"] == "none":
|
||||
v, w, scale = guard.regulate_command(pose[0],
|
||||
self.model.route_monitor, response["speed_mps"], response["yaw_rate_rps"])
|
||||
response.update(speed_mps=v, yaw_rate_rps=w)
|
||||
if scale == 0:
|
||||
response["reason"] = "route-corridor"
|
||||
completed = self.clock()
|
||||
if response["reason"] == "none" and (
|
||||
response.get("observation_id") != result["observation_id"]
|
||||
or not all(math.isfinite(response[key])
|
||||
for key in ("speed_mps", "yaw_rate_rps"))):
|
||||
raise ValueError("Controller reply does not match its observation")
|
||||
# All deadlines stay in the capture host's monotonic
|
||||
# clock. Transport/server work consumes the original
|
||||
# budget; receiving a reply never renews old evidence.
|
||||
expires_at = min(started + .25, pose[2] + .5,
|
||||
perception[1]["observation"]["captured_at"] + 2.,
|
||||
sensor[2]["captured_at"] + .8 if sensor else started,
|
||||
result["captured_at"] + .8)
|
||||
with self.condition:
|
||||
if self.current(epoch) and self.intent_revision == intent_revision:
|
||||
self.control = (completed, pose[2], response, expires_at,
|
||||
intent_revision)
|
||||
self.condition.notify_all()
|
||||
journal.write(json.dumps({"started_at":started, "completed_at":completed,
|
||||
"observation_id":result["observation_id"],
|
||||
"expires_at":expires_at,
|
||||
"freshness_deadlines":dict(command=started+.25, pose=pose[2]+.5,
|
||||
perception=perception[1]["observation"]["captured_at"]+2.,
|
||||
range=sensor[2]["captured_at"]+.8 if sensor else started,
|
||||
plan=result["captured_at"]+.8),
|
||||
**response})+"\n")
|
||||
journal.flush()
|
||||
with self.condition:
|
||||
self.condition.wait(timeout=max(0.001, 0.05-(self.clock()-started)))
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def command(self, now, **_):
|
||||
with self.condition:
|
||||
result, command = self.result, self.control
|
||||
if self.closed or not self.enabled:
|
||||
return 0.0, 0.0, "paused", result
|
||||
if self.error:
|
||||
return 0.0, 0.0, "inference-error", result
|
||||
if result is not None and result["decision"]["reason"] not in {"road", "replanning"}:
|
||||
return 0.0, 0.0, "control-blocked", result
|
||||
if command is None or now-command[0] > 0.25:
|
||||
return 0.0, 0.0, "stale-command", result
|
||||
_, pose_at, response, expires_at, intent_revision = command
|
||||
if intent_revision != self.intent_revision or now >= expires_at:
|
||||
return 0.0, 0.0, "stale-command", result
|
||||
if result is not None:
|
||||
result = {**result, "control_completed_at": command[0]}
|
||||
if now-pose_at > 0.5:
|
||||
return 0.0, 0.0, "stale-pose", result
|
||||
reason = response["reason"]
|
||||
if reason != "none":
|
||||
reason = reason if reason in {"stale-range", "stale-pose", "stale-perception"} else "control-blocked"
|
||||
return 0.0, 0.0, reason, result
|
||||
return response["speed_mps"], response["yaw_rate_rps"], "none", result
|
||||
|
||||
def apply_command(self, apply_target, *, shape=None, stop=False):
|
||||
"""Consume the current command and set the actuator under one intent lock.
|
||||
|
||||
The callbacks are bounded local arithmetic / target assignment only.
|
||||
Physics integration and I/O stay outside. Record only successful writes;
|
||||
the record is an applied target, not measured motion or certification.
|
||||
"""
|
||||
with self.condition:
|
||||
checked_at = self.clock()
|
||||
source = self.control
|
||||
command = self.command(checked_at)
|
||||
velocity, angular, reason, decision = command
|
||||
if stop:
|
||||
velocity = angular = 0.0
|
||||
reason = "control-blocked" if reason == "none" else reason
|
||||
if shape is not None:
|
||||
velocity, angular = shape(velocity, angular, reason)
|
||||
# Shaping and lock wait consume the original lease as well.
|
||||
if reason == "none" and self.command(self.clock())[:3] != command[:3]:
|
||||
velocity = angular = 0.0
|
||||
reason = "stale-command"
|
||||
if shape is not None:
|
||||
velocity, angular = shape(0.0, 0.0, reason)
|
||||
apply_target(velocity, angular)
|
||||
self.applied_target = dict(intent_revision=self.intent_revision,
|
||||
applied_at=self.clock(), speed_mps=velocity, yaw_rate_rps=angular,
|
||||
reason=reason, checked_at=checked_at,
|
||||
control_completed_at=source[0] if source is not None else None,
|
||||
expires_at=source[3] if source is not None else None,
|
||||
observation_id=source[2].get('observation_id') if source is not None else None)
|
||||
return velocity, angular, reason, decision
|
||||
|
||||
def close(self):
|
||||
with self.condition:
|
||||
self.closed = True
|
||||
self.condition.notify_all()
|
||||
for thread in self.threads:
|
||||
thread.join(timeout=15)
|
||||
if any(thread.is_alive() for thread in self.threads):
|
||||
raise RuntimeError("Continuous stage did not stop")
|
||||
if not self.writer_closed:
|
||||
self.writer.close()
|
||||
if self.model is not None:
|
||||
self.model.close()
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Frozen synthetic control matrix and independent measurements (no Isaac imports)."""
|
||||
|
||||
import math
|
||||
|
||||
SCHEMA = "missioncore.control-matrix/v1"
|
||||
DT = 1 / 60
|
||||
PHASES = (
|
||||
("hold", 2, 0, 0),
|
||||
("straight", 4, 1, 0),
|
||||
("left-arc", 4, 1, 0.2),
|
||||
("release-left", 2, 1, 0),
|
||||
("right-arc", 4, 1, -0.2),
|
||||
("release-right", 2, 1, 0),
|
||||
("stop", 3, 0, 0),
|
||||
("pivot-left", 12, 0, 0.35),
|
||||
("hold-left", 3, 0, 0),
|
||||
("pivot-right", 12, 0, -0.35),
|
||||
("hold-right", 3, 0, 0),
|
||||
("reverse", 3, -1, 0),
|
||||
("hold-reverse", 3, 0, 0),
|
||||
("resume", 3, 1, 0),
|
||||
("final-hold", 3, 0, 0),
|
||||
)
|
||||
CRITERIA = {
|
||||
"translation_fraction_min": 0.5,
|
||||
"turn_fraction_min": 0.45,
|
||||
"straight_heading_max_rad": 0.2,
|
||||
"pivot_displacement_max_m": 0.3,
|
||||
"settled_hold_speed_max_mps": 0.01,
|
||||
"settled_hold_drift_max_m": 0.01,
|
||||
"settled_after_s": 1.0,
|
||||
"stop_deadline_s": 1.0,
|
||||
"stop_speed_mps": 0.01,
|
||||
"stop_stable_seconds": 0.25,
|
||||
"arrival_radius_m": 0.4,
|
||||
}
|
||||
|
||||
|
||||
def specifications():
|
||||
return [
|
||||
dict(
|
||||
id=f"v{speed:.2f}-m{100 + payload}-mu{friction:.2f}",
|
||||
speed_mps=speed,
|
||||
payload_kg=payload,
|
||||
dynamic_friction=friction,
|
||||
static_friction=friction + 0.1,
|
||||
)
|
||||
for speed in (0.1, 0.2, 0.3)
|
||||
for payload in (0, 30)
|
||||
for friction in (0.8, 0.35)
|
||||
]
|
||||
|
||||
|
||||
def angle_delta(a, b):
|
||||
return math.atan2(math.sin(a - b), math.cos(a - b))
|
||||
|
||||
|
||||
def phase_metrics(rows, criterion=CRITERIA):
|
||||
first, last = rows[0], rows[-1]
|
||||
requested_v, requested_w = first["request"]
|
||||
distance = sum(r["distance_step_m"] for r in rows)
|
||||
origin = first.get("phase_origin", first["position"])
|
||||
displacement = max(math.dist(r["position"][:2], origin[:2]) for r in rows)
|
||||
turn = sum(r["turn_step_rad"] for r in rows)
|
||||
nominal_distance = sum(abs(r["nominal"][0]) * r["dt"] for r in rows)
|
||||
nominal_turn = sum(r["nominal"][1] * r["dt"] for r in rows)
|
||||
speeds = [math.hypot(*r["velocity"][:2]) for r in rows]
|
||||
tail = [r for r in rows if r["phase_seconds"] >= criterion["settled_after_s"]]
|
||||
drift = max(math.dist(r["position"][:2], tail[0]["position"][:2]) for r in tail)
|
||||
speed = max(math.hypot(*r["velocity"][:2]) for r in tail)
|
||||
checks = {}
|
||||
if requested_v:
|
||||
signed = sum(r["forward_mps"] * r["dt"] for r in rows)
|
||||
checks["translation"] = signed * math.copysign(1, requested_v) > (
|
||||
nominal_distance * criterion["translation_fraction_min"]
|
||||
)
|
||||
if requested_w:
|
||||
checks["turn"] = turn * math.copysign(1, requested_w) > (
|
||||
abs(nominal_turn) * criterion["turn_fraction_min"]
|
||||
)
|
||||
checks["continuous_arc"] = (
|
||||
min(r["forward_mps"] for r in rows if r["phase_seconds"] >= 1) > 0.01
|
||||
)
|
||||
else:
|
||||
checks["heading"] = abs(turn) < criterion["straight_heading_max_rad"]
|
||||
elif requested_w:
|
||||
checks["turn"] = turn * math.copysign(1, requested_w) > (
|
||||
abs(nominal_turn) * criterion["turn_fraction_min"]
|
||||
)
|
||||
checks["pivot_position"] = displacement < criterion["pivot_displacement_max_m"]
|
||||
else:
|
||||
checks["hold_speed"] = speed < criterion["settled_hold_speed_max_mps"]
|
||||
checks["hold_drift"] = drift < criterion["settled_hold_drift_max_m"]
|
||||
checks["held_belts"] = all(all(r["held_sides"]) for r in tail)
|
||||
stable_frames = round(criterion["stop_stable_seconds"] / first["dt"])
|
||||
stopped_at = next(
|
||||
(
|
||||
i
|
||||
for i in range(len(rows) - stable_frames + 1)
|
||||
if max(speeds[i : i + stable_frames]) < criterion["stop_speed_mps"]
|
||||
),
|
||||
None,
|
||||
)
|
||||
stopping_time = None if stopped_at is None else rows[stopped_at]["phase_seconds"]
|
||||
stopping_distance = (
|
||||
None if stopped_at is None else sum(r["distance_step_m"] for r in rows[: stopped_at + 1])
|
||||
)
|
||||
if not requested_v and not requested_w:
|
||||
checks["stop_deadline"] = (
|
||||
stopping_time is not None and stopping_time <= criterion["stop_deadline_s"]
|
||||
)
|
||||
cumulative = 0.0
|
||||
turning_times = {"90": None, "180": None}
|
||||
for r in rows:
|
||||
cumulative += r["turn_step_rad"]
|
||||
for degrees in turning_times:
|
||||
if turning_times[degrees] is None and abs(cumulative) >= math.radians(int(degrees)):
|
||||
turning_times[degrees] = r["phase_seconds"]
|
||||
return dict(
|
||||
phase=first["phase"],
|
||||
duration_s=last["phase_seconds"],
|
||||
request=first["request"],
|
||||
distance_m=distance,
|
||||
maximum_displacement_m=displacement,
|
||||
heading_change_rad=turn,
|
||||
nominal_distance_m=nominal_distance,
|
||||
nominal_turn_rad=nominal_turn,
|
||||
peak_speed_mps=max(speeds),
|
||||
mean_forward_mps=sum(r["forward_mps"] for r in rows) / len(rows),
|
||||
mean_yaw_rps=sum(r["yaw_rps"] for r in rows) / len(rows),
|
||||
peak_acceleration_mps2=max(abs(r["acceleration_mps2"]) for r in rows),
|
||||
settled_hold_drift_m=drift,
|
||||
settled_speed_mps=speed,
|
||||
stopping_time_s=stopping_time,
|
||||
stopping_distance_m=stopping_distance,
|
||||
turning_times_s=turning_times,
|
||||
checks=checks,
|
||||
passed=all(checks.values()),
|
||||
)
|
||||
|
||||
|
||||
def goal_body_supported(position, heading, target, geometry, support_xyxy):
|
||||
"""Independent rectangle fixture: arrival point AND whole body support.
|
||||
|
||||
Arrival radius bounds the reference point, not the entire 1.163 m body.
|
||||
Does not authorize planner motion or infer unobserved terrain.
|
||||
"""
|
||||
if math.dist(position[:2], target[:2]) > CRITERIA["arrival_radius_m"]:
|
||||
return False
|
||||
xmin, ymin, xmax, ymax = support_xyxy
|
||||
c, s = math.cos(heading), math.sin(heading)
|
||||
for x in (-geometry["length_m"] / 2, geometry["length_m"] / 2):
|
||||
for y in (-geometry["width_m"] / 2, geometry["width_m"] / 2):
|
||||
px, py = position[0] + c * x - s * y, position[1] + s * x + c * y
|
||||
if not (xmin <= px <= xmax and ymin <= py <= ymax):
|
||||
return False
|
||||
return True
|
||||
@@ -9,6 +9,15 @@ from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
PREFIX = "/api/v1/ai-polygon"
|
||||
ASSET_BLOCK_BYTES = 256 * 1024
|
||||
ASSET_READ_TIMEOUT_SECONDS = 5
|
||||
|
||||
|
||||
class CoreRequestRejected(RuntimeError):
|
||||
def __init__(self, status, detail):
|
||||
self.status = status
|
||||
self.detail = detail
|
||||
super().__init__("Core rejected simulation operation: " + str(status))
|
||||
|
||||
|
||||
class CoreClient:
|
||||
@@ -55,8 +64,14 @@ class CoreClient:
|
||||
)
|
||||
response = connection.getresponse()
|
||||
raw = response.read(4 * 1024**2 + 1)
|
||||
if response.status not in (200, 201) or len(raw) > 4 * 1024**2:
|
||||
raise RuntimeError("Core rejected simulation operation: " + str(response.status))
|
||||
if len(raw) > 4 * 1024**2:
|
||||
raise RuntimeError("Core response exceeds admitted size")
|
||||
if response.status not in (200, 201):
|
||||
try:
|
||||
detail = json.loads(raw).get("detail")
|
||||
except (ValueError, AttributeError):
|
||||
detail = None
|
||||
raise CoreRequestRejected(response.status, detail)
|
||||
self._connections.last_used = time.monotonic()
|
||||
return json.loads(raw)
|
||||
except Exception:
|
||||
@@ -65,18 +80,39 @@ class CoreClient:
|
||||
# Never retry an uncertain mutation automatically.
|
||||
raise
|
||||
|
||||
def download(self, world: dict, target: Path):
|
||||
def download(self, world: dict, target: Path, pulse=None):
|
||||
if pulse:
|
||||
pulse()
|
||||
if target.exists():
|
||||
digest = hashlib.sha256()
|
||||
with target.open("rb") as stream:
|
||||
if hashlib.file_digest(stream, "sha256").hexdigest() == world["sha256"]:
|
||||
while block := stream.read(ASSET_BLOCK_BYTES):
|
||||
digest.update(block)
|
||||
if pulse:
|
||||
pulse()
|
||||
if digest.hexdigest() == world["sha256"]:
|
||||
return
|
||||
if world.get("storage", {}).get("kind") == "worker":
|
||||
raise RuntimeError("The admitted Worker-local scene is missing or changed")
|
||||
connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30)
|
||||
self.download_asset(
|
||||
PREFIX + "/worlds/" + world["world_id"] + "/source.ply", world, target, pulse=pulse
|
||||
)
|
||||
|
||||
def download_asset(self, path: str, descriptor: dict, target: Path, pulse=None):
|
||||
if not path.startswith("/api/v1/") or ".." in path or "\\" in path:
|
||||
raise ValueError("Invalid Core asset path")
|
||||
world = descriptor
|
||||
connection = http.client.HTTPConnection(
|
||||
"127.0.0.1", self.port, timeout=ASSET_READ_TIMEOUT_SECONDS
|
||||
)
|
||||
temporary = target.with_suffix(".part")
|
||||
try:
|
||||
connection.request("GET", PREFIX + "/worlds/" + world["world_id"] + "/source.ply")
|
||||
if pulse:
|
||||
pulse()
|
||||
connection.request("GET", path)
|
||||
response = connection.getresponse()
|
||||
if pulse:
|
||||
pulse()
|
||||
if (
|
||||
response.status != 200
|
||||
or int(response.getheader("Content-Length") or 0) != world["byte_length"]
|
||||
@@ -84,7 +120,12 @@ class CoreClient:
|
||||
raise RuntimeError("Scene transfer contract changed")
|
||||
digest, size = hashlib.sha256(), 0
|
||||
with temporary.open("wb") as stream:
|
||||
while block := response.read(4 * 1024**2):
|
||||
# read() may wait for a whole multi-MB block on a slow but live
|
||||
# stream. read1() returns the next available bounded socket read
|
||||
# so control/lease pulses remain independent of transfer size.
|
||||
while block := response.read1(ASSET_BLOCK_BYTES):
|
||||
if pulse:
|
||||
pulse()
|
||||
size += len(block)
|
||||
if size > world["byte_length"]:
|
||||
raise RuntimeError("Scene transfer exceeds admitted size")
|
||||
|
||||
@@ -14,6 +14,26 @@ import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def encode_surface(mask, confidence):
|
||||
"""Retain reference labels; low confidence is neither permission nor ban.
|
||||
|
||||
0.55 is an explicit engineering gate, shared with the ADE adapter, not a
|
||||
claim of calibrated probabilities or a scene-dependent tuning parameter.
|
||||
"""
|
||||
if (
|
||||
mask.shape != (512, 512)
|
||||
or not np.issubdtype(mask.dtype, np.integer)
|
||||
or np.any(mask < 0)
|
||||
or np.any(mask >= 64)
|
||||
or confidence.shape != mask.shape
|
||||
or not np.isfinite(confidence).all()
|
||||
or np.any((confidence < 0) | (confidence > 1))
|
||||
):
|
||||
raise ValueError("DDRNet surface certainty contract changed")
|
||||
known = (confidence >= 0.55) & ~np.isin(mask, (0, 56))
|
||||
return mask.astype(np.uint8).tobytes() + known.astype(np.uint8).tobytes()
|
||||
|
||||
|
||||
def checked(path, expected):
|
||||
value = Path(path)
|
||||
if hashlib.sha256(value.read_bytes()).hexdigest() != expected:
|
||||
@@ -22,6 +42,8 @@ def checked(path, expected):
|
||||
|
||||
|
||||
def main():
|
||||
import torch
|
||||
|
||||
checkpoint = checked(
|
||||
"/assets/ddrnet-checkpoint.pth",
|
||||
"b99c2838051bcd7b092fd3970aa62a77d5c0bbb809c9b9afb2ff4b0ebdaa4ee6",
|
||||
@@ -34,8 +56,18 @@ def main():
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
model, _, _ = module.load_model("ddrnet", checkpoint)
|
||||
tensor, _ = module.preprocess(Image.fromarray(np.zeros((600, 800, 3), np.uint8)))
|
||||
module.infer(model, tensor)
|
||||
|
||||
def infer(rgb):
|
||||
tensor, _ = module.preprocess(Image.fromarray(rgb))
|
||||
with torch.inference_mode():
|
||||
logits = module.logits_from_output(model(tensor.cuda(non_blocking=True)))
|
||||
# Preserve the pinned reference's sigmoid/first-index tie labels.
|
||||
# Measure certainty of that exact selected class, including ties.
|
||||
labels = logits.sigmoid().argmax(1)
|
||||
confidence = logits.softmax(1).gather(1, labels[:, None])[:, 0]
|
||||
return encode_surface(labels[0].cpu().numpy(), confidence[0].cpu().numpy())
|
||||
|
||||
infer(np.zeros((600, 800, 3), np.uint8))
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def setup(self):
|
||||
@@ -53,7 +85,16 @@ def main():
|
||||
if self.path != "/ready":
|
||||
self.reply(404, b"")
|
||||
return
|
||||
self.reply(200, json.dumps({"model": "ddrnet-goose-pytorch-reference"}).encode())
|
||||
self.reply(
|
||||
200,
|
||||
json.dumps(
|
||||
{
|
||||
"model": "ddrnet-goose-pytorch-reference",
|
||||
"output": "goose64-labels-and-known-square512-v2",
|
||||
"minimum_class_confidence": 0.55,
|
||||
}
|
||||
).encode(),
|
||||
)
|
||||
|
||||
def do_POST(self):
|
||||
if self.path != "/infer" or self.headers.get("Content-Length") != "1440000":
|
||||
@@ -64,11 +105,7 @@ def main():
|
||||
if len(raw) != 1440000:
|
||||
raise ValueError("Incomplete camera frame")
|
||||
rgb = np.frombuffer(raw, np.uint8).reshape(600, 800, 3)
|
||||
tensor, _ = module.preprocess(Image.fromarray(rgb))
|
||||
mask, _ = module.infer(model, tensor)
|
||||
if mask.shape != (512, 512) or np.any(mask < 0) or np.any(mask >= 64):
|
||||
raise ValueError("DDRNet output contract changed")
|
||||
self.reply(200, mask.astype(np.uint8).tobytes())
|
||||
self.reply(200, infer(rgb))
|
||||
except (TimeoutError, ValueError, RuntimeError):
|
||||
self.reply(500, b"DDRNet inference failed")
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// Lossless Draco unpacking through the same vendored Google decoder as PlayCanvas.
|
||||
// No reconstruction, simplification or frame change is performed here.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vendor = path.resolve(__dirname, '../../apps/control-station/public/vendor/playcanvas/draco/1.5.7');
|
||||
const vm = require('node:vm');
|
||||
const decoderModule = {exports:{}};
|
||||
vm.runInNewContext(fs.readFileSync(path.join(vendor,'draco_wasm_wrapper_gltf.js'),'utf8'),
|
||||
{module:decoderModule,exports:decoderModule.exports,require,process,Buffer,console,
|
||||
__dirname:vendor,__filename:path.join(vendor,'draco_wasm_wrapper_gltf.js')});
|
||||
const factory = decoderModule.exports;
|
||||
async function main() {
|
||||
const input=fs.readFileSync(process.argv[2]);
|
||||
if(input.readUInt32LE(0)!==0x46546c67 || input.readUInt32LE(4)!==2 || input.readUInt32LE(8)!==input.length) throw Error('Invalid GLB');
|
||||
let document, binary;
|
||||
for(let o=12;o<input.length;) {
|
||||
const n=input.readUInt32LE(o),kind=input.readUInt32LE(o+4),bytes=input.subarray(o+8,o+8+n);
|
||||
if(kind===0x4e4f534a)document=JSON.parse(bytes);if(kind===0x004e4942)binary=bytes;o+=8+n;
|
||||
}
|
||||
if(!document||!binary)throw Error('Missing GLB chunks');
|
||||
if(document.nodes.some(n=>n.matrix||n.translation||n.rotation||n.scale))throw Error('Unbaked collider transform');
|
||||
const module=await factory({wasmBinary:fs.readFileSync(path.join(vendor,'draco_decoder_gltf.wasm'))});
|
||||
const decoder=new module.Decoder(), chunks=[],views=[],accessors=[],meshes=[];let offset=0;
|
||||
function append(values,type,componentType) {
|
||||
const bytes=Buffer.from(values.buffer,values.byteOffset,values.byteLength);
|
||||
const index=accessors.length;
|
||||
accessors.push({bufferView:views.length,componentType,count:values.length/(type==='VEC3'?3:1),type});
|
||||
views.push({buffer:0,byteOffset:offset,byteLength:bytes.length});chunks.push(bytes);offset+=bytes.length;
|
||||
return index;
|
||||
}
|
||||
function raw(index) {
|
||||
const a=document.accessors[index],v=document.bufferViews[a.bufferView];
|
||||
const C=a.componentType===5126?Float32Array:a.componentType===5125?Uint32Array:Uint16Array;
|
||||
const width=a.type==='VEC3'?3:1,out=new C(a.count*width), stride=v.byteStride||C.BYTES_PER_ELEMENT*width;
|
||||
for(let i=0;i<a.count;i++) for(let j=0;j<width;j++) {
|
||||
const o=(v.byteOffset||0)+(a.byteOffset||0)+i*stride+j*C.BYTES_PER_ELEMENT;
|
||||
out[i*width+j]=a.componentType===5126?binary.readFloatLE(o):a.componentType===5125?binary.readUInt32LE(o):binary.readUInt16LE(o);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
try { for(const mesh of document.meshes) {
|
||||
const primitives=[];
|
||||
for(const p of mesh.primitives) {
|
||||
if(p.mode!==undefined&&p.mode!==4)throw Error('Collider requires triangles');
|
||||
const ext=p.extensions?.KHR_draco_mesh_compression;let positions,indices;
|
||||
if(ext) {
|
||||
const v=document.bufferViews[ext.bufferView],bytes=binary.subarray(v.byteOffset||0,(v.byteOffset||0)+v.byteLength);
|
||||
const buffer=new module.DecoderBuffer(), decoded=new module.Mesh(), positionsArray=new module.DracoFloat32Array(), face=new module.DracoInt32Array();
|
||||
try {
|
||||
buffer.Init(new Int8Array(bytes),bytes.length);
|
||||
const status=decoder.DecodeBufferToMesh(buffer,decoded);
|
||||
if(!status.ok())throw Error(status.error_msg());
|
||||
const attribute=decoder.GetAttributeByUniqueId(decoded,ext.attributes.POSITION);
|
||||
if(!decoder.GetAttributeFloatForAllPoints(decoded,attribute,positionsArray))throw Error('Cannot decode position');
|
||||
positions=new Float32Array(decoded.num_points()*3);
|
||||
for(let i=0;i<positions.length;i++)positions[i]=positionsArray.GetValue(i);
|
||||
indices=new Uint32Array(decoded.num_faces()*3);
|
||||
for(let i=0;i<decoded.num_faces();i++){decoder.GetFaceFromMesh(decoded,i,face);for(let j=0;j<3;j++)indices[i*3+j]=face.GetValue(j);}
|
||||
} finally {for(const o of [face,positionsArray,decoded,buffer])module.destroy(o);}
|
||||
} else {positions=raw(p.attributes.POSITION);indices=new Uint32Array(raw(p.indices));}
|
||||
primitives.push({attributes:{POSITION:append(positions,'VEC3',5126)},indices:append(indices,'SCALAR',5125),mode:4});
|
||||
}
|
||||
meshes.push({primitives});
|
||||
}} finally {module.destroy(decoder);}
|
||||
const output={asset:{version:'2.0',generator:'Mission Core / Google Draco 1.5.7'},scene:0,scenes:[{nodes:meshes.map((_,i)=>i)}],nodes:meshes.map((_,i)=>({mesh:i})),meshes,accessors,bufferViews:views,buffers:[{byteLength:offset}]};
|
||||
const json=Buffer.from(JSON.stringify(output));const padding=Buffer.alloc((4-json.length%4)%4,32),body=Buffer.concat(chunks);
|
||||
const header=Buffer.alloc(20);header.writeUInt32LE(0x46546c67);header.writeUInt32LE(2,4);header.writeUInt32LE(28+json.length+padding.length+body.length,8);header.writeUInt32LE(json.length+padding.length,12);header.writeUInt32LE(0x4e4f534a,16);
|
||||
const binaryHeader=Buffer.alloc(8);binaryHeader.writeUInt32LE(body.length);binaryHeader.writeUInt32LE(0x004e4942,4);
|
||||
fs.writeFileSync(process.argv[3],Buffer.concat([header,json,padding,binaryHeader,body]));
|
||||
}
|
||||
main().catch(e=>{console.error(e.message);process.exitCode=1;});
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"432ee329fc75d86b50d0b577542adca579b0749b4939044fc3980f27b2618ece": {
|
||||
"manifest": "forest-scan-259c0051-v1-local/source-manifest.json",
|
||||
"manifest_sha256": "55b9fab459b98ac81126dc5df460f3e6b6f3b31108cfa053c094e33cae09f478"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Bounded SOG editor build and resumable push over the private Core channel."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
import zipfile
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
|
||||
from local_state import write_json
|
||||
from prepare_terrain import prepare_terrain
|
||||
|
||||
|
||||
def digest(path):
|
||||
with path.open("rb") as stream:
|
||||
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
|
||||
|
||||
def verify_sog(source, output):
|
||||
"""Reject accidental density or SH-band reduction before publishing a cache."""
|
||||
with source.open("rb") as stream:
|
||||
header = stream.read(65536).split(b"end_header", 1)[0].decode("ascii")
|
||||
count = None
|
||||
harmonics = 0
|
||||
for line in header.splitlines():
|
||||
parts = line.split()
|
||||
if parts[:2] == ["element", "vertex"]:
|
||||
count = int(parts[2])
|
||||
if parts and parts[0] == "property" and parts[-1].startswith("f_rest_"):
|
||||
harmonics += 1
|
||||
bands = {0: 0, 9: 1, 24: 2, 45: 3}.get(harmonics)
|
||||
with zipfile.ZipFile(output) as bundle:
|
||||
metadata = json.loads(bundle.read("meta.json"))
|
||||
actual_bands = metadata.get("shN", {}).get("bands", 0)
|
||||
if count is None or bands is None or metadata["count"] != count or actual_bands != bands:
|
||||
raise ValueError("SOG must retain the source Gaussian count and SH bands")
|
||||
return {"gaussian_count": count, "sh_bands": bands}
|
||||
|
||||
|
||||
def reuse_sog_archive(assets, world, output):
|
||||
"""Bundle an admitted original SOG without another lossy encode.
|
||||
|
||||
The versioned registry binds the imported PLY digest to its original archive.
|
||||
The archived manifest then pins every metadata/WebP byte (including SH).
|
||||
"""
|
||||
registry = json.loads(Path(__file__).with_name("editor-sources.json").read_text())
|
||||
entry = registry.get(world["sha256"])
|
||||
if not entry:
|
||||
return False
|
||||
manifest = assets / entry["manifest"]
|
||||
if not manifest.exists():
|
||||
return False
|
||||
if digest(manifest) != entry["manifest_sha256"]:
|
||||
raise ValueError("Original SOG archive manifest changed")
|
||||
archive = json.loads(manifest.read_text(encoding="utf-8"))
|
||||
if archive["source_url"] != world["source_url"]:
|
||||
raise ValueError("Original SOG archive source changed")
|
||||
for row in archive["files"]:
|
||||
if row["path"] != "meta.json" and not re.fullmatch(r"[A-Za-z0-9_-]+\.webp", row["path"]):
|
||||
raise ValueError("Invalid original SOG asset name")
|
||||
path = manifest.parent / row["path"]
|
||||
if path.stat().st_size != row["byte_length"] or digest(path) != row["sha256"]:
|
||||
raise ValueError("Original SOG asset checksum changed")
|
||||
with zipfile.ZipFile(output, "w") as bundle:
|
||||
for row in archive["files"]:
|
||||
info = zipfile.ZipInfo(row["path"]) # fixed timestamp, stored bytes
|
||||
with (
|
||||
(manifest.parent / row["path"]).open("rb") as source,
|
||||
bundle.open(info, "w") as target,
|
||||
):
|
||||
shutil.copyfileobj(source, target)
|
||||
return True
|
||||
|
||||
|
||||
def prepare_editor(client, request, state, job):
|
||||
key, world = request["key"], request["world"]
|
||||
endpoint = "/worker/editor-cache/" + key
|
||||
root = state.parent
|
||||
target = root / "assets/editor-v2" / key
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
log_path = target / "preparation.log"
|
||||
last_heartbeat = -float("inf")
|
||||
|
||||
def pulse():
|
||||
nonlocal last_heartbeat
|
||||
# Asset readers call us for every bounded chunk. Keep those checkpoints
|
||||
# cheap; network lease renewal depends on elapsed time, not asset size.
|
||||
if time.monotonic() - last_heartbeat < 1:
|
||||
return
|
||||
# Heartbeats are idempotent; an expired HTTP keep-alive must not kill CPU preparation.
|
||||
for attempt in range(3):
|
||||
try:
|
||||
client.request("/worker/heartbeat", {"instance_id": client.instance})
|
||||
last_heartbeat = time.monotonic()
|
||||
return
|
||||
except Exception:
|
||||
if attempt == 2:
|
||||
raise
|
||||
time.sleep(0.5)
|
||||
|
||||
try:
|
||||
client.request(endpoint, {"action": "prepare"})
|
||||
source = state / "worlds" / (world["sha256"] + ".ply")
|
||||
source.parent.mkdir(exist_ok=True)
|
||||
client.download(world, source, pulse=pulse)
|
||||
terrain = json.loads(
|
||||
prepare_terrain(root, target, world, job, pulse).read_text(encoding="utf-8-sig")
|
||||
)
|
||||
collider = Path(terrain["collider"])
|
||||
if digest(collider) != terrain["collider_sha256"]:
|
||||
raise ValueError("Collision source changed")
|
||||
preview = target / "scene.sog"
|
||||
metadata = target / "assets.json"
|
||||
files = None
|
||||
if metadata.exists():
|
||||
files = json.loads(metadata.read_text())
|
||||
if any(
|
||||
not p.exists() or digest(p) != files[n]["sha256"]
|
||||
for n, p in {"scene.sog": preview, "collision.glb": collider}.items()
|
||||
):
|
||||
raise ValueError("Prepared editor asset changed")
|
||||
if files is None:
|
||||
tool_root = root / "tools/splat-transform-3.4.0"
|
||||
cli = tool_root / "node_modules/@playcanvas/splat-transform/bin/cli.mjs"
|
||||
reused = reuse_sog_archive(root / "assets", world, preview)
|
||||
commands = (
|
||||
[]
|
||||
if reused
|
||||
else [
|
||||
[
|
||||
"node.exe",
|
||||
str(cli),
|
||||
"--gpu",
|
||||
"cpu",
|
||||
"-w",
|
||||
"--max-workers",
|
||||
"4",
|
||||
str(source),
|
||||
str(preview),
|
||||
],
|
||||
]
|
||||
)
|
||||
with log_path.open("wb") as log:
|
||||
if reused:
|
||||
log.write(b"Reused hash-verified original SOG archive; no re-encoding.\n")
|
||||
for command in commands:
|
||||
process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT)
|
||||
job.assign(process)
|
||||
deadline = time.monotonic() + 3600
|
||||
while process.poll() is None:
|
||||
pulse()
|
||||
if time.monotonic() > deadline:
|
||||
raise TimeoutError("Editor preparation timed out")
|
||||
time.sleep(1)
|
||||
if process.returncode:
|
||||
raise RuntimeError(f"Editor proxy preparation failed: {process.returncode}")
|
||||
write_json(target / "quality.json", verify_sog(source, preview))
|
||||
files = {
|
||||
name: {"sha256": digest(path), "byte_length": path.stat().st_size}
|
||||
for name, path in {
|
||||
"scene.sog": preview,
|
||||
"collision.glb": collider,
|
||||
}.items()
|
||||
}
|
||||
write_json(metadata, files)
|
||||
status = client.request(endpoint, {"action": "manifest", "files": files})
|
||||
for name, path in {"scene.sog": preview, "collision.glb": collider}.items():
|
||||
with path.open("rb") as stream:
|
||||
offset = status["files"][name]["uploaded_bytes"]
|
||||
stream.seek(offset)
|
||||
while block := stream.read(512 * 1024):
|
||||
# An uncertain response resumes from the durable Core offset.
|
||||
client.request(
|
||||
endpoint,
|
||||
{
|
||||
"action": "chunk",
|
||||
"name": name,
|
||||
"offset": offset,
|
||||
"data": base64.b64encode(block).decode(),
|
||||
},
|
||||
)
|
||||
offset += len(block)
|
||||
client.request(endpoint, {"action": "complete"})
|
||||
except Exception:
|
||||
import logging
|
||||
|
||||
logging.exception("Editor asset preparation failed")
|
||||
with suppress(Exception):
|
||||
client.request(endpoint, {"action": "fail"})
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"repository": "tue-mps/cityscapes_semantic_eomt_large_1024",
|
||||
"revision": "8d6b6d1a3f7b50d441afd7d247c2ed10db186e8f",
|
||||
"existing_asset_path": "D:/NDC_MISSIONCORE/runtime/assets/observatory-portable/eomt-model-cache-cityscapes-large-1024-v1/huggingface/models--tue-mps--cityscapes_semantic_eomt_large_1024/snapshots/8d6b6d1a3f7b50d441afd7d247c2ed10db186e8f",
|
||||
"files": {
|
||||
"config.json": "7f4aa94fa4e43c0dbd79a5420edb511120aef62bd82bfbcbcece79948286a650",
|
||||
"preprocessor_config.json": "97e2fbf7f0bdba2cfc90251c5133bae9c27ddc9c4410509f40670be2332854e7",
|
||||
"model.safetensors": "c265da9a74f58f5c3f4826d23ca4ca78beac0b106cca5842beca61580de5b782"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Pinned OneFormer comparison on recorded views; no rover commands."""
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
from transformers import AutoImageProcessor, EomtForUniversalSegmentation
|
||||
|
||||
|
||||
def sha(path):
|
||||
digest = hashlib.sha256()
|
||||
with path.open('rb') as stream:
|
||||
for chunk in iter(lambda: stream.read(1024*1024), b''):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def main():
|
||||
torch.set_num_threads(3)
|
||||
assets = Path('/assets')
|
||||
descriptor = json.loads(Path('/adapter/model.json').read_text())
|
||||
for name, expected in descriptor['files'].items():
|
||||
assert sha(assets/name) == expected, name
|
||||
processor = AutoImageProcessor.from_pretrained(assets, local_files_only=True, use_fast=True)
|
||||
model, loading = EomtForUniversalSegmentation.from_pretrained(assets, local_files_only=True, output_loading_info=True)
|
||||
assert not any(loading[k] for k in ('missing_keys','unexpected_keys','mismatched_keys','error_msgs')), loading
|
||||
model.to(device='cuda', dtype=torch.float16).eval()
|
||||
rows=[]
|
||||
output=Path('/evidence')
|
||||
for source in json.loads(Path('/inputs/manifest.json').read_text()):
|
||||
path=Path('/inputs')/source['file']
|
||||
assert sha(path)==source['sha256']
|
||||
original=Image.open(path).convert('RGB')
|
||||
for crop in (True,False):
|
||||
side=min(original.size);x=(original.width-side)//2;y=(original.height-side)//2
|
||||
image=original.crop((x,y,x+side,y+side)) if crop else original
|
||||
inputs=processor(images=image,return_tensors='pt').to(device='cuda', dtype=torch.float16)
|
||||
torch.cuda.synchronize();begin=time.monotonic()
|
||||
with torch.inference_mode():
|
||||
prediction=model(**inputs)
|
||||
labels=processor.post_process_semantic_segmentation(prediction,target_sizes=[(image.height,image.width)])[0].cpu().numpy().astype(np.uint8)
|
||||
torch.cuda.synchronize();elapsed=time.monotonic()-begin
|
||||
name=path.stem+('-crop' if crop else '-full')
|
||||
Image.fromarray(labels).save(output/(name+'.labels.png'))
|
||||
colors=np.zeros((*labels.shape,3),dtype=np.uint8)
|
||||
colors[(labels==1)]=[20,220,170];colors[labels==0]=[220,40,50]
|
||||
Image.blend(image,Image.fromarray(colors),.45).save(output/(name+'.jpg'))
|
||||
ids,counts=np.unique(labels,return_counts=True)
|
||||
row=dict(case=name,source=source,utc=datetime.now(timezone.utc).isoformat(),monotonic=time.monotonic(),inference_seconds=elapsed,
|
||||
sidewalk_fraction=float((labels==1).mean()),road_fraction=float((labels==0).mean()),
|
||||
classes={model.config.id2label[int(i)]:int(n) for i,n in zip(ids,counts)})
|
||||
rows.append(row);(output/'results.json').write_text(json.dumps(rows,indent=2))
|
||||
print(json.dumps(row),flush=True)
|
||||
(output/'artifact-sha256.json').write_text(json.dumps({p.name:sha(p) for p in output.iterdir() if p.is_file()},indent=2))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,60 @@
|
||||
"""One offline GPU job under a Core simulation reservation, with exact cleanup."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--reservation", type=Path, required=True)
|
||||
parser.add_argument("--inputs", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--root", type=Path, default=Path("D:/NDC_MISSIONCORE/runtime/simulation"))
|
||||
args = parser.parse_args()
|
||||
receipt = json.loads(args.reservation.read_text())
|
||||
assert receipt["state"] == "reserved" and receipt["owner_id"].startswith("airun-")
|
||||
assert not (args.root / "state/active.json").exists(), "A rover run is active"
|
||||
assert 0 <= (datetime.now(UTC) - datetime.fromisoformat(receipt["utc"])).total_seconds() < 900
|
||||
adapter = Path(__file__).parent.resolve()
|
||||
descriptor = json.loads((adapter / "model.json").read_text())
|
||||
assets = Path(descriptor["existing_asset_path"])
|
||||
assert (assets / "model.safetensors").is_file()
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
identity = None
|
||||
begin = time.monotonic()
|
||||
try:
|
||||
identity = subprocess.check_output([
|
||||
"docker", "run", "-d", "--name", "ndc-eomt-qualification-" + receipt["owner_id"][-8:],
|
||||
"--gpus", "all", "--cpus", "3", "--memory", "6g",
|
||||
"--label", "com.nodedc.product=mission-core", "--label", "com.nodedc.stack=ai-polygon-qualification",
|
||||
"--label", "com.nodedc.role=qualification", "--label", "com.nodedc.managed-by=ai-polygon-qualification",
|
||||
"--mount", f"type=bind,source={adapter},target=/adapter,readonly",
|
||||
"--mount", f"type=bind,source={assets},target=/assets,readonly",
|
||||
"--mount", f"type=bind,source={args.inputs.resolve()},target=/inputs,readonly",
|
||||
"--mount", f"type=bind,source={args.output.resolve()},target=/evidence",
|
||||
"--mount", "type=bind,source=D:/NDC_MISSIONCORE/runtime/derived/perception-p0-env-v1,target=/opt/env,readonly",
|
||||
"--mount", "type=bind,source=D:/NDC_MISSIONCORE/runtime/derived/perception-p0-transformers4576-v1,target=/opt/transformers,readonly",
|
||||
"-e", "PYTHONPATH=/opt/transformers:/opt/env",
|
||||
"--entrypoint", "python3",
|
||||
"sha256:211852dfae4ab1acbd1195d4968a385ea56bd7bd3d0c4241a6be7e02794999b7",
|
||||
"-B", "/adapter/qualify.py",
|
||||
], text=True).strip()
|
||||
result = subprocess.check_output(["docker", "wait", identity], timeout=240, text=True).strip()
|
||||
logs = subprocess.check_output(["docker", "logs", identity], stderr=subprocess.STDOUT, text=True)
|
||||
(args.output / "execution.log").write_text(logs)
|
||||
print(logs[-14000:])
|
||||
assert result == "0", "Model qualification failed: exit " + result
|
||||
finally:
|
||||
released = identity is None or subprocess.run(["docker", "rm", "-f", identity], capture_output=True).returncode == 0
|
||||
(args.output / "cleanup.json").write_text(json.dumps(dict(
|
||||
owner_id=receipt["owner_id"], released=released, utc=datetime.now(UTC).isoformat(),
|
||||
elapsed_seconds=time.monotonic() - begin)))
|
||||
assert released
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Transfer a latched pipeline failure to its native episode lifecycle owner."""
|
||||
|
||||
from local_state import write_json
|
||||
|
||||
|
||||
def consume_pipeline_failure(pipeline, directory, stop_command):
|
||||
accessor = getattr(pipeline, "terminal_failure", None)
|
||||
failure = accessor() if accessor is not None else None
|
||||
if failure is None:
|
||||
return None
|
||||
# This stops actuator intent only. It neither rewrites measured velocity
|
||||
# nor claims that the physical body has already stopped.
|
||||
stop_command(0.0, 0.0)
|
||||
write_json(directory / "pipeline-failure.json", failure)
|
||||
return {
|
||||
"outcome": "failed",
|
||||
"mission_outcome": "error",
|
||||
"message": "Симуляция завершена после ошибки обработки наблюдений. Журнал сохранён.",
|
||||
"pipeline_failure": failure,
|
||||
}
|
||||
@@ -30,7 +30,7 @@ if raw[:2] == b"\x1f\x8b":
|
||||
if len(raw) > 1024**2:
|
||||
raise ValueError("LOD manifest too large")
|
||||
meta = json.loads(raw)
|
||||
if meta["version"] != 1 or not 1 <= meta["counts"][0] <= 20_000_000:
|
||||
if meta["version"] != 1 or meta["counts"][0] < 1:
|
||||
raise ValueError("Unsupported scene size or LOD version")
|
||||
indices = set()
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ if raw[:2] == b"\x1f\x8b":
|
||||
(args.output / "meta.json").write_bytes(raw)
|
||||
meta = {"path": "meta.json", "byte_length": len(raw), "sha256": hashlib.sha256(raw).hexdigest()}
|
||||
metadata = json.loads(raw)
|
||||
if metadata.get("version") != 2 or not 1 <= metadata["count"] <= 20_000_000:
|
||||
if metadata.get("version") != 2 or metadata["count"] < 1:
|
||||
raise ValueError("Unsupported SOG version or size")
|
||||
files = sorted(
|
||||
{
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Verified Gaussian conversion cache, independent of Isaac imports.
|
||||
|
||||
The caller supplies the real reader/writer and runtime identities. A code
|
||||
bundle alone is not evidence of which cached USD the renderer will load.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
SCHEMA = "missioncore.gaussian-usd-cache/v1"
|
||||
|
||||
|
||||
def file_sha256(path):
|
||||
digest = hashlib.sha256()
|
||||
with Path(path).open("rb") as stream:
|
||||
while chunk := stream.read(1024 * 1024):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _json_bytes(value):
|
||||
return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
|
||||
|
||||
|
||||
def _identity(source, recipe):
|
||||
if not isinstance(recipe, dict) or set(recipe) != {"reader", "writer", "runtime", "output_schema"}:
|
||||
raise ValueError("Gaussian recipe requires reader, writer, runtime and output_schema identities")
|
||||
if any(not recipe[key] for key in recipe):
|
||||
raise ValueError("Gaussian conversion identities must not be empty")
|
||||
# Round-trip creates an immutable JSON snapshot of caller-owned dictionaries.
|
||||
recipe = json.loads(_json_bytes(recipe))
|
||||
before = source.stat()
|
||||
source_sha256 = file_sha256(source)
|
||||
after = source.stat()
|
||||
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
|
||||
raise RuntimeError("Gaussian source changed while its identity was read")
|
||||
return {
|
||||
"source_sha256": source_sha256,
|
||||
"source_bytes": after.st_size,
|
||||
"cache_adapter_sha256": file_sha256(__file__),
|
||||
"recipe": recipe,
|
||||
}
|
||||
|
||||
|
||||
def _receipt(path, identity, key, output):
|
||||
try:
|
||||
value = json.loads(path.read_text(encoding="utf-8"))
|
||||
if (
|
||||
not isinstance(value, dict)
|
||||
or value.get("schema_version") != SCHEMA
|
||||
or value.get("cache_key") != key
|
||||
or value.get("identity") != identity
|
||||
or value.get("usd_file") != output.name
|
||||
or value.get("usd_bytes", 0) <= 0
|
||||
or not output.is_file()
|
||||
or output.stat().st_size != value["usd_bytes"]
|
||||
or file_sha256(output) != value.get("usd_sha256")
|
||||
):
|
||||
return None
|
||||
return value
|
||||
except (OSError, ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def prepare_gaussian(source, convert, recipe, *, cache_root=None):
|
||||
"""Return the verified USD path and the receipt for the loaded artifact.
|
||||
|
||||
``convert(source_path, temporary_usd_path)`` owns the real conversion and
|
||||
format checks. It must finish writing before returning. This helper proves
|
||||
byte identity/reuse, not renderer or optical equivalence. Worker admission
|
||||
serializes scene preparation; this is not a multi-writer cache service.
|
||||
"""
|
||||
source = Path(source)
|
||||
identity = _identity(source, recipe)
|
||||
key = hashlib.sha256(_json_bytes(identity)).hexdigest()
|
||||
root = Path(cache_root) if cache_root is not None else source.parent / "gaussian-usd-cache"
|
||||
directory = root / key
|
||||
output, receipt_path = directory / "gaussians.usd", directory / "receipt.json"
|
||||
valid = _receipt(receipt_path, identity, key, output)
|
||||
if valid is not None:
|
||||
return output, valid
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
token = uuid.uuid4().hex
|
||||
temporary = directory / (token + ".part.usd")
|
||||
receipt_temporary = directory / (token + ".part.json")
|
||||
try:
|
||||
convert(source, temporary)
|
||||
if not temporary.is_file() or temporary.stat().st_size == 0:
|
||||
raise ValueError("Gaussian conversion did not produce a nonempty USD")
|
||||
if source.stat().st_size != identity["source_bytes"] or file_sha256(source) != identity["source_sha256"]:
|
||||
raise RuntimeError("Gaussian source changed during conversion")
|
||||
value = {
|
||||
"schema_version": SCHEMA,
|
||||
"cache_key": key,
|
||||
"identity": identity,
|
||||
"usd_file": output.name,
|
||||
"usd_bytes": temporary.stat().st_size,
|
||||
"usd_sha256": file_sha256(temporary),
|
||||
}
|
||||
receipt_temporary.write_bytes(_json_bytes(value) + b"\n")
|
||||
temporary.replace(output)
|
||||
receipt_temporary.replace(receipt_path)
|
||||
return output, value
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
receipt_temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def verify_loaded_gaussian(source, receipt, *, cache_root=None):
|
||||
"""Verify the episode's loaded artifact, never the legacy sibling USD.
|
||||
|
||||
Verification is read-only: an invalid or missing artifact cannot be repaired
|
||||
after the episode and then presented as the bytes it actually loaded.
|
||||
"""
|
||||
source = Path(source)
|
||||
if not isinstance(receipt, dict) or not isinstance(receipt.get("identity"), dict):
|
||||
raise ValueError("Missing loaded Gaussian identity")
|
||||
identity = _identity(source, receipt["identity"].get("recipe"))
|
||||
key = hashlib.sha256(_json_bytes(identity)).hexdigest()
|
||||
root = Path(cache_root) if cache_root is not None else source.parent / "gaussian-usd-cache"
|
||||
output = root / key / "gaussians.usd"
|
||||
valid = _receipt(output.parent / "receipt.json", identity, key, output)
|
||||
if valid is None or valid != receipt:
|
||||
raise ValueError("Loaded Gaussian evidence differs from source, recipe or actual USD bytes")
|
||||
return output
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Lossless array-based adapter to Isaac's ParticleField3DGaussianSplat schema.
|
||||
|
||||
The installed NVIDIA reader owns PLY decoding. This writer matches its position,
|
||||
scale, quaternion, opacity and channel-major SH conversion using NumPy/Vt arrays.
|
||||
Chunking bounds temporary work; it neither reduces Gaussian count nor SH degree.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def write_gaussian_usd(data, output, *, chunk_size=250_000, progress=None):
|
||||
from pxr import Sdf, Usd, UsdGeom, Vt
|
||||
|
||||
if data.count < 1 or chunk_size < 1:
|
||||
raise ValueError("Empty Gaussian scene or invalid conversion chunk")
|
||||
stage = Usd.Stage.CreateNew(str(output))
|
||||
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
|
||||
UsdGeom.SetStageMetersPerUnit(stage, 1)
|
||||
root = UsdGeom.Xform.Define(stage, "/Gaussians")
|
||||
stage.SetDefaultPrim(root.GetPrim())
|
||||
k = data.f_rest.shape[1] if data.f_rest is not None else 0
|
||||
if k not in (0, 9, 24, 45):
|
||||
raise ValueError("Unsupported Gaussian SH attributes")
|
||||
degree = {0: 0, 9: 1, 24: 2, 45: 3}[k]
|
||||
for start in range(0, data.count, chunk_size):
|
||||
end = min(data.count, start + chunk_size)
|
||||
part = slice(start, end)
|
||||
field = stage.DefinePrim(f"/Gaussians/Part_{start}", "ParticleField3DGaussianSplat")
|
||||
def attr(name, kind, value):
|
||||
attribute = field.CreateAttribute(name, kind)
|
||||
attribute.Set(value)
|
||||
return attribute
|
||||
positions = np.asarray(data.positions[part], dtype=np.float32)
|
||||
attr("positions", Sdf.ValueTypeNames.Point3fArray, Vt.Vec3fArray.FromNumpy(positions))
|
||||
extent = np.clip(np.array([positions.min(axis=0), positions.max(axis=0)]), -50000, 50000)
|
||||
UsdGeom.Boundable(field).CreateExtentAttr(Vt.Vec3fArray.FromNumpy(extent))
|
||||
scales = np.exp(data.scales[part].astype(np.float64)).astype(np.float32)
|
||||
attr("scales", Sdf.ValueTypeNames.Float3Array, Vt.Vec3fArray.FromNumpy(scales))
|
||||
quaternions = np.array(data.rotations[part], dtype=np.float32, copy=True)
|
||||
norms = np.sqrt(np.sum(quaternions * quaternions, axis=1))
|
||||
valid = norms >= 1e-10
|
||||
quaternions[valid] /= norms[valid, None]
|
||||
quaternions[~valid] = [1, 0, 0, 0]
|
||||
# Gf.Quatf's memory layout is [imaginary xyz, real w]. PLY is wxyz.
|
||||
quaternions = np.ascontiguousarray(quaternions[:, [1, 2, 3, 0]])
|
||||
attr("orientations", Sdf.ValueTypeNames.QuatfArray, Vt.QuatfArray.FromNumpy(quaternions))
|
||||
opacities = (1 / (1 + np.exp(-data.opacities[part].astype(np.float64)))).astype(np.float32)
|
||||
attr("opacities", Sdf.ValueTypeNames.FloatArray, Vt.FloatArray.FromNumpy(opacities))
|
||||
attr("radiance:sphericalHarmonicsDegree", Sdf.ValueTypeNames.Int, degree)
|
||||
sh = np.empty((end - start, 1 + k // 3, 3), dtype=np.float32)
|
||||
sh[:, 0, :] = data.f_dc[part]
|
||||
if k:
|
||||
sh[:, 1:, :] = data.f_rest[part].reshape(end - start, 3, k // 3).transpose(0, 2, 1)
|
||||
coefficients = attr("radiance:sphericalHarmonicsCoefficients", Sdf.ValueTypeNames.Float3Array,
|
||||
Vt.Vec3fArray.FromNumpy(sh.reshape(-1, 3)))
|
||||
primvar = UsdGeom.Primvar(coefficients)
|
||||
primvar.SetElementSize(1 + k // 3)
|
||||
primvar.SetInterpolation(UsdGeom.Tokens.vertex)
|
||||
colors = np.clip(.5 + .28209479177387814 * data.f_dc[part].astype(np.float64), 0, 1).astype(np.float32)
|
||||
UsdGeom.PrimvarsAPI(field).CreatePrimvar("displayColor", Sdf.ValueTypeNames.Color3fArray,
|
||||
UsdGeom.Tokens.vertex).Set(Vt.Vec3fArray.FromNumpy(colors))
|
||||
if progress:
|
||||
progress(end, data.count)
|
||||
stage.GetRootLayer().comment = "Full-quality Gaussian arrays; all source points and SH coefficients retained."
|
||||
stage.GetRootLayer().Save()
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Bounded, read-only operator views selected from the executed composition ports.
|
||||
|
||||
Register a port renderer here when a provider adds an observable output. The UI
|
||||
uses descriptors, not model names. No preview is ever fed back into inference.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import io
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
from local_state import write_json
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
|
||||
def jpeg(image, size=(400, 300)):
|
||||
output = io.BytesIO()
|
||||
image.resize(size, Image.Resampling.BILINEAR).save(output, "JPEG", quality=72)
|
||||
raw = base64.b64encode(output.getvalue()).decode()
|
||||
if len(raw) > 100000:
|
||||
raise ValueError("Preview exceeds budget")
|
||||
return raw
|
||||
|
||||
|
||||
def overlay(original, colors):
|
||||
image = original.copy()
|
||||
crop = Image.fromarray(colors).resize((600, 600), Image.Resampling.NEAREST)
|
||||
image.paste(Image.blend(original.crop((100, 0, 700, 600)), crop, 0.6), (100, 0))
|
||||
return image
|
||||
|
||||
|
||||
def segmentation(original, values, names):
|
||||
labels = values["segmentation.labels"].astype(np.uint16)
|
||||
colors = np.stack(
|
||||
((labels * 67 + 41) % 255, (labels * 131 + 97) % 255, (labels * 47 + 173) % 255), axis=-1
|
||||
).astype(np.uint8)
|
||||
ids, counts = np.unique(labels, return_counts=True)
|
||||
legend = [
|
||||
{
|
||||
"class_id": int(i),
|
||||
"label": names.get(int(i), f"Класс {i}"),
|
||||
"color": "#"
|
||||
+ "".join(
|
||||
f"{int(c):02x}"
|
||||
for c in ((i * 67 + 41) % 255, (i * 131 + 97) % 255, (i * 47 + 173) % 255)
|
||||
),
|
||||
}
|
||||
for i in ids[np.argsort(counts)[::-1][:8]]
|
||||
]
|
||||
return {"kind": "image", "jpeg": jpeg(overlay(original, colors)), "legend": legend}
|
||||
|
||||
|
||||
def surface(original, values, names):
|
||||
colors = np.zeros((512, 512, 3), dtype=np.uint8)
|
||||
colors[:] = [215, 60, 55]
|
||||
colors[values["navigation.surface"]] = [140, 220, 80]
|
||||
return {
|
||||
"kind": "image",
|
||||
"jpeg": jpeg(overlay(original, colors)),
|
||||
"legend": [
|
||||
{"class_id": 1, "label": "Разрешённое покрытие", "color": "#8cdc50"},
|
||||
{"class_id": 0, "label": "Не разрешено", "color": "#d73c37"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def detection(original, values, names):
|
||||
image = original.copy()
|
||||
draw = ImageDraw.Draw(image)
|
||||
for x1, y1, x2, y2 in values["detection.boxes"]:
|
||||
draw.rectangle((x1 * 800, y1 * 600, x2 * 800, y2 * 600), outline=(255, 200, 70), width=3)
|
||||
return {"kind": "image", "jpeg": jpeg(image)}
|
||||
|
||||
|
||||
def lidar(original, values, names):
|
||||
points = np.asarray(values["source.lidar"], dtype=float).reshape(-1, 3)
|
||||
points = points[np.isfinite(points).all(axis=1)]
|
||||
pose = np.asarray(values["source.pose"], dtype=float)
|
||||
x, y, z, w = pose[3:] / np.linalg.norm(pose[3:])
|
||||
rotation = np.array(
|
||||
[
|
||||
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
|
||||
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
|
||||
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
|
||||
]
|
||||
)
|
||||
count = len(points)
|
||||
# Display sampling only. Inference retains the complete original returns.
|
||||
points = points[:: max(1, int(np.ceil(count / 2048)))]
|
||||
points = (points - pose[:3]) @ rotation
|
||||
return {
|
||||
"kind": "points3d",
|
||||
"points": np.round(points, 4).tolist(),
|
||||
"source_count": count,
|
||||
"frame": "body-x-forward-y-left-z-up",
|
||||
}
|
||||
|
||||
|
||||
def camera_layers(observation):
|
||||
"""Read-only views of the same timestamped sensor packet used for fusion."""
|
||||
layers = []
|
||||
names = (
|
||||
("insta360_panorama", "Insta360 · панорама", (640, 320)),
|
||||
("insta360_left", "Insta360 · левая линза", (320, 320)),
|
||||
("insta360_right", "Insta360 · правая линза", (320, 320)),
|
||||
("realsense_rgb", "RealSense · изображение", (400, 300)),
|
||||
)
|
||||
for key, label, size in names:
|
||||
if key not in observation.get("camera_sources", {}):
|
||||
continue
|
||||
layers.append(
|
||||
{
|
||||
"id": key.replace("_", "-"),
|
||||
"label": label,
|
||||
"kind": "image",
|
||||
"ports": ["source.camera." + key],
|
||||
"image_size": list(size),
|
||||
"jpeg": jpeg(Image.fromarray(observation["camera_sources"][key]), size),
|
||||
}
|
||||
)
|
||||
if "realsense_depth" in observation:
|
||||
depth = np.asarray(observation["realsense_depth"])
|
||||
valid = np.isfinite(depth) & (depth >= 0.52) & (depth <= 6.0)
|
||||
gray = np.zeros(depth.shape, dtype=np.uint8)
|
||||
gray[valid] = np.round(32 + 223 * (6.0 - depth[valid]) / (6.0 - 0.52)).astype(np.uint8)
|
||||
layers.append(
|
||||
{
|
||||
"id": "realsense-depth",
|
||||
"label": "RealSense · глубина",
|
||||
"kind": "image",
|
||||
"ports": ["source.realsense.depth"],
|
||||
"image_size": [400, 300],
|
||||
"jpeg": jpeg(Image.fromarray(gray)),
|
||||
"legend": [
|
||||
{"class_id": 0, "label": "Нет измерения", "color": "#000000"},
|
||||
{"class_id": 1, "label": "0,52 м", "color": "#ffffff"},
|
||||
{"class_id": 2, "label": "6 м", "color": "#202020"},
|
||||
],
|
||||
}
|
||||
)
|
||||
return layers
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PortView:
|
||||
id: str
|
||||
label: str
|
||||
ports: tuple[str, ...]
|
||||
render: object
|
||||
|
||||
|
||||
PORT_VIEWS = (
|
||||
PortView("segmentation", "Сегментация", ("segmentation.labels",), segmentation),
|
||||
PortView("surface", "Проходимость", ("navigation.surface",), surface),
|
||||
PortView("detection", "Детекция", ("detection.boxes",), detection),
|
||||
PortView("lidar", "LiDAR", ("source.lidar", "source.pose"), lidar),
|
||||
)
|
||||
|
||||
|
||||
class InferencePreview:
|
||||
def __init__(self, directory, graph, environment, names=None):
|
||||
self.path = directory.parent / "inference-preview.json"
|
||||
self.graph, self.environment = graph, environment
|
||||
self.last = 0.0
|
||||
self.names = names or {}
|
||||
# A source existing in the observation does not imply this composition
|
||||
# consumes it. Admit only outputs/inputs of the resolved graph.
|
||||
ports = {port for node in graph.nodes for port in node.module.provides}
|
||||
ports.update(port for node in graph.nodes for port, _ in node.inputs)
|
||||
self.views = [view for view in PORT_VIEWS if set(view.ports) <= ports]
|
||||
|
||||
def publish(self, rgb, values, observation, frame_id):
|
||||
now = time.monotonic()
|
||||
if now - self.last < 0.5:
|
||||
return
|
||||
self.last = now
|
||||
original = Image.fromarray(rgb)
|
||||
layers = [
|
||||
{
|
||||
"id": view.id,
|
||||
"label": view.label,
|
||||
"ports": list(view.ports),
|
||||
**view.render(original, values, self.names),
|
||||
}
|
||||
for view in self.views
|
||||
if all(port in values for port in view.ports)
|
||||
]
|
||||
layers.extend(camera_layers(observation))
|
||||
write_json(
|
||||
self.path,
|
||||
{
|
||||
"frame_id": frame_id,
|
||||
"simulation_time_ns": observation["simulation_time_ns"],
|
||||
"composition_sha256": self.graph.sha256,
|
||||
"environment": self.environment,
|
||||
"layers": layers,
|
||||
},
|
||||
)
|
||||
@@ -3,10 +3,44 @@
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def create_episode(state: Path, run_id: str, evidence_root: Path | None = None):
|
||||
"""Keep the canonical episode path while using explicit evidence storage.
|
||||
|
||||
A whole-episode junction preserves relative asset paths and the sealed
|
||||
evidence boundary. Existing episodes and targets are never reused.
|
||||
"""
|
||||
episode = state / run_id
|
||||
if evidence_root is None or evidence_root.resolve() == state.resolve():
|
||||
episode.mkdir(exist_ok=False)
|
||||
return episode
|
||||
if os.name != 'nt' or not evidence_root.is_absolute():
|
||||
raise ValueError('External episode storage requires an absolute Windows directory')
|
||||
for path in (episode, evidence_root):
|
||||
if any(c in str(path) for c in '&|<>^%!"\r\n'):
|
||||
raise ValueError('Unsupported episode storage path')
|
||||
if episode.exists() or episode.is_junction():
|
||||
raise FileExistsError(episode)
|
||||
evidence_root.mkdir(parents=True, exist_ok=True)
|
||||
target = evidence_root / run_id
|
||||
target.mkdir(exist_ok=False)
|
||||
try:
|
||||
subprocess.run(['cmd.exe', '/d', '/c', 'mklink', '/J', str(episode), str(target)],
|
||||
check=True, capture_output=True, timeout=10)
|
||||
if not episode.is_junction() or episode.resolve() != target.resolve():
|
||||
raise RuntimeError('Episode storage junction identity mismatch')
|
||||
except BaseException:
|
||||
if episode.is_junction():
|
||||
os.rmdir(episode)
|
||||
target.rmdir() # Only our newly created, still-empty directory.
|
||||
raise
|
||||
return episode
|
||||
|
||||
|
||||
class StateChannel:
|
||||
"""Latest-value local IPC using SQLite WAL, available in both Python hosts.
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"repository": "facebook/mask2former-swin-large-mapillary-vistas-semantic",
|
||||
"revision": "2cc022513f0012ff47d4438516284fd0946a196a",
|
||||
"asset_directory": "mask2former-mapillary",
|
||||
"qualification_only": true,
|
||||
"files": {
|
||||
"config.json": "b40bec8d82de3b53ef967dce0496c37de520b69466f1a8d2f6c035700cbae9f3",
|
||||
"preprocessor_config.json": "22ef0608c7add19c5e9a64f8eeba95b7d3d1237ef20bf14efead9d8bc671da9f",
|
||||
"README.md": "b534d1a4be6fd8f61da29dde0887ccdffb18f866a1ab88da381fb585c9ba60c7",
|
||||
"pytorch_model.bin": "8120d77b194b34527b5937a576c36291ae7e76157f57a22433480c19d71e1551"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Prepare only the pinned optional research model; no host packages or services."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def sha(path):
|
||||
with path.open("rb") as stream:
|
||||
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--root", type=Path, default=Path("D:/NDC_MISSIONCORE/runtime/simulation"))
|
||||
args = parser.parse_args()
|
||||
descriptor = json.loads(Path(__file__).with_name("model.json").read_text())
|
||||
output = args.root / "assets" / descriptor["asset_directory"] / descriptor["revision"]
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
for name, expected in descriptor["files"].items():
|
||||
path = output / name
|
||||
if not path.exists():
|
||||
part = path.with_name(name + f".{os.getpid()}.part")
|
||||
url = f'https://huggingface.co/{descriptor["repository"]}/resolve/{descriptor["revision"]}/{name}'
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=60) as response, part.open("xb") as stream:
|
||||
while chunk := response.read(1024 * 1024):
|
||||
stream.write(chunk)
|
||||
if sha(part) != expected:
|
||||
raise ValueError("Downloaded model checksum mismatch: " + name)
|
||||
part.replace(path)
|
||||
finally:
|
||||
part.unlink(missing_ok=True)
|
||||
if sha(path) != expected:
|
||||
raise ValueError("Existing model checksum mismatch: " + name)
|
||||
receipt = dict(schema_version="missioncore.optional-model-preparation/v1",
|
||||
descriptor=descriptor, utc=datetime.now(UTC).isoformat(),
|
||||
assets=str(output), scope="offline simulation qualification",
|
||||
rollback="Remove this optional qualification asset; no active model was changed")
|
||||
(output / "installation.json").write_text(json.dumps(receipt, indent=2))
|
||||
print(json.dumps(receipt))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Bounded recorded-image qualification. Produces no navigation command."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--context", action="store_true")
|
||||
args = parser.parse_args()
|
||||
descriptor = json.loads(Path("/adapter/model.json").read_text())
|
||||
for name, expected in descriptor["files"].items():
|
||||
digest = hashlib.sha256()
|
||||
with (Path("/assets") / name).open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
assert digest.hexdigest() == expected, name
|
||||
output = Path("/evidence")
|
||||
torch.set_num_threads(3)
|
||||
processor = AutoImageProcessor.from_pretrained("/assets", local_files_only=True)
|
||||
model = Mask2FormerForUniversalSegmentation.from_pretrained("/assets", local_files_only=True).cuda().eval()
|
||||
rows = []
|
||||
for path in sorted(Path("/inputs").glob("*-crop.jpg")):
|
||||
original = Image.open(path).convert("RGB")
|
||||
for crop in ((False,) if args.context else (True, False)):
|
||||
image = original.crop((100, 0, 700, 600)) if crop else original
|
||||
for size in ((1024, 1536, 2048) if args.context else (384, 768)):
|
||||
shape = ({"height": round(size * image.height / image.width), "width": size}
|
||||
if args.context else {"height": size, "width": size})
|
||||
inputs = processor(images=image, return_tensors="pt", size=shape).to("cuda")
|
||||
torch.cuda.reset_peak_memory_stats()
|
||||
torch.cuda.synchronize()
|
||||
begin = time.monotonic()
|
||||
with torch.inference_mode():
|
||||
prediction = model(**inputs)
|
||||
labels = processor.post_process_semantic_segmentation(
|
||||
prediction, target_sizes=[(image.height, image.width)]
|
||||
)[0].cpu().numpy().astype(np.uint8)
|
||||
torch.cuda.synchronize()
|
||||
elapsed = time.monotonic() - begin
|
||||
key = f"{path.stem}-{'crop' if crop else 'full'}-{size}"
|
||||
Image.fromarray(labels).save(output / (key + ".labels.png"))
|
||||
# Only visualization: pedestrian area/sidewalk cyan, road red,
|
||||
# potential crossing yellow. These colors grant no permissions.
|
||||
colors = np.zeros((*labels.shape, 3), dtype=np.uint8)
|
||||
colors[np.isin(labels, (11, 15))] = [20, 220, 170]
|
||||
colors[labels == 13] = [220, 40, 50]
|
||||
colors[np.isin(labels, (8, 23))] = [240, 200, 20]
|
||||
Image.blend(image, Image.fromarray(colors), .45).save(output / (key + ".jpg"))
|
||||
ids, counts = np.unique(labels, return_counts=True)
|
||||
rows.append(dict(case=key, inference_seconds=elapsed,
|
||||
input_shape=list(inputs["pixel_values"].shape),
|
||||
gpu_peak_bytes=torch.cuda.max_memory_allocated(),
|
||||
pedestrian_fraction=float(np.isin(labels, (11, 15)).mean()),
|
||||
road_fraction=float((labels == 13).mean()),
|
||||
classes={model.config.id2label[int(i)]: int(n) for i, n in zip(ids, counts)}))
|
||||
(output / "results.json").write_text(json.dumps(rows, indent=2))
|
||||
print(json.dumps(rows[-1]), flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,59 @@
|
||||
"""One offline GPU job under a Core simulation reservation, with exact cleanup."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--reservation", type=Path, required=True)
|
||||
parser.add_argument("--inputs", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--context", action="store_true")
|
||||
parser.add_argument("--root", type=Path, default=Path("D:/NDC_MISSIONCORE/runtime/simulation"))
|
||||
args = parser.parse_args()
|
||||
receipt = json.loads(args.reservation.read_text())
|
||||
assert receipt["state"] == "reserved" and receipt["owner_id"].startswith("airun-")
|
||||
assert not (args.root / "state/active.json").exists(), "A rover run is active"
|
||||
assert 0 <= (datetime.now(UTC) - datetime.fromisoformat(receipt["utc"])).total_seconds() < 900
|
||||
adapter = Path(__file__).parent.resolve()
|
||||
descriptor = json.loads((adapter / "model.json").read_text())
|
||||
assets = args.root / "assets" / descriptor["asset_directory"] / descriptor["revision"]
|
||||
assert (assets / "installation.json").is_file()
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
identity = None
|
||||
begin = time.monotonic()
|
||||
try:
|
||||
identity = subprocess.check_output([
|
||||
"docker", "run", "-d", "--name", "ndc-mapillary-qualification-" + receipt["owner_id"][-8:],
|
||||
"--gpus", "all", "--cpus", "3", "--memory", "6g",
|
||||
"--label", "com.nodedc.product=mission-core", "--label", "com.nodedc.stack=ai-polygon-qualification",
|
||||
"--label", "com.nodedc.role=qualification", "--label", "com.nodedc.managed-by=ai-polygon-qualification",
|
||||
"--mount", f"type=bind,source={adapter},target=/adapter,readonly",
|
||||
"--mount", f"type=bind,source={assets},target=/assets,readonly",
|
||||
"--mount", f"type=bind,source={args.inputs.resolve()},target=/inputs,readonly",
|
||||
"--mount", f"type=bind,source={args.output.resolve()},target=/evidence",
|
||||
"--entrypoint", "/opt/conda/envs/goose/bin/python",
|
||||
"sha256:f37681beb9feecee991e71a60a68259f15b56b168c939db3c3cb259c322e9536",
|
||||
"-B", "/adapter/qualify.py",
|
||||
*(["--context"] if args.context else []),
|
||||
], text=True).strip()
|
||||
result = subprocess.check_output(["docker", "wait", identity], timeout=240, text=True).strip()
|
||||
logs = subprocess.check_output(["docker", "logs", identity], stderr=subprocess.STDOUT, text=True)
|
||||
(args.output / "execution.log").write_text(logs)
|
||||
print(logs[-14000:])
|
||||
assert result == "0", "Model qualification failed: exit " + result
|
||||
finally:
|
||||
released = identity is None or subprocess.run(["docker", "rm", "-f", identity], capture_output=True).returncode == 0
|
||||
(args.output / "cleanup.json").write_text(json.dumps(dict(
|
||||
owner_id=receipt["owner_id"], released=released, utc=datetime.now(UTC).isoformat(),
|
||||
elapsed_seconds=time.monotonic() - begin)))
|
||||
assert released
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Pinned urban surface inference; potential crossings grant no driving authority."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
|
||||
|
||||
|
||||
def main():
|
||||
descriptor = json.loads(Path(__file__).with_name("model.json").read_text())
|
||||
for name, expected in descriptor["files"].items():
|
||||
digest = hashlib.sha256()
|
||||
with (Path("/assets") / name).open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
if digest.hexdigest() != expected:
|
||||
raise RuntimeError("Mapillary asset identity changed: " + name)
|
||||
processor = AutoImageProcessor.from_pretrained("/assets", local_files_only=True)
|
||||
model = Mask2FormerForUniversalSegmentation.from_pretrained("/assets", local_files_only=True).cuda().eval()
|
||||
torch.set_num_threads(3)
|
||||
|
||||
def infer(rgb):
|
||||
# Preserve the existing central-square pixel geometry. 768 is an
|
||||
# explicitly qualified processor override, not a checkpoint default.
|
||||
image = Image.fromarray(rgb).crop((100, 0, 700, 600))
|
||||
inputs = processor(images=image, return_tensors="pt", size={"height": 768, "width": 768}).to("cuda")
|
||||
with torch.inference_mode():
|
||||
output = model(**inputs)
|
||||
masks = torch.nn.functional.interpolate(output.masks_queries_logits,
|
||||
size=(512, 512), mode="bilinear", align_corners=False).sigmoid()
|
||||
classes = output.class_queries_logits.softmax(-1)[..., :-1]
|
||||
scores = torch.einsum("bqc,bqhw->bchw", classes, masks)
|
||||
score, labels = scores.max(1)
|
||||
# Query-aggregated scores are not calibrated class probabilities.
|
||||
# Require both absolute evidence and dominance over other classes.
|
||||
known = (score >= .55) & (score / scores.sum(1).clamp_min(1e-8) >= .55)
|
||||
labels = labels[0].cpu().numpy().astype(np.uint8)
|
||||
known = known[0].cpu().numpy()
|
||||
candidate = np.isin(labels, (7, 8, 9, 10, 11, 13, 14, 15, 23)) & known
|
||||
return labels.tobytes() + candidate.astype(np.uint8).tobytes() + known.astype(np.uint8).tobytes()
|
||||
|
||||
infer(np.zeros((600, 800, 3), dtype=np.uint8))
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def setup(self):
|
||||
super().setup()
|
||||
self.connection.settimeout(10)
|
||||
|
||||
def reply(self, status, body):
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/octet-stream")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self):
|
||||
self.reply(200 if self.path == "/ready" else 404,
|
||||
b'{"model":"mask2former-mapillary65"}')
|
||||
|
||||
def do_POST(self):
|
||||
if self.path != "/infer" or self.headers.get("Content-Length") != "1440000":
|
||||
self.reply(400, b"Expected 800x600 raw RGB uint8")
|
||||
return
|
||||
try:
|
||||
raw = self.rfile.read(1440000)
|
||||
if len(raw) != 1440000:
|
||||
raise ValueError("Incomplete camera frame")
|
||||
self.reply(200, infer(np.frombuffer(raw, np.uint8).reshape(600, 800, 3)))
|
||||
except (TimeoutError, ValueError, RuntimeError):
|
||||
self.reply(500, b"Surface inference failed")
|
||||
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
HTTPServer(("0.0.0.0", 8010), Handler).serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Metric terrain fixtures for the selected tracked chassis, independent of maps.
|
||||
|
||||
These are engineering samples, not claims of ASTM conformity or building-code
|
||||
stair dimensions. NIST's separation of stairs, ramps and gaps informs the cases.
|
||||
Fixtures are simulation truth; planners must receive sensor observations only.
|
||||
"""
|
||||
import math
|
||||
|
||||
|
||||
def fixtures():
|
||||
rows = []
|
||||
def add(name, profile, goal, kind):
|
||||
rows.append(dict(name=name, kind=kind, profile_xz_m=profile,
|
||||
goal_x_m=goal, start_z_m=profile[0][1], target_mps=.3))
|
||||
add('level', [(-4, 0), (8, 0)], 3.5, 'control')
|
||||
for rise, tread, count in ((.15, .30, 6), (.18, .30, 5), (.15, .60, 4)):
|
||||
for sign in (1, -1):
|
||||
z = 0 if sign > 0 else rise * count
|
||||
points = [(-4, z), (1, z)]
|
||||
for i in range(count):
|
||||
x = 1 + i*tread
|
||||
points.extend([(x, z), (x, z+sign*rise), (x+tread, z+sign*rise)])
|
||||
z += sign*rise
|
||||
points.append((8, z))
|
||||
add(f'stairs_{round(rise*100)}_{round(tread*100)}_' + ('up' if sign>0 else 'down'),
|
||||
points, 1+count*tread+.7, 'stairs')
|
||||
for angle in (15, 25, 35, 45):
|
||||
rise = 2*math.tan(math.radians(angle))
|
||||
add(f'ramp_{angle}', [(-4,0),(1,0),(3,rise),(8,rise)], 3.7, 'ramp')
|
||||
add('depression_30_ramped', [(-4,0),(1,0),(2,-.3),(3,-.3),(4,0),(8,0)], 4.7, 'depression')
|
||||
return rows
|
||||
|
||||
|
||||
def surface_mesh(profile, width=3):
|
||||
points, faces = [], []
|
||||
for a, b in zip(profile, profile[1:]):
|
||||
if a == b:
|
||||
continue
|
||||
offset = len(points)
|
||||
points.extend([(a[0],-width/2,a[1]), (b[0],-width/2,b[1]),
|
||||
(b[0],width/2,b[1]), (a[0],width/2,a[1])])
|
||||
faces.extend([offset,offset+1,offset+2,offset,offset+2,offset+3])
|
||||
return points, faces
|
||||
@@ -6,16 +6,24 @@ import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(ROOT.parents[1] / "src"))
|
||||
NAVIGATION_NAME = "ndc-mission-core-ai-module-simulation-cmu-navigation"
|
||||
NAV2_NAME = "ndc-mission-core-ai-module-simulation-nav2-navigation"
|
||||
TERRAIN_NAME = "ndc-mission-core-ai-module-observed-terrain"
|
||||
NAMES = (
|
||||
"ndc-ai-polygon-ddrnet",
|
||||
"ndc-ai-polygon-segformer",
|
||||
"ndc-ai-polygon-cityscapes",
|
||||
"ndc-ai-polygon-mapillary",
|
||||
"ndc-ai-polygon-sam3",
|
||||
"ndc-ai-polygon-rfdetr",
|
||||
NAVIGATION_NAME,
|
||||
NAV2_NAME,
|
||||
TERRAIN_NAME,
|
||||
)
|
||||
|
||||
|
||||
@@ -24,23 +32,60 @@ def sha256(path):
|
||||
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
|
||||
|
||||
def docker(*args, check=True):
|
||||
def docker(*args, check=True, timeout=120):
|
||||
return subprocess.run(
|
||||
["docker", *args], check=check, capture_output=True, text=True, timeout=120
|
||||
["docker", *args], check=check, capture_output=True, text=True, timeout=timeout
|
||||
)
|
||||
|
||||
|
||||
def wait_for_docker(status, sleep=time.sleep):
|
||||
"""Desktop's engine may start after the login task; don't exhaust task retries.
|
||||
|
||||
Only engine availability is retried. Missing pinned assets and invalid
|
||||
identities still fail the subsequent preflight, with their original error.
|
||||
"""
|
||||
from local_state import write_json
|
||||
|
||||
while True:
|
||||
try:
|
||||
response = docker("version", "--format", "{{.Server.Version}}", check=False, timeout=8)
|
||||
if response.returncode == 0 and response.stdout.strip():
|
||||
return
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
write_json(status, {"state": "waiting-docker", "utc": datetime.now(UTC).isoformat()})
|
||||
sleep(3)
|
||||
|
||||
|
||||
class ModelStack:
|
||||
def __init__(self):
|
||||
self.profile_path = ROOT / "models.worker-006.json"
|
||||
self.profile = json.loads(self.profile_path.read_text())
|
||||
self.ids = []
|
||||
|
||||
def preflight(self):
|
||||
def preflight(self, selection=None):
|
||||
from k1link.simulation.ai_polygon.composition import compose
|
||||
|
||||
compose(ROOT) # Portable graph admission happens before any Isaac boot.
|
||||
for model in [*self.profile["models"], self.profile["navigation"]]:
|
||||
graph = compose(ROOT, selection) # Admission before any Isaac boot.
|
||||
selected = {node.module.module_id for node in graph.nodes}
|
||||
providers = {
|
||||
'simulation-ddrnet-goose': 'ddrnet-goose-pytorch-reference',
|
||||
'simulation-rf-detr': 'rf_detr_large',
|
||||
'simulation-segformer-ade': 'segformer-b2-ade150',
|
||||
'simulation-segformer-cityscapes': 'segformer-b2-cityscapes19',
|
||||
'simulation-mask2former-mapillary': 'mask2former-mapillary65',
|
||||
'simulation-sam3-surfaces': 'sam3-litetext-surfaces',
|
||||
}
|
||||
required = {providers[module] for module in selected if module in providers}
|
||||
models = [model for model in self.profile['models'] if model['id'] in required]
|
||||
if {model['id'] for model in models} != required:
|
||||
raise RuntimeError('Selected simulation model descriptor is missing')
|
||||
if 'simulation-cmu-navigation' in selected:
|
||||
models.append(self.profile['navigation'])
|
||||
if 'simulation-nav2-navigation' in selected:
|
||||
models.extend((self.profile['nav2'],
|
||||
dict(image=self.profile['nav2']['terrain_image'])))
|
||||
for model in models:
|
||||
for key in ("checkpoint", "runner"):
|
||||
if key in model and sha256(model[key]) != model[key + "_sha256"]:
|
||||
raise RuntimeError("Simulation model identity changed: " + model["id"])
|
||||
@@ -49,23 +94,35 @@ class ModelStack:
|
||||
).stdout.strip()
|
||||
if actual != model["image"]:
|
||||
raise RuntimeError("Simulation model image is unavailable")
|
||||
if sha256(self.profile["labels"]) != self.profile["labels_sha256"]:
|
||||
if ('simulation-ddrnet-goose' in selected
|
||||
and sha256(self.profile["labels"]) != self.profile["labels_sha256"]):
|
||||
raise RuntimeError("GOOSE label table changed")
|
||||
|
||||
def start(self, cancelled=None, on_acquired=None, selection=None):
|
||||
def start(self, cancelled=None, on_acquired=None, selection=None, inputs_path=None):
|
||||
from k1link.simulation.ai_polygon.composition import compose
|
||||
|
||||
graph = compose(ROOT, selection)
|
||||
services = {
|
||||
"simulation-ddrnet-goose": "ddrnet",
|
||||
"simulation-segformer-ade": "segformer",
|
||||
"simulation-segformer-cityscapes": "cityscapes",
|
||||
"simulation-mask2former-mapillary": "mapillary",
|
||||
"simulation-sam3-surfaces": "sam3",
|
||||
"simulation-rf-detr": "detector",
|
||||
}
|
||||
module_ids = [node.module.module_id for node in graph.nodes]
|
||||
installed = {*services, "simulation-cmu-navigation", "simulation-waypoint-mission"}
|
||||
installed = {
|
||||
*services,
|
||||
"simulation-cmu-navigation",
|
||||
"simulation-nav2-navigation",
|
||||
"simulation-waypoint-mission",
|
||||
"simulation-declared-route",
|
||||
}
|
||||
if set(module_ids) - installed:
|
||||
raise ValueError("Uninstalled simulation provider")
|
||||
self.preflight()
|
||||
if "simulation-nav2-navigation" in module_ids and inputs_path is None:
|
||||
raise ValueError("Nav2 requires immutable run inputs")
|
||||
self.preflight(selection)
|
||||
for name in NAMES:
|
||||
if docker("container", "inspect", name, check=False).returncode == 0:
|
||||
raise RuntimeError(
|
||||
@@ -76,7 +133,17 @@ class ModelStack:
|
||||
try:
|
||||
selected = [services[module] for module in module_ids if module in services]
|
||||
docker("compose", "-f", str(ROOT / "compose.models.yaml"), "up", "-d", *selected)
|
||||
if "simulation-nav2-navigation" in module_ids:
|
||||
self.start_nav2(graph, inputs_path)
|
||||
if "simulation-cmu-navigation" in module_ids:
|
||||
input_mount = []
|
||||
if inputs_path is not None:
|
||||
input_mount = [
|
||||
"--mount",
|
||||
f"type=bind,source={Path(inputs_path).resolve()},target=/run-inputs.json,readonly",
|
||||
"-e",
|
||||
"MISSIONCORE_RUN_INPUTS=/run-inputs.json",
|
||||
]
|
||||
docker(
|
||||
"run",
|
||||
"-d",
|
||||
@@ -102,6 +169,7 @@ class ModelStack:
|
||||
"127.0.0.1:18093:8010",
|
||||
"--mount",
|
||||
f"type=bind,source={ROOT},target=/adapter,readonly",
|
||||
*input_mount,
|
||||
self.profile["navigation"]["image"],
|
||||
)
|
||||
finally:
|
||||
@@ -139,6 +207,33 @@ class ModelStack:
|
||||
time.sleep(0.5)
|
||||
raise TimeoutError("Simulation models did not become ready")
|
||||
|
||||
def start_nav2(self, graph, inputs_path):
|
||||
if inputs_path is None:
|
||||
raise ValueError("Nav2 requires immutable run inputs")
|
||||
common = ["--restart", "no", "--read-only", "--cpus", "3", "--memory", "2g",
|
||||
"--pids-limit", "256", "--cap-drop", "ALL", "--security-opt", "no-new-privileges",
|
||||
"--tmpfs", "/tmp:rw,size=256m",
|
||||
"--label", "com.nodedc.product=mission-core", "--label", "com.nodedc.stack=ai-polygon",
|
||||
"--label", "com.nodedc.role=ai-module", "--label", "com.nodedc.managed-by=ai-polygon-worker",
|
||||
"--label", "com.nodedc.composition-sha256="+graph.sha256,
|
||||
"-e", "ROS_LOCALHOST_ONLY=1", "-e", "ROS_DOMAIN_ID=83",
|
||||
"-e", "ROS_LOG_DIR=/tmp/ros-logs", "-e", "PYTHONDONTWRITEBYTECODE=1",
|
||||
"-e", "PYTHONPATH=/adapter", "--mount", f"type=bind,source={ROOT},target=/adapter,readonly",
|
||||
"--mount", f"type=bind,source={Path(inputs_path).resolve()},target=/run-inputs.json,readonly",
|
||||
"-e", "MISSIONCORE_RUN_INPUTS=/run-inputs.json"]
|
||||
# Two immutable dependency environments, one private ROS namespace.
|
||||
# The terrain container hosts the loopback-bound HTTP port; only the
|
||||
# Nav2 adapter in the shared namespace listens on that port.
|
||||
docker("run", "-d", "--name", TERRAIN_NAME, "--ipc", "shareable",
|
||||
"-p", "127.0.0.1:18093:8010", *common, "--entrypoint", "/bin/bash",
|
||||
self.profile['nav2']['terrain_image'], "-c",
|
||||
"source /opt/ros/humble/setup.bash && source /opt/cmu/install/setup.bash "
|
||||
"&& exec python3 /adapter/nav2/terrain_node.py")
|
||||
docker("run", "-d", "--name", NAV2_NAME, "--network", "container:"+TERRAIN_NAME,
|
||||
"--ipc", "container:"+TERRAIN_NAME, *common,
|
||||
self.profile['nav2']['image'],
|
||||
"python3", "/adapter/nav2/server.py")
|
||||
|
||||
def stop(self):
|
||||
failures = []
|
||||
for identity in self.ids:
|
||||
|
||||
@@ -34,19 +34,56 @@
|
||||
"preprocess": "RGB centre 600-square crop; pinned processor bilinear 512, ImageNet normalization; logits bilinear 512; candidate confidence >=0.55",
|
||||
"config_sha256": "ee7400840fdb1e5045f0b2eba78bf053df8e33a309c4acec31705a48c8cc5c00",
|
||||
"processor_sha256": "8039d1d210abaa7117ad78e58cdfd6141a2ec72c03dae891b3cd76737e422c6c"
|
||||
},
|
||||
{
|
||||
"id": "segformer-b2-cityscapes19",
|
||||
"image": "sha256:f37681beb9feecee991e71a60a68259f15b56b168c939db3c3cb259c322e9536",
|
||||
"checkpoint": "D:/NDC_MISSIONCORE/runtime/simulation/assets/segformer-b2-cityscapes/d633b2072669ca68d8f8e309de9b52bfdbf6bf72/pytorch_model.bin",
|
||||
"checkpoint_sha256": "584d72ace8c17c5683c198e1a4c3eda2e1026bafc02711ac5e5a4dc097bd05fe",
|
||||
"revision": "d633b2072669ca68d8f8e309de9b52bfdbf6bf72",
|
||||
"preprocess": "RGB centre 600-square crop; pinned Cityscapes processor bilinear 512, ImageNet normalization; logits bilinear 512; candidate confidence >=0.55",
|
||||
"config_sha256": "3bafe3a84c87270732bb383f6ef33801d1cd441907da8cedc2c8a4986276945d",
|
||||
"processor_sha256": "d96ab2cb112985c19d5ea32f1d1f2369104fc78b1379f5ce26e33ca8646202a7"
|
||||
},
|
||||
{
|
||||
"id": "mask2former-mapillary65",
|
||||
"image": "sha256:f37681beb9feecee991e71a60a68259f15b56b168c939db3c3cb259c322e9536",
|
||||
"checkpoint": "D:/NDC_MISSIONCORE/runtime/simulation/assets/mask2former-mapillary/2cc022513f0012ff47d4438516284fd0946a196a/pytorch_model.bin",
|
||||
"checkpoint_sha256": "8120d77b194b34527b5937a576c36291ae7e76157f57a22433480c19d71e1551",
|
||||
"revision": "2cc022513f0012ff47d4438516284fd0946a196a",
|
||||
"preprocess": "RGB centre 600-square crop; pinned processor with explicit 768-square resize; query logits interpolated to 512; score and class dominance >=0.55; no crossing authority",
|
||||
"config_sha256": "b40bec8d82de3b53ef967dce0496c37de520b69466f1a8d2f6c035700cbae9f3",
|
||||
"processor_sha256": "22ef0608c7add19c5e9a64f8eeba95b7d3d1237ef20bf14efead9d8bc671da9f"
|
||||
},
|
||||
{
|
||||
"id": "sam3-litetext-surfaces",
|
||||
"image": "sha256:727ff5ab1a9eec1704ec15f9bef1b4ae5c47912aa9e1eff622f90a1dc3045cff",
|
||||
"checkpoint": "D:/NDC_MISSIONCORE/runtime/simulation/assets/sam3-litetext-s1/85b05896928f974e308f889d7ccb2eefc069de98/sam3_litetext/sam3_litetext_mobileclip_s1_ctx16.pt",
|
||||
"checkpoint_sha256": "2cb918109a0082292cb414f48ae077f4351a56279f05ab67d56adc8b24f21731",
|
||||
"revision": "85b05896928f974e308f889d7ccb2eefc069de98",
|
||||
"preprocess": "Full RGB 800x600; pinned SAM3 processor resize 1008, normalization [-1,1]; BF16; independent masks: sidewalk confidence >=0.3, roadway/crosswalk/wall >=0.5; exclusions veto overlaps; crop output to central600 and nearest512; no crossing authority"
|
||||
}
|
||||
],
|
||||
"labels": "D:/NDC_MISSIONCORE/runtime/assets/observatory-portable/lab-v1-static-files-v1/ddrnet-goose-mapping.csv",
|
||||
"labels_sha256": "88ae319ba5a3877dd3ae0773f693a6a5fdc283934140de9dfaff029108aefd7f",
|
||||
"navigation": {
|
||||
"id": "cmu-terrain-navigation",
|
||||
"image": "sha256:698228d0d378b166ceaf299aa86ab95b5e74179837532f2378c036c7f7621dcc",
|
||||
"image": "sha256:8517fd5d13406648907c87dd4adf771238c6a3a30fcedd555ca5a5287edebc16",
|
||||
"upstream_commit": "158e67b31b644ed1e8b06eb1d7f70e183cc62591"
|
||||
},
|
||||
"default_modules": [
|
||||
"simulation-segformer-ade",
|
||||
"simulation-ddrnet-goose",
|
||||
"simulation-rf-detr",
|
||||
"simulation-cmu-navigation",
|
||||
"simulation-waypoint-mission"
|
||||
]
|
||||
],
|
||||
"nav2": {
|
||||
"id": "nav2-humble-rover",
|
||||
"image": "sha256:946a333254e5a6805571b53b8f689fcbb686fc90b69518cf78df16c679c475f1",
|
||||
"upstream_commit": "0f8fda36ca1b84a840ad9b72a6c71776eefa6790",
|
||||
"version": "1.1.17",
|
||||
"terrain_image": "sha256:7e9964bb182e963eea0d36f410ad145e6f88e9f2ef41e867cc983be7b967d053",
|
||||
"terrain_upstream_commit": "158e67b31b644ed1e8b06eb1d7f70e183cc62591",
|
||||
"preparation_sha256": "7b5c949fdd0d1f25d5af1b825a9c2e55838c412371aea34a733a7307e0762637"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,36 +1,165 @@
|
||||
"""Physics-clock command envelope; perception remains asynchronous.
|
||||
"""Physics-clock adapter for the common two-side command contract.
|
||||
|
||||
Limit wheel-surface acceleration without delaying a safety reduction. Scaling
|
||||
both sides together preserves the planner's requested curvature. Stops bypass
|
||||
the ramp, as required by the already qualified collision/braking envelope.
|
||||
This is a simulation actuator, not a VESC controller or a motor calibration.
|
||||
The profile declares simulation-only limits and the contact proxy's stop mode.
|
||||
Zero intent is immediate; actual deceleration belongs to the physics adapter.
|
||||
"""
|
||||
|
||||
CONTROL_PROFILE = {
|
||||
"clock": "physics-pre-step",
|
||||
"rate_hz": 60,
|
||||
"wheel_surface_acceleration_mps2": 0.2,
|
||||
"safety_reductions": "immediate",
|
||||
"authority": "simulation-only",
|
||||
}
|
||||
from rover_profile import ROBOT_DOCUMENT
|
||||
|
||||
CONTROL_PROFILE = ROBOT_DOCUMENT["control"]
|
||||
|
||||
|
||||
def reserve_chassis_speed(velocity, yaw_rate, maximum_mps, reserve_mps):
|
||||
"""Leave declared tracking-error room below a run's body-speed ceiling.
|
||||
|
||||
Scale moving arcs together; stationary pivots and safety zero retain their
|
||||
meaning. This is a planning reserve, not a guarantee about physical speed.
|
||||
"""
|
||||
from k1link.fleet.differential_drive import finite
|
||||
|
||||
finite(velocity, yaw_rate, maximum_mps, reserve_mps)
|
||||
if not 0 <= reserve_mps < maximum_mps:
|
||||
raise ValueError("Speed reserve must be below the run speed ceiling")
|
||||
scale = min(1.0, (maximum_mps - reserve_mps) / max(abs(velocity), 1e-12))
|
||||
return velocity * scale, yaw_rate * scale
|
||||
|
||||
|
||||
class DriveEnvelope:
|
||||
def __init__(self, track_width=0.9, acceleration=0.2):
|
||||
self.half_track = track_width / 2
|
||||
self.acceleration = acceleration
|
||||
self.wheels = (0.0, 0.0)
|
||||
def __init__(self, track_width=None, acceleration=None, *, control=None):
|
||||
from k1link.fleet.differential_drive import DriveLimits, TwoSideDrive
|
||||
|
||||
control = CONTROL_PROFILE if control is None else control
|
||||
self.limits = DriveLimits(
|
||||
track_centres_m=(
|
||||
ROBOT_DOCUMENT["physics"]["track_width_m"] if track_width is None else track_width
|
||||
),
|
||||
max_side_speed_mps=control["max_side_speed_mps"],
|
||||
acceleration_mps2=(
|
||||
control["acceleration_mps2"] if acceleration is None else acceleration
|
||||
),
|
||||
deceleration_mps2=control["deceleration_mps2"],
|
||||
max_step_seconds=control["max_step_seconds"],
|
||||
)
|
||||
self.drive = TwoSideDrive(self.limits)
|
||||
self.requested = self.drive.applied
|
||||
|
||||
@property
|
||||
def wheels(self):
|
||||
return self.drive.applied.left_mps, self.drive.applied.right_mps
|
||||
|
||||
def step(self, velocity, yaw_rate, dt, *, stop=False):
|
||||
requested = (velocity - yaw_rate * self.half_track, velocity + yaw_rate * self.half_track)
|
||||
if stop or max(map(abs, requested)) < 1e-8:
|
||||
self.wheels = (0.0, 0.0)
|
||||
return 0.0, 0.0
|
||||
scale = 1.0
|
||||
for old, new in zip(self.wheels, requested, strict=True):
|
||||
# Reversal starts from zero; never retain motion in the old direction.
|
||||
prior = abs(old) if old * new >= 0 else 0.0
|
||||
if abs(new) > prior:
|
||||
scale = min(scale, (prior + self.acceleration * max(0.0, dt)) / abs(new))
|
||||
self.wheels = tuple(value * scale for value in requested)
|
||||
return velocity * scale, yaw_rate * scale
|
||||
from k1link.fleet.differential_drive import SideSpeeds
|
||||
|
||||
self.requested = SideSpeeds.from_twist(velocity, yaw_rate, self.limits.track_centres_m)
|
||||
return self.drive.step(self.requested, dt, stop=stop).twist(self.limits.track_centres_m)
|
||||
|
||||
|
||||
class ChassisSpeedFeedback:
|
||||
"""Inner speed correction for autonomous chassis intent on a pitching body.
|
||||
|
||||
The lower contact moves at v_COM - height * pitch_rate. A belt encoder
|
||||
alone therefore does not regulate COM speed over uneven terrain. This
|
||||
controller uses measured forward speed and angular velocity; it only
|
||||
changes bounded belt targets. Native forces still own all body motion.
|
||||
"""
|
||||
|
||||
def __init__(self, profile, contact_height_m, track_centres_m, max_side_mps):
|
||||
from k1link.fleet.differential_drive import finite
|
||||
|
||||
self.gain = profile["proportional_gain"]
|
||||
self.maximum = profile["max_correction_mps"]
|
||||
self.height = contact_height_m
|
||||
self.track_centres = track_centres_m
|
||||
self.max_side = max_side_mps
|
||||
finite(self.gain, self.maximum, self.height, self.track_centres, self.max_side)
|
||||
if min(self.gain, self.maximum, self.height, self.track_centres, self.max_side) <= 0:
|
||||
raise ValueError("Invalid chassis feedback parameters")
|
||||
self.metrics = {}
|
||||
|
||||
def step(self, velocity, yaw_rate, measured_forward_mps, pitch_rate_rps):
|
||||
from k1link.fleet.differential_drive import SideSpeeds, finite
|
||||
|
||||
finite(velocity, yaw_rate, measured_forward_mps, pitch_rate_rps)
|
||||
correction = 0.0
|
||||
if velocity != 0.0 or yaw_rate != 0.0:
|
||||
correction = max(
|
||||
-self.maximum,
|
||||
min(
|
||||
self.maximum,
|
||||
-self.height * pitch_rate_rps + self.gain * (velocity - measured_forward_mps),
|
||||
),
|
||||
)
|
||||
if velocity == 0.0 and yaw_rate != 0.0:
|
||||
# A pivot requests zero body translation, not zero feedback.
|
||||
# Counter measured drift with a common belt adjustment, bounded
|
||||
# by the opposed-side intent so neither side reverses and the
|
||||
# requested yaw differential is retained. Safety zero stays zero.
|
||||
pivot_room = abs(yaw_rate) * self.track_centres / 2
|
||||
correction = max(-pivot_room, min(pivot_room, correction))
|
||||
corrected = velocity + correction
|
||||
# Feedback may reduce translation to zero, but cannot request an
|
||||
# unplanned reversal. A pivot retains its opposed side directions.
|
||||
if velocity * corrected < 0:
|
||||
corrected = 0.0
|
||||
nominal = SideSpeeds.from_twist(velocity, yaw_rate, self.track_centres)
|
||||
proposed = SideSpeeds.from_twist(corrected, yaw_rate, self.track_centres)
|
||||
# The nominal envelope owns each side's reversal through zero. A
|
||||
# common correction must also respect a stationary/turning inner belt.
|
||||
target = SideSpeeds(
|
||||
*(
|
||||
value if intent * value > 0 else 0.0
|
||||
for intent, value in zip(
|
||||
vars(nominal).values(), vars(proposed).values(), strict=True
|
||||
)
|
||||
)
|
||||
).bounded(self.max_side)
|
||||
applied = target.twist(self.track_centres)
|
||||
self.metrics = dict(
|
||||
nominal_twist=[velocity, yaw_rate],
|
||||
measured_forward_mps=measured_forward_mps,
|
||||
pitch_rate_rps=pitch_rate_rps,
|
||||
correction_mps=correction,
|
||||
actuator_twist=list(applied),
|
||||
)
|
||||
return applied
|
||||
|
||||
|
||||
class RoverMotionControl:
|
||||
"""The same autonomous intent -> belt target path for runtime and rigs.
|
||||
|
||||
Physics remains the sole owner of actual body motion. A rig supplies the
|
||||
same measured forward velocity and pitch rate as the live callback.
|
||||
"""
|
||||
|
||||
def __init__(self, robot, maximum_mps):
|
||||
self.maximum = maximum_mps
|
||||
physics, control = robot["physics"], robot["control"]
|
||||
self.envelope = DriveEnvelope(track_width=physics["track_width_m"], control=control)
|
||||
settings = control.get("chassis_speed_feedback", {})
|
||||
self.feedback = None
|
||||
self.reserve = 0.0
|
||||
if settings.get("enabled", False):
|
||||
self.feedback = ChassisSpeedFeedback(
|
||||
settings,
|
||||
robot.get("tracked_contact", {}).get(
|
||||
"chassis_com_height_m", physics["body_contact_height_m"]
|
||||
),
|
||||
physics["track_width_m"],
|
||||
control["max_side_speed_mps"],
|
||||
)
|
||||
self.reserve = (
|
||||
maximum_mps * settings["body_speed_reserve_fraction"]
|
||||
if "body_speed_reserve_fraction" in settings
|
||||
else settings.get("body_speed_reserve_mps", 0.0)
|
||||
)
|
||||
reserve_chassis_speed(0, 0, maximum_mps, self.reserve)
|
||||
|
||||
def step(self, velocity, yaw_rate, dt, forward_mps, pitch_rps, *, stop=False):
|
||||
if self.feedback is not None:
|
||||
velocity, yaw_rate = reserve_chassis_speed(
|
||||
velocity, yaw_rate, self.maximum, self.reserve
|
||||
)
|
||||
velocity, yaw_rate = self.envelope.step(velocity, yaw_rate, dt, stop=stop)
|
||||
if self.feedback is not None:
|
||||
velocity, yaw_rate = self.feedback.step(velocity, yaw_rate, forward_mps, pitch_rps)
|
||||
return velocity, yaw_rate
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Episode distance from physics-clock poses, independent of viewer polling."""
|
||||
import math
|
||||
|
||||
|
||||
def planar_twist(linear, angular, forward):
|
||||
"""Measured world velocities expressed in the rover's horizontal heading.
|
||||
|
||||
Yaw rate is the derivative of atan2(forward_y, forward_x), including pitch;
|
||||
world angular-Z alone is not that derivative on inclined ground.
|
||||
"""
|
||||
if any(len(v) != 3 or not all(math.isfinite(x) for x in v)
|
||||
for v in (linear, angular, forward)):
|
||||
raise ValueError('Invalid physical velocity observation')
|
||||
fx, fy, fz = forward
|
||||
horizontal = fx*fx + fy*fy
|
||||
if horizontal <= 1e-12:
|
||||
raise ValueError('Heading is undefined for a vertical body axis')
|
||||
length = math.sqrt(horizontal)
|
||||
vx = (linear[0]*fx + linear[1]*fy) / length
|
||||
vy = (-linear[0]*fy + linear[1]*fx) / length
|
||||
yaw = angular[2] - fz*(fx*angular[0] + fy*angular[1]) / horizontal
|
||||
return vx, vy, yaw
|
||||
|
||||
|
||||
class PlanarDistance:
|
||||
def __init__(self):
|
||||
self.metres = 0.0
|
||||
self.previous = None
|
||||
|
||||
def observe(self, xy):
|
||||
xy = tuple(xy)
|
||||
if len(xy) != 2 or not all(math.isfinite(value) for value in xy):
|
||||
raise ValueError('Invalid distance observation')
|
||||
if self.previous is not None:
|
||||
self.metres += math.dist(self.previous, xy)
|
||||
self.previous = xy
|
||||
return self.metres
|
||||
@@ -0,0 +1,315 @@
|
||||
"""Isaac implementation of the portable Rover 006 observation rig.
|
||||
|
||||
Two separated RTX fisheyes produce panorama and a calibrated digital view.
|
||||
D455 RGB and ideal first-hit depth remain separate observations. All geometry
|
||||
queries retain first-hit self occlusion; unknown depth never clears space.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
from k1link.simulation.ai_polygon.camera_optics import (
|
||||
DualFisheye,
|
||||
axes,
|
||||
fisheye_intrinsics,
|
||||
pinhole_rays,
|
||||
view_toward,
|
||||
)
|
||||
from k1link.simulation.ai_polygon.run_inputs import MOUNTED_SENSOR_SCHEMA, CONTINUOUS_SENSOR_SCHEMA
|
||||
from k1link.simulation.ai_polygon.sensor_mounts import validate_mounts
|
||||
|
||||
|
||||
class MountedSensors:
|
||||
def __init__(self, stage, rig, contact_height):
|
||||
import omni.replicator.core as rep
|
||||
from pxr import Gf, UsdGeom, UsdPhysics
|
||||
|
||||
self.rig, self.contact_height = rig, contact_height
|
||||
self.mounts = validate_mounts(rig["mounts"])
|
||||
self.optics = DualFisheye(self.mounts["insta360"])
|
||||
self.cameras, self.products, self.rgb, self.depth = [], [], [], []
|
||||
self.focal = 800 * rig["focal_length_mm"] / rig["horizontal_aperture_mm"]
|
||||
self.intrinsics = [self.focal, self.focal, 400, 300]
|
||||
rs = self.mounts["realsense"]
|
||||
self.rs_axes = axes(0, rs["pitch_degrees"])
|
||||
|
||||
def camera(name, size, spec=None):
|
||||
value = UsdGeom.Camera.Define(stage, "/World/Sensors/" + name)
|
||||
value.CreateClippingRangeAttr(Gf.Vec2f(0.001, 1000))
|
||||
value.CreateFocalLengthAttr(14)
|
||||
value.CreateHorizontalApertureAttr(36)
|
||||
value.CreateVerticalApertureAttr(36 * size[1] / size[0])
|
||||
if spec is not None:
|
||||
prim = value.GetPrim()
|
||||
if not prim.ApplyAPI("OmniLensDistortionOpenCvFisheyeAPI"):
|
||||
raise RuntimeError("Native RTX fisheye schema unavailable")
|
||||
prim.GetAttribute("omni:lensdistortion:model").Set("opencvFisheye")
|
||||
fx, fy, cx, cy = fisheye_intrinsics(spec)
|
||||
for key, number in dict(
|
||||
fx=fx,
|
||||
fy=fy,
|
||||
cx=cx,
|
||||
cy=cy,
|
||||
k1=0.0,
|
||||
k2=0.0,
|
||||
k3=0.0,
|
||||
k4=0.0,
|
||||
imageSize=Gf.Vec2i(*size),
|
||||
).items():
|
||||
if not prim.GetAttribute("omni:lensdistortion:opencvFisheye:" + key).Set(
|
||||
number
|
||||
):
|
||||
raise RuntimeError("Cannot configure fisheye parameter " + key)
|
||||
else:
|
||||
value.CreateFocalLengthAttr(1.0)
|
||||
value.CreateHorizontalApertureAttr(
|
||||
2 * math.tan(math.radians(rs["fov_degrees"][0] / 2))
|
||||
)
|
||||
value.CreateVerticalApertureAttr(
|
||||
2 * math.tan(math.radians(rs["fov_degrees"][1] / 2))
|
||||
)
|
||||
self.cameras.append((value.AddTranslateOp(), value.AddOrientOp()))
|
||||
product = rep.create.render_product(str(value.GetPath()), tuple(size))
|
||||
rgb = rep.AnnotatorRegistry.get_annotator("rgb")
|
||||
rgb.attach(product)
|
||||
self.products.append(product)
|
||||
self.rgb.append(rgb)
|
||||
if spec is not None:
|
||||
depth = rep.AnnotatorRegistry.get_annotator("distance_to_camera")
|
||||
depth.attach(product)
|
||||
self.depth.append(depth)
|
||||
|
||||
x4 = self.mounts["insta360"]
|
||||
camera("InstaLeft", x4["image_size"], x4)
|
||||
camera("InstaRight", x4["image_size"], x4)
|
||||
camera("RealSense", rs["image_size"])
|
||||
# Shapes are explicitly approximate sensor envelopes, attached to the
|
||||
# chassis. They occlude other sensors rather than being hidden from them.
|
||||
for name, center, size, pitch in (
|
||||
("Insta360", x4["body_center_m"], x4["body_size_m"], 0),
|
||||
(
|
||||
"RealSense",
|
||||
(np.asarray(rs["origin_m"]) - self.rs_axes[:, 0] * 0.014).tolist(),
|
||||
rs["body_size_m"],
|
||||
rs["pitch_degrees"],
|
||||
),
|
||||
(
|
||||
"K1",
|
||||
(np.asarray(self.mounts["k1"]["origin_m"]) - axes(0, -15)[:, 2] * 0.12).tolist(),
|
||||
self.mounts["k1"]["body_size_m"],
|
||||
-15,
|
||||
),
|
||||
):
|
||||
shape = UsdGeom.Cube.Define(stage, "/World/Rover/chassis/Sensor" + name)
|
||||
shape.CreateSizeAttr(1)
|
||||
shape.AddTranslateOp().Set(Gf.Vec3d(center[0], center[1], center[2] - contact_height))
|
||||
shape.AddRotateYOp().Set(-pitch)
|
||||
shape.AddScaleOp().Set(Gf.Vec3f(*size))
|
||||
shape.CreateDisplayColorAttr([Gf.Vec3f(0.07, 0.08, 0.09)])
|
||||
UsdPhysics.CollisionAPI.Apply(shape.GetPrim())
|
||||
|
||||
def update(self, transform):
|
||||
from pxr import Gf
|
||||
|
||||
self.body_axes = np.asarray(transform, dtype=float)[:3, :3].T
|
||||
self.position = np.array(transform.ExtractTranslation())
|
||||
x4 = self.mounts["insta360"]
|
||||
locations = [*x4["lens_centres_m"], self.mounts["realsense"]["origin_m"]]
|
||||
self.origins, self.rotations = [], []
|
||||
for (pos, rotation), local, local_axes in zip(
|
||||
self.cameras, locations, [*self.optics.lens_axes, self.rs_axes], strict=True
|
||||
):
|
||||
origin = transform.Transform(
|
||||
Gf.Vec3d(local[0], local[1], local[2] - self.contact_height)
|
||||
)
|
||||
world_axes = self.body_axes @ local_axes
|
||||
pos.Set(origin)
|
||||
rotation.Set(
|
||||
Gf.Quatf(
|
||||
Gf.Matrix4d()
|
||||
.SetLookAt(
|
||||
origin, origin + Gf.Vec3d(*world_axes[:, 0]), Gf.Vec3d(*world_axes[:, 2])
|
||||
)
|
||||
.GetInverse()
|
||||
.ExtractRotationQuat()
|
||||
)
|
||||
)
|
||||
self.origins.append(list(origin))
|
||||
self.rotations.append(world_axes)
|
||||
|
||||
def capture(self, target):
|
||||
images = [np.array(a.get_data()[..., :3], copy=True) for a in self.rgb]
|
||||
depths = [np.array(a.get_data(), copy=True) for a in self.depth]
|
||||
if any(image.shape != (640, 640, 3) for image in images[:2]) or images[2].shape != (
|
||||
480,
|
||||
640,
|
||||
3,
|
||||
):
|
||||
return None
|
||||
view = view_toward(
|
||||
self.position[:2],
|
||||
self.body_axes,
|
||||
target["xy"] if target else None,
|
||||
self.rig["camera_height_m"],
|
||||
single_lens=self.rig["schema_version"] == MOUNTED_SENSOR_SCHEMA,
|
||||
)
|
||||
if self.rig["schema_version"] == CONTINUOUS_SENSOR_SCHEMA:
|
||||
view = axes(0, -20)
|
||||
calibration = {
|
||||
"projection": "dual-origin-rectilinear/v1",
|
||||
"origin": np.mean(self.origins[:2], axis=0).tolist(),
|
||||
"rotation": (self.body_axes @ view).reshape(-1).tolist(),
|
||||
"intrinsics": self.intrinsics,
|
||||
"lens_origins": self.origins[:2],
|
||||
"lens_axes": np.stack(self.rotations[:2]).tolist(),
|
||||
"body_contact_height_m": self.contact_height,
|
||||
}
|
||||
return images[0], {
|
||||
"calibration": calibration,
|
||||
"lens_depths": depths,
|
||||
"rectified_body_axes": view,
|
||||
"camera_sources": {
|
||||
"insta360_left": images[0],
|
||||
"insta360_right": images[1],
|
||||
"realsense_rgb": images[2],
|
||||
},
|
||||
}
|
||||
|
||||
def close(self):
|
||||
for annotator, product in zip(self.rgb, self.products, strict=True):
|
||||
annotator.detach(product)
|
||||
for annotator, product in zip(self.depth, self.products[:2], strict=True):
|
||||
annotator.detach(product)
|
||||
for product in self.products:
|
||||
product.destroy()
|
||||
|
||||
|
||||
class MountedRange:
|
||||
def __init__(self, rig, contact_height):
|
||||
from terrain import RangeSensor
|
||||
|
||||
legacy = RangeSensor()
|
||||
self.query = legacy.query
|
||||
self.mounts, self.contact_height = rig["mounts"], contact_height
|
||||
k1 = self.mounts["k1"]
|
||||
elevation, azimuth = np.meshgrid(
|
||||
np.radians(np.linspace(*k1["elevation_degrees"], 21)),
|
||||
np.radians(np.arange(-180, 180, 3)),
|
||||
indexing="ij",
|
||||
)
|
||||
fan = np.stack(
|
||||
(
|
||||
np.cos(elevation) * np.cos(azimuth),
|
||||
np.cos(elevation) * np.sin(azimuth),
|
||||
np.sin(elevation),
|
||||
),
|
||||
axis=-1,
|
||||
).reshape(-1, 3)
|
||||
self.k1_directions = fan @ axes(0, -k1["tilt_forward_degrees"]).T
|
||||
rs = self.mounts["realsense"]
|
||||
w, h = rs["depth_sample_size"]
|
||||
intrinsic = [
|
||||
w / (2 * math.tan(math.radians(rs["fov_degrees"][0] / 2))),
|
||||
h / (2 * math.tan(math.radians(rs["fov_degrees"][1] / 2))),
|
||||
w / 2,
|
||||
h / 2,
|
||||
]
|
||||
self.rs_rays = pinhole_rays([w, h], intrinsic).reshape(-1, 3)
|
||||
self.rs_directions = self.rs_rays @ axes(0, rs["pitch_degrees"]).T
|
||||
self.rs_size = (h, w)
|
||||
self.view_parameters = np.asarray([
|
||||
[-180, 3, k1["elevation_degrees"][0],
|
||||
(k1["elevation_degrees"][1]-k1["elevation_degrees"][0])/20],
|
||||
intrinsic,
|
||||
], dtype=float)
|
||||
self.view_axes = np.stack((axes(0, -k1["tilt_forward_degrees"]),
|
||||
axes(0, rs["pitch_degrees"])))
|
||||
|
||||
def capture(self, transform):
|
||||
from pxr import Gf
|
||||
|
||||
points, ends, indices, view_ranges = [], [], [], []
|
||||
self.hit_paths, origins = {}, []
|
||||
self.depth = np.full(len(self.rs_rays), np.nan, np.float32)
|
||||
self.source_counts = {"k1": 0, "realsense": 0}
|
||||
rotation = np.asarray(transform, dtype=float)[:3, :3]
|
||||
for index, (key, rays) in enumerate(
|
||||
(("k1", self.k1_directions), ("realsense", self.rs_directions))
|
||||
):
|
||||
local = self.mounts[key]["origin_m"]
|
||||
origin = np.array(
|
||||
transform.Transform(Gf.Vec3d(local[0], local[1], local[2] - self.contact_height))
|
||||
)
|
||||
origins.append(origin)
|
||||
observed, clear, depth, paths = mounted_range_returns(
|
||||
self.query, origin, rays @ rotation, key, self.mounts[key], self.rs_rays[:, 0],
|
||||
organized_ranges=view_ranges,
|
||||
)
|
||||
points.extend(observed)
|
||||
ends.extend(clear)
|
||||
indices.extend([index] * len(clear))
|
||||
self.source_counts[key] = len(observed)
|
||||
for path in paths:
|
||||
self.hit_paths[path] = self.hit_paths.get(path, 0) + 1
|
||||
if key == "realsense":
|
||||
self.depth = depth
|
||||
self.depth = self.depth.reshape(self.rs_size)
|
||||
self.rays = {
|
||||
"origins": np.asarray(origins, np.float32),
|
||||
"origin_indices": np.asarray(indices, np.int32),
|
||||
"ends": np.asarray(ends, np.float32).reshape(-1, 3),
|
||||
"view_models": np.asarray([0, 1], np.int32),
|
||||
"view_sizes": np.asarray([[120, 21], list(reversed(self.rs_size))], np.int32),
|
||||
"view_axes": rotation.T @ self.view_axes,
|
||||
"view_parameters": self.view_parameters,
|
||||
"view_ranges": np.concatenate(view_ranges),
|
||||
}
|
||||
return np.asarray(points, np.float32).reshape(-1, 3)
|
||||
|
||||
|
||||
def mounted_range_returns(query, origin, directions, key, spec, forward, *, organized_ranges=None):
|
||||
"""Same first-hit rays, with range filtering outside the Python query loop.
|
||||
|
||||
Keep per-beam ownership and order. A self hit never becomes a no-return
|
||||
clearing ray; an invalid D455 depth remains unknown. Only the native query
|
||||
itself is scalar, avoiding thousands of tiny NumPy allocations per frame.
|
||||
"""
|
||||
count = len(directions)
|
||||
maximum = np.full(count, 8.0) if key == "k1" else np.minimum(8.0, 6.0 / forward)
|
||||
mount = tuple(origin)
|
||||
positions = np.full((count, 3), np.nan)
|
||||
no_hit = np.zeros(count, dtype=bool)
|
||||
paths = [None] * count
|
||||
for row, (direction, limit) in enumerate(
|
||||
zip(directions.tolist(), maximum.tolist(), strict=True)
|
||||
):
|
||||
hit = query.raycast_closest(mount, tuple(direction), limit, bothSides=True)
|
||||
if not hit["hit"]:
|
||||
no_hit[row] = True
|
||||
elif not (
|
||||
str(hit.get("rigidBody", "")).startswith("/World/Rover")
|
||||
or str(hit.get("collision", "")).startswith("/World/Rover")
|
||||
):
|
||||
positions[row] = hit["position"]
|
||||
paths[row] = str(hit.get("collision", ""))
|
||||
distances = np.linalg.norm(positions - origin, axis=1)
|
||||
depth = np.full(count, np.nan, np.float32)
|
||||
if key == "k1":
|
||||
valid = np.isfinite(distances) & (distances >= spec["range_m"][0])
|
||||
positions[no_hit] = origin + directions[no_hit] * maximum[no_hit, None]
|
||||
clear = valid | no_hit
|
||||
else:
|
||||
z = distances * forward
|
||||
low, high = spec["depth_z_range_m"]
|
||||
valid = np.isfinite(z) & (z >= low) & (z <= high)
|
||||
depth[valid] = z[valid]
|
||||
clear = valid
|
||||
if organized_ranges is not None:
|
||||
# Zero is unknown, including every self hit and invalid stereo depth.
|
||||
# Only the lidar's declared no-hit range is a free-space observation.
|
||||
ranges = np.where(valid, distances, 0.0)
|
||||
if key == "k1":
|
||||
ranges[no_hit] = maximum[no_hit]
|
||||
organized_ranges.append(ranges.astype(np.float32))
|
||||
return positions[valid], positions[clear], depth, [paths[i] for i in np.flatnonzero(valid)]
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Prepare a pinned Nav2 module in one bounded Worker-owned compiler container.
|
||||
|
||||
No host installation, registry credentials, network changes, or activation.
|
||||
The immutable base, source, scripts and completed image are recorded together.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def digest(path):
|
||||
with Path(path).open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def docker(*args, timeout=60, check=True):
|
||||
return subprocess.run(['docker', *args], capture_output=True, text=True,
|
||||
timeout=timeout, check=check)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--source', type=Path, required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--runtime', type=Path,
|
||||
default=Path('D:/NDC_MISSIONCORE/runtime/simulation'))
|
||||
args = parser.parse_args()
|
||||
root = Path(__file__).resolve().parent
|
||||
lock = json.loads((root / 'source.lock.json').read_text())
|
||||
if (args.runtime / 'state/active.json').exists():
|
||||
raise RuntimeError('A simulation is active; build was not started')
|
||||
if digest(args.source) != lock['archive_sha256']:
|
||||
raise ValueError('Nav2 source archive identity changed')
|
||||
base = docker('image', 'inspect', lock['base_image'], '--format', '{{.Id}}').stdout.strip()
|
||||
if base != lock['base_image']:
|
||||
raise ValueError('Pinned Nav2 dependency image unavailable')
|
||||
files = {name: digest(root / name) for name in
|
||||
('build.py', 'build.sh', 'entrypoint.sh', 'source.lock.json')}
|
||||
identity = hashlib.sha256(json.dumps(files, sort_keys=True).encode()).hexdigest()
|
||||
name = 'ndc-mission-core-nav2-build-' + identity[:16]
|
||||
tag = 'ndc-mission-core-nav2:1.1.17-' + identity[:16]
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
receipt = dict(started_utc=datetime.now(timezone.utc).isoformat(), files=files,
|
||||
source=lock, build_identity=identity, container_name=name,
|
||||
tag=tag, status='preparing', activated=False)
|
||||
receipt_path = args.output / 'build.json'
|
||||
|
||||
def save():
|
||||
receipt_path.write_text(json.dumps(receipt, indent=2) + '\n')
|
||||
|
||||
save()
|
||||
container = None
|
||||
started = time.monotonic()
|
||||
try:
|
||||
container = docker(
|
||||
'create', '--name', name, '--network', 'none', '--cpus', '4',
|
||||
'--memory', '8g', '--pids-limit', '512', '--cap-drop', 'ALL',
|
||||
'--security-opt', 'no-new-privileges',
|
||||
'--label', 'com.nodedc.product=mission-core',
|
||||
'--label', 'com.nodedc.stack=ai-polygon',
|
||||
'--label', 'com.nodedc.role=nav2-build',
|
||||
'--label', 'com.nodedc.managed-by=ai-polygon-preparation',
|
||||
'--label', 'com.nodedc.build-sha256=' + identity,
|
||||
'--entrypoint', '/bin/bash', base,
|
||||
'-c', 'exec timeout --signal=TERM --kill-after=15s 1800 bash /ndc-build/build.sh',
|
||||
).stdout.strip()
|
||||
receipt.update(container_id=container, status='building')
|
||||
save()
|
||||
docker('cp', str(root), container + ':/ndc-build')
|
||||
docker('cp', str(args.source.resolve()), container + ':/source.tar.gz', timeout=120)
|
||||
with (args.output / 'build.log').open('w') as log:
|
||||
subprocess.run(['docker', 'start', '-a', container], stdout=log,
|
||||
stderr=subprocess.STDOUT, timeout=1850, check=True)
|
||||
state = json.loads(docker('inspect', container).stdout)[0]['State']
|
||||
if state['ExitCode'] != 0:
|
||||
raise RuntimeError('Nav2 compiler exited: ' + str(state))
|
||||
docker('cp', container + ':/opt/ndc_nav2/packages.json', str(args.output / 'packages.json'))
|
||||
image = docker(
|
||||
'commit', '--change', 'ENTRYPOINT ["/bin/bash", "/ndc-build/entrypoint.sh"]',
|
||||
'--change', 'CMD ["bash"]', '--change', 'WORKDIR /opt/ndc_nav2',
|
||||
'--change', 'LABEL com.nodedc.role=nav2-runtime',
|
||||
container, tag, timeout=180,
|
||||
).stdout.strip()
|
||||
receipt.update(status='built', image=image,
|
||||
packages=json.loads((args.output / 'packages.json').read_text()))
|
||||
except BaseException as error:
|
||||
receipt.update(status='failed', error=type(error).__name__ + ': ' + str(error))
|
||||
raise
|
||||
finally:
|
||||
if container:
|
||||
docker('rm', '-f', container, check=False)
|
||||
remaining = docker('ps', '-a', '--no-trunc', '-q', '--filter', 'id=' + container)
|
||||
receipt['owned_container_removed'] = not remaining.stdout.strip()
|
||||
receipt['elapsed_s'] = time.monotonic() - started
|
||||
receipt['finished_utc'] = datetime.now(timezone.utc).isoformat()
|
||||
save()
|
||||
if container and not receipt['owned_container_removed']:
|
||||
raise RuntimeError('Owned Nav2 build container cleanup was not confirmed')
|
||||
print(json.dumps(receipt))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/bin/bash
|
||||
set -eo pipefail
|
||||
source /opt/ros/humble/setup.bash
|
||||
source /opt/underlay_ws/install/setup.bash
|
||||
mkdir -p /opt/ndc_nav2/src/navigation2
|
||||
cd /opt/ndc_nav2
|
||||
echo '641b6abe527eb862e9102259e3d4a33d5f8823f0bed7079adf4e785d466b6d1d /source.tar.gz' | sha256sum --check
|
||||
tar -xzf /source.tar.gz --no-same-owner --no-same-permissions --strip-components=1 -C src/navigation2
|
||||
export MAKEFLAGS=-j2 CMAKE_BUILD_PARALLEL_LEVEL=2
|
||||
colcon build --base-paths src --parallel-workers 2 \
|
||||
--packages-up-to nav2_bt_navigator nav2_behaviors nav2_smac_planner \
|
||||
dwb_critics dwb_plugins nav2_controller nav2_planner nav2_smoother \
|
||||
nav2_lifecycle_manager nav2_map_server nav2_collision_monitor nav2_velocity_smoother \
|
||||
--cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
|
||||
source install/setup.bash
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
from ament_index_python.packages import get_package_share_directory
|
||||
packages = ('nav2_bt_navigator', 'nav2_behaviors', 'nav2_smac_planner',
|
||||
'dwb_critics', 'dwb_plugins', 'dwb_core', 'nav2_controller',
|
||||
'nav2_planner', 'nav2_smoother', 'nav2_lifecycle_manager',
|
||||
'nav2_map_server', 'nav2_collision_monitor', 'nav2_velocity_smoother')
|
||||
versions = {}
|
||||
for package in packages:
|
||||
share = Path(get_package_share_directory(package))
|
||||
assert share.is_relative_to('/opt/ndc_nav2/install'), str(share)
|
||||
version = ET.parse(share / 'package.xml').findtext('version')
|
||||
assert version == '1.1.17', (package, version)
|
||||
versions[package] = version
|
||||
Path('/opt/ndc_nav2/packages.json').write_text(json.dumps(versions, indent=2))
|
||||
print(json.dumps(versions))
|
||||
PY
|
||||
chmod 755 /ndc-build/entrypoint.sh
|
||||
# Preserve upstream source/licenses and build logs; omit compiler intermediates.
|
||||
rm -rf /opt/ndc_nav2/build
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Exact output comparison for the batched prefilter, without motion authority."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from navigation import terrain_costs as costs # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
for name in ('inputs', 'robot', 'output', 'snapshot'):
|
||||
parser.add_argument('--' + name, type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
args.output.mkdir(exist_ok=False)
|
||||
original = costs._NativeNeighborhoods.candidates
|
||||
source = json.loads(args.snapshot.read_text())
|
||||
grid = np.array([[x, y] for x in np.arange(-.6, .601, .05)
|
||||
for y in np.arange(-.6, .601, .05)])
|
||||
report = dict(qualified=False, scope='exact numerical prefilter equivalence', passed=False,
|
||||
snapshot_sha256=hashlib.sha256(args.snapshot.read_bytes()).hexdigest(), cases=[])
|
||||
maximum = .8*math.tan(math.radians(25+1e-4))+.15
|
||||
try:
|
||||
for dtype in (np.float32, np.float64):
|
||||
slope = np.column_stack((grid, grid[:, 0]*math.tan(math.radians(15)),
|
||||
np.full(len(grid), .2))).astype(dtype)
|
||||
step = slope.copy(); step[:, 2] = np.where(step[:, 0] >= 0, .11, 0)
|
||||
random = np.random.default_rng(53).uniform(-.8, .8, size=(512, 4)).astype(dtype)
|
||||
random[:, 3] = .2
|
||||
cases = [('slope', slope), ('step', step),
|
||||
('gap', slope[np.abs(slope[:, 0]) > .15]), ('random', random),
|
||||
('archive', np.array(source['geometry'], dtype=dtype))]
|
||||
for count in (7, 8, 9):
|
||||
for span in (np.nextafter(dtype(maximum), dtype(-np.inf)), dtype(maximum),
|
||||
np.nextafter(dtype(maximum), dtype(np.inf))):
|
||||
points = np.zeros((count, 4), dtype=dtype)
|
||||
points[:, 0] = np.linspace(-.1, .1, count); points[-1, 2] = span
|
||||
points[:, 3] = .2
|
||||
cases.append((f'count-{count}-span-{span}', points))
|
||||
shifted = slope.copy(); shifted[:, :3] += np.array([500., -320., 10.], dtype=dtype)
|
||||
cases.append(('translated-slope', shifted))
|
||||
for name, terrain in cases:
|
||||
around = costs._NativeNeighborhoods(terrain)
|
||||
assert around.screen is not None, 'New kernel is missing'
|
||||
indices = np.flatnonzero(terrain[:, 3] > .1)
|
||||
expected = []
|
||||
for index in indices:
|
||||
nearby = around(index)
|
||||
if len(nearby) >= 8 and np.ptp(nearby[:, 2]) <= maximum:
|
||||
expected.append(index)
|
||||
assert np.array_equal(around.candidates(indices), expected), (dtype, name)
|
||||
timings, outputs = [], []
|
||||
for batched in (False, True):
|
||||
costs._NativeNeighborhoods.candidates = original if batched else lambda self, ids: ids
|
||||
normalizer = costs.TerrainCostNormalizer()
|
||||
elapsed = []
|
||||
for _ in range(4):
|
||||
started = time.perf_counter(); result, count = normalizer(terrain)
|
||||
elapsed.append((time.perf_counter()-started)*1000)
|
||||
outputs.append((result.tobytes(), count))
|
||||
timings.append(statistics.median(elapsed))
|
||||
assert all(output == outputs[0] for output in outputs), (dtype, name)
|
||||
report['cases'].append(dict(dtype=np.dtype(dtype).name, name=name,
|
||||
points=len(terrain), candidates=len(indices), retained=len(expected),
|
||||
before_ms=timings[0], after_ms=timings[1], bit_exact=True))
|
||||
costs._NativeNeighborhoods.candidates = original
|
||||
report['passed'] = True
|
||||
finally:
|
||||
costs._NativeNeighborhoods.candidates = original
|
||||
(args.output/'result.json').write_text(json.dumps(report, indent=2)+'\n')
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,241 @@
|
||||
"""Full HTTP-to-ROS adapter check on archived ranges, no physics/actuator.
|
||||
|
||||
Stationary odometry and renewed diagnostic capture times are explicit test
|
||||
inputs. The resulting proposals cannot qualify the original native route.
|
||||
"""
|
||||
import argparse
|
||||
import copy
|
||||
import http.client
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser()
|
||||
for key in ('inputs','snapshot','output'):
|
||||
parser.add_argument('--'+key,type=Path,required=True)
|
||||
parser.add_argument('--external-server', action='store_true')
|
||||
parser.add_argument('--port',type=int,default=8010)
|
||||
args=parser.parse_args()
|
||||
inputs=json.loads(args.inputs.read_text())
|
||||
snapshot=json.loads(args.snapshot.read_text())
|
||||
original=snapshot['exchange']['request']
|
||||
assert original['execution_inputs_sha256']==inputs['sha256']
|
||||
args.output.mkdir(parents=True,exist_ok=False)
|
||||
report=dict(qualified=False,authority=None,scope='HTTP/ROS integration; archived geometry, synthetic stationary odometry',passed=False)
|
||||
log=(args.output/'server.log').open('w')
|
||||
env={**os.environ,'MISSIONCORE_RUN_INPUTS':str(args.inputs)}
|
||||
process=None if args.external_server else subprocess.Popen(
|
||||
['python3',str(Path(__file__).with_name('server.py'))],env=env,
|
||||
stdout=log,stderr=subprocess.STDOUT)
|
||||
condition=threading.Lock()
|
||||
state=dict(enabled=False,observation_id='bootstrap')
|
||||
responses=[];errors=[];running=threading.Event();running.set()
|
||||
|
||||
def request(path,value=None):
|
||||
client=http.client.HTTPConnection('127.0.0.1',args.port,timeout=2)
|
||||
try:
|
||||
client.request('GET' if value is None else 'POST',path,
|
||||
body=None if value is None else json.dumps(value),
|
||||
headers={} if value is None else {'Content-Type':'application/json'})
|
||||
response=client.getresponse();body=json.loads(response.read())
|
||||
if response.status!=200:raise RuntimeError((path,response.status,body))
|
||||
return body
|
||||
finally:client.close()
|
||||
|
||||
def ready():
|
||||
deadline=time.monotonic()+15
|
||||
while True:
|
||||
try:
|
||||
receipt=request('/ready')
|
||||
assert receipt['execution_inputs_sha256']==inputs['sha256']
|
||||
return
|
||||
except (OSError,RuntimeError):
|
||||
if (process and process.poll() is not None) or time.monotonic()>=deadline:raise
|
||||
time.sleep(.05)
|
||||
|
||||
def controls():
|
||||
try:
|
||||
while running.is_set():
|
||||
with condition:current=dict(state)
|
||||
packet=dict(execution_inputs_sha256=inputs['sha256'],pose=original['pose'],
|
||||
measured_twist=[0.,0.,0.],speed_mps=0.,pose_age_seconds=.01,
|
||||
perception_age_seconds=0.,**current)
|
||||
result=request('/control',packet)
|
||||
responses.append(result)
|
||||
time.sleep(.05)
|
||||
except BaseException as error:errors.append(error)
|
||||
|
||||
thread=None
|
||||
try:
|
||||
ready()
|
||||
assert request('/reset',{})['reset']
|
||||
ready()
|
||||
thread=threading.Thread(target=controls);thread.start()
|
||||
plans=[];bootstrap=[]
|
||||
# /ready confirms transport and terrain service availability. Native
|
||||
# lifecycle activation starts with the first measured pose/plan. Give
|
||||
# that separate bootstrap the same fixed 15 s readiness deadline;
|
||||
# do not spend the twelve geometry/planning trials on inactive nodes.
|
||||
bootstrap_deadline=time.monotonic()+15
|
||||
index=0
|
||||
while len(plans)<12:
|
||||
value=copy.deepcopy(original)
|
||||
value.update(observation_id='diagnostic-'+str(index),geometry_age_seconds=0.,
|
||||
detection_age_seconds=0.)
|
||||
for sample in value['semantic_observations']:
|
||||
sample['age_seconds']=0.
|
||||
result=request('/plan',value)
|
||||
index+=1
|
||||
if result.get('diagnostic',{}).get('failure')=='waiting-for-measured-controller-state':
|
||||
bootstrap.append(result)
|
||||
assert time.monotonic()<bootstrap_deadline,'Native lifecycle readiness timed out'
|
||||
time.sleep(.15)
|
||||
continue
|
||||
plans.append(result)
|
||||
with condition:
|
||||
state.update(observation_id=value['observation_id'],enabled=result['status']=='path')
|
||||
if result['status']=='path':
|
||||
time.sleep(.2)
|
||||
break
|
||||
time.sleep(.15)
|
||||
report.update(bootstrap_plans=bootstrap,plans=plans,controls=responses)
|
||||
(args.output/'snapshot.json').write_text(json.dumps(request('/diagnostic-snapshot')))
|
||||
assert any(p['status']=='path' for p in plans),'No native path through HTTP'
|
||||
admitted=[row for row in responses if row.get('reason')=='none'
|
||||
and abs(row['speed_mps'])+abs(row['yaw_rate_rps'])>1e-6]
|
||||
report['admitted_commands']=len(admitted)
|
||||
assert admitted,'No native command passed the unchanged rover gates'
|
||||
# A fresh scan for the SAME goal may arrive before its HTTP response
|
||||
# reaches the caller. The preceding, still-fresh observation remains
|
||||
# usable. A changed motion goal must not have that permission.
|
||||
continued = []
|
||||
for index in range(6):
|
||||
with condition:previous_id=state['observation_id']
|
||||
value['observation_id']='refresh-'+str(index)
|
||||
result=request('/plan',value)
|
||||
assert result['status']=='path',result
|
||||
old=request('/control',dict(execution_inputs_sha256=inputs['sha256'],
|
||||
pose=original['pose'],measured_twist=[0.,0.,0.],speed_mps=0.,
|
||||
pose_age_seconds=.01,perception_age_seconds=0.,enabled=True,
|
||||
observation_id=previous_id))
|
||||
assert old['reason']=='none',old
|
||||
continued.append(old)
|
||||
with condition:state['observation_id']=value['observation_id']
|
||||
time.sleep(.05)
|
||||
report['same_goal_refresh_commands']=continued
|
||||
old_id=value['observation_id']
|
||||
value['observation_id']='changed-limit'
|
||||
value['max_speed_mps']*=.5
|
||||
result=request('/plan',value)
|
||||
assert result['status']=='path',result
|
||||
old=request('/control',dict(execution_inputs_sha256=inputs['sha256'],
|
||||
pose=original['pose'],measured_twist=[0.,0.,0.],speed_mps=0.,
|
||||
pose_age_seconds=.01,perception_age_seconds=0.,enabled=True,
|
||||
observation_id=old_id))
|
||||
assert old['speed_mps']==old['yaw_rate_rps']==0.,old
|
||||
report['changed_goal_rejects_previous_observation']=old
|
||||
with condition:state['observation_id']=value['observation_id']
|
||||
# A measured translation destination belongs to Smac/DWB even during
|
||||
# recovery. A bearing hint must not impose a separate in-place Spin.
|
||||
x,y,z,w=original['pose'][3:]
|
||||
yaw=math.atan2(2*(w*z+x*y),1-2*(y*y+z*z))
|
||||
value.update(recovery_orientation=True,translation_allowed=True,
|
||||
observation_id='recovery-translation',
|
||||
orientation_target=dict(key='http-recovery-bearing',xy=[
|
||||
original['pose'][0]+math.cos(yaw+.4),
|
||||
original['pose'][1]+math.sin(yaw+.4)]))
|
||||
translated=request('/plan',value)
|
||||
assert translated['status']=='path' and translated['controller_goal'][0]=='path',translated
|
||||
report['recovery_translation_uses_native_path']=translated
|
||||
with condition:state['observation_id']=value['observation_id']
|
||||
# Explicit orientation-only intent still invokes native Spin. Its
|
||||
# zero-angle completion on stationary test odometry cannot translate.
|
||||
value.update(translation_allowed=False,
|
||||
orientation_target=dict(key='http-spin-complete',xy=[
|
||||
original['pose'][0]+math.cos(yaw),
|
||||
original['pose'][1]+math.sin(yaw)]))
|
||||
orientation_plans=[]
|
||||
deadline=time.monotonic()+3
|
||||
while True:
|
||||
value['observation_id']='spin-complete-'+str(len(orientation_plans))
|
||||
result=request('/plan',value)
|
||||
orientation_plans.append(result)
|
||||
with condition:state['observation_id']=value['observation_id']
|
||||
if result.get('diagnostic',{}).get('failure')=='no-permitted-goal':break
|
||||
assert time.monotonic()<deadline,orientation_plans
|
||||
time.sleep(.05)
|
||||
report['orientation_only_spin_completion']=orientation_plans
|
||||
value.update(observation_id='orientation-no-translation',translation_allowed=False)
|
||||
blocked=request('/plan',value)
|
||||
assert blocked['status']=='blocked' and blocked['diagnostic']['failure']=='no-permitted-goal',blocked
|
||||
with condition:state['observation_id']=value['observation_id']
|
||||
time.sleep(.1)
|
||||
assert responses[-1]['speed_mps']==responses[-1]['yaw_rate_rps']==0.,responses[-1]
|
||||
report['completed_spin_without_translation']=blocked
|
||||
value.update(observation_id='orientation-translation-restored',translation_allowed=True)
|
||||
restored=request('/plan',value)
|
||||
assert restored['status']=='path' and restored['controller_goal'][0]=='path',restored
|
||||
with condition:state['observation_id']=value['observation_id']
|
||||
with condition:state['enabled']=False
|
||||
time.sleep(.1)
|
||||
assert responses[-1]['speed_mps']==responses[-1]['yaw_rate_rps']==0.
|
||||
time.sleep(.85) # Expire the unchanged .8 s range lease; poses stay fresh.
|
||||
with condition:state['enabled']=True
|
||||
time.sleep(.15)
|
||||
assert responses[-1]['reason']=='stale-range',responses[-1]
|
||||
assert responses[-1]['speed_mps']==responses[-1]['yaw_rate_rps']==0.
|
||||
report['expired_range_reason']=responses[-1]['reason']
|
||||
if process:
|
||||
# Losing the run-owned map process must not renew its last map
|
||||
# through otherwise healthy control/odometry traffic.
|
||||
value['observation_id']='map-process-fault'
|
||||
assert request('/plan',value)['status']=='path'
|
||||
with condition:state['observation_id']=value['observation_id']
|
||||
children=[]
|
||||
for entry in Path('/proc').iterdir():
|
||||
if entry.name.isdecimal():
|
||||
try:
|
||||
stat=(entry/'stat').read_text().split(') ',1)[1].split()
|
||||
command=(entry/'cmdline').read_bytes()
|
||||
except (FileNotFoundError,ProcessLookupError):
|
||||
continue
|
||||
if int(stat[1])==process.pid and b'multiprocessing.spawn' in command:
|
||||
children.append(int(entry.name))
|
||||
assert len(children)==1,children
|
||||
os.kill(children[0],signal.SIGTERM)
|
||||
time.sleep(.1)
|
||||
try:
|
||||
request('/plan',value)
|
||||
except RuntimeError as error:
|
||||
assert '503' in str(error),error
|
||||
else:
|
||||
raise AssertionError('A failed map process accepted an observation')
|
||||
time.sleep(.85)
|
||||
assert responses[-1]['speed_mps']==responses[-1]['yaw_rate_rps']==0.
|
||||
report['map_process_failure_zero']=responses[-1]['reason']
|
||||
if errors:raise errors[0]
|
||||
report['passed']=True
|
||||
except BaseException as error:
|
||||
report['error']=type(error).__name__+': '+str(error)
|
||||
raise
|
||||
finally:
|
||||
running.clear()
|
||||
if thread:thread.join(timeout=3)
|
||||
if process:
|
||||
process.terminate()
|
||||
try:process.wait(timeout=7)
|
||||
except subprocess.TimeoutExpired:process.kill();process.wait(timeout=2)
|
||||
log.close()
|
||||
report['controls']=responses
|
||||
(args.output/'result.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
print(json.dumps({k:v for k,v in report.items() if k not in ('plans','controls')}))
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Exercise production ROS adapter against actual Smac/DWB, no actuator."""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import Future
|
||||
from pathlib import Path
|
||||
|
||||
import rclpy
|
||||
import yaml
|
||||
from check_ros_integration import Check
|
||||
from configuration import configuration
|
||||
from rclpy.executors import MultiThreadedExecutor
|
||||
from nav_msgs.msg import Odometry
|
||||
from nav2_msgs.action import FollowPath
|
||||
from action_msgs.msg import GoalStatus
|
||||
from ros_navigation import RosNavigation
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
for name in ('inputs', 'robot', 'output'):
|
||||
parser.add_argument('--' + name, type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
args.output.mkdir(exist_ok=False, parents=True)
|
||||
config = configuration(json.loads(args.inputs.read_text()), json.loads(args.robot.read_text()))
|
||||
path = args.output/'parameters.yaml'; path.write_text(yaml.safe_dump(config, sort_keys=False))
|
||||
rclpy.init()
|
||||
fixture, bridge = Check(), RosNavigation()
|
||||
measured = []
|
||||
fixture.create_subscription(Odometry, '/odom', lambda value: measured.append([
|
||||
value.twist.twist.linear.x, value.twist.twist.linear.y,
|
||||
value.twist.twist.angular.z]), 5)
|
||||
fixture.destroy_timer(fixture.timer) # The production adapter owns TF/odometry.
|
||||
running = threading.Event(); running.set()
|
||||
errors = []
|
||||
executor = MultiThreadedExecutor(num_threads=2)
|
||||
spinner = threading.Thread(target=executor.spin)
|
||||
pose = [0.,0.,.37,0.,0.,0.,1.]
|
||||
continuous_updates = threading.Event()
|
||||
continuity_samples = []
|
||||
|
||||
def measurements():
|
||||
try:
|
||||
while running.is_set():
|
||||
bridge.observe_pose(pose, .01, [.03, -.005, .012])
|
||||
if continuous_updates.is_set():
|
||||
continuity_samples.append(bridge.native_command())
|
||||
time.sleep(.04)
|
||||
except BaseException as error:
|
||||
errors.append(error)
|
||||
|
||||
source = threading.Thread(target=measurements)
|
||||
processes, logs = [], []
|
||||
report = dict(qualified=False, scope='native ROS action/odometry integration', passed=False)
|
||||
try:
|
||||
fixture.map_case('free')
|
||||
# map_case uses spin_once for initial map publication; that helper
|
||||
# removes its node from the temporary executor afterwards.
|
||||
executor.add_node(fixture); executor.add_node(bridge)
|
||||
spinner.start(); source.start()
|
||||
for package, name in (('nav2_planner', 'planner_server'), ('nav2_controller', 'controller_server'),
|
||||
('nav2_behaviors', 'behavior_server')):
|
||||
log = (args.output/(name+'.log')).open('w');logs.append(log)
|
||||
processes.append(subprocess.Popen([
|
||||
'/opt/ndc_nav2/install/'+package+'/lib/'+package+'/'+name,
|
||||
'--ros-args','--params-file',str(path), '-r', '/cmd_vel:=/nav2/'+
|
||||
('behavior' if package=='nav2_behaviors' else 'controller')+'_cmd_vel'],
|
||||
stdout=log,stderr=subprocess.STDOUT))
|
||||
bridge.activate()
|
||||
history=[]
|
||||
for goal in ([5.,0.], [3.,1.]):
|
||||
planned=bridge.plan(pose,goal,math.atan2(goal[1],goal[0]))
|
||||
assert planned is not None and len(planned.poses)>1
|
||||
proposed=bridge.follow(planned)
|
||||
assert proposed is not None
|
||||
time.sleep(.3)
|
||||
current=bridge.native_command()
|
||||
assert current is not None and all(math.isfinite(v) for v in current)
|
||||
assert abs(current[1])+abs(current[2])>1e-5
|
||||
history.append(dict(goal=goal,path_points=len(planned.poses),proposal=list(current),
|
||||
command_sequence=bridge.command_sequence))
|
||||
# A new observed path is a native preemption, not a cancel/restart.
|
||||
# Repeated updates must not insert zero commands or reset progress.
|
||||
with bridge.condition:
|
||||
before = bridge.command_sequence
|
||||
continuous_updates.set()
|
||||
refresh_ms=[]
|
||||
for _ in range(6):
|
||||
began=time.monotonic()
|
||||
assert bridge.follow(planned, continuing=True) is not None
|
||||
refresh_ms.append((time.monotonic()-began)*1000)
|
||||
time.sleep(.1)
|
||||
continuous_updates.clear()
|
||||
assert continuity_samples and all(x is not None for x in continuity_samples)
|
||||
report['uninterrupted_command_samples'] = len(continuity_samples)
|
||||
report['same_goal_refresh_ms'] = refresh_ms
|
||||
with bridge.condition:
|
||||
updates = [row for row in bridge.history if row[0] > before]
|
||||
assert updates and all(row[2:] != (0., 0.) for row in updates), updates
|
||||
report['continuous_path_update_commands'] = len(updates)
|
||||
# Lost feedback must not hide a terminal zero. With stationary pose,
|
||||
# the unchanged native progress checker aborts this real action.
|
||||
with bridge.condition:
|
||||
bridge.pending_feedback = object()
|
||||
terminal = bridge.await_result(bridge.terminal, 10.)
|
||||
assert terminal.status == GoalStatus.STATUS_ABORTED
|
||||
assert bridge.native_command() is None
|
||||
bridge.stop()
|
||||
report['unacknowledged_terminal_status'] = terminal.status
|
||||
spin = bridge.spin(.5, 3.)
|
||||
assert spin is not None and spin[1] == 0 and spin[2] > 0
|
||||
# A command from an inactive publisher cannot acquire velocity ownership.
|
||||
from geometry_msgs.msg import Twist
|
||||
foreign=Twist();foreign.linear.x=99.
|
||||
bridge.on_command(foreign, 'controller')
|
||||
assert bridge.native_command()[1] == 0
|
||||
reverse = bridge.backup(.3, .1, 4.)
|
||||
assert reverse is not None and reverse[1] < 0 and reverse[2] == 0
|
||||
report['behaviors'] = dict(spin=list(spin), backup=list(reverse))
|
||||
bridge.stop()
|
||||
assert bridge.native_command() is None
|
||||
with bridge.condition:
|
||||
assert bridge.history[-1][2:] == (0.,0.)
|
||||
commands=list(bridge.history)
|
||||
# No caller may silently turn unsigned speed into odometry.
|
||||
report['received_odometry_samples'] = len(measured)
|
||||
assert measured and measured[-1]==[.03,-.005,.012], measured[-3:]
|
||||
report['measured_twist']=measured[-1]
|
||||
# Delay delivery of a real controller's acceptance beyond the caller's
|
||||
# deadline. The adapter must cancel that late accepted action and latch
|
||||
# closed until reset, even though the native server already started it.
|
||||
accepted, delayed = [], Future()
|
||||
ready = threading.Event()
|
||||
class DelayedAcceptance:
|
||||
def send_goal_async(self, request):
|
||||
def receive(future):
|
||||
accepted.append(future.result()); ready.set()
|
||||
bridge.controller.send_goal_async(request).add_done_callback(receive)
|
||||
return delayed
|
||||
request = FollowPath.Goal()
|
||||
request.path, request.controller_id, request.goal_checker_id = planned, 'FollowPath', 'goal_checker'
|
||||
try:
|
||||
bridge.accept(DelayedAcceptance(), request, .05)
|
||||
raise AssertionError('Delayed acceptance did not time out')
|
||||
except TimeoutError:
|
||||
pass
|
||||
assert ready.wait(1) and accepted[0].accepted
|
||||
terminal = accepted[0].get_result_async()
|
||||
delayed.set_result(accepted[0])
|
||||
result = bridge.await_result(terminal, 1.)
|
||||
assert result.status == GoalStatus.STATUS_CANCELED
|
||||
assert bridge.failed and bridge.native_command() is None
|
||||
report['late_acceptance_cancel_status'] = result.status
|
||||
report.update(paths=history,commands=commands,passed=True)
|
||||
if errors: raise errors[0]
|
||||
except BaseException as error:
|
||||
report.update(passed=False,error=type(error).__name__+': '+str(error))
|
||||
raise
|
||||
finally:
|
||||
running.clear()
|
||||
if source.is_alive(): source.join(timeout=1)
|
||||
for process in processes: process.terminate()
|
||||
for process in processes:
|
||||
try: process.wait(timeout=3)
|
||||
except subprocess.TimeoutExpired: process.kill();process.wait(timeout=3)
|
||||
for log in logs:log.close()
|
||||
executor.shutdown(timeout_sec=2)
|
||||
if spinner.is_alive(): spinner.join(timeout=2)
|
||||
bridge.destroy_node();fixture.destroy_node();rclpy.shutdown()
|
||||
(args.output/'result.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
print(json.dumps({k:v for k,v in report.items() if k!='commands'}))
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Fixed ground/object fixtures for the actual PCL library; no actuator."""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from navigation.pcl_ground import PclGround # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser()
|
||||
for name in ('inputs','robot','snapshot','output'):
|
||||
p.add_argument('--'+name,type=Path,required=True)
|
||||
args=p.parse_args();args.output.mkdir(parents=True,exist_ok=False)
|
||||
inputs=json.loads(args.inputs.read_text())
|
||||
ground=PclGround(inputs['robot']['geometry'])
|
||||
report=dict(authority=None,qualified=False,cases=[],parameters=dict(
|
||||
method="PCL SAC_RANSAC perpendicular plane",height_m=ground.height_m,angle=ground.angle))
|
||||
try:
|
||||
for grade in (0,8,20):
|
||||
for angle,shift in ((0,[0,0,0]),(71,[40,-20,2])):
|
||||
x,y=np.meshgrid(np.arange(-1.5,1.51,.04),np.arange(-1.5,1.51,.04))
|
||||
x,y=x.ravel(),y.ravel();z=x*math.tan(math.radians(grade))
|
||||
low=(abs(x)<.18)&(abs(y)<.18)
|
||||
high=(abs(x-.7)<.18)&(abs(y+.4)<.18)
|
||||
z[low]+=.08;z[high]+=.6
|
||||
points=np.column_stack((x,y,z))
|
||||
a=math.radians(angle);rot=np.array([[math.cos(a),-math.sin(a),0],
|
||||
[math.sin(a),math.cos(a),0],[0,0,1]])
|
||||
points=points@rot.T+shift
|
||||
before=time.monotonic();mask=ground.mask(points, ground_anchor=shift);elapsed=time.monotonic()-before
|
||||
interior=(abs(x)<1)&(abs(y)<1)&~(low|high)
|
||||
row=dict(grade=grade,angle=angle,ground_fraction=float(mask[interior].mean()),
|
||||
low_object_ground=int(mask[low].sum()),high_object_ground=int(mask[high].sum()),
|
||||
processing_ms=elapsed*1000)
|
||||
report['cases'].append(row)
|
||||
assert row['ground_fraction']>=.98 and not mask[low|high].any(),row
|
||||
# A different horizontal floor/table cannot use the rover ground reference.
|
||||
elevated=points.copy();elevated[:,2]+=.6
|
||||
assert not ground.mask(elevated, ground_anchor=shift).any()
|
||||
snapshot=json.loads(args.snapshot.read_text())
|
||||
request=snapshot['exchange']['request'];points=np.array(request['points'])
|
||||
anchor=np.array(request['pose'][:3]);anchor[2]-=request['body_contact_height_m']
|
||||
before=time.monotonic();mask=ground.mask(points, ground_anchor=anchor)
|
||||
indices=request['detection_point_indices']
|
||||
report['archive']=dict(candidates=len(indices),pcl_ground=int(mask[indices].sum()),
|
||||
retained_points=points[np.array(indices)[~mask[indices]]].tolist(),
|
||||
processing_ms=(time.monotonic()-before)*1000)
|
||||
report['passed']=True
|
||||
except BaseException as error:
|
||||
report['error']=type(error).__name__+': '+str(error);raise
|
||||
finally:
|
||||
(args.output/'result.json').write_text(json.dumps(report,indent=2))
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Bounded real ROS/Nav2 plugin check on synthetic maps, never vehicle authority.
|
||||
|
||||
Run inside the pinned image. Checks fixed pass/block cases with the actual rig
|
||||
footprint, unknown space, controller output and cancellation. No physics claim.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import rclpy
|
||||
import yaml
|
||||
from action_msgs.msg import GoalStatus
|
||||
from configuration import configuration
|
||||
from geometry_msgs.msg import TransformStamped, Twist
|
||||
from lifecycle_msgs.msg import Transition
|
||||
from lifecycle_msgs.srv import ChangeState
|
||||
from nav2_msgs.action import ComputePathToPose, FollowPath
|
||||
from nav2_msgs.srv import GetCostmap
|
||||
from nav_msgs.msg import OccupancyGrid, Odometry
|
||||
from rclpy.action import ActionClient
|
||||
from rclpy.node import Node
|
||||
from rclpy.qos import DurabilityPolicy, QoSProfile, ReliabilityPolicy
|
||||
from tf2_ros import TransformBroadcaster
|
||||
|
||||
|
||||
class Check(Node):
|
||||
def __init__(self):
|
||||
super().__init__('missioncore_nav2_integration_check')
|
||||
qos = QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL,
|
||||
reliability=ReliabilityPolicy.RELIABLE)
|
||||
self.map_pub = self.create_publisher(OccupancyGrid, '/observed_map', qos)
|
||||
self.odom_pub = self.create_publisher(Odometry, '/odom', 5)
|
||||
self.tf = TransformBroadcaster(self)
|
||||
self.timer = self.create_timer(0.02, self.publish_pose)
|
||||
self.commands = []
|
||||
self.create_subscription(Twist, '/cmd_vel', self.command, 20)
|
||||
self.planner = ActionClient(self, ComputePathToPose, '/compute_path_to_pose')
|
||||
self.controller = ActionClient(self, FollowPath, '/follow_path')
|
||||
|
||||
def command(self, value):
|
||||
self.commands.append((time.monotonic(), value.linear.x, value.angular.z))
|
||||
|
||||
def publish_pose(self):
|
||||
tf = TransformStamped()
|
||||
tf.header.stamp = self.get_clock().now().to_msg()
|
||||
tf.header.frame_id, tf.child_frame_id = 'map', 'base_link'
|
||||
tf.transform.rotation.w = 1.0
|
||||
self.tf.sendTransform(tf)
|
||||
odom = Odometry()
|
||||
odom.header = tf.header
|
||||
odom.child_frame_id = 'base_link'
|
||||
odom.pose.pose.orientation.w = 1.0
|
||||
self.odom_pub.publish(odom)
|
||||
|
||||
def spin_for(self, duration):
|
||||
end = time.monotonic() + duration
|
||||
while time.monotonic() < end:
|
||||
rclpy.spin_once(self, timeout_sec=min(0.02, end - time.monotonic()))
|
||||
|
||||
def await_result(self, future, timeout=8.0):
|
||||
rclpy.spin_until_future_complete(self, future, timeout_sec=timeout)
|
||||
if not future.done():
|
||||
raise TimeoutError('ROS response timeout')
|
||||
return future.result()
|
||||
|
||||
def lifecycle(self, name, transition):
|
||||
client = self.create_client(ChangeState, '/' + name + '/change_state')
|
||||
try:
|
||||
if not client.wait_for_service(timeout_sec=10):
|
||||
raise TimeoutError(name + ' lifecycle service unavailable')
|
||||
request = ChangeState.Request()
|
||||
request.transition.id = transition
|
||||
if not self.await_result(client.call_async(request)).success:
|
||||
raise RuntimeError(name + ' lifecycle transition failed')
|
||||
finally:
|
||||
self.destroy_client(client)
|
||||
|
||||
def map_case(self, case):
|
||||
grid = OccupancyGrid()
|
||||
grid.header.frame_id = 'map'
|
||||
grid.header.stamp = self.get_clock().now().to_msg()
|
||||
grid.info.resolution = 0.05
|
||||
grid.info.width, grid.info.height = 240, 160
|
||||
grid.info.origin.position.x, grid.info.origin.position.y = -2.0, -4.0
|
||||
grid.info.origin.orientation.w = 1.0
|
||||
values = []
|
||||
for iy in range(grid.info.height):
|
||||
for ix in range(grid.info.width):
|
||||
x, y = -2 + (ix + 0.5) * 0.05, -4 + (iy + 0.5) * 0.05
|
||||
cost = 100 if ix in (0, 239) or iy in (0, 159) else 0
|
||||
if 2.0 <= x < 2.2:
|
||||
if case == 'blocked-wall':
|
||||
cost = 100
|
||||
elif case == 'unknown-band':
|
||||
cost = -1
|
||||
elif case in ('narrow-gap', 'wide-gap'):
|
||||
half = 0.4 if case == 'narrow-gap' else 0.65
|
||||
cost = 100 if abs(y) >= half else 0
|
||||
values.append(cost)
|
||||
grid.data = values
|
||||
self.map_pub.publish(grid)
|
||||
self.spin_for(0.4)
|
||||
return grid
|
||||
|
||||
def confirm_map(self, case):
|
||||
client = self.create_client(GetCostmap, '/global_costmap/get_costmap')
|
||||
try:
|
||||
if not client.wait_for_service(timeout_sec=5):
|
||||
raise TimeoutError('Costmap service unavailable')
|
||||
value = self.await_result(client.call_async(GetCostmap.Request())).map
|
||||
# Confirm the wall update reached the planner before querying it.
|
||||
ix = int((2.075 - value.metadata.origin.position.x) / value.metadata.resolution)
|
||||
iy = int((0.875 - value.metadata.origin.position.y) / value.metadata.resolution)
|
||||
cost = value.data[iy * value.metadata.size_x + ix]
|
||||
expected = 0 if case == 'free' else 255 if case == 'unknown-band' else 254
|
||||
if cost != expected:
|
||||
raise AssertionError(('Costmap update missing', case, cost, expected))
|
||||
return int(cost)
|
||||
finally:
|
||||
self.destroy_client(client)
|
||||
|
||||
def plan(self):
|
||||
if not self.planner.wait_for_server(timeout_sec=5):
|
||||
raise TimeoutError('Planner action unavailable')
|
||||
request = ComputePathToPose.Goal()
|
||||
request.planner_id, request.use_start = 'GridBased', True
|
||||
for pose, x in ((request.start, 0.0), (request.goal, 5.0)):
|
||||
pose.header.frame_id = 'map'
|
||||
pose.header.stamp = self.get_clock().now().to_msg()
|
||||
pose.pose.position.x, pose.pose.orientation.w = x, 1.0
|
||||
handle = self.await_result(self.planner.send_goal_async(request))
|
||||
if not handle.accepted:
|
||||
raise RuntimeError('Planner action was not accepted')
|
||||
return self.await_result(handle.get_result_async())
|
||||
|
||||
def follow_and_cancel(self, path):
|
||||
if not self.controller.wait_for_server(timeout_sec=5):
|
||||
raise TimeoutError('Controller action unavailable')
|
||||
goal = FollowPath.Goal()
|
||||
goal.path, goal.controller_id, goal.goal_checker_id = path, 'FollowPath', 'goal_checker'
|
||||
first = len(self.commands)
|
||||
handle = self.await_result(self.controller.send_goal_async(goal))
|
||||
if not handle.accepted:
|
||||
raise RuntimeError('Controller action was not accepted')
|
||||
self.spin_for(0.75)
|
||||
active = self.commands[first:]
|
||||
assert active and all(math.isfinite(v) for row in active for v in row)
|
||||
assert any(row[1] > 0.001 for row in active), 'DWB did not propose forward motion'
|
||||
cancel_at = time.monotonic()
|
||||
self.await_result(handle.cancel_goal_async())
|
||||
terminal = self.await_result(handle.get_result_async())
|
||||
self.spin_for(0.15)
|
||||
stopped = [row for row in self.commands if row[0] >= cancel_at]
|
||||
assert terminal.status == GoalStatus.STATUS_CANCELED, terminal.status
|
||||
assert stopped and stopped[-1][1:] == (0.0, 0.0), 'Cancellation did not publish zero'
|
||||
return dict(commands=active, cancelled_status=terminal.status, after_cancel=stopped)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--inputs', type=Path, required=True)
|
||||
parser.add_argument('--robot', type=Path, required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
inputs, robot = json.loads(args.inputs.read_text()), json.loads(args.robot.read_text())
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
config = configuration(inputs, robot)
|
||||
config_path = args.output / 'parameters.yaml'
|
||||
config_path.write_text(yaml.safe_dump(config, sort_keys=False))
|
||||
report = dict(scope='real ROS2 plugins on synthetic maps; no physical motion',
|
||||
qualified=False, execution_inputs_sha256=inputs['sha256'],
|
||||
configuration_sha256=hashlib.sha256(config_path.read_bytes()).hexdigest(),
|
||||
cases=[], passed=False)
|
||||
processes, logs = [], []
|
||||
rclpy.init()
|
||||
node = Check()
|
||||
try:
|
||||
node.map_case('free')
|
||||
for package, executable in (('nav2_planner', 'planner_server'),
|
||||
('nav2_controller', 'controller_server')):
|
||||
log = (args.output / (executable + '.log')).open('w')
|
||||
logs.append(log)
|
||||
binary = '/opt/ndc_nav2/install/' + package + '/lib/' + package + '/' + executable
|
||||
processes.append(subprocess.Popen(
|
||||
[binary, '--ros-args', '--params-file', str(config_path)],
|
||||
stdout=log, stderr=subprocess.STDOUT))
|
||||
node.lifecycle(executable, Transition.TRANSITION_CONFIGURE)
|
||||
node.lifecycle(executable, Transition.TRANSITION_ACTIVATE)
|
||||
for name, expected in (('free', True), ('blocked-wall', False),
|
||||
('unknown-band', False), ('narrow-gap', False), ('wide-gap', True)):
|
||||
grid = node.map_case(name)
|
||||
observed_cost = node.confirm_map(name)
|
||||
result = node.plan()
|
||||
path = result.result.path
|
||||
success = result.status == GoalStatus.STATUS_SUCCEEDED and len(path.poses) > 1
|
||||
row = dict(case=name, expected_path=expected, status=result.status,
|
||||
confirmed_cost=observed_cost,
|
||||
path=[[p.pose.position.x, p.pose.position.y,
|
||||
p.pose.orientation.z, p.pose.orientation.w] for p in path.poses],
|
||||
grid_sha256=hashlib.sha256(bytes(v + 1 for v in grid.data)).hexdigest())
|
||||
report['cases'].append(row)
|
||||
assert success == expected, (name, expected, result.status, len(path.poses))
|
||||
if name == 'free':
|
||||
row['controller'] = node.follow_and_cancel(path)
|
||||
report['passed'] = True
|
||||
except BaseException as error:
|
||||
report['error'] = type(error).__name__ + ': ' + str(error)
|
||||
raise
|
||||
finally:
|
||||
for process in processes:
|
||||
process.terminate()
|
||||
for process in processes:
|
||||
try:
|
||||
process.wait(timeout=3)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=3)
|
||||
for log in logs:
|
||||
log.close()
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
(args.output / 'result.json').write_text(json.dumps(report, indent=2) + '\n')
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Archived full sensor-to-Nav2 check with the unchanged CMU terrain node.
|
||||
|
||||
Two pinned images communicate with standard ROS2 messages. There is no
|
||||
actuator. Diagnostic republishing is not a live observation or qualification.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import rclpy
|
||||
from action_msgs.msg import GoalStatus
|
||||
from lifecycle_msgs.msg import Transition
|
||||
from navigation.footprint import Footprint
|
||||
from replay_observations import Replay
|
||||
from rig_collision import collision_geometry
|
||||
from terrain_observation import TerrainObservation
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
for key in ('inputs', 'snapshot', 'output'):
|
||||
parser.add_argument('--' + key, type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
inputs = json.loads(args.inputs.read_text())
|
||||
snapshot = json.loads(args.snapshot.read_text())
|
||||
request = snapshot['exchange']['request']
|
||||
assert request['execution_inputs_sha256'] == inputs['sha256']
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
report = dict(qualified=False, authority=None, scope='archived terrain/ROS integration',
|
||||
source_observation_id=snapshot['exchange']['observation_id'],
|
||||
snapshot_sha256=hashlib.sha256(args.snapshot.read_bytes()).hexdigest(),
|
||||
execution_inputs_sha256=inputs['sha256'], passed=False)
|
||||
rclpy.init()
|
||||
node = Replay(snapshot, inputs['robot']['geometry']['max_step_m'])
|
||||
# Geometry for contact fits remains the measured chassis/track geometry;
|
||||
# the collision monitor separately includes the mounted sensor bodies.
|
||||
geometry = collision_geometry(inputs['robot']['geometry'], inputs['sensors']['mounts'])
|
||||
terrain = TerrainObservation(node, Footprint(geometry), inputs['robot']['geometry'])
|
||||
processes, logs = [], []
|
||||
thread = None
|
||||
observed, failure = [], []
|
||||
try:
|
||||
deadline = time.monotonic()+5
|
||||
while (terrain.scan.get_subscription_count() == 0
|
||||
or terrain.odom.get_subscription_count() == 0):
|
||||
node.spin_for(.02)
|
||||
if time.monotonic() > deadline:
|
||||
raise RuntimeError('Terrain subscriptions unavailable')
|
||||
|
||||
def observe():
|
||||
try:
|
||||
observed.append(terrain.observe(request))
|
||||
except BaseException as error:
|
||||
failure.append(error)
|
||||
|
||||
thread = threading.Thread(target=observe)
|
||||
thread.start()
|
||||
while thread.is_alive():
|
||||
node.spin_for(.01)
|
||||
thread.join()
|
||||
if failure:
|
||||
raise failure[0]
|
||||
result = observed[0]
|
||||
node.hazards = [p for p in result['terrain'] if p[3] > terrain.monitor.max_step + 1e-4]
|
||||
report['terrain'] = dict(metrics=result['metrics'], points=len(result['terrain']),
|
||||
hazards=len(node.hazards), source_points=len(request['points']))
|
||||
(args.output / 'terrain.json').write_text(json.dumps({key:result[key].tolist()
|
||||
for key in ('terrain','physical_terrain','current_points','detected')}))
|
||||
for package, name in (('nav2_planner', 'planner_server'),
|
||||
('nav2_controller', 'controller_server')):
|
||||
log = (args.output / (name + '.log')).open('w'); logs.append(log)
|
||||
processes.append(subprocess.Popen(
|
||||
['/opt/ndc_nav2/install/' + package + '/lib/' + package + '/' + name,
|
||||
'--ros-args', '--params-file', '/check/parameters.yaml'],
|
||||
stdout=log, stderr=subprocess.STDOUT))
|
||||
node.lifecycle(name, Transition.TRANSITION_CONFIGURE)
|
||||
node.lifecycle(name, Transition.TRANSITION_ACTIVATE)
|
||||
node.spin_for(.5)
|
||||
path = node.plan()
|
||||
report['status'] = path.status
|
||||
report['path'] = [[p.pose.position.x, p.pose.position.y,
|
||||
p.pose.orientation.z, p.pose.orientation.w] for p in path.result.path.poses]
|
||||
assert path.status == GoalStatus.STATUS_SUCCEEDED and len(report['path']) > 1
|
||||
report['controller'] = node.follow_and_cancel(path.result.path)
|
||||
report['passed'] = True
|
||||
except BaseException as error:
|
||||
report['error'] = type(error).__name__ + ': ' + str(error)
|
||||
raise
|
||||
finally:
|
||||
if thread:
|
||||
thread.join(timeout=1)
|
||||
for process in processes:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=3)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill(); process.wait(timeout=3)
|
||||
for log in logs:
|
||||
log.close()
|
||||
node.destroy_node(); rclpy.shutdown()
|
||||
(args.output/'result.json').write_text(json.dumps(report, indent=2)+'\n')
|
||||
print(json.dumps({k:v for k,v in report.items() if k not in ('path','controller')}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Nav2 Humble parameters derived from the selected rover, without map data.
|
||||
|
||||
The drive limits remain the simulation profile's engineering assumptions.
|
||||
Compiling or activating these parameters does not qualify physical dynamics.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from rig_collision import collision_geometry # noqa: E402
|
||||
|
||||
|
||||
def configuration(inputs, robot):
|
||||
body = {key: value for key, value in inputs.items() if key != 'sha256'}
|
||||
actual = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(',', ':'),
|
||||
allow_nan=False).encode()).hexdigest()
|
||||
if actual != inputs['sha256']:
|
||||
raise ValueError('Execution inputs identity changed')
|
||||
geometry = collision_geometry(inputs['robot']['geometry'], inputs['sensors']['mounts'])
|
||||
x, y = geometry['collision_length_m'] / 2, geometry['collision_width_m'] / 2
|
||||
control = robot['control']
|
||||
speed = float(inputs['behavior']['max_speed_mps'])
|
||||
acceleration = float(control['acceleration_mps2'])
|
||||
deceleration = float(control['deceleration_mps2'])
|
||||
yaw = float(control['max_yaw_rps'])
|
||||
track_width = float(robot['physics']['track_width_m'])
|
||||
track_centres = [(band['lower_xy_m'][1]+band['upper_xy_m'][1])/2
|
||||
for band in inputs['robot']['geometry']['ground_contact']['bands']]
|
||||
if not all(math.isfinite(v) and v > 0 for v in
|
||||
(x, y, speed, acceleration, deceleration, yaw, track_width)):
|
||||
raise ValueError('Invalid rover envelope')
|
||||
footprint = json.dumps([[x, y], [-x, y], [-x, -y], [x, -y]])
|
||||
costmap = dict(
|
||||
use_sim_time=False, global_frame='map', robot_base_frame='base_link',
|
||||
update_frequency=10.0, publish_frequency=5.0, resolution=0.05,
|
||||
rolling_window=False, track_unknown_space=True, footprint=footprint,
|
||||
footprint_padding=0.05, transform_tolerance=0.2,
|
||||
always_send_full_costmap=True, plugins=['static_layer', 'inflation_layer'],
|
||||
static_layer=dict(plugin='nav2_costmap_2d::StaticLayer', map_topic='/observed_map',
|
||||
map_subscribe_transient_local=True, subscribe_to_updates=False),
|
||||
inflation_layer=dict(plugin='nav2_costmap_2d::InflationLayer',
|
||||
cost_scaling_factor=3.0, inflation_radius=math.hypot(x, y) + 0.15),
|
||||
)
|
||||
# The upstream differential primitives include pure rotation. They are
|
||||
# geometrical candidates; the drive/support/freshness gates remain required.
|
||||
lattice = ('/opt/ndc_nav2/install/nav2_smac_planner/share/nav2_smac_planner/'
|
||||
'sample_primitives/5cm_resolution/0.5m_turning_radius/diff/output.json')
|
||||
return {
|
||||
'behavior_server': {'ros__parameters': dict(
|
||||
use_sim_time=False, global_frame='map', robot_base_frame='base_link',
|
||||
costmap_topic='local_costmap/costmap_raw',
|
||||
footprint_topic='local_costmap/published_footprint',
|
||||
cycle_frequency=20.0, transform_tolerance=0.2,
|
||||
behavior_plugins=['spin', 'backup'],
|
||||
spin=dict(plugin='nav2_behaviors/Spin'),
|
||||
backup=dict(plugin='nav2_behaviors/BackUp'),
|
||||
simulate_ahead_time=0.8+speed/deceleration,
|
||||
max_rotational_vel=yaw, min_rotational_vel=0.0,
|
||||
rotational_acc_lim=2*acceleration/track_width,
|
||||
)},
|
||||
'planner_server': {'ros__parameters': dict(
|
||||
use_sim_time=False, expected_planner_frequency=5.0, planner_plugins=['GridBased'],
|
||||
GridBased=dict(plugin='nav2_smac_planner/SmacPlannerLattice',
|
||||
lattice_filepath=lattice, allow_unknown=False,
|
||||
tolerance=0.0, max_planning_time=0.5,
|
||||
allow_reverse_expansion=False, cache_obstacle_heuristic=False,
|
||||
smooth_path=False),
|
||||
)},
|
||||
'controller_server': {'ros__parameters': dict(
|
||||
use_sim_time=False, controller_frequency=20.0, odom_topic='/odom',
|
||||
min_x_velocity_threshold=0.001, min_y_velocity_threshold=0.001,
|
||||
min_theta_velocity_threshold=0.001, failure_tolerance=0.0,
|
||||
progress_checker_plugin='progress_checker', goal_checker_plugins=['goal_checker'],
|
||||
controller_plugins=['FollowPath'],
|
||||
progress_checker=dict(plugin='nav2_controller::SimpleProgressChecker',
|
||||
required_movement_radius=0.05, movement_time_allowance=8.0),
|
||||
goal_checker=dict(plugin='nav2_controller::SimpleGoalChecker', stateful=True,
|
||||
xy_goal_tolerance=float(inputs['mission']['arrival_radius_m']),
|
||||
yaw_goal_tolerance=0.15),
|
||||
FollowPath={
|
||||
'plugin': 'dwb_core::DWBLocalPlanner',
|
||||
# Upstream default: score acceleration-integrated trajectories
|
||||
# over sim_time. A one-control-period DWA window at rest has
|
||||
# sub-cell endpoints on this rover's 5 cm costmap and aliases
|
||||
# the distance critics. The actuator still applies its own
|
||||
# unchanged acceleration/deceleration limits.
|
||||
'trajectory_generator_name': 'dwb_plugins::StandardTrajectoryGenerator',
|
||||
'min_vel_x': 0.0, 'max_vel_x': speed,
|
||||
'min_vel_y': 0.0, 'max_vel_y': 0.0,
|
||||
'max_vel_theta': yaw, 'min_speed_xy': 0.0,
|
||||
'max_speed_xy': speed, 'min_speed_theta': 0.0,
|
||||
'acc_lim_x': acceleration, 'decel_lim_x': -deceleration,
|
||||
'acc_lim_y': 0.0, 'decel_lim_y': 0.0,
|
||||
'acc_lim_theta': 2 * acceleration / track_width,
|
||||
'decel_lim_theta': -2 * deceleration / track_width,
|
||||
'vx_samples': 20, 'vy_samples': 1, 'vtheta_samples': 20,
|
||||
'sim_time': 0.8 + speed / deceleration,
|
||||
'linear_granularity': 0.025, 'angular_granularity': 0.025,
|
||||
'transform_tolerance': 0.2, 'trans_stopped_velocity': 0.01,
|
||||
'xy_goal_tolerance': float(inputs['mission']['arrival_radius_m']),
|
||||
'short_circuit_trajectory_evaluation': True,
|
||||
'critics': ['ndc_rover_critics::ForwardTracksCritic', 'RotateToGoal',
|
||||
'Oscillation', 'ObstacleFootprint', 'PreferForward',
|
||||
'GoalAlign', 'PathAlign', 'PathDist', 'GoalDist'],
|
||||
'ndc_rover_critics::ForwardTracksCritic.track_centres_y_m': track_centres,
|
||||
# Upstream angular preference; no arbitrary minimum speed in
|
||||
# the initial acceleration window. Geometry gates stay hard.
|
||||
'PreferForward.strafe_x': 0.0,
|
||||
'PreferForward.strafe_theta': 0.0,
|
||||
'ObstacleFootprint.scale': 0.02,
|
||||
'PathAlign.scale': 32.0, 'PathAlign.forward_point_distance': x,
|
||||
'GoalAlign.scale': 24.0, 'GoalAlign.forward_point_distance': x,
|
||||
'PathDist.scale': 32.0, 'GoalDist.scale': 24.0,
|
||||
'RotateToGoal.scale': 32.0, 'RotateToGoal.slowing_factor': 5.0,
|
||||
'RotateToGoal.lookahead_time': -1.0,
|
||||
},
|
||||
)},
|
||||
'global_costmap': {'global_costmap': {'ros__parameters': costmap}},
|
||||
'local_costmap': {'local_costmap': {'ros__parameters': copy.deepcopy(costmap)}},
|
||||
}
|
||||
|
||||
|
||||
def observed_configuration(inputs, robot, origin_count):
|
||||
"""Use upstream ray clearing/obstacle marking for a rolling collision map.
|
||||
|
||||
Ground support and surface permission are separate inputs/gates. In
|
||||
particular, a free collision cell is not evidence of supporting pavement.
|
||||
"""
|
||||
if type(origin_count) is not int or not 1 <= origin_count <= 16:
|
||||
raise ValueError('Invalid observed sensor origin count')
|
||||
config = configuration(inputs, robot)
|
||||
sources = {
|
||||
'hazards': dict(topic='/observed_hazards', data_type='PointCloud2',
|
||||
sensor_frame='base_link', marking=True, clearing=False,
|
||||
min_obstacle_height=-0.01, max_obstacle_height=0.01,
|
||||
obstacle_min_range=0.0, obstacle_max_range=16.0,
|
||||
observation_persistence=0.0),
|
||||
}
|
||||
for index in range(origin_count):
|
||||
sources['range' + str(index)] = dict(
|
||||
topic='/observed_rays_' + str(index), data_type='PointCloud2',
|
||||
sensor_frame='range' + str(index), marking=False, clearing=True,
|
||||
min_obstacle_height=-0.01, max_obstacle_height=0.01,
|
||||
raytrace_min_range=0.0, raytrace_max_range=8.0,
|
||||
observation_persistence=0.0,
|
||||
)
|
||||
layer = dict(plugin='nav2_costmap_2d::ObstacleLayer',
|
||||
footprint_clearing_enabled=True,
|
||||
observation_sources=' '.join(sources), **sources)
|
||||
for name in ('global_costmap', 'local_costmap'):
|
||||
costmap = config[name][name]['ros__parameters']
|
||||
costmap.pop('static_layer')
|
||||
costmap.update(rolling_window=True, width=16, height=16,
|
||||
plugins=['obstacle_layer', 'inflation_layer'],
|
||||
obstacle_layer=copy.deepcopy(layer))
|
||||
return config
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
source /opt/ros/humble/setup.bash
|
||||
source /opt/underlay_ws/install/setup.bash
|
||||
source /opt/ndc_nav2/install/setup.bash
|
||||
exec "$@"
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Own only upstream Nav2 processes; stop the group when any node exits."""
|
||||
import argparse
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--parameters', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
processes = []
|
||||
stopped = False
|
||||
|
||||
def stop(signum, frame):
|
||||
nonlocal stopped
|
||||
stopped = True
|
||||
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
try:
|
||||
for package, executable in (('nav2_planner', 'planner_server'),
|
||||
('nav2_controller', 'controller_server'),
|
||||
('nav2_behaviors', 'behavior_server')):
|
||||
binary = '/opt/ndc_nav2/install/' + package + '/lib/' + package + '/' + executable
|
||||
processes.append(subprocess.Popen(
|
||||
[binary, '--ros-args', '--params-file', str(args.parameters), '-r',
|
||||
'/cmd_vel:=/nav2/'+('behavior' if package=='nav2_behaviors' else 'controller')+'_cmd_vel']))
|
||||
while not stopped and all(p.poll() is None for p in processes):
|
||||
time.sleep(.05)
|
||||
if not stopped:
|
||||
raise RuntimeError('A required Nav2 node exited')
|
||||
finally:
|
||||
for process in processes:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
for process in processes:
|
||||
try:
|
||||
process.wait(timeout=3)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=3)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Publish first-hit clearing rays and measured hazards to Nav2 ObstacleLayer.
|
||||
|
||||
Collision free space is not ground support or permission to drive. Those
|
||||
independent gates keep the existing observed terrain and semantic evidence.
|
||||
"""
|
||||
import math
|
||||
import struct
|
||||
|
||||
from geometry_msgs.msg import TransformStamped
|
||||
from rclpy.time import Time
|
||||
from sensor_msgs.msg import PointCloud2, PointField
|
||||
|
||||
|
||||
def cloud(stamp, frame, points):
|
||||
message = PointCloud2()
|
||||
message.header.stamp, message.header.frame_id = stamp, frame
|
||||
message.height, message.width = 1, len(points)
|
||||
message.fields = [PointField(name=name, offset=4*i, datatype=PointField.FLOAT32, count=1)
|
||||
for i, name in enumerate(('x','y','z'))]
|
||||
message.is_bigendian, message.is_dense = False, True
|
||||
message.point_step, message.row_step = 12, 12*len(points)
|
||||
message.data = b''.join(struct.pack('<fff', float(p[0]), float(p[1]), 0.) for p in points)
|
||||
return message
|
||||
|
||||
|
||||
class ObservedCollision:
|
||||
def __init__(self, node, max_step, origin_count):
|
||||
self.node, self.max_step = node, max_step
|
||||
self.rays = [node.create_publisher(PointCloud2, '/observed_rays_'+str(i), 2)
|
||||
for i in range(origin_count)]
|
||||
self.hazards = node.create_publisher(PointCloud2, '/observed_hazards', 2)
|
||||
|
||||
def publish(self, request, terrain, elapsed):
|
||||
rays = request['range_rays']
|
||||
age = float(request['geometry_age_seconds'])+elapsed
|
||||
if not math.isfinite(age) or age < 0 or len(rays['origins']) != len(self.rays):
|
||||
raise ValueError('Invalid observed collision age/origins')
|
||||
if age > .8:
|
||||
return False
|
||||
stamp = Time(nanoseconds=self.node.get_clock().now().nanoseconds-int(age*1e9)).to_msg()
|
||||
transforms=[]
|
||||
for i, origin in enumerate(rays['origins']):
|
||||
tf = TransformStamped()
|
||||
tf.header.frame_id, tf.child_frame_id, tf.header.stamp = 'map','range'+str(i),stamp
|
||||
tf.transform.translation.x, tf.transform.translation.y = map(float, origin[:2])
|
||||
tf.transform.rotation.w = 1.
|
||||
transforms.append(tf)
|
||||
self.node.tf.sendTransform(transforms)
|
||||
for i, (publisher, origin) in enumerate(zip(self.rays, rays['origins'])):
|
||||
points=[[end[0]-origin[0],end[1]-origin[1]]
|
||||
for end, owner in zip(rays['ends'], rays['origin_indices']) if owner==i]
|
||||
publisher.publish(cloud(stamp,'range'+str(i),points))
|
||||
self.hazards.publish(cloud(stamp,'map',terrain[terrain[:,3]>self.max_step+1e-4]))
|
||||
return True
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Prepare existing geometry kernels and a narrow DWB track critic, offline."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import subprocess
|
||||
import tarfile
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
BASE = 'sha256:dc6daf1153157860a70dc4a62419da0d61a5dd3941c8f41282ab9f7413a9dac6'
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser()
|
||||
parser.add_argument('--output',type=Path,required=True)
|
||||
parser.add_argument('--ground',action='store_true',help='Build PCL in its existing terrain dependency image')
|
||||
args=parser.parse_args()
|
||||
root=Path(__file__).resolve().parents[1]/'navigation'
|
||||
base = 'sha256:8517fd5d13406648907c87dd4adf771238c6a3a30fcedd555ca5a5287edebc16' if args.ground else BASE
|
||||
sources={name:(root/name).read_bytes() for name in
|
||||
(('pcl_ground.cpp',) if args.ground else ('support_native.cpp','terrain_connectivity.cpp'))}
|
||||
if args.ground:
|
||||
sources['CMakeLists.txt'] = (root/'pcl_ground.cmake').read_bytes()
|
||||
if not args.ground:
|
||||
for path in (root.parent/'nav2/rover_critics').iterdir():
|
||||
if path.is_file(): sources['rover_critics/'+path.name]=path.read_bytes()
|
||||
entrypoint = 'terrain_entrypoint.sh' if args.ground else 'runtime_entrypoint.sh'
|
||||
sources['runtime_entrypoint.sh']=(root.parent/'nav2'/entrypoint).read_bytes()
|
||||
files={name:hashlib.sha256(data).hexdigest() for name,data in sources.items()}
|
||||
files['prepare_kernels.py']=hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
|
||||
identity=hashlib.sha256(json.dumps(dict(base=base,files=files),sort_keys=True).encode()).hexdigest()
|
||||
args.output.mkdir(parents=True,exist_ok=False)
|
||||
report=dict(base=base,files=files,identity=identity,utc=datetime.now(timezone.utc).isoformat(),activated=False)
|
||||
cid=None;started=time.monotonic()
|
||||
def docker(*args,timeout=30,check=True):
|
||||
return subprocess.run(['docker',*args],capture_output=True,text=True,timeout=timeout,check=check)
|
||||
try:
|
||||
assert docker('image','inspect',base,'--format','{{.Id}}').stdout.strip()==base
|
||||
assert not Path('D:/NDC_MISSIONCORE/runtime/simulation/state/active.json').exists()
|
||||
command='mkdir -p /opt/missioncore && g++ -std=c++17 -O3 -shared -fPIC /sources/support_native.cpp -o /opt/missioncore/libsupport_surface.so && g++ -O3 -std=c++17 -ffp-contract=off -fno-fast-math -fPIC -shared /sources/terrain_connectivity.cpp -o /opt/missioncore/libterrain_connectivity.so'
|
||||
command += ' && source /opt/ros/humble/setup.bash && source /opt/underlay_ws/install/setup.bash && source /opt/ndc_nav2/install/setup.bash && mkdir -p /opt/ndc_rover && cd /opt/ndc_rover && MAKEFLAGS=-j2 colcon build --base-paths /sources/rover_critics --packages-select ndc_rover_critics --parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF'
|
||||
if args.ground:
|
||||
command = 'mkdir -p /opt/missioncore && cmake -S /sources -B /tmp/pcl-build -DCMAKE_BUILD_TYPE=Release && cmake --build /tmp/pcl-build -j2'
|
||||
cid=docker('create','--name','ndc-mission-core-nav2-kernels-'+identity[:16],
|
||||
'--network','none','--cpus','2','--memory','2g','--pids-limit','128','--cap-drop','ALL',
|
||||
'--security-opt','no-new-privileges','--label','com.nodedc.product=mission-core',
|
||||
'--label','com.nodedc.stack=ai-polygon','--label','com.nodedc.role=nav2-kernel-preparation',
|
||||
'--label','com.nodedc.managed-by=ai-polygon-preparation',
|
||||
'--label','com.nodedc.build-sha256='+identity,
|
||||
'--entrypoint','/bin/bash',base,'-c','exec timeout --signal=TERM --kill-after=5s 90 bash -c '+__import__('shlex').quote(command)).stdout.strip()
|
||||
report['container_id']=cid
|
||||
payload=io.BytesIO()
|
||||
with tarfile.open(fileobj=payload,mode='w') as archive:
|
||||
for name,data in sources.items():
|
||||
entry=tarfile.TarInfo('sources/'+name);entry.size=len(data)
|
||||
archive.addfile(entry,io.BytesIO(data))
|
||||
subprocess.run(['docker','cp','-',cid+':/'],input=payload.getvalue(),capture_output=True,check=True,timeout=10)
|
||||
result=docker('start','-a',cid,timeout=100,check=False)
|
||||
(args.output/'build.log').write_text(result.stdout+result.stderr)
|
||||
if result.returncode:raise RuntimeError('Existing geometry kernels did not compile')
|
||||
docker('cp',cid+':/opt/missioncore',str(args.output/'kernels'))
|
||||
report['kernels']={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in (args.output/'kernels').iterdir()}
|
||||
tag=('ndc-mission-core-terrain:pcl-ground-' if args.ground else 'ndc-mission-core-nav2:1.1.17-rover-')+identity[:16]
|
||||
image=docker('commit','--change','ENTRYPOINT ["/bin/bash", "/sources/runtime_entrypoint.sh"]',
|
||||
'--change','CMD ["bash"]','--change','LABEL com.nodedc.role=nav2-runtime',cid,tag,timeout=120).stdout.strip()
|
||||
report.update(image=image,tag=tag,status='built')
|
||||
except BaseException as error:
|
||||
report.update(status='failed',error=type(error).__name__+': '+str(error));raise
|
||||
finally:
|
||||
if cid:
|
||||
docker('rm','-f',cid)
|
||||
report['cleanup_confirmed']=not docker('ps','-aq','--filter','id='+cid).stdout.strip()
|
||||
report['elapsed_s']=time.monotonic()-started
|
||||
(args.output/'build.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Compare native Nav2 on archived first-hit rays and classified obstacles.
|
||||
|
||||
Replays captured data on a diagnostic ROS clock with no actuator or live
|
||||
command authority. No scene mesh, synthesized floor, or added route points.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import rclpy
|
||||
import yaml
|
||||
from action_msgs.msg import GoalStatus
|
||||
from check_ros_integration import Check
|
||||
from configuration import observed_configuration
|
||||
from geometry_msgs.msg import TransformStamped
|
||||
from lifecycle_msgs.msg import Transition
|
||||
from nav2_msgs.action import ComputePathToPose
|
||||
from nav2_msgs.srv import GetCostmap
|
||||
from nav_msgs.msg import Odometry
|
||||
from sensor_msgs.msg import PointCloud2
|
||||
from observed_collision import cloud
|
||||
|
||||
|
||||
class Replay(Check):
|
||||
def __init__(self, snapshot, max_step):
|
||||
self.request = snapshot['exchange']['request']
|
||||
self.rays = self.request['range_rays']
|
||||
self.pose = self.request['pose']
|
||||
self.hazards = [p for p in snapshot['exchange']['terrain'] if p[3] > max_step + 1e-4]
|
||||
x, y, z, w = self.pose[3:]
|
||||
self.yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
|
||||
super().__init__()
|
||||
self.ray_pubs = [self.create_publisher(PointCloud2, '/observed_rays_' + str(i), 2)
|
||||
for i in range(len(self.rays['origins']))]
|
||||
self.hazard_pub = self.create_publisher(PointCloud2, '/observed_hazards', 2)
|
||||
self.ray_timer = self.create_timer(0.1, self.publish_observation)
|
||||
|
||||
def publish_pose(self):
|
||||
transforms = []
|
||||
stamp = self.get_clock().now().to_msg()
|
||||
for name, xyz, yaw in [('base_link', self.pose[:3], self.yaw), *[
|
||||
('range' + str(i), p, 0.) for i, p in enumerate(self.rays['origins'])]]:
|
||||
tf = TransformStamped()
|
||||
tf.header.stamp, tf.header.frame_id, tf.child_frame_id = stamp, 'map', name
|
||||
tf.transform.translation.x, tf.transform.translation.y = map(float, xyz[:2])
|
||||
tf.transform.rotation.z, tf.transform.rotation.w = math.sin(yaw/2), math.cos(yaw/2)
|
||||
transforms.append(tf)
|
||||
self.tf.sendTransform(transforms)
|
||||
odom = Odometry()
|
||||
odom.header.stamp, odom.header.frame_id, odom.child_frame_id = stamp, 'map', 'base_link'
|
||||
odom.pose.pose.position.x, odom.pose.pose.position.y = map(float, self.pose[:2])
|
||||
odom.pose.pose.orientation = transforms[0].transform.rotation
|
||||
self.odom_pub.publish(odom)
|
||||
|
||||
def publish_observation(self):
|
||||
stamp = self.get_clock().now().to_msg()
|
||||
for index, (publisher, origin) in enumerate(zip(self.ray_pubs, self.rays['origins'])):
|
||||
points = [[end[0]-origin[0], end[1]-origin[1]]
|
||||
for end, owner in zip(self.rays['ends'], self.rays['origin_indices'])
|
||||
if owner == index]
|
||||
publisher.publish(cloud(stamp, 'range' + str(index), points))
|
||||
self.hazard_pub.publish(cloud(stamp, 'map', self.hazards))
|
||||
|
||||
def plan(self):
|
||||
if not self.planner.wait_for_server(timeout_sec=5):
|
||||
raise TimeoutError('Planner action unavailable')
|
||||
request = ComputePathToPose.Goal()
|
||||
request.planner_id, request.use_start = 'GridBased', True
|
||||
goal = self.request['goal']
|
||||
heading = math.atan2(goal[1]-self.pose[1], goal[0]-self.pose[0])
|
||||
for target, position, yaw in ((request.start, self.pose, self.yaw),
|
||||
(request.goal, goal, heading)):
|
||||
target.header.frame_id, target.header.stamp = 'map', self.get_clock().now().to_msg()
|
||||
target.pose.position.x, target.pose.position.y = map(float, position[:2])
|
||||
target.pose.orientation.z, target.pose.orientation.w = math.sin(yaw/2), math.cos(yaw/2)
|
||||
handle = self.await_result(self.planner.send_goal_async(request))
|
||||
if not handle.accepted:
|
||||
raise RuntimeError('Planner action was not accepted')
|
||||
return self.await_result(handle.get_result_async())
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
for name in ('inputs', 'robot', 'snapshot', 'output'):
|
||||
parser.add_argument('--' + name, type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
inputs, robot = json.loads(args.inputs.read_text()), json.loads(args.robot.read_text())
|
||||
snapshot = json.loads(args.snapshot.read_text())
|
||||
if snapshot['exchange']['request']['execution_inputs_sha256'] != inputs['sha256']:
|
||||
raise ValueError('Archived observation execution identity mismatch')
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
config = observed_configuration(inputs, robot, len(snapshot['exchange']['request']['range_rays']['origins']))
|
||||
parameters = args.output / 'parameters.yaml'
|
||||
parameters.write_text(yaml.safe_dump(config, sort_keys=False))
|
||||
report = dict(authority=None, qualified=False, scope='archived-input Nav2 diagnostic',
|
||||
snapshot_sha256=hashlib.sha256(args.snapshot.read_bytes()).hexdigest(),
|
||||
configuration_sha256=hashlib.sha256(parameters.read_bytes()).hexdigest(),
|
||||
source_observation_id=snapshot['exchange']['observation_id'])
|
||||
processes, logs = [], []
|
||||
rclpy.init()
|
||||
node = Replay(snapshot, inputs['robot']['geometry']['max_step_m'])
|
||||
try:
|
||||
for package, executable in (('nav2_planner', 'planner_server'),
|
||||
('nav2_controller', 'controller_server')):
|
||||
log = (args.output / (executable + '.log')).open('w'); logs.append(log)
|
||||
processes.append(subprocess.Popen(
|
||||
['/opt/ndc_nav2/install/' + package + '/lib/' + package + '/' + executable,
|
||||
'--ros-args', '--params-file', str(parameters)], stdout=log, stderr=subprocess.STDOUT))
|
||||
node.lifecycle(executable, Transition.TRANSITION_CONFIGURE)
|
||||
node.lifecycle(executable, Transition.TRANSITION_ACTIVATE)
|
||||
node.spin_for(0.5)
|
||||
client = node.create_client(GetCostmap, '/global_costmap/get_costmap')
|
||||
assert client.wait_for_service(timeout_sec=5)
|
||||
grid = node.await_result(client.call_async(GetCostmap.Request())).map
|
||||
(args.output / 'costmap.json').write_text(json.dumps(dict(
|
||||
origin=[grid.metadata.origin.position.x, grid.metadata.origin.position.y],
|
||||
resolution=grid.metadata.resolution, size=[grid.metadata.size_x, grid.metadata.size_y],
|
||||
data=list(grid.data))))
|
||||
result = node.plan()
|
||||
report.update(status=result.status,
|
||||
path=[[p.pose.position.x, p.pose.position.y, p.pose.orientation.z, p.pose.orientation.w]
|
||||
for p in result.result.path.poses],
|
||||
original={k:snapshot['exchange']['result'][k] for k in ('status', 'speed_mps', 'yaw_rate_rps')})
|
||||
if result.status == GoalStatus.STATUS_SUCCEEDED:
|
||||
report['controller'] = node.follow_and_cancel(result.result.path)
|
||||
except BaseException as error:
|
||||
report['error'] = type(error).__name__ + ': ' + str(error)
|
||||
raise
|
||||
finally:
|
||||
for process in processes:
|
||||
process.terminate()
|
||||
for process in processes:
|
||||
try:
|
||||
process.wait(timeout=3)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill(); process.wait(timeout=3)
|
||||
for log in logs:
|
||||
log.close()
|
||||
node.destroy_node(); rclpy.shutdown()
|
||||
(args.output / 'result.json').write_text(json.dumps(report, indent=2) + '\n')
|
||||
print(json.dumps({k:v for k,v in report.items() if k not in ('path','controller')}, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,291 @@
|
||||
"""ROS action/message boundary; upstream Nav2 owns paths and velocity proposals.
|
||||
|
||||
The caller spins this node and owns observation/command leases. Repeating TF
|
||||
uses the original measurement stamp. FollowPath updates use Nav2's native
|
||||
preemption; command admission resumes after feedback for the new goal.
|
||||
"""
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
|
||||
from action_msgs.msg import GoalStatus
|
||||
from builtin_interfaces.msg import Duration
|
||||
from geometry_msgs.msg import TransformStamped, Twist
|
||||
from lifecycle_msgs.msg import Transition
|
||||
from lifecycle_msgs.srv import ChangeState
|
||||
from nav2_msgs.action import BackUp, ComputePathToPose, FollowPath, Spin
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.action import ActionClient
|
||||
from rclpy.node import Node
|
||||
from rclpy.time import Time
|
||||
from tf2_ros import TransformBroadcaster
|
||||
|
||||
|
||||
def yaw_of(pose):
|
||||
x, y, z, w = pose[3:]
|
||||
return math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
|
||||
|
||||
|
||||
class RosNavigation(Node):
|
||||
def __init__(self):
|
||||
super().__init__('missioncore_nav2_adapter')
|
||||
self.condition = threading.Condition()
|
||||
self.action_lock = threading.Lock()
|
||||
self.pose = None
|
||||
self.action_handle = self.terminal = self.latest_command = None
|
||||
self.command_sequence = 0
|
||||
self.action_sequence = 0
|
||||
self.last_zero_sequence = 0
|
||||
self.failed = False
|
||||
self.pending_feedback = None
|
||||
self.history = deque(maxlen=256)
|
||||
self.tf = TransformBroadcaster(self)
|
||||
self.odom = self.create_publisher(Odometry, '/odom', 5)
|
||||
self.create_timer(.02, self.publish_pose)
|
||||
self.active_source = None
|
||||
for source in ('controller', 'behavior'):
|
||||
self.create_subscription(Twist, '/nav2/'+source+'_cmd_vel',
|
||||
lambda value, owner=source: self.on_command(value, owner), 20)
|
||||
self.planner = ActionClient(self, ComputePathToPose, '/compute_path_to_pose')
|
||||
self.controller = ActionClient(self, FollowPath, '/follow_path')
|
||||
self.spin_client = ActionClient(self, Spin, '/spin')
|
||||
self.backup_client = ActionClient(self, BackUp, '/backup')
|
||||
|
||||
@staticmethod
|
||||
def await_result(future, timeout):
|
||||
done = threading.Event()
|
||||
future.add_done_callback(lambda _: done.set())
|
||||
if not done.wait(timeout):
|
||||
raise TimeoutError('Nav2 response timeout')
|
||||
return future.result()
|
||||
|
||||
def activate(self):
|
||||
for name in ('planner_server', 'controller_server', 'behavior_server'):
|
||||
client = self.create_client(ChangeState, '/' + name + '/change_state')
|
||||
try:
|
||||
if not client.wait_for_service(timeout_sec=8):
|
||||
raise TimeoutError(name + ' unavailable')
|
||||
for transition in (Transition.TRANSITION_CONFIGURE, Transition.TRANSITION_ACTIVATE):
|
||||
request = ChangeState.Request()
|
||||
request.transition.id = transition
|
||||
if not self.await_result(client.call_async(request), 8).success:
|
||||
raise RuntimeError(name + ' lifecycle transition failed')
|
||||
finally:
|
||||
self.destroy_client(client)
|
||||
for client in (self.planner, self.controller, self.spin_client, self.backup_client):
|
||||
if not client.wait_for_server(timeout_sec=2):
|
||||
raise TimeoutError('Nav2 action unavailable')
|
||||
|
||||
def observe_pose(self, pose, age, twist=None):
|
||||
if (len(pose) != 7 or (twist is not None and len(twist) != 3)
|
||||
or not all(math.isfinite(float(v)) for v in (*pose, *(twist or []), age))
|
||||
or age < 0 or abs(sum(v*v for v in pose[3:])-1) > .02):
|
||||
raise ValueError('Invalid measured odometry')
|
||||
now = time.monotonic()
|
||||
stamp = self.get_clock().now().nanoseconds-int(age*1e9)
|
||||
if stamp < 0:
|
||||
raise ValueError('Invalid odometry stamp')
|
||||
with self.condition:
|
||||
captured = now-age
|
||||
if self.pose is None or captured >= self.pose[0]:
|
||||
self.pose = (captured, tuple(pose), tuple(twist) if twist is not None else None, stamp)
|
||||
self.publish_pose()
|
||||
|
||||
def publish_pose(self):
|
||||
with self.condition:
|
||||
measured = self.pose
|
||||
if measured is None or time.monotonic()-measured[0] > .5:
|
||||
return
|
||||
_, pose, twist, stamp = measured
|
||||
yaw = yaw_of(pose)
|
||||
transform = TransformStamped()
|
||||
transform.header.frame_id, transform.child_frame_id = 'map', 'base_link'
|
||||
transform.header.stamp = Time(nanoseconds=stamp).to_msg()
|
||||
transform.transform.translation.x, transform.transform.translation.y = map(float, pose[:2])
|
||||
transform.transform.rotation.z, transform.transform.rotation.w = math.sin(yaw/2), math.cos(yaw/2)
|
||||
self.tf.sendTransform(transform)
|
||||
if twist is None:
|
||||
return # A bootstrap pose is not a measured zero velocity.
|
||||
odom = Odometry()
|
||||
odom.header, odom.child_frame_id = transform.header, 'base_link'
|
||||
odom.pose.pose.position.x, odom.pose.pose.position.y = map(float, pose[:2])
|
||||
odom.pose.pose.orientation = transform.transform.rotation
|
||||
odom.twist.twist.linear.x, odom.twist.twist.linear.y, odom.twist.twist.angular.z = map(float, twist)
|
||||
self.odom.publish(odom)
|
||||
|
||||
def on_command(self, value, source):
|
||||
command = (time.monotonic(), float(value.linear.x), float(value.angular.z))
|
||||
with self.condition:
|
||||
if source != self.active_source:
|
||||
return
|
||||
self.command_sequence += 1
|
||||
self.history.append((self.command_sequence, *command))
|
||||
if command[1:] == (0., 0.):
|
||||
self.last_zero_sequence = self.command_sequence
|
||||
if self.pending_feedback is None:
|
||||
self.latest_command = command
|
||||
self.condition.notify_all()
|
||||
|
||||
def plan(self, pose, goal, yaw):
|
||||
request = ComputePathToPose.Goal()
|
||||
request.planner_id, request.use_start = 'GridBased', True
|
||||
for target, xy, heading in ((request.start, pose[:2], yaw_of(pose)),
|
||||
(request.goal, goal[:2], yaw)):
|
||||
target.header.frame_id, target.header.stamp = 'map', self.get_clock().now().to_msg()
|
||||
target.pose.position.x, target.pose.position.y = map(float, xy)
|
||||
target.pose.orientation.z, target.pose.orientation.w = math.sin(heading/2), math.cos(heading/2)
|
||||
handle = self.accept(self.planner, request, .2)
|
||||
if not handle.accepted:
|
||||
raise RuntimeError('Nav2 planner rejected request')
|
||||
try:
|
||||
result = self.await_result(handle.get_result_async(), .65)
|
||||
except TimeoutError:
|
||||
# Do not leave work from a timed-out HTTP transaction as authority.
|
||||
self.await_result(handle.cancel_goal_async(), .2)
|
||||
raise
|
||||
return result.result.path if result.status == GoalStatus.STATUS_SUCCEEDED else None
|
||||
|
||||
def accept(self, client, request, timeout, feedback_callback=None):
|
||||
if self.failed:
|
||||
raise RuntimeError('Nav2 action boundary requires reset')
|
||||
options = {} if feedback_callback is None else {'feedback_callback': feedback_callback}
|
||||
future = client.send_goal_async(request, **options)
|
||||
try:
|
||||
return self.await_result(future, timeout)
|
||||
except TimeoutError:
|
||||
# A late action acceptance must not survive the failed transaction.
|
||||
# The callback cannot block the ROS executor waiting for its reply.
|
||||
with self.condition:
|
||||
self.failed = True
|
||||
self.active_source = self.latest_command = None
|
||||
def cancel_late(done):
|
||||
handle = done.result()
|
||||
if handle is not None and handle.accepted:
|
||||
handle.cancel_goal_async()
|
||||
future.add_done_callback(cancel_late)
|
||||
raise
|
||||
|
||||
def _stop(self):
|
||||
if self.action_handle is None:
|
||||
return
|
||||
with self.condition:
|
||||
self.pending_feedback = None
|
||||
sequence = self.command_sequence
|
||||
if not self.terminal.done():
|
||||
self.await_result(self.action_handle.cancel_goal_async(), .25)
|
||||
result = self.await_result(self.terminal, .4)
|
||||
if result.status not in (GoalStatus.STATUS_CANCELED, GoalStatus.STATUS_SUCCEEDED,
|
||||
GoalStatus.STATUS_ABORTED):
|
||||
raise RuntimeError('Nav2 action did not terminate')
|
||||
with self.condition:
|
||||
if not self.condition.wait_for(lambda: self.last_zero_sequence > sequence, .25):
|
||||
raise TimeoutError('Nav2 cancellation zero was not observed')
|
||||
else:
|
||||
with self.condition:
|
||||
if not self.condition.wait_for(
|
||||
lambda: self.last_zero_sequence > self.action_sequence, .25):
|
||||
raise TimeoutError('Nav2 terminal zero was not observed')
|
||||
self.action_handle = self.terminal = None
|
||||
with self.condition:
|
||||
self.active_source = None
|
||||
self.latest_command = None
|
||||
|
||||
def stop(self):
|
||||
with self.action_lock:
|
||||
self._stop()
|
||||
|
||||
def _execute(self, client, request, source):
|
||||
with self.action_lock:
|
||||
self._stop()
|
||||
with self.condition:
|
||||
self.latest_command = None
|
||||
self.active_source = source
|
||||
sequence = self.command_sequence
|
||||
self.action_sequence = sequence
|
||||
self.action_handle = self.accept(client, request, .25)
|
||||
if not self.action_handle.accepted:
|
||||
self.action_handle = None
|
||||
self.active_source = None
|
||||
raise RuntimeError('Nav2 motion action rejected request')
|
||||
self.terminal = self.action_handle.get_result_async()
|
||||
with self.condition:
|
||||
self.condition.wait_for(lambda: self.command_sequence > sequence
|
||||
and self.latest_command is not None, .25)
|
||||
return self.native_command()
|
||||
|
||||
def follow(self, path, *, continuing=False):
|
||||
request = FollowPath.Goal()
|
||||
request.path, request.controller_id, request.goal_checker_id = path, 'FollowPath', 'goal_checker'
|
||||
with self.action_lock:
|
||||
# The controller's updateGlobalPath accepts a pending FollowPath
|
||||
# without zeroing velocity or resetting its progress checker.
|
||||
# Spin/BackUp still require terminal cancellation and a zero.
|
||||
if self.active_source != 'controller' or self.terminal is None or self.terminal.done():
|
||||
self._stop()
|
||||
continuing = False
|
||||
token = object()
|
||||
received = threading.Event()
|
||||
with self.condition:
|
||||
# Updating geometry for the same goal preserves the native
|
||||
# command stream. A changed goal still needs new feedback.
|
||||
self.pending_feedback = None if continuing else token
|
||||
if not continuing:
|
||||
self.latest_command = None
|
||||
self.active_source = 'controller'
|
||||
sequence = self.command_sequence
|
||||
self.action_sequence = sequence
|
||||
def feedback(_):
|
||||
# Feedback is emitted only after updateGlobalPath and the
|
||||
# new path's computeVelocityCommands in the pinned server.
|
||||
with self.condition:
|
||||
if continuing:
|
||||
received.set()
|
||||
elif self.pending_feedback is token:
|
||||
self.pending_feedback = None
|
||||
self.latest_command = None
|
||||
received.set()
|
||||
handle = self.accept(self.controller, request, .25, feedback)
|
||||
if not handle.accepted:
|
||||
with self.condition:
|
||||
self.failed = True
|
||||
self.active_source = self.latest_command = None
|
||||
raise RuntimeError('Nav2 path update rejected')
|
||||
self.action_handle, self.terminal = handle, handle.get_result_async()
|
||||
if continuing:
|
||||
# This same-goal stream is already admitted during preemption.
|
||||
# Waiting for its feedback only delays the next sensor frame;
|
||||
# accept() still fences rejection and late action acceptance.
|
||||
return self.native_command()
|
||||
if not received.wait(.25):
|
||||
# Do not bind a proposal to a path not yet used by Nav2.
|
||||
# A later /control may use it once matching feedback arrives.
|
||||
return self.native_command() if continuing else None
|
||||
with self.condition:
|
||||
self.condition.wait_for(lambda: self.command_sequence > sequence
|
||||
and self.latest_command is not None, .25)
|
||||
return self.native_command()
|
||||
|
||||
def spin(self, angle, duration):
|
||||
if not math.isfinite(angle) or abs(angle) > math.pi or not math.isfinite(duration) or duration < 0:
|
||||
raise ValueError('Invalid orientation goal')
|
||||
request = Spin.Goal()
|
||||
request.target_yaw = float(angle)
|
||||
request.time_allowance = Duration(sec=int(duration), nanosec=int((duration%1)*1e9))
|
||||
return self._execute(self.spin_client, request, 'behavior')
|
||||
|
||||
def backup(self, distance, speed, duration):
|
||||
if (not all(math.isfinite(v) and v > 0 for v in (distance, speed))
|
||||
or not math.isfinite(duration) or duration < 0):
|
||||
raise ValueError('Invalid reverse goal')
|
||||
request = BackUp.Goal()
|
||||
request.target.x, request.speed = float(distance), float(speed)
|
||||
request.time_allowance = Duration(sec=int(duration), nanosec=int((duration%1)*1e9))
|
||||
return self._execute(self.backup_client, request, 'behavior')
|
||||
|
||||
def native_command(self):
|
||||
with self.condition:
|
||||
if (self.failed or self.pending_feedback is not None or self.action_handle is None
|
||||
or self.terminal is None or self.terminal.done()):
|
||||
return None
|
||||
return self.latest_command
|
||||
@@ -0,0 +1,14 @@
|
||||
cmake_minimum_required(VERSION 3.8)
|
||||
project(ndc_rover_critics)
|
||||
find_package(ament_cmake REQUIRED)
|
||||
find_package(dwb_core REQUIRED)
|
||||
find_package(dwb_msgs REQUIRED)
|
||||
find_package(nav2_util REQUIRED)
|
||||
find_package(rclcpp REQUIRED)
|
||||
find_package(pluginlib REQUIRED)
|
||||
add_library(ndc_rover_critics SHARED forward_tracks.cpp)
|
||||
target_compile_features(ndc_rover_critics PUBLIC cxx_std_17)
|
||||
ament_target_dependencies(ndc_rover_critics dwb_core dwb_msgs nav2_util rclcpp pluginlib)
|
||||
pluginlib_export_plugin_description_file(dwb_core critics.xml)
|
||||
install(TARGETS ndc_rover_critics LIBRARY DESTINATION lib)
|
||||
ament_package()
|
||||
@@ -0,0 +1,5 @@
|
||||
<library path="ndc_rover_critics">
|
||||
<class type="ndc_rover_critics::ForwardTracksCritic" base_class_type="dwb_core::TrajectoryCritic">
|
||||
<description>Reject forward arcs requiring a track to reverse; native in-place spin remains separate.</description>
|
||||
</class>
|
||||
</library>
|
||||
@@ -0,0 +1,40 @@
|
||||
// DWB owns velocity sampling/scoring. This admits the rover's existing forward
|
||||
// mode before scoring; it does not rewrite a velocity or propose another path.
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
#include "dwb_core/trajectory_critic.hpp"
|
||||
#include "dwb_core/exceptions.hpp"
|
||||
#include "nav2_util/node_utils.hpp"
|
||||
#include "pluginlib/class_list_macros.hpp"
|
||||
|
||||
namespace ndc_rover_critics {
|
||||
class ForwardTracksCritic : public dwb_core::TrajectoryCritic {
|
||||
std::vector<double> centres_;
|
||||
public:
|
||||
void onInit() override {
|
||||
auto node = node_.lock();
|
||||
if (!node) {throw std::runtime_error("No DWB lifecycle node");}
|
||||
const auto key = dwb_plugin_name_ + "." + name_ + ".track_centres_y_m";
|
||||
nav2_util::declare_parameter_if_not_declared(
|
||||
node, key, rclcpp::ParameterValue(std::vector<double>{}));
|
||||
node->get_parameter(key, centres_);
|
||||
if (centres_.size() != 2 || !std::isfinite(centres_[0]) ||
|
||||
!std::isfinite(centres_[1]) || centres_[0] <= centres_[1]) {
|
||||
throw std::runtime_error("Ordered measured left/right track centres required");
|
||||
}
|
||||
}
|
||||
double scoreTrajectory(const dwb_msgs::msg::Trajectory2D & traj) override {
|
||||
const double v = traj.velocity.x, w = traj.velocity.theta;
|
||||
// Match SupportPolicy.fresh_context's existing 1e-6 direction boundary:
|
||||
// a stationary inner track needs both front/rear observations, just as a
|
||||
// spin does. Forward mode keeps both tracks moving forward; it cannot
|
||||
// silently request that different observation contract at the boundary.
|
||||
if (v > 1e-8 && (v - w*centres_[0] < 1e-6 || v - w*centres_[1] < 1e-6)) {
|
||||
throw dwb_core::IllegalTrajectoryException(name_, "Forward arc stops or reverses a track");
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
};
|
||||
}
|
||||
PLUGINLIB_EXPORT_CLASS(ndc_rover_critics::ForwardTracksCritic, dwb_core::TrajectoryCritic)
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0"?>
|
||||
<package format="3">
|
||||
<name>ndc_rover_critics</name><version>0.1.0</version>
|
||||
<description>Selected track kinematics admission for upstream DWB candidates.</description>
|
||||
<maintainer email="engineering@nodedc.local">Mission Core</maintainer>
|
||||
<license>BSD-3-Clause</license>
|
||||
<buildtool_depend>ament_cmake</buildtool_depend>
|
||||
<depend>dwb_core</depend><depend>dwb_msgs</depend><depend>nav2_util</depend>
|
||||
<depend>rclcpp</depend><depend>pluginlib</depend>
|
||||
<export><build_type>ament_cmake</build_type></export>
|
||||
</package>
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
source /opt/ros/humble/setup.bash
|
||||
source /opt/underlay_ws/install/setup.bash
|
||||
source /opt/ndc_nav2/install/setup.bash
|
||||
source /opt/ndc_rover/install/setup.bash
|
||||
exec "$@"
|
||||
@@ -0,0 +1,324 @@
|
||||
"""Mission Core transport for upstream Nav2 and the existing observed terrain.
|
||||
|
||||
No scene geometry, global route invention or alternative velocity controller.
|
||||
The HTTP interface stays compatible with the run-owned simulation pipeline.
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import rclpy
|
||||
import yaml
|
||||
from action_msgs.msg import GoalStatus
|
||||
from configuration import observed_configuration
|
||||
from navigation.arrival_approach import validate_orientation
|
||||
from navigation.continuous_control import ContinuousControl
|
||||
from navigation.footprint import Footprint
|
||||
from navigation.route_observation import route_observation
|
||||
from navigation.support_policy import SupportPolicy
|
||||
from observed_collision import ObservedCollision
|
||||
from rig_collision import collision_geometry
|
||||
from ros_navigation import RosNavigation, yaw_of
|
||||
from std_srvs.srv import Trigger
|
||||
from terrain_process import TerrainProcess
|
||||
|
||||
|
||||
class Navigation:
|
||||
def __init__(self, node, inputs, robot):
|
||||
self.node, self.inputs = node, inputs
|
||||
self.geometry = collision_geometry(inputs['robot']['geometry'], inputs['sensors']['mounts'])
|
||||
self.monitor = Footprint(self.geometry, deceleration=robot['control']['deceleration_mps2'])
|
||||
self.support = SupportPolicy(self.monitor, observed_pivots=True, observed_approaches=True,
|
||||
body_top_m=self.geometry['collision_top_m'])
|
||||
self.terrain = TerrainProcess(self.geometry, robot['control']['deceleration_mps2'],
|
||||
inputs['robot']['geometry'])
|
||||
self.collision = ObservedCollision(node, self.monitor.max_step, 2)
|
||||
self.plan_lock, self.owner_lock = threading.Lock(), threading.Lock()
|
||||
self.action_key = None
|
||||
self.completed_orientation = None
|
||||
self.path = None
|
||||
self.path_planned_at = float('-inf')
|
||||
self.active, self.failure = False, None
|
||||
self.activating = False
|
||||
self.latest_terrain = None
|
||||
self.control = ContinuousControl(self.monitor, self.support, lambda _:None,
|
||||
lambda *_:None, self.native_command, body_top_m=self.geometry['collision_top_m'],
|
||||
native_only=True)
|
||||
|
||||
def activate(self):
|
||||
try:
|
||||
self.node.activate()
|
||||
self.active = True
|
||||
except BaseException as error:
|
||||
self.failure = type(error).__name__+': '+str(error)
|
||||
|
||||
def native_command(self):
|
||||
with self.control.lock:
|
||||
plan = self.control.plans.get(self.control.path_id)
|
||||
with self.owner_lock:
|
||||
if plan is None or plan['result'].get('controller_goal') != self.action_key:
|
||||
return None
|
||||
return self.node.native_command()
|
||||
|
||||
def tick(self, value):
|
||||
self.node.observe_pose(value['pose'], float(value['pose_age_seconds']), value['measured_twist'])
|
||||
with self.owner_lock:
|
||||
owner = self.action_key
|
||||
result = self.control.tick(value)
|
||||
with self.owner_lock:
|
||||
if owner != self.action_key:
|
||||
result.update(speed_mps=0., yaw_rate_rps=0., reason='changed-path')
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def reply(reason, *, status='waiting-for-plan', **extra):
|
||||
return dict(speed_mps=0., yaw_rate_rps=0., status=status, path=[],
|
||||
diagnostic=dict(failure=reason), **extra)
|
||||
|
||||
def plan(self, value):
|
||||
entered = time.monotonic()
|
||||
if self.failure:
|
||||
raise RuntimeError(self.failure)
|
||||
pose, goal = np.asarray(value['pose'], dtype=float), np.asarray(value['goal'], dtype=float)
|
||||
limit, age = float(value['max_speed_mps']), float(value['geometry_age_seconds'])
|
||||
if (pose.shape != (7,) or goal.shape != (3,) or not np.isfinite(pose).all()
|
||||
or not np.isfinite(goal).all() or not math.isfinite(limit)
|
||||
or not 0 <= limit <= self.inputs['behavior']['max_speed_mps']
|
||||
or not math.isfinite(age) or age < 0
|
||||
or type(value['allow_reverse']) is not bool
|
||||
or type(value['translation_allowed']) is not bool):
|
||||
raise ValueError('Invalid navigation request')
|
||||
if age > .8 or value['detection_age_seconds'] > 2.:
|
||||
return self.reply('stale-observation')
|
||||
self.control.observe(value)
|
||||
if self.node.pose is None:
|
||||
self.node.observe_pose(value['pose'], age) # TF only; no invented velocity.
|
||||
if not self.activating:
|
||||
self.activating = True
|
||||
threading.Thread(target=self.activate, daemon=True).start()
|
||||
if not self.active or self.node.pose is None or self.node.pose[2] is None:
|
||||
return self.reply('waiting-for-measured-controller-state')
|
||||
if time.monotonic()-self.node.pose[0] > .5:
|
||||
return self.reply('stale-pose')
|
||||
observed = self.terrain.observe(value)
|
||||
terrain = observed['terrain']
|
||||
self.latest_terrain = observed
|
||||
observed['observation_id'] = value['observation_id']
|
||||
if not self.collision.publish(value, observed['search_terrain'], time.monotonic()-entered):
|
||||
return self.reply('stale-range')
|
||||
route = route_observation(terrain, pose, value, self.monitor.max_step)
|
||||
orientation = validate_orientation(value.get('orientation_target'))
|
||||
target = value.get('arrival_target')
|
||||
if target is not None:
|
||||
if len(target) != 2 or not all(math.isfinite(x) for x in target):
|
||||
raise ValueError('Invalid arrival target')
|
||||
if math.dist(pose[:2], target) <= self.inputs['mission']['arrival_radius_m']:
|
||||
assessment = self.monitor.assess_pose(terrain, pose, value['body_contact_height_m'])
|
||||
if assessment['admitted']:
|
||||
self.node.stop()
|
||||
with self.owner_lock:
|
||||
self.action_key = None
|
||||
return self.reply('arrival', status='arrival-accepted', arrival={**assessment,
|
||||
'observation':dict(pose=pose.tolist(), target_xy=list(target),
|
||||
simulation_time_seconds=value['simulation_time_seconds'],
|
||||
execution_inputs_sha256=self.inputs['sha256'])})
|
||||
if not value.get('visual_goal_available'):
|
||||
goal[:2] = target
|
||||
reverse = value['allow_reverse']
|
||||
orientation_key = ('spin', orientation['key'], tuple(orientation['xy'])) if orientation else None
|
||||
if (orientation_key is not None and self.action_key == orientation_key
|
||||
and self.node.terminal is not None and self.node.terminal.done()
|
||||
and self.node.terminal.result().status == GoalStatus.STATUS_SUCCEEDED):
|
||||
self.completed_orientation = orientation_key
|
||||
# Smac/DWB owns the approach to a permitted translation destination,
|
||||
# including recovery goals. Forcing a bearing-alignment Spin first can
|
||||
# sweep the rear into an obstacle when a forward arc is available.
|
||||
# Spin belongs only to explicit orientation-only intent; its completion
|
||||
# cannot authorize translation. BackUp keeps the existing body heading.
|
||||
orienting = (not reverse and orientation is not None
|
||||
and orientation_key != self.completed_orientation
|
||||
and not value['translation_allowed'])
|
||||
if not value['translation_allowed'] and not orienting:
|
||||
self.node.stop()
|
||||
return self.reply('no-permitted-goal', status='blocked', route_observation=route)
|
||||
if orienting:
|
||||
delta = np.asarray(orientation['xy'])-pose[:2]
|
||||
heading = math.atan2(delta[1], delta[0])
|
||||
angle = math.atan2(math.sin(heading-yaw_of(pose)), math.cos(heading-yaw_of(pose)))
|
||||
key = orientation_key
|
||||
if key != self.action_key:
|
||||
with self.owner_lock:
|
||||
self.action_key = None
|
||||
# Existing mission budgets use simulation time. Do not invent
|
||||
# a second wall-clock maneuver budget in a slower simulation.
|
||||
# The unchanged command/data leases still gate every output.
|
||||
self.node.spin(angle, 0.)
|
||||
local_path = [[0.,0.,0.],[0.,0.,0.]]
|
||||
elif reverse:
|
||||
delta = goal[:2]-pose[:2]
|
||||
heading = yaw_of(pose)
|
||||
rear = -float(delta @ [math.cos(heading), math.sin(heading)])
|
||||
if rear <= 0:
|
||||
self.node.stop()
|
||||
return self.reply('reverse-goal-is-not-behind', status='blocked')
|
||||
key = ('backup', tuple(goal[:2]), limit)
|
||||
if key != self.action_key:
|
||||
with self.owner_lock:
|
||||
self.action_key = None
|
||||
self.node.backup(rear, min(limit,.1), 0.)
|
||||
local_path = [[0.,0.,0.],[-rear,0.,0.]]
|
||||
else:
|
||||
# A sensor refresh is not a new motion goal. ROS feedback fences
|
||||
# a path update; the existing capture leases and raw range gates
|
||||
# still validate every command against the caller's observation.
|
||||
key = ('path', tuple(goal[:2]), limit)
|
||||
continuing = key == self.action_key
|
||||
# Match the pinned Nav2 BT's 1 Hz ComputePathToPose cadence.
|
||||
# The path is an intent, not a sensor sample: terrain, costmaps,
|
||||
# capture leases and command gates still refresh above/every tick.
|
||||
if (not continuing or self.path is None or self.node.native_command() is None
|
||||
or entered-self.path_planned_at >= 1.0):
|
||||
path = self.node.plan(pose, goal, math.atan2(goal[1]-pose[1],goal[0]-pose[0]))
|
||||
if path is None or len(path.poses) < 2:
|
||||
self.node.stop()
|
||||
return self.reply('no-path', status='blocked', route_observation=route)
|
||||
if not continuing:
|
||||
with self.owner_lock:
|
||||
self.action_key = None
|
||||
self.node.follow(path, continuing=continuing)
|
||||
self.path, self.path_planned_at = path, entered
|
||||
path = self.path
|
||||
c, s = math.cos(yaw_of(pose)), math.sin(yaw_of(pose))
|
||||
local_path = [[(p.pose.position.x-pose[0])*c+(p.pose.position.y-pose[1])*s,
|
||||
-(p.pose.position.x-pose[0])*s+(p.pose.position.y-pose[1])*c, 0.]
|
||||
for p in path.poses]
|
||||
with self.owner_lock:
|
||||
self.action_key = key
|
||||
native = self.node.native_command()
|
||||
if native is None:
|
||||
terminal = self.node.terminal.result() if self.node.terminal and self.node.terminal.done() else None
|
||||
return self.reply('native-action-complete' if terminal and terminal.status==GoalStatus.STATUS_SUCCEEDED
|
||||
else 'waiting-for-controller', route_observation=route)
|
||||
result = dict(speed_mps=native[1], yaw_rate_rps=native[2], status='path', path=local_path,
|
||||
controller_goal=key,
|
||||
route_observation=route, diagnostic=dict(terrain=observed['metrics'], controller='nav2'))
|
||||
# This is a proposal returned to the mission layer; /control supplies
|
||||
# the separately admitted command bound to current pose/range/intent.
|
||||
self.control.accept(value, result, terrain, detections=observed['detected'])
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
inputs = json.loads(Path(os.environ['MISSIONCORE_RUN_INPUTS']).read_text())
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
robot = json.loads((root/'robots'/ (inputs['robot']['robot_id']+'.json')).read_text())
|
||||
config = observed_configuration(inputs, robot, 2) # Mounted K1 and depth origins.
|
||||
parameters = Path('/tmp/missioncore-nav2.yaml')
|
||||
parameters.write_text(yaml.safe_dump(config, sort_keys=False))
|
||||
rclpy.init()
|
||||
node = RosNavigation()
|
||||
navigation = Navigation(node, inputs, robot)
|
||||
thread = threading.Thread(target=rclpy.spin, args=(node,), daemon=True); thread.start()
|
||||
terrain_reset = node.create_client(Trigger, '/terrain/reset')
|
||||
terrain_ready = node.create_client(Trigger, '/terrain/ready')
|
||||
process = subprocess.Popen([sys.executable, str(Path(__file__).with_name('nodes.py')),
|
||||
'--parameters', str(parameters)])
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = 'HTTP/1.1'
|
||||
disable_nagle_algorithm = True
|
||||
def reply(self, status, value):
|
||||
body = json.dumps(value, allow_nan=False).encode()
|
||||
self.send_response(status)
|
||||
self.send_header('Content-Type','application/json')
|
||||
self.send_header('Content-Length',str(len(body)))
|
||||
self.end_headers(); self.wfile.write(body)
|
||||
|
||||
def do_GET(self):
|
||||
if self.path == '/diagnostic-snapshot':
|
||||
with navigation.plan_lock:
|
||||
observed = navigation.latest_terrain
|
||||
self.reply(200,dict(schema_version='missioncore.navigation-diagnostic/v1',
|
||||
authority='none',execution_inputs_sha256=inputs['sha256'],
|
||||
exchange=navigation.control.snapshot(),
|
||||
current_observation_id=observed['observation_id'] if observed else None,
|
||||
current_metrics=observed['metrics'] if observed else None,
|
||||
current_detected=observed['detected'].tolist() if observed else [],
|
||||
geometry=observed['physical_terrain'].tolist() if observed else []))
|
||||
return
|
||||
ready = process.poll() is None and terrain_ready.service_is_ready() and not navigation.failure
|
||||
if ready:
|
||||
try:
|
||||
ready = node.await_result(terrain_ready.call_async(Trigger.Request()), .3).success
|
||||
except Exception:
|
||||
ready = False
|
||||
self.reply(200 if self.path=='/ready' and ready else 503,
|
||||
dict(ready=ready,execution_inputs_sha256=inputs['sha256'],
|
||||
robot_geometry=inputs['robot']['geometry']))
|
||||
|
||||
def do_POST(self):
|
||||
try:
|
||||
entered = time.perf_counter()
|
||||
size=int(self.headers.get('Content-Length','0'))
|
||||
if not 0 < size <= 3_000_000:
|
||||
raise ValueError('Bounded JSON body required')
|
||||
value=json.loads(self.rfile.read(size))
|
||||
decoded = time.perf_counter()
|
||||
if self.path=='/reset':
|
||||
with navigation.plan_lock:
|
||||
navigation.node.stop()
|
||||
response=node.await_result(terrain_reset.call_async(Trigger.Request()),2.)
|
||||
if not response.success:
|
||||
raise RuntimeError('Terrain reset failed')
|
||||
navigation.terrain.close()
|
||||
process.terminate(); process.wait(timeout=5)
|
||||
self.reply(200,dict(reset=True))
|
||||
os.execv(sys.executable,[sys.executable,str(Path(__file__).resolve())])
|
||||
if value.get('execution_inputs_sha256') != inputs['sha256']:
|
||||
raise ValueError('Execution input identity mismatch')
|
||||
if self.path=='/plan':
|
||||
with navigation.plan_lock:
|
||||
locked = time.perf_counter()
|
||||
result=navigation.plan(value)
|
||||
result.setdefault('diagnostic',{})['server_stage_ms'] = dict(
|
||||
read_decode=(decoded-entered)*1000,
|
||||
plan_lock=(locked-decoded)*1000,
|
||||
plan=(time.perf_counter()-locked)*1000)
|
||||
self.reply(200,result)
|
||||
elif self.path=='/control':
|
||||
self.reply(200,navigation.tick(value))
|
||||
else:
|
||||
self.reply(404,dict(error='unknown endpoint'))
|
||||
except (ValueError,KeyError,TypeError) as error:
|
||||
self.reply(400,dict(error=str(error)))
|
||||
except Exception as error:
|
||||
self.reply(503,dict(error=str(error)))
|
||||
|
||||
def log_message(self,*_):
|
||||
pass
|
||||
|
||||
def shutdown(*_):
|
||||
raise SystemExit(0)
|
||||
signal.signal(signal.SIGTERM,shutdown)
|
||||
try:
|
||||
ThreadingHTTPServer(('0.0.0.0',8010),Handler).serve_forever()
|
||||
finally:
|
||||
try:
|
||||
navigation.terrain.close()
|
||||
finally:
|
||||
process.terminate()
|
||||
try: process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired: process.kill();process.wait(timeout=2)
|
||||
rclpy.try_shutdown(); thread.join(timeout=2); node.destroy_node()
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"repository": "https://github.com/ros-navigation/navigation2",
|
||||
"version": "1.1.17",
|
||||
"commit": "0f8fda36ca1b84a840ad9b72a6c71776eefa6790",
|
||||
"archive_url": "https://codeload.github.com/ros-navigation/navigation2/tar.gz/0f8fda36ca1b84a840ad9b72a6c71776eefa6790",
|
||||
"archive_sha256": "641b6abe527eb862e9102259e3d4a33d5f8823f0bed7079adf4e785d466b6d1d",
|
||||
"base_image": "sha256:48d3727817bdb1582a40c46f3d2caecea509a60a67895b96e6558ed24b040644",
|
||||
"base_reference": "ghcr.io/ros-navigation/navigation2@sha256:48d3727817bdb1582a40c46f3d2caecea509a60a67895b96e6558ed24b040644"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
source /opt/ros/humble/setup.bash
|
||||
source /opt/cmu/install/setup.bash
|
||||
exec "$@"
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Own/reset the unchanged terrain process inside its pinned dependency image."""
|
||||
import signal
|
||||
import subprocess
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import rclpy
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.node import Node
|
||||
from sensor_msgs.msg import PointCloud2, PointField
|
||||
from sensor_msgs_py import point_cloud2
|
||||
from std_srvs.srv import Trigger
|
||||
from terrain_observation import PARAMETERS
|
||||
from navigation.pcl_ground import PclGround
|
||||
|
||||
|
||||
class TerrainNode(Node):
|
||||
def __init__(self):
|
||||
super().__init__('missioncore_terrain_owner')
|
||||
geometry = json.loads(Path(os.environ['MISSIONCORE_RUN_INPUTS']).read_text())['robot']['geometry']
|
||||
self.ground = PclGround(geometry)
|
||||
self.contact_height = geometry['body_contact_height_m']
|
||||
self.pending_scans, self.pending_poses = {}, {}
|
||||
self.ground_reply = self.create_publisher(PointCloud2, '/terrain/current_ground', 2)
|
||||
self.create_subscription(PointCloud2, '/terrain/current_scan', self.scan, 2)
|
||||
self.create_subscription(Odometry, '/state_estimation', self.pose, 2)
|
||||
self.process = None
|
||||
self.start()
|
||||
self.create_service(Trigger, '/terrain/reset', self.reset)
|
||||
self.create_service(Trigger, '/terrain/ready', self.ready)
|
||||
|
||||
def start(self):
|
||||
command = ['/opt/cmu/install/terrain_analysis/lib/terrain_analysis/terrainAnalysis', '--ros-args']
|
||||
for key, value in PARAMETERS.items():
|
||||
command += ['-p', key+':='+str(value).lower()]
|
||||
self.process = subprocess.Popen(command)
|
||||
|
||||
def stop(self):
|
||||
if self.process is None:
|
||||
return
|
||||
self.process.terminate()
|
||||
try:
|
||||
self.process.wait(timeout=1)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.process.kill(); self.process.wait(timeout=1)
|
||||
self.process = None
|
||||
|
||||
def ready(self, request, response):
|
||||
response.success = self.process is not None and self.process.poll() is None
|
||||
return response
|
||||
|
||||
def reset(self, request, response):
|
||||
self.pending_scans.clear(); self.pending_poses.clear()
|
||||
self.stop(); self.start()
|
||||
return self.ready(request, response)
|
||||
|
||||
def pose(self, message):
|
||||
self.pair(message, self.pending_poses)
|
||||
|
||||
def scan(self, message):
|
||||
self.pair(message, self.pending_scans)
|
||||
|
||||
def pair(self, message, pending):
|
||||
stamp = (message.header.stamp.sec, message.header.stamp.nanosec)
|
||||
pending[stamp] = message
|
||||
while len(pending) > 2:
|
||||
del pending[next(iter(pending))]
|
||||
if stamp not in self.pending_scans or stamp not in self.pending_poses:
|
||||
return
|
||||
scan, pose = self.pending_scans.pop(stamp), self.pending_poses.pop(stamp).pose.pose
|
||||
points = point_cloud2.read_points_numpy(scan, field_names=['x','y','z']).copy()
|
||||
q = pose.orientation
|
||||
up = np.array([2*(q.x*q.z+q.w*q.y), 2*(q.y*q.z-q.w*q.x),
|
||||
1-2*(q.x*q.x+q.y*q.y)])
|
||||
anchor = np.array([pose.position.x,pose.position.y,pose.position.z])-self.contact_height*up
|
||||
mask = self.ground.mask(points, ground_anchor=anchor)
|
||||
fields = [PointField(name=name, offset=i*4, datatype=PointField.FLOAT32, count=1)
|
||||
for i,name in enumerate(('x','y','z','intensity'))]
|
||||
self.ground_reply.publish(point_cloud2.create_cloud(scan.header, fields,
|
||||
np.column_stack((points, mask.astype(np.float32)))))
|
||||
|
||||
|
||||
def main():
|
||||
rclpy.init()
|
||||
node = TerrainNode()
|
||||
def stop(*_):
|
||||
rclpy.try_shutdown()
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
try:
|
||||
rclpy.spin(node)
|
||||
finally:
|
||||
node.stop(); node.destroy_node(); rclpy.try_shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,147 @@
|
||||
"""Reuse the existing ground observation stage, without CMU motion planning.
|
||||
|
||||
Only first-hit sensor data and calibrated semantic observations enter here.
|
||||
Output is measured terrain cost; it is not a command or a route permission.
|
||||
"""
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
|
||||
import numpy as np
|
||||
from nav_msgs.msg import Odometry
|
||||
from sensor_msgs.msg import PointCloud2, PointField
|
||||
from sensor_msgs_py import point_cloud2
|
||||
from std_msgs.msg import Header
|
||||
|
||||
from navigation.detection_obstacles import DetectionObstacles
|
||||
from navigation.observed_ground import observed_ground_costs
|
||||
from navigation.observed_space import ObservedSpace
|
||||
from navigation.semantic_surface import SemanticSurface
|
||||
from navigation.support_obstacles import SupportObstacles
|
||||
from navigation.terrain_costs import TerrainCostNormalizer, underbody_support_costs
|
||||
|
||||
|
||||
PARAMETERS = dict(scanVoxelSize=0.06, inputIsMapSnapshot=True, decayTime=0.5,
|
||||
noDecayDis=0.0, useSorting=True, quantileZ=0.25, considerDrop=True,
|
||||
clearDyObs=False, noDataObstacle=False, vehicleHeight=0.9,
|
||||
minRelZ=-2.0, maxRelZ=1.0, voxelPointUpdateThre=1, voxelTimeUpdateThre=0.0)
|
||||
|
||||
|
||||
class TerrainObservation:
|
||||
def __init__(self, node, monitor, geometry):
|
||||
self.node, self.monitor, self.geometry = node, monitor, geometry
|
||||
self.observed = ObservedSpace()
|
||||
self.normalize = TerrainCostNormalizer()
|
||||
self.semantics = SemanticSurface(retain_near=True, fuse_observations=True)
|
||||
self.detections = DetectionObstacles(monitor)
|
||||
self.support_obstacles = SupportObstacles(1.0)
|
||||
self.condition = threading.Condition()
|
||||
self.reply = None
|
||||
self.ground_reply = None
|
||||
self.seen_semantics = OrderedDict()
|
||||
self.scan = node.create_publisher(PointCloud2, '/registered_scan', 2)
|
||||
self.current_scan = node.create_publisher(PointCloud2, '/terrain/current_scan', 2)
|
||||
self.odom = node.create_publisher(Odometry, '/state_estimation', 2)
|
||||
node.create_subscription(PointCloud2, '/terrain_map', self.receive, 2)
|
||||
node.create_subscription(PointCloud2, '/terrain/current_ground', self.receive_ground, 2)
|
||||
|
||||
def receive_ground(self, message):
|
||||
points = point_cloud2.read_points_numpy(
|
||||
message, field_names=['x','y','z','intensity']).copy()
|
||||
stamp = message.header.stamp.sec * 1_000_000_000 + message.header.stamp.nanosec
|
||||
with self.condition:
|
||||
self.ground_reply = stamp, points
|
||||
self.condition.notify_all()
|
||||
|
||||
def receive(self, message):
|
||||
points = point_cloud2.read_points_numpy(
|
||||
message, field_names=['x', 'y', 'z', 'intensity'], skip_nans=True).copy()
|
||||
stamp = message.header.stamp.sec * 1_000_000_000 + message.header.stamp.nanosec
|
||||
with self.condition:
|
||||
self.reply = stamp, points
|
||||
self.condition.notify_all()
|
||||
|
||||
def observe(self, request):
|
||||
started = time.monotonic()
|
||||
pose = np.asarray(request['pose'], dtype=float)
|
||||
current = np.asarray(request['points'], dtype=np.float32)
|
||||
if (current.ndim != 2 or current.shape[1] != 3 or not 50 <= len(current) <= 30000
|
||||
or pose.shape != (7,) or not np.isfinite(current).all()
|
||||
or not np.isfinite(pose).all() or abs(np.linalg.norm(pose[3:])-1) > .01):
|
||||
raise ValueError('Invalid range/pose observation')
|
||||
rays = request['range_rays']
|
||||
points = self.observed.observe(current, pose, started,
|
||||
rays['origins'], rays['ends'], rays['origin_indices'], range_views=rays)
|
||||
remembered_at, remembered_count = time.monotonic(), len(points)
|
||||
for sample in request['semantic_observations']:
|
||||
age = float(sample['age_seconds'])
|
||||
if not math.isfinite(age) or age < 0:
|
||||
raise ValueError('Invalid semantic capture age')
|
||||
identity = sample['frame_id']
|
||||
if identity not in self.seen_semantics:
|
||||
self.semantics.observe(sample['samples'], started-age, pose,
|
||||
evidence_id=sample.get('capture_id', identity))
|
||||
self.seen_semantics[identity] = True
|
||||
while len(self.seen_semantics) > 128:
|
||||
self.seen_semantics.popitem(last=False)
|
||||
semantics_at = time.monotonic()
|
||||
header = Header(stamp=self.node.get_clock().now().to_msg(), frame_id='map')
|
||||
identity = header.stamp.sec * 1_000_000_000 + header.stamp.nanosec
|
||||
odom = Odometry(header=header, child_frame_id='vehicle')
|
||||
odom.pose.pose.position.x, odom.pose.pose.position.y, odom.pose.pose.position.z = map(float, pose[:3])
|
||||
q = odom.pose.pose.orientation
|
||||
q.x, q.y, q.z, q.w = map(float, pose[3:])
|
||||
fields = [PointField(name=name, offset=i*4, datatype=PointField.FLOAT32, count=1)
|
||||
for i, name in enumerate(('x', 'y', 'z', 'intensity'))]
|
||||
self.odom.publish(odom)
|
||||
self.current_scan.publish(point_cloud2.create_cloud(header, fields,
|
||||
np.column_stack((current, np.zeros(len(current), np.float32)))))
|
||||
self.scan.publish(point_cloud2.create_cloud(header, fields,
|
||||
np.column_stack((points, np.zeros(len(points), np.float32)))))
|
||||
with self.condition:
|
||||
ready = self.condition.wait_for(
|
||||
lambda: (self.reply is not None and abs(self.reply[0]-identity) <= 1000
|
||||
and self.ground_reply is not None and self.ground_reply[0] == identity),
|
||||
timeout=0.6)
|
||||
if not ready:
|
||||
raise TimeoutError('Terrain observation did not match the submitted sensor frame')
|
||||
points = self.reply[1].copy()
|
||||
ground = self.ground_reply[1].copy()
|
||||
if (ground.shape != (len(current), 4) or not np.array_equal(ground[:,:3], current)
|
||||
or not np.isin(ground[:,3], [0,1]).all()):
|
||||
raise ValueError('Ground segmentation changed the source range returns')
|
||||
terrain_at = time.monotonic()
|
||||
points, slope_count = self.normalize(points)
|
||||
points, body_count = underbody_support_costs(points, pose,
|
||||
request['body_contact_height_m'], geometry=self.geometry)
|
||||
points, patch_count = observed_ground_costs(points, pose,
|
||||
request['body_contact_height_m'], monitor=self.monitor)
|
||||
physical = points.copy()
|
||||
ground_at = time.monotonic()
|
||||
self.support_obstacles.revalidate(points, pose, request['body_contact_height_m'],
|
||||
monitor=self.monitor)
|
||||
self.support_obstacles.observe_ahead(points, pose, request['body_contact_height_m'],
|
||||
monitor=self.monitor, speed_mps=float(request['max_speed_mps']))
|
||||
support_at = time.monotonic()
|
||||
candidates = self.detections.observed(request)
|
||||
ground = current[ground[:,3] == 1]
|
||||
detected = self.detections.without_ground(candidates,
|
||||
self.semantics.permitted_terrain(ground, time.monotonic()))
|
||||
points = self.detections.overlay(points, detected)
|
||||
points, forbidden = self.semantics.apply(points, time.monotonic())
|
||||
search, _ = self.support_obstacles.apply(points, pose=pose, monitor=self.monitor)
|
||||
return dict(terrain=points, search_terrain=search, physical_terrain=physical, detected=detected,
|
||||
current_points=current,
|
||||
metrics=dict(detection_candidates=len(candidates),
|
||||
detection_ground_returns=len(candidates)-len(detected),
|
||||
slope_corrected=slope_count, observed_patches=patch_count,
|
||||
underbody_points=body_count, forbidden_points=forbidden,
|
||||
remembered_points=remembered_count, terrain_points=len(points),
|
||||
stage_ms=dict(memory=(remembered_at-started)*1000,
|
||||
semantics=(semantics_at-remembered_at)*1000,
|
||||
terrain=(terrain_at-semantics_at)*1000,
|
||||
ground=(ground_at-terrain_at)*1000,
|
||||
support=(support_at-ground_at)*1000,
|
||||
overlays=(time.monotonic()-support_at)*1000),
|
||||
processing_ms=(time.monotonic()-started)*1000))
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Run map construction apart from the latency-sensitive control interpreter.
|
||||
|
||||
One outstanding observation, ordinary process IPC, unchanged ROS PointCloud2
|
||||
and terrain implementation. All observation deadlines still belong to the
|
||||
caller; completion never makes an old observation fresh.
|
||||
"""
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
import multiprocessing
|
||||
import threading
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
|
||||
from navigation.footprint import Footprint
|
||||
from terrain_observation import TerrainObservation
|
||||
|
||||
_node = _thread = _terrain = None
|
||||
|
||||
|
||||
def initialize(geometry, deceleration, robot_geometry):
|
||||
global _node, _thread, _terrain
|
||||
rclpy.init()
|
||||
_node = Node('missioncore_terrain_observation')
|
||||
_terrain = TerrainObservation(_node, Footprint(geometry, deceleration=deceleration), robot_geometry)
|
||||
_thread = threading.Thread(target=rclpy.spin, args=(_node,), daemon=True)
|
||||
_thread.start()
|
||||
|
||||
|
||||
def ready():
|
||||
deadline = time.monotonic()+8
|
||||
while not (_terrain.scan.get_subscription_count() and _terrain.odom.get_subscription_count()
|
||||
and _terrain.current_scan.get_subscription_count()):
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError('Terrain observation subscriptions unavailable')
|
||||
time.sleep(.02)
|
||||
return True
|
||||
|
||||
|
||||
def observe(value):
|
||||
return _terrain.observe(value)
|
||||
|
||||
|
||||
def close():
|
||||
rclpy.try_shutdown()
|
||||
_thread.join(timeout=2)
|
||||
_node.destroy_node()
|
||||
|
||||
|
||||
class TerrainProcess:
|
||||
def __init__(self, geometry, deceleration, robot_geometry):
|
||||
self.pool = ProcessPoolExecutor(max_workers=1, mp_context=multiprocessing.get_context('spawn'),
|
||||
initializer=initialize, initargs=(geometry, deceleration, robot_geometry))
|
||||
try:
|
||||
self.pool.submit(ready).result(timeout=10)
|
||||
except BaseException:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def observe(self, value):
|
||||
# The enclosing single plan_lock prevents a sensor-frame queue.
|
||||
return self.pool.submit(observe, value).result(timeout=2)
|
||||
|
||||
def close(self):
|
||||
pool, self.pool = self.pool, None
|
||||
if pool is None:
|
||||
return
|
||||
try:
|
||||
pool.submit(close).result(timeout=3)
|
||||
finally:
|
||||
pool.shutdown(wait=True, cancel_futures=True)
|
||||
@@ -0,0 +1,9 @@
|
||||
FROM ndc-ai-polygon-cmu:dense-footprint-v1
|
||||
COPY patch_clearance_preference.py /opt/cmu/patch_clearance_preference.py
|
||||
COPY missioncore_clearance.hpp /opt/cmu/src/local_planner/src/missioncore_clearance.hpp
|
||||
WORKDIR /opt/cmu
|
||||
RUN python3 patch_clearance_preference.py && source /opt/ros/humble/setup.bash \
|
||||
&& MAKEFLAGS=-j2 colcon build --base-paths src --packages-select local_planner \
|
||||
--parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
|
||||
WORKDIR /adapter
|
||||
LABEL com.nodedc.navigation-adapter="clearance-preference-v2"
|
||||
@@ -0,0 +1,6 @@
|
||||
FROM ndc-ai-polygon-cmu:support-v1
|
||||
COPY missioncore_clearance.hpp /opt/cmu/src/local_planner/src/missioncore_clearance.hpp
|
||||
WORKDIR /opt/cmu
|
||||
RUN source /opt/ros/humble/setup.bash && MAKEFLAGS=-j2 colcon build --base-paths src --packages-select local_planner --parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
|
||||
WORKDIR /adapter
|
||||
LABEL com.nodedc.navigation-adapter="clearance-free-space-utility-v3"
|
||||
@@ -0,0 +1,8 @@
|
||||
FROM ndc-ai-polygon-cmu:snapshot-v1
|
||||
COPY patch_continuous.py /opt/cmu/patch_continuous.py
|
||||
WORKDIR /opt/cmu
|
||||
RUN python3 patch_continuous.py && source /opt/ros/humble/setup.bash \
|
||||
&& MAKEFLAGS=-j2 colcon build --base-paths src --packages-select local_planner \
|
||||
--parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
|
||||
WORKDIR /adapter
|
||||
LABEL com.nodedc.navigation-adapter="independent-odometry-world-path-v1"
|
||||
@@ -0,0 +1,8 @@
|
||||
FROM ndc-ai-polygon-cmu:pursuit-v1
|
||||
COPY patch_dense_footprint.py /opt/cmu/patch_dense_footprint.py
|
||||
WORKDIR /opt/cmu
|
||||
RUN python3 patch_dense_footprint.py && source /opt/ros/humble/setup.bash \
|
||||
&& MAKEFLAGS=-j2 colcon build --base-paths src --packages-select local_planner \
|
||||
--parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
|
||||
WORKDIR /adapter
|
||||
LABEL com.nodedc.navigation-adapter="dense-primitive-footprint-v1"
|
||||
@@ -0,0 +1,9 @@
|
||||
FROM ndc-ai-polygon-cmu:connectivity-v2
|
||||
COPY missioncore_footprint.hpp /opt/cmu/src/local_planner/src/missioncore_footprint.hpp
|
||||
COPY patch_direction.py /opt/cmu/patch_direction.py
|
||||
WORKDIR /opt/cmu
|
||||
RUN python3 patch_direction.py && source /opt/ros/humble/setup.bash \
|
||||
&& MAKEFLAGS=-j2 colcon build --base-paths src --packages-select local_planner \
|
||||
--parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
|
||||
WORKDIR /adapter
|
||||
LABEL com.nodedc.navigation-adapter="observed-direction-v1"
|
||||
@@ -0,0 +1,7 @@
|
||||
FROM ndc-ai-polygon-cmu:clearance-v2
|
||||
COPY patch_prefix_goal.py /opt/cmu/patch_prefix_goal.py
|
||||
COPY missioncore_prefix.hpp /opt/cmu/src/local_planner/src/missioncore_prefix.hpp
|
||||
WORKDIR /opt/cmu
|
||||
RUN python3 patch_prefix_goal.py && /bin/bash -lc 'source /opt/ros/humble/setup.bash && MAKEFLAGS=-j2 colcon build --base-paths src --packages-select local_planner --parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF'
|
||||
WORKDIR /adapter
|
||||
LABEL com.nodedc.navigation-adapter="prefix-goal-v1"
|
||||
@@ -0,0 +1,9 @@
|
||||
FROM ndc-ai-polygon-cmu:continuous-v1
|
||||
COPY patch_pursuit.py /opt/cmu/patch_pursuit.py
|
||||
COPY missioncore_pursuit.hpp /opt/cmu/src/local_planner/src/missioncore_pursuit.hpp
|
||||
WORKDIR /opt/cmu
|
||||
RUN python3 patch_pursuit.py && source /opt/ros/humble/setup.bash \
|
||||
&& MAKEFLAGS=-j2 colcon build --base-paths src --packages-select local_planner \
|
||||
--parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
|
||||
WORKDIR /adapter
|
||||
LABEL com.nodedc.navigation-adapter="speed-coupled-pure-pursuit-v1"
|
||||
@@ -0,0 +1,8 @@
|
||||
FROM ndc-ai-polygon-cmu:direction-v1
|
||||
COPY patch_snapshot.py /opt/cmu/patch_snapshot.py
|
||||
WORKDIR /opt/cmu
|
||||
RUN python3 patch_snapshot.py && source /opt/ros/humble/setup.bash \
|
||||
&& MAKEFLAGS=-j2 colcon build --base-paths src --packages-select terrain_analysis \
|
||||
--parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
|
||||
WORKDIR /adapter
|
||||
LABEL com.nodedc.navigation-adapter="causal-map-snapshot-v1"
|
||||
@@ -0,0 +1,8 @@
|
||||
FROM ndc-ai-polygon-cmu:clearance-v3
|
||||
COPY support_native.cpp /opt/missioncore/support_native.cpp
|
||||
RUN g++ -std=c++17 -O3 -shared -fPIC /opt/missioncore/support_native.cpp -o /opt/missioncore/libsupport_surface.so
|
||||
LABEL com.nodedc.product="mission-core" \
|
||||
com.nodedc.stack="ai-polygon" \
|
||||
com.nodedc.role="navigation" \
|
||||
com.nodedc.managed-by="mission-core-artifact" \
|
||||
com.nodedc.navigation-support="connected-observed-patches-v2"
|
||||
@@ -0,0 +1,18 @@
|
||||
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$base = 'sha256:12835df9ceb377257a7e99ccbbb37636eb67d989e9bf24df8cb530341acf0c3c'
|
||||
$docker = 'C:\Program Files\Docker\Docker\resources\bin\docker.exe'
|
||||
$actual = & $docker image inspect 'ndc-ai-polygon-cmu:dense-footprint-v1' --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Pinned dense-footprint-v1 image required' }
|
||||
$endpoint = & $docker context inspect --format '{{.Endpoints.docker.Host}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
|
||||
$config = Join-Path $Root 'state\clearance-public-build'
|
||||
New-Item -ItemType Directory -Force $config | Out-Null
|
||||
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
|
||||
$env:DOCKER_CONFIG = $config
|
||||
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
|
||||
& $docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:clearance-v2 -f (Join-Path $PSScriptRoot 'Dockerfile.clearance') $PSScriptRoot
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Clearance preference build failed' }
|
||||
$image = & $docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:clearance-v2 --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
|
||||
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'patch_clearance_preference.py') -Algorithm SHA256).Hash.ToLower(); built_at=[DateTime]::UtcNow.ToString('o'); rollback_image=$base} | ConvertTo-Json
|
||||
@@ -0,0 +1,18 @@
|
||||
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$base = 'sha256:422fdf745e4ba6d5c722422c47a48483a85fe2f952f3a506411f832bded7bba2'
|
||||
$docker = 'C:\Program Files\Docker\Docker\resources\bin\docker.exe'
|
||||
$actual = & $docker image inspect 'ndc-ai-polygon-cmu:support-v1' --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Pinned support-v1 image required' }
|
||||
$endpoint = & $docker context inspect --format '{{.Endpoints.docker.Host}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
|
||||
$config = Join-Path $Root 'state\clearance-refinement-public-build'
|
||||
New-Item -ItemType Directory -Force $config | Out-Null
|
||||
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
|
||||
$env:DOCKER_CONFIG = $config
|
||||
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
|
||||
& $docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:clearance-v3 -f (Join-Path $PSScriptRoot 'Dockerfile.clearance-refinement') $PSScriptRoot
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Support kernel build failed' }
|
||||
$image = & $docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:clearance-v3 --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
|
||||
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'missioncore_clearance.hpp') -Algorithm SHA256).Hash.ToLower(); built_at=[DateTime]::UtcNow.ToString('o'); rollback_image=$base} | ConvertTo-Json
|
||||
@@ -10,8 +10,8 @@ New-Item -ItemType Directory -Force $config | Out-Null
|
||||
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
|
||||
$env:DOCKER_CONFIG = $config
|
||||
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
|
||||
docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:connectivity-v1 -f (Join-Path $PSScriptRoot 'Dockerfile.connectivity') $PSScriptRoot
|
||||
docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:connectivity-v2 -f (Join-Path $PSScriptRoot 'Dockerfile.connectivity') $PSScriptRoot
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Terrain connectivity build failed' }
|
||||
$image = docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:connectivity-v1 --format '{{.Id}}'
|
||||
$image = docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:connectivity-v2 --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
|
||||
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'terrain_connectivity.cpp') -Algorithm SHA256).Hash.ToLower(); installed_at=[DateTime]::UtcNow.ToString('o')} | ConvertTo-Json
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$base = 'sha256:6063ad1e3e4634b3f4f71e445289faf85ba25999b346f70c10b2e2840392271c'
|
||||
$docker = 'C:\Program Files\Docker\Docker\resources\bin\docker.exe'
|
||||
$actual = & $docker image inspect 'ndc-ai-polygon-cmu:snapshot-v1' --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Pinned snapshot-v1 image required' }
|
||||
$endpoint = & $docker context inspect --format '{{.Endpoints.docker.Host}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
|
||||
$config = Join-Path $Root 'state\continuous-public-build'
|
||||
New-Item -ItemType Directory -Force $config | Out-Null
|
||||
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
|
||||
$env:DOCKER_CONFIG = $config
|
||||
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
|
||||
& $docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:continuous-v1 -f (Join-Path $PSScriptRoot 'Dockerfile.continuous') $PSScriptRoot
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Continuous follower build failed' }
|
||||
$image = & $docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:continuous-v1 --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
|
||||
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'patch_continuous.py') -Algorithm SHA256).Hash.ToLower(); built_at=[DateTime]::UtcNow.ToString('o'); rollback_image=$base} | ConvertTo-Json
|
||||
@@ -0,0 +1,18 @@
|
||||
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$base = 'sha256:f84cbbb110120fbb4a40d18a568b27320d9b2b8bcf930b34a578e46da13cb96b'
|
||||
$docker = 'C:\Program Files\Docker\Docker\resources\bin\docker.exe'
|
||||
$actual = & $docker image inspect 'ndc-ai-polygon-cmu:pursuit-v1' --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Pinned pursuit-v1 image required' }
|
||||
$endpoint = & $docker context inspect --format '{{.Endpoints.docker.Host}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
|
||||
$config = Join-Path $Root 'state\dense-footprint-public-build'
|
||||
New-Item -ItemType Directory -Force $config | Out-Null
|
||||
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
|
||||
$env:DOCKER_CONFIG = $config
|
||||
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
|
||||
& $docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:dense-footprint-v1 -f (Join-Path $PSScriptRoot 'Dockerfile.dense-footprint') $PSScriptRoot
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Dense footprint selector build failed' }
|
||||
$image = & $docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:dense-footprint-v1 --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
|
||||
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'patch_dense_footprint.py') -Algorithm SHA256).Hash.ToLower(); built_at=[DateTime]::UtcNow.ToString('o'); rollback_image=$base} | ConvertTo-Json
|
||||
@@ -0,0 +1,17 @@
|
||||
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$base = 'sha256:a4ba369f9d647c8d69c488d3066a64362277734cbe0533aa3ce7790c6cd63609'
|
||||
$actual = docker image inspect 'ndc-ai-polygon-cmu:connectivity-v2' --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Prepare the pinned connectivity-v2 CMU image first' }
|
||||
$endpoint = docker context inspect --format '{{.Endpoints.docker.Host}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
|
||||
$config = Join-Path $Root 'state\direction-public-build'
|
||||
New-Item -ItemType Directory -Force $config | Out-Null
|
||||
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
|
||||
$env:DOCKER_CONFIG = $config
|
||||
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
|
||||
docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:direction-v1 -f (Join-Path $PSScriptRoot 'Dockerfile.direction') $PSScriptRoot
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Direction policy build failed' }
|
||||
$image = docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:direction-v1 --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
|
||||
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'patch_direction.py') -Algorithm SHA256).Hash.ToLower(); installed_at=[DateTime]::UtcNow.ToString('o')} | ConvertTo-Json
|
||||
@@ -0,0 +1,18 @@
|
||||
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$base = 'sha256:c2811450584ebbc61a6b15aa9d8c0663d6e1294fc2355e61ea3de722a5d50b50'
|
||||
$docker = 'C:\Program Files\Docker\Docker\resources\bin\docker.exe'
|
||||
$actual = & $docker image inspect 'ndc-ai-polygon-cmu:clearance-v2' --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Pinned clearance-v2 image required' }
|
||||
$endpoint = & $docker context inspect --format '{{.Endpoints.docker.Host}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
|
||||
$config = Join-Path $Root 'state\prefix-goal-public-build'
|
||||
New-Item -ItemType Directory -Force $config | Out-Null
|
||||
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
|
||||
$env:DOCKER_CONFIG = $config
|
||||
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
|
||||
& $docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:prefix-goal-v1 -f (Join-Path $PSScriptRoot 'Dockerfile.prefix-goal') $PSScriptRoot
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Prefix goal build failed' }
|
||||
$image = & $docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:prefix-goal-v1 --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
|
||||
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'patch_prefix_goal.py') -Algorithm SHA256).Hash.ToLower(); built_at=[DateTime]::UtcNow.ToString('o'); rollback_image=$base} | ConvertTo-Json
|
||||
@@ -0,0 +1,18 @@
|
||||
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$base = 'sha256:4d680cbec2a78864bceccade5e58b2996a7aa3c51dbaab9c391fdc70abd1c67c'
|
||||
$docker = 'C:\Program Files\Docker\Docker\resources\bin\docker.exe'
|
||||
$actual = & $docker image inspect 'ndc-ai-polygon-cmu:continuous-v1' --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Pinned continuous-v1 image required' }
|
||||
$endpoint = & $docker context inspect --format '{{.Endpoints.docker.Host}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
|
||||
$config = Join-Path $Root 'state\pursuit-public-build'
|
||||
New-Item -ItemType Directory -Force $config | Out-Null
|
||||
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
|
||||
$env:DOCKER_CONFIG = $config
|
||||
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
|
||||
& $docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:pursuit-v1 -f (Join-Path $PSScriptRoot 'Dockerfile.pursuit') $PSScriptRoot
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Pursuit follower build failed' }
|
||||
$image = & $docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:pursuit-v1 --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
|
||||
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'patch_pursuit.py') -Algorithm SHA256).Hash.ToLower(); header_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'missioncore_pursuit.hpp') -Algorithm SHA256).Hash.ToLower(); built_at=[DateTime]::UtcNow.ToString('o'); rollback_image=$base} | ConvertTo-Json
|
||||
@@ -0,0 +1,19 @@
|
||||
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$base = 'sha256:aa077bc9177c6b6a8d1bae46c3795e8e38bdd919d324d354d73be7ca5733eaf8'
|
||||
$actual = docker image inspect 'ndc-ai-polygon-cmu:direction-v1' --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Pinned direction-v1 CMU image required' }
|
||||
$existing = docker image inspect 'ndc-ai-polygon-cmu:snapshot-v1' --format '{{.Id}}' 2>$null
|
||||
if ($LASTEXITCODE -eq 0) { throw 'Snapshot image exists; inspect its evidence before rebuilding' }
|
||||
$endpoint = docker context inspect --format '{{.Endpoints.docker.Host}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
|
||||
$config = Join-Path $Root 'state\snapshot-public-build'
|
||||
New-Item -ItemType Directory -Force $config | Out-Null
|
||||
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
|
||||
$env:DOCKER_CONFIG = $config
|
||||
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
|
||||
docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:snapshot-v1 -f (Join-Path $PSScriptRoot 'Dockerfile.snapshot') $PSScriptRoot
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Snapshot build failed' }
|
||||
$image = docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:snapshot-v1 --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
|
||||
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'patch_snapshot.py') -Algorithm SHA256).Hash.ToLower(); built_at=[DateTime]::UtcNow.ToString('o'); rollback_image=$base} | ConvertTo-Json
|
||||
@@ -0,0 +1,18 @@
|
||||
param([string]$Root = 'D:\NDC_MISSIONCORE\runtime\simulation')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$base = 'sha256:f3f10ee2a594f95d4145635be7feb93b45b1b321c87ae326569db334d094cfc3'
|
||||
$docker = 'C:\Program Files\Docker\Docker\resources\bin\docker.exe'
|
||||
$actual = & $docker image inspect 'ndc-ai-polygon-cmu:prefix-goal-v1' --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0 -or $actual.Trim() -ne $base) { throw 'Pinned prefix-goal-v1 image required' }
|
||||
$endpoint = & $docker context inspect --format '{{.Endpoints.docker.Host}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Docker endpoint unavailable' }
|
||||
$config = Join-Path $Root 'state\support-public-build'
|
||||
New-Item -ItemType Directory -Force $config | Out-Null
|
||||
[IO.File]::WriteAllText((Join-Path $config 'config.json'), '{"auths":{"https://index.docker.io/v1/":{}}}')
|
||||
$env:DOCKER_CONFIG = $config
|
||||
$env:BUILDX_CONFIG = Join-Path $config 'buildx'
|
||||
& $docker --config $config --host $endpoint.Trim() build --progress plain -t ndc-ai-polygon-cmu:support-v1 -f (Join-Path $PSScriptRoot 'Dockerfile.support') $PSScriptRoot
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Support kernel build failed' }
|
||||
$image = & $docker --config $config --host $endpoint.Trim() image inspect ndc-ai-polygon-cmu:support-v1 --format '{{.Id}}'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Built image unavailable' }
|
||||
@{base_image=$base; image=$image.Trim(); source_sha256=(Get-FileHash (Join-Path $PSScriptRoot 'support_native.cpp') -Algorithm SHA256).Hash.ToLower(); built_at=[DateTime]::UtcNow.ToString('o'); rollback_image=$base} | ConvertTo-Json
|
||||
@@ -0,0 +1,255 @@
|
||||
"""One observed stop-and-orient phase per task goal or declared route segment.
|
||||
|
||||
A direction grants no translation, ground or arrival authority. Every pivot
|
||||
must pass the existing swept-obstacle and support guards on the same sensor
|
||||
transaction. Completed orientation never overrides a local obstacle detour.
|
||||
"""
|
||||
|
||||
import math
|
||||
import re
|
||||
|
||||
|
||||
def separate_counter_rotation(speed, yaw_rate, track_centres_y, *, stationary):
|
||||
"""Autonomy stops before a turn that would reverse one moving track.
|
||||
|
||||
A normal forward arc remains continuous. A pivot is only a proposal: the
|
||||
caller must apply the complete sweep and live observation checks anew.
|
||||
"""
|
||||
side_speeds = [speed - yaw_rate * y for y in track_centres_y]
|
||||
if speed > 0 and min(side_speeds) < 0 < max(side_speeds):
|
||||
return (
|
||||
0.0,
|
||||
yaw_rate if stationary else 0.0,
|
||||
{
|
||||
"phase": "pivoting" if stationary else "braking",
|
||||
"requested_command": [speed, yaw_rate],
|
||||
"authority": "proposal-requires-swept-obstacle-and-support-admission",
|
||||
},
|
||||
)
|
||||
return speed, yaw_rate, None
|
||||
|
||||
|
||||
def path_alignment_command(path, *, lookahead_m, maximum_yaw_rps):
|
||||
"""Propose a stationary turn toward the SAME selected local path.
|
||||
|
||||
A translation sweep may be blocked beside a front corner while a stationary
|
||||
pivot is clear. This grants no motion: callers require a stopped body and
|
||||
independently admit the full pivot with current obstacle and support data.
|
||||
Do not rotate for a straight blocked path, invent a detour, or reverse.
|
||||
"""
|
||||
if len(path) < 2:
|
||||
return None
|
||||
point = next((p for p in path if math.hypot(*p[:2]) >= lookahead_m), path[-1])
|
||||
if not all(math.isfinite(x) for x in point[:2]) or point[0] <= 0:
|
||||
return None
|
||||
heading = math.atan2(point[1], point[0])
|
||||
if abs(heading) <= 0.02:
|
||||
return None
|
||||
return 0.0, max(-maximum_yaw_rps, min(maximum_yaw_rps, 2 * heading))
|
||||
|
||||
|
||||
def admit_path_alignment(path, monitor, policy, terrain, pose, contact_height_m,
|
||||
current_points, *, stationary, reverse, orienting, lookahead_m):
|
||||
"""A blocked translation can turn first, with its own complete admission.
|
||||
|
||||
Ground rejection and body collision both require a different swept region;
|
||||
neither may authorize the original arc. Reuse the selected path heading,
|
||||
require a stopped body, and recheck obstacle and support independently.
|
||||
"""
|
||||
if not stationary or reverse or orienting:
|
||||
return None
|
||||
pivot = path_alignment_command(path, lookahead_m=lookahead_m,
|
||||
maximum_yaw_rps=policy.partial_yaw_rps)
|
||||
if pivot is None:
|
||||
return None
|
||||
v, w, body_scale = monitor.regulate_command(*pivot, terrain, pose)
|
||||
if body_scale == 0:
|
||||
return None
|
||||
v, w, ground_scale, ground = policy.regulate(
|
||||
v, w, terrain, pose, contact_height_m, current_points=current_points)
|
||||
if ground_scale == 0 or ground["status"] != "observed-supported":
|
||||
return None
|
||||
return v, w, body_scale, ground_scale, ground, dict(
|
||||
phase="path-alignment", proposed_command=list(pivot),
|
||||
authority="stationary-selected-path; independently admitted pivot sweep and support")
|
||||
|
||||
|
||||
def forward_path_command(path, track_centres_y, *, lookahead_m, maximum_speed,
|
||||
maximum_yaw_rps):
|
||||
"""Pure-pursuit proposal along the selected path with both tracks forward.
|
||||
|
||||
A local follower's rotate-first preference must not be the only proposal
|
||||
for a driveable bend. Pursue a lookahead on that SAME prefix, limiting
|
||||
curvature so the inner track keeps at least 10% of the outer track's speed.
|
||||
This is a steering constraint, not proof the wider arc is clear; its actual
|
||||
sweep still needs independent admission. Do not extend a short path,
|
||||
aim directly at the mission goal or grant collision/support admission.
|
||||
"""
|
||||
if not track_centres_y or maximum_speed <= 0 or maximum_yaw_rps <= 0:
|
||||
return None
|
||||
if len(path) < 2:
|
||||
return None
|
||||
candidates = []
|
||||
for point in path:
|
||||
x, y = point[:2]
|
||||
if not all(math.isfinite(n) for n in (x, y)):
|
||||
return None
|
||||
if math.hypot(x, y) >= lookahead_m:
|
||||
candidates.append(point)
|
||||
if not candidates:
|
||||
candidates = [path[-1]] # Native paths may be cropped before lookahead.
|
||||
for point in candidates:
|
||||
x, y = point[:2]
|
||||
distance = math.hypot(x, y)
|
||||
if x <= 0 or distance < min(lookahead_m, max(map(abs, track_centres_y))):
|
||||
continue
|
||||
requested_curvature = 2*y/(distance*distance)
|
||||
minimum_track_ratio = 0.1
|
||||
radius = max(map(abs, track_centres_y))
|
||||
if radius <= 0:
|
||||
return None
|
||||
limit = (1-minimum_track_ratio)/(1+minimum_track_ratio)/radius
|
||||
curvature = max(-limit, min(limit, requested_curvature))
|
||||
speed = min(maximum_speed, maximum_yaw_rps/max(abs(curvature), 1e-12))
|
||||
yaw_rate = max(-maximum_yaw_rps, min(maximum_yaw_rps, speed*curvature))
|
||||
return speed, yaw_rate, {
|
||||
"phase": "forward-path", "lookahead_vehicle_xy": [x, y],
|
||||
"curvature_per_m": curvature,
|
||||
"requested_curvature_per_m": requested_curvature,
|
||||
"minimum_track_ratio": minimum_track_ratio,
|
||||
"authority": "selected-prefix-proposal; requires live sweep and support",
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
def follower_stopped_short(pose, goal, command, *, arrival_complete, stop_distance):
|
||||
"""Follower tolerance cannot stand in for measured mission arrival.
|
||||
|
||||
Even a fully supported current body can be outside the task region when
|
||||
its selected destination lies near that region's edge.
|
||||
"""
|
||||
return bool(
|
||||
not arrival_complete
|
||||
and abs(command[0]) + abs(command[1]) < 1e-5
|
||||
and math.dist(goal[:2], pose[:2]) <= stop_distance
|
||||
)
|
||||
|
||||
|
||||
def terminal_path_command(
|
||||
pose, goal, path, command, *, stop_distance, maximum_speed, command_bounds
|
||||
):
|
||||
"""Finish a fresh local path whose follower tolerance precedes body arrival.
|
||||
|
||||
This proposes a short final approach only after the caller has admitted
|
||||
the complete destination. It follows the existing CMU prefix; it never
|
||||
extends that prefix, certifies support, or changes mission acceptance.
|
||||
The caller must reassess the actual command through all live sweep gates.
|
||||
"""
|
||||
if (
|
||||
len(path) < 2
|
||||
or abs(command[0]) + abs(command[1]) > 1e-5
|
||||
or math.dist(pose[:2], goal[:2]) > 2 * stop_distance
|
||||
):
|
||||
return None
|
||||
x, y = path[-1][:2] # Same-transaction vehicle-yaw frame, not world XY.
|
||||
distance = math.hypot(x, y)
|
||||
if not 0 < distance <= 2 * stop_distance or x <= 0:
|
||||
return None
|
||||
heading = math.atan2(y, x)
|
||||
if abs(heading) > 0.3:
|
||||
return None
|
||||
yaw = max(-0.15, min(0.15, 2 * heading))
|
||||
limit = min(maximum_speed, 0.1)
|
||||
# Use the owning monitor's horizon, not a second copy of its timing limits.
|
||||
# The upper speed limit makes the bound conservative for the output.
|
||||
horizon = command_bounds(limit, yaw)["horizon_seconds"]
|
||||
speed = min(limit, distance / horizon)
|
||||
return (
|
||||
speed,
|
||||
yaw,
|
||||
{
|
||||
"phase": "terminal-path",
|
||||
"path_endpoint_vehicle_xy": [x, y],
|
||||
"prefix_length_m": distance,
|
||||
"held_translation_bound_m": speed * horizon,
|
||||
"authority": "proposal-requires-destination-and-live-sweep-admission",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def validate_orientation(value):
|
||||
if value is None:
|
||||
return None
|
||||
if (
|
||||
not isinstance(value, dict)
|
||||
or set(value) != {"key", "xy"}
|
||||
or not isinstance(value["key"], str)
|
||||
or not re.fullmatch(r"[a-zA-Z0-9_-]{1,80}", value["key"])
|
||||
or not isinstance(value["xy"], list)
|
||||
or len(value["xy"]) != 2
|
||||
or any(
|
||||
isinstance(v, bool) or not isinstance(v, (float, int)) or not math.isfinite(v)
|
||||
for v in value["xy"]
|
||||
)
|
||||
):
|
||||
raise ValueError("Invalid orientation intent")
|
||||
return value
|
||||
|
||||
|
||||
class ArrivalApproach:
|
||||
def __init__(self):
|
||||
self.turning = self.completed = False
|
||||
self.previous = self.target = None
|
||||
|
||||
def command(self, pose, target, seconds, speed, yaw_rate, *, enabled):
|
||||
target = validate_orientation(target)
|
||||
if not enabled or target is None:
|
||||
self.previous = None
|
||||
return speed, yaw_rate, {"phase": "local-path"}
|
||||
if not all(math.isfinite(v) for v in (*pose, seconds, speed, yaw_rate)):
|
||||
raise ValueError("Non-finite orientation observation")
|
||||
if self.target != target["key"]:
|
||||
self.target = target["key"]
|
||||
self.turning = self.completed = False
|
||||
self.previous = None
|
||||
if self.completed:
|
||||
return speed, yaw_rate, {"phase": "local-path", "target_key": self.target}
|
||||
if math.dist(pose[:2], target["xy"]) <= 0.4:
|
||||
self.completed = True
|
||||
return speed, yaw_rate, {"phase": "body-placement", "target_key": self.target}
|
||||
observed_speed = None
|
||||
if self.previous is not None:
|
||||
position, before = self.previous
|
||||
dt = seconds - before
|
||||
if dt < 0:
|
||||
raise ValueError("Orientation observations must not rewind")
|
||||
if 0 < dt <= 1:
|
||||
observed_speed = math.dist(pose[:2], position) / dt
|
||||
self.previous = (list(pose[:2]), seconds)
|
||||
x, y, z, w = pose[3:7]
|
||||
heading = math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
|
||||
bearing = math.atan2(target["xy"][1] - pose[1], target["xy"][0] - pose[0])
|
||||
error = math.atan2(math.sin(bearing - heading), math.cos(bearing - heading))
|
||||
self.turning = abs(error) > (0.1 if self.turning else 0.3)
|
||||
phase = "local-path"
|
||||
if self.turning:
|
||||
speed = 0.0
|
||||
if observed_speed is None or observed_speed > 0.025:
|
||||
yaw_rate, phase = 0.0, "braking"
|
||||
else:
|
||||
yaw_rate = max(-math.radians(20), min(math.radians(20), 2 * error))
|
||||
phase = "aligning"
|
||||
else:
|
||||
self.completed = True
|
||||
return (
|
||||
speed,
|
||||
yaw_rate,
|
||||
{
|
||||
"phase": phase,
|
||||
"target_key": self.target,
|
||||
"heading_error_radians": error,
|
||||
"observed_translation_mps": observed_speed,
|
||||
"proposed_command": [speed, yaw_rate],
|
||||
"authority": "proposal-requires-swept-obstacle-and-support-admission",
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Bounded spatial refinement of a declared arrival region.
|
||||
|
||||
Only proposal coordinates and a cursor survive between observations. Each body
|
||||
assessment still uses the current terrain, permission, attitude and timestamp.
|
||||
"""
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
class ArrivalPoseSearch:
|
||||
batch_size = 32
|
||||
|
||||
def __init__(self, *, stopping_margin_m=0.0):
|
||||
if not math.isfinite(stopping_margin_m) or not 0 <= stopping_margin_m < .39:
|
||||
raise ValueError("Invalid arrival stopping margin")
|
||||
radius = .39 - stopping_margin_m
|
||||
axis = np.linspace(-radius, radius, math.ceil(2 * radius / .025) + 1)
|
||||
offsets = [(float(x), float(y)) for x in axis for y in axis
|
||||
if math.hypot(x, y) <= radius]
|
||||
offsets += [(sample_radius * math.cos(angle), sample_radius * math.sin(angle))
|
||||
for sample_radius in (.1, .2, .3, radius) if sample_radius <= radius
|
||||
for angle in (0, math.pi/4, -math.pi/4, math.pi/2, -math.pi/2, math.pi)]
|
||||
self.offsets = list(dict.fromkeys(offsets))
|
||||
self.ordered = self.offsets
|
||||
self.target = self.pose = None
|
||||
self.cursor = 0
|
||||
|
||||
def batch(self, pose, target, minimum_translation_m):
|
||||
key = (*map(float, target), float(minimum_translation_m))
|
||||
if (self.target != key or self.pose is None
|
||||
or np.linalg.norm(np.asarray(pose[:3]) - self.pose[:3]) > .025
|
||||
or abs(float(np.dot(pose[3:], self.pose[3:]))) < math.cos(.025 / 2)):
|
||||
self.target, self.pose, self.cursor = key, np.asarray(pose).copy(), 0
|
||||
qx, qy, qz, qw = pose[3:]
|
||||
yaw = math.atan2(2*(qw*qz+qx*qy), 1-2*(qy*qy+qz*qz))
|
||||
axes = np.array([[math.cos(yaw), -math.sin(yaw)],
|
||||
[math.sin(yaw), math.cos(yaw)]])
|
||||
local_target = (np.asarray(target) - np.asarray(pose[:2])) @ axes
|
||||
|
||||
def rank(offset):
|
||||
delta = local_target + offset
|
||||
return abs(math.atan2(delta[1], delta[0])), float(np.linalg.norm(delta))
|
||||
|
||||
# Arrival is a region, not its centre. Prefer a supported placement
|
||||
# requiring less heading change before considering travel distance.
|
||||
# Centre-first proposals can cause a needless near-edge pivot.
|
||||
# This ordering grants no path, support or motion authority.
|
||||
self.ordered = sorted(self.offsets, key=rank)
|
||||
if self.cursor >= len(self.offsets):
|
||||
self.cursor = 0 # Revisit on new observations; no cached admission.
|
||||
result = self.ordered[self.cursor:self.cursor + self.batch_size]
|
||||
self.cursor += len(result)
|
||||
return result
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Versioned native support build; preserves the exact qualified CMU predecessor."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
from datetime import UTC, datetime
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
base = 'ndc-ai-polygon-cmu:clearance-v3'
|
||||
expected = 'sha256:67a7fc163ed27cb029c71a24d6d935562577fe32e20ddb94c4742accdd51a13c'
|
||||
actual = json.loads(subprocess.check_output(['docker', 'image', 'inspect', base], text=True))[0]['Id']
|
||||
if actual != expected:
|
||||
raise RuntimeError('Navigation build predecessor changed')
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
context = args.output / 'context'; context.mkdir()
|
||||
for src, dest in [('Dockerfile.support', 'Dockerfile'), ('support_native.cpp', 'support_native.cpp')]:
|
||||
shutil.copyfile(Path(__file__).with_name(src), context / dest)
|
||||
inputs = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(context.iterdir())}
|
||||
encoded = json.dumps(dict(base=expected, files=inputs), sort_keys=True).encode()
|
||||
digest = hashlib.sha256(encoded).hexdigest()
|
||||
tag = 'ndc-navigation-support:' + digest[:16]
|
||||
(args.output / 'build-inputs.json').write_bytes(encoded)
|
||||
with (args.output / 'build.log').open('w') as log:
|
||||
subprocess.run(['docker', 'build', '--pull=false', '-t', tag, str(context)],
|
||||
env={**os.environ, 'DOCKER_BUILDKIT': '0'}, stdout=log, stderr=subprocess.STDOUT,
|
||||
check=True, timeout=180)
|
||||
identity = json.loads(subprocess.check_output(['docker', 'image', 'inspect', tag], text=True))[0]['Id']
|
||||
receipt = dict(image=identity, tag=tag, input_sha256=digest,
|
||||
utc=datetime.now(UTC).isoformat(), predecessor=expected,
|
||||
runtime_changes='none; isolated image only')
|
||||
(args.output / 'image.json').write_text(json.dumps(receipt, indent=2))
|
||||
shutil.rmtree(context)
|
||||
print(json.dumps(receipt))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Report the gate that actually rejected a command, before unevaluated gates.
|
||||
|
||||
No motion permission is created here. In particular, missing visual intent is
|
||||
not an obstacle observation and must not seed a route exclusion.
|
||||
"""
|
||||
|
||||
|
||||
def command_failure(*, tilt, orienting, translation_allowed, path_points,
|
||||
footprint_clear, direction_clear, support_scale,
|
||||
support_reason, velocity, yaw_rate):
|
||||
if tilt >= 30:
|
||||
return "inclination"
|
||||
if not orienting and not translation_allowed:
|
||||
return "no-permitted-goal"
|
||||
if not orienting and path_points <= 1:
|
||||
return "no-path"
|
||||
if not direction_clear:
|
||||
return "direction"
|
||||
if not footprint_clear:
|
||||
return "footprint"
|
||||
if support_scale == 0:
|
||||
return support_reason
|
||||
return "controller-hold" if abs(velocity) + abs(yaw_rate) < 1e-5 else "none"
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Conservative swept cells of the selected robot's nominal ground contacts.
|
||||
|
||||
Contact strips remain separate on straight travel. During a turn we bound each
|
||||
rotated strip plus the same incomplete-motion/discrepancy bounds as the chassis.
|
||||
This is flat-ground geometry, not a pressure, bridging or stability model.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
if __package__:
|
||||
from . import support_native
|
||||
else:
|
||||
import support_native
|
||||
|
||||
|
||||
class ContactSupport:
|
||||
spacing_m = 0.05
|
||||
angle_step_rad = 0.05
|
||||
|
||||
def __init__(self, value, length, width):
|
||||
if (
|
||||
value.get("schema_version") != "missioncore.ground-contact/v1"
|
||||
or value.get("model") != "two-track-bottom-bands"
|
||||
or [b.get("side") for b in value.get("bands", [])] != ["left", "right"]
|
||||
):
|
||||
raise ValueError("Unsupported ground contact geometry")
|
||||
self.value = value
|
||||
self.bands = []
|
||||
for band in value["bands"]:
|
||||
low, high = np.asarray(band["lower_xy_m"]), np.asarray(band["upper_xy_m"])
|
||||
if (
|
||||
low.shape != (2,)
|
||||
or high.shape != (2,)
|
||||
or not np.isfinite([low, high]).all()
|
||||
or np.any(low >= high)
|
||||
or np.any(np.maximum(np.abs(low), np.abs(high)) > [length / 2, width / 2])
|
||||
):
|
||||
raise ValueError("Invalid contact band dimensions")
|
||||
self.bands.append((low.astype(float), high.astype(float)))
|
||||
if self.bands[0][0][1] <= self.bands[1][1][1]:
|
||||
raise ValueError("Track contact bands overlap")
|
||||
|
||||
def stationary_samples(self, spacing):
|
||||
"""Include every band edge/corner without demanding ground in the gap."""
|
||||
return np.array(
|
||||
[
|
||||
[x, y]
|
||||
for low, high in self.bands
|
||||
for x in np.linspace(low[0], high[0], math.ceil((high[0] - low[0]) / spacing) + 1)
|
||||
for y in np.linspace(low[1], high[1], math.ceil((high[1] - low[1]) / spacing) + 1)
|
||||
]
|
||||
)
|
||||
|
||||
def cells(self, bounds, yaw_rate):
|
||||
"""All 5 cm cells intersecting the bounded contact sweep, side masks.
|
||||
|
||||
Orientation bins are fixed from zero and rounded outwards. A smaller
|
||||
command removes bins instead of shifting them; the cell lattice is also
|
||||
fixed. This preserves nesting for same-arc command reduction.
|
||||
"""
|
||||
if support_native.LIBRARY is not None:
|
||||
return support_native.contact_cells(self.bands, bounds, yaw_rate)
|
||||
low = np.asarray(bounds["centre_lower_xy_m"]) - bounds["discrepancy_xy_m"]
|
||||
high = np.asarray(bounds["centre_upper_xy_m"]) + bounds["discrepancy_xy_m"]
|
||||
translation, radius = (low + high) / 2, (high - low) / 2
|
||||
angle = abs(yaw_rate) * bounds["horizon_seconds"]
|
||||
count = math.ceil(angle / self.angle_step_rad)
|
||||
if count > 256:
|
||||
raise ValueError("Contact sweep exceeds bounded orientation budget")
|
||||
angles = (
|
||||
np.sign(yaw_rate) * (np.arange(count) + 0.5) * self.angle_step_rad if count else [0.0]
|
||||
)
|
||||
patches = []
|
||||
# A square cell is enclosed by this radius. Extra angular radius bounds
|
||||
# every point between the sampled midpoint and either end of its bin.
|
||||
cell_radius = self.spacing_m / math.sqrt(2)
|
||||
for side, (a, b) in enumerate(self.bands):
|
||||
centre, half = (a + b) / 2, (b - a) / 2
|
||||
reach = np.linalg.norm(np.maximum(np.abs(a), np.abs(b)))
|
||||
pad = cell_radius + (reach * self.angle_step_rad / 2 if count else 0)
|
||||
for theta in angles:
|
||||
c, s = math.cos(theta), math.sin(theta)
|
||||
axes = np.array([[c, -s], [s, c]])
|
||||
origin = translation + axes @ centre
|
||||
normals = np.vstack((np.eye(2), axes.T))
|
||||
extent = np.abs(normals @ axes) @ half + np.abs(normals) @ radius + pad
|
||||
patches.append((side, origin, normals, extent))
|
||||
lower = np.min([p[1] - p[3][:2] for p in patches], axis=0)
|
||||
upper = np.max([p[1] + p[3][:2] for p in patches], axis=0)
|
||||
first = np.floor(lower / self.spacing_m).astype(int)
|
||||
last = np.ceil(upper / self.spacing_m).astype(int)
|
||||
if np.prod(last - first + 1) > 20000:
|
||||
raise ValueError("Contact sweep exceeds bounded sample budget")
|
||||
cells = (
|
||||
np.array(
|
||||
[[x, y] for x in range(first[0], last[0] + 1) for y in range(first[1], last[1] + 1)]
|
||||
)
|
||||
* self.spacing_m
|
||||
)
|
||||
sides = np.zeros((len(cells), 2), dtype=bool)
|
||||
for side, origin, normals, extent in patches:
|
||||
sides[:, side] |= np.all(np.abs((cells - origin) @ normals.T) <= extent + 1e-10, axis=1)
|
||||
keep = np.any(sides, axis=1)
|
||||
return cells[keep], sides[keep]
|
||||
@@ -0,0 +1,223 @@
|
||||
"""Fast control admission, independent of camera inference and map construction.
|
||||
|
||||
The native CMU follower supplies proposals from live odometry. Every delivered
|
||||
proposal is checked against the current observed geometry and contact policy.
|
||||
Wall-clock observation leases are never renewed by a controller poll.
|
||||
"""
|
||||
|
||||
import math
|
||||
import copy
|
||||
import threading
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
|
||||
import numpy as np
|
||||
|
||||
if __package__:
|
||||
from .arrival_approach import separate_counter_rotation
|
||||
from .detection_obstacles import DetectionObstacles
|
||||
else:
|
||||
from arrival_approach import separate_counter_rotation
|
||||
from detection_obstacles import DetectionObstacles
|
||||
|
||||
|
||||
class ContinuousControl:
|
||||
range_deadline = 0.8
|
||||
pose_deadline = 0.5
|
||||
semantic_deadline = 2.0
|
||||
|
||||
def __init__(self, monitor, support_policy, publish_pose, publish_path, native_command,
|
||||
clock=time.monotonic, body_top_m=math.inf, native_only=False):
|
||||
self.monitor, self.support = monitor, support_policy
|
||||
self.detections = DetectionObstacles(monitor)
|
||||
self.publish_pose, self.publish_path, self.native_command = (
|
||||
publish_pose, publish_path, native_command)
|
||||
self.clock, self.lock = clock, threading.Lock()
|
||||
self.geometry = None
|
||||
self.plans = OrderedDict()
|
||||
self.path_id = None
|
||||
self.body_top_m = body_top_m
|
||||
self.range_sequence = None
|
||||
self.native_only = native_only
|
||||
|
||||
def observe(self, value):
|
||||
age = float(value["geometry_age_seconds"])
|
||||
if not math.isfinite(age) or age < 0:
|
||||
raise ValueError("Invalid range capture age")
|
||||
points = np.asarray(value["points"], dtype=float).reshape(-1, 3).copy()
|
||||
if not np.isfinite(points).all():
|
||||
raise ValueError("Non-finite live range")
|
||||
sequence = value.get("range_sequence")
|
||||
if sequence is not None:
|
||||
if (not isinstance(sequence, list) or len(sequence) != 2
|
||||
or any(type(n) is not int or n < 0 for n in sequence)):
|
||||
raise ValueError("Invalid range sequence")
|
||||
sequence = tuple(sequence)
|
||||
with self.lock:
|
||||
# Once the direct sensor channel is active, planner transactions
|
||||
# cannot replace its newer packet or renew its capture lease.
|
||||
if self.range_sequence is not None and (sequence is None or sequence <= self.range_sequence):
|
||||
return
|
||||
self.geometry = (self.clock() - age, points)
|
||||
self.range_sequence = sequence
|
||||
|
||||
def accept(self, value, result, terrain, *, detections=None):
|
||||
candidates = self.detections.observed(value)
|
||||
if detections is None:
|
||||
detections = candidates
|
||||
else:
|
||||
detections = np.asarray(detections, dtype=float).reshape(-1, 3).copy()
|
||||
if not set(map(tuple, detections)) <= set(map(tuple, candidates)):
|
||||
raise ValueError("Refined detection is not an original associated range return")
|
||||
record = dict(value=value, result=result, detections=detections,
|
||||
terrain=np.asarray(terrain, dtype=float).reshape(-1, 4).copy(),
|
||||
received_at=self.clock())
|
||||
with self.lock:
|
||||
self.plans[value["observation_id"]] = record
|
||||
while len(self.plans) > 4:
|
||||
self.plans.popitem(last=False)
|
||||
|
||||
def snapshot(self):
|
||||
"""One immutable planning transaction for offline diagnosis, no authority."""
|
||||
with self.lock:
|
||||
if not self.plans:
|
||||
return None
|
||||
identity, plan = next(reversed(self.plans.items()))
|
||||
return dict(observation_id=identity, request=copy.deepcopy(plan["value"]),
|
||||
result=copy.deepcopy(plan["result"]), terrain=plan["terrain"].tolist())
|
||||
|
||||
def tick(self, value):
|
||||
started = self.clock()
|
||||
pose = np.asarray(value["pose"], dtype=float)
|
||||
age = float(value["pose_age_seconds"])
|
||||
perception_age = float(value["perception_age_seconds"])
|
||||
if (pose.shape != (7,) or not np.isfinite(pose).all()
|
||||
or abs(np.linalg.norm(pose[3:]) - 1) > 0.01
|
||||
or not all(math.isfinite(x) and x >= 0 for x in (age, perception_age))
|
||||
or type(value["enabled"]) is not bool):
|
||||
raise ValueError("Invalid continuous state")
|
||||
if "range_observation" in value:
|
||||
self.observe(value["range_observation"])
|
||||
# Always feed current state, including while stopped, without waiting
|
||||
# for terrain_analysis or a model. This publisher is follower-only.
|
||||
self.publish_pose(pose)
|
||||
with self.lock:
|
||||
geometry = self.geometry
|
||||
plan = self.plans.get(value.get("observation_id"))
|
||||
|
||||
def output(v=0.0, w=0.0, reason="waiting", **evidence):
|
||||
return dict(speed_mps=float(v), yaw_rate_rps=float(w), reason=reason,
|
||||
processing_ms=(self.clock() - started) * 1000, **evidence)
|
||||
|
||||
if not value["enabled"]:
|
||||
return output(reason="paused")
|
||||
if age > self.pose_deadline:
|
||||
return output(reason="stale-pose")
|
||||
if perception_age > self.semantic_deadline:
|
||||
return output(reason="stale-perception")
|
||||
if geometry is None or started - geometry[0] > self.range_deadline:
|
||||
return output(reason="stale-range")
|
||||
if len(geometry[1]) < 50:
|
||||
return output(reason="insufficient-range")
|
||||
if plan is None or plan["result"].get("status") != "path":
|
||||
return output(reason="waiting-for-plan")
|
||||
if started - plan["received_at"] > self.range_deadline:
|
||||
return output(reason="stale-plan")
|
||||
request, result = plan["value"], plan["result"]
|
||||
if (started - plan["received_at"] + request.get("detection_age_seconds", 0)
|
||||
> self.detections.deadline_seconds):
|
||||
return output(reason="stale-detection")
|
||||
if self.path_id != value["observation_id"]:
|
||||
self.publish_path(result["path"], request["pose"])
|
||||
self.path_id = value["observation_id"]
|
||||
native = self.native_command()
|
||||
if native is None or started - native[0] > 0.25:
|
||||
return output(reason="waiting-for-controller")
|
||||
limit = float(request["max_speed_mps"])
|
||||
reverse = request.get("allow_reverse", False)
|
||||
stationary = abs(float(value.get("speed_mps", 0))) < 0.02
|
||||
qx, qy, qz, qw = pose[3:]
|
||||
if 1 - 2 * (qx*qx + qy*qy) <= math.cos(math.radians(30)):
|
||||
return output(reason="inclination")
|
||||
# Newly arrived raw returns can veto a map that has not finished its
|
||||
# next terrain pass yet. Ground support uses independent first-hit data.
|
||||
points = geometry[1]
|
||||
up = np.array([2*(qx*qz + qw*qy), 2*(qy*qz - qw*qx), 1-2*(qx*qx+qy*qy)])
|
||||
height = (points - pose[:3]) @ up + request["body_contact_height_m"]
|
||||
raised = (height > self.monitor.max_step + 1e-4) & (height <= self.body_top_m)
|
||||
hazards = np.column_stack((points[raised], np.ones(int(raised.sum()))))
|
||||
terrain = np.concatenate((plan["terrain"], hazards))
|
||||
def admit(command):
|
||||
speed, angular = map(float, command)
|
||||
if not all(math.isfinite(x) for x in (speed, angular)):
|
||||
return output(reason="invalid-proposal")
|
||||
speed = max(-limit, min(limit, speed))
|
||||
angular = max(-0.8, min(0.8, angular))
|
||||
if not self.native_only and not reverse and self.monitor.contacts is not None:
|
||||
speed, angular, _ = separate_counter_rotation(speed, angular,
|
||||
[(low[1]+high[1])/2 for low, high in self.monitor.contacts.bands],
|
||||
stationary=stationary)
|
||||
if abs(speed) < 1e-8 and abs(angular) > 1e-8:
|
||||
angular = max(-self.support.partial_yaw_rps,
|
||||
min(self.support.partial_yaw_rps, angular)) if stationary else 0.0
|
||||
if (reverse and (speed > 0 or abs(angular) > 0.15)) or (not reverse and speed < 0):
|
||||
return output(reason="direction")
|
||||
speed, angular, obstacle_scale = self.monitor.regulate_command(speed, angular, terrain, pose)
|
||||
if obstacle_scale == 0:
|
||||
return output(reason="obstacle")
|
||||
speed, angular, support_scale, support = self.support.regulate(
|
||||
speed, angular, terrain, pose, request["body_contact_height_m"],
|
||||
current_points=points,
|
||||
)
|
||||
evidence = dict(support_policy=support["policy"]["reason"],
|
||||
support_reasons=support["support_reasons"],
|
||||
fresh_context=support["policy"]["fresh_context"])
|
||||
if support_scale == 0:
|
||||
return output(reason=support["policy"]["reason"], **evidence)
|
||||
speed, angular, detection_scale = self.detections.regulate(
|
||||
speed, angular, plan["detections"], pose)
|
||||
evidence["detection_command_scale"] = detection_scale
|
||||
if detection_scale == 0:
|
||||
return output(reason="detected-object-sweep", **evidence)
|
||||
return output(speed, angular, "none", **evidence)
|
||||
|
||||
if self.native_only:
|
||||
# Nav2 owns the proposal. No CMU fallback, arrival override or
|
||||
# alternative local pursuit may become a competing controller.
|
||||
response = admit(native[1:])
|
||||
response.update(command_source="nav2", observation_id=value["observation_id"],
|
||||
native_command=list(native[1:]),
|
||||
processing_ms=(self.clock()-started)*1000)
|
||||
return response
|
||||
|
||||
planned = [result["speed_mps"], result["yaw_rate_rps"]]
|
||||
approach = result.get("diagnostic", {}).get("arrival_approach", {})
|
||||
phase = approach.get("phase")
|
||||
terminal = result.get("diagnostic", {}).get("terminal_approach")
|
||||
local_turn = result.get("diagnostic", {}).get("local_turn") or {}
|
||||
if phase == "path-alignment" and not stationary:
|
||||
return output(reason="path-alignment-braking")
|
||||
# A short, destination-admitted terminal prefix may lie inside the
|
||||
# native follower's stop tolerance. Its valid zero command must not
|
||||
# suppress the terminal proposal. It retains the plan's bounded lease
|
||||
# and traverses exactly the same current-pose/range guards below.
|
||||
proposal = planned if (terminal or local_turn.get("phase") == "forward-path"
|
||||
or phase in {"braking", "aligning", "path-alignment"}) else native[1:]
|
||||
response = admit(proposal)
|
||||
source = ("local-path" if local_turn.get("phase") == "forward-path" else "arrival") \
|
||||
if proposal is planned else "follower"
|
||||
if response["reason"] != "none" and tuple(proposal) != tuple(planned):
|
||||
# A fresh path proposal and the live follower can disagree on
|
||||
# curvature. Test the planner's original command at the CURRENT
|
||||
# pose and ranges before declaring deadlock. This is no admission
|
||||
# shortcut: both candidates traverse exactly the same guards.
|
||||
fallback = admit(planned)
|
||||
if fallback["reason"] == "none":
|
||||
fallback["rejected_follower"] = response
|
||||
response, source = fallback, "guarded-plan"
|
||||
response.update(range_age_ms=(started-geometry[0])*1000,
|
||||
pose_age_ms=age*1000, perception_age_ms=perception_age*1000,
|
||||
native_command=list(native[1:]), command_source=source,
|
||||
observation_id=value["observation_id"],
|
||||
processing_ms=(self.clock()-started)*1000)
|
||||
return response
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Observed detector hazards enter search and command admission separately.
|
||||
|
||||
Inspired by the obstacle-layer / collision-monitor separation in Nav2. Boxes
|
||||
alone never create metric obstacles. Source indices bind each hazard to this
|
||||
range transaction. Search costs mark existing measured voxels; the independent
|
||||
swept-body guard tests the exact associated returns at the current pose.
|
||||
This is a simulation candidate, not a certified human-separation controller.
|
||||
"""
|
||||
import copy
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
class DetectionObstacles:
|
||||
deadline_seconds = 2.0
|
||||
# Additional reserve for detector-associated objects. Separate from the
|
||||
# ordinary 5 cm rigid-body margin, terrain capability and road permissions.
|
||||
clearance_m = 0.35
|
||||
voxel_m = 0.12
|
||||
|
||||
def __init__(self, monitor):
|
||||
self.monitor = copy.copy(monitor)
|
||||
self.monitor.clearance_m = max(monitor.clearance_m, self.clearance_m)
|
||||
self.cost = monitor.max_step + 1.0
|
||||
|
||||
@staticmethod
|
||||
def observed(value):
|
||||
points = np.asarray(value["points"], dtype=float).reshape(-1, 3)
|
||||
indices = value.get("detection_point_indices", [])
|
||||
if (not isinstance(indices, list) or len(indices) > len(points)
|
||||
or len(indices) != len(set(indices))
|
||||
or any(type(i) is not int or not 0 <= i < len(points) for i in indices)
|
||||
or not np.isfinite(points).all()):
|
||||
raise ValueError("Invalid detector range association")
|
||||
age = float(value.get("detection_age_seconds", 0))
|
||||
if not math.isfinite(age) or age < 0:
|
||||
raise ValueError("Invalid detector capture age")
|
||||
return points[indices].copy()
|
||||
|
||||
def overlay(self, terrain, detected):
|
||||
if not len(detected):
|
||||
return terrain
|
||||
cells = set(map(tuple, np.floor(detected / self.voxel_m).astype(np.int64)))
|
||||
keys = np.floor(terrain[:, :3] / self.voxel_m).astype(np.int64)
|
||||
marked = np.fromiter((tuple(k) in cells for k in keys), bool, len(keys))
|
||||
result = terrain.copy()
|
||||
result[marked, 3] = np.maximum(result[marked, 3], self.cost)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def without_ground(detected, permitted_terrain):
|
||||
"""Remove only positively permitted PCL ground in this exact scan.
|
||||
|
||||
No voxel-neighbour inference: segmentation preserves original return
|
||||
indices; unknown and unmatched candidates keep their object reserve.
|
||||
Raw range and CMU geometric costs remain untouched.
|
||||
"""
|
||||
detected = np.asarray(detected, dtype=float).reshape(-1, 3)
|
||||
ground = np.asarray(permitted_terrain, dtype=np.float32).reshape(-1, 3)
|
||||
if not np.isfinite(detected).all() or not np.isfinite(ground).all():
|
||||
raise ValueError("Non-finite detection ground observation")
|
||||
known = set(map(tuple, ground))
|
||||
keep = np.fromiter((tuple(p) not in known for p in detected.astype(np.float32)), bool, len(detected))
|
||||
return detected[keep].copy()
|
||||
|
||||
def regulate(self, speed, angular, detected, pose):
|
||||
# These are the original XYZ returns, not filled voxels or box centres.
|
||||
terrain = np.column_stack((detected, np.full(len(detected), self.cost)))
|
||||
return self.monitor.regulate_command(speed, angular, terrain, pose)
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Metre-square swept-body check on CMU's observed terrain and chosen path.
|
||||
"""Selected robot swept-body check on CMU's observed terrain and chosen path.
|
||||
|
||||
CMU's circular path table proposes paths. This final adapter check preserves
|
||||
the actual square chassis, including the initial turn, without widening it to
|
||||
the actual rectangular chassis, including the initial turn, without widening it to
|
||||
its circumscribed circle for straight travel. No scene geometry enters here.
|
||||
"""
|
||||
|
||||
@@ -9,99 +9,558 @@ import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
MAX_STEP_M = 0.10
|
||||
if __package__:
|
||||
from .contact_support import ContactSupport
|
||||
from .support_surface import SupportSurface
|
||||
else:
|
||||
from contact_support import ContactSupport
|
||||
from support_surface import SupportSurface
|
||||
|
||||
FRAME_DEADLINE_SECONDS = 0.8
|
||||
|
||||
|
||||
def _obstacles(terrain, pose):
|
||||
terrain = np.asarray(terrain, dtype=float)
|
||||
obstacles = terrain[terrain[:, 3] > MAX_STEP_M + 1e-4, :2] - np.asarray(pose[:2])
|
||||
x, y, z, w = pose[3:]
|
||||
yaw = math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
|
||||
return obstacles @ np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]])
|
||||
|
||||
|
||||
def _clearances(obstacles):
|
||||
return np.maximum(np.abs(obstacles[:, 0]) - 0.5, np.abs(obstacles[:, 1]) - 0.5)
|
||||
|
||||
|
||||
def _clear(obstacles, position, angle):
|
||||
delta = obstacles - position
|
||||
c, s = math.cos(angle), math.sin(angle)
|
||||
along = delta[:, 0] * c + delta[:, 1] * s
|
||||
across = -delta[:, 0] * s + delta[:, 1] * c
|
||||
initial = _clearances(obstacles)
|
||||
if np.any(initial <= 0):
|
||||
return False # Never excuse an overlap of the actual metre-square body.
|
||||
clearance = np.maximum(np.abs(along) - 0.5, np.abs(across) - 0.5)
|
||||
# An observed point may already be inside the 5 cm reserve behind the body.
|
||||
# Permit only motion that never decreases that initial clearance. This
|
||||
# cannot authorize moving toward it, reversing into it or corner penetration.
|
||||
return bool(np.all(clearance + 1e-6 >= np.minimum(initial, 0.05)))
|
||||
|
||||
|
||||
def command_footprint_clear(speed, yaw_rate, terrain, pose):
|
||||
"""Collision monitor over deadman latency plus a conservative braking arc.
|
||||
|
||||
CMU replans the route continuously. A later blocked corner must not prevent
|
||||
safe progress on its prefix; this checks the command that can actually be
|
||||
applied before the source-frame deadline, plus braking and 0.5 s reserve.
|
||||
"""
|
||||
obstacles = _obstacles(terrain, pose)
|
||||
horizon = FRAME_DEADLINE_SECONDS + 0.5 + abs(speed) / 0.4 + abs(yaw_rate) / 1.6
|
||||
for t in np.arange(0, horizon + 0.025, 0.025):
|
||||
angle = yaw_rate * t
|
||||
position = (
|
||||
np.array([speed * math.sin(angle) / yaw_rate, speed * (1 - math.cos(angle)) / yaw_rate])
|
||||
if abs(yaw_rate) > 1e-6
|
||||
else np.array([speed * t, 0])
|
||||
class Footprint:
|
||||
def __init__(self, geometry, deceleration=0.4, *, clearance_m=0.05):
|
||||
self.half_length = geometry["length_m"] / 2
|
||||
self.half_width = geometry["width_m"] / 2
|
||||
# Mounted bodies affect collision clearance; tracks still define support.
|
||||
self.collision_half_length = geometry.get("collision_length_m", geometry["length_m"]) / 2
|
||||
self.collision_half_width = geometry.get("collision_width_m", geometry["width_m"]) / 2
|
||||
if (not all(math.isfinite(v) for v in
|
||||
(self.collision_half_length, self.collision_half_width))
|
||||
or self.collision_half_length < self.half_length
|
||||
or self.collision_half_width < self.half_width):
|
||||
raise ValueError("Collision projection cannot shrink the chassis")
|
||||
self.max_step = geometry["max_step_m"]
|
||||
self.max_slope = math.tan(math.radians(geometry["max_slope_degrees"]))
|
||||
self.deceleration = deceleration
|
||||
self.clearance_m = float(clearance_m)
|
||||
if not math.isfinite(self.clearance_m) or self.clearance_m < 0.05:
|
||||
raise ValueError("Invalid obstacle clearance")
|
||||
if min(self.half_length, self.half_width, self.max_step, deceleration) <= 0:
|
||||
raise ValueError("Invalid footprint geometry")
|
||||
self.contacts = (
|
||||
ContactSupport(geometry["ground_contact"], geometry["length_m"], geometry["width_m"])
|
||||
if "ground_contact" in geometry
|
||||
else None
|
||||
)
|
||||
if not _clear(obstacles, position, angle):
|
||||
|
||||
def classify_contacts(self, surface, offsets):
|
||||
if self.contacts is None:
|
||||
return surface.classify(offsets)
|
||||
width = min(high[1]-low[1] for low, high in self.contacts.bands)
|
||||
return surface.classify_contacts(offsets, width)
|
||||
|
||||
def _obstacles(self, terrain, pose):
|
||||
terrain = np.asarray(terrain, dtype=float)
|
||||
obstacles = terrain[terrain[:, 3] > self.max_step + 1e-4, :2] - np.asarray(pose[:2])
|
||||
x, y, z, w = pose[3:]
|
||||
yaw = math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
|
||||
return obstacles @ np.array(
|
||||
[[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]]
|
||||
)
|
||||
|
||||
def _clearances(self, obstacles):
|
||||
return np.maximum(
|
||||
np.abs(obstacles[:, 0]) - self.collision_half_length,
|
||||
np.abs(obstacles[:, 1]) - self.collision_half_width
|
||||
)
|
||||
|
||||
def _clear(self, obstacles, position, angle):
|
||||
delta = obstacles - position
|
||||
c, s = math.cos(angle), math.sin(angle)
|
||||
along = delta[:, 0] * c + delta[:, 1] * s
|
||||
across = -delta[:, 0] * s + delta[:, 1] * c
|
||||
initial = self._clearances(obstacles)
|
||||
if np.any(initial <= 0):
|
||||
return False # Never excuse an overlap of the actual robot body.
|
||||
clearance = np.maximum(np.abs(along) - self.collision_half_length,
|
||||
np.abs(across) - self.collision_half_width)
|
||||
# An observed point may already be inside the 5 cm reserve behind the body.
|
||||
# Permit only motion that never decreases that initial clearance. This
|
||||
# cannot authorize moving toward it, reversing into it or corner penetration.
|
||||
return bool(np.all(clearance + 1e-6 >= np.minimum(initial, self.clearance_m)))
|
||||
|
||||
def assess_pose(self, terrain, pose, contact_height_m, *, support_terrain=None):
|
||||
"""Certify a stationary body using observed support, never empty space.
|
||||
|
||||
The 10 cm lattice includes every contact edge and corner for v2, or
|
||||
every body edge and corner for legacy v1. Each point
|
||||
must lie inside a local observed ground patch (15 cm radius), with a
|
||||
bounded plane slope/residual. Nearest returns alone cannot extrapolate
|
||||
support past a ledge. This is sampled geometric support, not load or
|
||||
soil-bearing-capacity estimation, and does not authorize a path to it.
|
||||
"""
|
||||
terrain = np.asarray(terrain, dtype=float).reshape(-1, 4)
|
||||
pose = np.asarray(pose, dtype=float)
|
||||
if not np.isfinite(terrain).all() or pose.shape != (7,) or not np.isfinite(pose).all():
|
||||
raise ValueError("Invalid body assessment observation")
|
||||
qx, qy, qz, qw = pose[3:]
|
||||
yaw = math.atan2(2 * (qw * qz + qx * qy), 1 - 2 * (qy * qy + qz * qz))
|
||||
axes = np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]])
|
||||
spacing, radius = 0.1, 0.15
|
||||
grid = (
|
||||
self.contacts.stationary_samples(spacing)
|
||||
if self.contacts is not None
|
||||
else np.array(
|
||||
[
|
||||
[x, y]
|
||||
for x in np.linspace(
|
||||
-self.half_length,
|
||||
self.half_length,
|
||||
math.ceil(2 * self.half_length / spacing) + 1,
|
||||
)
|
||||
for y in np.linspace(
|
||||
-self.half_width,
|
||||
self.half_width,
|
||||
math.ceil(2 * self.half_width / spacing) + 1,
|
||||
)
|
||||
]
|
||||
)
|
||||
) @ axes.T
|
||||
support = (
|
||||
terrain
|
||||
if support_terrain is None
|
||||
else np.asarray(support_terrain, dtype=float).reshape(-1, 4)
|
||||
)
|
||||
if not np.isfinite(support).all():
|
||||
raise ValueError("Invalid support observation")
|
||||
surface = SupportSurface(
|
||||
support, pose, contact_height_m, self.max_step, self.max_slope,
|
||||
anchor_radius_m=math.hypot(self.half_length, self.half_width)
|
||||
)
|
||||
states, reasons = self.classify_contacts(surface, grid)
|
||||
supported = int(np.count_nonzero(states == "observed-supported"))
|
||||
collision_free = self._clear(self._obstacles(terrain, pose), np.zeros(2), 0)
|
||||
return dict(
|
||||
schema_version="missioncore.body-clearance/v2"
|
||||
if self.contacts is not None
|
||||
else "missioncore.body-clearance/v1",
|
||||
collision_free=collision_free,
|
||||
support_known=supported == len(grid),
|
||||
admitted=collision_free and supported == len(grid),
|
||||
support_samples=len(grid),
|
||||
supported_samples=supported,
|
||||
support_spacing_m=spacing,
|
||||
support_radius_m=radius,
|
||||
support_reasons=reasons,
|
||||
**({"ground_contact": self.contacts.value} if self.contacts is not None else {}),
|
||||
)
|
||||
|
||||
def find_arrival_pose(
|
||||
self,
|
||||
terrain,
|
||||
pose,
|
||||
target_xy,
|
||||
contact_height_m,
|
||||
*,
|
||||
support_terrain=None,
|
||||
minimum_translation_m=0.0,
|
||||
refinement=None,
|
||||
):
|
||||
"""Find an observed pose inside the existing 0.4 m task region.
|
||||
|
||||
Keep the measured heading; do not assume room for a turn. The bounded
|
||||
search proposes a destination only. CMU must plan it on a new sensor
|
||||
transaction, and the command sweep retains its independent veto.
|
||||
"""
|
||||
if not math.isfinite(minimum_translation_m) or minimum_translation_m < 0:
|
||||
raise ValueError("Invalid arrival translation minimum")
|
||||
terrain = np.asarray(terrain, dtype=float).reshape(-1, 4)
|
||||
pose = np.asarray(pose, dtype=float)
|
||||
qx, qy, qz, qw = pose[3:]
|
||||
up = np.array(
|
||||
[2 * (qx * qz + qw * qy), 2 * (qy * qz - qw * qx), 1 - 2 * (qx * qx + qy * qy)]
|
||||
)
|
||||
if up[2] <= 0:
|
||||
return None
|
||||
yaw = math.atan2(2 * (qw * qz + qx * qy), 1 - 2 * (qy * qy + qz * qz))
|
||||
# Sample centre, then forward and lateral options. The 1 cm inset
|
||||
# belongs to the proposal; the mission's admission radius stays 0.4 m.
|
||||
offsets = [(0, 0)] + [
|
||||
(radius * math.cos(yaw + angle), radius * math.sin(yaw + angle))
|
||||
for radius in (0.1, 0.2, 0.3, 0.39)
|
||||
for angle in (0, math.pi / 4, -math.pi / 4, math.pi / 2, -math.pi / 2, math.pi)
|
||||
]
|
||||
if refinement is not None:
|
||||
# The radial coarse search can miss a narrow but fully supported
|
||||
# placement. Refine at the existing 2.5 cm sweep resolution without
|
||||
# monopolizing a planning transaction. Never retain body receipts.
|
||||
axes = np.array([[math.cos(yaw), -math.sin(yaw)],
|
||||
[math.sin(yaw), math.cos(yaw)]])
|
||||
offsets = [axes @ offset for offset in refinement.batch(
|
||||
pose, target_xy, minimum_translation_m)]
|
||||
for offset in offsets:
|
||||
candidate = pose.copy()
|
||||
candidate[:2] = np.asarray(target_xy) + offset
|
||||
if np.linalg.norm(candidate[:2] - pose[:2]) <= minimum_translation_m:
|
||||
continue
|
||||
candidate[2] -= np.dot(up[:2], candidate[:2] - pose[:2]) / up[2]
|
||||
# Cheap identical collision veto before fitting contact support.
|
||||
if not self._clear(self._obstacles(terrain, candidate), np.zeros(2), 0):
|
||||
continue
|
||||
if self.assess_pose(
|
||||
terrain, candidate, contact_height_m, support_terrain=support_terrain
|
||||
)["admitted"]:
|
||||
return candidate.tolist()
|
||||
return None
|
||||
|
||||
def find_observed_approach(
|
||||
self, terrain, pose, target_xy, contact_height_m, *, support_terrain, minimum_translation_m
|
||||
):
|
||||
"""Propose a full supported body placement before an unseen destination.
|
||||
|
||||
Only measured, positively classified support may supply this bounded
|
||||
receding horizon. This is not an arrival, a path, or motion permission;
|
||||
the local planner and swept command gates remain mandatory.
|
||||
"""
|
||||
pose = np.asarray(pose, dtype=float)
|
||||
delta = np.asarray(target_xy, dtype=float) - pose[:2]
|
||||
distance = np.linalg.norm(delta)
|
||||
if distance <= 0.4 or support_terrain is None or len(support_terrain) == 0:
|
||||
return None
|
||||
if not math.isfinite(minimum_translation_m) or minimum_translation_m <= 0:
|
||||
raise ValueError("Invalid approach translation minimum")
|
||||
qx, qy, qz, qw = pose[3:]
|
||||
up = np.array(
|
||||
[2 * (qx * qz + qw * qy), 2 * (qy * qz - qw * qx), 1 - 2 * (qx * qx + qy * qy)]
|
||||
)
|
||||
if up[2] <= 0:
|
||||
return None
|
||||
limit = min(distance - 0.41, 2 * max(self.half_length, self.half_width))
|
||||
# Stop before the unchanged task region. A candidate is never accepted
|
||||
# merely because the current body is supported; assess its whole body.
|
||||
for travel in np.arange(limit, minimum_translation_m, -0.1):
|
||||
candidate = pose.copy()
|
||||
offset = delta * travel / distance
|
||||
candidate[:2] += offset
|
||||
candidate[2] -= np.dot(up[:2], offset) / up[2]
|
||||
if self.assess_pose(
|
||||
terrain, candidate, contact_height_m, support_terrain=support_terrain
|
||||
)["admitted"]:
|
||||
return candidate.tolist()
|
||||
return None
|
||||
|
||||
def command_bounds(self, speed, yaw_rate):
|
||||
"""Bound a held command, allowing incomplete translation and turning.
|
||||
|
||||
The body need not follow an ideal differential-drive arc: each response
|
||||
can range from zero to the requested rate. Bound its centre by integrating
|
||||
component extrema over that heading sector, then add the rotating body's
|
||||
rectangular projections. Straight travel retains rectangular dimensions.
|
||||
|
||||
The additional directional discrepancy is an empirical simulation margin,
|
||||
calibrated on the DCD-006 flat-ground matrix (100/130 kg, 0.1–0.3 m/s,
|
||||
friction 0.35/0.8). It is not a physical guarantee, a ground-support proof,
|
||||
or qualification of every speed/load accepted by the settings editor.
|
||||
"""
|
||||
if not math.isfinite(speed) or not math.isfinite(yaw_rate):
|
||||
raise ValueError("Non-finite motion command")
|
||||
horizon = (
|
||||
FRAME_DEADLINE_SECONDS + 0.5 + abs(speed) / self.deceleration + abs(yaw_rate) / 1.6
|
||||
)
|
||||
angle = abs(yaw_rate) * horizon
|
||||
|
||||
def extent(along, across):
|
||||
if angle >= math.atan2(across, along):
|
||||
return math.hypot(along, across)
|
||||
return along * math.cos(angle) + across * math.sin(angle)
|
||||
|
||||
cosine_min = math.cos(min(angle, math.pi))
|
||||
sine_max = math.sin(min(angle, math.pi / 2))
|
||||
sine_min = 0 if angle <= math.pi else math.sin(min(angle, 1.5 * math.pi))
|
||||
if yaw_rate < 0:
|
||||
sine_min, sine_max = -sine_max, -sine_min
|
||||
travel = speed * horizon
|
||||
x_range = sorted((travel * min(0, cosine_min), travel))
|
||||
y_range = sorted((travel * min(0, sine_min), travel * max(0, sine_max)))
|
||||
half = np.array(
|
||||
[extent(self.collision_half_length, self.collision_half_width), extent(self.collision_half_width, self.collision_half_length)]
|
||||
)
|
||||
lower = np.array([x_range[0], y_range[0]]) - half
|
||||
upper = np.array([x_range[1], y_range[1]]) + half
|
||||
discrepancy = horizon * (np.array([0.01, 0.03]) + 0.15 * abs(yaw_rate))
|
||||
return dict(
|
||||
horizon_seconds=horizon,
|
||||
centre_lower_xy_m=[x_range[0], y_range[0]],
|
||||
centre_upper_xy_m=[x_range[1], y_range[1]],
|
||||
lower_xy_m=lower.tolist(),
|
||||
upper_xy_m=upper.tolist(),
|
||||
discrepancy_xy_m=discrepancy.tolist(),
|
||||
)
|
||||
|
||||
def command_footprint_clear(self, speed, yaw_rate, terrain, pose):
|
||||
"""Veto observed obstacles in the command's bounded swept body.
|
||||
|
||||
Empty observations do not certify terrain support. The independent
|
||||
planner, unknown-space policy and stationary arrival checks retain that
|
||||
responsibility. A zero return from regulation always means stop; it is
|
||||
never a certificate that an already unsafe pose has become safe.
|
||||
"""
|
||||
bounds = self.command_bounds(speed, yaw_rate)
|
||||
terrain = np.asarray(terrain, dtype=float).reshape(-1, 4)
|
||||
pose = np.asarray(pose, dtype=float)
|
||||
if pose.shape != (7,) or not np.isfinite(pose).all() or not np.isfinite(terrain).all():
|
||||
raise ValueError("Invalid swept-body observation")
|
||||
obstacles = self._obstacles(terrain, pose)
|
||||
initial = self._clearances(obstacles)
|
||||
if np.any(initial <= 0):
|
||||
return False
|
||||
return True
|
||||
lower, upper = np.array(bounds["lower_xy_m"]), np.array(bounds["upper_xy_m"])
|
||||
error = np.array(bounds["discrepancy_xy_m"])
|
||||
clearance = np.maximum(lower - obstacles, obstacles - upper).max(axis=1)
|
||||
hard_clearance = np.maximum(lower - error - obstacles, obstacles - upper - error).max(
|
||||
axis=1
|
||||
)
|
||||
# Keep the pre-existing reserve exception, but never excuse penetration
|
||||
# of the body discrepancy envelope, even when departing an obstacle.
|
||||
suspects = (clearance + 1e-6 < np.minimum(initial, self.clearance_m)) | (hard_clearance <= 0)
|
||||
if not np.any(suspects):
|
||||
return True
|
||||
return self._rotating_envelope_clear(
|
||||
obstacles[suspects], initial[suspects], bounds, yaw_rate)
|
||||
|
||||
def _rotating_envelope_clear(self, obstacles, initial, bounds, yaw_rate):
|
||||
"""Refine the broad AABB without shrinking any motion uncertainty.
|
||||
|
||||
def regulate_command(speed, yaw_rate, terrain, pose):
|
||||
"""Reduce speed along CMU's same arc when its full-speed stop is unsafe.
|
||||
AABB corners combine body extrema attained at different headings and
|
||||
can falsely forbid a pivot AWAY from an obstacle beside the front.
|
||||
Retain the entire uncertain translation rectangle at every orientation.
|
||||
Test its Minkowski sum with the oriented body on all four separating
|
||||
axes. Each angular interval is enclosed by a corner-displacement disk;
|
||||
this is an outer bound between samples, not a collision sampling gap.
|
||||
The same reserve, latency, braking and discrepancy remain mandatory.
|
||||
"""
|
||||
angle = max(-2 * math.pi, min(2 * math.pi, yaw_rate * bounds["horizon_seconds"]))
|
||||
if abs(angle) < 1e-12:
|
||||
return False # Straight AABB is already exact.
|
||||
low, high = np.array(bounds["centre_lower_xy_m"]), np.array(bounds["centre_upper_xy_m"])
|
||||
centre, half = (low + high) / 2, (high - low) / 2
|
||||
error = np.array(bounds["discrepancy_xy_m"])
|
||||
count = max(1, math.ceil(abs(angle) / 0.025))
|
||||
step = angle / count
|
||||
radius = math.hypot(self.collision_half_length, self.collision_half_width)
|
||||
delta = obstacles - centre
|
||||
reserve = np.minimum(initial, self.clearance_m)
|
||||
intervals = [(index * step, (index + 1) * step, 0) for index in range(count)]
|
||||
while intervals:
|
||||
start, end, depth = intervals.pop()
|
||||
theta = (start + end) / 2
|
||||
angular_error = 2 * radius * math.sin(abs(end - start) / 4)
|
||||
c, s = math.cos(theta), math.sin(theta)
|
||||
abs_c, abs_s = abs(c), abs(s)
|
||||
# Axes of the axis-aligned centre box and of the rotated chassis
|
||||
# are all edge normals of their Minkowski sum (a zonotope).
|
||||
projections = np.column_stack((np.abs(delta),
|
||||
np.abs(delta[:,0]*c + delta[:,1]*s),
|
||||
np.abs(-delta[:,0]*s + delta[:,1]*c)))
|
||||
extent = np.array([
|
||||
half[0] + self.collision_half_length*abs_c + self.collision_half_width*abs_s,
|
||||
half[1] + self.collision_half_length*abs_s + self.collision_half_width*abs_c,
|
||||
self.collision_half_length + half[0]*abs_c + half[1]*abs_s,
|
||||
self.collision_half_width + half[0]*abs_s + half[1]*abs_c,
|
||||
])
|
||||
separation = projections - extent
|
||||
uncertainty = np.array([error[0], error[1],
|
||||
error[0]*abs_c + error[1]*abs_s, error[0]*abs_s + error[1]*abs_c])
|
||||
# A midpoint collision is an actual counterexample. Otherwise an
|
||||
# inconclusive outer bound needs refinement, not a permanent veto:
|
||||
# a coarse angular disk can consume a genuinely clear few mm at a
|
||||
# corner and strand the same nominal path on every observation.
|
||||
if np.any(separation.max(axis=1) + 1e-6 < reserve):
|
||||
return False
|
||||
if np.any((separation - uncertainty).max(axis=1) <= 0):
|
||||
return False
|
||||
bounded = separation - angular_error
|
||||
if (np.any(bounded.max(axis=1) + 1e-6 < reserve)
|
||||
or np.any((bounded - uncertainty).max(axis=1) <= 0)):
|
||||
if depth >= 10:
|
||||
return False # Unresolved intervals never grant motion.
|
||||
intervals.extend(((start, theta, depth + 1), (theta, end, depth + 1)))
|
||||
return True
|
||||
|
||||
Scaling both components preserves curvature. The shortened stopping envelope
|
||||
is a prefix of the original arc, so search for its largest admitted scale.
|
||||
Never choose another turn/direction, ignore a hazard or creep arbitrarily.
|
||||
"""
|
||||
if command_footprint_clear(speed, yaw_rate, terrain, pose):
|
||||
return speed, yaw_rate, 1.0
|
||||
low, high = 0.2, 1.0
|
||||
if not command_footprint_clear(speed * low, yaw_rate * low, terrain, pose):
|
||||
return 0.0, 0.0, 0.0
|
||||
for _ in range(7):
|
||||
middle = (low + high) / 2
|
||||
if command_footprint_clear(speed * middle, yaw_rate * middle, terrain, pose):
|
||||
low = middle
|
||||
def assess_command_support(
|
||||
self, speed, yaw_rate, terrain, pose, contact_height_m, *, surface=None
|
||||
):
|
||||
"""Check newly entered area, without demanding sight through the body.
|
||||
|
||||
Legacy inputs use the full-body lattice; v2 uses selected contact bands.
|
||||
Each fixed lattice rounds outward from its envelope. Its samples
|
||||
are nested when command scale decreases; reducing speed cannot skip a
|
||||
failed sample by shifting a grid. The currently occupied body is excluded
|
||||
from this future-ground test, not painted as observed terrain. Known
|
||||
obstacles retain their independent full-body veto. A stop is always
|
||||
available and does not certify that the existing pose is safe.
|
||||
"""
|
||||
bounds = self.command_bounds(speed, yaw_rate)
|
||||
lower = np.array(bounds["lower_xy_m"]) - bounds["discrepancy_xy_m"]
|
||||
upper = np.array(bounds["upper_xy_m"]) + bounds["discrepancy_xy_m"]
|
||||
if self.contacts is not None:
|
||||
spacing = self.contacts.spacing_m
|
||||
local, sides = self.contacts.cells(bounds, yaw_rate)
|
||||
else:
|
||||
high = middle
|
||||
return speed * low, yaw_rate * low, low
|
||||
spacing = 0.1
|
||||
low, high = np.floor(lower / spacing).astype(int), np.ceil(upper / spacing).astype(int)
|
||||
if np.prod(high - low + 1) > 20000:
|
||||
raise ValueError("Support envelope exceeds bounded sample budget")
|
||||
local = (
|
||||
np.array(
|
||||
[[x, y] for x in range(low[0], high[0] + 1) for y in range(low[1], high[1] + 1)]
|
||||
)
|
||||
* spacing
|
||||
)
|
||||
pose = np.asarray(pose, dtype=float)
|
||||
if pose.shape != (7,) or not np.isfinite(pose).all():
|
||||
raise ValueError("Invalid support pose")
|
||||
x, y, z, w = pose[3:]
|
||||
yaw = math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
|
||||
axes = np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]])
|
||||
offsets = local @ axes.T
|
||||
current = (np.abs(local[:, 0]) <= self.half_length) & (
|
||||
np.abs(local[:, 1]) <= self.half_width
|
||||
)
|
||||
moving = abs(speed) + abs(yaw_rate) > 1e-8
|
||||
required = ~current if moving else np.zeros(len(local), bool)
|
||||
if surface is None:
|
||||
surface = SupportSurface(terrain, pose, contact_height_m, self.max_step, self.max_slope,
|
||||
anchor_radius_m=math.hypot(self.half_length, self.half_width))
|
||||
states, reasons = self.classify_contacts(surface, offsets[required])
|
||||
supported = int(np.count_nonzero(states == "observed-supported"))
|
||||
unknown = int(np.count_nonzero(states == "unknown"))
|
||||
unsafe = int(np.count_nonzero(states == "observed-unsafe"))
|
||||
missing = offsets[required][states != "observed-supported"] + pose[:2]
|
||||
return dict(
|
||||
schema_version="missioncore.swept-support/v2"
|
||||
if self.contacts is not None
|
||||
else "missioncore.swept-support/v1",
|
||||
admitted=supported == len(states),
|
||||
status="hold"
|
||||
if not moving
|
||||
else "current-footprint-only"
|
||||
if not len(states)
|
||||
else "observed-unsafe"
|
||||
if unsafe
|
||||
else "unknown"
|
||||
if unknown
|
||||
else "observed-supported",
|
||||
support_samples=len(states),
|
||||
supported_samples=supported,
|
||||
unknown_samples=unknown,
|
||||
unsafe_samples=unsafe,
|
||||
current_body_excluded_samples=int(current.sum()),
|
||||
scope="newly-entered-area; current body occupancy is not a ground observation",
|
||||
support_spacing_m=spacing,
|
||||
support_radius_m=SupportSurface.radius_m,
|
||||
support_reasons=reasons,
|
||||
bounds=bounds,
|
||||
roughness_obstacles_xyz=list(surface.raised_obstacles.values()),
|
||||
support_obstacle_samples=surface.hazard_samples(
|
||||
offsets[required][states == "observed-unsafe"]),
|
||||
unsupported_xy=missing[:12].tolist(),
|
||||
**(
|
||||
{
|
||||
"ground_contact": self.contacts.value,
|
||||
"per_side": {
|
||||
name: {
|
||||
"support_samples": int(sides[required, side].sum()),
|
||||
"unknown_samples": int(
|
||||
np.count_nonzero((states == "unknown") & sides[required, side])
|
||||
),
|
||||
"unsafe_samples": int(
|
||||
np.count_nonzero(
|
||||
(states == "observed-unsafe") & sides[required, side]
|
||||
)
|
||||
),
|
||||
}
|
||||
for side, name in enumerate(("left", "right"))
|
||||
},
|
||||
}
|
||||
if self.contacts is not None
|
||||
else {}
|
||||
),
|
||||
)
|
||||
|
||||
def regulate_supported_command(self, speed, yaw_rate, terrain, pose, contact_height_m):
|
||||
"""The same requested arc must pass obstacle and new-ground checks."""
|
||||
surface = SupportSurface(terrain, pose, contact_height_m, self.max_step, self.max_slope,
|
||||
anchor_radius_m=math.hypot(self.half_length, self.half_width))
|
||||
|
||||
def swept_footprint_clear(path, terrain, pose):
|
||||
path = np.asarray(path, dtype=float)[:, :2]
|
||||
terrain = np.asarray(terrain, dtype=float)
|
||||
if len(path) < 2 or terrain.ndim != 2 or terrain.shape[1] != 4:
|
||||
return False
|
||||
obstacles = _obstacles(terrain, pose)
|
||||
def assess(scale):
|
||||
v, w = speed * scale, yaw_rate * scale
|
||||
ground = self.assess_command_support(
|
||||
v, w, terrain, pose, contact_height_m, surface=surface
|
||||
)
|
||||
return self.command_footprint_clear(v, w, terrain, pose) and ground["admitted"], ground
|
||||
|
||||
previous_angle = 0.0
|
||||
for start, end in zip(path[:-1], path[1:], strict=True):
|
||||
delta = end - start
|
||||
length = np.linalg.norm(delta)
|
||||
if length < 1e-6:
|
||||
continue
|
||||
angle = math.atan2(delta[1], delta[0])
|
||||
turn = math.atan2(math.sin(angle - previous_angle), math.cos(angle - previous_angle))
|
||||
for fraction in np.linspace(0, 1, max(2, math.ceil(abs(turn) / 0.035) + 1)):
|
||||
if not _clear(obstacles, start, previous_angle + fraction * turn):
|
||||
return False
|
||||
for fraction in np.linspace(0, 1, max(2, math.ceil(length / 0.025) + 1)):
|
||||
if not _clear(obstacles, start + fraction * delta, angle):
|
||||
return False
|
||||
previous_angle = angle
|
||||
return True
|
||||
clear, support = assess(1.0)
|
||||
if clear:
|
||||
return speed, yaw_rate, 1.0, support
|
||||
low, high = self.minimum_command_scale(speed, yaw_rate), 1.0
|
||||
clear, support = assess(low)
|
||||
if not clear:
|
||||
return 0.0, 0.0, 0.0, support
|
||||
for _ in range(7):
|
||||
middle = (low + high) / 2
|
||||
clear, candidate = assess(middle)
|
||||
if clear:
|
||||
low, support = middle, candidate
|
||||
else:
|
||||
high = middle
|
||||
return speed * low, yaw_rate * low, low, support
|
||||
|
||||
def regulate_command(self, speed, yaw_rate, terrain, pose):
|
||||
"""Reduce speed along CMU's same arc when its full-speed stop is unsafe.
|
||||
|
||||
Scaling both components preserves requested curvature. The sector bounds
|
||||
and discrepancy shrink monotonically, so find the largest admitted scale.
|
||||
Never choose another turn/direction, ignore a hazard or creep arbitrarily.
|
||||
"""
|
||||
if self.command_footprint_clear(speed, yaw_rate, terrain, pose):
|
||||
return speed, yaw_rate, 1.0
|
||||
low, high = self.minimum_command_scale(speed, yaw_rate), 1.0
|
||||
if not self.command_footprint_clear(speed * low, yaw_rate * low, terrain, pose):
|
||||
return 0.0, 0.0, 0.0
|
||||
for _ in range(7):
|
||||
middle = (low + high) / 2
|
||||
if self.command_footprint_clear(speed * middle, yaw_rate * middle, terrain, pose):
|
||||
low = middle
|
||||
else:
|
||||
high = middle
|
||||
return speed * low, yaw_rate * low, low
|
||||
|
||||
@staticmethod
|
||||
def minimum_command_scale(speed, yaw_rate):
|
||||
"""Bound arbitrarily slow creep in physical units, not a setpoint ratio.
|
||||
|
||||
The existing 0.1 commands admitted regulation down to 0.02 m/s or
|
||||
rad/s. Keep that simulation floor for larger setpoints too: raising
|
||||
the operator's maximum must not remove an already feasible slow arc.
|
||||
Smaller original proposals (e.g. acceleration ramps) stay unchanged.
|
||||
This is an operational floor, not a motor/traction qualification.
|
||||
"""
|
||||
magnitude = abs(speed) if abs(speed) > 1e-8 else abs(yaw_rate)
|
||||
return min(1.0, 0.02 / max(magnitude, 1e-12))
|
||||
|
||||
def swept_footprint_clear(self, path, terrain, pose):
|
||||
path = np.asarray(path, dtype=float)[:, :2]
|
||||
terrain = np.asarray(terrain, dtype=float)
|
||||
if len(path) < 2 or terrain.ndim != 2 or terrain.shape[1] != 4:
|
||||
return False
|
||||
obstacles = self._obstacles(terrain, pose)
|
||||
|
||||
previous_angle = 0.0
|
||||
for start, end in zip(path[:-1], path[1:], strict=True):
|
||||
delta = end - start
|
||||
length = np.linalg.norm(delta)
|
||||
if length < 1e-6:
|
||||
continue
|
||||
angle = math.atan2(delta[1], delta[0])
|
||||
turn = math.atan2(math.sin(angle - previous_angle), math.cos(angle - previous_angle))
|
||||
for fraction in np.linspace(0, 1, max(2, math.ceil(abs(turn) / 0.035) + 1)):
|
||||
if not self._clear(obstacles, start, previous_angle + fraction * turn):
|
||||
return False
|
||||
for fraction in np.linspace(0, 1, max(2, math.ceil(length / 0.025) + 1)):
|
||||
if not self._clear(obstacles, start + fraction * delta, angle):
|
||||
return False
|
||||
previous_angle = angle
|
||||
return True
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Select a nearby forward arc when the chosen path's first command is blocked.
|
||||
|
||||
CMU still owns the path. Like a trajectory-sampling controller, this adapter
|
||||
checks several velocities against that path and the independent body/support
|
||||
constraints. No new target, map permission or unseen ground is created here.
|
||||
"""
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
if __package__:
|
||||
from .arrival_approach import forward_path_command
|
||||
else:
|
||||
from arrival_approach import forward_path_command
|
||||
|
||||
|
||||
def follows_prefix(command, path, monitor, tolerance):
|
||||
"""The entire nominal stop trajectory stays near the existing local path."""
|
||||
points = np.asarray(path, dtype=float)[:, :2]
|
||||
if len(points) < 2 or not np.isfinite(points).all():
|
||||
return False
|
||||
a, delta = points[:-1], np.diff(points, axis=0)
|
||||
length = np.linalg.norm(delta, axis=1)
|
||||
keep = length > 1e-8
|
||||
if not keep.any():
|
||||
return False
|
||||
a, delta, length = a[keep], delta[keep], length[keep]
|
||||
starts = np.r_[0, np.cumsum(length)[:-1]]
|
||||
v, w = command
|
||||
horizon = monitor.command_bounds(v, w)['horizon_seconds']
|
||||
# <= 2 cm nominal travel between samples, plus both endpoints. Body and
|
||||
# support checks independently bound the continuous uncertain motion.
|
||||
count = max(2, math.ceil(abs(v)*horizon/.02)+1)
|
||||
times = np.linspace(0, horizon, count)
|
||||
if abs(w) < 1e-9:
|
||||
trace = np.c_[v*times, np.zeros(count)]
|
||||
else:
|
||||
trace = v/w*np.c_[np.sin(w*times), 1-np.cos(w*times)]
|
||||
shift = trace[:, None, :] - a
|
||||
fractions = np.clip(np.einsum('nsi,si->ns', shift, delta)/(length**2), 0, 1)
|
||||
distance = np.linalg.norm(shift - fractions[:, :, None]*delta, axis=2)
|
||||
closest = np.argmin(distance, axis=1)
|
||||
progress = starts[closest] + fractions[np.arange(count), closest]*length[closest]
|
||||
return bool(np.max(distance[np.arange(count), closest]) <= tolerance
|
||||
and progress[-1] > progress[0] + .01
|
||||
and np.min(np.diff(progress)) >= -.01)
|
||||
|
||||
|
||||
def admit_forward_prefix(path, monitor, policy, terrain, pose, height, current_points,
|
||||
*, lookahead_m, maximum_speed):
|
||||
"""Prefer the chosen path curvature, then test gentler forward arcs.
|
||||
|
||||
This is a bounded fallback, not a reverse/turn recovery or obstacle waiver.
|
||||
Its lateral tracking tolerance is half the narrower physical track width.
|
||||
Every candidate must have completely observed stopping support. The live
|
||||
controller repeats admission with the current pose and raw ranges.
|
||||
"""
|
||||
if monitor.contacts is None:
|
||||
return None
|
||||
centres = [(low[1]+high[1])/2 for low, high in monitor.contacts.bands]
|
||||
base = forward_path_command(path, centres, lookahead_m=lookahead_m,
|
||||
maximum_speed=min(maximum_speed, .3), maximum_yaw_rps=policy.partial_yaw_rps)
|
||||
if base is None:
|
||||
return None
|
||||
tolerance = min(high[1]-low[1] for low, high in monitor.contacts.bands)/2
|
||||
trials = []
|
||||
# Two speed levels let a short prefix be followed without extending it.
|
||||
for speed in dict.fromkeys((base[0], min(base[0], policy.partial_speed_mps))):
|
||||
for factor in (1., .5, 0.):
|
||||
yaw = speed * base[2]['curvature_per_m'] * factor
|
||||
v, w, body_scale = monitor.regulate_command(speed, yaw, terrain, pose)
|
||||
if body_scale == 0 or v <= 0:
|
||||
continue
|
||||
if not follows_prefix((v, w), path, monitor, tolerance):
|
||||
continue
|
||||
v, w, scale, ground = policy.regulate(v, w, terrain, pose, height,
|
||||
current_points=current_points)
|
||||
trials.append(dict(proposal=[speed, yaw], admitted=bool(scale > 0 and ground['admitted'])))
|
||||
if scale == 0 or not ground['admitted']:
|
||||
continue
|
||||
if not follows_prefix((v, w), path, monitor, tolerance):
|
||||
continue
|
||||
return v, w, body_scale, scale, ground, dict(
|
||||
phase='forward-path', method='velocity-sampling',
|
||||
tracking_tolerance_m=tolerance, trials=trials,
|
||||
authority='existing-prefix; full stopping support and live obstacle veto')
|
||||
return None
|
||||
@@ -0,0 +1,54 @@
|
||||
// A smooth preference for space, independent of the hard swept-body veto.
|
||||
// Known hazards only; missing ground never becomes a traversability grant.
|
||||
#pragma once
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
template <class TerrainCloud, class PathCloud>
|
||||
double missioncoreClearancePreference(const TerrainCloud& terrain, const PathCloud& path,
|
||||
double rotation, double scale, double range, double length, double width,
|
||||
double threshold, double decayLength) {
|
||||
if (!(decayLength > 0)) return 1.0;
|
||||
const double halfLength = length / 2 - .05, halfWidth = width / 2 - .05;
|
||||
const double cap = std::min(range, 1.2);
|
||||
// At six decay lengths the remaining influence is below 0.25%.
|
||||
const double influence = 6 * decayLength;
|
||||
std::vector<std::pair<double,double>> hazards;
|
||||
for (const auto& p : terrain.points)
|
||||
if (p.intensity > threshold && std::hypot(p.x,p.y) <
|
||||
cap + std::hypot(halfLength,halfWidth) + influence)
|
||||
hazards.emplace_back(p.x,p.y);
|
||||
if (hazards.empty()) return 1.0;
|
||||
const double c = std::cos(rotation), s = std::sin(rotation);
|
||||
double lastX = 0, lastY = 0, lastSample = -.1, penalty = 0;
|
||||
int count = 0;
|
||||
for (const auto& p : path.points) {
|
||||
const double distance = std::hypot(p.x,p.y)*scale;
|
||||
if (distance > cap) break;
|
||||
const double x = scale*(c*p.x-s*p.y), y = scale*(s*p.x+c*p.y);
|
||||
const double dx = x-lastX, dy = y-lastY;
|
||||
if (std::hypot(dx,dy) < 1e-6) continue;
|
||||
const double yaw = std::atan2(dy,dx);
|
||||
lastX = x; lastY = y;
|
||||
// Sample by distance, so dense path vertices don't bias the preference.
|
||||
if (distance-lastSample < .1) continue;
|
||||
lastSample = distance;
|
||||
const double cy = std::cos(yaw), sy = std::sin(yaw);
|
||||
double nearest = influence;
|
||||
for (const auto& h : hazards) {
|
||||
const double hx = h.first-x, hy = h.second-y;
|
||||
const double along = std::max(0.0,std::abs(hx*cy+hy*sy)-halfLength);
|
||||
const double across = std::max(0.0,std::abs(-hx*sy+hy*cy)-halfWidth);
|
||||
nearest = std::min(nearest,std::hypot(along,across));
|
||||
}
|
||||
penalty += std::exp(-nearest/decayLength);
|
||||
++count;
|
||||
}
|
||||
// Zero clearance must not retain a one-third score floor: that floor let
|
||||
// goal direction dominate the clearance field beside a forbidden verge.
|
||||
// Exponential free-space utility approaches zero continuously at contact.
|
||||
// Positive narrow corridors remain candidates; the hard veto is separate.
|
||||
return count ? std::max(1e-9, 1.0-penalty/count) : 1.0;
|
||||
}
|
||||
@@ -49,6 +49,10 @@ bool missioncoreFootprintClear(const TerrainCloud& terrain, const PathCloud& pat
|
||||
lookYaw = rotation + std::atan2(p.y, p.x);
|
||||
if (std::hypot(p.x, p.y) * scale >= std::min(0.7, cap)) break;
|
||||
}
|
||||
// A forward-only mission must not select a reversing primitive merely
|
||||
// because its initial turn is collision-free. Reverse requires an explicit
|
||||
// observed recovery grant, shared with pathFollower for this transaction.
|
||||
if (!twoWayDrive && std::cos(lookYaw) < 0) return false;
|
||||
// A reversing body follows the rear-facing primitive without first turning
|
||||
// 180 degrees. Match pathFollower's twoWayDrive direction selection.
|
||||
const bool reverse = twoWayDrive && std::cos(lookYaw) < 0;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
#include <cmath>
|
||||
|
||||
// Score the endpoint bearing of the same prefix localPlanner publishes. The
|
||||
// full lattice path's final heading is unrelated to a short, cropped target.
|
||||
// Coordinates and limit are in the unscaled primitive frame. Rotation is
|
||||
// applied by the existing selector, exactly as for the published trajectory.
|
||||
template <class Cloud>
|
||||
double missioncorePrefixDirection(const Cloud& path, double limit) {
|
||||
double x = 0, y = 0;
|
||||
for (const auto& point : path.points) {
|
||||
const float distance = std::sqrt(point.x * point.x + point.y * point.y);
|
||||
if (distance > limit) break;
|
||||
x = point.x;
|
||||
y = point.y;
|
||||
}
|
||||
return std::atan2(y, x) * 180.0 / std::acos(-1.0);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Pure pursuit of the existing local path, in the current vehicle frame.
|
||||
// Geometry determines curvature; changing speed must preserve the same arc.
|
||||
// Rotation-in-place, acceleration, goal stop and safety gates remain owned by
|
||||
// pathFollower and the independent live swept-body/support monitor.
|
||||
#pragma once
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
inline double missioncorePursuitYaw(double speed, double lateral,
|
||||
double distance, double maxYaw) {
|
||||
if (distance <= 1e-6) return 0.0;
|
||||
const double yaw = speed * 2.0 * lateral / (distance * distance);
|
||||
return std::max(-maxYaw, std::min(maxYaw, yaw));
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Local intent from current range and causal multi-view surface observations.
|
||||
|
||||
Changing the camera sector must not move a still observed goal to that sector's
|
||||
image centre. This selects measured points, never a route or permission to move;
|
||||
the native planner still admits the complete commanded body sweep.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .semantic_surface import SemanticSurface
|
||||
|
||||
|
||||
class ObservedGoals:
|
||||
def __init__(self):
|
||||
self.surface = SemanticSurface(retain_near=True)
|
||||
self.evidence = None
|
||||
|
||||
def observe(self, samples, captured_at, pose):
|
||||
self.surface.observe(samples, captured_at, pose)
|
||||
|
||||
def maneuver(self, points, pose, target, prior, excluded, geometry, now, candidate_mask=None):
|
||||
"""Measured local destinations may temporarily move away from the task.
|
||||
|
||||
This removes the greedy progress constraint ONLY during a surveyed
|
||||
recovery. It proposes a heading/destination, not a path or a clearance
|
||||
receipt. The native planner and body/support guards remain mandatory.
|
||||
"""
|
||||
points = np.asarray(points, dtype=float).reshape(-1, 3)
|
||||
if not len(points) or target is None:
|
||||
return None
|
||||
if prior is not None and prior.get("kind") == "orient":
|
||||
# The viewing intent survives its source leaving the crop. Current
|
||||
# range and full swept-body support still govern the actual pivot.
|
||||
return prior
|
||||
def inspect_heading():
|
||||
# Nav-style Spin intent: inspect with front range sensors when the
|
||||
# panoramic image has no usable metric correspondence (self occlusion
|
||||
# included). These XY values encode a bearing, NEVER a drive goal.
|
||||
x, y, z, w = pose[3:7]
|
||||
yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
|
||||
directions = [yaw+offset for offset in (math.pi/2, -math.pi/2, math.pi)]
|
||||
views = [np.asarray(pose[:2])+2*geometry["length_m"]*np.array([math.cos(a),math.sin(a)])
|
||||
for a in directions]
|
||||
for xy in sorted(views, key=lambda p: math.dist(p, target)):
|
||||
if all(math.dist(xy, p[:2]) > .6 for p in excluded):
|
||||
return dict(goal=[*xy.tolist(), pose[2]-geometry["body_contact_height_m"]],
|
||||
reverse=False, kind="orient")
|
||||
return None
|
||||
permitted = self.surface.permitted_terrain(points, now)
|
||||
if not len(permitted):
|
||||
return None if prior is not None else inspect_heading()
|
||||
xy = np.asarray(pose[:2])
|
||||
if prior is not None:
|
||||
point = np.asarray(prior["goal"])
|
||||
cell = tuple(self.surface.cell_keys(point[None])[0])
|
||||
permission, stamp = self.surface.cells.get(cell, (0, -math.inf))
|
||||
# The point may enter the near camera/range blind strip. Retain its
|
||||
# causal intent only; current swept support still vetoes every tick.
|
||||
if (permission != 1 or not self.surface.retained(cell, stamp, now)
|
||||
or (candidate_mask is not None and not candidate_mask(point[None])[0])
|
||||
or (math.dist(point[:2], xy) > .6
|
||||
and not np.any(np.linalg.norm(permitted-point, axis=1) <= .2))):
|
||||
return None
|
||||
return prior
|
||||
delta = permitted[:, :2] - xy
|
||||
distance = np.linalg.norm(delta, axis=1)
|
||||
good = (distance >= .6) & (distance <= 2 * geometry["length_m"])
|
||||
good &= np.abs(permitted[:, 2] - (pose[2]-geometry["body_contact_height_m"])) <= (
|
||||
geometry["max_step_m"] + distance*math.tan(math.radians(geometry["max_slope_degrees"])))
|
||||
if candidate_mask is not None:
|
||||
good &= candidate_mask(permitted)
|
||||
for failed in excluded:
|
||||
good &= np.linalg.norm(permitted[:, :2] - np.asarray(failed[:2]), axis=1) > .6
|
||||
candidates = permitted[good]
|
||||
if not len(candidates):
|
||||
return inspect_heading()
|
||||
x, y, z, w = pose[3:7]
|
||||
yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
|
||||
delta = candidates[:, :2] - xy
|
||||
bearings = np.arctan2(delta[:, 1], delta[:, 0]) - yaw
|
||||
errors = np.arctan2(np.sin(bearings), np.cos(bearings))
|
||||
distance = np.linalg.norm(delta, axis=1)
|
||||
# A short straight back-out is one option, alongside forward arcs and
|
||||
# stopped pivots. It is never an obligatory first recovery action.
|
||||
reverse = (np.abs(errors) > math.pi-.12) & (distance <= .8)
|
||||
turning = np.where(reverse, math.pi-np.abs(errors), np.abs(errors))
|
||||
score = np.linalg.norm(candidates[:, :2]-target, axis=1) + .2*turning + .15*distance
|
||||
offsets = np.linspace(-geometry["width_m"]/2, geometry["width_m"]/2,
|
||||
math.ceil(geometry["width_m"]/.1)+1)
|
||||
# Search once per 20 cm observed cell, not every duplicate ray return.
|
||||
tried = set()
|
||||
for i in np.argsort(score, kind="stable"):
|
||||
point = candidates[i]
|
||||
key = tuple(self.surface.cell_keys(point[None])[0])
|
||||
if key in tried:
|
||||
continue
|
||||
tried.add(key)
|
||||
forward = delta[i]/distance[i]
|
||||
lateral = np.array([-forward[1], forward[0]])
|
||||
across = point[:2]+offsets[:, None]*lateral
|
||||
distances = np.linalg.norm(across[:, None, :]-permitted[None, :, :2], axis=2)
|
||||
nearest = np.argmin(distances, axis=1)
|
||||
if np.any(distances[np.arange(len(across)), nearest] > .15):
|
||||
continue
|
||||
heights = permitted[nearest, 2]
|
||||
fit = np.polyfit(offsets, heights, 1)
|
||||
if (abs(fit[0]) > math.tan(math.radians(geometry["max_slope_degrees"]))
|
||||
or np.max(np.abs(heights-np.polyval(fit, offsets))) > .05):
|
||||
continue
|
||||
self.evidence = dict(source="surveyed-local-maneuver", goal=point.tolist(),
|
||||
reverse=bool(reverse[i]), authority="intent-only; live native admission required")
|
||||
return dict(goal=point.tolist(), reverse=bool(reverse[i]))
|
||||
# A visible permitted sector can be too narrow/sparse to establish a
|
||||
# translation destination while still being worth inspecting with the
|
||||
# front depth sensors. This grants ONLY an orientation intent. Neither
|
||||
# the point nor the camera survey certifies the ground under a pivot.
|
||||
for i in np.argsort(score, kind="stable"):
|
||||
if abs(errors[i]) >= math.radians(30):
|
||||
return dict(goal=candidates[i].tolist(), reverse=False, kind="orient")
|
||||
return inspect_heading()
|
||||
|
||||
def choose(self, points, pose, target, prior, excluded, geometry, now, candidate_mask=None):
|
||||
self.evidence = None
|
||||
if target is None:
|
||||
return None
|
||||
points, pose, target = map(lambda x: np.asarray(x, dtype=float), (points, pose, target))
|
||||
if points.ndim != 2 or points.shape[1] != 3 or not np.isfinite(points).all():
|
||||
raise ValueError("Invalid observed goal range")
|
||||
if not len(points):
|
||||
return None
|
||||
direction = target - pose[:2]
|
||||
remaining = float(np.linalg.norm(direction))
|
||||
if remaining <= 0.4:
|
||||
return None # Exact arrival remains the native whole-body receipt.
|
||||
forward = direction / remaining
|
||||
lateral = np.array([-forward[1], forward[0]])
|
||||
delta = points[:, :2] - pose[:2]
|
||||
distance = np.linalg.norm(delta, axis=1)
|
||||
progress = np.linalg.norm(points[:, :2] - target, axis=1)
|
||||
good = (
|
||||
(distance >= 0.4) & (distance <= 3.5) & (progress < remaining - 0.1)
|
||||
& (np.abs(points[:, 2] - (pose[2] - geometry["body_contact_height_m"]))
|
||||
<= distance * math.tan(math.radians(geometry["max_slope_degrees"])))
|
||||
)
|
||||
if candidate_mask is not None:
|
||||
good &= candidate_mask(points)
|
||||
for failed in excluded:
|
||||
good &= np.linalg.norm(points[:, :2] - np.asarray(failed[:2]), axis=1) > 0.6
|
||||
candidates = points[good]
|
||||
if len(candidates) < 8:
|
||||
return None
|
||||
allowed = {
|
||||
key: stamp for key, (permission, stamp) in self.surface.cells.items()
|
||||
if permission == 1 and self.surface.retained(key, stamp, now)
|
||||
}
|
||||
candidates = candidates[[tuple(key) in allowed
|
||||
for key in self.surface.cell_keys(candidates)]]
|
||||
if not len(candidates):
|
||||
return None
|
||||
offsets = np.linspace(-geometry["width_m"] / 2, geometry["width_m"] / 2,
|
||||
math.ceil(geometry["width_m"] / 0.1) + 1)
|
||||
|
||||
def supported(point):
|
||||
across = point[:2] + offsets[:, None] * lateral
|
||||
# Bind each lateral query to measured, permitted ground at its own
|
||||
# height. Do not copy the centre elevation across a cross-slope or
|
||||
# project a sidewalk label through an overhang onto another floor.
|
||||
distances = np.linalg.norm(across[:,None,:]-candidates[None,:,:2],axis=2)
|
||||
nearest = np.argmin(distances,axis=1)
|
||||
if np.any(distances[np.arange(len(across)),nearest] > .15):
|
||||
return False
|
||||
keys = [tuple(cell) for cell in self.surface.cell_keys(candidates[nearest])]
|
||||
self.evidence = {
|
||||
"source": "current-range-and-observed-semantic-memory",
|
||||
"goal": point.tolist(),
|
||||
"oldest_surface_age_seconds": max(now - allowed[key] for key in keys),
|
||||
"authority": "intent-only; native swept-obstacle-and-support-admission-required",
|
||||
}
|
||||
return True
|
||||
|
||||
# A lens switch cannot replace a currently measured, permitted goal.
|
||||
# A new prohibition, missing current range or changed corridor can.
|
||||
if prior is not None:
|
||||
before = np.asarray(prior, dtype=float)
|
||||
matched = np.linalg.norm(candidates - before, axis=1) <= 0.15
|
||||
if (math.dist(before[:2], pose[:2]) > 0.8 and matched.any()
|
||||
and all(math.dist(before[:2], failed[:2]) > 0.6 for failed in excluded)
|
||||
and (candidate_mask is None or candidate_mask(before[None])[0])
|
||||
and supported(before)):
|
||||
return before.tolist()
|
||||
distance_to_target = np.linalg.norm(candidates[:, :2] - target, axis=1)
|
||||
# The declared task, not the selected lens, owns the preferred direction.
|
||||
score = distance_to_target + 2 * np.abs((candidates[:, :2] - pose[:2]) @ lateral)
|
||||
for index in np.argsort(score, kind="stable"):
|
||||
if supported(candidates[index]):
|
||||
return candidates[index].tolist()
|
||||
return None
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Reconcile coarse elevation costs using measured local ground patches.
|
||||
|
||||
CMU's low-quantile reference spans a wider neighborhood than a contact patch.
|
||||
A nearby depression can give a level sidewalk a high cost. Only low returns
|
||||
near the measured body contact plane are candidates; their complete measured
|
||||
neighborhood must independently pass the existing support estimator. This runs
|
||||
before semantic/object overlays and never fills an unobserved ground region.
|
||||
"""
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
if __package__:
|
||||
from .support_surface import SupportSurface
|
||||
else:
|
||||
from support_surface import SupportSurface
|
||||
|
||||
|
||||
def observed_ground_costs(terrain, pose, contact_height_m, *, monitor):
|
||||
terrain = np.asarray(terrain)
|
||||
pose = np.asarray(pose, dtype=float)
|
||||
if (terrain.ndim != 2 or terrain.shape[1] != 4 or pose.shape != (7,)
|
||||
or not np.isfinite(terrain).all() or not np.isfinite(pose).all()):
|
||||
raise ValueError("Invalid observed ground cost input")
|
||||
x, y, z, w = pose[3:]
|
||||
up = np.array([2*(x*z+w*y), 2*(y*z-w*x), 1-2*(x*x+y*y)])
|
||||
height = (terrain[:, :3]-pose[:3]) @ up + contact_height_m
|
||||
band = min(.08, .8*monitor.max_step)
|
||||
candidates = (terrain[:, 3] > monitor.max_step+1e-4) & (np.abs(height) <= band)
|
||||
if not candidates.any() or up[2] < 1/math.sqrt(1+monitor.max_slope**2):
|
||||
return terrain, 0
|
||||
# Separate raised objects from the ground fit, as the live range guard
|
||||
# does. Otherwise a wall/bench column tilts the fit of the pavement beside
|
||||
# it, and that pavement becomes a phantom solid obstacle in path search.
|
||||
# Raised returns retain their ORIGINAL costs; negative returns remain in
|
||||
# the fit, so this cannot erase a drop or manufacture its floor.
|
||||
ground_cost = np.where(height > monitor.max_step+1e-4, monitor.max_step+1, 0)
|
||||
surface = SupportSurface(np.column_stack((terrain[:, :3], ground_cost)),
|
||||
pose, contact_height_m, monitor.max_step, monitor.max_slope,
|
||||
anchor_radius_m=math.hypot(monitor.half_length, monitor.half_width))
|
||||
indices = np.flatnonzero(candidates)
|
||||
states, _ = surface.classify(terrain[indices, :2]-pose[:2])
|
||||
accepted = indices[states == "observed-supported"]
|
||||
result = terrain.copy()
|
||||
result[accepted, 3] = np.abs(height[accepted])
|
||||
return result, len(accepted)
|
||||
@@ -0,0 +1,175 @@
|
||||
"""Causal range memory: clear only measured free space, retain occluded near field.
|
||||
|
||||
Organized sensors clear whole 6 cm voxels through calibrated range images;
|
||||
legacy packets use traversed ray voxels. A missing observation grants no
|
||||
clearing. Endpoints are inserted afterwards, so current occupied evidence wins.
|
||||
Scene identities, hidden geometry and qualification fixtures never enter here.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
if __package__:
|
||||
from .range_image import RangeImages, VIEW_FIELDS
|
||||
else:
|
||||
from range_image import RangeImages, VIEW_FIELDS
|
||||
|
||||
|
||||
class ObservedSpace:
|
||||
voxel_m = 0.06
|
||||
endpoint_margin_m = 0.12
|
||||
near_memory_m = 4.0
|
||||
far_decay_seconds = 2.0
|
||||
maximum_observation_points = 30000
|
||||
# A persistent 360-degree map is not one sensor packet. Bound its storage
|
||||
# separately (128K occupied voxels), retaining the existing spatial/age
|
||||
# window and fail-closed overflow. Never evict a near hazard to fit a frame.
|
||||
maximum_cells = 131072
|
||||
|
||||
def __init__(self):
|
||||
self.cells = {}
|
||||
self.last_time = None
|
||||
self.metrics = {}
|
||||
|
||||
def keys(self, points):
|
||||
grid = np.floor(np.asarray(points, dtype=float) / self.voxel_m)
|
||||
if not np.isfinite(grid).all() or np.any(np.abs(grid) >= 2**20):
|
||||
raise ValueError("Range memory coordinate envelope exceeded")
|
||||
cells = grid.astype(np.int64)
|
||||
cells += 2**20
|
||||
return (cells[..., 0] << 42) | (cells[..., 1] << 21) | cells[..., 2]
|
||||
|
||||
def free_keys(self, origins, ends, origin_indices=None):
|
||||
if origins is None and ends is None:
|
||||
return np.empty(0, dtype=np.int64)
|
||||
origins, ends = np.asarray(origins, dtype=float), np.asarray(ends, dtype=float)
|
||||
if origin_indices is not None:
|
||||
indices = np.asarray(origin_indices)
|
||||
if (
|
||||
origins.ndim != 2
|
||||
or origins.shape[1] != 3
|
||||
or indices.ndim != 1
|
||||
or len(indices) > 8000
|
||||
or (len(indices) and not np.issubdtype(indices.dtype, np.integer))
|
||||
or np.any(indices < 0)
|
||||
or np.any(indices >= len(origins))
|
||||
):
|
||||
raise ValueError("Invalid range-ray mount indices")
|
||||
origins = origins[indices.astype(np.int64)]
|
||||
if origins.size == ends.size == 0:
|
||||
return np.empty(0, dtype=np.int64)
|
||||
if (
|
||||
origins.ndim != 2
|
||||
or origins.shape[1] != 3
|
||||
or ends.shape != origins.shape
|
||||
or len(origins) > 8000
|
||||
or not np.isfinite(origins).all()
|
||||
or not np.isfinite(ends).all()
|
||||
):
|
||||
raise ValueError("Invalid observed range-ray packet")
|
||||
delta = ends - origins
|
||||
ranges = np.linalg.norm(delta, axis=1)
|
||||
if np.any(ranges > 8.01):
|
||||
raise ValueError("Range ray exceeds the declared sensor envelope")
|
||||
# Amanatides-Woo traversal: fixed-distance sampling misses arbitrarily
|
||||
# short crossings near voxel edges and leaves permanent ghost walls.
|
||||
# Traverse the measured open segment only; never dilate its free space.
|
||||
valid = ranges > 2*self.endpoint_margin_m
|
||||
directions = delta[valid] / ranges[valid, None]
|
||||
starts = origins[valid] + self.endpoint_margin_m*directions
|
||||
lengths = ranges[valid] - 2*self.endpoint_margin_m
|
||||
if not len(lengths):
|
||||
return np.empty(0, dtype=np.int64)
|
||||
self.keys(starts) # Validate the same coordinate envelope before packing.
|
||||
self.keys(starts + lengths[:,None]*directions)
|
||||
cells = np.floor(starts / self.voxel_m).astype(np.int64)
|
||||
signs = np.sign(directions).astype(np.int64)
|
||||
increments = np.divide(self.voxel_m, np.abs(directions),
|
||||
out=np.full_like(directions, np.inf), where=directions != 0)
|
||||
boundary = (cells + (signs > 0))*self.voxel_m
|
||||
crossings = np.divide(boundary-starts, directions,
|
||||
out=np.full_like(directions, np.inf), where=directions != 0)
|
||||
entered = np.zeros(len(cells))
|
||||
active = np.ones(len(cells), dtype=bool)
|
||||
keys = []
|
||||
bound = math.ceil(float(lengths.max())*math.sqrt(3)/self.voxel_m)+4
|
||||
for _ in range(bound):
|
||||
leaving = crossings.min(axis=1)
|
||||
occupied_segment = active & (np.minimum(leaving,lengths) > entered + 1e-12)
|
||||
grid = cells[occupied_segment] + 2**20
|
||||
keys.append((grid[:,0] << 42) | (grid[:,1] << 21) | grid[:,2])
|
||||
active &= leaving < lengths - 1e-12
|
||||
if not active.any():
|
||||
break
|
||||
crossed = (crossings <= leaving[:,None] + 1e-12) & active[:,None]
|
||||
cells += signs*crossed
|
||||
crossings += np.where(crossed, increments, 0)
|
||||
entered = leaving
|
||||
else:
|
||||
raise RuntimeError("Range traversal exceeded its geometric bound")
|
||||
return np.unique(np.concatenate(keys)) if keys else np.empty(0, dtype=np.int64)
|
||||
|
||||
def observe(self, points, pose, now, origins=None, ends=None, origin_indices=None,
|
||||
*, range_views=None):
|
||||
points, pose = np.asarray(points, dtype=float), np.asarray(pose, dtype=float)
|
||||
if (
|
||||
points.ndim != 2
|
||||
or points.shape[1] != 3
|
||||
or len(points) > self.maximum_observation_points
|
||||
or not np.isfinite(points).all()
|
||||
or pose.shape != (7,)
|
||||
or not np.isfinite(pose).all()
|
||||
or not math.isfinite(now)
|
||||
or (self.last_time is not None and now < self.last_time)
|
||||
):
|
||||
raise ValueError("Invalid causal range-memory observation")
|
||||
occupied = self.keys(points)
|
||||
images = None
|
||||
if range_views is not None and any(key in range_views for key in VIEW_FIELDS):
|
||||
if not all(key in range_views for key in VIEW_FIELDS):
|
||||
raise ValueError("Incomplete organized range packet")
|
||||
images = RangeImages(origins, range_views)
|
||||
free = (np.empty(0, dtype=np.int64) if images is not None else
|
||||
self.free_keys(origins, ends, origin_indices))
|
||||
before, removed = len(self.cells), 0
|
||||
if self.cells:
|
||||
keys = np.fromiter(self.cells, dtype=np.int64)
|
||||
cleared = (images.cleared([point for point, _ in self.cells.values()],
|
||||
self.voxel_m, self.endpoint_margin_m)
|
||||
if images is not None else np.isin(keys, free))
|
||||
for key in keys[cleared]:
|
||||
del self.cells[int(key)]
|
||||
removed += 1
|
||||
for key, point in zip(occupied, points, strict=True):
|
||||
# A row view would keep its entire source frame alive as long as
|
||||
# any one voxel survived, and permit later input mutation to alter
|
||||
# history. Each voxel owns only its three measured coordinates.
|
||||
self.cells[int(key)] = (point.copy(), now)
|
||||
# Do not allocate a NumPy vector in a Python loop for every retained
|
||||
# return on every frame. The same age/distance rule is vectorized.
|
||||
cell_keys = np.fromiter(self.cells, dtype=np.int64)
|
||||
observations = list(self.cells.values())
|
||||
retained_points = np.asarray([item[0] for item in observations], dtype=np.float64).reshape(-1, 3)
|
||||
seen = np.fromiter((item[1] for item in observations), dtype=float)
|
||||
expired = cell_keys[
|
||||
(now - seen > self.far_decay_seconds)
|
||||
& (np.hypot(retained_points[:, 0] - pose[0], retained_points[:, 1] - pose[1])
|
||||
>= self.near_memory_m)
|
||||
]
|
||||
for key in expired:
|
||||
del self.cells[int(key)]
|
||||
if len(self.cells) > self.maximum_cells:
|
||||
raise RuntimeError("Range memory capacity exceeded; refusing blind eviction")
|
||||
self.last_time = now
|
||||
self.metrics = {
|
||||
"cells_before": before,
|
||||
"cleared_by_rays": removed,
|
||||
"clearing_model": "projective-full-voxel/v1" if images is not None else "ray-voxel/v1",
|
||||
"expired_far_cells": len(expired),
|
||||
"retained_cells": len(self.cells),
|
||||
"observed_rays": 0 if ends is None else len(ends),
|
||||
}
|
||||
return np.asarray([point for point, _ in self.cells.values()], dtype=np.float32).reshape(
|
||||
-1, 3
|
||||
)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Add cost-aware free-space preference to the pinned CMU primitive selector."""
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def patch(source):
|
||||
if "missioncoreClearancePreference" in source:
|
||||
raise ValueError("Clearance preference already present")
|
||||
include = '#include "missioncore_footprint.hpp"'
|
||||
declaration = ' nh->declare_parameter<double>("vehicleWidth", vehicleWidth);'
|
||||
getter = ' nh->get_parameter("vehicleWidth", vehicleWidth);'
|
||||
edits = {
|
||||
include: '#include "missioncore_clearance.hpp"\ndouble footprintClearanceScale = 0;\n' + include,
|
||||
declaration: ' nh->declare_parameter<double>("footprintClearanceScale", footprintClearanceScale);\n' + declaration,
|
||||
getter: ' nh->get_parameter("footprintClearanceScale", footprintClearanceScale);\n' + getter,
|
||||
" maxScore = clearPathPerGroupScore[i];": ''' // Rank only candidates that passed the hard body veto above.
|
||||
// In blocked space evaluating the soft field for every rejected
|
||||
// primitive at every reduced range can starve the sensor lease.
|
||||
const double candidateScore = clearPathPerGroupScore[i] *
|
||||
missioncoreClearancePreference(*plannerFootprintCloud,
|
||||
*startPaths[i % groupNum], rotAng, pathScale,
|
||||
std::min(pathRange, relativeGoalDis), vehicleLength, vehicleWidth,
|
||||
obstacleHeightThre, footprintClearanceScale);
|
||||
if (candidateScore <= maxScore) continue;
|
||||
maxScore = candidateScore;''',
|
||||
}
|
||||
for anchor, replacement in edits.items():
|
||||
if source.count(anchor) != 1:
|
||||
raise ValueError("Unexpected pinned CMU clearance anchor: " + anchor)
|
||||
source = source.replace(anchor, replacement)
|
||||
return source
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
path = Path("/opt/cmu/src/local_planner/src/localPlanner.cpp")
|
||||
path.write_text(patch(path.read_text()))
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Opt-in world-frame paths for CMU's existing live-odometry path follower."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def patch(source):
|
||||
edits = {
|
||||
"bool pathInit = false;": "bool pathInit = false;\nbool pathInMapFrame = false;",
|
||||
' nh->declare_parameter<double>("lookAheadDis", lookAheadDis);':
|
||||
' nh->declare_parameter<bool>("pathInMapFrame", pathInMapFrame);\n'
|
||||
' nh->declare_parameter<double>("lookAheadDis", lookAheadDis);',
|
||||
' nh->get_parameter("lookAheadDis", lookAheadDis);':
|
||||
' nh->get_parameter("pathInMapFrame", pathInMapFrame);\n'
|
||||
' nh->get_parameter("lookAheadDis", lookAheadDis);',
|
||||
" vehicleXRec = vehicleX;": """ if (pathInMapFrame) {
|
||||
if (pathIn->header.frame_id != "map") { pathInit = false; return; }
|
||||
const double c = cos(vehicleYaw), s = sin(vehicleYaw);
|
||||
for (int i = 0; i < pathSize; i++) {
|
||||
const double x = path.poses[i].pose.position.x - vehicleX;
|
||||
const double y = path.poses[i].pose.position.y - vehicleY;
|
||||
path.poses[i].pose.position.x = c * x + s * y;
|
||||
path.poses[i].pose.position.y = -s * x + c * y;
|
||||
path.poses[i].pose.position.z -= vehicleZ;
|
||||
}
|
||||
}
|
||||
|
||||
vehicleXRec = vehicleX;""",
|
||||
}
|
||||
for anchor, replacement in edits.items():
|
||||
if source.count(anchor) != 1:
|
||||
raise ValueError("Unexpected pinned CMU continuous anchor: " + anchor)
|
||||
source = source.replace(anchor, replacement)
|
||||
return source
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
path = Path("/opt/cmu/src/local_planner/src/pathFollower.cpp")
|
||||
path.write_text(patch(path.read_text()))
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Preserve measured hazard positions for CMU's final primitive veto.
|
||||
|
||||
Voxel centroids remain useful for ranking primitives, but can move an obstacle
|
||||
away from a chassis corner. The selector and downstream guard must see the
|
||||
same unaveraged terrain snapshot. Laser-only mode and explicit boundaries keep
|
||||
their existing semantics.
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def patch(source):
|
||||
if "plannerFootprintCloud" in source:
|
||||
raise ValueError("Dense footprint patch already present")
|
||||
declaration = "pcl::VoxelGrid<pcl::PointXYZI> laserDwzFilter, terrainDwzFilter;"
|
||||
boundary = " int boundaryCloudSize = boundaryCloud->points.size();"
|
||||
selector = "missioncoreFootprintClear(*plannerCloudCrop, *startPaths[i % groupNum],"
|
||||
additions = """ if (dis < adjacentRange) {
|
||||
plannerCloudCrop->push_back(point);
|
||||
}"""
|
||||
for anchor, count in ((declaration, 1), (boundary, 1), (selector, 1), (additions, 2)):
|
||||
if source.count(anchor) != count:
|
||||
raise ValueError("Unexpected pinned CMU dense footprint anchor")
|
||||
source = source.replace(declaration, declaration + "\n"
|
||||
"pcl::PointCloud<pcl::PointXYZI>::Ptr plannerFootprintCloud(new pcl::PointCloud<pcl::PointXYZI>());")
|
||||
source = source.replace(boundary, """ // Use the same pose and raw terrain snapshot as the command guard.
|
||||
// Never average hazard positions or intensities for the body veto.
|
||||
plannerFootprintCloud->clear();
|
||||
if (useTerrainAnalysis) {
|
||||
for (const auto& raw : terrainCloudCrop->points) {
|
||||
const float dx = raw.x - vehicleX, dy = raw.y - vehicleY;
|
||||
point.x = dx * cosVehicleYaw + dy * sinVehicleYaw;
|
||||
point.y = -dx * sinVehicleYaw + dy * cosVehicleYaw;
|
||||
point.z = raw.z - vehicleZ;
|
||||
point.intensity = raw.intensity;
|
||||
if (std::hypot(point.x, point.y) < adjacentRange)
|
||||
plannerFootprintCloud->push_back(point);
|
||||
}
|
||||
} else {
|
||||
*plannerFootprintCloud = *plannerCloudCrop;
|
||||
}
|
||||
|
||||
""" + boundary)
|
||||
source = source.replace(additions, additions.replace(
|
||||
"plannerCloudCrop->push_back(point);", "plannerCloudCrop->push_back(point);\n"
|
||||
" plannerFootprintCloud->push_back(point);"))
|
||||
return source.replace(selector, selector.replace("*plannerCloudCrop", "*plannerFootprintCloud"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
path = Path("/opt/cmu/src/local_planner/src/localPlanner.cpp")
|
||||
path.write_text(patch(path.read_text()))
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Add acknowledged direction admission to the pinned CMU ROS nodes."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def patch(source, follower=False):
|
||||
anchor = ' nh->get_parameter("twoWayDrive", twoWayDrive);'
|
||||
if source.count(anchor) != 1:
|
||||
raise ValueError("Unexpected pinned CMU direction parameter")
|
||||
reset = (
|
||||
"navFwd = true; vehicleSpeed = 0; vehicleYawRate = 0; pathInit = false;" if follower else ""
|
||||
)
|
||||
callback = """
|
||||
auto directionPolicy = nh->add_on_set_parameters_callback(
|
||||
[](const std::vector<rclcpp::Parameter>& parameters) {
|
||||
rcl_interfaces::msg::SetParametersResult result;
|
||||
result.successful = true;
|
||||
for (const auto& parameter : parameters) {
|
||||
if (parameter.get_name() == "twoWayDrive") {
|
||||
if (parameter.get_type() != rclcpp::ParameterType::PARAMETER_BOOL) {
|
||||
result.successful = false;
|
||||
result.reason = "Direction permission must be boolean";
|
||||
return result;
|
||||
}
|
||||
twoWayDrive = parameter.as_bool();
|
||||
RESET
|
||||
}
|
||||
}
|
||||
return result;
|
||||
});
|
||||
""".replace("RESET", reset)
|
||||
return source.replace(anchor, anchor + callback)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
root = Path("/opt/cmu/src/local_planner/src")
|
||||
for name in ("localPlanner", "pathFollower"):
|
||||
path = root / f"{name}.cpp"
|
||||
path.write_text(patch(path.read_text(), name == "pathFollower"))
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user