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:
_StrictOne hand-picked combination in a
CasesSweep.- Parameters:
- configuration_options¶
{option path: value}, as aConfigurationSweepsets them.
- variables¶
{variable path: value}, as aVariableSweepfixes them.
- model_inputs¶
Entries that set variables from stored data, as a
ModelInputsSweepvalue does.
- 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:
_StrictEach 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
productwith a price sweep runs every case at every price).- Parameters:
- cases¶
The cases; their names must differ.
- 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:
_StrictEach task sets the configuration option at
pathto one ofvalues.The option is set in a copy of the base spec (the
configurehook), which is stored under the task’s tag with the base as parent. For flex-pse,pathis 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:
- 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:
BaseModelThe parameters of
execute_study.- Parameters:
config (StudyConfig)
dry_run (bool)
ray_address (str | None)
- config¶
The study config.
- 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:
_StrictHow 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 atray_address. Either way the main process stores every result, so workers never hold database credentials.- Parameters:
- ray_address¶
A Ray cluster, e.g.
"ray://tenant-ray-head:10001"; local Ray ifNone. Its workers need flex-orchestrator and the hooks’ modules installed.- Type:
str | None
- resources¶
What each task reserves on Ray.
- max_calls¶
Restart a Ray worker process after this many tasks, to keep memory bounded;
Nonenever 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;Nonemeans 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:
- on_error¶
Go on with the other tasks after one fails (
continue) or stop (stop); on Ray,stopcancels 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:
_StrictWhat each task’s result stores; nothing set means the default selection.
- Parameters:
- 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:
_StrictHooks for the study’s tasks: import strings or registered names.
Unset slots use the orchestrator’s hooks; hooks passed to
execute_studywin over these.- Parameters:
- 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:
_StrictEach task sets model variables from one of
values’ sets of data.An entry in a set replaces the config’s
model_inputsentry for the same path, so a sweep can vary only the streams it names.- Parameters:
- values¶
The sets; their labels must differ.
- 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:
_StrictEach task builds from one of
specsinstead ofbase_model_spec.- Parameters:
- 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:
_StrictA study as data; see
flexorchestrator.study.config.- Parameters:
study (str | None)
base_model_spec (str | None)
design (DesignStudy | None)
model_inputs (list[ModelInput])
hooks (HooksConfig)
sweeps (list[Annotated[SurrogateSweep | VariableSweep | ConfigurationSweep | SpecListSweep | ModelInputsSweep | CasesSweep, FieldInfo(annotation=NoneType, required=True, discriminator='type')]])
combine (Literal['product', 'zip'])
export (ExportConfig)
output_name (str | None)
on_existing (Literal['error', 'skip', 'replace'])
execution (Execution)
- base_model_spec¶
The model spec every task builds from, unless a
spec_listsweep names others.- Type:
str | None
- design¶
Run every task as a design study (
DesignStudy). Can’t be combined withmodel_inputs.- Type:
- fits¶
fit_surrogateparameters, run before the sweeps.
- 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.
- hooks¶
See
HooksConfig.
- sweeps¶
See
SurrogateSweep,VariableSweep,ConfigurationSweep,SpecListSweep,ModelInputsSweepandCasesSweep.- 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) orzip(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_limitandoptions.
- export¶
See
ExportConfig.
- output_name¶
Each task’s tag, e.g.
"ro_{surrogate}_{plant.ro.recovery}": fields are the sweeps’ names, plusbaseandindex. By default the base tag and each sweep’s value, joined by_. A value is written exactly (str;0.1 + 0.2gives0.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),skipit (resume), orreplaceit.- Type:
Literal[‘error’, ‘skip’, ‘replace’]
- 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:
BaseModelWhat
execute_studydid, or (dry_run) would do.- Parameters:
study (str)
dry_run (bool)
fits (list[FitSummary])
results (list[TaskResult])
- fits¶
What each
fitsentry stored, in order.
- tasks¶
The planned tasks.
- results¶
How each task ended, in order (empty for a dry run).
- 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:
BaseModelOne surrogate a task applies.
- 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:
_StrictEach task uses one of
surrogatesforunit.- Parameters:
- 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:
BaseModelHow one task ended.
- Parameters:
- 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) orskipped(already stored, withon_existing: skip).- Type:
Literal[‘succeeded’, ‘failed’, ‘error’, ‘skipped’]
- outcome¶
The solve outcome.
- Type:
- seconds¶
Wall times of its last attempt:
build(with writing the spec’s files),solve,exportandstore.
- rss_mb¶
The memory of the process that built and solved it, after exporting, in MB.
- Type:
float | None
- 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:
BaseModelOne planned build-solve-store.
- Parameters:
index (int)
tag (str)
base (str)
surrogates (list[SurrogateChoice])
model_inputs (list[ModelInput])
swept_inputs (list[ModelInput])
export (ExportConfig)
on_existing (Literal['error', 'skip', 'replace'])
- surrogates¶
Surrogates applied to
base(after the configuration).
- model_inputs¶
The study’s
model_inputsentries, resolved against the spec’s time steps before the build.
- swept_inputs¶
Entries from a sweep or case; each replaces a
model_inputsentry that sets the same path.
- hooks¶
Hook import strings or registered names by slot; unset slots use the orchestrator’s.
- export¶
What the result stores.
- on_existing¶
error,skiporreplace.- Type:
Literal[‘error’, ‘skip’, ‘replace’]
- model_config = {'extra': 'forbid'}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class flexorchestrator.study.VariableSweep(*, type, name=None, path, values)[source]¶
Bases:
_StrictEach task fixes the model variable at
pathto one ofvalues.The values are passed to the build hook as overrides; for flex-pse each becomes a
fixelement. Use it for variables ("plant.ro.recovery"); an option the unit is built with is aConfigurationSweep.- Parameters:
- path¶
The variable’s path from the model root, e.g.
"plant.ro.recovery"or"plant.tank.level[*]".- Type:
- 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_namenames an unknown field, or a tag is invalid or repeated.- Parameters:
cfg (StudyConfig)
- Return type:
- flexorchestrator.study.load_config(config)[source]¶
Return
configas aStudyConfig.- 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:
- 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
erroroutcome). Reading or storing its spec, and storing its result, aren’t retried.hooks (HookSet | None) – The resolved hooks (
study_hooks()), instead ofruntime.
- Returns:
The result; an exception becomes an
errorresult, so one task doesn’t end the study.- Raises:
TagExistsError – If the tag (or a different derived spec) is stored and
on_existingdoesn’t allow it; that’s a config problem, not a task failure.- Return type:
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:
_StrictRun 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 (str)
years (Annotated[list[PlanningYear], MinLen(min_length=1)])
months (Annotated[list[RepresentativeMonth], MinLen(min_length=1)])
changes (list[ParameterChange])
capacities (Annotated[list[CapacityDecision], MinLen(min_length=1)])
- years¶
The modeled years, ascending.
- months¶
The representative months.
- changes¶
Changes to base elements, applied in order.
- capacities¶
What to size.
- 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:
_StrictOne modeled year of a design study.
- 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:
_StrictOne calendar month modeled in every planning year.
- 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:
_StrictA change to one base element for some years and months.
- Parameters:
- values¶
The fields to deep-merge into it. Files named here are stored with the spec.
- 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:
_StrictOne capacity the design study sizes, shared by every horizon.
- Parameters:
- 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:
BaseModelOne sized capacity.
- Parameters:
- 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:
BaseModelA stored design study’s sizes and annualized costs.
- Parameters:
- capacities¶
{name: capacity}.
- operating_cost_by_horizon¶
{(year, month): the horizon's own bill}.
- 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
baseoverdesign.
- flexorchestrator.study.design.summary_selection(spec)[source]¶
Return the export selection that stores a design study’s summary.
- flexorchestrator.study.design.read_summary(data, spec)[source]¶
Return the summary of a design study’s stored values.
- Parameters:
- Raises:
ExportError – If the result’s export left out a value the summary needs; export
capacity*,annual*and each horizon’saggregate_operating_cost.- Return type:
Execution¶
- class flexorchestrator.study.config.Resources(*, num_cpus=1.0, memory=None)[source]¶
Bases:
_StrictWhat each Ray task reserves.
- num_cpus¶
CPUs per task; Ray runs as many at once as the cluster fits, up to
max_workers.- Type:
- 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.
The config is expanded into tasks (
expand()): the sweeps’ values are combined (productorzip) and each combination’s tag is rendered fromoutput_name. Repeated or invalid tags fail here, before anything runs;dry_runstops here and returns the plan.With
on_existing: error, every task’s tag is checked; a stored one raises before anything runs.fitsrun (fit_surrogate), so the sweeps can use their surrogates.The tasks run: one after another in this process (
run_task()), or withmax_workers > 1on 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:
prepare()(main process) checks the tag, stores the derived spec if the task has one, and reads the spec and its files into aWork.execute()(in this process or on a worker) builds, solves and exports, and returns aDone: the outcome and the values.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:
- 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, somax_workerssolves don’t oversubscribe the CPUs.- Type:
- flexorchestrator.parallel.POLL_S = 0.25¶
How often the loop checks timeouts and cancellation, in seconds.
- Type:
- flexorchestrator.parallel.connect(address=None)[source]¶
Return the
raymodule, connected: toaddress, 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";Nonestarts local Ray (once per process).- Returns:
The
raymodule.- Raises:
StudyConfigError – If Ray isn’t installed.
- Return type:
- flexorchestrator.parallel.remote(ray, fn, *, num_cpus=1.0, memory=None, max_calls=None)[source]¶
Return
fnas 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:
- Returns:
The remote function; call it with
.remote(...).- Return type:
- 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:
- Raises:
TagExistsError – As
study.task.prepare.CommandCancelled – If the command is cancelled; running tasks are cancelled first.
- Return type:
- flexorchestrator.parallel.map_ordered(fn, jobs, *, workers, ray_address=None, progress=None, **options)[source]¶
Run
fn(*job)for every job on Ray, at mostworkersat 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;
CommandCancelledlikewise.- Return type:
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:
_StrictHow 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:
_StrictOne value of a
model_inputssweep: a labelled set of entries.- Parameters:
label (str)
inputs (Annotated[list[ModelInput], MinLen(min_length=1)])
- inputs¶
The entries a task with this value uses.
- 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:
SelectorOne
model_inputsentry: a selector, then its alignment.- Parameters:
dataset (str | None)
study (str | None)
result (str | None)
streams (list[StreamName] | None)
resolve (str | None)
sparql (str | None)
start (datetime | None)
end (datetime | None)
timezone (str)
resample (InputResample | None)
gaps (Literal['interpolate', 'ffill', 'zero', 'error'])
reduce (Literal['mean', 'last', 'first', 'min', 'max', 'median'] | None)
offset (str | None)
- 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.UTCby default: data stored in UTC means a model in UTC.- Type:
- resample¶
How the samples in one time step combine;
meanby default.- Type:
- gaps¶
A time step with no value is filled by
interpolate(in time, the default),ffill(the last value carried forward) orzero;errorrefuses any gap.- Type:
Literal[‘interpolate’, ‘ffill’, ‘zero’, ‘error’]
- limit¶
The longest run of missing steps
interpolateorffillfills; 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:
its UTC timestamps go to the entry’s
timezoneand lose it, since the model’s time steps are the facility’s naive wall clock;the data is shifted by
offsetonto the model’s horizon;it is resampled onto the model’s time steps and its gaps filled;
or, with
reduce, the horizon’s data becomes one number.
- class flexorchestrator.inputs.resolve.Resolved(values=<factory>, provenance=<factory>)[source]¶
Bases:
objectWhat a list of entries set.
- values¶
{model path: value}, for the build hook: a list with one number per time point (or one number, forreduce), as{"value", "units"}when the data has a unit.
- 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_gridhook);Nonefor a model without a time axis, which takes onlyreduceentries.swept (Sequence[ModelInput]) – Entries from a sweep or case; one replaces an
inputsentry 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: