Exemplo n.º 1
0
def radsimp(expr):
    """
    Rationalize the denominator.

    Examples:
    =========
        >>> from sympy import *
        >>> radsimp(1/(2+sqrt(2)))
        1 - 1/2*2**(1/2)
        >>> x,y = map(Symbol, 'xy')
        >>> e = ( (2+2*sqrt(2))*x+(2+sqrt(8))*y )/( 2+sqrt(2) )
        >>> radsimp(e)
        x*2**(1/2) + y*2**(1/2)
    """
    n,d = fraction(expr)
    a,b,c = map(Wild, 'abc')
    r = d.match(a+b*Basic.sqrt(c))
    if r is not None:
        a = r[a]
        if r[b] == 0:
            b,c = 0,0
        else:
            b,c = r[b],r[c]

        syms = list(n.atoms(type=Basic.Symbol))
        n = collect( (n*(a-b*Basic.sqrt(c))).expand(), syms )
        d = a**2 - c*b**2

    return n/d
Exemplo n.º 2
0
    def parse_term(expr):
        rat_expo, sym_expo = Rational(1), None
        sexpr, deriv = expr, None

        if isinstance(expr, Pow):
            if isinstance(expr.base, Derivative):
                sexpr, deriv = parse_derivative(expr.base)
            else:
                sexpr = expr.base

            if isinstance(expr.exp, Rational):
                rat_expo = expr.exp
            elif isinstance(expr.exp, Mul):
                coeff, tail = term.exp.as_coeff_terms()

                if isinstance(coeff, Rational):
                    rat_expo, sym_expo = coeff, Basic.Mul(*tail)
                else:
                    sym_expo = expr.exp
            else:
                sym_expo = expr.exp
        elif isinstance(expr, Basic.exp):
            if isinstance(expr[0], Rational):
                sexpr, rat_expo = Basic.exp(Rational(1)), expr[0]
            elif isinstance(expr[0], Mul):
                coeff, tail = expr[0].as_coeff_terms()

                if isinstance(coeff, Rational):
                    sexpr, rat_expo = Basic.exp(Basic.Mul(*tail)), coeff
        elif isinstance(expr, Derivative):
            sexpr, deriv = parse_derivative(expr)

        return sexpr, rat_expo, sym_expo, deriv
Exemplo n.º 3
0
    def _eval_apply(self, z, a=S.One):
        z, a = map(Basic.sympify, (z, a))

        if isinstance(a, Basic.Number):
            if isinstance(a, Basic.NaN):
                return S.NaN
            elif isinstance(a, Basic.Zero):
                return self(z)

        if isinstance(z, Basic.Number):
            if isinstance(z, Basic.NaN):
                return S.NaN
            elif isinstance(z, Basic.Infinity):
                return S.One
            elif isinstance(z, Basic.Zero):
                if a.is_negative:
                    return S.Half - a - 1
                else:
                    return S.Half - a
            elif isinstance(z, Basic.One):
                return S.ComplexInfinity
            elif isinstance(z, Basic.Integer):
                if isinstance(a, Basic.Integer):
                    if z.is_negative:
                        zeta = (-1)**z * Basic.bernoulli(-z+1)/(-z+1)
                    elif z.is_even:
                        B, F = Basic.bernoulli(z), Basic.Factorial(z)
                        zeta = 2**(z-1) * abs(B) * pi**z / F

                    if a.is_negative:
                        return zeta + Basic.harmonic(abs(a), z)
                    else:
                        return zeta - Basic.harmonic(a-1, z)
Exemplo n.º 4
0
    def _eval_apply(cls, arg):
        arg = Basic.sympify(arg)

        if isinstance(arg, Basic.Number):
            if isinstance(arg, Basic.NaN):
                return S.NaN
            elif isinstance(arg, Basic.Infinity):
                return S.Infinity
            elif isinstance(arg, Basic.Integer):
                if arg.is_positive:
                    return Basic.Factorial(arg-1)
                else:
                    return S.ComplexInfinity
            elif isinstance(arg, Basic.Rational):
                if arg.q == 2:
                    n = abs(arg.p) / arg.q

                    if arg.is_positive:
                        k, coeff = n, S.One
                    else:
                        n = k = n + 1

                        if n & 1 == 0:
                            coeff = S.One
                        else:
                            coeff = S.NegativeOne

                    for i in range(3, 2*k, 2):
                        coeff *= i

                    if arg.is_positive:
                        return coeff*Basic.sqrt(S.Pi) / 2**n
                    else:
                        return 2**n*Basic.sqrt(S.Pi) / coeff
Exemplo n.º 5
0
    def _eval_apply(cls, a, x):
        if isinstance(a, Basic.Number):
            if isinstance(a, Basic.One):
                return S.One - Basic.exp(-x)
            elif isinstance(a, Basic.Integer):
                b = a - 1

                if b.is_positive:
                    return b*cls(b, x) - x**b * Basic.exp(-x)
Exemplo n.º 6
0
    def __new__(cls, f, z, **assumptions):
        f = Basic.sympify(f)

        if not f.is_polynomial(z):
            return f

        obj = Basic.__new__(cls, **assumptions)
        obj._args = (f.as_polynomial(z), z)

        return obj
Exemplo n.º 7
0
def separate(expr, deep=False):
    """Rewrite or separate a power of product to a product of powers
       but without any expanding, ie. rewriting products to summations.

       >>> from sympy import *
       >>> x, y, z = symbols('x', 'y', 'z')

       >>> separate((x*y)**2)
       x**2*y**2

       >>> separate((x*(y*z)**3)**2)
       x**2*y**6*z**6

       >>> separate((x*sin(x))**y + (x*cos(x))**y)
       x**y*cos(x)**y + x**y*sin(x)**y

       #>>> separate((exp(x)*exp(y))**x)
       #exp(x*y)*exp(x**2)

       Notice that summations are left un touched. If this is not the
       requested behaviour, apply 'expand' to input expression before:

       >>> separate(((x+y)*z)**2)
       z**2*(x + y)**2

       >>> separate((x*y)**(1+z))
       x**(1 + z)*y**(1 + z)

    """
    expr = Basic.sympify(expr)

    if isinstance(expr, Basic.Pow):
        terms, expo = [], separate(expr.exp, deep)
        #print expr, terms, expo, expr.base

        if isinstance(expr.base, Mul):
            t = [ separate(Basic.Pow(t,expo), deep) for t in expr.base ]
            return Basic.Mul(*t)
        elif isinstance(expr.base, Basic.exp):
            if deep == True:
                return Basic.exp(separate(expr.base[0], deep)*expo)
            else:
                return Basic.exp(expr.base[0]*expo)
        else:
            return Basic.Pow(separate(expr.base, deep), expo)
    elif isinstance(expr, (Basic.Add, Basic.Mul)):
        return type(expr)(*[ separate(t, deep) for t in expr ])
    elif isinstance(expr, Basic.Function) and deep:
        return expr.func(*[ separate(t) for t in expr])
    else:
        return expr
Exemplo n.º 8
0
 def __new__(cls, e, z, z0, dir="+"):
     e = sympify(e)
     z = sympify(z)
     z0 = sympify(z0)
     obj = Basic.__new__(cls)
     obj._args = (e, z, z0, dir)
     return obj
Exemplo n.º 9
0
    def __new__(cls, *args):
        from sympy.matrices.immutable import ImmutableDenseMatrix
        args = map(sympify, args)
        mat = ImmutableDenseMatrix(*args)

        obj = Basic.__new__(cls, mat)
        return obj
Exemplo n.º 10
0
 def __new__(cls, radius=1, center=[0,0,0], direction=[0,0,1], closed=False, **kwargs):
     """
     >>> from sympy import *
     >>> from symplus.strplus import init_mprinting
     >>> init_mprinting()
     >>> InfiniteCylinder()
     InfiniteCylinder(1, [0 0 0]', [0 0 1]', False)
     >>> InfiniteCylinder(2, [0,0,0], [0,1,1])
     InfiniteCylinder(2, [0 0 0]', [0 -sqrt(2)/2 -sqrt(2)/2]', False)
     >>> InfiniteCylinder().contains((1,1,1))
     False
     >>> InfiniteCylinder(2, [0,0,0], [0,1,1]).contains((1,1,1))
     True
     """
     normalization = kwargs.pop("normalization", True)
     radius = sympify(abs(radius))
     direction = Mat(direction)
     if normalization:
         if norm(direction) == 0:
             raise ValueError
         direction = simplify(normalize(direction))
     direction = max(direction, -direction, key=hash)
     center = Mat(center)
     if normalization:
         center = simplify(center - project(center, direction))
     closed = sympify(bool(closed))
     return Basic.__new__(cls, radius, center, direction, closed)
Exemplo n.º 11
0
    def __new__(cls, *args, **options):
        # (Try to) sympify args first
        newargs = []
        for ec in args:
            pair = ExprCondPair(*ec)
            cond = pair.cond
            if cond == false:
                continue
            if not isinstance(cond, (bool, Relational, Boolean)):
                raise TypeError(
                    "Cond %s is of type %s, but must be a Relational,"
                    " Boolean, or a built-in bool." % (cond, type(cond)))
            newargs.append(pair)
            if cond == True:
                break

        if options.pop('evaluate', True):
            r = cls.eval(*newargs)
        else:
            r = None

        if r is None:
            return Basic.__new__(cls, *newargs, **options)
        else:
            return r
Exemplo n.º 12
0
    def __new__(cls, *components):
        if components and not isinstance(components[0], Morphism):
            # Maybe the user has explicitly supplied a list of
            # morphisms.
            return CompositeMorphism.__new__(cls, *components[0])

        normalised_components = Tuple()

        for current, following in zip(components, components[1:]):
            if not isinstance(current, Morphism) or \
                    not isinstance(following, Morphism):
                raise TypeError("All components must be morphisms.")

            if current.codomain != following.domain:
                raise ValueError("Uncomposable morphisms.")

            normalised_components = CompositeMorphism._add_morphism(
                normalised_components, current)

        # We haven't added the last morphism to the list of normalised
        # components.  Add it now.
        normalised_components = CompositeMorphism._add_morphism(
            normalised_components, components[-1])

        if not normalised_components:
            # If ``normalised_components`` is empty, only identities
            # were supplied.  Since they all were composable, they are
            # all the same identities.
            return components[0]
        elif len(normalised_components) == 1:
            # No sense to construct a whole CompositeMorphism.
            return normalised_components[0]

        return Basic.__new__(cls, normalised_components)
Exemplo n.º 13
0
    def __new__(cls, name, objects=EmptySet(), commutative_diagrams=EmptySet()):
        if not name:
            raise ValueError("A Category cannot have an empty name.")

        new_category = Basic.__new__(cls, Symbol(name), Class(objects),
                                     FiniteSet(*commutative_diagrams))
        return new_category
Exemplo n.º 14
0
    def __new__(cls, *args, **kw_args):
        """
        The constructor for the Prufer object.

        Examples
        ========
        >>> from sympy.combinatorics.prufer import Prufer

        A Prufer object can be constructed from a list of node connections
        and the number of nodes:

        >>> a = Prufer([[0, 1], [0, 2], [0, 3]], 4)
        >>> a.prufer_repr
        [0, 0]

        A Prufer object can be constructed from a Prufer sequence:

        >>> b = Prufer([1, 3])
        >>> b.tree_repr
        [[2, 1], [1, 3], [3, 0]]
        """
        ret_obj = Basic.__new__(cls, *args, **kw_args)
        if isinstance(args[0][0], list):
            ret_obj._tree_repr = args[0]
            ret_obj._nodes = args[1]
        else:
            ret_obj._prufer_repr = args[0]
            ret_obj._nodes = len(ret_obj._prufer_repr) + 2
        return ret_obj
Exemplo n.º 15
0
    def __new__(cls, *args, **kw_args):
        """
        Constructor for the Permutation object.

        Examples
        ========

        >>> from sympy.combinatorics.permutations import Permutation
        >>> p = Permutation([0,1,2])
        >>> p
        Permutation([0, 1, 2])
        >>> q = Permutation([[0,1],[2]])
        >>> q
        Permutation([[0, 1], [2]])
        """
        if not args or not is_sequence(args[0]) or len(args) > 1 or \
           len(set(is_sequence(a) for a in args[0])) > 1:
            raise ValueError('Permutation argument must be a list of ints or a list of lists.')

        # 0, 1, ..., n-1 should all be present

        temp = [int(i) for i in flatten(args[0])]
        if set(range(len(temp))) != set(temp):
            raise ValueError("Integers 0 through %s must be present." % len(temp))

        cform = aform = None
        if args[0] and is_sequence(args[0][0]):
            cform = [list(a) for a in args[0]]
        else:
            aform = list(args[0])

        ret_obj = Basic.__new__(cls, (cform or aform), **kw_args)
        ret_obj._cyclic_form, ret_obj._array_form = cform, aform
        return ret_obj
Exemplo n.º 16
0
 def __new__(cls, arg, expr):
     if not isinstance(arg, Argument):
         raise TypeError("arg must be of type `Argument`")
     expr = _sympify(expr)
     if not isinstance(expr, (Expr, MatrixExpr)):
         raise TypeError("Unsupported expression type %s." % type(expr))
     return Basic.__new__(cls, arg, expr)
Exemplo n.º 17
0
 def __new__(cls, mat):
     mat = _sympify(mat)
     if not mat.is_Matrix:
         raise TypeError("mat should be a matrix")
     if not mat.is_square:
         raise ShapeError("Inverse of non-square matrix %s" % mat)
     return Basic.__new__(cls, mat)
Exemplo n.º 18
0
    def __new__(cls, subset, superset):
        """
        Default constructor.

        It takes the subset and its superset as its parameters.

        Examples:
        >>> from sympy.combinatorics.subsets import Subset
        >>> a = Subset(['c','d'], ['a','b','c','d'])
        >>> a.subset
        ['c', 'd']
        >>> a.superset
        ['a', 'b', 'c', 'd']
        >>> a.size
        2
        """
        if len(subset) > len(superset):
            raise ValueError("Invalid arguments have been provided. The superset must be larger than the subset.")
        for elem in subset:
            if elem not in superset:
                raise ValueError("The superset provided is invalid as it does not contain the element %i" % elem)
        obj = Basic.__new__(cls)
        obj._subset = subset
        obj._superset = superset
        return obj
Exemplo n.º 19
0
 def __new__(cls, func, center=[0,0,0], direction=[0,0,1], **kwargs):
     center = Mat(center)
     direction = Mat(direction)
     if norm(direction) == 0:
         raise ValueError
     direction = normalize(direction)
     return Basic.__new__(cls, func, center, direction)
Exemplo n.º 20
0
    def __new__(cls, *args, **kwargs):
        check = kwargs.get('check', True)

        obj = Basic.__new__(cls, *args)
        if check:
            validate(*args)
        return obj
Exemplo n.º 21
0
    def __new__(cls, partition, integer=None):
        """
        Generates a new IntegerPartition object from a list or dictionary.

        The partition can be given as a list of positive integers or a
        dictionary of (integer, multiplicity) items. If the partition is
        preceeded by an integer an error will be raised if the partition
        does not sum to that given integer.

        Examples
        ========

        >>> from sympy.combinatorics.partitions import IntegerPartition
        >>> a = IntegerPartition([5, 4, 3, 1, 1])
        >>> a
        IntegerPartition(14, (5, 4, 3, 1, 1))
        >>> print a
        [5, 4, 3, 1, 1]
        >>> IntegerPartition({1:3, 2:1})
        IntegerPartition(5, (2, 1, 1, 1))

        If the value that the partion should sum to is given first, a check
        will be made to see n error will be raised if there is a discrepancy:
        >>> IntegerPartition(10, [5, 4, 3, 1])
        Traceback (most recent call last):
        ...
        ValueError: The partition is not valid

        """
        from sympy.ntheory.residue_ntheory import int_tested

        if integer is not None:
            integer, partition = partition, integer
        if isinstance(partition, (dict, Dict)):
            _ = []
            for k, v in sorted(partition.items(), reverse=True):
                if not v:
                    continue
                k, v = int_tested(k, v)
                _.extend([k]*v)
            partition = tuple(_)
        else:
            partition = tuple(sorted(int_tested(partition), reverse=True))
        sum_ok = False
        if integer is None:
            integer = sum(partition)
            sum_ok = True
        else:
            integer = int_tested(integer)

        if not sum_ok and sum(partition) != integer:
            raise ValueError("Partition did not add to %s" % integer)
        if any(i < 1 for i in partition):
            raise ValueError("The summands must all be positive.")

        obj = Basic.__new__(cls, integer, partition)
        obj.partition = list(partition)
        obj.integer = integer
        return obj
