Metadata-Version: 2.4
Name: robot-data-collector-irsl
Version: 0.1.0a2
Summary: Robot episode collection and portable NumPy/HDF5 readers with Grain data loading
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Topic :: Scientific/Engineering
Requires-Dist: numpy
Requires-Dist: h5py
Requires-Dist: pyzmq
Requires-Dist: robot-msg-irsl==0.5.0
Requires-Dist: textual
Requires-Dist: grain==0.2.18
Requires-Dist: mujoco==3.13.0
Requires-Dist: pillow>=11.0,<13
Requires-Dist: pyrealsense2==2.59.1.11053 ; sys_platform == 'linux' or sys_platform == 'win32'
Requires-Python: >=3.11
Provides-Extra: preview
Description-Content-Type: text/markdown

# robot-data-collector-irsl

Portable **NumPy/HDF5 robot episode readers**, a default **Google Grain** training pipeline,
and a receive-only collector/TUI for `switch_controller`.

**0.1.0a2 is an alpha RGB-D/API preview.** It supports this collector's native recordings,
numeric schema1 and RGB-D schema2 robomimic-compatible exports—not arbitrary image/RL datasets.
RGB is high-quality JPEG; native uint16 depth is lossless PNG. MuJoCo is installed by default.
The distribution is `robot-data-collector-irsl`; import `robot_data_collector`; command `rdc`.
MIT licensed. No JAX, PyTorch, TensorFlow, robomimic package or PyArrow is required.

## Install

Python **3.11+**:

```bash
python -m pip install --pre robot-data-collector-irsl==0.1.0a2
# or, in a uv project:
uv add --prerelease allow robot-data-collector-irsl==0.1.0a2
rdc --help
```

These are the intended public-index commands; see the release report for actual upload status.
Grain **0.2.18 is a default dependency**, not an extra. Its native wheels for CPython3.11
cover Linux x86_64/aarch64 (glibc), macOS ARM64 and Windows AMD64. Do not infer macOS Intel,
Windows ARM64 or Alpine support. The **native live collector/raw repository uses POSIX locks**
and is currently qualified on Linux; the typed reader/Grain path has not been runtime-tested
on every wheel platform. Installing a wheel is not evidence of full-platform support.

## Fast training reads

Training data should be exported once to typed HDF5. Do not decode/realign raw envelopes on
every training epoch.

```python
from robot_data_collector import RobomimicDataset, make_grain_dataset


def main():
    with RobomimicDataset.open("training-export", split="train") as dataset:
        print(dataset.observation_keys, dataset.action_names, dataset.fps)
        with dataset.sequences(length=32, stride=1, action_space="normalized") as source:
            sample = source[0]
            print(sample["actions"].shape)  # (32, action_dimension)
            pipeline = make_grain_dataset(
                source,
                batch_size=32,
                shuffle=True,
                seed=42,
                num_workers=2,
                prefetch=1,
            )
            iterator = iter(pipeline)
            batch = None
            try:
                for batch in iterator:
                    print(batch["actions"].shape)  # (B, 32, action_dimension)
            finally:
                batch = None  # optional: release caller-owned output memory
                iterator.close()


if __name__ == "__main__":
    main()
```

- Sequences never cross demonstration/clip boundaries; incomplete trailing sequences are
  excluded, not silently padded. Train/valid splits remain grouped by original parent episode.
- `observations[key]`, `actions`, `time_ns`, `valid`, `sequence_mask`, `demo_index` and
  `start_index` are NumPy leaves. `valid` is not the padding mask or split mask.
- `action_space="physical"` uses the stored inverse transform; no inferred units/bounds.
- `source.read_batch([5, 0, 5])` coalesces nearby reads while preserving order and duplicates.
  Ordinary Grain batching does **not** promise to call that bulk reader.
