Studies

See Studies from a config for an overview.

Declarative studies: StudyConfig and the execute_study command.

Example

>>> run = orch.execute_study({
...     "base_model_spec": "base",
...     "sweeps": [{"type": "surrogate", "unit": "plant.ro",
...                 "surrogates": ["ro_average", "ro_linear"]}],
...     "output_name": "{surrogate}",
... })
>>> run.counts()
{'succeeded': 2}
class flexorchestrator.study.Case(*, name, spec=None, surrogates=<factory>, configuration_options=<factory>, variables=<factory>, model_inputs=<factory>)[source]

Bases: _Strict

One hand-picked combination in a CasesSweep.

Parameters:
name

The case’s name, which output_name renders as {case}.

Type:

str

spec

A model spec to build from instead of base_model_spec.

Type:

str | None

surrogates

{unit: surrogate tag}.

Type:

dict[str, str]

configuration_options

{option path: value}, as a ConfigurationSweep sets them.

Type:

dict[str, Any]

variables

{variable path: value}, as a VariableSweep fixes them.

Type:

dict[str, Any]

model_inputs

Entries that set variables from stored data, as a ModelInputsSweep value does.

Type:

list[flexorchestrator.inputs.models.ModelInput]

model_config = {'extra': 'forbid'}

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

class flexorchestrator.study.CasesSweep(*, type, name=None, cases)[source]

Bases: _Strict

Each task runs one of cases: chosen combinations, not every one.

A cases sweep is one sweep like any other, so it can be combined with the rest (a product with a price sweep runs every case at every price).

Parameters:
name

The field output_name renders the case’s name as; case by default.

Type:

str | None

cases

The cases; their names must differ.

Type:

list[flexorchestrator.study.config.Case]

model_config = {'extra': 'forbid'}

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

class flexorchestrator.study.ConfigurationSweep(*, type, name=None, path, values)[source]

Bases: _Strict

Each task sets the configuration option at path to one of values.

The option is set in a copy of the base spec (the configure hook), which is stored under the task’s tag with the base as parent. For flex-pse, path is any element’s name followed by the option: a unit’s construction option ("plant.feed.max_withdrawal") or another element’s field ("costing.energy_prices.electrical"). A dict-valued option is set whole by a dict value, or one key at a time by a longer path ("plant.feed.max_withdrawal.value").

Parameters:
name

The field output_name renders the value as; path by default.

Type:

str | None

path

The option’s path.

Type:

str

values

The values; any JSON value, dicts included.

Type:

list[Any]

model_config = {'extra': 'forbid'}

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

class flexorchestrator.study.ExecuteParams(*, config, dry_run=False, max_workers=None, ray_address=None)[source]

Bases: BaseModel

The parameters of execute_study.

Parameters:
config

The study config.

Type:

flexorchestrator.study.config.StudyConfig

dry_run

Return the plan without storing or solving anything.

Type:

bool

max_workers

Overrides config.execution.max_workers.

Type:

int | None

ray_address

Overrides config.execution.ray_address.

Type:

str | None

model_config = {}

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

class flexorchestrator.study.Execution(*, max_workers=1, ray_address=None, resources=<factory>, max_calls=None, task_timeout_s=7200.0, retries=0, on_error='continue')[source]

Bases: _Strict

How tasks run.

max_workers: 1 (the default) runs the tasks one after another in this process. More than 1 runs them on Ray: a local Ray started for this process (namespace="flexorch"), the one already connected, or the cluster at ray_address. Either way the main process stores every result, so workers never hold database credentials.

Parameters:
max_workers

Tasks run at once.

Type:

int

ray_address

A Ray cluster, e.g. "ray://tenant-ray-head:10001"; local Ray if None. Its workers need flex-orchestrator and the hooks’ modules installed.

Type:

str | None

resources

What each task reserves on Ray.

Type:

flexorchestrator.study.config.Resources

max_calls

Restart a Ray worker process after this many tasks, to keep memory bounded; None never restarts.

Type:

int | None

task_timeout_s

A task’s time limit on Ray, counted from when it’s submitted, so it includes starting a worker (a few seconds the first time). A task that runs over is killed and stored as a failed result (termination: timeout); it isn’t retried. Two hours by default; None means no limit. In-process it is not enforced.

Type:

float | None

retries

