# Copyright (c) 2026, Nepher Robotics # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Map observations to a pi0.5 DROID policy and back to absolute joints.""" from __future__ import annotations import numpy as np IMAGE_HW = (224, 224) BATCH_SIZES = (1, 4, 16) """Row counts the model is compiled for. A call is padded up to the next one.""" def padded_rows(rows: int) -> int: """Return the compiled batch size that holds ``rows`` rows. The size depends only on ``rows``, so a row is always computed in the same program no matter how many calls the server has merged or in what order. Args: rows: Number of real rows, at most ``BATCH_SIZES[-1]``. """ for size in BATCH_SIZES: if rows <= size: return size raise ValueError(f"{rows} rows exceed the largest batch size {BATCH_SIZES[-1]}") def row_slices(rows: int) -> list[slice]: """Split ``rows`` into slices of at most ``BATCH_SIZES[-1]`` rows.""" limit = BATCH_SIZES[-1] return [slice(start, min(start + limit, rows)) for start in range(0, rows, limit)] def stack_padded(items: list, size: int): """Stack nested dicts of arrays on a new axis 0 and pad to ``size`` rows. Pad rows repeat the first row, so they never feed zeros or NaNs to the model. Args: items: One nested dict of arrays per row, all with the same structure. size: Row count after padding, at least ``len(items)``. """ if len(items) > size: raise ValueError(f"{len(items)} rows do not fit in a batch of {size}") padded = list(items) + [items[0]] * (size - len(items)) return _stack(padded) def _stack(items: list): first = items[0] if isinstance(first, dict): return {key: _stack([item[key] for item in items]) for key in first} return np.stack([np.asarray(item) for item in items], axis=0) def resize_with_pad(image: np.ndarray, height: int = IMAGE_HW[0], width: int = IMAGE_HW[1]) -> np.ndarray: """Resize one HWC image to ``height`` x ``width`` without stretching. Scale uniformly and pad the short side with zeros, matching ``openpi_client.image_tools.resize_with_pad``. An image that is already the target size is returned unchanged. Args: image: uint8 image, shape [H, W, C]. height: Target height [pixels]. width: Target width [pixels]. """ array = np.asarray(image) if array.shape[-3:-1] == (height, width): return array from PIL import Image if array.dtype != np.uint8: array = np.clip(array, 0, 255).astype(np.uint8) current_height, current_width = array.shape[0], array.shape[1] ratio = max(current_width / width, current_height / height) resized_height = int(current_height / ratio) resized_width = int(current_width / ratio) resized = Image.fromarray(array).resize((resized_width, resized_height), resample=Image.BILINEAR) canvas = Image.new(resized.mode, (width, height), 0) pad_height = max(0, int((height - resized_height) / 2)) pad_width = max(0, int((width - resized_width) / 2)) canvas.paste(resized, (pad_width, pad_height)) return np.asarray(canvas) def joint_chunk(actions: np.ndarray, horizon: int, *, offset: int = 0) -> np.ndarray: """Keep absolute joint targets [rad] and snap the gripper. The pi0.5 DROID joint-position config adds the observed joints back onto the first seven columns, so those values are already absolute. The eighth column is the gripper. A value above 0.5 closes it. Args: actions: Policy actions, shape [H, 8] or wider. horizon: Number of steps to keep. Returns: Actions, shape [horizon, 8]. The last column is 0 open or 1 closed. """ raw = np.asarray(actions, dtype=np.float32) if raw.ndim != 2 or raw.shape[0] < horizon or raw.shape[1] < 8: raise ValueError(f"expected at least {(horizon, 8)} actions, got {raw.shape}") if not 0 <= offset < horizon: raise ValueError(f"offset must be between 0 and {horizon - 1}") # Keep the advertised wire horizon after shifting the executable prefix. # The pinned evaluator consumes only the first eight rows. indices = np.minimum(np.arange(horizon) + offset, horizon - 1) chunk = raw[indices, :8] if not np.isfinite(chunk).all(): raise ValueError("the policy produced non-finite joint commands") chunk[..., -1] = (chunk[..., -1] > 0.5).astype(chunk.dtype) return chunk def blend_overlap( chunk: np.ndarray, previous: np.ndarray, previous_start: int, executed_steps: int, ) -> None: """Blend arm targets for the same future steps when both chunks agree on gripper state.""" overlap = min(executed_steps, previous.shape[1] - previous_start) if previous_start <= 0 or overlap <= 0: return old = previous[:, previous_start:previous_start + overlap, :8] new = chunk[:, :overlap, :] agree = (old[..., 7] > 0.5) == (new[..., 7] > 0.5) # Taper the old prediction's influence and preserve the new gripper command. taper = 0.5 * (1.0 - np.arange(overlap, dtype=np.float32) / overlap) weight = (agree * taper)[..., None] new[..., :7] += weight * (old[..., :7] - new[..., :7]) def committed_actions(previous, step: int, count: int, length: int) -> np.ndarray | None: """Return queued absolute commands starting at this observation timestamp.""" if previous is None or length == 0: return None start, sent = previous index = step - start if index < 0 or index + length > sent.shape[1] or sent.shape[0] != count: return None return sent[:, index:index + length].copy() def select_consistent(plans: np.ndarray, committed: np.ndarray, joint_scale: np.ndarray) -> np.ndarray: """Select one complete sampled trajectory per row by likelihood of its queued prefix.""" prefix = plans[:, :, :committed.shape[1], :8] arm_error = (prefix[..., :7] - committed[None, ..., :7]) / joint_scale # At contact, the temporal order of opening and closing is as important as one arm joint. grip_error = (np.clip(prefix[..., 7], 0, 1) - committed[None, ..., 7]) ** 2 distance = np.mean(np.square(arm_error), axis=-1) + grip_error best = np.argmin(distance.mean(axis=-1), axis=0) return plans[best, np.arange(plans.shape[1])] def normalized_prefix(commands, joints, lower, upper, delay, padded_dim): """Express queued absolute joint targets in this observation's DROID delta coordinates.""" count = len(joints) result = np.zeros((count, delay, padded_dim), dtype=np.float32) if commands is not None: delta = commands.copy() delta[..., :7] -= joints[:, None, :7] result[..., :8] = (delta - lower) / (upper - lower + 1e-6) * 2 - 1 result[..., 8] = 1 return result