- Each worker lazily opens its own HDF5 handle. Pickles contain paths/options/metadata,
  never live file handles. Use `__main__` for spawn and close both iterator and source.
  Yielded batches are ordinary caller-owned arrays: retaining them does not hold worker/SHM
  resources. Closing the iterator cannot free arrays you still retain; budget them separately.
- `num_workers=0` reads synchronously with no prefetch thread. Positive worker counts use
  project-owned spawn readers, explicit credits and bounded numeric pipes; public Grain
  source/shuffle/batch operations still determine finite order and values. No upstream process
  prefetch, shared-memory output, whole-batch pickle, queue feeder or private Grain API is used.
  Multiprocessing has startup/RSS costs and is not always faster. Admission covers numeric,
  HDF5 cache/chunk scratch and transport buffers, not total RSS. See the public API for
  close deadlines, late-start ownership and semantic checkpoint compatibility.

## Read native recordings without modifying them

```python
from robot_data_collector import Dataset

with Dataset.open("recording-copy", mode="snapshot") as dataset:
    info = next(dataset.iter_episodes(status="complete"))
    with dataset.episode(info.id) as episode:
        print(episode.primary, episode.sources, episode.recorded_root)
        print(episode.fields(max_events=256))  # bounded, explicitly sampled discovery
        window = episode.load_window("0.1", "0.3", {"q": episode.primary}, strict=True)
        print(window.fields["q"].values, window.fields["q"].time_ns)
```

`snapshot` is for an **externally immutable offline copy**: moved/copied data is allowed;
source-side cache/locks/metadata are not written. An external disposable cache is cleaned
on close. It is not concurrent live snapshot isolation. The default `mode="live"` retains
writable repository coordination and deletion-protecting OS leases; no silent fallback occurs.

Native fields are **asynchronous** and can have different timestamps/lengths. Decimal-string
or `Decimal` seconds map to int64 ns; intervals are `[start, stop)`. Missing/empty/zero remain
distinct. `load_window` is capped at100,000 rows/64MiB. Use `iter_events` or an explicit recipe
with `episode.view(...).iter_aligned(...)` for large reads. `view` is nonpersistent;
`episode.clip(...)` deliberately saves metadata and is not allowed in snapshot mode.

## Try the installed package without a robot

Run from any empty working directory; no checkout paths or private APIs are required:

```bash
rdc demo --root ./demo-data --seconds 3 --hz 100
rdc episodes --root ./demo-data
rdc init-config --template recipe-demo --output ./demo-recipe.toml
python -m robot_data_collector.examples.export_demo \
  --root ./demo-data --recipe ./demo-recipe.toml --output ./demo-training
rdc verify ./demo-training
python -m robot_data_collector.examples.public_read --root ./demo-data
python -m robot_data_collector.examples.train_grain \
  --dataset ./demo-training --split all --length 8 --batch-size 4 --workers 2
```

The demo publishes synthetic14-coordinate state/action only on **random loopback ports**,
never controller ports. Its bounds are synthetic, not real-robot limits. Example export begins
at an actual primary sample, not an arbitrary timestamp that could lack a causal observation.
Existing paths are not overwritten. `init-config` requires an existing parent directory.

## Receive-only collection and TUI

```bash
# Copy the INSTALLED template, then edit root/hosts/fields for your deployment.
rdc init-config --template collector --output ./collector.toml
rdc tui --config ./collector.toml

# State-only inspection of an already running local simulator/controller:
rdc init-config --template state-only --output ./state.toml
rdc record --config ./state.toml --task inspection --seconds 3
```

The state `28400` address is the **controller host**. Action `28402` is the **external target
publisher host**, not necessarily that same machine. `28401` is ControllerCommand. Templates
are explicit local examples, not device autodiscovery. The collector does not start/stop,
reconfigure, restart or send motion commands to the controller. State-only capture is not
training-ready; an explicit observation/action recipe is required.