How many times a task is built and solved again when building or exporting raises, the solve hook raises, or its Ray worker dies. A task whose spec or result can’t be stored isn’t retried.

Type:

int

on_error

Go on with the other tasks after one fails (continue) or stop (stop); on Ray, stop cancels the tasks still running.

Type:

Literal[‘continue’, ‘stop’]

model_config = {'extra': 'forbid'}

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

class flexorchestrator.study.ExportConfig(*, keys=None, include=None, exclude=None, streams=None, strict_units=False)[source]

Bases: _Strict

What each task’s result stores; nothing set means the default selection.

Parameters:
keys

Exact paths to export.

Type:

list[str] | None

include

Glob patterns to export.

Type:

list[str] | None

exclude

Glob patterns to leave out.

Type:

list[str] | None

streams

Values to also store natively.

Type:

list[str] | None

strict_units

Raise on a unit with no QUDT key.

Type:

bool

model_config = {'extra': 'forbid'}

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

class flexorchestrator.study.HooksConfig(*, build=None, solve=None, apply_surrogate=None, swap_surrogate=None, time_sets=None, configure=None, time_grid=None)[source]

Bases: _Strict

Hooks for the study’s tasks: import strings or registered names.

Unset slots use the orchestrator’s hooks; hooks passed to execute_study win over these.

Parameters:
  • build (str | None)

  • solve (str | None)

  • apply_surrogate (str | None)

  • swap_surrogate (str | None)

  • time_sets (str | None)

  • configure (str | None)

  • time_grid (str | None)

build

The build hook.

Type:

str | None

solve

The solve hook.

Type:

str | None

apply_surrogate

Applies a surrogate sweep’s surrogates to the spec.

Type:

str | None

swap_surrogate

Swaps a surrogate on a live model.

Type:

str | None

time_sets

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

Type:

str | None

configure

Sets a configuration sweep’s options in the spec.

Type:

str | None

time_grid

Gives a spec’s time axis, for model_inputs.

Type:

str | None

model_config = {'extra': 'forbid'}

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

class flexorchestrator.study.ModelInputsSweep(*, type, name=None, values)[source]

Bases: _Strict

Each task sets model variables from one of values’ sets of data.

An entry in a set replaces the config’s model_inputs entry for the same path, so a sweep can vary only the streams it names.

Parameters:
name

The field output_name renders a set’s label as; model_inputs by default.

Type:

str | None

values

The sets; their labels must differ.

Type:

list[flexorchestrator.inputs.models.InputSet]

model_config = {'extra': 'forbid'}

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

class flexorchestrator.study.SpecListSweep(*, type, name=None, specs)[source]

Bases: _Strict

Each task builds from one of specs instead of base_model_spec.

Parameters:
name

The field output_name renders the tag as; spec by default.

Type:

str | None

specs

Model spec tags.

Type:

list[str]

model_config = {'extra': 'forbid'}

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

class flexorchestrator.study.StudyConfig(*, study=None, base_model_spec=None, design=None, fits=<factory>, model_inputs=<factory>, hooks=<factory>, sweeps=<factory>, combine='product', solve_options=<factory>, export=<factory>, output_name=None, on_existing='error', execution=<factory>)[source]

Bases: _Strict

A study as data; see flexorchestrator.study.config.

Parameters:
study

The study to run in, created if needed; the selected one if omitted.

Type:

str | None

base_model_spec

The model spec every task builds from, unless a spec_list sweep names others.

Type:

str | None

design

Run every task as a design study (DesignStudy). Can’t be combined with model_inputs.

Type:

flexorchestrator.study.config.DesignStudy | None

fits

fit_surrogate parameters, run before the sweeps.

Type:

list[flexorchestrator.fitting.models.FitParams]

model_inputs

Model variables every task sets from stored data: fit selectors, each column (after rename) named by the path it sets, lined up with the model’s time steps.

Type:

list[flexorchestrator.inputs.models.ModelInput]

hooks

See HooksConfig.

Type:

flexorchestrator.study.config.HooksConfig

sweeps

See SurrogateSweep, VariableSweep, ConfigurationSweep, SpecListSweep, ModelInputsSweep and CasesSweep.

Type:

list[Annotated[flexorchestrator.study.config.SurrogateSweep | flexorchestrator.study.config.VariableSweep | flexorchestrator.study.config.ConfigurationSweep | flexorchestrator.study.config.SpecListSweep | flexorchestrator.study.config.ModelInputsSweep | flexorchestrator.study.config.CasesSweep, FieldInfo(annotation=NoneType, required=True, discriminator=’type’)]]