Exemplo n.º 22
0
    def __new__(cls, *args, **kwargs):
        args = list(map(sympify, args))
        check = kwargs.get('check', True)

        obj = Basic.__new__(cls, *args)
        if check:
            validate(*args)
        return obj
Exemplo n.º 23
0
 def _new(cls, *args, **kwargs):
     if len(args) == 1 and isinstance(args[0], ImmutableMatrix):
         return args[0]
     rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs)
     rows = Integer(rows)
     cols = Integer(cols)
     mat = Tuple(*flat_list)
     return Basic.__new__(cls, rows, cols, mat)
Exemplo n.º 24
0
    def _eval_apply(cls, a, z):
        if isinstance(z, Basic.Number):
            if isinstance(z, Basic.NaN):
                return S.NaN
            elif isinstance(z, Basic.Infinity):
                return S.Zero
            elif isinstance(z, Basic.Zero):
                return gamma(a)

        if isinstance(a, Basic.Number):
            if isinstance(a, Basic.One):
                return Basic.exp(-z)
            elif isinstance(a, Basic.Integer):
                b = a - 1

                if b.is_positive:
                    return b*cls(b, z) + z**b * Basic.exp(-z)
Exemplo n.º 25
0
    def __new__(cls, f, *symbols, **assumptions):
        f = Basic.sympify(f)

        if isinstance(f, Basic.Number):
            if isinstance(f, Basic.NaN):
                return S.NaN
            elif isinstance(f, Basic.Zero):
                return S.Zero

        if not symbols:
            limits = f.atoms(Symbol)

            if not limits:
                return f
        else:
            limits = []

            for V in symbols:
                if isinstance(V, Symbol):
                    limits.append(V)
                    continue
                elif isinstance(V, Equality):
                    if isinstance(V.lhs, Symbol):
                        if isinstance(V.rhs, Interval):
                            limits.append((V.lhs, V.rhs.start, V.rhs.end))
                        else:
                            limits.append((V.lhs, V.rhs))

                        continue
                elif isinstance(V, (tuple, list)):
                    if len(V) == 1:
                        if isinstance(V[0], Symbol):
                            limits.append(V[0])
                            continue
                    elif len(V) in (2, 3):
                        if isinstance(V[0], Symbol):
                            limits.append(tuple(V))
                            continue

                raise ValueError("Invalid summation variable or limits")

        obj = Basic.__new__(cls, **assumptions)
        obj._args = (f, tuple(limits))

        return obj
Exemplo n.º 26
0
    def __new__(cls, *args, **kwargs):
        check = kwargs.get('check', True)

        args = map(sympify, args)
        obj = Basic.__new__(cls, *args)
        factor, matrices = obj.as_coeff_matrices()
        if check:
            validate(*matrices)
        return obj
Exemplo n.º 27
0
 def _new(cls, *args, **kwargs):
     # same as sympy version, only always creates new class
     # even if passed in a matrix
     from sympy.core import Basic, Integer
     rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs)
     rows = Integer(rows)
     cols = Integer(cols)
     mat = Tuple(*flat_list)
     return Basic.__new__(cls, rows, cols, mat)
Exemplo n.º 28
0
 def __new__(cls, dtype, expr):
     if isinstance(dtype, str):
         dtype = datatype(dtype)
     elif not isinstance(dtype, DataType):
         raise TypeError("datatype must be an instance of DataType.")
     expr = _sympify(expr)
     if not isinstance(expr, (Expr, MatrixExpr)):
         raise TypeError("Unsupported expression type %s." % type(expr))
     return Basic.__new__(cls, dtype, expr)
Exemplo n.º 29
0
 def __new__(cls, routine, args):
     if not isinstance(routine, Routine):
         raise TypeError("routine must be of type Routine")
     if len(routine.arguments) != len(args):
         raise ValueError("Incorrect number of arguments")
     for n, (a, p) in enumerate(zip(args, routine.arguments)):
         cls._validate_arg(a, p)
     args = Tuple(*args)
     return Basic.__new__(cls, routine, args)
Exemplo n.º 30
0
 def __new__(cls, mat, exp=S(-1)):
     # exp is there to make it consistent with
     # inverse.func(*inverse.args) == inverse
     mat = _sympify(mat)
     if not mat.is_Matrix:
         raise TypeError("mat should be a matrix")
     if not mat.is_square:
         raise ShapeError("Inverse of non-square matrix %s" % mat)
     return Basic.__new__(cls, mat, exp)
