Function formulation API

Use the experiment tutorial for a guided introduction.

PowerOptLab.PWLFunction — Type
PWLFunction(breakpoints, values; input_unit=:unitless, output_unit=:unitless)

Immutable continuous scalar piecewise-linear function on the finite closed domain (first(breakpoints), last(breakpoints)). Coordinates and values are physical; unit symbols are metadata, not automatic unit conversions. Outside-domain public numeric evaluation is rejected. Smoothing uses the flat extension of this curve.

source

Control intent and lowering

PowerOptLab.VoltVarWattIntent — Type
VoltVarWattIntent(; volt_watt=nothing, volt_var=nothing,
    sensing=:worst_phase, volt_watt_basis=:available,
    conflict_policy=:dominant, conflict_epsilon=0.01,
    worst_phase_watt_guard=true)

Encoding-independent positive-sequence control intent. Curves are immutable PWLFunctions: inputs are physical volts, volt-watt outputs are fractions in [0,1], and volt-var outputs multiply the request's q_scale (positive injection). Both are non-increasing and extend flat beyond their endpoint knots. No smoothing family, solver or model-coordinate scale is stored here.

Sensing is :worst_phase, :average_voltage, or :positive_sequence. Conflict settings apply to worst-phase sensing; the optional watt guard applies to positive-sequence sensing. conflict_epsilon is part of the existing firmware blend semantics, including exact replay; it is not a solver approximation knob.

source
PowerOptLab.VoltVarWattEncoding — Type
VoltVarWattEncoding(; volt_watt=nothing, volt_var=nothing, extrema_epsilon=0.05)

Numerical choices kept separate from VoltVarWattIntent. Assign an explicit formulation to every present curve. extrema_epsilon is the physical voltage width of the established algebraic phase extrema/guard in the full smooth policy. Graph formulations can be used for individual bounded curve ports; complete IBR policy lowering currently accepts smooth formulations only.

source
PowerOptLab.lower_positive_policy — Function
lower_positive_policy(intent, encoding)

Lower semantic volt-var/watt intent to the existing smooth IBR policy without building a JuMP model. Reuse the result when building many snapshots. The result fits SequenceController and its exact/smooth evaluators and staged builder. Non-smooth graph encodings throw UnsupportedFormulation here: support for an individual PWL graph does not imply support for the whole AC controller.

source
PowerOptLab.formulate_control_curve! — Function
formulate_control_curve!(model_or_context, intent, role, sensed_voltage,
    encoding; domain, input_scale=1, output_scale=1, reuse=true)

Lower one :volt_watt or :volt_var curve port at an already selected voltage. The explicit finite domain=(lower_V,upper_V) restricts the port's physical voltage and may extend into the intent's flat tails. encoding is a VoltVarWattEncoding; its selected role may be smooth, MPCC, exact MIP or hull. Return a PWLFormulationHandle in fraction output units. Sensing, P/Q conversion, conflict resolution and plant coupling are not added by this curve-port operation.

With reuse=true, identical calls at the same VariableRef return the same handle and rows. Caches belong to one model; they are never shared across models. Mutable/general input expressions are not cached. reuse=false forces a fresh output/constraint block. Domain, role, curve data, encoding and scales key reuse.

source
PowerOptLab.lowering_statistics — Function
lowering_statistics(model_or_context)

Inspect model structure and PowerOptLab cache sizes: variables, constraints, PWL/hinge scalar operators and shared control-curve blocks. Counts describe construction, not solve cost or a performance benchmark. Upstream registration caches are not counted in the PowerOptLab operator fields.

source
PowerOptLab.PWLRelationPlan — Type
PWLRelationPlan

Inspectable, model-independent lowering decision for a PWL relation on a physical domain. Fields include relation (:equal, :upper, :lower), shape, strategy, semantics, reason/reason_code, conservative, physical output_shift, the signed approximation_contract, affine lines, and remaining nonlinear smooth active_hinges (empty for affine or graph strategies). Plans describe scalar relations, not convexity or solvability of an entire model.

source
PowerOptLab.plan_pwl_relation — Function
plan_pwl_relation(curve, domain; relation=:equal, formulation=:auto, specialize=true, conservative=false)