combine

product (every combination) or zip (the sweeps in step; they must be the same length).

Type:

Literal[‘product’, ‘zip’]

solve_options

Passed to the solve hook. For flex-pse: prefer, tee, warmstart, mip_gap, time_limit and options.

Type:

dict[str, Any]

export

See ExportConfig.

Type:

flexorchestrator.study.config.ExportConfig

output_name

Each task’s tag, e.g. "ro_{surrogate}_{plant.ro.recovery}": fields are the sweeps’ names, plus base and index. By default the base tag and each sweep’s value, joined by _. A value is written exactly (str; 0.1 + 0.2 gives 0.30000000000000004) unless the field has a format spec, as in Python: {recovery:.3g}, {price:.2f}. The tag is only a name: the values themselves are stored in full with the result. Values that format alike make tags that repeat, which is refused before anything runs.

Type:

str | None

on_existing

When a task’s tag is stored: error (checked before anything runs), skip it (resume), or replace it.

Type:

Literal[‘error’, ‘skip’, ‘replace’]

execution

See Execution.

Type:

flexorchestrator.study.config.Execution

model_config = {'extra': 'forbid'}

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

class flexorchestrator.study.StudyRun(*, study, dry_run=False, planned_fits=<factory>, fits=<factory>, tasks=<factory>, results=<factory>)[source]

Bases: BaseModel

What execute_study did, or (dry_run) would do.

Parameters:
study

The study it ran in.

Type:

str

dry_run

Whether this is only the plan.

Type:

bool

planned_fits

The tags fits stores (or would store).

Type:

list[str]

fits

What each fits entry stored, in order.

Type:

list[flexorchestrator.fitting.models.FitSummary]

tasks

The planned tasks.

Type:

list[flexorchestrator.study.task.TaskSpec]

results

How each task ended, in order (empty for a dry run).

Type:

list[flexorchestrator.study.task.TaskResult]

counts()[source]

Return how many tasks ended each way, {status: count}.

Return type:

dict[str, int]

result(tag)[source]

Return the result of the task tagged tag.

Parameters:

tag (str)

Return type:

TaskResult

model_config = {}

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

class flexorchestrator.study.SurrogateChoice(*, unit, relation=None, surrogate)[source]

Bases: BaseModel

One surrogate a task applies.

Parameters:
  • unit (str)

  • relation (str | None)

  • surrogate (str)

unit

The unit’s path.

Type:

str

relation

The relation it replaces; the hook’s default if None.

Type:

str | None

surrogate

The surrogate spec’s tag.

Type:

str

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

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

class flexorchestrator.study.SurrogateSweep(*, type, name=None, unit, relation=None, surrogates)[source]

Bases: _Strict

Each task uses one of surrogates for unit.

Parameters:
name

The field output_name renders the surrogate’s tag as; surrogate by default.

Type:

str | None

unit

The unit’s path, e.g. "plant.ro".

Type:

str

relation

The relation the surrogate replaces; the hook’s default if omitted.

Type:

str | None

surrogates

Surrogate spec tags, stored or fitted by fits.

Type:

list[str]

model_config = {'extra': 'forbid'}

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

class flexorchestrator.study.TaskResult(*, index, tag, status, spec_tag=None, run_id=None, outcome=None, error=None, attempts=0, seconds=<factory>, rss_mb=None)[source]

Bases: BaseModel

How one task ended.

Parameters:
index

The task’s position.

Type:

int

tag

The result’s tag.

Type:

str

status

succeeded, failed (the solve ended without an optimal solution; stored as a failed result), error (building or storing raised, or the solve hook did; a raising solve is stored as a failed result too) or skipped (already stored, with on_existing: skip).

Type:

Literal[‘succeeded’, ‘failed’, ‘error’, ‘skipped’]

spec_tag

The model spec it was built from.

Type:

str | None

run_id

The result run, if one was stored.

Type:

str | None

outcome

The solve outcome.

Type:

flexorchestrator.hooks.SolveOutcome | None

error

The error, for error.

Type:

str | None

attempts

How many times it was tried.

Type:

int

seconds

Wall times of its last attempt: build (with writing the spec’s files), solve, export and store.