Exemplo n.º 31
0
    def __new__(cls, n, *args, **kw_args):
        """
        Default constructor.

        It takes a single argument ``n`` which gives the dimension of the Gray
        code. The starting Gray code string (``start``) or the starting ``rank``
        may also be given; the default is to start at rank = 0 ('0...0').

        Examples
        ========

        >>> from sympy.combinatorics.graycode import GrayCode
        >>> a = GrayCode(3)
        >>> a
        GrayCode(3)
        >>> a.n
        3

        >>> a = GrayCode(3, start='100')
        >>> a.current
        '100'

        >>> a = GrayCode(4, rank=4)
        >>> a.current
        '0110'
        >>> a.rank
        4

        """
        if n < 1 or int(n) != n:
            raise ValueError(
                'Gray code dimension must be a positive integer, not %i' % n)
        n = int(n)
        args = (n, ) + args
        obj = Basic.__new__(cls, *args)
        if 'start' in kw_args:
            obj._current = kw_args["start"]
            if len(obj._current) > n:
                raise ValueError(
                    'Gray code start has length %i but should not be greater than %i'
                    % (len(obj._current), n))
        elif 'rank' in kw_args:
            if int(kw_args["rank"]) != kw_args["rank"]:
                raise ValueError(
                    'Gray code rank must be a positive integer, not %i' %
                    kw_args["rank"])
            obj._rank = int(kw_args["rank"]) % obj.selections
            obj._current = obj.unrank(n, obj._rank)
        return obj
Exemplo n.º 32
0
    def __new__(cls, arguments, expr, check=False):

        # ...
        if expr.atoms(DomainIntegral, BoundaryIntegral):
            raise TypeError('')
        # ...

        # ...
        if check and not is_linear_form(expr, arguments):
            msg = '> Expression is not linear'
            raise UnconsistentLinearExpressionError(msg)
        # ...

        args = _sanitize_arguments(arguments, is_linear=True)
        return Basic.__new__(cls, args, expr)
Exemplo n.º 33
0
    def __new__(cls, *args, **options):
        # (Try to) sympify args first

        if options.pop('evaluate', True):

            args = cls._annotate(*args)
            r = cls.eval(*args, **options)

        else:
            r = None

        if r is None:
            return Basic.__new__(cls, *args, **options)
        else:
            return r
Exemplo n.º 34
0
    def _new(cls, *args, **kwargs):
        if len(args) == 1 and isinstance(args[0], ImmutableDenseMatrix):
            return args[0]
        if kwargs.get('copy', True) is False:
            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
        rows = Integer(rows)
        cols = Integer(cols)
        if not isinstance(flat_list, Tuple):
            flat_list = Tuple(*flat_list)

        return Basic.__new__(cls, rows, cols, flat_list)
Exemplo n.º 35
0
    def __new__(cls, *args, **kwargs):
        if not args:
            return GenericZeroMatrix()

        # This must be removed aggressively in the constructor to avoid
        # TypeErrors from GenericZeroMatrix().shape
        args = filter(lambda i: GenericZeroMatrix() != i, args)
        args = list(map(sympify, args))
        check = kwargs.get('check', False)

        obj = Basic.__new__(cls, *args)
        if check:
            if all(not isinstance(i, MatrixExpr) for i in args):
                return Add.fromiter(args)
            validate(*args)
        return obj
Exemplo n.º 36
0
    def __new__(cls, function, *symbols, **assumptions):
        if any(len(l) != 3 or None for l in symbols):
            raise ValueError('ArrayComprehension requires values lower and upper bound'
                              ' for the expression')

        if not isLambda(function):
            raise ValueError('Data type not supported')

        arglist = cls._check_limits_validity(function, symbols)
        obj = Basic.__new__(cls, *arglist, **assumptions)
        obj._limits = obj._args
        obj._shape = cls._calculate_shape_from_limits(obj._limits)
        obj._rank = len(obj._shape)
        obj._loop_size = cls._calculate_loop_size(obj._shape)
        obj._lambda = function
        return obj
Exemplo n.º 37
0
    def __new__(cls, arg1, arg2):
        arg1, arg2 = _sympify((arg1, arg2))

        if not arg1.is_Matrix:
            raise TypeError("Argument 1 of DotProduct is not a matrix")
        if not arg2.is_Matrix:
            raise TypeError("Argument 2 of DotProduct is not a matrix")
        if not (1 in arg1.shape):
            raise TypeError("Argument 1 of DotProduct is not a vector")
        if not (1 in arg2.shape):
            raise TypeError("Argument 2 of DotProduct is not a vector")

        if set(arg1.shape) != set(arg2.shape):
            raise TypeError("DotProduct arguments are not the same length")

        return Basic.__new__(cls, arg1, arg2)
Exemplo n.º 38
0
    def __new__(cls, name, dim=None):
        target = None
        if not isinstance(name, str):
            target = name
            name = name.name

        if not (target is None):
            if isinstance(target, ProductDomain):
                dim = target.dim

        obj = Basic.__new__(cls, name)

        obj._dim = dim
        obj._target = target

        return obj
Exemplo n.º 39
0
    def __new__(cls, *args, **options):
        # (Try to) sympify args first

        name = options.pop('name', None)

        if options.pop('evaluate', True):
            r = cls.eval(*args)
        else:
            r = None

        if r is None:
            obj = Basic.__new__(cls, *args, **options)
            obj._name = name
            return obj
        else:
            r._name = name
            return r
