Simulation#

The simulated machine behind the virtual accelerator. The package root imports neither numpy nor lume; the heavier modules are imported by their own names.

The simulated machine behind OSPREY’s simulator connectors.

The package root holds only what every reader needs without loading a model: the tick period and the fast period of timed passes, char-waveform decoding, the gated and labelled value types and the model status lookups. It imports neither numpy nor lume; the active-scenario state, value coercion, the composite, the texture engine, the archive and the series primitives are imported from their own modules.

osprey_connectors.simulation.DEFAULT_FAST_TICK_S = 0.1#

The fast period when the config does not set one, in seconds.

osprey_connectors.simulation.DEFAULT_TICK_S = 1.0#

The tick period when the config does not set one, in seconds.

osprey_connectors.simulation.FAST_TICK_KEY = 'simulation.fast_tick_s'#

how often the served machine advances its timed state between ticks.

Type:

The config key holding the fast period, in seconds

osprey_connectors.simulation.TICK_KEY = 'simulation.tick_s'#

The config key holding the simulated machine’s tick period, in seconds.

osprey_connectors.simulation.decode_char_waveform(value)[source]#

The text a string channel holds, whichever shape it arrives in.

A str passes unchanged. An array of character codes (a list, a tuple or a numpy array, signed or unsigned bytes) is read up to its first NUL and decoded as UTF-8, an invalid byte becoming U+FFFD.

Parameters:

value (str | Sequence[int] | np.ndarray) – The value read from the channel.

Returns:

The decoded text.

Return type:

str

osprey_connectors.simulation.model_status(connector, model)[source]#

A served physics model’s status: ok or its engine’s error text.

Parameters:
  • connector (object) – A connected control system connector serving a composite in process.

  • model (str) – The name of a served physics model.

Returns:

ok while the model’s engine serves it, no deck for a model built on purpose from nothing; otherwise the engine’s error text, capped by the composite.

Raises:

ValueError – model is not a served physics model, the message naming the served ones; or the connector serves no composite in process.

Return type:

str

async osprey_connectors.simulation.read_model_status(connector, address)[source]#

A served physics model’s status, read from its status channel.

Parameters:
  • connector (Any) – A connected control system connector.

  • address (str) – The model’s status address, <code>:SIM:<model>:STATUS.

Returns:

ok or the model’s error text.

Return type:

The text the channel holds

osprey_connectors.simulation.resolve_fast_tick_s(config)[source]#

The fast period a config asks for.

Parameters:

config (Mapping[str, Any]) – The full project config.

Returns:

simulation.fast_tick_s in seconds, or DEFAULT_FAST_TICK_S when the simulation section or its fast_tick_s entry is absent.

Raises:

ValueError – If the value is not a number greater than zero; the message names the key.

Return type:

float

osprey_connectors.simulation.resolve_tick_s(config)[source]#

The simulated machine’s tick period a config asks for.

Parameters:

config (Mapping[str, Any]) – The full project config.

Returns:

simulation.tick_s in seconds, or DEFAULT_TICK_S when the simulation section or its tick_s entry is absent.

Raises:

ValueError – If the value is not a number greater than zero; the message names the key.

Return type:

float

The active scenario set and the composition rule scenarios must obey.

Every reader of the active set — sim apply, the archive, the composite and the stand-in — resolves it and checks it here, so they cannot disagree on which scenarios run or on which sets compose; sim apply writes it here too, with write_active_state().

Scenarios compose only when they write disjoint targets: two scenarios writing one target would apply in an order-dependent way, so such a set is refused as an Overlap naming the target. A scenario’s still meets only the motion other scenarios set: it overlaps the noise or couple of the readings it stills, never another target and never another still. An archiver entry writes no target: events several scenarios script on one channel compose in set order in the archive, so they never refuse a set. A process that serves without a scenario because of an overlap logs one overlap_record(), and readers print it with format_overlap_record().

The module imports neither numpy nor lume.

osprey_connectors.simulation.state.ACTIVE_SCENARIOS_FILENAME = 'active_scenarios'#

Name of the plain-text file holding the active scenario set.

osprey_connectors.simulation.state.DEFAULT_SCENARIO = 'nominal'#

The baseline scenario, active in every set.

osprey_connectors.simulation.state.OVERLAP_EVENT = 'scenario-overlap'#

The event an overlap record carries in a simulator log.

osprey_connectors.simulation.state.STILL_SCENARIO = 'still'#

The scenario every view lists, which stills every reading.

class osprey_connectors.simulation.state.Overlap(target, first, second, motion=False)[source]#

Bases: object

One target written by two scenarios of one set.

Variables:
  • target (str) – The address or variable both scenarios write.

  • first (str) – The scenario that claimed the target first, in set order.

  • second (str) – The scenario that writes it again.

  • motion (bool) – True when one scenario stills the reading at target and the other sets its motion.

target: str#
first: str#
second: str#
motion: bool = False#
__init__(target, first, second, motion=False)#
osprey_connectors.simulation.state.composed_set(scenarios_view, names)[source]#

The set a reader serves for names: the set itself, or nominal alone.

A set whose scenarios write one target twice does not compose, and a reader serves the machine without its scenarios rather than in an order-dependent state.

Parameters:
  • scenarios_view (Mapping[str, Collection[str]]) – Each scenario’s name mapped to the targets it writes.

  • names (Sequence[str]) – The resolved set, nominal first.

Returns:

The set to serve, and the overlaps that kept its scenarios out.

Raises:

ValueError – If a name is not in scenarios_view.

Return type:

tuple[list[str], list[Overlap]]

osprey_connectors.simulation.state.format_overlap_record(model, record)[source]#

One printable line for an overlap record read back from a model’s log.

The line names where it came from, so a reader never takes it for the model’s status.

Parameters:
  • model (str) – The model whose log holds the record.

  • record (Mapping[str, object]) – The record as overlap_record() wrote it.

Returns:

<model> (log, instance <i>, pid <p>): <event> on <target>.

Return type:

str

osprey_connectors.simulation.state.overlap_record(overlap, *, instance, pid)[source]#

The log record a process writes when it serves without a scenario.

Parameters:
  • overlap (Overlap) – The overlap that kept the scenario out.

  • instance (str) – The serving instance that logs it.

  • pid (int) – The process id of that instance.

Returns:

The record, one JSON line in the simulator log.

Return type:

dict[str, str | int]

osprey_connectors.simulation.state.parse_active_state(text)[source]#

The scenario names and the anchor an active_scenarios file records.

Blank lines and # comments are skipped. A key=value line is metadata, of which only anchor=<ISO 8601> is read; every other line is a scenario name, kept in file order. A naive anchor is read in the facility timezone; a malformed one is logged and ignored.

Parameters:

text (str) – The file’s contents.

Returns:

The names, and the anchor as epoch seconds or None when the file records none.

Return type:

tuple[list[str], float | None]

osprey_connectors.simulation.state.read_active_state(state_dir)[source]#

The scenario names and the anchor the active_scenarios file in state_dir records.

Parameters:

state_dir (Path) – The directory holding the file.

Returns:

What parse_active_state() reads from the file, or ([], None) when the file is absent.

Return type:

tuple[list[str], float | None]

osprey_connectors.simulation.state.resolve_active_scenarios(names)[source]#

The active scenario set a request for names really means.

nominal is the machine’s baseline, not a fault: it is always active, so it is prepended whether or not the caller named it. The rest keep the caller’s order and are deduplicated, because activating a scenario twice would compose its physics twice.

One function for a rule two callers depend on — activation writes the state file from it, and physics-fault rendering derives VA_* variables from it — so the environment a project is built with and the scenarios its engine runs cannot describe different machines.

Return type:

list[str]

osprey_connectors.simulation.state.scenario_targets(scenario)[source]#

The targets a scenario writes: addresses, engine variables and coupled channels.

Parameters:

scenario (Mapping[str, Any]) – One entry of the simulator view’s scenario list.

Returns:

The keys of its overrides, the keys of every fault’s writes, the keys of its channel_faults, and the keys of couple and noise; a block the scenario does not state contributes nothing. archiver entries are not targets: the archive merges the events of every active scenario on a channel in set order. The couple and noise keys and the still readings are also targets of the motion namespace, which validate_composition() reads apart.

Return type:

set[str]

osprey_connectors.simulation.state.validate_composition(scenarios_view, names)[source]#

Return the overlaps of a scenario set; an empty list means it composes.

nominal writes nothing, so it is skipped when the view does not list it.

Parameters:
  • scenarios_view (Mapping[str, Collection[str]]) – Each scenario’s name mapped to the targets it writes.

  • names (Sequence[str]) – Scenario names to check, in set order.

Returns:

One Overlap per target a later scenario writes again, sorted by target within each scenario, then one per reading and scenario pair where one scenario stills the reading and the other sets its motion.

Raises:

ValueError – If a name is not in scenarios_view.

Return type:

list[Overlap]

osprey_connectors.simulation.state.write_active_state(path, scenarios_view, names, *, anchor=None)[source]#

Activate a scenario set by writing the active_scenarios file.

The file holds an anchor=<ISO 8601> line when anchor is given, then the set’s scenarios other than nominal, or nominal alone. It is replaced whole through safety_file.atomic_replace, so a reader polling it never reads a half-written set.

Parameters:
  • path (Path) – The state file.

  • scenarios_view (Mapping[str, Collection[str]]) – Each scenario’s name mapped to the targets it writes.

  • names (Sequence[str]) – The requested scenario names; nominal is always active.

  • anchor (datetime | None) – The instant the set is applied at.

Returns:

The resolved set, nominal first.

Raises:

ValueError – If a name is unknown or the set does not compose; nothing is written.

Return type:

list[str]

The simulator view a build writes, and the one reader of it.

osprey build writes each render’s simulator view into <render>/data/simulator/; this module names its files and their schemas and opens it. Every reader of a view opens it through SimulatorView, which refuses a file whose schema is not the one this OSPREY reads, so a render from an older OSPREY is rebuilt rather than misread.

A wiring record of a physics model carries what its engine’s describe() stated at build time: its engine_role (one of ENGINE_ROLES), the transverse plane it steers or reads (x, y or None), its refresh (one of REFRESH) and, when it carries any, its marks (of MARKS). The words are the facility schema’s. A readback is any read of an element’s setting, paired with a setpoint or not; a reader wanting the readback of a setpoint reads that setpoint channel’s pair.

The module imports only the standard library and osprey_connectors, so a reader that must not load a model can open a view.

osprey_connectors.simulation.view.COMMAND_MARK = 'command'#

