Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Inside the trace or on disk, one grid or many: which container holds the window?

GeoStack · background · carriers · 2 of 2: many arrays

Abstract

One array has one carrier. A data-assimilation window has five ingredients in four geometries: an initial condition, a state, parameters, observations and the model read at the observations. Inside the trace they travel as a pytree of CFields; on disk, one grid is an xr.Dataset and the whole window is an xr.DataTree. The same North Atlantic window as the carrier arrays page carries every section.

Keywords:carrierspytreeCFieldStateParamsxarrayDatasetDataTreexgcm4D-Vardata assimilation

At a glance

Two questions place every container: does it enter the trace, and how many grids does it hold?

how many grids?
oneseveral

in the trace

vector xvec\vect{x}_\text{vec}flat, for filterax and vardax57 600 entries without ghostsa view of one State, not a container

pytreeState, Params of CFieldsgrids not stored: the model holds any numberjit, grad, vmap, scan

jit boundary: dataset_to_state ↑ · state_to_dataset ↓
outside it
xr.Datasetvariables on shared coordsone grid, one swath, one set of pointslazy, Zarr
xr.DataTreea Dataset per nodeone node per ingredientchildren inherit coordsthe window on disk

Teal: device arrays with static layout. Blue: xarray, lazy, labelled, any size. Only one hop crosses the dashed line.

The running example

Notation

Indices: tt is the hour (frame), j,ij, i the grid row and column, oo an observation.

Table 2:The symbols used on this page.

SymbolMeaningShapeUnit
x0,xt\vect{x}_0, \vect{x}_tstate at the window start and at hour tt3 fields (y, x)m, m s⁻¹
μx,Σx\gvect{\mu}_x, \gmat{\Sigma}_xbackground (GLORYS on the model grid) and its error covariance(state,), (state, state)m, m s⁻¹; squared
yt,Σε,t\vect{y}_t, \gmat{\Sigma}_{\varepsilon,t}observations of hour tt, their error covariance (diagonal)(obs,), (obs, obs)m; m²
Ht\mat{H}_tobservation operator: η\eta read at hour tt’s positions(state,) → (obs,)m → m
ffthe model run over one hour, from xt−1\vect{x}_{t-1} to xt\vect{x}_t(state,) → (state,)—
θ=(g,γ,H)\gvect{\theta} = (g, \gamma, H)gravity, linear drag, depth(), (), (y, x)m s⁻², s⁻¹, m
xvec\vect{x}_\text{vec}the state as one flat vector(state,)mixed
r\vect{r}innovation, y−Hx\vect{y} - \mat{H}\vect{x}(obs,)m

1 · The window as a model

The containers follow from what the window computes. Strong-constraint 4D-Var finds the initial state that, run forward, best fits the background and every observation in the window.

Each symbol in the cost (11) lives somewhere else. μx\gvect{\mu}_x arrives on GLORYS’s grid, HH on GEBCO’s, yt\vect{y}_t on points and a swath. Only x\vect{x} is on the model grid. Two conversions carry everything across:

background μx\gvect{\mu}_xGLORYS 1/12°, 360 × 480

depth HHGEBCO 15″, 7 200 × 9 600

average 3 × 3, stagger uu, vv

average 60 × 60 → depth, mask

conversion 1 · in: regrid and stagger

the model grid: spherical C-grid, 1/4°x0→f→x1…x240\vect{x}_0 \to f \to \vect{x}_1 \ldots \vect{x}_{240} (one scan)State: η\eta at T, uu at U, vv at V · Params: gg, γ\gamma, HH at Tthe only place grad flows

η\eta frames read at each obs position and hour

conversion 2 · out: Hx\mat{H}\vect{x}

nadir yn\vect{y}_\text{n}points (obs,)+ hx, innovation

SWOT ys\vect{y}_\text{s}swath (line, pixel)+ hx, innovation

Everything else stays in the geometry it arrived in. Hx\mat{H}\vect{x} and the innovation are written next to their observation.

2 · Inside the trace: a pytree of CFields

