Extending

See Hooks, commands and plugins for an overview.

Hooks

User-replaceable build and solve steps.

The orchestrator manages storage and runs; it never requires flex-pse to build or solve a model. A run is build(spec, **overrides) followed by solve(model, **options), and both steps are hooks: plain callables that follow BuildFn and SolveFn. Two optional hooks change the surrogate a unit uses, either in the spec before building (ApplySurrogateFn) or on a live model (SwapSurrogateFn), one sets a configuration option in a spec (ConfigureFn), and one names a built model’s time Sets for the exporter (TimeSetsFn).

A hook can be given three ways, and a HookSet slot accepts any of them:

  1. a callable;

  2. a name registered with HookRegistry.register() ("my_model"), which picks that set’s hook of the same kind;

  3. an import string, "package.module:function". Ray workers and the HTTP API need this form, because they can’t receive a callable.

The flex-pse defaults are DEFAULT_HOOKS. They are import strings, so this module doesn’t import flex-pse (or pyomo) and works without it.

flexorchestrator.hooks.SolveStatus

How a solve ended. "ok" (optimal), "failed" (the solver finished without an optimal solution) or "error" (the solve raised).

alias of Literal[‘ok’, ‘failed’, ‘error’]

class flexorchestrator.hooks.SolveOutcome(*, status, termination=None, message=None, wall_time=None, solver=None, log=None)[source]

Bases: BaseModel

The result of one solve, as stored with its run.

Parameters:
  • status (Literal['ok', 'failed', 'error'])

  • termination (str | None)

  • message (str | None)

  • wall_time (float | None)

  • solver (str | None)

  • log (str | None)

status

"ok", "failed" or "error" (see SolveStatus).

Type:

Literal[‘ok’, ‘failed’, ‘error’]

termination

The solver’s termination condition, e.g. "optimal" or "infeasible"; None when the solve raised.

Type:

str | None

message

A human-readable message from the solver or the exception.

Type:

str | None

wall_time

Seconds the solve took. run_solve() fills it in when the hook leaves it unset.

Type:

float | None

solver

The solver’s name, e.g. "highs".

Type:

str | None

log

Solver output or the traceback of a solve that raised.

Type:

str | None

Example

>>> outcome = SolveOutcome(status="ok", termination="optimal")
>>> outcome.ok
True
model_config = {'frozen': True}

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

property ok: bool

Whether the solve found an optimal solution.

classmethod from_stored(stored)[source]

Return the outcome a run stored (its JSON), or None if there is none.

The stored ok is dropped: it is computed from status.

Example

>>> stored = SolveOutcome(status="ok").model_dump(mode="json")
>>> SolveOutcome.from_stored(stored).ok
True
Parameters:

stored (Mapping[str, Any] | None)

Return type:

SolveOutcome | None

class flexorchestrator.hooks.BuildFn(*args, **kwargs)[source]

Bases: Protocol

Builds a model from a stored spec.

Example

>>> def build(spec: dict, **overrides) -> dict:
...     return {**spec, **overrides}
class flexorchestrator.hooks.SolveFn(*args, **kwargs)[source]

Bases: Protocol

Solves a built model.

Example

>>> def solve(model, **options) -> SolveOutcome:
...     return SolveOutcome(status="ok", termination="optimal")
class flexorchestrator.hooks.ApplySurrogateFn(*args, **kwargs)[source]

Bases: Protocol

Puts a surrogate into a spec, so the next build uses it.

Example

>>> def apply_surrogate(spec, unit, surrogate_spec, relation=None) -> dict:
...     return {**spec, "surrogates": {unit: surrogate_spec}}
class flexorchestrator.hooks.SwapSurrogateFn(*args, **kwargs)[source]

Bases: Protocol

Swaps a surrogate into a model that is already built.

Example

>>> def swap_surrogate(model, unit, surrogate_spec, relation=None) -> None:
...     model.surrogates[unit] = surrogate_spec
class flexorchestrator.hooks.ConfigureFn(*args, **kwargs)[source]

Bases: Protocol

Sets one configuration option in a spec, so the next build uses it.

Example

>>> def configure(spec, path, value) -> dict:
...     return {**spec, path: value}
class flexorchestrator.hooks.TimeSetsFn(*args, **kwargs)[source]

Bases: Protocol

Names a built model’s time Sets, for the exporter.

Example

