Storage

See What is stored, and moving it for an overview.

Backends

Storage backends: the contract, in-memory, files, and Acquirium.

class flexorchestrator.backend.FileBackend(path)[source]

Bases: object

Studies, variables and runs kept in a folder (see the module docstring).

One process uses a folder at a time; within it, the backend is safe to share between threads.

Parameters:

path (str | PathLike[str]) – The folder. It’s created if it doesn’t exist; an existing folder must be empty or one this backend wrote.

path

The folder.

resolve_unit

Always None: there is no unit vocabulary, so the exporter’s QUDT keys stay unverified and aren’t declared.

Raises:

StorageError – If path holds something else, or a newer layout.

Parameters:

path (str | PathLike[str])

Example

>>> import tempfile
>>> backend = FileBackend(tempfile.mkdtemp())
>>> backend.define_study("s")
>>> FileBackend(backend.path).has_study("s")  # opened again
True
define_study(name)[source]

Create the study if it doesn’t exist.

Parameters:

name (str)

Return type:

None

has_study(name)[source]

Return whether the study exists.

Parameters:

name (str)

Return type:

bool

studies()[source]

Return the names of every study, sorted.

Return type:

list[str]

variable(study, label)[source]

Return the declaration of label, or None.

Parameters:
Return type:

Variable | None

declare(study, label, *, role, kind, unit=None, metadata=None)[source]

Declare a variable, or return it if declared the same way.

Raises:

StorageError – If label is declared differently, a JSON, table or file variable is given a unit, or the metadata isn’t JSON.

Parameters:
Return type:

Variable

start_run(study, metadata)[source]

Start a run and return its id.

Raises:

StorageError – If the study doesn’t exist or the metadata isn’t JSON.

Parameters:
Return type:

str

record(run_id, label, value)[source]

Record a value in a running run.

Raises:

StorageError – If the run isn’t running, label isn’t declared, or the value doesn’t fit the kind: a timeseries row without a value, a table that isn’t a polars DataFrame, a file that isn’t a FileValue, or a value that isn’t JSON (NaN included).

Parameters:
Return type:

None

finish_run(run_id)[source]

Mark a running run succeeded.

Parameters:

run_id (str)

Return type:

None

fail_run(run_id, error)[source]

Mark a running run failed.

Parameters:
Return type:

None

runs(study, *, status=None, metadata=None)[source]

Return the study’s runs, oldest first.

Parameters:
Return type:

list[Run]

variables(study)[source]

Return every variable declared in the study.

Parameters:

study (str)

Return type:

list[Variable]

delete_runs(study, run_ids)[source]

Delete finished runs and everything they recorded.

Parameters:
Return type:

None

delete_study(name)[source]

Delete a study, its declarations and every run.

Parameters:

name (str)

Return type:

None

records(study, run_id, labels=None)[source]

Return what a run recorded, in the order it was recorded.

Parameters:
Return type:

list[Record]

class flexorchestrator.backend.FileValue(name, data)[source]

Bases: object

The value of a file variable.

Parameters:
name

The file name (no directory).

Type:

str

data

The file’s bytes.

Type:

bytes

class flexorchestrator.backend.MemoryBackend[source]

Bases: object

Studies, variables and runs held in dicts, safe to share between threads.

resolve_unit

Always None: there is no unit vocabulary, so the exporter’s QUDT keys stay unverified and aren’t declared.

Example

>>> backend = MemoryBackend()
>>> backend.define_study("s")
>>> backend.has_study("s")
True
define_study(name)[source]

Create the study if it doesn’t exist.

Parameters:

name (str)

Return type:

None

has_study(name)[source]

Return whether the study exists.

Parameters:

name (str)

Return type:

bool

studies()[source]

Return the names of every study, sorted.

Return type:

list[str]

variable(study, label)[source]

Return the declaration of label, or None.

Parameters:
Return type:

Variable | None

declare(study, label, *, role, kind, unit=None, metadata=None)[source]

Declare a variable, or return it if declared the same way.

Raises:

StorageError – If label is declared differently, or a JSON, table or file variable is given a unit.

Parameters:
Return type:

Variable

start_run(study, metadata)[source]

Start a run and return its id.

Parameters:
Return type:

str

record(run_id, label, value)[source]

Record a value in a running run.

Raises:

StorageError – If the run isn’t running, label isn’t declared, or the value doesn’t fit the kind: a timeseries row without a value, a table that isn’t a polars DataFrame, a file that isn’t a FileValue, or a value that isn’t JSON (NaN included).

Parameters:
Return type:

None

finish_run(run_id)[source]

Mark a running run succeeded.

Parameters:

run_id (str)

Return type:

None

fail_run(run_id, error)[source]

Mark a running run failed.

Parameters:
Return type:

None

runs(study, *, status=None, metadata=None)[source]

Return the study’s runs, oldest first.

Parameters:
Return type:

list[Run]

variables(study)[source]

Return every variable declared in the study.

Parameters:

study (str)

Return type:

list[Variable]

delete_runs(study, run_ids)[source]

Delete finished runs and everything they recorded.

Parameters:
Return type:

None

delete_study(name)[source]

Delete a study, its declarations and every run.

Parameters:

name (str)

Return type:

None

records(study, run_id, labels=None)[source]

Return what a run recorded, in the order it was recorded.

Parameters:
Return type:

list[Record]

class flexorchestrator.backend.Record(label, kind, value=None, rows=None)[source]

Bases: object

One value a run recorded.

Parameters:
label

The variable’s label.

Type:

str

kind

The variable’s kind.

Type:

Literal[‘timeseries’, ‘scalar’, ‘json’, ‘table’, ‘file’]

value

The value of a scalar or JSON variable, the polars DataFrame of a table, or the FileValue of a file.

Type:

Any

rows

The samples of a timeseries, in time order.

Type:

list[tuple[datetime.datetime, float]] | None

class flexorchestrator.backend.Run(run_id, status, metadata, started_at=None, error=None)[source]

Bases: object

One run of a study.

Parameters:
run_id

The backend’s id for the run.

Type:

str

status

"running", "succeeded" or "failed".

Type:

Literal[‘running’, ‘succeeded’, ‘failed’]

metadata

The metadata the run started with.

Type:

dict[str, Any]

started_at

When it started (UTC).

Type:

datetime.datetime | None

error

{"type", "message"} for a failed run.

Type:

Any

class flexorchestrator.backend.StorageBackend(*args, **kwargs)[source]

Bases: Protocol

What the orchestrator needs from a store.

resolve_unit

Looks a unit up in QUDT (see flexorchestrator.export.units.Resolver), or None if the backend has no unit vocabulary.

Type:

collections.abc.Callable[[str], collections.abc.Mapping[str, Any] | None] | None

define_study(name)[source]

Create the study if it doesn’t exist (idempotent).

Parameters:

name (str)

Return type:

None

has_study(name)[source]

Return whether the study exists.

Parameters:

name (str)

Return type:

bool

studies()[source]

Return the names of every study, sorted.

Return type:

list[str]

variable(study, label)[source]

Return the declaration of label, or None.

Parameters:
Return type:

Variable | None

declare(study, label, *, role, kind, unit=None, metadata=None)[source]

Declare a variable, or return it if declared the same way.

Raises:

StorageError – If label is declared with another role, kind, unit or metadata, or the backend rejects the unit.

Parameters:
Return type:

Variable

start_run(study, metadata)[source]

Start a run and return its id.

Parameters:
Return type:

str

record(run_id, label, value)[source]

Record a value in a running run.

value is a list of Row for a timeseries (every row with a number), a number or None for a scalar, any JSON value for a JSON variable, a polars DataFrame for a table, and a FileValue for a file.

Raises:

StorageError – If the run isn’t running, label isn’t declared, or the value doesn’t fit the variable’s kind.

Parameters:
Return type:

None

finish_run(run_id)[source]

Mark a running run succeeded.

Parameters:

run_id (str)

Return type:

None

fail_run(run_id, error)[source]

Mark a running run failed, recording error.

Parameters:
Return type:

None

runs(study, *, status=None, metadata=None)[source]

Return the study’s runs, oldest first.

Parameters:
  • study (str) – The study.

  • status (Literal['running', 'succeeded', 'failed'] | None) – Only runs with this status.

  • metadata (Mapping[str, Any] | None) – Only runs whose metadata has these exact values.

Return type:

list[Run]

variables(study)[source]

Return every variable declared in the study.

Parameters:

study (str)

Return type:

list[Variable]

delete_runs(study, run_ids)[source]

Delete finished runs and everything they recorded.

Raises:

StorageError – If a run doesn’t exist in the study or is still running; then nothing is deleted.

Parameters:
Return type:

None

delete_study(name)[source]

Delete a study, its declarations and every run.

Raises:

StorageError – If the study doesn’t exist or has a running run.

Parameters:

name (str)

Return type:

None

records(study, run_id, labels=None)[source]

Return what a run recorded, in the order it was recorded.

Parameters:
  • study (str) – The study.

  • run_id (str) – The run.

  • labels (Sequence[str] | None) – Only these labels; a backend then reads only their data.

Return type:

list[Record]

class flexorchestrator.backend.Variable(label, role, kind, unit=None, metadata=<factory>)[source]

Bases: object

A declared variable.

Parameters:
  • label (str)

  • role (Literal['input', 'output'])

  • kind (Literal['timeseries', 'scalar', 'json', 'table', 'file'])

  • unit (str | None)

  • metadata (dict[str, Any])

label

The variable’s label, unique within its study.

Type:

str

role

"input" or "output".

Type:

Literal[‘input’, ‘output’]

kind

"timeseries", "scalar", "json", "table" or "file".

Type:

Literal[‘timeseries’, ‘scalar’, ‘json’, ‘table’, ‘file’]

unit

The QUDT unit key, or None.

Type:

str | None

metadata

Everything else declared with it.

Type:

dict[str, Any]

flexorchestrator.backend.align(by_column, columns)[source]

Put columns of {time: value} on the sorted union of their timestamps.

Parameters:
Returns:

(timestamps, {column: values}), None where a column has no value.

Return type:

tuple[list[datetime], dict[str, list[Any]]]

Example

>>> t1, t2 = datetime(2025, 1, 1, 1), datetime(2025, 1, 1, 2)
>>> align({"a": {t2: 2.0}, "b": {t1: 1.0}}, ["a", "b"])[1]
{'a': [None, 2.0], 'b': [1.0, None]}
flexorchestrator.backend.qudt_key(uri)[source]

Return the QUDT key a unit URI ends in (its last path part).

Example

>>> qudt_key("http://qudt.org/vocab/unit/KiloW-HR")
'KiloW-HR'
Parameters:

uri (str)

Return type:

str

flexorchestrator.backend.recording(backend, study, metadata)[source]

Start a run, yield its id, and finish it; fail it if the block raises.

Parameters:
  • backend (StorageBackend) – The store.

  • study (str) – The study the run belongs to; its variables must be declared.

  • metadata (Mapping[str, Any]) – The run metadata.

Yields:

The run id, for StorageBackend.record().

Return type:

Iterator[str]

Example

>>> from flexorchestrator.backend import MemoryBackend
>>> backend = MemoryBackend()
>>> backend.define_study("s")
>>> _ = backend.declare("s", "x", role="output", kind="scalar")
>>> with recording(backend, "s", {}) as run_id:
...     backend.record(run_id, "x", 1.0)
>>> backend.runs("s")[0].status
'succeeded'
flexorchestrator.backend.to_rows(timestamps, values)[source]

Pair timestamps with values as UTC samples.

Each sample is a Row.

A missing value (None) is left out: a timeseries has no sample there.

Raises:

StorageError – If a timestamp isn’t a datetime.

Parameters:
Return type:

list[tuple[datetime, float]]

flexorchestrator.backend.to_utc(when)[source]

Return when as a timezone-aware UTC datetime.

Parameters:

when (Any) – A datetime (or a pandas Timestamp); naive means UTC.

Returns:

The UTC datetime.

Raises:

StorageError – If when isn’t a datetime.

Return type:

datetime

Example

>>> to_utc(datetime(2025, 7, 8)).isoformat()
'2025-07-08T00:00:00+00:00'
class flexorchestrator.backend.AcquiriumBackend(acquirium)[source]

Bases: object

Stores studies, variables and runs in Acquirium.

Parameters:

acquirium (Any) – A connected Acquirium client, e.g. from acquirium.init(data_dir=...).

acquirium

The client.

resolve_unit

Acquirium’s QUDT lookup, so the exporter verifies every unit key against the store’s own vocabulary.

Example

>>> import acquirium as aq
>>> backend = AcquiriumBackend(aq.init(data_dir=".flexorch"))
define_study(name)[source]

Create the study if it doesn’t exist.

Parameters:

name (str)

Return type:

None

has_study(name)[source]

Return whether the study exists.

Parameters:

name (str)

Return type:

bool

studies()[source]

Return the names of every study, sorted.

Return type:

list[str]

variable(study, label)[source]

Return the declaration of label, or None.

Parameters:
Return type:

Variable | None

declare(study, label, *, role, kind, unit=None, metadata=None)[source]

Declare a variable, or return it if declared the same way.

Raises:

StorageError – If label is declared differently, or Acquirium can’t resolve unit.

Parameters:
Return type:

Variable

start_run(study, metadata)[source]

Start a run and return its id.

Parameters:
Return type:

str

record(run_id, label, value)[source]

Record a value in a running run.

Raises:

StorageError – If the run isn’t running here, label isn’t declared, or Acquirium rejects the value.

Parameters:
Return type:

None

finish_run(run_id)[source]

Mark a running run succeeded.

Parameters:

run_id (str)

Return type:

None

fail_run(run_id, error)[source]

Mark a running run failed.

Parameters:
Return type:

None

runs(study, *, status=None, metadata=None)[source]

Return the study’s runs, oldest first.

Parameters:
Return type:

list[Run]

variables(study)[source]

Return every variable declared in the study.

Parameters:

study (str)

Return type:

list[Variable]

delete_runs(study, run_ids)[source]

Delete finished runs and everything they recorded.

Parameters:
Return type:

None

delete_study(name)[source]

Delete a study, its declarations and every run.

Parameters:

name (str)

Return type:

None

records(study, run_id, labels=None)[source]

Return what a run recorded, in the order it was recorded.

Parameters:
Return type:

list[Record]

stream_rows(ref, start=None, end=None)[source]

Return a stream’s samples, oldest first, as UTC (time, value) rows.

Read through Acquirium’s query API, so the values are in the unit stream_info() reports (Acquirium converts a stream stored in another unit than its point’s).

Parameters:
  • ref (str) – The stream’s reference URI.

  • start (Any) – Only samples at or after this datetime.

  • end (Any) – Only samples at or before this datetime.

Return type:

list[tuple[datetime, float]]

sparql_select(query)[source]

Run a read-only SPARQL query; return {"columns", "rows"}.

Only for the sparql selector, whose query the user writes; the other stream lookups go through Acquirium’s query API.

Parameters:

query (str)

Return type:

dict[str, Any]

stream_info(refs)[source]

Return each stream’s name (its source-local name), label and unit.

The label is its point’s; the unit is a QUDT key, the one stream_rows() gives values in, or None if it has none. A stream Acquirium doesn’t have gets no name.

Parameters:

refs (Sequence[str])

Return type:

dict[str, dict[str, Any]]

stream_ref(source_id, ref_name)[source]

Return the reference URI of source_id’s stream ref_name.

Acquirium derives it from the two names, so this doesn’t check that the stream exists; stream_info() gives a missing stream no name.

Parameters:
  • source_id (str)

  • ref_name (str)

Return type:

str

find_streams(text)[source]

Find the streams whose point’s label matches text.

A label equal to text (ignoring case) wins; failing that, every label containing all of its words. With no label match, text is resolved to a point with Acquirium’s resolve and that point’s streams are returned.

Returns:

[{"ref", "label", "point"}], sorted by label.

Parameters:

text (str)

Return type:

list[dict[str, Any]]

flexorchestrator.backend.base.Row

One timeseries sample, (timestamp, value).

alias of tuple[datetime, float]

class flexorchestrator.backend.base.StreamStore(*args, **kwargs)[source]

Bases: Protocol

Optional: a backend that also reads the general store’s streams.

Streams outside the experiment ledger (a plant historian’s, say) are what the ref_uris, streams, resolve and sparql fit selectors read. The Acquirium backend has them; the memory backend doesn’t. This protocol documents the methods; the selectors check for them with hasattr.

stream_rows(ref, start=None, end=None)[source]

Return a stream’s samples between start and end, oldest first.

Parameters:
Return type:

list[tuple[datetime, float]]

sparql_select(query)[source]

Run a read-only SPARQL query; return {"columns", "rows"}.

Parameters:

query (str)

Return type:

dict[str, Any]

stream_info(refs)[source]

Return {ref: {"name", "label", "unit"}}; the unit is a QUDT key.

Parameters:

refs (Sequence[str])

Return type:

dict[str, dict[str, Any]]

find_streams(text)[source]

Return [{"ref", "label", "point"}] for streams matching text.

Parameters:

text (str)

Return type:

list[dict[str, Any]]

stream_ref(source_id, ref_name)[source]

Return the reference URI of source_id’s stream ref_name.

Parameters:
  • source_id (str)

  • ref_name (str)

Return type:

str

What is stored

Datasets: tables of measured data stored with a study.

A dataset name is one run of <s>::data carrying {flexorch_kind: "data", flexorch_tag: name}:

  • each column is a timeseries input labelled <name>/<column>, so two datasets can both have a flow column, declared with its QUDT unit (when one is found) and the metadata dataset, column and unit_text (the unit as the user wrote it);

  • the manifest JSON lists the columns in order, their units, the row count and the time range.

Units are found the way the exporter finds them (pint’s parts, verified with the backend’s resolver), and failing that by the resolver’s own text lookup, which understands spellings like m3/day. A unit the resolver can’t place is stored as text only, with a warning; without a resolver (the memory backend) every unit is stored as text only.

flexorchestrator.data.MANIFEST = 'manifest'

The label of a dataset’s JSON manifest.

Type:

str

class flexorchestrator.data.StoredData(name, run_id, columns, rows, units)[source]

Bases: object

What store_data() stored.

Parameters:
name

The dataset’s name.

Type:

str

run_id

The backend run.

Type:

str

columns

The column names, in order.

Type:

list[str]

rows

The number of rows.

Type:

int

units

{column: QUDT key or None}.

Type:

dict[str, str | None]

flexorchestrator.data.column_label(name, column)[source]

Return the variable label of a dataset column.

Parameters:
Return type:

str

flexorchestrator.data.qudt_unit(text, mapper)[source]

Return the verified QUDT key for a unit as a user wrote it, or None.

Without a resolver no key can be verified, so the answer is None.

Parameters:
Return type:

str | None

flexorchestrator.data.store(backend, study, name, timestamps, columns, units, mapper, metadata)[source]

Declare and record one dataset as a run of study.

Everything is checked and declared before the run starts.

Parameters:
  • backend (StorageBackend) – The store.

  • study (str) – The <s>::data study.

  • name (str) – The dataset’s name.

  • timestamps (list) – The UTC timestamps, one per row.

  • columns (Mapping[str, list[float | None]]) – {column: values}, a value per timestamp (None if missing).

  • units (Mapping[str, str | None]) – {column: unit as the user wrote it}; columns left out have none.

  • mapper (UnitMapper) – Finds each unit’s QUDT key.

  • metadata (Mapping[str, Any]) – The run metadata.

Returns:

What was stored.

Raises:

StorageError – If the table is empty, units names a column the table doesn’t have, or a column is already declared with other units.

Return type:

StoredData

flexorchestrator.data.read(backend, study, run_id, name, columns)[source]

Read a dataset’s columns back, aligned on their timestamps.

Parameters:
  • backend (StorageBackend) – The store.

  • study (str) – The <s>::data study.

  • run_id (str) – The dataset’s run.

  • name (str) – The dataset’s name.

  • columns (list[str] | None) – The columns to read, in order; every column if None.

Returns:

(timestamps, {column: values}), None where a column has no value at a timestamp.

Raises:

StorageError – If columns names a column the dataset doesn’t have.

Return type:

tuple[list, dict[str, list[float | None]]]

Write exported model values to a backend, and read them back.

Every stored result keeps the whole model as a snapshot, two outputs of its run:

  • model_values, a table: a UTC time column and one Float64 column per timeseries key, null where the model had no value;

  • model_manifest, a JSON document: for every exported key, in walk order, its kind, component, index, Pyomo unit and QUDT unit, the value of each scalar, and the rows of model_values a timeseries covers when it isn’t every row (a subset of time such as startup).

Reads rebuild ModelData from the snapshot and convert units with pint when asked.

Keys a user asks for (streams=) are also written as native Acquirium variables, so they can be queried and fitted: a timeseries becomes a timeseries variable labelled by its key, a scalar a scalar variable. Their declarations carry the QUDT unit (only when verified, since Acquirium rejects a unit it can’t resolve) and the metadata pyomo_unit, component and index. A native label keeps the unit it was first declared with: a later run exporting it in another unit of the same dimensions is converted, and one whose units don’t convert raises.

flexorchestrator.results.MODEL_VALUES = 'model_values'

The label of a result’s table of timeseries values.

Type:

str

flexorchestrator.results.MODEL_MANIFEST = 'model_manifest'

The label of a result’s JSON manifest.

Type:

str

flexorchestrator.results.TIME = 'time'

The time column of model_values.

Type:

str

flexorchestrator.results.snapshot(data)[source]

Turn exported values into the model_values table and its manifest.

Parameters:

data (ModelData) – The exported values.

Returns:

(table, manifest); the table is None when nothing is a timeseries.

Raises:

StorageError – If a timeseries has no datetimes, or a key is time.

Return type:

tuple[DataFrame | None, dict[str, Any]]

flexorchestrator.results.layout(data)[source]

Place every timeseries on one sorted UTC time axis.

Parameters:

data (ModelData) – The exported values.

Returns:

the union of the timestamps, sorted, and for each timeseries key the positions in times it has values at, or None when it has one at every position.

Return type:

(times, rows)

Raises:

StorageError – If a timeseries has no datetimes, or a key is time.

flexorchestrator.results.spread(rows, values, size)[source]

Return size values: values at rows, None elsewhere.

rows is None when values already has one per position (see layout()).

Parameters:
Return type:

list[float | None]

flexorchestrator.results.read_snapshot(table, manifest)[source]

Rebuild a result’s ModelData.

It is read from the result’s table and manifest.

Raises:

StorageError – If the manifest’s schema isn’t one this version reads.

Parameters:
Return type:

ModelData

flexorchestrator.results.convert(data, units)[source]

Convert values to other Pyomo units, with pint.

Parameters:
  • data (ModelData) – The values.

  • units (Mapping[str, str]) – {key or component path: Pyomo unit}; a component path converts all of its keys.

Returns:

The values, with unit_pyomo set to the new unit and unit_qudt cleared where converted.

Raises:
  • ExportError – If units names a key or component that isn’t there.

  • UnitError – If a value has no unit, or its unit doesn’t convert.

Return type:

ModelData

class flexorchestrator.results.ResultReads[source]

Bases: object

The read methods a stored or loaded result shares.

A subclass provides data(units) and to_frame(frame, units); this adds the conveniences on top of them.

data(units=None)[source]

Return the values, converted to units if given.

Parameters:

units (Mapping[str, str] | None)

Return type:

ModelData

to_frame(frame=None, units=None)[source]

Return the timeseries as one table, a column per key.

Parameters:
Return type:

Any

to_polars(units=None)[source]

Return to_frame() as a polars DataFrame.

Parameters:

units (Mapping[str, str] | None)

Return type:

Any

to_pandas(units=None)[source]

Return to_frame() as a pandas DataFrame.

Parameters:

units (Mapping[str, str] | None)

Return type:

Any

scalars(units=None)[source]

Return {key: value} for every scalar.

Parameters:

units (Mapping[str, str] | None)

Return type:

dict[str, Any]

property units: dict[str, str | None]

{key: Pyomo unit} for every stored key.

flexorchestrator.results.select(data, patterns)[source]

Pick the values a list of keys, component paths or globs names.

A pattern matches a key or a component path exactly, or as a glob ("costing.*").

Raises:

ExportError – If a pattern matches nothing.

Parameters:
Return type:

ModelData

flexorchestrator.results.plan_writes(backend, study, data)[source]

Check values against the study’s declarations and prepare native writes.

Nothing is written, so a run is never started for values that can’t be stored.

Parameters:
  • backend (StorageBackend) – The store.

  • study (str) – The study the run will belong to.

  • data (ModelData) – The values to write natively.

Returns:

One write per value, in walk order, with values converted to the declared units. A timeseries leaves out points with no value.

Raises:
  • StorageError – If a key is declared with another kind, or a timeseries has no datetimes.

  • UnitError – If a value’s unit doesn’t convert to its declared unit.

Return type:

list[_Write]

flexorchestrator.results.declare(backend, study, writes)[source]

Declare every native value that isn’t declared yet.

Parameters:
Return type:

None

flexorchestrator.results.record(backend, run_id, writes)[source]

Record the prepared native values in a running run.

Parameters:
Return type:

None

Specs as runs of <s>::specs.

Each stored spec is one run. Its inputs are the spec_record JSON (the SpecRecord: the spec with every referenced path replaced by its stored name, its format, hash, parent and assets) and one file input per referenced file, labelled with the asset’s stored name. The run metadata is the record’s (flexorch_kind, flexorch_tag, spec_hash, spec_format, parent_tag) plus the run provenance.

Acquirium keeps a file’s bytes once per content hash, so the same tariff referenced by many specs is stored once.

flexorchestrator.spec_store.SPEC_RECORD = 'spec_record'

The label of a spec run’s JSON input holding the SpecRecord.

Type:

str

flexorchestrator.spec_store.write(backend, ledger, record, files, metadata)[source]

Store a spec and its files as one run, and return the run id.

Parameters:
  • backend (StorageBackend) – The store.

  • ledger (str) – The <s>::specs study.

  • record (SpecRecord) – The spec, already holding its assets’ stored names.

  • files (Mapping[str, bytes]) – {stored name: bytes} for every asset.

  • metadata (Mapping[str, Any]) – The run metadata.

Return type:

str

flexorchestrator.spec_store.read(backend, ledger, run_id)[source]

Read a stored spec and its files back, checking the hash.

Parameters:
  • backend (StorageBackend) – The store.

  • ledger (str) – The <s>::specs study.

  • run_id (str) – The spec’s run.

Returns:

The record and {stored name: bytes}.

Raises:

SpecError – If the record is missing, or the spec or a file doesn’t match its hash.

Return type:

tuple[SpecRecord, dict[str, bytes]]

Files a spec references but doesn’t embed.

A flex-pse flowsheet can point at a tariff file, a demand-response events file, or {"$source": "<path>"} data files, which flex-pse reads when it builds the model. The stored spec alone can’t rebuild that model, so the files are stored with it:

  • find_assets() lists every reference as a JSON pointer into the spec and the path written there. A format’s finder knows where its references live (flexpse_assets(), which reads the JSON only and needs no flex-pse); any spec can also name pointers explicitly.

  • collect_assets() reads each file (or takes its bytes, for a caller that has them, such as a service handling an upload), and rewrites its path in the spec to the stable name assets/<sha256[:12]>-<filename>, so the stored spec doesn’t depend on where the files were.

  • materialize_spec() writes the files to a directory and points the spec at them, so the build hook gets ordinary paths.

Nothing here imports pyomo or flex-pse.

flexorchestrator.assets.ASSET_DIR = 'assets'

The directory part of every stored asset name.

Type:

str

class flexorchestrator.assets.AssetRef(*, name, sha256, size)[source]

Bases: BaseModel

One stored file a spec references.

Parameters:
name

The stored name, assets/<sha256[:12]>-<filename>; the spec holds this name where it held the path.

Type:

str

sha256

The file’s sha256, hex.

Type:

str

size

The file’s size in bytes.

Type:

int