Plan y == f(x), y <= f(x) (:upper), or y >= f(x) (:lower) in physical coordinates. :auto selects only proven exact affine or polyhedral relations; otherwise the plan is :unresolved and building requires an explicit formulation. Concave upper bounds and convex lower bounds use supporting lines. No near-convexity tolerance or inference from the objective is used.

Explicit smooth formulations preserve the chosen surrogate. Local C2 hinges are removed exactly outside their patches; softplus/algebraic tails are retained. An explicit graph/hull representation may also simplify when the relation is exactly polyhedral. specialize=false retains an explicit representation for comparison. A hull that is not exact remains labeled :outer_relaxation.

For an explicit smooth upper/lower relation, conservative=true shifts the surrogate by -error_upper / -error_lower, respectively. This is an inner approximation of the canonical scalar relation under the declared real-arithmetic error contract. For Local C2, the contract counts only patches intersecting the effective domain, independently of specialize; other smooth families retain their global contract. Inspect plan.approximation_contract. It can conflict with other constraints (e.g. nonnegative power at a zero cap); no clipping or fallback changes that model. Equality and nonsmooth requests reject this option. Finite solver residuals remain additional errors.

source
PowerOptLab.formulate_pwl_relation! — Function
formulate_pwl_relation!(target, curve, input, output; domain=nothing,
    relation=:equal, formulation=:auto, specialize=true, conservative=false,
    input_scale=1, output_scale=1, reuse=true)

Build a contextual scalar relation. Intersect an explicit physical domain with finite declared bounds (or a fixed value) of a VariableRef input. General expressions require an explicit domain: no network bound propagation is performed. Both endpoints must be finite. Always enforce the effective domain in added rows, so later loosening variable bounds does not invalidate the specialization.

:auto refuses nonpolyhedral relations before adding rows; choose a smooth, exact-graph, complementarity or hull formulation explicitly. The input and output are working coordinates with positive physical scales. A shared cache is keyed by both variables, effective domain, relation, formulation, specialization, conservative correction and scales. A law used at another variable or as another relation can lower differently. No optimizer or objective is selected. Return a PWLRelationHandle.

source
PowerOptLab.formulate_control_relation! — Function
formulate_control_relation!(target, intent, role, voltage, fraction; kwargs...)

Lower one VoltVarWattIntent curve as an equality or bound on an existing output. role is :volt_watt or :volt_var. Keywords are those of formulate_pwl_relation!, including relation, formulation and optional domain. No sensing, power-base multiplication, availability or plant constraints are added.

source
PowerOptLab.audit_pwl_relation — Function
audit_pwl_relation(handle)

Report signed output - canonical(input), one-sided/equality relation violation, selected-surrogate violation (including any conservative output shift) when relevant, and physical domain violation. A slack upper limit is not a tracking error. These are candidate checks, not solve or stationarity certificates; a hull's relation violation may be positive. The optional graph_audit separately checks the lifted auxiliary graph, including complementarity residuals; it does not treat that auxiliary as dispatched power.

source

Curve representations and graph construction

PowerOptLab.AlgebraicFormulation — Type

AlgebraicFormulation(width) uses the C∞ hinge (x + sqrt(x² + width²))/2, with physical input width. This is the established algebraic family used by inverter-control selectors.

source
PowerOptLab.ComplementarityGraph — Type

ComplementarityGraph(; scale=nothing) encodes an exact graph with MOI complementarity. scale normalizes hinge variables in physical input units independently of network coordinates; nothing retains legacy input-scale normalization.

source
PowerOptLab.ExactPWLGraph — Type

ExactPWLGraph(; method=:Logarithmic) delegates the exact bounded segment graph to the optional PiecewiseLinearOpt extension.

source
PowerOptLab.primitive_value — Function
primitive_value(curve, x[, formulation])

Evaluate in physical units on the declared domain. The default is the canonical PWL function; a smooth formulation evaluates its surrogate. domain_policy=:flat_extension explicitly permits evaluating the flat-extended curve (or its smoothing) outside the declared domain, as needed for controller tails. A convex hull has no single-valued evaluator. Numeric softplus delegates to BMOPFTools (Float64); use primitive_derivatives for its analytic derivatives.

source
PowerOptLab.formulation_contract — Function
formulation_contract(curve, formulation)

