Ejemplo n.º 1
0
	def simplify(self):
		self._eqn = sympy.factor(sympy.numer(sympy.factor(self._eqn)))
		if isinstance(self._eqn, sympy.Mul):
			def is_not_constant(ex):
				sym = ex.free_symbols
				return x in sym or y in sym or z in sym
			self._eqn = sympy.Mul(*(filter(is_not_constant, self._eqn.args)))
Ejemplo n.º 2
0
def main():
    u, v, R = symbols('u v R', real=True)
    xi, eta = symbols(r'\xi \eta', cls=Function)

    numer = 4*R**2
    denom = u**2 + v**2 + numer

    # inverse of a stereographic projection from the south pole
    # onto the XY plane:
    pinv = Matrix([numer * u / denom,
                   numer * v / denom,
                   -(2 * R * (u**2 + v**2)) / denom]) # OK
    if False:
        # textbook style
        Dpinv = simplify(pinv.jacobian([u, v]))
        print_latex(Dpinv, mat_str='pmatrix', mat_delim=None) # OK?

        tDpinvDpinv = factor(Dpinv.transpose() @ Dpinv)
        print_latex(tDpinvDpinv, mat_str='pmatrix', mat_delim=None) # OK

        tDpinvDpinv = tDpinvDpinv.subs([(u, xi(t)), (v, eta(t))])
        dcdt = Matrix([xi(t).diff(), eta(t).diff()])
        print_latex(simplify(
            sqrt((dcdt.transpose() @ tDpinvDpinv).dot(dcdt))))
    else:
        # directly 
        dpinvc = pinv.subs([(u, xi(t)), (v, eta(t))]).diff(t, 1)
        print_latex(sqrt(factor(dpinvc.dot(dpinvc))))
Ejemplo n.º 3
0
def sympy_factor(expr_sympy):
    try:
        result = sympy.together(expr_sympy)
        numer, denom = result.as_numer_denom()
        if denom == 1:
            result = sympy.factor(expr_sympy)
        else:
            result = sympy.factor(numer) / sympy.factor(denom)
    except sympy.PolynomialError:
        return expr_sympy
    return result
Ejemplo n.º 4
0
def test_binomial_symbolic():
    n = 10  # Because we're using for loops, can't do symbolic n
    p = symbols('p', positive=True)
    X = Binomial('X', n, p)
    assert simplify(E(X)) == n*p
    assert simplify(variance(X)) == n*p*(1 - p)
    assert factor(simplify(skewness(X))) == factor((1-2*p)/sqrt(n*p*(1-p)))

    # Test ability to change success/failure winnings
    H, T = symbols('H T')
    Y = Binomial('Y', n, p, succ=H, fail=T)
    assert simplify(E(Y)) == simplify(n*(H*p + T*(1 - p)))
Ejemplo n.º 5
0
def test_factor_expand():
    A = MatrixSymbol("A", n, n)
    B = MatrixSymbol("B", n, n)
    expr1 = (A + B)*(C + D)
    expr2 = A*C + B*C + A*D + B*D
    assert expr1 != expr2
    assert expand(expr1) == expr2
    assert factor(expr2) == expr1

    expr = B**(-1)*(A**(-1)*B**(-1) - A**(-1)*C*B**(-1))**(-1)*A**(-1)
    I = Identity(n)
    # Ideally we get the first, but we at least don't want a wrong answer
    assert factor(expr) in [I - C, B**-1*(A**-1*(I - C)*B**-1)**-1*A**-1]
Ejemplo n.º 6
0
 def apply(self, expr, evaluation):
     'Factor[expr_]'
     
     expr_sympy = expr.to_sympy()
     try:
         result = sympy.together(expr_sympy)
         numer, denom = result.as_numer_denom()
         if denom == 1:
             result = sympy.factor(expr_sympy)
         else:
             result = sympy.factor(numer) / sympy.factor(denom)
     except sympy.PolynomialError:
         return expr
     return from_sympy(result)
Ejemplo n.º 7
0
def _inverse_mellin_transform(F, s, x_, strip, as_meijerg=False):
    """ A helper for the real inverse_mellin_transform function, this one here
        assumes x to be real and positive. """
    from sympy import (expand, expand_mul, hyperexpand, meijerg, And, Or,
                       arg, pi, re, factor, Heaviside, gamma, Add)
    x = _dummy('t', 'inverse-mellin-transform', F, positive=True)
    # Actually, we won't try integration at all. Instead we use the definition
    # of the Meijer G function as a fairly general inverse mellin transform.
    F = F.rewrite(gamma)
    for g in [factor(F), expand_mul(F), expand(F)]:
        if g.is_Add:
            # do all terms separately
            ress = [_inverse_mellin_transform(G, s, x, strip, as_meijerg,
                                              noconds=False) \
                    for G in g.args]
            conds = [p[1] for p in ress]
            ress = [p[0] for p in ress]
            res = Add(*ress)
            if not as_meijerg:
                res = factor(res, gens=res.atoms(Heaviside))
            return res.subs(x, x_), And(*conds)

        try:
            a, b, C, e, fac = _rewrite_gamma(g, s, strip[0], strip[1])
        except IntegralTransformError:
            continue
        G = meijerg(a, b, C/x**e)
        if as_meijerg:
            h = G
        else:
            h = hyperexpand(G)
            if h.is_Piecewise and len(h.args) == 3:
                # XXX we break modularity here!
                h = Heaviside(x - abs(C))*h.args[0].args[0] \
                  + Heaviside(abs(C) - x)*h.args[1].args[0]
        # We must ensure that the intgral along the line we want converges,
        # and return that value.
        # See [L], 5.2
        cond = [abs(arg(G.argument)) < G.delta*pi]
        # Note: we allow ">=" here, this corresponds to convergence if we let
        # limits go to oo symetrically. ">" corresponds to absolute convergence.
        cond += [And(Or(len(G.ap) != len(G.bq), 0 >= re(G.nu) + 1),
                     abs(arg(G.argument)) == G.delta*pi)]
        cond = Or(*cond)
        if cond is False:
            raise IntegralTransformError('Inverse Mellin', F, 'does not converge')
        return (h*fac).subs(x, x_), cond

    raise IntegralTransformError('Inverse Mellin', F, '')
Ejemplo n.º 8
0
def test_fourier_transform():
    from sympy import simplify, expand, expand_complex, factor, expand_trig
    FT = fourier_transform
    IFT = inverse_fourier_transform

    def simp(x):
        return simplify(expand_trig(expand_complex(expand(x))))

    def sinc(x):
        return sin(pi*x)/(pi*x)
    k = symbols('k', real=True)
    f = Function("f")

    # TODO for this to work with real a, need to expand abs(a*x) to abs(a)*abs(x)
    a = symbols('a', positive=True)
    b = symbols('b', positive=True)

    posk = symbols('posk', positive=True)

    # Test unevaluated form
    assert fourier_transform(f(x), x, k) == FourierTransform(f(x), x, k)
    assert inverse_fourier_transform(
        f(k), k, x) == InverseFourierTransform(f(k), k, x)

    # basic examples from wikipedia
    assert simp(FT(Heaviside(1 - abs(2*a*x)), x, k)) == sinc(k/a)/a
    # TODO IFT is a *mess*
    assert simp(FT(Heaviside(1 - abs(a*x))*(1 - abs(a*x)), x, k)) == sinc(k/a)**2/a
    # TODO IFT

    assert factor(FT(exp(-a*x)*Heaviside(x), x, k), extension=I) == \
        1/(a + 2*pi*I*k)
    # NOTE: the ift comes out in pieces
    assert IFT(1/(a + 2*pi*I*x), x, posk,
            noconds=False) == (exp(-a*posk), True)
    assert IFT(1/(a + 2*pi*I*x), x, -posk,
            noconds=False) == (0, True)
    assert IFT(1/(a + 2*pi*I*x), x, symbols('k', negative=True),
            noconds=False) == (0, True)
    # TODO IFT without factoring comes out as meijer g

    assert factor(FT(x*exp(-a*x)*Heaviside(x), x, k), extension=I) == \
        1/(a + 2*pi*I*k)**2
    assert FT(exp(-a*x)*sin(b*x)*Heaviside(x), x, k) == \
        b/(b**2 + (a + 2*I*pi*k)**2)

    assert FT(exp(-a*x**2), x, k) == sqrt(pi)*exp(-pi**2*k**2/a)/sqrt(a)
    assert IFT(sqrt(pi/a)*exp(-(pi*k)**2/a), k, x) == exp(-a*x**2)
    assert FT(exp(-a*abs(x)), x, k) == 2*a/(a**2 + 4*pi**2*k**2)
Ejemplo n.º 9
0
Archivo: core.py Proyecto: bcbnz/lcapy
    def _as_ratfun_delay(self):
        """Split expr as (N, D, delay)
        where expr = (N / D) * exp(var * delay)
        
        Note, delay only represents a delay when var is s."""

        expr, var = self.expr, self.var

        F = sym.factor(expr).as_ordered_factors()

        delay = sympify(0)
        ratfun = sympify(1)
        for f in F:
            b, e = f.as_base_exp()
            if b == sym.E and e.is_polynomial(var):
                p = sym.Poly(e, var)
                c = p.all_coeffs()
                if p.degree() == 1:
                    delay -= c[0]
                    if c[1] != 0:
                        ratfun *= sym.exp(c[1])
                    continue

            ratfun *= f

        if not ratfun.is_rational_function(var):
            raise ValueError('Expression not a product of rational function'
                             ' and exponential')

        numer, denom = ratfun.as_numer_denom()
        N = sym.Poly(numer, var)
        D = sym.Poly(denom, var)

        return N, D, delay
Ejemplo n.º 10
0
 def solve_high(self, params):
     poly = x**(4+self.num_of_keys)
     for n in xrange(4+self.num_of_keys):
         poly += params[n]*x**(4+self.num_of_keys-n-1)
     if self.debug:
         print "[*] factor:", poly
     return solve(factor(poly))
Ejemplo n.º 11
0
Archivo: ratfun.py Proyecto: mph-/lcapy
def as_ratfun_delay_undef(expr, var):
    delay = sym.S.Zero
    undef = sym.S.One
    
    if expr.is_rational_function(var):
        N, D = expr.as_numer_denom()
        return N, D, delay, undef

    F = sym.factor(expr).as_ordered_factors()

    rf = sym.S.One
    for f in F:
        b, e = f.as_base_exp()
        if b == sym.E and e.is_polynomial(var):
            p = sym.Poly(e, var)
            c = p.all_coeffs()
            if p.degree() == 1:
                delay -= c[0]
                if c[1] != 0:
                    rf *= sym.exp(c[1])
                    continue
        if isinstance(f, sym.function.AppliedUndef):
            undef *= f
            continue
                
        rf *= f

    if not rf.is_rational_function(var):
        raise ValueError('Expression not a product of rational function'
                         ' exponential, and undefined functions')
    
    N, D = rf.as_numer_denom()
    return N, D, delay, undef
Ejemplo n.º 12
0
def tests():
    x, y, z = symbols('x,y,z')
    #print(x + x + 1)
    expr = x**2 - y**2
    factors = factor(expr)
    print(factors, " | ", expand(factors))
    pprint(expand(factors))
Ejemplo n.º 13
0
def deltaproduct(f, limit):
    """
    Handle products containing a KroneckerDelta.

    See Also
    ========

    deltasummation
    sympy.functions.special.tensor_functions.KroneckerDelta
    sympy.concrete.products.product
    """
    from sympy.concrete.products import product

    if ((limit[2] - limit[1]) < 0) is True:
        return S.One

    if not f.has(KroneckerDelta):
        return product(f, limit)

    if f.is_Add:
        # Identify the term in the Add that has a simple KroneckerDelta
        delta = None
        terms = []
        for arg in sorted(f.args, key=default_sort_key):
            if delta is None and _has_simple_delta(arg, limit[0]):
                delta = arg
            else:
                terms.append(arg)
        newexpr = f.func(*terms)
        k = Dummy("kprime", integer=True)
        if isinstance(limit[1], int) and isinstance(limit[2], int):
            result = deltaproduct(newexpr, limit) + sum([
                deltaproduct(newexpr, (limit[0], limit[1], ik - 1)) *
                delta.subs(limit[0], ik) *
                deltaproduct(newexpr, (limit[0], ik + 1, limit[2])) for ik in range(int(limit[1]), int(limit[2] + 1))]
            )
        else:
            result = deltaproduct(newexpr, limit) + deltasummation(
                deltaproduct(newexpr, (limit[0], limit[1], k - 1)) *
                delta.subs(limit[0], k) *
                deltaproduct(newexpr, (limit[0], k + 1, limit[2])), (k, limit[1], limit[2]), no_piecewise=True
            )
        return _remove_multiple_delta(result)

    delta, _ = _extract_delta(f, limit[0])

    if not delta:
        g = _expand_delta(f, limit[0])
        if f != g:
            from sympy import factor
            try:
                return factor(deltaproduct(g, limit))
            except AssertionError:
                return deltaproduct(g, limit)
        return product(f, limit)

    from sympy import Eq
    c = Eq(limit[2], limit[1] - 1)
    return _remove_multiple_delta(f.subs(limit[0], limit[1])*KroneckerDelta(limit[2], limit[1])) + \
        S.One*_simplify_delta(KroneckerDelta(limit[2], limit[1] - 1))
Ejemplo n.º 14
0
def test_nsimplify():
    x = Symbol("x")
    assert nsimplify(0) == 0
    assert nsimplify(-1) == -1
    assert nsimplify(1) == 1
    assert nsimplify(1 + x) == 1 + x
    assert nsimplify(2.7) == Rational(27, 10)
    assert nsimplify(1 - GoldenRatio) == (1 - sqrt(5))/2
    assert nsimplify((1+sqrt(5))/4, [GoldenRatio]) == GoldenRatio/2
    assert nsimplify(2/GoldenRatio, [GoldenRatio]) == 2*GoldenRatio - 2
    assert nsimplify(exp(5*pi*I/3, evaluate=False)) == sympify('1/2 - sqrt(3)*I/2')
    assert nsimplify(sin(3*pi/5, evaluate=False)) == sympify('sqrt(sqrt(5)/8 + 5/8)')
    assert nsimplify(sqrt(atan('1', evaluate=False))*(2+I), [pi]) == sqrt(pi) + sqrt(pi)/2*I
    assert nsimplify(2 + exp(2*atan('1/4')*I)) == sympify('49/17 + 8*I/17')
    assert nsimplify(pi, tolerance=0.01) == Rational(22, 7)
    assert nsimplify(pi, tolerance=0.001) == Rational(355, 113)
    assert nsimplify(0.33333, tolerance=1e-4) == Rational(1, 3)
    assert nsimplify(2.0**(1/3.), tolerance=0.001) == Rational(635, 504)
    assert nsimplify(2.0**(1/3.), tolerance=0.001, full=True) == 2**Rational(1, 3)
    assert nsimplify(x + .5, rational=True) == Rational(1, 2) + x
    assert nsimplify(1/.3 + x, rational=True) == Rational(10, 3) + x
    assert nsimplify(log(3).n(), rational=True) == \
           sympify('109861228866811/100000000000000')
    assert nsimplify(Float(0.272198261287950), [pi,log(2)]) == pi*log(2)/8
    assert nsimplify(Float(0.272198261287950).n(3), [pi,log(2)]) == \
        -pi/4 - log(2) + S(7)/4
    assert nsimplify(x/7.0) == x/7
    assert nsimplify(pi/1e2) == pi/100
    assert nsimplify(pi/1e2, rational=False) == pi/100.0
    assert nsimplify(pi/1e-7) == 10000000*pi
    assert not nsimplify(factor(-3.0*z**2*(z**2)**(-2.5) + 3*(z**2)**(-1.5))).atoms(Float)
Ejemplo n.º 15
0
def test_H27():
    f = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5
    g = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z
    h = -2*z*y**7 \
        *(6*x**9*y**9*z**3 + 10*x**7*z**6 + 17*y*x**5*z**12 + 40*y**7) \
        *(3*x**22 + 47*x**17*y**5*z**8 - 6*x**15*y**9*z**2 - 24*x*y**19*z**8 - 5)
    assert factor(expand(f*g)) == h
Ejemplo n.º 16
0
 def apply_list(self, expr, vars, evaluation):
     'FactorTermsList[expr_, vars_List]'
     if expr == Integer(0):
         return Expression('List', Integer(1), Integer(0))
     elif isinstance(expr, Number):
         return Expression('List', expr, Integer(1))
     
     for x in vars.leaves:
         if not(isinstance(x, Atom)):
             return evaluation.message('CoefficientList', 'ivar', x)
     
     sympy_expr = expr.to_sympy()
     if sympy_expr is None:
         return Expression('List', Integer(1), expr)
     sympy_expr = sympy.together(sympy_expr)
     
     sympy_vars = [x.to_sympy() for x in vars.leaves if isinstance(x, Symbol) and sympy_expr.is_polynomial(x.to_sympy())]
     
     result = []
     numer, denom = sympy_expr.as_numer_denom()
     try:
         from sympy import factor, factor_list, Poly
         if denom == 1:
             # Get numerical part
             num_coeff, num_polys = factor_list(Poly(numer))
             result.append(num_coeff)
             
             # Get factors are independent of sub list of variables
             if (sympy_vars and isinstance(expr, Expression) 
                 and any(x.free_symbols.issubset(sympy_expr.free_symbols) for x in sympy_vars)):
                 for i in reversed(range(len(sympy_vars))):
                     numer = factor(numer) / factor(num_coeff)
                     num_coeff, num_polys = factor_list(Poly(numer), *[x for x in sympy_vars[:(i+1)]])
                     result.append(sympy.expand(num_coeff))
             
             # Last factor
             numer = factor(numer) / factor(num_coeff)
             result.append(sympy.expand(numer))
         else:
             num_coeff, num_polys = factor_list(Poly(numer))
             den_coeff, den_polys = factor_list(Poly(denom))
             result = [num_coeff / den_coeff, sympy.expand(factor(numer)/num_coeff / (factor(denom)/den_coeff))]
     except sympy.PolynomialError: # MMA does not raise error for non poly
         result.append(sympy.expand(numer))
         # evaluation.message(self.get_name(), 'poly', expr)
     
     return Expression('List', *[from_sympy(i) for i in result])
Ejemplo n.º 17
0
def test_factor_nc():
    x, y = symbols('x,y')
    k = symbols('k', integer=True)
    n, m, o = symbols('n,m,o', commutative=False)

    # mul and multinomial expansion is needed
    from sympy.simplify.simplify import _mexpand
    e = x*(1 + y)**2
    assert _mexpand(e) == x + x*2*y + x*y**2

    def factor_nc_test(e):
        ex = _mexpand(e)
        assert ex.is_Add
        f = factor_nc(ex)
        assert not f.is_Add and _mexpand(f) == ex

    factor_nc_test(x*(1 + y))
    factor_nc_test(n*(x + 1))
    factor_nc_test(n*(x + m))
    factor_nc_test((x + m)*n)
    factor_nc_test(n*m*(x*o + n*o*m)*n)
    s = Sum(x, (x, 1, 2))
    factor_nc_test(x*(1 + s))
    factor_nc_test(x*(1 + s)*s)
    factor_nc_test(x*(1 + sin(s)))
    factor_nc_test((1 + n)**2)

    factor_nc_test((x + n)*(x + m)*(x + y))
    factor_nc_test(x*(n*m + 1))
    factor_nc_test(x*(n*m + x))
    factor_nc_test(x*(x*n*m + 1))
    factor_nc_test(x*n*(x*m + 1))
    factor_nc_test(x*(m*n + x*n*m))
    factor_nc_test(n*(1 - m)*n**2)

    factor_nc_test((n + m)**2)
    factor_nc_test((n - m)*(n + m)**2)
    factor_nc_test((n + m)**2*(n - m))
    factor_nc_test((m - n)*(n + m)**2*(n - m))

    assert factor_nc(n*(n + n*m)) == n**2*(1 + m)
    assert factor_nc(m*(m*n + n*m*n**2)) == m*(m + n*m*n)*n
    eq = m*sin(n) - sin(n)*m
    assert factor_nc(eq) == eq

    # for coverage:
    from sympy.physics.secondquant import Commutator
    from sympy import factor
    eq = 1 + x*Commutator(m, n)
    assert factor_nc(eq) == eq
    eq = x*Commutator(m, n) + x*Commutator(m, o)*Commutator(m, n)
    assert factor(eq) == x*(1 + Commutator(m, o))*Commutator(m, n)

    # issue 3435
    assert (2*n + 2*m).factor() == 2*(n + m)

    # issue 3602
    assert factor_nc(n**k + n**(k + 1)) == n**k*(1 + n)
    assert factor_nc((m*n)**k + (m*n)**(k + 1)) == (1 + m*n)*(m*n)**k
Ejemplo n.º 18
0
def test_factor_expand():
    A = MatrixSymbol("A", n, n)
    B = MatrixSymbol("B", n, n)
    expr1 = (A + B)*(C + D)
    expr2 = A*C + B*C + A*D + B*D
    assert expr1 != expr2
    assert expand(expr1) == expr2
    assert factor(expr2) == expr1
Ejemplo n.º 19
0
def test_issue_841():
    a,b,c,d = symbols('a:d', positive=True, bounded=True)
    assert integrate(exp(-x**2 + I*c*x), x) == sqrt(pi)*erf(x - I*c/2)*exp(-c**S(2)/4)/2
    assert integrate(exp(a*x**2 + b*x + c), x) == I*sqrt(pi)*erf(-I*x*sqrt(a) - I*b/(2*sqrt(a)))*exp(c)*exp(-b**2/(4*a))/(2*sqrt(a))
    a,b,c,d = symbols('a:d', positive=True)
    i = integrate(exp(-a*x**2 + 2*d*x), (x, -oo, oo))
    ans = sqrt(pi)*exp(d**2/a)*(1 + erf(oo - d/sqrt(a)))/(2*sqrt(a))
    n, d = i.as_numer_denom()
    assert factor(n, expand=False)/d == ans
Ejemplo n.º 20
0
 def __factor(self):
     try:
         print("Factoring..")
         expr = sympy.sympify(self.ent.get())
         fexpr = sympy.factor(expr)
         print(str(fexpr))
         self.res["text"] = "Your expression factors as %s" % str(fexpr)
     except Exception as e:
         showerror("ERROR!", str(e))
Ejemplo n.º 21
0
def coeff(k):
    """
    return the coeffs of T_n in the k-fold integral of 
    T_{n-k} ... T_{n+k} as functions of n
    """
    d = integral(k)
    ans = dict()
    for k in d.keys():
        ans[-k] = sympy.factor(d[k].subs(n, n-k))
    return ans
Ejemplo n.º 22
0
def test_apart_extension():
    f = 2/(x**2 + 1)
    g = I/(x + I) - I/(x - I)

    assert apart(f, extension=I) == g
    assert apart(f, gaussian=True) == g

    f = x/((x - 2)*(x + I))

    assert factor(together(apart(f))) == f
Ejemplo n.º 23
0
def poly_factorize(poly):
    """Factorize multivariate polynomials into a sum of products of monomials.

    This function can be used to decompose polynomials into a form which
    minimizes the number of additions and multiplications, and which thus
    can be evaluated efficently."""
    max_deg = {}

    if 'horner' in dir(sympy):
        return sympy.horner(poly)

    if not isinstance(poly, Poly):
        poly = Poly(sympy.expand(poly), *poly.atoms(Symbol))

    denom, poly = poly.as_integer()

    # Determine the order of factorization.  We proceed through the
    # symbols, starting with the one present in the highest order
    # in the polynomial.
    for i, sym in enumerate(poly.symbols):
        max_deg[i] = 0

    for monom in poly.monoms:
        for i, symvar in enumerate(monom):
            max_deg[i] = max(max_deg[i], symvar)

    ret_poly = 0
    monoms = list(poly.monoms)

    for isym, maxdeg in sorted(max_deg.items(), key=itemgetter(1), reverse=True):
        drop_idx = []
        new_poly = []

        for i, monom in enumerate(monoms):
            if monom[isym] > 0:
                drop_idx.append(i)
                new_poly.append((poly.coeff(*monom), monom))

        if not new_poly:
            continue

        ret_poly += sympy.factor(Poly(new_poly, *poly.symbols))

        for idx in reversed(drop_idx):
            del monoms[idx]

    # Add any remaining O(1) terms.
    new_poly = []
    for i, monom in enumerate(monoms):
        new_poly.append((poly.coeff(*monom), monom))

    if new_poly:
        ret_poly += Poly(new_poly, *poly.symbols)

    return ret_poly / denom
Ejemplo n.º 24
0
def test_nsimplify():
    x = Symbol("x")
    assert nsimplify(0) == 0
    assert nsimplify(-1) == -1
    assert nsimplify(1) == 1
    assert nsimplify(1 + x) == 1 + x
    assert nsimplify(2.7) == Rational(27, 10)
    assert nsimplify(1 - GoldenRatio) == (1 - sqrt(5)) / 2
    assert nsimplify((1 + sqrt(5)) / 4, [GoldenRatio]) == GoldenRatio / 2
    assert nsimplify(2 / GoldenRatio, [GoldenRatio]) == 2 * GoldenRatio - 2
    assert nsimplify(exp(5 * pi * I / 3, evaluate=False)) == sympify("1/2 - sqrt(3)*I/2")
    assert nsimplify(sin(3 * pi / 5, evaluate=False)) == sympify("sqrt(sqrt(5)/8 + 5/8)")
    assert nsimplify(sqrt(atan("1", evaluate=False)) * (2 + I), [pi]) == sqrt(pi) + sqrt(pi) / 2 * I
    assert nsimplify(2 + exp(2 * atan("1/4") * I)) == sympify("49/17 + 8*I/17")
    assert nsimplify(pi, tolerance=0.01) == Rational(22, 7)
    assert nsimplify(pi, tolerance=0.001) == Rational(355, 113)
    assert nsimplify(0.33333, tolerance=1e-4) == Rational(1, 3)
    assert nsimplify(2.0 ** (1 / 3.0), tolerance=0.001) == Rational(635, 504)
    assert nsimplify(2.0 ** (1 / 3.0), tolerance=0.001, full=True) == 2 ** Rational(1, 3)
    assert nsimplify(x + 0.5, rational=True) == Rational(1, 2) + x
    assert nsimplify(1 / 0.3 + x, rational=True) == Rational(10, 3) + x
    assert nsimplify(log(3).n(), rational=True) == sympify("109861228866811/100000000000000")
    assert nsimplify(Float(0.272198261287950), [pi, log(2)]) == pi * log(2) / 8
    assert nsimplify(Float(0.272198261287950).n(3), [pi, log(2)]) == -pi / 4 - log(2) + S(7) / 4
    assert nsimplify(x / 7.0) == x / 7
    assert nsimplify(pi / 1e2) == pi / 100
    assert nsimplify(pi / 1e2, rational=False) == pi / 100.0
    assert nsimplify(pi / 1e-7) == 10000000 * pi
    assert not nsimplify(factor(-3.0 * z ** 2 * (z ** 2) ** (-2.5) + 3 * (z ** 2) ** (-1.5))).atoms(Float)
    e = x ** 0.0
    assert e.is_Pow and nsimplify(x ** 0.0) == 1
    assert nsimplify(3.333333, tolerance=0.1, rational=True) == Rational(10, 3)
    assert nsimplify(3.333333, tolerance=0.01, rational=True) == Rational(10, 3)
    assert nsimplify(3.666666, tolerance=0.1, rational=True) == Rational(11, 3)
    assert nsimplify(3.666666, tolerance=0.01, rational=True) == Rational(11, 3)
    assert nsimplify(33, tolerance=10, rational=True) == Rational(33)
    assert nsimplify(33.33, tolerance=10, rational=True) == Rational(30)
    assert nsimplify(37.76, tolerance=10, rational=True) == Rational(40)
    assert nsimplify(-203.1) == -S(2031) / 10
    assert nsimplify(0.2, tolerance=0) == S.One / 5
    assert nsimplify(-0.2, tolerance=0) == -S.One / 5
    assert nsimplify(0.2222, tolerance=0) == S(1111) / 5000
    assert nsimplify(-0.2222, tolerance=0) == -S(1111) / 5000
    # issue 7211, PR 4112
    assert nsimplify(S(2e-8)) == S(1) / 50000000
    # issue 7322 direct test
    assert nsimplify(1e-42, rational=True) != 0
    # issue 10336
    inf = Float("inf")
    infs = (-oo, oo, inf, -inf)
    for i in infs:
        ans = sign(i) * oo
        assert nsimplify(i) == ans
        assert nsimplify(i + x) == x + ans
Ejemplo n.º 25
0
def test_issue_4892b():
    # Issues relating to issue 4596 are making the actual result of this hard
    # to test.  The answer should be something like
    #
    # (-sin(y) + sqrt(-72 + 48*cos(y) - 8*cos(y)**2)/2)*log(x + sqrt(-72 +
    # 48*cos(y) - 8*cos(y)**2)/(2*(3 - cos(y)))) + (-sin(y) - sqrt(-72 +
    # 48*cos(y) - 8*cos(y)**2)/2)*log(x - sqrt(-72 + 48*cos(y) -
    # 8*cos(y)**2)/(2*(3 - cos(y)))) + x**2*sin(y)/2 + 2*x*cos(y)

    expr = (sin(y)*x**3 + 2*cos(y)*x**2 + 12)/(x**2 + 2)
    assert trigsimp(factor(integrate(expr, x).diff(x) - expr)) == 0
Ejemplo n.º 26
0
 def simp(self, sym):
     sym = factor(sym)
     new_sym = tools.ONE
     for expr in Mul.make_args(sym):
         if expr.is_Pow:
             expr, pow_val = expr.args
         else:
             pow_val = 1
         expr = self.C2S2_simp(expr)
         expr = self.CS12_simp(expr, silent=True)
         new_sym *= expr**pow_val
     return new_sym
Ejemplo n.º 27
0
 def simp(self, sym):
     sym = factor(sym)
     new_sym = ONE
     for e in Mul.make_args(sym):
         if e.is_Pow:
             e, p = e.args
         else:
             p = 1
         e = self.C2S2_simp(e)
         e = self.CS12_simp(e, silent=True)
         new_sym *= e**p
     return new_sym
Ejemplo n.º 28
0
def do_simp(expr, method):
	### Module Reference
	### http://docs.sympy.org/latest/modules/simplify/simplify.html

	if method == "simplify":
		simp = sympy.simplify(expr)
	elif method == "expand":
		simp = sympy.expand(expr)
	elif method == "factor":
		simp = sympy.factor(expr)
	else:
		return None, "unknown method"
	return simp, None
Ejemplo n.º 29
0
def main():
    x, y = symbols("x y")
    print(x + y - x)
    print(x + 2 * y - 6 * x - 5 * x)

    expr = (x + x * y) / x
    print(simplify(expr))

    expr = x + y
    expr = x * expr
    print(expr)
    print(expand(expr))
    print(factor(expand(expr)))
Ejemplo n.º 30
0
Archivo: poly.py Proyecto: Mortal/poly
def polynomial_through(roots, degree, xs, general=False, quick=True, verbose=False):
    ms = monomials(xs, degree)
    system = sympy.Matrix([[m.subs(zip(xs, x)) for m in ms] + [0] for x in roots])
    symbols = tuple(coefficients(xs, degree))
    print("%d roots, %d coefficients" % (len(roots), len(symbols)))

    if verbose:
        print("Linear system:")
        print_matrix(system)
        print(symbols)
    if general or not quick:
        sol = sympy.solvers.solve_linear_system(system, *symbols)
    else:
        sol = sympy.solvers.minsolve_linear_system(system, *symbols, quick=quick)
    if verbose:
        print("Solution:")
        for k, v in sol.items():
            print("  %s = %s" % (k, v))

    if () == tuple(filter(lambda n: n != 0, sol.values())):
        if verbose:
            print("No non-trivial solution")
        return None

    p = sum(sol.get(ci, ci) * m for ci, m in zip(symbols, ms))
    frees_orig = tuple(frozenset(p.free_symbols).difference(xs))
    frees = default_coefficients(len(frees_orig))
    p = p.subs(zip(frees_orig, frees))

    if verbose:
        print("Degrees of freedom: %d" % len(frees))
        print("General solution:")
        print(p)

    if frees and not general:
        # Choose concrete values for free variables
        # (Does not happen when minsolve_linear_system is used)
        concretes = []
        for free in frees:
            c = p.subs((v, 1 if v == free else 0) for v in frees)
            c = remove_denominator(c)
            concretes.append(c)
        degrees = map(lambda p: p.as_poly(*xs).total_degree(), concretes)
        ps, ds = zip(*sorted(zip(concretes, degrees), key=lambda a: a[1]))
        if verbose:
            print("Concretizations:")
            for pi, di in zip(ps, ds):
                print("  %s  (degree %d)" % (sympy.factor(pi), di))
        p = ps[0]

    return p
Ejemplo n.º 31
0
- Helps solve hypergeometric equations using input from the user

Author : Anwesan De

Date   : 7/10/21

'''
import sympy as sy
sy.init_printing() # for LaTeX formatted output
from IPython.display import display
x,t = sy.symbols('x t'); y = sy.symbols('y', cls=sy.Function)
cy2=sy.sympify(input("Enter the coeff. of y’’ "))
cy1=sy.sympify(input("Enter the coeff. of y’ "))
cy0=sy.sympify(input("Enter the coeff. of y "))
s=sy.Eq(sy.factor(cy2)*y(x).diff(x,x)+cy1*y(x).diff(x)+cy0*y(x),0)
display(s)
print("Let us compare it with (x-A)(x-B)y’’+(Cx+D)y’+Ey=0.")
A=sy.sympify(input("Here A = "))
B=sy.sympify(input("and B = "))
print('So using the transformation x=(B-A)t+A, we get')
t1=(B-A)*t+A
k2=sy.lambdify(x,cy2);
k1=sy.lambdify(x,cy1);
k0=sy.lambdify(x,cy0)
s=sy.Eq(sy.factor(k2(t1))*y(t).diff(t,t)*(sy.diff(t1,t))**-2+sy.simplify((sy.diff(t1,t)**-1)*k1(t1))*y(t).diff(t)+k0(t1)*y(t),0)
display(s)
print("Comparing with t(t-1)y’’+[(a+b+1)t-c]y’+aby=0, we have")
S=sy.sympify(input("a+b+1 = "))
c=sy.sympify(input("c = "))
P=sy.sympify(input("ab = "))
 def get_sympy_representation(self, input_attributes):
     return sympy.factor(self.sympy_method(*input_attributes))
Ejemplo n.º 33
0
def checkForCommonFactor(infisTmp, allVariables, m):
    spy.var('epsilon')
    #extract all factors from first infinitesimal
    for i in range(len(allVariables)):
        if infisTmp[i] != 0:
            fac = spy.factor(infisTmp[i])
            if type(fac) == type(epsilon + 1):
                factors = [infisTmp[i]]
            elif type(fac) == type(epsilon):
                factors = [fac]
            else:
                factors = list(fac.args)

            break

    i = 0
    while i < len(factors):
        if factors[i].is_number:
            factors.pop(i)
        elif factors[i] in allVariables[:m]:
            factors.pop(i)
        elif type(factors[i]) == type(epsilon + 1):
            factors.pop(i)
        elif type(factors[i]) == type(epsilon**2):
            if type(factors[i].args[0]) != type(epsilon + 1):
                factors[i] = factors[i].args[0]
                i += 1
            else:
                factors.pop(i)
        else:
            i += 1

    #check which of the factors is in all other infinitesimals
    for i in range(1, len(infisTmp)):
        if infisTmp[i] == 0: continue
        fac = spy.factor(infisTmp[i])
        if type(fac) == type(epsilon + 1):
            factorsTmp = [fac]
        elif type(fac) == type(epsilon):
            factorsTmp = [fac]
        else:
            factorsTmp = list(fac.args)

        j = 0
        while j < len(factors):
            k = 0
            while k < len(factorsTmp):
                if factorsTmp[k].is_number:
                    factorsTmp.pop(k)
                elif factorsTmp[k] in allVariables[:m]:
                    factorsTmp.pop(k)
                elif type(factorsTmp[k]) == type(epsilon + 1):
                    factorsTmp.pop(k)
                elif type(factorsTmp[k]) == type(epsilon**2):
                    if type(factorsTmp[k].args[0]) != type(epsilon + 1):
                        factorsTmp[k] = factorsTmp[k].args[0]
                        k += 1
                    else:
                        factorsTmp.pop(k)
                else:
                    k += 1
            if factors[j] in factorsTmp:
                j += 1
                continue
            else:
                factors.pop(j)

        if len(factors) != 0:
            continue  #if potential common factors are left, try next ifinitesimal
        else:
            break  #otherwise treat next solution

    if len(factors) == 0:
        return False
    else:
        return True
Ejemplo n.º 34
0
from sympy import Symbol, expand, factor, solve, simplify, apart, together, collect, latex, preview

x = Symbol('x')
y = Symbol('y')
z = Symbol('z')

print('EXPAND, FACTOR, SUBSTITUTE, SOLVE')
e = (x + 1)**2
print(e)
e = expand(e)
print(e)
e = factor(e)
print(e)
e = expand(e)
print(e)
e = e.subs(x**2, y)
print(e)
r = solve(e, y)[0]
print(r)

print('SIMPLIFY')
e = expand((x + 1) * (y + 1)) / (y + 1)
print(e)
e = simplify(e)
print(e)

print('TOGETHER, APART')
e = 1 / x + 1 / y + 1 / z
print(e)
e = together(e)
print(e)
Ejemplo n.º 35
0
def test_factor():
    assert factor(A * B - B * A) == A * B - B * A
Ejemplo n.º 36
0
def test_gauss_opt():
    mat = RayTransferMatrix(1, 2, 3, 4)
    assert mat == Matrix([[1, 2], [3, 4]])
    assert mat == RayTransferMatrix( Matrix([[1, 2], [3, 4]]) )
    assert [mat.A, mat.B, mat.C, mat.D] == [1, 2, 3, 4]

    d, f, h, n1, n2, R = symbols('d f h n1 n2 R')
    lens = ThinLens(f)
    assert lens == Matrix([[   1, 0], [-1/f, 1]])
    assert lens.C == -1/f
    assert FreeSpace(d) == Matrix([[ 1, d], [0, 1]])
    assert FlatRefraction(n1, n2) == Matrix([[1, 0], [0, n1/n2]])
    assert CurvedRefraction(
        R, n1, n2) == Matrix([[1, 0], [(n1 - n2)/(R*n2), n1/n2]])
    assert FlatMirror() == Matrix([[1, 0], [0, 1]])
    assert CurvedMirror(R) == Matrix([[   1, 0], [-2/R, 1]])
    assert ThinLens(f) == Matrix([[   1, 0], [-1/f, 1]])

    mul = CurvedMirror(R)*FreeSpace(d)
    mul_mat = Matrix([[   1, 0], [-2/R, 1]])*Matrix([[ 1, d], [0, 1]])
    assert mul.A == mul_mat[0, 0]
    assert mul.B == mul_mat[0, 1]
    assert mul.C == mul_mat[1, 0]
    assert mul.D == mul_mat[1, 1]

    angle = symbols('angle')
    assert GeometricRay(h, angle) == Matrix([[    h], [angle]])
    assert FreeSpace(
        d)*GeometricRay(h, angle) == Matrix([[angle*d + h], [angle]])
    assert GeometricRay( Matrix( ((h,), (angle,)) ) ) == Matrix([[h], [angle]])
    assert (FreeSpace(d)*GeometricRay(h, angle)).height == angle*d + h
    assert (FreeSpace(d)*GeometricRay(h, angle)).angle == angle

    p = BeamParameter(530e-9, 1, w=1e-3)
    assert streq(p.q, 1 + 1.88679245283019*I*pi)
    assert streq(N(p.q), 1.0 + 5.92753330865999*I)
    assert streq(N(p.w_0), Float(0.00100000000000000))
    assert streq(N(p.z_r), Float(5.92753330865999))
    fs = FreeSpace(10)
    p1 = fs*p
    assert streq(N(p.w), Float(0.00101413072159615))
    assert streq(N(p1.w), Float(0.00210803120913829))

    w, wavelen = symbols('w wavelen')
    assert waist2rayleigh(w, wavelen) == pi*w**2/wavelen
    z_r, wavelen = symbols('z_r wavelen')
    assert rayleigh2waist(z_r, wavelen) == sqrt(wavelen*z_r)/sqrt(pi)

    a, b, f = symbols('a b f')
    assert geometric_conj_ab(a, b) == a*b/(a + b)
    assert geometric_conj_af(a, f) == a*f/(a - f)
    assert geometric_conj_bf(b, f) == b*f/(b - f)
    assert geometric_conj_ab(oo, b) == b
    assert geometric_conj_ab(a, oo) == a

    s_in, z_r_in, f = symbols('s_in z_r_in f')
    assert gaussian_conj(
        s_in, z_r_in, f)[0] == 1/(-1/(s_in + z_r_in**2/(-f + s_in)) + 1/f)
    assert gaussian_conj(
        s_in, z_r_in, f)[1] == z_r_in/(1 - s_in**2/f**2 + z_r_in**2/f**2)
    assert gaussian_conj(
        s_in, z_r_in, f)[2] == 1/sqrt(1 - s_in**2/f**2 + z_r_in**2/f**2)

    l, w_i, w_o, f = symbols('l w_i w_o f')
    assert conjugate_gauss_beams(l, w_i, w_o, f=f)[0] == f*(
        -sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)) + 1)
    assert factor(conjugate_gauss_beams(l, w_i, w_o, f=f)[1]) == f*w_o**2*(
        w_i**2/w_o**2 - sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)))/w_i**2
    assert conjugate_gauss_beams(l, w_i, w_o, f=f)[2] == f

    z, l, w = symbols('z l r', positive=True)
    p = BeamParameter(l, z, w=w)
    assert p.radius == z*(l**2*z**2/(pi**2*w**4) + 1)
    assert p.w == w*sqrt(l**2*z**2/(pi**2*w**4) + 1)
    assert p.w_0 == w
    assert p.divergence == l/(pi*w)
    assert p.gouy == atan2(z, pi*w**2/l)
    assert p.waist_approximation_limit == 2*l/pi
Ejemplo n.º 37
0
def test_factor_nc():
    x, y = symbols('x,y')
    k = symbols('k', integer=True)
    n, m, o = symbols('n,m,o', commutative=False)

    # mul and multinomial expansion is needed
    from sympy.simplify.simplify import _mexpand
    e = x * (1 + y)**2
    assert _mexpand(e) == x + x * 2 * y + x * y**2

    def factor_nc_test(e):
        ex = _mexpand(e)
        assert ex.is_Add
        f = factor_nc(ex)
        assert not f.is_Add and _mexpand(f) == ex

    factor_nc_test(x * (1 + y))
    factor_nc_test(n * (x + 1))
    factor_nc_test(n * (x + m))
    factor_nc_test((x + m) * n)
    factor_nc_test(n * m * (x * o + n * o * m) * n)
    s = Sum(x, (x, 1, 2))
    factor_nc_test(x * (1 + s))
    factor_nc_test(x * (1 + s) * s)
    factor_nc_test(x * (1 + sin(s)))
    factor_nc_test((1 + n)**2)

    factor_nc_test((x + n) * (x + m) * (x + y))
    factor_nc_test(x * (n * m + 1))
    factor_nc_test(x * (n * m + x))
    factor_nc_test(x * (x * n * m + 1))
    factor_nc_test(x * n * (x * m + 1))
    factor_nc_test(x * (m * n + x * n * m))
    factor_nc_test(n * (1 - m) * n**2)

    factor_nc_test((n + m)**2)
    factor_nc_test((n - m) * (n + m)**2)
    factor_nc_test((n + m)**2 * (n - m))
    factor_nc_test((m - n) * (n + m)**2 * (n - m))

    assert factor_nc(n * (n + n * m)) == n**2 * (1 + m)
    assert factor_nc(m * (m * n + n * m * n**2)) == m * (m + n * m * n) * n
    eq = m * sin(n) - sin(n) * m
    assert factor_nc(eq) == eq

    # for coverage:
    from sympy.physics.secondquant import Commutator
    from sympy import factor
    eq = 1 + x * Commutator(m, n)
    assert factor_nc(eq) == eq
    eq = x * Commutator(m, n) + x * Commutator(m, o) * Commutator(m, n)
    assert factor(eq) == x * (1 + Commutator(m, o)) * Commutator(m, n)

    # issue 6534
    assert (2 * n + 2 * m).factor() == 2 * (n + m)

    # issue 6701
    assert factor_nc(n**k + n**(k + 1)) == n**k * (1 + n)
    assert factor_nc((m * n)**k + (m * n)**(k + 1)) == (1 + m * n) * (m * n)**k

    # issue 6918
    assert factor_nc(-n * (2 * x**2 + 2 * x)) == -2 * n * x * (x + 1)
Ejemplo n.º 38
0
def test_H25():
    e = (x - 2 * y**2 + 3 * z**3)**20
    assert factor(expand(e)) == e
Ejemplo n.º 39
0
def test_H23():
    f = x**11 + x + 1
    g = (x**2 + x + 1) * (x**9 - x**8 + x**6 - x**5 + x**3 - x**2 + 1)
    assert factor(f, modulus=65537) == g
Ejemplo n.º 40
0
def test_H22():
    assert factor(x**4 - 3 * x**2 + 1, modulus=5) == (x - 2)**2 * (x + 2)**2
Ejemplo n.º 41
0
def test_H18():
    # Factor over complex rationals.
    test = factor(4 * x**4 + 8 * x**3 + 77 * x**2 + 18 * x + 53)
    good = (2 * x + 3 * I) * (2 * x - 3 * I) * (x + 1 - 4 * I)(x + 1 + 4 * I)
    assert test == good
Ejemplo n.º 42
0
def test_H17():
    assert simplify(factor(expand(p1 * p2)) - p1 * p2) == 0
Ejemplo n.º 43
0
def test_H4():
    expr = factor(6 * x - 10)
    assert type(expr) is Mul
    assert expr.args[0] == 2
    assert expr.args[1] == 3 * x - 5
Ejemplo n.º 44
0
def test_integrate_hyperexponential():
    # TODO: Add tests for integrate_hyperexponential() from the book
    a = Poly(
        (1 + 2 * t1 + t1**2 + 2 * t1**3) * t**2 + (1 + t1**2) * t + 1 + t1**2,
        t)
    d = Poly(1, t)
    DE = DifferentialExtension(
        extension={
            'D': [Poly(1, x),
                  Poly(1 + t1**2, t1),
                  Poly(t * (1 + t1**2), t)],
            'Tfuncs': [tan, Lambda(i, exp(tan(i)))]
        })
    assert integrate_hyperexponential(a, d, DE) == \
        (exp(2*tan(x))*tan(x) + exp(tan(x)), 1 + t1**2, True)
    a = Poly((t1**3 + (x + 1) * t1**2 + t1 + x + 2) * t, t)
    assert integrate_hyperexponential(a, d, DE) == \
        ((x + tan(x))*exp(tan(x)), 0, True)

    a = Poly(t, t)
    d = Poly(1, t)
    DE = DifferentialExtension(extension={
        'D': [Poly(1, x), Poly(2 * x * t, t)],
        'Tfuncs': [Lambda(i, exp(x**2))]
    })

    assert integrate_hyperexponential(a, d, DE) == \
        (0, NonElementaryIntegral(exp(x**2), x), False)

    DE = DifferentialExtension(extension={
        'D': [Poly(1, x), Poly(t, t)],
        'Tfuncs': [exp]
    })
    assert integrate_hyperexponential(a, d, DE) == (exp(x), 0, True)

    a = Poly(
        25 * t**6 - 10 * t**5 + 7 * t**4 - 8 * t**3 + 13 * t**2 + 2 * t - 1, t)
    d = Poly(25 * t**6 + 35 * t**4 + 11 * t**2 + 1, t)
    assert integrate_hyperexponential(a, d, DE) == \
        (-(11 - 10*exp(x))/(5 + 25*exp(2*x)) + log(1 + exp(2*x)), -1, True)
    DE = DifferentialExtension(
        extension={
            'D': [Poly(1, x), Poly(t0, t0),
                  Poly(t0 * t, t)],
            'Tfuncs': [exp, Lambda(i, exp(exp(i)))]
        })
    assert integrate_hyperexponential(Poly(2 * t0 * t**2, t), Poly(1, t),
                                      DE) == (exp(2 * exp(x)), 0, True)

    DE = DifferentialExtension(
        extension={
            'D': [Poly(1, x), Poly(t0, t0),
                  Poly(-t0 * t, t)],
            'Tfuncs': [exp, Lambda(i, exp(-exp(i)))]
        })
    assert integrate_hyperexponential(Poly(-27*exp(9) - 162*t0*exp(9) +
    27*x*t0*exp(9), t), Poly((36*exp(18) + x**2*exp(18) - 12*x*exp(18))*t, t), DE) == \
        (27*exp(exp(x))/(-6*exp(9) + x*exp(9)), 0, True)

    DE = DifferentialExtension(extension={
        'D': [Poly(1, x), Poly(t, t)],
        'Tfuncs': [exp]
    })
    assert integrate_hyperexponential(Poly(x**2/2*t, t), Poly(1, t), DE) == \
        ((2 - 2*x + x**2)*exp(x)/2, 0, True)
    assert integrate_hyperexponential(Poly(1 + t, t), Poly(t, t), DE) == \
        (-exp(-x), 1, True)  # x - exp(-x)
    assert integrate_hyperexponential(Poly(x, t), Poly(t + 1, t), DE) == \
        (0, NonElementaryIntegral(x/(1 + exp(x)), x), False)

    DE = DifferentialExtension(
        extension={
            'D': [Poly(1, x),
                  Poly(1 / x, t0),
                  Poly(2 * x * t1, t1)],
            'Tfuncs': [log, Lambda(i, exp(i**2))]
        })

    elem, nonelem, b = integrate_hyperexponential(
        Poly(
            (8 * x**7 - 12 * x**5 + 6 * x**3 - x) * t1**4 +
            (8 * t0 * x**7 - 8 * t0 * x**6 - 4 * t0 * x**5 + 2 * t0 * x**3 +
             2 * t0 * x**2 - t0 * x + 24 * x**8 - 36 * x**6 - 4 * x**5 +
             22 * x**4 + 4 * x**3 - 7 * x**2 - x + 1) * t1**3 +
            (8 * t0 * x**8 - 4 * t0 * x**6 - 16 * t0 * x**5 - 2 * t0 * x**4 +
             12 * t0 * x**3 + t0 * x**2 - 2 * t0 * x + 24 * x**9 - 36 * x**7 -
             8 * x**6 + 22 * x**5 + 12 * x**4 - 7 * x**3 - 6 * x**2 + x + 1) *
            t1**2 + (8 * t0 * x**8 - 8 * t0 * x**6 - 16 * t0 * x**5 +
                     6 * t0 * x**4 + 10 * t0 * x**3 - 2 * t0 * x**2 - t0 * x +
                     8 * x**10 - 12 * x**8 - 4 * x**7 + 2 * x**6 + 12 * x**5 +
                     3 * x**4 - 9 * x**3 - x**2 + 2 * x) * t1 + 8 * t0 * x**7 -
            12 * t0 * x**6 - 4 * t0 * x**5 + 8 * t0 * x**4 - t0 * x**2 -
            4 * x**7 + 4 * x**6 + 4 * x**5 - 4 * x**4 - x**3 + x**2, t1),
        Poly((8 * x**7 - 12 * x**5 + 6 * x**3 - x) * t1**4 +
             (24 * x**8 + 8 * x**7 - 36 * x**6 - 12 * x**5 + 18 * x**4 +
              6 * x**3 - 3 * x**2 - x) * t1**3 +
             (24 * x**9 + 24 * x**8 - 36 * x**7 - 36 * x**6 + 18 * x**5 +
              18 * x**4 - 3 * x**3 - 3 * x**2) * t1**2 +
             (8 * x**10 + 24 * x**9 - 12 * x**8 - 36 * x**7 + 6 * x**6 +
              18 * x**5 - x**4 - 3 * x**3) * t1 + 8 * x**10 - 12 * x**8 +
             6 * x**6 - x**4, t1), DE)

    assert factor(elem) == -((x - 1) * log(x) / ((x + exp(x**2)) *
                                                 (2 * x**2 - 1)))
    assert (nonelem,
            b) == (NonElementaryIntegral(exp(x**2) / (exp(x**2) + 1),
                                         x), False)
Ejemplo n.º 45
0
ficEqns = (
    XCR - pGam * gamCr - pDel * delCr - pLav * lavCr,
    XNB - pGam * gamNb - pDel * delNb - pLav * lavNb,
    ficGdCr - ficDdCr,
    ficGdNb - ficDdNb,
    ficGdCr - ficLdCr,
    ficGdNb - ficLdNb,
)

ficVars = (gamCr, gamNb, delCr, delNb, lavCr, lavNb)

fictitious = solve(ficEqns, ficVars, dict=True)

# Note: denominator is the determinant, identical by
# definition. So, we separate it to save some FLOPs.
fict_gam_Cr = factor(expand(fictitious[0][gamCr]))
fict_gam_Nb = factor(expand(fictitious[0][gamNb]))
fict_del_Cr = factor(expand(fictitious[0][delCr]))
fict_del_Nb = factor(expand(fictitious[0][delNb]))
fict_lav_Cr = factor(expand(fictitious[0][lavCr]))
fict_lav_Nb = factor(expand(fictitious[0][lavNb]))

# ============ COMPOSITION SHIFTS ============
## Ref: TKR5p219

r_del, r_lav = symbols("r_del, r_lav")

GaCrCr = p_d2Ggam_dxCrCr
GaCrNb = p_d2Ggam_dxCrNb
GaNbNb = p_d2Ggam_dxNbNb
Ejemplo n.º 46
0
def test_H26():
    g = expand((sin(x) - 2 * cos(y)**2 + 3 * tan(z)**3)**20)
    assert factor(g, expand=False) == (-sin(x) + 2 * cos(y)**2 -
                                       3 * tan(z)**3)**20
Ejemplo n.º 47
0
e2 = (x - y)**2
e3 = x**2 + y**2 + 2 * x * y
m1 = sm.Matrix([e1, e2]).reshape(2, 1)
m2 = sm.Matrix([(x + y)**2, (x - y)**2]).reshape(1, 2)
m3 = m1 + sm.Matrix([x, y]).reshape(2, 1)
am = sm.Matrix([i.expand() for i in m1]).reshape((m1).shape[0], (m1).shape[1])
cm = sm.Matrix([
    i.expand() for i in sm.Matrix([(x + y)**2, (x - y)**2]).reshape(1, 2)
]).reshape((sm.Matrix([(x + y)**2, (x - y)**2]).reshape(1, 2)).shape[0],
           (sm.Matrix([(x + y)**2, (x - y)**2]).reshape(1, 2)).shape[1])
em = sm.Matrix([i.expand() for i in m1 + sm.Matrix([x, y]).reshape(2, 1)
                ]).reshape((m1 + sm.Matrix([x, y]).reshape(2, 1)).shape[0],
                           (m1 + sm.Matrix([x, y]).reshape(2, 1)).shape[1])
f = (e1).expand()
g = (e2).expand()
a = sm.factor((e3), x)
bm = sm.Matrix([sm.factor(i, x) for i in m1]).reshape((m1).shape[0],
                                                      (m1).shape[1])
cm = sm.Matrix([sm.factor(i, x) for i in m1 + sm.Matrix([x, y]).reshape(2, 1)
                ]).reshape((m1 + sm.Matrix([x, y]).reshape(2, 1)).shape[0],
                           (m1 + sm.Matrix([x, y]).reshape(2, 1)).shape[1])
a = (e3).diff(x)
b = (e3).diff(y)
cm = sm.Matrix([i.diff(x) for i in m2]).reshape((m2).shape[0], (m2).shape[1])
dm = sm.Matrix([i.diff(x) for i in m1 + sm.Matrix([x, y]).reshape(2, 1)
                ]).reshape((m1 + sm.Matrix([x, y]).reshape(2, 1)).shape[0],
                           (m1 + sm.Matrix([x, y]).reshape(2, 1)).shape[1])
frame_a = me.ReferenceFrame('a')
frame_b = me.ReferenceFrame('b')
frame_b.orient(frame_a, 'DCM',
               sm.Matrix([1, 0, 0, 1, 0, 0, 1, 0, 0]).reshape(3, 3))
Ejemplo n.º 48
0
print('a -> for x = 7')
print(expr, '=', expr.subs(x, 7))

y = sym.symbols('y')
print('b ->', sym.expand(x + y)**2)

print('c ->', sym.simplify(4 * x**3 + 21 * x**2 + 10 * x + 12))

print('d ->', sym.limit(1 / (x**2), x, sym.oo))
n, i = sym.symbols('n i')
print('e ->', sym.summation(2 * i + i - 1, (i, 5, n)))

print('f ->', sym.integrate(sym.sin(x) + sym.exp(x) * sym.cos(x) + sym.tan(x)))

z = sym.symbols('z')
print('g ->', sym.factor(x**3 + 12 * x * y * z + 3 * y**2 * z))

print('h ->', sym.solveset(x - 4, x))

matrix1 = sym.Matrix([[5, 12, 40], [30, 70, 2]])
matrix2 = sym.Matrix([2, 1, 0])
print('i ->')
sym.pprint(matrix1 * matrix2)
print()

print('j ->')
plot(x**3 + 3, (x, -10, 10))
print()

print('k ->')
plot3d(x**2 * y**3, (x, -6, 6), (y, -6, 6))
Ejemplo n.º 49
0
    def define_g_eqns(self) -> None:
        r"""
        Define eqns for metric tensor :math:`g` and its dual  :math:`g^*`.

        Attributes:
            gstar_varphi_pxpz_eqn (`Equality`_):
                :math:`g^{*} = \left[\begin{matrix}\
                \dfrac{2 p_{x}^{3} \varphi^{2}{\left(\mathbf{r} \right)}}
                {\left(p_{x}^{2} + p_{z}^{2}\right)^{\frac{3}{2}}} \
                - \dfrac{3 p_{x}^{3} \left(p_{x}^{2}
                + \dfrac{3 p_{z}^{2}}{2}\right)
                \varphi^{2}{\left(\mathbf{r} \right)}}
                {\left(p_{x}^{2} + p_{z}^{2}\right)^{\frac{5}{2}}} \
                + \dfrac{2 p_{x} \left(p_{x}^{2}
                + \dfrac{3 p_{z}^{2}}{2}\right)
                \varphi^{2}{\left(\mathbf{r} \right)}}
                {\left(p_{x}^{2} + p_{z}^{2}\right)^{\frac{3}{2}}} \
                & \dfrac{3 p_{x}^{4} p_{z}
                \varphi^{2}{\left(\mathbf{r} \right)}}{2 \left(p_{x}^{2}
                + p_{z}^{2}\right)^{\frac{5}{2}}} \
                - \dfrac{3 p_{x}^{2} p_{z}
                \varphi^{2}{\left(\mathbf{r} \right)}}
                {2 \left(p_{x}^{2} + p_{z}^{2}\right)^{\frac{3}{2}}}\\ \
                \dfrac{3 p_{x}^{2} p_{z} \varphi^{2}{\left(\mathbf{r} \right)}}
                {\left(p_{x}^{2} + p_{z}^{2}\right)^{\frac{3}{2}}} \
                - \dfrac{3 p_{x}^{2} p_{z} \left(p_{x}^{2}
                + \dfrac{3 p_{z}^{2}}{2}\right)
                \varphi^{2}{\left(\mathbf{r} \right)}}
                {\left(p_{x}^{2} + p_{z}^{2}\right)^{\frac{5}{2}}} \
                & \dfrac{3 p_{x}^{3} p_{z}^{2} \varphi^{2}
                {\left(\mathbf{r} \right)}}
                {2 \left(p_{x}^{2} + p_{z}^{2}\right)^{\frac{5}{2}}} \
                - \dfrac{p_{x}^{3} \varphi^{2}{\left(\mathbf{r} \right)}}
                {2 \left(p_{x}^{2} + p_{z}^{2}\right)^{\frac{3}{2}}}\
                \end{matrix}\right]`

            det_gstar_varphi_pxpz_eqn (`Equality`_):
                :math:`\det\left(g^*\right) \
                = \dfrac{p_{x}^{4} \left(- \dfrac{p_{x}^{2}}{2} \
                + \dfrac{3 p_{z}^{2}}{4}\right) \varphi^{4}{\left(\mathbf{r}
                \right)}}{p_{x}^{6} + 3 p_{x}^{4} p_{z}^{2}
                + 3 p_{x}^{2} p_{z}^{4} + p_{z}^{6}}`

            g_varphi_pxpz_eqn (`Equality`_):
                :math:`g = \left[\begin{matrix}\
                \dfrac{2 \left(p_{x}^{2} - 2 p_{z}^{2}\right) \sqrt{p_{x}^{2}
                + p_{z}^{2}}}{p_{x} \left(2 p_{x}^{2}
                - 3 p_{z}^{2}\right) \varphi^{2}{\left(\mathbf{r} \right)}} \
                & - \dfrac{6 p_{z}^{3} \sqrt{p_{x}^{2} + p_{z}^{2}}}{p_{x}^{2}
                \left(2 p_{x}^{2} - 3 p_{z}^{2}\right)
                \varphi^{2}{\left(\mathbf{r} \right)}}\\ \
                - \dfrac{6 p_{z}^{3} \sqrt{p_{x}^{2} + p_{z}^{2}}}{p_{x}^{2}
                \left(2 p_{x}^{2} - 3 p_{z}^{2}\right)
                \varphi^{2}{\left(\mathbf{r} \right)}} \
                & - \dfrac{4 p_{x}^{6} + 14 p_{x}^{4} p_{z}^{2}
                + 22 p_{x}^{2} p_{z}^{4} + 12 p_{z}^{6}}{p_{x}^{3}
                \sqrt{p_{x}^{2} + p_{z}^{2}} \left(2 p_{x}^{2}
                - 3 p_{z}^{2}\right) \varphi^{2}{\left(\mathbf{r}
                \right)}}\
                \end{matrix}\right]`

            gstar_eigen_varphi_pxpz (list of :class:`~sympy.core.expr.Expr`) :
                eigenvalues and eigenvectors of :math:`g^{*}` in one object

            gstar_eigenvalues (`Matrix`_):
                :math:`\left[\begin{matrix}\
                \dfrac{\varphi_0^{2} p_{x} x_{1}^{- 4 \mu} \left(\varepsilon
                x_{1}^{2 \mu} + \left(x_{1} - {r}^x\right)^{2 \mu}\right)^{2}
                \left(- 3 \left(p_{x}^{2} + p_{z}^{2}\right) \sqrt{p_{x}^{12}
                + 4 p_{x}^{10} p_{z}^{2} + 10 p_{x}^{8} p_{z}^{4}
                + 20 p_{x}^{6} p_{z}^{6} + 25 p_{x}^{4} p_{z}^{8}
                + 16 p_{x}^{2} p_{z}^{10} + 4 p_{z}^{12}} + \left(p_{x}^{2}
                + 6 p_{z}^{2}\right) \left(p_{x}^{6} + 3 p_{x}^{4} p_{z}^{2}
                + 3 p_{x}^{2} p_{z}^{4} + p_{z}^{6}\right)\right)}
                {4 \left(p_{x}^{2} + p_{z}^{2}\right)^{\frac{3}{2}}
                \left(p_{x}^{6}
                + 3 p_{x}^{4} p_{z}^{2} + 3 p_{x}^{2} p_{z}^{4}
                + p_{z}^{6}\right)}\\\
                \dfrac{\varphi_0^{2} p_{x} x_{1}^{- 4 \mu} \left(\varepsilon
                x_{1}^{2 \mu} + \left(x_{1} - {r}^x\right)^{2 \mu}\right)^{2}
                \left(3 \left(p_{x}^{2} + p_{z}^{2}\right) \sqrt{p_{x}^{12}
                + 4 p_{x}^{10} p_{z}^{2} + 10 p_{x}^{8} p_{z}^{4} + 20
                p_{x}^{6} p_{z}^{6} + 25 p_{x}^{4} p_{z}^{8} + 16 p_{x}^{2}
                p_{z}^{10} + 4 p_{z}^{12}} + \left(p_{x}^{2}
                + 6 p_{z}^{2}\right) \left(p_{x}^{6} + 3 p_{x}^{4} p_{z}^{2}
                + 3 p_{x}^{2} p_{z}^{4} + p_{z}^{6}\right)\right)}
                {4 \left(p_{x}^{2} + p_{z}^{2}\right)^{\frac{3}{2}}
                \left(p_{x}^{6} + 3 p_{x}^{4}
                p_{z}^{2} + 3 p_{x}^{2} p_{z}^{4} + p_{z}^{6}\right)}\
                \end{matrix}\right]`

            gstar_eigenvectors (list) :
                :math:`\left[\
                \begin{matrix}\dfrac{p_{x} p_{z}^{3} \left(p_{x}^{6}
                + 2 p_{x}^{4} p_{z}^{2} + 3 p_{x}^{2} p_{z}^{4} + 2 p_{z}^{6}
                + \sqrt{p_{x}^{12} + 4 p_{x}^{10} p_{z}^{2} + 10 p_{x}^{8}
                p_{z}^{4} + 20 p_{x}^{6} p_{z}^{6} + 25 p_{x}^{4} p_{z}^{8}
                + 16 p_{x}^{2} p_{z}^{10} + 4 p_{z}^{12}}\right)}{p_{x}^{10}
                + 3 p_{x}^{8} p_{z}^{2} + 7 p_{x}^{6} p_{z}^{4} + 11 p_{x}^{4}
                p_{z}^{6} + p_{x}^{4} \sqrt{p_{x}^{12} + 4 p_{x}^{10}
                p_{z}^{2} + 10 p_{x}^{8} p_{z}^{4} + 20 p_{x}^{6} p_{z}^{6}
                + 25 p_{x}^{4} p_{z}^{8} + 16 p_{x}^{2}p_{z}^{10}+4 p_{z}^{12}}
                + 10 p_{x}^{2} p_{z}^{8} + p_{x}^{2} p_{z}^{2} \sqrt{p_{x}^{12}
                + 4 p_{x}^{10} p_{z}^{2} + 10 p_{x}^{8} p_{z}^{4} +20 p_{x}^{6}
                p_{z}^{6} + 25 p_{x}^{4} p_{z}^{8} + 16 p_{x}^{2} p_{z}^{10}
                + 4 p_{z}^{12}} + 4 p_{z}^{10} + 2 p_{z}^{4} \sqrt{p_{x}^{12}
                + 4 p_{x}^{10} p_{z}^{2} + 10 p_{x}^{8} p_{z}^{4} + 20p_{x}^{6}
                p_{z}^{6} + 25 p_{x}^{4} p_{z}^{8} + 16 p_{x}^{2} p_{z}^{10}
                + 4 p_{z}^{12}}}\\ \
                1 \
                \end{matrix}\
                \right] \\ \
                \left[\
                \begin{matrix}\dfrac{p_{x} p_{z}^{3} \left(p_{x}^{6}
                + 2 p_{x}^{4} p_{z}^{2} + 3 p_{x}^{2} p_{z}^{4} + 2 p_{z}^{6}
                - \sqrt{p_{x}^{12} + 4 p_{x}^{10} p_{z}^{2} + 10 p_{x}^{8}
                p_{z}^{4} + 20 p_{x}^{6} p_{z}^{6} + 25 p_{x}^{4} p_{z}^{8}
                + 16 p_{x}^{2} p_{z}^{10} + 4 p_{z}^{12}}\right)}{p_{x}^{10}
                + 3 p_{x}^{8} p_{z}^{2} + 7 p_{x}^{6} p_{z}^{4} + 11 p_{x}^{4}
                p_{z}^{6} - p_{x}^{4} \sqrt{p_{x}^{12} + 4 p_{x}^{10} p_{z}^{2}
                + 10 p_{x}^{8} p_{z}^{4} + 20 p_{x}^{6} p_{z}^{6}
                + 25 p_{x}^{4} p_{z}^{8} + 16 p_{x}^{2} p_{z}^{10}
                + 4 p_{z}^{12}} + 10 p_{x}^{2} p_{z}^{8} - p_{x}^{2} p_{z}^{2}
                \sqrt{p_{x}^{12} + 4 p_{x}^{10} p_{z}^{2} + 10 p_{x}^{8}
                p_{z}^{4} + 20 p_{x}^{6} p_{z}^{6} + 25 p_{x}^{4} p_{z}^{8}
                + 16 p_{x}^{2} p_{z}^{10} + 4 p_{z}^{12}} + 4 p_{z}^{10} -
                2 p_{z}^{4} \sqrt{p_{x}^{12} + 4 p_{x}^{10} p_{z}^{2} +
                10 p_{x}^{8} p_{z}^{4} + 20 p_{x}^{6} p_{z}^{6} + 25 p_{x}^{4}
                p_{z}^{8} + 16 p_{x}^{2} p_{z}^{10} + 4 p_{z}^{12}}}\\ \
                1 \
                \end{matrix}\right]`
        """
        logging.info("gme.core.metrictensor.define_g_eqns")
        self.gstar_varphi_pxpz_eqn = None
        self.det_gstar_varphi_pxpz_eqn = None
        self.g_varphi_pxpz_eqn = None
        self.gstar_eigen_varphi_pxpz = None
        self.gstar_eigenvalues = None
        self.gstar_eigenvectors = None

        eta_sub = {eta: self.eta_}
        self.gstar_varphi_pxpz_eqn = Eq(
            gstar,
            factor(
                Matrix([
                    diff(self.rdot_vec_eqn.rhs, self.p_covec_eqn.rhs[0]).T,
                    diff(self.rdot_vec_eqn.rhs, self.p_covec_eqn.rhs[1]).T,
                ])),
        ).subs(eta_sub)
        self.det_gstar_varphi_pxpz_eqn = Eq(
            det_gstar,
            (simplify(self.gstar_varphi_pxpz_eqn.rhs.subs(eta_sub).det())),
        )
        if self.eta_ == 1 and self.beta_type == "sin":
            print(r"Cannot compute all metric tensor $g^{ij}$ equations " +
                  r"for $\sin\beta$ model and $\eta=1$")
            return
        self.g_varphi_pxpz_eqn = Eq(
            g,
            simplify(self.gstar_varphi_pxpz_eqn.rhs.subs(eta_sub).inverse()))
        self.gstar_eigen_varphi_pxpz = (
            self.gstar_varphi_pxpz_eqn.rhs.eigenvects())
        self.gstar_eigenvalues = simplify(
            Matrix([
                self.gstar_eigen_varphi_pxpz[0][0],
                self.gstar_eigen_varphi_pxpz[1][0],
            ]).subs({varphi_r(rvec): self.varphi_rx_eqn.rhs}))
        self.gstar_eigenvectors = [
            simplify(
                Matrix(self.gstar_eigen_varphi_pxpz[0][2][0]).subs(
                    {varphi_r(rvec): self.varphi_rx_eqn.rhs})),
            simplify(
                Matrix(self.gstar_eigen_varphi_pxpz[1][2][0]).subs(
                    {varphi_r(rvec): self.varphi_rx_eqn.rhs})),
        ]
Ejemplo n.º 50
0
    def _create_char_eq(self):
        r = sympy.Symbol('r')
        #
        # # build the dictionary where we link every constant to every a_n value
        # dicts = {}
        # self._dictBuilder(self._recurrence, dicts)
        #
        # # start building our new expression!
        # newExpr = r ** self._degree
        # for i in range(1, self._degree + 1):
        #     newExpr = newExpr - dicts.get(-i, 0) * r ** (self._degree - i)

        # anc = self._anc_dict
        #
        # r = sympy.Symbol('r')
        # degree = ((self._degree)*-1)
        # #char_eq = r ** degree
        # char_eq = 'r**{}'.format(degree)
        #
        # ordered_anc = sorted(anc.keys(), reverse=True)
        # ordered_const = ['({})'.format(anc[v]) for v in ordered_anc]
        #
        # for c, an in enumerate(range(0,len(ordered_anc))):
        #     char_eq = '{} - {} * r**{}'.format(char_eq, ordered_const[c], degree+ordered_anc[an])
        #     # char_eq = char_eq - ordered_const[c] * r**(degree +ordered_anc[an])
        #
        # print('charasteric equation: {}'.format(char_eq))
        # print(sympy.factor(char_eq))
        # print(sympy.roots(sympy.sympify(char_eq)))
        # print(len(sympy.roots(char_eq)))
        #
        # rdict = {s: m for (s, m) in sympy.roots(char_eq).items() if sympy.I not in s.atoms()}
        #
        # print('roots without imaginary: {}'.format(rdict))
        # self._char_eq = char_eq

        anc = self._anc_dict

        r = sympy.Symbol('r')
        degree = ((self._degree) * -1)
        char_eq = r**degree

        ordered_anc = sorted(anc.keys(), reverse=True)
        ordered_const = [anc[v] for v in ordered_anc]

        for c, an in enumerate(range(0, len(ordered_anc))):
            char_eq = char_eq - ordered_const[c] * r**(degree +
                                                       ordered_anc[an])

        print('charasteric equation: {}'.format(char_eq))
        print(sympy.factor(char_eq))
        print(sympy.roots(char_eq))
        print(len(sympy.roots(char_eq)))

        rdict = {
            s: m
            for (s, m) in sympy.roots(char_eq).items()
            if sympy.I not in s.atoms()
        }

        print('roots without imaginary: {}'.format(rdict))
        self._char_eq = char_eq
Ejemplo n.º 51
0
def design_z_filter_single_pole(filt_str, max_gain_freq):
    """
  Finds the coefficients for a simple lowpass/highpass filter.

  This function just prints the coefficient values, besides the given
  filter equation and its power gain. There's 3 constraints used to find the
  coefficients:

  1. The G value is defined by the max gain of 1 (0 dB) imposed at a
     specific frequency
  2. The R value is defined by the 50% power cutoff frequency given in
     rad/sample.
  3. Filter should be stable (-1 < R < 1)

  Parameters
  ----------
  filt_str :
    Filter equation as a string using the G, R, w and z values.
  max_gain_freq :
    A value of zero (DC) or pi (Nyquist) to ensure the max gain as 1 (0 dB).

  Note
  ----
  The R value is evaluated only at pi/4 rad/sample to find whether -1 < R < 1,
  and the max gain is assumed to be either 0 or pi, using other values might
  fail.
  """
    print("H(z) = " + filt_str)  # Avoids printing as "1/z"
    filt = sympify(filt_str, dict(G=G, R=R, w=w, z=z))
    print()

    # Finds the power magnitude equation for the filter
    freq_resp = filt.subs(z, exp(I * w))
    frr, fri = freq_resp.as_real_imag()
    power_resp = fcompose(expand_complex, cancel, trigsimp)(frr**2 + fri**2)
    pprint(Eq(Symbol("Power"), power_resp))
    print()

    # Finds the G value given the max gain value of 1 at the DC or Nyquist
    # frequency. As exp(I*pi) is -1 and exp(I*0) is 1, we can use freq_resp
    # (without "abs") instead of power_resp.
    Gsolutions = factor(solve(Eq(freq_resp.subs(w, max_gain_freq), 1), G))
    assert len(Gsolutions) == 1
    pprint(Eq(G, Gsolutions[0]))
    print()

    # Finds the unconstrained R values for a given cutoff frequency
    power_resp_no_G = power_resp.subs(G, Gsolutions[0])
    half_power_eq = Eq(power_resp_no_G, S.Half)
    Rsolutions = solve(half_power_eq, R)

    # Constraining -1 < R < 1 when w = pi/4 (although the constraint is general)
    Rsolutions_stable = [
        el for el in Rsolutions if -1 < el.subs(w, pi / 4) < 1
    ]
    assert len(Rsolutions_stable) == 1

    # Constraining w to the [0;pi] range, so |sin(w)| = sin(w)
    Rsolution = Rsolutions_stable[0].subs(abs(sin(w)), sin(w))
    pprint(Eq(R, Rsolution))

    # More information about the pole (or -pole)
    print("\n  ** Alternative way to write R **\n")
    if has_sqrt(Rsolution):
        x = Symbol("x")  # A helper symbol
        xval = sum(el for el in Rsolution.args if not has_sqrt(el))
        pprint(Eq(x, xval))
        print()
        pprint(Eq(R, expand(Rsolution.subs(xval, x))))
    else:
        # That's also what would be found in a bilinear transform with prewarping
        pprint(Eq(R,
                  Rsolution.rewrite(tan).cancel()))  # Not so nice numerically

        # See whether the R denominator can be zeroed
        for root in solve(fraction(Rsolution)[1], w):
            if 0 <= root <= pi:
                power_resp_r = fcompose(expand,
                                        cancel)(power_resp_no_G.subs(w, root))
                Rsolutions_r = solve(Eq(power_resp_r, S.Half), R)
                assert len(Rsolutions_r) == 1
                print("\nDenominator is zero for this value of " + pretty(w))
                pprint(Eq(w, root))
                pprint(Eq(R, Rsolutions_r[0]))
Ejemplo n.º 52
0
def test_nsimplify():
    x = Symbol("x")
    assert nsimplify(0) == 0
    assert nsimplify(-1) == -1
    assert nsimplify(1) == 1
    assert nsimplify(1 + x) == 1 + x
    assert nsimplify(2.7) == Rational(27, 10)
    assert nsimplify(1 - GoldenRatio) == (1 - sqrt(5))/2
    assert nsimplify((1 + sqrt(5))/4, [GoldenRatio]) == GoldenRatio/2
    assert nsimplify(2/GoldenRatio, [GoldenRatio]) == 2*GoldenRatio - 2
    assert nsimplify(exp(5*pi*I/3, evaluate=False)) == \
        sympify('1/2 - sqrt(3)*I/2')
    assert nsimplify(sin(3*pi/5, evaluate=False)) == \
        sympify('sqrt(sqrt(5)/8 + 5/8)')
    assert nsimplify(sqrt(atan('1', evaluate=False))*(2 + I), [pi]) == \
        sqrt(pi) + sqrt(pi)/2*I
    assert nsimplify(2 + exp(2*atan('1/4')*I)) == sympify('49/17 + 8*I/17')
    assert nsimplify(pi, tolerance=0.01) == Rational(22, 7)
    assert nsimplify(pi, tolerance=0.001) == Rational(355, 113)
    assert nsimplify(0.33333, tolerance=1e-4) == Rational(1, 3)
    assert nsimplify(2.0**(1/3.), tolerance=0.001) == Rational(635, 504)
    assert nsimplify(2.0**(1/3.), tolerance=0.001, full=True) == \
        2**Rational(1, 3)
    assert nsimplify(x + .5, rational=True) == Rational(1, 2) + x
    assert nsimplify(1/.3 + x, rational=True) == Rational(10, 3) + x
    assert nsimplify(log(3).n(), rational=True) == \
        sympify('109861228866811/100000000000000')
    assert nsimplify(Float(0.272198261287950), [pi, log(2)]) == pi*log(2)/8
    assert nsimplify(Float(0.272198261287950).n(3), [pi, log(2)]) == \
        -pi/4 - log(2) + S(7)/4
    assert nsimplify(x/7.0) == x/7
    assert nsimplify(pi/1e2) == pi/100
    assert nsimplify(pi/1e2, rational=False) == pi/100.0
    assert nsimplify(pi/1e-7) == 10000000*pi
    assert not nsimplify(
        factor(-3.0*z**2*(z**2)**(-2.5) + 3*(z**2)**(-1.5))).atoms(Float)
    e = x**0.0
    assert e.is_Pow and nsimplify(x**0.0) == 1
    assert nsimplify(3.333333, tolerance=0.1, rational=True) == Rational(10, 3)
    assert nsimplify(3.333333, tolerance=0.01, rational=True) == Rational(10, 3)
    assert nsimplify(3.666666, tolerance=0.1, rational=True) == Rational(11, 3)
    assert nsimplify(3.666666, tolerance=0.01, rational=True) == Rational(11, 3)
    assert nsimplify(33, tolerance=10, rational=True) == Rational(33)
    assert nsimplify(33.33, tolerance=10, rational=True) == Rational(30)
    assert nsimplify(37.76, tolerance=10, rational=True) == Rational(40)
    assert nsimplify(-203.1) == -S(2031)/10
    assert nsimplify(.2, tolerance=0) == S.One/5
    assert nsimplify(-.2, tolerance=0) == -S.One/5
    assert nsimplify(.2222, tolerance=0) == S(1111)/5000
    assert nsimplify(-.2222, tolerance=0) == -S(1111)/5000
    # issue 7211, PR 4112
    assert nsimplify(S(2e-8)) == S(1)/50000000
    # issue 7322 direct test
    assert nsimplify(1e-42, rational=True) != 0
    # issue 10336
    inf = Float('inf')
    infs = (-oo, oo, inf, -inf)
    for i in infs:
        ans = sign(i)*oo
        assert nsimplify(i) == ans
        assert nsimplify(i + x) == x + ans

    assert nsimplify(0.33333333, rational=True, rational_conversion='exact') == Rational(0.33333333)

    # Make sure nsimplify on expressions uses full precision
    assert nsimplify(pi.evalf(100)*x, rational_conversion='exact').evalf(100) == pi.evalf(100)*x
Ejemplo n.º 53
0
import sympy.physics.mechanics as me
import sympy as sm
import math as m
import numpy as np

x, y = me.dynamicsymbols('x y')
a, b = sm.symbols('a b', real=True)
e = a * (b * x + y)**2
m = sm.Matrix([e, e]).reshape(2, 1)
e = e.expand()
m = sm.Matrix([i.expand() for i in m]).reshape((m).shape[0], (m).shape[1])
e = sm.factor(e, x)
m = sm.Matrix([sm.factor(i, x) for i in m]).reshape((m).shape[0], (m).shape[1])
eqn = sm.Matrix([[0]])
eqn[0] = a * x + b * y
eqn = eqn.row_insert(eqn.shape[0], sm.Matrix([[0]]))
eqn[eqn.shape[0] - 1] = 2 * a * x - 3 * b * y
print(sm.solve(eqn, x, y))
rhs_y = sm.solve(eqn, x, y)[y]
e = (x + y)**2 + 2 * x**2
e.collect(x)
a, b, c = sm.symbols('a b c', real=True)
m = sm.Matrix([a, b, c, 0]).reshape(2, 2)
m2 = sm.Matrix([i.subs({
    a: 1,
    b: 2,
    c: 3
}) for i in m]).reshape((m).shape[0], (m).shape[1])
eigvalue = sm.Matrix([i.evalf() for i in (m2).eigenvals().keys()])
eigvec = sm.Matrix([i[2][0].evalf() for i in (m2).eigenvects()
                    ]).reshape(m2.shape[0], m2.shape[1])
Ejemplo n.º 54
0
def test_issue_6387():
    assert str(factor(-3.0*z + 3)) == '-3.0*(1.0*z - 1.0)'
Ejemplo n.º 55
0
def test_H29():
    assert factor(4 * x**2 - 21 * x * y + 20 * y**2,
                  modulus=3) == (x + y) * (x - y)
Ejemplo n.º 56
0
def quadratic_factor(quad_val):
    return sympy.factor(quad_val)
Ejemplo n.º 57
0
def test_H30():
    test = factor(x**3 + y**3, extension=sqrt(-3))
    answer = (x + y) * (x + y * (-R(1, 2) - sqrt(3) / 2 * I)) * (
        x + y * (-R(1, 2) + sqrt(3) / 2 * I))
    assert answer == test
Ejemplo n.º 58
0
def deltaproduct(f, limit):
    """
    Handle products containing a KroneckerDelta.

    See Also
    ========

    deltasummation
    sympy.functions.special.tensor_functions.KroneckerDelta
    sympy.concrete.products.product
    """
    from sympy.concrete.products import product

    if ((limit[2] - limit[1]) < 0) is True:
        return S.One

    if not f.has(KroneckerDelta):
        return product(f, limit)

    if f.is_Add:
        # Identify the term in the Add that has a simple KroneckerDelta
        delta = None
        terms = []
        for arg in sorted(f.args, key=default_sort_key):
            if delta is None and _has_simple_delta(arg, limit[0]):
                delta = arg
            else:
                terms.append(arg)
        newexpr = f.func(*terms)
        k = Dummy("kprime", integer=True)
        if isinstance(limit[1], int) and isinstance(limit[2], int):
            result = deltaproduct(newexpr, limit) + sum([
                deltaproduct(newexpr, (limit[0], limit[1], ik - 1)) *
                delta.subs(limit[0], ik) *
                deltaproduct(newexpr, (limit[0], ik + 1, limit[2]))
                for ik in range(int(limit[1]), int(limit[2] + 1))
            ])
        else:
            result = deltaproduct(newexpr, limit) + deltasummation(
                deltaproduct(newexpr, (limit[0], limit[1], k - 1)) *
                delta.subs(limit[0], k) *
                deltaproduct(newexpr, (limit[0], k + 1, limit[2])),
                (k, limit[1], limit[2]),
                no_piecewise=_has_simple_delta(newexpr, limit[0]))
        return _remove_multiple_delta(result)

    delta, _ = _extract_delta(f, limit[0])

    if not delta:
        g = _expand_delta(f, limit[0])
        if f != g:
            from sympy import factor
            try:
                return factor(deltaproduct(g, limit))
            except AssertionError:
                return deltaproduct(g, limit)
        return product(f, limit)

    from sympy import Eq
    c = Eq(limit[2], limit[1] - 1)
    return _remove_multiple_delta(f.subs(limit[0], limit[1])*KroneckerDelta(limit[2], limit[1])) + \
        S.One*_simplify_delta(KroneckerDelta(limit[2], limit[1] - 1))
Ejemplo n.º 59
0
#x**2+y+1
print(expr.subs(x, 1))
# y+2
print(expr.subs(x, y))
# y**2+y+1
print(expr.subs([(x, 1), (y, 2)]))
# 4

expr = (x + 1)**2
print(expr)

expr_ex = sympy.expand(expr)  #式の展開
print(expr_ex)

expr_ex = x**2 + 2 * x + 1
expr = sympy.factor(expr_ex)  #因数分解
print(expr)

print(sympy.factor(x**3 - x**2 - 3 * x + 3))
print(sympy.factor(x * y + x + y + 1))

expr1 = 3 * x + 5 * y - 29
expr2 = x + y - 7
print(sympy.solve([expr1, expr2]))
#rennrituhouteisiki
#{x: 3, y: 4}

print(sympy.diff(x**3 + 2 * x**2 + x))
#bibunn
#3*x**2 + 4*x + 1
Ejemplo n.º 60
0
    def __init__(self, **kwargs):
        if 'seed' in kwargs:
            self.seed = kwargs['seed']
        else:
            self.seed = random.random()
        random.seed(self.seed)

        x = sy.Symbol('x')

        self.type_of_problem = random.choice([
            'easyFactorExpr', 'factorByGroupingExpr', 'specialPatternExpr',
            'fancyFactorExpr', 'quadraticPatternExpr'
        ])

        # self.type_of_problem = 'easyFactorExpr'
        # self.type_of_problem = 'quadraticPatternExpr'
        # self.type_of_problem = 'specialPatternExpr'
        # self.type_of_problem = 'factorByGroupingExpr'

        if self.type_of_problem == 'quadraticPatternExpr':
            p = 0
            while p == 0:
                p = random.randint(-7, 7)
            q = 0
            while q == 0:
                q = random.randint(-5, 5)
            r = random.randint(2, 6)
            expr = 1
            for num in [p, q]:
                new_r = r
                depth = 1
                while new_r / 2 % 1 == 0 and num < 0 and (-num)**(
                        1 / (depth + 1)) % 1 == 0:
                    depth += 1
                    new_r = int(new_r / 2)
                    expr *= (x**new_r + int((-num)**(1 / depth)))
                if new_r < r:
                    expr *= (x**new_r - int((abs(num))**(1 / depth)))
                else:
                    expr *= (x**r + num)
        if self.type_of_problem == 'fancyFactorExpr':
            m = random.randint(2, 5)
            p = random.choice([-5, -3, -2, -1, 1, 2, 3, 5])
            n = random.choice([-5, -3, -2, -1, 1, 2, 3, 5])
            q = random.choice([-5, -3, -2, -1, 1, 2, 3, 5])
            expr = (m * x + p) * (n * x + q)
        if self.type_of_problem == 'specialPatternExpr':
            a = random.randint(1, 9)
            b = random.randint(1, 9)
            sign1 = random.choice([-1, 1])
            sign2 = random.choice([-1, 1])
            x, t, r, y = sy.symbols('x t r y')
            vars = random.choice([(x, 1), (x, y), (r, t), (y, 1)])
            # vars = (r,t)
            x = vars[0]
            A = a * vars[0]
            B1 = sign1 * b * vars[1]
            B2 = sign2 * b * vars[1]
            expr = (A + B1) * (A + B2)
        if self.type_of_problem == 'factorByGroupingExpr':
            a = 0
            while a == 0:
                a = random.randint(-5, 5)
            b = 0
            while b == 0:
                b = random.randint(-5, 5)
            c = 0
            while c == 0:
                c = random.randint(-5, 5)
            d = 0
            while d == 0:
                d = random.randint(-5, 5)
            x, t, r, y = sy.symbols('x t r y')
            vars = random.choice([(x, 1), (x, y), (r, t)])
            # vars = [x,1]
            x = vars[0]
            A = a * vars[0]**2
            C = c * vars[1]
            B = b * vars[0]
            D = d * vars[1]

            def is_perfect_square(num):
                return float(sy.sqrt(num)) % 1 == 0

            def check_for_square_minus_square(a, b):
                if (a < 0 and b < 0) or (a > 0 and b > 0):
                    return False
                if is_perfect_square(abs(a)) and is_perfect_square(abs(b)):
                    return True
                return False

            if check_for_square_minus_square(a, c):
                expr1 = sy.factor(A + C)
            else:
                expr1 = A + C
            expr = expr1 * (B + D)
        if self.type_of_problem == 'easyFactorExpr':
            p = 0
            while p == 0:
                p = random.randint(-9, 9)
            q = 0
            while q == 0:
                q = random.randint(-9, 9)
            b = p + q
            c = p * q
            expr = x**2 + b * x + c
            expr = sy.factor(expr)
        random.seed(
            self.seed
        )  #Why do I have to put this here??? ... meaning, I put it here to get consistent behavior from the random generator, but why do I need to do that?
        A = 0
        while A == 0:
            A = random.randint(-7, 7)
        e = random.randint(0, 5)

        GCF = A * x**e

        expr = GCF * expr

        self.answer = expr
        # expr1 = sy.factor(A+B1)*(A+B2)
        # expr2 = (A+B1)*sy.factor(A+B2)
        # expr3 = sy.factor((A+B1)*(A+B2))
        # self.answers = [expr, expr1, expr2, expr3]
        self.format_answer = f'\( {sy.latex(self.answer)}\)'

        self.format_given = f"\\[{sy.latex(sy.expand(self.answer))} \\]"

        self.format_given_for_tex = f"""