Example #1
0
    def __new__(cls, expr, condition=None, **kwargs):
        expr = _sympify(expr)
        if not kwargs.pop('evaluate', global_evaluate[0]):
            if condition is None:
                obj = Expr.__new__(cls, expr)
            else:
                condition = _sympify(condition)
                obj = Expr.__new__(cls, expr, condition)
            obj._condition = condition
            return obj

        if not expr.has(RandomSymbol):
            return expr

        if condition is not None:
            condition = _sympify(condition)

        if isinstance(expr, Add):
            return Add(*[Expectation(a, condition=condition) for a in expr.args])
        elif isinstance(expr, Mul):
            rv = []
            nonrv = []
            for a in expr.args:
                if isinstance(a, RandomSymbol) or a.has(RandomSymbol):
                    rv.append(a)
                else:
                    nonrv.append(a)
            return Mul(*nonrv)*Expectation(Mul(*rv), condition=condition, evaluate=False)
        else:
            if condition is None:
                obj = Expr.__new__(cls, expr)
            else:
                obj = Expr.__new__(cls, expr, condition)
            obj._condition = condition
            return obj
Example #2
0
    def __new__(cls, *args, **kwargs):
        from sympy.tensor.array import NDimArray, tensorproduct, Array
        from sympy import MatrixBase, MatrixExpr
        from sympy.strategies import flatten

        args = [sympify(arg) for arg in args]
        evaluate = kwargs.get("evaluate", global_evaluate[0])

        if not evaluate:
            obj = Expr.__new__(cls, *args)
            return obj

        arrays = []
        other = []
        scalar = S.One
        for arg in args:
            if isinstance(arg, (Iterable, MatrixBase, NDimArray)):
                arrays.append(Array(arg))
            elif isinstance(arg, (MatrixExpr,)):
                other.append(arg)
            else:
                scalar *= arg

        coeff = scalar*tensorproduct(*arrays)
        if len(other) == 0:
            return coeff
        if coeff != 1:
            newargs = [coeff] + other
        else:
            newargs = other
        obj = Expr.__new__(cls, *newargs, **kwargs)
        return flatten(obj)
Example #3
0
    def __new__(cls, *args):
        """ Construct a Trace object.

        Parameters
        ==========
        args = sympy expression

        """

        expr = args[0]
        indices = Tuple(*args[1]) if len(args) == 2 else Tuple()
        if isinstance(expr, Matrix):
            return expr.trace()
        elif hasattr(expr, 'trace') and callable(t.x):
            #for any objects that have trace() defined e.g numpy
            return expr.trace()
        elif isinstance(expr, Add):
            return Add(*[Tr(arg, indices) for arg in expr.args])
        elif isinstance(expr, Mul):
            c_part, nc_part = expr.args_cnc()
            if len(nc_part) == 0:
                return Mul(*c_part)
            else:
                nc_part_ordered = _cycle_permute(_rearrange_args(nc_part))
                return Mul(*c_part) * Expr.__new__(cls, Mul(*nc_part_ordered), indices )
        elif isinstance(expr, Pow):
            if (_is_scalar(expr.args[0]) and
                _is_scalar(expr.args[1])):
                return expr
            else:
                return Expr.__new__(cls, expr, indices)
        else:
            if (_is_scalar(expr)):
                return expr
            return Expr.__new__(cls, expr, indices)
Example #4
0
File: spin.py Project: 101man/sympy
 def __new__(cls, *args, **hints):
     if not len(args) == 6:
         raise ValueError('6 parameters expected, got %s' % args)
     evaluate = hints.get('evaluate', False)
     if evaluate:
         return Expr.__new__(cls, *args)._eval_wignerd()
     return Expr.__new__(cls, *args, **{'evaluate': False})
Example #5
0
    def __new__(cls, *args, **kwargs):
        from sympy.tensor.array import NDimArray, tensorproduct, Array
        from sympy import MatrixBase, MatrixExpr
        from sympy.strategies import flatten

        args = [sympify(arg) for arg in args]
        evaluate = kwargs.get("evaluate", global_parameters.evaluate)

        if not evaluate:
            obj = Expr.__new__(cls, *args)
            return obj

        arrays = []
        other = []
        scalar = S.One
        for arg in args:
            if isinstance(arg, (Iterable, MatrixBase, NDimArray)):
                arrays.append(Array(arg))
            elif isinstance(arg, (MatrixExpr, )):
                other.append(arg)
            else:
                scalar *= arg

        coeff = scalar * tensorproduct(*arrays)
        if len(other) == 0:
            return coeff
        if coeff != 1:
            newargs = [coeff] + other
        else:
            newargs = other
        obj = Expr.__new__(cls, *newargs, **kwargs)
        return flatten(obj)
 def _call_super_constructor(cls, arg1, arg2, condition):
     if condition is not None:
         obj = Expr.__new__(cls, arg1, arg2, condition)
     else:
         obj = Expr.__new__(cls, arg1, arg2)
     obj._condition = condition
     return obj
