motrix-env-core 0.4.0b0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. motrix_env_core/__init__.py +52 -0
  2. motrix_env_core/array/__init__.py +3 -0
  3. motrix_env_core/array/env.py +330 -0
  4. motrix_env_core/array_api.py +41 -0
  5. motrix_env_core/base.py +99 -0
  6. motrix_env_core/config/__init__.py +8 -0
  7. motrix_env_core/config/decorate.py +141 -0
  8. motrix_env_core/config/scene/__init__.py +114 -0
  9. motrix_env_core/config/scene/_utils.py +24 -0
  10. motrix_env_core/config/scene/actuator.py +47 -0
  11. motrix_env_core/config/scene/asset.py +183 -0
  12. motrix_env_core/config/scene/base.py +338 -0
  13. motrix_env_core/config/scene/compiler.py +18 -0
  14. motrix_env_core/config/scene/geometry.py +43 -0
  15. motrix_env_core/config/scene/light.py +25 -0
  16. motrix_env_core/config/scene/mjcf.py +10 -0
  17. motrix_env_core/config/scene/sensor.py +125 -0
  18. motrix_env_core/config/scene/terrain.py +518 -0
  19. motrix_env_core/config/scene/urdf.py +84 -0
  20. motrix_env_core/config/scene/validation.py +73 -0
  21. motrix_env_core/config/sim.py +30 -0
  22. motrix_env_core/config/sim_reset.py +42 -0
  23. motrix_env_core/direct/__init__.py +7 -0
  24. motrix_env_core/direct/env.py +75 -0
  25. motrix_env_core/direct/reward.py +71 -0
  26. motrix_env_core/input/__init__.py +26 -0
  27. motrix_env_core/input/bindings.py +204 -0
  28. motrix_env_core/input/command.py +46 -0
  29. motrix_env_core/input/device.py +57 -0
  30. motrix_env_core/manager/__init__.py +72 -0
  31. motrix_env_core/manager/math/__init__.py +8 -0
  32. motrix_env_core/manager/math/quaternion.py +15 -0
  33. motrix_env_core/math/__init__.py +6 -0
  34. motrix_env_core/math/quaternion.py +340 -0
  35. motrix_env_core/math/utils.py +53 -0
  36. motrix_env_core/mdp/__init__.py +4 -0
  37. motrix_env_core/mdp/action.py +215 -0
  38. motrix_env_core/mdp/action_space.py +143 -0
  39. motrix_env_core/mdp/noise.py +36 -0
  40. motrix_env_core/mdp/observations.py +260 -0
  41. motrix_env_core/mdp/rewards.py +133 -0
  42. motrix_env_core/mdp/state.py +23 -0
  43. motrix_env_core/mdp/terminations.py +85 -0
  44. motrix_env_core/mdp/terrain.py +77 -0
  45. motrix_env_core/numba/__init__.py +18 -0
  46. motrix_env_core/numba/fingerprint.py +84 -0
  47. motrix_env_core/numba/kernel.py +142 -0
  48. motrix_env_core/numba/kernel_data/__init__.py +64 -0
  49. motrix_env_core/numba/kernel_data/canonical.py +28 -0
  50. motrix_env_core/numba/kernel_data/lowering.py +433 -0
  51. motrix_env_core/numba/kernel_data/map.py +115 -0
  52. motrix_env_core/numba/kernel_data/methods.py +51 -0
  53. motrix_env_core/numba/kernel_data/tree.py +324 -0
  54. motrix_env_core/numba/manager/__init__.py +4 -0
  55. motrix_env_core/numba/manager/actions.py +113 -0
  56. motrix_env_core/numba/manager/commands.py +97 -0
  57. motrix_env_core/numba/manager/compiler/__init__.py +19 -0
  58. motrix_env_core/numba/manager/compiler/cache.py +106 -0
  59. motrix_env_core/numba/manager/compiler/codegen.py +202 -0
  60. motrix_env_core/numba/manager/compiler/compiler.py +1023 -0
  61. motrix_env_core/numba/manager/compiler/fingerprint.py +18 -0
  62. motrix_env_core/numba/manager/compiler/plan.py +112 -0
  63. motrix_env_core/numba/manager/compiler/program.py +51 -0
  64. motrix_env_core/numba/manager/context.py +80 -0
  65. motrix_env_core/numba/manager/dispatch.py +27 -0
  66. motrix_env_core/numba/manager/env.py +929 -0
  67. motrix_env_core/numba/manager/metrics.py +95 -0
  68. motrix_env_core/numba/manager/observations.py +141 -0
  69. motrix_env_core/numba/manager/rand.py +101 -0
  70. motrix_env_core/numba/manager/rewards.py +66 -0
  71. motrix_env_core/numba/manager/sim_reset.py +112 -0
  72. motrix_env_core/numba/manager/terminations.py +107 -0
  73. motrix_env_core/numba/manager/terms.py +68 -0
  74. motrix_env_core/numba/math/__init__.py +4 -0
  75. motrix_env_core/numba/math/quaternion.py +175 -0
  76. motrix_env_core/numba/program.py +18 -0
  77. motrix_env_core/numba/threading.py +59 -0
  78. motrix_env_core/perf.py +292 -0
  79. motrix_env_core/py.typed +0 -0
  80. motrix_env_core/registry.py +419 -0
  81. motrix_env_core/renderer.py +150 -0
  82. motrix_env_core/sim/__init__.py +122 -0
  83. motrix_env_core/sim/backend.py +218 -0
  84. motrix_env_core/sim/body.py +175 -0
  85. motrix_env_core/sim/config.py +35 -0
  86. motrix_env_core/sim/model.py +398 -0
  87. motrix_env_core/sim/read.py +513 -0
  88. motrix_env_core/sim/registry.py +127 -0
  89. motrix_env_core/sim/write.py +354 -0
  90. motrix_env_core/torch/reward.py +59 -0
  91. motrix_env_core-0.4.0b0.dist-info/METADATA +82 -0
  92. motrix_env_core-0.4.0b0.dist-info/RECORD +94 -0
  93. motrix_env_core-0.4.0b0.dist-info/WHEEL +4 -0
  94. motrix_env_core-0.4.0b0.dist-info/licenses/LICENSE +204 -0
