Exemplo n.º 1
0
 def solve_eqn(self):
     q, betasq, ml, md, m0 = sympy.symbols('q,betasq,ml,md,m0')
     nbetasq = self.model_betasq()
     eqn1, eqn2, eqn3, eqn4, eqn5 = self.get_eqns()
     sols = sympy.solve([eqn1.subs(betasq, nbetasq), 
                         eqn2.subs(betasq, nbetasq), 
                         eqn3.subs(betasq, nbetasq),
                         eqn4.subs(betasq, nbetasq)],
                        [q, ml, md, m0])
     isAllReal = lambda item: im(item[0])==0 and im(item[1])==0 and im(item[2])==0 and im(item[3])==0
     sols = filter(isAllReal, sols)
     isValid = lambda item: item[0]>0 and item[1]>=0 and item[2]>=0 and item[3]>0
     sols = filter(isValid, sols)
     return sols
Exemplo n.º 2
0
def roots_binomial(f):
    """Returns a list of roots of a binomial polynomial."""
    n = f.degree()

    a, b = f.nth(n), f.nth(0)
    alpha = (-cancel(b / a))**Rational(1, n)

    if alpha.is_number:
        alpha = alpha.expand(complex=True)

    roots, I = [], S.ImaginaryUnit

    for k in xrange(n):
        zeta = exp(2 * k * S.Pi * I / n).expand(complex=True)
        roots.append((alpha * zeta).expand(power_base=False))

    if all([r.is_number for r in roots]):
        reals, complexes = [], []

        for root in roots:
            if root.is_real:
                reals.append(root)
            else:
                complexes.append(root)

        roots = sorted(reals) + sorted(complexes,
                                       key=lambda r: (re(r), -im(r)))

    return roots
Exemplo n.º 3
0
def roots_binomial(f):
    """Returns a list of roots of a binomial polynomial."""
    n = f.degree()

    a, b = f.nth(n), f.nth(0)
    alpha = (-cancel(b/a))**Rational(1, n)

    if alpha.is_number:
        alpha = alpha.expand(complex=True)

    roots, I = [], S.ImaginaryUnit

    for k in xrange(n):
        zeta = exp(2*k*S.Pi*I/n).expand(complex=True)
        roots.append((alpha*zeta).expand(power_base=False))

    if all([ r.is_number for r in roots ]):
        reals, complexes = [], []

        for root in roots:
            if root.is_real:
                reals.append(root)
            else:
                complexes.append(root)

        roots = sorted(reals) + sorted(complexes, key=lambda r: (re(r), -im(r)))

    return roots
Exemplo n.º 4
0
 def solve_eqn(self):
     q, betasq, ml, md, m0 = sympy.symbols('q,betasq,ml,md,m0')
     nbetasq = self.model_betasq()
     eqn1, eqn2, eqn3, eqn4, eqn5 = self.get_eqns()
     sols = sympy.solve([
         eqn1.subs(betasq, nbetasq),
         eqn2.subs(betasq, nbetasq),
         eqn3.subs(betasq, nbetasq),
         eqn4.subs(betasq, nbetasq)
     ], [q, ml, md, m0])
     isAllReal = lambda item: im(item[0]) == 0 and im(item[1]) == 0 and im(
         item[2]) == 0 and im(item[3]) == 0
     sols = filter(isAllReal, sols)
     isValid = lambda item: item[0] > 0 and item[1] >= 0 and item[
         2] >= 0 and item[3] > 0
     sols = filter(isValid, sols)
     return sols
Exemplo n.º 5
0
def reduce_poly_inequalities(exprs, gen, assume=True, relational=True):
    """Reduce a system of polynomial inequalities with rational coefficients. """
    exact = True
    polys = []

    for _exprs in exprs:
        _polys = []

        for expr in _exprs:
            if isinstance(expr, tuple):
                expr, rel = expr
            else:
                if expr.is_Relational:
                    expr, rel = expr.lhs - expr.rhs, expr.rel_op
                else:
                    expr, rel = expr, '=='

            poly = Poly(expr, gen)

            if not poly.get_domain().is_Exact:
                poly, exact = poly.to_exact(), False

            domain = poly.get_domain()

            if not (domain.is_ZZ or domain.is_QQ):
                raise NotImplementedError(
                    "inequality solving is not supported over %s" % domain)

            _polys.append((poly, rel))

        polys.append(_polys)

    solution = solve_poly_inequalities(polys)

    if isinstance(solution, Union):
        intervals = list(solution.args)
    elif isinstance(solution, Interval):
        intervals = [solution]
    else:
        intervals = []

    if not exact:
        intervals = map(interval_evalf, intervals)

    if not relational:
        return intervals

    real = ask(gen, 'real', assume)

    def relationalize(gen):
        return Or(*[i.as_relational(gen) for i in intervals])

    if not real:
        result = And(relationalize(re(gen)), Eq(im(gen), 0))
    else:
        result = relationalize(gen)

    return result
Exemplo n.º 6
0
def test_even():
    x, y, z, t = symbols('x,y,z,t')
    assert ask(x, Q.even) == None
    assert ask(x, Q.even, Assume(x, Q.integer)) == None
    assert ask(x, Q.even, Assume(x, Q.integer, False)) == False
    assert ask(x, Q.even, Assume(x, Q.rational)) == None
    assert ask(x, Q.even, Assume(x, Q.positive)) == None

    assert ask(2 * x, Q.even) == None
    assert ask(2 * x, Q.even, Assume(x, Q.integer)) == True
    assert ask(2 * x, Q.even, Assume(x, Q.even)) == True
    assert ask(2 * x, Q.even, Assume(x, Q.irrational)) == False
    assert ask(2 * x, Q.even, Assume(x, Q.odd)) == True
    assert ask(2 * x, Q.even, Assume(x, Q.integer, False)) == None
    assert ask(3 * x, Q.even, Assume(x, Q.integer)) == None
    assert ask(3 * x, Q.even, Assume(x, Q.even)) == True
    assert ask(3 * x, Q.even, Assume(x, Q.odd)) == False

    assert ask(x + 1, Q.even, Assume(x, Q.odd)) == True
    assert ask(x + 1, Q.even, Assume(x, Q.even)) == False
    assert ask(x + 2, Q.even, Assume(x, Q.odd)) == False
    assert ask(x + 2, Q.even, Assume(x, Q.even)) == True
    assert ask(7 - x, Q.even, Assume(x, Q.odd)) == True
    assert ask(7 + x, Q.even, Assume(x, Q.odd)) == True
    assert ask(x + y, Q.even, Assume(x, Q.odd) & Assume(y, Q.odd)) == True
    assert ask(x + y, Q.even, Assume(x, Q.odd) & Assume(y, Q.even)) == False
    assert ask(x + y, Q.even, Assume(x, Q.even) & Assume(y, Q.even)) == True

    assert ask(2 * x + 1, Q.even, Assume(x, Q.integer)) == False
    assert ask(2 * x * y, Q.even,
               Assume(x, Q.rational) & Assume(x, Q.rational)) == None
    assert ask(2 * x * y, Q.even,
               Assume(x, Q.irrational) & Assume(x, Q.irrational)) == None

    assert ask(x+y+z, Q.even, Assume(x, Q.odd) & Assume(y, Q.odd) & \
                     Assume(z, Q.even)) == True
    assert ask(x+y+z+t, Q.even, Assume(x, Q.odd) & Assume(y, Q.odd) & \
                     Assume(z, Q.even) & Assume(t, Q.integer)) == None

    assert ask(Abs(x), Q.even, Assume(x, Q.even)) == True
    assert ask(Abs(x), Q.even, Assume(x, Q.even, False)) == None
    assert ask(re(x), Q.even, Assume(x, Q.even)) == True
    assert ask(re(x), Q.even, Assume(x, Q.even, False)) == None
    assert ask(im(x), Q.even, Assume(x, Q.even)) == True
    assert ask(im(x), Q.even, Assume(x, Q.real)) == True
Exemplo n.º 7
0
def reduce_poly_inequalities(exprs, gen, assume=True, relational=True):
    """Reduce a system of polynomial inequalities with rational coefficients. """
    exact = True
    polys = []

    for _exprs in exprs:
        _polys = []

        for expr in _exprs:
            if isinstance(expr, tuple):
                expr, rel = expr
            else:
                if expr.is_Relational:
                    expr, rel = expr.lhs - expr.rhs, expr.rel_op
                else:
                    expr, rel = expr, '=='

            poly = Poly(expr, gen)

            if not poly.get_domain().is_Exact:
                poly, exact = poly.to_exact(), False

            domain = poly.get_domain()

            if not (domain.is_ZZ or domain.is_QQ):
                raise NotImplementedError("inequality solving is not supported over %s" % domain)

            _polys.append((poly, rel))

        polys.append(_polys)

    solution = solve_poly_inequalities(polys)

    if isinstance(solution, Union):
        intervals = list(solution.args)
    elif isinstance(solution, Interval):
        intervals = [solution]
    else:
        intervals = []

    if not exact:
        intervals = map(interval_evalf, intervals)

    if not relational:
        return intervals

    real = ask(gen, 'real', assume)

    def relationalize(gen):
        return Or(*[ i.as_relational(gen) for i in intervals ])

    if not real:
        result = And(relationalize(re(gen)), Eq(im(gen), 0))
    else:
        result = relationalize(gen)

    return result
Exemplo n.º 8
0
def test_even():
    x, y, z, t = symbols("x,y,z,t")
    assert ask(x, Q.even) == None
    assert ask(x, Q.even, Assume(x, Q.integer)) == None
    assert ask(x, Q.even, Assume(x, Q.integer, False)) == False
    assert ask(x, Q.even, Assume(x, Q.rational)) == None
    assert ask(x, Q.even, Assume(x, Q.positive)) == None

    assert ask(2 * x, Q.even) == None
    assert ask(2 * x, Q.even, Assume(x, Q.integer)) == True
    assert ask(2 * x, Q.even, Assume(x, Q.even)) == True
    assert ask(2 * x, Q.even, Assume(x, Q.irrational)) == False
    assert ask(2 * x, Q.even, Assume(x, Q.odd)) == True
    assert ask(2 * x, Q.even, Assume(x, Q.integer, False)) == None
    assert ask(3 * x, Q.even, Assume(x, Q.integer)) == None
    assert ask(3 * x, Q.even, Assume(x, Q.even)) == True
    assert ask(3 * x, Q.even, Assume(x, Q.odd)) == False

    assert ask(x + 1, Q.even, Assume(x, Q.odd)) == True
    assert ask(x + 1, Q.even, Assume(x, Q.even)) == False
    assert ask(x + 2, Q.even, Assume(x, Q.odd)) == False
    assert ask(x + 2, Q.even, Assume(x, Q.even)) == True
    assert ask(7 - x, Q.even, Assume(x, Q.odd)) == True
    assert ask(7 + x, Q.even, Assume(x, Q.odd)) == True
    assert ask(x + y, Q.even, Assume(x, Q.odd) & Assume(y, Q.odd)) == True
    assert ask(x + y, Q.even, Assume(x, Q.odd) & Assume(y, Q.even)) == False
    assert ask(x + y, Q.even, Assume(x, Q.even) & Assume(y, Q.even)) == True

    assert ask(2 * x + 1, Q.even, Assume(x, Q.integer)) == False
    assert ask(2 * x * y, Q.even, Assume(x, Q.rational) & Assume(x, Q.rational)) == None
    assert ask(2 * x * y, Q.even, Assume(x, Q.irrational) & Assume(x, Q.irrational)) == None

    assert ask(x + y + z, Q.even, Assume(x, Q.odd) & Assume(y, Q.odd) & Assume(z, Q.even)) == True
    assert (
        ask(x + y + z + t, Q.even, Assume(x, Q.odd) & Assume(y, Q.odd) & Assume(z, Q.even) & Assume(t, Q.integer))
        == None
    )

    assert ask(Abs(x), Q.even, Assume(x, Q.even)) == True
    assert ask(Abs(x), Q.even, Assume(x, Q.even, False)) == None
    assert ask(re(x), Q.even, Assume(x, Q.even)) == True
    assert ask(re(x), Q.even, Assume(x, Q.even, False)) == None
    assert ask(im(x), Q.even, Assume(x, Q.even)) == True
    assert ask(im(x), Q.even, Assume(x, Q.real)) == True
Exemplo n.º 9
0
def test_Function():
    assert mcode(sin(x)**cos(x)) == "sin(x).^cos(x)"
    assert mcode(abs(x)) == "abs(x)"
    assert mcode(ceiling(x)) == "ceil(x)"
    assert mcode(arg(x)) == "angle(x)"
    assert mcode(im(x)) == "imag(x)"
    assert mcode(re(x)) == "real(x)"
    assert mcode(Max(x, y) + Min(x, y)) == "max(x, y) + min(x, y)"
    assert mcode(Max(x, y, z)) == "max(x, max(y, z))"
    assert mcode(Min(x, y, z)) == "min(x, min(y, z))"
Exemplo n.º 10
0
def test_Function():
    assert mcode(sin(x) ** cos(x)) == "sin(x).^cos(x)"
    assert mcode(abs(x)) == "abs(x)"
    assert mcode(ceiling(x)) == "ceil(x)"
    assert mcode(arg(x)) == "angle(x)"
    assert mcode(im(x)) == "imag(x)"
    assert mcode(re(x)) == "real(x)"
    assert mcode(Max(x, y) + Min(x, y)) == "max(x, y) + min(x, y)"
    assert mcode(Max(x, y, z)) == "max(x, max(y, z))"
    assert mcode(Min(x, y, z)) == "min(x, min(y, z))"
Exemplo n.º 11
0
def test_even():
    x, y, z, t = symbols('x,y,z,t')
    assert ask(Q.even(x)) == None
    assert ask(Q.even(x), Q.integer(x)) == None
    assert ask(Q.even(x), ~Q.integer(x)) == False
    assert ask(Q.even(x), Q.rational(x)) == None
    assert ask(Q.even(x), Q.positive(x)) == None

    assert ask(Q.even(2 * x)) == None
    assert ask(Q.even(2 * x), Q.integer(x)) == True
    assert ask(Q.even(2 * x), Q.even(x)) == True
    assert ask(Q.even(2 * x), Q.irrational(x)) == False
    assert ask(Q.even(2 * x), Q.odd(x)) == True
    assert ask(Q.even(2 * x), ~Q.integer(x)) == None
    assert ask(Q.even(3 * x), Q.integer(x)) == None
    assert ask(Q.even(3 * x), Q.even(x)) == True
    assert ask(Q.even(3 * x), Q.odd(x)) == False

    assert ask(Q.even(x + 1), Q.odd(x)) == True
    assert ask(Q.even(x + 1), Q.even(x)) == False
    assert ask(Q.even(x + 2), Q.odd(x)) == False
    assert ask(Q.even(x + 2), Q.even(x)) == True
    assert ask(Q.even(7 - x), Q.odd(x)) == True
    assert ask(Q.even(7 + x), Q.odd(x)) == True
    assert ask(Q.even(x + y), Q.odd(x) & Q.odd(y)) == True
    assert ask(Q.even(x + y), Q.odd(x) & Q.even(y)) == False
    assert ask(Q.even(x + y), Q.even(x) & Q.even(y)) == True

    assert ask(Q.even(2 * x + 1), Q.integer(x)) == False
    assert ask(Q.even(2 * x * y), Q.rational(x) & Q.rational(x)) == None
    assert ask(Q.even(2 * x * y), Q.irrational(x) & Q.irrational(x)) == None

    assert ask(Q.even(x + y + z), Q.odd(x) & Q.odd(y) & Q.even(z)) == True
    assert ask(Q.even(x + y + z + t),
               Q.odd(x) & Q.odd(y) & Q.even(z) & Q.integer(t)) == None

    assert ask(Q.even(Abs(x)), Q.even(x)) == True
    assert ask(Q.even(Abs(x)), ~Q.even(x)) == None
    assert ask(Q.even(re(x)), Q.even(x)) == True
    assert ask(Q.even(re(x)), ~Q.even(x)) == None
    assert ask(Q.even(im(x)), Q.even(x)) == True
    assert ask(Q.even(im(x)), Q.real(x)) == True
