Metadata-Version: 2.4
Name: vcti-fileloader-numpy
Version: 2.0.0
Summary: NumPy-backed NPY, NPZ, and CSV file loaders for the vcti-fileloader framework
Author: Visual Collaboration Technologies Inc.
License-Expression: LicenseRef-Proprietary
Project-URL: Repository, https://github.com/vcollab/vcti-python-fileloader-numpy
Project-URL: Changelog, https://github.com/vcollab/vcti-python-fileloader-numpy/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.26
Requires-Dist: vcti-fileloader<8,>=7.0.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 NumPy

NumPy-backed NPY, NPZ, and CSV file loaders for the vcti-fileloader framework

## Overview

`vcti-fileloader-numpy` ships three loader plugins for the
`vcti-fileloader` framework, all implemented against NumPy. Each
implements the `Loader` protocol: `populate(handle, tree, parent)`
attaches the file's content as a subtree under `parent` in any
`LockableTree`, and the returned subtree is structure-locked and
payload-locked.

- **`NpyLoader`** loads a `.npy` file as one array node. `mmap_mode`
  memory-maps the file instead of reading it.
- **`NpzLoader`** loads a `.npz` archive as one node per array. The
  nodes are `LazyDataNode`s by default, with `shape` and `dtype` filled
  in up front, so a caller can browse the archive without reading any
  array.
- **`CsvLoader`** loads delimited text (`.csv`, `.tsv`, `.txt`) through
  `numpy.genfromtxt` as one array node, and records the column names on
  the subtree root when the file is read with a header row.

The loaders add no attributes of their own beyond those column names.
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-numpy>=2.0.0"
```

### In `pyproject.toml` dependencies

```toml
dependencies = [
    "vcti-fileloader-numpy>=2.0.0",
]
```

---

## Quick Start

### NPY

```python
from pathlib import Path

import numpy as np
from vcti.fileloader.core import DataNode, prepare_loader
from vcti.fileloader.numpy import NpyLoader
from vcti.tree.core import DictTree

# A small file to load.
npy_path = Path("data.npy")
np.save(npy_path, np.array([1.0, 2.0, 3.0]))

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

with loader.open(npy_path) as handle:
    subtree_root = loader.populate(handle, tree, tree.root_handle)

[child] = tree.children(subtree_root)
print(tree.payload(child).data)   # [1. 2. 3.]
```

Memory-map a large file instead of reading it into memory:

```python
array = loader.load(npy_path, mmap_mode="r")
print(array[:2])   # [1. 2.]
del array          # the memmap keeps the file open until it is collected
```

### NPZ

```python
from vcti.fileloader.core import LazyDataNode, materialise_subtree
from vcti.fileloader.numpy import NpzLoader

npz_path = Path("data.npz")
np.savez(npz_path, ids=np.array([10, 20, 30]), stress=np.ones((2, 2)))

npz_loader = NpzLoader()
prepare_loader(npz_loader)
tree = DictTree(DataNode())

with npz_loader.open(npz_path) as handle:
    subtree_root = npz_loader.populate(handle, tree, tree.root_handle)

    # Arrays are lazy: name, shape and dtype without a read.
    for child in tree.children(subtree_root):
        node = tree.payload(child)
        assert isinstance(node, LazyDataNode)
        print(node.name, node.shape, node.dtype, node.is_loaded)

    # Read every array, so the tree stays usable after the archive closes.
    materialise_subtree(tree, subtree_root)
```

`lazy=False` reads every array during `populate`, so the handle can
close straight away:

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

### CSV / TSV

Options to `load` and `open` go to `numpy.genfromtxt`. With
`names=True` the first row is read as column names, the array is
structured, and the names are recorded on the subtree root:

```python
from vcti.fileloader.numpy import CsvLoader

csv_path = Path("data.csv")
csv_path.write_text("x,y\n1.0,2.0\n3.0,4.0\n", encoding="utf-8")