Example #7
0
 def _call_super_constructor(cls, arg1, arg2, condition):
     if condition is not None:
         obj = Expr.__new__(cls, arg1, arg2, condition)
     else:
         obj = Expr.__new__(cls, arg1, arg2)
     obj._condition = condition
     return obj
Example #8
0
    def __new__(cls, *args):
        """ Construct a Trace object.

        """
        expr = args[0]
        indices = args[1] if len(args) == 2 else -1  # -1 indicates full trace
        if isinstance(expr, Matrix):
            return expr.trace()
        elif hasattr(expr, "trace") and callable(t.x):
            # for any objects that have trace() defined e.g numpy
            return expr.trace()
        elif isinstance(expr, Add):
            return Add(*[Tr(arg, indices) for arg in expr.args])
        elif isinstance(expr, Mul):
            c_part, nc_part = expr.args_cnc()
            if len(nc_part) == 0:
                return Mul(*c_part)
            else:
                # cyclic permute nc_part for canonical ordering
                nc_part_ordered = _cycle_permute(nc_part)
                return Mul(*c_part) * Expr.__new__(cls, Mul(*nc_part_ordered), indices)
        elif isinstance(expr, Pow):
            if _is_scalar(expr.args[0]) and _is_scalar(expr.args[1]):
                return expr
            else:
                return Expr.__new__(cls, expr, indices)
        else:
            if _is_scalar(expr):
                return expr
            return Expr.__new__(cls, expr, indices)
Example #9
0
    def __new__(cls, arg1, arg2, condition=None, **kwargs):
        arg1 = _sympify(arg1)
        arg2 = _sympify(arg2)

        if not kwargs.pop('evaluate', global_evaluate[0]):
            if condition is None:
                obj = Expr.__new__(cls, arg1, arg2)
            else:
                condition = _sympify(condition)
                obj = Expr.__new__(cls, arg1, arg2, condition)
            obj._condition = condition
            return obj

        if condition is not None:
            condition = _sympify(condition)

        if arg1 == arg2:
            return Variance(arg1, condition)

        if not arg1.has(RandomSymbol):
            return S.Zero
        if not arg2.has(RandomSymbol):
            return S.Zero

        arg1, arg2 = sorted([arg1, arg2], key=default_sort_key)

        if isinstance(arg1, RandomSymbol) and isinstance(arg2, RandomSymbol):
            return Expr.__new__(cls, arg1, arg2)

        coeff_rv_list1 = cls._expand_single_argument(arg1.expand())
        coeff_rv_list2 = cls._expand_single_argument(arg2.expand())

        addends = [a*b*Covariance(*sorted([r1, r2], key=default_sort_key), evaluate=False)
                   for (a, r1) in coeff_rv_list1 for (b, r2) in coeff_rv_list2]
        return Add(*addends)
Example #10
0
 def __new__(cls, *args, **hints):
     if not len(args) == 6:
         raise ValueError("6 parameters expected, got %s" % args)
     args = sympify(args)
     evaluate = hints.get("evaluate", False)
     if evaluate:
         return Expr.__new__(cls, *args)._eval_wignerd()
     return Expr.__new__(cls, *args, **{"evaluate": False})
Example #11
0
 def __new__(cls, *args, **hints):
     if not len(args) == 6:
         raise ValueError('6 parameters expected, got %s' % args)
     args = sympify(args)
     evaluate = hints.get('evaluate', False)
     if evaluate:
         return Expr.__new__(cls, *args)._eval_wignerd()
     return Expr.__new__(cls, *args, **{'evaluate': False})
 def __new__(cls, arg, condition=None, **kwargs):
     arg = _sympify(arg)
     if condition is None:
         obj = Expr.__new__(cls, arg)
     else:
         condition = _sympify(condition)
         obj = Expr.__new__(cls, arg, condition)
     obj._condition = condition
     return obj
 def __new__(cls, arg, condition=None, **kwargs):
     arg = _sympify(arg)
     if condition is None:
         obj = Expr.__new__(cls, arg)
     else:
         condition = _sympify(condition)
         obj = Expr.__new__(cls, arg, condition)
     obj._condition = condition
     return obj