>>> def time_sets(model) -> list:
...     return [model.t]
class flexorchestrator.hooks.TimeGridFn(*args, **kwargs)[source]

Bases: Protocol

Gives a model’s time axis, so stored data can be aligned to it.

Example

>>> import pandas as pd
>>> def time_grid(spec_or_model):
...     return pd.date_range("2025-07-08", periods=24, freq="1h")
class flexorchestrator.hooks.ApplyValuesFn(*args, **kwargs)[source]

Bases: Protocol

Fixes variables of a built model to values.

orch.apply_model_inputs uses it to set stored data on a model that is already built.

Example

>>> def apply_values(model, values) -> None:
...     for path, value in values.items():
...         model.find_component(path).fix(value)
flexorchestrator.hooks.HookRef

A hook as given by a user: a callable, an import string or a registered name.

class flexorchestrator.hooks.HookSet(build=None, solve=None, apply_surrogate=None, swap_surrogate=None, time_sets=None, configure=None, time_grid=None, apply_values=None)[source]

Bases: object

The hooks for a run, one slot per kind in HOOK_KINDS.

Each slot holds a callable, an import string, a registered name, or None (not set). HookRegistry.resolve() turns every slot into a callable.

Parameters:
  • build (Any)

  • solve (Any)

  • apply_surrogate (Any)

  • swap_surrogate (Any)

  • time_sets (Any)

  • configure (Any)

  • time_grid (Any)

  • apply_values (Any)

build

The BuildFn.

Type:

Any

solve

The SolveFn.

Type:

Any

apply_surrogate

The optional ApplySurrogateFn.

Type:

Any

swap_surrogate

The optional SwapSurrogateFn.

Type:

Any

time_sets

The optional TimeSetsFn.

Type:

Any

configure

The optional ConfigureFn.

Type:

Any

time_grid

The optional TimeGridFn.

Type:

Any

apply_values

The optional ApplyValuesFn.

Type:

Any

Example

>>> hooks = DEFAULT_HOOKS.merged(HookSet(build="mypkg.models:build"))
>>> hooks.build
'mypkg.models:build'
merged(other)[source]

Return these hooks with every slot other sets taking precedence.

This is how the precedence call arguments > study config > orchestrator defaults is applied: defaults.merged(config).merged(arguments).

Parameters:

other (HookSet) – The hooks that win where they are set.

Returns:

The combined hooks.

Return type:

HookSet

slots()[source]

Return {kind: hook} for every slot, set or not.

Return type:

dict[str, Any]

to_refs()[source]

Return every set slot as an import string.

For callers that need portable hooks, which a Ray worker or another process can import. Resolve registered names first, with HookRegistry.resolve().

Returns:

{kind: "package.module:function"} for every slot that is set.

Raises:

HookError – If a slot holds a callable that can’t be imported back (a lambda, a closure, or a function defined in __main__), or a registered name.

Return type:

dict[str, str]

Example

>>> DEFAULT_HOOKS.to_refs()["build"]
'flexorchestrator.flexpse:build'
flexorchestrator.hooks.HOOK_KINDS = ('build', 'solve', 'apply_surrogate', 'swap_surrogate', 'time_sets', 'configure', 'time_grid', 'apply_values')

The hook slots a HookSet has: build, solve, apply_surrogate, swap_surrogate, time_sets, configure, time_grid and apply_values.

Type:

tuple[str, …]

flexorchestrator.hooks.DEFAULT_HOOKS = HookSet(build='flexorchestrator.flexpse:build', solve='flexorchestrator.flexpse:solve', apply_surrogate='flexorchestrator.flexpse:apply_surrogate', swap_surrogate='flexorchestrator.flexpse:swap_surrogate', time_sets='flexorchestrator.flexpse:time_sets', configure='flexorchestrator.flexpse:configure', time_grid='flexorchestrator.flexpse:time_grid', apply_values='flexorchestrator.flexpse:apply_values')

The flex-pse hooks, used when nothing else is configured.

Type:

HookSet

flexorchestrator.hooks.import_hook(ref)[source]

Import the callable an import string names.

Parameters:

ref (str) – "package.module:attribute"; the attribute may be dotted ("package.module:Class.method").

Returns:

The callable.

Raises:

HookError – If ref is malformed, the module can’t be imported, the attribute doesn’t exist, or it isn’t callable.

Return type:

Any

Example