Exemplo n.º 12
0
def test_even():
    x, y, z, t = symbols('x,y,z,t')
    assert ask(Q.even(x)) == None
    assert ask(Q.even(x), Q.integer(x)) == None
    assert ask(Q.even(x), ~Q.integer(x)) == False
    assert ask(Q.even(x), Q.rational(x)) == None
    assert ask(Q.even(x), Q.positive(x)) == None

    assert ask(Q.even(2*x)) == None
    assert ask(Q.even(2*x), Q.integer(x)) == True
    assert ask(Q.even(2*x), Q.even(x)) == True
    assert ask(Q.even(2*x), Q.irrational(x)) == False
    assert ask(Q.even(2*x), Q.odd(x)) == True
    assert ask(Q.even(2*x), ~Q.integer(x)) == None
    assert ask(Q.even(3*x), Q.integer(x)) == None
    assert ask(Q.even(3*x), Q.even(x)) == True
    assert ask(Q.even(3*x), Q.odd(x)) == False

    assert ask(Q.even(x+1), Q.odd(x)) == True
    assert ask(Q.even(x+1), Q.even(x)) == False
    assert ask(Q.even(x+2), Q.odd(x)) == False
    assert ask(Q.even(x+2), Q.even(x)) == True
    assert ask(Q.even(7-x), Q.odd(x)) == True
    assert ask(Q.even(7+x), Q.odd(x)) == True
    assert ask(Q.even(x+y), Q.odd(x) & Q.odd(y)) == True
    assert ask(Q.even(x+y), Q.odd(x) & Q.even(y)) == False
    assert ask(Q.even(x+y), Q.even(x) & Q.even(y)) == True

    assert ask(Q.even(2*x + 1), Q.integer(x)) == False
    assert ask(Q.even(2*x*y), Q.rational(x) & Q.rational(x)) == None
    assert ask(Q.even(2*x*y), Q.irrational(x) & Q.irrational(x)) == None

    assert ask(Q.even(x+y+z), Q.odd(x) & Q.odd(y) & Q.even(z)) == True
    assert ask(Q.even(x+y+z+t),
               Q.odd(x) & Q.odd(y) & Q.even(z) & Q.integer(t)) == None

    assert ask(Q.even(Abs(x)), Q.even(x)) == True
    assert ask(Q.even(Abs(x)), ~Q.even(x)) == None
    assert ask(Q.even(re(x)), Q.even(x)) == True
    assert ask(Q.even(re(x)), ~Q.even(x)) == None
    assert ask(Q.even(im(x)), Q.even(x)) == True
    assert ask(Q.even(im(x)), Q.real(x)) == True
Exemplo n.º 13
0
def change_matrix_type(matrix, num_to_sym=1):
	"""
	Change a matrix or array from numpy to sympy and a sympy matrix
	to numpy matrix.
	"""
	if num_to_sym:
		n = len(matrix)
		new_matrix = sp.Matrix([[matrix[i,j] for j in range(n)] for i in range(n)])
	else:
		n = int(sqrt(len(matrix)))
		new_matrix = np.matrix([[complex(fun.re(matrix[i,j]), fun.im(matrix[i,j])) for j in range(n)] for i in range(n)])	
	return new_matrix
Exemplo n.º 14
0
def findPrimitiveRoot(n):
    if (n == 1):
        return solve(x - 1)[0]
    else:
        unorderedRoots = solve(x**n - 1)
        if unorderedRoots[0] != 1:
            currentMax = unorderedRoots[0]
        else:
            currentMax = unorderedRoots[1]
        for item in unorderedRoots:
            if re(item) >= re(currentMax) and im(item) > 0:
                currentMax = item
        return currentMax
Exemplo n.º 15
0
def eqFinder(r, K, q, eL, eH, p, w, gamma):
    n = Symbol('n')
    A = solve(
        p * q * n - p * q * r * gamma * n**2 + p * q * r * gamma * n**3 / K -
        w, n)
    B = np.array(A)
    C = B.astype('complex128')
    nStar = np.zeros(len(C))
    for i in range(len(C)):
        if np.abs(im(C[i])) < .001:
            nStar[i] = re(C[i])
        else:
            nStar[i] = np.nan
    xStar = eH / (eH - eL) - (r) / (q * (eH - eL)) * (1 - 1 / K * nStar)
    return (xStar, nStar)
Exemplo n.º 16
0
def reduce_poly_inequalities(exprs, gen, assume=True, relational=True):
    """Reduce a system of polynomial inequalities with rational coefficients. """
    exact = True
    polys = []

    for _exprs in exprs:
        _polys = []

        for expr in _exprs:
            if isinstance(expr, tuple):
                expr, rel = expr
            else:
                if expr.is_Relational:
                    expr, rel = expr.lhs - expr.rhs, expr.rel_op
                else:
                    expr, rel = expr, '=='

            poly = Poly(expr, gen)

            if not poly.get_domain().is_Exact:
                poly, exact = poly.to_exact(), False

            domain = poly.get_domain()

            if not (domain.is_ZZ or domain.is_QQ):
                raise NotImplementedError(
                    "inequality solving is not supported over %s" % domain)

            _polys.append((poly, rel))

        polys.append(_polys)

    solution = solve_poly_inequalities(polys)

    if not exact:
        solution = solution.evalf()

    if not relational:
        return solution

    real = ask(Q.real(gen), assumptions=assume)

    if not real:
        result = And(solution.as_relational(re(gen)), Eq(im(gen), 0))
    else:
        result = solution.as_relational(gen)

    return result
Exemplo n.º 17
0
def reduce_poly_inequalities(exprs, gen, assume=True, relational=True):
    """Reduce a system of polynomial inequalities with rational coefficients. """
    exact = True
    polys = []

    for _exprs in exprs:
        _polys = []

        for expr in _exprs:
            if isinstance(expr, tuple):
                expr, rel = expr
            else:
                if expr.is_Relational:
                    expr, rel = expr.lhs - expr.rhs, expr.rel_op
                else:
                    expr, rel = expr, "=="

            poly = Poly(expr, gen)

            if not poly.get_domain().is_Exact:
                poly, exact = poly.to_exact(), False

            domain = poly.get_domain()

            if not (domain.is_ZZ or domain.is_QQ):
                raise NotImplementedError("inequality solving is not supported over %s" % domain)

            _polys.append((poly, rel))

        polys.append(_polys)

    solution = solve_poly_inequalities(polys)

    if not exact:
        solution = solution.evalf()

    if not relational:
        return solution

    real = ask(Q.real(gen), assumptions=assume)

    if not real:
        result = And(solution.as_relational(re(gen)), Eq(im(gen), 0))
    else:
        result = solution.as_relational(gen)

    return result
Exemplo n.º 18
0
def test_real():
    x, y = symbols('x y')
    assert ask(x, Q.real) == None
    assert ask(x, Q.real, Assume(x, Q.real)) == True
    assert ask(x, Q.real, Assume(x, Q.nonzero)) == True
    assert ask(x, Q.real, Assume(x, Q.positive)) == True
    assert ask(x, Q.real, Assume(x, Q.negative)) == True
    assert ask(x, Q.real, Assume(x, Q.integer)) == True
    assert ask(x, Q.real, Assume(x, Q.even)) == True
    assert ask(x, Q.real, Assume(x, Q.prime)) == True

    assert ask(x/sqrt(2), Q.real, Assume(x, Q.real)) == True
    assert ask(x/sqrt(-2), Q.real, Assume(x, Q.real)) == False

    I = S.ImaginaryUnit
    assert ask(x+1, Q.real, Assume(x, Q.real)) == True
    assert ask(x+I, Q.real, Assume(x, Q.real)) == False
    assert ask(x+I, Q.real, Assume(x, Q.complex)) == None

    assert ask(2*x, Q.real, Assume(x, Q.real)) == True
    assert ask(I*x, Q.real, Assume(x, Q.real)) == False
    assert ask(I*x, Q.real, Assume(x, Q.imaginary)) == True
    assert ask(I*x, Q.real, Assume(x, Q.complex)) == None

    assert ask(x**2, Q.real, Assume(x, Q.real)) == True
    assert ask(sqrt(x), Q.real, Assume(x, Q.negative)) == False
    assert ask(x**y, Q.real, Assume(x, Q.real) & Assume(y, Q.integer)) == True
    assert ask(x**y, Q.real, Assume(x, Q.real) & Assume(y, Q.real)) == None
    assert ask(x**y, Q.real, Assume(x, Q.positive) & \
                     Assume(y, Q.real)) == True

    # trigonometric functions
    assert ask(sin(x), Q.real) == None
    assert ask(cos(x), Q.real) == None
    assert ask(sin(x), Q.real, Assume(x, Q.real)) == True
    assert ask(cos(x), Q.real, Assume(x, Q.real)) == True

    # exponential function
    assert ask(exp(x), Q.real) == None
    assert ask(exp(x), Q.real, Assume(x, Q.real)) == True
    assert ask(x + exp(x), Q.real, Assume(x, Q.real)) == True

    # Q.complexes
    assert ask(re(x), Q.real) == True
    assert ask(im(x), Q.real) == True
