Skip to content

Commit

Permalink
Merge pull request #27 from TomNicholas/docs
Browse files Browse the repository at this point in the history
Roughout of Sphinx Docs
  • Loading branch information
norlandrhagen authored Mar 18, 2024
2 parents 1f34fd0 + 350d806 commit 46d32a9
Show file tree
Hide file tree
Showing 14 changed files with 306 additions and 11 deletions.
10 changes: 6 additions & 4 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ name: CI

on:
push:
branches:
- main
branches: [ "main" ]
paths-ignore:
- 'docs/**'
pull_request:
branches:
- main
branches: [ "main" ]
paths-ignore:
- 'docs/**'
schedule:
- cron: "0 0 * * *"

Expand Down
23 changes: 23 additions & 0 deletions .readthedocs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details

# Required
version: 2

# Set the version of Python and other tools you might need
build:
os: ubuntu-20.04
tools:
python: "mambaforge-4.10"

# Build documentation in the doc/ directory with Sphinx
sphinx:
configuration: docs/conf.py

# Optionally declare the Python requirements required to build your docs
conda:
environment: ci/doc.yml
python:
install:
- method: pip
path: .
15 changes: 15 additions & 0 deletions ci/doc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
name: virtualizarr-docs
channels:
- conda-forge
- nodefaults
dependencies:
- python>=3.9
- "sphinx"
- "pydata_sphinx_theme"
- "sphinx-autodoc-typehints"
- "sphinx_copybutton"
- "sphinx_togglebutton"
- "sphinx_design"
- "myst_nb"
- pip:
- -e ..
20 changes: 20 additions & 0 deletions docs/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#

# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = .
BUILDDIR = _build

# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

.PHONY: help Makefile

# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
21 changes: 21 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# API Reference


## Manifests

```{eval-rst}
.. autoclass:: virtualizarr.manifests.manifest.ChunkManifest
:members:
```

```{eval-rst}
.. autoclass:: virtualizarr.manifests.ManifestArray
:members:
```

## Xarray

```{eval-rst}
.. autoclass:: virtualizarr.xarray.open_dataset_via_kerchunk
:members:
```
48 changes: 48 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information

project = "virtualizarr"
copyright = "2024, Thomas Nicholas"
author = "Thomas Nicholas"

# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration


extensions = [
"myst_nb",
"sphinx.ext.autodoc",
"sphinx.ext.extlinks",
"sphinx_autodoc_typehints",
"sphinx_copybutton",
"sphinx_togglebutton",
"sphinx_design",
]
templates_path = ["_templates"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]


# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output

html_theme = "pydata_sphinx_theme"
html_theme_options = {
"repository_url": "https://github.com/TomNicholas/VirtualiZarr",
"repository_branch": "main",
"path_to_docs": "docs",
}

html_logo = "_static/_future_logo.png"

html_static_path = ["_static"]


# issues
# pangeo logo
# dark mode/lm switch
# needs to add api ref
7 changes: 7 additions & 0 deletions docs/dev_status_roadmap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Development Status and Roadmap

VirtualiZarr is ready to use for many of the tasks that we are used to using kerchunk for, but the most general and powerful vision of this library can only be implemented once certain changes upstream in Zarr have occurred.

