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.

Irene.base.LaTeX(obj)[source]

Returns LaTeX representation of Irene’s 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.

AvailableSDPSolvers()[source]

find the existing sdp solvers.

static which(program)[source]

Check the availability of the program system-wide. Returns the path of the program if exists and returns ‘None’ otherwise.

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:

str

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. Default False.

Type:

bool

sparsity_detection

Run correlative-sparsity analysis on the problem polynomials and decompose the moment matrix into independent blocks when possible.

Type:

bool

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:

bool

border_basis_degree

Degree bound for the border-basis quotient algebra representation (only used when reduction_method='border_basis'). Default 2.

Type:

int

verbose_reduction

Print diagnostics (basis sizes, reduction ratios) during setup.

Type:

bool

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 sympy symbols and function symbols,

  • relations which is a set of sympy expressions 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 Mmnt is 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 is True, it runs in parallel mode, otherwise in serial.

P5.8: When config.sparsity_block_sdp is True (or reduction_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.T is routed through SymEngine’s C++ backend when available. Each entry of the resulting matrix is expanded with se.expand() (C++) before being converted back to SymPy for Groebner reduction via ReduceExp.

LocalizedMoment_(p)[source]

Computes the reduced symbolic moment generating matrix localized at p.

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.

MomentsOrd(ordr)[source]

Sets the order of moments to be considered.

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.

ReducedMonomialBase(deg)[source]

Returns a reduce monomial basis up to degree d.

Phase 3 integration: the reduction pipeline is controlled via self.config. When config.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. When config.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.

Resume()[source]

Resumes the process of a previously saved program.

SaveState()[source]

Saves the current state of the relaxation object to the file self.Name+’.rlx’.

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.

State()[source]

Returns the latest state of the object at last break and save.

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.TruncatedMmntSeq a dictionary of resulted moments

  • SDRelaxSol.MomentMatrix the resulted moment matrix

  • SDRelaxSol.Primal the value of the SDP in primal form

  • SDRelaxSol.Dual the value of the SDP in dual form

  • SDRelaxSol.RunTime the run time of the sdp solver

  • SDRelaxSol.InitTime the total time consumed for initialization of the sdp

  • SDRelaxSol.Solver the name of sdp solver

  • SDRelaxSol.Status final status of the sdp solver

  • SDRelaxSol.RelaxationOrd order of relaxation

  • SDRelaxSol.Message the message that maybe returned by the sdp solver

  • SDRelaxSol.ScipySolver the scipy solver to extract solutions

  • SDRelaxSol.err_tol the minimum value which is considered to be nonzero

  • SDRelaxSol.Support the support of discrete measure resulted from SDPRelaxation.Minimize()

  • SDRelaxSol.Weights corresponding weights for the Dirac measures

ExtractSolution(mthd='LH', card=0)[source]

Extract support of the solution measure from SDPRelaxations:

-mthd should be either ‘LH’ or ‘Scipy’, where ‘LH’ stands for ‘Lasserre-Henrion’ and ‘Scipy’ employs a Scipy solver to find points matching the moments,

-card restricts the number of points of the support.

ExtractSolutionLH(card=0)[source]

Extract solutions based on Lasserre–Henrion’s method.

ExtractSolutionScipy(card=0)[source]

This method tries to extract the corresponding values for generators of the SDPRelaxation class. 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 by scipy:

  • hybr,

  • lm (default),

  • broyden1,

  • broyden2,

  • anderson,

  • linearmixing,

  • diagbroyden,

  • excitingmixing,

  • krylov,

  • df-sane.

NumericalRank()[source]

Finds the rank of the moment matrix based on the size of its eigenvalues. It considers those with absolute value less than self.err_tol to be zero.

Pivot(arr)[source]

Get the leading term of each column.

SetScipySolver(solver)[source]

Sets the scipy.optimize.root solver to solver.

StblRedEch(A)[source]

Compute the stabilized row reduced echelon form.

Term2Mmnt(trm, rnk, X)[source]

Converts a moment object into an algebraic equation.

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 numpy matrices 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 AddConstraintBlock fills the blocks associated with \(i^{th}\) variable \(x_i\).

CvxOpt()[source]

This calls CVXOPT and DSDP to solve the initiated semidefinite program.

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: True or False, 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 exceeds maxIteration;

    • 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.

SetObjective(b)[source]

Takes the coefficients of the objective function.

static VEC(M)[source]

Converts the matrix M into a column vector acceptable by CVXOPT.

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().

sdpa_param()[source]

Produces sdpa.param file from SolverOptions.

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.solver if 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().

write_sdpa_dat(filename)[source]

Writes the semidefinite program in the file filename with dense SDPA format.

write_sdpa_dat_sparse(filename)[source]

Writes the semidefinite program in the file filename with sparse SDPA format. Uses sparse iteration over non-zero entries to avoid dense nested loops.

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:

SemigroupAlgebra

relations

The relations of the optimization problem.

Type:

list[SemigroupAlgebraElement]

semigroup

The semigroup of the optimization problem.

Type:

CommutativeSemigroup

objective

The objective function of the optimization problem.

Type:

SemigroupAlgebraElement

constraints

The constraints of the optimization problem.

Type:

list[SemigroupAlgebraElement]

objective_degree

The degree of the objective function.

Type:

int

objective_half_degree

The half degree of the objective function.

Type:

int

constraints_degree

The degrees of the constraints.

Type:

list[int]

constraints_half_degree

The half degrees of the constraints.

Type:

list[int]

objective_trms_with_positive_coefficient

The terms of the objective function with positive coefficients.

Type:

list[SemigroupAlgebraElement]

objective_trms_with_negative_coefficient

The terms of the objective function with negative coefficients.

Type:

list[SemigroupAlgebraElement]

objective_terms_with_even_exponent

The terms of the objective function with even exponents.

Type:

list[SemigroupAlgebraElement]

objective_terms_with_odd_exponent

The terms of the objective function with odd exponents.

Type:

list[SemigroupAlgebraElement]

constraint_trms_with_positive_coefficient

The terms of the constraints with positive coefficients.

Type:

list[SemigroupAlgebraElement]

constraint_trms_with_negative_coefficient

The terms of the constraints with negative coefficients.

Type:

list[SemigroupAlgebraElement]

constraint_terms_with_even_exponent

The terms of the constraints with even exponents.

Type:

list[SemigroupAlgebraElement]

constraint_terms_with_odd_exponent

The terms of the constraints with odd exponents.

Type:

list[SemigroupAlgebraElement]

total_degree

The total degree of the optimization problem.

Type:

int

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:

numpy.ndarray

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:
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:

dict[str, set[SemigroupAlgebraElement]]

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:
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:

tuple[bool, int]

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:

bool

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:

numpy.ndarray

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:

tuple

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:

list[tuple[int, SemigroupAlgebraElement]]

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:

int

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:

bool

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:

SemigroupAlgebraElement

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:

CommutativeSemigroup

symbol

The symbol of the element.

Type:

str

content

The content of the element.

Type:

list

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:

float

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:

SemigroupAlgebraElement

divide(fs: list) → tuple[list, SemigroupAlgebraElement][source]

Divides the element by a list of elements or expressions.

Parameters:

fs (list) – The list of elements or expressions to divide by.

Returns:

A tuple containing the quotient and remainder of the division.

Return type:

tuple

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:

bool

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.

gens

The generators of the semigroup.

Type:

list

is_semigroup

True if the semigroup is a semigroup, False otherwise.

Type:

bool

is_abelian

True if the semigroup is abelian, False otherwise.

Type:

bool

rels

The relations of the semigroup.

Type:

list

aux_rels

The auxiliary relations of the semigroup.

Type:

list

inverses

The inverses of the generators of the semigroup.

Type:

dict

max_deg

The maximum degree of the relations of the semigroup.

Type:

int

edges

The edges of the lattice of the semigroup.

Type:

list

vertices

The vertices of the lattice of the semigroup.

Type:

dict

symbols

The symbols of the semigroup.

Type:

list

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:

int

element_sub_lattice(elm: Expr, ex: set = None) → set[source]

Computes the sublattice of the lattice of the semigroup generated by an element.

Parameters:
  • elm (sympy.Expr) – The element of the semigroup to generate the sublattice from.

  • ex (set) – The set of elements to exclude from the sublattice.

Returns:

The sublattice of the lattice of the semigroup generated by the element.

Return type:

set

lattice_edges(degree: int) → None[source]

Computes the edges of the lattice of the semigroup.

Parameters:

degree (int) – The degree of the lattice.

lattice_vertices() → None[source]

Computes the vertices of the lattice of the semigroup.

The vertices of the lattice are the elements of the semigroup that are generated by the edges of the lattice.

positive_exp(expr: Expr) → bool[source]

Checks if an expression in the semigroup has only positive exponents.

Parameters:

expr (sympy.Expr) – The expression to check.

Returns:

True if the expression has only positive exponents, False otherwise.

Return type:

bool

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.

gens

The generators of the semigroup.

Type:

list

semigroup

The semigroup of the algebra.

Type:

CommutativeSemigroup

derivatives

A list of dictionaries mapping the elements of the semigroup to their derivatives.

Type:

list

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:
Returns:

The derivative of the expression.

Return type:

SemigroupAlgebraElement

diff(expr: Any, base_map: dict)[source]

Computes the derivative of an expression in the algebra.

Parameters:
Returns:

The derivative of the expression.

Return type:

SemigroupAlgebraElement

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.

content

The content of the element.

Type:

list

semigroup

The semigroup of the element.

Type:

CommutativeSemigroup

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:

float

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:

SemigroupAlgebraElement

divide(fs: list) → tuple[list, SemigroupAlgebraElement][source]

Divides the element by a list of elements or expressions.

Parameters:

fs (list) – The list of elements or expressions to divide by.

Returns:

A tuple containing the quotient and remainder of the division.

Return type:

tuple

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:

bool

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.

transform_program() → None[source]

Transform the program using the transformation matrix H.

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.

val

Optimal \(\lambda^*\), a lower bound on \(f^*\).

Type:

float

method

'sos', 'sonc', 'sos-first', or 'sonc-first'.

Type:

str

f_sos

SOS summand of f - val (if applicable).

Type:

optional

f_sonc

SONC summand of f - val (if applicable).

Type:

optional

status

'optimal', 'infeasible', or 'error'.

Type:

str

error_code

0 = success, 1 = infeasible, 2 = solver error.

Type:

int

runtime

Wall-clock time in seconds.

Type:

float

message

Human-readable status message.

Type:

str

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 OptimizationProblem with an objective set via prog.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:

SOSONCRelaxSol

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:

SOSONCRelaxSol

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:

SOSONCRelaxSol

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:
  1. A monomial basis B (standard monomials spanning K[x]/I)

  2. The border partial B = {bcdotx_i : b in B, i=1..n} B

  3. 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_alpha has entries M_{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

reduce(expr)[source]

Reduce an expression using the border basis multiplication tables.

Parameters:

expr – A polynomial expression to reduce modulo the ideal.

Returns:

The reduced expression as a linear combination of basis monomials.

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).

summary() → Dict[source]

Return a human-readable summary of the sparsity pattern.

class Irene.sparsity.UnionFind(n: int)[source]

Disjoint-set union-find with path compression and rank.

get_components() → Dict[int, List[int]][source]

Return mapping from root -> list of members.

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 in required_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 of required_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.

summary() → Dict[source]

Return a human-readable summary of the pruning results.

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). Default None keeps 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). Default None keeps 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

  1. One constructor – RelaxationEngine(prog) wraps any OptimizationProblem.

  2. Consistent return type – every solve call returns a RelaxResult with the same attributes (value, status, timing, solver metadata).

  3. Method dispatch – the user picks 'sos', 'sonc', or 'sosonc'; the engine routes to the correct backend class internally.

  4. 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.RelaxMethod(value)[source]

Supported relaxation backends.

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.

value

Lower bound on the global minimum (-inf on failure).

Type:

float

method

Which relaxation was used.

Type:

str

status

'optimal', 'infeasible', or 'error'.

Type:

str

error_code

0 = success, 1 = infeasible, 2 = solver/computation error.

Type:

int

runtime

Wall-clock seconds for the solve phase (excludes matrix setup).

Type:

float

init_time

Time spent building moment/localizing matrices (if available).

Type:

Optional[float]

message

Human-readable status or error description.

Type:

str

certificate

SOS/SONC polynomial certificate if the backend exposes one.

Type:

Optional[Any]

solver_info

Backend-specific metadata (solver name, iterations, etc.).

Type:

dict

property success: bool

True if the relaxation returned a finite bound without error.

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) or prog.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:

RelaxResult

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 RelaxationEngine constructor (order, solver, error_bound, verbosity, etc.).

Return type:

RelaxResult

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 generators

  • toric_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_iterations was 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_A convention (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).

tables
Type:

list of r_ x r_ arrays; column k = [x^{a_i} b_k] in B.

normal_forms[e]
Type:

coefficient vector d over R[A]^{s_star}, x^e - sum d_j b_j in J.

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), which check_relations tests.

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
normal_form(e)[source]

Coefficient vector d over R[A]^{s_star}: x^e - sum_j d[b_j] b_j in J.

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).

lambda_vec
Type:

moment vector Lambda(x^alpha), alpha in R[A]_t (position-ordered).

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_t
Type:

|R[A]_t|, number of SDP variables.

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 Info dict 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.

A
Type:

tuple of exponent vectors (validated, deduplicated)

r
Type:

number of generators = len(A); ambient dimension m = len(A[0])

z
Type:

the generator symbols z_1..z_r of R[z] ~= R[A] (isomorphic)

G_A
Type:

Groebner basis of the toric ideal T_A in R[z] (empty if none)

rho_A
Type:

max total degree over G_A, or 0 when T_A = <0> (paper eq. 3)

classmethod from_exponents(A: Sequence[Sequence[int]]) → ToricSetup[source]

Build the setup for an exponent set A subset of N^m.

Example

>>> import sympy as sp
>>> ts = ToricSetup.from_exponents([(2, 0), (3, 0)])   # R[x^2, x^3]
>>> ts.rho_A
3
>>> [sp.simplify(g) for g in ts.G_A]
[z1**3 - z2**2]
property is_full_ring: bool

True iff A is a monomial basis of the full polynomial ring (T_A < 0>); then rho_A = 0 and no toric reduction applies.

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) where monoms is the sorted list of exponent tuples in R[A]^t (by A-degree, then lexicographic), index maps each exponent to its position in that list, and levels gives deg_A(x^beta) for every enumerated beta. The length of monoms is 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_i with deg_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_iterations exceeded -> 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 SparseRootsResult with 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 with no_real_roots recorded on it via roots == [] 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\)):

  1. rank(M_s(Lambda)) = rank(M_{s-1}(Lambda)), or

  2. 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 converged is 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 the

  • monomials 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 the IRENE_SYMBOLIC_BACKEND environment 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

