The orchestrator

The orchestrator: studies, datasets and model results on a storage backend.

Model results are stored explicitly: every call names the model and the tag, and there is no “current model”. A study s is laid out as backend studies: s itself; s::runs, where each stored result is one run carrying {flexorch_kind: "result", flexorch_tag: tag}, the model snapshot (flexorchestrator.results), any values stored natively, and the solve_outcome JSON; s::data, where each dataset is one run (flexorchestrator.data); s::specs, where each model or surrogate spec is one run with the files it references (flexorchestrator.spec_store); and s::fits, where each surrogate fit is one run with its training-data provenance (flexorchestrator.fitting). Every run’s metadata also records the versions, the user, the hooks and the connection, so a result can be reproduced.

Commands extend it: execute_study and fit_surrogate are built in, plugins add more, and every call is recorded in flexorch::commands.

Without a backend, the orchestrator connects to Acquirium itself, in one of three modes (flexorchestrator.connection). To keep studies in a folder on disk with no Acquirium, pass a FileBackend.

class flexorchestrator.Orchestrator(backend=None, *, study=None, data_dir=None, db=None, acquirium_url=None, db_credentials=None, hooks=None, registry=None, unit_mapper=None, strict_units=False, frame='polars', allow_delete=True, plugins=None, environ=None, ray_address=None)[source]

Bases: object

Studies, model results and hooks on one storage backend.

Without backend, it connects to Acquirium in one of three modes:

  • Orchestrator(): a local managed Acquirium with DuckDB in data_dir (.flexorch by default);

  • Orchestrator(db="postgresql://host/db", data_dir=...): a managed Acquirium on Postgres, with the login from FLEXORCH_DB_PASSWORD_FILE, FLEXORCH_DB_USER / FLEXORCH_DB_PASSWORD or libpq’s PG* / ~/.pgpass, never from script code;

  • Orchestrator(acquirium_url="http://acquirium:8000"): a running one.

Parameters:
  • backend (StorageBackend | None) – The store, e.g. FileBackend (a folder on disk, no Acquirium), MemoryBackend or AcquiriumBackend. Leave it out to connect to Acquirium with the arguments below.

  • study (str | None) – A study to select; it must exist.

  • data_dir (str | PathLike[str] | None) – The managed Acquirium’s directory (modes 1 and 2).

  • db (str | None) – A Postgres URL without a password (mode 2).

  • acquirium_url (str | None) – A running Acquirium (mode 3). FLEXORCH_ACQUIRIUM_URL (from environ) selects it for the whole process, which is how a container or a host application points the library at its Acquirium; while it’s set, passing another store raises (see connect()).

  • db_credentials (DBCredentials | None) – An explicit Postgres login, for developers and tests.

  • hooks (HookSet | None) – Hooks that replace the flex-pse defaults, slot by slot.

  • registry (HookRegistry | None) – Where registered hook names resolve.

  • unit_mapper (UnitMapper | None) – Maps Pyomo units to QUDT. By default it verifies keys with the backend’s resolve_unit.

  • strict_units (bool) – With the default mapper, raise on a unit with no QUDT key instead of storing it without one.

  • frame (Literal['polars', 'pandas']) – What reads return by default, "polars" or "pandas".

  • allow_delete (bool) – Whether delete(), delete_study() and replace=True may delete anything. A deployment that must never lose a stored item turns this off.

  • plugins (Sequence[Plugin | str] | None) – Plugins to load: Plugin objects or installed plugin names. Plugins named in FLEXORCH_PLUGINS load too. Use create_orchestrator() to get a plugin’s orchestrator subclass.

  • environ (Mapping[str, str] | None) – Where FLEXORCH_PLUGINS, FLEXORCH_RAY_ADDRESS, FLEXORCH_ACQUIRIUM_URL and FLEXORCH_START_ACQUIRIUM are read; os.environ by default.

  • ray_address (str | None) – The Ray cluster for studies with max_workers > 1 when their config names none; FLEXORCH_RAY_ADDRESS if unset, else local Ray.

user

Who runs and stores are recorded as (flexorch_user); if None, FLEXORCH_USER or the login name. A host application sets it on each caller’s study handle.

Selecting a study (select_study(), create_study(), get_or_create_study()) makes it this orchestrator’s study, and also returns a study handle: a light copy fixed to that study, sharing the connection. A script keeps using the orchestrator; code that works in several studies at once, or from several threads, keeps the handle.

Example

>>> from flexorchestrator.backend import MemoryBackend
>>> orch = Orchestrator(MemoryBackend())
>>> a = orch.create_study("example_a")
>>> a.study, orch.study
('example_a', 'example_a')
close()[source]

Disconnect from an Acquirium this orchestrator connected to.

A managed server this process started is stopped; its data is kept. A backend that was passed in is left alone. Plugins’ on_shutdown runs first, once. A study handle shares the connection, so closing it does nothing: close the orchestrator it came from.

Return type:

None

property acquirium: Any

The backend’s Acquirium client, for Acquirium’s own API.

The orchestrator doesn’t wrap queries: use the client directly, e.g. orch.acquirium.study.get("example_a::runs").experiments.where(...).

Raises:

StorageError – If the backend isn’t backed by Acquirium.

property study: str

The selected study.

Raises:

StudyNotFoundError – If no study is selected.

create_study(name)[source]

Create a study and select it.

Returns:

A handle fixed to the study (see select_study()).

Raises:

StudyExistsError – If the study exists. Use get_or_create_study() when either is fine.

Parameters:

name (str)

Return type:

Self

select_study(name)[source]

Select an existing study, and return a handle fixed to it.

The study becomes this orchestrator’s, so a script goes on with orch. The handle is a light copy that keeps working in name whatever is selected on orch later, or from another thread: it shares the connection, plugins, hooks and the per-study locks. Set user on it to record who works through it. Closing a handle does nothing; close the orchestrator.

Raises:

StudyNotFoundError – If it doesn’t exist.

Parameters:

name (str)

Return type:

Self

Example

>>> from flexorchestrator.backend import MemoryBackend
>>> orch = Orchestrator(MemoryBackend())
>>> a, b = orch.create_study("a"), orch.create_study("b")
>>> a.study, b.study, orch.study
('a', 'b', 'b')
get_or_create_study(name)[source]

Select the study, creating it if it doesn’t exist; return its handle.

Parameters:

name (str)

Return type:

Self

studies()[source]

Return the names of the orchestrator studies in the store, sorted.

The ledger studies (<s>::runs and so on) aren’t listed.

Return type:

list[str]

register_hooks(name, **hooks)[source]

Register a named set of hooks, e.g. build=my_build.

A HookSet slot, or build(..., build="name"), can then refer to it by name. See register().

Parameters:
Return type:

HookSet

delete_study(name)[source]

Delete a study and everything stored in it, for good.

Deletes the study and its ledgers (results, datasets, specs and fits) with their declarations in Acquirium. If it is the selected study, none is selected afterwards, here and on the orchestrator a study handle came from; other handles to it then fail.

Raises:
  • StorageError – If deletion is turned off, or a run in the study is still running (then nothing is deleted).

  • StudyNotFoundError – If the study doesn’t exist.

Parameters:

name (str)

Return type:

None

delete(kind, tag)[source]

Delete a stored item, for good: every run with this kind and tag.

Parameters:
  • kind (str) – "result", "data", "model_spec", "surrogate_spec" or "fit".

  • tag (str) – The item’s tag (a result, spec or fit tag, or a dataset name).

Returns:

How many runs were deleted (failed attempts included).

Raises:
  • StorageError – If deletion is turned off, or the item’s run is still running.

  • TagNotFoundError – If nothing has this kind and tag.

  • ValueError – If kind isn’t one of the kinds above.

Return type:

int

store_model_spec(tag, spec, *, parent=None, base_dir=None, files=None, assets=(), spec_format=None, replace=False)[source]

Store a model spec, with the files it references, under tag.

The spec is validated and normalised by its format’s validator when that library is installed (a flex-pse spec gets its defaults written out). Every file it references (for flex-pse: tariff and events files and {"$source": path} data) is read and stored with it, and its path in the stored spec becomes the file’s stored name, so the spec rebuilds anywhere (build()). The hash covers the files too: editing a tariff changes spec_hash.

Parameters:
  • tag (str) – The spec’s tag, unique among the study’s model specs.

  • spec (Any) – A dict or pydantic model.

  • parent (str | None) – The tag of the model spec this one was derived from. Files the parent stored are reused when the spec names them by their stored names, as apply_surrogate()’s specs do.

  • base_dir (str | PathLike[str] | None) – The directory relative file paths resolve against; the working directory by default (flex-pse’s rule for a dict spec).

  • files (Mapping[str, bytes] | None) – The referenced files’ bytes, {path as the spec writes it: bytes}, instead of reading them (a service with an upload): then nothing is read from disk. Stored exactly as the same files read from disk, with the same spec_hash. A spec read back with model_spec() (tag, with_files=True) stores again unchanged with its files. Not with base_dir.

  • assets (Iterable[str]) – More file references, as JSON pointers to path strings, for a format the orchestrator can’t search.

  • spec_format (str | None) – The format; detected from the spec when omitted.

  • replace (bool) – Replace a stored spec with this tag.

Returns:

The stored record.

Raises:
  • TagExistsError – If a model spec with this tag is stored.

  • TagNotFoundError – If parent isn’t a stored model spec.

  • SpecError – If the spec or its tag is invalid, a referenced file can’t be read, or files lacks one or has one the spec doesn’t reference.

Return type:

SpecRecord

store_surrogate_spec(tag, spec, *, parent=None, spec_format=None, replace=False)[source]

Store a surrogate spec under tag.

Parameters:
  • tag (str) – The spec’s tag, unique among the study’s surrogate specs.

  • spec (Any) – A dict or pydantic model (for flex-pse, a SurrogateSpec).

  • parent (str | None) – The tag of the surrogate spec this one was derived from.

  • spec_format (str | None) – The format; detected from the spec when omitted.

  • replace (bool) – Replace a stored spec with this tag.

Returns:

The stored record.

Raises:
Return type:

SpecRecord

model_spec(tag, *, with_files=False)[source]

Return a stored model spec, checked against its hash.

Parameters:
Raises:

TagNotFoundError – If there is none with this tag.

Return type:

SpecRecord

surrogate_spec(tag)[source]

Return a stored surrogate spec, checked against its hash.

Raises:

TagNotFoundError – If there is none with this tag.

Parameters:

tag (str)

Return type:

SpecRecord

stored_specs(kind='model_spec')[source]

Return the study’s stored specs of one kind, oldest first.

Parameters:

kind (Literal['model_spec', 'surrogate_spec']) – "model_spec" or "surrogate_spec".

Raises:

ValueError – If kind isn’t a spec kind.

Return type:

list[SpecRecord]

materialize_spec(tag, directory)[source]

Write a stored model spec’s files to directory; return the spec.

The returned spec points at the written files by absolute path, so the build hook can read them from any working directory (or Ray worker).

Parameters:
Return type:

dict

build(tag, *, build=None, **overrides)[source]

Build the model a stored spec describes.

The spec’s files are written to a temporary directory for the build, so it doesn’t matter where they were when the spec was stored. The model remembers the spec tag, hash and overrides, so storing its results links them to the spec. Set variables from stored data afterwards, with apply_model_inputs().

Parameters:
  • tag (str) – The model spec’s tag.

  • build (Any) – The build hook; the orchestrator’s by default.

  • **overrides (Any) – Passed to the build hook (for flex-pse, fix elements: {"plant.ro.recovery": 0.6}).

Raises:
Return type:

Any

apply_model_inputs(model, model_inputs)[source]

Set variables of a built model from stored data.

Each entry’s data is lined up with the model’s time steps (the time_grid hook) and its variables fixed to it (the apply_values hook). A model from build() remembers what was applied, so storing its results records the values (in overrides) and where they came from (model_inputs). Applying a path again replaces it.

Parameters:
  • model (Any) – The built model, changed in place.

  • model_inputs (Any) – One entry or a list, each a ModelInput or a mapping in its shape (a fit selector, its columns renamed to the paths they set, plus how to line it up).

Returns:

the values fixed and their provenance.

Return type:

A Resolved

Raises:

ModelInputError – If an entry can’t be resolved, or sets a path the build’s overrides set.

Example

>>> model = orch.build("base")
>>> orch.apply_model_inputs(model, {
...     "streams": [{"source_id": "historian", "ref_name": "FT_101"}],
...     "rename": {"*": "plant.ro.permeate"},
... })
resolve_model_inputs(tag, model_inputs)[source]

Resolve model inputs against a stored spec, without building.

Parameters:
  • tag (str) – The model spec whose time steps the data is lined up with.

  • model_inputs (Sequence[Any]) – The entries: ModelInput or mappings.

Returns:

values (the build overrides) and provenance.

Return type:

A Resolved

Raises:
apply_surrogate(base, *, unit, surrogate, relation=None)[source]

Return a stored model spec with a stored surrogate applied to a unit.

Calls the apply_surrogate hook; the result isn’t stored. Store it with store_model_spec(tag, spec, parent=base), which reuses the base spec’s files.

Parameters:
  • base (str) – The model spec’s tag.

  • unit (str) – The unit to apply it to, e.g. "plant.digester".

  • surrogate (str) – The surrogate spec’s tag.

  • relation (str | None) – The relation it replaces; the hook’s default if omitted.

Return type:

dict

store_data(name, df, units=None, *, time_column=None, replace=False)[source]

Store a table of measured data as the dataset name.

Each column becomes a timeseries with its unit, so it can be queried, converted and used to fit surrogates. Timestamps are stored in UTC; naive ones are taken as UTC.