| Key | TUI action |
|---|---|
| `F1`, `F2`, `F3` | collect, episode library, export |
| `R`, `S`, `Ctrl-Q` | start recording, stop/drain/save, finalize and quit |
| Review `Space`, arrows, Shift+arrows | play/pause, sample step, larger step |
| `I`, `O`, `L`, `G`, `+/-` | In/Out, range loop, exact time, zoom |

Use Review & Trim to select with mouse/keyboard and save a non-destructive clip/revision.
`O` includes the current sample by snapping to its next boundary; storage remains `[In, Out)`.
Task/text/select focus does not issue collection shortcuts. Episode/clip/export counts are
separate. Trash/restore preserve IDs; permanent purge needs explicit confirmation and refuses
referenced or leased data. Startup failures show **SERVICE FAILED**, not an endless connection
claim. Configuration-relative `../data` paths are supported with traversal/symlink defenses.

## 3D preview (default installation)

The current source includes **MuJoCo3.13.0 by default**. No `--extra preview` is needed:

```bash
uv sync
uv run rdc tui --config configs/dual_nero_preview.toml
```

For a package installation, create the installed profile instead of relying on a checkout:

```bash
rdc init-config --template simulation-preview --output ./simulation.toml
rdc tui --config ./simulation.toml
```

The simulator must already provide native StateSnapshot PUB28405 and read-only model TCP28430.
This profile records new episodes under `data/dual-nero-preview`, separate from state-only data.
In the TUI, record with `R`, stop/save with `S`, then **F2 → Review & Trim → scroll down →
`3D preview / close`**. The robot appears in a **separate MuJoCo window**, not in the terminal.
The CLI equivalent is `rdc replay EPISODE_ID --root DATASET_ROOT --preview`.

**0.1.0a2 installs MuJoCo by default**; the historical0.1.0a1 used an optional extra.
A state-only episode does not gain recorded native pose or model metadata just because today's
configuration is changed. Keep it for numeric review, or record a new episode using
`simulation-preview`.

Passive preview applies measurements with `mj_forward`, **not** `mj_step` or robot commands.
MJB requires the descriptor's exact engine version, even if some other MuJoCo release installs
successfully. Missing display/model or an engine mismatch gives a diagnostic and graph-only
fallback. Small actual-engine mapping and passive-window tests have run with3.13.0; a live
simulator/robot model is qualified separately when its existing services are available.

## RGB-D: compact recording, replay and training

```bash
# Without hardware: actual capture/codec/storage path, synthetic acquisition only.
rdc demo --rgbd --root ./rgbd-data --seconds 3 --hz 200
python -m robot_data_collector.examples.export_rgbd_demo \
  --root ./rgbd-data --output ./rgbd-training
rdc verify ./rgbd-training
python -m robot_data_collector.examples.read_rgbd \
  --dataset ./rgbd-training --camera front --length 1 --workers 2 --max-mib 256 --transform

# With one D4xx: edit hosts/root/serial BEFORE starting collection.
rdc init-config --template realsense --output ./camera.toml
rdc tui --config ./camera.toml
rdc init-config --template recipe-rgbd --output ./rgbd-recipe.toml
```

The reference native profile is **RGB640×480 + Z16 depth640×480 at30FPS**. The installed
`realsense` template requires the camera and the configured state/external-action publishers.
A missing required camera prevents recording; no fallback profile is silently negotiated.
The SDK is a default dependency on supported Linux/Windows wheels; macOS has no SDK marker.
Live collection uses POSIX locks and is qualified on Linux, not Windows despite SDK availability.
Enumeration on the reference host found **no device**: physical sensor capture remains unverified.

- Native storage keeps one atomic header/JPEG/PNG pair: RGB **JPEG90,4:4:4**, depth **lossless
  uint16 PNG level1**, including invalid0 and65535. Calibration, native unaligned dimensions,
  directed extrinsics, depth scale, device frame clocks and host receipt times are preserved.
  No automatic normalization, alignment, hole filling, filtering or resampling occurs.
