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.

Design Decisions


D1: Everything is an Operator (uniform __call__ interface)

Status: accepted

Context: Should preprocessing steps, models, and metrics share a common abstraction, or be separate systems?

Options:

Decision: Option B. A regridding step, a trained model, and a metric are all callable objects with the same interface. This enables Sequential([preprocess, model, metric]) as a single pipeline.

Consequences:


D2: Split-object pattern for stateful operations (no fit/transform)

Status: accepted

Context: Some operations need to learn from data (e.g., climatology). Should operators have fit / transform methods like sklearn?

Options:

Decision: Option B. Every operator in a Sequential is Dataset → Dataset, always. State computation is explicit and happens upstream, not hidden inside the pipeline.

Consequences:


D3: Dual-mode __call__ for eager vs symbolic execution

Status: accepted

Context: Layer 2 Graph API requires operators to work in symbolic mode (building a DAG) as well as eager mode (executing on data). Should this require special operator subclasses?

Options:

Decision: Option B. The detection is in the Operator base class. Every existing operator works in a Graph automatically with zero changes.

Consequences:


D4: No framework dependency for inference (ModelOp)

Status: accepted

Context: ModelOp wraps trained models from sklearn, JAX, PyTorch, etc. Should it import these frameworks?

Options:

Decision: Option B. ModelOp never imports JAX, torch, or sklearn. It calls the model via duck typing. Framework-specific wrappers (JaxModelOp, SklearnModelOp) set ergonomic defaults but are thin subclasses.

Consequences:


D5: numpy/scipy/sklearn for compute, xarray for interface

Status: accepted

Context: What should the compute core be? JAX? Dask? Pure numpy?

Options:

Decision: Option B. Preprocessing doesn’t need GPU or autodiff. numpy/scipy/sklearn are universally available and fast enough. JAX/Dask enter only through inference backends or optional integrations.

Consequences:


D6: Graph is Dict-in, Dict-out

Status: accepted

Context: How should Graph handle multiple inputs and outputs?

Decision: Graph(inputs={"name": Input}, outputs={"name": Node}). Called with graph(name=ds). Single-input/single-output graphs can be called positionally: graph(ds).

Consequences:


D7: Metrics — own the implementation, two-layer (functions + Operator)

Status: accepted (resolved 2026-04-25)

Context: Should xrtoolz.metrics wrap xskillscore, depend on it optionally, or own the implementation?

Options:

Decision: Option C.

Consequences:


D8: Encoders live under transforms, organized by what they encode

Status: accepted (resolved 2026-04-25)

Context: Coordinate encoders (LonLatToCartesian, CyclicalTime) and basis / feature encoders (FourierFeatures, RandomFourierFeatures, PolynomialFeatures) overlap conceptually with both geo (coordinate-aware) and transforms (basis expansion). Where do they live?

Options:

Decision: Option C. All encoders move under xrtoolz.transforms.encoders, sub-organized by category:

xrtoolz/transforms/encoders/
    coord_space.py    # LonLatToCartesian, GeocentricToENU, …
    coord_time.py     # CyclicalTimeEncoding, JulianDate, …
    basis.py          # FourierFeatures, RandomFourierFeatures, PolynomialFeatures

Rationale:

Consequences:


D9: Domain stubs collapse into one kinematics submodule, sub-organized by domain

Status: accepted (resolved 2026-04-25)

Context: xrtoolz currently has empty stubs at xrtoolz/atm/, xrtoolz/ocn/, xrtoolz/ice/, xrtoolz/rs/. Each was intended to host derived physical-quantity operators (GeostrophicVelocities, WindSpeed, NormalizedDifference, etc.). Should they fill out as four parallel domain-named submodules, or collapse into one home?

Options:

Decision: Option B.

xrtoolz/kinematics/_src/
    ocean.py
    atmosphere.py
    ice.py
    remote.py

Each sub-file follows the metrics two-layer pattern: Layer 0 pure functions + Layer 1 Operator wrappers.

Rationale:

Consequences:


D10: Viz operators are first-class Operators that return Figure / Axes

Status: accepted (resolved 2026-04-25)

Context: Plotting (PlotMap, PlotSpectrum, PlotTimeseries, QuicklookPanel, etc.) produces matplotlib.Figure / Axes, not xr.Dataset. The base contract states single-input operators are Dataset → Dataset. How are viz operators integrated?

Options:

Decision: Option A.

Rationale:

Consequences:


D11: Two-tier type contract — xarray (Layer 0) → Operator (Layer 1)

Status: accepted (revised 2026-05-26)