Exemplo n.º 19
0
def test_real():
    x, y = symbols('x,y')
    assert ask(Q.real(x)) == None
    assert ask(Q.real(x), Q.real(x)) == True
    assert ask(Q.real(x), Q.nonzero(x)) == True
    assert ask(Q.real(x), Q.positive(x)) == True
    assert ask(Q.real(x), Q.negative(x)) == True
    assert ask(Q.real(x), Q.integer(x)) == True
    assert ask(Q.real(x), Q.even(x)) == True
    assert ask(Q.real(x), Q.prime(x)) == True

    assert ask(Q.real(x/sqrt(2)), Q.real(x)) == True
    assert ask(Q.real(x/sqrt(-2)), Q.real(x)) == False

    I = S.ImaginaryUnit
    assert ask(Q.real(x+1), Q.real(x)) == True
    assert ask(Q.real(x+I), Q.real(x)) == False
    assert ask(Q.real(x+I), Q.complex(x)) == None

    assert ask(Q.real(2*x), Q.real(x)) == True
    assert ask(Q.real(I*x), Q.real(x)) == False
    assert ask(Q.real(I*x), Q.imaginary(x)) == True
    assert ask(Q.real(I*x), Q.complex(x)) == None

    assert ask(Q.real(x**2), Q.real(x)) == True
    assert ask(Q.real(sqrt(x)), Q.negative(x)) == False
    assert ask(Q.real(x**y), Q.real(x) & Q.integer(y)) == True
    assert ask(Q.real(x**y), Q.real(x) & Q.real(y)) == None
    assert ask(Q.real(x**y), Q.positive(x) & Q.real(y)) == True

    # trigonometric functions
    assert ask(Q.real(sin(x))) == None
    assert ask(Q.real(cos(x))) == None
    assert ask(Q.real(sin(x)), Q.real(x)) == True
    assert ask(Q.real(cos(x)), Q.real(x)) == True

    # exponential function
    assert ask(Q.real(exp(x))) == None
    assert ask(Q.real(exp(x)), Q.real(x)) == True
    assert ask(Q.real(x + exp(x)), Q.real(x)) == True

    # Q.complexes
    assert ask(Q.real(re(x))) == True
    assert ask(Q.real(im(x))) == True
Exemplo n.º 20
0
def test_real():
    x, y = symbols('x,y')
    assert ask(Q.real(x)) == None
    assert ask(Q.real(x), Q.real(x)) == True
    assert ask(Q.real(x), Q.nonzero(x)) == True
    assert ask(Q.real(x), Q.positive(x)) == True
    assert ask(Q.real(x), Q.negative(x)) == True
    assert ask(Q.real(x), Q.integer(x)) == True
    assert ask(Q.real(x), Q.even(x)) == True
    assert ask(Q.real(x), Q.prime(x)) == True

    assert ask(Q.real(x / sqrt(2)), Q.real(x)) == True
    assert ask(Q.real(x / sqrt(-2)), Q.real(x)) == False

    I = S.ImaginaryUnit
    assert ask(Q.real(x + 1), Q.real(x)) == True
    assert ask(Q.real(x + I), Q.real(x)) == False
    assert ask(Q.real(x + I), Q.complex(x)) == None

    assert ask(Q.real(2 * x), Q.real(x)) == True
    assert ask(Q.real(I * x), Q.real(x)) == False
    assert ask(Q.real(I * x), Q.imaginary(x)) == True
    assert ask(Q.real(I * x), Q.complex(x)) == None

    assert ask(Q.real(x**2), Q.real(x)) == True
    assert ask(Q.real(sqrt(x)), Q.negative(x)) == False
    assert ask(Q.real(x**y), Q.real(x) & Q.integer(y)) == True
    assert ask(Q.real(x**y), Q.real(x) & Q.real(y)) == None
    assert ask(Q.real(x**y), Q.positive(x) & Q.real(y)) == True

    # trigonometric functions
    assert ask(Q.real(sin(x))) == None
    assert ask(Q.real(cos(x))) == None
    assert ask(Q.real(sin(x)), Q.real(x)) == True
    assert ask(Q.real(cos(x)), Q.real(x)) == True

    # exponential function
    assert ask(Q.real(exp(x))) == None
    assert ask(Q.real(exp(x)), Q.real(x)) == True
    assert ask(Q.real(x + exp(x)), Q.real(x)) == True

    # Q.complexes
    assert ask(Q.real(re(x))) == True
    assert ask(Q.real(im(x))) == True
Exemplo n.º 21
0
def test_Function_change_name():
    assert mcode(abs(x)) == "abs(x)"
    assert mcode(ceiling(x)) == "ceil(x)"
    assert mcode(arg(x)) == "angle(x)"
    assert mcode(im(x)) == "imag(x)"
    assert mcode(re(x)) == "real(x)"
    assert mcode(conjugate(x)) == "conj(x)"
    assert mcode(chebyshevt(y, x)) == "chebyshevT(y, x)"
    assert mcode(chebyshevu(y, x)) == "chebyshevU(y, x)"
    assert mcode(laguerre(x, y)) == "laguerreL(x, y)"
    assert mcode(Chi(x)) == "coshint(x)"
    assert mcode(Shi(x)) ==  "sinhint(x)"
    assert mcode(Ci(x)) == "cosint(x)"
    assert mcode(Si(x)) ==  "sinint(x)"
    assert mcode(li(x)) ==  "logint(x)"
    assert mcode(loggamma(x)) ==  "gammaln(x)"
    assert mcode(polygamma(x, y)) == "psi(x, y)"
    assert mcode(RisingFactorial(x, y)) == "pochhammer(x, y)"
    assert mcode(DiracDelta(x)) == "dirac(x)"
    assert mcode(DiracDelta(x, 3)) == "dirac(3, x)"
    assert mcode(Heaviside(x)) == "heaviside(x)"
    assert mcode(Heaviside(x, y)) == "heaviside(x, y)"
Exemplo n.º 22
0
def test_Function_change_name():
    assert mcode(abs(x)) == "abs(x)"
    assert mcode(ceiling(x)) == "ceil(x)"
    assert mcode(arg(x)) == "angle(x)"
    assert mcode(im(x)) == "imag(x)"
    assert mcode(re(x)) == "real(x)"
    assert mcode(conjugate(x)) == "conj(x)"
    assert mcode(chebyshevt(y, x)) == "chebyshevT(y, x)"
    assert mcode(chebyshevu(y, x)) == "chebyshevU(y, x)"
    assert mcode(laguerre(x, y)) == "laguerreL(x, y)"
    assert mcode(Chi(x)) == "coshint(x)"
    assert mcode(Shi(x)) == "sinhint(x)"
    assert mcode(Ci(x)) == "cosint(x)"
    assert mcode(Si(x)) == "sinint(x)"
    assert mcode(li(x)) == "logint(x)"
    assert mcode(loggamma(x)) == "gammaln(x)"
    assert mcode(polygamma(x, y)) == "psi(x, y)"
    assert mcode(RisingFactorial(x, y)) == "pochhammer(x, y)"
    assert mcode(DiracDelta(x)) == "dirac(x)"
    assert mcode(DiracDelta(x, 3)) == "dirac(3, x)"
    assert mcode(Heaviside(x)) == "heaviside(x)"
    assert mcode(Heaviside(x, y)) == "heaviside(x, y)"
