Skip to content

Commit

Permalink
Performance improvement in creating Basis objects
Browse files Browse the repository at this point in the history
  • Loading branch information
yuanchenyang committed Oct 5, 2024
1 parent d9bc6ff commit 3c713ba
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 8 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ __pycache__
*.out

# Project specific
/Untitled.ipynb
/examples
/.ipynb_checkpoints/
/build/
/dist/
Expand Down
2 changes: 1 addition & 1 deletion src/SumOfSquares/SoS.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def poly_opt_prob(vars : List[sp.Symbol],
deg : Optional[int] = None,
sparse : bool = False) -> SOSProblem:
'''Formulates and returns a degree DEG Sum-of-Squares relaxation of a polynomial
optimization problem in variables VARS that mininizes OBJ subject to
optimization problem in variables VARS that minimizes OBJ subject to
equality constraints EQS (g(x) = 0) and inequality constraints INEQS (h(x)
>= 0). INEQ_PRODS determines if products of inequalities are used. SPARSE
uses Newton polytope reduction to do computations in a reduced-size
Expand Down
18 changes: 12 additions & 6 deletions src/SumOfSquares/basis.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import sympy as sp
import numpy as np
import math
from functools import lru_cache
from collections import defaultdict
from typing import Iterable, Tuple, List, Union

Expand Down Expand Up @@ -39,19 +40,24 @@ def __init__(self, monoms: List[Tuple[int]]):
self.nvars = len(monoms[0])
self.is_hom = sum(sum(m) != self.deg for m in self.monoms) == 0

# A map from a monomial m (represented as tuple) to list of pairs (i, j)
# for all such pairs where m = basis[i]*basis[j].
self.sos_sym_entries = defaultdict(list)
for i, bi in enumerate(self):
for j, bj in enumerate(self):
self.sos_sym_entries[sum_tuple(bi, bj)].append((i, j))

def __len__(self) -> int:
return len(self.monoms)

def __iter__(self) -> Iterable[Tuple[int]]:
return iter(self.monoms)

@property
@lru_cache()
def sos_sym_entries(self):
# A map from a monomial m (represented as tuple) to list of pairs (i, j)
# for all such pairs where m = basis[i]*basis[j].
sos_sym_entries = defaultdict(list)
for i, bi in enumerate(self):
for j, bj in enumerate(self):
sos_sym_entries[sum_tuple(bi, bj)].append((i, j))
return sos_sym_entries

def from_degree(nvars: int, deg: int, hom: bool=False) -> Basis:
'''Constructs a basis by specifying the number of variables and degree'''
return Basis(list((basis_hom if hom else basis_inhom)(nvars, deg)))
Expand Down

0 comments on commit 3c713ba

Please sign in to comment.