The mark of a record whose write is a command; only a write record carries it.

osprey_connectors.simulation.view.DECKS_DIR = 'decks'#

The directory holding a byte copy of each deck-bearing model’s deck.

osprey_connectors.simulation.view.ENGINE_ROLES = ('setpoint', 'readback', 'monitor', 'output')#

The engine roles a wiring record’s description names. A channel’s facility role is setpoint or readback.

osprey_connectors.simulation.view.IOC_HEALTH_SIGNALS = ('HEARTBEAT', 'UPTIME', 'ENGINEER')#

The signals of a model’s IOC health addresses, <code>:SIM:<model>:<signal>, in the order a view lists them.

osprey_connectors.simulation.view.MARKS = ('command',)#

The marks a wiring record’s description may set.

osprey_connectors.simulation.view.PERIODIC_IOC_HEALTH = ('HEARTBEAT', 'UPTIME')#

The IOC health signals each periodic pass publishes.

osprey_connectors.simulation.view.PLANES = ('x', 'y')#

The planes a wiring record’s description names; None is no plane.

osprey_connectors.simulation.view.REFRESH = ('pass', 'periodic', 'fast', 'event')#

pass with each write’s solve, periodic with the periodic solve alone, fast at the fast period, event with each event the engine raises.

Type:

The refresh a wiring record’s description names

osprey_connectors.simulation.view.SCENARIOS_DIR = 'scenarios'#

The directory holding each scenario’s attached files, scenarios/<name>/, under the facility tree and under the view alike.

osprey_connectors.simulation.view.SERVED_SIGNAL_PROPERTY = 'signal'#

The directory property the simulator sets on each status and IOC health row, valued with that row’s signal; channel rows carry none.

osprey_connectors.simulation.view.SCHEMAS: Mapping[str, str] = mappingproxy({'served_models.json': 'osprey.facility.served_models/1', 'addresses.json': 'osprey.facility.addresses/1', 'variables.json': 'osprey.facility.simulator/4', 'seeds.json': 'osprey.facility.seeds/2', 'scenarios.json': 'osprey.facility.scenarios/3'})#

Each view file and the schema it carries.

osprey_connectors.simulation.view.STATUS_SIGNAL = 'STATUS'#

The signal of a physics model’s status address, <code>:SIM:<model>:STATUS.

osprey_connectors.simulation.view.VIEW_RELPATH = PurePosixPath('data/simulator')#

The view’s directory under a render.

class osprey_connectors.simulation.view.Binding(id, model, address, direction, engine_role, plane, refresh, element, record, marks=frozenset({}))[source]#

Bases: object

One wiring record of a physics model: the address it serves and what it is.

Variables:
  • id (str) – The wiring record’s id.

  • model (str) – The model the record belongs to.

  • address (str) – The channel address the record serves.

  • direction (str) – write or read.

  • engine_role (str) – One of ENGINE_ROLES. A readback reads an element’s setting, paired with a setpoint or not; the setpoint channel’s pair names its readback.

  • plane (str | None) – x or y for a record steering or reading one transverse plane, else None.

  • refresh (str) – One of REFRESH.

  • element (str | None) – The element the record names, or None (a record naming slices, or none).

  • record (collections.abc.Mapping[str, Any]) – The wiring record as the view states it, read-only; the engine’s build takes it verbatim.

  • marks (frozenset[str]) – The MARKS the record carries; empty when it carries none.

id: str#
model: str#
address: str#
direction: str#
engine_role: str#
plane: str | None#
refresh: str#
element: str | None#
record: Mapping[str, Any]#
marks: frozenset[str] = frozenset({})#
classmethod from_record(model, record)[source]#

Read one wiring record of variables.json.

Raises:

ViewSchemaError – the record lacks engine_role, plane or refresh.

Return type:

Binding

__init__(id, model, address, direction, engine_role, plane, refresh, element, record, marks=frozenset({}))#
class osprey_connectors.simulation.view.Channel(address, role, pair, value_type, unit, description, writable, value_range, owner, on, options, shape, precision)[source]#

Bases: object

One channel of the view, as variables.json states it.

Variables:
  • address (str) – The channel’s address.

  • role (str) – The facility file’s role, readback when it states none.

  • pair (str | None) – A setpoint’s readback, itself when it names none; None on any other role.

  • value_type (str) – The channel’s value type.

  • unit (str | None) – The channel’s unit, or None.

  • description (str | None) – The channel’s description, or None.

  • writable (bool) – Whether a write to the channel is allowed.

  • value_range (tuple[float, float] | None) – (min, max) from the channel’s limits record, or None.

  • owner (str) – The model wiring the address, else texture.

  • on (collections.abc.Mapping[str, str] | None) – The node the channel is on, {device: id} or {place: id}, or None.

  • options (tuple[str, ...] | None) – An enum channel’s options, or None.

  • shape (tuple[int, ...] | None) – A waveform channel’s shape, or None.

  • precision (int | None) – A float channel’s display precision, or None.

address: str#
role: str#
pair: str | None#
value_type: str#
unit: str | None#
description: str | None#
writable: bool#
value_range: tuple[float, float] | None#
owner: str#
on: Mapping[str, str] | None#
options: tuple[str, ...] | None#
shape: tuple[int, ...] | None#
precision: int | None#
classmethod from_entry(entry)[source]#

Read one channel entry of variables.json.

Raises:

ViewSchemaError – the entry lacks a key every channel carries.

Return type:

Channel

__init__(address, role, pair, value_type, unit, description, writable, value_range, owner, on, options, shape, precision)#
class osprey_connectors.simulation.view.Model(name, engine, served, settings, deck, bindings, inputs=())[source]#

Bases: object

One model of the view.

Variables:
  • name (str) – The model’s name.

  • engine (str | None) – The engine the model names.

  • served (bool) – Whether the render serves the model.

  • settings (collections.abc.Mapping[str, object]) – The model’s settings, read-only.

  • deck (pathlib.Path | None) – The path of the view’s copy of the model’s deck, or None.

  • bindings (tuple[osprey_connectors.simulation.view.Binding, ...]) – The model’s wiring records, in wiring order; empty for a texture model or one without wiring.

  • inputs (tuple[collections.abc.Mapping[str, object], ...]) – The model’s inputs, in declared order, each a read-only {address, engine} record: the producer channel’s address and the engine block the consuming engine reads; empty when the model declares none.

name: str#
engine: str | None#
served: bool#
settings: Mapping[str, object]#
deck: Path | None#
bindings: tuple[Binding, ...]#
inputs: tuple[Mapping[str, object], ...] = ()#
__init__(name, engine, served, settings, deck, bindings, inputs=())#
exception osprey_connectors.simulation.view.NoSimulatorView[source]#

Bases: LookupError

The place holds no simulator view: it has no addresses.json.

class osprey_connectors.simulation.view.SimulatorView(path)[source]#

Bases: object

A render’s simulator view, opened from its directory.

addresses.json is read when the view opens; every other file is read once, on first use, and each is refused when its schema is not the one this OSPREY reads.

Variables:
  • path – The view’s directory.

  • render_root – The render the view sits in, when the view is at <render>/data/simulator; else None.

__init__(path)[source]#
classmethod open(view_dir)[source]#

Open the view in view_dir.

Raises:
Return type:

SimulatorView

classmethod of_render(render_root)[source]#

Open the view of the render rooted at render_root.

Return type:

SimulatorView

classmethod path_for_project(project_dir)[source]#

Where the view of project_dir’s render is, read or not.

A deployment repo keeps its render under build/, beside the rendered config.yml; a container’s project directory is the render itself.

Return type:

Path

classmethod of_project(project_dir)[source]#

Open the view of project_dir’s render (path_for_project()).

Return type:

SimulatorView

classmethod find(project_dir)[source]#

Open the view of project_dir’s render, or None when it has none.

Raises:

ViewSchemaError – the view is there but from another schema.

Return type:

SimulatorView | None

document(name)[source]#

One view file, parsed once and read-only.

Parameters:

name (str) – The file’s name, one of SCHEMAS.

Raises:

ViewSchemaError – the file’s schema is absent or neither SCHEMAS[name] nor an older one this OSPREY still reads.

Return type:

Mapping[str, Any]

property code: str#

The facility’s identity code.

models()[source]#

Every model of the facility file, sorted by name.

Return type:

tuple[Model, …]

model(name)[source]#

The model named name.

Raises:

KeyError – the view has no such model.

Return type:

Model

served()[source]#

The names of the models the render serves, in served_models.json order.

Return type:

tuple[str, …]

physics_models()[source]#

The served models whose engine is not texture, sorted by name.

Return type:

tuple[Model, …]

channels()[source]#

Every channel address of the facility file, sorted.

Return type:

tuple[str, …]

status_addresses()[source]#

Each served physics model’s status address, <code>:SIM:<model>:STATUS.

Return type:

Mapping[str, str]

ioc_health_by_model()[source]#

Each listed model’s IOC health addresses by signal, {model: {signal: address}}.

An address is <code>:SIM:<model>:<signal> with <signal> one of IOC_HEALTH_SIGNALS; each model’s signals keep the list’s order. ioc_health is optional under ADDRESSES_SCHEMA: a view from a build without it yields an empty mapping. Unlike the status addresses, it lists the texture model too.

Raises:

ViewSchemaError – a listed entry is not such an address.

Return type:

Mapping[str, Mapping[str, str]]

channel(address)[source]#

The channel at address.

Raises:

KeyError – the view has no channel at address.

Return type:

Channel

bindings(*, model=None, engine_role=None, plane=None, node=None, served_only=True)[source]#

The physics models’ wiring records, model by name, then in wiring order.

Parameters:
  • model (str | None) – Only this model’s records.

  • engine_role (str | None) – Only records of this engine role.

  • plane (str | None) – Only records of this plane.

  • node (str | None) – Only records whose channel is on this node (a value of the channel’s on).

  • served_only (bool) – Only the served models’ records.

Return type:

tuple[Binding, …]

binding(address)[source]#

The served physics model’s wiring record of address, or None.

Return type:

Binding | None

seed(address)[source]#

The seed record of the channel at address, or None.

Return type:

Mapping[str, Any] | None

scenarios()[source]#

Every scenario of scenarios.json, sorted by name.

Raises:

ViewSchemaError – A scenario’s still is not a list of addresses.

Return type:

tuple[Mapping[str, Any], …]

motion_envelope(address, active=())[source]#

The band address’s served motion keeps it within around its held value.

Parameters:
  • address (str) – A channel address.

  • active (Sequence[str]) – The active scenario names, in order; nominal always counts, as the composite counts it.