Type:

dict[str, float]

rss_mb

The memory of the process that built and solved it, after exporting, in MB.

Type:

float | None

property ok: bool

Whether the task stored a result (or one was already stored).

model_config = {}

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

class flexorchestrator.study.TaskSpec(*, index, tag, base, design=None, configuration=<factory>, surrogates=<factory>, overrides=<factory>, model_inputs=<factory>, swept_inputs=<factory>, labels=<factory>, hooks=<factory>, export=<factory>, solve_options=<factory>, on_existing='error')[source]

Bases: BaseModel

One planned build-solve-store.

Parameters:
index

Its position in the study, from 0.

Type:

int

tag

The result’s tag (and the derived spec’s, with surrogates).

Type:

str

base

The model spec it builds from (or derives from).

Type:

str

design

A dumped DesignStudy: base runs as this design study.

Type:

dict[str, Any] | None

configuration

{option path: value}, set in base first.

Type:

dict[str, Any]

surrogates

Surrogates applied to base (after the configuration).

Type:

list[flexorchestrator.study.task.SurrogateChoice]

overrides

Passed to the build hook: the variables to fix.

Type:

dict[str, Any]

model_inputs

The study’s model_inputs entries, resolved against the spec’s time steps before the build.

Type:

list[flexorchestrator.inputs.models.ModelInput]

swept_inputs

Entries from a sweep or case; each replaces a model_inputs entry that sets the same path.

Type:

list[flexorchestrator.inputs.models.ModelInput]

labels

The values output_name was rendered with.

Type:

dict[str, Any]

hooks

Hook import strings or registered names by slot; unset slots use the orchestrator’s.

Type:

dict[str, str]

export

What the result stores.

Type:

flexorchestrator.study.config.ExportConfig

solve_options

Passed to the solve hook.

Type:

dict[str, Any]

on_existing

error, skip or replace.

Type:

Literal[‘error’, ‘skip’, ‘replace’]

model_config = {'extra': 'forbid'}

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

property spec_tag: str

The model spec it builds; its own tag when it derives one.

property derives: bool

Whether it stores a derived spec (a design, options or surrogates).

class flexorchestrator.study.VariableSweep(*, type, name=None, path, values)[source]

Bases: _Strict

Each task fixes the model variable at path to one of values.

The values are passed to the build hook as overrides; for flex-pse each becomes a fix element. Use it for variables ("plant.ro.recovery"); an option the unit is built with is a ConfigurationSweep.

Parameters:
name

The field output_name renders the value as; path by default.

Type:

str | None

path

The variable’s path from the model root, e.g. "plant.ro.recovery" or "plant.tank.level[*]".

Type:

str

values

The values: numbers in the variable’s units, {"value", "units"}, or one number per time point.

Type:

list[Any]

model_config = {'extra': 'forbid'}

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

flexorchestrator.study.expand(cfg)[source]

Return the config’s tasks, in order.

Raises:

StudyConfigError – If there’s no base spec, zipped sweeps differ in length, two sweeps share a field name or set the same thing, output_name names an unknown field, or a tag is invalid or repeated.

Parameters:

cfg (StudyConfig)

Return type:

list[TaskSpec]

flexorchestrator.study.load_config(config)[source]

Return config as a StudyConfig.

Parameters:

config (Any) – A StudyConfig, a mapping, or the path of a YAML (.yaml, .yml) or JSON file.

Raises:

StudyConfigError – If the file can’t be read or the config doesn’t validate; the message lists each problem.

Return type:

StudyConfig

flexorchestrator.study.run_task(orch, task, runtime=None, retries=0, hooks=None)[source]

Run one task in this process: prepare(), execute(), finish().

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

  • task (TaskSpec) – The task.

  • runtime (HookSet | None) – Hooks (callables allowed) that win over task.hooks.

  • retries (int) – Executes it again this many times when building or exporting raises, or the solve hook raised (an error outcome). Reading or storing its spec, and storing its result, aren’t retried.

  • hooks (HookSet | None) – The resolved hooks (study_hooks()), instead of runtime.

Returns:

The result; an exception becomes an error result, so one task doesn’t end the study.

Raises:

TagExistsError – If the tag (or a different derived spec) is stored and on_existing doesn’t allow it; that’s a config problem, not a task failure.

Return type:

TaskResult

The config

