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.

Where does a piece of code belong?

GeoStack · background · the role ladder, read as grammar

Abstract

A library is a small language: nouns, the verbs that act on them, the adverbs that say how, and sentences and paragraphs built from them. The role ladder names seven rungs of that language, from a ⓪ structure to a ⑥ recipe, with setup beside it and orchestration above it, and says what each rung may use. This page gives the ladder and its rules. Two worked examples climb it one rung at a time, on two different sciences: a trace-gas source, from one scene to how often it leaks, and an ocean data-assimilation window.

Keywords:role ladderstructureprimitivestrategymodelalgorithmsteprecipesetuporchestration

The problem: code with no address

Most scientific code starts as one block that does the whole job: a notebook cell that turns radiance into an emission rate, or a script that runs one assimilation window from reading the background to writing the analysis. Every line in it can be right. What is missing is any answer to “where does each piece belong?”, so every piece belongs to that one block. Three ordinary requests then become hard:

  1. Reuse. Another script needs one piece, such as the noise level of a filter. It has to copy the block.

  2. Swap. Someone wants to try another covariance estimator or another taper. They have to edit the middle of the block.

  3. Save. Someone wants to rerun last month’s settings exactly. Nothing records which version of the block, with which numbers, produced the result.

The ladder is the fix: give every piece a level, and a rule for what each level may touch. Each worked example opens with its own version of the block: the trace-gas cell and the assimilation script.

Reading the figures

the jit boundary
exact: drop, assert, move
≈ lossy: interpolate, regrid
a view, a floor, not built yet
look here
an observation

The line marks used in the figures on this page and in both worked examples.

The ladder at a glance

Read it from the bottom: nouns, the verbs that act on them, the adverbs that say how, the noun phrases that carry fitted state, the sentence that does a method, and above the dashed line the sentence with its own settings and the paragraph that makes a job. The two columns are the two worked examples; the trace-gas column shows the retrieval names, and its page adds segmentation, quantification and persistency. Each rung holds a different science’s names and the same kind of thing.

rung · grammartrace gas one scene, retrieval namesocean one DA window

orchestration not a rungevery new EMIT sceneevery window, nightly

⑥ recipe paragraphplume_recipeDACycle

⑤ step sentence + settingsMethaneRetrieval(…)LocalETKF(cutoff_km=300)

carriers above · arrays belowjit boundary: the step unwraps, calls down, rewraps

④ algorithm sentencematched_filter, segmentlocal_etkf, average_apply

③ model noun phrase

Background (μy,Σy)(\gvect{\mu}_y, \gmat{\Sigma}_y)

obs plan (WH,VH)(\mat{W}_H, \mat{V}_H)

② strategy adverbLedoitWolf, SigmaThresholdGaspariCohn(c), OverlapAdd

① primitive verbtarget_signature, pixel_areagather, eigh, segment_sum

⓪ structure nounradiance (band, y, x)ensemble (member, field, y, x)

setup beside the ladderBackground.fit (spectra)interp_plan(grid, obs)

::::

:::{div}
:class: gs-figcap
Same rungs, same rules, two sciences. `matched_filter` and `local_etkf` are both ④ sentences; `Background` and the observation plan are both ③ noun phrases built once by setup.
:::
RungGrammarWhat it isTrace gas: retrieval; persistencyOcean
⓪ structurenouna thing the others act onthe radiance cube, Σ_y; the event cataloguethe ensemble, a PSD operator
① primitiveverbone call on a noun, no statetarget_signature; compute_E_Pdgather, eigh
② strategyadverbhow to do it: settings, no dataLedoitWolf; LognormalMarkGaspariCohn(c)
③ modelnoun phrasea noun with meaning and fitted stateBackground (μ_y, Σ_y); InstrumentPODobs plan WH,VH\mat{W}_H, \mat{V}_H
④ algorithmsentencea method over models, as a functionmatched_filter; fit_poisson_ratelocal_etkf
⑤ stepsentence + settingsone transformation of a carrier, ready to chainMethaneRetrieval; PersistencyLocalETKF
⑥ recipeparagraphsteps in order, making one jobplume_recipe; persistency_recipeDACycle
setupbesidebuilds a model’s state once, outside jitBackground.fit; load_pod_calibrationsinterp_plan
orchestrationaboveruns recipes on a schedule or behind an APIevery new scene; every facilityevery window, nightly

Which rung is it?

Ask eight questions in order, top to bottom, and stop at the first yes. The order matters: a recipe also transforms data, and a step also holds settings, so the bigger question goes first.

Runs other things on a schedule, over many items, behind an API?orchestration
Composes steps into one job, in code or as data?⑥ recipe
One transformation with its own config, ready to chain?⑤ step
A function that takes a model and says what to do with it?④ algorithm
An object that holds meaning and fitted state?③ model
Only settings for how something is computed, and no data?② strategy
One call on an object, with no state of its own?① primitive
The thing the calls act on?⓪ structure
No yes anywhere: it builds state from data once, so it is setup.