Inspect domain, units, semantics, regularity and a signed physical output-error interval (surrogate - exact). Hull error bounds are nothing: its feasible points are not a surrogate function; use hull_gap_bound for bounded vertical graph deviations. Smooth bounds are analytic real-arithmetic bounds; floating-point evaluation and solver feasibility errors are additional. second_derivative_bound bounds absolute physical curve curvature for smooth formulations (output units / input units²); it is not a KKT condition number.

source
PowerOptLab.PWLFormulationHandle — Type
PWLFormulationHandle

A built representation: canonical curve, formulation, working-coordinate input and output, coordinate scales, physical voltage/input domain, and complementarity pairs. The domain can differ from the curve's outer knots for smooth control ports, without changing the smoothed curve. Inspect its semantics with formulation_contract(handle.curve, handle.formulation) and its candidate values with audit_pwl. Handles do not certify a network solution.

source
PowerOptLab.formulate_pwl! — Function
formulate_pwl!(model_or_context, curve, input, formulation;
               input_scale=1, output_scale=1)

Build a PWL representation and constrain its input to the declared domain. A physical input is input_scale * input; a physical output is output_scale * handle.output. Both scales must be finite and positive.

A BMOPFTools staged context uses its public softplus expression builder. A plain JuMP model uses cached scalar operators with analytic first/second derivatives. Complementarity requires external solver support; the exact segment graph requires import PiecewiseLinearOpt (avoiding its exported PWLFunction name conflict). No optimizer, homotopy, or retry is selected here.

source
PowerOptLab.audit_pwl — Function
audit_pwl(handle)

Inspect a solver candidate in physical coordinates, independently of solver status. Reports domain violation, signed exact-graph error, smooth-equation error when applicable, and complementarity minimum/product residuals in physical input units and their square. A hull candidate can satisfy its encoding while missing the graph. No status is promoted and no physical safety or stationarity certificate is issued.

source

Smoothing and selector extensions

PowerOptLab.AbstractPWLSmoothing — Type
AbstractPWLSmoothing <: AbstractPWLFormulation

Extension interface for a smooth hinge family. Implement hinge_value, hinge_derivatives, and hinge_contract. Use immutable configuration objects. The scalar JuMP operator and complete PWL error accounting are then supplied here.

source
PowerOptLab.hinge_value — Function

hinge_value(x, smoothing) evaluates the smooth approximation to max(0,x). Extension method for new families.

source
PowerOptLab.hinge_contract — Function
hinge_contract(smoothing)

Declare a hinge's signed error interval, regularity, physical width and maximum absolute second derivative. Custom declarations are researcher-supplied claims, not automatically proved. The built-in bounds hold in real arithmetic.

source
PowerOptLab.hinge_expression — Function
hinge_expression(model_or_context, input, smoothing; input_scale=1, output_scale=1)

Build a global smooth positive-part expression. Physical input is input_scale * input; output is physical hinge value divided by output_scale. Custom families reuse their analytic value/derivative interface. Unlike a bounded PWL graph this primitive imposes no domain constraint.

source
PowerOptLab.selector_value — Function
selector_value(a, b, smoothing; kind=:max)

Numeric smooth binary maximum/minimum in physical units. kind=:nonnegative_min uses a*b/smooth_max(a,b), requires a,b>=0, preserves zero and lies below the exact minimum. Ordinary smooth minima may be negative at zero and should not be substituted blindly into capability scale composition.

source
PowerOptLab.selector_expression — Function
selector_expression(model_or_context, a, b, smoothing;
                    kind=:max, input_scale=1, output_scale=1)

Symbolic counterpart of selector_value. Inputs use working coordinates; both share input_scale, and the returned output is divided by output_scale. For :nonnegative_min, the caller must ensure nonnegative inputs in the model. No domain inequalities or extra variables are introduced by this function.

source
PowerOptLab.selector_contract — Function
selector_contract(smoothing; kind=:max)

Signed real-arithmetic error interval relative to the selected hard maximum or minimum, with its domain assumptions. Bounds for custom families inherit the author's hinge contract. A nonnegative minimum requires an upper hinge with finite error bound B and a positive value at zero; its deficit is at most B.

source
PowerOptLab.symmetric_clip_value — Function
symmetric_clip_value(value, limit, smoothing)

