|
4 | 4 | from __future__ import annotations |
5 | 5 |
|
6 | 6 | import warnings |
7 | | -from dataclasses import dataclass |
| 7 | +from dataclasses import dataclass, fields |
8 | 8 | from typing import Any |
9 | 9 |
|
10 | 10 | import numpy as np |
@@ -42,6 +42,78 @@ def _scatter_add_kernel( |
42 | 42 | computed_output[idx] = computed_output[idx] + computed_forces[i] |
43 | 43 |
|
44 | 44 |
|
| 45 | +def _assign_state_value(dst: Any, src: Any, name: str) -> None: |
| 46 | + """Copy a supported state value without replacing its storage.""" |
| 47 | + if dst is None and src is None: |
| 48 | + return |
| 49 | + if dst is None or src is None: |
| 50 | + raise ValueError(f"Cannot assign '{name}': present in one state and missing in the other.") |
| 51 | + |
| 52 | + dst_is_warp = isinstance(dst, wp.array) |
| 53 | + src_is_warp = isinstance(src, wp.array) |
| 54 | + if dst_is_warp or src_is_warp: |
| 55 | + if not (dst_is_warp and src_is_warp): |
| 56 | + raise ValueError(f"Cannot assign '{name}': a Warp array in one state and not in the other.") |
| 57 | + dst.assign(src) |
| 58 | + return |
| 59 | + |
| 60 | + dst_is_torch = type(dst).__module__.startswith("torch") |
| 61 | + src_is_torch = type(src).__module__.startswith("torch") |
| 62 | + if dst_is_torch or src_is_torch: |
| 63 | + if not (dst_is_torch and src_is_torch): |
| 64 | + raise ValueError(f"Cannot assign '{name}': a Torch tensor in one state and not in the other.") |
| 65 | + if dst.shape != src.shape: |
| 66 | + raise ValueError(f"Cannot assign '{name}': tensor shapes differ ({dst.shape} and {src.shape}).") |
| 67 | + import torch |
| 68 | + |
| 69 | + with torch.inference_mode(): |
| 70 | + dst.copy_(src) |
| 71 | + return |
| 72 | + |
| 73 | + raise ValueError(f"Cannot assign '{name}': expected Warp arrays or Torch tensors.") |
| 74 | + |
| 75 | + |
| 76 | +def _assign_component_state(dst: Any, src: Any, name: str) -> None: |
| 77 | + """Copy one actuator component state from *src* into *dst*. |
| 78 | +
|
| 79 | + Args: |
| 80 | + dst: Component state to copy into. |
| 81 | + src: Component state to copy from. |
| 82 | + name: Component name, used in error messages. |
| 83 | +
|
| 84 | + Raises: |
| 85 | + ValueError: The two actuator states have incompatible components or |
| 86 | + fields. |
| 87 | + NotImplementedError: A custom state is not a dataclass and does not |
| 88 | + implement ``assign()``. |
| 89 | + """ |
| 90 | + if dst is None and src is None: |
| 91 | + return |
| 92 | + if dst is None or src is None: |
| 93 | + raise ValueError(f"Cannot assign '{name}': one state has it allocated and the other does not.") |
| 94 | + if type(dst) is not type(src): |
| 95 | + raise ValueError(f"Cannot assign '{name}': state types differ ({type(dst).__name__} and {type(src).__name__}).") |
| 96 | + |
| 97 | + custom_assign = getattr(dst, "assign", None) |
| 98 | + if custom_assign is not None: |
| 99 | + custom_assign(src) |
| 100 | + return |
| 101 | + |
| 102 | + if "__dataclass_fields__" not in type(dst).__dict__: |
| 103 | + raise NotImplementedError(f"{type(dst).__qualname__} must be decorated with @dataclass or implement assign") |
| 104 | + |
| 105 | + state_fields = fields(dst) |
| 106 | + field_names = {field.name for field in state_fields} |
| 107 | + attributes = set(getattr(dst, "__dict__", ())) | set(getattr(src, "__dict__", ())) |
| 108 | + undeclared = attributes - field_names |
| 109 | + if undeclared: |
| 110 | + names = ", ".join(sorted(undeclared)) |
| 111 | + raise ValueError(f"Cannot assign '{name}': undeclared state attributes: {names}.") |
| 112 | + |
| 113 | + for field in state_fields: |
| 114 | + _assign_state_value(getattr(dst, field.name), getattr(src, field.name), f"{name}.{field.name}") |
| 115 | + |
| 116 | + |
45 | 117 | class Actuator: |
46 | 118 | """Composed actuator: delay → drive → clamping. |
47 | 119 |
|
@@ -130,6 +202,33 @@ def reset(self, mask: wp.array[wp.bool] | None = None) -> None: |
130 | 202 | if self.drive_state is not None: |
131 | 203 | self.drive_state.reset(mask) |
132 | 204 |
|
| 205 | + def assign(self, other: Actuator.State) -> None: |
| 206 | + """Copy the state held by *other* into this one. |
| 207 | +
|
| 208 | + A CUDA graph records buffer addresses rather than the caller's |
| 209 | + Python names. Assigning at the boundary of an odd-length captured |
| 210 | + region, in place of its final state swap, preserves the advanced |
| 211 | + state for the next replay:: |
| 212 | +
|
| 213 | + for i in range(steps): |
| 214 | + control.joint_f.zero_() |
| 215 | + actuator.step(state, control, state_0, state_1, dt=0.01) |
| 216 | + if steps % 2 == 1 and i == steps - 1: |
| 217 | + state_0.assign(state_1) |
| 218 | + else: |
| 219 | + state_0, state_1 = state_1, state_0 |
| 220 | +
|
| 221 | + Args: |
| 222 | + other: State to copy from. |
| 223 | +
|
| 224 | + Raises: |
| 225 | + ValueError: The two states do not hold the same components. |
| 226 | + NotImplementedError: A custom state does not implement |
| 227 | + assignment. |
| 228 | + """ |
| 229 | + _assign_component_state(self.delay_state, other.delay_state, "delay_state") |
| 230 | + _assign_component_state(self.drive_state, other.drive_state, "drive_state") |
| 231 | + |
133 | 232 | def __init__( |
134 | 233 | self, |
135 | 234 | indices: wp.array[wp.uint32], |
|
0 commit comments