def test_reduce_poly_inequalities_complex_relational():
    cond = Eq(im(x), 0)

    assert reduce_poly_inequalities(
        [[Eq(x**2, 0)]], x, relational=True) == And(Eq(re(x), 0), cond)
    assert reduce_poly_inequalities(
        [[Le(x**2, 0)]], x, relational=True) == And(Eq(re(x), 0), cond)
    assert reduce_poly_inequalities(
        [[Lt(x**2, 0)]], x, relational=True) is False
    assert reduce_poly_inequalities(
        [[Ge(x**2, 0)]], x, relational=True) == cond
    assert reduce_poly_inequalities([[Gt(x**2, 0)]], x, relational=True) == And(Or(Lt(re(x), 0), Lt(0, re(x))), cond)
    assert reduce_poly_inequalities([[Ne(x**2, 0)]], x, relational=True) == And(Or(Lt(re(x), 0), Lt(0, re(x))), cond)

    assert reduce_poly_inequalities([[Eq(x**2, 1)]], x, relational=True) == And(Or(Eq(re(x), -1), Eq(re(x), 1)), cond)
    assert reduce_poly_inequalities([[Le(x**2, 1)]], x, relational=True) == And(And(Le(-1, re(x)), Le(re(x), 1)), cond)
    assert reduce_poly_inequalities([[Lt(x**2, 1)]], x, relational=True) == And(And(Lt(-1, re(x)), Lt(re(x), 1)), cond)
    assert reduce_poly_inequalities([[Ge(x**2, 1)]], x, relational=True) == And(Or(Le(re(x), -1), Le(1, re(x))), cond)
    assert reduce_poly_inequalities([[Gt(x**2, 1)]], x, relational=True) == And(Or(Lt(re(x), -1), Lt(1, re(x))), cond)
    assert reduce_poly_inequalities([[Ne(x**2, 1)]], x, relational=True) == And(Or(Lt(re(x), -1), And(Lt(-1, re(x)), Lt(re(x), 1)), Lt(1, re(x))), cond)

    assert reduce_poly_inequalities([[Eq(x**2, 1.0)]], x, relational=True).evalf() == And(Or(Eq(re(x), -1.0), Eq(re(x), 1.0)), cond)
    assert reduce_poly_inequalities([[Le(x**2, 1.0)]], x, relational=True) == And(And(Le(-1.0, re(x)), Le(re(x), 1.0)), cond)
    assert reduce_poly_inequalities([[Lt(x**2, 1.0)]], x, relational=True) == And(And(Lt(-1.0, re(x)), Lt(re(x), 1.0)), cond)
    assert reduce_poly_inequalities([[Ge(x**2, 1.0)]], x, relational=True) == And(Or(Le(re(x), -1.0), Le(1.0, re(x))), cond)
    assert reduce_poly_inequalities([[Gt(x**2, 1.0)]], x, relational=True) == And(Or(Lt(re(x), -1.0), Lt(1.0, re(x))), cond)
    assert reduce_poly_inequalities([[Ne(x**2, 1.0)]], x, relational=True) == And(Or(Lt(re(x), -1.0), And(Lt(-1.0, re(x)), Lt(re(x), 1.0)), Lt(1.0, re(x))), cond)
Example #2
0
def test_f_expand_complex():
    x = Symbol("x", real=True)

    assert f(x).expand(complex=True) == I * im(f(x)) + re(f(x))
    assert exp(x).expand(complex=True) == exp(x)
    assert exp(I * x).expand(complex=True) == cos(x) + I * sin(x)
    assert exp(z).expand(complex=True) == cos(im(z)) * exp(re(z)) + I * sin(im(z)) * exp(re(z))
Example #3
0
    def _generic_mul(q1, q2):

        q1 = sympify(q1)
        q2 = sympify(q2)

        # None is a Quaternion:
        if not isinstance(q1, Quaternion) and not isinstance(q2, Quaternion):
            return q1 * q2

        # If q1 is a number or a sympy expression instead of a quaternion
        if not isinstance(q1, Quaternion):
            if q2.real_field:
                if q1.is_complex:
                    return q2 * Quaternion(re(q1), im(q1), 0, 0)
                else:
                    return Mul(q1, q2)
            else:
                return Quaternion(q1 * q2.a, q1 * q2.b, q1 * q2.c, q1 * q2.d)


        # If q2 is a number or a sympy expression instead of a quaternion
        if not isinstance(q2, Quaternion):
            if q1.real_field:
                if q2.is_complex:
                    return q1 * Quaternion(re(q2), im(q2), 0, 0)
                else:
                    return Mul(q1, q2)
            else:
                return Quaternion(q2 * q1.a, q2 * q1.b, q2 * q1.c, q2 * q1.d)

        return Quaternion(-q1.b*q2.b - q1.c*q2.c - q1.d*q2.d + q1.a*q2.a,
                          q1.b*q2.a + q1.c*q2.d - q1.d*q2.c + q1.a*q2.b,
                          -q1.b*q2.d + q1.c*q2.a + q1.d*q2.b + q1.a*q2.c,
                          q1.b*q2.c - q1.c*q2.b + q1.d*q2.a + q1.a * q2.d)
Example #4
0
def test_real_imag():
    x, y, z = symbols('x, y, z')
    X, Y, Z = symbols('X, Y, Z', commutative=False)
    a = Symbol('a', real=True)
    assert (2*a*x).as_real_imag() == (2*a*re(x), 2*a*im(x))

    # issue 2296:
    assert (x*x.conjugate()).as_real_imag() == (Abs(x)**2, 0)
    assert im(x*x.conjugate()) == 0
    assert im(x*y.conjugate()*z*y) == im(x*z)*Abs(y)**2
    assert im(x*y.conjugate()*x*y) == im(x**2)*Abs(y)**2
    assert im(Z*y.conjugate()*X*y) == im(Z*X)*Abs(y)**2
    assert im(X*X.conjugate()) == im(X*X.conjugate(), evaluate=False)
    assert (sin(x)*sin(x).conjugate()).as_real_imag() == \
        (Abs(sin(x))**2, 0)

    # issue 3474:
    assert (x**2).as_real_imag() == (re(x)**2 - im(x)**2, 2*re(x)*im(x))

    # issue 3329:
    r = Symbol('r', real=True)
    i = Symbol('i', imaginary=True)
    assert (i*r*x).as_real_imag() == (I*i*r*im(x), -I*i*r*re(x))

    # issue 4007:
    assert ((1 + I)/(1 - I)).as_real_imag() == (0, 1)
    assert ((1 + 2*I)*(1 + 3*I)).as_real_imag() == (-5, 5)
Example #5
0
def test_im():
    x, y = symbols('x,y')
    a, b = symbols('a,b', real=True)

    r = Symbol('r', real=True)
    i = Symbol('i', imaginary=True)

    assert im(nan) == nan

    assert im(oo*I) == oo
    assert im(-oo*I) == -oo

    assert im(0) == 0

    assert im(1) == 0
    assert im(-1) == 0

    assert im(E*I) == E
    assert im(-E*I) == -E

    assert im(x) == im(x)
    assert im(x*I) == re(x)
    assert im(r*I) == r
    assert im(r) == 0
    assert im(i*I) == 0
    assert im(i) == -I * i

    assert im(x + y) == im(x + y)
    assert im(x + r) == im(x)
    assert im(x + r*I) == im(x) + r

    assert im(im(x)*I) == im(x)

    assert im(2 + I) == 1
    assert im(x + I) == im(x) + 1

    assert im(x + y*I) == im(x) + re(y)
    assert im(x + r*I) == im(x) + r

    assert im(log(2*I)) == pi/2

    assert im((2 + I)**2).expand(complex=True) == 4

    assert im(conjugate(x)) == -im(x)
    assert conjugate(im(x)) == im(x)

    assert im(x).as_real_imag() == (im(x), 0)

    assert im(i*r*x).diff(r) == im(i*x)
    assert im(i*r*x).diff(i) == -I * re(r*x)

    assert im(
        sqrt(a + b*I)) == (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)
    assert im(a * (2 + b*I)) == a*b

    assert im((1 + sqrt(a + b*I))/2) == \
        (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2

    assert im(x).rewrite(re) == x - re(x)
    assert (x + im(y)).rewrite(im, re) == x + y - re(y)
Example #6
0
def test_solve_inequalities():
    system = [Lt(x ** 2 - 2, 0), Gt(x ** 2 - 1, 0)]

    assert solve(system) == And(
        Or(And(Lt(-sqrt(2), re(x)), Lt(re(x), -1)), And(Lt(1, re(x)), Lt(re(x), sqrt(2)))), Eq(im(x), 0)
    )
    assert solve(system, assume=Q.real(x)) == Or(And(Lt(-sqrt(2), x), Lt(x, -1)), And(Lt(1, x), Lt(x, sqrt(2))))
Example #7
0
def test_mellin_transform_fail():
    skip("Risch takes forever.")

    from sympy import Max, Min
    MT = mellin_transform

    bpos = symbols('b', positive=True)
    bneg = symbols('b', negative=True)

    expr = (sqrt(x + b**2) + b)**a/sqrt(x + b**2)
    # TODO does not work with bneg, argument wrong. Needs changes to matching.
    assert MT(expr.subs(b, -bpos), x, s) == \
        ((-1)**(a + 1)*2**(a + 2*s)*bpos**(a + 2*s - 1)*gamma(a + s)
         *gamma(1 - a - 2*s)/gamma(1 - s),
            (-re(a), -re(a)/2 + S(1)/2), True)

    expr = (sqrt(x + b**2) + b)**a
    assert MT(expr.subs(b, -bpos), x, s) == \
        (
            2**(a + 2*s)*a*bpos**(a + 2*s)*gamma(-a - 2*
                   s)*gamma(a + s)/gamma(-s + 1),
            (-re(a), -re(a)/2), True)

    # Test exponent 1:
    assert MT(expr.subs({b: -bpos, a: 1}), x, s) == \
        (-bpos**(2*s + 1)*gamma(s)*gamma(-s - S(1)/2)/(2*sqrt(pi)),
            (-1, -S(1)/2), True)
Example #8
0
def test_messy():
    from sympy import (laplace_transform, Si, Shi, Chi, atan, Piecewise,
                       acoth, E1, besselj, acosh, asin, And, re,
                       fourier_transform, sqrt)
    assert laplace_transform(Si(x), x, s) == ((-atan(s) + pi/2)/s, 0, True)

    assert laplace_transform(Shi(x), x, s) == (acoth(s)/s, 1, True)

    # where should the logs be simplified?
    assert laplace_transform(Chi(x), x, s) == \
        ((log(s**(-2)) - log((s**2 - 1)/s**2))/(2*s), 1, True)

    # TODO maybe simplify the inequalities?
    assert laplace_transform(besselj(a, x), x, s)[1:] == \
        (0, And(S(0) < re(a/2) + S(1)/2, S(0) < re(a/2) + 1))

    # NOTE s < 0 can be done, but argument reduction is not good enough yet
    assert fourier_transform(besselj(1, x)/x, x, s, noconds=False) == \
        (Piecewise((0, 4*abs(pi**2*s**2) > 1),
                   (2*sqrt(-4*pi**2*s**2 + 1), True)), s > 0)
    # TODO FT(besselj(0,x)) - conditions are messy (but for acceptable reasons)
    #                       - folding could be better

    assert integrate(E1(x)*besselj(0, x), (x, 0, oo), meijerg=True) == \
        log(1 + sqrt(2))
    assert integrate(E1(x)*besselj(1, x), (x, 0, oo), meijerg=True) == \
        log(S(1)/2 + sqrt(2)/2)

    assert integrate(1/x/sqrt(1 - x**2), x, meijerg=True) == \
        Piecewise((-acosh(1/x), 1 < abs(x**(-2))), (I*asin(1/x), True))
Example #9
0
def test_as_real_imag():
    n = pi**1000
    # the special code for working out the real
    # and complex parts of a power with Integer exponent
    # should not run if there is no imaginary part, hence
    # this should not hang
    assert n.as_real_imag() == (n, 0)

    # issue 6261
    x = Symbol('x')
    assert sqrt(x).as_real_imag() == \
        ((re(x)**2 + im(x)**2)**(S(1)/4)*cos(atan2(im(x), re(x))/2),
     (re(x)**2 + im(x)**2)**(S(1)/4)*sin(atan2(im(x), re(x))/2))

    # issue 3853
    a, b = symbols('a,b', real=True)
    assert ((1 + sqrt(a + b*I))/2).as_real_imag() == \
           (
               (a**2 + b**2)**Rational(
                   1, 4)*cos(atan2(b, a)/2)/2 + Rational(1, 2),
               (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2)

    assert sqrt(a**2).as_real_imag() == (sqrt(a**2), 0)
    i = symbols('i', imaginary=True)
    assert sqrt(i**2).as_real_imag() == (0, abs(i))
Example #10
0
def horo_image_height(M,z,h):
    # assert linalg.det(M) == 1
    c = get_c(M)
    d = get_d(M)
    if c*z + d != 0 :
        return h / sym.re((c*z + d)*(c*z + d).conjugate())
    else :
        return 1 / sym.re(h * c * c.conjugate())
Example #11
0
def test_derivatives_issue1658():
    x = Symbol('x')
    f = Function('f')
    assert re(f(x)).diff(x) == re(f(x).diff(x))
    assert im(f(x)).diff(x) == im(f(x).diff(x))

    x = Symbol('x', real=True)
    assert Abs(f(x)).diff(x).subs(f(x), 1+I*x).doit() == x/sqrt(1 + x**2)
    assert arg(f(x)).diff(x).subs(f(x), 1+I*x**2).doit() == 2*x/(1+x**4)
Example #12
0
def test_f_expand_complex():
    f = Function('f')
    x = Symbol('x', real=True)
    z = Symbol('z')

    assert f(x).expand(complex=True)        == I*im(f(x)) + re(f(x))
    assert exp(x).expand(complex=True)      == exp(x)
    assert exp(I*x).expand(complex=True)    == cos(x) + I*sin(x)
    assert exp(z).expand(complex=True)      == cos(im(z))*exp(re(z)) + \
                                             I*sin(im(z))*exp(re(z))
def dictprint(n,D):
   """
   Prints the tableau format of the
   dictionary representation in D,
   n is the number of variables.
   """
   print len(D), n
   for k in D.keys():
      c = D[k]
      print sp.re(c), sp.im(c), strexp(k)
Example #14
0
def test_latex_functions():
    assert latex(exp(x)) == "e^{x}"
    assert latex(exp(1)+exp(2)) == "e + e^{2}"

    f = Function('f')
    assert latex(f(x)) == '\\operatorname{f}{\\left (x \\right )}'

    beta = Function('beta')

    assert latex(beta(x)) == r"\beta{\left (x \right )}"
    assert latex(sin(x)) == r"\sin{\left (x \right )}"
    assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}"
    assert latex(sin(2*x**2), fold_func_brackets=True) == \
    r"\sin {2 x^{2}}"
    assert latex(sin(x**2), fold_func_brackets=True) == \
    r"\sin {x^{2}}"

    assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left (x \right )}"
    assert latex(asin(x)**2,inv_trig_style="full") == \
        r"\arcsin^{2}{\left (x \right )}"
    assert latex(asin(x)**2,inv_trig_style="power") == \
        r"\sin^{-1}{\left (x \right )}^{2}"
    assert latex(asin(x**2),inv_trig_style="power",fold_func_brackets=True) == \
        r"\sin^{-1} {x^{2}}"

    assert latex(factorial(k)) == r"k!"
    assert latex(factorial(-k)) == r"\left(- k\right)!"

    assert latex(factorial2(k)) == r"k!!"
    assert latex(factorial2(-k)) == r"\left(- k\right)!!"

    assert latex(binomial(2,k)) == r"{\binom{2}{k}}"

    assert latex(FallingFactorial(3,k)) == r"{\left(3\right)}_{\left(k\right)}"
    assert latex(RisingFactorial(3,k)) == r"{\left(3\right)}^{\left(k\right)}"

    assert latex(floor(x)) == r"\lfloor{x}\rfloor"
    assert latex(ceiling(x)) == r"\lceil{x}\rceil"
    assert latex(Abs(x)) == r"\lvert{x}\rvert"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(re(x+y)) == r"\Re {\left (x + y \right )}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(conjugate(x)) == r"\overline{x}"
    assert latex(gamma(x)) == r"\Gamma\left(x\right)"
    assert latex(Order(x)) == r"\mathcal{O}\left(x\right)"
    assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)'
    assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)'

    assert latex(cot(x)) == r'\cot{\left (x \right )}'
    assert latex(coth(x)) == r'\coth{\left (x \right )}'
    assert latex(re(x)) == r'\Re{x}'
    assert latex(im(x)) == r'\Im{x}'
    assert latex(root(x,y)) == r'x^{\frac{1}{y}}'
    assert latex(arg(x)) == r'\arg{\left (x \right )}'
    assert latex(zeta(x)) == r'\zeta{\left (x \right )}'