Exemplo n.º 23
0
def _get_const_characteristic_eq_sols(r, func, order):
    r"""
    Returns the roots of characteristic equation of constant coefficient
    linear ODE and list of collectterms which is later on used by simplification
    to use collect on solution.

    The parameter `r` is a dict of order:coeff terms, where order is the order of the
    derivative on each term, and coeff is the coefficient of that derivative.

    """
    x = func.args[0]
    # First, set up characteristic equation.
    chareq, symbol = S.Zero, Dummy('x')

    for i in r.keys():
        if type(i) == str or i < 0:
            pass
        else:
            chareq += r[i] * symbol**i

    chareq = Poly(chareq, symbol)
    # Can't just call roots because it doesn't return rootof for unsolveable
    # polynomials.
    chareqroots = roots(chareq, multiple=True)
    if len(chareqroots) != order:
        chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]

    chareq_is_complex = not all(i.is_real for i in chareq.all_coeffs())

    # Create a dict root: multiplicity or charroots
    charroots = defaultdict(int)
    for root in chareqroots:
        charroots[root] += 1
    # We need to keep track of terms so we can run collect() at the end.
    # This is necessary for constantsimp to work properly.
    collectterms = []
    gensols = []
    conjugate_roots = []  # used to prevent double-use of conjugate roots
    # Loop over roots in theorder provided by roots/rootof...
    for root in chareqroots:
        # but don't repoeat multiple roots.
        if root not in charroots:
            continue
        multiplicity = charroots.pop(root)
        for i in range(multiplicity):
            if chareq_is_complex:
                gensols.append(x**i * exp(root * x))
                collectterms = [(i, root, 0)] + collectterms
                continue
            reroot = re(root)
            imroot = im(root)
            if imroot.has(atan2) and reroot.has(atan2):
                # Remove this condition when re and im stop returning
                # circular atan2 usages.
                gensols.append(x**i * exp(root * x))
                collectterms = [(i, root, 0)] + collectterms
            else:
                if root in conjugate_roots:
                    collectterms = [(i, reroot, imroot)] + collectterms
                    continue
                if imroot == 0:
                    gensols.append(x**i * exp(reroot * x))
                    collectterms = [(i, reroot, 0)] + collectterms
                    continue
                conjugate_roots.append(conjugate(root))
                gensols.append(x**i * exp(reroot * x) * sin(abs(imroot) * x))
                gensols.append(x**i * exp(reroot * x) * cos(imroot * x))

                # This ordering is important
                collectterms = [(i, reroot, imroot)] + collectterms
    return gensols, collectterms
Exemplo n.º 24
0
def reduce_rational_inequalities(exprs, gen, assume=True, relational=True):
    """Reduce a system of rational inequalities with rational coefficients.

    Examples
    ========

    >>> from sympy import Poly, Symbol
    >>> from sympy.solvers.inequalities import reduce_rational_inequalities

    >>> x = Symbol('x', real=True)

    >>> reduce_rational_inequalities([[x**2 <= 0]], x)
    x == 0

    >>> reduce_rational_inequalities([[x + 2 > 0]], x)
    And(-2 < x, x < oo)
    >>> reduce_rational_inequalities([[(x + 2, ">")]], x)
    And(-2 < x, x < oo)
    >>> reduce_rational_inequalities([[x + 2]], x)
    x == -2
    """
    exact = True
    eqs = []

    for _exprs in exprs:
        _eqs = []

        for expr in _exprs:
            if isinstance(expr, tuple):
                expr, rel = expr
            else:
                if expr.is_Relational:
                    expr, rel = expr.lhs - expr.rhs, expr.rel_op
                else:
                    expr, rel = expr, '=='

            try:
                (numer, denom), opt = parallel_poly_from_expr(
                    expr.together().as_numer_denom(), gen)
            except PolynomialError:
                raise PolynomialError("only polynomials and "
                    "rational functions are supported in this context")

            if not opt.domain.is_Exact:
                numer, denom, exact = numer.to_exact(), denom.to_exact(), False

            domain = opt.domain.get_exact()

            if not (domain.is_ZZ or domain.is_QQ):
                raise NotImplementedError(
                    "inequality solving is not supported over %s" % opt.domain)

            _eqs.append(((numer, denom), rel))

        eqs.append(_eqs)

    solution = solve_rational_inequalities(eqs)

    if not exact:
        solution = solution.evalf()

    if not relational:
        return solution

    real = ask(Q.real(gen), assumptions=assume)

    if not real:
        result = And(solution.as_relational(re(gen)), Eq(im(gen), 0))
    else:
        result = solution.as_relational(gen)

    return result
Exemplo n.º 25
0
import sympy
from sympy.functions import im, re

import pystencils
from pystencils import AssignmentCollection
from pystencils.data_types import TypedSymbol, create_type

X, Y = pystencils.fields('x, y: complex64[2d]')
A, B = pystencils.fields('a, b: float32[2d]')
S1, S2, T = sympy.symbols('S1, S2, T')

TEST_ASSIGNMENTS = [
    AssignmentCollection({X[0, 0]: 1j}),
    AssignmentCollection({
        S1: re(Y.center),
        S2: im(Y.center),
        X[0, 0]: 2j * S1 + S2
    }),
    AssignmentCollection({
        A.center: re(Y.center),
        B.center: im(Y.center),
    }),
    AssignmentCollection({
        Y.center: re(Y.center) + X.center + 2j,
    }),
    AssignmentCollection({
        T: 2 + 4j,
        Y.center: X.center / T,
    })
]
Exemplo n.º 26
0
def reduce_rational_inequalities(exprs, gen, assume=True, relational=True):
    """Reduce a system of rational inequalities with rational coefficients.

    Examples
    ========

    >>> from sympy import Poly, Symbol
    >>> from sympy.solvers.inequalities import reduce_rational_inequalities

    >>> x = Symbol('x', real=True)

    >>> reduce_rational_inequalities([[x**2 <= 0]], x)
    x == 0

    >>> reduce_rational_inequalities([[x + 2 > 0]], x)
    -2 < x
    """
    exact = True
    eqs = []

    for _exprs in exprs:
        _eqs = []

        for expr in _exprs:
            if isinstance(expr, tuple):
                expr, rel = expr
            else:
                if expr.is_Relational:
                    expr, rel = expr.lhs - expr.rhs, expr.rel_op
                else:
                    expr, rel = expr, '=='

            try:
                (numer, denom), opt = parallel_poly_from_expr(expr.together().as_numer_denom(), gen)
            except PolynomialError:
                raise PolynomialError("only polynomials and rational functions are supported in this context")

            if not opt.domain.is_Exact:
                numer, denom, exact = numer.to_exact(), denom.to_exact(), False

            domain = opt.domain.get_exact()

            if not (domain.is_ZZ or domain.is_QQ):
                raise NotImplementedError("inequality solving is not supported over %s" % opt.domain)

            _eqs.append(((numer, denom), rel))

        eqs.append(_eqs)

    solution = solve_rational_inequalities(eqs)

    if not exact:
        solution = solution.evalf()

    if not relational:
        return solution

    real = ask(Q.real(gen), assumptions=assume)

    if not real:
        result = And(solution.as_relational(re(gen)), Eq(im(gen), 0))
    else:
        result = solution.as_relational(gen)

    return result
