Metadata-Version: 2.4
Name: zarrchive
Version: 0.3.0
Summary: Schema-driven Zarr v3 storage for time series and their static data, including images, 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 definition of a Zarr archive, with easy python API and CLI tools to append to it, including support of image codecs.

## Install

Requires Python 3.12 or newer.

```bash
uv add zarrchive                 # or: pip install zarrchive
```


## 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)`  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` names the axes the payload does not carry, by label.

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

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

### Command `create`

```bash
zarrchive create <out.zarr> -s <template.yaml> [-a <meta.yml>] [-n/--dry-run]
```

`create` builds a store from a template, or updates one that already exists. An array's layout is fixed when the array is created.


`-a` reads placeholder values from a YAML, JSON or INI file. `-n` prints the plan without touching the store. 

### Command `import`

```bash
zarrchive import <out.zarr> -v <var_name> -b <input_dir> -p './images/{yyyy}-{mm}-{dd}T{HH}:{MM}.jpg'
```

`import` fills one variable from image files. 

`-p` provides the patterns of input images.

By default, this command only allows lossless storage : JPG images are copied as is in jpeg chunks (passthrough).



## Quickstart

**1. Describe the store.** 

A template define the dimensions, variables, encoding and metadata of the Zarr store.

It can contain `"{placeholders}"` that are replaced at runtime using the `-a` option of the `create` command.

```yaml
dimensions:

    time: # Full definition of a dimension, with attributes and type
        size: expand # This dimensions expands as data is appended
        type: uint64
        grid: {frequency: PT15M, grid_tolerance: PT1S}
        attributes: {units: seconds since 1970-01-01 00:00:00} # CF conventions

    band: #  Bands of the images. Static. size and type inferred from the labels
        values: [R, G1, B, G2]
        
    # Short defitions of dimensions
    y: auto  # Infered 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 (=one day) per file on disk

variables:
    radiance:
        dimensions: [time, band, y, x]
        type: float32

        # JPG codec : passthrough of the input images
        encoding: {name: imagecodecs_jpegxl, args: {lossless: true}}

        attributes: {units: W m-2 sr-1, _FillValue: .nan}

# Extra matadata, should follow the recommendations of ACDD and "Climate and Forecast" conventions
attributes:

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

See a full example [here](./examples/template.yml)


**2. Write to it.** 

`frame` should be a chunk of `DataArray` or `numpy` array of the proper size. 
`loc` provides the coordinates of the chunk : the dimensions that are not provided in the `DataArray`


```python
from zarrchive import Zarrchive

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

**3. Read it back.**

The output Zarr arichive doesn't require ` zarrchive`.

It can be opened with vanilla `xarray` (+`imagecodecs`)


```python
import imagecodecs.zarr
import xarray as xr

# The arrays name image codecs (JPEG here); register them before opening.
imagecodecs.zarr.register_codecs()

# A store is a hierarchy of groups
tree = xr.open_datatree("out.zarr", zarr_format=3, consolidated=False)
tree
```

See the full [notebook here](./examples/notebook.ipynb)


## 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.

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

# 2. Fill the image variable from the four captures.
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
```

## Documentation

Detailed documentation is available here :

| Page                                                 | What it covers                                                                                                                                              |
| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **[Command line](docs/cli.md)**                 | `zarrchive create` and `zarrchive import`: building 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.


# Authors 

* [Valentin Bauer](mailto:valentin.bauer@minesparis.psl.eu)
* [Raphael Jolivet](mailto:raphael.jolivet@minesparis.psl.eu)

# License

[MIT](./LICENSE)