Example #15
0
def _laplace_transform(f, t, s, simplify=True):
    """ The backend function for laplace transforms. """
    from sympy import (re, Max, exp, pi, Abs, Min, periodic_argument as arg,
                       cos, Wild, symbols)
    F = integrate(exp(-s*t) * f, (t, 0, oo))

    if not F.has(Integral):
        return _simplify(F, simplify), -oo, True

    if not F.is_Piecewise:
        raise IntegralTransformError('Laplace', f, 'could not compute integral')

    F, cond = F.args[0]
    if F.has(Integral):
        raise IntegralTransformError('Laplace', f, 'integral in unexpected form')

    a = -oo
    aux = True
    conds = conjuncts(to_cnf(cond))
    u = Dummy('u', real=True)
    p, q, w1, w2, w3 = symbols('p q w1 w2 w3', cls=Wild, exclude=[s])
    for c in conds:
        a_ = oo
        aux_ = []
        for d in disjuncts(c):
            m = d.match(abs(arg((s + w3)**p*q, w1)) < w2)
            if m:
                if m[q] > 0 and m[w2]/m[p] == pi/2:
                    d = re(s + m[w3]) > 0
            m = d.match(0 < cos(abs(arg(s, q)))*abs(s) - p)
            if m:
                d = re(s) > m[p]
            d_ = d.replace(re, lambda x: x.expand().as_real_imag()[0]).subs(re(s), t)
            if not d.is_Relational or (d.rel_op != '<' and d.rel_op != '<=') \
               or d_.has(s) or not d_.has(t):
                aux_ += [d]
                continue
            soln = _solve_inequality(d_, t)
            if not soln.is_Relational or \
               (soln.rel_op != '<' and soln.rel_op != '<='):
                aux_ += [d]
                continue
            if soln.lhs == t:
                raise IntegralTransformError('Laplace', f,
                                     'convergence not in half-plane?')
            else:
                a_ = Min(soln.lhs, a_)
        if a_ != oo:
            a = Max(a_, a)
        else:
            aux = And(aux, Or(*aux_))

    return _simplify(F, simplify), a, aux
Example #16
0
def test_solve_inequalities():
    system = [Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)]

    assert solve(system) == \
        And(Or(And(Lt(-sqrt(2), re(x)), Lt(re(x), -1)),
               And(Lt(1, re(x)), Lt(re(x), sqrt(2)))), Eq(im(x), 0))
    assert solve(system, assume=Q.real(x)) == \
        Or(And(Lt(-sqrt(2), x), Lt(x, -1)), And(Lt(1, x), Lt(x, sqrt(2))))

    # issue 3528, 3448
    assert solve((x - 3)/(x - 2) < 0, x, assume=Q.real(x)) == And(Lt(2, x), Lt(x, 3))
    assert solve(x/(x + 1) > 1, x, assume=Q.real(x)) == Lt(x, -1)
Example #17
0
def test_map_coeffs():
    p = Poly(x**2 + 2*x*y, x, y)
    q = p.map_coeffs(lambda c: 2*c)

    assert q.as_basic() == 2*x**2 + 4*x*y

    p = Poly(u*x**2 + v*x*y, x, y)
    q = p.map_coeffs(expand, complex=True)

    assert q.as_basic() == x**2*(I*im(u) + re(u)) + x*y*(I*im(v) + re(v))

    raises(PolynomialError, "p.map_coeffs(lambda c: x*c)")
Example #18
0
def test_derivatives_issue_4757():
    x = Symbol('x', real=True)
    y = Symbol('y', imaginary=True)
    f = Function('f')
    assert re(f(x)).diff(x) == re(f(x).diff(x))
    assert im(f(x)).diff(x) == im(f(x).diff(x))
    assert re(f(y)).diff(y) == -I*im(f(y).diff(y))
    assert im(f(y)).diff(y) == -I*re(f(y).diff(y))
    assert Abs(f(x)).diff(x).subs(f(x), 1 + I*x).doit() == x/sqrt(1 + x**2)
    assert arg(f(x)).diff(x).subs(f(x), 1 + I*x**2).doit() == 2*x/(1 + x**4)
    assert Abs(f(y)).diff(y).subs(f(y), 1 + y).doit() == -y/sqrt(1 - y**2)
    assert arg(f(y)).diff(y).subs(f(y), I + y**2).doit() == 2*y/(1 + y**4)
Example #19
0
def test_exp_assumptions():
    x = Symbol('x')
    r = Symbol('r', real=True)
    i = Symbol('i', imaginary=True)
    for e in exp, exp_polar:
        assert e(x).is_real is None
        assert e(x).is_imaginary is None
        assert e(i).is_real is None
        assert e(i).is_imaginary is None
        assert e(r).is_real is True
        assert e(r).is_imaginary is False
        assert e(re(x)).is_real is True
        assert e(re(x)).is_imaginary is False
Example #20
0
def test_as_real_imag():
    n = pi**1000
    # the special code for working out the real
    # and complex parts of a power with Integer exponent
    # should not run if there is no imaginary part, hence
    # this should not hang
    assert n.as_real_imag() == (n, 0)

    # issue 3162
    x = Symbol('x')
    assert sqrt(x).as_real_imag() == \
    ((re(x)**2 + im(x)**2)**(S(1)/4)*cos(atan2(im(x), re(x))/2), \
     (re(x)**2 + im(x)**2)**(S(1)/4)*sin(atan2(im(x), re(x))/2))
Example #21
0
def test_zero_assumptions():
    nr = Symbol('nonreal', real=False)
    ni = Symbol('nonimaginary', imaginary=False)
    # imaginary implies not zero
    nzni = Symbol('nonzerononimaginary', zero=False, imaginary=False)

    assert re(nr).is_zero is None
    assert im(nr).is_zero is False

    assert re(ni).is_zero is None
    assert im(ni).is_zero is None

    assert re(nzni).is_zero is False
    assert im(nzni).is_zero is None
Example #22
0
def test_diff_no_eval_derivative():
    class My(Expr):
        def __new__(cls, x):
            return Expr.__new__(cls, x)

    x, y = symbols('x y')
    # My doesn't have its own _eval_derivative method
    assert My(x).diff(x).func is Derivative
    assert My(x).diff(x, 3).func is Derivative
    assert re(x).diff(x, 2) == Derivative(re(x), (x, 2))  # issue 15518
    assert diff(NDimArray([re(x), im(x)]), (x, 2)) == NDimArray(
        [Derivative(re(x), (x, 2)), Derivative(im(x), (x, 2))])
    # it doesn't have y so it shouldn't need a method for this case
    assert My(x).diff(y) == 0
Example #23
0
def test_im():
    x, y = symbols('x,y')

    r = Symbol('r', real=True)
    i = Symbol('i', imaginary=True)

    assert im(nan) == nan

    assert im(oo*I) == oo
    assert im(-oo*I) == -oo

    assert im(0) == 0

    assert im(1) == 0
    assert im(-1) == 0

    assert im(E*I) == E
    assert im(-E*I) == -E

    assert im(x) == im(x)
    assert im(x*I) == re(x)
    assert im(r*I) == r
    assert im(r) == 0
    assert im(i*I) == 0
    assert im(i) == -I * i

    assert im(x + y) == im(x + y)
    assert im(x + r) == im(x)
    assert im(x + r*I) == im(x) + r

    assert im(im(x)*I) == im(x)

    assert im(2 + I) == 1
    assert im(x + I) == im(x) + 1

    assert im(x + y*I) == im(x) + re(y)
    assert im(x + r*I) == im(x) + r

    assert im(log(2*I)) == pi/2

    assert im((2+I)**2).expand(complex=True) == 4

    assert im(conjugate(x)) == -im(x)
    assert conjugate(im(x)) == im(x)

    assert im(x).as_real_imag() == (im(x), 0)

    assert im(i*r*x).diff(r) == im(i*x)
    assert im(i*r*x).diff(i) == -I * re(r*x)
Example #24
0
 def convergence_statement(self):
     """ Return a condition on z under which the series converges. """
     from sympy import And, Or, re, Ne, oo
     R = self.radius_of_convergence
     if R == 0:
         return False
     if R == oo:
         return True
     # The special functions and their approximations, page 44
     e = self.eta
     z = self.argument
     c1 = And(re(e) < 0, abs(z) <= 1)
     c2 = And(0 <= re(e), re(e) < 1, abs(z) <= 1, Ne(z, 1))
     c3 = And(re(e) >= 1, abs(z) < 1)
     return Or(c1, c2, c3)
Example #25
0
def test_reduce_inequalities_multivariate():
    x = Symbol('x')
    y = Symbol('y')

    assert reduce_inequalities([Ge(x**2, 1), Ge(y**2, 1)]) == \
        And(Eq(im(x), 0), Eq(im(y), 0), Or(And(Le(1, re(x)), Lt(re(x), oo)),
                                           And(Le(re(x), -1), Lt(-oo, re(x)))),
            Or(And(Le(1, re(y)), Lt(re(y), oo)), And(Le(re(y), -1), Lt(-oo, re(y)))))
Example #26
0
def test_bugs():
    from sympy import polar_lift, re

    assert abs(re((1 + I)**2)) < 1e-15

    # anything that evalf's to 0 will do in place of polar_lift
    assert abs(polar_lift(0)).n() == 0
Example #27
0
def test_atan2():
    assert atan2(0, 0) == S.NaN
    assert atan2(0, 1) == 0
    assert atan2(1, 1) == pi/4
    assert atan2(1, 0) == pi/2
    assert atan2(1, -1) == 3*pi/4
    assert atan2(0, -1) == pi
    assert atan2(-1, -1) == -3*pi/4
    assert atan2(-1, 0) == -pi/2
    assert atan2(-1, 1) == -pi/4

    u = Symbol("u", positive=True)
    assert atan2(0, u) == 0
    u = Symbol("u", negative=True)
    assert atan2(0, u) == pi

    assert atan2(y, oo) ==  0
    assert atan2(y, -oo)==  2*pi*Heaviside(re(y)) - pi

    assert atan2(y, x).rewrite(log) == -I*log((x + I*y)/sqrt(x**2 + y**2))
    assert atan2(y, x).rewrite(atan) == 2*atan(y/(x + sqrt(x**2 + y**2)))

    assert diff(atan2(y, x), x) == -y/(x**2 + y**2)
    assert diff(atan2(y, x), y) == x/(x**2 + y**2)

    assert simplify(diff(atan2(y, x).rewrite(log), x)) == -y/(x**2 + y**2)
    assert simplify(diff(atan2(y, x).rewrite(log), y)) ==  x/(x**2 + y**2)

    assert isinstance(atan2(2, 3*I).n(), atan2)
def test_catalan():
    n = Symbol('n', integer=True)
    m = Symbol('n', integer=True, positive=True)

    catalans = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786]
    for i, c in enumerate(catalans):
        assert catalan(i) == c
        assert catalan(n).rewrite(factorial).subs(n, i) == c
        assert catalan(n).rewrite(Product).subs(n, i).doit() == c

    assert catalan(x) == catalan(x)
    assert catalan(2*x).rewrite(binomial) == binomial(4*x, 2*x)/(2*x + 1)
    assert catalan(Rational(1, 2)).rewrite(gamma) == 8/(3*pi)
    assert catalan(Rational(1, 2)).rewrite(factorial).rewrite(gamma) ==\
        8 / (3 * pi)
    assert catalan(3*x).rewrite(gamma) == 4**(
        3*x)*gamma(3*x + Rational(1, 2))/(sqrt(pi)*gamma(3*x + 2))
    assert catalan(x).rewrite(hyper) == hyper((-x + 1, -x), (2,), 1)

    assert catalan(n).rewrite(factorial) == factorial(2*n) / (factorial(n + 1)
                                                              * factorial(n))
    assert isinstance(catalan(n).rewrite(Product), catalan)
    assert isinstance(catalan(m).rewrite(Product), Product)

    assert diff(catalan(x), x) == (polygamma(
        0, x + Rational(1, 2)) - polygamma(0, x + 2) + log(4))*catalan(x)

    assert catalan(x).evalf() == catalan(x)
    c = catalan(S.Half).evalf()
    assert str(c) == '0.848826363156775'
    c = catalan(I).evalf(3)
    assert str((re(c), im(c))) == '(0.398, -0.0209)'
