Ejemplo n.º 1
0
    def __new__(cls, expr, *symbols, **assumptions):
        expr = sympify(expr)
        if not symbols: return expr
        symbols = Derivative._symbolgen(*symbols)
        if not assumptions.get("evaluate", False) and not isinstance(
                expr, Derivative):
            obj = Basic.__new__(cls, expr, *symbols)
            return obj
        unevaluated_symbols = []
        for s in symbols:
            s = sympify(s)
            if not isinstance(s, Symbol):
                raise ValueError(
                    'Invalid literal: %s is not a valid variable' % s)
            if not expr.has(s):
                return S.Zero
            obj = expr._eval_derivative(s)
            if obj is None:
                unevaluated_symbols.append(s)
            elif obj is S.Zero:
                return S.Zero
            else:
                expr = obj

        if not unevaluated_symbols:
            return expr
        return Basic.__new__(cls, expr, *unevaluated_symbols)
Ejemplo n.º 2
0
    def __new__(cls, expr, *symbols, **assumptions):
        expr = Basic.sympify(expr)
        if not symbols: return expr
        symbols = map(Basic.sympify, symbols)

        if not assumptions.get("evaluate", True):
            obj = Basic.__new__(cls, expr, *symbols)
            return obj

        for s in symbols:
            assert isinstance(s, Basic.Symbol),`s`
            if not expr.has(s):
                return Basic.Zero()

        unevaluated_symbols = []
        for s in symbols:
            obj = expr._eval_derivative(s)
            if obj is None:
                unevaluated_symbols.append(s)
            else:
                expr = obj

        if not unevaluated_symbols:
            return expr
        return Basic.__new__(cls, expr, *unevaluated_symbols)
Ejemplo n.º 3
0
    def __new__(cls, *args, **options):
        # NOTE: this __new__ is twofold:
        #
        # 1 -- it can create another *class*, which can then be instantiated by
        #      itself e.g. Function('f') creates a new class f(Function)
        #
        # 2 -- on the other hand, we instantiate -- that is we create an
        #      *instance* of a class created earlier in 1.
        #
        # So please keep, both (1) and (2) in mind.

        # (1) create new function class
        #     UC: Function('f')
        if cls is Function:
            #when user writes Function("f"), do an equivalent of:
            #taking the whole class Function(...):
            #and rename the Function to "f" and return f, thus:
            #In [13]: isinstance(f, Function)
            #Out[13]: False
            #In [14]: isinstance(f, FunctionClass)
            #Out[14]: True

            if len(args) == 1 and isinstance(args[0], str):
                #always create Function
                return FunctionClass(Function, *args)
                return FunctionClass(Function, *args, **options)
            else:
                print args
                print type(args[0])
                raise Exception("You need to specify exactly one string")

        # (2) create new instance of a class created in (1)
        #     UC: Function('f')(x)
        #     UC: sin(x)
        args = map(sympify, args)
        # these lines should be refactored
        for opt in [
                "nargs", "dummy", "comparable", "noncommutative", "commutative"
        ]:
            if opt in options:
                del options[opt]
        # up to here.
        if options.get('evaluate') is False:
            return Basic.__new__(cls, *args, **options)
        r = cls.canonize(*args)
        if isinstance(r, Basic):
            return r
        elif r is None:
            # Just undefined functions have nargs == None
            if not cls.nargs and hasattr(cls, 'undefined_Function'):
                r = Basic.__new__(cls, *args, **options)
                r.nargs = len(args)
                return r
            pass
        elif not isinstance(r, tuple):
            args = (r, )
        return Basic.__new__(cls, *args, **options)
Ejemplo n.º 4
0
    def __new__(cls, *args, **options):
        # NOTE: this __new__ is twofold:
        #
        # 1 -- it can create another *class*, which can then be instantiated by
        #      itself e.g. Function('f') creates a new class f(Function)
        #
        # 2 -- on the other hand, we instantiate -- that is we create an
        #      *instance* of a class created earlier in 1.
        #
        # So please keep, both (1) and (2) in mind.

        # (1) create new function class
        #     UC: Function('f')
        if cls is Function:
            #when user writes Function("f"), do an equivalent of:
            #taking the whole class Function(...):
            #and rename the Function to "f" and return f, thus:
            #In [13]: isinstance(f, Function)
            #Out[13]: False
            #In [14]: isinstance(f, FunctionClass)
            #Out[14]: True

            if len(args) == 1 and isinstance(args[0], str):
                #always create Function
                return FunctionClass(Function, *args)
                return FunctionClass(Function, *args, **options)
            else:
                print args
                print type(args[0])
                raise Exception("You need to specify exactly one string")

        # (2) create new instance of a class created in (1)
        #     UC: Function('f')(x)
        #     UC: sin(x)
        args = map(sympify, args)
        # these lines should be refactored
        for opt in ["nargs", "dummy", "comparable", "noncommutative", "commutative"]:
            if opt in options:
                del options[opt]
        # up to here.
        if options.get('evaluate') is False:
            return Basic.__new__(cls, *args, **options)
        r = cls.eval(*args)
        if isinstance(r, Basic):
            return r
        elif r is None:
            # Just undefined functions have nargs == None
            if not cls.nargs and hasattr(cls, 'undefined_Function'):
                r = Basic.__new__(cls, *args, **options)
                r.nargs = len(args)
                return r
            pass
        elif not isinstance(r, tuple):
            args = (r,)
        return Basic.__new__(cls, *args, **options)
Ejemplo n.º 5
0
 def __new__(cls, b, e, **assumptions):
     b = _sympify(b)
     e = _sympify(e)
     if assumptions.get("evaluate") is False:
         return Basic.__new__(cls, b, e, **assumptions)
     if e is S.Zero:
         return S.One
     if e is S.One:
         return b
     obj = b._eval_power(e)
     if obj is None:
         obj = Basic.__new__(cls, b, e, **assumptions)
         obj.is_commutative = b.is_commutative and e.is_commutative
     return obj
Ejemplo n.º 6
0
 def __new__(cls, a, b, **assumptions):
     a = _sympify(a)
     b = _sympify(b)
     if assumptions.get("evaluate") is False:
         return Basic.__new__(cls, a, b, **assumptions)
     if b is S.Zero:
         return S.One
     if b is S.One:
         return a
     obj = a._eval_power(b)
     if obj is None:
         obj = Basic.__new__(cls, a, b, **assumptions)
         obj.is_commutative = a.is_commutative and b.is_commutative
     return obj
Ejemplo n.º 7
0
 def __new__(cls, a, b, **assumptions):
     a = _sympify(a)
     b = _sympify(b)
     if assumptions.get('evaluate') is False:
         return Basic.__new__(cls, a, b, **assumptions)
     if b is S.Zero:
         return S.One
     if b is S.One:
         return a
     obj = a._eval_power(b)
     if obj is None:
         obj = Basic.__new__(cls, a, b, **assumptions)
         obj.is_commutative = (a.is_commutative and b.is_commutative)
     return obj
Ejemplo n.º 8
0
 def __new__(cls, b, e, **assumptions):
     b = _sympify(b)
     e = _sympify(e)
     if assumptions.get('evaluate') is False:
         return Basic.__new__(cls, b, e, **assumptions)
     if e is S.Zero:
         return S.One
     if e is S.One:
         return b
     obj = b._eval_power(e)
     if obj is None:
         obj = Basic.__new__(cls, b, e, **assumptions)
         obj.is_commutative = (b.is_commutative and e.is_commutative)
     return obj
Ejemplo n.º 9
0
 def _new(cls, _mpf_, _prec):
     if _mpf_ == mlib.fzero:
         return S.Zero
     obj = Basic.__new__(cls)
     obj._mpf_ = _mpf_
     obj._prec = _prec
     return obj
Ejemplo n.º 10
0
 def __new__(cls, p, q = None):
     if q is None:
         if isinstance(p, str):
             p, q = _parse_rational(p)
         else:
             return Integer(p)
     if q==0:
         if p==0:
             if _errdict["divide"]:
                 raise ValueError("Indeterminate 0/0")
             else:
                 return S.NaN
         if p<0: return S.NegativeInfinity
         return S.Infinity
     if q<0:
         q = -q
         p = -p
     n = igcd(abs(p), q)
     if n>1:
         p //= n
         q //= n
     if q==1: return Integer(p)
     if p==1 and q==2: return S.Half
     obj = Basic.__new__(cls)
     obj.p = int(p)
     obj.q = int(q)
     #obj._args = (p, q)
     return obj
Ejemplo n.º 11
0
    def __new__(cls, start, end, left_open=False, right_open=False):

        start = _sympify(start)
        end = _sympify(end)

        # Only allow real intervals (use symbols with 'is_real=True').
        if not start.is_real or not end.is_real:
            raise ValueError("Only real intervals are supported")

        # Make sure that the created interval will be valid.
        if end.is_comparable and start.is_comparable:
            if end < start:
                return S.EmptySet

        if end == start and (left_open or right_open):
            return S.EmptySet
        if end == start and not (left_open or right_open):
            return FiniteSet(end)

        # Make sure infinite interval end points are open.
        if start == S.NegativeInfinity:
            left_open = True
        if end == S.Infinity:
            right_open = True

        return Basic.__new__(cls, start, end, left_open, right_open)
Ejemplo n.º 12
0
 def _new(cls, _mpf_, _prec):
     if _mpf_ == mlib.fzero:
         return S.Zero
     obj = Basic.__new__(cls)
     obj._mpf_ = _mpf_
     obj._prec = _prec
     return obj
Ejemplo n.º 13
0
 def __new__(cls, p, q = None):
     if q is None:
         if isinstance(p, str):
             p, q = _parse_rational(p)
         else:
             return Integer(p)
     if q==0:
         if p==0:
             if _errdict["divide"]:
                 raise Exception("Indeterminate 0/0")
             else:
                 return S.NaN
         if p<0: return S.NegativeInfinity
         return S.Infinity
     if q<0:
         q = -q
         p = -p
     n = igcd(abs(p), q)
     if n>1:
         p //= n
         q //= n
     if q==1: return Integer(p)
     if p==1 and q==2: return S.Half
     obj = Basic.__new__(cls)
     obj.p = int(p)
     obj.q = int(q)
     #obj._args = (p, q)
     return obj