>>> import_hook("flexorchestrator.testing:fake_build").__name__
'fake_build'
flexorchestrator.hooks.hook_ref(fn)[source]

Return the import string that resolves back to fn, if there is one.

Parameters:

fn (Any) – A callable.

Returns:

"module:qualname", or None when importing that string wouldn’t give back fn (lambdas, closures, bound methods, functions defined in __main__).

Return type:

str | None

Example

>>> from flexorchestrator.testing import fake_build
>>> hook_ref(fake_build)
'flexorchestrator.testing.hooks:fake_build'
class flexorchestrator.hooks.HookRegistry[source]

Bases: object

Named hook sets, and resolution of any HookSet to callables.

Example

>>> registry = HookRegistry()
>>> _ = registry.register(
...     "fake",
...     build="flexorchestrator.testing:fake_build",
...     solve="flexorchestrator.testing:fake_solve",
... )
>>> registry.resolve(HookSet(build="fake")).build.__name__
'fake_build'
register(name, *, build=None, solve=None, apply_surrogate=None, swap_surrogate=None, time_sets=None, configure=None, time_grid=None, apply_values=None, replace=False)[source]

Register a named set of hooks.

Parameters:
  • name (str) – The name a HookSet slot or a study config uses to refer to this set. Must not contain ":".

  • build (Any) – A callable or import string.

  • solve (Any) – A callable or import string.

  • apply_surrogate (Any) – A callable or import string.

  • swap_surrogate (Any) – A callable or import string.

  • time_sets (Any) – A callable or import string.

  • configure (Any) – A callable or import string.

  • time_grid (Any) – A callable or import string.

  • apply_values (Any) – A callable or import string.

  • replace (bool) – Allow replacing a set already registered under name.

Returns:

The registered set.

Raises:

HookError – If name is empty, contains ":" or is already registered (without replace), or a hook is neither a callable nor an import string.

Return type:

HookSet

names()[source]

Return the registered names, sorted.

Return type:

list[str]

resolve_ref(ref, kind)[source]

Resolve one hook to a callable.

Parameters:
  • ref (Any) – A callable, an import string or a registered name.

  • kind (str) – Which slot this is for (one of HOOK_KINDS); picks the hook out of a registered set.

Returns:

The callable.

Raises:

HookError – If kind is unknown, the name isn’t registered, its set has no hook of this kind, or an import string fails.

Return type:

Any

resolve(hooks)[source]

Resolve every set slot of hooks to a callable.

Parameters:

hooks (HookSet) – The hooks to resolve.

Returns:

A HookSet holding callables (unset slots stay None).

Raises:

HookError – If any slot fails to resolve (see resolve_ref()).

Return type:

HookSet

flexorchestrator.hooks.run_solve(solve, model, **options)[source]

Call a solve hook and always come back with a SolveOutcome.

An exception from the hook becomes an "error" outcome carrying the traceback, so one failed solve doesn’t end a sweep. wall_time is filled in when the hook didn’t set it.

Parameters:
  • solve (SolveFn) – The resolved solve hook.

  • model (Any) – The built model.

  • **options (Any) – Passed to the hook.

Returns:

The hook’s outcome, or an "error" outcome if it raised.

Raises:

HookError – If the hook returns something other than a SolveOutcome (a bug in the hook, not a failed solve).

Return type:

SolveOutcome

Example

>>> from flexorchestrator.testing import fake_solve
>>> run_solve(fake_solve, model=None).status
'ok'

The flex-pse hooks

The default hooks, built on flex-pse 0.3.

This is the only package that imports flex-pse. Nothing else imports it directly: DEFAULT_HOOKS refers to these functions by import string, so the rest of the library works without flex-pse installed. Specs are flex-pse flowsheet specs (schema 0.1.1; older specs migrate on load).

flexorchestrator.flexpse.apply_surrogate(spec, unit, surrogate_spec, relation=None)[source]

Return a copy of spec in which unit uses surrogate_spec.

Adds a surrogate element, replacing any the spec already has for the same unit and relation. Storing the edited spec lets the run be replayed without the live model.

Parameters:
  • spec (dict) – A FlowsheetSpec as JSON, or a DesignSpec, whose base is edited. Not modified.

  • unit (str) – The unit’s element name, e.g. "demo.digester".

  • surrogate_spec (dict) – A SurrogateSpec as JSON (surrogate_type, data, optional provenance).

  • relation (str | None) – The unit’s relation to replace, e.g. "biogas_relation". None means flex-pse’s default, DEFAULT_RELATION.

Returns:

The new spec.

Raises:

SpecError – If unit isn’t a unit of the spec, or surrogate_spec is invalid.

Return type:

dict

Example

>>> spec = apply_surrogate(
...     spec, "demo.digester", arima_spec, relation="biogas_relation"
... )
flexorchestrator.flexpse.apply_values(model, values)[source]

Fix variables of a built flex-pse model, as fix elements would.

The values are checked against the variables’ bounds and applied together, all or nothing (flexops.apply_spec()). A later apply of a point replaces an earlier one.

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

  • values (Mapping[str, Any]) – {variable path: value}, as with_overrides() takes them. A costing field (a price) can’t be set on a built model; set it before building, as a configuration option.

Raises:
  • flexcore.exceptions.FlexConfigError – If a path names no variable, or a value doesn’t fit it.

  • SpecError – If model is a merged design model, which has several time blocks; set values per horizon with the design’s changes.

Return type:

None

flexorchestrator.flexpse.build(spec, **overrides)[source]

Build a flex-pse model from a stored flowsheet spec.

The overrides are added to the spec as fix elements (with_overrides()), then flexops.build_model() validates and builds it, arcs expanded.

Relative paths in the spec (tariff_source, $source files) resolve against the working directory of the process that builds, which on Ray is the worker’s.

Parameters:
  • spec (dict) – A FlowsheetSpec as JSON (schema 0.1.1; older specs migrate on load), or a DesignSpec, which build_design() builds.

  • **overrides (Any) – Values to fix, keyed by variable path from the model root (see with_overrides()).

Returns:

The model, ready to solve.

Raises:

flexcore.exceptions.FlexConfigError – If the spec is invalid or an override names no variable; the message names the offending field.

Return type:

ConcreteModel

Example

>>> model = build(spec, **{"demo.pump.flow_in": 10.0})
flexorchestrator.flexpse.build_design(spec, **overrides)[source]

Build the merged model of a design study.

Parameters:
  • spec (dict) – A DesignSpec as JSON.

  • **overrides (Any) – Values to fix in every horizon, as build() takes them, except that each must be one value, since horizons differ in length.

Returns:

The merged model, ready to solve.

Raises:

SpecError – If an override names a capacity’s variable, which the study decides (fix its size with the capacity’s lower and upper), or gives a value per time point.

Return type:

ConcreteModel

flexorchestrator.flexpse.configure(spec, path, value)[source]

Return a copy of spec with one configuration option set.

path is an element’s name followed by the option: the element is the one whose name is the longest leading part of path, so this works for any unit or block, however deeply named ("plant.train_1.ro.recovery"). A unit’s options are its construction_options; any other element’s are its own fields ("costing.energy_prices.electrical", "properties.options.default_temperature").

Dict-valued options can be set whole or one key at a time: the value {"value": 200, "units": "m^3/hr"} at "plant.feed.max_withdrawal" replaces the option, and 200 at "plant.feed.max_withdrawal.value" changes only its number. Missing dicts on the way are created, so an option the spec leaves at its default can be set too. The option isn’t checked here; flex-pse validates the spec when it’s stored or built.

In a design study, capacities.<name>.<field> sets a field of that capacity ("capacities.battery_energy.capital_cost"), and any other path is an option of the base flowsheet.

Parameters:
  • spec (dict) – A FlowsheetSpec or DesignSpec as JSON. Not modified.

  • path (str) – The element’s name, then the option’s dotted path within it.

  • value (Any) – The new value: a number, a string, a list or a dict.

Returns:

The new spec.

Raises:

SpecError – If no element’s name starts path, path names only an element, or a part of the path on the way isn’t a dict.

Return type:

dict

Example

>>> configure(spec, "plant.feed.max_withdrawal.value", 200)
flexorchestrator.flexpse.get_regressor(name)[source]

Return the flex-pse regressor class for a SurrogateType name.

Parameters:

name (str) – A flex-pse SurrogateType, e.g. "multilinear".

Returns:

The regressor class.

Raises:
  • NotImplementedError – If the installed flex-pse reserves the type but doesn’t fit it yet; the message names the installed version.

  • FitError – If name isn’t a surrogate type.

Return type:

type

Example