Parameters:
  • name (str) – The dataset’s name, unique among the study’s datasets.

  • df (Any) – A polars or pandas DataFrame of numeric columns.

  • units (dict[str, str | None] | None) – {column: unit}, as QUDT keys ("M3-PER-DAY") or as written ("m3/day", "gal/min"). Columns left out have no unit.

  • time_column (str | None) – The datetime column. For pandas the default is the index; for polars, the only datetime column.

  • replace (bool) – Replace a stored dataset of this name: the new one is written first, then the old one is deleted.

Returns:

What was stored.

Raises:
  • TagExistsError – If the dataset exists and replace is false.

  • SpecError – If name isn’t a valid tag.

  • StorageError – If the table can’t be stored (no datetimes, repeated timestamps, a non-numeric column, an empty table).

Return type:

StoredData

Example

>>> units = {"biogas_volume": "m3/day"}
>>> orch.store_data("biogas_data", df, units=units)
get_data(name=None, columns=None, start=None, end=None, *, column=None, frame=None)[source]

Read a dataset, or one column found across the study’s datasets.

Parameters:
  • name (str | None) – The dataset.

  • columns (list[str] | None) – Only these columns, in this order.

  • start (Any) – Only rows at or after this datetime (naive means UTC).

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

  • column (str | None) – Instead of name: a column name, looked up across the study’s datasets.

  • frame (Literal['polars', 'pandas'] | None) – "polars" or "pandas"; the orchestrator’s default if omitted.

Returns:

A polars DataFrame with a time column first, or a pandas DataFrame with a UTC DatetimeIndex.

Raises:
Return type:

Any

store_model_results(tag, model, outcome=None, keys=None, include=None, exclude=None, *, streams=None, replace=False, time_sets=None, datetime_index=None, spec=None, overrides=None)[source]

Export a model’s values and store them under tag.

Values are exported with export_model_data() and stored as one snapshot (a table of timeseries plus a JSON manifest). Keys named in streams are also stored as native Acquirium variables, for queries and fitting. Everything is checked before the run starts, so a value that can’t be stored leaves no run behind. If outcome isn’t ok, only the outcome is stored, in a failed run, so the tag can be used again.

Parameters:
  • tag (str) – The result’s tag, unique among the study’s results.

  • model (Any) – The model, passed explicitly (there is no current model).

  • outcome (SolveOutcome | None) – How the solve ended; stored as solve_outcome.

  • keys (Iterable[str] | None) – Exact paths to export (see export_model_data).

  • include (Iterable[str] | None) – Glob patterns to export.

  • exclude (Iterable[str] | None) – Glob patterns to leave out.

  • streams (Iterable[str] | None) – Keys, component paths or globs of exported values to also store natively (["costing.aggregate_electrical_power"]).

  • replace (bool) – Replace a stored result with this tag: the new one is written first, then the old one is deleted. A failed solve leaves the old result in place.

  • time_sets (Sequence[Any] | None) – The model’s time Sets. By default the time_sets hook gives them (for flex-pse models, including the partial-horizon Sets of startup/shutdown).

  • datetime_index (Sequence[Any] | None) – One datetime per time point, for models whose time block doesn’t have them.

  • spec (str | None) – The tag of the model spec the model was built from. A model from build() remembers its spec, so this is only needed for models built another way.

  • overrides (Mapping[str, Any] | None) – The build overrides used with spec.

Returns:

What was stored.

Raises:
Return type:

StoredResult

store_model_data(tag, data, outcome=None, *, streams=None, replace=False, spec=None, overrides=None, model_inputs=None)[source]

Store values that are already exported under tag.

store_model_results() is this after export_model_data(). Use it directly for values exported another way, e.g. from a model that isn’t Pyomo.

Parameters:
Returns:

What was stored.

Raises:
Return type:

StoredResult

solve_and_store(tag, model, keys=None, include=None, exclude=None, *, streams=None, replace=False, solve=None, time_sets=None, datetime_index=None, spec=None, overrides=None, **options)[source]

Solve a model and store its results under tag.

The tag is checked before solving, so a solve is never wasted on a tag that can’t be stored. A solve that raises or isn’t optimal is stored as a failed result holding only its outcome.

Parameters:
Returns:

What was stored, with the outcome.

Raises:
  • TagExistsError – If a result with this tag is running or succeeded (and replace is false).

  • SpecError – If tag isn’t a valid tag.

Return type:

StoredResult

model_results(tag, units=None)[source]

Read a stored result’s model values back from its snapshot.

Values come back as they were exported, with UTC timestamps, unless units asks for others.

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

  • units (Mapping[str, str] | None) – {key or component path: Pyomo unit} to convert to, with pint ({"costing.aggregate_electrical_power": "W"}).

Raises:
Return type:

ModelData

design_results(tag)[source]

Return the sizes and annualized costs of a stored design study.

Parameters:

