Code Documentation¶
This is the base module for all other objects of the package.
LaTeX returns a LaTeX string out of an Irene object.
base is the parent of all Irene objects.
- class Irene.base.base[source]¶
All the modules in Irene extend this class which perform some common tasks such as checking existence of certain software.
This module is responsible for conversion of a given symbolic optimization problem into semidefinite optimization problems. The main classes included in this module are:
SDPRelaxations
SDRelaxSol
Mom
- Irene.relaxations.Calpha_(expn, Mmnt)[source]¶
Given an exponent expn, this function finds the corresponding \(C_{expn}\) matrix which can be used for parallel processing.
- Irene.relaxations.Calpha__(expn, Mmnt, ii, q)[source]¶
Given an exponent expn, this function finds the corresponding \(C_{expn}\) matrix which can be used for parallel processing.
- class Irene.relaxations.Mom(expr)[source]¶
This is a simple interface to define moment constraints to be used via SDPRelaxations.MomentConstraint. It takes a sympy expression as input and initiates an object which can be used to force particular constraints on the moment sequence.
Example: Force the moment of \(x^2f(x) + f(x)^2\) to be at least .5:
Mom(x**2 * f + f**2) >= .5 # OR Mom(x**2 * f) + Mom(f**2) >= .5
- class Irene.relaxations.RelaxationConfig(reduction_method: str = 'none', monomial_pruning: bool = False, sparsity_detection: bool = False, sparsity_block_sdp: bool = False, border_basis_degree: int = 2, verbose_reduction: bool = False, quotient_basis: str = 'groebner')[source]¶
Configuration for the SDP relaxation monomial-reduction pipeline.
The default reduction strategy is
'newton_polytope'based on Phase 3 benchmark results (bench_phase3_reductions.py, 2026-08-08): Newton pruning achieves 64–67 % basis reduction on sparse gallery problems with zero overhead on dense ones. Sparsity detection only helps 2/12 problems, and border basis shows no conditioning advantage at low degrees.- reduction_method¶
Which reduction strategy to apply before building the moment matrix. One of
'none','newton_polytope','border_basis', or'sparsity'(correlative sparsity decomposition). Default'none'.- Type:
- monomial_pruning¶
Enable Newton-polytope pruning of the monomial basis via the newton_polytope module (Minkowski hull of the objective + constraint supports). Until a complete SOS-support certificate exists, this path retains the full degree-bounded support (hull membership alone does not certify that an exponent is removable from the moment/Gram basis – see
_pruned_basis_from_module), so enabling it currently changes no SDP; the option is kept so a certified reduction can be activated later. DefaultFalse.- Type:
- sparsity_detection¶
Run correlative-sparsity analysis on the problem polynomials and decompose the moment matrix into independent blocks when possible.
- Type:
- sparsity_block_sdp¶
When True and sparsity detection finds disconnected variable cliques, build and solve one SDP per clique instead of a single monolithic SDP. This can give exponential savings for problems whose variables split into truly independent sub-problems (e.g. block-diagonal objectives). Default
False.- Type:
- border_basis_degree¶
Degree bound for the border-basis quotient algebra representation (only used when
reduction_method='border_basis'). Default2.- Type:
- class Irene.relaxations.SDPRelaxations(gens, relations=(), name='SDPRlx', config=None)[source]¶
This class defines a function space by taking a family of sympy symbolic functions and relations among them. Simply, it initiates a commutative free real algebra on the symbolic functions and defines the function space as the quotient of the free algebra by the ideal generated by the given relations. It takes three arguments:
gens which is a list of
sympysymbols and function symbols,relations which is a set of
sympyexpressions in terms of gens that defines an ideal.name is a given name which is used to save the state of the instant at break.
- AddConstraint(cnst)[source]¶
Takes an (in)equality as an algebraic combination of the generating functions that defines the feasibility region. It reduces the defining (in)equalities according to the given relations.
- Calpha(expn, Mmnt)[source]¶
Given an exponent expn, this method finds the corresponding \(C_{expn}\) matrix.
P5.7: When
Mmntis a precomputed dict-of-dicts (from_precompute_entry_dicts), uses O(1) dict lookups instead of per-entry _poly() conversions. Falls back to the original path for raw symbolic matrices.
- Commit(blk, c, idx)[source]¶
Sets the latest computed values for the final SDP and saves the current state.
- Decompose()[source]¶
Returns a dictionary that associates a list to every constraint, \(g_i\ge0\) for \(i=0,\dots,m\), where \(g_0=1\). Each list consists of elements of algebra whose sums of squares is equal to \(\sigma_i\) and \(f-f_*=\sum_{i=0}^m\sigma_ig_i\). Here, \(f_*\) is the output of the
SDPRelaxation.Minimize().
- ExponentsVec(deg)[source]¶
Returns all the exponents that appear in the reduced basis of all monomials of the auxiliary symbols of degree at most deg.
- InitSDP()[source]¶
Initializes the SDP based on the value of
self.Parallel. If it isTrue, it runs in parallel mode, otherwise in serial.P5.8: When
config.sparsity_block_sdpis True (orreduction_method='sparsity'), routes through the correlative sparsity decomposition path instead of a monolithic SDP.
- LocalizedMoment(p)[source]¶
Computes the reduced symbolic moment generating matrix localized at p.
P5.6: The large polynomial product
p * m * m.Tis routed through SymEngine’s C++ backend when available. Each entry of the resulting matrix is expanded withse.expand()(C++) before being converted back to SymPy for Groebner reduction viaReduceExp.
- Minimize(**kwargs)¶
Finds the minimum of the truncated moment problem which provides a lower bound for the actual minimum.
Includes stability diagnostics for high-order relaxations (Risk 1).
Telemetry: when enabled, records total pipeline time, solver status, primal/dual objectives, and moment-matrix condition number.
- MomentConstraint(cnst)[source]¶
Takes constraints on the moments. The input must be an instance of Mom class.
- MomentMat()[source]¶
Returns the numerical moment matrix resulted from solving the SDP.
P5.7: Precomputes Poly dicts for all entries once, then uses them directly instead of re-running _poly() per entry.
- PolyCoefFullVec()[source]¶
return the vector of coefficient of the reduced objective function as an element of the vector space of elements of degree up to the order of moments.
- ReduceExp(expr)[source]¶
Takes an expression expr, either in terms of internal free symbolic variables or generating functions and returns the reduced expression in terms of internal symbolic variables, if a relation among generators is present, otherwise it just substitutes generating functions with their corresponding internal symbols.
- The reduction engine is selected by
config.quotient_basis: ‘groebner’ (default): classical Groebner-basis reduction, the original Irene behavior.
‘border’: BorderBasis quotient-algebra reduction (Irene), using the numerically computed multiplication tables.
- The reduction engine is selected by
- ReducedMonomialBase(deg)[source]¶
Returns a reduce monomial basis up to degree d.
Phase 3 integration: the reduction pipeline is controlled via
self.config. Whenconfig.reduction_method == 'newton_polytope', only exponent tuples that appear in the Minkowski sum of objective + constraint supports are generated, which can cut the basis size by 60–90 % for sparse problems. Whenconfig.reduction_method == 'border_basis', the quotient-algebra border basis is used to replace the full monomial basis.
- RelaxationDeg()[source]¶
Finds the minimum required order of moments according to user’s request, objective function and constraints.
- SetMonoOrd(ordr)[source]¶
Changes the default monomial order to ord which mustbe among lex, grlex, grevlex, ilex, igrlex, igrevlex.
- SetNumCores(num)[source]¶
Sets the maximum number of workers which cannot be bigger than number of available cores.
- SetObjective(obj)[source]¶
Takes the objective function obj as an algebraic combination of the generating symbolic functions, replace the symbolic functions with corresponding auxiliary symbols and reduce them according to the given relations.
- SetSDPSolver(solver)[source]¶
- Sets the default SDP solver. The followings are currently supported:
CVXOPT (legacy, via CVXPY or native)
DSDP (via CVXPY or native)
SDPA (legacy text writer)
CSDP (legacy text writer)
CLARABEL (CVXPY – recommended default)
SCS (CVXPY – first-order, fast for large problems)
The selected solver must be installed otherwise it cannot be called. CVXPY-family solvers (CLARABEL, SCS, CVXOPT) are routed through the direct DCP formulation layer and bypass legacy text-file I/O entirely. When a legacy solver is specified but CVXPY is available, CVXPY is tried first as a fast path with fallback to the legacy backend.
- classmethod from_problem(optim_prob: OptimizationProblem, name='SDPRlx', config=None)[source]¶
Creates an SDPRelaxations instance from an OptimizationProblem.
This method acts as an alternative constructor to bridge compatibility with problems defined using SemigroupAlgebra.
- Parameters:
optim_prob (OptimizationProblem) – The optimization problem defined with SemigroupAlgebra.
name (str) – A name for the relaxation instance.
config – RelaxationConfig instance controlling Phase 3 reduction pipeline. When None, defaults to no reduction.
- Returns:
An instance of SDPRelaxations.
- getConstraint(idx)[source]¶
Returns the constraint number idx of the problem after reduction modulo the relations, if given.
- getMomentConstraint(idx)[source]¶
Returns the moment constraint number idx of the problem after reduction modulo the relations, if given.
- getObjective()[source]¶
Returns the objective function of the problem after reduction modulo the relations, if given.
- pInitSDP(**kwargs)¶
Initializes the semidefinite program (SDP), in parallel, whose solution is a lower bound for the minimum of the program.
Telemetry: when enabled, records wall-clock init time, monomial basis sizes, block dimensions, and relaxation order.
- sInitSDP(**kwargs)¶
Initializes the semidefinite program (SDP), in serial mode, whose solution is a lower bound for the minimum of the program.
Telemetry: when enabled, records wall-clock init time, monomial basis sizes, block dimensions, and relaxation order.
- class Irene.relaxations.SDRelaxSol(X, symdict={}, err_tol=1e-05)[source]¶
Instances of this class carry information on the solution of the semidefinite relaxation associated to an optimization problem. It includes various pieces of information:
SDRelaxSol.TruncatedMmntSeqa dictionary of resulted momentsSDRelaxSol.MomentMatrixthe resulted moment matrixSDRelaxSol.Primalthe value of the SDP in primal formSDRelaxSol.Dualthe value of the SDP in dual formSDRelaxSol.RunTimethe run time of the sdp solverSDRelaxSol.InitTimethe total time consumed for initialization of the sdpSDRelaxSol.Solverthe name of sdp solverSDRelaxSol.Statusfinal status of the sdp solverSDRelaxSol.RelaxationOrdorder of relaxationSDRelaxSol.Messagethe message that maybe returned by the sdp solverSDRelaxSol.ScipySolverthe scipy solver to extract solutionsSDRelaxSol.err_tolthe minimum value which is considered to be nonzeroSDRelaxSol.Supportthe support of discrete measure resulted fromSDPRelaxation.Minimize()SDRelaxSol.Weightscorresponding weights for the Dirac measures
- ExtractSolution(mthd='LH', card=0)[source]¶
Extract support of the solution measure from
SDPRelaxations:-
mthdshould be either ‘LH’ or ‘Scipy’, where ‘LH’ stands for ‘Lasserre-Henrion’ and ‘Scipy’ employs a Scipy solver to find points matching the moments,-
cardrestricts the number of points of the support.
- ExtractSolutionScipy(card=0)[source]¶
This method tries to extract the corresponding values for generators of the
SDPRelaxationclass. Number of points is the rank of the moment matrix which is computed numerically according to the size of its eigenvalues. Then the points are extracted as solutions of a system of polynomial equations using a scipy solver. The following solvers are currently acceptable byscipy:hybr,lm(default),broyden1,broyden2,anderson,linearmixing,diagbroyden,excitingmixing,krylov,df-sane.
- class Irene.sdp.sdp(solver='cvxopt', solver_path=None)[source]¶
This is the class which intends to solve semidefinite programs in primal format:
\[\begin{split}\left\lbrace \begin{array}{lll} \min & \sum_{i=1}^m b_i x_i & \\ \textrm{subject to} & & \\ & \sum_{i=1}^m A_{ij}x_i - C_j \succeq 0 & j=1,\dots,k. \end{array}\right.\end{split}\]- For the argument solver following sdp solvers are supported (if they are installed):
CVXOPT,
CSDP,
SDPA,
DSDP.
- AddConstantBlock(C)[source]¶
C must be a list of
numpymatrices that represent \(C_j\) for each j. This method sets the value for \(C=[C_1,\dots,C_k]\).
- AddConstraintBlock(A)[source]¶
This takes a list of square matrices which corresponds to coefficient of \(x_i\). Simply, \(A_i=[A_{i1},\dots,A_{ik}]\). Note that the \(i^{th}\) call of
AddConstraintBlockfills the blocks associated with \(i^{th}\) variable \(x_i\).
- Option(param, val)[source]¶
Sets the param option of the solver to val if the solver accepts such an option. The following options are supported by solvers:
CVXOPT:show_progress:TrueorFalse, turns the output to the screen on or off (default:True);maxiters: maximum number of iterations (default: 100);abstol: absolute accuracy (default: 1e-7);reltol: relative accuracy (default: 1e-6);feastol: tolerance for feasibility conditions (default: 1e-7);refinement: number of iterative refinement steps when solving KKT equations (default: 0 if the problem has no second-order cone or matrix inequality constraints; 1 otherwise).
SDPA:maxIteration: Maximum number of iterations. The SDPA stops when the iteration exceedsmaxIteration;epsilonStar,epsilonDash: The accuracy of an approximate optimal solution of the SDP;lambdaStar: This parameter determines an initial point;omegaStar: This parameter determines the region in which the SDPA searches an optimal solution;lowerBound: Lower bound of the minimum objective value of the primal problem;upperBound: Upper bound of the maximum objective value of the dual problem;betaStar: Parameter controlling the search direction when current state is feasible;betaBar: Parameter controlling the search direction when current state is infeasible;gammaStar: Reduction factor for the primal and dual step lengths; 0.0 <gammaStar< 1.0.
- csdp()[source]¶
Calls CSDP to solve the initiated semidefinite program.
Deprecated since version This: method uses the legacy text-file I/O interface. The CVXPY DCP layer is now preferred and tried first in
solve().
- static parse_solution_matrix(iterator)[source]¶
Parses and returns the matrices and vectors found by SDPA solver. This was taken from ncpol2sdpa and customized for Irene.
- read_csdp_out(filename, txt)[source]¶
Takes a file name and a string that are the outputs of CSDP as a file and command line outputs of the solver and extracts the required information.
- read_sdpa_out(filename)[source]¶
Extracts information from SDPA’s output file filename. This was taken from ncpol2sdpa and customized for Irene.
- sdpa()[source]¶
Calls SDPA to solve the initiated semidefinite program.
Deprecated since version This: method uses the legacy text-file I/O interface. The CVXPY DCP layer is now preferred and tried first in
solve().
- solve(**kwargs)¶
Solves the initiated semidefinite program.
Tries CVXPY first (no text I/O, direct DCP formulation). Falls back to the legacy solver specified by
self.solverif CVXPY is unavailable or fails.Telemetry: when enabled, records wall-clock solve time, block dimensions, variable count, and solver name in a structured dict accessible via
Irene.telemetry.get_telemetry().
- class Irene.program.OptimizationProblem(sga: SemigroupAlgebra | None = None, relations: list[SemigroupAlgebraElement] | None = None)[source]¶
This class represents an optimization problem.
- sga¶
The semigroup algebra of the optimization problem.
- Type:
- relations¶
The relations of the optimization problem.
- Type:
- semigroup¶
The semigroup of the optimization problem.
- Type:
- objective¶
The objective function of the optimization problem.
- Type:
- constraints¶
The constraints of the optimization problem.
- Type:
- objective_trms_with_positive_coefficient¶
The terms of the objective function with positive coefficients.
- Type:
- objective_trms_with_negative_coefficient¶
The terms of the objective function with negative coefficients.
- Type:
- objective_terms_with_even_exponent¶
The terms of the objective function with even exponents.
- Type:
- objective_terms_with_odd_exponent¶
The terms of the objective function with odd exponents.
- Type:
- constraint_trms_with_positive_coefficient¶
The terms of the constraints with positive coefficients.
- Type:
- constraint_trms_with_negative_coefficient¶
The terms of the constraints with negative coefficients.
- Type:
- constraint_terms_with_even_exponent¶
The terms of the constraints with even exponents.
- Type:
- constraint_terms_with_odd_exponent¶
The terms of the constraints with odd exponents.
- Type:
- add_constraints(const: list[SemigroupAlgebraElement]) None[source]¶
Adds polynomial inequality or equality constraints to the optimization problem.
This method extends the optimization problem with additional constraints, typically representing feasibility conditions like bounds or domain restrictions. Each constraint is analyzed for its degree to assist in later relaxation construction.
Place in code structure: Complements set_objective() to fully define the constrained optimization problem. Called during problem setup before relaxation methods.
- Parameters:
const (list[SemigroupAlgebraElement]) – List of polynomial constraint expressions, each represented as a SemigroupAlgebraElement.
- Returns:
None
- Side effects:
Appends each constraint to self.constraints
Updates self.semigroup if any constraint uses a different semigroup
Computes and stores degree and half-degree for each constraint
- analyse_program() None[source]¶
Performs structural analysis of the optimization problem’s polynomial terms.
This method categorizes all terms from the objective function and constraints based on two key properties: (1) sign of coefficients, and (2) parity of exponents. This analysis is essential for specialized polynomial optimization techniques like SONC (sums of non-negative circuit polynomials) and conditional relaxations.
Place in code structure: Called after problem setup to preprocess the polynomial structure. Populates classification lists used by relaxation algorithms (relaxations.py) and decomposition methods (sonc.py).
- Returns:
None
- Side effects:
Populates the following attributes: - objective_trms_with_positive/negative_coefficient: Objective terms by sign - constraint_trms_with_positive/negative_coefficient: Constraint terms by sign - objective_terms_with_even/odd_exponent: Objective terms by exponent parity - constraint_terms_with_even/odd_exponent: Constraint terms by exponent parity
- convex_combination(point: Sequence[float]) ndarray | None[source]¶
Finds the representation of a point as a convex combination of Newton polytope vertices.
This method formulates and solves a linear program to express a point as a convex combination of the polytope vertices, enforcing both non-negativity of coefficients and that they sum to 1. This is more restrictive than linear_combination() but guarantees the point lies within the convex hull.
Place in code structure: Advanced geometric utility for Newton polytope analysis. Uses scipy.optimize to solve the constrained optimization problem. Results can guide sparse relaxation strategies by identifying how to express new terms using existing ones.
- Parameters:
point – A numeric sequence representing coordinates in the exponent space that should be expressed as a convex combination of self.vertices.
- Returns:
- Array of non-negative coefficients summing to 1 that express the point
as a convex combination of vertices, or None if no such combination exists (i.e., point is outside the Newton polytope).
- Return type:
- delta(xprsn: SemigroupAlgebraElement, deg: int) dict[str, set][source]¶
Identifies problematic terms in polynomial expressions for relaxation construction.
The delta function categorizes terms that cannot be directly represented in a sum-of-squares (SOS) form: terms with odd exponents or negative coefficients. These terms are grouped by whether their total degree equals the target degree (‘=d’) or is less than it (‘<d’), which affects how they’re handled in relaxations.
Place in code structure: Core analysis method used by relaxation algorithms (relaxations.py) to identify which terms need special treatment through auxiliary variables or alternative decomposition strategies.
- Parameters:
xprsn (SemigroupAlgebraElement) – The polynomial expression to analyze.
deg (int) – The target degree for comparison.
- Returns:
- Dictionary with two keys:
’=d’: Set of monomials with degree exactly equal to deg ‘<d’: Set of monomials with degree less than deg Both contain only non-square or negative coefficient terms.
- Return type:
- delta_vertex(xprsn: SemigroupAlgebraElement, vertices: list) None[source]¶
Computes delta relative to Newton polytope vertices (currently unimplemented).
This method is intended to analyze terms based on their relationship to the vertices of the Newton polytope, likely for geometric programming or sparsity exploitation.
Place in code structure: Placeholder for advanced geometric analysis that would work with the newton() and related polytope methods for exploiting problem structure.
- Parameters:
xprsn (SemigroupAlgebraElement) – The expression to analyze.
vertices (list) – List of vertices from the Newton polytope.
- Returns:
None (not yet implemented)
- static has_symbol(symb: str, mono: SemigroupAlgebraElement) tuple[bool, int][source]¶
Searches for a specific variable (symbol) in a monomial and returns its position.
This method determines whether a given variable name appears in a monomial’s factorization, which is useful for variable-specific operations like substitution, elimination, or targeted relaxation strategies.
Place in code structure: Static utility method for monomial inspection. Used by various algorithms that need to check variable presence or extract variable-specific information from polynomial terms.
- Parameters:
symb (str) – The name of the variable/symbol to search for (e.g., ‘x’, ‘y’).
mono (SemigroupAlgebraElement) – The monomial to search within.
- Returns:
- A tuple where the first element is True if the symbol is found,
False otherwise. The second element is the index of the symbol in the monomial’s array form if found, or -1 if not found.
- Return type:
- in_newton(point: Sequence[float]) bool[source]¶
Tests whether a point lies inside the Newton polytope.
This method uses Delaunay triangulation to efficiently determine if a given point (typically representing a monomial’s exponents) is within the convex hull of the problem’s support. This is useful for determining which monomials are representable as convex combinations of existing terms.
Place in code structure: Geometric query method that depends on newton() being called first. Used in sparsity analysis and to determine valid monomial spaces for relaxations.
- Parameters:
point – A numeric sequence (tuple, list, or array) representing exponent coordinates to test for inclusion in the Newton polytope.
- Returns:
- True if the point is inside or on the boundary of the Newton polytope,
False otherwise.
- Return type:
- Raises:
ValueError – If vertices are empty or if Delaunay triangulation fails due to degenerate geometry.
- linear_combination(point: Sequence[float]) ndarray[source]¶
Expresses a point as a linear combination of Newton polytope vertices.
This method solves a linear system to find coefficients that express the given point as a linear combination of polytope vertices. Note that unlike convex_combination(), this method doesn’t enforce non-negativity or that coefficients sum to 1, so it’s suitable for affine (not necessarily convex) combinations.
Place in code structure: Geometric utility for expressing points in terms of vertices. Complements convex_combination() but with less restrictive constraints. Used when affine relationships are needed rather than strictly convex ones.
- Parameters:
point – A numeric sequence representing coordinates to express in terms of vertices.
- Returns:
- Array of coefficients for the linear combination. Note that these
coefficients may be negative or sum to values other than 1.
- Return type:
Note
Excludes the origin vertex [0, 0, …] if present to avoid singularity issues.
- mono2ord_tuple(mono: Any) tuple[int, ...][source]¶
Converts a monomial from semigroup representation to a tuple of exponents.
This method transforms a symbolic monomial into a numeric tuple where each position corresponds to a generator in the semigroup, containing that generator’s exponent. This standardized format is essential for numerical computations like convex hull calculations and geometric analysis.
Place in code structure: Conversion utility used by newton() and related geometric methods to transform symbolic polynomial data into numeric arrays suitable for scipy geometric algorithms.
- Parameters:
mono (SemigroupAlgebraElement) – The monomial to convert. Can also be a scalar (int or float) representing a constant term.
- Returns:
- A tuple of integers representing the exponents of each generator in order.
For constants, returns a tuple of zeros.
- Return type:
- newton() None[source]¶
Computes the Newton polytope of the optimization problem.
The Newton polytope is the convex hull of all exponent vectors appearing in the objective function and constraints. This geometric object encodes the sparsity structure of the problem and can be exploited to construct more efficient relaxations.
Place in code structure: Geometric analysis method that should be called after problem setup. Its results (stored in newton_polytope and vertices) are used by in_newton(), convex_combination(), and potentially specialized relaxation strategies.
- Returns:
None
- Side effects:
Collects all exponent tuples from objective and constraints
Computes and stores the convex hull in self.newton_polytope
Extracts and stores sorted vertex list in self.vertices
Raises ValueError if polytope is degenerate (insufficient points or dimension mismatch)
- static omega(xprsn: SemigroupAlgebraElement, deg: int) list[tuple[float, Any]][source]¶
Extracts terms from a polynomial that don’t match a specific univariate degree pattern.
The omega function filters out univariate monomials of exactly the specified degree, keeping all multivariate terms, constant terms, and univariate terms of other degrees. This is used in conditional optimization where certain degree-specific terms need special treatment.
Place in code structure: Static helper method used by delta() to identify terms that require special handling in relaxation construction, particularly for conditional constraints and geometric programming.
- Parameters:
xprsn (SemigroupAlgebraElement) – The polynomial expression to filter.
deg (int) – The specific univariate degree to exclude.
- Returns:
- List of (coefficient, monomial) tuples
representing terms that don’t match the degree criterion.
- Return type:
- program_degree() int[source]¶
Computes the overall degree of the optimization problem.
This method determines the maximum degree among all polynomials (objective and constraints) in the problem, rounded up to the nearest even number. This degree is critical for determining the size of sum-of-squares (SOS) relaxations.
Place in code structure: Utility method used during relaxation construction to determine the appropriate degree for SOS decompositions and moment matrices.
- Returns:
- The maximum degree among all polynomials, adjusted to be even (adds 1 if odd).
This ensures compatibility with SOS relaxations which require even degrees.
- Return type:
- set_objective(obj: SemigroupAlgebraElement) None[source]¶
Sets the objective function for the optimization problem.
This method is central to defining the optimization problem. It assigns the objective function that will be minimized or maximized, and automatically updates the semigroup and computes the degree information needed for polynomial optimization.
Place in code structure: Core setup method that must be called before relaxation generation. Works with add_constraints() to fully specify the optimization problem.
- Parameters:
obj (SemigroupAlgebraElement) – A polynomial expression to be optimized, represented as an element in a semigroup algebra.
- Returns:
None
- Side effects:
Updates self.objective with the provided expression
Updates self.semigroup if different from current
Computes and stores objective_degree (total degree of the leading monomial)
Computes and stores objective_half_degree (ceiling of degree/2)
- static square_exponent(xpnt: Any) bool[source]¶
Determines if a monomial has only even exponents (is a perfect square).
This method checks whether all variables in a monomial appear with even powers, meaning the monomial can be expressed as a square of another monomial. This property is fundamental for identifying terms that are inherently non-negative and for constructing sum-of-squares decompositions.
Place in code structure: Static utility method used throughout analysis and relaxation construction. Called by analyse_program(), delta(), and other methods that need to identify square monomials for optimization techniques.
- Parameters:
xpnt (SemigroupAlgebraElement) – A monomial whose exponents are to be checked.
- Returns:
- True if all exponents in the monomial are even (divisible by 2),
False if any exponent is odd.
- Return type:
- to_sympy(expr: SemigroupAlgebraElement, sym_map: dict[str, Symbol])[source]¶
Converts a SemigroupAlgebraElement polynomial to a SymPy symbolic expression.
This method provides interoperability with the SymPy computer algebra system, enabling use of SymPy’s extensive symbolic manipulation capabilities (differentiation, integration, simplification, etc.) on polynomials defined in the semigroup algebra framework.
Place in code structure: Interface method for exporting to SymPy. Useful for visualization, symbolic analysis, or interfacing with other tools that expect SymPy expressions. Complements the internal semigroup algebra representation.
- Parameters:
expr (SemigroupAlgebraElement) – The polynomial expression to convert.
sym_map (dict) – Dictionary mapping generator name strings to SymPy Symbol objects, e.g., {‘x’: engine.Symbol(‘x’), ‘y’: engine.Symbol(‘y’)}.
- Returns:
- A SymPy expression algebraically equivalent to the input, using the
symbols provided in sym_map.
- Return type:
sympy.Expr
- tuple2mono(xpnt: Sequence[int])[source]¶
Converts a tuple of exponents back to a monomial in semigroup representation.
This method performs the inverse operation of mono2ord_tuple, constructing a symbolic monomial from numeric exponents. Each position in the input tuple corresponds to the power of the respective generator in the semigroup.
Place in code structure: Inverse conversion utility that works with mono2ord_tuple to enable round-trip conversions between symbolic and numeric representations. Used when translating geometric analysis results back to polynomial terms.
- Parameters:
xpnt – A sequence (tuple or list) of integers representing exponents for each generator in the semigroup, in the same order as semigroup.generators.
- Returns:
- The monomial product of generators raised to their
corresponding powers from xpnt.
- Return type:
A module for working with commutative semigroups and their differential algebras.
This module provides classes and functions for working with commutative semigroups and their differential algebras.
A semigroup is a set S together with an associative binary operation on S. A commutative semigroup is a semigroup in which the binary operation is commutative.
A semigroup algebra is a vector space over a field with a basis consisting of the elements of a semigroup equipped with multiplication compatible with the semigroup’s operation.
This module provides the following classes:
CommutativeSemigroup: A class representing a commutative semigroup.
AtomicSGElement: A class representing an atomic element of a semigroup algebra.
SemigroupAlgebraElement: A class representing an element of a semigroup algebra.
SemigroupAlgebra: A class representing a semigroup algebra.
This module also provides the following functions:
_degree: Computes the degree of a given expression.
diff: Computes the derivative of an expression in a semigroup algebra.
- class Irene.grouprings.AtomicSGElement(semigroup: CommutativeSemigroup, element: str)[source]¶
An atomic element of a semigroup algebra.
An atomic element is an element of the semigroup algebra that is not a sum of other elements.
- semigroup¶
The semigroup of the element.
- Type:
- LC() float[source]¶
Returns the leading coefficient of the element.
The leading coefficient of an element is the coefficient of the term with the highest degree.
- Returns:
The leading coefficient of the element.
- Return type:
- LM() Expr[source]¶
Returns the leading monomial of the element.
The leading monomial of an element is the monomial with the highest degree.
- Returns:
The leading monomial of the element.
- Return type:
sympy.Expr
- LT() SemigroupAlgebraElement[source]¶
Returns the leading term of the element.
The leading term of an element is the term with the highest degree.
- Returns:
The leading term of the element.
- Return type:
- divide(fs: list) tuple[list, SemigroupAlgebraElement][source]¶
Divides the element by a list of elements or expressions.
- lt_divisible_by(expr: Any) bool[source]¶
Checks if the leading term of the element is divisible by the leading term of another element or expression.
- Parameters:
expr (int, float, AtomicSGElement, SemigroupAlgebraElement) – The element or expression to check divisibility by.
- Returns:
True if the leading term of the element is divisible by the leading term of the other element or expression, False otherwise.
- Return type:
- class Irene.grouprings.CommutativeSemigroup(gens: list, is_semigroup: bool = True, is_abelian: bool = True)[source]¶
A class representing a commutative semigroup.
A semigroup is a set S together with an associative binary operation on S. A commutative semigroup is a semigroup in which the binary operation is commutative.
- add_relations(rels: list)[source]¶
Adds relations to the semigroup.
- Parameters:
rels (list) – The relations to add to the semigroup.
- degree(expr) int[source]¶
Computes the degree of an expression in the semigroup.
The degree of an expression is the sum of the absolute values of the exponents of its terms.
- Parameters:
expr – The expression whose degree is to be computed.
- Returns:
The degree of the expression.
- Return type:
- element_sub_lattice(elm: Expr, ex: set = None) set[source]¶
Computes the sublattice of the lattice of the semigroup generated by an element.
- lattice_edges(degree: int) None[source]¶
Computes the edges of the lattice of the semigroup.
- Parameters:
degree (int) – The degree of the lattice.
- class Irene.grouprings.SemigroupAlgebra(semigroup: CommutativeSemigroup)[source]¶
A semigroup algebra.
A semigroup algebra is a vector space over a field with a basis consisting of the elements of a semigroup.
- semigroup¶
The semigroup of the algebra.
- Type:
- derivatives¶
A list of dictionaries mapping the elements of the semigroup to their derivatives.
- Type:
- add_derivative(base_map: dict) None[source]¶
Adds a derivative to the algebra.
- Parameters:
base_map (dict) – A dictionary mapping the elements of the semigroup to their derivatives.
- derivative(expr: Any, idx: int)[source]¶
Computes the derivative of an expression in the algebra.
- Parameters:
expr (SemigroupAlgebraElement, AtomicSGElement, int, float) – The expression to differentiate.
idx (int) – The index of the derivative to use.
- Returns:
The derivative of the expression.
- Return type:
- diff(expr: Any, base_map: dict)[source]¶
Computes the derivative of an expression in the algebra.
- Parameters:
expr (SemigroupAlgebraElement, AtomicSGElement, int, float) – The expression to differentiate.
base_map (dict) – A dictionary mapping the elements of the semigroup to their derivatives.
- Returns:
The derivative of the expression.
- Return type:
- class Irene.grouprings.SemigroupAlgebraElement(terms: list, semigroup: CommutativeSemigroup)[source]¶
An element of a semigroup algebra.
A semigroup algebra is a vector space over a field with a basis consisting of the elements of a semigroup.
- semigroup¶
The semigroup of the element.
- Type:
- LC() float[source]¶
Returns the leading coefficient of the element.
The leading coefficient of an element is the coefficient of the term with the highest degree.
- Returns:
The leading coefficient of the element.
- Return type:
- LM() Expr[source]¶
Returns the leading monomial of the element.
The leading monomial of an element is the monomial with the highest degree.
- Returns:
The leading monomial of the element.
- Return type:
sympy.Expr
- LT() SemigroupAlgebraElement[source]¶
Returns the leading term of the element.
The leading term of an element is the term with the highest degree.
- Returns:
The leading term of the element.
- Return type:
- divide(fs: list) tuple[list, SemigroupAlgebraElement][source]¶
Divides the element by a list of elements or expressions.
- lt_divisible_by(expr: Any) bool[source]¶
Checks if the leading term of the element is divisible by the leading term of another element or expression.
- Parameters:
expr (int, float, AtomicSGElement, SemigroupAlgebraElement) – The element or expression to check divisibility by.
- Returns:
True if the leading term of the element is divisible by the leading term of the other element or expression, False otherwise.
- Return type:
This module provides a framework for polynomial optimization using the techniques introduced by Ghasemi, Lasserre, and Marshall, using Geometric Programming.
- class Irene.geometric.GPRelaxations(prog: OptimizationProblem, **kwargs)[source]¶
This class aims to provide a framework for polynomial optimization using the techniques introduced by Ghasemi, Lasserre, and Marshall, using Geometric Programming.
- auto_transform_matrix() ndarray[source]¶
Compute the automatic transformation matrix H.
- Returns:
The transformation matrix H.
- static compare_diags(vec: list[float]) tuple[int, list[float]][source]¶
Compare two vectors by the number of non-zero elements.
- Parameters:
vec – The first vector.
- Returns:
The number of non-zero elements in the vector.
- h_plus(xprsn: Any, idn: Any = None) float[source]¶
Compute the h_plus function for a given expression.
- Parameters:
xprsn – The expression to evaluate.
idn – The identity element of the semigroup.
- Returns:
The value of h_plus(xprsn).
- solve(**kwargs)¶
Form the geometric program relaxation.
- Returns:
The optimal value of the relaxation.
- class Irene.sonc.SONCRelaxations(prog: OptimizationProblem, **kwargs)[source]¶
Framework for constrained SONC relaxations formulated as geometric programs.
- solve(**kwargs)¶
Build and solve the constrained SONC geometric program.
SOS+SONC Relaxation Framework¶
Implements the SOS+SONC two-step optimization algorithms from Moritz Schick’s PhD thesis (Sums of squares plus sums of nonnegative circuit polynomials, Universität Konstanz), translated from MATLAB to Python and integrated into the Irene framework.
Classes¶
- SOSONCRelaxations
Combined SOS+SONC lower-bound computation for unconstrained polynomial optimization.
- SOSONCRelaxSol
Container for relaxation results (optimal value, certificates, timing, status).
- class Irene.sosonc.SOSONCRelaxSol[source]¶
Carries optimisation results for SOS+SONC relaxations.
- f_sos¶
SOS summand of
f - val(if applicable).- Type:
optional
- f_sonc¶
SONC summand of
f - val(if applicable).- Type:
optional
- class Irene.sosonc.SOSONCRelaxations(prog: OptimizationProblem, **kwargs)[source]¶
Combined SOS+SONC relaxation framework.
Implements the algorithms from Schick’s SOS+SONC toolbox:
globalMinSOS– pure SOS relaxation (SDP via Gram matrix)globalMinSONC– pure SONC relaxation (signomial GP)globalMinSOSPSONC– two-step SOS+SONC (Algorithms 4 & 5)
- Parameters:
prog (OptimizationProblem) – An Irene
OptimizationProblemwith an objective set viaprog.Minimize(f). Constraints are optional.error_bound (float) – Numerical zero tolerance (default
1e-10).verbosity (int) – Log level (0 = silent, 1 = verbose; default 1).
solver (str) – SDP solver name forwarded to
SDPRelaxations('cvxopt','csdp','sdpa','dsdp').use_local_solve (bool) – Use signomial GP local solve for the SONC portion (default
True).relaxation_order (int) – Relaxation order for SDP (default
1, i.e., the first Lasserre moment relaxation).
- globalMinSONC() SOSONCRelaxSol[source]¶
Compute a lower bound using the SONC relaxation.
Solves \(\sup\{\lambda : f - \lambda \in C\}\) via a signomial geometric program using Irene’s
SONCRelaxations.- Return type:
- globalMinSOS() SOSONCRelaxSol[source]¶
Compute a lower bound using the SOS relaxation.
Solves \(\sup\{\lambda : f - \lambda \in \Sigma\}\) via a Gram-matrix SDP using Irene’s
SDPRelaxations.- Return type:
- globalMinSOSPSONC(first: str = 'sos') SOSONCRelaxSol[source]¶
Two-step SOS+SONC lower bound (Algorithms 4 & 5).
- Parameters:
first (str) –
'sos'(Algorithm 4: SOS preprocess, then SONC) or'sonc'(Algorithm 5: SONC preprocess, then SOS).- Returns:
Lower bound \(f_{\\Sigma + C}^*\) together with decomposed certificate.
- Return type:
- Irene.sosonc.sosonc_bounds(prog: OptimizationProblem, **kwargs) dict[str, float][source]¶
Compute SOS, SONC, and SOS+SONC lower bounds.
Returns a dict with keys
'sos','sonc','sos_first','sonc_first'.
Border basis module for quotient algebra representations.
Border bases generalize Gröbner bases to zero-dimensional ideals and provide numerically stable bases for the quotient algebra K[x]/I. Unlike Gröbner bases, which depend on a monomial ordering and can be ill-conditioned, border bases work with any finite K-basis of the quotient space and maintain numerical stability through orthogonalization.
- Key references:
Traverso (1990), “A new algorithm for computing in algebraic extensions”
Greuel & Pfister (2002), “A Border Basis Algorithm”
Becker et al. (2005), “Border Bases and the Moment Problem”
- The border basis representation consists of:
A monomial basis B (standard monomials spanning K[x]/I)
The border partial B = {bcdotx_i : b in B, i=1..n} B
Multiplication tables: for each f in partial B, the representation of f mod I as a linear combination of elements in B
- class Irene.border_basis.BorderBasis(variables, generators, degree)[source]¶
Border basis for the quotient algebra K[x_{1},…,x_n]/I.
Given an ideal I generated by polynomials g_{1},…,g_m in K[x_{1},…,x_n], this class computes a border basis representation of the quotient algebra up to a specified degree bound. The border basis provides:
A monomial basis B for the quotient space (degree leqslant d)
The border partial B (monomials of degree d+1 reachable from B)
Multiplication tables expressing each border element as a linear combination of basis elements modulo I
- Parameters:
variables – List of symbolic variables [x_{1}, …, x_n].
generators – List of polynomials generating the ideal I.
degree – Maximum degree for the monomial basis.
- nvars¶
Number of variables.
- degree¶
Degree bound of the basis.
- basis¶
List of exponent tuples forming the monomial basis B.
- border¶
List of exponent tuples forming the border partial B.
- mult_tables¶
Dict mapping each border element to its coefficient vector over the basis (i.e., f equiv Sigma c_b cdot b^alpha mod I).
- conditioning_diagnostic()[source]¶
Compute numerical conditioning diagnostics for the border basis.
- Returns:
‘condition_number’: condition number of the multiplication table matrix ‘basis_conditioning’: condition number of the basis monomial evaluation matrix ‘is_well_conditioned’: boolean flag (True if cond < 1e10)
- Return type:
dict with keys
- moment_matrix_structure()[source]¶
Return the block structure of the moment matrix induced by the border basis.
The moment matrix
M_alphahas entriesM_{alpha,beta} = y_{alpha+beta}where the moment variables. The border basis partitions this into blocks based on which monomials appear in the basis vs the border.- Returns:
‘basis_size’: number of basis elements ‘border_size’: number of border elements ‘block_structure’: list of (row_start, row_end, col_start, col_end) tuples
- Return type:
dict with keys
Correlative sparsity detection for SDP relaxation decomposition.
Correlative sparsity exploits the fact that not all variables appear together in every polynomial constraint. By building a variable dependency graph where edges connect variables that co-occur in the same term, we can find connected components and decompose a large moment matrix into smaller independent blocks.
- Key references:
Hall & Sastry (2015), “Exploiting sparsity in polynomial optimization”
Kurzhanskiy et al. (2017), “Sparse semidefinite programming relaxations”
Louveaux et al. (2018), “Correlative and term-at-a-time sparsity”
The implementation uses a union-find data structure for efficient connected component detection, then returns the clique decomposition needed to partition moment matrices.
- class Irene.sparsity.CorrelativeSparsity(num_vars: int, var_names: List | None = None)[source]¶
Detect and exploit correlative sparsity in polynomial optimization problems.
Given an optimization problem with variables x_1, …, x_n and polynomials (objective + constraints), this class builds a variable dependency graph where an edge (i, j) exists if variables i and j appear together in some monomial term. The connected components of this graph define the correlative sparsity pattern.
- Parameters:
num_vars – Number of optimization variables.
var_names – Optional list of variable names/symbols for debugging.
- adjacency¶
Adjacency list representation of the dependency graph.
- components¶
Connected components as lists of variable indices.
- is_sparse¶
True if sparsity detected (more than one component).
- add_poly_terms(exponent_dict: Dict[Tuple[int, ...], object]) None[source]¶
Add edges from a polynomial’s term dictionary.
- Parameters:
exponent_dict – Mapping from exponent tuple -> coefficient (as returned by engine.Poly(…).as_dict()). Each key represents one monomial.
- add_term(var_indices: List[int]) None[source]¶
Add edges for a monomial term involving the given variables.
For a term like x_1^2 * x_3, var_indices would be [0, 2]. All pairs of co-occurring variables get connected.
- Parameters:
var_indices – Indices of variables that appear in this term.
- finalize() List[List[int]][source]¶
Compute connected components and return them sorted by size (descending).
- moment_matrix_partition(deg: int) Dict[int, List[Tuple[int, ...]]][source]¶
Partition the moment matrix basis by sparsity components.
For each connected component of variables, compute which exponent tuples belong exclusively to that component (i.e., only use variables from that component). This allows decomposing the large moment matrix into smaller independent blocks.
- Parameters:
deg – Maximum degree for moment basis generation.
- Returns:
Dict mapping component index -> list of exponent tuples belonging to that component’s moment block. Exponents that span multiple components are assigned to a ‘cross’ block (key=-1).
- reduction_factor(deg: int) float[source]¶
Estimate the moment matrix size reduction from sparsity.
Returns the ratio of total work with sparsity vs without. A value < 1 means sparsity helps. For a problem decomposed into k components of sizes n_1, …, n_k, the reduction is roughly:
sum_i (2*deg choose n_i) / (2*deg choose n)- Parameters:
deg – Relaxation degree.
- Returns:
Reduction factor (< 1 means improvement).
- class Irene.sparsity.UnionFind(n: int)[source]¶
Disjoint-set union-find with path compression and rank.
- Irene.sparsity.detect_sparsity_from_polys(polynomials, num_vars: int) CorrelativeSparsity[source]¶
Detect correlative sparsity from a list of polynomial expressions.
- Parameters:
polynomials – List of symbolic polynomial expressions.
num_vars – Number of variables in the problem.
- Returns:
Configured CorrelativeSparsity instance with finalized components.
- Irene.sparsity.detect_sparsity_from_problem(prog) CorrelativeSparsity[source]¶
Detect correlative sparsity from an OptimizationProblem instance.
Inspects the objective and constraints, extracts variable co-occurrence patterns from each polynomial’s term structure, and builds the dependency graph.
- Parameters:
prog – An OptimizationProblem with set_objective() and add_constraint() already called.
- Returns:
Configured CorrelativeSparsity instance with finalized components.
Newton polytope monomial pruning for moment matrix dimension reduction.
For a polynomial optimization problem, the Newton polytopes of the objective
and constraints identify exponent candidates that are potentially relevant:
an exponent outside 2\cdotNewt(f) can never occur as a term of g*h with
supp(g), supp(h) inside the Minkowski-sum support, so it is never needed in
the objective coefficient vector. Filtering on this hull reduces the moment
matrix size – sometimes by orders of magnitude for sparse problems.
Safety contract: hull membership alone is not a certificate that an exponent
may be removed from the moment/Gram basis of a Lasserre SDP. Removing exponents
drops PSD coupling entries and can introduce recession directions (or force
invalid objective values) even when every objective-support exponent is kept;
the Motzkin polynomial at order 3 is such a counterexample (the pruned SDP has
an unbounded rank-one recession ray while the full one is bounded). Until a
complete SOS-support certificate exists, callers must pass required_support
with the exponents that must be retained regardless of hull membership; the
certified safe choice at present is the full degree-bounded support.
- Key references:
Parrilo (2000), “Structured Semidefinite Programs and Semialgebraic Geometry”
Lasserre (2006), “Moments, Positive Polynomials and Their Applications”
Kim & Kojima (2014), “Sparse SOS decompositions via Newton polytopes”
The implementation computes the Minkowski sum of scaled Newton polytopes,
then filters the full monomial basis to those inside the hull, always retaining
required_support.
- class Irene.newton_polytope.NewtonPruner(num_vars: int, max_degree: int, polytope_vertices: ndarray | None = None, required_support: Set[Tuple[int, ...]] | None = None)[source]¶
Filter monomial basis using Newton polytope pruning.
Given the combined Newton polytope of an optimization problem’s polynomials, this class filters the full monomial basis to those exponent vectors that lie within the convex hull of
2\cdotNewt(f), always retaining every exponent inrequired_support(see module docstring for why hull membership alone is not a removal certificate).- Parameters:
num_vars – Number of variables in the problem.
max_degree – Maximum degree for moment matrix construction.
polytope_vertices – Precomputed vertices of 2cdotcombined Newton polytope. If None, will be computed from polynomials later.
required_support – Exponent tuples that must appear in the returned basis regardless of hull membership (degree-bounded to
max_degree). Pass the full degree-bounded support until a complete SOS-support certificate is available; pass a smaller certified set once one exists.
- full_basis_size¶
Size of unpruned monomial basis.
- pruned_basis_size¶
Size after Newton polytope filtering (plus required support).
- reduction_ratio¶
Fraction of basis retained (lower = more pruning).
- compute_pruned_basis(vars_list=None)[source]¶
Compute the pruned monomial basis.
Iterates over all monomials up to
max_degree, filters those outside the Newton polytope, and then retains every exponent ofrequired_support(degree-bounded) regardless of hull membership.- Parameters:
vars_list – Optional variable list (for compatibility).
- Returns:
List of exponent tuples forming the pruned basis; always a superset of
{e in required_support : sum(e) <= max_degree}.
- moment_matrix_dimension_reduction() Dict[source]¶
Estimate the moment matrix size reduction from Newton pruning.
The moment matrix has dimension RtimesR where R is the basis size. Pruning reduces this to R’timesR’, so the reduction factor is (R’/R)^2.
- Returns:
Dict with full_size, pruned_size, matrix_reduction, and savings.
- Irene.newton_polytope.combined_newton_polytope(polynomials, vars_list=None)[source]¶
Compute the Minkowski sum of Newton polytopes of multiple polynomials.
For moment matrix construction, we need 2cdot(Newt(f_0) oplus Newt(g_1) oplus …), where f_0 is the objective and g_i are constraint polynomials.
- Parameters:
polynomials – List of symbolic polynomial expressions.
vars_list – Shared variable list for consistent exponent ordering.
- Returns:
Combined Newton polytope vertices (deduplicated).
- Return type:
np.ndarray
- Irene.newton_polytope.minkowski_sum(polytope_a, polytope_b)[source]¶
Compute the Minkowski sum of two point sets.
A oplus B = {a + b | a in A, b in B}
- Parameters:
polytope_a – Arrays of shape (n, d) and (m, d).
polytope_b – Arrays of shape (n, d) and (m, d).
- Returns:
All pairwise sums, shape (n*m, d). Deduplicated.
- Return type:
np.ndarray
- Irene.newton_polytope.newton_polytope(expr, vars_list=None)[source]¶
Compute the Newton polytope of a polynomial expression.
The Newton polytope is the convex hull of exponent vectors of all terms with nonzero coefficients in the polynomial.
- Parameters:
expr – A symbolic polynomial expression (SymPy or SymEngine), a scalar, or a SemigroupAlgebra element (converted to SymPy automatically).
vars_list – List of variables to extract exponents for. If None, inferred.
- Returns:
Array of shape (num_terms, num_vars) of exponent vectors.
- Return type:
np.ndarray
- Raises:
ValueError – If the input cannot be parsed as a polynomial. This function never returns a silently degraded (origin-only) polytope; unparseable input is an explicit error instead.
- Irene.newton_polytope.prune_basis_from_polys(polynomials, num_vars: int, max_degree: int, required_support: Set[Tuple[int, ...]] | None = None) NewtonPruner[source]¶
Convenience function: compute pruned basis from a list of polynomials.
- Parameters:
polynomials – List of symbolic polynomial expressions (objective + constraints). SymPy expressions, scalars, and SemigroupAlgebra elements are all accepted; ring elements are converted to SymPy automatically (see
newton_polytope()).num_vars – Number of variables in the problem.
max_degree – Maximum degree for moment matrix construction (usually 2*d).
required_support – Exponents that must be retained regardless of hull membership (see
NewtonPruner). DefaultNonekeeps only hull-interior exponents – callers building relaxation bases should pass the certified safe set.
- Returns:
Configured NewtonPruner with pruned basis computed.
- Raises:
ValueError – If any polynomial cannot be parsed (no silent fallback).
- Irene.newton_polytope.prune_basis_from_problem(prog, max_degree: int, required_support: Set[Tuple[int, ...]] | None = None) NewtonPruner[source]¶
Convenience function: compute pruned basis from an OptimizationProblem.
The objective and constraint polynomials may be SymPy expressions or SemigroupAlgebra elements; ring elements are converted to SymPy automatically (see
newton_polytope()), so problems built via Irene’s documented construction path work directly.- Parameters:
prog – An OptimizationProblem with set_objective() and add_constraint().
max_degree – Maximum degree for moment matrix construction.
required_support – Exponents that must be retained regardless of hull membership (see
NewtonPruner). DefaultNonekeeps only hull-interior exponents – callers building relaxation bases should pass the certified safe set.
- Returns:
Configured NewtonPruner with pruned basis computed.
- Raises:
ValueError – If any polynomial cannot be parsed (no silent fallback).
- Irene.newton_polytope.scale_polytope(polytope, factor)[source]¶
Scale all exponent vectors by an integer factor.
Unified Relaxation API¶
A single entry point for all relaxation methods (SOS, SONC, SOS+SONC).
Design goals¶
One constructor –
RelaxationEngine(prog)wraps anyOptimizationProblem.Consistent return type – every solve call returns a
RelaxResultwith the same attributes (value, status, timing, solver metadata).Method dispatch – the user picks
'sos','sonc', or'sosonc'; the engine routes to the correct backend class internally.Backward compatibility – the old classes (
SDPRelaxations, etc.) still work; this module is additive, not destructive.
Usage¶
>>> from Irene.program import OptimizationProblem
>>> from Irene.relaxation_api import RelaxationEngine, RelaxResult
>>> engine = RelaxationEngine(prog)
>>> result: RelaxResult = engine.solve(method='sos', order=2, solver='cvxopt')
>>> print(result.value) # lower bound
>>> print(result.status) # 'optimal' | 'infeasible' | 'error'
For a full comparison across all methods in one call:
>>> results = engine.compare(order=1)
>>> for m, r in results.items():
... print(f"{m}: {r.value:.6f}")
- class Irene.relaxation_api.RelaxResult(value: float = -inf, method: str = '', status: str = 'error', error_code: int = 2, runtime: float = 0.0, init_time: float | None = None, message: str = '', certificate: Any = None, solver_info: dict = <factory>)[source]¶
Uniform result container for all relaxation methods.
- certificate¶
SOS/SONC polynomial certificate if the backend exposes one.
- Type:
Optional[Any]
- class Irene.relaxation_api.RelaxationEngine(prog: OptimizationProblem, order: int = 1, solver: str = 'cvxopt', error_bound: float = 1e-10, verbosity: int = 1, use_local_solve: bool = True, config=None)[source]¶
Single entry point for SOS, SONC, and combined relaxations.
- Parameters:
prog (OptimizationProblem) – An Irene optimization problem with an objective set via
prog.Minimize(f)orprog.set_objective(f).order (int) – Relaxation/hierarchy order (default 1).
solver (str) – SDP solver name forwarded to the SOS backend (
'cvxopt','csdp','sdpa','dsdp').error_bound (float) – Numerical zero tolerance for SONC GP.
verbosity (int) – Log level: 0 = silent, 1 = normal, 2+ = verbose.
use_local_solve (bool) – Use signomial GP local solver for the SONC portion.
config (RelaxationConfig, optional) – Phase 3 reduction pipeline configuration (Newton polytope pruning, border basis, correlative sparsity). Defaults to no reduction.
Examples
>>> engine = RelaxationEngine(prog, order=2, solver='cvxopt') >>> res = engine.solve('sos') >>> print(res.value)
Compare all methods at once:
>>> results = engine.compare() >>> best_method = max(results, key=lambda m: results[m].value)
- compare(order: int | None = None, solver: str | None = None) dict[str, RelaxResult][source]¶
Run all four relaxation variants and return results keyed by method.
Parameters are the same as
solve(). Returns a dict mapping method name ->RelaxResult.
- solve(method: Literal['sos', 'sonc', 'sosonc_sos_first', 'sosonc_sonc_first'] | RelaxMethod = 'sos', order: int | None = None, solver: str | None = None) RelaxResult[source]¶
Run a single relaxation and return a
RelaxResult.- Parameters:
method (str or RelaxMethod) –
Which relaxation to use. Accepted values:
'sos' -- pure SOS (Gram-matrix SDP) 'sonc' -- pure SONC (signomial GP) 'sosonc_sos_first' -- two-step: SOS -> SONC residual 'sosonc_sonc_first' -- two-step: SONC -> SOS residual
order (int, optional) – Override the hierarchy order for this call.
solver (str, optional) – Override the SDP solver name for this call.
- Return type:
- Irene.relaxation_api.compare_all(prog: OptimizationProblem, **kwargs: Any) dict[str, RelaxResult][source]¶
Run all four relaxation variants and return results keyed by method.
Convenience wrapper around
RelaxationEngine.compare().
- Irene.relaxation_api.relax(prog: OptimizationProblem, method: Literal['sos', 'sonc', 'sosonc_sos_first', 'sosonc_sonc_first'] | RelaxMethod = 'sos', **kwargs: Any) RelaxResult[source]¶
Quick one-liner for solving a relaxation.
- Parameters:
prog (OptimizationProblem) – The optimization problem to relax.
method (str or RelaxMethod) – Which relaxation backend to use.
**kwargs – Passed through to
RelaxationEngineconstructor (order,solver,error_bound,verbosity, etc.).
- Return type:
Examples
>>> from Irene.relaxation_api import relax >>> res = relax(prog, method='sos', order=2) >>> print(res.value)
Sparse moment method for real roots of sparse polynomial systems.
Implements the algorithm of Baumbach & Bender, “The Moment Method for Computing Real Points of Sparse Polynomial Systems” (arXiv:2609.33313): polynomial systems solved on the semigroup ring R[A] = R[x^{alpha_1}, …, x^{alpha_r}] by exploiting the toric ideal T_A to keep moment matrices small, with a termination guarantee via sparse flat-extension rank conditions (Theorem 3.27 of the paper).
This module currently provides S51.0 – the semigroup-ring setup:
ToricSetup– exponent set A, ambient dimension, toric generatorstoric_ideal(A)– a Groebner basis G_A of T_A = ker(psi_A) in R[z]rho_A– max total degree of the generators (0 if T_A < 0>)deg_A(f, A)– the A-graduation: min{s : f in R[A]^s}
LATER SUBTASKS (Vikunja #51): S51.2 Theorem 3.27 rank conditions and termination loop, S51.3 sparse border basis, S51.4 sparse Stickelberger eigenvalue recovery, S51.5 Algorithm 2 (randomized single root).
S51.1 provides: semigroup_level_map, moment_indices (R[A]^t enumeration),
prolongations (H_t, eq. (9)) and SparseMomentSDP – the K_t spectrahedron
of eq. (10) as a standard-form SDP on CvxpySDPSolver.
NOTATION (paper sections referenced)¶
A = {alpha_1, …, alpha_r} subset N^m finite set of exponents R[A]^s = < x^{sum_{i<=s} alpha_i} > s-truncation (Def 2.4) psi_A : R[z] -> R[x], z_i |-> x^{alpha_i} the semigroup map (1) T_A := ker(psi_A), G_A a generating set, rho_A := max{deg(g) : g in G_A}, rho_A = 0 if T_A < 0> (3)
- class Irene.sparse_moment.Algorithm1Result(converged: bool = False, no_real_roots: bool = False, t: int = 0, iterations: int = 0, rank_test: RankTestResult | None = None, kernel_polys: List[Expr] = <factory>, quotient_basis: Tuple[int, ...]]=<factory>, lambda_vec: ndarray | None = None, moment_matrix: ndarray | None = None, infeasible_at_t: int | None = None)[source]¶
Outcome of the Algorithm-1 termination loop (paper, end of Section 3.4).
- converged¶
V_{R[A]}(I) is empty – a Stengle certificate), or when
max_iterationswas exceeded without rank stabilization.- Type:
False when K_t was infeasible at some t (Lemma 3.29(i): then
- no_real_roots¶
- Type:
True iff the loop stopped on an infeasible K_t.
- t¶
- Type:
truncation degree at which the loop stopped.
- iterations¶
- Type:
number of K_t SDPs solved (t increments by 1 each iteration).
- rank_test¶
- Type:
final RankTestResult (None when not converged).
- kernel_polys¶
ker(M_{s_star}(Lambda)) – a generating set for J = <ker M_s(Lambda)>. When converged and Lambda generic, J is exactly the real radical. Variable names follow the
deg_Aconvention (sorted free symbols of the input system). Coefficients are snapped to 0/integers when close.- Type:
sympy expressions p = sum v_i x^{beta_i} spanning
- quotient_basis¶
M_{s_star - 1}(Lambda); by Corollary 3.19 their residue classes form a basis of R[A]/J (Remark 3.28: the greedy-in-order choice gives a connected-to-one border basis). len(quotient_basis) = n_real when converged and Lambda generic.
- Type:
exponent tuples indexing a monomial column basis B of
- lambda_vec, moment_matrix
(diagnostics; None until convergence).
- Type:
the optimizer and its flat matrix M_{s_star}
- infeasible_at_t¶
- Type:
t at which K_t was reported empty (None otherwise).
Example
>>> import sympy as sp >>> x = sp.Symbol('x') >>> r = solve_algorithm1([x**3 - x], A=[(1,)]) >>> (r.converged, r.t, sorted(str(p) for p in r.kernel_polys)) (True, 6, ['x**3 - x'])
Notes
The constant-objective SDP returns a generic element of K_t with interior-point solvers (Lemma 3.23 / eq. (11): all relint points share the same kernel space N_t); first-order solvers may land on the boundary, in which case pass
solver='CLARABEL'explicitly.
- class Irene.sparse_moment.RankTestResult(converged: bool = False, condition: str | None = None, s_star: int | None = None, D: int = 0, d: int = 1, rho_A: int = 0, ranks: Dict[int, int]=<factory>, n_real: int | None = None, t: int = 0, tol: float = 1e-06)[source]¶
Outcome of the Theorem 3.27 convergence test at one truncation t.
- converged¶
- Type:
True iff condition (i) or (ii) holds for some admissible s.
- condition¶
cases carry different proof obligations in Thm 3.27, so the distinction is kept even though both imply a flat extension at level s.
- Type:
‘flat’ (case i), ‘interpolation’ (case ii), or None. The two
- s_star¶
- Type:
smallest admissible s at which convergence was detected.
- D¶
- Type:
max_i deg_A(f_i) (0 when I < 0>); d = max(1, ceil(D/2)); rho_A from T_A.
- ranks¶
- Type:
{k: rank(M_k(Lambda))} for all 0 <= k <= floor(t/2).
- n_real¶
converged and Lambda generic (Lemma 3.14 / Thm 3.27).
- Type:
rank(M_{s_star}(Lambda)) – the number of real toric roots when
- t, tol
- Type:
truncation degree and eigenvalue threshold used.
Example
>>> import sympy as sp >>> x = sp.Symbol('x') >>> sdp = SparseMomentSDP([x**3 - x], [(1,)], 6) >>> res = sdp.solve() >>> rt = test_theorem_327(res.lambda_vec, [x**3 - x], [(1,)], 6, ... sdp.index, sdp.levels, sdp.monoms_t) >>> (rt.converged, rt.condition, rt.s_star, rt.n_real) (True, 'flat', 3, 3)
- class Irene.sparse_moment.SparseBorderBasis(lam_vec, basis: Sequence[Sequence[int]], A, t: int, s_star: int, monoms: List[Tuple[int, ...]], index: Dict[Tuple[int, ...], int], levels: dict, tol: float = 1e-06)[source]¶
Sparse border basis B of the quotient algebra \(R[A]/J\), J = \(\langle \ker M_{s^{*}}(\Lambda)\rangle\), built from the moment data of a converged Algorithm-1 run (Theorem 3.27 + Corollary 3.19 / Remark 3.28).
B is taken to be the quotient basis of the
Algorithm1Result– the greedy-in-deg_A-order column basis of \(M_{s^{*}-1}(\Lambda)\) – which Remark 3.28 guarantees connected-to-one (Def A.2); this class verifies that property by BFS rather than assuming it.For every exponent e with \(\deg_A(e) \le s^{*}\) the normal form \([x^e] = \sum_j d_j b_j\) (i.e. \(x^e - \sum_j d_j b_j \in J\)) is recovered from the moment equalities of flat extension: under the rank condition, Lambda admits a representing measure with n_real atoms on V_{R[A]}(J), hence for all u with \(\deg_A(u) + \deg_A(e) \le t\)
Lambda(x^{u+e}) = sum_j d_j Lambda(x^{u+b_j}),
an exactly consistent linear system solved in least squares (residuals are exposed for diagnostics). The multiplication table of each semigroup generator x^{a_i} is then the matrix whose k-th column is [x^{a_i} b_k] in B; these tables are self-adjoint on V, commute, and respect every toric relation (Def A.3) – verified numerically by
check_relations()(Appendix A.1 normal-form criterion).- Parameters:
lam_vec (moment vector Lambda(x^alpha) over R[A]^t (position-ordered), t >= 2*s_star.)
basis (exponent tuples of B, with basis[0] == (0,...,0); normally) –
Algorithm1Result.quotient_basis.A (exponent set (sequence or ToricSetup).)
t (truncation degree; levels must cover R[A]^{s_star}.)
s_star (level at which flat extension was detected.)
monoms (basis data from
moment_indices(A, t).)index (basis data from
moment_indices(A, t).)levels (basis data from
moment_indices(A, t).)tol (least-squares / residual threshold (default 1e-6).)
- basis, r_
- Type:
the border basis and its cardinality (= n_real on convergence).
- nf_residuals[e]¶
- Type:
lstsq residual of the moment system for e (0 on exact flatness).
- connected_to_one¶
- Type:
Def A.2 flag, verified by BFS from 1 inside B.
Example
>>> import sympy as sp >>> x = sp.Symbol('x') >>> r = solve_algorithm1([x**3 - x], A=[(1,)]) >>> monoms, index, levels = moment_indices([(1,)], r.t) >>> bb = SparseBorderBasis(r.lambda_vec, r.quotient_basis, [(1,)], r.t, ... r.rank_test.s_star, monoms, index, levels) >>> (bb.r_, tuple(bb.basis), bb.connected_to_one) (3, ((0,), (1,), (2,)), True)
Notes
Semigroup-aware twin of
Irene.border_basis.BorderBasis(dense ring): here the extra constraint is Def A.3 – every g in G_A must annihilate V under M(g), whichcheck_relationstests.- check_relations() float[source]¶
Max over g in G_A of \(\|g(M_1,\ldots,M_r)\|_2\) – the Def A.3 / Appendix A.1 compatibility residual (0 when every toric relation holds on V).
Example
>>> import sympy as sp >>> x = sp.Symbol('x') >>> r = solve_algorithm1([x**4 - 5*x**2 + 4], A=[(2, 0), (3, 0)]) >>> monoms, index, levels = moment_indices([(2, 0), (3, 0)], r.t) >>> bb = SparseBorderBasis(r.lambda_vec, r.quotient_basis, [(2, 0), (3, 0)], ... r.t, r.rank_test.s_star, monoms, index, levels) >>> bool(bb.check_relations() < 1e-6) # z1^3 = z2^2 holds on V True
- class Irene.sparse_moment.SparseMomentResult(status: str, lambda_vec: ndarray | None = None, M_s: ndarray | None = None, rank_Ms: int | None = None, rank_Ms_minus_1: int | None = None, n_monomials_t: int = 0, n_monomials_s: int = 0, h_count: int = 0, objective_value: float | None = None, wall_time: float = 0.0, solver_info: dict = <factory>)[source]¶
Structured output of
SparseMomentSDP.solve.- status¶
Infeasible means K_t = empty, hence by Lemma 3.29(i) the system has no real toric solution (1 is an SOS modulo I – a Stengle certificate).
- Type:
‘Optimal’ | ‘Infeasible’ | … (solver verdict).
- M_s¶
- Type:
the sparse truncated moment matrix M_{floor(t/2)}(Lambda).
- rank_Ms, rank_Ms_minus_1
submatrix on R[A]^{s-1} – the flat-extension pair (Theorem 3.27).
- Type:
ranks of M_s and its top-left principal
- n_monomials_s¶
benchmark vs the dense monomial count binom(n+s-1, s)).
- Type:
|R[A]_{floor(t/2)}|, moment-matrix dimension (the sparsity
- h_count¶
- Type:
number of prolongation constraints in H_t after deduplication.
- objective_value¶
- Type:
min c^T Lambda over K_t (constant 1 for Algorithm 1).
- wall_time¶
- Type:
seconds spent inside CvxpySDPSolver.solve().
- solver_info¶
- Type:
the legacy
Infodict from CvxpySDPSolver.
- class Irene.sparse_moment.SparseMomentSDP(f_system: Sequence[Basic], A: Sequence[Sequence[int]], t: int, objective: str | Sequence[float] = 'constant', solver=None)[source]¶
The K_t spectrahedron of eq. (10), built on
CvxpySDPSolver.\[K_t = \{ \Lambda \in R[A]^*_t : \Lambda(1)=1,\; M_{\lfloor t/2 \rfloor}(\Lambda) \succeq 0, \; \Lambda(f)=0 \;\forall f \in H_t \}.\]One SDP variable per monomial of R[A]_t (enumerated by A-degree, not total degree – this is exactly where the sparsity pays off); one PSD block for M_{floor(t/2)}; affine equalities for normalization and prolongations.
- Parameters:
f_system (generators f_i of I in R[A].)
A (exponent set, or a
ToricSetup.)t (truncation degree >= max_i deg_A(f_i).)
objective ('constant' (Algorithm 1: min Lambda(1) -- feasibility probe)) – or an array-like c over R[A]_t (one entry per monomial position, as in
moment_indices); a random Gaussian choice realizes Algorithm 2.solver (SDP backend name passed to CvxpySDPSolver.)
Example
>>> import sympy as sp >>> x = sp.Symbol('x') >>> sdp = SparseMomentSDP([x*(x-1)*(x+1)], [(1,)], 4) # I < x^3-x > >>> res = sdp.solve() >>> bool(abs(res.lambda_vec[sdp.index[(0,)]] - 1.0) < 1e-6) # Lambda(1) = 1 True
- solve() SparseMomentResult[source]¶
Solve min b^T Lambda over K_t and return structured moment data.
- class Irene.sparse_moment.SparseRootsResult(roots: Dict[str, float]]=<factory>, bwe: List[float] = <factory>, bwe_components: List[List[float]] = <factory>, eigenvalues: List[float] = <factory>, coefficients: Tuple[int, ...] | None=None, trials: int = 0, kernel_polys: List[Expr] = <factory>, connected_to_one: bool = False)[source]¶
Output of the sparse Stickelberger eigenvalue method (Appendix A.2).
- roots¶
z_i = x^{a_i} the semigroup generators (values m^{a_i}).
- Type:
one dict per real toric root, {‘z1’: v1, …, ‘z_r’: vr} with
- bwe¶
(sum_alpha |c_{alpha,f} Lambda_m(x^alpha)| + 1). The paper reports log10(BWE) in [-7, -3] for its random systems.
- Type:
backward error per root, eq. (12): (1/m) sum_i |Lambda_m(f_i)| /
- bwe_components¶
- Type:
per-root list of the m summands above (diagnostics).
- eigenvalues¶
Stickelberger functional f = c_1 x^{a_1} + … + c_r x^{a_r}.
- Type:
the r_ distinct real values Lambda_m(f) of the successful
- coefficients¶
- Type:
integer coefficient vector c of that functional.
- trials¶
- Type:
number of random functionals tried (genericity, Theorem A.4).
- kernel_polys¶
- Type:
generators of J = <ker M_{s_star}(Lambda)> (Algorithm 1 step 5).
- connected_to_one¶
- Type:
Def A.2 flag from the border basis used.
Example
>>> import sympy as sp >>> x = sp.Symbol('x') >>> r = solve_algorithm1([x**3 - x], A=[(1,)]) >>> out = recover_all_sparse_roots(r, [(1,)], [x**3 - x]) >>> sorted(round(v['z1'], 6) for v in out.roots) [-1.0, 0.0, 1.0]
- class Irene.sparse_moment.ToricSetup(A: Tuple[Tuple[int, ...], ...], r: int, z: Tuple[Symbol, ...], G_A: Tuple[Expr, ...], rho_A: int)[source]¶
Semigroup-ring data for the sparse moment method.
- rho_A¶
- Type:
max total degree over G_A, or 0 when T_A = <0> (paper eq. 3)
- Irene.sparse_moment.deg_A(f: Expr, A: Sequence[Sequence[int]]) int[source]¶
A-graduation of f in R[A] (paper Section 2):
deg_A(f) = min{ s in N : f in R[A]^s },
where R[A]^s is spanned by the monomials x^{alpha_{i_1} + … + alpha_{i_s}} with at most s summands. Subadditive: deg_A(fg) <= deg_A(f)+deg_A(g), deg_A(f+g) <= max{deg_A(f), deg_A(g)}.
- Parameters:
f (SymPy polynomial (or 0); its free symbols are taken as the ambient) – variables x_1..x_m in sorted-name order, so len(free_symbols) must equal the ambient dimension of A. All monomials must lie in R[A].
A (exponent set; may also be a
ToricSetup.)
- Raises:
ValueError if f contains monomials outside R[A] or its number of free –
symbols does not match len(A[0]). –
Example
>>> import sympy as sp >>> x = sp.Symbol('x') >>> deg_A(x**7, [(2, 0), (3, 0)]) # x^7 in R[x^2, x^3] 3
- Irene.sparse_moment.moment_indices(A: Sequence[Sequence[int]], t: int)[source]¶
Enumerate the truncated ring \(R[A]^t\).
Returns
(monoms, index, levels)wheremonomsis the sorted list of exponent tuples in R[A]^t (by A-degree, then lexicographic),indexmaps each exponent to its position in that list, andlevelsgivesdeg_A(x^beta)for every enumerated beta. The length ofmonomsis the number of SDP variables in K_t; the sub-list with level <= floor(t/2) indexes the rows/columns of the moment matrix M_{floor(t/2)}.Example
>>> from Irene.sparse_moment import moment_indices >>> monoms, index, levels = moment_indices([(1,)], 4) # R[x], t = 4 >>> len(monoms), index[(0,)] (5, 0)
- Irene.sparse_moment.prolongations(f_system: Sequence[Basic], A: Sequence[Sequence[int]], t: int, index: Dict[Tuple[int, ...], int])[source]¶
The set \(H_t\) of eq. (9): all products
x^beta f_iwithdeg_A(x^beta) <= t - deg_A(f_i), expressed in the moment basis.Returns one dict per distinct polynomial of H_t, each mapping monomial positions (in
index) to float coefficients – i.e. the row vector of the linear constraint \(\Lambda(h) = 0\) over R[A]_t.- Parameters:
f_system (polynomials f_i in R[A] (sympy expressions).)
A (exponent set, or a
ToricSetup.)t (truncation degree; must be >= deg_A(f_i) for every i.)
index (monomial -> position map from
moment_indices(A, t).)
- Raises:
ValueError if some f_i is not in R[A] or has A-degree > t. –
Example
>>> import sympy as sp >>> x = sp.Symbol('x') >>> monoms, index, levels = moment_indices([(1,)], 3) >>> H = prolongations([x**2 - 1], [(1,)], 3, index) # {x^2-1, x^3-x} >>> sorted(H[0].items()), sorted(H[1].items()) ([(0, -1.0), (2, 1.0)], [(1, -1.0), (3, 1.0)])
- Irene.sparse_moment.recover_all_sparse_roots(result: Algorithm1Result, A, f_system: Sequence | None = None, *, seed: int = 2026, max_trials: int = 50, tol: float = 1e-08) SparseRootsResult[source]¶
Recover all points of \(V_{R[A]}(I)\) from a converged Algorithm-1 run.
Implements the sparse Stickelberger eigenvalue method (paper Appendix A.2, Theorem A.4): pick random integer coefficients c = (c_1,…,c_r), form the multiplication matrix of \(f = \sum_i c_i x^{a_i}\) on the border basis B, take its left eigenvectors w normalized by their 1-coordinate (eq. 14: \(w \propto (\Lambda_m(x^{b_1}),\ldots,\Lambda_m(x^{b_r}))\)), and read off each generator value – directly from the W-row when \(x^{a_i} \in B\), else via the normal form of x^{a_i} (eq. 15). A trial is generic iff it yields exactly r_ distinct real eigenvalues; random integer coefficients are distinct w.p. 1, so a single retry suffices with overwhelming probability.
- Parameters:
result (CONVERGED
Algorithm1Result(lambda_vec and quotient_basis set).)A (the exponent set used for the run ((sequence of tuples) or ToricSetup);) – must match what produced
result.f_system (generators of I, used only for the BWE diagnostic (eq. 12);) – defaults to [] (BWE = 0).
:param Returns a
SparseRootsResult.:
- Irene.sparse_moment.semigroup_level_map(A: Sequence[Sequence[int]], max_level: int) dict[source]¶
Minimal summand count for every exponent reachable within
max_level.Returns the map \(\beta \mapsto d_A(\beta)\) for all \(\beta \in \bigcup_{s \le max\_level} A^s\), where \(d_A(x^\beta) = min\{ s : x^\beta \in R[A]^s \}\) is the minimal number of summands of \(A\) adding up to \(\beta\). BFS over the exponent lattice with steps in
A; exponents whose total degree already exceeds \(max\_level \cdot max|a_i|\) are pruned (all relevant paths stay below that bound).- Parameters:
A (sequence of exponent vectors in N^m, or a
ToricSetup.)max_level (int >= 0; the largest A-degree to enumerate.)
- Irene.sparse_moment.solve_algorithm1(f_system: Sequence[Basic], A: Sequence[Sequence[int]] | None = None, t0: int | None = None, tol: float = 1e-06, max_iterations: int = 8, solver=None) Algorithm1Result[source]¶
Algorithm 1 (all real roots): the K_t SDP + Theorem 3.27 termination loop.
Solves
min Lambda(1)over \(K_t\) (eq. (10)) at truncation t, tests the rank conditions of Theorem 3.27, and on failure increments \(t \leftarrow t + 1\) and re-solves (paper step 4). Stopping cases:K_t infeasible -> by Lemma 3.29(i) there is no real toric solution;
rank stabilization at some admissible s -> J = <ker M_s(Lambda)> is the real radical for generic Lambda (Thm 3.27);
max_iterationsexceeded -> RuntimeError with the last rank profile.
- Parameters:
f_system (generators of I, each in R[A] (sympy expressions).)
A (exponent set; optional only for single-variable systems, where it is) – inferred as [(1,)] from the free symbols.
t0 (starting truncation degree; defaults to
2*max{D, rho_A}per) – Algorithm 1 step 1 (with a floor of max(4, D) so K_t contains H_t).tol (eigenvalue threshold for numerical ranks (paper practice: 1e-3..1e-7).)
max_iterations (guard against Lemma 3.29's "sufficiently large t".)
solver (SDP backend name passed to
CvxpySDPSolver; interior-point) – methods are preferred so the optimizer lies in relint(K_t) (Lemma 3.23).
:param Returns an
Algorithm1Result.:Example
>>> import sympy as sp >>> x = sp.Symbol('x') >>> r = solve_algorithm1([x**3 - x], A=[(1,)]) >>> (r.converged, r.t, sorted(str(p) for p in r.kernel_polys)) (True, 6, ['x**3 - x'])
>>> import sympy as sp >>> x = sp.Symbol('x') >>> r = solve_algorithm1([x**2 + 1], A=[(1,)]) >>> (r.converged, r.no_real_roots) (False, True)
- Irene.sparse_moment.solve_sparse_real_roots(f_system: Sequence[Basic], A: Sequence[Sequence[int]] | None = None, t0: int | None = None, tol: float = 1e-06, max_iterations: int = 8, seed: int = 2026, solver=None) SparseRootsResult[source]¶
Top-level pipeline: Algorithm 1 (S51.2) + sparse border basis (S51.3) + Stickelberger recovery (S51.4).
Returns a
SparseRootsResultwith one dict per real toric root of the system in the semigroup generators z_i = x^{a_i}, backward-error diagnostics (eq. 12), and the J-generators from ker M_{s_star}. When K_t is infeasible (Lemma 3.29(i): no real toric solution) an empty result is returned withno_real_rootsrecorded on it viaroots == []and a non-empty kernel list left untouched.Example
>>> import sympy as sp >>> x = sp.Symbol('x') >>> out = solve_sparse_real_roots([x*(x-1)*(x+1)], A=[(1,)]) >>> sorted(round(v['z1'], 6) for v in out.roots) [-1.0, 0.0, 1.0]
- Irene.sparse_moment.test_theorem_327(lam_vec, f_system: Sequence[Basic], A: Sequence[Sequence[int]], t: int, index: Dict[Tuple[int, ...], int], levels: dict, monoms: List[Tuple[int, ...]], tol: float = 1e-06) RankTestResult[source]¶
Theorem 3.27 convergence test for an optimizer \(\Lambda \in K_t\).
With \(D = \max_i \deg_A(f_i)\) and \(d = \lceil D/2\rceil\), check for admissible s (case i: \(\max\{D, \rho_A\} \le s \le \lfloor t/2\rfloor\); case ii: \(\max\{d, \rho_A\} \le s \le \lfloor t/2\rfloor\)):
rank(M_s(Lambda)) = rank(M_{s-1}(Lambda)), or
rank(M_s(Lambda)) = rank(M_{s-d}(Lambda)).
Either condition implies :math:`sqrt R I subseteq J := langle ker M_s(Lambda)
angle`; for generic Lambda, equality (paper Thm 3.27).
The full rank profile is always returned so a non-convergent truncation can still report which ranks were computed. Note: for small t the admissible range may be empty – then
convergedis False and the caller must increment t (Algorithm 1 step 4).lam_vec : moment vector Lambda(x^alpha) over R[A]_t (position-ordered). f_system : generators of I (sympy expressions in R[A]). A : exponent set, or a ToricSetup. t : the truncation degree K_t was solved at; must be >= 2*max admissible s. index, levels, monoms : the basis data from
moment_indices(A, t). tol : absolute eigenvalue threshold for numerical ranks.Returns a
RankTestResult.
- Irene.sparse_moment.toric_ideal(A: Sequence[Sequence[int]]) List[Expr][source]¶
Compute a Groebner basis G_A of the toric ideal T_A = ker(psi_A).
Uses standard elimination (Sturmfels, “Grobner Bases and Convex Polytopes”, Theorem 2.3): introduce u_1..u_m for x_1..x_m and z_1..z_r for the r monomials x^{alpha_i}, then eliminate u from
< z_i - prod_j u_j^{alpha_{i,j}} : i = 1..r > (lex, u first)
The ideal G_A in R[z] alone is exactly T_A.
- Parameters:
A (sequence of exponent vectors in N^m)
- Returns:
list of SymPy expressions in z_1..z_r generating T_A;
[]iff themonomials are algebraically independent (T_A = <0>).
symbolic_engine.py – user-selectable symbolic backend (SymEngine or SymPy).
- Design:
The default backend is SymEngine (C++ backend) for expansion, matrix and symbol creation; operations SymEngine does not implement (Groebner basis, Poly.as_dict(), reduced(), lambdify, DomainMatrix/PolyMatrix, …) always run on SymPy, with transparent to_sympy() casting.
Users can select the backend at runtime:
from Irene.symbolic_engine import engine, set_symbolic_backend set_symbolic_backend(‘sympy’) # or ‘symengine’ / ‘auto’
or via the environment variable IRENE_SYMBOLIC_BACKEND:
IRENE_SYMBOLIC_BACKEND=sympy python3 my_script.py IRENE_SYMBOLIC_BACKEND=symengine python3 my_script.py
Accepted values: ‘symengine’ (default when installed), ‘sympy’, ‘auto’ (prefer SymEngine when available, else SymPy).
If SymEngine is not installed, the engine automatically falls back to SymPy and engine.backend reports ‘sympy’.
- Usage in existing modules (e.g., relaxations.py):
# OLD: from sympy import groebner, Poly, Matrix, expand, lambdify, Symbol, QQ, zeros, reduced, sympify # NEW: from Irene.symbolic_engine import engine x = engine.Symbol(‘x’) g = engine.groebner([f1, f2], x) # always SymPy (SymEngine lacks Groebner) p = engine.Poly(expr, x) # always SymPy (SymEngine lacks full Poly API) M = engine.Matrix([[x**2, 1], [0, x]]) # DenseMatrix (SymEngine) or sp.Matrix (SymPy) result = engine.expand(p * q) # backend-native expand
- class Irene.symbolic_engine.SymbolicEngine(use_symengine=None)[source]¶
Unified symbolic computation engine.
Primary path: SymEngine (C++ backend) when use_symengine is True. Fallback: SymPy for operations SymEngine doesn’t support.
The backend can be selected at construction, at runtime via
set_backend(), or globally via theIRENE_SYMBOLIC_BACKENDenvironment variable (read once at import time for the default engine).- use_symengine¶
bool – True uses SymEngine primary path (default True)
- fallback_log¶
list – records which calls fell back to SymPy
- Matrix(*args, **kwargs)[source]¶
Construct a matrix in the selected backend.
SymEngine DenseMatrix when the backend is SymEngine and entries are compatible; SymPy Matrix otherwise.
- property QQ¶
Rational field – SymPy only.
- groebner(polys, *gens, order='lex')[source]¶
Groebner basis – always SymPy (SymEngine doesn’t support this).
- lambdify(symbols, expressions, modules='numpy')[source]¶
Compile to numerical function – SymPy lambdify (SymEngine lacks this).
- set_backend(backend)[source]¶
Select the symbolic backend.
- Parameters:
backend – ‘symengine’, ‘sympy’, or ‘auto’ (prefer installed).
- Returns:
self (chainable).
- Raises:
ValueError – unknown backend name.
ImportError – ‘symengine’ requested but not installed.
- Irene.symbolic_engine.fallback_to_sympy(func)[source]¶
Decorator: run func with SymEngine; on failure, cast inputs->SymPy->run native->cast result.
- Irene.symbolic_engine.get_symbolic_backend()[source]¶
Module-level helper: name of the default engine’s backend.
- Irene.symbolic_engine.set_symbolic_backend(backend)[source]¶
Module-level helper: select the backend of the default engine.
- Irene.symbolic_engine.to_symengine(obj)[source]¶
Cast a SymPy object (or list/matrix of them) to SymEngine.
Returns the object unchanged when SymEngine is unavailable or the object cannot be converted.
- Irene.symbolic_engine.to_sympy(obj)[source]¶
Cast a SymEngine object (or list/matrix of them) to SymPy.
CVXPY-based solver abstraction layer for Irene SDP relaxations.
Replaces text-based solver writers (SDPA/CSDP dat files) with a DCP-compliant formulation that routes to Clarabel, SCS, or CVXOPT through CVXPY’s unified API.
The SDP is formulated in primal standard form:
min b^T x s.t. sum_i A_{i,j} * x[i] - C_j >= 0 for j = 1..k (PSD blocks)
where each block j has dimension BlockStruct[j].
- class Irene.cvxpy_solver.CvxpySDPSolver(solver: str | None = None)[source]¶
CVXPY-based SDP solver with the same API as
Irene.sdp.sdp.Usage mirrors the legacy interface:
solver = CvxpySDPSolver(solver='CLARABEL') solver.SetObjective(b) solver.AddConstraintBlock(A_i) # for each variable x_i solver.AddConstantBlock(C_j) # constant PSD blocks result = solver.solve()
- Parameters:
solver (str, optional) – Solver backend. One of
'CLARABEL','SCS','CVXOPT'. Defaults to the first available solver from that list.
- AddConstantBlock(C)[source]¶
Set constant PSD blocks.
- Parameters:
C (list of ndarray, length k) –
C[j]is the constant matrix (d_j x d_j) for block j.
- AddConstraintBlock(A)[source]¶
Add constraint matrices for one primal variable.
- Parameters:
A (list of ndarray, length k) –
A[j]is the coefficient matrix (d_j x d_j) for block j.
- AddEquality(a, b)[source]¶
Add one affine equality constraint
a^T x = b.Needed by moment-spectrahedron formulations (e.g. the K_t set of Baumbach–Bender: normalization
Lambda(1) = 1and prolongation constraintsLambda(f) = 0), which the PSD blocks alone do not express.- Parameters:
a (array-like of shape (m,)) – Coefficient vector;
mmust match the objective length set bySetObjective.b (float) – Right-hand side.
- Option(param: str, val)[source]¶
Set a solver option.
- Parameters:
param (str) – Option name (solver-specific).
val (any) – Option value.
- class Irene.cvxpy_solver.SDPResult[source]¶
Container for SDP solution data.
Attributes mirror the legacy
sdp.Infodictionary keys so that downstream code inrelaxations.pycan consume results without change.
- Irene.cvxpy_solver.available_solvers() list[str][source]¶
Return list of SDP-capable solvers currently installed.
Differential Semidefinite Programming (DSDP) relaxations.
Extends the Lasserre SDP hierarchy to handle optimization problems where polynomial terms include functions satisfying algebraic differential equations (ADEs). Uses Ritt-Woodin differential algebra to encode ADE constraints as algebraic relations in the moment hierarchy.
- Key features:
ADE lift: encode transcendental functions via algebraic relations (e.g., y*z=1 for exp, y’ = y for dy/dx = y)
Differential KKT: inject stationarity conditions derived via Leibniz rule
Mean polynomial certificates: M_{q,p}(X,w) nonnegativity via SDP
Archimedean (boxing) constraints for convergence guarantees
- Integration:
Inherits SDPRelaxations (sympy-based moment hierarchy)
Compatible with OptimizationProblem via from_problem()
Works with SemigroupAlgebra derivation support
- class Irene.dsdp.DSDPKKTRelaxation(gens, relations=(), name='DSDPKKTRlx', diff_map=None, **kwargs)[source]¶
DSDP relaxation with differential KKT condition injection.
Injects stationarity conditions derived from differentiating the Lagrangian, which can tighten bounds significantly (equivalent to one higher Lasserre order).
- class Irene.dsdp.DSDPMeanRelaxation(gens, weights, q=1, p=0, relations=(), name='DSDPMeanRlx', **kwargs)[source]¶
Specialized DSDP relaxation using mean polynomial certificates.
Focuses on the \(M_{q,p}(X,w)\) nonnegativity certificate as the primary relaxation mechanism, with ADE relations as secondary constraints.
The mean polynomial cone \(\mathcal{M}_{n,2d}\) contains both SOS and SONC cones, providing a potentially tighter relaxation.
- class Irene.dsdp.DSDPRelaxations(gens, relations=(), name='DSDPRlx', **kwargs)[source]¶
Differential SDP relaxation framework.
Extends
SDPRelaxationsto handle problems with ADE-constrained variables. The ADE is encoded as algebraic relations in the Groebner basis, and differential KKT conditions are injected as additional linear moment constraints.- The relaxation constructs a moment hierarchy where:
ADE relations are enforced as equality constraints on moment variables
Differential KKT conditions tighten the relaxation (degree-lift equivalent)
Mean polynomial certificates \(M_{q,p}(X,w)\) provide nonnegativity proofs
Example
>>> from sympy import symbols, exp >>> from Irene import DSDPRelaxations >>> x, y, z = symbols('x y z') >>> # Minimize e^x - x^2 via ADE lift y = e^x, z = e^{-x}, y*z = 1 >>> dsdp = DSDPRelaxations([x, y, z], relations=[y*z - 1]) >>> dsdp.SetObjective(y - x**2) >>> dsdp.solve()
- add_ade_moment_constraint(expr, rhs=0)[source]¶
Add an ADE-derived moment constraint directly.
- Parameters:
expr – Sympy polynomial expression for the constraint.
rhs – Right-hand side value (default: 0 for equality).
- build_ade_relations(diff_map: dict, prefix='d', wrt=None)[source]¶
Build ADE relations from a derivation map by introducing derivative symbols.
For each generator g in diff_map, creates a new symbol d_g representing d_x(g), then adds the relation d_g - expr to the quotient ring. This encodes the ADE constraint algebraically via Groebner reduction.
CRITICAL: Derivative symbols MUST be prepended to the generator list so they become leading terms in the lex-ordered Groebner basis. Without this, ReduceExp() cannot substitute them back to polynomial expressions.
- Parameters:
diff_map – Dictionary mapping generators to their derivative expressions.
prefix – Prefix for generated derivative symbols (default: “d”).
wrt – Derivation variable name for symbol prefix. When provided, symbols are named “{prefix}{wrt}_{gen}” (e.g., “dx_y”, “dy_v”). When None, uses “{prefix}_{gen}” (backward compatible).
- Returns:
derivative_syms: Dict mapping original generators to their derivative symbols.
relations: List of relation expressions (d_g - expr).
new_gens: Updated generator list with derivative symbols prepended.
- Return type:
Tuple (derivative_syms, relations, new_gens)
Example
>>> # tan(x) ADE: D_x(u) = 1 + u^2 >>> dm = {x: 1, u: 1 + u**2} >>> dsyms, rels, gens = dsdp.build_ade_relations(dm) >>> # dsyms = {x: dx, u: du} >>> # rels = [dx - 1, du - (1 + u**2)] >>> # gens = [dx, du, x, u] (derivatives first!)
>>> # Multi-derivation: D_y(L) = v, D_y(v) = -v^2 >>> dsyms, rels, gens = dsdp.build_ade_relations({y:1, L:v, v:-v**2}, wrt='y') >>> # dsyms = {y: dy_y, L: dy_L, v: dy_v}
- differentiate(expr, var=None)[source]¶
Compute the formal derivative of an expression using the registered derivation map.
Applies the Leibniz rule: d(f*g) = d(f)*g + f*d(g). If no derivation map is registered, falls back to sympy’s diff().
- Parameters:
expr – Sympy expression to differentiate.
var – Variable to differentiate with respect to (default: first generator).
- Returns:
Formal derivative of expr.
- set_derivation(diff_map: dict) None[source]¶
Register a derivation map for differential KKT conditions.
- Parameters:
diff_map – Dictionary mapping sympy generators to their derivatives. E.g., {x: y, y: -y} encodes dy/dx = -y.
- solve(order=None)[source]¶
Solve the DSDP relaxation with automatic solver routing.
Builds the relaxation and routes to the appropriate solver based on certificate structure: - Posynomial certificates -> GP/SONC (convex log-domain optimization) - Mixed-sign certificates -> SDP (general moment hierarchy) - Depth >= 2 -> SDP (alternating-sign expansion terms)
- Parameters:
order – Relaxation order (default: auto from problem degree).
- Returns:
Lower bound on the optimal value.
- property sp_auxsyms¶
Return AuxSyms converted to pure SymPy (engine.Symbol -> sympy.Symbol).
Execution telemetry for Irene SDP pipeline.
Provides zero-overhead phase timing, structured diagnostics collection,
and JSON export for benchmarking. Controlled by the environment variable
IRENE_TELEMETRY (default "1" – enabled). Set to "0" to disable
all telemetry with no runtime cost.
Public API¶
@timed(phase)– decorator that logs wall-clock time for a named phase.TelemetryContext– context manager that collects structured metrics.get_telemetry()– retrieve the current session’s telemetry dict.clear_telemetry()– reset the session state.export_json(path)– write telemetry to a JSON file.
Usage example¶
>>> from Irene.telemetry import timed, TelemetryContext, export_json
>>> @timed("basis_construction")
... def build_basis(deg): ...
>>> with TelemetryContext("sdp_solve", monomial_count=42):
... solve_sdp()
>>> export_json("benchmark.json")
- class Irene.telemetry.PhaseTiming(wall_clock_s: float = 0.0)[source]¶
Wall-clock timing for a single pipeline phase.
- class Irene.telemetry.TelemetryContext(phase: str, **kwargs)[source]¶
Context manager that collects structured metrics for one SDP run.
- Parameters:
phase (str) – Top-level phase name (e.g.
"sdp_solve","init_sdp_serial").**kwargs – Arbitrary metadata key-value pairs attached to this record.
Example
>>> with TelemetryContext("solve", monomial_count=42, block_dims=[10, 5]): ... sdp.solve()
- class Irene.telemetry.TelemetryRecord(phase: str = '', timings: Dict[str, ~Irene.telemetry.PhaseTiming]=<factory>, metadata: Dict[str, ~typing.Any]=<factory>)[source]¶
Structured telemetry record for one SDP relaxation run.
- timings¶
Per-sub-phase wall-clock times accumulated via the
@timeddecorator.- Type:
- Irene.telemetry.export_json(path: str) str[source]¶
Write the full session telemetry to a JSON file.
- Irene.telemetry.get_active_record() dict | None[source]¶
Return the currently active telemetry record (if any) as a dict.
- Irene.telemetry.get_telemetry() list[dict][source]¶
Return all telemetry records as a list of plain dicts.
Each dict has keys
phase, optionallytimingsandmetadata.
- Irene.telemetry.timed(phase: str)[source]¶
Decorator that logs wall-clock time for a named sub-phase.
When telemetry is disabled (
IRENE_TELEMETRY=0), this becomes a no-op wrapper with zero overhead beyond the function call itself.- Parameters:
phase (str) – Name of the pipeline phase to time (e.g.
"basis_construction","matrix_assembly","solve","post_processing").
Example
>>> @timed("basis_construction") ... def build_basis(deg): ... return [monomials]
- Irene.matrices.find_psd_gram_matrix(polynomial)[source]¶
Uses Convex Optimization (SDP) to find a Positive Semidefinite (PSD) Gram matrix for the given polynomial.
- Irene.matrices.get_gram_matrix(polynomial)[source]¶
Computes a symmetric Gram matrix Q for a given polynomial p such that p = Z.T * Q * Z, where Z is the vector of monomials.
Uses SymEngine for polynomial expansion and SymPy fallback for Poly operations.
- Parameters:
polynomial – A symbolic polynomial expression (SymEngine or SymPy).
- Returns:
The Gram matrix as float64 array. Q_sym: The symbolic Gram matrix.
- Return type:
Q_np (np.ndarray)
- Irene.matrices.is_psd_numeric(matrix, tol=1e-08)[source]¶
Checks if a matrix is Positive Semidefinite using NumPy.
- Irene.matrices.numpy_to_latex(matrix, precision=3, env='bmatrix')[source]¶
Converts a numpy matrix or array into LaTeX code.
- class Irene.invariant.InvariantPolynomial(Prg)[source]¶
A class for computations on polynomials invariant under a finite group of permutations.
- ConjugateClosure(H)[source]¶
Computes the conjugate closure of a subgroup.
- Parameters:
H (Subgroup) – The subgroup to compute the conjugate closure of.
- Returns:
The conjugate closure of the subgroup.
- Return type:
Subgroup
- Reynolds(f, G)[source]¶
Computes the Reynolds operator associated o the group G on the polynomial f.
Doctest Integration¶
To ensure that code snippets in docstrings remain synchronized with the
Irene codebase, Sphinx can be configured to run doctest blocks
during documentation builds.
Enable in conf.py:
extensions = [
# ... other extensions ...
'sphinx.ext.doctest',
]
Then run as part of the documentation build pipeline:
cd doc
make doctest
Alternatively, run via pytest against the installed package:
.venv/bin/python3 -m pytest --doctest-modules Irene/
The following modules are doctest-ready (their docstrings contain executable
examples): relaxation_api.py, program.py, border_basis.py. See
Benchmarks and Performance Evaluation for the gallery-based integration test suite that serves as
the primary verification layer.