>>> get_regressor("multilinear").__name__
'LinearRegressor'
flexorchestrator.flexpse.predict_surrogate(spec, X)[source]

Evaluate a multilinear or constant_intensity surrogate spec on X.

multilinear is its intercept plus each coefficient times its term, a *-separated product of input columns; constant_intensity is its coefficient times the one input. Values are in the units the spec was fitted in, which are X’s.

Parameters:
  • spec (dict[str, Any]) – The surrogate spec as JSON (surrogate_type and data).

  • X (DataFrame) – The inputs, a column per input variable.

Returns:

One predicted value per row of X.

Raises:

FitError – For another surrogate type, a term X doesn’t have, or a constant_intensity spec without exactly one coefficient and one input column.

Return type:

list[float]

flexorchestrator.flexpse.solve(model, *, prefer=None, **options)[source]

Solve a model with the best available solver.

Parameters:
  • model (Block) – The built model.

  • prefer (str | None) – A solver name to try first (see flexcore.solvers.get_solver()). None uses the spec’s solver field when the model was built from one.

  • **options (Any) – Passed to flexcore.solvers.SolverFacade.solve(): tee, warmstart, mip_gap, time_limit and options.

Returns:

"ok" when the termination is optimal, "failed" otherwise.

Raises:

flexcore.exceptions.FlexSolverError – If no installed solver can solve the model. run_solve() records this as an "error" outcome.

Return type:

SolveOutcome

Example

>>> outcome = solve(model, prefer="highs")
flexorchestrator.flexpse.swap_surrogate(model, unit, surrogate_spec, relation=None)[source]

Swap surrogate_spec into a built model, in place.

The old relation is deactivated, not deleted, and the surrogate reuses the unit’s variables, so arcs are kept.

Parameters:
  • model (Block) – The built model.

  • unit (str) – The unit’s element name, e.g. "demo.digester".

  • surrogate_spec (dict) – A SurrogateSpec as JSON.

  • relation (str | None) – The relation to replace; None means DEFAULT_RELATION.

Raises:
  • SpecError – If surrogate_spec is invalid, or model is a merged design model.

  • flexcore.exceptions.FlexConfigError – If the model has no such unit or relation.

Return type:

None

Example

>>> swap_surrogate(
...     model, "demo.digester", arima_spec, relation="biogas_relation"
... )
flexorchestrator.flexpse.time_grid(spec_or_model)[source]

Return the time points of a flex-pse spec’s time element, or a model’s.

For a spec, the points flexops builds the model’s time block on: from start_date (inclusive) to end_date (exclusive) every time_step, in naive local time. For a built model, its time block’s.

Parameters:

spec_or_model (Any) – A FlowsheetSpec as JSON, or a built model. Not modified.

Returns:

The points; None if there’s no time axis.

Raises:

SpecError – If there are two time axes, or the dates or step don’t make a whole number of steps.

Return type:

DatetimeIndex | None

Example

>>> time_grid(spec)[:2]
DatetimeIndex(['2025-07-08 00:00:00', '2025-07-08 01:00:00'], ...)
flexorchestrator.flexpse.time_sets(model)[source]

Return a flex-pse model’s time Sets, for the exporter.

The TimeBlock’s time_index comes first. After it come the index Sets of every unit’s startup / shutdown Vars, found on the units themselves and so registered by identity. A Set that merely holds time-like integers, such as a set element [0, 1, 2] indexing RO trains, is never included.

Parameters:

model (Block) – A built flex-pse model.

Return type:

list[Set]

A merged design model has one TimeBlock per horizon: each horizon’s Sets follow in turn, its time_index first.

Returns:

The time Sets, main one first, or [] if the model doesn’t have exactly one TimeBlock (a user’s own model, say). The exporter then finds time itself, and reports several TimeBlocks as ambiguous.

Parameters:

model (Block)

Return type:

list[Set]

Example

>>> export_model_data(model, time_sets=time_sets(model))
flexorchestrator.flexpse.validate_design_spec(spec)[source]

Check a design spec with flex-pse, and normalise it.

Parameters:

spec (dict) – A DesignSpec as JSON, with base inline.

Returns:

The validated spec as JSON, with defaults written out and an older base schema migrated.

Raises:

SpecError – If flex-pse rejects it; the message names the bad field.

Return type:

dict

flexorchestrator.flexpse.validate_model_spec(spec)[source]

Check a flowsheet spec with flex-pse’s own loader, and normalise it.

