Exemple #1
0
def test_expand_non_commutative():
    A = Symbol("A", commutative=False)
    B = Symbol("B", commutative=False)
    C = Symbol("C", commutative=False)
    a = Symbol("a")
    b = Symbol("b")
    i = Symbol("i", integer=True)
    n = Symbol("n", negative=True)
    m = Symbol("m", negative=True)
    p = Symbol("p", polar=True)
    np = Symbol("p", polar=False)

    assert (C * (A + B)).expand() == C * A + C * B
    assert (C * (A + B)).expand() != A * C + B * C
    assert ((A + B) ** 2).expand() == A ** 2 + A * B + B * A + B ** 2
    assert ((A + B) ** 3).expand() == (
        A ** 2 * B + B ** 2 * A + A * B ** 2 + B * A ** 2 + A ** 3 + B ** 3 + A * B * A + B * A * B
    )
    # issue 6219
    assert ((a * A * B * A ** -1) ** 2).expand() == a ** 2 * A * B ** 2 / A
    # Note that (a*A*B*A**-1)**2 is automatically converted to a**2*(A*B*A**-1)**2
    assert ((a * A * B * A ** -1) ** 2).expand(deep=False) == a ** 2 * (A * B * A ** -1) ** 2
    assert ((a * A * B * A ** -1) ** 2).expand() == a ** 2 * (A * B ** 2 * A ** -1)
    assert ((a * A * B * A ** -1) ** 2).expand(force=True) == a ** 2 * A * B ** 2 * A ** (-1)
    assert ((a * A * B) ** 2).expand() == a ** 2 * A * B * A * B
    assert ((a * A) ** 2).expand() == a ** 2 * A ** 2
    assert ((a * A * B) ** i).expand() == a ** i * (A * B) ** i
    assert ((a * A * (B * (A * B / A) ** 2)) ** i).expand() == a ** i * (A * B * A * B ** 2 / A) ** i
    # issue 6558
    assert (A * B * (A * B) ** -1).expand() == A * B * (A * B) ** -1
    assert ((a * A) ** i).expand() == a ** i * A ** i
    assert ((a * A * B * A ** -1) ** 3).expand() == a ** 3 * A * B ** 3 / A
    assert ((a * A * B * A * B / A) ** 3).expand() == a ** 3 * A * B * (A * B ** 2) * (A * B ** 2) * A * B * A ** (-1)
    assert ((a * A * B * A * B / A) ** -3).expand() == a ** -3 * (
        A * B * (A * B ** 2) * (A * B ** 2) * A * B * A ** (-1)
    ) ** -1
    assert ((a * b * A * B * A ** -1) ** i).expand() == a ** i * b ** i * (A * B / A) ** i
    assert ((a * (a * b) ** i) ** i).expand() == a ** i * a ** (i ** 2) * b ** (i ** 2)
    e = Pow(Mul(a, 1 / a, A, B, evaluate=False), S(2), evaluate=False)
    assert e.expand() == A * B * A * B
    assert sqrt(a * (A * b) ** i).expand() == sqrt(a * b ** i * A ** i)
    assert (sqrt(-a) ** a).expand() == sqrt(-a) ** a
    assert expand((-2 * n) ** (i / 3)) == 2 ** (i / 3) * (-n) ** (i / 3)
    assert expand((-2 * n * m) ** (i / a)) == (-2) ** (i / a) * (-n) ** (i / a) * (-m) ** (i / a)
    assert expand((-2 * a * p) ** b) == 2 ** b * p ** b * (-a) ** b
    assert expand((-2 * a * np) ** b) == 2 ** b * (-a * np) ** b
    assert expand(sqrt(A * B)) == sqrt(A * B)
    assert expand(sqrt(-2 * a * b)) == sqrt(2) * sqrt(-a * b)
Exemple #2
0
def _replace_op_func(e, variable):

    if isinstance(e, Operator):
        return OperatorFunction(e, variable)

    if e.is_Number:
        return e

    if isinstance(e, Pow):
        return Pow(_replace_op_func(e.base, variable), e.exp)

    new_args = [_replace_op_func(arg, variable) for arg in e.args]

    if isinstance(e, Add):
        return Add(*new_args)

    elif isinstance(e, Mul):
        return Mul(*new_args)

    else:
        return e
Exemple #3
0
def test_constant_power_as_exp():
    assert constant_renumber(constantsimp(x**C1, [C1]), 'C', 1, 1) == x**C1
    assert constant_renumber(constantsimp(y**C1, [C1, y]), 'C', 1, 1) == C1
    assert constant_renumber(constantsimp(x**y**C1, [C1, y]), 'C', 1,
                             1) == x**C1
    assert constant_renumber(constantsimp((x**y)**C1, [C1]), 'C', 1,
                             1) == (x**y)**C1
    assert constant_renumber(constantsimp(x**(y**C1), [C1, y]), 'C', 1,
                             1) == x**C1
    assert constant_renumber(constantsimp(x**C1**y, [C1, y]), 'C', 1,
                             1) == x**C1
    assert constant_renumber(constantsimp(x**(C1**y), [C1, y]), 'C', 1,
                             1) == x**C1
    assert constant_renumber(constantsimp((x**C1)**y, [C1]), 'C', 1,
                             1) == (x**C1)**y
    assert constant_renumber(constantsimp(2**C1, [C1]), 'C', 1, 1) == C1
    assert constant_renumber(constantsimp(S(2)**C1, [C1]), 'C', 1, 1) == C1
    assert constant_renumber(constantsimp(exp(C1), [C1]), 'C', 1, 1) == C1
    assert constant_renumber(constantsimp(exp(C1 + x), [C1]), 'C', 1,
                             1) == C1 * exp(x)
    assert constant_renumber(constantsimp(Pow(2, C1), [C1]), 'C', 1, 1) == C1
Exemple #4
0
def test_Mul():
    assert str(x/y) == "x/y"
    assert str(y/x) == "y/x"
    assert str(x/y/z) == "x/(y*z)"
    assert str((x + 1)/(y + 2)) == "(x + 1)/(y + 2)"
    assert str(2*x/3) == '2*x/3'
    assert str(-2*x/3) == '-2*x/3'
    assert str(-1.0*x) == '-1.0*x'
    assert str(1.0*x) == '1.0*x'
    assert str(Mul(0, 1, evaluate=False)) == '0*1'
    assert str(Mul(1, 0, evaluate=False)) == '1*0'
    assert str(Mul(1, 1, evaluate=False)) == '1*1'
    assert str(Mul(1, 1, 1, evaluate=False)) == '1*1*1'
    assert str(Mul(1, 2, evaluate=False)) == '1*2'
    assert str(Mul(1, S.Half, evaluate=False)) == '1*(1/2)'
    assert str(Mul(1, 1, S.Half, evaluate=False)) == '1*1*(1/2)'
    assert str(Mul(1, 1, 2, 3, x, evaluate=False)) == '1*1*2*3*x'
    assert str(Mul(1, -1, evaluate=False)) == '1*(-1)'
    assert str(Mul(-1, 1, evaluate=False)) == '(-1)*1'
    assert str(Mul(4, 3, 2, 1, 0, y, x, evaluate=False)) == '4*3*2*1*0*y*x'
    assert str(Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)) == '4*3*2*(z + 1)*0*y*x'
    assert str(Mul(Rational(2, 3), Rational(5, 7), evaluate=False)) == '(2/3)*(5/7)'
    # For issue 14160
    assert str(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False),
                                                evaluate=False)) == '-2*x/(y*y)'


    class CustomClass1(Expr):
        is_commutative = True

    class CustomClass2(Expr):
        is_commutative = True
    cc1 = CustomClass1()
    cc2 = CustomClass2()
    assert str(Rational(2)*cc1) == '2*CustomClass1()'
    assert str(cc1*Rational(2)) == '2*CustomClass1()'
    assert str(cc1*Float("1.5")) == '1.5*CustomClass1()'
    assert str(cc2*Rational(2)) == '2*CustomClass2()'
    assert str(cc2*Rational(2)*cc1) == '2*CustomClass1()*CustomClass2()'
    assert str(cc1*Rational(2)*cc2) == '2*CustomClass1()*CustomClass2()'