StudyConfig: a whole study as data.

A config names a base model spec, optional fits (run first, so sweeps can use the surrogates they store), sweeps (combined as a product or zipped), and how each task’s result is named, exported and stored. A sweep varies one thing:

  • surrogate: the surrogate a unit uses;

  • variable: a model variable, fixed to each value;

  • configuration_option: an option the model is built with, such as a unit’s construction option or a price;

  • spec_list: the model spec itself;

  • model_inputs: the stored data model variables are set from;

  • cases: named, hand-picked combinations of the above.

design (optional) runs each task as a design study: the model spec over every year and representative month, sizing shared capacities. Leave it out for an ordinary study.

model_inputs (outside the sweeps) sets model variables from stored data in every task: a dataset, a stored result or general-store streams, selected as a fit’s X and y are.

For example:

base_model_spec: base
fits:
  - tag: "ro_{name}"
    X: {dataset: ro_operation, columns: [permeate]}
    y: {dataset: ro_operation, columns: [power_electrical]}
    variants:
      - {name: average, regressor: constant_intensity}
      - {name: linear, regressor: multilinear}
sweeps:
  - type: surrogate
    unit: plant.ro
    surrogates: [ro_average, ro_linear]
export: {include: ["plant.ro.*", "costing.aggregate_operating_cost"]}
output_name: "{surrogate}"

Hooks are import strings or registered names, so a config is plain data that a Ray worker or the HTTP API can carry. Its JSON Schema is StudyConfig.model_json_schema() (published in docs/schemas/).

Design studies

The design: section of a config.

class flexorchestrator.study.config.DesignStudy(*, schema_version='0.1.0', years, months, changes=<factory>, capacities)[source]

Bases: _Strict

Run each task’s model spec as a flex-pse design study.

This mirrors flex-pse’s DesignSpec; flex-pse checks the rules (weights sum to 12, years are consecutive) before any task runs.

Parameters:
schema_version

The version of this study.

Type:

str

years

The modeled years, ascending.

Type:

list[flexorchestrator.study.config.PlanningYear]

months

The representative months.

Type:

list[flexorchestrator.study.config.RepresentativeMonth]

changes

Changes to base elements, applied in order.

Type:

list[flexorchestrator.study.config.ParameterChange]

capacities

What to size.

Type:

list[flexorchestrator.study.config.CapacityDecision]

model_config = {'extra': 'forbid'}

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

class flexorchestrator.study.config.PlanningYear(*, year, represents=1)[source]

Bases: _Strict

One modeled year of a design study.

Parameters:
year

The calendar year.

Type:

int

represents

The calendar years it stands in for.

Type:

int

model_config = {'extra': 'forbid'}

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

class flexorchestrator.study.config.RepresentativeMonth(*, month, weight, days=None)[source]

Bases: _Strict

One calendar month modeled in every planning year.

Parameters:
month

The calendar month, 1 to 12.

Type:

int

weight

The months of the year it stands in for; weights sum to 12.

Type:

float

days

Model only the first N days and scale the bill up to the full month; the whole month if omitted.

Type:

int | None

model_config = {'extra': 'forbid'}

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

class flexorchestrator.study.config.ParameterChange(*, element, values, years=None, months=None)[source]

Bases: _Strict

A change to one base element for some years and months.

Parameters:
element

The name of the base element.

Type:

str

values

The fields to deep-merge into it. Files named here are stored with the spec.

Type:

dict[str, Any]

years

The years it applies to; all if omitted.

Type:

list[int] | None

months

The months it applies to; all if omitted.

Type:

list[int] | None

model_config = {'extra': 'forbid'}

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

class flexorchestrator.study.config.CapacityDecision(*, name, variable, capital_cost, lifetime_years, lower=0.0, upper)[source]

Bases: _Strict

One capacity the design study sizes, shared by every horizon.

Parameters:
name

The decision’s name, e.g. "battery_energy".

Type:

str

variable

The scalar variable’s path, e.g. "battery.energy_capacity".

Type:

str

capital_cost

The overnight cost per unit of the variable.

Type:

float

lifetime_years

The asset life used to annualize it.

Type:

float

lower

The lower bound, in the variable’s units.

Type:

float

upper

The upper bound, in the variable’s units.

Type:

float

model_config = {'extra': 'forbid'}

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

Design studies as plain data: composing specs and reading their results.