Exemplo n.º 40
0
def test_issue_3001():
    x = Symbol('x')
    y = Symbol('y')
    assert x**1.0 == x
    assert x == x**1.0
    assert True != x**1.0
    assert x**1.0 is not True
    assert x is not True
    assert x*y == (x*y)**1.0
    assert (x**1.0)**1.0 == x
    assert (x**1.0)**2.0 == x**2
    b = Basic()
    assert Pow(b, 1.0, evaluate=False) == b
    # if the following gets distributed as a Mul (x**1.0*y**1.0 then
    # __eq__ methods could be added to Symbol and Pow to detect the
    # power-of-1.0 case.
    assert ((x*y)**1.0).func is Pow
Exemplo n.º 41
0
    def __new__(cls, f, *symbols, **assumptions):
        f = sympify(f)

        if f.is_Number:
            if f is S.NaN:
                return S.NaN
            elif f is S.Zero:
                return S.Zero

        if not symbols:
            limits = f.atoms(Symbol)

            if not limits:
                return f
        else:
            limits = []

            for V in symbols:
                if isinstance(V, Symbol):
                    limits.append(V)
                    continue
                elif isinstance(V, Equality):
                    if isinstance(V.lhs, Symbol):
                        if isinstance(V.rhs, Interval):
                            limits.append((V.lhs, V.rhs.start, V.rhs.end))
                        else:
                            limits.append((V.lhs, V.rhs))

                        continue
                elif isinstance(V, (tuple, list)):
                    if len(V) == 1:
                        if isinstance(V[0], Symbol):
                            limits.append(V[0])
                            continue
                    elif len(V) in (2, 3):
                        if isinstance(V[0], Symbol):
                            limits.append(tuple(map(sympify, V)))
                            continue

                raise ValueError("Invalid summation variable or limits")

        obj = Basic.__new__(cls, **assumptions)
        obj._args = (f, tuple(limits))

        return obj
Exemplo n.º 42
0
def test_issue_6100_12942_4473():
    x = Symbol("x")
    y = Symbol("y")
    assert x**1.0 != x
    assert x != x**1.0
    assert True != x**1.0
    assert x**1.0 is not True
    assert x is not True
    assert x * y != (x * y)**1.0
    # Pow != Symbol
    assert (x**1.0)**1.0 != x
    assert (x**1.0)**2.0 != x**2
    b = Basic()
    assert Pow(b, 1.0, evaluate=False) != b
    # if the following gets distributed as a Mul (x**1.0*y**1.0 then
    # __eq__ methods could be added to Symbol and Pow to detect the
    # power-of-1.0 case.
    assert ((x * y)**1.0).func is Pow
Exemplo n.º 43
0
    def __new__(cls, name, bnd_minus, bnd_plus, mapping=None, logical_domain=None):

        if not isinstance(name     , str    ): raise TypeError(name)
        if not isinstance(bnd_minus, Boundary): raise TypeError(bnd_minus)
        if not isinstance(bnd_plus , Boundary): raise TypeError(bnd_plus)

        if bnd_minus.dim != bnd_plus.dim:
            raise TypeError('Dimension mismatch: {} != {}'.format(
                bnd_minus.dim, bnd_plus.dim))

        assert mapping is None and logical_domain is None or\
               mapping is not None and logical_domain is not None

        assert bnd_minus.axis == bnd_plus.axis
        obj = Basic.__new__(cls, name, bnd_minus, bnd_plus)
        obj._mapping        = mapping
        obj._logical_domain = logical_domain
        return obj
Exemplo n.º 44
0
def _new_from_array_form(perm):
    """
    factory function to produce a Permutation object from a list;
    the list is bound to the _array_form attribute, so it must
    not be modified; this method is meant for internal use only;
    the list a is supposed to be generated as a temporary value in a method,
    so p = _new_from_array_form(a) is the only object to hold a
    reference to a::

        >>> from sympy.combinatorics.permutations import _new_from_array_form
        >>> a = [2,1,3,0]
        >>> p = _new_from_array_form(a)
        >>> p
        Permutation([2, 1, 3, 0])

    """
    p = Basic.__new__(Permutation, perm)
    p._array_form = perm
    return p
Exemplo n.º 45
0
 def __new__(cls, name, args, results):
     # name
     if isinstance(name, str):
         name = Symbol(name)
     elif not isinstance(name, Symbol):
         raise TypeError("name must be Symbol or string")
     # args
     if not iterable(args):
         raise TypeError("args must be an iterable")
     if not all(isinstance(a, Argument) for a in args):
         raise TypeError("All args must be of type Argument")
     args = Tuple(*args)
     # results
     if not iterable(results):
         raise TypeError("results must be an iterable")
     if not all(isinstance(i, RoutineResult) for i in results):
         raise TypeError("All results must be of type RoutineResult")
     results = Tuple(*results)
     return Basic.__new__(cls, name, args, results)
Exemplo n.º 46
0
    def __new__(cls, *args, **options):
        # (Try to) sympify args first
        newargs = []
        for ec in args:
            pair = ExprCondPair(*ec)
            cond_type = type(pair.cond)
            if not (cond_type is bool or issubclass(cond_type, Relational) or \
                    issubclass(cond_type, Number) or issubclass(cond_type, Set)):
                raise TypeError, \
                    "Cond %s is of type %s, but must be a bool," \
                    " Relational, Number or Set" % (pair.cond, cond_type)
            newargs.append(pair)

        r = cls.eval(*newargs)

        if r is None:
            return Basic.__new__(cls, *newargs, **options)
        else:
            return r
