From eb78de436f3e96c6d08564ec31dc02884c1433de Mon Sep 17 00:00:00 2001 From: 40% Date: Sun, 14 Jun 2026 11:30:44 +0800 Subject: [PATCH 01/36] wrap "" for error message --- 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 62f0c880d..97be7fee8 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -200,7 +200,7 @@ cdef class ExprLike: ): if kwargs.get("out", None) is not None: raise TypeError( - f"{self.__class__.__name__} doesn't support the 'out' parameter in __array_ufunc__" + f"{self.__class__.__name__!s} doesn't support the 'out' parameter in __array_ufunc__" ) if method == "__call__": From 146dc11dfbb5e9a7c333ea12d98cd2b919a62405 Mon Sep 17 00:00:00 2001 From: 40% Date: Sun, 14 Jun 2026 11:52:55 +0800 Subject: [PATCH 02/36] Split `Variable` and `Expr` into two classes --- src/pyscipopt/expr.pxi | 88 ++++++++++++++++++++++++++++-------------- src/pyscipopt/scip.pxd | 6 +-- src/pyscipopt/scip.pxi | 25 ++++++++---- src/pyscipopt/scip.pyi | 31 ++++++--------- 4 files changed, 91 insertions(+), 59 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 97be7fee8..8148120b4 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -257,44 +257,72 @@ cdef class ExprLike: return NotImplemented + def __add__(self, other, /): + return self._as_expr() + other + def __radd__(self, other, /): - return self + other + return self._as_expr() + other def __sub__(self, other, /): - return self + (-other) + return self._as_expr() + (-other) def __rsub__(self, other, /): - return (-self) + other + return (-self._as_expr()) + other + + def __mul__(self, other, /): + return self._as_expr() * other def __rmul__(self, other, /): - return self * other + return self._as_expr() * other + + def __truediv__(self, other, /): + return self._as_expr() / other def __rtruediv__(self, other, /) -> GenExpr: - return buildGenExprObj(other) / self + return buildGenExprObj(other) / self._as_expr() + + def __pow__(self, other, /): + return self._as_expr() ** other + + def __rpow__(self, other, /): + return other ** self._as_expr() def __richcmp__(self, other, int op): - return _expr_richcmp(self, other, op) + return _expr_richcmp(self._as_expr(), other, op) def __neg__(self, /) -> Union[Expr, GenExpr]: - return self * -1.0 + return self._as_expr() * -1.0 + + def __abs__(self, /) -> GenExpr: + return UnaryExpr(Operator.fabs, buildGenExprObj(self._as_expr())) + + def exp(self, /) -> GenExpr: + return UnaryExpr(Operator.exp, buildGenExprObj(self._as_expr())) + + def log(self, /) -> GenExpr: + return UnaryExpr(Operator.log, buildGenExprObj(self._as_expr())) - def __abs__(self) -> GenExpr: - return UnaryExpr(Operator.fabs, buildGenExprObj(self)) + def sqrt(self, /) -> GenExpr: + return UnaryExpr(Operator.sqrt, buildGenExprObj(self._as_expr())) - def exp(self) -> GenExpr: - return UnaryExpr(Operator.exp, buildGenExprObj(self)) + def sin(self, /) -> GenExpr: + return UnaryExpr(Operator.sin, buildGenExprObj(self._as_expr())) - def log(self) -> GenExpr: - return UnaryExpr(Operator.log, buildGenExprObj(self)) + def cos(self, /) -> GenExpr: + return UnaryExpr(Operator.cos, buildGenExprObj(self._as_expr())) - def sqrt(self) -> GenExpr: - return UnaryExpr(Operator.sqrt, buildGenExprObj(self)) + def degree(self, /) -> float: + return self._as_expr().degree() - def sin(self) -> GenExpr: - return UnaryExpr(Operator.sin, buildGenExprObj(self)) + cpdef double _evaluate(self, Solution sol) except *: + raise NotImplementedError( + f"{self.__class__.__name__!s} need to implement _evaluate() method" + ) - def cos(self) -> GenExpr: - return UnaryExpr(Operator.cos, buildGenExprObj(self)) + cdef ExprLike _as_expr(self): + raise NotImplementedError( + f"{self.__class__.__name__!s} need to implement _as_expr() method" + ) ##@details Polynomial expressions of variables with operator overloading. \n @@ -310,6 +338,9 @@ cdef class Expr(ExprLike): if len(self.terms) == 0: self.terms[CONST] = 0.0 + cdef Expr _as_expr(self): + return self + def __getitem__(self, key): if not isinstance(key, Term): key = Term(key) @@ -318,7 +349,7 @@ cdef class Expr(ExprLike): def __iter__(self): return iter(self.terms) - def __add__(self, other): + def __add__(self, other, /): if not _is_expr_compatible(other): return NotImplemented @@ -384,7 +415,7 @@ cdef class Expr(ExprLike): return NotImplemented return super().__rtruediv__(other) - def __pow__(self, other, modulo): + def __pow__(self, other): if float(other).is_integer() and other >= 0: exp = int(other) else: # need to transform to GenExpr @@ -414,12 +445,8 @@ cdef class Expr(ExprLike): def __repr__(self): return 'Expr(%s)' % repr(self.terms) - def degree(self): - '''computes highest degree of terms''' - if len(self.terms) == 0: - return 0 - else: - return max(len(v) for v in self.terms) + def degree(self, /) -> float: + return max((i.degree() for i in self)) if self else 0 cpdef double _evaluate(self, Solution sol) except *: cdef double res = 0 @@ -547,6 +574,9 @@ cdef class GenExpr(ExprLike): def __init__(self): # do we need it ''' ''' + cdef GenExpr _as_expr(self): + return self + def __add__(self, other): if not _is_genexpr_compatible(other): return NotImplemented @@ -655,7 +685,7 @@ cdef class GenExpr(ExprLike): # self.children.append(right) # return self - def __pow__(self, other, modulo): + def __pow__(self, other): expo = buildGenExprObj(other) if expo.getOp() != Operator.const: raise NotImplementedError("exponents must be numbers") @@ -695,7 +725,7 @@ cdef class GenExpr(ExprLike): return NotImplemented return super().__rtruediv__(other) - def degree(self): + def degree(self, /) -> float: '''Note: none of these expressions should be polynomial''' return float('inf') diff --git a/src/pyscipopt/scip.pxd b/src/pyscipopt/scip.pxd index 9ff2979e7..8b5303f1d 100644 --- a/src/pyscipopt/scip.pxd +++ b/src/pyscipopt/scip.pxd @@ -2151,13 +2151,13 @@ cdef extern from "tpi/tpi.h": int SCIPtpiGetNumThreads() cdef class ExprLike: - pass + + cdef ExprLike _as_expr(self) + cpdef double _evaluate(self, Solution sol) cdef class Expr(ExprLike): cdef public terms - cpdef double _evaluate(self, Solution sol) - cdef class Event: cdef SCIP_EVENT* event # can be used to store problem data diff --git a/src/pyscipopt/scip.pxi b/src/pyscipopt/scip.pxi index 45f0ccf9e..714e182e1 100644 --- a/src/pyscipopt/scip.pxi +++ b/src/pyscipopt/scip.pxi @@ -1530,17 +1530,22 @@ cdef class Node: return (self.__class__ == other.__class__ and self.scip_node == (other).scip_node) -cdef class Variable(Expr): - """Is a linear expression and has SCIP_VAR*""" +cdef class Variable(ExprLike): + + def __init__(self, *_): + raise NotImplementedError( + "Direct instantiation of 'Variable' is not supported. " + "Please use Model to create variables." + ) @staticmethod - cdef create(SCIP_VAR* scipvar): + cdef create(SCIP_VAR* scip_var): """ Main method for creating a Variable class. Is used instead of __init__. Parameters ---------- - scipvar : SCIP_VAR* + scip_var : SCIP_VAR* A pointer to the SCIP_VAR Returns @@ -1549,11 +1554,12 @@ cdef class Variable(Expr): The Python representative of the SCIP_VAR """ - if scipvar == NULL: + if scip_var == NULL: raise Warning("cannot create Variable with SCIP_VAR* == NULL") - var = Variable() - var.scip_var = scipvar - Expr.__init__(var, {Term(var) : 1.0}) + + cdef Variable var = Variable.__new__(Variable) + var.scip_var = scip_var + var._expr_view = Expr({Term(var): 1.0}) return var property name: @@ -1569,6 +1575,9 @@ cdef class Variable(Expr): def __repr__(self): return self.name + cdef Variable _as_expr(self): + return self._expr_view + def vtype(self): """ Retrieve the variables type (BINARY, INTEGER, CONTINUOUS, or IMPLINT) diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index 86196cfc1..1973075aa 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -332,26 +332,30 @@ class ExprLike: *args: Incomplete, **kwargs: Incomplete, ) -> Incomplete: ... + def __add__(self, other: object, /) -> Incomplete: ... def __radd__(self, other: object, /) -> Incomplete: ... def __sub__(self, other: object, /) -> Incomplete: ... def __rsub__(self, other: object, /) -> Incomplete: ... + def __mul__(self, other: object, /) -> Incomplete: ... def __rmul__(self, other: object, /) -> Incomplete: ... + def __truediv__(self, other: object, /) -> Incomplete: ... def __rtruediv__(self, other: object, /) -> GenExpr: ... + def __pow__(self, other: object, /) -> Incomplete: ... + def __rpow__(self, other: object, /) -> Incomplete: ... def __neg__(self, /) -> Union[Expr, GenExpr]: ... - def __abs__(self) -> GenExpr: ... - def exp(self) -> GenExpr: ... - def log(self) -> GenExpr: ... - def sqrt(self) -> GenExpr: ... - def sin(self) -> GenExpr: ... - def cos(self) -> GenExpr: ... + def __abs__(self, /) -> GenExpr: ... + def exp(self, /) -> GenExpr: ... + def log(self, /) -> GenExpr: ... + def sqrt(self, /) -> GenExpr: ... + def sin(self, /) -> GenExpr: ... + def cos(self, /) -> GenExpr: ... + def degree(self, /) -> float: ... @disjoint_base class Expr(ExprLike): terms: Incomplete def __init__(self, terms: Incomplete = ...) -> None: ... - def degree(self) -> Incomplete: ... def normalize(self) -> Incomplete: ... - def __add__(self, other: Incomplete, /) -> Incomplete: ... def __eq__(self, other: object, /) -> bool: ... def __ge__(self, other: object, /) -> bool: ... def __getitem__(self, index: Incomplete, /) -> Incomplete: ... @@ -360,11 +364,7 @@ class Expr(ExprLike): def __iter__(self) -> Incomplete: ... def __le__(self, other: object, /) -> bool: ... def __lt__(self, other: object, /) -> bool: ... - def __mul__(self, other: Incomplete, /) -> Incomplete: ... def __ne__(self, other: object, /) -> bool: ... - def __pow__(self, other: Incomplete, modulo: Incomplete = ..., /) -> Incomplete: ... - def __rpow__(self, other: Incomplete, /) -> Incomplete: ... - def __truediv__(self, other: Incomplete, /) -> Incomplete: ... @disjoint_base class ExprCons: @@ -388,19 +388,12 @@ class GenExpr(ExprLike): _op: Incomplete children: Incomplete def __init__(self) -> None: ... - def degree(self) -> Incomplete: ... def getOp(self) -> Incomplete: ... - def __add__(self, other: Incomplete, /) -> Incomplete: ... def __eq__(self, other: object, /) -> bool: ... def __ge__(self, other: object, /) -> bool: ... def __gt__(self, other: object, /) -> bool: ... def __le__(self, other: object, /) -> bool: ... def __lt__(self, other: object, /) -> bool: ... - def __mul__(self, other: Incomplete, /) -> Incomplete: ... - def __ne__(self, other: object, /) -> bool: ... - def __pow__(self, other: Incomplete, modulo: Incomplete = ..., /) -> Incomplete: ... - def __rpow__(self, other: Incomplete, /) -> Incomplete: ... - def __truediv__(self, other: Incomplete, /) -> Incomplete: ... @disjoint_base class Heur: From f7d2b96d15f5657ec3de23d77896512faa5a67d9 Mon Sep 17 00:00:00 2001 From: 40% Date: Sun, 14 Jun 2026 11:55:56 +0800 Subject: [PATCH 03/36] force magic methods to use positional keywords --- src/pyscipopt/expr.pxi | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 8148120b4..a888ae02b 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -360,7 +360,7 @@ cdef class Expr(ExprLike): return Expr(_to_dict(self, other, copy=True)) - def __iadd__(self, other): + def __iadd__(self, other, /): if not _is_expr_compatible(other): return NotImplemented @@ -371,7 +371,7 @@ cdef class Expr(ExprLike): return self - def __mul__(self, other): + def __mul__(self, other, /): if not _is_expr_compatible(other): return NotImplemented @@ -402,7 +402,7 @@ cdef class Expr(ExprLike): res[child] = coef return Expr(res) - def __truediv__(self, other): + def __truediv__(self, other, /): if not _is_expr_compatible(other): return NotImplemented @@ -415,7 +415,7 @@ cdef class Expr(ExprLike): return NotImplemented return super().__rtruediv__(other) - def __pow__(self, other): + def __pow__(self, other, /): if float(other).is_integer() and other >= 0: exp = int(other) else: # need to transform to GenExpr @@ -426,7 +426,7 @@ cdef class Expr(ExprLike): res *= self return res - def __rpow__(self, other): + def __rpow__(self, other, /): """ Implements base**x as scip.exp(x * scip.log(base)). Note: base must be positive. @@ -577,7 +577,7 @@ cdef class GenExpr(ExprLike): cdef GenExpr _as_expr(self): return self - def __add__(self, other): + def __add__(self, other, /): if not _is_genexpr_compatible(other): return NotImplemented @@ -635,7 +635,7 @@ cdef class GenExpr(ExprLike): # self.children.append(right) # return self - def __mul__(self, other): + def __mul__(self, other, /): if not _is_genexpr_compatible(other): return NotImplemented @@ -685,7 +685,7 @@ cdef class GenExpr(ExprLike): # self.children.append(right) # return self - def __pow__(self, other): + def __pow__(self, other, /): expo = buildGenExprObj(other) if expo.getOp() != Operator.const: raise NotImplementedError("exponents must be numbers") @@ -697,7 +697,7 @@ cdef class GenExpr(ExprLike): return ans - def __rpow__(self, other): + def __rpow__(self, other, /): """ Implements base**x as scip.exp(x * scip.log(base)). Note: base must be positive. @@ -710,7 +710,7 @@ cdef class GenExpr(ExprLike): return (self * Constant(base).log()).exp() #TODO: ipow, idiv, etc - def __truediv__(self,other): + def __truediv__(self,other, /): if not _is_genexpr_compatible(other): return NotImplemented From 798e8cec94dcd6690be6ec1a8df6ce4e84f97735 Mon Sep 17 00:00:00 2001 From: 40% Date: Sun, 14 Jun 2026 12:10:37 +0800 Subject: [PATCH 04/36] Revert changes to `Expr.degree` --- src/pyscipopt/expr.pxi | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index a888ae02b..c4c270a02 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -445,8 +445,12 @@ cdef class Expr(ExprLike): def __repr__(self): return 'Expr(%s)' % repr(self.terms) - def degree(self, /) -> float: - return max((i.degree() for i in self)) if self else 0 + def degree(self, /) -> int: + '''computes highest degree of terms''' + if len(self.terms) == 0: + return 0 + else: + return max(len(v) for v in self.terms) cpdef double _evaluate(self, Solution sol) except *: cdef double res = 0 From 6f0e75814b0e713914f913cebb526dfb152acc72 Mon Sep 17 00:00:00 2001 From: 40% Date: Sun, 14 Jun 2026 16:01:29 +0800 Subject: [PATCH 05/36] convert `normalize` into cdef function --- src/pyscipopt/expr.pxi | 24 +++++++++++++++--------- src/pyscipopt/scip.pxd | 1 + src/pyscipopt/scip.pyi | 2 -- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index c4c270a02..30a66d5c0 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -314,14 +314,17 @@ cdef class ExprLike: def degree(self, /) -> float: return self._as_expr().degree() - cpdef double _evaluate(self, Solution sol) except *: + cdef ExprLike _as_expr(self): raise NotImplementedError( - f"{self.__class__.__name__!s} need to implement _evaluate() method" + f"{self.__class__.__name__!s} need to implement _as_expr() method" ) - cdef ExprLike _as_expr(self): + cdef void normalize(self): + self._as_expr().normalize() + + cpdef double _evaluate(self, Solution sol) except *: raise NotImplementedError( - f"{self.__class__.__name__!s} need to implement _as_expr() method" + f"{self.__class__.__name__!s} need to implement _evaluate() method" ) @@ -438,10 +441,6 @@ cdef class Expr(ExprLike): raise ValueError("Base of a**x must be positive, as expression is reformulated to scip.exp(x * scip.log(a)); got %g" % base) return (self * Constant(base).log()).exp() - def normalize(self): - '''remove terms with coefficient of 0''' - self.terms = {t:c for (t,c) in self.terms.items() if c != 0.0} - def __repr__(self): return 'Expr(%s)' % repr(self.terms) @@ -452,6 +451,10 @@ cdef class Expr(ExprLike): else: return max(len(v) for v in self.terms) + cdef void normalize(self): + '''remove terms with coefficient of 0''' + self.terms = {t:c for (t,c) in self.terms.items() if c != 0.0} + cpdef double _evaluate(self, Solution sol) except *: cdef double res = 0 cdef Py_ssize_t pos = 0 @@ -480,7 +483,7 @@ cdef class ExprCons: assert not (lhs is None and rhs is None) self.normalize() - def normalize(self): + cdef void normalize(self): '''move constant terms in expression to bounds''' if isinstance(self.expr, Expr): c = self.expr[CONST] @@ -751,6 +754,9 @@ cdef class GenExpr(ExprLike): (res).expo = (self).expo return res + cdef void normalize(self): + ... + # Sum Expressions cdef class SumExpr(GenExpr): diff --git a/src/pyscipopt/scip.pxd b/src/pyscipopt/scip.pxd index 8b5303f1d..4beaf5152 100644 --- a/src/pyscipopt/scip.pxd +++ b/src/pyscipopt/scip.pxd @@ -2153,6 +2153,7 @@ cdef extern from "tpi/tpi.h": cdef class ExprLike: cdef ExprLike _as_expr(self) + cdef void normalize(self) cpdef double _evaluate(self, Solution sol) cdef class Expr(ExprLike): diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index 1973075aa..372ddac8f 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -355,7 +355,6 @@ class ExprLike: class Expr(ExprLike): terms: Incomplete def __init__(self, terms: Incomplete = ...) -> None: ... - def normalize(self) -> Incomplete: ... def __eq__(self, other: object, /) -> bool: ... def __ge__(self, other: object, /) -> bool: ... def __getitem__(self, index: Incomplete, /) -> Incomplete: ... @@ -374,7 +373,6 @@ class ExprCons: def __init__( self, expr: Incomplete, lhs: Incomplete = ..., rhs: Incomplete = ... ) -> None: ... - def normalize(self) -> Incomplete: ... def __bool__(self) -> bool: ... def __eq__(self, other: object, /) -> bool: ... def __ge__(self, other: object, /) -> bool: ... From 582f1e8c6e9e5643709e7346a0b989807d933e7e Mon Sep 17 00:00:00 2001 From: 40% Date: Sun, 14 Jun 2026 16:03:53 +0800 Subject: [PATCH 06/36] rename `_as_expr` to `as_expr` --- src/pyscipopt/expr.pxi | 48 +++++++++++++++++++++--------------------- src/pyscipopt/scip.pxd | 2 +- src/pyscipopt/scip.pxi | 2 +- 3 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 30a66d5c0..6c14721a8 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -258,69 +258,69 @@ cdef class ExprLike: return NotImplemented def __add__(self, other, /): - return self._as_expr() + other + return self.as_expr() + other def __radd__(self, other, /): - return self._as_expr() + other + return self.as_expr() + other def __sub__(self, other, /): - return self._as_expr() + (-other) + return self.as_expr() + (-other) def __rsub__(self, other, /): - return (-self._as_expr()) + other + return (-self.as_expr()) + other def __mul__(self, other, /): - return self._as_expr() * other + return self.as_expr() * other def __rmul__(self, other, /): - return self._as_expr() * other + return self.as_expr() * other def __truediv__(self, other, /): - return self._as_expr() / other + return self.as_expr() / other def __rtruediv__(self, other, /) -> GenExpr: - return buildGenExprObj(other) / self._as_expr() + return buildGenExprObj(other) / self.as_expr() def __pow__(self, other, /): - return self._as_expr() ** other + return self.as_expr() ** other def __rpow__(self, other, /): - return other ** self._as_expr() + return other ** self.as_expr() def __richcmp__(self, other, int op): - return _expr_richcmp(self._as_expr(), other, op) + return _expr_richcmp(self.as_expr(), other, op) def __neg__(self, /) -> Union[Expr, GenExpr]: - return self._as_expr() * -1.0 + return self.as_expr() * -1.0 def __abs__(self, /) -> GenExpr: - return UnaryExpr(Operator.fabs, buildGenExprObj(self._as_expr())) + return UnaryExpr(Operator.fabs, buildGenExprObj(self.as_expr())) def exp(self, /) -> GenExpr: - return UnaryExpr(Operator.exp, buildGenExprObj(self._as_expr())) + return UnaryExpr(Operator.exp, buildGenExprObj(self.as_expr())) def log(self, /) -> GenExpr: - return UnaryExpr(Operator.log, buildGenExprObj(self._as_expr())) + return UnaryExpr(Operator.log, buildGenExprObj(self.as_expr())) def sqrt(self, /) -> GenExpr: - return UnaryExpr(Operator.sqrt, buildGenExprObj(self._as_expr())) + return UnaryExpr(Operator.sqrt, buildGenExprObj(self.as_expr())) def sin(self, /) -> GenExpr: - return UnaryExpr(Operator.sin, buildGenExprObj(self._as_expr())) + return UnaryExpr(Operator.sin, buildGenExprObj(self.as_expr())) def cos(self, /) -> GenExpr: - return UnaryExpr(Operator.cos, buildGenExprObj(self._as_expr())) + return UnaryExpr(Operator.cos, buildGenExprObj(self.as_expr())) def degree(self, /) -> float: - return self._as_expr().degree() + return self.as_expr().degree() - cdef ExprLike _as_expr(self): + cdef ExprLike as_expr(self): raise NotImplementedError( - f"{self.__class__.__name__!s} need to implement _as_expr() method" + f"{self.__class__.__name__!s} need to implement as_expr() method" ) cdef void normalize(self): - self._as_expr().normalize() + self.as_expr().normalize() cpdef double _evaluate(self, Solution sol) except *: raise NotImplementedError( @@ -341,7 +341,7 @@ cdef class Expr(ExprLike): if len(self.terms) == 0: self.terms[CONST] = 0.0 - cdef Expr _as_expr(self): + cdef Expr as_expr(self): return self def __getitem__(self, key): @@ -581,7 +581,7 @@ cdef class GenExpr(ExprLike): def __init__(self): # do we need it ''' ''' - cdef GenExpr _as_expr(self): + cdef GenExpr as_expr(self): return self def __add__(self, other, /): diff --git a/src/pyscipopt/scip.pxd b/src/pyscipopt/scip.pxd index 4beaf5152..c8b4c729f 100644 --- a/src/pyscipopt/scip.pxd +++ b/src/pyscipopt/scip.pxd @@ -2152,7 +2152,7 @@ cdef extern from "tpi/tpi.h": cdef class ExprLike: - cdef ExprLike _as_expr(self) + cdef ExprLike as_expr(self) cdef void normalize(self) cpdef double _evaluate(self, Solution sol) diff --git a/src/pyscipopt/scip.pxi b/src/pyscipopt/scip.pxi index 714e182e1..82abd1e8a 100644 --- a/src/pyscipopt/scip.pxi +++ b/src/pyscipopt/scip.pxi @@ -1575,7 +1575,7 @@ cdef class Variable(ExprLike): def __repr__(self): return self.name - cdef Variable _as_expr(self): + cdef Variable as_expr(self): return self._expr_view def vtype(self): From 5100c48adb3e990c201d99416d7d48177d7ae465 Mon Sep 17 00:00:00 2001 From: 40% Date: Sun, 14 Jun 2026 16:17:44 +0800 Subject: [PATCH 07/36] ExprLike support `__getitem__` and `__iter__` --- src/pyscipopt/expr.pxi | 26 ++++++++++++++++---------- src/pyscipopt/scip.pxd | 2 +- src/pyscipopt/scip.pyi | 4 ++-- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 6c14721a8..0d014c298 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -243,7 +243,7 @@ cdef class ExprLike: elif ufunc is np.equal: return args[0] == args[1] elif ufunc is np.absolute: - return args[0].__abs__() + return abs(args[0]) elif ufunc is np.exp: return args[0].exp() elif ufunc is np.log: @@ -257,6 +257,12 @@ cdef class ExprLike: return NotImplemented + def __getitem__(self, key): + return self.as_expr()[key] + + def __iter__(self): + return iter(self.as_expr()) + def __add__(self, other, /): return self.as_expr() + other @@ -341,9 +347,6 @@ cdef class Expr(ExprLike): if len(self.terms) == 0: self.terms[CONST] = 0.0 - cdef Expr as_expr(self): - return self - def __getitem__(self, key): if not isinstance(key, Term): key = Term(key) @@ -451,6 +454,9 @@ cdef class Expr(ExprLike): else: return max(len(v) for v in self.terms) + cdef Expr as_expr(self): + return self + cdef void normalize(self): '''remove terms with coefficient of 0''' self.terms = {t:c for (t,c) in self.terms.items() if c != 0.0} @@ -581,9 +587,6 @@ cdef class GenExpr(ExprLike): def __init__(self): # do we need it ''' ''' - cdef GenExpr as_expr(self): - return self - def __add__(self, other, /): if not _is_genexpr_compatible(other): return NotImplemented @@ -740,6 +743,12 @@ cdef class GenExpr(ExprLike): '''returns operator of GenExpr''' return self._op + cdef GenExpr as_expr(self): + return self + + cdef void normalize(self): + ... + cdef GenExpr copy(self, bool copy = True): cdef object cls = Py_TYPE(self) cdef GenExpr res = cls.__new__(cls) @@ -754,9 +763,6 @@ cdef class GenExpr(ExprLike): (res).expo = (self).expo return res - cdef void normalize(self): - ... - # Sum Expressions cdef class SumExpr(GenExpr): diff --git a/src/pyscipopt/scip.pxd b/src/pyscipopt/scip.pxd index c8b4c729f..3b9750d69 100644 --- a/src/pyscipopt/scip.pxd +++ b/src/pyscipopt/scip.pxd @@ -2235,7 +2235,7 @@ cdef class Node: @staticmethod cdef create(SCIP_NODE* scipnode) -cdef class Variable(Expr): +cdef class Variable(ExprLike): cdef SCIP_VAR* scip_var # can be used to store problem data cdef public object data diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index 372ddac8f..70f705d50 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -332,6 +332,8 @@ class ExprLike: *args: Incomplete, **kwargs: Incomplete, ) -> Incomplete: ... + def __getitem__(self, index: Incomplete, /) -> Incomplete: ... + def __iter__(self) -> Incomplete: ... def __add__(self, other: object, /) -> Incomplete: ... def __radd__(self, other: object, /) -> Incomplete: ... def __sub__(self, other: object, /) -> Incomplete: ... @@ -357,10 +359,8 @@ class Expr(ExprLike): def __init__(self, terms: Incomplete = ...) -> None: ... def __eq__(self, other: object, /) -> bool: ... def __ge__(self, other: object, /) -> bool: ... - def __getitem__(self, index: Incomplete, /) -> Incomplete: ... def __gt__(self, other: object, /) -> bool: ... def __iadd__(self, other: Incomplete, /) -> Incomplete: ... # noqa: PYI034 - def __iter__(self) -> Incomplete: ... def __le__(self, other: object, /) -> bool: ... def __lt__(self, other: object, /) -> bool: ... def __ne__(self, other: object, /) -> bool: ... From 7bed806f96e5f2d6609bc92fb5aa17f3194a8951 Mon Sep 17 00:00:00 2001 From: 40% Date: Sun, 14 Jun 2026 16:31:40 +0800 Subject: [PATCH 08/36] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 80bea8d07..a6c53e972 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ ### Changed - Move magic methods (`__radd__`, `__sub__`, `__rsub__`, `__rmul__`, `__richcmp__`, `__neg__`, and `__rtruediv__`) to `ExprLike` base class (#1204) - Speed up `Expr.__add__` and `Expr.__iadd__` via the C-level API +- Refactored the inheritance hierarchy of `Variable` from `Expr` to the base interface `ExprLike` ### Removed ## 6.2.1 - 2026.05.16 From b029053ce07027b6bf1a2c6b9a4ac9d43fd8f16a Mon Sep 17 00:00:00 2001 From: 40% Date: Sun, 14 Jun 2026 16:48:52 +0800 Subject: [PATCH 09/36] Update annotations --- src/pyscipopt/expr.pxi | 30 ++++++++++++++++-------------- src/pyscipopt/scip.pxd | 1 + src/pyscipopt/scip.pxi | 39 +++++++++++++++++++++------------------ src/pyscipopt/scip.pyi | 8 +++++--- 4 files changed, 43 insertions(+), 35 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 0d014c298..d173c6637 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -167,12 +167,12 @@ def buildGenExprObj(expr: Union[int, float, np.number, Expr, GenExpr]) -> GenExp if _is_number(expr): return Constant(expr) - elif isinstance(expr, Expr): + elif isinstance(expr, (Variable, Expr)): # loop over terms and create a sumexpr with the sum of each term # each term is either a variable (which gets transformed into varexpr) # or a product of variables (which gets tranformed into a prod) sumexpr = SumExpr() - for vars, coef in expr.terms.items(): + for vars, coef in expr.as_expr().terms.items(): if len(vars) == 0: sumexpr += coef elif len(vars) == 1: @@ -329,9 +329,7 @@ cdef class ExprLike: self.as_expr().normalize() cpdef double _evaluate(self, Solution sol) except *: - raise NotImplementedError( - f"{self.__class__.__name__!s} need to implement _evaluate() method" - ) + return self.as_expr()._evaluate(sol) ##@details Polynomial expressions of variables with operator overloading. \n @@ -396,10 +394,10 @@ cdef class Expr(ExprLike): while PyDict_Next(self.terms, &pos1, &k1_ptr, &v1_ptr): res[k1_ptr] = (v1_ptr) * coef - elif isinstance(other, Expr): + elif isinstance(other, (Variable, Expr)): while PyDict_Next(self.terms, &pos1, &k1_ptr, &v1_ptr): pos2 = 0 - while PyDict_Next(other.terms, &pos2, &k2_ptr, &v2_ptr): + while PyDict_Next(other.as_expr().terms, &pos2, &k2_ptr, &v2_ptr): child = (k1_ptr) * (k2_ptr) coef = ((v1_ptr)) * ((v2_ptr)) if (old_v_ptr := PyDict_GetItem(res, child)) != NULL: @@ -491,7 +489,7 @@ cdef class ExprCons: cdef void normalize(self): '''move constant terms in expression to bounds''' - if isinstance(self.expr, Expr): + if isinstance(self.expr, (Variable, Expr)): c = self.expr[CONST] self.expr -= c assert self.expr[CONST] == 0.0 @@ -1036,11 +1034,15 @@ cdef inline object _wrap_ufunc(object x, object ufunc): cdef inline object _ensure_matrix(object arg): if type(arg) is np.ndarray: return arg.view(MatrixExpr) - matrix = MatrixExpr if isinstance(arg, Expr) else MatrixGenExpr + matrix = MatrixExpr if isinstance(arg, (Variable, Expr)) else MatrixGenExpr return np.array(arg, dtype=object).view(matrix) -cdef dict _to_dict(Expr expr, Expr other, bool copy = True): - cdef dict children = expr.terms.copy() if copy else expr.terms +cdef dict _to_dict( + expr: Union[Variable, Expr], + other: Union[Variable, Expr], + bool copy = True, +): + cdef dict children = expr.as_expr().terms.copy() if copy else expr.as_expr().terms cdef Py_ssize_t pos = 0 cdef PyObject* k_ptr = NULL cdef PyObject* v_ptr = NULL @@ -1048,7 +1050,7 @@ cdef dict _to_dict(Expr expr, Expr other, bool copy = True): cdef double other_v cdef object k_obj - while PyDict_Next(other.terms, &pos, &k_ptr, &v_ptr): + while PyDict_Next(other.as_expr().terms, &pos, &k_ptr, &v_ptr): other_v = (v_ptr) k_obj = k_ptr old_v_ptr = PyDict_GetItem(children, k_obj) @@ -1109,14 +1111,14 @@ cdef inline bint _is_number(object x): return PyNumber_Check(x) cdef inline bint _is_expr_compatible(object x): - return _is_number(x) or isinstance(x, Expr) + return _is_number(x) or isinstance(x, (Variable, Expr)) cdef inline bint _is_genexpr_compatible(object x): return _is_expr_compatible(x) or isinstance(x, GenExpr) cdef object _expr_richcmp( ExprLike self, - other: Union[int, float, np.number, Expr, GenExpr], + other: Union[int, float, np.number, Variable, Expr, GenExpr], int op, ): if isinstance(other, np.ndarray): diff --git a/src/pyscipopt/scip.pxd b/src/pyscipopt/scip.pxd index 3b9750d69..4016f068d 100644 --- a/src/pyscipopt/scip.pxd +++ b/src/pyscipopt/scip.pxd @@ -2237,6 +2237,7 @@ cdef class Node: cdef class Variable(ExprLike): cdef SCIP_VAR* scip_var + cdef Expr expr_view # can be used to store problem data cdef public object data diff --git a/src/pyscipopt/scip.pxi b/src/pyscipopt/scip.pxi index 82abd1e8a..2411d25e8 100644 --- a/src/pyscipopt/scip.pxi +++ b/src/pyscipopt/scip.pxi @@ -1105,12 +1105,12 @@ cdef class Solution: def __getitem__( self, - expr: Union[Expr, GenExpr, MatrixExpr], + expr: Union[Variable, Variable, Expr, GenExpr, MatrixExpr], ) -> Union[float, np.ndarray]: - if not isinstance(expr, (Expr, GenExpr, MatrixExpr)): + if not isinstance(expr, (ExprLike, MatrixExpr)): raise TypeError( - "Argument 'expr' has incorrect type, expected 'Expr', 'GenExpr', or " - f"'MatrixExpr', got {type(expr).__name__!r}" + "Argument 'expr' has incorrect type, expected 'Variable', 'Expr', " + f"'GenExpr', or 'MatrixExpr', got {type(expr).__name__!r}" ) self._checkStage("SCIPgetSolVal") @@ -1559,7 +1559,7 @@ cdef class Variable(ExprLike): cdef Variable var = Variable.__new__(Variable) var.scip_var = scip_var - var._expr_view = Expr({Term(var): 1.0}) + var.expr_view = Expr({Term(var): 1.0}) return var property name: @@ -1576,7 +1576,7 @@ cdef class Variable(ExprLike): return self.name cdef Variable as_expr(self): - return self._expr_view + return self.expr_view def vtype(self): """ @@ -4062,7 +4062,7 @@ cdef class Model: Parameters ---------- - expr : Expr or float + expr : Variable, Expr or float the objective function SCIP Expr, or constant value sense : str, optional the objective sense ("minimize" or "maximize") (Default value = 'minimize') @@ -4076,9 +4076,9 @@ cdef class Model: cdef int i cdef _VarArray wrapper - if not isinstance(expr, Expr) and not _is_number(expr): + if not isinstance(expr, (Variable, Expr)) and not _is_number(expr): raise TypeError( - f"requires Expr or number but got type {type(expr).__name__!s}" + f"requires Variable, Expr or number but got type {type(expr).__name__!s}" ) # turn the constant value into an Expr instance for further processing @@ -6986,14 +6986,14 @@ cdef class Model: """ return PY_SCIP_CALL(SCIPprintCons(self._scip, constraint.scip_cons, NULL)) - def addExprNonlinear(self, Constraint cons, expr, coef): + def addExprNonlinear(self, Constraint cons, ExprLike expr, double coef): """ Add coef*expr to nonlinear constraint. Parameters ---------- cons : Constraint - expr : Expr or GenExpr + expr : Variable, Expr or GenExpr coef : float """ @@ -11329,7 +11329,7 @@ cdef class Model: def getSolVal( self, Solution sol, - expr: Union[Expr, GenExpr, MatrixExpr], + expr: Union[Variable, Expr, GenExpr, MatrixExpr], ) -> Union[float, np.ndarray]: """ Retrieve value of given variable or expression in the given solution. @@ -11340,7 +11340,7 @@ cdef class Model: Solution to query the value from. If None, the current LP/pseudo solution is used. - expr : Expr, GenExpr, MatrixExpr + expr : Variable, Expr, GenExpr, MatrixExpr Expression to query the value of. Returns @@ -11355,14 +11355,17 @@ cdef class Model: # no need to create a NULL solution wrapper in case we have a variable return (sol or Solution.create(self._scip, NULL))[expr] - def getVal(self, expr: Union[Expr, GenExpr, MatrixExpr]) -> Union[float, np.ndarray]: + def getVal( + self, + expr: Union[Variable, Expr, GenExpr, MatrixExpr], + ) -> Union[float, np.ndarray]: """ Retrieve the value of the given variable or expression in the best known solution. Can only be called after solving is completed. Parameters ---------- - expr : Expr, GenExpr or MatrixExpr + expr : Variable, Expr, GenExpr or MatrixExpr Expression to query the value of. Returns @@ -12239,13 +12242,13 @@ cdef class Model: raise Warning("method cannot be called in stage %i." % self.getStage()) PY_SCIP_CALL(SCIPfreeReoptSolve(self._scip)) - def chgReoptObjective(self, coeffs, sense = 'minimize'): + def chgReoptObjective(self, coeffs: Union[Variable, Expr], sense = 'minimize'): """ Change the objective function for reoptimization. Parameters ---------- - coeffs : Expr + coeffs : Variable, Expr the coefficients as a linear expression sense : str the objective sense (Default value = 'minimize') @@ -12265,7 +12268,7 @@ cdef class Model: else: raise Warning("unrecognized optimization sense: %s" % sense) - assert isinstance(coeffs, Expr), "given coefficients are not Expr but %s" % coeffs.__class__.__name__ + assert isinstance(coeffs, (Variable, Expr)), "given coefficients are not Variable or Expr but %s" % coeffs.__class__.__name__ if coeffs.degree() > 1: raise ValueError("Nonlinear objective functions are not supported!") diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index 70f705d50..4b61971be 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -1250,7 +1250,9 @@ class Model: ) -> Incomplete: ... def getSolTime(self, sol: Incomplete) -> Incomplete: ... @overload - def getSolVal(self, sol: Solution, expr: Union[Expr, GenExpr]) -> float: ... + def getSolVal( + self, sol: Solution, expr: Union[Variable, Expr, GenExpr] + ) -> float: ... @overload def getSolVal(self, sol: Solution, expr: MatrixExpr) -> np.ndarray: ... def getSols(self) -> Incomplete: ... @@ -1265,7 +1267,7 @@ class Model: def getTransformedVar(self, var: Incomplete) -> Incomplete: ... def getTreesizeEstimation(self) -> Incomplete: ... @overload - def getVal(self, expr: Union[Expr, GenExpr]) -> float: ... + def getVal(self, expr: Union[Variable, Expr, GenExpr]) -> float: ... @overload def getVal(self, expr: MatrixExpr) -> np.ndarray: ... def getValsLinear(self, cons: Incomplete) -> Incomplete: ... @@ -2261,7 +2263,7 @@ class VarExpr(GenExpr): def __init__(self, *args: Incomplete, **kwargs: Incomplete) -> None: ... @disjoint_base -class Variable(Expr): +class Variable(ExprLike): data: Incomplete name: Incomplete def __init__(self) -> None: ... From d2f78e1df9414272785b7fa2b40049d4e13c1092 Mon Sep 17 00:00:00 2001 From: 40% Date: Tue, 20 Oct 2026 21:49:36 +0800 Subject: [PATCH 10/36] perf: inline ExprLike template ops to skip PyNumber_* dispatch __add__/__mul__/__truediv__ now call Expr methods directly via __Pyx_PyObject_FastCallMethod instead of going through PyNumber_Add/ PyNumber_Mul/PyNumber_TrueDivide slot lookup. __getitem__/__iter__ inlined to direct dict access (v.terms.get / iter(v.terms)), equivalent to Expr originals. __pow__ unchanged (internal res *= self still dispatches; full inline not worth the complexity). Perf: x+y regression reduced from +48% to +16%; x*y regression eliminated (-6%); degree still +15% (as_expr indirection). 97 tests pass, mypy 0 errors. --- src/pyscipopt/expr.pxi | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 9853a0bd4..95af59188 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -265,13 +265,18 @@ cdef class ExprLike: return NotImplemented def __getitem__(self, key): - return self.as_expr()[key] + cdef Expr v = self.as_expr() + if not isinstance(key, Term): + key = Term(key) + return v.terms.get(key, 0.0) def __iter__(self): - return iter(self.as_expr()) + cdef Expr v = self.as_expr() + return iter(v.terms) def __add__(self, other, /): - return self.as_expr() + other + cdef Expr v = self.as_expr() + return Expr.__add__(v, other) def __radd__(self, other, /): return self + other @@ -283,13 +288,15 @@ cdef class ExprLike: return (-self) + other def __mul__(self, other, /): - return self.as_expr() * other + cdef Expr v = self.as_expr() + return Expr.__mul__(v, other) def __rmul__(self, other, /): return self * other def __truediv__(self, other, /): - return self.as_expr() / other + cdef Expr v = self.as_expr() + return Expr.__truediv__(v, other) def __rtruediv__(self, other, /) -> GenExpr: return buildGenExprObj(other) / self From 70aec700f06c30709a96a4904724058d47c7a231 Mon Sep 17 00:00:00 2001 From: 40% Date: Mon, 26 Oct 2026 23:03:27 +0800 Subject: [PATCH 11/36] Fix chgReoptObjective for Variable and add Variable tests --- src/pyscipopt/expr.pxi | 2 +- src/pyscipopt/scip.pxi | 14 ++++-- tests/test_Variable.py | 105 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 115 insertions(+), 6 deletions(-) create mode 100644 tests/test_Variable.py diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index e5bd905ee..e7c9b05c0 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -919,7 +919,7 @@ cdef class VarExpr(GenExpr): return expr cpdef double _evaluate(self, Solution sol) except *: - return (self.children[0])._evaluate(sol) + return (self.children[0]).as_expr()._evaluate(sol) # Pow Expressions diff --git a/src/pyscipopt/scip.pxi b/src/pyscipopt/scip.pxi index 28f9e0749..7e54578fd 100644 --- a/src/pyscipopt/scip.pxi +++ b/src/pyscipopt/scip.pxi @@ -1104,7 +1104,7 @@ cdef class Solution: def __getitem__( self, - expr: Union[Variable, Variable, Expr, GenExpr, MatrixExpr], + expr: Union[ExprLike, MatrixExpr], ) -> Union[float, np.ndarray]: if not isinstance(expr, (ExprLike, MatrixExpr)): raise TypeError( @@ -12668,6 +12668,7 @@ cdef class Model: cdef SCIP_OBJSENSE objsense cdef int i cdef _VarArray wrapper + cdef Expr _coeffs_expr if sense == "minimize": objsense = SCIP_OBJSENSE_MINIMIZE @@ -12678,12 +12679,15 @@ cdef class Model: assert isinstance(coeffs, (Variable, Expr)), "given coefficients are not Variable or Expr but %s" % coeffs.__class__.__name__ - if coeffs.degree() > 1: + # Variable is not an Expr anymore (M4): use its shared, read-only Expr view. + _coeffs_expr = (coeffs).as_expr() + + if _coeffs_expr.degree() > 1: raise ValueError("Nonlinear objective functions are not supported!") - if coeffs[CONST] != 0.0: + if _coeffs_expr[CONST] != 0.0: raise ValueError("Constant offsets in objective are not supported!") - nvars = len(coeffs.terms) - (CONST in coeffs.terms) + nvars = len(_coeffs_expr.terms) - (CONST in _coeffs_expr.terms) if nvars == 0: PY_SCIP_CALL(SCIPchgReoptObjective(self._scip, objsense, NULL, NULL, 0)) @@ -12693,7 +12697,7 @@ cdef class Model: vars = malloc(nvars * sizeof(SCIP_VAR*)) i = 0 - for term, coef in coeffs.terms.items(): + for term, coef in _coeffs_expr.terms.items(): # avoid CONST term of Expr if term != CONST: wrapper = _VarArray(term[0]) diff --git a/tests/test_Variable.py b/tests/test_Variable.py new file mode 100644 index 000000000..6e080e875 --- /dev/null +++ b/tests/test_Variable.py @@ -0,0 +1,105 @@ +import unittest + +from pyscipopt import Model, quicksum, sqrt +from pyscipopt.scip import ( + CONST, + Expr, + ExprCons, + ExprLike, + GenExpr, + Term, + Variable, +) + + +class VariableTest(unittest.TestCase): + """Tests for the M4 semantics: Variable is an ExprLike, not an Expr.""" + + def setUp(self): + self.m = Model() + self.m.hideOutput() + self.x = self.m.addVar(name="x", lb=0, ub=10) + self.y = self.m.addVar(name="y", lb=0, ub=10) + + def test_isinstance_semantics(self): + x = self.x + self.assertIsInstance(x, ExprLike) + self.assertNotIsInstance(x, Expr) + self.assertIsInstance(x, Variable) + + expr = x + 1 + self.assertIsInstance(expr, Expr) + self.assertNotIsInstance(expr, Variable) + + gen = sqrt(x) + self.assertIsInstance(gen, GenExpr) + self.assertIsInstance(gen, ExprLike) + + def test_add_variables(self): + x, y = self.x, self.y + expr = x + y + self.assertIsInstance(expr, Expr) + self.assertEqual(len(expr.terms), 2) + self.assertEqual(expr[x], 1.0) + self.assertEqual(expr[y], 1.0) + self.assertEqual(expr[CONST], 0.0) + + def test_multiply_variable_with_itself(self): + x = self.x + square = x * x + self.assertIsInstance(square, Expr) + self.assertEqual(len(square.terms), 1) + self.assertEqual(square[Term(x, x)], 1.0) + self.assertEqual(square[x], 0.0) + + def test_subtract_variable_from_itself(self): + x = self.x + diff = x - x + self.assertIsInstance(diff, Expr) + self.assertEqual(diff[x], 0.0) + self.assertEqual(diff[CONST], 0.0) + + # Normalization through ExprCons drops the zero coefficient. + cons = ExprCons(diff, lhs=0.0) + self.assertEqual(cons.expr.terms, {}) + + def test_quicksum_matches_addition(self): + x, y = self.x, self.y + quick = quicksum([x, y]) + added = x + y + self.assertIsInstance(quick, Expr) + # quicksum starts from an Expr carrying an explicit zero constant term, + # so compare the coefficients instead of the raw dict. + self.assertEqual(quick[CONST], added[CONST]) + self.assertEqual(len(quick.terms) - 1, len(added.terms)) + for var in (x, y): + self.assertEqual(quick[var], added[var]) + + def test_operations_do_not_mutate_variable_view(self): + x, y = self.x, self.y + _ = x + y + _ = 2 * x + _ = quicksum([x, y]) + # x still represents exactly the variable term x + self.assertEqual(str(x), "x") + self.assertEqual(x[x], 1.0) + self.assertEqual(x[y], 0.0) + + def test_chgReoptObjective_with_variable(self): + m = self.m + x, y = self.x, self.y + m.enableReoptimization() + m.addCons(x + y <= 15) + m.setObjective(x + y, sense="maximize") + m.optimize() + self.assertAlmostEqual(m.getObjVal(), 15.0) + + m.freeReoptSolve() + # Regression: Variable used to be an Expr with a .terms attribute. + m.chgReoptObjective(x, sense="maximize") + m.optimize() + self.assertAlmostEqual(m.getVal(x), 10.0) + + +if __name__ == "__main__": + unittest.main() From 2116e0f2833d9ac3e13ba72e8c4cd41174df5487 Mon Sep 17 00:00:00 2001 From: 40% Date: Mon, 2 Nov 2026 10:42:00 +0800 Subject: [PATCH 12/36] Optimize ExprLike operator dispatch and unify expression types - Forward __add__, __mul__, and __truediv__ through operator syntax instead of unbound Expr method calls - Annotate expression-compatible APIs with ExprLike - Remove duplicated Expr.__getitem__/__iter__ in favor of ExprLike - Assert ExprCons.expr is a plain Expr after normalize() - Rename Variable.expr_view to Variable._expr - Raise clearer errors when indexing or iterating a GenExpr --- src/pyscipopt/expr.pxi | 35 ++++++++++++++++++----------------- src/pyscipopt/scip.pxd | 2 +- src/pyscipopt/scip.pxi | 8 ++++---- src/pyscipopt/scip.pyi | 16 ++++++++-------- 4 files changed, 31 insertions(+), 30 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index c0256e5a4..8581e0080 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -166,7 +166,7 @@ CONST = Term() # helper function -def buildGenExprObj(expr: Union[int, float, np.number, Expr, GenExpr]) -> GenExpr: +def buildGenExprObj(expr: Union[int, float, np.number, ExprLike]) -> GenExpr: """helper function to generate an object of type GenExpr""" if not _is_genexpr_compatible(expr): raise TypeError(f"unsupported type {type(expr).__name__!s}") @@ -275,8 +275,7 @@ cdef class ExprLike: return iter(v.terms) def __add__(self, other, /): - cdef Expr v = self.as_expr() - return Expr.__add__(v, other) + return self.as_expr() + other def __radd__(self, other, /): return self + other @@ -288,15 +287,13 @@ cdef class ExprLike: return (-self) + other def __mul__(self, other, /): - cdef Expr v = self.as_expr() - return Expr.__mul__(v, other) + return self.as_expr() * other def __rmul__(self, other, /): return self * other def __truediv__(self, other, /): - cdef Expr v = self.as_expr() - return Expr.__truediv__(v, other) + return self.as_expr() / other def __rtruediv__(self, other, /) -> GenExpr: return buildGenExprObj(other) / self @@ -310,10 +307,10 @@ cdef class ExprLike: def __richcmp__(self, other, int op): return _expr_richcmp(self, other, op) - def __neg__(self, /) -> Union[Expr, GenExpr]: + def __neg__(self, /) -> ExprLike: return self * -1.0 - def __pos__(self, /) -> Union[Expr, GenExpr]: + def __pos__(self, /) -> ExprLike: return self.copy() def __abs__(self, /) -> AbsExpr: @@ -367,14 +364,6 @@ cdef class Expr(ExprLike): if len(self.terms) == 0: self.terms[CONST] = 0.0 - def __getitem__(self, key): - if not isinstance(key, Term): - key = Term(key) - return self.terms.get(key, 0.0) - - def __iter__(self): - return iter(self.terms) - def __add__(self, other, /): if not _is_expr_compatible(other): if isinstance(other, GenExpr): @@ -518,6 +507,8 @@ cdef class ExprCons: self._rhs = rhs assert not (lhs is None and rhs is None) self.normalize() + assert not isinstance(self.expr, Variable), \ + "ExprCons.expr must be a plain Expr after normalize()" cdef void normalize(self): '''move constant terms in expression to bounds''' @@ -622,6 +613,16 @@ cdef class GenExpr(ExprLike): def __init__(self): # do we need it ''' ''' + def __getitem__(self, key): + raise TypeError( + f"{self.__class__.__name__!s} has no polynomial form and cannot be indexed" + ) + + def __iter__(self): + raise TypeError( + f"{self.__class__.__name__!s} has no polynomial form and cannot be iterated" + ) + def __add__(self, other, /): if not _is_genexpr_compatible(other): return NotImplemented diff --git a/src/pyscipopt/scip.pxd b/src/pyscipopt/scip.pxd index a1038bdb0..ec78cbf36 100644 --- a/src/pyscipopt/scip.pxd +++ b/src/pyscipopt/scip.pxd @@ -2280,7 +2280,7 @@ cdef class Node: cdef class Variable(ExprLike): cdef SCIP_VAR* scip_var - cdef Expr expr_view + cdef Expr _expr # can be used to store problem data cdef public object data diff --git a/src/pyscipopt/scip.pxi b/src/pyscipopt/scip.pxi index 7e54578fd..3326fc946 100644 --- a/src/pyscipopt/scip.pxi +++ b/src/pyscipopt/scip.pxi @@ -1558,7 +1558,7 @@ cdef class Variable(ExprLike): cdef Expr view = Expr.__new__(Expr) var.scip_var = scip_var view.terms = {Term(var): 1.0} - var.expr_view = view + var._expr = view return var @property @@ -1577,7 +1577,7 @@ cdef class Variable(ExprLike): return self.name cdef Expr as_expr(self): - return self.expr_view + return self._expr def vtype(self): """ @@ -11676,7 +11676,7 @@ cdef class Model: def getSolVal( self, Solution sol, - expr: Union[Variable, Expr, GenExpr, MatrixExpr], + expr: Union[ExprLike, MatrixExpr], ) -> Union[float, np.ndarray]: """ Retrieve value of given variable or expression in the given solution. @@ -11704,7 +11704,7 @@ cdef class Model: def getVal( self, - expr: Union[Variable, Expr, GenExpr, MatrixExpr], + expr: Union[ExprLike, MatrixExpr], ) -> Union[float, np.ndarray]: """ Retrieve the value of the given variable or expression in the best known solution. diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index 955c8ce6e..8691a3dc3 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -420,7 +420,7 @@ class Expr(ExprLike): @overload # type: ignore[override] def __truediv__(self, other: float, /) -> Expr: ... @overload - def __truediv__(self, other: Expr | GenExpr, /) -> ProdExpr: ... + def __truediv__(self, other: ExprLike, /) -> ProdExpr: ... @overload def __truediv__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExpr: ... def __rtruediv__(self, other: float, /) -> ProdExpr: ... # type: ignore[override] @@ -443,9 +443,9 @@ class Expr(ExprLike): class ExprCons: _lhs: float | None _rhs: float | None - expr: Expr | GenExpr + expr: ExprLike def __init__( - self, expr: Expr | GenExpr, lhs: float | None = None, rhs: float | None = None + self, expr: ExprLike, lhs: float | None = None, rhs: float | None = None ) -> None: ... def __bool__(self) -> bool: ... def __ge__(self, other: float, /) -> ExprCons: ... @@ -973,7 +973,7 @@ class Model: ) -> list[Constraint]: ... def addCut(self, cut: Row, forcecut: bool = False) -> bool: ... def addExprNonlinear( - self, cons: Constraint, expr: Expr | GenExpr, coef: float + self, cons: Constraint, expr: ExprLike, coef: float ) -> None: ... def addMatrixCons( self, @@ -1111,7 +1111,7 @@ class Model: def chgCoefLinear(self, cons: Constraint, var: Variable, value: float) -> None: ... def chgLhs(self, cons: Constraint, lhs: float | None) -> None: ... def chgReoptObjective( - self, coeffs: Expr, sense: Literal["minimize", "maximize"] = "minimize" + self, coeffs: Variable | Expr, sense: Literal["minimize", "maximize"] = "minimize" ) -> None: ... def chgRhs(self, cons: Constraint, rhs: float | None) -> None: ... def chgRowLhsDive(self, row: Row, newlhs: float) -> None: ... @@ -1700,7 +1700,7 @@ class Model: def setObjIntegral(self) -> None: ... def setObjective( self, - expr: Expr | SupportsFloat, + expr: Variable | Expr | SupportsFloat, sense: Literal["minimize", "maximize"] = "minimize", clear: bool | Literal["true"] = "true", # TODO: typo? ) -> None: ... @@ -2335,7 +2335,7 @@ class Solution: def retransform(self) -> None: ... def translate(self, target: Model) -> Solution: ... @overload - def __getitem__(self, index: Expr | GenExpr, /) -> float: ... + def __getitem__(self, index: ExprLike, /) -> float: ... @overload def __getitem__(self, index: MatrixExpr, /) -> np.ndarray: ... def __setitem__(self, key: Variable, value: float, /) -> None: ... @@ -2441,7 +2441,7 @@ class SinExpr(UnaryExpr): ... class CosExpr(UnaryExpr): ... class VarExpr(GenExpr): - def __init__(self, var: Expr) -> None: ... + def __init__(self, var: Variable) -> None: ... def __neg__(self, /) -> ProdExpr: ... @disjoint_base From 14560b961c68c717792619586fa4cee7ab089101 Mon Sep 17 00:00:00 2001 From: 40% Date: Mon, 2 Nov 2026 10:45:31 +0800 Subject: [PATCH 13/36] Rename local Expr view to expr in Variable.create --- src/pyscipopt/scip.pxi | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/pyscipopt/scip.pxi b/src/pyscipopt/scip.pxi index 3326fc946..535b4eb5c 100644 --- a/src/pyscipopt/scip.pxi +++ b/src/pyscipopt/scip.pxi @@ -1555,10 +1555,10 @@ cdef class Variable(ExprLike): raise Warning("cannot create Variable with SCIP_VAR* == NULL") cdef Variable var = Variable.__new__(Variable) - cdef Expr view = Expr.__new__(Expr) + cdef Expr expr = Expr.__new__(Expr) var.scip_var = scip_var - view.terms = {Term(var): 1.0} - var._expr = view + expr.terms = {Term(var): 1.0} + var._expr = expr return var @property From fae57b57cbdd5b11e1f4b3993b6af649977b99ed Mon Sep 17 00:00:00 2001 From: 40% Date: Mon, 2 Nov 2026 11:03:00 +0800 Subject: [PATCH 14/36] Narrow __neg__ return types to Expr or GenExpr ExprLike.__neg__ never returns a Variable, so Expr | GenExpr is more accurate. Add a Variable.__neg__ override returning Expr, and apply ruff formatting to the stub. --- src/pyscipopt/expr.pxi | 2 +- src/pyscipopt/scip.pyi | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 8581e0080..cb4867642 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -307,7 +307,7 @@ cdef class ExprLike: def __richcmp__(self, other, int op): return _expr_richcmp(self, other, op) - def __neg__(self, /) -> ExprLike: + def __neg__(self, /) -> Union[Expr, GenExpr]: return self * -1.0 def __pos__(self, /) -> ExprLike: diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index 8691a3dc3..45778c4a9 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -357,7 +357,7 @@ class ExprLike: def __getitem__(self, index: Incomplete, /) -> Incomplete: ... def __iter__(self) -> Incomplete: ... def __pos__(self, /) -> Self: ... - def __neg__(self, /) -> ExprLike: ... + def __neg__(self, /) -> Expr | GenExpr: ... def __abs__(self, /) -> AbsExpr: ... def __add__(self, other: object, /) -> Incomplete: ... def __radd__(self, other: object, /) -> Incomplete: ... @@ -1111,7 +1111,9 @@ class Model: def chgCoefLinear(self, cons: Constraint, var: Variable, value: float) -> None: ... def chgLhs(self, cons: Constraint, lhs: float | None) -> None: ... def chgReoptObjective( - self, coeffs: Variable | Expr, sense: Literal["minimize", "maximize"] = "minimize" + self, + coeffs: Variable | Expr, + sense: Literal["minimize", "maximize"] = "minimize", ) -> None: ... def chgRhs(self, cons: Constraint, rhs: float | None) -> None: ... def chgRowLhsDive(self, row: Row, newlhs: float) -> None: ... @@ -1410,7 +1412,9 @@ class Model: def getSolObjVal(self, sol: Solution | None, original: bool = True) -> float: ... def getSolTime(self, sol: Solution) -> float: ... @overload - def getSolVal(self, sol: Solution | None, expr: Variable | Expr | GenExpr) -> float: ... + def getSolVal( + self, sol: Solution | None, expr: Variable | Expr | GenExpr + ) -> float: ... @overload def getSolVal(self, sol: Solution | None, expr: MatrixExpr) -> np.ndarray: ... def getSols(self) -> list[Solution]: ... @@ -2449,6 +2453,7 @@ class Variable(ExprLike): data: Any name: str def __init__(self) -> None: ... + def __neg__(self, /) -> Expr: ... def getAvgSol(self) -> float: ... def getCol(self) -> Column: ... def getImplType(self) -> Incomplete: ... From 4edf417ab55166a41dbcdf614bf61d580642e112 Mon Sep 17 00:00:00 2001 From: 40% Date: Mon, 23 Nov 2026 21:58:45 +0800 Subject: [PATCH 15/36] correct the return type --- src/pyscipopt/scip.pyi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index f8eb6b4a1..6902707a2 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -448,7 +448,7 @@ class Expr(ExprLike): @disjoint_base class ExprCons: @property - def expr(self) -> Expr | GenExpr: ... + def expr(self) -> ExprLike: ... @property def _lhs(self) -> float | None: ... @property From 15a332272aa862a74d2ad06ffa989a6ed0c5fdde Mon Sep 17 00:00:00 2001 From: 40% Date: Mon, 23 Nov 2026 22:05:07 +0800 Subject: [PATCH 16/36] simplify error message --- src/pyscipopt/expr.pxi | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 5c3086552..c57e7be5e 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -641,15 +641,11 @@ cdef class GenExpr(ExprLike): def __init__(self): # do we need it ''' ''' - def __getitem__(self, key): - raise TypeError( - f"{self.__class__.__name__!s} has no polynomial form and cannot be indexed" - ) + def __getitem__(self, _): + raise TypeError(f"{self.__class__.__name__!s} cannot be indexed") def __iter__(self): - raise TypeError( - f"{self.__class__.__name__!s} has no polynomial form and cannot be iterated" - ) + raise TypeError(f"{self.__class__.__name__!s} cannot be iterated") def __add__(self, other, /): if not _is_genexpr_compatible(other): From aaf047d9eaf931e51823f6bac11f2e1f26c5c1ae Mon Sep 17 00:00:00 2001 From: 40% Date: Mon, 23 Nov 2026 22:05:49 +0800 Subject: [PATCH 17/36] add Variable to the unary argument doc --- src/pyscipopt/expr.pxi | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index c57e7be5e..d7cae8aa4 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -996,7 +996,7 @@ cdef class PowExpr(GenExpr): cdef class UnaryExpr(GenExpr): - def __init__(self, op, expr: Union[Expr, GenExpr]): + def __init__(self, op, GenExpr expr not None): self._op = op self.children = [expr] @@ -1148,7 +1148,7 @@ def exp(x): Parameters ---------- - x : Expr, GenExpr, number, np.ndarray, list, or tuple + x : Variable, Expr, GenExpr, number, np.ndarray, list, or tuple - If x is a scalar expression or number, apply the exp function directly to it. And if it's a number, convert it to a Constant expression first. - If x is a vector (np.ndarray, list, or tuple), apply the exp function @@ -1172,7 +1172,7 @@ def log(x): Parameters ---------- - x : Expr, GenExpr, number, np.ndarray, list, or tuple + x : Variable, Expr, GenExpr, number, np.ndarray, list, or tuple - If x is a scalar expression or number, apply the log function directly to it. And if it's a number, convert it to a Constant expression first. - If x is a vector (np.ndarray, list, or tuple), apply the log function @@ -1196,7 +1196,7 @@ def sqrt(x): Parameters ---------- - x : Expr, GenExpr, number, np.ndarray, list, or tuple + x : Variable, Expr, GenExpr, number, np.ndarray, list, or tuple - If x is a scalar expression or number, apply the sqrt function directly to it. And if it's a number, convert it to a Constant expression first. - If x is a vector (np.ndarray, list, or tuple), apply the sqrt function @@ -1220,7 +1220,7 @@ def sin(x): Parameters ---------- - x : Expr, GenExpr, number, np.ndarray, list, or tuple + x : Variable, Expr, GenExpr, number, np.ndarray, list, or tuple - If x is a scalar expression or number, apply the sin function directly to it. And if it's a number, convert it to a Constant expression first. - If x is a vector (np.ndarray, list, or tuple), apply the sin function @@ -1244,7 +1244,7 @@ def cos(x): Parameters ---------- - x : Expr, GenExpr, number, np.ndarray, list, or tuple + x : Variable, Expr, GenExpr, number, np.ndarray, list, or tuple - If x is a scalar expression or number, apply the cos function directly to it. And if it's a number, convert it to a Constant expression first. - If x is a vector (np.ndarray, list, or tuple), apply the cos function @@ -1273,7 +1273,7 @@ cdef inline object _wrap_ufunc(object x, object ufunc): Parameters ---------- - x : Expr, GenExpr, number, np.ndarray, list, or tuple + x : Variable, Expr, GenExpr, number, np.ndarray, list, or tuple - If x is a scalar expression or number, apply the ufunc directly to it. And if it's a number, convert it to a Constant expression first. - If x is a vector (np.ndarray, list, or tuple), apply the ufunc element-wise From bd6ecd18322fe3bb3b0c60221900421ce8b2bdd9 Mon Sep 17 00:00:00 2001 From: 40% Date: Mon, 23 Nov 2026 22:13:27 +0800 Subject: [PATCH 18/36] simplify a bit --- 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 d7cae8aa4..15f9f271d 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -389,7 +389,7 @@ cdef class Expr(ExprLike): def __add__(self, other, /): if not _is_expr_compatible(other): if isinstance(other, GenExpr): - return other.__add__(self) + return other + self return NotImplemented if _is_number(other): @@ -413,7 +413,7 @@ cdef class Expr(ExprLike): def __mul__(self, other, /): if not _is_expr_compatible(other): if isinstance(other, GenExpr): - return other.__mul__(self) + return other * self return NotImplemented cdef dict res = {} From 4d3de6928f1b63a7759e1dbfc5a18be09254b024 Mon Sep 17 00:00:00 2001 From: 40% Date: Mon, 23 Nov 2026 22:23:06 +0800 Subject: [PATCH 19/36] remove extra lines --- src/pyscipopt/scip.pxi | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/pyscipopt/scip.pxi b/src/pyscipopt/scip.pxi index d8429f357..aba6a9077 100644 --- a/src/pyscipopt/scip.pxi +++ b/src/pyscipopt/scip.pxi @@ -11810,10 +11810,7 @@ cdef class Model: # no need to create a NULL solution wrapper in case we have a variable return (sol or Solution.create(self._scip, NULL))[expr] - def getVal( - self, - expr: Union[ExprLike, MatrixExpr], - ) -> Union[float, np.ndarray]: + def getVal(self, expr: Union[ExprLike, MatrixExpr]) -> Union[float, np.ndarray]: """ Retrieve the value of the given variable or expression in the best known solution. Can only be called after solving is completed. From 1ac35f9af1dd3a227c219ec96ba5c087a2196c31 Mon Sep 17 00:00:00 2001 From: 40% Date: Mon, 23 Nov 2026 22:49:43 +0800 Subject: [PATCH 20/36] correct variable name --- src/pyscipopt/expr.pxi | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 15f9f271d..9d7ff8c63 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -287,14 +287,14 @@ cdef class ExprLike: return NotImplemented def __getitem__(self, key): - cdef Expr v = self.as_expr() + cdef Expr expr = self.as_expr() if not isinstance(key, Term): key = Term(key) - return v.terms.get(key, 0.0) + return expr.terms.get(key, 0.0) def __iter__(self): - cdef Expr v = self.as_expr() - return iter(v.terms) + cdef Expr expr = self.as_expr() + return iter(expr.terms) def __add__(self, other, /): return self.as_expr() + other From 2bf38ca6e8e57f6a70654be738b8d2f774f88183 Mon Sep 17 00:00:00 2001 From: 40% Date: Mon, 23 Nov 2026 23:02:41 +0800 Subject: [PATCH 21/36] Speed up degree and move it to ExprLike Move the degree computation from Expr to ExprLike as a cpdef double method with "except? -1", so Expr, Variable and GenExpr share one implementation; GenExpr overrides it to return INFINITY. Expr.degree now returns float instead of int, and the stub is updated accordingly. Replace the generator-based max() with an explicit C loop (generators are not allowed inside cpdef functions). Benchmark (Python call, min of 5 runs): 1000 terms: 71.6 us -> 9.3 us (7.7x) 2 terms: 679 ns -> 151 ns (4.5x) Also update test_Variable for the single-argument Term constructor. --- src/pyscipopt/expr.pxi | 19 +++++++++---------- src/pyscipopt/scip.pxd | 1 + src/pyscipopt/scip.pyi | 2 +- tests/test_Variable.py | 2 +- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 9d7ff8c63..96ec877ca 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -353,8 +353,14 @@ cdef class ExprLike: def cos(self, /) -> CosExpr: return CosExpr(Operator.cos, buildGenExprObj(self)) - def degree(self, /) -> float: - return self.as_expr().degree() + cpdef double degree(self) except? -1: + cdef Expr expr = self.as_expr() + cdef double deg = 0 + cdef Term t + for t in expr.terms: + if len(t) > deg: + deg = len(t) + return deg cdef Expr as_expr(self): raise NotImplementedError( @@ -482,13 +488,6 @@ cdef class Expr(ExprLike): def __repr__(self) -> str: return 'Expr(%s)' % repr(self.terms) - def degree(self, /) -> int: - '''computes highest degree of terms''' - if len(self.terms) == 0: - return 0 - else: - return max(len(v) for v in self.terms) - cdef Expr as_expr(self): return self @@ -788,7 +787,7 @@ cdef class GenExpr(ExprLike): return NotImplemented return super().__rtruediv__(other) - def degree(self, /) -> float: + cpdef double degree(self) except? -1: '''Note: none of these expressions should be polynomial''' return INFINITY diff --git a/src/pyscipopt/scip.pxd b/src/pyscipopt/scip.pxd index 966822660..882fcb390 100644 --- a/src/pyscipopt/scip.pxd +++ b/src/pyscipopt/scip.pxd @@ -2211,6 +2211,7 @@ cdef extern from "tpi/tpi.h": cdef class ExprLike: + cpdef double degree(self) except? -1 cdef Expr as_expr(self) cdef void normalize(self) cpdef double _evaluate(self, Solution sol) diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index 6902707a2..1fc5c990e 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -399,7 +399,7 @@ class Expr(ExprLike): @property def terms(self) -> dict[Term, float]: ... def __init__(self, terms: Incomplete = None) -> None: ... - def degree(self) -> int: ... + def degree(self) -> float: ... def __neg__(self, /) -> Expr: ... def __iadd__(self, other: Incomplete, /) -> Incomplete: ... # type: ignore[misc] @overload # type: ignore[override] diff --git a/tests/test_Variable.py b/tests/test_Variable.py index 6e080e875..19cecab0b 100644 --- a/tests/test_Variable.py +++ b/tests/test_Variable.py @@ -49,7 +49,7 @@ def test_multiply_variable_with_itself(self): square = x * x self.assertIsInstance(square, Expr) self.assertEqual(len(square.terms), 1) - self.assertEqual(square[Term(x, x)], 1.0) + self.assertEqual(square[Term(x) * Term(x)], 1.0) self.assertEqual(square[x], 0.0) def test_subtract_variable_from_itself(self): From 47300f3d1b76d63c37401c493b72e158bb5b0843 Mon Sep 17 00:00:00 2001 From: 40% Date: Mon, 23 Nov 2026 23:16:33 +0800 Subject: [PATCH 22/36] simplify 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 96ec877ca..fa4013f91 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -1343,7 +1343,7 @@ cdef inline bint _is_genexpr_compatible(object x): cdef object _expr_richcmp( ExprLike self, - other: Union[int, float, np.number, Variable, Expr, GenExpr], + other: Union[int, float, np.number, ExprLike], int op, ): if isinstance(other, np.ndarray): From 3363c33169acff5d7db40a8e34d683205b3f8ac6 Mon Sep 17 00:00:00 2001 From: 40% Date: Mon, 23 Nov 2026 23:20:43 +0800 Subject: [PATCH 23/36] add the temp cache --- src/pyscipopt/expr.pxi | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index fa4013f91..243c1fd9f 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -355,12 +355,13 @@ cdef class ExprLike: cpdef double degree(self) except? -1: cdef Expr expr = self.as_expr() - cdef double deg = 0 + cdef double deg = 0, res = 0 cdef Term t for t in expr.terms: - if len(t) > deg: - deg = len(t) - return deg + deg = len(t) + if deg > res: + res = deg + return res cdef Expr as_expr(self): raise NotImplementedError( From 2a3ca87cf9e8194ffd0650c15f5dd9cb305b922c Mon Sep 17 00:00:00 2001 From: 40% Date: Mon, 23 Nov 2026 23:52:25 +0800 Subject: [PATCH 24/36] Improve ExprLike indexing and add membership test - __getitem__: reject None explicitly and raise a clear TypeError for invalid index types; annotate the return type - __iter__: simplify and annotate as Iterator[Term] - __contains__: add O(1) membership test for Term and Variable - GenExpr: override __contains__ to raise TypeError like __getitem__/__iter__ - Stub: drop the duplicate Expr.__getitem__/__iter__ and update signatures --- src/pyscipopt/expr.pxi | 30 ++++++++++++++++++++++++------ src/pyscipopt/scip.pyi | 9 ++++----- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 243c1fd9f..4f665d69d 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -286,15 +286,30 @@ cdef class ExprLike: return NotImplemented - def __getitem__(self, key): - cdef Expr expr = self.as_expr() + def __getitem__(self, key) -> float: + if key is None: + raise TypeError("index must be a Term or Variable, got None") if not isinstance(key, Term): - key = Term(key) - return expr.terms.get(key, 0.0) + try: + key = Term(key) + except TypeError: + raise TypeError( + f"index must be a Term or Variable, got {type(key).__name__}" + ) from None + return self.as_expr().terms.get(key, 0.0) def __iter__(self): - cdef Expr expr = self.as_expr() - return iter(expr.terms) + return iter(self.as_expr().terms) + + def __contains__(self, key) -> bool: + if key is None: + return False + if not isinstance(key, Term): + try: + key = Term(key) + except TypeError: + return False + return key in self.as_expr().terms def __add__(self, other, /): return self.as_expr() + other @@ -647,6 +662,9 @@ cdef class GenExpr(ExprLike): def __iter__(self): raise TypeError(f"{self.__class__.__name__!s} cannot be iterated") + def __contains__(self, _): + raise TypeError(f"{self.__class__.__name__!s} cannot be used with 'in'") + def __add__(self, other, /): if not _is_genexpr_compatible(other): return NotImplemented diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index 1fc5c990e..75dbb3782 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -1,5 +1,5 @@ import os -from collections.abc import Iterable, Mapping, Sequence +from collections.abc import Iterable, Iterator, Mapping, Sequence from enum import IntEnum, IntFlag from typing import Any, ClassVar, Literal, SupportsFloat, overload @@ -360,8 +360,9 @@ class ExprLike: *args: Incomplete, **kwargs: Incomplete, ) -> Incomplete: ... - def __getitem__(self, index: Incomplete, /) -> Incomplete: ... - def __iter__(self) -> Incomplete: ... + def __getitem__(self, key: Incomplete, /) -> float: ... + def __iter__(self) -> Iterator[Term]: ... + def __contains__(self, key: Incomplete, /) -> bool: ... def __pos__(self, /) -> Self: ... def __neg__(self, /) -> Expr | GenExpr: ... def __abs__(self, /) -> AbsExpr: ... @@ -442,8 +443,6 @@ class Expr(ExprLike): @overload def __pow__(self, other: float, mod: Incomplete = ..., /) -> PowExpr: ... def __rpow__(self, other: float, /) -> ExpExpr: ... # type: ignore[override] - def __getitem__(self, index: Incomplete, /) -> Incomplete: ... - def __iter__(self) -> Incomplete: ... @disjoint_base class ExprCons: From afd9d034ad5974e8a474452b239a6b27572d6b01 Mon Sep 17 00:00:00 2001 From: 40% Date: Tue, 24 Nov 2026 00:12:01 +0800 Subject: [PATCH 25/36] correct variable name --- src/pyscipopt/scip.pxi | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/pyscipopt/scip.pxi b/src/pyscipopt/scip.pxi index aba6a9077..aa6bb0032 100644 --- a/src/pyscipopt/scip.pxi +++ b/src/pyscipopt/scip.pxi @@ -12756,7 +12756,7 @@ cdef class Model: cdef SCIP_OBJSENSE objsense cdef int i cdef _VarArray wrapper - cdef Expr _coeffs_expr + cdef Expr expr if sense == "minimize": objsense = SCIP_OBJSENSE_MINIMIZE @@ -12768,14 +12768,14 @@ cdef class Model: assert isinstance(coeffs, (Variable, Expr)), "given coefficients are not Variable or Expr but %s" % coeffs.__class__.__name__ # Variable is not an Expr anymore (M4): use its shared, read-only Expr view. - _coeffs_expr = (coeffs).as_expr() + expr = (coeffs).as_expr() - if _coeffs_expr.degree() > 1: + if expr.degree() > 1: raise ValueError("Nonlinear objective functions are not supported!") - if _coeffs_expr[CONST] != 0.0: + if expr[CONST] != 0.0: raise ValueError("Constant offsets in objective are not supported!") - nvars = len(_coeffs_expr.terms) - (CONST in _coeffs_expr.terms) + nvars = len(expr.terms) - (CONST in expr.terms) if nvars == 0: PY_SCIP_CALL(SCIPchgReoptObjective(self._scip, objsense, NULL, NULL, 0)) @@ -12785,7 +12785,7 @@ cdef class Model: vars = malloc(nvars * sizeof(SCIP_VAR*)) i = 0 - for term, coef in _coeffs_expr.terms.items(): + for term, coef in expr.terms.items(): # avoid CONST term of Expr if term != CONST: wrapper = _VarArray(term[0]) From b5a8eb80e84159a3f45fe35853e89dfd74b157eb Mon Sep 17 00:00:00 2001 From: 40% Date: Tue, 24 Nov 2026 12:04:35 +0800 Subject: [PATCH 26/36] avoid double checking --- src/pyscipopt/expr.pxi | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 4f665d69d..d564c1e96 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -409,9 +409,9 @@ cdef class Expr(ExprLike): self.terms[CONST] = 0.0 def __add__(self, other, /): + if isinstance(other, GenExpr): + return other + self if not _is_expr_compatible(other): - if isinstance(other, GenExpr): - return other + self return NotImplemented if _is_number(other): @@ -433,9 +433,9 @@ cdef class Expr(ExprLike): return self def __mul__(self, other, /): + if isinstance(other, GenExpr): + return other * self if not _is_expr_compatible(other): - if isinstance(other, GenExpr): - return other * self return NotImplemented cdef dict res = {} From f45344d3d67d129e231a3d1ae0ccdc77e805298a Mon Sep 17 00:00:00 2001 From: 40% Date: Tue, 24 Nov 2026 23:05:24 +0800 Subject: [PATCH 27/36] set variable concept to matrix --- src/pyscipopt/matrix.pxi | 8 +++-- src/pyscipopt/scip.pxi | 16 +++++----- src/pyscipopt/scip.pyi | 68 +++++++++++++++++++++------------------- 3 files changed, 49 insertions(+), 43 deletions(-) diff --git a/src/pyscipopt/matrix.pxi b/src/pyscipopt/matrix.pxi index b60e23c99..b607262fa 100644 --- a/src/pyscipopt/matrix.pxi +++ b/src/pyscipopt/matrix.pxi @@ -14,7 +14,7 @@ from pyscipopt.scip cimport Expr, Solution cnp.import_array() -class MatrixExpr(np.ndarray): +class MatrixExprLike(np.ndarray): __array_priority__ = 100 @@ -78,7 +78,11 @@ class MatrixExpr(np.ndarray): return _vec_evaluate(self, sol).view(np.ndarray) -class MatrixGenExpr(MatrixExpr): +class MatrixExpr(MatrixExprLike): + pass + + +class MatrixGenExpr(MatrixExprLike): pass diff --git a/src/pyscipopt/scip.pxi b/src/pyscipopt/scip.pxi index aa6bb0032..724117b8a 100644 --- a/src/pyscipopt/scip.pxi +++ b/src/pyscipopt/scip.pxi @@ -1137,12 +1137,12 @@ cdef class Solution: def __getitem__( self, - expr: Union[ExprLike, MatrixExpr], + expr: Union[ExprLike, MatrixExprLike], ) -> Union[float, np.ndarray]: - if not isinstance(expr, (ExprLike, MatrixExpr)): + if not isinstance(expr, (ExprLike, MatrixExprLike)): raise TypeError( "Argument 'expr' has incorrect type, expected 'Variable', 'Expr', " - f"'GenExpr', or 'MatrixExpr', got {type(expr).__name__!r}" + f"'GenExpr', 'MatrixVariable', or 'MatrixExpr', got {type(expr).__name__!r}" ) self._checkStage("SCIPgetSolVal") @@ -2025,7 +2025,7 @@ cdef class Variable(ExprLike): """ return SCIPvarGetNBranchingsCurrentRun(self.scip_var, branchdir) -class MatrixVariable(MatrixExpr): +class MatrixVariable(MatrixExprLike): def vtype(self): """ @@ -11784,7 +11784,7 @@ cdef class Model: def getSolVal( self, Solution sol, - expr: Union[ExprLike, MatrixExpr], + expr: Union[ExprLike, MatrixExprLike], ) -> Union[float, np.ndarray]: """ Retrieve value of given variable or expression in the given solution. @@ -11795,7 +11795,7 @@ cdef class Model: Solution to query the value from. If None, the current LP/pseudo solution is used. - expr : Variable, Expr, GenExpr, MatrixExpr + expr : Variable, Expr, GenExpr, MatrixVariable, MatrixExpr Expression to query the value of. Returns @@ -11810,14 +11810,14 @@ cdef class Model: # no need to create a NULL solution wrapper in case we have a variable return (sol or Solution.create(self._scip, NULL))[expr] - def getVal(self, expr: Union[ExprLike, MatrixExpr]) -> Union[float, np.ndarray]: + def getVal(self, expr: Union[ExprLike, MatrixExprLike]) -> Union[float, np.ndarray]: """ Retrieve the value of the given variable or expression in the best known solution. Can only be called after solving is completed. Parameters ---------- - expr : Variable, Expr, GenExpr or MatrixExpr + expr : Variable, Expr, GenExpr, MatrixVariable, MatrixExpr Expression to query the value of. Returns diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index 75dbb3782..96ab6ae7b 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -32,23 +32,23 @@ def str_conversion(x: str) -> bytes: ... @overload def exp(x: float | Expr | GenExpr) -> ExpExpr: ... @overload -def exp(x: list | tuple | np.ndarray | MatrixExpr) -> MatrixGenExpr: ... +def exp(x: list | tuple | np.ndarray | MatrixExprLike) -> MatrixGenExpr: ... @overload def log(x: float | Expr | GenExpr) -> LogExpr: ... @overload -def log(x: list | tuple | np.ndarray | MatrixExpr) -> MatrixGenExpr: ... +def log(x: list | tuple | np.ndarray | MatrixExprLike) -> MatrixGenExpr: ... @overload def sqrt(x: float | Expr | GenExpr) -> SqrtExpr: ... @overload -def sqrt(x: list | tuple | np.ndarray | MatrixExpr) -> MatrixGenExpr: ... +def sqrt(x: list | tuple | np.ndarray | MatrixExprLike) -> MatrixGenExpr: ... @overload def sin(x: float | Expr | GenExpr) -> SinExpr: ... @overload -def sin(x: list | tuple | np.ndarray | MatrixExpr) -> MatrixGenExpr: ... +def sin(x: list | tuple | np.ndarray | MatrixExprLike) -> MatrixGenExpr: ... @overload def cos(x: float | Expr | GenExpr) -> CosExpr: ... @overload -def cos(x: list | tuple | np.ndarray | MatrixExpr) -> MatrixGenExpr: ... +def cos(x: list | tuple | np.ndarray | MatrixExprLike) -> MatrixGenExpr: ... @disjoint_base class Benders: @@ -385,15 +385,15 @@ class ExprLike: @overload def __le__(self, other: float | ExprLike, /) -> ExprCons: ... @overload - def __le__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExprCons: ... # type: ignore[misc] + def __le__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExprCons: ... # type: ignore[misc] @overload def __ge__(self, other: float | ExprLike, /) -> ExprCons: ... @overload - def __ge__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExprCons: ... # type: ignore[misc] + def __ge__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExprCons: ... # type: ignore[misc] @overload # type: ignore[override] def __eq__(self, other: float | ExprLike, /) -> ExprCons: ... @overload - def __eq__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExprCons: ... + def __eq__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExprCons: ... @disjoint_base class Expr(ExprLike): @@ -408,28 +408,28 @@ class Expr(ExprLike): @overload def __add__(self, other: GenExpr, /) -> SumExpr: ... @overload - def __add__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExpr: ... + def __add__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExpr: ... def __radd__(self, other: float, /) -> Expr: ... # type: ignore[override] @overload # type: ignore[override] def __sub__(self, other: float | Expr, /) -> Expr: ... @overload def __sub__(self, other: GenExpr, /) -> SumExpr: ... @overload - def __sub__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExpr: ... + def __sub__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExpr: ... def __rsub__(self, other: float, /) -> Expr: ... # type: ignore[override] @overload # type: ignore[override] def __mul__(self, other: float | Expr, /) -> Expr: ... @overload def __mul__(self, other: GenExpr, /) -> ProdExpr: ... @overload - def __mul__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExpr: ... + def __mul__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExpr: ... def __rmul__(self, other: float, /) -> Expr: ... # type: ignore[override] @overload # type: ignore[override] def __truediv__(self, other: float, /) -> Expr: ... @overload def __truediv__(self, other: ExprLike, /) -> ProdExpr: ... @overload - def __truediv__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExpr: ... + def __truediv__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExpr: ... def __rtruediv__(self, other: float, /) -> ProdExpr: ... # type: ignore[override] # __pow__'s return type depends on the value of `other`: # non-negative integers (including integer-valued floats) yield Expr, @@ -472,22 +472,22 @@ class GenExpr(ExprLike): @overload # type: ignore[override] def __add__(self, other: float | ExprLike, /) -> SumExpr: ... @overload - def __add__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExpr: ... + def __add__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExpr: ... def __radd__(self, other: float, /) -> SumExpr: ... # type: ignore[override] @overload # type: ignore[override] def __sub__(self, other: float | ExprLike, /) -> SumExpr: ... @overload - def __sub__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExpr: ... + def __sub__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExpr: ... def __rsub__(self, other: float, /) -> SumExpr: ... # type: ignore[override] @overload # type: ignore[override] def __mul__(self, other: float | ExprLike, /) -> ProdExpr: ... @overload - def __mul__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExpr: ... + def __mul__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExpr: ... def __rmul__(self, other: float, /) -> ProdExpr: ... # type: ignore[override] @overload # type: ignore[override] def __truediv__(self, other: float | ExprLike, /) -> ProdExpr: ... @overload - def __truediv__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExpr: ... + def __truediv__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExpr: ... def __rtruediv__(self, other: float, /) -> ProdExpr: ... # type: ignore[override] def __pow__(self, other: float | Constant, mod: Incomplete = ..., /) -> PowExpr: ... # type: ignore[override] def __rpow__(self, other: float, mod: Incomplete = ..., /) -> ExpExpr: ... # type: ignore[override] @@ -616,7 +616,7 @@ class MatrixConstraint(np.ndarray): def isSeparated(self) -> Incomplete: ... def isStickingAtNode(self) -> Incomplete: ... -class MatrixExpr(np.ndarray): +class MatrixExprLike(np.ndarray): def _evaluate(self, sol: Solution) -> NDArray[np.object_]: ... def __array_ufunc__( self, @@ -628,36 +628,40 @@ class MatrixExpr(np.ndarray): def __neg__(self, /) -> MatrixExpr: ... def __abs__(self, /) -> MatrixExpr: ... def __add__( # type: ignore[override] - self, other: float | ExprLike | np.ndarray | MatrixExpr, / + self, other: float | ExprLike | np.ndarray | MatrixExprLike, / ) -> MatrixExpr: ... def __radd__(self, other: float, /) -> MatrixExpr: ... # type: ignore[override] def __sub__( # type: ignore[override] - self, other: float | ExprLike | np.ndarray | MatrixExpr, / + self, other: float | ExprLike | np.ndarray | MatrixExprLike, / ) -> MatrixExpr: ... def __rsub__(self, other: float, /) -> MatrixExpr: ... # type: ignore[override] def __mul__( # type: ignore[override] - self, other: float | ExprLike | np.ndarray | MatrixExpr, / + self, other: float | ExprLike | np.ndarray | MatrixExprLike, / ) -> MatrixExpr: ... def __rmul__(self, other: float, /) -> MatrixExpr: ... # type: ignore[override] def __truediv__( # type: ignore[override] - self, other: float | ExprLike | np.ndarray | MatrixExpr, / + self, other: float | ExprLike | np.ndarray | MatrixExprLike, / ) -> MatrixExpr: ... def __rtruediv__(self, other: float, /) -> MatrixExpr: ... # type: ignore[override] def __eq__( # type: ignore[override] - self, other: float | ExprLike | np.ndarray | MatrixExpr, / + self, other: float | ExprLike | np.ndarray | MatrixExprLike, / ) -> MatrixExprCons: ... def __le__( # type: ignore[override] - self, other: float | ExprLike | np.ndarray | MatrixExpr, / + self, other: float | ExprLike | np.ndarray | MatrixExprLike, / ) -> MatrixExprCons: ... def __ge__( # type: ignore[override] - self, other: float | ExprLike | np.ndarray | MatrixExpr, / + self, other: float | ExprLike | np.ndarray | MatrixExprLike, / ) -> MatrixExprCons: ... - def __matmul__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExpr: ... # type: ignore[override] + def __matmul__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExpr: ... # type: ignore[override] def __pow__( # type: ignore[override] self, other: float | np.ndarray, mod: Incomplete = ..., / ) -> MatrixExpr: ... def __rpow__(self, other: float, mod: Incomplete = ..., /) -> MatrixExpr: ... # type: ignore[override] +class MatrixExpr(MatrixExprLike): ... + +class MatrixGenExpr(MatrixExprLike): ... + class MatrixExprCons(np.ndarray): def __array_ufunc__( self, @@ -669,9 +673,7 @@ class MatrixExprCons(np.ndarray): def __ge__(self, other: float | np.ndarray, /) -> MatrixExprCons: ... # type: ignore[override] def __le__(self, other: float | np.ndarray, /) -> MatrixExprCons: ... # type: ignore[override] -class MatrixGenExpr(MatrixExpr): ... - -class MatrixVariable(MatrixExpr): +class MatrixVariable(MatrixExprLike): def getAvgSol(self) -> NDArray[np.float64]: ... def getCol(self) -> NDArray[np.object_]: ... def getIndex(self) -> NDArray[np.int_]: ... @@ -1429,7 +1431,7 @@ class Model: self, sol: Solution | None, expr: Variable | Expr | GenExpr ) -> float: ... @overload - def getSolVal(self, sol: Solution | None, expr: MatrixExpr) -> np.ndarray: ... + def getSolVal(self, sol: Solution | None, expr: MatrixExprLike) -> np.ndarray: ... def getSols(self) -> list[Solution]: ... def getSolvingTime(self) -> float: ... def getStage(self) -> PY_SCIP_STAGE: ... @@ -1470,7 +1472,7 @@ class Model: @overload def getVal(self, expr: Variable | Expr | GenExpr) -> float: ... @overload - def getVal(self, expr: MatrixExpr) -> np.ndarray: ... + def getVal(self, expr: MatrixExprLike) -> np.ndarray: ... def getValsLinear(self, cons: Constraint) -> dict[str, float]: ... def getVarDict(self, transformed: bool = False) -> dict[str, float]: ... def getVarLbDive(self, var: Variable) -> float: ... @@ -2364,9 +2366,9 @@ class Solution: def retransform(self) -> None: ... def translate(self, target: Model) -> Solution: ... @overload - def __getitem__(self, index: ExprLike, /) -> float: ... + def __getitem__(self, key: ExprLike, /) -> float: ... @overload - def __getitem__(self, index: MatrixExpr, /) -> np.ndarray: ... + def __getitem__(self, key: MatrixExprLike, /) -> np.ndarray: ... def __setitem__(self, key: Variable, value: float, /) -> None: ... class Statistics: @@ -2450,7 +2452,7 @@ class Term: def __mul__(self, other: Term, /) -> Term: ... def __eq__(self, other: object, /) -> bool: ... def __ge__(self, other: object, /) -> bool: ... - def __getitem__(self, index: Incomplete, /) -> Incomplete: ... + def __getitem__(self, key: Incomplete, /) -> Incomplete: ... def __gt__(self, other: object, /) -> bool: ... def __hash__(self) -> int: ... def __le__(self, other: object, /) -> bool: ... From b6ddcee29f57e924742ba12e6931e2f7ae58a35f Mon Sep 17 00:00:00 2001 From: 40% Date: Tue, 24 Nov 2026 23:37:54 +0800 Subject: [PATCH 28/36] Rename test_Variable.py to test_variable.py and convert to pytest --- tests/test_Variable.py | 105 ---------------------------------------- tests/test_variable.py | 107 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 107 insertions(+), 105 deletions(-) delete mode 100644 tests/test_Variable.py create mode 100644 tests/test_variable.py diff --git a/tests/test_Variable.py b/tests/test_Variable.py deleted file mode 100644 index 19cecab0b..000000000 --- a/tests/test_Variable.py +++ /dev/null @@ -1,105 +0,0 @@ -import unittest - -from pyscipopt import Model, quicksum, sqrt -from pyscipopt.scip import ( - CONST, - Expr, - ExprCons, - ExprLike, - GenExpr, - Term, - Variable, -) - - -class VariableTest(unittest.TestCase): - """Tests for the M4 semantics: Variable is an ExprLike, not an Expr.""" - - def setUp(self): - self.m = Model() - self.m.hideOutput() - self.x = self.m.addVar(name="x", lb=0, ub=10) - self.y = self.m.addVar(name="y", lb=0, ub=10) - - def test_isinstance_semantics(self): - x = self.x - self.assertIsInstance(x, ExprLike) - self.assertNotIsInstance(x, Expr) - self.assertIsInstance(x, Variable) - - expr = x + 1 - self.assertIsInstance(expr, Expr) - self.assertNotIsInstance(expr, Variable) - - gen = sqrt(x) - self.assertIsInstance(gen, GenExpr) - self.assertIsInstance(gen, ExprLike) - - def test_add_variables(self): - x, y = self.x, self.y - expr = x + y - self.assertIsInstance(expr, Expr) - self.assertEqual(len(expr.terms), 2) - self.assertEqual(expr[x], 1.0) - self.assertEqual(expr[y], 1.0) - self.assertEqual(expr[CONST], 0.0) - - def test_multiply_variable_with_itself(self): - x = self.x - square = x * x - self.assertIsInstance(square, Expr) - self.assertEqual(len(square.terms), 1) - self.assertEqual(square[Term(x) * Term(x)], 1.0) - self.assertEqual(square[x], 0.0) - - def test_subtract_variable_from_itself(self): - x = self.x - diff = x - x - self.assertIsInstance(diff, Expr) - self.assertEqual(diff[x], 0.0) - self.assertEqual(diff[CONST], 0.0) - - # Normalization through ExprCons drops the zero coefficient. - cons = ExprCons(diff, lhs=0.0) - self.assertEqual(cons.expr.terms, {}) - - def test_quicksum_matches_addition(self): - x, y = self.x, self.y - quick = quicksum([x, y]) - added = x + y - self.assertIsInstance(quick, Expr) - # quicksum starts from an Expr carrying an explicit zero constant term, - # so compare the coefficients instead of the raw dict. - self.assertEqual(quick[CONST], added[CONST]) - self.assertEqual(len(quick.terms) - 1, len(added.terms)) - for var in (x, y): - self.assertEqual(quick[var], added[var]) - - def test_operations_do_not_mutate_variable_view(self): - x, y = self.x, self.y - _ = x + y - _ = 2 * x - _ = quicksum([x, y]) - # x still represents exactly the variable term x - self.assertEqual(str(x), "x") - self.assertEqual(x[x], 1.0) - self.assertEqual(x[y], 0.0) - - def test_chgReoptObjective_with_variable(self): - m = self.m - x, y = self.x, self.y - m.enableReoptimization() - m.addCons(x + y <= 15) - m.setObjective(x + y, sense="maximize") - m.optimize() - self.assertAlmostEqual(m.getObjVal(), 15.0) - - m.freeReoptSolve() - # Regression: Variable used to be an Expr with a .terms attribute. - m.chgReoptObjective(x, sense="maximize") - m.optimize() - self.assertAlmostEqual(m.getVal(x), 10.0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_variable.py b/tests/test_variable.py new file mode 100644 index 000000000..9cb1df54e --- /dev/null +++ b/tests/test_variable.py @@ -0,0 +1,107 @@ +import pytest + +from pyscipopt import Model, quicksum, sqrt +from pyscipopt.scip import ( + CONST, + Expr, + ExprCons, + ExprLike, + GenExpr, + Term, + Variable, +) + + +@pytest.fixture +def model(): + """Tests for the M4 semantics: Variable is an ExprLike, not an Expr.""" + m = Model() + m.hideOutput() + x = m.addVar(name="x", lb=0, ub=10) + y = m.addVar(name="y", lb=0, ub=10) + return m, x, y + + +def test_isinstance_semantics(model): + _, x, _ = model + assert isinstance(x, ExprLike) + assert not isinstance(x, Expr) + assert isinstance(x, Variable) + + expr = x + 1 + assert isinstance(expr, Expr) + assert not isinstance(expr, Variable) + + gen = sqrt(x) + assert isinstance(gen, GenExpr) + assert isinstance(gen, ExprLike) + + +def test_add_variables(model): + _, x, y = model + expr = x + y + assert isinstance(expr, Expr) + assert len(expr.terms) == 2 + assert expr[x] == 1.0 + assert expr[y] == 1.0 + assert expr[CONST] == 0.0 + + +def test_multiply_variable_with_itself(model): + _, x, _ = model + square = x * x + assert isinstance(square, Expr) + assert len(square.terms) == 1 + assert square[Term(x) * Term(x)] == 1.0 + assert square[x] == 0.0 + + +def test_subtract_variable_from_itself(model): + _, x, _ = model + diff = x - x + assert isinstance(diff, Expr) + assert diff[x] == 0.0 + assert diff[CONST] == 0.0 + + # Normalization through ExprCons drops the zero coefficient. + cons = ExprCons(diff, lhs=0.0) + assert cons.expr.terms == {} + + +def test_quicksum_matches_addition(model): + _, x, y = model + quick = quicksum([x, y]) + added = x + y + assert isinstance(quick, Expr) + # quicksum starts from an Expr carrying an explicit zero constant term, + # so compare the coefficients instead of the raw dict. + assert quick[CONST] == added[CONST] + assert len(quick.terms) - 1 == len(added.terms) + for var in (x, y): + assert quick[var] == added[var] + + +def test_operations_do_not_mutate_variable_view(model): + _, x, y = model + _ = x + y + _ = 2 * x + _ = quicksum([x, y]) + # x still represents exactly the variable term x + assert str(x) == "x" + assert x[x] == 1.0 + assert x[y] == 0.0 + + +def test_chgReoptObjective_with_variable(model): + m, x, y = model + m.enableReoptimization() + m.addCons(x + y <= 15) + m.setObjective(x + y, sense="maximize") + m.optimize() + assert m.getObjVal() == pytest.approx(15.0) + + m.freeReoptSolve() + # Regression: Variable used to be an Expr with a .terms attribute. + m.chgReoptObjective(x, sense="maximize") + m.optimize() + assert m.getVal(x) == pytest.approx(10.0) From e913e47a5543ae259d7e4959130a745faec69ad4 Mon Sep 17 00:00:00 2001 From: 40% Date: Tue, 24 Nov 2026 23:38:09 +0800 Subject: [PATCH 29/36] Add CHANGELOG entry for matrix inheritance hierarchy refactor --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82996d911..c4760dd9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ - `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 +- Refactored the inheritance hierarchy of `MatrixVariable` and `MatrixGenExpr` from `MatrixExpr` to the base interface `MatrixExprLike` ### Removed - Removed support for Python 3.8 From 2610cf89b6d9b4af2ce512c6e025020acf873add Mon Sep 17 00:00:00 2001 From: 40% Date: Tue, 24 Nov 2026 23:40:11 +0800 Subject: [PATCH 30/36] Refresh mypy baseline after matrix hierarchy change --- tests/@types/expr.mypy.out | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/@types/expr.mypy.out b/tests/@types/expr.mypy.out index 28ba7158e..935a680d5 100644 --- a/tests/@types/expr.mypy.out +++ b/tests/@types/expr.mypy.out @@ -593,12 +593,10 @@ tests/@types/expr.py:2258: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:2271: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:2272: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:2273: error: Unused "type: ignore" comment [unused-ignore] -tests/@types/expr.py:2285: error: Expression is of type "ndarray[tuple[Any, ...], dtype[Any]]", not "MatrixExpr" [assert-type] tests/@types/expr.py:2287: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:2288: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:2289: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:2290: error: Unused "type: ignore" comment [unused-ignore] -tests/@types/expr.py:2301: error: Expression is of type "ndarray[tuple[Any, ...], dtype[Any]]", not "MatrixExpr" [assert-type] tests/@types/expr.py:2303: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:2304: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:2305: error: Unused "type: ignore" comment [unused-ignore] From 8722916537ea2a97e02676ba43922c5c89bebc3e Mon Sep 17 00:00:00 2001 From: 40% Date: Tue, 24 Nov 2026 23:44:56 +0800 Subject: [PATCH 31/36] correct the place of changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c4760dd9d..6de3b4612 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ - `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 +- Refactored the inheritance hierarchy of `Variable` from `Expr` to the base interface `ExprLike` - Refactored the inheritance hierarchy of `MatrixVariable` and `MatrixGenExpr` from `MatrixExpr` to the base interface `MatrixExprLike` ### Removed - Removed support for Python 3.8 @@ -51,7 +52,6 @@ - Speed up `ProdExpr.__neg__` and `Constant.__neg__` via C-level API (#1250) - Extended `structured_optimization_trace` recipe to support context-managed JSONL tracing with final `run_end` records, alongside the existing attach-style in-memory tracing. - Integration tests now run in the merge queue before merging instead of after pushing to `master` (#1249) -- Refactored the inheritance hierarchy of `Variable` from `Expr` to the base interface `ExprLike` ### Removed - `SumExpr`.coefs has been removed; its values were always 1.0 (#1258) - Deprecated `getOp` method in `GenExpr` (#1259) From 2c333ba3ca257c57bdfbac2a5a29cf6f9c534b01 Mon Sep 17 00:00:00 2001 From: 40% Date: Wed, 25 Nov 2026 00:17:46 +0800 Subject: [PATCH 32/36] Fix stubtest mismatches for pow, Variable init, and unused allowlist entries --- src/pyscipopt/scip.pyi | 7 +++---- stubs/allowlist | 6 ------ 2 files changed, 3 insertions(+), 10 deletions(-) diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index 96ab6ae7b..a204c50c6 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -374,8 +374,8 @@ class ExprLike: def __rmul__(self, other: object, /) -> Incomplete: ... def __truediv__(self, other: object, /) -> Incomplete: ... def __rtruediv__(self, other: object, /) -> GenExpr: ... - def __pow__(self, other: object, /) -> Incomplete: ... - def __rpow__(self, other: object, /) -> Incomplete: ... + def __pow__(self, other: object, mod: Incomplete = ..., /) -> Incomplete: ... + def __rpow__(self, other: object, mod: Incomplete = ..., /) -> Incomplete: ... def exp(self, /) -> ExpExpr: ... def log(self, /) -> LogExpr: ... def sqrt(self, /) -> SqrtExpr: ... @@ -659,7 +659,6 @@ class MatrixExprLike(np.ndarray): def __rpow__(self, other: float, mod: Incomplete = ..., /) -> MatrixExpr: ... # type: ignore[override] class MatrixExpr(MatrixExprLike): ... - class MatrixGenExpr(MatrixExprLike): ... class MatrixExprCons(np.ndarray): @@ -2479,7 +2478,7 @@ class VarExpr(GenExpr): class Variable(ExprLike): data: Any name: str - def __init__(self) -> None: ... + def __init__(self, *args: Incomplete, **kwargs: Incomplete) -> None: ... def __neg__(self, /) -> Expr: ... def getAvgSol(self) -> float: ... def getCol(self) -> Column: ... diff --git a/stubs/allowlist b/stubs/allowlist index 33d6a8c28..7b1f3b387 100644 --- a/stubs/allowlist +++ b/stubs/allowlist @@ -1,12 +1,6 @@ .*.__reduce_cython__ .*.__setstate_cython__ pyscipopt.scip.__test__ -# These exist at runtime but aren't useful in the stubs, they are added to the child classes -pyscipopt.scip.ExprLike.__radd__ -pyscipopt.scip.ExprLike.__rmul__ -pyscipopt.scip.ExprLike.__rsub__ -pyscipopt.scip.ExprLike.__rtruediv__ -pyscipopt.scip.ExprLike.__sub__ # Cython exposes generic signatures; these constructors reject arguments at runtime. pyscipopt.scip.PowExpr.__init__ pyscipopt.scip.ProdExpr.__init__ From d280ef4f935a2b6bf6e6fa418d78bcc84f978a61 Mon Sep 17 00:00:00 2001 From: 40% Date: Wed, 25 Nov 2026 22:55:52 +0800 Subject: [PATCH 33/36] Restore typed arithmetic overloads for Variable and refresh mypy baseline --- src/pyscipopt/scip.pyi | 55 ++++++++++++++++++++++++++++++-------- tests/@types/expr.mypy.out | 40 ++++++++++++--------------- 2 files changed, 61 insertions(+), 34 deletions(-) diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index a204c50c6..cdbea788a 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -30,23 +30,23 @@ def print_memory_in_use() -> None: ... def readStatistics(filename: StrOrBytesPath) -> Statistics: ... def str_conversion(x: str) -> bytes: ... @overload -def exp(x: float | Expr | GenExpr) -> ExpExpr: ... +def exp(x: float | Expr | GenExpr | Variable) -> ExpExpr: ... @overload def exp(x: list | tuple | np.ndarray | MatrixExprLike) -> MatrixGenExpr: ... @overload -def log(x: float | Expr | GenExpr) -> LogExpr: ... +def log(x: float | Expr | GenExpr | Variable) -> LogExpr: ... @overload def log(x: list | tuple | np.ndarray | MatrixExprLike) -> MatrixGenExpr: ... @overload -def sqrt(x: float | Expr | GenExpr) -> SqrtExpr: ... +def sqrt(x: float | Expr | GenExpr | Variable) -> SqrtExpr: ... @overload def sqrt(x: list | tuple | np.ndarray | MatrixExprLike) -> MatrixGenExpr: ... @overload -def sin(x: float | Expr | GenExpr) -> SinExpr: ... +def sin(x: float | Expr | GenExpr | Variable) -> SinExpr: ... @overload def sin(x: list | tuple | np.ndarray | MatrixExprLike) -> MatrixGenExpr: ... @overload -def cos(x: float | Expr | GenExpr) -> CosExpr: ... +def cos(x: float | Expr | GenExpr | Variable) -> CosExpr: ... @overload def cos(x: list | tuple | np.ndarray | MatrixExprLike) -> MatrixGenExpr: ... @@ -404,24 +404,24 @@ class Expr(ExprLike): def __neg__(self, /) -> Expr: ... def __iadd__(self, other: Incomplete, /) -> Incomplete: ... # type: ignore[misc] @overload # type: ignore[override] - def __add__(self, other: float | Expr, /) -> Expr: ... - @overload def __add__(self, other: GenExpr, /) -> SumExpr: ... @overload + def __add__(self, other: float | Expr | Variable, /) -> Expr: ... + @overload def __add__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExpr: ... def __radd__(self, other: float, /) -> Expr: ... # type: ignore[override] @overload # type: ignore[override] - def __sub__(self, other: float | Expr, /) -> Expr: ... - @overload def __sub__(self, other: GenExpr, /) -> SumExpr: ... @overload + def __sub__(self, other: float | Expr | Variable, /) -> Expr: ... + @overload def __sub__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExpr: ... def __rsub__(self, other: float, /) -> Expr: ... # type: ignore[override] @overload # type: ignore[override] - def __mul__(self, other: float | Expr, /) -> Expr: ... - @overload def __mul__(self, other: GenExpr, /) -> ProdExpr: ... @overload + def __mul__(self, other: float | Expr | Variable, /) -> Expr: ... + @overload def __mul__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExpr: ... def __rmul__(self, other: float, /) -> Expr: ... # type: ignore[override] @overload # type: ignore[override] @@ -2480,6 +2480,39 @@ class Variable(ExprLike): name: str def __init__(self, *args: Incomplete, **kwargs: Incomplete) -> None: ... def __neg__(self, /) -> Expr: ... + @overload # type: ignore[override] + def __add__(self, other: GenExpr, /) -> SumExpr: ... + @overload + def __add__(self, other: float | Expr | Variable, /) -> Expr: ... + @overload + def __add__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExpr: ... + def __radd__(self, other: float, /) -> Expr: ... # type: ignore[override] + @overload # type: ignore[override] + def __sub__(self, other: GenExpr, /) -> SumExpr: ... + @overload + def __sub__(self, other: float | Expr | Variable, /) -> Expr: ... + @overload + def __sub__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExpr: ... + def __rsub__(self, other: float, /) -> Expr: ... # type: ignore[override] + @overload # type: ignore[override] + def __mul__(self, other: GenExpr, /) -> ProdExpr: ... + @overload + def __mul__(self, other: float | Expr | Variable, /) -> Expr: ... + @overload + def __mul__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExpr: ... + def __rmul__(self, other: float, /) -> Expr: ... # type: ignore[override] + @overload # type: ignore[override] + def __truediv__(self, other: float, /) -> Expr: ... + @overload + def __truediv__(self, other: ExprLike, /) -> ProdExpr: ... + @overload + def __truediv__(self, other: np.ndarray | MatrixExprLike, /) -> MatrixExpr: ... + def __rtruediv__(self, other: float, /) -> ProdExpr: ... # type: ignore[override] + @overload # type: ignore[override] + def __pow__(self, other: int, mod: Incomplete = ..., /) -> Expr: ... + @overload + def __pow__(self, other: float, mod: Incomplete = ..., /) -> PowExpr: ... + def __rpow__(self, other: float, mod: Incomplete = ..., /) -> ExpExpr: ... # type: ignore[override] def getAvgSol(self) -> float: ... def getCol(self) -> Column: ... def getImplType(self) -> PY_SCIP_IMPLINTTYPE: ... diff --git a/tests/@types/expr.mypy.out b/tests/@types/expr.mypy.out index 935a680d5..ba9f421a0 100644 --- a/tests/@types/expr.mypy.out +++ b/tests/@types/expr.mypy.out @@ -67,13 +67,13 @@ tests/@types/expr.py:476: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:491: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:507: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:512: error: Expression is of type "Any", not "Expr" [assert-type] -tests/@types/expr.py:512: error: No overload variant of "__add__" of "Expr" matches argument type "Decimal" [operator] +tests/@types/expr.py:512: error: No overload variant of "__add__" of "Variable" matches argument type "Decimal" [operator] tests/@types/expr.py:513: error: Expression is of type "Any", not "Expr" [assert-type] -tests/@types/expr.py:513: error: No overload variant of "__sub__" of "Expr" matches argument type "Decimal" [operator] +tests/@types/expr.py:513: error: No overload variant of "__sub__" of "Variable" matches argument type "Decimal" [operator] tests/@types/expr.py:514: error: Expression is of type "Any", not "Expr" [assert-type] -tests/@types/expr.py:514: error: No overload variant of "__mul__" of "Expr" matches argument type "Decimal" [operator] +tests/@types/expr.py:514: error: No overload variant of "__mul__" of "Variable" matches argument type "Decimal" [operator] tests/@types/expr.py:515: error: Expression is of type "Any", not "Expr" [assert-type] -tests/@types/expr.py:515: error: No overload variant of "__pow__" of "Expr" matches argument type "Decimal" [operator] +tests/@types/expr.py:515: error: No overload variant of "__pow__" of "Variable" matches argument type "Decimal" [operator] tests/@types/expr.py:516: error: Expression is of type "Any", not "ExprCons" [assert-type] tests/@types/expr.py:516: error: No overload variant of "__le__" of "ExprLike" matches argument type "Decimal" [operator] tests/@types/expr.py:517: error: Expression is of type "Any", not "ExprCons" [assert-type] @@ -2297,6 +2297,7 @@ tests/@types/expr.py:6461: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:6462: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:6463: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:6474: error: Incompatible types in assignment (expression has type "Expr", variable has type "Variable") [assignment] +tests/@types/expr.py:6475: error: Expression is of type "Variable", not "Expr" [assert-type] tests/@types/expr.py:6480: error: Incompatible types in assignment (expression has type "Expr", variable has type "Variable") [assignment] tests/@types/expr.py:6481: error: Expression is of type "Variable", not "Expr" [assert-type] tests/@types/expr.py:6486: error: Incompatible types in assignment (expression has type "Expr", variable has type "Variable") [assignment] @@ -2330,6 +2331,7 @@ tests/@types/expr.py:6631: error: Expression is of type "Variable", not "ProdExp tests/@types/expr.py:6636: error: Incompatible types in assignment (expression has type "ProdExpr", variable has type "Variable") [assignment] tests/@types/expr.py:6637: error: Expression is of type "Variable", not "ProdExpr" [assert-type] tests/@types/expr.py:6655: error: Incompatible types in assignment (expression has type "Expr", variable has type "Variable") [assignment] +tests/@types/expr.py:6656: error: Expression is of type "Variable", not "Expr" [assert-type] tests/@types/expr.py:6661: error: Incompatible types in assignment (expression has type "Expr", variable has type "Variable") [assignment] tests/@types/expr.py:6662: error: Expression is of type "Variable", not "Expr" [assert-type] tests/@types/expr.py:6667: error: Incompatible types in assignment (expression has type "Expr", variable has type "Variable") [assignment] @@ -2388,6 +2390,7 @@ tests/@types/expr.py:6896: error: Expression is of type "Variable", not "ProdExp tests/@types/expr.py:6967: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:6972: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:6980: error: Incompatible types in assignment (expression has type "Expr", variable has type "Variable") [assignment] +tests/@types/expr.py:6981: error: Expression is of type "Variable", not "Expr" [assert-type] tests/@types/expr.py:6986: error: Incompatible types in assignment (expression has type "Expr", variable has type "Variable") [assignment] tests/@types/expr.py:6987: error: Expression is of type "Variable", not "Expr" [assert-type] tests/@types/expr.py:6992: error: Incompatible types in assignment (expression has type "Expr", variable has type "Variable") [assignment] @@ -2397,6 +2400,7 @@ tests/@types/expr.py:6999: error: Expression is of type "Variable", not "Expr" tests/@types/expr.py:7004: error: Incompatible types in assignment (expression has type "Expr", variable has type "Variable") [assignment] tests/@types/expr.py:7005: error: Expression is of type "Variable", not "Expr" [assert-type] tests/@types/expr.py:7018: error: Incompatible types in assignment (expression has type "Expr", variable has type "Variable") [assignment] +tests/@types/expr.py:7019: error: Expression is of type "Variable", not "Expr" [assert-type] tests/@types/expr.py:7024: error: Incompatible types in assignment (expression has type "Expr", variable has type "Variable") [assignment] tests/@types/expr.py:7025: error: Expression is of type "Variable", not "Expr" [assert-type] tests/@types/expr.py:7030: error: Incompatible types in assignment (expression has type "Expr", variable has type "Variable") [assignment] @@ -2405,15 +2409,16 @@ tests/@types/expr.py:7036: error: Incompatible types in assignment (expression h tests/@types/expr.py:7037: error: Expression is of type "Variable", not "Expr" [assert-type] tests/@types/expr.py:7042: error: Incompatible types in assignment (expression has type "PowExpr", variable has type "Variable") [assignment] tests/@types/expr.py:7043: error: Expression is of type "Variable", not "PowExpr" [assert-type] -tests/@types/expr.py:7056: error: No overload variant of "__add__" of "Expr" matches argument type "Decimal" [operator] -tests/@types/expr.py:7057: error: Expression is of type "Any", not "Variable" [assert-type] -tests/@types/expr.py:7062: error: No overload variant of "__sub__" of "Expr" matches argument type "Decimal" [operator] +tests/@types/expr.py:7056: error: No overload variant of "__add__" of "Variable" matches argument type "Decimal" [operator] +tests/@types/expr.py:7057: error: Expression is of type "Any", not "Expr" [assert-type] +tests/@types/expr.py:7062: error: No overload variant of "__sub__" of "Variable" matches argument type "Decimal" [operator] tests/@types/expr.py:7063: error: Expression is of type "Any", not "Expr" [assert-type] -tests/@types/expr.py:7068: error: No overload variant of "__mul__" of "Expr" matches argument type "Decimal" [operator] +tests/@types/expr.py:7068: error: No overload variant of "__mul__" of "Variable" matches argument type "Decimal" [operator] tests/@types/expr.py:7069: error: Expression is of type "Any", not "Expr" [assert-type] -tests/@types/expr.py:7079: error: No overload variant of "__pow__" of "Expr" matches argument type "Decimal" [operator] +tests/@types/expr.py:7079: error: No overload variant of "__pow__" of "Variable" matches argument type "Decimal" [operator] tests/@types/expr.py:7080: error: Expression is of type "Any", not "Expr" [assert-type] tests/@types/expr.py:7093: error: Incompatible types in assignment (expression has type "Expr", variable has type "Variable") [assignment] +tests/@types/expr.py:7094: error: Expression is of type "Variable", not "Expr" [assert-type] tests/@types/expr.py:7099: error: Incompatible types in assignment (expression has type "Expr", variable has type "Variable") [assignment] tests/@types/expr.py:7100: error: Expression is of type "Variable", not "Expr" [assert-type] tests/@types/expr.py:7105: error: Incompatible types in assignment (expression has type "Expr", variable has type "Variable") [assignment] @@ -2926,7 +2931,6 @@ tests/@types/expr.py:10263: error: Unused "type: ignore" comment [unused-ignore tests/@types/expr.py:10268: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:10294: error: Incompatible types in assignment (expression has type "ProdExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10295: error: Expression is of type "Expr", not "ProdExpr" [assert-type] -tests/@types/expr.py:10313: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10314: error: Expression is of type "Expr", not "MatrixExpr" [assert-type] tests/@types/expr.py:10319: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10320: error: Expression is of type "Expr", not "MatrixExpr" [assert-type] @@ -2935,7 +2939,6 @@ tests/@types/expr.py:10326: error: Expression is of type "Expr", not "MatrixExpr tests/@types/expr.py:10331: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10332: error: Expression is of type "Expr", not "MatrixExpr" [assert-type] tests/@types/expr.py:10342: error: Unused "type: ignore" comment [unused-ignore] -tests/@types/expr.py:10350: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10351: error: Expression is of type "Expr", not "MatrixExpr" [assert-type] tests/@types/expr.py:10356: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10357: error: Expression is of type "Expr", not "MatrixExpr" [assert-type] @@ -2944,7 +2947,7 @@ tests/@types/expr.py:10363: error: Expression is of type "Expr", not "MatrixExpr tests/@types/expr.py:10368: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10369: error: Expression is of type "Expr", not "MatrixExpr" [assert-type] tests/@types/expr.py:10379: error: Unused "type: ignore" comment [unused-ignore] -tests/@types/expr.py:10420: error: Incompatible types in assignment (expression has type "SumExpr", variable has type "Expr") [assignment] +tests/@types/expr.py:10387: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:10421: error: Expression is of type "Expr", not "SumExpr" [assert-type] tests/@types/expr.py:10426: error: Incompatible types in assignment (expression has type "SumExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10427: error: Expression is of type "Expr", not "SumExpr" [assert-type] @@ -2954,7 +2957,6 @@ tests/@types/expr.py:10438: error: Incompatible types in assignment (expression tests/@types/expr.py:10439: error: Expression is of type "Expr", not "ProdExpr" [assert-type] tests/@types/expr.py:10475: error: Incompatible types in assignment (expression has type "ProdExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10476: error: Expression is of type "Expr", not "ProdExpr" [assert-type] -tests/@types/expr.py:10494: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10495: error: Expression is of type "Expr", not "MatrixExpr" [assert-type] tests/@types/expr.py:10500: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10501: error: Expression is of type "Expr", not "MatrixExpr" [assert-type] @@ -2963,7 +2965,6 @@ tests/@types/expr.py:10507: error: Expression is of type "Expr", not "MatrixExpr tests/@types/expr.py:10512: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10513: error: Expression is of type "Expr", not "MatrixExpr" [assert-type] tests/@types/expr.py:10523: error: Unused "type: ignore" comment [unused-ignore] -tests/@types/expr.py:10531: error: Incompatible types in assignment (expression has type "SumExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10532: error: Expression is of type "Expr", not "SumExpr" [assert-type] tests/@types/expr.py:10537: error: Incompatible types in assignment (expression has type "SumExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10538: error: Expression is of type "Expr", not "SumExpr" [assert-type] @@ -2971,7 +2972,6 @@ tests/@types/expr.py:10543: error: Incompatible types in assignment (expression tests/@types/expr.py:10544: error: Expression is of type "Expr", not "ProdExpr" [assert-type] tests/@types/expr.py:10549: error: Incompatible types in assignment (expression has type "ProdExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10550: error: Expression is of type "Expr", not "ProdExpr" [assert-type] -tests/@types/expr.py:10568: error: Incompatible types in assignment (expression has type "SumExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10569: error: Expression is of type "Expr", not "SumExpr" [assert-type] tests/@types/expr.py:10574: error: Incompatible types in assignment (expression has type "SumExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10575: error: Expression is of type "Expr", not "SumExpr" [assert-type] @@ -2979,7 +2979,6 @@ tests/@types/expr.py:10580: error: Incompatible types in assignment (expression tests/@types/expr.py:10581: error: Expression is of type "Expr", not "ProdExpr" [assert-type] tests/@types/expr.py:10586: error: Incompatible types in assignment (expression has type "ProdExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10587: error: Expression is of type "Expr", not "ProdExpr" [assert-type] -tests/@types/expr.py:10605: error: Incompatible types in assignment (expression has type "SumExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10606: error: Expression is of type "Expr", not "SumExpr" [assert-type] tests/@types/expr.py:10611: error: Incompatible types in assignment (expression has type "SumExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10612: error: Expression is of type "Expr", not "SumExpr" [assert-type] @@ -2987,7 +2986,6 @@ tests/@types/expr.py:10617: error: Incompatible types in assignment (expression tests/@types/expr.py:10618: error: Expression is of type "Expr", not "ProdExpr" [assert-type] tests/@types/expr.py:10623: error: Incompatible types in assignment (expression has type "ProdExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10624: error: Expression is of type "Expr", not "ProdExpr" [assert-type] -tests/@types/expr.py:10642: error: Incompatible types in assignment (expression has type "SumExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10643: error: Expression is of type "Expr", not "SumExpr" [assert-type] tests/@types/expr.py:10648: error: Incompatible types in assignment (expression has type "SumExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10649: error: Expression is of type "Expr", not "SumExpr" [assert-type] @@ -2995,7 +2993,6 @@ tests/@types/expr.py:10654: error: Incompatible types in assignment (expression tests/@types/expr.py:10655: error: Expression is of type "Expr", not "ProdExpr" [assert-type] tests/@types/expr.py:10660: error: Incompatible types in assignment (expression has type "ProdExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10661: error: Expression is of type "Expr", not "ProdExpr" [assert-type] -tests/@types/expr.py:10679: error: Incompatible types in assignment (expression has type "SumExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10680: error: Expression is of type "Expr", not "SumExpr" [assert-type] tests/@types/expr.py:10685: error: Incompatible types in assignment (expression has type "SumExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10686: error: Expression is of type "Expr", not "SumExpr" [assert-type] @@ -3003,12 +3000,12 @@ tests/@types/expr.py:10691: error: Incompatible types in assignment (expression tests/@types/expr.py:10692: error: Expression is of type "Expr", not "ProdExpr" [assert-type] tests/@types/expr.py:10697: error: Incompatible types in assignment (expression has type "ProdExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10698: error: Expression is of type "Expr", not "ProdExpr" [assert-type] +tests/@types/expr.py:10716: error: Unused "type: ignore" comment [unused-ignore] +tests/@types/expr.py:10749: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:10769: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:10774: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:10844: error: Incompatible types in assignment (expression has type "PowExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10845: error: Expression is of type "Expr", not "PowExpr" [assert-type] -tests/@types/expr.py:10858: error: No overload variant of "__add__" of "Expr" matches argument type "Decimal" [operator] -tests/@types/expr.py:10859: error: Expression is of type "Any", not "Expr" [assert-type] tests/@types/expr.py:10864: error: No overload variant of "__sub__" of "Expr" matches argument type "Decimal" [operator] tests/@types/expr.py:10865: error: Expression is of type "Any", not "Expr" [assert-type] tests/@types/expr.py:10870: error: No overload variant of "__mul__" of "Expr" matches argument type "Decimal" [operator] @@ -3016,13 +3013,11 @@ tests/@types/expr.py:10871: error: Expression is of type "Any", not "Expr" [ass tests/@types/expr.py:10881: error: No overload variant of "__pow__" of "Expr" matches argument type "Decimal" [operator] tests/@types/expr.py:10882: error: Expression is of type "Any", not "Expr" [assert-type] tests/@types/expr.py:10919: error: Incompatible types in assignment (expression has type "PowExpr", variable has type "Expr") [assignment] -tests/@types/expr.py:10933: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10939: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10945: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10951: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10958: error: Expression is of type "Any", not "Expr" [assert-type] tests/@types/expr.py:10963: error: Unused "type: ignore" comment [unused-ignore] -tests/@types/expr.py:10971: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10972: error: Expression is of type "Expr", not "MatrixExpr" [assert-type] tests/@types/expr.py:10977: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:10978: error: Expression is of type "Expr", not "MatrixExpr" [assert-type] @@ -3032,7 +3027,6 @@ tests/@types/expr.py:10989: error: Incompatible types in assignment (expression tests/@types/expr.py:10990: error: Expression is of type "Expr", not "MatrixExpr" [assert-type] tests/@types/expr.py:10995: error: Unused "type: ignore" comment [unused-ignore] tests/@types/expr.py:11000: error: Unused "type: ignore" comment [unused-ignore] -tests/@types/expr.py:11008: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:11009: error: Expression is of type "Expr", not "MatrixExpr" [assert-type] tests/@types/expr.py:11014: error: Incompatible types in assignment (expression has type "MatrixExpr", variable has type "Expr") [assignment] tests/@types/expr.py:11015: error: Expression is of type "Expr", not "MatrixExpr" [assert-type] From b1d213f5294451e96c627bf3c8a925425eeda912 Mon Sep 17 00:00:00 2001 From: 40% Date: Wed, 25 Nov 2026 22:55:56 +0800 Subject: [PATCH 34/36] Add tests for ExprLike indexing, iteration, membership, and degree --- tests/test_expr.py | 55 +++++++++++++++++++++++++++++++++-- tests/test_matrix_variable.py | 14 ++++++++- tests/test_variable.py | 11 +++++++ 3 files changed, 77 insertions(+), 3 deletions(-) diff --git a/tests/test_expr.py b/tests/test_expr.py index 2976c253e..21bc4bb52 100644 --- a/tests/test_expr.py +++ b/tests/test_expr.py @@ -136,8 +136,59 @@ def test_genexpr_op_genexpr(model): def test_degree(model): m, x, y, z = model - expr = GenExpr() - assert expr.degree() == float('inf') + assert GenExpr().degree() == float('inf') + + # ExprLike.degree is the maximum number of variables in a term + assert (x + y).degree() == 1.0 + assert (x * y).degree() == 2.0 + assert (x * y * z).degree() == 3.0 + assert (x ** 2).degree() == 2.0 + assert Expr().degree() == 0.0 + # zero coefficients are only dropped on normalization + assert (x - x).degree() == 1.0 + assert x.degree() == 1.0 + + +def test_getitem(model): + m, x, y, z = model + expr = 2 * x + 3 * y + 5 + assert expr[x] == 2.0 + assert expr[y] == 3.0 + assert expr[Term(x)] == 2.0 + assert expr[CONST] == 5.0 + assert expr[z] == 0.0 + + with pytest.raises(TypeError, match="index must be a Term or Variable, got None"): + expr[None] + with pytest.raises(TypeError, match="index must be a Term or Variable, got int"): + expr[1] + + +def test_iter(model): + m, x, y, z = model + expr = 2 * x + 3 * y + terms = list(expr) + assert len(terms) == 2 + assert all(isinstance(term, Term) for term in terms) + assert set(terms) == {Term(x), Term(y)} + + +def test_contains(model): + m, x, y, z = model + expr = 2 * x + 3 * y + assert x in expr + assert Term(x) in expr + assert z not in expr + assert None not in expr + assert 1 not in expr + assert Term(x) * Term(y) not in expr + + +def test_contains_genexpr_raises(model): + m, x, y, z = model + with pytest.raises(TypeError, match="cannot be used with 'in'"): + x in exp(x) + # In contrast to Expr inequalities, we can't expect much of the sides def test_inequality(model): diff --git a/tests/test_matrix_variable.py b/tests/test_matrix_variable.py index 0aa022e29..85e38f068 100644 --- a/tests/test_matrix_variable.py +++ b/tests/test_matrix_variable.py @@ -20,7 +20,7 @@ sin, sqrt, ) -from pyscipopt.scip import CONST, GenExpr +from pyscipopt.scip import CONST, GenExpr, MatrixExprLike, MatrixGenExpr def test_catching_errors(): @@ -711,3 +711,15 @@ def test_evaluate(): assert type(m.getVal(x)) is np.ndarray assert m.getVal(x).sum() == 1 + + +def test_matrix_exprlike_hierarchy(): + m = Model() + mvar = m.addMatrixVar(shape=(2,)) + assert isinstance(mvar, MatrixExprLike) + assert not isinstance(mvar, MatrixExpr) + + gen = sqrt([2, 2]) + assert isinstance(gen, MatrixGenExpr) + assert isinstance(gen, MatrixExprLike) + assert not isinstance(gen, MatrixExpr) diff --git a/tests/test_variable.py b/tests/test_variable.py index 9cb1df54e..3e4c46712 100644 --- a/tests/test_variable.py +++ b/tests/test_variable.py @@ -92,6 +92,17 @@ def test_operations_do_not_mutate_variable_view(model): assert x[y] == 0.0 +def test_degree_and_membership(model): + _, x, y = model + assert x.degree() == 1.0 + + expr = 2 * x + 3 * y + assert x in expr + assert y in expr + assert x not in (y + 1) + assert set(expr) == {Term(x), Term(y)} + + def test_chgReoptObjective_with_variable(model): m, x, y = model m.enableReoptimization() From df531a471d61ececf3833ad6bfc9e3cc248639fe Mon Sep 17 00:00:00 2001 From: 40% Date: Wed, 25 Nov 2026 22:58:34 +0800 Subject: [PATCH 35/36] simplify the type --- src/pyscipopt/scip.pyi | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index cdbea788a..aa5d2fa8c 100644 --- a/src/pyscipopt/scip.pyi +++ b/src/pyscipopt/scip.pyi @@ -30,23 +30,23 @@ def print_memory_in_use() -> None: ... def readStatistics(filename: StrOrBytesPath) -> Statistics: ... def str_conversion(x: str) -> bytes: ... @overload -def exp(x: float | Expr | GenExpr | Variable) -> ExpExpr: ... +def exp(x: float | ExprLike) -> ExpExpr: ... @overload def exp(x: list | tuple | np.ndarray | MatrixExprLike) -> MatrixGenExpr: ... @overload -def log(x: float | Expr | GenExpr | Variable) -> LogExpr: ... +def log(x: float | ExprLike) -> LogExpr: ... @overload def log(x: list | tuple | np.ndarray | MatrixExprLike) -> MatrixGenExpr: ... @overload -def sqrt(x: float | Expr | GenExpr | Variable) -> SqrtExpr: ... +def sqrt(x: float | ExprLike) -> SqrtExpr: ... @overload def sqrt(x: list | tuple | np.ndarray | MatrixExprLike) -> MatrixGenExpr: ... @overload -def sin(x: float | Expr | GenExpr | Variable) -> SinExpr: ... +def sin(x: float | ExprLike) -> SinExpr: ... @overload def sin(x: list | tuple | np.ndarray | MatrixExprLike) -> MatrixGenExpr: ... @overload -def cos(x: float | Expr | GenExpr | Variable) -> CosExpr: ... +def cos(x: float | ExprLike) -> CosExpr: ... @overload def cos(x: list | tuple | np.ndarray | MatrixExprLike) -> MatrixGenExpr: ... From ed09cf70ff78c16a80a2d7f1115179cfbf3ad202 Mon Sep 17 00:00:00 2001 From: 40% Date: Wed, 25 Nov 2026 23:24:20 +0800 Subject: [PATCH 36/36] update error type --- src/pyscipopt/scip.pxi | 6 +++--- tests/test_variable.py | 6 ++++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/pyscipopt/scip.pxi b/src/pyscipopt/scip.pxi index 724117b8a..161caa34e 100644 --- a/src/pyscipopt/scip.pxi +++ b/src/pyscipopt/scip.pxi @@ -1563,9 +1563,9 @@ cdef class Node: cdef class Variable(ExprLike): def __init__(self, *_): - raise NotImplementedError( - "Direct instantiation of 'Variable' is not supported. " - "Please use Model to create variables." + raise TypeError( + "cannot create 'Variable' instances directly, " + "use Model.addVar() instead" ) @staticmethod diff --git a/tests/test_variable.py b/tests/test_variable.py index 3e4c46712..60fe8583c 100644 --- a/tests/test_variable.py +++ b/tests/test_variable.py @@ -92,6 +92,12 @@ def test_operations_do_not_mutate_variable_view(model): assert x[y] == 0.0 +def test_direct_instantiation_is_rejected(): + # A Variable must be backed by a SCIP_VAR*, so it can only come from a Model. + with pytest.raises(TypeError, match="cannot create 'Variable' instances"): + Variable() + + def test_degree_and_membership(model): _, x, y = model assert x.degree() == 1.0