Exemplo n.º 27
0
def test_complex():
    x, y = symbols('x,y')
    assert ask(Q.complex(x)) == None
    assert ask(Q.complex(x), Q.complex(x)) == True
    assert ask(Q.complex(x), Q.complex(y)) == None
    assert ask(Q.complex(x), ~Q.complex(x)) == False
    assert ask(Q.complex(x), Q.real(x)) == True
    assert ask(Q.complex(x), ~Q.real(x)) == None
    assert ask(Q.complex(x), Q.rational(x)) == True
    assert ask(Q.complex(x), Q.irrational(x)) == True
    assert ask(Q.complex(x), Q.positive(x)) == True
    assert ask(Q.complex(x), Q.imaginary(x)) == True

    # a+b
    assert ask(Q.complex(x + 1), Q.complex(x)) == True
    assert ask(Q.complex(x + 1), Q.real(x)) == True
    assert ask(Q.complex(x + 1), Q.rational(x)) == True
    assert ask(Q.complex(x + 1), Q.irrational(x)) == True
    assert ask(Q.complex(x + 1), Q.imaginary(x)) == True
    assert ask(Q.complex(x + 1), Q.integer(x)) == True
    assert ask(Q.complex(x + 1), Q.even(x)) == True
    assert ask(Q.complex(x + 1), Q.odd(x)) == True
    assert ask(Q.complex(x + y), Q.complex(x) & Q.complex(y)) == True
    assert ask(Q.complex(x + y), Q.real(x) & Q.imaginary(y)) == True

    # a*x +b
    assert ask(Q.complex(2 * x + 1), Q.complex(x)) == True
    assert ask(Q.complex(2 * x + 1), Q.real(x)) == True
    assert ask(Q.complex(2 * x + 1), Q.positive(x)) == True
    assert ask(Q.complex(2 * x + 1), Q.rational(x)) == True
    assert ask(Q.complex(2 * x + 1), Q.irrational(x)) == True
    assert ask(Q.complex(2 * x + 1), Q.imaginary(x)) == True
    assert ask(Q.complex(2 * x + 1), Q.integer(x)) == True
    assert ask(Q.complex(2 * x + 1), Q.even(x)) == True
    assert ask(Q.complex(2 * x + 1), Q.odd(x)) == True

    # x**2
    assert ask(Q.complex(x**2), Q.complex(x)) == True
    assert ask(Q.complex(x**2), Q.real(x)) == True
    assert ask(Q.complex(x**2), Q.positive(x)) == True
    assert ask(Q.complex(x**2), Q.rational(x)) == True
    assert ask(Q.complex(x**2), Q.irrational(x)) == True
    assert ask(Q.complex(x**2), Q.imaginary(x)) == True
    assert ask(Q.complex(x**2), Q.integer(x)) == True
    assert ask(Q.complex(x**2), Q.even(x)) == True
    assert ask(Q.complex(x**2), Q.odd(x)) == True

    # 2**x
    assert ask(Q.complex(2**x), Q.complex(x)) == True
    assert ask(Q.complex(2**x), Q.real(x)) == True
    assert ask(Q.complex(2**x), Q.positive(x)) == True
    assert ask(Q.complex(2**x), Q.rational(x)) == True
    assert ask(Q.complex(2**x), Q.irrational(x)) == True
    assert ask(Q.complex(2**x), Q.imaginary(x)) == True
    assert ask(Q.complex(2**x), Q.integer(x)) == True
    assert ask(Q.complex(2**x), Q.even(x)) == True
    assert ask(Q.complex(2**x), Q.odd(x)) == True
    assert ask(Q.complex(x**y), Q.complex(x) & Q.complex(y)) == True

    # trigonometric expressions
    assert ask(Q.complex(sin(x))) == True
    assert ask(Q.complex(sin(2 * x + 1))) == True
    assert ask(Q.complex(cos(x))) == True
    assert ask(Q.complex(cos(2 * x + 1))) == True

    # exponential
    assert ask(Q.complex(exp(x))) == True
    assert ask(Q.complex(exp(x))) == True

    # Q.complexes
    assert ask(Q.complex(Abs(x))) == True
    assert ask(Q.complex(re(x))) == True
    assert ask(Q.complex(im(x))) == True
Exemplo n.º 28
0
def test_complex():
    x, y = symbols('xy')
    assert ask(x, Q.complex) == None
    assert ask(x, Q.complex, Assume(x, Q.complex)) == True
    assert ask(x, Q.complex, Assume(y, Q.complex)) == None
    assert ask(x, Q.complex, Assume(x, Q.complex, False)) == False
    assert ask(x, Q.complex, Assume(x, Q.real)) == True
    assert ask(x, Q.complex, Assume(x, Q.real, False)) == None
    assert ask(x, Q.complex, Assume(x, Q.rational)) == True
    assert ask(x, Q.complex, Assume(x, Q.irrational)) == True
    assert ask(x, Q.complex, Assume(x, Q.positive)) == True
    assert ask(x, Q.complex, Assume(x, Q.imaginary)) == True

    # a+b
    assert ask(x+1, Q.complex, Assume(x, Q.complex)) == True
    assert ask(x+1, Q.complex, Assume(x, Q.real)) == True
    assert ask(x+1, Q.complex, Assume(x, Q.rational)) == True
    assert ask(x+1, Q.complex, Assume(x, Q.irrational)) == True
    assert ask(x+1, Q.complex, Assume(x, Q.imaginary)) == True
    assert ask(x+1, Q.complex, Assume(x, Q.integer))  == True
    assert ask(x+1, Q.complex, Assume(x, Q.even))  == True
    assert ask(x+1, Q.complex, Assume(x, Q.odd))  == True
    assert ask(x+y, Q.complex, Assume(x, Q.complex) & Assume(y, Q.complex)) == True
    assert ask(x+y, Q.complex, Assume(x, Q.real) & Assume(y, Q.imaginary)) == True

    # a*x +b
    assert ask(2*x+1, Q.complex, Assume(x, Q.complex)) == True
    assert ask(2*x+1, Q.complex, Assume(x, Q.real)) == True
    assert ask(2*x+1, Q.complex, Assume(x, Q.positive)) == True
    assert ask(2*x+1, Q.complex, Assume(x, Q.rational)) == True
    assert ask(2*x+1, Q.complex, Assume(x, Q.irrational)) == True
    assert ask(2*x+1, Q.complex, Assume(x, Q.imaginary)) == True
    assert ask(2*x+1, Q.complex, Assume(x, Q.integer))  == True
    assert ask(2*x+1, Q.complex, Assume(x, Q.even))  == True
    assert ask(2*x+1, Q.complex, Assume(x, Q.odd))  == True

    # x**2
    assert ask(x**2, Q.complex, Assume(x, Q.complex)) == True
    assert ask(x**2, Q.complex, Assume(x, Q.real)) == True
    assert ask(x**2, Q.complex, Assume(x, Q.positive)) == True
    assert ask(x**2, Q.complex, Assume(x, Q.rational)) == True
    assert ask(x**2, Q.complex, Assume(x, Q.irrational)) == True
    assert ask(x**2, Q.complex, Assume(x, Q.imaginary)) == True
    assert ask(x**2, Q.complex, Assume(x, Q.integer))  == True
    assert ask(x**2, Q.complex, Assume(x, Q.even))  == True
    assert ask(x**2, Q.complex, Assume(x, Q.odd))  == True

    # 2**x
    assert ask(2**x, Q.complex, Assume(x, Q.complex)) == True
    assert ask(2**x, Q.complex, Assume(x, Q.real)) == True
    assert ask(2**x, Q.complex, Assume(x, Q.positive)) == True
    assert ask(2**x, Q.complex, Assume(x, Q.rational)) == True
    assert ask(2**x, Q.complex, Assume(x, Q.irrational)) == True
    assert ask(2**x, Q.complex, Assume(x, Q.imaginary)) == True
    assert ask(2**x, Q.complex, Assume(x, Q.integer))  == True
    assert ask(2**x, Q.complex, Assume(x, Q.even))  == True
    assert ask(2**x, Q.complex, Assume(x, Q.odd))  == True
    assert ask(x**y, Q.complex, Assume(x, Q.complex) & \
                     Assume(y, Q.complex)) == True

    # trigonometric expressions
    assert ask(sin(x), Q.complex) == True
    assert ask(sin(2*x + 1), Q.complex) == True
    assert ask(cos(x), Q.complex) == True
    assert ask(cos(2*x+1), Q.complex) == True

    # exponential
    assert ask(exp(x), Q.complex) == True
    assert ask(exp(x), Q.complex) == True

    # Q.complexes
    assert ask(Abs(x), Q.complex) == True
    assert ask(re(x),  Q.complex) == True
    assert ask(im(x),  Q.complex) == True
