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 model or problem_class may be given. If model is given it is classified via classify(); if neither is given the class defaults to ProblemClass.LP (smallest choice, implementer’s). Candidate order is prefer (if named and capable) then the fixed priority list ["gurobi", "scip", "highs", "cbc", "ipopt"]. If prefer is 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 ProblemClass to solve; mutually exclusive with model.

  • prefer – A solver name to try first.

  • settings – The tuning settings applied to every solver call.

  • strategy – How to solve, e.g. RelaxAndFix; defaults to Direct.

Returns:

A SolverFacade bound to the chosen solver.

Raises:
  • ValueError – If both model and problem_class are given.

  • FlexSolverError – If no available solver supports the problem class. For MINLP the message points at flexschedule.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.

name

The Pyomo solver name (e.g. "highs").

Type:

str

problem_class

The class this solver was selected for.

Type:

flexcore.solvers.classify.ProblemClass

settings

The tuning settings applied to every solver call.

Type:

flexcore.solvers.options.SolverSettings

strategy

How one solve call is turned into solver calls.

Type:

flexcore.solvers.strategies.SolveStrategy

last_report

The SolveReport of the most recent solve.

Type:

flexcore.solvers.strategies.SolveReport | None

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 model with 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 classifies NLP, not QP: only a quadratic objective over all-linear constraints is QP (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/MINLP are the classes classify() can return. MINLP_OA (outer approximation) and MINLP_TR (trust region) are reserved strategy slots — deliberately unimplemented in v0 and never returned by classify().

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 CAPABILITIES whose 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

highs

LP, MILP

cbc

LP, MILP

ipopt

NLP (built from idaes with HSL ma27 when available, else stock IPOPT)

scip

MILP, MINLP (preferred over HiGHS for MILP, the default open source MINLP solver)

gurobi

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 model in one step; see SolveStrategy.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.gap measures it against the relaxation’s bound.

fix_tol

A relaxed binary below fix_tol is fixed to 0 and one above 1 - fix_tol to 1. Must be in [0, 0.5); 0 fixes nothing.

Type:

float

Raises:

ValueError – If fix_tol is 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; see SolveStrategy.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 model using run_step for 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 solve call, plus its bound.

strategy

The strategy’s name.

Type:

str

steps

The steps in the order they ran; the last produced the solution.

Type:

list[flexcore.solvers.strategies.StepResult]

bound

A bound on the optimal objective, if the strategy computed one.

Type:

float | None

property gap: float | None

Relative distance of the final objective from bound, or None.

property objective: float | None

The objective value of the final step.

property wall_time: float

Total seconds across all steps.

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.

label

What the step was, e.g. "direct" or "relaxation".

Type:

str

solver

The Pyomo solver name that ran it.

Type:

str

termination

The solver’s termination condition.

Type:

pyomo.opt.results.solver.TerminationCondition

objective

The active objective’s value, or None if no solution loaded.

Type:

float | None

wall_time

Seconds for the whole call, including model write and read.

Type:

float

solver_time

Seconds the solver reported for itself, if it reports one.

Type:

float | None

n_fixed

Number of variables the strategy fixed for this step.

Type:

int

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.

SolverSettings.UNIT_COMMITMENT

Solver

Options

gurobi

MIPFocus=3 (push the bound), Symmetry=2 (parallel identical units), Cuts=2

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

warmstart=True

gurobi

passed through

highs

solved through the appsi_highs interface, which accepts it

cbc

passed through

scip, ipopt

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.

FlowsheetSpec

A flowsheet as a flat list of elements, in any order.

TimeElement

The discrete-time horizon; builds the model's time_block.

PropertyPackageElement

A property package, built at the model root under its name.

CostingElement

The costing package: tariff, prices, demand response and finance terms.

NetworkElement

A network of plants.

PlantElement

A plant of units.

SetElement

A set of members that units and connections can be indexed over.

UnitElement

A unit model and the connections that leave it.

Connection

An arc from a port of the unit that owns it to another unit's port.

SurrogateElement

A surrogate placed on one relation of a unit after the unit is built.

RampElement

A limit on how fast a variable may change.

StatusElement

An on/off status binary gating a unit's output between two limits.

StartupShutdownElement

Startup and shutdown binaries with minimum up and down times.

DwellElement

Hold a continuous variable constant within blocks of k steps.

BypassElement

Let part of a flow bypass the unit's energy relation.

StartupDelayElement

Allow a unit on only once an upstream unit has been on for k steps.

ConditionalElement

When a unit is on, another unit is on (or off).

ParallelGroupElement

Interchangeable units ordered so the first listed runs first.

DegradationElement

A priced degradation (wear) penalty on a unit's variables.

DispatchElement

Values an external controller sets for one variable of a unit.

FixElement

Fix one or more model variables, named by their path from the model root.

UnfixElement

Unfix one or more model variables (e.g. a parameter a unit fixes by default).

ExtensionElement

A user function that adds constraints or an objective to the model.

ObjectiveElement

The objective the model optimizes.

Quantity

A number with units, e.g. {"value": 0.5, "units": "kWh/m^3"}.

SourceRef

Data kept in a JSON or gzipped JSON file beside the spec.

SourcedPrice

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:

str

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.

Shared building blocks

UnitConfig

A single unit model: its class, construction options, and IO/logic.

PropertyPackageSpec

A property package the model builds, by class name and options.

IOVariableSpec

A declared process input or output variable of a unit.

SurrogateSpec

A fitted (or default) energy/IO relationship for a unit.

SurrogateType

Which predefined surrogate class a SurrogateSpec describes.

ParameterState

One surrogate parameter's value and whether the model holds it fixed.

ExternalDispatchSpec

Declares an external (DERMS) command source for a controllable variable.

UnitCommitmentConfig

Per-unit unit-commitment configuration, a validated container.

DegradationSpec

A named, priced degradation penalty on a unit: a sum of wear-driver terms.

DegradationTermSpec

One priced wear driver of a unit variable, valued in that variable's units.

DegradationTerm

Which wear driver a DegradationTermSpec charges for.

TimeConfig

The discrete-time horizon specification.

CostingConfig

Tariff, price, demand-response, and solve/objective options for a run.

PriceSpec

A native price for one energy carrier or fuel: a number and its units.

DRConfig

Demand-response container slot, a placeholder in v0: DR containers exist so wiring is stable, but no DR constraints are built.

Config I/O

flexcore.config.io.load_spec(source) → FlowsheetSpec

Load and validate a flat spec.

Parameters:

source – A .json path, a parsed mapping (not mutated), or a FlowsheetSpec (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 $source reference names.

Parameters:
  • source – Path of a .json or .json.gz file.

  • 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 $source reference in value with 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:

value with 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_version on 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 with indent=2 and sort_keys=True so the checked-in schema diffs only on real schema changes. Descriptions are collapsed to single-line plain text. Run once and commit the result to src/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.

data is split into config and parameters and config_version is set to 1; every other key (surrogate_type, provenance, and an element’s kind, unit, relation and name) 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 their data as config.

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_coefs list with several inputs, which cannot be paired with its inputs reliably.

flexcore.config.surrogate_migration.is_legacy_surrogate(spec: dict) → bool

Return whether spec uses the pre-0.2.0 data layout.

Parameters:

spec – A surrogate spec or surrogate element, as a parsed dict.

Returns:

True when it carries data instead of config/parameters.

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:

str

flexcore.nomenclature.POWER_THERMAL = 'power_thermal'

name of a unit’s thermal duty Var (kW), registered at a temperature.

Type:

str

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:

str

class flexcore.nomenclature.PowerKind(*values)

The kinds of power draw a unit can declare.

Each member’s value is the kind string accepted by register_power and declare_power and stored on an flexops.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 ConfigDict entry 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_simplifications method.

Note: This module was generated with AI assistance.

Registered via logging.setLoggerClass so that logging.getLogger returns an instance of this class when the name matches. The added method emits log records at the custom CONFIGURATION_SIMPLIFICATIONS level, 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_SIMPLIFICATIONS custom level.

Note: This module was generated with AI assistance.

Parameters:
  • msg – The message to log. Supports %-style formatting with args.

  • *args – Positional arguments interpolated into msg.

  • **kwargs – Extra keyword arguments forwarded to the underlying logging.Logger emit 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 optional target handler for forwarding, making it composable with other handlers (e.g. a file handler plus a dedup wrapper).

emit(record)

Process a log record, emitting it if it is not a recent duplicate.

Note: This module was generated with AI assistance.

Parameters

recordlogging.LogRecord

The log record to process.

Returns

None

Returns None when the record is suppressed as a duplicate.

flexcore.logger.get_logger(name=None, dedup_enabled=None)

Return a project logger with a DedupHandler attached.

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 a DedupHandler, 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. When None, 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 via get_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 levelno to True (dedup enabled) or False (dedup disabled). Missing levels default to False. The default mapping enables dedup for logging.WARNING and CONFIGURATION_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 levelno to dedup flag. Existing handlers keep their current state; call get_logger() again or mutate handler.dedup_enabled directly 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.