Ejemplo n.º 14
0
    def __new__(cls, start, end, left_open=False, right_open=False):

        start = _sympify(start)
        end = _sympify(end)

        # Only allow real intervals (use symbols with 'is_real=True').
        if not start.is_real or not end.is_real:
            raise ValueError("Only real intervals are supported")

        # Make sure that the created interval will be valid.
        if end.is_comparable and start.is_comparable:
            if end < start:
                return S.EmptySet

        if end == start and (left_open or right_open):
            return S.EmptySet
        if end == start and not (left_open or right_open):
            return FiniteSet(end)

        # Make sure infinite interval end points are open.
        if start == S.NegativeInfinity:
            left_open = True
        if end == S.Infinity:
            right_open = True

        return Basic.__new__(cls, start, end, left_open, right_open)
Ejemplo n.º 15
0
    def __new__(cls, *args):
        def flatten(arg):
            if is_flattenable(arg):
                return sum(map(flatten, arg), [])
            return [arg]
        args = flatten(list(args))

        # Sympify Arguments
        args = map(sympify, args)
        # Turn tuples into Tuples
        args = [Tuple(*arg) if arg.__class__ is tuple else arg for arg in args]

        if len(args) == 0:
            return EmptySet()

        try:
            if all([arg.is_real and arg.is_number for arg in args]):
                cls = RealFiniteSet
        except AttributeError:
            pass

        elements = frozenset(map(sympify, args))
        obj = Basic.__new__(cls, elements)
        obj.elements = elements
        return obj
Ejemplo n.º 16
0
    def __new__(cls, *args):

        # Flatten out Iterators and Unions to form one list of sets
        args = list(args)
        def flatten(arg):
            if arg == S.EmptySet:
               return []
            if isinstance(arg, Set):
                if arg.is_Union:
                    return sum(map(flatten, arg.args), [])
                else:
                    return [arg]
            if is_flattenable(arg): # and not isinstance(arg, Set) (implicit)
                return sum(map(flatten, arg), [])
            raise TypeError("Input must be Sets or iterables of Sets")
        args = flatten(args)
        if len(args) == 0:
            return S.EmptySet

        # Only real parts? Return a RealUnion
        if all(arg.is_real for arg in args):
            return RealUnion(args)

        # Lets find and merge real elements if we have them
        # Separate into finite, real and other sets

        finite_set = sum([s for s in args if s.is_FiniteSet], S.EmptySet)
        real_sets = [s for s in args if s.is_real]
        other_sets = [s for s in args if not s.is_FiniteSet and not s.is_real]

        # Separate finite_set into real and other part
        real_finite = RealFiniteSet(i for i in finite_set if i.is_real)
        other_finite = FiniteSet(i for i in finite_set if not i.is_real)

        # Merge real part of set
        real_union = RealUnion(real_sets+[real_finite])

        if not real_union: # Real part was empty
            sets = other_sets + [other_finite]
        elif real_union.is_FiniteSet: # Real part was just a FiniteSet
            sets = other_sets + [real_union+other_finite]
        elif real_union.is_Interval: # Real part was just an Interval
            sets = [real_union] + other_sets + [other_finite]
        # If is_RealUnion then separate
        elif real_union.is_Union and real_union.is_real:
            intervals = [s for s in real_union.args if s.is_Interval]
            finite_set = sum([s for s in real_union.args if s.is_FiniteSet] +
                [other_finite], S.EmptySet) # Join FiniteSet back together
            sets = intervals + [finite_set] + other_sets

        # Clear out Empty Sets
        sets = [set for set in sets if set != S.EmptySet]

        # If a single set is left over, don't create a new Union object but
        # rather return the single set.
        if len(sets) == 1:
            return sets[0]

        return Basic.__new__(cls, *sets)
Ejemplo n.º 17
0
    def __new__(cls, *args):

        # Flatten out Iterators and Unions to form one list of sets
        args = list(args)
        def flatten(arg):
            if arg == S.EmptySet:
                return []
            if isinstance(arg, Set):
                if arg.is_Union:
                    return sum(map(flatten, arg.args), [])
                else:
                    return [arg]
            if is_flattenable(arg): # and not isinstance(arg, Set) (implicit)
                return sum(map(flatten, arg), [])
            raise TypeError("Input must be Sets or iterables of Sets")
        args = flatten(args)
        if len(args) == 0:
            return S.EmptySet

        # Only real parts? Return a RealUnion
        if all(arg.is_real for arg in args):
            return RealUnion(args)

        # Lets find and merge real elements if we have them
        # Separate into finite, real and other sets

        finite_set = sum([s for s in args if s.is_FiniteSet], S.EmptySet)
        real_sets = [s for s in args if s.is_real]
        other_sets = [s for s in args if not s.is_FiniteSet and not s.is_real]

        # Separate finite_set into real and other part
        real_finite = RealFiniteSet(i for i in finite_set if i.is_real)
        other_finite = FiniteSet(i for i in finite_set if not i.is_real)

        # Merge real part of set
        real_union = RealUnion(real_sets+[real_finite])

        if not real_union: # Real part was empty
            sets = other_sets + [other_finite]
        elif real_union.is_FiniteSet: # Real part was just a FiniteSet
            sets = other_sets + [real_union+other_finite]
        elif real_union.is_Interval: # Real part was just an Interval
            sets = [real_union] + other_sets + [other_finite]
        # If is_RealUnion then separate
        elif real_union.is_Union and real_union.is_real:
            intervals = [s for s in real_union.args if s.is_Interval]
            finite_set = sum([s for s in real_union.args if s.is_FiniteSet] +
                [other_finite], S.EmptySet) # Join FiniteSet back together
            sets = intervals + [finite_set] + other_sets

        # Clear out Empty Sets
        sets = [set for set in sets if set != S.EmptySet]

        # If a single set is left over, don't create a new Union object but
        # rather return the single set.
        if len(sets) == 1:
            return sets[0]

        return Basic.__new__(cls, *sets)
Ejemplo n.º 18
0
 def __new__(cls, i):
     if isinstance(i, Integer):
         return i
     if i==0: return S.Zero
     if i==1: return S.One
     if i==-1: return S.NegativeOne
     obj = Basic.__new__(cls)
     obj.p = i
     return obj
Ejemplo n.º 19
0
        def cls_new(cls):
            try:
                obj = getattr(SingletonFactory, cls.__name__)

            except AttributeError:
                obj = Basic.__new__(cls, *(), **{})
                setattr(SingletonFactory, cls.__name__, obj)

            return obj
Ejemplo n.º 20
0
 def __new__(cls, lhs, rhs, rop=None, **assumptions):
     lhs = _sympify(lhs)
     rhs = _sympify(rhs)
     if cls is not Relational:
         rop_cls = cls
     else:
         rop_cls, swap = Relational.get_relational_class(rop)
         if swap: lhs, rhs = rhs, lhs
     obj = Basic.__new__(rop_cls, lhs, rhs, **assumptions)
     return obj
Ejemplo n.º 21
0
    def __new__(cls, *args, **assumptions):
        if assumptions.get('evaluate') is False:
            return Basic.__new__(cls, *map(_sympify, args), **assumptions)
        if len(args)==0:
            return cls.identity()
        if len(args)==1:
            return _sympify(args[0])
        c_part, nc_part, order_symbols = cls.flatten(map(_sympify, args))
        if len(c_part) + len(nc_part) <= 1:
            if c_part: obj = c_part[0]
            elif nc_part: obj = nc_part[0]
            else: obj = cls.identity()
        else:
            obj = Basic.__new__(cls, *(c_part + nc_part), **assumptions)
            obj.is_commutative = not nc_part

        if order_symbols is not None:
            obj = C.Order(obj, *order_symbols)
        return obj
Ejemplo n.º 22
0
    def __new__(cls, num):
        if isinstance(num, (int, long)):
            return Integer(num)

        singleton_cls_name = decimal_to_Number_cls.get(num.as_tuple(), None)
        if singleton_cls_name is not None:
            return getattr(Basic, singleton_cls_name)()
        obj = Basic.__new__(cls)
        obj.num = num
        return obj
Ejemplo n.º 23
0
    def __new__(cls, *args, **assumptions):
        if assumptions.get('evaluate') is False:
            return Basic.__new__(cls, *map(_sympify, args), **assumptions)
        if len(args)==0:
            return cls.identity()
        if len(args)==1:
            return _sympify(args[0])
        c_part, nc_part, order_symbols = cls.flatten(map(_sympify, args))
        if len(c_part) + len(nc_part) <= 1:
            if c_part: obj = c_part[0]
            elif nc_part: obj = nc_part[0]
            else: obj = cls.identity()
        else:
            obj = Basic.__new__(cls, *(c_part + nc_part), **assumptions)
            obj.is_commutative = not nc_part

        if order_symbols is not None:
            obj = C.Order(obj, *order_symbols)
        return obj
Ejemplo n.º 24
0
 def __new__(cls, *args):
     if len(args)==1 and args[0].__class__ is dict:
         items = [Tuple(k, v) for k, v in args[0].iteritems()]
     elif iterable(args) and all(len(arg) == 2 for arg in args):
         items = [Tuple(k, v) for k, v in args]
     else:
         raise TypeError('Pass Dict args as Dict((k1, v1), ...) or Dict({k1: v1, ...})')
     obj = Basic.__new__(cls, *items)
     obj._dict = dict(items) # In case Tuple decides it wants to sympify
     return obj
Ejemplo n.º 25
0
 def __new__(cls, lhs, rhs, rop=None, **assumptions):
     lhs = Basic.sympify(lhs)
     rhs = Basic.sympify(rhs)
     if cls is not Relational:
         rop_cls = cls
     else:
         rop_cls, swap = Relational.get_relational_class(rop)
         if swap: lhs, rhs = rhs, lhs
     obj = Basic.__new__(rop_cls, lhs, rhs, **assumptions)
     return obj
Ejemplo n.º 26
0
 def __new__(cls, a, b, **assumptions):
     a = Basic.sympify(a)
     b = Basic.sympify(b)
     if isinstance(b, Basic.Zero):
         return S.One
     if isinstance(b, Basic.One):
         return a
     obj = a._eval_power(b)
     if obj is None:
         obj = Basic.__new__(cls, a, b, **assumptions)
     return obj
Ejemplo n.º 27
0
 def __new__(cls, *args):
     if len(args) == 1 and args[0].__class__ is dict:
         items = [Tuple(k, v) for k, v in args[0].items()]
     elif iterable(args) and all(len(arg) == 2 for arg in args):
         items = [Tuple(k, v) for k, v in args]
     else:
         raise TypeError(
             'Pass Dict args as Dict((k1, v1), ...) or Dict({k1: v1, ...})')
     elements = frozenset(items)
     obj = Basic.__new__(cls, elements)
     obj.elements = elements
     obj._dict = dict(items)  # In case Tuple decides it wants to sympify
     return obj
Ejemplo n.º 28
0
 def __new__(cls, lhs, rhs, rop=None, **assumptions):
     lhs = _sympify(lhs)
     rhs = _sympify(rhs)
     if cls is not Relational:
         rop_cls = cls
     else:
         rop_cls, swap = Relational.get_relational_class(rop)
         if swap: lhs, rhs = rhs, lhs
     if lhs.is_real and lhs.is_number and rhs.is_real and rhs.is_number:
         return rop_cls._eval_relation(lhs.evalf(), rhs.evalf())
     else:
         obj = Basic.__new__(rop_cls, lhs, rhs, **assumptions)
         return obj
Ejemplo n.º 29
0
    def __new__(cls, expr, *symbols, **assumptions):
        expr = sympify(expr)
        if not symbols:
            return expr
        symbols = Derivative._symbolgen(*symbols)
        if expr.is_commutative:
            assumptions["commutative"] = True
        if "evaluate" in assumptions:
            evaluate = assumptions["evaluate"]
            del assumptions["evaluate"]
        else:
            evaluate = False
        if not evaluate and not isinstance(expr, Derivative):
            symbols = list(symbols)
            if len(symbols) == 0:
                # We make a special case for 0th derivative, because there
                # is no good way to unambiguously print this.
                return expr
            obj = Basic.__new__(cls, expr, *symbols, **assumptions)
            return obj
        unevaluated_symbols = []
        for s in symbols:
            s = sympify(s)
            if not isinstance(s, Symbol):
                raise ValueError("Invalid literal: %s is not a valid variable" % s)
            if not expr.has(s):
                return S.Zero
            obj = expr._eval_derivative(s)
            if obj is None:
                unevaluated_symbols.append(s)
            elif obj is S.Zero:
                return S.Zero
            else:
                expr = obj

        if not unevaluated_symbols:
            return expr
        return Basic.__new__(cls, expr, *unevaluated_symbols, **assumptions)
Ejemplo n.º 30
0
    def eval(cls,*args):
        obj = Basic.__new__(cls, *args)
        #use dummy variables internally, just to be sure
        nargs = len(args)-1

        expression = args[nargs]
        funargs = [Symbol(arg.name, dummy=True) for arg in args[:nargs]]
        #probably could use something like foldl here
        for arg,funarg in zip(args[:nargs],funargs):
            expression = expression.subs(arg,funarg)
        funargs.append(expression)
        obj._args = tuple(funargs)

        return obj
Ejemplo n.º 31
0
    def canonize(cls, *args):
        obj = Basic.__new__(cls, *args)
        #use dummy variables internally, just to be sure
        nargs = len(args) - 1

        expression = args[nargs]
        funargs = [Symbol(arg.name, dummy=True) for arg in args[:nargs]]
        #probably could use something like foldl here
        for arg, funarg in zip(args[:nargs], funargs):
            expression = expression.subs(arg, funarg)
        funargs.append(expression)
        obj._args = tuple(funargs)

        return obj
Ejemplo n.º 32
0
 def __new__(cls, *args, **assumptions):
     args = (_sympify(arg) for arg in args)
     try:
         _args = frozenset(cls._new_args_filter(args))
     except ShortCircuit:
         return cls.zero
     if not _args:
         return cls.identity
     elif len(_args) == 1:
         return set(_args).pop()
     else:
         obj = Basic.__new__(cls, _args, **assumptions)
         obj._argset = _args
         return obj
Ejemplo n.º 33
0
 def __new__(cls, expr, *args):
     expr = Basic.sympify(expr)
     args = tuple(map(Basic.sympify, args))
     #if isinstance(expr, Apply):
     #    if expr[:]==args:
     #        return expr.func
     dummy_args = []
     for a in args:
         if not isinstance(a, Basic.Symbol):
             raise TypeError("%s %s-th argument must be Symbol instance (got %r)" \
                             % (cls.__name__, len(dummy_args)+1,a))
         d = a.as_dummy()
         expr = expr.subs(a, d)
         dummy_args.append(d)
     obj = Basic.__new__(cls, expr, *dummy_args, **expr._assumptions)
     return obj
