Пример #1
0
def validate(*args):
    if not all(arg.is_Matrix for arg in args):
        raise TypeError("Mix of Matrix and Scalar symbols")
    A = args[0]
    for B in args[1:]:
        if A.shape != B.shape:
            raise ShapeError("Matrices %s and %s are not aligned" % (A, B))
Пример #2
0
 def lu_solve(self, rhs):
     if self.shape[0] != rhs.shape[0]:
         raise ShapeError("Shape")
     if not self.domain.is_Field:
         raise ValueError('Not a field')
     sol = self.rep.lu_solve(rhs.rep)
     return self.from_ddm(sol)
Пример #3
0
def _MatrixArithmetic__mul__(self, other):
	other = _matrixify(other)
	# matrix-like objects can have shapes.  This is
	# our first sanity check.
	if hasattr(other, 'shape') and len(other.shape) == 2:
		if self.shape[1] != other.shape[0]:
			raise ShapeError("Matrix size mismatch: %s * %s." % (
				self.shape, other.shape))

	# honest sympy matrices defer to their class's routine
	if getattr(other, 'is_Matrix', False):
		m = self._eval_matrix_mul(other)
		return m.applyfunc(_dotprodsimp)

	# Matrix-like objects can be passed to CommonMatrix routines directly.
	if getattr(other, 'is_MatrixLike', False):
		return MatrixArithmetic._eval_matrix_mul(self, other)

	# if 'other' is not iterable then scalar multiplication.
	if not isinstance(other, Iterable):
		try:
			return self._eval_scalar_mul(other)
		except TypeError:
			pass

	raise NotImplementedError()
Пример #4
0
 def _multiply(self, other, method):
     if np.isscalar(other):
         mat = [a * other for a in self._mat]
         return SymbolicVector._new(self.rows, self.cols, mat, copy=False)
     elif isinstance(other, (np.ndarray, SymbolicVector, sp.MatrixSymbol)):
         if self.shape[0] != other.shape[0]:
             raise ShapeError("SymbolicVector size mismatch: %s * %s." %
                              (self.shape, other.shape))
         if len(other.shape) > 1:
             for s in other.shape[1:]:
                 if s != 1:
                     raise ShapeError(
                         "SymbolicVector size mismatch: %s * %s." %
                         (self.shape, other.shape))
         mat = [a * b for a, b in zip(self._mat, other)]
         return SymbolicVector._new(self.rows, self.cols, mat, copy=False)
     else:
         return getattr(super(SymbolicVector, self), method)(other)
Пример #5
0
 def __add__(self, other):
     if np.isscalar(other):
         mat = [a + other for a in self._mat]
         return SymbolicVector._new(self.rows, self.cols, mat, copy=False)
     elif isinstance(other, (np.ndarray, SymbolicVector)):
         if self.shape[0] != other.shape[0]:
             raise ShapeError("SymbolicVector size mismatch: %s + %s." %
                              (self.shape, other.shape))
         if len(other.shape) > 1:
             for s in other.shape[1:]:
                 if s != 1:
                     raise ShapeError(
                         "SymbolicVector size mismatch: %s + %s." %
                         (self.shape, other.shape))
         mat = [a + b for a, b in zip(self._mat, other)]
         return SymbolicVector._new(self.rows, self.cols, mat, copy=False)
     else:
         return super(SymbolicVector, self).__add__(other)
    def col_join(self, bott):
        # Allows you to build a matrix even if it is null matrix
        if not self:
            return type(self)(bott)

        if self.cols != bott.cols:
            raise ShapeError(
                "`self` and `bott` must have the same number of columns.")
        newmat = NewMatrix.zeros(self.rows + bott.rows, self.cols)
        newmat[:self.rows, :] = self
        newmat[self.rows:, :] = bott
        return type(self)(newmat)
    def row_join(self, rhs):
        # Allows you to build a matrix even if it is null matrix
        if not self:
            return type(self)(rhs)

        if self.rows != rhs.rows:
            raise ShapeError(
                "`self` and `rhs` must have the same number of rows.")
        newmat = NewMatrix.zeros(self.rows, self.cols + rhs.cols)
        newmat[:, :self.cols] = self
        newmat[:, self.cols:] = rhs
        return type(self)(newmat)
