Align Nav2 with physics time and preserve complete simulation scenes
This commit is contained in:
@@ -38,7 +38,17 @@ def main():
|
||||
state=dict(enabled=False,observation_id='bootstrap')
|
||||
responses=[];errors=[];running=threading.Event();running.set()
|
||||
|
||||
clock_started = time.monotonic()
|
||||
|
||||
def request(path,value=None):
|
||||
# Explicit synthetic clock for this isolated, stationary-odometry check.
|
||||
# Production obtains these fields only from completed physics steps.
|
||||
seconds = 10 + time.monotonic()-clock_started
|
||||
if path == '/control':
|
||||
value = {**value, 'pose_simulation_time_ns': round(seconds*1e9)}
|
||||
elif path == '/plan':
|
||||
value = {**value, 'simulation_time_seconds': seconds}
|
||||
|
||||
client=http.client.HTTPConnection('127.0.0.1',args.port,timeout=2)
|
||||
try:
|
||||
client.request('GET' if value is None else 'POST',path,
|
||||
|
||||
@@ -23,12 +23,14 @@ def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
for name in ('inputs', 'robot', 'output'):
|
||||
parser.add_argument('--' + name, type=Path, required=True)
|
||||
parser.add_argument('--simulation-clock', action='store_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()))
|
||||
config = configuration(json.loads(args.inputs.read_text()), json.loads(args.robot.read_text()),
|
||||
use_sim_time=args.simulation_clock)
|
||||
path = args.output/'parameters.yaml'; path.write_text(yaml.safe_dump(config, sort_keys=False))
|
||||
rclpy.init()
|
||||
fixture, bridge = Check(), RosNavigation()
|
||||
fixture, bridge = Check(), RosNavigation(simulation_clock=args.simulation_clock)
|
||||
measured = []
|
||||
fixture.create_subscription(Odometry, '/odom', lambda value: measured.append([
|
||||
value.twist.twist.linear.x, value.twist.twist.linear.y,
|
||||
@@ -42,10 +44,13 @@ def main():
|
||||
continuous_updates = threading.Event()
|
||||
continuity_samples = []
|
||||
|
||||
clock_started = time.monotonic()
|
||||
|
||||
def measurements():
|
||||
try:
|
||||
while running.is_set():
|
||||
bridge.observe_pose(pose, .01, [.03, -.005, .012])
|
||||
bridge.observe_pose(pose, .01, [.03, -.005, .012],
|
||||
round((10 + time.monotonic()-clock_started)*1e9) if args.simulation_clock else None)
|
||||
if continuous_updates.is_set():
|
||||
continuity_samples.append(bridge.native_command())
|
||||
time.sleep(.04)
|
||||
@@ -54,7 +59,7 @@ def main():
|
||||
|
||||
source = threading.Thread(target=measurements)
|
||||
processes, logs = [], []
|
||||
report = dict(qualified=False, scope='native ROS action/odometry integration', passed=False)
|
||||
report = dict(simulation_clock=args.simulation_clock, 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
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Real ROS clock/odometry check; synthetic measurements, no actuator authority."""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import rclpy
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.executors import MultiThreadedExecutor
|
||||
from rclpy.node import Node
|
||||
from rclpy.parameter import Parameter
|
||||
from ros_navigation import RosNavigation
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
rclpy.init()
|
||||
bridge = RosNavigation(simulation_clock=True)
|
||||
observer = Node('clock_check', parameter_overrides=[Parameter('use_sim_time', value=True)])
|
||||
rows = []
|
||||
observer.create_subscription(Odometry, '/odom', lambda m: rows.append(dict(
|
||||
stamp=m.header.stamp.sec*10**9+m.header.stamp.nanosec,
|
||||
x=m.pose.pose.position.x, vx=m.twist.twist.linear.x)), 20)
|
||||
executor = MultiThreadedExecutor(num_threads=2)
|
||||
executor.add_node(bridge); executor.add_node(observer)
|
||||
spinner = threading.Thread(target=executor.spin); spinner.start()
|
||||
report = dict(passed=False, qualified=False, scope='ROS timestamps at variable pacing and pause')
|
||||
stamp = 10_000_000_000
|
||||
try:
|
||||
time.sleep(.3)
|
||||
for rate in (.4, 1., 2.):
|
||||
for _ in range(12):
|
||||
stamp += 50_000_000
|
||||
bridge.observe_pose([.4*stamp/1e9, 0., .37, 0., 0., 0., 1.], .013,
|
||||
[.4, 0., 0.], stamp)
|
||||
time.sleep(.05/rate)
|
||||
time.sleep(.1)
|
||||
assert observer.get_clock().now().nanoseconds == stamp
|
||||
# Late delivery must not rewind the source clock or renew old odometry.
|
||||
before = bridge.pose
|
||||
bridge.observe_pose([0.,0.,.37,0.,0.,0.,1.], 0., [.4,0.,0.], stamp-1)
|
||||
assert bridge.pose == before
|
||||
paused = observer.get_clock().now().nanoseconds
|
||||
time.sleep(.65)
|
||||
assert observer.get_clock().now().nanoseconds == paused
|
||||
count = len(rows); bridge.publish_pose(); time.sleep(.1)
|
||||
assert len(rows) == count, 'Wall-stale measurement was republished at frozen sim time'
|
||||
unique = {r['stamp']: r for r in rows}
|
||||
ordered = [unique[k] for k in sorted(unique)]
|
||||
assert len(ordered) >= 30
|
||||
residuals = [abs((b['x']-a['x'])/((b['stamp']-a['stamp'])/1e9)-a['vx'])
|
||||
for a,b in zip(ordered, ordered[1:])]
|
||||
assert max(residuals) < 1e-10
|
||||
assert all(math.isfinite(r['x']) for r in ordered)
|
||||
sample = bridge.observation_stamp(10.5, .9)
|
||||
assert sample.sec*10**9+sample.nanosec == 10_500_000_000
|
||||
try:
|
||||
bridge.observe_pose([0.,0.,.37,0.,0.,0.,1.], 0., [0.,0.,0.])
|
||||
raise AssertionError('Missing physics time was accepted')
|
||||
except ValueError:
|
||||
pass
|
||||
report.update(passed=True, unique_measurements=len(ordered), pacing_factors=[.4,1.,2.],
|
||||
maximum_velocity_stamp_residual=max(residuals), pause_preserved=True,
|
||||
stale_pose_expired_by_wall_time=True, source_stamp_preserved=True)
|
||||
except BaseException as error:
|
||||
report['error'] = type(error).__name__+': '+str(error)
|
||||
raise
|
||||
finally:
|
||||
executor.shutdown(timeout_sec=2); spinner.join(timeout=2)
|
||||
bridge.destroy_node(); observer.destroy_node(); rclpy.shutdown()
|
||||
(args.output/'result.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -15,7 +15,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from rig_collision import collision_geometry # noqa: E402
|
||||
|
||||
|
||||
def configuration(inputs, robot):
|
||||
def configuration(inputs, robot, *, use_sim_time=False):
|
||||
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()
|
||||
@@ -36,7 +36,7 @@ def configuration(inputs, robot):
|
||||
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',
|
||||
use_sim_time=use_sim_time, 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,
|
||||
@@ -61,7 +61,7 @@ def configuration(inputs, robot):
|
||||
heading_bins = max(8, 4 * math.ceil((2 * math.pi / angle_step) / 4))
|
||||
return {
|
||||
'behavior_server': {'ros__parameters': dict(
|
||||
use_sim_time=False, global_frame='map', robot_base_frame='base_link',
|
||||
use_sim_time=use_sim_time, 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,
|
||||
@@ -73,7 +73,7 @@ def configuration(inputs, robot):
|
||||
rotational_acc_lim=2*acceleration/track_width,
|
||||
)},
|
||||
'planner_server': {'ros__parameters': dict(
|
||||
use_sim_time=False, expected_planner_frequency=5.0, planner_plugins=['GridBased'],
|
||||
use_sim_time=use_sim_time, expected_planner_frequency=5.0, planner_plugins=['GridBased'],
|
||||
GridBased=dict(plugin='nav2_smac_planner/SmacPlannerHybrid',
|
||||
motion_model_for_search='DUBIN',
|
||||
# Retain the former differential lattice's 0.5 m
|
||||
@@ -85,7 +85,7 @@ def configuration(inputs, robot):
|
||||
cache_obstacle_heuristic=False, smooth_path=False),
|
||||
)},
|
||||
'controller_server': {'ros__parameters': dict(
|
||||
use_sim_time=False, controller_frequency=20.0, odom_topic='/odom',
|
||||
use_sim_time=use_sim_time, 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'],
|
||||
@@ -143,7 +143,7 @@ def configuration(inputs, robot):
|
||||
}
|
||||
|
||||
|
||||
def observed_configuration(inputs, robot, origin_count):
|
||||
def observed_configuration(inputs, robot, origin_count, *, use_sim_time=False):
|
||||
"""Use upstream ray clearing/obstacle marking for a rolling collision map.
|
||||
|
||||
Ground support and surface permission are separate inputs/gates. In
|
||||
@@ -151,7 +151,7 @@ def observed_configuration(inputs, robot, origin_count):
|
||||
"""
|
||||
if type(origin_count) is not int or not 1 <= origin_count <= 16:
|
||||
raise ValueError('Invalid observed sensor origin count')
|
||||
config = configuration(inputs, robot)
|
||||
config = configuration(inputs, robot, use_sim_time=use_sim_time)
|
||||
sources = {
|
||||
'hazards': dict(topic='/observed_hazards', data_type='PointCloud2',
|
||||
sensor_frame='base_link', marking=True, clearing=False,
|
||||
|
||||
@@ -9,7 +9,6 @@ import struct
|
||||
import numpy as np
|
||||
from detector_exclusion import DetectorExclusion
|
||||
from geometry_msgs.msg import TransformStamped
|
||||
from rclpy.time import Time
|
||||
from sensor_msgs.msg import PointCloud2, PointField
|
||||
|
||||
|
||||
@@ -41,7 +40,7 @@ class ObservedCollision:
|
||||
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()
|
||||
stamp = self.node.observation_stamp(request['simulation_time_seconds'], age)
|
||||
transforms=[]
|
||||
for i, origin in enumerate(rays['origins']):
|
||||
tf = TransformStamped()
|
||||
|
||||
@@ -20,6 +20,8 @@ from nav2_msgs.msg import Costmap
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.action import ActionClient
|
||||
from rclpy.node import Node
|
||||
from rclpy.parameter import Parameter
|
||||
from rosgraph_msgs.msg import Clock
|
||||
from rclpy.time import Time
|
||||
from tf2_ros import TransformBroadcaster
|
||||
|
||||
@@ -30,8 +32,11 @@ def yaw_of(pose):
|
||||
|
||||
|
||||
class RosNavigation(Node):
|
||||
def __init__(self):
|
||||
super().__init__('missioncore_nav2_adapter')
|
||||
def __init__(self, *, simulation_clock=False):
|
||||
super().__init__('missioncore_nav2_adapter', parameter_overrides=[
|
||||
Parameter('use_sim_time', value=simulation_clock)])
|
||||
self.simulation_clock = simulation_clock
|
||||
self.clock_publisher = self.create_publisher(Clock, '/clock', 1) if simulation_clock else None
|
||||
self.condition = threading.Condition()
|
||||
self.action_lock = threading.Lock()
|
||||
self.pose = None
|
||||
@@ -100,21 +105,38 @@ class RosNavigation(Node):
|
||||
if not client.wait_for_server(timeout_sec=2):
|
||||
raise TimeoutError('Nav2 action unavailable')
|
||||
|
||||
def observe_pose(self, pose, age, twist=None):
|
||||
def observe_pose(self, pose, age, twist=None, simulation_time_ns=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 self.simulation_clock:
|
||||
if type(simulation_time_ns) is not int or not 0 <= simulation_time_ns < 2**63:
|
||||
raise ValueError('Measured simulation time is required for odometry')
|
||||
stamp = simulation_time_ns
|
||||
else:
|
||||
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)
|
||||
if self.pose is not None and (captured < self.pose[0] or stamp < self.pose[3]):
|
||||
return # Delayed delivery cannot rewind TF or the episode clock.
|
||||
self.pose = (captured, tuple(pose), tuple(twist) if twist is not None else None, stamp)
|
||||
if self.clock_publisher is not None:
|
||||
# Physics owns time. Repeated measurements at pause never advance
|
||||
# it; HTTP age and all transport/action waits remain wall time.
|
||||
self.clock_publisher.publish(Clock(clock=Time(nanoseconds=stamp).to_msg()))
|
||||
self.publish_pose()
|
||||
|
||||
def observation_stamp(self, seconds, wall_age):
|
||||
if self.simulation_clock:
|
||||
if not math.isfinite(seconds) or seconds < 0:
|
||||
raise ValueError('Invalid observed simulation time')
|
||||
return Time(nanoseconds=round(seconds*1e9)).to_msg()
|
||||
return Time(nanoseconds=self.get_clock().now().nanoseconds-int(wall_age*1e9)).to_msg()
|
||||
|
||||
def publish_pose(self):
|
||||
with self.condition:
|
||||
measured = self.pose
|
||||
|
||||
@@ -75,7 +75,8 @@ class Navigation:
|
||||
return self.node.native_command()
|
||||
|
||||
def tick(self, value):
|
||||
self.node.observe_pose(value['pose'], float(value['pose_age_seconds']), value['measured_twist'])
|
||||
self.node.observe_pose(value['pose'], float(value['pose_age_seconds']), value['measured_twist'],
|
||||
value.get('pose_simulation_time_ns'))
|
||||
with self.owner_lock:
|
||||
owner = self.command_generation
|
||||
result = self.control.tick(value)
|
||||
@@ -149,7 +150,8 @@ class Navigation:
|
||||
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.
|
||||
self.node.observe_pose(value['pose'], age, None,
|
||||
round(value['simulation_time_seconds']*1e9)) # TF only.
|
||||
if not self.activating:
|
||||
self.activating = True
|
||||
threading.Thread(target=self.activate, daemon=True).start()
|
||||
@@ -321,11 +323,11 @@ 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.
|
||||
config = observed_configuration(inputs, robot, 2, use_sim_time=True) # 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()
|
||||
node = RosNavigation(simulation_clock=True)
|
||||
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')
|
||||
|
||||
Reference in New Issue
Block a user