Smooth clipping to [-limit, limit], limit>=0, using the symmetric sum smooth_min(value,limit)+smooth_max(value,-limit)-value. For built-in hinges with error [0,B], its signed error at a fixed limit is in [-B,B].

source
PowerOptLab.symmetric_clip_expression — Function
symmetric_clip_expression(model_or_context, value, limit, smoothing;
                          input_scale=1, output_scale=1)

Symbolic counterpart of symmetric_clip_value. The caller must ensure a nonnegative limit. This expression adds no exact physical capability constraint.

source
PowerOptLab.smoothing_for_error — Function
smoothing_for_error(curve, family, budget)

Choose a physical input width from a positive absolute output-error budget using signed slope-change sums. This controls function approximation, not solver or network error. A constant curve needs no smoothing and requires an explicit width if a smoothing object is still desired. Inspect formulation_contract(curve, result) for the resulting error and curvature bounds. Custom families can extend this method.

source
PowerOptLab.smooth_pwl_expression — Function
smooth_pwl_expression(model_or_context, curve, input, smoothing;
                      input_scale=1, output_scale=1)

Return a smooth expression of the canonical flat extension, without imposing a bounded domain or adding an output variable. Suitable for controller curves whose tails remain active beyond their breakpoints. Use formulate_pwl! when the domain must be enforced. Staged softplus construction delegates to BMOPFTools.

source

Physical magnitudes and error accounting

PowerOptLab.MagnitudeApproximation — Type
MagnitudeApproximation(epsilon; direction=:lower, unit=:unitless, scale=nothing)

Smooth Euclidean magnitude with a physical absolute error budget. :lower uses sqrt(sum(x²)+epsilon²)-epsilon and preserves zero; :upper omits the shift and bounds the exact magnitude from above. Direction is mathematical, not a complete certificate that a composed network inequality is conservative. Optional scale is the characteristic magnitude in physical units, preserved in staged upstream annotations after conversion to working coordinates.

source
PowerOptLab.magnitude_expression — Function
magnitude_expression(model_or_context, components, approximation;
                     component_scale=1, output_scale=1)

Build the magnitude from working-coordinate real components. Physical components are component_scale * components; the returned expression is in units of physical magnitude / output_scale. On staged contexts reuse BMOPFTools.smoothnorm. The optional name labels the differentiability annotation. `epsrelcan preserve a previously used relative-width calculation and its exact floating-point provenance; it must agree with the physical budget to rounding tolerance. Both plain models and staged contexts honor an explicit relative width; plain models add no annotation. Without an override, plain models use the absolute working widthepsilon/component_scale` directly. Lower norms retain BMOPFTools annotations; upper norms record their own overestimation semantics. This adds no capability constraint: squared physical inequalities remain available.

source
PowerOptLab.positive_root_expression — Function
positive_root_expression(model_or_context, radicand; lower_bound)

Add the strictly positive domain radicand >= lower_bound and return its exact square root. Both radicand and lower bound use the same working units. This changes the allowed domain explicitly; it is not a smoothing of a root at zero.

source
PowerOptLab.affine_error_bound — Function
affine_error_bound(weights, intervals)

Propagate signed real-arithmetic error intervals through a fixed affine combination. Correlations are ignored, so the interval may be conservative. All weighted errors must have compatible output units, which the caller supplies.

source
PowerOptLab.hull_gap_bound — Function
hull_gap_bound(curve, domain=(first(curve.breakpoints), last(curve.breakpoints)))

Compute maximum vertical deviations of the bounded graph hull from its canonical PWL curve. upper_gap is the concave-envelope excess, lower_gap the deficit to the convex envelope; any hull point obeys -lower_gap <= y-f(x) <= upper_gap. Returns physical units, envelope vertices and attaining witness inputs. A supplied finite domain can cut segments or extend into the canonical flat tails.

Monotone-chain scans use O(n) rational operations on the exact supplied Float64 coordinates; maximum gaps occur at restricted curve knots. Gap bounds are rounded outwards to Float64; displayed envelope/witness values use nearest rounding. These bound vertical scalar graph discrepancy, not a network objective gap, equilibrium error or DOE safety. Constraint-coefficient rounding and solver residuals remain additional. No solver or JuMP model is constructed.

source
PowerOptLab.local_error_response — Function
local_error_response(jacobian, residual_perturbation; condition_limit=1e10)

