diff --git a/CHANGELOG.md b/CHANGELOG.md index d4fb44353..6de3b4612 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,8 @@ - `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 diff --git a/src/pyscipopt/expr.pxi b/src/pyscipopt/expr.pxi index 09601e59a..d564c1e96 100644 --- a/src/pyscipopt/expr.pxi +++ b/src/pyscipopt/expr.pxi @@ -188,7 +188,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}") @@ -196,12 +196,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: @@ -229,7 +229,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__": @@ -272,7 +272,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: @@ -286,6 +286,34 @@ cdef class ExprLike: return NotImplemented + 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): + 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): + 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 + def __radd__(self, other, /): return self + other @@ -295,19 +323,31 @@ cdef class ExprLike: def __rsub__(self, other, /): return (-self) + other + def __mul__(self, other, /): + return self.as_expr() * other + def __rmul__(self, other, /): return self * other + def __truediv__(self, other, /): + return self.as_expr() / other + def __rtruediv__(self, other, /) -> GenExpr: return buildGenExprObj(other) / self + 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) def __neg__(self, /) -> Union[Expr, GenExpr]: return self * -1.0 - def __pos__(self, /) -> Union[Expr, GenExpr]: + def __pos__(self, /) -> ExprLike: return self.copy() def __abs__(self, /) -> AbsExpr: @@ -328,11 +368,27 @@ cdef class ExprLike: def cos(self, /) -> CosExpr: return CosExpr(Operator.cos, buildGenExprObj(self)) - cpdef double _evaluate(self, Solution sol) except *: + cpdef double degree(self) except? -1: + cdef Expr expr = self.as_expr() + cdef double deg = 0, res = 0 + cdef Term t + for t in expr.terms: + deg = len(t) + if deg > res: + res = deg + return res + + cdef Expr 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 void normalize(self): + self.as_expr().normalize() + + cpdef double _evaluate(self, Solution sol) except *: + return self.as_expr()._evaluate(sol) + cdef ExprLike copy(self, bint copy=True): raise NotImplementedError( f"{self.__class__.__name__!s} need to implement copy() method" @@ -352,15 +408,9 @@ 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): + def __add__(self, other, /): + if isinstance(other, GenExpr): + return other + self if not _is_expr_compatible(other): return NotImplemented @@ -371,7 +421,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 @@ -382,7 +432,9 @@ cdef class Expr(ExprLike): return self - def __mul__(self, other): + def __mul__(self, other, /): + if isinstance(other, GenExpr): + return other * self if not _is_expr_compatible(other): return NotImplemented @@ -401,10 +453,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: @@ -413,7 +465,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 @@ -426,7 +478,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 @@ -437,7 +489,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. @@ -449,19 +501,15 @@ 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) -> str: 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) + 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} cpdef double _evaluate(self, Solution sol) except *: cdef double res = 0 @@ -502,14 +550,16 @@ 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()" - def normalize(self): + 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 - self.expr.normalize() + (self.expr).normalize() else: assert isinstance(self.expr, GenExpr) return @@ -606,7 +656,16 @@ cdef class GenExpr(ExprLike): def __init__(self): # do we need it ''' ''' - def __add__(self, other): + def __getitem__(self, _): + raise TypeError(f"{self.__class__.__name__!s} cannot be indexed") + + 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 @@ -657,7 +716,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 @@ -707,7 +766,7 @@ cdef class GenExpr(ExprLike): # self.children.append(right) # return self - def __pow__(self, other, modulo): + def __pow__(self, other, /): expo = buildGenExprObj(other) if Py_TYPE(expo) is not Constant: raise NotImplementedError("exponents must be numbers") @@ -719,7 +778,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. @@ -732,7 +791,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 @@ -747,7 +806,7 @@ cdef class GenExpr(ExprLike): return NotImplemented return super().__rtruediv__(other) - def degree(self): + cpdef double degree(self) except? -1: '''Note: none of these expressions should be polynomial''' return INFINITY @@ -771,6 +830,9 @@ cdef class GenExpr(ExprLike): f"{self.__class__.__name__!s} need to implement to_scip_expr() method" ) + cdef void normalize(self): + ... + cdef GenExpr copy(self, bint copy=True): cdef object cls = Py_TYPE(self) cdef GenExpr res = cls.__new__(cls) @@ -907,7 +969,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 @@ -952,7 +1014,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] @@ -1104,7 +1166,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 @@ -1128,7 +1190,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 @@ -1152,7 +1214,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 @@ -1176,7 +1238,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 @@ -1200,7 +1262,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 @@ -1229,7 +1291,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 @@ -1255,11 +1317,17 @@ 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 Expr _expr = (expr).as_expr() + cdef Expr _other = (other).as_expr() + cdef dict children = _expr.terms.copy() if copy else _expr.terms cdef Py_ssize_t pos = 0 cdef PyObject* k_ptr = NULL cdef PyObject* v_ptr = NULL @@ -1267,7 +1335,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.terms, &pos, &k_ptr, &v_ptr): other_v = (v_ptr) k_obj = k_ptr old_v_ptr = PyDict_GetItem(children, k_obj) @@ -1287,14 +1355,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, ExprLike], int op, ): if isinstance(other, np.ndarray): 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.pxd b/src/pyscipopt/scip.pxd index a7e79f992..882fcb390 100644 --- a/src/pyscipopt/scip.pxd +++ b/src/pyscipopt/scip.pxd @@ -2211,6 +2211,9 @@ 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) cdef ExprLike copy(self, bint copy=*) @@ -2293,8 +2296,9 @@ cdef class Node: @staticmethod cdef create(SCIP_NODE* scipnode) -cdef class Variable(Expr): +cdef class Variable(ExprLike): cdef SCIP_VAR* scip_var + 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 aee5de9c1..161caa34e 100644 --- a/src/pyscipopt/scip.pxi +++ b/src/pyscipopt/scip.pxi @@ -1137,12 +1137,12 @@ cdef class Solution: def __getitem__( self, - expr: Union[Expr, GenExpr, MatrixExpr], + expr: Union[ExprLike, MatrixExprLike], ) -> Union[float, np.ndarray]: - if not isinstance(expr, (Expr, GenExpr, MatrixExpr)): + if not isinstance(expr, (ExprLike, MatrixExprLike)): 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', 'MatrixVariable', or 'MatrixExpr', got {type(expr).__name__!r}" ) self._checkStage("SCIPgetSolVal") @@ -1560,17 +1560,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 TypeError( + "cannot create 'Variable' instances directly, " + "use Model.addVar() instead" + ) @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 @@ -1579,11 +1584,14 @@ 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) + cdef Expr expr = Expr.__new__(Expr) + var.scip_var = scip_var + expr.terms = {Term(var): 1.0} + var._expr = expr return var @property @@ -1601,6 +1609,9 @@ cdef class Variable(Expr): def __repr__(self): return self.name + cdef Expr as_expr(self): + return self._expr + def vtype(self): """ Retrieve the variables type (BINARY, INTEGER, CONTINUOUS, or IMPLINT) @@ -2014,7 +2025,7 @@ cdef class Variable(Expr): """ return SCIPvarGetNBranchingsCurrentRun(self.scip_var, branchdir) -class MatrixVariable(MatrixExpr): +class MatrixVariable(MatrixExprLike): def vtype(self): """ @@ -4317,7 +4328,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') @@ -4331,9 +4342,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 @@ -4376,7 +4387,7 @@ cdef class Model: """ variables = self.getVars() - objective = Expr() + cdef Expr objective = Expr() for var in variables: coeff = var.getObj() if coeff != 0: @@ -7291,14 +7302,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 """ @@ -11773,7 +11784,7 @@ cdef class Model: def getSolVal( self, Solution sol, - expr: Union[Expr, GenExpr, MatrixExpr], + expr: Union[ExprLike, MatrixExprLike], ) -> Union[float, np.ndarray]: """ Retrieve value of given variable or expression in the given solution. @@ -11784,7 +11795,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, MatrixVariable, MatrixExpr Expression to query the value of. Returns @@ -11799,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[Expr, GenExpr, 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 : Expr, GenExpr or MatrixExpr + expr : Variable, Expr, GenExpr, MatrixVariable, MatrixExpr Expression to query the value of. Returns @@ -12727,13 +12738,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') @@ -12745,6 +12756,7 @@ cdef class Model: cdef SCIP_OBJSENSE objsense cdef int i cdef _VarArray wrapper + cdef Expr expr if sense == "minimize": objsense = SCIP_OBJSENSE_MINIMIZE @@ -12753,14 +12765,17 @@ 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: + # Variable is not an Expr anymore (M4): use its shared, read-only Expr view. + expr = (coeffs).as_expr() + + if expr.degree() > 1: raise ValueError("Nonlinear objective functions are not supported!") - if coeffs[CONST] != 0.0: + if expr[CONST] != 0.0: raise ValueError("Constant offsets in objective are not supported!") - nvars = len(coeffs.terms) - (CONST in coeffs.terms) + nvars = len(expr.terms) - (CONST in expr.terms) if nvars == 0: PY_SCIP_CALL(SCIPchgReoptObjective(self._scip, objsense, NULL, NULL, 0)) @@ -12770,7 +12785,7 @@ cdef class Model: vars = malloc(nvars * sizeof(SCIP_VAR*)) i = 0 - for term, coef in coeffs.terms.items(): + for term, coef in expr.terms.items(): # avoid CONST term of Expr if term != CONST: wrapper = _VarArray(term[0]) diff --git a/src/pyscipopt/scip.pyi b/src/pyscipopt/scip.pyi index a83baa645..aa5d2fa8c 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 @@ -30,25 +30,25 @@ 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 | ExprLike) -> 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: ... +def log(x: float | ExprLike) -> 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: ... +def sqrt(x: float | ExprLike) -> 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: ... +def sin(x: float | ExprLike) -> 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: ... +def cos(x: float | ExprLike) -> CosExpr: ... @overload -def cos(x: list | tuple | np.ndarray | MatrixExpr) -> MatrixGenExpr: ... +def cos(x: list | tuple | np.ndarray | MatrixExprLike) -> MatrixGenExpr: ... @disjoint_base class Benders: @@ -360,63 +360,77 @@ class ExprLike: *args: Incomplete, **kwargs: Incomplete, ) -> 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, /) -> ExprLike: ... + def __neg__(self, /) -> Expr | GenExpr: ... def __abs__(self, /) -> AbsExpr: ... + 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, mod: Incomplete = ..., /) -> Incomplete: ... + def __rpow__(self, other: object, mod: Incomplete = ..., /) -> Incomplete: ... def exp(self, /) -> ExpExpr: ... def log(self, /) -> LogExpr: ... def sqrt(self, /) -> SqrtExpr: ... def sin(self, /) -> SinExpr: ... def cos(self, /) -> CosExpr: ... + def degree(self, /) -> float: ... @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): @property def terms(self) -> dict[Term, float]: ... def __init__(self, terms: Incomplete = None) -> None: ... - def degree(self) -> int: ... - def normalize(self) -> None: ... + def degree(self) -> float: ... def __neg__(self, /) -> Expr: ... - @overload - def __add__(self, other: float | Expr, /) -> Expr: ... - @overload + def __iadd__(self, other: Incomplete, /) -> Incomplete: ... # type: ignore[misc] + @overload # type: ignore[override] def __add__(self, other: GenExpr, /) -> SumExpr: ... @overload - def __add__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExpr: ... - def __radd__(self, other: float, /) -> Expr: ... - @overload - def __sub__(self, other: float | Expr, /) -> Expr: ... + 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: np.ndarray | MatrixExpr, /) -> MatrixExpr: ... - def __rsub__(self, other: float, /) -> Expr: ... - @overload - def __mul__(self, other: float | Expr, /) -> Expr: ... + 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: np.ndarray | MatrixExpr, /) -> MatrixExpr: ... - def __rmul__(self, other: float, /) -> Expr: ... + 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: Expr | GenExpr, /) -> ProdExpr: ... + def __truediv__(self, other: ExprLike, /) -> ProdExpr: ... @overload - def __truediv__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExpr: ... - def __rtruediv__(self, other: float, /) -> ProdExpr: ... + 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, # negative integers and non-integers yield PowExpr @@ -424,18 +438,16 @@ class Expr(ExprLike): # knowing it might be wrong in some cases, and likewise the float case as # PowExpr can be wrong. We aim to make the stubs useful in common cases # even though the type system cannot fully express the real types. - @overload + @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, /) -> ExpExpr: ... - def __getitem__(self, index: Incomplete, /) -> Incomplete: ... - def __iter__(self) -> Incomplete: ... + def __rpow__(self, other: float, /) -> ExpExpr: ... # type: ignore[override] @disjoint_base class ExprCons: @property - def expr(self) -> Expr | GenExpr: ... + def expr(self) -> ExprLike: ... @property def _lhs(self) -> float | None: ... @property @@ -443,7 +455,6 @@ class ExprCons: def __init__( self, expr: ExprLike, lhs: float | None = None, rhs: float | None = None ) -> None: ... - def normalize(self) -> None: ... def __bool__(self) -> bool: ... def __ge__(self, other: float, /) -> ExprCons: ... def __le__(self, other: float, /) -> ExprCons: ... @@ -458,28 +469,28 @@ class GenExpr(ExprLike): @deprecated("Deprecated since 6.3.0; use type(expr) instead.") def getOp(self) -> str | None: ... def __neg__(self, /) -> ProdExpr | Constant: ... - @overload + @overload # type: ignore[override] def __add__(self, other: float | ExprLike, /) -> SumExpr: ... @overload - def __add__(self, other: np.ndarray | MatrixExpr, /) -> MatrixExpr: ... - def __radd__(self, other: float, /) -> SumExpr: ... - @overload + 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 __rsub__(self, other: float, /) -> SumExpr: ... - @overload + 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 __rmul__(self, other: float, /) -> ProdExpr: ... - @overload + 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 __rtruediv__(self, other: float, /) -> ProdExpr: ... - def __pow__(self, other: float | Constant, mod: Incomplete = ..., /) -> PowExpr: ... - def __rpow__(self, other: float, mod: Incomplete = ..., /) -> ExpExpr: ... + 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] @disjoint_base class Heur: @@ -605,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, @@ -617,36 +628,39 @@ 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, @@ -658,9 +672,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_]: ... @@ -971,7 +983,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 +1123,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: 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: ... @@ -1412,9 +1426,11 @@ 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: 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 getSolVal(self, sol: Solution | None, expr: MatrixExprLike) -> np.ndarray: ... def getSols(self) -> list[Solution]: ... def getSolvingTime(self) -> float: ... def getStage(self) -> PY_SCIP_STAGE: ... @@ -1453,9 +1469,9 @@ class Model: def getTransformedVar(self, var: Variable) -> Variable: ... def getTreesizeEstimation(self) -> float: ... @overload - def getVal(self, expr: Expr | GenExpr) -> float: ... + 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: ... @@ -1708,7 +1724,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: ... @@ -2349,9 +2365,9 @@ class Solution: def retransform(self) -> None: ... def translate(self, target: Model) -> Solution: ... @overload - def __getitem__(self, index: Expr | GenExpr, /) -> 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: @@ -2435,7 +2451,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: ... @@ -2455,14 +2471,48 @@ 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 -class Variable(Expr): +class Variable(ExprLike): data: Any name: str - def __init__(self) -> None: ... + 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/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__ diff --git a/tests/@types/expr.mypy.out b/tests/@types/expr.mypy.out index 28ba7158e..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] @@ -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] @@ -2299,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] @@ -2332,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] @@ -2390,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] @@ -2399,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] @@ -2407,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] @@ -2928,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] @@ -2937,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] @@ -2946,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] @@ -2956,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] @@ -2965,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] @@ -2973,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] @@ -2981,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] @@ -2989,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] @@ -2997,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] @@ -3005,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] @@ -3018,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] @@ -3034,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] 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 new file mode 100644 index 000000000..60fe8583c --- /dev/null +++ b/tests/test_variable.py @@ -0,0 +1,124 @@ +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_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 + + 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() + 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)