Exemple #5
0
def cg_simp(e):
    """Simplify and combine CG coefficients

    This function uses various symmetry and properties of sums and
    products of Clebsch-Gordan coefficients to simplify statements
    involving these terms [1]_.

    Examples
    ========

    Simplify the sum over CG(a,alpha,0,0,a,alpha) for all alpha to
    2*a+1

        >>> from sympy.physics.quantum.cg import CG, cg_simp
        >>> a = CG(1,1,0,0,1,1)
        >>> b = CG(1,0,0,0,1,0)
        >>> c = CG(1,-1,0,0,1,-1)
        >>> cg_simp(a+b+c)
        3

    See Also
    ========

    CG: Clebsh-Gordan coefficients

    References
    ==========

    .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
    """
    if isinstance(e, Add):
        return _cg_simp_add(e)
    elif isinstance(e, Sum):
        return _cg_simp_sum(e)
    elif isinstance(e, Mul):
        return Mul(*[cg_simp(arg) for arg in e.args])
    elif isinstance(e, Pow):
        return Pow(cg_simp(e.base), e.exp)
    else:
        return e
Exemple #6
0
def pow_to_mul(expr):
    if q_leaf(expr) or isinstance(expr, Basic):
        return expr
    elif expr.is_Pow:
        base, exp = expr.as_base_exp()
        if exp > 10 or exp < -10 or int(exp) != exp or exp == 0:
            # Large and non-integer powers remain untouched
            return expr
        elif exp == -1:
            # Reciprocals also remain untouched, but we traverse the base
            # looking for other Pows
            return expr.func(pow_to_mul(base), exp, evaluate=False)
        elif exp > 0:
            return Mul(*[base] * int(exp), evaluate=False)
        else:
            # SymPy represents 1/x as Pow(x,-1). Also, it represents
            # 2/x as Mul(2, Pow(x, -1)). So we shouldn't end up here,
            # but just in case SymPy changes its internal conventions...
            posexpr = Mul(*[base] * (-int(exp)), evaluate=False)
            return Pow(posexpr, -1, evaluate=False)
    else:
        return expr.func(*[pow_to_mul(i) for i in expr.args], evaluate=False)
Exemple #7
0
    def mapBetaFunctions(self):
        loggingInfo("Re-combining the RGES ...")

        #This is for progress bar
        nTot = 0
        count = 0
        for couplingType, RGlist in self.allRGEs.items():
            nTot += len(
                self.potential[couplingType]) * self.loopDic[couplingType]

        for couplingType, RGloops in self.allRGEs.items():
            mat = self.lagrangianMapping[couplingType]
            for n, RGlist in RGloops.items():
                couplingRGEs = mat * Matrix(RGlist)

                # Take into account the beta-exponent
                expFactor = 1
                if 'Anomalous' not in couplingType:
                    exponent = self.betaExponent(n + 1) - 2 * (n + 1)
                    if exponent != 0:
                        expFactor = Pow(4 * pi, exponent)

                for pos, coupling in enumerate(
                        list(self.potential[couplingType])):
                    try:
                        self.couplingRGEs[couplingType][n][coupling] = expand(
                            couplingRGEs[pos] * expFactor)
                    except BaseException as e:
                        loggingCritical(
                            f"Error expanding term at : {couplingType}, {n}, {pos}"
                        )
                        loggingCritical(e)
                        exit()
                    count += 1
                    print_progress(count,
                                   nTot,
                                   prefix='    ',
                                   bar_length=20,
                                   printTime=self.times)
Exemple #8
0
    def __new__(cls, base, exp):
        base = S(base)
        exp = S(exp)
        if base.is_Vector:
            raise TypeError("Vector power not available")
        if exp.is_Vector:
            raise TypeError("Vector power not available")

        if ((not isinstance(base, VectorExpr))
                and (not isinstance(exp, VectorExpr))):
            return Pow(base, exp)

        if base == S.One:
            return base
        if exp == S.One:
            return base

        obj = Basic.__new__(cls, base, exp)
        # at this point I know the base is an instance of VectorExpr with
        # is_Vector=False, hence is_scalar = True
        obj.is_Vector = False
        return obj
Exemple #9
0
def test_NaN():
    assert nan == nan
    assert nan != 1
    assert 1*nan == nan
    assert 1 != nan
    assert nan == -nan
    assert oo != Symbol("x")**3
    assert nan + 1 == nan
    assert 2 + nan == nan
    assert 3*nan + 2 == nan
    assert -nan*3 == nan
    assert nan + nan == nan
    assert -nan + nan*(-5) == nan
    assert 1/nan == nan
    assert 1/(-nan) == nan
    assert 8/nan == nan
    assert not nan > 0
    assert not nan < 0
    assert not nan >= 0
    assert not nan <= 0
    assert not 0 < nan
    assert not 0 > nan
    assert not 0 <= nan
    assert not 0 >= nan
    assert S.One + nan == nan
    assert S.One - nan == nan
    assert S.One*nan == nan
    assert S.One/nan == nan
    assert nan - S.One == nan
    assert nan*S.One == nan
    assert nan + S.One == nan
    assert nan/S.One == nan
    assert nan**0 == 1  # as per IEEE 754
    assert 1**nan == nan # IEEE 754 is not the best choice for symbolic work
    # test Pow._eval_power's handling of NaN
    assert Pow(nan, 0, evaluate=False)**2 == 1
Exemple #10
0
def quartic_0():
    a0, a1, a2, a3, a4 = symbols("a0 a1 a2 a3 a4")
    q0, q1, q2, q3, q4 = symbols("q0 q1 q2 q3 q4")

    x, z, l = symbols("x z l")

    ex_ = Pow(x, 4) + a3 * Pow(x, 3) + a2 * Pow(x, 2) + a1 * Pow(
        x, 1) + a0  # setting a4 to 1

    ex = ex_.subs(x, x - l).subs(l,
                                 a3 / 4)  # picking this l kills the x**3 term

    c = get_coeff(ex, x, 5)

    assert c[3] == 0  # x**3 term is killed

    p, q, r = symbols("p q r")

    simp = [(a2 - 3 * a3**2 / 8, p), (a1 - a2 * a3 / 2 + a3**3 / 8, q),
            (-a1 * a3 / 4 + a2 * a3**2 / 16 - 3 * a3**4 / 256, r)]

    cs = get_coeff_(ex, x, 5)
    print_coeff(cs, "cs")
Exemple #11
0
def exp2(x):
    """exp2(x)

    Calculate `2**x`.
    """
    return Pow(2, x)
Exemple #12
0
    def _sympy_matrix(self, name, m):
        self._store_matrix(name, 'sympy', to_sympy(m))

    def _numpy_matrix(self, name, m):
        m = to_numpy(m, dtype=self.dtype)
        self._store_matrix(name, 'numpy', m)

    def _scipy_sparse_matrix(self, name, m):
        # TODO: explore different sparse formats. But sparse.kron will use
        # coo in most cases, so we use that here.
        m = to_scipy_sparse(m, dtype=self.dtype)
        self._store_matrix(name, 'scipy.sparse', m)


sqrt2_inv = Pow(2, Rational(-1, 2), evaluate=False)

