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:
objectStudies, 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
pathholds something else, or a newer layout.- Parameters:
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
- declare(study, label, *, role, kind, unit=None, metadata=None)[source]¶
Declare a variable, or return it if declared the same way.
- Raises:
StorageError – If
labelis declared differently, a JSON, table or file variable is given a unit, or the metadata isn’t JSON.- Parameters:
- Return type:
- record(run_id, label, value)[source]¶
Record a value in a running run.
- Raises:
StorageError – If the run isn’t running,
labelisn’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:
run_id (str)
error (BaseException)
- Return type:
None
- class flexorchestrator.backend.FileValue(name, data)[source]¶
Bases:
objectThe value of a
filevariable.
- class flexorchestrator.backend.MemoryBackend[source]¶
Bases:
objectStudies, 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
- declare(study, label, *, role, kind, unit=None, metadata=None)[source]¶
Declare a variable, or return it if declared the same way.
- Raises:
StorageError – If
labelis declared differently, or a JSON, table or file variable is given a unit.- Parameters:
- Return type:
- record(run_id, label, value)[source]¶
Record a value in a running run.
- Raises:
StorageError – If the run isn’t running,
labelisn’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:
run_id (str)
error (BaseException)
- Return type:
None
- class flexorchestrator.backend.Record(label, kind, value=None, rows=None)[source]¶
Bases:
objectOne value a run recorded.
- Parameters:
- 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
FileValueof 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:
objectOne run of a study.
- Parameters:
- status¶
"running","succeeded"or"failed".- Type:
Literal[‘running’, ‘succeeded’, ‘failed’]
- 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:
ProtocolWhat the orchestrator needs from a store.
- resolve_unit¶
Looks a unit up in QUDT (see
flexorchestrator.export.units.Resolver), orNoneif 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
- declare(study, label, *, role, kind, unit=None, metadata=None)[source]¶
Declare a variable, or return it if declared the same way.
- Raises:
StorageError – If
labelis declared with another role, kind, unit or metadata, or the backend rejects the unit.- Parameters:
- Return type:
- record(run_id, label, value)[source]¶
Record a value in a running run.
valueis a list ofRowfor a timeseries (every row with a number), a number orNonefor a scalar, any JSON value for a JSON variable, a polars DataFrame for a table, and aFileValuefor a file.- Raises:
StorageError – If the run isn’t running,
labelisn’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, recordingerror.- Parameters:
run_id (str)
error (BaseException)
- Return type:
None
- 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
- class flexorchestrator.backend.Variable(label, role, kind, unit=None, metadata=<factory>)[source]¶
Bases:
objectA declared variable.
- Parameters:
- role¶
"input"or"output".- Type:
Literal[‘input’, ‘output’]
- kind¶
"timeseries","scalar","json","table"or"file".- Type:
Literal[‘timeseries’, ‘scalar’, ‘json’, ‘table’, ‘file’]
- flexorchestrator.backend.align(by_column, columns)[source]¶
Put columns of
{time: value}on the sorted union of their timestamps.- Parameters:
- Returns:
(timestamps, {column: values}),Nonewhere a column has no value.- Return type:
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'
- 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.
- Yields:
The run id, for
StorageBackend.record().- Return type:
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.
- flexorchestrator.backend.to_utc(when)[source]¶
Return
whenas a timezone-aware UTC datetime.- Parameters:
when (Any) – A
datetime(or a pandasTimestamp); naive means UTC.- Returns:
The UTC datetime.
- Raises:
StorageError – If
whenisn’t a datetime.- Return type:
Example
>>> to_utc(datetime(2025, 7, 8)).isoformat() '2025-07-08T00:00:00+00:00'
- class flexorchestrator.backend.AcquiriumBackend(acquirium)[source]¶
Bases:
objectStores 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
- declare(study, label, *, role, kind, unit=None, metadata=None)[source]¶
Declare a variable, or return it if declared the same way.
- record(run_id, label, value)[source]¶
Record a value in a running run.
- Raises:
StorageError – If the run isn’t running here,
labelisn’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:
run_id (str)
error (BaseException)
- 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.
- 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).
- sparql_select(query)[source]¶
Run a read-only SPARQL query; return
{"columns", "rows"}.Only for the
sparqlselector, whose query the user writes; the other stream lookups go through Acquirium’s query API.
- stream_info(refs)[source]¶
Return each stream’s
name(its source-local name),labeland unit.The label is its point’s; the unit is a QUDT key, the one
stream_rows()gives values in, orNoneif it has none. A stream Acquirium doesn’t have gets noname.
- stream_ref(source_id, ref_name)[source]¶
Return the reference URI of
source_id’s streamref_name.Acquirium derives it from the two names, so this doesn’t check that the stream exists;
stream_info()gives a missing stream noname.
- flexorchestrator.backend.base.Row¶
One timeseries sample,
(timestamp, value).
- class flexorchestrator.backend.base.StreamStore(*args, **kwargs)[source]¶
Bases:
ProtocolOptional: 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,resolveandsparqlfit selectors read. The Acquirium backend has them; the memory backend doesn’t. This protocol documents the methods; the selectors check for them withhasattr.- stream_rows(ref, start=None, end=None)[source]¶
Return a stream’s samples between
startandend, oldest first.
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 aflowcolumn, declared with its QUDT unit (when one is found) and the metadatadataset,columnandunit_text(the unit as the user wrote it);the
manifestJSON 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.
- class flexorchestrator.data.StoredData(name, run_id, columns, rows, units)[source]¶
Bases:
objectWhat
store_data()stored.
- flexorchestrator.data.column_label(name, column)[source]¶
Return the variable label of a dataset column.
- 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:
text (str | None)
mapper (UnitMapper)
- 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>::datastudy.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 (Noneif 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.
- Returns:
What was stored.
- Raises:
StorageError – If the table is empty,
unitsnames a column the table doesn’t have, or a column is already declared with other units.- Return type:
- flexorchestrator.data.read(backend, study, run_id, name, columns)[source]¶
Read a dataset’s columns back, aligned on their timestamps.
- Parameters:
- Returns:
(timestamps, {column: values}),Nonewhere a column has no value at a timestamp.- Raises:
StorageError – If
columnsnames a column the dataset doesn’t have.- Return type:
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, atable: a UTCtimecolumn 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 ofmodel_valuesa timeseries covers when it isn’t every row (a subset of time such asstartup).
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
tableof timeseries values.- Type:
- flexorchestrator.results.MODEL_MANIFEST = 'model_manifest'¶
The label of a result’s JSON manifest.
- Type:
- flexorchestrator.results.snapshot(data)[source]¶
Turn exported values into the
model_valuestable and its manifest.
- 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
timesit has values at, orNonewhen 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
sizevalues:valuesatrows,Noneelsewhere.rowsisNonewhenvaluesalready has one per position (seelayout()).
- 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:
- flexorchestrator.results.convert(data, units)[source]¶
Convert values to other Pyomo units, with pint.
- Parameters:
- Returns:
The values, with
unit_pyomoset to the new unit andunit_qudtcleared where converted.- Raises:
ExportError – If
unitsnames a key or component that isn’t there.UnitError – If a value has no unit, or its unit doesn’t convert.
- Return type:
- class flexorchestrator.results.ResultReads[source]¶
Bases:
objectThe read methods a stored or loaded result shares.
A subclass provides
data(units)andto_frame(frame, units); this adds the conveniences on top of them.- to_polars(units=None)[source]¶
Return
to_frame()as a polars DataFrame.
- to_pandas(units=None)[source]¶
Return
to_frame()as a pandas DataFrame.
- 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:
- 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:
backend (StorageBackend)
study (str)
writes (Sequence[_Write])
- Return type:
None
- flexorchestrator.results.record(backend, run_id, writes)[source]¶
Record the prepared native values in a running run.
- Parameters:
backend (StorageBackend)
run_id (str)
writes (Sequence[_Write])
- 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:
- 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>::specsstudy.record (SpecRecord) – The spec, already holding its assets’ stored names.
files (Mapping[str, bytes]) –
{stored name: bytes}for every asset.
- Return type:
- 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>::specsstudy.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 nameassets/<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:
- class flexorchestrator.assets.AssetRef(*, name, sha256, size)[source]¶
Bases:
BaseModelOne stored file a spec references.
- name¶
The stored name,
assets/<sha256[:12]>-<filename>; the spec holds this name where it held the path.- Type:
- 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 filespecreferences.- Parameters:
- Raises:
SpecError – If a pointer doesn’t name a string in the spec.
- Return type:
- 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) anddr.events_source, where they end in.jsonor.csv, plus every{"$source": path}value anywhere.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
baseflowsheet (flexpse_assets()), plus those itschangesbring:{"$source": path}values anywhere, and a costing element’stariff_sourceanddr.events_source.
- 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:
references (Mapping[str, str]) –
{JSON pointer: path}, fromfind_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. byapply_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. Withoutbase_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
directoryand point the spec at them.- Parameters:
- 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:
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:
_Filedata/<name>.json: one dataset.- Parameters:
- columns¶
{column: DatasetColumn}, in order.
- 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:
objectWhat
export_study()wrote.- path¶
The export’s folder.
- Type:
- 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:
_Filefits/<tag>.json: one fit run.- Parameters:
- series¶
The fitted series, if stored.
- Type:
- 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:
objectWhat
import_study()did.
- class flexorchestrator.archive.LoadedResult(file)[source]¶
Bases:
ResultReadsA result read from an export file; works like a
ResultHandle, offline.- Parameters:
file (ResultFile)
- file¶
The parsed file.
- property outcome: SolveOutcome | None¶
How the solve ended.
- 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:
_Fileresults/<tag>.json: one stored result.- Parameters:
- status¶
"succeeded"(only stored results are exported).- Type:
Literal[‘succeeded’]
- time_index¶
The timestamps.
- timeseries¶
{key: ResultSeries}.
- scalars¶
{key: ResultScalar}.
- 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:
_Filespecs/models/<tag>.jsonorspecs/surrogates/<tag>.json.The spec’s referenced files are in
specs/under their stored names (specs/assets/<sha256[:12]>-<name>).- Parameters:
- kind¶
"model_spec"or"surrogate_spec".- Type:
Literal[‘model_spec’, ‘surrogate_spec’]
- assets¶
{JSON pointer: AssetRef}for each referenced file.- Type:
- 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:
_Filestudy.json: what the export holds, and how it was made.- Parameters:
- 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.gzcompresses it).- Parameters:
- Returns:
The file written.
- Raises:
TagNotFoundError – If no result has this tag.
- Return type:
- 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.
parts (Iterable[str]) – Which of
specs,data,fitsandresults.tags (Iterable[str] | None) – Only items with these tags (dataset names count as tags).
compress (bool) – Write
*.json.gzinstead of*.json(study.jsonand 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
pathisn’t empty (withoutoverwrite) or a part is unknown.- Return type:
- flexorchestrator.archive.import_study(orch, path, *, name=None, on_existing='error')[source]¶
Import an exported study and select it.
- Parameters:
- 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_existingiserror.
- Return type:
- flexorchestrator.archive.json_schemas()[source]¶
Return
{name: JSON Schema}for every export file model.
- flexorchestrator.archive.load_result(path)[source]¶
Read a result file (
results/<tag>.json, or one fromexport_result).No database is needed.
- Raises:
ArchiveError – If the file can’t be read or isn’t a result file.
- Parameters:
- Return type:
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:
- Return type:
- flexorchestrator.archive.models.SCHEMA = 'flexorch-export/1'¶
The schema version every export file carries.
- Type:
- flexorchestrator.archive.export.PARTS = ('specs', 'data', 'fits', 'results')¶
The parts an export can hold, in the order they’re imported.
- flexorchestrator.archive.imports.IMPORTED_FROM = 'flexorch_imported_from'¶
The run metadata key recording an imported item’s origin.
- Type:
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:
BaseModelOne column of a dataset file.
- 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:
BaseModelA result’s timestamps, stored once.
- 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:
BaseModelOne timeseries of a result file.
- Parameters:
- rows¶
For a series covering only part of time (
startup), the positions intime_indexit covers; all of them if omitted.
- 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:
BaseModelOne 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:
BaseModelA fit’s
actual/fitted/residualseries.- 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
samplesby 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:
- Returns:
A dict with
report,checked_at,samples,problems(a list) andstudies, which is{study: {kind: {"runs", "tags", "hashes"}}}. A kind holdsruns({status: count}),tags(sorted) andhashes({tag: {"run_id", "hash"}}).- Return type:
- flexorchestrator.verify.compare(before, after)[source]¶
Return how
afterdiffers frombefore;[]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_atand the problems lists aren’t compared:verify()reports problems on its own.