Example #29
0
def plot_and_save():
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')
    #implicit plot tests
    plot_implicit(Eq(y, cos(x)), (x, -5, 5), (y, -2, 2)).save(tmp_file())
    plot_implicit(Eq(y**2, x**3 - x), (x, -5, 5),
            (y, -4, 4)).save(tmp_file())
    plot_implicit(y > 1 / x, (x, -5, 5),
            (y, -2, 2)).save(tmp_file())
    plot_implicit(y < 1 / tan(x), (x, -5, 5),
            (y, -2, 2)).save(tmp_file())
    plot_implicit(y >= 2 * sin(x) * cos(x), (x, -5, 5),
            (y, -2, 2)).save(tmp_file())
    plot_implicit(y <= x**2, (x, -3, 3),
            (y, -1, 5)).save(tmp_file())

    #Test all input args for plot_implicit
    plot_implicit(Eq(y**2, x**3 - x)).save(tmp_file())
    plot_implicit(Eq(y**2, x**3 - x), adaptive=False).save(tmp_file())
    plot_implicit(Eq(y**2, x**3 - x), adaptive=False, points = 500).save(tmp_file())
    plot_implicit(y > x, (x, -5, 5)).save(tmp_file())
    plot_implicit(And(y > exp(x), y > x + 2)).save(tmp_file())
    plot_implicit(Or(y > x, y > -x)).save(tmp_file())
    plot_implicit(x**2 - 1, (x, -5, 5)).save(tmp_file())
    plot_implicit(x**2 - 1).save(tmp_file())
    plot_implicit(y > x, depth = -5).save(tmp_file())
    plot_implicit(y > x, depth = 5).save(tmp_file())
    plot_implicit(y > cos(x), adaptive=False).save(tmp_file())
    plot_implicit(y < cos(x), adaptive=False).save(tmp_file())
    plot_implicit(And(y > cos(x), Or(y > x, Eq(y, x)))).save(tmp_file())

    #Test plots which cannot be rendered using the adaptive algorithm
    #TODO: catch the warning.
    plot_implicit(Eq(y, re(cos(x) + I*sin(x)))).save(tmp_file())
Example #30
0
 def process_conds(cond):
     """
     Turn ``cond`` into a strip (a, b), and auxiliary conditions.
     """
     a = -oo
     b = oo
     aux = True
     conds = conjuncts(to_cnf(cond))
     t = Dummy('t', real=True)
     for c in conds:
         a_ = oo
         b_ = -oo
         aux_ = []
         for d in disjuncts(c):
             d_ = d.replace(re, lambda x: x.as_real_imag()[0]).subs(re(s), t)
             if not d.is_Relational or (d.rel_op != '<' and d.rel_op != '<=') \
                or d_.has(s) or not d_.has(t):
                 aux_ += [d]
                 continue
             soln = _solve_inequality(d_, t)
             if not soln.is_Relational or \
                (soln.rel_op != '<' and soln.rel_op != '<='):
                 aux_ += [d]
                 continue
             if soln.lhs == t:
                 b_ = Max(soln.rhs, b_)
             else:
                 a_ = Min(soln.lhs, a_)
         if a_ != oo and a_ != b:
             a = Max(a_, a)
         elif b_ != -oo and b_ != a:
             b = Min(b_, b)
         else:
             aux = And(aux, Or(*aux_))
     return a, b, aux
Example #31
0
def g_bessel(n):
    order = n  # order is given
    s = symbols('s')  # as a variable

    # reverse Bessel Function
    def bessel(s):
        b = [0 for i in range(order + 1)]
        b[0] = 1
        b[1] = 1 + s
        for i in range(1, order):
            b[i + 1] = b[i] + (s**2) * b[i - 1] / (4 * i**2 - 1)
        return simplify(b[order])

    # Transfer function
    def S12(s):
        return 1 / bessel(s)

    # F function
    def F(s):
        return S12(s) * S12(-s)

    # p,q are numerator and denominator of S11, respectively
    p, q = fraction(simplify(1 - F(s)))
    p = expand(p)
    q = expand(q)
    # factor_num,factor_den are coefficients of polynomial p,q
    factor_num = [float(p.coeff(s, i)) for i in range(order**2, -1, -1)]
    factor_den = [float(q.coeff(s, i)) for i in range(order**2, -1, -1)]
    ## KEY POINT: tf2zpk is a function that gives you zeros and poles of a fractional function(and really fast)
    zero, pole, k = signal.tf2zpk(factor_num, factor_den)

    ## We need only points on the left plane
    # numerator
    p1 = []
    for i in range(len(zero)):
        if re(zero[i]) < 0:  # without s=0 in case of complexity
            p1.append(zero[i])
    while len(p1) < order:  # put back s=0 since the order is determined
        p1.append(0)
    # denominator
    q1 = []
    for i in range(len(pole)):
        if re(pole[i]) < 0:
            q1.append(pole[i])
    while len(q1) < order:
        q1.append(0)

    ##Build S11 with p1,q1
    def z_frac(s, p1, q1):
        b = 1
        a = 1
        for i in range(order):
            b = b * (s - p1[i])
            a = a * (s - q1[i])
        return expand(a + b), expand(a - b)  # z=(1+S11)/(1-S11)

    # p2,q2 are numerator and denominator of Zin, respectively
    p2, q2 = z_frac(s, p1, q1)

    # p2,q2's coefficients are real now,but because of floats and approximation, the imaginary parts are very close to 0
    def coeff(s, p2, q2):
        numerator = [re(p2.coeff(s, i)) for i in range(order, -1, -1)]
        denominator = [re(q2.coeff(s, i)) for i in range(order, -1, -1)]
        return numerator, denominator

    ## continuous fraction equation
    def continued_fraction_expr_series(s, p2, q2):
        numerator, denominator = coeff(s, p2, q2)
        g = [0 for i in range(order)]
        for i in range(order):
            if (numerator[i] - 0 > 0.001) & (denominator[i] - 0 > 0.001):
                g[i] = numerator[i] / denominator[i]
                for j in range(order, i - 1, -1):
                    numerator[j] = simplify(numerator[j] -
                                            g[i] * denominator[j])
            elif (numerator[i] - 0 < 0.001) & (denominator[i] - 0 > 0.001):
                g[i] = denominator[i] / numerator[i + 1]
                for j in range(order - 1, i - 1, -1):
                    denominator[j] = simplify(denominator[j] -
                                              g[i] * numerator[j + 1])
            elif (numerator[i] - 0 > 0.001) & (denominator[i] - 0 < 0.001):
                g[i] = numerator[i] / denominator[i + 1]
                for j in range(order - 1, i - 1, -1):
                    numerator[j] = simplify(numerator[j] -
                                            g[i] * denominator[j + 1])
        return g

    return continued_fraction_expr_series(s, p2, q2)
Example #32
0
def test_inverse_mellin_transform():
    from sympy import (sin, simplify, Max, Min, expand, powsimp, exp_polar,
                       cos, cot)
    IMT = inverse_mellin_transform

    assert IMT(gamma(s), s, x, (0, oo)) == exp(-x)
    assert IMT(gamma(-s), s, x, (-oo, 0)) == exp(-1 / x)
    assert simplify(IMT(s/(2*s**2 - 2), s, x, (2, oo))) == \
        (x**2 + 1)*Heaviside(1 - x)/(4*x)

    # test passing "None"
    assert IMT(1/(s**2 - 1), s, x, (-1, None)) == \
        -x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x)
    assert IMT(1/(s**2 - 1), s, x, (None, 1)) == \
        -x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x)

    # test expansion of sums
    assert IMT(gamma(s) + gamma(s - 1), s, x, (1, oo)) == (x + 1) * exp(-x) / x

    # test factorisation of polys
    r = symbols('r', real=True)
    assert IMT(1/(s**2 + 1), s, exp(-x), (None, oo)
              ).subs(x, r).rewrite(sin).simplify() \
        == sin(r)*Heaviside(1 - exp(-r))

    # test multiplicative substitution
    _a, _b = symbols('a b', positive=True)
    assert IMT(_b**(-s / _a) * factorial(s / _a) / s, s, x,
               (0, oo)) == exp(-_b * x**_a)
    assert IMT(factorial(_a / _b + s / _b) / (_a + s), s, x,
               (-_a, oo)) == x**_a * exp(-x**_b)

    def simp_pows(expr):
        return simplify(powsimp(expand_mul(expr, deep=False),
                                force=True)).replace(exp_polar, exp)

    # Now test the inverses of all direct transforms tested above

    # Section 8.4.2
    nu = symbols('nu', real=True, finite=True)
    assert IMT(-1 / (nu + s), s, x, (-oo, None)) == x**nu * Heaviside(x - 1)
    assert IMT(1 / (nu + s), s, x, (None, oo)) == x**nu * Heaviside(1 - x)
    assert simp_pows(IMT(gamma(beta)*gamma(s)/gamma(s + beta), s, x, (0, oo))) \
        == (1 - x)**(beta - 1)*Heaviside(1 - x)
    assert simp_pows(IMT(gamma(beta)*gamma(1 - beta - s)/gamma(1 - s),
                         s, x, (-oo, None))) \
        == (x - 1)**(beta - 1)*Heaviside(x - 1)
    assert simp_pows(IMT(gamma(s)*gamma(rho - s)/gamma(rho), s, x, (0, None))) \
        == (1/(x + 1))**rho
    assert simp_pows(IMT(d**c*d**(s - 1)*sin(pi*c)
                         *gamma(s)*gamma(s + c)*gamma(1 - s)*gamma(1 - s - c)/pi,
                         s, x, (Max(-re(c), 0), Min(1 - re(c), 1)))) \
        == (x**c - d**c)/(x - d)

    assert simplify(IMT(1/sqrt(pi)*(-c/2)*gamma(s)*gamma((1 - c)/2 - s)
                        *gamma(-c/2 - s)/gamma(1 - c - s),
                        s, x, (0, -re(c)/2))) == \
        (1 + sqrt(x + 1))**c
    assert simplify(IMT(2**(a + 2*s)*b**(a + 2*s - 1)*gamma(s)*gamma(1 - a - 2*s)
                        /gamma(1 - a - s), s, x, (0, (-re(a) + 1)/2))) == \
        b**(a - 1)*(sqrt(1 + x/b**2) + 1)**(a - 1)*(b**2*sqrt(1 + x/b**2) +
        b**2 + x)/(b**2 + x)
    assert simplify(IMT(-2**(c + 2*s)*c*b**(c + 2*s)*gamma(s)*gamma(-c - 2*s)
                        / gamma(-c - s + 1), s, x, (0, -re(c)/2))) == \
        b**c*(sqrt(1 + x/b**2) + 1)**c

    # Section 8.4.5
    assert IMT(24 / s**5, s, x, (0, oo)) == log(x)**4 * Heaviside(1 - x)
    assert expand(IMT(6/s**4, s, x, (-oo, 0)), force=True) == \
        log(x)**3*Heaviside(x - 1)
    assert IMT(pi / (s * sin(pi * s)), s, x, (-1, 0)) == log(x + 1)
    assert IMT(pi / (s * sin(pi * s / 2)), s, x, (-2, 0)) == log(x**2 + 1)
    assert IMT(pi / (s * sin(2 * pi * s)), s, x,
               (-S(1) / 2, 0)) == log(sqrt(x) + 1)
    assert IMT(pi / (s * sin(pi * s)), s, x, (0, 1)) == log(1 + 1 / x)

    # TODO
    def mysimp(expr):
        from sympy import expand, logcombine, powsimp
        return expand(powsimp(logcombine(expr, force=True),
                              force=True,
                              deep=True),
                      force=True).replace(exp_polar, exp)

    assert mysimp(mysimp(IMT(pi / (s * tan(pi * s)), s, x, (-1, 0)))) in [
        log(1 - x) * Heaviside(1 - x) + log(x - 1) * Heaviside(x - 1),
        log(x) * Heaviside(x - 1) + log(1 - 1 / x) * Heaviside(x - 1) +
        log(-x + 1) * Heaviside(-x + 1)
    ]
    # test passing cot
    assert mysimp(IMT(pi * cot(pi * s) / s, s, x, (0, 1))) in [
        log(1 / x - 1) * Heaviside(1 - x) + log(1 - 1 / x) * Heaviside(x - 1),
        -log(x) * Heaviside(-x + 1) + log(1 - 1 / x) * Heaviside(x - 1) +
        log(-x + 1) * Heaviside(-x + 1),
    ]

    # 8.4.14
    assert IMT(-gamma(s + S(1)/2)/(sqrt(pi)*s), s, x, (-S(1)/2, 0)) == \
        erf(sqrt(x))

    # 8.4.19
    assert simplify(IMT(gamma(a/2 + s)/gamma(a/2 - s + 1), s, x, (-re(a)/2, S(3)/4))) \
        == besselj(a, 2*sqrt(x))
    assert simplify(IMT(2**a*gamma(S(1)/2 - 2*s)*gamma(s + (a + 1)/2)
                      / (gamma(1 - s - a/2)*gamma(1 - 2*s + a)),
                      s, x, (-(re(a) + 1)/2, S(1)/4))) == \
        sin(sqrt(x))*besselj(a, sqrt(x))
    assert simplify(IMT(2**a*gamma(a/2 + s)*gamma(S(1)/2 - 2*s)
                      / (gamma(S(1)/2 - s - a/2)*gamma(1 - 2*s + a)),
                      s, x, (-re(a)/2, S(1)/4))) == \
        cos(sqrt(x))*besselj(a, sqrt(x))
    # TODO this comes out as an amazing mess, but simplifies nicely
    assert simplify(IMT(gamma(a + s)*gamma(S(1)/2 - s)
                      / (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)),
                      s, x, (-re(a), S(1)/2))) == \
        besselj(a, sqrt(x))**2
    assert simplify(IMT(gamma(s)*gamma(S(1)/2 - s)
                      / (sqrt(pi)*gamma(1 - s - a)*gamma(1 + a - s)),
                      s, x, (0, S(1)/2))) == \
        besselj(-a, sqrt(x))*besselj(a, sqrt(x))
    assert simplify(IMT(4**s*gamma(-2*s + 1)*gamma(a/2 + b/2 + s)
                      / (gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1)
                         *gamma(a/2 + b/2 - s + 1)),
                      s, x, (-(re(a) + re(b))/2, S(1)/2))) == \
        besselj(a, sqrt(x))*besselj(b, sqrt(x))

    # Section 8.4.20
    # TODO this can be further simplified!
    assert simplify(IMT(-2**(2*s)*cos(pi*a/2 - pi*b/2 + pi*s)*gamma(-2*s + 1) *
                    gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s) /
                    (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)),
                    s, x,
                    (Max(-re(a)/2 - re(b)/2, -re(a)/2 + re(b)/2), S(1)/2))) == \
                    besselj(a, sqrt(x))*-(besselj(-b, sqrt(x)) -
                    besselj(b, sqrt(x))*cos(pi*b))/sin(pi*b)
    # TODO more

    # for coverage

    assert IMT(pi / cos(pi * s), s, x, (0, S(1) / 2)) == sqrt(x) / (x + 1)