# Save the common matrices that we will need
matrix_cache = MatrixCache()
matrix_cache.cache_matrix('eye2', Matrix([[1, 0], [0, 1]]))
matrix_cache.cache_matrix('op11', Matrix([[0, 0], [0, 1]]))  # |1><1|
matrix_cache.cache_matrix('op00', Matrix([[1, 0], [0, 0]]))  # |0><0|
matrix_cache.cache_matrix('op10', Matrix([[0, 0], [1, 0]]))  # |1><0|
matrix_cache.cache_matrix('op01', Matrix([[0, 1], [0, 0]]))  # |0><1|
matrix_cache.cache_matrix('X', Matrix([[0, 1], [1, 0]]))
matrix_cache.cache_matrix('Y', Matrix([[0, -I], [I, 0]]))
matrix_cache.cache_matrix('Z', Matrix([[1, 0], [0, -1]]))
matrix_cache.cache_matrix('S', Matrix([[1, 0], [0, I]]))
matrix_cache.cache_matrix('T', Matrix([[1, 0], [0, exp(I*pi/4)]]))
matrix_cache.cache_matrix('H', sqrt2_inv*Matrix([[1, 1], [1, -1]]))
matrix_cache.cache_matrix('Hsqrt2', Matrix([[1, 1], [1, -1]]))
Exemple #13
0
class TestAllGood(object):
    # These latex strings should parse to the corresponding SymPy expression
    GOOD_PAIRS = [
        ("0", Rational(0)),
        ("1", Rational(1)),
        ("-3.14", Rational(-314, 100)),
        ("5-3", _Add(5, _Mul(-1, 3))),
        ("(-7.13)(1.5)", _Mul(Rational('-7.13'), Rational('1.5'))),
        ("\\left(-7.13\\right)\\left(1.5\\right)", _Mul(Rational('-7.13'), Rational('1.5'))),
        ("x", x),
        ("2x", 2 * x),
        ("x^2", x**2),
        ("x^{3 + 1}", x**_Add(3, 1)),
        ("x^{\\left\\{3 + 1\\right\\}}", x**_Add(3, 1)),
        ("-3y + 2x", _Add(_Mul(2, x), Mul(-1, 3, y, evaluate=False))),
        ("-c", -c),
        ("a \\cdot b", a * b),
        ("a / b", a / b),
        ("a \\div b", a / b),
        ("a + b", a + b),
        ("a + b - a", Add(a, b, _Mul(-1, a), evaluate=False)),
        ("a^2 + b^2 = c^2", Eq(a**2 + b**2, c**2)),
        ("a^2 + b^2 != 2c^2", Ne(a**2 + b**2, 2 * c**2)),
        ("a\\mod b", Mod(a, b)),
        ("\\sin \\theta", sin(theta)),
        ("\\sin(\\theta)", sin(theta)),
        ("\\sin\\left(\\theta\\right)", sin(theta)),
        ("\\sin^{-1} a", asin(a)),
        ("\\sin a \\cos b", _Mul(sin(a), cos(b))),
        ("\\sin \\cos \\theta", sin(cos(theta))),
        ("\\sin(\\cos \\theta)", sin(cos(theta))),
        ("\\arcsin(a)", asin(a)),
        ("\\arccos(a)", acos(a)),
        ("\\arctan(a)", atan(a)),
        ("\\sinh(a)", sinh(a)),
        ("\\cosh(a)", cosh(a)),
        ("\\tanh(a)", tanh(a)),
        ("\\sinh^{-1}(a)", asinh(a)),
        ("\\cosh^{-1}(a)", acosh(a)),
        ("\\tanh^{-1}(a)", atanh(a)),
        ("\\arcsinh(a)", asinh(a)),
        ("\\arccosh(a)", acosh(a)),
        ("\\arctanh(a)", atanh(a)),
        ("\\arsinh(a)", asinh(a)),
        ("\\arcosh(a)", acosh(a)),
        ("\\artanh(a)", atanh(a)),
        ("\\operatorname{arcsinh}(a)", asinh(a)),
        ("\\operatorname{arccosh}(a)", acosh(a)),
        ("\\operatorname{arctanh}(a)", atanh(a)),
        ("\\operatorname{arsinh}(a)", asinh(a)),
        ("\\operatorname{arcosh}(a)", acosh(a)),
        ("\\operatorname{artanh}(a)", atanh(a)),
        ("\\operatorname{gcd}(a, b)", UnevaluatedExpr(gcd(a, b))),
        ("\\operatorname{lcm}(a, b)", UnevaluatedExpr(lcm(a, b))),
        ("\\operatorname{gcd}(a,b)", UnevaluatedExpr(gcd(a, b))),
        ("\\operatorname{lcm}(a,b)", UnevaluatedExpr(lcm(a, b))),
        ("\\operatorname{floor}(a)", floor(a)),
        ("\\operatorname{ceil}(b)", ceiling(b)),
        ("\\cos^2(x)", cos(x)**2),
        ("\\cos(x)^2", cos(x)**2),
        ("\\gcd(a, b)", UnevaluatedExpr(gcd(a, b))),
        ("\\lcm(a, b)", UnevaluatedExpr(lcm(a, b))),
        ("\\gcd(a,b)", UnevaluatedExpr(gcd(a, b))),
        ("\\lcm(a,b)", UnevaluatedExpr(lcm(a, b))),
        ("\\floor(a)", floor(a)),
        ("\\ceil(b)", ceiling(b)),
        ("\\max(a, b)", Max(a, b)),
        ("\\min(a, b)", Min(a, b)),
        ("\\frac{a}{b}", a / b),
        ("\\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))),
        ("\\frac{7}{3}", Rational(7, 3)),
        ("(\\csc x)(\\sec y)", csc(x) * sec(y)),
        ("\\lim_{x \\to 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\rightarrow 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\Rightarrow 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\longrightarrow 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\Longrightarrow 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\to 3^{+}} a", Limit(a, x, 3, dir='+')),
        ("\\lim_{x \\to 3^{-}} a", Limit(a, x, 3, dir='-')),
        ("\\infty", oo),
        ("\\infty\\%", oo),
        ("\\$\\infty", oo),
        ("-\\infty", -oo),
        ("-\\infty\\%", -oo),
        ("-\\$\\infty", -oo),
        ("\\lim_{x \\to \\infty} \\frac{1}{x}", Limit(_Mul(1, _Pow(x, -1)), x, oo)),
        ("\\frac{d}{dx} x", Derivative(x, x)),
        ("\\frac{d}{dt} x", Derivative(x, t)),
        # ("f(x)", f(x)),
        # ("f(x, y)", f(x, y)),
        # ("f(x, y, z)", f(x, y, z)),
        # ("\\frac{d f(x)}{dx}", Derivative(f(x), x)),
        # ("\\frac{d\\theta(x)}{dx}", Derivative(theta(x), x)),
        ("|x|", _Abs(x)),
        ("\\left|x\\right|", _Abs(x)),
        ("||x||", _Abs(_Abs(x))),
        ("|x||y|", _Abs(x) * _Abs(y)),
        ("||x||y||", _Abs(_Abs(x) * _Abs(y))),
        ("\\lfloor x\\rfloor", floor(x)),
        ("\\lceil y\\rceil", ceiling(y)),
        ("\\pi^{|xy|}", pi**_Abs(x * y)),
        ("\\frac{\\pi}{3}", _Mul(pi, _Pow(3, -1))),
        ("\\sin{\\frac{\\pi}{2}}", sin(_Mul(pi, _Pow(2, -1)), evaluate=False)),
        ("a+bI", a + I * b),
        ("e^{I\\pi}", Integer(-1)),
        ("\\int x dx", Integral(x, x)),
        ("\\int x d\\theta", Integral(x, theta)),
        ("\\int (x^2 - y)dx", Integral(x**2 - y, x)),
        ("\\int x + a dx", Integral(_Add(x, a), x)),
        ("\\int da", Integral(1, a)),
        ("\\int_0^7 dx", Integral(1, (x, 0, 7))),
        ("\\int_a^b x dx", Integral(x, (x, a, b))),
        ("\\int^b_a x dx", Integral(x, (x, a, b))),
        ("\\int_{a}^b x dx", Integral(x, (x, a, b))),
        ("\\int^{b}_a x dx", Integral(x, (x, a, b))),
        ("\\int_{a}^{b} x dx", Integral(x, (x, a, b))),
        ("\\int_{  }^{}x dx", Integral(x, x)),
        ("\\int^{  }_{ }x dx", Integral(x, x)),
        ("\\int^{b}_{a} x dx", Integral(x, (x, a, b))),
        # ("\\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))),
        ("\\int (x+a)", Integral(_Add(x, a), x)),
        ("\\int a + b + c dx", Integral(Add(a, b, c, evaluate=False), x)),
        ("\\int \\frac{dz}{z}", Integral(Pow(z, -1), z)),
        ("\\int \\frac{3 dz}{z}", Integral(3 * Pow(z, -1), z)),
        ("\\int \\frac{1}{x} dx", Integral(Pow(x, -1), x)),
        ("\\int \\frac{1}{a} + \\frac{1}{b} dx", Integral(_Add(_Pow(a, -1), Pow(b, -1)), x)),
        ("\\int \\frac{3 \\cdot d\\theta}{\\theta}", Integral(3 * _Pow(theta, -1), theta)),
        ("\\int \\frac{1}{x} + 1 dx", Integral(_Add(_Pow(x, -1), 1), x)),
        ("x_0", Symbol('x_0', real=True, positive=True)),
        ("x_{1}", Symbol('x_1', real=True, positive=True)),
        ("x_a", Symbol('x_a', real=True, positive=True)),
        ("x_{b}", Symbol('x_b', real=True, positive=True)),
        ("h_\\theta", Symbol('h_{\\theta}', real=True, positive=True)),
        ("h_\\theta ", Symbol('h_{\\theta}', real=True, positive=True)),
        ("h_{\\theta}", Symbol('h_{\\theta}', real=True, positive=True)),
        # ("h_{\\theta}(x_0, x_1)", Symbol('h_{theta}', real=True)(Symbol('x_{0}', real=True), Symbol('x_{1}', real=True))),
        ("x!", _factorial(x)),
        ("100!", _factorial(100)),
        ("\\theta!", _factorial(theta)),
        ("(x + 1)!", _factorial(_Add(x, 1))),
        ("\\left(x + 1\\right)!", _factorial(_Add(x, 1))),
        ("(x!)!", _factorial(_factorial(x))),
        ("x!!!", _factorial(_factorial(_factorial(x)))),
        ("5!7!", _Mul(_factorial(5), _factorial(7))),
        ("\\sqrt{x}", sqrt(x)),
        ("\\sqrt{x + b}", sqrt(_Add(x, b))),
        ("\\sqrt[3]{\\sin x}", root(sin(x), 3)),
        ("\\sqrt[y]{\\sin x}", root(sin(x), y)),
        ("\\sqrt[\\theta]{\\sin x}", root(sin(x), theta)),
        ("x < y", StrictLessThan(x, y)),
        ("x \\leq y", LessThan(x, y)),
        ("x > y", StrictGreaterThan(x, y)),
        ("x \\geq y", GreaterThan(x, y)),
        ("\\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))),
        ("\\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))),
        ("\\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))),
        ("\\sum^3_{k = 1} c", Sum(c, (k, 1, 3))),
        ("\\sum_{k = 1}^{10} k^2", Sum(k**2, (k, 1, 10))),
        ("\\sum_{n = 0}^{\\infty} \\frac{1}{n!}", Sum(_Pow(_factorial(n), -1), (n, 0, oo))),
        ("\\prod_{a = b}^{c} x", Product(x, (a, b, c))),
        ("\\prod_{a = b}^c x", Product(x, (a, b, c))),
        ("\\prod^{c}_{a = b} x", Product(x, (a, b, c))),
        ("\\prod^c_{a = b} x", Product(x, (a, b, c))),
        ("\\ln x", _log(x, E)),
        ("\\ln xy", _log(x * y, E)),
        ("\\log x", _log(x, 10)),
        ("\\log xy", _log(x * y, 10)),
        # ("\\log_2 x", _log(x, 2)),
        ("\\log_{2} x", _log(x, 2)),
        # ("\\log_a x", _log(x, a)),
        ("\\log_{a} x", _log(x, a)),
        ("\\log_{11} x", _log(x, 11)),
        ("\\log_{a^2} x", _log(x, _Pow(a, 2))),
        ("[x]", x),
        ("[a + b]", _Add(a, b)),
        ("\\frac{d}{dx} [ \\tan x ]", Derivative(tan(x), x)),
        ("2\\overline{x}", 2 * Symbol('xbar', real=True, positive=True)),
        ("2\\overline{x}_n", 2 * Symbol('xbar_n', real=True, positive=True)),
        ("\\frac{x}{\\overline{x}_n}", x / Symbol('xbar_n', real=True, positive=True)),
        ("\\frac{\\sin(x)}{\\overline{x}_n}", sin(x) / Symbol('xbar_n', real=True, positive=True)),
        ("2\\bar{x}", 2 * Symbol('xbar', real=True, positive=True)),
        ("2\\bar{x}_n", 2 * Symbol('xbar_n', real=True, positive=True)),
        ("\\sin\\left(\\theta\\right) \\cdot4", sin(theta) * 4),
        ("\\ln\\left(\\theta\\right)", _log(theta, E)),
        ("\\ln\\left(x-\\theta\\right)", _log(x - theta, E)),
        ("\\ln\\left(\\left(x-\\theta\\right)\\right)", _log(x - theta, E)),
        ("\\ln\\left(\\left[x-\\theta\\right]\\right)", _log(x - theta, E)),
        ("\\ln\\left(\\left\\{x-\\theta\\right\\}\\right)", _log(x - theta, E)),
        ("\\ln\\left(\\left|x-\\theta\\right|\\right)", _log(_Abs(x - theta), E)),
        ("\\frac{1}{2}xy(x+y)", Mul(Rational(1, 2), x, y, (x + y), evaluate=False)),
        ("\\frac{1}{2}\\theta(x+y)", Mul(Rational(1, 2), theta, (x + y), evaluate=False)),
        ("1-f(x)", 1 - f * x),

        ("\\begin{matrix}1&2\\\\3&4\\end{matrix}", Matrix([[1, 2], [3, 4]])),
        ("\\begin{matrix}x&x^2\\\\\\sqrt{x}&x\\end{matrix}", Matrix([[x, x**2], [_Pow(x, S.Half), x]])),
        ("\\begin{matrix}\\sqrt{x}\\\\\\sin(\\theta)\\end{matrix}", Matrix([_Pow(x, S.Half), sin(theta)])),
        ("\\begin{pmatrix}1&2\\\\3&4\\end{pmatrix}", Matrix([[1, 2], [3, 4]])),
        ("\\begin{bmatrix}1&2\\\\3&4\\end{bmatrix}", Matrix([[1, 2], [3, 4]])),

        # scientific notation
        ("2.5\\times 10^2", Rational(250)),
        ("1,500\\times 10^{-1}", Rational(150)),

        # e notation
        ("2.5E2", Rational(250)),
        ("1,500E-1", Rational(150)),

        # multiplication without cmd
        ("2x2y", Mul(2, x, 2, y, evaluate=False)),
        ("2x2", Mul(2, x, 2, evaluate=False)),
        ("x2", x * 2),

        # lin alg processing
        ("\\theta\\begin{matrix}1&2\\\\3&4\\end{matrix}", MatMul(theta, Matrix([[1, 2], [3, 4]]), evaluate=False)),
        ("\\theta\\begin{matrix}1\\\\3\\end{matrix} - \\begin{matrix}-1\\\\2\\end{matrix}", MatAdd(MatMul(theta, Matrix([[1], [3]]), evaluate=False), MatMul(-1, Matrix([[-1], [2]]), evaluate=False), evaluate=False)),
        ("\\theta\\begin{matrix}1&0\\\\0&1\\end{matrix}*\\begin{matrix}3\\\\-2\\end{matrix}", MatMul(theta, Matrix([[1, 0], [0, 1]]), Matrix([3, -2]), evaluate=False)),
        ("\\frac{1}{9}\\theta\\begin{matrix}1&2\\\\3&4\\end{matrix}", MatMul(Rational(1, 9), theta, Matrix([[1, 2], [3, 4]]), evaluate=False)),
        ("\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix},\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix}", [Matrix([1, 2, 3]), Matrix([4, 3, 1])]),
        ("\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix};\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix}", [Matrix([1, 2, 3]), Matrix([4, 3, 1])]),
        ("\\left\\{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix},\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix}\\right\\}", [Matrix([1, 2, 3]), Matrix([4, 3, 1])]),
        ("\\left\\{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix},\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix},\\begin{pmatrix}1\\\\1\\\\1\\end{pmatrix}\\right\\}", [Matrix([1, 2, 3]), Matrix([4, 3, 1]), Matrix([1, 1, 1])]),
        ("\\left\\{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix}\\right\\}", Matrix([1, 2, 3])),
        ("\\left{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix}\\right}", Matrix([1, 2, 3])),
        ("{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix}}", Matrix([1, 2, 3])),

        # us dollars
        ("\\$1,000.00", Rational(1000)),
        ("\\$543.21", Rational(54321, 100)),
        ("\\$0.009", Rational(9, 1000)),

        # percentages
        ("100\\%", Rational(1)),
        ("1.5\\%", Rational(15, 1000)),
        ("0.05\\%", Rational(5, 10000)),

        # empty set
        ("\\emptyset", S.EmptySet),

        # divide by zero
        ("\\frac{1}{0}", _Pow(0, -1)),
        ("1+\\frac{5}{0}", _Add(1, _Mul(5, _Pow(0, -1)))),

        # adjacent single char sub sup
        ("4^26^2", _Mul(_Pow(4, 2), _Pow(6, 2))),
        ("x_22^2", _Mul(Symbol('x_2', real=True, positive=True), _Pow(2, 2)))
    ]

    def test_good_pair(self, s, eq):
        assert_equal(s, eq)
Exemple #14
0
def test_nested_substitution():
    # Substitution within a substitution.
    e = Add(Pow(w*x+y,2), sqrt(w*x+y))
    substs, reduced = cse([e], optimizations=[])
    assert substs == [(x0, w*x), (x1, x0+y)]
    assert reduced == [sqrt(x1) + x1**2]
Exemple #15
0
def test_powers_Integer():
    """Test Integer._eval_power"""
    # check infinity
    assert S(1) ** S.Infinity == S.NaN
    assert S(-1)** S.Infinity == S.NaN
    assert S(2) ** S.Infinity == S.Infinity
    assert S(-2)** S.Infinity == S.Infinity + S.Infinity * S.ImaginaryUnit
    assert S(0) ** S.Infinity == 0

    # check Nan
    assert S(1) ** S.NaN == S.NaN
    assert S(-1) ** S.NaN == S.NaN

    # check for exact roots
    assert S(-1) ** Rational(6, 5) == - (-1)**(S(1)/5)
    assert sqrt(S(4)) == 2
    assert sqrt(S(-4)) == I * 2
    assert S(16) ** Rational(1, 4) == 2
    assert S(-16) ** Rational(1, 4) == 2 * (-1)**Rational(1, 4)
    assert S(9) ** Rational(3, 2) == 27
    assert S(-9) ** Rational(3, 2) == -27*I
    assert S(27) ** Rational(2, 3) == 9
    assert S(-27) ** Rational(2, 3) == 9 * (S(-1) ** Rational(2, 3))
    assert (-2) ** Rational(-2, 1) == Rational(1, 4)

    # not exact roots
    assert sqrt(-3) == I*sqrt(3)
    assert (3) ** (S(3)/2) == 3 * sqrt(3)
    assert (-3) ** (S(3)/2) == - 3 * sqrt(-3)
    assert (-3) ** (S(5)/2) == 9 * I * sqrt(3)
    assert (-3) ** (S(7)/2) == - I * 27 * sqrt(3)
    assert (2) ** (S(3)/2) == 2 * sqrt(2)
    assert (2) ** (S(-3)/2) == sqrt(2) / 4
    assert (81) ** (S(2)/3) == 9 * (S(3) ** (S(2)/3))
    assert (-81) ** (S(2)/3) == 9 * (S(-3) ** (S(2)/3))
    assert (-3) ** Rational(-7, 3) == \
        -(-1)**Rational(2, 3)*3**Rational(2, 3)/27
    assert (-3) ** Rational(-2, 3) == \
        -(-1)**Rational(1, 3)*3**Rational(1, 3)/3

    # join roots
    assert sqrt(6) + sqrt(24) == 3*sqrt(6)
    assert sqrt(2) * sqrt(3) == sqrt(6)

    # separate symbols & constansts
    x = Symbol("x")
    assert sqrt(49 * x) == 7 * sqrt(x)
    assert sqrt((3 - sqrt(pi)) ** 2) == 3 - sqrt(pi)

    # check that it is fast for big numbers
    assert (2**64 + 1) ** Rational(4, 3)
    assert (2**64 + 1) ** Rational(17, 25)

    # negative rational power and negative base
    assert (-3) ** Rational(-7, 3) == \
        -(-1)**Rational(2, 3)*3**Rational(2, 3)/27
    assert (-3) ** Rational(-2, 3) == \
        -(-1)**Rational(1, 3)*3**Rational(1, 3)/3

    assert S(1234).factors() == {617: 1, 2: 1}
    assert Rational(2*3, 3*5*7).factors() == {2: 1, 5: -1, 7: -1}

    # test that eval_power factors numbers bigger than
    # the current limit in factor_trial_division (2**15)
    from sympy import nextprime
    n = nextprime(2**15)
    assert sqrt(n**2) == n
    assert sqrt(n**3) == n*sqrt(n)
    assert sqrt(4*n) == 2*sqrt(n)

    # check that factors of base with powers sharing gcd with power are removed
    assert (2**4*3)**Rational(1, 6) == 2**Rational(2, 3)*3**Rational(1, 6)
    assert (2**4*3)**Rational(5, 6) == 8*2**Rational(1, 3)*3**Rational(5, 6)

    # check that bases sharing a gcd are exptracted
    assert 2**Rational(1, 3)*3**Rational(1, 4)*6**Rational(1, 5) == \
        2**Rational(8, 15)*3**Rational(9, 20)
    assert sqrt(8)*24**Rational(1, 3)*6**Rational(1, 5) == \
        4*2**Rational(7, 10)*3**Rational(8, 15)
    assert sqrt(8)*(-24)**Rational(1, 3)*(-6)**Rational(1, 5) == \
        4*(-3)**Rational(8, 15)*2**Rational(7, 10)
    assert 2**Rational(1, 3)*2**Rational(8, 9) == 2*2**Rational(2, 9)
    assert 2**Rational(2, 3)*6**Rational(1, 3) == 2*3**Rational(1, 3)
    assert 2**Rational(2, 3)*6**Rational(8, 9) == \
        2*2**Rational(5, 9)*3**Rational(8, 9)
    assert (-2)**Rational(2, S(3))*(-4)**Rational(1, S(3)) == -2*2**Rational(1, 3)
    assert 3*Pow(3, 2, evaluate=False) == 3**3
    assert 3*Pow(3, -1/S(3), evaluate=False) == 3**(2/S(3))
    assert (-2)**(1/S(3))*(-3)**(1/S(4))*(-5)**(5/S(6)) == \
        -(-1)**Rational(5, 12)*2**Rational(1, 3)*3**Rational(1, 4) * \
        5**Rational(5, 6)

    assert Integer(-2)**Symbol('', even=True) == \
        Integer(2)**Symbol('', even=True)
    assert (-1)**Float(.5) == 1.0*I
Exemple #16
0
def test_chop_value():
    for i in range(-27, 28):
        assert (Pow(10, i)*2).n(chop=10**i) and not (Pow(10, i)).n(chop=10**i)
Exemple #17
0
def test_nested_substitution():
    # Substitution within a substitution.
    e = Add(Pow(w*x + y, 2), sqrt(w*x + y))
    substs, reduced = cse([e])
    assert substs == [(x0, w*x + y)]
    assert reduced == [sqrt(x0) + x0**2]
Exemple #18
0
def GeneralizedMultivariateLogGammaOmega(syms, omega, v, lamda, mu):
    """
    Extends GeneralizedMultivariateLogGamma.

    Parameters
    ==========

    syms: list/tuple/set of symbols for identifying each component
    omega: A square matrix
           Every element of square matrix must be absolute value of
           square root of correlation coefficient
    v: positive real
    lamda: a list of positive reals
    mu: a list of positive reals

    Returns
    =======

    A Random Symbol

    Examples
    ========

    >>> from sympy.stats import density
    >>> from sympy.stats.joint_rv import marginal_distribution
    >>> from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaOmega
    >>> from sympy import Matrix, symbols, S
    >>> omega = Matrix([[1, S.Half, S.Half], [S.Half, 1, S.Half], [S.Half, S.Half, 1]])
    >>> v = 1
    >>> l, mu = [1, 1, 1], [1, 1, 1]
    >>> G = GeneralizedMultivariateLogGammaOmega('G', omega, v, l, mu)
    >>> y = symbols('y_1:4', positive=True)
    >>> density(G)(y[0], y[1], y[2])
    sqrt(2)*Sum((1 - sqrt(2)/2)**n*exp((n + 1)*(y_1 + y_2 + y_3) - exp(y_1) -
    exp(y_2) - exp(y_3))/gamma(n + 1)**3, (n, 0, oo))/2

    References
    ==========

    See references of GeneralizedMultivariateLogGamma.

    Notes
    =====

    If the GeneralizedMultivariateLogGammaOmega is too long to type use,
    `from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaOmega as GMVLGO`
    """
    _value_check((omega.is_square, isinstance(omega, Matrix)), "omega must be a"
                                                            " square matrix")
    for val in omega.values():
        _value_check((val >= 0, val <= 1),
            "all values in matrix must be between 0 and 1(both inclusive).")
    _value_check(omega.diagonal().equals(ones(1, omega.shape[0])),
                    "all the elements of diagonal should be 1.")
    _value_check((omega.shape[0] == len(lamda), len(lamda) == len(mu)),
                    "lamda, mu should be of same length and omega should "
                    " be of shape (length of lamda, length of mu)")
    _value_check(len(lamda) > 1,"the distribution should have at least"
                            " two random variables.")
    delta = Pow(Rational(omega.det()), Rational(1, len(lamda) - 1))
    return GeneralizedMultivariateLogGamma(syms, delta, v, lamda, mu)
Exemple #19
0
def test_TransferFunction_functions():
    # classmethod from_rational_expression
    expr_1 = Mul(0, Pow(s, -1, evaluate=False), evaluate=False)
    expr_2 = s / 0
    expr_3 = (p * s**2 + 5 * s) / (s + 1)**3
    expr_4 = 6
    expr_5 = ((2 + 3 * s) * (5 + 2 * s)) / ((9 + 3 * s) * (5 + 2 * s**2))
    expr_6 = (9 * s**4 + 4 * s**2 + 8) / ((s + 1) * (s + 9))
    tf = TransferFunction(s + 1, s**2 + 2, s)
    delay = exp(-s / tau)
    expr_7 = delay * tf.to_expr()
    H1 = TransferFunction.from_rational_expression(expr_7, s)
    H2 = TransferFunction(s + 1, (s**2 + 2) * exp(s / tau), s)
    expr_8 = Add(2, 3 * s / (s**2 + 1), evaluate=False)

    assert TransferFunction.from_rational_expression(
        expr_1) == TransferFunction(0, s, s)
    raises(ZeroDivisionError,
           lambda: TransferFunction.from_rational_expression(expr_2))
    raises(ValueError,
           lambda: TransferFunction.from_rational_expression(expr_3))
    assert TransferFunction.from_rational_expression(expr_3,
                                                     s) == TransferFunction(
                                                         (p * s**2 + 5 * s),
                                                         (s + 1)**3, s)
    assert TransferFunction.from_rational_expression(expr_3,
                                                     p) == TransferFunction(
                                                         (p * s**2 + 5 * s),
                                                         (s + 1)**3, p)
    raises(ValueError,
           lambda: TransferFunction.from_rational_expression(expr_4))
    assert TransferFunction.from_rational_expression(expr_4,
                                                     s) == TransferFunction(
                                                         6, 1, s)
    assert TransferFunction.from_rational_expression(expr_5, s) == \
        TransferFunction((2 + 3*s)*(5 + 2*s), (9 + 3*s)*(5 + 2*s**2), s)
    assert TransferFunction.from_rational_expression(expr_6, s) == \
        TransferFunction((9*s**4 + 4*s**2 + 8), (s + 1)*(s + 9), s)
    assert H1 == H2
    assert TransferFunction.from_rational_expression(expr_8, s) == \
        TransferFunction(2*s**2 + 3*s + 2, s**2 + 1, s)

    # explicitly cancel poles and zeros.
    tf0 = TransferFunction(s**5 + s**3 + s, s - s**2, s)
    a = TransferFunction(-(s**4 + s**2 + 1), s - 1, s)
    assert tf0.simplify() == simplify(tf0) == a

    tf1 = TransferFunction((p + 3) * (p - 1), (p - 1) * (p + 5), p)
    b = TransferFunction(p + 3, p + 5, p)
    assert tf1.simplify() == simplify(tf1) == b

    # expand the numerator and the denominator.
    G1 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
    G2 = TransferFunction(1, -3, p)
    c = (a2 * s**p + a1 * s**s + a0 * p**p) * (p**s + s**p)
    d = (b0 * s**s + b1 * p**s) * (b2 * s * p + p**p)
    e = a0 * p**p * p**s + a0 * p**p * s**p + a1 * p**s * s**s + a1 * s**p * s**s + a2 * p**s * s**p + a2 * s**(
        2 * p)
    f = b0 * b2 * p * s * s**s + b0 * p**p * s**s + b1 * b2 * p * p**s * s + b1 * p**p * p**s
    g = a1 * a2 * s * s**p + a1 * p * s + a2 * b1 * p * s * s**p + b1 * p**2 * s
    G3 = TransferFunction(c, d, s)
    G4 = TransferFunction(a0 * s**s - b0 * p**p,
                          (a1 * s + b1 * s * p) * (a2 * s**p + p), p)

    assert G1.expand() == TransferFunction(s**2 - 2 * s + 1,
                                           s**4 + 2 * s**2 + 1, s)
    assert tf1.expand() == TransferFunction(p**2 + 2 * p - 3, p**2 + 4 * p - 5,
                                            p)
    assert G2.expand() == G2
    assert G3.expand() == TransferFunction(e, f, s)
    assert G4.expand() == TransferFunction(a0 * s**s - b0 * p**p, g, p)

    # purely symbolic polynomials.
    p1 = a1 * s + a0
    p2 = b2 * s**2 + b1 * s + b0
    SP1 = TransferFunction(p1, p2, s)
    expect1 = TransferFunction(2.0 * s + 1.0, 5.0 * s**2 + 4.0 * s + 3.0, s)
    expect1_ = TransferFunction(2 * s + 1, 5 * s**2 + 4 * s + 3, s)
    assert SP1.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}) == expect1_
    assert SP1.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}).evalf() == expect1
    assert expect1_.evalf() == expect1

    c1, d0, d1, d2 = symbols('c1, d0:3')
    p3, p4 = c1 * p, d2 * p**3 + d1 * p**2 - d0
    SP2 = TransferFunction(p3, p4, p)
    expect2 = TransferFunction(2.0 * p, 5.0 * p**3 + 2.0 * p**2 - 3.0, p)
    expect2_ = TransferFunction(2 * p, 5 * p**3 + 2 * p**2 - 3, p)
    assert SP2.subs({c1: 2, d0: 3, d1: 2, d2: 5}) == expect2_
    assert SP2.subs({c1: 2, d0: 3, d1: 2, d2: 5}).evalf() == expect2
    assert expect2_.evalf() == expect2

    SP3 = TransferFunction(a0 * p**3 + a1 * s**2 - b0 * s + b1, a1 * s + p, s)
    expect3 = TransferFunction(2.0 * p**3 + 4.0 * s**2 - s + 5.0, p + 4.0 * s,
                               s)
    expect3_ = TransferFunction(2 * p**3 + 4 * s**2 - s + 5, p + 4 * s, s)
    assert SP3.subs({a0: 2, a1: 4, b0: 1, b1: 5}) == expect3_
    assert SP3.subs({a0: 2, a1: 4, b0: 1, b1: 5}).evalf() == expect3
    assert expect3_.evalf() == expect3

    SP4 = TransferFunction(s - a1 * p**3, a0 * s + p, p)
    expect4 = TransferFunction(7.0 * p**3 + s, p - s, p)
    expect4_ = TransferFunction(7 * p**3 + s, p - s, p)
    assert SP4.subs({a0: -1, a1: -7}) == expect4_
    assert SP4.subs({a0: -1, a1: -7}).evalf() == expect4
    assert expect4_.evalf() == expect4

    # Low-frequency (or DC) gain.
    assert tf0.dc_gain() == 1
    assert tf1.dc_gain() == Rational(3, 5)
    assert SP2.dc_gain() == 0
    assert expect4.dc_gain() == -1
    assert expect2_.dc_gain() == 0
    assert TransferFunction(1, s, s).dc_gain() == oo

    # Poles of a transfer function.
    tf_ = TransferFunction(x**3 - k, k, x)
    _tf = TransferFunction(k, x**4 - k, x)
    TF_ = TransferFunction(x**2, x**10 + x + x**2, x)
    _TF = TransferFunction(x**10 + x + x**2, x**2, x)
    assert G1.poles() == [I, I, -I, -I]
    assert G2.poles() == []
    assert tf1.poles() == [-5, 1]
    assert expect4_.poles() == [s]
    assert SP4.poles() == [-a0 * s]
    assert expect3.poles() == [-0.25 * p]
    assert str(expect2.poles()) == str([
        0.729001428685125, -0.564500714342563 - 0.710198984796332 * I,
        -0.564500714342563 + 0.710198984796332 * I
    ])
    assert str(expect1.poles()) == str(
        [-0.4 - 0.66332495807108 * I, -0.4 + 0.66332495807108 * I])
    assert _tf.poles() == [
        k**(Rational(1, 4)), -k**(Rational(1, 4)), I * k**(Rational(1, 4)),
        -I * k**(Rational(1, 4))
    ]
    assert TF_.poles() == [
        CRootOf(x**9 + x + 1, 0), 0,
        CRootOf(x**9 + x + 1, 1),
        CRootOf(x**9 + x + 1, 2),
        CRootOf(x**9 + x + 1, 3),
        CRootOf(x**9 + x + 1, 4),
        CRootOf(x**9 + x + 1, 5),
        CRootOf(x**9 + x + 1, 6),
        CRootOf(x**9 + x + 1, 7),
        CRootOf(x**9 + x + 1, 8)
    ]
    raises(NotImplementedError,
           lambda: TransferFunction(x**2, a0 * x**10 + x + x**2, x).poles())

    # Stability of a transfer function.
    q, r = symbols('q, r', negative=True)
    t = symbols('t', positive=True)
    TF_ = TransferFunction(s**2 + a0 - a1 * p, q * s - r, s)
    stable_tf = TransferFunction(s**2 + a0 - a1 * p, q * s - 1, s)
    stable_tf_ = TransferFunction(s**2 + a0 - a1 * p, q * s - t, s)

    assert G1.is_stable() is False
    assert G2.is_stable() is True
    assert tf1.is_stable(
    ) is False  # as one pole is +ve, and the other is -ve.
    assert expect2.is_stable() is False
    assert expect1.is_stable() is True
    assert stable_tf.is_stable() is True
    assert stable_tf_.is_stable() is True
    assert TF_.is_stable() is False
    assert expect4_.is_stable(
    ) is None  # no assumption provided for the only pole 's'.
    assert SP4.is_stable() is None

    # Zeros of a transfer function.
    assert G1.zeros() == [1, 1]
    assert G2.zeros() == []
    assert tf1.zeros() == [-3, 1]
    assert expect4_.zeros() == [
        7**(Rational(2, 3)) * (-s)**(Rational(1, 3)) / 7,
        -7**(Rational(2, 3)) * (-s)**(Rational(1, 3)) / 14 -
        sqrt(3) * 7**(Rational(2, 3)) * I * (-s)**(Rational(1, 3)) / 14,
        -7**(Rational(2, 3)) * (-s)**(Rational(1, 3)) / 14 +
        sqrt(3) * 7**(Rational(2, 3)) * I * (-s)**(Rational(1, 3)) / 14
    ]
    assert SP4.zeros() == [(s / a1)**(Rational(1, 3)),
                           -(s / a1)**(Rational(1, 3)) / 2 - sqrt(3) * I *
                           (s / a1)**(Rational(1, 3)) / 2,
                           -(s / a1)**(Rational(1, 3)) / 2 + sqrt(3) * I *
                           (s / a1)**(Rational(1, 3)) / 2]
    assert str(expect3.zeros()) == str([
        0.125 - 1.11102430216445 * sqrt(-0.405063291139241 * p**3 - 1.0),
        1.11102430216445 * sqrt(-0.405063291139241 * p**3 - 1.0) + 0.125
    ])
    assert tf_.zeros() == [
        k**(Rational(1, 3)),
        -k**(Rational(1, 3)) / 2 - sqrt(3) * I * k**(Rational(1, 3)) / 2,
        -k**(Rational(1, 3)) / 2 + sqrt(3) * I * k**(Rational(1, 3)) / 2
    ]
    assert _TF.zeros() == [
        CRootOf(x**9 + x + 1, 0), 0,
        CRootOf(x**9 + x + 1, 1),
        CRootOf(x**9 + x + 1, 2),
        CRootOf(x**9 + x + 1, 3),
        CRootOf(x**9 + x + 1, 4),
        CRootOf(x**9 + x + 1, 5),
        CRootOf(x**9 + x + 1, 6),
        CRootOf(x**9 + x + 1, 7),
        CRootOf(x**9 + x + 1, 8)
    ]
    raises(NotImplementedError,
           lambda: TransferFunction(a0 * x**10 + x + x**2, x**2, x).zeros())

    # negation of TF.
    tf2 = TransferFunction(s + 3, s**2 - s**3 + 9, s)
    tf3 = TransferFunction(-3 * p + 3, 1 - p, p)
    assert -tf2 == TransferFunction(-s - 3, s**2 - s**3 + 9, s)
    assert -tf3 == TransferFunction(3 * p - 3, 1 - p, p)

    # taking power of a TF.
    tf4 = TransferFunction(p + 4, p - 3, p)
    tf5 = TransferFunction(s**2 + 1, 1 - s, s)
    expect2 = TransferFunction((s**2 + 1)**3, (1 - s)**3, s)
    expect1 = TransferFunction((p + 4)**2, (p - 3)**2, p)
    assert (tf4 * tf4).doit() == tf4**2 == pow(tf4, 2) == expect1
    assert (tf5 * tf5 * tf5).doit() == tf5**3 == pow(tf5, 3) == expect2
    assert tf5**0 == pow(tf5, 0) == TransferFunction(1, 1, s)
    assert Series(tf4).doit()**-1 == tf4**-1 == pow(
        tf4, -1) == TransferFunction(p - 3, p + 4, p)
    assert (tf5 * tf5).doit()**-1 == tf5**-2 == pow(
        tf5, -2) == TransferFunction((1 - s)**2, (s**2 + 1)**2, s)

    raises(ValueError, lambda: tf4**(s**2 + s - 1))
    raises(ValueError, lambda: tf5**s)
    raises(ValueError, lambda: tf4**tf5)

    # sympy's own functions.
    tf = TransferFunction(s - 1, s**2 - 2 * s + 1, s)
    tf6 = TransferFunction(s + p, p**2 - 5, s)
    assert factor(tf) == TransferFunction(s - 1, (s - 1)**2, s)
    assert tf.num.subs(s, 2) == tf.den.subs(s, 2) == 1
    # subs & xreplace
    assert tf.subs(s, 2) == TransferFunction(s - 1, s**2 - 2 * s + 1, s)
    assert tf6.subs(p, 3) == TransferFunction(s + 3, 4, s)
    assert tf3.xreplace({p: s}) == TransferFunction(-3 * s + 3, 1 - s, s)
    raises(TypeError, lambda: tf3.xreplace({p: exp(2)}))
    assert tf3.subs(p, exp(2)) == tf3

    tf7 = TransferFunction(a0 * s**p + a1 * p**s, a2 * p - s, s)
    assert tf7.xreplace({s: k}) == TransferFunction(a0 * k**p + a1 * p**k,
                                                    a2 * p - k, k)
    assert tf7.subs(s, k) == TransferFunction(a0 * s**p + a1 * p**s,
                                              a2 * p - s, s)

    # Conversion to Expr with to_expr()
    tf8 = TransferFunction(a0 * s**5 + 5 * s**2 + 3, s**6 - 3, s)
    tf9 = TransferFunction((5 + s), (5 + s) * (6 + s), s)
    tf10 = TransferFunction(0, 1, s)
    tf11 = TransferFunction(1, 1, s)
    assert tf8.to_expr() == Mul((a0 * s**5 + 5 * s**2 + 3),
                                Pow((s**6 - 3), -1, evaluate=False),
                                evaluate=False)
    assert tf9.to_expr() == Mul((s + 5),
                                Pow((5 + s) * (6 + s), -1, evaluate=False),
                                evaluate=False)
    assert tf10.to_expr() == Mul(S(0),
                                 Pow(1, -1, evaluate=False),
                                 evaluate=False)
    assert tf11.to_expr() == Pow(1, -1, evaluate=False)
Exemple #20
0
def _Pow(a, b):
    return Pow(a, b, evaluate=False)
Exemple #21
0
 ("\\int x dx", Integral(x, x)),
 ("\\int x d\\theta", Integral(x, theta)),
 ("\\int (x^2 - y)dx", Integral(x**2 - y, x)),
 ("\\int x + a dx", Integral(_Add(x, a), x)),
 ("\\int da", Integral(1, a)),
 ("\\int_0^7 dx", Integral(1, (x, 0, 7))),
 ("\\int_a^b x dx", Integral(x, (x, a, b))),
 ("\\int^b_a x dx", Integral(x, (x, a, b))),
 ("\\int_{a}^b x dx", Integral(x, (x, a, b))),
 ("\\int^{b}_a x dx", Integral(x, (x, a, b))),
 ("\\int_{a}^{b} x dx", Integral(x, (x, a, b))),
 ("\\int^{b}_{a} x dx", Integral(x, (x, a, b))),
 ("\\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))),
 ("\\int (x+a)", Integral(_Add(x, a), x)),
 ("\\int a + b + c dx", Integral(_Add(_Add(a, b), c), x)),
 ("\\int \\frac{dz}{z}", Integral(Pow(z, -1), z)),
 ("\\int \\frac{3 dz}{z}", Integral(3 * Pow(z, -1), z)),
 ("\\int \\frac{1}{x} dx", Integral(Pow(x, -1), x)),
 ("\\int \\frac{1}{a} + \\frac{1}{b} dx",
  Integral(_Add(_Pow(a, -1), Pow(b, -1)), x)),
 ("\\int \\frac{3 \\cdot d\\theta}{\\theta}",
  Integral(3 * _Pow(theta, -1), theta)),
 ("\\int \\frac{1}{x} + 1 dx", Integral(_Add(_Pow(x, -1), 1), x)),
 ("x_0", Symbol('x_{0}')), ("x_{1}", Symbol('x_{1}')),
 ("x_a", Symbol('x_{a}')), ("x_{b}", Symbol('x_{b}')),
 ("h_\\theta", Symbol('h_{theta}')),
 ("h_{\\theta}", Symbol('h_{theta}')),
 ("h_{\\theta}(x_0, x_1)",
  Function('h_{theta}')(Symbol('x_{0}'), Symbol('x_{1}'))),
 ("x!", _factorial(x)), ("100!", _factorial(100)),
 ("\\theta!", _factorial(theta)),
Exemple #22
0

def Pow(*args, **kwargs):
    return OldPow(*args, **kwargs, evaluate=False)


def Mul(*args, **kwargs):
    return OldMul(*args, **kwargs, evaluate=False)


init_printing()

e = Mod(
    Add(
        Mod(
            Mul(
                Mod(Symbol('b'), Symbol('c')),
                Mod(Pow(Add(Symbol('m'), Integer(-1)), Integer(-1)),
                    Symbol('c')),
                Mod(Add(Pow(Symbol('m'), Symbol('n')), Integer(-1)),
                    Symbol('c')),
            ), Symbol('c')),
        Mod(
            Mul(
                Mod(Pow(Symbol('m'), Symbol('n')), Symbol('c')),
                Mod(Symbol('x'), Symbol('c')),
            ), Symbol('c')),
    ), Symbol('c'))
print(e)
print(e.evalf(subs=dict(b=8036, x=499, n=2, m=7975, c=10007)))
Exemple #23
0
def square(x):
    """square(x)

    Return the square of the input, x * x.
    """
    return Pow(x, 2)
Exemple #24
0
def ldexp(x, i):
    """ldexp(x, i)

    Return x * (2**i).
    """
    return x * Pow(2, i)
Exemple #25
0
def torus_1():
    """
    http://www.cosinekitty.com/raytrace/chapter13_torus.html

    Symbolic manipulations matching cosinekitty example

    * simplifying coeffs separately then putting 
      back together seems an effective approach

    """
    x, y, z, A, B = symbols("x y z A B")

    _sq_lhs = (x * x + y * y + z * z + A * A - B * B)
    _rhs = 4 * A * A * (x * x + y * y)

    ox, oy, oz, t, sx, sy, sz, SS, OO, OS = symbols(
        "ox oy oz t sx sy sz SS OO OS")

    ray = [(x, ox + t * sx), (y, oy + t * sy), (z, oz + t * sz)]
    simp0 = [(sx**2 + sy**2 + sz**2, SS), (ox**2 + oy**2 + oz**2, OO),
             (ox * sx + oy * sy + oz * sz, OS)]

    G, H, I, J, K, L = symbols("G H I J K L")

    exG = 4 * A * A * (sx * sx + sy * sy)
    exH = 8 * A * A * (ox * sx + oy * sy)
    exI = 4 * A * A * (ox * ox + oy * oy)
    exJ = sx * sx + sy * sy + sz * sz
    exK = 2 * (ox * sx + oy * sy + oz * sz)
    exL = ox * ox + oy * oy + oz * oz + A * A - B * B

    simp1 = [
        (exG, G),
        (exH, H),
        (exI, I),
        (exJ, J),
        (exK / 2, K / 2),  # fails to sub with 2 on other side
        (exL, L)
    ]

    sq_lhs = _sq_lhs.subs(ray + simp0)
    rhs = _rhs.subs(ray + simp0)

    cl = get_coeff(sq_lhs, t, 3)
    cr = get_coeff(rhs, t, 3)

    subs_coeff(cl, simp1)
    subs_coeff(cr, simp1)

    print_coeff(cl, "cl")
    print_coeff(cr, "cr")

    SQ_LHS = expr_coeff(cl, t)
    RHS = expr_coeff(cr, t)

    ex = Pow(SQ_LHS, 2) - RHS

    c = get_coeff(ex, t, 5)

    print_coeff(c, "c")

    exc = range(5)
    exc[4] = exJ**2
    exc[3] = 2 * exJ * exK
    exc[2] = -exG + 2 * exJ * exL + exK**2
    exc[1] = -exH + 2 * exK * exL
    exc[0] = -exI + exL**2

    subs = {}
    subs["O->X+"] = [(ox, 0), (oy, 0), (oz, 0), (sx, 1), (sy, 0), (sz, 0)]
    subs["zenith->-Z"] = [(ox, 0), (oy, 0), (oz, A), (sx, 0), (sy, 0),
                          (sz, -1)]
    subs["corner"] = [(ox, A), (oy, A), (oz, A), (sx, -isq3), (sy, -isq3),
                      (sz, -isq3)]

    radii = [(A, 500), (B, 50)]

    for key in subs:
        print("\n\n", key)
        for j, exc_ in enumerate(exc):
            print("\n", j, exc_)
            print(exc_.subs(subs[key]))
            print(exc_.subs(subs[key]).subs(radii))

    return ex, cl
Exemple #26
0
def test_evaluate_false():
    for no in [0, False, None]:
        assert Add(3, 2, evaluate=no).is_Add
        assert Mul(3, 2, evaluate=no).is_Mul
        assert Pow(3, 2, evaluate=no).is_Pow
    assert Pow(y, 2, evaluate=True) - Pow(y, 2, evaluate=True) == 0
Exemple #27
0
 def _eval_derivative(self, x):
     from sympy import Pow
     return Pow._eval_derivative(self, x)
Exemple #28
0
def test_issue_6611a():
    assert Mul.flatten([3**Rational(1, 3),
        Pow(-Rational(1, 9), Rational(2, 3), evaluate=False)]) == \
        ([Rational(1, 3), (-1)**Rational(2, 3)], [], None)
Exemple #29
0
def test_cse_single():
    # Simple substitution.
    e = Add(Pow(x + y, 2), sqrt(x + y))
    substs, reduced = cse([e])
    assert substs == [(x0, x + y)]
    assert reduced == [sqrt(x0) + x0**2]
Exemple #30
0
def test_issue_2941():
    a, b = Pow(1, 2, evaluate=False), S.One
    assert a != b
    assert b != a
    assert not (a == b)
    assert not (b == a)
Exemple #31
0
def test_cse_single2():
    # Simple substitution, test for being able to pass the expression directly
    e = Add(Pow(x+y,2), sqrt(x+y))
    substs, reduced = cse(e, optimizations=[])
    assert substs == [(x0, x+y)]
    assert reduced == [sqrt(x0) + x0**2]