API reference¶
The symbols below are the complete public namespace exported by blvpy
0.5. Objects in the advanced section expose canonical numerical
metadata for inspection; their detailed structure might change.
Modeling and solving¶
- class blvpy.LowerProblem(objective, constraints=(), parameters=())[source]¶
A convex lower problem parameterized by selected upper variables.
LowerProblemhas the same basic construction pattern ascvxpy.Problem, with the additionalparametersargument. Each variable listed there is an upper variable: BLVPY replaces it internally by a CVXPY parameter while retaining every unlisted variable as a lower decision variable. The supplied expression trees are not mutated.- Parameters:
objective (cvxpy.Objective) – Objective of the lower problem. A supported bilevel model must use
cvxpy.Minimizeorcvxpy.Maximizeand satisfy DCP and DPP when validated. Maximization objectives are normalized internally to equivalent minimization objectives during canonicalization.constraints (sequence of cvxpy.Constraint or None, optional) – Lower constraints.
Noneand the default empty sequence both mean that the lower problem has no explicit constraints.parameters (sequence of cvxpy.Variable or None, optional) – Upper variables that are held fixed when solving the lower problem. Every listed variable must occur in
objectiveorconstraints.Noneand the default empty sequence mean that no upper variables occur in the lower model.
- Raises:
TypeError – If the objective, constraints, or parameters have invalid types.
ParameterMappingError – If a parameter variable is duplicated or does not occur in the lower expressions.
Notes
Domain attributes and native bounds on a listed variable are copied to its generated parameter. Lower decision variables remain the same CVXPY objects used by the upper expressions, which implements optimistic selection among multiple lower optima.
- property objective¶
The original lower objective.
- Type:
cvxpy.Objective
- property constraints¶
Original lower constraints in construction order.
- Type:
tuple of cvxpy.Constraint
- property parameters¶
Upper variables treated as lower parameters.
- Type:
tuple of cvxpy.Variable
- class blvpy.BilevelProblem(upper_objective, lower_problem, upper_constraints=())[source]¶
An optimistic bilevel optimization problem.
The upper expressions reuse the lower decision-variable objects from
lower_problem. BLVPY therefore optimizes over all lower-optimal solutions and implements optimistic bilevel semantics.- Parameters:
upper_objective (cvxpy.Objective) – Objective of the upper problem. Validation requires a real-valued scalar
cvxpy.Minimizeorcvxpy.Maximizeobjective.lower_problem (LowerProblem) – Convex lower problem and its linked upper variables.
upper_constraints (sequence of cvxpy.Constraint, optional) – Constraints of the upper problem. Generated constraints that preserve the domains of linked variables are added internally.
- upper_objective¶
The upper objective supplied at construction.
- Type:
cvxpy.Objective
- lower_problem¶
The lower model supplied at construction.
- Type:
- upper_constraints¶
The supplied upper constraints in construction order.
- Type:
tuple of cvxpy.Constraint
- Raises:
TypeError – If an argument is not the required CVXPY or BLVPY type.
Notes
Constructing this object does not canonicalize or solve either level. Call
validate()for detailed structural diagnostics orsolve()to validate and compute a local numerical result.- property upper_variables¶
Upper variables in stable discovery order.
Variables owned by the generated lower CVXPY problem are excluded, even when they also occur in the upper objective or constraints.
- Type:
tuple of cvxpy.Variable
- property source_variables¶
All user-created variables in stable order.
Upper variables precede lower decision variables, and repeated CVXPY objects appear only once.
- Type:
tuple of cvxpy.Variable
- is_dblp()[source]¶
Return whether the model passes BLVPY’s structural validation.
- Returns:
Truewhenvalidate()succeeds, otherwiseFalse.- Return type:
bool
Notes
This convenience check suppresses the validation exception. Use
validate()when the failure reason is needed. It does not test numerical feasibility, boundedness, or solver availability.
- validate()[source]¶
Validate and assemble the supported single-level reformulation.
Validation checks the upper model, lower DCP and DPP compliance, the audited exact-canonicalization policy, the supported affine-cone restriction, and DNLP compatibility of the lifted formulation.
- Return type:
None
- Raises:
ValidationError – If the upper or lower model violates a structural requirement.
UnsupportedModelError – If the model uses an unsupported variable type, atom, or DNLP expression.
UnsupportedConeError – If lower canonicalization produces an unsupported cone.
ApproximateCanonicalizationError – If an accepted-looking source expression would be canonicalized only approximately.
CanonicalizationError – If CVXPY does not expose the expected exact conic program.
Notes
The canonical and lifted representations produced by successful validation are cached. Source-level structural checks are repeated on later calls. Validation does not prove feasibility, boundedness, constraint qualifications, or solver convergence.
- canonicalize()[source]¶
Canonicalize the lower problem into BLVPY’s supported affine conic form.
- Returns:
Cached metadata for
min c.T @ u + dsubject toA @ u + s == bandsin the recorded product cone.- Return type:
- Raises:
ValidationError – If the lower problem is not a supported DCP/DPP optimization problem.
UnsupportedConeError – If canonicalization contains PSD or N-dimensional power cones.
CanonicalizationError – If the fixed Clarabel-compatible reduction cannot be extracted.
Notes
This method is intended for numerical inspection. Fixed ordinary CVXPY parameters are frozen at their current values the first time canonicalization occurs.
- solve(*, epsilon_initial=0.1, epsilon_target=1e-06, contraction=0.1, best_of=None, feasibility_tolerance=1e-07, seed=None, solver='IPOPT', conic_solver='CLARABEL', solver_options=None, conic_solver_options=None, restoration=True, max_retries=8, verbose=True, solver_verbose=False)[source]¶
Solve locally by epsilon-gap continuation.
- Parameters:
epsilon_initial (float, default=1e-1) – Positive relaxation used for the first nonlinear solve.
epsilon_target (float, default=1e-6) – Positive final relaxation. It cannot exceed
epsilon_initial.contraction (float, default=0.1) – Factor in
(0, 1)used to decrease epsilon after an accepted continuation point.best_of (int or None, default=None) –
Noneperforms one deterministic continuation. A positive integer performs that many independently initialized complete continuations and selects the acceptable target-epsilon result with the best upper objective in its modeled sense.feasibility_tolerance (float, default=1e-7) – Nonnegative threshold applied to independently computed lifted feasibility and relaxed-gap residuals.
seed (int, numpy.random.Generator, or None, default=None) – Random generator specification for explicit
best_ofruns. It has no effect on deterministic initialization.solver (str, default=cvxpy.IPOPT) – CVXPY DNLP backend used for restoration and continuation. IPOPT is BLVPY’s installed and tested default; other CVXPY DNLP backends must be installed independently.
conic_solver (str, default=cvxpy.CLARABEL) – CVXPY conic backend used for upper-point projection and fixed-upper lower initialization.
solver_options (mapping or None, default=None) – Backend-specific options forwarded to each DNLP solve. The mapping is copied and is not modified by BLVPY.
conic_solver_options (mapping or None, default=None) – Backend-specific options forwarded to conic solves. The mapping is copied and is not modified by BLVPY.
restoration (bool, default=True) – Whether to attempt a DNLP feasibility-restoration solve when the initialized lifted point exceeds
feasibility_tolerance.max_retries (int, default=8) – Maximum number of intermediate-epsilon insertions following failed continuation attempts within each run.
verbose (bool, default=True) – Whether to write BLVPY’s concise progress transcript to standard error.
solver_verbose (bool, default=False) – Whether to request CVXPY and native backend output. Backend silence is best effort.
- Returns:
Immutable snapshots of the selected local point, its residuals, and every attempted run and continuation step. If no run reaches the target after successful initialization, a best partial result with status
"continuation_failed"is returned.- Return type:
- Raises:
ValueError – If a numerical setting has an invalid type or range.
ValidationError – If the model does not satisfy BLVPY’s structural requirements.
InitializationError – If no run produces an acceptable initial-epsilon point.
SolverUnavailableError – If a requested solver is unavailable or cannot load.
Notes
Deterministic initialization preserves existing upper-variable values; otherwise it uses native-bound interior points or zero. Explicit
best_ofusesvariable.sample_boundsfirst, then an existing value, then finite native bounds. Every viable run has an independent continuation and retry budget.
- gap_diagnostics(result, *, solver='CLARABEL', solver_options=None, solver_verbose=False)[source]¶
Compute canonical and source-level gap diagnostics for a result.
- Parameters:
result (BilevelResult) – Successful or
"continuation_failed"result produced by this problem. Complete source and canonical snapshots are required.solver (str, default=cvxpy.CLARABEL) – CVXPY conic backend for one fresh fixed-upper lower solve.
solver_options (mapping or None, default=None) – Backend-specific options copied and forwarded unchanged to CVXPY.
solver_verbose (bool, default=False) – Whether to request CVXPY and native conic-solver output.
- Returns:
Canonical inexact-gap terms and lower-level source-objective suboptimality against the reference optimum.
- Return type:
- Raises:
TypeError – If
resultis not ablvpy.BilevelResult.ValueError – If the result is incompatible, incomplete, nonfinite, or has a status unsuitable for diagnosis.
SolverUnavailableError – If the requested conic solver is unavailable or cannot load.
SolveError – If the fixed-upper lower reference solve fails or returns no usable solution.
Notes
The diagnostic solve uses fixed-parameter values captured at initial canonicalization. All affected CVXPY variable and parameter values are restored before this method returns or raises.
- polish(result, *, solver='CLARABEL', solver_options=None, verbose=True, solver_verbose=False)[source]¶
Re-solve the lower problem at a result’s fixed upper point.
- Parameters:
result (BilevelResult) – Successful or
"continuation_failed"result produced by this problem with complete source-variable snapshots.solver (str, default=cvxpy.CLARABEL) – CVXPY conic backend used for the fixed-upper lower solve.
solver_options (mapping or None, default=None) – Backend-specific options copied and forwarded unchanged to CVXPY.
verbose (bool, default=True) – Whether to write the concise polishing summary to standard error.
solver_verbose (bool, default=False) – Whether to request CVXPY and native conic-solver output.
- Returns:
Immutable polished candidate with residual diagnostics and an upper-objective comparison.
- Return type:
- Raises:
TypeError – If
resultis not ablvpy.BilevelResult.ValueError – If the result is incompatible or unsuitable for polishing, or an argument has an invalid value.
SolverUnavailableError – If the requested conic solver is unavailable or cannot load.
SolveError – If the fixed-upper lower solve returns no usable certificate.
Notes
This method restores all model state before returning or raising. A polished response can violate upper constraints or lose an optimistic lower-level selection when the lower solution is nonunique.
Results and diagnostics¶
- class blvpy.BilevelResult(status, objective=None, variable_values=<factory>, canonical_primal=None, slack=None, dual=None, iterations=(), runs=(), selected_run_index=None, final_iteration=None, message=None, _feasibility_tolerance=1e-07, _problem_token=None)[source]¶
Immutable result returned by
blvpy.BilevelProblem.solve().- Parameters:
status (str) – Nonempty terminal status. Use
succeededinstead of depending on backend-specific success spellings.objective (float or None, optional) – Upper objective at the returned point, or
Nonewhen unavailable.variable_values (mapping, optional) – Snapshots keyed by the original upper and lower CVXPY variable objects.
canonical_primal (array-like or None, optional) – Returned canonical lower primal vector
u.slack (array-like or None, optional) – Returned canonical primal cone vector
s.dual (array-like or None, optional) – Returned canonical dual cone vector
lambda.iterations (tuple of IterationRecord, optional) – Continuation attempts belonging to the selected run.
runs (tuple of RunRecord, optional) – Every deterministic or explicit
best_ofrun in index order.selected_run_index (int or None, optional) – Zero-based index of the run whose state is exposed by the top-level fields.
final_iteration (IterationRecord or None, optional) – Record representing the returned selected-run state. If omitted while
iterationsis nonempty, the last attempted record is used.message (str or None, optional) – Terminal failure or diagnostic detail.
- Raises:
ValueError – If a scalar field, numerical snapshot, iteration or run collection, selected-run index, or final iteration is invalid or inconsistent.
Notes
Numeric values are copied into read-only NumPy arrays, and mappings are read-only views. A
"continuation_failed"result exposes the best available partial run but is not successful.- property epsilon_history¶
Selected-run tolerances accepted in decreasing order.
- Type:
tuple of float
- property attempted_epsilon_history¶
All selected-run attempts, including failures and retries.
- Type:
tuple of float
- property solver_statuses¶
Status of every selected-run continuation attempt.
- Type:
tuple of str
- property complementarity¶
Canonical complementarity at the returned point.
- Type:
float or None
- property final_epsilon¶
Epsilon associated with the returned point.
- Type:
float or None
- property succeeded¶
Whether the top-level status is a BLVPY success status.
- Type:
bool
- property all_objectives¶
Terminal objective of every run in recorded order.
- Type:
tuple
- class blvpy.PolishResult(variable_values, residuals, feasibility_tolerance, objective, objective_improvement_ratio)[source]¶
Immutable candidate returned by
blvpy.BilevelProblem.polish().- Parameters:
variable_values (mapping) – Complete polished snapshots keyed by the original CVXPY variables. Upper values are fixed at the supplied bilevel result and lower values come from the fresh fixed-upper lower solve.
residuals (Residuals) – Residuals for the complete candidate at zero complementarity relaxation.
feasibility_tolerance (float) – Finite nonnegative tolerance inherited from the originating solve and used to determine
feasible.objective (float) – Polished upper objective in its original modeled sense.
objective_improvement_ratio (float or None) – Relative improvement over the original point. Positive is better and negative is worse for both minimization and maximization;
Nonerepresents a zero baseline. Signed infinity is retained when the relative magnitude exceeds floating-point range; NaN is invalid.
Notes
The mapping and every numerical value are immutable snapshots. Polishing does not assign the candidate to the user’s CVXPY variables.
- property feasible¶
Whether the polished candidate passes its stored residual check.
- Type:
bool
For the fixed-upper post-solve workflow and interpretation of
blvpy.PolishResult, see Polishing.
- class blvpy.RunRecord(index, initial_values, status, objective=None, iterations=(), final_iteration=None, message=None)[source]¶
Outcome and complete history of one independently initialized run.
- Parameters:
index (int) – Zero-based nonnegative run index.
initial_values (mapping) – Upper-variable initialization recorded for the run. These are the post-projection values when projection succeeds and the original candidate if initialization fails earlier. Keys are normally CVXPY variables; values are copied into read-only NumPy arrays.
status (str) – Nonempty terminal solver or BLVPY status.
objective (float or None, optional) – Terminal upper objective, or
Nonewhen unavailable.iterations (tuple of IterationRecord, optional) – All epsilon-continuation attempts in execution order, including rejected and inserted-epsilon attempts.
final_iteration (IterationRecord or None, optional) – Record representing the state returned for this run. If omitted while
iterationsis nonempty, the last attempted record is used.message (str or None, optional) – Terminal failure or diagnostic detail.
- Raises:
ValueError – If the index, status, objective, initial-value mapping, iteration records, or final iteration is invalid.
Notes
Each explicit
best_ofcandidate receives its own continuation and retry budget. A run can retain a useful partial point even when it does not reach the requested target epsilon.- property epsilon_history¶
Successful tolerances in decreasing accepted order.
- Type:
tuple of float
- property attempted_epsilon_history¶
All attempted tolerances, including failures and retries.
- Type:
tuple of float
- property solver_statuses¶
Status of every attempt in continuation order.
- Type:
tuple of str
- property complementarity¶
Canonical complementarity at the returned point.
- Type:
float or None
- property final_epsilon¶
Continuation tolerance at the returned point.
- Type:
float or None
- property succeeded¶
Whether the terminal status is one of BLVPY’s success statuses.
- Type:
bool
- class blvpy.IterationRecord(epsilon, status, objective, residuals, solver_name=None, solve_time=None, num_iters=None, message=None)[source]¶
Numerical record for one epsilon-continuation attempt.
- Parameters:
epsilon (float) – Finite nonnegative relaxation requested for this attempt.
status (str) – Nonempty CVXPY solver status or BLVPY diagnostic status.
objective (float or None) – Upper objective reported for the attempt, or
Nonewhen unavailable.residuals (Residuals) – Independently computed lifted residuals.
solver_name (str or None, optional) – Name of the selected nonlinear backend.
solve_time (float or None, optional) – Finite nonnegative solver-reported time in seconds, when available.
num_iters (int or None, optional) – Nonnegative solver-reported iteration count, when available.
message (str or None, optional) – Additional failure or diagnostic detail.
- Raises:
ValueError – If epsilon, status, objective, residuals, solver time, or iteration count has an invalid value or type.
Notes
A solver success status does not by itself make an attempt acceptable; BLVPY also applies its independent residual checks.
- class blvpy.Residuals(primal_equality, dual_equality, recovery, upper_constraints, primal_cone, dual_cone, complementarity, gap_violation)[source]¶
Residual summary recomputed independently of the DNLP solver status.
- Parameters:
primal_equality (float) – Euclidean norm of
A @ u + s - b.dual_equality (float) – Euclidean norm of
A.T @ lambda + c.recovery (float) – Largest Euclidean mismatch between a source lower variable and its value recovered from the canonical primal vector.
upper_constraints (float) – Largest CVXPY violation norm among the upper and generated linked-variable domain constraints.
primal_cone (float) – Numerical distance diagnostic from
sto the primal product cone. Exponential and 3D power-cone contributions are numerical estimates with a conservative upper-bound fallback.dual_cone (float) – Numerical distance diagnostic from
lambdato the dual product cone. Exponential and 3D power-cone contributions are numerical estimates with a conservative upper-bound fallback.complementarity (float) – Raw canonical pairing
s.T @ lambda. It may be slightly negative at a numerically infeasible point.gap_violation (float) – Violation
max(complementarity - epsilon, 0)of the relaxed gap constraint.
- Raises:
ValueError – If a field is not real-valued, or if a residual other than
complementarityis negative or NaN.
Notes
All fields except
complementarityare nonnegative. Infinite residuals are retained to represent missing or nonfinite numerical solver output. Zero, nonnegative, and second-order cone distances are analytic. Nonlinear cone diagnostics reserve zero for exact membership and may retry uncertain solver results. If no usable positive estimate is available, they use a conservative upper bound; numerical estimates are not certificates.- property max_feasibility¶
Largest lifted-feasibility residual, excluding the gap constraint.
- Type:
float
- property max_violation¶
Largest feasibility or relaxed-gap violation.
- Type:
float
- is_feasible(tolerance, *, gap_tolerance=None)[source]¶
Test the lifted feasibility and relaxed-gap residuals.
- Parameters:
tolerance (float) – Finite nonnegative bound for
max_feasibility.gap_tolerance (float or None, optional) – Finite nonnegative bound for
gap_violation.Noneusestolerance.
- Returns:
Whether both residual bounds are satisfied.
- Return type:
bool
- Raises:
ValueError – If either tolerance is negative, nonfinite, or not real-valued.
- class blvpy.GapDiagnostics(primal_objective, dual_objective, complementarity, dual_residual_term, primal_residual_term, source_gap=None)[source]¶
Terms in the inexact canonical primal-dual gap identity.
- Parameters:
primal_objective (float) – Canonical linear objective
c.T @ u, without the common offset.dual_objective (float) – Canonical dual objective
-b.T @ lambda, without the common offset.complementarity (float) – Canonical cone pairing
s.T @ lambda.dual_residual_term (float) – Correction
u.T @ r_d, wherer_d = A.T @ lambda + c.primal_residual_term (float) – Correction
lambda.T @ r_p, wherer_p = A @ u + s - b.source_gap (float or None, optional) – Lower-level source-objective suboptimality against a fresh fixed-upper reference solve: returned objective minus the optimum for minimization, and the optimum minus returned objective for maximization.
blvpy.BilevelProblem.gap_diagnostics()populates this field.
- Raises:
ValueError – If any supplied diagnostic term is not real-valued.
Notes
The identity is
primal_objective - dual_objective = complementarity +dual_residual_term - primal_residual_term.Small nonzero identity errors and slightly negative source gaps can arise from floating-point solver tolerances.
- property normalized_gap¶
Canonical primal objective minus canonical dual objective.
- Type:
float
- property inexact_identity_rhs¶
Complementarity plus the two signed residual corrections.
- Type:
float
- property identity_error¶
Left-hand side minus right-hand side of the inexact identity.
- Type:
float
Exceptions¶
- exception blvpy.BilevelError[source]¶
Base class for BLVPY-specific errors.
Catch this class to handle any modeled validation, canonicalization, initialization, or solve failure emitted through BLVPY’s public API. Ordinary CVXPY and Python argument errors may still propagate when they do not belong to a BLVPY-specific boundary.
- exception blvpy.ValidationError[source]¶
Raised when a model fails disciplined bilevel validation.
This includes invalid upper/lower structure and lower DCP or DPP failures. More specific unsupported-model and parameter-linking failures derive from this class.
- exception blvpy.ParameterMappingError[source]¶
Raised when an upper variable cannot parameterize the lower problem.
Examples include duplicate or unused
LowerProblem.parameters, missing fixed parameter values, incompatible shapes, and invalid canonical parameter packing.
- exception blvpy.UnsupportedModelError[source]¶
Raised when a model uses a feature outside BLVPY’s supported subset.
Unsupported variable domains, source atoms, and lifted expressions that are not DNLP-compliant are reported through this exception.
- exception blvpy.UnsupportedConeError[source]¶
Raised when lower canonicalization produces an unsupported cone.
BLVPY supports zero, nonnegative, second-order, exponential, and 3D power cones. PSD and N-dimensional power-cone blocks trigger this exception before nonlinear solving.
- exception blvpy.ApproximateCanonicalizationError[source]¶
Raised when a source expression has only an approximate cone graph.
The supported affine-conic reformulation requires an audited pointwise-exact canonicalization; approximation-based atoms and constraints are rejected.
- exception blvpy.CanonicalizationError[source]¶
Raised when CVXPY cannot expose BLVPY’s expected canonical program.
This signals a failure or unexpected reduction structure after source-level validation, rather than an unsupported cone reported by
blvpy.UnsupportedConeError.
- exception blvpy.InitializationError[source]¶
Raised when no acceptable initial continuation point can be built.
The message identifies upper variables that need explicit values or, for randomized
best_ofsolving, finite sampling ranges whenever possible. Diagnostic notes may include lower-solve or restoration failures.
Raised when a requested numerical backend is unavailable.
BLVPY translates CVXPY’s missing-solver response and native import or loading failures into this exception at the actual solve call.
- exception blvpy.SolveError[source]¶
Raised when a required numerical operation cannot produce a result.
The main public use is a failed reference lower solve requested by
blvpy.BilevelProblem.gap_diagnostics(). Derivative-compilation and restoration failures encountered duringsolve()are normally captured in run histories or summarized byblvpy.InitializationError.
Advanced canonical inspection¶
Note
These classes are public so that you can inspect the canonical lower problem:
for example, its cone layout, parameter-dependent numerical data, and source-
variable recovery maps. Obtain them by calling
blvpy.BilevelProblem.canonicalize() and use their documented inspection
methods.
For a lower cp.Maximize(f) objective, these objects expose the normalized
cp.Minimize(-f) conic form. Their canonical objective values therefore have
the opposite sign from the original lower objective.
They are not intended to be constructed or modified by users. In particular, do not instantiate these classes directly, mutate arrays or CVXPY expressions stored inside them, or rely on their exact field organization remaining unchanged.
- class blvpy.CanonicalLowerProblem[source]¶
Fixed exact conic canonicalization of a lower problem.
Instances are produced and cached by
blvpy.BilevelProblem.canonicalize(). They expose the affine canonical data and source-recovery metadata for advanced numerical inspection; direct construction is not a supported modeling workflow.- canonical_variable_offsets¶
Read-only mapping from each CVXPY canonical variable ID to its starting canonical column.
- Type:
collections.abc.Mapping[int, int]
- cone_layout¶
Ordered zero, nonnegative, second-order, exponential, and 3D power-cone blocks.
- Type:
- canonical_size¶
Length of the canonical primal vector
u.- Type:
int
- constraint_size¶
Length of the canonical slack and dual vectors.
- Type:
int
- parameter_specs¶
Packing metadata for parameters retained in the affine data map.
- Type:
tuple of ParameterSpec
- recovery_specs¶
Affine source-variable recovery maps.
- Type:
tuple of RecoverySpec
- fixed_parameter_values¶
Read-only mapping of unmapped parameter IDs to read-only value snapshots captured at canonicalization time.
- Type:
collections.abc.Mapping[int, numpy.ndarray]
Notes
The represented program is
min c(x).T @ u + d(x)subject toA(x) @ u + s == b(x)andsinblvpy.CanonicalLowerProblem.cone_layout. Its matrix convention is pre-solver CVXPY canonical data, before Clarabel scaling or presolve.- property source_variable_ids¶
Original lower-variable IDs in CVXPY problem order.
- Type:
tuple of int
- property recovery_map¶
Combined recovery map for all source lower variables.
- Type:
- property parameter_ids¶
Retained parameter IDs in CVXPY problem order.
Unmapped parameters are frozen into constant canonical data at canonicalization time and therefore do not appear here.
- Type:
tuple of int
- apply_numeric(values=None)[source]¶
Evaluate the affine canonical data numerically.
- Parameters:
values (mapping or None, optional) – Parameter overrides keyed by a retained CVXPY parameter object or its integer ID. Missing mapped values are read from their linked upper expressions. Unmapped parameters remain frozen at their canonicalization-time values.
- Returns:
Evaluated
A,b,c, andd.- Return type:
- Raises:
ParameterMappingError – If a required linked value is absent, has the wrong shape, or is nonfinite.
ValueError – If the evaluated canonical dimensions or values are invalid.
- build_data_expressions(parameter_expr_by_id)[source]¶
Build symbolic affine expressions for the canonical data.
- Parameters:
parameter_expr_by_id (mapping) – Optional replacements keyed by a retained CVXPY parameter object or its integer ID. Values must be affine CVXPY expressions with the source parameter shape. Missing mapped entries use their linked upper expressions.
- Returns:
Affine expressions for
A,b,c, andd.- Return type:
- Raises:
ParameterMappingError – If a replacement has an incompatible shape or is not affine, or if no value is available for a required parameter.
Notes
Unmapped parameters were frozen as constants before the affine map was extracted.
- recovery_expressions(u)[source]¶
Construct recovery expressions for all source lower variables.
- Parameters:
u (cvxpy.Expression) – Canonical primal vector.
- Returns:
Source-shaped expressions keyed by original variable ID.
- Return type:
dict[int, cvxpy.Expression]
- recover_numeric(u)[source]¶
Recover all source lower variables from a canonical vector.
- Parameters:
u (array-like) – Canonical primal vector.
- Returns:
Source-shaped values keyed by original variable ID.
- Return type:
dict[int, numpy.ndarray]
- Raises:
ValueError – If the canonical vector has an incompatible length.
- class blvpy.CanonicalData(A, b, c, d)[source]¶
Numerical data for one evaluated canonical lower problem.
- Parameters:
A (scipy.sparse.csc_array) – Constraint matrix in the convention
A @ u + s == b.b (array-like) – One-dimensional right-hand-side vector.
c (array-like) – One-dimensional linear-objective vector.
d (float) – Scalar objective offset, so the primal objective is
c.T @ u + d.
- Raises:
ValueError – If dimensions are inconsistent or any data are nonfinite.
Notes
bandcare stored as read-onlyfloat64arrays. The row order ofAandbis described by the correspondingblvpy.ConeLayout.
- class blvpy.CanonicalExpressions(A, b, c, d)[source]¶
Symbolic affine data of a canonical lower problem.
- Parameters:
A (cvxpy.Expression) – Canonical constraint matrix as an affine expression of linked upper variables.
b (cvxpy.Expression) – Canonical right-hand-side vector.
c (cvxpy.Expression) – Canonical linear-objective vector.
d (cvxpy.Expression) – Canonical scalar objective offset.
Notes
These expressions use the convention
A @ u + s == band objectivec.T @ u + d. They are primarily intended for advanced inspection; BLVPY constructs the lifted model from them internally.
- class blvpy.ParameterSpec(parameter_id, name, shape, size, mapped, internal_parameter_id, internal_shape, internal_size, offset, transform='identity', sparse_indices=())[source]¶
Description of one parameter in CVXPY’s packed canonical data.
- Parameters:
parameter_id (int) – ID of the parameter before CVXPY attribute reduction.
name (str) – Source parameter name used in diagnostics.
shape (tuple of int) – Original parameter shape.
size (int) – Number of entries in the original shape.
mapped (bool) – Whether the parameter represents a linked upper variable.
internal_parameter_id (int) – ID after CVXPY attribute reduction.
internal_shape (tuple of int) – Shape after attribute reduction.
internal_size (int) – Number of packed entries after attribute reduction.
offset (int) – Starting column in CVXPY’s packed parameter vector.
transform ({“identity”, “symmetric”, “diagonal”, “sparse”}, optional) – Transformation from the source value to the packed representation.
sparse_indices (tuple of tuple of int, optional) – Source indices retained by the
"sparse"transformation.
Notes
This is provisional inspection metadata returned through
blvpy.CanonicalLowerProblem; users normally do not construct it.- pack_numeric(value)[source]¶
Pack a numeric source value in CVXPY’s internal order.
- Parameters:
value (array-like) – Finite value whose shape exactly matches
shape.- Returns:
One-dimensional packed value of length
internal_size.- Return type:
numpy.ndarray
- Raises:
ParameterMappingError – If the shape is wrong or any entry is nonfinite.
- pack_expression(value)[source]¶
Pack an affine CVXPY expression in the internal parameter order.
- Parameters:
value (cvxpy.Expression or array-like) – Affine expression with shape
shape.- Returns:
One-dimensional packed expression of length
internal_size.- Return type:
cvxpy.Expression
- Raises:
ParameterMappingError – If the expression has the wrong shape or is not affine.
- class blvpy.RecoverySpec(variable_id, name, shape, matrix, offset)[source]¶
Fixed affine recovery of one source lower variable.
- Parameters:
variable_id (int) – ID of the original CVXPY lower variable.
name (str) – Original variable name used in diagnostics.
shape (tuple of int) – Original variable shape.
matrix (array-like) – Two-dimensional matrix multiplying the canonical primal vector.
offset (array-like) – Vector added before reshaping in Fortran order to
shape.
- Raises:
ValueError – If
matrixandoffsetdo not describe the requested source shape.
Notes
Recovery has the form
reshape(matrix @ u + offset, shape, order="F").
- class blvpy.AffineRecoveryMap(specs)[source]¶
Affine recovery maps for the original lower variables.
- Parameters:
specs (tuple of RecoverySpec) – Per-variable maps in the original lower problem’s variable order.
- class blvpy.ConeLayout(zero=0, nonnegative=0, second_order=(), power_3d=(), exponential=0)[source]¶
Ordered layout of a supported product cone.
- Parameters:
zero (int, default=0) – Number of scalar rows in the zero-cone block.
nonnegative (int, default=0) – Number of scalar rows in the nonnegative-cone block.
second_order (tuple of int, optional) – Dimensions of the second-order cone blocks. Each dimension includes the scalar head and must be at least two.
power_3d (tuple of float, optional) – Exponent
alphafor each three-dimensional power-cone block. Every exponent must be finite and lie strictly between zero and one.exponential (int, default=0) – Number of three-dimensional exponential-cone blocks. This field is declared after
power_3dto preserve existing positional calls, while its rows precede power-cone rows in canonical order.
- Raises:
ValueError – If a dimension or power-cone exponent is invalid.
Notes
Rows follow CVXPY’s canonical order: zero, nonnegative, each SOC in sequence, each exponential cone, and each 3D power cone in sequence. The associated dual cone is unrestricted on zero-cone rows and self-dual on nonnegative and SOC rows. Exponential and power cones use their respective nonsymmetric duals.
- classmethod from_dims(dims)[source]¶
Build a layout from CVXPY cone dimensions.
- Parameters:
dims (object or mapping) – A CVXPY
ConeDims-like object or mapping. CVXPY aliases such asf,l, andqare recognized.- Returns:
Validated supported product-cone row layout.
- Return type:
- Raises:
ValueError – If
dimsisNone, contains invalid dimensions, or declares nonempty PSD or N-dimensional power cones.
- property nonneg¶
CVXPY-compatible alias for
nonnegative.- Type:
int
- property soc¶
CVXPY-compatible alias for
second_order.- Type:
tuple of int
- property p3d¶
CVXPY-compatible alias for
power_3d.- Type:
tuple of float
- property exp¶
CVXPY-compatible alias for
exponential.- Type:
int
- property size¶
Total number of scalar product-cone rows.
- Type:
int
- primal_constraints(value)[source]¶
Construct CVXPY constraints for primal-cone membership.
- Parameters:
value (cvxpy.Expression or array-like) – Real vector with
sizeentries.- Returns:
Zero equalities, nonnegative inequalities, scalar-form SOC inequalities, and exact exponential- and 3D power-cone constraints in canonical block order.
- Return type:
tuple of cvxpy.Constraint
- Raises:
ValueError – If
valueis complex or has the wrong number of entries.
- dual_constraints(value)[source]¶
Construct CVXPY constraints for dual-cone membership.
- Parameters:
value (cvxpy.Expression or array-like) – Real vector with
sizeentries.- Returns:
Nonnegative, SOC, dual exponential-cone, and dual 3D power-cone membership constraints. Zero-cone dual rows are unrestricted and therefore add no constraints.
- Return type:
tuple of cvxpy.Constraint
- Raises:
ValueError – If
valueis complex or has the wrong number of entries.
- primal_distance(value)[source]¶
Compute distance to the primal product cone.
- Parameters:
value (array-like) – Real numeric vector with
sizeentries.- Returns:
Numerical Euclidean product-cone distance. Zero, nonnegative, and second-order contributions are analytic. Exponential and 3D power-cone contributions are numerical estimates. Exact membership contributes zero, and uncertain solver results may be retried. If no usable positive estimate is available, a conservative finite upper bound is returned. With finite zero-cone entries, nonfinite entries in a constrained block produce positive infinity; NaN in a zero-cone block propagates to the result.
- Return type:
float
- Raises:
ValueError – If
valueis complex, nonnumeric, or has the wrong size.
- dual_distance(value)[source]¶
Compute distance to the dual product cone.
- Parameters:
value (array-like) – Real numeric vector with
sizeentries.- Returns:
Numerical Euclidean product-cone distance, with zero-cone dual rows unrestricted. Exponential and 3D power-cone contributions are numerical estimates. Exact membership contributes zero, and uncertain solver results may be retried. If no usable positive estimate is available, a conservative finite upper bound is returned. Nonfinite constrained entries produce positive infinity.
- Return type:
float
- Raises:
ValueError – If
valueis complex, nonnumeric, or has the wrong size.
- class blvpy.ConeBlock(kind, start, stop, index=0)[source]¶
One contiguous block in a canonical product-cone vector.
- Parameters:
kind ({“zero”, “nonnegative”, “second_order”, “exponential”, “power_3d”}) – Cone represented by the block.
start (int) – Inclusive zero-based row offset.
stop (int) – Exclusive row offset; it must be greater than
start.index (int, default=0) – Zero-based index among blocks of the same kind. It distinguishes multiple cones of one kind.
- Raises:
ValueError – If the kind, offsets, or index are invalid.
- property size¶
Number of scalar rows in the block.
- Type:
int