def Vector(*args): '''Create a Vector expression.''' # if the input is a numpy array, put it into a ConstantVectorExpr if len(args)==1: x = args[0] else: x = args if isinstance(x, ndarray): order = len(x.shape) if order != 1: raise ValueError('Non-vector input [{}] to Vector()'.format(x)) if len(x) <= 1: raise ValueError('1D input [{}] to Vector()'.format(x)) return ConstantVector(x) # if the input is a 1D list or tuple: # (*) Form a ConstantVectorExpr if all the elements are constants # (*) Form a VectorExpr otherwise if isinstance(x, (list, tuple, AggExpr)): allConsts = True elems = [] if len(x) == 1: raise ValueError('Impossible to convert a 1D object to a vector') for x_i in x: if isinstance(x_i, Number): elems.append(x_i) elif isinstance(x_i, Expr): if not isinstance(x_i.shape(), ScalarShape): raise ValueError('Vector() element not scalar: [{}]'.format(x_i)) if not x_i.isConstant(): allConsts = False elems.append(x_i) else: elems.append(Expr._convertToExpr(x_i.data())) else: raise ValueError('Vector() input neither number nor expr: [{}]'.format(x_i)) if allConsts: return ConstantVectorExpr(array(elems)) else: exprElems = [] for e in elems: exprElems.append(Expr._convertToExpr(e)) return AggedVectorExpr(exprElems) # If the input is a tensor, this won't work if isinstance(x, Expr) and isinstance(x.shape(), TensorShape): raise ValueError('impossible to convert a tensor to a vector') # If the input is a scalar, this won't work if isinstance(x, Expr) and isinstance(x.shape(), ScalarShape): raise ValueError('pointless to convert a scalar to a vector') # Don't know what this input is raise ValueError('bad input {} to Vector()')
def test_AggIter(self): x = Coordinate(0) a = np.array([1, 2, 3]) a2 = Expr._convertToExpr(a) c = 1 c2 = Expr._convertToExpr(c) L = AggExpr(c, x, a) tup = (c2, x, a2) same = True for e1, e2 in zip(L, tup): same = same and (e1.sameas(e2)) assert (same)
def __init__(self, name, arg): assert (Expr._convertibleToExpr(arg)) expr = Expr._convertToExpr(arg) if not isinstance(expr.shape(), ScalarShape): raise ValueError( 'UnivariateFuncExpr ctor: non-scalar arg [{}]'.format(expr)) super().__init__(expr, expr.shape()) self._name = name
def __call__(self, arg): # Make sure the type makes sense if not Expr._convertibleToExpr(arg): raise TypeError('diff op [{}] cannot accept type [{}]'.format( self, arg)) f = Expr._convertToExpr(arg) # Make sure the operator and input are consistent if not self.acceptShape(f.shape()): raise TypeError('diff op [{}] cannot accept argument [{}]'.format( self, f)) # Form the diff op expression if isinstance(f, SymbolicFunctionBase): return DiffOpOnFunction(self, f) return DiffOp(self, f)