Historical context: Originally accepted as a three-tier contract (array / xarray / Operator) on 2026-04-27. The array tier was a public surface for raw-numpy users at xrtoolz.<module>.array. After PRs α / β / γ (#206 / #208 / #209) flipped Layer 0 to DataArray-positional, the array tier added more surface than it earned — it duplicated Layer 0’s signatures with a different positional / keyword convention and forced every public-surface review to discuss “should this also exist as axis= ?”. The array tier is demoted to private _*_kernels.py modules. Users who want raw numpy can either drop into the private kernels (no stability promise) or pre-convert DataArrays.

Context: Layer 0 signatures across the package drift between numpy, xr.DataArray, and xr.Dataset. Without a clear contract, fourier / dct / wavelet / metrics / viz Layer 0 functions take a DataArray, kinematics functions take a Dataset, and users have no consistent expectation.

Decision: Two public tiers, plus a private kernel layer.

Rationale:

Modules where private kernels are not meaningful (validation, crs, subset, masks, whose math is inherently coord/attr-manipulation rather than arithmetic): they have no kernel module. Layer 0 takes xr.Dataset directly. The per-module section in api/components.md documents this.

Consequences:


D12: interpolate — unified resampling, aggregation, and smoothing module

Status: accepted (structural decision 2026-04-27; open questions resolved 2026-05-04)

Context: The v0.1 design split value resampling across three small modules: regrid (grid → grid), interpolation (gap fill + time resample), and discretize (binning). They were artificially separated; in practice users reach for “the interpolation module” as one concept. Adjacent operations — vertical coord remapping, temporal smoothing, learned super-resolution — have no clear home today (detrend.LowpassFilter is the canonical orphan).

Options:

Decision (structural): Option B.

xrtoolz/interpolate/
    _src/
        grid_to_grid.py    # Regrid, Coarsen (deterministic aggregation), Refine (deterministic interpolation)
        grid_to_points.py  # SampleAtPoints, AlongTrack
        points_to_grid.py  # ScatterToGrid, Kriging
        binning.py         # Bin2D, BinND, Bin2DTime
        gap_fill.py        # FillNaN, FillNaNRBF, FillNaNKriging
        coord_remap.py     # generic RemapAxis + vertical presets (ToSigma, ToIsopycnal, ToPressureLevels, …) and temporal preset (ToPhase)
        resample.py        # Resample (down), Upsample
        smooth.py          # MovingAverage, GaussianSmooth, LowpassFilter (KalmanSmoother → future assimilate.smooth, see resolution 3 below)
        downscale.py       # Downscale, Upscale (both wrap a ModelOp)

Naming convention:

coord_remap is generalized: vertical coord remapping (depth ↔ σ ↔ isopycnal ↔ pressure-level) is the canonical usage, but the same primitive RemapAxis handles temporal phase remapping, curvilinear-orthogonal coord transforms, and Lagrangian ↔ Eulerian rebinning. Named subclasses are presets over the generic operator.

Modules outside interpolate that handle adjacent concerns: crs.Reproject (CRS-aware regridding — calls into interpolate.Regrid internally), transforms.encoders.coord_{space,time} (coord relabeling, not value resampling).

Open-question resolutions (2026-05-04, F3.5):

  1. Super-resolution patch tiling — resolved. Downscale is a pure ModelOp wrapper with no patch_size / overlap constructor args. Tiling is delegated to xrpatcher upstream of the operator. Rationale: keeps Downscale orthogonal to tiling strategy and avoids duplicating xrpatcher’s API surface.

  2. Data fusion home — deferred. No fusion code lands in F3; revisit when the first fusion operator is proposed. interpolate.fusion remains the working assumption for deterministic-only fusion, but no commitment until assimilate exists.

  3. KalmanSmoother home — resolved. KalmanSmoother is out of scope for interpolate.smooth. It lives under future assimilate.smooth because it requires a state-space model. interpolate.smooth is restricted to deterministic, non–state-space smoothers (MovingAverage, GaussianSmooth, LowpassFilter); these still take parameters (window, sigma, cutoff), but none requires fitting a model from data.

  4. coord_remap preset scope — resolved. Ship vertical (ToSigma, FromSigma, ToIsopycnal, ToPressureLevels, ToHeight) + temporal (ToPhase) only. ToTropopauseRelative, ToBoundaryLayerCoord, and other domain-specific presets are deferred — add them on demand as new issues, each as a thin subclass over the generic RemapAxis.

Consequences:

D13: NaN/land masks — adaptive stencil selection in the kernel, opt-in

Status: accepted (2026-08-18)

Context: Finite-difference stencils propagate NaN, so every NaN cell costs a halo of roughly accuracy valid cells in each differentiated direction. xrgrad’s primary consumers are masked ocean fields, so this silently ate a strip of water around every coastline; the package did not previously mention NaN at all. See docs/design/xrgrad-nan-masks.md for the full note and the measurements.

Options:

Decision: Option B, exposed as nan_policy="adaptive" on partial / gradient / divergence / curl / laplacian, defaulting to "propagate".

Measured on an analytic field with a synthetic coastline, at the coastal cells: propagate loses 62% of them; fill-then-mask keeps them but at RMS relative error 6.5e-01; adaptive keeps them at 7.2e-03 (accuracy=1) or 1.4e-04 (accuracy=2). Interior cells are bit-identical to propagate. Filling to fix a derivative is actively harmful — harmonic relaxation solves ∇²u = 0, so the filled gradient is an artefact of the fill, converting a visible gap into an invisible wrong answer.

Option B is cheap to implement because NaN is its own support detector: any stencil reading a NaN yields NaN (0 * nan is nan, so a zero centre coefficient does not save it). Differentiating three times — central, forward, backward — and taking per point the first finite variant is exactly “widest stencil that fits”, with no mask-dilation pass and no dependence on finitediffx’s internal stencil sizing.

Consequences:


D14: Staggered (C-grid) model output — collocate before xrtoolz

Status: proposed (2026-10-05, #324) — accepted when the PR recording it merges.

Context: Ocean models built on finitevolX (somax first) hold u, v and h on Arakawa C-grid points, but write them to snapshots.zarr with the same (y, x) dims and no stagger metadata. Every horizontal diagnostic in ocn, metrics.physical and viz assumes all inputs share one grid; ocn.advection is the only place that says so (“Staggered grids are not supported”), and the only destaggering code in the workspace is WRF-specific (atm/_src/wrf.py::destagger). Mixing u-point and t-point fields silently shifts every derivative by half a cell. We need one rule for where staggering is resolved.

Options:

Decision: Option A. xrtoolz consumes collocated fields only; destaggering is the producer’s job.

Consequences: