Metadata-Version: 2.4
Name: zarrchive
Version: 0.2.0
Summary: Schema-driven Zarr v3 storage for camera sensor timeseries, driven by a YAML template.
Keywords: zarr,all-sky camera,timeseries,cf,acdd,image codecs
Author: Raphael Jolivet, Valentin Bauer
Author-email: Raphael Jolivet <raphael.jolivet@minesparis.psl.eu>, Valentin Bauer <valentin.bauer@minesparis.psl.eu>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
Requires-Dist: pydantic>=2.12.5
Requires-Dist: pyyaml>=6.0.3
Requires-Dist: imagecodecs>=2026.6.6
Requires-Dist: xarray>=2026.2.0
Requires-Dist: zarr>=3.4.1
Requires-Dist: cast-value-rs>=0.4.2
Requires-Dist: numpy>=2.4.3
Requires-Dist: filelock>=3.30.2
Requires-Dist: fastapi>=0.115 ; extra == 'upload'
Requires-Dist: uvicorn>=0.30 ; extra == 'upload'
Requires-Dist: stream-unzip>=0.0.100 ; extra == 'upload'
Requires-Dist: requests>=2.32 ; extra == 'upload'
Requires-Dist: fsspec>=2024.1.0 ; extra == 'upload'
Requires-Dist: aiohttp>=3.9 ; extra == 'upload'
Requires-Python: >=3.12
Project-URL: Homepage, https://git.sophia.minesparis.psl.eu/oie/zarrchive
Project-URL: Issues, https://git.sophia.minesparis.psl.eu/oie/zarrchive/-/issues
Project-URL: Repository, https://git.sophia.minesparis.psl.eu/oie/zarrchive
Provides-Extra: upload
Description-Content-Type: text/markdown

# zarrchive

