{ "cells": [ { "cell_type": "markdown", "id": "9bbc94a2", "metadata": {}, "source": [ "# Loose HDF5 recipe\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. the `rddac download --extract --remove-zip` workflow that leaves loose `.h5` files on disk,\n", "2. simulate it here by extracting three members of `sample.zip` into a throwaway directory,\n", "3. inspect the loose layout,\n", "4. read `process_parameters.csv` with pandas and filter the rows of interest,\n", "5. open each loose `.h5` directly with `h5py`,\n", "6. stream the loose layout with `rddac.streaming.iter_view` (this works — unlike the zip-only manifest path).\n", "\n", "## Assumptions\n", "\n", "- This notebook writes a throwaway copy into the system temp directory; the project-local `../data` stays untouched.\n", "- `rddac.open_h5` and `RDDACDataset` walk the **zips** referenced by the manifest. Once `--remove-zip` deletes them, those two are gone for the extracted experiments — but `rddac.streaming.iter_view` recognises loose files natively (a deliberate difference from `ddacs`), so the view machinery keeps working." ] }, { "cell_type": "code", "execution_count": 1, "id": "15a888aa", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T12:50:54.717372Z", "iopub.status.busy": "2026-07-06T12:50:54.717230Z", "iopub.status.idle": "2026-07-06T12:50:56.471033Z", "shell.execute_reply": "2026-07-06T12:50:56.470389Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "rddac 0.1.0\n", "loose layout goes to: /tmp/rddac_loose_w6y5flzl\n" ] } ], "source": [ "import warnings\n", "warnings.filterwarnings('ignore')\n", "\n", "import shutil\n", "import tempfile\n", "import zipfile\n", "from pathlib import Path\n", "\n", "import h5py\n", "import numpy as np\n", "import pandas as pd\n", "\n", "import rddac\n", "print('rddac', rddac.__version__)\n", "\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'\n", "LOOSE_DIR = Path(tempfile.mkdtemp(prefix='rddac_loose_'))\n", "print('loose layout goes to:', LOOSE_DIR)" ] }, { "cell_type": "markdown", "id": "94651cc5", "metadata": {}, "source": [ "## 1. Download with extract + remove\n", "\n", "`rddac download --extract --remove-zip` fetches the bundle, unzips each archive next to the zip, and deletes the zip on success. The result is a directory of loose `NNNN.h5` files instead of `.zip` archives. Run this once from a shell:\n", "\n", "```bash\n", "rddac download --small --extract --remove-zip --out ./data -y\n", "```\n", "\n", "The zip members sit at the archive root, so extraction leaves the `.h5` files directly beside `metadata.json` and `process_parameters.csv`. (`rddac.streaming` also recognises an `h5/` subdirectory if you prefer to tidy them away.)\n", "\n", "The dataset is already on disk in this repository, so instead of re-downloading, the next cell **simulates** the workflow: it extracts three members of `sample.zip` into the throwaway directory and copies the two index files alongside — byte-for-byte the layout the CLI command produces." ] }, { "cell_type": "code", "execution_count": 2, "id": "8eb7962d", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T12:50:56.473126Z", "iopub.status.busy": "2026-07-06T12:50:56.472916Z", "iopub.status.idle": "2026-07-06T12:50:56.511143Z", "shell.execute_reply": "2026-07-06T12:50:56.510524Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "extracted ['0000.h5', '0500.h5', '1002.h5']\n" ] } ], "source": [ "members = ['0000.h5', '0500.h5', '1002.h5']\n", "with zipfile.ZipFile(DATA_DIR / 'h5' / 'sample.zip') as zf:\n", " for name in members:\n", " zf.extract(name, LOOSE_DIR)\n", "\n", "shutil.copy(DATA_DIR / 'process_parameters.csv', LOOSE_DIR)\n", "shutil.copy(DATA_DIR / 'metadata.json', LOOSE_DIR)\n", "print('extracted', members)" ] }, { "cell_type": "markdown", "id": "2bd1d7f9", "metadata": {}, "source": [ "## 2. Inspect the loose layout\n", "\n", "After extraction, `metadata.json` and `process_parameters.csv` sit at the root next to the loose experiment files." ] }, { "cell_type": "code", "execution_count": 3, "id": "dc1a4129", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T12:50:56.512984Z", "iopub.status.busy": "2026-07-06T12:50:56.512881Z", "iopub.status.idle": "2026-07-06T12:50:56.515733Z", "shell.execute_reply": "2026-07-06T12:50:56.515155Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 0000.h5 10.0 MB\n", " 0500.h5 10.0 MB\n", " 1002.h5 10.0 MB\n", " metadata.json 0.0 MB\n", " process_parameters.csv 0.4 MB\n" ] } ], "source": [ "for entry in sorted(LOOSE_DIR.iterdir()):\n", " size_mb = entry.stat().st_size / 1e6\n", " print(f' {entry.name:28s} {size_mb:8.1f} MB')" ] }, { "cell_type": "markdown", "id": "9951a844", "metadata": {}, "source": [ "## 3. Read `process_parameters.csv` with pandas\n", "\n", "The CSV is the experiment index: one row per experiment id, with every process parameter exposed as a named column. Filter it in pandas before touching any HDF5 file." ] }, { "cell_type": "code", "execution_count": 4, "id": "2eb84796", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T12:50:56.517430Z", "iopub.status.busy": "2026-07-06T12:50:56.517334Z", "iopub.status.idle": "2026-07-06T12:50:56.529868Z", "shell.execute_reply": "2026-07-06T12:50:56.529240Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "rows: 9000, columns: ['index', 'experiment_id', 'category', 'geometry', 'blankholder_force', 'mean_punch_temp', 'oil_type', 'has_pointcloud', 'has_oil', 'split']\n", "\n", " index experiment_id category geometry blankholder_force mean_punch_temp oil_type has_pointcloud has_oil split\n", "0 0 1 0 concave 100 20.2 coarse True True val\n", "1 1 2 0 concave 100 20.3 coarse True True train\n", "2 2 3 0 concave 100 20.4 coarse True True val\n" ] } ], "source": [ "params = pd.read_csv(LOOSE_DIR / 'process_parameters.csv')\n", "print(f'rows: {len(params)}, columns: {list(params.columns)}')\n", "print()\n", "print(params.head(3).to_string())" ] }, { "cell_type": "markdown", "id": "637767a7", "metadata": {}, "source": [ "## 4. Iterate the loose files with `h5py`\n", "\n", "Walk the (filtered) rows, build the zero-padded path, skip experiments whose `.h5` is missing locally, and open each one with `h5py.File`. Below: take the concave subset, then read the sheet-thickness traverse from every loose file that landed on disk. The raw traverse contains negative sensor-error spikes, so the summary masks `value <= 0` first (see the visualization notebook). With three extracted files the loop yields three lines." ] }, { "cell_type": "code", "execution_count": 5, "id": "040f1a48", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T12:50:56.531678Z", "iopub.status.busy": "2026-07-06T12:50:56.531577Z", "iopub.status.idle": "2026-07-06T12:50:56.698366Z", "shell.execute_reply": "2026-07-06T12:50:56.697749Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "concave experiments in CSV: 4500 of 9000\n", " experiment 0 oil_type=coarse sheet thickness 985.9 - 1000.4 um (206 valid samples)\n", " experiment 500 oil_type=fine sheet thickness 950.1 - 988.7 um (206 valid samples)\n", " experiment 1002 oil_type=medium sheet thickness 983.2 - 998.4 um (206 valid samples)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "opened 3 loose h5 file(s)\n" ] } ], "source": [ "concave = params.query(\"geometry == 'concave'\")\n", "print(f'concave experiments in CSV: {len(concave):>5d} of {len(params)}')\n", "\n", "found = 0\n", "for _, row in concave.iterrows():\n", " h5_path = LOOSE_DIR / f\"{row['index']:04d}.h5\"\n", " if not h5_path.is_file():\n", " continue\n", " with h5py.File(h5_path, 'r') as f:\n", " thickness = f['sheet_thickness/data'][:]\n", " valid = thickness[thickness[:, 1] > 0, 1]\n", " print(f\" experiment {row['index']:>4d} oil_type={row['oil_type']:<7s} \"\n", " f\"sheet thickness {valid.min():7.1f} - {valid.max():7.1f} um ({len(valid)} valid samples)\")\n", " found += 1\n", "print(f'\\nopened {found} loose h5 file(s)')" ] }, { "cell_type": "markdown", "id": "c86a5447", "metadata": {}, "source": [ "## 5. Stream the loose layout with `iter_view`\n", "\n", "`rddac.streaming.iter_view` builds a unified index at startup that recognises **both** loose `NNNN.h5` files (at the data-dir root or under `h5/`) and zipped archives — preferring loose files when both exist, because direct `h5py` reads skip the per-record `BytesIO` round trip. Pointing `data_dir` at the loose directory is therefore all it takes; views, slicing, `where=` filters, and the numpy export from the streaming notebook keep working unchanged.\n", "\n", "The zip-backed single-file helper does *not* survive the transition: `rddac.open_h5` walks the manifest-mapped zips only, so on this directory it raises `FileNotFoundError` — reach for `h5py.File(path)` directly instead (step 4), the file name is just the zero-padded experiment id." ] }, { "cell_type": "code", "execution_count": 6, "id": "d8443bbf", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T12:50:56.700220Z", "iopub.status.busy": "2026-07-06T12:50:56.700118Z", "iopub.status.idle": "2026-07-06T12:50:56.947223Z", "shell.execute_reply": "2026-07-06T12:50:56.946651Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " experiment 0: force_data shape=(1140, 8)\n", " experiment 500: force_data shape=(1140, 8)\n", " experiment 1002: force_data shape=(1140, 8)\n", "\n", "open_h5 on the loose layout: FileNotFoundError: 0000.h5 not found in any locally mapped zip under PosixPath('/tmp/rddac_loose_w6...\n" ] } ], "source": [ "for rec in rddac.streaming.iter_view('force-curve', data_dir=LOOSE_DIR):\n", " print(f\" experiment {rec['_sim_id']:>4d}: force_data shape={rec['force_data'].shape}\")\n", "\n", "try:\n", " rddac.open_h5(0, data_dir=LOOSE_DIR)\n", "except FileNotFoundError as e:\n", " print(f'\\nopen_h5 on the loose layout: FileNotFoundError: {str(e)[:80]}...')" ] }, { "cell_type": "markdown", "id": "bc5a3c38", "metadata": {}, "source": [ "## 6. Clean up\n", "\n", "The loose copy was a demonstration artifact; remove it so repeated runs start fresh." ] }, { "cell_type": "code", "execution_count": 7, "id": "5a1801f1", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T12:50:56.949016Z", "iopub.status.busy": "2026-07-06T12:50:56.948915Z", "iopub.status.idle": "2026-07-06T12:50:56.955859Z", "shell.execute_reply": "2026-07-06T12:50:56.955169Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "removed /tmp/rddac_loose_w6y5flzl\n" ] } ], "source": [ "shutil.rmtree(LOOSE_DIR)\n", "print('removed', LOOSE_DIR)" ] } ], "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 }