Beispiel #1
0
    def add(self):
        adder = Add()

        if self.args['one_sample'] is not None:
            new_sample = [tuple(entry.strip('}').strip('{').strip(',').split(':')) for entry in self.args['one_sample']]
            new_sample = dict(new_sample)

            adder.add_one_sample(new_sample)
            if len(self.args['email']) > 0:

                if not sampleinfo_mongo.is_fully_annotated(new_sample['SAMPLE']):
                    annotate = Annotate()
                    annotate.annotate_sample(new_sample['SAMPLE'], 'orig')

                output_files = Output()
                final_file = output_files.sample_variants_csv(new_sample['SAMPLE'], 'orig')

                message = "Here are all the variants for the sample %s with their QC status." % new_sample['SAMPLE']
                for address in self.args['email']:
                    self.__log_sending_email(address)
                    output_bash.email_file(message, final_file, address)

        elif self.args['sample_info'] is not None:

            adder.add_sample_info(self.args['sample_info'])
Beispiel #2
0
    def as_real_imag(self, deep=True, **hints):
        from sympy.core.symbol import symbols
        from sympy.polys.polytools import poly
        from sympy.core.function import expand_multinomial
        if self.exp.is_Integer:
            exp = self.exp
            re, im = self.base.as_real_imag(deep=deep)
            if re.func == C.re or im.func == C.im:
                return self, S.Zero
            a, b = symbols('a b', cls=Dummy)
            if exp >= 0:
                if re.is_Number and im.is_Number:
                    # We can be more efficient in this case
                    expr = expand_multinomial(self.base**exp)
                    return expr.as_real_imag()

                expr = poly((a + b)**exp) # a = re, b = im; expr = (a + b*I)**exp
            else:
                mag = re**2 + im**2
                re, im = re/mag, -im/mag
                if re.is_Number and im.is_Number:
                    # We can be more efficient in this case
                    expr = expand_multinomial((re + im*S.ImaginaryUnit)**-exp)
                    return expr.as_real_imag()

                expr = poly((a + b)**-exp)

            # Terms with even b powers will be real
            r = [i for i in expr.terms() if not i[0][1] % 2]
            re_part = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
            # Terms with odd b powers will be imaginary
            r = [i for i in expr.terms() if i[0][1] % 4 == 1]
            im_part1 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
            r = [i for i in expr.terms() if i[0][1] % 4 == 3]
            im_part3 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])

            return (re_part.subs({a: re, b: S.ImaginaryUnit*im}),
            im_part1.subs({a: re, b: im}) + im_part3.subs({a: re, b: -im}))

        elif self.exp.is_Rational:
            # NOTE: This is not totally correct since for x**(p/q) with
            #       x being imaginary there are actually q roots, but
            #       only a single one is returned from here.
            re, im = self.base.as_real_imag(deep=deep)
            if re.func == C.re or im.func == C.im:
                return self, S.Zero
            r = Pow(Pow(re, 2) + Pow(im, 2), S.Half)
            t = C.atan2(im, re)

            rp, tp = Pow(r, self.exp), t*self.exp

            return (rp*C.cos(tp), rp*C.sin(tp))
        else:

            if deep:
                hints['complex'] = False
                return (C.re(self.expand(deep, **hints)),
                        C.im(self.expand(deep, **hints)))
            else:
                return (C.re(self), C.im(self))
Beispiel #3
0
    def add(self):
        """
        This carries out the appropriate operation if add is selected from the parser.
        :return:
        """
        adder = Add()

        # This is the adding procedure performed for when one sample is added from the command line.
        if self.args['one_sample'] is not None:
            new_sample = [tuple(entry.strip('}').strip('{').strip(',').split(':')) for entry in self.args['one_sample']]
            new_sample = dict(new_sample)

            # The adder actually adds the sample to the database.
            adder.add_one_sample(new_sample)

            # This is what is carried out if an email is desired, it will actually peform an additional
            # annotation to make sure that the result has all of the necessary information.
            if len(self.args['email']) > 0:

                if not sampleinfo_mongo.is_fully_annotated(new_sample['SAMPLE']):
                    annotate = Annotate()
                    annotate.annotate_sample(new_sample['SAMPLE'], 'orig')

                output_files = Output()
                final_file = output_files.sample_variants_csv(new_sample['SAMPLE'], 'orig')

                # This actually carries out the emailing.
                message = "Here are all the variants for the sample %s with their QC status." % new_sample['SAMPLE']
                for address in self.args['email']:
                    self.__log_sending_email(address)
                    output_bash.email_file(message, final_file, address)

        # This is how the samples are added from a  file of many samples.
        elif self.args['sample_info'] is not None:

            adder.add_sample_info(self.args['sample_info'])
Beispiel #4
0
 def __radd__(self, other):
     return Add(other, self)
Beispiel #5
0
    def flatten(cls, seq):

        # apply associativity, separate commutative part of seq
        c_part = []  # out: commutative factors
        nc_part = []  # out: non-commutative factors

        nc_seq = []

        coeff = S.One  # standalone term
        # e.g. 3 * ...

        c_powers = []  # (base,exp)      n
        # e.g. (x,n) for x

        num_exp = []  # (num-base, exp)           y
        # e.g.  (3, y)  for  ... * 3  * ...

        order_symbols = None

        # --- PART 1 ---
        #
        # "collect powers and coeff":
        #
        # o coeff
        # o c_powers
        # o num_exp
        #
        # NOTE: this is optimized for all-objects-are-commutative case

        for o in seq:
            # O(x)
            if o.is_Order:
                o, order_symbols = o.as_expr_variables(order_symbols)

            # Mul([...])
            if o.is_Mul:
                if o.is_commutative:
                    seq.extend(o.args)  # XXX zerocopy?

                else:
                    # NCMul can have commutative parts as well
                    for q in o.args:
                        if q.is_commutative:
                            seq.append(q)
                        else:
                            nc_seq.append(q)

                    # append non-commutative marker, so we don't forget to
                    # process scheduled non-commutative objects
                    seq.append(NC_Marker)

                continue

            # 3
            elif o.is_Number:
                if o is S.NaN or coeff is S.ComplexInfinity and o is S.Zero:
                    # we know for sure the result will be nan
                    return [S.NaN], [], None
                elif coeff.is_Number:  # it could be zoo
                    coeff *= o
                    if coeff is S.NaN:
                        # we know for sure the result will be nan
                        return [S.NaN], [], None
                continue

            elif o is S.ComplexInfinity:
                if not coeff or coeff is S.ComplexInfinity:
                    # we know for sure the result will be nan
                    return [S.NaN], [], None
                coeff = S.ComplexInfinity
                continue

            elif o.is_commutative:
                #      e
                # o = b
                b, e = o.as_base_exp()

                #  y
                # 3
                if o.is_Pow and b.is_Number:
                    # get all the factors with numeric base so they can be
                    # combined below, but don't combine negatives unless
                    # the exponent is an integer
                    if b.is_positive or e.is_integer:
                        num_exp.append((b, e))
                        continue

                #         n          n          n
                # (-3 + y)   ->  (-1)  * (3 - y)
                #
                # Give powers a chance to become a Mul if that's the
                # behavior obtained from Add._eval_power()
                if not Basic.keep_sign and b.is_Add and e.is_Number:
                    cb = b._eval_power(e, terms=True)
                    if cb:
                        c, b = cb
                        coeff *= c

                c_powers.append((b, e))

            # NON-COMMUTATIVE
            # TODO: Make non-commutative exponents not combine automatically
            else:
                if o is not NC_Marker:
                    nc_seq.append(o)

                # process nc_seq (if any)
                while nc_seq:
                    o = nc_seq.pop(0)
                    if not nc_part:
                        nc_part.append(o)
                        continue

                    #                             b    c       b+c
                    # try to combine last terms: a  * a   ->  a
                    o1 = nc_part.pop()
                    b1, e1 = o1.as_base_exp()
                    b2, e2 = o.as_base_exp()
                    new_exp = e1 + e2
                    # Only allow powers to combine if the new exponent is
                    # not an Add. This allow things like a**2*b**3 == a**5
                    # if a.is_commutative == False, but prohibits
                    # a**x*a**y and x**a*x**b from combining (x,y commute).
                    if b1 == b2 and (not new_exp.is_Add):
                        o12 = b1**new_exp

                        # now o12 could be a commutative object
                        if o12.is_commutative:
                            seq.append(o12)
                            continue
                        else:
                            nc_seq.insert(0, o12)

                    else:
                        nc_part.append(o1)
                        nc_part.append(o)

        # We do want a combined exponent if it would not be an Add, such as
        #  y    2y     3y
        # x  * x   -> x
        # We determine this if two exponents have the same term in as_coeff_mul
        #
        # Unfortunately, this isn't smart enough to consider combining into
        # exponents that might already be adds, so things like:
        #  z - y    y
        # x      * x  will be left alone.  This is because checking every possible
        # combination can slow things down.

        # gather exponents of common bases...
        # in c_powers
        new_c_powers = []
        common_b = {}  # b:e

        for b, e in c_powers:
            co = e.as_coeff_mul()
            common_b.setdefault(b, {}).setdefault(co[1], []).append(co[0])
        for b, d in common_b.items():
            for di, li in d.items():
                d[di] = Add(*li)

        for b, e in common_b.items():
            for t, c in e.items():
                new_c_powers.append((b, c * Mul(*t)))
        c_powers = new_c_powers

        # and in num_exp
        new_num_exp = []
        common_b = {}  # b:e

        for b, e in num_exp:
            co = e.as_coeff_mul()
            common_b.setdefault(b, {}).setdefault(co[1], []).append(co[0])
        for b, d in common_b.items():
            for di, li in d.items():
                d[di] = Add(*li)

        for b, e in common_b.items():
            for t, c in e.items():
                new_num_exp.append((b, c * Mul(*t)))
        num_exp = new_num_exp

        # --- PART 2 ---
        #
        # o process collected powers  (x**0 -> 1; x**1 -> x; otherwise Pow)
        # o combine collected powers  (2**x * 3**x -> 6**x)
        #   with numeric base

        # ................................
        # now we have:
        # - coeff:
        # - c_powers:    (b, e)
        # - num_exp:     (2, e)

        #  0             1
        # x  -> 1       x  -> x
        for b, e in c_powers:
            if e is S.Zero:
                continue

            if e is S.One:
                if b.is_Number:
                    coeff *= b
                else:
                    c_part.append(b)
            elif e.is_Integer and b.is_Number:
                coeff *= Pow(b, e)
            else:
                c_part.append(Pow(b, e))

        #  x    x     x
        # 2  * 3  -> 6
        inv_exp_dict = {}  # exp:Mul(num-bases)     x    x
        # e.g.  x:6  for  ... * 2  * 3  * ...
        for b, e in num_exp:
            inv_exp_dict.setdefault(e, []).append(b)
        for e, b in inv_exp_dict.items():
            inv_exp_dict[e] = Mul(*b)

        reeval = False

        for e, b in inv_exp_dict.items():
            if e is S.Zero:
                continue

            if e is S.One:
                if b.is_Number:
                    coeff *= b
                else:
                    c_part.append(b)
            elif e.is_Integer and b.is_Number:
                coeff *= Pow(b, e)
            else:
                obj = b**e
                if obj.is_Mul:
                    # We may have split out a number that needs to go in coeff
                    # e.g., sqrt(6)*sqrt(2) == 2*sqrt(3).  See issue 415.
                    reeval = True
                if obj.is_Number:
                    coeff *= obj
                else:
                    c_part.append(obj)

        # oo, -oo
        if (coeff is S.Infinity) or (coeff is S.NegativeInfinity):
            new_c_part = []
            coeff_sign = 1
            for t in c_part:
                if t.is_positive:
                    continue
                if t.is_negative:
                    coeff_sign *= -1
                    continue
                new_c_part.append(t)
            c_part = new_c_part
            new_nc_part = []
            for t in nc_part:
                if t.is_positive:
                    continue
                if t.is_negative:
                    coeff_sign *= -1
                    continue
                new_nc_part.append(t)
            nc_part = new_nc_part
            coeff *= coeff_sign

        # zoo
        if coeff is S.ComplexInfinity:
            # zoo might be
            #   unbounded_real + bounded_im
            #   bounded_real + unbounded_im
            #   unbounded_real + unbounded_im
            # and non-zero real or imaginary will not change that status.
            c_part = [
                c for c in c_part
                if not (c.is_nonzero and c.is_real is not None)
            ]
            nc_part = [
                c for c in nc_part
                if not (c.is_nonzero and c.is_real is not None)
            ]

        # 0
        elif coeff is S.Zero:
            # we know for sure the result will be 0
            return [coeff], [], order_symbols

        elif coeff.is_Real:
            if coeff == Real(0):
                c_part, nc_part = [coeff], []
            elif coeff == Real(1):
                # change it to One, so it doesn't get inserted to slot0
                coeff = S.One

        # order commutative part canonically
        c_part.sort(Basic.compare)

        # current code expects coeff to be always in slot-0
        if coeff is not S.One:
            c_part.insert(0, coeff)

        # we are done
        if len(c_part) == 2 and c_part[0].is_Number and c_part[1].is_Add:
            # 2*(1+a) -> 2 + 2 * a
            coeff = c_part[0]
            c_part = [Add(*[coeff * f for f in c_part[1].args])]

        if reeval:
            c_part, _, _ = Mul.flatten(c_part)
        return c_part, nc_part, order_symbols
