From dcfe9f42c002521ab821d75c4bb5453d7da725d0 Mon Sep 17 00:00:00 2001 From: sdementen Date: Fri, 28 Jan 2022 06:08:44 +0100 Subject: [PATCH] support np.array for modeling - implement @ operator for np.array - check * is not used with np.array - add __array_ufunc__ = None to allow CyLPExpr to take over np.array broadcasting (remove need for PyLPArray) --- cylp/py/modeling/CyLPModel.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/cylp/py/modeling/CyLPModel.py b/cylp/py/modeling/CyLPModel.py index 1a5d26bd..830a8430 100644 --- a/cylp/py/modeling/CyLPModel.py +++ b/cylp/py/modeling/CyLPModel.py @@ -170,6 +170,8 @@ def identitySub(var): return I(n)[var.indices, :] class CyLPExpr: + __array_ufunc__ = None + operators = ('>=', '<=', '==', '+', '-', '*', 'u-', 'sum') def __init__(self, opr='', left='', right=''): @@ -209,17 +211,33 @@ def __eq__(self, other): return v def __rmul__(self, other): + if type(other)==np.ndarray: + raise ValueError("You should use @ when multiplying a variable with a numpy array") v = CyLPExpr(opr="*", left=other, right=self) v.expr = v self.expr = v return v def __mul__(self, other): + if type(other)==np.ndarray: + raise ValueError("You should use @ when multiplying a variable with a numpy array") v = CyLPExpr(opr="*", left=self, right=other) v.expr = v self.expr = v return v + 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 + def __rsub__(self, other): v = CyLPExpr(opr="-", left=other, right=self) v.expr = v