Exemplo n.º 47
0
    def __new__(cls,
                name,
                domain,
                axis=None,
                ext=None,
                mapping=None,
                logical_domain=None):

        if axis is not None:
            assert isinstance(axis, int)

        if ext is not None:
            assert isinstance(ext, int)

        obj = Basic.__new__(cls, name, domain, axis, ext)
        obj._mapping = mapping
        obj._logical_domain = logical_domain

        return obj
Exemplo n.º 48
0
    def __new__(cls, function, *symbols, **assumptions):
        function = sympify(function)

        if function.is_Number:
            if function is S.NaN:
                return S.NaN
            elif function is S.Infinity:
                return S.Infinity
            elif function is S.NegativeInfinity:
                return S.NegativeInfinity

        if symbols:
            limits = []

            for V in symbols:
                if isinstance(V, Symbol):
                    limits.append((V, None))
                    continue
                elif isinstance(V, (tuple, list)):
                    if len(V) == 3:
                        if isinstance(V[0], Symbol):
                            nlim = map(sympify, V[1:])
                            limits.append((V[0], tuple(nlim)))
                            continue
                    elif len(V) == 1 or (len(V) == 2 and V[1] is None):
                        if isinstance(V[0], Symbol):
                            limits.append((V[0], None))
                            continue

                raise ValueError("Invalid integration variable or limits: %s" %
                                 str(symbols))
        else:
            # no symbols provided -- let's compute full antiderivative
            limits = [(symb, None) for symb in function.atoms(Symbol)]

            if not limits:
                return function

        obj = Basic.__new__(cls, **assumptions)
        obj._args = (function, tuple(limits))

        return obj
Exemplo n.º 49
0
    def __new__(cls, name, domain, shape, kind):

        if not isinstance(domain, BasicDomain):
            raise TypeError('> Expecting a BasicDomain object for domain')

        obj = Basic.__new__(cls)
        obj._name = name
        obj._domain = domain
        obj._shape = shape

        # ...
        if kind is None:
            kind = 'undefined'

        if isinstance(kind, str):
            kind_str = kind.lower()
            assert (kind_str in ['h1', 'hcurl', 'hdiv', 'l2', 'undefined'])

            kind = dtype_space_registry[kind_str]
        elif not isinstance(kind, SpaceType):
            raise TypeError('Expecting kind to be of SpaceType')

        kind_str = kind.name
        obj._kind = kind

        # ...
        if not (kind_str == 'undefined'):
            obj._regularity = dtype_regularity_registry[kind_str]
        # ...

        # ...
        # TODO remove this if => bug in tensor form
        if isinstance(domain, Interval):
            is_broken = False

        else:
            is_broken = len(domain) > 1

        obj._is_broken = is_broken
        # ...

        return obj
Exemplo n.º 50
0
    def __new__(cls, arg1, arg2):
        if not arg1.is_Matrix:
            raise TypeError("Input to Dot Product, %s, not a matrix" %
                            str(arg1))
        if not arg2.is_Matrix:
            raise TypeError("Input to Dot Product, %s, not a matrix" %
                            str(arg2))
        if not (1 in arg1.shape):
            raise TypeError("Input to Dot Product, %s, not a vector" %
                            str(arg1))
        if not (1 in arg2.shape):
            raise TypeError("Input to Dot Product, %s, not a vector" %
                            str(arg1))

        if arg1.shape != arg2.shape:
            raise TypeError(
                "Input to Dot Product, %s and %s, are not of same dimensions" %
                (str(arg1), str(arg2)))

        return Basic.__new__(cls, arg1, arg2)
Exemplo n.º 51
0
    def __new__(cls, *args, **kwargs):
        check = kwargs.get('check', True)

        if not args:
            return GenericIdentity()

        # This must be removed aggressively in the constructor to avoid
        # TypeErrors from GenericIdentity().shape
        args = filter(lambda i: GenericIdentity() != i, args)
        args = list(map(sympify, args))
        obj = Basic.__new__(cls, *args)
        factor, matrices = obj.as_coeff_matrices()
        if check:
            validate(*matrices)
        if not matrices:
            # Should it be
            #
            # return Basic.__neq__(cls, factor, GenericIdentity()) ?
            return factor
        return obj
Exemplo n.º 52
0
    def __new__(cls, name, dim=None, dtype=None, mapping=None, logical_domain=None):
        target = None
        if not isinstance(name, str):
            target = name
            name   = name.name

        if not( target is None ):
            dim = target.dim

        assert mapping is None and logical_domain is None or \
        mapping is not None and logical_domain  is not None

        obj = Basic.__new__(cls, name)

        obj._dim            = dim
        obj._target         = target
        obj._dtype          = dtype
        obj._mapping        = mapping
        obj._logical_domain = logical_domain

        return obj
Exemplo n.º 53
0
    def __new__(cls, *args, evaluate=False, check=False, _sympify=True):
        if not args:
            return cls.identity

        # This must be removed aggressively in the constructor to avoid
        # TypeErrors from GenericZeroMatrix().shape
        args = list(filter(lambda i: cls.identity != i, args))
        if _sympify:
            args = list(map(sympify, args))

        obj = Basic.__new__(cls, *args)

        if check:
            if not any(isinstance(i, MatrixExpr) for i in args):
                return Add.fromiter(args)
            validate(*args)

        if evaluate:
            obj = cls._evaluate(obj)

        return obj
