Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ jobs:
- run: npm ci
- run: npm run build # widget dist/widget.js (embedded into widget state on execute)

- run: npm run build:forecast

# Install the package + a kernel so the example notebooks can be executed.
# numpy is needed by the Chart examples (it's an optional extra); nbformat
# for the doc generator.
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,6 @@ docs/widgets/*.ipynb

# OS
.DS_Store

# Bundled forecast example (built before notebook execution)
docs/examples/forecast/dist/
149 changes: 149 additions & 0 deletions docs/examples/ensemble-forecast.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "e1efd338",
"metadata": {},
"source": [
"# Europe's temperature outlook\n",
"\n",
"Compare next week's temperatures across Europe, then click a place to see its\n",
"forecast range. The page checks for a recent ECMWF run each time you open it."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "25843662",
"metadata": {
"tags": [
"remove-input"
]
},
"outputs": [],
"source": [
"from pathlib import Path\n",
"import sys\n",
"from manywidgets import Fullscreen\n",
"\n",
"examples = next(\n",
" p for p in [Path(\".\"), Path(\"docs/examples\")]\n",
" if (p / \"forecast/widget.ts\").exists()\n",
")\n",
"sys.path.insert(0, str(examples.resolve()))\n",
"from forecast import EuropeForecast\n",
"\n",
"forecast = EuropeForecast()\n",
"Fullscreen(forecast, widget_id=\"europe-forecast\")"
]
},
{
"cell_type": "markdown",
"id": "90ce0f36",
"metadata": {},
"source": [
"## Put it in a notebook\n",
"\n",
"This example wraps a browser-side forecast map in `Fullscreen`. The calendar,\n",
"map tabs and local chart share the same widget state. Dates and weather data are\n",
"loaded when the widget opens, so the exported page keeps working without a kernel.\n",
"\n",
"Run `npm run build:forecast` from the repository root before opening this notebook.\n",
"The renderer uses deck.gl and MapLibre, with ZarrLayer from\n",
"[deck.gl-raster](https://developmentseed.org/deck.gl-raster/) reading the\n",
"[Dynamical archive](https://dynamical.org/catalog/ecmwf-ifs-ens-forecast-15-day-0-25-degree/)\n",
"directly. The basemap comes from [OpenFreeMap](https://openfreemap.org/quick_start/).\n",
"\n",
"The widget exposes `day_index`, `metric` (`mean` or `spread`) and `playing`.\n",
"These are ordinary traits that can be linked to other manywidgets controls."
]
},
{
"cell_type": "markdown",
"id": "7ad5ee9a",
"metadata": {},
"source": [
"```python\n",
"from pathlib import Path\n",
"import sys\n",
"from manywidgets import Fullscreen\n",
"\n",
"examples = next(\n",
" p for p in [Path(\".\"), Path(\"docs/examples\")]\n",
" if (p / \"forecast/widget.ts\").exists()\n",
")\n",
"sys.path.insert(0, str(examples.resolve()))\n",
"from forecast import EuropeForecast\n",
"\n",
"forecast = EuropeForecast()\n",
"Fullscreen(forecast, widget_id=\"europe-forecast\")\n",
"```\n",
"\n",
"The wrapper lives in `forecast/__init__.py` beside the renderer. To use a smaller\n",
"region, pass bounds and locations when creating the widget:\n",
"\n",
"```python\n",
"forecast = EuropeForecast(\n",
" region_name=\"Switzerland\",\n",
" bounds=[5.9, 45.8, 10.6, 47.9],\n",
" locations=[\n",
" {\"name\": \"Zurich\", \"lon\": 8.542, \"lat\": 47.377},\n",
" {\"name\": \"Geneva\", \"lon\": 6.143, \"lat\": 46.204},\n",
" ],\n",
" initial_location=\"Zurich\",\n",
" forecast_days=7,\n",
" day_index=0,\n",
" temperature_range=[-5, 25],\n",
" spread_range=[0, 6],\n",
")\n",
"Fullscreen(forecast)\n",
"```\n",
"\n",
"Bounds, locations, forecast length and palettes are set at creation. Create a new\n",
"widget to change them. `day_index`, `metric` and `playing` can change while it is\n",
"open. The data reader still uses the same ECMWF archive; this is not an arbitrary\n",
"Zarr viewer.\n",
"\n",
"To read a compatible copy of the ECMWF archive, pass\n",
"`store_url=\"https://your-host.example/ecmwf.zarr\"` at creation. The URL must point\n",
"to the Zarr root and allow browser access. The copy must retain the original\n",
"variables, units, coordinates, dimensions and chunks, and contain recent runs.\n",
"Other Zarr layouts need changes to the data reader."
]
},
{
"cell_type": "markdown",
"id": "0fb0765e",
"metadata": {},
"source": [
"The first map load reads several ensemble chunks, so it can take a while on a\n",
"slow connection. Once loaded, changing the date or map layer reuses the data.\n",
"The browser needs WebGL2 and access to the public data services.\n",
"\n",
"[Example documentation](https://github.com/developmentseed/manywidgets/tree/main/docs/examples/forecast)\n",
"covers setup, code structure and data limitations."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
165 changes: 165 additions & 0 deletions docs/examples/forecast/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
# Europe's temperature outlook

A live ECMWF ensemble forecast for Europe, displayed in an anywidget inside
manywidgets' Fullscreen container. The map opens on a date about one week ahead.
A daily timeline covers the next available 12 UTC forecasts, up to fourteen days.
Click a place to see its temperature range through that period.

## Run the example

From the repository root:

```sh
npm ci
npm run build
npm run build:forecast
jupyter nbconvert --to notebook --execute --inplace docs/examples/ensemble-forecast.ipynb
```

The notebook embeds the renderer and styles in its widget state. No Python
kernel is needed on the exported page. WebGL2 and network access to the public
Zarr store and basemap are required.

## Configure from Python

Import `EuropeForecast` from the example's `forecast` folder, as shown in the
notebook. This wrapper is example code, not an installed manywidgets API.

```python
forecast = EuropeForecast(
region_name="Switzerland",
bounds=[5.9, 45.8, 10.6, 47.9],
locations=[
{"name": "Zurich", "lon": 8.542, "lat": 47.377},
{"name": "Geneva", "lon": 6.143, "lat": 46.204},
],
initial_location="Zurich",
forecast_days=7,
day_index=0,
temperature_range=[-5, 25],
spread_range=[0, 6],
temperature_colors=["#607faa", "#e8e9c1", "#be6454"],
)
Fullscreen(forecast)
```

| Option | Default | Meaning |
| --- | --- | --- |
| `store_url` | Public dynamical.org ECMWF store | Absolute HTTP(S) URL of the Zarr root. Accepts compatible copies or mirrors. |
| `region_name` | `"Europe"` | Heading, reset button and map description. |
| `bounds` | `[-25, 34, 45, 72]` | West, south, east, north in degrees. Sets the starting view, clickable region and chunk filter. |
| `locations` | 13 European cities | Dictionaries with unique `name`, `lon` and `lat`, all within bounds. If omitted, default cities are filtered to the bounds. At least one is required. |
| `initial_location` | First location | Name of the starting location. Also used to check recent runs. |
| `forecast_days` | `14` | Future outlook length, from 1 to 14 days. The archive may provide fewer dates. |
| `temperature_range` | `[-10, 40]` | Map and legend endpoints in °C. |
| `spread_range` | `[0, 10]` | Map and legend endpoints in °C, with a nonnegative minimum. |
| `temperature_colors`, `spread_colors` | Existing five-color ramps | At least two `#RRGGBB` colors, evenly spaced across the range. |

These are constructor options. Python validates them and syncs a single `config`
object. Create a new widget to change them. `defaults.json` supplies the defaults
for both Python and TypeScript. Bounds cannot cross the antimeridian and must
stay within ±85° latitude, matching the basemap's usable area.

The live traits remain linkable to other widgets:

- `day_index`: zero-based timeline index. Initially `-1` selects about a week ahead. An index beyond the available timeline is clamped to the final date.
- `metric`: `"mean"` or `"spread"`.
- `playing`: starts or pauses playback after the forecast loads. Loading a run pauses playback.

Region and palette options do not change the source variable, units or grid.
The adapter still expects dynamical.org's ECMWF temperature archive with 51
members. To use a compatible mirror, pass `store_url="https://your-host.example/ecmwf.zarr"`.
The browser must be able to read it, with cross-origin requests allowed (CORS).
Pass the store root without query parameters, a fragment or embedded credentials.
The mirror must preserve the Zarr v3 metadata, variables, dimension order,
coordinate conventions, units, grid and chunk layout of the original archive.
The existing format checks still run, and the archive must contain recent runs.
Supporting a different Zarr layout requires a data adapter change.

## Choosing a current run

On each mount, the browser revalidates the store metadata and time coordinates.
It tries the newest three runs within the last 72 hours, newest first, checking
temperature values at the configured starting location across all displayed days and all 51 members.
This verifies one location, not complete global ingestion. Missing map pixels and local
forecast values remain missing. A stale archive or unavailable recent runs
produce an error.

Dates come from `init_time` and `lead_time`. The timeline contains only future
12 UTC snapshots, at most fourteen. A run must cover at least seven future days, or the requested horizon if shorter.
By default, the selected date starts about seven days from opening. The run timestamp is
visible and doubles as a refresh button. Returning to a tab after 30 minutes
checks the source again.

## Data and rendering

- [Dynamical catalog](https://dynamical.org/catalog/ecmwf-ifs-ens-forecast-15-day-0-25-degree/) documents the variables, units, dates and chunking.
- [Public Zarr metadata](https://s3.us-west-2.amazonaws.com/us-west-2.opendata.source.coop/dynamical/ecmwf-ifs-ens-forecast-15-day-0-25-degree/v0.1.0.zarr/zarr.json) is fetched directly from S3.
- [The upstream deck.gl-raster example](https://github.com/developmentseed/deck.gl-raster/tree/main/examples/dynamical-zarr-ecmwf) uses the same Zarr archive.
- [OpenFreeMap](https://openfreemap.org/quick_start/) supplies the free vector basemap. Source attribution appears on the map.

Zarrita reads Zarr chunks in the browser. ZarrLayer from deck.gl-raster renders
mean temperature and population standard deviation through deck.gl, interleaved
with MapLibre. Water is drawn over the raster to focus on land. The raster is
limited to chunks intersecting the configured bounds, which default to Europe.
Boundary chunks can extend slightly beyond those bounds.

Each source chunk contains 85 leads, 51 members and 32 by 32 spatial cells,
about 17 MiB uncompressed. Three concurrent tile reads and an 80-tile cache limit
working memory. The browser caches mean and spread summaries for every lead time in memory.
Each tile has one 2D GPU texture; switching dates or map layers uploads the
selected cached slice without another forecast download. This archive has no spatial overviews,
so the first Europe-wide view can transfer substantially more data than a
regional map. A loading message stays visible while tiles arrive.

Local point reads use the nearest 0.25° grid cell. The chart retains only mean,
10th and 90th percentiles, with a twelve-point cache. Missing members invalidate
the corresponding value. There is no interpolation or elevation correction.
The values are instantaneous temperature at 12 UTC, not daily maxima. Ensemble
ranges describe the members and are not calibrated prediction intervals.

Rendering uses deck.gl-raster’s built-in `CreateTexture`, `FilterNoDataVal`,
`LinearRescale` and `Colormap` modules. Missing summaries are encoded with a
finite sentinel before upload. A shared colormap texture samples the two legend
ramps into 256 colors each.

The raster affine treats coordinates as cell centres. Colours and legends share
the configured ranges and palettes. Values outside those ranges use the end
colours. The source grid and units are checked before rendering.

## Theming

The controls, chart, legend panels and basemap use manywidgets' `--mw-*` theme
tokens. They inherit a parent theme or follow the host page's light/dark mode.
To set a Radix theme explicitly:

```python
from manywidgets.themes import radix_theme

forecast = EuropeForecast(
theme=radix_theme(appearance="dark", accent="green", gray="sage")
)
```

When supplying an explicit Radix theme, choose the appearance that matches your
host. Host color variables retain their usual precedence over Radix semantic
colors. The basemap updates its paint colors when theme tokens change, retaining
loaded forecast tiles. Temperature and spread ramps remain fixed so their legends mean the same
thing in either appearance.

## Code structure

- `__init__.py` validates notebook options and defines the synced traits.
- `defaults.json` and `config.ts` define the shared display settings.
- `widget.ts` mounts the view and controller, observes size changes, and disposes them.
- `view.ts` owns markup, element references, controls, legends and chart display.
- `controller.ts` handles model changes, forecast and point requests, playback and selection restoration.
- `map.ts` owns MapLibre, raster tile loading, the location marker and GPU cleanup.
- `data.ts` reads and summarizes Zarr data. `chart.ts` and `basemap.ts` handle their respective rendering details.
- `raster.ts` prepares texture slices and palettes for the library’s built-in rendering pipeline.
- `types.ts` names the forecast data and selection types shared between modules.

The view emits user actions to the controller. The controller updates the view
and map; neither rendering module reads the widget model. Each module releases
the resources and listeners it creates. Controller tests cover request races,
playback readiness, responsive remounts and disposal during a fetch.
Loading
Loading