tag (str) – The result’s tag.

Returns:

A DesignSummary.

Raises:
  • TagNotFoundError – If no succeeded result has this tag.

  • SpecError – If the result wasn’t built from a design study.

  • ExportError – If its export left out a value the summary needs.

Return type:

Any

result(tag)[source]

Return a handle on a stored result; nothing is read until asked for.

Raises:

TagNotFoundError – If no succeeded result has this tag.

Parameters:

tag (str)

Return type:

ResultHandle

Example

>>> orch.result("base").to_pandas()
stored_model_results(tags=None)[source]

Return handles on the study’s stored results, oldest first.

Parameters:

tags (Iterable[str] | None) – Only these tags.

Return type:

list[ResultHandle]

Example

>>> for r in orch.stored_model_results():
...     df = r.to_frame("polars")
run_command(name, params=None, /, *, progress=None, runtime=None, **fields)[source]

Run a command by name, recording the call in flexorch::commands.

Parameters:
  • name (str) – The command, e.g. "execute_study" or a plugin’s.

  • params (Any) – Its parameters, as a mapping or its params model.

  • progress (Progress | None) – Receives progress reports and can cancel the call.

  • runtime (Mapping[str, Any] | None) – Values JSON can’t carry (e.g. a build callable); not recorded, apart from the import strings of callables.

  • **fields (Any) – More parameters, merged over params.

Returns:

What the command returned.

Raises:

CommandError – If there is no such command or the parameters don’t validate.

Return type:

Any

Example

>>> orch.run_command("fit_surrogate", tag="ro", ...)
register_command(cmd)[source]

Add a command to this orchestrator (a plugin’s are added for you).

Raises:

CommandError – If its name is taken.

Parameters:

cmd (Command)

Return type:

Command

execute_study(config, *, build=None, solve=None, max_workers=None, ray_address=None, dry_run=False, progress=None)[source]

Run a study from a config: fits, then sweeps of build-solve-store tasks.

The execute_study command; see flexorchestrator.study.

Parameters:
  • config (Any) – A StudyConfig, its dict, or the path of a YAML or JSON file.

  • build (Any) – A build hook (callable, import string or registered name) that wins over the config’s.

  • solve (Any) – A solve hook that wins over the config’s.

  • max_workers (int | None) – Overrides execution.max_workers; more than 1 runs the tasks (and the fits’ variants) on Ray.

  • ray_address (str | None) – Overrides execution.ray_address.

  • dry_run (bool) – Expand the config and return the planned fits and tasks without storing or solving anything.

  • progress (Progress | None) – Receives a report after each fit and task.

Returns:

A StudyRun.

Raises:
  • StudyConfigError – If the config is invalid.

  • TagExistsError – With on_existing: error, if a task’s tag is already stored (checked before anything runs).

Return type:

Any

fit_surrogate(*, progress=None, **params)[source]

Fit surrogates from stored data and store them (fit_surrogate).

See FitParams for the parameters: tag, regressor, X, y and optionally variants, window, prep, validation, params, spec_options and on_existing.

Returns:

A FitSummary.

Parameters:
Return type:

Any

Example

>>> orch.fit_surrogate(
...     tag="ro_linear", regressor="multilinear",
...     X={"dataset": "ro", "columns": ["permeate"]},
...     y={"dataset": "ro", "columns": ["power_electrical"]},
... )
export_study(path, *, parts=('specs', 'data', 'fits', 'results'), tags=None, compress=False, overwrite=False)[source]

Export the selected study to a folder of JSON files.

See flexorchestrator.archive.export_study().

Parameters:
Return type:

Any

export_result(tag, path)[source]

Export one stored result to a JSON file.

See flexorchestrator.archive.export_result().

Parameters:
Return type:

Any

import_study(path, *, name=None, on_existing='error')[source]

Re-create an exported study in this store, and select it.

See flexorchestrator.archive.import_study().

Parameters:
Return type:

Any

build_hooks()[source]

Return the default hooks; the hooks given to __init__ win over them.

Override to change the defaults for every orchestrator of a subclass.

Return type:

HookSet

default_export_selection()[source]

Return the export selection used when a store names none.

{"keys": [...], "include": [...], "exclude": [...]}, any of them; {} (the default) exports everything.

Return type:

dict[str, Any]

before_store(item)[source]

Called before an item is stored; raise to refuse it.

Add to item.metadata to store more run metadata.

Parameters:

item (StoreItem)

Return type:

None

after_store(item)[source]

Called after an item is stored, with item.run_id set.

Parameters:

item (StoreItem)

Return type:

None

on_task_result(result)[source]

Called with each task’s TaskResult as a study runs.

Parameters:

result (Any)

Return type:

None

on_study_created(study)[source]