Beispiel #6
0
 def add(self):
     self.add = Add()
     self.add.show()
Beispiel #7
0
Datei: zjm.py Projekt: adminwj1/-
 def add(self):
     add = Add()
Beispiel #8
0
    def as_real_imag(self, deep=True, **hints):
        from sympy.polys.polytools import poly

        if self.exp.is_Integer:
            exp = self.exp
            re, im = self.base.as_real_imag(deep=deep)
            if not im:
                return self, S.Zero
            a, b = symbols('a b', cls=Dummy)
            if exp >= 0:
                if re.is_Number and im.is_Number:
                    # We can be more efficient in this case
                    expr = expand_multinomial(self.base**exp)
                    return expr.as_real_imag()

                expr = poly(
                    (a + b)**exp)  # a = re, b = im; expr = (a + b*I)**exp
            else:
                mag = re**2 + im**2
                re, im = re / mag, -im / mag
                if re.is_Number and im.is_Number:
                    # We can be more efficient in this case
                    expr = expand_multinomial(
                        (re + im * S.ImaginaryUnit)**-exp)
                    return expr.as_real_imag()

                expr = poly((a + b)**-exp)

            # Terms with even b powers will be real
            r = [i for i in expr.terms() if not i[0][1] % 2]
            re_part = Add(*[cc * a**aa * b**bb for (aa, bb), cc in r])
            # Terms with odd b powers will be imaginary
            r = [i for i in expr.terms() if i[0][1] % 4 == 1]
            im_part1 = Add(*[cc * a**aa * b**bb for (aa, bb), cc in r])
            r = [i for i in expr.terms() if i[0][1] % 4 == 3]
            im_part3 = Add(*[cc * a**aa * b**bb for (aa, bb), cc in r])

            return (re_part.subs({
                a: re,
                b: S.ImaginaryUnit * im
            }), im_part1.subs({
                a: re,
                b: im
            }) + im_part3.subs({
                a: re,
                b: -im
            }))

        elif self.exp.is_Rational:
            # NOTE: This is not totally correct since for x**(p/q) with
            #       x being imaginary there are actually q roots, but
            #       only a single one is returned from here.
            re, im = self.base.as_real_imag(deep=deep)
            r = Pow(Pow(re, 2) + Pow(im, 2), S.Half)
            t = C.atan2(im, re)

            rp, tp = Pow(r, self.exp), t * self.exp

            return (rp * C.cos(tp), rp * C.sin(tp))
        else:

            if deep:
                hints['complex'] = False

                expanded = self.expand(deep, **hints)
                if hints.get('ignore') == expanded:
                    return None
                else:
                    return (C.re(expanded), C.im(expanded))
            else:
                return (C.re(self), C.im(self))