Parameters:

spec (dict) – A FlowsheetSpec as JSON.

Returns:

The validated spec as JSON, with defaults written out and any older schema migrated by flex-pse. Fields are written under their aliases ({"$source": ...}), the form flex-pse itself writes.

Raises:

SpecError – If flex-pse rejects it; the message names the bad field.

Return type:

dict

flexorchestrator.flexpse.validate_surrogate_spec(spec)[source]

Check a surrogate spec against flex-pse’s SurrogateSpec and normalise it.

Parameters:

spec (dict) – A SurrogateSpec as JSON.

Returns:

The validated spec as JSON, with defaults written out.

Raises:

SpecError – If it doesn’t validate.

Return type:

dict

flexorchestrator.flexpse.with_overrides(spec, overrides)[source]

Return a copy of spec with one fix element per override.

A path whose first part names a costing element and whose next part is one of its fields ("costing.energy_prices.electrical") edits that field instead: that’s how a price is swept.

Parameters:
  • spec (dict) – A FlowsheetSpec as JSON. Not modified.

  • overrides (Mapping[str, Any]) – {variable path: value}. The path is a Pyomo ComponentUID path from the model root ("demo.pump.flow_in", "demo.pump.flow_in[3]", "demo.ro[*].status"). The value is anything a fix element takes: a number in the variable’s own units, {"value": ..., "units": ...}, a list with one number per time point, or a {time index: value} mapping.

Returns:

The new spec. Its fix elements are named "override:<path>".

Return type:

dict

Example

>>> with_overrides(spec, {"demo.pump.flow_in": 10.0})
flexorchestrator.flexpse.surrogate.DEFAULT_RELATION

The relation a surrogate replaces when none is given ("power_electrical_relation").

Type:

str

Commands, plugins and events

The extension API: commands, plugins and lifecycle events.

  • command() makes a function a Command, callable from Python (orch.run_command), the CLI (flex-orch cmd) and a host app’s HTTP API.

  • A Plugin bundles commands, named hooks, listeners and an orchestrator subclass; create_orchestrator() builds an orchestrator with the enabled plugins.

  • An Orchestrator subclass may override the stable methods build_hooks, default_export_selection, before_store, after_store, on_task_result and on_study_created.

class flexorchestrator.ext.Command(name, fn, params_model, role='editor', long_running=False, description='')[source]

Bases: object

A registered command.

Parameters:
name

The command’s unique name.

Type:

str

fn

fn(orch, params, progress, **runtime) -> result.

Type:

collections.abc.Callable[[…], Any]

params_model

The pydantic model its parameters are checked against.

Type:

type[pydantic.main.BaseModel]

role

The least role that may run it over HTTP.

Type:

Literal[‘viewer’, ‘editor’, ‘owner’]

long_running

Whether HTTP sends it through a job queue.

Type:

bool

description

One line for --help and the OpenAPI schema; the first line of the function’s docstring by default.

Type:

str

call(orch, params, progress, **runtime)[source]

Call the function with the arguments it takes.

fn(orch), fn(orch, params) and fn(orch, params, progress) are all commands; runtime values go in as keywords.

Parameters:
Return type:

Any

validate(params=None, **fields)[source]

Return params (a mapping or model) and fields as the params model.

Raises:

CommandError – If they don’t validate; the message lists each field.

Parameters:
Return type:

BaseModel

class flexorchestrator.ext.CommandRegistry[source]

Bases: object

Commands by name, with where each came from.

Example

>>> registry = CommandRegistry()
>>> @command()
... def ping(orch) -> str:
...     return "pong"
>>> registry.register(ping).name
'ping'
register(cmd, *, source='user')[source]

Register a command.

Parameters:
  • cmd (Command) – The command.

  • source (str) – Where it comes from ("builtin", "plugin:<name>", "user"), named in collision errors.

Raises:

CommandError – If the name is taken.

Return type:

Command

get(name)[source]

Return a command by name.

Raises:

CommandError – If there is none.

Parameters:

name (str)

Return type:

Command

source(name)[source]

Return where a command came from.

Parameters:

name (str)

Return type:

str

names()[source]

Return the registered names, sorted.

Return type:

list[str]

class flexorchestrator.ext.EventBus[source]

Bases: object

Listeners per event.

Example

