You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Speed up np.mean(MatrixExpr) and more via MatrixExpr.sum #1153
Is your feature request related to a problem? Please describe.
Since there is already speed up MatrixExpr.sum
Now we can speed up other high-level operations, such as np.mean, np.trace, and part of np.dot.
Describe the solution you'd like
np.mean will call np.reduce.add in inner, and np.reduce.add will use __add__.
Use numpy __array_ufunc__ protocol to call MatrixExpr.sum instead of np.ndarray.sum.
Additional context
It sppeds up 834x than before in the shape of (200, 200).
fromtimeimporttimeimportnumpyasnpfrompyscipoptimportMatrixVariable, ModelclassSpeedMatrix(MatrixVariable):
def__array_ufunc__(self, ufunc, method, *args, **kwargs):
ifmethod=="reduce"andufuncisnp.add:
returnargs[0].sum(**kwargs)
returnsuper().__array_ufunc__(ufunc, method, *args, **kwargs)
if__name__=="__main__":
model=Model()
n=200x=model.addMatrixVar((n, n))
x_optimized=x.view(SpeedMatrix)
start=time()
np.mean(x)
end=time()
print(f"Standard mean time: {end-start:.6f} seconds")
# Standard mean time: 16.185321 secondsstart=time()
np.mean(x_optimized)
end=time()
print(f"Optimized mean time: {end-start:.6f} seconds")
# Optimized mean time: 0.019406 secondsstart=time()
np.sum(x) /x.sizeend=time()
print(f"Standard mean (sum/size) time: {end-start:.6f} seconds")
# Standard mean (sum/size) time: 0.017425 seconds
changed the title [-]Speed up `np.mean(MatrixExpr)`, `np.trace(MatrixExpr)` and more via `.sum`[/-][+]Speed up `np.mean(MatrixExpr)` and more via `MatrixExpr.sum`[/+]on Jan 15, 2026
Activity
[-]Speed up `np.mean(MatrixExpr)`, `np.trace(MatrixExpr)` and more via `.sum`[/-][+]Speed up `np.mean(MatrixExpr)` and more via `MatrixExpr.sum`[/+]Joao-Dionisio commentedon Jan 20, 2026
Closing this to clear the issue page, as it's already being actively developed in #1157.