Example #14
0
 def __new__(cls, prob, condition=None, **kwargs):
     prob = _sympify(prob)
     if condition is None:
         obj = Expr.__new__(cls, prob)
     else:
         condition = _sympify(condition)
         obj = Expr.__new__(cls, prob, condition)
     obj._condition = condition
     return obj
Example #15
0
 def __new__(cls, *args, **options):
     assert len(args) == 1
     if isinstance(args[0], Transpose):
         return args[0].arg
     elif isinstance(args[0], Add):
         return Add(*[Transpose(a) for a in args[0].args])
     elif isinstance(args[0], Mul):
         coeffs = [a for a in args[0].args if a.is_commutative]
         args = [a for a in args[0].args if not a.is_commutative]
         return Mul(*coeffs) * Expr.__new__(cls, Mul(*args))
     return Expr.__new__(cls, *args)
 def __new__(cls, expr, condition=None, **kwargs):
     expr = _sympify(expr)
     if condition is None:
         if not expr.has(RandomSymbol):
             return expr
         obj = Expr.__new__(cls, expr)
     else:
         condition = _sympify(condition)
         obj = Expr.__new__(cls, expr, condition)
     obj._condition = condition
     return obj
 def __new__(cls, expr, condition=None, **kwargs):
     expr = _sympify(expr)
     if condition is None:
         if not expr.has(RandomSymbol):
             return expr
         obj = Expr.__new__(cls, expr)
     else:
         condition = _sympify(condition)
         obj = Expr.__new__(cls, expr, condition)
     obj._condition = condition
     return obj
Example #18
0
    def __new__(cls, *args):
        """ Construct a Trace object.

        Parameters
        ==========
        args = sympy expression
        indices = tuple/list if indices, optional

        """

        # expect no indices,int or a tuple/list/Tuple
        if (len(args) == 2):
            if not isinstance(args[1], (list, Tuple, tuple)):
                indices = Tuple(args[1])
            else:
                indices = Tuple(*args[1])

            expr = args[0]
        elif (len(args) == 1):
            indices = Tuple()
            expr = args[0]
        else:
            raise ValueError("Arguments to Tr should be of form"
                             "(expr[, [indices]])")


        if isinstance(expr, Matrix):
            return expr.trace()
        elif hasattr(expr, 'trace') and callable(expr.trace):
            #for any objects that have trace() defined e.g numpy
            return expr.trace()
        elif isinstance(expr, Add):
            return Add(*[Tr(arg, indices) for arg in expr.args])
        elif isinstance(expr, Mul):
            c_part, nc_part = expr.args_cnc()
            if len(nc_part) == 0:
                return Mul(*c_part)
            else:
                obj = Expr.__new__(cls, Mul(*nc_part), indices )
                #this check is needed to prevent cached instances
                #being returned even if len(c_part)==0
                return Mul(*c_part)*obj if len(c_part)>0 else obj
        elif isinstance(expr, Pow):
            if (_is_scalar(expr.args[0]) and
                _is_scalar(expr.args[1])):
                return expr
            else:
                return Expr.__new__(cls, expr, indices)
        else:
            if (_is_scalar(expr)):
                return expr

            return Expr.__new__(cls, expr, indices)
Example #19
0
    def __new__(cls, arg, condition=None, **kwargs):
        arg = _sympify(arg)

        if arg.is_Matrix:
            from sympy.stats.symbolic_multivariate_probability import VarianceMatrix
            return VarianceMatrix(arg, condition)
        if condition is None:
            obj = Expr.__new__(cls, arg)
        else:
            condition = _sympify(condition)
            obj = Expr.__new__(cls, arg, condition)
        obj._condition = condition
        return obj
Example #20
0
    def __new__(cls, expr, condition=None):
        expr = _sympify(expr)
        if condition is None:
            if not is_random(expr):
                return expr
            obj = Expr.__new__(cls, expr)
        else:
            condition = _sympify(condition)
            obj = Expr.__new__(cls, expr, condition)

        obj._shape = expr.shape
        obj._condition = condition
        return obj
Example #21
0
 def __new__(cls, expr, condition=None, **kwargs):
     expr = _sympify(expr)
     if expr.is_Matrix:
         from sympy.stats.symbolic_multivariate_probability import ExpectationMatrix
         return ExpectationMatrix(expr, condition)
     if condition is None:
         if not is_random(expr):
             return expr
         obj = Expr.__new__(cls, expr)
     else:
         condition = _sympify(condition)
         obj = Expr.__new__(cls, expr, condition)
     obj._condition = condition
     return obj
    def __new__(cls, arg1, arg2, condition=None, **kwargs):
        arg1 = _sympify(arg1)
        arg2 = _sympify(arg2)

        if kwargs.pop('evaluate', global_evaluate[0]):
            arg1, arg2 = sorted([arg1, arg2], key=default_sort_key)

        if condition is None:
            obj = Expr.__new__(cls, arg1, arg2)
        else:
            condition = _sympify(condition)
            obj = Expr.__new__(cls, arg1, arg2, condition)
        obj._condition = condition
        return obj
    def __new__(cls, arg1, arg2, condition=None, **kwargs):
        arg1 = _sympify(arg1)
        arg2 = _sympify(arg2)

        if kwargs.pop('evaluate', global_evaluate[0]):
            arg1, arg2 = sorted([arg1, arg2], key=default_sort_key)

        if condition is None:
            obj = Expr.__new__(cls, arg1, arg2)
        else:
            condition = _sympify(condition)
            obj = Expr.__new__(cls, arg1, arg2, condition)
        obj._condition = condition
        return obj
Example #24
0
File: qexpr.py Project: cklb/sympy
 def _eval_adjoint(self):
     obj = Expr._eval_adjoint(self)
     if obj is None:
         obj = Expr.__new__(Dagger, self)
     if isinstance(obj, QExpr):
         obj.hilbert_space = self.hilbert_space
     return obj
Example #25
0
File: qexpr.py Project: ytann/sympy
 def _eval_adjoint(self):
     obj = Expr._eval_adjoint(self)
     if obj is None:
         obj = Expr.__new__(Dagger, self)
     if isinstance(obj, QExpr):
         obj.hilbert_space = self.hilbert_space
     return obj
Example #26
0
    def __new__(cls, factor=1, unit=None, abbrev='', **assumptions):

        if not isinstance(factor, str):
            factor = sympify(factor)

        # if the given unit is a number (because of some operations) and
        # the factor is represented as a number, then return a number
        if ((unit is None or isinstance(unit, (Number, numbers.Real)))
                    and isinstance(factor, (Number, numbers.Real))):
            return factor * (unit or 1)

        #TODO: if factor is of the form "1 m", parse the factor and the unit
        if isinstance(factor, (Number, numbers.Real)):
            unit = cls.qsimplify(unit)
            if isinstance(unit, Quantity):
                unit = unit.as_unit
            if not isinstance(unit, Unit):
                raise TypeError("'unit' should be a Unit instance; %s found"
                                % type(unit))
        else:
            raise NotImplementedError

        obj = Expr.__new__(cls, factor, unit, **assumptions)
        obj.factor, obj.unit = factor, unit
        obj._abbrev = abbrev

        return obj
Example #27
0
 def __new__(cls, X, n, c=0, condition=None, **kwargs):
     X = _sympify(X)
     n = _sympify(n)
     c = _sympify(c)
     if condition is not None:
         condition = _sympify(condition)
     return Expr.__new__(cls, X, n, c, condition)
Example #28
0
 def __new__(cls, arg, **old_assumptions):
     # Return the dagger of a sympy Matrix immediately.
     if isinstance(arg, (Matrix, numpy_ndarray, scipy_sparse_matrix)):
         return matrix_dagger(arg)
     arg = sympify(arg)
     r = cls.eval(arg)
     if isinstance(r, Expr):
         return r
     #make unevaluated dagger commutative or non-commutative depending on arg
     if arg.is_commutative:
         obj = Expr.__new__(cls, arg, **{'commutative':True})
     else:
         obj = Expr.__new__(cls, arg, **{'commutative':False})
     if isinstance(obj, QExpr):
         obj.hilbert_space = arg.hilbert_space
     return obj
    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
Example #30
0
 def __new__(cls, bra, ket):
     if not isinstance(ket, KetBase):
         raise TypeError('KetBase subclass expected, got: %r' % ket)
     if not isinstance(bra, BraBase):
         raise TypeError('BraBase subclass expected, got: %r' % ket)
     obj = Expr.__new__(cls, bra, ket)
     return obj
