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: object

A 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:
crs: str
west: float
north: float
resolution_x: float
resolution_y: float
width: int
height: int
property shape: tuple[int, int]

Rows then columns, matching NumPy and rasterio.

property east: float
property south: float
locate(other)[source]

Row and column of another grid origin inside this one.

Raises when the other grid is not a cell-aligned subgrid. This is the check every decoder owes its caller before slicing a native array.

Parameters:

other (Grid)

Return type:

tuple[int, int]

contains(other)[source]
Parameters:

other (Grid)

Return type:

bool

class nowcast_runtime.ports.WindowSpec(offsets)[source]

Bases: object

Which 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.

Parameters:

offsets (tuple[timedelta, ...])

offsets: tuple[timedelta, ...]
classmethod uniform(step, count)[source]

The common case: count observations spaced step apart, ending now.

Parameters:
Return type:

WindowSpec

times(run_time)[source]
Parameters:

run_time (datetime)

Return type:

tuple[datetime, …]

class nowcast_runtime.ports.Frame(values, missing, units, grid, time)[source]

Bases: object

One 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.

Parameters:
values: ndarray
missing: ndarray
units: str
grid: Grid
time: datetime
property variables: int
class nowcast_runtime.ports.Prediction(values, missing, lead, valid_time)[source]

Bases: object

One 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.

Parameters:
values: ndarray
missing: ndarray
lead: int
valid_time: datetime
property members: int
class nowcast_runtime.ports.Observation(time, name, location)[source]

Bases: object

One remote or local object that a decoder can turn into a Frame.

Parameters:
time: datetime
name: str
location: str
class nowcast_runtime.ports.Source(*args, **kwargs)[source]

Bases: Protocol

Where 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 identity: str

Stable description for the run manifest. Must not carry credentials.

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.

Parameters:
Return type:

Sequence[tuple[str, str]]

fetch(observation)[source]

Return a local, fully transferred and structurally valid file.

Parameters:

observation (Observation)

Return type:

Path

prune(ttl)[source]

Delete expired managed downloads. Supplied inputs are never removed.

Parameters:

ttl (timedelta)

Return type:

int

class nowcast_runtime.ports.Decoder(*args, **kwargs)[source]

Bases: Protocol

How 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.

property native_grid: Grid

The full grid the provider publishes, which requests must fit inside.

property units: str

Physical units of the decoded values.

observed_at(name)[source]

The observation time this name encodes, or None when it is not ours.

Parameters:

name (str)

Return type:

datetime | None

read(path, grid)[source]

Decode and crop, raising on truncation or a misaligned grid.

Parameters:
Return type:

Frame

class nowcast_runtime.ports.Preprocess(*args, **kwargs)[source]

Bases: Protocol

One 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.

apply(frame)[source]

Return a Frame on the same grid, at the same time.

Parameters:

frame (Frame)

Return type:

Frame

describe()[source]

Parameters to record in the run manifest.

Return type:

Mapping[str, object]

class nowcast_runtime.ports.Postprocess(*args, **kwargs)[source]

Bases: Protocol

One 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:

Prediction

describe()[source]

Parameters to record in the run manifest.

Return type:

Mapping[str, object]

class nowcast_runtime.ports.Transform(*args, **kwargs)[source]

Bases: Protocol

A 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).

forward(values)[source]

Physical units to model space.

Parameters:

values (ndarray)

Return type:

ndarray

inverse(values)[source]

Model space back to physical units.

Parameters:

values (ndarray)

Return type:

ndarray

describe()[source]

Parameters to record in the run manifest.

Return type:

Mapping[str, object]

representable_minimum: float
representable_maximum: float
class nowcast_runtime.ports.Predictor(*args, **kwargs)[source]

Bases: Protocol

A 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 step: timedelta

Spacing between consecutive output leads.

property output_steps: int

Native horizon in leads. A request may be shorter, never longer.

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.

property grid: Grid

The grid this instance was loaded for.

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.

Parameters:
Return type:

Iterator[ndarray]

class nowcast_runtime.ports.Sink(*args, **kwargs)[source]

Bases: Protocol

How one lead is named and written.

property extension: str

File extension, without the leading dot.

filename(slug, run_time, prediction, member)[source]

Name one output. A deterministic run omits any member component.

Parameters:
Return type:

str

write(path, prediction, member, grid, units, tags)[source]

Write one member of one lead into a staging directory.

Parameters:
Return type:

None

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: object

Everything 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.

