Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
0988f86
refactor: replace Python math with C-level math functions and refacto…
Zeroto521 Jun 8, 2026
3c7a981
feat(type stubs): add specific unary expression types
Zeroto521 Jun 8, 2026
166dc21
Update CHANGELOG.md
Zeroto521 Jun 8, 2026
647f8ac
style(scip): condense UnaryExpr subclass definitions to single lines
Zeroto521 Jun 8, 2026
fadf4e1
Remove extra blank line
Zeroto521 Jun 9, 2026
c27fe01
Remove extra blank lines
Zeroto521 Jun 9, 2026
e5bdabc
Simplify via `ExprLike.__abs__`
Zeroto521 Jun 11, 2026
8294d8a
test C-level math functions
Zeroto521 Jun 11, 2026
94131e9
Merge branch 'master' into UnaryExpr
Zeroto521 Jun 21, 2026
c681760
let `_evaluate` as the base method
Zeroto521 Jun 21, 2026
c0750cb
Merge branch 'master' into UnaryExpr
Joao-Dionisio Jun 21, 2026
b919f18
Merge branch 'master' into UnaryExpr
Zeroto521 Sep 6, 2026
e5063c0
raise error for log(inputing <= 0)
Zeroto521 Sep 6, 2026
df92b3f
raise error for sqrt(inputing < 0)
Zeroto521 Sep 6, 2026
9db933a
replace `float('inf')` with `INFINITY`
Zeroto521 Sep 6, 2026
ad0a977
raise error if sin(inputing is inf)
Zeroto521 Sep 6, 2026
d2bda36
raise error if cos(inputing is inf)
Zeroto521 Sep 6, 2026
7683db2
add test cases for math domain error
Zeroto521 Sep 6, 2026
261a83b
Update return types for mathematical functions in scip.pyi
Zeroto521 Sep 9, 2026
e15d943
update expr mypy baseline for typed unary expressions
Zeroto521 Sep 9, 2026
623a742
Fix mypy type errors and unused ignore comments
Zeroto521 Sep 9, 2026
abf181e
Merge branch 'master' into UnaryExpr
Zeroto521 Sep 16, 2026
0467eb1
resort the importing
Zeroto521 Sep 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,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 (#1205)
- Replace Python math with C-level math functions and refactor unary expressions (#1224)
- 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.
### Removed
Expand Down
99 changes: 76 additions & 23 deletions src/pyscipopt/expr.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@
# which should, in princple, modify the expr. However, since we do not implement __isub__, __sub__
# gets called (I guess) and so a copy is returned.
# Modifying the expression directly would be a bug, given that the expression might be re-used by the user. </pre>
import math
from typing import TYPE_CHECKING, Literal, Union

import numpy as np
Expand All @@ -54,6 +53,13 @@ from cpython.number cimport PyNumber_Check
from cpython.object cimport Py_LE, Py_EQ, Py_GE, Py_TYPE
from cpython.ref cimport PyObject
from cpython.tuple cimport PyTuple_GET_ITEM
from libc.math cimport cos as c_cos
from libc.math cimport exp as c_exp
from libc.math cimport fabs as c_fabs
from libc.math cimport log as c_log
from libc.math cimport sqrt as c_sqrt
from libc.math cimport sin as c_sin
from libc.math cimport INFINITY

cimport numpy as cnp
from pyscipopt.scip cimport Variable, Solution
Expand Down Expand Up @@ -281,23 +287,28 @@ cdef class ExprLike:
def __pos__(self, /) -> Union[Expr, GenExpr]:
return self.copy()

def __abs__(self) -> GenExpr:
return UnaryExpr(Operator.fabs, buildGenExprObj(self))
def __abs__(self, /) -> AbsExpr:
return AbsExpr(Operator.fabs, buildGenExprObj(self))

def exp(self) -> GenExpr:
return UnaryExpr(Operator.exp, buildGenExprObj(self))
def exp(self, /) -> ExpExpr:
return ExpExpr(Operator.exp, buildGenExprObj(self))

def log(self) -> GenExpr:
return UnaryExpr(Operator.log, buildGenExprObj(self))
def log(self, /) -> LogExpr:
return LogExpr(Operator.log, buildGenExprObj(self))

def sqrt(self) -> GenExpr:
return UnaryExpr(Operator.sqrt, buildGenExprObj(self))
def sqrt(self, /) -> SqrtExpr:
return SqrtExpr(Operator.sqrt, buildGenExprObj(self))

def sin(self) -> GenExpr:
return UnaryExpr(Operator.sin, buildGenExprObj(self))
def sin(self, /) -> SinExpr:
return SinExpr(Operator.sin, buildGenExprObj(self))

def cos(self) -> GenExpr:
return UnaryExpr(Operator.cos, buildGenExprObj(self))
def cos(self, /) -> CosExpr:
return CosExpr(Operator.cos, buildGenExprObj(self))

cpdef double _evaluate(self, Solution sol) except *:
raise NotImplementedError(
f"{self.__class__.__name__!s} need to implement _evaluate() method"
)

cdef ExprLike copy(self, bint copy=True):
raise NotImplementedError(
Expand Down Expand Up @@ -711,7 +722,7 @@ cdef class GenExpr(ExprLike):

def degree(self):
'''Note: none of these expressions should be polynomial'''
return float('inf')
return INFINITY

def getOp(self):
'''returns operator of GenExpr'''
Expand Down Expand Up @@ -833,24 +844,66 @@ cdef class PowExpr(GenExpr):
return res


# Exp, Log, Sqrt, Sin, Cos Expressions
cdef class UnaryExpr(GenExpr):

def __init__(self, op, expr):
self.children = []
self.children.append(expr)
self._op = op

def __abs__(self) -> UnaryExpr:
if self._op == "abs":
return <UnaryExpr>self.copy()
return UnaryExpr(Operator.fabs, self)
Comment thread
Joao-Dionisio marked this conversation as resolved.
Resolved

def __repr__(self):
def __repr__(self) -> str:
return self._op + "(" + self.children[0].__repr__() + ")"


cdef class AbsExpr(UnaryExpr):

def __abs__(self) -> AbsExpr:
return <AbsExpr>self.copy()

cpdef double _evaluate(self, Solution sol) except *:
return c_fabs((<GenExpr>self.children[0])._evaluate(sol))

Comment thread
Zeroto521 marked this conversation as resolved.
Resolved

cdef class ExpExpr(UnaryExpr):

cpdef double _evaluate(self, Solution sol) except *:
return c_exp((<GenExpr>self.children[0])._evaluate(sol))


cdef class LogExpr(UnaryExpr):

cpdef double _evaluate(self, Solution sol) except *:
cdef double val = (<GenExpr>self.children[0])._evaluate(sol)
if val <= 0.0:
raise ValueError("math domain error")
return c_log(val)


cdef class SqrtExpr(UnaryExpr):

cpdef double _evaluate(self, Solution sol) except *:
cdef double val = (<GenExpr>self.children[0])._evaluate(sol)
if val < 0.0:
raise ValueError("math domain error")
return c_sqrt(val)


cdef class SinExpr(UnaryExpr):

cpdef double _evaluate(self, Solution sol) except *:
cdef double val = (<GenExpr>self.children[0])._evaluate(sol)
if c_fabs(val) == INFINITY:
Comment thread
Joao-Dionisio marked this conversation as resolved.
Resolved
raise ValueError("math domain error")
return c_sin(val)


cdef class CosExpr(UnaryExpr):

cpdef double _evaluate(self, Solution sol) except *:
cdef double res = (<GenExpr>self.children[0])._evaluate(sol)
return math.fabs(res) if self._op == "abs" else getattr(math, self._op)(res)
cdef double val = (<GenExpr>self.children[0])._evaluate(sol)
if c_fabs(val) == INFINITY:
raise ValueError("math domain error")
return c_cos(val)


# class for constant expressions
Expand Down
3 changes: 1 addition & 2 deletions src/pyscipopt/scip.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -2188,13 +2188,12 @@ cdef extern from "tpi/tpi.h":

cdef class ExprLike:

cpdef double _evaluate(self, Solution sol)
cdef ExprLike copy(self, bint copy=*)

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
Expand Down
35 changes: 21 additions & 14 deletions src/pyscipopt/scip.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -31,23 +31,23 @@ str_conversion: Incomplete
value_to_array: Incomplete

@overload
def exp(x: float | Expr | GenExpr) -> UnaryExpr: ...
def exp(x: float | Expr | GenExpr) -> ExpExpr: ...
@overload
def exp(x: list | tuple | np.ndarray | MatrixExpr) -> MatrixGenExpr: ...
@overload
def log(x: float | Expr | GenExpr) -> UnaryExpr: ...
def log(x: float | Expr | GenExpr) -> LogExpr: ...
@overload
def log(x: list | tuple | np.ndarray | MatrixExpr) -> MatrixGenExpr: ...
@overload
def sqrt(x: float | Expr | GenExpr) -> UnaryExpr: ...
def sqrt(x: float | Expr | GenExpr) -> SqrtExpr: ...
@overload
def sqrt(x: list | tuple | np.ndarray | MatrixExpr) -> MatrixGenExpr: ...
@overload
def sin(x: float | Expr | GenExpr) -> UnaryExpr: ...
def sin(x: float | Expr | GenExpr) -> SinExpr: ...
@overload
def sin(x: list | tuple | np.ndarray | MatrixExpr) -> MatrixGenExpr: ...
@overload
def cos(x: float | Expr | GenExpr) -> UnaryExpr: ...
def cos(x: float | Expr | GenExpr) -> CosExpr: ...
@overload
def cos(x: list | tuple | np.ndarray | MatrixExpr) -> MatrixGenExpr: ...

Expand Down Expand Up @@ -357,12 +357,12 @@ class ExprLike:
) -> Incomplete: ...
def __pos__(self, /) -> Self: ...
def __neg__(self, /) -> ExprLike: ...
def __abs__(self, /) -> UnaryExpr: ...
def exp(self) -> UnaryExpr: ...
def log(self) -> UnaryExpr: ...
def sqrt(self) -> UnaryExpr: ...
def sin(self) -> UnaryExpr: ...
def cos(self) -> UnaryExpr: ...
def __abs__(self, /) -> AbsExpr: ...
def exp(self, /) -> ExpExpr: ...
def log(self, /) -> LogExpr: ...
def sqrt(self, /) -> SqrtExpr: ...
def sin(self, /) -> SinExpr: ...
def cos(self, /) -> CosExpr: ...
@overload
def __le__(self, other: float | ExprLike, /) -> ExprCons: ...
@overload
Expand Down Expand Up @@ -422,7 +422,7 @@ class Expr(ExprLike):
def __pow__(self, other: int, mod: Incomplete = ..., /) -> Expr: ...
@overload
def __pow__(self, other: float, mod: Incomplete = ..., /) -> PowExpr: ...
def __rpow__(self, other: float, /) -> UnaryExpr: ...
def __rpow__(self, other: float, /) -> ExpExpr: ...
def __getitem__(self, index: Incomplete, /) -> Incomplete: ...
def __iter__(self) -> Incomplete: ...

Expand Down Expand Up @@ -468,7 +468,7 @@ class GenExpr(ExprLike):
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 = ..., /) -> UnaryExpr: ...
def __rpow__(self, other: float, mod: Incomplete = ..., /) -> ExpExpr: ...

@disjoint_base
class Heur:
Expand Down Expand Up @@ -590,7 +590,7 @@ class MatrixConstraint(np.ndarray):
def isStickingAtNode(self) -> Incomplete: ...

class MatrixExpr(np.ndarray):
def _evaluate(self, sol: Incomplete) -> Incomplete: ...
def _evaluate(self, sol: Solution) -> Incomplete: ...
def __array_ufunc__(
self,
ufunc: np.ufunc,
Expand Down Expand Up @@ -2378,6 +2378,13 @@ class UnaryExpr(GenExpr):
def __init__(self, *args: Incomplete, **kwargs: Incomplete) -> None: ...
def __neg__(self, /) -> ProdExpr: ...

class AbsExpr(UnaryExpr): ...
class ExpExpr(UnaryExpr): ...
class LogExpr(UnaryExpr): ...
class SqrtExpr(UnaryExpr): ...
class SinExpr(UnaryExpr): ...
class CosExpr(UnaryExpr): ...

@disjoint_base
class VarExpr(GenExpr):
var: Incomplete
Expand Down
Loading
Loading