Called after create_study() creates a study.

Parameters:

study (str)

Return type:

None

on(event, fn=None)[source]

Register a listener for a lifecycle event; a decorator without fn.

See flexorchestrator.ext.events for the events.

Example

>>> @orch.on("result_stored")
... def log(item):
...     print(item.tag)
Parameters:
Return type:

Any

class flexorchestrator.StoredResult(tag, run_id, status, outcome=None, keys=<factory>, streams=<factory>)[source]

Bases: object

What Orchestrator.store_model_results() stored.

Parameters:
tag

The result’s tag.

Type:

str

run_id

The backend run.

Type:

str

status

"succeeded", or "failed" when the solve wasn’t ok (then only the solve outcome is stored, and the tag can be reused).

Type:

Literal[‘succeeded’, ‘failed’]

outcome

The solve outcome, if one was given.

Type:

flexorchestrator.hooks.SolveOutcome | None

keys

The exported keys stored in the snapshot.

Type:

list[str]

streams

The keys also stored as native variables.

Type:

list[str]

property ok: bool

Whether the result was stored with its model values.

class flexorchestrator.ResultHandle(tag, run_id, metadata, started_at, _orch, _loaded=None)[source]

Bases: ResultReads

A stored result, read lazily from its snapshot.

The snapshot is read the first time values are asked for, then kept.

Parameters:
tag

The result’s tag.

Type:

str

run_id

The backend run.

Type:

str

metadata

The run’s metadata (flexorch_tag, versions, …).

Type:

dict[str, Any]

started_at

When the run started (UTC).

Type:

Any

data(units=None)[source]

Return the values, converted to units if given.

Parameters:

units (Mapping[str, str] | None) – {key or component path: Pyomo unit}, as in Orchestrator.model_results().

Return type:

ModelData

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

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

polars gets a time column first, pandas a UTC index. Scalars are in scalars().

Parameters:
  • frame (Literal['polars', 'pandas'] | None) – "polars" or "pandas"; the orchestrator’s default if omitted.

  • units (Mapping[str, str] | None) – Units to convert to, as in data().

Return type:

Any

property spec_tag: str | None

The tag of the model spec the result was built from, if recorded.

property overrides: dict[str, Any]

The build overrides recorded with the spec ({} if none).

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

Where its model inputs came from, per entry; [] if none.

Each entry holds the entry as sent (input), what its selector resolved to (resolved: the dataset run, or the stream refs), the paths it set, the window read, the steps filled and the values’ data_hash. The values themselves are in overrides.

spec()[source]

Return the model spec the result was built from.

Raises:

TagNotFoundError – If no spec was recorded, or it was deleted.

Return type:

SpecRecord

property outcome: SolveOutcome | None

The solve outcome stored with the result, if any.

class flexorchestrator.orchestrator.StoreItem(kind, tag, metadata=<factory>, run_id=None)[source]

Bases: object

An item about to be stored, as before_store sees it.

See before_store().

Parameters:
kind

"result", "data", "model_spec", "surrogate_spec" or "fit".

Type:

str

tag

The item’s tag (a dataset’s name).

Type:

str

metadata

Extra run metadata; before_store may add to it. It can’t replace the orchestrator’s own keys.

Type:

dict[str, Any]

run_id

The run, once stored (in after_store and the events).

Type:

str | None

Specs

Model and surrogate specs as stored data.

A spec is any JSON object. Storing one as data, not as a live model, is what lets a run be replayed: the stored spec goes back through the build hook. This module is format-agnostic and imports neither pyomo nor flex-pse.

  • to_json_spec() turns a dict or pydantic model into a plain JSON dict.

  • spec_hash() is the sha256 of the spec’s canonical JSON. Two specs that differ only in key order, or in 1 versus 1.0, hash the same. The hash is how execute_study recognises runs it has already done, so the canonical form must never change.

  • detect_format() names the spec’s format; validate_spec() checks it with the format’s validator when that format’s library is installed.

  • SpecRecord is what a store call writes: the spec with its kind, tag, format, hash, parent and the files it references (flexorchestrator.assets).

flexorchestrator.specs.SpecKind

What a stored spec describes.

alias of Literal[‘model_spec’, ‘surrogate_spec’]

flexorchestrator.specs.FLEXPSE_FLOWSHEET = 'flex-pse.flowsheet'

Format family of a flex-pse flowsheet spec (a FlowsheetSpec).

Type:

str

flexorchestrator.specs.FLEXPSE_SURROGATE = 'flex-pse.surrogate'

Format family of a flex-pse SurrogateSpec.

Type:

str

flexorchestrator.specs.FLEXPSE_DESIGN = 'flex-pse.design'