Parameters:
name: str
slug: str
version: str
bundle_roles: tuple[str, ...]
requires_runtime: str
load: Callable[[Mapping[str, Path], str, Grid], Predictor]
transform: Callable[[Mapping[str, Path]], Transform] | None = None
preprocess: Callable[[Mapping[str, Path]], Sequence[Preprocess]] | None = None
postprocess: Callable[[Mapping[str, Path]], Sequence[Postprocess]] | None = None
library_versions

alias of dict

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: object

The expensive half: a predictor, its transform and its own stages.

Parameters:
predictor: Predictor
transform: Transform
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: object

One composed deployment, before the checkpoint is read.

Parameters:
plugin: ModelPlugin
source: Source
decoder: Decoder
sink: Sink
grid: Grid
bundle: Mapping[str, object]
artifacts: Mapping[str, Path]
device: str = 'cpu'
preprocess: tuple[Preprocess, ...] = ()
postprocess: tuple[Postprocess, ...] = ()
units: str = ''
extra_versions: Mapping[str, str]
property slug: str
load()[source]

Read the checkpoint and build the model side of the pipeline.

Return type:

Loaded

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.

Parameters:

slug (str)

Return type:

Path

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:

ArgumentParser

nowcast_runtime.pipeline.validate_runtime(args)[source]
Parameters:

args (Namespace)

Return type:

None

nowcast_runtime.pipeline.forecast_directory(root, product, run_time, slug)[source]
Parameters:
Return type:

Path

nowcast_runtime.pipeline.require_fresh(run_time, max_age_hours)[source]
Parameters:
Return type:

None

nowcast_runtime.pipeline.prune(deployment, args)[source]
Parameters:
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:

str

nowcast_runtime.pipeline.apply_stages(payload, stages)[source]
nowcast_runtime.pipeline.run(args, deployment, product)[source]
Parameters:
Return type:

Path

nowcast_runtime.pipeline.tags(deployment, product, run_time, prediction)[source]
Parameters:
Return type:

dict

nowcast_runtime.pipeline.manifest(args, deployment, loaded, observations, paths, fractions, missing, steps)[source]
Return type:

dict

nowcast_runtime.pipeline.main(compose, slug, name, argv=None, sources=('local', 'ftp'))[source]

compose(args) builds the Deployment; nothing here knows a concrete adapter.

Parameters:
Return type:

int

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.

Parameters:
nowcast_runtime.scheduler.completed_run(target, timestamp, product, steps, model)[source]
Parameters:
Return type:

bool

nowcast_runtime.scheduler.poll_once(args, compose)[source]
Parameters:

args (Namespace)

Return type:

Path | None

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: ValueError

A 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.

Parameters:

value (str)

Return type:

datetime

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:
Return type:

list[Observation]

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:
Return type:

list[Observation]

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:

datetime

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: object

A 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.

Parameters:
west: float
south: float
east: float
north: float
to_grid(native)[source]
Parameters:

native (Grid)

Return type:

Grid

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:
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]
classmethod load(path)[source]
Parameters:

path (Path)

Return type:

Config

Versioned artifact bundle, verified against its own checksum manifest.

exception nowcast_runtime.artifacts.MissingArtifact[source]

Bases: FileNotFoundError

A 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.

nowcast_runtime.artifacts.sha256(path)[source]
Parameters:

path (Path)

Return type:

str

nowcast_runtime.artifacts.verify_bundle(directory, roles)[source]

Check every role a plugin declared, and only those.

Roles are a parameter rather than a fixed triple, so a model with no normalization statistics, or one carrying auxiliary static fields, needs no change here.

Parameters:
Return type:

tuple[dict, dict[str, Path]]

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: object

A 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:
  • pattern (str)

  • stamp_format (str)

  • template (str | None)

  • interval (timedelta | None)

  • end_format (str | None)

pattern: str
stamp_format: str
template: str | None = None
interval: timedelta | None = None
end_format: str | None = None
property compiled: Pattern
filename(observed)[source]

Build a name for an observation time, checked against the pattern.

Parameters:

observed (datetime)

Return type:

str

observed_at(name)[source]
Parameters:

name (str)

Return type:

datetime | None

class nowcast_runtime.builtin.decoders.RawBinaryDecoder(native_grid, naming, units, dtype='<f4', roll_columns=0, gzipped=True, suffix='.dat.gz')[source]

Bases: object

A 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:
native_grid: Grid
naming: TimestampedName
units: str
dtype: str = '<f4'
roll_columns: int = 0
gzipped: bool = True
suffix: str = '.dat.gz'
property glob: str

Pattern a local source may use to narrow its listing cheaply.

observed_at(name)[source]
Parameters:

name (str)

Return type:

datetime | None

filename(observed)[source]

A name this decoder recognizes, for generating synthetic observations.

Parameters:

observed (datetime)

Return type:

str

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.

Parameters:
Return type:

Frame

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.

