def exact_Kolmogorov_expression(n_dim, theta, Orders, Orders_out, const_, r=1): Thetas, Thetas_out = get_theta_parameters(theta.reshape((-1, )), Orders, Orders_out, n_dim) symbols_ = 'X0 ' for m in range(n_dim - 1): if m < n_dim - 2: symbols_ += 'X' + str(m + 1) + ' ' else: symbols_ += 'X' + str(m + 1) dims_ = symbols(symbols_) inner_funcs = [ MeijerG(theta=Thetas[k], order=Orders[k]) for k in range(n_dim) ] outer_funcs = MeijerG(theta=Thetas_out[0], order=Orders_out[0]) out_expr_ = 0 x = symbols('x') for v in range(n_dim): out_expr_ += sympify(str(re(inner_funcs[v].expression()))).subs( x, dims_[v]) out_expr_ = simplify( sympify(str(re(outer_funcs.expression()))).subs(x, out_expr_)) final_expr = simplify(sympify(str(const_ / (const_ + out_expr_)))) return final_expr, dims_
def Kolmogorov_expression(n_dim, Thetas, Orders, Thetas_out, Orders_out, r=1): symbols_ = 'X0 ' for m in range(n_dim - 1): if m < n_dim - 2: symbols_ += 'X' + str(m + 1) + ' ' else: symbols_ += 'X' + str(m + 1) dims_ = symbols(symbols_) inner_funcs = [ MeijerG(theta=Thetas[k], order=Orders[k]) for k in range(n_dim) ] outer_funcs = MeijerG(theta=Thetas_out[0], order=Orders_out[0]) out_expr_ = 0 x = symbols('x') for v in range(n_dim): out_expr_ += sympify(str(re(inner_funcs[v].approx_expression()))).subs( x, dims_[v]) out_expr_ = simplify( sympify(str(re(outer_funcs.expression()))).subs(x, out_expr_)) return out_expr_, dims_
def fixed_point(channel): """Calculates the fixed point of a 1-qubit channel""" rho = final_dens_matrix(channel) final_point = [fun.re((Xsym*rho).trace().expand()), fun.re((Ysym*rho).trace().expand()), fun.re((Zsym*rho).trace().expand())] final_point[0] -= x final_point[1] -= y final_point[2] -= z return solve(final_point)
def evaluate_Kolmogorov(out_expr, dims_, x_in): n_dim = len(dims_) val_expr = sympify(str(re(out_expr))).subs(dims_[0], x_in[0]) for k in range(n_dim - 1): val_expr = sympify(str(re(val_expr))).subs(dims_[k + 1], x_in[k + 1]) return val_expr.evalf()
def main(args): a, b = sp.symbols('a b') expr = (2 * I - a * b + 8)**2 expanded = sp.expand(expr) print expr print expanded print re(expr) print re(expanded) return 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
def polynomial_length(expr): '''Determines the size of a polynomial using the formula: L(P) = sum(coeffs(i)) for i in polynomial coefficients Args: Expr: A standard sympy expression Returns: i: an integer corresponding to the polynomial size ''' if is_numerical_equation(expr)[0]: return abs(re(N(expr))) if isinstance(expr, Mul) and any( isinstance(arg, Add) for arg in expr.args): return sum(polynomial_length(arg) for arg in expr.args) return sum(abs(re(N(coef))) for coef in Poly(expr).coeffs())
def convergence_statement(self): """ Return a condition on z under which the series converges. """ R = self.radius_of_convergence if R == 0: return False if R == oo: return True # The special functions and their approximations, page 44 e = self.eta z = self.argument c1 = And(re(e) < 0, abs(z) <= 1) c2 = And(0 <= re(e), re(e) < 1, abs(z) <= 1, Ne(z, 1)) c3 = And(re(e) >= 1, abs(z) < 1) return Or(c1, c2, c3)
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
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
def parse(self, s, depth=16): e = sympify(s) s = e.series(z, oo, depth + 1) logging.info(s) coeffs = [float(re(s.coeff(z, n))) for n in range(-depth, 1)] logging.info('coeffs: {}'.format(coeffs)) return lambda memory: sum(map(operator.mul, coeffs, list(memory) + [1]))
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
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
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
def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[2] x0 = arg.subs(x, 0) if x0 is S.NaN: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 is S.Zero: return S.One return super()._eval_as_leading_term(x, logx=logx, cdir=cdir)
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
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))"
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))"
def eval_one_dimension_(Meijer_G_func, dim_name, vals): evaluated = [ simplify( sympify(str(re(Meijer_G_func.approx_expression()))).subs( dim_name, vals[k])).evalf() for k in range(vals.shape[0]) ] evaluated = np.array(evaluated) return evaluated
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
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
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
def ik(self): chain = Chain().make() chain.transform_summary() theta1, theta2, theta3 = symbols('theta1:4') f = chain.c * Matrix([0, 0, 0, 1]) f = Matrix(f[:3]) solutions = solve(f - Matrix(TARGET), (theta1, theta2, theta3)) print('\n\nTarget:') print(TARGET) print('\n\nSolutions:') for sol in solutions: t1 = re(sol[0]) t2 = re(sol[1]) t3 = re(sol[2]) print('IK Angles: ' + str([t1, t2, t3])) r = chain.forward({'theta1': t1, 'theta2': t2, 'theta3': t3}) print('FK Points: ' + str(r)) print('')
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)
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
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
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
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
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
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)"
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
import pytest 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, }) ]
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
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
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
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
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
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
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)"
def get_exact_Kolmogorov_expression(self, theta): Thetas, Thetas_out = get_theta_parameters(theta.reshape( (-1, )), self.Orders_in, self.Orders_out, self.n_dim) Thetas_in_0, Thetas_out_0 = get_theta_parameters( self.theta_0.reshape((-1, )), self.Orders_in, self.Orders_out, self.n_dim) symbols_ = 'X0 ' for m in range(self.single_dim - 1): if m < self.single_dim - 2: symbols_ += 'X' + str(m + 1) + ' ' else: symbols_ += 'X' + str(m + 1) dims_ = symbols(symbols_) inner_funcs = [ MeijerG(theta=Thetas[k], order=self.Orders_in[k]) for k in range(self.n_dim) ] outer_funcs = MeijerG(theta=Thetas_out[0], order=self.Orders_out[0]) inner_fun_0 = [ MeijerG(theta=Thetas_in_0[k], order=self.Orders_in[k]) for k in range(self.n_dim) ] out_expr_ = 0 x = symbols('x') for v in range(self.n_dim): if v < self.single_dim: if v not in self.zero_locs: out_expr_ += sympify(str(re( inner_funcs[v].expression()))).subs(x, dims_[v]) else: if v not in self.zero_locs: dim_0 = self.dim_combins[self.single_dim + (v - self.single_dim)][0] dim_1 = self.dim_combins[self.single_dim + (v - self.single_dim)][1] out_expr_ += sympify(str(re( inner_funcs[v].expression()))).subs( x, dims_[dim_0] * dims_[dim_1]) out_expr_ = simplify( sympify(str(re(outer_funcs.expression()))).subs(x, out_expr_)) final_expr = simplify( sympify(str(self.init_scale / (self.init_scale + out_expr_)))) return final_expr, dims_
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