Repository navigation
Conversation
Avoid sorted, the key lambda, and the generator used to build the hash for the common single-variable case by storing the fresh argument tuple directly and hashing the SCIP variable pointer. Handle the constant term explicitly as well.
Expose Variable.ptr() and Variable.getIndex() as cpdef so Cython callers avoid Python dispatch, and reuse them in Term instead of reading scip_var directly. In the single-variable Term path, fetch the variable with PyTuple_GET_ITEM (the *args tuple is exact, so no bounds check is needed) and keep the Variable type check through the <object> cast, so non-Variable arguments still raise TypeError instead of being read as SCIP_VAR*.
Term.vartuple only ever holds Variables (guaranteed by __init__ and __mul__), so the unchecked PyTuple_GET_ITEM is safe in _evaluate and matches what __eq__ and __mul__ already do. Take the lengths from len(self.vartuple) instead of len(self), which is a PyObject_Length call dispatching through Term.__len__, and use Py_ssize_t for the lengths and loop counters: list/tuple sizes are Py_ssize_t, and storing them in an int would truncate silently.
hash(tuple(v.ptr() for v in res.vartuple)) goes through a generator and calls the Python-level Variable.ptr() once per variable. Collect the pointers in the merge loop instead and hash the resulting tuple, which keeps the hash identical to the one Term.__init__ builds for the same variables.
1d87ba2 to
fe8433d
Compare
| self.vartuple = vartuple | ||
| self.hashval = <Py_ssize_t>hash((var.ptr(),)) | ||
|
|
||
| else: |
There was a problem hiding this comment.
Should Term forbid n > 1? Term(x, y) (n>1) cannot be initialized directly, it’s always comes from Term.mul
There was a problem hiding this comment.
But users could still use it to access the coefficients of a quadratic constraint, for example, right?
There was a problem hiding this comment.
What do you think about this, @Zeroto521 ? It's not a big deal either way for me
There was a problem hiding this comment.
I prefer Term should receive one single variable or a None.
The normal user would call x^3 instead of Term(x, x, x) and they don’t need to know how to import Term. Term is kind of an inner class.
There was a problem hiding this comment.
Alright, we can change this. But I think there's a test that'd need to change as well.
|
Hey @Zeroto521 , as always sorry for taking so long! I will try to have this reviewed properly by the end of next weekend. |
|
/benchmark |
|
✅ |
|
Results for Benchmark results (base → PR)No regressions
Instructions from callgrind, time is the best of several runs, memory is Python-side (tracemalloc). Flagged above 1% instructions, 20% time, 5% peak memory, 5% retained memory. Against v6.3.0v6.3.0 → PR
Instructions from callgrind, time is the best of several runs, memory is Python-side (tracemalloc). Flagged above 1% instructions, 20% time, 5% peak memory, 5% retained memory. Base |
|
The following used to return an error, but now segfaults:
|
Co-authored-by: João Dionísio <57299939+Joao-Dionisio@users.noreply.github.com>
Co-authored-by: João Dionísio <57299939+Joao-Dionisio@users.noreply.github.com>
The *args items are not type-checked by Cython, and assigning None to a cdef class variable is allowed (it stores Py_None), so Term(None) stored Py_None in a Variable variable and crashed in var.ptr(), which dispatches through the vtab pointer read from the Py_None object. Validate the arguments up front and raise TypeError, matching the error already raised for other non-Variable arguments. The single-variable fast path can then use an unchecked cast. Add a regression test covering None and non-Variable arguments.
| def __init__(self, *vartuple: Variable): | ||
| self.vartuple = tuple(sorted(vartuple, key=lambda v: v.getIndex())) | ||
| self.hashval = <Py_ssize_t>hash(tuple(v.ptr() for v in self.vartuple)) | ||
| cdef Py_ssize_t i, n = PyTuple_GET_SIZE(vartuple) | ||
| cdef Variable var | ||
| cdef object item | ||
|
|
||
| for i in range(n): | ||
| item = <object>PyTuple_GET_ITEM(vartuple, i) | ||
| if not isinstance(item, Variable): | ||
| raise TypeError( | ||
| f"Term() arguments must be Variable, got {type(item).__name__}" | ||
| ) |
There was a problem hiding this comment.
The following used to return an error, but now segfaults:
Term(None)Term(x) * Nonem.delVar(None)
fixed
Termis created for every variable that enters an expression (x + y,2 * x,quicksum(...), ...) and it is the key of thedictbehindExpr.terms, so its constructor, its comparison and the*used to multiply monomials are all on the hot path of modelling code.This PR adds a shortcut path for
Const=Term()(n=0) andTerm(Variable)(n=1), inspared by #1273. Terms with two or more variables construct through the unchanged code path, User can't callTerm(x, y)directly in real code.Term(x, y)will be created fromTerm.__mul__.Term()CONST)Term(v)Variable)Term(v, w)Term(w, v)Term(v, w, x)Term(v, w, x, y)Term(v) == Term(v)Term(v, w, x) == Term(v, w, x)dict[Term(v)]Term(v) * Term(w)Term(v, w) * Term(x, y)(v + w) * (x + y)Term._evaluate(1 var)Term._evaluate(3 vars)