Parameters:
Return type:

Path

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:

RawBinaryDecoder

Built-in sources. Each one owns its path syntax and reports bare names.

exception nowcast_runtime.builtin.sources.IncompleteDownload[source]

Bases: OSError

The 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:
  • timeout_seconds (float)

  • attempts (int)

  • retry_delay_seconds (float)

  • max_retry_delay_seconds (float)

timeout_seconds: float
attempts: int
retry_delay_seconds: float
max_retry_delay_seconds: float
delay(attempt)[source]
Parameters:

attempt (int)

Return type:

float

class nowcast_runtime.builtin.sources.Credentials(host, user, password)[source]

Bases: object

Read from the environment, never from configuration or a command line.

Parameters:
host: str
user: str
password: str
classmethod from_env(default_host, host_var, user_var, password_var, environ=None)[source]
Parameters:
Return type:

Credentials

class nowcast_runtime.builtin.sources.LocalFiles(directory, glob='*')[source]

Bases: object

Observations already on disk. Supplied inputs are never removed.

Parameters:
  • directory (Path)

  • glob (str)

property identity: str
property live: bool

Supplied inputs are reprocessed on purpose, so staleness is not a fault.

candidates(window, run_time)[source]
Parameters:
Return type:

Sequence[tuple[str, str]]

fetch(observation)[source]
Parameters:

observation (Observation)

Return type:

Path

prune(ttl)[source]
Parameters:

ttl (timedelta)

Return type:

int

class nowcast_runtime.builtin.sources.FtpSource(directory, cache, credentials, retry, verify, connect=None, sleep=<built-in function sleep>)[source]

Bases: object

FTP with bounded retries and a verified, content-addressed local cache.

Parameters:
property host: str
property identity: str

credentials never reach a run manifest.

Type:

Host and directory only

property live: bool

A latest directory keeps changing; an archive template does not.

property templated: bool

True when the directory is an archive template needing an explicit time.

candidates(window, run_time)[source]
Parameters:
Return type:

Sequence[tuple[str, str]]

fetch(observation)[source]
Parameters:

observation (Observation)

Return type:

Path

prune(ttl, now=None)[source]

Remove expired downloads from managed hash directories only.

Scoping to directories whose names are sixteen hex characters means only this cache’s own namespaces are touched, so a user directory that happens to sit under the same root is never considered.

Parameters:
Return type:

int

Built-in processing steps, each one previously a branch in shared code.

class nowcast_runtime.builtin.stages.ClipNegative(floor=0.0)[source]

Bases: object

Clamp 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)

floor: float = 0.0
apply(frame)[source]
Parameters:

frame (Frame)

Return type:

Frame

describe()[source]
Return type:

Mapping[str, object]

class nowcast_runtime.builtin.stages.MissingPolicy(policy, max_fraction, fill=0.0)[source]

Bases: object

Bound 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.

Parameters:
policy: str
max_fraction: float
fill: float = 0.0
apply(frame)[source]
Parameters:

frame (Frame)

Return type:

Frame

describe()[source]
Return type:

Mapping[str, object]

class nowcast_runtime.builtin.stages.FlipLatitude[source]

Bases: object

Reverse 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.

apply(payload)[source]
describe()[source]
Return type:

Mapping[str, object]

Built-in transforms, including the identity a model without one receives.

class nowcast_runtime.builtin.transforms.Identity[source]

Bases: object

What 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.

forward(values)[source]
Parameters:

values (ndarray)

Return type:

ndarray

inverse(values)[source]
Parameters:

values (ndarray)

Return type:

ndarray

neutral()[source]

The physical value a model reads as neutral: zero, for identity.

Return type:

float

describe()[source]
Return type:

Mapping[str, object]

class nowcast_runtime.builtin.transforms.LogZScore(mean, std)[source]

Bases: object

log1p 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.

Parameters:
mean: float
std: float
classmethod from_arrays(mean, std)[source]
Parameters:
Return type:

LogZScore

forward(values)[source]
Parameters:

values (ndarray)

Return type:

ndarray

inverse(values)[source]
Parameters:

values (ndarray)

Return type:

ndarray

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:

float

describe()[source]
Return type:

Mapping[str, object]

Built-in output formats.

class nowcast_runtime.builtin.sinks.GeoTiffSink(nodata=-9999.0, compress='deflate', predictor=3, blocksize=256, variable_names=<factory>)[source]

Bases: object

North-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:
nodata: float = -9999.0
compress: str = 'deflate'
predictor: int = 3
blocksize: int = 256
variable_names: Sequence[str]
property extension: str
filename(slug, run_time, prediction, member)[source]
Parameters:
Return type:

str