Ejemplo n.º 34
0
    def __new__(cls, i):
        try:
            return _intcache[i]
        except KeyError:
            # We only work with well-behaved integer types. This converts, for
            # example, numpy.int32 instances.
            ival = int(i)
            if ival == 0: obj = S.Zero
            elif ival == 1: obj = S.One
            elif ival == -1: obj = S.NegativeOne
            else:
                obj = Basic.__new__(cls)
                obj.p = ival

            _intcache[i] = obj
            return obj
Ejemplo n.º 35
0
    def __new__(cls, *sets, **assumptions):
        def flatten(arg):
            if isinstance(arg, Set):
                if arg.is_ProductSet:
                    return sum(map(flatten, arg.args), [])
                else:
                    return [arg]
            elif is_flattenable(arg):
                return sum(map(flatten, arg), [])
            raise TypeError("Input must be Sets or iterables of Sets")
        sets = flatten(list(sets))

        if EmptySet() in sets or len(sets)==0:
            return EmptySet()

        return Basic.__new__(cls, *sets, **assumptions)
Ejemplo n.º 36
0
 def __new__(cls, num, prec=15):
     prec = mpmath.settings.dps_to_prec(prec)
     if isinstance(num, (int, long)):
         return Integer(num)
     if isinstance(num, (str, decimal.Decimal)):
         _mpf_ = mlib.from_str(str(num), prec, rnd)
     elif isinstance(num, tuple) and len(num) == 4:
         _mpf_ = num
     else:
         _mpf_ = mpmath.mpf(num)._mpf_
     if not num:
         return C.Zero()
     obj = Basic.__new__(cls)
     obj._mpf_ = _mpf_
     obj._prec = prec
     return obj
Ejemplo n.º 37
0
 def __new__(cls, num, prec=15):
     prec = mpmath.settings.dps_to_prec(prec)
     if isinstance(num, (int, long)):
         return Integer(num)
     if isinstance(num, (str, decimal.Decimal)):
         _mpf_ = mlib.from_str(str(num), prec, rnd)
     elif isinstance(num, tuple) and len(num) == 4:
         _mpf_ = num
     else:
         _mpf_ = mpmath.mpf(num)._mpf_
     if not num:
         return C.Zero()
     obj = Basic.__new__(cls)
     obj._mpf_ = _mpf_
     obj._prec = prec
     return obj
Ejemplo n.º 38
0
    def __new__(cls, *sets, **assumptions):
        def flatten(arg):
            if isinstance(arg, Set):
                if arg.is_ProductSet:
                    return sum(map(flatten, arg.args), [])
                else:
                    return [arg]
            elif is_flattenable(arg):
                return sum(map(flatten, arg), [])
            raise TypeError("Input must be Sets or iterables of Sets")
        sets = flatten(list(sets))

        if EmptySet() in sets or len(sets)==0:
            return EmptySet()

        return Basic.__new__(cls, *sets, **assumptions)
Ejemplo n.º 39
0
 def __new__(cls, *args, **assumptions):
     if len(args)==0:
         return cls.identity()
     if len(args)==1:
         return Basic.sympify(args[0])
     c_part, nc_part, lambda_args, order_symbols = cls.flatten(map(Basic.sympify, args))
     if len(c_part) + len(nc_part) <= 1:
         if c_part: obj = c_part[0]
         elif nc_part: obj = nc_part[0]
         else: obj = cls.identity()
     else:
         assumptions['commutative'] = not nc_part
         obj = Basic.__new__(cls, *(c_part + nc_part), **assumptions)
     if order_symbols is not None:
         obj = Basic.Order(obj, *order_symbols)
     if lambda_args is not None:
         obj = Basic.Lambda(obj, *lambda_args)
     return obj
Ejemplo n.º 40
0
    def __new__(cls, i):
        try:
            return _intcache[i]
        except KeyError:
            # The most often situation is when Integers are created from Python
            # int or long
            if isinstance(i, (int, long)):
                obj = Basic.__new__(cls)
                obj.p = i
                _intcache[i] = obj
                return obj

            # Also, we seldomly need the following to work:
            # UC: Integer(Integer(4))   <-- sympify('4')
            elif isinstance(i, Integer):
                return i

            else:
                raise ValueError('invalid argument for Integer: %r' % (i,))
Ejemplo n.º 41
0
    def __new__(cls, i):
        try:
            return _intcache[i]
        except KeyError:
            # The most often situation is when Integers are created from Python
            # int or long
            if isinstance(i, (int, long)):
                obj = Basic.__new__(cls)
                obj.p = i
                _intcache[i] = obj
                return obj

            # Also, we seldomly need the following to work:
            # UC: Integer(Integer(4))   <-- sympify('4')
            elif isinstance(i, Integer):
                return i

            else:
                raise ValueError('invalid argument for Integer: %r' % (i,))