Example #31
0
 def __new__(cls, before, variable, after):
     if not variable.is_symbol:
         variable = Symbol(variable)
     return Expr.__new__(cls,
             sympify(before),
             variable,
             sympify(after, {variable.name: variable}))
Example #32
0
 def __new__(cls, bra, ket):
     if not isinstance(ket, KetBase):
         raise TypeError('KetBase subclass expected, got: %r' % ket)
     if not isinstance(bra, BraBase):
         raise TypeError('BraBase subclass expected, got: %r' % ket)
     obj = Expr.__new__(cls, bra, ket)
     return obj
Example #33
0
    def __new__(cls, expr1, expr2):
        expr1 = sympify(expr1)
        expr2 = sympify(expr2)

        check = lambda x: isinstance(x, (VectorExpr, Vector))
        if not (check(expr1) and check(expr2) and \
                expr1.is_Vector and expr2.is_Vector):
            raise TypeError(
                "Both side of the cross-operator must be vectors\n" +
                "\t Left: " + str(expr1.func) + ", " + str(expr1.is_Vector) +
                ", {}\n".format(expr1) + "\t Right: " + str(expr2.func) +
                ", " + str(expr2.is_Vector) + ", {}\n".format(expr2))
        if expr1 == VectorZero() or expr2 == VectorZero():
            return VectorZero()
        if (isinstance(expr1, Vector) and isinstance(expr2, Vector)
                and expr1 == expr2):
            # TODO: At this point I'm dealing with unevaluated cross product.
            # is it better to return VectorZero()?
            return expr1.zero
        if expr1 == expr2 and isinstance(expr1, Nabla):
            raise TypeError(
                "Cross product of two nabla operators not supported.")
        if isinstance(expr2, Nabla):
            raise TypeError(
                "To compute the curl, nabla operator must be the first argument.\n"
                +
                "To write the advection operator, use the class Advection.\n" +
                "\t Left: " + str(expr1.func) + "{}\n".format(expr1) +
                "\t Right: " + str(expr2.func) + "{}\n".format(expr2))
        if expr1 == expr2:
            return VectorZero()

        obj = Expr.__new__(cls, expr1, expr2)
        return obj
Example #34
0
 def __new__(cls, bra, ket, **old_assumptions):
     if not isinstance(ket, KetBase):
         raise TypeError('KetBase subclass expected, got: %r' % ket)
     if not isinstance(bra, BraBase):
         raise TypeError('BraBase subclass expected, got: %r' % ket)
     obj = Expr.__new__(cls, *(bra, ket), **{'commutative': True})
     return obj
Example #35
0
File: qexpr.py Project: Aang/sympy
    def __new__(cls, *args, **old_assumptions):
        """Construct a new quantum object.

        Parameters
        ==========
        args : tuple
            The list of numbers or parameters that uniquely specify the
            quantum object. For a state, this will be its symbol or its
            set of quantum numbers.

        Examples
        ========

        >>> from sympy.physics.quantum.qexpr import QExpr
        >>> q = QExpr(0)
        >>> q
        0
        >>> q.label
        (0,)
        >>> q.hilbert_space
        H
        >>> q.args
        (0,)
        >>> q.is_commutative
        False
        """

        # First compute args and call Expr.__new__ to create the instance
        args = cls._eval_args(args)
        inst = Expr.__new__(cls, *args, **{'commutative':False})
        # Now set the slots on the instance
        inst.hilbert_space = cls._eval_hilbert_space(args)
        return inst
Example #36
0
 def __new__(cls, bra, ket, **old_assumptions):
     if not isinstance(ket, KetBase):
         raise TypeError('KetBase subclass expected, got: %r' % ket)
     if not isinstance(bra, BraBase):
         raise TypeError('BraBase subclass expected, got: %r' % ket)
     obj = Expr.__new__(cls, *(bra, ket), **{'commutative':True})
     return obj
Example #37
0
 def __new__(cls, arg):
     if isinstance(arg, LiteralFloat):
         return LiteralFloat(arg, precision = cls._precision)
     elif isinstance(arg, LiteralInteger):
         return LiteralFloat(arg.p, precision = cls._precision)
     else:
         return Expr.__new__(cls, arg)