Abs(expr)[source]

Absolute value in the selected backend.

DomainMatrix(matrix, domain)[source]

Domain matrix – SymPy only.

Function(name)[source]

Symbolic function – SymPy only (SymEngine lacks this).

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.

Poly(expr, *gens)[source]

Construct polynomial. SymPy fallback (SymEngine lacks full Poly API).

PolyMatrix(matrix, *gens)[source]

Polynomial matrix – SymPy only.

property QQ

Rational field – SymPy only.

Symbol(name, **kwargs)[source]

Create a symbolic variable in the selected backend.

static available_backends()[source]

Backends that can be selected on this installation.

clear_fallback_log()[source]

Clear the fallback log.

expand(expr)[source]

Expand a polynomial expression using the selected backend.

fallback_stats()[source]

Return dict of how many times each operation fell back to SymPy.

get_backend()[source]

Current backend name: ‘symengine’ or ‘sympy’.

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).

latex(expr)[source]

LaTeX string representation (SymPy printer for both backends).

reduced(expr, groebner_basis)[source]

Reduce expression modulo Groebner basis – always SymPy.

set_backend(backend)[source]

Select the symbolic backend.

Parameters:

backend – ‘symengine’, ‘sympy’, or ‘auto’ (prefer installed).

Returns:

self (chainable).

Raises:
sqrt(expr)[source]

Square root in the selected backend.

symbols(names, **kwargs)[source]

Create multiple symbolic variables in the selected backend.

sympify(obj)[source]

Convert Python/SymEngine object to symbolic expression.

zeros(rows, cols)[source]

Zero matrix in the selected backend.

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) = 1 and prolongation constraints Lambda(f) = 0), which the PSD blocks alone do not express.

Parameters:
  • a (array-like of shape (m,)) – Coefficient vector; m must match the objective length set by SetObjective.

  • b (float) – Right-hand side.