Example #33
0
def test_periodicity():
    x = Symbol("x")
    y = Symbol("y")
    z = Symbol("z", real=True)

    assert periodicity(sin(2 * x), x) == pi
    assert periodicity((-2) * tan(4 * x), x) == pi / 4
    assert periodicity(sin(x)**2, x) == 2 * pi
    assert periodicity(3**tan(3 * x), x) == pi / 3
    assert periodicity(tan(x) * cos(x), x) == 2 * pi
    assert periodicity(sin(x)**(tan(x)), x) == 2 * pi
    assert periodicity(tan(x) * sec(x), x) == 2 * pi
    assert periodicity(sin(2 * x) * cos(2 * x) - y, x) == pi / 2
    assert periodicity(tan(x) + cot(x), x) == pi
    assert periodicity(sin(x) - cos(2 * x), x) == 2 * pi
    assert periodicity(sin(x) - 1, x) == 2 * pi
    assert periodicity(sin(4 * x) + sin(x) * cos(x), x) == pi
    assert periodicity(exp(sin(x)), x) == 2 * pi
    assert periodicity(log(cot(2 * x)) - sin(cos(2 * x)), x) == pi
    assert periodicity(sin(2 * x) * exp(tan(x) - csc(2 * x)), x) == pi
    assert periodicity(cos(sec(x) - csc(2 * x)), x) == 2 * pi
    assert periodicity(tan(sin(2 * x)), x) == pi
    assert periodicity(2 * tan(x)**2, x) == pi
    assert periodicity(sin(x % 4), x) == 4
    assert periodicity(sin(x) % 4, x) == 2 * pi
    assert periodicity(tan((3 * x - 2) % 4), x) == Rational(4, 3)
    assert periodicity((sqrt(2) * (x + 1) + x) % 3, x) == 3 / (sqrt(2) + 1)
    assert periodicity((x**2 + 1) % x, x) is None
    assert periodicity(sin(re(x)), x) == 2 * pi
    assert periodicity(sin(x)**2 + cos(x)**2, x) is S.Zero
    assert periodicity(tan(x), y) is S.Zero
    assert periodicity(sin(x) + I * cos(x), x) == 2 * pi
    assert periodicity(x - sin(2 * y), y) == pi

    assert periodicity(exp(x), x) is None
    assert periodicity(exp(I * x), x) == 2 * pi
    assert periodicity(exp(I * z), z) == 2 * pi
    assert periodicity(exp(z), z) is None
    assert periodicity(exp(log(sin(z) + I * cos(2 * z)), evaluate=False),
                       z) == 2 * pi
    assert periodicity(exp(log(sin(2 * z) + I * cos(z)), evaluate=False),
                       z) == 2 * pi
    assert periodicity(exp(sin(z)), z) == 2 * pi
    assert periodicity(exp(2 * I * z), z) == pi
    assert periodicity(exp(z + I * sin(z)), z) is None
    assert periodicity(exp(cos(z / 2) + sin(z)), z) == 4 * pi
    assert periodicity(log(x), x) is None
    assert periodicity(exp(x)**sin(x), x) is None
    assert periodicity(sin(x)**y, y) is None

    assert periodicity(Abs(sin(Abs(sin(x)))), x) == pi
    assert all(
        periodicity(Abs(f(x)), x) == pi
        for f in (cos, sin, sec, csc, tan, cot))
    assert periodicity(Abs(sin(tan(x))), x) == pi
    assert periodicity(Abs(sin(sin(x) + tan(x))), x) == 2 * pi
    assert periodicity(sin(x) > S.Half, x) == 2 * pi

    assert periodicity(x > 2, x) is None
    assert periodicity(x**3 - x**2 + 1, x) is None
    assert periodicity(Abs(x), x) is None
    assert periodicity(Abs(x**2 - 1), x) is None

    assert periodicity((x**2 + 4) % 2, x) is None
    assert periodicity((E**x) % 3, x) is None

    assert periodicity(sin(expint(1, x)) / expint(1, x), x) is None
Example #34
0
def test_expand_function():
    assert expand(x + y) == x + y
    assert expand(x + y, complex=True) == I * im(x) + I * im(y) + re(x) + re(y)
    assert expand((x + y)**11, modulus=11) == x**11 + y**11
Example #35
0
Z3, Z4, ZC, V, relation = symbols('Z3 Z4 ZC V relation', imaginary=True)
ZC = -I*(1/(omega * C))
Z3 = R4
Z4 = R3 * ZC / (R3 + ZC)
V = 1 + Z4/Z3



relation = limit(V,omega,0) / V
#relation = limit(relation,R2,R1)

pprint(limit(V,omega,0))
relation = Abs(relation)

relation = relation.subs(R3,R4)
realRelation = re(relation)
imRelation = im(relation)
absrelation = simplify(sqrt(realRelation**2 + imRelation**2))
#pprint( simplify(absrelation - (2/sqrt(2)) )**2 )
pprint(solve( absrelation - (2/sqrt(2)),C))


#pprint(  )

# example of calculations 
# set value for R4 = 100 Ohm 
relation = relation.subs(R4,100)
# set value for R3 = 10 Ohm
relation = relation.subs(R3,100)
# set cutoff frequency 200Hz
relation = relation.subs(omega,200/(2*pi))
Example #36
0
def test_Abs():
    raises(TypeError, lambda: Abs(Interval(2, 3)))  # issue 8717

    x, y = symbols('x,y')
    assert sign(sign(x)) == sign(x)
    assert sign(x * y).func is sign
    assert Abs(0) == 0
    assert Abs(1) == 1
    assert Abs(-1) == 1
    assert Abs(I) == 1
    assert Abs(-I) == 1
    assert Abs(nan) == nan
    assert Abs(zoo) == oo
    assert Abs(I * pi) == pi
    assert Abs(-I * pi) == pi
    assert Abs(I * x) == Abs(x)
    assert Abs(-I * x) == Abs(x)
    assert Abs(-2 * x) == 2 * Abs(x)
    assert Abs(-2.0 * x) == 2.0 * Abs(x)
    assert Abs(2 * pi * x * y) == 2 * pi * Abs(x * y)
    assert Abs(conjugate(x)) == Abs(x)
    assert conjugate(Abs(x)) == Abs(x)
    assert Abs(x).expand(complex=True) == sqrt(re(x)**2 + im(x)**2)

    a = Symbol('a', positive=True)
    assert Abs(2 * pi * x * a) == 2 * pi * a * Abs(x)
    assert Abs(2 * pi * I * x * a) == 2 * pi * a * Abs(x)

    x = Symbol('x', real=True)
    n = Symbol('n', integer=True)
    assert Abs((-1)**n) == 1
    assert x**(2 * n) == Abs(x)**(2 * n)
    assert Abs(x).diff(x) == sign(x)
    assert abs(x) == Abs(x)  # Python built-in
    assert Abs(x)**3 == x**2 * Abs(x)
    assert Abs(x)**4 == x**4
    assert (Abs(x)**(3 * n)).args == (Abs(x), 3 * n
                                      )  # leave symbolic odd unchanged
    assert (1 / Abs(x)).args == (Abs(x), -1)
    assert 1 / Abs(x)**3 == 1 / (x**2 * Abs(x))
    assert Abs(x)**-3 == Abs(x) / (x**4)
    assert Abs(x**3) == x**2 * Abs(x)
    assert Abs(I**I) == exp(-pi / 2)
    assert Abs((4 + 5 * I)**(6 + 7 * I)) == 68921 * exp(-7 * atan(S(5) / 4))
    y = Symbol('y', real=True)
    assert Abs(I**y) == 1
    y = Symbol('y')
    assert Abs(I**y) == exp(-pi * im(y) / 2)

    x = Symbol('x', imaginary=True)
    assert Abs(x).diff(x) == -sign(x)

    eq = -sqrt(10 + 6 * sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3 * sqrt(3))
    # if there is a fast way to know when you can and when you cannot prove an
    # expression like this is zero then the equality to zero is ok
    assert abs(eq).func is Abs or abs(eq) == 0
    # but sometimes it's hard to do this so it's better not to load
    # abs down with tests that will be very slow
    q = 1 + sqrt(2) - 2 * sqrt(3) + 1331 * sqrt(6)
    p = expand(q**3)**Rational(1, 3)
    d = p - q
    assert abs(d).func is Abs or abs(d) == 0

    assert Abs(4 * exp(pi * I / 4)) == 4
    assert Abs(3**(2 + I)) == 9
    assert Abs((-3)**(1 - I)) == 3 * exp(pi)

    assert Abs(oo) is oo
    assert Abs(-oo) is oo
    assert Abs(oo + I) is oo
    assert Abs(oo + I * oo) is oo

    a = Symbol('a', algebraic=True)
    t = Symbol('t', transcendental=True)
    x = Symbol('x')
    assert re(a).is_algebraic
    assert re(x).is_algebraic is None
    assert re(t).is_algebraic is False
Example #37
0
def test_re():
    x, y = symbols('x,y')
    a, b = symbols('a,b', real=True)

    r = Symbol('r', real=True)
    i = Symbol('i', imaginary=True)

    assert re(nan) == nan

    assert re(oo) == oo
    assert re(-oo) == -oo

    assert re(0) == 0

    assert re(1) == 1
    assert re(-1) == -1

    assert re(E) == E
    assert re(-E) == -E

    assert unchanged(re, x)
    assert re(x * I) == -im(x)
    assert re(r * I) == 0
    assert re(r) == r
    assert re(i * I) == I * i
    assert re(i) == 0

    assert re(x + y) == re(x + y)
    assert re(x + r) == re(x) + r

    assert re(re(x)) == re(x)

    assert re(2 + I) == 2
    assert re(x + I) == re(x)

    assert re(x + y * I) == re(x) - im(y)
    assert re(x + r * I) == re(x)

    assert re(log(2 * I)) == log(2)

    assert re((2 + I)**2).expand(complex=True) == 3

    assert re(conjugate(x)) == re(x)
    assert conjugate(re(x)) == re(x)

    assert re(x).as_real_imag() == (re(x), 0)

    assert re(i * r * x).diff(r) == re(i * x)
    assert re(i * r * x).diff(i) == I * r * im(x)

    assert re(
        sqrt(a +
             b * I)) == (a**2 + b**2)**Rational(1, 4) * cos(atan2(b, a) / 2)
    assert re(a * (2 + b * I)) == 2 * a

    assert re((1 + sqrt(a + b*I))/2) == \
        (a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)/2 + Rational(1, 2)

    assert re(x).rewrite(im) == x - S.ImaginaryUnit * im(x)
    assert (x + re(y)).rewrite(re, im) == x + y - S.ImaginaryUnit * im(y)

    a = Symbol('a', algebraic=True)
    t = Symbol('t', transcendental=True)
    x = Symbol('x')
    assert re(a).is_algebraic
    assert re(x).is_algebraic is None
    assert re(t).is_algebraic is False

    assert re(S.ComplexInfinity) == S.NaN

    n, m, l = symbols('n m l')
    A = MatrixSymbol('A', n, m)
    assert re(A) == (S(1) / 2) * (A + conjugate(A))

    A = Matrix([[1 + 4 * I, 2], [0, -3 * I]])
    assert re(A) == Matrix([[1, 2], [0, 0]])

    A = ImmutableMatrix([[1 + 3 * I, 3 - 2 * I], [0, 2 * I]])
    assert re(A) == ImmutableMatrix([[1, 3], [0, 0]])

    X = SparseMatrix([[2 * j + i * I for i in range(5)] for j in range(5)])
    assert re(X) - Matrix([[0, 0, 0, 0, 0], [2, 2, 2, 2, 2], [4, 4, 4, 4, 4],
                           [6, 6, 6, 6, 6], [8, 8, 8, 8, 8]
                           ]) == Matrix.zeros(5)

    assert im(X) - Matrix([[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4],
                           [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]
                           ]) == Matrix.zeros(5)

    X = FunctionMatrix(3, 3, Lambda((n, m), n + m * I))
    assert re(X) == Matrix([[0, 0, 0], [1, 1, 1], [2, 2, 2]])
