Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
- Methods taking a list of variables (e.g. `addConsKnapsack()`) no longer convert it to a NumPy array to check its dimension
- Speed up `PowExpr._evaluate` via the C-level API
- `PowExpr._evaluate` now raises `ValueError("math domain error")` for a negative base with a non-integer exponent and `OverflowError` when the result overflows.
- Faster construction of polynomial expressions (`Term()` creation, comparison, and multiplication are cheaper).
- `Term` now accepts a single argument (`Variable` or `None`) instead of multiple arguments
### Removed
- Removed support for Python 3.8

Expand Down
58 changes: 39 additions & 19 deletions src/pyscipopt/expr.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
# A `term` is a tuple of variables
# For examples, 2*x*x*y*z - 1.3 x*y*y + 1 is stored as a
# {Term(x,x,y,z) : 2, Term(x,y,y) : -1.3, Term() : 1}
# (the keys above are reprs: a Term holds a single variable, and multi-variable
# terms are produced by multiplying Terms, e.g. Term(x) * Term(x) * Term(y))
# Addition of common terms and expansion of exponents occur automatically.
# Given the way `Expr`s are stored, it is easy to access the terms: e.g.
# expr = 2*x*x*y*z - 1.3 x*y*y + 1
# expr[Term(x,x,y,z)] returns 1.3
# expr[Term(x) * Term(x) * Term(y) * Term(z)] returns 1.3
# expr[Term(x)] returns 0.0
#
# On the other hand, when dealing with expressions more general than polynomials,
Expand Down Expand Up @@ -53,7 +55,7 @@ from cpython.long cimport PyLong_Check
from cpython.number cimport PyNumber_Check
from cpython.object cimport Py_LE, Py_EQ, Py_GE, Py_TYPE
from cpython.ref cimport PyObject
from cpython.tuple cimport PyTuple_GET_ITEM
from cpython.tuple cimport PyTuple_GET_ITEM, PyTuple_GET_SIZE
from libc.math cimport cos as c_cos
from libc.math cimport exp as c_exp
from libc.math cimport fabs as c_fabs
Expand All @@ -73,14 +75,24 @@ if TYPE_CHECKING:


cdef class Term:
'''This is a monomial term'''
"""This is a monomial term.

A Term holds a single variable; ``Term()`` (or ``Term(None)``) is the
constant term. Multi-variable terms are produced by multiplying Terms.
"""

cdef readonly tuple vartuple
cdef Py_ssize_t hashval

def __init__(self, *vartuple: Variable):
self.vartuple = tuple(sorted(vartuple, key=lambda v: v.getIndex()))
self.hashval = <Py_ssize_t>hash(tuple(v.ptr() for v in self.vartuple))
def __init__(self, Variable var=None):
if var is None:
# The constant term
self.vartuple = ()
self.hashval = <Py_ssize_t>hash(self.vartuple)
else:
# Avoid sorting single variable
self.vartuple = (var,)
self.hashval = <Py_ssize_t>hash((var.ptr(),))

def __getitem__(self, idx):
return self.vartuple[idx]
Expand All @@ -94,12 +106,12 @@ cdef class Term:
if <type>Py_TYPE(other) is not Term:
return False

cdef int n = len(self)
cdef Py_ssize_t n = PyTuple_GET_SIZE(self.vartuple)
cdef Term _other = <Term>other
if n != len(_other) or self.hashval != _other.hashval:
if n != PyTuple_GET_SIZE(_other.vartuple) or self.hashval != _other.hashval:
return False

cdef int i
cdef Py_ssize_t i
cdef Variable var1, var2
for i in range(n):
var1 = <Variable>PyTuple_GET_ITEM(self.vartuple, i)
Expand All @@ -109,41 +121,49 @@ cdef class Term:
return True

def __len__(self):
return len(self.vartuple)
return PyTuple_GET_SIZE(self.vartuple)

def __mul__(self, Term other):
# NOTE: This merge algorithm requires a sorted `Term.vartuple`.
# This should be ensured in the constructor of Term.
cdef int n1 = len(self)
cdef int n2 = len(other)
cdef Py_ssize_t n1 = PyTuple_GET_SIZE(self.vartuple)
cdef Py_ssize_t n2 = PyTuple_GET_SIZE(other.vartuple)
if n1 == 0: return other
if n2 == 0: return self

cdef list vartuple = [None] * (n1 + n2)
cdef int i = 0, j = 0, k = 0
cdef Py_ssize_t m = n1 + n2
cdef list vartuple = [None] * m
cdef list ptrs = [None] * m
cdef Py_ssize_t i = 0, j = 0, k = 0
cdef Variable var1, var2
while i < n1 and j < n2:
var1 = <Variable>PyTuple_GET_ITEM(self.vartuple, i)
var2 = <Variable>PyTuple_GET_ITEM(other.vartuple, j)
if var1.getIndex() <= var2.getIndex():
vartuple[k] = var1
ptrs[k] = var1.ptr()
i += 1
else:
vartuple[k] = var2
ptrs[k] = var2.ptr()
j += 1
k += 1
while i < n1:
vartuple[k] = <Variable>PyTuple_GET_ITEM(self.vartuple, i)
var1 = <Variable>PyTuple_GET_ITEM(self.vartuple, i)
vartuple[k] = var1
ptrs[k] = var1.ptr()
i += 1
k += 1
while j < n2:
vartuple[k] = <Variable>PyTuple_GET_ITEM(other.vartuple, j)
var2 = <Variable>PyTuple_GET_ITEM(other.vartuple, j)
vartuple[k] = var2
ptrs[k] = var2.ptr()
j += 1
k += 1

cdef Term res = Term.__new__(Term)
res.vartuple = tuple(vartuple)
res.hashval = <Py_ssize_t>hash(tuple(v.ptr() for v in res.vartuple))
res.hashval = <Py_ssize_t>hash(tuple(ptrs))
return res

def __repr__(self) -> str:
Expand All @@ -153,11 +173,11 @@ cdef class Term:
cdef double res = 1.0
cdef SCIP* scip_ptr = sol.scip
cdef SCIP_SOL* sol_ptr = sol.sol
cdef int i = 0, n = len(self)
cdef Py_ssize_t i, n = PyTuple_GET_SIZE(self.vartuple)
cdef Variable var

for i in range(n):
var = <Variable>self.vartuple[i]
var = <Variable>PyTuple_GET_ITEM(self.vartuple, i)
res *= SCIPgetSolVal(scip_ptr, sol_ptr, var.scip_var)
if res == 0: # early stop
return 0.0
Expand Down
3 changes: 3 additions & 0 deletions src/pyscipopt/scip.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -2301,6 +2301,9 @@ cdef class Variable(Expr):
@staticmethod
cdef create(SCIP_VAR* scipvar)

cpdef size_t ptr(self) noexcept
cpdef int getIndex(self) noexcept

cdef class Constraint:
cdef SCIP_CONS* scip_cons
# can be used to store problem data
Expand Down
4 changes: 2 additions & 2 deletions src/pyscipopt/scip.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -1595,7 +1595,7 @@ cdef class Variable(Expr):
cdef Variable copy(self, bint copy=True):
return self

def ptr(self):
cpdef size_t ptr(self) noexcept:
Comment thread
Joao-Dionisio marked this conversation as resolved.
Resolved
return <size_t>(self.scip_var)

def __repr__(self):
Expand Down Expand Up @@ -1730,7 +1730,7 @@ cdef class Variable(Expr):
"""
return SCIPvarIsInLP(self.scip_var)

def getIndex(self):
cpdef int getIndex(self) noexcept:
"""
Retrieve the unique index of the variable.

Expand Down
2 changes: 1 addition & 1 deletion src/pyscipopt/scip.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -2431,7 +2431,7 @@ class SumExpr(GenExpr):
class Term:
@property
def vartuple(self) -> tuple[Variable, ...]: ...
def __init__(self, *vartuple: Variable) -> None: ...
def __init__(self, var: Variable | None = None) -> None: ...
def __mul__(self, other: Term, /) -> Term: ...
def __eq__(self, other: object, /) -> bool: ...
def __ge__(self, other: object, /) -> bool: ...
Expand Down
14 changes: 14 additions & 0 deletions tests/test_expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
GenExpr,
MatrixGenExpr,
ProdExpr,
Term,
)


Expand Down Expand Up @@ -680,3 +681,16 @@ def test_neg():
assert str(neg_expr) == "prod(1.0,sqrt(sum(0.0,prod(1.0,x))))"

assert str(-Constant(3.0)) == "-3.0"


def test_term_constructor(model):
m, x, y, z = model

# No argument and None both denote the constant term.
assert Term() == Term(None) == CONST
assert len(Term(x)) == 1

with pytest.raises(TypeError):
Term(1) # not a Variable
with pytest.raises(TypeError):
Term(x, y) # only a single argument is accepted
12 changes: 6 additions & 6 deletions tests/test_linexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,27 +70,27 @@ def test_operations_quadratic(model):
assert expr[x] == 0.0
assert expr[y] == 0.0
assert expr[CONST] == 0.0
assert expr[Term(x,x)] == 1.0
assert expr[Term(x) * Term(x)] == 1.0

expr = x*y
assert isinstance(expr, Expr)
assert expr[x] == 0.0
assert expr[y] == 0.0
assert expr[CONST] == 0.0
assert expr[Term(x,y)] == 1.0
assert expr[Term(x) * Term(y)] == 1.0

expr = (x - 1)*(y + 1)
assert isinstance(expr, Expr)
assert expr[x] == 1.0
assert expr[y] == -1.0
assert expr[CONST] == -1.0
assert expr[Term(x,y)] == 1.0
assert expr[Term(x) * Term(y)] == 1.0

def test_power_for_quadratic(model):
m, x, y, z = model
expr = x**2 + x + 1
assert isinstance(expr, Expr)
assert expr[Term(x,x)] == 1.0
assert expr[Term(x) * Term(x)] == 1.0
assert expr[x] == 1.0
assert expr[CONST] == 1.0
assert len(expr.terms) == 3
Expand All @@ -105,8 +105,8 @@ def test_operations_poly(model):
assert expr[x] == 0.0
assert expr[y] == 0.0
assert expr[CONST] == 0.0
assert expr[Term(x,x,x)] == 1.0
assert expr[Term(y,y)] == 2.0
assert expr[Term(x) * Term(x) * Term(x)] == 1.0
assert expr[Term(y) * Term(y)] == 2.0
assert expr.terms == (x**3 + 2*y**2).terms

def test_degree(model):
Expand Down
Loading