Changelog¶
All notable changes to this project are documented in this file. The format follows Keep a Changelog.
[Unreleased]¶
Added¶
flexparameterize.run_sweepandsolve_pointsweep a Pyomo model with watertap-org’sparameter-sweep(new[sweep]extra).run_sweep(config, build_model, initialize, optimize)draws theParameterizeConfiginputs 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 andsolve_successful.bounds=resamples a box inside the config ranges.solve_pointsolves 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_sweepfits surrogate specs to parameter-sweep results. AParameterizeConfig(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 thanmax_failed_fractionfailed. It converts each output to the spec’s units, fits it withget_regressor, checks the holdout maximum relative error and relative RMSE (10% each by default) and, ifr2_minis set, R^2, and returns{unit: {relation: SurrogateSpec}}forapply_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.GenericRenewablescan be curtailed.curtailable=Truefrees a newpower_curtailed[t]Var (non-negative, kW). Each period,curtailment_balancegivespower_delivered = power_generated - power_curtailed, andpower_electricalis now-power_delivered.power_generatedstill targets the swappable relation and now means available output. By defaultpower_curtailedis fixed at 0, so existing models behave as before.power_curtailedis registered as an IO output.Tanktakesfix_initial_stateandcyclic.fix_initial_state=Falseleaves theinitial_volumeVar free and registers no initial state, so a tank can be used in a design study.initial_volume_lower_limitandinitial_volume_upper_limitkeep the start within the fill window of the chosencapacity.cyclic=Trueaddscyclic_volume, which requires the final volume to be at least the starting volume.DesignSpec.capex_budgetcaps total capital spending in a design study (issue #170). When set,build_design_modeladds the constraintcapex_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’scapacity[name].capital_costis now a Var tied to its size bycapital_cost_def, in place of an Expression, so set it alongsidesizewhen evaluating costs without a solve.flexdesign.investment_metricsreports NPV and IRR for a solved design. It is reporting only and reads aDesignResultsplus 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 anInvestmentMetricswith the cash flows, NPV at the study rate, IRR vianumpy-financial(Noneif there is no sign change) andsummary().horizon_yearsdefaults to the study length, and later years repeat the last modeled year.
Changed¶
idaes-pseis pinned to 2.13.0 (was 2.12.0). WaterTAP 1.8 requiresidaes-pse>=2.13, so this lets the two be installed side by side.pyomostays at 6.10.1.Breaking:
ReverseOsmosis.recoveryis indexed by time and is no longer a regressable parameter.recovery[t]is fixed at the configuredrecoveryat every step and bounded byrecovery_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 readpyo.value(ro.recovery)or setro.recovery.set_value(...)now indexes a step. FlexParameterize no longer fits RO recovery. OtherSIDOBlockunits keep a scalar, regressablesplit_fraction; a subclass can opt into a time-indexed split by overriding_declare_split_parameter.add_startup_shutdown’sstartup/shutdownare continuous on[0, 1], no longer Binary. Withstatusbinary,transitionplus themin_uptime/min_downtimerows already force them to 0/1, so each unit now carries T binaries instead of 3T. They are no longer tracked byrelax/unrelax; constraints and solutions are unchanged.Breaking:
BatteryModelstart and cyclic conditions are independent options.fix_initial_state(defaultTrue) starts thet=0balance fromcharge_initand registers it as initial state. When it isFalse,charge_initis left free.charge_init_lower_limit,charge_init_upper_limitandcharge_init_soh_limitkeep the start within the same SOC and state-of-health windows ascharge[t].cyclic=Trueno longer frees the start or wrapscharge[0]to the final charge. It now addscyclic_charge, which requires the final charge to be at least the starting charge. A spec that relied oncyclic: truefor a free start must also setfix_initial_state: false.Breaking: initial states are fixed scalar Vars, not mutable Params:
Tank.initial_volume, the electrolyzer’sinitial_liquid_volume,BatteryModel.charge_initand the boiler’sinitial_heat_output.BatteryModel.charge_startis removed; withfix_initial_state=Falsethe free start ischarge_inititself. All four are built withdeclare_process_parameter, so a sweep can set them throughupdate_parametersand a scenario can unfix them and solve for the starting state in place. Code that called.set_value()on them still works, andpyo.value()still reads them.TimeBlock.register_initial_statenow accepts a fixed scalar Var as well as a mutable Param.Breaking: surrogate specs carry
configandparametersinstead ofdata(schema 0.2.0). EverySurrogateSpecand flowsheetsurrogateelement now has the same shape, whether a fit produced it, a live block emitted it, or a person wrote it.configholds everything the surrogate needs besides its fitted values, in the shape its class defines. Examples are variables and units, ARIMA’sorder,deterministic,max_ar_coeffandhistory, and multilinear’sterms.parametersmaps 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), andfixedcovers the whole parameter. ARIMA coefficients are now namedintercept/drift,ar.L1,ma.L1andexog.<input>, the namesupdate_parametersalready used, so each exogenous coefficient stays paired with its input by name.fixeddefaults totrueand is always written on emit. A free parameter may omitvalueto start from the class’s documented guess. Each surrogate type versions its ownconfigwithconfig_versionand migrates older versions when it is constructed.load_specmigrates 0.1.1 files automatically, with aFlexMigrationWarning: 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 ARIMAexog_coefslist with several inputs can’t be paired reliably and is refused, with the equivalent mapping in the error. Saved standalone specs can be upgraded withflexcore.config.surrogate_migration.migrate_surrogate_spec.Breaking: surrogate classes are built from a spec and define their own contract.
MultilinearSurrogate(spec),ArimaSurrogate(spec)andsurrogate_from_spec(spec)take aSurrogateSpec. Build one with the class’s typedmake_spec(...). A class declaresconfig_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’smax_ar_coeffis nowconfig["max_ar_coeff"], not a constructor argument.constant_intensitygets a class,ConstantIntensitySurrogate, which sets the unit’senergy_intensityinstead of swapping a relation. flexparameterize’s regressors build their specs throughmake_spec, andArimaTerms.param_namescomes from flexops’arima_parameter_names, so a fit’s coefficient names and a built block’s registry can’t drift apart.surrogate_coefficientsis removed fromflexparameterize.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_specis a pure read that returns aSurrogateSpec; solved state is recorded byupdate_surrogate_state().OpsBlock.get_surrogate_spec()used to return a baredatadict 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, callunit.update_surrogate_state()after the solve, thenget_surrogate_spec()oremit_model. The update rewrites ARIMA’sconfig.historyfrom the solved horizon; surrogates without time-dependent state are unchanged.ArimaSurrogate.get_surrogate_specis replaced bysolved_history,update_stateandread_spec. An unsolved block is refused.CoefficientRegistrysupports 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, andfix/unfixwith an optional name work on scalars and arrays alike.update_parametersand the newupdate_surrogate_parameterstake nested lists for an array parameter, after checking its shape.apply_specupdates 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¶
LinearRegressorfits inputs on very different scales. scikit-learn’sLinearRegressiondrops singular values below itstol(1e-6), so inputs in units like m^3/s next to Pa came back with wrong coefficients.fitnow scales each column to unit standard deviation before fitting and scales the coefficients back.LinearRegressorfits cross terms that build on the unit. A product column named"a*b"used to be copied into the spec’sinput_variables, soMultilinearSurrogate.buildlooked 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.fitneedsinput_unitsfor each factor and none for the product column.A flowsheet spec can build an
arimasurrogate element. Building one raisedKeyError: '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_modelreads each surrogate’s spec back from its active block, so the spec carries the current values and fixed flags, and no raw-pathfix/unfixpatches 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_parametersor 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_parametersrefuses a name that several surrogates on a unit share. On a unit with two surrogates (an RO skid’ssplit_definitionandpower_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_variablesname 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 andapply_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 aKeyErroror a misleading units error. Aconstant_intensityspec’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 aliasapply_to_modelwrites.apply_to_modelwrites units that a spec can parse back. It recorded Pyomo’sstr()of each column’s units (m**3/h), which spec units don’t accept. It now usesunits_to_str(m^3/h).Tankand electrolyzer separator holdups now include the first time step.Tank.holdupand the electrolyzer’sliquid_holdupwere written only fort = 1, ..., N-1, withvolume[0](liquid_volume[0]) pinned to the initial value, so the flows att = 0were in no balance and the first step’s water entered or left for free. Both balances now cover everyt, with the starting volume as the predecessor oft = 0, asBatteryModel.charge_balancealready did.initial_volume_eqandinitial_liquid_volume_eqare removed.initial_volumeandinitial_liquid_volumeare now the level before step 0’s flows, andvolume[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. ADesignSpec(flexcore.config.design) names a base flowsheet, the modeledyears, the representativemonthsand thecapacitiesto size. Itschangeslist varies any named base element by year, month or both.build_design_modelbuilds one operations model per year and month, merges them underm.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 optionaldaysmodels only its first days and scales the bill up to the full month.design_resultsreports capacities and annualized costs, with a textsummary(). New pages:docs/how_to/run_a_design_study.mdanddocs/explanation/design_annualization.md.$sourcein unit options.construction_optionsnow resolve$sourcereferences, so a long series such asGenericRenewables.capacity_factorcan sit in a file beside the spec.flexops.costing.capital_recovery_factor(rate, lifetime_years)exposes the annuity formulaFlexCostingalready used.BatteryModelcan be sized. A newpower_capacityVar (fixed at the larger power limit by default) sizes power independently of energy, through thepower_charge_limitandpower_discharge_limitrows.cyclic=Truetiescharge[0]to the final charge instead ofinitial_soc, and registers no initial state. Breaking:socis now an Expression,charge / energy_capacity, replacing the Var andsoc_capacity_link.soc_minandsoc_maxare enforced by the linear rowssoc_lower_limitandsoc_upper_limit, so the battery stays linear when its energy capacity is free. Readingpyo.value(battery.soc[t])still works, but afixelement or.fix()onsocmust move tocharge.Breaking:
BatteryModel.capacityis nowenergy_capacity, both the Var and the constructor option, so the two sizing Vars read asenergy_capacity(kWh) andpower_capacity(kW).SCHEMA_VERSIONmoves to 0.1.1, and a 0.1.0 spec migrates on load: aBatteryModelunit’scapacityoption and anyfixorunfixof itscapacityare renamed. Extension functions are user code and are not migrated, so one that readsbattery.capacitymust change by hand.Tank.capacityandGenericRenewables.capacitykeep their names.Solve strategies, warm starts, and solver-neutral options (issue #72).
get_solvertakesstrategy=andsettings=, andSolverFacade.solvetakes explicittee,warmstart,mip_gap,time_limitandoptionskeywords in place of**kwargs.Direct(the default) solves once. The opt-inRelaxAndFix(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=Trueworks onhighs(throughappsi_highs),gurobiandcbc; other solvers log a warning and solve cold.mip_gap/time_limitare translated to each solver’s own option name (time_limitbounds the whole solve, across every step; nativeoptionsare dropped with a warning on a step that falls back to another solver), andSolverSettings.UNIT_COMMITMENTadds Gurobi’sMIPFocus=3,Symmetry=2,Cuts=2. Setting the same native option from two of settings, keyword andoptionsraisesValueErrorrather than one silently winning. Each solve records aSolveReport(steps, wall time, relaxation bound, gap) onSolverFacade.last_report.classifycaches 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.Boilerunit model, fired or heat recovery.flexops.unit_models.powergeneration.boiler.Boiler, selected withboiler_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 viaregister_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 throughsteam_to_water_density_ratio), a steam outlet, a burner limit (max_firing_rate), a backward Euler first-order thermal lag (time_constant, withinitial_heat_outputas the rolling horizon state), an unpricedheat_dissipatedterm so ramp-down and shutdown stay feasible, a thermal export registered at the steam temperature, and an auxiliary electrical draw. The swappable relations areheat_absorbed_relation,heat_recovered_relation,steam_flow_relation,steam_pressure_relation, andpower_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 optionalperiod_hours. The billable wear cost is registered onFlexCostingas the scalar operating cost<unit>_<name>. The watched quantity and the cost rate are registered relations, soswap_relationcan replace them with richer fitted relationships. Seedocs/explanation/degradation.md.degradationspec element. NewDegradationSpec,DegradationTermSpecandDegradationTermmodels, and adegradationelement kind (DegradationElement) that names its unit and acosting_package("auto"by default,nullfor unbilled). A newdegradationbuild stage, after topology and before surrogates, builds it on every member of the unit (so asurrogateelement can swap its registered relations), andadd_degradationrecords itself soemit_modelwrites it back.
Changed¶
An infeasible solve no longer raises on HiGHS.
SolverFacade.solveloads a solution only when the solver found one, so an infeasible model returns results with aninfeasibletermination condition on every solver, logged as a warning, as Gurobi and SCIP already did, instead of raisingNoFeasibleSolutionErroron HiGHS.Fuel-source validators moved to
flexops.unit_models.powergeneration.utils.inlet_names_domain,heating_values_domain,utility_fuel_source_domain,validate_fuel_sources, andheating_value_mismatchare now shared byCombustorandBoiler.Combustor’s behavior and error fields are unchanged.Faster CI. Jobs install with
uvand a dependency cache, and no job waits for lint. The full suite runs once with coverage, in the ubuntu/py3.13unit-testsjob, which also enforces the per-subpackage floors (replacingcoverage-floors) and makes the only Codecov upload.integrationis a single Linux job until integration tests exist.standard-installinstalls one wheel built by a newbuild-wheeljob. Tests run in parallel withpytest-xdist, now in thedevextra (pytest -n auto).
Fixed¶
classifyno longer reports spec-built linear models asNLP. Parsed price units such askWh**-1madepolynomial_degree()returnNone, so natively priced LPs were routed to IPOPT.classifynow 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_configparses each{"value", "units"}value of a mapping option such asheating_values, so aCombustororBoilerwith heating values round-trips throughemit_model/build_model; it previously failed on rebuild.Boiler.boiler_typeaccepts its value string ("heat_recovery"), as a persisted spec holds it, and the unit contract test now coversBoiler.
[0.2.0] - 2026-10-20¶
Added¶
Flat, order-agnostic flowsheet spec (
FlowsheetSpec, schema0.1.0). A flowsheet is one flat list of elements (time,property_package,costing,network,plant,set,unitwith itsconnections,surrogate,dispatch,fix,unfix, the logic kindsstatus,startup_shutdown,dwell,bypass,ramp,startup_delay,conditional,parallel_group,extensionandobjective). An element’snameis the dotted path of the component it builds, so file order never matters.load_spec/dump_specread and write it; units can be indexed over aset, connections can be indexed ({i}) or undirected, and{"$package": name}passes a named property package to a unit. The JSON Schema is exported toschemas/flowsheet_spec.schema.json.build_modelruns 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_specapplies the mutable kinds (surrogate,dispatch,fix,unfix) to a live model, andapply_relation_specis the one path that attaches aSurrogateSpecto a live unit (now used byflexparameterize.apply_to_model).Checked
fix/unfix. Afixnames any variable byComponentUIDpath (*matches every index in a position) with one number, a per-time-point list, a{time: value}mapping or a$sourcefile, plus optionalunitsandat. The state stage plans every point first, so it is all or nothing and order-agnostic: conflicting elements raiseFlexConfigError. Values outside bounds or domain followfix_on_violation(default"error";"warn"and"skip"raise oneFlexFixWarningper element) andfix_tolerance; the result is kept asmodel._flex_fix_report(flexops.FixReport,flexops.FixViolation).flexops.emit_model: code-built model → flat spec. Returns theFlowsheetSpecthatbuild_modelturns back into the same model, covering every element kind, logic recorded by theflexops.logichelpers,@flexops.extensioncalls, and.fix()/.unfix()made in code. It rebuilds the spec and issues aFlexEmitWarninglisting anything it can’t express;data_dir=writes long lists to.json.gzsidecars referenced as{"$source": ...}.flexops.core.compare:model_differenceslists the structural differences between two models andassert_models_equivalentraises on any.Round-trip corpus and unit contract test. Code-built models in
flexops/tests/fixtures/roundtrip_corpus.pyand everyflexops.unit_modelsclass round-trip through emit → JSON → build with noFlexEmitWarning. New how-to:docs/how_to/round_trip_a_model.md.GridConnectionunit model (issue #110). Built on aPlantBlock, it splits the plant’s net electrical draw into non-negativegrid_import[t]/grid_export[t](grid_import - grid_export == total_electrical_power). Optional per-periodmin_import/max_import/min_export/max_exportlimits (None= unlimited) replace hand-written constraints onFlexCosting.aggregate_power. Export is priced byFlexCosting(export_prices=...), not by the unit.Per-period boundary limits accept a series.
Feed/Productperiod-basis limits (andGridConnection’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 likeenergy_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-negativeopex.import_<carrier>/opex.export_<carrier>Vars; an export price above its import price, or a key with noenergy_pricesentry, raisesFlexConfigError. Also available ascosting.export_pricesin the model config. Models without it are unchanged. (#111)EECO
decomposition_typepassthrough.FlexCosting(decomposition_type=...)(andcosting.decomposition_typein the model config) is forwarded to EECO’scalculate_itemized_costfor the electric and gas legs, in both the in-objective cost and the post-solve bill, so tariffexportcharges apply to exporting sites."linear"keeps the model an LP. The bridge functionsadd_electricity_cost,add_fuel_cost,evaluate_costandevaluate_fuel_costtake the same argument. DefaultNoneis unchanged, except that a tariff with an electric or gasexportcharge and nodecomposition_typenow raisesFlexConfigError, 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)fillsoperating.importsandoperating.exports, carrier-keyed dicts for every natively priced carrier, alongside the netelectricityandfuel; tariff-billed carriers are left out, and the default leaves bothNone. (#112)Electrolyzer unit models.
Electrolyzer,WaterElectrolyzer(PEM/AEM viatechnology), andCO2Electrolyzermodel 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 awaste_heatExpression reports stack heat. The per-product Faradaic relations andpower_electrical_relationare registered, so they can be swapped for surrogates.CO2Electrolyzertakes a configurableElectrochemicalProducttable and adds a CO2 feed set by single-pass conversion, plus carbonate crossover. The anode reaction is ananode_productstable (defaultOXYGEN), so a non-oxygen anode such as chlorine evolution is configurable;WaterElectrolyzerfixes it to oxygen. Each gas port builds fromgas_property_packageunless given its own package:cathode_gas_property_package,anode_gas_property_package, or (onCO2Electrolyzer)co2_property_package.Electrolyzer current density, ohmic loss, and dissolved CO2. The operating variable is now
current_density[t](A/cm²), set withelectrode_areaandrated_current_density.current[t]is an Expression, andrated_currentis removed.ohmic_loss(bool, defaultFalse) sets whetheroperating_voltage[t]addsarea_specific_resistance * current_density, a fixed regressable parameter. Enabling it makes power quadratic in current density and logs a warning.CO2Electrolyzer.co2_dissolved_fractionsends 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.reactantsmaps each reactant name to moles consumed per mole of product (negative if produced), replacingco2_per_molandwater_per_mol. The unit builds aconsumption_{reactant}[t]Expression for each reactant, with water always included;CO2Electrolyzer.co2_consumptionis nowconsumption_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_productoption 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.CO2Electrolyzerdefaults it to"H2", sofaradaic_relation_H2andfaradaic_efficiency_H2are no longer built there; passbalance_product=Nonefor a product table without hydrogen.CO2Electrolyzer.mass_transfer_coefficient(withco2_bulk_concentration, default 34 mol/m³) addsco2_local_concentration[t]and a linearco2_transport_limit[t]capping the CO2 used at what diffusion delivers.Electrolyzer model explanation page.
docs/explanation/electrolyzer_model.mdnow 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.
OpsBlockDatanow exposeslist_surrogate_blocks(relation_name=None),current_surrogate_block(relation_name=None),switch_surrogate_block(block_name),fix_surrogate_coefficients(relation_name=None), andunfix_surrogate_coefficients(relation_name=None). When called withoutrelation_name, list/current operate across all relations on the unit, matching the common case of a single-relation unit.CoefficientRegistrysupports indexed Vars. The registry now accepts both scalarpyo.Varand indexedpyo.Varobjects.register_coefficientsdetects an indexed Var and iterates over its index set automatically, surfacing a flatname → VarDataview to callers. This removes the need for per-coefficient name sanitization inMultilinearSurrogate.MultilinearSurrogateuses a single indexed Var for coefficients. Instead of creating one scalarpyo.Varper coefficient (requiringalphanum_label_from_namesanitization that could collide),build()now creates onecoefficient_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_parametersworks on surrogate coefficients. Registered surrogate coefficient Vars (including indexed-Var entries) can now be mutated in place through the standardupdate_parameterspath. 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_blocksandcurrent_surrogate_blockwith and withoutrelation_name, named-relation fix/unfix,CoefficientRegistryduplicate/non-Var/bulk registration, andupdate_parameterson 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.ArimaRegressorcan fit the criterion the Pyomo surrogate actually runs.forecast_horizonminimizes windowed free-run error: the series is cut into windows ofHsteps, each seeded from actual data and simulated forward with innovations at zero, as the surrogate forecasts. The horizon is an int number of steps (default1) or a duration such as"2D","48h"orpd.Timedelta(days=2), the same formsto_surrogate_spec(history_length=...)takes, whichfit()rounds up to whole steps of the training index. AtH=1that 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 separatefit_objectiveoption. Longer horizons exist because ad=1model 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=192cut meand=1forecast RMSE from 0.0095 to 0.0065 and made no difference ford=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 forARIMA(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 thed=0objective so flat thatleast_squaresground to its 5000-evaluation limit.metrics["free_run_rmse"], plusma_max_rootandforecast_horizoninfit_diagnostics(). The free-run error is reported at the fit’s own horizon, so at the defaultforecast_horizon=1it equals the one-steprmse. 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 > 1are kept stable. Every MA coefficient is bounded to[-0.99, 0.99], and a fit whose MA block is still non-invertible (possible forq >= 2) raisesFlexConfigError. 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 defaultforecast_horizon=1MA 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 bymax_ar_persistencedoes 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 raisesFlexConfigErrorwhen 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. Withmax_ar_persistence=Nonethe check still applies.FlexCostingData.relaxation_gap(model, results)returnsreported bill - in-objective proxypost-solve (positive: the objective understated the bill). It raisesFlexSolverErrorifresultsis not an optimal solve.
Changed¶
ArimaRegressor(auto=True)uses its own order search;statsforecastis no longer a dependency.statsforecast2.1+ requirespandas<3, so with the corepandas>=3pin pip fell back to 2.0.3, which capsscipy<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 picksdfrom KPSS (null: stationary) and ADF (null: unit root) tests at 5% on the disturbancey - X @ beta:d=1when only KPSS rejects,d=0when only ADF rejects. When both reject (contradictory) or neither does (inconclusive) it raisesFlexDataError, suggesting more exogenous covariates (e.g. lagged inputs), removing trends or seasonality, or passingd=0/d=1explicitly; a series too short for ADF is refused the same way. ADF comes from statsmodels, imported only whendis tested, so it needs the[parameterize]extra andimport flexparameterize.regressionworks without it. It then fits every(p, q)within the limits by one-step least squares (undermax_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, andstationary. Any other keyword raisesFlexConfigError, where it was previously forwarded toAutoARIMA.max_d=2ord=2is now refused at construction instead of after the search. Selected orders may differ fromAutoARIMA’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 lasthistory_lengthof fitted disturbances and innovations plus themax(p + d, q)lags ahead of them, and moveshistory.start_dateto 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=0keeps only the terminal state for forecast-only use, andNonekeeps 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 keyhistory.y_valuesis renamedhistory.eta_values, since it holds the disturbancey - X @ beta, not the output; specs saved withy_valuesmust 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.pynow holds onlyArimaRegressor. 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 onefree_run, and both recursions run throughscipy.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 totests/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 nowregressor.model.terms.p/d/…;predict(start=...)raisesFlexDataErrorinstead of indexing out of range whenstartleaves fewer thanmax(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
rmseno longer counts the artificial first row of ad=1fit. The level-scale fitted values set row 0 equal to the data, which counted as a zero-error point.rmseis now exactlysqrt(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 takestime_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_specno longer passes it. No backward compatibility is kept for the old three-argument form.ARIMA information criteria now exclude the zero-padded leading residuals.
residkeeps its full length for alignment, but the leadingmax(p, q)entries carry no residual, and dividing by them understatedsigma2and inflated the log-likelihood.llf,aic,bic, andsigma2are now computed over the newDirectResults.effective_resid/nobs_effective, so reported values shift (more so for high orders on short series) andfit_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. Withinclude_mean=Falseandd=0the spec previously carriedintercept: 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, whileinclude_mean=Falseemits nothing.to_fit_result()matches, and no longer drops a legitimately-zeroconst.ArimaRegressordrops the statsmodels/statsforecast look-alike options that did nothing here.seasonal_orderis gone: onlyNoneor the no-op(0, 0, 0, m)was accepted, and withauto=Trueit only switched on a seasonal AutoARIMA search whose resultsfit()then had to reject.include_driftis gone: ford=1it was an alias forinclude_mean, and ford=0an error.stationaryis gone as a named argument; it still reaches AutoARIMA through**auto_kwargs(ArimaRegressor(auto=True, stationary=True)works as before).DirectResults.predict()losesdynamic, which only ever acceptedTrue.aiccis removed fromDirectResultsandfit_diagnostics()(previouslyNonewhen undefined);aicandbicremain. The AutoARIMA search is now always non-seasonal, soauto_kwargsmay no longer setseasonaloric, which raiseFlexConfigError. Extra keywords withoutauto=Truenow raiseFlexConfigErrortoo; 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 fromybut the full, undroppedXwas 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, socaplognever saw the warning and"non-invertible" not in caplog.textheld unconditionally. ARIMA tests now capture the module logger directly.ArimaRegressor.fit()raisedZeroDivisionErroron short series.fit()computes AICc viamodel_, so an order the row-sufficiency check accepts – e.g.order=(0, 0, 0)on three rows – crashed inside_aicc_from_directinstead of fitting.ArimaSurrogateaccepted a history too short to build from._validaterequiredlen(y_values) >= p + dandlen(eps_values) >= q, butbuild()slices both out of a sharedmax(p + d, q)prefix. Withq > p + da short history passed validation and then failed inbuild()with a misleading “y_values and eps_values must contain the same number of modeled points”. Both series are now checked againstmax(p + d, q)up front. Regression mode, which supplies nohistoryat all, is unaffected.ARIMA docstrings corrected.
ArimaRegressor.predict()no longer claimssteps=0returns in-sample fitted values (it returns an empty array);_auto_select_orderno longer claims non-seasonaldis forced to 0 (only seasonalDis);fit()now documents its real row-sufficiency requirement instead oforder[2] + 1;to_surrogate_spec()documents thehistoryfield it actually emits rather than a nonexistentinitial_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()andget_surrogate_spec()gained their missingArgs/Returns/Raisessections, the latter documenting thattime_indexis validated but that the extracted history always spans the full horizon.Two ARIMA cross-validation tests were mismarked as
unitwhile solving with ipopt.test_pyomo_matches_direct_fit_for_multiple_arima_ordersandtest_reswapping_arima_relation_succeeds_and_uses_latest_coefficientsare nowcomponent+needs_ipopt, per the rule that unit tests must not invoke a solver.Removed dead ARIMA code. The
innovation_squareExpression on the surrogate block (never read;get_regression_objectivesquaresepsitself),ArimaRegressor._fitted_values(assigned, never read), the unreachable_DirectResults.fittedvalues_levelreconstruction fallback (the array is always supplied by_fit_direct, and itsd > 1branch was wrong for a class that only allowsd <= 1), and the commented-out seasonal-order placeholder into_surrogate_spec. The tautologicaltest_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_roundtripcompared signed relative deviations.np.max((a - b) / b)let an arbitrarily large negative in-sample or forecast deviation pass the< 1e-4gate; 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-dindexing bug whereself._resid(aligned to the differenced series) was sliced using a level-indexstartunshifted byd, silently misaligning the MA lookback for everyd=1, q>0model.An infeasible solve no longer raises on HiGHS.
SolverFacade.solveloads a solution only when the solver found one, so an infeasible model returns results with aninfeasibletermination condition on every solver, logged as a warning, as Gurobi and SCIP already did, instead of raisingNoFeasibleSolutionErroron HiGHS.Fuel-source validators moved to
flexops.unit_models.powergeneration.utils.inlet_names_domain,heating_values_domain,utility_fuel_source_domain,validate_fuel_sources, andheating_value_mismatchare now shared byCombustorandBoiler.Combustor’s behavior and error fields are unchanged.Faster CI. Jobs install with
uvand a dependency cache, and no job waits for lint. The full suite runs once with coverage, in the ubuntu/py3.13unit-testsjob, which also enforces the per-subpackage floors (replacingcoverage-floors) and makes the only Codecov upload.integrationis a single Linux job until integration tests exist.standard-installinstalls one wheel built by a newbuild-wheeljob. Tests run in parallel withpytest-xdist, now in thedevextra (pytest -n auto).BREAKING: the nested
ModelConfigformat is removed.ModelConfig,NetworkConfig,PlantConfig,ArcSpec,load_model_config,dump_model_config,load_surrogate_source,SurrogateSpec.sourceandflexparameterize.emit_model_configare gone; write configs as flat specs, and save a parameterized model withapply_to_modelthenflexops.emit_model. The unbuiltUnitCommitmentConfigfields (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
statuselements by settingallows_status_element = False(asTankandBatteryModeldo), and logic that needs a status checks that the built unit has one.FlowsheetSpecno longer lists unit classes (SELF_STATUS_CLASSESandNO_STATUS_CLASSESare removed), soload_specaccepts these two mistakes andbuild_modelraisesFlexConfigErrorfor them, still before any solve. (#126)build_modelnow expands arcs by default (expand_arcs=True), so logic and extensions can use the expanded equalities. Passexpand_arcs=Falsefor 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_coefficientsnow uses registry key names forParameterRecord. 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’slocal_name. This makes target removal and parameter lookup correct for all coefficient storage modes.swap_relationfitted constraint activation.switch_surrogate_blocknow explicitly activates the fittedConstraintafterblock.activate(), because PyomoBlock.activate()does not cascade to childConstraintobjects that were explicitly deactivated.EECO pinned to
eeco==0.4.2(from0.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(from0.4.0). 0.4.1 prices a top tier at one constant rate exactly in the objective, with no estimate, so the demo tariff’stier2surcharge is no longer dropped.
Fixed¶
Unit-model reference pages render their tables again. The unit-model autosummary entries named the
unit_model.rsttemplate by a path Sphinx could not resolve, so every page silently fell back to a bareautoclasswith 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_unitsreads 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 bare1.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.pynever forwarded a consumption estimate to EECO, which without one drops every tier other than a flat top tier. The newCostingConfig.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 throughadd_electricity_cost/add_fuel_cost/add_operating_cost. The defaultNonekeeps the previous behaviour. A warning is now logged when a tariff tier would be zeroed because its utility has no estimate, andCostingConfig.consumption_estimateonly 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 repoflex-pse-examples, published as an interactive site at flex-pse.github.io/flex-pse-examples; the marimopump_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 thetariff.json/dr_events.jsonfixtures now live undersrc/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 thanexamples/.
Added¶
The docs system is finished.
docs/_ext/flexdoc.pyadds two generated-content Sphinx directives:flexops-unit-tablesbuilds 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), andflexops-config-tablerenders a pydantic config model’s fields. Every public unit model — theSISOBlock/SIDOBlock/DIDOBlocktopology 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 theunit_model.rstautosummary template.docs/explanation/config_schema.mdrenders the fullModelConfigfield tree the same way. Newdocs/explanation/reported_cost.mdexplains, in plain language, why the number in a cost report is never the solver’s internal objective.docs/reference/flexparameterize/index.rstgains a section for theflexparameterize.estimationnative-constraint NLP estimation API, documented as the reserved, not-yet-implemented surface it is.src/flexops/tests/docs/test_flexdoc_tables.pyis the unit test guarding againstflexdocsilently 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 acrossflexops,flexcore, andflexparameterizedropped itsM09/R3/§-style references, in favor of plain-language explanations — readers of the published docs have no access toplan/, so those citations pointed nowhere. Several pages that had gone stale relative to the actual codebase (the arc/topology layer described as “M09, future” whenNetworkBlock/PlantBlock/Arccomposition has long since landed; a rolling-horizon relaxation pipeline described as available whenflexscheduledoes 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-exampleshas moved on from Jupyter notebooks pulled into this repo’s Sphinx build viamyst-nb/nb_execution_modeto its own marimo + WebAssembly site with a precomputed-data pipeline and independent GitHub Pages deploy. Rather than force a stale integration model,docs/conf.pydropsmyst_nb/nb_execution_modefor the lightermyst_parser(Markdown parsing only, no notebook machinery to speak of), and newdocs/examples/index.mdlinks out to the liveflex-pse-examplessite instead of embedding and executing notebooks.docs.yml(replacingbuild-docs.yml) builds and deploys this repo’s own docs only, with no cross-repo checkout step; there is nonightly.yml, since there is no longer a notebook-execution safety net to run. Thedocsextra swapsmyst-nbformyst-parseraccordingly.BREAKING: a unit’s constant energy intensity is now metered on its product flow, not its inlet.
OpsBlockData.add_constant_intensity_relationkeyspower_electrical[t]to the flow the unit delivers, soenergy_intensityreads as energy per unit of output.ConstantEnergyIntensityModelandPumpmove to the outlet flow (numerically unchanged — the SISO pass-through ties it to the inlet),Exchangertoflow_out_a, andReverseOsmosistopermeate, 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. ThePumphydraulic relation is untouched — it is a physical power law, not an energy intensity. The basis is recorded perPowerKindon the newIORegistry.intensity_basis, andflexparameterize.apply_to_modelregresses against exactly that stream (falling back to a unit’s single non-power registered output for a unit that hand-rolls its relation, asPumpstill does).BREAKING:
SurrogateSpecnames a predefined surrogate class instead of an open-string builder;schema_versionis now0.0.3.functional_form/coefficients/input_variables/output_variablesare replaced bysurrogate_type(aSurrogateTypeenum member) and an opaquedatamapping in the shape that class defines. The class (flexops.surrogates) validatesdatain its__init__and builds the Pyomo relationship inbuild(); a type not yet implemented raisesNotImplementedErrorat build time, an unknownsurrogate_typename 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’sdatacontract — telling the user to re-emit it; the exported JSON Schema is regenerated.multilinearis the one implemented surrogate class, covering what werelinear(no cross terms) andbilinear(one cross term): a constant plus a sum ofcoefficient * (product of distinct declared inputs).quadratic/polynomial/^-exponent terms are gone; a coefficient key is a*-separated product of names fromdata['input_variables'], each appearing at most once, plus the reservedintercept. 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, raisingFlexConfigErroron a dimensionally incompatible declaration instead of silently rescaling.QuadraticSurrogate/ExponentialSurrogate/ArimaSurrogate/NeuralNetworkSurrogateare reserved classes raisingNotImplementedError, namingMultilinearSurrogateas the implemented alternative.BREAKING:
OpsBlockData.swap_energy_relationis gone, replaced byregister_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), andswap_relation(relation_name, surrogate)replaces it in place, taking a liveflexops.surrogates.Surrogateinstance (built viasurrogate_from_spec) rather than aSurrogateSpecdirectly, and resolving units from the relation’s own target rather than assuming kW. Every constant-intensity unit registers its own energy relation automatically;SIDOBlock/ReverseOsmosisadditionally registersplit_definition(recovery/flux) andTankitslevel_definition(fill geometry) — conservation constraints on both are deliberately not registered.Pump’s default relation is folded onto the sharedadd_constant_intensity_relationpath (previously hand-rolled aspower_eqwith a mutableParam), so it is renamed topower_electrical_relation, its intensity becomes a fixed, regressableVar, and it is swappable for the first time; thehydraulicpower law is untouched (a physical relationship, not an intensity, and not registered).flexparameterize.apply.ApplyReport.swapped_units: list[str]is replaced byswapped_relations: dict[str, list[str]](unit -> relation names), andapply_to_model’ssurrogates=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_relationcallssurrogate.build(unit, target)on whateverSurrogateit is given — any Pyomo-expressible function of the unit’s own variables, returningpyomo.environ.Constraint.Skipfor 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 newSurrogatesubclass, never a config-schema change.
Added¶
flexops.surrogates: the predefined surrogate-structure classes (SurrogateABC,SURROGATESregistry,surrogate_from_spec), a leaf subpackage offlexops(imports onlyflexcoreand Pyomo) so a config’s surrogate is realized at unit construction time with noflexparameterizeimport anywhere inflexops. See “Changed” above forMultilinearSurrogateand the four reserved stubs.flexops.core.units.parse_units, extracted fromflexops.core.build(still re-exported there) into a leaf moduleflexops.surrogatescan import without a cycle.flexops.core.registration.RelationRecord/IORegistry.relationsanditer_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, orapply_to_model) — not a required step on any build or apply path, and not a detector of changes made outsideswap_relation.flexcore.config.io.load_surrogate_sourceand the newSurrogateSpec.sourcefield: a relationship may live in a JSON sidecar supplyingdatainstead of being inlined in the config. A relative path resolves against the config file’s own directory, andload_model_configfills 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 dottedplant.unit.variablealiasing, JSON-loadable,difflibsuggestions for unmapped columns and no new dependencies);check_sufficiency/SufficiencyReport/IOPairStatus(validate.py, per-registered-IO-pair coverage, non-null counts andDatetimeIndexalignment — it reports, it never raises);ConstantIntensityRegressor(regression/constant.py,intensity = mean(power / flow)after dropping null and zero-flow rows, withr2/rmse/n_samples/data_window);emit_model_config(emit.py, fit -> aModelConfigthatbuild_modelrebuilds the parameterized model from, with provenance carrying the fit metrics, data window and theflex-pse/pyomo/pandasversions read at emit time); andapply_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’spower_electrical_relationand attaches an equality built from theSurrogateSpec, on the same unit object with its ports and arcs untouched). Both directions consume the sameSurrogateSpecfrom the same regressor, so they cannot disagree;apply_to_modelraisesFlexDataErrorup front on insufficient data, since it mutates a real model. Both also accept a hand-builtSurrogateSpecdirectly — a vendor curve or datasheet coefficient needs no data, no sufficiency check and no regressor — andapply_to_model’ssurrogates=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 newdocs/reference/glossary.mddefining zero-degree-of-freedom regression and model alias.The pluggable-regressor protocol, and
LinearRegressor.flexparameterize.regression.base.Regressor(aruntime_checkabletyping.Protocol:fit(X, y) -> Self,to_fit_result() -> FitResult,to_surrogate_spec(**kwargs) -> SurrogateSpec) andFitResult(coefficients/metrics/n_samples/data_window) formalize the shape every regressor’s fit already reduced to by hand;ConstantIntensityRegressorgainsto_fit_result()with no other change.LinearRegressor(regression/linear.py, needs the[parameterize]extra’s newscikit-learndependency, 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 amultilinearSurrogateSpecconsumed identically byapply_to_modelandemit_model_config.flexparameterize.regression.get_regressor(surrogate_type)resolves aSurrogateType(member or string) to the regressor that fits it, raisingNotImplementedErrorfor the four still-reserved types andFlexConfigErrorfor an unknown one.emit.py’s_surrogate_and_fit_provenancenow reads a fit’s four provenance fields offto_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)andProduct(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’sflow_vol_phaseby hand, and a product existed only as a barePlantBlockData.register_product(...)call against some other unit’s variable — nothing owned a boundary stream, metered the total resource crossing it, or priced it. AFeedis a source (zero inlets, N namedoutlet_{name}ports) that carries the boundary state, meterswithdrawal[t]through the equalityeq_withdrawal, and passes its composition/pressure/temperature downstream over arcs; aProductis the mirror sink (N namedinlet_{name}ports, zero outlets) aggregatingdelivery[t]througheq_delivery. Both subclassOpsBlockDatadirectly, since a config-driven port count fits no fixed-arity topology base, and neither declarespower_electricalorpower_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 inoutlet_names— carries the boundary conditions and every other outlet is held at it byoutlet_state_equality_{state_var}[t, name]: one source, one condition. AProductdeliberately does not blend; each inlet’s intensive states arrive from its own arc and stay independent, because blending isMixer’s job and is bilinear.resource_nameis the aggregation key, independent of the Pyomo block name, and defaults to that block name soplant.raw_water = Feed(...)andplant.citric_acid = Feed(...)are distinct resources with no extra config. Two blocks sharing aresource_namesum 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. ManyFeed/Productblocks 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(andmin_demand/max_demand) take a units-carrying scalar and buildwithdrawal_min/withdrawal_maxplus their_limitConstraints, converted onto the flow basis. Params rather thansetlb/setubbecauseset_valueis the sanctioned in-place update path (conventions §9), because they surviveset_external_dispatchfixing 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 inheritedset_external_dispatch.withdrawal_basis/demand_basischoose 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 scalarwithdrawal_total/delivery_totalVar and the equalityeq_withdrawal_total/eq_delivery_totaldefining it assum_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 meteredwithdrawal[t]/delivery[t]stays time-indexed under either basis, so costing,total_feed/total_productaggregation andset_external_dispatchare 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) raisesFlexConfigErrornaming the config key rather than silently rescaling. A basis with no limit configured builds nothing.priceis a flat scalar routed through the existingFlexCosting.register_scalar_cost, so its sign convention is unchanged: positive is a cost (raw water withdrawn, brine disposed), negative is revenue (potable water sold). Apriceset with nocosting_packageraisesFlexConfigError(field="price")rather than silently dropping the cost.
PlantBlock/NetworkBlocknow aggregate boundary flows intototal_feed[resource, t], andtotal_product[resource, t]merges both routes. Discovery keys off the new_io_registry.boundaryrecord, the same way power and fuel are discovered — never anisinstancecheck againstFeed/Product, which would be a circular import (flexops.unit_modelsimportsflexops.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 explicitregister_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_linkalready takes time-indexed quantities, so a plant total is passed aspyo.Reference(plant.total_product["potable_water", :])and a boundary total asfeed.withdrawaldirectly.OpsBlockData.register_boundary_flow(var, *, resource, kind), withflexops.core.registration.BoundaryKind(FEED/PRODUCT) andBoundaryRecordon theIORegistry. Modelled onregister_fuel_usage: any unit may register a boundary flow, not onlyFeed/Product, and an emptyresourceraisesFlexConfigError(field="resource").flexcore.nomenclature.TOTAL_FEEDjoinsTOTAL_PRODUCT/TOTAL_FUEL_USAGEas 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 oneoutletby the single equalitymixing_mass_balance. Density is assumed constant across the junction, so volume is conserved directly and there is no energy input: the unit declares neitherpower_electricalnorpower_thermal. Pressure (and any other intensive state the property package carries) is held at the reference inlet’s value — the first name ininlet_names— and passes through to the outlet, the way it behaves at a physical mixing node.temperature_mixingchooses 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 viaoutlet_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 aUserWarningin the two configurations that reach past what it represents: aproperty_packagecarrying 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 — oneinletdivided among N named outlet ports (outlet_{name}) by the single equalitysplit_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 aSplitteris not a generalizedSIDOBlock. Callers wanting a prescribed split should keep usingSIDOBlock(orReverseOsmosis), whose fixed and regressablesplit_fractioncloses those degrees of freedom. Everything the stream carries other than flow passes through to every outlet.Both units subclass
OpsBlockDatadirectly, 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 viafind_component) across a caller-chosen subset of a network’s plants — e.g. one building’s power draw within a larger campus — building aVar/Constraintpair (defaulting toaggregate_{var_name}/eq_aggregate_{var_name}). A plant missingvar_nameis skipped with a logged warning. Calling again with the samenameupdates the existing Constraint’s body in place (never deleting it, conventions §9); passreplace=Falseto 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.unitsis 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 andunits[0]is the first one on. Chainsadd_conditionalover every consecutive pair rather than re-implementing implication logic, returning thelen(units) - 1attachedconditionalConstraints; each pair’s Constraint lands on the later unit, sounits[0]carries noconditional.variablesnames continuous Vars — as each unit exposes them, so a renaming unit’s renamed name (ReverseOsmosiscarriesrecovery, notsplit_fraction) — to order the same way, as{name}_orderingConstraints attached beside each pair’sconditional. 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 nothenargument, because pairwise mutual exclusion is a different relation and not what a parallel group means; callers wanting “these two may not run together” calladd_conditional(a, b, then="off")on the pair directly.order_status=Falseskips the status chain and orders the namedvariablesalone. This is how a group whose units carry nostatusVar is registered:statusis attached by the caller viaadd_status, never by a unit’s ownbuild(), so absent hand-applied unit commitmentadd_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. RaisesFlexConfigErrorfor fewer than two units, a repeated unit,order_status=Falsewith novariables(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 = 50under identical linear cost,25/25,30/20and50/0all satisfyf0 >= f1at equal cost. The module docstring previously claimed the stronger property; corrected here and in the reference page.docs/reference/flexops/logic.rst: theflexops.logicpackage was previously undocumented; it now has a reference page covering the unit-commitment pieces and stating the canonical parallel-train ordering once.CostReportnames its own currency.report_costnow returns aCostReportwith acurrency: strfield (str(base_currency)— the tariff sheet’s basis when a tariff is given, else the configuredcurrency), 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 costVar/Paramdoc=strings (which already carried the currency in theirunits=), andCostingConfig.fixed_operating_cost, which claimed “in dollars” but is denominated in whatever basis is in force.schema_versionis unchanged (only adescriptionstring moved); exported JSON Schema regenerated.OpsBlockData.create_stream_naming_convention()and anaming_dictargument on every IO-topology base’sbuild()(SISOBlock/SIDOBlock/DIDOBlock). Each base carries its generic role -> Pyomo component name mapping as_component_namesand registers it at the top ofbuild(); 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", ...}), asReverseOsmosisdoes forfeed/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 awindow-step span (the “N-minute ramp rate” pattern), withramp_up/ramp_downindependently optional. Builds the ramped quantity as its own trackedVartied tovarby a defining equality, rather than inliningvar[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. Everyt < windowis 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_costand theevaluate_cost/evaluate_fuel_costbridges gained an optionalprev_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 toNone, 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_costpassdemand_scale_factorandfixed_scale_factor(andprev_demand_dict) toeeco.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_nameshelpers and the customer-key manipulation in_charge_dict, which is now a thinget_charge_dictwrapper. Reported totals are unchanged. Keepingdemand_scale_factorandfixed_scale_factoras 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 optionaldemand_scale_factor/fixed_scale_factoroverrides when a rolling-horizon weighting policy needs them.EECO pinned to
eeco==0.4.0(from0.3.0). Required, not cosmetic:fixed_scale_factor— the kwarg the proration change above passes tocalculate_cost/calculate_itemized_costto prorate the customer charge — does not exist in 0.3.0. The bump is otherwise purely additive (0.4.0 removes nothing and also addsget_timesteps,get_billing_period_scale_factorandget_prev_demand_dict, none of which flex-pse calls).Renamed the example plant block
svcwtowaterfacilitythroughout 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 theenergy_intensitybasis (issue #85). The class docstring’s math and Config summary saidP_elec[t] = energy_intensity * V_feed[t], while theenergy_intensityConfigValue said “product” andbuild()has applied the intensity to the permeate since bc69357 (#76) — a factor ofrecoveryapart. 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 configuredenergy_intensityon the pre-bc69357 feed basis are drawingrecoverytimes too little power and should divide their configured value byrecovery.BREAKING:
register_parallel_groupordered its group backwards (issue #64). It chainedadd_conditional(units[i], units[i+1], then="on"), expanding tounits[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 forcedu0.status == u1.statusat everyt, locking every train on or off together. The chain is now built back to front (add_conditional(units[i+1], units[i])), givingunits[0].status[t] >= units[1].status[t] >= .... Callers relying on the old direction must reverse theirunitslist; the pair Constraints also move fromunits[0..n-2]tounits[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_delaysampled a single lagged point instead of the trailing window (issue #68). It builtunit.status[t] <= upstream.status[t - k], which never constrained againstupstream.status[t]itself (the downstream could run while the upstream was off outright) and only checked the pointt - krather 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 everylagin0..k, so the downstream may be on attonly if the upstream was on continuously across[t - k, t]. Newinitially_on: bool = Truekeyword 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 att = 0counts as warmed up (right for a standalone horizon);Falsekeeps the oldstatus[t] == 0clamp fort < k(right for a rolling-horizon window with no assumed prior state), now on a separatestartup_delay_coldConstraint.
Removed¶
BREAKING: automatic parallel-train detection is gone.
flexops.logic.detect_parallel_trainsandflexops.logic.break_parallel_symmetryare removed, along with the v0 interchangeability predicate behind them (same*Dataclass, same Port names, and every comparable config entry equal) and the block-leveltrain_orderingConstraint 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_groupis the whole API; callers ofbreak_parallel_symmetry(plant)replace it with an explicitregister_parallel_group([...])per group, which additionally orders continuous variables.BREAKING:
dens_massis no longer a state variable on either property package, andSimpleAqueousFlow’sfixed_density/densityconfig options are gone. No unit model needed density — it was structural boilerplate inherited from WaterTAP’sprop_ZOpattern, and carrying it only added a state variable to fix.SimpleAqueousFlowstate blocks now carryflow_vol_phaseplus the opt-inpressure/temperature;SimpleGasFlowcarriesflow_vol_phase/pressure/temperature. Callers passingfixed_density=/density=(includingexamples/api_freeze.py, the frozen-API tripwire script, and thepropertiesblock of a persisted config) must drop those keys.BREAKING:
Combustor.outlet_density_eqis 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 atflue_gas_temperature.
Added¶
PlantBlock/NetworkBlocknow aggregate registered fuel usage intototal_fuel_usage[fuel_name, t](m³/hr), alongside the existingtotal_electrical_power/total_thermal_power/total_product. Follows thetotal_productpattern: keyed by fuel name (there is noFuelKindenum), 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
Tankunit model’s internal module and implementation class fromstorage_tank/StorageTankDatatotank/TankData, matching the publicTankname. No public API change.Moved the private per-
PowerKindname registries (_POWER_VARS/_INTENSITY_VARSinops_block.py,_TOTAL_POWER/TOTAL_PRODUCTinplant_block.py) intoflexcore.nomenclatureas public constants (POWER_VARS,INTENSITY_VARS,TOTAL_POWER_VARS,TOTAL_PRODUCT, plus the newTOTAL_FUEL_USAGE), consistent with nomenclature already being the single source of canonical component names. Pure relocation, no behavior change.
Fixed¶
jsonschemawas missing from thedevextra, sotest_api_freeze_config_is_schema_valid(src/flexops/tests/test_api_freeze.py) failed withModuleNotFoundErroron a cleanpip install -e .[dev]. Added topyproject.toml’sdevlist.
Added¶
Combustor: the firstSimpleGasFlowunit 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_packageIO-topology base (SISOBlock/SIDOBlock/DIDOBlock). A combustor’s inlet count is a config option (inlet_names), so no fixed-arity base fits —Combustorsubclassesflexops.core.ops_block.OpsBlockDatadirectly and hand-writes its own ports, mixing mass balance, and energy relation, the wayBatteryModeldoes. Deviates from the earlierCombustor(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 theBatteryModeldischarge 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 constraintpower_electrical_sign[t]: power_electrical[t] == -power_generated[t]. Onlypower_electrical_relationis registered, soswap_relationcan 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 withpower_electrical’s upper bound of 0.power_generated(notpower_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, elsepower_generated[t] = energy_intensity * Σ flow_in_i[t](the sign constraint above carries either topower_electrical).efficiency, everyheating_value_iandenergy_intensityare all bounded below at 0, so unfixing one for a design mode or a regression cannot flip the relation’s sign. A partialheating_valuesmapping, or an option the resolved relation would ignore (efficiencyunder constant intensity,energy_intensityunder heating value), raisesFlexConfigErrornaming the field. Both build the Constraintpower_electrical_relation— the same swap-contract name every other unit uses, soFlexParameterize’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. Plusinlet_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_temperatureconfig option.New
flexops.testing.dummy_gas_time_block(n)— theSimpleGasFlowtwin ofdummy_time_block, needed becauseSimpleGasFlow’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.
GenericRenewablessplits its magnitude from its sign the same wayCombustordoes (above). Its registeredpower_electrical_relationdeterminespower_generated[t] == capacity_factor[t] * capacity— non-negative, bounded below at 0 — and the deliberately unregisteredpower_electrical_sign[t]negates it intopower_electrical[t], so a swapped-in output curve (a fitted irradiance or wind-speed relationship) cannot flip the unit into a load.power_generatedrather thanpower_electricalis its registered IO output, so a fit is written in generation-magnitude space.GenericRenewables.capacity_factormust lie in[0, 1], checked inbuild()alongside the existing shape and horizon-length checks and raisingFlexConfigError(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 bysrc/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 twinexamples/api_freeze_config.jsonbuilds through the newfo.build_model(...)and is held to the same solved objective. Delivered to get there:Composition (
fo.PlantBlock,fo.NetworkBlock). APlantBlockis a collection of unit blocks (one facility, holding the arcs between its units); aNetworkBlockis a composition of plant blocks (R7) — a plant is never nested inside a plant. Both are thin IDAESFlowsheetBlockDatasubclasses forced todynamic=False, with theTimeBlock’s ordered integerSetinstalled as their time domain by reference (plant.time is time_block.time_index; never Pyomo.DAE, R2). Each exposestotal_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 areplace_unit: FlexParameterize mutates units in place. A plant canregister_product(var, name=..., quality=...); the network sums the amounts intototal_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 onlyTimeBlockand raisesFlexConfigErroron zero or several.IO-topology bases
SIDOBlock(1→2) andDIDOBlock(2→2), joining M04’sSISOBlock.SIDOBlocksplits one feed intooutlet_a/outlet_bwith two constraints — conservationflow_in == flow_out_a + flow_out_bplussplit_definition(flow_out_a == split_fraction * flow_in), since conservation alone leaves the split undetermined.DIDOBlockcouples two streams through onetransfer_fraction(flow_out_a == (1 - f) * flow_in_a,flow_out_b == flow_in_b + f * flow_in_a). Both ratios are fixed, regressable scalarVars, so the topologies stay linear/LP-representable and the split is the natural regression target.SIDOBlockbounds 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 (seeReverseOsmosisbelow). Each base passes everything a stream carries other than flow through to each of its outlets;OpsBlockData.add_pass_through_constraintsgains aname_prefix=so a multi-outlet topology’s repeated calls do not collide on one component name.The physical zoo: no intermediate
Separator/Electrolyzerclass (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_namesdict resolved throughOpsBlockData._named().Exchanger(DIDOBlock)andReverseOsmosis(SIDOBlock)(outlet_aispermeate, and the split is renamed torecovery—split_fractiondoes not exist on the skid — bounded by the newrecovery_min/recovery_maxseawater window, which an inverted or unsatisfiable setting rejects withFlexConfigError).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’swaterfacility.plant). There is deliberately noLinearRegressionModelor 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 intensityVar(energy_intensity/thermal_intensity, fixed and registeredregressable=True), and the equality as the Constraintpower_electrical_relation(resp.power_thermal_relation). That name is the documented swap contract: newOpsBlockData.swap_energy_relation(surrogate, kind=...)deactivates exactly it (never deletes — conventions §9) and attachespower_<kind>_relation_fittedbuilt from a fittedSurrogateSpec, 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_intensityform) and, from M10,flexparameterize.apply_to_model.linearis the one fitted form v0 builds; the reservednn/arima/multiconvexraise.OpsBlockData.build_from_config(cfg, **kwargs)is real (aNotImplementedErrorstub since M03). It round-trips a path/mapping through the pydantic schema (so a raw dict is never passed on, conventions §4), resolvescfg.unit_model_classagainstflexops.unit_models, and merges construction options with the caller’s runtime-only ones (property_package,costing_package), which win. An invalid config raisespydantic.ValidationErrorunwrapped, 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 validatedModelConfig. Arcs are declared but not expanded — applyingTransformationFactory("network.expand_arcs")stays the caller’s explicit step, in the config path as in the script. Newparse_quantity/parse_unitsresolve 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’sbuild_from_configTODO 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) andexamples/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-outdocs/how_to/build_a_plant.md(build order, the config conventions, multi-plant networks), the R2/R7 rationale indocs/explanation/time_and_dynamics.md, and reference pages for every new class.BatteryModelalso gets the reference page M08 omitted (sphinx-build -Wwas failing on it).
Changed¶
parse_quantitygainedstrict=, andbuild_from_configpassesstrict=False, so a construction option written as a plain string in a persisted config (e.g. an enum member’s name) reaches the unit’sConfigValuedomain instead of being rejected as a malformed quantity. This restoresbuild_from_config’s documented contract (“anything else passes through unchanged”).TimeConfig.time_stepstill parses strictly, so"15 min"keeps its loud error.Tank’smax_volume/initial_volumenow have defaults (1000 m³ and 500 m³, half full) instead of being required. Needed so the frozenfo.Tank(property_package=m.properties)builds; a real tank is still always given its own sizing.A
BatteryModelwith unit commitment on and no power rating now derives a 1C limit (its whole capacity in one hour) instead of raising. The frozen script buildsBatteryModel(capacity=1 * pyunits.kWh, costing_package=...)with no rating at all, and the semicontinuousstatuslink needs a finite bound; giving one ofpower_charge_max/power_discharge_maxwithout the other still raises.test_status_requires_both_power_maximais renamed and its both-unset case replaced by one asserting the 1C fallback.BatteryModel’sunit_commitment.statusnow defaults toFalse, overriding the project-wideTruedefault (CONFIG.get("unit_commitment").set_default_value(...), the same patternSISOBlock/Combustoruse forallow_pass_through) instead of just inheriting it — a bareBatteryModel(capacity=...)now builds as a plain LP with no on/off binary. Opt in withunit_commitment=UnitCommitmentConfig(status=True). The 1C power fallback above is decoupled fromstatusso 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 importArcfrompyomo.network(m.waterfacility.tank_to_plant = Arc(...)). The earlierpyo.Arcspelling names an API Pyomo has never had —Arclives inpyomo.networkand is not re-exported intopyomo.environ— so the script could not have run as written. Corrected at the source soexamples/api_freeze.pystays 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_blockdelegates to a new module-levelflexops.core.time_block.find_time_block(model), the one auto-discovery implementation now shared withPlantBlock/NetworkBlock.
Added¶
Solvers are installed in CI. New
solversoptional dependency (pip install -e ".[solvers]") pulls in the HiGHS wheel (highspy), and a new.github/actions/setup-ipoptcomposite action runsidaes get-extensionsfor IPOPT, caching the idaes binary directory keyed on OS + idaes version and exporting it toPATH. On Linux runners the action also apt-installs the LAPACK/BLAS/gfortran runtime libraries the IDAESubuntu2204IPOPT build links against (absent from the ubuntu-24.04 image, whereipoptotherwise exits 127 onliblapack.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, soneeds_ipoptdoes not skip in that case. Both thefast-testsandintegrationCI jobs now use them, soneeds_highs/needs_ipopttests actually run on a PR instead of skipping.BatteryModelgainssoh(state of health, default 0.85/mid-life) and asoh_capacity_limitconstraint (charge[t] <= soh * capacity, independent ofsoc_max), pluseta_charge/eta_dischargeare now fixedVars (not plain config floats) — all three registeredregressable=True(matchingPump.efficiency) so a future FlexParameterize regression can fit them from SCADA data:power_charge/power_dischargein,charge(now registered as the process output) out,capacityknown. Not part of the M08 spec — added at explicit user request; see the class docstring’s “Deviations from the milestone spec.”BatteryModelgainscharge_leakage_rate(self-discharge), a fixedVarin fraction-of-charge-per-day (default0.0005, i.e. 0.05%/day), registeredregressable=Truelikeeta_charge/eta_discharge/soh.charge_balancenow subtractscharge[t-1] * charge_leakage_rate * dteach 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’senergy_pricesentries 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 mutableParamupdated between rolling-horizon solves, or even aVar. An indexed price need not live on the TimeBlock’stime_index, only have exactly one value per time point (read in its own index-set order). The native cost formula generalizes fromprice × Σ_t quantity[t] × dttoΣ_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 inreport_cost’s independent post-solve recomputation alike. A price with the wrong number of values raisesFlexConfigErroratFlexCostingconstruction — the earliest point the horizon length is known — naming both counts; aMappingprice 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 —kWhfor 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’sPriceSpec.valuewidens tofloat | 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 aTimeConfig.time_stepstring parser, which does not exist yet) and remains the runtime one.schema_versionstays0.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.
FlexCostinggains anenergy_pricesconfig 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 asprice × Σ_t quantity[t] × dtand 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/tariffrelax 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 newmerge_tariffs, which raises rather than silently doubling a charge two sources both define. Several files always collapse to onerate_dataframe whoseutilitycolumn selects rows per leg; the covered utilities are recorded so an unpriced carrier raisesFlexConfigErrornaming the carrier instead of contributing a silent$0. Theeecoimport is now soft:import flexopsand a fully flat-priced build/solve/report_costwork with EECO absent, and any tariff path raisesFlexConfigErrornaming both remedies (installeeco, or price the carrier flat). Newcurrency_units(symbol="USD")supplies the Pyomo currency for writing flat prices and is the base currency when no tariff sets one (newcurrencyconfig entry).CostingConfigmirrors all of it (tariff_sourcewidened tostr | list | dict | None, newenergy_pricesofPriceSpec(value+unitsstring),currency, plus a validator requiring a tariff or at least one price); exported JSON Schema regenerated.Annualization takes a cost of capital. New
interest_rateconfig entry (defaultNone) onFlexCosting/CostingConfig. The capital recovery factor is now built on a singleeffective_rateParam:discount_ratealone wheninterest_rateis unset — so existing configs annualize exactly as before — and the real rate(1 + interest_rate) / (1 + discount_rate) - 1when both are given. An effective rate of0still falls back to straight-line1/lifetime_years; an effective rate<= -1or a non-positivelifetime_yearsnow raisesFlexConfigError(the> 0boundlifetime_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.00per-kW monthly demand charges. With the newprorate_monthly_charges(defaultTrue, onFlexCostingandCostingConfig) both are scaled by the newmonthly_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.00monthly bill is unchanged).prorate=Falseonadd_electricity_cost/add_fuel_cost/add_operating_cost/evaluate_cost/evaluate_fuel_costrestores 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 theget_charge_dictpath exposes no equivalent option (EECO’scalculate_costadds the customer charge whole, and itsdemand_scale_factoris suppressed for charges spanning<= 1day — 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).OperatingCostHandlesgainscustomer_chargeandscale_factor.FlexCosting’s flat-price, fuel-price, and scalar-cost line items share oneprice × Σ_t series[t] × dtbuilder, which integrates over the series’ own index set and raisesFlexConfigErrorif that is not the model’stime_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-modelassert_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_poweris now dimensionless (the kW-converted aggregate divided by its units), and the fuel legs gain the matchingopex.fuel_<name>.eeco_aggregate_fuel_usageinstead of passing the m³/hraggregate_fuel_usageReference straight through.aggregate_power/aggregate_fuel_usagekeep their units, so nothing user-facing moves. Thepower/electrical_power/fuel_powerarguments ofadd_electricity_cost/add_fuel_cost/add_operating_costare documented accordingly: pass a bare kW / m³/hr magnitude.
Added¶
FlexCostingextensibility groundwork (additive; no cost values change).opex.total_operating_costnow 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-totalVarand appending one name.FlexCosting.register_scalar_costgains an optional keyword-onlyunit=that records the owning unit block on the returnedScalarCostSpec(defaultNone), so per-unit maintenance/chemical/labor attribution can be surfaced later without a signature change.FlexCostinghardening — Var+Constraint model, arbitrary energy carriers, non-energy scalar costs, annualization. Every quantityFlexCostingexposes is now a decision-visibleVardefined by aneq_<name>equalityConstraint(not a bareExpression): aggregate power, each cost line item, the annualized cost, and the totals.cost_process()now aggregates all registered power draws into an indexedaggregate_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 withpyunits.convertat aggregation, so a non-power draw fails loudly. The electrical series is normalized to EECO’s expected units via an explicitopex.eeco_*Var + constraint before it is handed to EECO.declare_power/register_powertake an optionaltemperature(required forTHERMAL), carried onPowerRecord. 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 asopex.scalar_costintotal_operating_cost. Annualization:CostingConfig.lifetime_years+discount_rateform acapital_recovery_factorand anannualized_costVar ($/year, opex scaled horizon→year + capex×CRF).report_costgains anoperating.scalarfield and sums each fuel’s post-hoc EECO bill. A unit-consistency check reconciles every operating-cost line item onto the tariff currency or raisesFlexConfigError. NewScalarCostSpecexported fromflexops.costing. Exported JSON Schema regenerated. Deviation from the M07 spec: the spec builds the aggregates/line items asExpressions; per user direction these are nowVar+ definingConstraint(unit tests stay solver-free by propagating through the constraints viacalculate_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 aPowerKind) and newOpsBlockData.register_fuel_usage(var, fuel_name), which records aFuelUsageRecordon the newIORegistry.fuellist; for aSimpleGasFlowstream (whoseflow_vol_phaseis already m³/hr) that var is aReferenceto the stream’s flow.FlexCosting.cost_process()pulls every registered flow from the model and buildsaggregate_fuel_usage[t, fuel]directly in EECO’s m³/hr (pyunits.convertrejects a non-volumetric flow loudly), then bills each fuel viaadd_fuel_coston its ownopex.fuel_<name>sub-block. Fuels are discovered from the model rather than declared:FlexCosting.register_fuel,fuel_spec, and theFuelSpecdataclass are removed, along withPowerKind.FUEL,POWER_FUEL,PowerRecord.fuel_name, thefuel_namekwarg ondeclare_power/register_power, and the per-fuelopex.eeco_gas_usage_<name>normalization Var (the aggregate is already in EECO’s units).report_costreads the realized fuel bill offaggregate_fuel_usage; a model that burns no fuel builds no gas leg andopex.fuel_costis0. Withdrawn as out of spec: the earlier same-session design in which a fuel was aPowerKind.FUELkW draw converted to a usage rate by a user-suppliedheating_valueand an optionalfuel_units=thermbasis. It contradicted M07 §”a kW heat duty is NOT the fuel-cost input” and architecture §4 (which lists onlypower_electrical/power_thermal), andfuel_units=thermsilently 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 barechargecolumn. Energy-basis conversion is EECO’s job, not flex-pse’s.flexops.costing.opexnow passeselectric_consumption_units/gas_consumption_units(kW / m³/hr) explicitly into everyeeco.costs.calculate_itemized_costcall 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. Thefuel_usageblock-attribute nameadd_operating_costreads is now theflexcore.nomenclature.FUEL_USAGEconstant 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, andmarimo/matplotlibare added to thedevextra.First end-to-end economic result: EECO-backed
FlexCosting; pump+tank LP shifts load off-peak.flexops.costing.FlexCosting(exported asfo.FlexCosting) subclasses IDAESFlowsheetCostingBlockDataand delegates all tariff operating cost to EECO (decision R4).cost_process()aggregates every unit’spower_electricalinto 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: anopexblock holding all operating cost —electricity_costandfuel_cost(both built onto it via the M06opex.pybridge) plus a user-definedfixed_operating_cost— re-exposed asaggregate_operating_cost; and an emptycapexplaceholder (total_capital_cost == 0, re-exposed asaggregate_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 categorizedCostReport(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 (adrplaceholder + no-op_build_drhook).FlexCosting.base_currencyand every operating-/capital-cost expression carry the tariff sheet’s currency basis (read from the chargeunitscolumn by the newflexops.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. Newdocs/how_to/build_a_plant.mdskeleton andFlexCostingcosting-reference section.New
fixed_operating_costfield onflexcore.config.CostingConfig(default0.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.OpsBlockgains an optionalcosting_package=config: when set,register_powerforwards the unit’s power draw to thatFlexCostingblock (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 inpyproject.toml) as flex-pse’s tariff/operating-cost engine, with the whole integration collected inflexops/costing/opex.py— the soleeecoimport point in the codebase (decision R12; agrepconvention, not an import-linter contract). Public API exported fromflexops.costing:load_tariff/load_dr_program(resolve atariff_source/events_sourceto an EECO object; wrap load errors asFlexDataError),tariff_csv_to_dict(EECOrate_dataCSV or pre-loaded DataFrame → the dictload_tariffaccepts, with optionalwrite_to=JSON persistence), the pandas signal helpersprice_series/is_peak/peak_windows/price_gradient(flex-pse helpers over EECO’sget_charge_dictcharge arrays, for logic/heuristic constraints), the in-objective Pyomo bridgesadd_operating_cost/add_fuel_costreturningOperatingCostHandles(EECO builds the convex-relaxed costExpressions viacosts.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 evaluatorsevaluate_cost/evaluate_fuel_cost(the TRUE de-relaxed bill on a fixed realized numpy array — the user-facing number, R4/R9;evaluate_costreproduces a hand-computed PG&E-B-20-flavored monthly bill to the cent, $14,085.00), and theDRConfigdemand-response container. DR is containers-only in v0 (architecture §2.4):DRConfigloads a DR file and the internal_build_drhook 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 withFlexDataError. New costing reference page (docs/reference/flexops/costing.rst) and numpy intersphinx mapping (M06).flexops.costing.add_operating_costis now the facility-level umbrella that builds the whole in-objective operating cost — electricity and gas — onto one opex block, returning a singleOperatingCostHandleswhosetotal_operating_costis the sum across utilities (EECO namespaces its Pyomo components by utility, soelectric_*/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, withelectrical_power=/fuel_power=overrides; a utility whose series is neither passed nor present is omitted, and it raisesFlexConfigErrorif neither resolves. The former electric-onlyadd_operating_costis renamedadd_electricity_cost(still exported) and, withadd_fuel_cost, remains the single-utility builder. Deviation from the M06 spec: the spec namesadd_operating_costas the electric-only bridge; this session renames that toadd_electricity_costand repurposesadd_operating_costas 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 namefuel_usageis theflexcore.nomenclature.FUEL_USAGEconstant — a volumetric gas-usage series in m³/hr, not apower_thermalkW duty.add_gas_cost/evaluate_gas_costrenamed toadd_fuel_cost/evaluate_fuel_cost. Both now take afuel_typekeyword (default"gas", the only utility EECO 0.2.1 exposes) so a future EECO hydrogen utility is a newfuel_typevalue rather than a new function.add_operating_cost’sgas_powerparam and thegas_usageblock-attribute convention are renamedfuel_power/fuel_usageto match.Pumpgains apower_relationconfig option ("constant_intensity", the default, or"hydraulic"): the hydraulic relation adds adelta_pressure[t]Vartied to the inlet/outlet pressure states by thepressure_changeequality constraint (delta_pressure[t] == outlet_state.pressure[t] - inlet_state.pressure[t]), requiring aproperty_packagebuilt withhas_pressure=True, and excludespressurefrom the inherited inlet-to-outlet bypass (a pump raises pressure rather than passing it through); bothinlet_state.pressure/outlet_state.pressureare registered as IO inputs (fixed boundary conditions, like dispatch flow). Adds a mutableefficiencyVar (dimensionless, bounded[0, 1], default 0.7, fixed at build), and buildspower_electrical[t] = delta_pressure[t] * inlet flow / efficiencyin place of the constant-energy-intensity law. Patch to M04’sPump, deferred at the time for simplicity.
Changed¶
The tariff JSON records key is now
tariff_data(wasrate_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.pynow sources its rate_data column names, charge-column names, and theelectric/gas/energysentinels fromeeco.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. Aunittest guards that the tuples equal EECO’s constants (M06).Install pipeline is now conda-only:
uvis removed andenvironment.ymlinstalls the editable package and its Python dependencies (including the pip-onlyeeco) through apip:subsection, soconda env create -f environment.ymlis the single install command. README,PLAN.md, and the M00 milestone spec updated accordingly.Renamed the intra-unit property-copying API to
pass_through, reservingbypassfor the flow-diversion stream.OpsBlockData.add_bypass_constraints→add_pass_through_constraints, the config slotallow_bypass→allow_pass_through, and the generated equality componentsbypass_{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 thebypassname). Behavior-preserving: no constraint math changed. Deviation from the M04 spec, which named the methodadd_bypass_constraints/configallow_bypass; the M04/M03 milestone wording is updated to match, and a newdocs/explanation/pass_through_and_bypass.mdpage 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 integertime_indexset,timeParam of elapsedi*dtin the user’s units, unit-carryingdt, datetime↔index utilities, rolling-horizon initial-state registry and window metadata); a configurablemax_length(dateutilrelativedelta, default one calendar month) bounding the horizon; minimal Sphinx docs skeleton (M02).CI
standard-installjob (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 theget_solver/SolverFacadefacade 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 toenvironment.yml), and IPOPT for NLP — built from idaes (HSLma27linear solver) when idaes is importable, falling back to stockSolverFactoryIPOPT (MUMPS) otherwise. When no MINLP-capable solver is installed, MINLP still raises pointing atflexschedule.SolveSequence. SCIP’s dynamic-library path is isolated at invocation so it does not clash with idaes’s bundledlibipopt. The rootconftest.pynow forbids solver invocation and network access under-m unitand skipsneeds_*-marked tests via the registry; adds aflexcorereference page and a relaxation-policies explanation page (M05).Added the
OpsBlockbase of every flex-pse unit model (flexops.core.ops_block, inheriting IDAESUnitModelBlockDatawith no ControlVolumes, decision R1): the registration API (register_io_variable/register_process_parameter/register_power), base-providedpower_electrical/power_thermalkW Vars viadeclare_power, the external-dispatch (DERMS) hookset_external_dispatch, the validated-only config slots (unit_commitment,relaxation,allow_pass_through,external_dispatch; their constraints land in M08), and an M09-deferredbuild_from_configstub.register_power/declare_powerrequire aflexcore.nomenclature.PowerKindmember forkind(plain strings are rejected), and call sites import the nomenclature module asnmso constants likenm.POWER_ELECTRICALread unambiguously as string names. Added the in-place update hookupdate_parameters(values)(set_valueon 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-rewirereplace_unithelper was dropped in favor of it (conventions §9). Registration records and model-wide discovery live inflexops.core.registration(IORegistry,iter_io_registry). Added theadd_stream_portshelper: it builds a single scalar inlet/outlet state block per stream from the configuredproperty_package(state variables indexed over time), registers each side’s volumetric flow (flow_vol_phase) as an input/output IO variable via a time-indexedReference, and exposes theinlet/outletports through the inherited IDAESadd_inlet_port/add_outlet_port(M03).New
model_and_block_structureexplanation page: defines the ConcreteModel/TimeBlock/OpsBlock/property-package block hierarchy and the variable-indexing convention (operational Vars indexed overtime_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 aflow_vol_phaseindexed by time then phase (singleLiq), and a time-indexeddens_massstate variable (fixed at the configureddensityby default, free withfixed_density=False), plus opt-inpressure/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 atime_indexstate-block config option, yielding one scalar state block per stream; exported fromflexops(M03).Added
SimpleGasFlow: the gas-phase counterpart ofSimpleAqueousFlowwhose state block always carries aflow_vol_phase(indexed by time then the singleVapphase), plus time-indexeddens_mass,pressure, andtemperature(gas density varies with pressure/temperature; no equation of state is imposed). Exported fromflexops, alongside a new top-levelPowerKindre-export so the standardized power-kind names (PowerKind.ELECTRICAL/PowerKind.THERMAL) are importable directly fromflexops(M03).Added the full versioned config schema (
flexcore.config.schema, pydantic v2, decision R3):IOVariableSpec,SurrogateSpec,ExternalDispatchSpec,UnitCommitmentConfig,UnitConfig,PlantConfig,NetworkConfig,TimeConfig,CostingConfig(with aDRConfigcontainer slot), and the top-levelModelConfig(mandatory semantic-versionschema_version, exactly-one-ofnetwork/plant). Addedflexcore.config.io(load_model_config/dump_model_configwith JSON as the only on-disk format plus direct dict input, aMIGRATIONStable, andexport_json_schemaswith an optionalfilenamefor side-by-side schema versions) and the checked-in JSON Schema atsrc/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). Addedflexcore.nomenclature(thePOWER_ELECTRICAL/POWER_THERMALconstants andPowerKind). New docs: config-schema and energy-nomenclature explanation pages,flexcoreconfig/nomenclature/exceptions reference sections, and aflexops.propertiesreference 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_dofon theunittier;test_solve,test_solutionon thecomponenttier, skipping cleanly ifflexcore.solvers.get_solveris unavailable). Addedflexops.testing.dummy_time_block(n=3), a throwawayTimeBlock+SimpleAqueousFlowmodel reused by the M14 docs generator. AddedOpsBlockData.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_massunderfixed_densityis skipped automatically), gated byself.config.allow_pass_through; it resolves each port’s sibling"{port}_state"block rather than the port’s ownvarsmapping, since the latter are auto-generatedReferences carrying a leaky extraUnindexedComponent_setdimension. AddedSISOBlock(flexops.unit_models.base), the first IO-topology base class (architecture §3.4/R6): builds the inlet/outlet ports via the inheritedadd_stream_ports, then its per-stream pass-through viaadd_pass_through_constraintswith no exclusions (flow’s pass-through is itself a pass-through equality, namedpass_through_flow_vol_phase_eq);SISOBlockoverrides the inheritedallow_pass_throughdefault toTrueso the topology is well-posed out of the box. AddedSimpleAqueousFlow.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) andTank(SISOBlock)(holdup difference equationvolume[t+1] = volume[t] + dt*(in - out)overt = 0..N-2, converting the whole flow-difference expression rather than assuming the flow basis’s units).Tanknow distinguishesmax_volume(the maximum possible tank volume – fixed by prior investment or space constraints, a static upper bound) fromcapacity(the chosen volume, a fixable designVarnow bounded(min_volume, max_volume)so a design-mode solve can never exceed the maximum possible size). Added a boundedlevel[t]Var (level_min/level_maxconfig, default(0.0, 1.0)) defined bylevel_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 (capacityfixed) but bilinear (NLP) in design mode (capacityfree), so design-mode solves of a model containing a tank need IPOPT or aflexschedule.SolveSequence, not HiGHS.Tankforcesunit_commitment.status = Falseregardless 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.testingandflexops.unit_models(with theunit_model.rstautosummary template, aflexops-unit-tablesTODO placeholder for M14) reference pages (M04).
Fixed¶
import flexops.testingno longer fails on a standard install.flexops.testingimportspytestat module level (UnitModelTestHarnessusespytest.mark/pytest.skip/pytest.approx), butpytestwas listed only in thedevextra, sopip install flex-psefollowed byimport flexops.testingraisedModuleNotFoundError: No module named 'pytest'. Newtestingoptional dependency: users subclassing the harness in their own test suites installpip install "flex-pse[testing]"(contributors already get it fromdev). Installing without it still works —flexops.testingis the only module that needs it. The CIstandard-installjob’s bare-install smoke-import list dropsflexops.testingaccordingly and gains a second step that installsflex-pse[testing]and imports it, so both paths are covered.OpsBlocknow coerces an explicitunit_commitment=Noneto an all-defaultsUnitCommitmentConfiginbuild()(Pyomo skipsConfigValuedomains forNone, so the domain-level coercion never ran).