Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support @ operator (__matmul__) for np.array (as alternative to using np.matrix / CyLPArray) #143

Closed
sdementen opened this issue Jan 28, 2022 · 0 comments · Fixed by #144

Comments

@sdementen
Copy link
Contributor

With the introduction of the @ operator in python & numpy, it may be more natural to use standard np.array instead of np.matrix and CyLPArray to build a model.

Currently, to build CyLPExpr, we can/must use:

import numpy as np
from cylp.py.modeling.CyLPModel import CyLPModel, CyLPArray

model = CyLPModel()
T = 3
x = model.addVariable("x", T)
c = np.ones((T,))
A = np.ones((5, T,))

print(CyLPArray(c) <= x)
print(x <= c)     # no need to convert to CyLPArray as CyLPar.__le__ has priority over np.array
print(x * np.matrix(c))
print(np.matrix(c) * x)
print(np.matrix(A) * x)

(I have explicitly converted np.array to np.matrix/CyLPArray when stricly needed).

It would be nice to support the following:

import numpy as np
from cylp.py.modeling.CyLPModel import CyLPModel, CyLPArray

model = CyLPModel()
T = 3
x = model.addVariable("x", T)
c = np.ones((T,))
A = np.ones((5, T,))

print(c <= x)          # no need to wrap c into a CyLPArray
print(x <= c)
print(x @ c)            # use of @ operator for matrix multiplication instead of 
print(c @ x)
print(A @ x)

Supporting this requires to add the following to the CyLPExpr class

    __array_ufunc__ = None
    def __rmatmul__(self, other):
        v = CyLPExpr(opr="*", left=other, right=self)
        v.expr = v
        self.expr = v
        return v

    def __matmul__(self, other):
        v = CyLPExpr(opr="*", left=self, right=other)
        v.expr = v
        self.expr = v
        return v

I will prepare a PR with this change

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant