diff --git a/source/isaaclab/changelog.d/sensor-update-period-float-drift.fixed.rst b/source/isaaclab/changelog.d/sensor-update-period-float-drift.fixed.rst new file mode 100644 index 000000000000..bc0c450a5446 --- /dev/null +++ b/source/isaaclab/changelog.d/sensor-update-period-float-drift.fixed.rst @@ -0,0 +1,10 @@ +* Fixed :class:`~isaaclab.sensors.SensorBase` refreshing sensors later than their ``update_period`` once the + sensor clock had run for some seconds. Whether a sensor is due was decided by subtracting two float32 + timestamps that grow with the episode, and their rounding error exceeded the ``1e-6`` tolerance, so sensors + with ``update_period`` set to a multiple of the physics time step skipped refreshes (for example, the height + scanner of the locomotion tasks from 16 s into an episode, and sensors with long update periods at small + time steps within the first second). The time since the last refresh is now accumulated in float64. + Existing timestamp buffers and Warp kernel signatures were preserved. Custom sensors that allocate or + replace their own timestamp buffers automatically acquire elapsed-time tracking on first use. + Built-in sensors use the new ``*_elapsed_kernel`` entry points; direct callers of the existing kernels + continue to work with their original timestamp-based timing behavior. diff --git a/source/isaaclab/isaaclab/sensors/contact_sensor/base_contact_sensor.py b/source/isaaclab/isaaclab/sensors/contact_sensor/base_contact_sensor.py index 736225ce1731..d5a618965198 100644 --- a/source/isaaclab/isaaclab/sensors/contact_sensor/base_contact_sensor.py +++ b/source/isaaclab/isaaclab/sensors/contact_sensor/base_contact_sensor.py @@ -149,8 +149,8 @@ def _resolve_first_transition_tolerance(self, abs_tol: float | None) -> float: Valid air and contact timers are integer multiples of the sensor update interval, so half an interval is the midpoint between "one update ago" and "two updates ago". Using it as the - tolerance keeps the comparison robust to the float32 rounding error of the sensor clock, - which grows with simulated time and quickly exceeds any fixed tolerance. + tolerance keeps the comparison robust to the float32 rounding of the timers, which exceeds + any small fixed tolerance for periods of a few tenths of a second. Args: abs_tol: The caller-provided tolerance [s]. If None, half the sensor update interval diff --git a/source/isaaclab/isaaclab/sensors/kernels.py b/source/isaaclab/isaaclab/sensors/kernels.py index 8488ec863655..8cbea2839f66 100644 --- a/source/isaaclab/isaaclab/sensors/kernels.py +++ b/source/isaaclab/isaaclab/sensors/kernels.py @@ -74,3 +74,95 @@ def reset_envs_kernel( timestamp_last_update[env] = 0.0 # Set all reset sensors to outdated so that they are updated when data is called the next time. is_outdated[env] = True + + +@wp.kernel +def update_timestamp_elapsed_kernel( + is_outdated: wp.array(dtype=wp.bool), + timestamp: wp.array(dtype=wp.float32), + elapsed_since_update: wp.array(dtype=wp.float64), + dt: wp.float64, + due_threshold: wp.float64, +): + """Advances the sensor clocks and marks environments as outdated if the update period elapsed. + + Due-ness is decided on the time elapsed since the last refresh, accumulated in float64 from zero. + Subtracting two float32 timestamps instead loses precision as the timestamps grow, which delays + refreshes once the episode has run for some seconds. + + Args: + is_outdated: Boolean array indicating which envs need update. + timestamp: Current timestamp per env [s]. + elapsed_since_update: Time since the last refresh per env [s]. + dt: Simulation time step [s]. + due_threshold: Elapsed time at which the sensor is due, ``update_period - 1e-6`` [s]. + """ + env = wp.tid() + timestamp[env] = timestamp[env] + wp.float32(dt) + elapsed = elapsed_since_update[env] + dt + elapsed_since_update[env] = elapsed + if elapsed >= due_threshold: + is_outdated[env] = True + + +@wp.kernel +def update_outdated_envs_elapsed_kernel( + is_outdated: wp.array(dtype=wp.bool), + timestamp: wp.array(dtype=wp.float32), + timestamp_last_update: wp.array(dtype=wp.float32), + elapsed_since_update: wp.array(dtype=wp.float64), +): + """Updates timestamp and clears outdated flag for outdated environments. + + Args: + is_outdated: Boolean array indicating which envs need update. Will be set to False. + timestamp: Current timestamp per env. + timestamp_last_update: Last update timestamp per env. Will be set to current timestamp. + elapsed_since_update: Time since the last refresh per env. Will be set to 0.0. + """ + env = wp.tid() + if is_outdated[env]: + timestamp_last_update[env] = timestamp[env] + elapsed_since_update[env] = wp.float64(0.0) + is_outdated[env] = False + + +@wp.kernel +def reset_envs_elapsed_kernel( + reset_mask: wp.array(dtype=wp.bool), + is_outdated: wp.array(dtype=wp.bool), + timestamp: wp.array(dtype=wp.float32), + timestamp_last_update: wp.array(dtype=wp.float32), + elapsed_since_update: wp.array(dtype=wp.float64), +): + """Resets the current and last update timestamps and marks environments as outdated for those being reset. + + Args: + reset_mask: Boolean array indicating which envs to reset. + is_outdated: Boolean array indicating which envs need update. Will be set to True for reset envs. + timestamp: Current timestamp per env. Will be set to 0.0 for reset envs. + timestamp_last_update: Last update timestamp per env. Will be set to 0.0 for reset envs. + elapsed_since_update: Time since the last refresh per env. Will be set to 0.0 for reset envs. + """ + env = wp.tid() + if not reset_mask[env]: + return + + # Reset the timestamp for the sensors + timestamp[env] = 0.0 + + timestamp_last_update[env] = 0.0 + elapsed_since_update[env] = wp.float64(0.0) + # Set all reset sensors to outdated so that they are updated when data is called the next time. + is_outdated[env] = True + + +@wp.kernel +def initialize_elapsed_time_kernel( + timestamp: wp.array(dtype=wp.float32), + timestamp_last_update: wp.array(dtype=wp.float32), + elapsed_since_update: wp.array(dtype=wp.float64), +): + """Initialize elapsed time from existing sensor timestamps when adopting timing buffers.""" + env = wp.tid() + elapsed_since_update[env] = wp.float64(timestamp[env]) - wp.float64(timestamp_last_update[env]) diff --git a/source/isaaclab/isaaclab/sensors/sensor_base.py b/source/isaaclab/isaaclab/sensors/sensor_base.py index 00e443fa4753..5c542011752f 100644 --- a/source/isaaclab/isaaclab/sensors/sensor_base.py +++ b/source/isaaclab/isaaclab/sensors/sensor_base.py @@ -29,7 +29,21 @@ from ..sim.utils.queries import get_first_matching_ancestor_prim from ..sim.utils.transforms import resolve_prim_pose from ..utils import index_fill_ -from .kernels import reset_envs_kernel, update_outdated_envs_kernel, update_timestamp_kernel +from .kernels import ( + initialize_elapsed_time_kernel, + reset_envs_elapsed_kernel, + update_outdated_envs_elapsed_kernel, + update_timestamp_elapsed_kernel, +) +from .kernels import ( + reset_envs_kernel as reset_envs_kernel, +) +from .kernels import ( + update_outdated_envs_kernel as update_outdated_envs_kernel, +) +from .kernels import ( + update_timestamp_kernel as update_timestamp_kernel, +) if TYPE_CHECKING: from .sensor_base_cfg import SensorBaseCfg @@ -48,6 +62,9 @@ class SensorBase(ABC): sensor is updated at every simulation step. """ + _elapsed_timestamp: wp.array | None = None + _elapsed_timestamp_last_update: wp.array | None = None + def __init__(self, cfg: SensorBaseCfg): """Initialize the sensor class. @@ -187,9 +204,15 @@ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None """ env_mask = self._resolve_indices_and_mask(env_ids, env_mask) wp.launch( - reset_envs_kernel, + reset_envs_elapsed_kernel, dim=self._num_envs, - inputs=[env_mask, self._is_outdated, self._timestamp, self._timestamp_last_update], + inputs=[ + env_mask, + self._is_outdated, + self._timestamp, + self._timestamp_last_update, + self._elapsed_since_update, + ], device=self._device, ) self._data_dirty = True @@ -201,9 +224,15 @@ def update(self, dt: float, force_recompute: bool = False): self._data_dirty = True # Update the timestamp for the sensors wp.launch( - update_timestamp_kernel, + update_timestamp_elapsed_kernel, dim=self._num_envs, - inputs=[self._is_outdated, self._timestamp, self._timestamp_last_update, dt, self.cfg.update_period], + inputs=[ + self._is_outdated, + self._timestamp, + self._elapsed_since_update, + dt, + self.cfg.update_period - 1e-6, + ], device=self._device, ) # Update the buffers; debug visualization refreshes lazily from its callback. @@ -265,10 +294,7 @@ def _initialize_impl(self): self._ALL_ENV_MASK = wp.ones((self._num_envs), dtype=wp.bool, device=self._device) self._reset_mask = wp.zeros((self._num_envs), dtype=wp.bool, device=self._device) self._reset_mask_torch = wp.to_torch(self._reset_mask) - # timestamp and outdated flags - self._is_outdated = wp.ones(self._num_envs, dtype=wp.bool, device=self._device) - self._timestamp = wp.zeros(self._num_envs, dtype=wp.float32, device=self._device) - self._timestamp_last_update = wp.zeros_like(self._timestamp) + self._create_timing_buffers() self._data_dirty = True # Initialize debug visualization handle @@ -418,6 +444,37 @@ def _clear_debug_vis_handle(self) -> None: Helper functions. """ + def _create_timing_buffers(self) -> None: + """Allocates the per-environment outdated flags, timestamps and elapsed times used to schedule updates. + + Sensors can call this again after changing :attr:`_num_envs` and reallocating their environment masks. + """ + # timestamp and outdated flags + self._is_outdated = wp.ones(self._num_envs, dtype=wp.bool, device=self._device) + self._timestamp = wp.zeros(self._num_envs, dtype=wp.float32, device=self._device) + self._timestamp_last_update = wp.zeros_like(self._timestamp) + self._elapsed_time_buffer = wp.zeros(self._num_envs, dtype=wp.float64, device=self._device) + self._elapsed_timestamp = self._timestamp + self._elapsed_timestamp_last_update = self._timestamp_last_update + + @property + def _elapsed_since_update(self) -> wp.array: + """Elapsed time since refresh, adopting timestamp buffers allocated by custom sensors.""" + if ( + self._elapsed_timestamp is not self._timestamp + or self._elapsed_timestamp_last_update is not self._timestamp_last_update + ): + self._elapsed_time_buffer = wp.empty(self._timestamp.shape, dtype=wp.float64, device=self._timestamp.device) + wp.launch( + initialize_elapsed_time_kernel, + dim=self._num_envs, + inputs=[self._timestamp, self._timestamp_last_update, self._elapsed_time_buffer], + device=self._device, + ) + self._elapsed_timestamp = self._timestamp + self._elapsed_timestamp_last_update = self._timestamp_last_update + return self._elapsed_time_buffer + def _update_outdated_buffers(self, force_recompute: bool = False) -> None: """Fills the sensor data for the outdated sensors.""" if not force_recompute and not self._data_dirty: @@ -429,9 +486,9 @@ def _mark_buffers_updated(self) -> None: """Commit capture timestamps after the sensor's output buffers have been filled.""" # update timestamps and clear outdated flags wp.launch( - update_outdated_envs_kernel, + update_outdated_envs_elapsed_kernel, dim=self._num_envs, - inputs=[self._is_outdated, self._timestamp, self._timestamp_last_update], + inputs=[self._is_outdated, self._timestamp, self._timestamp_last_update, self._elapsed_since_update], device=self._device, ) self._data_dirty = False diff --git a/source/isaaclab/test/renderers/test_simulation_render_context.py b/source/isaaclab/test/renderers/test_simulation_render_context.py index 1c4dba459ef1..7256e7e7a015 100644 --- a/source/isaaclab/test/renderers/test_simulation_render_context.py +++ b/source/isaaclab/test/renderers/test_simulation_render_context.py @@ -297,9 +297,7 @@ def __init__(self, renderer, name, update_period=0.0): self._frame = ProxyArray(wp.zeros(2, dtype=wp.int64, device="cpu")) self._ALL_INDICES = wp.array([0, 1], dtype=wp.int32, device="cpu") self._ALL_ENV_MASK = wp.ones(2, dtype=wp.bool, device="cpu") - self._is_outdated = wp.ones(2, dtype=wp.bool, device="cpu") - self._timestamp = wp.zeros(2, device="cpu") - self._timestamp_last_update = wp.zeros(2, device="cpu") + self._create_timing_buffers() self._data_dirty = True self.pose = 0.0 self._view = SimpleNamespace(count=2, xform_world_space_writer=self._pose_writer) @@ -329,9 +327,7 @@ def __init__(self, name, batches=None): self._num_envs = 2 self._is_initialized = True self._is_visualizing = False - self._is_outdated = wp.ones(2, dtype=wp.bool, device="cpu") - self._timestamp = wp.zeros(2, device="cpu") - self._timestamp_last_update = wp.zeros(2, device="cpu") + self._create_timing_buffers() self._data_dirty = True self._data = np.zeros(2, dtype=int) self.name = name diff --git a/source/isaaclab/test/sensors/test_contact_timing_kernels.py b/source/isaaclab/test/sensors/test_contact_timing_kernels.py new file mode 100644 index 000000000000..17d8f7226260 --- /dev/null +++ b/source/isaaclab/test/sensors/test_contact_timing_kernels.py @@ -0,0 +1,123 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Contact timing and compatibility of the backend-specific Warp kernel entry points.""" + +import numpy as np +import pytest +import warp as wp +from isaaclab_newton.sensors.contact_sensor import contact_sensor_kernels as newton_kernels +from isaaclab_ov.sensors.contact_sensor import kernels as ov_kernels +from isaaclab_physx.sensors.contact_sensor import kernels as physx_kernels + +from isaaclab.test.utils import DeviceScope, test_devices + +pytestmark = [pytest.mark.unit, pytest.mark.kitless] + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.CPU)) +@pytest.mark.parametrize("backend", ["physx", "ovphysx", "newton"]) +def test_contact_kernel_entry_points_preserve_timing_and_mask(backend, device): + """Old timestamp callers and new elapsed-time callers update forces and transitions correctly.""" + for use_elapsed in (False, True): + timestamp = wp.full(2, 8.25, dtype=wp.float32, device=device) + timing = ( + [wp.full(2, 0.02, dtype=wp.float64, device=device)] + if use_elapsed + else [timestamp, wp.full(2, 8.0, dtype=wp.float32, device=device)] + ) + mask = wp.array([True, False], dtype=wp.bool, device=device) + normal = wp.array([[(0.0, 0.0, 10.0)], [(0.0, 0.0, 20.0)]], dtype=wp.vec3f, device=device) + friction = wp.zeros((2, 1), dtype=wp.vec3f, device=device) + normal_history = wp.zeros((2, 2, 1), dtype=wp.vec3f, device=device) + total_history = wp.zeros_like(normal_history) + normal_output = wp.zeros_like(normal) + total_output = wp.zeros_like(normal) + air = wp.full((2, 1), 0.5, dtype=wp.float32, device=device) + contact = wp.zeros_like(air) + last_air = wp.full_like(air, -1.0) + last_contact = wp.full_like(air, -1.0) + + if backend == "newton": + kernel = ( + newton_kernels.update_contact_sensor_elapsed_kernel + if use_elapsed + else newton_kernels.update_contact_sensor_kernel + ) + inputs = [ + 2, + 0, + 1.0, + mask, + normal, + None, + normal, + None, + friction, + None, + *timing, + total_history, + None, + normal_history, + None, + None, + None, + air, + contact, + last_air, + last_contact, + ] + else: + if backend == "physx": + kernel = ( + physx_kernels.update_net_forces_elapsed_kernel + if use_elapsed + else physx_kernels.update_net_forces_kernel + ) + else: + kernel = ( + ov_kernels.update_net_forces_ovphysx_elapsed_kernel + if use_elapsed + else ov_kernels.update_net_forces_ovphysx_kernel + ) + inputs = [ + normal.flatten(), + friction.flatten(), + None, + None, + mask, + 2, + 0, + 2, + 1.0, + *([timestamp, *timing] if use_elapsed else timing), + normal_output, + normal_history, + None, + None, + air, + contact, + last_air, + last_contact, + total_output, + total_history, + None, + None, + None, + None, + None, + None, + ] + wp.launch(kernel, dim=(2, 1), inputs=inputs, device=device) + + dt = 0.02 if use_elapsed else 0.25 + np.testing.assert_allclose(contact.numpy(), [[dt], [0.0]], atol=1e-7, rtol=0) + np.testing.assert_allclose(last_air.numpy(), [[0.5 + dt], [-1.0]], atol=1e-7, rtol=0) + np.testing.assert_array_equal(air.numpy(), [[0.0], [0.5]]) + np.testing.assert_array_equal(last_contact.numpy(), [[-1.0], [-1.0]]) + expected_history = np.zeros((2, 2, 1, 3), dtype=np.float32) + expected_history[0, 0, 0, 2] = 10.0 + np.testing.assert_array_equal(normal_history.numpy(), expected_history) + np.testing.assert_array_equal(total_history.numpy(), expected_history) diff --git a/source/isaaclab/test/sensors/test_sensor_update_schedule.py b/source/isaaclab/test/sensors/test_sensor_update_schedule.py new file mode 100644 index 000000000000..34c119b857b3 --- /dev/null +++ b/source/isaaclab/test/sensors/test_sensor_update_schedule.py @@ -0,0 +1,149 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for when :class:`~isaaclab.sensors.SensorBase` refreshes its buffers. + +The per-env sensor clocks are float32, so the runs are long enough for their rounding error to exceed +the ``1e-6`` due tolerance. +""" + +from __future__ import annotations + +import numpy as np +import pytest +import warp as wp + +from isaaclab.sensors import SensorBase, SensorBaseCfg +from isaaclab.sensors.kernels import reset_envs_kernel, update_outdated_envs_kernel, update_timestamp_kernel +from isaaclab.test.utils import DeviceScope, test_devices + +pytestmark = [pytest.mark.unit, pytest.mark.kitless] + + +class _RefreshLogSensor(SensorBase): + """Sensor that records the step index of every buffer refresh, per environment.""" + + def __init__(self, update_period: float, device: str, num_envs: int = 2): + # SensorBase.__init__ needs a USD stage; only the timing state is under test here. + self.cfg = SensorBaseCfg(prim_path="/World/envs/env_.*/sensor", update_period=update_period) + self._device = device + self._num_envs = num_envs + self._is_initialized = True + self._is_visualizing = False + self._create_timing_buffers() + self._data_dirty = True + self.step = 0 + self.refreshes = [[] for _ in range(num_envs)] + + def __del__(self): + pass + + @property + def data(self): + self._update_outdated_buffers() + + def _initialize_impl(self): + pass + + def _update_buffers_impl(self, env_mask: wp.array): + for env in np.flatnonzero(env_mask.numpy()): + self.refreshes[env].append(self.step) + + +class _LegacyTimingSensor(_RefreshLogSensor): + """Custom sensor that allocates only the timing buffers available before this fix.""" + + def _create_timing_buffers(self): + self._is_outdated = wp.ones(self._num_envs, dtype=wp.bool, device=self._device) + self._timestamp = wp.zeros(self._num_envs, dtype=wp.float32, device=self._device) + self._timestamp_last_update = wp.zeros_like(self._timestamp) + + +def _run(sensor: _RefreshLogSensor, dts: list[float], read_every: int = 1) -> list[list[int]]: + """Calls ``update(dt)`` for each step and reads the data every ``read_every`` steps.""" + for step, dt in enumerate(dts, start=1): + sensor.update(dt) + if step % read_every == 0: + sensor.step = step + _ = sensor.data + return sensor.refreshes + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA)) +def test_refresh_cadence_holds_as_the_clock_ages(device): + """A 4-step period refreshes every 4 steps for 20 s (height scanner of the locomotion tasks).""" + sensor = _RefreshLogSensor(update_period=0.02, device=device) + refreshes = _run(sensor, [0.005] * 4000) + assert refreshes == [list(range(1, 4001, 4))] * 2 + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +def test_unread_sensor_stays_due_until_read(device): + """The period restarts at the read that refreshed the sensor, not on a fixed time grid.""" + # reads every 3 steps leave a 4-step sensor due and unread for 2 steps, so it refreshes every 6 steps + sensor = _RefreshLogSensor(update_period=0.02, device=device) + refreshes = _run(sensor, [0.005] * 4000, read_every=3) + assert refreshes == [list(range(3, 4001, 6))] * 2 + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +def test_refresh_follows_the_time_passed_to_update(device): + """The period is measured in the ``dt`` passed to each update, not in a number of updates.""" + sensor = _RefreshLogSensor(update_period=0.02, device=device) + refreshes = _run(sensor, [0.005, 0.015] * 2000) + assert refreshes == [list(range(1, 4001, 2))] * 2 + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.CPU)) +def test_custom_sensor_adopts_legacy_timing_buffers(device): + """Custom allocation, reset-before-update, lazy reads and replacement preserve refresh timing.""" + sensor = _LegacyTimingSensor(update_period=0.02, device=device) + mask = wp.ones(2, dtype=wp.bool, device=device) + sensor.reset(env_mask=mask) + assert _run(sensor, [0.005] * 5) == [[1, 5]] * 2 + + sensor.update(0.005) + sensor.reset(env_mask=wp.array([True, False], dtype=wp.bool, device=device)) + sensor.refreshes = [[], []] + assert _run(sensor, [0.005] * 3) == [[1], [3]] + + # Replace buffers at the same size, retaining time accumulated since a previous refresh. + sensor._timestamp = wp.full(2, 0.01, dtype=wp.float32, device=device) + sensor._timestamp_last_update = wp.zeros_like(sensor._timestamp) + sensor._is_outdated = wp.zeros(2, dtype=wp.bool, device=device) + sensor.refreshes = [[], []] + assert _run(sensor, [0.005] * 2) == [[2]] * 2 + + # Resize without calling the new SensorBase timing allocator, then read before stepping. + sensor._num_envs = 3 + sensor._create_timing_buffers() + sensor.refreshes = [[], [], []] + sensor.step = 0 + sensor._data_dirty = True + _ = sensor.data + assert _run(sensor, [0.005] * 4) == [[0, 4]] * 3 + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.CPU)) +def test_timestamp_kernel_signatures_remain_compatible(device): + """Direct callers can still advance, refresh and partially reset with float32 timestamp arrays.""" + outdated = wp.zeros(2, dtype=wp.bool, device=device) + timestamp = wp.array([1.0, 2.0], dtype=wp.float32, device=device) + last_update = wp.clone(timestamp) + for _ in range(2): + wp.launch(update_timestamp_kernel, dim=2, inputs=[outdated, timestamp, last_update, 0.005, 0.01], device=device) + np.testing.assert_array_equal(outdated.numpy(), [True, True]) + np.testing.assert_allclose(timestamp.numpy(), [1.01, 2.01], atol=1e-6, rtol=0) + np.testing.assert_array_equal(last_update.numpy(), [1.0, 2.0]) + + wp.launch(update_outdated_envs_kernel, dim=2, inputs=[outdated, timestamp, last_update], device=device) + np.testing.assert_array_equal(outdated.numpy(), [False, False]) + np.testing.assert_allclose(last_update.numpy(), [1.01, 2.01], atol=1e-6, rtol=0) + + mask = wp.array([True, False], dtype=wp.bool, device=device) + wp.launch(reset_envs_kernel, dim=2, inputs=[mask, outdated, timestamp, last_update], device=device) + np.testing.assert_array_equal(outdated.numpy(), [True, False]) + np.testing.assert_allclose(timestamp.numpy(), [0.0, 2.01], atol=1e-6, rtol=0) + np.testing.assert_allclose(last_update.numpy(), [0.0, 2.01], atol=1e-6, rtol=0) diff --git a/source/isaaclab_newton/changelog.d/sensor-update-period-float-drift.fixed.rst b/source/isaaclab_newton/changelog.d/sensor-update-period-float-drift.fixed.rst new file mode 100644 index 000000000000..a076dea51001 --- /dev/null +++ b/source/isaaclab_newton/changelog.d/sensor-update-period-float-drift.fixed.rst @@ -0,0 +1,3 @@ +* Fixed the air and contact times of :class:`~isaaclab_newton.sensors.ContactSensor` drifting with the age of the + sensor clock. Each refresh added the difference of two growing float32 timestamps, which was off by up to 8e-5 s + after 40 s of simulated time. It now adds the float64 time since the last refresh kept by the sensor base class. diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/contact_sensor/contact_sensor.py b/source/isaaclab_newton/isaaclab_newton/sensors/contact_sensor/contact_sensor.py index 307ffaff1bc7..1ea8d984c821 100644 --- a/source/isaaclab_newton/isaaclab_newton/sensors/contact_sensor/contact_sensor.py +++ b/source/isaaclab_newton/isaaclab_newton/sensors/contact_sensor/contact_sensor.py @@ -28,7 +28,10 @@ compute_first_transition_kernel, copy_from_newton_kernel, reset_contact_sensor_kernel, - update_contact_sensor_kernel, + update_contact_sensor_elapsed_kernel, +) +from .contact_sensor_kernels import ( + update_contact_sensor_kernel as update_contact_sensor_kernel, ) if TYPE_CHECKING: @@ -503,7 +506,7 @@ def _update_buffers_impl(self, env_mask: wp.array): # Update history and air/contact time tracking wp.launch( - update_contact_sensor_kernel, + update_contact_sensor_elapsed_kernel, dim=(self._num_envs, self._num_sensors), inputs=[ self._history_length, @@ -516,8 +519,7 @@ def _update_buffers_impl(self, env_mask: wp.array): self._data._normal_force_matrix_w, self._data._net_friction_forces_w, self._data._friction_force_matrix_w, - self._timestamp, - self._timestamp_last_update, + self._elapsed_since_update, self._data._net_forces_w_history, self._data._force_matrix_w_history, self._data._net_normal_forces_w_history, diff --git a/source/isaaclab_newton/isaaclab_newton/sensors/contact_sensor/contact_sensor_kernels.py b/source/isaaclab_newton/isaaclab_newton/sensors/contact_sensor/contact_sensor_kernels.py index f3e1d5dcf0bc..d73625730f5e 100644 --- a/source/isaaclab_newton/isaaclab_newton/sensors/contact_sensor/contact_sensor_kernels.py +++ b/source/isaaclab_newton/isaaclab_newton/sensors/contact_sensor/contact_sensor_kernels.py @@ -158,8 +158,10 @@ def reset_contact_sensor_kernel( last_contact_time[env, sensor] = 0.0 -@wp.kernel -def update_contact_sensor_kernel( +@wp.func +def _update_contact_sensor( + env: int, + sensor: int, # in history_length: int, num_filter_objects: int, @@ -171,8 +173,7 @@ def update_contact_sensor_kernel( normal_force_matrix: wp.array3d(dtype=wp.vec3f), net_friction_forces: wp.array2d(dtype=wp.vec3f), friction_force_matrix: wp.array3d(dtype=wp.vec3f), - timestamp: wp.array(dtype=wp.float32), - timestamp_last_update: wp.array(dtype=wp.float32), + elapsed_time: wp.float32, # in-out net_forces_history: wp.array3d(dtype=wp.vec3f), force_matrix_history: wp.array4d(dtype=wp.vec3f), @@ -186,11 +187,7 @@ def update_contact_sensor_kernel( last_air_time: wp.array2d(dtype=wp.float32), last_contact_time: wp.array2d(dtype=wp.float32), ): - """Update the contact sensor data (history and air/contact time tracking). - - Launch with dim=(num_envs, num_sensors). - """ - env, sensor = wp.tid() + """Update force buffers and advance contact timers by the supplied elapsed time.""" if env_mask: if not env_mask[env]: @@ -234,7 +231,6 @@ def update_contact_sensor_kernel( # Update air/contact time tracking from normal force magnitude. if current_air_time: - elapsed_time = timestamp[env] - timestamp_last_update[env] in_contact = wp.length_sq(net_normal_forces[env, sensor]) > contact_force_threshold * contact_force_threshold cat = current_air_time[env, sensor] @@ -251,6 +247,131 @@ def update_contact_sensor_kernel( current_air_time[env, sensor] = wp.where(in_contact, 0.0, cat + elapsed_time) +@wp.kernel +def update_contact_sensor_kernel( + # in + history_length: int, + num_filter_objects: int, + contact_force_threshold: wp.float32, + env_mask: wp.array(dtype=wp.bool), + net_forces: wp.array2d(dtype=wp.vec3f), + force_matrix: wp.array3d(dtype=wp.vec3f), + net_normal_forces: wp.array2d(dtype=wp.vec3f), + normal_force_matrix: wp.array3d(dtype=wp.vec3f), + net_friction_forces: wp.array2d(dtype=wp.vec3f), + friction_force_matrix: wp.array3d(dtype=wp.vec3f), + timestamp: wp.array(dtype=wp.float32), + timestamp_last_update: wp.array(dtype=wp.float32), + # in-out + net_forces_history: wp.array3d(dtype=wp.vec3f), + force_matrix_history: wp.array4d(dtype=wp.vec3f), + net_normal_forces_history: wp.array3d(dtype=wp.vec3f), + normal_force_matrix_history: wp.array4d(dtype=wp.vec3f), + net_friction_forces_history: wp.array3d(dtype=wp.vec3f), + friction_force_matrix_history: wp.array4d(dtype=wp.vec3f), + current_air_time: wp.array2d(dtype=wp.float32), + current_contact_time: wp.array2d(dtype=wp.float32), + # out + last_air_time: wp.array2d(dtype=wp.float32), + last_contact_time: wp.array2d(dtype=wp.float32), +): + """Update the contact sensor data (history and air/contact time tracking). + + Launch with dim=(num_envs, num_sensors). + """ + env, sensor = wp.tid() + elapsed_time = wp.float32(0.0) + if current_air_time: + elapsed_time = timestamp[env] - timestamp_last_update[env] + _update_contact_sensor( + env, + sensor, + history_length, + num_filter_objects, + contact_force_threshold, + env_mask, + net_forces, + force_matrix, + net_normal_forces, + normal_force_matrix, + net_friction_forces, + friction_force_matrix, + elapsed_time, + net_forces_history, + force_matrix_history, + net_normal_forces_history, + normal_force_matrix_history, + net_friction_forces_history, + friction_force_matrix_history, + current_air_time, + current_contact_time, + last_air_time, + last_contact_time, + ) + + +@wp.kernel +def update_contact_sensor_elapsed_kernel( + # in + history_length: int, + num_filter_objects: int, + contact_force_threshold: wp.float32, + env_mask: wp.array(dtype=wp.bool), + net_forces: wp.array2d(dtype=wp.vec3f), + force_matrix: wp.array3d(dtype=wp.vec3f), + net_normal_forces: wp.array2d(dtype=wp.vec3f), + normal_force_matrix: wp.array3d(dtype=wp.vec3f), + net_friction_forces: wp.array2d(dtype=wp.vec3f), + friction_force_matrix: wp.array3d(dtype=wp.vec3f), + elapsed_since_update: wp.array(dtype=wp.float64), + # in-out + net_forces_history: wp.array3d(dtype=wp.vec3f), + force_matrix_history: wp.array4d(dtype=wp.vec3f), + net_normal_forces_history: wp.array3d(dtype=wp.vec3f), + normal_force_matrix_history: wp.array4d(dtype=wp.vec3f), + net_friction_forces_history: wp.array3d(dtype=wp.vec3f), + friction_force_matrix_history: wp.array4d(dtype=wp.vec3f), + current_air_time: wp.array2d(dtype=wp.float32), + current_contact_time: wp.array2d(dtype=wp.float32), + # out + last_air_time: wp.array2d(dtype=wp.float32), + last_contact_time: wp.array2d(dtype=wp.float32), +): + """Update the contact sensor data (history and air/contact time tracking). + + Launch with dim=(num_envs, num_sensors). + """ + env, sensor = wp.tid() + elapsed_time = wp.float32(0.0) + if current_air_time: + elapsed_time = wp.float32(elapsed_since_update[env]) + _update_contact_sensor( + env, + sensor, + history_length, + num_filter_objects, + contact_force_threshold, + env_mask, + net_forces, + force_matrix, + net_normal_forces, + normal_force_matrix, + net_friction_forces, + friction_force_matrix, + elapsed_time, + net_forces_history, + force_matrix_history, + net_normal_forces_history, + normal_force_matrix_history, + net_friction_forces_history, + friction_force_matrix_history, + current_air_time, + current_contact_time, + last_air_time, + last_contact_time, + ) + + @wp.kernel def compute_first_transition_kernel( # in diff --git a/source/isaaclab_ov/changelog.d/sensor-update-period-float-drift.fixed.rst b/source/isaaclab_ov/changelog.d/sensor-update-period-float-drift.fixed.rst new file mode 100644 index 000000000000..7e42488d3ba0 --- /dev/null +++ b/source/isaaclab_ov/changelog.d/sensor-update-period-float-drift.fixed.rst @@ -0,0 +1,3 @@ +* Fixed the air and contact times of :class:`~isaaclab_ov.sensors.ContactSensor` drifting with the age of the + sensor clock. Each refresh added the difference of two growing float32 timestamps, which was off by up to 8e-5 s + after 40 s of simulated time. It now adds the float64 time since the last refresh kept by the sensor base class. diff --git a/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py b/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py index af9f92b1d464..ae26c7e27ff9 100644 --- a/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py +++ b/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py @@ -33,7 +33,10 @@ reset_contact_sensor_kernel, split_flat_pose_to_pos_quat, unpack_contact_buffer_data, - update_net_forces_ovphysx_kernel, + update_net_forces_ovphysx_elapsed_kernel, +) +from .kernels import ( + update_net_forces_ovphysx_kernel as update_net_forces_ovphysx_kernel, ) if TYPE_CHECKING: @@ -286,9 +289,7 @@ def has_contact_report(prim) -> bool: self._ALL_ENV_MASK = wp.ones((self._num_envs,), dtype=wp.bool, device=self._device) self._reset_mask = wp.zeros((self._num_envs,), dtype=wp.bool, device=self._device) self._reset_mask_torch = wp.to_torch(self._reset_mask) - self._is_outdated = wp.ones(self._num_envs, dtype=wp.bool, device=self._device) - self._timestamp = wp.zeros(self._num_envs, dtype=wp.float32, device=self._device) - self._timestamp_last_update = wp.zeros_like(self._timestamp) + self._create_timing_buffers() # Optional: pose tracking via a RIGID_BODY_POSE tensor binding. # ovphysx fnmatch does not brace-expand, so we cannot match multiple @@ -411,7 +412,7 @@ def _update_buffers_impl(self, env_mask: wp.array | None = None) -> None: friction_matrix_flat = None wp.launch( - update_net_forces_ovphysx_kernel, + update_net_forces_ovphysx_elapsed_kernel, dim=(self._num_envs, self._num_sensors), inputs=[ normal_forces_flat, @@ -424,7 +425,7 @@ def _update_buffers_impl(self, env_mask: wp.array | None = None) -> None: self._history_length, self.cfg.force_threshold, self._timestamp, - self._timestamp_last_update, + self._elapsed_since_update, ], outputs=[ self._data._net_normal_forces_w, diff --git a/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/kernels.py b/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/kernels.py index 79180259e4dd..816fef5e8553 100644 --- a/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/kernels.py +++ b/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/kernels.py @@ -209,8 +209,10 @@ def compute_first_transition_kernel( result[env, sensor] = 0.0 -@wp.kernel -def update_net_forces_ovphysx_kernel( +@wp.func +def _update_net_forces_ovphysx( + env: int, + sensor: int, # in normal_forces_flat: wp.array(dtype=wp.vec3f), friction_forces_flat: wp.array(dtype=wp.vec3f), @@ -222,7 +224,7 @@ def update_net_forces_ovphysx_kernel( history_length: int, contact_force_threshold: wp.float32, timestamp: wp.array(dtype=wp.float32), - timestamp_last_update: wp.array(dtype=wp.float32), + elapsed_time: wp.float32, # out net_normal_forces_w: wp.array2d(dtype=wp.vec3f), net_normal_forces_w_history: wp.array3d(dtype=wp.vec3f), @@ -241,51 +243,7 @@ def update_net_forces_ovphysx_kernel( friction_force_matrix_w: wp.array3d(dtype=wp.vec3f), friction_force_matrix_w_history: wp.array4d(dtype=wp.vec3f), ): - """Update the net forces, force matrix and air/contact time for each (env, sensor) pair. - - Launch with dim=(num_envs, num_sensors). - - The OVPhysX :class:`ContactBinding` returns sensors in **pattern-major** - order: the flat buffer index for ``(env, sensor)`` is - ``sensor * num_envs + env``, not the PhysX env-major - ``env * num_sensors + sensor``. We pass ``num_envs`` so the kernel can - compute the right index. - - Args: - normal_forces_flat: Flat net normal forces. Shape is (num_sensors*num_envs,) in pattern-major order. - friction_forces_flat: Flat net friction forces. Shape is (num_sensors*num_envs,) in pattern-major order. - normal_forces_matrix_flat: Flat normal force matrix. Shape is (num_sensors*num_envs, num_filter_shapes). - friction_forces_matrix_flat: Flat friction force matrix. Shape is (num_sensors*num_envs, num_filter_shapes). - mask: Mask array. Shape is (num_envs,). - num_envs: Number of environments. - num_filter_shapes: Number of filter shapes. - history_length: Length of history. - contact_force_threshold: Threshold for the contact force. - timestamp: Timestamp array. Shape is (num_envs,). - timestamp_last_update: Timestamp last update array. Shape is (num_envs,). - net_normal_forces_w: Net forces array. Shape is (num_envs, num_sensors). - net_normal_forces_w_history: Net forces history array. Shape is (num_envs, history_length, num_sensors). - normal_force_matrix_w: Force matrix array. Shape is (num_envs, num_sensors, num_filter_shapes). - normal_force_matrix_w_history: Force matrix history array. Shape is - (num_envs, history_length, num_sensors, num_filter_shapes). - current_air_time: Current air time array. Shape is (num_envs, num_sensors). - current_contact_time: Current contact time array. Shape is (num_envs, num_sensors). - last_air_time: Last air time array. Shape is (num_envs, num_sensors). - last_contact_time: Last contact time array. Shape is (num_envs, num_sensors). - net_forces_w: Total net forces array. Shape is (num_envs, num_sensors). - net_forces_w_history: Total net force history. Shape is (num_envs, history_length, num_sensors). - force_matrix_w: Total force matrix. Shape is (num_envs, num_sensors, num_filter_shapes). - force_matrix_w_history: Total force matrix history. Shape is - (num_envs, history_length, num_sensors, num_filter_shapes). - net_friction_forces_w: Optional net friction forces. Shape is (num_envs, num_sensors). - net_friction_forces_w_history: Optional net friction force history. Shape is - (num_envs, history_length, num_sensors). - friction_force_matrix_w: Optional friction force matrix. Shape is - (num_envs, num_sensors, num_filter_shapes). - friction_force_matrix_w_history: Optional friction force matrix history. Shape is - (num_envs, history_length, num_sensors, num_filter_shapes). - """ - env, sensor = wp.tid() + """Update force buffers and advance contact timers by the supplied elapsed time.""" if mask: if not mask[env]: @@ -334,7 +292,6 @@ def update_net_forces_ovphysx_kernel( # Update air/contact time tracking if current_air_time: - elapsed_time = timestamp[env] - timestamp_last_update[env] in_contact = wp.length_sq(net_normal_forces_w[env, sensor]) > contact_force_threshold * contact_force_threshold cat = current_air_time[env, sensor] @@ -351,6 +308,193 @@ def update_net_forces_ovphysx_kernel( current_air_time[env, sensor] = wp.where(in_contact, 0.0, cat + elapsed_time) +@wp.kernel +def update_net_forces_ovphysx_kernel( + # in + normal_forces_flat: wp.array(dtype=wp.vec3f), + friction_forces_flat: wp.array(dtype=wp.vec3f), + normal_forces_matrix_flat: wp.array2d(dtype=wp.vec3f), + friction_forces_matrix_flat: wp.array2d(dtype=wp.vec3f), + mask: wp.array(dtype=wp.bool), + num_envs: int, + num_filter_shapes: int, + history_length: int, + contact_force_threshold: wp.float32, + timestamp: wp.array(dtype=wp.float32), + timestamp_last_update: wp.array(dtype=wp.float32), + # out + net_normal_forces_w: wp.array2d(dtype=wp.vec3f), + net_normal_forces_w_history: wp.array3d(dtype=wp.vec3f), + normal_force_matrix_w: wp.array3d(dtype=wp.vec3f), + normal_force_matrix_w_history: wp.array4d(dtype=wp.vec3f), + current_air_time: wp.array2d(dtype=wp.float32), + current_contact_time: wp.array2d(dtype=wp.float32), + last_air_time: wp.array2d(dtype=wp.float32), + last_contact_time: wp.array2d(dtype=wp.float32), + net_forces_w: wp.array2d(dtype=wp.vec3f), + net_forces_w_history: wp.array3d(dtype=wp.vec3f), + force_matrix_w: wp.array3d(dtype=wp.vec3f), + force_matrix_w_history: wp.array4d(dtype=wp.vec3f), + net_friction_forces_w: wp.array2d(dtype=wp.vec3f), + net_friction_forces_w_history: wp.array3d(dtype=wp.vec3f), + friction_force_matrix_w: wp.array3d(dtype=wp.vec3f), + friction_force_matrix_w_history: wp.array4d(dtype=wp.vec3f), +): + """Update the net forces, force matrix and air/contact time for each (env, sensor) pair. + + Launch with dim=(num_envs, num_sensors). + + The OVPhysX :class:`ContactBinding` returns sensors in **pattern-major** + order: the flat buffer index for ``(env, sensor)`` is + ``sensor * num_envs + env``, not the PhysX env-major + ``env * num_sensors + sensor``. We pass ``num_envs`` so the kernel can + compute the right index. + + Args: + normal_forces_flat: Flat net normal forces. Shape is (num_sensors*num_envs,) in pattern-major order. + friction_forces_flat: Flat net friction forces. Shape is (num_sensors*num_envs,) in pattern-major order. + normal_forces_matrix_flat: Flat normal force matrix. Shape is (num_sensors*num_envs, num_filter_shapes). + friction_forces_matrix_flat: Flat friction force matrix. Shape is (num_sensors*num_envs, num_filter_shapes). + mask: Mask array. Shape is (num_envs,). + num_envs: Number of environments. + num_filter_shapes: Number of filter shapes. + history_length: Length of history. + contact_force_threshold: Threshold for the contact force. + timestamp: Timestamp array. Shape is (num_envs,). + timestamp_last_update: Timestamp last update array. Shape is (num_envs,). + net_normal_forces_w: Net forces array. Shape is (num_envs, num_sensors). + net_normal_forces_w_history: Net forces history array. Shape is (num_envs, history_length, num_sensors). + normal_force_matrix_w: Force matrix array. Shape is (num_envs, num_sensors, num_filter_shapes). + normal_force_matrix_w_history: Force matrix history array. Shape is + (num_envs, history_length, num_sensors, num_filter_shapes). + current_air_time: Current air time array. Shape is (num_envs, num_sensors). + current_contact_time: Current contact time array. Shape is (num_envs, num_sensors). + last_air_time: Last air time array. Shape is (num_envs, num_sensors). + last_contact_time: Last contact time array. Shape is (num_envs, num_sensors). + net_forces_w: Total net forces array. Shape is (num_envs, num_sensors). + net_forces_w_history: Total net force history. Shape is (num_envs, history_length, num_sensors). + force_matrix_w: Total force matrix. Shape is (num_envs, num_sensors, num_filter_shapes). + force_matrix_w_history: Total force matrix history. Shape is + (num_envs, history_length, num_sensors, num_filter_shapes). + net_friction_forces_w: Optional net friction forces. Shape is (num_envs, num_sensors). + net_friction_forces_w_history: Optional net friction force history. Shape is + (num_envs, history_length, num_sensors). + friction_force_matrix_w: Optional friction force matrix. Shape is + (num_envs, num_sensors, num_filter_shapes). + friction_force_matrix_w_history: Optional friction force matrix history. Shape is + (num_envs, history_length, num_sensors, num_filter_shapes). + """ + env, sensor = wp.tid() + elapsed_time = wp.float32(0.0) + if current_air_time: + elapsed_time = timestamp[env] - timestamp_last_update[env] + _update_net_forces_ovphysx( + env, + sensor, + normal_forces_flat, + friction_forces_flat, + normal_forces_matrix_flat, + friction_forces_matrix_flat, + mask, + num_envs, + num_filter_shapes, + history_length, + contact_force_threshold, + timestamp, + elapsed_time, + net_normal_forces_w, + net_normal_forces_w_history, + normal_force_matrix_w, + normal_force_matrix_w_history, + current_air_time, + current_contact_time, + last_air_time, + last_contact_time, + net_forces_w, + net_forces_w_history, + force_matrix_w, + force_matrix_w_history, + net_friction_forces_w, + net_friction_forces_w_history, + friction_force_matrix_w, + friction_force_matrix_w_history, + ) + + +@wp.kernel +def update_net_forces_ovphysx_elapsed_kernel( + # in + normal_forces_flat: wp.array(dtype=wp.vec3f), + friction_forces_flat: wp.array(dtype=wp.vec3f), + normal_forces_matrix_flat: wp.array2d(dtype=wp.vec3f), + friction_forces_matrix_flat: wp.array2d(dtype=wp.vec3f), + mask: wp.array(dtype=wp.bool), + num_envs: int, + num_filter_shapes: int, + history_length: int, + contact_force_threshold: wp.float32, + timestamp: wp.array(dtype=wp.float32), + elapsed_since_update: wp.array(dtype=wp.float64), + # out + net_normal_forces_w: wp.array2d(dtype=wp.vec3f), + net_normal_forces_w_history: wp.array3d(dtype=wp.vec3f), + normal_force_matrix_w: wp.array3d(dtype=wp.vec3f), + normal_force_matrix_w_history: wp.array4d(dtype=wp.vec3f), + current_air_time: wp.array2d(dtype=wp.float32), + current_contact_time: wp.array2d(dtype=wp.float32), + last_air_time: wp.array2d(dtype=wp.float32), + last_contact_time: wp.array2d(dtype=wp.float32), + net_forces_w: wp.array2d(dtype=wp.vec3f), + net_forces_w_history: wp.array3d(dtype=wp.vec3f), + force_matrix_w: wp.array3d(dtype=wp.vec3f), + force_matrix_w_history: wp.array4d(dtype=wp.vec3f), + net_friction_forces_w: wp.array2d(dtype=wp.vec3f), + net_friction_forces_w_history: wp.array3d(dtype=wp.vec3f), + friction_force_matrix_w: wp.array3d(dtype=wp.vec3f), + friction_force_matrix_w_history: wp.array4d(dtype=wp.vec3f), +): + """Update forces and contact timers using float64 elapsed time since the last refresh. + + Uses the force buffers and launch dimensions of the timestamp-based kernel, with + ``elapsed_since_update`` [s] replacing ``timestamp_last_update``. + """ + env, sensor = wp.tid() + elapsed_time = wp.float32(0.0) + if current_air_time: + elapsed_time = wp.float32(elapsed_since_update[env]) + _update_net_forces_ovphysx( + env, + sensor, + normal_forces_flat, + friction_forces_flat, + normal_forces_matrix_flat, + friction_forces_matrix_flat, + mask, + num_envs, + num_filter_shapes, + history_length, + contact_force_threshold, + timestamp, + elapsed_time, + net_normal_forces_w, + net_normal_forces_w_history, + normal_force_matrix_w, + normal_force_matrix_w_history, + current_air_time, + current_contact_time, + last_air_time, + last_contact_time, + net_forces_w, + net_forces_w_history, + force_matrix_w, + force_matrix_w_history, + net_friction_forces_w, + net_friction_forces_w_history, + friction_force_matrix_w, + friction_force_matrix_w_history, + ) + + @wp.kernel def concat_pos_and_quat_to_pose_kernel( pos: wp.array2d(dtype=wp.vec3f), diff --git a/source/isaaclab_ov/isaaclab_ov/sensors/frame_transformer/frame_transformer.py b/source/isaaclab_ov/isaaclab_ov/sensors/frame_transformer/frame_transformer.py index 2c8f583ad5a9..f8c82af50eca 100644 --- a/source/isaaclab_ov/isaaclab_ov/sensors/frame_transformer/frame_transformer.py +++ b/source/isaaclab_ov/isaaclab_ov/sensors/frame_transformer/frame_transformer.py @@ -273,9 +273,7 @@ def _initialize_impl(self) -> None: self._ALL_ENV_MASK = wp.ones((self._num_envs,), dtype=wp.bool, device=self._device) self._reset_mask = wp.zeros((self._num_envs,), dtype=wp.bool, device=self._device) self._reset_mask_torch = wp.to_torch(self._reset_mask) - self._is_outdated = wp.ones(self._num_envs, dtype=wp.bool, device=self._device) - self._timestamp = wp.zeros(self._num_envs, dtype=wp.float32, device=self._device) - self._timestamp_last_update = wp.zeros_like(self._timestamp) + self._create_timing_buffers() read_buf = wp.zeros(self._num_envs, dtype=wp.transformf, device=self._device) dst_torch = torch.tensor( diff --git a/source/isaaclab_ov/isaaclab_ov/sensors/joint_wrench/joint_wrench_sensor.py b/source/isaaclab_ov/isaaclab_ov/sensors/joint_wrench/joint_wrench_sensor.py index f5e1e62f0124..1706a528741e 100644 --- a/source/isaaclab_ov/isaaclab_ov/sensors/joint_wrench/joint_wrench_sensor.py +++ b/source/isaaclab_ov/isaaclab_ov/sensors/joint_wrench/joint_wrench_sensor.py @@ -151,9 +151,7 @@ def _initialize_impl(self) -> None: self._ALL_ENV_MASK = wp.ones((self._num_envs,), dtype=wp.bool, device=self._device) self._reset_mask = wp.zeros((self._num_envs,), dtype=wp.bool, device=self._device) self._reset_mask_torch = wp.to_torch(self._reset_mask) - self._is_outdated = wp.ones(self._num_envs, dtype=wp.bool, device=self._device) - self._timestamp = wp.zeros(self._num_envs, dtype=wp.float32, device=self._device) - self._timestamp_last_update = wp.zeros_like(self._timestamp) + self._create_timing_buffers() # Wrench storage as (N, L) spatial_vectorf, read each step via the view. The view # reinterprets this structured buffer off the binding's flat float32 shape and caches diff --git a/source/isaaclab_physx/changelog.d/sensor-update-period-float-drift.fixed.rst b/source/isaaclab_physx/changelog.d/sensor-update-period-float-drift.fixed.rst new file mode 100644 index 000000000000..51b0fcefd381 --- /dev/null +++ b/source/isaaclab_physx/changelog.d/sensor-update-period-float-drift.fixed.rst @@ -0,0 +1,3 @@ +* Fixed the air and contact times of :class:`~isaaclab_physx.sensors.ContactSensor` drifting with the age of the + sensor clock. Each refresh added the difference of two growing float32 timestamps, which was off by up to 8e-5 s + after 40 s of simulated time. It now adds the float64 time since the last refresh kept by the sensor base class. diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py b/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py index bcb2dccdf91a..42df63d2a3e3 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py @@ -35,7 +35,10 @@ split_flat_pose_to_pos_quat, unpack_contact_buffer_data, update_filtered_force_history_kernel, - update_net_forces_kernel, + update_net_forces_elapsed_kernel, +) +from .kernels import ( + update_net_forces_kernel as update_net_forces_kernel, ) if TYPE_CHECKING: @@ -619,7 +622,7 @@ def _compute(self) -> None: preallocated arrays (no allocations and no Python branching on GPU data). """ wp.launch( - update_net_forces_kernel, + update_net_forces_elapsed_kernel, dim=(self._num_envs, self._num_sensors), inputs=[ self._net_normal_forces_flat, @@ -632,7 +635,7 @@ def _compute(self) -> None: self._history_length, self.cfg.force_threshold, self._timestamp, - self._timestamp_last_update, + self._elapsed_since_update, ], outputs=[ self._data._net_normal_forces_w, diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/kernels.py b/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/kernels.py index 640ad2a21a86..507fd9f0a555 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/kernels.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/kernels.py @@ -248,8 +248,10 @@ def compute_first_transition_kernel( result[env, sensor] = 0.0 -@wp.kernel -def update_net_forces_kernel( +@wp.func +def _update_net_forces( + env: int, + sensor: int, # in normal_forces_flat: wp.array(dtype=wp.vec3f), friction_forces_flat: wp.array(dtype=wp.vec3f), @@ -261,7 +263,7 @@ def update_net_forces_kernel( history_length: int, contact_force_threshold: wp.float32, timestamp: wp.array(dtype=wp.float32), - timestamp_last_update: wp.array(dtype=wp.float32), + elapsed_time: wp.float32, # out net_normal_forces_w: wp.array2d(dtype=wp.vec3f), net_normal_forces_w_history: wp.array3d(dtype=wp.vec3f), @@ -280,50 +282,7 @@ def update_net_forces_kernel( friction_force_matrix_w: wp.array3d(dtype=wp.vec3f), friction_force_matrix_w_history: wp.array4d(dtype=wp.vec3f), ): - """Update the net forces, force matrix and air/contact time for each (env, sensor) pair. - - Launch with dim=(num_envs, num_sensors). The flat arrays are body-major (view created - from one pattern per body): ``src_idx = sensor_id * num_envs + env_id``. - - Args: - normal_forces_flat: Flat net normal forces. Shape is (num_sensors*num_envs,). - friction_forces_flat: Flat net friction forces. Shape is (num_sensors*num_envs,), or None - with Isaac Sim 6.1. - normal_forces_matrix_flat: Flat normal force matrix. Shape is - (num_sensors*num_envs, num_filter_shapes). - friction_forces_matrix_flat: Flat friction force matrix. Shape is - (num_sensors*num_envs, num_filter_shapes), or None with Isaac Sim 6.1. - mask: Mask array. Shape is (num_envs,). - num_envs: Number of environments. - num_filter_shapes: Number of filter shapes. - history_length: Length of history. - contact_force_threshold: Threshold for the contact force. - timestamp: Timestamp array. Shape is (num_envs,). - timestamp_last_update: Timestamp last update array. Shape is (num_envs,). - net_normal_forces_w: Net forces array. Shape is (num_envs, num_sensors). - net_normal_forces_w_history: Net forces history array. Shape is (num_envs, history_length, num_sensors). - normal_force_matrix_w: Force matrix array. Shape is (num_envs, num_sensors, num_filter_shapes). - normal_force_matrix_w_history: Force matrix history array. Shape is - (num_envs, history_length, num_sensors, num_filter_shapes). - current_air_time: Current air time array. Shape is (num_envs, num_sensors). - current_contact_time: Current contact time array. Shape is (num_envs, num_sensors). - last_air_time: Last air time array. Shape is (num_envs, num_sensors). - last_contact_time: Last contact time array. Shape is (num_envs, num_sensors). - net_forces_w: Optional total net forces array. Shape is (num_envs, num_sensors). - net_forces_w_history: Optional total net force history. Shape is - (num_envs, history_length, num_sensors). - force_matrix_w: Optional total force matrix. Shape is (num_envs, num_sensors, num_filter_shapes). - force_matrix_w_history: Optional total force matrix history. Shape is - (num_envs, history_length, num_sensors, num_filter_shapes). - net_friction_forces_w: Optional net friction forces. Shape is (num_envs, num_sensors). - net_friction_forces_w_history: Optional net friction force history. Shape is - (num_envs, history_length, num_sensors). - friction_force_matrix_w: Optional friction force matrix. Shape is - (num_envs, num_sensors, num_filter_shapes). - friction_force_matrix_w_history: Optional friction force matrix history. Shape is - (num_envs, history_length, num_sensors, num_filter_shapes). - """ - env, sensor = wp.tid() + """Update force buffers and advance contact timers by the supplied elapsed time.""" if mask: if not mask[env]: @@ -387,7 +346,6 @@ def update_net_forces_kernel( # Update air/contact time tracking if current_air_time: - elapsed_time = timestamp[env] - timestamp_last_update[env] in_contact = wp.length_sq(net_normal_forces_w[env, sensor]) > contact_force_threshold * contact_force_threshold cat = current_air_time[env, sensor] @@ -404,6 +362,192 @@ def update_net_forces_kernel( current_air_time[env, sensor] = wp.where(in_contact, 0.0, cat + elapsed_time) +@wp.kernel +def update_net_forces_kernel( + # in + normal_forces_flat: wp.array(dtype=wp.vec3f), + friction_forces_flat: wp.array(dtype=wp.vec3f), + normal_forces_matrix_flat: wp.array2d(dtype=wp.vec3f), + friction_forces_matrix_flat: wp.array2d(dtype=wp.vec3f), + mask: wp.array(dtype=wp.bool), + num_envs: int, + num_filter_shapes: int, + history_length: int, + contact_force_threshold: wp.float32, + timestamp: wp.array(dtype=wp.float32), + timestamp_last_update: wp.array(dtype=wp.float32), + # out + net_normal_forces_w: wp.array2d(dtype=wp.vec3f), + net_normal_forces_w_history: wp.array3d(dtype=wp.vec3f), + normal_force_matrix_w: wp.array3d(dtype=wp.vec3f), + normal_force_matrix_w_history: wp.array4d(dtype=wp.vec3f), + current_air_time: wp.array2d(dtype=wp.float32), + current_contact_time: wp.array2d(dtype=wp.float32), + last_air_time: wp.array2d(dtype=wp.float32), + last_contact_time: wp.array2d(dtype=wp.float32), + net_forces_w: wp.array2d(dtype=wp.vec3f), + net_forces_w_history: wp.array3d(dtype=wp.vec3f), + force_matrix_w: wp.array3d(dtype=wp.vec3f), + force_matrix_w_history: wp.array4d(dtype=wp.vec3f), + net_friction_forces_w: wp.array2d(dtype=wp.vec3f), + net_friction_forces_w_history: wp.array3d(dtype=wp.vec3f), + friction_force_matrix_w: wp.array3d(dtype=wp.vec3f), + friction_force_matrix_w_history: wp.array4d(dtype=wp.vec3f), +): + """Update the net forces, force matrix and air/contact time for each (env, sensor) pair. + + Launch with dim=(num_envs, num_sensors). The flat arrays are body-major (view created + from one pattern per body): ``src_idx = sensor_id * num_envs + env_id``. + + Args: + normal_forces_flat: Flat net normal forces. Shape is (num_sensors*num_envs,). + friction_forces_flat: Flat net friction forces. Shape is (num_sensors*num_envs,), or None + with Isaac Sim 6.1. + normal_forces_matrix_flat: Flat normal force matrix. Shape is + (num_sensors*num_envs, num_filter_shapes). + friction_forces_matrix_flat: Flat friction force matrix. Shape is + (num_sensors*num_envs, num_filter_shapes), or None with Isaac Sim 6.1. + mask: Mask array. Shape is (num_envs,). + num_envs: Number of environments. + num_filter_shapes: Number of filter shapes. + history_length: Length of history. + contact_force_threshold: Threshold for the contact force. + timestamp: Timestamp array. Shape is (num_envs,). + timestamp_last_update: Timestamp last update array. Shape is (num_envs,). + net_normal_forces_w: Net forces array. Shape is (num_envs, num_sensors). + net_normal_forces_w_history: Net forces history array. Shape is (num_envs, history_length, num_sensors). + normal_force_matrix_w: Force matrix array. Shape is (num_envs, num_sensors, num_filter_shapes). + normal_force_matrix_w_history: Force matrix history array. Shape is + (num_envs, history_length, num_sensors, num_filter_shapes). + current_air_time: Current air time array. Shape is (num_envs, num_sensors). + current_contact_time: Current contact time array. Shape is (num_envs, num_sensors). + last_air_time: Last air time array. Shape is (num_envs, num_sensors). + last_contact_time: Last contact time array. Shape is (num_envs, num_sensors). + net_forces_w: Optional total net forces array. Shape is (num_envs, num_sensors). + net_forces_w_history: Optional total net force history. Shape is + (num_envs, history_length, num_sensors). + force_matrix_w: Optional total force matrix. Shape is (num_envs, num_sensors, num_filter_shapes). + force_matrix_w_history: Optional total force matrix history. Shape is + (num_envs, history_length, num_sensors, num_filter_shapes). + net_friction_forces_w: Optional net friction forces. Shape is (num_envs, num_sensors). + net_friction_forces_w_history: Optional net friction force history. Shape is + (num_envs, history_length, num_sensors). + friction_force_matrix_w: Optional friction force matrix. Shape is + (num_envs, num_sensors, num_filter_shapes). + friction_force_matrix_w_history: Optional friction force matrix history. Shape is + (num_envs, history_length, num_sensors, num_filter_shapes). + """ + env, sensor = wp.tid() + elapsed_time = wp.float32(0.0) + if current_air_time: + elapsed_time = timestamp[env] - timestamp_last_update[env] + _update_net_forces( + env, + sensor, + normal_forces_flat, + friction_forces_flat, + normal_forces_matrix_flat, + friction_forces_matrix_flat, + mask, + num_envs, + num_filter_shapes, + history_length, + contact_force_threshold, + timestamp, + elapsed_time, + net_normal_forces_w, + net_normal_forces_w_history, + normal_force_matrix_w, + normal_force_matrix_w_history, + current_air_time, + current_contact_time, + last_air_time, + last_contact_time, + net_forces_w, + net_forces_w_history, + force_matrix_w, + force_matrix_w_history, + net_friction_forces_w, + net_friction_forces_w_history, + friction_force_matrix_w, + friction_force_matrix_w_history, + ) + + +@wp.kernel +def update_net_forces_elapsed_kernel( + # in + normal_forces_flat: wp.array(dtype=wp.vec3f), + friction_forces_flat: wp.array(dtype=wp.vec3f), + normal_forces_matrix_flat: wp.array2d(dtype=wp.vec3f), + friction_forces_matrix_flat: wp.array2d(dtype=wp.vec3f), + mask: wp.array(dtype=wp.bool), + num_envs: int, + num_filter_shapes: int, + history_length: int, + contact_force_threshold: wp.float32, + timestamp: wp.array(dtype=wp.float32), + elapsed_since_update: wp.array(dtype=wp.float64), + # out + net_normal_forces_w: wp.array2d(dtype=wp.vec3f), + net_normal_forces_w_history: wp.array3d(dtype=wp.vec3f), + normal_force_matrix_w: wp.array3d(dtype=wp.vec3f), + normal_force_matrix_w_history: wp.array4d(dtype=wp.vec3f), + current_air_time: wp.array2d(dtype=wp.float32), + current_contact_time: wp.array2d(dtype=wp.float32), + last_air_time: wp.array2d(dtype=wp.float32), + last_contact_time: wp.array2d(dtype=wp.float32), + net_forces_w: wp.array2d(dtype=wp.vec3f), + net_forces_w_history: wp.array3d(dtype=wp.vec3f), + force_matrix_w: wp.array3d(dtype=wp.vec3f), + force_matrix_w_history: wp.array4d(dtype=wp.vec3f), + net_friction_forces_w: wp.array2d(dtype=wp.vec3f), + net_friction_forces_w_history: wp.array3d(dtype=wp.vec3f), + friction_force_matrix_w: wp.array3d(dtype=wp.vec3f), + friction_force_matrix_w_history: wp.array4d(dtype=wp.vec3f), +): + """Update forces and contact timers using float64 elapsed time since the last refresh. + + Uses the force buffers and launch dimensions of the timestamp-based kernel, with + ``elapsed_since_update`` [s] replacing ``timestamp_last_update``. + """ + env, sensor = wp.tid() + elapsed_time = wp.float32(0.0) + if current_air_time: + elapsed_time = wp.float32(elapsed_since_update[env]) + _update_net_forces( + env, + sensor, + normal_forces_flat, + friction_forces_flat, + normal_forces_matrix_flat, + friction_forces_matrix_flat, + mask, + num_envs, + num_filter_shapes, + history_length, + contact_force_threshold, + timestamp, + elapsed_time, + net_normal_forces_w, + net_normal_forces_w_history, + normal_force_matrix_w, + normal_force_matrix_w_history, + current_air_time, + current_contact_time, + last_air_time, + last_contact_time, + net_forces_w, + net_forces_w_history, + force_matrix_w, + force_matrix_w_history, + net_friction_forces_w, + net_friction_forces_w_history, + friction_force_matrix_w, + friction_force_matrix_w_history, + ) + + @wp.kernel def concat_pos_and_quat_to_pose_kernel( pos: wp.array2d(dtype=wp.vec3f),