Returns:

The channel’s envelope under active (osprey_connectors.simulation.envelope.active_envelopes()); 0.0 for a channel that declares no motion.

Return type:

float

scenario_dir(name)[source]#

The view’s copy of a scenario’s attached files, scenarios/<name>/.

Return type:

Path

exception osprey_connectors.simulation.view.ViewSchemaError[source]#

Bases: ValueError

A view file’s schema is not the one this OSPREY reads, or its shape breaks that schema.

Channel value coercion and zero values per value_type.

One function set shared by the connectors package and the facility build, so both accept and refuse exactly the same values. The module imports only the standard library: no framework enters through it.

Stored representations:

  • float -> float; int -> int;

  • bool / enum -> the label (str) from options;

  • string -> str;

  • waveform -> a flat, row-major list[float] whose length is the product of shape.

osprey_connectors.simulation.values.GATED_TYPES = ('float', 'int', 'bool', 'enum')#

The value types a seed’s gate applies to.

osprey_connectors.simulation.values.LABELLED_TYPES = ('bool', 'enum')#

The value types whose channels carry labels.

osprey_connectors.simulation.values.StoredValue: TypeAlias = float | int | str | list[float]#

A channel value in its stored representation.

osprey_connectors.simulation.values.channel_labels(channel)[source]#

The labels of a bool or enum channel record.

Parameters:

channel (Mapping[str, Any]) – The channel record.

Returns:

The record’s options, or DEFAULT_BOOL_OPTIONS without them.

Return type:

list[str]

osprey_connectors.simulation.values.coerce(value: object, value_type: Literal['float'], options: Sequence[str] | None = None, shape: Sequence[int] | None = None) → float[source]#
osprey_connectors.simulation.values.coerce(value: object, value_type: Literal['int'], options: Sequence[str] | None = None, shape: Sequence[int] | None = None) → int
osprey_connectors.simulation.values.coerce(value: object, value_type: Literal['bool', 'enum', 'string'], options: Sequence[str] | None = None, shape: Sequence[int] | None = None) → str
osprey_connectors.simulation.values.coerce(value: object, value_type: Literal['waveform'], options: Sequence[str] | None = None, shape: Sequence[int] | None = None) → list[float]
osprey_connectors.simulation.values.coerce(value: object, value_type: str | None, options: Sequence[str] | None = None, shape: Sequence[int] | None = None) → float | int | str | list[float]

Coerce value to the stored representation of value_type.

Parameters:
  • value (object) – The value to coerce.

  • value_type (str | None) – One of _VALUE_TYPES; None means float.

  • options (Sequence[str] | None) – The labels of a bool or enum channel; a bool without options uses DEFAULT_BOOL_OPTIONS.

  • shape (Sequence[int] | None) – The dimensions of a waveform channel.

Returns:

The coerced value in its stored representation.

Raises:

ValueError – The value is refused for the type; the message names the type and the value.

Return type:

float | int | str | list[float]

osprey_connectors.simulation.values.is_waveform(value_type)[source]#

Whether a channel of value_type carries a trace rather than a scalar.

Return type:

bool

osprey_connectors.simulation.values.zero(value_type, options, shape)[source]#

Return the zero value of value_type in its stored representation.

Parameters:
  • value_type (str | None) – One of _VALUE_TYPES; None means float.

  • options (Sequence[str] | None) – The labels of a bool or enum channel.

  • shape (Sequence[int] | None) – The dimensions of a waveform channel.

Returns:

0.0, 0, options[0], "" or product(shape) zeros.

Raises:

ValueError – value_type is unknown, or its options or shape are missing.

Return type:

float | int | str | list[float]

A served physics model’s status, read from a connector.

model_status() answers from the composite a connector serves in process. read_model_status() reads a model’s status channel through any connector, the way a target served by a separate process reports it. STATUS_OK and STATUS_NO_DECK are the two texts that are not an error; is_error() is the one test of that. The module imports nothing beyond the standard library, so a status lookup loads no model: the composite is reached through the connector when asked.

osprey_connectors.simulation.status.STATUS_NO_DECK = 'no deck'#

The status of a model that names no deck and wires no channel. Nothing is built for it, by design: the facility describes the machine, and every channel of it is the texture’s.

osprey_connectors.simulation.status.STATUS_OK = 'ok'#

A physics model’s status while its engine serves it.

osprey_connectors.simulation.status.is_error(status)[source]#

Whether a model’s status text is an error.

Parameters:

status (str) – A model’s status, as model_status() or read_model_status() returns it.

Returns:

False for STATUS_OK and STATUS_NO_DECK, a model built on purpose from nothing; True for any other text, which is the error the model failed with.

Return type:

bool

osprey_connectors.simulation.status.model_status(connector, model)[source]#

A served physics model’s status: ok or its engine’s error text.

Parameters:
  • connector (object) – A connected control system connector serving a composite in process.

  • model (str) – The name of a served physics model.

Returns:

ok while the model’s engine serves it, no deck for a model built on purpose from nothing; otherwise the engine’s error text, capped by the composite.

Raises:

ValueError – model is not a served physics model, the message naming the served ones; or the connector serves no composite in process.

Return type:

str

async osprey_connectors.simulation.status.read_model_status(connector, address)[source]#

A served physics model’s status, read from its status channel.

Parameters:
  • connector (Any) – A connected control system connector.

  • address (str) – The model’s status address, <code>:SIM:<model>:STATUS.

Returns:

ok or the model’s error text.

Return type:

The text the channel holds

Materializing a deployment’s archive: the base seed and its fingerprint.

A deployment that serves simulated channels needs history for them, and the honest way to have history is to store it. This module computes that stored history and writes it: one document per timestamp carrying every channel, over a two-tier grid reaching back the configured retention, in the schema MongoDBArchiverConnector already reads.

The values are not this module’s invention. Every channel is read from the archive composite (build()), the simulator view’s composite at the start state of the active scenario set, evaluated at each document’s own absolute timestamp. Every sample is a pure function of (channel, epoch seconds) under that set, so a document written here at time T holds exactly what the composite serves at T: seeded history and the served machine are one world rather than two plausible ones.

Three pieces of the design are worth stating outright:

  • Two tiers, one grid. The coarse tier spans the full retention window; the dense tier adds samples between its points over the recent span. They are built from one epoch-aligned grid and the dense tier skips timestamps the coarse tier already owns, so no timestamp is written twice — the schema is one document per timestamp and a duplicate would be a second, competing sample.

  • Retention is per document, not per collection. Each document carries an expireAt that a TTL index acts on, stamped by the tier that produced it. A coarse sample lives for the retention span, a dense one until it ages out of the dense span, and a document with no stamp at all never expires — which is what lets a later scenario rewrite protect the windows it touches by simply removing the field.

  • Reseeding is a decision, not a default. A seed manifest records the knobs the store was built with, and compare_fingerprint() reports match, mismatch or absence. The seed instant is stored but deliberately excluded from the comparison — it differs on every deploy, and including it would make every deploy a reseed.

This module never imports pymongo: the functions that talk to a store take a collection handle their caller opened. That keeps an optional dependency optional, and leaves the grid, the fingerprint and the synthesis — the parts worth reasoning about — pure and testable with no store at all.

The archive composite. build() reads a simulator view’s history through a composite of its own, built at the start state of one active scenario set: the set’s active writes, never a session write. The composite is read once, one solve per physics model, and ArchiveComposite then computes every timestamp from those held values: the active scenarios’ archiver events, then the texture’s drift, couplings and keyed noise, the physics engine’s readout and the clamp, as the composite serves them. Samples are in the wire representation, so a bool or enum channel archives its option index. lume is imported inside build() only.

osprey_connectors.simulation.archive.DATE_FIELD = 'date'#

Field naming the instant a document’s sample was taken. The connector queries and sorts on it; the manifest document deliberately has none, which is what keeps it out of every archiver read without needing a filter.

osprey_connectors.simulation.archive.EXPIRE_FIELD = 'expireAt'#

Field the TTL index acts on. A document without it never expires.

osprey_connectors.simulation.archive.MANIFEST_ID = 'osprey:seed_manifest'#

_id of the seed-manifest document. A fixed id makes writing it an upsert and reading it a primary-key lookup, and makes a second manifest impossible.

class osprey_connectors.simulation.archive.ArchiveComposite(channels, held, events, composite, *, anchor_s, tz, state=None, pulses=None, topoffs=None)[source]#

Bases: object

A simulator view’s history for one active scenario set.

Every sample is a pure function of the channel, its held value at the start state, the active scenarios and the epoch time, so two windows that share a timestamp agree on it.

Parameters:
  • channels (Mapping[str, Mapping[str, Any]]) – Each channel’s record in variables.json, by address.

  • held (Mapping[str, object]) – Each channel’s held value at the start state, in its stored representation; a gate channel’s is its gated value while an input blocks, as the live read serves it.

  • events (Mapping[str, Sequence[Mapping[str, Any]]]) – The active scenarios’ archiver events, by address.

  • composite (Composite) – The composite at the start state, whose readings every float channel carries.

  • anchor_s (float) – The epoch seconds an at_offset event is placed from.

  • tz (ZoneInfo | None) – The zone a daily at_time event is placed in.

  • state (tempfile.TemporaryDirectory[str] | None) – The directory holding composite’s active set, removed by close.

  • pulses (Mapping[str, Mapping[str, object]] | None) – Each pulsed waveform channel’s pulse seed, by address: the driver and enable channels its trace is computed from.

  • topoffs (Mapping[str, Mapping[str, Any]] | None) – Each channel’s topoff seed record, by address, for the channels whose loss events top-off refills.

Raises:

ValueError – A pulse seed names a driver or enable that is not a channel of the view.

__init__(channels, held, events, composite, *, anchor_s, tz, state=None, pulses=None, topoffs=None)[source]#
topoff_record(address)[source]#

The topoff seed record that refills address’s loss events, or None.

Return type:

Mapping[str, Any] | None

close()[source]#

Remove the state directory, when the composite holds one; a second call does nothing.

property addresses: list[str]#

The archived channel addresses, sorted.

property waveform_addresses: list[str]#

The archived waveform channel addresses, sorted.

Their traces are stored one document per channel and instant in the waveform_collection() beside the snapshot documents.

property scalar_addresses: list[str]#

every non-waveform channel.

Type:

The archived addresses the snapshot documents carry

traces(address, t_s)[source]#

One waveform channel’s traces at absolute epoch seconds.