Example #38
0
    def __new__(cls, *args, **old_assumptions):
        """Construct a new quantum object.

        Parameters
        ==========
        args : tuple
            The list of numbers or parameters that uniquely specify the
            quantum object. For a state, this will be its symbol or its
            set of quantum numbers.

        Examples
        ========

        >>> from sympy.physics.quantum.qexpr import QExpr
        >>> q = QExpr(0)
        >>> q
        0
        >>> q.label
        (0,)
        >>> q.hilbert_space
        H
        >>> q.args
        (0,)
        >>> q.is_commutative
        False
        """

        # First compute args and call Expr.__new__ to create the instance
        args = cls._eval_args(args)
        inst = Expr.__new__(cls, *args, **{'commutative':False})
        # Now set the slots on the instance
        inst.hilbert_space = cls._eval_hilbert_space(args)
        return inst
    def __new__(cls, prob, given):
        assert prob.is_random, prob
        assert given.is_random, given

        prob = _sympify(prob)
        given = _sympify(given)
        if prob.is_Conditioned:
            return Expr.__new__(cls, prob.lhs, prob.rhs & given)
        if prob.is_And:
            if given.is_And:
                if given._argset & prob._argset:
                    prob = prob.func(*prob._argset - given._argset)
            else:
                if given in prob._argset:
                    prob = prob.func(*prob._argset - {given})
        return Expr.__new__(cls, prob, given)
Example #40
0
 def __new__(cls, symbol, *shape):
     if isinstance(symbol, str):
         symbol = Symbol(symbol)
     # symbol = _sympify(symbol)
     shape = map(_sympify, shape)
     obj = Expr.__new__(cls, symbol, *shape)
     return obj
Example #41
0
 def __new__(cls, arg, **old_assumptions):
     # Return the dagger of a sympy Matrix immediately.
     if isinstance(arg, (Matrix, numpy_ndarray, scipy_sparse_matrix)):
         return matrix_dagger(arg)
     arg = sympify(arg)
     r = cls.eval(arg)
     if isinstance(r, Expr):
         return r
     #make unevaluated dagger commutative or non-commutative depending on arg
     if arg.is_commutative:
         obj = Expr.__new__(cls, arg, **{'commutative':True})
     else:
         obj = Expr.__new__(cls, arg, **{'commutative':False})
     if isinstance(obj, QExpr):
         obj.hilbert_space = arg.hilbert_space
     return obj
Example #42
0
    def __new__(cls, arg0, arg1=LiteralFloat(0)):

        if isinstance(arg0, Literal) and isinstance(arg1, Literal):
            real_part = 0
            imag_part = 0

            # Collect real and imag part from first argument
            if isinstance(arg0, LiteralComplex):
                real_part += arg0.real.python_value
                imag_part += arg0.imag.python_value
            else:
                real_part += arg0.python_value

            # Collect real and imag part from second argument
            if isinstance(arg1, LiteralComplex):
                real_part -= arg1.imag.python_value
                imag_part += arg1.real.python_value
            else:
                imag_part += arg1.python_value

            return LiteralComplex(real_part, imag_part, precision = cls._precision)


        # Split arguments depending on their type to ensure that the arguments are
        # either a complex and LiteralFloat(0) or 2 floats
        from .operators import PyccelAdd, PyccelMul

        if arg0.dtype is NativeComplex() and arg1.dtype is NativeComplex():
            # both args are complex
            return PyccelAdd(arg0, PyccelMul(arg1, LiteralImaginaryUnit()))
        return Expr.__new__(cls, arg0, arg1)
Example #43
0
 def __new__(cls, *args):
     if not len(args) in [1, 2]:
         raise ValueError('1 or 2 parameters expected, got %s' % str(args))
     if len(args) == 1:
         args = (args[0], Integer(0))
     if len(args) == 2:
         args = (args[0], Integer(args[1]))
     return Expr.__new__(cls, *args)
Example #44
0
 def __new__(cls, *args):
     if not len(args) in [1, 2]:
         raise ValueError('1 or 2 parameters expected, got %s' % str(args))
     if len(args) == 1:
         args = (args[0], Integer(0))
     if len(args) == 2:
         args = (args[0], Integer(args[1]))
     return Expr.__new__(cls, *args)
Example #45
0
 def __new__(cls, p, q=None, prec=15):
     rat = Rational.__new__(cls, p, q)
     if isinstance(rat, (Integer, Infinity)):
         return rat
     obj = Expr.__new__(cls)
     obj.p = rat.p
     obj.q = rat.q
     obj.prec = prec
     return obj