Ask from the top. The first yes is the rung. What a name is called, or how much happens inside it, does not count; how it is built and what it takes does.

NameRungBecause
Reproject⑤ stepcomplex inside, but one closed block with settings
RGBRecipe⑤ stepdespite its name, it does one thing to its input
UnscentedIntegrator② strategya choice of how to integrate, like CGSolver is a choice of how to solve
DACycle, TrainingLoop⑥ recipetemplates: compositions with slots for your steps
GeoArray.crop① primitivea verb on a data noun; it moves data and georeference, and computes no new field
An Airflow task that runs a recipe nightlynot a rungorchestration: it decides when and on what

The role fixes the kind

Each rung is packaged one way, so each contract is written once per kind. Here x∈RDx\vect{x} \in \mathbb{R}^{D_x} is the data, u∈RDu\vect{u} \in \mathbb{R}^{D_u} what a function needs to know about where the data sits (a transform, cell areas), θ∈RDθ\gvect{\theta} \in \mathbb{R}^{D_\theta} parameters, ψ∈RDψ\gvect{\psi} \in \mathbb{R}^{D_\psi} fitted state and cfg\mathrm{cfg} a step’s config.

KindRungsFormContract
function① ④y=f(x,u;θ)\vect{y} = f(\vect{x}, \vect{u}; \gvect{\theta})pure, arrays in and out; never sees a name, a CRS or a fill value, so it traces
Module⓪ ② ③ψ=setup(X,u;θ)\gvect{\psi} = \op{setup}(\mat{X}, \vect{u}; \gvect{\theta}), then f(x,u;θ,ψ)f(\vect{x}, \vect{u}; \gvect{\theta}, \gvect{\psi})setup once, may be untraceable; the call is pure; never holds a carrier
Operator⑤ ⑥S[f;θ](xgeo;cfg)\mathcal{S}[f; \gvect{\theta}](\vect{x}_\text{geo}; \mathrm{cfg})unwrap, compute on arrays, rewrap; cfg\mathrm{cfg} is JSON and never reaches ff

The cut between the compiled region and the carriers follows. A ⑤ step unwraps with πcfg\pi_\mathrm{cfg}, calls a ④ algorithm and rewraps with ιcfg\iota_\mathrm{cfg}:

S[f;θ](xgeo;cfg)=ιcfg(f(πcfg(xgeo);θ),xgeo)\mathcal{S}[f; \gvect{\theta}](\vect{x}_\text{geo}; \mathrm{cfg}) = \iota_\mathrm{cfg}(f(\pi_\mathrm{cfg}(\vect{x}_\text{geo}); \gvect{\theta}), \vect{x}_\text{geo})

So the apply context is exactly rungs ⓪ to ④, and the step is the seam where the georeference leaves and comes back. Three invariants hold across the stack: arrays go everywhere; carriers stop at the step; configs stop at Operators. One entanglement is allowed and documented: a verb may take an adverb (solve(A, b, solver=CGSolver())), and some adverbs call verbs.

Beside and above the ladder

Setup builds state from data or geometry, once, outside jit: a model’s state, or a structure such as a low-rank factor. It is not a rung because it is not called in the pipeline’s flow; it runs before, and its output is shipped. It is the same thing as the setup execution context, under the same name. In the trace-gas example it fits each scene’s background and loads the instruments’ detection curves; in the ocean example it builds the observation plan and the regridding plans.

Orchestration runs recipes over many items, on a schedule or behind an API, with retries and storage. It decides when, where and how often, never what is computed: the maths was finished at the recipe. Its unit of work is one scene, and then one facility, in the trace-gas example, and one 10-day window in the ocean example.

The rules that make it a ladder

RuleWhat it meansWhy
Calls go downa rung uses the rungs below it, never those aboveanything can be tested without what is built on it; the ladder is the build order
Arrays below ⑤rungs ⓪ to ④ take arrays and numbers, never a georeferenced containerthe maths runs on any container, under jit, in any library
Settings stop at ⑤configs build steps and recipes; lower rungs take plain valuesone place where settings are named and saved
Composition is closeda recipe of recipes is a recipe, so the ladder ends at ⑥what lies above is running, not composing
One name, one runga public name has exactly one rolethe docs, the tests and the reader all know where to look

The ladder and the other axes

The ladder says how big a piece is. The execution context, the pipeline stage and the map properties say other things about the same pieces, and each meets the ladder at a fixed place:

AxisMeets the ladder atHow
execution context: apply⓪ to ④the compiled region; vmap and sharding wrap a ④ algorithm
execution context: setupbeside ③the same word in both: it builds a model’s state, once, outside jit
execution context: host I/O① and ② tooquery and write_cog are ① primitives, LocalCache a ② strategy, but on bytes, not arrays
execution context: parallelism④, ⑤, ⑥, abovevmap at ④, map_blocks at ⑤, orchestration over ⑥
pipeline stage⑤ and ⑥each stage is one ⑤ step; the chain of stages is a ⑥ recipe
map properties① and ④a step inherits its algorithm’s map kind, locality and linearity

So the ladder is not an apply-only ladder. The lower rungs are grammar every context uses: host I/O has its own verbs and adverbs, and so does splitting a domain (SphericalCap is a strategy). What is apply-only is the compiled region, and that is ⓪ to ④.

Who works where

Each kind of user works in a band of the ladder and treats one rung as atomic: their floor. A page for one band says what the floor guarantees in one line and does not open it.

orchestration ⑥ recipe ⑤ step ④ algorithm ③ model ② strategy ① primitive ⓪ structure JAX, lineax data engineers geoscience researchers ML researchers numerics and CS

Filled: where each user works, coloured by the context of those rungs (blue outside the trace, teal inside). Dashed: their floor, the rung they treat as given (for data engineers and geoscientists, the bottom of their own band).

WhoWorks atFloorSpeaks in
data engineersorchestration, ⑥recipes, often as datacarriers and files
geoscience researchers⑤, ⑥stepsband names, CRS, fill values
ML researchers②, ③, ④primitivesshapes
numerics and CS⓪ to ④JAX, lineax, diffraxshapes

This is why the top two rungs get the strictest stability promises and the friendliest errors: they are the surface most people touch. And since floors leak, every step’s documentation names the algorithm it wraps, so a user can go one rung down without reading source.

The same ladder in libraries you know

RungIn libraries you knowIn the stack
⓪ Structurenp.ndarray, xr.DataArray, a SciPy sparse matrixGeoArray, DimArray, gaussx Kronecker
① Primitivenp.linalg.solve, scipy.ndimage.labelgaussx solve, logdet; geoarray crop
② Strategymethod="L-BFGS-B" in SciPy, an optax optimiser, diffrax.Tsit5CGSolver, NystromPreconditioner
③ Modela fitted scikit-learn estimator, a torch.nn.Module with weightsMultivariateNormal, LGSSM, a sesmax model
④ Algorithmscipy.optimize.minimize, a training functionkalman_filter, etkf_transform
⑤ Stepa scikit-learn transformer, a Keras layer, a torchvision transformgeoops MatchedFilter, Reproject
⑥ Recipea scikit-learn Pipeline, a Keras Sequential, a Pangeo Forge recipepipekit Sequential, Graph; DACycle
OrchestrationAirflow, Prefect, a DVC pipeline, a FastAPI serviceDVC stages, GeoApps

The correspondences in the middle column are analogies, not claims about how those libraries describe themselves. The pattern is common; what the stack adds is naming the rungs and holding every library to them.

Explaining with the ladder

The ladder is also an order for explaining a method. Nouns before verbs, verbs before adverbs, then the model, then the sentence, and only then the rungs above, if the reader works there:

  1. Start from the sentence. Say in one line what the method does.

  2. Name the nouns. Each with its shape and unit.

  3. Name the verbs. One equation each.

  4. Name the adverbs. Each as a family and a trade: what swapping it changes and what it leaves alone.

  5. Name the noun phrases. What each means, what state it holds, and what builds it.

  6. Return to the sentence. Write the method using only the pieces above. If a line needs a piece not yet named, the explanation is missing one.

  7. Go up only if the reader works there. The step and the recipe for a geoscientist; stop at move 6 for an ML reader.

Both worked examples end with this recipe applied: the matched filter in seven moves and the local ETKF in seven moves.

Worked examples

Each example climbs the ladder on one application, with the same sections in the same order, so the two can be read side by side.

ExampleApplicationThe jobWhat it shows best
Trace gas: from one scene to persistencysourcesretrieve, segment and quantify one scene; then estimate how often the facility emits, from manyevery rung filled in four stages; a model fitted once and used twice; a second recipe whose unit of work is a facility, not a scene
Ocean: one data-assimilation windowocean surfaceone 10-day local ETKF analysis over the North Atlanticstrategies as a family; setup building plans; a recipe that is a graph; parallelism at ④, ⑤ and above

Sensor fusion, land extremes and calibration are the next candidates, one per application.

Where this goes next

Idea hereIn the design pages
The ladderdefined for the whole stack, with the full EMIT example and each library’s rungs (kinds and roles)
Function, Module, Operatorthe kind axis: how each rung is packaged, in symbols (kinds and roles)
Arrays below ⑤, carriers abovethe data axis and the rule that carriers stop at GeoStack (kinds and roles, rule 3)
Which library may hold which runglayers and tiers (layer map)