Пример #8
0
    def copyin_matrix(self, key, value):
        """Copy in values from a matrix into the given bounds.

        Parameters
        ==========

        key : slice
            The section of this matrix to replace.
        value : Matrix
            The matrix to copy values from.

        Examples
        ========

        >>> from sympy.matrices import Matrix, eye
        >>> M = Matrix([[0, 1], [2, 3], [4, 5]])
        >>> I = eye(3)
        >>> I[:3, :2] = M
        >>> I
        Matrix([
        [0, 1, 0],
        [2, 3, 0],
        [4, 5, 1]])
        >>> I[0, 1] = M
        >>> I
        Matrix([
        [0, 0, 1],
        [2, 2, 3],
        [4, 4, 5]])

        See Also
        ========

        copyin_list
        """
        rlo, rhi, clo, chi = self.key2bounds(key)
        shape = value.shape
        dr, dc = rhi - rlo, chi - clo
        if shape != (dr, dc):
            raise ShapeError(
                filldedent("The Matrix `value` doesn't have the "
                           "same dimensions "
                           "as the in sub-Matrix given by `key`."))

        for i in range(value.rows):
            for j in range(value.cols):
                self[i + rlo, j + clo] = value[i, j]
    def __new__(cls, arg, condition=None):
        arg = _sympify(arg)

        if 1 not in arg.shape:
            raise ShapeError("Expression is not a vector")

        shape = (arg.shape[0],
                 arg.shape[0]) if arg.shape[1] == 1 else (arg.shape[1],
                                                          arg.shape[1])

        if condition:
            obj = Expr.__new__(cls, arg, condition)
        else:
            obj = Expr.__new__(cls, arg)

        obj._shape = shape
        obj._condition = condition
        return obj
    def __new__(cls, arg1, arg2, condition=None):
        arg1 = _sympify(arg1)
        arg2 = _sympify(arg2)

        if (1 not in arg1.shape) or (1 not in arg2.shape) or (arg1.shape[1] !=
                                                              arg2.shape[1]):
            raise ShapeError("Expression is not a vector")

        shape = (arg1.shape[0], arg2.shape[0]) if arg1.shape[1] == 1 and arg2.shape[1] == 1 \
                    else (1, 1)

        if condition:
            obj = Expr.__new__(cls, arg1, arg2, condition)
        else:
            obj = Expr.__new__(cls, arg1, arg2)

        obj._shape = shape
        obj._condition = condition
        return obj
Пример #11
0
 def _new(cls, *args, copy=True, **kwargs):
     if copy is False:
         # The input was rows, cols, [list].
         # It should be used directly without creating a copy.
         if len(args) != 3:
             raise TypeError(
                 "'copy=False' requires a matrix be initialized as rows,cols,[list]"
             )
         rows, cols, flat_list = args
     else:
         rows, cols, flat_list = cls._handle_creation_inputs(
             *args, **kwargs)
         flat_list = list(flat_list)  # create a shallow copy
     self = object.__new__(cls)
     self.rows = rows
     self.cols = cols
     if cols != 1:
         raise ShapeError("SymVector input must be a list")
     self._mat = flat_list
     return self
Пример #12
0
def hessian(f, varlist, constraints=[]):
    """Compute Hessian matrix for a function f wrt parameters in varlist
    which may be given as a sequence or a row/column vector. A list of
    constraints may optionally be given.

    Examples
    ========

    >>> from sympy import Function, hessian, pprint
    >>> from sympy.abc import x, y
    >>> f = Function('f')(x, y)
    >>> g1 = Function('g')(x, y)
    >>> g2 = x**2 + 3*y
    >>> pprint(hessian(f, (x, y), [g1, g2]))
    [                   d               d            ]
    [     0        0    --(g(x, y))     --(g(x, y))  ]
    [                   dx              dy           ]
    [                                                ]
    [     0        0        2*x              3       ]
    [                                                ]
    [                     2               2          ]
    [d                   d               d           ]
    [--(g(x, y))  2*x   ---(f(x, y))   -----(f(x, y))]
    [dx                   2            dy dx         ]
    [                   dx                           ]
    [                                                ]
    [                     2               2          ]
    [d                   d               d           ]
    [--(g(x, y))   3   -----(f(x, y))   ---(f(x, y)) ]
    [dy                dy dx              2          ]
    [                                   dy           ]

    References
    ==========

    https://en.wikipedia.org/wiki/Hessian_matrix

    See Also
    ========

    sympy.matrices.matrices.MatrixCalculus.jacobian
    wronskian
    """
    # f is the expression representing a function f, return regular matrix
    if isinstance(varlist, MatrixBase):
        if 1 not in varlist.shape:
            raise ShapeError("`varlist` must be a column or row vector.")
        if varlist.cols == 1:
            varlist = varlist.T
        varlist = varlist.tolist()[0]
    if is_sequence(varlist):
        n = len(varlist)
        if not n:
            raise ShapeError("`len(varlist)` must not be zero.")
    else:
        raise ValueError("Improper variable list in hessian function")
    if not getattr(f, 'diff'):
        # check differentiability
        raise ValueError("Function `f` (%s) is not differentiable" % f)
    m = len(constraints)
    N = m + n
    out = zeros(N)
    for k, g in enumerate(constraints):
        if not getattr(g, 'diff'):
            # check differentiability
            raise ValueError("Function `f` (%s) is not differentiable" % f)
        for i in range(n):
            out[k, i + m] = g.diff(varlist[i])
    for i in range(n):
        for j in range(i, n):
            out[i + m, j + m] = f.diff(varlist[i]).diff(varlist[j])
    for i in range(N):
        for j in range(i + 1, N):
            out[j, i] = out[i, j]
    return out
Пример #13
0
def validate(*matrices):
    """ Checks for valid shapes for args of MatMul """
    for i in range(len(matrices) - 1):
        A, B = matrices[i:i + 2]
        if A.cols != B.rows:
            raise ShapeError("Matrices %s and %s are not aligned" % (A, B))
Пример #14
0
 def sub(A, B):
     if A.shape != B.shape:
         raise ShapeError("shape")
     if A.domain != B.domain:
         raise ValueError("domain")
     return A.from_ddm(A.rep.sub(B.rep))