csv_loader = CsvLoader()
prepare_loader(csv_loader)
tree = DictTree(DataNode())

with csv_loader.open(csv_path, delimiter=",", names=True) as handle:
    subtree_root = csv_loader.populate(handle, tree, tree.root_handle)

print(tree.payload(subtree_root).file_attributes["columns"])   # ['x', 'y']
```

### 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 loaders do not do:

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

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

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

### Through a registry

```python
from vcti.fileloader.core import LoaderRegistry
from vcti.fileloader.numpy import (
    get_csv_loader_descriptor,
    get_npy_loader_descriptor,
    get_npz_loader_descriptor,
)

registry = LoaderRegistry()
registry.register(get_npy_loader_descriptor())
registry.register(get_npz_loader_descriptor())
registry.register(get_csv_loader_descriptor())
loader = registry.get("npy-numpy-loader").loader
```

---

## Key API

### Loaders

`NpyLoader`, `NpzLoader` and `CsvLoader` share the `Loader` protocol's
methods:

| Method | Description |
|--------|-------------|
| `load(path, **options)` | Read or open the file and return the handle |
| `open(path, **options)` | Context manager — load and auto-unload |
| `populate(handle, tree, parent, *, before_lock=None, **options)` | Attach the content as a locked subtree; return the subtree root handle |
| `unload(handle)` | Release the handle |
| `can_load(path)` | Check the file extension |

What differs between them:

| Loader | Handle | `load` options | Extensions |
|---|---|---|---|
| `NpyLoader` | the `numpy.ndarray` (`unload` is a no-op) | `mmap_mode`, `allow_pickle` | `.npy` |
| `NpzLoader` | an open `NpzFile` (`unload` closes it) | `allow_pickle`; `populate` also takes `lazy` | `.npz` |
| `CsvLoader` | the `numpy.ndarray` (`unload` is a no-op) | any `numpy.genfromtxt` keyword | `.csv`, `.tsv`, `.txt` as a hint; `load` accepts any path |

`allow_pickle` defaults to `False`: a pickled array can run arbitrary
code when it is read.

### Helpers

| | Description |
|---|---|
| `get_npy_loader_descriptor()`, `get_npz_loader_descriptor()`, `get_csv_loader_descriptor()` | Create a `LoaderDescriptor` for a `LoaderRegistry` |
| `NpyValidator`, `NpzValidator`, `CsvValidator` | Verify that NumPy is importable |
| `NpySetup`, `NpzSetup`, `CsvSetup` | No-op setup |

---

## Lazy Arrays and the Archive Handle

With `lazy=True` (the default), each NPZ array'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,
)

tree = DictTree(DataNode())
try:
    with npz_loader.open(npz_path) as handle:
        subtree_root = npz_loader.populate(handle, tree, tree.root_handle)
except FileNotFoundError:
    ...
except UnsupportedFormatError:
    # the extension is not .npy (NpyLoader) or .npz (NpzLoader)
    ...
except LazyLoadError:
    # a lazy NPZ array was read after its archive was closed
    ...
except LoadError:
    # the file could not be parsed, or an eager NPZ read failed during populate
    ...
except UnloadError:
    # closing the NPZ archive failed
    ...
except TreeAttachmentError:
    # parent is missing, deleted, or structure-locked in `tree`
    ...
except ValueError:
    # populate() was called on a closed NPZ archive
    ...
```

If `populate` fails partway, the partial subtree is removed before the
exception propagates — callers never see a half-built subtree. An
exception raised by `before_lock` propagates unchanged.

---

## Dependencies

- [numpy](https://numpy.org/) (>=1.26)
- [vcti-fileloader](https://pypi.org/project/vcti-fileloader/) (>=7.0.0, <8) — `Loader` protocol, `SubtreeBuilder`, `DataNode`, `LazyDataNode`, `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 why there are three loaders, the subtree each one builds, the lazy NPZ contract, thread safety, memory-mapped NPY, and what the loaders leave out | [docs/design.md](docs/design.md) |