Ejemplo n.º 42
0
    def __new__(cls, name, commutative=True, dummy=False, **assumptions):
        """if dummy == True, then this Symbol is totally unique, i.e.::

        >>> bool(Symbol("x") == Symbol("x")) == True
        True

        but with the dummy variable ::

        >>> bool(Symbol("x", dummy = True) == Symbol("x", dummy = True)) == True
        False

        """
        obj = Basic.__new__(cls, commutative=commutative, dummy=dummy, **assumptions)
        if dummy:
            Symbol.dummycount += 1
            obj.dummy_index = Symbol.dummycount
        assert isinstance(name, str), ` type(name) `
        obj.name = name
        return obj
Ejemplo n.º 43
0
    def _new_rawargs(self, *args):
        """create new instance of own class with args exactly as provided by caller

           This is handy when we want to optimize things, e.g.

           >>> from sympy import Mul, symbols
           >>> x,y = symbols('xy')
           >>> e = Mul(3,x,y)
           >>> e.args
           (3, x, y)
           >>> Mul(*e.args[1:])
           x*y
           >>> e._new_rawargs(*e.args[1:])  # the same as above, but faster
           x*y

        """
        obj = Basic.__new__(type(self), *args)  # NB no assumptions for Add/Mul
        obj.is_commutative = self.is_commutative

        return obj
Ejemplo n.º 44
0
    def _new_rawargs(self, *args):
        """create new instance of own class with args exactly as provided by caller

           This is handy when we want to optimize things, e.g.

           >>> from sympy import Mul, symbols
           >>> x,y = symbols('xy')
           >>> e = Mul(3,x,y)
           >>> e.args
           (3, x, y)
           >>> Mul(*e.args[1:])
           x*y
           >>> e._new_rawargs(*e.args[1:])  # the same as above, but faster
           x*y

        """
        obj = Basic.__new__(type(self), *args)  # NB no assumptions for Add/Mul
        obj.is_commutative = self.is_commutative

        return obj
Ejemplo n.º 45
0
    def __new__(cls, *args, **options):
        if cls is SingleValuedFunction or cls is Function:
            #when user writes SingleValuedFunction("f"), do an equivalent of:
            #taking the whole class SingleValuedFunction(...):
            #and rename the SingleValuedFunction to "f" and return f, thus:
            #In [13]: isinstance(f, SingleValuedFunction)
            #Out[13]: False
            #In [14]: isinstance(f, FunctionClass)
            #Out[14]: True

            if len(args) == 1 and isinstance(args[0], str):
                #always create SingleValuedFunction
                return FunctionClass(SingleValuedFunction, *args)
                return FunctionClass(SingleValuedFunction, *args, **options)
            else:
                print args
                print type(args[0])
                raise Exception("You need to specify exactly one string")
        args = map(Basic.sympify, args)
        # these lines should be refactored
        if "nofargs" in options:
            del options["nofargs"]
        if "dummy" in options:
            del options["dummy"]
        if "comparable" in options:
            del options["comparable"]
        if "noncommutative" in options:
            del options["noncommutative"]
        if "commutative" in options:
            del options["commutative"]
        # up to here.
        r = cls._eval_apply(*args, **options)
        if isinstance(r, Basic):
            return r
        elif r is None:
            pass
        elif not isinstance(r, tuple):
            args = (r,)
        return Basic.__new__(cls, *args, **options)
Ejemplo n.º 46
0
    def __new__(cls, *args):
        def flatten(arg):
            if is_flattenable(arg):
                return sum(map(flatten, arg), [])
            return [arg]
        args = flatten(list(args))

        # Sympify Arguments
        args = map(sympify, args)
        # Turn tuples into Tuples
        args = [Tuple(*arg) if arg.__class__ is tuple else arg for arg in args]

        if len(args) == 0:
            return EmptySet()

        if all(arg.is_number and arg.is_real for arg in args):
            cls = RealFiniteSet

        elements = frozenset(map(sympify, args))
        obj = Basic.__new__(cls, elements)
        obj.elements = elements
        return obj
Ejemplo n.º 47
0
    def __new__(cls, *args, **assumptions):
        intervals, other_sets = [], []
        for arg in args:
            if isinstance(arg, EmptySet):
                continue

            elif isinstance(arg, Interval):
                intervals.append(arg)

            elif isinstance(arg, Union):
                intervals += arg.args

            elif isinstance(arg, Set):
                other_sets.append(arg)

            else:
                raise ValueError, "Unknown argument '%s'" % arg

        # Any non-empty sets at all?
        if len(intervals) == 0 and len(other_sets) == 0:
            return S.EmptySet

        # Sort intervals according to their infimum
        intervals.sort(lambda i, j: cmp(i.start, j.start))

        # Merge comparable overlapping intervals
        i = 0
        while i < len(intervals) - 1:
            cur = intervals[i]
            next = intervals[i + 1]

            merge = False
            if cur._is_comparable(next):
                if next.start < cur.end:
                    merge = True
                elif next.start == cur.end:
                    # Must be careful with boundaries.
                    merge = not(next.left_open and cur.right_open)

            if merge:
                if cur.start == next.start:
                    left_open = cur.left_open and next.left_open
                else:
                    left_open = cur.left_open

                if cur.end < next.end:
                    right_open = next.right_open
                    end = next.end
                elif cur.end > next.end:
                    right_open = cur.right_open
                    end = cur.end
                else:
                    right_open = cur.right_open and next.right_open
                    end = cur.end

                intervals[i] = Interval(cur.start, end, left_open, right_open)
                del intervals[i + 1]
            else:
                i += 1

        # If a single set is left over, don't create a new Union object but
        # rather return the single set.
        if len(intervals) == 1 and len(other_sets) == 0:
            return intervals[0]
        elif len(intervals) == 0 and len(other_sets) == 1:
            return other_sets[0]

        return Basic.__new__(cls, *(intervals + other_sets), **assumptions)