Inside jit, a state is an eqx.Module whose fields are CFields (sesmax#138, 23 Nov 2026). The class is the schema: its attribute names are the field names, its annotations say which are fields and which are parameters, and jax.tree sees only the arrays.

SWState (eqx.Module)
SWParams (eqx.Module)

etaCField Tm\mathrm{m}

uCField Um s−1\mathrm{m\ s^{-1}}

vCField Vm s−1\mathrm{m\ s^{-1}}

gravityfloatm s−2\mathrm{m\ s^{-2}}

dragfloats−1\mathrm{s^{-1}}

depthCField Tm\mathrm{m}

jax.tree.leaves
(122, 162)
(122, 162)
(122, 162)
()
()
(122, 162)

What the trace seessix leaves; dims and staggers are static, so a run recompiles only when a field’s layout changes.What grad sees∂J/∂x0\partial \mathcal{J} / \partial \vect{x}_0 has SWState’s shape; ∂J/∂θ\partial \mathcal{J} / \partial \gvect{\theta} has SWParams’ shape, depth included.

# Shapes: N_row × N_col = 120 × 160 interior cells, stored (122, 162)
# Units:  η m; u, v m s⁻¹; g m s⁻²; γ s⁻¹; H m

# today (sesmax-core, sesmax#138)
class SWState(sesmax_core.State):
    # η, stagger {y: center, x: center}
    eta: gridax.CField
    # u, stagger {y: center, x: right}
    u: gridax.CField
    # v, stagger {y: right, x: center}
    v: gridax.CField

# today (sesmax-core, sesmax#138)
class SWParams(sesmax_core.Params):
    # g
    gravity: float
    # γ
    drag: float
    # H(φ, λ) at T points: a parameter that is a field
    depth: gridax.CField

Program 1:The shallow-water state and parameters as Equinox modules of CFields: the class is the schema, and the depth is a parameter that is a field.

The depth is why Params holds CFields too. It sits on the model grid like the state, grad reaches it as a leaf so it can be estimated, and on disk it goes in a node, not in attrs.

2.1 The DA vector, and the ghost ring inside it

Ensemble filters and variational solvers work on one flat vector. ravel_pytree (and sesmax-core’s state_to_vector) concatenate the leaves:

η\eta

uu

vv

grey: ghost ring

ravel_pytree (today)
59 292 entries, 1 692 of them ghosts (2.9 %)
57 600 interior entries: gridax.interior per field, embed back

The proposed vector concatenates each field’s interior, written ηint\eta_\text{int} and so on, with vec\op{vec} stacking a 2-D array into a column:

xvec=[vec(ηint);vec(uint);vec(vint)]\vect{x}_\text{vec} = [\op{vec}(\eta_\text{int}); \op{vec}(u_\text{int}); \op{vec}(v_\text{int})]
xvec∈R3NrowNcol\vect{x}_\text{vec} \in \mathbb{R}^{3 N_\text{row} N_\text{col}}

where ηint\eta_\text{int}, uintu_\text{int} and vintv_\text{int} each have shape Nrow×NcolN_\text{row} \times N_\text{col} = 120 × 160, in m and m s⁻¹.

2.2 Ensembles: name the member axis

jax.vmap over 32 members returns CFields whose data gained a leading axis. gridax names it for you: pipekit’s vmap rule (gridax#569) drops the mapped dim inside the trace and brings it back as "batch", so the dims always match the data. What it cannot know is that the axis means members; sesmax-core’s writer skips batch dims when it records a field’s dims. Rename it at rest.

after vmap (today)
data (32, 122, 162)dims ("batch","y","x")
at rest (recommended)
data (32, 122, 162)dims ("member","y","x")

gridax operators take leading batch axes, so either name costs nothing inside the trace; member is for whoever reads the file.

Carries welltransforms (jit, grad in x0\vect{x}_0 or θ\gvect{\theta}, scan over time); mixed content (fields, scalars, nested states); one flat vector for DA
Stops atcoordinates (time, member and layer are positions only); alignment by value; describing itself on disk, since its meaning is a Python class (the cfield_loc attr carries the point, nothing else)

3 · One grid on disk: an xr.Dataset

A Dataset holds several variables on shared coordinates, so it is the file form of one state or one trajectory on one grid. Its rule is the one geoarray already enforces in to_dataset: every variable on the same grid, shared coordinates aligned with join="exact", so xarray never unions two layouts and fills the gap with NaN.

3.1 Staggering as dimensions

xgcm’s convention gives each position on an axis its own dimension, with an axis attribute and, for a shifted position, c_grid_axis_shift. The model grid then has four 1-D coordinates: y_c and x_c at centres, y_g and x_g half a cell north and east. CField.to_xarray(grid, name) writes exactly these, from the grid’s coordinates, ghost ring included.

η\etauuvvx_c at the centrex_g at the east facey_cy_g

variable → dimseta (time, y_c, x_c)u (time, y_c, x_g)v (time, y_g, x_c)attrs on x_gaxis: “X”c_grid_axis_shift: 0.5xgcm.Grid(ds) reads them; CField.to_xarray writes them, one field at a time (today)

3.2 What sesmax-core writes today

state_to_dataset and snapshots_to_dataset (at 9a2fc25) take dims from the array’s rank alone: (y, x) for every 2-D field, no spatial coordinates, ghost ring included. Since sesmax#138 each CField variable also carries two attrs, cfield_dims and cfield_loc, so dataset_to_state rebuilds uu at U. Any other reader (xgcm, xrops, a plot) still sees uu on the T dims.

today
eta (time, y, x)u (time, y, x)v (time, y, x)attrs cfield_loc: "U", …no coordinates; ghosts on diskonly sesmax reads u at U
proposed
eta (time, y_c, x_c)u (time, y_c, x_g)v (time, y_g, x_c)four 1-D coordinateseach field via CField.to_xarrayxgcm reads the positions
Carries wellfiles (Zarr, netCDF), lazy dask chunks, labelled analysis, a member dim for 32 members that share every coordinate
Stops atone geometry (GLORYS’s 360 × 480 next to the 120 × 160 state needs renamed dims or a tree); no trace; no pipekit adapter (PK-P5: xrops’s Operator._apply takes a Dataset directly)

4 · A whole window on disk: an xr.DataTree

A DataTree is a tree of Datasets. Each node keeps its own dims and coordinates, and a child inherits its parent’s. So the carriers rule goes up one level: one grid is one node, and anything on another grid, or another geometry, is another node.

/ attrs: window 2026-01-01 to 2026-01-11, model, config
background/GLORYS as read: zos, uo, vo on (latitude, longitude), 360 × 480
bathymetry/GEBCO as read: elevation on (lat, lon), 7 200 × 9 600
model/coords y_c, y_g, x_c, x_g; hourly time
↓ children inherit the grid
params/depth(y_c, x_c); attrs gravity, drag
initial/eta, u, v at their positions
forecast/the same, with time: 240 frames
analysis/the same, with time
obs/no shared geometry: each child has its own
nadir/sla, sigma, hx, innovation on (obs); lon, lat, time on (obs)
swot/ssh, sigma, hx, innovation on (line, pixel); time on (line)

Teal: the model grid, held once and inherited. Blue: ingredients in the geometry they arrived in.

Hx\mat{H}\vect{x} and the innovation sit next to the observation they belong to, on its dims, so a reader can map an innovation without knowing the model grid at all.

Table 3:What already builds or reads a DataTree on main.

Exists on mainWhat it does
geoarray to_datatree, from_datatreeone node per grid: to_datatree({"r10m": g10, "r20m": g20})
xrops operatorsaccept a DataTree wherever they accept a Dataset: _apply mapped over every data-bearing node; mixing a tree and a Dataset in one call raises
geocatalog load_statesreturns a DataTree with one leaf per grid when the matched files hold more than one
Stops atnode-wise maps only: anything that couples nodes (an analysis from background and observations, fluxes between ocean and atmosphere) is explicit code, not a tree map; no trace

5 · Side by side

Table 4:The three containers, property by property.

Pytree of CFieldsxr.Datasetxr.DataTree
Structurea Python class; attributes are fieldsflat: named variablesnested: a path per node, a Dataset in each
Schema lives inthe classthe filethe file, one level deeper
Gridsany number, not stored; the model holds themoneone per node
Shared coordinatesnoneacross all variableswithin a node, plus what parents pass down
Field positionsstatic stagger per CFieldxgcm dims and attrsthe same, per node
Parametersleaves of a Params moduleattrs, or 0-d variablesa params node
jit, grad, vmapyesnono
DA vectorravel_pytree / state_to_vectorvia a statevia a state
Ensemblea leading member axisa member dima member dim inside each node
Lazy, bigger than memoryno: device arraysyesyes, per node
Operatorsgridax, GridOps, sesmax Termsxrops Operator._applyxrops, node by node
Built today bysesmax states of CFields (sesmax#138)sesmax-core io, geoarray to_datasetgeoarray to_datatree, geocatalog load_states

6 · Conversions: one hop crosses the trace

Every hop is a named call. Only one crosses into the trace, Dataset to State and back; the vector is a view of the state for the DA libraries.

Zarr store open_datatree · to_zarrDataTree (the window)tree[“/background”].to_dataset()Dataset (one grid)geoarray.from_datasetGeoArray (regrid here)ResampleLike(average), flip, embed trace boundaryCField per field

stagger uu, vv (lossy, warns)

State (pytree) select interior · embed + fill ghostsvector xvec\vect{x}_\text{vec} (a view)state_to_dataset

Above the line: xarray, lazy, labelled, any size. Below it: device arrays with static layout. Dotted hops change values (lossy); solid hops only change the container.

Table 5:Every conversion between the containers, and whether it ships.

From → toCallStatus
Zarr ↔ DataTreexr.open_datatree(store, engine="zarr"), tree.to_zarr(store)today
DataTree → Datasettree["/model/forecast"].to_dataset()today
GeoArrays ↔ Dataset / DataTreegeoarray.to_dataset, from_dataset, to_datatree, from_datatreetoday
background Dataset → Statefrom_dataset → ResampleLike(…, "average") → CField + gridax.embed; uu, vv through gridax.staggertoday
bathymetry → depth and maskthe same resample; gridax.Mask2D.from_bathymetry(depth, min_depth)today
obs file → GeoPoints / GeoSwaththe constructors; from_xarray when geoarray wrote the filetoday
GeoSwath → GeoPointsthe finite pixels, each with its line’s timeuser code
State trajectory → Hx\mat{H}\vect{x}η\eta frames as a GeoArray (trim, flip), then geoops.geom.interp_at(frames, points, frame=hour)interp_at today; the frames step has no helper
Dataset → Statesesmax_core.io.dataset_to_state(ds, SWState)today: dims by rank, the point from cfield_loc
State → Datasetstate_to_dataset, snapshots_to_datasettoday with the point as an attr; xgcm dims proposed
State ↔ vectorravel_pytree, sesmax_core.da.state_to_vectortoday with ghosts; interior proposed

7 · The window, end to end

Five steps take the window from files to one tree on disk. Each card names the container it starts and ends in. Code is a sketch: proposed names don’t exist yet, and user marks code the experiment writes itself.

7.1 Initial condition: GLORYS Dataset → model State

Setupbackground_to_stateonce per window · NumPy, then wrap

In

μx\gvect{\mu}_x GLORYS zos, uo, volat–lon A-grid, 1/12°, all at cell centres(latitude, longitude)m\mathrm{m}, m s−1\mathrm{m\ s^{-1}}

↓ηˉji=19∑(j′,i′)∈Sjiηj′i′\bar{\eta}_{ji} = \frac{1}{9} \sum_{(j', i') \in \mathcal{S}_{ji}} \eta_{j'i'}

↓uj,i+12=12(uj,i+uj,i+1)u_{j, i + \frac{1}{2}} = \frac{1}{2} (u_{j,i} + u_{j,i+1})

Out

x0\vect{x}_0 SWStateη\eta at T exact; uu at U and vv at V lossy (warns)3 × (122, 162)m\mathrm{m}, m s−1\mathrm{m\ s^{-1}}

Sji\mathcal{S}_{ji} is the 3 × 3 block of GLORYS cells inside T cell (j,i)(j, i). Regrid while it is still a GeoArray; a CField never holds a foreign grid.

# Shapes: GLORYS 360 × 480 at 1/12°; model N_row × N_col = 120 × 160 at 1/4°
# Units:  η m; u, v m s⁻¹

# today (xarray)
# → Dataset: zos, uo, vo on (latitude, longitude), 360 × 480
glorys = xr.open_zarr(glorys_store).sel(time=window_start)

# today (geoarray)
# → dict of GeoArray (360, 480)
background = geoarray.from_dataset(glorys)

# today* (geoops)
# η̄ⱼᵢ = (1/9) ∑ η over the 3 × 3 cells in T cell (j, i)
# (360, 480) → GeoArray (120, 160), m
to_model = geoops.geom.ResampleLike(like=model_t, resampling="average")
eta_t = to_model(background["zos"])

# user
# rows run south in the GeoArray, north in the model: flip, wrap, add ghosts
# (120, 160) → CField (122, 162), T
def to_t_field(g: GeoArray["y x"]) -> gridax.CField:
    # today (gridax)
    return gridax.embed(gridax.CField(g.data[::-1], ("y", "x")), grid)

# → CField (122, 162), T, m
eta_initial = to_t_field(eta_t)

# today (gridax.stagger)
# u at U = ½ (u at T west + u at T east); warns LossyConversionWarning
# → CField (122, 162), U, m s⁻¹
u_initial = gridax.stagger(to_t_field(to_model(background["uo"])), agrid, dst="U", bc=walls)

Program 2:The initial condition: GLORYS read as a Dataset, regridded as GeoArrays, wrapped as CFields at T and staggered to U.

7.2 Parameters: GEBCO GeoArray → Params and the mask

Setupdepth_and_maskonce per grid · NumPy

In

GEBCO elevation15″ grid; negative below sea level(7200, 9600)m\mathrm{m}

↓Hji=−13600∑(j′,i′)∈Gjizj′i′H_{ji} = -\frac{1}{3600} \sum_{(j', i') \in \mathcal{G}_{ji}} z_{j'i'}

↓mji=[Hji>10]m_{ji} = [H_{ji} > 10]

Out · for every call of the model

HH depth in SWParamsa CField at T, positive down(122, 162)m\mathrm{m}

mm wet mask, Mask2DT; U, V and X follow from it(122, 162)bool

zz is GEBCO elevation and Gji\mathcal{G}_{ji} the 60 × 60 GEBCO cells inside T cell (j,i)(j, i). Depth and coastline come from one field, so they agree by construction. GEBCO nests exactly, so a reshape and a mean does this without a 3 600-tap plan.

7.3 Observations: two files → GeoPoints

Host I/Oread_observationsonce per window

In

yn\vect{y}_\text{n} nadir SLA; ys\vect{y}_\text{s} SWOT SSHpoints with lon, lat, time; a swath with lat, lon per pixel, time per line(obs,), (line, pixel)m\mathrm{m}

↓λ←((λ+180) mod 360)−180\lambda \leftarrow ((\lambda + 180) \bmod 360) - 180

Out

GeoPoints ×2SWOT’s finite pixels, each with its line’s time(obs,)m\mathrm{m}

SWOT longitudes run 0–360°; the box is −70 to −30°. Neither file touches the model grid.

7.4 Run and Hx\mat{H}\vect{x}: State → GeoArray frames → GeoPoints

Gravity waves set the time step. The fastest wave has speed c=gHc = \sqrt{g H}, and the 2-D C-grid limit uses the narrowest cell.

Here Nstep=19 200N_\text{step} = 19\ 200 is the number of model steps in the window and Δxmin\Delta x_\text{min} the narrowest cell width.

Applyrun_and_observeevery cost evaluation · jit, one scan

In

x0\vect{x}_0, θ\gvect{\theta}SWState , SWParams3 × (122, 162)m\mathrm{m}, m s−1\mathrm{m\ s^{-1}}

y\vect{y} GeoPointspositions and hours(obs,)m\mathrm{m}

↓xt=f(xt−1;θ)\vect{x}_t = f(\vect{x}_{t-1}; \gvect{\theta})

↓r=y−Hxto\vect{r} = \vect{y} - \mat{H}\vect{x}_{t_o}

Out

forecast SWStateleaves gain a time axis(240, 122, 162)m\mathrm{m}, m s−1\mathrm{m\ s^{-1}}

Hx\mat{H}\vect{x}, r\vect{r}on the observations’ dims; invalid outside the box and next to land(obs,)m\mathrm{m}

tot_o is observation oo’s hour. The frames step (trim ghosts, flip rows, attach the transform) is user code today; geoarray.from_cfield is the recommended helper.

7.5 The window on disk: one DataTree

# today (xarray)
# one node per ingredient, each in its own geometry
# → DataTree, the layout of section 4
tree = xr.DataTree.from_dict({
    "/background": glorys,
    "/bathymetry": gebco.to_xarray().to_dataset(name="elevation"),
    "/model/params": params_dataset,
    "/model/initial": sesmax_core.io.state_to_dataset(x_initial),
    "/model/forecast": sesmax_core.io.snapshots_to_dataset(forecast, frame_times),
    "/model/analysis": sesmax_core.io.snapshots_to_dataset(analysis, frame_times),
    "/obs/nadir": nadir_dataset,
    "/obs/swot": swot_dataset,
})

# today (xarray)
tree.to_zarr(window_store)

Program 3:The whole window written as one DataTree, one node per ingredient, each in its own geometry.

Three pieces are missing today. The model nodes come out on (y, x) with no coordinates, so their children inherit no grid and a reader cannot place uu (writing each field through CField.to_xarray would fix it). params_dataset and the obs datasets with hx and innovation are written by hand; a states_to_datatree would build the model half.

The same split holds beyond one window. A coupled run keeps one module per component inside the trace (ocean 120 × 160, atmosphere 60 × 80) and a node per component on disk. An evaluation across resolutions opens the window tree beside an L4 product; xrops runs node by node, and the comparison itself is an explicit regrid that writes a new node.

8 · Numbers for the window

Table 6:Sizes in the window, container by container.

ContainerQuantityValueUnit
pytreeleaves of SWState + SWParams6—
vectortoday, with ghosts59 292entries
vectorinterior only57 600entries
vector32-member ensemble, float32, interior7.37MB
Datasetforecast, 3 × 240 × 122 × 162 float3256.9MB
DataTreebathymetry node, int16, as read138MB
DataTreemodel grid coordinates held once41-D arrays
runstability margin, 57 s / 45 s1.27—

9 · Rules and open questions

Proposed rules (none decided yet):

  1. Only pytrees enter a trace. A Dataset or DataTree is converted at the boundary.

  2. One geometry is one Dataset; a window of several is a DataTree with one node per ingredient.

  3. Each ingredient keeps the geometry it arrived in, on disk. The tree never regrids.

  4. Regrid while it is still a GeoArray, then wrap as a CField on the model grid.

  5. Hx\mat{H}\vect{x} and the innovation live in the observation’s node, on its dims.

  6. Members, layers and time are dims, never nodes or separate variables.

  7. A state on disk records its positions as xgcm dims, through CField.to_xarray, not only as a cfield_loc attr.

  8. A DA vector holds the interior only (gridax.interior per field); the way back is gridax.embed and a ghost fill from the BCs.

Open questions, each with a recommendation:

Table 7:The open questions and the recommended answer to each.

QuestionRecommended
Who turns a T-point CField into a GeoArray for Hx\mat{H}\vect{x}?geoarray.from_cfield(f, grid) for regular grids, duck-typed like to_geoswath; the to_geoswath path also needs interp_at to read a GeoSwath
Where does states_to_datatree live?sesmax-core io, beside the State ↔ Dataset pair
Parameters on disk?a params node: fields as variables, scalars as attrs
How does an ensemble name its axis?an explicit member dim at rest
Dataset and DataTree adapters in pipekit?no: leave PK-P5, xrops owns them