VirtualiZarr is therefore evolving in tandem with developments in the Zarr Specification, which then need to be implemented in specific Zarr reader implementations (especially the Zarr-Python V3 implementation). There is an [overall roadmap for this integration with Zarr](https://hackmd.io/t9Myqt0HR7O0nq6wiHWCDA), whose final completion requires acceptance of at least two new Zarr Enhancement Proposals (the ["Chunk Manifest"](https://github.com/zarr-developers/zarr-specs/issues/287) and ["Virtual Concatenation"](https://github.com/zarr-developers/zarr-specs/issues/288) ZEPs).

Whilst we wait for these upstream changes, in the meantime VirtualiZarr aims to provide utility in a significant subset of cases, for example by enabling writing virtualized zarr stores out to the existing kerchunk references format, so that they can be read by fsspec today.
14 changes: 14 additions & 0 deletions docs/how_it_works.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# How Does This Work?


I'm glad you asked! We can think of the problem of providing virtualized zarr-like access to a set of legacy files in some other format as a series of steps:

1) **Read byte ranges** - We use the various [kerchunk file format backends](https://fsspec.github.io/kerchunk/reference.html#file-format-backends) to determine which byte ranges within a given legacy file would have to be read in order to get a specific chunk of data we want.
2) **Construct a representation of a single file (or array within a file)** - Kerchunk's backends return a nested dictionary representing an entire file, but we instead immediately parse this dict and wrap it up into a set of `ManifestArray` objects. The record of where to look to find the file and the byte ranges is stored under the `ManifestArray.manifest` attribute, in a `ChunkManifest` object. Both steps (1) and (2) are handled by the `'virtualizarr'` xarray backend, which returns one `xarray.Dataset` object per file, each wrapping multiple `ManifestArray` instances (as opposed to e.g. numpy/dask arrays).
3) **Deduce the concatenation order** - The desired order of concatenation can either be inferred from the order in which the datasets are supplied (which is what `xr.combined_nested` assumes), or it can be read from the coordinate data in the files (which is what `xr.combine_by_coords` does). If the ordering information is not present as a coordinate (e.g. because it's in the filename), a pre-processing step might be required.
4) **Check that the desired concatenation is valid** - Whether called explicitly by the user or implicitly via `xr.combine_nested/combine_by_coords/open_mfdataset`, `xr.concat` is used to concatenate/stack the wrapped `ManifestArray` objects. When doing this xarray will spend time checking that the array objects and any coordinate indexes can be safely aligned and concatenated. Along with opening files, and loading coordinates in step (3), this is the main reason why `xr.open_mfdataset` can take a long time to return a dataset created from a large number of files.
5) **Combine into one big dataset** - `xr.concat` dispatches to the `concat/stack` methods of the underlying `ManifestArray` objects. These perform concatenation by merging their respective Chunk Manifests. Using xarray's `combine_*` methods means that we can handle multi-dimensional concatenations as well as merging many different variables.
6) **Serialize the combined result to disk** - The resultant `xr.Dataset` object wraps `ManifestArray` objects which contain the complete list of byte ranges for every chunk we might want to read. We now serialize this information to disk, either using the [kerchunk specification](https://fsspec.github.io/kerchunk/spec.html#version-1), or in future we plan to use [new Zarr extensions](https://github.com/zarr-developers/zarr-specs/issues/287) to write valid Zarr stores directly.
7) **Open the virtualized dataset from disk** - The virtualized zarr store can now be read from disk, skipping all the work we did above. Chunk reads from this store will be redirected to read the corresponding bytes in the original legacy files.

**Note:** Using the `kerchunk` library alone will perform a similar set of steps overall, but because (3), (4), (5), and (6) are all performed by the `kerchunk.combine.MultiZarrToZarr` function, and no internal abstractions are exposed, the design is much less modular, and the use cases are limited by kerchunk's API surface.
35 changes: 35 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# VirtualiZarr

**VirtualiZarr creates virtual Zarr stores for cloud-friendly access to archival data, using familiar xarray syntax.**