@@ -0,0 +1,52 @@
1
+ # Copyright Motphys Technology Co., Ltd. 2025, 2026
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Public API of the environment framework.
5
+
6
+ Importing this package never imports a simulator. Simulator backends live in
7
+ their own distributions (``motrix-env-motrixsim``, ``motrix-env-mujoco``) and
8
+ register through the ``motrix_env.sim_backends`` entry-point group; the
9
+ backend-neutral boundary is :mod:`motrix_env_core.sim` and its registry is
10
+ :mod:`motrix_env_core.sim.registry`. The torch-tensor frontend for MotrixSim
11
+ lives in :mod:`motrix_env_motrixsim.torch_env`, not here.
12
+ """
13
+
14
+ from motrix_env_core import registry
15
+ from motrix_env_core.base import ABEnv, EnvCfg, ObsSpace, SimCfg
16
+ from motrix_env_core.config import configclass
17
+ from motrix_env_core.config.scene import SceneCfg
18
+ from motrix_env_core.input import (
19
+ BoundedGamePadPlanarVelocityBinding,
20
+ CommandBinding,
21
+ ConstantPlanarVelocityBinding,
22
+ GamePadDevice,
23
+ GamePadPlanarVelocityBinding,
24
+ InputDevice,
25
+ KeyboardDevice,
26
+ KeyboardPlanarVelocityBinding,
27
+ PlanarVelocityCommand,
28
+ )
29
+ from motrix_env_core.perf import Perf, PerfNode, perf_root, perf_scope
30
+
31
+ __all__ = [
32
+ "ABEnv",
33
+ "BoundedGamePadPlanarVelocityBinding",
34
+ "CommandBinding",
35
+ "ConstantPlanarVelocityBinding",
36
+ "EnvCfg",
37
+ "GamePadDevice",
38
+ "GamePadPlanarVelocityBinding",
39
+ "InputDevice",
40
+ "KeyboardDevice",
41
+ "KeyboardPlanarVelocityBinding",
42
+ "ObsSpace",
43
+ "Perf",
44
+ "PerfNode",
45
+ "PlanarVelocityCommand",
46
+ "SceneCfg",
47
+ "SimCfg",
48
+ "configclass",
49
+ "perf_root",
50
+ "perf_scope",
51
+ "registry",
52
+ ]
@@ -0,0 +1,3 @@
1
+ # Copyright Motphys Technology Co., Ltd. 2025, 2026
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
@@ -0,0 +1,330 @@
1
+ # Copyright Motphys Technology Co., Ltd. 2025, 2026
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ import abc
5
+ import dataclasses
6
+ from dataclasses import dataclass
7
+ from typing import Generic, TypeVar
8
+
9
+ import gymnasium as gym
10
+ import numpy as np
11
+
12
+ from motrix_env_core.base import ABEnv, EnvCfg, ObsSpace
13
+ from motrix_env_core.perf import Perf, perf_root
14
+ from motrix_env_core.sim.backend import (
15
+ RenderConfig,
16
+ SimRenderer,
17
+ )
18
+
19
+ # The concrete config type an ArrayEnv subclass consumes. Subclasses parametrize
20
+ # via ``ArrayEnv[MyCfg]`` so ``self.cfg`` is typed as ``MyCfg`` (IDE hint +
21
+ # pyright narrowing). Unparametrized subclasses fall back to ``EnvCfg``
22
+ # (back-compat).
23
+ EnvCfgType = TypeVar("EnvCfgType", bound=EnvCfg)
24
+
25
+
26
+ @dataclass
27
+ class NpObs:
28
+ policy: np.ndarray
29
+ value: np.ndarray | None = None
30
+
31
+ @property
32
+ def value_or_policy(self) -> np.ndarray:
33
+ return self.policy if self.value is None else self.value
34
+
35
+
36
+ @dataclass
37
+ class ArrayEnvState:
38
+ obs: NpObs
39
+ reward: np.ndarray
40
+ terminated: np.ndarray
41
+ truncated: np.ndarray
42
+ episode_steps: np.ndarray
43
+ # Per-term reward breakdown for the latest transition: term name to a
44
+ # ``(num_envs,)`` array. Freshly written every transition; empty when the
45
+ # environment does not decompose its reward.
46
+ reward_terms: dict[str, np.ndarray] = dataclasses.field(default_factory=dict)
47
+ # Live diagnostics view: per-environment quantities stay unreduced as
48
+ # ``(num_envs,)`` arrays and are views into manager buffers that kernels
49
+ # overwrite every step; batch-level gauges are scalars. Values always
50
+ # reflect the latest step: retain values across steps through
51
+ # :meth:`process_metrics`, which returns a fresh dict of reduced scalars.
52
+ metrics: dict[str, float | np.ndarray] = dataclasses.field(default_factory=dict)
53
+
54
+ @property
55
+ def done(self) -> np.ndarray:
56
+ """
57
+ Check if the environment is done.
58
+ """
59
+ return np.logical_or(self.terminated, self.truncated)
60
+
61
+ def replace(self, **updates) -> "ArrayEnvState":
62
+ return dataclasses.replace(self, **updates)
63
+
64
+ def process_metrics(self) -> dict[str, float]:
65
+ """Reduce per-environment metrics into batch-level scalar floats.
66
+
67
+ Per-env arrays are reduced with their mean (bool arrays become trigger
68
+ rates); scalars pass through. The result is a fresh, small dict that is
69
+ safe to retain across steps, unlike the raw ``metrics`` arrays.
70
+ """
71
+ return {
72
+ name: float(np.mean(value)) if isinstance(value, np.ndarray) else float(value)
73
+ for name, value in self.metrics.items()
74
+ }
75
+
76
+ def validate(self):
77
+ num_envs = self.obs.policy.shape[0]
78
+ assert self.obs.policy.shape[0] == num_envs, self.obs.policy.shape
79
+ if self.obs.value is not None:
80
+ assert self.obs.value.shape[0] == num_envs, self.obs.value.shape
81
+ assert self.reward.shape == (num_envs,), self.reward.shape
82
+ assert self.terminated.shape == (num_envs,), self.terminated.shape
83
+ assert self.truncated.shape == (num_envs,), self.truncated.shape
84
+ assert self.episode_steps.shape == (num_envs,), self.episode_steps.shape
85
+
86
+
87
+ def _as_obs_space(space: gym.Space | ObsSpace) -> ObsSpace:
88
+ if isinstance(space, ObsSpace):
89
+ return space
90
+ assert isinstance(space, gym.spaces.Box)
91
+ return ObsSpace(policy=space)
92
+
93
+
94
+ def _as_obs(obs: NpObs | np.ndarray) -> NpObs:
95
+ if isinstance(obs, NpObs):
96
+ return obs
97
+ assert isinstance(obs, np.ndarray)
98
+ return NpObs(policy=obs)
99
+
100
+
101
+ class ArrayEnv(ABEnv, Generic[EnvCfgType]):
102
+ """Simulator-agnostic NumPy frontend environment lifecycle.
103
+
104
+ ``ArrayEnv`` owns the step / auto-reset / truncation lifecycle shared by
105
+ NumPy-frontend environments. It is deliberately free of simulator-state
106
+ concepts: subclasses address simulator rows themselves inside the reset
107
+ hooks, so the frontend only ever speaks in environment indices.
108
+ """
109
+
110
+ _cfg: EnvCfgType
111
+ _state: ArrayEnvState = None
112
+ _render_spacing: float
113
+
114
+ def __init__(self, cfg: EnvCfgType, num_envs: int = 1):
115
+ self._cfg = cfg
116
+ self._num_envs = num_envs
117
+ self.perf = Perf()
118
+ if cfg.scene is None:
119
+ raise ValueError("EnvCfg.scene must be configured")
120
+ self._render_spacing = cfg.render_spacing
121
+
122
+ @property
123
+ def state(self) -> ArrayEnvState:
124
+ """
125
+ Get the current environment state
126
+ """
127
+ return self._state
128
+
129
+ @property
130
+ def cfg(self) -> EnvCfgType:
131
+ """
132
+ Get the environment configuration
133
+ """
134
+ return self._cfg
135
+
136
+ @property
137
+ def render_spacing(self) -> float:
138
+ """
139
+ Get the render spacing, with which the multi-envs will be rendered seperately in grid
140
+ """
141
+ return self._render_spacing
142
+
143
+ @property
144
+ def num_envs(self) -> int:
145
+ return self._num_envs
146
+
147
+ def init_state(self) -> ArrayEnvState:
148
+ """
149
+ Create a new environment state
150
+ """
151
+ obs = self._zeros_obs(self.observation_space)
152
+ reward = np.zeros((self._num_envs,), dtype=np.float32)
153
+ terminated = np.ones((self._num_envs,), dtype=bool)
154
+ truncated = np.zeros((self._num_envs,), dtype=bool)
155
+ episode_steps = np.zeros((self._num_envs,), dtype=np.uint64)
156
+ self._state = self._new_state(obs, reward, terminated, truncated, episode_steps)
157
+ self._reset_done_envs()
158
+ with self.perf.scope("observation"):
159
+ self._state = self.compute_observation(self._state)
160
+ self._state = self._state.replace(obs=_as_obs(self._state.obs))
161
+ self._state.validate()
162
+ return self._state
163
+
164
+ def _new_state(
165
+ self,
166
+ obs: NpObs,
167
+ reward: np.ndarray,
168
+ terminated: np.ndarray,
169
+ truncated: np.ndarray,
170
+ episode_steps: np.ndarray,
171
+ ) -> ArrayEnvState:
172
+ """Assemble the environment state; subclasses add simulator-owned fields."""
173
+ return ArrayEnvState(
174
+ obs=obs,
175
+ reward=reward,
176
+ terminated=terminated,
177
+ truncated=truncated,
178
+ episode_steps=episode_steps,
179
+ )
180
+
181
+ @property
182
+ def policy_observation_space(self) -> gym.spaces.Box:
183
+ return _as_obs_space(self.observation_space).policy
184
+
185
+ @property
186
+ def value_observation_space(self) -> gym.spaces.Box:
187
+ return _as_obs_space(self.observation_space).value_or_policy
188
+
189
+ @property
190
+ def has_value_observation(self) -> bool:
191
+ return _as_obs_space(self.observation_space).value is not None
192
+
193
+ def _zeros_box(self, space: gym.spaces.Box) -> np.ndarray:
194
+ return np.zeros((self._num_envs, *space.shape), dtype=space.dtype)
195
+
196
+ def _zeros_obs(self, space: gym.Space | ObsSpace) -> NpObs:
197
+ obs_space = _as_obs_space(space)
198
+ value = None if obs_space.value is None else self._zeros_box(obs_space.value)
199
+ return NpObs(policy=self._zeros_box(obs_space.policy), value=value)
200
+
201
+ def _assign_obs(self, dst: NpObs, mask: np.ndarray, src: NpObs | np.ndarray):
202
+ src = _as_obs(src)
203
+ dst.policy[mask] = src.policy
204
+ if dst.value is not None:
205
+ assert src.value is not None
206
+ dst.value[mask] = src.value
207
+ else:
208
+ assert src.value is None
209
+
210
+ def _reset_done_envs(self) -> None:
211
+ """
212
+ Reset the environments that are done
213
+ """
214
+ state = self._state
215
+ with self.perf.scope("done_mask"):
216
+ done = state.done
217
+ assert done.shape == (self._num_envs,)
218
+ has_done = np.any(done)
219
+ if not has_done:
220
+ return
221
+
222
+ with self.perf.scope("select_done"):
223
+ np.putmask(state.episode_steps, done, 0)
224
+ env_ids = np.flatnonzero(done)
225
+ with self.perf.scope("reset_envs"):
226
+ self.reset(env_ids)
227
+
228
+ @abc.abstractmethod
229
+ def reset(self, env_ids: np.ndarray) -> None:
230
+ """Write reset rows for the selected environments.
231
+
232
+ Subclasses address their simulator's rows themselves. Observation
233
+ generation is deferred until :meth:`compute_observation`, after reset
234
+ writes have completed.
235
+ """
236
+
237
+ def _max_episode_steps(self) -> int | None:
238
+ return self._cfg.max_episode_steps
239
+
240
+ def _update_truncate(self):
241
+ """
242
+ Truncate the environments that have reached max episode length
243
+ """
244
+ max_episode_steps = self._max_episode_steps()
245
+ if not max_episode_steps:
246
+ return
247
+ self._state.truncated = self._state.episode_steps >= max_episode_steps
248
+
249
+ @abc.abstractmethod
250
+ def create_renderer(self, config: RenderConfig) -> SimRenderer:
251
+ """Create the backend-owned renderer bound to this environment."""
252
+
253
+ @abc.abstractmethod
254
+ def apply_action(self, actions: np.ndarray, state: ArrayEnvState) -> ArrayEnvState:
255
+ """
256
+ Apply the action to the environment
257
+
258
+ Args:
259
+ actions (np.ndarray): The actions to apply
260
+ state (ArrayEnvState): The environment state to apply the actions.
261
+ """
262
+
263
+ @abc.abstractmethod
264
+ def compute_transition(self, state: ArrayEnvState) -> ArrayEnvState:
265
+ """
266
+ Update the environment state after physics step
267
+
268
+ This is the only full simulator-data refresh point of a step: concrete
269
+ environments execute their whole read program here before deriving
270
+ reward, termination, and metrics. It must not write ``state.obs`` —
271
+ observations belong to :meth:`compute_observation`.
272
+
273
+ Args:
274
+ state (ArrayEnvState): The environment state to update
275
+ """
276
+
277
+ @abc.abstractmethod
278
+ def physics_step(self):
279
+ """Advance the simulator by the configured substeps."""
280
+
281
+ def _prev_physics_step(self):
282
+ state = self._state
283
+ state.reward.fill(0.0)
284
+ state.terminated.fill(False)
285
+ state.truncated.fill(False)
286
+
287
+ def compute_observation(self, state: ArrayEnvState) -> ArrayEnvState:
288
+ """Compute observations for all environments after reset.
289
+
290
+ Called once after the first reset of :meth:`init_state` and once per
291
+ :meth:`step` after episode bookkeeping and auto-reset. Implementations
292
+ must purely construct the observation from the simulator data already
293
+ refreshed by :meth:`compute_transition` (whole batch) and reset
294
+ (selected rows) without executing further reads. The default preserves
295
+ observations already present in ``state``.
296
+ """
297
+ return state
298
+
299
+ @perf_root("step")
300
+ def step(self, actions: np.ndarray) -> ArrayEnvState:
301
+ """Advance one control step.
302
+
303
+ Timing: ``apply_action`` -> ``physics_step`` -> ``compute_transition``
304
+ (the only full simulator-data refresh) -> episode bookkeeping ->
305
+ ``reset(env_ids)`` for done rows (may refresh selected rows) ->
306
+ ``compute_observation`` (whole batch, pure construction).
307
+ """
308
+ if self._state is None:
309
+ with self.perf.scope("init_state"):
310
+ self.init_state()
311
+
312
+ self._prev_physics_step()
313
+ with self.perf.scope("apply_action"):
314
+ self._state = self.apply_action(actions, self._state)
315
+ assert self._state is not None, "apply_action must return a valid environment state"
316
+ with self.perf.scope("physics"):
317
+ self.physics_step()
318
+ with self.perf.scope("transition"):
319
+ self._state = self.compute_transition(self._state)
320
+ self._state.episode_steps += 1
321
+ self._update_truncate()
322
+ with self.perf.scope("reset"):
323
+ self._reset_done_envs()
324
+ with self.perf.scope("observation"):
325
+ self._state = self.compute_observation(self._state)
326
+ self._state = self._state.replace(obs=_as_obs(self._state.obs))
327
+ return self._state
328
+
329
+
330
+ __all__ = ["ArrayEnv", "ArrayEnvState", "EnvCfgType", "NpObs"]
@@ -0,0 +1,41 @@
1
+ # Copyright Motphys Technology Co., Ltd. 2025, 2026
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Backend-neutral array types and operations shared across runtimes."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from types import ModuleType
9
+ from typing import Any, TypeAlias, TypeGuard, Union
10
+
11
+ import numpy as np
12
+ import numpy.typing as npt
13
+ from array_api_compat import array_namespace as _array_namespace
14
+ from array_api_compat import is_numpy_array, is_torch_array
15
+
16
+ Array: TypeAlias = Union[npt.NDArray[Any], "torch.Tensor"] # noqa: F821
17
+
18
+
19
+ def array_namespace(*arrays: Array) -> ModuleType:
20
+ """Return the NumPy or Torch Array API namespace shared by ``arrays``."""
21
+
22
+ for array in arrays:
23
+ if not is_array(array):
24
+ raise TypeError(
25
+ f"array_namespace only supports NumPy arrays and Torch tensors, got {type(array).__name__}."
26
+ )
27
+
28
+ return _array_namespace(*arrays)
29
+
30
+
31
+ def is_array(value: object) -> TypeGuard[Array]:
32
+ """Return whether ``value`` is a supported NumPy array or Torch tensor."""
33
+
34
+ return (is_numpy_array(value) and isinstance(value, np.ndarray)) or is_torch_array(value)
35
+
36
+
37
+ __all__ = [
38
+ "Array",
39
+ "array_namespace",
40
+ "is_array",
41
+ ]
@@ -0,0 +1,99 @@
1
+ # Copyright Motphys Technology Co., Ltd. 2025, 2026
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ import abc
5
+ from dataclasses import dataclass
6
+
7
+ import gymnasium as gym
8
+
9
+ from motrix_env_core.config import configclass
10
+ from motrix_env_core.config.scene import SceneCfg, validate_scene_cfg
11
+ from motrix_env_core.config.sim import SimCfg
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class ObsSpace:
16
+ policy: gym.spaces.Box
17
+ value: gym.spaces.Box | None = None
18
+
19
+ @property
20
+ def value_or_policy(self) -> gym.spaces.Box:
21
+ return self.policy if self.value is None else self.value
22
+
23
+
24
+ @configclass
25
+ class EnvCfg:
26
+ """
27
+ Config for the environment
28
+
29
+ """
30
+
31
+ scene: SceneCfg | None = None
32
+ sim: SimCfg = SimCfg()
33
+ max_episode_seconds: float = None
34
+ ctrl_dt: float = 0.01
35
+ render_spacing: float = 1.0
36
+
37
+ @property
38
+ def max_episode_steps(self) -> int | None:
39
+ """
40
+ return the max episode steps
41
+ """
42
+ if self.max_episode_seconds is None:
43
+ return None
44
+ return int(self.max_episode_seconds / self.ctrl_dt)
45
+
46
+ @property
47
+ def sim_substeps(self) -> int:
48
+ """
49
+ return the number of simulation steps per control step
50
+ """
51
+ return int(round(self.ctrl_dt / self.sim.dt))
52
+
53
+ def validate(self):
54
+ """
55
+ validate the config
56
+ """
57
+ self.sim.validate()
58
+ if self.sim.dt > self.ctrl_dt:
59
+ raise ValueError("sim.dt must be less than or equal to ctrl_dt")
60
+ if self.scene is None:
61
+ raise ValueError("EnvCfg.scene must be configured")
62
+ validate_scene_cfg(self.scene)
63
+
64
+ def for_play(self) -> "EnvCfg":
65
+ """Return the config variant used for play/eval rollouts.
66
+
67
+ The default is mode-agnostic (play behaves exactly like train). Envs
68
+ whose play behavior differs override this to return a modified copy
69
+ (e.g. no episode cap, deterministic start, disabled curriculum/noise).
70
+ Keeping the difference on the config makes it the single source of
71
+ truth and keeps the environment itself unaware of any runtime "mode".
72
+ """
73
+ return self
74
+
75
+
76
+ class ABEnv(abc.ABC):
77
+ @property
78
+ @abc.abstractmethod
79
+ def num_envs(self) -> int:
80
+ """
81
+ return the size of the env if it is vectorized
82
+ """
83
+
84
+ @property
85
+ @abc.abstractmethod
86
+ def cfg(self) -> EnvCfg:
87
+ """
88
+ The configuration of the environment
89
+ """
90
+
91
+ @property
92
+ @abc.abstractmethod
93
+ def observation_space(self) -> gym.Space | ObsSpace:
94
+ """Observation space"""
95
+
96
+ @property
97
+ @abc.abstractmethod
98
+ def action_space(self) -> gym.Space:
99
+ """Action space"""
@@ -0,0 +1,8 @@
1
+ # Copyright Motphys Technology Co., Ltd. 2025, 2026
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ from motrix_env_core.config.decorate import configclass
5
+ from motrix_env_core.config.sim import SimCfg
6
+ from motrix_env_core.config.sim_reset import ManagerResetCfg, ResetTermCfg
7
+
8
+ __all__ = ["SimCfg", "ManagerResetCfg", "ResetTermCfg", "configclass"]
@@ -0,0 +1,141 @@
1
+ # Copyright Motphys Technology Co., Ltd. 2025, 2026
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ from __future__ import annotations
5
+
6
+ from collections.abc import Callable
7
+ from copy import deepcopy
8
+ from dataclasses import Field, InitVar, dataclass, field, is_dataclass
9
+ from typing import Any, ClassVar, TypeVar, get_origin, get_type_hints, overload
10
+
11
+ import numpy as np
12
+ from typing_extensions import dataclass_transform
13
+
14
+ _T = TypeVar("_T")
15
+
16
+
17
+ def _requires_copy(value: object) -> bool:
18
+ if isinstance(value, (list, dict, set, np.ndarray)):
19
+ return True
20
+ if is_dataclass(value) and not isinstance(value, type):
21
+ return True
22
+ if isinstance(value, tuple):
23
+ return any(_requires_copy(item) for item in value)
24
+ return False
25
+
26
+
27
+ def _copy_factory(owner: str, name: str, template: object) -> Callable[[], object]:
28
+ def factory() -> object:
29
+ try:
30
+ return deepcopy(template)
31
+ except Exception as exc:
32
+ raise TypeError(f"Failed to deepcopy default value for {owner}.{name}") from exc
33
+
34
+ return factory
35
+
36
+
37
+ def _normalized_annotation_name(annotation: str) -> str:
38
+ return annotation.replace("typing.", "").replace("dataclasses.", "").replace(" ", "")
39
+
40
+
41
+ def _is_class_var(annotation: object) -> bool:
42
+ if get_origin(annotation) is ClassVar:
43
+ return True
44
+ if isinstance(annotation, str):
45
+ name = _normalized_annotation_name(annotation)
46
+ return name == "ClassVar" or name.startswith("ClassVar[")
47
+ return False
48
+
49
+
50
+ def _is_init_var(annotation: object) -> bool:
51
+ if annotation is InitVar or isinstance(annotation, InitVar):
52
+ return True
53
+ if isinstance(annotation, str):
54
+ name = _normalized_annotation_name(annotation)
55
+ return name == "InitVar" or name.startswith("InitVar[")
56
+ return False
57
+
58
+
59
+ def _resolved_annotations(cls: type[Any], annotations: dict[str, object]) -> dict[str, object]:
60
+ try:
61
+ resolved = get_type_hints(cls, include_extras=True)
62
+ except (NameError, TypeError):
63
+ return annotations
64
+ return {name: resolved.get(name, annotation) for name, annotation in annotations.items()}
65
+
66
+
67
+ def _wrap_configclass(cls: type[_T], **dataclass_options: Any) -> type[_T]:
68
+ if "__dataclass_fields__" in cls.__dict__:
69
+ raise TypeError(f"{cls.__qualname__} is already a dataclass; use either @configclass or @dataclass")
70
+
71
+ annotations = dict(cls.__dict__.get("__annotations__", {}))
72
+ resolved_annotations = _resolved_annotations(cls, annotations)
73
+
74
+ for name, annotation in resolved_annotations.items():
75
+ if name not in cls.__dict__ or _is_class_var(annotation) or _is_init_var(annotation):
76
+ continue
77
+
78
+ value = cls.__dict__[name]
79
+ if isinstance(value, Field) or isinstance(value, type) or callable(value) or not _requires_copy(value):
80
+ continue
81
+
82
+ setattr(cls, name, field(default_factory=_copy_factory(cls.__qualname__, name, value)))
83
+
84
+ return dataclass(cls, **dataclass_options)
85
+
86
+
87
+ @overload
88
+ def configclass(cls: type[_T], /) -> type[_T]: ...
89
+
90
+
91
+ @overload
92
+ def configclass(
93
+ cls: None = None,
94
+ /,
95
+ *,
96
+ init: bool = True,
97
+ repr: bool = True,
98
+ eq: bool = True,
99
+ order: bool = False,
100
+ unsafe_hash: bool = False,
101
+ frozen: bool = False,
102
+ match_args: bool = True,
103
+ kw_only: bool = False,
104
+ slots: bool = False,
105
+ ) -> Callable[[type[_T]], type[_T]]: ...
106
+
107
+
108
+ @dataclass_transform(field_specifiers=(field,))
109
+ def configclass(
110
+ cls: type[_T] | None = None,
111
+ /,
112
+ *,
113
+ init: bool = True,
114
+ repr: bool = True,
115
+ eq: bool = True,
116
+ order: bool = False,
117
+ unsafe_hash: bool = False,
118
+ frozen: bool = False,
119
+ match_args: bool = True,
120
+ kw_only: bool = False,
121
+ slots: bool = False,
122
+ ) -> type[_T] | Callable[[type[_T]], type[_T]]:
123
+ """Create a dataclass whose declared mutable defaults are copied per instance."""
124
+ options = {
125
+ "init": init,
126
+ "repr": repr,
127
+ "eq": eq,
128
+ "order": order,
129
+ "unsafe_hash": unsafe_hash,
130
+ "frozen": frozen,
131
+ "match_args": match_args,
132
+ "kw_only": kw_only,
133
+ "slots": slots,
134
+ }
135
+
136
+ if cls is None:
137
+ return lambda decorated_cls: _wrap_configclass(decorated_cls, **options)
138
+ return _wrap_configclass(cls, **options)
139
+
140
+
141
+ __all__ = ["configclass"]