Nothing here imports flex-pse; flexorchestrator.flexpse.design builds them.

class flexorchestrator.study.design.DesignCapacity(*, size, units, at_upper_bound, capital_cost, lifetime_years, annualized_capital_cost)[source]

Bases: BaseModel

One sized capacity.

Parameters:
size

The size, in units.

Type:

float

units

The Pyomo unit of the size.

Type:

str | None

at_upper_bound

Whether the bound, not the economics, set the size.

Type:

bool

capital_cost

The overnight cost.

Type:

float

lifetime_years

The asset life used to annualize it.

Type:

float

annualized_capital_cost

The cost per year.

Type:

float

model_config = {}

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

class flexorchestrator.study.design.DesignSummary(*, study_years, currency, capacities, annual_operating_cost_by_year, operating_cost_by_horizon, annualized_operating_cost, annualized_capital_cost, annualized_cost, total_capital_cost)[source]

Bases: BaseModel

A stored design study’s sizes and annualized costs.

Parameters:
study_years

The calendar years the study covers.

Type:

int

currency

The Pyomo unit of the costs.

Type:

str | None

capacities

{name: capacity}.

Type:

dict[str, flexorchestrator.study.design.DesignCapacity]

annual_operating_cost_by_year

{modeled year: cost}.

Type:

dict[int, float]

operating_cost_by_horizon