CvxOpt()[source]

Legacy compatibility – delegates to solve().

Option(param: str, val)[source]

Set a solver option.

Parameters:
  • param (str) – Option name (solver-specific).

  • val (any) – Option value.

SetObjective(b)[source]

Set objective coefficient vector b.

Parameters:

b (array-like of shape (m,)) – Coefficients of the linear objective min b^T x.

solve() → SDPResult[source]

Solve the SDP and return structured results.

Returns:

Container with status, objectives, primal/dual variables, etc.

Return type:

SDPResult

class Irene.cvxpy_solver.SDPResult[source]

Container for SDP solution data.

Attributes mirror the legacy sdp.Info dictionary keys so that downstream code in relaxations.py can consume results without change.

to_info_dict() → dict[source]

Return legacy-compatible Info dictionary.

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).

solve_kkt(order=None)[source]

Solve with KKT stationarity injection.

Parameters:

order – Relaxation order.

Returns:

Tightened lower bound.

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.

construct_mean_moment_matrix()[source]

Construct the moment matrix for the mean polynomial certificate.

Returns:

Block-diagonal moment matrix encoding M_{q,p} nonnegativity.

solve_mean(order=None)[source]

Solve using mean polynomial relaxation.

Parameters:

order – Relaxation order.

Returns:

Lower bound from mean relaxation.

class Irene.dsdp.DSDPRelaxations(gens, relations=(), name='DSDPRlx', **kwargs)[source]

Differential SDP relaxation framework.

Extends SDPRelaxations to 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:
  1. ADE relations are enforced as equality constraints on moment variables

  2. Differential KKT conditions tighten the relaxation (degree-lift equivalent)

  3. 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()
set(key: str, value: Any)[source]

Attach or update a metadata field on the active record.

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.

phase

Human-readable phase name (e.g. "basis_construction").

Type:

str

timings

Per-sub-phase wall-clock times accumulated via the @timed decorator.

Type:

dict[str, PhaseTiming]

metadata

Arbitrary key-value pairs set by the caller (monomial counts, block dims, etc.).

Type:

dict[str, Any]

Irene.telemetry.clear_telemetry()[source]

Reset all session-level telemetry state.

Irene.telemetry.export_json(path: str) → str[source]

Write the full session telemetry to a JSON file.

Parameters:

path (str) – File path for the output JSON.

Returns:

The absolute path of the written file.

Return type:

str

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, optionally timings and metadata.

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.

Parameters:
  • matrix (np.ndarray) – The input matrix.

  • tol (float) – Tolerance for floating point errors.

Returns:

True if PSD, False otherwise.

Return type:

bool

Irene.matrices.is_psd_symbolic(matrix)[source]

Checks if a SymPy matrix is Positive Semidefinite.

Irene.matrices.numpy_to_latex(matrix, precision=3, env='bmatrix')[source]

Converts a numpy matrix or array into LaTeX code.

Parameters:
  • matrix (np.ndarray) – The input matrix.

  • precision (int) – Decimal places for floating point numbers.

  • env (str) – The LaTeX environment (bmatrix, pmatrix, vmatrix, etc.)

Returns:

The generated LaTeX string.

Return type:

str

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

GenMon(alpha)[source]

Returns the monomial corresponding to the input tuple.

OmegaFtilde()[source]

Finds the equivalence classes of exponents of the polynomial.

QOmega()[source]

Finds the equivalence classes of exponents with respect to the group action.

RedPart(f, P)[source]

Computes the reduced part of a polynomial.

Parameters:
  • f (Polynomial) – The polynomial to compute the reduced part of.

  • P (list[list[int]]) – The partition of the variables.

Returns:

The reduced part of the polynomial.

Return type:

Polynomial

Reynolds(f, G)[source]

Computes the Reynolds operator associated o the group G on the polynomial f.

SigmaAlpha(sigma, alpha)[source]

Takes a permutation and an n-tuple and returns the result of the permutation on the indices of the tuple.

Stabilizer(G, alpha)[source]

Returns the stabilizer group of an exponent.

StblTldMax()[source]

Finds the largest subgroup which fixes the associated ring of tilde{f}_{max}

tildemax()[source]

Computes the tilde{f}_{max} corresponding to the polynomial and the group action.

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.