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:
objectStudies, 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 indata_dir(.flexorchby default);Orchestrator(db="postgresql://host/db", data_dir=...): a managed Acquirium on Postgres, with the login fromFLEXORCH_DB_PASSWORD_FILE,FLEXORCH_DB_USER/FLEXORCH_DB_PASSWORDor libpq’sPG*/~/.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),MemoryBackendorAcquiriumBackend. 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(fromenviron) 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 (seeconnect()).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()andreplace=Truemay delete anything. A deployment that must never lose a stored item turns this off.plugins (Sequence[Plugin | str] | None) – Plugins to load:
Pluginobjects or installed plugin names. Plugins named inFLEXORCH_PLUGINSload too. Usecreate_orchestrator()to get a plugin’s orchestrator subclass.environ (Mapping[str, str] | None) – Where
FLEXORCH_PLUGINS,FLEXORCH_RAY_ADDRESS,FLEXORCH_ACQUIRIUM_URLandFLEXORCH_START_ACQUIRIUMare read;os.environby default.ray_address (str | None) – The Ray cluster for studies with
max_workers > 1when their config names none;FLEXORCH_RAY_ADDRESSif unset, else local Ray.
- user¶
Who runs and stores are recorded as (
flexorch_user); ifNone,FLEXORCH_USERor 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_shutdownruns 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:
- 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 innamewhatever is selected onorchlater, or from another thread: it shares the connection, plugins, hooks and the per-study locks. Setuseron 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:
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.
- studies()[source]¶
Return the names of the orchestrator studies in the store, sorted.
The ledger studies (
<s>::runsand so on) aren’t listed.
- register_hooks(name, **hooks)[source]¶
Register a named set of hooks, e.g.
build=my_build.A
HookSetslot, orbuild(..., build="name"), can then refer to it by name. Seeregister().
- 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:
- 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
kindisn’t one of the kinds above.
- Return type:
- 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 changesspec_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 samespec_hash. A spec read back withmodel_spec()(tag, with_files=True)stores again unchanged with itsfiles. Not withbase_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
parentisn’t a stored model spec.SpecError – If the spec or its tag is invalid, a referenced file can’t be read, or
fileslacks one or has one the spec doesn’t reference.
- Return type:
- 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:
TagExistsError – If a surrogate spec with this tag is stored.
TagNotFoundError – If
parentisn’t a stored surrogate spec.SpecError – If the spec or its tag is invalid.
- Return type:
- model_spec(tag, *, with_files=False)[source]¶
Return a stored model spec, checked against its hash.
- Parameters:
tag (str) – The spec’s tag.
with_files (bool) – Also return its files’ bytes: a
SpecRecordWithFiles, whosefilesis{stored name: bytes}. For a caller with no folder tomaterialize_spec()into.
- Raises:
TagNotFoundError – If there is none with this tag.
- Return type:
- 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:
- 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
kindisn’t a spec kind.- Return type:
- 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).
- 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:
- Raises:
TagNotFoundError – If the spec isn’t stored.
SpecError – If
overridesaren’t JSON.
- Return type:
- 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_gridhook) and its variables fixed to it (theapply_valueshook). A model frombuild()remembers what was applied, so storing its results records the values (inoverrides) 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
ModelInputor a mapping in its shape (a fit selector, its columns renamed to the paths they set, plus how to line it up).
- Returns:
the
valuesfixed and theirprovenance.- 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:
ModelInputor mappings.
- Returns:
values(the build overrides) andprovenance.- Return type:
A
Resolved- Raises:
TagNotFoundError – If the spec isn’t stored.
ModelInputError – If an entry can’t be resolved.
- apply_surrogate(base, *, unit, surrogate, relation=None)[source]¶
Return a stored model spec with a stored surrogate applied to a unit.
Calls the
apply_surrogatehook; the result isn’t stored. Store it withstore_model_spec(tag, spec, parent=base), which reuses the base spec’s files.
- 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
replaceis false.SpecError – If
nameisn’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:
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
timecolumn first, or a pandas DataFrame with a UTCDatetimeIndex.- Raises:
TagNotFoundError – If the dataset, or a dataset with
column, doesn’t exist.AmbiguousColumnError – If
columnis in several datasets.
- Return type:
- 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 (atableof timeseries plus a JSON manifest). Keys named instreamsare 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. Ifoutcomeisn’tok, only the outcome is stored, in afailedrun, 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).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_setshook 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:
TagExistsError – If a result with this tag is running or succeeded (and
replaceis false).TagNotFoundError – If
specisn’t a stored model spec.SpecError – If
tagisn’t a valid tag.ExportError, StorageError, UnitError – If the values can’t be exported or stored.
- Return type:
- 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 afterexport_model_data(). Use it directly for values exported another way, e.g. from a model that isn’t Pyomo.- Parameters:
tag (str) – The result’s tag, unique among the study’s results.
data (ModelData) – The values.
outcome (SolveOutcome | None) – How the solve ended. If it isn’t
ok,datais ignored and only the outcome is stored, in afailedrun.streams (Iterable[str] | None) – Values to also store natively; see
store_model_results().replace (bool) – Replace a stored result; see
store_model_results().spec (str | None) – The model spec the values came from; see
store_model_results().overrides (Mapping[str, Any] | None) – The build overrides used with
spec.model_inputs (Sequence[Mapping[str, Any]] | None) – Where the model inputs among
overridescame from, recorded withspec.
- Returns:
What was stored.
- Raises:
TagExistsError – If a result with this tag is running or succeeded (and
replaceis false).SpecError – If
tagisn’t a valid tag.ExportError, StorageError, UnitError – If the values can’t be stored.
- Return type:
- 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
failedresult holding only its outcome.- Parameters:
tag (str) – The result’s tag.
model (Any) – The built model.
exclude (Iterable[str] | None) – Glob patterns to leave out.
streams (Iterable[str] | None) – Values to also store natively; see
store_model_results().replace (bool) – Replace a stored result; see
store_model_results().solve (Any) – The solve hook (a callable, import string or registered name); the orchestrator’s
solvehook by default.time_sets (Sequence[Any] | None) – See
store_model_results().datetime_index (Sequence[Any] | None) – See
store_model_results().spec (str | None) – See
store_model_results().overrides (Mapping[str, Any] | None) – See
store_model_results().**options (Any) – Passed to the solve hook.
- Returns:
What was stored, with the outcome.
- Raises:
TagExistsError – If a result with this tag is running or succeeded (and
replaceis false).SpecError – If
tagisn’t a valid tag.
- Return type:
- 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
unitsasks for others.- Parameters:
- Raises:
TagNotFoundError – If no succeeded result has this tag.
ExportError, UnitError – If
unitsnames a key that wasn’t stored, or a unit that doesn’t convert.
- Return type:
- design_results(tag)[source]¶
Return the sizes and annualized costs of a stored design study.
- Parameters:
tag (str) – The result’s tag.
- Returns:
- 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:
- 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:
Example
>>> orch.result("base").to_pandas()
- stored_model_results(tags=None)[source]¶
Return handles on the study’s stored results, oldest first.
- Parameters:
- Return type:
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
buildcallable); 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:
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:
- 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_studycommand; seeflexorchestrator.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:
- fit_surrogate(*, progress=None, **params)[source]¶
Fit surrogates from stored data and store them (
fit_surrogate).See
FitParamsfor the parameters:tag,regressor,X,yand optionallyvariants,window,prep,validation,params,spec_optionsandon_existing.- Returns:
A
FitSummary.- Parameters:
- Return type:
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.
- import_study(path, *, name=None, on_existing='error')[source]¶
Re-create an exported study in this store, and select it.
- 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:
- default_export_selection()[source]¶
Return the export selection used when a store names none.
{"keys": [...], "include": [...], "exclude": [...]}, any of them;{}(the default) exports everything.
- before_store(item)[source]¶
Called before an item is stored; raise to refuse it.
Add to
item.metadatato store more run metadata.- Parameters:
item (StoreItem)
- Return type:
None
- after_store(item)[source]¶
Called after an item is stored, with
item.run_idset.- Parameters:
item (StoreItem)
- Return type:
None
- on_task_result(result)[source]¶
Called with each task’s
TaskResultas 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
- class flexorchestrator.StoredResult(tag, run_id, status, outcome=None, keys=<factory>, streams=<factory>)[source]¶
Bases:
objectWhat
Orchestrator.store_model_results()stored.- Parameters:
- status¶
"succeeded", or"failed"when the solve wasn’tok(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:
- class flexorchestrator.ResultHandle(tag, run_id, metadata, started_at, _orch, _loaded=None)[source]¶
Bases:
ResultReadsA stored result, read lazily from its snapshot.
The snapshot is read the first time values are asked for, then kept.
- Parameters:
- started_at¶
When the run started (UTC).
- Type:
Any
- data(units=None)[source]¶
Return the values, converted to
unitsif given.- Parameters:
units (Mapping[str, str] | None) –
{key or component path: Pyomo unit}, as inOrchestrator.model_results().- Return type:
- to_frame(frame=None, units=None)[source]¶
Return the timeseries as one table, a column per key.
polars gets a
timecolumn first, pandas a UTC index. Scalars are inscalars().
- 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), thepathsit set, thewindowread, the stepsfilledand the values’data_hash. The values themselves are inoverrides.
- spec()[source]¶
Return the model spec the result was built from.
- Raises:
TagNotFoundError – If no spec was recorded, or it was deleted.
- Return type:
- 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:
objectAn item about to be stored, as
before_storesees it.See
before_store().- metadata¶
Extra run metadata;
before_storemay add to it. It can’t replace the orchestrator’s own keys.
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 in1versus1.0, hash the same. The hash is howexecute_studyrecognises 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.SpecRecordis 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:
- flexorchestrator.specs.FLEXPSE_SURROGATE = 'flex-pse.surrogate'¶
Format family of a flex-pse
SurrogateSpec.- Type:
- flexorchestrator.specs.FLEXPSE_DESIGN = 'flex-pse.design'¶
Format of a flex-pse
DesignSpec. It has no version part: a design spec’sschema_versionis the version of that study, not of the format.- Type:
- 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
SpecErrorif 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:
- flexorchestrator.specs.to_json_spec(spec)[source]¶
Return
specas 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
specisn’t a mapping or model, or holds a value JSON can’t represent (a set, an arbitrary object, NaN or infinity).- Return type:
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:
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:
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_studycompares 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;
Noneis the same as{}.
- Returns:
64 lowercase hex characters.
- Return type:
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:
- Returns:
The hex sha256.
- Return type:
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:
- flexorchestrator.specs.detect_format(spec)[source]¶
Name the format of a JSON spec from its shape.
- Parameters:
- 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:
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.
- flexorchestrator.specs.validate_spec(spec, spec_format)[source]¶
Check and normalise
specwith 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:
- Returns:
The normalised spec, or
Noneif no validator ran.- Raises:
SpecError – If the validator rejects the spec.
- Return type:
- flexorchestrator.specs.check_tag(tag)[source]¶
Check that
tagcan 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:
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:
BaseModelA spec as stored: the data plus what identifies it.
This is the content of a
<s>::specsrun 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’]
- spec_format¶
See
detect_format().- Type:
- spec_hash¶
See
record_hash(): the spec’s hash, covering its assets’ hashes when it has any.- Type:
- 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:
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:
- class flexorchestrator.specs.SpecRecordWithFiles(*, kind, tag, spec, spec_format, spec_hash, parent_tag=None, assets=<factory>, files=<factory>)[source]¶
Bases:
SpecRecordA stored spec with its files’ bytes, for a caller that has no folder.
What
model_spec(tag, with_files=True)returns.filesis{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 tostore_model_spec(..., files=...)to store it again, unchanged.- Parameters:
- model_config = {'extra': 'forbid', 'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].