{(year, month): the horizon's own bill}.

Type:

dict[tuple[int, int], float]

annualized_operating_cost

Discounted operating cost per year.

Type:

float

annualized_capital_cost

Capital recovery per year.

Type:

float

annualized_cost

The objective: the sum of the two.

Type:

float

total_capital_cost

Overnight capital, undiscounted.

Type:

float

model_config = {}

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

flexorchestrator.study.design.compose_design(base, design, name)[source]

Return the design spec that runs flowsheet base over design.

Parameters:
Return type:

dict

flexorchestrator.study.design.summary_selection(spec)[source]

Return the export selection that stores a design study’s summary.

Parameters:

spec (dict[str, Any]) – A design spec as JSON.

Return type:

dict[str, list[str]]

flexorchestrator.study.design.read_summary(data, spec)[source]

Return the summary of a design study’s stored values.

Parameters:
  • data (ModelData) – The stored result.

  • spec (dict[str, Any]) – The design spec it was built from.

Raises:

ExportError – If the result’s export left out a value the summary needs; export capacity*, annual* and each horizon’s aggregate_operating_cost.

Return type:

DesignSummary

Execution

class flexorchestrator.study.config.Resources(*, num_cpus=1.0, memory=None)[source]

Bases: _Strict

What each Ray task reserves.

Parameters:
num_cpus

CPUs per task; Ray runs as many at once as the cluster fits, up to max_workers.

Type:

float

memory

Bytes of memory per task, or None to reserve none.

Type:

float | None

model_config = {'extra': 'forbid'}

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

How a study runs

The built-in execute_study command, which runs a study config.

The config is a StudyConfig.

  1. The config is expanded into tasks (expand()): the sweeps’ values are combined (product or zip) and each combination’s tag is rendered from output_name. Repeated or invalid tags fail here, before anything runs; dry_run stops here and returns the plan.

  2. With on_existing: error, every task’s tag is checked; a stored one raises before anything runs.

  3. fits run (fit_surrogate), so the sweeps can use their surrogates.

  4. The tasks run: one after another in this process (run_task()), or with max_workers > 1 on Ray (flexorchestrator.parallel.run_tasks()), where workers build and solve and this process stores. Either way the stored results are the same.

The command returns a StudyRun; the call, its parameters and its summary are recorded in flexorch::commands like every command’s.

One task of a study: build a model from a stored spec, solve it, store it.

A TaskSpec is plain data (hooks as import strings or registered names), so it can be written to a dry-run plan. Running one has three steps, split so that a Ray worker needs only plain data and never the store:

  1. prepare() (main process) checks the tag, stores the derived spec if the task has one, and reads the spec and its files into a Work.

  2. execute() (in this process or on a worker) builds, solves and exports, and returns a Done: the outcome and the values.

  3. finish() (main process) maps the units and stores the result.

run_task() runs all three here, with retries; execute_study runs them on Ray when max_workers > 1. Both store the same results, and both retry only execute(): a raising prepare() or finish() is a storage problem, and the task ends as an error result at once.

A task with configuration options or surrogates stores a derived model spec under its own tag, with the base as parent: the base spec with each option set by the configure hook, then each surrogate applied by the apply_surrogate hook. A derived spec that is already stored and identical is reused, so a resumed study doesn’t trip over its own specs.

Running a study’s tasks, and a fit’s variants, on Ray.

max_workers > 1 sends work here. The main process keeps the store: it prepares each task (study.task.prepare), Ray workers build, solve and export (study.task.execute), and a ray.wait loop in the main process stores each result as it arrives (study.task.finish). Workers get plain data and import strings, never a model, a connection or a credential.

The loop keeps at most max_workers tasks running, kills a task that runs past task_timeout_s (ray.cancel(force=True)), retries a task whose worker died or whose build or solve raised (never one whose spec or result couldn’t be stored), and cancels everything still running when the command is cancelled or on_error: stop trips.

Ray is local unless an address is given: ray.init(address="local", namespace="flexorch", include_dashboard=False), started once per process and reused. A Ray the caller already connected to is used as it is.

flexorchestrator.parallel.NAMESPACE = 'flexorch'

The Ray namespace the orchestrator’s tasks run in.

Type:

str

flexorchestrator.parallel.RUNTIME_ENV = {'env_vars': {'MKL_NUM_THREADS': '1', 'OMP_NUM_THREADS': '1', 'OPENBLAS_NUM_THREADS': '1'}}

Every worker’s runtime_env: one thread per solver library, so max_workers solves don’t oversubscribe the CPUs.

Type:

dict

flexorchestrator.parallel.POLL_S = 0.25

How often the loop checks timeouts and cancellation, in seconds.

Type:

float

flexorchestrator.parallel.connect(address=None)[source]

Return the ray module, connected: to address, or local Ray.

A Ray this process is already connected to is used as it is.

Parameters:

address (str | None) – A Ray cluster, e.g. "ray://tenant-ray-head:10001"; None starts local Ray (once per process).

Returns:

The ray module.

Raises:

StudyConfigError – If Ray isn’t installed.

Return type:

Any

flexorchestrator.parallel.remote(ray, fn, *, num_cpus=1.0, memory=None, max_calls=None)[source]

Return fn as a Ray remote function with the orchestrator’s options.

Ray’s own retries are off (max_retries=0): the loops here retry, so one budget (retries) covers a raising task and a dead worker alike.

Parameters:
  • ray (Any) – The connected ray module (connect()).

  • fn (Any) – A module-level function, importable on the workers.

  • num_cpus (float) – CPUs each call reserves.

  • memory (float | None) – Bytes of memory each call reserves, if set.

  • max_calls (int | None) – Restart a worker process after this many calls, if set.

Returns:

The remote function; call it with .remote(...).

Return type:

Any

flexorchestrator.parallel.run_tasks(orch, tasks, hooks, execution, workers, progress)[source]

Run a study’s tasks on Ray; return their results in task order.

Parameters:
  • orch (Any) – The orchestrator (main process).

  • tasks (list[Any]) – The TaskSpec s.

  • hooks (Any) – The portable hooks (study.task.study_hooks).

  • execution (Any) – The config’s Execution.

  • workers (int) – Tasks running at once.

  • progress (Any) – Advanced after each task; cancellation is checked often.

Raises:
Return type:

list[Any]

flexorchestrator.parallel.map_ordered(fn, jobs, *, workers, ray_address=None, progress=None, **options)[source]

Run fn(*job) for every job on Ray, at most workers at once.

Parameters:
  • fn (Any) – A module-level function, importable on the workers.

  • jobs (list[tuple[Any, ...]]) – The positional arguments of each call.

  • workers (int) – Calls running at once.

  • ray_address (str | None) – The Ray to connect to (connect()).

  • progress (Any) – Checked for cancellation while waiting, if given.

  • **options (Any) – Passed to remote() (num_cpus, memory, max_calls).

Returns:

What each call returned, in job order.

Raises:

Exception – The first exception a job raised, after the jobs still running are cancelled; CommandCancelled likewise.

Return type:

list[Any]

Model inputs

Model inputs from stored data.

A model_inputs entry (ModelInput) is a fit selector plus how its data lines up with the model’s time steps; resolve() turns entries into build overrides and a provenance record.

class flexorchestrator.inputs.InputResample(*, agg='mean')[source]

Bases: _Strict

How samples become one value per time step.

Parameters:

agg (Literal['mean', 'sum', 'min', 'max', 'median', 'first', 'last'])

agg

How the samples in one step combine.

Type:

Literal[‘mean’, ‘sum’, ‘min’, ‘max’, ‘median’, ‘first’, ‘last’]

model_config = {'extra': 'forbid'}

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

class flexorchestrator.inputs.InputSet(*, label, inputs)[source]

Bases: _Strict

One value of a model_inputs sweep: a labelled set of entries.

Parameters:
label

What output_name renders the set as.

Type:

str

inputs

The entries a task with this value uses.

Type:

list[flexorchestrator.inputs.models.ModelInput]

model_config = {'extra': 'forbid'}

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

class flexorchestrator.inputs.ModelInput(*, dataset=None, study=None, columns=None, result=None, keys=None, ref_uris=None, streams=None, resolve=None, sparql=None, start=None, end=None, units=None, rename=<factory>, timezone='UTC', resample=None, gaps='interpolate', limit=None, reduce=None, offset=None)[source]

Bases: Selector

One model_inputs entry: a selector, then its alignment.

Parameters:
timezone

The facility’s time zone (an IANA name such as "America/Los_Angeles"). The model runs on that site’s wall clock, so stored UTC timestamps are converted to it before they’re lined up with the model’s (naive) time steps. UTC by default: data stored in UTC means a model in UTC.

Type:

str

resample

How the samples in one time step combine; mean by default.

Type:

flexorchestrator.inputs.models.InputResample | None

gaps

A time step with no value is filled by interpolate (in time, the default), ffill (the last value carried forward) or zero; error refuses any gap.

Type:

Literal[‘interpolate’, ‘ffill’, ‘zero’, ‘error’]

limit

The longest run of missing steps interpolate or ffill fills; a longer one fails.

Type:

int | None

reduce

Set the variable to one number instead of a series: this statistic of the data over the model’s horizon.

Type:

Literal[‘mean’, ‘last’, ‘first’, ‘min’, ‘max’, ‘median’] | None

offset

Read the data this far from the model’s horizon, as a pandas offset ("-365D": last year’s data for this horizon).

Type:

str | None

model_config = {'extra': 'forbid'}

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

model_inputs entries: stored data a model variable is set from.

An entry is a fit selector (dataset, result, ref_uris, streams, resolve or sparql, with start, end, units and rename) plus how its data is lined up with the model’s time steps. After rename, each column’s name is the model path it sets.

Plain pydantic, so a study config carries it as data.

Turn model_inputs entries into build overrides.

Runs in the main process, which holds the store; the values it returns are plain data a Ray worker builds with. Each entry’s selector is loaded with the fit selectors (fitting.selectors.load), then:

  1. its UTC timestamps go to the entry’s timezone and lose it, since the model’s time steps are the facility’s naive wall clock;

  2. the data is shifted by offset onto the model’s horizon;

  3. it is resampled onto the model’s time steps and its gaps filled;

  4. or, with reduce, the horizon’s data becomes one number.

class flexorchestrator.inputs.resolve.Resolved(values=<factory>, provenance=<factory>)[source]

Bases: object

What a list of entries set.

Parameters:
values

{model path: value}, for the build hook: a list with one number per time point (or one number, for reduce), as {"value", "units"} when the data has a unit.

Type:

dict[str, Any]

provenance

Per entry: the entry as sent, what its selector resolved to, the window read, how many steps were filled, and the values’ hash.

Type:

list[dict[str, Any]]

flexorchestrator.inputs.resolve.resolve(orch, inputs, grid, swept=(), cache=None)[source]

Resolve a task’s entries against its model’s time steps.

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

  • inputs (Sequence[ModelInput]) – The study’s (or one build’s) entries.

  • grid (DatetimeIndex | None) – The model’s time steps (the time_grid hook); None for a model without a time axis, which takes only reduce entries.

  • swept (Sequence[ModelInput]) – Entries from a sweep or case; one replaces an inputs entry that sets the same path.

  • cache (dict | None) – Selector data read so far, reused for an entry that reads the same data (a study passes one for all its tasks).

Raises:

ModelInputError – If an entry’s data can’t be read or lined up, or two entries of one list set the same path.

Return type:

Resolved