>>> bus = EventBus()
>>> seen = []
>>> @bus.on("study_created")
... def remember(study):
...     seen.append(study)
>>> bus.emit("study_created", study="a")
>>> seen
['a']
on(event, fn=None)[source]

Register fn for event; without fn, return a decorator.

Raises:

PluginError – If event isn’t one of EVENTS.

Parameters:
Return type:

Callable[[…], Any]

emit(event, **payload)[source]

Call every listener of event with payload, in order.

Parameters:
Return type:

None

class flexorchestrator.ext.NoParams[source]

Bases: BaseModel

The params model of a command that takes no parameters.

model_config = {}

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

class flexorchestrator.ext.Plugin(name, api_version='>=1, <2', commands=(), hooks=<factory>, orchestrator_cls=None, routers=(), on_startup=None, on_shutdown=None, on_events=<factory>)[source]

Bases: object

What a plugin provides.

Parameters:
name

The plugin’s name, as listed in FLEXORCH_PLUGINS.

Type:

str

api_version

The PLUGIN_API_VERSION range it supports, e.g. ">=1,<2".

Type:

str

commands

Commands it adds.

Type:

collections.abc.Sequence[flexorchestrator.ext.commands.Command]

hooks

Named hooks: {name: import string} registers that hook for every slot, {name: {"build": ..., "solve": ...}} registers a set.

Type:

collections.abc.Mapping[str, str | collections.abc.Mapping[str, str]]

orchestrator_cls

An Orchestrator subclass; create_orchestrator() builds it.

Type:

type | None

routers

FastAPI routers, for a host app to mount at /ext/<name>; the library keeps them and doesn’t import FastAPI.

Type:

collections.abc.Sequence[Any]

on_startup

Called with the orchestrator once it is set up.

Type:

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

on_shutdown

Called with the orchestrator when it closes.

Type:

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

on_events

{event: listener or [listeners]} (see flexorchestrator.ext.events).

Type:

collections.abc.Mapping[str, collections.abc.Callable[[…], Any] | collections.abc.Sequence[collections.abc.Callable[[…], Any]]]

class flexorchestrator.ext.Progress(callback=None)[source]

Bases: object

Progress reports and cancellation for one command call.

A command calls update() as it goes and check() between steps; whoever runs it (a caller, the CLI, a host app’s job queue) reads snapshot() and may cancel() it.

Parameters:

callback (Callable[[dict[str, Any]], None] | None) – Called with snapshot() after every update.

Example

>>> progress = Progress()
>>> progress.update(total=2, message="fitting")
>>> progress.advance()
>>> progress.snapshot()["done"]
1
update(done=None, total=None, message=None)[source]

Set how much is done, of how much, and what is happening.

Parameters:
  • done (int | None)

  • total (int | None)

  • message (str | None)

Return type:

None

advance(steps=1, message=None)[source]

Count steps more as done.

Parameters:
  • steps (int)

  • message (str | None)

Return type:

None

cancel()[source]

Ask the command to stop at its next check().

Return type:

None

child()[source]

Return a Progress with its own counts that shares this one’s cancel.

For a step that reports its own progress, such as the fits a study runs first: cancelling either cancels both.

Example

>>> parent = Progress()
>>> step = parent.child()
>>> parent.cancel()
>>> step.cancelled
True
Return type:

Progress

property cancelled: bool

Whether cancel() was called.

check()[source]

Raise CommandCancelled if cancelled.

Return type:

None

snapshot()[source]

Return {done, total, message, cancelled}.

Return type:

dict[str, Any]

flexorchestrator.ext.command(name=None, *, role='editor', long_running=False, params=None, description=None)[source]

Make a function a Command.

Parameters:
  • name (str | None) – The command’s name; the function’s name by default.

  • role (Literal['viewer', 'editor', 'owner']) – The least role that may run it over HTTP.

  • long_running (bool) – Whether HTTP sends it through a job queue.

  • params (type[BaseModel] | None) – The params model; by default the annotation of the function’s second parameter, or NoParams if it has none.

  • description (str | None) – One line of help; the docstring’s first line by default.

Returns:

A decorator that returns the Command.

Return type:

Callable[[Callable[[…], Any]], Command]

Example

>>> from pydantic import BaseModel
>>> class Echo(BaseModel):
...     text: str
>>> @command()
... def echo(orch, params: Echo, progress) -> dict:
...     return {"text": params.text}
>>> echo.name, echo.params_model.__name__
('echo', 'Echo')
flexorchestrator.ext.create_orchestrator(*args, plugins=None, **kwargs)[source]

