Speed up -SumExpr, -ProdExpr and -Constant#1179
Conversation
Refactors the __neg__ method in the Expr class to use Cython's PyDict_Next and PyDict_SetItem for more efficient negation of terms, replacing the previous Python dict comprehension.
Introduces a copy method to GenExpr for duplicating expression objects, with support for deep or shallow copying. Also implements the __neg__ method for ProdExpr to allow negation of product expressions by negating their constant term.
Added explicit return type annotations to the __neg__ methods in Expr and ProdExpr classes, and updated the corresponding type hints in scip.pyi. This improves type checking and code clarity.
Refactors SumExpr to use cpython.array for storing coefficients instead of Python lists, improving performance and memory efficiency. Adds a __neg__ method for SumExpr to efficiently negate coefficients and the constant term. Updates the copy method to properly clone arrays when copying SumExpr instances.
Introduces the test_neg function to verify correct behavior when negating ProdExpr and SumExpr objects in the expression API. Ensures that negated expressions have the expected types, string representations, and coefficients.
Added an entry noting the speedup of `Expr.__neg__`, `ProdExpr.__neg__`, and `Constant.__neg__` using the C-level API.
The @disjoint_base decorator was removed from the UnaryExpr class in the type stub, possibly to correct or update the class hierarchy or decorator usage.
There was a problem hiding this comment.
Pull request overview
This PR aims to speed up expression negation by moving __neg__ implementations to faster C-level loops for core expression types.
Changes:
- Optimized
Expr.__neg__by iterating the underlying term dictionary using CPython C-API helpers. - Added specialized
__neg__implementations forSumExprandProdExpr(including newGenExpr.copyhelper). - Added a new unit test covering negation behavior for
ProdExprandSumExpr, and refined type stubs for__neg__.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
tests/test_expr.py |
Adds a test_neg test validating negation results/types for product and sum expressions. |
src/pyscipopt/scip.pyi |
Tightens typing for __neg__ on Expr and GenExpr. |
src/pyscipopt/expr.pxi |
Implements faster negation paths and introduces GenExpr.copy; changes SumExpr.coefs storage to array('d'). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Changed the type of 'coefs' from list to memoryview (double[:]) in SumExpr._evaluate for more efficient access during evaluation.
Refactors the negation method in SumExpr to correctly create a new instance, negate the constant, copy children, and set the operator. This ensures proper behavior when negating sum expressions.
Implemented the __neg__ method for the Constant class, allowing unary negation of constant expressions.
Imported Constant from pyscipopt.scip and added an assertion to test the string representation of the negated Constant expression in test_neg.
-Expr and -ProdExpr and -Constant-Expr, SumExpr, -ProdExpr and -Constant
-Expr, SumExpr, -ProdExpr and -Constant-Expr, -SumExpr, -ProdExpr and -Constant
Added assertions to test_neg to verify correct negation and string representation of expressions involving powers. This enhances test coverage for expression negation logic.
Clarified that `SumExpr.__neg__` is also sped up via the C-level API, in addition to other negation methods.
| def __init__(self): | ||
| self.constant = 0.0 | ||
| self.coefs = [] | ||
| self.coefs = array("d") |
There was a problem hiding this comment.
@Joao-Dionisio Could you have a loook about this problem? SumExpr.coefs has a bug, so this CI failed.
If SumExpr.coefs is not [1, 1], the result from expr_to_array to addCons won't be right.
All GenExpr will use the expr_to_array function to add to SCIP. But expr_to_array doesn't have any code to handle SumExpr.coefs. SumExpr.coefs doesn't work at all.
PySCIPOpt/src/pyscipopt/expr.pxi
Lines 829 to 849 in bc24757
Two solutions to fix this.
- Remove
SumExpr.coefs. Any coefficient to aSumExprwill be aProdExpr. And each element coefficient should be 1. We follow current behavior. So,SumExpr.coefsrelated codes could be removed. - Let
expr_to_arraysupportSumExpr.coefs.
There was a problem hiding this comment.
SumExpr.coefs has a bug. So the latest CI is still failing.
There was a problem hiding this comment.
SumExpr.coefs has a bug, as I said before. There are two solutions we could fix that. @Joao-Dionisio
- Remove
SumExpr.coefs. Any coefficient to aSumExprwill be aProdExpr. And each element coefficient should be 1. We follow current behavior. So,SumExpr.coefsrelated codes could be removed. - Let
expr_to_arraysupportSumExpr.coefs.
There was a problem hiding this comment.
I'd rather extend the support of expr_to_array. A suggestion:
- In
expr_to_array: forOperator.add, includeexpr.coefsandexpr.constantin the node tuple instead of appending the constant - In
scip.pxi(theOperator.addbranch): read the actual coefs and constant from the node and pass them toSCIPcreateExprSum.
Do you think this might fix things?
There was a problem hiding this comment.
I want to drop SumExpr.coefs now.
When I'm working on expr_to_array, I find that SumExpr.coefs can't be printed well. The coefficient should be close to its value. But children and coefs both are list, they are not a single dict. Although we could use zip, it is not a better way for __repr__.
def __repr__(self):
return self._op + "(" + str(self.constant) + "," + ",".join(map(lambda child : child.__repr__(), self.children)) + ")"Replaces usage of cpython.array for storing coefficients in SumExpr with standard Python lists. Simplifies code by removing array-specific imports and clone operations, improving maintainability and compatibility.
Removed the unused GenExpr.copy() method and refactored the __neg__ methods for SumExpr and ProdExpr to avoid using the copy method. This simplifies the code and clarifies object construction during negation.
Applied the @disjoint_base decorator to the UnaryExpr class in scip.pyi to clarify its role in the type hierarchy.
Move and centralize operator overloads for ExprLike: __radd__, __sub__, __rsub__, __rmul__, __neg__ and __richcmp__ are added earlier in the class and the duplicate implementations later in the file were removed. This refactor cleans up the class definition and avoids duplicated method definitions.
Consolidate reflected true-division handling by adding __rtruediv__ to the ExprLike base class and removing duplicate implementations from Expr and GenExpr. The reflected division now uniformly uses buildGenExprObj(other) / self, reducing code duplication and ensuring consistent behavior across expression types.
Document a refactor that moves several dunder methods (__radd__, __sub__, __rsub__, __rmul__, __richcmp__, __neg__, __rtruediv__) into the ExprLike base class to centralize operator behavior. This change only updates CHANGELOG.md to record the API/internal restructuring.
Add the positional-only marker ('/') to several operator method signatures in ExprLike to prevent passing the operand as a keyword and to align with CPython semantics. Affected methods: __radd__, __sub__, __rsub__, __rmul__, and __rtruediv__. This is a signature-level change only and should not alter runtime behavior.
Update src/pyscipopt/scip.pyi: add missing arithmetic/operator dunder declarations (__radd__, __sub__, __rsub__, __rmul__, __rtruediv__, __neg__) to the ExprLike base stub and remove redundant/operator declarations from Expr and GenExpr. This consolidates common operator signatures in the base protocol, reduces duplication, and improves typing/stub consistency.
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Delete an extraneous blank line between the end of ExprLike and the @disjoint_base decorator/Expr class in src/pyscipopt/scip.pyi to tidy file formatting. No functional changes.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Replace Incomplete with object for several ExprLike operator stubs (__radd__, __sub__, __rsub__, __rmul__, __rtruediv__, __neg__) to relax/standardize return and operand typing. Also add missing __rtruediv__ stubs to Expr and GenExpr. These changes improve the type stubs for static type checkers and better reflect Python operator semantics.
Add the positional-only marker (/) to the ExprLike.__neg__ signature in src/pyscipopt/expr.pxi. This enforces that the unary negation method cannot be called with keyword arguments and aligns the signature with Python/Cython expectations, avoiding potential warnings or misuse.
Update type stubs in src/pyscipopt/scip.pyi to change return types of several ExprLike dunder operators from object to Incomplete for improved typing precision. Affected methods: __radd__, __sub__, __rsub__, __rmul__, __rtruediv__, and __neg__. This is a type-only change with no runtime behavior modifications.
Add explicit GenExpr return annotations for __rtruediv__ across implementation and typing stub. Updated src/pyscipopt/expr.pxi to annotate ExprLike, Expr and GenExpr __rtruediv__ methods with -> GenExpr, and updated src/pyscipopt/scip.pyi to change the stub return types from object to GenExpr for Expr.__rtruediv__ and GenExpr.__rtruediv__. This improves static typing consistency between the Cython implementation and the Python stubs.
Update negation operator type hints to return Union[Expr, GenExpr]. - src/pyscipopt/expr.pxi: add a Cython return annotation for __neg__. - src/pyscipopt/scip.pyi: change __neg__ from Incomplete to Union[Expr, GenExpr]. These changes improve static typing and IDE support by accurately describing the result of unary negation on expression-like objects.
Update typing in src/pyscipopt/scip.pyi: change ExprLike.__rtruediv__ return type from Incomplete to GenExpr and remove duplicate __rtruediv__ declarations from Expr and GenExpr. This consolidates the right-division signature in the base ExprLike class to avoid conflicting or redundant stub definitions and improve type consistency.
Update the typing stub for ExprLike.__neg__ in src/pyscipopt/scip.pyi to include the positional-only marker (/). This clarifies that __neg__ accepts no keyword arguments and returns Union[Expr, GenExpr]; no runtime behavior changes.
Replace manual object construction and child copying in ProdExpr.__neg__ with self.copy(copy=True) and negate the copied constant. This simplifies the negation implementation, preserves existing attributes (like operator and children) via the copy method, and reduces duplicated code that could lead to inconsistencies.
|
Let's drop |
Use a C-level to speed up
SumExpr.__neg__,ProdExpr.__neg__, andConstant.__neg__.SumExpris 2.1x faster than before, andProdExpris 4.9x faster than before.-SumExprtime: 1.38s-ProdExprtime: 1.39s-SumExprtime: 0.64s-ProdExprtime: 0.28s