model_config = {'extra': 'forbid', 'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

flexorchestrator.assets.find_assets(spec, spec_format, pointers=())[source]

Return {JSON pointer: path} for every file spec references.

Parameters:
  • spec (Mapping[str, Any]) – The spec, as JSON.

  • spec_format (str) – Its format; flex-pse.flowsheet/... uses flexpse_assets().

  • pointers (Iterable[str]) – More references, as JSON pointers to path strings, for formats without a finder.

Raises:

SpecError – If a pointer doesn’t name a string in the spec.

Return type:

dict[str, str]

flexorchestrator.assets.flexpse_assets(spec)[source]

Find the files a flex-pse flowsheet references.

These are each costing element’s tariff_source (a path, a list, or a {name: path} mapping) and dr.events_source, where they end in .json or .csv, plus every {"$source": path} value anywhere.

Returns:

{JSON pointer: path}.

Parameters:

spec (Mapping[str, Any])

Return type:

dict[str, str]

Example

>>> flexpse_assets({"elements": [{"kind": "costing",
...     "tariff_source": "tariff.csv"}]})
{'/elements/0/tariff_source': 'tariff.csv'}
flexorchestrator.assets.flexpse_design_assets(spec)[source]

Find the files a flex-pse design study references.

These are the files of its base flowsheet (flexpse_assets()), plus those its changes bring: {"$source": path} values anywhere, and a costing element’s tariff_source and dr.events_source.

Returns:

{JSON pointer: path}.

Parameters:

spec (Mapping[str, Any])

Return type:

dict[str, str]

flexorchestrator.assets.collect_assets(spec, references, base_dir=None, known=None, given=None)[source]

Read the referenced files and point the spec at their stored names.

Parameters:
  • spec (Mapping[str, Any]) – The spec, as JSON (not changed).

  • references (Mapping[str, str]) – {JSON pointer: path}, from find_assets().

  • base_dir (str | Path | None) – The directory relative paths resolve against; the working directory by default.

  • known (Mapping[str, tuple[AssetRef, bytes]] | None) – Assets already stored, {name: (ref, bytes)}. A reference that is one of these names is kept as it is, so a spec derived from a stored one (e.g. by apply_surrogate) needs no files.

  • given (Mapping[str, bytes] | None) – The files’ bytes, {path as the spec writes it: bytes}, instead of reading them: then nothing is read from disk, so a spec from elsewhere can’t make this process read its own files. A path that is a stored name (assets/<sha256[:12]>-<name>) whose bytes match it keeps that name, so a spec read back with its files stores again unchanged. Without base_dir.

Returns:

The spec with each path replaced by its stored name, the references as {pointer: AssetRef}, and {name: bytes} for every file.

Raises:

SpecError – If a file can’t be read (a missing file is never skipped), or, with given, a reference has no bytes or bytes are given for a path the spec doesn’t reference.

Return type:

tuple[dict[str, Any], dict[str, AssetRef], dict[str, bytes]]

flexorchestrator.assets.materialize_spec(spec, assets, files, directory)[source]

Write a stored spec’s files to directory and point the spec at them.

Parameters:
  • spec (Mapping[str, Any]) – The stored spec, holding asset names.

  • assets (Mapping[str, AssetRef]) – Its {pointer: AssetRef}.

  • files (Mapping[str, bytes]) – {name: bytes} for every asset.

  • directory (str | Path) – Where to write the files (<directory>/assets/...).

Returns:

A copy of the spec with each asset name replaced by the file’s absolute path.

Raises:

SpecError – If a file is missing or doesn’t match its hash.

Return type:

dict[str, Any]

flexorchestrator.assets.get_pointer(document, pointer)[source]

Return the value at a JSON pointer (RFC 6901).

Raises:

SpecError – If the pointer doesn’t resolve.

Parameters:
  • document (Any)

  • pointer (str)

Return type:

Any

flexorchestrator.assets.set_pointer(document, pointer, new)[source]

Set the value at a JSON pointer, in place.

Raises:

SpecError – If the pointer doesn’t resolve to an existing value.

Parameters:
Return type:

None

Export and import

Study export to a folder of JSON files, and import back.

Example

>>> orch.export_study("exports/example_a")
>>> res = load_result("exports/example_a/results/base.json")
>>> orch.import_study("exports/example_a", name="example_a_copy")
class flexorchestrator.archive.DatasetFile(*, schema='flexorch-export/1', name, run_id, created_at=None, created_by=None, time_index, columns, metadata=<factory>, manifest=<factory>)[source]

Bases: _File

data/<name>.json: one dataset.

Parameters:
name

The dataset’s name.

Type:

str

run_id

Its run in <s>::data.

Type:

str

created_at

When it was stored.

Type:

str | None

created_by

Who stored it.

Type:

str | None

time_index

UTC timestamps, ISO 8601.

Type:

list[str]

columns

{column: DatasetColumn}, in order.

Type:

dict[str, flexorchestrator.archive.models.DatasetColumn]

metadata

The run’s metadata.

Type:

dict[str, Any]

manifest

The dataset’s stored manifest.

Type:

dict[str, Any]

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class flexorchestrator.archive.ExportReport(path, counts, files=<factory>)[source]

Bases: object

What export_study() wrote.

Parameters:
path

The export’s folder.

Type:

pathlib.Path

counts

Files per part.

Type:

dict[str, int]

files

Every file, relative to the folder.

Type:

list[str]

class flexorchestrator.archive.FitFile(*, schema='flexorch-export/1', tag, run_id, started_at=None, metadata=<factory>, fit_params, training_data, fit_result, series=None)[source]

Bases: _File

fits/<tag>.json: one fit run.

Parameters:
tag

The fit’s tag (its surrogate spec’s).

Type:

str

run_id

Its run in <s>::fits.

Type:

str

started_at

When it ran.

Type:

str | None

metadata

The run’s metadata.

Type:

dict[str, Any]

fit_params

The fit as planned.

Type:

dict[str, Any]

training_data

What the data resolved to, and how it was prepared.

Type:

dict[str, Any]

fit_result

Coefficients, metrics and diagnostics.

Type:

dict[str, Any]

series

The fitted series, if stored.

Type:

flexorchestrator.archive.models.FitSeries | None

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class flexorchestrator.archive.ImportReport(study, counts=<factory>, skipped=<factory>, run_ids=<factory>)[source]

Bases: object

What import_study() did.

Parameters:
study

The study it imported into.

Type:

str

counts

Items imported per part.

Type:

dict[str, int]

skipped

kind:tag of items already stored (on_existing: skip).

Type:

list[str]

run_ids

Original run id -> new run id.

Type:

dict[str, str]

class flexorchestrator.archive.LoadedResult(file)[source]

Bases: ResultReads

A result read from an export file; works like a ResultHandle, offline.

Parameters:

file (ResultFile)

file

The parsed file.

Type:

flexorchestrator.archive.models.ResultFile

property tag: str

The result’s tag.

property run_id: str

The run it was exported from.

property metadata: dict[str, Any]

The run’s metadata.

property spec_tag: str | None

The model spec it was built from.

property overrides: dict[str, Any]

The build overrides.

property model_inputs: list[dict[str, Any]]

Where the model inputs among overrides came from.

property outcome: SolveOutcome | None

How the solve ended.

data(units=None)[source]

Return the values, converted to units if given (see ResultHandle).

Parameters:

units (Mapping[str, str] | None)

Return type:

ModelData

to_frame(frame='polars', units=None)[source]

Return the timeseries as one table, a column per key.

Parameters:
Return type:

Any

class flexorchestrator.archive.ResultFile(*, schema='flexorch-export/1', tag, run_id, status='succeeded', started_at=None, model_spec_ref=None, overrides=<factory>, model_inputs=<factory>, hooks=<factory>, solve_outcome=None, metadata=<factory>, streams=<factory>, keys=<factory>, time_index, timeseries, scalars, stale=<factory>)[source]

Bases: _File

results/<tag>.json: one stored result.

Parameters:
tag

The result’s tag.

Type:

str

run_id

Its run in <s>::runs.

Type:

str

status

"succeeded" (only stored results are exported).

Type:

Literal[‘succeeded’]

started_at

When its run started.

Type:

str | None

model_spec_ref

{tag, spec_hash} of the spec it was built from.

Type:

dict[str, str] | None

overrides

The build overrides.

Type:

dict[str, Any]

model_inputs

Where the model inputs among overrides came from.

Type:

list[dict[str, Any]]

hooks

The hooks that built and solved it.

Type:

dict[str, str]

solve_outcome

How the solve ended.

Type:

dict[str, Any] | None

metadata

The run’s metadata.

Type:

dict[str, Any]

streams

The keys also stored as native variables.

Type:

list[str]

keys

Every key, in the order the model was walked.

Type:

list[str]

time_index

The timestamps.

Type:

flexorchestrator.archive.models.TimeIndex

timeseries

{key: ResultSeries}.

Type:

dict[str, flexorchestrator.archive.models.ResultSeries]

scalars

{key: ResultScalar}.

Type:

dict[str, flexorchestrator.archive.models.ResultScalar]

stale

Keys with missing values.

Type:

list[str]

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class flexorchestrator.archive.SpecFile(*, schema='flexorch-export/1', tag, kind, spec_format, spec_hash, parent_tag=None, created_at=None, created_by=None, run_id, versions=<factory>, metadata=<factory>, assets=<factory>, spec)[source]

Bases: _File

specs/models/<tag>.json or specs/surrogates/<tag>.json.

The spec’s referenced files are in specs/ under their stored names (specs/assets/<sha256[:12]>-<name>).

Parameters:
tag

The spec’s tag.

Type:

str

kind

"model_spec" or "surrogate_spec".

Type:

Literal[‘model_spec’, ‘surrogate_spec’]

spec_format

The spec’s format.

Type:

str

spec_hash

Its hash, files included.

Type:

str

parent_tag

The spec it was derived from.

Type:

str | None

created_at

When it was stored.

Type:

str | None

created_by

Who stored it.

Type:

str | None

run_id

Its run in <s>::specs.

Type:

str

versions

The versions that stored it.

Type:

dict[str, str | None]

metadata

The run’s metadata (fit_run_id for a fitted surrogate).

Type:

dict[str, Any]

assets

{JSON pointer: AssetRef} for each referenced file.

Type:

dict[str, flexorchestrator.assets.AssetRef]

spec

The spec.

Type:

dict[str, Any]

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class flexorchestrator.archive.StudyManifest(*, schema='flexorch-export/1', study, exported_at, exported_by=None, tenant=None, versions, counts, options, files)[source]

Bases: _File

study.json: what the export holds, and how it was made.

Parameters:
study

The exported study.

Type:

str

exported_at

When (UTC, ISO 8601).

Type:

str

exported_by

Who (FLEXORCH_USER or the login name).

Type:

str | None

tenant

The tenant the study belongs to; None outside a tenant stack.

Type:

str | None

versions

flex-orchestrator, flex-pse and Acquirium versions.

Type:

dict[str, str | None]

counts

How many files each part has.

Type:

dict[str, int]

options

The options the export was made with.

Type:

dict[str, Any]

files

Every other file of the export, relative to its folder.

Type:

list[str]

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

flexorchestrator.archive.export_result(orch, tag, path)[source]

Export one stored result to a JSON file (.json.gz compresses it).

Parameters:
  • orch (Any) – The orchestrator, with the result’s study selected.

  • tag (str) – The result’s tag.

  • path (str | PathLike[str]) – The file to write; a .gz suffix gzips it. Its folder is created if needed.

Returns:

The file written.

Raises:

TagNotFoundError – If no result has this tag.

Return type:

Path

flexorchestrator.archive.export_study(orch, path, *, parts=('specs', 'data', 'fits', 'results'), tags=None, compress=False, overwrite=False)[source]

Export the orchestrator’s selected study to path.

Parameters:
  • orch (Any) – The orchestrator.

  • path (str | PathLike[str]) – The folder to create.

  • parts (Iterable[str]) – Which of specs, data, fits and results.

  • tags (Iterable[str] | None) – Only items with these tags (dataset names count as tags).

  • compress (bool) – Write *.json.gz instead of *.json (study.json and the spec’s referenced files stay as they are).

  • overwrite (bool) – Replace a folder that isn’t empty.

Returns:

What was written.

Raises:

ArchiveError – If path isn’t empty (without overwrite) or a part is unknown.

Return type:

ExportReport

flexorchestrator.archive.import_study(orch, path, *, name=None, on_existing='error')[source]

Import an exported study and select it.

Parameters:
  • orch (Any) – The orchestrator to import into.

  • path (str | PathLike[str]) – The export’s folder.

  • name (str | None) – The new study’s name; the exported study’s by default.

  • on_existing (Literal['error', 'skip']) – If the study exists: error, or skip the items it already has and import the rest into it.

Returns:

What was imported.

Raises:
  • ArchiveError – If a checksum doesn’t match, a file is missing or unlisted, a file’s schema isn’t flexorch-export/1, or a result names a spec whose stored hash differs from the one it was built from.

  • StudyExistsError – If the study exists and on_existing is error.

Return type:

ImportReport

flexorchestrator.archive.json_schemas()[source]

Return {name: JSON Schema} for every export file model.

Return type:

dict[str, dict[str, Any]]

flexorchestrator.archive.load_result(path)[source]

Read a result file (results/<tag>.json, or one from export_result).

No database is needed.

Raises:

ArchiveError – If the file can’t be read or isn’t a result file.

Parameters:

path (str | PathLike[str])

Return type:

LoadedResult

Example

>>> res = load_result("exports/example_a/results/base.json")
>>> res.to_frame("pandas"), res.units
flexorchestrator.archive.read_json(path)[source]

Read an export file, gzipped (.gz) or not.

Raises:

ArchiveError – If it can’t be read, isn’t JSON, or has another schema.

Parameters:

path (str | PathLike[str])

Return type:

Any

flexorchestrator.archive.models.SCHEMA = 'flexorch-export/1'

The schema version every export file carries.

Type:

str

flexorchestrator.archive.export.PARTS = ('specs', 'data', 'fits', 'results')

The parts an export can hold, in the order they’re imported.

Type:

tuple[str, …]

flexorchestrator.archive.imports.IMPORTED_FROM = 'flexorch_imported_from'

The run metadata key recording an imported item’s origin.

Type:

str

The flexorch-export/1 file formats, as pydantic models.

Every file of a study export is one of these models as JSON, with "schema": "flexorch-export/1". Their JSON Schemas are published in docs/schemas/ (flexorchestrator.schemas), so an export can be read without the orchestrator.

The parts of the export file formats:

class flexorchestrator.archive.models.DatasetColumn(*, unit=None, qudt_unit=None, values)[source]

Bases: BaseModel

One column of a dataset file.

Parameters:
unit

The unit as the user wrote it.

Type:

str | None

qudt_unit

Its QUDT key, if one was found.

Type:

str | None

values

One per time_index entry; null where missing.

Type:

list[float | None]

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class flexorchestrator.archive.models.TimeIndex(*, timestamps)[source]

Bases: BaseModel

A result’s timestamps, stored once.

Parameters:

timestamps (list[str])

timestamps

UTC, ISO 8601; every timeseries lines up with them.

Type:

list[str]

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class flexorchestrator.archive.models.ResultSeries(*, unit=None, pyomo_unit=None, unit_verified=False, component, index=<factory>, values, rows=None)[source]

Bases: BaseModel

One timeseries of a result file.

Parameters:
unit

The QUDT key.

Type:

str | None

pyomo_unit

The Pyomo unit.

Type:

str | None

unit_verified

Whether the QUDT key is confirmed.

Type:

bool

component

The Pyomo component.

Type:

str

index

Its custom index ([] for none), JSON values of their types.

Type:

list[Any]

values

One per time_index timestamp; null where missing.

Type:

list[float | None]

rows

For a series covering only part of time (startup), the positions in time_index it covers; all of them if omitted.

Type:

list[int] | None

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class flexorchestrator.archive.models.ResultScalar(*, unit=None, pyomo_unit=None, unit_verified=False, component, index=<factory>, value)[source]

Bases: BaseModel

One scalar of a result file (see ResultSeries).

Parameters:
model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class flexorchestrator.archive.models.FitSeries(*, time_index, actual, fitted, residual)[source]

Bases: BaseModel

A fit’s actual / fitted / residual series.

Parameters:
model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

Verify

verify: check a store and fingerprint what it holds.

Run after a restore or a migration, or any time. For every orchestrator study it reports, per kind of item (results, datasets, model and surrogate specs, fits):

  • how many runs there are in each status, and the tags that succeeded;

  • problems: a tag stored twice (only one is allowed), a run still running, and an item whose values can’t be read back;

  • for a sample of items (the first samples by tag), a hash of every value stored with it: read from the database, the tables and the files, so a restore that lost any of them shows.

compare() lines two reports up: take one before a restore (or a move), one after, and expect no differences.

flexorchestrator.verify.verify(orch, studies=None, samples=5)[source]

Check every study (or studies) and return the report.

Parameters:
  • orch (Any) – The orchestrator, on the store to check.

  • studies (list[str] | None) – The studies to check; every orchestrator study by default.

  • samples (int) – How many items of each kind to read in full and hash.

Returns:

A dict with report, checked_at, samples, problems (a list) and studies, which is {study: {kind: {"runs", "tags", "hashes"}}}. A kind holds runs ({status: count}), tags (sorted) and hashes ({tag: {"run_id", "hash"}}).

Return type:

dict

flexorchestrator.verify.compare(before, after)[source]

Return how after differs from before; [] if it doesn’t.

Compares the studies, each kind’s succeeded runs and tags, and the hashes of items sampled in both. Run ids aren’t compared, nor failed or running runs (an export copies only what succeeded), so a copy (an import, a move to another store) matches its original. checked_at and the problems lists aren’t compared: verify() reports problems on its own.

Parameters:
Return type:

list[str]