Exemplo n.º 29
0
def _get_euler_characteristic_eq_sols(eq, func, match_obj):
    r"""
    Returns the solution of homogeneous part of the linear euler ODE and
    the list of roots of characteristic equation.

    The parameter ``match_obj`` is a dict of order:coeff terms, where order is the order
    of the derivative on each term, and coeff is the coefficient of that derivative.

    """
    x = func.args[0]
    f = func.func

    # First, set up characteristic equation.
    chareq, symbol = S.Zero, Dummy('x')

    for i in match_obj:
        if i >= 0:
            chareq += (match_obj[i] * diff(x**symbol, x, i) *
                       x**-symbol).expand()

    chareq = Poly(chareq, symbol)
    chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
    collectterms = []

    # A generator of constants
    constants = list(get_numbered_constants(eq, num=chareq.degree() * 2))
    constants.reverse()

    # Create a dict root: multiplicity or charroots
    charroots = defaultdict(int)
    for root in chareqroots:
        charroots[root] += 1
    gsol = S.Zero
    ln = log
    for root, multiplicity in charroots.items():
        for i in range(multiplicity):
            if isinstance(root, RootOf):
                gsol += (x**root) * constants.pop()
                if multiplicity != 1:
                    raise ValueError("Value should be 1")
                collectterms = [(0, root, 0)] + collectterms
            elif root.is_real:
                gsol += ln(x)**i * (x**root) * constants.pop()
                collectterms = [(i, root, 0)] + collectterms
            else:
                reroot = re(root)
                imroot = im(root)
                gsol += ln(x)**i * (
                    x**reroot) * (constants.pop() * sin(abs(imroot) * ln(x)) +
                                  constants.pop() * cos(imroot * ln(x)))
                collectterms = [(i, reroot, imroot)] + collectterms

    gsol = Eq(f(x), gsol)

    gensols = []
    # Keep track of when to use sin or cos for nonzero imroot
    for i, reroot, imroot in collectterms:
        if imroot == 0:
            gensols.append(ln(x)**i * x**reroot)
        else:
            sin_form = ln(x)**i * x**reroot * sin(abs(imroot) * ln(x))
            if sin_form in gensols:
                cos_form = ln(x)**i * x**reroot * cos(imroot * ln(x))
                gensols.append(cos_form)
            else:
                gensols.append(sin_form)
    return gsol, gensols