Compute the first-order estimate delta = -J \ perturbation for a square linearization. Return no estimate for singular/poorly conditioned matrices. This is a local diagnostic, not a nonlinear error bound or a uniqueness certificate. Condition numbers depend on the supplied row/state scaling. The diagnostic uses a dense matrix and is intended for small examples or reduced sensitivity systems.

source

Experiments and reference cases

PowerOptLab.FormulationCase — Type
FormulationCase(id, build; metadata=NamedTuple())

A researcher-defined case. build(representation, configuration) returns a named record with model::JuMP.Model, optional observations (graph or relation handles belonging to that model), and optional metrics (a zero-argument callback returning a dictionary/named tuple). Each run must build a fresh model. Cases may represent primitives, inverters, feeders or DOEs.

source
PowerOptLab.FormulationMethod — Type
FormulationMethod(id, representation, optimizer;
                  options=[], configure! = identity, metadata=NamedTuple())

Representation and external solver configuration. The representation may be a custom object or a named tuple selecting multiple primitives. configure!(model) can install bridges before the optimizer is attached. Solver options and method metadata are caller-owned; no continuation, retry or tolerance defaults are added.

source
PowerOptLab.run_formulation_experiment — Function
run_formulation_experiment(cases, methods;
    configurations=[NamedTuple()], solve=true, assess=nothing,
    on_result=identity, on_error=:record)

Run the caller's case/method/configuration product with one fresh model per entry. Raw solver outcomes, candidate audits, custom metrics and optional assess(row) results remain distinct. Non-success candidates are available for diagnostics; only strict MOI success sets strict_solver_success. No acceptance tolerance is imposed. on_error=:throw stops on ordinary errors; interrupts always propagate. solve=false records model structure without requiring a solver.

Callbacks are trusted user code. Timing includes first-use compilation and is not by itself a controlled performance benchmark. Configurations should be immutable or treated as read-only by callbacks.

source
PowerOptLab.write_formulation_results — Function
write_formulation_results(path, rows; metadata=NamedTuple(), sources=[])

Write a versioned TOML result bundle with Julia/platform/core package versions and SHA-256 hashes of caller-selected source files. The bundle does not automatically capture a complete dependency lock or arbitrary callback code: supply a manifest, configuration script and relevant source paths when reproducibility requires them. Custom configuration/metrics must be plain data. Existing files are overwritten.

source
PowerOptLab.resistive_equilibria — Function
resistive_equilibria(curve, source_voltage, resistance; atol=1e-9)

Enumerate canonical equilibria of V = source_voltage + resistance * curve(V) on the curve's bounded domain by solving each affine segment. Return isolated points and degenerate intervals; uniqueness is not assumed. atol is an absolute voltage tolerance for endpoint inclusion/deduplication. Continuum detection uses exact zero coefficients in floating-point arithmetic; nearly parallel segments remain isolated, potentially ill-conditioned intersections. This is a scalar electrical reference, not a general AC power-flow solver.

source
PowerOptLab.resistive_control_case — Function
resistive_control_case(curve; source_voltage, resistance, id="resistive")

Create a configurable scalar electrical case with a bounded PWL current law. Configuration keys override source_voltage, resistance, input_scale, output_scale, start_input, and objective (:max_current or :zero). Values are physical volts, amperes and ohms except the normalized model coordinates. The method representation is either a formulation or a callable (curve, config) returning one. Metrics include canonical equilibria and physical equation errors.

source
PowerOptLab.controlled_inverter_case — Function
controlled_inverter_case(network, device_builder, request;
                         id="controlled_inverter", metrics=nothing)

Adapt the existing single-inverter staged model to formulation experiments. device_builder(representation, config) returns a ControlledDevice; network is a dictionary or config -> dictionary, and request is a request or callback. Each network is copied. Configuration supports s_base and selection_objective (:loss or :zero). Supply additional model changes through a custom case.

Candidate metrics contain physical POC voltage/current phasors and a same-voltage exact/smooth controller target gap before plant capability backoff. They are diagnostics even when the solver does not succeed; they do not certify equilibrium or hardware feasibility. Optional metrics(ctx, handles, device, request) supplies additional named/dictionary data under custom. Optimizers belong to the method.

source