Fitting surrogates

Fit surrogates from stored data: the fit_surrogate command.

Data comes from Selector objects (a dataset, a stored result, or general-store streams), is prepared (Prep), and is fitted by a regressor named by a flex-pse SurrogateType or an import string. Each fit stores a surrogate spec in <s>::specs and a fit run, with its training-data provenance, in <s>::fits.

Example

>>> orch.fit_surrogate(
...     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"},
...     ],
... )
class flexorchestrator.fitting.FitParams(*, tag, regressor=None, params=<factory>, spec_options=<factory>, X, y, window=None, prep=<factory>, validation=None, variants=None, on_existing='error', store_series=False, max_workers=1, ray_address=None)[source]

Bases: _Strict

The parameters of fit_surrogate.

Parameters:
tag

The surrogate spec’s tag; a template with {name} when there are variants ("biogas_{name}").

Type:

str

regressor

A flex-pse SurrogateType ("multilinear", "constant_intensity") or an import string of a class that follows flex-pse’s Regressor protocol.

Type:

str | None

params

The regressor’s constructor arguments.

Type:

dict[str, Any]

spec_options

Passed to its to_surrogate_spec.

Type:

dict[str, Any]

X

The inputs: one selector or a list, merged column-wise.

Type:

flexorchestrator.fitting.models.Selector | list[flexorchestrator.fitting.models.Selector]

y

The output: one selector (or a list) giving one column.

Type:

flexorchestrator.fitting.models.Selector | list[flexorchestrator.fitting.models.Selector]

window

Only data in this window.

Type:

flexorchestrator.fitting.models.Window | None

prep

How the data is prepared (see Prep).

Type:

flexorchestrator.fitting.models.Prep

validation

Hold-out metrics (see Validation).

Type:

flexorchestrator.fitting.models.Validation | None

variants

Several fits in one call, each overriding these fields.

Type:

list[flexorchestrator.fitting.models.Variant] | None

on_existing

What to do when a tag is stored: error, skip it, or replace it.

Type:

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

store_series

Also store actual / fitted / residual timeseries with the fit, for plotting.

Type:

bool

max_workers

Variants fitted at once; more than 1 fits them on Ray. In a study, the study’s execution decides instead.

Type:

int

ray_address

The Ray cluster for max_workers > 1; local Ray if None.

Type:

str | None

expand()[source]

Return one FitPlan per variant (one if there are none).

Raises:

FitError – If a variant has no regressor, or two render the same tag.

Return type:

list[FitPlan]

model_config = {'extra': 'forbid'}

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

class flexorchestrator.fitting.FitPlan(*, tag, name=None, regressor, params, spec_options, X, y, window, prep, validation, store_series)[source]

Bases: _Strict

One fit, with its variant applied: what a fit run records as its parameters.

Parameters:
tag

The surrogate spec’s tag, rendered.

Type:

str

name

The variant’s name, if it came from one.

Type:

str | None

The other fields are those of FitParams, with the variant’s set.

model_config = {'extra': 'forbid'}

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

class flexorchestrator.fitting.FitRecord(*, tag, status, run_id=None, spec_hash=None, regressor=None, coefficients=<factory>, metrics=<factory>, holdout=None, n_samples=None, data_hash=None)[source]

Bases: BaseModel

What one fit stored.

Parameters:
tag

The surrogate spec’s tag.

Type:

str

status

"stored", or "skipped" (on_existing: skip).

Type:

Literal[‘stored’, ‘skipped’]

run_id

The fit run in <s>::fits.

Type:

str | None

spec_hash

The stored surrogate spec’s hash.

Type:

str | None

regressor

The regressor used.

Type:

str | None

coefficients

The fitted coefficients.

Type:

dict[str, float]

metrics

The fit’s r2 and rmse (and more, per regressor).

Type:

dict[str, float]

holdout

Metrics on the held-out rows, if validated.

Type:

dict[str, float] | None

n_samples

Rows the fit used.

Type:

int | None

data_hash

sha256 of the prepared data.

Type:

str | None

model_config = {}

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

class flexorchestrator.fitting.FitSummary(*, fits)[source]

Bases: BaseModel

What fit_surrogate returns: one record per fit, in order.

Parameters:

fits (list[FitRecord])

fits

The records.

Type:

list[flexorchestrator.fitting.models.FitRecord]

property tags: list[str]

The tags of the fits stored (not skipped).

model_config = {}

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

class flexorchestrator.fitting.Prep(*, align='inner', resample=None, gaps='error', limit=None, max_rows=1000000)[source]

Bases: _Strict

How the selected data is prepared before fitting.

Parameters:
align

inner keeps the timestamps every column has; outer keeps any column’s, leaving gaps.

