API reference
Generated from the source. The contracts in ports are the part worth reading
first; everything else exists to serve them.
Contracts
Contracts between the runtime and the pieces a deployment composes.
Several shapes carry axes that are length one in every deployment today. That is deliberate: ADR 0001 commits the contracts to admitting several input products, auxiliary variables and ensemble members, and a unit-length axis is never squeezed in shared code, because the squeeze is what makes the retrofit expensive later.
Arrays cross these boundaries as NumPy, never as the tensor type of a particular deep learning framework. Tensor handling belongs inside a model.
The spine every run follows, where bracketed stages may be empty:
- Source -> Decoder -> [Preprocess] -> Transform.forward -> Predictor
-> Transform.inverse -> [Postprocess] -> Sink
Stage order is load bearing, so it is fixed rather than left to a composition: configured stages run first on input and last on output, model stages run last on input and first on output. A configured step therefore always sees physical units as the provider published them, and a model step always sees them as its checkpoint expects. Reversing the output restores the input ordering, so a pair such as flipping latitude composes correctly without either side knowing about the other.
- class nowcast_runtime.ports.Grid(crs, west, north, resolution_x, resolution_y, width, height)[source]
Bases:
objectA regular, axis-aligned, north-up grid of cell areas in a single CRS.
The origin is the outer corner of the north-west cell, matching the GeoTIFF convention, so a grid is fully described without a separate transform.
- Parameters:
- class nowcast_runtime.ports.WindowSpec(offsets)[source]
Bases:
objectWhich observations one run consumes, as offsets from its run time.
Offsets are non-positive, unique and increasing, so the run time is the last entry and no run depends on a future observation. Explicit offsets subsume a fixed step with a count, and admit a non-uniform history without changing this signature.
- class nowcast_runtime.ports.Frame(values, missing, units, grid, time)[source]
Bases:
objectOne decoded observation in physical units, with its missing-data mask.
Both arrays have shape (variables, height, width). The variable axis is length one for a single-product deployment and is not squeezed.
- class nowcast_runtime.ports.Prediction(values, missing, lead, valid_time)[source]
Bases:
objectOne lead, with the mask it inherited from its inputs.
values has shape (members, variables, height, width). Both leading axes are length one for a deterministic, single-variable model and are not squeezed. Carrying the mask here keeps a Prediction self-contained, so a postprocess step and a sink both receive everything they need from one object.
- class nowcast_runtime.ports.Observation(time, name, location)[source]
Bases:
objectOne remote or local object that a decoder can turn into a Frame.
- class nowcast_runtime.ports.Source(*args, **kwargs)[source]
Bases:
ProtocolWhere observation objects are listed, and how they reach local storage.
A source owns path syntax: it supplies each candidate bare name, so shared code never has to guess whether a location is POSIX or native.
- property live: bool
True when this source keeps publishing, so staleness is meaningful.
A directory of supplied inputs is not live: rejecting it for being old would make reprocessing an archive impossible.
- candidates(window, run_time)[source]
Name and location of every object that might belong to the window.
- fetch(observation)[source]
Return a local, fully transferred and structurally valid file.
- Parameters:
observation (Observation)
- Return type:
- class nowcast_runtime.ports.Decoder(*args, **kwargs)[source]
Bases:
ProtocolHow a named object becomes a Frame on the requested grid.
The decoder owns the file name contract and the native grid, which is why a new input product requires no change to acquisition or scheduling.
- class nowcast_runtime.ports.Preprocess(*args, **kwargs)[source]
Bases:
ProtocolOne step applied to a decoded Frame, in physical units.
Runs before the transform. A deployment may declare none, which is the default: the absence of preprocessing is an ordinary configuration, not a special case.
- class nowcast_runtime.ports.Postprocess(*args, **kwargs)[source]
Bases:
ProtocolOne step applied to a Prediction, in physical units.
Runs after the inverse transform, so a step sees real units rather than model space. A deployment may declare none.
- apply(prediction)[source]
Return a Prediction for the same lead and valid time.
- Parameters:
prediction (Prediction)
- Return type:
- class nowcast_runtime.ports.Transform(*args, **kwargs)[source]
Bases:
ProtocolA model input scaling, inseparable from its checkpoint.
Optional: a model that consumes physical units declares no transform and the runtime applies identity. When one exists, the plugin binds it and configuration cannot override it, because the statistics live in the artifact bundle and a mismatch would raise nothing while producing plausible but meaningless output (ADR 0001, ADR 0004).
- class nowcast_runtime.ports.Predictor(*args, **kwargs)[source]
Bases:
ProtocolA loaded model, ready to infer on one fixed grid.
A predictor may also expose a device attribute naming where it was placed (anything whose str() reads as cpu or cuda:0). It is optional, so it is not declared below: when present the run manifest records it as the resolved device, and when absent the manifest can only repeat what was requested.
- property window: WindowSpec
The history this model consumes, including its spacing.
- property output_variables: int
How many variables each lead carries.
Declared rather than inferred from the inputs: a model may consume one field and emit several, such as a rate beside an exceedance probability.
- leads(inputs, steps)[source]
Yield steps fields of shape (members, variables, height, width), in order.
Inputs arrive as (time, variables, height, width) in model space. A model yields bare arrays: lead numbering, valid times and the mask inherited from the inputs are the runtime’s job, so a model author writes less and cannot get them inconsistent.
An iterator, so a direct model can run a single forward pass while a recurrent or autoregressive model advances its own state per lead.
- class nowcast_runtime.ports.Sink(*args, **kwargs)[source]
Bases:
ProtocolHow one lead is named and written.
- class nowcast_runtime.ports.ModelPlugin(name, slug, version, bundle_roles, requires_runtime, load, transform=None, preprocess=None, postprocess=None, library_versions=<class 'dict'>)[source]
Bases:
objectEverything the runtime needs from a model, and nothing more.
Only the first six fields are required. A model that consumes physical units and needs no model-side stages declares nothing further, because the absence of pre and post processing is the default path rather than a special case (ADR 0004).
bundle_roles is declared rather than fixed, so a model with no normalization statistics, or one with auxiliary static fields, is expressible without changing the manifest reader.
The optional factories receive the verified artifact paths, so a model-side stage may be parameterized by its own bundle.
Composition
Where concrete pieces are chosen, and the only place that knows all of them.
A model’s entrypoint builds a Deployment and hands it to the pipeline, so the runtime never imports an adapter and an adapter never imports the pipeline.
Composition is two phase on purpose. Everything a scheduled poll needs to decide whether there is new work is cheap; loading a checkpoint is not. Deployment holds the cheap half and Deployment.load produces the rest, so a poll that finds nothing new never reads a 300 MB file.
- class nowcast_runtime.composition.Loaded(predictor, transform, preprocess, postprocess)[source]
Bases:
objectThe expensive half: a predictor, its transform and its own stages.
- Parameters:
predictor (Predictor)
transform (Transform)
preprocess (tuple[Preprocess, ...])
postprocess (tuple[Postprocess, ...])
- preprocess: tuple[Preprocess, ...]
- postprocess: tuple[Postprocess, ...]
- class nowcast_runtime.composition.Deployment(plugin, source, decoder, sink, grid, bundle, artifacts, device='cpu', preprocess=(), postprocess=(), units='', extra_versions=<factory>)[source]
Bases:
objectOne composed deployment, before the checkpoint is read.
- Parameters:
- plugin: ModelPlugin
- preprocess: tuple[Preprocess, ...] = ()
- postprocess: tuple[Postprocess, ...] = ()
- input_stages(model_side)[source]
Configured steps first, so they see units as the provider published them.
- Parameters:
model_side (Sequence[Preprocess])
- Return type:
tuple[Preprocess, …]
- output_stages(model_side)[source]
Model steps first, mirroring the input order so a symmetric pair undoes itself.
- Parameters:
model_side (Sequence[Postprocess])
- Return type:
tuple[Postprocess, …]
Orchestration
Orchestration: acquire, decode, stage, infer, and atomically publish.
The invariant sequence lives here and a deployment fills the steps. That is what makes the operational guarantees uniform across models: nothing partial is ever published, a complete run is never overwritten, and every run carries a manifest recording exactly what produced it.
- nowcast_runtime.pipeline.default_cache_dir(slug)[source]
Isolate per user: a POSIX /tmp is shared, the Windows temp dir already is not.
- nowcast_runtime.pipeline.parser(slug, name, sources=('local', 'ftp'))[source]
The command line every deployment shares.
sources is the deployment’s own list of –source choices, so a model whose observations come over something other than FTP names it here rather than passing for FTP.
- Parameters:
- Return type:
- nowcast_runtime.pipeline.validate_runtime(args)[source]
- Parameters:
args (Namespace)
- Return type:
None
- nowcast_runtime.pipeline.prune(deployment, args)[source]
- Parameters:
deployment (Deployment)
args (Namespace)
- Return type:
None
- nowcast_runtime.pipeline.resolved_device(deployment, predictor)[source]
The device the model reports it is on, or the request when it reports none.
A request such as auto is resolved by the model, since only the model knows its framework. A predictor exposing a device attribute lets the manifest record where the run really happened; one without it leaves the request as the only thing known.
- Parameters:
deployment (Deployment)
- Return type:
- nowcast_runtime.pipeline.run(args, deployment, product)[source]
- Parameters:
args (Namespace)
deployment (Deployment)
product (str)
- Return type:
- nowcast_runtime.pipeline.tags(deployment, product, run_time, prediction)[source]
- Parameters:
deployment (Deployment)
product (str)
run_time (datetime)
prediction (Prediction)
- Return type:
- nowcast_runtime.pipeline.manifest(args, deployment, loaded, observations, paths, fractions, missing, steps)[source]
- Return type:
- nowcast_runtime.pipeline.main(compose, slug, name, argv=None, sources=('local', 'ftp'))[source]
compose(args) builds the Deployment; nothing here knows a concrete adapter.
One idempotent polling cycle. Any scheduler may drive it.
- nowcast_runtime.scheduler.poll_lock(output_dir, product, slug)[source]
Advisory lock shared by scheduled invocations using the same output root.
Turn a source listing into the exact window a run consumes.
What is left here is only the part that is the same for every provider. Listing, transferring and pruning belong to a Source; recognizing a name belongs to a Decoder.
- exception nowcast_runtime.acquisition.DataNotReady[source]
Bases:
ValueErrorA complete, current observation window is not available yet.
- nowcast_runtime.acquisition.parse_time(value)[source]
Parse an explicit run time. Alignment is checked when the window is known.
- nowcast_runtime.acquisition.catalog(source, decoder, window, run_time)[source]
Ask the source what exists and the decoder which of it is an observation.
- Parameters:
source (Source)
decoder (Decoder)
window (WindowSpec)
run_time (datetime | None)
- Return type:
- nowcast_runtime.acquisition.select_window(observations, window, run_time=None)[source]
Pick exactly the observations the window names, in chronological order.
A partial window is never silently narrowed to an older one: a missing entry is DataNotReady, so a scheduled poll waits instead of publishing a forecast built from the wrong history.
- Parameters:
observations (list[Observation])
window (WindowSpec)
run_time (datetime | None)
- Return type:
- nowcast_runtime.acquisition.latest_time(observations)[source]
The most recent observation time, for deciding whether a poll has work.
- Parameters:
observations (list[Observation])
- Return type:
Configuration and artifacts
Validated configuration; all paths are relative to the configuration file.
A deployment is described by one file. The runtime validates the fields it owns and carries the rest through in extra, so a model keeps its own settings beside them rather than in a second file that can drift out of step.
The schema is still close to one deployment’s shape rather than fully declarative: selecting a source or decoder by name belongs with the registry, and until then a model’s composition root reads these fields. What has gone is the hardcoded product whitelist, because a decoder now validates its own product.
- class nowcast_runtime.config.Bounds(west, south, east, north)[source]
Bases:
objectA requested extent, in the CRS of whichever decoder supplies the data.
Bounds alone cannot make a Grid: resolution and CRS belong to the provider. to_grid is therefore the negotiation between what an operator asked for and what a decoder publishes, and it fails loudly when they disagree.
- class nowcast_runtime.config.Config(artifacts: 'Path', domain: 'Bounds', model_latitude_order: 'str', product: 'str', remote_directory: 'str', missing_policy: 'str', max_missing_fraction: 'float', ftp: 'RetryPolicy', extra: 'Mapping[str, Any]' = <factory>)[source]
Bases:
object- Parameters:
- ftp: RetryPolicy
Versioned artifact bundle, verified against its own checksum manifest.
- exception nowcast_runtime.artifacts.MissingArtifact[source]
Bases:
FileNotFoundErrorA file the manifest declares is not in the bundle directory.
Distinct from a checksum mismatch on purpose. Weights are large and kept out of version control, so a fresh clone lacks them by design and the remedy is to download or prepare the bundle. A file that is present and wrong is corruption or tampering, and stays a plain error.
Built-in adapters
Decoders general enough that a new product is configuration, not code.
- class nowcast_runtime.builtin.decoders.TimestampedName(pattern, stamp_format, template=None, interval=None, end_format=None)[source]
Bases:
objectA file name contract: a regex with a stamp group, and how to read it.
One group holding the whole timestamp, rather than separate date and hour groups, is what admits a sub-hourly product: a ten-minute observation is a different stamp_format, not a different class.
template generates names and pattern matches them, because a pattern with optional groups accepts more names than it can produce.
interval and end_format together verify a provider that appends the end of its accumulation window, such as the GSMaP NOW product, instead of trusting it.
- Parameters:
- class nowcast_runtime.builtin.decoders.RawBinaryDecoder(native_grid, naming, units, dtype='<f4', roll_columns=0, gzipped=True, suffix='.dat.gz')[source]
Bases:
objectA headerless, fixed-shape binary field on a regular grid.
Everything that varies between such products is a parameter: byte order and width through dtype, the grid the array covers, how far the columns must be rolled to reach that grid origin, the units, and the file name contract. The GSMaP binary format is one configuration of this class, which is the point: another raw product needs no new module.
- Parameters:
- naming: TimestampedName
- read(path, grid)[source]
Decode and crop, raising on truncation or a misaligned request.
Values are returned exactly as stored, in physical units. Non-finite cells are reported through the mask; a provider sentinel such as a negative fill is a preprocess concern, not this decoder’s, because it is coupled to the source rather than to the format.
- synthesize(path, values, grid)[source]
Write a file this decoder reads back as values on grid.
The exact inverse of read: embed the subgrid in a native-sized array, undo the column roll, and write the raw block. A conformance suite can therefore exercise a whole deployment without any real observation, for any model whose decoder is one of these.
- nowcast_runtime.builtin.decoders.gsmap(product, native_grid=Grid(crs='EPSG:4326', west=-180.0, north=60.0, resolution_x=0.1, resolution_y=0.1, width=3600, height=1200))[source]
The GSMaP hourly rain rate binary, expressed as configuration.
JAXA stores the global field starting half a cell east of the antimeridian, so the columns are rolled by half the width to reach a -180 origin. Rows are already north first. The NOW product may append the end of its hour.
- Parameters:
- Return type:
Built-in sources. Each one owns its path syntax and reports bare names.
- exception nowcast_runtime.builtin.sources.IncompleteDownload[source]
Bases:
OSErrorThe remote object may still be uploading; retry the transfer.
- class nowcast_runtime.builtin.sources.RetryPolicy(timeout_seconds: 'float', attempts: 'int', retry_delay_seconds: 'float', max_retry_delay_seconds: 'float')[source]
Bases:
object- Parameters:
- class nowcast_runtime.builtin.sources.Credentials(host, user, password)[source]
Bases:
objectRead from the environment, never from configuration or a command line.
- class nowcast_runtime.builtin.sources.LocalFiles(directory, glob='*')[source]
Bases:
objectObservations already on disk. Supplied inputs are never removed.
- Parameters:
directory (Path)
glob (str)
- fetch(observation)[source]
- Parameters:
observation (Observation)
- Return type:
- class nowcast_runtime.builtin.sources.FtpSource(directory, cache, credentials, retry, verify, connect=None, sleep=<built-in function sleep>)[source]
Bases:
objectFTP with bounded retries and a verified, content-addressed local cache.
- Parameters:
directory (str)
cache (Path)
credentials (Credentials)
retry (RetryPolicy)
verify (Callable[[Path], None])
connect (Callable[[], ftplib.FTP] | None)
sleep (Callable[[float], None])
- fetch(observation)[source]
- Parameters:
observation (Observation)
- Return type:
Built-in processing steps, each one previously a branch in shared code.
- class nowcast_runtime.builtin.stages.ClipNegative(floor=0.0)[source]
Bases:
objectClamp finite negatives to a floor, leaving non-finite cells untouched.
A provider sentinel such as -99 is a source concern, not a format one, so it is clipped here rather than inside a decoder. Non-finite cells stay non-finite and remain the mask’s business.
- Parameters:
floor (float)
- class nowcast_runtime.builtin.stages.MissingPolicy(policy, max_fraction, fill=0.0)[source]
Bases:
objectBound how much may be missing, and decide what fills the gaps.
The fill is an explicit physical value, so this step is independent of any model transform. A deployment that wants the value a model reads as neutral passes it in; the composition root resolves that from the transform, because only the plugin knows what neutral means for its checkpoint.
- class nowcast_runtime.builtin.stages.FlipLatitude[source]
Bases:
objectReverse row order, for a model trained south to north.
The same step serves as a preprocess and a postprocess, so a deployment declares it once at each end and the output is restored to the orientation the grid describes.
Built-in transforms, including the identity a model without one receives.
- class nowcast_runtime.builtin.transforms.Identity[source]
Bases:
objectWhat the runtime applies when a plugin declares no transform.
A model that consumes physical units therefore needs no transform code at all, which is the point: the absence of preprocessing is the default path.
- class nowcast_runtime.builtin.transforms.LogZScore(mean, std)[source]
Bases:
objectlog1p followed by a scalar z-score, and its exact inverse.
The statistics belong to one checkpoint, so a plugin binds this and configuration cannot replace it.
- neutral()[source]
The physical value that maps to zero in model space.
log1p(expm1(mean)) is mean, so a cell filled with this reads as the training mean. It is not bit-identical to writing zero into model space; the difference is at float32 resolution and applies only to cells the mask already marks as missing, whose outputs are published as NoData.
- Return type:
Built-in output formats.
- class nowcast_runtime.builtin.sinks.GeoTiffSink(nodata=-9999.0, compress='deflate', predictor=3, blocksize=256, variable_names=<factory>)[source]
Bases:
objectNorth-up, pixel-area GeoTIFF with one band per variable.
A deterministic run omits any member component from the file name, so the single-member case reads exactly as it did before members were admitted.
- Parameters:
Operations
Long-lived container driver: prepare the bundle, then poll on one cadence.
The runtime owns the loop and its signal handling; a model supplies only the two callables that fetch its bundle and run one scheduled poll.
- nowcast_runtime.service.run_loop(stop, interval, download, poll)[source]
Block until the bundle is valid, then poll forever. Both phases honour stop.
Advisory, non-blocking, OS-owned exclusive lock for a single host.
- nowcast_runtime.locking.exclusive_lock(path)[source]
Yield True while this process holds the lock, False if another process holds it.
The operating system owns the lock, so it is released even when the process is killed; a leftover file never blocks a later poll. The lock covers one host and one filesystem, not replicas sharing a network volume.
- Parameters:
path (Path)
Download a versioned model bundle from public HTTP(S) using pinned local hashes.
- nowcast_runtime.download_artifacts.default_bundle()[source]
The deployment’s bundle, which is mounted beside the working directory.
The runtime ships no artifacts of its own, so there is nothing to infer from the installed package location; callers that know better pass –bundle.
- Return type:
- nowcast_runtime.download_artifacts.bundle_files(manifest)[source]
Every role the manifest declares, without trusting remote metadata.
Roles are read from the manifest rather than fixed, so a bundle with no normalization statistics, or one carrying auxiliary fields, needs no change here. The second branch reads a flat pre-schema bundle and exists only until those are republished under schema_version 1.
- nowcast_runtime.download_artifacts.download_one(url, target, expected_hash, attempts, timeout)[source]
Testing and scaffolding
A conformance suite a model repository subclasses.
Types cannot express what these contracts actually require: that a transform round trips, that a stage leaves a frame on its own grid, that nothing partial is ever published, that a completed run is recognized rather than redone. This is the third layer of enforcement ADR 0003 promised, and the only one that checks semantics.
Use it from a model’s own tests:
from nowcast_runtime.testing import ConformanceSuite
- class TestMyModel(ConformanceSuite):
product = “my_product”
- def build(self, tmp_path):
return compose_for_conformance(tmp_path)
build returns a Deployment whose source is a LocalFiles pointing at an empty directory. The suite fills that directory with observations synthesized through the deployment’s own decoder, so no real data is needed. A deployment whose decoder cannot synthesize still gets every contract-level check; the end-to-end ones skip with an explicit reason.
- class nowcast_runtime.testing.ConformanceSuite[source]
Bases:
objectContract checks every deployment must pass. Subclass, do not edit.
- field(index, shape)[source]
One synthetic input field. Override for a model needing plausible values.
- deployment(tmp_path)[source]
The deployment under test, or a skip when its bundle was never fetched.
Weights are kept out of version control, so a fresh clone cannot build the deployment at all. That is an absent prerequisite rather than a broken contract, and reporting it as an error per check buries the real ones. Only absence skips: a file that is present with the wrong checksum still fails.
- Return type:
- populated(deployment, loaded)[source]
Synthesize one full window into the deployment’s input directory.
- test_the_transform_round_trips(deployment, loaded)[source]
Over values as the transform really receives them: after the input stages.
Testing the raw field instead would be testing the wrong contract. A provider sentinel is still raw at that point, and a transform is never asked to survive one.
A transform may be lossy. A reflectivity scale saturates at both ends, so its inverse is a left inverse only between them, and a round trip outside that range is a physical property rather than a defect. Such a transform says so with representable_minimum and representable_maximum, and the check narrows to what it claims.
- raw_frame(deployment)[source]
A frame shaped exactly as a decoder would hand one over.
The mask is derived from the values rather than assumed empty. Assuming it produced a frame no decoder could ever emit, with gaps in the values and nothing in the mask, and a gap-filling stage then failed on it.
- Return type:
- test_a_full_run_publishes_a_complete_and_serializable_manifest(deployment, loaded, populated, outputs)[source]
Generate a model project that already passes conformance.
The skeleton ships a persistence predictor and a synthesized bundle, so the generated tests are green before the adopter writes a line. They then replace one function with their own architecture and watch what breaks. Starting from something that works, rather than from something that must be assembled before it can be run, is the whole point.
Templates use $-substitution so that generated Python can contain braces freely.
- class nowcast_runtime.scaffold.Plan(name: 'str', slug: 'str', package: 'str', product: 'str', units: 'str', target: 'Path', runtime_source: 'str')[source]
Bases:
object- Parameters:
- nowcast_runtime.scaffold.runtime_source(target)[source]
Point at a checked-out runtime, or leave resolution to an index.
- nowcast_runtime.scaffold.render(plan)[source]
Every generated text file, keyed by its path inside the project.
- nowcast_runtime.scaffold.write_bundle(bundle)[source]
A placeholder bundle with a real manifest, so conformance runs at once.