A pulsed channel’s trace is trace() at each instant, at its driver’s and its enable’s levels there: each one’s start-state value moved by the active scenarios’ archiver events, with no texture motion. An enable is on where its wire value is not zero, so a bool or enum enable is off at its first option. A waveform channel without a pulse seed holds its start-state trace.

Parameters:
  • address (str) – A waveform channel address of the view.

  • t_s (Sequence[float] | ndarray) – Epoch seconds, ascending.

Returns:

One flat float64 trace per timestamp.

Raises:
  • ChannelNotFoundError – address is not a channel of the facility.

  • ValueError – address is not a waveform channel.

Return type:

list[ndarray]

held(address)[source]#

A channel’s held value at the start state, in its stored representation.

Raises:

KeyError – address is not a channel of the view.

Return type:

object

series(address, t_s)[source]#

One channel’s samples at absolute epoch seconds, in the wire representation.

A float channel holds its start-state value, moved by the active scenarios’ archiver events, and reads that level as the composite serves it: a moving channel with its motion, its engine’s readout and its clamp, a physics setpoint as it is. Any other channel holds its start-state value, moved only by step events; a bool or enum sample is its option index. A waveform sample is its trace (traces()) as a list[float].

Parameters:
  • address (str) – A channel address of the view.

  • t_s (Sequence[float] | ndarray) – Epoch seconds, ascending.

Returns:

One sample per timestamp.

Raises:

KeyError – address is not a channel of the view.

Return type:

list[object]

samples(addresses, t_s)[source]#

Several channels’ samples at absolute epoch seconds, as series() gives each.

The float channels are read together, so a physics model’s readout runs once per timestamp for all of them rather than once per channel.

Parameters:
  • addresses (Sequence[str]) – Channel addresses of the view.

  • t_s (Sequence[float] | ndarray) – Epoch seconds, ascending.

Returns:

One sample per timestamp, by address.

Raises:

KeyError – An address is not a channel of the view.

Return type:

dict[str, list[object]]

class osprey_connectors.simulation.archive.FingerprintComparison(state, differences=(), seeded_at=None)[source]#

Bases: object

The outcome of comparing a store’s manifest against current knobs.

state: SeedState#
differences: tuple[tuple[str, object, object], ...] = ()#

(key, stored, expected) for each field that moved. Empty unless the state is SeedState.MISMATCH. Carried so the deploy step can report what changed rather than announcing an unexplained reseed.

seeded_at: datetime | None = None#

The instant the stored seed was anchored at, when there is one. Metadata: it is never compared (see the module docstring).

describe()[source]#

One line per changed knob, for a deploy-time report.

Return type:

str

__init__(state, differences=(), seeded_at=None)#
class osprey_connectors.simulation.archive.SeedKnobs(retention_days=30, hot_span_hours=48, hot_cadence_sec=10, tail_cadence_sec=60)[source]#

Bases: object

The shape of the archive, as the profile’s va_archiver: block sets it.

Defaults mirror VAArchiverConfig so a caller holding no config still gets the shipped archive rather than an arbitrary one. The block validates ranges and the cadence-divisibility rule at build time; validate() repeats the ones this module’s arithmetic depends on, because a store can also be seeded from a hand-written config that never went through a profile.

retention_days: int = 30#
hot_span_hours: int = 48#
hot_cadence_sec: int = 10#
tail_cadence_sec: int = 60#
classmethod from_config(config)[source]#

Read the knobs out of a rendered project config.

Parameters:

config (Mapping[str, object]) – The loaded config.yml as a mapping. Its va_archiver subtree supplies the knobs; any absent one keeps its default, so a config predating a knob still seeds.

Returns:

The parsed knobs.

Raises:

ValueError – If a knob is present but not a positive integer, or the set is internally inconsistent (see validate()).

Return type:

SeedKnobs

validate()[source]#

Refuse knobs this module’s grid arithmetic cannot honor.

Raises:

ValueError – If any knob is below one, the dense span reaches past retention, or the coarse cadence is not a whole multiple of the dense one — that last is what makes the coarse grid a subset of the dense one rather than a second grid interleaved with it.

property retention_s: int#

Retention span in seconds.

property hot_span_s: int#

Dense-tier span in seconds.

__init__(retention_days=30, hot_span_hours=48, hot_cadence_sec=10, tail_cadence_sec=60)#
class osprey_connectors.simulation.archive.SeedReport(documents=0, channels=0, start=None, end=None, elapsed_s=0.0, chunks=0)[source]#

Bases: object

What one seeding run wrote.

documents: int = 0#
channels: int = 0#
start: datetime | None = None#
end: datetime | None = None#
elapsed_s: float = 0.0#
chunks: int = 0#
describe()[source]#

A one-line summary for a deploy-time progress report.

Return type:

str

__init__(documents=0, channels=0, start=None, end=None, elapsed_s=0.0, chunks=0)#
class osprey_connectors.simulation.archive.SeedState(value)[source]#

Bases: Enum

What a store’s manifest says about the seed it holds.

ABSENT = 'absent'#

the store has never been seeded (or was wiped).

Type:

No manifest document

MATCH = 'match'#

The store was built with the knobs now in force. Nothing to do.

MISMATCH = 'mismatch'#

The store was built with different knobs, so its coverage no longer describes what the profile asks for. The store has to be rebuilt.

osprey_connectors.simulation.archive.build(view, active_set, *, anchor_s=None)[source]#

Build the archive composite of a simulator view at one active set’s start state.

The view’s composite is built once at the set’s start state and read once, one solve per physics model; no session write and no writes journal is read. A set whose scenarios write one target twice is archived without its scenarios, as the composite serves it.

Parameters:
  • view (SimulatorView | Path | str) – The simulator view, <render>/data/simulator, opened or as its directory, which is opened with SimulatorView.open().

  • active_set (Sequence[str]) – The active scenario names; nominal is always active.

  • anchor_s (float | None) – The epoch seconds the set was applied at, from which an at_offset event is placed; None is the time of the build.

Returns:

The archive composite.

Raises:
  • RuntimeError – A physics model fails to build or read at the start state; the message names it and its engine’s error. A model without a deck is unbuilt by design (no deck) and does not raise.

  • ValueError – A pulse seed names a channel the view does not hold.

  • NoSimulatorView – The directory holds no simulator view.

  • ViewSchemaError – A view file is not the schema this OSPREY reads.

Return type:

ArchiveComposite

osprey_connectors.simulation.archive.compare_fingerprint(collection, fingerprint)[source]#

Whether the store in front of us was built with the knobs now in force.

Parameters:
  • collection (Collection) – The sample collection.

  • fingerprint (Mapping[str, object]) – What seed_fingerprint() says the knobs are now.

Returns:

The comparison. MISMATCH carries every field that moved, including ones the stored manifest lacks entirely (reported as None), so a store seeded by an older version reseeds with a readable reason rather than silently.

Return type:

FingerprintComparison

osprey_connectors.simulation.archive.oldest_sample(collection)[source]#

The instant of the oldest stored sample, or None for an empty store.

This is what honest archiver metadata reports as the start of coverage. The filter on date skips the manifest, which has none — and skipping it is the reason the manifest was given no date in the first place.

Return type:

datetime | None

osprey_connectors.simulation.archive.scenario_events(scenarios, names)[source]#

The archiver events a scenario set writes, by channel.

Parameters:
  • scenarios (Mapping[str, Mapping[str, Any]]) – The simulator view’s scenarios, by name.

  • names (Sequence[str]) – The scenario names of the set, in set order; a name scenarios does not list contributes nothing.

Returns:

Each channel’s events in set order; a channel an archiver entry names with no events maps to an empty list.

Return type:

dict[str, list[dict[str, Any]]]

osprey_connectors.simulation.archive.seed_base(collection, archive, knobs, *, t0, compression='zstd', workers=_DEFAULT_WORKERS, chunk_size=_DEFAULT_CHUNK_SIZE, progress=None, waveforms=None)[source]#

Build the store: indexes, the whole base series, then the manifest.

The order is the contract. Indexes come first so the documents land into an indexed collection instead of being indexed afterwards; the manifest comes last, so a run that dies halfway leaves a store with no manifest — which the next deploy reads as ABSENT and rebuilds. A manifest written first would make a half-seeded store indistinguishable from a complete one.

Synthesis runs on the calling thread and inserts overlap it on a small pool. That split is deliberate: the composite is not contractually thread-safe, while the round trip to the store is the part worth overlapping. Submission blocks once the pool is saturated, so memory stays bounded at a few chunks rather than the whole window.

A waveform channel’s traces go to the waveform_collection() beside collection, one document per channel per coarse-cadence instant over the whole retention window (waveform_document()), written in the same chunk loop and so also before the manifest.

Parameters:
  • collection (Collection) – The sample collection. Existing samples are not removed — a caller reseeding is expected to drop first, and one that is extending a store deliberately is not second-guessed here.

  • archive (ArchiveComposite) – The archive composite of the active set; every one of its channels is seeded.

  • knobs (SeedKnobs) – The archive’s shape.

  • t0 (datetime) – The seed anchor; the window ends here.

  • compression (str) – The collection’s block compressor, recorded in the manifest because changing it changes the store’s size on disk.

  • workers (int) – Concurrent insert workers.

  • chunk_size (int) – Timestamps synthesized and inserted per batch.

  • progress (Callable[[SeedReport], None] | None) – Called after each chunk with the running report, for a deploy-time progress line.

  • waveforms (Collection | None) – The waveform_collection() beside collection; None opens it from collection’s database. Only a view with waveform channels needs it.

Returns:

The completed report; documents counts the snapshot documents.

Raises:

ValueError – If chunk_size or workers is below one, or the knobs are inconsistent.

Return type:

SeedReport

osprey_connectors.simulation.archive.seed_fingerprint(knobs, channel_addresses, *, compression)[source]#

The knobs a store’s coverage depends on, as a comparable dict.

Everything here changes what the store contains: the window’s depth and density, which channels are in it, how it is compressed on disk, the document schema itself, the pulse shape every stored trace is drawn from (SHAPE_VERSION), and the top-off sawtooth every stored decaying current is drawn from (SHAPE_VERSION). Nothing here is an instant or a count — those move on every deploy and would make the comparison a coin flip.

Parameters:
  • knobs (SeedKnobs) – The archive’s shape.

  • channel_addresses (Iterable[str]) – The seeded channel set. Order does not matter; the hash is taken over the sorted, deduplicated names.

  • compression (str) – The collection’s block compressor.

Returns:

The fingerprint, JSON-serializable and safe to store verbatim.

Return type:

dict[str, int | str]

