|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "cell_type": "markdown", |
| 5 | + "id": "cb74c064", |
| 6 | + "metadata": {}, |
| 7 | + "source": [ |
| 8 | + "# Working with Zarr and NDArray data in SedonaDB\n", |
| 9 | + "\n", |
| 10 | + "SedonaDB's raster type is **N-dimensional**: a band isn't limited to a 2-D `(y, x)` grid — it can carry additional axes such as `time`, `year`, or `band`. This makes it a natural fit for *datacubes*: climate reanalyses, satellite time series, and model outputs.\n", |
| 11 | + "\n", |
| 12 | + "The `sedonadb-zarr` extension reads [Zarr](https://zarr.dev/) groups (v2 or v3) — local or in cloud object storage — directly into that raster type, so a datacube becomes a table you can query.\n", |
| 13 | + "\n", |
| 14 | + "This page walks through loading a real Zarr datacube from object storage, inspecting its dimensions, slicing out a 2-D plane, drawing its chunk grid on a map, and handing a plane to NumPy." |
| 15 | + ] |
| 16 | + }, |
| 17 | + { |
| 18 | + "cell_type": "markdown", |
| 19 | + "id": "18f72319", |
| 20 | + "metadata": {}, |
| 21 | + "source": [ |
| 22 | + "## Install\n", |
| 23 | + "\n", |
| 24 | + "`sedonadb-zarr` is an extension, distributed separately from the core SedonaDB package. The examples below also use `sedonadb-expr` (which adds the `.rst` raster accessor used in the DataFrame expressions) and, for the map, `lonboard`:\n", |
| 25 | + "\n", |
| 26 | + "```bash\n", |
| 27 | + "pip install \"apache-sedona[db]\" sedonadb-zarr sedonadb-expr lonboard\n", |
| 28 | + "```\n", |
| 29 | + "\n", |
| 30 | + "`lonboard` is only needed for the map at the end; everything else works without it." |
| 31 | + ] |
| 32 | + }, |
| 33 | + { |
| 34 | + "cell_type": "markdown", |
| 35 | + "id": "3f348994", |
| 36 | + "metadata": {}, |
| 37 | + "source": [ |
| 38 | + "## Connect and load\n", |
| 39 | + "\n", |
| 40 | + "Register the extension on your connection, then read a Zarr group. We'll use a public, anonymously readable cube: ERA5 rainfall over 2015–2020, stored as a multiscale Zarr pyramid in EPSG:3857. We read one pyramid level and the `rain_ok` rainfall array:" |
| 41 | + ] |
| 42 | + }, |
| 43 | + { |
| 44 | + "cell_type": "code", |
| 45 | + "execution_count": 1, |
| 46 | + "id": "e079dfe7", |
| 47 | + "metadata": {}, |
| 48 | + "outputs": [], |
| 49 | + "source": [ |
| 50 | + "import sedona.db\n", |
| 51 | + "import sedonadb_zarr\n", |
| 52 | + "\n", |
| 53 | + "sd = sedona.db.connect()\n", |
| 54 | + "sd.register(sedonadb_zarr.ZarrExtension())\n", |
| 55 | + "\n", |
| 56 | + "url = \"https://weathermapdata.rdrn.me/era5_2015_2020_l5.zarr/2\"\n", |
| 57 | + "# The path doesn't end in `.zarr`, so name the format. `arrays` selects the\n", |
| 58 | + "# data array to read (the group also holds coordinate / CRS variables).\n", |
| 59 | + "spec = sedonadb_zarr.Zarr().with_options({\"arrays\": [\"rain_ok\"]})\n", |
| 60 | + "cube = sd.read(url, format=spec)" |
| 61 | + ] |
| 62 | + }, |
| 63 | + { |
| 64 | + "cell_type": "markdown", |
| 65 | + "id": "ddb7915c", |
| 66 | + "metadata": {}, |
| 67 | + "source": [ |
| 68 | + "When a group's path *does* end in `.zarr` and needs no options, you can name the format with the string shorthand instead: `sd.read(uri, format=\"zarr\")`.\n", |
| 69 | + "\n", |
| 70 | + "`sedonadb-zarr` emits **one row per Zarr chunk**, so the storage layout *is* the data layout. This level tiles its `512 × 512` grid into a `4 × 4` grid of `128 × 128` chunks, and the cube is chunked one year per chunk — so it loads as `16 × 6 = 96` rows, each a single year of one spatial tile:" |
| 71 | + ] |
| 72 | + }, |
| 73 | + { |
| 74 | + "cell_type": "code", |
| 75 | + "execution_count": 2, |
| 76 | + "id": "71fd0f21", |
| 77 | + "metadata": {}, |
| 78 | + "outputs": [ |
| 79 | + { |
| 80 | + "data": { |
| 81 | + "text/plain": [ |
| 82 | + "96" |
| 83 | + ] |
| 84 | + }, |
| 85 | + "execution_count": 2, |
| 86 | + "metadata": {}, |
| 87 | + "output_type": "execute_result" |
| 88 | + } |
| 89 | + ], |
| 90 | + "source": [ |
| 91 | + "cube.count()" |
| 92 | + ] |
| 93 | + }, |
| 94 | + { |
| 95 | + "cell_type": "markdown", |
| 96 | + "id": "cb563aba", |
| 97 | + "metadata": {}, |
| 98 | + "source": [ |
| 99 | + "## Inspect the dimensions\n", |
| 100 | + "\n", |
| 101 | + "The dimension accessors read the raster's schema only — **no pixel data is loaded** — so they return near-instantly even against a large remote cube. Each row reports its **chunk's** shape, not the full cube extent. All chunks share the same shape here, so we look at one:" |
| 102 | + ] |
| 103 | + }, |
| 104 | + { |
| 105 | + "cell_type": "code", |
| 106 | + "execution_count": 3, |
| 107 | + "id": "a8e37ba1", |
| 108 | + "metadata": {}, |
| 109 | + "outputs": [ |
| 110 | + { |
| 111 | + "name": "stdout", |
| 112 | + "output_type": "stream", |
| 113 | + "text": [ |
| 114 | + "┌───────┬──────────────┬───────────────┬────────┐\n", |
| 115 | + "│ ndim ┆ dims ┆ shape ┆ n_year │\n", |
| 116 | + "│ int32 ┆ list ┆ list ┆ int64 │\n", |
| 117 | + "╞═══════╪══════════════╪═══════════════╪════════╡\n", |
| 118 | + "│ 3 ┆ [year, y, x] ┆ [1, 128, 128] ┆ 1 │\n", |
| 119 | + "└───────┴──────────────┴───────────────┴────────┘\n" |
| 120 | + ] |
| 121 | + } |
| 122 | + ], |
| 123 | + "source": [ |
| 124 | + "cube.select(\n", |
| 125 | + " cube.raster.rst.num_dimensions().alias(\"ndim\"),\n", |
| 126 | + " cube.raster.rst.dim_names().alias(\"dims\"),\n", |
| 127 | + " cube.raster.rst.shape().alias(\"shape\"),\n", |
| 128 | + " cube.raster.rst.dim_size(\"year\").alias(\"n_year\"),\n", |
| 129 | + ").show(1)" |
| 130 | + ] |
| 131 | + }, |
| 132 | + { |
| 133 | + "cell_type": "markdown", |
| 134 | + "id": "eb79fbdf", |
| 135 | + "metadata": {}, |
| 136 | + "source": [ |
| 137 | + "Each chunk is 3-dimensional (`[year, y, x]`) with a `128 × 128` spatial footprint — one tile of the full `512 × 512` grid. `n_year = 1` because the cube is chunked one year per chunk: a single row carries one year of one tile." |
| 138 | + ] |
| 139 | + }, |
| 140 | + { |
| 141 | + "cell_type": "markdown", |
| 142 | + "id": "4ed7f1d1", |
| 143 | + "metadata": {}, |
| 144 | + "source": [ |
| 145 | + "## Slice out a 2-D plane\n", |
| 146 | + "\n", |
| 147 | + "`RS_Slice` selects a single index along a named dimension and drops it. Here each chunk's `year` axis has length 1, so slicing index `0` collapses it, turning every `[1, 128, 128]` chunk into a 2-D `[y, x]` plane — the tile's rainfall field for its year:" |
| 148 | + ] |
| 149 | + }, |
| 150 | + { |
| 151 | + "cell_type": "code", |
| 152 | + "execution_count": 4, |
| 153 | + "id": "34c51b8d", |
| 154 | + "metadata": {}, |
| 155 | + "outputs": [ |
| 156 | + { |
| 157 | + "name": "stdout", |
| 158 | + "output_type": "stream", |
| 159 | + "text": [ |
| 160 | + "┌────────┬────────────┐\n", |
| 161 | + "│ dims ┆ shape │\n", |
| 162 | + "│ list ┆ list │\n", |
| 163 | + "╞════════╪════════════╡\n", |
| 164 | + "│ [y, x] ┆ [128, 128] │\n", |
| 165 | + "└────────┴────────────┘\n" |
| 166 | + ] |
| 167 | + } |
| 168 | + ], |
| 169 | + "source": [ |
| 170 | + "sliced = cube.select(plane=cube.raster.rst.slice(\"year\", 0))\n", |
| 171 | + "sliced.select(\n", |
| 172 | + " dims=sliced.plane.rst.dim_names(),\n", |
| 173 | + " shape=sliced.plane.rst.shape(),\n", |
| 174 | + ").show(1)" |
| 175 | + ] |
| 176 | + }, |
| 177 | + { |
| 178 | + "cell_type": "markdown", |
| 179 | + "id": "93948010", |
| 180 | + "metadata": {}, |
| 181 | + "source": [ |
| 182 | + "`RS_Slice` needs pixel data, so SedonaDB resolves each row's Zarr chunk on demand before slicing — you never call a loader yourself.\n", |
| 183 | + "\n", |
| 184 | + "Related accessors reshape a cube in other ways:\n", |
| 185 | + "\n", |
| 186 | + "- `cube.raster.rst.slice_range(dim, start, end)` keeps a contiguous range of a dimension instead of a single index.\n", |
| 187 | + "- `cube.raster.rst.dim_to_band(dim)` / `cube.raster.rst.band_to_dim(name)` move an axis between the dimension list and the band list." |
| 188 | + ] |
| 189 | + }, |
| 190 | + { |
| 191 | + "cell_type": "markdown", |
| 192 | + "id": "2084a32b", |
| 193 | + "metadata": {}, |
| 194 | + "source": [ |
| 195 | + "## See where the chunks are — on a map\n", |
| 196 | + "\n", |
| 197 | + "Every row is a chunk with a real, georeferenced footprint (the cube declares EPSG:3857), so `RS_Envelope` turns a chunk into its bounding geometry without decoding a single pixel. Reproject the footprints to lon/lat and you can draw the chunk grid straight onto a map:" |
| 198 | + ] |
| 199 | + }, |
| 200 | + { |
| 201 | + "cell_type": "code", |
| 202 | + "execution_count": null, |
| 203 | + "id": "be432f29", |
| 204 | + "metadata": {}, |
| 205 | + "outputs": [], |
| 206 | + "source": [ |
| 207 | + "from lonboard import viz # in a notebook with lonboard installed\n", |
| 208 | + "\n", |
| 209 | + "f = sd.funcs\n", |
| 210 | + "chunks = cube.select(geom=f.st_transform(cube.raster.rst.envelope(), \"EPSG:4326\"))\n", |
| 211 | + "\n", |
| 212 | + "# Draw outlines only, so the basemap shows through the chunk grid.\n", |
| 213 | + "viz(\n", |
| 214 | + " chunks,\n", |
| 215 | + " polygon_kwargs=dict(\n", |
| 216 | + " filled=False,\n", |
| 217 | + " stroked=True,\n", |
| 218 | + " get_line_color=[236, 64, 160],\n", |
| 219 | + " line_width_min_pixels=2,\n", |
| 220 | + " ),\n", |
| 221 | + ")" |
| 222 | + ] |
| 223 | + }, |
| 224 | + { |
| 225 | + "cell_type": "markdown", |
| 226 | + "id": "f802e0f7", |
| 227 | + "metadata": {}, |
| 228 | + "source": [ |
| 229 | + "" |
| 230 | + ] |
| 231 | + }, |
| 232 | + { |
| 233 | + "cell_type": "markdown", |
| 234 | + "id": "9e0e82d9", |
| 235 | + "metadata": {}, |
| 236 | + "source": [ |
| 237 | + "Because each year tiles into a `4 × 4` grid, the envelopes lay out that grid over the mapped extent — a picture of the cube's layout, drawn entirely from metadata. A `LIMIT` or row filter trims which chunks you draw (and, later, fetch)." |
| 238 | + ] |
| 239 | + }, |
| 240 | + { |
| 241 | + "cell_type": "markdown", |
| 242 | + "id": "69bde03e", |
| 243 | + "metadata": {}, |
| 244 | + "source": [ |
| 245 | + "## Bring a plane into NumPy\n", |
| 246 | + "\n", |
| 247 | + "A raster band carries its bytes, shape, and pixel type, so a materialized band decodes to a correctly-shaped, correctly-typed NumPy array in one call — `Band.to_numpy()`:" |
| 248 | + ] |
| 249 | + }, |
| 250 | + { |
| 251 | + "cell_type": "code", |
| 252 | + "execution_count": 6, |
| 253 | + "id": "04289b8c", |
| 254 | + "metadata": {}, |
| 255 | + "outputs": [ |
| 256 | + { |
| 257 | + "name": "stdout", |
| 258 | + "output_type": "stream", |
| 259 | + "text": [ |
| 260 | + "(128, 128) float32\n" |
| 261 | + ] |
| 262 | + } |
| 263 | + ], |
| 264 | + "source": [ |
| 265 | + "planes = sliced.to_arrow_table()[\"plane\"]\n", |
| 266 | + "raster = planes[0].as_py() # one 128x128 spatial tile for its year\n", |
| 267 | + "band = raster.bands[0].to_numpy()\n", |
| 268 | + "print(band.shape, band.dtype)" |
| 269 | + ] |
| 270 | + }, |
| 271 | + { |
| 272 | + "cell_type": "markdown", |
| 273 | + "id": "d8f29e2b", |
| 274 | + "metadata": {}, |
| 275 | + "source": [ |
| 276 | + "Note that `planes[0]` currently forces a copy of the raster out of the Arrow buffer (a pyarrow limitation), so this path is **not yet zero-copy**. Rows correspond to chunks rather than a guaranteed order, so apply your own ordering (or carry a chunk identifier) if you need to know which tile and year a given plane covers." |
| 277 | + ] |
| 278 | + }, |
| 279 | + { |
| 280 | + "cell_type": "markdown", |
| 281 | + "id": "fb471acd", |
| 282 | + "metadata": {}, |
| 283 | + "source": [ |
| 284 | + "## Reading from cloud storage\n", |
| 285 | + "\n", |
| 286 | + "The same code reads a datacube over S3 or HTTP(S) — only the URI changes. Supported schemes are `file://` (and bare local paths), `s3://`, `http://`, and `https://`.\n", |
| 287 | + "\n", |
| 288 | + "For S3, credentials come from the standard AWS environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`). To read a **public** bucket anonymously, set the region and request unsigned access:\n", |
| 289 | + "\n", |
| 290 | + "```bash\n", |
| 291 | + "export AWS_REGION=us-west-2\n", |
| 292 | + "export AWS_SKIP_SIGNATURE=true # read public objects without credentials\n", |
| 293 | + "```\n", |
| 294 | + "\n", |
| 295 | + "```python\n", |
| 296 | + "# A real public bucket (CarbonPlan), readable with the settings above:\n", |
| 297 | + "df = sd.read(\"s3://carbonplan-share/zarr-layer-examples/antarctic_era5.zarr\")\n", |
| 298 | + "```\n", |
| 299 | + "\n", |
| 300 | + "### Selecting arrays with the `arrays` option\n", |
| 301 | + "\n", |
| 302 | + "By default SedonaDB discovers a group's arrays automatically — from the group's consolidated metadata when present, otherwise by listing the store. The `arrays` option names an explicit subset to read instead (as we did above):\n", |
| 303 | + "\n", |
| 304 | + "```python\n", |
| 305 | + "spec = sedonadb_zarr.Zarr().with_options({\"arrays\": [\"rain_ok\"]})\n", |
| 306 | + "df = sd.read(url, format=spec)\n", |
| 307 | + "```\n", |
| 308 | + "\n", |
| 309 | + "Naming arrays is needed in two situations:\n", |
| 310 | + "\n", |
| 311 | + "- **The store can't list and has no consolidated metadata.** Plain HTTP servers generally can't list directories. Cloud Zarr groups often ship a consolidated-metadata block, so reads typically work without `arrays` — but a group (or sub-group) lacking one can't be auto-discovered over such a store, and you must name the arrays.\n", |
| 312 | + "- **The group mixes arrays with different shapes or chunk grids.** Every array read together must share one chunk grid, so name a compatible subset (for example, read the data array and leave out a differently-shaped coordinate or CRS variable).\n", |
| 313 | + "\n", |
| 314 | + "Because each row corresponds to one chunk, a `LIMIT` or row filter directly bounds how many chunks SedonaDB fetches — handy for sampling a large remote cube before committing to a full scan." |
| 315 | + ] |
| 316 | + } |
| 317 | + ], |
| 318 | + "metadata": { |
| 319 | + "kernelspec": { |
| 320 | + "display_name": "Python 3 (ipykernel)", |
| 321 | + "language": "python", |
| 322 | + "name": "python3" |
| 323 | + }, |
| 324 | + "language_info": { |
| 325 | + "name": "python" |
| 326 | + } |
| 327 | + }, |
| 328 | + "nbformat": 4, |
| 329 | + "nbformat_minor": 5 |
| 330 | +} |
0 commit comments