Format of a flex-pse DesignSpec. It has no version part: a design spec’s schema_version is the version of that study, not of the format.

Type:

str

flexorchestrator.specs.GENERIC_JSON = 'json'

Format of any spec no validator knows.

Type:

str

flexorchestrator.specs.VALIDATORS: dict[str, tuple[str, str]] = {'flex-pse.design': ('flexdesign', 'flexorchestrator.flexpse:validate_design_spec'), 'flex-pse.flowsheet': ('flexops', 'flexorchestrator.flexpse:validate_model_spec'), 'flex-pse.surrogate': ('flexops', 'flexorchestrator.flexpse:validate_surrogate_spec')}

Format family -> (module that must be importable, validator import string). A validator takes the spec, raises SpecError if it is invalid, and returns it normalised: validated and dumped back to JSON, so defaults are written out and every way of building the same spec stores (and hashes) the same JSON.

Type:

dict

flexorchestrator.specs.to_json_spec(spec)[source]

Return spec as a plain JSON object, independent of the input.

Parameters:

spec (Any) – A mapping, or a pydantic model (dumped with mode="json").

Returns:

A new dict holding only JSON types. Tuples become lists and non-string keys become strings, as in any JSON round trip.

Raises:

SpecError – If spec isn’t a mapping or model, or holds a value JSON can’t represent (a set, an arbitrary object, NaN or infinity).

Return type:

dict[str, Any]

Example

>>> to_json_spec({"order": (0, 0, 1)})
{'order': [0, 0, 1]}
flexorchestrator.specs.canonical_json(spec)[source]

Return the canonical JSON text that spec_hash() hashes.

Keys are sorted, there is no whitespace, and a float with an integral value is written as an integer, so {"b": 1.0, "a": 2} and {"a": 2, "b": 1} give the same text. Only the hash uses this form; stored specs keep their values as given.

Parameters:

spec (Any) – Anything to_json_spec() accepts.

Returns:

The canonical text.

Raises:

SpecError – As to_json_spec().

Return type:

str

Example

>>> canonical_json({"b": 1.0, "a": [2, 0.5]})
'{"a":[2,0.5],"b":1}'
flexorchestrator.specs.spec_hash(spec)[source]

Return the sha256 hex digest of the spec’s canonical_json().

Parameters:

spec (Any) – Anything to_json_spec() accepts.

Returns:

64 lowercase hex characters.

Raises:

SpecError – As to_json_spec().

Return type:

str

Example

>>> spec_hash({"a": 1}) == spec_hash({"a": 1.0})
True
flexorchestrator.specs.run_hash(model_spec_hash, overrides=None)[source]

Return the hash that identifies one run: a spec plus its overrides.

execute_study compares it with the runs already stored to skip work that succeeded before.

Parameters:
  • model_spec_hash (str) – The spec_hash() of the model spec.

  • overrides (Mapping[str, Any] | None) – The run’s overrides; None is the same as {}.

Returns:

64 lowercase hex characters.

Return type:

str

Example

>>> run_hash("ab", {"x": 1}) == run_hash("ab", {"x": 1.0})
True
flexorchestrator.specs.record_hash(spec, assets=None)[source]

Return the hash of a stored spec and the files it references.

Without assets it is spec_hash() of the spec, unchanged. With assets it also covers each file’s sha256, so editing a referenced file (a tariff, say) changes the hash even though the spec text doesn’t.

Parameters:
  • spec (Any) – The stored spec JSON.

  • assets (Mapping[str, AssetRef] | None) – {JSON pointer: AssetRef} for each file it references.

Returns:

The hex sha256.

Return type:

str

Example

>>> record_hash({"a": 1}) == spec_hash({"a": 1})
True
flexorchestrator.specs.normalise_spec(kind, spec, spec_format=None, validate=True)[source]

Return a spec as stored JSON and its format, validated when possible.

Parameters:
  • kind (Literal['model_spec', 'surrogate_spec']) – What the spec describes: "model_spec" or "surrogate_spec".

  • spec (Any) – A mapping or pydantic model.

  • spec_format (str | None) – Its format; detected from the spec when omitted.

  • validate (bool) – Run the format’s validator, when its library is installed.

Returns:

(the stored JSON, the format).

Raises:

SpecError – If the spec isn’t JSON, its format belongs to the other kind, or validation fails.

Return type:

tuple[dict[str, Any], str]

flexorchestrator.specs.detect_format(spec)[source]

Name the format of a JSON spec from its shape.

Parameters:

spec (Mapping[str, Any]) – A JSON spec.

Returns:

"flex-pse.flowsheet/<schema_version>" for a flex-pse flowsheet, "flex-pse.surrogate" for a flex-pse surrogate spec, "flex-pse.design" for a flex-pse design study, otherwise "json".