Build an orchestrator with the enabled plugins, as their subclass if one has it.

The plugins are the ones passed plus those in FLEXORCH_PLUGINS. A plugin’s orchestrator_cls is the class built; otherwise Orchestrator.

Parameters:
  • *args (Any) – Passed to the orchestrator (e.g. a backend).

  • plugins (Any) – Plugin objects or installed plugin names.

  • **kwargs (Any) – Passed to the orchestrator; environ (os.environ by default) is where FLEXORCH_PLUGINS and FLEXORCH_RAY_ADDRESS are read.

Returns:

The orchestrator.

Raises:

PluginError – If a plugin can’t be loaded (see load_plugins()).

Return type:

Any

flexorchestrator.ext.installed_plugins()[source]

Return the names of the plugins installed, loaded or not, sorted.

Return type:

list[str]

flexorchestrator.ext.load_plugins(plugins=None, *, environ=None, builtin_commands=())[source]

Return the plugins to load: those passed, plus those in the allowlist.

Parameters:
  • plugins (Sequence[Plugin | str] | None) – Plugin objects, or names of installed plugins.

  • environ (Mapping[str, str] | None) – Where FLEXORCH_PLUGINS is read; os.environ by default.

  • builtin_commands (Sequence[str]) – Names plugins may not reuse.

Returns:

The plugins, allowlisted ones first, each once.

Raises:

PluginError – If a name isn’t installed, an entry point isn’t a Plugin, an api_version excludes this version, or two plugins collide.

Return type:

list[Plugin]

Commands: named, validated operations on an orchestrator.

A command is a function fn(orch, params, progress, **runtime) -> result whose params argument is a pydantic model (a command that needs neither may take only orch, or orch and params). command() turns it into a Command, and one definition is then callable from Python (orch.run_command("price_sweep", prices=[0.1])), from the CLI (flex-orch cmd price_sweep --prices 0.1) and from a host app’s HTTP API, with the same JSON parameters.

runtime carries what JSON can’t: callables such as a build hook passed from Python. It is never recorded, apart from the hooks’ import strings.

Every call is recorded as a run of the flexorch::commands ledger: its parameters as the params input, what it returned as the result output (JSON), and who ran it on which study in the metadata. A call that raises ends failed with the error.

flexorchestrator.ext.commands.COMMANDS_LEDGER = 'flexorch::commands'

The backend study every command call is recorded in.

Type:

str

Plugins: bundles of commands, hooks and an orchestrator subclass.

A plugin package exposes a Plugin through the flexorchestrator.plugins entry-point group:

[project.entry-points."flexorchestrator.plugins"]
digester_tools = "digester_tools:plugin"

Being installed isn’t enough to load: a plugin loads only when its name is in FLEXORCH_PLUGINS (comma-separated) or it is passed explicitly (Orchestrator(plugins=[...])), so each deployment enables its own set. Loading checks that the plugin’s api_version range includes PLUGIN_API_VERSION, and that no two plugins (or a plugin and a built-in) claim the same command or hook name, or both provide an orchestrator subclass.

flexorchestrator.ext.plugins.PLUGIN_API_VERSION = '1.0.0'

The plugin API’s version (semver, separate from the package version).

Type:

str

flexorchestrator.ext.plugins.ENTRY_POINT_GROUP = 'flexorchestrator.plugins'

The entry-point group installed plugins register under.

Type:

str

flexorchestrator.ext.plugins.ALLOWLIST_ENV = 'FLEXORCH_PLUGINS'

The environment variable listing the installed plugins to enable, comma-separated (installed plugins are off unless listed).

Type:

str

Lifecycle events: a lighter alternative to subclassing.

@orch.on("result_stored") registers a listener; the orchestrator calls it with keyword arguments after the event. A listener that raises propagates: the item is already stored by then, so nothing is undone.

Event

Keyword arguments

study_created

study

spec_stored

item (a StoreItem)

result_stored

item

data_stored

item

fit_stored

item

job_finished

job (an execute_study summary)

command_finished

name, status (succeeded/failed), error

flexorchestrator.ext.events.EVENTS = ('study_created', 'spec_stored', 'result_stored', 'data_stored', 'fit_stored', 'job_finished', 'command_finished')

Every lifecycle event.

Type:

tuple[str, …]