Metadata-Version: 2.4
Name: vcti-fileloader-hdf5
Version: 6.0.0
Summary: h5py-backed HDF5 file loader for the vcti-fileloader framework
Author: Visual Collaboration Technologies Inc.
License-Expression: LicenseRef-Proprietary
Project-URL: Repository, https://github.com/vcollab/vcti-python-fileloader-hdf5
Project-URL: Changelog, https://github.com/vcollab/vcti-python-fileloader-hdf5/blob/main/CHANGELOG.md
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: <3.15,>=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: h5py>=3.0
Requires-Dist: vcti-fileloader<8,>=7.1.0
Requires-Dist: vcti-tree<4,>=3.0.0
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Provides-Extra: lint
Requires-Dist: ruff; extra == "lint"
Provides-Extra: typecheck
Requires-Dist: mypy; extra == "typecheck"
Dynamic: license-file

# FileLoader HDF5

h5py-backed HDF5 file loader for the vcti-fileloader framework

## Overview

`vcti-fileloader-hdf5` is the HDF5 plugin for the `vcti-fileloader`
framework. It implements the `Loader` protocol: `populate(handle, tree,
parent)` walks the HDF5 hierarchy once via `h5py.File.visit()` and
attaches the file's groups and datasets as a subtree under `parent` in
any `LockableTree`. The returned subtree is structure-locked and
payload-locked.

Groups become `DataNode` payloads; datasets become `LazyDataNode`
payloads whose `shape` and `dtype` are filled in up front, so a caller
can browse the file without reading any array. A dataset with a null
dataspace (a dtype and no values) becomes a `TypeOnlyDataNode`. Every node's
`file_attributes` is the HDF5 object's own `obj.attrs`, verbatim: the
loader adds no keys of its own. Anything else a caller wants on the
nodes (the file path, tags, derived metadata) is written from the
`before_lock` hook on `populate`.

## Installation

```bash
pip install "vcti-fileloader-hdf5>=6.0.0"
```

### In `pyproject.toml` dependencies

```toml
dependencies = [
    "vcti-fileloader-hdf5>=6.0.0",
]
```

---

## Quick Start

```python
from pathlib import Path

import h5py
import numpy as np
from vcti.fileloader.core import DataNode, LazyDataNode, materialise_subtree, prepare_loader
from vcti.fileloader.hdf5 import H5pyLoader
from vcti.tree.core import DictTree, descendants

# A small file to load.
path = Path("data.h5")
with h5py.File(path, "w") as h5:
    results = h5.create_group("results")
    stress = results.create_dataset("stress", data=np.array([1.0, 2.0, 3.0]))
    stress.attrs["units"] = "MPa"
    h5.create_dataset("ids", data=np.array([10, 20, 30]))

loader = H5pyLoader()
prepare_loader(loader)  # once, before first use; raises ValidationError / SetupError
tree: DictTree[DataNode] = DictTree(DataNode())

handle = loader.load(path)
try:
    subtree_root = loader.populate(handle, tree, tree.root_handle)

    # Datasets are lazy: name, shape, dtype and attributes without a read.
    for node_handle in descendants(tree, subtree_root):
        node = tree.payload(node_handle)
        if isinstance(node, LazyDataNode):
            print(node.name, node.shape, node.dtype, dict(node.file_attributes))
            # ids (3,) int64 {}
            # stress (3,) float64 {'units': 'MPa'}

    # Read every dataset, so the tree stays usable after the file closes.
    materialise_subtree(tree, subtree_root)
finally:
    loader.unload(handle)
```

### Eager loading

`lazy=False` reads every dataset during `populate`, so the handle can
close straight away. `loader.open()` loads and unloads around the block:

```python
tree = DictTree(DataNode())
with loader.open(path) as handle:
    subtree_root = loader.populate(handle, tree, tree.root_handle, lazy=False)
```

### With a `before_lock` hook

The hook runs after the subtree is built and before it is locked. A
typical use is to attach the file path, which the loader does not do:

