flexparameterize¶
Parameterizes a FlexOps model from tabular plant data. The pipeline is tabular data → tag aliasing → sufficiency validation → regression → apply to model (then {func}`flexops.emit_model` to save it). See Parameterize a model from data.
Any tabular source works, whether that’s a historian export, a spreadsheet, a CSV, or a database query.
Nothing here requires a historian connection. The only requirement is that a
TagMap maps the data’s columns onto the right model aliases.
Tag aliasing¶
Maps a tabular source's column names onto dotted model aliases. |
|
Which source columns no |
- flexparameterize.tags.model_alias(var) str¶
Return the model alias of a registered Pyomo variable.
The alias is the variable’s fully qualified name on its model — e.g.
"facility.plant.power_electrical"for a unitplantin a plant blockfacility, and"facility.plant.inlet_state.flow_vol_phase"for a state-block variable. This is the dottedplant.unit.variableform aTagMap’s values take, and it is unambiguous: an inlet and an outlet state variable share a local name but never an alias.- Parameters:
var – A Pyomo component attached to a model.
- Returns:
The dotted alias.
Sufficiency validation¶
Does the data determine every registered regression problem, satisfying the zero-degree-of-freedom regression condition? The check reports. It never raises.
Whether a data frame determines every registered regression problem. |
|
Data coverage of one registered |
- flexparameterize.validate.check_sufficiency(registry, data: DataFrame, time_block=None, *, min_rows: int = 10) SufficiencyReport¶
Report whether
datadetermines every registered regression problem.Walks each registered IO pair — the cartesian product of a unit’s registered input and output variables, so a unit with several valid pairs gets each checked — and records which of the pair’s aliases are present as data columns and how many non-null rows they carry. Together with the index check this is the zero-degree-of-freedom regression condition: the registered IO pairs exactly determine the regression problem — no unmapped inputs, no free parameters after fit.
Insufficient data is reported, never raised: the caller decides (see
apply_to_model(), which does raise).- Parameters:
registry – A built model to walk, or a single
IORegistry.data – The data frame, with columns already renamed to model aliases by
apply().time_block – The model’s
TimeBlockData; when given, the data index is compared against its horizon.min_rows – Minimum non-null rows a present column must carry.
- Returns:
The
SufficiencyReport.
Regression¶
This is the seam for pluggable regressors. Every regressor conforms to
Regressor, a runtime_checkable
Protocol, and reduces its fit to a shared
FitResult.
Structural contract every pluggable regressor conforms to. |
|
The common shape every regressor's fit reduces to, for provenance. |
Fits the mean energy intensity of a unit from paired flow and power data. |
- flexparameterize.regression.constant.COEFFICIENT_NAME = 'energy_intensity'¶
the parameter the fitted coefficient is stored under in a
SurrogateSpec’sparameters; it is also the name of the process parameter the fit determines on a unit.- Type:
Fits a unit's output as an ordinary-least-squares function of its inputs. |
Fit regression with ARIMA errors and expose the shared fit protocol. |
- flexparameterize.regression.get_regressor(name: SurrogateType | str) type¶
Resolve a
SurrogateTypeto the regressor class that fits it.- Parameters:
name – A
SurrogateTypemember or its string value.- Returns:
The regressor class.
- Raises:
NotImplementedError – If
nameis a reservedSurrogateTypewith no regressor yet (mirrors the correspondingflexops.surrogatesstub class).FlexConfigError – If
nameis not a knownSurrogateTypevalue at all, listing the valid and reserved names.
Sweep configuration¶
Everything a parameter sweep and its fit need: the swept inputs, the recorded outputs and the flex-pse relations they are fitted to, the sampler, the solver, and the holdout and acceptance limits.
Everything a sweep and its fit need: inputs, outputs, sampling and limits. |
|
One swept model input. |
|
One model output to record and fit to a flex-pse unit's relation. |
|
How sweep points are drawn from the input ranges. |
|
How many sweep points to draw, and how. |
|
The solver handed to the optimize function. |
|
Which rows are held out of the fit: those at position p with p % k == r. |
|
Limits the holdout rows must meet for a fit to be returned. |
- flexparameterize.config.config_hash(config: ParameterizeConfig) str¶
Return the SHA-256 hex digest of the config’s JSON dump.
- Parameters:
config – The config to hash.
- Returns:
A 64-character hex string.
Running and fitting sweeps¶
run_sweep and solve_point need the [sweep] extra. See
Fit a surrogate from a parameter sweep.
- flexparameterize.sweep.run_sweep(config: ParameterizeConfig, build_model: Callable[[], ConcreteModel], initialize: Callable[[ConcreteModel], None], optimize: Callable[[ConcreteModel, object], object], *, bounds: dict[str, tuple[float, float]] | None = None) DataFrame¶
Sweep the model over the config’s inputs and return one row per point.
- Parameters:
config – Inputs, outputs, sampler and solver of the sweep.
build_model – Builds a fresh model; called again before every point.
initialize – Initializes a built model at the point’s input values.
optimize – Solves the model with the given solver and returns the solver results.
bounds – Optional
{input: (low, high)}box replacing the config ranges of those inputs for this sweep.
- Returns:
A frame with
index, one column per input and output, andsolve_successful.- Raises:
FlexConfigError – If
boundsnames an unknown input or leaves the config range,parameter-sweepis not installed, or a path or units does not match the built model.
- flexparameterize.sweep.solve_point(config: ParameterizeConfig, build_model: Callable[[], ConcreteModel], initialize: Callable[[ConcreteModel], None], optimize: Callable[[ConcreteModel, object], object], point: dict[str, float]) DataFrame¶
Solve the model at one point exactly as a sweep would and return one row.
- Parameters:
config – Inputs, outputs and solver of the sweep.
build_model – Builds a fresh model.
initialize – Initializes a built model at the point’s input values.
optimize – Solves the model with the given solver and returns the solver results.
point – A value for every config input, inside its range.
- Returns:
A one-row frame with the same columns as
run_sweep().- Raises:
FlexConfigError – If
pointmisses, adds or leaves the range of an input,parameter-sweepis not installed, or a path or units does not match the built model.
- flexparameterize.sweep.fit_sweep(config: ParameterizeConfig, data: DataFrame) dict[str, dict[str, SurrogateSpec]]¶
Fit one surrogate spec per configured output to sweep results.
- Parameters:
config – The config the data was swept with.
data – Rows from
run_sweepandsolve_point, concatenated in any order, with a column per input and output andsolve_successful.
- Returns:
{unit: {relation: spec}}, the shapeapply_to_modeltakes assurrogates.- Raises:
FlexDataError – If a column is missing, more than
max_failed_fractionof the rows failed, fewer than two holdout rows solved, a holdout output is zero, or the holdout misses an acceptance limit.
Applying a fit to a live model¶
This is the FlexParameterize → FlexOps direction of the coupling that runs both ways. It fixes
regressed parameters in place and, where the relationship is richer than the
unit’s default constant intensity, realizes the
SurrogateSpec as a
Surrogate (surrogate_from_spec())
and swaps it in for the unit’s power_electrical_relation Constraint (or
any other relation the unit registered, see surrogates=), keeping the same unit
object and the same ports and arcs.
What |
- flexparameterize.apply.apply_to_model(model, data: DataFrame, tagmap: TagMap, surrogates: dict | None = None, *, active_surrogates: dict[str, str] | None = None, min_rows: int = 10) ApplyReport¶
Fit a built model’s registered parameters from data and mutate it in place.
Every unit that registers a regressable process parameter is fitted from
dataand updated. A unit named insurrogatesis not fitted at all — its relationship is already known in closed form — so no data is required for it and no sufficiency check is run against it; the two paths mix freely across units in one call.- Parameters:
model – The built FlexOps model to mutate.
data – Tabular plant data from any source, indexed by timestamp.
tagmap – The
TagMaprenamingdata’s columns onto model aliases (passTagMap({})if they already are).surrogates – Optional unit name (the unit’s full model name, e.g.
"facility.pump") -> either a hand-builtSurrogateSpec, attached as the unit’s own energy relationship, or a{relation_name: spec}mapping naming one or more of the unit’s other registered relations (seeregister_relation()) — an RO skid’ssplit_definition, a tank’slevel_definition.active_surrogates – Optional mapping of unit name to the local name of a pre-built surrogate block to activate before fitting (e.g.
"surrogate_power"). The block must already exist on the unit from a priorswap_relationcall. When provided,switch_surrogate_blockis called for that unit before any fitting or swapping, so the correct block’s coefficients are registered and can be refitted.min_rows – Minimum non-null rows a data column must carry.
- Returns:
The
ApplyReportdescribing what changed.- Raises:
FlexDataError – If the data does not determine the fit for a unit that has to be fitted; the model is left untouched.
FlexConfigError – If a relationship cannot be attached to its unit.
Native-constraint NLP estimation (not yet implemented)¶
A sibling capability to the regression pipeline above, not a replacement for
it. Instead of fitting a regressor against bare tabular columns, this fits
parameters directly against a unit’s own already built constraint that’s
nonlinear in its parameters (a pump’s hydraulic power law, for example), using
pyomo.contrib.parmest. The shape below is reserved. Every entry point
raises NotImplementedError until it lands.
The result of a native-constraint NLP parameter fit. |
|
Wraps a built unit as one |
- flexparameterize.estimation.estimate_parameters(unit, data: DataFrame, tagmap: TagMap, parameter_names: list[str], *, output_names: list[str] | None = None, measurement_error: dict[str, float] | None = None, cov_method: str | None = 'reduced_hessian', solver: str = 'ipopt') EstimationResult¶
Fit
parameter_namesagainstunit’s own native constraint.Never mutates
unit— seecommit_estimate()for the write-back.Not yet implemented.
- flexparameterize.estimation.commit_estimate(unit, result: EstimationResult) None¶
Write
result.point_estimatesintounitand re-fix each Var.Not yet implemented.