Type:

Literal[‘inner’, ‘outer’]

resample

Resample to a regular index first.

Type:

flexorchestrator.fitting.models.Resample | None

gaps

What to do with missing values: error (the default), drop the rows, interpolate (in time, up to limit missing values in a row), or keep the longest_segment with none.

Type:

Literal[‘error’, ‘drop’, ‘interpolate’, ‘longest_segment’]

limit

The longest run of missing values interpolate fills.

Type:

int | None

max_rows

Refuse more rows than this (a guard against running out of memory).

Type:

int

model_config = {'extra': 'forbid'}

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

class flexorchestrator.fitting.Resample(*, freq, agg='mean')[source]

Bases: _Strict

Resample to a regular index.

Parameters:
  • freq (str)

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

freq

A pandas offset alias, e.g. "1h".

Type:

str

agg

How values in one bin 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.fitting.Selector(*, 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>)[source]

Bases: _Strict

Where one or more columns of fit data come from.

Exactly one source key is set:

  • dataset (with optional study and columns): a dataset of this study, or of another study in the same store;

  • result (with keys): exported values of a stored result;

  • ref_uris: streams of the general store, by reference URI;

  • streams: streams of the general store, by source_id and ref_name;

  • resolve: the one general-store stream whose label matches this text;

  • sparql: a read-only SPARQL SELECT whose first column is stream references.

Parameters:
start

Only rows at or after this time.

Type:

datetime.datetime | None

end

Only rows at or before this time.

Type:

datetime.datetime | None

units

Units to convert to: one for every column, or {column: unit} (after rename). A Pyomo unit ("m^3/hr") or a QUDT key ("M3-PER-HR").

Type:

str | dict[str, str] | None

rename

{column: new name}, or {"*": name} for a selector with one column. The surrogate’s variable names are the column names, so they must be the unit’s variable names.

Type:

dict[str, str]

property source: str

Which source key is set.

model_config = {'extra': 'forbid'}

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

class flexorchestrator.fitting.StreamName(*, source_id, ref_name)[source]

Bases: _Strict

A general-store stream by the names its driver registered it with.

Parameters:
  • source_id (str)

  • ref_name (str)

source_id

The datasource, e.g. "historian".

Type:

str

ref_name

The stream’s name in that source, e.g. "FT_101".

Type:

str

model_config = {'extra': 'forbid'}

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

class flexorchestrator.fitting.Validation(*, holdout)[source]

Bases: _Strict

Hold out the end of the data to check the fit on.

Parameters:

holdout (str)

holdout

How much to hold out from the end, as a pandas offset ("7D"); the fit uses the rows before it.

Type:

str

model_config = {'extra': 'forbid'}

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

class flexorchestrator.fitting.Variant(*, name, regressor=None, params=None, spec_options=None, X=None, y=None, window=None, prep=None, validation=None)[source]

Bases: _Strict

One fit of a FitParams with variants; set fields override the base.

Parameters:
name

Rendered into the tag template as {name}.

Type:

str

The other fields are those of FitParams; None keeps the base’s.

model_config = {'extra': 'forbid'}

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

class flexorchestrator.fitting.Window(*, start=None, end=None)[source]

Bases: _Strict

A time window; either end may be open.

Parameters:
start

Rows at or after this time (naive means UTC).

Type:

datetime.datetime | None

end

Rows at or before this time.

Type:

datetime.datetime | None

model_config = {'extra': 'forbid'}

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

The parameters of fit_surrogate, as JSON-friendly pydantic models.

The same parameters arrive from Python, the CLI, a study config’s fits: section and a host app’s HTTP API, so every field is plain JSON.

Load fit data from what a Selector names.

Each selector becomes a pandas DataFrame with a UTC index, the Pyomo unit of each column, and a provenance record of what it resolved to: the dataset run, the result run, or the stream references.

Prepare selected data for a regressor: align, resample, gaps.

X and y must share one index, and later time-series regressors need it regular and gap-free, so the selectors’ frames are joined on their timestamps, optionally resampled, and their gaps dealt with. Every step is recorded with the fit, as is a sha256 of the prepared data (data_hash()): the same data gives the same hash on every run.

Fit runs in <s>::fits: what was fitted, on which data.

Each fit is one run tagged like its surrogate spec, with:

  • fit_params (input): the fit as planned, selectors as sent;

  • training_data (input): what the selectors resolved to, the preparation steps, the row count, the units and the data_hash;

  • fit_result (output): coefficients, metrics, sample count, data window, diagnostics and holdout metrics;

  • fit_series (output, optional): a table of actual, fitted and residual over the training rows, for plotting.

The surrogate spec’s run metadata names the fit run (fit_run_id).