Exemplo n.º 54
0
    def __new__(cls, *args, **kw_args):
        """
        The constructor for the Prufer object.

        Examples:
        >>> from sympy.combinatorics.prufer import Prufer
        >>> a = Prufer([[0, 1], [0, 2], [0, 3]], 4)
        >>> a.prufer_repr
        [0, 0]
        >>> b = Prufer([1, 3])
        >>> b.tree_repr
        [[2, 1], [1, 3], [3, 0]]
        """
        ret_obj = Basic.__new__(cls, *args, **kw_args)
        if isinstance(args[0][0], list):
            ret_obj._tree_repr = args[0]
            ret_obj._nodes = args[1]
        else:
            ret_obj._prufer_repr = args[0]
            ret_obj._nodes = len(ret_obj._prufer_repr) + 2
        return ret_obj
Exemplo n.º 55
0
    def __new__(cls, term, *symbols, **assumptions):
        term = sympify(term)

        if term.is_Number:
            if term is S.NaN:
                return S.NaN
            elif term is S.Infinity:
                return S.NaN
            elif term is S.NegativeInfinity:
                return S.NaN
            elif term is S.Zero:
                return S.Zero
            elif term is S.One:
                return S.One

        if len(symbols) == 1:
            symbol = symbols[0]

            if isinstance(symbol, C.Equality):
                k = symbol.lhs
                a = symbol.rhs.start
                n = symbol.rhs.end
            elif isinstance(symbol, (tuple, list)):
                k, a, n = symbol
            else:
                raise ValueError("Invalid arguments")

            k, a, n = map(sympify, (k, a, n))

            if isinstance(a, C.Number) and isinstance(n, C.Number):
                return Mul(
                    *[term.subs(k, i) for i in xrange(int(a),
                                                      int(n) + 1)])
        else:
            raise NotImplementedError

        obj = Basic.__new__(cls, **assumptions)
        obj._args = (term, k, a, n)

        return obj
Exemplo n.º 56
0
    def __new__(cls, expr, domain, eval=True):

        if eval:
            expr = Integral(expr, domain)
        obj = Basic.__new__(cls, expr, domain)

        # compute dim from fields if available
        ls = list(expr.atoms((ScalarField, VectorField)))
        if ls:
            F = ls[0]
            space = F.space

        else:
            tag = random_string( 3 )
            space_name = 'space_{}'.format(tag)
            space = ScalarFunctionSpace(space_name, domain)
            # TODO vector case

        obj._ldim = domain.dim
        obj._space = space

        return obj
Exemplo n.º 57
0
    def is_shape_numeric(self):
        """
        Test if the array is shape-numeric which means there is no symbolic
        dimension.

        Examples
        ========

        >>> from sympy.tensor.array import ArrayComprehension
        >>> from sympy import symbols
        >>> i, j, k = symbols('i j k')
        >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
        >>> a.is_shape_numeric
        True
        >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
        >>> b.is_shape_numeric
        False
        """
        for _, inf, sup in self._limits:
            if Basic(inf, sup).atoms(Symbol):
                return False
        return True
Exemplo n.º 58
0
    def __new__(cls, *args, **options):
        # (Try to) sympify args first
        newargs = []
        for ec in args:
            # ec could be a ExprCondPair or a tuple
            pair = ExprCondPair(*getattr(ec, 'args', ec))
            cond = pair.cond
            if cond is false:
                continue
            newargs.append(pair)
            if cond is true:
                break

        if options.pop('evaluate', True):
            r = cls.eval(*newargs)
        else:
            r = None

        if r is None:
            return Basic.__new__(cls, *newargs, **options)
        else:
            return r
Exemplo n.º 59
0
    def is_numeric(self):
        """
        Return True if the expanded array is numeric, which means that there is not
        symbolic dimension.

        Examples
        ========

        >>> from sympy.tensor.array import ArrayComprehension
        >>> from sympy.abc import i, j, k
        >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
        >>> a.is_numeric
        True
        >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
        >>> b.is_numeric
        False

        """
        for var, inf, sup in self._limits:
            if Basic(inf, sup).atoms(Symbol):
                return False
        return True
Exemplo n.º 60
0
    def __new__(cls, *components):
        if components and not isinstance(components[0], Morphism):
            # Maybe the user has explicitly supplied a list of
            # morphisms.
            return CompositeMorphism.__new__(cls, *components[0])

        normalised_components = Tuple()

        # TODO: Fix the unpythonicity.
        for i in xrange(len(components) - 1):
            current = components[i]
            following = components[i + 1]

            if not isinstance(current, Morphism) or \
                    not isinstance(following, Morphism):
                raise TypeError("All components must be morphisms.")

            if current.codomain != following.domain:
                raise ValueError("Uncomposable morphisms.")

            normalised_components = CompositeMorphism._add_morphism(
                normalised_components, current)

        # We haven't added the last morphism to the list of normalised
        # components.  Add it now.
        normalised_components = CompositeMorphism._add_morphism(
            normalised_components, components[-1])

        if not normalised_components:
            # If ``normalised_components`` is empty, only identities
            # were supplied.  Since they all were composable, they are
            # all the same identities.
            return components[0]
        elif len(normalised_components) == 1:
            # No sense to construct a whole CompositeMorphism.
            return normalised_components[0]

        return Basic.__new__(cls, normalised_components)