Example #38
0
def test_im():
    x, y = symbols('x,y')
    a, b = symbols('a,b', real=True)

    r = Symbol('r', real=True)
    i = Symbol('i', imaginary=True)

    assert im(nan) == nan

    assert im(oo * I) == oo
    assert im(-oo * I) == -oo

    assert im(0) == 0

    assert im(1) == 0
    assert im(-1) == 0

    assert im(E * I) == E
    assert im(-E * I) == -E

    assert unchanged(im, x)
    assert im(x * I) == re(x)
    assert im(r * I) == r
    assert im(r) == 0
    assert im(i * I) == 0
    assert im(i) == -I * i

    assert im(x + y) == im(x + y)
    assert im(x + r) == im(x)
    assert im(x + r * I) == im(x) + r

    assert im(im(x) * I) == im(x)

    assert im(2 + I) == 1
    assert im(x + I) == im(x) + 1

    assert im(x + y * I) == im(x) + re(y)
    assert im(x + r * I) == im(x) + r

    assert im(log(2 * I)) == pi / 2

    assert im((2 + I)**2).expand(complex=True) == 4

    assert im(conjugate(x)) == -im(x)
    assert conjugate(im(x)) == im(x)

    assert im(x).as_real_imag() == (im(x), 0)

    assert im(i * r * x).diff(r) == im(i * x)
    assert im(i * r * x).diff(i) == -I * re(r * x)

    assert im(
        sqrt(a +
             b * I)) == (a**2 + b**2)**Rational(1, 4) * sin(atan2(b, a) / 2)
    assert im(a * (2 + b * I)) == a * b

    assert im((1 + sqrt(a + b*I))/2) == \
        (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2

    assert im(x).rewrite(re) == -S.ImaginaryUnit * (x - re(x))
    assert (x + im(y)).rewrite(im, re) == x - S.ImaginaryUnit * (y - re(y))

    a = Symbol('a', algebraic=True)
    t = Symbol('t', transcendental=True)
    x = Symbol('x')
    assert re(a).is_algebraic
    assert re(x).is_algebraic is None
    assert re(t).is_algebraic is False

    assert im(S.ComplexInfinity) == S.NaN

    n, m, l = symbols('n m l')
    A = MatrixSymbol('A', n, m)

    assert im(A) == (S(1) / (2 * I)) * (A - conjugate(A))

    A = Matrix([[1 + 4 * I, 2], [0, -3 * I]])
    assert im(A) == Matrix([[4, 0], [0, -3]])

    A = ImmutableMatrix([[1 + 3 * I, 3 - 2 * I], [0, 2 * I]])
    assert im(A) == ImmutableMatrix([[3, -2], [0, 2]])

    X = ImmutableSparseMatrix([[i * I + i for i in range(5)]
                               for i in range(5)])
    Y = SparseMatrix([[i for i in range(5)] for i in range(5)])
    assert im(X).as_immutable() == Y

    X = FunctionMatrix(3, 3, Lambda((n, m), n + m * I))
    assert im(X) == Matrix([[0, 1, 2], [0, 1, 2], [0, 1, 2]])
Example #39
0
def test_issue_7450():
    ans = integrate(exp(-(1 + I)*x), (x, 0, oo))
    assert re(ans) == S.Half and im(ans) == -S.Half
Example #40
0
def test_coth():
    x, y = symbols('x,y')

    k = Symbol('k', integer=True)

    assert coth(nan) == nan
    assert coth(zoo) == nan

    assert coth(oo) == 1
    assert coth(-oo) == -1

    assert coth(0) == coth(0)
    assert coth(0) == zoo
    assert coth(1) == coth(1)
    assert coth(-1) == -coth(1)

    assert coth(x) == coth(x)
    assert coth(-x) == -coth(x)

    assert coth(pi*I) == -I*cot(pi)
    assert coth(-pi*I) == cot(pi)*I

    assert coth(2**1024 * E) == coth(2**1024 * E)
    assert coth(-2**1024 * E) == -coth(2**1024 * E)

    assert coth(pi*I) == -I*cot(pi)
    assert coth(-pi*I) == I*cot(pi)
    assert coth(2*pi*I) == -I*cot(2*pi)
    assert coth(-2*pi*I) == I*cot(2*pi)
    assert coth(-3*10**73*pi*I) == I*cot(3*10**73*pi)
    assert coth(7*10**103*pi*I) == -I*cot(7*10**103*pi)

    assert coth(pi*I/2) == 0
    assert coth(-pi*I/2) == 0
    assert coth(5*pi*I/2) == 0
    assert coth(7*pi*I/2) == 0

    assert coth(pi*I/3) == -I/sqrt(3)
    assert coth(-2*pi*I/3) == -I/sqrt(3)

    assert coth(pi*I/4) == -I
    assert coth(-pi*I/4) == I
    assert coth(17*pi*I/4) == -I
    assert coth(-3*pi*I/4) == -I

    assert coth(pi*I/6) == -sqrt(3)*I
    assert coth(-pi*I/6) == sqrt(3)*I
    assert coth(7*pi*I/6) == -sqrt(3)*I
    assert coth(-5*pi*I/6) == -sqrt(3)*I

    assert coth(pi*I/105) == -cot(pi/105)*I
    assert coth(-pi*I/105) == cot(pi/105)*I

    assert coth(2 + 3*I) == coth(2 + 3*I)

    assert coth(x*I) == -cot(x)*I

    assert coth(k*pi*I) == -cot(k*pi)*I
    assert coth(17*k*pi*I) == -cot(17*k*pi)*I

    assert coth(k*pi*I) == -cot(k*pi)*I

    assert coth(log(tan(2))) == coth(log(-tan(2)))
    assert coth(1 + I*pi/2) == tanh(1)

    assert coth(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(sin(im(x))**2
                                + sinh(re(x))**2),
                                -sin(im(x))*cos(im(x))/(sin(im(x))**2 + sinh(re(x))**2))
    x = Symbol('x', extended_real=True)
    assert coth(x).as_real_imag(deep=False) == (coth(x), 0)
Example #41
0
 def as_real_imag(self, deep=True, **hints):
     from sympy import im, re
     if hints.get('ignore') == self:
         return None
     else:
         return (re(self), im(self))
Example #42
0
# w_log = np.logspace(0, 7, N)
w_lin = np.linspace(20, 20E3*6, N)
w_log = np.logspace(0, 5, N)
w = np.concatenate((w_lin, w_log), axis=0)
f = w/(2*pi)
S0_array = [0.2, 0.4, 0.6, 0.8, 1-epsilon]
S0_label = [str(i) for i in S0_array]
k = Symbol('k')

for i in range(len(S0_array)):
    S0 = S0_array[i]
    print('Progress: ' + str(int(100*(i+1)/5)) + '%')
    disp_rel = longitudinal_disp(S0, w, material_mode)
    k_array = [list(nroots(d, maxsteps = 100))[0:3] for d in disp_rel]
    for j in range(3):
        speed_array = w[N:]/[abs(re(e[j])) for e in k_array][N:]
        attenuation_array = [abs(im(e[j])) for e in k_array][:N]

        plt.figure(j)
        plt.semilogx(f[N:], speed_array, label=S0_label[i])

        plt.figure(j+3)
        if j == 2:
            plt.plot(f[:N], attenuation_array, label=S0_label[i])
        else:
            plt.semilogy(f[:N], attenuation_array, label=S0_label[i])


for j in range(3):
    plt.figure(j)
    plt.legend()
Example #43
0
def test_mellin_transform_bessel():
    from sympy import Max
    MT = mellin_transform

    # 8.4.19
    assert MT(besselj(a, 2*sqrt(x)), x, s) == \
        (gamma(a/2 + s)/gamma(a/2 - s + 1), (-re(a)/2, S(3)/4), True)
    assert MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s) == \
        (2**a*gamma(-2*s + S(1)/2)*gamma(a/2 + s + S(1)/2)/(
        gamma(-a/2 - s + 1)*gamma(a - 2*s + 1)), (
        -re(a)/2 - S(1)/2, S(1)/4), True)
    assert MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s) == \
        (2**a*gamma(a/2 + s)*gamma(-2*s + S(1)/2)/(
        gamma(-a/2 - s + S(1)/2)*gamma(a - 2*s + 1)), (
        -re(a)/2, S(1)/4), True)
    assert MT(besselj(a, sqrt(x))**2, x, s) == \
        (gamma(a + s)*gamma(S(1)/2 - s)
         / (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)),
            (-re(a), S(1)/2), True)
    assert MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s) == \
        (gamma(s)*gamma(S(1)/2 - s)
         / (sqrt(pi)*gamma(1 - a - s)*gamma(1 + a - s)),
            (0, S(1)/2), True)
    # NOTE: prudnikov gives the strip below as (1/2 - re(a), 1). As far as
    #       I can see this is wrong (since besselj(z) ~ 1/sqrt(z) for z large)
    assert MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s) == \
        (gamma(1 - s)*gamma(a + s - S(1)/2)
         / (sqrt(pi)*gamma(S(3)/2 - s)*gamma(a - s + S(1)/2)),
            (S(1)/2 - re(a), S(1)/2), True)
    assert MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s) == \
        (4**s*gamma(1 - 2*s)*gamma((a + b)/2 + s)
         / (gamma(1 - s + (b - a)/2)*gamma(1 - s + (a - b)/2)
            *gamma( 1 - s + (a + b)/2)),
            (-(re(a) + re(b))/2, S(1)/2), True)
    assert MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)[1:] == \
        ((Max(re(a), -re(a)), S(1)/2), True)

    # Section 8.4.20
    assert MT(bessely(a, 2*sqrt(x)), x, s) == \
        (-cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)/pi,
            (Max(-re(a)/2, re(a)/2), S(3)/4), True)
    assert MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s) == \
        (-4**s*sin(pi*(a/2 - s))*gamma(S(1)/2 - 2*s)
         * gamma((1 - a)/2 + s)*gamma((1 + a)/2 + s)
         / (sqrt(pi)*gamma(1 - s - a/2)*gamma(1 - s + a/2)),
            (Max(-(re(a) + 1)/2, (re(a) - 1)/2), S(1)/4), True)
    assert MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s) == \
        (-4**s*cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)*gamma(S(1)/2 - 2*s)
         / (sqrt(pi)*gamma(S(1)/2 - s - a/2)*gamma(S(1)/2 - s + a/2)),
            (Max(-re(a)/2, re(a)/2), S(1)/4), True)
    assert MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s) == \
        (-cos(pi*s)*gamma(s)*gamma(a + s)*gamma(S(1)/2 - s)
         / (pi**S('3/2')*gamma(1 + a - s)),
            (Max(-re(a), 0), S(1)/2), True)
    assert MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s) == \
        (-4**s*cos(pi*(a/2 - b/2 + s))*gamma(1 - 2*s)
         * gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s)
         / (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)),
            (Max((-re(a) + re(b))/2, (-re(a) - re(b))/2), S(1)/2), True)
    # NOTE bessely(a, sqrt(x))**2 and bessely(a, sqrt(x))*bessely(b, sqrt(x))
    # are a mess (no matter what way you look at it ...)
    assert MT(bessely(a, sqrt(x))**2, x, s)[1:] == \
             ((Max(-re(a), 0, re(a)), S(1)/2), True)

    # Section 8.4.22
    # TODO we can't do any of these (delicate cancellation)

    # Section 8.4.23
    assert MT(besselk(a, 2*sqrt(x)), x, s) == \
        (gamma(
         s - a/2)*gamma(s + a/2)/2, (Max(-re(a)/2, re(a)/2), oo), True)
    assert MT(
        besselj(a, 2 * sqrt(2 * sqrt(x))) * besselk(a, 2 * sqrt(2 * sqrt(x))),
        x, s) == (4**(-s) * gamma(2 * s) * gamma(a / 2 + s) /
                  (2 * gamma(a / 2 - s + 1)), (Max(0, -re(a) / 2), oo), True)
    # TODO bessely(a, x)*besselk(a, x) is a mess
    assert MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s) == \
        (gamma(s)*gamma(
        a + s)*gamma(-s + S(1)/2)/(2*sqrt(pi)*gamma(a - s + 1)),
        (Max(-re(a), 0), S(1)/2), True)
    assert MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s) == \
        (2**(2*s - 1)*gamma(-2*s + 1)*gamma(-a/2 + b/2 + s)* \
        gamma(a/2 + b/2 + s)/(gamma(-a/2 + b/2 - s + 1)* \
        gamma(a/2 + b/2 - s + 1)), (Max(-re(a)/2 - re(b)/2, \
        re(a)/2 - re(b)/2), S(1)/2), True)

    # TODO products of besselk are a mess

    mt = MT(exp(-x / 2) * besselk(a, x / 2), x, s)
    mt0 = combsimp((trigsimp(combsimp(mt[0].expand(func=True)))))
    assert mt0 == 2 * pi**(S(3) / 2) * cos(pi * s) * gamma(-s + S(1) / 2) / (
        (cos(2 * pi * a) - cos(2 * pi * s)) * gamma(-a - s + 1) *
        gamma(a - s + 1))
    assert mt[1:] == ((Max(-re(a), re(a)), oo), True)
Example #44
0
def test_issue_21756():
    term = (1 - exp(-2 * I * pi * z)) / (1 - exp(-2 * I * pi * z / 5))
    assert term.limit(z, 0) == 5
    assert re(term).limit(z, 0) == 5
Example #45
0
def test_im():
    x, y = symbols('x,y')
    a, b = symbols('a,b', real=True)

    r = Symbol('r', real=True)
    i = Symbol('i', imaginary=True)

    assert im(nan) == nan

    assert im(oo * I) == oo
    assert im(-oo * I) == -oo

    assert im(0) == 0

    assert im(1) == 0
    assert im(-1) == 0

    assert im(E * I) == E
    assert im(-E * I) == -E

    assert im(x) == im(x)
    assert im(x * I) == re(x)
    assert im(r * I) == r
    assert im(r) == 0
    assert im(i * I) == 0
    assert im(i) == -I * i

    assert im(x + y) == im(x + y)
    assert im(x + r) == im(x)
    assert im(x + r * I) == im(x) + r

    assert im(im(x) * I) == im(x)

    assert im(2 + I) == 1
    assert im(x + I) == im(x) + 1

    assert im(x + y * I) == im(x) + re(y)
    assert im(x + r * I) == im(x) + r

    assert im(log(2 * I)) == pi / 2

    assert im((2 + I)**2).expand(complex=True) == 4

    assert im(conjugate(x)) == -im(x)
    assert conjugate(im(x)) == im(x)

    assert im(x).as_real_imag() == (im(x), 0)

    assert im(i * r * x).diff(r) == im(i * x)
    assert im(i * r * x).diff(i) == -I * re(r * x)

    assert im(
        sqrt(a +
             b * I)) == (a**2 + b**2)**Rational(1, 4) * sin(atan2(b, a) / 2)
    assert im(a * (2 + b * I)) == a * b

    assert im((1 + sqrt(a + b*I))/2) == \
        (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2

    assert im(x).rewrite(re) == x - re(x)
    assert (x + im(y)).rewrite(im, re) == x + y - re(y)

    a = Symbol('a', algebraic=True)
    t = Symbol('t', transcendental=True)
    x = Symbol('x')
    assert re(a).is_algebraic
    assert re(x).is_algebraic is None
    assert re(t).is_algebraic is False
Example #46
0
# 0 - Air
# 1 - Oil
# 2 - Gas
material_mode = 2

S0 = np.linspace(epsilon, 1 - epsilon, N)
w_array = [10, 100, 500, 1000, 5000]
w_label = [str(i) for i in w_array]
k = Symbol('k')

for i in range(len(w_array)):
    w = w_array[i]
    print('Progress: ' + str(int(100 * (i + 1) / 5)) + '%')
    disp_rel = transverse_disp(S0, w, material_mode)
    k_array = [list(solveset(i, k))[0] for i in disp_rel]
    speed_array = [w / abs(re(e)) for e in k_array]
    attenuation_array = [abs(im(e)) for e in k_array]

    plt.figure(1)
    plt.plot(S0, speed_array, '-', label=w_label[i])

    plt.figure(2)
    plt.semilogy(S0, attenuation_array, '-', label=w_label[i])

plt.figure(1)
plt.legend()
plt.xlabel(r'initial saturation $S_0$')
plt.ylabel(r'velocity / $ms^{-1}$')
plt.savefig('../plots/speed_sat_s.eps')
plt.clf()
Example #47
0
def test_re():
    x, y = symbols('x,y')
    a, b = symbols('a,b', real=True)

    r = Symbol('r', real=True)
    i = Symbol('i', imaginary=True)

    assert re(nan) == nan

    assert re(oo) == oo
    assert re(-oo) == -oo

    assert re(0) == 0

    assert re(1) == 1
    assert re(-1) == -1

    assert re(E) == E
    assert re(-E) == -E

    assert re(x) == re(x)
    assert re(x * I) == -im(x)
    assert re(r * I) == 0
    assert re(r) == r
    assert re(i * I) == I * i
    assert re(i) == 0

    assert re(x + y) == re(x + y)
    assert re(x + r) == re(x) + r

    assert re(re(x)) == re(x)

    assert re(2 + I) == 2
    assert re(x + I) == re(x)

    assert re(x + y * I) == re(x) - im(y)
    assert re(x + r * I) == re(x)

    assert re(log(2 * I)) == log(2)

    assert re((2 + I)**2).expand(complex=True) == 3

    assert re(conjugate(x)) == re(x)
    assert conjugate(re(x)) == re(x)

    assert re(x).as_real_imag() == (re(x), 0)

    assert re(i * r * x).diff(r) == re(i * x)
    assert re(i * r * x).diff(i) == I * r * im(x)

    assert re(
        sqrt(a +
             b * I)) == (a**2 + b**2)**Rational(1, 4) * cos(atan2(b, a) / 2)
    assert re(a * (2 + b * I)) == 2 * a

    assert re((1 + sqrt(a + b*I))/2) == \
        (a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)/2 + Rational(1, 2)

    assert re(x).rewrite(im) == x - im(x)
    assert (x + re(y)).rewrite(re, im) == x + y - im(y)

    a = Symbol('a', algebraic=True)
    t = Symbol('t', transcendental=True)
    x = Symbol('x')
    assert re(a).is_algebraic
    assert re(x).is_algebraic is None
    assert re(t).is_algebraic is False
Example #48
0
def _lambert(eq, x, domain=S.Complexes):
    """
    Given an expression assumed to be in the form
        ``F(X, a..f) = a*log(b*X + c) + d*X + f = 0``
    where X = g(x) and x = g^-1(X), return the Lambert solution,
        ``x = g^-1(-c/b + (a/d)*W(d/(a*b)*exp(c*d/a/b)*exp(-f/a)))``.
    """
    eq = _mexpand(expand_log(eq))
    mainlog = _mostfunc(eq, log, x)
    if not mainlog:
        return []  # violated assumptions
    other = eq.subs(mainlog, 0)
    if isinstance(-other, log):
        eq = (eq - other).subs(mainlog, mainlog.args[0])
        mainlog = mainlog.args[0]
        if not isinstance(mainlog, log):
            return []  # violated assumptions
        other = -(-other).args[0]
        eq += other
    if not x in other.free_symbols:
        return []  # violated assumptions
    d, f, X2 = _linab(other, x)
    logterm = collect(eq - other, mainlog)
    a = logterm.as_coefficient(mainlog)
    if a is None or x in a.free_symbols:
        return []  # violated assumptions
    logarg = mainlog.args[0]
    b, c, X1 = _linab(logarg, x)
    if X1 != X2:
        return []  # violated assumptions

    # invert the generator X1 so we have x(u)
    u = Dummy('rhs')

    xusolns = solve(X1 - u, x, domain=domain)

    # There are infinitely many branches for LambertW
    # but only branches for k = -1 and 0 might be real. The k = 0
    # branch is real and the k = -1 branch is real if the LambertW argumen
    # in in range [-1/e, 0]. Since `solve` does not return infinite
    # solutions we will only include the -1 branch if it tests as real.
    # Otherwise, inclusion of any LambertW in the solution indicates to
    #  the user that there are imaginary solutions corresponding to
    # different k values.
    lambert_real_branches = [-1, 0]
    sol = []

    # solution of the given Lambert equation is like
    # sol = -c/b + (a/d)*LambertW(arg, k),
    # where arg = d/(a*b)*exp((c*d-b*f)/a/b) and k in lambert_real_branches.
    # Instead of considering the single arg, `d/(a*b)*exp((c*d-b*f)/a/b)`,
    # the individual `p` roots obtained when writing `exp((c*d-b*f)/a/b)`
    # as `exp(A/p) = exp(A)**(1/p)`, where `p` is an Integer, are used.

    # calculating args for LambertW
    num, den = ((c * d - b * f) / a / b).as_numer_denom()
    p, den = den.as_coeff_Mul()
    e = exp(num / den)
    t = Dummy('t')
    real = None

    if p == 1:
        t = e
        args = [d / (a * b) * t]
    elif domain.is_real:
        ind_ls = [d / (a * b) * t for t in roots(t**p - e, t).keys()]
        args = []
        j = -1
        for i in ind_ls:
            j += 1
            if not isinstance(i, int):
                if not i.has(I):
                    args.append(ind_ls[j])
                    real = True
            elif isinstance(i, int):
                args.append(ind_ls[j])
    else:
        args = [d / (a * b) * t for t in roots(t**p - e, t).keys()]
    if len(args) == 0:
        return S.EmptySet
    # calculating solutions from args

    for arg in args:
        if not len(list(eq.atoms(Symbol, Dummy))) > 1:
            if not domain.is_subset(S.Reals) and (
                    re(arg) < -1 / E or
                    arg.has(I)) and (not LambertW(arg).is_real) and (not real):
                integer = Symbol('integer', integer=True)
                rhs = -c / b + (a / d) * LambertW(arg, integer)
                for xu in xusolns:
                    sol.append(xu.subs(u, rhs))
            else:
                if -1 / E <= re(arg) < 0 and LambertW(arg).is_real:
                    for k in lambert_real_branches:
                        w = LambertW(arg, k)
                        rhs = -c / b + (a / d) * w
                        for xu in xusolns:
                            sol.append(xu.subs(u, rhs))
                elif re(arg) >= 0 and LambertW(arg).is_real:
                    w = LambertW(arg)
                    rhs = -c / b + (a / d) * w
                    for xu in xusolns:
                        sol.append(xu.subs(u, rhs))
                elif re(arg) < -1 / E:
                    return S.EmptySet

        elif (arg.has(Symbol)) and not arg.has(Dummy):
            if (list(arg.atoms(Symbol))[0]).is_negative and (list(
                    arg.atoms(Symbol))[0]).is_real and domain.is_subset(
                        S.Reals):
                for k in lambert_real_branches:
                    w = LambertW(arg, k)
                    rhs = -c / b + (a / d) * w
                    if rhs.has(I) or w.has(I):
                        continue
                    for xu in xusolns:
                        sol.append(xu.subs(u, rhs))

            if (list(arg.atoms(Symbol))[0]).is_positive and (list(
                    arg.atoms(Symbol))[0]).is_real and domain.is_subset(
                        S.Reals):
                w = LambertW(arg)
                rhs = -c / b + (a / d) * w
                if rhs.has(I) or w.has(I):
                    continue

                for xu in xusolns:
                    sol.append(xu.subs(u, rhs))

            if (list(arg.atoms(Symbol))[0]).is_negative and (list(
                    arg.atoms(Symbol))[0]).is_real and not domain.is_subset(
                        S.Reals):
                integer = Symbol('integer', integer=True)
                rhs = -c / b + (a / d) * LambertW(arg, integer)

                for xu in xusolns:
                    sol.append(xu.subs(u, rhs))

            elif domain.is_subset(S.Reals):
                for k in lambert_real_branches:
                    w = LambertW(arg, k)
                    rhs = -c / b + (a / d) * w
                    if rhs.has(I) or w.has(I):
                        continue
                    for xu in xusolns:
                        sol.append(xu.subs(u, rhs))

            elif domain.is_subset(S.Complexes):
                integer = Symbol('integer', integer=True)
                rhs = -c / b + (a / d) * LambertW(arg, integer)
                for xu in xusolns:
                    sol.append(xu.subs(u, rhs))

        else:
            if not domain.is_subset(
                    S.Reals) and (not LambertW(arg).is_real) and (not real):
                integer = Symbol('integer', integer=True)
                rhs = Lambda(integer,
                             -c / b + (a / d) * LambertW(arg, integer))
                for xu in xusolns:
                    sol.append(xu.subs(u, rhs))
            else:
                w = LambertW(arg)
                rhs = -c / b + (a / d) * w
                for xu in xusolns:
                    sol.append(xu.subs(u, rhs))

    return list(set(sol))
Example #49
0
def test_meijerint():
    from sympy import symbols, expand, arg
    s, t, mu = symbols('s t mu', real=True)
    assert integrate(
        meijerg([], [], [0], [], s * t) *
        meijerg([], [], [mu / 2], [-mu / 2], t**2 / 4),
        (t, 0, oo)).is_Piecewise
    s = symbols('s', positive=True)
    assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo)) == \
        gamma(s + 1)
    assert integrate(x**s * meijerg([[], []], [[0], []], x), (x, 0, oo),
                     meijerg=True) == gamma(s + 1)
    assert isinstance(
        integrate(x**s * meijerg([[], []], [[0], []], x), (x, 0, oo),
                  meijerg=False), Integral)

    assert meijerint_indefinite(exp(x), x) == exp(x)

    # TODO what simplifications should be done automatically?
    # This tests "extra case" for antecedents_1.
    a, b = symbols('a b', positive=True)
    assert simplify(meijerint_definite(x**a, x, 0, b)[0]) == \
        b**(a + 1)/(a + 1)

    # This tests various conditions and expansions:
    meijerint_definite((x + 1)**3 * exp(-x), x, 0, oo) == (16, True)

    # Again, how about simplifications?
    sigma, mu = symbols('sigma mu', positive=True)
    i, c = meijerint_definite(exp(-((x - mu) / (2 * sigma))**2), x, 0, oo)
    assert simplify(i) == sqrt(pi) * sigma * (2 - erfc(mu / (2 * sigma)))
    assert c == True

    i, _ = meijerint_definite(exp(-mu * x) * exp(sigma * x), x, 0, oo)
    # TODO it would be nice to test the condition
    assert simplify(i) == 1 / (mu - sigma)

    # Test substitutions to change limits
    assert meijerint_definite(exp(x), x, -oo, 2) == (exp(2), True)
    # Note: causes a NaN in _check_antecedents
    assert expand(meijerint_definite(exp(x), x, 0, I)[0]) == exp(I) - 1
    assert expand(meijerint_definite(exp(-x), x, 0, x)[0]) == \
        1 - exp(-exp(I*arg(x))*abs(x))

    # Test -oo to oo
    assert meijerint_definite(exp(-x**2), x, -oo, oo) == (sqrt(pi), True)
    assert meijerint_definite(exp(-abs(x)), x, -oo, oo) == (2, True)
    assert meijerint_definite(exp(-(2*x - 3)**2), x, -oo, oo) == \
        (sqrt(pi)/2, True)
    assert meijerint_definite(exp(-abs(2 * x - 3)), x, -oo, oo) == (1, True)
    assert meijerint_definite(
        exp(-((x - mu) / sigma)**2 / 2) / sqrt(2 * pi * sigma**2), x, -oo,
        oo) == (1, True)
    assert meijerint_definite(sinc(x)**2, x, -oo, oo) == (pi, True)

    # Test one of the extra conditions for 2 g-functinos
    assert meijerint_definite(exp(-x) * sin(x), x, 0, oo) == (S(1) / 2, True)

    # Test a bug
    def res(n):
        return (1 / (1 + x**2)).diff(x, n).subs(x, 1) * (-1)**n

    for n in range(6):
        assert integrate(exp(-x)*sin(x)*x**n, (x, 0, oo), meijerg=True) == \
            res(n)

    # This used to test trigexpand... now it is done by linear substitution
    assert simplify(integrate(exp(-x) * sin(x + a), (x, 0, oo),
                              meijerg=True)) == sqrt(2) * sin(a + pi / 4) / 2

    # Test the condition 14 from prudnikov.
    # (This is besselj*besselj in disguise, to stop the product from being
    #  recognised in the tables.)
    a, b, s = symbols('a b s')
    from sympy import And, re
    assert meijerint_definite(meijerg([], [], [a/2], [-a/2], x/4)
                  *meijerg([], [], [b/2], [-b/2], x/4)*x**(s - 1), x, 0, oo) == \
        (4*2**(2*s - 2)*gamma(-2*s + 1)*gamma(a/2 + b/2 + s)
         /(gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1)
           *gamma(a/2 + b/2 - s + 1)),
            And(0 < -2*re(4*s) + 8, 0 < re(a/2 + b/2 + s), re(2*s) < 1))

    # test a bug
    assert integrate(sin(x**a)*sin(x**b), (x, 0, oo), meijerg=True) == \
        Integral(sin(x**a)*sin(x**b), (x, 0, oo))

    # test better hyperexpand
    assert integrate(exp(-x**2)*log(x), (x, 0, oo), meijerg=True) == \
        (sqrt(pi)*polygamma(0, S(1)/2)/4).expand()

    # Test hyperexpand bug.
    from sympy import lowergamma
    n = symbols('n', integer=True)
    assert simplify(integrate(exp(-x)*x**n, x, meijerg=True)) == \
        lowergamma(n + 1, x)

    # Test a bug with argument 1/x
    alpha = symbols('alpha', positive=True)
    assert meijerint_definite((2 - x)**alpha*sin(alpha/x), x, 0, 2) == \
        (sqrt(pi)*alpha*gamma(alpha + 1)*meijerg(((), (alpha/2 + S(1)/2,
        alpha/2 + 1)), ((0, 0, S(1)/2), (-S(1)/2,)), alpha**S(2)/16)/4, True)

    # test a bug related to 3016
    a, s = symbols('a s', positive=True)
    assert simplify(integrate(x**s*exp(-a*x**2), (x, -oo, oo))) == \
        a**(-s/2 - S(1)/2)*((-1)**s + 1)*gamma(s/2 + S(1)/2)/2
Example #50
0
 def coeff(s, p2, q2):
     numerator = [re(p2.coeff(s, i)) for i in range(order, -1, -1)]
     denominator = [re(q2.coeff(s, i)) for i in range(order, -1, -1)]
     return numerator, denominator
Example #51
0
def test_re():
    x, y = symbols('x,y')
    a, b = symbols('a,b', real=True)

    r = Symbol('r', real=True)
    i = Symbol('i', imaginary=True)

    assert re(nan) == nan

    assert re(oo) == oo
    assert re(-oo) == -oo

    assert re(0) == 0

    assert re(1) == 1
    assert re(-1) == -1

    assert re(E) == E
    assert re(-E) == -E

    assert re(x) == re(x)
    assert re(x * I) == -im(x)
    assert re(r * I) == 0
    assert re(r) == r
    assert re(i * I) == I * i
    assert re(i) == 0

    assert re(x + y) == re(x + y)
    assert re(x + r) == re(x) + r

    assert re(re(x)) == re(x)

    assert re(2 + I) == 2
    assert re(x + I) == re(x)

    assert re(x + y * I) == re(x) - im(y)
    assert re(x + r * I) == re(x)

    assert re(log(2 * I)) == log(2)

    assert re((2 + I)**2).expand(complex=True) == 3

    assert re(conjugate(x)) == re(x)
    assert conjugate(re(x)) == re(x)

    assert re(x).as_real_imag() == (re(x), 0)

    assert re(i * r * x).diff(r) == re(i * x)
    assert re(i * r * x).diff(i) == I * r * im(x)

    assert re(
        sqrt(a +
             b * I)) == (a**2 + b**2)**Rational(1, 4) * cos(atan2(b, a) / 2)
    assert re(a * (2 + b * I)) == 2 * a

    assert re((1 + sqrt(a + b*I))/2) == \
        (a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)/2 + Rational(1, 2)
Example #52
0
def test_latex_functions():
    assert latex(exp(x)) == "e^{x}"
    assert latex(exp(1) + exp(2)) == "e + e^{2}"

    f = Function('f')
    assert latex(f(x)) == '\\operatorname{f}{\\left (x \\right )}'

    beta = Function('beta')

    assert latex(beta(x)) == r"\beta{\left (x \right )}"
    assert latex(sin(x)) == r"\sin{\left (x \right )}"
    assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}"
    assert latex(sin(2*x**2), fold_func_brackets=True) == \
        r"\sin {2 x^{2}}"
    assert latex(sin(x**2), fold_func_brackets=True) == \
        r"\sin {x^{2}}"

    assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left (x \right )}"
    assert latex(asin(x)**2, inv_trig_style="full") == \
        r"\arcsin^{2}{\left (x \right )}"
    assert latex(asin(x)**2, inv_trig_style="power") == \
        r"\sin^{-1}{\left (x \right )}^{2}"
    assert latex(asin(x**2), inv_trig_style="power",
                 fold_func_brackets=True) == \
        r"\sin^{-1} {x^{2}}"

    assert latex(factorial(k)) == r"k!"
    assert latex(factorial(-k)) == r"\left(- k\right)!"

    assert latex(factorial2(k)) == r"k!!"
    assert latex(factorial2(-k)) == r"\left(- k\right)!!"

    assert latex(binomial(2, k)) == r"{\binom{2}{k}}"

    assert latex(FallingFactorial(3,
                                  k)) == r"{\left(3\right)}_{\left(k\right)}"
    assert latex(RisingFactorial(3, k)) == r"{\left(3\right)}^{\left(k\right)}"

    assert latex(floor(x)) == r"\lfloor{x}\rfloor"
    assert latex(ceiling(x)) == r"\lceil{x}\rceil"
    assert latex(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)"
    assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)"
    assert latex(Abs(x)) == r"\lvert{x}\rvert"
    assert latex(re(x)) == r"\Re{x}"
    assert latex(re(x + y)) == r"\Re{x} + \Re{y}"
    assert latex(im(x)) == r"\Im{x}"
    assert latex(conjugate(x)) == r"\overline{x}"
    assert latex(gamma(x)) == r"\Gamma\left(x\right)"
    assert latex(Order(x)) == r"\mathcal{O}\left(x\right)"
    assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)'
    assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)'

    assert latex(cot(x)) == r'\cot{\left (x \right )}'
    assert latex(coth(x)) == r'\coth{\left (x \right )}'
    assert latex(re(x)) == r'\Re{x}'
    assert latex(im(x)) == r'\Im{x}'
    assert latex(root(x, y)) == r'x^{\frac{1}{y}}'
    assert latex(arg(x)) == r'\arg{\left (x \right )}'
    assert latex(zeta(x)) == r'\zeta\left(x\right)'

    assert latex(zeta(x)) == r"\zeta\left(x\right)"
    assert latex(zeta(x)**2) == r"\zeta^{2}\left(x\right)"
    assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)"
    assert latex(zeta(x, y)**2) == r"\zeta^{2}\left(x, y\right)"
    assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)"
    assert latex(dirichlet_eta(x)**2) == r"\eta^{2}\left(x\right)"
    assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)"
    assert latex(polylog(x,
                         y)**2) == r"\operatorname{Li}_{x}^{2}\left(y\right)"
    assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)"
    assert latex(lerchphi(x, y, n)**2) == r"\Phi^{2}\left(x, y, n\right)"

    assert latex(Ei(x)) == r'\operatorname{Ei}{\left (x \right )}'
    assert latex(Ei(x)**2) == r'\operatorname{Ei}^{2}{\left (x \right )}'
    assert latex(expint(x, y)**2) == r'\operatorname{E}_{x}^{2}\left(y\right)'
    assert latex(Shi(x)**2) == r'\operatorname{Shi}^{2}{\left (x \right )}'
    assert latex(Si(x)**2) == r'\operatorname{Si}^{2}{\left (x \right )}'
    assert latex(Ci(x)**2) == r'\operatorname{Ci}^{2}{\left (x \right )}'
    assert latex(Chi(x)**2) == r'\operatorname{Chi}^{2}{\left (x \right )}'

    assert latex(jacobi(n, a, b,
                        x)) == r'P_{n}^{\left(a,b\right)}\left(x\right)'
    assert latex(jacobi(
        n, a, b,
        x)**2) == r'\left(P_{n}^{\left(a,b\right)}\left(x\right)\right)^{2}'
    assert latex(gegenbauer(n, a,
                            x)) == r'C_{n}^{\left(a\right)}\left(x\right)'
    assert latex(gegenbauer(
        n, a,
        x)**2) == r'\left(C_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(chebyshevt(n, x)) == r'T_{n}\left(x\right)'
    assert latex(chebyshevt(n,
                            x)**2) == r'\left(T_{n}\left(x\right)\right)^{2}'
    assert latex(chebyshevu(n, x)) == r'U_{n}\left(x\right)'
    assert latex(chebyshevu(n,
                            x)**2) == r'\left(U_{n}\left(x\right)\right)^{2}'
    assert latex(legendre(n, x)) == r'P_{n}\left(x\right)'
    assert latex(legendre(n, x)**2) == r'\left(P_{n}\left(x\right)\right)^{2}'
    assert latex(assoc_legendre(n, a,
                                x)) == r'P_{n}^{\left(a\right)}\left(x\right)'
    assert latex(assoc_legendre(
        n, a,
        x)**2) == r'\left(P_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(laguerre(n, x)) == r'L_{n}\left(x\right)'
    assert latex(laguerre(n, x)**2) == r'\left(L_{n}\left(x\right)\right)^{2}'
    assert latex(assoc_laguerre(n, a,
                                x)) == r'L_{n}^{\left(a\right)}\left(x\right)'
    assert latex(assoc_laguerre(
        n, a,
        x)**2) == r'\left(L_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
    assert latex(hermite(n, x)) == r'H_{n}\left(x\right)'
    assert latex(hermite(n, x)**2) == r'\left(H_{n}\left(x\right)\right)^{2}'

    # Test latex printing of function names with "_"
    assert latex(
        polar_lift(0)) == r"\operatorname{polar\_lift}{\left (0 \right )}"
    assert latex(polar_lift(0)**
                 3) == r"\operatorname{polar\_lift}^{3}{\left (0 \right )}"
Example #53
0
File: rde.py Project: msgoff/sympy
                etaa, etad = frac_in(dcoeff, DE.t)
                A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE)
                if A is not None:
                    Q, m, z = A
                    if Q == 1:
                        n = min(n, m)

        elif case == "tan":
            dcoeff = DE.d.quo(Poly(DE.t**2 + 1, DE.t))
            with DecrementLevel(DE):  # We are guaranteed to not have problems,
                # because case != 'base'.
                alphaa, alphad = frac_in(
                    im(-ba.eval(sqrt(-1)) / bd.eval(sqrt(-1)) /
                       a.eval(sqrt(-1))), DE.t)
                betaa, betad = frac_in(
                    re(-ba.eval(sqrt(-1)) / bd.eval(sqrt(-1)) /
                       a.eval(sqrt(-1))), DE.t)
                etaa, etad = frac_in(dcoeff, DE.t)

                if recognize_log_derivative(2 * betaa, betad, DE):
                    A = parametric_log_deriv(
                        alphaa * sqrt(-1) * betad + alphad * betaa,
                        alphad * betad,
                        etaa,
                        etad,
                        DE,
                    )
                    if A is not None:
                        Q, m, z = A
                        if Q == 1:
                            n = min(n, m)
    N = max(0, -nb, n - nc)
Example #54
0
def test_polygamma():
    from sympy import I

    assert polygamma(n, nan) is nan

    assert polygamma(0, oo) is oo
    assert polygamma(0, -oo) is oo
    assert polygamma(0, I * oo) is oo
    assert polygamma(0, -I * oo) is oo
    assert polygamma(1, oo) == 0
    assert polygamma(5, oo) == 0

    assert polygamma(0, -9) is zoo

    assert polygamma(0, -9) is zoo
    assert polygamma(0, -1) is zoo

    assert polygamma(0, 0) is zoo

    assert polygamma(0, 1) == -EulerGamma
    assert polygamma(0, 7) == Rational(49, 20) - EulerGamma

    assert polygamma(1, 1) == pi**2 / 6
    assert polygamma(1, 2) == pi**2 / 6 - 1
    assert polygamma(1, 3) == pi**2 / 6 - Rational(5, 4)
    assert polygamma(3, 1) == pi**4 / 15
    assert polygamma(3, 5) == 6 * (Rational(-22369, 20736) + pi**4 / 90)
    assert polygamma(5, 1) == 8 * pi**6 / 63

    assert polygamma(1, S.Half) == pi**2 / 2
    assert polygamma(2, S.Half) == -14 * zeta(3)
    assert polygamma(11, S.Half) == 176896 * pi**12

    def t(m, n):
        x = S(m) / n
        r = polygamma(0, x)
        if r.has(polygamma):
            return False
        return abs(polygamma(0, x.n()).n() - r.n()).n() < 1e-10

    assert t(1, 2)
    assert t(3, 2)
    assert t(-1, 2)
    assert t(1, 4)
    assert t(-3, 4)
    assert t(1, 3)
    assert t(4, 3)
    assert t(3, 4)
    assert t(2, 3)
    assert t(123, 5)

    assert polygamma(0, x).rewrite(zeta) == polygamma(0, x)
    assert polygamma(1, x).rewrite(zeta) == zeta(2, x)
    assert polygamma(2, x).rewrite(zeta) == -2 * zeta(3, x)
    assert polygamma(I, 2).rewrite(zeta) == polygamma(I, 2)
    n1 = Symbol('n1')
    n2 = Symbol('n2', real=True)
    n3 = Symbol('n3', integer=True)
    n4 = Symbol('n4', positive=True)
    n5 = Symbol('n5', positive=True, integer=True)
    assert polygamma(n1, x).rewrite(zeta) == polygamma(n1, x)
    assert polygamma(n2, x).rewrite(zeta) == polygamma(n2, x)
    assert polygamma(n3, x).rewrite(zeta) == polygamma(n3, x)
    assert polygamma(n4, x).rewrite(zeta) == polygamma(n4, x)
    assert polygamma(
        n5,
        x).rewrite(zeta) == (-1)**(n5 + 1) * factorial(n5) * zeta(n5 + 1, x)

    assert polygamma(3, 7 * x).diff(x) == 7 * polygamma(4, 7 * x)

    assert polygamma(0, x).rewrite(harmonic) == harmonic(x - 1) - EulerGamma
    assert polygamma(
        2, x).rewrite(harmonic) == 2 * harmonic(x - 1, 3) - 2 * zeta(3)
    ni = Symbol("n", integer=True)
    assert polygamma(
        ni,
        x).rewrite(harmonic) == (-1)**(ni + 1) * (-harmonic(x - 1, ni + 1) +
                                                  zeta(ni + 1)) * factorial(ni)

    # Polygamma of non-negative integer order is unbranched:
    from sympy import exp_polar
    k = Symbol('n', integer=True, nonnegative=True)
    assert polygamma(k, exp_polar(2 * I * pi) * x) == polygamma(k, x)

    # but negative integers are branched!
    k = Symbol('n', integer=True)
    assert polygamma(k,
                     exp_polar(2 * I * pi) *
                     x).args == (k, exp_polar(2 * I * pi) * x)

    # Polygamma of order -1 is loggamma:
    assert polygamma(-1, x) == loggamma(x)

    # But smaller orders are iterated integrals and don't have a special name
    assert polygamma(-2, x).func is polygamma

    # Test a bug
    assert polygamma(0, -x).expand(func=True) == polygamma(0, -x)

    assert polygamma(2, 2.5).is_positive == False
    assert polygamma(2, -2.5).is_positive == False
    assert polygamma(3, 2.5).is_positive == True
    assert polygamma(3, -2.5).is_positive is True
    assert polygamma(-2, -2.5).is_positive is None
    assert polygamma(-3, -2.5).is_positive is None

    assert polygamma(2, 2.5).is_negative == True
    assert polygamma(3, 2.5).is_negative == False
    assert polygamma(3, -2.5).is_negative == False
    assert polygamma(2, -2.5).is_negative is True
    assert polygamma(-2, -2.5).is_negative is None
    assert polygamma(-3, -2.5).is_negative is None

    assert polygamma(I, 2).is_positive is None
    assert polygamma(I, 3).is_negative is None

    # issue 17350
    assert polygamma(pi, 3).evalf() == polygamma(pi, 3)
    assert (I*polygamma(I, pi)).as_real_imag() == \
           (-im(polygamma(I, pi)), re(polygamma(I, pi)))
    assert (tanh(polygamma(I, 1))).rewrite(exp) == \
           (exp(polygamma(I, 1)) - exp(-polygamma(I, 1)))/(exp(polygamma(I, 1)) + exp(-polygamma(I, 1)))
    assert (I / polygamma(I, 4)).rewrite(exp) == \
           I*sqrt(re(polygamma(I, 4))**2 + im(polygamma(I, 4))**2)\
           /((re(polygamma(I, 4)) + I*im(polygamma(I, 4)))*Abs(polygamma(I, 4)))
    assert unchanged(polygamma, 2.3, 1.0)

    # issue 12569
    assert unchanged(im, polygamma(0, I))
    assert polygamma(Symbol('a', positive=True), Symbol(
        'b', positive=True)).is_real is True
    assert polygamma(0, I).is_real is None
Example #55
0
        equation = equation.subs(r4, 10000)
    elif case == 3:
        equation = equation.subs(r1, 25000)
        equation = equation.subs(r2, 2500)
        equation = equation.subs(r3, 25000)
        equation = equation.subs(r4, 100000)
    return simplify(equation)


s = Symbol('s')
aw = A0 / (1 + s / WP)  #W or wp?

h = -((r2 / r1) / (1 + ((r2 / r1) / a) + (1 / a) + ((r2 / r3) / a)))
h = simplify(h)

hMod = sqrt(re(h)**2 + im(h)**2)
hMod = simplify(hMod)

print("inverter: Vo/Vi=")
result1 = replaceValues(
    h, 1, A0)  #pasarle A0 o aw dependiendo de lo que quiera analizar.
print("CASO 1>")
print(latex(result1.evalf()))

result2 = replaceValues(
    h, 2, A0)  #pasarle A0 o aw dependiendo de lo que quiera analizar.
print("CASO 2>")
print(latex(result2.evalf()))

result3 = replaceValues(
    h, 3, A0)  #pasarle A0 o aw dependiendo de lo que quiera analizar.
Example #56
0
def test_mellin_transform():
    from sympy import Max, Min
    MT = mellin_transform

    bpos = symbols('b', positive=True)

    # 8.4.2
    assert MT(x**nu*Heaviside(x - 1), x, s) == \
        (-1/(nu + s), (-oo, -re(nu)), True)
    assert MT(x**nu*Heaviside(1 - x), x, s) == \
        (1/(nu + s), (-re(nu), oo), True)

    assert MT((1 - x)**(beta - 1)*Heaviside(1 - x), x, s) == \
        (gamma(beta)*gamma(s)/gamma(beta + s), (0, oo), re(-beta) < 0)
    assert MT((x - 1)**(beta - 1)*Heaviside(x - 1), x, s) == \
        (gamma(beta)*gamma(1 - beta - s)/gamma(1 - s),
            (-oo, -re(beta) + 1), re(-beta) < 0)

    assert MT((1 + x)**(-rho), x, s) == \
        (gamma(s)*gamma(rho - s)/gamma(rho), (0, re(rho)), True)

    # TODO also the conditions should be simplified
    assert MT(abs(1 - x)**(-rho), x,
              s) == (2 * sin(pi * rho / 2) * gamma(1 - rho) *
                     cos(pi * (rho / 2 - s)) * gamma(s) * gamma(rho - s) / pi,
                     (0, re(rho)), And(re(rho) - 1 < 0,
                                       re(rho) < 1))
    mt = MT((1 - x)**(beta - 1) * Heaviside(1 - x) + a *
            (x - 1)**(beta - 1) * Heaviside(x - 1), x, s)
    assert mt[1], mt[2] == ((0, -re(beta) + 1), True)

    assert MT((x**a - b**a)/(x - b), x, s)[0] == \
        pi*b**(a + s - 1)*sin(pi*a)/(sin(pi*s)*sin(pi*(a + s)))
    assert MT((x**a - bpos**a)/(x - bpos), x, s) == \
        (pi*bpos**(a + s - 1)*sin(pi*a)/(sin(pi*s)*sin(pi*(a + s))),
            (Max(-re(a), 0), Min(1 - re(a), 1)), True)

    expr = (sqrt(x + b**2) + b)**a
    assert MT(expr.subs(b, bpos), x, s) == \
        (-a*(2*bpos)**(a + 2*s)*gamma(s)*gamma(-a - 2*s)/gamma(-a - s + 1),
         (0, -re(a)/2), True)

    expr = (sqrt(x + b**2) + b)**a / sqrt(x + b**2)
    assert MT(expr.subs(b, bpos), x, s) == \
        (2**(a + 2*s)*bpos**(a + 2*s - 1)*gamma(s)
                                         *gamma(1 - a - 2*s)/gamma(1 - a - s),
            (0, -re(a)/2 + S(1)/2), True)

    # 8.4.2
    assert MT(exp(-x), x, s) == (gamma(s), (0, oo), True)
    assert MT(exp(-1 / x), x, s) == (gamma(-s), (-oo, 0), True)

    # 8.4.5
    assert MT(log(x)**4 * Heaviside(1 - x), x, s) == (24 / s**5, (0, oo), True)
    assert MT(log(x)**3 * Heaviside(x - 1), x, s) == (6 / s**4, (-oo, 0), True)
    assert MT(log(x + 1), x, s) == (pi / (s * sin(pi * s)), (-1, 0), True)
    assert MT(log(1 / x + 1), x, s) == (pi / (s * sin(pi * s)), (0, 1), True)
    assert MT(log(abs(1 - x)), x, s) == (pi / (s * tan(pi * s)), (-1, 0), True)
    assert MT(log(abs(1 - 1 / x)), x,
              s) == (pi / (s * tan(pi * s)), (0, 1), True)

    # TODO we cannot currently do these (needs summation of 3F2(-1))
    #      this also implies that they cannot be written as a single g-function
    #      (although this is possible)
    mt = MT(log(x) / (x + 1), x, s)
    assert mt[1:] == ((0, 1), True)
    assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg)
    mt = MT(log(x)**2 / (x + 1), x, s)
    assert mt[1:] == ((0, 1), True)
    assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg)
    mt = MT(log(x) / (x + 1)**2, x, s)
    assert mt[1:] == ((0, 2), True)
    assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg)

    # 8.4.14
    assert MT(erf(sqrt(x)), x, s) == \
        (-gamma(s + S(1)/2)/(sqrt(pi)*s), (-S(1)/2, 0), True)
Example #57
0
def test_issue_1985():
    x = Symbol('x')
    assert ((x + x*I)/(1 + I)).as_real_imag() == (re((x + I*x)/(1 + I)
            ), im((x + I*x)/(1 + I)))
Example #58
0
def get_constraint(eigenvals, vib_modes, operation):
    princ_rot = eigenvals[0]
    refl_Re, refl_Im = eigenvals[1], eigenvals[2]
    inver_eigenval = eigenvals[3]
    try:
        os.chdir(os.getcwd() + '/constraints')
        constraintfiles = os.listdir(os.getcwd())
        constraintargs = [sym.sympify(i[0:i.index('_')].replace('X','*')) for i in constraintfiles]
        #Open refl.sym file
        for arg in constraintargs:
            if sym.simplify(princ_rot-arg) == 0:
                with open(replace_all(str(arg),{'*':'X',' ':''})+"_"+operation+".sym","r") as sym_file:
                    constraint_lines  = sym_file.readlines()
            elif sym.simplify(sym.re(princ_rot)-sym.im(princ_rot)*1j - arg) == 0:
                with open(replace_all(str(arg),{'*':'X',' ':''})+"_"+operation+".sym","r") as sym_file:
                    constraint_lines  = sym_file.readlines()
        os.chdir('..')
    except OSError as e:
        print(e)
        
    vib_modes = [i.replace("''",'"') for i in vib_modes]

    if operation == 'refl':
        eigen_req = '[' + str(refl_Re) + ',' + str(refl_Im) + ']'
        vib_modes = [replace_all(i,{'G':'','U':'',"'":'','"':''}) for i in vib_modes]

    elif operation == 'inver' or operation == 'hrefl':
        eigen_req = '[' + str(inver_eigenval) + ']'
        vib_modes = [replace_all(i,{'1':'','2':''}) for i in vib_modes]

    if len(vib_modes) == 1:        
        if operation == 'refl':
            vib_modes.append('A1')
        elif operation == 'inver':
            vib_modes.append('AG')
        elif operation == 'hrefl':
            vib_modes.append("A'")
    mode_req = vib_modes
    max_count = len(constraint_lines) - 1
    for count,line in enumerate(constraint_lines):
        modes_in_line = ''.join(line.split(',')[0])
        modes_in_line = modes_in_line[1:-1]
        modes_in_line = modes_in_line.split('.')
        line = line.replace('\n','')  
        if set([str(mode) for mode in mode_req]) == set(modes_in_line) and eigen_req in line:
            match_line = line
        if (count == max_count):
            try:
                match_line
            except NameError: #no matching constraints
                return {}
    constraints = match_line.split(': ',1)[1]

    constraints = constraints.split(',')
    constraints_dict = {}
    for constraint in constraints:
        index = constraint.split(' ')[0]
        restriction = ' '.join(constraint.split(' ')[1:])
        constraints_dict[index] = restriction
    if 'all' in constraints_dict:
        if constraints_dict['all'] == 'nr':
            del constraints_dict['all'] #check if any composite cases where 
    return constraints_dict
Example #59
0
def test_cosh():
    x, y = symbols('x,y')

    k = Symbol('k', integer=True)

    assert cosh(nan) == nan
    assert cosh(zoo) == nan

    assert cosh(oo) == oo
    assert cosh(-oo) == oo

    assert cosh(0) == 1

    assert cosh(1) == cosh(1)
    assert cosh(-1) == cosh(1)

    assert cosh(x) == cosh(x)
    assert cosh(-x) == cosh(x)

    assert cosh(pi*I) == cos(pi)
    assert cosh(-pi*I) == cos(pi)

    assert cosh(2**1024 * E) == cosh(2**1024 * E)
    assert cosh(-2**1024 * E) == cosh(2**1024 * E)

    assert cosh(pi*I/2) == 0
    assert cosh(-pi*I/2) == 0
    assert cosh((-3*10**73 + 1)*pi*I/2) == 0
    assert cosh((7*10**103 + 1)*pi*I/2) == 0

    assert cosh(pi*I) == -1
    assert cosh(-pi*I) == -1
    assert cosh(5*pi*I) == -1
    assert cosh(8*pi*I) == 1

    assert cosh(pi*I/3) == S.Half
    assert cosh(-2*pi*I/3) == -S.Half

    assert cosh(pi*I/4) == S.Half*sqrt(2)
    assert cosh(-pi*I/4) == S.Half*sqrt(2)
    assert cosh(11*pi*I/4) == -S.Half*sqrt(2)
    assert cosh(-3*pi*I/4) == -S.Half*sqrt(2)

    assert cosh(pi*I/6) == S.Half*sqrt(3)
    assert cosh(-pi*I/6) == S.Half*sqrt(3)
    assert cosh(7*pi*I/6) == -S.Half*sqrt(3)
    assert cosh(-5*pi*I/6) == -S.Half*sqrt(3)

    assert cosh(pi*I/105) == cos(pi/105)
    assert cosh(-pi*I/105) == cos(pi/105)

    assert cosh(2 + 3*I) == cosh(2 + 3*I)

    assert cosh(x*I) == cos(x)

    assert cosh(k*pi*I) == cos(k*pi)
    assert cosh(17*k*pi*I) == cos(17*k*pi)

    assert cosh(k*pi) == cosh(k*pi)

    assert cosh(x).as_real_imag(deep=False) == (cos(im(x))*cosh(re(x)),
                sin(im(x))*sinh(re(x)))
    x = Symbol('x', extended_real=True)
    assert cosh(x).as_real_imag(deep=False) == (cosh(x), 0)

    x = Symbol('x', real=True)
    assert cosh(I*x).is_finite is True
Example #60
0
def duoparam_analysis(N, subplot, alpha=_alpha, k1=_k1, k_1=_k_1, k2=_k2, k_2=_k_2, k3=_k3):
    xstep = np.linspace(0, 1, N)
    x, y, k2, k1 = sp.symbols('x y k2 k1')
    f1 = k1 * (1 - x - y) - k_1 * x - k3 * (1 - x)**alpha * x * y
    f2 = k2 * (1 - x - y) ** 2 - k_2 * y**2 - k3 * (1 - x)**alpha * x * y

    eq1 = sp.lambdify((x, y, k1), f1)
    eq2 = sp.lambdify((x, y, k2), f2)
    Y, X = np.mgrid[0:.5:1000j, 0:1:2000j]

    U = eq1(X, Y, 0.012)
    V = eq2(X, Y, 0.012)
    print("HERE")
    velocity = np.sqrt(U * U + V * V)
    plt.streamplot(X, Y, U, V, density=[2.5, 0.8], color=velocity)
    plt.xlabel('x')
    plt.ylabel('y')
    # plt.xlim([0.1, 0.5])
    # plt.ylim([0.1, 0.5])
    # plt.title('Phase portrait')
    plt.show()

    #след и определитель Якобиана
    A = sp.Matrix([f1, f2])
    jacA = A.jacobian([x, y])
    det_jacA = jacA.det()
    trace = sp.trace(jacA)

    Y = sp.solve(f1, y)[0]
    Det = sp.solve(det_jacA.subs(y, Y), k2)[0]
    Trace = sp.solve(trace.subs(y, Y), k2)[0]
    K2 = sp.solve(f2.subs(y, Y), k2)[0]
    res = Det - K2
    tr = sp.solve(Trace - K2, k1)[0]
    print("3.5: ", res)
    print("tr", tr)
    # print("3.5: ", sp.expand(Det - K2))
    # K1 = sp.solve((Det - K2), k1)[0]
    # print("4 ", K1)

    k1step_det = []
    k2step_det = []
    k1step_tr = []
    k2step_tr = []

    dots = []
    for i in xstep:
        sol1 = sp.solve(res.subs(x, i), k1)
        # print("sol", sol1)
        if len(sol1) > 0:
            tmpk1_det = sol1[0]
            tmpk2_det = Det.subs([(k1, tmpk1_det), (x, i)])
            # print("tmpk1", tmpk1_det)
            # print("tmpk2", tmpk2_det)
            k1step_det.append(sp.re(tmpk1_det))
            k2step_det.append(sp.re(tmpk2_det))

        tmpk1_tr = tr.subs(x, i)
        tmpk2_tr = Trace.subs([(k1, tmpk1_tr), (x, i)])
        k1step_tr.append(sp.re(tmpk1_tr))
        k2step_tr.append(sp.re(tmpk2_tr))
        print(i)
    print("k1det", k1step_det)
    print("k1tr", k1step_tr)
    param_plot(k1step_det, k2step_det, subplot1, 'g', [0, 1], 0)
    param_plot(k1step_tr, k2step_tr, subplot1, 'b', [0, 1], 0)