VirtualiZarr grew out of [discussions](https://github.com/fsspec/kerchunk/issues/377) on the [kerchunk repository](https://github.com/fsspec/kerchunk), and is an attempt to provide the game-changing power of kerchunk in a zarr-native way, and with a familiar array-like API.

## What's the difference between VirtualiZarr and Kerchunk?

The Kerchunk idea solves an incredibly important problem: accessing big archival datasets via a cloud-optimized pattern, but without copying or modifying the original data in any way. This is a win-win-win for users, data engineers, and data providers. Users see fast-opening zarr-compliant stores that work performantly with libraries like xarray and dask, data engineers can provide this speed by adding a lightweight virtualization layer on top of existing data (without having to ask anyone's permission), and data providers don't have to change anything about their legacy files for them to be used in a cloud-optimized way.

However, kerchunk's current design is limited:
- Store-level abstractions make combining datasets complicated, idiosyncratic, and requires duplicating logic that already exists in libraries like xarray,
- The kerchunk format for storing on-disk references requires the caller to understand it, usually via [`fsspec`](https://github.com/fsspec/filesystem_spec) (which is currently only implemented in python).

VirtualiZarr aims to build on the excellent ideas of kerchunk whilst solving the above problems:
- Using array-level abstractions instead is more modular, easier to reason about, allows convenient wrapping by high-level tools like xarray, and is simpler to parallelize,
- Writing the virtualized arrays out as a valid Zarr store directly (through new Zarr Extensions) will allow for Zarr implementations in any language to read the archival data.

## Licence

Apache 2.0

## Site Contents

```{toctree}
:maxdepth: 2
self
installation
usage
how_it_works
dev_status_roadmap
api
```
22 changes: 22 additions & 0 deletions docs/installation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Installation


```shell
git clone https://github.com/TomNicholas/VirtualiZarr
cd VirtualiZarr
pip install -e .
```


## Install Test Dependencies

```shell
pip install '-e .[test]'
```


## Install Docs Dependencies

```shell
pip install '-e .[docs]'
```
35 changes: 35 additions & 0 deletions docs/make.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
@ECHO OFF

pushd %~dp0

REM Command file for Sphinx documentation

if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=.
set BUILDDIR=_build

%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.https://www.sphinx-doc.org/
exit /b 1
)

if "%1" == "" goto help

%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end

:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%

:end
popd
49 changes: 49 additions & 0 deletions docs/usage.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Usage


Let's say you have a bunch of legacy files (e.g. netCDF) which together tile to form a large dataset. Let's imagine you already know how to use xarray to open these files and combine the opened dataset objects into one complete dataset. (If you don't then read the [xarray docs page on combining data](https://docs.xarray.dev/en/stable/user-guide/combining.html).)

```python
ds = xr.open_mfdataset(
'/my/files*.nc',
engine='h5netcdf',
combine='by_coords', # 'by_coords' requires reading coord data to determine concatenation order
)
ds # the complete lazy xarray dataset
```

However, you don't want to run this set of xarray operations every time you open this dataset, as running commands like `xr.open_mfdataset` can be expensive. Instead you would prefer to just be able to open a virtualized Zarr store (i.e. `xr.open_dataset('my_virtual_store.zarr')`), as that would open instantly, but still give access to the same data underneath.

**`VirtualiZarr` allows you to use the same xarray incantation you would normally use to open and combine all your files, but cache that result as a virtual Zarr store.**

What's being cached here, you ask? We're effectively caching the result of performing all the various consistency checks that xarray performs when it combines newly-encountered datasets together. Once you have the new virtual Zarr store xarray is able to assume that this checking has already been done, and trusts your Zarr store enough to just open it instantly.

Creating the virtual store looks very similar to how we normally open data with xarray:

```python
import virtualizarr # required for the xarray backend and accessor to be present

virtual_ds = xr.open_mfdataset(
'/my/files*.nc',
engine='virtualizarr', # virtualizarr registers an xarray IO backend that returns ManifestArray objects
combine='by_coords', # 'by_coords' stills requires actually reading coordinate data
)

virtual_ds # now wraps a bunch of virtual ManifestArray objects directly

# cache the combined dataset pattern to disk, in this case using the existing kerchunk specification for reference files
virtual_ds.virtualize.to_kerchunk('combined.json', format='json')
```

Now you can open your shiny new Zarr store instantly:

```python
fs = fsspec.filesystem('reference', fo='combined.json')
m = fs.get_mapper('')

ds = xr.open_dataset(m, engine='kerchunk', chunks={}) # normal xarray.Dataset object, wrapping dask/numpy arrays etc.
```

(Since we serialized the cached results using the kerchunk specification then opening this zarr store still requires using fsspec via the kerchunk xarray backend.)

No data has been loaded or copied in this process, we have merely created an on-disk lookup table that points xarray into the specific parts of the original netCDF files when it needs to read each chunk.
12 changes: 9 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

[project]
name = "virtualizarr"
description = "Create virtual Zarr stores from archival data using xarray API"
Expand All @@ -18,20 +19,25 @@ classifiers = [
"Programming Language :: Python :: 3.11",
]
requires-python = ">=3.9"
dynamic = ["version"]
dependencies = [
"xarray",
"kerchunk",
"ujson",
"pydantic",
"packaging",
]
dynamic = ["version"]

[project.optional-dependencies]
test = [
"pytest"
"pre-commit",
"pytest-mypy",
"pytest",
]





[project.urls]
Home = "https://github.com/TomNicholas/VirtualiZarr"
Documentation = "https://github.com/TomNicholas/VirtualiZarr/blob/main/README.md"
Expand Down
6 changes: 2 additions & 4 deletions virtualizarr/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from .manifests import ManifestArray # type: ignore # noqa
from .xarray import ( # type: ignore # noqa
VirtualiZarrDatasetAccessor,
open_dataset_via_kerchunk,
)
from .xarray import VirtualiZarrDatasetAccessor # type: ignore # noqa
from .xarray import open_dataset_via_kerchunk # noqa: F401

0 comments on commit 46d32a9

Please sign in to comment.