From 1ae1ca8f08d80b397f817a4cefdc7ef8236834ff Mon Sep 17 00:00:00 2001 From: 40% Date: Thu, 29 Oct 2026 08:05:15 +0800 Subject: [PATCH 01/15] Speed up Term construction for single-variable terms Avoid sorted, the key lambda, and the generator used to build the hash for the common single-variable case by storing the fresh argument tuple directly and hashing the SCIP variable pointer. Handle the constant term explicitly as well. --- CHANGELOG.md | 1 + src/pyscipopt/expr.pxi | 17 +++++++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 29b8597bf..3ac1c7cfb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ - Made expression fields read-only to prevent accidental runtime modification - 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 +- Speed up `Term` construction for single-variable terms - `PowExpr._evaluate` now raises `ValueError("math domain error")` for a negative base with a non-integer exponent and `OverflowError` when the result overflows. ### Removed diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 46414b2ca..c6f96c99b 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -79,8 +79,21 @@ cdef class Term: cdef Py_ssize_t hashval def __init__(self, *vartuple: Variable): - self.vartuple = tuple(sorted(vartuple, key=lambda v: v.getIndex())) - self.hashval = hash(tuple(v.ptr() for v in self.vartuple)) + cdef Py_ssize_t n = len(vartuple) + cdef Variable var + if n == 0: + # The constant term; the empty args tuple is already canonical. + self.vartuple = vartuple + self.hashval = hash(vartuple) + elif n == 1: + # A single variable is trivially sorted, so avoid `sorted` and the + # generator, and build the one-element pointer tuple for the hash. + var = vartuple[0] + self.vartuple = vartuple + self.hashval = hash((var.scip_var,)) + else: + self.vartuple = tuple(sorted(vartuple, key=lambda v: v.getIndex())) + self.hashval = hash(tuple(v.ptr() for v in self.vartuple)) def __getitem__(self, idx): return self.vartuple[idx] From f806404eff4447f120b1124927120d0c43779027 Mon Sep 17 00:00:00 2001 From: 40% Date: Thu, 29 Oct 2026 22:26:42 +0800 Subject: [PATCH 02/15] Make Variable.ptr/getIndex cpdef and tighten Term fast path Expose Variable.ptr() and Variable.getIndex() as cpdef so Cython callers avoid Python dispatch, and reuse them in Term instead of reading scip_var directly. In the single-variable Term path, fetch the variable with PyTuple_GET_ITEM (the *args tuple is exact, so no bounds check is needed) and keep the Variable type check through the cast, so non-Variable arguments still raise TypeError instead of being read as SCIP_VAR*. --- src/pyscipopt/expr.pxi | 14 +++++++++----- src/pyscipopt/scip.pxd | 3 +++ src/pyscipopt/scip.pxi | 4 ++-- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index c6f96c99b..79b560a9c 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -81,16 +81,20 @@ cdef class Term: def __init__(self, *vartuple: Variable): cdef Py_ssize_t n = len(vartuple) cdef Variable var + if n == 0: - # The constant term; the empty args tuple is already canonical. + # The constant term; the empty args tuple is already canonical self.vartuple = vartuple self.hashval = hash(vartuple) + elif n == 1: - # A single variable is trivially sorted, so avoid `sorted` and the - # generator, and build the one-element pointer tuple for the hash. - var = vartuple[0] + # A single variable is trivially sorted, so avoid sorted and the generator. + # `vartuple` is the exact tuple built from *args, so PyTuple_GET_ITEM needs no + # bounds check; the `` cast keeps the Variable type check. + var = PyTuple_GET_ITEM(vartuple, 0) self.vartuple = vartuple - self.hashval = hash((var.scip_var,)) + self.hashval = hash((var.ptr(),)) + else: self.vartuple = tuple(sorted(vartuple, key=lambda v: v.getIndex())) self.hashval = hash(tuple(v.ptr() for v in self.vartuple)) diff --git a/src/pyscipopt/scip.pxd b/src/pyscipopt/scip.pxd index c5053ebba..92e879579 100644 --- a/src/pyscipopt/scip.pxd +++ b/src/pyscipopt/scip.pxd @@ -2284,6 +2284,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 diff --git a/src/pyscipopt/scip.pxi b/src/pyscipopt/scip.pxi index 214b8bad5..019e9eddb 100644 --- a/src/pyscipopt/scip.pxi +++ b/src/pyscipopt/scip.pxi @@ -1562,7 +1562,7 @@ cdef class Variable(Expr): cdef Variable copy(self, bint copy=True): return self - def ptr(self): + cpdef size_t ptr(self) noexcept: return (self.scip_var) def __repr__(self): @@ -1697,7 +1697,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. From 4664651513a0f6858a92ace6a462877da103c816 Mon Sep 17 00:00:00 2001 From: 40% Date: Thu, 29 Oct 2026 22:45:04 +0800 Subject: [PATCH 03/15] Use PyTuple_GET_ITEM in Term._evaluate and Py_ssize_t for indices Term.vartuple only ever holds Variables (guaranteed by __init__ and __mul__), so the unchecked PyTuple_GET_ITEM is safe in _evaluate and matches what __eq__ and __mul__ already do. Take the lengths from len(self.vartuple) instead of len(self), which is a PyObject_Length call dispatching through Term.__len__, and use Py_ssize_t for the lengths and loop counters: list/tuple sizes are Py_ssize_t, and storing them in an int would truncate silently. --- src/pyscipopt/expr.pxi | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 79b560a9c..60934d5f1 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -83,14 +83,14 @@ cdef class Term: cdef Variable var if n == 0: - # The constant term; the empty args tuple is already canonical + # The constant term; the empty args tuple is already canonical. self.vartuple = vartuple self.hashval = hash(vartuple) elif n == 1: # A single variable is trivially sorted, so avoid sorted and the generator. - # `vartuple` is the exact tuple built from *args, so PyTuple_GET_ITEM needs no - # bounds check; the `` cast keeps the Variable type check. + # `vartuple` is the exact tuple built from *args, so PyTuple_GET_ITEM needs + # no bounds check; the `` cast keeps the Variable type check. var = PyTuple_GET_ITEM(vartuple, 0) self.vartuple = vartuple self.hashval = hash((var.ptr(),)) @@ -111,12 +111,12 @@ cdef class Term: if Py_TYPE(other) is not Term: return False - cdef int n = len(self) + cdef Py_ssize_t n = len(self.vartuple) cdef Term _other = other - if n != len(_other) or self.hashval != _other.hashval: + if n != len(_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 = PyTuple_GET_ITEM(self.vartuple, i) @@ -131,13 +131,13 @@ cdef class Term: 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 = len(self.vartuple) + cdef Py_ssize_t n2 = len(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 i = 0, j = 0, k = 0 cdef Variable var1, var2 while i < n1 and j < n2: var1 = PyTuple_GET_ITEM(self.vartuple, i) @@ -170,11 +170,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 = len(self.vartuple) cdef Variable var for i in range(n): - var = self.vartuple[i] + var = PyTuple_GET_ITEM(self.vartuple, i) res *= SCIPgetSolVal(scip_ptr, sol_ptr, var.scip_var) if res == 0: # early stop return 0.0 From f9d1e34bf67ddf72d0943cc46ba6fb8ae929d507 Mon Sep 17 00:00:00 2001 From: 40% Date: Thu, 29 Oct 2026 22:59:41 +0800 Subject: [PATCH 04/15] Build the Term hash during the merge in Term.__mul__ hash(tuple(v.ptr() for v in res.vartuple)) goes through a generator and calls the Python-level Variable.ptr() once per variable. Collect the pointers in the merge loop instead and hash the resulting tuple, which keeps the hash identical to the one Term.__init__ builds for the same variables. --- src/pyscipopt/expr.pxi | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 60934d5f1..6223c66f1 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -136,7 +136,12 @@ cdef class Term: if n1 == 0: return other if n2 == 0: return self - cdef list vartuple = [None] * (n1 + n2) + cdef Py_ssize_t m = n1 + n2 + cdef list vartuple = [None] * m + # The variable pointers are collected during the merge, so the hash can be + # built without a generator that calls the Python-level `Variable.ptr()` + # once per variable. + 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: @@ -144,23 +149,29 @@ cdef class Term: var2 = 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] = PyTuple_GET_ITEM(self.vartuple, i) + var1 = PyTuple_GET_ITEM(self.vartuple, i) + vartuple[k] = var1 + ptrs[k] = var1.ptr() i += 1 k += 1 while j < n2: - vartuple[k] = PyTuple_GET_ITEM(other.vartuple, j) + var2 = 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 = hash(tuple(v.ptr() for v in res.vartuple)) + res.hashval = hash(tuple(ptrs)) return res def __repr__(self) -> str: From fe8433d65173b107be6154c87136780e2de8b544 Mon Sep 17 00:00:00 2001 From: 40% Date: Thu, 29 Oct 2026 23:04:17 +0800 Subject: [PATCH 05/15] Update CHANGELOG for the Term performance changes --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ac1c7cfb..5ff26d702 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ - Made expression fields read-only to prevent accidental runtime modification - 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 -- Speed up `Term` construction for single-variable terms +- Speed up `Term.__init__`, `Term.__eq__`, and `Term.__mul__` 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. ### Removed From 9e9be5775f0e678a942eb4bd3d63c2ed94450c51 Mon Sep 17 00:00:00 2001 From: 40% Date: Fri, 30 Oct 2026 16:13:32 +0800 Subject: [PATCH 06/15] use PyTuple_GET_SIZE replace __len__ --- src/pyscipopt/expr.pxi | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 6223c66f1..ce89f558e 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -53,7 +53,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 @@ -79,7 +79,7 @@ cdef class Term: cdef Py_ssize_t hashval def __init__(self, *vartuple: Variable): - cdef Py_ssize_t n = len(vartuple) + cdef Py_ssize_t n = PyTuple_GET_SIZE(vartuple) cdef Variable var if n == 0: @@ -111,9 +111,9 @@ cdef class Term: if Py_TYPE(other) is not Term: return False - cdef Py_ssize_t n = len(self.vartuple) + cdef Py_ssize_t n = PyTuple_GET_SIZE(self.vartuple) cdef Term _other = other - if n != len(_other.vartuple) or self.hashval != _other.hashval: + if n != PyTuple_GET_SIZE(_other.vartuple) or self.hashval != _other.hashval: return False cdef Py_ssize_t i @@ -126,13 +126,13 @@ 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 Py_ssize_t n1 = len(self.vartuple) - cdef Py_ssize_t n2 = len(other.vartuple) + 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 @@ -181,7 +181,7 @@ cdef class Term: cdef double res = 1.0 cdef SCIP* scip_ptr = sol.scip cdef SCIP_SOL* sol_ptr = sol.sol - cdef Py_ssize_t i, n = len(self.vartuple) + cdef Py_ssize_t i, n = PyTuple_GET_SIZE(self.vartuple) cdef Variable var for i in range(n): From 1b63c1f208f37cfdc1933641123e8ee77459be90 Mon Sep 17 00:00:00 2001 From: 40% Date: Sat, 21 Nov 2026 10:39:26 +0800 Subject: [PATCH 07/15] Apply suggestion from @Joao-Dionisio MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: João Dionísio <57299939+Joao-Dionisio@users.noreply.github.com> --- src/pyscipopt/expr.pxi | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index c860e4fc5..e8183ece6 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -88,9 +88,7 @@ cdef class Term: self.hashval = hash(vartuple) elif n == 1: - # A single variable is trivially sorted, so avoid sorted and the generator. - # `vartuple` is the exact tuple built from *args, so PyTuple_GET_ITEM needs - # no bounds check; the `` cast keeps the Variable type check. + # Avoid sorting single variable var = PyTuple_GET_ITEM(vartuple, 0) self.vartuple = vartuple self.hashval = hash((var.ptr(),)) From 9b15ea156ab007a66f437dcfd34ecebd1e8ada58 Mon Sep 17 00:00:00 2001 From: 40% Date: Sat, 21 Nov 2026 10:39:47 +0800 Subject: [PATCH 08/15] Apply suggestion from @Joao-Dionisio MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: João Dionísio <57299939+Joao-Dionisio@users.noreply.github.com> --- src/pyscipopt/expr.pxi | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index e8183ece6..b87c7480b 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -136,9 +136,6 @@ cdef class Term: cdef Py_ssize_t m = n1 + n2 cdef list vartuple = [None] * m - # The variable pointers are collected during the merge, so the hash can be - # built without a generator that calls the Python-level `Variable.ptr()` - # once per variable. cdef list ptrs = [None] * m cdef Py_ssize_t i = 0, j = 0, k = 0 cdef Variable var1, var2 From 155189ca4bd3fbbd0bb75c86e76257da58eb308f Mon Sep 17 00:00:00 2001 From: 40% Date: Sat, 21 Nov 2026 10:41:25 +0800 Subject: [PATCH 09/15] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b4bdb5643..30e176848 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,7 +25,7 @@ - Expression fields now use concrete Cython types (`double`/`list`), so values are converted on construction - 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 -- Speed up `Term.__init__`, `Term.__eq__`, and `Term.__mul__` via the C-level API +- Add shortcut path for `Term()` and `Term(x)`to speed up `Term.__init__`, `Term.__eq__`, and `Term.__mul__` - `PowExpr._evaluate` now raises `ValueError("math domain error")` for a negative base with a non-integer exponent and `OverflowError` when the result overflows. ### Removed - Removed support for Python 3.8 From 35600c68c0e5187e85d5e890d8da2ce94b107ac3 Mon Sep 17 00:00:00 2001 From: 40% Date: Sat, 21 Nov 2026 11:21:21 +0800 Subject: [PATCH 10/15] Fix segfault when Term() receives a non-Variable argument The *args items are not type-checked by Cython, and assigning None to a cdef class variable is allowed (it stores Py_None), so Term(None) stored Py_None in a Variable variable and crashed in var.ptr(), which dispatches through the vtab pointer read from the Py_None object. Validate the arguments up front and raise TypeError, matching the error already raised for other non-Variable arguments. The single-variable fast path can then use an unchecked cast. Add a regression test covering None and non-Variable arguments. --- src/pyscipopt/expr.pxi | 12 ++++++++++-- tests/test_expr.py | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index b87c7480b..2edd2f20b 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -79,8 +79,16 @@ cdef class Term: cdef Py_ssize_t hashval def __init__(self, *vartuple: Variable): - cdef Py_ssize_t n = PyTuple_GET_SIZE(vartuple) + cdef i, Py_ssize_t n = PyTuple_GET_SIZE(vartuple) cdef Variable var + cdef object item + + for i in range(n): + item = PyTuple_GET_ITEM(vartuple, i) + if not isinstance(item, Variable): + raise TypeError( + f"Term() arguments must be Variable, got {type(item).__name__}" + ) if n == 0: # The constant term; the empty args tuple is already canonical. @@ -89,7 +97,7 @@ cdef class Term: elif n == 1: # Avoid sorting single variable - var = PyTuple_GET_ITEM(vartuple, 0) + var = PyTuple_GET_ITEM(vartuple, 0) self.vartuple = vartuple self.hashval = hash((var.ptr(),)) diff --git a/tests/test_expr.py b/tests/test_expr.py index 64d007572..000aebed3 100644 --- a/tests/test_expr.py +++ b/tests/test_expr.py @@ -12,6 +12,7 @@ GenExpr, MatrixGenExpr, ProdExpr, + Term, ) @@ -680,3 +681,21 @@ 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_rejects_non_variable_arguments(model): + m, x, y, z = model + + with pytest.raises(TypeError, match="must be Variable"): + Term(None) + with pytest.raises(TypeError, match="must be Variable"): + Term(1) + with pytest.raises(TypeError, match="must be Variable"): + Term(x, None) + with pytest.raises(TypeError, match="must be Variable"): + Term(None, x) + + # Valid constructions are unaffected. + assert len(Term()) == 0 + assert len(Term(x)) == 1 + assert Term(x, y) == Term(y, x) From 2ac6968779a9429b049d232a70c93b50e5d0b415 Mon Sep 17 00:00:00 2001 From: 40% Date: Sat, 21 Nov 2026 11:23:23 +0800 Subject: [PATCH 11/15] correct the type --- src/pyscipopt/expr.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 2edd2f20b..1ff7816da 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -79,7 +79,7 @@ cdef class Term: cdef Py_ssize_t hashval def __init__(self, *vartuple: Variable): - cdef i, Py_ssize_t n = PyTuple_GET_SIZE(vartuple) + cdef Py_ssize_t i, n = PyTuple_GET_SIZE(vartuple) cdef Variable var cdef object item From f106bd2cc20c3602c6b39afba49a645443e471aa Mon Sep 17 00:00:00 2001 From: 40% Date: Sun, 22 Nov 2026 16:27:12 +0800 Subject: [PATCH 12/15] Update Term stub and tests for single-argument constructor - scip.pyi: Term.__init__ takes var: Variable | None = None - tests: rename to test_term_constructor, cover Term(None) == CONST and the type/arity errors - expr.pxi: document that multi-variable Terms are produced by multiplication --- CHANGELOG.md | 3 ++- src/pyscipopt/expr.pxi | 39 ++++++++++++++------------------------- src/pyscipopt/scip.pyi | 2 +- tests/test_expr.py | 21 ++++++++------------- tests/test_linexpr.py | 12 ++++++------ 5 files changed, 31 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 30e176848..31dcdd0f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,8 +25,9 @@ - Expression fields now use concrete Cython types (`double`/`list`), so values are converted on construction - 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 -- Add shortcut path for `Term()` and `Term(x)`to speed up `Term.__init__`, `Term.__eq__`, and `Term.__mul__` - `PowExpr._evaluate` now raises `ValueError("math domain error")` for a negative base with a non-integer exponent and `OverflowError` when the result overflows. +- Add shortcut path for `Term()` and `Term(x)` to speed up `Term.__init__`, `Term.__eq__`, and `Term.__mul__` +- `Term` now accepts a single argument (`Variable` or `None`) instead of multiple arguments ### Removed - Removed support for Python 3.8 diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 1ff7816da..41d056c19 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -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, @@ -73,38 +75,25 @@ 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): - cdef Py_ssize_t i, n = PyTuple_GET_SIZE(vartuple) - cdef Variable var - cdef object item - - for i in range(n): - item = PyTuple_GET_ITEM(vartuple, i) - if not isinstance(item, Variable): - raise TypeError( - f"Term() arguments must be Variable, got {type(item).__name__}" - ) - - if n == 0: + def __init__(self, Variable var=None): + if var is None: # The constant term; the empty args tuple is already canonical. - self.vartuple = vartuple - self.hashval = hash(vartuple) - - elif n == 1: + self.vartuple = () + self.hashval = hash(self.vartuple) + else: # Avoid sorting single variable - var = PyTuple_GET_ITEM(vartuple, 0) - self.vartuple = vartuple + self.vartuple = (var,) self.hashval = hash((var.ptr(),)) - else: - self.vartuple = tuple(sorted(vartuple, key=lambda v: v.getIndex())) - self.hashval = hash(tuple(v.ptr() for v in self.vartuple)) - def __getitem__(self, idx): return self.vartuple[idx] diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index d3b46e794..a83baa645 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -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: ... diff --git a/tests/test_expr.py b/tests/test_expr.py index 000aebed3..2976c253e 100644 --- a/tests/test_expr.py +++ b/tests/test_expr.py @@ -683,19 +683,14 @@ def test_neg(): assert str(-Constant(3.0)) == "-3.0" -def test_term_rejects_non_variable_arguments(model): +def test_term_constructor(model): m, x, y, z = model - with pytest.raises(TypeError, match="must be Variable"): - Term(None) - with pytest.raises(TypeError, match="must be Variable"): - Term(1) - with pytest.raises(TypeError, match="must be Variable"): - Term(x, None) - with pytest.raises(TypeError, match="must be Variable"): - Term(None, x) - - # Valid constructions are unaffected. - assert len(Term()) == 0 + # No argument and None both denote the constant term. + assert Term() == Term(None) == CONST assert len(Term(x)) == 1 - assert Term(x, y) == Term(y, x) + + with pytest.raises(TypeError): + Term(1) # not a Variable + with pytest.raises(TypeError): + Term(x, y) # only a single argument is accepted diff --git a/tests/test_linexpr.py b/tests/test_linexpr.py index f7eb54281..cb7d9aae8 100644 --- a/tests/test_linexpr.py +++ b/tests/test_linexpr.py @@ -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 @@ -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): From 9d67861383489f851c253314d0c7dbc9bf785d44 Mon Sep 17 00:00:00 2001 From: 40% Date: Sun, 22 Nov 2026 16:33:42 +0800 Subject: [PATCH 13/15] single quote to double quotes --- src/pyscipopt/expr.pxi | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 41d056c19..253a993b3 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -75,11 +75,11 @@ 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 From fbd3ea3e6a7f9b07f66b44fe07439dbf855e8d29 Mon Sep 17 00:00:00 2001 From: 40% Date: Sun, 22 Nov 2026 16:34:40 +0800 Subject: [PATCH 14/15] simple a bit --- src/pyscipopt/expr.pxi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 253a993b3..09601e59a 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -86,7 +86,7 @@ cdef class Term: def __init__(self, Variable var=None): if var is None: - # The constant term; the empty args tuple is already canonical. + # The constant term self.vartuple = () self.hashval = hash(self.vartuple) else: From f8c1233f2a870cd9fa08791d1691614654424055 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Dion=C3=ADsio?= <57299939+Joao-Dionisio@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:01:01 +0000 Subject: [PATCH 15/15] Apply suggestion from @Joao-Dionisio --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 31dcdd0f2..d4fb44353 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,7 +26,7 @@ - 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. -- Add shortcut path for `Term()` and `Term(x)` to speed up `Term.__init__`, `Term.__eq__`, and `Term.__mul__` +- 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