- **F2 → Review & Trim → camera selector → RGB / Depth preview** opens a separate passive
  GLFW window (RGB left, depth colormap right). Seek/I/O/loop share the graph playhead.
  Display colorization does not change saved depth; missing/stale frames are explicit.
- `episode.iter_frames(camera="front", decode=False)` returns lazy pair references. Use
  `decode=True` for owned uint8 HWC RGB / uint16 HW depth. Snapshot reads do not write source.
- Export schema2 keeps RGB uint8 HWC under `obs` and raw depth under `collector/media`.
  `RobomimicDataset.sequences(..., depth_keys=("front",))` explicitly selects Z16. Typed
  training epochs use HDF5, not Pillow again. `rgb_chw` and `depth_metres` are explicit helpers.
  Raw Z16 is **not** registered in stock robomimic's clipping depth modality.
- Typed export is a separate dense pixel copy and may be substantially larger than native
  JPEG/PNG, particularly with held images. Preflight reserves decoded output plus free-space
  reserve. Recording does not automatically double-store/export every episode.
- Image carry-in is opt-in (`ImageSpec` default false); the packaged recipe explicitly uses
  true with100ms maximum age. RGB/depth always come from the same causal at-or-before pair.
  Original timestamp/ref/age are preserved; repeated device frames cannot refresh age.

See [RGB-D API and schema](docs/rgbd-loading.md) and [measured quality/capacity/performance](docs/rgbd-performance.md).

## Other known limitations
- External robomimic v0.5.0 loader/full BC training tests remain opt-in and unexecuted.
  `env_args.type=-1` is an offline-only sentinel, not an instantiable simulator/rollout promise.
- Core codec is `robot-msg-irsl==0.5.0`; newer0.5.1 planning RobotAction bytes may be rejected.
  Raw preservation is not semantic compatibility. No automatic dependency migration occurs.
- Published action is **intent**, not applied/accepted output. Controller-local TUI actions
  are not observed on the wire. PUB/SUB is best effort; send time is not measurement time,
  and clock IDs do not establish physical synchronization. No zero-impact/lossless claim.
- Alpha2 fixes the historical a1 no-predecessor future-seek, repeated range-step scan and
  cancelled cold-index owned temporary-file cleanup issues with regressions. Native first
  index/carry-in reconstruction can still scan history; there is no universal instant-seek claim.
- Policy training, cloud upload and real motion replay are not implemented.
- Historical upstream Grain SHM execution emitted cleanup warnings; a subsequent upstream
  copied-IPC candidate hung on large-batch close and retained queue FDs. Those failures remain
  documented, not suppressed. Current source uses project-owned workers and numeric pipes;
  finite RGB-D/numeric, retained handles, fault/close and checkpoint regressions are separate
  evidence, not a universal OS-stall/shutdown guarantee. The historical288-case performance
  matrix is not relabelled as current throughput; a new short4-case comparison is recorded.
- Synthetic post-optimization1000Hz state+action30s capture completed on the reference host
  with60,127 admitted=committed and zero observed local queue overflow. Historical pre-fix
  runs overflowed. This is **not** a real payload, indefinite, or upstream-loss guarantee.
  Typed reading benchmarks also record worker startup and memory penalties.

## Development and verification

In a source checkout: `uv sync --locked`, `uv run pytest`, `uv run ruff check .`,
`uv run ruff format --check .`, `uv build --no-sources`. No controller is launched by these
commands. Release builds use exact new-name artifacts; no datasets/cache/credentials are shipped.

Source-checkout details: [public API](docs/public-api.md), [reading measurements](docs/reading-performance.md),
[collection use](docs/usage.md), [format](docs/data-format.md), [recipes](docs/recipes.md),
[recovery](docs/recovery.md), [capture measurements](docs/performance.md),
[0.1.0a2 release notes](docs/releases/0.1.0a2.md). The installed examples and templates above
remain usable even when those checkout documents are not installed.
