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

TagMap

Maps a tabular source's column names onto dotted model aliases.

TagReport

Which source columns no TagMap entry claimed, and near misses for them.

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 unit plant in a plant block facility, and "facility.plant.inlet_state.flow_vol_phase" for a state-block variable. This is the dotted plant.unit.variable form a TagMap’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.

SufficiencyReport

Whether a data frame determines every registered regression problem.

IOPairStatus

Data coverage of one registered (input, output) variable pair.

flexparameterize.validate.check_sufficiency(registry, data: DataFrame, time_block=None, *, min_rows: int = 10) → SufficiencyReport

Report whether data determines 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.

Regressor

Structural contract every pluggable regressor conforms to.

FitResult

The common shape every regressor's fit reduces to, for provenance.

ConstantIntensityRegressor

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’s parameters; it is also the name of the process parameter the fit determines on a unit.

Type:

str

LinearRegressor

Fits a unit's output as an ordinary-least-squares function of its inputs.

ArimaRegressor

Fit regression with ARIMA errors and expose the shared fit protocol.

flexparameterize.regression.get_regressor(name: SurrogateType | str) → type

Resolve a SurrogateType to the regressor class that fits it.

Parameters:

name – A SurrogateType member or its string value.

Returns:

The regressor class.

Raises:
  • NotImplementedError – If name is a reserved SurrogateType with no regressor yet (mirrors the corresponding flexops.surrogates stub class).

  • FlexConfigError – If name is not a known SurrogateType value 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.

ParameterizeConfig

Everything a sweep and its fit need: inputs, outputs, sampling and limits.

SweepInput

One swept model input.

SweepOutput

One model output to record and fit to a flex-pse unit's relation.

SamplerType

How sweep points are drawn from the input ranges.

SamplerConfig

How many sweep points to draw, and how.

SolverConfig

The solver handed to the optimize function.

HoldoutConfig

Which rows are held out of the fit: those at position p with p % k == r.

AcceptanceConfig

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, and solve_successful.

Raises:

FlexConfigError – If bounds names an unknown input or leaves the config range, parameter-sweep is 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 point misses, adds or leaves the range of an input, parameter-sweep is 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_sweep and solve_point, concatenated in any order, with a column per input and output and solve_successful.

Returns:

{unit: {relation: spec}}, the shape apply_to_model takes as surrogates.

Raises:

FlexDataError – If a column is missing, more than max_failed_fraction of 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.

ApplyReport

What apply_to_model() changed on the model.

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 data and updated. A unit named in surrogates is 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 TagMap renaming data’s columns onto model aliases (pass TagMap({}) if they already are).

  • surrogates – Optional unit name (the unit’s full model name, e.g. "facility.pump") -> either a hand-built SurrogateSpec, 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 (see register_relation()) — an RO skid’s split_definition, a tank’s level_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 prior swap_relation call. When provided, switch_surrogate_block is 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 ApplyReport describing 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.

EstimationResult

The result of a native-constraint NLP parameter fit.

UnitExperiment

Wraps a built unit as one parmest Experiment over its whole horizon.

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_names against unit’s own native constraint.

Never mutates unit — see commit_estimate() for the write-back.

Not yet implemented.

flexparameterize.estimation.commit_estimate(unit, result: EstimationResult) → None

Write result.point_estimates into unit and re-fix each Var.

Not yet implemented.