Example #46
0
    def __new__(cls, arg1, arg2, condition=None, **kwargs):
        arg1 = _sympify(arg1)
        arg2 = _sympify(arg2)

        if arg1.is_Matrix or arg2.is_Matrix:
            from sympy.stats.symbolic_multivariate_probability import CrossCovarianceMatrix
            return CrossCovarianceMatrix(arg1, arg2, condition)

        if kwargs.pop('evaluate', global_parameters.evaluate):
            arg1, arg2 = sorted([arg1, arg2], key=default_sort_key)

        if condition is None:
            obj = Expr.__new__(cls, arg1, arg2)
        else:
            condition = _sympify(condition)
            obj = Expr.__new__(cls, arg1, arg2, condition)
        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
Example #48
0
    def __new__(cls, *args, **old_assumptions):
        from sympy.physics.quantum.state import KetBase, BraBase

        if len(args) != 2:
            raise ValueError('2 parameters expected, got %d' % len(args))

        ket_expr = expand(args[0])
        bra_expr = expand(args[1])

        if (isinstance(ket_expr, (KetBase, Mul)) and
                isinstance(bra_expr, (BraBase, Mul))):
            ket_c, kets = ket_expr.args_cnc()
            bra_c, bras = bra_expr.args_cnc()

            if len(kets) != 1 or not isinstance(kets[0], KetBase):
                raise TypeError('KetBase subclass expected'
                                ', got: %r' % Mul(*kets))

            if len(bras) != 1 or not isinstance(bras[0], BraBase):
                raise TypeError('BraBase subclass expected'
                                ', got: %r' % Mul(*bras))

            if not kets[0].dual_class() == bras[0].__class__:
                raise TypeError(
                    'ket and bra are not dual classes: %r, %r' %
                    (kets[0].__class__, bras[0].__class__)
                    )

            # TODO: make sure the hilbert spaces of the bra and ket are
            # compatible
            obj = Expr.__new__(cls, *(kets[0], bras[0]), **old_assumptions)
            obj.hilbert_space = kets[0].hilbert_space
            return Mul(*(ket_c + bra_c)) * obj

        op_terms = []
        if isinstance(ket_expr, Add) and isinstance(bra_expr, Add):
            for ket_term in ket_expr.args:
                for bra_term in bra_expr.args:
                    op_terms.append(OuterProduct(ket_term, bra_term,
                                                 **old_assumptions))
        elif isinstance(ket_expr, Add):
            for ket_term in ket_expr.args:
                op_terms.append(OuterProduct(ket_term, bra_expr,
                                             **old_assumptions))
        elif isinstance(bra_expr, Add):
            for bra_term in bra_expr.args:
                op_terms.append(OuterProduct(ket_expr, bra_term,
                                             **old_assumptions))
        else:
            raise TypeError(
                'Expected ket and bra expression, got: %r, %r' %
                (ket_expr, bra_expr)
                )

        return Add(*op_terms)
Example #49
0
    def __new__(cls, *args, **hints):
        if not len(args) in [2, 3]:
            raise ValueError('2 or 3 parameters expected, got %s' % args)

        if len(args) == 2:
            args = (args[0], args[1], Integer(0))

        if len(args) == 3:
            args = (args[0], args[1], Integer(args[2]))

        return Expr.__new__(cls, *args)
Example #50
0
 def __new__(cls, *args, **assumptions):
     if isinstance(args[0], (Matrix, numpy_ndarray, scipy_sparse_matrix)):
         return matrix_tensor_product(*args)
     c_part, new_args = cls.flatten(sympify(args))
     c_part = Mul(*c_part)
     if len(new_args) == 0:
         return c_part
     elif len(new_args) == 1:
         return c_part*new_args[0]
     else:
         tp = Expr.__new__(cls, *new_args, **{'commutative': False})
         return c_part*tp
Example #51
0
 def __new__(cls, arg, **old_assumptions):
     # Return the dagger of a sympy Matrix immediately.
     if isinstance(arg, (Matrix, numpy_ndarray, scipy_sparse_matrix)):
         return matrix_dagger(arg)
     arg = sympify(arg)
     r = cls.eval(arg)
     if isinstance(r, Expr):
         return r
     obj = Expr.__new__(cls, arg)
     if isinstance(obj, QExpr):
         obj.hilbert_space = arg.hilbert_space
     return obj
Example #52
0
File: qexpr.py Project: Aang/sympy
    def _new_rawargs(cls, hilbert_space, *args):
        """Create new instance of this class with hilbert_space and args.

        This is used to bypass the more complex logic in the ``__new__``
        method in cases where you already have the exact ``hilbert_space``
        and ``args``. This should be used when you are positive these
        arguments are valid, in their final, proper form and want to optimize
        the creation of the object.
        """

        obj = Expr.__new__(cls, *args, **{'commutative':False})
        obj.hilbert_space = hilbert_space
        return obj
Example #53
0
    def __new__(cls, expr, coeffs=Tuple(), alias=None, **args):
        """Construct a new algebraic number. """
        expr = sympify(expr)

        if isinstance(expr, (tuple, Tuple)):
            minpoly, root = expr

            if not minpoly.is_Poly:
                minpoly = Poly(minpoly)
        elif expr.is_AlgebraicNumber:
            minpoly, root = expr.minpoly, expr.root
        else:
            minpoly, root = minimal_polynomial(
                expr, args.get('gen'), polys=True), expr

        dom = minpoly.get_domain()

        if coeffs != Tuple():
            if not isinstance(coeffs, ANP):
                rep = DMP.from_sympy_list(sympify(coeffs), 0, dom)
                scoeffs = Tuple(*coeffs)
            else:
                rep = DMP.from_list(coeffs.to_list(), 0, dom)
                scoeffs = Tuple(*coeffs.to_list())

            if rep.degree() >= minpoly.degree():
                rep = rep.rem(minpoly.rep)

            sargs = (root, scoeffs)

        else:
            rep = DMP.from_list([1, 0], 0, dom)

            if ask(Q.negative(root)):
                rep = -rep

            sargs = (root, coeffs)

        if alias is not None:
            if not isinstance(alias, Symbol):
                alias = Symbol(alias)
            sargs = sargs + (alias,)

        obj = Expr.__new__(cls, *sargs)

        obj.rep = rep
        obj.root = root
        obj.alias = alias
        obj.minpoly = minpoly

        return obj
Example #54
0
    def __new__(cls, *args):
        """ Construct a Trace object.

        Parameters
        ==========
        args = sympy expression

        """

        expr = args[0]
        indices = Tuple(*args[1]) if len(args) == 2 else Tuple()
        if isinstance(expr, Matrix):
            return expr.trace()
        elif hasattr(expr, 'trace') and callable(expr.trace):
            #for any objects that have trace() defined e.g numpy
            return expr.trace()
        elif isinstance(expr, Add):
            return Add(*[Tr(arg, indices) for arg in expr.args])
        elif isinstance(expr, Mul):
            c_part, nc_part = expr.args_cnc()
            if len(nc_part) == 0:
                return Mul(*c_part)
            else:
                obj = Expr.__new__(cls, Mul(*nc_part), indices )
                #this check is needed to prevent cached instances
                #being returned even if len(c_part)==0
                return Mul(*c_part)*obj if len(c_part)>0 else obj
        elif isinstance(expr, Pow):
            if (_is_scalar(expr.args[0]) and
                _is_scalar(expr.args[1])):
                return expr
            else:
                return Expr.__new__(cls, expr, indices)
        else:
            if (_is_scalar(expr)):
                return expr

            return Expr.__new__(cls, expr, indices)
Example #55
0
 def __new__(cls, wavelen, z, **kwargs):
     wavelen, z = map(sympify, (wavelen, z))
     inst = Expr.__new__(cls, wavelen, z)
     inst.wavelen = wavelen
     inst.z = z
     if len(kwargs) != 1:
         raise ValueError('Constructor expects exactly one named argument.')
     elif 'z_r' in kwargs:
         inst.z_r = sympify(kwargs['z_r'])
     elif 'w' in kwargs:
         inst.z_r = waist2rayleigh(sympify(kwargs['w']), wavelen)
     else:
         raise ValueError('The constructor needs named argument w or z_r')
     return inst
Example #56
0
    def __new__(cls, name, abbrev, exponent, base=sympify(10)):

        name = sympify(name)
        abbrev = sympify(abbrev)
        exponent = sympify(exponent)
        base = sympify(base)

        obj = Expr.__new__(cls, name, abbrev, exponent, base)
        obj._name = name
        obj._abbrev = abbrev
        obj._scale_factor = base**exponent
        obj._exponent = exponent
        obj._base = base
        return obj