Changelog

All notable changes to this project are documented in this file. The format follows Keep a Changelog.

[Unreleased]

Added

  • flexparameterize.run_sweep and solve_point sweep a Pyomo model with watertap-org’s parameter-sweep (new [sweep] extra). run_sweep(config, build_model, initialize, optimize) draws the ParameterizeConfig inputs on a grid or a seeded Latin hypercube, rebuilds and re-initializes the model before every point, and returns one row per point with its inputs, outputs and solve_successful. bounds= resamples a box inside the config ranges. solve_point solves one point through the same path, so it returns the row the point would get in a sweep. Both check that every path exists, that swept inputs are fixed Vars or mutable Params, and that units match the model. New page: docs/how_to/fit_a_surrogate_from_a_sweep.md.

  • flexparameterize.fit_sweep fits surrogate specs to parameter-sweep results. A ParameterizeConfig (flexparameterize.config) names the swept inputs, the recorded outputs, the flex-pse unit relation and variable (output_name) each output is fitted to, and the terms to fit. It also sets the sampler, the solver, the holdout rows (position % k == r) and the acceptance limits. fit_sweep(config, data) drops failed points, raising if more than max_failed_fraction failed. It converts each output to the spec’s units, fits it with get_regressor, checks the holdout maximum relative error and relative RMSE (10% each by default) and, if r2_min is set, R^2, and returns {unit: {relation: SurrogateSpec}} for apply_to_model(surrogates=...). Each spec’s provenance records the config hash, a hash of the data, package versions, the fitted input ranges and the metrics.

  • GenericRenewables can be curtailed. curtailable=True frees a new power_curtailed[t] Var (non-negative, kW). Each period, curtailment_balance gives power_delivered = power_generated - power_curtailed, and power_electrical is now -power_delivered. power_generated still targets the swappable relation and now means available output. By default power_curtailed is fixed at 0, so existing models behave as before. power_curtailed is registered as an IO output.

  • Tank takes fix_initial_state and cyclic. fix_initial_state=False leaves the initial_volume Var free and registers no initial state, so a tank can be used in a design study. initial_volume_lower_limit and initial_volume_upper_limit keep the start within the fill window of the chosen capacity. cyclic=True adds cyclic_volume, which requires the final volume to be at least the starting volume.

  • DesignSpec.capex_budget caps total capital spending in a design study (issue #170). When set, build_design_model adds the constraint capex_limit, so the sum of the decisions’ overnight capital costs stays within the budget. This bounds studies whose operating revenue would otherwise push sizes to their upper bounds. Each decision’s capacity[name].capital_cost is now a Var tied to its size by capital_cost_def, in place of an Expression, so set it alongside size when evaluating costs without a solve.

  • flexdesign.investment_metrics reports NPV and IRR for a solved design. It is reporting only and reads a DesignResults plus the baseline annual operating cost by modeled year. It builds yearly cash flows: capital in year 0, savings over the horizon, replacements when an asset’s lifetime ends inside it, and straight-line salvage at the end. It returns an InvestmentMetrics with the cash flows, NPV at the study rate, IRR via numpy-financial (None if there is no sign change) and summary(). horizon_years defaults to the study length, and later years repeat the last modeled year.

Changed

  • idaes-pse is pinned to 2.13.0 (was 2.12.0). WaterTAP 1.8 requires idaes-pse>=2.13, so this lets the two be installed side by side. pyomo stays at 6.10.1.

  • Breaking: ReverseOsmosis.recovery is indexed by time and is no longer a regressable parameter. recovery[t] is fixed at the configured recovery at every step and bounded by recovery_min/recovery_max, so operations or a design study can unfix single steps, and a surrogate can take recovery as a time-indexed input. Code that read pyo.value(ro.recovery) or set ro.recovery.set_value(...) now indexes a step. FlexParameterize no longer fits RO recovery. Other SIDOBlock units keep a scalar, regressable split_fraction; a subclass can opt into a time-indexed split by overriding _declare_split_parameter.

  • add_startup_shutdown’s startup/shutdown are continuous on [0, 1], no longer Binary. With status binary, transition plus the min_uptime/min_downtime rows already force them to 0/1, so each unit now carries T binaries instead of 3T. They are no longer tracked by relax/unrelax; constraints and solutions are unchanged.

  • Breaking: BatteryModel start and cyclic conditions are independent options. fix_initial_state (default True) starts the t=0 balance from charge_init and registers it as initial state. When it is False, charge_init is left free. charge_init_lower_limit, charge_init_upper_limit and charge_init_soh_limit keep the start within the same SOC and state-of-health windows as charge[t]. cyclic=True no longer frees the start or wraps charge[0] to the final charge. It now adds cyclic_charge, which requires the final charge to be at least the starting charge. A spec that relied on cyclic: true for a free start must also set fix_initial_state: false.

  • Breaking: initial states are fixed scalar Vars, not mutable Params: Tank.initial_volume, the electrolyzer’s initial_liquid_volume, BatteryModel.charge_init and the boiler’s initial_heat_output. BatteryModel.charge_start is removed; with fix_initial_state=False the free start is charge_init itself. All four are built with declare_process_parameter, so a sweep can set them through update_parameters and a scenario can unfix them and solve for the starting state in place. Code that called .set_value() on them still works, and pyo.value() still reads them. TimeBlock.register_initial_state now accepts a fixed scalar Var as well as a mutable Param.

  • Breaking: surrogate specs carry config and parameters instead of data (schema 0.2.0). Every SurrogateSpec and flowsheet surrogate element now has the same shape, whether a fit produced it, a live block emitted it, or a person wrote it. config holds everything the surrogate needs besides its fitted values, in the shape its class defines. Examples are variables and units, ARIMA’s order, deterministic, max_ar_coeff and history, and multilinear’s terms. parameters maps each fitted value, by the name the built block registers, to {"value": ..., "fixed": true|false}. A value is a number or a list (nested lists for a matrix), and fixed covers the whole parameter. ARIMA coefficients are now named intercept/drift, ar.L1, ma.L1 and exog.<input>, the names update_parameters already used, so each exogenous coefficient stays paired with its input by name. fixed defaults to true and is always written on emit. A free parameter may omit value to start from the class’s documented guess. Each surrogate type versions its own config with config_version and migrates older versions when it is constructed. load_spec migrates 0.1.1 files automatically, with a FlexMigrationWarning: every coefficient the old build created is listed, fixed at the value the old build gave it, so a migrated spec builds the same model. An ARIMA exog_coefs list with several inputs can’t be paired reliably and is refused, with the equivalent mapping in the error. Saved standalone specs can be upgraded with flexcore.config.surrogate_migration.migrate_surrogate_spec.

  • Breaking: surrogate classes are built from a spec and define their own contract. MultilinearSurrogate(spec), ArimaSurrogate(spec) and surrogate_from_spec(spec) take a SurrogateSpec. Build one with the class’s typed make_spec(...). A class declares config_model, parameter_shapes(config) and _build, and the base class checks the built registry against the contract and applies each parameter’s value and fixed flag. ArimaSurrogate’s max_ar_coeff is now config["max_ar_coeff"], not a constructor argument. constant_intensity gets a class, ConstantIntensitySurrogate, which sets the unit’s energy_intensity instead of swapping a relation. flexparameterize’s regressors build their specs through make_spec, and ArimaTerms.param_names comes from flexops’ arima_parameter_names, so a fit’s coefficient names and a built block’s registry can’t drift apart. surrogate_coefficients is removed from flexparameterize.regression.utils.arima_utils. Since exports are validated now, to_surrogate_spec() refuses an output with unparsable units (such as "" or "%"), which used to produce a spec that couldn’t be built.

  • Breaking: get_surrogate_spec is a pure read that returns a SurrogateSpec; solved state is recorded by update_surrogate_state(). OpsBlock.get_surrogate_spec() used to return a bare data dict with ARIMA’s history rolled forward over the solved horizon. Now it returns the surrogate’s current spec and changes nothing. For the receding-horizon handoff, call unit.update_surrogate_state() after the solve, then get_surrogate_spec() or emit_model. The update rewrites ARIMA’s config.history from the solved horizon; surrogates without time-dependent state are unchanged. ArimaSurrogate.get_surrogate_spec is replaced by solved_history, update_state and read_spec. An unsolved block is refused.

  • CoefficientRegistry supports array parameters. register_coefficient(name, indexed_var, shape=...) registers a whole indexed Var as one parameter (it used to raise), for surrogates with many fitted values such as ML weights. value, set_value, shape, is_fixed, and fix/unfix with an optional name work on scalars and arrays alike. update_parameters and the new update_surrogate_parameters take nested lists for an array parameter, after checking its shape.

  • apply_spec updates a surrogate in place when only its parameters change. When a surrogate element has the active surrogate’s type, config version and config, its values and fixed flags are applied to the existing block. Any other change still swaps a new block in.

  • Surrogate parameters’ fixed state is logged. Building, swapping, applying or emitting a surrogate logs one line, at INFO when any parameter is free (naming them) and at DEBUG when all are fixed.

Fixed

  • LinearRegressor fits inputs on very different scales. scikit-learn’s LinearRegression drops singular values below its tol (1e-6), so inputs in units like m^3/s next to Pa came back with wrong coefficients. fit now scales each column to unit standard deviation before fitting and scales the coefficients back.

  • LinearRegressor fits cross terms that build on the unit. A product column named "a*b" used to be copied into the spec’s input_variables, so MultilinearSurrogate.build looked for a variable called "a*b" on the unit and failed. The product’s factors are now the spec’s inputs and "a*b" is only a term. fit needs input_units for each factor and none for the product column.

  • A flowsheet spec can build an arima surrogate element. Building one raised KeyError: 'order', because ARIMA nested its coefficients under keys that its block registry names differently. With values now keyed by registry name, there is nothing to translate.

  • Emitted surrogate specs describe the live model. emit_model reads each surrogate’s spec back from its active block, so the spec carries the current values and fixed flags, and no raw-path fix/unfix patches are written for surrogates. Several bugs are fixed with it:

    • After switch_surrogate_block, emit wrote the surrogate swapped in last rather than the one switched to, so the rebuild built the wrong surrogate.

    • A predefined surrogate constructed directly, such as MultilinearSurrogate(spec), was left out of the spec as if it were custom.

    • After a second swap, values changed with update_parameters or by unfixing were written as patches on the generated block path. The patches no longer matched the rebuilt block, so unfixed coefficients came back fixed.

    • The rebuild check compared the inactive blocks of earlier swaps too, and patched the rebuild with their values.

  • update_parameters refuses a name that several surrogates on a unit share. On a unit with two surrogates (an RO skid’s split_definition and power_electrical_relation, say), update_parameters({"intercept": ...}) silently changed only the one registered last. It now raises and names the relations. update_surrogate_parameters(values, relation_name=...) is the explicit form.

  • A surrogate naming a variable that isn’t there, or isn’t the right one, is refused. A mistyped output_variables name used to build silently, since only its units were checked, and so did an output naming some other variable on the unit. swap_relation (and so a spec’s surrogate element and apply_spec) now requires the output to resolve on the unit and be the variable the relation determines. An input or output that names a block or constraint is refused with a clear error instead of a KeyError or a misleading units error. A constant_intensity spec’s variables, which used to be unchecked documentation, must name the unit’s intensity basis flow and its electrical power draw, either by local name or by the model alias apply_to_model writes.

  • apply_to_model writes units that a spec can parse back. It recorded Pyomo’s str() of each column’s units (m**3/h), which spec units don’t accept. It now uses units_to_str (m^3/h).

  • Tank and electrolyzer separator holdups now include the first time step. Tank.holdup and the electrolyzer’s liquid_holdup were written only for t = 1, ..., N-1, with volume[0] (liquid_volume[0]) pinned to the initial value, so the flows at t = 0 were in no balance and the first step’s water entered or left for free. Both balances now cover every t, with the starting volume as the predecessor of t = 0, as BatteryModel.charge_balance already did. initial_volume_eq and initial_liquid_volume_eq are removed. initial_volume and initial_liquid_volume are now the level before step 0’s flows, and volume[0] is the level after the first step. Results of models with a tank or electrolyzer change slightly, since the first step’s flows now count.

[0.3.0] - 2026-11-06

Added

  • flexdesign: size equipment across representative months of a multi-year study. A DesignSpec (flexcore.config.design) names a base flowsheet, the modeled years, the representative months and the capacities to size. Its changes list varies any named base element by year, month or both. build_design_model builds one operations model per year and month, merges them under m.horizon[year, month], links each capacity to one shared size, and minimizes annualized operating plus capital cost. Each decision has its own overnight cost and lifetime. A month’s optional days models only its first days and scales the bill up to the full month. design_results reports capacities and annualized costs, with a text summary(). New pages: docs/how_to/run_a_design_study.md and docs/explanation/design_annualization.md.

  • $source in unit options. construction_options now resolve $source references, so a long series such as GenericRenewables.capacity_factor can sit in a file beside the spec.

  • flexops.costing.capital_recovery_factor(rate, lifetime_years) exposes the annuity formula FlexCosting already used.

  • BatteryModel can be sized. A new power_capacity Var (fixed at the larger power limit by default) sizes power independently of energy, through the power_charge_limit and power_discharge_limit rows. cyclic=True ties charge[0] to the final charge instead of initial_soc, and registers no initial state. Breaking: soc is now an Expression, charge / energy_capacity, replacing the Var and soc_capacity_link. soc_min and soc_max are enforced by the linear rows soc_lower_limit and soc_upper_limit, so the battery stays linear when its energy capacity is free. Reading pyo.value(battery.soc[t]) still works, but a fix element or .fix() on soc must move to charge.

  • Breaking: BatteryModel.capacity is now energy_capacity, both the Var and the constructor option, so the two sizing Vars read as energy_capacity (kWh) and power_capacity (kW). SCHEMA_VERSION moves to 0.1.1, and a 0.1.0 spec migrates on load: a BatteryModel unit’s capacity option and any fix or unfix of its capacity are renamed. Extension functions are user code and are not migrated, so one that reads battery.capacity must change by hand. Tank.capacity and GenericRenewables.capacity keep their names.

  • Solve strategies, warm starts, and solver-neutral options (issue #72). get_solver takes strategy= and settings=, and SolverFacade.solve takes explicit tee, warmstart, mip_gap, time_limit and options keywords in place of **kwargs. Direct (the default) solves once. The opt-in RelaxAndFix(fix_tol=0.1) solves the binary relaxation, fixes the binaries it already decided, and re-solves the rest exactly, loosening the tolerance if fixing makes the model infeasible. It leaves the model’s domains and fixed variables as built. warmstart=True works on highs (through appsi_highs), gurobi and cbc; other solvers log a warning and solve cold. mip_gap/time_limit are translated to each solver’s own option name (time_limit bounds the whole solve, across every step; native options are dropped with a warning on a step that falls back to another solver), and SolverSettings.UNIT_COMMITMENT adds Gurobi’s MIPFocus=3, Symmetry=2, Cuts=2. Setting the same native option from two of settings, keyword and options raises ValueError rather than one silently winning. Each solve records a SolveReport (steps, wall time, relaxation bound, gap) on SolverFacade.last_report. classify caches its result on the model until its set of active constraints, objectives, fixed variables or discrete variables changes. New explanation page: docs/explanation/solve_strategies.md.

  • Boiler unit model, fired or heat recovery. flexops.unit_models.powergeneration.boiler.Boiler, selected with boiler_type=BoilerType.FIRED | BoilerType.HEAT_RECOVERY, is a linear steam boiler for scheduling. Fuel comes in through inlet ports (fuel_inlet_names), from utilities billed via register_fuel_usage (utility_fuel_source), or both, each with a heating value. A heat recovery boiler adds a hot gas inlet and a cooled gas outlet (gas_heat_content, stack_temperature), with optional duct firing. Both types have a feedwater inlet (mass conserved through steam_to_water_density_ratio), a steam outlet, a burner limit (max_firing_rate), a backward Euler first-order thermal lag (time_constant, with initial_heat_output as the rolling horizon state), an unpriced heat_dissipated term so ramp-down and shutdown stay feasible, a thermal export registered at the steam temperature, and an auxiliary electrical draw. The swappable relations are heat_absorbed_relation, heat_recovered_relation, steam_flow_relation, steam_pressure_relation, and power_electrical_relation. A new page, docs/explanation/boiler.md, maps each parameter onto an experiment in a detailed boiler model (Taler et al., Energy 175, 2019) and explains which sub-minute transients are left out.

  • Degradation penalties. flexops.logic.add_degradation(unit, spec, costing=None) prices wear on a unit’s variables as a sum of linear terms (variation, deviation, exceedance, throughput), each charged in currency per unit of the driver beyond a per-step deadband. A penalty can also carry a covered cost (free wear cost per period) and a hard horizon budget, both prorated from an optional period_hours. The billable wear cost is registered on FlexCosting as the scalar operating cost <unit>_<name>. The watched quantity and the cost rate are registered relations, so swap_relation can replace them with richer fitted relationships. See docs/explanation/degradation.md.

  • degradation spec element. New DegradationSpec, DegradationTermSpec and DegradationTerm models, and a degradation element kind (DegradationElement) that names its unit and a costing_package ("auto" by default, null for unbilled). A new degradation build stage, after topology and before surrogates, builds it on every member of the unit (so a surrogate element can swap its registered relations), and add_degradation records itself so emit_model writes it back.

Changed

  • An infeasible solve no longer raises on HiGHS. SolverFacade.solve loads a solution only when the solver found one, so an infeasible model returns results with an infeasible termination condition on every solver, logged as a warning, as Gurobi and SCIP already did, instead of raising NoFeasibleSolutionError on HiGHS.

  • Fuel-source validators moved to flexops.unit_models.powergeneration.utils. inlet_names_domain, heating_values_domain, utility_fuel_source_domain, validate_fuel_sources, and heating_value_mismatch are now shared by Combustor and Boiler. Combustor’s behavior and error fields are unchanged.

  • Faster CI. Jobs install with uv and a dependency cache, and no job waits for lint. The full suite runs once with coverage, in the ubuntu/py3.13 unit-tests job, which also enforces the per-subpackage floors (replacing coverage-floors) and makes the only Codecov upload. integration is a single Linux job until integration tests exist. standard-install installs one wheel built by a new build-wheel job. Tests run in parallel with pytest-xdist, now in the dev extra (pytest -n auto).

Fixed

  • classify no longer reports spec-built linear models as NLP. Parsed price units such as kWh**-1 made polynomial_degree() return None, so natively priced LPs were routed to IPOPT. classify now reads the degree from Pyomo’s standard representation, with fixed variables treated as constants.

  • Quantities inside a mapping construction option now build from a spec. build_from_config parses each {"value", "units"} value of a mapping option such as heating_values, so a Combustor or Boiler with heating values round-trips through emit_model/build_model; it previously failed on rebuild. Boiler.boiler_type accepts its value string ("heat_recovery"), as a persisted spec holds it, and the unit contract test now covers Boiler.

[0.2.0] - 2026-10-20

Added

  • Flat, order-agnostic flowsheet spec (FlowsheetSpec, schema 0.1.0). A flowsheet is one flat list of elements (time, property_package, costing, network, plant, set, unit with its connections, surrogate, dispatch, fix, unfix, the logic kinds status, startup_shutdown, dwell, bypass, ramp, startup_delay, conditional, parallel_group, extension and objective). An element’s name is the dotted path of the component it builds, so file order never matters. load_spec/dump_spec read and write it; units can be indexed over a set, connections can be indexed ({i}) or undirected, and {"$package": name} passes a named property package to a unit. The JSON Schema is exported to schemas/flowsheet_spec.schema.json.

  • build_model runs eight named stages (flexops.core.stages.STAGES: declare, topology, surrogates, ramping, logic, state, extensions, costing), costing last so it sees every registered term. flexops.apply_spec applies the mutable kinds (surrogate, dispatch, fix, unfix) to a live model, and apply_relation_spec is the one path that attaches a SurrogateSpec to a live unit (now used by flexparameterize.apply_to_model).

  • Checked fix/unfix. A fix names any variable by ComponentUID path (* matches every index in a position) with one number, a per-time-point list, a {time: value} mapping or a $source file, plus optional units and at. The state stage plans every point first, so it is all or nothing and order-agnostic: conflicting elements raise FlexConfigError. Values outside bounds or domain follow fix_on_violation (default "error"; "warn" and "skip" raise one FlexFixWarning per element) and fix_tolerance; the result is kept as model._flex_fix_report (flexops.FixReport, flexops.FixViolation).

  • flexops.emit_model: code-built model → flat spec. Returns the FlowsheetSpec that build_model turns back into the same model, covering every element kind, logic recorded by the flexops.logic helpers, @flexops.extension calls, and .fix()/.unfix() made in code. It rebuilds the spec and issues a FlexEmitWarning listing anything it can’t express; data_dir= writes long lists to .json.gz sidecars referenced as {"$source": ...}.

  • flexops.core.compare: model_differences lists the structural differences between two models and assert_models_equivalent raises on any.

  • Round-trip corpus and unit contract test. Code-built models in flexops/tests/fixtures/roundtrip_corpus.py and every flexops.unit_models class round-trip through emit → JSON → build with no FlexEmitWarning. New how-to: docs/how_to/round_trip_a_model.md.

  • GridConnection unit model (issue #110). Built on a PlantBlock, it splits the plant’s net electrical draw into non-negative grid_import[t]/grid_export[t] (grid_import - grid_export == total_electrical_power). Optional per-period min_import/max_import/min_export/max_export limits (None = unlimited) replace hand-written constraints on FlexCosting.aggregate_power. Export is priced by FlexCosting(export_prices=...), not by the unit.

  • Per-period boundary limits accept a series. Feed/Product period-basis limits (and GridConnection’s) accept a length-T sequence or a time-indexed Pyomo component as well as a scalar, so a limit can vary by period without rewriting Params after construction.

  • Export prices per carrier. FlexCosting(export_prices={...}), keyed like energy_prices, prices exports of electricity or any fuel below (or at) the import price while staying an LP. Each such carrier’s net series is split into non-negative opex.import_<carrier> / opex.export_<carrier> Vars; an export price above its import price, or a key with no energy_prices entry, raises FlexConfigError. Also available as costing.export_prices in the model config. Models without it are unchanged. (#111)

  • EECO decomposition_type passthrough. FlexCosting(decomposition_type=...) (and costing.decomposition_type in the model config) is forwarded to EECO’s calculate_itemized_cost for the electric and gas legs, in both the in-objective cost and the post-solve bill, so tariff export charges apply to exporting sites. "linear" keeps the model an LP. The bridge functions add_electricity_cost, add_fuel_cost, evaluate_cost and evaluate_fuel_cost take the same argument. Default None is unchanged, except that a tariff with an electric or gas export charge and no decomposition_type now raises FlexConfigError, because EECO otherwise bills the net series as both imports and exports.

  • Optional import/export split in the cost report. report_cost(m, split_imports_exports=True) fills operating.imports and operating.exports, carrier-keyed dicts for every natively priced carrier, alongside the net electricity and fuel; tariff-billed carriers are left out, and the default leaves both None. (#112)

  • Electrolyzer unit models. Electrolyzer, WaterElectrolyzer (PEM/AEM via technology), and CO2Electrolyzer model a stack together with its gas-liquid separators, so every port is single-phase: liquid make-up in, a cathode and an anode gas outlet, and an optional liquid outlet. Stack current drives the linear relations: Faraday’s law per product, power_electrical = N_cells * cell_voltage * current * (1 + bop_fraction), and gas volumes at the fixed operating T/P. The separators hold a liquid inventory, and a waste_heat Expression reports stack heat. The per-product Faradaic relations and power_electrical_relation are registered, so they can be swapped for surrogates. CO2Electrolyzer takes a configurable ElectrochemicalProduct table and adds a CO2 feed set by single-pass conversion, plus carbonate crossover. The anode reaction is an anode_products table (default OXYGEN), so a non-oxygen anode such as chlorine evolution is configurable; WaterElectrolyzer fixes it to oxygen. Each gas port builds from gas_property_package unless given its own package: cathode_gas_property_package, anode_gas_property_package, or (on CO2Electrolyzer) co2_property_package.

  • Electrolyzer current density, ohmic loss, and dissolved CO2. The operating variable is now current_density[t] (A/cm²), set with electrode_area and rated_current_density. current[t] is an Expression, and rated_current is removed. ohmic_loss (bool, default False) sets whether operating_voltage[t] adds area_specific_resistance * current_density, a fixed regressable parameter. Enabling it makes power quadratic in current density and logs a warning. CO2Electrolyzer.co2_dissolved_fraction sends part of the unreacted CO2 out as a dissolved molar flow, co2_dissolved[t], instead of with the cathode gas.

  • Electrolyzer reactant table and liquid anode products. ElectrochemicalProduct.reactants maps each reactant name to moles consumed per mole of product (negative if produced), replacing co2_per_mol and water_per_mol. The unit builds a consumption_{reactant}[t] Expression for each reactant, with water always included; CO2Electrolyzer.co2_consumption is now consumption_CO2. Anode products may now be liquid and leave through the liquid outlet, so reactants such as NaCl and anode products such as hypochlorite can be modeled.

  • Electrolyzer charge balance and CO2 transport limit. A new balance_product option names a cathode product whose rate closes the charge balance (charge_balance_{name}) in place of its own Faradaic relation. Swapped Faradaic curves therefore cannot use more charge than the stack passes. CO2Electrolyzer defaults it to "H2", so faradaic_relation_H2 and faradaic_efficiency_H2 are no longer built there; pass balance_product=None for a product table without hydrogen. CO2Electrolyzer.mass_transfer_coefficient (with co2_bulk_concentration, default 34 mol/m³) adds co2_local_concentration[t] and a linear co2_transport_limit[t] capping the CO2 used at what diffusion delivers.

  • Electrolyzer model explanation page. docs/explanation/electrolyzer_model.md now has a nomenclature table mapping each symbol to its units and model name, the waste-heat equation, the modeling assumptions, a worked PEM operating point checked against the solved model, and a guide to reading a solved schedule. The three electrolyzer classes are registered in the flexdoc table builders.

  • Surrogate coefficient management API. OpsBlockData now exposes list_surrogate_blocks(relation_name=None), current_surrogate_block(relation_name=None), switch_surrogate_block(block_name), fix_surrogate_coefficients(relation_name=None), and unfix_surrogate_coefficients(relation_name=None). When called without relation_name, list/current operate across all relations on the unit, matching the common case of a single-relation unit.

  • CoefficientRegistry supports indexed Vars. The registry now accepts both scalar pyo.Var and indexed pyo.Var objects. register_coefficients detects an indexed Var and iterates over its index set automatically, surfacing a flat name → VarData view to callers. This removes the need for per-coefficient name sanitization in MultilinearSurrogate.

  • MultilinearSurrogate uses a single indexed Var for coefficients. Instead of creating one scalar pyo.Var per coefficient (requiring alphanum_label_from_name sanitization that could collide), build() now creates one coefficient_vars = pyo.Var(index_set, initialize=1.0) keyed by the raw coefficient strings including "intercept". Raw keys like "flow_out*outlet_state.pressure" are preserved exactly.

  • update_parameters works on surrogate coefficients. Registered surrogate coefficient Vars (including indexed-Var entries) can now be mutated in place through the standard update_parameters path. The fitted constraint body sees new values without any component rebuild.

  • Comprehensive tests for surrogate block lifecycle. New tests cover switching among 3+ surrogate blocks with correct activate/deactivate semantics, list_surrogate_blocks and current_surrogate_block with and without relation_name, named-relation fix/unfix, CoefficientRegistry duplicate/non-Var/bulk registration, and update_parameters on surrogate coefficients.

  • AR stability bound is now enforced during fitting, for both backends. ArimaRegressor(max_ar_persistence=0.85) now bounds AR coefficients to [-0.85, 0.85] during the fit itself (via bounded least squares), instead of only rejecting the fit afterward. ArimaSurrogate(data, max_ar_coeff=0.85) adds the same bound on the Pyomo side: a supplied coefficient beyond the bound raises immediately, and an unfixed one (regression mode) is bounded during solving.

  • ArimaRegressor can fit the criterion the Pyomo surrogate actually runs. forecast_horizon minimizes windowed free-run error: the series is cut into windows of H steps, each seeded from actual data and simulated forward with innovations at zero, as the surrogate forecasts. The horizon is an int number of steps (default 1) or a duration such as "2D", "48h" or pd.Timedelta(days=2), the same forms to_surrogate_spec(history_length=...) takes, which fit() rounds up to whole steps of the training index. At H=1 that is exactly the classical one-step (equation-error) fit, which stays the default and keeps its vectorized solve; a longer horizon refines that fit. There is no separate fit_objective option. Longer horizons exist because a d=1 model integrates its drift term: drift is nearly unidentified by one-step residuals yet accumulates over a forecast. In a held-out benchmark on the biogas data (4-day train, 2-day forecast, 11 starting points, 13 orders), forecast_horizon=192 cut mean d=1 forecast RMSE from 0.0095 to 0.0065 and made no difference for d=0, but it refused 17 of 143 fits that the default fit without complaint. The gain was concentrated in (0,1,1) and (2,1,2), which improved at 91% of starting points; elsewhere it was a coin flip. The in-sample 2.9x free-run improvement first measured for ARIMA(3,1,3) did not carry over to held-out data in the same form. Set the horizon to the one you intend to forecast over; restarting each window from data is what keeps the fit fast and grounded, since a single window over 5757 rows left the d=0 objective so flat that least_squares ground to its 5000-evaluation limit.

  • metrics["free_run_rmse"], plus ma_max_root and forecast_horizon in fit_diagnostics(). The free-run error is reported at the fit’s own horizon, so at the default forecast_horizon=1 it equals the one-step rmse. It is in-sample, and a longer-horizon fit minimizes it directly, so compare horizons on held-out data rather than on this number.

  • Fits with forecast_horizon > 1 are kept stable. Every MA coefficient is bounded to [-0.99, 0.99], and a fit whose MA block is still non-invertible (possible for q >= 2) raises FlexConfigError. Unbounded, the free-run objective pushed MA roots as far as 1.24, and because the forecast seeds its MA lags from one-step residuals, first-step forecasts reached ~1e6 at 8 of 11 held-out starting points for some orders. At the default forecast_horizon=1 MA is fully identified, so it is not bounded and a non-invertible block only warns: it is common (8 of 11 starting points for (1,0,1) on biogas) and harmless for forecasting, since the forecast seeds from the residuals that fit minimized.

  • fit() rejects a non-stationary AR block at every horizon. Bounding each AR coefficient by max_ar_persistence does not make the block stationary – [0.85, 0.85] has a root of ~1.44 – and long-horizon fits produced exactly such fits, whose forecasts diverged within a few steps. fit() now raises FlexConfigError when the largest AR root reaches the unit circle. This replaces the old per-coefficient post-check, which by construction could only fire on floating-point slop at the bound. With max_ar_persistence=None the check still applies.

  • FlexCostingData.relaxation_gap(model, results) returns reported bill - in-objective proxy post-solve (positive: the objective understated the bill). It raises FlexSolverError if results is not an optimal solve.

Changed

  • ArimaRegressor(auto=True) uses its own order search; statsforecast is no longer a dependency. statsforecast 2.1+ requires pandas<3, so with the core pandas>=3 pin pip fell back to 2.0.3, which caps scipy<1.16. That downgraded scipy on Python 3.11-3.13, and on 3.14 (no scipy 1.15 wheels) pip tried to build scipy from source and failed. The new search picks d from KPSS (null: stationary) and ADF (null: unit root) tests at 5% on the disturbance y - X @ beta: d=1 when only KPSS rejects, d=0 when only ADF rejects. When both reject (contradictory) or neither does (inconclusive) it raises FlexDataError, suggesting more exogenous covariates (e.g. lagged inputs), removing trends or seasonality, or passing d=0/d=1 explicitly; a series too short for ADF is refused the same way. ADF comes from statsmodels, imported only when d is tested, so it needs the [parameterize] extra and import flexparameterize.regression works without it. It then fits every (p, q) within the limits by one-step least squares (under max_ar_persistence, as the final fit is) and picks the lowest AIC among stationary, invertible candidates, all scored over one common sample after a 10-step burn-in. Search options are now validated when the regressor is constructed: max_p, max_q, max_order (default 5 each), max_d (0 or 1, default 1), d, and stationary. Any other keyword raises FlexConfigError, where it was previously forwarded to AutoARIMA. max_d=2 or d=2 is now refused at construction instead of after the search. Selected orders may differ from AutoARIMA’s. [parameterize] also no longer pulls in numba, fugue, pyarrow, or coreforecast.

  • ARIMA surrogate specs keep a trailing history window instead of the whole training series. ArimaRegressor.to_surrogate_spec(history_length="7D") keeps the last history_length of fitted disturbances and innovations plus the max(p + d, q) lags ahead of them, and moves history.start_date to the first kept point; the default is one week. ARIMA state is Markov in those lags, so a horizon starting inside the window or after it initializes exactly as before. history_length=0 keeps only the terminal state for forecast-only use, and None keeps the full series (the old behavior). A horizon that starts before the kept window now raises an error naming the fix. emit_model_config(..., spec_options={...}) forwards the option. The persisted key history.y_values is renamed history.eta_values, since it holds the disturbance y - X @ beta, not the output; specs saved with y_values must be re-exported.

  • ARIMA fitting machinery moved to flexparameterize.regression.utils.arima_utils, and shrank from 2,700 lines to about 1,790 across both files. arima.py now holds only ArimaRegressor. The fitting and forecasting machinery – ArimaTerms (the parameter-vector layout that used to be passed around as nine positional arguments), DirectResults, the residual functions, and the AutoARIMA backend – lives in the new internal module. The three hand-written copies of the forward recursion (in-sample prediction, out-of-sample prediction, output-error windows) are now one free_run, and both recursions run through scipy.signal.lfilter. Fits are 5-15x faster, and the default one-step fits reproduce the old coefficients to ~1e-9. The separate OLS paths for pure-AR and no-lag models are gone, since one least-squares fit started from the same OLS estimate reaches the same optimum. Helper tests moved to tests/regression/utils/test_arima_utils.py, with plain-loop reference implementations pinning the vectorized recursions. Internal API changes: regressor.model.model.k_ar/k_diff/… is now regressor.model.terms.p/d/…; predict(start=...) raises FlexDataError instead of indexing out of range when start leaves fewer than max(p + d, q) rows of history; and the in-sample MA lags before the first defined innovation are zero-padded, as in the surrogate’s history, rather than dropping the MA term.

  • ARIMA one-step rmse no longer counts the artificial first row of a d=1 fit. The level-scale fitted values set row 0 equal to the data, which counted as a zero-error point. rmse is now exactly sqrt(sigma2) over the rows the equation defines. A no-parameter fit (order=(0, d, 0), include_mean=False, no inputs) no longer silently centers its residuals on the series mean, which no coefficient represented.

  • ArimaSurrogate.get_surrogate_spec(block, target) no longer takes time_index. The parameter was validated as a contiguous prefix of the local horizon and then ignored – the extracted history always spanned the full horizon regardless. OpsBlockData.get_surrogate_spec no longer passes it. No backward compatibility is kept for the old three-argument form.

  • ARIMA information criteria now exclude the zero-padded leading residuals. resid keeps its full length for alignment, but the leading max(p, q) entries carry no residual, and dividing by them understated sigma2 and inflated the log-likelihood. llf, aic, bic, and sigma2 are now computed over the new DirectResults.effective_resid / nobs_effective, so reported values shift (more so for high orders on short series) and fit_diagnostics()["n_samples"] is now the effective count rather than the padded one.

  • ArimaRegressor.to_surrogate_spec() omits the deterministic term when the fit has none. With include_mean=False and d=0 the spec previously carried intercept: 0.0, which the surrogate reads as a real (fixed) intercept Var rather than as “no intercept”. Presence of the key now tracks the fit, so a term that genuinely fits to 0.0 is still emitted, while include_mean=False emits nothing. to_fit_result() matches, and no longer drops a legitimately-zero const.

  • ArimaRegressor drops the statsmodels/statsforecast look-alike options that did nothing here. seasonal_order is gone: only None or the no-op (0, 0, 0, m) was accepted, and with auto=True it only switched on a seasonal AutoARIMA search whose results fit() then had to reject. include_drift is gone: for d=1 it was an alias for include_mean, and for d=0 an error. stationary is gone as a named argument; it still reaches AutoARIMA through **auto_kwargs (ArimaRegressor(auto=True, stationary=True) works as before). DirectResults.predict() loses dynamic, which only ever accepted True. aicc is removed from DirectResults and fit_diagnostics() (previously None when undefined); aic and bic remain. The AutoARIMA search is now always non-seasonal, so auto_kwargs may no longer set seasonal or ic, which raise FlexConfigError. Extra keywords without auto=True now raise FlexConfigError too; they used to be silently ignored, which would have hidden the removed options. No backward compatibility is kept.

Fixed

  • ArimaRegressor.fit() misaligned or crashed on null rows when it had exogenous inputs. Null rows were dropped from y but the full, undropped X was passed to the fit, giving a shape mismatch (or a silent row shift). Inputs are now taken from the same null-dropped frame as the output.

  • The MA-warning test could never fail. flexcore’s logger does not propagate, so caplog never saw the warning and "non-invertible" not in caplog.text held unconditionally. ARIMA tests now capture the module logger directly.

  • ArimaRegressor.fit() raised ZeroDivisionError on short series. fit() computes AICc via model_, so an order the row-sufficiency check accepts – e.g. order=(0, 0, 0) on three rows – crashed inside _aicc_from_direct instead of fitting.

  • ArimaSurrogate accepted a history too short to build from. _validate required len(y_values) >= p + d and len(eps_values) >= q, but build() slices both out of a shared max(p + d, q) prefix. With q > p + d a short history passed validation and then failed in build() with a misleading “y_values and eps_values must contain the same number of modeled points”. Both series are now checked against max(p + d, q) up front. Regression mode, which supplies no history at all, is unaffected.

  • ARIMA docstrings corrected. ArimaRegressor.predict() no longer claims steps=0 returns in-sample fitted values (it returns an empty array); _auto_select_order no longer claims non-seasonal d is forced to 0 (only seasonal D is); fit() now documents its real row-sufficiency requirement instead of order[2] + 1; to_surrogate_spec() documents the history field it actually emits rather than a nonexistent initial_state; and the AIC/BIC/AICc/log-likelihood/sigma2 statistics now carry an explicit note that they are computed over zero-padded leading residuals and so are not comparable to statsmodels. ArimaSurrogate.build() and get_surrogate_spec() gained their missing Args/Returns/Raises sections, the latter documenting that time_index is validated but that the extracted history always spans the full horizon.

  • Two ARIMA cross-validation tests were mismarked as unit while solving with ipopt. test_pyomo_matches_direct_fit_for_multiple_arima_orders and test_reswapping_arima_relation_succeeds_and_uses_latest_coefficients are now component + needs_ipopt, per the rule that unit tests must not invoke a solver.

  • Removed dead ARIMA code. The innovation_square Expression on the surrogate block (never read; get_regression_objective squares eps itself), ArimaRegressor._fitted_values (assigned, never read), the unreachable _DirectResults.fittedvalues_level reconstruction fallback (the array is always supplied by _fit_direct, and its d > 1 branch was wrong for a class that only allows d <= 1), and the commented-out seasonal-order placeholder in to_surrogate_spec. The tautological test_surrogate_spec_seasonal_order_none_without_seasonal, which asserted a key that is never present, is gone with them; seasonal orders remain rejected at construction.

  • test_arima_roundtrip compared signed relative deviations. np.max((a - b) / b) let an arbitrarily large negative in-sample or forecast deviation pass the < 1e-4 gate; both checks now compare magnitudes.

  • ArimaRegressor.predict(dynamic=True, start=...) no longer leaks real residuals past the first forecast step. The in-sample branch now zeros the MA lag after step 0, matching its own documented contract and the out-of-sample branch, so it agrees with the Pyomo surrogate’s zero-future-innovation forecast.

  • ArimaRegressor.predict() fixed an off-by-d indexing bug where self._resid (aligned to the differenced series) was sliced using a level-index start unshifted by d, silently misaligning the MA lookback for every d=1, q>0 model.

  • An infeasible solve no longer raises on HiGHS. SolverFacade.solve loads a solution only when the solver found one, so an infeasible model returns results with an infeasible termination condition on every solver, logged as a warning, as Gurobi and SCIP already did, instead of raising NoFeasibleSolutionError on HiGHS.

  • Fuel-source validators moved to flexops.unit_models.powergeneration.utils. inlet_names_domain, heating_values_domain, utility_fuel_source_domain, validate_fuel_sources, and heating_value_mismatch are now shared by Combustor and Boiler. Combustor’s behavior and error fields are unchanged.

  • Faster CI. Jobs install with uv and a dependency cache, and no job waits for lint. The full suite runs once with coverage, in the ubuntu/py3.13 unit-tests job, which also enforces the per-subpackage floors (replacing coverage-floors) and makes the only Codecov upload. integration is a single Linux job until integration tests exist. standard-install installs one wheel built by a new build-wheel job. Tests run in parallel with pytest-xdist, now in the dev extra (pytest -n auto).

  • BREAKING: the nested ModelConfig format is removed. ModelConfig, NetworkConfig, PlantConfig, ArcSpec, load_model_config, dump_model_config, load_surrogate_source, SurrogateSpec.source and flexparameterize.emit_model_config are gone; write configs as flat specs, and save a parameterized model with apply_to_model then flexops.emit_model. The unbuilt UnitCommitmentConfig fields (startup_shutdown, dwell, min_up, min_down, delays, conditional) are removed; use the logic elements instead.

  • Status rules are checked when the model is built, by asking each unit. A unit refuses status elements by setting allows_status_element = False (as Tank and BatteryModel do), and logic that needs a status checks that the built unit has one. FlowsheetSpec no longer lists unit classes (SELF_STATUS_CLASSES and NO_STATUS_CLASSES are removed), so load_spec accepts these two mistakes and build_model raises FlexConfigError for them, still before any solve. (#126)

  • build_model now expands arcs by default (expand_arcs=True), so logic and extensions can use the expanded equalities. Pass expand_arcs=False for the old behavior.

  • Relative paths in a spec resolve against the spec file’s directory (the working directory for a spec given as a dict).

  • register_surrogate_coefficients now uses registry key names for ParameterRecord. When coefficients are stored in an indexed Var, the parameter name stored in the IO registry is the raw coefficient key (e.g. "flow_out*outlet_state.pressure"), not the parent block’s local_name. This makes target removal and parameter lookup correct for all coefficient storage modes.

  • swap_relation fitted constraint activation. switch_surrogate_block now explicitly activates the fitted Constraint after block.activate(), because Pyomo Block.activate() does not cascade to child Constraint objects that were explicitly deactivated.

  • EECO pinned to eeco==0.4.2 (from 0.4.1). 0.4.2 adds the "linear" decomposition type, an LP split of net consumption into imports and exports.

  • EECO pinned to eeco==0.4.1 (from 0.4.0). 0.4.1 prices a top tier at one constant rate exactly in the objective, with no estimate, so the demo tariff’s tier2 surcharge is no longer dropped.

Fixed

  • Unit-model reference pages render their tables again. The unit-model autosummary entries named the unit_model.rst template by a path Sphinx could not resolve, so every page silently fell back to a bare autoclass with no members and no Variables, Constraints or Degrees of Freedom tables. A unit with no registered inputs (Feed, GenericRenewables) now renders “None.” under Degrees of Freedom instead of an invalid empty table.

  • parse_units reads the chained divisions and unit numerators Pyomo prints (kg/m^2/s, J/kg/K, 1/s); it previously stopped at one / and rejected a bare 1.

  • A flat spec’s list-valued price ({"value": [...], "units": ...}) and quantity-valued property-package options (e.g. density) now build; both previously raised.

  • A tiered tariff charge could silently price at $0 in the objective (issue #73). opex.py never forwarded a consumption estimate to EECO, which without one drops every tier other than a flat top tier. The new CostingConfig.consumption_estimate / FlexCosting(consumption_estimate=...), a mapping of EECO utility ("electric"/"gas") to the estimated total consumption over the horizon (kWh / m^3), is forwarded through add_electricity_cost/add_fuel_cost/add_operating_cost. The default None keeps the previous behaviour. A warning is now logged when a tariff tier would be zeroed because its utility has no estimate, and CostingConfig.consumption_estimate only accepts the keys "electric" and "gas".

[0.1.0] - 2026-09-04

flex-pse 0.1.0 is the first release. It ships flexops and flexparameterize: build a plant imperatively in Python or from one versioned JSON config (flexops.build_model); model unit commitment (on/off, dwell, startup/shutdown delays, conditional and parallel-train ordering, bypass); price tariff- and demand-response-aware operating cost through EECO, reported post-solve from the de-relaxed realized dispatch (never the solver’s own objective); and round-trip parameterize a model from tabular plant data (fit -> apply in place, or emit a config, both from the same regressor so they cannot disagree). Single-period design-mode costing (set_design_mode/ set_operations_mode) works; the multi-period design wrapper does not exist yet.

Deferred to 0.2 or later (PLAN.md §4, “Post-0.1.0 backlog”): flexschedule ships as an unpopulated scaffold — rolling-horizon scheduling and solve sequences, and set-point extraction/smoothing, are not implemented; the multi-period flexops.design wrapper; multi-dimensional surrogates and multi-component property packages; and the further backlog (parallel-train replication helpers, a working demand-response formulation, a scenario/sweep tool, an external forecaster interface, and more).

Removed

  • examples/ is gone. Worked examples and notebooks move to the companion repo flex-pse-examples, published as an interactive site at flex-pse.github.io/flex-pse-examples; the marimo pump_tank_load_shifting/ demo goes with them. The frozen-API tripwire is unaffected in substance but has moved: api_freeze.py, api_freeze_config.json, and the tariff.json/dr_events.json fixtures now live under src/flexops/tests/fixtures/api_freeze/, next to the test that runs them, and the ruff/black excludes that keep the script byte-for-byte identical to the PLAN.md §2 snippet moved with it. Anyone running the frozen script by hand should copy that fixture directory rather than examples/.

Added

  • The docs system is finished. docs/_ext/flexdoc.py adds two generated-content Sphinx directives: flexops-unit-tables builds a unit-model class on a throwaway model and renders its Variables/Constraints/Degrees-of-Freedom tables straight from the built model’s registered IO and Pyomo constraints (never hand-written, so a reference page cannot drift from the code it describes), and flexops-config-table renders a pydantic config model’s fields. Every public unit model — the SISOBlock/SIDOBlock/DIDOBlock topology bases and the full collection of flex-pse’s native physics-based unit models (Pump, Tank, BatteryModel, Exchanger, ReverseOsmosis, Combustor, GenericRenewables, Feed, Product, Mixer, Splitter, Digestor, ConstantEnergyIntensityModel) — now renders these generated tables via the unit_model.rst autosummary template. docs/explanation/config_schema.md renders the full ModelConfig field tree the same way. New docs/explanation/reported_cost.md explains, in plain language, why the number in a cost report is never the solver’s internal objective. docs/reference/flexparameterize/index.rst gains a section for the flexparameterize.estimation native-constraint NLP estimation API, documented as the reserved, not-yet-implemented surface it is. src/flexops/tests/docs/test_flexdoc_tables.py is the unit test guarding against flexdoc silently emitting empty tables.

Changed

  • Public docs — and every public docstring that renders into them — no longer cite internal milestone/decision codes. Every page under docs/ and every rendered class/function/module docstring across flexops, flexcore, and flexparameterize dropped its M09/R3/§-style references, in favor of plain-language explanations — readers of the published docs have no access to plan/, so those citations pointed nowhere. Several pages that had gone stale relative to the actual codebase (the arc/topology layer described as “M09, future” when NetworkBlock/PlantBlock/Arc composition has long since landed; a rolling-horizon relaxation pipeline described as available when flexschedule does not exist yet) were corrected to describe the platform as it actually behaves today. New rule recorded in the conventions and the docs milestone.

  • No more notebook execution in this repo’s docs build. The companion repo flex-pse-examples has moved on from Jupyter notebooks pulled into this repo’s Sphinx build via myst-nb/nb_execution_mode to its own marimo + WebAssembly site with a precomputed-data pipeline and independent GitHub Pages deploy. Rather than force a stale integration model, docs/conf.py drops myst_nb/nb_execution_mode for the lighter myst_parser (Markdown parsing only, no notebook machinery to speak of), and new docs/examples/index.md links out to the live flex-pse-examples site instead of embedding and executing notebooks. docs.yml (replacing build-docs.yml) builds and deploys this repo’s own docs only, with no cross-repo checkout step; there is no nightly.yml, since there is no longer a notebook-execution safety net to run. The docs extra swaps myst-nb for myst-parser accordingly.

  • BREAKING: a unit’s constant energy intensity is now metered on its product flow, not its inlet. OpsBlockData.add_constant_intensity_relation keys power_electrical[t] to the flow the unit delivers, so energy_intensity reads as energy per unit of output. ConstantEnergyIntensityModel and Pump move to the outlet flow (numerically unchanged — the SISO pass-through ties it to the inlet), Exchanger to flow_out_a, and ReverseOsmosis to permeate, which does change value: its 3.0 kWh/m^3 default is now the specific energy consumption per m^3 of permeate that the desalination industry quotes, so at a recovery below one the same number means a smaller absolute draw than the previous feed-based reading. The Pump hydraulic relation is untouched — it is a physical power law, not an energy intensity. The basis is recorded per PowerKind on the new IORegistry.intensity_basis, and flexparameterize.apply_to_model regresses against exactly that stream (falling back to a unit’s single non-power registered output for a unit that hand-rolls its relation, as Pump still does).

  • BREAKING: SurrogateSpec names a predefined surrogate class instead of an open-string builder; schema_version is now 0.0.3. functional_form/coefficients/input_variables/output_variables are replaced by surrogate_type (a SurrogateType enum member) and an opaque data mapping in the shape that class defines. The class (flexops.surrogates) validates data in its __init__ and builds the Pyomo relationship in build(); a type not yet implemented raises NotImplementedError at build time, an unknown surrogate_type name is rejected at config-validation time (an improvement over the old open string, which deferred that check to the build). MIGRATIONS["0.0.2"] rejects a config whose surrogate is still in the old shape — the coefficient grammar cannot be mechanically translated into a class’s data contract — telling the user to re-emit it; the exported JSON Schema is regenerated.

  • multilinear is the one implemented surrogate class, covering what were linear (no cross terms) and bilinear (one cross term): a constant plus a sum of coefficient * (product of distinct declared inputs). quadratic/polynomial/^-exponent terms are gone; a coefficient key is a *-separated product of names from data['input_variables'], each appearing at most once, plus the reserved intercept. New: every input and output declares its own units (data['input_variables']/['output_variables'] are {name: units} mappings, not bare name lists) — the basis the relationship was fitted or written in, not necessarily the model’s own. Each factor is converted from its actual unit into its declared one before the coefficient multiplies it, and the whole body is converted from its declared output units into the registered target’s own units; both conversions double as validation, raising FlexConfigError on a dimensionally incompatible declaration instead of silently rescaling. QuadraticSurrogate/ExponentialSurrogate/ArimaSurrogate/NeuralNetworkSurrogate are reserved classes raising NotImplementedError, naming MultilinearSurrogate as the implemented alternative.

  • BREAKING: OpsBlockData.swap_energy_relation is gone, replaced by register_relation/swap_relation. The swap is no longer power-specific: register_relation(constraint, target) declares any relationship a unit builds as swappable (an unregistered constraint — a mass balance, any conservation law — can never be swapped: there is no naming convention to accidentally satisfy), and swap_relation(relation_name, surrogate) replaces it in place, taking a live flexops.surrogates.Surrogate instance (built via surrogate_from_spec) rather than a SurrogateSpec directly, and resolving units from the relation’s own target rather than assuming kW. Every constant-intensity unit registers its own energy relation automatically; SIDOBlock/ReverseOsmosis additionally register split_definition (recovery/flux) and Tank its level_definition (fill geometry) — conservation constraints on both are deliberately not registered. Pump’s default relation is folded onto the shared add_constant_intensity_relation path (previously hand-rolled as power_eq with a mutable Param), so it is renamed to power_electrical_relation, its intensity becomes a fixed, regressable Var, and it is swappable for the first time; the hydraulic power law is untouched (a physical relationship, not an intensity, and not registered). flexparameterize.apply.ApplyReport.swapped_units: list[str] is replaced by swapped_relations: dict[str, list[str]] (unit -> relation names), and apply_to_model’s surrogates= values may now be a {relation_name: spec} mapping to swap a unit’s other registered relations (an RO skid’s recovery, a tank’s geometry) instead of its energy draw, mixed freely with the plain-spec form across units in one call.

  • The swap is not limited to flexops.surrogates’ own classes. swap_relation calls surrogate.build(unit, target) on whatever Surrogate it is given — any Pyomo-expressible function of the unit’s own variables, returning pyomo.environ.Constraint.Skip for a horizon point a lag does not reach, and free to attach its own auxiliary Vars/Constraints, which a later re-swap deactivates alongside the relation itself. Registering a new shape is a new Surrogate subclass, never a config-schema change.

Added

  • flexops.surrogates: the predefined surrogate-structure classes (Surrogate ABC, SURROGATES registry, surrogate_from_spec), a leaf subpackage of flexops (imports only flexcore and Pyomo) so a config’s surrogate is realized at unit construction time with no flexparameterize import anywhere in flexops. See “Changed” above for MultilinearSurrogate and the four reserved stubs.

  • flexops.core.units.parse_units, extracted from flexops.core.build (still re-exported there) into a leaf module flexops.surrogates can import without a cycle.

  • flexops.core.registration.RelationRecord/IORegistry.relations and iter_swapped_relations(model): a whole-model, O(registered relations) debugging/reporting aid answering “what in this model differs from its defaults?” for a model built any way (config, by hand, or apply_to_model) — not a required step on any build or apply path, and not a detector of changes made outside swap_relation.

  • flexcore.config.io.load_surrogate_source and the new SurrogateSpec.source field: a relationship may live in a JSON sidecar supplying data instead of being inlined in the config. A relative path resolves against the config file’s own directory, and load_model_config fills every unit’s surrogate in at the boundary, so nothing downstream sees a half-loaded relationship.

  • flexparameterize: the parameterization pipeline, in both directions. tabular data -> tag aliasing -> sufficiency validation -> regression -> {apply to model | emit config} (architecture §5, R10). New public API: TagMap/TagReport/model_alias (tags.py, source-column to dotted plant.unit.variable aliasing, JSON-loadable, difflib suggestions for unmapped columns and no new dependencies); check_sufficiency/SufficiencyReport/IOPairStatus (validate.py, per-registered-IO-pair coverage, non-null counts and DatetimeIndex alignment — it reports, it never raises); ConstantIntensityRegressor (regression/constant.py, intensity = mean(power / flow) after dropping null and zero-flow rows, with r2/rmse/n_samples/data_window); emit_model_config (emit.py, fit -> a ModelConfig that build_model rebuilds the parameterized model from, with provenance carrying the fit metrics, data window and the flex-pse/pyomo/pandas versions read at emit time); and apply_to_model/ApplyReport (apply.py, fit -> an in-place mutation of a live model: registered parameters are fixed at their fitted values and a richer-than-constant-intensity relationship deactivates the unit’s power_electrical_relation and attaches an equality built from the SurrogateSpec, on the same unit object with its ports and arcs untouched). Both directions consume the same SurrogateSpec from the same regressor, so they cannot disagree; apply_to_model raises FlexDataError up front on insufficient data, since it mutates a real model. Both also accept a hand-built SurrogateSpec directly — a vendor curve or datasheet coefficient needs no data, no sufficiency check and no regressor — and apply_to_model’s surrogates= and fit-from-data paths mix freely across units in one call. Nothing in the package assumes a historian: any tabular source works once its columns are mapped.

  • Docs: docs/how_to/parameterize_from_data.md (the pipeline stage by stage, both terminal directions, and the no-fit path), docs/reference/flexparameterize/index.rst, and a new docs/reference/glossary.md defining zero-degree-of-freedom regression and model alias.

  • The pluggable-regressor protocol, and LinearRegressor. flexparameterize.regression.base.Regressor (a runtime_checkable typing.Protocol: fit(X, y) -> Self, to_fit_result() -> FitResult, to_surrogate_spec(**kwargs) -> SurrogateSpec) and FitResult (coefficients/metrics/n_samples/data_window) formalize the shape every regressor’s fit already reduced to by hand; ConstantIntensityRegressor gains to_fit_result() with no other change. LinearRegressor (regression/linear.py, needs the [parameterize] extra’s new scikit-learn dependency, imported lazily so the extra-less package still imports cleanly) fits an ordinary-least-squares line — one output, one or more input columns, no automatic cross terms — and emits a multilinear SurrogateSpec consumed identically by apply_to_model and emit_model_config. flexparameterize.regression.get_regressor(surrogate_type) resolves a SurrogateType (member or string) to the regressor that fits it, raising NotImplementedError for the four still-reserved types and FlexConfigError for an unknown one. emit.py’s _surrogate_and_fit_provenance now reads a fit’s four provenance fields off to_fit_result() instead of the regressor’s own attribute names, so a future regressor needs no emit-path change.

  • Feed(property_package, outlet_names=("a",), resource_name=None, min_withdrawal=None, max_withdrawal=None, withdrawal_basis="period", price=None) and Product(property_package, inlet_names=("a",), resource_name=None, min_demand=None, max_demand=None, demand_basis="period", price=None): the two boundary blocks flex-pse was missing. Until now a feed was made by fixing an inlet state block’s flow_vol_phase by hand, and a product existed only as a bare PlantBlockData.register_product(...) call against some other unit’s variable — nothing owned a boundary stream, metered the total resource crossing it, or priced it. A Feed is a source (zero inlets, N named outlet_{name} ports) that carries the boundary state, meters withdrawal[t] through the equality eq_withdrawal, and passes its composition/pressure/temperature downstream over arcs; a Product is the mirror sink (N named inlet_{name} ports, zero outlets) aggregating delivery[t] through eq_delivery. Both subclass OpsBlockData directly, since a config-driven port count fits no fixed-arity topology base, and neither declares power_electrical or power_thermal — a boundary block has no energy relation.

    • Composition is whatever the property package carries. There is no new quality concept: the boundary state block’s variables (IDAES on-demand properties included) are the composition. On a Feed, the reference outlet — the first name in outlet_names — carries the boundary conditions and every other outlet is held at it by outlet_state_equality_{state_var}[t, name]: one source, one condition. A Product deliberately does not blend; each inlet’s intensive states arrive from its own arc and stay independent, because blending is Mixer’s job and is bilinear.

    • resource_name is the aggregation key, independent of the Pyomo block name, and defaults to that block name so plant.raw_water = Feed(...) and plant.citric_acid = Feed(...) are distinct resources with no extra config. Two blocks sharing a resource_name sum into one row — how the same resource entering at two points is modelled — while costing stays per block: the opex line item is named from the block’s own dotted Pyomo name (sanitized), so blocks sharing a resource still get separate, differently-priced line items. Many Feed/Product blocks per plant is the expected case, not the edge case; one block carries one resource.

    • Limits are mutable per-period Params, not variable bounds. min_withdrawal/max_withdrawal (and min_demand/max_demand) take a units-carrying scalar and build withdrawal_min/withdrawal_max plus their _limit Constraints, converted onto the flow basis. Params rather than setlb/setub because set_value is the sanctioned in-place update path (conventions §9), because they survive set_external_dispatch fixing the metered Var, and because they carry duals — so the shadow price of a resource limit is readable after a solve. A time-varying limit is written (feed.withdrawal_max[t].set_value(v)), not configured; an exact profile is not a limit at all and uses the inherited set_external_dispatch.

    • withdrawal_basis/demand_basis choose what those limits mean, because a rate ceiling and a horizon allowance are different constraints rather than two spellings of one — the first is strictly tighter, and it is the second that a permit or a take-or-pay contract actually states. On the default "period" basis the limit is a rate (m**3/hr) binding in every period, exactly as before. On "horizon" it is a quantity (m**3) over the whole horizon: the block builds a scalar withdrawal_total/delivery_total Var and the equality eq_withdrawal_total/eq_delivery_total defining it as sum_t quantity[t] * dt, and bounds that instead — leaving the optimizer free to shape the profile beneath the allowance, which is the flexibility the platform exists to find. The limit Params keep their names and differ only in shape (scalar rather than time-indexed), and the scalar limit carries the permit’s shadow price. The metered withdrawal[t]/delivery[t] stays time-indexed under either basis, so costing, total_feed/total_product aggregation and set_external_dispatch are untouched; the total is a derived scalar and is deliberately not registered as an IO variable. The basis is stated, never inferred from the units — but the units are checked against it, so a rate given on the horizon basis (or a horizon quantity left on the period basis) raises FlexConfigError naming the config key rather than silently rescaling. A basis with no limit configured builds nothing.

    • price is a flat scalar routed through the existing FlexCosting.register_scalar_cost, so its sign convention is unchanged: positive is a cost (raw water withdrawn, brine disposed), negative is revenue (potable water sold). A price set with no costing_package raises FlexConfigError(field="price") rather than silently dropping the cost.

  • PlantBlock/NetworkBlock now aggregate boundary flows into total_feed[resource, t], and total_product[resource, t] merges both routes. Discovery keys off the new _io_registry.boundary record, the same way power and fuel are discovered — never an isinstance check against Feed/Product, which would be a circular import (flexops.unit_models imports flexops.core). Deferred and re-entrant like the other aggregates, and a network sums each contributing plant’s own total rather than re-walking its units (no double-counting, architecture §3.3/R7). The existing explicit register_product(var, name=..., quality=...) registry keeps working unchanged and is merged with the discovered products, at the plant and at the network level. Cross-network hooks need no new API: NetworkBlock.add_link already takes time-indexed quantities, so a plant total is passed as pyo.Reference(plant.total_product["potable_water", :]) and a boundary total as feed.withdrawal directly.

  • OpsBlockData.register_boundary_flow(var, *, resource, kind), with flexops.core.registration.BoundaryKind (FEED/PRODUCT) and BoundaryRecord on the IORegistry. Modelled on register_fuel_usage: any unit may register a boundary flow, not only Feed/Product, and an empty resource raises FlexConfigError(field="resource"). flexcore.nomenclature.TOTAL_FEED joins TOTAL_PRODUCT/TOTAL_FUEL_USAGE as the canonical Expression name.

  • Mixer(property_package, inlet_names=("a", "b"), temperature_mixing="equal"): an arbitrary-arity mixing junction — N named inlet ports (inlet_{name}) summed into one outlet by the single equality mixing_mass_balance. Density is assumed constant across the junction, so volume is conserved directly and there is no energy input: the unit declares neither power_electrical nor power_thermal. Pressure (and any other intensive state the property package carries) is held at the reference inlet’s value — the first name in inlet_names — and passes through to the outlet, the way it behaves at a physical mixing node. temperature_mixing chooses how the outlet temperature is set: "equal" (the default) treats temperature like pressure, keeping the block linear; "flow_weighted" leaves the inlet temperatures independent and blends them by volume via outlet_temperature_eq, which is the correct rule under constant density and constant heat capacity but is bilinear, so a model containing one is an NLP needing IPOPT rather than HiGHS. Requesting "flow_weighted" on a property package with no temperature state is rejected rather than silently ignored. Because the model is only this volumetric balance, construction raises a UserWarning in the two configurations that reach past what it represents: a property_package carrying more than one component (total volumetric flow is summed and no per-component mass balance is written, so the outlet composition is not tracked), and a vapor phase under "flow_weighted" (volumes are additive only at equal temperature and pressure — the one configuration where a gas can actually mix at unequal conditions, since pressure is held equal across inlets under either rule and so is temperature under "equal").

  • Splitter(property_package, outlet_names=("a", "b")): the mirror unit — one inlet divided among N named outlet ports (outlet_{name}) by the single equality split_mass_balance, again at constant density and with no energy input. It builds no split fractions, and that is the point: conservation alone leaves (N-1) free outlet flows per time point, so the routing is a decision the enclosing model’s objective makes rather than a parameter the modeler fixes — which is why a Splitter is not a generalized SIDOBlock. Callers wanting a prescribed split should keep using SIDOBlock (or ReverseOsmosis), whose fixed and regressable split_fraction closes those degrees of freedom. Everything the stream carries other than flow passes through to every outlet.

  • Both units subclass OpsBlockData directly, since a config-driven port count fits no fixed-arity topology base, and both give each stream its own port: port members are equalities in this codebase, so one port carries one arc — N streams means N ports, never one port shared by N arcs. Both require a single-phase property package and work on either shipped package.

  • NetworkBlockData.add_subset_aggregate(plants, var_name, *, name=None, replace=True): sums a time-indexed quantity (looked up per plant via find_component) across a caller-chosen subset of a network’s plants — e.g. one building’s power draw within a larger campus — building a Var/Constraint pair (defaulting to aggregate_{var_name}/eq_aggregate_{var_name}). A plant missing var_name is skipped with a logged warning. Calling again with the same name updates the existing Constraint’s body in place (never deleting it, conventions §9); pass replace=False to instead log a warning and leave the existing aggregate untouched. Distinct from the network’s own always-every-plant totals (architecture §3.3/R7), which this does not affect.

  • flexops.logic.register_parallel_group(units, *, variables=(), order_status=True): declares >= 2 units as a parallel/degenerate hierarchy group — parallel skids, staged trains, a lead/lag pair. units is given in priority order and the group is ordered descending along that list — units[0].status[t] >= units[1].status[t] >= ..., so a train may not run unless its predecessor runs and units[0] is the first one on. Chains add_conditional over every consecutive pair rather than re-implementing implication logic, returning the len(units) - 1 attached conditional Constraints; each pair’s Constraint lands on the later unit, so units[0] carries no conditional. variables names continuous Vars — as each unit exposes them, so a renaming unit’s renamed name (ReverseOsmosis carries recovery, not split_fraction) — to order the same way, as {name}_ordering Constraints attached beside each pair’s conditional. Time-indexed Vars are ordered at every index and scalar ones get a single Constraint; a unit’s regressable process parameters are fixed at construction, so an ordering over them only binds once a caller or FlexParameterize unfixes them. A group is always a hierarchy — there is no then argument, because pairwise mutual exclusion is a different relation and not what a parallel group means; callers wanting “these two may not run together” call add_conditional(a, b, then="off") on the pair directly. order_status=False skips the status chain and orders the named variables alone. This is how a group whose units carry no status Var is registered: status is attached by the caller via add_status, never by a unit’s own build(), so absent hand-applied unit commitment add_conditional — and therefore the default path — rejects the group outright. It also covers units that do carry a status but whose on/off order should stay free, e.g. when every train runs and only the duty split is degenerate. Raises FlexConfigError for fewer than two units, a repeated unit, order_status=False with no variables (the call would order nothing), or a variable name that does not resolve to a Var on every unit or resolves to differently-indexed Vars across the group.

  • Note on what an ordering achieves: it removes the permuted copies of a split duty — three trains trading recovery among themselves reach the same cost under any relabelling, and the ordering admits one — which shrinks the search tree. It does not make a continuous split unique: with f0 + f1 = 50 under identical linear cost, 25/25, 30/20 and 50/0 all satisfy f0 >= f1 at equal cost. The module docstring previously claimed the stronger property; corrected here and in the reference page.

  • docs/reference/flexops/logic.rst: the flexops.logic package was previously undocumented; it now has a reference page covering the unit-commitment pieces and stating the canonical parallel-train ordering once.

  • CostReport names its own currency. report_cost now returns a CostReport with a currency: str field (str(base_currency) — the tariff sheet’s basis when a tariff is given, else the configured currency), so a report is self-describing away from the costing block that produced it. Docstrings that hardcoded ($) are corrected accordingly: the report dataclasses, the nine cost Var/Param doc= strings (which already carried the currency in their units=), and CostingConfig.fixed_operating_cost, which claimed “in dollars” but is denominated in whatever basis is in force. schema_version is unchanged (only a description string moved); exported JSON Schema regenerated.

  • OpsBlockData.create_stream_naming_convention() and a naming_dict argument on every IO-topology base’s build() (SISOBlock/SIDOBlock/DIDOBlock). Each base carries its generic role -> Pyomo component name mapping as _component_names and registers it at the top of build(); a physical subclass renames any subset by spreading that default and passing the result up (super().build(naming_dict={**SIDOBlockData._component_names, "flow_in": "feed", ...}), as ReverseOsmosis does for feed/permeate/brine/recovery). Everything the unit builds or looks up resolves through _named(); ports are never renamed.

  • Combustor.air_to_fuel_ratio (default 9.5, dimensionless): volumes of combustion air entrained per unit volume of fuel gas, a fixed and regressable scalar Var that sets the flue-gas volume. An IC-design property — estimate or model it externally rather than deriving it here. Defined as air-per-fuel (a multiplier) rather than the reciprocal fuel-per-air so the mass balance stays linear even once a design mode or regression unfixes it.

  • flexops.logic.add_ramp_rate(var, *, name=None, ramp_up=None, ramp_down=None, ramp_rate_units=None, window=1): bounds how fast a time-indexed Var may change, either step-to-step (window=1, the default) or as a net change allowed over a window-step span (the “N-minute ramp rate” pattern), with ramp_up/ramp_down independently optional. Builds the ramped quantity as its own tracked Var tied to var by a defining equality, rather than inlining var[t] into the ramp constraints, so a future extension (a windowed average, or a surrogate expression of several Vars) can redefine that one equality without touching the ramp constraints. Every t < window is skipped — there is no pre-horizon history to ramp against. Attaching a second ramp to a Var that already has one is allowed but logs a warning.

Changed

  • FlexCosting.report_cost and the evaluate_cost/evaluate_fuel_cost bridges gained an optional prev_demand_dict — a prior-demand carry for billing a horizon as one slice of a longer billing period (the rolling-horizon case M12 will use), so EECO bills only the demand incremental above the running peak rather than recounting it in every window. Defaults to None, so a standalone report is unchanged.

  • All sub-month proration of the monthly-assessed demand and fixed charges is now EECO’s — evaluate_cost/add_operating_cost pass demand_scale_factor and fixed_scale_factor (and prev_demand_dict) to eeco.costs.calculate_itemized_cost, which scales the demand charge assessment-aware (monthly-assessed only; daily-assessed demand, keyed and billed per day, is left alone) and the customer charge by the same horizon fraction. This removes flex-pse’s own charge-array handling entirely — the _prorate_charge_dict/_daily_assessed_demand_names helpers and the customer-key manipulation in _charge_dict, which is now a thin get_charge_dict wrapper. Reported totals are unchanged. Keeping demand_scale_factor and fixed_scale_factor as independent factors (flex-pse passes the same horizon fraction to both today) is deliberate plumbing for M12: it positions the bridge to weight the per-window demand allocation separately — e.g. non-uniformly across the month — while the fixed charge stays uniformly prorated, by exposing optional demand_scale_factor/fixed_scale_factor overrides when a rolling-horizon weighting policy needs them.

  • EECO pinned to eeco==0.4.0 (from 0.3.0). Required, not cosmetic: fixed_scale_factor — the kwarg the proration change above passes to calculate_cost/calculate_itemized_cost to prorate the customer charge — does not exist in 0.3.0. The bump is otherwise purely additive (0.4.0 removes nothing and also adds get_timesteps, get_billing_period_scale_factor and get_prev_demand_dict, none of which flex-pse calls).

  • Renamed the example plant block svcw to waterfacility throughout the API-freeze script, its config twin, the docs, and the plan. A placeholder name only; no API or behavior change.

Fixed

  • ReverseOsmosis’s docstring contradicted its code on the energy_intensity basis (issue #85). The class docstring’s math and Config summary said P_elec[t] = energy_intensity * V_feed[t], while the energy_intensity ConfigValue said “product” and build() has applied the intensity to the permeate since bc69357 (#76) — a factor of recovery apart. Permeate is the intended basis and is now stated consistently in all three places; a unit test pins it. Behavior is unchanged, but callers who configured energy_intensity on the pre-bc69357 feed basis are drawing recovery times too little power and should divide their configured value by recovery.

  • BREAKING: register_parallel_group ordered its group backwards (issue #64). It chained add_conditional(units[i], units[i+1], then="on"), expanding to units[i+1].status[t] >= units[i].status[t]: units[0] being on forced every later unit on, so the highest-indexed unit was the first one on and the list read as reverse priority. This was also the exact opposite of the (now removed) break_parallel_symmetry, and applying both to the same units forced u0.status == u1.status at every t, locking every train on or off together. The chain is now built back to front (add_conditional(units[i+1], units[i])), giving units[0].status[t] >= units[1].status[t] >= .... Callers relying on the old direction must reverse their units list; the pair Constraints also move from units[0..n-2] to units[1..n-1]. Note this is the opposite of the literal formula in issue #64’s body, which contradicts that issue’s own prose and in fact described the pre-existing behavior — the prose (“turn on skid 0, then skid 1, then skid 2”) won.

  • BREAKING: add_startup_delay sampled a single lagged point instead of the trailing window (issue #68). It built unit.status[t] <= upstream.status[t - k], which never constrained against upstream.status[t] itself (the downstream could run while the upstream was off outright) and only checked the point t - k rather than the whole window (an upstream that shut down and restarted inside the window left the downstream permitted on). The constraint is now indexed over (t, lag) and disaggregated across the trailing window: unit.status[t] <= upstream.status[t - lag] for every lag in 0..k, so the downstream may be on at t only if the upstream was on continuously across [t - k, t]. New initially_on: bool = True keyword controls what happens at the window’s horizon head: True (the new default) clamps the window to [max(t - k, 0), t], so a unit already running at t = 0 counts as warmed up (right for a standalone horizon); False keeps the old status[t] == 0 clamp for t < k (right for a rolling-horizon window with no assumed prior state), now on a separate startup_delay_cold Constraint.

Removed

  • BREAKING: automatic parallel-train detection is gone. flexops.logic.detect_parallel_trains and flexops.logic.break_parallel_symmetry are removed, along with the v0 interchangeability predicate behind them (same *Data class, same Port names, and every comparable config entry equal) and the block-level train_ordering Constraint they produced. Guessing which units are interchangeable from class and config never had enough information to be trusted — two units with identical config can be piped in series — so a group is now something the caller states rather than something the library infers. register_parallel_group is the whole API; callers of break_parallel_symmetry(plant) replace it with an explicit register_parallel_group([...]) per group, which additionally orders continuous variables.

  • BREAKING: dens_mass is no longer a state variable on either property package, and SimpleAqueousFlow’s fixed_density/density config options are gone. No unit model needed density — it was structural boilerplate inherited from WaterTAP’s prop_ZO pattern, and carrying it only added a state variable to fix. SimpleAqueousFlow state blocks now carry flow_vol_phase plus the opt-in pressure/temperature; SimpleGasFlow carries flow_vol_phase/pressure/temperature. Callers passing fixed_density=/density= (including examples/api_freeze.py, the frozen-API tripwire script, and the properties block of a persisted config) must drop those keys.

  • BREAKING: Combustor.outlet_density_eq is gone, along with the isobaric ideal-gas density correction it imposed — there is no longer a density state variable to correct. The outlet’s temperature is still fixed at flue_gas_temperature.

Added

  • PlantBlock/NetworkBlock now aggregate registered fuel usage into total_fuel_usage[fuel_name, t] (m³/hr), alongside the existing total_electrical_power/total_thermal_power/total_product. Follows the total_product pattern: keyed by fuel name (there is no FuelKind enum), deferred and re-entrant like the other aggregates, and a network sums each contributing plant’s own total rather than re-walking its units (no double-counting).

Changed

  • Renamed the Tank unit model’s internal module and implementation class from storage_tank/StorageTankData to tank/TankData, matching the public Tank name. No public API change.

  • Moved the private per-PowerKind name registries (_POWER_VARS/_INTENSITY_VARS in ops_block.py, _TOTAL_POWER/TOTAL_PRODUCT in plant_block.py) into flexcore.nomenclature as public constants (POWER_VARS, INTENSITY_VARS, TOTAL_POWER_VARS, TOTAL_PRODUCT, plus the new TOTAL_FUEL_USAGE), consistent with nomenclature already being the single source of canonical component names. Pure relocation, no behavior change.

Fixed

  • jsonschema was missing from the dev extra, so test_api_freeze_config_is_schema_valid (src/flexops/tests/test_api_freeze.py) failed with ModuleNotFoundError on a clean pip install -e .[dev]. Added to pyproject.toml’s dev list.

Added

  • Combustor: the first SimpleGasFlow unit model — an arbitrary number of gas inlets mixed into one flue-gas outlet, exporting electrical power. Every unit model shipped until now moved water, built on a single-property_package IO-topology base (SISOBlock/SIDOBlock/DIDOBlock). A combustor’s inlet count is a config option (inlet_names), so no fixed-arity base fits — Combustor subclasses flexops.core.ops_block.OpsBlockData directly and hand-writes its own ports, mixing mass balance, and energy relation, the way BatteryModel does. Deviates from the earlier Combustor(SIDOBlock) sketch in architecture §3.4/the M09 plan; that table is updated. Delivered:

    • power_electrical[t] is signed negative and upper-bounded at 0 — a combustor exports power, following the BatteryModel discharge convention, so plant aggregation nets generation against load with no per-unit sign-flipping. docs/explanation/energy_nomenclature.md’s sign rule now covers generation as well as storage.

    • The sign is structural, not a property of the relation’s coefficients. The unit carries a second Var, power_generated[t] (kW, bounded below at 0), holding the generation magnitude, and a separate constraint power_electrical_sign[t]: power_electrical[t] == -power_generated[t]. Only power_electrical_relation is registered, so swap_relation can replace the magnitude relation and can never touch the sign constraint — a fitted relationship cannot flip a combustor into a load. Nothing can prove an arbitrary swapped-in surrogate body is non-positive over the feasible region, so the export convention is enforced by the target’s own lower bound instead: a fit that predicts a negative export violates a bound naming the quantity it got wrong, rather than silently conflicting with power_electrical’s upper bound of 0. power_generated (not power_electrical) is therefore the unit’s registered IO output, so surrogates are fitted in generation-magnitude space — positive, the convention generation data is normally logged in — and no sign flip is needed anywhere between the historian column and the constraint.

    • Two flow-to-power relations, resolved automatically from whether every configured inlet was given a heating value (never a user-selected mode): power_generated[t] = efficiency * Σ heating_value_i * flow_in_i[t] when every inlet has one, else power_generated[t] = energy_intensity * Σ flow_in_i[t] (the sign constraint above carries either to power_electrical). efficiency, every heating_value_i and energy_intensity are all bounded below at 0, so unfixing one for a design mode or a regression cannot flip the relation’s sign. A partial heating_values mapping, or an option the resolved relation would ignore (efficiency under constant intensity, energy_intensity under heating value), raises FlexConfigError naming the field. Both build the Constraint power_electrical_relation — the same swap-contract name every other unit uses, so FlexParameterize’s constraint swap works unmodified.

    • Flue gas: every configured inlet is a fuel stream; combustion air is not modeled as an inlet, so flow_out[t] == (1 + air_to_fuel_ratio) * Σ flow_in_i[t] — the fuel burned plus the air it entrains. Plus inlet_state_equality_<state>[t, name] tying every non-reference inlet’s pressure/temperature to the reference inlet’s (a mixing node shares intensive state). Only the reference inlet’s non-flow states are registered as IO inputs — registering every inlet’s would over-determine the model, since these equalities already pin the rest.

    • Outlet state: pressure passes through from the reference inlet; temperature is fixed at the new flue_gas_temperature config option.

    • New flexops.testing.dummy_gas_time_block(n) — the SimpleGasFlow twin of dummy_time_block, needed because SimpleGasFlow’s always-on state blocks give a gas unit a different degrees-of-freedom accounting than the aqueous default.

    • Registering fuel usage for costing (register_fuel_usage) is deliberately out of scope for this unit — pinned by a test so a later change to that is deliberate, not incidental.

  • GenericRenewables splits its magnitude from its sign the same way Combustor does (above). Its registered power_electrical_relation determines power_generated[t] == capacity_factor[t] * capacity — non-negative, bounded below at 0 — and the deliberately unregistered power_electrical_sign[t] negates it into power_electrical[t], so a swapped-in output curve (a fitted irradiance or wind-speed relationship) cannot flip the unit into a load. power_generated rather than power_electrical is its registered IO output, so a fit is written in generation-magnitude space.

  • GenericRenewables.capacity_factor must lie in [0, 1], checked in build() alongside the existing shape and horizon-length checks and raising FlexConfigError(field="capacity_factor") naming the offending position and value. A capacity factor is a fraction of nameplate: below 0 would make the unit a load, above 1 would export more than the capacity the plant is sized and costed for. An array-like is checked entrywise; a live time-indexed Pyomo reference is checked over the values it carries at construction, skipping an uninitialized member rather than guessing at it — holding a later assignment in range is that component’s own bounds’ job, not this unit’s.

  • The public API is frozen, and the whole model builds from one config file (M09). New examples/api_freeze.py — the PLAN.md §2 script — runs top to bottom and solves, guarded by src/flexops/tests/test_api_freeze.py: from now on, a change that forces an edit to that script is a breaking change. Its config-driven twin examples/api_freeze_config.json builds through the new fo.build_model(...) and is held to the same solved objective. Delivered to get there:

    • Composition (fo.PlantBlock, fo.NetworkBlock). A PlantBlock is a collection of unit blocks (one facility, holding the arcs between its units); a NetworkBlock is a composition of plant blocks (R7) — a plant is never nested inside a plant. Both are thin IDAES FlowsheetBlockData subclasses forced to dynamic=False, with the TimeBlock’s ordered integer Set installed as their time domain by reference (plant.time is time_block.time_index; never Pyomo.DAE, R2). Each exposes total_electrical_power[t] / total_thermal_power[t] Expressions, and a network’s totals are the sums of its plants’ totals — never a second walk over their units, so no unit is double-counted. Aggregation is deferred and re-entrant (_build_aggregates() creates the Expression once and refreshes its body from the children present at each call), because the frozen script builds costing and the plant before any unit exists; FlexCosting.cost_process() now triggers it for every plant/network on the model, so the common path needs no user call. Neither block has a replace_unit: FlexParameterize mutates units in place. A plant can register_product(var, name=..., quality=...); the network sums the amounts into total_product[product, t] and, where qualities are registered, requires like-quality mixing (eq_product_quality, the linear reading — a flow-weighted blend would make every mixing point bilinear). NetworkBlock.add_link(name, source, destination) constrains any two time-indexed quantities across plants (heat out vs. heating load, product out vs. feed in) — the network relates quantities, where a plant copies stream state with arcs. time_block= stays the primary, tested-first path on both; omitting it discovers the model’s only TimeBlock and raises FlexConfigError on zero or several.

    • IO-topology bases SIDOBlock (1→2) and DIDOBlock (2→2), joining M04’s SISOBlock. SIDOBlock splits one feed into outlet_a/outlet_b with two constraints — conservation flow_in == flow_out_a + flow_out_b plus split_definition (flow_out_a == split_fraction * flow_in), since conservation alone leaves the split undetermined. DIDOBlock couples two streams through one transfer_fraction (flow_out_a == (1 - f) * flow_in_a, flow_out_b == flow_in_b + f * flow_in_a). Both ratios are fixed, regressable scalar Vars, so the topologies stay linear/LP-representable and the split is the natural regression target. SIDOBlock bounds its split only to a physical fraction and takes no window options; a physical subclass renames the split into its own vocabulary and narrows the window (see ReverseOsmosis below). Each base passes everything a stream carries other than flow through to each of its outlets; OpsBlockData.add_pass_through_constraints gains a name_prefix= so a multi-outlet topology’s repeated calls do not collide on one component name.

    • The physical zoo: no intermediate Separator/Electrolyzer class (R6) — a physical unit subclasses the matching topology base directly and renames its generic roles (flow_in/flow_out_a/split_fraction/…) into its own vocabulary via a _component_names dict resolved through OpsBlockData._named(). Exchanger(DIDOBlock) and ReverseOsmosis(SIDOBlock) (outlet_a is permeate, and the split is renamed to recovery — split_fraction does not exist on the skid — bounded by the new recovery_min/recovery_max seawater window, which an inverted or unsatisfiable setting rejects with FlexConfigError).

    • ConstantEnergyIntensityModel(SISOBlock) — the generic “energy factor × flow” unit, and FlexOps’ one building block for anything without a bespoke physical topology (a whole treatment plant as a single surrogate, as in the frozen script’s waterfacility.plant). There is deliberately no LinearRegressionModel or other regression unit class (R11).

    • One place builds a flow-to-energy relationship. New OpsBlockData.add_constant_intensity_relation(flow, kind=..., intensity=...) declares the power draw, its intensity Var (energy_intensity / thermal_intensity, fixed and registered regressable=True), and the equality as the Constraint power_electrical_relation (resp. power_thermal_relation). That name is the documented swap contract: new OpsBlockData.swap_energy_relation(surrogate, kind=...) deactivates exactly it (never deletes — conventions §9) and attaches power_<kind>_relation_fitted built from a fitted SurrogateSpec, reusing the unit’s existing registered variables so ports and arcs are untouched. One swap implementation, two callers: construction time (a config carrying a non-constant_intensity form) and, from M10, flexparameterize.apply_to_model. linear is the one fitted form v0 builds; the reserved nn/arima/multiconvex raise.

    • OpsBlockData.build_from_config(cfg, **kwargs) is real (a NotImplementedError stub since M03). It round-trips a path/mapping through the pydantic schema (so a raw dict is never passed on, conventions §4), resolves cfg.unit_model_class against flexops.unit_models, and merges construction options with the caller’s runtime-only ones (property_package, costing_package), which win. An invalid config raises pydantic.ValidationError unwrapped, naming the offending field path.

    • fo.build_model(config) builds the TimeBlock, property package, FlexCosting, the network/plant/unit tree, its arcs, any declared external (DERMS) dispatch, and the objective from one validated ModelConfig. Arcs are declared but not expanded — applying TransformationFactory("network.expand_arcs") stays the caller’s explicit step, in the config path as in the script. New parse_quantity/parse_units resolve the units a persisted config carries as data ({"value": 0.5, "units": "kWh/m^3"}, or "15 min" for the time step), closing the gap M03’s build_from_config TODO flagged as the blocker; unknown unit tokens register as a currency, so "USD/kWh" parses without a costing block existing yet.

    • Fixtures examples/data/tariff.json (a tiny TOU sheet) and examples/data/dr_events.json (an empty DR program), which the frozen script loads by bare filename.

    • docs/getting_started/ten_minutes.md (new), a fleshed-out docs/how_to/build_a_plant.md (build order, the config conventions, multi-plant networks), the R2/R7 rationale in docs/explanation/time_and_dynamics.md, and reference pages for every new class. BatteryModel also gets the reference page M08 omitted (sphinx-build -W was failing on it).

Changed

  • parse_quantity gained strict=, and build_from_config passes strict=False, so a construction option written as a plain string in a persisted config (e.g. an enum member’s name) reaches the unit’s ConfigValue domain instead of being rejected as a malformed quantity. This restores build_from_config’s documented contract (“anything else passes through unchanged”). TimeConfig.time_step still parses strictly, so "15 min" keeps its loud error.

  • Tank’s max_volume/initial_volume now have defaults (1000 m³ and 500 m³, half full) instead of being required. Needed so the frozen fo.Tank(property_package=m.properties) builds; a real tank is still always given its own sizing.

  • A BatteryModel with unit commitment on and no power rating now derives a 1C limit (its whole capacity in one hour) instead of raising. The frozen script builds BatteryModel(capacity=1 * pyunits.kWh, costing_package=...) with no rating at all, and the semicontinuous status link needs a finite bound; giving one of power_charge_max/power_discharge_max without the other still raises. test_status_requires_both_power_maxima is renamed and its both-unset case replaced by one asserting the 1C fallback.

  • BatteryModel’s unit_commitment.status now defaults to False, overriding the project-wide True default (CONFIG.get("unit_commitment").set_default_value(...), the same pattern SISOBlock/Combustor use for allow_pass_through) instead of just inheriting it — a bare BatteryModel(capacity=...) now builds as a plain LP with no on/off binary. Opt in with unit_commitment=UnitCommitmentConfig(status=True). The 1C power fallback above is decoupled from status so it applies either way — a battery with no explicit power rating is never left unbounded, on or off.

  • PLAN.md §2 and the frozen script import Arc from pyomo.network (m.waterfacility.tank_to_plant = Arc(...)). The earlier pyo.Arc spelling names an API Pyomo has never had — Arc lives in pyomo.network and is not re-exported into pyomo.environ — so the script could not have run as written. Corrected at the source so examples/api_freeze.py stays byte-for-byte identical to PLAN.md §2, and recorded there alongside the existing slide-API corrections.

  • docs/explanation/time_and_dynamics.md’s holdup example is written in the backward difference form the codebase actually uses (V[t] = V[t-1] + dt * (...), conventions §2); it previously showed the forward form.

  • OpsBlockData._find_time_block delegates to a new module-level flexops.core.time_block.find_time_block(model), the one auto-discovery implementation now shared with PlantBlock/NetworkBlock.

Added

  • Solvers are installed in CI. New solvers optional dependency (pip install -e ".[solvers]") pulls in the HiGHS wheel (highspy), and a new .github/actions/setup-ipopt composite action runs idaes get-extensions for IPOPT, caching the idaes binary directory keyed on OS + idaes version and exporting it to PATH. On Linux runners the action also apt-installs the LAPACK/BLAS/gfortran runtime libraries the IDAES ubuntu2204 IPOPT build links against (absent from the ubuntu-24.04 image, where ipopt otherwise exits 127 on liblapack.so.3), and finishes by solving a one-variable NLP so a binary that cannot load its libraries fails in setup rather than mid-suite — SolverFactory("ipopt").available() only checks that the file exists, so needs_ipopt does not skip in that case. Both the fast-tests and integration CI jobs now use them, so needs_highs/needs_ipopt tests actually run on a PR instead of skipping.

  • BatteryModel gains soh (state of health, default 0.85/mid-life) and a soh_capacity_limit constraint (charge[t] <= soh * capacity, independent of soc_max), plus eta_charge/eta_discharge are now fixed Vars (not plain config floats) — all three registered regressable=True (matching Pump.efficiency) so a future FlexParameterize regression can fit them from SCADA data: power_charge/power_discharge in, charge (now registered as the process output) out, capacity known. Not part of the M08 spec — added at explicit user request; see the class docstring’s “Deviations from the milestone spec.”

  • BatteryModel gains charge_leakage_rate (self-discharge), a fixed Var in fraction-of-charge-per-day (default 0.0005, i.e. 0.05%/day), registered regressable=True like eta_charge/eta_discharge/soh. charge_balance now subtracts charge[t-1] * charge_leakage_rate * dt each step. Not part of the M08 spec — added at explicit user request; see the class docstring’s “Deviations from the milestone spec.”

  • An energy price may vary over the horizon, and a bare number is now accepted. FlexCosting’s energy_prices entries widen from a units-carrying scalar to any of three forms per carrier: a single value (flat over the horizon), an array-like with one value per time point (list/tuple/numpy array, read in time-index order), or a Pyomo component indexed over the horizon — so a price can be a mutable Param updated between rolling-horizon solves, or even a Var. An indexed price need not live on the TimeBlock’s time_index, only have exactly one value per time point (read in its own index-set order). The native cost formula generalizes from price × Σ_t quantity[t] × dt to Σ_t price[t] × quantity[t] × dt (unchanged for a flat price, which is still factored out of the sum), in the in-objective constraint and in report_cost’s independent post-solve recomputation alike. A price with the wrong number of values raises FlexConfigError at FlexCosting construction — the earliest point the horizon length is known — naming both counts; a Mapping price is rejected outright, since iterating it would cost its keys. A bare number is no longer rejected (it previously raised “has no units”): it is read in the currency over the carrier’s metered quantity — kWh for a power carrier, m³ for a fuel — so {"electrical": 0.12} means $0.12/kWh and {"natural_gas": 0.50} means $0.50/m³. A price that does carry units is passed through untouched, so a mis-dimensioned price still fails the unit-consistency check rather than being silently reinterpreted. CostingConfig’s PriceSpec.value widens to float | list[float] (non-empty) to mirror it; the length-vs-horizon check is not enforceable in the persisted schema (deriving the number of time points needs a TimeConfig.time_step string parser, which does not exist yet) and remains the runtime one. schema_version stays 0.0.1: widening a field is backward-compatible and every existing config still validates. Exported JSON Schema regenerated.

  • A tariff is now optional: flat energy prices, several tariff files, and EECO as a soft dependency. FlexCosting gains an energy_prices config entry mapping a carrier or fuel name ("electrical", or a registered fuel) to a units-carrying price (e.g. 0.12 * currency_units("USD") / pyunits.kWh); that carrier is then billed natively as price × Σ_t quantity[t] × dt and never sent to EECO. A flat price wins over a tariff covering the same carrier, so tariff-priced electricity and a flat-priced fuel can be mixed. tariff_file/tariff relax from exactly one to at most one and now also accept several sources — a list to merge, or a mapping of EECO utility ("electric"/"gas") to source to merge and assign each file to a utility (keeping only that utility’s rows, so a sheet’s stray rows cannot leak into the bill) — via the new merge_tariffs, which raises rather than silently doubling a charge two sources both define. Several files always collapse to one rate_data frame whose utility column selects rows per leg; the covered utilities are recorded so an unpriced carrier raises FlexConfigError naming the carrier instead of contributing a silent $0. The eeco import is now soft: import flexops and a fully flat-priced build/solve/report_cost work with EECO absent, and any tariff path raises FlexConfigError naming both remedies (install eeco, or price the carrier flat). New currency_units(symbol="USD") supplies the Pyomo currency for writing flat prices and is the base currency when no tariff sets one (new currency config entry). CostingConfig mirrors all of it (tariff_source widened to str | list | dict | None, new energy_prices of PriceSpec (value + units string), currency, plus a validator requiring a tariff or at least one price); exported JSON Schema regenerated.

  • Annualization takes a cost of capital. New interest_rate config entry (default None) on FlexCosting/CostingConfig. The capital recovery factor is now built on a single effective_rate Param: discount_rate alone when interest_rate is unset — so existing configs annualize exactly as before — and the real rate (1 + interest_rate) / (1 + discount_rate) - 1 when both are given. An effective rate of 0 still falls back to straight-line 1/lifetime_years; an effective rate <= -1 or a non-positive lifetime_years now raises FlexConfigError (the > 0 bound lifetime_years’ description already claimed was never enforced).

Changed

  • Monthly-assessed tariff charges are prorated to sub-monthly horizons (this changes cost values). A demand charge and a tariff’s fixed (customer) charge are billed per calendar month, but flex-pse billed them in full on any horizon — a 24-hour run paid the whole $150/month customer charge and the whole $21.50 + $19.00 per-kW monthly demand charges. With the new prorate_monthly_charges (default True, on FlexCosting and CostingConfig) both are scaled by the new monthly_scale_factor — horizon length over the real length of the calendar month it starts in. Energy charges are never scaled, a demand charge marked "assessed": "daily" is left alone (it is already at horizon granularity), and a full-month horizon is unaffected (the golden $14,085.00 monthly bill is unchanged). prorate=False on add_electricity_cost/add_fuel_cost/add_operating_cost/evaluate_cost/evaluate_fuel_cost restores the old numbers. The headline load-shifting regression constant is re-recorded accordingly (1467.388888888889 → 147.4964157706093, a 24-h horizon of a 31-day month). Prorating is applied to the charge rates before EECO sees them, leaving EECO’s tiered-surcharge arithmetic untouched; flex-pse does this itself because the get_charge_dict path exposes no equivalent option (EECO’s calculate_cost adds the customer charge whole, and its demand_scale_factor is suppressed for charges spanning <= 1 day — which, since EECO clips charge-key dates to the horizon, would silently include every monthly charge on a one-day horizon, the very case prorating exists for). OperatingCostHandles gains customer_charge and scale_factor.

  • FlexCosting’s flat-price, fuel-price, and scalar-cost line items share one price × Σ_t series[t] × dt builder, which integrates over the series’ own index set and raises FlexConfigError if that is not the model’s time_index — so costing a batch or cyclic unit on a separate time index is a loud error rather than a silently wrong bill (supporting it needs the power/fuel aggregation and the EECO bridge changed first, as both assume one uniform grid).

  • What crosses the EECO cost boundary is now a bare magnitude, not a units-carrying expression (no cost values change). EECO applies its unit conversion as a plain float factor and constrains its own dimensionless Vars to the series it is handed (electric_converted[t] == series[t] * factor), so handing it kW / m³/hr expressions left EECO’s internal constraints dimensionally inconsistent — a whole-model assert_units_consistent, the standard Pyomo/IDAES diagnostic, failed on any tariff-priced model (48 constraints on a 24-step model with one fuel). opex.eeco_aggregate_electrical_power is now dimensionless (the kW-converted aggregate divided by its units), and the fuel legs gain the matching opex.fuel_<name>.eeco_aggregate_fuel_usage instead of passing the m³/hr aggregate_fuel_usage Reference straight through. aggregate_power/aggregate_fuel_usage keep their units, so nothing user-facing moves. The power/electrical_power/fuel_power arguments of add_electricity_cost/add_fuel_cost/add_operating_cost are documented accordingly: pass a bare kW / m³/hr magnitude.

Added

  • FlexCosting extensibility groundwork (additive; no cost values change). opex.total_operating_cost now sums over an explicit list of category sub-total names (electricity_cost/fuel_cost/fixed_operating_cost/scalar_cost) instead of a hardcoded four-term expression, so a future cost category is added by building its sub-total Var and appending one name. FlexCosting.register_scalar_cost gains an optional keyword-only unit= that records the owning unit block on the returned ScalarCostSpec (default None), so per-unit maintenance/chemical/labor attribution can be surfaced later without a signature change.

  • FlexCosting hardening — Var+Constraint model, arbitrary energy carriers, non-energy scalar costs, annualization. Every quantity FlexCosting exposes is now a decision-visible Var defined by an eq_<name> equality Constraint (not a bare Expression): aggregate power, each cost line item, the annualized cost, and the totals. cost_process() now aggregates all registered power draws into an indexed aggregate_power[t, carrier] (kW) — "electrical" and one carrier per distinct thermal temperature ("thermal@<T>K"; duties at different temperatures are never summed). Every draw is normalized to kW with pyunits.convert at aggregation, so a non-power draw fails loudly. The electrical series is normalized to EECO’s expected units via an explicit opex.eeco_* Var + constraint before it is handed to EECO. declare_power/register_power take an optional temperature (required for THERMAL), carried on PowerRecord. Fuel is a metered volumetric flow, not a power (see the separate entry below). FlexCosting.register_scalar_cost(name, quantity, price, quantity_units) adds a wholly non-EECO operating-cost category for flows/supplies/products (price × Σ quantity × dt; a signed price supports revenue credits), exposed as opex.scalar_cost in total_operating_cost. Annualization: CostingConfig.lifetime_years + discount_rate form a capital_recovery_factor and an annualized_cost Var ($/year, opex scaled horizon→year + capex×CRF). report_cost gains an operating.scalar field and sums each fuel’s post-hoc EECO bill. A unit-consistency check reconciles every operating-cost line item onto the tariff currency or raises FlexConfigError. New ScalarCostSpec exported from flexops.costing. Exported JSON Schema regenerated. Deviation from the M07 spec: the spec builds the aggregates/line items as Expressions; per user direction these are now Var + defining Constraint (unit tests stay solver-free by propagating through the constraints via calculate_variable_from_constraint).

  • Fuel is costed on a volume basis (m³/hr); flex-pse assumes no heating value. A combustible fuel is metered and billed on volume, so it is no longer modeled as a kW power draw. New flexcore.nomenclature.FUEL_USAGE (fuel_usage_<fuel_name>, a volumetric flow in m³/hr — deliberately not a PowerKind) and new OpsBlockData.register_fuel_usage(var, fuel_name), which records a FuelUsageRecord on the new IORegistry.fuel list; for a SimpleGasFlow stream (whose flow_vol_phase is already m³/hr) that var is a Reference to the stream’s flow. FlexCosting.cost_process() pulls every registered flow from the model and builds aggregate_fuel_usage[t, fuel] directly in EECO’s m³/hr (pyunits.convert rejects a non-volumetric flow loudly), then bills each fuel via add_fuel_cost on its own opex.fuel_<name> sub-block. Fuels are discovered from the model rather than declared: FlexCosting.register_fuel, fuel_spec, and the FuelSpec dataclass are removed, along with PowerKind.FUEL, POWER_FUEL, PowerRecord.fuel_name, the fuel_name kwarg on declare_power/register_power, and the per-fuel opex.eeco_gas_usage_<name> normalization Var (the aggregate is already in EECO’s units). report_cost reads the realized fuel bill off aggregate_fuel_usage; a model that burns no fuel builds no gas leg and opex.fuel_cost is 0. Withdrawn as out of spec: the earlier same-session design in which a fuel was a PowerKind.FUEL kW draw converted to a usage rate by a user-supplied heating_value and an optional fuel_units=therm basis. It contradicted M07 §”a kW heat duty is NOT the fuel-cost input” and architecture §4 (which lists only power_electrical/power_thermal), and fuel_units=therm silently mis-costed fuel by ~2.83× — EECO always interprets its gas series as m³/hr (gas_consumption_units) and applies its own CH4 heating value (2.83168) only when a tariff prices gas in therms via the bare charge column. Energy-basis conversion is EECO’s job, not flex-pse’s.

  • flexops.costing.opex now passes electric_consumption_units/gas_consumption_units (kW / m³/hr) explicitly into every eeco.costs.calculate_itemized_cost call instead of relying on EECO’s matching defaults, so an upstream default change surfaces as a loud conversion rather than a silently mis-scaled bill. The fuel_usage block-attribute name add_operating_cost reads is now the flexcore.nomenclature.FUEL_USAGE constant rather than a module-local literal.

  • New examples/pump_tank_load_shifting/ — an interactive marimo notebook stretching the M07 headline pump+tank load-shifting LP from one day to a full month (July 2025, hourly), with pump/tank sizing and the tariff demand charge exposed as sliders. Outside the milestone system and expected to move to a separate examples repo after the API freeze; examples/ is excluded from ruff/black, and marimo/matplotlib are added to the dev extra.

  • First end-to-end economic result: EECO-backed FlexCosting; pump+tank LP shifts load off-peak. flexops.costing.FlexCosting (exported as fo.FlexCosting) subclasses IDAES FlowsheetCostingBlockData and delegates all tariff operating cost to EECO (decision R4). cost_process() aggregates every unit’s power_electrical into a kW series (pulled from the model, so the block may be constructed before or after the units) and organizes cost into two sub-blocks: an opex block holding all operating cost — electricity_cost and fuel_cost (both built onto it via the M06 opex.py bridge) plus a user-defined fixed_operating_cost — re-exposed as aggregate_operating_cost; and an empty capex placeholder (total_capital_cost == 0, re-exposed as aggregate_capital_cost) that later milestones fill. Capital cost enters the objective only in design mode (set_design_mode()/set_operations_mode() are idempotent single-model toggles; no-ops in v0 with an empty sizing registry). report_cost(model) returns a categorized CostReport (capital vs. operating, each itemized: electricity, fuel, fixed, dr_revenue) recomputed post-solve via EECO’s evaluator — never the raw objective (R9, §6); in v0 fuel/dr_revenue/capital are zero placeholders. Demand response stays containers-only (a dr placeholder + no-op _build_dr hook). FlexCosting.base_currency and every operating-/capital-cost expression carry the tariff sheet’s currency basis (read from the charge units column by the new flexops.costing.tariff_currency_units; $ → USD), casting EECO’s dimensionless cost expressions to it. The headline component test solves a pump→tank LP under the demo tariff and confirms zero pumping in the peak window. New docs/how_to/build_a_plant.md skeleton and FlexCosting costing-reference section.

  • New fixed_operating_cost field on flexcore.config.CostingConfig (default 0.0): the non-tariff fixed operating cost ($ over the horizon — maintenance/labor/chemicals), distinct from the tariff’s own fixed charge (which EECO folds into the electricity cost). Exported JSON Schema regenerated.

  • OpsBlock gains an optional costing_package= config: when set, register_power forwards the unit’s power draw to that FlexCosting block (the explicit unit↔costing association). Strictly conditional — costing-less units (M04) are unaffected.

  • Wired in the external EECO package (eeco==0.2.1, already pinned in pyproject.toml) as flex-pse’s tariff/operating-cost engine, with the whole integration collected in flexops/costing/opex.py — the sole eeco import point in the codebase (decision R12; a grep convention, not an import-linter contract). Public API exported from flexops.costing: load_tariff/load_dr_program (resolve a tariff_source/events_source to an EECO object; wrap load errors as FlexDataError), tariff_csv_to_dict (EECO rate_data CSV or pre-loaded DataFrame → the dict load_tariff accepts, with optional write_to= JSON persistence), the pandas signal helpers price_series/is_peak/peak_windows/price_gradient (flex-pse helpers over EECO’s get_charge_dict charge arrays, for logic/heuristic constraints), the in-objective Pyomo bridges add_operating_cost/add_fuel_cost returning OperatingCostHandles (EECO builds the convex-relaxed cost Expressions via costs.calculate_itemized_cost; the wrapper only renames outputs and asserts the demand charge stayed a linear epigraph — the built model classifies LP), the post-optimization evaluators evaluate_cost/evaluate_fuel_cost (the TRUE de-relaxed bill on a fixed realized numpy array — the user-facing number, R4/R9; evaluate_cost reproduces a hand-computed PG&E-B-20-flavored monthly bill to the cent, $14,085.00), and the DRConfig demand-response container. DR is containers-only in v0 (architecture §2.4): DRConfig loads a DR file and the internal _build_dr hook is a no-op — supplying a DR file never changes the objective. EECO reasons in naive local wall-clock time; tz-aware indices are rejected at the wrapper boundary with FlexDataError. New costing reference page (docs/reference/flexops/costing.rst) and numpy intersphinx mapping (M06).

  • flexops.costing.add_operating_cost is now the facility-level umbrella that builds the whole in-objective operating cost — electricity and gas — onto one opex block, returning a single OperatingCostHandles whose total_operating_cost is the sum across utilities (EECO namespaces its Pyomo components by utility, so electric_*/gas_* never collide on one block). It reads the facility consumption from the standard series on the block (block.power_electrical, block.fuel_usage) when not passed, with electrical_power=/fuel_power= overrides; a utility whose series is neither passed nor present is omitted, and it raises FlexConfigError if neither resolves. The former electric-only add_operating_cost is renamed add_electricity_cost (still exported) and, with add_fuel_cost, remains the single-utility builder. Deviation from the M06 spec: the spec names add_operating_cost as the electric-only bridge; this session renames that to add_electricity_cost and repurposes add_operating_cost as the combined electric+gas umbrella, folding facility-level aggregation (nominally M07 FlexCosting territory) into M06 at the user’s request. The fuel-consumption block attribute name fuel_usage is the flexcore.nomenclature.FUEL_USAGE constant — a volumetric gas-usage series in m³/hr, not a power_thermal kW duty.

  • add_gas_cost/evaluate_gas_cost renamed to add_fuel_cost/evaluate_fuel_cost. Both now take a fuel_type keyword (default "gas", the only utility EECO 0.2.1 exposes) so a future EECO hydrogen utility is a new fuel_type value rather than a new function. add_operating_cost’s gas_power param and the gas_usage block-attribute convention are renamed fuel_power/fuel_usage to match.

  • Pump gains a power_relation config option ("constant_intensity", the default, or "hydraulic"): the hydraulic relation adds a delta_pressure[t] Var tied to the inlet/outlet pressure states by the pressure_change equality constraint (delta_pressure[t] == outlet_state.pressure[t] - inlet_state.pressure[t]), requiring a property_package built with has_pressure=True, and excludes pressure from the inherited inlet-to-outlet bypass (a pump raises pressure rather than passing it through); both inlet_state.pressure/outlet_state.pressure are registered as IO inputs (fixed boundary conditions, like dispatch flow). Adds a mutable efficiency Var (dimensionless, bounded [0, 1], default 0.7, fixed at build), and builds power_electrical[t] = delta_pressure[t] * inlet flow / efficiency in place of the constant-energy-intensity law. Patch to M04’s Pump, deferred at the time for simplicity.

Changed

  • The tariff JSON records key is now tariff_data (was rate_data, which collided with EECO’s own DataFrame/column-schema term): load_tariff, tariff_csv_to_dict, and the demo fixture/example tariff files updated accordingly.

  • flexops/costing/opex.py now sources its rate_data column names, charge-column names, and the electric/gas/energy sentinels from eeco.costs’ own string constants (UTILITY, TYPE, CHARGE_METRIC, ELECTRIC, ENERGY, …) instead of hardcoded literals, so an upstream EECO column rename tracks automatically rather than silently breaking tariff validation. Which columns flex-pse requires stays flex-pse’s choice; only the string values are borrowed. A unit test guards that the tuples equal EECO’s constants (M06).

  • Install pipeline is now conda-only: uv is removed and environment.yml installs the editable package and its Python dependencies (including the pip-only eeco) through a pip: subsection, so conda env create -f environment.yml is the single install command. README, PLAN.md, and the M00 milestone spec updated accordingly.

  • Renamed the intra-unit property-copying API to pass_through, reserving bypass for the flow-diversion stream. OpsBlockData.add_bypass_constraints → add_pass_through_constraints, the config slot allow_bypass → allow_pass_through, and the generated equality components bypass_{name}_eq → pass_through_{name}_eq. This copies every state variable a unit does not otherwise govern straight through (outlet == inlet) so a single unit is well-posed — distinct from a physical bypass that diverts flow around a unit (flexops.logic.bypass.add_bypass, which keeps the bypass name). Behavior-preserving: no constraint math changed. Deviation from the M04 spec, which named the method add_bypass_constraints/config allow_bypass; the M04/M03 milestone wording is updated to match, and a new docs/explanation/pass_through_and_bypass.md page distinguishes pass-through (intra-unit, now) from the bypass stream (flow diversion, M08) and the arc/topology layer (M09).

Added

  • Project scaffold: four-package src/ layout (flexcore, flexops, flexparameterize, flexschedule), import-linter DAG contract, pytest tier markers with collection-time enforcement, and CI skeleton (M00).

  • Exception hierarchy; pinned idaes-pse/pyomo versions (M01).

  • Added TimeBlock: the discrete-time substrate (ordered integer time_index set, time Param of elapsed i*dt in the user’s units, unit-carrying dt, datetime↔index utilities, rolling-horizon initial-state registry and window metadata); a configurable max_length (dateutil relativedelta, default one calendar month) bounding the horizon; minimal Sphinx docs skeleton (M02).

  • CI standard-install job (committed but commented out, pending the repo going public): remote-only install from the git ref (pip install "git+<repo>@<ref>", no checkout) matrixed over Python 3.11–3.14 that imports every subpackage from a scratch dir, catching subpackages missing from the built distribution — or files left uncommitted — that the editable dev install would mask (M00).

  • Added flexcore.solvers: a model classifier (classify/ProblemClass), a capability-matrix registry with cached availability probing (available_solvers), and the get_solver/SolverFacade facade that selects a solver by problem class and errors loudly (decision R5) when no capable solver is installed. Default open-source stack: HiGHS for LP, SCIP for MILP and MINLP (preferred over HiGHS for MILP; added to environment.yml), and IPOPT for NLP — built from idaes (HSL ma27 linear solver) when idaes is importable, falling back to stock SolverFactory IPOPT (MUMPS) otherwise. When no MINLP-capable solver is installed, MINLP still raises pointing at flexschedule.SolveSequence. SCIP’s dynamic-library path is isolated at invocation so it does not clash with idaes’s bundled libipopt. The root conftest.py now forbids solver invocation and network access under -m unit and skips needs_*-marked tests via the registry; adds a flexcore reference page and a relaxation-policies explanation page (M05).

  • Added the OpsBlock base of every flex-pse unit model (flexops.core.ops_block, inheriting IDAES UnitModelBlockData with no ControlVolumes, decision R1): the registration API (register_io_variable/register_process_parameter/register_power), base-provided power_electrical/power_thermal kW Vars via declare_power, the external-dispatch (DERMS) hook set_external_dispatch, the validated-only config slots (unit_commitment, relaxation, allow_pass_through, external_dispatch; their constraints land in M08), and an M09-deferred build_from_config stub. register_power/declare_power require a flexcore.nomenclature.PowerKind member for kind (plain strings are rejected), and call sites import the nomenclature module as nm so constants like nm.POWER_ELECTRICAL read unambiguously as string names. Added the in-place update hook update_parameters(values) (set_value on registered mutable params, driven by FlexParameterize in M10): flex-pse never deletes model components — deletion leaves stale references in anything that captured the old component — so the earlier delete-and-rewire replace_unit helper was dropped in favor of it (conventions §9). Registration records and model-wide discovery live in flexops.core.registration (IORegistry, iter_io_registry). Added the add_stream_ports helper: it builds a single scalar inlet/outlet state block per stream from the configured property_package (state variables indexed over time), registers each side’s volumetric flow (flow_vol_phase) as an input/output IO variable via a time-indexed Reference, and exposes the inlet/outlet ports through the inherited IDAES add_inlet_port/add_outlet_port (M03).

  • New model_and_block_structure explanation page: defines the ConcreteModel/TimeBlock/OpsBlock/property-package block hierarchy and the variable-indexing convention (operational Vars indexed over time_index; property state variables carry the time index themselves on a single scalar state block per stream), plus the extensive/intensive arc split.

  • Added SimpleAqueousFlow: the minimal IDAES property package whose state block carries a flow_vol_phase indexed by time then phase (single Liq), and a time-indexed dens_mass state variable (fixed at the configured density by default, free with fixed_density=False), plus opt-in pressure/temperature. State variables are indexed over time directly — extensive per-phase quantities lead with time then phase, intensive stream properties (dens_mass/pressure/temperature) drop the phase index — and the owning unit passes the time set via a time_index state-block config option, yielding one scalar state block per stream; exported from flexops (M03).

  • Added SimpleGasFlow: the gas-phase counterpart of SimpleAqueousFlow whose state block always carries a flow_vol_phase (indexed by time then the single Vap phase), plus time-indexed dens_mass, pressure, and temperature (gas density varies with pressure/temperature; no equation of state is imposed). Exported from flexops, alongside a new top-level PowerKind re-export so the standardized power-kind names (PowerKind.ELECTRICAL/PowerKind.THERMAL) are importable directly from flexops (M03).

  • Added the full versioned config schema (flexcore.config.schema, pydantic v2, decision R3): IOVariableSpec, SurrogateSpec, ExternalDispatchSpec, UnitCommitmentConfig, UnitConfig, PlantConfig, NetworkConfig, TimeConfig, CostingConfig (with a DRConfig container slot), and the top-level ModelConfig (mandatory semantic-version schema_version, exactly-one-of network/plant). Added flexcore.config.io (load_model_config/dump_model_config with JSON as the only on-disk format plus direct dict input, a MIGRATIONS table, and export_json_schemas with an optional filename for side-by-side schema versions) and the checked-in JSON Schema at src/flexcore/config/schemas/model_config.schema.json, whose descriptions are exported as plain single-line text (no newlines or section-sign codes; wrapping is the doc builder’s job). Added flexcore.nomenclature (the POWER_ELECTRICAL/POWER_THERMAL constants and PowerKind). New docs: config-schema and energy-nomenclature explanation pages, flexcore config/nomenclature/exceptions reference sections, and a flexops.properties reference page (M03).

  • Added the public, shipped flexops.testing.UnitModelTestHarness: every unit-model milestone (and any user writing a custom unit model) subclasses it instead of hand-writing the build/units-consistency/registration/energy-naming/degrees-of-freedom/solve/solution checks (test_build, test_units_consistent, test_io_registration, test_energy_naming, test_dof on the unit tier; test_solve, test_solution on the component tier, skipping cleanly if flexcore.solvers.get_solver is unavailable). Added flexops.testing.dummy_time_block(n=3), a throwaway TimeBlock + SimpleAqueousFlow model reused by the M14 docs generator. Added OpsBlockData.add_pass_through_constraints(inlet, outlet, *, exclude_vars=()): a generic inlet-to-outlet pass-through for every non-excluded, non-fixed state variable (e.g. dens_mass under fixed_density is skipped automatically), gated by self.config.allow_pass_through; it resolves each port’s sibling "{port}_state" block rather than the port’s own vars mapping, since the latter are auto-generated References carrying a leaky extra UnindexedComponent_set dimension. Added SISOBlock (flexops.unit_models.base), the first IO-topology base class (architecture §3.4/R6): builds the inlet/outlet ports via the inherited add_stream_ports, then its per-stream pass-through via add_pass_through_constraints with no exclusions (flow’s pass-through is itself a pass-through equality, named pass_through_flow_vol_phase_eq); SISOBlock overrides the inherited allow_pass_through default to True so the topology is well-posed out of the box. Added SimpleAqueousFlow.get_flow_basis_var_name()/SimpleGasFlow.get_flow_basis_var_name() (both return "flow_vol_phase"), letting callers exclude “the flow” from a generic pass-through without hardcoding a property-package-specific name. Added the first two physical unit models on top of the SISO base: Pump(SISOBlock) (power_electrical[t] = energy_intensity * inlet flow, dimensionally exact kWh/m³ × m³/hr = kW; carries a .. todo:: note for a future detailed power law, e.g. density·flowrate·head/efficiency, not built here) and Tank(SISOBlock) (holdup difference equation volume[t+1] = volume[t] + dt*(in - out) over t = 0..N-2, converting the whole flow-difference expression rather than assuming the flow basis’s units). Tank now distinguishes max_volume (the maximum possible tank volume – fixed by prior investment or space constraints, a static upper bound) from capacity (the chosen volume, a fixable design Var now bounded (min_volume, max_volume) so a design-mode solve can never exceed the maximum possible size). Added a bounded level[t] Var (level_min/level_max config, default (0.0, 1.0)) defined by level_definition[t]: volume[t] == level[t] * capacity – the fractional fill relative to the chosen capacity, preventing the tank from draining all the way down or overfilling; this is linear (LP) in operations mode (capacity fixed) but bilinear (NLP) in design mode (capacity free), so design-mode solves of a model containing a tank need IPOPT or a flexschedule.SolveSequence, not HiGHS. Tank forces unit_commitment.status = False regardless of what a caller passes – a tank has no on/off status, the canonical example of a physical subclass turning off a base capability (R6). New docs: flexops.testing and flexops.unit_models (with the unit_model.rst autosummary template, a flexops-unit-tables TODO placeholder for M14) reference pages (M04).

Fixed

  • import flexops.testing no longer fails on a standard install. flexops.testing imports pytest at module level (UnitModelTestHarness uses pytest.mark/pytest.skip/pytest.approx), but pytest was listed only in the dev extra, so pip install flex-pse followed by import flexops.testing raised ModuleNotFoundError: No module named 'pytest'. New testing optional dependency: users subclassing the harness in their own test suites install pip install "flex-pse[testing]" (contributors already get it from dev). Installing without it still works — flexops.testing is the only module that needs it. The CI standard-install job’s bare-install smoke-import list drops flexops.testing accordingly and gains a second step that installs flex-pse[testing] and imports it, so both paths are covered.

  • OpsBlock now coerces an explicit unit_commitment=None to an all-defaults UnitCommitmentConfig in build() (Pyomo skips ConfigValue domains for None, so the domain-level coercion never ran).