```python
def stamp_file_path(tree, root):
    tree.payload(root).enricher_attributes["file_path"] = str(path)

tree = DictTree(DataNode())
with loader.open(path) as handle:
    root = loader.populate(
        handle, tree, tree.root_handle, lazy=False, before_lock=stamp_file_path
    )

print(tree.payload(root).attributes["file_path"])   # data.h5
```

### Through a registry

```python
from vcti.fileloader.core import LoaderRegistry
from vcti.fileloader.hdf5 import get_loader_descriptor

registry = LoaderRegistry()
registry.register(get_loader_descriptor())
loader = registry.get("hdf5-h5py-loader").loader
```

---

## Key API

### H5pyLoader

| Method | Description |
|--------|-------------|
| `load(path, **options)` | Open the HDF5 file read-only and return an `h5py.File` handle. Options go to `h5py.File`; a `mode` other than `'r'` raises `ValueError` |
| `open(path, **options)` | Context manager — load and auto-unload |
| `populate(handle, tree, parent, *, before_lock=None, lazy=True, **options)` | Attach the file's content as a locked subtree; return the subtree root handle |
| `unload(handle)` | Close the file handle (idempotent) |
| `can_load(path)` | Check extension (`.h5`, `.hdf5`) |

### Helpers

| | Description |
|---|---|
| `get_loader_descriptor()` | Create a `LoaderDescriptor` for a `LoaderRegistry` |
| `H5pyValidator` | Verify that h5py is importable |
| `H5pySetup` | No-op setup |

---

## Lazy Datasets and the File Handle

With `lazy=True` (the default), each dataset's `data` is `None` until
its `.load()` is called, and that call reads from `handle`. Once
`loader.unload(handle)` has run, `.load()` on a node that was never
read raises `LazyLoadError`. Three ways to stay clear of that:

1. Keep the handle open for as long as the tree is in use.
2. Call `materialise_subtree(tree, subtree_root)` (from
   `vcti.fileloader.core`) before unloading, as the Quick Start does.
3. Pass `lazy=False` to `populate`.

---

## Error Handling

```python
from vcti.fileloader.core import (
    LazyLoadError,
    LoadError,
    TreeAttachmentError,
    UnloadError,
    UnsupportedFormatError,
)

try:
    with loader.open(path) as handle:
        subtree_root = loader.populate(handle, tree, tree.root_handle)
except FileNotFoundError:
    ...
except UnsupportedFormatError:
    # the file has no HDF5 signature
    ...
except LazyLoadError:
    # a lazy dataset was read after its file handle was closed
    ...
except LoadError:
    # the file could not be opened (permissions, locking, I/O, or a
    # truncated or corrupt HDF5 file), or reading it failed during populate
    ...
except UnloadError:
    # closing the file failed
    ...
except TreeAttachmentError:
    # parent is missing, deleted, or structure-locked in `tree`
    ...
except ValueError:
    # populate() was called on a closed handle, or load() was given a
    # mode other than 'r'
    ...
```

If `populate` fails partway, the partial subtree is removed before the
exception propagates — callers never see a half-built subtree. A
failure to read the file surfaces as `LoadError` with the original
exception on `__cause__`; an exception raised by `before_lock`
propagates unchanged.

---

## Dependencies

- [h5py](https://www.h5py.org/) (>=3.0)
- [numpy](https://numpy.org/) (>=1.24)
- [vcti-fileloader](https://pypi.org/project/vcti-fileloader/) (>=7.1.0, <8) — `Loader` protocol, `SubtreeBuilder`, `DataNode`, `LazyDataNode`, `TypeOnlyDataNode`, `materialise_subtree` (import from `vcti.fileloader.core`)
- [vcti-tree](https://pypi.org/project/vcti-tree/) (>=3.0.0, <4) — `LockableTree` protocol

---

## Documentation

| If you want to… | Read |
|---|---|
| Get started using the package | Quick Start above |
| Understand what the loader writes onto each node, how null-dataspace datasets and links are handled, failure semantics, the handle lifetime, and what the loader leaves out | [docs/design.md](docs/design.md) |