Exemplo n.º 30
0
def matrix_exp_jordan_form(A, t):
    r"""
    Matrix exponential $\exp(A*t)$ for the matrix *A* and scalar *t*.

    Explanation
    ===========

    Returns the Jordan form of the $\exp(A*t)$ along with the matrix $P$ such that:

    .. math::
        \exp(A*t) = P * expJ * P^{-1}

    Examples
    ========

    >>> from sympy import Matrix, Symbol
    >>> from sympy.solvers.ode.systems import matrix_exp, matrix_exp_jordan_form
    >>> t = Symbol('t')

    We will consider a 2x2 defective matrix. This shows that our method
    works even for defective matrices.

    >>> A = Matrix([[1, 1], [0, 1]])

    It can be observed that this function gives us the Jordan normal form
    and the required invertible matrix P.

    >>> P, expJ = matrix_exp_jordan_form(A, t)

    Here, it is shown that P and expJ returned by this function is correct
    as they satisfy the formula: P * expJ * P_inverse = exp(A*t).

    >>> P * expJ * P.inv() == matrix_exp(A, t)
    True

    Parameters
    ==========

    A : Matrix
        The matrix $A$ in the expression $\exp(A*t)$
    t : Symbol
        The independent variable

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Defective_matrix
    .. [2] https://en.wikipedia.org/wiki/Jordan_matrix
    .. [3] https://en.wikipedia.org/wiki/Jordan_normal_form

    """

    N, M = A.shape
    if N != M:
        raise ValueError('Needed square matrix but got shape (%s, %s)' %
                         (N, M))
    elif A.has(t):
        raise ValueError('Matrix A should not depend on t')

    def jordan_chains(A):
        '''Chains from Jordan normal form analogous to M.eigenvects().
        Returns a dict with eignevalues as keys like:
            {e1: [[v111,v112,...], [v121, v122,...]], e2:...}
        where vijk is the kth vector in the jth chain for eigenvalue i.
        '''
        P, blocks = A.jordan_cells()
        basis = [P[:, i] for i in range(P.shape[1])]
        n = 0
        chains = {}
        for b in blocks:
            eigval = b[0, 0]
            size = b.shape[0]
            if eigval not in chains:
                chains[eigval] = []
            chains[eigval].append(basis[n:n + size])
            n += size
        return chains

    eigenchains = jordan_chains(A)

    # Needed for consistency across Python versions:
    eigenchains_iter = sorted(eigenchains.items(), key=default_sort_key)
    isreal = not A.has(I)

    blocks = []
    vectors = []
    seen_conjugate = set()
    for e, chains in eigenchains_iter:
        for chain in chains:
            n = len(chain)
            if isreal and e != e.conjugate() and e.conjugate() in eigenchains:
                if e in seen_conjugate:
                    continue
                seen_conjugate.add(e.conjugate())
                exprt = exp(re(e) * t)
                imrt = im(e) * t
                imblock = Matrix([[cos(imrt), sin(imrt)],
                                  [-sin(imrt), cos(imrt)]])
                expJblock2 = Matrix(
                    n, n, lambda i, j: imblock * t**(j - i) / factorial(j - i)
                    if j >= i else zeros(2, 2))
                expJblock = Matrix(
                    2 * n, 2 * n,
                    lambda i, j: expJblock2[i // 2, j // 2][i % 2, j % 2])

                blocks.append(exprt * expJblock)
                for i in range(n):
                    vectors.append(re(chain[i]))
                    vectors.append(im(chain[i]))
            else:
                vectors.extend(chain)
                fun = lambda i, j: t**(j - i) / factorial(j - i
                                                          ) if j >= i else 0
                expJblock = Matrix(n, n, fun)
                blocks.append(exp(e * t) * expJblock)

    expJ = Matrix.diag(*blocks)
    P = Matrix(N, N, lambda i, j: vectors[j][i])

    return P, expJ
Exemplo n.º 31
0
def test_tensorflow_complexes():
    assert tensorflow_code(re(x)) == "tensorflow.math.real(x)"
    assert tensorflow_code(im(x)) == "tensorflow.math.imag(x)"
    assert tensorflow_code(arg(x)) == "tensorflow.math.angle(x)"
Exemplo n.º 32
0
def test_complex():
    x, y = symbols('x,y')
    assert ask(Q.complex(x)) == None
    assert ask(Q.complex(x), Q.complex(x)) == True
    assert ask(Q.complex(x), Q.complex(y)) == None
    assert ask(Q.complex(x), ~Q.complex(x)) == False
    assert ask(Q.complex(x), Q.real(x)) == True
    assert ask(Q.complex(x), ~Q.real(x)) == None
    assert ask(Q.complex(x), Q.rational(x)) == True
    assert ask(Q.complex(x), Q.irrational(x)) == True
    assert ask(Q.complex(x), Q.positive(x)) == True
    assert ask(Q.complex(x), Q.imaginary(x)) == True

    # a+b
    assert ask(Q.complex(x+1), Q.complex(x)) == True
    assert ask(Q.complex(x+1), Q.real(x)) == True
    assert ask(Q.complex(x+1), Q.rational(x)) == True
    assert ask(Q.complex(x+1), Q.irrational(x)) == True
    assert ask(Q.complex(x+1), Q.imaginary(x)) == True
    assert ask(Q.complex(x+1), Q.integer(x))  == True
    assert ask(Q.complex(x+1), Q.even(x))  == True
    assert ask(Q.complex(x+1), Q.odd(x))  == True
    assert ask(Q.complex(x+y), Q.complex(x) & Q.complex(y)) == True
    assert ask(Q.complex(x+y), Q.real(x) & Q.imaginary(y)) == True

    # a*x +b
    assert ask(Q.complex(2*x+1), Q.complex(x)) == True
    assert ask(Q.complex(2*x+1), Q.real(x)) == True
    assert ask(Q.complex(2*x+1), Q.positive(x)) == True
    assert ask(Q.complex(2*x+1), Q.rational(x)) == True
    assert ask(Q.complex(2*x+1), Q.irrational(x)) == True
    assert ask(Q.complex(2*x+1), Q.imaginary(x)) == True
    assert ask(Q.complex(2*x+1), Q.integer(x))  == True
    assert ask(Q.complex(2*x+1), Q.even(x))  == True
    assert ask(Q.complex(2*x+1), Q.odd(x))  == True

    # x**2
    assert ask(Q.complex(x**2), Q.complex(x)) == True
    assert ask(Q.complex(x**2), Q.real(x)) == True
    assert ask(Q.complex(x**2), Q.positive(x)) == True
    assert ask(Q.complex(x**2), Q.rational(x)) == True
    assert ask(Q.complex(x**2), Q.irrational(x)) == True
    assert ask(Q.complex(x**2), Q.imaginary(x)) == True
    assert ask(Q.complex(x**2), Q.integer(x))  == True
    assert ask(Q.complex(x**2), Q.even(x))  == True
    assert ask(Q.complex(x**2), Q.odd(x))  == True

    # 2**x
    assert ask(Q.complex(2**x), Q.complex(x)) == True
    assert ask(Q.complex(2**x), Q.real(x)) == True
    assert ask(Q.complex(2**x), Q.positive(x)) == True
    assert ask(Q.complex(2**x), Q.rational(x)) == True
    assert ask(Q.complex(2**x), Q.irrational(x)) == True
    assert ask(Q.complex(2**x), Q.imaginary(x)) == True
    assert ask(Q.complex(2**x), Q.integer(x))  == True
    assert ask(Q.complex(2**x), Q.even(x))  == True
    assert ask(Q.complex(2**x), Q.odd(x))  == True
    assert ask(Q.complex(x**y), Q.complex(x) & Q.complex(y)) == True

    # trigonometric expressions
    assert ask(Q.complex(sin(x))) == True
    assert ask(Q.complex(sin(2*x + 1))) == True
    assert ask(Q.complex(cos(x))) == True
    assert ask(Q.complex(cos(2*x+1))) == True

    # exponential
    assert ask(Q.complex(exp(x))) == True
    assert ask(Q.complex(exp(x))) == True

    # Q.complexes
    assert ask(Q.complex(Abs(x))) == True
    assert ask(Q.complex(re(x))) == True
    assert ask(Q.complex(im(x))) == True
Exemplo n.º 33
0
def roots_quintic(f):
    """
    Calculate exact roots of a solvable quintic
    """
    result = []
    coeff_5, coeff_4, p, q, r, s = f.all_coeffs()

    # Eqn must be of the form x^5 + px^3 + qx^2 + rx + s
    if coeff_4:
        return result

    if coeff_5 != 1:
        l = [p/coeff_5, q/coeff_5, r/coeff_5, s/coeff_5]
        if not all(coeff.is_Rational for coeff in l):
            return result
        f = Poly(f/coeff_5)
    quintic = PolyQuintic(f)

    # Eqn standardized. Algo for solving starts here
    if not f.is_irreducible:
        return result

    f20 = quintic.f20
    # Check if f20 has linear factors over domain Z
    if f20.is_irreducible:
        return result

    # Now, we know that f is solvable
    for _factor in f20.factor_list()[1]:
        if _factor[0].is_linear:
            theta = _factor[0].root(0)
            break
    d = discriminant(f)
    delta = sqrt(d)
    # zeta = a fifth root of unity
    zeta1, zeta2, zeta3, zeta4 = quintic.zeta
    T = quintic.T(theta, d)
    tol = S(1e-10)
    alpha = T[1] + T[2]*delta
    alpha_bar = T[1] - T[2]*delta
    beta = T[3] + T[4]*delta
    beta_bar = T[3] - T[4]*delta

    disc = alpha**2 - 4*beta
    disc_bar = alpha_bar**2 - 4*beta_bar

    l0 = quintic.l0(theta)

    l1 = _quintic_simplify((-alpha + sqrt(disc)) / S(2))
    l4 = _quintic_simplify((-alpha - sqrt(disc)) / S(2))

    l2 = _quintic_simplify((-alpha_bar + sqrt(disc_bar)) / S(2))
    l3 = _quintic_simplify((-alpha_bar - sqrt(disc_bar)) / S(2))

    order = quintic.order(theta, d)
    test = (order*delta.n()) - ( (l1.n() - l4.n())*(l2.n() - l3.n()) )
    # Comparing floats
    if not comp(test, 0, tol):
        l2, l3 = l3, l2

    # Now we have correct order of l's
    R1 = l0 + l1*zeta1 + l2*zeta2 + l3*zeta3 + l4*zeta4
    R2 = l0 + l3*zeta1 + l1*zeta2 + l4*zeta3 + l2*zeta4
    R3 = l0 + l2*zeta1 + l4*zeta2 + l1*zeta3 + l3*zeta4
    R4 = l0 + l4*zeta1 + l3*zeta2 + l2*zeta3 + l1*zeta4

    Res = [None, [None]*5, [None]*5, [None]*5, [None]*5]
    Res_n = [None, [None]*5, [None]*5, [None]*5, [None]*5]
    sol = Symbol('sol')

    # Simplifying improves performance a lot for exact expressions
    R1 = _quintic_simplify(R1)
    R2 = _quintic_simplify(R2)
    R3 = _quintic_simplify(R3)
    R4 = _quintic_simplify(R4)

    # Solve imported here. Causing problems if imported as 'solve'
    # and hence the changed name
    from sympy.solvers.solvers import solve as _solve
    a, b = symbols('a b', cls=Dummy)
    _sol = _solve( sol**5 - a - I*b, sol)
    for i in range(5):
        _sol[i] = factor(_sol[i])
    R1 = R1.as_real_imag()
    R2 = R2.as_real_imag()
    R3 = R3.as_real_imag()
    R4 = R4.as_real_imag()

    for i, currentroot in enumerate(_sol):
        Res[1][i] = _quintic_simplify(currentroot.subs({ a: R1[0], b: R1[1] }))
        Res[2][i] = _quintic_simplify(currentroot.subs({ a: R2[0], b: R2[1] }))
        Res[3][i] = _quintic_simplify(currentroot.subs({ a: R3[0], b: R3[1] }))
        Res[4][i] = _quintic_simplify(currentroot.subs({ a: R4[0], b: R4[1] }))

    for i in range(1, 5):
        for j in range(5):
            Res_n[i][j] = Res[i][j].n()
            Res[i][j] = _quintic_simplify(Res[i][j])
    r1 = Res[1][0]
    r1_n = Res_n[1][0]

    for i in range(5):
        if comp(im(r1_n*Res_n[4][i]), 0, tol):
            r4 = Res[4][i]
            break

    # Now we have various Res values. Each will be a list of five
    # values. We have to pick one r value from those five for each Res
    u, v = quintic.uv(theta, d)
    testplus = (u + v*delta*sqrt(5)).n()
    testminus = (u - v*delta*sqrt(5)).n()

    # Evaluated numbers suffixed with _n
    # We will use evaluated numbers for calculation. Much faster.
    r4_n = r4.n()
    r2 = r3 = None

    for i in range(5):
        r2temp_n = Res_n[2][i]
        for j in range(5):
            # Again storing away the exact number and using
            # evaluated numbers in computations
            r3temp_n = Res_n[3][j]
            if (comp((r1_n*r2temp_n**2 + r4_n*r3temp_n**2 - testplus).n(), 0, tol) and
                comp((r3temp_n*r1_n**2 + r2temp_n*r4_n**2 - testminus).n(), 0, tol)):
                r2 = Res[2][i]
                r3 = Res[3][j]
                break
        if r2:
            break

    # Now, we have r's so we can get roots
    x1 = (r1 + r2 + r3 + r4)/5
    x2 = (r1*zeta4 + r2*zeta3 + r3*zeta2 + r4*zeta1)/5
    x3 = (r1*zeta3 + r2*zeta1 + r3*zeta4 + r4*zeta2)/5
    x4 = (r1*zeta2 + r2*zeta4 + r3*zeta1 + r4*zeta3)/5
    x5 = (r1*zeta1 + r2*zeta2 + r3*zeta3 + r4*zeta4)/5
    result = [x1, x2, x3, x4, x5]

    # Now check if solutions are distinct

    saw = set()
    for r in result:
        r = r.n(2)
        if r in saw:
            # Roots were identical. Abort, return []
            # and fall back to usual solve
            return []
        saw.add(r)
    return result
Exemplo n.º 34
0
def test_torch_complexes():
    assert torch_code(re(x)) == "torch.real(x)"
    assert torch_code(im(x)) == "torch.imag(x)"
    assert torch_code(arg(x)) == "torch.angle(x)"