osprey_connectors.simulation.archive.tier_expiry(knobs, epoch_s)[source]#

When each of these samples expires, by the tier its timestamp belongs to.

A timestamp on the coarse cadence belongs to the coarse tier and lives out the retention span; anything else is a dense-tier sample and lives until it ages out of the dense span. Membership is read off the timestamp rather than tracked alongside it, which is what lets a later writer — a scenario rewrite restoring a window it once protected — re-stamp a document correctly without knowing how it was originally produced.

Return type:

ndarray

osprey_connectors.simulation.archive.waveform_collection(collection)[source]#

The name of the collection holding collection’s archived waveforms.

A trace is hundreds of samples, so it is stored as its own document beside the per-timestamp snapshot documents rather than inside them. Every party to the store — preparation, the reseed drop, the seeder, the live recorder and the reader — derives the sibling’s name here, and nowhere else spells it, so the writers and the reader cannot drift apart.

Return type:

str

osprey_connectors.simulation.archive.waveform_document(channel, date, values, *, expire_at)[source]#

One archived trace: one document per (channel, instant).

The keys mirror a scalar snapshot document, so the same field naming and the same TTL index serve both: date is the sample instant, the channel’s field_name() holds the trace, and expireAt is the document’s own deadline.

The trace is stored as plain doubles: a list[float] with one entry per element of the channel’s shape, which BSON keeps as an array of doubles and every reader gets back unchanged.

Raises:

ValueError – when values is not a non-empty one-dimensional array.

Return type:

dict[str, object]

Pure time-series synthesis primitives for the simulated archive and texture.

These functions turn a baseline series plus a scenario’s archiver events (step/ramp/spike/burst/loss, positioned by window fraction, wall-clock offset, or daily time-of-day) into a concrete value series, and supply the keyed draws and the band-limited texture the texture engine layers on a served value. They hold no state: the caller supplies the channel values and events and these functions do the math (see tests/simulation/test_series_primitives.py).

osprey_connectors.simulation.series.anchored_instant(event, anchor, tz=None)[source]#

Epoch seconds of an event placed relative to the activation anchor.

at_offset is seconds from the anchor. at_when is the logbook’s own {days_ago, time}: the calendar day days_ago days before the anchor’s date, at time, both read in tz (UTC when omitted) – the same rule a scenario’s logbook entries resolve by, so an event and the entry narrating it name one instant.

Parameters:
  • event (Mapping[str, Any]) – An event carrying at_offset or at_when.

  • anchor (float) – The activation anchor T0, in epoch seconds.

  • tz (ZoneInfo | None) – The facility timezone calendar days are counted in.

Returns:

The event’s instant in epoch seconds.

Return type:

float

osprey_connectors.simulation.series.BURST_WINDOW_TAUS = 10.0#

How many of a burst’s slowest time constants count as inside its window: exp(-10) leaves under 0.005% of the burst outside it.

osprey_connectors.simulation.series.apply_events(series, events, n, t_abs, anchor, tz=None, topoff=None)[source]#

Apply step/ramp/spike/burst/loss events in order (window-fraction or wall-clock).

A step with an end (see step_end()) holds to over [start, end) and leaves later samples on the baseline; without one it holds to the end. A burst (_burst_profile()) and a loss (_loss_deficit()) start at their instant and never move a sample before it; topoff is the channel’s topoff seed record, which alone refills a loss.

Return type:

ndarray

osprey_connectors.simulation.series.loss_refill_bound(event, topoff)[source]#

Seconds after its instant by which a loss is surely refilled; None if never.

One top-off period to the first refill, wherever in the period the loss falls, plus the shots the amount takes.

Return type:

float | None

osprey_connectors.simulation.series.channel_key_bytes(channel)[source]#

Per-channel key for the counter-based draw primitives.

The key is the SHA-256 digest of the UTF-8 channel name. The builtin hash() is deliberately not used: it is salted per process, so draws keyed on it would differ between runs of the same scenario.

Callers derive independent streams for the same channel by appending a subkey (e.g. channel_key_bytes(channel) + b":noise_abs").

Parameters:

channel (str) – Channel name.

Returns:

A 32-byte digest suitable as the channel_key argument of keyed_normals().

Return type:

bytes

osprey_connectors.simulation.series.clamp(value, min_value, max_value)[source]#

Clamp a scalar into [min_value, max_value] (either bound optional).

The result is a float whichever side is hit, because clamp applies to float channels only.

Return type:

float

osprey_connectors.simulation.series.daily_occurrences(at_time, t_abs, tz=None)[source]#

Epoch-second positions of a daily time-of-day within [t_abs[0], t_abs[-1]].

Walks calendar dates from the window start to its end (in timezone tz) and keeps every occurrence of at_time that falls inside the window. Placing the time-of-day in an explicit zone — rather than the deploy host’s local zone — makes the result independent of the box $TZ. tz defaults to UTC; callers resolve and pass the facility zone, so this module stays free of config. Assumes ascending timestamps (the same contract apply_events relies on via np.searchsorted).

Return type:

list[float]

osprey_connectors.simulation.series.driver_key_bytes(driver)[source]#

Key for a scenario’s shared latent driver, addressed by the driver’s name.

A driver is the common cause behind several channels, so its draws must not depend on which channel asks for them: every channel coupled to the driver evaluates wander() under this one key and sees the identical value at the same instant. The driver: namespace keeps a driver that happens to share a channel’s name from replaying that channel’s own texture stream.

Parameters:

driver (str) – Driver name, as declared in a scenario’s drivers block.

Returns:

A 32-byte digest usable wherever a channel_key is expected.

Return type:

bytes

osprey_connectors.simulation.series.epoch_seconds_array(timestamps)[source]#

Convert timestamps to epoch seconds, or None when not convertible.

Return type:

ndarray | None

osprey_connectors.simulation.series.event_positions(event, t_frac, t_abs, anchor, tz=None)[source]#

Coordinate axis and event position(s) for one event.

Fraction-positioned (at) and anchored (at_offset, at_when) events yield one position, on the normalized window axis and the epoch-seconds axis respectively. Daily at_time events yield one epoch-seconds position per calendar date whose time-of-day occurrence falls inside the window, placed in the facility timezone (tz). Returns an empty list when an anchored or time-of-day event cannot be placed because the timestamps were not convertible to epoch seconds.

Return type:

list[tuple[ndarray, float]]

osprey_connectors.simulation.series.keyed_normals(channel_key, counters_ms)[source]#

Standard normal draws addressed by (channel key, counter).

Each sample’s draw is a pure function of its own counter, so two windows that share a timestamp get the same value, in any order, in any batch size, from any process. This is the pinned construction for all synthesis noise:

  1. a uint64 avalanche mix of the counter against two key-derived lane words (exactly two words per sample, fixed consumption by construction);

  2. an open-interval mapping of the log argument, u1 = ((w >> 11) | 1) * 2**-53, so u1 > 0 always and log(u1) can never be -inf — a frozen calendar timestamp that produced -inf would fail permanently rather than transiently;

  3. the Box-Muller cosine branch.

The ziggurat rejection sampler behind numpy’s batch normal draws consumes a variable number of words per sample, so a batch drawn from a window-start counter does not equal the corresponding per-sample draws — it is forbidden on this path, and tests/simulation/test_series_primitives.py pins the equivalence against a per-sample reference implementation.

Parameters:
  • channel_key (bytes) – Channel key, typically channel_key_bytes() output optionally suffixed with a subkey to get an independent stream.

  • counters_ms (ndarray) – Per-sample counters, conventionally epoch milliseconds. Floats are rounded to the nearest integer; any shape is accepted.

Returns:

A float64 array of standard normal draws with the shape of counters_ms.

Return type:

ndarray

osprey_connectors.simulation.series.step_end(event, anchor, tz=None)[source]#

Where a bounded step ends, on the same axis as its start; None when unbounded.

until is a window fraction (paired with at), until_offset is seconds from the anchor (paired with at_offset) and until_when is a {days_ago, time} placed exactly as at_when is (paired with it).

Parameters:
  • event (Mapping[str, Any]) – A step event.

  • anchor (float) – The activation anchor T0, in epoch seconds.

  • tz (ZoneInfo | None) – The facility timezone until_when calendar days are counted in.

Returns:

The end position, or None when the step states no end.

Return type:

float | None

osprey_connectors.simulation.series.wander(channel_key, t_abs_s, amplitude, period_s)[source]#

Band-limited quasi-random baseline texture, evaluated on absolute time.

A seeded sum of _WANDER_COMPONENTS sinusoids whose periods are log-spaced downward from period_s. One declaration therefore covers two timescales: with period_s of many hours the slowest terms read as a distinct quasi-static offset inside any short query window, while the faster octaves supply visible motion — which is what lets a whole channel family share one set of declared parameters and still look individual.

The envelope is bounded structurally rather than by clipping: the weights are positive and sum to 1, so |wander| <= amplitude follows from the triangle inequality and the output stays linear in amplitude.

Being a pure function of absolute epoch seconds is what makes overlapping archiver windows agree exactly on their shared timestamps.

Parameters:
  • channel_key (bytes) – Channel key, as for keyed_normals().

  • t_abs_s (ndarray) – Absolute epoch seconds; any shape.

  • amplitude (float) – Envelope bound, in the channel’s declared units.

  • period_s (float) – Slowest period in seconds; must be positive.

Returns:

A float64 array of texture offsets with the shape of t_abs_s.

Raises:

ValueError – If period_s is not positive; the guard keeps a caller from turning a division by zero into silent NaN in the series.

Return type:

ndarray

How far a simulated channel’s declared motion can carry its value.

A channel’s seed may declare two kinds of motion: noise, a Gaussian draw, and drift, a slow wander whose amplitude bounds it (|wander| <= amplitude by construction). A noise record states exactly one term: {absolute: <sigma>}, a sigma in the channel’s unit, or {relative: <fraction>}, a sigma as a fraction of the reading. An active scenario may couple the channel to shared drivers, each adding gain * (1 + gain_wander) * driver with |driver| <= drive.amplitude, and may replace its noise.

A served value is therefore the held value plus at most its envelope:

|drift.amplitude|
  + sum |gain| x (1 + |gain_wander.amplitude|) x |drive.amplitude|
  + _MOTION_SIGMAS x noise sigma
  + tooth depth

where a relative noise sigma is taken at the seed’s own nominal, or at the level a topoff seed holds, and the tooth depth is how far a topoff seed’s sawtooth carries the reading from that level. A channel that declares no motion, or that an active scenario stills, has an envelope of 0.0.

The module imports only the standard library and the standard-library-only topoff, so the build, the simulator view’s reader and the texture model share one rule.

osprey_connectors.simulation.envelope.active_envelopes(seeds, scenarios, active)[source]#

Every seeded, coupled or noise-replaced channel’s envelope under active.

The active scenarios’ noise and couple blocks merge in order, a later scenario’s noise record replacing an earlier one’s, and each coupling takes its driver’s drive from the merged drivers; a coupling to an undeclared driver adds nothing, as it serves nothing. A reading any active scenario’s still list names has an envelope of 0.0.

Parameters:
  • seeds (Mapping[str, Mapping[str, Any]]) – Seeds by address.

  • scenarios (Mapping[str, Mapping[str, Any]]) – Scenario records by name.

  • active (Sequence[str]) – The active scenario names, in order; a name scenarios lacks adds nothing.

Returns:

The envelope by address, sorted.

Return type:

dict[str, float]

osprey_connectors.simulation.envelope.declares_motion(seed)[source]#

Whether a seed states motion: a non-zero noise term, drift, or topoff.

Return type:

bool

osprey_connectors.simulation.envelope.motion_envelope(seed, *, noise=None, couplings=(), still=False)[source]#

The band a channel’s motion keeps its value within around the held value.

Parameters:
  • seed (Mapping[str, Any] | None) – The channel’s seed, or None.

  • noise (Mapping[str, Any] | None) – A scenario’s noise record standing in for the seed’s, or None for the seed’s own.

  • couplings (Iterable[Mapping[str, Any]]) – Resolved couplings, each {driver, gain, gain_wander?, drive} with drive the driver’s {kind, amplitude, period_s}.

  • still (bool) – The active scenarios still the channel.

Returns:

|drift.amplitude| + sum |gain| x (1 + |gain_wander.amplitude|) x |drive.amplitude| + _MOTION_SIGMAS x noise sigma + tooth depth; 0.0 for an absent seed with no couplings, and for a stilled channel.

Return type:

float

The faults of a simulated channel itself, applied by the composite’s channel layer.

A scenario’s channel_faults maps an address to one word of CHANNEL_FAULTS. A fault acts on the channel whether a physics model wires it or the texture holds it, while its scenario is active:

  • stuck faults a setpoint. A write is accepted and held, and forwarded to nothing; the setpoint reads the value last written, its start value before any write. Its readback shows the machine where it was: a wired readback the model’s reading, a texture readback its held value, with no echo.

  • frozen faults a reading (a readback or a none channel). It reads the value it served when the fault became active, with no motion and no model update.

  • disconnected faults any channel. A float reading reads not-a-number, a reading of any other type the value it served when the fault became active, and the reading reports the udf condition. A disconnected setpoint holds its writes as stuck does and reads its demand; its readback is the disconnected reading. A setpoint with no readback of its own reads its demand and reports the condition itself.

No fault withholds a reply: a read always answers.

The module imports only the standard library, so the build’s validator and the composite share one table.

osprey_connectors.simulation.channel_faults.CHANNEL_FAULTS: Mapping[str, ChannelFault] = mappingproxy({'stuck': ChannelFault(roles=frozenset({'setpoint'}), write=True, read=None, severity=None), 'frozen': ChannelFault(roles=frozenset({'readback', 'none'}), write=False, read=<function _snapshot>, severity=None), 'disconnected': ChannelFault(roles=frozenset({'readback', 'none', 'setpoint'}), write=True, read=<function _not_a_number>, severity='udf')})#

Every channel fault, by its word.

osprey_connectors.simulation.channel_faults.STUCK = 'stuck'#

Holds a setpoint’s writes.

class osprey_connectors.simulation.channel_faults.ChannelFault(roles, write, read, severity)[source]#

Bases: object

One channel fault’s semantics.

Variables:
  • roles (frozenset[str]) – The facility channel roles the fault may name.

  • write (bool) – Whether a write to a faulted setpoint is held and forwarded to nothing.

  • read (collections.abc.Callable[[str, object], object] | None) – What a faulted reading answers, given its value_type and the value it served when the fault became active; None when the fault changes no reading.

  • severity (str | None) – The condition a faulted reading reports, or None.

roles: frozenset[str]#
write: bool#
read: Callable[[str, object], object] | None#
severity: str | None#
__init__(roles, write, read, severity)#

The pulsed-septum current trace: one pure function of address, time and drive.

A pulsed supply fires about once a second; each firing is captured as a fixed window of 500 samples. The pulse has a fast rise, a flat top that droops slightly, and a slower exponential fall. The flat top rings: a few damped sinusoids whose amplitudes and phases are drawn fresh for every shot, together with a small per-shot jitter of the rise edge. On top of that sit a slow amplitude drift and a slow timing drift (periods of minutes) and a small sample noise, all keyed by the channel address and the epoch millisecond, the same way the texture engine keys its motion. That is what lets the live server and the seeded archive produce the identical trace for the same instant.

The trace is linear in the driver level (the supply setpoint): every term, noise included, is a multiple of it, so the peak ratio of two traces at the same instant equals their driver ratio. A disabled supply reads flat zero.

The shape constants live here, not in seeds. SHAPE_VERSION is a digest of them; the archive seed fingerprint consumes it, so changing the shape re-seeds the stored history.

osprey_connectors.simulation.pulse.SHAPE_VERSION = '6d3f30d46f36eb04'#

Digest of the shape constants; the archive seed fingerprint consumes it.

osprey_connectors.simulation.pulse.trace(address, t_s, driver, enable)[source]#

The captured pulse of address at epoch second t_s.

Pure: the result depends only on the arguments. Time is taken at whole epoch milliseconds, matching how the texture engine keys its motion.

Parameters:
  • address (str) – Channel address; keys the drift, ringing and noise streams.

  • t_s (float) – Absolute epoch seconds.

  • driver (float) – Driver level (the supply setpoint); the trace scales linearly with it.

  • enable (bool) – Supply on-state; False gives a flat zero trace.

Returns:

A float64 array of shape (_TRACE_POINTS,).

Return type:

ndarray

The top-off sawtooth: a stored current that decays with a lifetime and refills on a period.

A topoff seed {ceiling, lifetime_h, period_s} describes a float channel that starts each period at ceiling and decays exponentially with the lifetime tau = lifetime_h * 3600 seconds until the next refill. The unit shape is a pure function of epoch seconds:

s(t) = exp(-((t mod period_s) / tau))

so every channel with the same seed refills at the same instants, and a live read and an archived sample at the same instant agree. Its mean over one period is:

m = (tau / period_s) * (1 - exp(-period_s / tau))

The channel HOLDS the level ceiling * m – the value a limits band and an archive’s start state see – and the sawtooth is MOTION around it: the tooth level * (s(t) / m - 1), added on the level it rides, so at the held level the reading is ceiling * s(t), and a level moved to zero carries no tooth at all.

A topoff_lifetime seed {of} names a channel whose seed is topoff and holds that seed’s lifetime_h as a constant: the lifetime readback that produces the decay.

The module imports only the standard library, so the envelope rule and the facility build share it with the texture model. SHAPE_VERSION is a digest of the shape constants; the archive seed fingerprint consumes it, so a change to the shape re-seeds the stored history.

osprey_connectors.simulation.topoff.SHAPE_VERSION = '5e78a68264884cad'#

Digest of the shape constants; the archive seed fingerprint consumes it.

osprey_connectors.simulation.topoff.held_value(seed, lookup=None)[source]#

The value a topoff or topoff_lifetime seed holds.

Parameters:
  • seed (Mapping[str, Any] | None) – A channel’s seed, or None.

  • lookup (Callable[[str], Mapping[str, Any] | None] | None) – Returns the seed of an address, or None; resolves the channel a topoff_lifetime names. Without one a topoff_lifetime holds nothing.

Returns:

ceiling * m for a topoff seed; the referenced seed’s lifetime_h for a topoff_lifetime seed whose channel carries topoff; None for any other seed.

Return type:

float | None

osprey_connectors.simulation.topoff.period_mean(record)[source]#

The mean m of the unit sawtooth over one period.

Return type:

float

osprey_connectors.simulation.topoff.tau_period(record)[source]#

(tau, period_s) of a topoff record, both in seconds.

Return type:

tuple[float, float]

osprey_connectors.simulation.topoff.tooth_depth(record)[source]#

How far the sawtooth carries a reading from its held level ceiling * m.

Returns:

the larger of the overshoot at a refill and the undershoot just before one.

Return type:

|ceiling| * max(1 - m, m - exp(-period_s / tau))

osprey_connectors.simulation.topoff.topoff_record(seed)[source]#

The topoff record of a seed, or None when it has none.

Return type:

Mapping[str, Any] | None

The texture model: the simulator’s value for every channel no served model wires.

TextureModel is a LUMEModel built from two documents of the simulator view, variables.json and seeds.json. It owns the VALUE of a channel whose owner is texture or names a model the view marks unserved, and the MOTION (keyed noise and drift) and clamp of every channel the view declares, so a served model’s readbacks can carry the same motion.

A texture channel reads clamp(held + drift(t) + couplings(t) + noise(t)). held starts at the channel’s nominal: the seed’s nominal, else the unserved model’s wiring default, else the zero of the channel’s value_type. A paired readback starts at its setpoint’s nominal. A linear channel holds the weighted sum of its inputs’ held values, a linear input counting as its own sum. Noise and drift are pure functions of the address and the epoch millisecond, so a live read and an archived sample at the same instant agree. Writing a setpoint holds the value and echoes it into the readback its pair names.

A noise record states one term: {absolute: sigma} adds sigma times a keyed normal draw, and {relative: f} adds f times held + drift + couplings times one. The active scenarios add motion through TextureModel.set_motion(): a coupled channel adds gain * (1 + gain_wander(t)) * driver(t) per coupling, where every channel coupled to one driver sees the same driver(t), and a scenario’s noise record stands in for the seed’s while it is held, drawing from its own stream. A reading the active scenarios still serves its held value: no drift, couplings or noise.

A waveform channel whose seed states pulse: {driver, enable} reads trace() at the read time, scaled by the driver’s held value and switched by the enable channel’s held label, so it moves on every read. Every other waveform channel reads its held array.

A float channel whose seed states topoff: {ceiling, lifetime_h, period_s} holds the level ceiling * m of topoff and carries the tooth level * (s(t) / m - 1) as motion on that level, so it reads ceiling * s(t) at the held level and a stilled one serves the level. A channel whose seed states topoff_lifetime: {of} holds the named topoff seed’s lifetime_h.

A channel whose seed states gate: {inputs, gated} holds its gated value while any input holds its blocking label, and its value by the rules above otherwise. gated is typed by the channel: a float holds its value times the factor gated, so a gated reading keeps a small residual and its motion; a bool or enum holds the label gated; an int holds the integer gated. An input is read as its own held value, gate included, and an input the model does not hold never blocks. The gate is part of the held value, so a read, TextureModel.held() and every reader built on it – the archive seed, a subscription comparing held values – see it alike.

osprey_connectors.simulation.texture.TEXTURE_OWNER = 'texture'#

The owner the simulator view writes for a channel no model wires.

class osprey_connectors.simulation.texture.TextureModel(variables, seeds, *, clock=time.time)[source]#

Bases: LUMEModel

Serve the texture-owned channels of a simulator view.

Parameters:
  • variables (Mapping[str, Any]) – The view’s variables.json document (models[] and channels[]).

  • seeds (Mapping[str, Any]) – The view’s seeds.json document (seeds by address).

  • clock (Callable[[], float]) – Returns the current instant in epoch seconds.

__init__(variables, seeds, *, clock=time.time)[source]#
property supported_variables: dict[str, Variable]#

The texture-owned channels, by address.

reset()[source]#

Return every texture-owned channel to its nominal, then apply the active writes.

set_active(writes)[source]#

Make the active scenarios’ writes the start state, and reset to it.

An active write is held whether or not its channel is settable, and a setpoint’s write echoes into its readback as a set does.

Parameters:

writes (Mapping[str, object]) – Values by texture-owned address; empty for none.

Raises:

ValueError – A value is refused for its channel’s value_type; the model keeps its earlier start state and held values.

held(names)[source]#

Each channel’s held value, without motion or clamp.

A linear channel holds the weighted sum of its inputs’ held values; an input the model does not hold counts as zero. A gate channel holds its gated value while any input holds its blocking label.

Parameters:

names (Sequence[str]) – Texture-owned addresses.

Returns:

The held value by address, in its stored representation.

Return type:

dict[str, float | int | str | list[float]]

reach()[source]#

What a write to each settable channel can change, by address.

The channel itself, the readback it echoes into, and every channel downstream of either: a linear channel summing it, a gate channel it blocks, a pulse waveform it drives or enables.

Return type:

dict[str, frozenset[str]]

set_motion(couple, noise, *, still=frozenset())[source]#

Hold the active scenarios’ motion until the next call.

Parameters:
  • couple (Mapping[str, Sequence[Mapping[str, Any]]]) – Couplings by address, each {driver, gain, gain_wander?, drive}: drive is the driver’s {kind, amplitude, period_s} and gain_wander an optional {amplitude, period_s}. Empty for no coupling.

  • noise (Mapping[str, Mapping[str, Any]]) – Noise records by address, each {absolute: <sigma>} or {relative: <fraction>}, standing in for the seed’s. Empty for the seeds’ noise.

  • still (frozenset[str]) – Addresses served without motion.

motion(address, t_s, base=0.0)[source]#

The motion of a channel at absolute epoch seconds.

Drift, then the held couplings, then a topoff seed’s tooth base * (s(t) / m - 1), then noise: the held scenario’s noise record, else the seed’s. An absolute term is its sigma times a keyed normal draw; a relative term scales base plus drift, couplings and tooth. Every term is a pure function of the address and the epoch time.

Parameters:
  • address (str) – Any address the view declares.

  • t_s (object) – Epoch seconds; any shape.

  • base (object) – The value the motion is added to, which a relative noise term scales; a scalar or an array shaped like t_s.

Returns:

A float64 array with the shape of t_s; zero for a channel without motion, stilled, or not of type float.

Return type:

ndarray

has_motion(address)[source]#

Whether motion() can be non-zero for address.

True for a pulse waveform channel, whose trace changes with time. Otherwise true exactly for a float channel the held motion does not still, with seed drift, a topoff seed, a held coupling, or a non-zero noise term under the held motion.

Return type:

bool

clamp(address, value)[source]#

Clamp a float into the seed’s clamp band; a null side is unbounded.

Return type:

float

osprey_connectors.simulation.texture.channel_value_type(channel)[source]#

A channel record’s value_type, float when it states none.

Return type:

str

osprey_connectors.simulation.texture.channel_variable(channel, nominal)[source]#

The LUME variable of one channel of the view’s variables.json.

A setpoint the view marks writable is settable; every other channel is read-only. value_type picks the class: an EnumVariable over the channel’s labels for bool and enum, a StrVariable for string, an NDVariable of the channel’s shape for waveform, an IntVariable for int and a ScalarVariable otherwise, each bounded by the view’s value_range.

Parameters:
  • channel (Mapping[str, Any]) – The channel’s record in variables.json.

  • nominal (Any) – Its start value, in its stored representation.

Returns:

The variable, named by the channel’s address.

Return type:

Variable

osprey_connectors.simulation.texture.is_float_channel(channel)[source]#

Whether a channel record holds a float.

Return type:

bool

The composite: one LUME model serving a simulator view’s every channel.

Composite reads the simulator view a render writes under data/simulator/ and serves its channels through two kinds of child:

  • one physics child per served model whose engine is not texture, built by the engine plug-in the osprey.simulation.engines entry-point group names, through build(model, wiring, deck, settings, active=...);

  • the texture, a TextureModel holding every other channel and the motion of all of them.

supported_variables is the channel addresses of addresses.json and its status addresses, <code>:SIM:<model>:STATUS, one per physics child. Each child’s own variables that no channel names (faults, optics) are reached as <model>/<name> through Composite.model_get() and Composite.model_set() only.

IOC health. supported_variables also holds the view’s ioc_health addresses, <code>:SIM:<model>:<signal>, read-only and served for every model the view lists whether or not it is built: HEARTBEAT counts the whole seconds since the composite started, UPTIME is those seconds, both on its clock, and ENGINEER is a fixed demo string. No read of one reaches a child.

Reads. A physics readback of type float reads truth + motion(address, t), passed through the child’s readout when the engine exports one, then clamped; the readout always sees both readings of a monitor, so a read of one plane reads its partner too. A texture channel reads as the texture serves it. A reading the active scenarios still has no motion: a physics readback reads its truth through readout and clamp, a texture channel its held value. Composite.get() returns each value as its variable declares it, a waveform as an array of the variable’s dtype and shape. Composite.held() reads every channel without motion or readout.

Writes. Composite.set() coerces each value to its channel’s value_type, then sets the physics children in their order (see Inputs) and the texture last. When any child refuses, every earlier child gets its previous inputs back and the refusal is raised as a WriteRefusedError (a ValueError) carrying the child’s text and, when one channel was refused, its address. A setpoint the active scenarios hold (stuck or disconnected in channel_faults) accepts a write, reads the value written, and forwards none of it; its readback shows the model where it was.

Channel faults. A frozen reading reads the value it served when its scenario became active. A disconnected reading reads not-a-number when it is a float, else the value it served when its scenario became active; a disconnected setpoint’s readback is that reading, and a setpoint that is its own readback reads its demand. Composite.output_severity() names every disconnected reading with the udf condition. A channel fault acts on live reads, writes and severity only; Composite.readings() serves history without it.

A model with no deck. A model whose record names no deck and wires no channel is not built: there is nothing for an engine to serve, and the facility describes such a machine so that its channels are the texture’s. Its status is no deck (STATUS_NO_DECK), its log records an unbuilt event, and it is no failure.

A failed child. A child whose engine raises while it is built or read is failed, with the engine’s error text as its status (ok otherwise), capped at _STATUS_MAX_BYTES UTF-8 bytes. It holds the inputs written to it and never raises: its setpoints read those inputs, its float outputs NaN, any other output its last good value or its type’s zero, and Composite.output_severity() names each of its channels. A refused write leaves a child as it was. A failed child is rebuilt on Composite.reset() and on a change of the active scenarios.

Scenarios. The active set is the active_scenarios file of the state directory, re-read when its modification time changes. A change rebuilds every physics child with the active scenarios’ writes and fault seeds as its start state, and hands the texture the active writes it owns and the active drivers, couplings and noise replacements; session writes are dropped. The readings any active scenario’s still list names, nominal included, are stilled. A set whose scenarios touch one target twice is served without its scenarios.

Evolution. A composite built with evolve=True drives the children whose engine states the time contract (advance, next_deadline, emitted, client_write), each looked up on the engine the way readout is: it calls advance(model, t) at its clock’s reading right after it builds or rebuilds a child, right after Composite.reset(), and before every read and write; Composite.next_deadline() is the earliest of the children’s deadlines and Composite.emitted() the union of what they emitted, drained. Only a write through Composite.set() that reaches a child’s model is a client write, handed to client_write(model, values, t); Composite.restore(), the start state and the scenario writes are not, and neither is a write a stuck or disconnected setpoint holds. A rebuild discards what a child had pending. Built without it, the default, the composite calls none of the four names.

Inputs. A model may declare inputs, each an {address, engine} record naming a channel another model produces. The children are ordered so every producer precedes its consumers, ties in name order, so a view without inputs keeps name order and makes no delivery call. A consumer whose engine exports take_inputs(model, inputs, t_s, *, baseline) gets one (record, value) pair per declared input, the value its producer’s plain read: when evolving, immediately before each advance of it, so it reads what its producers reached in the same pass; when not evolving, right after it is built or reset and after every Composite.set() or Composite.restore(). A delivery is a baseline when it is the first after the consumer or any of its producers was built, rebuilt or reset, and always when the composite does not evolve. A failed producer’s inputs are left out; with none left no call is made. A raise in take_inputs fails the consumer as any time-contract call does.

The model log. Each physics child appends JSON lines {instance, pid, ...} to var/simulator/<model>.log under the repo root of the loaded config, one os.write per record of under _LOG_RECORD_MAX_BYTES bytes. Without a loaded config the records go to the process logger only.

class osprey_connectors.simulation.composite.Composite(view, *, state_dir=None, instance='inprocess', clock=time.time, model_log=True, log_dir=None, evolve=False)[source]#

Bases: LUMEModel

Serve one simulator view through its physics children and the texture.

Parameters:
  • view (SimulatorView | Path | str) – The simulator view, <render>/data/simulator, opened or as its directory, which is opened with SimulatorView.open().

  • state_dir (Path | str | None) – The directory holding the active_scenarios file; None serves nominal alone.

  • instance (str) – The serving instance the model log names, one of _INSTANCES.

  • clock (Callable[[], float]) – Returns the current instant in epoch seconds.

  • model_log (bool) – False sends the model log records to the process logger only, for a composite no instance serves.

  • log_dir (Path | str | None) – The directory the model logs are appended in; None takes log_dir() when model_log is set.

  • evolve (bool) – Drive the children’s time contract with clock; False never calls it, so every channel holds its start state until written.

Raises:
  • ValueError – instance is not one of _INSTANCES.

  • NoSimulatorView – The directory holds no simulator view.

  • ViewSchemaError – A view file is not the schema this OSPREY reads.

__init__(view, *, state_dir=None, instance='inprocess', clock=time.time, model_log=True, log_dir=None, evolve=False)[source]#
advance()[source]#

Advance every time-driven child to the clock; nothing unless built to evolve.

next_deadline()[source]#

The earliest epoch second a time-driven child has a step due, else None.

None too when the composite does not evolve; a child whose engine raises is failed and has no deadline.

Return type:

float | None

emitted()[source]#

The addresses the time-driven children emitted since the last call, drained.

Empty when the composite does not evolve; a child whose engine raises is failed and emits nothing.

Return type:

frozenset[str]

property supported_variables: dict[str, Variable]#

Every channel, status and IOC health address of the view, by address.

property models: list[str]#

The served physics models, sorted by name.

property active: list[str]#

the active set, or nominal alone when its scenarios overlap.

Type:

The scenarios served

moving()[source]#

The served channels whose motion can be non-zero under the active scenarios.

The texture’s own channels, and the physics readbacks the texture moves on their level, each when no active scenario stills, freezes or disconnects it and its seed drift, a held coupling or a non-zero noise term moves it.

Return type:

frozenset[str]

texture_reach()[source]#

What a write to each settable texture channel can change, by address.

The channel, the readback it echoes into, and the texture channels derived from either. No physics model reads a texture channel, so the write changes nothing else.

Return type:

dict[str, frozenset[str]]

get(names)[source]#

Read channels, each as its variable declares it; a waveform as an array of its shape.

Parameters:

names (list[str] | str) – One address or a list of addresses.

Returns:

The value of a single address, else the values by address.

Raises:

ValueError – A name is not a channel or status address of the view.

Return type:

dict[str, Any] | Any

readout_group(address)[source]#

The channels a read of address reads with it, address among them.

A monitor plane of a physics child is read with its partner planes; any other channel alone.

Raises:

ValueError – address is not a channel of the view.

Return type:

tuple[str, …]

readings(levels, t_s)[source]#

Float channels as served at epoch seconds, from levels in place of held values.

A moving channel, a texture float or a physics float readback, reads its level plus its motion on that level, through its child’s readout when the engine exports one, then clamped; a physics setpoint reads its level. A failed child’s readbacks read NaN.

Parameters:
  • levels (Mapping[str, float | ndarray]) – Float channel levels by address, each a scalar or an array shaped like t_s; a monitor plane needs every channel of its readout_group().

  • t_s (object) – Epoch seconds, one-dimensional.

Returns:

One float64 array shaped like t_s per address of levels.

Raises:

ValueError – A name is not a float channel of the view, or a monitor plane’s partner has no level.

Return type:

dict[str, ndarray]

held(names)[source]#

Each channel’s held value: no motion, no readout, no clamp.

A texture channel returns the value the texture holds; a physics channel its child’s plain read; a setpoint the active scenarios hold the value last written to it; a faulted reading its unfaulted value; a status address its status; an IOC health address its value now.

Parameters:

names (Sequence[str]) – Channel, status or IOC health addresses.

Returns:

The value by address, in its stored representation.

Raises:

ValueError – A name is not a channel or status address of the view.

Return type:

dict[str, object]

output_severity(names)[source]#

The condition of each named channel whose child failed or whose fault reports one.

Parameters:

names (Sequence[str]) – Channel or status addresses.

Returns:

{name: {"condition": "udf"}} for each name a failed child owns, else {name: {"condition": <condition>}} for each name whose channel fault reports one; any other name is absent.

Return type:

dict[str, dict[str, str]]

status(model)[source]#

A served physics model’s status: ok or its engine’s capped error text.

Raises:

ValueError – model is not a served physics model; the message names the served ones.

Return type:

str

set(values_by_name)[source]#

Write channels: physics children first, producers before consumers, the texture last.

Parameters:

values_by_name (dict[str, Any]) – Values by channel address; a waveform as a flat or nested list.

Raises:
  • WriteRefusedError – (a ValueError) A name is not a channel of the view, a value is refused for its channel, or a child refuses the write; every earlier child has its previous inputs back. address names the channel when one channel was refused.

  • ReadOnlyError – A name is not a settable channel.

restore(values_by_name)[source]#

Put channels back as set() writes them, without a client write.

For a rollback or a replay: the children’s models take the values, and no engine is told a client wrote them.

Raises:
reset()[source]#

Return every child to its start state; a failed child is rebuilt.

Setpoints return to their active writes or defaults, the texture to its nominals and active writes; session writes are dropped, the ones a channel fault holds among them. A faulted reading keeps the value it served when its fault became active. An evolving composite advances each child to the clock right after, which anchors its time anew.

model_variables()[source]#

Each built physics model’s own variables, named <model>/<name>.

A model’s own variables are the ones it declares beyond the view’s channels. A failed model lists none.

Returns:

<model>/<name> -> (variable, start), models in name order and each model’s variables in its declaration order. start is what the model held for a writable variable when it was built at the active scenarios; a read-only variable’s is None.

Return type:

dict[str, tuple[Variable, object]]

model_get(names)[source]#

Read the children’s own variables, each named <model>/<name>.

Raises:

ValueError – A name names no served model, a channel, an unknown variable, or a variable of a failed model.

Return type:

dict[str, object]

model_set(values_by_name)[source]#

Write the children’s own variables, each named <model>/<name>.

Raises:

ValueError – A name names no served model, a channel, an unknown variable, or a variable of a failed model; or the child refuses the write.

log_event(event, **fields)[source]#

Append one event record to every physics model’s log.

A view with no physics model logs nothing here.

Parameters:
  • event (str) – The record’s event.

  • **fields (object) – Further fields of the record.

exception osprey_connectors.simulation.composite.WriteRefusedError(message, *, address=None)[source]#

Bases: ValueError

A write the composite refused; address is the one channel refused, else None.

__init__(message, *, address=None)[source]#
osprey_connectors.simulation.composite.log_dir()[source]#

The directory the model logs are appended in, or None without a loaded config.

Returns:

var/simulator under the repo root of the config this process loaded.

Return type:

Path | None

The logbook entries a scenario narrates, and the pictures they carry.

ScenarioLogEntry is the one entry shape the logbook seed reads. An entry’s pictures are shipped image files or PlotSpec records the seeder draws against the entry’s timestamp; parse_log_attachments() resolves and checks an entry’s attachments list, and parse_plot_spec() validates one decoded plot spec.

class osprey_connectors.simulation.logbook.PlotSeries(label, values)[source]#

Bases: object

One named line of a PlotSpec, one value per axis point.

label: str#
values: tuple[float, ...]#
__init__(label, values)#
class osprey_connectors.simulation.logbook.PlotSpec(filename, title, ylabel, hours_before, series, ylim=None)[source]#

Bases: object

A time-series picture drawn when its entry is seeded, not shipped as a file.

The time axis is relative: hours_before counts back from the instant the entry is written (0.0), so the drawn picture carries that entry’s real dates whatever anchor the narrative resolves against. Every series has one value per point of that shared axis.

Variables:
  • filename (str) – Name the drawn picture is stored under (a .png file name).

  • title (str) – Figure title.

  • ylabel (str) – Y-axis label.

  • hours_before (tuple[float, ...]) – Shared time axis, non-increasing, ending at 0.0.

  • series (tuple[osprey_connectors.simulation.logbook.PlotSeries, ...]) – The lines drawn, in legend order.

  • ylim (tuple[float, float] | None) – Fixed y-axis range (low, high), or None to fit the data.

filename: str#
title: str#
ylabel: str#
hours_before: tuple[float, ...]#
series: tuple[PlotSeries, ...]#
ylim: tuple[float, float] | None = None#
__init__(filename, title, ylabel, hours_before, series, ylim=None)#
class osprey_connectors.simulation.logbook.ScenarioLogEntry(entry_id, when, author, title, text, tags, categories, loto_tag, extra, attachments=())[source]#

Bases: object

A logbook entry owned by a scenario.

The one entry shape the ARIEL DB seed (via apply) reads, whether the entry came from a scenario bundle’s logbook.json or a facility scenario’s logbook block, so the telemetry overlay and its narrative ship together.

attachments are the pictures the entry carries, in the order its attachments list names them: a shipped picture as an absolute path inside the scenario directory (checked at load time to exist and to be an image), or a PlotSpec the seeder draws against the entry’s timestamp.

entry_id: str#
when: RelativeTimestamp#
author: str#
title: str#
text: str#
tags: tuple[str, ...]#
categories: tuple[str, ...]#
loto_tag: str | None#
extra: dict[str, object]#
attachments: tuple[Path | PlotSpec, ...] = ()#
__init__(entry_id, when, author, title, text, tags, categories, loto_tag, extra, attachments=())#
osprey_connectors.simulation.logbook.matches_signature(head, signature)[source]#

Whether head carries signature (an (offset, bytes) pair).

Return type:

bool

osprey_connectors.simulation.logbook.parse_log_attachments(prefix, raw, bundle)[source]#

Resolve a logbook entry’s attachments list to the pictures it carries.

Each item holds exactly one key. {"path": "<relative path>"} names a shipped picture: it must name an existing file with an image suffix that starts with that image format’s signature. {"plot": "<relative path>"} names a plot spec: a .json file holding a valid spec (see parse_plot_spec()). Either path is relative to the bundle directory and must stay inside it, and no two pictures of one entry may share a file name, so a misnamed, missing or malformed picture is a load error rather than a seed failure.

Return type:

tuple[Path | PlotSpec, …]

osprey_connectors.simulation.logbook.parse_plot_spec(raw, where='plot spec')[source]#

Validate a decoded plot spec and return it as a PlotSpec.

The schema is closed: filename (a .png file name, no directory), title, ylabel, hours_before (at least two finite numbers, non-negative, non-increasing, ending at 0), series (a non-empty list of {"label", "values"} with unique non-empty labels and one finite number per hours_before point) and optional ylim ([low, high] with low < high).

Parameters:
  • raw (object) – The decoded JSON value.

  • where (str) – How error messages name the spec.

Raises:

ValueError – If the spec breaks any of those rules.

Return type:

PlotSpec