poseres 0.1.0__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.
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: poseres
3
+ Version: 0.1.0
4
+ Summary: Pose Resolution Architecture — validation harness and batched in-memory core
5
+ Author: Daan Gerits
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/impire-io/poseres
8
+ Project-URL: Source, https://github.com/impire-io/poseres
9
+ Project-URL: Bug Tracker, https://github.com/impire-io/poseres/issues
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Requires-Python: >=3.13
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: numpy>=2.4
15
+ Provides-Extra: dev
16
+ Requires-Dist: pytest>=8.0; extra == "dev"
17
+ Requires-Dist: ruff>=0.6; extra == "dev"
18
+ Dynamic: license-file
19
+
20
+ # PRA — Pose Resolution Architecture
21
+
22
+ An in-memory, batched, deterministic core (PRA-01) and the validation harness
23
+ (PRA-02) that runs the acceptance suite **T1–T6** plus the investigatory
24
+ **T-SCALE**, emitting an honest, reproducible PASS/FAIL verdict per test.
25
+
26
+ See `specs/001-validation-harness/` for the spec, plan, and contracts, and
27
+ `design/` for the architecture documents. The behavioral oracle is
28
+ `design/validate/pra_sim_v4.py`.
29
+
30
+ ## Quickstart
31
+
32
+ **Fastest — install from PyPI with [`uv`](https://docs.astral.sh/uv/):**
33
+
34
+ ```bash
35
+ uvx --from poseres pra-validate suite
36
+ ```
37
+
38
+ No Python version juggling, no venv to manage. `uv` fetches Python 3.13 automatically if you don't have it.
39
+
40
+ **From source:**
41
+
42
+ ```bash
43
+ git clone https://github.com/impire-io/poseres.git
44
+ cd pra
45
+ python3.13 -m venv .venv
46
+ source .venv/bin/activate # Windows: .venv\Scripts\activate
47
+ pip install -e ".[dev]" # numpy + pytest + ruff
48
+
49
+ pra-validate suite # 8 seeds, true_dim=3, checkpoints 18/30/50
50
+ pra-validate suite --json out/report.json
51
+ pra-validate determinism --seed 1 # byte-identical re-run check
52
+ pra-validate scale --true-dims 20,35,50
53
+ pra-validate scan --true-dim 20 --hidden-sizes 12,32,64 # diagnostic dimension scan
54
+ pra-validate agency # curious vs random (T7) + value-signal telemetry
55
+
56
+ ruff format --check . && ruff check . && pytest -q
57
+ ```
58
+
59
+ Independent seeds run in parallel worker processes by default (`--workers`,
60
+ 0 = one per seed up to the CPU count) — parallelism never changes results
61
+ (byte-identical to sequential; each run keeps its own seeded, single-threaded
62
+ pipeline). The full default suite runs in ~20s on a 14-core machine.
63
+
64
+ `suite` emits, for each of **T1–T6**, the measured aggregate (mean ± std), the
65
+ exact pass criterion, and PASS/FAIL. **T4** is shown as the full per-seed `best_dim`
66
+ spread at every horizon checkpoint and PASSes only if the within-one-of-true
67
+ majority holds at *every* checkpoint — it can never pass on a lucky single horizon.
68
+ **T5** PASSes only when the population genuinely self-limits (no seed strictly
69
+ growing over its final third), not merely because it hit a cap. A single-seed run is
70
+ labelled **FOR DEBUGGING ONLY**. Exit code is 0 even when a test FAILs (a FAIL is
71
+ data, not a CLI error) unless `--strict` is passed.
72
+
73
+ ## Governing principle — honest summary
74
+
75
+ Where a tidy report and a faithful one conflict, the faithful one wins (FR-008): a
76
+ failing test is shown as FAIL *with the numbers that explain it*; a test needing a
77
+ spread is never reported by its mean alone; a seed that errors is surfaced and the
78
+ aggregate flagged incomplete, never silently dropped; too few samples reads
79
+ "not available", never a fabricated number. Two runs of a seed produce
80
+ byte-identical telemetry (single seeded RNG, fixed draw order, single-threaded BLAS).
81
+
82
+ ## Layout
83
+
84
+ ```
85
+ src/pra/
86
+ config.py # every PRA-01 §8 parameter + validation
87
+ world/event_source.py# EventSource seam + SensorimotorWorld (nonlinear, hidden latent)
88
+ core/ # contracts, bus, scorer, policies, the batched FrameGroup kernel, engine
89
+ motivation/ # Drive seam: curiosity (learning progress + novelty), weighted drive set
90
+ action/ # Policy seam: pinned random baseline + one-step curiosity lookahead
91
+ persistence/ # snapshot/restore: versioned blob + atomic SnapshotStore (opt-in)
92
+ anatomy/ # body: sensors/actuators, fixed-order composition, runtime tools
93
+ telemetry/recorder.py# deterministic per-seed summary
94
+ harness/ # acceptance (T1-T7/T-SCALE), runner, report, cli, scale, scan, agency
95
+ tests/ # unit (incl. batched-vs-reference proof) / contract (5 seams) / integration
96
+ ```
97
+
98
+ ## Behavioral oracle
99
+
100
+ `design/validate/pra_sim_v4.py` is the validated reference run. The batched core
101
+ reproduces its T1–T6 trajectory at the default config (the per-frame-vs-batched
102
+ equivalence is enforced by `tests/unit/test_batched_equivalence.py`) at roughly 40×
103
+ the speed. The full default suite (8 seeds × predictive + ablation × 50 cycles)
104
+ completes in well under a minute.
@@ -0,0 +1,37 @@
1
+ poseres-0.1.0.dist-info/licenses/LICENSE,sha256=2TJLWeXZgjoZoyQn14F9IKVTYFWSN5TNABdaTbevirk,1068
2
+ pra/__init__.py,sha256=VgfH2mN3NC_Q8Qh354D0cCEt3bv9SURVArHY3WupGlo,852
3
+ pra/config.py,sha256=65umA2SKg6ZSjnhbOl16M9NTSGFGVSo2lT5C3WPigRc,10219
4
+ pra/action/__init__.py,sha256=xSTczHw4xega8s6fBJmCQQoKHNewi4siuF9HJgwsAw8,77
5
+ pra/action/policy.py,sha256=0FeMAYFaL8zFAJeOM2h7wStnCZ2ReSi4XjsEQoYwC7g,3784
6
+ pra/anatomy/__init__.py,sha256=2oym5Doy3SGt6nBm3BtFrFlns46LBN25NFeq5q8TRrw,87
7
+ pra/anatomy/body.py,sha256=1krAGEjdcexuQNuSh4W2fAJwXIu2QtO-FPaE-IMq56o,8722
8
+ pra/core/__init__.py,sha256=2glkRw3R0f6HCB93PKRAr_Ix9muqryjH2A-ayvHsrOQ,23
9
+ pra/core/bus.py,sha256=FvksrC1Is8E3THKlYco4zLjX1L9JbnOydKxWgjL4DAc,2899
10
+ pra/core/contracts.py,sha256=9ujNBGPZOf-SuWuQSqihDSjqqYYeWl6hl9qMaCHkE1M,3078
11
+ pra/core/engine.py,sha256=zrqmr0Pe7MECkfWqVD-r0ohbOef1nojckAShCEveFe0,22288
12
+ pra/core/frame.py,sha256=E-YnQWYfV9hFcgWgM5i5zU8eF8UQt5Uc_-pYiUWRfKY,22707
13
+ pra/core/policies.py,sha256=YRBQwJ4xbnSB1eJ38wI9UnbSVSmaQIizvBUZzf7Uryk,5415
14
+ pra/core/scorer.py,sha256=MdnwFq_KRKzNZ5wAijbdoCviq0XeGlj5cFI7-wNzwuc,2086
15
+ pra/harness/__init__.py,sha256=kOeRN008vQTuaAhAVkEVnnH37rfRKgLLfuvyDCTSgvw,26
16
+ pra/harness/acceptance.py,sha256=2iXDQvSEpLcM3srJz9p8xKdepgxSQi55sk-vJkYYEbU,11533
17
+ pra/harness/agency.py,sha256=PJPo2T2f8nKjvwdiAxdxCM9BwIgtCppgm2a6JVw3JgA,3356
18
+ pra/harness/cli.py,sha256=TNWYdL2U8einiLs_ypf1eFkak8Pr0LNpsXrdOwmG0N4,9515
19
+ pra/harness/report.py,sha256=u3mimAzPzC8bipPuiHZVcdVQChxN2dCpLDDX0fNAofU,11275
20
+ pra/harness/runner.py,sha256=m6DYbPUUdWuzXRCO3TpbvJ4uxuj895J-JdP1HyZ_SSc,6090
21
+ pra/harness/scale.py,sha256=t0hFpIORQBYdxO8AmsGgg2_QFu7jRG-EMzesRK--9X4,3450
22
+ pra/harness/scan.py,sha256=tI2NqBzV4fuC-etdlsW15I5gMcs5rHJtIt0rlxHe5Ew,6805
23
+ pra/motivation/__init__.py,sha256=UTEQitGfIA-2zzsRm10mfbPZMRbUYlKHpZPEyG9JYks,89
24
+ pra/motivation/context.py,sha256=-8HitQDLb_ZGWj5YNLWBwEutlIYbm_V3GsKk-cQP4KI,864
25
+ pra/motivation/drive.py,sha256=GpclfY2bpsz-kozVZKJnIfu8ilJRNvpDCuuKBgJsuEk,7869
26
+ pra/persistence/__init__.py,sha256=e1Oa3duMZvd-MLERvd2begHGPl6WuUSVuV4B0qT5xoM,84
27
+ pra/persistence/snapshot.py,sha256=0aoixV5hfhcrdHCbZkYqopyA98Vmheo6yE-oMm8LIME,8035
28
+ pra/persistence/store.py,sha256=1pDW2HH7jYr1BKLyJ8jjK_pYs3UpVn7VX3DPVq9Lud8,4250
29
+ pra/telemetry/__init__.py,sha256=y_mFAGPqwgVhMcEiiolzekOljXzk-LnRejbPNcmvix0,28
30
+ pra/telemetry/recorder.py,sha256=_uKYhJxkc4ly9jtFrDU-IwICd0NDuDW2Ek-6C6aWs9g,5896
31
+ pra/world/__init__.py,sha256=VBvm1OgaNMZ_ZIZkADuQuNNpnhQMWORHnzIN8pr-8qc,24
32
+ pra/world/event_source.py,sha256=1rpzg4KWqMMhb_0uagVBL2MWQABRhYNGoZwNm738IjY,4182
33
+ poseres-0.1.0.dist-info/METADATA,sha256=InZpH9zV8FTAwgIltpXEaBT6F5PQOxCG5nGVPGd4ZN8,4776
34
+ poseres-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
35
+ poseres-0.1.0.dist-info/entry_points.txt,sha256=lGENmtLfYkWBegh7Eo9Qi4DwftVN4qx2N3O9bVIDJKw,54
36
+ poseres-0.1.0.dist-info/top_level.txt,sha256=Ap6zJD_aM-94A7oOusQX4WWF1D4Dv0HHmwjAFAqjZoc,4
37
+ poseres-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pra-validate = pra.harness.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Daan Gerits
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ pra
pra/__init__.py ADDED
@@ -0,0 +1,26 @@
1
+ """Pose Resolution Architecture (PRA).
2
+
3
+ A single in-memory, batched, deterministic core (PRA-01) plus the validation
4
+ harness (PRA-02) that runs the acceptance suite T1-T6 and the investigatory
5
+ T-SCALE.
6
+
7
+ Determinism (FR-010, SC-007, PRA-01 §7.1) requires a fixed float-accumulation
8
+ order. We pin every BLAS backend to a single thread *before* numpy is imported
9
+ anywhere in the process, so reductions are byte-stable across runs on one
10
+ machine. This module is imported before any ``pra`` submodule pulls in numpy.
11
+ """
12
+
13
+ import os as _os
14
+
15
+ # Pin BLAS threading before numpy is first imported (PRA-01 §7.1, research R3).
16
+ for _var in (
17
+ "OMP_NUM_THREADS",
18
+ "OPENBLAS_NUM_THREADS",
19
+ "MKL_NUM_THREADS",
20
+ "VECLIB_MAXIMUM_THREADS",
21
+ "NUMEXPR_NUM_THREADS",
22
+ ):
23
+ _os.environ.setdefault(_var, "1")
24
+
25
+ __all__ = ["__version__"]
26
+ __version__ = "0.1.0"
pra/action/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Action component (design Doc 05 §4): policy seam -> action selection."""
pra/action/policy.py ADDED
@@ -0,0 +1,98 @@
1
+ """Policies: action selection (Doc 05 §4).
2
+
3
+ The Policy seam replaces the engine's inline random action draw. The default
4
+ ``RandomPolicy`` reproduces that draw EXACTLY — one ``rng.integers(n_actions)``
5
+ per step, nothing else — so every existing mode (the validated T1-T6 suite,
6
+ determinism, scale, scan) consumes an identical RNG stream and stays
7
+ byte-identical to the validated build (FR-008, research R1).
8
+
9
+ ``CuriosityLookaheadPolicy`` is the shipped directed default (Doc 05 §4.2/§4.3):
10
+ ε-gate first; uniformly random when exploring, when no best frame exists, or
11
+ when the best frame is younger than the maturity bar; otherwise a one-step
12
+ lookahead — predict each candidate action's outcome with the best frame's
13
+ transition model, decode it, value it via the drive set — choosing the argmax
14
+ with ties broken by the lowest action index (no further draws). Policies are
15
+ stateless across steps; all randomness comes from the run's single seeded
16
+ generator in this fixed order (FR-007).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections.abc import Callable
22
+ from dataclasses import dataclass
23
+ from typing import Protocol, runtime_checkable
24
+
25
+ import numpy as np
26
+
27
+ from pra.config import Config
28
+
29
+ __all__ = ["PolicyContext", "Policy", "RandomPolicy", "CuriosityLookaheadPolicy", "PolicyParams"]
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class PolicyContext:
34
+ """The read-only view a policy selects from (data-model §3)."""
35
+
36
+ observation: np.ndarray
37
+ n_actions: int
38
+ best_frame_age: int | None # None when no frame exists
39
+ predict_decoded: Callable[[int], np.ndarray | None] # best-frame one-step, decoded
40
+ drive_value_of: Callable[[np.ndarray], float] # drive set valued at a hypothetical obs
41
+
42
+
43
+ @runtime_checkable
44
+ class Policy(Protocol):
45
+ def select_action(self, context: PolicyContext, rng: np.random.Generator) -> int: ...
46
+
47
+
48
+ class RandomPolicy:
49
+ """The pinned validation baseline: exactly the validated engine's inline draw."""
50
+
51
+ def select_action(self, context: PolicyContext, rng: np.random.Generator) -> int:
52
+ return int(rng.integers(context.n_actions))
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class PolicyParams:
57
+ exploration_epsilon: float
58
+ lookahead_min_age_cycles: int
59
+
60
+ @classmethod
61
+ def from_config(cls, config: Config) -> PolicyParams:
62
+ return cls(
63
+ exploration_epsilon=config.exploration_epsilon,
64
+ lookahead_min_age_cycles=config.lookahead_min_age_cycles,
65
+ )
66
+
67
+
68
+ class CuriosityLookaheadPolicy:
69
+ """One-step curiosity lookahead with ε-exploration and a cold-start gate."""
70
+
71
+ def __init__(self, params: PolicyParams):
72
+ self.params = params
73
+ self.last_was_directed = False # telemetry only; overwritten every step
74
+
75
+ def select_action(self, context: PolicyContext, rng: np.random.Generator) -> int:
76
+ # Fixed draw order (research R3): one uniform for the ε-gate, then one
77
+ # integer draw only on the random path. Exploit draws nothing further.
78
+ explore = rng.random() < self.params.exploration_epsilon
79
+ immature = (
80
+ context.best_frame_age is None
81
+ or context.best_frame_age < self.params.lookahead_min_age_cycles
82
+ )
83
+ if explore or immature:
84
+ self.last_was_directed = False
85
+ return int(rng.integers(context.n_actions))
86
+
87
+ best_action = 0
88
+ best_value = -np.inf
89
+ for action in range(context.n_actions): # ascending: lowest index wins ties
90
+ predicted = context.predict_decoded(action)
91
+ if predicted is None:
92
+ continue
93
+ value = context.drive_value_of(predicted)
94
+ if value > best_value:
95
+ best_value = value
96
+ best_action = action
97
+ self.last_was_directed = True
98
+ return best_action
@@ -0,0 +1 @@
1
+ """Anatomy component (design Doc 02): sensors, actuators, the composed body, tools."""
pra/anatomy/body.py ADDED
@@ -0,0 +1,239 @@
1
+ """The body: sensors, actuators, fixed-order composition, tools (Doc 02 §2–§5).
2
+
3
+ The anatomy is configurable and meaning-free: the system sees observations as
4
+ vectors (the fixed-order concatenation of all active sensors) and emits actions
5
+ as indices into the fixed-order disjoint union of all active actuators. The
6
+ declared order is semantic — changing it changes the meaning of every
7
+ observation dimension (Doc 02 §3.3).
8
+
9
+ The :class:`Body` satisfies the existing ``EventSource`` seam
10
+ (``reset``/``step``/``obs_dim``/``n_actions``), so it mounts wherever the
11
+ synthetic world mounts today — with 1:1 delegation for a world-only body, which
12
+ is what makes world-through-body runs byte-identical to the direct connection
13
+ (feature 004 research R1). Tool registrations are queued and take effect only
14
+ when the Engine calls :meth:`Body.apply_pending_tools` at a slow-loop boundary
15
+ (C4, Doc 02 §5.2); the only feedback path from an action is subsequent
16
+ observations (actuators return nothing, Doc 02 §4.2).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from typing import Protocol, runtime_checkable
22
+
23
+ import numpy as np
24
+
25
+ __all__ = [
26
+ "Sensor",
27
+ "Actuator",
28
+ "AnatomyError",
29
+ "Body",
30
+ "WorldSensor",
31
+ "WorldActuator",
32
+ "ConstantSensor",
33
+ ]
34
+
35
+
36
+ class AnatomyError(ValueError):
37
+ """A body-contract violation (wrong width, duplicate id, invalid routing)."""
38
+
39
+
40
+ @runtime_checkable
41
+ class Sensor(Protocol):
42
+ def id(self) -> str: ...
43
+ def width(self) -> int: ...
44
+ def read(self) -> np.ndarray: ...
45
+
46
+
47
+ @runtime_checkable
48
+ class Actuator(Protocol):
49
+ def id(self) -> str: ...
50
+ def action_count(self) -> int: ...
51
+ def apply(self, local_action_index: int) -> None: ...
52
+
53
+
54
+ class WorldSensor:
55
+ """Mounts the synthetic world's observation as one sensor. The world emits
56
+ on reset/step; this sensor exposes the cached emission (width = obs_dim)."""
57
+
58
+ def __init__(self, world, sensor_id: str = "world"):
59
+ self._world = world
60
+ self._id = sensor_id
61
+ self.last: np.ndarray | None = None
62
+
63
+ def id(self) -> str:
64
+ return self._id
65
+
66
+ def width(self) -> int:
67
+ return int(self._world.obs_dim)
68
+
69
+ def read(self) -> np.ndarray:
70
+ if self.last is None:
71
+ raise AnatomyError(f"sensor '{self._id}' read before the first emission")
72
+ return self.last
73
+
74
+
75
+ class WorldActuator:
76
+ """Mounts the synthetic world's action space; applying steps the world and
77
+ feeds the paired WorldSensor's cache. Returns nothing (Doc 02 §4.2)."""
78
+
79
+ def __init__(self, world, sensor: WorldSensor, actuator_id: str = "world"):
80
+ self._world = world
81
+ self._sensor = sensor
82
+ self._id = actuator_id
83
+
84
+ def id(self) -> str:
85
+ return self._id
86
+
87
+ def action_count(self) -> int:
88
+ return int(self._world.n_actions)
89
+
90
+ def apply(self, local_action_index: int) -> None:
91
+ self._sensor.last = self._world.step(local_action_index)
92
+
93
+
94
+ class ConstantSensor:
95
+ """A fixed-vector sensor (no RNG) — the tool-demo and test part."""
96
+
97
+ def __init__(self, sensor_id: str, values):
98
+ self._id = sensor_id
99
+ self._values = np.asarray(values, dtype=np.float64)
100
+
101
+ def id(self) -> str:
102
+ return self._id
103
+
104
+ def width(self) -> int:
105
+ return int(self._values.shape[0])
106
+
107
+ def read(self) -> np.ndarray:
108
+ return self._values
109
+
110
+
111
+ class Body:
112
+ """Fixed-order composition of sensors and actuators around an environment.
113
+
114
+ EventSource-compatible: ``reset()`` begins an episode on the environment
115
+ (the world sensor caches the first emission) and composes the observation;
116
+ ``step(a)`` routes the global index to ``(actuator, local)`` and composes
117
+ all sensors' reads. ``obs_dim``/``n_actions`` are derived from the active
118
+ parts and change only when :meth:`apply_pending_tools` applies queued
119
+ registrations at a slow-loop boundary.
120
+ """
121
+
122
+ def __init__(self, environment, sensors: list, actuators: list):
123
+ if not sensors or not actuators:
124
+ raise AnatomyError("a body needs at least one sensor and one actuator")
125
+ self._environment = environment
126
+ self._sensors: list = []
127
+ self._actuators: list = []
128
+ self._pending: list[tuple[str, object]] = []
129
+ for s in sensors:
130
+ self._add_sensor(s)
131
+ for a in actuators:
132
+ self._add_actuator(a)
133
+
134
+ # ---- derived anatomy (Doc 02 §3.3 / §4.2) ---------------------------------
135
+ @property
136
+ def obs_dim(self) -> int:
137
+ return sum(s.width() for s in self._sensors)
138
+
139
+ @property
140
+ def n_actions(self) -> int:
141
+ return sum(a.action_count() for a in self._actuators)
142
+
143
+ # ---- EventSource surface --------------------------------------------------
144
+ def reset(self) -> np.ndarray:
145
+ first = self._environment.reset()
146
+ for s in self._sensors:
147
+ if isinstance(s, WorldSensor):
148
+ s.last = first
149
+ return self._compose()
150
+
151
+ def step(self, action: int) -> np.ndarray:
152
+ actuator, local = self.route(action)
153
+ actuator.apply(local)
154
+ return self._compose()
155
+
156
+ # ---- composition & routing ------------------------------------------------
157
+ def _compose(self) -> np.ndarray:
158
+ parts = []
159
+ for s in self._sensors:
160
+ value = np.asarray(s.read(), dtype=np.float64)
161
+ if value.shape != (s.width(),):
162
+ raise AnatomyError(
163
+ f"sensor '{s.id()}' returned shape {value.shape}, declared width {s.width()}"
164
+ )
165
+ parts.append(value)
166
+ return parts[0] if len(parts) == 1 else np.concatenate(parts)
167
+
168
+ def route(self, action: int) -> tuple[object, int]:
169
+ """Global index -> (actuator, local index), by fixed declared order."""
170
+ if not 0 <= action < self.n_actions:
171
+ raise AnatomyError(f"action {action} outside [0, {self.n_actions})")
172
+ offset = 0
173
+ for a in self._actuators:
174
+ count = a.action_count()
175
+ if action < offset + count:
176
+ return a, action - offset
177
+ offset += count
178
+ raise AnatomyError("unreachable: routing table exhausted") # pragma: no cover
179
+
180
+ # ---- ToolRegistry (Doc 02 §5): queued, applied at the slow loop ------------
181
+ def register_sensor(self, sensor) -> str:
182
+ self._check_new_id(sensor.id())
183
+ self._pending.append(("sensor", sensor))
184
+ return sensor.id()
185
+
186
+ def register_actuator(self, actuator) -> str:
187
+ self._check_new_id(actuator.id())
188
+ self._pending.append(("actuator", actuator))
189
+ return actuator.id()
190
+
191
+ def deregister(self, tool_id: str) -> None:
192
+ self._pending.append(("deregister", tool_id))
193
+
194
+ def list_tools(self) -> list[tuple[str, str]]:
195
+ return [(s.id(), "sensor") for s in self._sensors] + [
196
+ (a.id(), "actuator") for a in self._actuators
197
+ ]
198
+
199
+ def apply_pending_tools(self) -> tuple[int, int] | None:
200
+ """Apply queued registrations (slow loop only, C4). Returns the new
201
+ ``(obs_dim, n_actions)`` iff anything changed, else None."""
202
+ if not self._pending:
203
+ return None
204
+ for kind, item in self._pending:
205
+ if kind == "sensor":
206
+ self._add_sensor(item)
207
+ elif kind == "actuator":
208
+ self._add_actuator(item)
209
+ else:
210
+ self._remove(item)
211
+ self._pending.clear()
212
+ return self.obs_dim, self.n_actions
213
+
214
+ # ---- internals --------------------------------------------------------------
215
+ def _check_new_id(self, tool_id: str) -> None:
216
+ active = {i for i, _ in self.list_tools()}
217
+ queued = {(item.id() if kind != "deregister" else item) for kind, item in self._pending}
218
+ if tool_id in active or tool_id in queued:
219
+ raise AnatomyError(f"duplicate tool id '{tool_id}'")
220
+
221
+ def _add_sensor(self, sensor) -> None:
222
+ if sensor.width() < 1:
223
+ raise AnatomyError(f"sensor '{sensor.id()}' declares width < 1")
224
+ self._sensors.append(sensor)
225
+
226
+ def _add_actuator(self, actuator) -> None:
227
+ if actuator.action_count() < 1:
228
+ raise AnatomyError(f"actuator '{actuator.id()}' declares no actions")
229
+ self._actuators.append(actuator)
230
+
231
+ def _remove(self, tool_id: str) -> None:
232
+ for group, kind in ((self._sensors, "sensor"), (self._actuators, "actuator")):
233
+ for part in group:
234
+ if part.id() == tool_id:
235
+ if len(group) == 1:
236
+ raise AnatomyError(f"cannot deregister the last {kind} ('{tool_id}')")
237
+ group.remove(part)
238
+ return
239
+ raise AnatomyError(f"no tool with id '{tool_id}'")