Beispiel #9
0
    def _eval_expand_multinomial(self, deep=True, **hints):
        """(a+b+..) ** n -> a**n + n*a**(n-1)*b + .., n is nonzero integer"""
        if deep:
            b = self.base.expand(deep=deep, **hints)
            e = self.exp.expand(deep=deep, **hints)
        else:
            b = self.base
            e = self.exp

        if b is None:
            base = self.base
        else:
            base = b

        if e is None:
            exp = self.exp
        else:
            exp = e

        if e is not None or b is not None:
            result = Pow(base, exp)

            if result.is_Pow:
                base, exp = result.base, result.exp
            else:
                return result
        else:
            result = None

        if exp.is_Rational and exp.p > 0 and base.is_Add:
            if not exp.is_Integer:
                n = Integer(exp.p // exp.q)

                if not n:
                    return Pow(base, exp)
                else:
                    radical, result = Pow(base, exp - n), []

                    for term in Add.make_args(
                            Pow(base, n)._eval_expand_multinomial(deep=False)):
                        result.append(term * radical)

                    return Add(*result)

            n = int(exp)

            if base.is_commutative:
                order_terms, other_terms = [], []

                for order in base.args:
                    if order.is_Order:
                        order_terms.append(order)
                    else:
                        other_terms.append(order)

                if order_terms:
                    # (f(x) + O(x^n))^m -> f(x)^m + m*f(x)^{m-1} *O(x^n)
                    f = Add(*other_terms)
                    g = (f**(n - 1)).expand()

                    return (f * g).expand() + n * g * Add(*order_terms)

                if base.is_number:
                    # Efficiently expand expressions of the form (a + b*I)**n
                    # where 'a' and 'b' are real numbers and 'n' is integer.
                    a, b = base.as_real_imag()

                    if a.is_Rational and b.is_Rational:
                        if not a.is_Integer:
                            if not b.is_Integer:
                                k = Pow(a.q * b.q, n)
                                a, b = a.p * b.q, a.q * b.p
                            else:
                                k = Pow(a.q, n)
                                a, b = a.p, a.q * b
                        elif not b.is_Integer:
                            k = Pow(b.q, n)
                            a, b = a * b.q, b.p
                        else:
                            k = 1

                        a, b, c, d = int(a), int(b), 1, 0

                        while n:
                            if n & 1:
                                c, d = a * c - b * d, b * c + a * d
                                n -= 1
                            a, b = a * a - b * b, 2 * a * b
                            n //= 2

                        I = S.ImaginaryUnit

                        if k == 1:
                            return c + I * d
                        else:
                            return Integer(c) / k + I * d / k

                p = other_terms
                # (x+y)**3 -> x**3 + 3*x**2*y + 3*x*y**2 + y**3
                # in this particular example:
                # p = [x,y]; n = 3
                # so now it's easy to get the correct result -- we get the
                # coefficients first:
                from sympy import multinomial_coefficients
                expansion_dict = multinomial_coefficients(len(p), n)
                # in our example: {(3, 0): 1, (1, 2): 3, (0, 3): 1, (2, 1): 3}
                # and now construct the expression.

                # An elegant way would be to use Poly, but unfortunately it is
                # slower than the direct method below, so it is commented out:
                #b = {}
                #for k in expansion_dict:
                #    b[k] = Integer(expansion_dict[k])
                #return Poly(b, *p).as_basic()

                from sympy.polys.polyutils import basic_from_dict
                result = basic_from_dict(expansion_dict, *p)
                return result
            else:
                if n == 2:
                    return Add(*[f * g for f in base.args for g in base.args])
                else:
                    multi = (base**(n -
                                    1))._eval_expand_multinomial(deep=False)
                    if multi.is_Add:
                        return Add(
                            *[f * g for f in base.args for g in multi.args])
                    else:
                        return Add(*[f * multi for f in base.args])
        elif exp.is_Rational and exp.p < 0 and base.is_Add and abs(
                exp.p) > exp.q:
            return 1 / Pow(base, -exp)._eval_expand_multinomial(deep=False)
        elif exp.is_Add and base.is_Number:
            #  a + b      a  b
            # n      --> n  n  , where n, a, b are Numbers

            coeff, tail = S.One, S.Zero

            for term in exp.args:
                if term.is_Number:
                    coeff *= Pow(base, term)
                else:
                    tail += term

            return coeff * Pow(base, tail)
        else:
            return result
Beispiel #10
0
    def flatten(cls, seq):

        # apply associativity, separate commutative part of seq
        c_part = []  # out: commutative factors
        nc_part = []  # out: non-commutative factors

        nc_seq = []

        coeff = S.One  # standalone term
        # e.g. 3 * ...

        c_powers = []  # (base,exp)      n
        # e.g. (x,n) for x

        num_exp = []  # (num-base, exp)           y
        # e.g.  (3, y)  for  ... * 3  * ...

        neg1e = 0  # exponent on -1 extracted from Number-based Pow

        pnum_rat = {}  # (num-base, Rat-exp)          1/2
        # e.g.  (3, 1/2)  for  ... * 3     * ...

        order_symbols = None

        # --- PART 1 ---
        #
        # "collect powers and coeff":
        #
        # o coeff
        # o c_powers
        # o num_exp
        # o neg1e
        # o pnum_rat
        #
        # NOTE: this is optimized for all-objects-are-commutative case

        for o in seq:
            # O(x)
            if o.is_Order:
                o, order_symbols = o.as_expr_variables(order_symbols)

            # Mul([...])
            if o.is_Mul:
                if o.is_commutative:
                    seq.extend(o.args)  # XXX zerocopy?

                else:
                    # NCMul can have commutative parts as well
                    for q in o.args:
                        if q.is_commutative:
                            seq.append(q)
                        else:
                            nc_seq.append(q)

                    # append non-commutative marker, so we don't forget to
                    # process scheduled non-commutative objects
                    seq.append(NC_Marker)

                continue

            # 3
            elif o.is_Number:
                if o is S.NaN or coeff is S.ComplexInfinity and o is S.Zero:
                    # we know for sure the result will be nan
                    return [S.NaN], [], None
                elif coeff.is_Number:  # it could be zoo
                    coeff *= o
                    if coeff is S.NaN:
                        # we know for sure the result will be nan
                        return [S.NaN], [], None
                continue

            elif o is S.ComplexInfinity:
                if not coeff or coeff is S.ComplexInfinity:
                    # we know for sure the result will be nan
                    return [S.NaN], [], None
                coeff = S.ComplexInfinity
                continue

            elif o.is_commutative:
                #      e
                # o = b
                b, e = o.as_base_exp()

                #  y
                # 3
                if o.is_Pow and b.is_Number:

                    # get all the factors with numeric base so they can be
                    # combined below, but don't combine negatives unless
                    # the exponent is an integer
                    if e.is_Rational:
                        if e.is_Integer:
                            coeff *= Pow(b, e)  # it is an unevaluated power
                            continue
                        elif e.is_negative:  # also a sign of an unevaluated power
                            seq.append(Pow(b, e))
                            continue
                        elif b.is_negative:
                            neg1e += e
                            b = -b
                        if b is not S.One:
                            pnum_rat.setdefault(b, []).append(e)
                        continue
                    elif b.is_positive or e.is_integer:
                        num_exp.append((b, e))
                        continue
                c_powers.append((b, e))

            # NON-COMMUTATIVE
            # TODO: Make non-commutative exponents not combine automatically
            else:
                if o is not NC_Marker:
                    nc_seq.append(o)

                # process nc_seq (if any)
                while nc_seq:
                    o = nc_seq.pop(0)
                    if not nc_part:
                        nc_part.append(o)
                        continue

                    #                             b    c       b+c
                    # try to combine last terms: a  * a   ->  a
                    o1 = nc_part.pop()
                    b1, e1 = o1.as_base_exp()
                    b2, e2 = o.as_base_exp()
                    new_exp = e1 + e2
                    # Only allow powers to combine if the new exponent is
                    # not an Add. This allow things like a**2*b**3 == a**5
                    # if a.is_commutative == False, but prohibits
                    # a**x*a**y and x**a*x**b from combining (x,y commute).
                    if b1 == b2 and (not new_exp.is_Add):
                        o12 = b1**new_exp

                        # now o12 could be a commutative object
                        if o12.is_commutative:
                            seq.append(o12)
                            continue
                        else:
                            nc_seq.insert(0, o12)

                    else:
                        nc_part.append(o1)
                        nc_part.append(o)

        # We do want a combined exponent if it would not be an Add, such as
        #  y    2y     3y
        # x  * x   -> x
        # We determine this if two exponents have the same term in as_coeff_mul
        #
        # Unfortunately, this isn't smart enough to consider combining into
        # exponents that might already be adds, so things like:
        #  z - y    y
        # x      * x  will be left alone.  This is because checking every possible
        # combination can slow things down.

        # gather exponents of common bases...
        # in c_powers
        new_c_powers = []
        common_b = {}  # b:e
        for b, e in c_powers:
            co = e.as_coeff_mul()
            common_b.setdefault(b, {}).setdefault(co[1], []).append(co[0])
        for b, d in common_b.items():
            for di, li in d.items():
                d[di] = Add(*li)
        for b, e in common_b.items():
            for t, c in e.items():
                new_c_powers.append((b, c * Mul(*t)))
        c_powers = new_c_powers

        # and in num_exp
        new_num_exp = []
        common_b = {}  # b:e
        for b, e in num_exp:
            co = e.as_coeff_mul()
            common_b.setdefault(b, {}).setdefault(co[1], []).append(co[0])
        for b, d in common_b.items():
            for di, li in d.items():
                d[di] = Add(*li)
        for b, e in common_b.items():
            for t, c in e.items():
                new_num_exp.append((b, c * Mul(*t)))
        num_exp = new_num_exp

        # --- PART 2 ---
        #
        # o process collected powers  (x**0 -> 1; x**1 -> x; otherwise Pow)
        # o combine collected powers  (2**x * 3**x -> 6**x)
        #   with numeric base

        # ................................
        # now we have:
        # - coeff:
        # - c_powers:    (b, e)
        # - num_exp:     (2, e)
        # - pnum_rat:    {(1/3, [1/3, 2/3, 1/4])}

        #  0             1
        # x  -> 1       x  -> x
        for b, e in c_powers:
            if e is S.One:
                if b.is_Number:
                    coeff *= b
                else:
                    c_part.append(b)
            elif not e is S.Zero:
                c_part.append(Pow(b, e))

        #  x    x     x
        # 2  * 3  -> 6
        inv_exp_dict = {}  # exp:Mul(num-bases)     x    x
        # e.g.  x:6  for  ... * 2  * 3  * ...
        for b, e in num_exp:
            inv_exp_dict.setdefault(e, []).append(b)
        for e, b in inv_exp_dict.items():
            inv_exp_dict[e] = Mul(*b)
        c_part.extend([Pow(b, e) for e, b in inv_exp_dict.iteritems() if e])

        # b, e -> e, b
        # {(1/5, [1/3]), (1/2, [1/12, 1/4]} -> {(1/3, [1/5, 1/2])}
        comb_e = {}
        for b, e in pnum_rat.iteritems():
            comb_e.setdefault(Add(*e), []).append(b)
        del pnum_rat
        # process them, reducing exponents to values less than 1
        # and updating coeff if necessary else adding them to
        # num_rat for further processing
        num_rat = []
        for e, b in comb_e.iteritems():
            b = Mul(*b)
            if e.q == 1:
                coeff *= Pow(b, e)
                continue
            if e.p > e.q:
                e_i, ep = divmod(e.p, e.q)
                coeff *= Pow(b, e_i)
                e = Rational(ep, e.q)
            num_rat.append((b, e))
        del comb_e

        # extract gcd of bases in num_rat
        # 2**(1/3)*6**(1/4) -> 2**(1/3+1/4)*3**(1/4)
        pnew = {}
        i = 0  # steps through num_rat which may grow
        while i < len(num_rat):
            bi, ei = num_rat[i]
            grow = []
            for j in range(i + 1, len(num_rat)):
                bj, ej = num_rat[j]
                g = igcd(bi, bj)
                if g != 1:
                    # 4**r1*6**r2 -> 2**(r1+r2)  *  2**r1 *  3**r2
                    # this might have a gcd with something else
                    e = ei + ej
                    if e.q == 1:
                        coeff *= Pow(g, e)
                    else:
                        if e.p > e.q:
                            e_i, ep = divmod(e.p, e.q)  # change e in place
                            coeff *= Pow(g, e_i)
                            e = Rational(ep, e.q)
                        grow.append((g, e))
                    # update the jth item
                    num_rat[j] = (bj // g, ej)
                    # update bi that we are checking with
                    bi = bi // g
                    if bi is S.One:
                        break
            if bi is not S.One:
                obj = Pow(bi, ei)
                if obj.is_Number:
                    coeff *= obj
                else:
                    if obj.is_Mul:  # 12**(1/2) -> 2*sqrt(3)
                        c, obj = obj.args  # expecting only 2 args
                        coeff *= c
                        assert obj.is_Pow
                        bi, ei = obj.args
                    pnew.setdefault(ei, []).append(bi)

            num_rat.extend(grow)
            i += 1

        # combine bases of the new powers
        for e, b in pnew.iteritems():
            pnew[e] = Mul(*b)

        # see if there is a base with matching coefficient
        # that the -1 can be joined with
        if neg1e:
            p = Pow(S.NegativeOne, neg1e)
            if p.is_Number:
                coeff *= p
            else:
                if p.is_Mul:
                    c, p = p.args
                    coeff *= c
                    assert p.is_Pow and p.base is S.NegativeOne
                    neg1e = p.args[1]
                for e, b in pnew.iteritems():
                    if e == neg1e and b.is_positive:
                        pnew[e] = -b
                        break
                else:
                    c_part.append(p)

        # add all the pnew powers
        c_part.extend([Pow(b, e) for e, b in pnew.iteritems()])

        # oo, -oo
        if (coeff is S.Infinity) or (coeff is S.NegativeInfinity):
            new_c_part = []
            coeff_sign = 1
            for t in c_part:
                if t.is_positive:
                    continue
                if t.is_negative:
                    coeff_sign *= -1
                    continue
                new_c_part.append(t)
            c_part = new_c_part
            new_nc_part = []
            for t in nc_part:
                if t.is_positive:
                    continue
                if t.is_negative:
                    coeff_sign *= -1
                    continue
                new_nc_part.append(t)
            nc_part = new_nc_part
            coeff *= coeff_sign

        # zoo
        if coeff is S.ComplexInfinity:
            # zoo might be
            #   unbounded_real + bounded_im
            #   bounded_real + unbounded_im
            #   unbounded_real + unbounded_im
            # and non-zero real or imaginary will not change that status.
            c_part = [
                c for c in c_part
                if not (c.is_nonzero and c.is_real is not None)
            ]
            nc_part = [
                c for c in nc_part
                if not (c.is_nonzero and c.is_real is not None)
            ]

        # 0
        elif coeff is S.Zero:
            # we know for sure the result will be 0
            return [coeff], [], order_symbols

        # order commutative part canonically
        c_part.sort(Basic.compare)

        # current code expects coeff to be always in slot-0
        if coeff is not S.One:
            c_part.insert(0, coeff)

        # we are done
        if len(c_part) == 2 and c_part[0].is_Number and c_part[1].is_Add:
            # 2*(1+a) -> 2 + 2 * a
            coeff = c_part[0]
            c_part = [Add(*[coeff * f for f in c_part[1].args])]

        return c_part, nc_part, order_symbols
Beispiel #11
0
from and_node import And
from warp_affine import WarpAffine
from dubbel_io_test import DubbelIoTest

#Only create node classes once, when module is first loaded
DEFAULT_DUMMY_NODE = BaseNode() #Used if name of node is not in the dictionary

NODE_DICTIONARY = {'HalfScaleGaussian'  : HalfScaleGaussian(),
                   'Subtract'           : Subtract(),
                   'Threshold'          : Threshold(),
                   'Sobel3x3'           : Sobel3x3(),
                   'AbsDiff'            : AbsDiff(),
                   'ConvertDepth'       : ConvertDepth(),
                   'Dilate3x3'          : Dilate3x3(),
                   'Erode3x3'           : Erode3x3(),
                   'Add'                : Add(),
                   'Multiply'           : Multiply(),
                   'ScaleImage'         : ScaleImage(),
                   'Magnitude'          : Magnitude(),
                   'TableLookup'        : TableLookup(),
                   'Or'                 : Or(),
                   'And'                : And(),
                   'WarpAffine'         : WarpAffine(),
                   'DubbelIoTest'       : DubbelIoTest(), #This is a dummy node used only for testing the parser.
                   'Dilate2x2'          : Dilate2x2(),
                   'Erode2x2'           : Erode2x2()
                   }

#This dict gives the first parameter index for the first input image in the vxCreateXXXNode function call
#Note that the vx_graph parameter is not counted when accessing node parameters
#Therefore the first index starts on 0, for the first parameter AFTER vx_graph.
Beispiel #12
0
def count_ops(expr, visual=False):
    """
    Return a representation (integer or expression) of the operations in expr.

    If `visual` is False (default) then the sum of the coefficients of the
    visual expression will be returned.

    If `visual` is True then the number of each type of operation is shown
    with the core class types (or their virtual equivalent) multiplied by the
    number of times they occur.

    If expr is an iterable, the sum of the op counts of the
    items will be returned.

    Examples:
        >>> from sympy.abc import a, b, x, y
        >>> from sympy import sin, count_ops

    Although there isn't a SUB object, minus signs are interpreted as
    either negations or subtractions:
        >>> (x - y).count_ops(visual=True)
        SUB
        >>> (-x).count_ops(visual=True)
        NEG

    Here, there are two Adds and a Pow:
        >>> (1 + a + b**2).count_ops(visual=True)
        POW + 2*ADD

    In the following, an Add, Mul, Pow and two functions:
        >>> (sin(x)*x + sin(x)**2).count_ops(visual=True)
        ADD + MUL + POW + 2*SIN

    for a total of 5:
        >>> (sin(x)*x + sin(x)**2).count_ops(visual=False)
        5

    Note that "what you type" is not always what you get. The expression
    1/x/y is translated by sympy into 1/(x*y) so it gives a DIV and MUL rather
    than two DIVs:
        >>> (1/x/y).count_ops(visual=True)
        DIV + MUL

    The visual option can be used to demonstrate the difference in
    operations for expressions in different forms. Here, the Horner
    representation is compared with the expanded form of a polynomial:
        >>> eq=x*(1 + x*(2 + x*(3 + x)))
        >>> count_ops(eq.expand(), visual=True) - count_ops(eq, visual=True)
        -MUL + 3*POW

    The count_ops function also handles iterables:
        >>> count_ops([x, sin(x), None, True, x + 2], visual=False)
        2
        >>> count_ops([x, sin(x), None, True, x + 2], visual=True)
        ADD + SIN
        >>> count_ops({x: sin(x), x + 2: y + 1}, visual=True)
        SIN + 2*ADD

    """
    from sympy.simplify.simplify import fraction

    expr = sympify(expr)
    if isinstance(expr, Expr):

        ops = []
        args = [expr]
        NEG = C.Symbol('NEG')
        DIV = C.Symbol('DIV')
        SUB = C.Symbol('SUB')
        ADD = C.Symbol('ADD')

        def isneg(a):
            c = a.as_coeff_mul()[0]
            return c.is_Number and c.is_negative

        while args:
            a = args.pop()
            if a.is_Rational:
                #-1/3 = NEG + DIV
                if a is not S.One:
                    if a.p < 0:
                        ops.append(NEG)
                    if a.q != 1:
                        ops.append(DIV)
                    continue
            elif a.is_Mul:
                if isneg(a):
                    ops.append(NEG)
                    if a.args[0] is S.NegativeOne:
                        a = a.as_two_terms()[1]
                    else:
                        a = -a
                n, d = fraction(a)
                if n.is_Integer:
                    ops.append(DIV)
                    if n < 0:
                        ops.append(NEG)
                    args.append(d)
                    continue  # won't be -Mul but could be Add
                elif d is not S.One:
                    if not d.is_Integer:
                        args.append(d)
                    ops.append(DIV)
                    args.append(n)
                    continue  # could be -Mul
            elif a.is_Add:
                aargs = list(a.args)
                negs = 0
                for i, ai in enumerate(aargs):
                    if isneg(ai):
                        negs += 1
                        args.append(-ai)
                        if i > 0:
                            ops.append(SUB)
                    else:
                        args.append(ai)
                        if i > 0:
                            ops.append(ADD)
                if negs == len(aargs):  # -x - y = NEG + SUB
                    ops.append(NEG)
                elif isneg(aargs[0]
                           ):  # -x + y = SUB, but we already recorded an ADD
                    ops.append(SUB - ADD)
                continue
            if a.is_Pow and a.exp is S.NegativeOne:
                ops.append(DIV)
                args.append(a.base)  # won't be -Mul but could be Add
                continue
            if (a.is_Mul or a.is_Pow or a.is_Function
                    or isinstance(a, Derivative) or isinstance(a, C.Integral)):

                o = C.Symbol(a.func.__name__.upper())
                # count the args
                if (a.is_Mul or isinstance(a, C.LatticeOp)):
                    ops.append(o * (len(a.args) - 1))
                else:
                    ops.append(o)
            args.extend(a.args)

    elif type(expr) is dict:
        ops = [
            count_ops(k, visual=visual) + count_ops(v, visual=visual)
            for k, v in expr.iteritems()
        ]
    elif hasattr(expr, '__iter__'):
        ops = [count_ops(i, visual=visual) for i in expr]
    elif not isinstance(expr, Basic):
        ops = []
    else:  # it's Basic not isinstance(expr, Expr):
        assert isinstance(expr, Basic)
        ops = [count_ops(a, visual=visual) for a in expr.args]

    if not ops:
        if visual:
            return S.Zero
        return 0

    ops = Add(*ops)

    if visual:
        return ops

    if ops.is_Number:
        return int(ops)

    return sum(int((a.args or [1])[0]) for a in Add.make_args(ops))
Beispiel #13
0
 def __add__(self, other):
     return Add(self, other)
Beispiel #14
0
def add_post():
    val = Add(request)
    print(val.correct_data)
    if val.correct_data:
        return val.message, 200
    return val.message, 400
Beispiel #15
0
 def addnew(self):
     self.withdraw()
     Add(self, self.id)
Beispiel #16
0
    def _eval_nseries(self, x, x0, n):
        from sympy import powsimp, collect

        def geto(e):
            "Returns the O(..) symbol, or None if there is none."
            if e.is_Order:
                return e
            if e.is_Add:
                for x in e.args:
                    if x.is_Order:
                        return x

        def getn(e):
            """
            Returns the order of the expression "e".

            The order is determined either from the O(...) term. If there
            is no O(...) term, it returns None.

            Example:
            >>> getn(1+x+O(x**2))
            2
            >>> getn(1+x)
            >>>
            """
            o = geto(e)
            if o is None:
                return None
            else:
                o = o.expr
                if o.is_Symbol:
                    return Integer(1)
                if o.is_Pow:
                    return o.args[1]
                n, d = o.as_numer_denom()
                if isinstance(d, log):
                    # i.e. o = x**2/log(x)
                    if n.is_Symbol:
                        return Integer(1)
                    if n.is_Pow:
                        return n.args[1]

            raise NotImplementedError()

        base, exp = self.args
        if exp.is_Integer:
            if exp > 0:
                # positive integer powers are easy to expand, e.g.:
                # sin(x)**4 = (x-x**3/3+...)**4 = ...
                return (base.nseries(x, x0, n) ** exp).expand()
            elif exp == -1:
                # this is also easy to expand using the formula:
                # 1/(1 + x) = 1 + x + x**2 + x**3 ...
                # so we need to rewrite base to the form "1+x"
                from sympy import log
                if base.has(log(x)):
                    # we need to handle the log(x) singularity:
                    assert x0 == 0
                    y = Symbol("y", dummy=True)
                    p = self.subs(log(x), -1/y)
                    if not p.has(x):
                        p = p.nseries(y, x0, n)
                        p = p.subs(y, -1/log(x))
                        return p

                base = base.nseries(x, x0, n)
                if base.has(log(x)):
                    # we need to handle the log(x) singularity:
                    assert x0 == 0
                    y = Symbol("y", dummy=True)
                    self0 = 1/base
                    p = self0.subs(log(x), -1/y)
                    if not p.has(x):
                        p = p.nseries(y, x0, n)
                        p = p.subs(y, -1/log(x))
                        return p
                prefactor = base.as_leading_term(x)
                # express "rest" as: rest = 1 + k*x**l + ... + O(x**n)
                rest = powsimp(((base-prefactor)/prefactor).expand(),\
                deep=True, combine='exp')
                if rest == 0:
                    # if prefactor == w**4 + x**2*w**4 + 2*x*w**4, we need to
                    # factor the w**4 out using collect:
                    return 1/collect(prefactor, x)
                if rest.is_Order:
                    return ((1+rest)/prefactor).expand()
                n2 = getn(rest)
                if n2 is not None:
                    n = n2

                term2 = collect(rest.as_leading_term(x), x)
                k, l = Wild("k"), Wild("l")
                r = term2.match(k*x**l)
                k, l = r[k], r[l]
                if l.is_Integer and l>0:
                    l = int(l)
                elif l.is_number and l>0:
                    l = float(l)
                else:
                    raise NotImplementedError()

                s = 1
                m = 1
                while l * m < n:
                    s += ((-rest)**m).expand()
                    m += 1
                r = (s/prefactor).expand()
                if n2 is None:
                    # Append O(...) because it is not included in "r"
                    from sympy import O
                    r += O(x**n)
                return powsimp(r, deep=True, combine='exp')
            else:
                # negative powers are rewritten to the cases above, for example:
                # sin(x)**(-4) = 1/( sin(x)**4) = ...
                # and expand the denominator:
                denominator = (base**(-exp)).nseries(x, x0, n)
                if 1/denominator == self:
                    return self
                # now we have a type 1/f(x), that we know how to expand
                return (1/denominator).nseries(x, x0, n)

        if exp.has(x):
            import sympy
            return sympy.exp(exp*sympy.log(base)).nseries(x, x0, n)

        if base == x:
            return powsimp(self, deep=True, combine='exp')

        order = C.Order(x**n, x)
        x = order.symbols[0]
        e = self.exp
        b = self.base
        ln = C.log
        exp = C.exp
        if e.has(x):
            return exp(e * ln(b)).nseries(x, x0, n)
        if b==x:
            return self
        b0 = b.limit(x,0)
        if b0 is S.Zero or b0.is_unbounded:
            lt = b.as_leading_term(x)
            o = order * lt**(1-e)
            bs = b.nseries(x, x0, n-e)
            if bs.is_Add:
                bs = bs.removeO()
            if bs.is_Add:
                # bs -> lt + rest -> lt * (1 + (bs/lt - 1))
                return (lt**e * ((bs/lt).expand()**e).nseries(x,
                        x0, n-e)).expand() + order

            return bs**e+order
        o2 = order * (b0**-e)
        # b -> b0 + (b-b0) -> b0 * (1 + (b/b0-1))
        z = (b/b0-1)
        #r = self._compute_oseries3(z, o2, self.taylor_term)
        x = o2.symbols[0]
        ln = C.log
        o = C.Order(z, x)
        if o is S.Zero:
            r = (1+z)
        else:
            if o.expr.is_number:
                e2 = ln(o2.expr*x)/ln(x)
            else:
                e2 = ln(o2.expr)/ln(o.expr)
            n = e2.limit(x,0) + 1
            if n.is_unbounded:
                # requested accuracy gives infinite series,
                # order is probably nonpolynomial e.g. O(exp(-1/x), x).
                r = (1+z)
            else:
                try:
                    n = int(n)
                except TypeError:
                    #well, the n is something more complicated (like 1+log(2))
                    n = int(n.evalf()) + 1
                assert n>=0,`n`
                l = []
                g = None
                for i in xrange(n+2):
                    g = self.taylor_term(i, z, g)
                    g = g.nseries(x, x0, n)
                    l.append(g)
                r = Add(*l)
        return r * b0**e + order
Beispiel #17
0
 def count_ops(self, symbolic=True):
     if symbolic:
         return Add(*[t.count_ops(symbolic) for t in self.args]) + Symbol('POW')
     return Add(*[t.count_ops(symbolic) for t in self.args]) + 1
Beispiel #18
0
from add import Add
from subtract import Subtract
from multiple import Multiple
from divide import Divide

operation1 = Add()
operation2 = Subtract(operation1)
operation3 = Divide(operation2)
operation4 = Multiple(operation3)

print(operation4.handle_request("2 + 3"))
Beispiel #19
0
 def __sub__(self, other):
     return Add(self, -other)
Beispiel #20
0
    def flatten(cls, seq):
        """Return commutative, noncommutative and order arguments by
        combining related terms.

        ** Developer Notes **
            * In an expression like ``a*b*c``, python process this through sympy
              as ``Mul(Mul(a, b), c)``. This can have undesirable consequences.

              -  Sometimes terms are not combined as one would like:
                 {c.f. http://code.google.com/p/sympy/issues/detail?id=1497}

                >>> from sympy import Mul, sqrt
                >>> from sympy.abc import x, y, z
                >>> 2*(x + 1) # this is the 2-arg Mul behavior
                2*x + 2
                >>> y*(x + 1)*2
                2*y*(x + 1)
                >>> 2*(x + 1)*y # 2-arg result will be obtained first
                y*(2*x + 2)
                >>> Mul(2, x + 1, y) # all 3 args simultaneously processed
                2*y*(x + 1)
                >>> 2*((x + 1)*y) # parentheses can control this behavior
                2*y*(x + 1)

                Powers with compound bases may not find a single base to
                combine with unless all arguments are processed at once.
                Post-processing may be necessary in such cases.
                {c.f. http://code.google.com/p/sympy/issues/detail?id=2629}

                >>> a = sqrt(x*sqrt(y))
                >>> a**3
                (x*sqrt(y))**(3/2)
                >>> Mul(a,a,a)
                (x*sqrt(y))**(3/2)
                >>> a*a*a
                x*sqrt(y)*sqrt(x*sqrt(y))
                >>> _.subs(a.base, z).subs(z, a.base)
                (x*sqrt(y))**(3/2)

              -  If more than two terms are being multiplied then all the
                 previous terms will be re-processed for each new argument.
                 So if each of ``a``, ``b`` and ``c`` were :class:`Mul`
                 expression, then ``a*b*c`` (or building up the product
                 with ``*=``) will process all the arguments of ``a`` and
                 ``b`` twice: once when ``a*b`` is computed and again when
                 ``c`` is multiplied.

                 Using ``Mul(a, b, c)`` will process all arguments once.

            * The results of Mul are cached according to arguments, so flatten
              will only be called once for ``Mul(a, b, c)``. If you can
              structure a calculation so the arguments are most likely to be
              repeats then this can save time in computing the answer. For
              example, say you had a Mul, M, that you wished to divide by ``d[i]``
              and multiply by ``n[i]`` and you suspect there are many repeats
              in ``n``. It would be better to compute ``M*n[i]/d[i]`` rather
              than ``M/d[i]*n[i]`` since every time n[i] is a repeat, the
              product, ``M*n[i]`` will be returned without flattening -- the
              cached value will be returned. If you divide by the ``d[i]``
              first (and those are more unique than the ``n[i]``) then that will
              create a new Mul, ``M/d[i]`` the args of which will be traversed
              again when it is multiplied by ``n[i]``.

              {c.f. http://code.google.com/p/sympy/issues/detail?id=2607}

              This consideration is moot if the cache is turned off.

            NB
              The validity of the above notes depends on the implementation
              details of Mul and flatten which may change at any time. Therefore,
              you should only consider them when your code is highly performance
              sensitive.

        """
        rv = None
        if len(seq) == 2:
            a, b = seq
            if b.is_Rational:
                a, b = b, a
            assert not a is S.One
            if a and a.is_Rational:
                r, b = b.as_coeff_Mul()
                a *= r
                if b.is_Mul:
                    bargs, nc = b.args_cnc()
                    rv = bargs, nc, None
                    if a is not S.One:
                        bargs.insert(0, a)

                elif b.is_Add and b.is_commutative:
                    if a is S.One:
                        rv = [b], [], None
                    else:
                        r, b = b.as_coeff_Add()
                        bargs = [_keep_coeff(a, bi) for bi in Add.make_args(b)]
                        bargs.sort(key=hash)
                        ar = a*r
                        if ar:
                            bargs.insert(0, ar)
                        bargs = [Add._from_args(bargs)]
                        rv = bargs, [], None
            if rv:
                return rv

        # apply associativity, separate commutative part of seq
        c_part = []         # out: commutative factors
        nc_part = []        # out: non-commutative factors

        nc_seq = []

        coeff = S.One       # standalone term
                            # e.g. 3 * ...

        c_powers = []       # (base,exp)      n
                            # e.g. (x,n) for x

        num_exp = []        # (num-base, exp)           y
                            # e.g.  (3, y)  for  ... * 3  * ...

        neg1e = 0           # exponent on -1 extracted from Number-based Pow

        pnum_rat = {}       # (num-base, Rat-exp)          1/2
                            # e.g.  (3, 1/2)  for  ... * 3     * ...

        order_symbols = None



        # --- PART 1 ---
        #
        # "collect powers and coeff":
        #
        # o coeff
        # o c_powers
        # o num_exp
        # o neg1e
        # o pnum_rat
        #
        # NOTE: this is optimized for all-objects-are-commutative case

        for o in seq:
            # O(x)
            if o.is_Order:
                o, order_symbols = o.as_expr_variables(order_symbols)

            # Mul([...])
            if o.is_Mul:
                if o.is_commutative:
                    seq.extend(o.args)    # XXX zerocopy?

                else:
                    # NCMul can have commutative parts as well
                    for q in o.args:
                        if q.is_commutative:
                            seq.append(q)
                        else:
                            nc_seq.append(q)

                    # append non-commutative marker, so we don't forget to
                    # process scheduled non-commutative objects
                    seq.append(NC_Marker)

                continue

            # 3
            elif o.is_Number:
                if o is S.NaN or coeff is S.ComplexInfinity and o is S.Zero:
                    # we know for sure the result will be nan
                    return [S.NaN], [], None
                elif coeff.is_Number: # it could be zoo
                    coeff *= o
                    if coeff is S.NaN:
                        # we know for sure the result will be nan
                        return [S.NaN], [], None
                continue

            elif o is S.ComplexInfinity:
                if not coeff or coeff is S.ComplexInfinity:
                    # we know for sure the result will be nan
                    return [S.NaN], [], None
                coeff = S.ComplexInfinity
                continue

            elif o.is_commutative:
                #      e
                # o = b
                b, e = o.as_base_exp()

                #  y
                # 3
                if o.is_Pow and b.is_Number:

                    # get all the factors with numeric base so they can be
                    # combined below, but don't combine negatives unless
                    # the exponent is an integer
                    if e.is_Rational:
                        if e.is_Integer:
                            coeff *= Pow(b, e) # it is an unevaluated power
                            continue
                        elif e.is_negative:    # also a sign of an unevaluated power
                            seq.append(Pow(b, e))
                            continue
                        elif b.is_negative:
                            neg1e += e
                            b = -b
                        if b is not S.One:
                            pnum_rat.setdefault(b, []).append(e)
                        continue
                    elif b.is_positive or e.is_integer:
                        num_exp.append((b, e))
                        continue
                c_powers.append((b,e))

            # NON-COMMUTATIVE
            # TODO: Make non-commutative exponents not combine automatically
            else:
                if o is not NC_Marker:
                    nc_seq.append(o)

                # process nc_seq (if any)
                while nc_seq:
                    o = nc_seq.pop(0)
                    if not nc_part:
                        nc_part.append(o)
                        continue

                    #                             b    c       b+c
                    # try to combine last terms: a  * a   ->  a
                    o1 = nc_part.pop()
                    b1,e1 = o1.as_base_exp()
                    b2,e2 = o.as_base_exp()
                    new_exp = e1 + e2
                    # Only allow powers to combine if the new exponent is
                    # not an Add. This allow things like a**2*b**3 == a**5
                    # if a.is_commutative == False, but prohibits
                    # a**x*a**y and x**a*x**b from combining (x,y commute).
                    if b1==b2 and (not new_exp.is_Add):
                        o12 = b1 ** new_exp

                        # now o12 could be a commutative object
                        if o12.is_commutative:
                            seq.append(o12)
                            continue
                        else:
                            nc_seq.insert(0, o12)

                    else:
                        nc_part.append(o1)
                        nc_part.append(o)

        # We do want a combined exponent if it would not be an Add, such as
        #  y    2y     3y
        # x  * x   -> x
        # We determine this if two exponents have the same term in as_coeff_mul
        #
        # Unfortunately, this isn't smart enough to consider combining into
        # exponents that might already be adds, so things like:
        #  z - y    y
        # x      * x  will be left alone.  This is because checking every possible
        # combination can slow things down.

        # gather exponents of common bases...
        # in c_powers
        new_c_powers = []
        common_b = {} # b:e
        for b, e in c_powers:
            co = e.as_coeff_mul()
            common_b.setdefault(b, {}).setdefault(co[1], []).append(co[0])
        for b, d in common_b.items():
            for di, li in d.items():
                d[di] = Add(*li)
        for b, e in common_b.items():
            for t, c in e.items():
                new_c_powers.append((b, c*Mul(*t)))
        c_powers = new_c_powers

        # and in num_exp
        new_num_exp = []
        common_b = {} # b:e
        for b, e in num_exp:
            co = e.as_coeff_mul()
            common_b.setdefault(b, {}).setdefault(co[1], []).append(co[0])
        for b, d in common_b.items():
            for di, li in d.items():
                d[di] = Add(*li)
        for b, e in common_b.items():
            for t, c in e.items():
                new_num_exp.append((b,c*Mul(*t)))
        num_exp = new_num_exp

        # --- PART 2 ---
        #
        # o process collected powers  (x**0 -> 1; x**1 -> x; otherwise Pow)
        # o combine collected powers  (2**x * 3**x -> 6**x)
        #   with numeric base

        # ................................
        # now we have:
        # - coeff:
        # - c_powers:    (b, e)
        # - num_exp:     (2, e)
        # - pnum_rat:    {(1/3, [1/3, 2/3, 1/4])}

        #  0             1
        # x  -> 1       x  -> x
        for b, e in c_powers:
            if e is S.One:
                if b.is_Number:
                    coeff *= b
                else:
                    c_part.append(b)
            elif e is not S.Zero:
                c_part.append(Pow(b, e))

        #  x    x     x
        # 2  * 3  -> 6
        inv_exp_dict = {}   # exp:Mul(num-bases)     x    x
                            # e.g.  x:6  for  ... * 2  * 3  * ...
        for b, e in num_exp:
            inv_exp_dict.setdefault(e, []).append(b)
        for e, b in inv_exp_dict.items():
            inv_exp_dict[e] = Mul(*b)
        c_part.extend([Pow(b, e) for e, b in inv_exp_dict.iteritems() if e])

        # b, e -> e' = sum(e), b
        # {(1/5, [1/3]), (1/2, [1/12, 1/4]} -> {(1/3, [1/5, 1/2])}
        comb_e = {}
        for b, e in pnum_rat.iteritems():
            comb_e.setdefault(Add(*e), []).append(b)
        del pnum_rat
        # process them, reducing exponents to values less than 1
        # and updating coeff if necessary else adding them to
        # num_rat for further processing
        num_rat = []
        for e, b in comb_e.iteritems():
            b = Mul(*b)
            if e.q == 1:
                coeff *= Pow(b, e)
                continue
            if e.p > e.q:
                e_i, ep = divmod(e.p, e.q)
                coeff *= Pow(b, e_i)
                e = Rational(ep, e.q)
            num_rat.append((b, e))
        del comb_e

        # extract gcd of bases in num_rat
        # 2**(1/3)*6**(1/4) -> 2**(1/3+1/4)*3**(1/4)
        pnew = {}
        i = 0 # steps through num_rat which may grow
        while i < len(num_rat):
            bi, ei = num_rat[i]
            grow = []
            for j in range(i + 1, len(num_rat)):
                bj, ej = num_rat[j]
                g = igcd(bi, bj)
                if g != 1:
                    # 4**r1*6**r2 -> 2**(r1+r2)  *  2**r1 *  3**r2
                    # this might have a gcd with something else
                    e = ei + ej
                    if e.q == 1:
                        coeff *= Pow(g, e)
                    else:
                        if e.p > e.q:
                            e_i, ep = divmod(e.p, e.q) # change e in place
                            coeff *= Pow(g, e_i)
                            e = Rational(ep, e.q)
                        grow.append((g, e))
                    # update the jth item
                    num_rat[j] = (bj//g, ej)
                    # update bi that we are checking with
                    bi = bi//g
                    if bi is S.One:
                        break
            if bi is not S.One:
                obj = Pow(bi, ei)
                if obj.is_Number:
                    coeff *= obj
                else:
                    if obj.is_Mul: # sqrt(12) -> 2*sqrt(3)
                        c, obj = obj.args # expecting only 2 args
                        coeff *= c
                        assert obj.is_Pow
                        bi, ei = obj.args
                    pnew.setdefault(ei, []).append(bi)

            num_rat.extend(grow)
            i += 1

        # combine bases of the new powers
        for e, b in pnew.iteritems():
            pnew[e] = Mul(*b)

        # see if there is a base with matching coefficient
        # that the -1 can be joined with
        if neg1e:
            p = Pow(S.NegativeOne, neg1e)
            if p.is_Number:
                coeff *= p
            else:
                if p.is_Mul:
                    c, p = p.args
                    coeff *= c
                    assert p.is_Pow and p.base is S.NegativeOne
                    neg1e = p.args[1]
                for e, b in pnew.iteritems():
                    if e == neg1e and b.is_positive:
                        pnew[e] = -b
                        break
                else:
                    c_part.append(p)

        # add all the pnew powers
        c_part.extend([Pow(b, e) for e, b in pnew.iteritems()])

        # oo, -oo
        if (coeff is S.Infinity) or (coeff is S.NegativeInfinity):
            new_c_part = []
            coeff_sign = 1
            for t in c_part:
                if t.is_positive:
                    continue
                if t.is_negative:
                    coeff_sign *= -1
                    continue
                new_c_part.append(t)
            c_part = new_c_part
            new_nc_part = []
            for t in nc_part:
                if t.is_positive:
                    continue
                if t.is_negative:
                    coeff_sign *= -1
                    continue
                new_nc_part.append(t)
            nc_part = new_nc_part
            coeff *= coeff_sign

        # zoo
        if coeff is S.ComplexInfinity:
            # zoo might be
            #   unbounded_real + bounded_im
            #   bounded_real + unbounded_im
            #   unbounded_real + unbounded_im
            # and non-zero real or imaginary will not change that status.
            c_part = [c for c in c_part if not (c.is_nonzero and
                                                c.is_real is not None)]
            nc_part = [c for c in nc_part if not (c.is_nonzero and
                                                  c.is_real is not None)]

        # 0
        elif coeff is S.Zero:
            # we know for sure the result will be 0
            return [coeff], [], order_symbols

        # order commutative part canonically
        c_part.sort(key=cls._args_sortkey)

        # current code expects coeff to be always in slot-0
        if coeff is not S.One:
            c_part.insert(0, coeff)


        # we are done
        if len(c_part)==2 and c_part[0].is_Number and c_part[1].is_Add:
            # 2*(1+a) -> 2 + 2 * a
            coeff = c_part[0]
            c_part = [Add(*[coeff*f for f in c_part[1].args])]

        return c_part, nc_part, order_symbols
Beispiel #21
0
 def __rsub__(self, other):
     return Add(other, -self)
Beispiel #22
0
    def _eval_nseries(self, x, n):
        from sympy import powsimp, collect, exp, log, O, ceiling

        b, e = self.args
        if e.is_Integer:
            if e > 0:
                # positive integer powers are easy to expand, e.g.:
                # sin(x)**4 = (x-x**3/3+...)**4 = ...
                return Pow(b._eval_nseries(x, n=n),
                           e)._eval_expand_multinomial(deep=False)
            elif e is S.NegativeOne:
                # this is also easy to expand using the formula:
                # 1/(1 + x) = 1 + x + x**2 + x**3 ...
                # so we need to rewrite base to the form "1+x"
                if b.has(log(x)):
                    # we need to handle the log(x) singularity:
                    y = Dummy("y")
                    p = self.subs(log(x), -1 / y)
                    if not p.has(x):
                        p = p._eval_nseries(y, n=n)
                        p = p.subs(y, -1 / log(x))
                        return p

                b = b._eval_nseries(x, n=n)
                if b.has(log(x)):
                    # we need to handle the log(x) singularity:
                    y = Dummy("y")
                    self0 = 1 / b
                    p = self0.subs(log(x), -1 / y)
                    if not p.has(x):
                        p = p._eval_nseries(y, n=n)
                        p = p.subs(y, -1 / log(x))
                        return p
                prefactor = b.as_leading_term(x)
                # express "rest" as: rest = 1 + k*x**l + ... + O(x**n)
                rest = ((b - prefactor) / prefactor)._eval_expand_mul()
                if rest == 0:
                    # if prefactor == w**4 + x**2*w**4 + 2*x*w**4, we need to
                    # factor the w**4 out using collect:
                    return 1 / collect(prefactor, x)
                if rest.is_Order:
                    return (1 + rest) / prefactor
                n2 = rest.getn()
                if n2 is not None:
                    n = n2

                term2 = collect(rest.as_leading_term(x), x)
                k, l = C.Wild("k"), C.Wild("l")
                r = term2.match(k * x**l)
                # if term2 is NaN then r will not contain l
                k = r.get(k, S.One)
                l = r.get(l, S.Zero)
                if l.is_Rational and l > 0:
                    pass
                elif l.is_number and l > 0:
                    l = l.evalf()
                else:
                    raise NotImplementedError()

                terms = [1 / prefactor]
                for m in xrange(1, ceiling(n / l)):
                    new_term = terms[-1] * (-rest)
                    if new_term.is_Pow:
                        new_term = new_term._eval_expand_multinomial(
                            deep=False)
                    else:
                        new_term = new_term._eval_expand_mul(deep=False)
                    terms.append(new_term)
                if n2 is None:
                    # Append O(...) because it is not included in "r"
                    terms.append(O(x**n))
                return powsimp(Add(*terms), deep=True, combine='exp')
            else:
                # negative powers are rewritten to the cases above, for example:
                # sin(x)**(-4) = 1/( sin(x)**4) = ...
                # and expand the denominator:
                denominator = (b**(-e))._eval_nseries(x, n=n)
                if 1 / denominator == self:
                    return self
                # now we have a type 1/f(x), that we know how to expand
                return (1 / denominator)._eval_nseries(x, n=n)

        if e.has(x):
            return exp(e * log(b))._eval_nseries(x, n=n)

        if b == x:
            return powsimp(self, deep=True, combine='exp')

        # work for b(x)**e where e is not an Integer and does not contain x
        # and hopefully has no other symbols

        def e2int(e):
            """return the integer value (if possible) of e and a
            flag indicating whether it is bounded or not."""
            n = e.limit(x, 0)
            unbounded = n.is_unbounded
            if not unbounded:
                # XXX was int or floor intended? int used to behave like floor
                # so int(-Rational(1, 2)) returned -1 rather than int's 0
                try:
                    n = int(n)
                except TypeError:
                    #well, the n is something more complicated (like 1+log(2))
                    try:
                        n = int(n.evalf()) + 1  # XXX why is 1 being added?
                    except TypeError:
                        pass  # hope that base allows this to be resolved
                n = _sympify(n)
            return n, unbounded

        order = O(x**n, x)
        ei, unbounded = e2int(e)
        b0 = b.limit(x, 0)
        if unbounded and (b0 is S.One or b0.has(Symbol)):
            # XXX what order
            if b0 is S.One:
                resid = (b - 1)
                if resid.is_positive:
                    return S.Infinity
                elif resid.is_negative:
                    return S.Zero
                raise ValueError('cannot determine sign of %s' % resid)

            return b0**ei

        if (b0 is S.Zero or b0.is_unbounded):
            if unbounded is not False:
                return b0**e  # XXX what order

            if not ei.is_number:  # if not, how will we proceed?
                raise ValueError('expecting numerical exponent but got %s' %
                                 ei)

            nuse = n - ei
            lt = b.as_leading_term(x)
            #  XXX o is not used -- was this to be used as o and o2 below to compute a new e?
            o = order * lt**(1 - e)
            bs = b._eval_nseries(x, n=nuse)
            if bs.is_Add:
                bs = bs.removeO()
            if bs.is_Add:
                # bs -> lt + rest -> lt*(1 + (bs/lt - 1))
                return ((Pow(lt, e) * Pow(
                    (bs / lt).expand(), e).nseries(x, n=nuse)).expand() +
                        order)

            return bs**e + order

        # either b0 is bounded but neither 1 nor 0 or e is unbounded
        # b -> b0 + (b-b0) -> b0 * (1 + (b/b0-1))
        o2 = order * (b0**-e)
        z = (b / b0 - 1)
        o = O(z, x)
        #r = self._compute_oseries3(z, o2, self.taylor_term)
        if o is S.Zero or o2 is S.Zero:
            unbounded = True
        else:
            if o.expr.is_number:
                e2 = log(o2.expr * x) / log(x)
            else:
                e2 = log(o2.expr) / log(o.expr)
            n, unbounded = e2int(e2)
        if unbounded:
            # requested accuracy gives infinite series,
            # order is probably nonpolynomial e.g. O(exp(-1/x), x).
            r = 1 + z
        else:
            l = []
            g = None
            for i in xrange(n + 2):
                g = self.taylor_term(i, z, g)
                g = g.nseries(x, n=n)
                l.append(g)
            r = Add(*l)
        return r * b0**e + order
Beispiel #23
0
    def extract_multiplicatively(self, c):
        """Return None if it's not possible to make self in the form
           c * something in a nice way, i.e. preserving the properties
           of arguments of self.

           >>> from sympy import symbols, Rational

           >>> x, y = symbols('xy', real=True)

           >>> ((x*y)**3).extract_multiplicatively(x**2 * y)
           x*y**2

           >>> ((x*y)**3).extract_multiplicatively(x**4 * y)

           >>> (2*x).extract_multiplicatively(2)
           x

           >>> (2*x).extract_multiplicatively(3)

           >>> (Rational(1,2)*x).extract_multiplicatively(3)
           x/6

        """
        c = sympify(c)
        if c is S.One:
            return self
        elif c == self:
            return S.One
        elif c.is_Mul:
            x = self.extract_multiplicatively(c.as_two_terms()[0])
            if x != None:
                return x.extract_multiplicatively(c.as_two_terms()[1])
        quotient = self / c
        if self.is_Number:
            if self is S.Infinity:
                if c.is_positive:
                    return S.Infinity
            elif self is S.NegativeInfinity:
                if c.is_negative:
                    return S.Infinity
                elif c.is_positive:
                    return S.NegativeInfinity
            elif self is S.ComplexInfinity:
                if not c.is_zero:
                    return S.ComplexInfinity
            elif self is S.NaN:
                return S.NaN
            elif self.is_Integer:
                if not quotient.is_Integer:
                    return None
                elif self.is_positive and quotient.is_negative:
                    return None
                else:
                    return quotient
            elif self.is_Rational:
                if not quotient.is_Rational:
                    return None
                elif self.is_positive and quotient.is_negative:
                    return None
                else:
                    return quotient
            elif self.is_Real:
                if not quotient.is_Real:
                    return None
                elif self.is_positive and quotient.is_negative:
                    return None
                else:
                    return quotient
        elif self.is_NumberSymbol or self.is_Symbol or self is S.ImaginaryUnit:
            if quotient.is_Mul and len(quotient.args) == 2:
                if quotient.args[0].is_Integer and quotient.args[
                        0].is_positive and quotient.args[1] == self:
                    return quotient
            elif quotient.is_Integer:
                return quotient
        elif self.is_Add:
            newargs = []
            for arg in self.args:
                newarg = arg.extract_multiplicatively(c)
                if newarg != None:
                    newargs.append(newarg)
                else:
                    return None
            return Add(*newargs)
        elif self.is_Mul:
            for i in xrange(len(self.args)):
                newargs = list(self.args)
                del (newargs[i])
                tmp = self._new_rawargs(*newargs).extract_multiplicatively(c)
                if tmp != None:
                    return tmp * self.args[i]
        elif self.is_Pow:
            if c.is_Pow and c.base == self.base:
                new_exp = self.exp.extract_additively(c.exp)
                if new_exp != None:
                    return self.base**(new_exp)
            elif c == self.base:
                new_exp = self.exp.extract_additively(1)
                if new_exp != None:
                    return self.base**(new_exp)
Beispiel #24
0
 def check(l, r):
     if l.is_Float and r.is_comparable:
         return Add(l, 0) == Add(r.evalf(), 0)
     return False
Beispiel #25
0
def test_add():
    assert Add(2, 4) == 6
Beispiel #26
0
    def _eval_expand_multinomial(self, **hints):
        """(a+b+..) ** n -> a**n + n*a**(n-1)*b + .., n is nonzero integer"""

        base, exp = self.args
        result = self

        if exp.is_Rational and exp.p > 0 and base.is_Add:
            if not exp.is_Integer:
                n = Integer(exp.p // exp.q)

                if not n:
                    return result
                else:
                    radical, result = Pow(base, exp - n), []

                    expanded_base_n = Pow(base, n)
                    if expanded_base_n.is_Pow:
                        expanded_base_n = \
                            expanded_base_n._eval_expand_multinomial()
                    for term in Add.make_args(expanded_base_n):
                        result.append(term * radical)

                    return Add(*result)

            n = int(exp)

            if base.is_commutative:
                order_terms, other_terms = [], []

                for b in base.args:
                    if b.is_Order:
                        order_terms.append(b)
                    else:
                        other_terms.append(b)

                if order_terms:
                    # (f(x) + O(x^n))^m -> f(x)^m + m*f(x)^{m-1} *O(x^n)
                    f = Add(*other_terms)
                    o = Add(*order_terms)

                    if n == 2:
                        return expand_multinomial(f**n, deep=False) + n * f * o
                    else:
                        g = expand_multinomial(f**(n - 1), deep=False)
                        return expand_mul(f * g, deep=False) + n * g * o

                if base.is_number:
                    # Efficiently expand expressions of the form (a + b*I)**n
                    # where 'a' and 'b' are real numbers and 'n' is integer.
                    a, b = base.as_real_imag()

                    if a.is_Rational and b.is_Rational:
                        if not a.is_Integer:
                            if not b.is_Integer:
                                k = Pow(a.q * b.q, n)
                                a, b = a.p * b.q, a.q * b.p
                            else:
                                k = Pow(a.q, n)
                                a, b = a.p, a.q * b
                        elif not b.is_Integer:
                            k = Pow(b.q, n)
                            a, b = a * b.q, b.p
                        else:
                            k = 1

                        a, b, c, d = int(a), int(b), 1, 0

                        while n:
                            if n & 1:
                                c, d = a * c - b * d, b * c + a * d
                                n -= 1
                            a, b = a * a - b * b, 2 * a * b
                            n //= 2

                        I = S.ImaginaryUnit

                        if k == 1:
                            return c + I * d
                        else:
                            return Integer(c) / k + I * d / k

                p = other_terms
                # (x+y)**3 -> x**3 + 3*x**2*y + 3*x*y**2 + y**3
                # in this particular example:
                # p = [x,y]; n = 3
                # so now it's easy to get the correct result -- we get the
                # coefficients first:
                from sympy import multinomial_coefficients
                from sympy.polys.polyutils import basic_from_dict
                expansion_dict = multinomial_coefficients(len(p), n)
                # in our example: {(3, 0): 1, (1, 2): 3, (0, 3): 1, (2, 1): 3}
                # and now construct the expression.
                return basic_from_dict(expansion_dict, *p)
            else:
                if n == 2:
                    return Add(*[f * g for f in base.args for g in base.args])
                else:
                    multi = (base**(n - 1))._eval_expand_multinomial()
                    if multi.is_Add:
                        return Add(
                            *[f * g for f in base.args for g in multi.args])
                    else:
                        # XXX can this ever happen if base was an Add?
                        return Add(*[f * multi for f in base.args])
        elif (exp.is_Rational and exp.p < 0 and base.is_Add
              and abs(exp.p) > exp.q):
            return 1 / Pow(base, -exp)._eval_expand_multinomial()
        elif exp.is_Add and base.is_Number:
            #  a + b      a  b
            # n      --> n  n  , where n, a, b are Numbers

            coeff, tail = S.One, S.Zero
            for term in exp.args:
                if term.is_Number:
                    coeff *= Pow(base, term)
                else:
                    tail += term

            return coeff * Pow(base, tail)
        else:
            return result
Beispiel #27
0
from add import Add
import sys

a = sys.argv[1]
b = sys.argv[2]
print("Calling ADD")
print(Add(a, b))
for i in range(1, 1000):
    print(i)
sys.stdout.flush()
Beispiel #28
0
    def _eval_nseries(self, x, n, logx):
        # NOTE! This function is an important part of the gruntz algorithm
        #       for computing limits. It has to return a generalized power
        #       series with coefficients in C(log, log(x)). In more detail:
        # It has to return an expression
        #     c_0*x**e_0 + c_1*x**e_1 + ... (finitely many terms)
        # where e_i are numbers (not necessarily integers) and c_i are
        # expressions involving only numbers, the log function, and log(x).
        from sympy import powsimp, collect, exp, log, O, ceiling
        b, e = self.args
        if e.is_Integer:
            if e > 0:
                # positive integer powers are easy to expand, e.g.:
                # sin(x)**4 = (x-x**3/3+...)**4 = ...
                return expand_multinomial(Pow(
                    b._eval_nseries(x, n=n, logx=logx), e),
                                          deep=False)
            elif e is S.NegativeOne:
                # this is also easy to expand using the formula:
                # 1/(1 + x) = 1 - x + x**2 - x**3 ...
                # so we need to rewrite base to the form "1+x"

                b = b._eval_nseries(x, n=n, logx=logx)
                prefactor = b.as_leading_term(x)
                # express "rest" as: rest = 1 + k*x**l + ... + O(x**n)
                rest = expand_mul((b - prefactor) / prefactor)
                if rest == 0:
                    # if prefactor == w**4 + x**2*w**4 + 2*x*w**4, we need to
                    # factor the w**4 out using collect:
                    return 1 / collect(prefactor, x)
                if rest.is_Order:
                    return 1 / prefactor + rest / prefactor
                n2 = rest.getn()
                if n2 is not None:
                    n = n2
                    # remove the O - powering this is slow
                    if logx is not None:
                        rest = rest.removeO()

                k, l = rest.leadterm(x)
                if l.is_Rational and l > 0:
                    pass
                elif l.is_number and l > 0:
                    l = l.evalf()
                else:
                    raise NotImplementedError()

                terms = [1 / prefactor]
                for m in xrange(1, ceiling(n / l)):
                    new_term = terms[-1] * (-rest)
                    if new_term.is_Pow:
                        new_term = new_term._eval_expand_multinomial(
                            deep=False)
                    else:
                        new_term = expand_mul(new_term, deep=False)
                    terms.append(new_term)

                # Append O(...), we know the order.
                if n2 is None or logx is not None:
                    terms.append(O(x**n))
                return powsimp(Add(*terms), deep=True, combine='exp')
            else:
                # negative powers are rewritten to the cases above, for
                # example:
                # sin(x)**(-4) = 1/( sin(x)**4) = ...
                # and expand the denominator:
                denominator = (b**(-e))._eval_nseries(x, n=n, logx=logx)
                if 1 / denominator == self:
                    return self
                # now we have a type 1/f(x), that we know how to expand
                return (1 / denominator)._eval_nseries(x, n=n, logx=logx)

        if e.has(Symbol):
            return exp(e * log(b))._eval_nseries(x, n=n, logx=logx)

        # see if the base is as simple as possible
        bx = b
        while bx.is_Pow and bx.exp.is_Rational:
            bx = bx.base
        if bx == x:
            return self

        # work for b(x)**e where e is not an Integer and does not contain x
        # and hopefully has no other symbols

        def e2int(e):
            """return the integer value (if possible) of e and a
            flag indicating whether it is bounded or not."""
            n = e.limit(x, 0)
            unbounded = n.is_unbounded
            if not unbounded:
                # XXX was int or floor intended? int used to behave like floor
                # so int(-Rational(1, 2)) returned -1 rather than int's 0
                try:
                    n = int(n)
                except TypeError:
                    #well, the n is something more complicated (like 1+log(2))
                    try:
                        n = int(n.evalf()) + 1  # XXX why is 1 being added?
                    except TypeError:
                        pass  # hope that base allows this to be resolved
                n = _sympify(n)
            return n, unbounded

        order = O(x**n, x)
        ei, unbounded = e2int(e)
        b0 = b.limit(x, 0)
        if unbounded and (b0 is S.One or b0.has(Symbol)):
            # XXX what order
            if b0 is S.One:
                resid = (b - 1)
                if resid.is_positive:
                    return S.Infinity
                elif resid.is_negative:
                    return S.Zero
                raise ValueError('cannot determine sign of %s' % resid)

            return b0**ei

        if (b0 is S.Zero or b0.is_unbounded):
            if unbounded is not False:
                return b0**e  # XXX what order

            if not ei.is_number:  # if not, how will we proceed?
                raise ValueError('expecting numerical exponent but got %s' %
                                 ei)

            nuse = n - ei

            if e.is_real and e.is_positive:
                lt = b.as_leading_term(x)

                # Try to correct nuse (= m) guess from:
                # (lt + rest + O(x**m))**e =
                # lt**e*(1 + rest/lt + O(x**m)/lt)**e =
                # lt**e + ... + O(x**m)*lt**(e - 1) = ... + O(x**n)
                try:
                    cf = C.Order(lt, x).getn()
                    nuse = ceiling(n - cf * (e - 1))
                except NotImplementedError:
                    pass

            bs = b._eval_nseries(x, n=nuse, logx=logx)
            terms = bs.removeO()
            if terms.is_Add:
                bs = terms
                lt = terms.as_leading_term(x)

                # bs -> lt + rest -> lt*(1 + (bs/lt - 1))
                return ((Pow(lt, e) * Pow((bs / lt).expand(), e).nseries(
                    x, n=nuse, logx=logx)).expand() + order)

            if bs.is_Add:
                from sympy import O
                # So, bs + O() == terms
                c = Dummy('c')
                res = []
                for arg in bs.args:
                    if arg.is_Order:
                        arg = c * arg.expr
                    res.append(arg)
                bs = Add(*res)
                rv = (bs**e).series(x).subs(c, O(1))
                rv += order
                return rv

            rv = bs**e
            if terms != bs:
                rv += order
            return rv

        # either b0 is bounded but neither 1 nor 0 or e is unbounded
        # b -> b0 + (b-b0) -> b0 * (1 + (b/b0-1))
        o2 = order * (b0**-e)
        z = (b / b0 - 1)
        o = O(z, x)
        #r = self._compute_oseries3(z, o2, self.taylor_term)
        if o is S.Zero or o2 is S.Zero:
            unbounded = True
        else:
            if o.expr.is_number:
                e2 = log(o2.expr * x) / log(x)
            else:
                e2 = log(o2.expr) / log(o.expr)
            n, unbounded = e2int(e2)
        if unbounded:
            # requested accuracy gives infinite series,
            # order is probably non-polynomial e.g. O(exp(-1/x), x).
            r = 1 + z
        else:
            l = []
            g = None
            for i in xrange(n + 2):
                g = self.taylor_term(i, z, g)
                g = g.nseries(x, n=n, logx=logx)
                l.append(g)
            r = Add(*l)
        return r * b0**e + order
Beispiel #29
0
class MIPSSimulator():
	'''Main class for MIPS pipeline simulator.

	Provides the main method tick(), which runs pipeline

	for one clock cycle.
	'''
	def __init__(self, memoryFile):
		self.nCycles = 0 # Used to hold number of clock cycles spent executing instructions

		# Fetch
		self.PCMux	  = Mux()
		self.ProgramC   = PC(long(0xbfc00200))
		self.InstMem	= InstructionMemory(memoryFile)
		self.IFadder	= Add()
		self.JMux	   = Mux()
		self.IFaddconst = Constant(4)
		self.IF_ID_Wall = Wall()
		self.fetchgroup = {}

		# Decode
		self.register   = RegisterFile()
		self.signext	= SignExtender()
		self.control	= ControlElement()
		self.jmpCalc	= JumpCalc()
		self.ID_EX_Wall = Wall()

		# Execute
		self.EXadder	= Add()
		self.shiftL	 = LeftShifter()
		self.ALogicUnit = ALU()
		self.ALUSrcMux  = Mux()
		self.RegDstMux  = Mux()
		self.ALUctrl	= AluControl()
		self.EX_MEM_Wall= Wall()

		# Memory
		self.storage	= DataMemory(memoryFile)
		self.brnch	  = Branch()
		self.MEM_WB_Wall= Wall()

		# Write Back
		self.WBmux = Mux()

		self.ProgramC
		self.elements1 = [self.InstMem, self.IFaddconst, self.IFadder, self.PCMux, self.JMux]
		self.elements2 = [self.control, self.register, self.signext, self.jmpCalc]
		self.elements3 = [self.shiftL, self.ALUSrcMux, self.RegDstMux, self.ALUctrl, self.ALogicUnit, self.EXadder]
		self.elements4 = [self.brnch, self.storage]
		self.elementsboot = [self.IFaddconst, self.IFadder, self.InstMem,
							 self.IF_ID_Wall, self.register, self.signext, self.control, self.jmpCalc,
							 self.ID_EX_Wall, self.RegDstMux, self.shiftL, self.EXadder, self.ALUSrcMux, self.ALUctrl, self.ALogicUnit,
							 self.EX_MEM_Wall, self.brnch, self.storage,
							 self.MEM_WB_Wall, self.WBmux, self.PCMux, self.JMux]
		self.walls = [self.MEM_WB_Wall, self.EX_MEM_Wall, self.ID_EX_Wall, self.IF_ID_Wall]


		self._connectCPUElements()

	def _connectCPUElements(self):
		# IF
		self.PCMux.connect(
			[(self.IFadder, "adderout"), (self.EX_MEM_Wall, "adderoutput")],
			["PCmuxoutput"],
			[(self.brnch, "PCSrc")],
			[]
		)

		self.JMux.connect(
			[(self.PCMux, "PCmuxoutput"), (self.jmpCalc, "output")],
			["output"],
			[(self.control, "Jump")],
			[]
		)

		self.IFaddconst.connect(
			[],
			['constant'],
			[],
			[]
		)

		self.ProgramC.connect(
			[(self.JMux, "output")],
			["output"],
			[],
			[]
		)

		self.InstMem.connect(
			[(self.ProgramC, "output")],
			["opcode", "rs", "rt", "rd", "shamt", "funct", "imm", "addr"],
			[],
			[]
		)

		self.IFadder.connect(
			[(self.ProgramC, "output"), (self.IFaddconst, "constant")],
			["adderout"],
			[],
			[]
		)

		self.IF_ID_Wall.connect(
			[(self.InstMem, "opcode"),(self.InstMem, "rs"),
			(self.InstMem, "rt"),(self.InstMem, "rd"),
			(self.InstMem, "shamt"), (self.InstMem, "funct"),
			(self.InstMem, "imm"), (self.InstMem, "addr"),
			(self.IFadder, "adderout")],
			["opcode", "rs", "rt", "rd",
			 "shamt", "funct", "imm", "addr",
			 "adderout"],
			[],
			[]
		)
		# IF
		# ID
		self.register.connect(
			[(self.IF_ID_Wall, "rs"), (self.IF_ID_Wall, "rt"),
			 (self.MEM_WB_Wall, "regdstoutput"), (self.WBmux, "output")],
			["Reg1", "Reg2"],
			[(self.MEM_WB_Wall, "RegWrite")],
			[]
		)

		self.signext.connect(
			[(self.IF_ID_Wall, "imm")],
			["extended"],
			[],
			[]
		)

		self.control.connect(
			[(self.IF_ID_Wall, "opcode")],
			[],
			[],
			["RegDst", "RegWrite", "ALUSrc", "MemtoReg",
			 "MemWrite", "MemRead", "Branch", "ALUOp", "Jump"]
		)

		self.jmpCalc.connect(
			[(self.IF_ID_Wall, "addr"), (self.IF_ID_Wall, "adderout")],
			["output"],
			[],
			[]
		)

		self.ID_EX_Wall.connect(
			[(self.register, "Reg1"), (self.register, "Reg2"),
			(self.signext, "extended"), (self.jmpCalc, "output"),
			(self.IF_ID_Wall, "adderout"), (self.IF_ID_Wall, "funct"),
			(self.IF_ID_Wall, "rd"), (self.IF_ID_Wall, "addr"),
			(self.IF_ID_Wall, "rt")],
			["Reg1", "Reg2", "extended", "output",
			 "adderout", "funct", "rd", "addr", "rt"],
			[(self.control, "RegDst"), (self.control, "RegWrite"),
			(self.control, "ALUSrc"), (self.control, "MemtoReg"),
			(self.control, "MemWrite"), (self.control, "MemRead"),
			(self.control, "Branch"), (self.control, "ALUOp"),
			(self.control, "Jump")],
			["RegDst", "RegWrite", "ALUSrc", "MemtoReg",
			 "MemWrite", "MemRead", "Branch", "ALUOp", "Jump"]
		)
		#ID
		#EX

		self.EXadder.connect(
			[(self.ID_EX_Wall, "adderout"), (self.shiftL, "shifted")],
			["output"],
			[],
			[]
		)

		self.shiftL.connect(
			[(self.ID_EX_Wall, "extended")],
			["shifted"],
			[],
			[]
		)

		self.ALogicUnit.connect(
			[(self.ID_EX_Wall, "Reg1"), (self.ALUSrcMux, "output")],
			["result"],
			[(self.ALUctrl, "ALUctrlsig")],
			["zero"]
		)

		self.ALUSrcMux.connect(
			[(self.ID_EX_Wall, "Reg2"), (self.ID_EX_Wall, "extended")],
			["output"],
			[(self.ID_EX_Wall, "ALUSrc")],
			[]
		)

		self.RegDstMux.connect(
			[(self.ID_EX_Wall, "rt"), (self.ID_EX_Wall, "rd")],
			["RegDstoutput"],
			[(self.ID_EX_Wall, "RegDst")],
			[]
		)

		self.ALUctrl.connect(
			[(self.ID_EX_Wall, "funct")],
			[],
			[(self.ID_EX_Wall, "ALUOp")],
			["ALUctrlsig"]
		)

		self.EX_MEM_Wall.connect(
			[(self.EXadder, "output"), (self.ALogicUnit, "result"),
			 (self.ID_EX_Wall, "rt"), (self.RegDstMux, "RegDstoutput")],
			["adderoutput", "result", "rt", "regdstoutput"],
			[(self.ID_EX_Wall, "RegWrite"), (self.ID_EX_Wall, "MemtoReg"),
			 (self.ID_EX_Wall, "MemWrite"), (self.ID_EX_Wall, "MemRead"),
			 (self.ID_EX_Wall, "Branch"), (self.ALogicUnit, "zero")],
			["RegWrite", "MemtoReg", "MemWrite", "MemRead", "Branch", "zero"]
		)
		#EX
		#MEM

		self.storage.connect(
			[(self.EX_MEM_Wall, "result"), (self.EX_MEM_Wall, "rt")],
			["data"],
			[(self.EX_MEM_Wall, "MemWrite"), (self.EX_MEM_Wall, "MemRead")],
			[]
		)

		self.brnch.connect(
			[],
			[],
			[(self.EX_MEM_Wall, "Branch"), (self.EX_MEM_Wall, "zero")],
			["PCSrc"]
		)


		self.MEM_WB_Wall.connect(
			[(self.EX_MEM_Wall, "adderoutput"), (self.storage, "data"),
			 (self.EX_MEM_Wall, "regdstoutput")],
			["adderoutput", "data", "regdstoutput"],
			[(self.EX_MEM_Wall, "RegWrite"), (self.EX_MEM_Wall, "MemtoReg")],
			["RegWrite", "MemtoReg"]
		)
		#MEM
		#WB
		self.WBmux.connect(
			[(self.MEM_WB_Wall, "adderoutput"), (self.MEM_WB_Wall, "data")],
			["output"],
			[(self.MEM_WB_Wall, "MemtoReg")],
			[]
		)

	def clockCycles(self):
		'''Returns the number of clock cycles spent executing instructions.'''

		return self.nCycles

	def dataMemory(self):
		'''Returns dictionary, mapping memory addresses to data, holding
		data memory after instructions have finished executing.'''

		return self.dataMemory.memory

	def registerFile(self):
		'''Returns dictionary, mapping register numbers to data, holding
		register file after instructions have finished executing.'''

		return self.registerFile.register

	def printDataMemory(self):
		self.dataMemory.printAll()

	def printRegisterFile(self):
		self.registerFile.printAll()

	def bootup(self):
		self.ProgramC.writeOutput()

		for elem in self.elementsboot:
			elem.readControlSignals()
			elem.readInput()
			elem.writeOutput()
			elem.setControlSignals()

		self.ProgramC.readInput()


	def tick(self):
		'''Execute one clock cycle of pipeline.'''

		self.nCycles += 1
		

		self.ProgramC.writeOutput()

		for elem in self.walls:
			elem.writeOutput()
			elem.setControlSignals()

		self.WBmux.readControlSignals()
		self.WBmux.readInput()
		self.WBmux.writeOutput()
		self.WBmux.setControlSignals()

		for elem in self.elements4:
			elem.readControlSignals()
			elem.readInput()
			elem.writeOutput()
			elem.setControlSignals()

		for elem in self.elements3:
			elem.readControlSignals()
			elem.readInput()
			elem.writeOutput()
			elem.setControlSignals()

		for elem in self.elements2:
			elem.readControlSignals()
			elem.readInput()
			elem.writeOutput()
			elem.setControlSignals()

		for elem in self.elements1:
			elem.readControlSignals()
			elem.readInput()
			elem.writeOutput()
			elem.setControlSignals()

		for elem in self.walls:
			elem.readControlSignals()
			elem.readInput()

		self.register.printAll()
		self.ProgramC.readInput()
		print "number of cycles", self.nCycles, "\n"
Beispiel #30
0
def init(argv):
  opts, methods = getopt(argv, 'hl:r:vm:s:a:fi:NP:ducS', ['help', 'lang=', 'reference=', 'version' ,'main=', 'skeleton=', 'add=', 'cout', 'force', 'include=', 'prefix=', 'downcase', 'uppercase', 'camel', 'snake'])
  xunit = load()
  includes = []
  prefix = 1
  force = 0
  cout = 0
  add = None
  skeleton = None
  main = None
  lang = None
  downcase = None
  snake = None
  for opt, value in opts:
    if '-h' == opt or '--help' == opt:
      usage()
      sys.exit(0)
    elif '-v' == opt or '--version' == opt:
      version()
      for lang in xunit.lang.items():
        print '  ' + lang[1].version + '(--lang ' + lang[0] + ')'
      sys.exit(0)
    elif '-r' == opt or '--reference' == opt:
      try:
        print xunit.lang[value].reference
      except KeyError:
        sys.stderr.write('Un Support Language:%s' % value)
        sys.exit(1)
    elif '-l' == opt or '--lang' == opt:
      try:
        lang = xunit.lang[value]
      except KeyError:
        sys.stderr.write('Un Support Language:%s' % value)
        sys.exit(1)
    elif '-m' == opt or '--main' == opt:
      main = value
    elif '-s' == opt or '--skeleton' == opt:
      skeleton = value
    elif '-a' == opt or '--add' == opt:
      add = value
      force = 1
    elif '-P' == opt or '--prefix' == opt:
      if value == '+':
        prefix = 1
      elif value == '-':
        prefix = 0
      else:
        raise ValueError, "prefix option can accept only '+' or '-'"
    elif '-f' == opt or '--force' == opt:
      force = 1
    elif '-d' == opt or '--downcase' == opt:
      downcase = 1
    elif '-u' == opt or '--uppercase' == opt:
      downcase = 0
    elif '-S' == opt or '--snake' == opt:
      snake = 1
    elif '-c' == opt or '--camel' == opt:
      snake = 0
    elif '--cout' == opt:
      cout = 1
    elif '-i' == opt or '--include' == opt:
      includes.append(value)
  if add is not None:
    add = Add(add, language(xunit, lang, add), methods, includes)
    add.create()
    output(add.filename, add.result, force, cout)
  else:
    if skeleton is not None:
      skeleton = Skeleton(skeleton, methods, includes, prefix, 
        language(xunit, lang, skeleton))
      skeleton.create()
      output(skeleton.filename, skeleton.result, force, cout)
    if main is not None:
      main = Main(main, language(xunit, lang, main))
      main.create()
      output(main.filename, main.result, force, cout)
Beispiel #31
0
 def count_ops(self, symbolic=True):
     #      f()             args
     return 1 + Add(*[t.count_ops(symbolic) for t in self.args])
Beispiel #32
0
        from handinserting import *

        hi = HandInserting()
        hi.insert_terms()
    elif ec == "4":
        from handinserting import *

        tables = []
        hi = HandInserting()
        hi.insert_phrases()
    elif ec == "5":
        from testing import *

        tph = TestPhrases()
        tph.start(["all_phrases"])
    elif ec == "6":
        from add import Add

        ad = Add()
        ad.add_term()
    elif ec == "7":
        from delete import Delete

        delete = Delete()
        delete.del_term()
    elif ec == "8":
        from change import Change

        ch = Change()
        ch.change_term()
from flask.views import MethodView
from home import Home
from index import Index
from add import Add
from remove import Remove

app = flask.Flask(__name__)
"""
route method of flask with '/' as landing page
"""
app.add_url_rule('/', view_func=Home.as_view('home'), methods=['GET'])
"""
route method of flask with '/add' as the page to list all recipes
"""
app.add_url_rule('/index/', view_func=Index.as_view('index'), methods=["GET"])
"""
route method of flask with '/add' as the page to add recipe
"""
app.add_url_rule('/add/',
                 view_func=Add.as_view('add'),
                 methods=['GET', 'POST'])
"""
route method of flask with '/remove' as the page to remove recipe
"""
app.add_url_rule('/remove/',
                 view_func=Remove.as_view('remove'),
                 methods=['GET', 'POST'])

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000, debug=True)
Beispiel #34
0
 def test_add(self):
     add = Add()
     self.assertEqual(add.add(1, 2), 3)
     self.assertEqual(add.add(-1, 2), 1)
     self.assertEqual(add.add(0, 0), 0)
Beispiel #35
0
class MIPSSimulator():
    '''Main class for MIPS pipeline simulator.
    
    Provides the main method tick(), which runs pipeline
    for one clock cycle.
    
    '''
    def __init__(self, memoryFile):
        self.nCycles = 0  # Used to hold number of clock cycles spent executing instructions

        self.dataMemory = DataMemory(memoryFile)
        self.instructionMemory = InstructionMemory(memoryFile)
        self.registerFile = RegisterFile()

        self.constant3 = Constant(3)
        self.constant4 = Constant(4)
        self.randomControl = RandomControl()
        self.mux = Mux()
        self.adder = Add()
        self.pc = PC(0xbfc00000)  # hard coded "boot" address

        self.elements = [
            self.constant3, self.constant4, self.randomControl, self.adder,
            self.mux
        ]

        self._connectCPUElements()

    def _connectCPUElements(self):
        self.constant3.connect([], ['constant'], [], [])

        self.constant4.connect([], ['constant'], [], [])

        self.randomControl.connect([], [], [], ['randomSignal'])

        self.adder.connect([(self.pc, 'pcAddress'),
                            (self.constant4, 'constant')], ['sum'], [], [])

        self.mux.connect([(self.adder, 'sum'),
                          (self.constant3, 'constant')], ['muxOut'],
                         [(self.randomControl, 'randomSignal')], [])

        self.pc.connect([(self.mux, 'muxOut')], ['pcAddress'], [], [])

    def clockCycles(self):
        '''Returns the number of clock cycles spent executing instructions.'''

        return self.nCycles

    def dataMemory(self):
        '''Returns dictionary, mapping memory addresses to data, holding
        data memory after instructions have finished executing.'''

        return self.dataMemory.memory

    def registerFile(self):
        '''Returns dictionary, mapping register numbers to data, holding
        register file after instructions have finished executing.'''

        return self.registerFile.register

    def printDataMemory(self):
        self.dataMemory.printAll()

    def printRegisterFile(self):
        self.registerFile.printAll()

    def tick(self):
        '''Execute one clock cycle of pipeline.'''

        self.nCycles += 1

        # The following is just a small sample implementation

        self.pc.writeOutput()

        for elem in self.elements:
            elem.readControlSignals()
            elem.readInput()
            elem.writeOutput()
            elem.setControlSignals()

        self.pc.readInput()