{ "cells": [ { "cell_type": "markdown", "id": "0827618f", "metadata": {}, "source": [ "# Build your own view\n", "\n", "Companion notebook for the RDDAC [documentation](https://rddac.readthedocs.io). It is written to stand on its own: every step is annotated so the notebook reads top to bottom.\n", "\n", "## Walkthrough\n", "\n", "1. load the dataset and list the published RecordSets,\n", "2. look up the available source fields in the `field-map` RecordSet,\n", "3. append a custom RecordSet with slicing,\n", "4. mix in `process-parameters` CSV columns,\n", "5. inspect the resolved source fields and transforms,\n", "6. stream records of the view with `rddac.streaming.iter_view`,\n", "7. register the prefab recipes from `rddac.views`,\n", "8. read the experiment index directly.\n", "\n", "## Assumptions\n", "\n", "- This notebook lives in `notebooks/` of the repository and reads the dataset from `../data/` (on your machine: the directory `rddac download` wrote to).\n", "- The data directory contains `metadata.json`, `process_parameters.csv`, and at least the bundled `sample.zip`." ] }, { "cell_type": "code", "execution_count": 1, "id": "1d078b0e", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:01:56.801007Z", "iopub.status.busy": "2026-07-07T09:01:56.800907Z", "iopub.status.idle": "2026-07-07T09:01:58.620063Z", "shell.execute_reply": "2026-07-07T09:01:58.619307Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "rddac 0.1.0\n" ] } ], "source": [ "import warnings\n", "warnings.filterwarnings('ignore')\n", "\n", "import rddac\n", "print('rddac', rddac.__version__)\n", "\n", "from pathlib import Path\n", "DATA_DIR = Path('../data')\n", "# DATA_DIR = Path('./data') # uncomment instead when running from the repository root\n", "assert (DATA_DIR / 'metadata.json').is_file(), f'{DATA_DIR} does not contain the dataset'" ] }, { "cell_type": "markdown", "id": "fe132196", "metadata": {}, "source": [ "## 1. Load the dataset\n", "\n", "`rddac.load(data_dir=...)` reads `metadata.json` from `data_dir`, registers any zip files it finds there so the HDF5 members can be read in place, and exposes the published RecordSets through `ds.metadata.record_sets`. Listing them first is good practice: a custom view is only ever needed when none of the published ones fit.\n", "\n", "Four h5-backed views ship with the manifest — `force-curve`, `thickness`, `pointcloud-op10`, and `pointcloud-op20` — plus the `process-parameters` index and the `field-map` lookup table that custom views build on." ] }, { "cell_type": "code", "execution_count": 2, "id": "b12ab07e", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:01:58.622101Z", "iopub.status.busy": "2026-07-07T09:01:58.621779Z", "iopub.status.idle": "2026-07-07T09:01:58.760576Z", "shell.execute_reply": "2026-07-07T09:01:58.759921Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "published RecordSets:\n", " process-parameters\n", " field-map\n", " pointcloud-op10\n", " pointcloud-op20\n", " force-curve\n", " sheet-thickness\n", " oil-thickness\n", " thickness\n" ] } ], "source": [ "ds = rddac.load(data_dir=DATA_DIR)\n", "print('published RecordSets:')\n", "for rs in ds.metadata.record_sets:\n", " print(f' {rs.id}')" ] }, { "cell_type": "markdown", "id": "a8dd6ea5", "metadata": {}, "source": [ "## 2. The `field-map` RecordSet\n", "\n", "Every HDF5 dataset that a view can pull from is declared once in the manifest's `field-map` RecordSet: the field name is what goes on the right-hand side of `add_view(fields=...)`, and the description documents what the array contains. The helper below prints the full lookup table, so there is no need to memorise anything." ] }, { "cell_type": "code", "execution_count": 3, "id": "a32d80a1", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:01:58.762219Z", "iopub.status.busy": "2026-07-07T09:01:58.762108Z", "iopub.status.idle": "2026-07-07T09:01:58.765113Z", "shell.execute_reply": "2026-07-07T09:01:58.764392Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " force_data Press force and process signals, time series. Columns: [time (s), load_cell_1..4 (kN), punch_temp (degC), punch_pos (mm), total_force (kN)]. HDF5 path: force/data. Shape (per file): (1140, 8).\n", " oil_thickness_data Lubricant film measurement along a sensor traverse. Columns: [sensor_position (mm), oil_value (g/m^2)]. HDF5 path: oil_thickness/data. Shape (per file): (421, 2).\n", " pointcloud_op10_luminescence Flattened luminescence/intensity buffer of the OP10 scan, pixel-aligned with op10/z. HDF5 path: pointcloud/op10/luminescence. Shape (per file): (6400000).\n", " pointcloud_op10_z Flattened height (Z) buffer of the OP10 laser scan (after deep drawing), row-major over a y_shape x x_shape grid (see group attributes). Reshape and apply per-pixel calibration to recover a 3D surface (see the rddacs preprocessing step). HDF5 path: pointcloud/op10/z. Shape (per file): (6400000).\n", " pointcloud_op20_luminescence Flattened luminescence/intensity buffer of the OP20 scan, pixel-aligned with op20/z. HDF5 path: pointcloud/op20/luminescence. Shape (per file): (6400000).\n", " pointcloud_op20_z Flattened height (Z) buffer of the OP20 laser scan (after cutting), row-major over a y_shape x x_shape grid (see group attributes). HDF5 path: pointcloud/op20/z. Shape (per file): (6400000).\n", " sheet_thickness_data Blank sheet thickness measurement along a sensor traverse. Columns: [sensor_position (mm), sheet_thickness (um)]. HDF5 path: sheet_thickness/data. Shape (per file): (208, 2).\n" ] } ], "source": [ "from rddac.croissant import field_map\n", "\n", "for name, f in field_map(ds).items():\n", " print(f' {name:32s} {(f.description or \"\")}')" ] }, { "cell_type": "markdown", "id": "934737c7", "metadata": {}, "source": [ "## 3. Append a custom RecordSet\n", "\n", "`rddac.add_view(ds, name, fields)` mutates `ds` in place. After it returns, the new RecordSet is part of `ds.metadata.record_sets` and can be streamed exactly like a published one.\n", "\n", "Each entry of `fields` maps an **alias** (the dict key) to a **source field** from `field-map`, plus an optional **index selection** along the first axis. The raw `force/data` table has shape `(n, 8)` with `n` varying per experiment, which makes it a good demonstrator for every supported shape:\n", "\n", "- `force` keeps the whole table -> `(n, 8)`, the form for a model that consumes the full press stroke.\n", "- `force_head` takes rows `0..99` -> `(100, 8)`, a fixed-size window (handy for batching, see the PyTorch notebook).\n", "- `first_sample` takes row `0` -> `(8,)`, a single snapshot; the integer index drops the axis.\n", "- `sheet` is the shortcut form: a bare string means \"the whole field\", same as `(\"...\", None)`.\n", "\n", "The published manifest on DaRUS is **not** modified; only the in-memory dataset grows." ] }, { "cell_type": "code", "execution_count": 4, "id": "32d95a8e", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:01:58.766703Z", "iopub.status.busy": "2026-07-07T09:01:58.766601Z", "iopub.status.idle": "2026-07-07T09:01:58.840512Z", "shell.execute_reply": "2026-07-07T09:01:58.839804Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "record_sets after add_view:\n", " process-parameters\n", " field-map\n", " pointcloud-op10\n", " pointcloud-op20\n", " force-curve\n", " sheet-thickness\n", " oil-thickness\n", " thickness\n", " my-view\n" ] } ], "source": [ "rddac.add_view(\n", " ds,\n", " 'my-view',\n", " fields={\n", " 'force': ('force_data', None), # whole (n, 8) table\n", " 'force_head': ('force_data', list(range(100))), # fixed 100-row window\n", " 'first_sample': ('force_data', 0), # one row\n", " 'sheet': 'sheet_thickness_data', # whole field, shortcut form\n", " },\n", ")\n", "\n", "print('record_sets after add_view:')\n", "for rs in ds.metadata.record_sets:\n", " print(f' {rs.id}')" ] }, { "cell_type": "markdown", "id": "455ccba5", "metadata": {}, "source": [ "## 4. Mix in process-parameters columns\n", "\n", "`add_view` also accepts **qualified** field IDs of the form `\"/\"`, which lets a single view combine HDF5 fields from `field-map` with CSV columns from `process-parameters`. The two sources are joined on the experiment id automatically: `mlcroissant` requires an explicit cross-source `references` link to validate the manifest, and `add_view` injects one on the first field-map field for you, so no manual join wiring is needed on the consumer side.\n", "\n", "Iteration via `rddac.streaming.iter_view` returns one record per experiment with both kinds of fields side by side: HDF5 arrays and CSV columns appear under their respective aliases. (At this layer the CSV goes through pandas, so strings arrive as `str`, not `bytes`.)" ] }, { "cell_type": "code", "execution_count": 5, "id": "7d72add9", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:01:58.842118Z", "iopub.status.busy": "2026-07-07T09:01:58.842012Z", "iopub.status.idle": "2026-07-07T09:02:00.165174Z", "shell.execute_reply": "2026-07-07T09:02:00.164278Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "experiment 0: force_head.shape=(100, 8) geometry='concave' blankholder_force=100 kN oil_type='coarse' split='val'\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "experiment 4500: force_head.shape=(100, 8) geometry='convex' blankholder_force=100 kN oil_type='coarse' split='train'\n" ] } ], "source": [ "rddac.add_view(\n", " ds,\n", " 'my-view-with-params',\n", " fields={\n", " 'force_head': ('force_data', list(range(100))),\n", " 'geometry': 'process-parameters/geometry',\n", " 'blankholder_force': 'process-parameters/blankholder_force',\n", " 'oil_type': 'process-parameters/oil_type',\n", " 'split': 'process-parameters/split',\n", " },\n", ")\n", "\n", "for rec in rddac.streaming.iter_view(\n", " 'my-view-with-params',\n", " data_dir=DATA_DIR,\n", " dataset=ds,\n", " sim_ids=[0, 4500],\n", "):\n", " print(f\"experiment {rec['_sim_id']:4d}: force_head.shape={rec['force_head'].shape} \"\n", " f\"geometry={rec['geometry']!r} blankholder_force={rec['blankholder_force']} kN \"\n", " f\"oil_type={rec['oil_type']!r} split={rec['split']!r}\")" ] }, { "cell_type": "markdown", "id": "975c5ab0", "metadata": {}, "source": [ "## 5. Inspect the new view's fields\n", "\n", "Each field of the view stores a **source** (the field-map entry it pulls from) and an **optional JSONPath transform** that records the index selection:\n", "\n", "- `(\"field_id\", 0)` -> JSONPath `$[0]`\n", "- `(\"field_id\", [0, 1, ...])` -> JSONPath `$[0,1,...]`\n", "- `\"field_id\"` or `(\"field_id\", None)` -> no transform (whole field)\n", "\n", "Printing the resolved transforms is a quick way to verify the view was built as expected before you start training on it." ] }, { "cell_type": "code", "execution_count": 6, "id": "93d5169b", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:02:00.167153Z", "iopub.status.busy": "2026-07-07T09:02:00.166906Z", "iopub.status.idle": "2026-07-07T09:02:00.171823Z", "shell.execute_reply": "2026-07-07T09:02:00.170983Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " my-view/force <- field-map/force_data transforms=[]\n", " my-view/force_head <- field-map/force_data transforms=['$[0,1,2,3,4,5,6,7,8,9,10,11...']\n", " my-view/first_sample <- field-map/force_data transforms=['$[0]']\n", " my-view/sheet <- field-map/sheet_thickness_data transforms=[]\n" ] } ], "source": [ "view = next(rs for rs in ds.metadata.record_sets if rs.id == 'my-view')\n", "for f in view.fields:\n", " transforms = [t.json_path for t in (f.source.transforms or [])]\n", " shown = [t if len(t) <= 30 else t[:27] + '...' for t in transforms]\n", " print(f' {f.id:24s} <- {f.source.uuid:28s} transforms={shown}')" ] }, { "cell_type": "markdown", "id": "048ec63b", "metadata": {}, "source": [ "## 6. Stream records of the view\n", "\n", "> **Heads up.** Do **not** iterate an h5-backed view through `ds.records(view)`. `mlcroissant` walks the whole FileSet at iterator setup and materialises every HDF5 member of every referenced zip before applying any filter — with the full release local (two ~40 GB zips) it did not produce a first record within several minutes in our tests. This path is fine for CSV-backed RecordSets (step 8 below) but the wrong tool for the measurement data.\n", ">\n", "> Two replacements both work and both scale to the full release. They share the same lazy `experiment id -> local zip` index, open a zip only when a record is actually requested, and silently skip experiments whose zip is missing on a partial download. Both accept the `dataset=` kwarg so the in-memory `add_view` mutation flows through:\n", ">\n", "> ```python\n", "> # No-PyTorch path: plain Python generator (this notebook + 06_streaming).\n", "> for rec in rddac.streaming.iter_view('my-view', data_dir=DATA_DIR, dataset=ds):\n", "> ...\n", ">\n", "> # PyTorch path: torch.utils.data.IterableDataset for DataLoader batching (03_pytorch).\n", "> from rddac import RDDACDataset\n", "> custom_ds = RDDACDataset(view='my-view', data_dir=DATA_DIR, dataset=ds)\n", "> ```\n", "\n", "Each record is a dict keyed by the aliases declared in `add_view`, with values already sliced according to the JSONPath transform, plus a private `_sim_id` key carrying the experiment id. `first_sample` comes out as `(8,)` (the `$[0]` transform dropped the first axis) while `force` keeps the full per-experiment `(n, 8)` shape — note how `n` differs between the two experiments below." ] }, { "cell_type": "code", "execution_count": 7, "id": "a007a9b9", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:02:00.173504Z", "iopub.status.busy": "2026-07-07T09:02:00.173322Z", "iopub.status.idle": "2026-07-07T09:02:00.221711Z", "shell.execute_reply": "2026-07-07T09:02:00.221031Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "experiment 0\n", " force shape=(1140, 8) dtype=float32\n", " force_head shape=(100, 8) dtype=float32\n", " first_sample shape=(8,) dtype=float32\n", " sheet shape=(208, 2) dtype=float32\n", "experiment 4500\n", " force shape=(720, 8) dtype=float32\n", " force_head shape=(100, 8) dtype=float32\n", " first_sample shape=(8,) dtype=float32\n", " sheet shape=(208, 2) dtype=float32\n" ] } ], "source": [ "import numpy as np\n", "\n", "for rec in rddac.streaming.iter_view('my-view', data_dir=DATA_DIR, dataset=ds, sim_ids=[0, 4500]):\n", " print(f\"experiment {rec['_sim_id']:4d}\")\n", " for k, v in rec.items():\n", " if k.startswith('_'):\n", " continue\n", " arr = np.asarray(v)\n", " print(f' {k:14s} shape={arr.shape} dtype={arr.dtype}')" ] }, { "cell_type": "markdown", "id": "b31d5795", "metadata": {}, "source": [ "## 8. Read the experiment index\n", "\n", "The `process-parameters` RecordSet is sourced from the CSV (not from the h5 zips), so the plain `mlcroissant` records iterator works regardless of which zips are downloaded locally — this is the one RecordSet where `ds.records(...)` is the canonical access path. For tabular work, `pandas.read_csv(DATA_DIR / 'process_parameters.csv')` is one line away." ] }, { "cell_type": "code", "execution_count": 8, "id": "949f0eb6", "metadata": { "execution": { "iopub.execute_input": "2026-07-07T09:02:00.223417Z", "iopub.status.busy": "2026-07-07T09:02:00.223299Z", "iopub.status.idle": "2026-07-07T09:02:00.247872Z", "shell.execute_reply": "2026-07-07T09:02:00.247287Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " process-parameters/index = 0\n", " process-parameters/experiment_id = 1\n", " process-parameters/category = 0\n", " process-parameters/geometry = b'concave'\n", " process-parameters/blankholder_force = 100\n", " process-parameters/mean_punch_temp = 20.2\n", " process-parameters/oil_type = b'coarse'\n", " process-parameters/has_pointcloud = True\n", " process-parameters/has_oil = True\n", " process-parameters/split = b'val'\n" ] } ], "source": [ "for n, rec in enumerate(ds.records('process-parameters'), start=1):\n", " if n == 1:\n", " for k, v in rec.items():\n", " print(f' {k:42s} = {v}')\n", " if n >= 1:\n", " break" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.14" } }, "nbformat": 4, "nbformat_minor": 5 }