Metadata-Version: 2.4
Name: robot-data-collector-irsl
Version: 0.1.0a1
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 ; extra == 'preview'
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.0a1 is an API preview.** It supports this collector's raw format and its numeric
`collector_schema_version=1` robomimic export—not arbitrary image/RL datasets.
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.0a1
# or, in a uv project:
uv add --prerelease allow robot-data-collector-irsl==0.1.0a1
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  # release consumer-owned shared arrays before shutdown
                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 caller-owned: drop the last batch and any derived views before iterator
  teardown/process exit. Closing the iterator cannot free arrays you still retain.
- One HDF5 reading thread, explicit small buffers and `num_workers=0` are safe defaults.
  Multiprocessing has startup/RSS costs and is not always faster. The admission budget covers
  numeric buffers, not interpreter/HDF5 total RSS; retaining old batches needs extra memory.

## 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.

## Preview and known limitations

- Optional `pip install --pre 'robot-data-collector-irsl[preview]==0.1.0a1'` adds MuJoCo;
  it is not installed automatically by the core. Passive preview uses measured pose and
  `mj_forward`, **not** `mj_step` or robot command replay. MJB requires the descriptor's exact
  engine version; the generic extra does not guarantee compatibility. **Actual MuJoCo/GUI
  tests have not yet been executed**; missing display/engine/model falls back to graphs.
- 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.
- In0.1.0a1, seeking before the parent's first primary sample can jump to that future in-clip
  sample; sample-aligned In avoids this known review-only issue. Cancelling cold replay-index
  preparation can leave temporary SQLite files/journals in `.cache`; repeated cancellations
  use disk space. Long-range sample stepping can scan its range. These are not silently
  described as fixed by the public reader release.
- Camera/RGB/depth, policy training, cloud upload and real motion replay are not implemented.
- A historical long Grain matrix emitted a shared-memory cleanup warning; its complete cause
  remains unqualified. The initial installed example also retained its final caller-owned batch
  until process teardown. Releasing that batch before iterator.close() fixed the reproduced
  basic example warning, with actual worker2 subprocess coverage. This is not a universal
  shutdown/leak-free guarantee. Checkpoint restore is qualified only for tested combinations.
- 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.0a1 release notes](docs/releases/0.1.0a1.md). The installed examples and templates above
remain usable even when those checkout documents are not installed.