Schema-driven [Zarr v3](https://zarr-specs.readthedocs.io/) storage for time
series and the static data that goes with them, including images.

A single YAML **template** describes the archive: dimensions, dtypes, chunking,
sharding, codecs, metadata. The store it creates is plain Zarr v3, readable by
any tool that speaks the spec, with or without this library.

## Install

Requires Python ≥ 3.12.

```bash
uv add zarrchive                 # or: pip install zarrchive
uv add 'zarrchive[upload]'       # plus the camera→archive transfer feature
```

Reading a store back needs only `xarray` and, when the template uses an
`imagecodecs` codec, `imagecodecs`. Never this library:

```python
import imagecodecs.zarr, xarray as xr
imagecodecs.zarr.register_codecs()
ds = xr.open_zarr("out.zarr")
```

## Python API

```python
import xarray as xr
from zarrchive import Zarrchive, load_template

load_template("cam.yaml")                        # validate without opening a store

with Zarrchive("out.zarr", "cam.yaml") as store:  # create or open
    store.write("radiance", frame, loc={"time": "2020-01-01T00:15:00"})
```

`Zarrchive(path, template)` takes the write lock for the session, creates the
store if it is absent, and restores the metadata on exit. `frame` is an
`xarray.DataArray`, or a numpy array with `dims=`. `loc` supplies the axes the
payload does not carry, by label, so `"R"` is a value of the `band` coordinate
rather than an index.

The main methods:

| Method | Effect |
|---|---|
| `write(name, data, loc=...)` | One observation, or a whole batch when the payload carries a `time` coordinate. |
| `bulk_write(name=[blocks], workers=...)` | Chunk-aligned blocks written shard by shard, without holding a shard in memory. |
| `reserve_time(labels)` | Grow the time axis before the data arrives. |
| `delete_before(cutoff)` / `delete_after(cutoff)` | Drop from one end of the time axis. |
| `finalize()` | Write the global attributes and consolidate metadata. Done for you on exit from a `with` block. |

Details in [Writing](docs/writing.md) and the [Python API](docs/api.md).

## CLI

```bash
zarrchive init examples/out.zarr -s examples/template.yml -a examples/meta.yml
```

Creates a store, or updates the metadata of one that exists. The layout of an
array is fixed when it is created, so a re-run with the same options does
nothing, and an option that contradicts the store on disk is refused rather than
ignored.

```bash
zarrchive init STORE -s TEMPLATE [-a ATTRIBUTES]
                  [--separator .|/] [--no-shard]
                  [--shard DIMENSION=SIZE] [-n/--dry-run]
```

`-a` reads placeholder values from a YAML, JSON or INI file. `--shard time=96`
sets the shard size along the time axis, `--no-shard` writes one storage object
per chunk, and `-n` prints the plan without touching the store. Metadata is
always consolidated, so a reader opens the store in one request.

```bash
zarrchive import examples/out.zarr -v captures -b examples
```

Fills one variable from image files. One file fills one chunk, the pattern's
placeholders give the coordinates, and the file supplies the dimensions the
pattern does not name. No dimension is assumed: a single calibration file is a
pattern with no time group. The pattern defaults to the one the store records for
the variable (`-p` overrides it), and `-b` sets the folder it is resolved against
(the current directory by default).

The store is the source of truth, so `import` takes no template. Because every
variable is materialised at `init`, its dimensions, dtype, chunking, sharding,
codec and default pattern are all read back from the store; a store that does not
carry them is refused with a clear message rather than guessed at.

A PNG or TIFF re-encoded into a JPEG array is refused unless you pass
`--allow-lossy`; a JPEG file stored into a JPEG array keeps its bytes. `--rmse`
caps the drift of a lossy re-encode, and `--workers` sets how many processes
encode shards.

See [Command line](docs/cli.md).

## Quickstart

**1. Describe the store.** One file, validated on load. Unknown fields, bad
dtypes and impossible chunk/shard combinations fail here, before any data moves.

```yaml
# cam.yaml
dimensions:
    time:                 # a block declares the coordinate variable too
        size: expand      # grows as observations arrive
        type: uint64
        grid: {frequency: PT15M, grid_tolerance: PT1S}   # omit for a free axis
        attributes: {units: seconds since 1970-01-01 00:00:00}
    band:
        values: [R, G1, B, G2]    # static; size and type inferred from the labels
    y: auto               # taken from the first frame written, fixed after that
    x: auto

chunks: {time: 1, band: -1, y: -1, x: -1}    # one frame per chunk; -1 = whole axis
shards: {time: 96, band: -1, y: -1, x: -1}   # 96 chunks per file on disk

variables:
    radiance:
        dimensions: [time, band, y, x]
        type: float32
        encoding: {name: imagecodecs_jpegxl, args: {lossless: true}}
        attributes: {units: W m-2 sr-1, _FillValue: .nan}

attributes:
    Conventions: CF-1.13, ACDD-1.3
    title: All-sky camera radiance
```

Prefer a fixed size over `auto` when the geometry is known. An axis declared
`auto` has no length until the first write, so its arrays start against a zero
length and are rebuilt once, when a file sizes the axis. An image size that is
fixed in practice is better written as an integer, which creates every array at
its real shape from the start.

**2. Write to it.** Creating the store writes every array's metadata and any
static coordinates; re-opening an existing store with the same template is a
no-op.

```python
from zarrchive import Zarrchive

with Zarrchive("out.zarr", "cam.yaml") as store:
    store.write("radiance", frame, loc={"time": "2020-01-01T00:15:00"})
```

A payload that carries a `time` dimension *and* coordinate is a whole batch: the
axis is reserved once and each shard written once.

**3. Read it back.** Plain xarray, as in Install above.

## Example

A small, runnable dataset lives in [`examples/`](examples/): a colour image
variable, a boolean calibration mask, four JPEG captures in
`images/2024-08-13/`, and the metadata file that fills the template's
placeholders. It is complete enough to run both commands and read the store
back, and small enough to read end to end.

```bash
# 1. Create the store. -a fills the template's {placeholders}.
zarrchive init examples/out.zarr -s examples/template.yml -a examples/meta.yml

# 2. Fill the image variable from the four captures. No -s: the store
#    describes itself, and no -p either: the template's source pattern is
#    stored in the variable's metadata and reused.
zarrchive import examples/out.zarr -v captures -b examples

# 3. Import the single calibration mask, a PNG with no time axis.
zarrchive import examples/out.zarr -v mask -b examples
```

Read it back with plain xarray, as any reader would:

```python
import imagecodecs.zarr, xarray as xr
imagecodecs.zarr.register_codecs()

xr.open_zarr("examples/out.zarr").sizes
# Frozen({'time': 4, 'y': 212, 'x': 221, 'band': 3})

xr.open_zarr("examples/out.zarr", group="calibration")["mask"]
# <xarray.DataArray 'mask' (y: 212, x: 221)> bool
```

The template declares its `time` and `band` coordinates inline, in the
`dimensions` section, and keeps only the two data variables in `variables`:
`captures[time, y, x, band]` in JPEG, and `mask[y, x]` in a `calibration` group.
`y` and `x` are `auto`, so their size comes from the first file imported.

[`examples/notebook.ipynb`](examples/notebook.ipynb) opens the same store with
`xarray`, lists its groups and variables, and renders a capture, an animation of
the four, and the mask. Its outputs are saved, so it reads without running.

## What it does

- Layout and metadata live in a validated template, not in calling code.
- The time axis is either pinned to a fixed grid, where jitter snaps onto slots
  and anything further off is rejected, or free, holding the exact instants it is
  given.
- Appends land at the end, and written rows are never rewritten or shifted.
  Deletion also only ever removes from an end.
- Appending or deleting touches the chunks it must and no others. The archive is
  never rebuilt.
- The template's CF and ACDD attributes are written into the store and restored
  after every write.
- Encoding goes through the codec the template names: JPEG-XL, JPEG2000, ZFP or
  Blosc/Zstd, with the axis order each needs, plus optional float-to-integer
  quantization.
- Adding a variable to the template and re-opening creates its array alongside
  the others, leaving old data in place.
- An open store holds an exclusive lock for its whole session, so two writers
  cannot interleave.

## Documentation

Start here if you want to do more than write one frame:

| Page | What it covers |
|---|---|
| **[Command line](docs/cli.md)** | `zarrchive init` and `zarrchive import`: creating a store from a shell, filling a variable from image files, and what a re-run can and cannot change. |
| **[Template YAML](docs/template.md)** | Every field of the template: dimensions, chunks and shards, variables, groups, encodings, quantization, the time axis, placeholders. |
| **[Writing](docs/writing.md)** | The two time models, append-only rules, reserving, single vs. batch vs. bulk writes, metadata edits, locking. |
| **[Reading](docs/reading.md)** | Opening a store with xarray, codec registration, consolidated metadata, what a reader needs. |
| **[Deleting](docs/deletion.md)** | `delete_before` / `delete_after`, why two mechanisms, and how shard size becomes a retention decision. |
| **[Upload client and server](docs/upload.md)** | Shipping a day from a camera to an archive and reclaiming it, with authentication and Docker. |
| **[Python API](docs/api.md)** | Every member of `Zarrchive` and the module map. |
| **[Storage layout](docs/storage-layout.md)** | Chunks, shards, and where the write cost goes. |
| **[Example notebook](examples/notebook.ipynb)** | Loading the example store with xarray: its groups and variables, one capture, an animation, the mask. Outputs saved, so it reads without running. |

The template format has its own versioned contract in
[`schema/schema.yml`](schema/schema.yml), kept in step with the code by a test.

## Project layout

| Path | Purpose |
|---|---|
| [`src/zarrchive/`](src/zarrchive/) | The library: pure logic (`schema`, `time_grid`, `planning`, `chunking`, `encoding`, `structure`) and a thin I/O shell (`cam_store`, `store_writer`, `append`). |
| [`src/zarrchive/codecs/`](src/zarrchive/codecs/) | Turns a template's `encoding:` block into zarr codecs, with the transposes image codecs need. |
| [`src/zarrchive/cli/`](src/zarrchive/cli/) | The `zarrchive` command: one module per subcommand, on top of the same API. |
| [`src/zarrchive/upload/`](src/zarrchive/upload/) | The optional camera→archive transfer. |
| [`schema/`](schema/) | The template format, as a versioned contract. |
| [`docs/`](docs/) | The detail behind this README. |
| [`tests/zarrchive/`](tests/zarrchive/) | Test suite and YAML fixtures. |

The code follows a functional-core / imperative-shell split: as much logic as
possible lives in pure functions, and filesystem access stays in a few thin
modules. Each module's docstring says which kind it is.

## Development

```bash
uv sync --group dev --extra upload
make test   # uv run pytest
make lint   # ruff check, ruff format --check, ty check
```
