flexcore¶
flex-pse’s tools share this substrate. It holds the exception hierarchy, the solver facade, and (later) the versioned config schema.
Solvers¶
The solver layer classifies a model, detects which solvers are installed, and selects one. It errors loudly rather than transforming the model (see Relaxation policies).
- flexcore.solvers.get_solver(model: ConcreteModel | None = None, problem_class: ProblemClass | None = None, prefer: str | None = None, settings: SolverSettings = SolverSettings.DEFAULT, strategy: SolveStrategy | None = None) SolverFacade¶
Select the best available solver for a problem class.
Exactly one of
modelorproblem_classmay be given. Ifmodelis given it is classified viaclassify(); if neither is given the class defaults toProblemClass.LP(smallest choice, implementer’s). Candidate order isprefer(if named and capable) then the fixed priority list["gurobi", "scip", "highs", "cbc", "ipopt"]. Ifpreferis named but unavailable or incapable, a warning is logged and selection falls through to the priority list. SCIP is tried before HiGHS, so MILP routes to SCIP when installed (benchmark-preferred); pure LP still routes to HiGHS since SCIP is not LP-capable. In particular MINLP routes to SCIP (the default open-source MINLP solver) when it is installed; only when no MINLP-capable solver is available does MINLP raise.- Parameters:
model – A Pyomo model to classify; mutually exclusive with
problem_class.problem_class – The
ProblemClassto solve; mutually exclusive withmodel.prefer – A solver name to try first.
settings – The tuning settings applied to every solver call.
strategy – How to solve, e.g.
RelaxAndFix; defaults toDirect.
- Returns:
A
SolverFacadebound to the chosen solver.- Raises:
ValueError – If both
modelandproblem_classare given.FlexSolverError – If no available solver supports the problem class. For
MINLPthe message points atflexschedule.SolveSequence; the facade never relaxes integrality itself.
Example
>>> from flexcore.solvers import get_solver, ProblemClass >>> solver = get_solver(problem_class=ProblemClass.LP) >>> results = solver.solve(model)
- class flexcore.solvers.SolverFacade(name: str, problem_class: ProblemClass, settings: SolverSettings = SolverSettings.DEFAULT, strategy: SolveStrategy = <factory>)¶
A selected solver plus how to tune it and how to solve with it.
- problem_class¶
The class this solver was selected for.
- settings¶
The tuning settings applied to every solver call.
- strategy¶
How one
solvecall is turned into solver calls.
- last_report¶
The
SolveReportof the most recentsolve.- Type:
- solve(model: ConcreteModel, *, tee: bool = False, warmstart: bool = False, mip_gap: float | None = None, time_limit: float | None = None, options: dict[str, Any] | None = None)¶
Solve
modelwith the facade’s strategy, solver and settings.The solution is loaded into the model only when the solver found one; an infeasible model returns its results without raising. The step-by-step record is kept on
last_report.- Parameters:
model – The Pyomo model to solve.
tee – Stream the solver’s log to stdout.
warmstart – Start from the model’s current values. A solver that cannot warm start logs a warning and solves cold.
mip_gap – Relative MIP gap at which to stop, applied to every step.
time_limit – Time limit in seconds for the whole solve, across all steps.
options – Native solver options; each must not also be set elsewhere. A step run on a different solver than the facade’s drops them.
- Returns:
The Pyomo results object of the step that produced the solution.
- flexcore.solvers.classify(model: ConcreteModel) ProblemClass¶
Classify a Pyomo model into a
ProblemClass.Only active constraints and the active objective are considered; inactive constraints, objectives, and blocks are ignored. A variable counts as discrete only if it is binary or integer and not fixed — so an LP with fixed binaries classifies
LP. Note that a quadratic constraint classifiesNLP, notQP: only a quadratic objective over all-linear constraints isQP(smallest choice consistent with the QP capability matrix).The result is cached on the model and reused while the sets of active constraints, active objectives, fixed variables, and unfixed discrete variables are unchanged. Replacing a constraint’s expression in place is not detected.
- Parameters:
model – A constructed Pyomo model to classify.
- Returns:
The problem class. Never returns
MINLP_OA/MINLP_TR(reserved).
Example
>>> import pyomo.environ as pyo >>> from flexcore.solvers import classify, ProblemClass >>> m = pyo.ConcreteModel() >>> m.x = pyo.Var() >>> m.c = pyo.Constraint(expr=m.x <= 1) >>> m.obj = pyo.Objective(expr=m.x) >>> classify(m) is ProblemClass.LP True
- class flexcore.solvers.ProblemClass(*values)¶
Mathematical program classes that the solver facade reasons about.
LP/QP/MILP/NLP/MINLPare the classesclassify()can return.MINLP_OA(outer approximation) andMINLP_TR(trust region) are reserved strategy slots — deliberately unimplemented in v0 and never returned byclassify().
- flexcore.solvers.available_solvers() dict[str, set[ProblemClass]]¶
Return the capability matrix restricted to installed solvers.
- Returns:
A dict mapping each installed solver name to its capability set — the subset of
CAPABILITIESwhose solver probes as available.
Capability matrix¶
available_solvers() returns the subset of this matrix whose solver is
installed. The matrix is a plain module constant (flexcore.solvers.registry.CAPABILITIES)
and is extensible. You can register an additional solver entry before
calling get_solver().
Solver |
Supported problem classes |
|---|---|
|
LP, MILP |
|
LP, MILP |
|
NLP (built from idaes with HSL |
|
MILP, MINLP (preferred over HiGHS for MILP, the default open source MINLP solver) |
|
LP, QP, MILP |
Solve strategies¶
A facade’s strategy decides how one solve call becomes solver calls. The
default, Direct, solves once. RelaxAndFix is an opt-in MIP
heuristic (see Solve strategies). Every solve
leaves a SolveReport on SolverFacade.last_report.
from flexcore.solvers import RelaxAndFix, SolverSettings, get_solver
solver = get_solver(
model=m,
settings=SolverSettings.UNIT_COMMITMENT,
strategy=RelaxAndFix(fix_tol=0.1),
)
results = solver.solve(m, mip_gap=0.002, time_limit=1800)
solver.last_report.gap # distance from the relaxation's bound
- class flexcore.solvers.Direct¶
Solve the model once, exactly as built.
- solve(model: ConcreteModel, problem_class: ProblemClass, run_step: Callable[[ProblemClass, str, bool], tuple[Any, StepResult]], warmstart: bool) tuple[Any, SolveReport]¶
Solve
modelin one step; seeSolveStrategy.solve().
- class flexcore.solvers.RelaxAndFix(fix_tol: float = 0.1)¶
Solve the binary relaxation, fix what it decided, then solve the rest exactly.
A heuristic: the returned schedule is integer-feasible but not proven optimal.
SolveReport.gapmeasures it against the relaxation’s bound.- fix_tol¶
A relaxed binary below
fix_tolis fixed to 0 and one above1 - fix_tolto 1. Must be in[0, 0.5);0fixes nothing.- Type:
- Raises:
ValueError – If
fix_tolis outside[0, 0.5).
- solve(model: ConcreteModel, problem_class: ProblemClass, run_step: Callable[[ProblemClass, str, bool], tuple[Any, StepResult]], warmstart: bool) tuple[Any, SolveReport]¶
Relax, fix and re-solve
model; seeSolveStrategy.solve().The model is left with its original domains and nothing newly fixed, with the final solution loaded.
- class flexcore.solvers.SolveStrategy(*args, **kwargs)¶
The interface every solve strategy implements.
- solve(model: ConcreteModel, problem_class: ProblemClass, run_step: Callable[[ProblemClass, str, bool], tuple[Any, StepResult]], warmstart: bool) tuple[Any, SolveReport]¶
Solve
modelusingrun_stepfor every solver call.- Parameters:
model – The Pyomo model to solve.
problem_class – The model’s class as classified by the facade.
run_step – Solves the model once as
(problem_class, label, warmstart).warmstart – Whether the caller asked to warm start from current values.
- Returns:
The Pyomo results of the step that produced the solution, and the report.
- class flexcore.solvers.SolveReport(strategy: str, steps: list[StepResult], bound: float | None = None)¶
Every step a strategy ran for one
solvecall, plus its bound.- steps¶
The steps in the order they ran; the last produced the solution.
- class flexcore.solvers.StepResult(label: str, solver: str, termination: TerminationCondition, objective: float | None, wall_time: float, solver_time: float | None, n_fixed: int = 0)¶
The outcome of one solver call made by a strategy.
- termination¶
The solver’s termination condition.
- Type:
pyomo.opt.results.solver.TerminationCondition
Options and settings¶
solve takes the solver-neutral keywords mip_gap and time_limit
and translates them to each solver’s own option name
(flexcore.solvers.options.OPTION_NAMES). A SolverSettings adds
tuning options per solver (flexcore.solvers.options.SETTINGS_OPTIONS).
Native options add anything else. No setting may come from two of these
sources: mip_gap=0.01 with options={"MIPGap": 0.05}, or the
UNIT_COMMITMENT settings with options={"MIPFocus": 1}, raises
ValueError. Use SolverSettings.DEFAULT to tune those options
yourself. A neutral option that a solver has no name for is dropped with a
warning.
- class flexcore.solvers.SolverOption(*values)¶
Solver-neutral options accepted as keywords by
SolverFacade.solve.
- class flexcore.solvers.SolverSettings(*values)¶
Named sets of solver tuning options for a kind of model.
Solver |
Options |
|---|---|
|
|
others |
none; their defaults already suit unit commitment |
Warm starting¶
solve(m, warmstart=True) starts the search from the model’s current
values. It helps a re-solve after a small change, such as a parameter
retarget, not a first solve. A solver that can’t warm start logs a warning
and solves cold instead of raising (flexcore.solvers.registry.WARMSTART_SOLVERS).
Solver |
|
|---|---|
|
passed through |
|
solved through the |
|
passed through |
|
warning, solved cold |
An infeasible model returns its results with an infeasible termination
condition on every solver; no solution is loaded.
Config schema¶
The versioned, canonical JSON spec that the whole model and run get built from
(see The config schema): a flowsheet as one flat list of
elements, in any order. Pydantic is the schema authority, and
SCHEMA_VERSION tags what this build writes.
A flowsheet as a flat list of elements, in any order. |
|
The discrete-time horizon; builds the model's time_block. |
|
A property package, built at the model root under its name. |
|
The costing package: tariff, prices, demand response and finance terms. |
|
A network of plants. |
|
A plant of units. |
|
A set of members that units and connections can be indexed over. |
|
A unit model and the connections that leave it. |
|
An arc from a port of the unit that owns it to another unit's port. |
|
A surrogate placed on one relation of a unit after the unit is built. |
|
A limit on how fast a variable may change. |
|
An on/off status binary gating a unit's output between two limits. |
|
Startup and shutdown binaries with minimum up and down times. |
|
Hold a continuous variable constant within blocks of k steps. |
|
Let part of a flow bypass the unit's energy relation. |
|
Allow a unit on only once an upstream unit has been on for k steps. |
|
When a unit is on, another unit is on (or off). |
|
Interchangeable units ordered so the first listed runs first. |
|
A priced degradation (wear) penalty on a unit's variables. |
|
Values an external controller sets for one variable of a unit. |
|
Fix one or more model variables, named by their path from the model root. |
|
Unfix one or more model variables (e.g. a parameter a unit fixes by default). |
|
A user function that adds constraints or an objective to the model. |
|
The objective the model optimizes. |
|
A number with units, e.g. {"value": 0.5, "units": "kWh/m^3"}. |
|
Data kept in a JSON or gzipped JSON file beside the spec. |
|
A native price whose values may sit in a file beside the spec. |
- flexcore.config.spec.SCHEMA_VERSION = '0.2.0'¶
the schema version this build writes and validates against.
- Type:
- flexcore.config.spec.PACKAGE_REF = '$package'¶
Key of a construction option
{"$package": name}naming a package element.
- flexcore.config.spec.KINDS: dict[str, tuple[str, bool]]¶
Element kind -> (build stage, whether it can change on a live model).
- flexcore.config.spec.LOGIC_KINDS = ('ramp', 'status', 'startup_shutdown', 'dwell', 'bypass', 'startup_delay', 'conditional', 'parallel_group', 'degradation')¶
Kinds that add operating logic to units they name.
Config I/O¶
- flexcore.config.io.load_spec(source) FlowsheetSpec¶
Load and validate a flat spec.
- Parameters:
source – A
.jsonpath, a parsed mapping (not mutated), or aFlowsheetSpec(returned as is).- Returns:
The validated spec, with its base directory set for relative paths.
- Raises:
FlexConfigError – If the document is unreadable, has a missing, malformed or too-new
schema_version, lacks a migration, or fails validation (the message names the bad field path).
- flexcore.config.io.dump_spec(spec: FlowsheetSpec, path) None¶
Write a flat spec to disk as indented JSON, elements in canonical order.
Elements are sorted by build stage, kind and name so files diff cleanly; defaults are left out.
- Parameters:
spec – The spec to serialize; it is not reordered.
path – Destination path ending in
.json.
- Raises:
FlexConfigError – For any other suffix.
- flexcore.config.io.read_source(source: str, base_dir)¶
Read the JSON data a
$sourcereference names.- Parameters:
source – Path of a
.jsonor.json.gzfile.base_dir – Directory a relative path resolves against, or None.
- Returns:
The parsed JSON data.
- Raises:
FlexConfigError – If the file has another suffix or cannot be read.
- flexcore.config.io.resolve_sources(value, base_dir)¶
Replace every
$sourcereference invaluewith the data it names.- Parameters:
value – A
SourceRef, a{"$source": path}mapping, or any JSON data containing them.base_dir – Directory a relative path resolves against, or None.
- Returns:
valuewith each reference replaced; the input is not mutated.- Raises:
FlexConfigError – If a referenced file cannot be read.
- flexcore.config.io.MIGRATIONS: dict[str, Callable[[dict], dict]] = {'0.1.0': <function _migrate_0_1_0>, '0.1.1': <function _migrate_0_1_1>}¶
Source version -> upgrade hook, applied in sequence on load. Each hook must set the new
schema_versionon the dict it returns.
- flexcore.config.io.export_json_schemas(directory, filename: str = 'flowsheet_spec.schema.json') None¶
Write the exported JSON Schema for the flat spec to
directory.Serializes
FlowsheetSpec’s JSON Schema withindent=2andsort_keys=Trueso the checked-in schema diffs only on real schema changes. Descriptions are collapsed to single-line plain text. Run once and commit the result tosrc/flexcore/config/schemas/.- Parameters:
directory – Destination directory for the schema file.
filename – Output filename; override it to keep schemas for several versions side by side in one directory.
Surrogate migration¶
- flexcore.config.surrogate_migration.migrate_surrogate_spec(spec: dict) dict¶
Return a pre-0.2.0 surrogate spec or element in the 0.2.0 form.
datais split intoconfigandparametersandconfig_versionis set to 1; every other key (surrogate_type,provenance, and an element’skind,unit,relationandname) is kept. A spec already in the 0.2.0 form is returned as an unchanged copy, so the function is safe to call on either. Types without a pre-0.2.0 implementation keep theirdataasconfig.- Parameters:
spec – A surrogate spec (e.g. saved from
to_surrogate_spec()) or a flowsheet surrogate element, as a parsed dict. Not modified.- Returns:
The migrated copy.
- Raises:
FlexConfigError – If the old data cannot be translated faithfully, such as an ARIMA
exog_coefslist with several inputs, which cannot be paired with its inputs reliably.
Nomenclature¶
The canonical names for energy variables (see Energy nomenclature).
- flexcore.nomenclature.POWER_ELECTRICAL = 'power_electrical'¶
name of a unit’s electrical draw Var (kW).
- Type:
- flexcore.nomenclature.POWER_THERMAL = 'power_thermal'¶
name of a unit’s thermal duty Var (kW), registered at a temperature.
- Type:
- flexcore.nomenclature.FUEL_USAGE = 'fuel_usage'¶
name of a fuel-usage Var — a volumetric flow in m³/hr, not a power. A unit burning one named fuel uses
f"{FUEL_USAGE}_{fuel_name}"(e.g.fuel_usage_natural_gas); a facility-level series is the bare name.- Type:
- class flexcore.nomenclature.PowerKind(*values)¶
The kinds of power draw a unit can declare.
Each member’s value is the
kindstring accepted byregister_poweranddeclare_powerand stored on anflexops.core.registration.PowerRecord. Fuel is absent by design — it is a volumetric flow (FUEL_USAGE), not a power.
Exceptions¶
- exception flexcore.exceptions.FlexError¶
Base class for all flex-pse errors.
Catch this to handle any flex-pse-specific failure regardless of category. Prefer raising one of the concrete subclasses below over this base class directly, so callers can distinguish failure categories.
- exception flexcore.exceptions.FlexConfigError(message: str, *, field: str | None = None, value: object = None)¶
Raised when persisted or runtime configuration is invalid.
Raise this for malformed or missing configuration: a pydantic config file that fails validation, a Pyomo
ConfigDictentry given an invalid value, or a config referencing a field/unit/tag that does not exist. The message must name the exact field that was wrong and what value would fix it.- field¶
Dotted name of the config field, unit, or tag that was invalid, if known.
- value¶
The invalid value that was supplied, if known.
- exception flexcore.exceptions.FlexSolverError(message: str, *, solver: str | None = None, problem_class: str | None = None)¶
Raised when a solver cannot be found, is unsupported, or fails to run.
Raise this when the solver facade cannot satisfy a request: the named solver is not installed, no available solver supports the model’s classification (e.g. NLP vs. MILP), or the solver process itself errors out before returning a status. The message must tell the user which solver was requested and how to install or substitute one.
- solver¶
Name of the solver that was requested or attempted, if known.
- problem_class¶
Name of the problem classification (e.g.
"MINLP") the solver needed to support, if known.
- exception flexcore.exceptions.FlexDataError(message: str, *, field: str | None = None)¶
Raised when input plant/historian data is missing or insufficient.
Raise this for problems with data supplied to FlexParameterize or FlexOps: missing historian tags, insufficient data to regress a parameter, or data that fails a sufficiency/validity check. The message must name the missing or invalid data and what additional data or action would resolve it.
- field¶
Name of the missing or invalid historian tag or field, if known.
- exception flexcore.exceptions.FlexEmitWarning¶
Warned when a model holds something its emitted spec cannot express yet.
Raise it to an error with
warnings.simplefilter("error", FlexEmitWarning)to require a model to round-trip exactly.
- exception flexcore.exceptions.FlexFixWarning¶
Warned when a fix value outside a variable’s bounds is fixed anyway or skipped.
Raise it to an error with
warnings.simplefilter("error", FlexFixWarning)so a run stops on any fix that differs from what the spec wrote.
Logging¶
The shared logger for flex-pse. It provides a custom level for configuration
simplifications, plus optional deduplication of INFO and WARNING records
emitted from the same call site within a sliding window.
- flexcore.logger.CONFIGURATION_SIMPLIFICATIONS = 21¶
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral. >>> int(‘0b100’, base=0) 4
- class flexcore.logger.FlexPseLogger(name, level=0)¶
Project logger class that adds a
configuration_simplificationsmethod.Note: This module was generated with AI assistance.
Registered via
logging.setLoggerClassso thatlogging.getLoggerreturns an instance of this class when the name matches. The added method emits log records at the customCONFIGURATION_SIMPLIFICATIONSlevel, which is intended for user-facing physical-simplification notices that should appear in normal output but benefit from deduplication.- configuration_simplifications(msg, *args, **kwargs)¶
Log a message at the
CONFIGURATION_SIMPLIFICATIONScustom level.Note: This module was generated with AI assistance.
- Parameters:
msg – The message to log. Supports
%-style formatting withargs.*args – Positional arguments interpolated into
msg.**kwargs – Extra keyword arguments forwarded to the underlying
logging.Loggeremit call.
- class flexcore.logger.DedupHandler(target=None, window=10.0, dedup_enabled=None)¶
Logging handler that suppresses duplicate messages within a sliding window.
Note: this module was module were generated with AI assistance.
Duplicates are keyed on
(message, pathname, lineno, levelno). The handler is thread-safe and allows an optionaltargethandler for forwarding, making it composable with other handlers (e.g. a file handler plus a dedup wrapper).
- flexcore.logger.get_logger(name=None, dedup_enabled=None)¶
Return a project logger with a
DedupHandlerattached.Note: This module was generated with AI assistance.
The logger is configured with the global log level and a single
DedupHandler. If the logger already has aDedupHandler, no new handler is added, allowing callers to re-acquire the same logger safely.Parameters¶
- namestr, optional
Logger name. Defaults to
DEFAULT_LOGGER_NAME("flex-pse").- dedup_enableddict[int, bool], optional
Dedup mapping for the attached
DedupHandler. WhenNone, the current global dedup configuration is used.
Returns¶
- logging.Logger
A logger instance with dedup-aware output.
- flexcore.logger.get_global_level() int¶
Return the current global minimum log level for flex-pse loggers.
Note: This module was generated with AI assistance.
Returns¶
- int
The current global log level (defaults to
CONFIGURATION_SIMPLIFICATIONS). Individual loggers created viaget_logger()inherit this level at creation time.
- flexcore.logger.set_global_level(level: int) None¶
Set the global minimum log level for subsequently created loggers.
Note: This module was generated with AI assistance.
Parameters¶
- levelint
The new global log level. Standard levels (e.g.
logging.DEBUG,logging.INFO) or custom levels (e.g.CONFIGURATION_SIMPLIFICATIONS) are accepted.
- flexcore.logger.get_global_dedup_enabled() dict[int, bool]¶
Return the global dedup configuration, keyed by log level.
Note: This module was generated with AI assistance.
Returns¶
- dict[int, bool]
Mapping of
levelnotoTrue(dedup enabled) orFalse(dedup disabled). Missing levels default toFalse. The default mapping enables dedup forlogging.WARNINGandCONFIGURATION_SIMPLIFICATIONS.
- flexcore.logger.set_global_dedup_enabled(dedup_enabled: dict[int, bool]) None¶
Replace the global dedup configuration for subsequently created handlers.
Note: This module was generated with AI assistance.
Parameters¶
- dedup_enableddict[int, bool]
New mapping of
levelnoto dedup flag. Existing handlers keep their current state; callget_logger()again or mutatehandler.dedup_enableddirectly to update live handlers.
Global configuration¶
Call set_global_level() and set_global_dedup_enabled() once at the
start of a script to control the threshold and deduplication behavior for all
loggers obtained afterward.
import logging
from flexcore.logger import get_logger, set_global_level, set_global_dedup_enabled
set_global_level(logging.WARNING)
set_global_dedup_enabled({
logging.WARNING: True,
logging.INFO: True,
})
# import additional flex-pse modules here, they will use above defaults
_log = get_logger(__name__)
These are the available levels, from lowest to highest.
logging.DEBUG(10)logging.INFO(20)CONFIGURATION_SIMPLIFICATIONS(21)logging.WARNING(30)logging.ERROR(40)logging.CRITICAL(50)
The default threshold is CONFIGURATION_SIMPLIFICATIONS. Deduplication is a
toggle you set per level. By default it is enabled for WARNING and
CONFIGURATION_SIMPLIFICATIONS.