Ejemplo n.º 48
0
 def __new__(cls, *args, **assumptions):
     args = [sympify(arg) for arg in args]
     obj = Basic.__new__(cls, *args, **assumptions)
     return obj
Ejemplo n.º 49
0
    def __new__(cls, *args):

        intervals, finite_sets, other_sets = [], [], []
        args = list(args)
        for arg in args:

            if isinstance(arg, Set):
                if arg == S.EmptySet:
                    continue
                elif arg.is_Union:
                    args += arg.args
                elif arg.is_FiniteSet:
                    finite_sets.append(arg)
                elif arg.is_Interval:
                    intervals.append(arg)
                else:
                    other_sets.append(arg)
            elif is_flattenable(arg):
                args += arg
            else:
                raise TypeError("%s: Not a set or iterable of sets"%arg)

        # Sort intervals according to their infimum
        intervals.sort(key=lambda i: i.start)

        # Merge comparable overlapping intervals
        i = 0
        while i < len(intervals) - 1:
            cur = intervals[i]
            next = intervals[i + 1]

            merge = False
            if cur._is_comparable(next):
                if next.start < cur.end:
                    merge = True
                elif next.start == cur.end:
                    # Must be careful with boundaries.
                    merge = not(next.left_open and cur.right_open)

            if merge:
                if cur.start == next.start:
                    left_open = cur.left_open and next.left_open
                else:
                    left_open = cur.left_open

                if cur.end < next.end:
                    right_open = next.right_open
                    end = next.end
                elif cur.end > next.end:
                    right_open = cur.right_open
                    end = cur.end
                else:
                    right_open = cur.right_open and next.right_open
                    end = cur.end

                intervals[i] = Interval(cur.start, end, left_open, right_open)
                del intervals[i + 1]
            else:
                i += 1

        # Collect all elements in the finite sets not in any interval
        if finite_sets:
            # Merge Finite Sets
            finite_set = sum(finite_sets, S.EmptySet)

            # Close open intervals if boundary is in finite_set
            for num, i in enumerate(intervals):
                closeLeft = i.start in finite_set if i.left_open else False
                closeRight = i.end in finite_set if i.right_open else False
                if ((closeLeft and i.left_open)
                        or (closeRight and i.right_open)):
                    intervals[num] = Interval(i.start, i.end,
                            not closeLeft, not closeRight)

            # All elements in finite_set not in any interval
            finite_complement = FiniteSet(
                    el for el in finite_set
                    if not el.is_number
                    or not any(el in i for i in intervals))
            if len(finite_complement)>0: # Anything left?
                other_sets.append(finite_complement)

        # Clear out empty sets
        sets = [set for set in (intervals + other_sets) if set]

        # If nothing is there then return the empty set
        if not sets:
            return S.EmptySet

        # If a single set is left over, don't create a new Union object but
        # rather return the single set.
        if len(sets) == 1:
            return sets[0]

        return Basic.__new__(cls, *sets)
Ejemplo n.º 50
0
 def __new__(cls, start, end, **assumptions):
     start = _sympify(start)
     end = _sympify(end)
     return Basic.__new__(cls, start, end, **assumptions)
Ejemplo n.º 51
0
 def __new_stage2__(cls, name, commutative=True, **assumptions):
     assert isinstance(name, str), ` type(name) `
     obj = Basic.__new__(cls, **assumptions)
     obj.is_commutative = commutative
     obj.name = name
     return obj
Ejemplo n.º 52
-1
    def __new__(cls, expr, *symbols, **assumptions):
        expr = sympify(expr)
        if not symbols: return expr
        symbols = Derivative._symbolgen(*symbols)
        if expr.is_commutative:
            assumptions["commutative"] = True
        if "evaluate" in assumptions:
            evaluate = assumptions["evaluate"]
            del assumptions["evaluate"]
        else:
            evaluate = False
        if not evaluate and not isinstance(expr, Derivative):
            obj = Basic.__new__(cls, expr, *symbols, **assumptions)
            return obj
        unevaluated_symbols = []
        for s in symbols:
            s = sympify(s)
            if not isinstance(s, Symbol):
                raise ValueError('Invalid literal: %s is not a valid variable' % s)
            if not expr.has(s):
                return S.Zero
            obj = expr._eval_derivative(s)
            if obj is None:
                unevaluated_symbols.append(s)
            elif obj is S.Zero:
                return S.Zero
            else:
                expr = obj

        if not unevaluated_symbols:
            return expr
        return Basic.__new__(cls, expr, *unevaluated_symbols, **assumptions)