write(path, prediction, member, grid, units, tags)[source]
Parameters:
Return type:

None

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.poll_interval_seconds(environ=None)[source]
Parameters:

environ (Mapping[str, str] | None)

Return type:

int

nowcast_runtime.service.run_loop(stop, interval, download, poll)[source]

Block until the bundle is valid, then poll forever. Both phases honour stop.

Parameters:
Return type:

None

nowcast_runtime.service.serve(name, download, poll)[source]
Parameters:
Return type:

int

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:

Path

nowcast_runtime.download_artifacts.sha256(path)[source]
Parameters:

path (Path)

Return type:

str

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.

Parameters:

manifest (dict)

Return type:

list[tuple[str, str]]

nowcast_runtime.download_artifacts.file_url(base_url, name)[source]
Parameters:
Return type:

str

nowcast_runtime.download_artifacts.download_one(url, target, expected_hash, attempts, timeout)[source]
Parameters:
Return type:

str

nowcast_runtime.download_artifacts.parser()[source]
Return type:

ArgumentParser

nowcast_runtime.download_artifacts.main(argv=None)[source]
Parameters:

argv (list[str] | None)

Return type:

int

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: object

Contract checks every deployment must pass. Subclass, do not edit.

product: str = 'product'
run_time: datetime = datetime.datetime(2000, 1, 2, 12, 0, tzinfo=datetime.timezone.utc)
build(tmp_path)[source]
Parameters:

tmp_path (Path)

Return type:

Deployment

field(index, shape)[source]

One synthetic input field. Override for a model needing plausible values.

Parameters:
Return type:

ndarray

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:

Deployment

loaded(deployment)[source]
outputs(tmp_path)[source]
Return type:

Path

populated(deployment, loaded)[source]

Synthesize one full window into the deployment’s input directory.

run(deployment, outputs, *extra)[source]
test_plugin_is_compatible_with_the_installed_runtime(deployment)[source]
test_every_declared_bundle_role_resolves(deployment)[source]
test_the_model_was_loaded_for_the_deployment_grid(deployment, loaded)[source]
test_the_requested_grid_fits_the_decoder_native_grid(deployment)[source]
test_the_window_ends_at_the_run_time_and_looks_backwards(loaded)[source]
test_the_horizon_and_output_width_are_positive(loaded)[source]
test_units_are_declared_and_agree_with_the_decoder(deployment)[source]
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.

test_the_transform_describes_itself_for_the_manifest(loaded)[source]
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:

Frame

staged_frame(deployment, loaded)[source]
Return type:

Frame

test_every_stage_preserves_what_it_must(deployment, loaded)[source]
test_the_decoder_ignores_a_name_that_is_not_its_own(deployment)[source]
test_the_sink_names_members_only_when_there_are_several(deployment, loaded)[source]
test_a_full_run_publishes_a_complete_and_serializable_manifest(deployment, loaded, populated, outputs)[source]
test_valid_times_follow_the_declared_step(deployment, loaded, populated, outputs)[source]
test_a_shorter_horizon_is_honoured(deployment, loaded, populated, outputs)[source]
test_a_longer_horizon_is_refused(deployment, loaded, populated, outputs)[source]
test_a_completed_run_is_recognized_and_never_overwritten(deployment, populated, outputs)[source]
test_an_incomplete_window_waits_rather_than_narrowing(deployment, loaded, populated, outputs)[source]
test_nothing_is_published_when_a_write_fails(deployment, populated, outputs, monkeypatch)[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:
name: str
slug: str
package: str
product: str
units: str
target: Path
runtime_source: str
property substitutions: dict[str, str]
nowcast_runtime.scaffold.sha256(path)[source]
Parameters:

path (Path)

Return type:

str

nowcast_runtime.scaffold.runtime_source(target)[source]

Point at a checked-out runtime, or leave resolution to an index.

Parameters:

target (Path)

Return type:

str

nowcast_runtime.scaffold.render(plan)[source]

Every generated text file, keyed by its path inside the project.

Parameters:

plan (Plan)

Return type:

dict[str, str]

nowcast_runtime.scaffold.write_bundle(bundle)[source]

A placeholder bundle with a real manifest, so conformance runs at once.

Parameters:

bundle (Path)

Return type:

list[Path]

nowcast_runtime.scaffold.plan_from(args)[source]
Parameters:

args (Namespace)

Return type:

Plan

nowcast_runtime.scaffold.generate(plan, force=False)[source]
Parameters:
Return type:

list[Path]

nowcast_runtime.scaffold.parser()[source]
Return type:

ArgumentParser

nowcast_runtime.scaffold.main(argv=None)[source]
Parameters:

argv (list[str] | None)

Return type:

int