Return type:

str

Example

>>> detect_format({"surrogate_type": "multilinear", "data": {}})
'flex-pse.surrogate'
flexorchestrator.specs.is_design_spec(spec)[source]

Whether a JSON spec is a flex-pse design study, from its shape.

Parameters:

spec (Mapping[str, Any])

Return type:

bool

flexorchestrator.specs.validate_spec(spec, spec_format)[source]

Check and normalise spec with its format’s validator, if available.

A format with no validator, or whose library isn’t installed, is accepted unchecked: specs are data, and the orchestrator doesn’t require flex-pse.

Parameters:
  • spec (dict[str, Any]) – A JSON spec.

  • spec_format (str) – Its format, e.g. "flex-pse.flowsheet/0.1.1". The part before / picks the validator.

Returns:

The normalised spec, or None if no validator ran.

Raises:

SpecError – If the validator rejects the spec.

Return type:

dict[str, Any] | None

flexorchestrator.specs.check_tag(tag)[source]

Check that tag can name a stored item.

Tags become Acquirium labels and the file names of a study export, so they are limited to letters, digits, _, . and -, start with a letter or digit, and are at most 128 characters.

Parameters:

tag (str) – The tag.

Returns:

tag.

Raises:

SpecError – If the tag isn’t valid.

Return type:

str

Example

>>> check_tag("model_with_surrogate_biogas_h1")
'model_with_surrogate_biogas_h1'
class flexorchestrator.specs.SpecRecord(*, kind, tag, spec, spec_format, spec_hash, parent_tag=None, assets=<factory>)[source]

Bases: BaseModel

A spec as stored: the data plus what identifies it.

This is the content of a <s>::specs run and of a study export’s spec file. Storage adds who stored it and when.

Parameters:
kind

"model_spec" or "surrogate_spec".

Type:

Literal[‘model_spec’, ‘surrogate_spec’]

tag

The tag, unique per kind within a study.

Type:

str

spec

The spec, as plain JSON.

Type:

dict[str, Any]

spec_format

See detect_format().

Type:

str

spec_hash

See record_hash(): the spec’s hash, covering its assets’ hashes when it has any.

Type:

str

parent_tag

The tag of the spec this one was derived from, e.g. the base model a surrogate was applied to.

Type:

str | None

assets

{JSON pointer: AssetRef} for each file the spec references; the spec holds each asset’s stored name at its pointer.

Type:

dict[str, flexorchestrator.assets.AssetRef]

Example

>>> record = SpecRecord.create("model_spec", "base", {"a": 1})
>>> record.spec_format, record.spec_hash == spec_hash({"a": 1})
('json', True)
model_config = {'extra': 'forbid', 'frozen': True}

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

classmethod create(kind, tag, spec, *, parent_tag=None, spec_format=None, validate=True, assets=None)[source]

Normalise, check and hash a spec for storing.

Parameters:
  • kind (Literal['model_spec', 'surrogate_spec']) – "model_spec" or "surrogate_spec".

  • tag (str) – The tag (see check_tag()).

  • spec (Any) – A mapping or pydantic model.

  • parent_tag (str | None) – The tag of the spec this one was derived from.

  • spec_format (str | None) – The format; detected from the spec when omitted.

  • validate (bool) – Run the format’s validator (see validate_spec()), which also normalises the spec: a flex-pse spec is stored with its defaults written out.

  • assets (Mapping[str, AssetRef] | None) – The files the spec references, already collected (see flexorchestrator.assets.collect_assets()).

Returns:

The record.

Raises:

SpecError – If the tag is invalid, the spec isn’t JSON, its format belongs to the other kind, or validation fails.

Return type:

SpecRecord

metadata()[source]

Return the run metadata stored with the spec.

Returns:

flexorch_kind, flexorch_tag, spec_hash, spec_format and, when set, parent_tag.

Return type:

dict[str, str]

verify()[source]

Check that spec_hash still matches spec.

Used when reading a record from storage or an export, to catch a spec that was edited without its hash.

Raises:

SpecError – If the hash doesn’t match.

Return type:

None

class flexorchestrator.specs.SpecRecordWithFiles(*, kind, tag, spec, spec_format, spec_hash, parent_tag=None, assets=<factory>, files=<factory>)[source]

Bases: SpecRecord

A stored spec with its files’ bytes, for a caller that has no folder.

What model_spec(tag, with_files=True) returns. files is {stored name: bytes}, the names the spec holds at its assets’ pointers; it isn’t part of the record’s JSON. Pass the spec and the files to store_model_spec(..., files=...) to store it again, unchanged.

Parameters:
files

{stored name: bytes} for every asset.

Type:

dict[str, bytes]

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

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