zarr-cm-tree 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 eodc
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,154 @@
1
+ Metadata-Version: 2.3
2
+ Name: zarr-cm-tree
3
+ Version: 0.1.0
4
+ Summary: GeoZarr convention attribute builders: a pyproj bridge over zarr-cm.
5
+ Author: eodc
6
+ Author-email: eodc <office@eodc.eu>
7
+ License: MIT License
8
+
9
+ Copyright (c) 2026 eodc
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+ Classifier: Intended Audience :: Science/Research
29
+ Classifier: Natural Language :: English
30
+ Classifier: Operating System :: POSIX
31
+ Classifier: Programming Language :: Python :: 3 :: Only
32
+ Classifier: Programming Language :: Python :: 3.12
33
+ Classifier: Programming Language :: Python :: 3.13
34
+ Classifier: Programming Language :: Python :: 3.14
35
+ Classifier: Topic :: Scientific/Engineering
36
+ Classifier: Topic :: Scientific/Engineering :: GIS
37
+ Classifier: Topic :: Software Development :: Libraries
38
+ Requires-Dist: pyproj>=3.6
39
+ Requires-Dist: zarr-cm>=0.4
40
+ Requires-Python: >=3.12
41
+ Project-URL: Repository, https://github.com/eodcgmbh/zarr-cm-tree
42
+ Description-Content-Type: text/markdown
43
+
44
+ # zarr-cm-tree
45
+
46
+ GeoZarr convention attribute builders — an opinionated bridge between
47
+ [pyproj](https://pyproj4.github.io/pyproj/) and
48
+ [zarr-cm](https://github.com/zarr-conventions/zarr-cm).
49
+
50
+ It produces the plain attribute dicts that make up the `attributes` block of a
51
+ Zarr v3 group or array for the GeoZarr conventions `proj:`, `spatial:` and
52
+ `multiscales`, plus an interim `dggs:` placeholder.
53
+
54
+ ```bash
55
+ uv add zarr-cm-tree
56
+ ```
57
+
58
+ ## Scope
59
+
60
+ `zarr_cm` owns the conventions themselves: schemas, validation, revisions, and
61
+ the `zarr_conventions` registry entries. This package adds only what it
62
+ deliberately does not:
63
+
64
+ - **A pyproj bridge.** `GeoZarrProj` holds a canonical `pyproj.CRS` and decides
65
+ how to serialise it — authority code when one exists, WKT2 otherwise — and
66
+ hands rioxarray a matching CRS string via `rio_input()`.
67
+ - **Domain defaults for gridded data.** `GeoZarrSpatial` defaults to `("y", "x")`
68
+ dims and `"pixel"` registration, and infers `transform_type="affine"`.
69
+ - **Layout rules the schema does not encode**, e.g. `derived_from` requires a
70
+ `transform`.
71
+ - **`geozarr_attrs`**, which emits several conventions at once together with a
72
+ matching `zarr_conventions` registry array, so the registry always describes
73
+ exactly the conventions present.
74
+
75
+ Everything returned is a plain `dict`, never a model, so it merges straight into
76
+ `xarray.Dataset.attrs`.
77
+
78
+ ## Usage
79
+
80
+ ```python
81
+ import zarr_cm_tree as gz
82
+
83
+ crs = gz.GeoZarrProj.from_user_input("EPSG:27704") # Equi7Grid EU
84
+ spatial = gz.GeoZarrSpatial(
85
+ transform=(10.0, 0.0, 5400000.0, 0.0, -10.0, 2700000.0),
86
+ shape=(10000, 10000),
87
+ )
88
+
89
+ attrs = gz.geozarr_attrs(crs=crs, spatial=spatial)
90
+ # {"proj:code": "EPSG:27704", "spatial:transform": [...], "zarr_conventions": [...]}
91
+
92
+ group.attrs.update(attrs) # or ds.attrs.update(attrs)
93
+ ```
94
+
95
+ Add a pyramid by passing the layout, one entry per level:
96
+
97
+ ```python
98
+ attrs = gz.geozarr_attrs(
99
+ crs=crs,
100
+ multiscales=[
101
+ {"asset": "0"},
102
+ {"asset": "1", "derived_from": "0", "transform": {"scale": [2.0, 2.0]}},
103
+ ],
104
+ )
105
+ ```
106
+
107
+ The individual builders (`build_proj_attrs`, `build_spatial_attrs`,
108
+ `build_multiscales_attrs`, `build_zarr_conventions`, `merge_attrs`) are public
109
+ too, for callers that want to assemble attrs themselves.
110
+ `build_zarr_conventions` accepts the legacy `"geo-proj"` spelling as an alias for
111
+ `"proj"`, since `zarr_cm.ConventionName` still carries it and so do stores
112
+ written before the upstream rename.
113
+
114
+ ## Convention revisions
115
+
116
+ Each convention in `zarr_cm` ships at one or more numbered *revisions*. A
117
+ revision fixes the convention's JSON Schema: which attribute keys are legal, how
118
+ strictly they are validated, and the `schema_url` written into the store's
119
+ `zarr_conventions` array.
120
+
121
+ This package writes at whatever revision the installed `zarr_cm` declares
122
+ latest, rather than pinning one — a pin nobody updates goes stale, and every
123
+ store records the revision that wrote it in its own `schema_url`, so drift stays
124
+ auditable after the fact. Reading is unaffected either way:
125
+ `zarr_cm.<convention>.detect()` sniffs the revision from the store.
126
+
127
+ `current_revisions()` reports what is in use:
128
+
129
+ | Convention | Current | Notes |
130
+ |---|---|---|
131
+ | `proj:` | `r3` | r2 restricted `proj:code` to `^[A-Z]+:[0-9]+$`, so `OGC:CRS84` was invalid |
132
+ | `spatial:` | `r3` | same keys as r2, looser validation |
133
+ | `multiscales` | `r2` | the only revision published so far |
134
+
135
+ `tests/test_conventions.py` asserts these, so a `zarr_cm` upgrade that ships a
136
+ new revision surfaces as one failing test rather than silently changing what gets
137
+ written. When it fails: read what changed, confirm the new attributes are what
138
+ you want, update `EXPECTED_REVISIONS`. Stricter validation would fail loudly at
139
+ ingest anyway; the test is there for the revisions that change quietly.
140
+
141
+ ## Known issues
142
+
143
+ - Writing a CRS onto a group with no y/x spatial dims (e.g. HEALPix) produces a
144
+ bogus identity `GeoTransform`. Carried over from cube-factory
145
+ (`ZarrGroup.to_dataset` in `_core.py`); the fix belongs wherever the
146
+ rioxarray-facing write path ends up living.
147
+
148
+ ## Development
149
+
150
+ ```bash
151
+ uv sync --all-groups
152
+ just test # pytest
153
+ just check # ruff lint + format + ty
154
+ ```
@@ -0,0 +1,111 @@
1
+ # zarr-cm-tree
2
+
3
+ GeoZarr convention attribute builders — an opinionated bridge between
4
+ [pyproj](https://pyproj4.github.io/pyproj/) and
5
+ [zarr-cm](https://github.com/zarr-conventions/zarr-cm).
6
+
7
+ It produces the plain attribute dicts that make up the `attributes` block of a
8
+ Zarr v3 group or array for the GeoZarr conventions `proj:`, `spatial:` and
9
+ `multiscales`, plus an interim `dggs:` placeholder.
10
+
11
+ ```bash
12
+ uv add zarr-cm-tree
13
+ ```
14
+
15
+ ## Scope
16
+
17
+ `zarr_cm` owns the conventions themselves: schemas, validation, revisions, and
18
+ the `zarr_conventions` registry entries. This package adds only what it
19
+ deliberately does not:
20
+
21
+ - **A pyproj bridge.** `GeoZarrProj` holds a canonical `pyproj.CRS` and decides
22
+ how to serialise it — authority code when one exists, WKT2 otherwise — and
23
+ hands rioxarray a matching CRS string via `rio_input()`.
24
+ - **Domain defaults for gridded data.** `GeoZarrSpatial` defaults to `("y", "x")`
25
+ dims and `"pixel"` registration, and infers `transform_type="affine"`.
26
+ - **Layout rules the schema does not encode**, e.g. `derived_from` requires a
27
+ `transform`.
28
+ - **`geozarr_attrs`**, which emits several conventions at once together with a
29
+ matching `zarr_conventions` registry array, so the registry always describes
30
+ exactly the conventions present.
31
+
32
+ Everything returned is a plain `dict`, never a model, so it merges straight into
33
+ `xarray.Dataset.attrs`.
34
+
35
+ ## Usage
36
+
37
+ ```python
38
+ import zarr_cm_tree as gz
39
+
40
+ crs = gz.GeoZarrProj.from_user_input("EPSG:27704") # Equi7Grid EU
41
+ spatial = gz.GeoZarrSpatial(
42
+ transform=(10.0, 0.0, 5400000.0, 0.0, -10.0, 2700000.0),
43
+ shape=(10000, 10000),
44
+ )
45
+
46
+ attrs = gz.geozarr_attrs(crs=crs, spatial=spatial)
47
+ # {"proj:code": "EPSG:27704", "spatial:transform": [...], "zarr_conventions": [...]}
48
+
49
+ group.attrs.update(attrs) # or ds.attrs.update(attrs)
50
+ ```
51
+
52
+ Add a pyramid by passing the layout, one entry per level:
53
+
54
+ ```python
55
+ attrs = gz.geozarr_attrs(
56
+ crs=crs,
57
+ multiscales=[
58
+ {"asset": "0"},
59
+ {"asset": "1", "derived_from": "0", "transform": {"scale": [2.0, 2.0]}},
60
+ ],
61
+ )
62
+ ```
63
+
64
+ The individual builders (`build_proj_attrs`, `build_spatial_attrs`,
65
+ `build_multiscales_attrs`, `build_zarr_conventions`, `merge_attrs`) are public
66
+ too, for callers that want to assemble attrs themselves.
67
+ `build_zarr_conventions` accepts the legacy `"geo-proj"` spelling as an alias for
68
+ `"proj"`, since `zarr_cm.ConventionName` still carries it and so do stores
69
+ written before the upstream rename.
70
+
71
+ ## Convention revisions
72
+
73
+ Each convention in `zarr_cm` ships at one or more numbered *revisions*. A
74
+ revision fixes the convention's JSON Schema: which attribute keys are legal, how
75
+ strictly they are validated, and the `schema_url` written into the store's
76
+ `zarr_conventions` array.
77
+
78
+ This package writes at whatever revision the installed `zarr_cm` declares
79
+ latest, rather than pinning one — a pin nobody updates goes stale, and every
80
+ store records the revision that wrote it in its own `schema_url`, so drift stays
81
+ auditable after the fact. Reading is unaffected either way:
82
+ `zarr_cm.<convention>.detect()` sniffs the revision from the store.
83
+
84
+ `current_revisions()` reports what is in use:
85
+
86
+ | Convention | Current | Notes |
87
+ |---|---|---|
88
+ | `proj:` | `r3` | r2 restricted `proj:code` to `^[A-Z]+:[0-9]+$`, so `OGC:CRS84` was invalid |
89
+ | `spatial:` | `r3` | same keys as r2, looser validation |
90
+ | `multiscales` | `r2` | the only revision published so far |
91
+
92
+ `tests/test_conventions.py` asserts these, so a `zarr_cm` upgrade that ships a
93
+ new revision surfaces as one failing test rather than silently changing what gets
94
+ written. When it fails: read what changed, confirm the new attributes are what
95
+ you want, update `EXPECTED_REVISIONS`. Stricter validation would fail loudly at
96
+ ingest anyway; the test is there for the revisions that change quietly.
97
+
98
+ ## Known issues
99
+
100
+ - Writing a CRS onto a group with no y/x spatial dims (e.g. HEALPix) produces a
101
+ bogus identity `GeoTransform`. Carried over from cube-factory
102
+ (`ZarrGroup.to_dataset` in `_core.py`); the fix belongs wherever the
103
+ rioxarray-facing write path ends up living.
104
+
105
+ ## Development
106
+
107
+ ```bash
108
+ uv sync --all-groups
109
+ just test # pytest
110
+ just check # ruff lint + format + ty
111
+ ```
@@ -0,0 +1,91 @@
1
+ [build-system]
2
+ build-backend = "uv_build"
3
+ requires = ["uv-build>=0.11.2,<0.12"]
4
+
5
+ [project]
6
+ name = "zarr-cm-tree"
7
+ version = "0.1.0"
8
+ description = "GeoZarr convention attribute builders: a pyproj bridge over zarr-cm."
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ classifiers = [
12
+ "Intended Audience :: Science/Research",
13
+ "Natural Language :: English",
14
+ "Operating System :: POSIX",
15
+ "Programming Language :: Python :: 3 :: Only",
16
+ "Programming Language :: Python :: 3.12",
17
+ "Programming Language :: Python :: 3.13",
18
+ "Programming Language :: Python :: 3.14",
19
+ "Topic :: Scientific/Engineering",
20
+ "Topic :: Scientific/Engineering :: GIS",
21
+ "Topic :: Software Development :: Libraries",
22
+ ]
23
+ dependencies = [
24
+ "pyproj>=3.6",
25
+ "zarr-cm>=0.4",
26
+ ]
27
+
28
+ [project.license]
29
+ file = "LICENSE.txt"
30
+
31
+ [[project.authors]]
32
+ name = "eodc"
33
+ email = "office@eodc.eu"
34
+
35
+ [project.urls]
36
+ Repository = "https://github.com/eodcgmbh/zarr-cm-tree"
37
+
38
+ [dependency-groups]
39
+ dev = [
40
+ "pytest>=9.0.1",
41
+ "pytest-cov>=7",
42
+ "ruff>=0.14.5",
43
+ "ty>=0.0.8",
44
+ ]
45
+
46
+ [tool.ruff.format]
47
+ quote-style = "double"
48
+ indent-style = "space"
49
+ skip-magic-trailing-comma = false
50
+ line-ending = "auto"
51
+ docstring-code-format = false
52
+ docstring-code-line-length = "dynamic"
53
+
54
+ [tool.ruff.lint]
55
+ select = ["ALL"]
56
+ ignore = [
57
+ "COM812",
58
+ "D203",
59
+ "D213",
60
+ "PLR0913",
61
+ "ANN401",
62
+ "CPY001",
63
+ ]
64
+ fixable = ["ALL"]
65
+ unfixable = []
66
+
67
+ [tool.ruff.lint.per-file-ignores]
68
+ "__init__.py" = ["E402"]
69
+ "**/{tests}/*" = [
70
+ "ANN001",
71
+ "ANN201",
72
+ "D",
73
+ "E402",
74
+ "INP001",
75
+ "PLR2004",
76
+ "S101",
77
+ ]
78
+
79
+ [tool.pyproject-fmt]
80
+ table_format = "long"
81
+ collapse_tables = ["project.authors"]
82
+
83
+ [tool.pytest.ini_options]
84
+ addopts = "--cov=zarr_cm_tree --cov-report term-missing -rsx --verbose --color=yes"
85
+
86
+ [tool.coverage.run]
87
+ relative_files = true
88
+
89
+ [tool.ty.rules]
90
+ possibly-missing-attribute = "ignore"
91
+ unresolved-attribute = "ignore"
@@ -0,0 +1,78 @@
1
+ [build-system]
2
+ build-backend = "uv_build"
3
+ requires = [ "uv-build>=0.11.2,<0.12" ]
4
+
5
+ [project]
6
+ name = "zarr-cm-tree"
7
+ version = "0.1.0"
8
+ description = "GeoZarr convention attribute builders: a pyproj bridge over zarr-cm."
9
+ readme = "README.md"
10
+ license = { file = "LICENSE.txt" }
11
+ authors = [ { name = "eodc", email = "office@eodc.eu" } ]
12
+ requires-python = ">=3.12"
13
+ classifiers = [
14
+ "Intended Audience :: Science/Research",
15
+ "Natural Language :: English",
16
+ "Operating System :: POSIX",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Programming Language :: Python :: 3.14",
21
+ "Topic :: Scientific/Engineering",
22
+ "Topic :: Scientific/Engineering :: GIS",
23
+ "Topic :: Software Development :: Libraries",
24
+ ]
25
+ dependencies = [
26
+ "pyproj>=3.6",
27
+ # Deliberately unbounded: conventions are written at zarr-cm's latest
28
+ # revision. ``tests/test_conventions.py`` asserts which revisions those are,
29
+ # so a new one surfaces as a failing test. See ``_conventions.py``.
30
+ "zarr-cm>=0.4",
31
+ ]
32
+ [project.urls]
33
+ Repository = "https://github.com/eodcgmbh/zarr-cm-tree"
34
+
35
+ [dependency-groups]
36
+ dev = [
37
+ "pytest>=9.0.1",
38
+ "pytest-cov>=7",
39
+ "ruff>=0.14.5",
40
+ "ty>=0.0.8",
41
+ ]
42
+
43
+ [tool.ruff.format]
44
+ quote-style = "double"
45
+ indent-style = "space"
46
+ skip-magic-trailing-comma = false
47
+ line-ending = "auto"
48
+ docstring-code-format = false
49
+ docstring-code-line-length = "dynamic"
50
+ [tool.ruff.lint]
51
+ select = [ "ALL" ]
52
+ ignore = [
53
+ "COM812", # missing-trailing-comma (may conflict with ruff formatter)
54
+ "D203", # incorrect-blank-line-before-class (conflicts with D211)
55
+ "D213", # multi-line-summary-second-line (conflicts with D212)
56
+ "PLR0913",
57
+ "ANN401", # allow Any
58
+ "CPY001", # no copyright headers in this codebase
59
+ ]
60
+ fixable = [ "ALL" ]
61
+ unfixable = []
62
+ [tool.ruff.lint.per-file-ignores]
63
+ "__init__.py" = [ "E402" ]
64
+ "**/{tests}/*" = [ "ANN001", "ANN201", "D", "E402", "INP001", "PLR2004", "S101" ]
65
+
66
+ [tool.pyproject-fmt]
67
+ table_format = "long"
68
+ collapse_tables = [ "project.authors" ]
69
+
70
+ [tool.pytest.ini_options]
71
+ addopts = "--cov=zarr_cm_tree --cov-report term-missing -rsx --verbose --color=yes"
72
+
73
+ [tool.coverage.run]
74
+ relative_files = true
75
+
76
+ [tool.ty.rules]
77
+ possibly-missing-attribute = "ignore"
78
+ unresolved-attribute = "ignore"
@@ -0,0 +1,65 @@
1
+ """GeoZarr convention attribute builders.
2
+
3
+ An opinionated bridge between :mod:`pyproj` and :mod:`zarr_cm`: it produces the
4
+ plain attribute dicts that make up the ``attributes`` block of a Zarr v3 group
5
+ or array for the GeoZarr conventions ``proj:``, ``spatial:`` and
6
+ ``multiscales``, plus an interim ``dggs:`` placeholder.
7
+
8
+ :mod:`zarr_cm` owns the conventions themselves (schemas, validation, revisions,
9
+ registry entries). This package adds what it deliberately does not: a
10
+ canonical :class:`pyproj.CRS` that knows how to serialise itself, domain
11
+ defaults for gridded data, layout rules the schema does not encode, and
12
+ :func:`geozarr_attrs` to emit several conventions at once with a matching
13
+ ``zarr_conventions`` registry.
14
+
15
+ Everything returned is a plain ``dict``, never a model, so it can be merged
16
+ straight into ``xarray.Dataset.attrs``.
17
+
18
+ References
19
+ ----------
20
+ * https://geozarr.org/conventions
21
+ * https://github.com/zarr-conventions/zarr-cm
22
+
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from zarr_cm_tree._attrs import geozarr_attrs
28
+ from zarr_cm_tree._conventions import (
29
+ MULTISCALES_UUID,
30
+ PROJ_UUID,
31
+ SPATIAL_UUID,
32
+ build_zarr_conventions,
33
+ convention_metadata,
34
+ current_revisions,
35
+ merge_attrs,
36
+ )
37
+ from zarr_cm_tree._dggs import DGGS_NAMESPACE, build_dggs_attrs
38
+ from zarr_cm_tree._multiscales import (
39
+ LayoutObject,
40
+ Transform,
41
+ build_multiscales_attrs,
42
+ )
43
+ from zarr_cm_tree._proj import GeoZarrProj, GeoZarrProjFormat, build_proj_attrs
44
+ from zarr_cm_tree._spatial import GeoZarrSpatial, build_spatial_attrs
45
+
46
+ __all__ = [
47
+ "DGGS_NAMESPACE",
48
+ "MULTISCALES_UUID",
49
+ "PROJ_UUID",
50
+ "SPATIAL_UUID",
51
+ "GeoZarrProj",
52
+ "GeoZarrProjFormat",
53
+ "GeoZarrSpatial",
54
+ "LayoutObject",
55
+ "Transform",
56
+ "build_dggs_attrs",
57
+ "build_multiscales_attrs",
58
+ "build_proj_attrs",
59
+ "build_spatial_attrs",
60
+ "build_zarr_conventions",
61
+ "convention_metadata",
62
+ "current_revisions",
63
+ "geozarr_attrs",
64
+ "merge_attrs",
65
+ ]
@@ -0,0 +1,68 @@
1
+ """Combine several conventions into one attribute dict."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from zarr_cm_tree._conventions import build_zarr_conventions
8
+ from zarr_cm_tree._multiscales import build_multiscales_attrs
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Mapping, Sequence
12
+
13
+ from zarr_cm_tree._proj import GeoZarrProj
14
+ from zarr_cm_tree._spatial import GeoZarrSpatial
15
+
16
+ __all__ = ["geozarr_attrs"]
17
+
18
+
19
+ def geozarr_attrs(
20
+ *,
21
+ crs: GeoZarrProj | None = None,
22
+ spatial: GeoZarrSpatial | None = None,
23
+ multiscales: Sequence[Mapping[str, Any]] | None = None,
24
+ resampling_method: str | None = None,
25
+ ) -> dict[str, Any]:
26
+ """Build the attrs for any combination of conventions, plus their registry.
27
+
28
+ The one-stop entry point for writing GeoZarr metadata onto a group: it emits
29
+ the convention attributes and the matching ``zarr_conventions`` registry
30
+ array, in a fixed ``proj`` -> ``spatial`` -> ``multiscales`` order, so the
31
+ registry always describes exactly the conventions present.
32
+
33
+ Parameters
34
+ ----------
35
+ crs : GeoZarrProj or None, optional
36
+ CRS to emit as ``proj:*``.
37
+ spatial : GeoZarrSpatial or None, optional
38
+ Grid geometry to emit as ``spatial:*``.
39
+ multiscales : Sequence[Mapping[str, Any]] or None, optional
40
+ Pyramid layout entries (see :func:`build_multiscales_attrs`). An empty
41
+ sequence is treated as absent.
42
+ resampling_method : str or None, optional
43
+ Default resampling method for the ``multiscales`` block.
44
+
45
+ Returns
46
+ -------
47
+ dict
48
+ Merged attributes ready for ``group.attrs.update(...)``, with a
49
+ ``zarr_conventions`` entry per active convention. Empty when no
50
+ convention is given.
51
+
52
+ """
53
+ attrs: dict[str, Any] = {}
54
+ conventions: list[str] = []
55
+ if crs is not None:
56
+ attrs.update(crs.to_proj_attrs())
57
+ conventions.append("proj")
58
+ if spatial is not None:
59
+ attrs.update(spatial.to_attrs())
60
+ conventions.append("spatial")
61
+ if multiscales:
62
+ attrs.update(
63
+ build_multiscales_attrs(multiscales, resampling_method=resampling_method)
64
+ )
65
+ conventions.append("multiscales")
66
+ if conventions:
67
+ attrs["zarr_conventions"] = build_zarr_conventions(*conventions)
68
+ return attrs
@@ -0,0 +1,127 @@
1
+ """Convention registry, revision awareness, and attribute merging.
2
+
3
+ Each GeoZarr convention in :mod:`zarr_cm` ships at one or more numbered
4
+ *revisions*. A revision fixes the convention's JSON Schema — which attribute
5
+ keys are legal, how strictly they are validated, and the ``schema_url`` written
6
+ into the ``zarr_conventions`` registry array of a store.
7
+
8
+ This package deliberately follows whatever revision the installed ``zarr_cm``
9
+ declares latest, rather than pinning one: a pin nobody updates goes stale, and
10
+ every store records the revision that wrote it in its own ``schema_url``, so
11
+ drift stays auditable after the fact. Reads are unaffected either way —
12
+ ``zarr_cm.<convention>.detect()`` sniffs the revision from the store.
13
+
14
+ The revisions in use are reported by :func:`current_revisions`, and
15
+ ``tests/test_conventions.py`` asserts them, so a ``zarr_cm`` upgrade that ships
16
+ a new revision surfaces as one failing test rather than silently changing what
17
+ gets written.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from typing import TYPE_CHECKING, Any, Final
23
+
24
+ from zarr_cm import multiscales as _zcm_multiscales
25
+ from zarr_cm import proj as _zcm_proj
26
+ from zarr_cm import spatial as _zcm_spatial
27
+
28
+ if TYPE_CHECKING:
29
+ from types import ModuleType
30
+
31
+ _CONVENTIONS: Final[dict[str, ModuleType]] = {
32
+ "proj": _zcm_proj,
33
+ "spatial": _zcm_spatial,
34
+ "multiscales": _zcm_multiscales,
35
+ }
36
+
37
+ _ALIASES: Final[dict[str, str]] = {"geo-proj": "proj"}
38
+ """Accepted spellings that are not the canonical name.
39
+
40
+ Upstream renamed ``geo-proj`` to ``proj``; ``zarr_cm.ConventionName`` still
41
+ carries the old spelling, and so do stores written before the rename.
42
+ """
43
+
44
+ PROJ_UUID: str = _zcm_proj.UUID
45
+ SPATIAL_UUID: str = _zcm_spatial.UUID
46
+ MULTISCALES_UUID: str = _zcm_multiscales.UUID
47
+
48
+
49
+ def _module(name: str) -> ModuleType:
50
+ """Resolve *name* to its :mod:`zarr_cm` convention module."""
51
+ resolved = _ALIASES.get(name, name)
52
+ try:
53
+ return _CONVENTIONS[resolved]
54
+ except KeyError:
55
+ msg = f"unknown GeoZarr convention: {name!r}"
56
+ raise KeyError(msg) from None
57
+
58
+
59
+ def current_revisions() -> dict[str, str]:
60
+ """Return the revision each convention is currently written at.
61
+
62
+ Returns
63
+ -------
64
+ dict[str, str]
65
+ Mapping from canonical convention name to the revision label the
66
+ installed :mod:`zarr_cm` declares latest, e.g. ``{"proj": "r3", ...}``.
67
+
68
+ """
69
+ return {name: module.LATEST for name, module in _CONVENTIONS.items()}
70
+
71
+
72
+ def convention_metadata(name: str) -> dict[str, Any]:
73
+ """Return the ``zarr_conventions`` registry entry for convention *name*.
74
+
75
+ Parameters
76
+ ----------
77
+ name : str
78
+ Convention name, e.g. ``"proj"`` (or its ``"geo-proj"`` alias),
79
+ ``"spatial"``, ``"multiscales"``.
80
+
81
+ Returns
82
+ -------
83
+ dict
84
+ A copy of the ConventionMetadataObject, carrying its ``uuid``,
85
+ ``schema_url``, ``spec_url``, ``name`` and ``description``.
86
+
87
+ Raises
88
+ ------
89
+ KeyError
90
+ If *name* is not a known GeoZarr convention.
91
+
92
+ """
93
+ return dict(_module(name).CMO)
94
+
95
+
96
+ def build_zarr_conventions(*names: str) -> list[dict[str, Any]]:
97
+ """Build ``zarr_conventions`` registry entries for the given conventions.
98
+
99
+ Parameters
100
+ ----------
101
+ *names : str
102
+ Convention names, e.g. ``"proj"``, ``"spatial"``, ``"multiscales"``.
103
+
104
+ Returns
105
+ -------
106
+ list[dict]
107
+ One registry entry per name, in the order given.
108
+
109
+ Raises
110
+ ------
111
+ KeyError
112
+ If any name is not a known GeoZarr convention.
113
+
114
+ """
115
+ return [convention_metadata(name) for name in names]
116
+
117
+
118
+ def merge_attrs(*parts: dict[str, Any] | None) -> dict[str, Any]:
119
+ """Merge attribute dicts left-to-right; later keys override earlier ones.
120
+
121
+ ``None`` parts are skipped.
122
+ """
123
+ merged: dict[str, Any] = {}
124
+ for part in parts:
125
+ if part:
126
+ merged.update(part)
127
+ return merged
@@ -0,0 +1,53 @@
1
+ """Interim ``dggs:`` attributes for the in-progress DGGS-in-Zarr convention."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Final
6
+
7
+ __all__ = [
8
+ "DGGS_NAMESPACE",
9
+ "build_dggs_attrs",
10
+ ]
11
+
12
+ DGGS_NAMESPACE: Final = "dggs:"
13
+ """Prefix used for the in-progress DGGS-in-Zarr convention.
14
+
15
+ The convention is *Under Consideration* on geozarr.org (repo
16
+ ``zarr-conventions/dggs``); no UUID or JSON Schema is published yet. When v1
17
+ ships, attribute keys produced by :func:`build_dggs_attrs` need a mechanical
18
+ rename only.
19
+ """
20
+
21
+
22
+ def build_dggs_attrs(
23
+ grid_name: str,
24
+ level: int,
25
+ indexing_scheme: str,
26
+ ) -> dict[str, Any]:
27
+ """Build interim ``dggs:`` attributes.
28
+
29
+ Until the convention ships, this only namespaces the ``grid_name`` /
30
+ ``level`` / ``indexing_scheme`` keys — there is no ``zarr_cm.dggs`` module
31
+ to delegate to and no ``zarr_conventions`` entry to register.
32
+
33
+ Parameters
34
+ ----------
35
+ grid_name : str
36
+ DGGS family identifier (e.g. ``"healpix"``).
37
+ level : int
38
+ Refinement level / zoom. Coerced with ``int()`` so numpy integers do
39
+ not reach the store as non-JSON-serialisable attribute values.
40
+ indexing_scheme : str
41
+ Cell indexing scheme (e.g. ``"nested"``).
42
+
43
+ Returns
44
+ -------
45
+ dict
46
+ ``{"dggs:grid_name": ..., "dggs:level": ..., "dggs:indexing_scheme": ...}``.
47
+
48
+ """
49
+ return {
50
+ f"{DGGS_NAMESPACE}grid_name": grid_name,
51
+ f"{DGGS_NAMESPACE}level": int(level),
52
+ f"{DGGS_NAMESPACE}indexing_scheme": indexing_scheme,
53
+ }
@@ -0,0 +1,69 @@
1
+ """GeoZarr ``multiscales`` layout attributes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, cast
6
+
7
+ from zarr_cm import multiscales as _zcm_multiscales
8
+ from zarr_cm.multiscales import LayoutObject, Transform
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Iterable, Mapping, Sequence
12
+
13
+ __all__ = [
14
+ "LayoutObject",
15
+ "Transform",
16
+ "build_multiscales_attrs",
17
+ ]
18
+
19
+
20
+ def build_multiscales_attrs(
21
+ layout: Sequence[Mapping[str, Any]],
22
+ *,
23
+ resampling_method: str | None = None,
24
+ ) -> dict[str, Any]:
25
+ """Build ``multiscales`` convention attributes.
26
+
27
+ Parameters
28
+ ----------
29
+ layout : Sequence[Mapping[str, Any]]
30
+ One entry per pyramid level. Each entry is a mapping with ``asset``
31
+ (path to the sibling Zarr array / group) and optional ``derived_from``,
32
+ ``transform``, and ``resampling_method``. Plain dicts are accepted and
33
+ checked at runtime; :class:`LayoutObject` is the typed shape.
34
+ resampling_method : str or None, optional
35
+ Top-level default resampling method (overridable per level).
36
+
37
+ Returns
38
+ -------
39
+ dict
40
+ ``{"multiscales": {...}}``. No ``zarr_conventions`` entry (see
41
+ :func:`~zarr_cm_tree.build_zarr_conventions`).
42
+
43
+ Raises
44
+ ------
45
+ ValueError
46
+ If *layout* is empty, an entry has no ``asset``, or an entry has
47
+ ``derived_from`` without a ``transform``.
48
+
49
+ """
50
+ levels = _validate_layout(layout)
51
+ if not levels:
52
+ msg = "multiscales layout must have at least one level"
53
+ raise ValueError(msg)
54
+ ms = _zcm_multiscales.create(layout=levels, resampling_method=resampling_method)
55
+ return {"multiscales": dict(ms)}
56
+
57
+
58
+ def _validate_layout(levels: Iterable[Mapping[str, Any]]) -> list[LayoutObject]:
59
+ """Validate and copy layout entries, enforcing the rules zarr_cm does not."""
60
+ out: list[LayoutObject] = []
61
+ for entry in levels:
62
+ if "asset" not in entry:
63
+ msg = "every multiscales layout entry must have an 'asset' key"
64
+ raise ValueError(msg)
65
+ if "derived_from" in entry and "transform" not in entry:
66
+ msg = "multiscales layout entry has 'derived_from' but no 'transform'"
67
+ raise ValueError(msg)
68
+ out.append(cast("LayoutObject", dict(entry)))
69
+ return out
@@ -0,0 +1,107 @@
1
+ """GeoZarr ``proj:`` attributes and the :mod:`pyproj` bridge."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from enum import StrEnum
7
+ from typing import Any
8
+
9
+ import pyproj
10
+ from zarr_cm import proj as _zcm_proj
11
+
12
+ __all__ = [
13
+ "GeoZarrProj",
14
+ "GeoZarrProjFormat",
15
+ "build_proj_attrs",
16
+ ]
17
+
18
+
19
+ def build_proj_attrs(
20
+ *,
21
+ crs_code: str | None = None,
22
+ wkt2: str | None = None,
23
+ projjson: dict[str, Any] | None = None,
24
+ ) -> dict[str, Any]:
25
+ """Build ``proj:*`` attributes via :mod:`zarr_cm`.
26
+
27
+ Parameters
28
+ ----------
29
+ crs_code : str or None
30
+ Authority code (e.g. ``"EPSG:27704"``).
31
+ wkt2 : str or None
32
+ WKT2 definition string.
33
+ projjson : dict or None
34
+ PROJJSON object.
35
+
36
+ Returns
37
+ -------
38
+ dict
39
+ ``{}`` if all arguments are ``None``; otherwise one of ``proj:code``,
40
+ ``proj:wkt2``, or ``proj:projjson``. No ``zarr_conventions`` entry (see
41
+ :func:`~zarr_cm_tree.build_zarr_conventions`). Prefer
42
+ :class:`GeoZarrProj` for validated inputs.
43
+
44
+ """
45
+ if crs_code is None and wkt2 is None and projjson is None:
46
+ return {}
47
+ return dict(_zcm_proj.create(code=crs_code, wkt2=wkt2, projjson=projjson))
48
+
49
+
50
+ class GeoZarrProjFormat(StrEnum):
51
+ """GeoZarr ``proj:*`` encoding to emit from a :class:`pyproj.CRS`."""
52
+
53
+ CODE = "code"
54
+ WKT2 = "wkt2"
55
+ PROJJSON = "projjson"
56
+
57
+
58
+ @dataclass(frozen=True, slots=True)
59
+ class GeoZarrProj:
60
+ """A CRS held as a canonical :class:`pyproj.CRS`, serialisable to ``proj:*``.
61
+
62
+ Parameters
63
+ ----------
64
+ crs : pyproj.CRS
65
+ Parsed coordinate reference system.
66
+ crs_format : GeoZarrProjFormat, optional
67
+ How :meth:`to_proj_attrs` serialises ``crs`` (default ``code``).
68
+ Authority codes are used when available; otherwise WKT2 is emitted.
69
+
70
+ """
71
+
72
+ crs: pyproj.CRS
73
+ crs_format: GeoZarrProjFormat = GeoZarrProjFormat.CODE
74
+
75
+ @classmethod
76
+ def from_user_input(
77
+ cls,
78
+ value: str | int | dict[str, Any],
79
+ *,
80
+ crs_format: GeoZarrProjFormat = GeoZarrProjFormat.CODE,
81
+ ) -> GeoZarrProj:
82
+ """Build from any input accepted by :meth:`pyproj.CRS.from_user_input`."""
83
+ return cls(crs=pyproj.CRS.from_user_input(value), crs_format=crs_format)
84
+
85
+ def rio_input(self) -> str:
86
+ """CRS string for :meth:`rioxarray.raster_array.RasterArray.write_crs`."""
87
+ match self.crs_format:
88
+ case GeoZarrProjFormat.CODE:
89
+ authority = self.crs.to_authority()
90
+ if authority is not None:
91
+ return f"{authority[0]}:{authority[1]}"
92
+ return self.crs.to_wkt(version="WKT2_2019")
93
+ case GeoZarrProjFormat.WKT2 | GeoZarrProjFormat.PROJJSON:
94
+ return self.crs.to_wkt(version="WKT2_2019")
95
+
96
+ def to_proj_attrs(self) -> dict[str, Any]:
97
+ """Build ``proj:*`` attributes for this CRS."""
98
+ match self.crs_format:
99
+ case GeoZarrProjFormat.CODE:
100
+ authority = self.crs.to_authority()
101
+ if authority is not None:
102
+ return build_proj_attrs(crs_code=f"{authority[0]}:{authority[1]}")
103
+ return build_proj_attrs(wkt2=self.crs.to_wkt(version="WKT2_2019"))
104
+ case GeoZarrProjFormat.WKT2:
105
+ return build_proj_attrs(wkt2=self.crs.to_wkt(version="WKT2_2019"))
106
+ case GeoZarrProjFormat.PROJJSON:
107
+ return build_proj_attrs(projjson=self.crs.to_json_dict())
@@ -0,0 +1,111 @@
1
+ """GeoZarr ``spatial:`` attributes for gridded data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ from zarr_cm import spatial as _zcm_spatial
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Sequence
12
+
13
+ __all__ = [
14
+ "GeoZarrSpatial",
15
+ "build_spatial_attrs",
16
+ ]
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class GeoZarrSpatial:
21
+ """GeoZarr ``spatial:`` metadata for a gridded dataset.
22
+
23
+ Parameters
24
+ ----------
25
+ transform : tuple[float, ...]
26
+ 6- (or 9-) element affine mapping ``(col, row) -> (X, Y)``.
27
+ dims : tuple[str, ...], optional
28
+ Spatial dimension names in storage order. Default ``("y", "x")``.
29
+ shape : tuple[int, ...] or None, optional
30
+ Pixel shape along ``dims``.
31
+ bbox : tuple[float, ...] or None, optional
32
+ ``(xmin, ymin, xmax, ymax)`` in the group's CRS.
33
+ registration : str, optional
34
+ ``"pixel"`` (centre) or ``"node"``. Default ``"pixel"``.
35
+ transform_type : str or None, optional
36
+ Transform type tag; defaults to ``"affine"`` when ``transform`` is set.
37
+
38
+ """
39
+
40
+ transform: tuple[float, ...]
41
+ dims: tuple[str, ...] = ("y", "x")
42
+ shape: tuple[int, ...] | None = None
43
+ bbox: tuple[float, ...] | None = None
44
+ registration: str = "pixel"
45
+ transform_type: str | None = None
46
+
47
+ def to_attrs(self) -> dict[str, Any]:
48
+ """Build ``spatial:*`` convention attributes."""
49
+ return build_spatial_attrs(
50
+ self.dims,
51
+ transform=self.transform,
52
+ shape=self.shape,
53
+ bbox=self.bbox,
54
+ registration=self.registration,
55
+ transform_type=self.transform_type,
56
+ )
57
+
58
+
59
+ def build_spatial_attrs(
60
+ dimensions: Sequence[str],
61
+ *,
62
+ transform: Sequence[float] | None = None,
63
+ shape: Sequence[int] | None = None,
64
+ bbox: Sequence[float] | None = None,
65
+ transform_type: str | None = None,
66
+ registration: str = "pixel",
67
+ ) -> dict[str, Any]:
68
+ """Build ``spatial:`` convention attributes.
69
+
70
+ Parameters
71
+ ----------
72
+ dimensions : Sequence[str]
73
+ Names of the spatial dimensions in storage order (e.g. ``["y", "x"]``).
74
+ transform : Sequence[float] or None, optional
75
+ 6- or 9-element affine pixel->world transform.
76
+ shape : Sequence[int] or None, optional
77
+ Spatial shape (length must match ``dimensions``).
78
+ bbox : Sequence[float] or None, optional
79
+ 4- or 6-element bounding box in CRS coordinates.
80
+ transform_type : str or None, optional
81
+ Optional transform-type tag (e.g. ``"affine"``). Defaults to
82
+ ``"affine"`` when *transform* is given.
83
+ registration : str, optional
84
+ Pixel registration, ``"pixel"`` (centre) or ``"node"``.
85
+
86
+ Returns
87
+ -------
88
+ dict
89
+ Attributes dict with the ``spatial:*`` keys.
90
+
91
+ Raises
92
+ ------
93
+ ValueError
94
+ If *dimensions* is empty.
95
+
96
+ """
97
+ if not dimensions:
98
+ msg = "spatial:dimensions must be non-empty"
99
+ raise ValueError(msg)
100
+ if transform is not None and transform_type is None:
101
+ transform_type = "affine"
102
+ return dict(
103
+ _zcm_spatial.create(
104
+ dimensions=list(dimensions),
105
+ transform=list(transform) if transform is not None else None,
106
+ shape=list(shape) if shape is not None else None,
107
+ bbox=list(bbox) if bbox is not None else None,
108
+ transform_type=transform_type,
109
+ registration=registration,
110
+ )
111
+ )