hash
stringlengths
64
64
content
stringlengths
0
1.51M
5e3e745ef74e45fa435367636717ba609fc1683b6ee89575291370df22044339
from sympy import (symbols, Symbol, sinh, diff, Function, Derivative, Matrix, Rational, S, I, Eq, sqrt, Mul, pi) from sympy.core.containers import Tuple from sympy.functions import exp, cos, sin, log, tan, Ci, Si, erf, erfi from sympy.matrices import dotprodsimp, NonSquareMatrixError from sympy.solvers.ode import dsolve from sympy.solvers.ode.ode import constant_renumber from sympy.solvers.ode.subscheck import checksysodesol from sympy.solvers.ode.systems import (_classify_linear_system, linear_ode_to_matrix, ODEOrderError, ODENonlinearError, _simpsol, _is_commutative_anti_derivative, linodesolve, canonical_odes, dsolve_system, _component_division, _eqs2dict, _dict2graph) from sympy.functions import airyai, airybi from sympy.integrals.integrals import Integral from sympy.simplify.ratsimp import ratsimp from sympy.testing.pytest import ON_TRAVIS, raises, slow, skip, XFAIL C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10 = symbols('C0:11') x = symbols('x') f = Function('f') g = Function('g') h = Function('h') def test_linear_ode_to_matrix(): f, g, h = symbols("f, g, h", cls=Function) t = Symbol("t") funcs = [f(t), g(t), h(t)] f1 = f(t).diff(t) g1 = g(t).diff(t) h1 = h(t).diff(t) f2 = f(t).diff(t, 2) g2 = g(t).diff(t, 2) h2 = h(t).diff(t, 2) eqs_1 = [Eq(f1, g(t)), Eq(g1, f(t))] sol_1 = ([Matrix([[1, 0], [0, 1]]), Matrix([[ 0, 1], [1, 0]])], Matrix([[0],[0]])) assert linear_ode_to_matrix(eqs_1, funcs[:-1], t, 1) == sol_1 eqs_2 = [Eq(f1, f(t) + 2*g(t)), Eq(g1, h(t)), Eq(h1, g(t) + h(t) + f(t))] sol_2 = ([Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), Matrix([[1, 2, 0], [ 0, 0, 1], [1, 1, 1]])], Matrix([[0], [0], [0]])) assert linear_ode_to_matrix(eqs_2, funcs, t, 1) == sol_2 eqs_3 = [Eq(2*f1 + 3*h1, f(t) + g(t)), Eq(4*h1 + 5*g1, f(t) + h(t)), Eq(5*f1 + 4*g1, g(t) + h(t))] sol_3 = ([Matrix([[2, 0, 3], [0, 5, 4], [5, 4, 0]]), Matrix([[1, 1, 0], [1, 0, 1], [0, 1, 1]])], Matrix([[0], [0], [0]])) assert linear_ode_to_matrix(eqs_3, funcs, t, 1) == sol_3 eqs_4 = [Eq(f2 + h(t), f1 + g(t)), Eq(2*h2 + g2 + g1 + g(t), 0), Eq(3*h1, 4)] sol_4 = ([Matrix([[1, 0, 0], [0, 1, 2], [0, 0, 0]]), Matrix([[1, 0, 0], [0, -1, 0], [0, 0, -3]]), Matrix([[0, 1, -1], [0, -1, 0], [0, 0, 0]])], Matrix([[0], [0], [4]])) assert linear_ode_to_matrix(eqs_4, funcs, t, 2) == sol_4 eqs_5 = [Eq(f2, g(t)), Eq(f1 + g1, f(t))] raises(ODEOrderError, lambda: linear_ode_to_matrix(eqs_5, funcs[:-1], t, 1)) eqs_6 = [Eq(f1, f(t)**2), Eq(g1, f(t) + g(t))] raises(ODENonlinearError, lambda: linear_ode_to_matrix(eqs_6, funcs[:-1], t, 1)) def test__classify_linear_system(): x, y, z, w = symbols('x, y, z, w', cls=Function) t, k, l = symbols('t k l') x1 = diff(x(t), t) y1 = diff(y(t), t) z1 = diff(z(t), t) w1 = diff(w(t), t) x2 = diff(x(t), t, t) y2 = diff(y(t), t, t) funcs = [x(t), y(t)] funcs_2 = funcs + [z(t), w(t)] eqs_1 = (5 * x1 + 12 * x(t) - 6 * (y(t)), (2 * y1 - 11 * t * x(t) + 3 * y(t) + t)) assert _classify_linear_system(eqs_1, funcs, t) is None eqs_2 = (5 * (x1**2) + 12 * x(t) - 6 * (y(t)), (2 * y1 - 11 * t * x(t) + 3 * y(t) + t)) sol2 = {'is_implicit': True, 'canon_eqs': [[Eq(Derivative(x(t), t), -sqrt(-12*x(t)/5 + 6*y(t)/5)), Eq(Derivative(y(t), t), 11*t*x(t)/2 - t/2 - 3*y(t)/2)], [Eq(Derivative(x(t), t), sqrt(-12*x(t)/5 + 6*y(t)/5)), Eq(Derivative(y(t), t), 11*t*x(t)/2 - t/2 - 3*y(t)/2)]]} assert _classify_linear_system(eqs_2, funcs, t) == sol2 eqs_2_1 = [Eq(Derivative(x(t), t), -sqrt(-12*x(t)/5 + 6*y(t)/5)), Eq(Derivative(y(t), t), 11*t*x(t)/2 - t/2 - 3*y(t)/2)] assert _classify_linear_system(eqs_2_1, funcs, t) is None eqs_2_2 = [Eq(Derivative(x(t), t), sqrt(-12*x(t)/5 + 6*y(t)/5)), Eq(Derivative(y(t), t), 11*t*x(t)/2 - t/2 - 3*y(t)/2)] assert _classify_linear_system(eqs_2_2, funcs, t) is None eqs_3 = (5 * x1 + 12 * x(t) - 6 * (y(t)), (2 * y1 - 11 * x(t) + 3 * y(t)), (5 * w1 + z(t)), (z1 + w(t))) answer_3 = {'no_of_equation': 4, 'eq': (12*x(t) - 6*y(t) + 5*Derivative(x(t), t), -11*x(t) + 3*y(t) + 2*Derivative(y(t), t), z(t) + 5*Derivative(w(t), t), w(t) + Derivative(z(t), t)), 'func': [x(t), y(t), z(t), w(t)], 'order': {x(t): 1, y(t): 1, z(t): 1, w(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [Rational(12, 5), Rational(-6, 5), 0, 0], [Rational(-11, 2), Rational(3, 2), 0, 0], [0, 0, 0, 1], [0, 0, Rational(1, 5), 0]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eqs_3, funcs_2, t) == answer_3 eqs_4 = (5 * x1 + 12 * x(t) - 6 * (y(t)), (2 * y1 - 11 * x(t) + 3 * y(t)), (z1 - w(t)), (w1 - z(t))) answer_4 = {'no_of_equation': 4, 'eq': (12 * x(t) - 6 * y(t) + 5 * Derivative(x(t), t), -11 * x(t) + 3 * y(t) + 2 * Derivative(y(t), t), -w(t) + Derivative(z(t), t), -z(t) + Derivative(w(t), t)), 'func': [x(t), y(t), z(t), w(t)], 'order': {x(t): 1, y(t): 1, z(t): 1, w(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [Rational(12, 5), Rational(-6, 5), 0, 0], [Rational(-11, 2), Rational(3, 2), 0, 0], [0, 0, 0, -1], [0, 0, -1, 0]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eqs_4, funcs_2, t) == answer_4 eqs_5 = (5*x1 + 12*x(t) - 6*(y(t)) + x2, (2*y1 - 11*x(t) + 3*y(t)), (z1 - w(t)), (w1 - z(t))) answer_5 = {'no_of_equation': 4, 'eq': (12*x(t) - 6*y(t) + 5*Derivative(x(t), t) + Derivative(x(t), (t, 2)), -11*x(t) + 3*y(t) + 2*Derivative(y(t), t), -w(t) + Derivative(z(t), t), -z(t) + Derivative(w(t), t)), 'func': [x(t), y(t), z(t), w(t)], 'order': {x(t): 2, y(t): 1, z(t): 1, w(t): 1}, 'is_linear': True, 'is_homogeneous': True, 'is_general': True, 'type_of_equation': 'type0', 'is_higher_order': True} assert _classify_linear_system(eqs_5, funcs_2, t) == answer_5 eqs_6 = (Eq(x1, 3*y(t) - 11*z(t)), Eq(y1, 7*z(t) - 3*x(t)), Eq(z1, 11*x(t) - 7*y(t))) answer_6 = {'no_of_equation': 3, 'eq': (Eq(Derivative(x(t), t), 3*y(t) - 11*z(t)), Eq(Derivative(y(t), t), -3*x(t) + 7*z(t)), Eq(Derivative(z(t), t), 11*x(t) - 7*y(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [ 0, -3, 11], [ 3, 0, -7], [-11, 7, 0]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eqs_6, funcs_2[:-1], t) == answer_6 eqs_7 = (Eq(x1, y(t)), Eq(y1, x(t))) answer_7 = {'no_of_equation': 2, 'eq': (Eq(Derivative(x(t), t), y(t)), Eq(Derivative(y(t), t), x(t))), 'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [ 0, -1], [-1, 0]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eqs_7, funcs, t) == answer_7 eqs_8 = (Eq(x1, 21*x(t)), Eq(y1, 17*x(t) + 3*y(t)), Eq(z1, 5*x(t) + 7*y(t) + 9*z(t))) answer_8 = {'no_of_equation': 3, 'eq': (Eq(Derivative(x(t), t), 21*x(t)), Eq(Derivative(y(t), t), 17*x(t) + 3*y(t)), Eq(Derivative(z(t), t), 5*x(t) + 7*y(t) + 9*z(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [-21, 0, 0], [-17, -3, 0], [ -5, -7, -9]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eqs_8, funcs_2[:-1], t) == answer_8 eqs_9 = (Eq(x1, 4*x(t) + 5*y(t) + 2*z(t)), Eq(y1, x(t) + 13*y(t) + 9*z(t)), Eq(z1, 32*x(t) + 41*y(t) + 11*z(t))) answer_9 = {'no_of_equation': 3, 'eq': (Eq(Derivative(x(t), t), 4*x(t) + 5*y(t) + 2*z(t)), Eq(Derivative(y(t), t), x(t) + 13*y(t) + 9*z(t)), Eq(Derivative(z(t), t), 32*x(t) + 41*y(t) + 11*z(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [ -4, -5, -2], [ -1, -13, -9], [-32, -41, -11]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eqs_9, funcs_2[:-1], t) == answer_9 eqs_10 = (Eq(3*x1, 4*5*(y(t) - z(t))), Eq(4*y1, 3*5*(z(t) - x(t))), Eq(5*z1, 3*4*(x(t) - y(t)))) answer_10 = {'no_of_equation': 3, 'eq': (Eq(3*Derivative(x(t), t), 20*y(t) - 20*z(t)), Eq(4*Derivative(y(t), t), -15*x(t) + 15*z(t)), Eq(5*Derivative(z(t), t), 12*x(t) - 12*y(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [ 0, Rational(-20, 3), Rational(20, 3)], [Rational(15, 4), 0, Rational(-15, 4)], [Rational(-12, 5), Rational(12, 5), 0]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eqs_10, funcs_2[:-1], t) == answer_10 eq11 = (Eq(x1, 3*y(t) - 11*z(t)), Eq(y1, 7*z(t) - 3*x(t)), Eq(z1, 11*x(t) - 7*y(t))) sol11 = {'no_of_equation': 3, 'eq': (Eq(Derivative(x(t), t), 3*y(t) - 11*z(t)), Eq(Derivative(y(t), t), -3*x(t) + 7*z(t)), Eq(Derivative(z(t), t), 11*x(t) - 7*y(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [ 0, -3, 11], [ 3, 0, -7], [-11, 7, 0]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eq11, funcs_2[:-1], t) == sol11 eq12 = (Eq(Derivative(x(t), t), y(t)), Eq(Derivative(y(t), t), x(t))) sol12 = {'no_of_equation': 2, 'eq': (Eq(Derivative(x(t), t), y(t)), Eq(Derivative(y(t), t), x(t))), 'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [0, -1], [-1, 0]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eq12, [x(t), y(t)], t) == sol12 eq13 = (Eq(Derivative(x(t), t), 21*x(t)), Eq(Derivative(y(t), t), 17*x(t) + 3*y(t)), Eq(Derivative(z(t), t), 5*x(t) + 7*y(t) + 9*z(t))) sol13 = {'no_of_equation': 3, 'eq': ( Eq(Derivative(x(t), t), 21 * x(t)), Eq(Derivative(y(t), t), 17 * x(t) + 3 * y(t)), Eq(Derivative(z(t), t), 5 * x(t) + 7 * y(t) + 9 * z(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [-21, 0, 0], [-17, -3, 0], [-5, -7, -9]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eq13, [x(t), y(t), z(t)], t) == sol13 eq14 = ( Eq(Derivative(x(t), t), 4*x(t) + 5*y(t) + 2*z(t)), Eq(Derivative(y(t), t), x(t) + 13*y(t) + 9*z(t)), Eq(Derivative(z(t), t), 32*x(t) + 41*y(t) + 11*z(t))) sol14 = {'no_of_equation': 3, 'eq': ( Eq(Derivative(x(t), t), 4 * x(t) + 5 * y(t) + 2 * z(t)), Eq(Derivative(y(t), t), x(t) + 13 * y(t) + 9 * z(t)), Eq(Derivative(z(t), t), 32 * x(t) + 41 * y(t) + 11 * z(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [-4, -5, -2], [-1, -13, -9], [-32, -41, -11]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eq14, [x(t), y(t), z(t)], t) == sol14 eq15 = (Eq(3*Derivative(x(t), t), 20*y(t) - 20*z(t)), Eq(4*Derivative(y(t), t), -15*x(t) + 15*z(t)), Eq(5*Derivative(z(t), t), 12*x(t) - 12*y(t))) sol15 = {'no_of_equation': 3, 'eq': ( Eq(3 * Derivative(x(t), t), 20 * y(t) - 20 * z(t)), Eq(4 * Derivative(y(t), t), -15 * x(t) + 15 * z(t)), Eq(5 * Derivative(z(t), t), 12 * x(t) - 12 * y(t))), 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': True, 'func_coeff': -Matrix([ [0, Rational(-20, 3), Rational(20, 3)], [Rational(15, 4), 0, Rational(-15, 4)], [Rational(-12, 5), Rational(12, 5), 0]]), 'type_of_equation': 'type1', 'is_general': True} assert _classify_linear_system(eq15, [x(t), y(t), z(t)], t) == sol15 # Constant coefficient homogeneous ODEs eq1 = (Eq(diff(x(t), t), x(t) + y(t) + 9), Eq(diff(y(t), t), 2*x(t) + 5*y(t) + 23)) sol1 = {'no_of_equation': 2, 'eq': (Eq(Derivative(x(t), t), x(t) + y(t) + 9), Eq(Derivative(y(t), t), 2*x(t) + 5*y(t) + 23)), 'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True, 'is_constant': True, 'is_homogeneous': False, 'is_general': True, 'func_coeff': -Matrix([[-1, -1], [-2, -5]]), 'rhs': Matrix([[ 9], [23]]), 'type_of_equation': 'type2'} assert _classify_linear_system(eq1, funcs, t) == sol1 # Non constant coefficient homogeneous ODEs eq1 = (Eq(diff(x(t), t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t), t), 2*x(t) + 5*t*y(t))) sol1 = {'no_of_equation': 2, 'eq': (Eq(Derivative(x(t), t), 5*t*x(t) + 2*y(t)), Eq(Derivative(y(t), t), 5*t*y(t) + 2*x(t))), 'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True, 'is_constant': False, 'is_homogeneous': True, 'func_coeff': -Matrix([ [-5*t, -2], [ -2, -5*t]]), 'commutative_antiderivative': Matrix([ [5*t**2/2, 2*t], [ 2*t, 5*t**2/2]]), 'type_of_equation': 'type3', 'is_general': True} assert _classify_linear_system(eq1, funcs, t) == sol1 # Non constant coefficient non-homogeneous ODEs eq1 = [Eq(x1, x(t) + t*y(t) + t), Eq(y1, t*x(t) + y(t))] sol1 = {'no_of_equation': 2, 'eq': [Eq(Derivative(x(t), t), t*y(t) + t + x(t)), Eq(Derivative(y(t), t), t*x(t) + y(t))], 'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True, 'is_constant': False, 'is_homogeneous': False, 'is_general': True, 'func_coeff': -Matrix([ [-1, -t], [-t, -1]]), 'commutative_antiderivative': Matrix([ [ t, t**2/2], [t**2/2, t]]), 'rhs': Matrix([ [t], [0]]), 'type_of_equation': 'type4'} assert _classify_linear_system(eq1, funcs, t) == sol1 eq2 = [Eq(x1, t*x(t) + t*y(t) + t), Eq(y1, t*x(t) + t*y(t) + cos(t))] sol2 = {'no_of_equation': 2, 'eq': [Eq(Derivative(x(t), t), t*x(t) + t*y(t) + t), Eq(Derivative(y(t), t), t*x(t) + t*y(t) + cos(t))], 'func': [x(t), y(t)], 'order': {x(t): 1, y(t): 1}, 'is_linear': True, 'is_homogeneous': False, 'is_general': True, 'rhs': Matrix([ [ t], [cos(t)]]), 'func_coeff': Matrix([ [t, t], [t, t]]), 'is_constant': False, 'type_of_equation': 'type4', 'commutative_antiderivative': Matrix([ [t**2/2, t**2/2], [t**2/2, t**2/2]])} assert _classify_linear_system(eq2, funcs, t) == sol2 eq3 = [Eq(x1, t*(x(t) + y(t) + z(t) + 1)), Eq(y1, t*(x(t) + y(t) + z(t))), Eq(z1, t*(x(t) + y(t) + z(t)))] sol3 = {'no_of_equation': 3, 'eq': [Eq(Derivative(x(t), t), t*(x(t) + y(t) + z(t) + 1)), Eq(Derivative(y(t), t), t*(x(t) + y(t) + z(t))), Eq(Derivative(z(t), t), t*(x(t) + y(t) + z(t)))], 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': False, 'is_homogeneous': False, 'is_general': True, 'func_coeff': -Matrix([ [-t, -t, -t], [-t, -t, -t], [-t, -t, -t]]), 'commutative_antiderivative': Matrix([ [t**2/2, t**2/2, t**2/2], [t**2/2, t**2/2, t**2/2], [t**2/2, t**2/2, t**2/2]]), 'rhs': Matrix([ [t], [0], [0]]), 'type_of_equation': 'type4'} assert _classify_linear_system(eq3, funcs_2[:-1], t) == sol3 eq4 = [Eq(x1, x(t) + y(t) + t*z(t) + 1), Eq(y1, x(t) + t*y(t) + z(t) + 10), Eq(z1, t*x(t) + y(t) + z(t) + t)] sol4 = {'no_of_equation': 3, 'eq': [Eq(Derivative(x(t), t), t*z(t) + x(t) + y(t) + 1), Eq(Derivative(y(t), t), t*y(t) + x(t) + z(t) + 10), Eq(Derivative(z(t), t), t*x(t) + t + y(t) + z(t))], 'func': [x(t), y(t), z(t)], 'order': {x(t): 1, y(t): 1, z(t): 1}, 'is_linear': True, 'is_constant': False, 'is_homogeneous': False, 'is_general': True, 'func_coeff': -Matrix([ [-1, -1, -t], [-1, -t, -1], [-t, -1, -1]]), 'commutative_antiderivative': Matrix([ [ t, t, t**2/2], [ t, t**2/2, t], [t**2/2, t, t]]), 'rhs': Matrix([ [ 1], [10], [ t]]), 'type_of_equation': 'type4'} assert _classify_linear_system(eq4, funcs_2[:-1], t) == sol4 sum_terms = t*(x(t) + y(t) + z(t) + w(t)) eq5 = [Eq(x1, sum_terms), Eq(y1, sum_terms), Eq(z1, sum_terms + 1), Eq(w1, sum_terms)] sol5 = {'no_of_equation': 4, 'eq': [Eq(Derivative(x(t), t), t*(w(t) + x(t) + y(t) + z(t))), Eq(Derivative(y(t), t), t*(w(t) + x(t) + y(t) + z(t))), Eq(Derivative(z(t), t), t*(w(t) + x(t) + y(t) + z(t)) + 1), Eq(Derivative(w(t), t), t*(w(t) + x(t) + y(t) + z(t)))], 'func': [x(t), y(t), z(t), w(t)], 'order': {x(t): 1, y(t): 1, z(t): 1, w(t): 1}, 'is_linear': True, 'is_constant': False, 'is_homogeneous': False, 'is_general': True, 'func_coeff': -Matrix([ [-t, -t, -t, -t], [-t, -t, -t, -t], [-t, -t, -t, -t], [-t, -t, -t, -t]]), 'commutative_antiderivative': Matrix([ [t**2/2, t**2/2, t**2/2, t**2/2], [t**2/2, t**2/2, t**2/2, t**2/2], [t**2/2, t**2/2, t**2/2, t**2/2], [t**2/2, t**2/2, t**2/2, t**2/2]]), 'rhs': Matrix([ [0], [0], [1], [0]]), 'type_of_equation': 'type4'} assert _classify_linear_system(eq5, funcs_2, t) == sol5 # Second Order t_ = symbols("t_") eq1 = (Eq(9*x(t) + 7*y(t) + 4*Derivative(x(t), t) + Derivative(x(t), (t, 2)) + 3*Derivative(y(t), t), 11*exp(I*t)), Eq(3*x(t) + 12*y(t) + 5*Derivative(x(t), t) + 8*Derivative(y(t), t) + Derivative(y(t), (t, 2)), 2*exp(I*t))) sol1 = {'no_of_equation': 2, 'eq': (Eq(9*x(t) + 7*y(t) + 4*Derivative(x(t), t) + Derivative(x(t), (t, 2)) + 3*Derivative(y(t), t), 11*exp(I*t)), Eq(3*x(t) + 12*y(t) + 5*Derivative(x(t), t) + 8*Derivative(y(t), t) + Derivative(y(t), (t, 2)), 2*exp(I*t))), 'func': [x(t), y(t)], 'order': {x(t): 2, y(t): 2}, 'is_linear': True, 'is_homogeneous': False, 'is_general': True, 'rhs': Matrix([ [11*exp(I*t)], [ 2*exp(I*t)]]), 'type_of_equation': 'type0', 'is_second_order': True, 'is_higher_order': True} assert _classify_linear_system(eq1, funcs, t) == sol1 eq2 = (Eq((4*t**2 + 7*t + 1)**2*Derivative(x(t), (t, 2)), 5*x(t) + 35*y(t)), Eq((4*t**2 + 7*t + 1)**2*Derivative(y(t), (t, 2)), x(t) + 9*y(t))) sol2 = {'no_of_equation': 2, 'eq': (Eq((4*t**2 + 7*t + 1)**2*Derivative(x(t), (t, 2)), 5*x(t) + 35*y(t)), Eq((4*t**2 + 7*t + 1)**2*Derivative(y(t), (t, 2)), x(t) + 9*y(t))), 'func': [x(t), y(t)], 'order': {x(t): 2, y(t): 2}, 'is_linear': True, 'is_homogeneous': True, 'is_general': True, 'type_of_equation': 'type2', 'A0': Matrix([ [Rational(53, 4), 35], [ 1, Rational(69, 4)]]), 'g(t)': sqrt(4*t**2 + 7*t + 1), 'tau': sqrt(33)*log(t - sqrt(33)/8 + Rational(7, 8))/33 - sqrt(33)*log(t + sqrt(33)/8 + Rational(7, 8))/33, 'is_transformed': True, 't_': t_, 'is_second_order': True, 'is_higher_order': True} assert _classify_linear_system(eq2, funcs, t) == sol2 eq3 = ((t*Derivative(x(t), t) - x(t))*log(t) + (t*Derivative(y(t), t) - y(t))*exp(t) + Derivative(x(t), (t, 2)), t**2*(t*Derivative(x(t), t) - x(t)) + t*(t*Derivative(y(t), t) - y(t)) + Derivative(y(t), (t, 2))) sol3 = {'no_of_equation': 2, 'eq': ((t*Derivative(x(t), t) - x(t))*log(t) + (t*Derivative(y(t), t) - y(t))*exp(t) + Derivative(x(t), (t, 2)), t**2*(t*Derivative(x(t), t) - x(t)) + t*(t*Derivative(y(t), t) - y(t)) + Derivative(y(t), (t, 2))), 'func': [x(t), y(t)], 'order': {x(t): 2, y(t): 2}, 'is_linear': True, 'is_homogeneous': True, 'is_general': True, 'type_of_equation': 'type1', 'A1': Matrix([ [-t*log(t), -t*exp(t)], [ -t**3, -t**2]]), 'is_second_order': True, 'is_higher_order': True} assert _classify_linear_system(eq3, funcs, t) == sol3 eq4 = (Eq(x2, k*x(t) - l*y1), Eq(y2, l*x1 + k*y(t))) sol4 = {'no_of_equation': 2, 'eq': (Eq(Derivative(x(t), (t, 2)), k*x(t) - l*Derivative(y(t), t)), Eq(Derivative(y(t), (t, 2)), k*y(t) + l*Derivative(x(t), t))), 'func': [x(t), y(t)], 'order': {x(t): 2, y(t): 2}, 'is_linear': True, 'is_homogeneous': True, 'is_general': True, 'type_of_equation': 'type0', 'is_second_order': True, 'is_higher_order': True} assert _classify_linear_system(eq4, funcs, t) == sol4 # Multiple matchs f, g = symbols("f g", cls=Function) y, t_ = symbols("y t_") funcs = [f(t), g(t)] eq1 = [Eq(Derivative(f(t), t)**2 - 2*Derivative(f(t), t) + 1, 4), Eq(-y*f(t) + Derivative(g(t), t), 0)] sol1 = {'is_implicit': True, 'canon_eqs': [[Eq(Derivative(f(t), t), -1), Eq(Derivative(g(t), t), y*f(t))], [Eq(Derivative(f(t), t), 3), Eq(Derivative(g(t), t), y*f(t))]]} assert _classify_linear_system(eq1, funcs, t) == sol1 raises(ValueError, lambda: _classify_linear_system(eq1, funcs[:1], t)) eq2 = [Eq(Derivative(f(t), t), (2*f(t) + g(t) + 1)/t), Eq(Derivative(g(t), t), (f(t) + 2*g(t))/t)] sol2 = {'no_of_equation': 2, 'eq': [Eq(Derivative(f(t), t), (2*f(t) + g(t) + 1)/t), Eq(Derivative(g(t), t), (f(t) + 2*g(t))/t)], 'func': [f(t), g(t)], 'order': {f(t): 1, g(t): 1}, 'is_linear': True, 'is_homogeneous': False, 'is_general': True, 'rhs': Matrix([ [1], [0]]), 'func_coeff': Matrix([ [2, 1], [1, 2]]), 'is_constant': False, 'type_of_equation': 'type6', 't_': t_, 'tau': log(t), 'commutative_antiderivative': Matrix([ [2*log(t), log(t)], [ log(t), 2*log(t)]])} assert _classify_linear_system(eq2, funcs, t) == sol2 eq3 = [Eq(Derivative(f(t), t), (2*f(t) + g(t))/t), Eq(Derivative(g(t), t), (f(t) + 2*g(t))/t)] sol3 = {'no_of_equation': 2, 'eq': [Eq(Derivative(f(t), t), (2*f(t) + g(t))/t), Eq(Derivative(g(t), t), (f(t) + 2*g(t))/t)], 'func': [f(t), g(t)], 'order': {f(t): 1, g(t): 1}, 'is_linear': True, 'is_homogeneous': True, 'is_general': True, 'func_coeff': Matrix([ [2, 1], [1, 2]]), 'is_constant': False, 'type_of_equation': 'type5', 't_': t_, 'rhs': Matrix([ [0], [0]]), 'tau': log(t), 'commutative_antiderivative': Matrix([ [2*log(t), log(t)], [ log(t), 2*log(t)]])} assert _classify_linear_system(eq3, funcs, t) == sol3 def test_matrix_exp(): from sympy.matrices.dense import Matrix, eye, zeros from sympy.solvers.ode.systems import matrix_exp t = Symbol('t') for n in range(1, 6+1): assert matrix_exp(zeros(n), t) == eye(n) for n in range(1, 6+1): A = eye(n) expAt = exp(t) * eye(n) assert matrix_exp(A, t) == expAt for n in range(1, 6+1): A = Matrix(n, n, lambda i,j: i+1 if i==j else 0) expAt = Matrix(n, n, lambda i,j: exp((i+1)*t) if i==j else 0) assert matrix_exp(A, t) == expAt A = Matrix([[0, 1], [-1, 0]]) expAt = Matrix([[cos(t), sin(t)], [-sin(t), cos(t)]]) assert matrix_exp(A, t) == expAt A = Matrix([[2, -5], [2, -4]]) expAt = Matrix([ [3*exp(-t)*sin(t) + exp(-t)*cos(t), -5*exp(-t)*sin(t)], [2*exp(-t)*sin(t), -3*exp(-t)*sin(t) + exp(-t)*cos(t)] ]) assert matrix_exp(A, t) == expAt A = Matrix([[21, 17, 6], [-5, -1, -6], [4, 4, 16]]) # TO update this. # expAt = Matrix([ # [(8*t*exp(12*t) + 5*exp(12*t) - 1)*exp(4*t)/4, # (8*t*exp(12*t) + 5*exp(12*t) - 5)*exp(4*t)/4, # (exp(12*t) - 1)*exp(4*t)/2], # [(-8*t*exp(12*t) - exp(12*t) + 1)*exp(4*t)/4, # (-8*t*exp(12*t) - exp(12*t) + 5)*exp(4*t)/4, # (-exp(12*t) + 1)*exp(4*t)/2], # [4*t*exp(16*t), 4*t*exp(16*t), exp(16*t)]]) expAt = Matrix([ [2*t*exp(16*t) + 5*exp(16*t)/4 - exp(4*t)/4, 2*t*exp(16*t) + 5*exp(16*t)/4 - 5*exp(4*t)/4, exp(16*t)/2 - exp(4*t)/2], [ -2*t*exp(16*t) - exp(16*t)/4 + exp(4*t)/4, -2*t*exp(16*t) - exp(16*t)/4 + 5*exp(4*t)/4, -exp(16*t)/2 + exp(4*t)/2], [ 4*t*exp(16*t), 4*t*exp(16*t), exp(16*t)] ]) assert matrix_exp(A, t) == expAt A = Matrix([[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, -S(1)/8], [0, 0, S(1)/2, S(1)/2]]) expAt = Matrix([ [exp(t), t*exp(t), 4*t*exp(3*t/4) + 8*t*exp(t) + 48*exp(3*t/4) - 48*exp(t), -2*t*exp(3*t/4) - 2*t*exp(t) - 16*exp(3*t/4) + 16*exp(t)], [0, exp(t), -t*exp(3*t/4) - 8*exp(3*t/4) + 8*exp(t), t*exp(3*t/4)/2 + 2*exp(3*t/4) - 2*exp(t)], [0, 0, t*exp(3*t/4)/4 + exp(3*t/4), -t*exp(3*t/4)/8], [0, 0, t*exp(3*t/4)/2, -t*exp(3*t/4)/4 + exp(3*t/4)] ]) assert matrix_exp(A, t) == expAt A = Matrix([ [ 0, 1, 0, 0], [-1, 0, 0, 0], [ 0, 0, 0, 1], [ 0, 0, -1, 0]]) expAt = Matrix([ [ cos(t), sin(t), 0, 0], [-sin(t), cos(t), 0, 0], [ 0, 0, cos(t), sin(t)], [ 0, 0, -sin(t), cos(t)]]) assert matrix_exp(A, t) == expAt A = Matrix([ [ 0, 1, 1, 0], [-1, 0, 0, 1], [ 0, 0, 0, 1], [ 0, 0, -1, 0]]) expAt = Matrix([ [ cos(t), sin(t), t*cos(t), t*sin(t)], [-sin(t), cos(t), -t*sin(t), t*cos(t)], [ 0, 0, cos(t), sin(t)], [ 0, 0, -sin(t), cos(t)]]) assert matrix_exp(A, t) == expAt # This case is unacceptably slow right now but should be solvable... #a, b, c, d, e, f = symbols('a b c d e f') #A = Matrix([ #[-a, b, c, d], #[ a, -b, e, 0], #[ 0, 0, -c - e - f, 0], #[ 0, 0, f, -d]]) A = Matrix([[0, I], [I, 0]]) expAt = Matrix([ [exp(I*t)/2 + exp(-I*t)/2, exp(I*t)/2 - exp(-I*t)/2], [exp(I*t)/2 - exp(-I*t)/2, exp(I*t)/2 + exp(-I*t)/2]]) assert matrix_exp(A, t) == expAt # Testing Errors M = Matrix([[1, 2, 3], [4, 5, 6], [7, 7, 7]]) M1 = Matrix([[t, 1], [1, 1]]) raises(ValueError, lambda: matrix_exp(M[:, :2], t)) raises(ValueError, lambda: matrix_exp(M[:2, :], t)) raises(ValueError, lambda: matrix_exp(M1, t)) raises(ValueError, lambda: matrix_exp(M1[:1, :1], t)) def test_canonical_odes(): f, g, h = symbols('f g h', cls=Function) x = symbols('x') funcs = [f(x), g(x), h(x)] eqs1 = [Eq(f(x).diff(x, x), f(x) + 2*g(x)), Eq(g(x) + 1, g(x).diff(x) + f(x))] sol1 = [[Eq(Derivative(f(x), (x, 2)), f(x) + 2*g(x)), Eq(Derivative(g(x), x), -f(x) + g(x) + 1)]] assert canonical_odes(eqs1, funcs[:2], x) == sol1 eqs2 = [Eq(f(x).diff(x), h(x).diff(x) + f(x)), Eq(g(x).diff(x)**2, f(x) + h(x)), Eq(h(x).diff(x), f(x))] sol2 = [[Eq(Derivative(f(x), x), 2*f(x)), Eq(Derivative(g(x), x), -sqrt(f(x) + h(x))), Eq(Derivative(h(x), x), f(x))], [Eq(Derivative(f(x), x), 2*f(x)), Eq(Derivative(g(x), x), sqrt(f(x) + h(x))), Eq(Derivative(h(x), x), f(x))]] assert canonical_odes(eqs2, funcs, x) == sol2 def test_sysode_linear_neq_order1_type1(): f, g, x, y, h = symbols('f g x y h', cls=Function) a, b, c, t = symbols('a b c t') eqs1 = [Eq(Derivative(x(t), t), x(t)), Eq(Derivative(y(t), t), y(t))] sol1 = [Eq(x(t), C1*exp(t)), Eq(y(t), C2*exp(t))] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0]) eqs2 = [Eq(Derivative(x(t), t), 2*x(t)), Eq(Derivative(y(t), t), 3*y(t))] sol2 = [Eq(x(t), C1*exp(2*t)), Eq(y(t), C2*exp(3*t))] assert dsolve(eqs2) == sol2 assert checksysodesol(eqs2, sol2) == (True, [0, 0]) eqs3 = [Eq(Derivative(x(t), t), a*x(t)), Eq(Derivative(y(t), t), a*y(t))] sol3 = [Eq(x(t), C1*exp(a*t)), Eq(y(t), C2*exp(a*t))] assert dsolve(eqs3) == sol3 assert checksysodesol(eqs3, sol3) == (True, [0, 0]) # Regression test case for issue #15474 # https://github.com/sympy/sympy/issues/15474 eqs4 = [Eq(Derivative(x(t), t), a*x(t)), Eq(Derivative(y(t), t), b*y(t))] sol4 = [Eq(x(t), C1*exp(a*t)), Eq(y(t), C2*exp(b*t))] assert dsolve(eqs4) == sol4 assert checksysodesol(eqs4, sol4) == (True, [0, 0]) eqs5 = [Eq(Derivative(x(t), t), -y(t)), Eq(Derivative(y(t), t), x(t))] sol5 = [Eq(x(t), -C1*sin(t) - C2*cos(t)), Eq(y(t), C1*cos(t) - C2*sin(t))] assert dsolve(eqs5) == sol5 assert checksysodesol(eqs5, sol5) == (True, [0, 0]) eqs6 = [Eq(Derivative(x(t), t), -2*y(t)), Eq(Derivative(y(t), t), 2*x(t))] sol6 = [Eq(x(t), -C1*sin(2*t) - C2*cos(2*t)), Eq(y(t), C1*cos(2*t) - C2*sin(2*t))] assert dsolve(eqs6) == sol6 assert checksysodesol(eqs6, sol6) == (True, [0, 0]) eqs7 = [Eq(Derivative(x(t), t), I*y(t)), Eq(Derivative(y(t), t), I*x(t))] sol7 = [Eq(x(t), -C1*exp(-I*t) + C2*exp(I*t)), Eq(y(t), C1*exp(-I*t) + C2*exp(I*t))] assert dsolve(eqs7) == sol7 assert checksysodesol(eqs7, sol7) == (True, [0, 0]) eqs8 = [Eq(Derivative(x(t), t), -a*y(t)), Eq(Derivative(y(t), t), a*x(t))] sol8 = [Eq(x(t), -I*C1*exp(-I*a*t) + I*C2*exp(I*a*t)), Eq(y(t), C1*exp(-I*a*t) + C2*exp(I*a*t))] assert dsolve(eqs8) == sol8 assert checksysodesol(eqs8, sol8) == (True, [0, 0]) eqs9 = [Eq(Derivative(x(t), t), x(t) + y(t)), Eq(Derivative(y(t), t), x(t) - y(t))] sol9 = [Eq(x(t), C1*(1 - sqrt(2))*exp(-sqrt(2)*t) + C2*(1 + sqrt(2))*exp(sqrt(2)*t)), Eq(y(t), C1*exp(-sqrt(2)*t) + C2*exp(sqrt(2)*t))] assert dsolve(eqs9) == sol9 assert checksysodesol(eqs9, sol9) == (True, [0, 0]) eqs10 = [Eq(Derivative(x(t), t), x(t) + y(t)), Eq(Derivative(y(t), t), x(t) + y(t))] sol10 = [Eq(x(t), -C1 + C2*exp(2*t)), Eq(y(t), C1 + C2*exp(2*t))] assert dsolve(eqs10) == sol10 assert checksysodesol(eqs10, sol10) == (True, [0, 0]) eqs11 = [Eq(Derivative(x(t), t), 2*x(t) + y(t)), Eq(Derivative(y(t), t), -x(t) + 2*y(t))] sol11 = [Eq(x(t), C1*exp(2*t)*sin(t) + C2*exp(2*t)*cos(t)), Eq(y(t), C1*exp(2*t)*cos(t) - C2*exp(2*t)*sin(t))] assert dsolve(eqs11) == sol11 assert checksysodesol(eqs11, sol11) == (True, [0, 0]) eqs12 = [Eq(Derivative(x(t), t), x(t) + 2*y(t)), Eq(Derivative(y(t), t), 2*x(t) + y(t))] sol12 = [Eq(x(t), -C1*exp(-t) + C2*exp(3*t)), Eq(y(t), C1*exp(-t) + C2*exp(3*t))] assert dsolve(eqs12) == sol12 assert checksysodesol(eqs12, sol12) == (True, [0, 0]) eqs13 = [Eq(Derivative(x(t), t), 4*x(t) + y(t)), Eq(Derivative(y(t), t), -x(t) + 2*y(t))] sol13 = [Eq(x(t), C2*t*exp(3*t) + (C1 + C2)*exp(3*t)), Eq(y(t), -C1*exp(3*t) - C2*t*exp(3*t))] assert dsolve(eqs13) == sol13 assert checksysodesol(eqs13, sol13) == (True, [0, 0]) eqs14 = [Eq(Derivative(x(t), t), a*y(t)), Eq(Derivative(y(t), t), a*x(t))] sol14 = [Eq(x(t), -C1*exp(-a*t) + C2*exp(a*t)), Eq(y(t), C1*exp(-a*t) + C2*exp(a*t))] assert dsolve(eqs14) == sol14 assert checksysodesol(eqs14, sol14) == (True, [0, 0]) eqs15 = [Eq(Derivative(x(t), t), a*y(t)), Eq(Derivative(y(t), t), b*x(t))] sol15 = [Eq(x(t), -C1*a*exp(-t*sqrt(a*b))/sqrt(a*b) + C2*a*exp(t*sqrt(a*b))/sqrt(a*b)), Eq(y(t), C1*exp(-t*sqrt(a*b)) + C2*exp(t*sqrt(a*b)))] assert dsolve(eqs15) == sol15 assert checksysodesol(eqs15, sol15) == (True, [0, 0]) eqs16 = [Eq(Derivative(x(t), t), a*x(t) + b*y(t)), Eq(Derivative(y(t), t), c*x(t))] sol16 = [Eq(x(t), -2*C1*b*exp(t*(a + sqrt(a**2 + 4*b*c))/2)/(a - sqrt(a**2 + 4*b*c)) - 2*C2*b*exp(t*(a - sqrt(a**2 + 4*b*c))/2)/(a + sqrt(a**2 + 4*b*c))), Eq(y(t), C1*exp(t*(a + sqrt(a**2 + 4*b*c))/2) + C2*exp(t*(a - sqrt(a**2 + 4*b*c))/2))] assert dsolve(eqs16) == sol16 assert checksysodesol(eqs16, sol16) == (True, [0, 0]) # Regression test case for issue #18562 # https://github.com/sympy/sympy/issues/18562 eqs17 = [Eq(Derivative(x(t), t), a*y(t) + x(t)), Eq(Derivative(y(t), t), a*x(t) - y(t))] sol17 = [Eq(x(t), C1*a*exp(t*sqrt(a**2 + 1))/(sqrt(a**2 + 1) - 1) - C2*a*exp(-t*sqrt(a**2 + 1))/(sqrt(a**2 + 1) + 1)), Eq(y(t), C1*exp(t*sqrt(a**2 + 1)) + C2*exp(-t*sqrt(a**2 + 1)))] assert dsolve(eqs17) == sol17 assert checksysodesol(eqs17, sol17) == (True, [0, 0]) eqs18 = [Eq(Derivative(x(t), t), 0), Eq(Derivative(y(t), t), 0)] sol18 = [Eq(x(t), C1), Eq(y(t), C2)] assert dsolve(eqs18) == sol18 assert checksysodesol(eqs18, sol18) == (True, [0, 0]) eqs19 = [Eq(Derivative(x(t), t), 2*x(t) - y(t)), Eq(Derivative(y(t), t), x(t))] sol19 = [Eq(x(t), C2*t*exp(t) + (C1 + C2)*exp(t)), Eq(y(t), C1*exp(t) + C2*t*exp(t))] assert dsolve(eqs19) == sol19 assert checksysodesol(eqs19, sol19) == (True, [0, 0]) eqs20 = [Eq(Derivative(x(t), t), x(t)), Eq(Derivative(y(t), t), x(t) + y(t))] sol20 = [Eq(x(t), C1*exp(t)), Eq(y(t), C1*t*exp(t) + C2*exp(t))] assert dsolve(eqs20) == sol20 assert checksysodesol(eqs20, sol20) == (True, [0, 0]) eqs21 = [Eq(Derivative(x(t), t), 3*x(t)), Eq(Derivative(y(t), t), x(t) + y(t))] sol21 = [Eq(x(t), 2*C1*exp(3*t)), Eq(y(t), C1*exp(3*t) + C2*exp(t))] assert dsolve(eqs21) == sol21 assert checksysodesol(eqs21, sol21) == (True, [0, 0]) eqs22 = [Eq(Derivative(x(t), t), 3*x(t)), Eq(Derivative(y(t), t), y(t))] sol22 = [Eq(x(t), C1*exp(3*t)), Eq(y(t), C2*exp(t))] assert dsolve(eqs22) == sol22 assert checksysodesol(eqs22, sol22) == (True, [0, 0]) @slow def test_sysode_linear_neq_order1_type1_slow(): t = Symbol('t') Z0 = Function('Z0') Z1 = Function('Z1') Z2 = Function('Z2') Z3 = Function('Z3') k01, k10, k20, k21, k23, k30 = symbols('k01 k10 k20 k21 k23 k30') eqs1 = [Eq(Derivative(Z0(t), t), -k01*Z0(t) + k10*Z1(t) + k20*Z2(t) + k30*Z3(t)), Eq(Derivative(Z1(t), t), k01*Z0(t) - k10*Z1(t) + k21*Z2(t)), Eq(Derivative(Z2(t), t), (-k20 - k21 - k23)*Z2(t)), Eq(Derivative(Z3(t), t), k23*Z2(t) - k30*Z3(t))] sol1 = [Eq(Z0(t), C1*k10/k01 - C2*(k10 - k30)*exp(-k30*t)/(k01 + k10 - k30) - C3*(k10*(k20 + k21 - k30) - k20**2 - k20*(k21 + k23 - k30) + k23*k30)*exp(-t*(k20 + k21 + k23))/(k23*(-k01 - k10 + k20 + k21 + k23)) - C4*exp(-t*(k01 + k10))), Eq(Z1(t), C1 - C2*k01*exp(-k30*t)/(k01 + k10 - k30) + C3*(-k01*(k20 + k21 - k30) + k20*k21 + k21**2 + k21*(k23 - k30))*exp(-t*(k20 + k21 + k23))/(k23*(-k01 - k10 + k20 + k21 + k23)) + C4*exp(-t*(k01 + k10))), Eq(Z2(t), -C3*(k20 + k21 + k23 - k30)*exp(-t*(k20 + k21 + k23))/k23), Eq(Z3(t), C2*exp(-k30*t) + C3*exp(-t*(k20 + k21 + k23)))] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0, 0, 0]) x, y, z, u, v, w = symbols('x y z u v w', cls=Function) k2, k3 = symbols('k2 k3') a_b, a_c = symbols('a_b a_c', real=True) eqs2 = [Eq(Derivative(z(t), t), k2*y(t)), Eq(Derivative(x(t), t), k3*y(t)), Eq(Derivative(y(t), t), (-k2 - k3)*y(t))] sol2 = [Eq(z(t), C1 - C2*k2*exp(-t*(k2 + k3))/(k2 + k3)), Eq(x(t), -C2*k3*exp(-t*(k2 + k3))/(k2 + k3) + C3), Eq(y(t), C2*exp(-t*(k2 + k3)))] assert dsolve(eqs2) == sol2 assert checksysodesol(eqs2, sol2) == (True, [0, 0, 0]) eqs3 = [4*u(t) - v(t) - 2*w(t) + Derivative(u(t), t), 2*u(t) + v(t) - 2*w(t) + Derivative(v(t), t), 5*u(t) + v(t) - 3*w(t) + Derivative(w(t), t)] sol3 = [Eq(u(t), C3*exp(-2*t) + (C1/2 + sqrt(3)*C2/6)*cos(sqrt(3)*t) + sin(sqrt(3)*t)*(sqrt(3)*C1/6 + C2*Rational(-1, 2))), Eq(v(t), (C1/2 + sqrt(3)*C2/6)*cos(sqrt(3)*t) + sin(sqrt(3)*t)*(sqrt(3)*C1/6 + C2*Rational(-1, 2))), Eq(w(t), C1*cos(sqrt(3)*t) - C2*sin(sqrt(3)*t) + C3*exp(-2*t))] assert dsolve(eqs3) == sol3 assert checksysodesol(eqs3, sol3) == (True, [0, 0, 0]) eqs4 = [Eq(Derivative(x(t), t), w(t)*Rational(-2, 9) + 2*x(t) + y(t) + z(t)*Rational(-8, 9)), Eq(Derivative(y(t), t), w(t)*Rational(4, 9) + 2*y(t) + z(t)*Rational(16, 9)), Eq(Derivative(z(t), t), w(t)*Rational(-2, 9) + z(t)*Rational(37, 9)), Eq(Derivative(w(t), t), w(t)*Rational(44, 9) + z(t)*Rational(-4, 9))] sol4 = [Eq(x(t), C1*exp(2*t) + C2*t*exp(2*t)), Eq(y(t), C2*exp(2*t) + 2*C3*exp(4*t)), Eq(z(t), 2*C3*exp(4*t) + C4*exp(5*t)*Rational(-1, 4)), Eq(w(t), C3*exp(4*t) + C4*exp(5*t))] assert dsolve(eqs4) == sol4 assert checksysodesol(eqs4, sol4) == (True, [0, 0, 0, 0]) # Regression test case for issue #15574 # https://github.com/sympy/sympy/issues/15574 eq5 = [Eq(x(t).diff(t), x(t)), Eq(y(t).diff(t), y(t)), Eq(z(t).diff(t), z(t)), Eq(w(t).diff(t), w(t))] sol5 = [Eq(x(t), C1*exp(t)), Eq(y(t), C2*exp(t)), Eq(z(t), C3*exp(t)), Eq(w(t), C4*exp(t))] assert dsolve(eq5) == sol5 assert checksysodesol(eq5, sol5) == (True, [0, 0, 0, 0]) eqs6 = [Eq(Derivative(x(t), t), x(t) + y(t)), Eq(Derivative(y(t), t), y(t) + z(t)), Eq(Derivative(z(t), t), w(t)*Rational(-1, 8) + z(t)), Eq(Derivative(w(t), t), w(t)/2 + z(t)/2)] sol6 = [Eq(x(t), C1*exp(t) + C2*t*exp(t) + 4*C4*t*exp(t*Rational(3, 4)) + (4*C3 + 48*C4)*exp(t*Rational(3, 4))), Eq(y(t), C2*exp(t) - C4*t*exp(t*Rational(3, 4)) - (C3 + 8*C4)*exp(t*Rational(3, 4))), Eq(z(t), C4*t*exp(t*Rational(3, 4))/4 + (C3/4 + C4)*exp(t*Rational(3, 4))), Eq(w(t), C3*exp(t*Rational(3, 4))/2 + C4*t*exp(t*Rational(3, 4))/2)] assert dsolve(eqs6) == sol6 assert checksysodesol(eqs6, sol6) == (True, [0, 0, 0, 0]) # Regression test case for issue #15574 # https://github.com/sympy/sympy/issues/15574 eq7 = [Eq(Derivative(x(t), t), x(t)), Eq(Derivative(y(t), t), y(t)), Eq(Derivative(z(t), t), z(t)), Eq(Derivative(w(t), t), w(t)), Eq(Derivative(u(t), t), u(t))] sol7 = [Eq(x(t), C1*exp(t)), Eq(y(t), C2*exp(t)), Eq(z(t), C3*exp(t)), Eq(w(t), C4*exp(t)), Eq(u(t), C5*exp(t))] assert dsolve(eq7) == sol7 assert checksysodesol(eq7, sol7) == (True, [0, 0, 0, 0, 0]) eqs8 = [Eq(Derivative(x(t), t), 2*x(t) + y(t)), Eq(Derivative(y(t), t), 2*y(t)), Eq(Derivative(z(t), t), 4*z(t)), Eq(Derivative(w(t), t), u(t) + 5*w(t)), Eq(Derivative(u(t), t), 5*u(t))] sol8 = [Eq(x(t), C1*exp(2*t) + C2*t*exp(2*t)), Eq(y(t), C2*exp(2*t)), Eq(z(t), C3*exp(4*t)), Eq(w(t), C4*exp(5*t) + C5*t*exp(5*t)), Eq(u(t), C5*exp(5*t))] assert dsolve(eqs8) == sol8 assert checksysodesol(eqs8, sol8) == (True, [0, 0, 0, 0, 0]) # Regression test case for issue #15574 # https://github.com/sympy/sympy/issues/15574 eq9 = [Eq(Derivative(x(t), t), x(t)), Eq(Derivative(y(t), t), y(t)), Eq(Derivative(z(t), t), z(t))] sol9 = [Eq(x(t), C1*exp(t)), Eq(y(t), C2*exp(t)), Eq(z(t), C3*exp(t))] assert dsolve(eq9) == sol9 assert checksysodesol(eq9, sol9) == (True, [0, 0, 0]) # Regression test case for issue #15407 # https://github.com/sympy/sympy/issues/15407 eqs10 = [Eq(Derivative(x(t), t), (-a_b - a_c)*x(t)), Eq(Derivative(y(t), t), a_b*y(t)), Eq(Derivative(z(t), t), a_c*x(t))] sol10 = [Eq(x(t), -C1*(a_b + a_c)*exp(-t*(a_b + a_c))/a_c), Eq(y(t), C2*exp(a_b*t)), Eq(z(t), C1*exp(-t*(a_b + a_c)) + C3)] assert dsolve(eqs10) == sol10 assert checksysodesol(eqs10, sol10) == (True, [0, 0, 0]) # Regression test case for issue #14312 # https://github.com/sympy/sympy/issues/14312 eqs11 = [Eq(Derivative(x(t), t), k3*y(t)), Eq(Derivative(y(t), t), (-k2 - k3)*y(t)), Eq(Derivative(z(t), t), k2*y(t))] sol11 = [Eq(x(t), C1 + C2*k3*exp(-t*(k2 + k3))/k2), Eq(y(t), -C2*(k2 + k3)*exp(-t*(k2 + k3))/k2), Eq(z(t), C2*exp(-t*(k2 + k3)) + C3)] assert dsolve(eqs11) == sol11 assert checksysodesol(eqs11, sol11) == (True, [0, 0, 0]) # Regression test case for issue #14312 # https://github.com/sympy/sympy/issues/14312 eqs12 = [Eq(Derivative(z(t), t), k2*y(t)), Eq(Derivative(x(t), t), k3*y(t)), Eq(Derivative(y(t), t), (-k2 - k3)*y(t))] sol12 = [Eq(z(t), C1 - C2*k2*exp(-t*(k2 + k3))/(k2 + k3)), Eq(x(t), -C2*k3*exp(-t*(k2 + k3))/(k2 + k3) + C3), Eq(y(t), C2*exp(-t*(k2 + k3)))] assert dsolve(eqs12) == sol12 assert checksysodesol(eqs12, sol12) == (True, [0, 0, 0]) f, g, h = symbols('f, g, h', cls=Function) a, b, c = symbols('a, b, c') # Regression test case for issue #15474 # https://github.com/sympy/sympy/issues/15474 eqs13 = [Eq(Derivative(f(t), t), 2*f(t) + g(t)), Eq(Derivative(g(t), t), a*f(t))] sol13 = [Eq(f(t), C1*exp(t*(sqrt(a + 1) + 1))/(sqrt(a + 1) - 1) - C2*exp(-t*(sqrt(a + 1) - 1))/(sqrt(a + 1) + 1)), Eq(g(t), C1*exp(t*(sqrt(a + 1) + 1)) + C2*exp(-t*(sqrt(a + 1) - 1)))] assert dsolve(eqs13) == sol13 assert checksysodesol(eqs13, sol13) == (True, [0, 0]) eqs14 = [Eq(Derivative(f(t), t), 2*g(t) - 3*h(t)), Eq(Derivative(g(t), t), -2*f(t) + 4*h(t)), Eq(Derivative(h(t), t), 3*f(t) - 4*g(t))] sol14 = [Eq(f(t), 2*C1 - sin(sqrt(29)*t)*(sqrt(29)*C2*Rational(3, 25) + C3*Rational(-8, 25)) - cos(sqrt(29)*t)*(C2*Rational(8, 25) + sqrt(29)*C3*Rational(3, 25))), Eq(g(t), C1*Rational(3, 2) + sin(sqrt(29)*t)*(sqrt(29)*C2*Rational(4, 25) + C3*Rational(6, 25)) - cos(sqrt(29)*t)*(C2*Rational(6, 25) + sqrt(29)*C3*Rational(-4, 25))), Eq(h(t), C1 + C2*cos(sqrt(29)*t) - C3*sin(sqrt(29)*t))] assert dsolve(eqs14) == sol14 assert checksysodesol(eqs14, sol14) == (True, [0, 0, 0]) eqs15 = [Eq(2*Derivative(f(t), t), 12*g(t) - 12*h(t)), Eq(3*Derivative(g(t), t), -8*f(t) + 8*h(t)), Eq(4*Derivative(h(t), t), 6*f(t) - 6*g(t))] sol15 = [Eq(f(t), C1 - sin(sqrt(29)*t)*(sqrt(29)*C2*Rational(6, 13) + C3*Rational(-16, 13)) - cos(sqrt(29)*t)*(C2*Rational(16, 13) + sqrt(29)*C3*Rational(6, 13))), Eq(g(t), C1 + sin(sqrt(29)*t)*(sqrt(29)*C2*Rational(8, 39) + C3*Rational(16, 13)) - cos(sqrt(29)*t)*(C2*Rational(16, 13) + sqrt(29)*C3*Rational(-8, 39))), Eq(h(t), C1 + C2*cos(sqrt(29)*t) - C3*sin(sqrt(29)*t))] assert dsolve(eqs15) == sol15 assert checksysodesol(eqs15, sol15) == (True, [0, 0, 0]) eq16 = (Eq(diff(x(t), t), 21*x(t)), Eq(diff(y(t), t), 17*x(t) + 3*y(t)), Eq(diff(z(t), t), 5*x(t) + 7*y(t) + 9*z(t))) sol16 = [Eq(x(t), 216*C1*exp(21*t)/209), Eq(y(t), 204*C1*exp(21*t)/209 - 6*C2*exp(3*t)/7), Eq(z(t), C1*exp(21*t) + C2*exp(3*t) + C3*exp(9*t))] assert dsolve(eq16) == sol16 assert checksysodesol(eq16, sol16) == (True, [0, 0, 0]) eqs17 = [Eq(Derivative(x(t), t), 3*y(t) - 11*z(t)), Eq(Derivative(y(t), t), -3*x(t) + 7*z(t)), Eq(Derivative(z(t), t), 11*x(t) - 7*y(t))] sol17 = [Eq(x(t), C1*Rational(7, 3) - sin(sqrt(179)*t)*(sqrt(179)*C2*Rational(11, 170) + C3*Rational(-21, 170)) - cos(sqrt(179)*t)*(C2*Rational(21, 170) + sqrt(179)*C3*Rational(11, 170))), Eq(y(t), C1*Rational(11, 3) + sin(sqrt(179)*t)*(sqrt(179)*C2*Rational(7, 170) + C3*Rational(33, 170)) - cos(sqrt(179)*t)*(C2*Rational(33, 170) + sqrt(179)*C3*Rational(-7, 170))), Eq(z(t), C1 + C2*cos(sqrt(179)*t) - C3*sin(sqrt(179)*t))] assert dsolve(eqs17) == sol17 assert checksysodesol(eqs17, sol17) == (True, [0, 0, 0]) eqs18 = [Eq(3*Derivative(x(t), t), 20*y(t) - 20*z(t)), Eq(4*Derivative(y(t), t), -15*x(t) + 15*z(t)), Eq(5*Derivative(z(t), t), 12*x(t) - 12*y(t))] sol18 = [Eq(x(t), C1 - sin(5*sqrt(2)*t)*(sqrt(2)*C2*Rational(4, 3) - C3) - cos(5*sqrt(2)*t)*(C2 + sqrt(2)*C3*Rational(4, 3))), Eq(y(t), C1 + sin(5*sqrt(2)*t)*(sqrt(2)*C2*Rational(3, 4) + C3) - cos(5*sqrt(2)*t)*(C2 + sqrt(2)*C3*Rational(-3, 4))), Eq(z(t), C1 + C2*cos(5*sqrt(2)*t) - C3*sin(5*sqrt(2)*t))] assert dsolve(eqs18) == sol18 assert checksysodesol(eqs18, sol18) == (True, [0, 0, 0]) eqs19 = [Eq(Derivative(x(t), t), 4*x(t) - z(t)), Eq(Derivative(y(t), t), 2*x(t) + 2*y(t) - z(t)), Eq(Derivative(z(t), t), 3*x(t) + y(t))] sol19 = [Eq(x(t), C2*t**2*exp(2*t)/2 + t*(2*C2 + C3)*exp(2*t) + (C1 + C2 + 2*C3)*exp(2*t)), Eq(y(t), C2*t**2*exp(2*t)/2 + t*(2*C2 + C3)*exp(2*t) + (C1 + 2*C3)*exp(2*t)), Eq(z(t), C2*t**2*exp(2*t) + t*(3*C2 + 2*C3)*exp(2*t) + (2*C1 + 3*C3)*exp(2*t))] assert dsolve(eqs19) == sol19 assert checksysodesol(eqs19, sol19) == (True, [0, 0, 0]) eqs20 = [Eq(Derivative(x(t), t), 4*x(t) - y(t) - 2*z(t)), Eq(Derivative(y(t), t), 2*x(t) + y(t) - 2*z(t)), Eq(Derivative(z(t), t), 5*x(t) - 3*z(t))] sol20 = [Eq(x(t), C1*exp(2*t) - sin(t)*(C2*Rational(3, 5) + C3/5) - cos(t)*(C2/5 + C3*Rational(-3, 5))), Eq(y(t), -sin(t)*(C2*Rational(3, 5) + C3/5) - cos(t)*(C2/5 + C3*Rational(-3, 5))), Eq(z(t), C1*exp(2*t) - C2*sin(t) + C3*cos(t))] assert dsolve(eqs20) == sol20 assert checksysodesol(eqs20, sol20) == (True, [0, 0, 0]) eq21 = (Eq(diff(x(t), t), 9*y(t)), Eq(diff(y(t), t), 12*x(t))) sol21 = [Eq(x(t), -sqrt(3)*C1*exp(-6*sqrt(3)*t)/2 + sqrt(3)*C2*exp(6*sqrt(3)*t)/2), Eq(y(t), C1*exp(-6*sqrt(3)*t) + C2*exp(6*sqrt(3)*t))] assert dsolve(eq21) == sol21 assert checksysodesol(eq21, sol21) == (True, [0, 0]) eqs22 = [Eq(Derivative(x(t), t), 2*x(t) + 4*y(t)), Eq(Derivative(y(t), t), 12*x(t) + 41*y(t))] sol22 = [Eq(x(t), C1*(39 - sqrt(1713))*exp(t*(sqrt(1713) + 43)/2)*Rational(-1, 24) + C2*(39 + sqrt(1713))*exp(t*(43 - sqrt(1713))/2)*Rational(-1, 24)), Eq(y(t), C1*exp(t*(sqrt(1713) + 43)/2) + C2*exp(t*(43 - sqrt(1713))/2))] assert dsolve(eqs22) == sol22 assert checksysodesol(eqs22, sol22) == (True, [0, 0]) eqs23 = [Eq(Derivative(x(t), t), x(t) + y(t)), Eq(Derivative(y(t), t), -2*x(t) + 2*y(t))] sol23 = [Eq(x(t), (C1/4 + sqrt(7)*C2/4)*cos(sqrt(7)*t/2)*exp(t*Rational(3, 2)) + sin(sqrt(7)*t/2)*(sqrt(7)*C1/4 + C2*Rational(-1, 4))*exp(t*Rational(3, 2))), Eq(y(t), C1*cos(sqrt(7)*t/2)*exp(t*Rational(3, 2)) - C2*sin(sqrt(7)*t/2)*exp(t*Rational(3, 2)))] assert dsolve(eqs23) == sol23 assert checksysodesol(eqs23, sol23) == (True, [0, 0]) # Regression test case for issue #15474 # https://github.com/sympy/sympy/issues/15474 a = Symbol("a", real=True) eq24 = [x(t).diff(t) - a*y(t), y(t).diff(t) + a*x(t)] sol24 = [Eq(x(t), C1*sin(a*t) + C2*cos(a*t)), Eq(y(t), C1*cos(a*t) - C2*sin(a*t))] assert dsolve(eq24) == sol24 assert checksysodesol(eq24, sol24) == (True, [0, 0]) # Regression test case for issue #19150 # https://github.com/sympy/sympy/issues/19150 eqs25 = [Eq(Derivative(f(t), t), 0), Eq(Derivative(g(t), t), (f(t) - 2*g(t) + x(t))/(b*c)), Eq(Derivative(x(t), t), (g(t) - 2*x(t) + y(t))/(b*c)), Eq(Derivative(y(t), t), (h(t) + x(t) - 2*y(t))/(b*c)), Eq(Derivative(h(t), t), 0)] sol25 = [Eq(f(t), -3*C1 + 4*C2), Eq(g(t), -2*C1 + 3*C2 - C3*exp(-2*t/(b*c)) + C4*exp(-t*(sqrt(2) + 2)/(b*c)) + C5*exp(-t*(2 - sqrt(2))/(b*c))), Eq(x(t), -C1 + 2*C2 - sqrt(2)*C4*exp(-t*(sqrt(2) + 2)/(b*c)) + sqrt(2)*C5*exp(-t*(2 - sqrt(2))/(b*c))), Eq(y(t), C2 + C3*exp(-2*t/(b*c)) + C4*exp(-t*(sqrt(2) + 2)/(b*c)) + C5*exp(-t*(2 - sqrt(2))/(b*c))), Eq(h(t), C1)] assert dsolve(eqs25) == sol25 assert checksysodesol(eqs25, sol25) == (True, [0, 0, 0, 0, 0]) eq26 = [Eq(Derivative(f(t), t), 2*f(t)), Eq(Derivative(g(t), t), 3*f(t) + 7*g(t))] sol26 = [Eq(f(t), -5*C1*exp(2*t)/3), Eq(g(t), C1*exp(2*t) + C2*exp(7*t))] assert dsolve(eq26) == sol26 assert checksysodesol(eq26, sol26) == (True, [0, 0]) eq27 = [Eq(Derivative(f(t), t), -9*I*f(t) - 4*g(t)), Eq(Derivative(g(t), t), -4*I*g(t))] sol27 = [Eq(f(t), 4*I*C1*exp(-4*I*t)/5 + C2*exp(-9*I*t)), Eq(g(t), C1*exp(-4*I*t))] assert dsolve(eq27) == sol27 assert checksysodesol(eq27, sol27) == (True, [0, 0]) eq28 = [Eq(Derivative(f(t), t), -9*I*f(t)), Eq(Derivative(g(t), t), -4*I*g(t))] sol28 = [Eq(f(t), C1*exp(-9*I*t)), Eq(g(t), C2*exp(-4*I*t))] assert dsolve(eq28) == sol28 assert checksysodesol(eq28, sol28) == (True, [0, 0]) eq29 = [Eq(Derivative(f(t), t), 0), Eq(Derivative(g(t), t), 0)] sol29 = [Eq(f(t), C1), Eq(g(t), C2)] assert dsolve(eq29) == sol29 assert checksysodesol(eq29, sol29) == (True, [0, 0]) eq30 = [Eq(Derivative(f(t), t), f(t)), Eq(Derivative(g(t), t), 0)] sol30 = [Eq(f(t), C1*exp(t)), Eq(g(t), C2)] assert dsolve(eq30) == sol30 assert checksysodesol(eq30, sol30) == (True, [0, 0]) eq31 = [Eq(Derivative(f(t), t), g(t)), Eq(Derivative(g(t), t), 0)] sol31 = [Eq(f(t), C1 + C2*t), Eq(g(t), C2)] assert dsolve(eq31) == sol31 assert checksysodesol(eq31, sol31) == (True, [0, 0]) eq32 = [Eq(Derivative(f(t), t), 0), Eq(Derivative(g(t), t), f(t))] sol32 = [Eq(f(t), C1), Eq(g(t), C1*t + C2)] assert dsolve(eq32) == sol32 assert checksysodesol(eq32, sol32) == (True, [0, 0]) eq33 = [Eq(Derivative(f(t), t), 0), Eq(Derivative(g(t), t), g(t))] sol33 = [Eq(f(t), C1), Eq(g(t), C2*exp(t))] assert dsolve(eq33) == sol33 assert checksysodesol(eq33, sol33) == (True, [0, 0]) eq34 = [Eq(Derivative(f(t), t), f(t)), Eq(Derivative(g(t), t), I*g(t))] sol34 = [Eq(f(t), C1*exp(t)), Eq(g(t), C2*exp(I*t))] assert dsolve(eq34) == sol34 assert checksysodesol(eq34, sol34) == (True, [0, 0]) eq35 = [Eq(Derivative(f(t), t), I*f(t)), Eq(Derivative(g(t), t), -I*g(t))] sol35 = [Eq(f(t), C1*exp(I*t)), Eq(g(t), C2*exp(-I*t))] assert dsolve(eq35) == sol35 assert checksysodesol(eq35, sol35) == (True, [0, 0]) eq36 = [Eq(Derivative(f(t), t), I*g(t)), Eq(Derivative(g(t), t), 0)] sol36 = [Eq(f(t), I*C1 + I*C2*t), Eq(g(t), C2)] assert dsolve(eq36) == sol36 assert checksysodesol(eq36, sol36) == (True, [0, 0]) eq37 = [Eq(Derivative(f(t), t), I*g(t)), Eq(Derivative(g(t), t), I*f(t))] sol37 = [Eq(f(t), -C1*exp(-I*t) + C2*exp(I*t)), Eq(g(t), C1*exp(-I*t) + C2*exp(I*t))] assert dsolve(eq37) == sol37 assert checksysodesol(eq37, sol37) == (True, [0, 0]) # Multiple systems eq1 = [Eq(Derivative(f(t), t)**2, g(t)**2), Eq(-f(t) + Derivative(g(t), t), 0)] sol1 = [[Eq(f(t), -C1*sin(t) - C2*cos(t)), Eq(g(t), C1*cos(t) - C2*sin(t))], [Eq(f(t), -C1*exp(-t) + C2*exp(t)), Eq(g(t), C1*exp(-t) + C2*exp(t))]] assert dsolve(eq1) == sol1 for sol in sol1: assert checksysodesol(eq1, sol) == (True, [0, 0]) def test_sysode_linear_neq_order1_type2(): f, g, h, k = symbols('f g h k', cls=Function) x, t, a, b, c, d, y = symbols('x t a b c d y') k1, k2 = symbols('k1 k2') eqs1 = [Eq(Derivative(f(x), x), f(x) + g(x) + 5), Eq(Derivative(g(x), x), -f(x) - g(x) + 7)] sol1 = [Eq(f(x), C1 + C2 + 6*x**2 + x*(C2 + 5)), Eq(g(x), -C1 - 6*x**2 - x*(C2 - 7))] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0]) eqs2 = [Eq(Derivative(f(x), x), f(x) + g(x) + 5), Eq(Derivative(g(x), x), f(x) + g(x) + 7)] sol2 = [Eq(f(x), -C1 + C2*exp(2*x) - x - 3), Eq(g(x), C1 + C2*exp(2*x) + x - 3)] assert dsolve(eqs2) == sol2 assert checksysodesol(eqs2, sol2) == (True, [0, 0]) eqs3 = [Eq(Derivative(f(x), x), f(x) + 5), Eq(Derivative(g(x), x), f(x) + 7)] sol3 = [Eq(f(x), C1*exp(x) - 5), Eq(g(x), C1*exp(x) + C2 + 2*x - 5)] assert dsolve(eqs3) == sol3 assert checksysodesol(eqs3, sol3) == (True, [0, 0]) eqs4 = [Eq(Derivative(f(x), x), f(x) + exp(x)), Eq(Derivative(g(x), x), x*exp(x) + f(x) + g(x))] sol4 = [Eq(f(x), C1*exp(x) + x*exp(x)), Eq(g(x), C1*x*exp(x) + C2*exp(x) + x**2*exp(x))] assert dsolve(eqs4) == sol4 assert checksysodesol(eqs4, sol4) == (True, [0, 0]) eqs5 = [Eq(Derivative(f(x), x), 5*x + f(x) + g(x)), Eq(Derivative(g(x), x), f(x) - g(x))] sol5 = [Eq(f(x), C1*(1 + sqrt(2))*exp(sqrt(2)*x) + C2*(1 - sqrt(2))*exp(-sqrt(2)*x) + x*Rational(-5, 2) + Rational(-5, 2)), Eq(g(x), C1*exp(sqrt(2)*x) + C2*exp(-sqrt(2)*x) + x*Rational(-5, 2))] assert dsolve(eqs5) == sol5 assert checksysodesol(eqs5, sol5) == (True, [0, 0]) eqs6 = [Eq(Derivative(f(x), x), -9*f(x) - 4*g(x)), Eq(Derivative(g(x), x), -4*g(x)), Eq(Derivative(h(x), x), h(x) + exp(x))] sol6 = [Eq(f(x), C1*exp(-4*x)*Rational(-4, 5) + C2*exp(-9*x)), Eq(g(x), C1*exp(-4*x)), Eq(h(x), C3*exp(x) + x*exp(x))] assert dsolve(eqs6) == sol6 assert checksysodesol(eqs6, sol6) == (True, [0, 0, 0]) # Regression test case for issue #8859 # https://github.com/sympy/sympy/issues/8859 eqs7 = [Eq(Derivative(f(t), t), 3*t + f(t)), Eq(Derivative(g(t), t), g(t))] sol7 = [Eq(f(t), C1*exp(t) - 3*t - 3), Eq(g(t), C2*exp(t))] assert dsolve(eqs7) == sol7 assert checksysodesol(eqs7, sol7) == (True, [0, 0]) # Regression test case for issue #8567 # https://github.com/sympy/sympy/issues/8567 eqs8 = [Eq(Derivative(f(t), t), f(t) + 2*g(t)), Eq(Derivative(g(t), t), -2*f(t) + g(t) + 2*exp(t))] sol8 = [Eq(f(t), C1*exp(t)*sin(2*t) + C2*exp(t)*cos(2*t) + exp(t)*cos(2*t)**2 + 2*exp(t)*sin(2*t)*tan(t)/(tan(t)**2 + 1)), Eq(g(t), C1*exp(t)*cos(2*t) - C2*exp(t)*sin(2*t) - exp(t)*sin(2*t)*cos(2*t) + 2*exp(t)*cos(2*t)*tan(t)/(tan(t)**2 + 1))] assert dsolve(eqs8) == sol8 assert checksysodesol(eqs8, sol8) == (True, [0, 0]) # Regression test case for issue #19150 # https://github.com/sympy/sympy/issues/19150 eqs9 = [Eq(Derivative(f(t), t), (c - 2*f(t) + g(t))/(a*b)), Eq(Derivative(g(t), t), (f(t) - 2*g(t) + h(t))/(a*b)), Eq(Derivative(h(t), t), (d + g(t) - 2*h(t))/(a*b))] sol9 = [Eq(f(t), -C1*exp(-2*t/(a*b)) + C2*exp(-t*(sqrt(2) + 2)/(a*b)) + C3*exp(-t*(2 - sqrt(2))/(a*b)) + Mul(Rational(1, 4), 3*c + d, evaluate=False)), Eq(g(t), -sqrt(2)*C2*exp(-t*(sqrt(2) + 2)/(a*b)) + sqrt(2)*C3*exp(-t*(2 - sqrt(2))/(a*b)) + Mul(Rational(1, 2), c + d, evaluate=False)), Eq(h(t), C1*exp(-2*t/(a*b)) + C2*exp(-t*(sqrt(2) + 2)/(a*b)) + C3*exp(-t*(2 - sqrt(2))/(a*b)) + Mul(Rational(1, 4), c + 3*d, evaluate=False))] assert dsolve(eqs9) == sol9 assert checksysodesol(eqs9, sol9) == (True, [0, 0, 0]) # Regression test case for issue #16635 # https://github.com/sympy/sympy/issues/16635 eqs10 = [Eq(Derivative(f(t), t), 15*t + f(t) - g(t) - 10), Eq(Derivative(g(t), t), -15*t + f(t) - g(t) - 5)] sol10 = [Eq(f(t), C1 + C2 + 5*t**3 + 5*t**2 + t*(C2 - 10)), Eq(g(t), C1 + 5*t**3 - 10*t**2 + t*(C2 - 5))] assert dsolve(eqs10) == sol10 assert checksysodesol(eqs10, sol10) == (True, [0, 0]) # Multiple solutions eqs11 = [Eq(Derivative(f(t), t)**2 - 2*Derivative(f(t), t) + 1, 4), Eq(-y*f(t) + Derivative(g(t), t), 0)] sol11 = [[Eq(f(t), C1 - t), Eq(g(t), C1*t*y + C2*y + t**2*y*Rational(-1, 2))], [Eq(f(t), C1 + 3*t), Eq(g(t), C1*t*y + C2*y + t**2*y*Rational(3, 2))]] assert dsolve(eqs11) == sol11 for s11 in sol11: assert checksysodesol(eqs11, s11) == (True, [0, 0]) # test case for issue #19831 # https://github.com/sympy/sympy/issues/19831 n = symbols('n', positive=True) x0 = symbols('x_0') t0 = symbols('t_0') x_0 = symbols('x_0') t_0 = symbols('t_0') t = symbols('t') x = Function('x') y = Function('y') T = symbols('T') eqs12 = [Eq(Derivative(y(t), t), x(t)), Eq(Derivative(x(t), t), n*(y(t) + 1))] sol12 = [Eq(y(t), C1*exp(sqrt(n)*t)*n**Rational(-1, 2) - C2*exp(-sqrt(n)*t)*n**Rational(-1, 2) - 1), Eq(x(t), C1*exp(sqrt(n)*t) + C2*exp(-sqrt(n)*t))] assert dsolve(eqs12) == sol12 assert checksysodesol(eqs12, sol12) == (True, [0, 0]) sol12b = [ Eq(y(t), (T*exp(-sqrt(n)*t_0)/2 + exp(-sqrt(n)*t_0)/2 + x_0*exp(-sqrt(n)*t_0)/(2*sqrt(n)))*exp(sqrt(n)*t) + (T*exp(sqrt(n)*t_0)/2 + exp(sqrt(n)*t_0)/2 - x_0*exp(sqrt(n)*t_0)/(2*sqrt(n)))*exp(-sqrt(n)*t) - 1), Eq(x(t), (T*sqrt(n)*exp(-sqrt(n)*t_0)/2 + sqrt(n)*exp(-sqrt(n)*t_0)/2 + x_0*exp(-sqrt(n)*t_0)/2)*exp(sqrt(n)*t) - (T*sqrt(n)*exp(sqrt(n)*t_0)/2 + sqrt(n)*exp(sqrt(n)*t_0)/2 - x_0*exp(sqrt(n)*t_0)/2)*exp(-sqrt(n)*t)) ] assert dsolve(eqs12, ics={y(t0): T, x(t0): x0}) == sol12b assert checksysodesol(eqs12, sol12b) == (True, [0, 0]) #Test cases added for the issue 19763 #https://github.com/sympy/sympy/issues/19763 eq13 = [Eq(Derivative(f(t), t), f(t) + g(t) + 9), Eq(Derivative(g(t), t), 2*f(t) + 5*g(t) + 23)] sol13 = [Eq(f(t), -C1*(2 + sqrt(6))*exp(t*(3 - sqrt(6)))/2 - C2*(2 - sqrt(6))*exp(t*(sqrt(6) + 3))/2 - Rational(22,3)), Eq(g(t), C1*exp(t*(3 - sqrt(6))) + C2*exp(t*(sqrt(6) + 3)) - Rational(5,3))] assert dsolve(eq13) == sol13 assert checksysodesol(eq13, sol13) == (True, [0, 0]) eq14 = [Eq(Derivative(f(t), t), f(t) + g(t) + 81), Eq(Derivative(g(t), t), -2*f(t) + g(t) + 23)] sol14 = [Eq(f(t), sqrt(2)*C1*exp(t)*sin(sqrt(2)*t)/2 + sqrt(2)*C2*exp(t)*cos(sqrt(2)*t)/2 + sqrt(2)*exp(t)*sin(sqrt(2)*t)*Integral(-23*exp(-t)*sin(sqrt(2)*t)**2/cos(sqrt(2)*t) + 81*sqrt(2)*exp(-t)*sin(sqrt(2)*t) + 23*exp(-t)/cos(sqrt(2)*t), t)/2 + 185*sqrt(2)*sin(sqrt(2)*t)*cos(sqrt(2)*t)/6 - 58*cos(sqrt(2)*t)**2/3), Eq(g(t), C1*exp(t)*cos(sqrt(2)*t) - C2*exp(t)*sin(sqrt(2)*t) + exp(t)*cos(sqrt(2)*t)*Integral(-23*exp(-t)*sin(sqrt(2)*t)**2/cos(sqrt(2)*t) + 81*sqrt(2)*exp(-t)*sin(sqrt(2)*t) + 23*exp(-t)/cos(sqrt(2)*t), t) - 185*sin(sqrt(2)*t)**2/3 + 58*sqrt(2)*sin(sqrt(2)*t)*cos(sqrt(2)*t)/3)] assert dsolve(eq14) == sol14 assert checksysodesol(eq14 , sol14) == (True , [0,0]) eq15 = [Eq(Derivative(f(t), t), f(t) + 2*g(t) + k1), Eq(Derivative(g(t), t), 3*f(t) + 4*g(t) + k2)] sol15 = [Eq(f(t), -C1*(3 - sqrt(33))*exp(t*(5 + sqrt(33))/2)/6 - C2*(3 + sqrt(33))*exp(t*(5 - sqrt(33))/2)/6 + 2*k1 - k2), Eq(g(t), C1*exp(t*(5 + sqrt(33))/2) + C2*exp(t*(5 - sqrt(33))/2) - Mul(Rational(1,2) , 3*k1 - k2 , evaluate = False))] assert dsolve(eq15) == sol15 assert checksysodesol(eq15 , sol15) == (True , [0,0]) eq16 = [Eq(Derivative(f(t), t), k1), Eq(Derivative(g(t), t), k2)] sol16 = [Eq(f(t), C1 + k1*t), Eq(g(t), C2 + k2*t)] assert dsolve(eq16) == sol16 assert checksysodesol(eq16 , sol16) == (True , [0,0]) eq17 = [Eq(Derivative(f(t), t), 0), Eq(Derivative(g(t), t), c*f(t) + k2)] sol17 = [Eq(f(t), C1), Eq(g(t), C2*c + t*(C1*c + k2))] assert dsolve(eq17) == sol17 assert checksysodesol(eq17 , sol17) == (True , [0,0]) eq18 = [Eq(Derivative(f(t), t), k1), Eq(Derivative(g(t), t), f(t) + k2)] sol18 = [Eq(f(t), C1 + k1*t), Eq(g(t), C2 + k1*t**2/2 + t*(C1 + k2))] assert dsolve(eq18) == sol18 assert checksysodesol(eq18 , sol18) == (True , [0,0]) eq19 = [Eq(Derivative(f(t), t), k1), Eq(Derivative(g(t), t), f(t) + 2*g(t) + k2)] sol19 = [Eq(f(t), -2*C1 + k1*t), Eq(g(t), C1 + C2*exp(2*t) - k1*t/2 - Mul(Rational(1,4), k1 + 2*k2 , evaluate = False))] assert dsolve(eq19) == sol19 assert checksysodesol(eq19 , sol19) == (True , [0,0]) eq20 = [Eq(diff(f(t), t), f(t) + k1), Eq(diff(g(t), t), k2)] sol20 = [Eq(f(t), C1*exp(t) - k1), Eq(g(t), C2 + k2*t)] assert dsolve(eq20) == sol20 assert checksysodesol(eq20 , sol20) == (True , [0,0]) eq21 = [Eq(diff(f(t), t), g(t) + k1), Eq(diff(g(t), t), 0)] sol21 = [Eq(f(t), C1 + t*(C2 + k1)), Eq(g(t), C2)] assert dsolve(eq21) == sol21 assert checksysodesol(eq21 , sol21) == (True , [0,0]) eq22 = [Eq(Derivative(f(t), t), f(t) + 2*g(t) + k1), Eq(Derivative(g(t), t), k2)] sol22 = [Eq(f(t), -2*C1 + C2*exp(t) - k1 - 2*k2*t - 2*k2), Eq(g(t), C1 + k2*t)] assert dsolve(eq22) == sol22 assert checksysodesol(eq22 , sol22) == (True , [0,0]) eq23 = [Eq(Derivative(f(t), t), g(t) + k1), Eq(Derivative(g(t), t), 2*g(t) + k2)] sol23 = [Eq(f(t), C1 + C2*exp(2*t)/2 - k2/4 + t*(2*k1 - k2)/2), Eq(g(t), C2*exp(2*t) - k2/2)] assert dsolve(eq23) == sol23 assert checksysodesol(eq23 , sol23) == (True , [0,0]) eq24 = [Eq(Derivative(f(t), t), f(t) + k1), Eq(Derivative(g(t), t), 2*f(t) + k2)] sol24 = [Eq(f(t), C1*exp(t)/2 - k1), Eq(g(t), C1*exp(t) + C2 - 2*k1 - t*(2*k1 - k2))] assert dsolve(eq24) == sol24 assert checksysodesol(eq24 , sol24) == (True , [0,0]) eq25 = [Eq(Derivative(f(t), t), f(t) + 2*g(t) + k1), Eq(Derivative(g(t), t), 3*f(t) + 6*g(t) + k2)] sol25 = [Eq(f(t), -2*C1 + C2*exp(7*t)/3 + 2*t*(3*k1 - k2)/7 - Mul(Rational(1,49), k1 + 2*k2 , evaluate = False)), Eq(g(t), C1 + C2*exp(7*t) - t*(3*k1 - k2)/7 - Mul(Rational(3,49), k1 + 2*k2 , evaluate = False))] assert dsolve(eq25) == sol25 assert checksysodesol(eq25 , sol25) == (True , [0,0]) eq26 = [Eq(Derivative(f(t), t), 2*f(t) - g(t) + k1), Eq(Derivative(g(t), t), 4*f(t) - 2*g(t) + 2*k1)] sol26 = [Eq(f(t), C1 + 2*C2 + t*(2*C1 + k1)), Eq(g(t), 4*C2 + t*(4*C1 + 2*k1))] assert dsolve(eq26) == sol26 assert checksysodesol(eq26 , sol26) == (True , [0,0]) def test_sysode_linear_neq_order1_type3(): f, g, h, k, x0 , y0 = symbols('f g h k x0 y0', cls=Function) x, t, a = symbols('x t a') r = symbols('r', real=True) eqs1 = [Eq(Derivative(f(r), r), r*g(r) + f(r)), Eq(Derivative(g(r), r), -r*f(r) + g(r))] sol1 = [Eq(f(r), C1*exp(r)*sin(r**2/2) + C2*exp(r)*cos(r**2/2)), Eq(g(r), C1*exp(r)*cos(r**2/2) - C2*exp(r)*sin(r**2/2))] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0]) eqs2 = [Eq(Derivative(f(x), x), x**2*g(x) + x*f(x)), Eq(Derivative(g(x), x), 2*x**2*f(x) + (3*x**2 + x)*g(x))] sol2 = [Eq(f(x), (sqrt(17)*C1/17 + C2*(17 - 3*sqrt(17))/34)*exp(x**3*(3 + sqrt(17))/6 + x**2/2) - exp(x**3*(3 - sqrt(17))/6 + x**2/2)*(sqrt(17)*C1/17 + C2*(3*sqrt(17) + 17)*Rational(-1, 34))), Eq(g(x), exp(x**3*(3 - sqrt(17))/6 + x**2/2)*(C1*(17 - 3*sqrt(17))/34 + sqrt(17)*C2*Rational(-2, 17)) + exp(x**3*(3 + sqrt(17))/6 + x**2/2)*(C1*(3*sqrt(17) + 17)/34 + sqrt(17)*C2*Rational(2, 17)))] assert dsolve(eqs2) == sol2 assert checksysodesol(eqs2, sol2) == (True, [0, 0]) eqs3 = [Eq(f(x).diff(x), x*f(x) + g(x)), Eq(g(x).diff(x), -f(x) + x*g(x))] sol3 = [Eq(f(x), (C1/2 + I*C2/2)*exp(x**2/2 - I*x) + exp(x**2/2 + I*x)*(C1/2 + I*C2*Rational(-1, 2))), Eq(g(x), (I*C1/2 + C2/2)*exp(x**2/2 + I*x) - exp(x**2/2 - I*x)*(I*C1/2 + C2*Rational(-1, 2)))] assert dsolve(eqs3) == sol3 assert checksysodesol(eqs3, sol3) == (True, [0, 0]) eqs4 = [Eq(f(x).diff(x), x*(f(x) + g(x) + h(x))), Eq(g(x).diff(x), x*(f(x) + g(x) + h(x))), Eq(h(x).diff(x), x*(f(x) + g(x) + h(x)))] sol4 = [Eq(f(x), -C1/3 - C2/3 + 2*C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2)), Eq(g(x), 2*C1/3 - C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2)), Eq(h(x), -C1/3 + 2*C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2))] assert dsolve(eqs4) == sol4 assert checksysodesol(eqs4, sol4) == (True, [0, 0, 0]) eqs5 = [Eq(f(x).diff(x), x**2*(f(x) + g(x) + h(x))), Eq(g(x).diff(x), x**2*(f(x) + g(x) + h(x))), Eq(h(x).diff(x), x**2*(f(x) + g(x) + h(x)))] sol5 = [Eq(f(x), -C1/3 - C2/3 + 2*C3/3 + (C1/3 + C2/3 + C3/3)*exp(x**3)), Eq(g(x), 2*C1/3 - C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(x**3)), Eq(h(x), -C1/3 + 2*C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(x**3))] assert dsolve(eqs5) == sol5 assert checksysodesol(eqs5, sol5) == (True, [0, 0, 0]) eqs6 = [Eq(Derivative(f(x), x), x*(f(x) + g(x) + h(x) + k(x))), Eq(Derivative(g(x), x), x*(f(x) + g(x) + h(x) + k(x))), Eq(Derivative(h(x), x), x*(f(x) + g(x) + h(x) + k(x))), Eq(Derivative(k(x), x), x*(f(x) + g(x) + h(x) + k(x)))] sol6 = [Eq(f(x), -C1/4 - C2/4 - C3/4 + 3*C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2)), Eq(g(x), 3*C1/4 - C2/4 - C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2)), Eq(h(x), -C1/4 + 3*C2/4 - C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2)), Eq(k(x), -C1/4 - C2/4 + 3*C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2))] assert dsolve(eqs6) == sol6 assert checksysodesol(eqs6, sol6) == (True, [0, 0, 0, 0]) y = symbols("y", real=True) eqs7 = [Eq(Derivative(f(y), y), y*f(y) + g(y)), Eq(Derivative(g(y), y), y*g(y) - f(y))] sol7 = [Eq(f(y), C1*exp(y**2/2)*sin(y) + C2*exp(y**2/2)*cos(y)), Eq(g(y), C1*exp(y**2/2)*cos(y) - C2*exp(y**2/2)*sin(y))] assert dsolve(eqs7) == sol7 assert checksysodesol(eqs7, sol7) == (True, [0, 0]) #Test cases added for the issue 19763 #https://github.com/sympy/sympy/issues/19763 eqs8 = [Eq(Derivative(f(t), t), 5*t*f(t) + 2*h(t)), Eq(Derivative(h(t), t), 2*f(t) + 5*t*h(t))] sol8 = [Eq(f(t), Mul(-1, (C1/2 - C2/2), evaluate = False)*exp(5*t**2/2 - 2*t) + (C1/2 + C2/2)*exp(5*t**2/2 + 2*t)), Eq(h(t), (C1/2 - C2/2)*exp(5*t**2/2 - 2*t) + (C1/2 + C2/2)*exp(5*t**2/2 + 2*t))] assert dsolve(eqs8) == sol8 assert checksysodesol(eqs8, sol8) == (True, [0, 0]) eqs9 = [Eq(diff(f(t), t), 5*t*f(t) + t**2*g(t)), Eq(diff(g(t), t), -t**2*f(t) + 5*t*g(t))] sol9 = [Eq(f(t), (C1/2 - I*C2/2)*exp(I*t**3/3 + 5*t**2/2) + (C1/2 + I*C2/2)*exp(-I*t**3/3 + 5*t**2/2)), Eq(g(t), Mul(-1, (I*C1/2 - C2/2) , evaluate = False)*exp(-I*t**3/3 + 5*t**2/2) + (I*C1/2 + C2/2)*exp(I*t**3/3 + 5*t**2/2))] assert dsolve(eqs9) == sol9 assert checksysodesol(eqs9 , sol9) == (True , [0,0]) eqs10 = [Eq(diff(f(t), t), t**2*g(t) + 5*t*f(t)), Eq(diff(g(t), t), -t**2*f(t) + (9*t**2 + 5*t)*g(t))] sol10 = [Eq(f(t), (C1*(77 - 9*sqrt(77))/154 + sqrt(77)*C2/77)*exp(t**3*(sqrt(77) + 9)/6 + 5*t**2/2) + (C1*(77 + 9*sqrt(77))/154 - sqrt(77)*C2/77)*exp(t**3*(9 - sqrt(77))/6 + 5*t**2/2)), Eq(g(t), (sqrt(77)*C1/77 + C2*(77 - 9*sqrt(77))/154)*exp(t**3*(9 - sqrt(77))/6 + 5*t**2/2) - (sqrt(77)*C1/77 - C2*(77 + 9*sqrt(77))/154)*exp(t**3*(sqrt(77) + 9)/6 + 5*t**2/2))] assert dsolve(eqs10) == sol10 assert checksysodesol(eqs10 , sol10) == (True , [0,0]) eqs11 = [Eq(diff(f(t), t), 5*t*f(t) + t**2*g(t)), Eq(diff(g(t), t), (1-t**2)*f(t) + (5*t + 9*t**2)*g(t))] sol11 = [Eq(f(t), C1*x0(t) + C2*x0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t)), Eq(g(t), C1*y0(t) + C2*(y0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t) + exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)))] assert dsolve(eqs11) == sol11 @slow def test_sysode_linear_neq_order1_type4(): f, g, h, k = symbols('f g h k', cls=Function) x, t, a = symbols('x t a') r = symbols('r', real=True) eqs1 = [Eq(diff(f(r), r), f(r) + r*g(r) + r**2), Eq(diff(g(r), r), -r*f(r) + g(r) + r)] sol1 = [Eq(f(r), C1*exp(r)*sin(r**2/2) + C2*exp(r)*cos(r**2/2) + exp(r)*sin(r**2/2)*Integral(r**2*exp(-r)*sin(r**2/2) + r*exp(-r)*cos(r**2/2), r) + exp(r)*cos(r**2/2)*Integral(r**2*exp(-r)*cos(r**2/2) - r*exp(-r)*sin(r**2/2), r)), Eq(g(r), C1*exp(r)*cos(r**2/2) - C2*exp(r)*sin(r**2/2) - exp(r)*sin(r**2/2)*Integral(r**2*exp(-r)*cos(r**2/2) - r*exp(-r)*sin(r**2/2), r) + exp(r)*cos(r**2/2)*Integral(r**2*exp(-r)*sin(r**2/2) + r*exp(-r)*cos(r**2/2), r))] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0]) eqs2 = [Eq(diff(f(r), r), f(r) + r*g(r) + r), Eq(diff(g(r), r), -r*f(r) + g(r) + log(r))] sol2 = [Eq(f(r), C1*exp(r)*sin(r**2/2) + C2*exp(r)*cos(r**2/2) + exp(r)*sin(r**2/2)*Integral(r*exp(-r)*sin(r**2/2) + exp(-r)*log(r)*cos(r**2/2), r) + exp(r)*cos(r**2/2)*Integral(r*exp(-r)*cos(r**2/2) - exp(-r)*log(r)*sin( r**2/2), r)), Eq(g(r), C1*exp(r)*cos(r**2/2) - C2*exp(r)*sin(r**2/2) - exp(r)*sin(r**2/2)*Integral(r*exp(-r)*cos(r**2/2) - exp(-r)*log(r)*sin(r**2/2), r) + exp(r)*cos(r**2/2)*Integral(r*exp(-r)*sin(r**2/2) + exp(-r)*log(r)*cos( r**2/2), r))] # XXX: dsolve hangs for this in integration assert dsolve_system(eqs2, simplify=False, doit=False) == [sol2] assert checksysodesol(eqs2, sol2) == (True, [0, 0]) eqs3 = [Eq(Derivative(f(x), x), x*(f(x) + g(x) + h(x)) + x), Eq(Derivative(g(x), x), x*(f(x) + g(x) + h(x)) + x), Eq(Derivative(h(x), x), x*(f(x) + g(x) + h(x)) + 1)] sol3 = [Eq(f(x), C1*Rational(-1, 3) + C2*Rational(-1, 3) + C3*Rational(2, 3) + x**2/6 + x*Rational(-1, 3) + (C1/3 + C2/3 + C3/3)*exp(x**2*Rational(3, 2)) + sqrt(6)*sqrt(pi)*erf(sqrt(6)*x/2)*exp(x**2*Rational(3, 2))/18 + Rational(-2, 9)), Eq(g(x), C1*Rational(2, 3) + C2*Rational(-1, 3) + C3*Rational(-1, 3) + x**2/6 + x*Rational(-1, 3) + (C1/3 + C2/3 + C3/3)*exp(x**2*Rational(3, 2)) + sqrt(6)*sqrt(pi)*erf(sqrt(6)*x/2)*exp(x**2*Rational(3, 2))/18 + Rational(-2, 9)), Eq(h(x), C1*Rational(-1, 3) + C2*Rational(2, 3) + C3*Rational(-1, 3) + x**2*Rational(-1, 3) + x*Rational(2, 3) + (C1/3 + C2/3 + C3/3)*exp(x**2*Rational(3, 2)) + sqrt(6)*sqrt(pi)*erf(sqrt(6)*x/2)*exp(x**2*Rational(3, 2))/18 + Rational(-2, 9))] assert dsolve(eqs3) == sol3 assert checksysodesol(eqs3, sol3) == (True, [0, 0, 0]) eqs4 = [Eq(Derivative(f(x), x), x*(f(x) + g(x) + h(x)) + sin(x)), Eq(Derivative(g(x), x), x*(f(x) + g(x) + h(x)) + sin(x)), Eq(Derivative(h(x), x), x*(f(x) + g(x) + h(x)) + sin(x))] sol4 = [Eq(f(x), C1*Rational(-1, 3) + C2*Rational(-1, 3) + C3*Rational(2, 3) + (C1/3 + C2/3 + C3/3)*exp(x**2*Rational(3, 2)) + Integral(sin(x)*exp(x**2*Rational(-3, 2)), x)*exp(x**2*Rational(3, 2))), Eq(g(x), C1*Rational(2, 3) + C2*Rational(-1, 3) + C3*Rational(-1, 3) + (C1/3 + C2/3 + C3/3)*exp(x**2*Rational(3, 2)) + Integral(sin(x)*exp(x**2*Rational(-3, 2)), x)*exp(x**2*Rational(3, 2))), Eq(h(x), C1*Rational(-1, 3) + C2*Rational(2, 3) + C3*Rational(-1, 3) + (C1/3 + C2/3 + C3/3)*exp(x**2*Rational(3, 2)) + Integral(sin(x)*exp(x**2*Rational(-3, 2)), x)*exp(x**2*Rational(3, 2)))] assert dsolve(eqs4) == sol4 assert checksysodesol(eqs4, sol4) == (True, [0, 0, 0]) eqs5 = [Eq(Derivative(f(x), x), x*(f(x) + g(x) + h(x) + k(x) + 1)), Eq(Derivative(g(x), x), x*(f(x) + g(x) + h(x) + k(x) + 1)), Eq(Derivative(h(x), x), x*(f(x) + g(x) + h(x) + k(x) + 1)), Eq(Derivative(k(x), x), x*(f(x) + g(x) + h(x) + k(x) + 1))] sol5 = [Eq(f(x), C1*Rational(-1, 4) + C2*Rational(-1, 4) + C3*Rational(-1, 4) + C4*Rational(3, 4) + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2) + Rational(-1, 4)), Eq(g(x), C1*Rational(3, 4) + C2*Rational(-1, 4) + C3*Rational(-1, 4) + C4*Rational(-1, 4) + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2) + Rational(-1, 4)), Eq(h(x), C1*Rational(-1, 4) + C2*Rational(3, 4) + C3*Rational(-1, 4) + C4*Rational(-1, 4) + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2) + Rational(-1, 4)), Eq(k(x), C1*Rational(-1, 4) + C2*Rational(-1, 4) + C3*Rational(3, 4) + C4*Rational(-1, 4) + (C1/4 + C2/4 + C3/4 + C4/4)*exp(2*x**2) + Rational(-1, 4))] assert dsolve(eqs5) == sol5 assert checksysodesol(eqs5, sol5) == (True, [0, 0, 0, 0]) eqs6 = [Eq(Derivative(f(x), x), x**2*(f(x) + g(x) + h(x) + k(x) + 1)), Eq(Derivative(g(x), x), x**2*(f(x) + g(x) + h(x) + k(x) + 1)), Eq(Derivative(h(x), x), x**2*(f(x) + g(x) + h(x) + k(x) + 1)), Eq(Derivative(k(x), x), x**2*(f(x) + g(x) + h(x) + k(x) + 1))] sol6 = [Eq(f(x), C1*Rational(-1, 4) + C2*Rational(-1, 4) + C3*Rational(-1, 4) + C4*Rational(3, 4) + (C1/4 + C2/4 + C3/4 + C4/4)*exp(x**3*Rational(4, 3)) + Rational(-1, 4)), Eq(g(x), C1*Rational(3, 4) + C2*Rational(-1, 4) + C3*Rational(-1, 4) + C4*Rational(-1, 4) + (C1/4 + C2/4 + C3/4 + C4/4)*exp(x**3*Rational(4, 3)) + Rational(-1, 4)), Eq(h(x), C1*Rational(-1, 4) + C2*Rational(3, 4) + C3*Rational(-1, 4) + C4*Rational(-1, 4) + (C1/4 + C2/4 + C3/4 + C4/4)*exp(x**3*Rational(4, 3)) + Rational(-1, 4)), Eq(k(x), C1*Rational(-1, 4) + C2*Rational(-1, 4) + C3*Rational(3, 4) + C4*Rational(-1, 4) + (C1/4 + C2/4 + C3/4 + C4/4)*exp(x**3*Rational(4, 3)) + Rational(-1, 4))] assert dsolve(eqs6) == sol6 assert checksysodesol(eqs6, sol6) == (True, [0, 0, 0, 0]) eqs7 = [Eq(Derivative(f(x), x), (f(x) + g(x) + h(x))*log(x) + sin(x)), Eq(Derivative(g(x), x), (f(x) + g(x) + h(x))*log(x) + sin(x)), Eq(Derivative(h(x), x), (f(x) + g(x) + h(x))*log(x) + sin(x))] sol7 = [Eq(f(x), -C1/3 - C2/3 + 2*C3/3 + (C1/3 + C2/3 + C3/3)*exp(x*(3*log(x) - 3)) + exp(x*(3*log(x) - 3))*Integral(exp(3*x)*exp(-3*x*log(x))*sin(x), x)), Eq(g(x), 2*C1/3 - C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(x*(3*log(x) - 3)) + exp(x*(3*log(x) - 3))*Integral(exp(3*x)*exp(-3*x*log(x))*sin(x), x)), Eq(h(x), -C1/3 + 2*C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(x*(3*log(x) - 3)) + exp(x*(3*log(x) - 3))*Integral(exp(3*x)*exp(-3*x*log(x))*sin(x), x))] with dotprodsimp(True): assert dsolve(eqs7, simplify=False, doit=False) == sol7 assert checksysodesol(eqs7, sol7) == (True, [0, 0, 0]) eqs8 = [Eq(Derivative(f(x), x), (f(x) + g(x) + h(x) + k(x))*log(x) + sin(x)), Eq(Derivative(g(x), x), (f(x) + g(x) + h(x) + k(x))*log(x) + sin(x)), Eq(Derivative(h(x), x), (f(x) + g(x) + h(x) + k(x))*log(x) + sin(x)), Eq(Derivative(k(x), x), (f(x) + g(x) + h(x) + k(x))*log(x) + sin(x))] sol8 = [Eq(f(x), -C1/4 - C2/4 - C3/4 + 3*C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(x*(4*log(x) - 4)) + exp(x*(4*log(x) - 4))*Integral(exp(4*x)*exp(-4*x*log(x))*sin(x), x)), Eq(g(x), 3*C1/4 - C2/4 - C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(x*(4*log(x) - 4)) + exp(x*(4*log(x) - 4))*Integral(exp(4*x)*exp(-4*x*log(x))*sin(x), x)), Eq(h(x), -C1/4 + 3*C2/4 - C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(x*(4*log(x) - 4)) + exp(x*(4*log(x) - 4))*Integral(exp(4*x)*exp(-4*x*log(x))*sin(x), x)), Eq(k(x), -C1/4 - C2/4 + 3*C3/4 - C4/4 + (C1/4 + C2/4 + C3/4 + C4/4)*exp(x*(4*log(x) - 4)) + exp(x*(4*log(x) - 4))*Integral(exp(4*x)*exp(-4*x*log(x))*sin(x), x))] with dotprodsimp(True): assert dsolve(eqs8) == sol8 assert checksysodesol(eqs8, sol8) == (True, [0, 0, 0, 0]) def test_sysode_linear_neq_order1_type5_type6(): f, g = symbols("f g", cls=Function) x, x_ = symbols("x x_") # Type 5 eqs1 = [Eq(Derivative(f(x), x), (2*f(x) + g(x))/x), Eq(Derivative(g(x), x), (f(x) + 2*g(x))/x)] sol1 = [Eq(f(x), -C1*x + C2*x**3), Eq(g(x), C1*x + C2*x**3)] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0]) # Type 6 eqs2 = [Eq(Derivative(f(x), x), (2*f(x) + g(x) + 1)/x), Eq(Derivative(g(x), x), (x + f(x) + 2*g(x))/x)] sol2 = [Eq(f(x), C2*x**3 - x*(C1 + Rational(1, 4)) + x*log(x)*Rational(-1, 2) + Rational(-2, 3)), Eq(g(x), C2*x**3 + x*log(x)/2 + x*(C1 + Rational(-1, 4)) + Rational(1, 3))] assert dsolve(eqs2) == sol2 assert checksysodesol(eqs2, sol2) == (True, [0, 0]) def test_higher_order_to_first_order(): f, g = symbols('f g', cls=Function) x = symbols('x') eqs1 = [Eq(Derivative(f(x), (x, 2)), 2*f(x) + g(x)), Eq(Derivative(g(x), (x, 2)), -f(x))] sol1 = [Eq(f(x), -C2*x*exp(-x) + C3*x*exp(x) - (C1 - C2)*exp(-x) + (C3 + C4)*exp(x)), Eq(g(x), C2*x*exp(-x) - C3*x*exp(x) + (C1 + C2)*exp(-x) + (C3 - C4)*exp(x))] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0]) eqs2 = [Eq(f(x).diff(x, 2), 0), Eq(g(x).diff(x, 2), f(x))] sol2 = [Eq(f(x), C1 + C2*x), Eq(g(x), C1*x**2/2 + C2*x**3/6 + C3 + C4*x)] assert dsolve(eqs2) == sol2 assert checksysodesol(eqs2, sol2) == (True, [0, 0]) eqs3 = [Eq(Derivative(f(x), (x, 2)), 2*f(x)), Eq(Derivative(g(x), (x, 2)), -f(x) + 2*g(x))] sol3 = [Eq(f(x), 4*C1*exp(-sqrt(2)*x) + 4*C2*exp(sqrt(2)*x)), Eq(g(x), sqrt(2)*C1*x*exp(-sqrt(2)*x) - sqrt(2)*C2*x*exp(sqrt(2)*x) + (C1 + sqrt(2)*C4)*exp(-sqrt(2)*x) + (C2 - sqrt(2)*C3)*exp(sqrt(2)*x))] assert dsolve(eqs3) == sol3 assert checksysodesol(eqs3, sol3) == (True, [0, 0]) eqs4 = [Eq(Derivative(f(x), (x, 2)), 2*f(x) + g(x)), Eq(Derivative(g(x), (x, 2)), 2*g(x))] sol4 = [Eq(f(x), C1*x*exp(sqrt(2)*x)/4 + C3*x*exp(-sqrt(2)*x)/4 + (C2/4 + sqrt(2)*C3/8)*exp(-sqrt(2)*x) - exp(sqrt(2)*x)*(sqrt(2)*C1/8 + C4*Rational(-1, 4))), Eq(g(x), sqrt(2)*C1*exp(sqrt(2)*x)/2 + sqrt(2)*C3*exp(-sqrt(2)*x)*Rational(-1, 2))] assert dsolve(eqs4) == sol4 assert checksysodesol(eqs4, sol4) == (True, [0, 0]) eqs5 = [Eq(f(x).diff(x, 2), f(x)), Eq(g(x).diff(x, 2), f(x))] sol5 = [Eq(f(x), -C1*exp(-x) + C2*exp(x)), Eq(g(x), -C1*exp(-x) + C2*exp(x) + C3 + C4*x)] assert dsolve(eqs5) == sol5 assert checksysodesol(eqs5, sol5) == (True, [0, 0]) eqs6 = [Eq(Derivative(f(x), (x, 2)), f(x) + g(x)), Eq(Derivative(g(x), (x, 2)), -f(x) - g(x))] sol6 = [Eq(f(x), C1 + C2*x**2/2 + C2 + C4*x**3/6 + x*(C3 + C4)), Eq(g(x), -C1 + C2*x**2*Rational(-1, 2) - C3*x + C4*x**3*Rational(-1, 6))] assert dsolve(eqs6) == sol6 assert checksysodesol(eqs6, sol6) == (True, [0, 0]) eqs7 = [Eq(Derivative(f(x), (x, 2)), f(x) + g(x) + 1), Eq(Derivative(g(x), (x, 2)), f(x) + g(x) + 1)] sol7 = [Eq(f(x), -C1 - C2*x + sqrt(2)*C3*exp(sqrt(2)*x)/2 + sqrt(2)*C4*exp(-sqrt(2)*x)*Rational(-1, 2) + Rational(-1, 2)), Eq(g(x), C1 + C2*x + sqrt(2)*C3*exp(sqrt(2)*x)/2 + sqrt(2)*C4*exp(-sqrt(2)*x)*Rational(-1, 2) + Rational(-1, 2))] assert dsolve(eqs7) == sol7 assert checksysodesol(eqs7, sol7) == (True, [0, 0]) eqs8 = [Eq(Derivative(f(x), (x, 2)), f(x) + g(x) + 1), Eq(Derivative(g(x), (x, 2)), -f(x) - g(x) + 1)] sol8 = [Eq(f(x), C1 + C2 + C4*x**3/6 + x**4/12 + x**2*(C2/2 + Rational(1, 2)) + x*(C3 + C4)), Eq(g(x), -C1 - C3*x + C4*x**3*Rational(-1, 6) + x**4*Rational(-1, 12) - x**2*(C2/2 + Rational(-1, 2)))] assert dsolve(eqs8) == sol8 assert checksysodesol(eqs8, sol8) == (True, [0, 0]) x, y = symbols('x, y', cls=Function) t, l = symbols('t, l') eqs10 = [Eq(Derivative(x(t), (t, 2)), 5*x(t) + 43*y(t)), Eq(Derivative(y(t), (t, 2)), x(t) + 9*y(t))] sol10 = [Eq(x(t), C1*(61 - 9*sqrt(47))*sqrt(sqrt(47) + 7)*exp(-t*sqrt(sqrt(47) + 7))/2 + C2*sqrt(7 - sqrt(47))*(61 + 9*sqrt(47))*exp(-t*sqrt(7 - sqrt(47)))/2 + C3*(61 - 9*sqrt(47))*sqrt(sqrt(47) + 7)*exp(t*sqrt(sqrt(47) + 7))*Rational(-1, 2) + C4*sqrt(7 - sqrt(47))*(61 + 9*sqrt(47))*exp(t*sqrt(7 - sqrt(47)))*Rational(-1, 2)), Eq(y(t), C1*(7 - sqrt(47))*sqrt(sqrt(47) + 7)*exp(-t*sqrt(sqrt(47) + 7))*Rational(-1, 2) + C2*sqrt(7 - sqrt(47))*(sqrt(47) + 7)*exp(-t*sqrt(7 - sqrt(47)))*Rational(-1, 2) + C3*(7 - sqrt(47))*sqrt(sqrt(47) + 7)*exp(t*sqrt(sqrt(47) + 7))/2 + C4*sqrt(7 - sqrt(47))*(sqrt(47) + 7)*exp(t*sqrt(7 - sqrt(47)))/2)] assert dsolve(eqs10) == sol10 assert checksysodesol(eqs10, sol10) == (True, [0, 0]) eqs11 = [Eq(7*x(t) + Derivative(x(t), (t, 2)) - 9*Derivative(y(t), t), 0), Eq(7*y(t) + 9*Derivative(x(t), t) + Derivative(y(t), (t, 2)), 0)] sol11 = [Eq(y(t), C1*(9 - sqrt(109))*sin(sqrt(2)*t*sqrt(9*sqrt(109) + 95)/2)/14 + C2*(9 - sqrt(109))*cos(sqrt(2)*t*sqrt(9*sqrt(109) + 95)/2)*Rational(-1, 14) + C3*(9 + sqrt(109))*sin(sqrt(2)*t*sqrt(95 - 9*sqrt(109))/2)/14 + C4*(9 + sqrt(109))*cos(sqrt(2)*t*sqrt(95 - 9*sqrt(109))/2)*Rational(-1, 14)), Eq(x(t), C1*(9 - sqrt(109))*cos(sqrt(2)*t*sqrt(9*sqrt(109) + 95)/2)*Rational(-1, 14) + C2*(9 - sqrt(109))*sin(sqrt(2)*t*sqrt(9*sqrt(109) + 95)/2)*Rational(-1, 14) + C3*(9 + sqrt(109))*cos(sqrt(2)*t*sqrt(95 - 9*sqrt(109))/2)/14 + C4*(9 + sqrt(109))*sin(sqrt(2)*t*sqrt(95 - 9*sqrt(109))/2)/14)] assert dsolve(eqs11) == sol11 assert checksysodesol(eqs11, sol11) == (True, [0, 0]) # Euler Systems # Note: To add examples of euler systems solver with non-homogeneous term. eqs13 = [Eq(Derivative(f(t), (t, 2)), Derivative(f(t), t)/t + f(t)/t**2 + g(t)/t**2), Eq(Derivative(g(t), (t, 2)), g(t)/t**2)] sol13 = [Eq(f(t), C1*(sqrt(5) + 3)*Rational(-1, 2)*t**(Rational(1, 2) + sqrt(5)*Rational(-1, 2)) + C2*t**(Rational(1, 2) + sqrt(5)/2)*(3 - sqrt(5))*Rational(-1, 2) - C3*t**(1 - sqrt(2))*(1 + sqrt(2)) - C4*t**(1 + sqrt(2))*(1 - sqrt(2))), Eq(g(t), C1*(1 + sqrt(5))*Rational(-1, 2)*t**(Rational(1, 2) + sqrt(5)*Rational(-1, 2)) + C2*t**(Rational(1, 2) + sqrt(5)/2)*(1 - sqrt(5))*Rational(-1, 2))] assert dsolve(eqs13) == sol13 assert checksysodesol(eqs13, sol13) == (True, [0, 0]) # Solving systems using dsolve separately eqs14 = [Eq(Derivative(f(t), (t, 2)), t*f(t)), Eq(Derivative(g(t), (t, 2)), t*g(t))] sol14 = [Eq(f(t), C1*airyai(t) + C2*airybi(t)), Eq(g(t), C3*airyai(t) + C4*airybi(t))] assert dsolve(eqs14) == sol14 assert checksysodesol(eqs14, sol14) == (True, [0, 0]) eqs15 = [Eq(Derivative(x(t), (t, 2)), t*(4*Derivative(x(t), t) + 8*Derivative(y(t), t))), Eq(Derivative(y(t), (t, 2)), t*(12*Derivative(x(t), t) - 6*Derivative(y(t), t)))] sol15 = [Eq(x(t), C1 - erf(sqrt(6)*t)*(sqrt(6)*sqrt(pi)*C2/33 + sqrt(6)*sqrt(pi)*C3*Rational(-1, 44)) + erfi(sqrt(5)*t)*(sqrt(5)*sqrt(pi)*C2*Rational(2, 55) + sqrt(5)*sqrt(pi)*C3*Rational(4, 55))), Eq(y(t), C4 + erf(sqrt(6)*t)*(sqrt(6)*sqrt(pi)*C2*Rational(2, 33) + sqrt(6)*sqrt(pi)*C3*Rational(-1, 22)) + erfi(sqrt(5)*t)*(sqrt(5)*sqrt(pi)*C2*Rational(3, 110) + sqrt(5)*sqrt(pi)*C3*Rational(3, 55)))] assert dsolve(eqs15) == sol15 assert checksysodesol(eqs15, sol15) == (True, [0, 0]) @slow def test_higher_order_to_first_order_9(): f, g = symbols('f g', cls=Function) x = symbols('x') eqs9 = [f(x) + g(x) - 2*exp(I*x) + 2*Derivative(f(x), x) + Derivative(f(x), (x, 2)), f(x) + g(x) - 2*exp(I*x) + 2*Derivative(g(x), x) + Derivative(g(x), (x, 2))] sol9 = [Eq(f(x), -C1 + C2*exp(-2*x)/2 + (C3/2 + C4/2)*exp(-x)*sin(x) + (2 + I)*exp(I*x)*sin(x)**2*Rational(-1, 5) + (1 - 2*I)*exp(I*x)*sin(x)*cos(x)*Rational(2, 5) + (4 - 3*I)*exp(I*x)*cos(x)**2/5 + exp(-x)*sin(x)*Integral(-exp(x)*exp(I*x)*sin(x)**2/cos(x) + exp(x)*exp(I*x)*sin(x) + exp(x)*exp(I*x)/cos(x), x) - exp(-x)*cos(x)*Integral(-exp(x)*exp(I*x)*sin(x)**2/cos(x) + exp(x)*exp(I*x)*sin(x) + exp(x)*exp(I*x)/cos(x), x) - exp(-x)*cos(x)*(C3/2 + C4*Rational(-1, 2))), Eq(g(x), C1 + C2*exp(-2*x)*Rational(-1, 2) + (C3/2 + C4/2)*exp(-x)*sin(x) + (2 + I)*exp(I*x)*sin(x)**2*Rational(-1, 5) + (1 - 2*I)*exp(I*x)*sin(x)*cos(x)*Rational(2, 5) + (4 - 3*I)*exp(I*x)*cos(x)**2/5 + exp(-x)*sin(x)*Integral(-exp(x)*exp(I*x)*sin(x)**2/cos(x) + exp(x)*exp(I*x)*sin(x) + exp(x)*exp(I*x)/cos(x), x) - exp(-x)*cos(x)*Integral(-exp(x)*exp(I*x)*sin(x)**2/cos(x) + exp(x)*exp(I*x)*sin(x) + exp(x)*exp(I*x)/cos(x), x) - exp(-x)*cos(x)*(C3/2 + C4*Rational(-1, 2)))] assert dsolve(eqs9) == sol9 assert checksysodesol(eqs9, sol9) == (True, [0, 0]) def test_higher_order_to_first_order_12(): f, g = symbols('f g', cls=Function) x = symbols('x') x, y = symbols('x, y', cls=Function) t, l = symbols('t, l') eqs12 = [Eq(4*x(t) + Derivative(x(t), (t, 2)) + 8*Derivative(y(t), t), 0), Eq(4*y(t) - 8*Derivative(x(t), t) + Derivative(y(t), (t, 2)), 0)] sol12 = [Eq(y(t), C1*(2 - sqrt(5))*sin(2*t*sqrt(4*sqrt(5) + 9))*Rational(-1, 2) + C2*(2 - sqrt(5))*cos(2*t*sqrt(4*sqrt(5) + 9))/2 + C3*(2 + sqrt(5))*sin(2*t*sqrt(9 - 4*sqrt(5)))*Rational(-1, 2) + C4*(2 + sqrt(5))*cos(2*t*sqrt(9 - 4*sqrt(5)))/2), Eq(x(t), C1*(2 - sqrt(5))*cos(2*t*sqrt(4*sqrt(5) + 9))*Rational(-1, 2) + C2*(2 - sqrt(5))*sin(2*t*sqrt(4*sqrt(5) + 9))*Rational(-1, 2) + C3*(2 + sqrt(5))*cos(2*t*sqrt(9 - 4*sqrt(5)))/2 + C4*(2 + sqrt(5))*sin(2*t*sqrt(9 - 4*sqrt(5)))/2)] assert dsolve(eqs12) == sol12 assert checksysodesol(eqs12, sol12) == (True, [0, 0]) def test_second_order_to_first_order_2(): f, g = symbols("f g", cls=Function) x, t, x_, t_, d, a, m = symbols("x t x_ t_ d a m") eqs2 = [Eq(f(x).diff(x, 2), 2*(x*g(x).diff(x) - g(x))), Eq(g(x).diff(x, 2),-2*(x*f(x).diff(x) - f(x)))] sol2 = [Eq(f(x), C1*x + x*Integral(C2*exp(-x_)*exp(I*exp(2*x_))/2 + C2*exp(-x_)*exp(-I*exp(2*x_))/2 - I*C3*exp(-x_)*exp(I*exp(2*x_))/2 + I*C3*exp(-x_)*exp(-I*exp(2*x_))/2, (x_, log(x)))), Eq(g(x), C4*x + x*Integral(I*C2*exp(-x_)*exp(I*exp(2*x_))/2 - I*C2*exp(-x_)*exp(-I*exp(2*x_))/2 + C3*exp(-x_)*exp(I*exp(2*x_))/2 + C3*exp(-x_)*exp(-I*exp(2*x_))/2, (x_, log(x))))] # XXX: dsolve hangs for this in integration assert dsolve_system(eqs2, simplify=False, doit=False) == [sol2] assert checksysodesol(eqs2, sol2) == (True, [0, 0]) eqs3 = (Eq(diff(f(t),t,t), 9*t*diff(g(t),t)-9*g(t)), Eq(diff(g(t),t,t),7*t*diff(f(t),t)-7*f(t))) sol3 = [Eq(f(t), C1*t + t*Integral(C2*exp(-t_)*exp(3*sqrt(7)*exp(2*t_)/2)/2 + C2*exp(-t_)* exp(-3*sqrt(7)*exp(2*t_)/2)/2 + 3*sqrt(7)*C3*exp(-t_)*exp(3*sqrt(7)*exp(2*t_)/2)/14 - 3*sqrt(7)*C3*exp(-t_)*exp(-3*sqrt(7)*exp(2*t_)/2)/14, (t_, log(t)))), Eq(g(t), C4*t + t*Integral(sqrt(7)*C2*exp(-t_)*exp(3*sqrt(7)*exp(2*t_)/2)/6 - sqrt(7)*C2*exp(-t_)* exp(-3*sqrt(7)*exp(2*t_)/2)/6 + C3*exp(-t_)*exp(3*sqrt(7)*exp(2*t_)/2)/2 + C3*exp(-t_)*exp(-3*sqrt(7)* exp(2*t_)/2)/2, (t_, log(t))))] # XXX: dsolve hangs for this in integration assert dsolve_system(eqs3, simplify=False, doit=False) == [sol3] assert checksysodesol(eqs3, sol3) == (True, [0, 0]) # Regression Test case for sympy#19238 # https://github.com/sympy/sympy/issues/19238 # Note: When the doit method is removed, these particular types of systems # can be divided first so that we have lesser number of big matrices. eqs5 = [Eq(Derivative(g(t), (t, 2)), a*m), Eq(Derivative(f(t), (t, 2)), 0)] sol5 = [Eq(g(t), C1 + C2*t + a*m*t**2/2), Eq(f(t), C3 + C4*t)] assert dsolve(eqs5) == sol5 assert checksysodesol(eqs5, sol5) == (True, [0, 0]) # Type 2 eqs6 = [Eq(Derivative(f(t), (t, 2)), f(t)/t**4), Eq(Derivative(g(t), (t, 2)), d*g(t)/t**4)] sol6 = [Eq(f(t), C1*sqrt(t**2)*exp(-1/t) - C2*sqrt(t**2)*exp(1/t)), Eq(g(t), C3*sqrt(t**2)*exp(-sqrt(d)/t)*d**Rational(-1, 2) - C4*sqrt(t**2)*exp(sqrt(d)/t)*d**Rational(-1, 2))] assert dsolve(eqs6) == sol6 assert checksysodesol(eqs6, sol6) == (True, [0, 0]) @slow def test_second_order_to_first_order_slow1(): f, g = symbols("f g", cls=Function) x, t, x_, t_, d, a, m = symbols("x t x_ t_ d a m") # Type 1 eqs1 = [Eq(f(x).diff(x, 2), 2/x *(x*g(x).diff(x) - g(x))), Eq(g(x).diff(x, 2),-2/x *(x*f(x).diff(x) - f(x)))] sol1 = [Eq(f(x), C1*x + 2*C2*x*Ci(2*x) - C2*sin(2*x) - 2*C3*x*Si(2*x) - C3*cos(2*x)), Eq(g(x), -2*C2*x*Si(2*x) - C2*cos(2*x) - 2*C3*x*Ci(2*x) + C3*sin(2*x) + C4*x)] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0]) def test_second_order_to_first_order_slow4(): f, g = symbols("f g", cls=Function) x, t, x_, t_, d, a, m = symbols("x t x_ t_ d a m") eqs4 = [Eq(Derivative(f(t), (t, 2)), t*sin(t)*Derivative(g(t), t) - g(t)*sin(t)), Eq(Derivative(g(t), (t, 2)), t*sin(t)*Derivative(f(t), t) - f(t)*sin(t))] sol4 = [Eq(f(t), C1*t + t*Integral(C2*exp(-t_)*exp(exp(t_)*cos(exp(t_)))*exp(-sin(exp(t_)))/2 + C2*exp(-t_)*exp(-exp(t_)*cos(exp(t_)))*exp(sin(exp(t_)))/2 - C3*exp(-t_)*exp(exp(t_)*cos(exp(t_)))* exp(-sin(exp(t_)))/2 + C3*exp(-t_)*exp(-exp(t_)*cos(exp(t_)))*exp(sin(exp(t_)))/2, (t_, log(t)))), Eq(g(t), C4*t + t*Integral(-C2*exp(-t_)*exp(exp(t_)*cos(exp(t_)))*exp(-sin(exp(t_)))/2 + C2*exp(-t_)*exp(-exp(t_)*cos(exp(t_)))*exp(sin(exp(t_)))/2 + C3*exp(-t_)*exp(exp(t_)*cos(exp(t_)))* exp(-sin(exp(t_)))/2 + C3*exp(-t_)*exp(-exp(t_)*cos(exp(t_)))*exp(sin(exp(t_)))/2, (t_, log(t))))] # XXX: dsolve hangs for this in integration assert dsolve_system(eqs4, simplify=False, doit=False) == [sol4] assert checksysodesol(eqs4, sol4) == (True, [0, 0]) def test_component_division(): f, g, h, k = symbols('f g h k', cls=Function) x = symbols("x") funcs = [f(x), g(x), h(x), k(x)] eqs1 = [Eq(Derivative(f(x), x), 2*f(x)), Eq(Derivative(g(x), x), f(x)), Eq(Derivative(h(x), x), h(x)), Eq(Derivative(k(x), x), h(x)**4 + k(x))] sol1 = [Eq(f(x), 2*C1*exp(2*x)), Eq(g(x), C1*exp(2*x) + C2), Eq(h(x), C3*exp(x)), Eq(k(x), C3**4*exp(4*x)/3 + C4*exp(x))] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0, 0, 0]) components1 = {((Eq(Derivative(f(x), x), 2*f(x)),), (Eq(Derivative(g(x), x), f(x)),)), ((Eq(Derivative(h(x), x), h(x)),), (Eq(Derivative(k(x), x), h(x)**4 + k(x)),))} eqsdict1 = ({f(x): set(), g(x): {f(x)}, h(x): set(), k(x): {h(x)}}, {f(x): Eq(Derivative(f(x), x), 2*f(x)), g(x): Eq(Derivative(g(x), x), f(x)), h(x): Eq(Derivative(h(x), x), h(x)), k(x): Eq(Derivative(k(x), x), h(x)**4 + k(x))}) graph1 = [{f(x), g(x), h(x), k(x)}, {(g(x), f(x)), (k(x), h(x))}] assert {tuple(tuple(scc) for scc in wcc) for wcc in _component_division(eqs1, funcs, x)} == components1 assert _eqs2dict(eqs1, funcs) == eqsdict1 assert [set(element) for element in _dict2graph(eqsdict1[0])] == graph1 eqs2 = [Eq(Derivative(f(x), x), 2*f(x)), Eq(Derivative(g(x), x), f(x)), Eq(Derivative(h(x), x), h(x)), Eq(Derivative(k(x), x), f(x)**4 + k(x))] sol2 = [Eq(f(x), C1*exp(2*x)), Eq(g(x), C1*exp(2*x)/2 + C2), Eq(h(x), C3*exp(x)), Eq(k(x), C1**4*exp(8*x)/7 + C4*exp(x))] assert dsolve(eqs2) == sol2 assert checksysodesol(eqs2, sol2) == (True, [0, 0, 0, 0]) components2 = {frozenset([(Eq(Derivative(f(x), x), 2*f(x)),), (Eq(Derivative(g(x), x), f(x)),), (Eq(Derivative(k(x), x), f(x)**4 + k(x)),)]), frozenset([(Eq(Derivative(h(x), x), h(x)),)])} eqsdict2 = ({f(x): set(), g(x): {f(x)}, h(x): set(), k(x): {f(x)}}, {f(x): Eq(Derivative(f(x), x), 2*f(x)), g(x): Eq(Derivative(g(x), x), f(x)), h(x): Eq(Derivative(h(x), x), h(x)), k(x): Eq(Derivative(k(x), x), f(x)**4 + k(x))}) graph2 = [{f(x), g(x), h(x), k(x)}, {(g(x), f(x)), (k(x), f(x))}] assert {frozenset(tuple(scc) for scc in wcc) for wcc in _component_division(eqs2, funcs, x)} == components2 assert _eqs2dict(eqs2, funcs) == eqsdict2 assert [set(element) for element in _dict2graph(eqsdict2[0])] == graph2 eqs3 = [Eq(Derivative(f(x), x), 2*f(x)), Eq(Derivative(g(x), x), x + f(x)), Eq(Derivative(h(x), x), h(x)), Eq(Derivative(k(x), x), f(x)**4 + k(x))] sol3 = [Eq(f(x), C1*exp(2*x)), Eq(g(x), C1*exp(2*x)/2 + C2 + x**2/2), Eq(h(x), C3*exp(x)), Eq(k(x), C1**4*exp(8*x)/7 + C4*exp(x))] assert dsolve(eqs3) == sol3 assert checksysodesol(eqs3, sol3) == (True, [0, 0, 0, 0]) components3 = {frozenset([(Eq(Derivative(f(x), x), 2*f(x)),), (Eq(Derivative(g(x), x), x + f(x)),), (Eq(Derivative(k(x), x), f(x)**4 + k(x)),)]), frozenset([(Eq(Derivative(h(x), x), h(x)),),])} eqsdict3 = ({f(x): set(), g(x): {f(x)}, h(x): set(), k(x): {f(x)}}, {f(x): Eq(Derivative(f(x), x), 2*f(x)), g(x): Eq(Derivative(g(x), x), x + f(x)), h(x): Eq(Derivative(h(x), x), h(x)), k(x): Eq(Derivative(k(x), x), f(x)**4 + k(x))}) graph3 = [{f(x), g(x), h(x), k(x)}, {(g(x), f(x)), (k(x), f(x))}] assert {frozenset(tuple(scc) for scc in wcc) for wcc in _component_division(eqs3, funcs, x)} == components3 assert _eqs2dict(eqs3, funcs) == eqsdict3 assert [set(l) for l in _dict2graph(eqsdict3[0])] == graph3 # Note: To be uncommented when the default option to call dsolve first for # single ODE system can be rearranged. This can be done after the doit # option in dsolve is made False by default. eqs4 = [Eq(Derivative(f(x), x), x*f(x) + 2*g(x)), Eq(Derivative(g(x), x), f(x) + x*g(x) + x), Eq(Derivative(h(x), x), h(x)), Eq(Derivative(k(x), x), f(x)**4 + k(x))] sol4 = [Eq(f(x), (C1/2 - sqrt(2)*C2/2 - sqrt(2)*Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 + x*exp(-x**2/2 +\ sqrt(2)*x)/2, x)/2 + Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 - sqrt(2)*x*exp(-x**2/2 +\ sqrt(2)*x)/2, x)/2)*exp(x**2/2 - sqrt(2)*x) + (C1/2 + sqrt(2)*C2/2 + sqrt(2)*Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 + x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2 + Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 - sqrt(2)*x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2)*exp(x**2/2 + sqrt(2)*x)), Eq(g(x), (-sqrt(2)*C1/4 + C2/2 + Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 + x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2 -\ sqrt(2)*Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 - sqrt(2)*x*exp(-x**2/2 + sqrt(2)*x)/2, x)/4)*exp(x**2/2 - sqrt(2)*x) + (sqrt(2)*C1/4 + C2/2 + Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 + x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2 + sqrt(2)*Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 - sqrt(2)*x*exp(-x**2/2 + sqrt(2)*x)/2, x)/4)*exp(x**2/2 + sqrt(2)*x)), Eq(h(x), C3*exp(x)), Eq(k(x), C4*exp(x) + exp(x)*Integral((C1*exp(x**2/2 - sqrt(2)*x)/2 + C1*exp(x**2/2 + sqrt(2)*x)/2 - sqrt(2)*C2*exp(x**2/2 - sqrt(2)*x)/2 + sqrt(2)*C2*exp(x**2/2 + sqrt(2)*x)/2 - sqrt(2)*exp(x**2/2 - sqrt(2)*x)*Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 + x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2 + exp(x**2/2 - sqrt(2)*x)*Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 - sqrt(2)*x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2 + sqrt(2)*exp(x**2/2 + sqrt(2)*x)*Integral(x*exp(-x**2/2 - sqrt(2)*x)/2 + x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2 + exp(x**2/2 + sqrt(2)*x)*Integral(sqrt(2)*x*exp(-x**2/2 - sqrt(2)*x)/2 - sqrt(2)*x*exp(-x**2/2 + sqrt(2)*x)/2, x)/2)**4*exp(-x), x))] components4 = {(frozenset([Eq(Derivative(f(x), x), x*f(x) + 2*g(x)), Eq(Derivative(g(x), x), x*g(x) + x + f(x))]), frozenset([Eq(Derivative(k(x), x), f(x)**4 + k(x)),])), (frozenset([Eq(Derivative(h(x), x), h(x)),]),)} eqsdict4 = ({f(x): {g(x)}, g(x): {f(x)}, h(x): set(), k(x): {f(x)}}, {f(x): Eq(Derivative(f(x), x), x*f(x) + 2*g(x)), g(x): Eq(Derivative(g(x), x), x*g(x) + x + f(x)), h(x): Eq(Derivative(h(x), x), h(x)), k(x): Eq(Derivative(k(x), x), f(x)**4 + k(x))}) graph4 = [{f(x), g(x), h(x), k(x)}, {(f(x), g(x)), (g(x), f(x)), (k(x), f(x))}] assert {tuple(frozenset(scc) for scc in wcc) for wcc in _component_division(eqs4, funcs, x)} == components4 assert _eqs2dict(eqs4, funcs) == eqsdict4 assert [set(element) for element in _dict2graph(eqsdict4[0])] == graph4 # XXX: dsolve hangs in integration here: assert dsolve_system(eqs4, simplify=False, doit=False) == [sol4] assert checksysodesol(eqs4, sol4) == (True, [0, 0, 0, 0]) eqs5 = [Eq(Derivative(f(x), x), x*f(x) + 2*g(x)), Eq(Derivative(g(x), x), x*g(x) + f(x)), Eq(Derivative(h(x), x), h(x)), Eq(Derivative(k(x), x), f(x)**4 + k(x))] sol5 = [Eq(f(x), (C1/2 - sqrt(2)*C2/2)*exp(x**2/2 - sqrt(2)*x) + (C1/2 + sqrt(2)*C2/2)*exp(x**2/2 + sqrt(2)*x)), Eq(g(x), (-sqrt(2)*C1/4 + C2/2)*exp(x**2/2 - sqrt(2)*x) + (sqrt(2)*C1/4 + C2/2)*exp(x**2/2 + sqrt(2)*x)), Eq(h(x), C3*exp(x)), Eq(k(x), C4*exp(x) + exp(x)*Integral((C1*exp(x**2/2 - sqrt(2)*x)/2 + C1*exp(x**2/2 + sqrt(2)*x)/2 - sqrt(2)*C2*exp(x**2/2 - sqrt(2)*x)/2 + sqrt(2)*C2*exp(x**2/2 + sqrt(2)*x)/2)**4*exp(-x), x))] components5 = {(frozenset([Eq(Derivative(f(x), x), x*f(x) + 2*g(x)), Eq(Derivative(g(x), x), x*g(x) + f(x))]), frozenset([Eq(Derivative(k(x), x), f(x)**4 + k(x)),])), (frozenset([Eq(Derivative(h(x), x), h(x)),]),)} eqsdict5 = ({f(x): {g(x)}, g(x): {f(x)}, h(x): set(), k(x): {f(x)}}, {f(x): Eq(Derivative(f(x), x), x*f(x) + 2*g(x)), g(x): Eq(Derivative(g(x), x), x*g(x) + f(x)), h(x): Eq(Derivative(h(x), x), h(x)), k(x): Eq(Derivative(k(x), x), f(x)**4 + k(x))}) graph5 = [{f(x), g(x), h(x), k(x)}, {(f(x), g(x)), (g(x), f(x)), (k(x), f(x))}] assert {tuple(frozenset(scc) for scc in wcc) for wcc in _component_division(eqs5, funcs, x)} == components5 assert _eqs2dict(eqs5, funcs) == eqsdict5 assert [set(element) for element in _dict2graph(eqsdict5[0])] == graph5 # XXX: dsolve hangs in integration here: assert dsolve_system(eqs5, simplify=False, doit=False) == [sol5] assert checksysodesol(eqs5, sol5) == (True, [0, 0, 0, 0]) def test_linodesolve(): t, x, a = symbols("t x a") f, g, h = symbols("f g h", cls=Function) # Testing the Errors raises(ValueError, lambda: linodesolve(1, t)) raises(ValueError, lambda: linodesolve(a, t)) A1 = Matrix([[1, 2], [2, 4], [4, 6]]) raises(NonSquareMatrixError, lambda: linodesolve(A1, t)) A2 = Matrix([[1, 2, 1], [3, 1, 2]]) raises(NonSquareMatrixError, lambda: linodesolve(A2, t)) # Testing auto functionality func = [f(t), g(t)] eq = [Eq(f(t).diff(t) + g(t).diff(t), g(t)), Eq(g(t).diff(t), f(t))] ceq = canonical_odes(eq, func, t) (A1, A0), b = linear_ode_to_matrix(ceq[0], func, t, 1) A = A0 sol = [C1*(-Rational(1, 2) + sqrt(5)/2)*exp(t*(-Rational(1, 2) + sqrt(5)/2)) + C2*(-sqrt(5)/2 - Rational(1, 2))* exp(t*(-sqrt(5)/2 - Rational(1, 2))), C1*exp(t*(-Rational(1, 2) + sqrt(5)/2)) + C2*exp(t*(-sqrt(5)/2 - Rational(1, 2)))] assert constant_renumber(linodesolve(A, t), variables=Tuple(*eq).free_symbols) == sol # Testing the Errors raises(ValueError, lambda: linodesolve(1, t, b=Matrix([t+1]))) raises(ValueError, lambda: linodesolve(a, t, b=Matrix([log(t) + sin(t)]))) raises(ValueError, lambda: linodesolve(Matrix([7]), t, b=t**2)) raises(ValueError, lambda: linodesolve(Matrix([a+10]), t, b=log(t)*cos(t))) raises(ValueError, lambda: linodesolve(7, t, b=t**2)) raises(ValueError, lambda: linodesolve(a, t, b=log(t) + sin(t))) A1 = Matrix([[1, 2], [2, 4], [4, 6]]) b1 = Matrix([t, 1, t**2]) raises(NonSquareMatrixError, lambda: linodesolve(A1, t, b=b1)) A2 = Matrix([[1, 2, 1], [3, 1, 2]]) b2 = Matrix([t, t**2]) raises(NonSquareMatrixError, lambda: linodesolve(A2, t, b=b2)) raises(ValueError, lambda: linodesolve(A1[:2, :], t, b=b1)) raises(ValueError, lambda: linodesolve(A1[:2, :], t, b=b1[:1])) # DOIT check A1 = Matrix([[1, -1], [1, -1]]) b1 = Matrix([15*t - 10, -15*t - 5]) sol1 = [C1 + C2*t + C2 - 10*t**3 + 10*t**2 + t*(15*t**2 - 5*t) - 10*t, C1 + C2*t - 10*t**3 - 5*t**2 + t*(15*t**2 - 5*t) - 5*t] assert constant_renumber(linodesolve(A1, t, b=b1, type="type2", doit=True), variables=[t]) == sol1 # Testing auto functionality func = [f(t), g(t)] eq = [Eq(f(t).diff(t) + g(t).diff(t), g(t) + t), Eq(g(t).diff(t), f(t))] ceq = canonical_odes(eq, func, t) (A1, A0), b = linear_ode_to_matrix(ceq[0], func, t, 1) A = A0 sol = [-C1*exp(-t/2 + sqrt(5)*t/2)/2 + sqrt(5)*C1*exp(-t/2 + sqrt(5)*t/2)/2 - sqrt(5)*C2*exp(-sqrt(5)*t/2 - t/2)/2 - C2*exp(-sqrt(5)*t/2 - t/2)/2 - exp(-t/2 + sqrt(5)*t/2)*Integral(t*exp(-sqrt(5)*t/2 + t/2)/(-5 + sqrt(5)) - sqrt(5)*t*exp(-sqrt(5)*t/2 + t/2)/(-5 + sqrt(5)), t)/2 + sqrt(5)*exp(-t/2 + sqrt(5)*t/2)*Integral(t*exp(-sqrt(5)*t/2 + t/2)/(-5 + sqrt(5)) - sqrt(5)*t*exp(-sqrt(5)*t/2 + t/2)/(-5 + sqrt(5)), t)/2 - sqrt(5)*exp(-sqrt(5)*t/2 - t/2)*Integral(-sqrt(5)*t*exp(t/2 + sqrt(5)*t/2)/5, t)/2 - exp(-sqrt(5)*t/2 - t/2)*Integral(-sqrt(5)*t*exp(t/2 + sqrt(5)*t/2)/5, t)/2, C1*exp(-t/2 + sqrt(5)*t/2) + C2*exp(-sqrt(5)*t/2 - t/2) + exp(-t/2 + sqrt(5)*t/2)*Integral(t*exp(-sqrt(5)*t/2 + t/2)/(-5 + sqrt(5)) - sqrt(5)*t*exp(-sqrt(5)*t/2 + t/2)/(-5 + sqrt(5)), t) + exp(-sqrt(5)*t/2 - t/2)*Integral(-sqrt(5)*t*exp(t/2 + sqrt(5)*t/2)/5, t)] assert constant_renumber(linodesolve(A, t, b=b), variables=[t]) == sol # non-homogeneous term assumed to be 0 sol1 = [-C1*exp(-t/2 + sqrt(5)*t/2)/2 + sqrt(5)*C1*exp(-t/2 + sqrt(5)*t/2)/2 - sqrt(5)*C2*exp(-sqrt(5)*t/2 - t/2)/2 - C2*exp(-sqrt(5)*t/2 - t/2)/2 - exp(-t/2 + sqrt(5)*t/2)*Integral(0, t)/2 + sqrt(5)*exp(-t/2 + sqrt(5)*t/2)*Integral(0, t)/2 - sqrt(5)*exp(-sqrt(5)*t/2 - t/2)*Integral(0, t)/2 - exp(-sqrt(5)*t/2 - t/2)*Integral(0, t)/2, C1*exp(-t/2 + sqrt(5)*t/2) + C2*exp(-sqrt(5)*t/2 - t/2) + exp(-t/2 + sqrt(5)*t/2)*Integral(0, t) + exp(-sqrt(5)*t/2 - t/2)*Integral(0, t)] assert constant_renumber(linodesolve(A, t, type="type2"), variables=[t]) == sol1 # Testing the Errors raises(ValueError, lambda: linodesolve(t+10, t)) raises(ValueError, lambda: linodesolve(a*t, t)) A1 = Matrix([[1, t], [-t, 1]]) B1, _ = _is_commutative_anti_derivative(A1, t) raises(NonSquareMatrixError, lambda: linodesolve(A1[:, :1], t, B=B1)) raises(ValueError, lambda: linodesolve(A1, t, B=1)) A2 = Matrix([[t, t, t], [t, t, t], [t, t, t]]) B2, _ = _is_commutative_anti_derivative(A2, t) raises(NonSquareMatrixError, lambda: linodesolve(A2, t, B=B2[:2, :])) raises(ValueError, lambda: linodesolve(A2, t, B=2)) raises(ValueError, lambda: linodesolve(A2, t, B=B2, type="type31")) raises(ValueError, lambda: linodesolve(A1, t, B=B2)) raises(ValueError, lambda: linodesolve(A2, t, B=B1)) # Testing auto functionality func = [f(t), g(t)] eq = [Eq(f(t).diff(t), f(t) + t*g(t)), Eq(g(t).diff(t), -t*f(t) + g(t))] ceq = canonical_odes(eq, func, t) (A1, A0), b = linear_ode_to_matrix(ceq[0], func, t, 1) A = A0 sol = [(C1/2 - I*C2/2)*exp(I*t**2/2 + t) + (C1/2 + I*C2/2)*exp(-I*t**2/2 + t), (-I*C1/2 + C2/2)*exp(-I*t**2/2 + t) + (I*C1/2 + C2/2)*exp(I*t**2/2 + t)] assert constant_renumber(linodesolve(A, t), variables=Tuple(*eq).free_symbols) == sol assert constant_renumber(linodesolve(A, t, type="type3"), variables=Tuple(*eq).free_symbols) == sol A1 = Matrix([[t, 1], [t, -1]]) raises(NotImplementedError, lambda: linodesolve(A1, t)) # Testing the Errors raises(ValueError, lambda: linodesolve(t+10, t, b=Matrix([t+1]))) raises(ValueError, lambda: linodesolve(a*t, t, b=Matrix([log(t) + sin(t)]))) raises(ValueError, lambda: linodesolve(Matrix([7*t]), t, b=t**2)) raises(ValueError, lambda: linodesolve(Matrix([a + 10*log(t)]), t, b=log(t)*cos(t))) raises(ValueError, lambda: linodesolve(7*t, t, b=t**2)) raises(ValueError, lambda: linodesolve(a*t**2, t, b=log(t) + sin(t))) A1 = Matrix([[1, t], [-t, 1]]) b1 = Matrix([t, t ** 2]) B1, _ = _is_commutative_anti_derivative(A1, t) raises(NonSquareMatrixError, lambda: linodesolve(A1[:, :1], t, b=b1)) A2 = Matrix([[t, t, t], [t, t, t], [t, t, t]]) b2 = Matrix([t, 1, t**2]) B2, _ = _is_commutative_anti_derivative(A2, t) raises(NonSquareMatrixError, lambda: linodesolve(A2[:2, :], t, b=b2)) raises(ValueError, lambda: linodesolve(A1, t, b=b2)) raises(ValueError, lambda: linodesolve(A2, t, b=b1)) raises(ValueError, lambda: linodesolve(A1, t, b=b1, B=B2)) raises(ValueError, lambda: linodesolve(A2, t, b=b2, B=B1)) # Testing auto functionality func = [f(x), g(x), h(x)] eq = [Eq(f(x).diff(x), x*(f(x) + g(x) + h(x)) + x), Eq(g(x).diff(x), x*(f(x) + g(x) + h(x)) + x), Eq(h(x).diff(x), x*(f(x) + g(x) + h(x)) + 1)] ceq = canonical_odes(eq, func, x) (A1, A0), b = linear_ode_to_matrix(ceq[0], func, x, 1) A = A0 _x1 = exp(-3*x**2/2) _x2 = exp(3*x**2/2) _x3 = Integral(2*_x1*x/3 + _x1/3 + x/3 - Rational(1, 3), x) _x4 = 2*_x2*_x3/3 _x5 = Integral(2*_x1*x/3 + _x1/3 - 2*x/3 + Rational(2, 3), x) sol = [ C1*_x2/3 - C1/3 + C2*_x2/3 - C2/3 + C3*_x2/3 + 2*C3/3 + _x2*_x5/3 + _x3/3 + _x4 - _x5/3, C1*_x2/3 + 2*C1/3 + C2*_x2/3 - C2/3 + C3*_x2/3 - C3/3 + _x2*_x5/3 + _x3/3 + _x4 - _x5/3, C1*_x2/3 - C1/3 + C2*_x2/3 + 2*C2/3 + C3*_x2/3 - C3/3 + _x2*_x5/3 - 2*_x3/3 + _x4 + 2*_x5/3, ] assert constant_renumber(linodesolve(A, x, b=b), variables=Tuple(*eq).free_symbols) == sol assert constant_renumber(linodesolve(A, x, b=b, type="type4"), variables=Tuple(*eq).free_symbols) == sol A1 = Matrix([[t, 1], [t, -1]]) raises(NotImplementedError, lambda: linodesolve(A1, t, b=b1)) # non-homogeneous term not passed sol1 = [-C1/3 - C2/3 + 2*C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2), 2*C1/3 - C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2), -C1/3 + 2*C2/3 - C3/3 + (C1/3 + C2/3 + C3/3)*exp(3*x**2/2)] assert constant_renumber(linodesolve(A, x, type="type4", doit=True), variables=Tuple(*eq).free_symbols) == sol1 @slow def test_linear_3eq_order1_type4_slow(): x, y, z = symbols('x, y, z', cls=Function) t = Symbol('t') f = t ** 3 + log(t) g = t ** 2 + sin(t) eq1 = (Eq(diff(x(t), t), (4 * f + g) * x(t) - f * y(t) - 2 * f * z(t)), Eq(diff(y(t), t), 2 * f * x(t) + (f + g) * y(t) - 2 * f * z(t)), Eq(diff(z(t), t), 5 * f * x(t) + f * y( t) + (-3 * f + g) * z(t))) with dotprodsimp(True): dsolve(eq1) @slow def test_linear_neq_order1_type2_slow1(): i, r1, c1, r2, c2, t = symbols('i, r1, c1, r2, c2, t') x1 = Function('x1') x2 = Function('x2') eq1 = r1*c1*Derivative(x1(t), t) + x1(t) - x2(t) - r1*i eq2 = r2*c1*Derivative(x1(t), t) + r2*c2*Derivative(x2(t), t) + x2(t) - r2*i eq = [eq1, eq2] # XXX: Solution is too complicated [sol] = dsolve_system(eq, simplify=False, doit=False) assert checksysodesol(eq, sol) == (True, [0, 0]) # Regression test case for issue #9204 # https://github.com/sympy/sympy/issues/9204 @slow def test_linear_new_order1_type2_de_lorentz_slow_check(): if ON_TRAVIS: skip("Too slow for travis.") m = Symbol("m", real=True) q = Symbol("q", real=True) t = Symbol("t", real=True) e1, e2, e3 = symbols("e1:4", real=True) b1, b2, b3 = symbols("b1:4", real=True) v1, v2, v3 = symbols("v1:4", cls=Function, real=True) eqs = [ -e1*q + m*Derivative(v1(t), t) - q*(-b2*v3(t) + b3*v2(t)), -e2*q + m*Derivative(v2(t), t) - q*(b1*v3(t) - b3*v1(t)), -e3*q + m*Derivative(v3(t), t) - q*(-b1*v2(t) + b2*v1(t)) ] sol = dsolve(eqs) assert checksysodesol(eqs, sol) == (True, [0, 0, 0]) # Regression test case for issue #14001 # https://github.com/sympy/sympy/issues/14001 @slow def test_linear_neq_order1_type2_slow_check(): RC, t, C, Vs, L, R1, V0, I0 = symbols("RC t C Vs L R1 V0 I0") V = Function("V") I = Function("I") system = [Eq(V(t).diff(t), -1/RC*V(t) + I(t)/C), Eq(I(t).diff(t), -R1/L*I(t) - 1/L*V(t) + Vs/L)] [sol] = dsolve_system(system, simplify=False, doit=False) assert checksysodesol(system, sol) == (True, [0, 0]) def _linear_3eq_order1_type4_long(): x, y, z = symbols('x, y, z', cls=Function) t = Symbol('t') f = t ** 3 + log(t) g = t ** 2 + sin(t) eq1 = (Eq(diff(x(t), t), (4*f + g)*x(t) - f*y(t) - 2*f*z(t)), Eq(diff(y(t), t), 2*f*x(t) + (f + g)*y(t) - 2*f*z(t)), Eq(diff(z(t), t), 5*f*x(t) + f*y( t) + (-3*f + g)*z(t))) dsolve_sol = dsolve(eq1) dsolve_sol1 = [_simpsol(sol) for sol in dsolve_sol] x_1 = sqrt(-t**6 - 8*t**3*log(t) + 8*t**3 - 16*log(t)**2 + 32*log(t) - 16) x_2 = sqrt(3) x_3 = 8324372644*C1*x_1*x_2 + 4162186322*C2*x_1*x_2 - 8324372644*C3*x_1*x_2 x_4 = 1 / (1903457163*t**3 + 3825881643*x_1*x_2 + 7613828652*log(t) - 7613828652) x_5 = exp(t**3/3 + t*x_1*x_2/4 - cos(t)) x_6 = exp(t**3/3 - t*x_1*x_2/4 - cos(t)) x_7 = exp(t**4/2 + t**3/3 + 2*t*log(t) - 2*t - cos(t)) x_8 = 91238*C1*x_1*x_2 + 91238*C2*x_1*x_2 - 91238*C3*x_1*x_2 x_9 = 1 / (66049*t**3 - 50629*x_1*x_2 + 264196*log(t) - 264196) x_10 = 50629 * C1 / 25189 + 37909*C2/25189 - 50629*C3/25189 - x_3*x_4 x_11 = -50629*C1/25189 - 12720*C2/25189 + 50629*C3/25189 + x_3*x_4 sol = [Eq(x(t), x_10*x_5 + x_11*x_6 + x_7*(C1 - C2)), Eq(y(t), x_10*x_5 + x_11*x_6), Eq(z(t), x_5*( -424*C1/257 - 167*C2/257 + 424*C3/257 - x_8*x_9) + x_6*(167*C1/257 + 424*C2/257 - 167*C3/257 + x_8*x_9) + x_7*(C1 - C2))] assert dsolve_sol1 == sol assert checksysodesol(eq1, dsolve_sol1) == (True, [0, 0, 0]) @slow def test_neq_order1_type4_slow_check1(): f, g = symbols("f g", cls=Function) x = symbols("x") eqs = [Eq(diff(f(x), x), x*f(x) + x**2*g(x) + x), Eq(diff(g(x), x), 2*x**2*f(x) + (x + 3*x**2)*g(x) + 1)] sol = dsolve(eqs) assert checksysodesol(eqs, sol) == (True, [0, 0]) @slow def test_neq_order1_type4_slow_check2(): f, g, h = symbols("f, g, h", cls=Function) x = Symbol("x") eqs = [ Eq(Derivative(f(x), x), x*h(x) + f(x) + g(x) + 1), Eq(Derivative(g(x), x), x*g(x) + f(x) + h(x) + 10), Eq(Derivative(h(x), x), x*f(x) + x + g(x) + h(x)) ] with dotprodsimp(True): sol = dsolve(eqs) assert checksysodesol(eqs, sol) == (True, [0, 0, 0]) def _neq_order1_type4_slow3(): f, g = symbols("f g", cls=Function) x = symbols("x") eqs = [ Eq(Derivative(f(x), x), x*f(x) + g(x) + sin(x)), Eq(Derivative(g(x), x), x**2 + x*g(x) - f(x)) ] sol = [ Eq(f(x), (C1/2 - I*C2/2 - I*Integral(x**2*exp(-x**2/2 - I*x)/2 + x**2*exp(-x**2/2 + I*x)/2 + I*exp(-x**2/2 - I*x)*sin(x)/2 - I*exp(-x**2/2 + I*x)*sin(x)/2, x)/2 + Integral(-I*x**2*exp(-x**2/2 - I*x)/2 + I*x**2*exp(-x**2/2 + I*x)/2 + exp(-x**2/2 - I*x)*sin(x)/2 + exp(-x**2/2 + I*x)*sin(x)/2, x)/2)*exp(x**2/2 + I*x) + (C1/2 + I*C2/2 + I*Integral(x**2*exp(-x**2/2 - I*x)/2 + x**2*exp(-x**2/2 + I*x)/2 + I*exp(-x**2/2 - I*x)*sin(x)/2 - I*exp(-x**2/2 + I*x)*sin(x)/2, x)/2 + Integral(-I*x**2*exp(-x**2/2 - I*x)/2 + I*x**2*exp(-x**2/2 + I*x)/2 + exp(-x**2/2 - I*x)*sin(x)/2 + exp(-x**2/2 + I*x)*sin(x)/2, x)/2)*exp(x**2/2 - I*x)), Eq(g(x), (-I*C1/2 + C2/2 + Integral(x**2*exp(-x**2/2 - I*x)/2 + x**2*exp(-x**2/2 + I*x)/2 + I*exp(-x**2/2 - I*x)*sin(x)/2 - I*exp(-x**2/2 + I*x)*sin(x)/2, x)/2 - I*Integral(-I*x**2*exp(-x**2/2 - I*x)/2 + I*x**2*exp(-x**2/2 + I*x)/2 + exp(-x**2/2 - I*x)*sin(x)/2 + exp(-x**2/2 + I*x)*sin(x)/2, x)/2)*exp(x**2/2 - I*x) + (I*C1/2 + C2/2 + Integral(x**2*exp(-x**2/2 - I*x)/2 + x**2*exp(-x**2/2 + I*x)/2 + I*exp(-x**2/2 - I*x)*sin(x)/2 - I*exp(-x**2/2 + I*x)*sin(x)/2, x)/2 + I*Integral(-I*x**2*exp(-x**2/2 - I*x)/2 + I*x**2*exp(-x**2/2 + I*x)/2 + exp(-x**2/2 - I*x)*sin(x)/2 + exp(-x**2/2 + I*x)*sin(x)/2, x)/2)*exp(x**2/2 + I*x)) ] return eqs, sol def test_neq_order1_type4_slow3(): eqs, sol = _neq_order1_type4_slow3() assert dsolve_system(eqs, simplify=False, doit=False) == [sol] # XXX: dsolve gives an error in integration: # assert dsolve(eqs) == sol # https://github.com/sympy/sympy/issues/20155 @slow def test_neq_order1_type4_slow_check3(): eqs, sol = _neq_order1_type4_slow3() assert checksysodesol(eqs, sol) == (True, [0, 0]) @XFAIL @slow def test_linear_3eq_order1_type4_long_dsolve_slow_xfail(): if ON_TRAVIS: skip("Too slow for travis.") eq, sol = _linear_3eq_order1_type4_long() dsolve_sol = dsolve(eq) dsolve_sol1 = [_simpsol(sol) for sol in dsolve_sol] assert dsolve_sol1 == sol @slow def test_linear_3eq_order1_type4_long_dsolve_dotprodsimp(): if ON_TRAVIS: skip("Too slow for travis.") eq, sol = _linear_3eq_order1_type4_long() # XXX: Only works with dotprodsimp see # test_linear_3eq_order1_type4_long_dsolve_slow_xfail which is too slow with dotprodsimp(True): dsolve_sol = dsolve(eq) dsolve_sol1 = [_simpsol(sol) for sol in dsolve_sol] assert dsolve_sol1 == sol @slow def test_linear_3eq_order1_type4_long_check(): if ON_TRAVIS: skip("Too slow for travis.") eq, sol = _linear_3eq_order1_type4_long() assert checksysodesol(eq, sol) == (True, [0, 0, 0]) def test_dsolve_system(): f, g = symbols("f g", cls=Function) x = symbols("x") eqs = [Eq(f(x).diff(x), f(x) + g(x)), Eq(g(x).diff(x), f(x) + g(x))] funcs = [f(x), g(x)] sol = [[Eq(f(x), -C1 + C2*exp(2*x)), Eq(g(x), C1 + C2*exp(2*x))]] assert dsolve_system(eqs, funcs=funcs, t=x, doit=True) == sol raises(ValueError, lambda: dsolve_system(1)) raises(ValueError, lambda: dsolve_system(eqs, 1)) raises(ValueError, lambda: dsolve_system(eqs, funcs, 1)) raises(ValueError, lambda: dsolve_system(eqs, funcs[:1], x)) eq = (Eq(f(x).diff(x), 12 * f(x) - 6 * g(x)), Eq(g(x).diff(x) ** 2, 11 * f(x) + 3 * g(x))) raises(NotImplementedError, lambda: dsolve_system(eq) == ([], [])) raises(NotImplementedError, lambda: dsolve_system(eq, funcs=[f(x), g(x)]) == ([], [])) raises(NotImplementedError, lambda: dsolve_system(eq, funcs=[f(x), g(x)], t=x) == ([], [])) raises(NotImplementedError, lambda: dsolve_system(eq, funcs=[f(x), g(x)], t=x, ics={f(0): 1, g(0): 1}) == ([], [])) raises(NotImplementedError, lambda: dsolve_system(eq, t=x, ics={f(0): 1, g(0): 1}) == ([], [])) raises(NotImplementedError, lambda: dsolve_system(eq, ics={f(0): 1, g(0): 1}) == ([], [])) raises(NotImplementedError, lambda: dsolve_system(eq, funcs=[f(x), g(x)], ics={f(0): 1, g(0): 1}) == ([], [])) def test_dsolve(): f, g = symbols('f g', cls=Function) x, y = symbols('x y') eqs = [f(x).diff(x) - x, f(x).diff(x) + x] with raises(ValueError): dsolve(eqs) eqs = [f(x, y).diff(x)] with raises(ValueError): dsolve(eqs) eqs = [f(x, y).diff(x)+g(x).diff(x), g(x).diff(x)] with raises(ValueError): dsolve(eqs) @slow def test_higher_order1_slow1(): x, y = symbols("x y", cls=Function) t = symbols("t") eq = [ Eq(diff(x(t),t,t), (log(t)+t**2)*diff(x(t),t)+(log(t)+t**2)*3*diff(y(t),t)), Eq(diff(y(t),t,t), (log(t)+t**2)*2*diff(x(t),t)+(log(t)+t**2)*9*diff(y(t),t)) ] sol, = dsolve_system(eq, simplify=False, doit=False) # The solution is too long to write out explicitly and checkodesol is too # slow so we test for particular values of t: for e in eq: res = (e.lhs - e.rhs).subs({sol[0].lhs:sol[0].rhs, sol[1].lhs:sol[1].rhs}) res = res.subs({d: d.doit(deep=False) for d in res.atoms(Derivative)}) assert ratsimp(res.subs(t, 1)) == 0 def test_second_order_type2_slow1(): x, y, z = symbols('x, y, z', cls=Function) t, l = symbols('t, l') eqs1 = [Eq(Derivative(x(t), (t, 2)), t*(2*x(t) + y(t))), Eq(Derivative(y(t), (t, 2)), t*(-x(t) + 2*y(t)))] sol1 = [Eq(x(t), I*C1*airyai(t*(2 - I)**(S(1)/3)) + I*C2*airybi(t*(2 - I)**(S(1)/3)) - I*C3*airyai(t*(2 + I)**(S(1)/3)) - I*C4*airybi(t*(2 + I)**(S(1)/3))), Eq(y(t), C1*airyai(t*(2 - I)**(S(1)/3)) + C2*airybi(t*(2 - I)**(S(1)/3)) + C3*airyai(t*(2 + I)**(S(1)/3)) + C4*airybi(t*(2 + I)**(S(1)/3)))] assert dsolve(eqs1) == sol1 assert checksysodesol(eqs1, sol1) == (True, [0, 0]) @slow @XFAIL def test_nonlinear_3eq_order1_type1(): if ON_TRAVIS: skip("Too slow for travis.") a, b, c = symbols('a b c') eqs = [ a * f(x).diff(x) - (b - c) * g(x) * h(x), b * g(x).diff(x) - (c - a) * h(x) * f(x), c * h(x).diff(x) - (a - b) * f(x) * g(x), ] assert dsolve(eqs) # NotImplementedError @XFAIL def test_nonlinear_3eq_order1_type4(): eqs = [ Eq(f(x).diff(x), (2*h(x)*g(x) - 3*g(x)*h(x))), Eq(g(x).diff(x), (4*f(x)*h(x) - 2*h(x)*f(x))), Eq(h(x).diff(x), (3*g(x)*f(x) - 4*f(x)*g(x))), ] dsolve(eqs) # KeyError when matching # sol = ? # assert dsolve_sol == sol # assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0]) @slow @XFAIL def test_nonlinear_3eq_order1_type3(): if ON_TRAVIS: skip("Too slow for travis.") eqs = [ Eq(f(x).diff(x), (2*f(x)**2 - 3 )), Eq(g(x).diff(x), (4 - 2*h(x) )), Eq(h(x).diff(x), (3*h(x) - 4*f(x)**2)), ] dsolve(eqs) # Not sure if this finishes... # sol = ? # assert dsolve_sol == sol # assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0]) @XFAIL def test_nonlinear_3eq_order1_type5(): eqs = [ Eq(f(x).diff(x), f(x)*(2*f(x) - 3*g(x))), Eq(g(x).diff(x), g(x)*(4*g(x) - 2*h(x))), Eq(h(x).diff(x), h(x)*(3*h(x) - 4*f(x))), ] dsolve(eqs) # KeyError # sol = ? # assert dsolve_sol == sol # assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0]) def test_linear_2eq_order1(): x, y, z = symbols('x, y, z', cls=Function) k, l, m, n = symbols('k, l, m, n', Integer=True) t = Symbol('t') x0, y0 = symbols('x0, y0', cls=Function) eq1 = (Eq(diff(x(t),t), x(t) + y(t) + 9), Eq(diff(y(t),t), 2*x(t) + 5*y(t) + 23)) sol1 = [Eq(x(t), C1*exp(t*(sqrt(6) + 3)) + C2*exp(t*(-sqrt(6) + 3)) - Rational(22, 3)), \ Eq(y(t), C1*(2 + sqrt(6))*exp(t*(sqrt(6) + 3)) + C2*(-sqrt(6) + 2)*exp(t*(-sqrt(6) + 3)) - Rational(5, 3))] assert checksysodesol(eq1, sol1) == (True, [0, 0]) eq2 = (Eq(diff(x(t),t), x(t) + y(t) + 81), Eq(diff(y(t),t), -2*x(t) + y(t) + 23)) sol2 = [Eq(x(t), (C1*cos(sqrt(2)*t) + C2*sin(sqrt(2)*t))*exp(t) - Rational(58, 3)), \ Eq(y(t), (-sqrt(2)*C1*sin(sqrt(2)*t) + sqrt(2)*C2*cos(sqrt(2)*t))*exp(t) - Rational(185, 3))] assert checksysodesol(eq2, sol2) == (True, [0, 0]) eq3 = (Eq(diff(x(t),t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t),t), 2*x(t) + 5*t*y(t))) sol3 = [Eq(x(t), (C1*exp(2*t) + C2*exp(-2*t))*exp(Rational(5, 2)*t**2)), \ Eq(y(t), (C1*exp(2*t) - C2*exp(-2*t))*exp(Rational(5, 2)*t**2))] assert checksysodesol(eq3, sol3) == (True, [0, 0]) eq4 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t))) sol4 = [Eq(x(t), (C1*cos((t**3)/3) + C2*sin((t**3)/3))*exp(Rational(5, 2)*t**2)), \ Eq(y(t), (-C1*sin((t**3)/3) + C2*cos((t**3)/3))*exp(Rational(5, 2)*t**2))] assert checksysodesol(eq4, sol4) == (True, [0, 0]) eq5 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + (5*t+9*t**2)*y(t))) sol5 = [Eq(x(t), (C1*exp((sqrt(77)/2 + Rational(9, 2))*(t**3)/3) + \ C2*exp((-sqrt(77)/2 + Rational(9, 2))*(t**3)/3))*exp(Rational(5, 2)*t**2)), \ Eq(y(t), (C1*(sqrt(77)/2 + Rational(9, 2))*exp((sqrt(77)/2 + Rational(9, 2))*(t**3)/3) + \ C2*(-sqrt(77)/2 + Rational(9, 2))*exp((-sqrt(77)/2 + Rational(9, 2))*(t**3)/3))*exp(Rational(5, 2)*t**2))] assert checksysodesol(eq5, sol5) == (True, [0, 0]) eq6 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), (1-t**2)*x(t) + (5*t+9*t**2)*y(t))) sol6 = [Eq(x(t), C1*x0(t) + C2*x0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t)), \ Eq(y(t), C1*y0(t) + C2*(y0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t) + \ exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)))] s = dsolve(eq6) assert s == sol6 # too complicated to test with subs and simplify # assert checksysodesol(eq10, sol10) == (True, [0, 0]) # this one fails def test_nonlinear_2eq_order1(): x, y, z = symbols('x, y, z', cls=Function) t = Symbol('t') eq1 = (Eq(diff(x(t),t),x(t)*y(t)**3), Eq(diff(y(t),t),y(t)**5)) sol1 = [ Eq(x(t), C1*exp((-1/(4*C2 + 4*t))**(Rational(-1, 4)))), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), C1*exp(-1/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), C1*exp(-I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), C1*exp(I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))] assert dsolve(eq1) == sol1 assert checksysodesol(eq1, sol1) == (True, [0, 0]) eq2 = (Eq(diff(x(t),t), exp(3*x(t))*y(t)**3),Eq(diff(y(t),t), y(t)**5)) sol2 = [ Eq(x(t), -log(C1 - 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), -log(C1 + 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), -log(C1 + 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), -log(C1 - 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))] assert dsolve(eq2) == sol2 assert checksysodesol(eq2, sol2) == (True, [0, 0]) eq3 = (Eq(diff(x(t),t), y(t)*x(t)), Eq(diff(y(t),t), x(t)**3)) tt = Rational(2, 3) sol3 = [ Eq(x(t), 6**tt/(6*(-sinh(sqrt(C1)*(C2 + t)/2)/sqrt(C1))**tt)), Eq(y(t), sqrt(C1 + C1/sinh(sqrt(C1)*(C2 + t)/2)**2)/3)] assert dsolve(eq3) == sol3 # FIXME: assert checksysodesol(eq3, sol3) == (True, [0, 0]) eq4 = (Eq(diff(x(t),t),x(t)*y(t)*sin(t)**2), Eq(diff(y(t),t),y(t)**2*sin(t)**2)) sol4 = {Eq(x(t), -2*exp(C1)/(C2*exp(C1) + t - sin(2*t)/2)), Eq(y(t), -2/(C1 + t - sin(2*t)/2))} assert dsolve(eq4) == sol4 # FIXME: assert checksysodesol(eq4, sol4) == (True, [0, 0]) eq5 = (Eq(x(t),t*diff(x(t),t)+diff(x(t),t)*diff(y(t),t)), Eq(y(t),t*diff(y(t),t)+diff(y(t),t)**2)) sol5 = {Eq(x(t), C1*C2 + C1*t), Eq(y(t), C2**2 + C2*t)} assert dsolve(eq5) == sol5 assert checksysodesol(eq5, sol5) == (True, [0, 0]) eq6 = (Eq(diff(x(t),t),x(t)**2*y(t)**3), Eq(diff(y(t),t),y(t)**5)) sol6 = [ Eq(x(t), 1/(C1 - 1/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), 1/(C1 + (-1/(4*C2 + 4*t))**(Rational(-1, 4)))), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), 1/(C1 + I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), 1/(C1 - I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))] assert dsolve(eq6) == sol6 assert checksysodesol(eq6, sol6) == (True, [0, 0]) @slow def test_nonlinear_3eq_order1(): x, y, z = symbols('x, y, z', cls=Function) t, u = symbols('t u') eq1 = (4*diff(x(t),t) + 2*y(t)*z(t), 3*diff(y(t),t) - z(t)*x(t), 5*diff(z(t),t) - x(t)*y(t)) sol1 = [Eq(4*Integral(1/(sqrt(-4*u**2 - 3*C1 + C2)*sqrt(-4*u**2 + 5*C1 - C2)), (u, x(t))), C3 - sqrt(15)*t/15), Eq(3*Integral(1/(sqrt(-6*u**2 - C1 + 5*C2)*sqrt(3*u**2 + C1 - 4*C2)), (u, y(t))), C3 + sqrt(5)*t/10), Eq(5*Integral(1/(sqrt(-10*u**2 - 3*C1 + C2)* sqrt(5*u**2 + 4*C1 - C2)), (u, z(t))), C3 + sqrt(3)*t/6)] assert [i.dummy_eq(j) for i, j in zip(dsolve(eq1), sol1)] # FIXME: assert checksysodesol(eq1, sol1) == (True, [0, 0, 0]) eq2 = (4*diff(x(t),t) + 2*y(t)*z(t)*sin(t), 3*diff(y(t),t) - z(t)*x(t)*sin(t), 5*diff(z(t),t) - x(t)*y(t)*sin(t)) sol2 = [Eq(3*Integral(1/(sqrt(-6*u**2 - C1 + 5*C2)*sqrt(3*u**2 + C1 - 4*C2)), (u, x(t))), C3 + sqrt(5)*cos(t)/10), Eq(4*Integral(1/(sqrt(-4*u**2 - 3*C1 + C2)*sqrt(-4*u**2 + 5*C1 - C2)), (u, y(t))), C3 - sqrt(15)*cos(t)/15), Eq(5*Integral(1/(sqrt(-10*u**2 - 3*C1 + C2)* sqrt(5*u**2 + 4*C1 - C2)), (u, z(t))), C3 + sqrt(3)*cos(t)/6)] assert [i.dummy_eq(j) for i, j in zip(dsolve(eq2), sol2)] # FIXME: assert checksysodesol(eq2, sol2) == (True, [0, 0, 0]) def test_C1_function_9239(): t = Symbol('t') C1 = Function('C1') C2 = Function('C2') C3 = Symbol('C3') C4 = Symbol('C4') eq = (Eq(diff(C1(t), t), 9*C2(t)), Eq(diff(C2(t), t), 12*C1(t))) sol = [Eq(C1(t), 9*C3*exp(6*sqrt(3)*t) + 9*C4*exp(-6*sqrt(3)*t)), Eq(C2(t), 6*sqrt(3)*C3*exp(6*sqrt(3)*t) - 6*sqrt(3)*C4*exp(-6*sqrt(3)*t))] assert checksysodesol(eq, sol) == (True, [0, 0]) def test_dsolve_linsystem_symbol(): eps = Symbol('epsilon', positive=True) eq1 = (Eq(diff(f(x), x), -eps*g(x)), Eq(diff(g(x), x), eps*f(x))) sol1 = [Eq(f(x), -C1*eps*cos(eps*x) - C2*eps*sin(eps*x)), Eq(g(x), -C1*eps*sin(eps*x) + C2*eps*cos(eps*x))] assert checksysodesol(eq1, sol1) == (True, [0, 0])
efb4dd0a52b4fe57cee657b4184b0f56585d855056ddd59442bd813219a75762
""" Tests from Michael Wester's 1999 paper "Review of CAS mathematical capabilities". http://www.math.unm.edu/~wester/cas/book/Wester.pdf See also http://math.unm.edu/~wester/cas_review.html for detailed output of each tested system. """ from sympy import (Rational, symbols, Dummy, factorial, sqrt, log, exp, oo, zoo, product, binomial, rf, pi, gamma, igcd, factorint, radsimp, combsimp, npartitions, totient, primerange, factor, simplify, gcd, resultant, expand, I, trigsimp, tan, sin, cos, cot, diff, nan, limit, EulerGamma, polygamma, bernoulli, hyper, hyperexpand, besselj, asin, assoc_legendre, Function, re, im, DiracDelta, chebyshevt, legendre_poly, polylog, series, O, atan, sinh, cosh, tanh, floor, ceiling, solve, asinh, acot, csc, sec, LambertW, N, apart, sqrtdenest, factorial2, powdenest, Mul, S, ZZ, Poly, expand_func, E, Q, And, Lt, Min, ask, refine, AlgebraicNumber, continued_fraction_iterator as cf_i, continued_fraction_periodic as cf_p, continued_fraction_convergents as cf_c, continued_fraction_reduce as cf_r, FiniteSet, elliptic_e, elliptic_f, powsimp, hessian, wronskian, fibonacci, sign, Lambda, Piecewise, Subs, residue, Derivative, logcombine, Symbol, Intersection, Union, EmptySet, Interval, idiff, ImageSet, acos, Max, MatMul, conjugate, Eq) import mpmath from sympy.functions.combinatorial.numbers import stirling from sympy.functions.special.delta_functions import Heaviside from sympy.functions.special.error_functions import Ci, Si, erf from sympy.functions.special.zeta_functions import zeta from sympy.testing.pytest import (XFAIL, slow, SKIP, skip, ON_TRAVIS, raises) from sympy.utilities.iterables import partitions from mpmath import mpi, mpc from sympy.matrices import Matrix, GramSchmidt, eye from sympy.matrices.expressions.blockmatrix import BlockMatrix, block_collapse from sympy.matrices.expressions import MatrixSymbol, ZeroMatrix from sympy.physics.quantum import Commutator from sympy.assumptions import assuming from sympy.polys.rings import PolyRing from sympy.polys.fields import FracField from sympy.polys.solvers import solve_lin_sys from sympy.concrete import Sum from sympy.concrete.products import Product from sympy.integrals import integrate from sympy.integrals.transforms import laplace_transform,\ inverse_laplace_transform, LaplaceTransform, fourier_transform,\ mellin_transform from sympy.solvers.recurr import rsolve from sympy.solvers.solveset import solveset, solveset_real, linsolve from sympy.solvers.ode import dsolve from sympy.core.relational import Equality from itertools import islice, takewhile from sympy.series.formal import fps from sympy.series.fourier import fourier_series from sympy.calculus.util import minimum R = Rational x, y, z = symbols('x y z') i, j, k, l, m, n = symbols('i j k l m n', integer=True) f = Function('f') g = Function('g') # A. Boolean Logic and Quantifier Elimination # Not implemented. # B. Set Theory def test_B1(): assert (FiniteSet(i, j, j, k, k, k) | FiniteSet(l, k, j) | FiniteSet(j, m, j)) == FiniteSet(i, j, k, l, m) def test_B2(): assert (FiniteSet(i, j, j, k, k, k) & FiniteSet(l, k, j) & FiniteSet(j, m, j)) == Intersection({j, m}, {i, j, k}, {j, k, l}) # Previous output below. Not sure why that should be the expected output. # There should probably be a way to rewrite Intersections that way but I # don't see why an Intersection should evaluate like that: # # == Union({j}, Intersection({m}, Union({j, k}, Intersection({i}, {l})))) def test_B3(): assert (FiniteSet(i, j, k, l, m) - FiniteSet(j) == FiniteSet(i, k, l, m)) def test_B4(): assert (FiniteSet(*(FiniteSet(i, j)*FiniteSet(k, l))) == FiniteSet((i, k), (i, l), (j, k), (j, l))) # C. Numbers def test_C1(): assert (factorial(50) == 30414093201713378043612608166064768844377641568960512000000000000) def test_C2(): assert (factorint(factorial(50)) == {2: 47, 3: 22, 5: 12, 7: 8, 11: 4, 13: 3, 17: 2, 19: 2, 23: 2, 29: 1, 31: 1, 37: 1, 41: 1, 43: 1, 47: 1}) def test_C3(): assert (factorial2(10), factorial2(9)) == (3840, 945) # Base conversions; not really implemented by sympy # Whatever. Take credit! def test_C4(): assert 0xABC == 2748 def test_C5(): assert 123 == int('234', 7) def test_C6(): assert int('677', 8) == int('1BF', 16) == 447 def test_C7(): assert log(32768, 8) == 5 def test_C8(): # Modular multiplicative inverse. Would be nice if divmod could do this. assert ZZ.invert(5, 7) == 3 assert ZZ.invert(5, 6) == 5 def test_C9(): assert igcd(igcd(1776, 1554), 5698) == 74 def test_C10(): x = 0 for n in range(2, 11): x += R(1, n) assert x == R(4861, 2520) def test_C11(): assert R(1, 7) == S('0.[142857]') def test_C12(): assert R(7, 11) * R(22, 7) == 2 def test_C13(): test = R(10, 7) * (1 + R(29, 1000)) ** R(1, 3) good = 3 ** R(1, 3) assert test == good def test_C14(): assert sqrtdenest(sqrt(2*sqrt(3) + 4)) == 1 + sqrt(3) def test_C15(): test = sqrtdenest(sqrt(14 + 3*sqrt(3 + 2*sqrt(5 - 12*sqrt(3 - 2*sqrt(2)))))) good = sqrt(2) + 3 assert test == good def test_C16(): test = sqrtdenest(sqrt(10 + 2*sqrt(6) + 2*sqrt(10) + 2*sqrt(15))) good = sqrt(2) + sqrt(3) + sqrt(5) assert test == good def test_C17(): test = radsimp((sqrt(3) + sqrt(2)) / (sqrt(3) - sqrt(2))) good = 5 + 2*sqrt(6) assert test == good def test_C18(): assert simplify((sqrt(-2 + sqrt(-5)) * sqrt(-2 - sqrt(-5))).expand(complex=True)) == 3 @XFAIL def test_C19(): assert radsimp(simplify((90 + 34*sqrt(7)) ** R(1, 3))) == 3 + sqrt(7) def test_C20(): inside = (135 + 78*sqrt(3)) test = AlgebraicNumber((inside**R(2, 3) + 3) * sqrt(3) / inside**R(1, 3)) assert simplify(test) == AlgebraicNumber(12) def test_C21(): assert simplify(AlgebraicNumber((41 + 29*sqrt(2)) ** R(1, 5))) == \ AlgebraicNumber(1 + sqrt(2)) @XFAIL def test_C22(): test = simplify(((6 - 4*sqrt(2))*log(3 - 2*sqrt(2)) + (3 - 2*sqrt(2))*log(17 - 12*sqrt(2)) + 32 - 24*sqrt(2)) / (48*sqrt(2) - 72)) good = sqrt(2)/3 - log(sqrt(2) - 1)/3 assert test == good def test_C23(): assert 2 * oo - 3 is oo @XFAIL def test_C24(): raise NotImplementedError("2**aleph_null == aleph_1") # D. Numerical Analysis def test_D1(): assert 0.0 / sqrt(2) == 0.0 def test_D2(): assert str(exp(-1000000).evalf()) == '3.29683147808856e-434295' def test_D3(): assert exp(pi*sqrt(163)).evalf(50).num.ae(262537412640768744) def test_D4(): assert floor(R(-5, 3)) == -2 assert ceiling(R(-5, 3)) == -1 @XFAIL def test_D5(): raise NotImplementedError("cubic_spline([1, 2, 4, 5], [1, 4, 2, 3], x)(3) == 27/8") @XFAIL def test_D6(): raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to FORTRAN") @XFAIL def test_D7(): raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to C") @XFAIL def test_D8(): # One way is to cheat by converting the sum to a string, # and replacing the '[' and ']' with ''. # E.g., horner(S(str(_).replace('[','').replace(']',''))) raise NotImplementedError("apply Horner's rule to sum(a[i]*x**i, (i,1,5))") @XFAIL def test_D9(): raise NotImplementedError("translate D8 to FORTRAN") @XFAIL def test_D10(): raise NotImplementedError("translate D8 to C") @XFAIL def test_D11(): #Is there a way to use count_ops? raise NotImplementedError("flops(sum(product(f[i][k], (i,1,k)), (k,1,n)))") @XFAIL def test_D12(): assert (mpi(-4, 2) * x + mpi(1, 3)) ** 2 == mpi(-8, 16)*x**2 + mpi(-24, 12)*x + mpi(1, 9) @XFAIL def test_D13(): raise NotImplementedError("discretize a PDE: diff(f(x,t),t) == diff(diff(f(x,t),x),x)") # E. Statistics # See scipy; all of this is numerical. # F. Combinatorial Theory. def test_F1(): assert rf(x, 3) == x*(1 + x)*(2 + x) def test_F2(): assert expand_func(binomial(n, 3)) == n*(n - 1)*(n - 2)/6 @XFAIL def test_F3(): assert combsimp(2**n * factorial(n) * factorial2(2*n - 1)) == factorial(2*n) @XFAIL def test_F4(): assert combsimp(2**n * factorial(n) * product(2*k - 1, (k, 1, n))) == factorial(2*n) @XFAIL def test_F5(): assert gamma(n + R(1, 2)) / sqrt(pi) / factorial(n) == factorial(2*n)/2**(2*n)/factorial(n)**2 def test_F6(): partTest = [p.copy() for p in partitions(4)] partDesired = [{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2:1}, {1: 4}] assert partTest == partDesired def test_F7(): assert npartitions(4) == 5 def test_F8(): assert stirling(5, 2, signed=True) == -50 # if signed, then kind=1 def test_F9(): assert totient(1776) == 576 # G. Number Theory def test_G1(): assert list(primerange(999983, 1000004)) == [999983, 1000003] @XFAIL def test_G2(): raise NotImplementedError("find the primitive root of 191 == 19") @XFAIL def test_G3(): raise NotImplementedError("(a+b)**p mod p == a**p + b**p mod p; p prime") # ... G14 Modular equations are not implemented. def test_G15(): assert Rational(sqrt(3).evalf()).limit_denominator(15) == R(26, 15) assert list(takewhile(lambda x: x.q <= 15, cf_c(cf_i(sqrt(3)))))[-1] == \ R(26, 15) def test_G16(): assert list(islice(cf_i(pi),10)) == [3, 7, 15, 1, 292, 1, 1, 1, 2, 1] def test_G17(): assert cf_p(0, 1, 23) == [4, [1, 3, 1, 8]] def test_G18(): assert cf_p(1, 2, 5) == [[1]] assert cf_r([[1]]).expand() == S.Half + sqrt(5)/2 @XFAIL def test_G19(): s = symbols('s', integer=True, positive=True) it = cf_i((exp(1/s) - 1)/(exp(1/s) + 1)) assert list(islice(it, 5)) == [0, 2*s, 6*s, 10*s, 14*s] def test_G20(): s = symbols('s', integer=True, positive=True) # Wester erroneously has this as -s + sqrt(s**2 + 1) assert cf_r([[2*s]]) == s + sqrt(s**2 + 1) @XFAIL def test_G20b(): s = symbols('s', integer=True, positive=True) assert cf_p(s, 1, s**2 + 1) == [[2*s]] # H. Algebra def test_H1(): assert simplify(2*2**n) == simplify(2**(n + 1)) assert powdenest(2*2**n) == simplify(2**(n + 1)) def test_H2(): assert powsimp(4 * 2**n) == 2**(n + 2) def test_H3(): assert (-1)**(n*(n + 1)) == 1 def test_H4(): expr = factor(6*x - 10) assert type(expr) is Mul assert expr.args[0] == 2 assert expr.args[1] == 3*x - 5 p1 = 64*x**34 - 21*x**47 - 126*x**8 - 46*x**5 - 16*x**60 - 81 p2 = 72*x**60 - 25*x**25 - 19*x**23 - 22*x**39 - 83*x**52 + 54*x**10 + 81 q = 34*x**19 - 25*x**16 + 70*x**7 + 20*x**3 - 91*x - 86 def test_H5(): assert gcd(p1, p2, x) == 1 def test_H6(): assert gcd(expand(p1 * q), expand(p2 * q)) == q def test_H7(): p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z assert gcd(p1, p2, x, y, z) == 1 def test_H8(): p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z q = 11*x**12*y**7*z**13 - 23*x**2*y**8*z**10 + 47*x**17*y**5*z**8 assert gcd(p1 * q, p2 * q, x, y, z) == q def test_H9(): p1 = 2*x**(n + 4) - x**(n + 2) p2 = 4*x**(n + 1) + 3*x**n assert gcd(p1, p2) == x**n def test_H10(): p1 = 3*x**4 + 3*x**3 + x**2 - x - 2 p2 = x**3 - 3*x**2 + x + 5 assert resultant(p1, p2, x) == 0 def test_H11(): assert resultant(p1 * q, p2 * q, x) == 0 def test_H12(): num = x**2 - 4 den = x**2 + 4*x + 4 assert simplify(num/den) == (x - 2)/(x + 2) @XFAIL def test_H13(): assert simplify((exp(x) - 1) / (exp(x/2) + 1)) == exp(x/2) - 1 def test_H14(): p = (x + 1) ** 20 ep = expand(p) assert ep == (1 + 20*x + 190*x**2 + 1140*x**3 + 4845*x**4 + 15504*x**5 + 38760*x**6 + 77520*x**7 + 125970*x**8 + 167960*x**9 + 184756*x**10 + 167960*x**11 + 125970*x**12 + 77520*x**13 + 38760*x**14 + 15504*x**15 + 4845*x**16 + 1140*x**17 + 190*x**18 + 20*x**19 + x**20) dep = diff(ep, x) assert dep == (20 + 380*x + 3420*x**2 + 19380*x**3 + 77520*x**4 + 232560*x**5 + 542640*x**6 + 1007760*x**7 + 1511640*x**8 + 1847560*x**9 + 1847560*x**10 + 1511640*x**11 + 1007760*x**12 + 542640*x**13 + 232560*x**14 + 77520*x**15 + 19380*x**16 + 3420*x**17 + 380*x**18 + 20*x**19) assert factor(dep) == 20*(1 + x)**19 def test_H15(): assert simplify(Mul(*[x - r for r in solveset(x**3 + x**2 - 7)])) == x**3 + x**2 - 7 def test_H16(): assert factor(x**100 - 1) == ((x - 1)*(x + 1)*(x**2 + 1)*(x**4 - x**3 + x**2 - x + 1)*(x**4 + x**3 + x**2 + x + 1)*(x**8 - x**6 + x**4 - x**2 + 1)*(x**20 - x**15 + x**10 - x**5 + 1)*(x**20 + x**15 + x**10 + x**5 + 1)*(x**40 - x**30 + x**20 - x**10 + 1)) def test_H17(): assert simplify(factor(expand(p1 * p2)) - p1*p2) == 0 @XFAIL def test_H18(): # Factor over complex rationals. test = factor(4*x**4 + 8*x**3 + 77*x**2 + 18*x + 153) good = (2*x + 3*I)*(2*x - 3*I)*(x + 1 - 4*I)*(x + 1 + 4*I) assert test == good def test_H19(): a = symbols('a') # The idea is to let a**2 == 2, then solve 1/(a-1). Answer is a+1") assert Poly(a - 1).invert(Poly(a**2 - 2)) == a + 1 @XFAIL def test_H20(): raise NotImplementedError("let a**2==2; (x**3 + (a-2)*x**2 - " + "(2*a+3)*x - 3*a) / (x**2-2) = (x**2 - 2*x - 3) / (x-a)") @XFAIL def test_H21(): raise NotImplementedError("evaluate (b+c)**4 assuming b**3==2, c**2==3. \ Answer is 2*b + 8*c + 18*b**2 + 12*b*c + 9") def test_H22(): assert factor(x**4 - 3*x**2 + 1, modulus=5) == (x - 2)**2 * (x + 2)**2 def test_H23(): f = x**11 + x + 1 g = (x**2 + x + 1) * (x**9 - x**8 + x**6 - x**5 + x**3 - x**2 + 1) assert factor(f, modulus=65537) == g def test_H24(): phi = AlgebraicNumber(S.GoldenRatio.expand(func=True), alias='phi') assert factor(x**4 - 3*x**2 + 1, extension=phi) == \ (x - phi)*(x + 1 - phi)*(x - 1 + phi)*(x + phi) def test_H25(): e = (x - 2*y**2 + 3*z**3) ** 20 assert factor(expand(e)) == e def test_H26(): g = expand((sin(x) - 2*cos(y)**2 + 3*tan(z)**3)**20) assert factor(g, expand=False) == (-sin(x) + 2*cos(y)**2 - 3*tan(z)**3)**20 def test_H27(): f = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 g = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z h = -2*z*y**7 \ *(6*x**9*y**9*z**3 + 10*x**7*z**6 + 17*y*x**5*z**12 + 40*y**7) \ *(3*x**22 + 47*x**17*y**5*z**8 - 6*x**15*y**9*z**2 - 24*x*y**19*z**8 - 5) assert factor(expand(f*g)) == h @XFAIL def test_H28(): raise NotImplementedError("expand ((1 - c**2)**5 * (1 - s**2)**5 * " + "(c**2 + s**2)**10) with c**2 + s**2 = 1. Answer is c**10*s**10.") @XFAIL def test_H29(): assert factor(4*x**2 - 21*x*y + 20*y**2, modulus=3) == (x + y)*(x - y) def test_H30(): test = factor(x**3 + y**3, extension=sqrt(-3)) answer = (x + y)*(x + y*(-R(1, 2) - sqrt(3)/2*I))*(x + y*(-R(1, 2) + sqrt(3)/2*I)) assert answer == test def test_H31(): f = (x**2 + 2*x + 3)/(x**3 + 4*x**2 + 5*x + 2) g = 2 / (x + 1)**2 - 2 / (x + 1) + 3 / (x + 2) assert apart(f) == g @XFAIL def test_H32(): # issue 6558 raise NotImplementedError("[A*B*C - (A*B*C)**(-1)]*A*C*B (product \ of a non-commuting product and its inverse)") def test_H33(): A, B, C = symbols('A, B, C', commutative=False) assert (Commutator(A, Commutator(B, C)) + Commutator(B, Commutator(C, A)) + Commutator(C, Commutator(A, B))).doit().expand() == 0 # I. Trigonometry def test_I1(): assert tan(pi*R(7, 10)) == -sqrt(1 + 2/sqrt(5)) @XFAIL def test_I2(): assert sqrt((1 + cos(6))/2) == -cos(3) def test_I3(): assert cos(n*pi) + sin((4*n - 1)*pi/2) == (-1)**n - 1 def test_I4(): assert refine(cos(pi*cos(n*pi)) + sin(pi/2*cos(n*pi)), Q.integer(n)) == (-1)**n - 1 @XFAIL def test_I5(): assert sin((n**5/5 + n**4/2 + n**3/3 - n/30) * pi) == 0 @XFAIL def test_I6(): raise NotImplementedError("assuming -3*pi<x<-5*pi/2, abs(cos(x)) == -cos(x), abs(sin(x)) == -sin(x)") @XFAIL def test_I7(): assert cos(3*x)/cos(x) == cos(x)**2 - 3*sin(x)**2 @XFAIL def test_I8(): assert cos(3*x)/cos(x) == 2*cos(2*x) - 1 @XFAIL def test_I9(): # Supposed to do this with rewrite rules. assert cos(3*x)/cos(x) == cos(x)**2 - 3*sin(x)**2 def test_I10(): assert trigsimp((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1)) is nan @SKIP("hangs") @XFAIL def test_I11(): assert limit((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1), x, 0) != 0 @XFAIL def test_I12(): # This should fail or return nan or something. res = diff((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1), x) assert res is nan # trigsimp(res) gives nan # J. Special functions. def test_J1(): assert bernoulli(16) == R(-3617, 510) def test_J2(): assert diff(elliptic_e(x, y**2), y) == (elliptic_e(x, y**2) - elliptic_f(x, y**2))/y @XFAIL def test_J3(): raise NotImplementedError("Jacobi elliptic functions: diff(dn(u,k), u) == -k**2*sn(u,k)*cn(u,k)") def test_J4(): assert gamma(R(-1, 2)) == -2*sqrt(pi) def test_J5(): assert polygamma(0, R(1, 3)) == -log(3) - sqrt(3)*pi/6 - EulerGamma - log(sqrt(3)) def test_J6(): assert mpmath.besselj(2, 1 + 1j).ae(mpc('0.04157988694396212', '0.24739764151330632')) def test_J7(): assert simplify(besselj(R(-5,2), pi/2)) == 12/(pi**2) def test_J8(): p = besselj(R(3,2), z) q = (sin(z)/z - cos(z))/sqrt(pi*z/2) assert simplify(expand_func(p) -q) == 0 def test_J9(): assert besselj(0, z).diff(z) == - besselj(1, z) def test_J10(): mu, nu = symbols('mu, nu', integer=True) assert assoc_legendre(nu, mu, 0) == 2**mu*sqrt(pi)/gamma((nu - mu)/2 + 1)/gamma((-nu - mu + 1)/2) def test_J11(): assert simplify(assoc_legendre(3, 1, x)) == simplify(-R(3, 2)*sqrt(1 - x**2)*(5*x**2 - 1)) @slow def test_J12(): assert simplify(chebyshevt(1008, x) - 2*x*chebyshevt(1007, x) + chebyshevt(1006, x)) == 0 def test_J13(): a = symbols('a', integer=True, negative=False) assert chebyshevt(a, -1) == (-1)**a def test_J14(): p = hyper([S.Half, S.Half], [R(3, 2)], z**2) assert hyperexpand(p) == asin(z)/z @XFAIL def test_J15(): raise NotImplementedError("F((n+2)/2,-(n-2)/2,R(3,2),sin(z)**2) == sin(n*z)/(n*sin(z)*cos(z)); F(.) is hypergeometric function") @XFAIL def test_J16(): raise NotImplementedError("diff(zeta(x), x) @ x=0 == -log(2*pi)/2") def test_J17(): assert integrate(f((x + 2)/5)*DiracDelta((x - 2)/3) - g(x)*diff(DiracDelta(x - 1), x), (x, 0, 3)) == 3*f(R(4, 5)) + Subs(Derivative(g(x), x), x, 1) @XFAIL def test_J18(): raise NotImplementedError("define an antisymmetric function") # K. The Complex Domain def test_K1(): z1, z2 = symbols('z1, z2', complex=True) assert re(z1 + I*z2) == -im(z2) + re(z1) assert im(z1 + I*z2) == im(z1) + re(z2) def test_K2(): assert abs(3 - sqrt(7) + I*sqrt(6*sqrt(7) - 15)) == 1 @XFAIL def test_K3(): a, b = symbols('a, b', real=True) assert simplify(abs(1/(a + I/a + I*b))) == 1/sqrt(a**2 + (I/a + b)**2) def test_K4(): assert log(3 + 4*I).expand(complex=True) == log(5) + I*atan(R(4, 3)) def test_K5(): x, y = symbols('x, y', real=True) assert tan(x + I*y).expand(complex=True) == (sin(2*x)/(cos(2*x) + cosh(2*y)) + I*sinh(2*y)/(cos(2*x) + cosh(2*y))) def test_K6(): assert sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) == sqrt(x*y)/sqrt(x) assert sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) != sqrt(y) def test_K7(): y = symbols('y', real=True, negative=False) expr = sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) sexpr = simplify(expr) assert sexpr == sqrt(y) def test_K8(): z = symbols('z', complex=True) assert simplify(sqrt(1/z) - 1/sqrt(z)) != 0 # Passes z = symbols('z', complex=True, negative=False) assert simplify(sqrt(1/z) - 1/sqrt(z)) == 0 # Fails def test_K9(): z = symbols('z', real=True, positive=True) assert simplify(sqrt(1/z) - 1/sqrt(z)) == 0 def test_K10(): z = symbols('z', real=True, negative=True) assert simplify(sqrt(1/z) + 1/sqrt(z)) == 0 # This goes up to K25 # L. Determining Zero Equivalence def test_L1(): assert sqrt(997) - (997**3)**R(1, 6) == 0 def test_L2(): assert sqrt(999983) - (999983**3)**R(1, 6) == 0 def test_L3(): assert simplify((2**R(1, 3) + 4**R(1, 3))**3 - 6*(2**R(1, 3) + 4**R(1, 3)) - 6) == 0 def test_L4(): assert trigsimp(cos(x)**3 + cos(x)*sin(x)**2 - cos(x)) == 0 @XFAIL def test_L5(): assert log(tan(R(1, 2)*x + pi/4)) - asinh(tan(x)) == 0 def test_L6(): assert (log(tan(x/2 + pi/4)) - asinh(tan(x))).diff(x).subs({x: 0}) == 0 @XFAIL def test_L7(): assert simplify(log((2*sqrt(x) + 1)/(sqrt(4*x + 4*sqrt(x) + 1)))) == 0 @XFAIL def test_L8(): assert simplify((4*x + 4*sqrt(x) + 1)**(sqrt(x)/(2*sqrt(x) + 1)) \ *(2*sqrt(x) + 1)**(1/(2*sqrt(x) + 1)) - 2*sqrt(x) - 1) == 0 @XFAIL def test_L9(): z = symbols('z', complex=True) assert simplify(2**(1 - z)*gamma(z)*zeta(z)*cos(z*pi/2) - pi**2*zeta(1 - z)) == 0 # M. Equations @XFAIL def test_M1(): assert Equality(x, 2)/2 + Equality(1, 1) == Equality(x/2 + 1, 2) def test_M2(): # The roots of this equation should all be real. Note that this # doesn't test that they are correct. sol = solveset(3*x**3 - 18*x**2 + 33*x - 19, x) assert all(s.expand(complex=True).is_real for s in sol) @XFAIL def test_M5(): assert solveset(x**6 - 9*x**4 - 4*x**3 + 27*x**2 - 36*x - 23, x) == FiniteSet(2**(1/3) + sqrt(3), 2**(1/3) - sqrt(3), +sqrt(3) - 1/2**(2/3) + I*sqrt(3)/2**(2/3), +sqrt(3) - 1/2**(2/3) - I*sqrt(3)/2**(2/3), -sqrt(3) - 1/2**(2/3) + I*sqrt(3)/2**(2/3), -sqrt(3) - 1/2**(2/3) - I*sqrt(3)/2**(2/3)) def test_M6(): assert set(solveset(x**7 - 1, x)) == \ {cos(n*pi*R(2, 7)) + I*sin(n*pi*R(2, 7)) for n in range(0, 7)} # The paper asks for exp terms, but sin's and cos's may be acceptable; # if the results are simplified, exp terms appear for all but # -sin(pi/14) - I*cos(pi/14) and -sin(pi/14) + I*cos(pi/14) which # will simplify if you apply the transformation foo.rewrite(exp).expand() def test_M7(): # TODO: Replace solve with solveset, as of now test fails for solveset sol = solve(x**8 - 8*x**7 + 34*x**6 - 92*x**5 + 175*x**4 - 236*x**3 + 226*x**2 - 140*x + 46, x) assert [s.simplify() for s in sol] == [ 1 - sqrt(-6 - 2*I*sqrt(3 + 4*sqrt(3)))/2, 1 + sqrt(-6 - 2*I*sqrt(3 + 4*sqrt(3)))/2, 1 - sqrt(-6 + 2*I*sqrt(3 + 4*sqrt(3)))/2, 1 + sqrt(-6 + 2*I*sqrt(3 + 4*sqrt (3)))/2, 1 - sqrt(-6 + 2*sqrt(-3 + 4*sqrt(3)))/2, 1 + sqrt(-6 + 2*sqrt(-3 + 4*sqrt(3)))/2, 1 - sqrt(-6 - 2*sqrt(-3 + 4*sqrt(3)))/2, 1 + sqrt(-6 - 2*sqrt(-3 + 4*sqrt(3)))/2] @XFAIL # There are an infinite number of solutions. def test_M8(): x = Symbol('x') z = symbols('z', complex=True) assert solveset(exp(2*x) + 2*exp(x) + 1 - z, x, S.Reals) == \ FiniteSet(log(1 + z - 2*sqrt(z))/2, log(1 + z + 2*sqrt(z))/2) # This one could be simplified better (the 1/2 could be pulled into the log # as a sqrt, and the function inside the log can be factored as a square, # giving [log(sqrt(z) - 1), log(sqrt(z) + 1)]). Also, there should be an # infinite number of solutions. # x = {log(sqrt(z) - 1), log(sqrt(z) + 1) + i pi} [+ n 2 pi i, + n 2 pi i] # where n is an arbitrary integer. See url of detailed output above. @XFAIL def test_M9(): # x = symbols('x') raise NotImplementedError("solveset(exp(2-x**2)-exp(-x),x) has complex solutions.") def test_M10(): # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(exp(x) - x, x) == [-LambertW(-1)] @XFAIL def test_M11(): assert solveset(x**x - x, x) == FiniteSet(-1, 1) def test_M12(): # TODO: x = [-1, 2*(+/-asinh(1)*I + n*pi}, 3*(pi/6 + n*pi/3)] # TODO: Replace solve with solveset, as of now test fails for solveset assert solve((x + 1)*(sin(x)**2 + 1)**2*cos(3*x)**3, x) == [ -1, pi/6, pi/2, - I*log(1 + sqrt(2)), I*log(1 + sqrt(2)), pi - I*log(1 + sqrt(2)), pi + I*log(1 + sqrt(2)), ] @XFAIL def test_M13(): n = Dummy('n') assert solveset_real(sin(x) - cos(x), x) == ImageSet(Lambda(n, n*pi - pi*R(7, 4)), S.Integers) @XFAIL def test_M14(): n = Dummy('n') assert solveset_real(tan(x) - 1, x) == ImageSet(Lambda(n, n*pi + pi/4), S.Integers) def test_M15(): n = Dummy('n') got = solveset(sin(x) - S.Half) assert any(got.dummy_eq(i) for i in ( Union(ImageSet(Lambda(n, 2*n*pi + pi/6), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi*R(5, 6)), S.Integers)), Union(ImageSet(Lambda(n, 2*n*pi + pi*R(5, 6)), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi/6), S.Integers)))) @XFAIL def test_M16(): n = Dummy('n') assert solveset(sin(x) - tan(x), x) == ImageSet(Lambda(n, n*pi), S.Integers) @XFAIL def test_M17(): assert solveset_real(asin(x) - atan(x), x) == FiniteSet(0) @XFAIL def test_M18(): assert solveset_real(acos(x) - atan(x), x) == FiniteSet(sqrt((sqrt(5) - 1)/2)) def test_M19(): # TODO: Replace solve with solveset, as of now test fails for solveset assert solve((x - 2)/x**R(1, 3), x) == [2] def test_M20(): assert solveset(sqrt(x**2 + 1) - x + 2, x) == EmptySet def test_M21(): assert solveset(x + sqrt(x) - 2) == FiniteSet(1) def test_M22(): assert solveset(2*sqrt(x) + 3*x**R(1, 4) - 2) == FiniteSet(R(1, 16)) def test_M23(): x = symbols('x', complex=True) # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(x - 1/sqrt(1 + x**2)) == [ -I*sqrt(S.Half + sqrt(5)/2), sqrt(Rational(-1, 2) + sqrt(5)/2)] def test_M24(): # TODO: Replace solve with solveset, as of now test fails for solveset solution = solve(1 - binomial(m, 2)*2**k, k) answer = log(2/(m*(m - 1)), 2) assert solution[0].expand() == answer.expand() def test_M25(): a, b, c, d = symbols(':d', positive=True) x = symbols('x') # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(a*b**x - c*d**x, x)[0].expand() == (log(c/a)/log(b/d)).expand() def test_M26(): # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(sqrt(log(x)) - log(sqrt(x))) == [1, exp(4)] def test_M27(): x = symbols('x', real=True) b = symbols('b', real=True) with assuming(sin(cos(1/E**2) + 1) + b > 0): # TODO: Replace solve with solveset solve(log(acos(asin(x**R(2, 3) - b) - 1)) + 2, x) == [-b - sin(1 + cos(1/E**2))**R(3/2), b + sin(1 + cos(1/E**2))**R(3/2)] @XFAIL def test_M28(): assert solveset_real(5*x + exp((x - 5)/2) - 8*x**3, x, assume=Q.real(x)) == [-0.784966, -0.016291, 0.802557] def test_M29(): x = symbols('x') assert solveset(abs(x - 1) - 2, domain=S.Reals) == FiniteSet(-1, 3) def test_M30(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions # assert solve(abs(2*x + 5) - abs(x - 2),x, assume=Q.real(x)) == [-1, -7] assert solveset_real(abs(2*x + 5) - abs(x - 2), x) == FiniteSet(-1, -7) def test_M31(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions # assert solve(1 - abs(x) - max(-x - 2, x - 2),x, assume=Q.real(x)) == [-3/2, 3/2] assert solveset_real(1 - abs(x) - Max(-x - 2, x - 2), x) == FiniteSet(R(-3, 2), R(3, 2)) @XFAIL def test_M32(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions assert solveset_real(Max(2 - x**2, x)- Max(-x, (x**3)/9), x) == FiniteSet(-1, 3) @XFAIL def test_M33(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions # Second answer can be written in another form. The second answer is the root of x**3 + 9*x**2 - 18 = 0 in the interval (-2, -1). assert solveset_real(Max(2 - x**2, x) - x**3/9, x) == FiniteSet(-3, -1.554894, 3) @XFAIL def test_M34(): z = symbols('z', complex=True) assert solveset((1 + I) * z + (2 - I) * conjugate(z) + 3*I, z) == FiniteSet(2 + 3*I) def test_M35(): x, y = symbols('x y', real=True) assert linsolve((3*x - 2*y - I*y + 3*I).as_real_imag(), y, x) == FiniteSet((3, 2)) def test_M36(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports solving for function # assert solve(f**2 + f - 2, x) == [Eq(f(x), 1), Eq(f(x), -2)] assert solveset(f(x)**2 + f(x) - 2, f(x)) == FiniteSet(-2, 1) def test_M37(): assert linsolve([x + y + z - 6, 2*x + y + 2*z - 10, x + 3*y + z - 10 ], x, y, z) == \ FiniteSet((-z + 4, 2, z)) def test_M38(): a, b, c = symbols('a, b, c') domain = FracField([a, b, c], ZZ).to_domain() ring = PolyRing('k1:50', domain) (k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k20, k21, k22, k23, k24, k25, k26, k27, k28, k29, k30, k31, k32, k33, k34, k35, k36, k37, k38, k39, k40, k41, k42, k43, k44, k45, k46, k47, k48, k49) = ring.gens system = [ -b*k8/a + c*k8/a, -b*k11/a + c*k11/a, -b*k10/a + c*k10/a + k2, -k3 - b*k9/a + c*k9/a, -b*k14/a + c*k14/a, -b*k15/a + c*k15/a, -b*k18/a + c*k18/a - k2, -b*k17/a + c*k17/a, -b*k16/a + c*k16/a + k4, -b*k13/a + c*k13/a - b*k21/a + c*k21/a + b*k5/a - c*k5/a, b*k44/a - c*k44/a, -b*k45/a + c*k45/a, -b*k20/a + c*k20/a, -b*k44/a + c*k44/a, b*k46/a - c*k46/a, b**2*k47/a**2 - 2*b*c*k47/a**2 + c**2*k47/a**2, k3, -k4, -b*k12/a + c*k12/a - a*k6/b + c*k6/b, -b*k19/a + c*k19/a + a*k7/c - b*k7/c, b*k45/a - c*k45/a, -b*k46/a + c*k46/a, -k48 + c*k48/a + c*k48/b - c**2*k48/(a*b), -k49 + b*k49/a + b*k49/c - b**2*k49/(a*c), a*k1/b - c*k1/b, a*k4/b - c*k4/b, a*k3/b - c*k3/b + k9, -k10 + a*k2/b - c*k2/b, a*k7/b - c*k7/b, -k9, k11, b*k12/a - c*k12/a + a*k6/b - c*k6/b, a*k15/b - c*k15/b, k10 + a*k18/b - c*k18/b, -k11 + a*k17/b - c*k17/b, a*k16/b - c*k16/b, -a*k13/b + c*k13/b + a*k21/b - c*k21/b + a*k5/b - c*k5/b, -a*k44/b + c*k44/b, a*k45/b - c*k45/b, a*k14/c - b*k14/c + a*k20/b - c*k20/b, a*k44/b - c*k44/b, -a*k46/b + c*k46/b, -k47 + c*k47/a + c*k47/b - c**2*k47/(a*b), a*k19/b - c*k19/b, -a*k45/b + c*k45/b, a*k46/b - c*k46/b, a**2*k48/b**2 - 2*a*c*k48/b**2 + c**2*k48/b**2, -k49 + a*k49/b + a*k49/c - a**2*k49/(b*c), k16, -k17, -a*k1/c + b*k1/c, -k16 - a*k4/c + b*k4/c, -a*k3/c + b*k3/c, k18 - a*k2/c + b*k2/c, b*k19/a - c*k19/a - a*k7/c + b*k7/c, -a*k6/c + b*k6/c, -a*k8/c + b*k8/c, -a*k11/c + b*k11/c + k17, -a*k10/c + b*k10/c - k18, -a*k9/c + b*k9/c, -a*k14/c + b*k14/c - a*k20/b + c*k20/b, -a*k13/c + b*k13/c + a*k21/c - b*k21/c - a*k5/c + b*k5/c, a*k44/c - b*k44/c, -a*k45/c + b*k45/c, -a*k44/c + b*k44/c, a*k46/c - b*k46/c, -k47 + b*k47/a + b*k47/c - b**2*k47/(a*c), -a*k12/c + b*k12/c, a*k45/c - b*k45/c, -a*k46/c + b*k46/c, -k48 + a*k48/b + a*k48/c - a**2*k48/(b*c), a**2*k49/c**2 - 2*a*b*k49/c**2 + b**2*k49/c**2, k8, k11, -k15, k10 - k18, -k17, k9, -k16, -k29, k14 - k32, -k21 + k23 - k31, -k24 - k30, -k35, k44, -k45, k36, k13 - k23 + k39, -k20 + k38, k25 + k37, b*k26/a - c*k26/a - k34 + k42, -2*k44, k45, k46, b*k47/a - c*k47/a, k41, k44, -k46, -b*k47/a + c*k47/a, k12 + k24, -k19 - k25, -a*k27/b + c*k27/b - k33, k45, -k46, -a*k48/b + c*k48/b, a*k28/c - b*k28/c + k40, -k45, k46, a*k48/b - c*k48/b, a*k49/c - b*k49/c, -a*k49/c + b*k49/c, -k1, -k4, -k3, k15, k18 - k2, k17, k16, k22, k25 - k7, k24 + k30, k21 + k23 - k31, k28, -k44, k45, -k30 - k6, k20 + k32, k27 + b*k33/a - c*k33/a, k44, -k46, -b*k47/a + c*k47/a, -k36, k31 - k39 - k5, -k32 - k38, k19 - k37, k26 - a*k34/b + c*k34/b - k42, k44, -2*k45, k46, a*k48/b - c*k48/b, a*k35/c - b*k35/c - k41, -k44, k46, b*k47/a - c*k47/a, -a*k49/c + b*k49/c, -k40, k45, -k46, -a*k48/b + c*k48/b, a*k49/c - b*k49/c, k1, k4, k3, -k8, -k11, -k10 + k2, -k9, k37 + k7, -k14 - k38, -k22, -k25 - k37, -k24 + k6, -k13 - k23 + k39, -k28 + b*k40/a - c*k40/a, k44, -k45, -k27, -k44, k46, b*k47/a - c*k47/a, k29, k32 + k38, k31 - k39 + k5, -k12 + k30, k35 - a*k41/b + c*k41/b, -k44, k45, -k26 + k34 + a*k42/c - b*k42/c, k44, k45, -2*k46, -b*k47/a + c*k47/a, -a*k48/b + c*k48/b, a*k49/c - b*k49/c, k33, -k45, k46, a*k48/b - c*k48/b, -a*k49/c + b*k49/c ] solution = { k49: 0, k48: 0, k47: 0, k46: 0, k45: 0, k44: 0, k41: 0, k40: 0, k38: 0, k37: 0, k36: 0, k35: 0, k33: 0, k32: 0, k30: 0, k29: 0, k28: 0, k27: 0, k25: 0, k24: 0, k22: 0, k21: 0, k20: 0, k19: 0, k18: 0, k17: 0, k16: 0, k15: 0, k14: 0, k13: 0, k12: 0, k11: 0, k10: 0, k9: 0, k8: 0, k7: 0, k6: 0, k5: 0, k4: 0, k3: 0, k2: 0, k1: 0, k34: b/c*k42, k31: k39, k26: a/c*k42, k23: k39 } assert solve_lin_sys(system, ring) == solution def test_M39(): x, y, z = symbols('x y z', complex=True) # TODO: Replace solve with solveset, as of now # solveset doesn't supports non-linear multivariate assert solve([x**2*y + 3*y*z - 4, -3*x**2*z + 2*y**2 + 1, 2*y*z**2 - z**2 - 1 ]) ==\ [{y: 1, z: 1, x: -1}, {y: 1, z: 1, x: 1},\ {y: sqrt(2)*I, z: R(1,3) - sqrt(2)*I/3, x: -sqrt(-1 - sqrt(2)*I)},\ {y: sqrt(2)*I, z: R(1,3) - sqrt(2)*I/3, x: sqrt(-1 - sqrt(2)*I)},\ {y: -sqrt(2)*I, z: R(1,3) + sqrt(2)*I/3, x: -sqrt(-1 + sqrt(2)*I)},\ {y: -sqrt(2)*I, z: R(1,3) + sqrt(2)*I/3, x: sqrt(-1 + sqrt(2)*I)}] # N. Inequalities def test_N1(): assert ask(E**pi > pi**E) @XFAIL def test_N2(): x = symbols('x', real=True) assert ask(x**4 - x + 1 > 0) is True assert ask(x**4 - x + 1 > 1) is False @XFAIL def test_N3(): x = symbols('x', real=True) assert ask(And(Lt(-1, x), Lt(x, 1)), abs(x) < 1 ) @XFAIL def test_N4(): x, y = symbols('x y', real=True) assert ask(2*x**2 > 2*y**2, (x > y) & (y > 0)) is True @XFAIL def test_N5(): x, y, k = symbols('x y k', real=True) assert ask(k*x**2 > k*y**2, (x > y) & (y > 0) & (k > 0)) is True @slow @XFAIL def test_N6(): x, y, k, n = symbols('x y k n', real=True) assert ask(k*x**n > k*y**n, (x > y) & (y > 0) & (k > 0) & (n > 0)) is True @XFAIL def test_N7(): x, y = symbols('x y', real=True) assert ask(y > 0, (x > 1) & (y >= x - 1)) is True @XFAIL @slow def test_N8(): x, y, z = symbols('x y z', real=True) assert ask(Eq(x, y) & Eq(y, z), (x >= y) & (y >= z) & (z >= x)) def test_N9(): x = Symbol('x') assert solveset(abs(x - 1) > 2, domain=S.Reals) == Union(Interval(-oo, -1, False, True), Interval(3, oo, True)) def test_N10(): x = Symbol('x') p = (x - 1)*(x - 2)*(x - 3)*(x - 4)*(x - 5) assert solveset(expand(p) < 0, domain=S.Reals) == Union(Interval(-oo, 1, True, True), Interval(2, 3, True, True), Interval(4, 5, True, True)) def test_N11(): x = Symbol('x') assert solveset(6/(x - 3) <= 3, domain=S.Reals) == Union(Interval(-oo, 3, True, True), Interval(5, oo)) def test_N12(): x = Symbol('x') assert solveset(sqrt(x) < 2, domain=S.Reals) == Interval(0, 4, False, True) def test_N13(): x = Symbol('x') assert solveset(sin(x) < 2, domain=S.Reals) == S.Reals @XFAIL def test_N14(): x = Symbol('x') # Gives 'Union(Interval(Integer(0), Mul(Rational(1, 2), pi), false, true), # Interval(Mul(Rational(1, 2), pi), Mul(Integer(2), pi), true, false))' # which is not the correct answer, but the provided also seems wrong. assert solveset(sin(x) < 1, x, domain=S.Reals) == Union(Interval(-oo, pi/2, True, True), Interval(pi/2, oo, True, True)) def test_N15(): r, t = symbols('r t') # raises NotImplementedError: only univariate inequalities are supported solveset(abs(2*r*(cos(t) - 1) + 1) <= 1, r, S.Reals) def test_N16(): r, t = symbols('r t') solveset((r**2)*((cos(t) - 4)**2)*sin(t)**2 < 9, r, S.Reals) @XFAIL def test_N17(): # currently only univariate inequalities are supported assert solveset((x + y > 0, x - y < 0), (x, y)) == (abs(x) < y) def test_O1(): M = Matrix((1 + I, -2, 3*I)) assert sqrt(expand(M.dot(M.H))) == sqrt(15) def test_O2(): assert Matrix((2, 2, -3)).cross(Matrix((1, 3, 1))) == Matrix([[11], [-5], [4]]) # The vector module has no way of representing vectors symbolically (without # respect to a basis) @XFAIL def test_O3(): # assert (va ^ vb) | (vc ^ vd) == -(va | vc)*(vb | vd) + (va | vd)*(vb | vc) raise NotImplementedError("""The vector module has no way of representing vectors symbolically (without respect to a basis)""") def test_O4(): from sympy.vector import CoordSys3D, Del N = CoordSys3D("N") delop = Del() i, j, k = N.base_vectors() x, y, z = N.base_scalars() F = i*(x*y*z) + j*((x*y*z)**2) + k*((y**2)*(z**3)) assert delop.cross(F).doit() == (-2*x**2*y**2*z + 2*y*z**3)*i + x*y*j + (2*x*y**2*z**2 - x*z)*k @XFAIL def test_O5(): #assert grad|(f^g)-g|(grad^f)+f|(grad^g) == 0 raise NotImplementedError("""The vector module has no way of representing vectors symbolically (without respect to a basis)""") #testO8-O9 MISSING!! def test_O10(): L = [Matrix([2, 3, 5]), Matrix([3, 6, 2]), Matrix([8, 3, 6])] assert GramSchmidt(L) == [Matrix([ [2], [3], [5]]), Matrix([ [R(23, 19)], [R(63, 19)], [R(-47, 19)]]), Matrix([ [R(1692, 353)], [R(-1551, 706)], [R(-423, 706)]])] def test_P1(): assert Matrix(3, 3, lambda i, j: j - i).diagonal(-1) == Matrix( 1, 2, [-1, -1]) def test_P2(): M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) M.row_del(1) M.col_del(2) assert M == Matrix([[1, 2], [7, 8]]) def test_P3(): A = Matrix([ [11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]) A11 = A[0:3, 1:4] A12 = A[(0, 1, 3), (2, 0, 3)] A21 = A A221 = -A[0:2, 2:4] A222 = -A[(3, 0), (2, 1)] A22 = BlockMatrix([[A221, A222]]).T rows = [[-A11, A12], [A21, A22]] raises(ValueError, lambda: BlockMatrix(rows)) B = Matrix(rows) assert B == Matrix([ [-12, -13, -14, 13, 11, 14], [-22, -23, -24, 23, 21, 24], [-32, -33, -34, 43, 41, 44], [11, 12, 13, 14, -13, -23], [21, 22, 23, 24, -14, -24], [31, 32, 33, 34, -43, -13], [41, 42, 43, 44, -42, -12]]) @XFAIL def test_P4(): raise NotImplementedError("Block matrix diagonalization not supported") def test_P5(): M = Matrix([[7, 11], [3, 8]]) assert M % 2 == Matrix([[1, 1], [1, 0]]) def test_P6(): M = Matrix([[cos(x), sin(x)], [-sin(x), cos(x)]]) assert M.diff(x, 2) == Matrix([[-cos(x), -sin(x)], [sin(x), -cos(x)]]) def test_P7(): M = Matrix([[x, y]])*( z*Matrix([[1, 3, 5], [2, 4, 6]]) + Matrix([[7, -9, 11], [-8, 10, -12]])) assert M == Matrix([[x*(z + 7) + y*(2*z - 8), x*(3*z - 9) + y*(4*z + 10), x*(5*z + 11) + y*(6*z - 12)]]) def test_P8(): M = Matrix([[1, -2*I], [-3*I, 4]]) assert M.norm(ord=S.Infinity) == 7 def test_P9(): a, b, c = symbols('a b c', nonzero=True) M = Matrix([[a/(b*c), 1/c, 1/b], [1/c, b/(a*c), 1/a], [1/b, 1/a, c/(a*b)]]) assert factor(M.norm('fro')) == (a**2 + b**2 + c**2)/(abs(a)*abs(b)*abs(c)) @XFAIL def test_P10(): M = Matrix([[1, 2 + 3*I], [f(4 - 5*I), 6]]) # conjugate(f(4 - 5*i)) is not simplified to f(4+5*I) assert M.H == Matrix([[1, f(4 + 5*I)], [2 + 3*I, 6]]) @XFAIL def test_P11(): # raises NotImplementedError("Matrix([[x,y],[1,x*y]]).inv() # not simplifying to extract common factor") assert Matrix([[x, y], [1, x*y]]).inv() == (1/(x**2 - 1))*Matrix([[x, -1], [-1/y, x/y]]) def test_P11_workaround(): # This test was changed to inverse method ADJ because it depended on the # specific form of inverse returned from the 'GE' method which has changed. M = Matrix([[x, y], [1, x*y]]).inv('ADJ') c = gcd(tuple(M)) assert MatMul(c, M/c, evaluate=False) == MatMul(c, Matrix([ [x*y, -y], [ -1, x]]), evaluate=False) def test_P12(): A11 = MatrixSymbol('A11', n, n) A12 = MatrixSymbol('A12', n, n) A22 = MatrixSymbol('A22', n, n) B = BlockMatrix([[A11, A12], [ZeroMatrix(n, n), A22]]) assert block_collapse(B.I) == BlockMatrix([[A11.I, (-1)*A11.I*A12*A22.I], [ZeroMatrix(n, n), A22.I]]) def test_P13(): M = Matrix([[1, x - 2, x - 3], [x - 1, x**2 - 3*x + 6, x**2 - 3*x - 2], [x - 2, x**2 - 8, 2*(x**2) - 12*x + 14]]) L, U, _ = M.LUdecomposition() assert simplify(L) == Matrix([[1, 0, 0], [x - 1, 1, 0], [x - 2, x - 3, 1]]) assert simplify(U) == Matrix([[1, x - 2, x - 3], [0, 4, x - 5], [0, 0, x - 7]]) def test_P14(): M = Matrix([[1, 2, 3, 1, 3], [3, 2, 1, 1, 7], [0, 2, 4, 1, 1], [1, 1, 1, 1, 4]]) R, _ = M.rref() assert R == Matrix([[1, 0, -1, 0, 2], [0, 1, 2, 0, -1], [0, 0, 0, 1, 3], [0, 0, 0, 0, 0]]) def test_P15(): M = Matrix([[-1, 3, 7, -5], [4, -2, 1, 3], [2, 4, 15, -7]]) assert M.rank() == 2 def test_P16(): M = Matrix([[2*sqrt(2), 8], [6*sqrt(6), 24*sqrt(3)]]) assert M.rank() == 1 def test_P17(): t = symbols('t', real=True) M=Matrix([ [sin(2*t), cos(2*t)], [2*(1 - (cos(t)**2))*cos(t), (1 - 2*(sin(t)**2))*sin(t)]]) assert M.rank() == 1 def test_P18(): M = Matrix([[1, 0, -2, 0], [-2, 1, 0, 3], [-1, 2, -6, 6]]) assert M.nullspace() == [Matrix([[2], [4], [1], [0]]), Matrix([[0], [-3], [0], [1]])] def test_P19(): w = symbols('w') M = Matrix([[1, 1, 1, 1], [w, x, y, z], [w**2, x**2, y**2, z**2], [w**3, x**3, y**3, z**3]]) assert M.det() == (w**3*x**2*y - w**3*x**2*z - w**3*x*y**2 + w**3*x*z**2 + w**3*y**2*z - w**3*y*z**2 - w**2*x**3*y + w**2*x**3*z + w**2*x*y**3 - w**2*x*z**3 - w**2*y**3*z + w**2*y*z**3 + w*x**3*y**2 - w*x**3*z**2 - w*x**2*y**3 + w*x**2*z**3 + w*y**3*z**2 - w*y**2*z**3 - x**3*y**2*z + x**3*y*z**2 + x**2*y**3*z - x**2*y*z**3 - x*y**3*z**2 + x*y**2*z**3 ) @XFAIL def test_P20(): raise NotImplementedError("Matrix minimal polynomial not supported") def test_P21(): M = Matrix([[5, -3, -7], [-2, 1, 2], [2, -3, -4]]) assert M.charpoly(x).as_expr() == x**3 - 2*x**2 - 5*x + 6 def test_P22(): d = 100 M = (2 - x)*eye(d) assert M.eigenvals() == {-x + 2: d} def test_P23(): M = Matrix([ [2, 1, 0, 0, 0], [1, 2, 1, 0, 0], [0, 1, 2, 1, 0], [0, 0, 1, 2, 1], [0, 0, 0, 1, 2]]) assert M.eigenvals() == { S('1'): 1, S('2'): 1, S('3'): 1, S('sqrt(3) + 2'): 1, S('-sqrt(3) + 2'): 1} def test_P24(): M = Matrix([[611, 196, -192, 407, -8, -52, -49, 29], [196, 899, 113, -192, -71, -43, -8, -44], [-192, 113, 899, 196, 61, 49, 8, 52], [ 407, -192, 196, 611, 8, 44, 59, -23], [ -8, -71, 61, 8, 411, -599, 208, 208], [ -52, -43, 49, 44, -599, 411, 208, 208], [ -49, -8, 8, 59, 208, 208, 99, -911], [ 29, -44, 52, -23, 208, 208, -911, 99]]) assert M.eigenvals() == { S('0'): 1, S('10*sqrt(10405)'): 1, S('100*sqrt(26) + 510'): 1, S('1000'): 2, S('-100*sqrt(26) + 510'): 1, S('-10*sqrt(10405)'): 1, S('1020'): 1} def test_P25(): MF = N(Matrix([[ 611, 196, -192, 407, -8, -52, -49, 29], [ 196, 899, 113, -192, -71, -43, -8, -44], [-192, 113, 899, 196, 61, 49, 8, 52], [ 407, -192, 196, 611, 8, 44, 59, -23], [ -8, -71, 61, 8, 411, -599, 208, 208], [ -52, -43, 49, 44, -599, 411, 208, 208], [ -49, -8, 8, 59, 208, 208, 99, -911], [ 29, -44, 52, -23, 208, 208, -911, 99]])) ev_1 = sorted(MF.eigenvals(multiple=True)) ev_2 = sorted( [-1020.0490184299969, 0.0, 0.09804864072151699, 1000.0, 1000.0, 1019.9019513592784, 1020.0, 1020.0490184299969]) for x, y in zip(ev_1, ev_2): assert abs(x - y) < 1e-12 def test_P26(): a0, a1, a2, a3, a4 = symbols('a0 a1 a2 a3 a4') M = Matrix([[-a4, -a3, -a2, -a1, -a0, 0, 0, 0, 0], [ 1, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 1, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 1, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 1, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, -1, -1, 0, 0], [ 0, 0, 0, 0, 0, 1, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 1, -1, -1], [ 0, 0, 0, 0, 0, 0, 0, 1, 0]]) assert M.eigenvals(error_when_incomplete=False) == { S('-1/2 - sqrt(3)*I/2'): 2, S('-1/2 + sqrt(3)*I/2'): 2} def test_P27(): a = symbols('a') M = Matrix([[a, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, a, 0, 0], [0, 0, 0, a, 0], [0, -2, 0, 0, 2]]) assert M.eigenvects() == [ (a, 3, [ Matrix([1, 0, 0, 0, 0]), Matrix([0, 0, 1, 0, 0]), Matrix([0, 0, 0, 1, 0]) ]), (1 - I, 1, [ Matrix([0, (1 + I)/2, 0, 0, 1]) ]), (1 + I, 1, [ Matrix([0, (1 - I)/2, 0, 0, 1]) ]), ] @XFAIL def test_P28(): raise NotImplementedError("Generalized eigenvectors not supported \ https://github.com/sympy/sympy/issues/5293") @XFAIL def test_P29(): raise NotImplementedError("Generalized eigenvectors not supported \ https://github.com/sympy/sympy/issues/5293") def test_P30(): M = Matrix([[1, 0, 0, 1, -1], [0, 1, -2, 3, -3], [0, 0, -1, 2, -2], [1, -1, 1, 0, 1], [1, -1, 1, -1, 2]]) _, J = M.jordan_form() assert J == Matrix([[-1, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 0, 1]]) @XFAIL def test_P31(): raise NotImplementedError("Smith normal form not implemented") def test_P32(): M = Matrix([[1, -2], [2, 1]]) assert exp(M).rewrite(cos).simplify() == Matrix([[E*cos(2), -E*sin(2)], [E*sin(2), E*cos(2)]]) def test_P33(): w, t = symbols('w t') M = Matrix([[0, 1, 0, 0], [0, 0, 0, 2*w], [0, 0, 0, 1], [0, -2*w, 3*w**2, 0]]) assert exp(M*t).rewrite(cos).expand() == Matrix([ [1, -3*t + 4*sin(t*w)/w, 6*t*w - 6*sin(t*w), -2*cos(t*w)/w + 2/w], [0, 4*cos(t*w) - 3, -6*w*cos(t*w) + 6*w, 2*sin(t*w)], [0, 2*cos(t*w)/w - 2/w, -3*cos(t*w) + 4, sin(t*w)/w], [0, -2*sin(t*w), 3*w*sin(t*w), cos(t*w)]]) @XFAIL def test_P34(): a, b, c = symbols('a b c', real=True) M = Matrix([[a, 1, 0, 0, 0, 0], [0, a, 0, 0, 0, 0], [0, 0, b, 0, 0, 0], [0, 0, 0, c, 1, 0], [0, 0, 0, 0, c, 1], [0, 0, 0, 0, 0, c]]) # raises exception, sin(M) not supported. exp(M*I) also not supported # https://github.com/sympy/sympy/issues/6218 assert sin(M) == Matrix([[sin(a), cos(a), 0, 0, 0, 0], [0, sin(a), 0, 0, 0, 0], [0, 0, sin(b), 0, 0, 0], [0, 0, 0, sin(c), cos(c), -sin(c)/2], [0, 0, 0, 0, sin(c), cos(c)], [0, 0, 0, 0, 0, sin(c)]]) @XFAIL def test_P35(): M = pi/2*Matrix([[2, 1, 1], [2, 3, 2], [1, 1, 2]]) # raises exception, sin(M) not supported. exp(M*I) also not supported # https://github.com/sympy/sympy/issues/6218 assert sin(M) == eye(3) @XFAIL def test_P36(): M = Matrix([[10, 7], [7, 17]]) assert sqrt(M) == Matrix([[3, 1], [1, 4]]) def test_P37(): M = Matrix([[1, 1, 0], [0, 1, 0], [0, 0, 1]]) assert M**S.Half == Matrix([[1, R(1, 2), 0], [0, 1, 0], [0, 0, 1]]) @XFAIL def test_P38(): M=Matrix([[0, 1, 0], [0, 0, 0], [0, 0, 0]]) #raises ValueError: Matrix det == 0; not invertible M**S.Half @XFAIL def test_P39(): """ M=Matrix([ [1, 1], [2, 2], [3, 3]]) M.SVD() """ raise NotImplementedError("Singular value decomposition not implemented") def test_P40(): r, t = symbols('r t', real=True) M = Matrix([r*cos(t), r*sin(t)]) assert M.jacobian(Matrix([r, t])) == Matrix([[cos(t), -r*sin(t)], [sin(t), r*cos(t)]]) def test_P41(): r, t = symbols('r t', real=True) assert hessian(r**2*sin(t),(r,t)) == Matrix([[ 2*sin(t), 2*r*cos(t)], [2*r*cos(t), -r**2*sin(t)]]) def test_P42(): assert wronskian([cos(x), sin(x)], x).simplify() == 1 def test_P43(): def __my_jacobian(M, Y): return Matrix([M.diff(v).T for v in Y]).T r, t = symbols('r t', real=True) M = Matrix([r*cos(t), r*sin(t)]) assert __my_jacobian(M,[r,t]) == Matrix([[cos(t), -r*sin(t)], [sin(t), r*cos(t)]]) def test_P44(): def __my_hessian(f, Y): V = Matrix([diff(f, v) for v in Y]) return Matrix([V.T.diff(v) for v in Y]) r, t = symbols('r t', real=True) assert __my_hessian(r**2*sin(t), (r, t)) == Matrix([ [ 2*sin(t), 2*r*cos(t)], [2*r*cos(t), -r**2*sin(t)]]) def test_P45(): def __my_wronskian(Y, v): M = Matrix([Matrix(Y).T.diff(x, n) for n in range(0, len(Y))]) return M.det() assert __my_wronskian([cos(x), sin(x)], x).simplify() == 1 # Q1-Q6 Tensor tests missing @XFAIL def test_R1(): i, j, n = symbols('i j n', integer=True, positive=True) xn = MatrixSymbol('xn', n, 1) Sm = Sum((xn[i, 0] - Sum(xn[j, 0], (j, 0, n - 1))/n)**2, (i, 0, n - 1)) # sum does not calculate # Unknown result Sm.doit() raise NotImplementedError('Unknown result') @XFAIL def test_R2(): m, b = symbols('m b') i, n = symbols('i n', integer=True, positive=True) xn = MatrixSymbol('xn', n, 1) yn = MatrixSymbol('yn', n, 1) f = Sum((yn[i, 0] - m*xn[i, 0] - b)**2, (i, 0, n - 1)) f1 = diff(f, m) f2 = diff(f, b) # raises TypeError: solveset() takes at most 2 arguments (3 given) solveset((f1, f2), (m, b), domain=S.Reals) @XFAIL def test_R3(): n, k = symbols('n k', integer=True, positive=True) sk = ((-1)**k) * (binomial(2*n, k))**2 Sm = Sum(sk, (k, 1, oo)) T = Sm.doit() T2 = T.combsimp() # returns -((-1)**n*factorial(2*n) # - (factorial(n))**2)*exp_polar(-I*pi)/(factorial(n))**2 assert T2 == (-1)**n*binomial(2*n, n) @XFAIL def test_R4(): # Macsyma indefinite sum test case: #(c15) /* Check whether the full Gosper algorithm is implemented # => 1/2^(n + 1) binomial(n, k - 1) */ #closedform(indefsum(binomial(n, k)/2^n - binomial(n + 1, k)/2^(n + 1), k)); #Time= 2690 msecs # (- n + k - 1) binomial(n + 1, k) #(d15) - -------------------------------- # n # 2 2 (n + 1) # #(c16) factcomb(makefact(%)); #Time= 220 msecs # n! #(d16) ---------------- # n # 2 k! 2 (n - k)! # Might be possible after fixing https://github.com/sympy/sympy/pull/1879 raise NotImplementedError("Indefinite sum not supported") @XFAIL def test_R5(): a, b, c, n, k = symbols('a b c n k', integer=True, positive=True) sk = ((-1)**k)*(binomial(a + b, a + k) *binomial(b + c, b + k)*binomial(c + a, c + k)) Sm = Sum(sk, (k, 1, oo)) T = Sm.doit() # hypergeometric series not calculated assert T == factorial(a+b+c)/(factorial(a)*factorial(b)*factorial(c)) def test_R6(): n, k = symbols('n k', integer=True, positive=True) gn = MatrixSymbol('gn', n + 2, 1) Sm = Sum(gn[k, 0] - gn[k - 1, 0], (k, 1, n + 1)) assert Sm.doit() == -gn[0, 0] + gn[n + 1, 0] def test_R7(): n, k = symbols('n k', integer=True, positive=True) T = Sum(k**3,(k,1,n)).doit() assert T.factor() == n**2*(n + 1)**2/4 @XFAIL def test_R8(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(k**2*binomial(n, k), (k, 1, n)) T = Sm.doit() #returns Piecewise function assert T.combsimp() == n*(n + 1)*2**(n - 2) def test_R9(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(binomial(n, k - 1)/k, (k, 1, n + 1)) assert Sm.doit().simplify() == (2**(n + 1) - 1)/(n + 1) @XFAIL def test_R10(): n, m, r, k = symbols('n m r k', integer=True, positive=True) Sm = Sum(binomial(n, k)*binomial(m, r - k), (k, 0, r)) T = Sm.doit() T2 = T.combsimp().rewrite(factorial) assert T2 == factorial(m + n)/(factorial(r)*factorial(m + n - r)) assert T2 == binomial(m + n, r).rewrite(factorial) # rewrite(binomial) is not working. # https://github.com/sympy/sympy/issues/7135 T3 = T2.rewrite(binomial) assert T3 == binomial(m + n, r) @XFAIL def test_R11(): n, k = symbols('n k', integer=True, positive=True) sk = binomial(n, k)*fibonacci(k) Sm = Sum(sk, (k, 0, n)) T = Sm.doit() # Fibonacci simplification not implemented # https://github.com/sympy/sympy/issues/7134 assert T == fibonacci(2*n) @XFAIL def test_R12(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(fibonacci(k)**2, (k, 0, n)) T = Sm.doit() assert T == fibonacci(n)*fibonacci(n + 1) @XFAIL def test_R13(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(sin(k*x), (k, 1, n)) T = Sm.doit() # Sum is not calculated assert T.simplify() == cot(x/2)/2 - cos(x*(2*n + 1)/2)/(2*sin(x/2)) @XFAIL def test_R14(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(sin((2*k - 1)*x), (k, 1, n)) T = Sm.doit() # Sum is not calculated assert T.simplify() == sin(n*x)**2/sin(x) @XFAIL def test_R15(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(binomial(n - k, k), (k, 0, floor(n/2))) T = Sm.doit() # Sum is not calculated assert T.simplify() == fibonacci(n + 1) def test_R16(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/k**2 + 1/k**3, (k, 1, oo)) assert Sm.doit() == zeta(3) + pi**2/6 def test_R17(): k = symbols('k', integer=True, positive=True) assert abs(float(Sum(1/k**2 + 1/k**3, (k, 1, oo))) - 2.8469909700078206) < 1e-15 def test_R18(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/(2**k*k**2), (k, 1, oo)) T = Sm.doit() assert T.simplify() == -log(2)**2/2 + pi**2/12 @slow @XFAIL def test_R19(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/((3*k + 1)*(3*k + 2)*(3*k + 3)), (k, 0, oo)) T = Sm.doit() # assert fails, T not simplified assert T.simplify() == -log(3)/4 + sqrt(3)*pi/12 @XFAIL def test_R20(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(binomial(n, 4*k), (k, 0, oo)) T = Sm.doit() # assert fails, T not simplified assert T.simplify() == 2**(n/2)*cos(pi*n/4)/2 + 2**(n - 1)/2 @XFAIL def test_R21(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/(sqrt(k*(k + 1)) * (sqrt(k) + sqrt(k + 1))), (k, 1, oo)) T = Sm.doit() # Sum not calculated assert T.simplify() == 1 # test_R22 answer not available in Wester samples # Sum(Sum(binomial(n, k)*binomial(n - k, n - 2*k)*x**n*y**(n - 2*k), # (k, 0, floor(n/2))), (n, 0, oo)) with abs(x*y)<1? @XFAIL def test_R23(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(Sum((factorial(n)/(factorial(k)**2*factorial(n - 2*k)))* (x/y)**k*(x*y)**(n - k), (n, 2*k, oo)), (k, 0, oo)) # Missing how to express constraint abs(x*y)<1? T = Sm.doit() # Sum not calculated assert T == -1/sqrt(x**2*y**2 - 4*x**2 - 2*x*y + 1) def test_R24(): m, k = symbols('m k', integer=True, positive=True) Sm = Sum(Product(k/(2*k - 1), (k, 1, m)), (m, 2, oo)) assert Sm.doit() == pi/2 def test_S1(): k = symbols('k', integer=True, positive=True) Pr = Product(gamma(k/3), (k, 1, 8)) assert Pr.doit().simplify() == 640*sqrt(3)*pi**3/6561 def test_S2(): n, k = symbols('n k', integer=True, positive=True) assert Product(k, (k, 1, n)).doit() == factorial(n) def test_S3(): n, k = symbols('n k', integer=True, positive=True) assert Product(x**k, (k, 1, n)).doit().simplify() == x**(n*(n + 1)/2) def test_S4(): n, k = symbols('n k', integer=True, positive=True) assert Product(1 + 1/k, (k, 1, n -1)).doit().simplify() == n def test_S5(): n, k = symbols('n k', integer=True, positive=True) assert (Product((2*k - 1)/(2*k), (k, 1, n)).doit().gammasimp() == gamma(n + S.Half)/(sqrt(pi)*gamma(n + 1))) @XFAIL def test_S6(): n, k = symbols('n k', integer=True, positive=True) # Product does not evaluate assert (Product(x**2 -2*x*cos(k*pi/n) + 1, (k, 1, n - 1)).doit().simplify() == (x**(2*n) - 1)/(x**2 - 1)) @XFAIL def test_S7(): k = symbols('k', integer=True, positive=True) Pr = Product((k**3 - 1)/(k**3 + 1), (k, 2, oo)) T = Pr.doit() # Product does not evaluate assert T.simplify() == R(2, 3) @XFAIL def test_S8(): k = symbols('k', integer=True, positive=True) Pr = Product(1 - 1/(2*k)**2, (k, 1, oo)) T = Pr.doit() # Product does not evaluate assert T.simplify() == 2/pi @XFAIL def test_S9(): k = symbols('k', integer=True, positive=True) Pr = Product(1 + (-1)**(k + 1)/(2*k - 1), (k, 1, oo)) T = Pr.doit() # Product produces 0 # https://github.com/sympy/sympy/issues/7133 assert T.simplify() == sqrt(2) @XFAIL def test_S10(): k = symbols('k', integer=True, positive=True) Pr = Product((k*(k + 1) + 1 + I)/(k*(k + 1) + 1 - I), (k, 0, oo)) T = Pr.doit() # Product does not evaluate assert T.simplify() == -1 def test_T1(): assert limit((1 + 1/n)**n, n, oo) == E assert limit((1 - cos(x))/x**2, x, 0) == S.Half def test_T2(): assert limit((3**x + 5**x)**(1/x), x, oo) == 5 def test_T3(): assert limit(log(x)/(log(x) + sin(x)), x, oo) == 1 def test_T4(): assert limit((exp(x*exp(-x)/(exp(-x) + exp(-2*x**2/(x + 1)))) - exp(x))/x, x, oo) == -exp(2) def test_T5(): assert limit(x*log(x)*log(x*exp(x) - x**2)**2/log(log(x**2 + 2*exp(exp(3*x**3*log(x))))), x, oo) == R(1, 3) def test_T6(): assert limit(1/n * factorial(n)**(1/n), n, oo) == exp(-1) def test_T7(): limit(1/n * gamma(n + 1)**(1/n), n, oo) def test_T8(): a, z = symbols('a z', real=True, positive=True) assert limit(gamma(z + a)/gamma(z)*exp(-a*log(z)), z, oo) == 1 @XFAIL def test_T9(): z, k = symbols('z k', real=True, positive=True) # raises NotImplementedError: # Don't know how to calculate the mrv of '(1, k)' assert limit(hyper((1, k), (1,), z/k), k, oo) == exp(z) @XFAIL def test_T10(): # No longer raises PoleError, but should return euler-mascheroni constant assert limit(zeta(x) - 1/(x - 1), x, 1) == integrate(-1/x + 1/floor(x), (x, 1, oo)) @XFAIL def test_T11(): n, k = symbols('n k', integer=True, positive=True) # evaluates to 0 assert limit(n**x/(x*product((1 + x/k), (k, 1, n))), n, oo) == gamma(x) def test_T12(): x, t = symbols('x t', real=True) # Does not evaluate the limit but returns an expression with erf assert limit(x * integrate(exp(-t**2), (t, 0, x))/(1 - exp(-x**2)), x, 0) == 1 def test_T13(): x = symbols('x', real=True) assert [limit(x/abs(x), x, 0, dir='-'), limit(x/abs(x), x, 0, dir='+')] == [-1, 1] def test_T14(): x = symbols('x', real=True) assert limit(atan(-log(x)), x, 0, dir='+') == pi/2 def test_U1(): x = symbols('x', real=True) assert diff(abs(x), x) == sign(x) def test_U2(): f = Lambda(x, Piecewise((-x, x < 0), (x, x >= 0))) assert diff(f(x), x) == Piecewise((-1, x < 0), (1, x >= 0)) def test_U3(): f = Lambda(x, Piecewise((x**2 - 1, x == 1), (x**3, x != 1))) f1 = Lambda(x, diff(f(x), x)) assert f1(x) == 3*x**2 assert f1(1) == 3 @XFAIL def test_U4(): n = symbols('n', integer=True, positive=True) x = symbols('x', real=True) d = diff(x**n, x, n) assert d.rewrite(factorial) == factorial(n) def test_U5(): # issue 6681 t = symbols('t') ans = ( Derivative(f(g(t)), g(t))*Derivative(g(t), (t, 2)) + Derivative(f(g(t)), (g(t), 2))*Derivative(g(t), t)**2) assert f(g(t)).diff(t, 2) == ans assert ans.doit() == ans def test_U6(): h = Function('h') T = integrate(f(y), (y, h(x), g(x))) assert T.diff(x) == ( f(g(x))*Derivative(g(x), x) - f(h(x))*Derivative(h(x), x)) @XFAIL def test_U7(): p, t = symbols('p t', real=True) # Exact differential => d(V(P, T)) => dV/dP DP + dV/dT DT # raises ValueError: Since there is more than one variable in the # expression, the variable(s) of differentiation must be supplied to # differentiate f(p,t) diff(f(p, t)) def test_U8(): x, y = symbols('x y', real=True) eq = cos(x*y) + x # If SymPy had implicit_diff() function this hack could be avoided # TODO: Replace solve with solveset, current test fails for solveset assert idiff(y - eq, y, x) == (-y*sin(x*y) + 1)/(x*sin(x*y) + 1) def test_U9(): # Wester sample case for Maple: # O29 := diff(f(x, y), x) + diff(f(x, y), y); # /d \ /d \ # |-- f(x, y)| + |-- f(x, y)| # \dx / \dy / # # O30 := factor(subs(f(x, y) = g(x^2 + y^2), %)); # 2 2 # 2 D(g)(x + y ) (x + y) x, y = symbols('x y', real=True) su = diff(f(x, y), x) + diff(f(x, y), y) s2 = su.subs(f(x, y), g(x**2 + y**2)) s3 = s2.doit().factor() # Subs not performed, s3 = 2*(x + y)*Subs(Derivative( # g(_xi_1), _xi_1), _xi_1, x**2 + y**2) # Derivative(g(x*2 + y**2), x**2 + y**2) is not valid in SymPy, # and probably will remain that way. You can take derivatives with respect # to other expressions only if they are atomic, like a symbol or a # function. # D operator should be added to SymPy # See https://github.com/sympy/sympy/issues/4719. assert s3 == (x + y)*Subs(Derivative(g(x), x), x, x**2 + y**2)*2 def test_U10(): # see issue 2519: assert residue((z**3 + 5)/((z**4 - 1)*(z + 1)), z, -1) == R(-9, 4) @XFAIL def test_U11(): # assert (2*dx + dz) ^ (3*dx + dy + dz) ^ (dx + dy + 4*dz) == 8*dx ^ dy ^dz raise NotImplementedError @XFAIL def test_U12(): # Wester sample case: # (c41) /* d(3 x^5 dy /\ dz + 5 x y^2 dz /\ dx + 8 z dx /\ dy) # => (15 x^4 + 10 x y + 8) dx /\ dy /\ dz */ # factor(ext_diff(3*x^5 * dy ~ dz + 5*x*y^2 * dz ~ dx + 8*z * dx ~ dy)); # 4 # (d41) (10 x y + 15 x + 8) dx dy dz raise NotImplementedError( "External diff of differential form not supported") def test_U13(): assert minimum(x**4 - x + 1, x) == -3*2**R(1,3)/8 + 1 @XFAIL def test_U14(): #f = 1/(x**2 + y**2 + 1) #assert [minimize(f), maximize(f)] == [0,1] raise NotImplementedError("minimize(), maximize() not supported") @XFAIL def test_U15(): raise NotImplementedError("minimize() not supported and also solve does \ not support multivariate inequalities") @XFAIL def test_U16(): raise NotImplementedError("minimize() not supported in SymPy and also \ solve does not support multivariate inequalities") @XFAIL def test_U17(): raise NotImplementedError("Linear programming, symbolic simplex not \ supported in SymPy") def test_V1(): x = symbols('x', real=True) assert integrate(abs(x), x) == Piecewise((-x**2/2, x <= 0), (x**2/2, True)) def test_V2(): assert integrate(Piecewise((-x, x < 0), (x, x >= 0)), x ) == Piecewise((-x**2/2, x < 0), (x**2/2, True)) def test_V3(): assert integrate(1/(x**3 + 2),x).diff().simplify() == 1/(x**3 + 2) def test_V4(): assert integrate(2**x/sqrt(1 + 4**x), x) == asinh(2**x)/log(2) @XFAIL def test_V5(): # Returns (-45*x**2 + 80*x - 41)/(5*sqrt(2*x - 1)*(4*x**2 - 4*x + 1)) assert (integrate((3*x - 5)**2/(2*x - 1)**R(7, 2), x).simplify() == (-41 + 80*x - 45*x**2)/(5*(2*x - 1)**R(5, 2))) @XFAIL def test_V6(): # returns RootSum(40*_z**2 - 1, Lambda(_i, _i*log(-4*_i + exp(-m*x))))/m assert (integrate(1/(2*exp(m*x) - 5*exp(-m*x)), x) == sqrt(10)*( log(2*exp(m*x) - sqrt(10)) - log(2*exp(m*x) + sqrt(10)))/(20*m)) def test_V7(): r1 = integrate(sinh(x)**4/cosh(x)**2) assert r1.simplify() == x*R(-3, 2) + sinh(x)**3/(2*cosh(x)) + 3*tanh(x)/2 @XFAIL def test_V8_V9(): #Macsyma test case: #(c27) /* This example involves several symbolic parameters # => 1/sqrt(b^2 - a^2) log([sqrt(b^2 - a^2) tan(x/2) + a + b]/ # [sqrt(b^2 - a^2) tan(x/2) - a - b]) (a^2 < b^2) # [Gradshteyn and Ryzhik 2.553(3)] */ #assume(b^2 > a^2)$ #(c28) integrate(1/(a + b*cos(x)), x); #(c29) trigsimp(ratsimp(diff(%, x))); # 1 #(d29) ------------ # b cos(x) + a raise NotImplementedError( "Integrate with assumption not supported") def test_V10(): assert integrate(1/(3 + 3*cos(x) + 4*sin(x)), x) == log(tan(x/2) + R(3, 4))/4 def test_V11(): r1 = integrate(1/(4 + 3*cos(x) + 4*sin(x)), x) r2 = factor(r1) assert (logcombine(r2, force=True) == log(((tan(x/2) + 1)/(tan(x/2) + 7))**R(1, 3))) def test_V12(): r1 = integrate(1/(5 + 3*cos(x) + 4*sin(x)), x) assert r1 == -1/(tan(x/2) + 2) @XFAIL def test_V13(): r1 = integrate(1/(6 + 3*cos(x) + 4*sin(x)), x) # expression not simplified, returns: -sqrt(11)*I*log(tan(x/2) + 4/3 # - sqrt(11)*I/3)/11 + sqrt(11)*I*log(tan(x/2) + 4/3 + sqrt(11)*I/3)/11 assert r1.simplify() == 2*sqrt(11)*atan(sqrt(11)*(3*tan(x/2) + 4)/11)/11 @slow @XFAIL def test_V14(): r1 = integrate(log(abs(x**2 - y**2)), x) # Piecewise result does not simplify to the desired result. assert (r1.simplify() == x*log(abs(x**2 - y**2)) + y*log(x + y) - y*log(x - y) - 2*x) def test_V15(): r1 = integrate(x*acot(x/y), x) assert simplify(r1 - (x*y + (x**2 + y**2)*acot(x/y))/2) == 0 @XFAIL def test_V16(): # Integral not calculated assert integrate(cos(5*x)*Ci(2*x), x) == Ci(2*x)*sin(5*x)/5 - (Si(3*x) + Si(7*x))/10 @XFAIL def test_V17(): r1 = integrate((diff(f(x), x)*g(x) - f(x)*diff(g(x), x))/(f(x)**2 - g(x)**2), x) # integral not calculated assert simplify(r1 - (f(x) - g(x))/(f(x) + g(x))/2) == 0 @XFAIL def test_W1(): # The function has a pole at y. # The integral has a Cauchy principal value of zero but SymPy returns -I*pi # https://github.com/sympy/sympy/issues/7159 assert integrate(1/(x - y), (x, y - 1, y + 1)) == 0 @XFAIL def test_W2(): # The function has a pole at y. # The integral is divergent but SymPy returns -2 # https://github.com/sympy/sympy/issues/7160 # Test case in Macsyma: # (c6) errcatch(integrate(1/(x - a)^2, x, a - 1, a + 1)); # Integral is divergent assert integrate(1/(x - y)**2, (x, y - 1, y + 1)) is zoo @XFAIL @slow def test_W3(): # integral is not calculated # https://github.com/sympy/sympy/issues/7161 assert integrate(sqrt(x + 1/x - 2), (x, 0, 1)) == R(4, 3) @XFAIL @slow def test_W4(): # integral is not calculated assert integrate(sqrt(x + 1/x - 2), (x, 1, 2)) == -2*sqrt(2)/3 + R(4, 3) @XFAIL @slow def test_W5(): # integral is not calculated assert integrate(sqrt(x + 1/x - 2), (x, 0, 2)) == -2*sqrt(2)/3 + R(8, 3) @XFAIL @slow def test_W6(): # integral is not calculated assert integrate(sqrt(2 - 2*cos(2*x))/2, (x, pi*R(-3, 4), -pi/4)) == sqrt(2) def test_W7(): a = symbols('a', real=True, positive=True) r1 = integrate(cos(x)/(x**2 + a**2), (x, -oo, oo)) assert r1.simplify() == pi*exp(-a)/a @XFAIL def test_W8(): # Test case in Mathematica: # In[19]:= Integrate[t^(a - 1)/(1 + t), {t, 0, Infinity}, # Assumptions -> 0 < a < 1] # Out[19]= Pi Csc[a Pi] raise NotImplementedError( "Integrate with assumption 0 < a < 1 not supported") @XFAIL @slow def test_W9(): # Integrand with a residue at infinity => -2 pi [sin(pi/5) + sin(2pi/5)] # (principal value) [Levinson and Redheffer, p. 234] *) r1 = integrate(5*x**3/(1 + x + x**2 + x**3 + x**4), (x, -oo, oo)) r2 = r1.doit() assert r2 == -2*pi*(sqrt(-sqrt(5)/8 + 5/8) + sqrt(sqrt(5)/8 + 5/8)) @XFAIL def test_W10(): # integrate(1/[1 + x + x^2 + ... + x^(2 n)], x = -infinity..infinity) = # 2 pi/(2 n + 1) [1 + cos(pi/[2 n + 1])] csc(2 pi/[2 n + 1]) # [Levinson and Redheffer, p. 255] => 2 pi/5 [1 + cos(pi/5)] csc(2 pi/5) */ r1 = integrate(x/(1 + x + x**2 + x**4), (x, -oo, oo)) r2 = r1.doit() assert r2 == 2*pi*(sqrt(5)/4 + 5/4)*csc(pi*R(2, 5))/5 @XFAIL def test_W11(): # integral not calculated assert (integrate(sqrt(1 - x**2)/(1 + x**2), (x, -1, 1)) == pi*(-1 + sqrt(2))) def test_W12(): p = symbols('p', real=True, positive=True) q = symbols('q', real=True) r1 = integrate(x*exp(-p*x**2 + 2*q*x), (x, -oo, oo)) assert r1.simplify() == sqrt(pi)*q*exp(q**2/p)/p**R(3, 2) @XFAIL def test_W13(): # Integral not calculated. Expected result is 2*(Euler_mascheroni_constant) r1 = integrate(1/log(x) + 1/(1 - x) - log(log(1/x)), (x, 0, 1)) assert r1 == 2*EulerGamma def test_W14(): assert integrate(sin(x)/x*exp(2*I*x), (x, -oo, oo)) == 0 @XFAIL def test_W15(): # integral not calculated assert integrate(log(gamma(x))*cos(6*pi*x), (x, 0, 1)) == R(1, 12) def test_W16(): assert integrate((1 + x)**3*legendre_poly(1, x)*legendre_poly(2, x), (x, -1, 1)) == R(36, 35) def test_W17(): a, b = symbols('a b', real=True, positive=True) assert integrate(exp(-a*x)*besselj(0, b*x), (x, 0, oo)) == 1/(b*sqrt(a**2/b**2 + 1)) def test_W18(): assert integrate((besselj(1, x)/x)**2, (x, 0, oo)) == 4/(3*pi) @XFAIL def test_W19(): # Integral not calculated # Expected result is (cos 7 - 1)/7 [Gradshteyn and Ryzhik 6.782(3)] assert integrate(Ci(x)*besselj(0, 2*sqrt(7*x)), (x, 0, oo)) == (cos(7) - 1)/7 @XFAIL def test_W20(): # integral not calculated assert (integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1)) == -pi**2/36 - R(17, 108) + zeta(3)/4 + (-pi**2/2 - 4*log(2) + log(2)**2 + 35/3)*log(2)/9) def test_W21(): assert abs(N(integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1))) - 0.210882859565594) < 1e-15 def test_W22(): t, u = symbols('t u', real=True) s = Lambda(x, Piecewise((1, And(x >= 1, x <= 2)), (0, True))) assert integrate(s(t)*cos(t), (t, 0, u)) == Piecewise( (0, u < 0), (-sin(Min(1, u)) + sin(Min(2, u)), True)) @slow def test_W23(): a, b = symbols('a b', real=True, positive=True) r1 = integrate(integrate(x/(x**2 + y**2), (x, a, b)), (y, -oo, oo)) assert r1.collect(pi).cancel() == -pi*a + pi*b def test_W23b(): # like W23 but limits are reversed a, b = symbols('a b', real=True, positive=True) r2 = integrate(integrate(x/(x**2 + y**2), (y, -oo, oo)), (x, a, b)) assert r2.collect(pi) == pi*(-a + b) @XFAIL @slow def test_W24(): if ON_TRAVIS: skip("Too slow for travis.") # Not that slow, but does not fully evaluate so simplify is slow. # Maybe also require doit() x, y = symbols('x y', real=True) r1 = integrate(integrate(sqrt(x**2 + y**2), (x, 0, 1)), (y, 0, 1)) assert (r1 - (sqrt(2) + asinh(1))/3).simplify() == 0 @XFAIL @slow def test_W25(): if ON_TRAVIS: skip("Too slow for travis.") a, x, y = symbols('a x y', real=True) i1 = integrate( sin(a)*sin(y)/sqrt(1 - sin(a)**2*sin(x)**2*sin(y)**2), (x, 0, pi/2)) i2 = integrate(i1, (y, 0, pi/2)) assert (i2 - pi*a/2).simplify() == 0 def test_W26(): x, y = symbols('x y', real=True) assert integrate(integrate(abs(y - x**2), (y, 0, 2)), (x, -1, 1)) == R(46, 15) def test_W27(): a, b, c = symbols('a b c') assert integrate(integrate(integrate(1, (z, 0, c*(1 - x/a - y/b))), (y, 0, b*(1 - x/a))), (x, 0, a)) == a*b*c/6 def test_X1(): v, c = symbols('v c', real=True) assert (series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8) == 5*v**6/(16*c**6) + 3*v**4/(8*c**4) + v**2/(2*c**2) + 1 + O(v**8)) def test_X2(): v, c = symbols('v c', real=True) s1 = series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8) assert (1/s1**2).series(v, x0=0, n=8) == -v**2/c**2 + 1 + O(v**8) def test_X3(): s1 = (sin(x).series()/cos(x).series()).series() s2 = tan(x).series() assert s2 == x + x**3/3 + 2*x**5/15 + O(x**6) assert s1 == s2 def test_X4(): s1 = log(sin(x)/x).series() assert s1 == -x**2/6 - x**4/180 + O(x**6) assert log(series(sin(x)/x)).series() == s1 @XFAIL def test_X5(): # test case in Mathematica syntax: # In[21]:= (* => [a f'(a d) + g(b d) + integrate(h(c y), y = 0..d)] # + [a^2 f''(a d) + b g'(b d) + h(c d)] (x - d) *) # In[22]:= D[f[a*x], x] + g[b*x] + Integrate[h[c*y], {y, 0, x}] # Out[22]= g[b x] + Integrate[h[c y], {y, 0, x}] + a f'[a x] # In[23]:= Series[%, {x, d, 1}] # Out[23]= (g[b d] + Integrate[h[c y], {y, 0, d}] + a f'[a d]) + # 2 2 # (h[c d] + b g'[b d] + a f''[a d]) (-d + x) + O[-d + x] h = Function('h') a, b, c, d = symbols('a b c d', real=True) # series() raises NotImplementedError: # The _eval_nseries method should be added to <class # 'sympy.core.function.Subs'> to give terms up to O(x**n) at x=0 series(diff(f(a*x), x) + g(b*x) + integrate(h(c*y), (y, 0, x)), x, x0=d, n=2) # assert missing, until exception is removed def test_X6(): # Taylor series of nonscalar objects (noncommutative multiplication) # expected result => (B A - A B) t^2/2 + O(t^3) [Stanly Steinberg] a, b = symbols('a b', commutative=False, scalar=False) assert (series(exp((a + b)*x) - exp(a*x) * exp(b*x), x, x0=0, n=3) == x**2*(-a*b/2 + b*a/2) + O(x**3)) def test_X7(): # => sum( Bernoulli[k]/k! x^(k - 2), k = 1..infinity ) # = 1/x^2 - 1/(2 x) + 1/12 - x^2/720 + x^4/30240 + O(x^6) # [Levinson and Redheffer, p. 173] assert (series(1/(x*(exp(x) - 1)), x, 0, 7) == x**(-2) - 1/(2*x) + R(1, 12) - x**2/720 + x**4/30240 - x**6/1209600 + O(x**7)) def test_X8(): # Puiseux series (terms with fractional degree): # => 1/sqrt(x - 3/2 pi) + (x - 3/2 pi)^(3/2) / 12 + O([x - 3/2 pi]^(7/2)) # see issue 7167: x = symbols('x', real=True) assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) == 1/sqrt(x - pi*R(3, 2)) + (x - pi*R(3, 2))**R(3, 2)/12 + (x - pi*R(3, 2))**R(7, 2)/160 + O((x - pi*R(3, 2))**4, (x, pi*R(3, 2)))) def test_X9(): assert (series(x**x, x, x0=0, n=4) == 1 + x*log(x) + x**2*log(x)**2/2 + x**3*log(x)**3/6 + O(x**4*log(x)**4)) def test_X10(): z, w = symbols('z w') assert (series(log(sinh(z)) + log(cosh(z + w)), z, x0=0, n=2) == log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2)) def test_X11(): z, w = symbols('z w') assert (series(log(sinh(z) * cosh(z + w)), z, x0=0, n=2) == log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2)) @XFAIL def test_X12(): # Look at the generalized Taylor series around x = 1 # Result => (x - 1)^a/e^b [1 - (a + 2 b) (x - 1) / 2 + O((x - 1)^2)] a, b, x = symbols('a b x', real=True) # series returns O(log(x-1)**2) # https://github.com/sympy/sympy/issues/7168 assert (series(log(x)**a*exp(-b*x), x, x0=1, n=2) == (x - 1)**a/exp(b)*(1 - (a + 2*b)*(x - 1)/2 + O((x - 1)**2))) def test_X13(): assert series(sqrt(2*x**2 + 1), x, x0=oo, n=1) == sqrt(2)*x + O(1/x, (x, oo)) @XFAIL def test_X14(): # Wallis' product => 1/sqrt(pi n) + ... [Knopp, p. 385] assert series(1/2**(2*n)*binomial(2*n, n), n, x==oo, n=1) == 1/(sqrt(pi)*sqrt(n)) + O(1/x, (x, oo)) @SKIP("https://github.com/sympy/sympy/issues/7164") def test_X15(): # => 0!/x - 1!/x^2 + 2!/x^3 - 3!/x^4 + O(1/x^5) [Knopp, p. 544] x, t = symbols('x t', real=True) # raises RuntimeError: maximum recursion depth exceeded # https://github.com/sympy/sympy/issues/7164 # 2019-02-17: Raises # PoleError: # Asymptotic expansion of Ei around [-oo] is not implemented. e1 = integrate(exp(-t)/t, (t, x, oo)) assert (series(e1, x, x0=oo, n=5) == 6/x**4 + 2/x**3 - 1/x**2 + 1/x + O(x**(-5), (x, oo))) def test_X16(): # Multivariate Taylor series expansion => 1 - (x^2 + 2 x y + y^2)/2 + O(x^4) assert (series(cos(x + y), x + y, x0=0, n=4) == 1 - (x + y)**2/2 + O(x**4 + x**3*y + x**2*y**2 + x*y**3 + y**4, x, y)) @XFAIL def test_X17(): # Power series (compute the general formula) # (c41) powerseries(log(sin(x)/x), x, 0); # /aquarius/data2/opt/local/macsyma_422/library1/trgred.so being loaded. # inf # ==== i1 2 i1 2 i1 # \ (- 1) 2 bern(2 i1) x # (d41) > ------------------------------ # / 2 i1 (2 i1)! # ==== # i1 = 1 # fps does not calculate assert fps(log(sin(x)/x)) == \ Sum((-1)**k*2**(2*k - 1)*bernoulli(2*k)*x**(2*k)/(k*factorial(2*k)), (k, 1, oo)) @XFAIL def test_X18(): # Power series (compute the general formula). Maple FPS: # > FormalPowerSeries(exp(-x)*sin(x), x = 0); # infinity # ----- (1/2 k) k # \ 2 sin(3/4 k Pi) x # ) ------------------------- # / k! # ----- # # Now, sympy returns # oo # _____ # \ ` # \ / k k\ # \ k |I*(-1 - I) I*(-1 + I) | # \ x *|----------- - -----------| # / \ 2 2 / # / ------------------------------ # / k! # /____, # k = 0 k = Dummy('k') assert fps(exp(-x)*sin(x)) == \ Sum(2**(S.Half*k)*sin(R(3, 4)*k*pi)*x**k/factorial(k), (k, 0, oo)) @XFAIL def test_X19(): # (c45) /* Derive an explicit Taylor series solution of y as a function of # x from the following implicit relation: # y = x - 1 + (x - 1)^2/2 + 2/3 (x - 1)^3 + (x - 1)^4 + # 17/10 (x - 1)^5 + ... # */ # x = sin(y) + cos(y); # Time= 0 msecs # (d45) x = sin(y) + cos(y) # # (c46) taylor_revert(%, y, 7); raise NotImplementedError("Solve using series not supported. \ Inverse Taylor series expansion also not supported") @XFAIL def test_X20(): # Pade (rational function) approximation => (2 - x)/(2 + x) # > numapprox[pade](exp(-x), x = 0, [1, 1]); # bytes used=9019816, alloc=3669344, time=13.12 # 1 - 1/2 x # --------- # 1 + 1/2 x # mpmath support numeric Pade approximant but there is # no symbolic implementation in SymPy # https://en.wikipedia.org/wiki/Pad%C3%A9_approximant raise NotImplementedError("Symbolic Pade approximant not supported") def test_X21(): """ Test whether `fourier_series` of x periodical on the [-p, p] interval equals `- (2 p / pi) sum( (-1)^n / n sin(n pi x / p), n = 1..infinity )`. """ p = symbols('p', positive=True) n = symbols('n', positive=True, integer=True) s = fourier_series(x, (x, -p, p)) # All cosine coefficients are equal to 0 assert s.an.formula == 0 # Check for sine coefficients assert s.bn.formula.subs(s.bn.variables[0], 0) == 0 assert s.bn.formula.subs(s.bn.variables[0], n) == \ -2*p/pi * (-1)**n / n * sin(n*pi*x/p) @XFAIL def test_X22(): # (c52) /* => p / 2 # - (2 p / pi^2) sum( [1 - (-1)^n] cos(n pi x / p) / n^2, # n = 1..infinity ) */ # fourier_series(abs(x), x, p); # p # (e52) a = - # 0 2 # # %nn # (2 (- 1) - 2) p # (e53) a = ------------------ # %nn 2 2 # %pi %nn # # (e54) b = 0 # %nn # # Time= 5290 msecs # inf %nn %pi %nn x # ==== (2 (- 1) - 2) cos(---------) # \ p # p > ------------------------------- # / 2 # ==== %nn # %nn = 1 p # (d54) ----------------------------------------- + - # 2 2 # %pi raise NotImplementedError("Fourier series not supported") def test_Y1(): t = symbols('t', real=True, positive=True) w = symbols('w', real=True) s = symbols('s') F, _, _ = laplace_transform(cos((w - 1)*t), t, s) assert F == s/(s**2 + (w - 1)**2) def test_Y2(): t = symbols('t', real=True, positive=True) w = symbols('w', real=True) s = symbols('s') f = inverse_laplace_transform(s/(s**2 + (w - 1)**2), s, t) assert f == cos(t*w - t) def test_Y3(): t = symbols('t', real=True, positive=True) w = symbols('w', real=True) s = symbols('s') F, _, _ = laplace_transform(sinh(w*t)*cosh(w*t), t, s) assert F == w/(s**2 - 4*w**2) def test_Y4(): t = symbols('t', real=True, positive=True) s = symbols('s') F, _, _ = laplace_transform(erf(3/sqrt(t)), t, s) assert F == (1 - exp(-6*sqrt(s)))/s @XFAIL def test_Y5_Y6(): # Solve y'' + y = 4 [H(t - 1) - H(t - 2)], y(0) = 1, y'(0) = 0 where H is the # Heaviside (unit step) function (the RHS describes a pulse of magnitude 4 and # duration 1). See David A. Sanchez, Richard C. Allen, Jr. and Walter T. # Kyner, _Differential Equations: An Introduction_, Addison-Wesley Publishing # Company, 1983, p. 211. First, take the Laplace transform of the ODE # => s^2 Y(s) - s + Y(s) = 4/s [e^(-s) - e^(-2 s)] # where Y(s) is the Laplace transform of y(t) t = symbols('t', real=True, positive=True) s = symbols('s') y = Function('y') F, _, _ = laplace_transform(diff(y(t), t, 2) + y(t) - 4*(Heaviside(t - 1) - Heaviside(t - 2)), t, s) # Laplace transform for diff() not calculated # https://github.com/sympy/sympy/issues/7176 assert (F == s**2*LaplaceTransform(y(t), t, s) - s + LaplaceTransform(y(t), t, s) - 4*exp(-s)/s + 4*exp(-2*s)/s) # TODO implement second part of test case # Now, solve for Y(s) and then take the inverse Laplace transform # => Y(s) = s/(s^2 + 1) + 4 [1/s - s/(s^2 + 1)] [e^(-s) - e^(-2 s)] # => y(t) = cos t + 4 {[1 - cos(t - 1)] H(t - 1) - [1 - cos(t - 2)] H(t - 2)} @XFAIL def test_Y7(): # What is the Laplace transform of an infinite square wave? # => 1/s + 2 sum( (-1)^n e^(- s n a)/s, n = 1..infinity ) # [Sanchez, Allen and Kyner, p. 213] t = symbols('t', real=True, positive=True) a = symbols('a', real=True) s = symbols('s') F, _, _ = laplace_transform(1 + 2*Sum((-1)**n*Heaviside(t - n*a), (n, 1, oo)), t, s) # returns 2*LaplaceTransform(Sum((-1)**n*Heaviside(-a*n + t), # (n, 1, oo)), t, s) + 1/s # https://github.com/sympy/sympy/issues/7177 assert F == 2*Sum((-1)**n*exp(-a*n*s)/s, (n, 1, oo)) + 1/s @XFAIL def test_Y8(): assert fourier_transform(1, x, z) == DiracDelta(z) def test_Y9(): assert (fourier_transform(exp(-9*x**2), x, z) == sqrt(pi)*exp(-pi**2*z**2/9)/3) def test_Y10(): assert (fourier_transform(abs(x)*exp(-3*abs(x)), x, z).cancel() == (-8*pi**2*z**2 + 18)/(16*pi**4*z**4 + 72*pi**2*z**2 + 81)) @SKIP("https://github.com/sympy/sympy/issues/7181") @slow def test_Y11(): # => pi cot(pi s) (0 < Re s < 1) [Gradshteyn and Ryzhik 17.43(5)] x, s = symbols('x s') # raises RuntimeError: maximum recursion depth exceeded # https://github.com/sympy/sympy/issues/7181 # Update 2019-02-17 raises: # TypeError: cannot unpack non-iterable MellinTransform object F, _, _ = mellin_transform(1/(1 - x), x, s) assert F == pi*cot(pi*s) @XFAIL def test_Y12(): # => 2^(s - 4) gamma(s/2)/gamma(4 - s/2) (0 < Re s < 1) # [Gradshteyn and Ryzhik 17.43(16)] x, s = symbols('x s') # returns Wrong value -2**(s - 4)*gamma(s/2 - 3)/gamma(-s/2 + 1) # https://github.com/sympy/sympy/issues/7182 F, _, _ = mellin_transform(besselj(3, x)/x**3, x, s) assert F == -2**(s - 4)*gamma(s/2)/gamma(-s/2 + 4) @XFAIL def test_Y13(): # Z[H(t - m T)] => z/[z^m (z - 1)] (H is the Heaviside (unit step) function) z raise NotImplementedError("z-transform not supported") @XFAIL def test_Y14(): # Z[H(t - m T)] => z/[z^m (z - 1)] (H is the Heaviside (unit step) function) raise NotImplementedError("z-transform not supported") def test_Z1(): r = Function('r') assert (rsolve(r(n + 2) - 2*r(n + 1) + r(n) - 2, r(n), {r(0): 1, r(1): m}).simplify() == n**2 + n*(m - 2) + 1) def test_Z2(): r = Function('r') assert (rsolve(r(n) - (5*r(n - 1) - 6*r(n - 2)), r(n), {r(0): 0, r(1): 1}) == -2**n + 3**n) def test_Z3(): # => r(n) = Fibonacci[n + 1] [Cohen, p. 83] r = Function('r') # recurrence solution is correct, Wester expects it to be simplified to # fibonacci(n+1), but that is quite hard expected = ((S(1)/2 - sqrt(5)/2)**n*(S(1)/2 - sqrt(5)/10) + (S(1)/2 + sqrt(5)/2)**n*(sqrt(5)/10 + S(1)/2)) sol = rsolve(r(n) - (r(n - 1) + r(n - 2)), r(n), {r(1): 1, r(2): 2}) assert sol == expected @XFAIL def test_Z4(): # => [c^(n+1) [c^(n+1) - 2 c - 2] + (n+1) c^2 + 2 c - n] / [(c-1)^3 (c+1)] # [Joan Z. Yu and Robert Israel in sci.math.symbolic] r = Function('r') c = symbols('c') # raises ValueError: Polynomial or rational function expected, # got '(c**2 - c**n)/(c - c**n) s = rsolve(r(n) - ((1 + c - c**(n-1) - c**(n+1))/(1 - c**n)*r(n - 1) - c*(1 - c**(n-2))/(1 - c**(n-1))*r(n - 2) + 1), r(n), {r(1): 1, r(2): (2 + 2*c + c**2)/(1 + c)}) assert (s - (c*(n + 1)*(c*(n + 1) - 2*c - 2) + (n + 1)*c**2 + 2*c - n)/((c-1)**3*(c+1)) == 0) @XFAIL def test_Z5(): # Second order ODE with initial conditions---solve directly # transform: f(t) = sin(2 t)/8 - t cos(2 t)/4 C1, C2 = symbols('C1 C2') # initial conditions not supported, this is a manual workaround # https://github.com/sympy/sympy/issues/4720 eq = Derivative(f(x), x, 2) + 4*f(x) - sin(2*x) sol = dsolve(eq, f(x)) f0 = Lambda(x, sol.rhs) assert f0(x) == C2*sin(2*x) + (C1 - x/4)*cos(2*x) f1 = Lambda(x, diff(f0(x), x)) # TODO: Replace solve with solveset, when it works for solveset const_dict = solve((f0(0), f1(0))) result = f0(x).subs(C1, const_dict[C1]).subs(C2, const_dict[C2]) assert result == -x*cos(2*x)/4 + sin(2*x)/8 # Result is OK, but ODE solving with initial conditions should be # supported without all this manual work raise NotImplementedError('ODE solving with initial conditions \ not supported') @XFAIL def test_Z6(): # Second order ODE with initial conditions---solve using Laplace # transform: f(t) = sin(2 t)/8 - t cos(2 t)/4 t = symbols('t', real=True, positive=True) s = symbols('s') eq = Derivative(f(t), t, 2) + 4*f(t) - sin(2*t) F, _, _ = laplace_transform(eq, t, s) # Laplace transform for diff() not calculated # https://github.com/sympy/sympy/issues/7176 assert (F == s**2*LaplaceTransform(f(t), t, s) + 4*LaplaceTransform(f(t), t, s) - 2/(s**2 + 4)) # rest of test case not implemented
12ceab880da59449913cf445ddf66e86e6a4dc59d06e2e6494d9b5c15d00a9b9
from textwrap import dedent from itertools import islice, product from sympy import ( symbols, Integer, Integral, Tuple, Dummy, Basic, default_sort_key, Matrix, factorial, true) from sympy.combinatorics import RGS_enum, RGS_unrank, Permutation from sympy.core.compatibility import iterable from sympy.utilities.iterables import ( _partition, _set_partitions, binary_partitions, bracelets, capture, cartes, common_prefix, common_suffix, connected_components, dict_merge, filter_symbols, flatten, generate_bell, generate_derangements, generate_involutions, generate_oriented_forest, group, has_dups, ibin, iproduct, kbins, minlex, multiset, multiset_combinations, multiset_partitions, multiset_permutations, necklaces, numbered_symbols, ordered, partitions, permutations, postfixes, postorder_traversal, prefixes, reshape, rotate_left, rotate_right, runs, sift, strongly_connected_components, subsets, take, topological_sort, unflatten, uniq, variations, ordered_partitions, rotations, is_palindromic) from sympy.utilities.enumerative import ( factoring_visitor, multiset_partitions_taocp ) from sympy.core.singleton import S from sympy.functions.elementary.piecewise import Piecewise, ExprCondPair from sympy.testing.pytest import raises w, x, y, z = symbols('w,x,y,z') def test_is_palindromic(): assert is_palindromic('') assert is_palindromic('x') assert is_palindromic('xx') assert is_palindromic('xyx') assert not is_palindromic('xy') assert not is_palindromic('xyzx') assert is_palindromic('xxyzzyx', 1) assert not is_palindromic('xxyzzyx', 2) assert is_palindromic('xxyzzyx', 2, -1) assert is_palindromic('xxyzzyx', 2, 6) assert is_palindromic('xxyzyx', 1) assert not is_palindromic('xxyzyx', 2) assert is_palindromic('xxyzyx', 2, 2 + 3) def test_postorder_traversal(): expr = z + w*(x + y) expected = [z, w, x, y, x + y, w*(x + y), w*(x + y) + z] assert list(postorder_traversal(expr, keys=default_sort_key)) == expected assert list(postorder_traversal(expr, keys=True)) == expected expr = Piecewise((x, x < 1), (x**2, True)) expected = [ x, 1, x, x < 1, ExprCondPair(x, x < 1), 2, x, x**2, true, ExprCondPair(x**2, True), Piecewise((x, x < 1), (x**2, True)) ] assert list(postorder_traversal(expr, keys=default_sort_key)) == expected assert list(postorder_traversal( [expr], keys=default_sort_key)) == expected + [[expr]] assert list(postorder_traversal(Integral(x**2, (x, 0, 1)), keys=default_sort_key)) == [ 2, x, x**2, 0, 1, x, Tuple(x, 0, 1), Integral(x**2, Tuple(x, 0, 1)) ] assert list(postorder_traversal(('abc', ('d', 'ef')))) == [ 'abc', 'd', 'ef', ('d', 'ef'), ('abc', ('d', 'ef'))] def test_flatten(): assert flatten((1, (1,))) == [1, 1] assert flatten((x, (x,))) == [x, x] ls = [[(-2, -1), (1, 2)], [(0, 0)]] assert flatten(ls, levels=0) == ls assert flatten(ls, levels=1) == [(-2, -1), (1, 2), (0, 0)] assert flatten(ls, levels=2) == [-2, -1, 1, 2, 0, 0] assert flatten(ls, levels=3) == [-2, -1, 1, 2, 0, 0] raises(ValueError, lambda: flatten(ls, levels=-1)) class MyOp(Basic): pass assert flatten([MyOp(x, y), z]) == [MyOp(x, y), z] assert flatten([MyOp(x, y), z], cls=MyOp) == [x, y, z] assert flatten({1, 11, 2}) == list({1, 11, 2}) def test_iproduct(): assert list(iproduct()) == [()] assert list(iproduct([])) == [] assert list(iproduct([1,2,3])) == [(1,),(2,),(3,)] assert sorted(iproduct([1, 2], [3, 4, 5])) == [ (1,3),(1,4),(1,5),(2,3),(2,4),(2,5)] assert sorted(iproduct([0,1],[0,1],[0,1])) == [ (0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)] assert iterable(iproduct(S.Integers)) is True assert iterable(iproduct(S.Integers, S.Integers)) is True assert (3,) in iproduct(S.Integers) assert (4, 5) in iproduct(S.Integers, S.Integers) assert (1, 2, 3) in iproduct(S.Integers, S.Integers, S.Integers) triples = set(islice(iproduct(S.Integers, S.Integers, S.Integers), 1000)) for n1, n2, n3 in triples: assert isinstance(n1, Integer) assert isinstance(n2, Integer) assert isinstance(n3, Integer) for t in set(product(*([range(-2, 3)]*3))): assert t in iproduct(S.Integers, S.Integers, S.Integers) def test_group(): assert group([]) == [] assert group([], multiple=False) == [] assert group([1]) == [[1]] assert group([1], multiple=False) == [(1, 1)] assert group([1, 1]) == [[1, 1]] assert group([1, 1], multiple=False) == [(1, 2)] assert group([1, 1, 1]) == [[1, 1, 1]] assert group([1, 1, 1], multiple=False) == [(1, 3)] assert group([1, 2, 1]) == [[1], [2], [1]] assert group([1, 2, 1], multiple=False) == [(1, 1), (2, 1), (1, 1)] assert group([1, 1, 2, 2, 2, 1, 3, 3]) == [[1, 1], [2, 2, 2], [1], [3, 3]] assert group([1, 1, 2, 2, 2, 1, 3, 3], multiple=False) == [(1, 2), (2, 3), (1, 1), (3, 2)] def test_subsets(): # combinations assert list(subsets([1, 2, 3], 0)) == [()] assert list(subsets([1, 2, 3], 1)) == [(1,), (2,), (3,)] assert list(subsets([1, 2, 3], 2)) == [(1, 2), (1, 3), (2, 3)] assert list(subsets([1, 2, 3], 3)) == [(1, 2, 3)] l = list(range(4)) assert list(subsets(l, 0, repetition=True)) == [()] assert list(subsets(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)] assert list(subsets(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)] assert list(subsets(l, 3, repetition=True)) == [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 2), (0, 2, 3), (0, 3, 3), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 2), (2, 2, 3), (2, 3, 3), (3, 3, 3)] assert len(list(subsets(l, 4, repetition=True))) == 35 assert list(subsets(l[:2], 3, repetition=False)) == [] assert list(subsets(l[:2], 3, repetition=True)) == [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)] assert list(subsets([1, 2], repetition=True)) == \ [(), (1,), (2,), (1, 1), (1, 2), (2, 2)] assert list(subsets([1, 2], repetition=False)) == \ [(), (1,), (2,), (1, 2)] assert list(subsets([1, 2, 3], 2)) == \ [(1, 2), (1, 3), (2, 3)] assert list(subsets([1, 2, 3], 2, repetition=True)) == \ [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)] def test_variations(): # permutations l = list(range(4)) assert list(variations(l, 0, repetition=False)) == [()] assert list(variations(l, 1, repetition=False)) == [(0,), (1,), (2,), (3,)] assert list(variations(l, 2, repetition=False)) == [(0, 1), (0, 2), (0, 3), (1, 0), (1, 2), (1, 3), (2, 0), (2, 1), (2, 3), (3, 0), (3, 1), (3, 2)] assert list(variations(l, 3, repetition=False)) == [(0, 1, 2), (0, 1, 3), (0, 2, 1), (0, 2, 3), (0, 3, 1), (0, 3, 2), (1, 0, 2), (1, 0, 3), (1, 2, 0), (1, 2, 3), (1, 3, 0), (1, 3, 2), (2, 0, 1), (2, 0, 3), (2, 1, 0), (2, 1, 3), (2, 3, 0), (2, 3, 1), (3, 0, 1), (3, 0, 2), (3, 1, 0), (3, 1, 2), (3, 2, 0), (3, 2, 1)] assert list(variations(l, 0, repetition=True)) == [()] assert list(variations(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)] assert list(variations(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (3, 3)] assert len(list(variations(l, 3, repetition=True))) == 64 assert len(list(variations(l, 4, repetition=True))) == 256 assert list(variations(l[:2], 3, repetition=False)) == [] assert list(variations(l[:2], 3, repetition=True)) == [ (0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1) ] def test_cartes(): assert list(cartes([1, 2], [3, 4, 5])) == \ [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)] assert list(cartes()) == [()] assert list(cartes('a')) == [('a',)] assert list(cartes('a', repeat=2)) == [('a', 'a')] assert list(cartes(list(range(2)))) == [(0,), (1,)] def test_filter_symbols(): s = numbered_symbols() filtered = filter_symbols(s, symbols("x0 x2 x3")) assert take(filtered, 3) == list(symbols("x1 x4 x5")) def test_numbered_symbols(): s = numbered_symbols(cls=Dummy) assert isinstance(next(s), Dummy) assert next(numbered_symbols('C', start=1, exclude=[symbols('C1')])) == \ symbols('C2') def test_sift(): assert sift(list(range(5)), lambda _: _ % 2) == {1: [1, 3], 0: [0, 2, 4]} assert sift([x, y], lambda _: _.has(x)) == {False: [y], True: [x]} assert sift([S.One], lambda _: _.has(x)) == {False: [1]} assert sift([0, 1, 2, 3], lambda x: x % 2, binary=True) == ( [1, 3], [0, 2]) assert sift([0, 1, 2, 3], lambda x: x % 3 == 1, binary=True) == ( [1], [0, 2, 3]) raises(ValueError, lambda: sift([0, 1, 2, 3], lambda x: x % 3, binary=True)) def test_take(): X = numbered_symbols() assert take(X, 5) == list(symbols('x0:5')) assert take(X, 5) == list(symbols('x5:10')) assert take([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5] def test_dict_merge(): assert dict_merge({}, {1: x, y: z}) == {1: x, y: z} assert dict_merge({1: x, y: z}, {}) == {1: x, y: z} assert dict_merge({2: z}, {1: x, y: z}) == {1: x, 2: z, y: z} assert dict_merge({1: x, y: z}, {2: z}) == {1: x, 2: z, y: z} assert dict_merge({1: y, 2: z}, {1: x, y: z}) == {1: x, 2: z, y: z} assert dict_merge({1: x, y: z}, {1: y, 2: z}) == {1: y, 2: z, y: z} def test_prefixes(): assert list(prefixes([])) == [] assert list(prefixes([1])) == [[1]] assert list(prefixes([1, 2])) == [[1], [1, 2]] assert list(prefixes([1, 2, 3, 4, 5])) == \ [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]] def test_postfixes(): assert list(postfixes([])) == [] assert list(postfixes([1])) == [[1]] assert list(postfixes([1, 2])) == [[2], [1, 2]] assert list(postfixes([1, 2, 3, 4, 5])) == \ [[5], [4, 5], [3, 4, 5], [2, 3, 4, 5], [1, 2, 3, 4, 5]] def test_topological_sort(): V = [2, 3, 5, 7, 8, 9, 10, 11] E = [(7, 11), (7, 8), (5, 11), (3, 8), (3, 10), (11, 2), (11, 9), (11, 10), (8, 9)] assert topological_sort((V, E)) == [3, 5, 7, 8, 11, 2, 9, 10] assert topological_sort((V, E), key=lambda v: -v) == \ [7, 5, 11, 3, 10, 8, 9, 2] raises(ValueError, lambda: topological_sort((V, E + [(10, 7)]))) def test_strongly_connected_components(): assert strongly_connected_components(([], [])) == [] assert strongly_connected_components(([1, 2, 3], [])) == [[1], [2], [3]] V = [1, 2, 3] E = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1)] assert strongly_connected_components((V, E)) == [[1, 2, 3]] V = [1, 2, 3, 4] E = [(1, 2), (2, 3), (3, 2), (3, 4)] assert strongly_connected_components((V, E)) == [[4], [2, 3], [1]] V = [1, 2, 3, 4] E = [(1, 2), (2, 1), (3, 4), (4, 3)] assert strongly_connected_components((V, E)) == [[1, 2], [3, 4]] def test_connected_components(): assert connected_components(([], [])) == [] assert connected_components(([1, 2, 3], [])) == [[1], [2], [3]] V = [1, 2, 3] E = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1)] assert connected_components((V, E)) == [[1, 2, 3]] V = [1, 2, 3, 4] E = [(1, 2), (2, 3), (3, 2), (3, 4)] assert connected_components((V, E)) == [[1, 2, 3, 4]] V = [1, 2, 3, 4] E = [(1, 2), (3, 4)] assert connected_components((V, E)) == [[1, 2], [3, 4]] def test_rotate(): A = [0, 1, 2, 3, 4] assert rotate_left(A, 2) == [2, 3, 4, 0, 1] assert rotate_right(A, 1) == [4, 0, 1, 2, 3] A = [] B = rotate_right(A, 1) assert B == [] B.append(1) assert A == [] B = rotate_left(A, 1) assert B == [] B.append(1) assert A == [] def test_multiset_partitions(): A = [0, 1, 2, 3, 4] assert list(multiset_partitions(A, 5)) == [[[0], [1], [2], [3], [4]]] assert len(list(multiset_partitions(A, 4))) == 10 assert len(list(multiset_partitions(A, 3))) == 25 assert list(multiset_partitions([1, 1, 1, 2, 2], 2)) == [ [[1, 1, 1, 2], [2]], [[1, 1, 1], [2, 2]], [[1, 1, 2, 2], [1]], [[1, 1, 2], [1, 2]], [[1, 1], [1, 2, 2]]] assert list(multiset_partitions([1, 1, 2, 2], 2)) == [ [[1, 1, 2], [2]], [[1, 1], [2, 2]], [[1, 2, 2], [1]], [[1, 2], [1, 2]]] assert list(multiset_partitions([1, 2, 3, 4], 2)) == [ [[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]], [[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]], [[1], [2, 3, 4]]] assert list(multiset_partitions([1, 2, 2], 2)) == [ [[1, 2], [2]], [[1], [2, 2]]] assert list(multiset_partitions(3)) == [ [[0, 1, 2]], [[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]], [[0], [1], [2]]] assert list(multiset_partitions(3, 2)) == [ [[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]]] assert list(multiset_partitions([1] * 3, 2)) == [[[1], [1, 1]]] assert list(multiset_partitions([1] * 3)) == [ [[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]] a = [3, 2, 1] assert list(multiset_partitions(a)) == \ list(multiset_partitions(sorted(a))) assert list(multiset_partitions(a, 5)) == [] assert list(multiset_partitions(a, 1)) == [[[1, 2, 3]]] assert list(multiset_partitions(a + [4], 5)) == [] assert list(multiset_partitions(a + [4], 1)) == [[[1, 2, 3, 4]]] assert list(multiset_partitions(2, 5)) == [] assert list(multiset_partitions(2, 1)) == [[[0, 1]]] assert list(multiset_partitions('a')) == [[['a']]] assert list(multiset_partitions('a', 2)) == [] assert list(multiset_partitions('ab')) == [[['a', 'b']], [['a'], ['b']]] assert list(multiset_partitions('ab', 1)) == [[['a', 'b']]] assert list(multiset_partitions('aaa', 1)) == [['aaa']] assert list(multiset_partitions([1, 1], 1)) == [[[1, 1]]] ans = [('mpsyy',), ('mpsy', 'y'), ('mps', 'yy'), ('mps', 'y', 'y'), ('mpyy', 's'), ('mpy', 'sy'), ('mpy', 's', 'y'), ('mp', 'syy'), ('mp', 'sy', 'y'), ('mp', 's', 'yy'), ('mp', 's', 'y', 'y'), ('msyy', 'p'), ('msy', 'py'), ('msy', 'p', 'y'), ('ms', 'pyy'), ('ms', 'py', 'y'), ('ms', 'p', 'yy'), ('ms', 'p', 'y', 'y'), ('myy', 'ps'), ('myy', 'p', 's'), ('my', 'psy'), ('my', 'ps', 'y'), ('my', 'py', 's'), ('my', 'p', 'sy'), ('my', 'p', 's', 'y'), ('m', 'psyy'), ('m', 'psy', 'y'), ('m', 'ps', 'yy'), ('m', 'ps', 'y', 'y'), ('m', 'pyy', 's'), ('m', 'py', 'sy'), ('m', 'py', 's', 'y'), ('m', 'p', 'syy'), ('m', 'p', 'sy', 'y'), ('m', 'p', 's', 'yy'), ('m', 'p', 's', 'y', 'y')] assert list(tuple("".join(part) for part in p) for p in multiset_partitions('sympy')) == ans factorings = [[24], [8, 3], [12, 2], [4, 6], [4, 2, 3], [6, 2, 2], [2, 2, 2, 3]] assert list(factoring_visitor(p, [2,3]) for p in multiset_partitions_taocp([3, 1])) == factorings def test_multiset_combinations(): ans = ['iii', 'iim', 'iip', 'iis', 'imp', 'ims', 'ipp', 'ips', 'iss', 'mpp', 'mps', 'mss', 'pps', 'pss', 'sss'] assert [''.join(i) for i in list(multiset_combinations('mississippi', 3))] == ans M = multiset('mississippi') assert [''.join(i) for i in list(multiset_combinations(M, 3))] == ans assert [''.join(i) for i in multiset_combinations(M, 30)] == [] assert list(multiset_combinations([[1], [2, 3]], 2)) == [[[1], [2, 3]]] assert len(list(multiset_combinations('a', 3))) == 0 assert len(list(multiset_combinations('a', 0))) == 1 assert list(multiset_combinations('abc', 1)) == [['a'], ['b'], ['c']] def test_multiset_permutations(): ans = ['abby', 'abyb', 'aybb', 'baby', 'bayb', 'bbay', 'bbya', 'byab', 'byba', 'yabb', 'ybab', 'ybba'] assert [''.join(i) for i in multiset_permutations('baby')] == ans assert [''.join(i) for i in multiset_permutations(multiset('baby'))] == ans assert list(multiset_permutations([0, 0, 0], 2)) == [[0, 0]] assert list(multiset_permutations([0, 2, 1], 2)) == [ [0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]] assert len(list(multiset_permutations('a', 0))) == 1 assert len(list(multiset_permutations('a', 3))) == 0 for nul in ([], {}, ''): assert list(multiset_permutations(nul)) == [[]] assert list(multiset_permutations(nul, 0)) == [[]] # impossible requests give no result assert list(multiset_permutations(nul, 1)) == [] assert list(multiset_permutations(nul, -1)) == [] def test(): for i in range(1, 7): print(i) for p in multiset_permutations([0, 0, 1, 0, 1], i): print(p) assert capture(lambda: test()) == dedent('''\ 1 [0] [1] 2 [0, 0] [0, 1] [1, 0] [1, 1] 3 [0, 0, 0] [0, 0, 1] [0, 1, 0] [0, 1, 1] [1, 0, 0] [1, 0, 1] [1, 1, 0] 4 [0, 0, 0, 1] [0, 0, 1, 0] [0, 0, 1, 1] [0, 1, 0, 0] [0, 1, 0, 1] [0, 1, 1, 0] [1, 0, 0, 0] [1, 0, 0, 1] [1, 0, 1, 0] [1, 1, 0, 0] 5 [0, 0, 0, 1, 1] [0, 0, 1, 0, 1] [0, 0, 1, 1, 0] [0, 1, 0, 0, 1] [0, 1, 0, 1, 0] [0, 1, 1, 0, 0] [1, 0, 0, 0, 1] [1, 0, 0, 1, 0] [1, 0, 1, 0, 0] [1, 1, 0, 0, 0] 6\n''') def test_partitions(): ans = [[{}], [(0, {})]] for i in range(2): assert list(partitions(0, size=i)) == ans[i] assert list(partitions(1, 0, size=i)) == ans[i] assert list(partitions(6, 2, 2, size=i)) == ans[i] assert list(partitions(6, 2, None, size=i)) != ans[i] assert list(partitions(6, None, 2, size=i)) != ans[i] assert list(partitions(6, 2, 0, size=i)) == ans[i] assert [p for p in partitions(6, k=2)] == [ {2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}] assert [p for p in partitions(6, k=3)] == [ {3: 2}, {1: 1, 2: 1, 3: 1}, {1: 3, 3: 1}, {2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}] assert [p for p in partitions(8, k=4, m=3)] == [ {4: 2}, {1: 1, 3: 1, 4: 1}, {2: 2, 4: 1}, {2: 1, 3: 2}] == [ i for i in partitions(8, k=4, m=3) if all(k <= 4 for k in i) and sum(i.values()) <=3] assert [p for p in partitions(S(3), m=2)] == [ {3: 1}, {1: 1, 2: 1}] assert [i for i in partitions(4, k=3)] == [ {1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}] == [ i for i in partitions(4) if all(k <= 3 for k in i)] # Consistency check on output of _partitions and RGS_unrank. # This provides a sanity test on both routines. Also verifies that # the total number of partitions is the same in each case. # (from pkrathmann2) for n in range(2, 6): i = 0 for m, q in _set_partitions(n): assert q == RGS_unrank(i, n) i += 1 assert i == RGS_enum(n) def test_binary_partitions(): assert [i[:] for i in binary_partitions(10)] == [[8, 2], [8, 1, 1], [4, 4, 2], [4, 4, 1, 1], [4, 2, 2, 2], [4, 2, 2, 1, 1], [4, 2, 1, 1, 1, 1], [4, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [2, 2, 2, 2, 1, 1], [2, 2, 2, 1, 1, 1, 1], [2, 2, 1, 1, 1, 1, 1, 1], [2, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] assert len([j[:] for j in binary_partitions(16)]) == 36 def test_bell_perm(): assert [len(set(generate_bell(i))) for i in range(1, 7)] == [ factorial(i) for i in range(1, 7)] assert list(generate_bell(3)) == [ (0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)] # generate_bell and trotterjohnson are advertised to return the same # permutations; this is not technically necessary so this test could # be removed for n in range(1, 5): p = Permutation(range(n)) b = generate_bell(n) for bi in b: assert bi == tuple(p.array_form) p = p.next_trotterjohnson() raises(ValueError, lambda: list(generate_bell(0))) # XXX is this consistent with other permutation algorithms? def test_involutions(): lengths = [1, 2, 4, 10, 26, 76] for n, N in enumerate(lengths): i = list(generate_involutions(n + 1)) assert len(i) == N assert len({Permutation(j)**2 for j in i}) == 1 def test_derangements(): assert len(list(generate_derangements(list(range(6))))) == 265 assert ''.join(''.join(i) for i in generate_derangements('abcde')) == ( 'badecbaecdbcaedbcdeabceadbdaecbdeacbdecabeacdbedacbedcacabedcadebcaebd' 'cdaebcdbeacdeabcdebaceabdcebadcedabcedbadabecdaebcdaecbdcaebdcbeadceab' 'dcebadeabcdeacbdebacdebcaeabcdeadbceadcbecabdecbadecdabecdbaedabcedacb' 'edbacedbca') assert list(generate_derangements([0, 1, 2, 3])) == [ [1, 0, 3, 2], [1, 2, 3, 0], [1, 3, 0, 2], [2, 0, 3, 1], [2, 3, 0, 1], [2, 3, 1, 0], [3, 0, 1, 2], [3, 2, 0, 1], [3, 2, 1, 0]] assert list(generate_derangements([0, 1, 2, 2])) == [ [2, 2, 0, 1], [2, 2, 1, 0]] assert list(generate_derangements('ba')) == [list('ab')] def test_necklaces(): def count(n, k, f): return len(list(necklaces(n, k, f))) m = [] for i in range(1, 8): m.append(( i, count(i, 2, 0), count(i, 2, 1), count(i, 3, 1))) assert Matrix(m) == Matrix([ [1, 2, 2, 3], [2, 3, 3, 6], [3, 4, 4, 10], [4, 6, 6, 21], [5, 8, 8, 39], [6, 14, 13, 92], [7, 20, 18, 198]]) def test_bracelets(): bc = [i for i in bracelets(2, 4)] assert Matrix(bc) == Matrix([ [0, 0], [0, 1], [0, 2], [0, 3], [1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3, 3] ]) bc = [i for i in bracelets(4, 2)] assert Matrix(bc) == Matrix([ [0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 0, 1], [0, 1, 1, 1], [1, 1, 1, 1] ]) def test_generate_oriented_forest(): assert list(generate_oriented_forest(5)) == [[0, 1, 2, 3, 4], [0, 1, 2, 3, 3], [0, 1, 2, 3, 2], [0, 1, 2, 3, 1], [0, 1, 2, 3, 0], [0, 1, 2, 2, 2], [0, 1, 2, 2, 1], [0, 1, 2, 2, 0], [0, 1, 2, 1, 2], [0, 1, 2, 1, 1], [0, 1, 2, 1, 0], [0, 1, 2, 0, 1], [0, 1, 2, 0, 0], [0, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1], [0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0]] assert len(list(generate_oriented_forest(10))) == 1842 def test_unflatten(): r = list(range(10)) assert unflatten(r) == list(zip(r[::2], r[1::2])) assert unflatten(r, 5) == [tuple(r[:5]), tuple(r[5:])] raises(ValueError, lambda: unflatten(list(range(10)), 3)) raises(ValueError, lambda: unflatten(list(range(10)), -2)) def test_common_prefix_suffix(): assert common_prefix([], [1]) == [] assert common_prefix(list(range(3))) == [0, 1, 2] assert common_prefix(list(range(3)), list(range(4))) == [0, 1, 2] assert common_prefix([1, 2, 3], [1, 2, 5]) == [1, 2] assert common_prefix([1, 2, 3], [1, 3, 5]) == [1] assert common_suffix([], [1]) == [] assert common_suffix(list(range(3))) == [0, 1, 2] assert common_suffix(list(range(3)), list(range(3))) == [0, 1, 2] assert common_suffix(list(range(3)), list(range(4))) == [] assert common_suffix([1, 2, 3], [9, 2, 3]) == [2, 3] assert common_suffix([1, 2, 3], [9, 7, 3]) == [3] def test_minlex(): assert minlex([1, 2, 0]) == (0, 1, 2) assert minlex((1, 2, 0)) == (0, 1, 2) assert minlex((1, 0, 2)) == (0, 2, 1) assert minlex((1, 0, 2), directed=False) == (0, 1, 2) assert minlex('aba') == 'aab' assert minlex(('bb', 'aaa', 'c', 'a'), key=len) == ('c', 'a', 'bb', 'aaa') def test_ordered(): assert list(ordered((x, y), hash, default=False)) in [[x, y], [y, x]] assert list(ordered((x, y), hash, default=False)) == \ list(ordered((y, x), hash, default=False)) assert list(ordered((x, y))) == [x, y] seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]], (lambda x: len(x), lambda x: sum(x))] assert list(ordered(seq, keys, default=False, warn=False)) == \ [[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]] raises(ValueError, lambda: list(ordered(seq, keys, default=False, warn=True))) def test_runs(): assert runs([]) == [] assert runs([1]) == [[1]] assert runs([1, 1]) == [[1], [1]] assert runs([1, 1, 2]) == [[1], [1, 2]] assert runs([1, 2, 1]) == [[1, 2], [1]] assert runs([2, 1, 1]) == [[2], [1], [1]] from operator import lt assert runs([2, 1, 1], lt) == [[2, 1], [1]] def test_reshape(): seq = list(range(1, 9)) assert reshape(seq, [4]) == \ [[1, 2, 3, 4], [5, 6, 7, 8]] assert reshape(seq, (4,)) == \ [(1, 2, 3, 4), (5, 6, 7, 8)] assert reshape(seq, (2, 2)) == \ [(1, 2, 3, 4), (5, 6, 7, 8)] assert reshape(seq, (2, [2])) == \ [(1, 2, [3, 4]), (5, 6, [7, 8])] assert reshape(seq, ((2,), [2])) == \ [((1, 2), [3, 4]), ((5, 6), [7, 8])] assert reshape(seq, (1, [2], 1)) == \ [(1, [2, 3], 4), (5, [6, 7], 8)] assert reshape(tuple(seq), ([[1], 1, (2,)],)) == \ (([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],)) assert reshape(tuple(seq), ([1], 1, (2,))) == \ (([1], 2, (3, 4)), ([5], 6, (7, 8))) assert reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)]) == \ [[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]] raises(ValueError, lambda: reshape([0, 1], [-1])) raises(ValueError, lambda: reshape([0, 1], [3])) def test_uniq(): assert list(uniq(p for p in partitions(4))) == \ [{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}] assert list(uniq(x % 2 for x in range(5))) == [0, 1] assert list(uniq('a')) == ['a'] assert list(uniq('ababc')) == list('abc') assert list(uniq([[1], [2, 1], [1]])) == [[1], [2, 1]] assert list(uniq(permutations(i for i in [[1], 2, 2]))) == \ [([1], 2, 2), (2, [1], 2), (2, 2, [1])] assert list(uniq([2, 3, 2, 4, [2], [1], [2], [3], [1]])) == \ [2, 3, 4, [2], [1], [3]] f = [1] raises(RuntimeError, lambda: [f.remove(i) for i in uniq(f)]) f = [[1]] raises(RuntimeError, lambda: [f.remove(i) for i in uniq(f)]) def test_kbins(): assert len(list(kbins('1123', 2, ordered=1))) == 24 assert len(list(kbins('1123', 2, ordered=11))) == 36 assert len(list(kbins('1123', 2, ordered=10))) == 10 assert len(list(kbins('1123', 2, ordered=0))) == 5 assert len(list(kbins('1123', 2, ordered=None))) == 3 def test1(): for orderedval in [None, 0, 1, 10, 11]: print('ordered =', orderedval) for p in kbins([0, 0, 1], 2, ordered=orderedval): print(' ', p) assert capture(lambda : test1()) == dedent('''\ ordered = None [[0], [0, 1]] [[0, 0], [1]] ordered = 0 [[0, 0], [1]] [[0, 1], [0]] ordered = 1 [[0], [0, 1]] [[0], [1, 0]] [[1], [0, 0]] ordered = 10 [[0, 0], [1]] [[1], [0, 0]] [[0, 1], [0]] [[0], [0, 1]] ordered = 11 [[0], [0, 1]] [[0, 0], [1]] [[0], [1, 0]] [[0, 1], [0]] [[1], [0, 0]] [[1, 0], [0]]\n''') def test2(): for orderedval in [None, 0, 1, 10, 11]: print('ordered =', orderedval) for p in kbins(list(range(3)), 2, ordered=orderedval): print(' ', p) assert capture(lambda : test2()) == dedent('''\ ordered = None [[0], [1, 2]] [[0, 1], [2]] ordered = 0 [[0, 1], [2]] [[0, 2], [1]] [[0], [1, 2]] ordered = 1 [[0], [1, 2]] [[0], [2, 1]] [[1], [0, 2]] [[1], [2, 0]] [[2], [0, 1]] [[2], [1, 0]] ordered = 10 [[0, 1], [2]] [[2], [0, 1]] [[0, 2], [1]] [[1], [0, 2]] [[0], [1, 2]] [[1, 2], [0]] ordered = 11 [[0], [1, 2]] [[0, 1], [2]] [[0], [2, 1]] [[0, 2], [1]] [[1], [0, 2]] [[1, 0], [2]] [[1], [2, 0]] [[1, 2], [0]] [[2], [0, 1]] [[2, 0], [1]] [[2], [1, 0]] [[2, 1], [0]]\n''') def test_has_dups(): assert has_dups(set()) is False assert has_dups(list(range(3))) is False assert has_dups([1, 2, 1]) is True def test__partition(): assert _partition('abcde', [1, 0, 1, 2, 0]) == [ ['b', 'e'], ['a', 'c'], ['d']] assert _partition('abcde', [1, 0, 1, 2, 0], 3) == [ ['b', 'e'], ['a', 'c'], ['d']] output = (3, [1, 0, 1, 2, 0]) assert _partition('abcde', *output) == [['b', 'e'], ['a', 'c'], ['d']] def test_ordered_partitions(): from sympy.functions.combinatorial.numbers import nT f = ordered_partitions assert list(f(0, 1)) == [[]] assert list(f(1, 0)) == [[]] for i in range(1, 7): for j in [None] + list(range(1, i)): assert ( sum(1 for p in f(i, j, 1)) == sum(1 for p in f(i, j, 0)) == nT(i, j)) def test_rotations(): assert list(rotations('ab')) == [['a', 'b'], ['b', 'a']] assert list(rotations(range(3))) == [[0, 1, 2], [1, 2, 0], [2, 0, 1]] assert list(rotations(range(3), dir=-1)) == [[0, 1, 2], [2, 0, 1], [1, 2, 0]] def test_ibin(): assert ibin(3) == [1, 1] assert ibin(3, 3) == [0, 1, 1] assert ibin(3, str=True) == '11' assert ibin(3, 3, str=True) == '011' assert list(ibin(2, 'all')) == [(0, 0), (0, 1), (1, 0), (1, 1)] assert list(ibin(2, '', str=True)) == ['00', '01', '10', '11'] raises(ValueError, lambda: ibin(-.5)) raises(ValueError, lambda: ibin(2, 1))
de6f8cb5b7b55f1c99ccb8449babe34d0fd01fa322e07e1c5c907893d39e6ec4
import itertools from sympy.core import S from sympy.core.containers import Tuple from sympy.core.function import _coeff_isneg from sympy.core.mul import Mul from sympy.core.numbers import Number, Rational from sympy.core.power import Pow from sympy.core.symbol import Symbol from sympy.core.sympify import SympifyError from sympy.printing.conventions import requires_partial from sympy.printing.precedence import PRECEDENCE, precedence, precedence_traditional from sympy.printing.printer import Printer, print_function from sympy.printing.str import sstr from sympy.utilities import default_sort_key from sympy.utilities.iterables import has_variety from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.printing.pretty.pretty_symbology import hobj, vobj, xobj, \ xsym, pretty_symbol, pretty_atom, pretty_use_unicode, greek_unicode, U, \ pretty_try_use_unicode, annotated # rename for usage from outside pprint_use_unicode = pretty_use_unicode pprint_try_use_unicode = pretty_try_use_unicode class PrettyPrinter(Printer): """Printer, which converts an expression into 2D ASCII-art figure.""" printmethod = "_pretty" _default_settings = { "order": None, "full_prec": "auto", "use_unicode": None, "wrap_line": True, "num_columns": None, "use_unicode_sqrt_char": True, "root_notation": True, "mat_symbol_style": "plain", "imaginary_unit": "i", "perm_cyclic": True } def __init__(self, settings=None): Printer.__init__(self, settings) if not isinstance(self._settings['imaginary_unit'], str): raise TypeError("'imaginary_unit' must a string, not {}".format(self._settings['imaginary_unit'])) elif self._settings['imaginary_unit'] not in ["i", "j"]: raise ValueError("'imaginary_unit' must be either 'i' or 'j', not '{}'".format(self._settings['imaginary_unit'])) def emptyPrinter(self, expr): return prettyForm(str(expr)) @property def _use_unicode(self): if self._settings['use_unicode']: return True else: return pretty_use_unicode() def doprint(self, expr): return self._print(expr).render(**self._settings) # empty op so _print(stringPict) returns the same def _print_stringPict(self, e): return e def _print_basestring(self, e): return prettyForm(e) def _print_atan2(self, e): pform = prettyForm(*self._print_seq(e.args).parens()) pform = prettyForm(*pform.left('atan2')) return pform def _print_Symbol(self, e, bold_name=False): symb = pretty_symbol(e.name, bold_name) return prettyForm(symb) _print_RandomSymbol = _print_Symbol def _print_MatrixSymbol(self, e): return self._print_Symbol(e, self._settings['mat_symbol_style'] == "bold") def _print_Float(self, e): # we will use StrPrinter's Float printer, but we need to handle the # full_prec ourselves, according to the self._print_level full_prec = self._settings["full_prec"] if full_prec == "auto": full_prec = self._print_level == 1 return prettyForm(sstr(e, full_prec=full_prec)) def _print_Cross(self, e): vec1 = e._expr1 vec2 = e._expr2 pform = self._print(vec2) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('MULTIPLICATION SIGN')))) pform = prettyForm(*pform.left(')')) pform = prettyForm(*pform.left(self._print(vec1))) pform = prettyForm(*pform.left('(')) return pform def _print_Curl(self, e): vec = e._expr pform = self._print(vec) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('MULTIPLICATION SIGN')))) pform = prettyForm(*pform.left(self._print(U('NABLA')))) return pform def _print_Divergence(self, e): vec = e._expr pform = self._print(vec) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('DOT OPERATOR')))) pform = prettyForm(*pform.left(self._print(U('NABLA')))) return pform def _print_Dot(self, e): vec1 = e._expr1 vec2 = e._expr2 pform = self._print(vec2) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('DOT OPERATOR')))) pform = prettyForm(*pform.left(')')) pform = prettyForm(*pform.left(self._print(vec1))) pform = prettyForm(*pform.left('(')) return pform def _print_Gradient(self, e): func = e._expr pform = self._print(func) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('NABLA')))) return pform def _print_Laplacian(self, e): func = e._expr pform = self._print(func) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('INCREMENT')))) return pform def _print_Atom(self, e): try: # print atoms like Exp1 or Pi return prettyForm(pretty_atom(e.__class__.__name__, printer=self)) except KeyError: return self.emptyPrinter(e) # Infinity inherits from Number, so we have to override _print_XXX order _print_Infinity = _print_Atom _print_NegativeInfinity = _print_Atom _print_EmptySet = _print_Atom _print_Naturals = _print_Atom _print_Naturals0 = _print_Atom _print_Integers = _print_Atom _print_Rationals = _print_Atom _print_Complexes = _print_Atom _print_EmptySequence = _print_Atom def _print_Reals(self, e): if self._use_unicode: return self._print_Atom(e) else: inf_list = ['-oo', 'oo'] return self._print_seq(inf_list, '(', ')') def _print_subfactorial(self, e): x = e.args[0] pform = self._print(x) # Add parentheses if needed if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol): pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('!')) return pform def _print_factorial(self, e): x = e.args[0] pform = self._print(x) # Add parentheses if needed if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol): pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.right('!')) return pform def _print_factorial2(self, e): x = e.args[0] pform = self._print(x) # Add parentheses if needed if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol): pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.right('!!')) return pform def _print_binomial(self, e): n, k = e.args n_pform = self._print(n) k_pform = self._print(k) bar = ' '*max(n_pform.width(), k_pform.width()) pform = prettyForm(*k_pform.above(bar)) pform = prettyForm(*pform.above(n_pform)) pform = prettyForm(*pform.parens('(', ')')) pform.baseline = (pform.baseline + 1)//2 return pform def _print_Relational(self, e): op = prettyForm(' ' + xsym(e.rel_op) + ' ') l = self._print(e.lhs) r = self._print(e.rhs) pform = prettyForm(*stringPict.next(l, op, r)) return pform def _print_Not(self, e): from sympy import Equivalent, Implies if self._use_unicode: arg = e.args[0] pform = self._print(arg) if isinstance(arg, Equivalent): return self._print_Equivalent(arg, altchar="\N{LEFT RIGHT DOUBLE ARROW WITH STROKE}") if isinstance(arg, Implies): return self._print_Implies(arg, altchar="\N{RIGHTWARDS ARROW WITH STROKE}") if arg.is_Boolean and not arg.is_Not: pform = prettyForm(*pform.parens()) return prettyForm(*pform.left("\N{NOT SIGN}")) else: return self._print_Function(e) def __print_Boolean(self, e, char, sort=True): args = e.args if sort: args = sorted(e.args, key=default_sort_key) arg = args[0] pform = self._print(arg) if arg.is_Boolean and not arg.is_Not: pform = prettyForm(*pform.parens()) for arg in args[1:]: pform_arg = self._print(arg) if arg.is_Boolean and not arg.is_Not: pform_arg = prettyForm(*pform_arg.parens()) pform = prettyForm(*pform.right(' %s ' % char)) pform = prettyForm(*pform.right(pform_arg)) return pform def _print_And(self, e): if self._use_unicode: return self.__print_Boolean(e, "\N{LOGICAL AND}") else: return self._print_Function(e, sort=True) def _print_Or(self, e): if self._use_unicode: return self.__print_Boolean(e, "\N{LOGICAL OR}") else: return self._print_Function(e, sort=True) def _print_Xor(self, e): if self._use_unicode: return self.__print_Boolean(e, "\N{XOR}") else: return self._print_Function(e, sort=True) def _print_Nand(self, e): if self._use_unicode: return self.__print_Boolean(e, "\N{NAND}") else: return self._print_Function(e, sort=True) def _print_Nor(self, e): if self._use_unicode: return self.__print_Boolean(e, "\N{NOR}") else: return self._print_Function(e, sort=True) def _print_Implies(self, e, altchar=None): if self._use_unicode: return self.__print_Boolean(e, altchar or "\N{RIGHTWARDS ARROW}", sort=False) else: return self._print_Function(e) def _print_Equivalent(self, e, altchar=None): if self._use_unicode: return self.__print_Boolean(e, altchar or "\N{LEFT RIGHT DOUBLE ARROW}") else: return self._print_Function(e, sort=True) def _print_conjugate(self, e): pform = self._print(e.args[0]) return prettyForm( *pform.above( hobj('_', pform.width())) ) def _print_Abs(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens('|', '|')) return pform _print_Determinant = _print_Abs def _print_floor(self, e): if self._use_unicode: pform = self._print(e.args[0]) pform = prettyForm(*pform.parens('lfloor', 'rfloor')) return pform else: return self._print_Function(e) def _print_ceiling(self, e): if self._use_unicode: pform = self._print(e.args[0]) pform = prettyForm(*pform.parens('lceil', 'rceil')) return pform else: return self._print_Function(e) def _print_Derivative(self, deriv): if requires_partial(deriv.expr) and self._use_unicode: deriv_symbol = U('PARTIAL DIFFERENTIAL') else: deriv_symbol = r'd' x = None count_total_deriv = 0 for sym, num in reversed(deriv.variable_count): s = self._print(sym) ds = prettyForm(*s.left(deriv_symbol)) count_total_deriv += num if (not num.is_Integer) or (num > 1): ds = ds**prettyForm(str(num)) if x is None: x = ds else: x = prettyForm(*x.right(' ')) x = prettyForm(*x.right(ds)) f = prettyForm( binding=prettyForm.FUNC, *self._print(deriv.expr).parens()) pform = prettyForm(deriv_symbol) if (count_total_deriv > 1) != False: pform = pform**prettyForm(str(count_total_deriv)) pform = prettyForm(*pform.below(stringPict.LINE, x)) pform.baseline = pform.baseline + 1 pform = prettyForm(*stringPict.next(pform, f)) pform.binding = prettyForm.MUL return pform def _print_Cycle(self, dc): from sympy.combinatorics.permutations import Permutation, Cycle # for Empty Cycle if dc == Cycle(): cyc = stringPict('') return prettyForm(*cyc.parens()) dc_list = Permutation(dc.list()).cyclic_form # for Identity Cycle if dc_list == []: cyc = self._print(dc.size - 1) return prettyForm(*cyc.parens()) cyc = stringPict('') for i in dc_list: l = self._print(str(tuple(i)).replace(',', '')) cyc = prettyForm(*cyc.right(l)) return cyc def _print_Permutation(self, expr): from sympy.combinatorics.permutations import Permutation, Cycle perm_cyclic = Permutation.print_cyclic if perm_cyclic is not None: SymPyDeprecationWarning( feature="Permutation.print_cyclic = {}".format(perm_cyclic), useinstead="init_printing(perm_cyclic={})" .format(perm_cyclic), issue=15201, deprecated_since_version="1.6").warn() else: perm_cyclic = self._settings.get("perm_cyclic", True) if perm_cyclic: return self._print_Cycle(Cycle(expr)) lower = expr.array_form upper = list(range(len(lower))) result = stringPict('') first = True for u, l in zip(upper, lower): s1 = self._print(u) s2 = self._print(l) col = prettyForm(*s1.below(s2)) if first: first = False else: col = prettyForm(*col.left(" ")) result = prettyForm(*result.right(col)) return prettyForm(*result.parens()) def _print_Integral(self, integral): f = integral.function # Add parentheses if arg involves addition of terms and # create a pretty form for the argument prettyF = self._print(f) # XXX generalize parens if f.is_Add: prettyF = prettyForm(*prettyF.parens()) # dx dy dz ... arg = prettyF for x in integral.limits: prettyArg = self._print(x[0]) # XXX qparens (parens if needs-parens) if prettyArg.width() > 1: prettyArg = prettyForm(*prettyArg.parens()) arg = prettyForm(*arg.right(' d', prettyArg)) # \int \int \int ... firstterm = True s = None for lim in integral.limits: # Create bar based on the height of the argument h = arg.height() H = h + 2 # XXX hack! ascii_mode = not self._use_unicode if ascii_mode: H += 2 vint = vobj('int', H) # Construct the pretty form with the integral sign and the argument pform = prettyForm(vint) pform.baseline = arg.baseline + ( H - h)//2 # covering the whole argument if len(lim) > 1: # Create pretty forms for endpoints, if definite integral. # Do not print empty endpoints. if len(lim) == 2: prettyA = prettyForm("") prettyB = self._print(lim[1]) if len(lim) == 3: prettyA = self._print(lim[1]) prettyB = self._print(lim[2]) if ascii_mode: # XXX hack # Add spacing so that endpoint can more easily be # identified with the correct integral sign spc = max(1, 3 - prettyB.width()) prettyB = prettyForm(*prettyB.left(' ' * spc)) spc = max(1, 4 - prettyA.width()) prettyA = prettyForm(*prettyA.right(' ' * spc)) pform = prettyForm(*pform.above(prettyB)) pform = prettyForm(*pform.below(prettyA)) if not ascii_mode: # XXX hack pform = prettyForm(*pform.right(' ')) if firstterm: s = pform # first term firstterm = False else: s = prettyForm(*s.left(pform)) pform = prettyForm(*arg.left(s)) pform.binding = prettyForm.MUL return pform def _print_Product(self, expr): func = expr.term pretty_func = self._print(func) horizontal_chr = xobj('_', 1) corner_chr = xobj('_', 1) vertical_chr = xobj('|', 1) if self._use_unicode: # use unicode corners horizontal_chr = xobj('-', 1) corner_chr = '\N{BOX DRAWINGS LIGHT DOWN AND HORIZONTAL}' func_height = pretty_func.height() first = True max_upper = 0 sign_height = 0 for lim in expr.limits: pretty_lower, pretty_upper = self.__print_SumProduct_Limits(lim) width = (func_height + 2) * 5 // 3 - 2 sign_lines = [horizontal_chr + corner_chr + (horizontal_chr * (width-2)) + corner_chr + horizontal_chr] for _ in range(func_height + 1): sign_lines.append(' ' + vertical_chr + (' ' * (width-2)) + vertical_chr + ' ') pretty_sign = stringPict('') pretty_sign = prettyForm(*pretty_sign.stack(*sign_lines)) max_upper = max(max_upper, pretty_upper.height()) if first: sign_height = pretty_sign.height() pretty_sign = prettyForm(*pretty_sign.above(pretty_upper)) pretty_sign = prettyForm(*pretty_sign.below(pretty_lower)) if first: pretty_func.baseline = 0 first = False height = pretty_sign.height() padding = stringPict('') padding = prettyForm(*padding.stack(*[' ']*(height - 1))) pretty_sign = prettyForm(*pretty_sign.right(padding)) pretty_func = prettyForm(*pretty_sign.right(pretty_func)) pretty_func.baseline = max_upper + sign_height//2 pretty_func.binding = prettyForm.MUL return pretty_func def __print_SumProduct_Limits(self, lim): def print_start(lhs, rhs): op = prettyForm(' ' + xsym("==") + ' ') l = self._print(lhs) r = self._print(rhs) pform = prettyForm(*stringPict.next(l, op, r)) return pform prettyUpper = self._print(lim[2]) prettyLower = print_start(lim[0], lim[1]) return prettyLower, prettyUpper def _print_Sum(self, expr): ascii_mode = not self._use_unicode def asum(hrequired, lower, upper, use_ascii): def adjust(s, wid=None, how='<^>'): if not wid or len(s) > wid: return s need = wid - len(s) if how == '<^>' or how == "<" or how not in list('<^>'): return s + ' '*need half = need//2 lead = ' '*half if how == ">": return " "*need + s return lead + s + ' '*(need - len(lead)) h = max(hrequired, 2) d = h//2 w = d + 1 more = hrequired % 2 lines = [] if use_ascii: lines.append("_"*(w) + ' ') lines.append(r"\%s`" % (' '*(w - 1))) for i in range(1, d): lines.append('%s\\%s' % (' '*i, ' '*(w - i))) if more: lines.append('%s)%s' % (' '*(d), ' '*(w - d))) for i in reversed(range(1, d)): lines.append('%s/%s' % (' '*i, ' '*(w - i))) lines.append("/" + "_"*(w - 1) + ',') return d, h + more, lines, more else: w = w + more d = d + more vsum = vobj('sum', 4) lines.append("_"*(w)) for i in range(0, d): lines.append('%s%s%s' % (' '*i, vsum[2], ' '*(w - i - 1))) for i in reversed(range(0, d)): lines.append('%s%s%s' % (' '*i, vsum[4], ' '*(w - i - 1))) lines.append(vsum[8]*(w)) return d, h + 2*more, lines, more f = expr.function prettyF = self._print(f) if f.is_Add: # add parens prettyF = prettyForm(*prettyF.parens()) H = prettyF.height() + 2 # \sum \sum \sum ... first = True max_upper = 0 sign_height = 0 for lim in expr.limits: prettyLower, prettyUpper = self.__print_SumProduct_Limits(lim) max_upper = max(max_upper, prettyUpper.height()) # Create sum sign based on the height of the argument d, h, slines, adjustment = asum( H, prettyLower.width(), prettyUpper.width(), ascii_mode) prettySign = stringPict('') prettySign = prettyForm(*prettySign.stack(*slines)) if first: sign_height = prettySign.height() prettySign = prettyForm(*prettySign.above(prettyUpper)) prettySign = prettyForm(*prettySign.below(prettyLower)) if first: # change F baseline so it centers on the sign prettyF.baseline -= d - (prettyF.height()//2 - prettyF.baseline) first = False # put padding to the right pad = stringPict('') pad = prettyForm(*pad.stack(*[' ']*h)) prettySign = prettyForm(*prettySign.right(pad)) # put the present prettyF to the right prettyF = prettyForm(*prettySign.right(prettyF)) # adjust baseline of ascii mode sigma with an odd height so that it is # exactly through the center ascii_adjustment = ascii_mode if not adjustment else 0 prettyF.baseline = max_upper + sign_height//2 + ascii_adjustment prettyF.binding = prettyForm.MUL return prettyF def _print_Limit(self, l): e, z, z0, dir = l.args E = self._print(e) if precedence(e) <= PRECEDENCE["Mul"]: E = prettyForm(*E.parens('(', ')')) Lim = prettyForm('lim') LimArg = self._print(z) if self._use_unicode: LimArg = prettyForm(*LimArg.right('\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{RIGHTWARDS ARROW}')) else: LimArg = prettyForm(*LimArg.right('->')) LimArg = prettyForm(*LimArg.right(self._print(z0))) if str(dir) == '+-' or z0 in (S.Infinity, S.NegativeInfinity): dir = "" else: if self._use_unicode: dir = '\N{SUPERSCRIPT PLUS SIGN}' if str(dir) == "+" else '\N{SUPERSCRIPT MINUS}' LimArg = prettyForm(*LimArg.right(self._print(dir))) Lim = prettyForm(*Lim.below(LimArg)) Lim = prettyForm(*Lim.right(E), binding=prettyForm.MUL) return Lim def _print_matrix_contents(self, e): """ This method factors out what is essentially grid printing. """ M = e # matrix Ms = {} # i,j -> pretty(M[i,j]) for i in range(M.rows): for j in range(M.cols): Ms[i, j] = self._print(M[i, j]) # h- and v- spacers hsep = 2 vsep = 1 # max width for columns maxw = [-1] * M.cols for j in range(M.cols): maxw[j] = max([Ms[i, j].width() for i in range(M.rows)] or [0]) # drawing result D = None for i in range(M.rows): D_row = None for j in range(M.cols): s = Ms[i, j] # reshape s to maxw # XXX this should be generalized, and go to stringPict.reshape ? assert s.width() <= maxw[j] # hcenter it, +0.5 to the right 2 # ( it's better to align formula starts for say 0 and r ) # XXX this is not good in all cases -- maybe introduce vbaseline? wdelta = maxw[j] - s.width() wleft = wdelta // 2 wright = wdelta - wleft s = prettyForm(*s.right(' '*wright)) s = prettyForm(*s.left(' '*wleft)) # we don't need vcenter cells -- this is automatically done in # a pretty way because when their baselines are taking into # account in .right() if D_row is None: D_row = s # first box in a row continue D_row = prettyForm(*D_row.right(' '*hsep)) # h-spacer D_row = prettyForm(*D_row.right(s)) if D is None: D = D_row # first row in a picture continue # v-spacer for _ in range(vsep): D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) if D is None: D = prettyForm('') # Empty Matrix return D def _print_MatrixBase(self, e): D = self._print_matrix_contents(e) D.baseline = D.height()//2 D = prettyForm(*D.parens('[', ']')) return D def _print_TensorProduct(self, expr): # This should somehow share the code with _print_WedgeProduct: circled_times = "\u2297" return self._print_seq(expr.args, None, None, circled_times, parenthesize=lambda x: precedence_traditional(x) <= PRECEDENCE["Mul"]) def _print_WedgeProduct(self, expr): # This should somehow share the code with _print_TensorProduct: wedge_symbol = "\u2227" return self._print_seq(expr.args, None, None, wedge_symbol, parenthesize=lambda x: precedence_traditional(x) <= PRECEDENCE["Mul"]) def _print_Trace(self, e): D = self._print(e.arg) D = prettyForm(*D.parens('(',')')) D.baseline = D.height()//2 D = prettyForm(*D.left('\n'*(0) + 'tr')) return D def _print_MatrixElement(self, expr): from sympy.matrices import MatrixSymbol from sympy import Symbol if (isinstance(expr.parent, MatrixSymbol) and expr.i.is_number and expr.j.is_number): return self._print( Symbol(expr.parent.name + '_%d%d' % (expr.i, expr.j))) else: prettyFunc = self._print(expr.parent) prettyFunc = prettyForm(*prettyFunc.parens()) prettyIndices = self._print_seq((expr.i, expr.j), delimiter=', ' ).parens(left='[', right=']')[0] pform = prettyForm(binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyIndices)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyIndices return pform def _print_MatrixSlice(self, m): # XXX works only for applied functions from sympy.matrices import MatrixSymbol prettyFunc = self._print(m.parent) if not isinstance(m.parent, MatrixSymbol): prettyFunc = prettyForm(*prettyFunc.parens()) def ppslice(x, dim): x = list(x) if x[2] == 1: del x[2] if x[0] == 0: x[0] = '' if x[1] == dim: x[1] = '' return prettyForm(*self._print_seq(x, delimiter=':')) prettyArgs = self._print_seq((ppslice(m.rowslice, m.parent.rows), ppslice(m.colslice, m.parent.cols)), delimiter=', ').parens(left='[', right=']')[0] pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_Transpose(self, expr): pform = self._print(expr.arg) from sympy.matrices import MatrixSymbol if not isinstance(expr.arg, MatrixSymbol): pform = prettyForm(*pform.parens()) pform = pform**(prettyForm('T')) return pform def _print_Adjoint(self, expr): pform = self._print(expr.arg) if self._use_unicode: dag = prettyForm('\N{DAGGER}') else: dag = prettyForm('+') from sympy.matrices import MatrixSymbol if not isinstance(expr.arg, MatrixSymbol): pform = prettyForm(*pform.parens()) pform = pform**dag return pform def _print_BlockMatrix(self, B): if B.blocks.shape == (1, 1): return self._print(B.blocks[0, 0]) return self._print(B.blocks) def _print_MatAdd(self, expr): s = None for item in expr.args: pform = self._print(item) if s is None: s = pform # First element else: coeff = item.as_coeff_mmul()[0] if _coeff_isneg(S(coeff)): s = prettyForm(*stringPict.next(s, ' ')) pform = self._print(item) else: s = prettyForm(*stringPict.next(s, ' + ')) s = prettyForm(*stringPict.next(s, pform)) return s def _print_MatMul(self, expr): args = list(expr.args) from sympy import Add, MatAdd, HadamardProduct, KroneckerProduct for i, a in enumerate(args): if (isinstance(a, (Add, MatAdd, HadamardProduct, KroneckerProduct)) and len(expr.args) > 1): args[i] = prettyForm(*self._print(a).parens()) else: args[i] = self._print(a) return prettyForm.__mul__(*args) def _print_Identity(self, expr): if self._use_unicode: return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL I}') else: return prettyForm('I') def _print_ZeroMatrix(self, expr): if self._use_unicode: return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO}') else: return prettyForm('0') def _print_OneMatrix(self, expr): if self._use_unicode: return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ONE}') else: return prettyForm('1') def _print_DotProduct(self, expr): args = list(expr.args) for i, a in enumerate(args): args[i] = self._print(a) return prettyForm.__mul__(*args) def _print_MatPow(self, expr): pform = self._print(expr.base) from sympy.matrices import MatrixSymbol if not isinstance(expr.base, MatrixSymbol): pform = prettyForm(*pform.parens()) pform = pform**(self._print(expr.exp)) return pform def _print_HadamardProduct(self, expr): from sympy import MatAdd, MatMul, HadamardProduct if self._use_unicode: delim = pretty_atom('Ring') else: delim = '.*' return self._print_seq(expr.args, None, None, delim, parenthesize=lambda x: isinstance(x, (MatAdd, MatMul, HadamardProduct))) def _print_HadamardPower(self, expr): # from sympy import MatAdd, MatMul if self._use_unicode: circ = pretty_atom('Ring') else: circ = self._print('.') pretty_base = self._print(expr.base) pretty_exp = self._print(expr.exp) if precedence(expr.exp) < PRECEDENCE["Mul"]: pretty_exp = prettyForm(*pretty_exp.parens()) pretty_circ_exp = prettyForm( binding=prettyForm.LINE, *stringPict.next(circ, pretty_exp) ) return pretty_base**pretty_circ_exp def _print_KroneckerProduct(self, expr): from sympy import MatAdd, MatMul if self._use_unicode: delim = ' \N{N-ARY CIRCLED TIMES OPERATOR} ' else: delim = ' x ' return self._print_seq(expr.args, None, None, delim, parenthesize=lambda x: isinstance(x, (MatAdd, MatMul))) def _print_FunctionMatrix(self, X): D = self._print(X.lamda.expr) D = prettyForm(*D.parens('[', ']')) return D def _print_TransferFunction(self, expr): if not expr.num == 1: num, den = expr.num, expr.den res = Mul(num, Pow(den, -1, evaluate=False), evaluate=False) return self._print_Mul(res) else: return self._print(1)/self._print(expr.den) def _print_Series(self, expr): args = list(expr.args) for i, a in enumerate(expr.args): args[i] = prettyForm(*self._print(a).parens()) return prettyForm.__mul__(*args) def _print_MIMOSeries(self, expr): from sympy.physics.control.lti import MIMOParallel args = list(expr.args) pretty_args = [] for i, a in enumerate(reversed(args)): if (isinstance(a, MIMOParallel) and len(expr.args) > 1): expression = self._print(a) expression.baseline = expression.height()//2 pretty_args.append(prettyForm(*expression.parens())) else: expression = self._print(a) expression.baseline = expression.height()//2 pretty_args.append(expression) return prettyForm.__mul__(*pretty_args) def _print_Parallel(self, expr): s = None for item in expr.args: pform = self._print(item) if s is None: s = pform # First element else: s = prettyForm(*stringPict.next(s)) s.baseline = s.height()//2 s = prettyForm(*stringPict.next(s, ' + ')) s = prettyForm(*stringPict.next(s, pform)) return s def _print_MIMOParallel(self, expr): from sympy.physics.control.lti import TransferFunctionMatrix s = None for item in expr.args: pform = self._print(item) if s is None: s = pform # First element else: s = prettyForm(*stringPict.next(s)) s.baseline = s.height()//2 s = prettyForm(*stringPict.next(s, ' + ')) if isinstance(item, TransferFunctionMatrix): s.baseline = s.height() - 1 s = prettyForm(*stringPict.next(s, pform)) # s.baseline = s.height()//2 return s def _print_Feedback(self, expr): from sympy.physics.control import TransferFunction, Series num, tf = expr.sys1, TransferFunction(1, 1, expr.var) num_arg_list = list(num.args) if isinstance(num, Series) else [num] den_arg_list = list(expr.sys2.args) if \ isinstance(expr.sys2, Series) else [expr.sys2] if isinstance(num, Series) and isinstance(expr.sys2, Series): den = Series(*num_arg_list, *den_arg_list) elif isinstance(num, Series) and isinstance(expr.sys2, TransferFunction): if expr.sys2 == tf: den = Series(*num_arg_list) else: den = Series(*num_arg_list, expr.sys2) elif isinstance(num, TransferFunction) and isinstance(expr.sys2, Series): if num == tf: den = Series(*den_arg_list) else: den = Series(num, *den_arg_list) else: if num == tf: den = Series(*den_arg_list) elif expr.sys2 == tf: den = Series(*num_arg_list) else: den = Series(*num_arg_list, *den_arg_list) denom = prettyForm(*stringPict.next(self._print(tf))) denom.baseline = denom.height()//2 denom = prettyForm(*stringPict.next(denom, ' + ')) if expr.sign == -1 \ else prettyForm(*stringPict.next(denom, ' - ')) denom = prettyForm(*stringPict.next(denom, self._print(den))) return self._print(num)/denom def _print_MIMOFeedback(self, expr): from sympy.physics.control import MIMOSeries, TransferFunctionMatrix inv_mat = self._print(MIMOSeries(expr.sys2, expr.sys1)) plant = self._print(expr.sys1) _feedback = prettyForm(*stringPict.next(inv_mat)) _feedback = prettyForm(*stringPict.right("I + ", _feedback)) if expr.sign == -1 \ else prettyForm(*stringPict.right("I - ", _feedback)) _feedback = prettyForm(*stringPict.parens(_feedback)) _feedback.baseline = 0 _feedback = prettyForm(*stringPict.right(_feedback, '-1 ')) _feedback.baseline = _feedback.height()//2 _feedback = prettyForm.__mul__(_feedback, prettyForm(" ")) if isinstance(expr.sys1, TransferFunctionMatrix): _feedback.baseline = _feedback.height() - 1 _feedback = prettyForm(*stringPict.next(_feedback, plant)) return _feedback def _print_TransferFunctionMatrix(self, expr): mat = self._print(expr._expr_mat) mat.baseline = mat.height() - 1 subscript = greek_unicode['tau'] if self._use_unicode else r'{t}' mat = prettyForm(*mat.right(subscript)) return mat def _print_BasisDependent(self, expr): from sympy.vector import Vector if not self._use_unicode: raise NotImplementedError("ASCII pretty printing of BasisDependent is not implemented") if expr == expr.zero: return prettyForm(expr.zero._pretty_form) o1 = [] vectstrs = [] if isinstance(expr, Vector): items = expr.separate().items() else: items = [(0, expr)] for system, vect in items: inneritems = list(vect.components.items()) inneritems.sort(key = lambda x: x[0].__str__()) for k, v in inneritems: #if the coef of the basis vector is 1 #we skip the 1 if v == 1: o1.append("" + k._pretty_form) #Same for -1 elif v == -1: o1.append("(-1) " + k._pretty_form) #For a general expr else: #We always wrap the measure numbers in #parentheses arg_str = self._print( v).parens()[0] o1.append(arg_str + ' ' + k._pretty_form) vectstrs.append(k._pretty_form) #outstr = u("").join(o1) if o1[0].startswith(" + "): o1[0] = o1[0][3:] elif o1[0].startswith(" "): o1[0] = o1[0][1:] #Fixing the newlines lengths = [] strs = [''] flag = [] for i, partstr in enumerate(o1): flag.append(0) # XXX: What is this hack? if '\n' in partstr: tempstr = partstr tempstr = tempstr.replace(vectstrs[i], '') if '\N{right parenthesis extension}' in tempstr: # If scalar is a fraction for paren in range(len(tempstr)): flag[i] = 1 if tempstr[paren] == '\N{right parenthesis extension}': tempstr = tempstr[:paren] + '\N{right parenthesis extension}'\ + ' ' + vectstrs[i] + tempstr[paren + 1:] break elif '\N{RIGHT PARENTHESIS LOWER HOOK}' in tempstr: flag[i] = 1 tempstr = tempstr.replace('\N{RIGHT PARENTHESIS LOWER HOOK}', '\N{RIGHT PARENTHESIS LOWER HOOK}' + ' ' + vectstrs[i]) else: tempstr = tempstr.replace('\N{RIGHT PARENTHESIS UPPER HOOK}', '\N{RIGHT PARENTHESIS UPPER HOOK}' + ' ' + vectstrs[i]) o1[i] = tempstr o1 = [x.split('\n') for x in o1] n_newlines = max([len(x) for x in o1]) # Width of part in its pretty form if 1 in flag: # If there was a fractional scalar for i, parts in enumerate(o1): if len(parts) == 1: # If part has no newline parts.insert(0, ' ' * (len(parts[0]))) flag[i] = 1 for i, parts in enumerate(o1): lengths.append(len(parts[flag[i]])) for j in range(n_newlines): if j+1 <= len(parts): if j >= len(strs): strs.append(' ' * (sum(lengths[:-1]) + 3*(len(lengths)-1))) if j == flag[i]: strs[flag[i]] += parts[flag[i]] + ' + ' else: strs[j] += parts[j] + ' '*(lengths[-1] - len(parts[j])+ 3) else: if j >= len(strs): strs.append(' ' * (sum(lengths[:-1]) + 3*(len(lengths)-1))) strs[j] += ' '*(lengths[-1]+3) return prettyForm('\n'.join([s[:-3] for s in strs])) def _print_NDimArray(self, expr): from sympy import ImmutableMatrix if expr.rank() == 0: return self._print(expr[()]) level_str = [[]] + [[] for i in range(expr.rank())] shape_ranges = [list(range(i)) for i in expr.shape] # leave eventual matrix elements unflattened mat = lambda x: ImmutableMatrix(x, evaluate=False) for outer_i in itertools.product(*shape_ranges): level_str[-1].append(expr[outer_i]) even = True for back_outer_i in range(expr.rank()-1, -1, -1): if len(level_str[back_outer_i+1]) < expr.shape[back_outer_i]: break if even: level_str[back_outer_i].append(level_str[back_outer_i+1]) else: level_str[back_outer_i].append(mat( level_str[back_outer_i+1])) if len(level_str[back_outer_i + 1]) == 1: level_str[back_outer_i][-1] = mat( [[level_str[back_outer_i][-1]]]) even = not even level_str[back_outer_i+1] = [] out_expr = level_str[0][0] if expr.rank() % 2 == 1: out_expr = mat([out_expr]) return self._print(out_expr) def _printer_tensor_indices(self, name, indices, index_map={}): center = stringPict(name) top = stringPict(" "*center.width()) bot = stringPict(" "*center.width()) last_valence = None prev_map = None for i, index in enumerate(indices): indpic = self._print(index.args[0]) if ((index in index_map) or prev_map) and last_valence == index.is_up: if index.is_up: top = prettyForm(*stringPict.next(top, ",")) else: bot = prettyForm(*stringPict.next(bot, ",")) if index in index_map: indpic = prettyForm(*stringPict.next(indpic, "=")) indpic = prettyForm(*stringPict.next(indpic, self._print(index_map[index]))) prev_map = True else: prev_map = False if index.is_up: top = stringPict(*top.right(indpic)) center = stringPict(*center.right(" "*indpic.width())) bot = stringPict(*bot.right(" "*indpic.width())) else: bot = stringPict(*bot.right(indpic)) center = stringPict(*center.right(" "*indpic.width())) top = stringPict(*top.right(" "*indpic.width())) last_valence = index.is_up pict = prettyForm(*center.above(top)) pict = prettyForm(*pict.below(bot)) return pict def _print_Tensor(self, expr): name = expr.args[0].name indices = expr.get_indices() return self._printer_tensor_indices(name, indices) def _print_TensorElement(self, expr): name = expr.expr.args[0].name indices = expr.expr.get_indices() index_map = expr.index_map return self._printer_tensor_indices(name, indices, index_map) def _print_TensMul(self, expr): sign, args = expr._get_args_for_traditional_printer() args = [ prettyForm(*self._print(i).parens()) if precedence_traditional(i) < PRECEDENCE["Mul"] else self._print(i) for i in args ] pform = prettyForm.__mul__(*args) if sign: return prettyForm(*pform.left(sign)) else: return pform def _print_TensAdd(self, expr): args = [ prettyForm(*self._print(i).parens()) if precedence_traditional(i) < PRECEDENCE["Mul"] else self._print(i) for i in expr.args ] return prettyForm.__add__(*args) def _print_TensorIndex(self, expr): sym = expr.args[0] if not expr.is_up: sym = -sym return self._print(sym) def _print_PartialDerivative(self, deriv): if self._use_unicode: deriv_symbol = U('PARTIAL DIFFERENTIAL') else: deriv_symbol = r'd' x = None for variable in reversed(deriv.variables): s = self._print(variable) ds = prettyForm(*s.left(deriv_symbol)) if x is None: x = ds else: x = prettyForm(*x.right(' ')) x = prettyForm(*x.right(ds)) f = prettyForm( binding=prettyForm.FUNC, *self._print(deriv.expr).parens()) pform = prettyForm(deriv_symbol) if len(deriv.variables) > 1: pform = pform**self._print(len(deriv.variables)) pform = prettyForm(*pform.below(stringPict.LINE, x)) pform.baseline = pform.baseline + 1 pform = prettyForm(*stringPict.next(pform, f)) pform.binding = prettyForm.MUL return pform def _print_Piecewise(self, pexpr): P = {} for n, ec in enumerate(pexpr.args): P[n, 0] = self._print(ec.expr) if ec.cond == True: P[n, 1] = prettyForm('otherwise') else: P[n, 1] = prettyForm( *prettyForm('for ').right(self._print(ec.cond))) hsep = 2 vsep = 1 len_args = len(pexpr.args) # max widths maxw = [max([P[i, j].width() for i in range(len_args)]) for j in range(2)] # FIXME: Refactor this code and matrix into some tabular environment. # drawing result D = None for i in range(len_args): D_row = None for j in range(2): p = P[i, j] assert p.width() <= maxw[j] wdelta = maxw[j] - p.width() wleft = wdelta // 2 wright = wdelta - wleft p = prettyForm(*p.right(' '*wright)) p = prettyForm(*p.left(' '*wleft)) if D_row is None: D_row = p continue D_row = prettyForm(*D_row.right(' '*hsep)) # h-spacer D_row = prettyForm(*D_row.right(p)) if D is None: D = D_row # first row in a picture continue # v-spacer for _ in range(vsep): D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) D = prettyForm(*D.parens('{', '')) D.baseline = D.height()//2 D.binding = prettyForm.OPEN return D def _print_ITE(self, ite): from sympy.functions.elementary.piecewise import Piecewise return self._print(ite.rewrite(Piecewise)) def _hprint_vec(self, v): D = None for a in v: p = a if D is None: D = p else: D = prettyForm(*D.right(', ')) D = prettyForm(*D.right(p)) if D is None: D = stringPict(' ') return D def _hprint_vseparator(self, p1, p2, left=None, right=None, delimiter='', ifascii_nougly=False): if ifascii_nougly and not self._use_unicode: return self._print_seq((p1, '|', p2), left=left, right=right, delimiter=delimiter, ifascii_nougly=True) tmp = self._print_seq((p1, p2,), left=left, right=right, delimiter=delimiter) sep = stringPict(vobj('|', tmp.height()), baseline=tmp.baseline) return self._print_seq((p1, sep, p2), left=left, right=right, delimiter=delimiter) def _print_hyper(self, e): # FIXME refactor Matrix, Piecewise, and this into a tabular environment ap = [self._print(a) for a in e.ap] bq = [self._print(b) for b in e.bq] P = self._print(e.argument) P.baseline = P.height()//2 # Drawing result - first create the ap, bq vectors D = None for v in [ap, bq]: D_row = self._hprint_vec(v) if D is None: D = D_row # first row in a picture else: D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) # make sure that the argument `z' is centred vertically D.baseline = D.height()//2 # insert horizontal separator P = prettyForm(*P.left(' ')) D = prettyForm(*D.right(' ')) # insert separating `|` D = self._hprint_vseparator(D, P) # add parens D = prettyForm(*D.parens('(', ')')) # create the F symbol above = D.height()//2 - 1 below = D.height() - above - 1 sz, t, b, add, img = annotated('F') F = prettyForm('\n' * (above - t) + img + '\n' * (below - b), baseline=above + sz) add = (sz + 1)//2 F = prettyForm(*F.left(self._print(len(e.ap)))) F = prettyForm(*F.right(self._print(len(e.bq)))) F.baseline = above + add D = prettyForm(*F.right(' ', D)) return D def _print_meijerg(self, e): # FIXME refactor Matrix, Piecewise, and this into a tabular environment v = {} v[(0, 0)] = [self._print(a) for a in e.an] v[(0, 1)] = [self._print(a) for a in e.aother] v[(1, 0)] = [self._print(b) for b in e.bm] v[(1, 1)] = [self._print(b) for b in e.bother] P = self._print(e.argument) P.baseline = P.height()//2 vp = {} for idx in v: vp[idx] = self._hprint_vec(v[idx]) for i in range(2): maxw = max(vp[(0, i)].width(), vp[(1, i)].width()) for j in range(2): s = vp[(j, i)] left = (maxw - s.width()) // 2 right = maxw - left - s.width() s = prettyForm(*s.left(' ' * left)) s = prettyForm(*s.right(' ' * right)) vp[(j, i)] = s D1 = prettyForm(*vp[(0, 0)].right(' ', vp[(0, 1)])) D1 = prettyForm(*D1.below(' ')) D2 = prettyForm(*vp[(1, 0)].right(' ', vp[(1, 1)])) D = prettyForm(*D1.below(D2)) # make sure that the argument `z' is centred vertically D.baseline = D.height()//2 # insert horizontal separator P = prettyForm(*P.left(' ')) D = prettyForm(*D.right(' ')) # insert separating `|` D = self._hprint_vseparator(D, P) # add parens D = prettyForm(*D.parens('(', ')')) # create the G symbol above = D.height()//2 - 1 below = D.height() - above - 1 sz, t, b, add, img = annotated('G') F = prettyForm('\n' * (above - t) + img + '\n' * (below - b), baseline=above + sz) pp = self._print(len(e.ap)) pq = self._print(len(e.bq)) pm = self._print(len(e.bm)) pn = self._print(len(e.an)) def adjust(p1, p2): diff = p1.width() - p2.width() if diff == 0: return p1, p2 elif diff > 0: return p1, prettyForm(*p2.left(' '*diff)) else: return prettyForm(*p1.left(' '*-diff)), p2 pp, pm = adjust(pp, pm) pq, pn = adjust(pq, pn) pu = prettyForm(*pm.right(', ', pn)) pl = prettyForm(*pp.right(', ', pq)) ht = F.baseline - above - 2 if ht > 0: pu = prettyForm(*pu.below('\n'*ht)) p = prettyForm(*pu.below(pl)) F.baseline = above F = prettyForm(*F.right(p)) F.baseline = above + add D = prettyForm(*F.right(' ', D)) return D def _print_ExpBase(self, e): # TODO should exp_polar be printed differently? # what about exp_polar(0), exp_polar(1)? base = prettyForm(pretty_atom('Exp1', 'e')) return base ** self._print(e.args[0]) def _print_Exp1(self, e): return prettyForm(pretty_atom('Exp1', 'e')) def _print_Function(self, e, sort=False, func_name=None): # optional argument func_name for supplying custom names # XXX works only for applied functions return self._helper_print_function(e.func, e.args, sort=sort, func_name=func_name) def _print_mathieuc(self, e): return self._print_Function(e, func_name='C') def _print_mathieus(self, e): return self._print_Function(e, func_name='S') def _print_mathieucprime(self, e): return self._print_Function(e, func_name="C'") def _print_mathieusprime(self, e): return self._print_Function(e, func_name="S'") def _helper_print_function(self, func, args, sort=False, func_name=None, delimiter=', ', elementwise=False): if sort: args = sorted(args, key=default_sort_key) if not func_name and hasattr(func, "__name__"): func_name = func.__name__ if func_name: prettyFunc = self._print(Symbol(func_name)) else: prettyFunc = prettyForm(*self._print(func).parens()) if elementwise: if self._use_unicode: circ = pretty_atom('Modifier Letter Low Ring') else: circ = '.' circ = self._print(circ) prettyFunc = prettyForm( binding=prettyForm.LINE, *stringPict.next(prettyFunc, circ) ) prettyArgs = prettyForm(*self._print_seq(args, delimiter=delimiter).parens()) pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_ElementwiseApplyFunction(self, e): func = e.function arg = e.expr args = [arg] return self._helper_print_function(func, args, delimiter="", elementwise=True) @property def _special_function_classes(self): from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.functions.special.gamma_functions import gamma, lowergamma from sympy.functions.special.zeta_functions import lerchphi from sympy.functions.special.beta_functions import beta from sympy.functions.special.delta_functions import DiracDelta from sympy.functions.special.error_functions import Chi return {KroneckerDelta: [greek_unicode['delta'], 'delta'], gamma: [greek_unicode['Gamma'], 'Gamma'], lerchphi: [greek_unicode['Phi'], 'lerchphi'], lowergamma: [greek_unicode['gamma'], 'gamma'], beta: [greek_unicode['Beta'], 'B'], DiracDelta: [greek_unicode['delta'], 'delta'], Chi: ['Chi', 'Chi']} def _print_FunctionClass(self, expr): for cls in self._special_function_classes: if issubclass(expr, cls) and expr.__name__ == cls.__name__: if self._use_unicode: return prettyForm(self._special_function_classes[cls][0]) else: return prettyForm(self._special_function_classes[cls][1]) func_name = expr.__name__ return prettyForm(pretty_symbol(func_name)) def _print_GeometryEntity(self, expr): # GeometryEntity is based on Tuple but should not print like a Tuple return self.emptyPrinter(expr) def _print_lerchphi(self, e): func_name = greek_unicode['Phi'] if self._use_unicode else 'lerchphi' return self._print_Function(e, func_name=func_name) def _print_dirichlet_eta(self, e): func_name = greek_unicode['eta'] if self._use_unicode else 'dirichlet_eta' return self._print_Function(e, func_name=func_name) def _print_Heaviside(self, e): func_name = greek_unicode['theta'] if self._use_unicode else 'Heaviside' if e.args[1]==1/2: pform = prettyForm(*self._print(e.args[0]).parens()) pform = prettyForm(*pform.left(func_name)) return pform else: return self._print_Function(e, func_name=func_name) def _print_fresnels(self, e): return self._print_Function(e, func_name="S") def _print_fresnelc(self, e): return self._print_Function(e, func_name="C") def _print_airyai(self, e): return self._print_Function(e, func_name="Ai") def _print_airybi(self, e): return self._print_Function(e, func_name="Bi") def _print_airyaiprime(self, e): return self._print_Function(e, func_name="Ai'") def _print_airybiprime(self, e): return self._print_Function(e, func_name="Bi'") def _print_LambertW(self, e): return self._print_Function(e, func_name="W") def _print_Lambda(self, e): expr = e.expr sig = e.signature if self._use_unicode: arrow = " \N{RIGHTWARDS ARROW FROM BAR} " else: arrow = " -> " if len(sig) == 1 and sig[0].is_symbol: sig = sig[0] var_form = self._print(sig) return prettyForm(*stringPict.next(var_form, arrow, self._print(expr)), binding=8) def _print_Order(self, expr): pform = self._print(expr.expr) if (expr.point and any(p != S.Zero for p in expr.point)) or \ len(expr.variables) > 1: pform = prettyForm(*pform.right("; ")) if len(expr.variables) > 1: pform = prettyForm(*pform.right(self._print(expr.variables))) elif len(expr.variables): pform = prettyForm(*pform.right(self._print(expr.variables[0]))) if self._use_unicode: pform = prettyForm(*pform.right(" \N{RIGHTWARDS ARROW} ")) else: pform = prettyForm(*pform.right(" -> ")) if len(expr.point) > 1: pform = prettyForm(*pform.right(self._print(expr.point))) else: pform = prettyForm(*pform.right(self._print(expr.point[0]))) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left("O")) return pform def _print_SingularityFunction(self, e): if self._use_unicode: shift = self._print(e.args[0]-e.args[1]) n = self._print(e.args[2]) base = prettyForm("<") base = prettyForm(*base.right(shift)) base = prettyForm(*base.right(">")) pform = base**n return pform else: n = self._print(e.args[2]) shift = self._print(e.args[0]-e.args[1]) base = self._print_seq(shift, "<", ">", ' ') return base**n def _print_beta(self, e): func_name = greek_unicode['Beta'] if self._use_unicode else 'B' return self._print_Function(e, func_name=func_name) def _print_betainc(self, e): func_name = "B'" return self._print_Function(e, func_name=func_name) def _print_betainc_regularized(self, e): func_name = 'I' return self._print_Function(e, func_name=func_name) def _print_gamma(self, e): func_name = greek_unicode['Gamma'] if self._use_unicode else 'Gamma' return self._print_Function(e, func_name=func_name) def _print_uppergamma(self, e): func_name = greek_unicode['Gamma'] if self._use_unicode else 'Gamma' return self._print_Function(e, func_name=func_name) def _print_lowergamma(self, e): func_name = greek_unicode['gamma'] if self._use_unicode else 'lowergamma' return self._print_Function(e, func_name=func_name) def _print_DiracDelta(self, e): if self._use_unicode: if len(e.args) == 2: a = prettyForm(greek_unicode['delta']) b = self._print(e.args[1]) b = prettyForm(*b.parens()) c = self._print(e.args[0]) c = prettyForm(*c.parens()) pform = a**b pform = prettyForm(*pform.right(' ')) pform = prettyForm(*pform.right(c)) return pform pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(greek_unicode['delta'])) return pform else: return self._print_Function(e) def _print_expint(self, e): from sympy import Function if e.args[0].is_Integer and self._use_unicode: return self._print_Function(Function('E_%s' % e.args[0])(e.args[1])) return self._print_Function(e) def _print_Chi(self, e): # This needs a special case since otherwise it comes out as greek # letter chi... prettyFunc = prettyForm("Chi") prettyArgs = prettyForm(*self._print_seq(e.args).parens()) pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_elliptic_e(self, e): pforma0 = self._print(e.args[0]) if len(e.args) == 1: pform = pforma0 else: pforma1 = self._print(e.args[1]) pform = self._hprint_vseparator(pforma0, pforma1) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('E')) return pform def _print_elliptic_k(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('K')) return pform def _print_elliptic_f(self, e): pforma0 = self._print(e.args[0]) pforma1 = self._print(e.args[1]) pform = self._hprint_vseparator(pforma0, pforma1) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('F')) return pform def _print_elliptic_pi(self, e): name = greek_unicode['Pi'] if self._use_unicode else 'Pi' pforma0 = self._print(e.args[0]) pforma1 = self._print(e.args[1]) if len(e.args) == 2: pform = self._hprint_vseparator(pforma0, pforma1) else: pforma2 = self._print(e.args[2]) pforma = self._hprint_vseparator(pforma1, pforma2, ifascii_nougly=False) pforma = prettyForm(*pforma.left('; ')) pform = prettyForm(*pforma.left(pforma0)) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(name)) return pform def _print_GoldenRatio(self, expr): if self._use_unicode: return prettyForm(pretty_symbol('phi')) return self._print(Symbol("GoldenRatio")) def _print_EulerGamma(self, expr): if self._use_unicode: return prettyForm(pretty_symbol('gamma')) return self._print(Symbol("EulerGamma")) def _print_Mod(self, expr): pform = self._print(expr.args[0]) if pform.binding > prettyForm.MUL: pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.right(' mod ')) pform = prettyForm(*pform.right(self._print(expr.args[1]))) pform.binding = prettyForm.OPEN return pform def _print_Add(self, expr, order=None): terms = self._as_ordered_terms(expr, order=order) pforms, indices = [], [] def pretty_negative(pform, index): """Prepend a minus sign to a pretty form. """ #TODO: Move this code to prettyForm if index == 0: if pform.height() > 1: pform_neg = '- ' else: pform_neg = '-' else: pform_neg = ' - ' if (pform.binding > prettyForm.NEG or pform.binding == prettyForm.ADD): p = stringPict(*pform.parens()) else: p = pform p = stringPict.next(pform_neg, p) # Lower the binding to NEG, even if it was higher. Otherwise, it # will print as a + ( - (b)), instead of a - (b). return prettyForm(binding=prettyForm.NEG, *p) for i, term in enumerate(terms): if term.is_Mul and _coeff_isneg(term): coeff, other = term.as_coeff_mul(rational=False) if coeff == -1: negterm = Mul(*other, evaluate=False) else: negterm = Mul(-coeff, *other, evaluate=False) pform = self._print(negterm) pforms.append(pretty_negative(pform, i)) elif term.is_Rational and term.q > 1: pforms.append(None) indices.append(i) elif term.is_Number and term < 0: pform = self._print(-term) pforms.append(pretty_negative(pform, i)) elif term.is_Relational: pforms.append(prettyForm(*self._print(term).parens())) else: pforms.append(self._print(term)) if indices: large = True for pform in pforms: if pform is not None and pform.height() > 1: break else: large = False for i in indices: term, negative = terms[i], False if term < 0: term, negative = -term, True if large: pform = prettyForm(str(term.p))/prettyForm(str(term.q)) else: pform = self._print(term) if negative: pform = pretty_negative(pform, i) pforms[i] = pform return prettyForm.__add__(*pforms) def _print_Mul(self, product): from sympy.physics.units import Quantity # Check for unevaluated Mul. In this case we need to make sure the # identities are visible, multiple Rational factors are not combined # etc so we display in a straight-forward form that fully preserves all # args and their order. args = product.args if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]): strargs = list(map(self._print, args)) # XXX: This is a hack to work around the fact that # prettyForm.__mul__ absorbs a leading -1 in the args. Probably it # would be better to fix this in prettyForm.__mul__ instead. negone = strargs[0] == '-1' if negone: strargs[0] = prettyForm('1', 0, 0) obj = prettyForm.__mul__(*strargs) if negone: obj = prettyForm('-' + obj.s, obj.baseline, obj.binding) return obj a = [] # items in the numerator b = [] # items that are in the denominator (if any) if self.order not in ('old', 'none'): args = product.as_ordered_factors() else: args = list(product.args) # If quantities are present append them at the back args = sorted(args, key=lambda x: isinstance(x, Quantity) or (isinstance(x, Pow) and isinstance(x.base, Quantity))) # Gather terms for numerator/denominator for item in args: if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative: if item.exp != -1: b.append(Pow(item.base, -item.exp, evaluate=False)) else: b.append(Pow(item.base, -item.exp)) elif item.is_Rational and item is not S.Infinity: if item.p != 1: a.append( Rational(item.p) ) if item.q != 1: b.append( Rational(item.q) ) else: a.append(item) from sympy import Integral, Piecewise, Product, Sum # Convert to pretty forms. Add parens to Add instances if there # is more than one term in the numer/denom for i in range(0, len(a)): if (a[i].is_Add and len(a) > 1) or (i != len(a) - 1 and isinstance(a[i], (Integral, Piecewise, Product, Sum))): a[i] = prettyForm(*self._print(a[i]).parens()) elif a[i].is_Relational: a[i] = prettyForm(*self._print(a[i]).parens()) else: a[i] = self._print(a[i]) for i in range(0, len(b)): if (b[i].is_Add and len(b) > 1) or (i != len(b) - 1 and isinstance(b[i], (Integral, Piecewise, Product, Sum))): b[i] = prettyForm(*self._print(b[i]).parens()) else: b[i] = self._print(b[i]) # Construct a pretty form if len(b) == 0: return prettyForm.__mul__(*a) else: if len(a) == 0: a.append( self._print(S.One) ) return prettyForm.__mul__(*a)/prettyForm.__mul__(*b) # A helper function for _print_Pow to print x**(1/n) def _print_nth_root(self, base, root): bpretty = self._print(base) # In very simple cases, use a single-char root sign if (self._settings['use_unicode_sqrt_char'] and self._use_unicode and root == 2 and bpretty.height() == 1 and (bpretty.width() == 1 or (base.is_Integer and base.is_nonnegative))): return prettyForm(*bpretty.left('\N{SQUARE ROOT}')) # Construct root sign, start with the \/ shape _zZ = xobj('/', 1) rootsign = xobj('\\', 1) + _zZ # Constructing the number to put on root rpretty = self._print(root) # roots look bad if they are not a single line if rpretty.height() != 1: return self._print(base)**self._print(1/root) # If power is half, no number should appear on top of root sign exp = '' if root == 2 else str(rpretty).ljust(2) if len(exp) > 2: rootsign = ' '*(len(exp) - 2) + rootsign # Stack the exponent rootsign = stringPict(exp + '\n' + rootsign) rootsign.baseline = 0 # Diagonal: length is one less than height of base linelength = bpretty.height() - 1 diagonal = stringPict('\n'.join( ' '*(linelength - i - 1) + _zZ + ' '*i for i in range(linelength) )) # Put baseline just below lowest line: next to exp diagonal.baseline = linelength - 1 # Make the root symbol rootsign = prettyForm(*rootsign.right(diagonal)) # Det the baseline to match contents to fix the height # but if the height of bpretty is one, the rootsign must be one higher rootsign.baseline = max(1, bpretty.baseline) #build result s = prettyForm(hobj('_', 2 + bpretty.width())) s = prettyForm(*bpretty.above(s)) s = prettyForm(*s.left(rootsign)) return s def _print_Pow(self, power): from sympy.simplify.simplify import fraction b, e = power.as_base_exp() if power.is_commutative: if e is S.NegativeOne: return prettyForm("1")/self._print(b) n, d = fraction(e) if n is S.One and d.is_Atom and not e.is_Integer and (e.is_Rational or d.is_Symbol) \ and self._settings['root_notation']: return self._print_nth_root(b, d) if e.is_Rational and e < 0: return prettyForm("1")/self._print(Pow(b, -e, evaluate=False)) if b.is_Relational: return prettyForm(*self._print(b).parens()).__pow__(self._print(e)) return self._print(b)**self._print(e) def _print_UnevaluatedExpr(self, expr): return self._print(expr.args[0]) def __print_numer_denom(self, p, q): if q == 1: if p < 0: return prettyForm(str(p), binding=prettyForm.NEG) else: return prettyForm(str(p)) elif abs(p) >= 10 and abs(q) >= 10: # If more than one digit in numer and denom, print larger fraction if p < 0: return prettyForm(str(p), binding=prettyForm.NEG)/prettyForm(str(q)) # Old printing method: #pform = prettyForm(str(-p))/prettyForm(str(q)) #return prettyForm(binding=prettyForm.NEG, *pform.left('- ')) else: return prettyForm(str(p))/prettyForm(str(q)) else: return None def _print_Rational(self, expr): result = self.__print_numer_denom(expr.p, expr.q) if result is not None: return result else: return self.emptyPrinter(expr) def _print_Fraction(self, expr): result = self.__print_numer_denom(expr.numerator, expr.denominator) if result is not None: return result else: return self.emptyPrinter(expr) def _print_ProductSet(self, p): if len(p.sets) >= 1 and not has_variety(p.sets): return self._print(p.sets[0]) ** self._print(len(p.sets)) else: prod_char = "\N{MULTIPLICATION SIGN}" if self._use_unicode else 'x' return self._print_seq(p.sets, None, None, ' %s ' % prod_char, parenthesize=lambda set: set.is_Union or set.is_Intersection or set.is_ProductSet) def _print_FiniteSet(self, s): items = sorted(s.args, key=default_sort_key) return self._print_seq(items, '{', '}', ', ' ) def _print_Range(self, s): if self._use_unicode: dots = "\N{HORIZONTAL ELLIPSIS}" else: dots = '...' if s.start.is_infinite and s.stop.is_infinite: if s.step.is_positive: printset = dots, -1, 0, 1, dots else: printset = dots, 1, 0, -1, dots elif s.start.is_infinite: printset = dots, s[-1] - s.step, s[-1] elif s.stop.is_infinite: it = iter(s) printset = next(it), next(it), dots elif len(s) > 4: it = iter(s) printset = next(it), next(it), dots, s[-1] else: printset = tuple(s) return self._print_seq(printset, '{', '}', ', ' ) def _print_Interval(self, i): if i.start == i.end: return self._print_seq(i.args[:1], '{', '}') else: if i.left_open: left = '(' else: left = '[' if i.right_open: right = ')' else: right = ']' return self._print_seq(i.args[:2], left, right) def _print_AccumulationBounds(self, i): left = '<' right = '>' return self._print_seq(i.args[:2], left, right) def _print_Intersection(self, u): delimiter = ' %s ' % pretty_atom('Intersection', 'n') return self._print_seq(u.args, None, None, delimiter, parenthesize=lambda set: set.is_ProductSet or set.is_Union or set.is_Complement) def _print_Union(self, u): union_delimiter = ' %s ' % pretty_atom('Union', 'U') return self._print_seq(u.args, None, None, union_delimiter, parenthesize=lambda set: set.is_ProductSet or set.is_Intersection or set.is_Complement) def _print_SymmetricDifference(self, u): if not self._use_unicode: raise NotImplementedError("ASCII pretty printing of SymmetricDifference is not implemented") sym_delimeter = ' %s ' % pretty_atom('SymmetricDifference') return self._print_seq(u.args, None, None, sym_delimeter) def _print_Complement(self, u): delimiter = r' \ ' return self._print_seq(u.args, None, None, delimiter, parenthesize=lambda set: set.is_ProductSet or set.is_Intersection or set.is_Union) def _print_ImageSet(self, ts): if self._use_unicode: inn = "\N{SMALL ELEMENT OF}" else: inn = 'in' fun = ts.lamda sets = ts.base_sets signature = fun.signature expr = self._print(fun.expr) # TODO: the stuff to the left of the | and the stuff to the right of # the | should have independent baselines, that way something like # ImageSet(Lambda(x, 1/x**2), S.Naturals) prints the "x in N" part # centered on the right instead of aligned with the fraction bar on # the left. The same also applies to ConditionSet and ComplexRegion if len(signature) == 1: S = self._print_seq((signature[0], inn, sets[0]), delimiter=' ') return self._hprint_vseparator(expr, S, left='{', right='}', ifascii_nougly=True, delimiter=' ') else: pargs = tuple(j for var, setv in zip(signature, sets) for j in (var, ' ', inn, ' ', setv, ", ")) S = self._print_seq(pargs[:-1], delimiter='') return self._hprint_vseparator(expr, S, left='{', right='}', ifascii_nougly=True, delimiter=' ') def _print_ConditionSet(self, ts): if self._use_unicode: inn = "\N{SMALL ELEMENT OF}" # using _and because and is a keyword and it is bad practice to # overwrite them _and = "\N{LOGICAL AND}" else: inn = 'in' _and = 'and' variables = self._print_seq(Tuple(ts.sym)) as_expr = getattr(ts.condition, 'as_expr', None) if as_expr is not None: cond = self._print(ts.condition.as_expr()) else: cond = self._print(ts.condition) if self._use_unicode: cond = self._print(cond) cond = prettyForm(*cond.parens()) if ts.base_set is S.UniversalSet: return self._hprint_vseparator(variables, cond, left="{", right="}", ifascii_nougly=True, delimiter=' ') base = self._print(ts.base_set) C = self._print_seq((variables, inn, base, _and, cond), delimiter=' ') return self._hprint_vseparator(variables, C, left="{", right="}", ifascii_nougly=True, delimiter=' ') def _print_ComplexRegion(self, ts): if self._use_unicode: inn = "\N{SMALL ELEMENT OF}" else: inn = 'in' variables = self._print_seq(ts.variables) expr = self._print(ts.expr) prodsets = self._print(ts.sets) C = self._print_seq((variables, inn, prodsets), delimiter=' ') return self._hprint_vseparator(expr, C, left="{", right="}", ifascii_nougly=True, delimiter=' ') def _print_Contains(self, e): var, set = e.args if self._use_unicode: el = " \N{ELEMENT OF} " return prettyForm(*stringPict.next(self._print(var), el, self._print(set)), binding=8) else: return prettyForm(sstr(e)) def _print_FourierSeries(self, s): if self._use_unicode: dots = "\N{HORIZONTAL ELLIPSIS}" else: dots = '...' return self._print_Add(s.truncate()) + self._print(dots) def _print_FormalPowerSeries(self, s): return self._print_Add(s.infinite) def _print_SetExpr(self, se): pretty_set = prettyForm(*self._print(se.set).parens()) pretty_name = self._print(Symbol("SetExpr")) return prettyForm(*pretty_name.right(pretty_set)) def _print_SeqFormula(self, s): if self._use_unicode: dots = "\N{HORIZONTAL ELLIPSIS}" else: dots = '...' if len(s.start.free_symbols) > 0 or len(s.stop.free_symbols) > 0: raise NotImplementedError("Pretty printing of sequences with symbolic bound not implemented") if s.start is S.NegativeInfinity: stop = s.stop printset = (dots, s.coeff(stop - 3), s.coeff(stop - 2), s.coeff(stop - 1), s.coeff(stop)) elif s.stop is S.Infinity or s.length > 4: printset = s[:4] printset.append(dots) printset = tuple(printset) else: printset = tuple(s) return self._print_list(printset) _print_SeqPer = _print_SeqFormula _print_SeqAdd = _print_SeqFormula _print_SeqMul = _print_SeqFormula def _print_seq(self, seq, left=None, right=None, delimiter=', ', parenthesize=lambda x: False, ifascii_nougly=True): try: pforms = [] for item in seq: pform = self._print(item) if parenthesize(item): pform = prettyForm(*pform.parens()) if pforms: pforms.append(delimiter) pforms.append(pform) if not pforms: s = stringPict('') else: s = prettyForm(*stringPict.next(*pforms)) # XXX: Under the tests from #15686 the above raises: # AttributeError: 'Fake' object has no attribute 'baseline' # This is caught below but that is not the right way to # fix it. except AttributeError: s = None for item in seq: pform = self.doprint(item) if parenthesize(item): pform = prettyForm(*pform.parens()) if s is None: # first element s = pform else : s = prettyForm(*stringPict.next(s, delimiter)) s = prettyForm(*stringPict.next(s, pform)) if s is None: s = stringPict('') s = prettyForm(*s.parens(left, right, ifascii_nougly=ifascii_nougly)) return s def join(self, delimiter, args): pform = None for arg in args: if pform is None: pform = arg else: pform = prettyForm(*pform.right(delimiter)) pform = prettyForm(*pform.right(arg)) if pform is None: return prettyForm("") else: return pform def _print_list(self, l): return self._print_seq(l, '[', ']') def _print_tuple(self, t): if len(t) == 1: ptuple = prettyForm(*stringPict.next(self._print(t[0]), ',')) return prettyForm(*ptuple.parens('(', ')', ifascii_nougly=True)) else: return self._print_seq(t, '(', ')') def _print_Tuple(self, expr): return self._print_tuple(expr) def _print_dict(self, d): keys = sorted(d.keys(), key=default_sort_key) items = [] for k in keys: K = self._print(k) V = self._print(d[k]) s = prettyForm(*stringPict.next(K, ': ', V)) items.append(s) return self._print_seq(items, '{', '}') def _print_Dict(self, d): return self._print_dict(d) def _print_set(self, s): if not s: return prettyForm('set()') items = sorted(s, key=default_sort_key) pretty = self._print_seq(items) pretty = prettyForm(*pretty.parens('{', '}', ifascii_nougly=True)) return pretty def _print_frozenset(self, s): if not s: return prettyForm('frozenset()') items = sorted(s, key=default_sort_key) pretty = self._print_seq(items) pretty = prettyForm(*pretty.parens('{', '}', ifascii_nougly=True)) pretty = prettyForm(*pretty.parens('(', ')', ifascii_nougly=True)) pretty = prettyForm(*stringPict.next(type(s).__name__, pretty)) return pretty def _print_UniversalSet(self, s): if self._use_unicode: return prettyForm("\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL U}") else: return prettyForm('UniversalSet') def _print_PolyRing(self, ring): return prettyForm(sstr(ring)) def _print_FracField(self, field): return prettyForm(sstr(field)) def _print_FreeGroupElement(self, elm): return prettyForm(str(elm)) def _print_PolyElement(self, poly): return prettyForm(sstr(poly)) def _print_FracElement(self, frac): return prettyForm(sstr(frac)) def _print_AlgebraicNumber(self, expr): if expr.is_aliased: return self._print(expr.as_poly().as_expr()) else: return self._print(expr.as_expr()) def _print_ComplexRootOf(self, expr): args = [self._print_Add(expr.expr, order='lex'), expr.index] pform = prettyForm(*self._print_seq(args).parens()) pform = prettyForm(*pform.left('CRootOf')) return pform def _print_RootSum(self, expr): args = [self._print_Add(expr.expr, order='lex')] if expr.fun is not S.IdentityFunction: args.append(self._print(expr.fun)) pform = prettyForm(*self._print_seq(args).parens()) pform = prettyForm(*pform.left('RootSum')) return pform def _print_FiniteField(self, expr): if self._use_unicode: form = '\N{DOUBLE-STRUCK CAPITAL Z}_%d' else: form = 'GF(%d)' return prettyForm(pretty_symbol(form % expr.mod)) def _print_IntegerRing(self, expr): if self._use_unicode: return prettyForm('\N{DOUBLE-STRUCK CAPITAL Z}') else: return prettyForm('ZZ') def _print_RationalField(self, expr): if self._use_unicode: return prettyForm('\N{DOUBLE-STRUCK CAPITAL Q}') else: return prettyForm('QQ') def _print_RealField(self, domain): if self._use_unicode: prefix = '\N{DOUBLE-STRUCK CAPITAL R}' else: prefix = 'RR' if domain.has_default_precision: return prettyForm(prefix) else: return self._print(pretty_symbol(prefix + "_" + str(domain.precision))) def _print_ComplexField(self, domain): if self._use_unicode: prefix = '\N{DOUBLE-STRUCK CAPITAL C}' else: prefix = 'CC' if domain.has_default_precision: return prettyForm(prefix) else: return self._print(pretty_symbol(prefix + "_" + str(domain.precision))) def _print_PolynomialRing(self, expr): args = list(expr.symbols) if not expr.order.is_default: order = prettyForm(*prettyForm("order=").right(self._print(expr.order))) args.append(order) pform = self._print_seq(args, '[', ']') pform = prettyForm(*pform.left(self._print(expr.domain))) return pform def _print_FractionField(self, expr): args = list(expr.symbols) if not expr.order.is_default: order = prettyForm(*prettyForm("order=").right(self._print(expr.order))) args.append(order) pform = self._print_seq(args, '(', ')') pform = prettyForm(*pform.left(self._print(expr.domain))) return pform def _print_PolynomialRingBase(self, expr): g = expr.symbols if str(expr.order) != str(expr.default_order): g = g + ("order=" + str(expr.order),) pform = self._print_seq(g, '[', ']') pform = prettyForm(*pform.left(self._print(expr.domain))) return pform def _print_GroebnerBasis(self, basis): exprs = [ self._print_Add(arg, order=basis.order) for arg in basis.exprs ] exprs = prettyForm(*self.join(", ", exprs).parens(left="[", right="]")) gens = [ self._print(gen) for gen in basis.gens ] domain = prettyForm( *prettyForm("domain=").right(self._print(basis.domain))) order = prettyForm( *prettyForm("order=").right(self._print(basis.order))) pform = self.join(", ", [exprs] + gens + [domain, order]) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(basis.__class__.__name__)) return pform def _print_Subs(self, e): pform = self._print(e.expr) pform = prettyForm(*pform.parens()) h = pform.height() if pform.height() > 1 else 2 rvert = stringPict(vobj('|', h), baseline=pform.baseline) pform = prettyForm(*pform.right(rvert)) b = pform.baseline pform.baseline = pform.height() - 1 pform = prettyForm(*pform.right(self._print_seq([ self._print_seq((self._print(v[0]), xsym('=='), self._print(v[1])), delimiter='') for v in zip(e.variables, e.point) ]))) pform.baseline = b return pform def _print_number_function(self, e, name): # Print name_arg[0] for one argument or name_arg[0](arg[1]) # for more than one argument pform = prettyForm(name) arg = self._print(e.args[0]) pform_arg = prettyForm(" "*arg.width()) pform_arg = prettyForm(*pform_arg.below(arg)) pform = prettyForm(*pform.right(pform_arg)) if len(e.args) == 1: return pform m, x = e.args # TODO: copy-pasted from _print_Function: can we do better? prettyFunc = pform prettyArgs = prettyForm(*self._print_seq([x]).parens()) pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_euler(self, e): return self._print_number_function(e, "E") def _print_catalan(self, e): return self._print_number_function(e, "C") def _print_bernoulli(self, e): return self._print_number_function(e, "B") _print_bell = _print_bernoulli def _print_lucas(self, e): return self._print_number_function(e, "L") def _print_fibonacci(self, e): return self._print_number_function(e, "F") def _print_tribonacci(self, e): return self._print_number_function(e, "T") def _print_stieltjes(self, e): if self._use_unicode: return self._print_number_function(e, '\N{GREEK SMALL LETTER GAMMA}') else: return self._print_number_function(e, "stieltjes") def _print_KroneckerDelta(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.right(prettyForm(','))) pform = prettyForm(*pform.right(self._print(e.args[1]))) if self._use_unicode: a = stringPict(pretty_symbol('delta')) else: a = stringPict('d') b = pform top = stringPict(*b.left(' '*a.width())) bot = stringPict(*a.right(' '*b.width())) return prettyForm(binding=prettyForm.POW, *bot.below(top)) def _print_RandomDomain(self, d): if hasattr(d, 'as_boolean'): pform = self._print('Domain: ') pform = prettyForm(*pform.right(self._print(d.as_boolean()))) return pform elif hasattr(d, 'set'): pform = self._print('Domain: ') pform = prettyForm(*pform.right(self._print(d.symbols))) pform = prettyForm(*pform.right(self._print(' in '))) pform = prettyForm(*pform.right(self._print(d.set))) return pform elif hasattr(d, 'symbols'): pform = self._print('Domain on ') pform = prettyForm(*pform.right(self._print(d.symbols))) return pform else: return self._print(None) def _print_DMP(self, p): try: if p.ring is not None: # TODO incorporate order return self._print(p.ring.to_sympy(p)) except SympifyError: pass return self._print(repr(p)) def _print_DMF(self, p): return self._print_DMP(p) def _print_Object(self, object): return self._print(pretty_symbol(object.name)) def _print_Morphism(self, morphism): arrow = xsym("-->") domain = self._print(morphism.domain) codomain = self._print(morphism.codomain) tail = domain.right(arrow, codomain)[0] return prettyForm(tail) def _print_NamedMorphism(self, morphism): pretty_name = self._print(pretty_symbol(morphism.name)) pretty_morphism = self._print_Morphism(morphism) return prettyForm(pretty_name.right(":", pretty_morphism)[0]) def _print_IdentityMorphism(self, morphism): from sympy.categories import NamedMorphism return self._print_NamedMorphism( NamedMorphism(morphism.domain, morphism.codomain, "id")) def _print_CompositeMorphism(self, morphism): circle = xsym(".") # All components of the morphism have names and it is thus # possible to build the name of the composite. component_names_list = [pretty_symbol(component.name) for component in morphism.components] component_names_list.reverse() component_names = circle.join(component_names_list) + ":" pretty_name = self._print(component_names) pretty_morphism = self._print_Morphism(morphism) return prettyForm(pretty_name.right(pretty_morphism)[0]) def _print_Category(self, category): return self._print(pretty_symbol(category.name)) def _print_Diagram(self, diagram): if not diagram.premises: # This is an empty diagram. return self._print(S.EmptySet) pretty_result = self._print(diagram.premises) if diagram.conclusions: results_arrow = " %s " % xsym("==>") pretty_conclusions = self._print(diagram.conclusions)[0] pretty_result = pretty_result.right( results_arrow, pretty_conclusions) return prettyForm(pretty_result[0]) def _print_DiagramGrid(self, grid): from sympy.matrices import Matrix from sympy import Symbol matrix = Matrix([[grid[i, j] if grid[i, j] else Symbol(" ") for j in range(grid.width)] for i in range(grid.height)]) return self._print_matrix_contents(matrix) def _print_FreeModuleElement(self, m): # Print as row vector for convenience, for now. return self._print_seq(m, '[', ']') def _print_SubModule(self, M): return self._print_seq(M.gens, '<', '>') def _print_FreeModule(self, M): return self._print(M.ring)**self._print(M.rank) def _print_ModuleImplementedIdeal(self, M): return self._print_seq([x for [x] in M._module.gens], '<', '>') def _print_QuotientRing(self, R): return self._print(R.ring) / self._print(R.base_ideal) def _print_QuotientRingElement(self, R): return self._print(R.data) + self._print(R.ring.base_ideal) def _print_QuotientModuleElement(self, m): return self._print(m.data) + self._print(m.module.killed_module) def _print_QuotientModule(self, M): return self._print(M.base) / self._print(M.killed_module) def _print_MatrixHomomorphism(self, h): matrix = self._print(h._sympy_matrix()) matrix.baseline = matrix.height() // 2 pform = prettyForm(*matrix.right(' : ', self._print(h.domain), ' %s> ' % hobj('-', 2), self._print(h.codomain))) return pform def _print_Manifold(self, manifold): return self._print(manifold.name) def _print_Patch(self, patch): return self._print(patch.name) def _print_CoordSystem(self, coords): return self._print(coords.name) def _print_BaseScalarField(self, field): string = field._coord_sys.symbols[field._index].name return self._print(pretty_symbol(string)) def _print_BaseVectorField(self, field): s = U('PARTIAL DIFFERENTIAL') + '_' + field._coord_sys.symbols[field._index].name return self._print(pretty_symbol(s)) def _print_Differential(self, diff): field = diff._form_field if hasattr(field, '_coord_sys'): string = field._coord_sys.symbols[field._index].name return self._print('\N{DOUBLE-STRUCK ITALIC SMALL D} ' + pretty_symbol(string)) else: pform = self._print(field) pform = prettyForm(*pform.parens()) return prettyForm(*pform.left("\N{DOUBLE-STRUCK ITALIC SMALL D}")) def _print_Tr(self, p): #TODO: Handle indices pform = self._print(p.args[0]) pform = prettyForm(*pform.left('%s(' % (p.__class__.__name__))) pform = prettyForm(*pform.right(')')) return pform def _print_primenu(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) if self._use_unicode: pform = prettyForm(*pform.left(greek_unicode['nu'])) else: pform = prettyForm(*pform.left('nu')) return pform def _print_primeomega(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) if self._use_unicode: pform = prettyForm(*pform.left(greek_unicode['Omega'])) else: pform = prettyForm(*pform.left('Omega')) return pform def _print_Quantity(self, e): if e.name.name == 'degree': pform = self._print("\N{DEGREE SIGN}") return pform else: return self.emptyPrinter(e) def _print_AssignmentBase(self, e): op = prettyForm(' ' + xsym(e.op) + ' ') l = self._print(e.lhs) r = self._print(e.rhs) pform = prettyForm(*stringPict.next(l, op, r)) return pform def _print_Str(self, s): return self._print(s.name) @print_function(PrettyPrinter) def pretty(expr, **settings): """Returns a string containing the prettified form of expr. For information on keyword arguments see pretty_print function. """ pp = PrettyPrinter(settings) # XXX: this is an ugly hack, but at least it works use_unicode = pp._settings['use_unicode'] uflag = pretty_use_unicode(use_unicode) try: return pp.doprint(expr) finally: pretty_use_unicode(uflag) def pretty_print(expr, **kwargs): """Prints expr in pretty form. pprint is just a shortcut for this function. Parameters ========== expr : expression The expression to print. wrap_line : bool, optional (default=True) Line wrapping enabled/disabled. num_columns : int or None, optional (default=None) Number of columns before line breaking (default to None which reads the terminal width), useful when using SymPy without terminal. use_unicode : bool or None, optional (default=None) Use unicode characters, such as the Greek letter pi instead of the string pi. full_prec : bool or string, optional (default="auto") Use full precision. order : bool or string, optional (default=None) Set to 'none' for long expressions if slow; default is None. use_unicode_sqrt_char : bool, optional (default=True) Use compact single-character square root symbol (when unambiguous). root_notation : bool, optional (default=True) Set to 'False' for printing exponents of the form 1/n in fractional form. By default exponent is printed in root form. mat_symbol_style : string, optional (default="plain") Set to "bold" for printing MatrixSymbols using a bold mathematical symbol face. By default the standard face is used. imaginary_unit : string, optional (default="i") Letter to use for imaginary unit when use_unicode is True. Can be "i" (default) or "j". """ print(pretty(expr, **kwargs)) pprint = pretty_print def pager_print(expr, **settings): """Prints expr using the pager, in pretty form. This invokes a pager command using pydoc. Lines are not wrapped automatically. This routine is meant to be used with a pager that allows sideways scrolling, like ``less -S``. Parameters are the same as for ``pretty_print``. If you wish to wrap lines, pass ``num_columns=None`` to auto-detect the width of the terminal. """ from pydoc import pager from locale import getpreferredencoding if 'num_columns' not in settings: settings['num_columns'] = 500000 # disable line wrap pager(pretty(expr, **settings).encode(getpreferredencoding()))
c6f99d0482a4656c89e814442bbe765baca87a32e39b77a1e0cd89e37bbbb1ed
from sympy import (Add, Abs, Catalan, cos, Derivative, E, EulerGamma, exp, factorial, factorial2, Function, GoldenRatio, TribonacciConstant, I, Integer, Integral, Interval, Lambda, Limit, Matrix, nan, O, oo, pi, Pow, Rational, Float, Rel, S, sin, SparseMatrix, sqrt, summation, Sum, Symbol, symbols, Wild, WildFunction, zeta, zoo, Dummy, Dict, Tuple, FiniteSet, factor, subfactorial, true, false, Equivalent, Xor, Complement, SymmetricDifference, AccumBounds, UnevaluatedExpr, Eq, Ne, Quaternion, Subs, MatrixSymbol, MatrixSlice, Q) from sympy.core import Expr, Mul from sympy.core.parameters import _exp_is_pow from sympy.external import import_module from sympy.physics.control.lti import TransferFunction, Series, Parallel, \ Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback from sympy.physics.units import second, joule from sympy.polys import (Poly, rootof, RootSum, groebner, ring, field, ZZ, QQ, ZZ_I, QQ_I, lex, grlex) from sympy.geometry import Point, Circle, Polygon, Ellipse, Triangle from sympy.tensor import NDimArray from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayElement from sympy.testing.pytest import raises from sympy.printing import sstr, sstrrepr, StrPrinter from sympy.core.trace import Tr x, y, z, w, t = symbols('x,y,z,w,t') d = Dummy('d') def test_printmethod(): class R(Abs): def _sympystr(self, printer): return "foo(%s)" % printer._print(self.args[0]) assert sstr(R(x)) == "foo(x)" class R(Abs): def _sympystr(self, printer): return "foo" assert sstr(R(x)) == "foo" def test_Abs(): assert str(Abs(x)) == "Abs(x)" assert str(Abs(Rational(1, 6))) == "1/6" assert str(Abs(Rational(-1, 6))) == "1/6" def test_Add(): assert str(x + y) == "x + y" assert str(x + 1) == "x + 1" assert str(x + x**2) == "x**2 + x" assert str(Add(0, 1, evaluate=False)) == "0 + 1" assert str(Add(0, 0, 1, evaluate=False)) == "0 + 0 + 1" assert str(1.0*x) == "1.0*x" assert str(5 + x + y + x*y + x**2 + y**2) == "x**2 + x*y + x + y**2 + y + 5" assert str(1 + x + x**2/2 + x**3/3) == "x**3/3 + x**2/2 + x + 1" assert str(2*x - 7*x**2 + 2 + 3*y) == "-7*x**2 + 2*x + 3*y + 2" assert str(x - y) == "x - y" assert str(2 - x) == "2 - x" assert str(x - 2) == "x - 2" assert str(x - y - z - w) == "-w + x - y - z" assert str(x - z*y**2*z*w) == "-w*y**2*z**2 + x" assert str(x - 1*y*x*y) == "-x*y**2 + x" assert str(sin(x).series(x, 0, 15)) == "x - x**3/6 + x**5/120 - x**7/5040 + x**9/362880 - x**11/39916800 + x**13/6227020800 + O(x**15)" def test_Catalan(): assert str(Catalan) == "Catalan" def test_ComplexInfinity(): assert str(zoo) == "zoo" def test_Derivative(): assert str(Derivative(x, y)) == "Derivative(x, y)" assert str(Derivative(x**2, x, evaluate=False)) == "Derivative(x**2, x)" assert str(Derivative( x**2/y, x, y, evaluate=False)) == "Derivative(x**2/y, x, y)" def test_dict(): assert str({1: 1 + x}) == sstr({1: 1 + x}) == "{1: x + 1}" assert str({1: x**2, 2: y*x}) in ("{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}") assert sstr({1: x**2, 2: y*x}) == "{1: x**2, 2: x*y}" def test_Dict(): assert str(Dict({1: 1 + x})) == sstr({1: 1 + x}) == "{1: x + 1}" assert str(Dict({1: x**2, 2: y*x})) in ( "{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}") assert sstr(Dict({1: x**2, 2: y*x})) == "{1: x**2, 2: x*y}" def test_Dummy(): assert str(d) == "_d" assert str(d + x) == "_d + x" def test_EulerGamma(): assert str(EulerGamma) == "EulerGamma" def test_Exp(): assert str(E) == "E" with _exp_is_pow(True): assert str(exp(x)) == "E**x" def test_factorial(): n = Symbol('n', integer=True) assert str(factorial(-2)) == "zoo" assert str(factorial(0)) == "1" assert str(factorial(7)) == "5040" assert str(factorial(n)) == "factorial(n)" assert str(factorial(2*n)) == "factorial(2*n)" assert str(factorial(factorial(n))) == 'factorial(factorial(n))' assert str(factorial(factorial2(n))) == 'factorial(factorial2(n))' assert str(factorial2(factorial(n))) == 'factorial2(factorial(n))' assert str(factorial2(factorial2(n))) == 'factorial2(factorial2(n))' assert str(subfactorial(3)) == "2" assert str(subfactorial(n)) == "subfactorial(n)" assert str(subfactorial(2*n)) == "subfactorial(2*n)" def test_Function(): f = Function('f') fx = f(x) w = WildFunction('w') assert str(f) == "f" assert str(fx) == "f(x)" assert str(w) == "w_" def test_Geometry(): assert sstr(Point(0, 0)) == 'Point2D(0, 0)' assert sstr(Circle(Point(0, 0), 3)) == 'Circle(Point2D(0, 0), 3)' assert sstr(Ellipse(Point(1, 2), 3, 4)) == 'Ellipse(Point2D(1, 2), 3, 4)' assert sstr(Triangle(Point(1, 1), Point(7, 8), Point(0, -1))) == \ 'Triangle(Point2D(1, 1), Point2D(7, 8), Point2D(0, -1))' assert sstr(Polygon(Point(5, 6), Point(-2, -3), Point(0, 0), Point(4, 7))) == \ 'Polygon(Point2D(5, 6), Point2D(-2, -3), Point2D(0, 0), Point2D(4, 7))' assert sstr(Triangle(Point(0, 0), Point(1, 0), Point(0, 1)), sympy_integers=True) == \ 'Triangle(Point2D(S(0), S(0)), Point2D(S(1), S(0)), Point2D(S(0), S(1)))' assert sstr(Ellipse(Point(1, 2), 3, 4), sympy_integers=True) == \ 'Ellipse(Point2D(S(1), S(2)), S(3), S(4))' def test_GoldenRatio(): assert str(GoldenRatio) == "GoldenRatio" def test_TribonacciConstant(): assert str(TribonacciConstant) == "TribonacciConstant" def test_ImaginaryUnit(): assert str(I) == "I" def test_Infinity(): assert str(oo) == "oo" assert str(oo*I) == "oo*I" def test_Integer(): assert str(Integer(-1)) == "-1" assert str(Integer(1)) == "1" assert str(Integer(-3)) == "-3" assert str(Integer(0)) == "0" assert str(Integer(25)) == "25" def test_Integral(): assert str(Integral(sin(x), y)) == "Integral(sin(x), y)" assert str(Integral(sin(x), (y, 0, 1))) == "Integral(sin(x), (y, 0, 1))" def test_Interval(): n = (S.NegativeInfinity, 1, 2, S.Infinity) for i in range(len(n)): for j in range(i + 1, len(n)): for l in (True, False): for r in (True, False): ival = Interval(n[i], n[j], l, r) assert S(str(ival)) == ival def test_AccumBounds(): a = Symbol('a', real=True) assert str(AccumBounds(0, a)) == "AccumBounds(0, a)" assert str(AccumBounds(0, 1)) == "AccumBounds(0, 1)" def test_Lambda(): assert str(Lambda(d, d**2)) == "Lambda(_d, _d**2)" # issue 2908 assert str(Lambda((), 1)) == "Lambda((), 1)" assert str(Lambda((), x)) == "Lambda((), x)" assert str(Lambda((x, y), x+y)) == "Lambda((x, y), x + y)" assert str(Lambda(((x, y),), x+y)) == "Lambda(((x, y),), x + y)" def test_Limit(): assert str(Limit(sin(x)/x, x, y)) == "Limit(sin(x)/x, x, y)" assert str(Limit(1/x, x, 0)) == "Limit(1/x, x, 0)" assert str( Limit(sin(x)/x, x, y, dir="-")) == "Limit(sin(x)/x, x, y, dir='-')" def test_list(): assert str([x]) == sstr([x]) == "[x]" assert str([x**2, x*y + 1]) == sstr([x**2, x*y + 1]) == "[x**2, x*y + 1]" assert str([x**2, [y + x]]) == sstr([x**2, [y + x]]) == "[x**2, [x + y]]" def test_Matrix_str(): M = Matrix([[x**+1, 1], [y, x + y]]) assert str(M) == "Matrix([[x, 1], [y, x + y]])" assert sstr(M) == "Matrix([\n[x, 1],\n[y, x + y]])" M = Matrix([[1]]) assert str(M) == sstr(M) == "Matrix([[1]])" M = Matrix([[1, 2]]) assert str(M) == sstr(M) == "Matrix([[1, 2]])" M = Matrix() assert str(M) == sstr(M) == "Matrix(0, 0, [])" M = Matrix(0, 1, lambda i, j: 0) assert str(M) == sstr(M) == "Matrix(0, 1, [])" def test_Mul(): assert str(x/y) == "x/y" assert str(y/x) == "y/x" assert str(x/y/z) == "x/(y*z)" assert str((x + 1)/(y + 2)) == "(x + 1)/(y + 2)" assert str(2*x/3) == '2*x/3' assert str(-2*x/3) == '-2*x/3' assert str(-1.0*x) == '-1.0*x' assert str(1.0*x) == '1.0*x' assert str(Mul(0, 1, evaluate=False)) == '0*1' assert str(Mul(1, 0, evaluate=False)) == '1*0' assert str(Mul(1, 1, evaluate=False)) == '1*1' assert str(Mul(1, 1, 1, evaluate=False)) == '1*1*1' assert str(Mul(1, 2, evaluate=False)) == '1*2' assert str(Mul(1, S.Half, evaluate=False)) == '1*(1/2)' assert str(Mul(1, 1, S.Half, evaluate=False)) == '1*1*(1/2)' assert str(Mul(1, 1, 2, 3, x, evaluate=False)) == '1*1*2*3*x' assert str(Mul(1, -1, evaluate=False)) == '1*(-1)' assert str(Mul(-1, 1, evaluate=False)) == '-1*1' assert str(Mul(4, 3, 2, 1, 0, y, x, evaluate=False)) == '4*3*2*1*0*y*x' assert str(Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)) == '4*3*2*(z + 1)*0*y*x' assert str(Mul(Rational(2, 3), Rational(5, 7), evaluate=False)) == '(2/3)*(5/7)' # For issue 14160 assert str(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False), evaluate=False)) == '-2*x/(y*y)' # issue 21537 assert str(Mul(x, Pow(1/y, -1, evaluate=False), evaluate=False)) == 'x/(1/y)' class CustomClass1(Expr): is_commutative = True class CustomClass2(Expr): is_commutative = True cc1 = CustomClass1() cc2 = CustomClass2() assert str(Rational(2)*cc1) == '2*CustomClass1()' assert str(cc1*Rational(2)) == '2*CustomClass1()' assert str(cc1*Float("1.5")) == '1.5*CustomClass1()' assert str(cc2*Rational(2)) == '2*CustomClass2()' assert str(cc2*Rational(2)*cc1) == '2*CustomClass1()*CustomClass2()' assert str(cc1*Rational(2)*cc2) == '2*CustomClass1()*CustomClass2()' def test_NaN(): assert str(nan) == "nan" def test_NegativeInfinity(): assert str(-oo) == "-oo" def test_Order(): assert str(O(x)) == "O(x)" assert str(O(x**2)) == "O(x**2)" assert str(O(x*y)) == "O(x*y, x, y)" assert str(O(x, x)) == "O(x)" assert str(O(x, (x, 0))) == "O(x)" assert str(O(x, (x, oo))) == "O(x, (x, oo))" assert str(O(x, x, y)) == "O(x, x, y)" assert str(O(x, x, y)) == "O(x, x, y)" assert str(O(x, (x, oo), (y, oo))) == "O(x, (x, oo), (y, oo))" def test_Permutation_Cycle(): from sympy.combinatorics import Permutation, Cycle # general principle: economically, canonically show all moved elements # and the size of the permutation. for p, s in [ (Cycle(), '()'), (Cycle(2), '(2)'), (Cycle(2, 1), '(1 2)'), (Cycle(1, 2)(5)(6, 7)(10), '(1 2)(6 7)(10)'), (Cycle(3, 4)(1, 2)(3, 4), '(1 2)(4)'), ]: assert sstr(p) == s for p, s in [ (Permutation([]), 'Permutation([])'), (Permutation([], size=1), 'Permutation([0])'), (Permutation([], size=2), 'Permutation([0, 1])'), (Permutation([], size=10), 'Permutation([], size=10)'), (Permutation([1, 0, 2]), 'Permutation([1, 0, 2])'), (Permutation([1, 0, 2, 3, 4, 5]), 'Permutation([1, 0], size=6)'), (Permutation([1, 0, 2, 3, 4, 5], size=10), 'Permutation([1, 0], size=10)'), ]: assert sstr(p, perm_cyclic=False) == s for p, s in [ (Permutation([]), '()'), (Permutation([], size=1), '(0)'), (Permutation([], size=2), '(1)'), (Permutation([], size=10), '(9)'), (Permutation([1, 0, 2]), '(2)(0 1)'), (Permutation([1, 0, 2, 3, 4, 5]), '(5)(0 1)'), (Permutation([1, 0, 2, 3, 4, 5], size=10), '(9)(0 1)'), (Permutation([0, 1, 3, 2, 4, 5], size=10), '(9)(2 3)'), ]: assert sstr(p) == s def test_Pi(): assert str(pi) == "pi" def test_Poly(): assert str(Poly(0, x)) == "Poly(0, x, domain='ZZ')" assert str(Poly(1, x)) == "Poly(1, x, domain='ZZ')" assert str(Poly(x, x)) == "Poly(x, x, domain='ZZ')" assert str(Poly(2*x + 1, x)) == "Poly(2*x + 1, x, domain='ZZ')" assert str(Poly(2*x - 1, x)) == "Poly(2*x - 1, x, domain='ZZ')" assert str(Poly(-1, x)) == "Poly(-1, x, domain='ZZ')" assert str(Poly(-x, x)) == "Poly(-x, x, domain='ZZ')" assert str(Poly(-2*x + 1, x)) == "Poly(-2*x + 1, x, domain='ZZ')" assert str(Poly(-2*x - 1, x)) == "Poly(-2*x - 1, x, domain='ZZ')" assert str(Poly(x - 1, x)) == "Poly(x - 1, x, domain='ZZ')" assert str(Poly(2*x + x**5, x)) == "Poly(x**5 + 2*x, x, domain='ZZ')" assert str(Poly(3**(2*x), 3**x)) == "Poly((3**x)**2, 3**x, domain='ZZ')" assert str(Poly((x**2)**x)) == "Poly(((x**2)**x), (x**2)**x, domain='ZZ')" assert str(Poly((x + y)**3, (x + y), expand=False) ) == "Poly((x + y)**3, x + y, domain='ZZ')" assert str(Poly((x - 1)**2, (x - 1), expand=False) ) == "Poly((x - 1)**2, x - 1, domain='ZZ')" assert str( Poly(x**2 + 1 + y, x)) == "Poly(x**2 + y + 1, x, domain='ZZ[y]')" assert str( Poly(x**2 - 1 + y, x)) == "Poly(x**2 + y - 1, x, domain='ZZ[y]')" assert str(Poly(x**2 + I*x, x)) == "Poly(x**2 + I*x, x, domain='ZZ_I')" assert str(Poly(x**2 - I*x, x)) == "Poly(x**2 - I*x, x, domain='ZZ_I')" assert str(Poly(-x*y*z + x*y - 1, x, y, z) ) == "Poly(-x*y*z + x*y - 1, x, y, z, domain='ZZ')" assert str(Poly(-w*x**21*y**7*z + (1 + w)*z**3 - 2*x*z + 1, x, y, z)) == \ "Poly(-w*x**21*y**7*z - 2*x*z + (w + 1)*z**3 + 1, x, y, z, domain='ZZ[w]')" assert str(Poly(x**2 + 1, x, modulus=2)) == "Poly(x**2 + 1, x, modulus=2)" assert str(Poly(2*x**2 + 3*x + 4, x, modulus=17)) == "Poly(2*x**2 + 3*x + 4, x, modulus=17)" def test_PolyRing(): assert str(ring("x", ZZ, lex)[0]) == "Polynomial ring in x over ZZ with lex order" assert str(ring("x,y", QQ, grlex)[0]) == "Polynomial ring in x, y over QQ with grlex order" assert str(ring("x,y,z", ZZ["t"], lex)[0]) == "Polynomial ring in x, y, z over ZZ[t] with lex order" def test_FracField(): assert str(field("x", ZZ, lex)[0]) == "Rational function field in x over ZZ with lex order" assert str(field("x,y", QQ, grlex)[0]) == "Rational function field in x, y over QQ with grlex order" assert str(field("x,y,z", ZZ["t"], lex)[0]) == "Rational function field in x, y, z over ZZ[t] with lex order" def test_PolyElement(): Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) Rx_zzi, xz = ring("x", ZZ_I) assert str(x - x) == "0" assert str(x - 1) == "x - 1" assert str(x + 1) == "x + 1" assert str(x**2) == "x**2" assert str(x**(-2)) == "x**(-2)" assert str(x**QQ(1, 2)) == "x**(1/2)" assert str((u**2 + 3*u*v + 1)*x**2*y + u + 1) == "(u**2 + 3*u*v + 1)*x**2*y + u + 1" assert str((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x) == "(u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x" assert str((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1) == "(u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1" assert str((-u**2 + 3*u*v - 1)*x**2*y - (u + 1)*x - 1) == "-(u**2 - 3*u*v + 1)*x**2*y - (u + 1)*x - 1" assert str(-(v**2 + v + 1)*x + 3*u*v + 1) == "-(v**2 + v + 1)*x + 3*u*v + 1" assert str(-(v**2 + v + 1)*x - 3*u*v + 1) == "-(v**2 + v + 1)*x - 3*u*v + 1" assert str((1+I)*xz + 2) == "(1 + 1*I)*x + (2 + 0*I)" def test_FracElement(): Fuv, u,v = field("u,v", ZZ) Fxyzt, x,y,z,t = field("x,y,z,t", Fuv) Rx_zzi, xz = field("x", QQ_I) i = QQ_I(0, 1) assert str(x - x) == "0" assert str(x - 1) == "x - 1" assert str(x + 1) == "x + 1" assert str(x/3) == "x/3" assert str(x/z) == "x/z" assert str(x*y/z) == "x*y/z" assert str(x/(z*t)) == "x/(z*t)" assert str(x*y/(z*t)) == "x*y/(z*t)" assert str((x - 1)/y) == "(x - 1)/y" assert str((x + 1)/y) == "(x + 1)/y" assert str((-x - 1)/y) == "(-x - 1)/y" assert str((x + 1)/(y*z)) == "(x + 1)/(y*z)" assert str(-y/(x + 1)) == "-y/(x + 1)" assert str(y*z/(x + 1)) == "y*z/(x + 1)" assert str(((u + 1)*x*y + 1)/((v - 1)*z - 1)) == "((u + 1)*x*y + 1)/((v - 1)*z - 1)" assert str(((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)) == "((u + 1)*x*y + 1)/((v - 1)*z - u*v*t - 1)" assert str((1+i)/xz) == "(1 + 1*I)/x" assert str(((1+i)*xz - i)/xz) == "((1 + 1*I)*x + (0 + -1*I))/x" def test_GaussianInteger(): assert str(ZZ_I(1, 0)) == "1" assert str(ZZ_I(-1, 0)) == "-1" assert str(ZZ_I(0, 1)) == "I" assert str(ZZ_I(0, -1)) == "-I" assert str(ZZ_I(0, 2)) == "2*I" assert str(ZZ_I(0, -2)) == "-2*I" assert str(ZZ_I(1, 1)) == "1 + I" assert str(ZZ_I(-1, -1)) == "-1 - I" assert str(ZZ_I(-1, -2)) == "-1 - 2*I" def test_GaussianRational(): assert str(QQ_I(1, 0)) == "1" assert str(QQ_I(QQ(2, 3), 0)) == "2/3" assert str(QQ_I(0, QQ(2, 3))) == "2*I/3" assert str(QQ_I(QQ(1, 2), QQ(-2, 3))) == "1/2 - 2*I/3" def test_Pow(): assert str(x**-1) == "1/x" assert str(x**-2) == "x**(-2)" assert str(x**2) == "x**2" assert str((x + y)**-1) == "1/(x + y)" assert str((x + y)**-2) == "(x + y)**(-2)" assert str((x + y)**2) == "(x + y)**2" assert str((x + y)**(1 + x)) == "(x + y)**(x + 1)" assert str(x**Rational(1, 3)) == "x**(1/3)" assert str(1/x**Rational(1, 3)) == "x**(-1/3)" assert str(sqrt(sqrt(x))) == "x**(1/4)" # not the same as x**-1 assert str(x**-1.0) == 'x**(-1.0)' # see issue #2860 assert str(Pow(S(2), -1.0, evaluate=False)) == '2**(-1.0)' def test_sqrt(): assert str(sqrt(x)) == "sqrt(x)" assert str(sqrt(x**2)) == "sqrt(x**2)" assert str(1/sqrt(x)) == "1/sqrt(x)" assert str(1/sqrt(x**2)) == "1/sqrt(x**2)" assert str(y/sqrt(x)) == "y/sqrt(x)" assert str(x**0.5) == "x**0.5" assert str(1/x**0.5) == "x**(-0.5)" def test_Rational(): n1 = Rational(1, 4) n2 = Rational(1, 3) n3 = Rational(2, 4) n4 = Rational(2, -4) n5 = Rational(0) n7 = Rational(3) n8 = Rational(-3) assert str(n1*n2) == "1/12" assert str(n1*n2) == "1/12" assert str(n3) == "1/2" assert str(n1*n3) == "1/8" assert str(n1 + n3) == "3/4" assert str(n1 + n2) == "7/12" assert str(n1 + n4) == "-1/4" assert str(n4*n4) == "1/4" assert str(n4 + n2) == "-1/6" assert str(n4 + n5) == "-1/2" assert str(n4*n5) == "0" assert str(n3 + n4) == "0" assert str(n1**n7) == "1/64" assert str(n2**n7) == "1/27" assert str(n2**n8) == "27" assert str(n7**n8) == "1/27" assert str(Rational("-25")) == "-25" assert str(Rational("1.25")) == "5/4" assert str(Rational("-2.6e-2")) == "-13/500" assert str(S("25/7")) == "25/7" assert str(S("-123/569")) == "-123/569" assert str(S("0.1[23]", rational=1)) == "61/495" assert str(S("5.1[666]", rational=1)) == "31/6" assert str(S("-5.1[666]", rational=1)) == "-31/6" assert str(S("0.[9]", rational=1)) == "1" assert str(S("-0.[9]", rational=1)) == "-1" assert str(sqrt(Rational(1, 4))) == "1/2" assert str(sqrt(Rational(1, 36))) == "1/6" assert str((123**25) ** Rational(1, 25)) == "123" assert str((123**25 + 1)**Rational(1, 25)) != "123" assert str((123**25 - 1)**Rational(1, 25)) != "123" assert str((123**25 - 1)**Rational(1, 25)) != "122" assert str(sqrt(Rational(81, 36))**3) == "27/8" assert str(1/sqrt(Rational(81, 36))**3) == "8/27" assert str(sqrt(-4)) == str(2*I) assert str(2**Rational(1, 10**10)) == "2**(1/10000000000)" assert sstr(Rational(2, 3), sympy_integers=True) == "S(2)/3" x = Symbol("x") assert sstr(x**Rational(2, 3), sympy_integers=True) == "x**(S(2)/3)" assert sstr(Eq(x, Rational(2, 3)), sympy_integers=True) == "Eq(x, S(2)/3)" assert sstr(Limit(x, x, Rational(7, 2)), sympy_integers=True) == \ "Limit(x, x, S(7)/2)" def test_Float(): # NOTE dps is the whole number of decimal digits assert str(Float('1.23', dps=1 + 2)) == '1.23' assert str(Float('1.23456789', dps=1 + 8)) == '1.23456789' assert str( Float('1.234567890123456789', dps=1 + 18)) == '1.234567890123456789' assert str(pi.evalf(1 + 2)) == '3.14' assert str(pi.evalf(1 + 14)) == '3.14159265358979' assert str(pi.evalf(1 + 64)) == ('3.141592653589793238462643383279' '5028841971693993751058209749445923') assert str(pi.round(-1)) == '0.0' assert str((pi**400 - (pi**400).round(1)).n(2)) == '-0.e+88' assert sstr(Float("100"), full_prec=False, min=-2, max=2) == '1.0e+2' assert sstr(Float("100"), full_prec=False, min=-2, max=3) == '100.0' assert sstr(Float("0.1"), full_prec=False, min=-2, max=3) == '0.1' assert sstr(Float("0.099"), min=-2, max=3) == '9.90000000000000e-2' def test_Relational(): assert str(Rel(x, y, "<")) == "x < y" assert str(Rel(x + y, y, "==")) == "Eq(x + y, y)" assert str(Rel(x, y, "!=")) == "Ne(x, y)" assert str(Eq(x, 1) | Eq(x, 2)) == "Eq(x, 1) | Eq(x, 2)" assert str(Ne(x, 1) & Ne(x, 2)) == "Ne(x, 1) & Ne(x, 2)" def test_AppliedBinaryRelation(): assert str(Q.eq(x, y)) == "Q.eq(x, y)" assert str(Q.ne(x, y)) == "Q.ne(x, y)" def test_CRootOf(): assert str(rootof(x**5 + 2*x - 1, 0)) == "CRootOf(x**5 + 2*x - 1, 0)" def test_RootSum(): f = x**5 + 2*x - 1 assert str( RootSum(f, Lambda(z, z), auto=False)) == "RootSum(x**5 + 2*x - 1)" assert str(RootSum(f, Lambda( z, z**2), auto=False)) == "RootSum(x**5 + 2*x - 1, Lambda(z, z**2))" def test_GroebnerBasis(): assert str(groebner( [], x, y)) == "GroebnerBasis([], x, y, domain='ZZ', order='lex')" F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1] assert str(groebner(F, order='grlex')) == \ "GroebnerBasis([x**2 - x - 3*y + 1, y**2 - 2*x + y - 1], x, y, domain='ZZ', order='grlex')" assert str(groebner(F, order='lex')) == \ "GroebnerBasis([2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7], x, y, domain='ZZ', order='lex')" def test_set(): assert sstr(set()) == 'set()' assert sstr(frozenset()) == 'frozenset()' assert sstr({1}) == '{1}' assert sstr(frozenset([1])) == 'frozenset({1})' assert sstr({1, 2, 3}) == '{1, 2, 3}' assert sstr(frozenset([1, 2, 3])) == 'frozenset({1, 2, 3})' assert sstr( {1, x, x**2, x**3, x**4}) == '{1, x, x**2, x**3, x**4}' assert sstr( frozenset([1, x, x**2, x**3, x**4])) == 'frozenset({1, x, x**2, x**3, x**4})' def test_SparseMatrix(): M = SparseMatrix([[x**+1, 1], [y, x + y]]) assert str(M) == "Matrix([[x, 1], [y, x + y]])" assert sstr(M) == "Matrix([\n[x, 1],\n[y, x + y]])" def test_Sum(): assert str(summation(cos(3*z), (z, x, y))) == "Sum(cos(3*z), (z, x, y))" assert str(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \ "Sum(x*y**2, (x, -2, 2), (y, -5, 5))" def test_Symbol(): assert str(y) == "y" assert str(x) == "x" e = x assert str(e) == "x" def test_tuple(): assert str((x,)) == sstr((x,)) == "(x,)" assert str((x + y, 1 + x)) == sstr((x + y, 1 + x)) == "(x + y, x + 1)" assert str((x + y, ( 1 + x, x**2))) == sstr((x + y, (1 + x, x**2))) == "(x + y, (x + 1, x**2))" def test_Series_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y) assert str(Series(tf1, tf2)) == \ "Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y))" assert str(Series(tf1, tf2, tf3)) == \ "Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y), TransferFunction(t*x**2 - t**w*x + w, t - y, y))" assert str(Series(-tf2, tf1)) == \ "Series(TransferFunction(-x + y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y))" def test_MIMOSeries_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) assert str(MIMOSeries(tfm_1, tfm_2)) == \ "MIMOSeries(TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), "\ "(TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)))), "\ "TransferFunctionMatrix(((TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)), "\ "(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)))))" def test_TransferFunction_str(): tf1 = TransferFunction(x - 1, x + 1, x) assert str(tf1) == "TransferFunction(x - 1, x + 1, x)" tf2 = TransferFunction(x + 1, 2 - y, x) assert str(tf2) == "TransferFunction(x + 1, 2 - y, x)" tf3 = TransferFunction(y, y**2 + 2*y + 3, y) assert str(tf3) == "TransferFunction(y, y**2 + 2*y + 3, y)" def test_Parallel_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y) assert str(Parallel(tf1, tf2)) == \ "Parallel(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y))" assert str(Parallel(tf1, tf2, tf3)) == \ "Parallel(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y), TransferFunction(t*x**2 - t**w*x + w, t - y, y))" assert str(Parallel(-tf2, tf1)) == \ "Parallel(TransferFunction(-x + y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y))" def test_MIMOParallel_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) assert str(MIMOParallel(tfm_1, tfm_2)) == \ "MIMOParallel(TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), "\ "(TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)))), "\ "TransferFunctionMatrix(((TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)), "\ "(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)))))" def test_Feedback_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y) assert str(Feedback(tf1*tf2, tf3)) == \ "Feedback(Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), " \ "TransferFunction(t*x**2 - t**w*x + w, t - y, y), -1)" assert str(Feedback(tf1, TransferFunction(1, 1, y), 1)) == \ "Feedback(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(1, 1, y), 1)" def test_MIMOFeedback_str(): tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) tfm_1 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) tfm_2 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) assert (str(MIMOFeedback(tfm_1, tfm_2)) \ == "MIMOFeedback(TransferFunctionMatrix(((TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x))," \ " (TransferFunction(x**2 - y**3, y - z, x), TransferFunction(-x + y, y + z, x)))), " \ "TransferFunctionMatrix(((TransferFunction(x**2 - y**3, y - z, x), " \ "TransferFunction(-x + y, y + z, x)), (TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x)))), -1)") assert (str(MIMOFeedback(tfm_1, tfm_2, 1)) \ == "MIMOFeedback(TransferFunctionMatrix(((TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x)), " \ "(TransferFunction(x**2 - y**3, y - z, x), TransferFunction(-x + y, y + z, x)))), " \ "TransferFunctionMatrix(((TransferFunction(x**2 - y**3, y - z, x), TransferFunction(-x + y, y + z, x)), "\ "(TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x)))), 1)") def test_TransferFunctionMatrix_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y) assert str(TransferFunctionMatrix([[tf1], [tf2]])) == \ "TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y),), (TransferFunction(x - y, x + y, y),)))" assert str(TransferFunctionMatrix([[tf1, tf2], [tf3, tf2]])) == \ "TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), (TransferFunction(t*x**2 - t**w*x + w, t - y, y), TransferFunction(x - y, x + y, y))))" def test_Quaternion_str_printer(): q = Quaternion(x, y, z, t) assert str(q) == "x + y*i + z*j + t*k" q = Quaternion(x,y,z,x*t) assert str(q) == "x + y*i + z*j + t*x*k" q = Quaternion(x,y,z,x+t) assert str(q) == "x + y*i + z*j + (t + x)*k" def test_Quantity_str(): assert sstr(second, abbrev=True) == "s" assert sstr(joule, abbrev=True) == "J" assert str(second) == "second" assert str(joule) == "joule" def test_wild_str(): # Check expressions containing Wild not causing infinite recursion w = Wild('x') assert str(w + 1) == 'x_ + 1' assert str(exp(2**w) + 5) == 'exp(2**x_) + 5' assert str(3*w + 1) == '3*x_ + 1' assert str(1/w + 1) == '1 + 1/x_' assert str(w**2 + 1) == 'x_**2 + 1' assert str(1/(1 - w)) == '1/(1 - x_)' def test_wild_matchpy(): from sympy.utilities.matchpy_connector import WildDot, WildPlus, WildStar matchpy = import_module("matchpy") if matchpy is None: return wd = WildDot('w_') wp = WildPlus('w__') ws = WildStar('w___') assert str(wd) == 'w_' assert str(wp) == 'w__' assert str(ws) == 'w___' assert str(wp/ws + 2**wd) == '2**w_ + w__/w___' assert str(sin(wd)*cos(wp)*sqrt(ws)) == 'sqrt(w___)*sin(w_)*cos(w__)' def test_zeta(): assert str(zeta(3)) == "zeta(3)" def test_issue_3101(): e = x - y a = str(e) b = str(e) assert a == b def test_issue_3103(): e = -2*sqrt(x) - y/sqrt(x)/2 assert str(e) not in ["(-2)*x**1/2(-1/2)*x**(-1/2)*y", "-2*x**1/2(-1/2)*x**(-1/2)*y", "-2*x**1/2-1/2*x**-1/2*w"] assert str(e) == "-2*sqrt(x) - y/(2*sqrt(x))" def test_issue_4021(): e = Integral(x, x) + 1 assert str(e) == 'Integral(x, x) + 1' def test_sstrrepr(): assert sstr('abc') == 'abc' assert sstrrepr('abc') == "'abc'" e = ['a', 'b', 'c', x] assert sstr(e) == "[a, b, c, x]" assert sstrrepr(e) == "['a', 'b', 'c', x]" def test_infinity(): assert sstr(oo*I) == "oo*I" def test_full_prec(): assert sstr(S("0.3"), full_prec=True) == "0.300000000000000" assert sstr(S("0.3"), full_prec="auto") == "0.300000000000000" assert sstr(S("0.3"), full_prec=False) == "0.3" assert sstr(S("0.3")*x, full_prec=True) in [ "0.300000000000000*x", "x*0.300000000000000" ] assert sstr(S("0.3")*x, full_prec="auto") in [ "0.3*x", "x*0.3" ] assert sstr(S("0.3")*x, full_prec=False) in [ "0.3*x", "x*0.3" ] def test_noncommutative(): A, B, C = symbols('A,B,C', commutative=False) assert sstr(A*B*C**-1) == "A*B*C**(-1)" assert sstr(C**-1*A*B) == "C**(-1)*A*B" assert sstr(A*C**-1*B) == "A*C**(-1)*B" assert sstr(sqrt(A)) == "sqrt(A)" assert sstr(1/sqrt(A)) == "A**(-1/2)" def test_empty_printer(): str_printer = StrPrinter() assert str_printer.emptyPrinter("foo") == "foo" assert str_printer.emptyPrinter(x*y) == "x*y" assert str_printer.emptyPrinter(32) == "32" def test_settings(): raises(TypeError, lambda: sstr(S(4), method="garbage")) def test_RandomDomain(): from sympy.stats import Normal, Die, Exponential, pspace, where X = Normal('x1', 0, 1) assert str(where(X > 0)) == "Domain: (0 < x1) & (x1 < oo)" D = Die('d1', 6) assert str(where(D > 4)) == "Domain: Eq(d1, 5) | Eq(d1, 6)" A = Exponential('a', 1) B = Exponential('b', 1) assert str(pspace(Tuple(A, B)).domain) == "Domain: (0 <= a) & (0 <= b) & (a < oo) & (b < oo)" def test_FiniteSet(): assert str(FiniteSet(*range(1, 51))) == ( 'FiniteSet(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,' ' 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,' ' 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)' ) assert str(FiniteSet(*range(1, 6))) == 'FiniteSet(1, 2, 3, 4, 5)' def test_UniversalSet(): assert str(S.UniversalSet) == 'UniversalSet' def test_PrettyPoly(): from sympy.polys.domains import QQ F = QQ.frac_field(x, y) R = QQ[x, y] assert sstr(F.convert(x/(x + y))) == sstr(x/(x + y)) assert sstr(R.convert(x + y)) == sstr(x + y) def test_categories(): from sympy.categories import (Object, NamedMorphism, IdentityMorphism, Category) A = Object("A") B = Object("B") f = NamedMorphism(A, B, "f") id_A = IdentityMorphism(A) K = Category("K") assert str(A) == 'Object("A")' assert str(f) == 'NamedMorphism(Object("A"), Object("B"), "f")' assert str(id_A) == 'IdentityMorphism(Object("A"))' assert str(K) == 'Category("K")' def test_Tr(): A, B = symbols('A B', commutative=False) t = Tr(A*B) assert str(t) == 'Tr(A*B)' def test_issue_6387(): assert str(factor(-3.0*z + 3)) == '-3.0*(1.0*z - 1.0)' def test_MatMul_MatAdd(): from sympy import MatrixSymbol X, Y = MatrixSymbol("X", 2, 2), MatrixSymbol("Y", 2, 2) assert str(2*(X + Y)) == "2*X + 2*Y" assert str(I*X) == "I*X" assert str(-I*X) == "-I*X" assert str((1 + I)*X) == '(1 + I)*X' assert str(-(1 + I)*X) == '(-1 - I)*X' def test_MatrixSlice(): n = Symbol('n', integer=True) X = MatrixSymbol('X', n, n) Y = MatrixSymbol('Y', 10, 10) Z = MatrixSymbol('Z', 10, 10) assert str(MatrixSlice(X, (None, None, None), (None, None, None))) == 'X[:, :]' assert str(X[x:x + 1, y:y + 1]) == 'X[x:x + 1, y:y + 1]' assert str(X[x:x + 1:2, y:y + 1:2]) == 'X[x:x + 1:2, y:y + 1:2]' assert str(X[:x, y:]) == 'X[:x, y:]' assert str(X[:x, y:]) == 'X[:x, y:]' assert str(X[x:, :y]) == 'X[x:, :y]' assert str(X[x:y, z:w]) == 'X[x:y, z:w]' assert str(X[x:y:t, w:t:x]) == 'X[x:y:t, w:t:x]' assert str(X[x::y, t::w]) == 'X[x::y, t::w]' assert str(X[:x:y, :t:w]) == 'X[:x:y, :t:w]' assert str(X[::x, ::y]) == 'X[::x, ::y]' assert str(MatrixSlice(X, (0, None, None), (0, None, None))) == 'X[:, :]' assert str(MatrixSlice(X, (None, n, None), (None, n, None))) == 'X[:, :]' assert str(MatrixSlice(X, (0, n, None), (0, n, None))) == 'X[:, :]' assert str(MatrixSlice(X, (0, n, 2), (0, n, 2))) == 'X[::2, ::2]' assert str(X[1:2:3, 4:5:6]) == 'X[1:2:3, 4:5:6]' assert str(X[1:3:5, 4:6:8]) == 'X[1:3:5, 4:6:8]' assert str(X[1:10:2]) == 'X[1:10:2, :]' assert str(Y[:5, 1:9:2]) == 'Y[:5, 1:9:2]' assert str(Y[:5, 1:10:2]) == 'Y[:5, 1::2]' assert str(Y[5, :5:2]) == 'Y[5:6, :5:2]' assert str(X[0:1, 0:1]) == 'X[:1, :1]' assert str(X[0:1:2, 0:1:2]) == 'X[:1:2, :1:2]' assert str((Y + Z)[2:, 2:]) == '(Y + Z)[2:, 2:]' def test_true_false(): assert str(true) == repr(true) == sstr(true) == "True" assert str(false) == repr(false) == sstr(false) == "False" def test_Equivalent(): assert str(Equivalent(y, x)) == "Equivalent(x, y)" def test_Xor(): assert str(Xor(y, x, evaluate=False)) == "x ^ y" def test_Complement(): assert str(Complement(S.Reals, S.Naturals)) == 'Complement(Reals, Naturals)' def test_SymmetricDifference(): assert str(SymmetricDifference(Interval(2, 3), Interval(3, 4),evaluate=False)) == \ 'SymmetricDifference(Interval(2, 3), Interval(3, 4))' def test_UnevaluatedExpr(): a, b = symbols("a b") expr1 = 2*UnevaluatedExpr(a+b) assert str(expr1) == "2*(a + b)" def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert(str(A[0, 0]) == "A[0, 0]") assert(str(3 * A[0, 0]) == "3*A[0, 0]") F = C[0, 0].subs(C, A - B) assert str(F) == "(A - B)[0, 0]" def test_MatrixSymbol_printing(): A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) assert str(A - A*B - B) == "A - A*B - B" assert str(A*B - (A+B)) == "-A + A*B - B" assert str(A**(-1)) == "A**(-1)" assert str(A**3) == "A**3" def test_MatrixExpressions(): n = Symbol('n', integer=True) X = MatrixSymbol('X', n, n) assert str(X) == "X" # Apply function elementwise (`ElementwiseApplyFunc`): expr = (X.T*X).applyfunc(sin) assert str(expr) == 'Lambda(_d, sin(_d)).(X.T*X)' lamda = Lambda(x, 1/x) expr = (n*X).applyfunc(lamda) assert str(expr) == 'Lambda(x, 1/x).(n*X)' def test_Subs_printing(): assert str(Subs(x, (x,), (1,))) == 'Subs(x, x, 1)' assert str(Subs(x + y, (x, y), (1, 2))) == 'Subs(x + y, (x, y), (1, 2))' def test_issue_15716(): e = Integral(factorial(x), (x, -oo, oo)) assert e.as_terms() == ([(e, ((1.0, 0.0), (1,), ()))], [e]) def test_str_special_matrices(): from sympy.matrices import Identity, ZeroMatrix, OneMatrix assert str(Identity(4)) == 'I' assert str(ZeroMatrix(2, 2)) == '0' assert str(OneMatrix(2, 2)) == '1' def test_issue_14567(): assert factorial(Sum(-1, (x, 0, 0))) + y # doesn't raise an error def test_issue_21119_21460(): ss = lambda x: str(S(x, evaluate=False)) assert ss('4/2') == '4/2' assert ss('4/-2') == '4/(-2)' assert ss('-4/2') == '-4/2' assert ss('-4/-2') == '-4/(-2)' assert ss('-2*3/-1') == '-2*3/(-1)' assert ss('-2*3/-1/2') == '-2*3/(-1*2)' assert ss('4/2/1') == '4/(2*1)' assert ss('-2/-1/2') == '-2/(-1*2)' assert ss('2*3*4**(-2*3)') == '2*3/4**(2*3)' assert ss('2*3*1*4**(-2*3)') == '2*3*1/4**(2*3)' def test_Str(): from sympy.core.symbol import Str assert str(Str('x')) == 'x' assert sstrrepr(Str('x')) == "Str('x')" def test_diffgeom(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField x,y = symbols('x y', real=True) m = Manifold('M', 2) assert str(m) == "M" p = Patch('P', m) assert str(p) == "P" rect = CoordSystem('rect', p, [x, y]) assert str(rect) == "rect" b = BaseScalarField(rect, 0) assert str(b) == "x" def test_NDimArray(): assert sstr(NDimArray(1.0), full_prec=True) == '1.00000000000000' assert sstr(NDimArray(1.0), full_prec=False) == '1.0' assert sstr(NDimArray([1.0, 2.0]), full_prec=True) == '[1.00000000000000, 2.00000000000000]' assert sstr(NDimArray([1.0, 2.0]), full_prec=False) == '[1.0, 2.0]' def test_Predicate(): assert sstr(Q.even) == 'Q.even' def test_AppliedPredicate(): assert sstr(Q.even(x)) == 'Q.even(x)' def test_printing_str_array_expressions(): assert sstr(ArraySymbol("A", 2, 3, 4)) == "A" assert sstr(ArrayElement("A", (2, 1/(1-x), 0))) == "A[2, 1/(1 - x), 0]"
5a2e4ff62c71a016167c99e1fd4738ba5e422cf307a40f2ea06566a9b027e941
from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayElement from sympy.tensor.toperators import PartialDerivative from sympy import ( Abs, Chi, Ci, CosineTransform, Dict, Ei, Eq, FallingFactorial, FiniteSet, Float, FourierTransform, Function, Indexed, IndexedBase, Integral, Interval, InverseCosineTransform, InverseFourierTransform, Derivative, InverseLaplaceTransform, InverseMellinTransform, InverseSineTransform, Lambda, LaplaceTransform, Limit, Matrix, Max, MellinTransform, Min, Mul, Order, Piecewise, Poly, ring, field, ZZ, Pow, Product, Range, Rational, Integer, RisingFactorial, rootof, RootSum, S, Shi, Si, SineTransform, Subs, Sum, Symbol, ImageSet, Tuple, Ynm, Znm, arg, asin, acsc, asinh, Mod, assoc_laguerre, assoc_legendre, beta, binomial, catalan, ceiling, chebyshevt, chebyshevu, conjugate, cot, coth, diff, dirichlet_eta, euler, exp, expint, factorial, factorial2, floor, gamma, gegenbauer, hermite, hyper, im, jacobi, laguerre, legendre, lerchphi, log, frac, meijerg, oo, polar_lift, polylog, re, root, sin, sqrt, symbols, uppergamma, zeta, subfactorial, totient, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, cos, tan, Wild, true, false, Equivalent, Not, Contains, divisor_sigma, SeqPer, SeqFormula, MatrixSlice, SeqAdd, SeqMul, fourier_series, pi, ConditionSet, ComplexRegion, fps, AccumBounds, reduced_totient, primenu, primeomega, SingularityFunction, stieltjes, mathieuc, mathieus, mathieucprime, mathieusprime, UnevaluatedExpr, Quaternion, I, KroneckerProduct, LambertW) from sympy.ntheory.factor_ import udivisor_sigma from sympy.abc import mu, tau from sympy.printing.latex import (latex, translate, greek_letters_set, tex_greek_dictionary, multiline_latex, latex_escape, LatexPrinter) from sympy.tensor.array import (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableSparseNDimArray, MutableDenseNDimArray, tensorproduct) from sympy.testing.pytest import XFAIL, raises, _both_exp_pow from sympy.functions import DiracDelta, Heaviside, KroneckerDelta, LeviCivita from sympy.functions.combinatorial.numbers import bernoulli, bell, lucas, \ fibonacci, tribonacci from sympy.logic import Implies from sympy.logic.boolalg import And, Or, Xor from sympy.physics.control.lti import TransferFunction, Series, Parallel, \ Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback from sympy.physics.quantum import Commutator, Operator from sympy.physics.units import meter, gibibyte, microgram, second from sympy.core.trace import Tr from sympy.combinatorics.permutations import \ Cycle, Permutation, AppliedPermutation from sympy.matrices.expressions.permutation import PermutationMatrix from sympy import MatrixSymbol, ln from sympy.vector import CoordSys3D, Cross, Curl, Dot, Divergence, Gradient, Laplacian from sympy.sets.setexpr import SetExpr from sympy.sets.sets import \ Union, Intersection, Complement, SymmetricDifference, ProductSet import sympy as sym class lowergamma(sym.lowergamma): pass # testing notation inheritance by a subclass with same name x, y, z, t, w, a, b, c, s, p = symbols('x y z t w a b c s p') k, m, n = symbols('k m n', integer=True) def test_printmethod(): class R(Abs): def _latex(self, printer): return "foo(%s)" % printer._print(self.args[0]) assert latex(R(x)) == r"foo(x)" class R(Abs): def _latex(self, printer): return "foo" assert latex(R(x)) == r"foo" def test_latex_basic(): assert latex(1 + x) == r"x + 1" assert latex(x**2) == r"x^{2}" assert latex(x**(1 + x)) == r"x^{x + 1}" assert latex(x**3 + x + 1 + x**2) == r"x^{3} + x^{2} + x + 1" assert latex(2*x*y) == r"2 x y" assert latex(2*x*y, mul_symbol='dot') == r"2 \cdot x \cdot y" assert latex(3*x**2*y, mul_symbol='\\,') == r"3\,x^{2}\,y" assert latex(1.5*3**x, mul_symbol='\\,') == r"1.5 \cdot 3^{x}" assert latex(Mul(0, 1, evaluate=False)) == r'0 \cdot 1' assert latex(Mul(1, 0, evaluate=False)) == r'1 \cdot 0' assert latex(Mul(1, 1, evaluate=False)) == r'1 \cdot 1' assert latex(Mul(-1, 1, evaluate=False)) == r'\left(-1\right) 1' assert latex(Mul(1, 1, 1, evaluate=False)) == r'1 \cdot 1 \cdot 1' assert latex(Mul(1, 2, evaluate=False)) == r'1 \cdot 2' assert latex(Mul(1, S.Half, evaluate=False)) == r'1 \frac{1}{2}' assert latex(Mul(1, 1, S.Half, evaluate=False)) == \ r'1 \cdot 1 \frac{1}{2}' assert latex(Mul(1, 1, 2, 3, x, evaluate=False)) == \ r'1 \cdot 1 \cdot 2 \cdot 3 x' assert latex(Mul(1, -1, evaluate=False)) == r'1 \left(-1\right)' assert latex(Mul(4, 3, 2, 1, 0, y, x, evaluate=False)) == \ r'4 \cdot 3 \cdot 2 \cdot 1 \cdot 0 y x' assert latex(Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)) == \ r'4 \cdot 3 \cdot 2 \left(z + 1\right) 0 y x' assert latex(Mul(Rational(2, 3), Rational(5, 7), evaluate=False)) == \ r'\frac{2}{3} \frac{5}{7}' assert latex(1/x) == r"\frac{1}{x}" assert latex(1/x, fold_short_frac=True) == r"1 / x" assert latex(-S(3)/2) == r"- \frac{3}{2}" assert latex(-S(3)/2, fold_short_frac=True) == r"- 3 / 2" assert latex(1/x**2) == r"\frac{1}{x^{2}}" assert latex(1/(x + y)/2) == r"\frac{1}{2 \left(x + y\right)}" assert latex(x/2) == r"\frac{x}{2}" assert latex(x/2, fold_short_frac=True) == r"x / 2" assert latex((x + y)/(2*x)) == r"\frac{x + y}{2 x}" assert latex((x + y)/(2*x), fold_short_frac=True) == \ r"\left(x + y\right) / 2 x" assert latex((x + y)/(2*x), long_frac_ratio=0) == \ r"\frac{1}{2 x} \left(x + y\right)" assert latex((x + y)/x) == r"\frac{x + y}{x}" assert latex((x + y)/x, long_frac_ratio=3) == r"\frac{x + y}{x}" assert latex((2*sqrt(2)*x)/3) == r"\frac{2 \sqrt{2} x}{3}" assert latex((2*sqrt(2)*x)/3, long_frac_ratio=2) == \ r"\frac{2 x}{3} \sqrt{2}" assert latex(binomial(x, y)) == r"{\binom{x}{y}}" x_star = Symbol('x^*') f = Function('f') assert latex(x_star**2) == r"\left(x^{*}\right)^{2}" assert latex(x_star**2, parenthesize_super=False) == r"{x^{*}}^{2}" assert latex(Derivative(f(x_star), x_star,2)) == r"\frac{d^{2}}{d \left(x^{*}\right)^{2}} f{\left(x^{*} \right)}" assert latex(Derivative(f(x_star), x_star,2), parenthesize_super=False) == r"\frac{d^{2}}{d {x^{*}}^{2}} f{\left(x^{*} \right)}" assert latex(2*Integral(x, x)/3) == r"\frac{2 \int x\, dx}{3}" assert latex(2*Integral(x, x)/3, fold_short_frac=True) == \ r"\left(2 \int x\, dx\right) / 3" assert latex(sqrt(x)) == r"\sqrt{x}" assert latex(x**Rational(1, 3)) == r"\sqrt[3]{x}" assert latex(x**Rational(1, 3), root_notation=False) == r"x^{\frac{1}{3}}" assert latex(sqrt(x)**3) == r"x^{\frac{3}{2}}" assert latex(sqrt(x), itex=True) == r"\sqrt{x}" assert latex(x**Rational(1, 3), itex=True) == r"\root{3}{x}" assert latex(sqrt(x)**3, itex=True) == r"x^{\frac{3}{2}}" assert latex(x**Rational(3, 4)) == r"x^{\frac{3}{4}}" assert latex(x**Rational(3, 4), fold_frac_powers=True) == r"x^{3/4}" assert latex((x + 1)**Rational(3, 4)) == \ r"\left(x + 1\right)^{\frac{3}{4}}" assert latex((x + 1)**Rational(3, 4), fold_frac_powers=True) == \ r"\left(x + 1\right)^{3/4}" assert latex(1.5e20*x) == r"1.5 \cdot 10^{20} x" assert latex(1.5e20*x, mul_symbol='dot') == r"1.5 \cdot 10^{20} \cdot x" assert latex(1.5e20*x, mul_symbol='times') == \ r"1.5 \times 10^{20} \times x" assert latex(1/sin(x)) == r"\frac{1}{\sin{\left(x \right)}}" assert latex(sin(x)**-1) == r"\frac{1}{\sin{\left(x \right)}}" assert latex(sin(x)**Rational(3, 2)) == \ r"\sin^{\frac{3}{2}}{\left(x \right)}" assert latex(sin(x)**Rational(3, 2), fold_frac_powers=True) == \ r"\sin^{3/2}{\left(x \right)}" assert latex(~x) == r"\neg x" assert latex(x & y) == r"x \wedge y" assert latex(x & y & z) == r"x \wedge y \wedge z" assert latex(x | y) == r"x \vee y" assert latex(x | y | z) == r"x \vee y \vee z" assert latex((x & y) | z) == r"z \vee \left(x \wedge y\right)" assert latex(Implies(x, y)) == r"x \Rightarrow y" assert latex(~(x >> ~y)) == r"x \not\Rightarrow \neg y" assert latex(Implies(Or(x,y), z)) == r"\left(x \vee y\right) \Rightarrow z" assert latex(Implies(z, Or(x,y))) == r"z \Rightarrow \left(x \vee y\right)" assert latex(~(x & y)) == r"\neg \left(x \wedge y\right)" assert latex(~x, symbol_names={x: "x_i"}) == r"\neg x_i" assert latex(x & y, symbol_names={x: "x_i", y: "y_i"}) == \ r"x_i \wedge y_i" assert latex(x & y & z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \ r"x_i \wedge y_i \wedge z_i" assert latex(x | y, symbol_names={x: "x_i", y: "y_i"}) == r"x_i \vee y_i" assert latex(x | y | z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \ r"x_i \vee y_i \vee z_i" assert latex((x & y) | z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \ r"z_i \vee \left(x_i \wedge y_i\right)" assert latex(Implies(x, y), symbol_names={x: "x_i", y: "y_i"}) == \ r"x_i \Rightarrow y_i" assert latex(Pow(Rational(1, 3), -1, evaluate=False)) == r"\frac{1}{\frac{1}{3}}" assert latex(Pow(Rational(1, 3), -2, evaluate=False)) == r"\frac{1}{(\frac{1}{3})^{2}}" assert latex(Pow(Integer(1)/100, -1, evaluate=False)) == r"\frac{1}{\frac{1}{100}}" p = Symbol('p', positive=True) assert latex(exp(-p)*log(p)) == r"e^{- p} \log{\left(p \right)}" def test_latex_builtins(): assert latex(True) == r"\text{True}" assert latex(False) == r"\text{False}" assert latex(None) == r"\text{None}" assert latex(true) == r"\text{True}" assert latex(false) == r'\text{False}' def test_latex_SingularityFunction(): assert latex(SingularityFunction(x, 4, 5)) == \ r"{\left\langle x - 4 \right\rangle}^{5}" assert latex(SingularityFunction(x, -3, 4)) == \ r"{\left\langle x + 3 \right\rangle}^{4}" assert latex(SingularityFunction(x, 0, 4)) == \ r"{\left\langle x \right\rangle}^{4}" assert latex(SingularityFunction(x, a, n)) == \ r"{\left\langle - a + x \right\rangle}^{n}" assert latex(SingularityFunction(x, 4, -2)) == \ r"{\left\langle x - 4 \right\rangle}^{-2}" assert latex(SingularityFunction(x, 4, -1)) == \ r"{\left\langle x - 4 \right\rangle}^{-1}" assert latex(SingularityFunction(x, 4, 5)**3) == \ r"{\left({\langle x - 4 \rangle}^{5}\right)}^{3}" assert latex(SingularityFunction(x, -3, 4)**3) == \ r"{\left({\langle x + 3 \rangle}^{4}\right)}^{3}" assert latex(SingularityFunction(x, 0, 4)**3) == \ r"{\left({\langle x \rangle}^{4}\right)}^{3}" assert latex(SingularityFunction(x, a, n)**3) == \ r"{\left({\langle - a + x \rangle}^{n}\right)}^{3}" assert latex(SingularityFunction(x, 4, -2)**3) == \ r"{\left({\langle x - 4 \rangle}^{-2}\right)}^{3}" assert latex((SingularityFunction(x, 4, -1)**3)**3) == \ r"{\left({\langle x - 4 \rangle}^{-1}\right)}^{9}" def test_latex_cycle(): assert latex(Cycle(1, 2, 4)) == r"\left( 1\; 2\; 4\right)" assert latex(Cycle(1, 2)(4, 5, 6)) == \ r"\left( 1\; 2\right)\left( 4\; 5\; 6\right)" assert latex(Cycle()) == r"\left( \right)" def test_latex_permutation(): assert latex(Permutation(1, 2, 4)) == r"\left( 1\; 2\; 4\right)" assert latex(Permutation(1, 2)(4, 5, 6)) == \ r"\left( 1\; 2\right)\left( 4\; 5\; 6\right)" assert latex(Permutation()) == r"\left( \right)" assert latex(Permutation(2, 4)*Permutation(5)) == \ r"\left( 2\; 4\right)\left( 5\right)" assert latex(Permutation(5)) == r"\left( 5\right)" assert latex(Permutation(0, 1), perm_cyclic=False) == \ r"\begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}" assert latex(Permutation(0, 1)(2, 3), perm_cyclic=False) == \ r"\begin{pmatrix} 0 & 1 & 2 & 3 \\ 1 & 0 & 3 & 2 \end{pmatrix}" assert latex(Permutation(), perm_cyclic=False) == \ r"\left( \right)" def test_latex_Float(): assert latex(Float(1.0e100)) == r"1.0 \cdot 10^{100}" assert latex(Float(1.0e-100)) == r"1.0 \cdot 10^{-100}" assert latex(Float(1.0e-100), mul_symbol="times") == \ r"1.0 \times 10^{-100}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=2) == \ r"1.0 \cdot 10^{4}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=4) == \ r"1.0 \cdot 10^{4}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=5) == \ r"10000.0" assert latex(Float('0.099999'), full_prec=True, min=-2, max=5) == \ r"9.99990000000000 \cdot 10^{-2}" def test_latex_vector_expressions(): A = CoordSys3D('A') assert latex(Cross(A.i, A.j*A.x*3+A.k)) == \ r"\mathbf{\hat{i}_{A}} \times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)" assert latex(Cross(A.i, A.j)) == \ r"\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}" assert latex(x*Cross(A.i, A.j)) == \ r"x \left(\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}\right)" assert latex(Cross(x*A.i, A.j)) == \ r'- \mathbf{\hat{j}_{A}} \times \left((x)\mathbf{\hat{i}_{A}}\right)' assert latex(Curl(3*A.x*A.j)) == \ r"\nabla\times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(Curl(3*A.x*A.j+A.i)) == \ r"\nabla\times \left(\mathbf{\hat{i}_{A}} + (3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(Curl(3*x*A.x*A.j)) == \ r"\nabla\times \left((3 \mathbf{{x}_{A}} x)\mathbf{\hat{j}_{A}}\right)" assert latex(x*Curl(3*A.x*A.j)) == \ r"x \left(\nabla\times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)\right)" assert latex(Divergence(3*A.x*A.j+A.i)) == \ r"\nabla\cdot \left(\mathbf{\hat{i}_{A}} + (3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(Divergence(3*A.x*A.j)) == \ r"\nabla\cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(x*Divergence(3*A.x*A.j)) == \ r"x \left(\nabla\cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)\right)" assert latex(Dot(A.i, A.j*A.x*3+A.k)) == \ r"\mathbf{\hat{i}_{A}} \cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)" assert latex(Dot(A.i, A.j)) == \ r"\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}" assert latex(Dot(x*A.i, A.j)) == \ r"\mathbf{\hat{j}_{A}} \cdot \left((x)\mathbf{\hat{i}_{A}}\right)" assert latex(x*Dot(A.i, A.j)) == \ r"x \left(\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}\right)" assert latex(Gradient(A.x)) == r"\nabla \mathbf{{x}_{A}}" assert latex(Gradient(A.x + 3*A.y)) == \ r"\nabla \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)" assert latex(x*Gradient(A.x)) == r"x \left(\nabla \mathbf{{x}_{A}}\right)" assert latex(Gradient(x*A.x)) == r"\nabla \left(\mathbf{{x}_{A}} x\right)" assert latex(Laplacian(A.x)) == r"\triangle \mathbf{{x}_{A}}" assert latex(Laplacian(A.x + 3*A.y)) == \ r"\triangle \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)" assert latex(x*Laplacian(A.x)) == r"x \left(\triangle \mathbf{{x}_{A}}\right)" assert latex(Laplacian(x*A.x)) == r"\triangle \left(\mathbf{{x}_{A}} x\right)" def test_latex_symbols(): Gamma, lmbda, rho = symbols('Gamma, lambda, rho') tau, Tau, TAU, taU = symbols('tau, Tau, TAU, taU') assert latex(tau) == r"\tau" assert latex(Tau) == r"T" assert latex(TAU) == r"\tau" assert latex(taU) == r"\tau" # Check that all capitalized greek letters are handled explicitly capitalized_letters = {l.capitalize() for l in greek_letters_set} assert len(capitalized_letters - set(tex_greek_dictionary.keys())) == 0 assert latex(Gamma + lmbda) == r"\Gamma + \lambda" assert latex(Gamma * lmbda) == r"\Gamma \lambda" assert latex(Symbol('q1')) == r"q_{1}" assert latex(Symbol('q21')) == r"q_{21}" assert latex(Symbol('epsilon0')) == r"\epsilon_{0}" assert latex(Symbol('omega1')) == r"\omega_{1}" assert latex(Symbol('91')) == r"91" assert latex(Symbol('alpha_new')) == r"\alpha_{new}" assert latex(Symbol('C^orig')) == r"C^{orig}" assert latex(Symbol('x^alpha')) == r"x^{\alpha}" assert latex(Symbol('beta^alpha')) == r"\beta^{\alpha}" assert latex(Symbol('e^Alpha')) == r"e^{A}" assert latex(Symbol('omega_alpha^beta')) == r"\omega^{\beta}_{\alpha}" assert latex(Symbol('omega') ** Symbol('beta')) == r"\omega^{\beta}" @XFAIL def test_latex_symbols_failing(): rho, mass, volume = symbols('rho, mass, volume') assert latex( volume * rho == mass) == r"\rho \mathrm{volume} = \mathrm{mass}" assert latex(volume / mass * rho == 1) == \ r"\rho \mathrm{volume} {\mathrm{mass}}^{(-1)} = 1" assert latex(mass**3 * volume**3) == \ r"{\mathrm{mass}}^{3} \cdot {\mathrm{volume}}^{3}" @_both_exp_pow def test_latex_functions(): assert latex(exp(x)) == r"e^{x}" assert latex(exp(1) + exp(2)) == r"e + e^{2}" f = Function('f') assert latex(f(x)) == r'f{\left(x \right)}' assert latex(f) == r'f' g = Function('g') assert latex(g(x, y)) == r'g{\left(x,y \right)}' assert latex(g) == r'g' h = Function('h') assert latex(h(x, y, z)) == r'h{\left(x,y,z \right)}' assert latex(h) == r'h' Li = Function('Li') assert latex(Li) == r'\operatorname{Li}' assert latex(Li(x)) == r'\operatorname{Li}{\left(x \right)}' mybeta = Function('beta') # not to be confused with the beta function assert latex(mybeta(x, y, z)) == r"\beta{\left(x,y,z \right)}" assert latex(beta(x, y)) == r'\operatorname{B}\left(x, y\right)' assert latex(beta(x, y)**2) == r'\operatorname{B}^{2}\left(x, y\right)' assert latex(mybeta(x)) == r"\beta{\left(x \right)}" assert latex(mybeta) == r"\beta" g = Function('gamma') # not to be confused with the gamma function assert latex(g(x, y, z)) == r"\gamma{\left(x,y,z \right)}" assert latex(g(x)) == r"\gamma{\left(x \right)}" assert latex(g) == r"\gamma" a1 = Function('a_1') assert latex(a1) == r"\operatorname{a_{1}}" assert latex(a1(x)) == r"\operatorname{a_{1}}{\left(x \right)}" # issue 5868 omega1 = Function('omega1') assert latex(omega1) == r"\omega_{1}" assert latex(omega1(x)) == r"\omega_{1}{\left(x \right)}" assert latex(sin(x)) == r"\sin{\left(x \right)}" assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}" assert latex(sin(2*x**2), fold_func_brackets=True) == \ r"\sin {2 x^{2}}" assert latex(sin(x**2), fold_func_brackets=True) == \ r"\sin {x^{2}}" assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left(x \right)}" assert latex(asin(x)**2, inv_trig_style="full") == \ r"\arcsin^{2}{\left(x \right)}" assert latex(asin(x)**2, inv_trig_style="power") == \ r"\sin^{-1}{\left(x \right)}^{2}" assert latex(asin(x**2), inv_trig_style="power", fold_func_brackets=True) == \ r"\sin^{-1} {x^{2}}" assert latex(acsc(x), inv_trig_style="full") == \ r"\operatorname{arccsc}{\left(x \right)}" assert latex(asinh(x), inv_trig_style="full") == \ r"\operatorname{arcsinh}{\left(x \right)}" assert latex(factorial(k)) == r"k!" assert latex(factorial(-k)) == r"\left(- k\right)!" assert latex(factorial(k)**2) == r"k!^{2}" assert latex(subfactorial(k)) == r"!k" assert latex(subfactorial(-k)) == r"!\left(- k\right)" assert latex(subfactorial(k)**2) == r"\left(!k\right)^{2}" assert latex(factorial2(k)) == r"k!!" assert latex(factorial2(-k)) == r"\left(- k\right)!!" assert latex(factorial2(k)**2) == r"k!!^{2}" assert latex(binomial(2, k)) == r"{\binom{2}{k}}" assert latex(binomial(2, k)**2) == r"{\binom{2}{k}}^{2}" assert latex(FallingFactorial(3, k)) == r"{\left(3\right)}_{k}" assert latex(RisingFactorial(3, k)) == r"{3}^{\left(k\right)}" assert latex(floor(x)) == r"\left\lfloor{x}\right\rfloor" assert latex(ceiling(x)) == r"\left\lceil{x}\right\rceil" assert latex(frac(x)) == r"\operatorname{frac}{\left(x\right)}" assert latex(floor(x)**2) == r"\left\lfloor{x}\right\rfloor^{2}" assert latex(ceiling(x)**2) == r"\left\lceil{x}\right\rceil^{2}" assert latex(frac(x)**2) == r"\operatorname{frac}{\left(x\right)}^{2}" assert latex(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)" assert latex(Min(x, y)**2) == r"\min\left(x, y\right)^{2}" assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)" assert latex(Max(x, y)**2) == r"\max\left(x, y\right)^{2}" assert latex(Abs(x)) == r"\left|{x}\right|" assert latex(Abs(x)**2) == r"\left|{x}\right|^{2}" assert latex(re(x)) == r"\operatorname{re}{\left(x\right)}" assert latex(re(x + y)) == \ r"\operatorname{re}{\left(x\right)} + \operatorname{re}{\left(y\right)}" assert latex(im(x)) == r"\operatorname{im}{\left(x\right)}" assert latex(conjugate(x)) == r"\overline{x}" assert latex(conjugate(x)**2) == r"\overline{x}^{2}" assert latex(conjugate(x**2)) == r"\overline{x}^{2}" assert latex(gamma(x)) == r"\Gamma\left(x\right)" w = Wild('w') assert latex(gamma(w)) == r"\Gamma\left(w\right)" assert latex(Order(x)) == r"O\left(x\right)" assert latex(Order(x, x)) == r"O\left(x\right)" assert latex(Order(x, (x, 0))) == r"O\left(x\right)" assert latex(Order(x, (x, oo))) == r"O\left(x; x\rightarrow \infty\right)" assert latex(Order(x - y, (x, y))) == \ r"O\left(x - y; x\rightarrow y\right)" assert latex(Order(x, x, y)) == \ r"O\left(x; \left( x, \ y\right)\rightarrow \left( 0, \ 0\right)\right)" assert latex(Order(x, x, y)) == \ r"O\left(x; \left( x, \ y\right)\rightarrow \left( 0, \ 0\right)\right)" assert latex(Order(x, (x, oo), (y, oo))) == \ r"O\left(x; \left( x, \ y\right)\rightarrow \left( \infty, \ \infty\right)\right)" assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)' assert latex(lowergamma(x, y)**2) == r'\gamma^{2}\left(x, y\right)' assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)' assert latex(uppergamma(x, y)**2) == r'\Gamma^{2}\left(x, y\right)' assert latex(cot(x)) == r'\cot{\left(x \right)}' assert latex(coth(x)) == r'\coth{\left(x \right)}' assert latex(re(x)) == r'\operatorname{re}{\left(x\right)}' assert latex(im(x)) == r'\operatorname{im}{\left(x\right)}' assert latex(root(x, y)) == r'x^{\frac{1}{y}}' assert latex(arg(x)) == r'\arg{\left(x \right)}' assert latex(zeta(x)) == r"\zeta\left(x\right)" assert latex(zeta(x)**2) == r"\zeta^{2}\left(x\right)" assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)" assert latex(zeta(x, y)**2) == r"\zeta^{2}\left(x, y\right)" assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)" assert latex(dirichlet_eta(x)**2) == r"\eta^{2}\left(x\right)" assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)" assert latex( polylog(x, y)**2) == r"\operatorname{Li}_{x}^{2}\left(y\right)" assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)" assert latex(lerchphi(x, y, n)**2) == r"\Phi^{2}\left(x, y, n\right)" assert latex(stieltjes(x)) == r"\gamma_{x}" assert latex(stieltjes(x)**2) == r"\gamma_{x}^{2}" assert latex(stieltjes(x, y)) == r"\gamma_{x}\left(y\right)" assert latex(stieltjes(x, y)**2) == r"\gamma_{x}\left(y\right)^{2}" assert latex(elliptic_k(z)) == r"K\left(z\right)" assert latex(elliptic_k(z)**2) == r"K^{2}\left(z\right)" assert latex(elliptic_f(x, y)) == r"F\left(x\middle| y\right)" assert latex(elliptic_f(x, y)**2) == r"F^{2}\left(x\middle| y\right)" assert latex(elliptic_e(x, y)) == r"E\left(x\middle| y\right)" assert latex(elliptic_e(x, y)**2) == r"E^{2}\left(x\middle| y\right)" assert latex(elliptic_e(z)) == r"E\left(z\right)" assert latex(elliptic_e(z)**2) == r"E^{2}\left(z\right)" assert latex(elliptic_pi(x, y, z)) == r"\Pi\left(x; y\middle| z\right)" assert latex(elliptic_pi(x, y, z)**2) == \ r"\Pi^{2}\left(x; y\middle| z\right)" assert latex(elliptic_pi(x, y)) == r"\Pi\left(x\middle| y\right)" assert latex(elliptic_pi(x, y)**2) == r"\Pi^{2}\left(x\middle| y\right)" assert latex(Ei(x)) == r'\operatorname{Ei}{\left(x \right)}' assert latex(Ei(x)**2) == r'\operatorname{Ei}^{2}{\left(x \right)}' assert latex(expint(x, y)) == r'\operatorname{E}_{x}\left(y\right)' assert latex(expint(x, y)**2) == r'\operatorname{E}_{x}^{2}\left(y\right)' assert latex(Shi(x)**2) == r'\operatorname{Shi}^{2}{\left(x \right)}' assert latex(Si(x)**2) == r'\operatorname{Si}^{2}{\left(x \right)}' assert latex(Ci(x)**2) == r'\operatorname{Ci}^{2}{\left(x \right)}' assert latex(Chi(x)**2) == r'\operatorname{Chi}^{2}\left(x\right)' assert latex(Chi(x)) == r'\operatorname{Chi}\left(x\right)' assert latex(jacobi(n, a, b, x)) == \ r'P_{n}^{\left(a,b\right)}\left(x\right)' assert latex(jacobi(n, a, b, x)**2) == \ r'\left(P_{n}^{\left(a,b\right)}\left(x\right)\right)^{2}' assert latex(gegenbauer(n, a, x)) == \ r'C_{n}^{\left(a\right)}\left(x\right)' assert latex(gegenbauer(n, a, x)**2) == \ r'\left(C_{n}^{\left(a\right)}\left(x\right)\right)^{2}' assert latex(chebyshevt(n, x)) == r'T_{n}\left(x\right)' assert latex(chebyshevt(n, x)**2) == \ r'\left(T_{n}\left(x\right)\right)^{2}' assert latex(chebyshevu(n, x)) == r'U_{n}\left(x\right)' assert latex(chebyshevu(n, x)**2) == \ r'\left(U_{n}\left(x\right)\right)^{2}' assert latex(legendre(n, x)) == r'P_{n}\left(x\right)' assert latex(legendre(n, x)**2) == r'\left(P_{n}\left(x\right)\right)^{2}' assert latex(assoc_legendre(n, a, x)) == \ r'P_{n}^{\left(a\right)}\left(x\right)' assert latex(assoc_legendre(n, a, x)**2) == \ r'\left(P_{n}^{\left(a\right)}\left(x\right)\right)^{2}' assert latex(laguerre(n, x)) == r'L_{n}\left(x\right)' assert latex(laguerre(n, x)**2) == r'\left(L_{n}\left(x\right)\right)^{2}' assert latex(assoc_laguerre(n, a, x)) == \ r'L_{n}^{\left(a\right)}\left(x\right)' assert latex(assoc_laguerre(n, a, x)**2) == \ r'\left(L_{n}^{\left(a\right)}\left(x\right)\right)^{2}' assert latex(hermite(n, x)) == r'H_{n}\left(x\right)' assert latex(hermite(n, x)**2) == r'\left(H_{n}\left(x\right)\right)^{2}' theta = Symbol("theta", real=True) phi = Symbol("phi", real=True) assert latex(Ynm(n, m, theta, phi)) == r'Y_{n}^{m}\left(\theta,\phi\right)' assert latex(Ynm(n, m, theta, phi)**3) == \ r'\left(Y_{n}^{m}\left(\theta,\phi\right)\right)^{3}' assert latex(Znm(n, m, theta, phi)) == r'Z_{n}^{m}\left(\theta,\phi\right)' assert latex(Znm(n, m, theta, phi)**3) == \ r'\left(Z_{n}^{m}\left(\theta,\phi\right)\right)^{3}' # Test latex printing of function names with "_" assert latex(polar_lift(0)) == \ r"\operatorname{polar\_lift}{\left(0 \right)}" assert latex(polar_lift(0)**3) == \ r"\operatorname{polar\_lift}^{3}{\left(0 \right)}" assert latex(totient(n)) == r'\phi\left(n\right)' assert latex(totient(n) ** 2) == r'\left(\phi\left(n\right)\right)^{2}' assert latex(reduced_totient(n)) == r'\lambda\left(n\right)' assert latex(reduced_totient(n) ** 2) == \ r'\left(\lambda\left(n\right)\right)^{2}' assert latex(divisor_sigma(x)) == r"\sigma\left(x\right)" assert latex(divisor_sigma(x)**2) == r"\sigma^{2}\left(x\right)" assert latex(divisor_sigma(x, y)) == r"\sigma_y\left(x\right)" assert latex(divisor_sigma(x, y)**2) == r"\sigma^{2}_y\left(x\right)" assert latex(udivisor_sigma(x)) == r"\sigma^*\left(x\right)" assert latex(udivisor_sigma(x)**2) == r"\sigma^*^{2}\left(x\right)" assert latex(udivisor_sigma(x, y)) == r"\sigma^*_y\left(x\right)" assert latex(udivisor_sigma(x, y)**2) == r"\sigma^*^{2}_y\left(x\right)" assert latex(primenu(n)) == r'\nu\left(n\right)' assert latex(primenu(n) ** 2) == r'\left(\nu\left(n\right)\right)^{2}' assert latex(primeomega(n)) == r'\Omega\left(n\right)' assert latex(primeomega(n) ** 2) == \ r'\left(\Omega\left(n\right)\right)^{2}' assert latex(LambertW(n)) == r'W\left(n\right)' assert latex(LambertW(n, -1)) == r'W_{-1}\left(n\right)' assert latex(LambertW(n, k)) == r'W_{k}\left(n\right)' assert latex(LambertW(n) * LambertW(n)) == r"W^{2}\left(n\right)" assert latex(Pow(LambertW(n), 2)) == r"W^{2}\left(n\right)" assert latex(LambertW(n)**k) == r"W^{k}\left(n\right)" assert latex(LambertW(n, k)**p) == r"W^{p}_{k}\left(n\right)" assert latex(Mod(x, 7)) == r'x\bmod{7}' assert latex(Mod(x + 1, 7)) == r'\left(x + 1\right)\bmod{7}' assert latex(Mod(2 * x, 7)) == r'2 x\bmod{7}' assert latex(Mod(x, 7) + 1) == r'\left(x\bmod{7}\right) + 1' assert latex(2 * Mod(x, 7)) == r'2 \left(x\bmod{7}\right)' # some unknown function name should get rendered with \operatorname fjlkd = Function('fjlkd') assert latex(fjlkd(x)) == r'\operatorname{fjlkd}{\left(x \right)}' # even when it is referred to without an argument assert latex(fjlkd) == r'\operatorname{fjlkd}' # test that notation passes to subclasses of the same name only def test_function_subclass_different_name(): class mygamma(gamma): pass assert latex(mygamma) == r"\operatorname{mygamma}" assert latex(mygamma(x)) == r"\operatorname{mygamma}{\left(x \right)}" def test_hyper_printing(): from sympy import pi from sympy.abc import x, z assert latex(meijerg(Tuple(pi, pi, x), Tuple(1), (0, 1), Tuple(1, 2, 3/pi), z)) == \ r'{G_{4, 5}^{2, 3}\left(\begin{matrix} \pi, \pi, x & 1 \\0, 1 & 1, 2, '\ r'\frac{3}{\pi} \end{matrix} \middle| {z} \right)}' assert latex(meijerg(Tuple(), Tuple(1), (0,), Tuple(), z)) == \ r'{G_{1, 1}^{1, 0}\left(\begin{matrix} & 1 \\0 & \end{matrix} \middle| {z} \right)}' assert latex(hyper((x, 2), (3,), z)) == \ r'{{}_{2}F_{1}\left(\begin{matrix} x, 2 ' \ r'\\ 3 \end{matrix}\middle| {z} \right)}' assert latex(hyper(Tuple(), Tuple(1), z)) == \ r'{{}_{0}F_{1}\left(\begin{matrix} ' \ r'\\ 1 \end{matrix}\middle| {z} \right)}' def test_latex_bessel(): from sympy.functions.special.bessel import (besselj, bessely, besseli, besselk, hankel1, hankel2, jn, yn, hn1, hn2) from sympy.abc import z assert latex(besselj(n, z**2)**k) == r'J^{k}_{n}\left(z^{2}\right)' assert latex(bessely(n, z)) == r'Y_{n}\left(z\right)' assert latex(besseli(n, z)) == r'I_{n}\left(z\right)' assert latex(besselk(n, z)) == r'K_{n}\left(z\right)' assert latex(hankel1(n, z**2)**2) == \ r'\left(H^{(1)}_{n}\left(z^{2}\right)\right)^{2}' assert latex(hankel2(n, z)) == r'H^{(2)}_{n}\left(z\right)' assert latex(jn(n, z)) == r'j_{n}\left(z\right)' assert latex(yn(n, z)) == r'y_{n}\left(z\right)' assert latex(hn1(n, z)) == r'h^{(1)}_{n}\left(z\right)' assert latex(hn2(n, z)) == r'h^{(2)}_{n}\left(z\right)' def test_latex_fresnel(): from sympy.functions.special.error_functions import (fresnels, fresnelc) from sympy.abc import z assert latex(fresnels(z)) == r'S\left(z\right)' assert latex(fresnelc(z)) == r'C\left(z\right)' assert latex(fresnels(z)**2) == r'S^{2}\left(z\right)' assert latex(fresnelc(z)**2) == r'C^{2}\left(z\right)' def test_latex_brackets(): assert latex((-1)**x) == r"\left(-1\right)^{x}" def test_latex_indexed(): Psi_symbol = Symbol('Psi_0', complex=True, real=False) Psi_indexed = IndexedBase(Symbol('Psi', complex=True, real=False)) symbol_latex = latex(Psi_symbol * conjugate(Psi_symbol)) indexed_latex = latex(Psi_indexed[0] * conjugate(Psi_indexed[0])) # \\overline{{\\Psi}_{0}} {\\Psi}_{0} vs. \\Psi_{0} \\overline{\\Psi_{0}} assert symbol_latex == r'\Psi_{0} \overline{\Psi_{0}}' assert indexed_latex == r'\overline{{\Psi}_{0}} {\Psi}_{0}' # Symbol('gamma') gives r'\gamma' assert latex(Indexed('x1', Symbol('i'))) == r'{x_{1}}_{i}' assert latex(IndexedBase('gamma')) == r'\gamma' assert latex(IndexedBase('a b')) == r'a b' assert latex(IndexedBase('a_b')) == r'a_{b}' def test_latex_derivatives(): # regular "d" for ordinary derivatives assert latex(diff(x**3, x, evaluate=False)) == \ r"\frac{d}{d x} x^{3}" assert latex(diff(sin(x) + x**2, x, evaluate=False)) == \ r"\frac{d}{d x} \left(x^{2} + \sin{\left(x \right)}\right)" assert latex(diff(diff(sin(x) + x**2, x, evaluate=False), evaluate=False))\ == \ r"\frac{d^{2}}{d x^{2}} \left(x^{2} + \sin{\left(x \right)}\right)" assert latex(diff(diff(diff(sin(x) + x**2, x, evaluate=False), evaluate=False), evaluate=False)) == \ r"\frac{d^{3}}{d x^{3}} \left(x^{2} + \sin{\left(x \right)}\right)" # \partial for partial derivatives assert latex(diff(sin(x * y), x, evaluate=False)) == \ r"\frac{\partial}{\partial x} \sin{\left(x y \right)}" assert latex(diff(sin(x * y) + x**2, x, evaluate=False)) == \ r"\frac{\partial}{\partial x} \left(x^{2} + \sin{\left(x y \right)}\right)" assert latex(diff(diff(sin(x*y) + x**2, x, evaluate=False), x, evaluate=False)) == \ r"\frac{\partial^{2}}{\partial x^{2}} \left(x^{2} + \sin{\left(x y \right)}\right)" assert latex(diff(diff(diff(sin(x*y) + x**2, x, evaluate=False), x, evaluate=False), x, evaluate=False)) == \ r"\frac{\partial^{3}}{\partial x^{3}} \left(x^{2} + \sin{\left(x y \right)}\right)" # mixed partial derivatives f = Function("f") assert latex(diff(diff(f(x, y), x, evaluate=False), y, evaluate=False)) == \ r"\frac{\partial^{2}}{\partial y\partial x} " + latex(f(x, y)) assert latex(diff(diff(diff(f(x, y), x, evaluate=False), x, evaluate=False), y, evaluate=False)) == \ r"\frac{\partial^{3}}{\partial y\partial x^{2}} " + latex(f(x, y)) # for negative nested Derivative assert latex(diff(-diff(y**2,x,evaluate=False),x,evaluate=False)) == r'\frac{d}{d x} \left(- \frac{d}{d x} y^{2}\right)' assert latex(diff(diff(-diff(diff(y,x,evaluate=False),x,evaluate=False),x,evaluate=False),x,evaluate=False)) == \ r'\frac{d^{2}}{d x^{2}} \left(- \frac{d^{2}}{d x^{2}} y\right)' # use ordinary d when one of the variables has been integrated out assert latex(diff(Integral(exp(-x*y), (x, 0, oo)), y, evaluate=False)) == \ r"\frac{d}{d y} \int\limits_{0}^{\infty} e^{- x y}\, dx" # Derivative wrapped in power: assert latex(diff(x, x, evaluate=False)**2) == \ r"\left(\frac{d}{d x} x\right)^{2}" assert latex(diff(f(x), x)**2) == \ r"\left(\frac{d}{d x} f{\left(x \right)}\right)^{2}" assert latex(diff(f(x), (x, n))) == \ r"\frac{d^{n}}{d x^{n}} f{\left(x \right)}" x1 = Symbol('x1') x2 = Symbol('x2') assert latex(diff(f(x1, x2), x1)) == r'\frac{\partial}{\partial x_{1}} f{\left(x_{1},x_{2} \right)}' n1 = Symbol('n1') assert latex(diff(f(x), (x, n1))) == r'\frac{d^{n_{1}}}{d x^{n_{1}}} f{\left(x \right)}' n2 = Symbol('n2') assert latex(diff(f(x), (x, Max(n1, n2)))) == \ r'\frac{d^{\max\left(n_{1}, n_{2}\right)}}{d x^{\max\left(n_{1}, n_{2}\right)}} f{\left(x \right)}' def test_latex_subs(): assert latex(Subs(x*y, (x, y), (1, 2))) == r'\left. x y \right|_{\substack{ x=1\\ y=2 }}' def test_latex_integrals(): assert latex(Integral(log(x), x)) == r"\int \log{\left(x \right)}\, dx" assert latex(Integral(x**2, (x, 0, 1))) == \ r"\int\limits_{0}^{1} x^{2}\, dx" assert latex(Integral(x**2, (x, 10, 20))) == \ r"\int\limits_{10}^{20} x^{2}\, dx" assert latex(Integral(y*x**2, (x, 0, 1), y)) == \ r"\int\int\limits_{0}^{1} x^{2} y\, dx\, dy" assert latex(Integral(y*x**2, (x, 0, 1), y), mode='equation*') == \ r"\begin{equation*}\int\int\limits_{0}^{1} x^{2} y\, dx\, dy\end{equation*}" assert latex(Integral(y*x**2, (x, 0, 1), y), mode='equation*', itex=True) \ == r"$$\int\int_{0}^{1} x^{2} y\, dx\, dy$$" assert latex(Integral(x, (x, 0))) == r"\int\limits^{0} x\, dx" assert latex(Integral(x*y, x, y)) == r"\iint x y\, dx\, dy" assert latex(Integral(x*y*z, x, y, z)) == r"\iiint x y z\, dx\, dy\, dz" assert latex(Integral(x*y*z*t, x, y, z, t)) == \ r"\iiiint t x y z\, dx\, dy\, dz\, dt" assert latex(Integral(x, x, x, x, x, x, x)) == \ r"\int\int\int\int\int\int x\, dx\, dx\, dx\, dx\, dx\, dx" assert latex(Integral(x, x, y, (z, 0, 1))) == \ r"\int\limits_{0}^{1}\int\int x\, dx\, dy\, dz" # for negative nested Integral assert latex(Integral(-Integral(y**2,x),x)) == \ r'\int \left(- \int y^{2}\, dx\right)\, dx' assert latex(Integral(-Integral(-Integral(y,x),x),x)) == \ r'\int \left(- \int \left(- \int y\, dx\right)\, dx\right)\, dx' # fix issue #10806 assert latex(Integral(z, z)**2) == r"\left(\int z\, dz\right)^{2}" assert latex(Integral(x + z, z)) == r"\int \left(x + z\right)\, dz" assert latex(Integral(x+z/2, z)) == \ r"\int \left(x + \frac{z}{2}\right)\, dz" assert latex(Integral(x**y, z)) == r"\int x^{y}\, dz" def test_latex_sets(): for s in (frozenset, set): assert latex(s([x*y, x**2])) == r"\left\{x^{2}, x y\right\}" assert latex(s(range(1, 6))) == r"\left\{1, 2, 3, 4, 5\right\}" assert latex(s(range(1, 13))) == \ r"\left\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\right\}" s = FiniteSet assert latex(s(*[x*y, x**2])) == r"\left\{x^{2}, x y\right\}" assert latex(s(*range(1, 6))) == r"\left\{1, 2, 3, 4, 5\right\}" assert latex(s(*range(1, 13))) == \ r"\left\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\right\}" def test_latex_SetExpr(): iv = Interval(1, 3) se = SetExpr(iv) assert latex(se) == r"SetExpr\left(\left[1, 3\right]\right)" def test_latex_Range(): assert latex(Range(1, 51)) == r'\left\{1, 2, \ldots, 50\right\}' assert latex(Range(1, 4)) == r'\left\{1, 2, 3\right\}' assert latex(Range(0, 3, 1)) == r'\left\{0, 1, 2\right\}' assert latex(Range(0, 30, 1)) == r'\left\{0, 1, \ldots, 29\right\}' assert latex(Range(30, 1, -1)) == r'\left\{30, 29, \ldots, 2\right\}' assert latex(Range(0, oo, 2)) == r'\left\{0, 2, \ldots\right\}' assert latex(Range(oo, -2, -2)) == r'\left\{\ldots, 2, 0\right\}' assert latex(Range(-2, -oo, -1)) == r'\left\{-2, -3, \ldots\right\}' assert latex(Range(-oo, oo)) == r'\left\{\ldots, -1, 0, 1, \ldots\right\}' assert latex(Range(oo, -oo, -1)) == r'\left\{\ldots, 1, 0, -1, \ldots\right\}' a, b, c = symbols('a:c') assert latex(Range(a, b, c)) == r'Range\left(a, b, c\right)' assert latex(Range(a, 10, 1)) == r'Range\left(a, 10, 1\right)' assert latex(Range(0, b, 1)) == r'Range\left(0, b, 1\right)' assert latex(Range(0, 10, c)) == r'Range\left(0, 10, c\right)' def test_latex_sequences(): s1 = SeqFormula(a**2, (0, oo)) s2 = SeqPer((1, 2)) latex_str = r'\left[0, 1, 4, 9, \ldots\right]' assert latex(s1) == latex_str latex_str = r'\left[1, 2, 1, 2, \ldots\right]' assert latex(s2) == latex_str s3 = SeqFormula(a**2, (0, 2)) s4 = SeqPer((1, 2), (0, 2)) latex_str = r'\left[0, 1, 4\right]' assert latex(s3) == latex_str latex_str = r'\left[1, 2, 1\right]' assert latex(s4) == latex_str s5 = SeqFormula(a**2, (-oo, 0)) s6 = SeqPer((1, 2), (-oo, 0)) latex_str = r'\left[\ldots, 9, 4, 1, 0\right]' assert latex(s5) == latex_str latex_str = r'\left[\ldots, 2, 1, 2, 1\right]' assert latex(s6) == latex_str latex_str = r'\left[1, 3, 5, 11, \ldots\right]' assert latex(SeqAdd(s1, s2)) == latex_str latex_str = r'\left[1, 3, 5\right]' assert latex(SeqAdd(s3, s4)) == latex_str latex_str = r'\left[\ldots, 11, 5, 3, 1\right]' assert latex(SeqAdd(s5, s6)) == latex_str latex_str = r'\left[0, 2, 4, 18, \ldots\right]' assert latex(SeqMul(s1, s2)) == latex_str latex_str = r'\left[0, 2, 4\right]' assert latex(SeqMul(s3, s4)) == latex_str latex_str = r'\left[\ldots, 18, 4, 2, 0\right]' assert latex(SeqMul(s5, s6)) == latex_str # Sequences with symbolic limits, issue 12629 s7 = SeqFormula(a**2, (a, 0, x)) latex_str = r'\left\{a^{2}\right\}_{a=0}^{x}' assert latex(s7) == latex_str b = Symbol('b') s8 = SeqFormula(b*a**2, (a, 0, 2)) latex_str = r'\left[0, b, 4 b\right]' assert latex(s8) == latex_str def test_latex_FourierSeries(): latex_str = \ r'2 \sin{\left(x \right)} - \sin{\left(2 x \right)} + \frac{2 \sin{\left(3 x \right)}}{3} + \ldots' assert latex(fourier_series(x, (x, -pi, pi))) == latex_str def test_latex_FormalPowerSeries(): latex_str = r'\sum_{k=1}^{\infty} - \frac{\left(-1\right)^{- k} x^{k}}{k}' assert latex(fps(log(1 + x))) == latex_str def test_latex_intervals(): a = Symbol('a', real=True) assert latex(Interval(0, 0)) == r"\left\{0\right\}" assert latex(Interval(0, a)) == r"\left[0, a\right]" assert latex(Interval(0, a, False, False)) == r"\left[0, a\right]" assert latex(Interval(0, a, True, False)) == r"\left(0, a\right]" assert latex(Interval(0, a, False, True)) == r"\left[0, a\right)" assert latex(Interval(0, a, True, True)) == r"\left(0, a\right)" def test_latex_AccumuBounds(): a = Symbol('a', real=True) assert latex(AccumBounds(0, 1)) == r"\left\langle 0, 1\right\rangle" assert latex(AccumBounds(0, a)) == r"\left\langle 0, a\right\rangle" assert latex(AccumBounds(a + 1, a + 2)) == \ r"\left\langle a + 1, a + 2\right\rangle" def test_latex_emptyset(): assert latex(S.EmptySet) == r"\emptyset" def test_latex_universalset(): assert latex(S.UniversalSet) == r"\mathbb{U}" def test_latex_commutator(): A = Operator('A') B = Operator('B') comm = Commutator(B, A) assert latex(comm.doit()) == r"- (A B - B A)" def test_latex_union(): assert latex(Union(Interval(0, 1), Interval(2, 3))) == \ r"\left[0, 1\right] \cup \left[2, 3\right]" assert latex(Union(Interval(1, 1), Interval(2, 2), Interval(3, 4))) == \ r"\left\{1, 2\right\} \cup \left[3, 4\right]" def test_latex_intersection(): assert latex(Intersection(Interval(0, 1), Interval(x, y))) == \ r"\left[0, 1\right] \cap \left[x, y\right]" def test_latex_symmetric_difference(): assert latex(SymmetricDifference(Interval(2, 5), Interval(4, 7), evaluate=False)) == \ r'\left[2, 5\right] \triangle \left[4, 7\right]' def test_latex_Complement(): assert latex(Complement(S.Reals, S.Naturals)) == \ r"\mathbb{R} \setminus \mathbb{N}" def test_latex_productset(): line = Interval(0, 1) bigline = Interval(0, 10) fset = FiniteSet(1, 2, 3) assert latex(line**2) == r"%s^{2}" % latex(line) assert latex(line**10) == r"%s^{10}" % latex(line) assert latex((line * bigline * fset).flatten()) == r"%s \times %s \times %s" % ( latex(line), latex(bigline), latex(fset)) def test_set_operators_parenthesis(): a, b, c, d = symbols('a:d') A = FiniteSet(a) B = FiniteSet(b) C = FiniteSet(c) D = FiniteSet(d) U1 = Union(A, B, evaluate=False) U2 = Union(C, D, evaluate=False) I1 = Intersection(A, B, evaluate=False) I2 = Intersection(C, D, evaluate=False) C1 = Complement(A, B, evaluate=False) C2 = Complement(C, D, evaluate=False) D1 = SymmetricDifference(A, B, evaluate=False) D2 = SymmetricDifference(C, D, evaluate=False) # XXX ProductSet does not support evaluate keyword P1 = ProductSet(A, B) P2 = ProductSet(C, D) assert latex(Intersection(A, U2, evaluate=False)) == \ r'\left\{a\right\} \cap ' \ r'\left(\left\{c\right\} \cup \left\{d\right\}\right)' assert latex(Intersection(U1, U2, evaluate=False)) == \ r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \ r'\cap \left(\left\{c\right\} \cup \left\{d\right\}\right)' assert latex(Intersection(C1, C2, evaluate=False)) == \ r'\left(\left\{a\right\} \setminus ' \ r'\left\{b\right\}\right) \cap \left(\left\{c\right\} ' \ r'\setminus \left\{d\right\}\right)' assert latex(Intersection(D1, D2, evaluate=False)) == \ r'\left(\left\{a\right\} \triangle ' \ r'\left\{b\right\}\right) \cap \left(\left\{c\right\} ' \ r'\triangle \left\{d\right\}\right)' assert latex(Intersection(P1, P2, evaluate=False)) == \ r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \ r'\cap \left(\left\{c\right\} \times ' \ r'\left\{d\right\}\right)' assert latex(Union(A, I2, evaluate=False)) == \ r'\left\{a\right\} \cup ' \ r'\left(\left\{c\right\} \cap \left\{d\right\}\right)' assert latex(Union(I1, I2, evaluate=False)) == \ r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \ r'\cup \left(\left\{c\right\} \cap \left\{d\right\}\right)' assert latex(Union(C1, C2, evaluate=False)) == \ r'\left(\left\{a\right\} \setminus ' \ r'\left\{b\right\}\right) \cup \left(\left\{c\right\} ' \ r'\setminus \left\{d\right\}\right)' assert latex(Union(D1, D2, evaluate=False)) == \ r'\left(\left\{a\right\} \triangle ' \ r'\left\{b\right\}\right) \cup \left(\left\{c\right\} ' \ r'\triangle \left\{d\right\}\right)' assert latex(Union(P1, P2, evaluate=False)) == \ r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \ r'\cup \left(\left\{c\right\} \times ' \ r'\left\{d\right\}\right)' assert latex(Complement(A, C2, evaluate=False)) == \ r'\left\{a\right\} \setminus \left(\left\{c\right\} ' \ r'\setminus \left\{d\right\}\right)' assert latex(Complement(U1, U2, evaluate=False)) == \ r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \ r'\setminus \left(\left\{c\right\} \cup ' \ r'\left\{d\right\}\right)' assert latex(Complement(I1, I2, evaluate=False)) == \ r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \ r'\setminus \left(\left\{c\right\} \cap ' \ r'\left\{d\right\}\right)' assert latex(Complement(D1, D2, evaluate=False)) == \ r'\left(\left\{a\right\} \triangle ' \ r'\left\{b\right\}\right) \setminus ' \ r'\left(\left\{c\right\} \triangle \left\{d\right\}\right)' assert latex(Complement(P1, P2, evaluate=False)) == \ r'\left(\left\{a\right\} \times \left\{b\right\}\right) '\ r'\setminus \left(\left\{c\right\} \times '\ r'\left\{d\right\}\right)' assert latex(SymmetricDifference(A, D2, evaluate=False)) == \ r'\left\{a\right\} \triangle \left(\left\{c\right\} ' \ r'\triangle \left\{d\right\}\right)' assert latex(SymmetricDifference(U1, U2, evaluate=False)) == \ r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \ r'\triangle \left(\left\{c\right\} \cup ' \ r'\left\{d\right\}\right)' assert latex(SymmetricDifference(I1, I2, evaluate=False)) == \ r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \ r'\triangle \left(\left\{c\right\} \cap ' \ r'\left\{d\right\}\right)' assert latex(SymmetricDifference(C1, C2, evaluate=False)) == \ r'\left(\left\{a\right\} \setminus ' \ r'\left\{b\right\}\right) \triangle ' \ r'\left(\left\{c\right\} \setminus \left\{d\right\}\right)' assert latex(SymmetricDifference(P1, P2, evaluate=False)) == \ r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \ r'\triangle \left(\left\{c\right\} \times ' \ r'\left\{d\right\}\right)' # XXX This can be incorrect since cartesian product is not associative assert latex(ProductSet(A, P2).flatten()) == \ r'\left\{a\right\} \times \left\{c\right\} \times ' \ r'\left\{d\right\}' assert latex(ProductSet(U1, U2)) == \ r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \ r'\times \left(\left\{c\right\} \cup ' \ r'\left\{d\right\}\right)' assert latex(ProductSet(I1, I2)) == \ r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \ r'\times \left(\left\{c\right\} \cap ' \ r'\left\{d\right\}\right)' assert latex(ProductSet(C1, C2)) == \ r'\left(\left\{a\right\} \setminus ' \ r'\left\{b\right\}\right) \times \left(\left\{c\right\} ' \ r'\setminus \left\{d\right\}\right)' assert latex(ProductSet(D1, D2)) == \ r'\left(\left\{a\right\} \triangle ' \ r'\left\{b\right\}\right) \times \left(\left\{c\right\} ' \ r'\triangle \left\{d\right\}\right)' def test_latex_Complexes(): assert latex(S.Complexes) == r"\mathbb{C}" def test_latex_Naturals(): assert latex(S.Naturals) == r"\mathbb{N}" def test_latex_Naturals0(): assert latex(S.Naturals0) == r"\mathbb{N}_0" def test_latex_Integers(): assert latex(S.Integers) == r"\mathbb{Z}" def test_latex_ImageSet(): x = Symbol('x') assert latex(ImageSet(Lambda(x, x**2), S.Naturals)) == \ r"\left\{x^{2}\; \middle|\; x \in \mathbb{N}\right\}" y = Symbol('y') imgset = ImageSet(Lambda((x, y), x + y), {1, 2, 3}, {3, 4}) assert latex(imgset) == \ r"\left\{x + y\; \middle|\; x \in \left\{1, 2, 3\right\} , y \in \left\{3, 4\right\}\right\}" imgset = ImageSet(Lambda(((x, y),), x + y), ProductSet({1, 2, 3}, {3, 4})) assert latex(imgset) == \ r"\left\{x + y\; \middle|\; \left( x, \ y\right) \in \left\{1, 2, 3\right\} \times \left\{3, 4\right\}\right\}" def test_latex_ConditionSet(): x = Symbol('x') assert latex(ConditionSet(x, Eq(x**2, 1), S.Reals)) == \ r"\left\{x\; \middle|\; x \in \mathbb{R} \wedge x^{2} = 1 \right\}" assert latex(ConditionSet(x, Eq(x**2, 1), S.UniversalSet)) == \ r"\left\{x\; \middle|\; x^{2} = 1 \right\}" def test_latex_ComplexRegion(): assert latex(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == \ r"\left\{x + y i\; \middle|\; x, y \in \left[3, 5\right] \times \left[4, 6\right] \right\}" assert latex(ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == \ r"\left\{r \left(i \sin{\left(\theta \right)} + \cos{\left(\theta "\ r"\right)}\right)\; \middle|\; r, \theta \in \left[0, 1\right] \times \left[0, 2 \pi\right) \right\}" def test_latex_Contains(): x = Symbol('x') assert latex(Contains(x, S.Naturals)) == r"x \in \mathbb{N}" def test_latex_sum(): assert latex(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \ r"\sum_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}" assert latex(Sum(x**2, (x, -2, 2))) == \ r"\sum_{x=-2}^{2} x^{2}" assert latex(Sum(x**2 + y, (x, -2, 2))) == \ r"\sum_{x=-2}^{2} \left(x^{2} + y\right)" assert latex(Sum(x**2 + y, (x, -2, 2))**2) == \ r"\left(\sum_{x=-2}^{2} \left(x^{2} + y\right)\right)^{2}" def test_latex_product(): assert latex(Product(x*y**2, (x, -2, 2), (y, -5, 5))) == \ r"\prod_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}" assert latex(Product(x**2, (x, -2, 2))) == \ r"\prod_{x=-2}^{2} x^{2}" assert latex(Product(x**2 + y, (x, -2, 2))) == \ r"\prod_{x=-2}^{2} \left(x^{2} + y\right)" assert latex(Product(x, (x, -2, 2))**2) == \ r"\left(\prod_{x=-2}^{2} x\right)^{2}" def test_latex_limits(): assert latex(Limit(x, x, oo)) == r"\lim_{x \to \infty} x" # issue 8175 f = Function('f') assert latex(Limit(f(x), x, 0)) == r"\lim_{x \to 0^+} f{\left(x \right)}" assert latex(Limit(f(x), x, 0, "-")) == \ r"\lim_{x \to 0^-} f{\left(x \right)}" # issue #10806 assert latex(Limit(f(x), x, 0)**2) == \ r"\left(\lim_{x \to 0^+} f{\left(x \right)}\right)^{2}" # bi-directional limit assert latex(Limit(f(x), x, 0, dir='+-')) == \ r"\lim_{x \to 0} f{\left(x \right)}" def test_latex_log(): assert latex(log(x)) == r"\log{\left(x \right)}" assert latex(ln(x)) == r"\log{\left(x \right)}" assert latex(log(x), ln_notation=True) == r"\ln{\left(x \right)}" assert latex(log(x)+log(y)) == \ r"\log{\left(x \right)} + \log{\left(y \right)}" assert latex(log(x)+log(y), ln_notation=True) == \ r"\ln{\left(x \right)} + \ln{\left(y \right)}" assert latex(pow(log(x), x)) == r"\log{\left(x \right)}^{x}" assert latex(pow(log(x), x), ln_notation=True) == \ r"\ln{\left(x \right)}^{x}" def test_issue_3568(): beta = Symbol(r'\beta') y = beta + x assert latex(y) in [r'\beta + x', r'x + \beta'] beta = Symbol(r'beta') y = beta + x assert latex(y) in [r'\beta + x', r'x + \beta'] def test_latex(): assert latex((2*tau)**Rational(7, 2)) == r"8 \sqrt{2} \tau^{\frac{7}{2}}" assert latex((2*mu)**Rational(7, 2), mode='equation*') == \ r"\begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}" assert latex((2*mu)**Rational(7, 2), mode='equation', itex=True) == \ r"$$8 \sqrt{2} \mu^{\frac{7}{2}}$$" assert latex([2/x, y]) == r"\left[ \frac{2}{x}, \ y\right]" def test_latex_dict(): d = {Rational(1): 1, x**2: 2, x: 3, x**3: 4} assert latex(d) == \ r'\left\{ 1 : 1, \ x : 3, \ x^{2} : 2, \ x^{3} : 4\right\}' D = Dict(d) assert latex(D) == \ r'\left\{ 1 : 1, \ x : 3, \ x^{2} : 2, \ x^{3} : 4\right\}' def test_latex_list(): ll = [Symbol('omega1'), Symbol('a'), Symbol('alpha')] assert latex(ll) == r'\left[ \omega_{1}, \ a, \ \alpha\right]' def test_latex_rational(): # tests issue 3973 assert latex(-Rational(1, 2)) == r"- \frac{1}{2}" assert latex(Rational(-1, 2)) == r"- \frac{1}{2}" assert latex(Rational(1, -2)) == r"- \frac{1}{2}" assert latex(-Rational(-1, 2)) == r"\frac{1}{2}" assert latex(-Rational(1, 2)*x) == r"- \frac{x}{2}" assert latex(-Rational(1, 2)*x + Rational(-2, 3)*y) == \ r"- \frac{x}{2} - \frac{2 y}{3}" def test_latex_inverse(): # tests issue 4129 assert latex(1/x) == r"\frac{1}{x}" assert latex(1/(x + y)) == r"\frac{1}{x + y}" def test_latex_DiracDelta(): assert latex(DiracDelta(x)) == r"\delta\left(x\right)" assert latex(DiracDelta(x)**2) == r"\left(\delta\left(x\right)\right)^{2}" assert latex(DiracDelta(x, 0)) == r"\delta\left(x\right)" assert latex(DiracDelta(x, 5)) == \ r"\delta^{\left( 5 \right)}\left( x \right)" assert latex(DiracDelta(x, 5)**2) == \ r"\left(\delta^{\left( 5 \right)}\left( x \right)\right)^{2}" def test_latex_Heaviside(): assert latex(Heaviside(x)) == r"\theta\left(x\right)" assert latex(Heaviside(x)**2) == r"\left(\theta\left(x\right)\right)^{2}" def test_latex_KroneckerDelta(): assert latex(KroneckerDelta(x, y)) == r"\delta_{x y}" assert latex(KroneckerDelta(x, y + 1)) == r"\delta_{x, y + 1}" # issue 6578 assert latex(KroneckerDelta(x + 1, y)) == r"\delta_{y, x + 1}" assert latex(Pow(KroneckerDelta(x, y), 2, evaluate=False)) == \ r"\left(\delta_{x y}\right)^{2}" def test_latex_LeviCivita(): assert latex(LeviCivita(x, y, z)) == r"\varepsilon_{x y z}" assert latex(LeviCivita(x, y, z)**2) == \ r"\left(\varepsilon_{x y z}\right)^{2}" assert latex(LeviCivita(x, y, z + 1)) == r"\varepsilon_{x, y, z + 1}" assert latex(LeviCivita(x, y + 1, z)) == r"\varepsilon_{x, y + 1, z}" assert latex(LeviCivita(x + 1, y, z)) == r"\varepsilon_{x + 1, y, z}" def test_mode(): expr = x + y assert latex(expr) == r'x + y' assert latex(expr, mode='plain') == r'x + y' assert latex(expr, mode='inline') == r'$x + y$' assert latex( expr, mode='equation*') == r'\begin{equation*}x + y\end{equation*}' assert latex( expr, mode='equation') == r'\begin{equation}x + y\end{equation}' raises(ValueError, lambda: latex(expr, mode='foo')) def test_latex_mathieu(): assert latex(mathieuc(x, y, z)) == r"C\left(x, y, z\right)" assert latex(mathieus(x, y, z)) == r"S\left(x, y, z\right)" assert latex(mathieuc(x, y, z)**2) == r"C\left(x, y, z\right)^{2}" assert latex(mathieus(x, y, z)**2) == r"S\left(x, y, z\right)^{2}" assert latex(mathieucprime(x, y, z)) == r"C^{\prime}\left(x, y, z\right)" assert latex(mathieusprime(x, y, z)) == r"S^{\prime}\left(x, y, z\right)" assert latex(mathieucprime(x, y, z)**2) == r"C^{\prime}\left(x, y, z\right)^{2}" assert latex(mathieusprime(x, y, z)**2) == r"S^{\prime}\left(x, y, z\right)^{2}" def test_latex_Piecewise(): p = Piecewise((x, x < 1), (x**2, True)) assert latex(p) == r"\begin{cases} x & \text{for}\: x < 1 \\x^{2} &" \ r" \text{otherwise} \end{cases}" assert latex(p, itex=True) == \ r"\begin{cases} x & \text{for}\: x \lt 1 \\x^{2} &" \ r" \text{otherwise} \end{cases}" p = Piecewise((x, x < 0), (0, x >= 0)) assert latex(p) == r'\begin{cases} x & \text{for}\: x < 0 \\0 &' \ r' \text{otherwise} \end{cases}' A, B = symbols("A B", commutative=False) p = Piecewise((A**2, Eq(A, B)), (A*B, True)) s = r"\begin{cases} A^{2} & \text{for}\: A = B \\A B & \text{otherwise} \end{cases}" assert latex(p) == s assert latex(A*p) == r"A \left(%s\right)" % s assert latex(p*A) == r"\left(%s\right) A" % s assert latex(Piecewise((x, x < 1), (x**2, x < 2))) == \ r'\begin{cases} x & ' \ r'\text{for}\: x < 1 \\x^{2} & \text{for}\: x < 2 \end{cases}' def test_latex_Matrix(): M = Matrix([[1 + x, y], [y, x - 1]]) assert latex(M) == \ r'\left[\begin{matrix}x + 1 & y\\y & x - 1\end{matrix}\right]' assert latex(M, mode='inline') == \ r'$\left[\begin{smallmatrix}x + 1 & y\\' \ r'y & x - 1\end{smallmatrix}\right]$' assert latex(M, mat_str='array') == \ r'\left[\begin{array}{cc}x + 1 & y\\y & x - 1\end{array}\right]' assert latex(M, mat_str='bmatrix') == \ r'\left[\begin{bmatrix}x + 1 & y\\y & x - 1\end{bmatrix}\right]' assert latex(M, mat_delim=None, mat_str='bmatrix') == \ r'\begin{bmatrix}x + 1 & y\\y & x - 1\end{bmatrix}' M2 = Matrix(1, 11, range(11)) assert latex(M2) == \ r'\left[\begin{array}{ccccccccccc}' \ r'0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10\end{array}\right]' def test_latex_matrix_with_functions(): t = symbols('t') theta1 = symbols('theta1', cls=Function) M = Matrix([[sin(theta1(t)), cos(theta1(t))], [cos(theta1(t).diff(t)), sin(theta1(t).diff(t))]]) expected = (r'\left[\begin{matrix}\sin{\left(' r'\theta_{1}{\left(t \right)} \right)} & ' r'\cos{\left(\theta_{1}{\left(t \right)} \right)' r'}\\\cos{\left(\frac{d}{d t} \theta_{1}{\left(t ' r'\right)} \right)} & \sin{\left(\frac{d}{d t} ' r'\theta_{1}{\left(t \right)} \right' r')}\end{matrix}\right]') assert latex(M) == expected def test_latex_NDimArray(): x, y, z, w = symbols("x y z w") for ArrayType in (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray): # Basic: scalar array M = ArrayType(x) assert latex(M) == r"x" M = ArrayType([[1 / x, y], [z, w]]) M1 = ArrayType([1 / x, y, z]) M2 = tensorproduct(M1, M) M3 = tensorproduct(M, M) assert latex(M) == \ r'\left[\begin{matrix}\frac{1}{x} & y\\z & w\end{matrix}\right]' assert latex(M1) == \ r"\left[\begin{matrix}\frac{1}{x} & y & z\end{matrix}\right]" assert latex(M2) == \ r"\left[\begin{matrix}" \ r"\left[\begin{matrix}\frac{1}{x^{2}} & \frac{y}{x}\\\frac{z}{x} & \frac{w}{x}\end{matrix}\right] & " \ r"\left[\begin{matrix}\frac{y}{x} & y^{2}\\y z & w y\end{matrix}\right] & " \ r"\left[\begin{matrix}\frac{z}{x} & y z\\z^{2} & w z\end{matrix}\right]" \ r"\end{matrix}\right]" assert latex(M3) == \ r"""\left[\begin{matrix}"""\ r"""\left[\begin{matrix}\frac{1}{x^{2}} & \frac{y}{x}\\\frac{z}{x} & \frac{w}{x}\end{matrix}\right] & """\ r"""\left[\begin{matrix}\frac{y}{x} & y^{2}\\y z & w y\end{matrix}\right]\\"""\ r"""\left[\begin{matrix}\frac{z}{x} & y z\\z^{2} & w z\end{matrix}\right] & """\ r"""\left[\begin{matrix}\frac{w}{x} & w y\\w z & w^{2}\end{matrix}\right]"""\ r"""\end{matrix}\right]""" Mrow = ArrayType([[x, y, 1/z]]) Mcolumn = ArrayType([[x], [y], [1/z]]) Mcol2 = ArrayType([Mcolumn.tolist()]) assert latex(Mrow) == \ r"\left[\left[\begin{matrix}x & y & \frac{1}{z}\end{matrix}\right]\right]" assert latex(Mcolumn) == \ r"\left[\begin{matrix}x\\y\\\frac{1}{z}\end{matrix}\right]" assert latex(Mcol2) == \ r'\left[\begin{matrix}\left[\begin{matrix}x\\y\\\frac{1}{z}\end{matrix}\right]\end{matrix}\right]' def test_latex_mul_symbol(): assert latex(4*4**x, mul_symbol='times') == r"4 \times 4^{x}" assert latex(4*4**x, mul_symbol='dot') == r"4 \cdot 4^{x}" assert latex(4*4**x, mul_symbol='ldot') == r"4 \,.\, 4^{x}" assert latex(4*x, mul_symbol='times') == r"4 \times x" assert latex(4*x, mul_symbol='dot') == r"4 \cdot x" assert latex(4*x, mul_symbol='ldot') == r"4 \,.\, x" def test_latex_issue_4381(): y = 4*4**log(2) assert latex(y) == r'4 \cdot 4^{\log{\left(2 \right)}}' assert latex(1/y) == r'\frac{1}{4 \cdot 4^{\log{\left(2 \right)}}}' def test_latex_issue_4576(): assert latex(Symbol("beta_13_2")) == r"\beta_{13 2}" assert latex(Symbol("beta_132_20")) == r"\beta_{132 20}" assert latex(Symbol("beta_13")) == r"\beta_{13}" assert latex(Symbol("x_a_b")) == r"x_{a b}" assert latex(Symbol("x_1_2_3")) == r"x_{1 2 3}" assert latex(Symbol("x_a_b1")) == r"x_{a b1}" assert latex(Symbol("x_a_1")) == r"x_{a 1}" assert latex(Symbol("x_1_a")) == r"x_{1 a}" assert latex(Symbol("x_1^aa")) == r"x^{aa}_{1}" assert latex(Symbol("x_1__aa")) == r"x^{aa}_{1}" assert latex(Symbol("x_11^a")) == r"x^{a}_{11}" assert latex(Symbol("x_11__a")) == r"x^{a}_{11}" assert latex(Symbol("x_a_a_a_a")) == r"x_{a a a a}" assert latex(Symbol("x_a_a^a^a")) == r"x^{a a}_{a a}" assert latex(Symbol("x_a_a__a__a")) == r"x^{a a}_{a a}" assert latex(Symbol("alpha_11")) == r"\alpha_{11}" assert latex(Symbol("alpha_11_11")) == r"\alpha_{11 11}" assert latex(Symbol("alpha_alpha")) == r"\alpha_{\alpha}" assert latex(Symbol("alpha^aleph")) == r"\alpha^{\aleph}" assert latex(Symbol("alpha__aleph")) == r"\alpha^{\aleph}" def test_latex_pow_fraction(): x = Symbol('x') # Testing exp assert r'e^{-x}' in latex(exp(-x)/2).replace(' ', '') # Remove Whitespace # Testing e^{-x} in case future changes alter behavior of muls or fracs # In particular current output is \frac{1}{2}e^{- x} but perhaps this will # change to \frac{e^{-x}}{2} # Testing general, non-exp, power assert r'3^{-x}' in latex(3**-x/2).replace(' ', '') def test_noncommutative(): A, B, C = symbols('A,B,C', commutative=False) assert latex(A*B*C**-1) == r"A B C^{-1}" assert latex(C**-1*A*B) == r"C^{-1} A B" assert latex(A*C**-1*B) == r"A C^{-1} B" def test_latex_order(): expr = x**3 + x**2*y + y**4 + 3*x*y**3 assert latex(expr, order='lex') == r"x^{3} + x^{2} y + 3 x y^{3} + y^{4}" assert latex( expr, order='rev-lex') == r"y^{4} + 3 x y^{3} + x^{2} y + x^{3}" assert latex(expr, order='none') == r"x^{3} + y^{4} + y x^{2} + 3 x y^{3}" def test_latex_Lambda(): assert latex(Lambda(x, x + 1)) == r"\left( x \mapsto x + 1 \right)" assert latex(Lambda((x, y), x + 1)) == r"\left( \left( x, \ y\right) \mapsto x + 1 \right)" assert latex(Lambda(x, x)) == r"\left( x \mapsto x \right)" def test_latex_PolyElement(): Ruv, u, v = ring("u,v", ZZ) Rxyz, x, y, z = ring("x,y,z", Ruv) assert latex(x - x) == r"0" assert latex(x - 1) == r"x - 1" assert latex(x + 1) == r"x + 1" assert latex((u**2 + 3*u*v + 1)*x**2*y + u + 1) == \ r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + u + 1" assert latex((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x) == \ r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + \left(u + 1\right) x" assert latex((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1) == \ r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + \left(u + 1\right) x + 1" assert latex((-u**2 + 3*u*v - 1)*x**2*y - (u + 1)*x - 1) == \ r"-\left({u}^{2} - 3 u v + 1\right) {x}^{2} y - \left(u + 1\right) x - 1" assert latex(-(v**2 + v + 1)*x + 3*u*v + 1) == \ r"-\left({v}^{2} + v + 1\right) x + 3 u v + 1" assert latex(-(v**2 + v + 1)*x - 3*u*v + 1) == \ r"-\left({v}^{2} + v + 1\right) x - 3 u v + 1" def test_latex_FracElement(): Fuv, u, v = field("u,v", ZZ) Fxyzt, x, y, z, t = field("x,y,z,t", Fuv) assert latex(x - x) == r"0" assert latex(x - 1) == r"x - 1" assert latex(x + 1) == r"x + 1" assert latex(x/3) == r"\frac{x}{3}" assert latex(x/z) == r"\frac{x}{z}" assert latex(x*y/z) == r"\frac{x y}{z}" assert latex(x/(z*t)) == r"\frac{x}{z t}" assert latex(x*y/(z*t)) == r"\frac{x y}{z t}" assert latex((x - 1)/y) == r"\frac{x - 1}{y}" assert latex((x + 1)/y) == r"\frac{x + 1}{y}" assert latex((-x - 1)/y) == r"\frac{-x - 1}{y}" assert latex((x + 1)/(y*z)) == r"\frac{x + 1}{y z}" assert latex(-y/(x + 1)) == r"\frac{-y}{x + 1}" assert latex(y*z/(x + 1)) == r"\frac{y z}{x + 1}" assert latex(((u + 1)*x*y + 1)/((v - 1)*z - 1)) == \ r"\frac{\left(u + 1\right) x y + 1}{\left(v - 1\right) z - 1}" assert latex(((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)) == \ r"\frac{\left(u + 1\right) x y + 1}{\left(v - 1\right) z - u v t - 1}" def test_latex_Poly(): assert latex(Poly(x**2 + 2 * x, x)) == \ r"\operatorname{Poly}{\left( x^{2} + 2 x, x, domain=\mathbb{Z} \right)}" assert latex(Poly(x/y, x)) == \ r"\operatorname{Poly}{\left( \frac{1}{y} x, x, domain=\mathbb{Z}\left(y\right) \right)}" assert latex(Poly(2.0*x + y)) == \ r"\operatorname{Poly}{\left( 2.0 x + 1.0 y, x, y, domain=\mathbb{R} \right)}" def test_latex_Poly_order(): assert latex(Poly([a, 1, b, 2, c, 3], x)) == \ r'\operatorname{Poly}{\left( a x^{5} + x^{4} + b x^{3} + 2 x^{2} + c'\ r' x + 3, x, domain=\mathbb{Z}\left[a, b, c\right] \right)}' assert latex(Poly([a, 1, b+c, 2, 3], x)) == \ r'\operatorname{Poly}{\left( a x^{4} + x^{3} + \left(b + c\right) '\ r'x^{2} + 2 x + 3, x, domain=\mathbb{Z}\left[a, b, c\right] \right)}' assert latex(Poly(a*x**3 + x**2*y - x*y - c*y**3 - b*x*y**2 + y - a*x + b, (x, y))) == \ r'\operatorname{Poly}{\left( a x^{3} + x^{2}y - b xy^{2} - xy - '\ r'a x - c y^{3} + y + b, x, y, domain=\mathbb{Z}\left[a, b, c\right] \right)}' def test_latex_ComplexRootOf(): assert latex(rootof(x**5 + x + 3, 0)) == \ r"\operatorname{CRootOf} {\left(x^{5} + x + 3, 0\right)}" def test_latex_RootSum(): assert latex(RootSum(x**5 + x + 3, sin)) == \ r"\operatorname{RootSum} {\left(x^{5} + x + 3, \left( x \mapsto \sin{\left(x \right)} \right)\right)}" def test_settings(): raises(TypeError, lambda: latex(x*y, method="garbage")) def test_latex_numbers(): assert latex(catalan(n)) == r"C_{n}" assert latex(catalan(n)**2) == r"C_{n}^{2}" assert latex(bernoulli(n)) == r"B_{n}" assert latex(bernoulli(n, x)) == r"B_{n}\left(x\right)" assert latex(bernoulli(n)**2) == r"B_{n}^{2}" assert latex(bernoulli(n, x)**2) == r"B_{n}^{2}\left(x\right)" assert latex(bell(n)) == r"B_{n}" assert latex(bell(n, x)) == r"B_{n}\left(x\right)" assert latex(bell(n, m, (x, y))) == r"B_{n, m}\left(x, y\right)" assert latex(bell(n)**2) == r"B_{n}^{2}" assert latex(bell(n, x)**2) == r"B_{n}^{2}\left(x\right)" assert latex(bell(n, m, (x, y))**2) == r"B_{n, m}^{2}\left(x, y\right)" assert latex(fibonacci(n)) == r"F_{n}" assert latex(fibonacci(n, x)) == r"F_{n}\left(x\right)" assert latex(fibonacci(n)**2) == r"F_{n}^{2}" assert latex(fibonacci(n, x)**2) == r"F_{n}^{2}\left(x\right)" assert latex(lucas(n)) == r"L_{n}" assert latex(lucas(n)**2) == r"L_{n}^{2}" assert latex(tribonacci(n)) == r"T_{n}" assert latex(tribonacci(n, x)) == r"T_{n}\left(x\right)" assert latex(tribonacci(n)**2) == r"T_{n}^{2}" assert latex(tribonacci(n, x)**2) == r"T_{n}^{2}\left(x\right)" def test_latex_euler(): assert latex(euler(n)) == r"E_{n}" assert latex(euler(n, x)) == r"E_{n}\left(x\right)" assert latex(euler(n, x)**2) == r"E_{n}^{2}\left(x\right)" def test_lamda(): assert latex(Symbol('lamda')) == r"\lambda" assert latex(Symbol('Lamda')) == r"\Lambda" def test_custom_symbol_names(): x = Symbol('x') y = Symbol('y') assert latex(x) == r"x" assert latex(x, symbol_names={x: "x_i"}) == r"x_i" assert latex(x + y, symbol_names={x: "x_i"}) == r"x_i + y" assert latex(x**2, symbol_names={x: "x_i"}) == r"x_i^{2}" assert latex(x + y, symbol_names={x: "x_i", y: "y_j"}) == r"x_i + y_j" def test_matAdd(): from sympy import MatrixSymbol from sympy.printing.latex import LatexPrinter C = MatrixSymbol('C', 5, 5) B = MatrixSymbol('B', 5, 5) l = LatexPrinter() assert l._print(C - 2*B) in [r'- 2 B + C', r'C -2 B'] assert l._print(C + 2*B) in [r'2 B + C', r'C + 2 B'] assert l._print(B - 2*C) in [r'B - 2 C', r'- 2 C + B'] assert l._print(B + 2*C) in [r'B + 2 C', r'2 C + B'] def test_matMul(): from sympy import MatrixSymbol from sympy.printing.latex import LatexPrinter A = MatrixSymbol('A', 5, 5) B = MatrixSymbol('B', 5, 5) x = Symbol('x') lp = LatexPrinter() assert lp._print_MatMul(2*A) == r'2 A' assert lp._print_MatMul(2*x*A) == r'2 x A' assert lp._print_MatMul(-2*A) == r'- 2 A' assert lp._print_MatMul(1.5*A) == r'1.5 A' assert lp._print_MatMul(sqrt(2)*A) == r'\sqrt{2} A' assert lp._print_MatMul(-sqrt(2)*A) == r'- \sqrt{2} A' assert lp._print_MatMul(2*sqrt(2)*x*A) == r'2 \sqrt{2} x A' assert lp._print_MatMul(-2*A*(A + 2*B)) in [r'- 2 A \left(A + 2 B\right)', r'- 2 A \left(2 B + A\right)'] def test_latex_MatrixSlice(): n = Symbol('n', integer=True) x, y, z, w, t, = symbols('x y z w t') X = MatrixSymbol('X', n, n) Y = MatrixSymbol('Y', 10, 10) Z = MatrixSymbol('Z', 10, 10) assert latex(MatrixSlice(X, (None, None, None), (None, None, None))) == r'X\left[:, :\right]' assert latex(X[x:x + 1, y:y + 1]) == r'X\left[x:x + 1, y:y + 1\right]' assert latex(X[x:x + 1:2, y:y + 1:2]) == r'X\left[x:x + 1:2, y:y + 1:2\right]' assert latex(X[:x, y:]) == r'X\left[:x, y:\right]' assert latex(X[:x, y:]) == r'X\left[:x, y:\right]' assert latex(X[x:, :y]) == r'X\left[x:, :y\right]' assert latex(X[x:y, z:w]) == r'X\left[x:y, z:w\right]' assert latex(X[x:y:t, w:t:x]) == r'X\left[x:y:t, w:t:x\right]' assert latex(X[x::y, t::w]) == r'X\left[x::y, t::w\right]' assert latex(X[:x:y, :t:w]) == r'X\left[:x:y, :t:w\right]' assert latex(X[::x, ::y]) == r'X\left[::x, ::y\right]' assert latex(MatrixSlice(X, (0, None, None), (0, None, None))) == r'X\left[:, :\right]' assert latex(MatrixSlice(X, (None, n, None), (None, n, None))) == r'X\left[:, :\right]' assert latex(MatrixSlice(X, (0, n, None), (0, n, None))) == r'X\left[:, :\right]' assert latex(MatrixSlice(X, (0, n, 2), (0, n, 2))) == r'X\left[::2, ::2\right]' assert latex(X[1:2:3, 4:5:6]) == r'X\left[1:2:3, 4:5:6\right]' assert latex(X[1:3:5, 4:6:8]) == r'X\left[1:3:5, 4:6:8\right]' assert latex(X[1:10:2]) == r'X\left[1:10:2, :\right]' assert latex(Y[:5, 1:9:2]) == r'Y\left[:5, 1:9:2\right]' assert latex(Y[:5, 1:10:2]) == r'Y\left[:5, 1::2\right]' assert latex(Y[5, :5:2]) == r'Y\left[5:6, :5:2\right]' assert latex(X[0:1, 0:1]) == r'X\left[:1, :1\right]' assert latex(X[0:1:2, 0:1:2]) == r'X\left[:1:2, :1:2\right]' assert latex((Y + Z)[2:, 2:]) == r'\left(Y + Z\right)\left[2:, 2:\right]' def test_latex_RandomDomain(): from sympy.stats import Normal, Die, Exponential, pspace, where from sympy.stats.rv import RandomDomain X = Normal('x1', 0, 1) assert latex(where(X > 0)) == r"\text{Domain: }0 < x_{1} \wedge x_{1} < \infty" D = Die('d1', 6) assert latex(where(D > 4)) == r"\text{Domain: }d_{1} = 5 \vee d_{1} = 6" A = Exponential('a', 1) B = Exponential('b', 1) assert latex( pspace(Tuple(A, B)).domain) == \ r"\text{Domain: }0 \leq a \wedge 0 \leq b \wedge a < \infty \wedge b < \infty" assert latex(RandomDomain(FiniteSet(x), FiniteSet(1, 2))) == \ r'\text{Domain: }\left\{x\right\}\text{ in }\left\{1, 2\right\}' def test_PrettyPoly(): from sympy.polys.domains import QQ F = QQ.frac_field(x, y) R = QQ[x, y] assert latex(F.convert(x/(x + y))) == latex(x/(x + y)) assert latex(R.convert(x + y)) == latex(x + y) def test_integral_transforms(): x = Symbol("x") k = Symbol("k") f = Function("f") a = Symbol("a") b = Symbol("b") assert latex(MellinTransform(f(x), x, k)) == \ r"\mathcal{M}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseMellinTransform(f(k), k, x, a, b)) == \ r"\mathcal{M}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(LaplaceTransform(f(x), x, k)) == \ r"\mathcal{L}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseLaplaceTransform(f(k), k, x, (a, b))) == \ r"\mathcal{L}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(FourierTransform(f(x), x, k)) == \ r"\mathcal{F}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseFourierTransform(f(k), k, x)) == \ r"\mathcal{F}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(CosineTransform(f(x), x, k)) == \ r"\mathcal{COS}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseCosineTransform(f(k), k, x)) == \ r"\mathcal{COS}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(SineTransform(f(x), x, k)) == \ r"\mathcal{SIN}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseSineTransform(f(k), k, x)) == \ r"\mathcal{SIN}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" def test_PolynomialRingBase(): from sympy.polys.domains import QQ assert latex(QQ.old_poly_ring(x, y)) == r"\mathbb{Q}\left[x, y\right]" assert latex(QQ.old_poly_ring(x, y, order="ilex")) == \ r"S_<^{-1}\mathbb{Q}\left[x, y\right]" def test_categories(): from sympy.categories import (Object, IdentityMorphism, NamedMorphism, Category, Diagram, DiagramGrid) A1 = Object("A1") A2 = Object("A2") A3 = Object("A3") f1 = NamedMorphism(A1, A2, "f1") f2 = NamedMorphism(A2, A3, "f2") id_A1 = IdentityMorphism(A1) K1 = Category("K1") assert latex(A1) == r"A_{1}" assert latex(f1) == r"f_{1}:A_{1}\rightarrow A_{2}" assert latex(id_A1) == r"id:A_{1}\rightarrow A_{1}" assert latex(f2*f1) == r"f_{2}\circ f_{1}:A_{1}\rightarrow A_{3}" assert latex(K1) == r"\mathbf{K_{1}}" d = Diagram() assert latex(d) == r"\emptyset" d = Diagram({f1: "unique", f2: S.EmptySet}) assert latex(d) == r"\left\{ f_{2}\circ f_{1}:A_{1}" \ r"\rightarrow A_{3} : \emptyset, \ id:A_{1}\rightarrow " \ r"A_{1} : \emptyset, \ id:A_{2}\rightarrow A_{2} : " \ r"\emptyset, \ id:A_{3}\rightarrow A_{3} : \emptyset, " \ r"\ f_{1}:A_{1}\rightarrow A_{2} : \left\{unique\right\}, " \ r"\ f_{2}:A_{2}\rightarrow A_{3} : \emptyset\right\}" d = Diagram({f1: "unique", f2: S.EmptySet}, {f2 * f1: "unique"}) assert latex(d) == r"\left\{ f_{2}\circ f_{1}:A_{1}" \ r"\rightarrow A_{3} : \emptyset, \ id:A_{1}\rightarrow " \ r"A_{1} : \emptyset, \ id:A_{2}\rightarrow A_{2} : " \ r"\emptyset, \ id:A_{3}\rightarrow A_{3} : \emptyset, " \ r"\ f_{1}:A_{1}\rightarrow A_{2} : \left\{unique\right\}," \ r" \ f_{2}:A_{2}\rightarrow A_{3} : \emptyset\right\}" \ r"\Longrightarrow \left\{ f_{2}\circ f_{1}:A_{1}" \ r"\rightarrow A_{3} : \left\{unique\right\}\right\}" # A linear diagram. A = Object("A") B = Object("B") C = Object("C") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") d = Diagram([f, g]) grid = DiagramGrid(d) assert latex(grid) == r"\begin{array}{cc}" + "\n" \ r"A & B \\" + "\n" \ r" & C " + "\n" \ r"\end{array}" + "\n" def test_Modules(): from sympy.polys.domains import QQ from sympy.polys.agca import homomorphism R = QQ.old_poly_ring(x, y) F = R.free_module(2) M = F.submodule([x, y], [1, x**2]) assert latex(F) == r"{\mathbb{Q}\left[x, y\right]}^{2}" assert latex(M) == \ r"\left\langle {\left[ {x},{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle" I = R.ideal(x**2, y) assert latex(I) == r"\left\langle {x^{2}},{y} \right\rangle" Q = F / M assert latex(Q) == \ r"\frac{{\mathbb{Q}\left[x, y\right]}^{2}}{\left\langle {\left[ {x},"\ r"{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle}" assert latex(Q.submodule([1, x**3/2], [2, y])) == \ r"\left\langle {{\left[ {1},{\frac{x^{3}}{2}} \right]} + {\left"\ r"\langle {\left[ {x},{y} \right]},{\left[ {1},{x^{2}} \right]} "\ r"\right\rangle}},{{\left[ {2},{y} \right]} + {\left\langle {\left[ "\ r"{x},{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle}} \right\rangle" h = homomorphism(QQ.old_poly_ring(x).free_module(2), QQ.old_poly_ring(x).free_module(2), [0, 0]) assert latex(h) == \ r"{\left[\begin{matrix}0 & 0\\0 & 0\end{matrix}\right]} : "\ r"{{\mathbb{Q}\left[x\right]}^{2}} \to {{\mathbb{Q}\left[x\right]}^{2}}" def test_QuotientRing(): from sympy.polys.domains import QQ R = QQ.old_poly_ring(x)/[x**2 + 1] assert latex(R) == \ r"\frac{\mathbb{Q}\left[x\right]}{\left\langle {x^{2} + 1} \right\rangle}" assert latex(R.one) == r"{1} + {\left\langle {x^{2} + 1} \right\rangle}" def test_Tr(): #TODO: Handle indices A, B = symbols('A B', commutative=False) t = Tr(A*B) assert latex(t) == r'\operatorname{tr}\left(A B\right)' def test_Adjoint(): from sympy.matrices import MatrixSymbol, Adjoint, Inverse, Transpose X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(Adjoint(X)) == r'X^{\dagger}' assert latex(Adjoint(X + Y)) == r'\left(X + Y\right)^{\dagger}' assert latex(Adjoint(X) + Adjoint(Y)) == r'X^{\dagger} + Y^{\dagger}' assert latex(Adjoint(X*Y)) == r'\left(X Y\right)^{\dagger}' assert latex(Adjoint(Y)*Adjoint(X)) == r'Y^{\dagger} X^{\dagger}' assert latex(Adjoint(X**2)) == r'\left(X^{2}\right)^{\dagger}' assert latex(Adjoint(X)**2) == r'\left(X^{\dagger}\right)^{2}' assert latex(Adjoint(Inverse(X))) == r'\left(X^{-1}\right)^{\dagger}' assert latex(Inverse(Adjoint(X))) == r'\left(X^{\dagger}\right)^{-1}' assert latex(Adjoint(Transpose(X))) == r'\left(X^{T}\right)^{\dagger}' assert latex(Transpose(Adjoint(X))) == r'\left(X^{\dagger}\right)^{T}' assert latex(Transpose(Adjoint(X) + Y)) == r'\left(X^{\dagger} + Y\right)^{T}' def test_Transpose(): from sympy.matrices import Transpose, MatPow, HadamardPower X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(Transpose(X)) == r'X^{T}' assert latex(Transpose(X + Y)) == r'\left(X + Y\right)^{T}' assert latex(Transpose(HadamardPower(X, 2))) == r'\left(X^{\circ {2}}\right)^{T}' assert latex(HadamardPower(Transpose(X), 2)) == r'\left(X^{T}\right)^{\circ {2}}' assert latex(Transpose(MatPow(X, 2))) == r'\left(X^{2}\right)^{T}' assert latex(MatPow(Transpose(X), 2)) == r'\left(X^{T}\right)^{2}' def test_Hadamard(): from sympy.matrices import MatrixSymbol, HadamardProduct, HadamardPower from sympy.matrices.expressions import MatAdd, MatMul, MatPow X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(HadamardProduct(X, Y*Y)) == r'X \circ Y^{2}' assert latex(HadamardProduct(X, Y)*Y) == r'\left(X \circ Y\right) Y' assert latex(HadamardPower(X, 2)) == r'X^{\circ {2}}' assert latex(HadamardPower(X, -1)) == r'X^{\circ \left({-1}\right)}' assert latex(HadamardPower(MatAdd(X, Y), 2)) == \ r'\left(X + Y\right)^{\circ {2}}' assert latex(HadamardPower(MatMul(X, Y), 2)) == \ r'\left(X Y\right)^{\circ {2}}' assert latex(HadamardPower(MatPow(X, -1), -1)) == \ r'\left(X^{-1}\right)^{\circ \left({-1}\right)}' assert latex(MatPow(HadamardPower(X, -1), -1)) == \ r'\left(X^{\circ \left({-1}\right)}\right)^{-1}' assert latex(HadamardPower(X, n+1)) == \ r'X^{\circ \left({n + 1}\right)}' def test_ElementwiseApplyFunction(): from sympy.matrices import MatrixSymbol X = MatrixSymbol('X', 2, 2) expr = (X.T*X).applyfunc(sin) assert latex(expr) == r"{\left( d \mapsto \sin{\left(d \right)} \right)}_{\circ}\left({X^{T} X}\right)" expr = X.applyfunc(Lambda(x, 1/x)) assert latex(expr) == r'{\left( x \mapsto \frac{1}{x} \right)}_{\circ}\left({X}\right)' def test_ZeroMatrix(): from sympy import ZeroMatrix assert latex(ZeroMatrix(1, 1), mat_symbol_style='plain') == r"\mathbb{0}" assert latex(ZeroMatrix(1, 1), mat_symbol_style='bold') == r"\mathbf{0}" def test_OneMatrix(): from sympy import OneMatrix assert latex(OneMatrix(3, 4), mat_symbol_style='plain') == r"\mathbb{1}" assert latex(OneMatrix(3, 4), mat_symbol_style='bold') == r"\mathbf{1}" def test_Identity(): from sympy import Identity assert latex(Identity(1), mat_symbol_style='plain') == r"\mathbb{I}" assert latex(Identity(1), mat_symbol_style='bold') == r"\mathbf{I}" def test_boolean_args_order(): syms = symbols('a:f') expr = And(*syms) assert latex(expr) == r'a \wedge b \wedge c \wedge d \wedge e \wedge f' expr = Or(*syms) assert latex(expr) == r'a \vee b \vee c \vee d \vee e \vee f' expr = Equivalent(*syms) assert latex(expr) == \ r'a \Leftrightarrow b \Leftrightarrow c \Leftrightarrow d \Leftrightarrow e \Leftrightarrow f' expr = Xor(*syms) assert latex(expr) == \ r'a \veebar b \veebar c \veebar d \veebar e \veebar f' def test_imaginary(): i = sqrt(-1) assert latex(i) == r'i' def test_builtins_without_args(): assert latex(sin) == r'\sin' assert latex(cos) == r'\cos' assert latex(tan) == r'\tan' assert latex(log) == r'\log' assert latex(Ei) == r'\operatorname{Ei}' assert latex(zeta) == r'\zeta' def test_latex_greek_functions(): # bug because capital greeks that have roman equivalents should not use # \Alpha, \Beta, \Eta, etc. s = Function('Alpha') assert latex(s) == r'A' assert latex(s(x)) == r'A{\left(x \right)}' s = Function('Beta') assert latex(s) == r'B' s = Function('Eta') assert latex(s) == r'H' assert latex(s(x)) == r'H{\left(x \right)}' # bug because sympy.core.numbers.Pi is special p = Function('Pi') # assert latex(p(x)) == r'\Pi{\left(x \right)}' assert latex(p) == r'\Pi' # bug because not all greeks are included c = Function('chi') assert latex(c(x)) == r'\chi{\left(x \right)}' assert latex(c) == r'\chi' def test_translate(): s = 'Alpha' assert translate(s) == r'A' s = 'Beta' assert translate(s) == r'B' s = 'Eta' assert translate(s) == r'H' s = 'omicron' assert translate(s) == r'o' s = 'Pi' assert translate(s) == r'\Pi' s = 'pi' assert translate(s) == r'\pi' s = 'LamdaHatDOT' assert translate(s) == r'\dot{\hat{\Lambda}}' def test_other_symbols(): from sympy.printing.latex import other_symbols for s in other_symbols: assert latex(symbols(s)) == r"" "\\" + s def test_modifiers(): # Test each modifier individually in the simplest case # (with funny capitalizations) assert latex(symbols("xMathring")) == r"\mathring{x}" assert latex(symbols("xCheck")) == r"\check{x}" assert latex(symbols("xBreve")) == r"\breve{x}" assert latex(symbols("xAcute")) == r"\acute{x}" assert latex(symbols("xGrave")) == r"\grave{x}" assert latex(symbols("xTilde")) == r"\tilde{x}" assert latex(symbols("xPrime")) == r"{x}'" assert latex(symbols("xddDDot")) == r"\ddddot{x}" assert latex(symbols("xDdDot")) == r"\dddot{x}" assert latex(symbols("xDDot")) == r"\ddot{x}" assert latex(symbols("xBold")) == r"\boldsymbol{x}" assert latex(symbols("xnOrM")) == r"\left\|{x}\right\|" assert latex(symbols("xAVG")) == r"\left\langle{x}\right\rangle" assert latex(symbols("xHat")) == r"\hat{x}" assert latex(symbols("xDot")) == r"\dot{x}" assert latex(symbols("xBar")) == r"\bar{x}" assert latex(symbols("xVec")) == r"\vec{x}" assert latex(symbols("xAbs")) == r"\left|{x}\right|" assert latex(symbols("xMag")) == r"\left|{x}\right|" assert latex(symbols("xPrM")) == r"{x}'" assert latex(symbols("xBM")) == r"\boldsymbol{x}" # Test strings that are *only* the names of modifiers assert latex(symbols("Mathring")) == r"Mathring" assert latex(symbols("Check")) == r"Check" assert latex(symbols("Breve")) == r"Breve" assert latex(symbols("Acute")) == r"Acute" assert latex(symbols("Grave")) == r"Grave" assert latex(symbols("Tilde")) == r"Tilde" assert latex(symbols("Prime")) == r"Prime" assert latex(symbols("DDot")) == r"\dot{D}" assert latex(symbols("Bold")) == r"Bold" assert latex(symbols("NORm")) == r"NORm" assert latex(symbols("AVG")) == r"AVG" assert latex(symbols("Hat")) == r"Hat" assert latex(symbols("Dot")) == r"Dot" assert latex(symbols("Bar")) == r"Bar" assert latex(symbols("Vec")) == r"Vec" assert latex(symbols("Abs")) == r"Abs" assert latex(symbols("Mag")) == r"Mag" assert latex(symbols("PrM")) == r"PrM" assert latex(symbols("BM")) == r"BM" assert latex(symbols("hbar")) == r"\hbar" # Check a few combinations assert latex(symbols("xvecdot")) == r"\dot{\vec{x}}" assert latex(symbols("xDotVec")) == r"\vec{\dot{x}}" assert latex(symbols("xHATNorm")) == r"\left\|{\hat{x}}\right\|" # Check a couple big, ugly combinations assert latex(symbols('xMathringBm_yCheckPRM__zbreveAbs')) == \ r"\boldsymbol{\mathring{x}}^{\left|{\breve{z}}\right|}_{{\check{y}}'}" assert latex(symbols('alphadothat_nVECDOT__tTildePrime')) == \ r"\hat{\dot{\alpha}}^{{\tilde{t}}'}_{\dot{\vec{n}}}" def test_greek_symbols(): assert latex(Symbol('alpha')) == r'\alpha' assert latex(Symbol('beta')) == r'\beta' assert latex(Symbol('gamma')) == r'\gamma' assert latex(Symbol('delta')) == r'\delta' assert latex(Symbol('epsilon')) == r'\epsilon' assert latex(Symbol('zeta')) == r'\zeta' assert latex(Symbol('eta')) == r'\eta' assert latex(Symbol('theta')) == r'\theta' assert latex(Symbol('iota')) == r'\iota' assert latex(Symbol('kappa')) == r'\kappa' assert latex(Symbol('lambda')) == r'\lambda' assert latex(Symbol('mu')) == r'\mu' assert latex(Symbol('nu')) == r'\nu' assert latex(Symbol('xi')) == r'\xi' assert latex(Symbol('omicron')) == r'o' assert latex(Symbol('pi')) == r'\pi' assert latex(Symbol('rho')) == r'\rho' assert latex(Symbol('sigma')) == r'\sigma' assert latex(Symbol('tau')) == r'\tau' assert latex(Symbol('upsilon')) == r'\upsilon' assert latex(Symbol('phi')) == r'\phi' assert latex(Symbol('chi')) == r'\chi' assert latex(Symbol('psi')) == r'\psi' assert latex(Symbol('omega')) == r'\omega' assert latex(Symbol('Alpha')) == r'A' assert latex(Symbol('Beta')) == r'B' assert latex(Symbol('Gamma')) == r'\Gamma' assert latex(Symbol('Delta')) == r'\Delta' assert latex(Symbol('Epsilon')) == r'E' assert latex(Symbol('Zeta')) == r'Z' assert latex(Symbol('Eta')) == r'H' assert latex(Symbol('Theta')) == r'\Theta' assert latex(Symbol('Iota')) == r'I' assert latex(Symbol('Kappa')) == r'K' assert latex(Symbol('Lambda')) == r'\Lambda' assert latex(Symbol('Mu')) == r'M' assert latex(Symbol('Nu')) == r'N' assert latex(Symbol('Xi')) == r'\Xi' assert latex(Symbol('Omicron')) == r'O' assert latex(Symbol('Pi')) == r'\Pi' assert latex(Symbol('Rho')) == r'P' assert latex(Symbol('Sigma')) == r'\Sigma' assert latex(Symbol('Tau')) == r'T' assert latex(Symbol('Upsilon')) == r'\Upsilon' assert latex(Symbol('Phi')) == r'\Phi' assert latex(Symbol('Chi')) == r'X' assert latex(Symbol('Psi')) == r'\Psi' assert latex(Symbol('Omega')) == r'\Omega' assert latex(Symbol('varepsilon')) == r'\varepsilon' assert latex(Symbol('varkappa')) == r'\varkappa' assert latex(Symbol('varphi')) == r'\varphi' assert latex(Symbol('varpi')) == r'\varpi' assert latex(Symbol('varrho')) == r'\varrho' assert latex(Symbol('varsigma')) == r'\varsigma' assert latex(Symbol('vartheta')) == r'\vartheta' def test_fancyset_symbols(): assert latex(S.Rationals) == r'\mathbb{Q}' assert latex(S.Naturals) == r'\mathbb{N}' assert latex(S.Naturals0) == r'\mathbb{N}_0' assert latex(S.Integers) == r'\mathbb{Z}' assert latex(S.Reals) == r'\mathbb{R}' assert latex(S.Complexes) == r'\mathbb{C}' @XFAIL def test_builtin_without_args_mismatched_names(): assert latex(CosineTransform) == r'\mathcal{COS}' def test_builtin_no_args(): assert latex(Chi) == r'\operatorname{Chi}' assert latex(beta) == r'\operatorname{B}' assert latex(gamma) == r'\Gamma' assert latex(KroneckerDelta) == r'\delta' assert latex(DiracDelta) == r'\delta' assert latex(lowergamma) == r'\gamma' def test_issue_6853(): p = Function('Pi') assert latex(p(x)) == r"\Pi{\left(x \right)}" def test_Mul(): e = Mul(-2, x + 1, evaluate=False) assert latex(e) == r'- 2 \left(x + 1\right)' e = Mul(2, x + 1, evaluate=False) assert latex(e) == r'2 \left(x + 1\right)' e = Mul(S.Half, x + 1, evaluate=False) assert latex(e) == r'\frac{x + 1}{2}' e = Mul(y, x + 1, evaluate=False) assert latex(e) == r'y \left(x + 1\right)' e = Mul(-y, x + 1, evaluate=False) assert latex(e) == r'- y \left(x + 1\right)' e = Mul(-2, x + 1) assert latex(e) == r'- 2 x - 2' e = Mul(2, x + 1) assert latex(e) == r'2 x + 2' def test_Pow(): e = Pow(2, 2, evaluate=False) assert latex(e) == r'2^{2}' assert latex(x**(Rational(-1, 3))) == r'\frac{1}{\sqrt[3]{x}}' x2 = Symbol(r'x^2') assert latex(x2**2) == r'\left(x^{2}\right)^{2}' def test_issue_7180(): assert latex(Equivalent(x, y)) == r"x \Leftrightarrow y" assert latex(Not(Equivalent(x, y))) == r"x \not\Leftrightarrow y" def test_issue_8409(): assert latex(S.Half**n) == r"\left(\frac{1}{2}\right)^{n}" def test_issue_8470(): from sympy.parsing.sympy_parser import parse_expr e = parse_expr("-B*A", evaluate=False) assert latex(e) == r"A \left(- B\right)" def test_issue_15439(): x = MatrixSymbol('x', 2, 2) y = MatrixSymbol('y', 2, 2) assert latex((x * y).subs(y, -y)) == r"x \left(- y\right)" assert latex((x * y).subs(y, -2*y)) == r"x \left(- 2 y\right)" assert latex((x * y).subs(x, -x)) == r"- x y" def test_issue_2934(): assert latex(Symbol(r'\frac{a_1}{b_1}')) == r'\frac{a_1}{b_1}' def test_issue_10489(): latexSymbolWithBrace = r'C_{x_{0}}' s = Symbol(latexSymbolWithBrace) assert latex(s) == latexSymbolWithBrace assert latex(cos(s)) == r'\cos{\left(C_{x_{0}} \right)}' def test_issue_12886(): m__1, l__1 = symbols('m__1, l__1') assert latex(m__1**2 + l__1**2) == \ r'\left(l^{1}\right)^{2} + \left(m^{1}\right)^{2}' def test_issue_13559(): from sympy.parsing.sympy_parser import parse_expr expr = parse_expr('5/1', evaluate=False) assert latex(expr) == r"\frac{5}{1}" def test_issue_13651(): expr = c + Mul(-1, a + b, evaluate=False) assert latex(expr) == r"c - \left(a + b\right)" def test_latex_UnevaluatedExpr(): x = symbols("x") he = UnevaluatedExpr(1/x) assert latex(he) == latex(1/x) == r"\frac{1}{x}" assert latex(he**2) == r"\left(\frac{1}{x}\right)^{2}" assert latex(he + 1) == r"1 + \frac{1}{x}" assert latex(x*he) == r"x \frac{1}{x}" def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert latex(A[0, 0]) == r"A_{0, 0}" assert latex(3 * A[0, 0]) == r"3 A_{0, 0}" F = C[0, 0].subs(C, A - B) assert latex(F) == r"\left(A - B\right)_{0, 0}" i, j, k = symbols("i j k") M = MatrixSymbol("M", k, k) N = MatrixSymbol("N", k, k) assert latex((M*N)[i, j]) == \ r'\sum_{i_{1}=0}^{k - 1} M_{i, i_{1}} N_{i_{1}, j}' def test_MatrixSymbol_printing(): # test cases for issue #14237 A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert latex(-A) == r"- A" assert latex(A - A*B - B) == r"A - A B - B" assert latex(-A*B - A*B*C - B) == r"- A B - A B C - B" def test_KroneckerProduct_printing(): A = MatrixSymbol('A', 3, 3) B = MatrixSymbol('B', 2, 2) assert latex(KroneckerProduct(A, B)) == r'A \otimes B' def test_Series_printing(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y) assert latex(Series(tf1, tf2)) == \ r'\left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right) \left(\frac{x - y}{x + y}\right)' assert latex(Series(tf1, tf2, tf3)) == \ r'\left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right) \left(\frac{x - y}{x + y}\right) \left(\frac{t x^{2} - t^{w} x + w}{t - y}\right)' assert latex(Series(-tf2, tf1)) == \ r'\left(\frac{- x + y}{x + y}\right) \left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right)' M_1 = Matrix([[5/s], [5/(2*s)]]) T_1 = TransferFunctionMatrix.from_Matrix(M_1, s) M_2 = Matrix([[5, 6*s**3]]) T_2 = TransferFunctionMatrix.from_Matrix(M_2, s) # Brackets assert latex(T_1*(T_2 + T_2)) == \ r'\left[\begin{matrix}\frac{5}{s}\\\frac{5}{2 s}\end{matrix}\right]_\tau\cdot\left(\left[\begin{matrix}\frac{5}{1} &' \ r' \frac{6 s^{3}}{1}\end{matrix}\right]_\tau + \left[\begin{matrix}\frac{5}{1} & \frac{6 s^{3}}{1}\end{matrix}\right]_\tau\right)' \ == latex(MIMOSeries(MIMOParallel(T_2, T_2), T_1)) # No Brackets M_3 = Matrix([[5, 6], [6, 5/s]]) T_3 = TransferFunctionMatrix.from_Matrix(M_3, s) assert latex(T_1*T_2 + T_3) == r'\left[\begin{matrix}\frac{5}{s}\\\frac{5}{2 s}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}' \ r'\frac{5}{1} & \frac{6 s^{3}}{1}\end{matrix}\right]_\tau + \left[\begin{matrix}\frac{5}{1} & \frac{6}{1}\\\frac{6}{1} & ' \ r'\frac{5}{s}\end{matrix}\right]_\tau' == latex(MIMOParallel(MIMOSeries(T_2, T_1), T_3)) def test_TransferFunction_printing(): tf1 = TransferFunction(x - 1, x + 1, x) assert latex(tf1) == r"\frac{x - 1}{x + 1}" tf2 = TransferFunction(x + 1, 2 - y, x) assert latex(tf2) == r"\frac{x + 1}{2 - y}" tf3 = TransferFunction(y, y**2 + 2*y + 3, y) assert latex(tf3) == r"\frac{y}{y^{2} + 2 y + 3}" def test_Parallel_printing(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) assert latex(Parallel(tf1, tf2)) == \ r'\frac{x y^{2} - z}{- t^{3} + y^{3}} + \frac{x - y}{x + y}' assert latex(Parallel(-tf2, tf1)) == \ r'\frac{- x + y}{x + y} + \frac{x y^{2} - z}{- t^{3} + y^{3}}' M_1 = Matrix([[5, 6], [6, 5/s]]) T_1 = TransferFunctionMatrix.from_Matrix(M_1, s) M_2 = Matrix([[5/s, 6], [6, 5/(s - 1)]]) T_2 = TransferFunctionMatrix.from_Matrix(M_2, s) M_3 = Matrix([[6, 5/(s*(s - 1))], [5, 6]]) T_3 = TransferFunctionMatrix.from_Matrix(M_3, s) assert latex(T_1 + T_2 + T_3) == r'\left[\begin{matrix}\frac{5}{1} & \frac{6}{1}\\\frac{6}{1} & \frac{5}{s}\end{matrix}\right]' \ r'_\tau + \left[\begin{matrix}\frac{5}{s} & \frac{6}{1}\\\frac{6}{1} & \frac{5}{s - 1}\end{matrix}\right]_\tau + \left[\begin{matrix}' \ r'\frac{6}{1} & \frac{5}{s \left(s - 1\right)}\\\frac{5}{1} & \frac{6}{1}\end{matrix}\right]_\tau' \ == latex(MIMOParallel(T_1, T_2, T_3)) == latex(MIMOParallel(T_1, MIMOParallel(T_2, T_3))) == latex(MIMOParallel(MIMOParallel(T_1, T_2), T_3)) def test_TransferFunctionMatrix_printing(): tf1 = TransferFunction(p, p + x, p) tf2 = TransferFunction(-s + p, p + s, p) tf3 = TransferFunction(p, y**2 + 2*y + 3, p) assert latex(TransferFunctionMatrix([[tf1], [tf2]])) == \ r'\left[\begin{matrix}\frac{p}{p + x}\\\frac{p - s}{p + s}\end{matrix}\right]_\tau' assert latex(TransferFunctionMatrix([[tf1, tf2], [tf3, -tf1]])) == \ r'\left[\begin{matrix}\frac{p}{p + x} & \frac{p - s}{p + s}\\\frac{p}{y^{2} + 2 y + 3} & \frac{\left(-1\right) p}{p + x}\end{matrix}\right]_\tau' def test_Feedback_printing(): tf1 = TransferFunction(p, p + x, p) tf2 = TransferFunction(-s + p, p + s, p) # Negative Feedback (Default) assert latex(Feedback(tf1, tf2)) == \ r'\frac{\frac{p}{p + x}}{\frac{1}{1} + \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}' assert latex(Feedback(tf1*tf2, TransferFunction(1, 1, p))) == \ r'\frac{\left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}{\frac{1}{1} + \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}' # Positive Feedback assert latex(Feedback(tf1, tf2, 1)) == \ r'\frac{\frac{p}{p + x}}{\frac{1}{1} - \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}' assert latex(Feedback(tf1*tf2, sign=1)) == \ r'\frac{\left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}{\frac{1}{1} - \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}' def test_MIMOFeedback_printing(): tf1 = TransferFunction(1, s, s) tf2 = TransferFunction(s, s**2 - 1, s) tf3 = TransferFunction(s, s - 1, s) tf4 = TransferFunction(s**2, s**2 - 1, s) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]]) tfm_2 = TransferFunctionMatrix([[tf4, tf3], [tf2, tf1]]) # Negative Feedback (Default) assert latex(MIMOFeedback(tfm_1, tfm_2)) == \ r'\left(I_{\tau} + \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left[' \ r'\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1} & \frac{1}{s}\end{matrix}\right]_\tau\right)^{-1} \cdot \left[\begin{matrix}' \ r'\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau' # Positive Feedback assert latex(MIMOFeedback(tfm_1*tfm_2, tfm_1, 1)) == \ r'\left(I_{\tau} - \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left' \ r'[\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1} & \frac{1}{s}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}' \ r'\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\right)^{-1} \cdot \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}' \ r'\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1}' \ r' & \frac{1}{s}\end{matrix}\right]_\tau' def test_Quaternion_latex_printing(): q = Quaternion(x, y, z, t) assert latex(q) == r"x + y i + z j + t k" q = Quaternion(x, y, z, x*t) assert latex(q) == r"x + y i + z j + t x k" q = Quaternion(x, y, z, x + t) assert latex(q) == r"x + y i + z j + \left(t + x\right) k" def test_TensorProduct_printing(): from sympy.tensor.functions import TensorProduct A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) assert latex(TensorProduct(A, B)) == r"A \otimes B" def test_WedgeProduct_printing(): from sympy.diffgeom.rn import R2 from sympy.diffgeom import WedgeProduct wp = WedgeProduct(R2.dx, R2.dy) assert latex(wp) == r"\operatorname{d}x \wedge \operatorname{d}y" def test_issue_9216(): expr_1 = Pow(1, -1, evaluate=False) assert latex(expr_1) == r"1^{-1}" expr_2 = Pow(1, Pow(1, -1, evaluate=False), evaluate=False) assert latex(expr_2) == r"1^{1^{-1}}" expr_3 = Pow(3, -2, evaluate=False) assert latex(expr_3) == r"\frac{1}{9}" expr_4 = Pow(1, -2, evaluate=False) assert latex(expr_4) == r"1^{-2}" def test_latex_printer_tensor(): from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, tensor_heads L = TensorIndexType("L") i, j, k, l = tensor_indices("i j k l", L) i0 = tensor_indices("i_0", L) A, B, C, D = tensor_heads("A B C D", [L]) H = TensorHead("H", [L, L]) K = TensorHead("K", [L, L, L, L]) assert latex(i) == r"{}^{i}" assert latex(-i) == r"{}_{i}" expr = A(i) assert latex(expr) == r"A{}^{i}" expr = A(i0) assert latex(expr) == r"A{}^{i_{0}}" expr = A(-i) assert latex(expr) == r"A{}_{i}" expr = -3*A(i) assert latex(expr) == r"-3A{}^{i}" expr = K(i, j, -k, -i0) assert latex(expr) == r"K{}^{ij}{}_{ki_{0}}" expr = K(i, -j, -k, i0) assert latex(expr) == r"K{}^{i}{}_{jk}{}^{i_{0}}" expr = K(i, -j, k, -i0) assert latex(expr) == r"K{}^{i}{}_{j}{}^{k}{}_{i_{0}}" expr = H(i, -j) assert latex(expr) == r"H{}^{i}{}_{j}" expr = H(i, j) assert latex(expr) == r"H{}^{ij}" expr = H(-i, -j) assert latex(expr) == r"H{}_{ij}" expr = (1+x)*A(i) assert latex(expr) == r"\left(x + 1\right)A{}^{i}" expr = H(i, -i) assert latex(expr) == r"H{}^{L_{0}}{}_{L_{0}}" expr = H(i, -j)*A(j)*B(k) assert latex(expr) == r"H{}^{i}{}_{L_{0}}A{}^{L_{0}}B{}^{k}" expr = A(i) + 3*B(i) assert latex(expr) == r"3B{}^{i} + A{}^{i}" # Test ``TensorElement``: from sympy.tensor.tensor import TensorElement expr = TensorElement(K(i, j, k, l), {i: 3, k: 2}) assert latex(expr) == r'K{}^{i=3,j,k=2,l}' expr = TensorElement(K(i, j, k, l), {i: 3}) assert latex(expr) == r'K{}^{i=3,jkl}' expr = TensorElement(K(i, -j, k, l), {i: 3, k: 2}) assert latex(expr) == r'K{}^{i=3}{}_{j}{}^{k=2,l}' expr = TensorElement(K(i, -j, k, -l), {i: 3, k: 2}) assert latex(expr) == r'K{}^{i=3}{}_{j}{}^{k=2}{}_{l}' expr = TensorElement(K(i, j, -k, -l), {i: 3, -k: 2}) assert latex(expr) == r'K{}^{i=3,j}{}_{k=2,l}' expr = TensorElement(K(i, j, -k, -l), {i: 3}) assert latex(expr) == r'K{}^{i=3,j}{}_{kl}' expr = PartialDerivative(A(i), A(i)) assert latex(expr) == r"\frac{\partial}{\partial {A{}^{L_{0}}}}{A{}^{L_{0}}}" expr = PartialDerivative(A(-i), A(-j)) assert latex(expr) == r"\frac{\partial}{\partial {A{}_{j}}}{A{}_{i}}" expr = PartialDerivative(K(i, j, -k, -l), A(m), A(-n)) assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}^{m}} \partial {A{}_{n}}}{K{}^{ij}{}_{kl}}" expr = PartialDerivative(B(-i) + A(-i), A(-j), A(-n)) assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}_{j}} \partial {A{}_{n}}}{\left(A{}_{i} + B{}_{i}\right)}" expr = PartialDerivative(3*A(-i), A(-j), A(-n)) assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}_{j}} \partial {A{}_{n}}}{\left(3A{}_{i}\right)}" def test_multiline_latex(): a, b, c, d, e, f = symbols('a b c d e f') expr = -a + 2*b -3*c +4*d -5*e expected = r"\begin{eqnarray}" + "\n"\ r"f & = &- a \nonumber\\" + "\n"\ r"& & + 2 b \nonumber\\" + "\n"\ r"& & - 3 c \nonumber\\" + "\n"\ r"& & + 4 d \nonumber\\" + "\n"\ r"& & - 5 e " + "\n"\ r"\end{eqnarray}" assert multiline_latex(f, expr, environment="eqnarray") == expected expected2 = r'\begin{eqnarray}' + '\n'\ r'f & = &- a + 2 b \nonumber\\' + '\n'\ r'& & - 3 c + 4 d \nonumber\\' + '\n'\ r'& & - 5 e ' + '\n'\ r'\end{eqnarray}' assert multiline_latex(f, expr, 2, environment="eqnarray") == expected2 expected3 = r'\begin{eqnarray}' + '\n'\ r'f & = &- a + 2 b - 3 c \nonumber\\'+ '\n'\ r'& & + 4 d - 5 e ' + '\n'\ r'\end{eqnarray}' assert multiline_latex(f, expr, 3, environment="eqnarray") == expected3 expected3dots = r'\begin{eqnarray}' + '\n'\ r'f & = &- a + 2 b - 3 c \dots\nonumber\\'+ '\n'\ r'& & + 4 d - 5 e ' + '\n'\ r'\end{eqnarray}' assert multiline_latex(f, expr, 3, environment="eqnarray", use_dots=True) == expected3dots expected3align = r'\begin{align*}' + '\n'\ r'f = &- a + 2 b - 3 c \\'+ '\n'\ r'& + 4 d - 5 e ' + '\n'\ r'\end{align*}' assert multiline_latex(f, expr, 3) == expected3align assert multiline_latex(f, expr, 3, environment='align*') == expected3align expected2ieee = r'\begin{IEEEeqnarray}{rCl}' + '\n'\ r'f & = &- a + 2 b \nonumber\\' + '\n'\ r'& & - 3 c + 4 d \nonumber\\' + '\n'\ r'& & - 5 e ' + '\n'\ r'\end{IEEEeqnarray}' assert multiline_latex(f, expr, 2, environment="IEEEeqnarray") == expected2ieee raises(ValueError, lambda: multiline_latex(f, expr, environment="foo")) def test_issue_15353(): from sympy import ConditionSet, Tuple, S, sin, cos a, x = symbols('a x') # Obtained from nonlinsolve([(sin(a*x)),cos(a*x)],[x,a]) sol = ConditionSet( Tuple(x, a), Eq(sin(a*x), 0) & Eq(cos(a*x), 0), S.Complexes**2) assert latex(sol) == \ r'\left\{\left( x, \ a\right)\; \middle|\; \left( x, \ a\right) \in ' \ r'\mathbb{C}^{2} \wedge \sin{\left(a x \right)} = 0 \wedge ' \ r'\cos{\left(a x \right)} = 0 \right\}' def test_trace(): # Issue 15303 from sympy import trace A = MatrixSymbol("A", 2, 2) assert latex(trace(A)) == r"\operatorname{tr}\left(A \right)" assert latex(trace(A**2)) == r"\operatorname{tr}\left(A^{2} \right)" def test_print_basic(): # Issue 15303 from sympy import Basic, Expr # dummy class for testing printing where the function is not # implemented in latex.py class UnimplementedExpr(Expr): def __new__(cls, e): return Basic.__new__(cls, e) # dummy function for testing def unimplemented_expr(expr): return UnimplementedExpr(expr).doit() # override class name to use superscript / subscript def unimplemented_expr_sup_sub(expr): result = UnimplementedExpr(expr) result.__class__.__name__ = 'UnimplementedExpr_x^1' return result assert latex(unimplemented_expr(x)) == r'UnimplementedExpr\left(x\right)' assert latex(unimplemented_expr(x**2)) == \ r'UnimplementedExpr\left(x^{2}\right)' assert latex(unimplemented_expr_sup_sub(x)) == \ r'UnimplementedExpr^{1}_{x}\left(x\right)' def test_MatrixSymbol_bold(): # Issue #15871 from sympy import trace A = MatrixSymbol("A", 2, 2) assert latex(trace(A), mat_symbol_style='bold') == \ r"\operatorname{tr}\left(\mathbf{A} \right)" assert latex(trace(A), mat_symbol_style='plain') == \ r"\operatorname{tr}\left(A \right)" A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert latex(-A, mat_symbol_style='bold') == r"- \mathbf{A}" assert latex(A - A*B - B, mat_symbol_style='bold') == \ r"\mathbf{A} - \mathbf{A} \mathbf{B} - \mathbf{B}" assert latex(-A*B - A*B*C - B, mat_symbol_style='bold') == \ r"- \mathbf{A} \mathbf{B} - \mathbf{A} \mathbf{B} \mathbf{C} - \mathbf{B}" A_k = MatrixSymbol("A_k", 3, 3) assert latex(A_k, mat_symbol_style='bold') == r"\mathbf{A}_{k}" A = MatrixSymbol(r"\nabla_k", 3, 3) assert latex(A, mat_symbol_style='bold') == r"\mathbf{\nabla}_{k}" def test_AppliedPermutation(): p = Permutation(0, 1, 2) x = Symbol('x') assert latex(AppliedPermutation(p, x)) == \ r'\sigma_{\left( 0\; 1\; 2\right)}(x)' def test_PermutationMatrix(): p = Permutation(0, 1, 2) assert latex(PermutationMatrix(p)) == r'P_{\left( 0\; 1\; 2\right)}' p = Permutation(0, 3)(1, 2) assert latex(PermutationMatrix(p)) == \ r'P_{\left( 0\; 3\right)\left( 1\; 2\right)}' def test_imaginary_unit(): assert latex(1 + I) == r'1 + i' assert latex(1 + I, imaginary_unit='i') == r'1 + i' assert latex(1 + I, imaginary_unit='j') == r'1 + j' assert latex(1 + I, imaginary_unit='foo') == r'1 + foo' assert latex(I, imaginary_unit="ti") == r'\text{i}' assert latex(I, imaginary_unit="tj") == r'\text{j}' def test_text_re_im(): assert latex(im(x), gothic_re_im=True) == r'\Im{\left(x\right)}' assert latex(im(x), gothic_re_im=False) == r'\operatorname{im}{\left(x\right)}' assert latex(re(x), gothic_re_im=True) == r'\Re{\left(x\right)}' assert latex(re(x), gothic_re_im=False) == r'\operatorname{re}{\left(x\right)}' def test_latex_diffgeom(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential from sympy.diffgeom.rn import R2 x,y = symbols('x y', real=True) m = Manifold('M', 2) assert latex(m) == r'\text{M}' p = Patch('P', m) assert latex(p) == r'\text{P}_{\text{M}}' rect = CoordSystem('rect', p, [x, y]) assert latex(rect) == r'\text{rect}^{\text{P}}_{\text{M}}' b = BaseScalarField(rect, 0) assert latex(b) == r'\mathbf{x}' g = Function('g') s_field = g(R2.x, R2.y) assert latex(Differential(s_field)) == \ r'\operatorname{d}\left(g{\left(\mathbf{x},\mathbf{y} \right)}\right)' def test_unit_printing(): assert latex(5*meter) == r'5 \text{m}' assert latex(3*gibibyte) == r'3 \text{gibibyte}' assert latex(4*microgram/second) == r'\frac{4 \mu\text{g}}{\text{s}}' def test_issue_17092(): x_star = Symbol('x^*') assert latex(Derivative(x_star, x_star,2)) == r'\frac{d^{2}}{d \left(x^{*}\right)^{2}} x^{*}' def test_latex_decimal_separator(): x, y, z, t = symbols('x y z t') k, m, n = symbols('k m n', integer=True) f, g, h = symbols('f g h', cls=Function) # comma decimal_separator assert(latex([1, 2.3, 4.5], decimal_separator='comma') == r'\left[ 1; \ 2{,}3; \ 4{,}5\right]') assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='comma') == r'\left\{1; 2{,}3; 4{,}5\right\}') assert(latex((1, 2.3, 4.6), decimal_separator = 'comma') == r'\left( 1; \ 2{,}3; \ 4{,}6\right)') assert(latex((1,), decimal_separator='comma') == r'\left( 1;\right)') # period decimal_separator assert(latex([1, 2.3, 4.5], decimal_separator='period') == r'\left[ 1, \ 2.3, \ 4.5\right]' ) assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='period') == r'\left\{1, 2.3, 4.5\right\}') assert(latex((1, 2.3, 4.6), decimal_separator = 'period') == r'\left( 1, \ 2.3, \ 4.6\right)') assert(latex((1,), decimal_separator='period') == r'\left( 1,\right)') # default decimal_separator assert(latex([1, 2.3, 4.5]) == r'\left[ 1, \ 2.3, \ 4.5\right]') assert(latex(FiniteSet(1, 2.3, 4.5)) == r'\left\{1, 2.3, 4.5\right\}') assert(latex((1, 2.3, 4.6)) == r'\left( 1, \ 2.3, \ 4.6\right)') assert(latex((1,)) == r'\left( 1,\right)') assert(latex(Mul(3.4,5.3), decimal_separator = 'comma') == r'18{,}02') assert(latex(3.4*5.3, decimal_separator = 'comma') == r'18{,}02') x = symbols('x') y = symbols('y') z = symbols('z') assert(latex(x*5.3 + 2**y**3.4 + 4.5 + z, decimal_separator = 'comma') == r'2^{y^{3{,}4}} + 5{,}3 x + z + 4{,}5') assert(latex(0.987, decimal_separator='comma') == r'0{,}987') assert(latex(S(0.987), decimal_separator='comma') == r'0{,}987') assert(latex(.3, decimal_separator='comma') == r'0{,}3') assert(latex(S(.3), decimal_separator='comma') == r'0{,}3') assert(latex(5.8*10**(-7), decimal_separator='comma') == r'5{,}8 \cdot 10^{-7}') assert(latex(S(5.7)*10**(-7), decimal_separator='comma') == r'5{,}7 \cdot 10^{-7}') assert(latex(S(5.7*10**(-7)), decimal_separator='comma') == r'5{,}7 \cdot 10^{-7}') x = symbols('x') assert(latex(1.2*x+3.4, decimal_separator='comma') == r'1{,}2 x + 3{,}4') assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='period') == r'\left\{1, 2.3, 4.5\right\}') # Error Handling tests raises(ValueError, lambda: latex([1,2.3,4.5], decimal_separator='non_existing_decimal_separator_in_list')) raises(ValueError, lambda: latex(FiniteSet(1,2.3,4.5), decimal_separator='non_existing_decimal_separator_in_set')) raises(ValueError, lambda: latex((1,2.3,4.5), decimal_separator='non_existing_decimal_separator_in_tuple')) def test_Str(): from sympy.core.symbol import Str assert str(Str('x')) == r'x' def test_latex_escape(): assert latex_escape(r"~^\&%$#_{}") == "".join([ r'\textasciitilde', r'\textasciicircum', r'\textbackslash', r'\&', r'\%', r'\$', r'\#', r'\_', r'\{', r'\}', ]) def test_emptyPrinter(): class MyObject: def __repr__(self): return "<MyObject with {...}>" # unknown objects are monospaced assert latex(MyObject()) == r"\mathtt{\text{<MyObject with \{...\}>}}" # even if they are nested within other objects assert latex((MyObject(),)) == r"\left( \mathtt{\text{<MyObject with \{...\}>}},\right)" def test_global_settings(): import inspect # settings should be visible in the signature of `latex` assert inspect.signature(latex).parameters['imaginary_unit'].default == r'i' assert latex(I) == r'i' try: # but changing the defaults... LatexPrinter.set_global_settings(imaginary_unit='j') # ... should change the signature assert inspect.signature(latex).parameters['imaginary_unit'].default == r'j' assert latex(I) == r'j' finally: # there's no public API to undo this, but we need to make sure we do # so as not to impact other tests del LatexPrinter._global_settings['imaginary_unit'] # check we really did undo it assert inspect.signature(latex).parameters['imaginary_unit'].default == r'i' assert latex(I) == r'i' def test_pickleable(): # this tests that the _PrintFunction instance is pickleable import pickle assert pickle.loads(pickle.dumps(latex)) is latex def test_printing_latex_array_expressions(): assert latex(ArraySymbol("A", 2, 3, 4)) == "A" assert latex(ArrayElement("A", (2, 1/(1-x), 0))) == "{{A}_{2, \\frac{1}{1 - x}, 0}}"
a5040c59b402162d89564c183331680dd13c7843d434aebb62279c7ea42de2e9
# -*- coding: utf-8 -*- from sympy import ( Add, And, Basic, Derivative, Dict, Eq, Equivalent, FF, FiniteSet, Function, Ge, Gt, I, Implies, Integral, SingularityFunction, Lambda, Le, Limit, Lt, Matrix, Mul, Nand, Ne, Nor, Not, O, Or, Pow, Product, QQ, RR, Rational, Ray, rootof, RootSum, S, Segment, Subs, Sum, Symbol, Tuple, Trace, Xor, ZZ, conjugate, groebner, oo, pi, symbols, ilex, grlex, Range, Contains, SeqPer, SeqFormula, SeqAdd, SeqMul, fourier_series, fps, ITE, Complement, Interval, Intersection, Union, EulerGamma, GoldenRatio, LambertW, airyai, airybi, airyaiprime, airybiprime, fresnelc, fresnels, Heaviside, dirichlet_eta, diag, MatrixSlice) from sympy.codegen.ast import (Assignment, AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment, DivAugmentedAssignment, ModAugmentedAssignment) from sympy.core.expr import UnevaluatedExpr from sympy.core.trace import Tr from sympy.functions import (Abs, Chi, Ci, Ei, KroneckerDelta, Piecewise, Shi, Si, atan2, beta, binomial, catalan, ceiling, cos, euler, exp, expint, factorial, factorial2, floor, gamma, hyper, log, meijerg, sin, sqrt, subfactorial, tan, uppergamma, lerchphi, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, DiracDelta, bell, bernoulli, fibonacci, tribonacci, lucas, stieltjes, mathieuc, mathieus, mathieusprime, mathieucprime) from sympy.matrices import Adjoint, Inverse, MatrixSymbol, Transpose, KroneckerProduct from sympy.matrices.expressions import hadamard_power from sympy.physics import mechanics from sympy.physics.control.lti import (TransferFunction, Feedback, TransferFunctionMatrix, Series, Parallel, MIMOSeries, MIMOParallel, MIMOFeedback) from sympy.physics.units import joule, degree from sympy.printing.pretty import pprint, pretty as xpretty from sympy.printing.pretty.pretty_symbology import center_accent, is_combining from sympy import ConditionSet from sympy.sets import ImageSet, ProductSet from sympy.sets.setexpr import SetExpr from sympy.tensor.array import (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray, tensorproduct) from sympy.tensor.functions import TensorProduct from sympy.tensor.tensor import (TensorIndexType, tensor_indices, TensorHead, TensorElement, tensor_heads) from sympy.testing.pytest import raises, _both_exp_pow from sympy.vector import CoordSys3D, Gradient, Curl, Divergence, Dot, Cross, Laplacian import sympy as sym class lowergamma(sym.lowergamma): pass # testing notation inheritance by a subclass with same name a, b, c, d, x, y, z, k, n, s, p = symbols('a,b,c,d,x,y,z,k,n,s,p') f = Function("f") th = Symbol('theta') ph = Symbol('phi') """ Expressions whose pretty-printing is tested here: (A '#' to the right of an expression indicates that its various acceptable orderings are accounted for by the tests.) BASIC EXPRESSIONS: oo (x**2) 1/x y*x**-2 x**Rational(-5,2) (-2)**x Pow(3, 1, evaluate=False) (x**2 + x + 1) # 1-x # 1-2*x # x/y -x/y (x+2)/y # (1+x)*y #3 -5*x/(x+10) # correct placement of negative sign 1 - Rational(3,2)*(x+1) -(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5) # issue 5524 ORDERING: x**2 + x + 1 1 - x 1 - 2*x 2*x**4 + y**2 - x**2 + y**3 RELATIONAL: Eq(x, y) Lt(x, y) Gt(x, y) Le(x, y) Ge(x, y) Ne(x/(y+1), y**2) # RATIONAL NUMBERS: y*x**-2 y**Rational(3,2) * x**Rational(-5,2) sin(x)**3/tan(x)**2 FUNCTIONS (ABS, CONJ, EXP, FUNCTION BRACES, FACTORIAL, FLOOR, CEILING): (2*x + exp(x)) # Abs(x) Abs(x/(x**2+1)) # Abs(1 / (y - Abs(x))) factorial(n) factorial(2*n) subfactorial(n) subfactorial(2*n) factorial(factorial(factorial(n))) factorial(n+1) # conjugate(x) conjugate(f(x+1)) # f(x) f(x, y) f(x/(y+1), y) # f(x**x**x**x**x**x) sin(x)**2 conjugate(a+b*I) conjugate(exp(a+b*I)) conjugate( f(1 + conjugate(f(x))) ) # f(x/(y+1), y) # denom of first arg floor(1 / (y - floor(x))) ceiling(1 / (y - ceiling(x))) SQRT: sqrt(2) 2**Rational(1,3) 2**Rational(1,1000) sqrt(x**2 + 1) (1 + sqrt(5))**Rational(1,3) 2**(1/x) sqrt(2+pi) (2+(1+x**2)/(2+x))**Rational(1,4)+(1+x**Rational(1,1000))/sqrt(3+x**2) DERIVATIVES: Derivative(log(x), x, evaluate=False) Derivative(log(x), x, evaluate=False) + x # Derivative(log(x) + x**2, x, y, evaluate=False) Derivative(2*x*y, y, x, evaluate=False) + x**2 # beta(alpha).diff(alpha) INTEGRALS: Integral(log(x), x) Integral(x**2, x) Integral((sin(x))**2 / (tan(x))**2) Integral(x**(2**x), x) Integral(x**2, (x,1,2)) Integral(x**2, (x,Rational(1,2),10)) Integral(x**2*y**2, x,y) Integral(x**2, (x, None, 1)) Integral(x**2, (x, 1, None)) Integral(sin(th)/cos(ph), (th,0,pi), (ph, 0, 2*pi)) MATRICES: Matrix([[x**2+1, 1], [y, x+y]]) # Matrix([[x/y, y, th], [0, exp(I*k*ph), 1]]) PIECEWISE: Piecewise((x,x<1),(x**2,True)) ITE: ITE(x, y, z) SEQUENCES (TUPLES, LISTS, DICTIONARIES): () [] {} (1/x,) [x**2, 1/x, x, y, sin(th)**2/cos(ph)**2] (x**2, 1/x, x, y, sin(th)**2/cos(ph)**2) {x: sin(x)} {1/x: 1/y, x: sin(x)**2} # [x**2] (x**2,) {x**2: 1} LIMITS: Limit(x, x, oo) Limit(x**2, x, 0) Limit(1/x, x, 0) Limit(sin(x)/x, x, 0) UNITS: joule => kg*m**2/s SUBS: Subs(f(x), x, ph**2) Subs(f(x).diff(x), x, 0) Subs(f(x).diff(x)/y, (x, y), (0, Rational(1, 2))) ORDER: O(1) O(1/x) O(x**2 + y**2) """ def pretty(expr, order=None): """ASCII pretty-printing""" return xpretty(expr, order=order, use_unicode=False, wrap_line=False) def upretty(expr, order=None): """Unicode pretty-printing""" return xpretty(expr, order=order, use_unicode=True, wrap_line=False) def test_pretty_ascii_str(): assert pretty( 'xxx' ) == 'xxx' assert pretty( "xxx" ) == 'xxx' assert pretty( 'xxx\'xxx' ) == 'xxx\'xxx' assert pretty( 'xxx"xxx' ) == 'xxx\"xxx' assert pretty( 'xxx\"xxx' ) == 'xxx\"xxx' assert pretty( "xxx'xxx" ) == 'xxx\'xxx' assert pretty( "xxx\'xxx" ) == 'xxx\'xxx' assert pretty( "xxx\"xxx" ) == 'xxx\"xxx' assert pretty( "xxx\"xxx\'xxx" ) == 'xxx"xxx\'xxx' assert pretty( "xxx\nxxx" ) == 'xxx\nxxx' def test_pretty_unicode_str(): assert pretty( 'xxx' ) == 'xxx' assert pretty( 'xxx' ) == 'xxx' assert pretty( 'xxx\'xxx' ) == 'xxx\'xxx' assert pretty( 'xxx"xxx' ) == 'xxx\"xxx' assert pretty( 'xxx\"xxx' ) == 'xxx\"xxx' assert pretty( "xxx'xxx" ) == 'xxx\'xxx' assert pretty( "xxx\'xxx" ) == 'xxx\'xxx' assert pretty( "xxx\"xxx" ) == 'xxx\"xxx' assert pretty( "xxx\"xxx\'xxx" ) == 'xxx"xxx\'xxx' assert pretty( "xxx\nxxx" ) == 'xxx\nxxx' def test_upretty_greek(): assert upretty( oo ) == '∞' assert upretty( Symbol('alpha^+_1') ) == 'α⁺₁' assert upretty( Symbol('beta') ) == 'β' assert upretty(Symbol('lambda')) == 'λ' def test_upretty_multiindex(): assert upretty( Symbol('beta12') ) == 'β₁₂' assert upretty( Symbol('Y00') ) == 'Y₀₀' assert upretty( Symbol('Y_00') ) == 'Y₀₀' assert upretty( Symbol('F^+-') ) == 'F⁺⁻' def test_upretty_sub_super(): assert upretty( Symbol('beta_1_2') ) == 'β₁ ₂' assert upretty( Symbol('beta^1^2') ) == 'β¹ ²' assert upretty( Symbol('beta_1^2') ) == 'β²₁' assert upretty( Symbol('beta_10_20') ) == 'β₁₀ ₂₀' assert upretty( Symbol('beta_ax_gamma^i') ) == 'βⁱₐₓ ᵧ' assert upretty( Symbol("F^1^2_3_4") ) == 'F¹ ²₃ ₄' assert upretty( Symbol("F_1_2^3^4") ) == 'F³ ⁴₁ ₂' assert upretty( Symbol("F_1_2_3_4") ) == 'F₁ ₂ ₃ ₄' assert upretty( Symbol("F^1^2^3^4") ) == 'F¹ ² ³ ⁴' def test_upretty_subs_missing_in_24(): assert upretty( Symbol('F_beta') ) == 'Fᵦ' assert upretty( Symbol('F_gamma') ) == 'Fᵧ' assert upretty( Symbol('F_rho') ) == 'Fᵨ' assert upretty( Symbol('F_phi') ) == 'Fᵩ' assert upretty( Symbol('F_chi') ) == 'Fᵪ' assert upretty( Symbol('F_a') ) == 'Fₐ' assert upretty( Symbol('F_e') ) == 'Fₑ' assert upretty( Symbol('F_i') ) == 'Fᵢ' assert upretty( Symbol('F_o') ) == 'Fₒ' assert upretty( Symbol('F_u') ) == 'Fᵤ' assert upretty( Symbol('F_r') ) == 'Fᵣ' assert upretty( Symbol('F_v') ) == 'Fᵥ' assert upretty( Symbol('F_x') ) == 'Fₓ' def test_missing_in_2X_issue_9047(): assert upretty( Symbol('F_h') ) == 'Fₕ' assert upretty( Symbol('F_k') ) == 'Fₖ' assert upretty( Symbol('F_l') ) == 'Fₗ' assert upretty( Symbol('F_m') ) == 'Fₘ' assert upretty( Symbol('F_n') ) == 'Fₙ' assert upretty( Symbol('F_p') ) == 'Fₚ' assert upretty( Symbol('F_s') ) == 'Fₛ' assert upretty( Symbol('F_t') ) == 'Fₜ' def test_upretty_modifiers(): # Accents assert upretty( Symbol('Fmathring') ) == 'F̊' assert upretty( Symbol('Fddddot') ) == 'F⃜' assert upretty( Symbol('Fdddot') ) == 'F⃛' assert upretty( Symbol('Fddot') ) == 'F̈' assert upretty( Symbol('Fdot') ) == 'Ḟ' assert upretty( Symbol('Fcheck') ) == 'F̌' assert upretty( Symbol('Fbreve') ) == 'F̆' assert upretty( Symbol('Facute') ) == 'F́' assert upretty( Symbol('Fgrave') ) == 'F̀' assert upretty( Symbol('Ftilde') ) == 'F̃' assert upretty( Symbol('Fhat') ) == 'F̂' assert upretty( Symbol('Fbar') ) == 'F̅' assert upretty( Symbol('Fvec') ) == 'F⃗' assert upretty( Symbol('Fprime') ) == 'F′' assert upretty( Symbol('Fprm') ) == 'F′' # No faces are actually implemented, but test to make sure the modifiers are stripped assert upretty( Symbol('Fbold') ) == 'Fbold' assert upretty( Symbol('Fbm') ) == 'Fbm' assert upretty( Symbol('Fcal') ) == 'Fcal' assert upretty( Symbol('Fscr') ) == 'Fscr' assert upretty( Symbol('Ffrak') ) == 'Ffrak' # Brackets assert upretty( Symbol('Fnorm') ) == '‖F‖' assert upretty( Symbol('Favg') ) == '⟨F⟩' assert upretty( Symbol('Fabs') ) == '|F|' assert upretty( Symbol('Fmag') ) == '|F|' # Combinations assert upretty( Symbol('xvecdot') ) == 'x⃗̇' assert upretty( Symbol('xDotVec') ) == 'ẋ⃗' assert upretty( Symbol('xHATNorm') ) == '‖x̂‖' assert upretty( Symbol('xMathring_yCheckPRM__zbreveAbs') ) == 'x̊_y̌′__|z̆|' assert upretty( Symbol('alphadothat_nVECDOT__tTildePrime') ) == 'α̇̂_n⃗̇__t̃′' assert upretty( Symbol('x_dot') ) == 'x_dot' assert upretty( Symbol('x__dot') ) == 'x__dot' def test_pretty_Cycle(): from sympy.combinatorics.permutations import Cycle assert pretty(Cycle(1, 2)) == '(1 2)' assert pretty(Cycle(2)) == '(2)' assert pretty(Cycle(1, 3)(4, 5)) == '(1 3)(4 5)' assert pretty(Cycle()) == '()' def test_pretty_Permutation(): from sympy.combinatorics.permutations import Permutation p1 = Permutation(1, 2)(3, 4) assert xpretty(p1, perm_cyclic=True, use_unicode=True) == "(1 2)(3 4)" assert xpretty(p1, perm_cyclic=True, use_unicode=False) == "(1 2)(3 4)" assert xpretty(p1, perm_cyclic=False, use_unicode=True) == \ '⎛0 1 2 3 4⎞\n'\ '⎝0 2 1 4 3⎠' assert xpretty(p1, perm_cyclic=False, use_unicode=False) == \ "/0 1 2 3 4\\\n"\ "\\0 2 1 4 3/" def test_pretty_basic(): assert pretty( -Rational(1)/2 ) == '-1/2' assert pretty( -Rational(13)/22 ) == \ """\ -13 \n\ ----\n\ 22 \ """ expr = oo ascii_str = \ """\ oo\ """ ucode_str = \ """\ ∞\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x**2) ascii_str = \ """\ 2\n\ x \ """ ucode_str = \ """\ 2\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 1/x ascii_str = \ """\ 1\n\ -\n\ x\ """ ucode_str = \ """\ 1\n\ ─\n\ x\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # not the same as 1/x expr = x**-1.0 ascii_str = \ """\ -1.0\n\ x \ """ ucode_str = \ """\ -1.0\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # see issue #2860 expr = Pow(S(2), -1.0, evaluate=False) ascii_str = \ """\ -1.0\n\ 2 \ """ ucode_str = \ """\ -1.0\n\ 2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = y*x**-2 ascii_str = \ """\ y \n\ --\n\ 2\n\ x \ """ ucode_str = \ """\ y \n\ ──\n\ 2\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str #see issue #14033 expr = x**Rational(1, 3) ascii_str = \ """\ 1/3\n\ x \ """ ucode_str = \ """\ 1/3\n\ x \ """ assert xpretty(expr, use_unicode=False, wrap_line=False,\ root_notation = False) == ascii_str assert xpretty(expr, use_unicode=True, wrap_line=False,\ root_notation = False) == ucode_str expr = x**Rational(-5, 2) ascii_str = \ """\ 1 \n\ ----\n\ 5/2\n\ x \ """ ucode_str = \ """\ 1 \n\ ────\n\ 5/2\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (-2)**x ascii_str = \ """\ x\n\ (-2) \ """ ucode_str = \ """\ x\n\ (-2) \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # See issue 4923 expr = Pow(3, 1, evaluate=False) ascii_str = \ """\ 1\n\ 3 \ """ ucode_str = \ """\ 1\n\ 3 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x**2 + x + 1) ascii_str_1 = \ """\ 2\n\ 1 + x + x \ """ ascii_str_2 = \ """\ 2 \n\ x + x + 1\ """ ascii_str_3 = \ """\ 2 \n\ x + 1 + x\ """ ucode_str_1 = \ """\ 2\n\ 1 + x + x \ """ ucode_str_2 = \ """\ 2 \n\ x + x + 1\ """ ucode_str_3 = \ """\ 2 \n\ x + 1 + x\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3] assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3] expr = 1 - x ascii_str_1 = \ """\ 1 - x\ """ ascii_str_2 = \ """\ -x + 1\ """ ucode_str_1 = \ """\ 1 - x\ """ ucode_str_2 = \ """\ -x + 1\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = 1 - 2*x ascii_str_1 = \ """\ 1 - 2*x\ """ ascii_str_2 = \ """\ -2*x + 1\ """ ucode_str_1 = \ """\ 1 - 2⋅x\ """ ucode_str_2 = \ """\ -2⋅x + 1\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = x/y ascii_str = \ """\ x\n\ -\n\ y\ """ ucode_str = \ """\ x\n\ ─\n\ y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -x/y ascii_str = \ """\ -x \n\ ---\n\ y \ """ ucode_str = \ """\ -x \n\ ───\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x + 2)/y ascii_str_1 = \ """\ 2 + x\n\ -----\n\ y \ """ ascii_str_2 = \ """\ x + 2\n\ -----\n\ y \ """ ucode_str_1 = \ """\ 2 + x\n\ ─────\n\ y \ """ ucode_str_2 = \ """\ x + 2\n\ ─────\n\ y \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = (1 + x)*y ascii_str_1 = \ """\ y*(1 + x)\ """ ascii_str_2 = \ """\ (1 + x)*y\ """ ascii_str_3 = \ """\ y*(x + 1)\ """ ucode_str_1 = \ """\ y⋅(1 + x)\ """ ucode_str_2 = \ """\ (1 + x)⋅y\ """ ucode_str_3 = \ """\ y⋅(x + 1)\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3] assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3] # Test for correct placement of the negative sign expr = -5*x/(x + 10) ascii_str_1 = \ """\ -5*x \n\ ------\n\ 10 + x\ """ ascii_str_2 = \ """\ -5*x \n\ ------\n\ x + 10\ """ ucode_str_1 = \ """\ -5⋅x \n\ ──────\n\ 10 + x\ """ ucode_str_2 = \ """\ -5⋅x \n\ ──────\n\ x + 10\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = -S.Half - 3*x ascii_str = \ """\ -3*x - 1/2\ """ ucode_str = \ """\ -3⋅x - 1/2\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = S.Half - 3*x ascii_str = \ """\ 1/2 - 3*x\ """ ucode_str = \ """\ 1/2 - 3⋅x\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -S.Half - 3*x/2 ascii_str = \ """\ 3*x 1\n\ - --- - -\n\ 2 2\ """ ucode_str = \ """\ 3⋅x 1\n\ - ─── - ─\n\ 2 2\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = S.Half - 3*x/2 ascii_str = \ """\ 1 3*x\n\ - - ---\n\ 2 2 \ """ ucode_str = \ """\ 1 3⋅x\n\ ─ - ───\n\ 2 2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_negative_fractions(): expr = -x/y ascii_str =\ """\ -x \n\ ---\n\ y \ """ ucode_str =\ """\ -x \n\ ───\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -x*z/y ascii_str =\ """\ -x*z \n\ -----\n\ y \ """ ucode_str =\ """\ -x⋅z \n\ ─────\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = x**2/y ascii_str =\ """\ 2\n\ x \n\ --\n\ y \ """ ucode_str =\ """\ 2\n\ x \n\ ──\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -x**2/y ascii_str =\ """\ 2 \n\ -x \n\ ----\n\ y \ """ ucode_str =\ """\ 2 \n\ -x \n\ ────\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -x/(y*z) ascii_str =\ """\ -x \n\ ---\n\ y*z\ """ ucode_str =\ """\ -x \n\ ───\n\ y⋅z\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -a/y**2 ascii_str =\ """\ -a \n\ ---\n\ 2\n\ y \ """ ucode_str =\ """\ -a \n\ ───\n\ 2\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = y**(-a/b) ascii_str =\ """\ -a \n\ ---\n\ b \n\ y \ """ ucode_str =\ """\ -a \n\ ───\n\ b \n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -1/y**2 ascii_str =\ """\ -1 \n\ ---\n\ 2\n\ y \ """ ucode_str =\ """\ -1 \n\ ───\n\ 2\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -10/b**2 ascii_str =\ """\ -10 \n\ ----\n\ 2 \n\ b \ """ ucode_str =\ """\ -10 \n\ ────\n\ 2 \n\ b \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Rational(-200, 37) ascii_str =\ """\ -200 \n\ -----\n\ 37 \ """ ucode_str =\ """\ -200 \n\ ─────\n\ 37 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Mul(0, 1, evaluate=False) assert pretty(expr) == "0*1" assert upretty(expr) == "0⋅1" expr = Mul(1, 0, evaluate=False) assert pretty(expr) == "1*0" assert upretty(expr) == "1⋅0" expr = Mul(1, 1, evaluate=False) assert pretty(expr) == "1*1" assert upretty(expr) == "1⋅1" expr = Mul(1, 1, 1, evaluate=False) assert pretty(expr) == "1*1*1" assert upretty(expr) == "1⋅1⋅1" expr = Mul(1, 2, evaluate=False) assert pretty(expr) == "1*2" assert upretty(expr) == "1⋅2" expr = Add(0, 1, evaluate=False) assert pretty(expr) == "0 + 1" assert upretty(expr) == "0 + 1" expr = Mul(1, 1, 2, evaluate=False) assert pretty(expr) == "1*1*2" assert upretty(expr) == "1⋅1⋅2" expr = Add(0, 0, 1, evaluate=False) assert pretty(expr) == "0 + 0 + 1" assert upretty(expr) == "0 + 0 + 1" expr = Mul(1, -1, evaluate=False) assert pretty(expr) == "1*(-1)" assert upretty(expr) == "1⋅(-1)" expr = Mul(1.0, x, evaluate=False) assert pretty(expr) == "1.0*x" assert upretty(expr) == "1.0⋅x" expr = Mul(1, 1, 2, 3, x, evaluate=False) assert pretty(expr) == "1*1*2*3*x" assert upretty(expr) == "1⋅1⋅2⋅3⋅x" expr = Mul(-1, 1, evaluate=False) assert pretty(expr) == "-1*1" assert upretty(expr) == "-1⋅1" expr = Mul(4, 3, 2, 1, 0, y, x, evaluate=False) assert pretty(expr) == "4*3*2*1*0*y*x" assert upretty(expr) == "4⋅3⋅2⋅1⋅0⋅y⋅x" expr = Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False) assert pretty(expr) == "4*3*2*(z + 1)*0*y*x" assert upretty(expr) == "4⋅3⋅2⋅(z + 1)⋅0⋅y⋅x" expr = Mul(Rational(2, 3), Rational(5, 7), evaluate=False) assert pretty(expr) == "2/3*5/7" assert upretty(expr) == "2/3⋅5/7" def test_issue_5524(): assert pretty(-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5)) == \ """\ 2 / ___ \\\n\ - (5 - y) + (x - 5)*\\-x - 2*\\/ 2 + 5/\ """ assert upretty(-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5)) == \ """\ 2 \n\ - (5 - y) + (x - 5)⋅(-x - 2⋅√2 + 5)\ """ def test_pretty_ordering(): assert pretty(x**2 + x + 1, order='lex') == \ """\ 2 \n\ x + x + 1\ """ assert pretty(x**2 + x + 1, order='rev-lex') == \ """\ 2\n\ 1 + x + x \ """ assert pretty(1 - x, order='lex') == '-x + 1' assert pretty(1 - x, order='rev-lex') == '1 - x' assert pretty(1 - 2*x, order='lex') == '-2*x + 1' assert pretty(1 - 2*x, order='rev-lex') == '1 - 2*x' f = 2*x**4 + y**2 - x**2 + y**3 assert pretty(f, order=None) == \ """\ 4 2 3 2\n\ 2*x - x + y + y \ """ assert pretty(f, order='lex') == \ """\ 4 2 3 2\n\ 2*x - x + y + y \ """ assert pretty(f, order='rev-lex') == \ """\ 2 3 2 4\n\ y + y - x + 2*x \ """ expr = x - x**3/6 + x**5/120 + O(x**6) ascii_str = \ """\ 3 5 \n\ x x / 6\\\n\ x - -- + --- + O\\x /\n\ 6 120 \ """ ucode_str = \ """\ 3 5 \n\ x x ⎛ 6⎞\n\ x - ── + ─── + O⎝x ⎠\n\ 6 120 \ """ assert pretty(expr, order=None) == ascii_str assert upretty(expr, order=None) == ucode_str assert pretty(expr, order='lex') == ascii_str assert upretty(expr, order='lex') == ucode_str assert pretty(expr, order='rev-lex') == ascii_str assert upretty(expr, order='rev-lex') == ucode_str def test_EulerGamma(): assert pretty(EulerGamma) == str(EulerGamma) == "EulerGamma" assert upretty(EulerGamma) == "γ" def test_GoldenRatio(): assert pretty(GoldenRatio) == str(GoldenRatio) == "GoldenRatio" assert upretty(GoldenRatio) == "φ" def test_pretty_relational(): expr = Eq(x, y) ascii_str = \ """\ x = y\ """ ucode_str = \ """\ x = y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lt(x, y) ascii_str = \ """\ x < y\ """ ucode_str = \ """\ x < y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Gt(x, y) ascii_str = \ """\ x > y\ """ ucode_str = \ """\ x > y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Le(x, y) ascii_str = \ """\ x <= y\ """ ucode_str = \ """\ x ≤ y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Ge(x, y) ascii_str = \ """\ x >= y\ """ ucode_str = \ """\ x ≥ y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Ne(x/(y + 1), y**2) ascii_str_1 = \ """\ x 2\n\ ----- != y \n\ 1 + y \ """ ascii_str_2 = \ """\ x 2\n\ ----- != y \n\ y + 1 \ """ ucode_str_1 = \ """\ x 2\n\ ───── ≠ y \n\ 1 + y \ """ ucode_str_2 = \ """\ x 2\n\ ───── ≠ y \n\ y + 1 \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] def test_Assignment(): expr = Assignment(x, y) ascii_str = \ """\ x := y\ """ ucode_str = \ """\ x := y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_AugmentedAssignment(): expr = AddAugmentedAssignment(x, y) ascii_str = \ """\ x += y\ """ ucode_str = \ """\ x += y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = SubAugmentedAssignment(x, y) ascii_str = \ """\ x -= y\ """ ucode_str = \ """\ x -= y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = MulAugmentedAssignment(x, y) ascii_str = \ """\ x *= y\ """ ucode_str = \ """\ x *= y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = DivAugmentedAssignment(x, y) ascii_str = \ """\ x /= y\ """ ucode_str = \ """\ x /= y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = ModAugmentedAssignment(x, y) ascii_str = \ """\ x %= y\ """ ucode_str = \ """\ x %= y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_rational(): expr = y*x**-2 ascii_str = \ """\ y \n\ --\n\ 2\n\ x \ """ ucode_str = \ """\ y \n\ ──\n\ 2\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = y**Rational(3, 2) * x**Rational(-5, 2) ascii_str = \ """\ 3/2\n\ y \n\ ----\n\ 5/2\n\ x \ """ ucode_str = \ """\ 3/2\n\ y \n\ ────\n\ 5/2\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = sin(x)**3/tan(x)**2 ascii_str = \ """\ 3 \n\ sin (x)\n\ -------\n\ 2 \n\ tan (x)\ """ ucode_str = \ """\ 3 \n\ sin (x)\n\ ───────\n\ 2 \n\ tan (x)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str @_both_exp_pow def test_pretty_functions(): """Tests for Abs, conjugate, exp, function braces, and factorial.""" expr = (2*x + exp(x)) ascii_str_1 = \ """\ x\n\ 2*x + e \ """ ascii_str_2 = \ """\ x \n\ e + 2*x\ """ ucode_str_1 = \ """\ x\n\ 2⋅x + ℯ \ """ ucode_str_2 = \ """\ x \n\ ℯ + 2⋅x\ """ ucode_str_3 = \ """\ x \n\ ℯ + 2⋅x\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3] expr = Abs(x) ascii_str = \ """\ |x|\ """ ucode_str = \ """\ │x│\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Abs(x/(x**2 + 1)) ascii_str_1 = \ """\ | x |\n\ |------|\n\ | 2|\n\ |1 + x |\ """ ascii_str_2 = \ """\ | x |\n\ |------|\n\ | 2 |\n\ |x + 1|\ """ ucode_str_1 = \ """\ │ x │\n\ │──────│\n\ │ 2│\n\ │1 + x │\ """ ucode_str_2 = \ """\ │ x │\n\ │──────│\n\ │ 2 │\n\ │x + 1│\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Abs(1 / (y - Abs(x))) ascii_str = \ """\ 1 \n\ ---------\n\ |y - |x||\ """ ucode_str = \ """\ 1 \n\ ─────────\n\ │y - │x││\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str n = Symbol('n', integer=True) expr = factorial(n) ascii_str = \ """\ n!\ """ ucode_str = \ """\ n!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial(2*n) ascii_str = \ """\ (2*n)!\ """ ucode_str = \ """\ (2⋅n)!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial(factorial(factorial(n))) ascii_str = \ """\ ((n!)!)!\ """ ucode_str = \ """\ ((n!)!)!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial(n + 1) ascii_str_1 = \ """\ (1 + n)!\ """ ascii_str_2 = \ """\ (n + 1)!\ """ ucode_str_1 = \ """\ (1 + n)!\ """ ucode_str_2 = \ """\ (n + 1)!\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = subfactorial(n) ascii_str = \ """\ !n\ """ ucode_str = \ """\ !n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = subfactorial(2*n) ascii_str = \ """\ !(2*n)\ """ ucode_str = \ """\ !(2⋅n)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str n = Symbol('n', integer=True) expr = factorial2(n) ascii_str = \ """\ n!!\ """ ucode_str = \ """\ n!!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial2(2*n) ascii_str = \ """\ (2*n)!!\ """ ucode_str = \ """\ (2⋅n)!!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial2(factorial2(factorial2(n))) ascii_str = \ """\ ((n!!)!!)!!\ """ ucode_str = \ """\ ((n!!)!!)!!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial2(n + 1) ascii_str_1 = \ """\ (1 + n)!!\ """ ascii_str_2 = \ """\ (n + 1)!!\ """ ucode_str_1 = \ """\ (1 + n)!!\ """ ucode_str_2 = \ """\ (n + 1)!!\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = 2*binomial(n, k) ascii_str = \ """\ /n\\\n\ 2*| |\n\ \\k/\ """ ucode_str = \ """\ ⎛n⎞\n\ 2⋅⎜ ⎟\n\ ⎝k⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2*binomial(2*n, k) ascii_str = \ """\ /2*n\\\n\ 2*| |\n\ \\ k /\ """ ucode_str = \ """\ ⎛2⋅n⎞\n\ 2⋅⎜ ⎟\n\ ⎝ k ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2*binomial(n**2, k) ascii_str = \ """\ / 2\\\n\ |n |\n\ 2*| |\n\ \\k /\ """ ucode_str = \ """\ ⎛ 2⎞\n\ ⎜n ⎟\n\ 2⋅⎜ ⎟\n\ ⎝k ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = catalan(n) ascii_str = \ """\ C \n\ n\ """ ucode_str = \ """\ C \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = catalan(n) ascii_str = \ """\ C \n\ n\ """ ucode_str = \ """\ C \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = bell(n) ascii_str = \ """\ B \n\ n\ """ ucode_str = \ """\ B \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = bernoulli(n) ascii_str = \ """\ B \n\ n\ """ ucode_str = \ """\ B \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = bernoulli(n, x) ascii_str = \ """\ B (x)\n\ n \ """ ucode_str = \ """\ B (x)\n\ n \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = fibonacci(n) ascii_str = \ """\ F \n\ n\ """ ucode_str = \ """\ F \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = lucas(n) ascii_str = \ """\ L \n\ n\ """ ucode_str = \ """\ L \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = tribonacci(n) ascii_str = \ """\ T \n\ n\ """ ucode_str = \ """\ T \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = stieltjes(n) ascii_str = \ """\ stieltjes \n\ n\ """ ucode_str = \ """\ γ \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = stieltjes(n, x) ascii_str = \ """\ stieltjes (x)\n\ n \ """ ucode_str = \ """\ γ (x)\n\ n \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = mathieuc(x, y, z) ascii_str = 'C(x, y, z)' ucode_str = 'C(x, y, z)' assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = mathieus(x, y, z) ascii_str = 'S(x, y, z)' ucode_str = 'S(x, y, z)' assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = mathieucprime(x, y, z) ascii_str = "C'(x, y, z)" ucode_str = "C'(x, y, z)" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = mathieusprime(x, y, z) ascii_str = "S'(x, y, z)" ucode_str = "S'(x, y, z)" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = conjugate(x) ascii_str = \ """\ _\n\ x\ """ ucode_str = \ """\ _\n\ x\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str f = Function('f') expr = conjugate(f(x + 1)) ascii_str_1 = \ """\ ________\n\ f(1 + x)\ """ ascii_str_2 = \ """\ ________\n\ f(x + 1)\ """ ucode_str_1 = \ """\ ________\n\ f(1 + x)\ """ ucode_str_2 = \ """\ ________\n\ f(x + 1)\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = f(x) ascii_str = \ """\ f(x)\ """ ucode_str = \ """\ f(x)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = f(x, y) ascii_str = \ """\ f(x, y)\ """ ucode_str = \ """\ f(x, y)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = f(x/(y + 1), y) ascii_str_1 = \ """\ / x \\\n\ f|-----, y|\n\ \\1 + y /\ """ ascii_str_2 = \ """\ / x \\\n\ f|-----, y|\n\ \\y + 1 /\ """ ucode_str_1 = \ """\ ⎛ x ⎞\n\ f⎜─────, y⎟\n\ ⎝1 + y ⎠\ """ ucode_str_2 = \ """\ ⎛ x ⎞\n\ f⎜─────, y⎟\n\ ⎝y + 1 ⎠\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = f(x**x**x**x**x**x) ascii_str = \ """\ / / / / / x\\\\\\\\\\ | | | | \\x /|||| | | | \\x /||| | | \\x /|| | \\x /| f\\x /\ """ ucode_str = \ """\ ⎛ ⎛ ⎛ ⎛ ⎛ x⎞⎞⎞⎞⎞ ⎜ ⎜ ⎜ ⎜ ⎝x ⎠⎟⎟⎟⎟ ⎜ ⎜ ⎜ ⎝x ⎠⎟⎟⎟ ⎜ ⎜ ⎝x ⎠⎟⎟ ⎜ ⎝x ⎠⎟ f⎝x ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = sin(x)**2 ascii_str = \ """\ 2 \n\ sin (x)\ """ ucode_str = \ """\ 2 \n\ sin (x)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = conjugate(a + b*I) ascii_str = \ """\ _ _\n\ a - I*b\ """ ucode_str = \ """\ _ _\n\ a - ⅈ⋅b\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = conjugate(exp(a + b*I)) ascii_str = \ """\ _ _\n\ a - I*b\n\ e \ """ ucode_str = \ """\ _ _\n\ a - ⅈ⋅b\n\ ℯ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = conjugate( f(1 + conjugate(f(x))) ) ascii_str_1 = \ """\ ___________\n\ / ____\\\n\ f\\1 + f(x)/\ """ ascii_str_2 = \ """\ ___________\n\ /____ \\\n\ f\\f(x) + 1/\ """ ucode_str_1 = \ """\ ___________\n\ ⎛ ____⎞\n\ f⎝1 + f(x)⎠\ """ ucode_str_2 = \ """\ ___________\n\ ⎛____ ⎞\n\ f⎝f(x) + 1⎠\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = f(x/(y + 1), y) ascii_str_1 = \ """\ / x \\\n\ f|-----, y|\n\ \\1 + y /\ """ ascii_str_2 = \ """\ / x \\\n\ f|-----, y|\n\ \\y + 1 /\ """ ucode_str_1 = \ """\ ⎛ x ⎞\n\ f⎜─────, y⎟\n\ ⎝1 + y ⎠\ """ ucode_str_2 = \ """\ ⎛ x ⎞\n\ f⎜─────, y⎟\n\ ⎝y + 1 ⎠\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = floor(1 / (y - floor(x))) ascii_str = \ """\ / 1 \\\n\ floor|------------|\n\ \\y - floor(x)/\ """ ucode_str = \ """\ ⎢ 1 ⎥\n\ ⎢───────⎥\n\ ⎣y - ⌊x⌋⎦\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = ceiling(1 / (y - ceiling(x))) ascii_str = \ """\ / 1 \\\n\ ceiling|--------------|\n\ \\y - ceiling(x)/\ """ ucode_str = \ """\ ⎡ 1 ⎤\n\ ⎢───────⎥\n\ ⎢y - ⌈x⌉⎥\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = euler(n) ascii_str = \ """\ E \n\ n\ """ ucode_str = \ """\ E \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = euler(1/(1 + 1/(1 + 1/n))) ascii_str = \ """\ E \n\ 1 \n\ ---------\n\ 1 \n\ 1 + -----\n\ 1\n\ 1 + -\n\ n\ """ ucode_str = \ """\ E \n\ 1 \n\ ─────────\n\ 1 \n\ 1 + ─────\n\ 1\n\ 1 + ─\n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = euler(n, x) ascii_str = \ """\ E (x)\n\ n \ """ ucode_str = \ """\ E (x)\n\ n \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = euler(n, x/2) ascii_str = \ """\ /x\\\n\ E |-|\n\ n\\2/\ """ ucode_str = \ """\ ⎛x⎞\n\ E ⎜─⎟\n\ n⎝2⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_sqrt(): expr = sqrt(2) ascii_str = \ """\ ___\n\ \\/ 2 \ """ ucode_str = \ "√2" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2**Rational(1, 3) ascii_str = \ """\ 3 ___\n\ \\/ 2 \ """ ucode_str = \ """\ 3 ___\n\ ╲╱ 2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2**Rational(1, 1000) ascii_str = \ """\ 1000___\n\ \\/ 2 \ """ ucode_str = \ """\ 1000___\n\ ╲╱ 2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = sqrt(x**2 + 1) ascii_str = \ """\ ________\n\ / 2 \n\ \\/ x + 1 \ """ ucode_str = \ """\ ________\n\ ╱ 2 \n\ ╲╱ x + 1 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (1 + sqrt(5))**Rational(1, 3) ascii_str = \ """\ ___________\n\ 3 / ___ \n\ \\/ 1 + \\/ 5 \ """ ucode_str = \ """\ 3 ________\n\ ╲╱ 1 + √5 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2**(1/x) ascii_str = \ """\ x ___\n\ \\/ 2 \ """ ucode_str = \ """\ x ___\n\ ╲╱ 2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = sqrt(2 + pi) ascii_str = \ """\ ________\n\ \\/ 2 + pi \ """ ucode_str = \ """\ _______\n\ ╲╱ 2 + π \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (2 + ( 1 + x**2)/(2 + x))**Rational(1, 4) + (1 + x**Rational(1, 1000))/sqrt(3 + x**2) ascii_str = \ """\ ____________ \n\ / 2 1000___ \n\ / x + 1 \\/ x + 1\n\ 4 / 2 + ------ + -----------\n\ \\/ x + 2 ________\n\ / 2 \n\ \\/ x + 3 \ """ ucode_str = \ """\ ____________ \n\ ╱ 2 1000___ \n\ ╱ x + 1 ╲╱ x + 1\n\ 4 ╱ 2 + ────── + ───────────\n\ ╲╱ x + 2 ________\n\ ╱ 2 \n\ ╲╱ x + 3 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_sqrt_char_knob(): # See PR #9234. expr = sqrt(2) ucode_str1 = \ """\ ___\n\ ╲╱ 2 \ """ ucode_str2 = \ "√2" assert xpretty(expr, use_unicode=True, use_unicode_sqrt_char=False) == ucode_str1 assert xpretty(expr, use_unicode=True, use_unicode_sqrt_char=True) == ucode_str2 def test_pretty_sqrt_longsymbol_no_sqrt_char(): # Do not use unicode sqrt char for long symbols (see PR #9234). expr = sqrt(Symbol('C1')) ucode_str = \ """\ ____\n\ ╲╱ C₁ \ """ assert upretty(expr) == ucode_str def test_pretty_KroneckerDelta(): x, y = symbols("x, y") expr = KroneckerDelta(x, y) ascii_str = \ """\ d \n\ x,y\ """ ucode_str = \ """\ δ \n\ x,y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_product(): n, m, k, l = symbols('n m k l') f = symbols('f', cls=Function) expr = Product(f((n/3)**2), (n, k**2, l)) unicode_str = \ """\ l \n\ ─┬──────┬─ \n\ │ │ ⎛ 2⎞\n\ │ │ ⎜n ⎟\n\ │ │ f⎜──⎟\n\ │ │ ⎝9 ⎠\n\ │ │ \n\ 2 \n\ n = k """ ascii_str = \ """\ l \n\ __________ \n\ | | / 2\\\n\ | | |n |\n\ | | f|--|\n\ | | \\9 /\n\ | | \n\ 2 \n\ n = k """ expr = Product(f((n/3)**2), (n, k**2, l), (l, 1, m)) unicode_str = \ """\ m l \n\ ─┬──────┬─ ─┬──────┬─ \n\ │ │ │ │ ⎛ 2⎞\n\ │ │ │ │ ⎜n ⎟\n\ │ │ │ │ f⎜──⎟\n\ │ │ │ │ ⎝9 ⎠\n\ │ │ │ │ \n\ l = 1 2 \n\ n = k """ ascii_str = \ """\ m l \n\ __________ __________ \n\ | | | | / 2\\\n\ | | | | |n |\n\ | | | | f|--|\n\ | | | | \\9 /\n\ | | | | \n\ l = 1 2 \n\ n = k """ assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str def test_pretty_Lambda(): # S.IdentityFunction is a special case expr = Lambda(y, y) assert pretty(expr) == "x -> x" assert upretty(expr) == "x ↦ x" expr = Lambda(x, x+1) assert pretty(expr) == "x -> x + 1" assert upretty(expr) == "x ↦ x + 1" expr = Lambda(x, x**2) ascii_str = \ """\ 2\n\ x -> x \ """ ucode_str = \ """\ 2\n\ x ↦ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lambda(x, x**2)**2 ascii_str = \ """\ 2 / 2\\ \n\ \\x -> x / \ """ ucode_str = \ """\ 2 ⎛ 2⎞ \n\ ⎝x ↦ x ⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lambda((x, y), x) ascii_str = "(x, y) -> x" ucode_str = "(x, y) ↦ x" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lambda((x, y), x**2) ascii_str = \ """\ 2\n\ (x, y) -> x \ """ ucode_str = \ """\ 2\n\ (x, y) ↦ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lambda(((x, y),), x**2) ascii_str = \ """\ 2\n\ ((x, y),) -> x \ """ ucode_str = \ """\ 2\n\ ((x, y),) ↦ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_TransferFunction(): tf1 = TransferFunction(s - 1, s + 1, s) assert upretty(tf1) == "s - 1\n─────\ns + 1" tf2 = TransferFunction(2*s + 1, 3 - p, s) assert upretty(tf2) == "2⋅s + 1\n───────\n 3 - p " tf3 = TransferFunction(p, p + 1, p) assert upretty(tf3) == " p \n─────\np + 1" def test_pretty_Series(): tf1 = TransferFunction(x + y, x - 2*y, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(x**2 + y, y - x, y) tf4 = TransferFunction(2, 3, y) tfm1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]]) tfm2 = TransferFunctionMatrix([[tf3], [-tf4]]) tfm3 = TransferFunctionMatrix([[tf1, -tf2, -tf3], [tf3, -tf4, tf2]]) tfm4 = TransferFunctionMatrix([[tf1, tf2], [tf3, -tf4], [-tf2, -tf1]]) tfm5 = TransferFunctionMatrix([[-tf2, -tf1], [tf4, -tf3], [tf1, tf2]]) expected1 = \ """\ ⎛ 2 ⎞\n\ ⎛ x + y ⎞ ⎜x + y⎟\n\ ⎜───────⎟⋅⎜──────⎟\n\ ⎝x - 2⋅y⎠ ⎝-x + y⎠\ """ expected2 = \ """\ ⎛-x + y⎞ ⎛ -x - y⎞\n\ ⎜──────⎟⋅⎜───────⎟\n\ ⎝x + y ⎠ ⎝x - 2⋅y⎠\ """ expected3 = \ """\ ⎛ 2 ⎞ \n\ ⎜x + y⎟ ⎛ x + y ⎞ ⎛ -x - y x - y⎞\n\ ⎜──────⎟⋅⎜───────⎟⋅⎜─────── + ─────⎟\n\ ⎝-x + y⎠ ⎝x - 2⋅y⎠ ⎝x - 2⋅y x + y⎠\ """ expected4 = \ """\ ⎛ 2 ⎞\n\ ⎛ x + y x - y⎞ ⎜x - y x + y⎟\n\ ⎜─────── + ─────⎟⋅⎜───── + ──────⎟\n\ ⎝x - 2⋅y x + y⎠ ⎝x + y -x + y⎠\ """ expected5 = \ """\ ⎡ x + y x - y⎤ ⎡ 2 ⎤ \n\ ⎢─────── ─────⎥ ⎢x + y⎥ \n\ ⎢x - 2⋅y x + y⎥ ⎢──────⎥ \n\ ⎢ ⎥ ⎢-x + y⎥ \n\ ⎢ 2 ⎥ ⋅⎢ ⎥ \n\ ⎢x + y 2 ⎥ ⎢ -2 ⎥ \n\ ⎢────── ─ ⎥ ⎢ ─── ⎥ \n\ ⎣-x + y 3 ⎦τ ⎣ 3 ⎦τ\ """ expected6 = \ """\ ⎛⎡ x + y x - y ⎤ ⎡ x - y x + y ⎤ ⎞\n\ ⎜⎢─────── ───── ⎥ ⎢ ───── ───────⎥ ⎟\n\ ⎡ x + y x - y⎤ ⎡ 2 ⎤ ⎜⎢x - 2⋅y x + y ⎥ ⎢ x + y x - 2⋅y⎥ ⎟\n\ ⎢─────── ─────⎥ ⎢ x + y -x + y - x - y⎥ ⎜⎢ ⎥ ⎢ ⎥ ⎟\n\ ⎢x - 2⋅y x + y⎥ ⎢─────── ────── ────────⎥ ⎜⎢ 2 ⎥ ⎢ 2 ⎥ ⎟\n\ ⎢ ⎥ ⎢x - 2⋅y x + y -x + y ⎥ ⎜⎢x + y -2 ⎥ ⎢ -2 x + y ⎥ ⎟\n\ ⎢ 2 ⎥ ⋅⎢ ⎥ ⋅⎜⎢────── ─── ⎥ + ⎢ ─── ────── ⎥ ⎟\n\ ⎢x + y 2 ⎥ ⎢ 2 ⎥ ⎜⎢-x + y 3 ⎥ ⎢ 3 -x + y ⎥ ⎟\n\ ⎢────── ─ ⎥ ⎢x + y -2 x - y ⎥ ⎜⎢ ⎥ ⎢ ⎥ ⎟\n\ ⎣-x + y 3 ⎦τ ⎢────── ─── ───── ⎥ ⎜⎢-x + y -x - y⎥ ⎢ -x - y -x + y ⎥ ⎟\n\ ⎣-x + y 3 x + y ⎦τ ⎜⎢────── ───────⎥ ⎢─────── ────── ⎥ ⎟\n\ ⎝⎣x + y x - 2⋅y⎦τ ⎣x - 2⋅y x + y ⎦τ⎠\ """ assert upretty(Series(tf1, tf3)) == expected1 assert upretty(Series(-tf2, -tf1)) == expected2 assert upretty(Series(tf3, tf1, Parallel(-tf1, tf2))) == expected3 assert upretty(Series(Parallel(tf1, tf2), Parallel(tf2, tf3))) == expected4 assert upretty(MIMOSeries(tfm2, tfm1)) == expected5 assert upretty(MIMOSeries(MIMOParallel(tfm4, -tfm5), tfm3, tfm1)) == expected6 def test_pretty_Parallel(): tf1 = TransferFunction(x + y, x - 2*y, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(x**2 + y, y - x, y) tf4 = TransferFunction(y**2 - x, x**3 + x, y) tfm1 = TransferFunctionMatrix([[tf1, tf2], [tf3, -tf4], [-tf2, -tf1]]) tfm2 = TransferFunctionMatrix([[-tf2, -tf1], [tf4, -tf3], [tf1, tf2]]) tfm3 = TransferFunctionMatrix([[-tf1, tf2], [-tf3, tf4], [tf2, tf1]]) tfm4 = TransferFunctionMatrix([[-tf1, -tf2], [-tf3, -tf4]]) expected1 = \ """\ x + y x - y\n\ ─────── + ─────\n\ x - 2⋅y x + y\ """ expected2 = \ """\ -x + y -x - y\n\ ────── + ───────\n\ x + y x - 2⋅y\ """ expected3 = \ """\ 2 \n\ x + y x + y ⎛ -x - y⎞ ⎛x - y⎞\n\ ────── + ─────── + ⎜───────⎟⋅⎜─────⎟\n\ -x + y x - 2⋅y ⎝x - 2⋅y⎠ ⎝x + y⎠\ """ expected4 = \ """\ ⎛ 2 ⎞\n\ ⎛ x + y ⎞ ⎛x - y⎞ ⎛x - y⎞ ⎜x + y⎟\n\ ⎜───────⎟⋅⎜─────⎟ + ⎜─────⎟⋅⎜──────⎟\n\ ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝x + y⎠ ⎝-x + y⎠\ """ expected5 = \ """\ ⎡ x + y -x + y ⎤ ⎡ x - y x + y ⎤ ⎡ x + y x - y ⎤ \n\ ⎢─────── ────── ⎥ ⎢ ───── ───────⎥ ⎢─────── ───── ⎥ \n\ ⎢x - 2⋅y x + y ⎥ ⎢ x + y x - 2⋅y⎥ ⎢x - 2⋅y x + y ⎥ \n\ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ \n\ ⎢ 2 2 ⎥ ⎢ 2 2 ⎥ ⎢ 2 2 ⎥ \n\ ⎢x + y x - y ⎥ ⎢x - y x + y ⎥ ⎢x + y x - y ⎥ \n\ ⎢────── ────── ⎥ + ⎢────── ────── ⎥ + ⎢────── ────── ⎥ \n\ ⎢-x + y 3 ⎥ ⎢ 3 -x + y ⎥ ⎢-x + y 3 ⎥ \n\ ⎢ x + x ⎥ ⎢x + x ⎥ ⎢ x + x ⎥ \n\ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ \n\ ⎢-x + y -x - y⎥ ⎢ -x - y -x + y ⎥ ⎢-x + y -x - y⎥ \n\ ⎢────── ───────⎥ ⎢─────── ────── ⎥ ⎢────── ───────⎥ \n\ ⎣x + y x - 2⋅y⎦τ ⎣x - 2⋅y x + y ⎦τ ⎣x + y x - 2⋅y⎦τ\ """ expected6 = \ """\ ⎡ x - y x + y ⎤ ⎡-x + y -x - y ⎤ \n\ ⎢ ───── ───────⎥ ⎢────── ─────── ⎥ \n\ ⎢ x + y x - 2⋅y⎥ ⎡ -x - y -x + y⎤ ⎢x + y x - 2⋅y ⎥ \n\ ⎢ ⎥ ⎢─────── ──────⎥ ⎢ ⎥ \n\ ⎢ 2 2 ⎥ ⎢x - 2⋅y x + y ⎥ ⎢ 2 2 ⎥ \n\ ⎢x - y x + y ⎥ ⎢ ⎥ ⎢-x + y - x - y⎥ \n\ ⎢────── ────── ⎥ ⋅⎢ 2 2⎥ + ⎢─────── ────────⎥ \n\ ⎢ 3 -x + y ⎥ ⎢- x - y x - y ⎥ ⎢ 3 -x + y ⎥ \n\ ⎢x + x ⎥ ⎢──────── ──────⎥ ⎢ x + x ⎥ \n\ ⎢ ⎥ ⎢ -x + y 3 ⎥ ⎢ ⎥ \n\ ⎢ -x - y -x + y ⎥ ⎣ x + x⎦τ ⎢ x + y x - y ⎥ \n\ ⎢─────── ────── ⎥ ⎢─────── ───── ⎥ \n\ ⎣x - 2⋅y x + y ⎦τ ⎣x - 2⋅y x + y ⎦τ\ """ assert upretty(Parallel(tf1, tf2)) == expected1 assert upretty(Parallel(-tf2, -tf1)) == expected2 assert upretty(Parallel(tf3, tf1, Series(-tf1, tf2))) == expected3 assert upretty(Parallel(Series(tf1, tf2), Series(tf2, tf3))) == expected4 assert upretty(MIMOParallel(-tfm3, -tfm2, tfm1)) == expected5 assert upretty(MIMOParallel(MIMOSeries(tfm4, -tfm2), tfm2)) == expected6 def test_pretty_Feedback(): tf = TransferFunction(1, 1, y) tf1 = TransferFunction(x + y, x - 2*y, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(y**2 - 2*y + 1, y + 5, y) tf4 = TransferFunction(x - 2*y**3, x + y, x) tf5 = TransferFunction(1 - x, x - y, y) tf6 = TransferFunction(2, 2, x) expected1 = \ """\ ⎛1⎞ \n\ ⎜─⎟ \n\ ⎝1⎠ \n\ ─────────────\n\ 1 ⎛ x + y ⎞\n\ ─ + ⎜───────⎟\n\ 1 ⎝x - 2⋅y⎠\ """ expected2 = \ """\ ⎛1⎞ \n\ ⎜─⎟ \n\ ⎝1⎠ \n\ ────────────────────────────────────\n\ ⎛ 2 ⎞\n\ 1 ⎛x - y⎞ ⎛ x + y ⎞ ⎜y - 2⋅y + 1⎟\n\ ─ + ⎜─────⎟⋅⎜───────⎟⋅⎜────────────⎟\n\ 1 ⎝x + y⎠ ⎝x - 2⋅y⎠ ⎝ y + 5 ⎠\ """ expected3 = \ """\ ⎛ x + y ⎞ \n\ ⎜───────⎟ \n\ ⎝x - 2⋅y⎠ \n\ ────────────────────────────────────────────\n\ ⎛ 2 ⎞ \n\ 1 ⎛ x + y ⎞ ⎛x - y⎞ ⎜y - 2⋅y + 1⎟ ⎛1 - x⎞\n\ ─ + ⎜───────⎟⋅⎜─────⎟⋅⎜────────────⎟⋅⎜─────⎟\n\ 1 ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝ y + 5 ⎠ ⎝x - y⎠\ """ expected4 = \ """\ ⎛ x + y ⎞ ⎛x - y⎞ \n\ ⎜───────⎟⋅⎜─────⎟ \n\ ⎝x - 2⋅y⎠ ⎝x + y⎠ \n\ ─────────────────────\n\ 1 ⎛ x + y ⎞ ⎛x - y⎞\n\ ─ + ⎜───────⎟⋅⎜─────⎟\n\ 1 ⎝x - 2⋅y⎠ ⎝x + y⎠\ """ expected5 = \ """\ ⎛ x + y ⎞ ⎛x - y⎞ \n\ ⎜───────⎟⋅⎜─────⎟ \n\ ⎝x - 2⋅y⎠ ⎝x + y⎠ \n\ ─────────────────────────────\n\ 1 ⎛ x + y ⎞ ⎛x - y⎞ ⎛1 - x⎞\n\ ─ + ⎜───────⎟⋅⎜─────⎟⋅⎜─────⎟\n\ 1 ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝x - y⎠\ """ expected6 = \ """\ ⎛ 2 ⎞ \n\ ⎜y - 2⋅y + 1⎟ ⎛1 - x⎞ \n\ ⎜────────────⎟⋅⎜─────⎟ \n\ ⎝ y + 5 ⎠ ⎝x - y⎠ \n\ ────────────────────────────────────────────\n\ ⎛ 2 ⎞ \n\ 1 ⎜y - 2⋅y + 1⎟ ⎛1 - x⎞ ⎛x - y⎞ ⎛ x + y ⎞\n\ ─ + ⎜────────────⎟⋅⎜─────⎟⋅⎜─────⎟⋅⎜───────⎟\n\ 1 ⎝ y + 5 ⎠ ⎝x - y⎠ ⎝x + y⎠ ⎝x - 2⋅y⎠\ """ expected7 = \ """\ ⎛ 3⎞ \n\ ⎜x - 2⋅y ⎟ \n\ ⎜────────⎟ \n\ ⎝ x + y ⎠ \n\ ──────────────────\n\ ⎛ 3⎞ \n\ 1 ⎜x - 2⋅y ⎟ ⎛2⎞\n\ ─ + ⎜────────⎟⋅⎜─⎟\n\ 1 ⎝ x + y ⎠ ⎝2⎠\ """ expected8 = \ """\ ⎛1 - x⎞ \n\ ⎜─────⎟ \n\ ⎝x - y⎠ \n\ ───────────\n\ 1 ⎛1 - x⎞\n\ ─ + ⎜─────⎟\n\ 1 ⎝x - y⎠\ """ expected9 = \ """\ ⎛ x + y ⎞ ⎛x - y⎞ \n\ ⎜───────⎟⋅⎜─────⎟ \n\ ⎝x - 2⋅y⎠ ⎝x + y⎠ \n\ ─────────────────────────────\n\ 1 ⎛ x + y ⎞ ⎛x - y⎞ ⎛1 - x⎞\n\ ─ - ⎜───────⎟⋅⎜─────⎟⋅⎜─────⎟\n\ 1 ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝x - y⎠\ """ expected10 = \ """\ ⎛1 - x⎞ \n\ ⎜─────⎟ \n\ ⎝x - y⎠ \n\ ───────────\n\ 1 ⎛1 - x⎞\n\ ─ - ⎜─────⎟\n\ 1 ⎝x - y⎠\ """ assert upretty(Feedback(tf, tf1)) == expected1 assert upretty(Feedback(tf, tf2*tf1*tf3)) == expected2 assert upretty(Feedback(tf1, tf2*tf3*tf5)) == expected3 assert upretty(Feedback(tf1*tf2, tf)) == expected4 assert upretty(Feedback(tf1*tf2, tf5)) == expected5 assert upretty(Feedback(tf3*tf5, tf2*tf1)) == expected6 assert upretty(Feedback(tf4, tf6)) == expected7 assert upretty(Feedback(tf5, tf)) == expected8 assert upretty(Feedback(tf1*tf2, tf5, 1)) == expected9 assert upretty(Feedback(tf5, tf, 1)) == expected10 def test_pretty_MIMOFeedback(): tf1 = TransferFunction(x + y, x - 2*y, y) tf2 = TransferFunction(x - y, x + y, y) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) tfm_3 = TransferFunctionMatrix([[tf1, tf1], [tf2, tf2]]) expected1 = \ """\ ⎛ ⎡ x + y x - y ⎤ ⎡ x - y x + y ⎤ ⎞-1 ⎡ x + y x - y ⎤ \n\ ⎜ ⎢─────── ───── ⎥ ⎢ ───── ───────⎥ ⎟ ⎢─────── ───── ⎥ \n\ ⎜ ⎢x - 2⋅y x + y ⎥ ⎢ x + y x - 2⋅y⎥ ⎟ ⎢x - 2⋅y x + y ⎥ \n\ ⎜I - ⎢ ⎥ ⋅⎢ ⎥ ⎟ ⋅ ⎢ ⎥ \n\ ⎜ ⎢ x - y x + y ⎥ ⎢ x + y x - y ⎥ ⎟ ⎢ x - y x + y ⎥ \n\ ⎜ ⎢ ───── ───────⎥ ⎢─────── ───── ⎥ ⎟ ⎢ ───── ───────⎥ \n\ ⎝ ⎣ x + y x - 2⋅y⎦τ ⎣x - 2⋅y x + y ⎦τ⎠ ⎣ x + y x - 2⋅y⎦τ\ """ expected2 = \ """\ ⎛ ⎡ x + y x - y ⎤ ⎡ x - y x + y ⎤ ⎡ x + y x + y ⎤ ⎞-1 ⎡ x + y x - y ⎤ ⎡ x - y x + y ⎤ \n\ ⎜ ⎢─────── ───── ⎥ ⎢ ───── ───────⎥ ⎢─────── ───────⎥ ⎟ ⎢─────── ───── ⎥ ⎢ ───── ───────⎥ \n\ ⎜ ⎢x - 2⋅y x + y ⎥ ⎢ x + y x - 2⋅y⎥ ⎢x - 2⋅y x - 2⋅y⎥ ⎟ ⎢x - 2⋅y x + y ⎥ ⎢ x + y x - 2⋅y⎥ \n\ ⎜I + ⎢ ⎥ ⋅⎢ ⎥ ⋅⎢ ⎥ ⎟ ⋅ ⎢ ⎥ ⋅⎢ ⎥ \n\ ⎜ ⎢ x - y x + y ⎥ ⎢ x + y x - y ⎥ ⎢ x - y x - y ⎥ ⎟ ⎢ x - y x + y ⎥ ⎢ x + y x - y ⎥ \n\ ⎜ ⎢ ───── ───────⎥ ⎢─────── ───── ⎥ ⎢ ───── ───── ⎥ ⎟ ⎢ ───── ───────⎥ ⎢─────── ───── ⎥ \n\ ⎝ ⎣ x + y x - 2⋅y⎦τ ⎣x - 2⋅y x + y ⎦τ ⎣ x + y x + y ⎦τ⎠ ⎣ x + y x - 2⋅y⎦τ ⎣x - 2⋅y x + y ⎦τ\ """ assert upretty(MIMOFeedback(tfm_1, tfm_2, 1)) == \ expected1 # Positive MIMOFeedback assert upretty(MIMOFeedback(tfm_1*tfm_2, tfm_3)) == \ expected2 # Negative MIMOFeedback (Default) def test_pretty_TransferFunctionMatrix(): tf1 = TransferFunction(x + y, x - 2*y, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(y**2 - 2*y + 1, y + 5, y) tf4 = TransferFunction(y, x**2 + x + 1, y) tf5 = TransferFunction(1 - x, x - y, y) tf6 = TransferFunction(2, 2, y) expected1 = \ """\ ⎡ x + y ⎤ \n\ ⎢───────⎥ \n\ ⎢x - 2⋅y⎥ \n\ ⎢ ⎥ \n\ ⎢ x - y ⎥ \n\ ⎢ ───── ⎥ \n\ ⎣ x + y ⎦τ\ """ expected2 = \ """\ ⎡ x + y ⎤ \n\ ⎢ ─────── ⎥ \n\ ⎢ x - 2⋅y ⎥ \n\ ⎢ ⎥ \n\ ⎢ x - y ⎥ \n\ ⎢ ───── ⎥ \n\ ⎢ x + y ⎥ \n\ ⎢ ⎥ \n\ ⎢ 2 ⎥ \n\ ⎢- y + 2⋅y - 1⎥ \n\ ⎢──────────────⎥ \n\ ⎣ y + 5 ⎦τ\ """ expected3 = \ """\ ⎡ x + y x - y ⎤ \n\ ⎢ ─────── ───── ⎥ \n\ ⎢ x - 2⋅y x + y ⎥ \n\ ⎢ ⎥ \n\ ⎢ 2 ⎥ \n\ ⎢y - 2⋅y + 1 y ⎥ \n\ ⎢──────────── ──────────⎥ \n\ ⎢ y + 5 2 ⎥ \n\ ⎢ x + x + 1⎥ \n\ ⎢ ⎥ \n\ ⎢ 1 - x 2 ⎥ \n\ ⎢ ───── ─ ⎥ \n\ ⎣ x - y 2 ⎦τ\ """ expected4 = \ """\ ⎡ x - y x + y y ⎤ \n\ ⎢ ───── ─────── ──────────⎥ \n\ ⎢ x + y x - 2⋅y 2 ⎥ \n\ ⎢ x + x + 1⎥ \n\ ⎢ ⎥ \n\ ⎢ 2 ⎥ \n\ ⎢- y + 2⋅y - 1 x - 1 -2 ⎥ \n\ ⎢────────────── ───── ─── ⎥ \n\ ⎣ y + 5 x - y 2 ⎦τ\ """ expected5 = \ """\ ⎡ x + y x - y x + y y ⎤ \n\ ⎢───────⋅───── ─────── ──────────⎥ \n\ ⎢x - 2⋅y x + y x - 2⋅y 2 ⎥ \n\ ⎢ x + x + 1⎥ \n\ ⎢ ⎥ \n\ ⎢ 1 - x 2 x + y -2 ⎥ \n\ ⎢ ───── + ─ ─────── ─── ⎥ \n\ ⎣ x - y 2 x - 2⋅y 2 ⎦τ\ """ assert upretty(TransferFunctionMatrix([[tf1], [tf2]])) == expected1 assert upretty(TransferFunctionMatrix([[tf1], [tf2], [-tf3]])) == expected2 assert upretty(TransferFunctionMatrix([[tf1, tf2], [tf3, tf4], [tf5, tf6]])) == expected3 assert upretty(TransferFunctionMatrix([[tf2, tf1, tf4], [-tf3, -tf5, -tf6]])) == expected4 assert upretty(TransferFunctionMatrix([[Series(tf2, tf1), tf1, tf4], [Parallel(tf6, tf5), tf1, -tf6]])) == \ expected5 def test_pretty_order(): expr = O(1) ascii_str = \ """\ O(1)\ """ ucode_str = \ """\ O(1)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(1/x) ascii_str = \ """\ /1\\\n\ O|-|\n\ \\x/\ """ ucode_str = \ """\ ⎛1⎞\n\ O⎜─⎟\n\ ⎝x⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(x**2 + y**2) ascii_str = \ """\ / 2 2 \\\n\ O\\x + y ; (x, y) -> (0, 0)/\ """ ucode_str = \ """\ ⎛ 2 2 ⎞\n\ O⎝x + y ; (x, y) → (0, 0)⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(1, (x, oo)) ascii_str = \ """\ O(1; x -> oo)\ """ ucode_str = \ """\ O(1; x → ∞)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(1/x, (x, oo)) ascii_str = \ """\ /1 \\\n\ O|-; x -> oo|\n\ \\x /\ """ ucode_str = \ """\ ⎛1 ⎞\n\ O⎜─; x → ∞⎟\n\ ⎝x ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(x**2 + y**2, (x, oo), (y, oo)) ascii_str = \ """\ / 2 2 \\\n\ O\\x + y ; (x, y) -> (oo, oo)/\ """ ucode_str = \ """\ ⎛ 2 2 ⎞\n\ O⎝x + y ; (x, y) → (∞, ∞)⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_derivatives(): # Simple expr = Derivative(log(x), x, evaluate=False) ascii_str = \ """\ d \n\ --(log(x))\n\ dx \ """ ucode_str = \ """\ d \n\ ──(log(x))\n\ dx \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Derivative(log(x), x, evaluate=False) + x ascii_str_1 = \ """\ d \n\ x + --(log(x))\n\ dx \ """ ascii_str_2 = \ """\ d \n\ --(log(x)) + x\n\ dx \ """ ucode_str_1 = \ """\ d \n\ x + ──(log(x))\n\ dx \ """ ucode_str_2 = \ """\ d \n\ ──(log(x)) + x\n\ dx \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] # basic partial derivatives expr = Derivative(log(x + y) + x, x) ascii_str_1 = \ """\ d \n\ --(log(x + y) + x)\n\ dx \ """ ascii_str_2 = \ """\ d \n\ --(x + log(x + y))\n\ dx \ """ ucode_str_1 = \ """\ ∂ \n\ ──(log(x + y) + x)\n\ ∂x \ """ ucode_str_2 = \ """\ ∂ \n\ ──(x + log(x + y))\n\ ∂x \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2], upretty(expr) # Multiple symbols expr = Derivative(log(x) + x**2, x, y) ascii_str_1 = \ """\ 2 \n\ d / 2\\\n\ -----\\log(x) + x /\n\ dy dx \ """ ascii_str_2 = \ """\ 2 \n\ d / 2 \\\n\ -----\\x + log(x)/\n\ dy dx \ """ ucode_str_1 = \ """\ 2 \n\ d ⎛ 2⎞\n\ ─────⎝log(x) + x ⎠\n\ dy dx \ """ ucode_str_2 = \ """\ 2 \n\ d ⎛ 2 ⎞\n\ ─────⎝x + log(x)⎠\n\ dy dx \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Derivative(2*x*y, y, x) + x**2 ascii_str_1 = \ """\ 2 \n\ d 2\n\ -----(2*x*y) + x \n\ dx dy \ """ ascii_str_2 = \ """\ 2 \n\ 2 d \n\ x + -----(2*x*y)\n\ dx dy \ """ ucode_str_1 = \ """\ 2 \n\ ∂ 2\n\ ─────(2⋅x⋅y) + x \n\ ∂x ∂y \ """ ucode_str_2 = \ """\ 2 \n\ 2 ∂ \n\ x + ─────(2⋅x⋅y)\n\ ∂x ∂y \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Derivative(2*x*y, x, x) ascii_str = \ """\ 2 \n\ d \n\ ---(2*x*y)\n\ 2 \n\ dx \ """ ucode_str = \ """\ 2 \n\ ∂ \n\ ───(2⋅x⋅y)\n\ 2 \n\ ∂x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Derivative(2*x*y, x, 17) ascii_str = \ """\ 17 \n\ d \n\ ----(2*x*y)\n\ 17 \n\ dx \ """ ucode_str = \ """\ 17 \n\ ∂ \n\ ────(2⋅x⋅y)\n\ 17 \n\ ∂x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Derivative(2*x*y, x, x, y) ascii_str = \ """\ 3 \n\ d \n\ ------(2*x*y)\n\ 2 \n\ dy dx \ """ ucode_str = \ """\ 3 \n\ ∂ \n\ ──────(2⋅x⋅y)\n\ 2 \n\ ∂y ∂x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # Greek letters alpha = Symbol('alpha') beta = Function('beta') expr = beta(alpha).diff(alpha) ascii_str = \ """\ d \n\ ------(beta(alpha))\n\ dalpha \ """ ucode_str = \ """\ d \n\ ──(β(α))\n\ dα \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Derivative(f(x), (x, n)) ascii_str = \ """\ n \n\ d \n\ ---(f(x))\n\ n \n\ dx \ """ ucode_str = \ """\ n \n\ d \n\ ───(f(x))\n\ n \n\ dx \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_integrals(): expr = Integral(log(x), x) ascii_str = \ """\ / \n\ | \n\ | log(x) dx\n\ | \n\ / \ """ ucode_str = \ """\ ⌠ \n\ ⎮ log(x) dx\n\ ⌡ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**2, x) ascii_str = \ """\ / \n\ | \n\ | 2 \n\ | x dx\n\ | \n\ / \ """ ucode_str = \ """\ ⌠ \n\ ⎮ 2 \n\ ⎮ x dx\n\ ⌡ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral((sin(x))**2 / (tan(x))**2) ascii_str = \ """\ / \n\ | \n\ | 2 \n\ | sin (x) \n\ | ------- dx\n\ | 2 \n\ | tan (x) \n\ | \n\ / \ """ ucode_str = \ """\ ⌠ \n\ ⎮ 2 \n\ ⎮ sin (x) \n\ ⎮ ─────── dx\n\ ⎮ 2 \n\ ⎮ tan (x) \n\ ⌡ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**(2**x), x) ascii_str = \ """\ / \n\ | \n\ | / x\\ \n\ | \\2 / \n\ | x dx\n\ | \n\ / \ """ ucode_str = \ """\ ⌠ \n\ ⎮ ⎛ x⎞ \n\ ⎮ ⎝2 ⎠ \n\ ⎮ x dx\n\ ⌡ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**2, (x, 1, 2)) ascii_str = \ """\ 2 \n\ / \n\ | \n\ | 2 \n\ | x dx\n\ | \n\ / \n\ 1 \ """ ucode_str = \ """\ 2 \n\ ⌠ \n\ ⎮ 2 \n\ ⎮ x dx\n\ ⌡ \n\ 1 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**2, (x, Rational(1, 2), 10)) ascii_str = \ """\ 10 \n\ / \n\ | \n\ | 2 \n\ | x dx\n\ | \n\ / \n\ 1/2 \ """ ucode_str = \ """\ 10 \n\ ⌠ \n\ ⎮ 2 \n\ ⎮ x dx\n\ ⌡ \n\ 1/2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**2*y**2, x, y) ascii_str = \ """\ / / \n\ | | \n\ | | 2 2 \n\ | | x *y dx dy\n\ | | \n\ / / \ """ ucode_str = \ """\ ⌠ ⌠ \n\ ⎮ ⎮ 2 2 \n\ ⎮ ⎮ x ⋅y dx dy\n\ ⌡ ⌡ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(sin(th)/cos(ph), (th, 0, pi), (ph, 0, 2*pi)) ascii_str = \ """\ 2*pi pi \n\ / / \n\ | | \n\ | | sin(theta) \n\ | | ---------- d(theta) d(phi)\n\ | | cos(phi) \n\ | | \n\ / / \n\ 0 0 \ """ ucode_str = \ """\ 2⋅π π \n\ ⌠ ⌠ \n\ ⎮ ⎮ sin(θ) \n\ ⎮ ⎮ ────── dθ dφ\n\ ⎮ ⎮ cos(φ) \n\ ⌡ ⌡ \n\ 0 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_matrix(): # Empty Matrix expr = Matrix() ascii_str = "[]" unicode_str = "[]" assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Matrix(2, 0, lambda i, j: 0) ascii_str = "[]" unicode_str = "[]" assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Matrix(0, 2, lambda i, j: 0) ascii_str = "[]" unicode_str = "[]" assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Matrix([[x**2 + 1, 1], [y, x + y]]) ascii_str_1 = \ """\ [ 2 ] [1 + x 1 ] [ ] [ y x + y]\ """ ascii_str_2 = \ """\ [ 2 ] [x + 1 1 ] [ ] [ y x + y]\ """ ucode_str_1 = \ """\ ⎡ 2 ⎤ ⎢1 + x 1 ⎥ ⎢ ⎥ ⎣ y x + y⎦\ """ ucode_str_2 = \ """\ ⎡ 2 ⎤ ⎢x + 1 1 ⎥ ⎢ ⎥ ⎣ y x + y⎦\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Matrix([[x/y, y, th], [0, exp(I*k*ph), 1]]) ascii_str = \ """\ [x ] [- y theta] [y ] [ ] [ I*k*phi ] [0 e 1 ]\ """ ucode_str = \ """\ ⎡x ⎤ ⎢─ y θ⎥ ⎢y ⎥ ⎢ ⎥ ⎢ ⅈ⋅k⋅φ ⎥ ⎣0 ℯ 1⎦\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str unicode_str = \ """\ ⎡v̇_msc_00 0 0 ⎤ ⎢ ⎥ ⎢ 0 v̇_msc_01 0 ⎥ ⎢ ⎥ ⎣ 0 0 v̇_msc_02⎦\ """ expr = diag(*MatrixSymbol('vdot_msc',1,3)) assert upretty(expr) == unicode_str def test_pretty_ndim_arrays(): x, y, z, w = symbols("x y z w") for ArrayType in (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray): # Basic: scalar array M = ArrayType(x) assert pretty(M) == "x" assert upretty(M) == "x" M = ArrayType([[1/x, y], [z, w]]) M1 = ArrayType([1/x, y, z]) M2 = tensorproduct(M1, M) M3 = tensorproduct(M, M) ascii_str = \ """\ [1 ]\n\ [- y]\n\ [x ]\n\ [ ]\n\ [z w]\ """ ucode_str = \ """\ ⎡1 ⎤\n\ ⎢─ y⎥\n\ ⎢x ⎥\n\ ⎢ ⎥\n\ ⎣z w⎦\ """ assert pretty(M) == ascii_str assert upretty(M) == ucode_str ascii_str = \ """\ [1 ]\n\ [- y z]\n\ [x ]\ """ ucode_str = \ """\ ⎡1 ⎤\n\ ⎢─ y z⎥\n\ ⎣x ⎦\ """ assert pretty(M1) == ascii_str assert upretty(M1) == ucode_str ascii_str = \ """\ [[1 y] ]\n\ [[-- -] [z ]]\n\ [[ 2 x] [ y 2 ] [- y*z]]\n\ [[x ] [ - y ] [x ]]\n\ [[ ] [ x ] [ ]]\n\ [[z w] [ ] [ 2 ]]\n\ [[- -] [y*z w*y] [z w*z]]\n\ [[x x] ]\ """ ucode_str = \ """\ ⎡⎡1 y⎤ ⎤\n\ ⎢⎢── ─⎥ ⎡z ⎤⎥\n\ ⎢⎢ 2 x⎥ ⎡ y 2 ⎤ ⎢─ y⋅z⎥⎥\n\ ⎢⎢x ⎥ ⎢ ─ y ⎥ ⎢x ⎥⎥\n\ ⎢⎢ ⎥ ⎢ x ⎥ ⎢ ⎥⎥\n\ ⎢⎢z w⎥ ⎢ ⎥ ⎢ 2 ⎥⎥\n\ ⎢⎢─ ─⎥ ⎣y⋅z w⋅y⎦ ⎣z w⋅z⎦⎥\n\ ⎣⎣x x⎦ ⎦\ """ assert pretty(M2) == ascii_str assert upretty(M2) == ucode_str ascii_str = \ """\ [ [1 y] ]\n\ [ [-- -] ]\n\ [ [ 2 x] [ y 2 ]]\n\ [ [x ] [ - y ]]\n\ [ [ ] [ x ]]\n\ [ [z w] [ ]]\n\ [ [- -] [y*z w*y]]\n\ [ [x x] ]\n\ [ ]\n\ [[z ] [ w ]]\n\ [[- y*z] [ - w*y]]\n\ [[x ] [ x ]]\n\ [[ ] [ ]]\n\ [[ 2 ] [ 2 ]]\n\ [[z w*z] [w*z w ]]\ """ ucode_str = \ """\ ⎡ ⎡1 y⎤ ⎤\n\ ⎢ ⎢── ─⎥ ⎥\n\ ⎢ ⎢ 2 x⎥ ⎡ y 2 ⎤⎥\n\ ⎢ ⎢x ⎥ ⎢ ─ y ⎥⎥\n\ ⎢ ⎢ ⎥ ⎢ x ⎥⎥\n\ ⎢ ⎢z w⎥ ⎢ ⎥⎥\n\ ⎢ ⎢─ ─⎥ ⎣y⋅z w⋅y⎦⎥\n\ ⎢ ⎣x x⎦ ⎥\n\ ⎢ ⎥\n\ ⎢⎡z ⎤ ⎡ w ⎤⎥\n\ ⎢⎢─ y⋅z⎥ ⎢ ─ w⋅y⎥⎥\n\ ⎢⎢x ⎥ ⎢ x ⎥⎥\n\ ⎢⎢ ⎥ ⎢ ⎥⎥\n\ ⎢⎢ 2 ⎥ ⎢ 2 ⎥⎥\n\ ⎣⎣z w⋅z⎦ ⎣w⋅z w ⎦⎦\ """ assert pretty(M3) == ascii_str assert upretty(M3) == ucode_str Mrow = ArrayType([[x, y, 1 / z]]) Mcolumn = ArrayType([[x], [y], [1 / z]]) Mcol2 = ArrayType([Mcolumn.tolist()]) ascii_str = \ """\ [[ 1]]\n\ [[x y -]]\n\ [[ z]]\ """ ucode_str = \ """\ ⎡⎡ 1⎤⎤\n\ ⎢⎢x y ─⎥⎥\n\ ⎣⎣ z⎦⎦\ """ assert pretty(Mrow) == ascii_str assert upretty(Mrow) == ucode_str ascii_str = \ """\ [x]\n\ [ ]\n\ [y]\n\ [ ]\n\ [1]\n\ [-]\n\ [z]\ """ ucode_str = \ """\ ⎡x⎤\n\ ⎢ ⎥\n\ ⎢y⎥\n\ ⎢ ⎥\n\ ⎢1⎥\n\ ⎢─⎥\n\ ⎣z⎦\ """ assert pretty(Mcolumn) == ascii_str assert upretty(Mcolumn) == ucode_str ascii_str = \ """\ [[x]]\n\ [[ ]]\n\ [[y]]\n\ [[ ]]\n\ [[1]]\n\ [[-]]\n\ [[z]]\ """ ucode_str = \ """\ ⎡⎡x⎤⎤\n\ ⎢⎢ ⎥⎥\n\ ⎢⎢y⎥⎥\n\ ⎢⎢ ⎥⎥\n\ ⎢⎢1⎥⎥\n\ ⎢⎢─⎥⎥\n\ ⎣⎣z⎦⎦\ """ assert pretty(Mcol2) == ascii_str assert upretty(Mcol2) == ucode_str def test_tensor_TensorProduct(): A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) assert upretty(TensorProduct(A, B)) == "A\u2297B" assert upretty(TensorProduct(A, B, A)) == "A\u2297B\u2297A" def test_diffgeom_print_WedgeProduct(): from sympy.diffgeom.rn import R2 from sympy.diffgeom import WedgeProduct wp = WedgeProduct(R2.dx, R2.dy) assert upretty(wp) == "ⅆ x∧ⅆ y" def test_Adjoint(): X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert pretty(Adjoint(X)) == " +\nX " assert pretty(Adjoint(X + Y)) == " +\n(X + Y) " assert pretty(Adjoint(X) + Adjoint(Y)) == " + +\nX + Y " assert pretty(Adjoint(X*Y)) == " +\n(X*Y) " assert pretty(Adjoint(Y)*Adjoint(X)) == " + +\nY *X " assert pretty(Adjoint(X**2)) == " +\n/ 2\\ \n\\X / " assert pretty(Adjoint(X)**2) == " 2\n/ +\\ \n\\X / " assert pretty(Adjoint(Inverse(X))) == " +\n/ -1\\ \n\\X / " assert pretty(Inverse(Adjoint(X))) == " -1\n/ +\\ \n\\X / " assert pretty(Adjoint(Transpose(X))) == " +\n/ T\\ \n\\X / " assert pretty(Transpose(Adjoint(X))) == " T\n/ +\\ \n\\X / " assert upretty(Adjoint(X)) == " †\nX " assert upretty(Adjoint(X + Y)) == " †\n(X + Y) " assert upretty(Adjoint(X) + Adjoint(Y)) == " † †\nX + Y " assert upretty(Adjoint(X*Y)) == " †\n(X⋅Y) " assert upretty(Adjoint(Y)*Adjoint(X)) == " † †\nY ⋅X " assert upretty(Adjoint(X**2)) == \ " †\n⎛ 2⎞ \n⎝X ⎠ " assert upretty(Adjoint(X)**2) == \ " 2\n⎛ †⎞ \n⎝X ⎠ " assert upretty(Adjoint(Inverse(X))) == \ " †\n⎛ -1⎞ \n⎝X ⎠ " assert upretty(Inverse(Adjoint(X))) == \ " -1\n⎛ †⎞ \n⎝X ⎠ " assert upretty(Adjoint(Transpose(X))) == \ " †\n⎛ T⎞ \n⎝X ⎠ " assert upretty(Transpose(Adjoint(X))) == \ " T\n⎛ †⎞ \n⎝X ⎠ " def test_pretty_Trace_issue_9044(): X = Matrix([[1, 2], [3, 4]]) Y = Matrix([[2, 4], [6, 8]]) ascii_str_1 = \ """\ /[1 2]\\ tr|[ ]| \\[3 4]/\ """ ucode_str_1 = \ """\ ⎛⎡1 2⎤⎞ tr⎜⎢ ⎥⎟ ⎝⎣3 4⎦⎠\ """ ascii_str_2 = \ """\ /[1 2]\\ /[2 4]\\ tr|[ ]| + tr|[ ]| \\[3 4]/ \\[6 8]/\ """ ucode_str_2 = \ """\ ⎛⎡1 2⎤⎞ ⎛⎡2 4⎤⎞ tr⎜⎢ ⎥⎟ + tr⎜⎢ ⎥⎟ ⎝⎣3 4⎦⎠ ⎝⎣6 8⎦⎠\ """ assert pretty(Trace(X)) == ascii_str_1 assert upretty(Trace(X)) == ucode_str_1 assert pretty(Trace(X) + Trace(Y)) == ascii_str_2 assert upretty(Trace(X) + Trace(Y)) == ucode_str_2 def test_MatrixSlice(): n = Symbol('n', integer=True) x, y, z, w, t, = symbols('x y z w t') X = MatrixSymbol('X', n, n) Y = MatrixSymbol('Y', 10, 10) Z = MatrixSymbol('Z', 10, 10) expr = MatrixSlice(X, (None, None, None), (None, None, None)) assert pretty(expr) == upretty(expr) == 'X[:, :]' expr = X[x:x + 1, y:y + 1] assert pretty(expr) == upretty(expr) == 'X[x:x + 1, y:y + 1]' expr = X[x:x + 1:2, y:y + 1:2] assert pretty(expr) == upretty(expr) == 'X[x:x + 1:2, y:y + 1:2]' expr = X[:x, y:] assert pretty(expr) == upretty(expr) == 'X[:x, y:]' expr = X[:x, y:] assert pretty(expr) == upretty(expr) == 'X[:x, y:]' expr = X[x:, :y] assert pretty(expr) == upretty(expr) == 'X[x:, :y]' expr = X[x:y, z:w] assert pretty(expr) == upretty(expr) == 'X[x:y, z:w]' expr = X[x:y:t, w:t:x] assert pretty(expr) == upretty(expr) == 'X[x:y:t, w:t:x]' expr = X[x::y, t::w] assert pretty(expr) == upretty(expr) == 'X[x::y, t::w]' expr = X[:x:y, :t:w] assert pretty(expr) == upretty(expr) == 'X[:x:y, :t:w]' expr = X[::x, ::y] assert pretty(expr) == upretty(expr) == 'X[::x, ::y]' expr = MatrixSlice(X, (0, None, None), (0, None, None)) assert pretty(expr) == upretty(expr) == 'X[:, :]' expr = MatrixSlice(X, (None, n, None), (None, n, None)) assert pretty(expr) == upretty(expr) == 'X[:, :]' expr = MatrixSlice(X, (0, n, None), (0, n, None)) assert pretty(expr) == upretty(expr) == 'X[:, :]' expr = MatrixSlice(X, (0, n, 2), (0, n, 2)) assert pretty(expr) == upretty(expr) == 'X[::2, ::2]' expr = X[1:2:3, 4:5:6] assert pretty(expr) == upretty(expr) == 'X[1:2:3, 4:5:6]' expr = X[1:3:5, 4:6:8] assert pretty(expr) == upretty(expr) == 'X[1:3:5, 4:6:8]' expr = X[1:10:2] assert pretty(expr) == upretty(expr) == 'X[1:10:2, :]' expr = Y[:5, 1:9:2] assert pretty(expr) == upretty(expr) == 'Y[:5, 1:9:2]' expr = Y[:5, 1:10:2] assert pretty(expr) == upretty(expr) == 'Y[:5, 1::2]' expr = Y[5, :5:2] assert pretty(expr) == upretty(expr) == 'Y[5:6, :5:2]' expr = X[0:1, 0:1] assert pretty(expr) == upretty(expr) == 'X[:1, :1]' expr = X[0:1:2, 0:1:2] assert pretty(expr) == upretty(expr) == 'X[:1:2, :1:2]' expr = (Y + Z)[2:, 2:] assert pretty(expr) == upretty(expr) == '(Y + Z)[2:, 2:]' def test_MatrixExpressions(): n = Symbol('n', integer=True) X = MatrixSymbol('X', n, n) assert pretty(X) == upretty(X) == "X" # Apply function elementwise (`ElementwiseApplyFunc`): expr = (X.T*X).applyfunc(sin) ascii_str = """\ / T \\\n\ (d -> sin(d)).\\X *X/\ """ ucode_str = """\ ⎛ T ⎞\n\ (d ↦ sin(d))˳⎝X ⋅X⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str lamda = Lambda(x, 1/x) expr = (n*X).applyfunc(lamda) ascii_str = """\ / 1\\ \n\ |x -> -|.(n*X)\n\ \\ x/ \ """ ucode_str = """\ ⎛ 1⎞ \n\ ⎜x ↦ ─⎟˳(n⋅X)\n\ ⎝ x⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_dotproduct(): from sympy.matrices import Matrix, MatrixSymbol from sympy.matrices.expressions.dotproduct import DotProduct n = symbols("n", integer=True) A = MatrixSymbol('A', n, 1) B = MatrixSymbol('B', n, 1) C = Matrix(1, 3, [1, 2, 3]) D = Matrix(1, 3, [1, 3, 4]) assert pretty(DotProduct(A, B)) == "A*B" assert pretty(DotProduct(C, D)) == "[1 2 3]*[1 3 4]" assert upretty(DotProduct(A, B)) == "A⋅B" assert upretty(DotProduct(C, D)) == "[1 2 3]⋅[1 3 4]" def test_pretty_piecewise(): expr = Piecewise((x, x < 1), (x**2, True)) ascii_str = \ """\ /x for x < 1\n\ | \n\ < 2 \n\ |x otherwise\n\ \\ \ """ ucode_str = \ """\ ⎧x for x < 1\n\ ⎪ \n\ ⎨ 2 \n\ ⎪x otherwise\n\ ⎩ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -Piecewise((x, x < 1), (x**2, True)) ascii_str = \ """\ //x for x < 1\\\n\ || |\n\ -|< 2 |\n\ ||x otherwise|\n\ \\\\ /\ """ ucode_str = \ """\ ⎛⎧x for x < 1⎞\n\ ⎜⎪ ⎟\n\ -⎜⎨ 2 ⎟\n\ ⎜⎪x otherwise⎟\n\ ⎝⎩ ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = x + Piecewise((x, x > 0), (y, True)) + Piecewise((x/y, x < 2), (y**2, x > 2), (1, True)) + 1 ascii_str = \ """\ //x \\ \n\ ||- for x < 2| \n\ ||y | \n\ //x for x > 0\\ || | \n\ x + |< | + |< 2 | + 1\n\ \\\\y otherwise/ ||y for x > 2| \n\ || | \n\ ||1 otherwise| \n\ \\\\ / \ """ ucode_str = \ """\ ⎛⎧x ⎞ \n\ ⎜⎪─ for x < 2⎟ \n\ ⎜⎪y ⎟ \n\ ⎛⎧x for x > 0⎞ ⎜⎪ ⎟ \n\ x + ⎜⎨ ⎟ + ⎜⎨ 2 ⎟ + 1\n\ ⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟ \n\ ⎜⎪ ⎟ \n\ ⎜⎪1 otherwise⎟ \n\ ⎝⎩ ⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = x - Piecewise((x, x > 0), (y, True)) + Piecewise((x/y, x < 2), (y**2, x > 2), (1, True)) + 1 ascii_str = \ """\ //x \\ \n\ ||- for x < 2| \n\ ||y | \n\ //x for x > 0\\ || | \n\ x - |< | + |< 2 | + 1\n\ \\\\y otherwise/ ||y for x > 2| \n\ || | \n\ ||1 otherwise| \n\ \\\\ / \ """ ucode_str = \ """\ ⎛⎧x ⎞ \n\ ⎜⎪─ for x < 2⎟ \n\ ⎜⎪y ⎟ \n\ ⎛⎧x for x > 0⎞ ⎜⎪ ⎟ \n\ x - ⎜⎨ ⎟ + ⎜⎨ 2 ⎟ + 1\n\ ⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟ \n\ ⎜⎪ ⎟ \n\ ⎜⎪1 otherwise⎟ \n\ ⎝⎩ ⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = x*Piecewise((x, x > 0), (y, True)) ascii_str = \ """\ //x for x > 0\\\n\ x*|< |\n\ \\\\y otherwise/\ """ ucode_str = \ """\ ⎛⎧x for x > 0⎞\n\ x⋅⎜⎨ ⎟\n\ ⎝⎩y otherwise⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Piecewise((x, x > 0), (y, True))*Piecewise((x/y, x < 2), (y**2, x > 2), (1, True)) ascii_str = \ """\ //x \\\n\ ||- for x < 2|\n\ ||y |\n\ //x for x > 0\\ || |\n\ |< |*|< 2 |\n\ \\\\y otherwise/ ||y for x > 2|\n\ || |\n\ ||1 otherwise|\n\ \\\\ /\ """ ucode_str = \ """\ ⎛⎧x ⎞\n\ ⎜⎪─ for x < 2⎟\n\ ⎜⎪y ⎟\n\ ⎛⎧x for x > 0⎞ ⎜⎪ ⎟\n\ ⎜⎨ ⎟⋅⎜⎨ 2 ⎟\n\ ⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟\n\ ⎜⎪ ⎟\n\ ⎜⎪1 otherwise⎟\n\ ⎝⎩ ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -Piecewise((x, x > 0), (y, True))*Piecewise((x/y, x < 2), (y**2, x > 2), (1, True)) ascii_str = \ """\ //x \\\n\ ||- for x < 2|\n\ ||y |\n\ //x for x > 0\\ || |\n\ -|< |*|< 2 |\n\ \\\\y otherwise/ ||y for x > 2|\n\ || |\n\ ||1 otherwise|\n\ \\\\ /\ """ ucode_str = \ """\ ⎛⎧x ⎞\n\ ⎜⎪─ for x < 2⎟\n\ ⎜⎪y ⎟\n\ ⎛⎧x for x > 0⎞ ⎜⎪ ⎟\n\ -⎜⎨ ⎟⋅⎜⎨ 2 ⎟\n\ ⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟\n\ ⎜⎪ ⎟\n\ ⎜⎪1 otherwise⎟\n\ ⎝⎩ ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Piecewise((0, Abs(1/y) < 1), (1, Abs(y) < 1), (y*meijerg(((2, 1), ()), ((), (1, 0)), 1/y), True)) ascii_str = \ """\ / 1 \n\ | 0 for --- < 1\n\ | |y| \n\ | \n\ < 1 for |y| < 1\n\ | \n\ | __0, 2 /2, 1 | 1\\ \n\ |y*/__ | | -| otherwise \n\ \\ \\_|2, 2 \\ 1, 0 | y/ \ """ ucode_str = \ """\ ⎧ 1 \n\ ⎪ 0 for ─── < 1\n\ ⎪ │y│ \n\ ⎪ \n\ ⎨ 1 for │y│ < 1\n\ ⎪ \n\ ⎪ ╭─╮0, 2 ⎛2, 1 │ 1⎞ \n\ ⎪y⋅│╶┐ ⎜ │ ─⎟ otherwise \n\ ⎩ ╰─╯2, 2 ⎝ 1, 0 │ y⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # XXX: We have to use evaluate=False here because Piecewise._eval_power # denests the power. expr = Pow(Piecewise((x, x > 0), (y, True)), 2, evaluate=False) ascii_str = \ """\ 2\n\ //x for x > 0\\ \n\ |< | \n\ \\\\y otherwise/ \ """ ucode_str = \ """\ 2\n\ ⎛⎧x for x > 0⎞ \n\ ⎜⎨ ⎟ \n\ ⎝⎩y otherwise⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_ITE(): expr = ITE(x, y, z) assert pretty(expr) == ( '/y for x \n' '< \n' '\\z otherwise' ) assert upretty(expr) == """\ ⎧y for x \n\ ⎨ \n\ ⎩z otherwise\ """ def test_pretty_seq(): expr = () ascii_str = \ """\ ()\ """ ucode_str = \ """\ ()\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = [] ascii_str = \ """\ []\ """ ucode_str = \ """\ []\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = {} expr_2 = {} ascii_str = \ """\ {}\ """ ucode_str = \ """\ {}\ """ assert pretty(expr) == ascii_str assert pretty(expr_2) == ascii_str assert upretty(expr) == ucode_str assert upretty(expr_2) == ucode_str expr = (1/x,) ascii_str = \ """\ 1 \n\ (-,)\n\ x \ """ ucode_str = \ """\ ⎛1 ⎞\n\ ⎜─,⎟\n\ ⎝x ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = [x**2, 1/x, x, y, sin(th)**2/cos(ph)**2] ascii_str = \ """\ 2 \n\ 2 1 sin (theta) \n\ [x , -, x, y, -----------]\n\ x 2 \n\ cos (phi) \ """ ucode_str = \ """\ ⎡ 2 ⎤\n\ ⎢ 2 1 sin (θ)⎥\n\ ⎢x , ─, x, y, ───────⎥\n\ ⎢ x 2 ⎥\n\ ⎣ cos (φ)⎦\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x**2, 1/x, x, y, sin(th)**2/cos(ph)**2) ascii_str = \ """\ 2 \n\ 2 1 sin (theta) \n\ (x , -, x, y, -----------)\n\ x 2 \n\ cos (phi) \ """ ucode_str = \ """\ ⎛ 2 ⎞\n\ ⎜ 2 1 sin (θ)⎟\n\ ⎜x , ─, x, y, ───────⎟\n\ ⎜ x 2 ⎟\n\ ⎝ cos (φ)⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Tuple(x**2, 1/x, x, y, sin(th)**2/cos(ph)**2) ascii_str = \ """\ 2 \n\ 2 1 sin (theta) \n\ (x , -, x, y, -----------)\n\ x 2 \n\ cos (phi) \ """ ucode_str = \ """\ ⎛ 2 ⎞\n\ ⎜ 2 1 sin (θ)⎟\n\ ⎜x , ─, x, y, ───────⎟\n\ ⎜ x 2 ⎟\n\ ⎝ cos (φ)⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = {x: sin(x)} expr_2 = Dict({x: sin(x)}) ascii_str = \ """\ {x: sin(x)}\ """ ucode_str = \ """\ {x: sin(x)}\ """ assert pretty(expr) == ascii_str assert pretty(expr_2) == ascii_str assert upretty(expr) == ucode_str assert upretty(expr_2) == ucode_str expr = {1/x: 1/y, x: sin(x)**2} expr_2 = Dict({1/x: 1/y, x: sin(x)**2}) ascii_str = \ """\ 1 1 2 \n\ {-: -, x: sin (x)}\n\ x y \ """ ucode_str = \ """\ ⎧1 1 2 ⎫\n\ ⎨─: ─, x: sin (x)⎬\n\ ⎩x y ⎭\ """ assert pretty(expr) == ascii_str assert pretty(expr_2) == ascii_str assert upretty(expr) == ucode_str assert upretty(expr_2) == ucode_str # There used to be a bug with pretty-printing sequences of even height. expr = [x**2] ascii_str = \ """\ 2 \n\ [x ]\ """ ucode_str = \ """\ ⎡ 2⎤\n\ ⎣x ⎦\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x**2,) ascii_str = \ """\ 2 \n\ (x ,)\ """ ucode_str = \ """\ ⎛ 2 ⎞\n\ ⎝x ,⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Tuple(x**2) ascii_str = \ """\ 2 \n\ (x ,)\ """ ucode_str = \ """\ ⎛ 2 ⎞\n\ ⎝x ,⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = {x**2: 1} expr_2 = Dict({x**2: 1}) ascii_str = \ """\ 2 \n\ {x : 1}\ """ ucode_str = \ """\ ⎧ 2 ⎫\n\ ⎨x : 1⎬\n\ ⎩ ⎭\ """ assert pretty(expr) == ascii_str assert pretty(expr_2) == ascii_str assert upretty(expr) == ucode_str assert upretty(expr_2) == ucode_str def test_any_object_in_sequence(): # Cf. issue 5306 b1 = Basic() b2 = Basic(Basic()) expr = [b2, b1] assert pretty(expr) == "[Basic(Basic()), Basic()]" assert upretty(expr) == "[Basic(Basic()), Basic()]" expr = {b2, b1} assert pretty(expr) == "{Basic(), Basic(Basic())}" assert upretty(expr) == "{Basic(), Basic(Basic())}" expr = {b2: b1, b1: b2} expr2 = Dict({b2: b1, b1: b2}) assert pretty(expr) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}" assert pretty( expr2) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}" assert upretty( expr) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}" assert upretty( expr2) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}" def test_print_builtin_set(): assert pretty(set()) == 'set()' assert upretty(set()) == 'set()' assert pretty(frozenset()) == 'frozenset()' assert upretty(frozenset()) == 'frozenset()' s1 = {1/x, x} s2 = frozenset(s1) assert pretty(s1) == \ """\ 1 \n\ {-, x} x \ """ assert upretty(s1) == \ """\ ⎧1 ⎫ ⎨─, x⎬ ⎩x ⎭\ """ assert pretty(s2) == \ """\ 1 \n\ frozenset({-, x}) x \ """ assert upretty(s2) == \ """\ ⎛⎧1 ⎫⎞ frozenset⎜⎨─, x⎬⎟ ⎝⎩x ⎭⎠\ """ def test_pretty_sets(): s = FiniteSet assert pretty(s(*[x*y, x**2])) == \ """\ 2 \n\ {x , x*y}\ """ assert pretty(s(*range(1, 6))) == "{1, 2, 3, 4, 5}" assert pretty(s(*range(1, 13))) == "{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}" assert pretty({x*y, x**2}) == \ """\ 2 \n\ {x , x*y}\ """ assert pretty(set(range(1, 6))) == "{1, 2, 3, 4, 5}" assert pretty(set(range(1, 13))) == \ "{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}" assert pretty(frozenset([x*y, x**2])) == \ """\ 2 \n\ frozenset({x , x*y})\ """ assert pretty(frozenset(range(1, 6))) == "frozenset({1, 2, 3, 4, 5})" assert pretty(frozenset(range(1, 13))) == \ "frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12})" assert pretty(Range(0, 3, 1)) == '{0, 1, 2}' ascii_str = '{0, 1, ..., 29}' ucode_str = '{0, 1, …, 29}' assert pretty(Range(0, 30, 1)) == ascii_str assert upretty(Range(0, 30, 1)) == ucode_str ascii_str = '{30, 29, ..., 2}' ucode_str = '{30, 29, …, 2}' assert pretty(Range(30, 1, -1)) == ascii_str assert upretty(Range(30, 1, -1)) == ucode_str ascii_str = '{0, 2, ...}' ucode_str = '{0, 2, …}' assert pretty(Range(0, oo, 2)) == ascii_str assert upretty(Range(0, oo, 2)) == ucode_str ascii_str = '{..., 2, 0}' ucode_str = '{…, 2, 0}' assert pretty(Range(oo, -2, -2)) == ascii_str assert upretty(Range(oo, -2, -2)) == ucode_str ascii_str = '{-2, -3, ...}' ucode_str = '{-2, -3, …}' assert pretty(Range(-2, -oo, -1)) == ascii_str assert upretty(Range(-2, -oo, -1)) == ucode_str def test_pretty_SetExpr(): iv = Interval(1, 3) se = SetExpr(iv) ascii_str = "SetExpr([1, 3])" ucode_str = "SetExpr([1, 3])" assert pretty(se) == ascii_str assert upretty(se) == ucode_str def test_pretty_ImageSet(): imgset = ImageSet(Lambda((x, y), x + y), {1, 2, 3}, {3, 4}) ascii_str = '{x + y | x in {1, 2, 3}, y in {3, 4}}' ucode_str = '{x + y │ x ∊ {1, 2, 3}, y ∊ {3, 4}}' assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str imgset = ImageSet(Lambda(((x, y),), x + y), ProductSet({1, 2, 3}, {3, 4})) ascii_str = '{x + y | (x, y) in {1, 2, 3} x {3, 4}}' ucode_str = '{x + y │ (x, y) ∊ {1, 2, 3} × {3, 4}}' assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str imgset = ImageSet(Lambda(x, x**2), S.Naturals) ascii_str = '''\ 2 \n\ {x | x in Naturals}''' ucode_str = '''\ ⎧ 2 │ ⎫\n\ ⎨x │ x ∊ ℕ⎬\n\ ⎩ │ ⎭''' assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str # TODO: The "x in N" parts below should be centered independently of the # 1/x**2 fraction imgset = ImageSet(Lambda(x, 1/x**2), S.Naturals) ascii_str = '''\ 1 \n\ {-- | x in Naturals} 2 \n\ x ''' ucode_str = '''\ ⎧1 │ ⎫\n\ ⎪── │ x ∊ ℕ⎪\n\ ⎨ 2 │ ⎬\n\ ⎪x │ ⎪\n\ ⎩ │ ⎭''' assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str imgset = ImageSet(Lambda((x, y), 1/(x + y)**2), S.Naturals, S.Naturals) ascii_str = '''\ 1 \n\ {-------- | x in Naturals, y in Naturals} 2 \n\ (x + y) ''' ucode_str = '''\ ⎧ 1 │ ⎫ ⎪──────── │ x ∊ ℕ, y ∊ ℕ⎪ ⎨ 2 │ ⎬ ⎪(x + y) │ ⎪ ⎩ │ ⎭''' assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str def test_pretty_ConditionSet(): from sympy import ConditionSet ascii_str = '{x | x in (-oo, oo) and sin(x) = 0}' ucode_str = '{x │ x ∊ ℝ ∧ (sin(x) = 0)}' assert pretty(ConditionSet(x, Eq(sin(x), 0), S.Reals)) == ascii_str assert upretty(ConditionSet(x, Eq(sin(x), 0), S.Reals)) == ucode_str assert pretty(ConditionSet(x, Contains(x, S.Reals, evaluate=False), FiniteSet(1))) == '{1}' assert upretty(ConditionSet(x, Contains(x, S.Reals, evaluate=False), FiniteSet(1))) == '{1}' assert pretty(ConditionSet(x, And(x > 1, x < -1), FiniteSet(1, 2, 3))) == "EmptySet" assert upretty(ConditionSet(x, And(x > 1, x < -1), FiniteSet(1, 2, 3))) == "∅" assert pretty(ConditionSet(x, Or(x > 1, x < -1), FiniteSet(1, 2))) == '{2}' assert upretty(ConditionSet(x, Or(x > 1, x < -1), FiniteSet(1, 2))) == '{2}' condset = ConditionSet(x, 1/x**2 > 0) ascii_str = '''\ 1 \n\ {x | -- > 0} 2 \n\ x ''' ucode_str = '''\ ⎧ │ ⎛1 ⎞⎫ ⎪x │ ⎜── > 0⎟⎪ ⎨ │ ⎜ 2 ⎟⎬ ⎪ │ ⎝x ⎠⎪ ⎩ │ ⎭''' assert pretty(condset) == ascii_str assert upretty(condset) == ucode_str condset = ConditionSet(x, 1/x**2 > 0, S.Reals) ascii_str = '''\ 1 \n\ {x | x in (-oo, oo) and -- > 0} 2 \n\ x ''' ucode_str = '''\ ⎧ │ ⎛1 ⎞⎫ ⎪x │ x ∊ ℝ ∧ ⎜── > 0⎟⎪ ⎨ │ ⎜ 2 ⎟⎬ ⎪ │ ⎝x ⎠⎪ ⎩ │ ⎭''' assert pretty(condset) == ascii_str assert upretty(condset) == ucode_str def test_pretty_ComplexRegion(): from sympy import ComplexRegion cregion = ComplexRegion(Interval(3, 5)*Interval(4, 6)) ascii_str = '{x + y*I | x, y in [3, 5] x [4, 6]}' ucode_str = '{x + y⋅ⅈ │ x, y ∊ [3, 5] × [4, 6]}' assert pretty(cregion) == ascii_str assert upretty(cregion) == ucode_str cregion = ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True) ascii_str = '{r*(I*sin(theta) + cos(theta)) | r, theta in [0, 1] x [0, 2*pi)}' ucode_str = '{r⋅(ⅈ⋅sin(θ) + cos(θ)) │ r, θ ∊ [0, 1] × [0, 2⋅π)}' assert pretty(cregion) == ascii_str assert upretty(cregion) == ucode_str cregion = ComplexRegion(Interval(3, 1/a**2)*Interval(4, 6)) ascii_str = '''\ 1 \n\ {x + y*I | x, y in [3, --] x [4, 6]} 2 \n\ a ''' ucode_str = '''\ ⎧ │ ⎡ 1 ⎤ ⎫ ⎪x + y⋅ⅈ │ x, y ∊ ⎢3, ──⎥ × [4, 6]⎪ ⎨ │ ⎢ 2⎥ ⎬ ⎪ │ ⎣ a ⎦ ⎪ ⎩ │ ⎭''' assert pretty(cregion) == ascii_str assert upretty(cregion) == ucode_str cregion = ComplexRegion(Interval(0, 1/a**2)*Interval(0, 2*pi), polar=True) ascii_str = '''\ 1 \n\ {r*(I*sin(theta) + cos(theta)) | r, theta in [0, --] x [0, 2*pi)} 2 \n\ a ''' ucode_str = '''\ ⎧ │ ⎡ 1 ⎤ ⎫ ⎪r⋅(ⅈ⋅sin(θ) + cos(θ)) │ r, θ ∊ ⎢0, ──⎥ × [0, 2⋅π)⎪ ⎨ │ ⎢ 2⎥ ⎬ ⎪ │ ⎣ a ⎦ ⎪ ⎩ │ ⎭''' assert pretty(cregion) == ascii_str assert upretty(cregion) == ucode_str def test_pretty_Union_issue_10414(): a, b = Interval(2, 3), Interval(4, 7) ucode_str = '[2, 3] ∪ [4, 7]' ascii_str = '[2, 3] U [4, 7]' assert upretty(Union(a, b)) == ucode_str assert pretty(Union(a, b)) == ascii_str def test_pretty_Intersection_issue_10414(): x, y, z, w = symbols('x, y, z, w') a, b = Interval(x, y), Interval(z, w) ucode_str = '[x, y] ∩ [z, w]' ascii_str = '[x, y] n [z, w]' assert upretty(Intersection(a, b)) == ucode_str assert pretty(Intersection(a, b)) == ascii_str def test_ProductSet_exponent(): ucode_str = ' 1\n[0, 1] ' assert upretty(Interval(0, 1)**1) == ucode_str ucode_str = ' 2\n[0, 1] ' assert upretty(Interval(0, 1)**2) == ucode_str def test_ProductSet_parenthesis(): ucode_str = '([4, 7] × {1, 2}) ∪ ([2, 3] × [4, 7])' a, b = Interval(2, 3), Interval(4, 7) assert upretty(Union(a*b, b*FiniteSet(1, 2))) == ucode_str def test_ProductSet_prod_char_issue_10413(): ascii_str = '[2, 3] x [4, 7]' ucode_str = '[2, 3] × [4, 7]' a, b = Interval(2, 3), Interval(4, 7) assert pretty(a*b) == ascii_str assert upretty(a*b) == ucode_str def test_pretty_sequences(): s1 = SeqFormula(a**2, (0, oo)) s2 = SeqPer((1, 2)) ascii_str = '[0, 1, 4, 9, ...]' ucode_str = '[0, 1, 4, 9, …]' assert pretty(s1) == ascii_str assert upretty(s1) == ucode_str ascii_str = '[1, 2, 1, 2, ...]' ucode_str = '[1, 2, 1, 2, …]' assert pretty(s2) == ascii_str assert upretty(s2) == ucode_str s3 = SeqFormula(a**2, (0, 2)) s4 = SeqPer((1, 2), (0, 2)) ascii_str = '[0, 1, 4]' ucode_str = '[0, 1, 4]' assert pretty(s3) == ascii_str assert upretty(s3) == ucode_str ascii_str = '[1, 2, 1]' ucode_str = '[1, 2, 1]' assert pretty(s4) == ascii_str assert upretty(s4) == ucode_str s5 = SeqFormula(a**2, (-oo, 0)) s6 = SeqPer((1, 2), (-oo, 0)) ascii_str = '[..., 9, 4, 1, 0]' ucode_str = '[…, 9, 4, 1, 0]' assert pretty(s5) == ascii_str assert upretty(s5) == ucode_str ascii_str = '[..., 2, 1, 2, 1]' ucode_str = '[…, 2, 1, 2, 1]' assert pretty(s6) == ascii_str assert upretty(s6) == ucode_str ascii_str = '[1, 3, 5, 11, ...]' ucode_str = '[1, 3, 5, 11, …]' assert pretty(SeqAdd(s1, s2)) == ascii_str assert upretty(SeqAdd(s1, s2)) == ucode_str ascii_str = '[1, 3, 5]' ucode_str = '[1, 3, 5]' assert pretty(SeqAdd(s3, s4)) == ascii_str assert upretty(SeqAdd(s3, s4)) == ucode_str ascii_str = '[..., 11, 5, 3, 1]' ucode_str = '[…, 11, 5, 3, 1]' assert pretty(SeqAdd(s5, s6)) == ascii_str assert upretty(SeqAdd(s5, s6)) == ucode_str ascii_str = '[0, 2, 4, 18, ...]' ucode_str = '[0, 2, 4, 18, …]' assert pretty(SeqMul(s1, s2)) == ascii_str assert upretty(SeqMul(s1, s2)) == ucode_str ascii_str = '[0, 2, 4]' ucode_str = '[0, 2, 4]' assert pretty(SeqMul(s3, s4)) == ascii_str assert upretty(SeqMul(s3, s4)) == ucode_str ascii_str = '[..., 18, 4, 2, 0]' ucode_str = '[…, 18, 4, 2, 0]' assert pretty(SeqMul(s5, s6)) == ascii_str assert upretty(SeqMul(s5, s6)) == ucode_str # Sequences with symbolic limits, issue 12629 s7 = SeqFormula(a**2, (a, 0, x)) raises(NotImplementedError, lambda: pretty(s7)) raises(NotImplementedError, lambda: upretty(s7)) b = Symbol('b') s8 = SeqFormula(b*a**2, (a, 0, 2)) ascii_str = '[0, b, 4*b]' ucode_str = '[0, b, 4⋅b]' assert pretty(s8) == ascii_str assert upretty(s8) == ucode_str def test_pretty_FourierSeries(): f = fourier_series(x, (x, -pi, pi)) ascii_str = \ """\ 2*sin(3*x) \n\ 2*sin(x) - sin(2*x) + ---------- + ...\n\ 3 \ """ ucode_str = \ """\ 2⋅sin(3⋅x) \n\ 2⋅sin(x) - sin(2⋅x) + ────────── + …\n\ 3 \ """ assert pretty(f) == ascii_str assert upretty(f) == ucode_str def test_pretty_FormalPowerSeries(): f = fps(log(1 + x)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ -k k \n\ \\ -(-1) *x \n\ / -----------\n\ / k \n\ /___, \n\ k = 1 \ """ ucode_str = \ """\ ∞ \n\ ____ \n\ ╲ \n\ ╲ -k k \n\ ╲ -(-1) ⋅x \n\ ╱ ───────────\n\ ╱ k \n\ ╱ \n\ ‾‾‾‾ \n\ k = 1 \ """ assert pretty(f) == ascii_str assert upretty(f) == ucode_str def test_pretty_limits(): expr = Limit(x, x, oo) ascii_str = \ """\ lim x\n\ x->oo \ """ ucode_str = \ """\ lim x\n\ x─→∞ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(x**2, x, 0) ascii_str = \ """\ 2\n\ lim x \n\ x->0+ \ """ ucode_str = \ """\ 2\n\ lim x \n\ x─→0⁺ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(1/x, x, 0) ascii_str = \ """\ 1\n\ lim -\n\ x->0+x\ """ ucode_str = \ """\ 1\n\ lim ─\n\ x─→0⁺x\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(sin(x)/x, x, 0) ascii_str = \ """\ /sin(x)\\\n\ lim |------|\n\ x->0+\\ x /\ """ ucode_str = \ """\ ⎛sin(x)⎞\n\ lim ⎜──────⎟\n\ x─→0⁺⎝ x ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(sin(x)/x, x, 0, "-") ascii_str = \ """\ /sin(x)\\\n\ lim |------|\n\ x->0-\\ x /\ """ ucode_str = \ """\ ⎛sin(x)⎞\n\ lim ⎜──────⎟\n\ x─→0⁻⎝ x ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(x + sin(x), x, 0) ascii_str = \ """\ lim (x + sin(x))\n\ x->0+ \ """ ucode_str = \ """\ lim (x + sin(x))\n\ x─→0⁺ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(x, x, 0)**2 ascii_str = \ """\ 2\n\ / lim x\\ \n\ \\x->0+ / \ """ ucode_str = \ """\ 2\n\ ⎛ lim x⎞ \n\ ⎝x─→0⁺ ⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(x*Limit(y/2,y,0), x, 0) ascii_str = \ """\ / /y\\\\\n\ lim |x* lim |-||\n\ x->0+\\ y->0+\\2//\ """ ucode_str = \ """\ ⎛ ⎛y⎞⎞\n\ lim ⎜x⋅ lim ⎜─⎟⎟\n\ x─→0⁺⎝ y─→0⁺⎝2⎠⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2*Limit(x*Limit(y/2,y,0), x, 0) ascii_str = \ """\ / /y\\\\\n\ 2* lim |x* lim |-||\n\ x->0+\\ y->0+\\2//\ """ ucode_str = \ """\ ⎛ ⎛y⎞⎞\n\ 2⋅ lim ⎜x⋅ lim ⎜─⎟⎟\n\ x─→0⁺⎝ y─→0⁺⎝2⎠⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(sin(x), x, 0, dir='+-') ascii_str = \ """\ lim sin(x)\n\ x->0 \ """ ucode_str = \ """\ lim sin(x)\n\ x─→0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_ComplexRootOf(): expr = rootof(x**5 + 11*x - 2, 0) ascii_str = \ """\ / 5 \\\n\ CRootOf\\x + 11*x - 2, 0/\ """ ucode_str = \ """\ ⎛ 5 ⎞\n\ CRootOf⎝x + 11⋅x - 2, 0⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_RootSum(): expr = RootSum(x**5 + 11*x - 2, auto=False) ascii_str = \ """\ / 5 \\\n\ RootSum\\x + 11*x - 2/\ """ ucode_str = \ """\ ⎛ 5 ⎞\n\ RootSum⎝x + 11⋅x - 2⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = RootSum(x**5 + 11*x - 2, Lambda(z, exp(z))) ascii_str = \ """\ / 5 z\\\n\ RootSum\\x + 11*x - 2, z -> e /\ """ ucode_str = \ """\ ⎛ 5 z⎞\n\ RootSum⎝x + 11⋅x - 2, z ↦ ℯ ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_GroebnerBasis(): expr = groebner([], x, y) ascii_str = \ """\ GroebnerBasis([], x, y, domain=ZZ, order=lex)\ """ ucode_str = \ """\ GroebnerBasis([], x, y, domain=ℤ, order=lex)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1] expr = groebner(F, x, y, order='grlex') ascii_str = \ """\ /[ 2 2 ] \\\n\ GroebnerBasis\\[x - x - 3*y + 1, y - 2*x + y - 1], x, y, domain=ZZ, order=grlex/\ """ ucode_str = \ """\ ⎛⎡ 2 2 ⎤ ⎞\n\ GroebnerBasis⎝⎣x - x - 3⋅y + 1, y - 2⋅x + y - 1⎦, x, y, domain=ℤ, order=grlex⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = expr.fglm('lex') ascii_str = \ """\ /[ 2 4 3 2 ] \\\n\ GroebnerBasis\\[2*x - y - y + 1, y + 2*y - 3*y - 16*y + 7], x, y, domain=ZZ, order=lex/\ """ ucode_str = \ """\ ⎛⎡ 2 4 3 2 ⎤ ⎞\n\ GroebnerBasis⎝⎣2⋅x - y - y + 1, y + 2⋅y - 3⋅y - 16⋅y + 7⎦, x, y, domain=ℤ, order=lex⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_UniversalSet(): assert pretty(S.UniversalSet) == "UniversalSet" assert upretty(S.UniversalSet) == '𝕌' def test_pretty_Boolean(): expr = Not(x, evaluate=False) assert pretty(expr) == "Not(x)" assert upretty(expr) == "¬x" expr = And(x, y) assert pretty(expr) == "And(x, y)" assert upretty(expr) == "x ∧ y" expr = Or(x, y) assert pretty(expr) == "Or(x, y)" assert upretty(expr) == "x ∨ y" syms = symbols('a:f') expr = And(*syms) assert pretty(expr) == "And(a, b, c, d, e, f)" assert upretty(expr) == "a ∧ b ∧ c ∧ d ∧ e ∧ f" expr = Or(*syms) assert pretty(expr) == "Or(a, b, c, d, e, f)" assert upretty(expr) == "a ∨ b ∨ c ∨ d ∨ e ∨ f" expr = Xor(x, y, evaluate=False) assert pretty(expr) == "Xor(x, y)" assert upretty(expr) == "x ⊻ y" expr = Nand(x, y, evaluate=False) assert pretty(expr) == "Nand(x, y)" assert upretty(expr) == "x ⊼ y" expr = Nor(x, y, evaluate=False) assert pretty(expr) == "Nor(x, y)" assert upretty(expr) == "x ⊽ y" expr = Implies(x, y, evaluate=False) assert pretty(expr) == "Implies(x, y)" assert upretty(expr) == "x → y" # don't sort args expr = Implies(y, x, evaluate=False) assert pretty(expr) == "Implies(y, x)" assert upretty(expr) == "y → x" expr = Equivalent(x, y, evaluate=False) assert pretty(expr) == "Equivalent(x, y)" assert upretty(expr) == "x ⇔ y" expr = Equivalent(y, x, evaluate=False) assert pretty(expr) == "Equivalent(x, y)" assert upretty(expr) == "x ⇔ y" def test_pretty_Domain(): expr = FF(23) assert pretty(expr) == "GF(23)" assert upretty(expr) == "ℤ₂₃" expr = ZZ assert pretty(expr) == "ZZ" assert upretty(expr) == "ℤ" expr = QQ assert pretty(expr) == "QQ" assert upretty(expr) == "ℚ" expr = RR assert pretty(expr) == "RR" assert upretty(expr) == "ℝ" expr = QQ[x] assert pretty(expr) == "QQ[x]" assert upretty(expr) == "ℚ[x]" expr = QQ[x, y] assert pretty(expr) == "QQ[x, y]" assert upretty(expr) == "ℚ[x, y]" expr = ZZ.frac_field(x) assert pretty(expr) == "ZZ(x)" assert upretty(expr) == "ℤ(x)" expr = ZZ.frac_field(x, y) assert pretty(expr) == "ZZ(x, y)" assert upretty(expr) == "ℤ(x, y)" expr = QQ.poly_ring(x, y, order=grlex) assert pretty(expr) == "QQ[x, y, order=grlex]" assert upretty(expr) == "ℚ[x, y, order=grlex]" expr = QQ.poly_ring(x, y, order=ilex) assert pretty(expr) == "QQ[x, y, order=ilex]" assert upretty(expr) == "ℚ[x, y, order=ilex]" def test_pretty_prec(): assert xpretty(S("0.3"), full_prec=True, wrap_line=False) == "0.300000000000000" assert xpretty(S("0.3"), full_prec="auto", wrap_line=False) == "0.300000000000000" assert xpretty(S("0.3"), full_prec=False, wrap_line=False) == "0.3" assert xpretty(S("0.3")*x, full_prec=True, use_unicode=False, wrap_line=False) in [ "0.300000000000000*x", "x*0.300000000000000" ] assert xpretty(S("0.3")*x, full_prec="auto", use_unicode=False, wrap_line=False) in [ "0.3*x", "x*0.3" ] assert xpretty(S("0.3")*x, full_prec=False, use_unicode=False, wrap_line=False) in [ "0.3*x", "x*0.3" ] def test_pprint(): import sys from io import StringIO fd = StringIO() sso = sys.stdout sys.stdout = fd try: pprint(pi, use_unicode=False, wrap_line=False) finally: sys.stdout = sso assert fd.getvalue() == 'pi\n' def test_pretty_class(): """Test that the printer dispatcher correctly handles classes.""" class C: pass # C has no .__class__ and this was causing problems class D: pass assert pretty( C ) == str( C ) assert pretty( D ) == str( D ) def test_pretty_no_wrap_line(): huge_expr = 0 for i in range(20): huge_expr += i*sin(i + x) assert xpretty(huge_expr ).find('\n') != -1 assert xpretty(huge_expr, wrap_line=False).find('\n') == -1 def test_settings(): raises(TypeError, lambda: pretty(S(4), method="garbage")) def test_pretty_sum(): from sympy.abc import x, a, b, k, m, n expr = Sum(k**k, (k, 0, n)) ascii_str = \ """\ n \n\ ___ \n\ \\ ` \n\ \\ k\n\ / k \n\ /__, \n\ k = 0 \ """ ucode_str = \ """\ n \n\ ___ \n\ ╲ \n\ ╲ k\n\ ╱ k \n\ ╱ \n\ ‾‾‾ \n\ k = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**k, (k, oo, n)) ascii_str = \ """\ n \n\ ___ \n\ \\ ` \n\ \\ k\n\ / k \n\ /__, \n\ k = oo \ """ ucode_str = \ """\ n \n\ ___ \n\ ╲ \n\ ╲ k\n\ ╱ k \n\ ╱ \n\ ‾‾‾ \n\ k = ∞ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**(Integral(x**n, (x, -oo, oo))), (k, 0, n**n)) ascii_str = \ """\ n \n\ n \n\ ______ \n\ \\ ` \n\ \\ oo \n\ \\ / \n\ \\ | \n\ \\ | n \n\ ) | x dx\n\ / | \n\ / / \n\ / -oo \n\ / k \n\ /_____, \n\ k = 0 \ """ ucode_str = \ """\ n \n\ n \n\ ______ \n\ ╲ \n\ ╲ \n\ ╲ ∞ \n\ ╲ ⌠ \n\ ╲ ⎮ n \n\ ╱ ⎮ x dx\n\ ╱ ⌡ \n\ ╱ -∞ \n\ ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ k = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**( Integral(x**n, (x, -oo, oo))), (k, 0, Integral(x**x, (x, -oo, oo)))) ascii_str = \ """\ oo \n\ / \n\ | \n\ | x \n\ | x dx \n\ | \n\ / \n\ -oo \n\ ______ \n\ \\ ` \n\ \\ oo \n\ \\ / \n\ \\ | \n\ \\ | n \n\ ) | x dx\n\ / | \n\ / / \n\ / -oo \n\ / k \n\ /_____, \n\ k = 0 \ """ ucode_str = \ """\ ∞ \n\ ⌠ \n\ ⎮ x \n\ ⎮ x dx \n\ ⌡ \n\ -∞ \n\ ______ \n\ ╲ \n\ ╲ \n\ ╲ ∞ \n\ ╲ ⌠ \n\ ╲ ⎮ n \n\ ╱ ⎮ x dx\n\ ╱ ⌡ \n\ ╱ -∞ \n\ ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ k = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**(Integral(x**n, (x, -oo, oo))), ( k, x + n + x**2 + n**2 + (x/n) + (1/x), Integral(x**x, (x, -oo, oo)))) ascii_str = \ """\ oo \n\ / \n\ | \n\ | x \n\ | x dx \n\ | \n\ / \n\ -oo \n\ ______ \n\ \\ ` \n\ \\ oo \n\ \\ / \n\ \\ | \n\ \\ | n \n\ ) | x dx\n\ / | \n\ / / \n\ / -oo \n\ / k \n\ /_____, \n\ 2 2 1 x \n\ k = n + n + x + x + - + - \n\ x n \ """ ucode_str = \ """\ ∞ \n\ ⌠ \n\ ⎮ x \n\ ⎮ x dx \n\ ⌡ \n\ -∞ \n\ ______ \n\ ╲ \n\ ╲ \n\ ╲ ∞ \n\ ╲ ⌠ \n\ ╲ ⎮ n \n\ ╱ ⎮ x dx\n\ ╱ ⌡ \n\ ╱ -∞ \n\ ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ 2 2 1 x \n\ k = n + n + x + x + ─ + ─ \n\ x n \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**( Integral(x**n, (x, -oo, oo))), (k, 0, x + n + x**2 + n**2 + (x/n) + (1/x))) ascii_str = \ """\ 2 2 1 x \n\ n + n + x + x + - + - \n\ x n \n\ ______ \n\ \\ ` \n\ \\ oo \n\ \\ / \n\ \\ | \n\ \\ | n \n\ ) | x dx\n\ / | \n\ / / \n\ / -oo \n\ / k \n\ /_____, \n\ k = 0 \ """ ucode_str = \ """\ 2 2 1 x \n\ n + n + x + x + ─ + ─ \n\ x n \n\ ______ \n\ ╲ \n\ ╲ \n\ ╲ ∞ \n\ ╲ ⌠ \n\ ╲ ⎮ n \n\ ╱ ⎮ x dx\n\ ╱ ⌡ \n\ ╱ -∞ \n\ ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ k = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(x, (x, 0, oo)) ascii_str = \ """\ oo \n\ __ \n\ \\ ` \n\ ) x\n\ /_, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ___ \n\ ╲ \n\ ╲ \n\ ╱ x\n\ ╱ \n\ ‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(x**2, (x, 0, oo)) ascii_str = \ """\ oo \n\ ___ \n\ \\ ` \n\ \\ 2\n\ / x \n\ /__, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ___ \n\ ╲ \n\ ╲ 2\n\ ╱ x \n\ ╱ \n\ ‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(x/2, (x, 0, oo)) ascii_str = \ """\ oo \n\ ___ \n\ \\ ` \n\ \\ x\n\ ) -\n\ / 2\n\ /__, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ____ \n\ ╲ \n\ ╲ \n\ ╲ x\n\ ╱ ─\n\ ╱ 2\n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(x**3/2, (x, 0, oo)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ 3\n\ \\ x \n\ / --\n\ / 2 \n\ /___, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ____ \n\ ╲ \n\ ╲ 3\n\ ╲ x \n\ ╱ ──\n\ ╱ 2 \n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum((x**3*y**(x/2))**n, (x, 0, oo)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ n\n\ \\ / x\\ \n\ ) | -| \n\ / | 3 2| \n\ / \\x *y / \n\ /___, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ _____ \n\ ╲ \n\ ╲ \n\ ╲ n\n\ ╲ ⎛ x⎞ \n\ ╱ ⎜ ─⎟ \n\ ╱ ⎜ 3 2⎟ \n\ ╱ ⎝x ⋅y ⎠ \n\ ╱ \n\ ‾‾‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(1/x**2, (x, 0, oo)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ 1 \n\ \\ --\n\ / 2\n\ / x \n\ /___, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ____ \n\ ╲ \n\ ╲ 1 \n\ ╲ ──\n\ ╱ 2\n\ ╱ x \n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(1/y**(a/b), (x, 0, oo)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ -a \n\ \\ ---\n\ / b \n\ / y \n\ /___, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ____ \n\ ╲ \n\ ╲ -a \n\ ╲ ───\n\ ╱ b \n\ ╱ y \n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(1/y**(a/b), (x, 0, oo), (y, 1, 2)) ascii_str = \ """\ 2 oo \n\ ____ ____ \n\ \\ ` \\ ` \n\ \\ \\ -a\n\ \\ \\ --\n\ / / b \n\ / / y \n\ /___, /___, \n\ y = 1 x = 0 \ """ ucode_str = \ """\ 2 ∞ \n\ ____ ____ \n\ ╲ ╲ \n\ ╲ ╲ -a\n\ ╲ ╲ ──\n\ ╱ ╱ b \n\ ╱ ╱ y \n\ ╱ ╱ \n\ ‾‾‾‾ ‾‾‾‾ \n\ y = 1 x = 0 \ """ expr = Sum(1/(1 + 1/( 1 + 1/k)) + 1, (k, 111, 1 + 1/n), (k, 1/(1 + m), oo)) + 1/(1 + 1/k) ascii_str = \ """\ 1 \n\ 1 + - \n\ oo n \n\ _____ _____ \n\ \\ ` \\ ` \n\ \\ \\ / 1 \\ \n\ \\ \\ |1 + ---------| \n\ \\ \\ | 1 | 1 \n\ ) ) | 1 + -----| + -----\n\ / / | 1| 1\n\ / / | 1 + -| 1 + -\n\ / / \\ k/ k\n\ /____, /____, \n\ 1 k = 111 \n\ k = ----- \n\ m + 1 \ """ ucode_str = \ """\ 1 \n\ 1 + ─ \n\ ∞ n \n\ ______ ______ \n\ ╲ ╲ \n\ ╲ ╲ \n\ ╲ ╲ ⎛ 1 ⎞ \n\ ╲ ╲ ⎜1 + ─────────⎟ \n\ ╲ ╲ ⎜ 1 ⎟ 1 \n\ ╱ ╱ ⎜ 1 + ─────⎟ + ─────\n\ ╱ ╱ ⎜ 1⎟ 1\n\ ╱ ╱ ⎜ 1 + ─⎟ 1 + ─\n\ ╱ ╱ ⎝ k⎠ k\n\ ╱ ╱ \n\ ‾‾‾‾‾‾ ‾‾‾‾‾‾ \n\ 1 k = 111 \n\ k = ───── \n\ m + 1 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_units(): expr = joule ascii_str1 = \ """\ 2\n\ kilogram*meter \n\ ---------------\n\ 2 \n\ second \ """ unicode_str1 = \ """\ 2\n\ kilogram⋅meter \n\ ───────────────\n\ 2 \n\ second \ """ ascii_str2 = \ """\ 2\n\ 3*x*y*kilogram*meter \n\ ---------------------\n\ 2 \n\ second \ """ unicode_str2 = \ """\ 2\n\ 3⋅x⋅y⋅kilogram⋅meter \n\ ─────────────────────\n\ 2 \n\ second \ """ from sympy.physics.units import kg, m, s assert upretty(expr) == "joule" assert pretty(expr) == "joule" assert upretty(expr.convert_to(kg*m**2/s**2)) == unicode_str1 assert pretty(expr.convert_to(kg*m**2/s**2)) == ascii_str1 assert upretty(3*kg*x*m**2*y/s**2) == unicode_str2 assert pretty(3*kg*x*m**2*y/s**2) == ascii_str2 def test_pretty_Subs(): f = Function('f') expr = Subs(f(x), x, ph**2) ascii_str = \ """\ (f(x))| 2\n\ |x=phi \ """ unicode_str = \ """\ (f(x))│ 2\n\ │x=φ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Subs(f(x).diff(x), x, 0) ascii_str = \ """\ /d \\| \n\ |--(f(x))|| \n\ \\dx /|x=0\ """ unicode_str = \ """\ ⎛d ⎞│ \n\ ⎜──(f(x))⎟│ \n\ ⎝dx ⎠│x=0\ """ assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Subs(f(x).diff(x)/y, (x, y), (0, Rational(1, 2))) ascii_str = \ """\ /d \\| \n\ |--(f(x))|| \n\ |dx || \n\ |--------|| \n\ \\ y /|x=0, y=1/2\ """ unicode_str = \ """\ ⎛d ⎞│ \n\ ⎜──(f(x))⎟│ \n\ ⎜dx ⎟│ \n\ ⎜────────⎟│ \n\ ⎝ y ⎠│x=0, y=1/2\ """ assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str def test_gammas(): assert upretty(lowergamma(x, y)) == "γ(x, y)" assert upretty(uppergamma(x, y)) == "Γ(x, y)" assert xpretty(gamma(x), use_unicode=True) == 'Γ(x)' assert xpretty(gamma, use_unicode=True) == 'Γ' assert xpretty(symbols('gamma', cls=Function)(x), use_unicode=True) == 'γ(x)' assert xpretty(symbols('gamma', cls=Function), use_unicode=True) == 'γ' def test_beta(): assert xpretty(beta(x,y), use_unicode=True) == 'Β(x, y)' assert xpretty(beta(x,y), use_unicode=False) == 'B(x, y)' assert xpretty(beta, use_unicode=True) == 'Β' assert xpretty(beta, use_unicode=False) == 'B' mybeta = Function('beta') assert xpretty(mybeta(x), use_unicode=True) == 'β(x)' assert xpretty(mybeta(x, y, z), use_unicode=False) == 'beta(x, y, z)' assert xpretty(mybeta, use_unicode=True) == 'β' # test that notation passes to subclasses of the same name only def test_function_subclass_different_name(): class mygamma(gamma): pass assert xpretty(mygamma, use_unicode=True) == r"mygamma" assert xpretty(mygamma(x), use_unicode=True) == r"mygamma(x)" def test_SingularityFunction(): assert xpretty(SingularityFunction(x, 0, n), use_unicode=True) == ( """\ n\n\ <x> \ """) assert xpretty(SingularityFunction(x, 1, n), use_unicode=True) == ( """\ n\n\ <x - 1> \ """) assert xpretty(SingularityFunction(x, -1, n), use_unicode=True) == ( """\ n\n\ <x + 1> \ """) assert xpretty(SingularityFunction(x, a, n), use_unicode=True) == ( """\ n\n\ <-a + x> \ """) assert xpretty(SingularityFunction(x, y, n), use_unicode=True) == ( """\ n\n\ <x - y> \ """) assert xpretty(SingularityFunction(x, 0, n), use_unicode=False) == ( """\ n\n\ <x> \ """) assert xpretty(SingularityFunction(x, 1, n), use_unicode=False) == ( """\ n\n\ <x - 1> \ """) assert xpretty(SingularityFunction(x, -1, n), use_unicode=False) == ( """\ n\n\ <x + 1> \ """) assert xpretty(SingularityFunction(x, a, n), use_unicode=False) == ( """\ n\n\ <-a + x> \ """) assert xpretty(SingularityFunction(x, y, n), use_unicode=False) == ( """\ n\n\ <x - y> \ """) def test_deltas(): assert xpretty(DiracDelta(x), use_unicode=True) == 'δ(x)' assert xpretty(DiracDelta(x, 1), use_unicode=True) == \ """\ (1) \n\ δ (x)\ """ assert xpretty(x*DiracDelta(x, 1), use_unicode=True) == \ """\ (1) \n\ x⋅δ (x)\ """ def test_hyper(): expr = hyper((), (), z) ucode_str = \ """\ ┌─ ⎛ │ ⎞\n\ ├─ ⎜ │ z⎟\n\ 0╵ 0 ⎝ │ ⎠\ """ ascii_str = \ """\ _ \n\ |_ / | \\\n\ | | | z|\n\ 0 0 \\ | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper((), (1,), x) ucode_str = \ """\ ┌─ ⎛ │ ⎞\n\ ├─ ⎜ │ x⎟\n\ 0╵ 1 ⎝1 │ ⎠\ """ ascii_str = \ """\ _ \n\ |_ / | \\\n\ | | | x|\n\ 0 1 \\1 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper([2], [1], x) ucode_str = \ """\ ┌─ ⎛2 │ ⎞\n\ ├─ ⎜ │ x⎟\n\ 1╵ 1 ⎝1 │ ⎠\ """ ascii_str = \ """\ _ \n\ |_ /2 | \\\n\ | | | x|\n\ 1 1 \\1 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper((pi/3, -2*k), (3, 4, 5, -3), x) ucode_str = \ """\ ⎛ π │ ⎞\n\ ┌─ ⎜ ─, -2⋅k │ ⎟\n\ ├─ ⎜ 3 │ x⎟\n\ 2╵ 4 ⎜ │ ⎟\n\ ⎝3, 4, 5, -3 │ ⎠\ """ ascii_str = \ """\ \n\ _ / pi | \\\n\ |_ | --, -2*k | |\n\ | | 3 | x|\n\ 2 4 | | |\n\ \\3, 4, 5, -3 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper((pi, S('2/3'), -2*k), (3, 4, 5, -3), x**2) ucode_str = \ """\ ┌─ ⎛π, 2/3, -2⋅k │ 2⎞\n\ ├─ ⎜ │ x ⎟\n\ 3╵ 4 ⎝3, 4, 5, -3 │ ⎠\ """ ascii_str = \ """\ _ \n\ |_ /pi, 2/3, -2*k | 2\\\n\ | | | x |\n\ 3 4 \\ 3, 4, 5, -3 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper([1, 2], [3, 4], 1/(1/(1/(1/x + 1) + 1) + 1)) ucode_str = \ """\ ⎛ │ 1 ⎞\n\ ⎜ │ ─────────────⎟\n\ ⎜ │ 1 ⎟\n\ ┌─ ⎜1, 2 │ 1 + ─────────⎟\n\ ├─ ⎜ │ 1 ⎟\n\ 2╵ 2 ⎜3, 4 │ 1 + ─────⎟\n\ ⎜ │ 1⎟\n\ ⎜ │ 1 + ─⎟\n\ ⎝ │ x⎠\ """ ascii_str = \ """\ \n\ / | 1 \\\n\ | | -------------|\n\ _ | | 1 |\n\ |_ |1, 2 | 1 + ---------|\n\ | | | 1 |\n\ 2 2 |3, 4 | 1 + -----|\n\ | | 1|\n\ | | 1 + -|\n\ \\ | x/\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_meijerg(): expr = meijerg([pi, pi, x], [1], [0, 1], [1, 2, 3], z) ucode_str = \ """\ ╭─╮2, 3 ⎛π, π, x 1 │ ⎞\n\ │╶┐ ⎜ │ z⎟\n\ ╰─╯4, 5 ⎝ 0, 1 1, 2, 3 │ ⎠\ """ ascii_str = \ """\ __2, 3 /pi, pi, x 1 | \\\n\ /__ | | z|\n\ \\_|4, 5 \\ 0, 1 1, 2, 3 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = meijerg([1, pi/7], [2, pi, 5], [], [], z**2) ucode_str = \ """\ ⎛ π │ ⎞\n\ ╭─╮0, 2 ⎜1, ─ 2, π, 5 │ 2⎟\n\ │╶┐ ⎜ 7 │ z ⎟\n\ ╰─╯5, 0 ⎜ │ ⎟\n\ ⎝ │ ⎠\ """ ascii_str = \ """\ / pi | \\\n\ __0, 2 |1, -- 2, pi, 5 | 2|\n\ /__ | 7 | z |\n\ \\_|5, 0 | | |\n\ \\ | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ucode_str = \ """\ ╭─╮ 1, 10 ⎛1, 1, 1, 1, 1, 1, 1, 1, 1, 1 1 │ ⎞\n\ │╶┐ ⎜ │ z⎟\n\ ╰─╯11, 2 ⎝ 1 1 │ ⎠\ """ ascii_str = \ """\ __ 1, 10 /1, 1, 1, 1, 1, 1, 1, 1, 1, 1 1 | \\\n\ /__ | | z|\n\ \\_|11, 2 \\ 1 1 | /\ """ expr = meijerg([1]*10, [1], [1], [1], z) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = meijerg([1, 2, ], [4, 3], [3], [4, 5], 1/(1/(1/(1/x + 1) + 1) + 1)) ucode_str = \ """\ ⎛ │ 1 ⎞\n\ ⎜ │ ─────────────⎟\n\ ⎜ │ 1 ⎟\n\ ╭─╮1, 2 ⎜1, 2 4, 3 │ 1 + ─────────⎟\n\ │╶┐ ⎜ │ 1 ⎟\n\ ╰─╯4, 3 ⎜ 3 4, 5 │ 1 + ─────⎟\n\ ⎜ │ 1⎟\n\ ⎜ │ 1 + ─⎟\n\ ⎝ │ x⎠\ """ ascii_str = \ """\ / | 1 \\\n\ | | -------------|\n\ | | 1 |\n\ __1, 2 |1, 2 4, 3 | 1 + ---------|\n\ /__ | | 1 |\n\ \\_|4, 3 | 3 4, 5 | 1 + -----|\n\ | | 1|\n\ | | 1 + -|\n\ \\ | x/\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(expr, x) ucode_str = \ """\ ⌠ \n\ ⎮ ⎛ │ 1 ⎞ \n\ ⎮ ⎜ │ ─────────────⎟ \n\ ⎮ ⎜ │ 1 ⎟ \n\ ⎮ ╭─╮1, 2 ⎜1, 2 4, 3 │ 1 + ─────────⎟ \n\ ⎮ │╶┐ ⎜ │ 1 ⎟ dx\n\ ⎮ ╰─╯4, 3 ⎜ 3 4, 5 │ 1 + ─────⎟ \n\ ⎮ ⎜ │ 1⎟ \n\ ⎮ ⎜ │ 1 + ─⎟ \n\ ⎮ ⎝ │ x⎠ \n\ ⌡ \ """ ascii_str = \ """\ / \n\ | \n\ | / | 1 \\ \n\ | | | -------------| \n\ | | | 1 | \n\ | __1, 2 |1, 2 4, 3 | 1 + ---------| \n\ | /__ | | 1 | dx\n\ | \\_|4, 3 | 3 4, 5 | 1 + -----| \n\ | | | 1| \n\ | | | 1 + -| \n\ | \\ | x/ \n\ | \n\ / \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_noncommutative(): A, B, C = symbols('A,B,C', commutative=False) expr = A*B*C**-1 ascii_str = \ """\ -1\n\ A*B*C \ """ ucode_str = \ """\ -1\n\ A⋅B⋅C \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = C**-1*A*B ascii_str = \ """\ -1 \n\ C *A*B\ """ ucode_str = \ """\ -1 \n\ C ⋅A⋅B\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A*C**-1*B ascii_str = \ """\ -1 \n\ A*C *B\ """ ucode_str = \ """\ -1 \n\ A⋅C ⋅B\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A*C**-1*B/x ascii_str = \ """\ -1 \n\ A*C *B\n\ -------\n\ x \ """ ucode_str = \ """\ -1 \n\ A⋅C ⋅B\n\ ───────\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_special_functions(): x, y = symbols("x y") # atan2 expr = atan2(y/sqrt(200), sqrt(x)) ascii_str = \ """\ / ___ \\\n\ |\\/ 2 *y ___|\n\ atan2|-------, \\/ x |\n\ \\ 20 /\ """ ucode_str = \ """\ ⎛√2⋅y ⎞\n\ atan2⎜────, √x⎟\n\ ⎝ 20 ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_geometry(): e = Segment((0, 1), (0, 2)) assert pretty(e) == 'Segment2D(Point2D(0, 1), Point2D(0, 2))' e = Ray((1, 1), angle=4.02*pi) assert pretty(e) == 'Ray2D(Point2D(1, 1), Point2D(2, tan(pi/50) + 1))' def test_expint(): expr = Ei(x) string = 'Ei(x)' assert pretty(expr) == string assert upretty(expr) == string expr = expint(1, z) ucode_str = "E₁(z)" ascii_str = "expint(1, z)" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str assert pretty(Shi(x)) == 'Shi(x)' assert pretty(Si(x)) == 'Si(x)' assert pretty(Ci(x)) == 'Ci(x)' assert pretty(Chi(x)) == 'Chi(x)' assert upretty(Shi(x)) == 'Shi(x)' assert upretty(Si(x)) == 'Si(x)' assert upretty(Ci(x)) == 'Ci(x)' assert upretty(Chi(x)) == 'Chi(x)' def test_elliptic_functions(): ascii_str = \ """\ / 1 \\\n\ K|-----|\n\ \\z + 1/\ """ ucode_str = \ """\ ⎛ 1 ⎞\n\ K⎜─────⎟\n\ ⎝z + 1⎠\ """ expr = elliptic_k(1/(z + 1)) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / | 1 \\\n\ F|1|-----|\n\ \\ |z + 1/\ """ ucode_str = \ """\ ⎛ │ 1 ⎞\n\ F⎜1│─────⎟\n\ ⎝ │z + 1⎠\ """ expr = elliptic_f(1, 1/(1 + z)) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / 1 \\\n\ E|-----|\n\ \\z + 1/\ """ ucode_str = \ """\ ⎛ 1 ⎞\n\ E⎜─────⎟\n\ ⎝z + 1⎠\ """ expr = elliptic_e(1/(z + 1)) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / | 1 \\\n\ E|1|-----|\n\ \\ |z + 1/\ """ ucode_str = \ """\ ⎛ │ 1 ⎞\n\ E⎜1│─────⎟\n\ ⎝ │z + 1⎠\ """ expr = elliptic_e(1, 1/(1 + z)) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / |4\\\n\ Pi|3|-|\n\ \\ |x/\ """ ucode_str = \ """\ ⎛ │4⎞\n\ Π⎜3│─⎟\n\ ⎝ │x⎠\ """ expr = elliptic_pi(3, 4/x) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / 4| \\\n\ Pi|3; -|6|\n\ \\ x| /\ """ ucode_str = \ """\ ⎛ 4│ ⎞\n\ Π⎜3; ─│6⎟\n\ ⎝ x│ ⎠\ """ expr = elliptic_pi(3, 4/x, 6) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_RandomDomain(): from sympy.stats import Normal, Die, Exponential, pspace, where X = Normal('x1', 0, 1) assert upretty(where(X > 0)) == "Domain: 0 < x₁ ∧ x₁ < ∞" D = Die('d1', 6) assert upretty(where(D > 4)) == 'Domain: d₁ = 5 ∨ d₁ = 6' A = Exponential('a', 1) B = Exponential('b', 1) assert upretty(pspace(Tuple(A, B)).domain) == \ 'Domain: 0 ≤ a ∧ 0 ≤ b ∧ a < ∞ ∧ b < ∞' def test_PrettyPoly(): F = QQ.frac_field(x, y) R = QQ.poly_ring(x, y) expr = F.convert(x/(x + y)) assert pretty(expr) == "x/(x + y)" assert upretty(expr) == "x/(x + y)" expr = R.convert(x + y) assert pretty(expr) == "x + y" assert upretty(expr) == "x + y" def test_issue_6285(): assert pretty(Pow(2, -5, evaluate=False)) == '1 \n--\n 5\n2 ' assert pretty(Pow(x, (1/pi))) == \ ' 1 \n'\ ' --\n'\ ' pi\n'\ 'x ' def test_issue_6359(): assert pretty(Integral(x**2, x)**2) == \ """\ 2 / / \\ \n\ | | | \n\ | | 2 | \n\ | | x dx| \n\ | | | \n\ \\/ / \ """ assert upretty(Integral(x**2, x)**2) == \ """\ 2 ⎛⌠ ⎞ \n\ ⎜⎮ 2 ⎟ \n\ ⎜⎮ x dx⎟ \n\ ⎝⌡ ⎠ \ """ assert pretty(Sum(x**2, (x, 0, 1))**2) == \ """\ 2 / 1 \\ \n\ | ___ | \n\ | \\ ` | \n\ | \\ 2| \n\ | / x | \n\ | /__, | \n\ \\x = 0 / \ """ assert upretty(Sum(x**2, (x, 0, 1))**2) == \ """\ 2 ⎛ 1 ⎞ \n\ ⎜ ___ ⎟ \n\ ⎜ ╲ ⎟ \n\ ⎜ ╲ 2⎟ \n\ ⎜ ╱ x ⎟ \n\ ⎜ ╱ ⎟ \n\ ⎜ ‾‾‾ ⎟ \n\ ⎝x = 0 ⎠ \ """ assert pretty(Product(x**2, (x, 1, 2))**2) == \ """\ 2 / 2 \\ \n\ |______ | \n\ | | | 2| \n\ | | | x | \n\ | | | | \n\ \\x = 1 / \ """ assert upretty(Product(x**2, (x, 1, 2))**2) == \ """\ 2 ⎛ 2 ⎞ \n\ ⎜─┬──┬─ ⎟ \n\ ⎜ │ │ 2⎟ \n\ ⎜ │ │ x ⎟ \n\ ⎜ │ │ ⎟ \n\ ⎝x = 1 ⎠ \ """ f = Function('f') assert pretty(Derivative(f(x), x)**2) == \ """\ 2 /d \\ \n\ |--(f(x))| \n\ \\dx / \ """ assert upretty(Derivative(f(x), x)**2) == \ """\ 2 ⎛d ⎞ \n\ ⎜──(f(x))⎟ \n\ ⎝dx ⎠ \ """ def test_issue_6739(): ascii_str = \ """\ 1 \n\ -----\n\ ___\n\ \\/ x \ """ ucode_str = \ """\ 1 \n\ ──\n\ √x\ """ assert pretty(1/sqrt(x)) == ascii_str assert upretty(1/sqrt(x)) == ucode_str def test_complicated_symbol_unchanged(): for symb_name in ["dexpr2_d1tau", "dexpr2^d1tau"]: assert pretty(Symbol(symb_name)) == symb_name def test_categories(): from sympy.categories import (Object, IdentityMorphism, NamedMorphism, Category, Diagram, DiagramGrid) A1 = Object("A1") A2 = Object("A2") A3 = Object("A3") f1 = NamedMorphism(A1, A2, "f1") f2 = NamedMorphism(A2, A3, "f2") id_A1 = IdentityMorphism(A1) K1 = Category("K1") assert pretty(A1) == "A1" assert upretty(A1) == "A₁" assert pretty(f1) == "f1:A1-->A2" assert upretty(f1) == "f₁:A₁——▶A₂" assert pretty(id_A1) == "id:A1-->A1" assert upretty(id_A1) == "id:A₁——▶A₁" assert pretty(f2*f1) == "f2*f1:A1-->A3" assert upretty(f2*f1) == "f₂∘f₁:A₁——▶A₃" assert pretty(K1) == "K1" assert upretty(K1) == "K₁" # Test how diagrams are printed. d = Diagram() assert pretty(d) == "EmptySet" assert upretty(d) == "∅" d = Diagram({f1: "unique", f2: S.EmptySet}) assert pretty(d) == "{f2*f1:A1-->A3: EmptySet, id:A1-->A1: " \ "EmptySet, id:A2-->A2: EmptySet, id:A3-->A3: " \ "EmptySet, f1:A1-->A2: {unique}, f2:A2-->A3: EmptySet}" assert upretty(d) == "{f₂∘f₁:A₁——▶A₃: ∅, id:A₁——▶A₁: ∅, " \ "id:A₂——▶A₂: ∅, id:A₃——▶A₃: ∅, f₁:A₁——▶A₂: {unique}, f₂:A₂——▶A₃: ∅}" d = Diagram({f1: "unique", f2: S.EmptySet}, {f2 * f1: "unique"}) assert pretty(d) == "{f2*f1:A1-->A3: EmptySet, id:A1-->A1: " \ "EmptySet, id:A2-->A2: EmptySet, id:A3-->A3: " \ "EmptySet, f1:A1-->A2: {unique}, f2:A2-->A3: EmptySet}" \ " ==> {f2*f1:A1-->A3: {unique}}" assert upretty(d) == "{f₂∘f₁:A₁——▶A₃: ∅, id:A₁——▶A₁: ∅, id:A₂——▶A₂: " \ "∅, id:A₃——▶A₃: ∅, f₁:A₁——▶A₂: {unique}, f₂:A₂——▶A₃: ∅}" \ " ══▶ {f₂∘f₁:A₁——▶A₃: {unique}}" grid = DiagramGrid(d) assert pretty(grid) == "A1 A2\n \nA3 " assert upretty(grid) == "A₁ A₂\n \nA₃ " def test_PrettyModules(): R = QQ.old_poly_ring(x, y) F = R.free_module(2) M = F.submodule([x, y], [1, x**2]) ucode_str = \ """\ 2\n\ ℚ[x, y] \ """ ascii_str = \ """\ 2\n\ QQ[x, y] \ """ assert upretty(F) == ucode_str assert pretty(F) == ascii_str ucode_str = \ """\ ╱ ⎡ 2⎤╲\n\ ╲[x, y], ⎣1, x ⎦╱\ """ ascii_str = \ """\ 2 \n\ <[x, y], [1, x ]>\ """ assert upretty(M) == ucode_str assert pretty(M) == ascii_str I = R.ideal(x**2, y) ucode_str = \ """\ ╱ 2 ╲\n\ ╲x , y╱\ """ ascii_str = \ """\ 2 \n\ <x , y>\ """ assert upretty(I) == ucode_str assert pretty(I) == ascii_str Q = F / M ucode_str = \ """\ 2 \n\ ℚ[x, y] \n\ ─────────────────\n\ ╱ ⎡ 2⎤╲\n\ ╲[x, y], ⎣1, x ⎦╱\ """ ascii_str = \ """\ 2 \n\ QQ[x, y] \n\ -----------------\n\ 2 \n\ <[x, y], [1, x ]>\ """ assert upretty(Q) == ucode_str assert pretty(Q) == ascii_str ucode_str = \ """\ ╱⎡ 3⎤ ╲\n\ │⎢ x ⎥ ╱ ⎡ 2⎤╲ ╱ ⎡ 2⎤╲│\n\ │⎢1, ──⎥ + ╲[x, y], ⎣1, x ⎦╱, [2, y] + ╲[x, y], ⎣1, x ⎦╱│\n\ ╲⎣ 2 ⎦ ╱\ """ ascii_str = \ """\ 3 \n\ x 2 2 \n\ <[1, --] + <[x, y], [1, x ]>, [2, y] + <[x, y], [1, x ]>>\n\ 2 \ """ def test_QuotientRing(): R = QQ.old_poly_ring(x)/[x**2 + 1] ucode_str = \ """\ ℚ[x] \n\ ────────\n\ ╱ 2 ╲\n\ ╲x + 1╱\ """ ascii_str = \ """\ QQ[x] \n\ --------\n\ 2 \n\ <x + 1>\ """ assert upretty(R) == ucode_str assert pretty(R) == ascii_str ucode_str = \ """\ ╱ 2 ╲\n\ 1 + ╲x + 1╱\ """ ascii_str = \ """\ 2 \n\ 1 + <x + 1>\ """ assert upretty(R.one) == ucode_str assert pretty(R.one) == ascii_str def test_Homomorphism(): from sympy.polys.agca import homomorphism R = QQ.old_poly_ring(x) expr = homomorphism(R.free_module(1), R.free_module(1), [0]) ucode_str = \ """\ 1 1\n\ [0] : ℚ[x] ──> ℚ[x] \ """ ascii_str = \ """\ 1 1\n\ [0] : QQ[x] --> QQ[x] \ """ assert upretty(expr) == ucode_str assert pretty(expr) == ascii_str expr = homomorphism(R.free_module(2), R.free_module(2), [0, 0]) ucode_str = \ """\ ⎡0 0⎤ 2 2\n\ ⎢ ⎥ : ℚ[x] ──> ℚ[x] \n\ ⎣0 0⎦ \ """ ascii_str = \ """\ [0 0] 2 2\n\ [ ] : QQ[x] --> QQ[x] \n\ [0 0] \ """ assert upretty(expr) == ucode_str assert pretty(expr) == ascii_str expr = homomorphism(R.free_module(1), R.free_module(1) / [[x]], [0]) ucode_str = \ """\ 1\n\ 1 ℚ[x] \n\ [0] : ℚ[x] ──> ─────\n\ <[x]>\ """ ascii_str = \ """\ 1\n\ 1 QQ[x] \n\ [0] : QQ[x] --> ------\n\ <[x]> \ """ assert upretty(expr) == ucode_str assert pretty(expr) == ascii_str def test_Tr(): A, B = symbols('A B', commutative=False) t = Tr(A*B) assert pretty(t) == r'Tr(A*B)' assert upretty(t) == 'Tr(A⋅B)' def test_pretty_Add(): eq = Mul(-2, x - 2, evaluate=False) + 5 assert pretty(eq) == '5 - 2*(x - 2)' def test_issue_7179(): assert upretty(Not(Equivalent(x, y))) == 'x ⇎ y' assert upretty(Not(Implies(x, y))) == 'x ↛ y' def test_issue_7180(): assert upretty(Equivalent(x, y)) == 'x ⇔ y' def test_pretty_Complement(): assert pretty(S.Reals - S.Naturals) == '(-oo, oo) \\ Naturals' assert upretty(S.Reals - S.Naturals) == 'ℝ \\ ℕ' assert pretty(S.Reals - S.Naturals0) == '(-oo, oo) \\ Naturals0' assert upretty(S.Reals - S.Naturals0) == 'ℝ \\ ℕ₀' def test_pretty_SymmetricDifference(): from sympy import SymmetricDifference, Interval from sympy.testing.pytest import raises assert upretty(SymmetricDifference(Interval(2,3), Interval(3,5), \ evaluate = False)) == '[2, 3] ∆ [3, 5]' with raises(NotImplementedError): pretty(SymmetricDifference(Interval(2,3), Interval(3,5), evaluate = False)) def test_pretty_Contains(): assert pretty(Contains(x, S.Integers)) == 'Contains(x, Integers)' assert upretty(Contains(x, S.Integers)) == 'x ∈ ℤ' def test_issue_8292(): from sympy.core import sympify e = sympify('((x+x**4)/(x-1))-(2*(x-1)**4/(x-1)**4)', evaluate=False) ucode_str = \ """\ 4 4 \n\ 2⋅(x - 1) x + x\n\ - ────────── + ──────\n\ 4 x - 1 \n\ (x - 1) \ """ ascii_str = \ """\ 4 4 \n\ 2*(x - 1) x + x\n\ - ---------- + ------\n\ 4 x - 1 \n\ (x - 1) \ """ assert pretty(e) == ascii_str assert upretty(e) == ucode_str def test_issue_4335(): y = Function('y') expr = -y(x).diff(x) ucode_str = \ """\ d \n\ -──(y(x))\n\ dx \ """ ascii_str = \ """\ d \n\ - --(y(x))\n\ dx \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_issue_8344(): from sympy.core import sympify e = sympify('2*x*y**2/1**2 + 1', evaluate=False) ucode_str = \ """\ 2 \n\ 2⋅x⋅y \n\ ────── + 1\n\ 2 \n\ 1 \ """ assert upretty(e) == ucode_str def test_issue_6324(): x = Pow(2, 3, evaluate=False) y = Pow(10, -2, evaluate=False) e = Mul(x, y, evaluate=False) ucode_str = \ """\ 3\n\ 2 \n\ ───\n\ 2\n\ 10 \ """ assert upretty(e) == ucode_str def test_issue_7927(): e = sin(x/2)**cos(x/2) ucode_str = \ """\ ⎛x⎞\n\ cos⎜─⎟\n\ ⎝2⎠\n\ ⎛ ⎛x⎞⎞ \n\ ⎜sin⎜─⎟⎟ \n\ ⎝ ⎝2⎠⎠ \ """ assert upretty(e) == ucode_str e = sin(x)**(S(11)/13) ucode_str = \ """\ 11\n\ ──\n\ 13\n\ (sin(x)) \ """ assert upretty(e) == ucode_str def test_issue_6134(): from sympy.abc import lamda, t phi = Function('phi') e = lamda*x*Integral(phi(t)*pi*sin(pi*t), (t, 0, 1)) + lamda*x**2*Integral(phi(t)*2*pi*sin(2*pi*t), (t, 0, 1)) ucode_str = \ """\ 1 1 \n\ 2 ⌠ ⌠ \n\ λ⋅x ⋅⎮ 2⋅π⋅φ(t)⋅sin(2⋅π⋅t) dt + λ⋅x⋅⎮ π⋅φ(t)⋅sin(π⋅t) dt\n\ ⌡ ⌡ \n\ 0 0 \ """ assert upretty(e) == ucode_str def test_issue_9877(): ucode_str1 = '(2, 3) ∪ ([1, 2] \\ {x})' a, b, c = Interval(2, 3, True, True), Interval(1, 2), FiniteSet(x) assert upretty(Union(a, Complement(b, c))) == ucode_str1 ucode_str2 = '{x} ∩ {y} ∩ ({z} \\ [1, 2])' d, e, f, g = FiniteSet(x), FiniteSet(y), FiniteSet(z), Interval(1, 2) assert upretty(Intersection(d, e, Complement(f, g))) == ucode_str2 def test_issue_13651(): expr1 = c + Mul(-1, a + b, evaluate=False) assert pretty(expr1) == 'c - (a + b)' expr2 = c + Mul(-1, a - b + d, evaluate=False) assert pretty(expr2) == 'c - (a - b + d)' def test_pretty_primenu(): from sympy.ntheory.factor_ import primenu ascii_str1 = "nu(n)" ucode_str1 = "ν(n)" n = symbols('n', integer=True) assert pretty(primenu(n)) == ascii_str1 assert upretty(primenu(n)) == ucode_str1 def test_pretty_primeomega(): from sympy.ntheory.factor_ import primeomega ascii_str1 = "Omega(n)" ucode_str1 = "Ω(n)" n = symbols('n', integer=True) assert pretty(primeomega(n)) == ascii_str1 assert upretty(primeomega(n)) == ucode_str1 def test_pretty_Mod(): from sympy.core import Mod ascii_str1 = "x mod 7" ucode_str1 = "x mod 7" ascii_str2 = "(x + 1) mod 7" ucode_str2 = "(x + 1) mod 7" ascii_str3 = "2*x mod 7" ucode_str3 = "2⋅x mod 7" ascii_str4 = "(x mod 7) + 1" ucode_str4 = "(x mod 7) + 1" ascii_str5 = "2*(x mod 7)" ucode_str5 = "2⋅(x mod 7)" x = symbols('x', integer=True) assert pretty(Mod(x, 7)) == ascii_str1 assert upretty(Mod(x, 7)) == ucode_str1 assert pretty(Mod(x + 1, 7)) == ascii_str2 assert upretty(Mod(x + 1, 7)) == ucode_str2 assert pretty(Mod(2 * x, 7)) == ascii_str3 assert upretty(Mod(2 * x, 7)) == ucode_str3 assert pretty(Mod(x, 7) + 1) == ascii_str4 assert upretty(Mod(x, 7) + 1) == ucode_str4 assert pretty(2 * Mod(x, 7)) == ascii_str5 assert upretty(2 * Mod(x, 7)) == ucode_str5 def test_issue_11801(): assert pretty(Symbol("")) == "" assert upretty(Symbol("")) == "" def test_pretty_UnevaluatedExpr(): x = symbols('x') he = UnevaluatedExpr(1/x) ucode_str = \ """\ 1\n\ ─\n\ x\ """ assert upretty(he) == ucode_str ucode_str = \ """\ 2\n\ ⎛1⎞ \n\ ⎜─⎟ \n\ ⎝x⎠ \ """ assert upretty(he**2) == ucode_str ucode_str = \ """\ 1\n\ 1 + ─\n\ x\ """ assert upretty(he + 1) == ucode_str ucode_str = \ ('''\ 1\n\ x⋅─\n\ x\ ''') assert upretty(x*he) == ucode_str def test_issue_10472(): M = (Matrix([[0, 0], [0, 0]]), Matrix([0, 0])) ucode_str = \ """\ ⎛⎡0 0⎤ ⎡0⎤⎞ ⎜⎢ ⎥, ⎢ ⎥⎟ ⎝⎣0 0⎦ ⎣0⎦⎠\ """ assert upretty(M) == ucode_str def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) ascii_str1 = "A_00" ucode_str1 = "A₀₀" assert pretty(A[0, 0]) == ascii_str1 assert upretty(A[0, 0]) == ucode_str1 ascii_str1 = "3*A_00" ucode_str1 = "3⋅A₀₀" assert pretty(3*A[0, 0]) == ascii_str1 assert upretty(3*A[0, 0]) == ucode_str1 ascii_str1 = "(-B + A)[0, 0]" ucode_str1 = "(-B + A)[0, 0]" F = C[0, 0].subs(C, A - B) assert pretty(F) == ascii_str1 assert upretty(F) == ucode_str1 def test_issue_12675(): from sympy.vector import CoordSys3D x, y, t, j = symbols('x y t j') e = CoordSys3D('e') ucode_str = \ """\ ⎛ t⎞ \n\ ⎜⎛x⎞ ⎟ j_e\n\ ⎜⎜─⎟ ⎟ \n\ ⎝⎝y⎠ ⎠ \ """ assert upretty((x/y)**t*e.j) == ucode_str ucode_str = \ """\ ⎛1⎞ \n\ ⎜─⎟ j_e\n\ ⎝y⎠ \ """ assert upretty((1/y)*e.j) == ucode_str def test_MatrixSymbol_printing(): # test cases for issue #14237 A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert pretty(-A*B*C) == "-A*B*C" assert pretty(A - B) == "-B + A" assert pretty(A*B*C - A*B - B*C) == "-A*B -B*C + A*B*C" # issue #14814 x = MatrixSymbol('x', n, n) y = MatrixSymbol('y*', n, n) assert pretty(x + y) == "x + y*" ascii_str = \ """\ 2 \n\ -2*y* -a*x\ """ assert pretty(-a*x + -2*y*y) == ascii_str def test_degree_printing(): expr1 = 90*degree assert pretty(expr1) == '90°' expr2 = x*degree assert pretty(expr2) == 'x°' expr3 = cos(x*degree + 90*degree) assert pretty(expr3) == 'cos(x° + 90°)' def test_vector_expr_pretty_printing(): A = CoordSys3D('A') assert upretty(Cross(A.i, A.x*A.i+3*A.y*A.j)) == "(i_A)×((x_A) i_A + (3⋅y_A) j_A)" assert upretty(x*Cross(A.i, A.j)) == 'x⋅(i_A)×(j_A)' assert upretty(Curl(A.x*A.i + 3*A.y*A.j)) == "∇×((x_A) i_A + (3⋅y_A) j_A)" assert upretty(Divergence(A.x*A.i + 3*A.y*A.j)) == "∇⋅((x_A) i_A + (3⋅y_A) j_A)" assert upretty(Dot(A.i, A.x*A.i+3*A.y*A.j)) == "(i_A)⋅((x_A) i_A + (3⋅y_A) j_A)" assert upretty(Gradient(A.x+3*A.y)) == "∇(x_A + 3⋅y_A)" assert upretty(Laplacian(A.x+3*A.y)) == "∆(x_A + 3⋅y_A)" # TODO: add support for ASCII pretty. def test_pretty_print_tensor_expr(): L = TensorIndexType("L") i, j, k = tensor_indices("i j k", L) i0 = tensor_indices("i_0", L) A, B, C, D = tensor_heads("A B C D", [L]) H = TensorHead("H", [L, L]) expr = -i ascii_str = \ """\ -i\ """ ucode_str = \ """\ -i\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i) ascii_str = \ """\ i\n\ A \n\ \ """ ucode_str = \ """\ i\n\ A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i0) ascii_str = \ """\ i_0\n\ A \n\ \ """ ucode_str = \ """\ i₀\n\ A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(-i) ascii_str = \ """\ \n\ A \n\ i\ """ ucode_str = \ """\ \n\ A \n\ i\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -3*A(-i) ascii_str = \ """\ \n\ -3*A \n\ i\ """ ucode_str = \ """\ \n\ -3⋅A \n\ i\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = H(i, -j) ascii_str = \ """\ i \n\ H \n\ j\ """ ucode_str = \ """\ i \n\ H \n\ j\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = H(i, -i) ascii_str = \ """\ L_0 \n\ H \n\ L_0\ """ ucode_str = \ """\ L₀ \n\ H \n\ L₀\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = H(i, -j)*A(j)*B(k) ascii_str = \ """\ i L_0 k\n\ H *A *B \n\ L_0 \ """ ucode_str = \ """\ i L₀ k\n\ H ⋅A ⋅B \n\ L₀ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (1+x)*A(i) ascii_str = \ """\ i\n\ (x + 1)*A \n\ \ """ ucode_str = \ """\ i\n\ (x + 1)⋅A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i) + 3*B(i) ascii_str = \ """\ i i\n\ 3*B + A \n\ \ """ ucode_str = \ """\ i i\n\ 3⋅B + A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_print_tensor_partial_deriv(): from sympy.tensor.toperators import PartialDerivative from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, tensor_heads L = TensorIndexType("L") i, j, k = tensor_indices("i j k", L) A, B, C, D = tensor_heads("A B C D", [L]) H = TensorHead("H", [L, L]) expr = PartialDerivative(A(i), A(j)) ascii_str = \ """\ d / i\\\n\ ---|A |\n\ j\\ /\n\ dA \n\ \ """ ucode_str = \ """\ ∂ ⎛ i⎞\n\ ───⎜A ⎟\n\ j⎝ ⎠\n\ ∂A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i)*PartialDerivative(H(k, -i), A(j)) ascii_str = \ """\ L_0 d / k \\\n\ A *---|H |\n\ j\\ L_0/\n\ dA \n\ \ """ ucode_str = \ """\ L₀ ∂ ⎛ k ⎞\n\ A ⋅───⎜H ⎟\n\ j⎝ L₀⎠\n\ ∂A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i)*PartialDerivative(B(k)*C(-i) + 3*H(k, -i), A(j)) ascii_str = \ """\ L_0 d / k k \\\n\ A *---|3*H + B *C |\n\ j\\ L_0 L_0/\n\ dA \n\ \ """ ucode_str = \ """\ L₀ ∂ ⎛ k k ⎞\n\ A ⋅───⎜3⋅H + B ⋅C ⎟\n\ j⎝ L₀ L₀⎠\n\ ∂A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (A(i) + B(i))*PartialDerivative(C(j), D(j)) ascii_str = \ """\ / i i\\ d / L_0\\\n\ |A + B |*-----|C |\n\ \\ / L_0\\ /\n\ dD \n\ \ """ ucode_str = \ """\ ⎛ i i⎞ ∂ ⎛ L₀⎞\n\ ⎜A + B ⎟⋅────⎜C ⎟\n\ ⎝ ⎠ L₀⎝ ⎠\n\ ∂D \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (A(i) + B(i))*PartialDerivative(C(-i), D(j)) ascii_str = \ """\ / L_0 L_0\\ d / \\\n\ |A + B |*---|C |\n\ \\ / j\\ L_0/\n\ dD \n\ \ """ ucode_str = \ """\ ⎛ L₀ L₀⎞ ∂ ⎛ ⎞\n\ ⎜A + B ⎟⋅───⎜C ⎟\n\ ⎝ ⎠ j⎝ L₀⎠\n\ ∂D \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = PartialDerivative(B(-i) + A(-i), A(-j), A(-n)) ucode_str = """\ 2 \n\ ∂ ⎛ ⎞\n\ ───────⎜A + B ⎟\n\ ⎝ i i⎠\n\ ∂A ∂A \n\ n j \ """ assert upretty(expr) == ucode_str expr = PartialDerivative(3*A(-i), A(-j), A(-n)) ucode_str = """\ 2 \n\ ∂ ⎛ ⎞\n\ ───────⎜3⋅A ⎟\n\ ⎝ i⎠\n\ ∂A ∂A \n\ n j \ """ assert upretty(expr) == ucode_str expr = TensorElement(H(i, j), {i:1}) ascii_str = \ """\ i=1,j\n\ H \n\ \ """ ucode_str = ascii_str assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = TensorElement(H(i, j), {i: 1, j: 1}) ascii_str = \ """\ i=1,j=1\n\ H \n\ \ """ ucode_str = ascii_str assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = TensorElement(H(i, j), {j: 1}) ascii_str = \ """\ i,j=1\n\ H \n\ \ """ ucode_str = ascii_str expr = TensorElement(H(-i, j), {-i: 1}) ascii_str = \ """\ j\n\ H \n\ i=1 \ """ ucode_str = ascii_str assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_issue_15560(): a = MatrixSymbol('a', 1, 1) e = pretty(a*(KroneckerProduct(a, a))) result = 'a*(a x a)' assert e == result def test_print_lerchphi(): # Part of issue 6013 a = Symbol('a') pretty(lerchphi(a, 1, 2)) uresult = 'Φ(a, 1, 2)' aresult = 'lerchphi(a, 1, 2)' assert pretty(lerchphi(a, 1, 2)) == aresult assert upretty(lerchphi(a, 1, 2)) == uresult def test_issue_15583(): N = mechanics.ReferenceFrame('N') result = '(n_x, n_y, n_z)' e = pretty((N.x, N.y, N.z)) assert e == result def test_matrixSymbolBold(): # Issue 15871 def boldpretty(expr): return xpretty(expr, use_unicode=True, wrap_line=False, mat_symbol_style="bold") from sympy import trace A = MatrixSymbol("A", 2, 2) assert boldpretty(trace(A)) == 'tr(𝐀)' A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert boldpretty(-A) == '-𝐀' assert boldpretty(A - A*B - B) == '-𝐁 -𝐀⋅𝐁 + 𝐀' assert boldpretty(-A*B - A*B*C - B) == '-𝐁 -𝐀⋅𝐁 -𝐀⋅𝐁⋅𝐂' A = MatrixSymbol("Addot", 3, 3) assert boldpretty(A) == '𝐀̈' omega = MatrixSymbol("omega", 3, 3) assert boldpretty(omega) == 'ω' omega = MatrixSymbol("omeganorm", 3, 3) assert boldpretty(omega) == '‖ω‖' a = Symbol('alpha') b = Symbol('b') c = MatrixSymbol("c", 3, 1) d = MatrixSymbol("d", 3, 1) assert boldpretty(a*B*c+b*d) == 'b⋅𝐝 + α⋅𝐁⋅𝐜' d = MatrixSymbol("delta", 3, 1) B = MatrixSymbol("Beta", 3, 3) assert boldpretty(a*B*c+b*d) == 'b⋅δ + α⋅Β⋅𝐜' A = MatrixSymbol("A_2", 3, 3) assert boldpretty(A) == '𝐀₂' def test_center_accent(): assert center_accent('a', '\N{COMBINING TILDE}') == 'ã' assert center_accent('aa', '\N{COMBINING TILDE}') == 'aã' assert center_accent('aaa', '\N{COMBINING TILDE}') == 'aãa' assert center_accent('aaaa', '\N{COMBINING TILDE}') == 'aaãa' assert center_accent('aaaaa', '\N{COMBINING TILDE}') == 'aaãaa' assert center_accent('abcdefg', '\N{COMBINING FOUR DOTS ABOVE}') == 'abcd⃜efg' def test_imaginary_unit(): from sympy import pretty # As it is redefined above assert pretty(1 + I, use_unicode=False) == '1 + I' assert pretty(1 + I, use_unicode=True) == '1 + ⅈ' assert pretty(1 + I, use_unicode=False, imaginary_unit='j') == '1 + I' assert pretty(1 + I, use_unicode=True, imaginary_unit='j') == '1 + ⅉ' raises(TypeError, lambda: pretty(I, imaginary_unit=I)) raises(ValueError, lambda: pretty(I, imaginary_unit="kkk")) def test_str_special_matrices(): from sympy.matrices import Identity, ZeroMatrix, OneMatrix assert pretty(Identity(4)) == 'I' assert upretty(Identity(4)) == '𝕀' assert pretty(ZeroMatrix(2, 2)) == '0' assert upretty(ZeroMatrix(2, 2)) == '𝟘' assert pretty(OneMatrix(2, 2)) == '1' assert upretty(OneMatrix(2, 2)) == '𝟙' def test_pretty_misc_functions(): assert pretty(LambertW(x)) == 'W(x)' assert upretty(LambertW(x)) == 'W(x)' assert pretty(LambertW(x, y)) == 'W(x, y)' assert upretty(LambertW(x, y)) == 'W(x, y)' assert pretty(airyai(x)) == 'Ai(x)' assert upretty(airyai(x)) == 'Ai(x)' assert pretty(airybi(x)) == 'Bi(x)' assert upretty(airybi(x)) == 'Bi(x)' assert pretty(airyaiprime(x)) == "Ai'(x)" assert upretty(airyaiprime(x)) == "Ai'(x)" assert pretty(airybiprime(x)) == "Bi'(x)" assert upretty(airybiprime(x)) == "Bi'(x)" assert pretty(fresnelc(x)) == 'C(x)' assert upretty(fresnelc(x)) == 'C(x)' assert pretty(fresnels(x)) == 'S(x)' assert upretty(fresnels(x)) == 'S(x)' assert pretty(Heaviside(x)) == 'Heaviside(x)' assert upretty(Heaviside(x)) == 'θ(x)' assert pretty(Heaviside(x, y)) == 'Heaviside(x, y)' assert upretty(Heaviside(x, y)) == 'θ(x, y)' assert pretty(dirichlet_eta(x)) == 'dirichlet_eta(x)' assert upretty(dirichlet_eta(x)) == 'η(x)' def test_hadamard_power(): m, n, p = symbols('m, n, p', integer=True) A = MatrixSymbol('A', m, n) B = MatrixSymbol('B', m, n) # Testing printer: expr = hadamard_power(A, n) ascii_str = \ """\ .n\n\ A \ """ ucode_str = \ """\ ∘n\n\ A \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hadamard_power(A, 1+n) ascii_str = \ """\ .(n + 1)\n\ A \ """ ucode_str = \ """\ ∘(n + 1)\n\ A \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hadamard_power(A*B.T, 1+n) ascii_str = \ """\ .(n + 1)\n\ / T\\ \n\ \\A*B / \ """ ucode_str = \ """\ ∘(n + 1)\n\ ⎛ T⎞ \n\ ⎝A⋅B ⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_issue_17258(): n = Symbol('n', integer=True) assert pretty(Sum(n, (n, -oo, 1))) == \ ' 1 \n'\ ' __ \n'\ ' \\ ` \n'\ ' ) n\n'\ ' /_, \n'\ 'n = -oo ' assert upretty(Sum(n, (n, -oo, 1))) == \ """\ 1 \n\ ___ \n\ ╲ \n\ ╲ \n\ ╱ n\n\ ╱ \n\ ‾‾‾ \n\ n = -∞ \ """ def test_is_combining(): line = "v̇_m" assert [is_combining(sym) for sym in line] == \ [False, True, False, False] def test_issue_17616(): assert pretty(pi**(1/exp(1))) == \ ' / -1\\\n'\ ' \\e /\n'\ 'pi ' assert upretty(pi**(1/exp(1))) == \ ' ⎛ -1⎞\n'\ ' ⎝ℯ ⎠\n'\ 'π ' assert pretty(pi**(1/pi)) == \ ' 1 \n'\ ' --\n'\ ' pi\n'\ 'pi ' assert upretty(pi**(1/pi)) == \ ' 1\n'\ ' ─\n'\ ' π\n'\ 'π ' assert pretty(pi**(1/EulerGamma)) == \ ' 1 \n'\ ' ----------\n'\ ' EulerGamma\n'\ 'pi ' assert upretty(pi**(1/EulerGamma)) == \ ' 1\n'\ ' ─\n'\ ' γ\n'\ 'π ' z = Symbol("x_17") assert upretty(7**(1/z)) == \ 'x₁₇___\n'\ ' ╲╱ 7 ' assert pretty(7**(1/z)) == \ 'x_17___\n'\ ' \\/ 7 ' def test_issue_17857(): assert pretty(Range(-oo, oo)) == '{..., -1, 0, 1, ...}' assert pretty(Range(oo, -oo, -1)) == '{..., 1, 0, -1, ...}' def test_issue_18272(): x = Symbol('x') n = Symbol('n') assert upretty(ConditionSet(x, Eq(-x + exp(x), 0), S.Complexes)) == \ '⎧ │ ⎛ x ⎞⎫\n'\ '⎨x │ x ∊ ℂ ∧ ⎝-x + ℯ = 0⎠⎬\n'\ '⎩ │ ⎭' assert upretty(ConditionSet(x, Contains(n/2, Interval(0, oo)), FiniteSet(-n/2, n/2))) == \ '⎧ │ ⎧-n n⎫ ⎛n ⎞⎫\n'\ '⎨x │ x ∊ ⎨───, ─⎬ ∧ ⎜─ ∈ [0, ∞)⎟⎬\n'\ '⎩ │ ⎩ 2 2⎭ ⎝2 ⎠⎭' assert upretty(ConditionSet(x, Eq(Piecewise((1, x >= 3), (x/2 - 1/2, x >= 2), (1/2, x >= 1), (x/2, True)) - 1/2, 0), Interval(0, 3))) == \ '⎧ │ ⎛⎛⎧ 1 for x ≥ 3⎞ ⎞⎫\n'\ '⎪ │ ⎜⎜⎪ ⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪x ⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪─ - 0.5 for x ≥ 2⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪2 ⎟ ⎟⎪\n'\ '⎨x │ x ∊ [0, 3] ∧ ⎜⎜⎨ ⎟ - 0.5 = 0⎟⎬\n'\ '⎪ │ ⎜⎜⎪ 0.5 for x ≥ 1⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪ ⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪ x ⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪ ─ otherwise⎟ ⎟⎪\n'\ '⎩ │ ⎝⎝⎩ 2 ⎠ ⎠⎭' def test_Str(): from sympy.core.symbol import Str assert pretty(Str('x')) == 'x' def test_diffgeom(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField x,y = symbols('x y', real=True) m = Manifold('M', 2) assert pretty(m) == 'M' p = Patch('P', m) assert pretty(p) == "P" rect = CoordSystem('rect', p, [x, y]) assert pretty(rect) == "rect" b = BaseScalarField(rect, 0) assert pretty(b) == "x"
c531d8c24fb728b82f0e437f0d16ece3ea616b91a69aca189e30bae609815bf2
from sympy import ( Abs, acos, acosh, Add, And, asin, asinh, atan, Ci, cos, sinh, cosh, tanh, Derivative, diff, DiracDelta, E, Ei, Eq, exp, erf, erfc, erfi, EulerGamma, Expr, factor, Function, gamma, gammasimp, I, Idx, im, IndexedBase, integrate, Interval, Lambda, LambertW, log, Matrix, Max, meijerg, Min, nan, Ne, O, oo, pi, Piecewise, polar_lift, Poly, polygamma, Rational, re, S, Si, sign, simplify, sin, sinc, SingularityFunction, sqrt, sstr, Sum, Symbol, summation, symbols, sympify, tan, trigsimp, Tuple, lerchphi, exp_polar, li, hyper, Float ) from sympy.core.expr import unchanged from sympy.functions.elementary.complexes import periodic_argument from sympy.functions.elementary.integers import floor from sympy.integrals.integrals import Integral from sympy.integrals.risch import NonElementaryIntegral from sympy.physics import units from sympy.testing.pytest import (raises, slow, skip, ON_TRAVIS, warns_deprecated_sympy) from sympy.testing.randtest import verify_numerically x, y, a, t, x_1, x_2, z, s, b = symbols('x y a t x_1 x_2 z s b') n = Symbol('n', integer=True) f = Function('f') def NS(e, n=15, **options): return sstr(sympify(e).evalf(n, **options), full_prec=True) def test_poly_deprecated(): p = Poly(2*x, x) assert p.integrate(x) == Poly(x**2, x, domain='QQ') with warns_deprecated_sympy(): integrate(p, x) with warns_deprecated_sympy(): Integral(p, (x,)) @slow def test_principal_value(): g = 1 / x assert Integral(g, (x, -oo, oo)).principal_value() == 0 assert Integral(g, (y, -oo, oo)).principal_value() == oo * sign(1 / x) raises(ValueError, lambda: Integral(g, (x)).principal_value()) raises(ValueError, lambda: Integral(g).principal_value()) l = 1 / ((x ** 3) - 1) assert Integral(l, (x, -oo, oo)).principal_value().together() == -sqrt(3)*pi/3 raises(ValueError, lambda: Integral(l, (x, -oo, 1)).principal_value()) d = 1 / (x ** 2 - 1) assert Integral(d, (x, -oo, oo)).principal_value() == 0 assert Integral(d, (x, -2, 2)).principal_value() == -log(3) v = x / (x ** 2 - 1) assert Integral(v, (x, -oo, oo)).principal_value() == 0 assert Integral(v, (x, -2, 2)).principal_value() == 0 s = x ** 2 / (x ** 2 - 1) assert Integral(s, (x, -oo, oo)).principal_value() is oo assert Integral(s, (x, -2, 2)).principal_value() == -log(3) + 4 f = 1 / ((x ** 2 - 1) * (1 + x ** 2)) assert Integral(f, (x, -oo, oo)).principal_value() == -pi / 2 assert Integral(f, (x, -2, 2)).principal_value() == -atan(2) - log(3) / 2 def diff_test(i): """Return the set of symbols, s, which were used in testing that i.diff(s) agrees with i.doit().diff(s). If there is an error then the assertion will fail, causing the test to fail.""" syms = i.free_symbols for s in syms: assert (i.diff(s).doit() - i.doit().diff(s)).expand() == 0 return syms def test_improper_integral(): assert integrate(log(x), (x, 0, 1)) == -1 assert integrate(x**(-2), (x, 1, oo)) == 1 assert integrate(1/(1 + exp(x)), (x, 0, oo)) == log(2) def test_constructor(): # this is shared by Sum, so testing Integral's constructor # is equivalent to testing Sum's s1 = Integral(n, n) assert s1.limits == (Tuple(n),) s2 = Integral(n, (n,)) assert s2.limits == (Tuple(n),) s3 = Integral(Sum(x, (x, 1, y))) assert s3.limits == (Tuple(y),) s4 = Integral(n, Tuple(n,)) assert s4.limits == (Tuple(n),) s5 = Integral(n, (n, Interval(1, 2))) assert s5.limits == (Tuple(n, 1, 2),) # Testing constructor with inequalities: s6 = Integral(n, n > 10) assert s6.limits == (Tuple(n, 10, oo),) s7 = Integral(n, (n > 2) & (n < 5)) assert s7.limits == (Tuple(n, 2, 5),) def test_basics(): assert Integral(0, x) != 0 assert Integral(x, (x, 1, 1)) != 0 assert Integral(oo, x) != oo assert Integral(S.NaN, x) is S.NaN assert diff(Integral(y, y), x) == 0 assert diff(Integral(x, (x, 0, 1)), x) == 0 assert diff(Integral(x, x), x) == x assert diff(Integral(t, (t, 0, x)), x) == x e = (t + 1)**2 assert diff(integrate(e, (t, 0, x)), x) == \ diff(Integral(e, (t, 0, x)), x).doit().expand() == \ ((1 + x)**2).expand() assert diff(integrate(e, (t, 0, x)), t) == \ diff(Integral(e, (t, 0, x)), t) == 0 assert diff(integrate(e, (t, 0, x)), a) == \ diff(Integral(e, (t, 0, x)), a) == 0 assert diff(integrate(e, t), a) == diff(Integral(e, t), a) == 0 assert integrate(e, (t, a, x)).diff(x) == \ Integral(e, (t, a, x)).diff(x).doit().expand() assert Integral(e, (t, a, x)).diff(x).doit() == ((1 + x)**2) assert integrate(e, (t, x, a)).diff(x).doit() == (-(1 + x)**2).expand() assert integrate(t**2, (t, x, 2*x)).diff(x) == 7*x**2 assert Integral(x, x).atoms() == {x} assert Integral(f(x), (x, 0, 1)).atoms() == {S.Zero, S.One, x} assert diff_test(Integral(x, (x, 3*y))) == {y} assert diff_test(Integral(x, (a, 3*y))) == {x, y} assert integrate(x, (x, oo, oo)) == 0 #issue 8171 assert integrate(x, (x, -oo, -oo)) == 0 # sum integral of terms assert integrate(y + x + exp(x), x) == x*y + x**2/2 + exp(x) assert Integral(x).is_commutative n = Symbol('n', commutative=False) assert Integral(n + x, x).is_commutative is False def test_diff_wrt(): class Test(Expr): _diff_wrt = True is_commutative = True t = Test() assert integrate(t + 1, t) == t**2/2 + t assert integrate(t + 1, (t, 0, 1)) == Rational(3, 2) raises(ValueError, lambda: integrate(x + 1, x + 1)) raises(ValueError, lambda: integrate(x + 1, (x + 1, 0, 1))) def test_basics_multiple(): assert diff_test(Integral(x, (x, 3*x, 5*y), (y, x, 2*x))) == {x} assert diff_test(Integral(x, (x, 5*y), (y, x, 2*x))) == {x} assert diff_test(Integral(x, (x, 5*y), (y, y, 2*x))) == {x, y} assert diff_test(Integral(y, y, x)) == {x, y} assert diff_test(Integral(y*x, x, y)) == {x, y} assert diff_test(Integral(x + y, y, (y, 1, x))) == {x} assert diff_test(Integral(x + y, (x, x, y), (y, y, x))) == {x, y} def test_conjugate_transpose(): A, B = symbols("A B", commutative=False) x = Symbol("x", complex=True) p = Integral(A*B, (x,)) assert p.adjoint().doit() == p.doit().adjoint() assert p.conjugate().doit() == p.doit().conjugate() assert p.transpose().doit() == p.doit().transpose() x = Symbol("x", real=True) p = Integral(A*B, (x,)) assert p.adjoint().doit() == p.doit().adjoint() assert p.conjugate().doit() == p.doit().conjugate() assert p.transpose().doit() == p.doit().transpose() def test_integration(): assert integrate(0, (t, 0, x)) == 0 assert integrate(3, (t, 0, x)) == 3*x assert integrate(t, (t, 0, x)) == x**2/2 assert integrate(3*t, (t, 0, x)) == 3*x**2/2 assert integrate(3*t**2, (t, 0, x)) == x**3 assert integrate(1/t, (t, 1, x)) == log(x) assert integrate(-1/t**2, (t, 1, x)) == 1/x - 1 assert integrate(t**2 + 5*t - 8, (t, 0, x)) == x**3/3 + 5*x**2/2 - 8*x assert integrate(x**2, x) == x**3/3 assert integrate((3*t*x)**5, x) == (3*t)**5 * x**6 / 6 b = Symbol("b") c = Symbol("c") assert integrate(a*t, (t, 0, x)) == a*x**2/2 assert integrate(a*t**4, (t, 0, x)) == a*x**5/5 assert integrate(a*t**2 + b*t + c, (t, 0, x)) == a*x**3/3 + b*x**2/2 + c*x def test_multiple_integration(): assert integrate((x**2)*(y**2), (x, 0, 1), (y, -1, 2)) == Rational(1) assert integrate((y**2)*(x**2), x, y) == Rational(1, 9)*(x**3)*(y**3) assert integrate(1/(x + 3)/(1 + x)**3, x) == \ log(3 + x)*Rational(-1, 8) + log(1 + x)*Rational(1, 8) + x/(4 + 8*x + 4*x**2) assert integrate(sin(x*y)*y, (x, 0, 1), (y, 0, 1)) == -sin(1) + 1 def test_issue_3532(): assert integrate(exp(-x), (x, 0, oo)) == 1 def test_issue_3560(): assert integrate(sqrt(x)**3, x) == 2*sqrt(x)**5/5 assert integrate(sqrt(x), x) == 2*sqrt(x)**3/3 assert integrate(1/sqrt(x)**3, x) == -2/sqrt(x) def test_issue_18038(): raises(AttributeError, lambda: integrate((x, x))) def test_integrate_poly(): p = Poly(x + x**2*y + y**3, x, y) with warns_deprecated_sympy(): qx = integrate(p, x) with warns_deprecated_sympy(): qy = integrate(p, y) assert isinstance(qx, Poly) is True assert isinstance(qy, Poly) is True assert qx.gens == (x, y) assert qy.gens == (x, y) assert qx.as_expr() == x**2/2 + x**3*y/3 + x*y**3 assert qy.as_expr() == x*y + x**2*y**2/2 + y**4/4 def test_integrate_poly_defined(): p = Poly(x + x**2*y + y**3, x, y) with warns_deprecated_sympy(): Qx = integrate(p, (x, 0, 1)) with warns_deprecated_sympy(): Qy = integrate(p, (y, 0, pi)) assert isinstance(Qx, Poly) is True assert isinstance(Qy, Poly) is True assert Qx.gens == (y,) assert Qy.gens == (x,) assert Qx.as_expr() == S.Half + y/3 + y**3 assert Qy.as_expr() == pi**4/4 + pi*x + pi**2*x**2/2 def test_integrate_omit_var(): y = Symbol('y') assert integrate(x) == x**2/2 raises(ValueError, lambda: integrate(2)) raises(ValueError, lambda: integrate(x*y)) def test_integrate_poly_accurately(): y = Symbol('y') assert integrate(x*sin(y), x) == x**2*sin(y)/2 # when passed to risch_norman, this will be a CPU hog, so this really # checks, that integrated function is recognized as polynomial assert integrate(x**1000*sin(y), x) == x**1001*sin(y)/1001 def test_issue_3635(): y = Symbol('y') assert integrate(x**2, y) == x**2*y assert integrate(x**2, (y, -1, 1)) == 2*x**2 # works in sympy and py.test but hangs in `setup.py test` def test_integrate_linearterm_pow(): # check integrate((a*x+b)^c, x) -- issue 3499 y = Symbol('y', positive=True) # TODO: Remove conds='none' below, let the assumption take care of it. assert integrate(x**y, x, conds='none') == x**(y + 1)/(y + 1) assert integrate((exp(y)*x + 1/y)**(1 + sin(y)), x, conds='none') == \ exp(-y)*(exp(y)*x + 1/y)**(2 + sin(y)) / (2 + sin(y)) def test_issue_3618(): assert integrate(pi*sqrt(x), x) == 2*pi*sqrt(x)**3/3 assert integrate(pi*sqrt(x) + E*sqrt(x)**3, x) == \ 2*pi*sqrt(x)**3/3 + 2*E *sqrt(x)**5/5 def test_issue_3623(): assert integrate(cos((n + 1)*x), x) == Piecewise( (sin(x*(n + 1))/(n + 1), Ne(n + 1, 0)), (x, True)) assert integrate(cos((n - 1)*x), x) == Piecewise( (sin(x*(n - 1))/(n - 1), Ne(n - 1, 0)), (x, True)) assert integrate(cos((n + 1)*x) + cos((n - 1)*x), x) == \ Piecewise((sin(x*(n - 1))/(n - 1), Ne(n - 1, 0)), (x, True)) + \ Piecewise((sin(x*(n + 1))/(n + 1), Ne(n + 1, 0)), (x, True)) def test_issue_3664(): n = Symbol('n', integer=True, nonzero=True) assert integrate(-1./2 * x * sin(n * pi * x/2), [x, -2, 0]) == \ 2.0*cos(pi*n)/(pi*n) assert integrate(x * sin(n * pi * x/2) * Rational(-1, 2), [x, -2, 0]) == \ 2*cos(pi*n)/(pi*n) def test_issue_3679(): # definite integration of rational functions gives wrong answers assert NS(Integral(1/(x**2 - 8*x + 17), (x, 2, 4))) == '1.10714871779409' def test_issue_3686(): # remove this when fresnel itegrals are implemented from sympy import expand_func, fresnels assert expand_func(integrate(sin(x**2), x)) == \ sqrt(2)*sqrt(pi)*fresnels(sqrt(2)*x/sqrt(pi))/2 def test_integrate_units(): m = units.m s = units.s assert integrate(x * m/s, (x, 1*s, 5*s)) == 12*m*s def test_transcendental_functions(): assert integrate(LambertW(2*x), x) == \ -x + x*LambertW(2*x) + x/LambertW(2*x) def test_log_polylog(): assert integrate(log(1 - x)/x, (x, 0, 1)) == -pi**2/6 assert integrate(log(x)*(1 - x)**(-1), (x, 0, 1)) == -pi**2/6 def test_issue_3740(): f = 4*log(x) - 2*log(x)**2 fid = diff(integrate(f, x), x) assert abs(f.subs(x, 42).evalf() - fid.subs(x, 42).evalf()) < 1e-10 def test_issue_3788(): assert integrate(1/(1 + x**2), x) == atan(x) def test_issue_3952(): f = sin(x) assert integrate(f, x) == -cos(x) raises(ValueError, lambda: integrate(f, 2*x)) def test_issue_4516(): assert integrate(2**x - 2*x, x) == 2**x/log(2) - x**2 def test_issue_7450(): ans = integrate(exp(-(1 + I)*x), (x, 0, oo)) assert re(ans) == S.Half and im(ans) == Rational(-1, 2) def test_issue_8623(): assert integrate((1 + cos(2*x)) / (3 - 2*cos(2*x)), (x, 0, pi)) == -pi/2 + sqrt(5)*pi/2 assert integrate((1 + cos(2*x))/(3 - 2*cos(2*x))) == -x/2 + sqrt(5)*(atan(sqrt(5)*tan(x)) + \ pi*floor((x - pi/2)/pi))/2 def test_issue_9569(): assert integrate(1 / (2 - cos(x)), (x, 0, pi)) == pi/sqrt(3) assert integrate(1/(2 - cos(x))) == 2*sqrt(3)*(atan(sqrt(3)*tan(x/2)) + pi*floor((x/2 - pi/2)/pi))/3 def test_issue_13733(): s = Symbol('s', positive=True) pz = exp(-(z - y)**2/(2*s*s))/sqrt(2*pi*s*s) pzgx = integrate(pz, (z, x, oo)) assert integrate(pzgx, (x, 0, oo)) == sqrt(2)*s*exp(-y**2/(2*s**2))/(2*sqrt(pi)) + \ y*erf(sqrt(2)*y/(2*s))/2 + y/2 def test_issue_13749(): assert integrate(1 / (2 + cos(x)), (x, 0, pi)) == pi/sqrt(3) assert integrate(1/(2 + cos(x))) == 2*sqrt(3)*(atan(sqrt(3)*tan(x/2)/3) + pi*floor((x/2 - pi/2)/pi))/3 def test_issue_18133(): assert integrate(exp(x)/(1 + x)**2, x) == NonElementaryIntegral(exp(x)/(x + 1)**2, x) def test_issue_21741(): a = Float('3999999.9999999995', precision=53) b = Float('2.5000000000000004e-7', precision=53) r = Piecewise((b*I*exp(-a*I*pi*t*y)*exp(-a*I*pi*x*z)/(pi*x), Ne(1.0*pi*x*exp(a*I*pi*t*y), 0)), (z*exp(-a*I*pi*t*y), True)) fun = E**((-2*I*pi*(z*x+t*y))/(500*10**(-9))) assert integrate(fun, z) == r def test_matrices(): M = Matrix(2, 2, lambda i, j: (i + j + 1)*sin((i + j + 1)*x)) assert integrate(M, x) == Matrix([ [-cos(x), -cos(2*x)], [-cos(2*x), -cos(3*x)], ]) def test_integrate_functions(): # issue 4111 assert integrate(f(x), x) == Integral(f(x), x) assert integrate(f(x), (x, 0, 1)) == Integral(f(x), (x, 0, 1)) assert integrate(f(x)*diff(f(x), x), x) == f(x)**2/2 assert integrate(diff(f(x), x) / f(x), x) == log(f(x)) def test_integrate_derivatives(): assert integrate(Derivative(f(x), x), x) == f(x) assert integrate(Derivative(f(y), y), x) == x*Derivative(f(y), y) assert integrate(Derivative(f(x), x)**2, x) == \ Integral(Derivative(f(x), x)**2, x) def test_transform(): a = Integral(x**2 + 1, (x, -1, 2)) fx = x fy = 3*y + 1 assert a.doit() == a.transform(fx, fy).doit() assert a.transform(fx, fy).transform(fy, fx) == a fx = 3*x + 1 fy = y assert a.transform(fx, fy).transform(fy, fx) == a a = Integral(sin(1/x), (x, 0, 1)) assert a.transform(x, 1/y) == Integral(sin(y)/y**2, (y, 1, oo)) assert a.transform(x, 1/y).transform(y, 1/x) == a a = Integral(exp(-x**2), (x, -oo, oo)) assert a.transform(x, 2*y) == Integral(2*exp(-4*y**2), (y, -oo, oo)) # < 3 arg limit handled properly assert Integral(x, x).transform(x, a*y).doit() == \ Integral(y*a**2, y).doit() _3 = S(3) assert Integral(x, (x, 0, -_3)).transform(x, 1/y).doit() == \ Integral(-1/x**3, (x, -oo, -1/_3)).doit() assert Integral(x, (x, 0, _3)).transform(x, 1/y) == \ Integral(y**(-3), (y, 1/_3, oo)) # issue 8400 i = Integral(x + y, (x, 1, 2), (y, 1, 2)) assert i.transform(x, (x + 2*y, x)).doit() == \ i.transform(x, (x + 2*z, x)).doit() == 3 i = Integral(x, (x, a, b)) assert i.transform(x, 2*s) == Integral(4*s, (s, a/2, b/2)) raises(ValueError, lambda: i.transform(x, 1)) raises(ValueError, lambda: i.transform(x, s*t)) raises(ValueError, lambda: i.transform(x, -s)) raises(ValueError, lambda: i.transform(x, (s, t))) raises(ValueError, lambda: i.transform(2*x, 2*s)) i = Integral(x**2, (x, 1, 2)) raises(ValueError, lambda: i.transform(x**2, s)) am = Symbol('a', negative=True) bp = Symbol('b', positive=True) i = Integral(x, (x, bp, am)) i.transform(x, 2*s) assert i.transform(x, 2*s) == Integral(-4*s, (s, am/2, bp/2)) i = Integral(x, (x, a)) assert i.transform(x, 2*s) == Integral(4*s, (s, a/2)) def test_issue_4052(): f = S.Half*asin(x) + x*sqrt(1 - x**2)/2 assert integrate(cos(asin(x)), x) == f assert integrate(sin(acos(x)), x) == f @slow def test_evalf_integrals(): assert NS(Integral(x, (x, 2, 5)), 15) == '10.5000000000000' gauss = Integral(exp(-x**2), (x, -oo, oo)) assert NS(gauss, 15) == '1.77245385090552' assert NS(gauss**2 - pi + E*Rational( 1, 10**20), 15) in ('2.71828182845904e-20', '2.71828182845905e-20') # A monster of an integral from http://mathworld.wolfram.com/DefiniteIntegral.html t = Symbol('t') a = 8*sqrt(3)/(1 + 3*t**2) b = 16*sqrt(2)*(3*t + 1)*sqrt(4*t**2 + t + 1)**3 c = (3*t**2 + 1)*(11*t**2 + 2*t + 3)**2 d = sqrt(2)*(249*t**2 + 54*t + 65)/(11*t**2 + 2*t + 3)**2 f = a - b/c - d assert NS(Integral(f, (t, 0, 1)), 50) == \ NS((3*sqrt(2) - 49*pi + 162*atan(sqrt(2)))/12, 50) # http://mathworld.wolfram.com/VardisIntegral.html assert NS(Integral(log(log(1/x))/(1 + x + x**2), (x, 0, 1)), 15) == \ NS('pi/sqrt(3) * log(2*pi**(5/6) / gamma(1/6))', 15) # http://mathworld.wolfram.com/AhmedsIntegral.html assert NS(Integral(atan(sqrt(x**2 + 2))/(sqrt(x**2 + 2)*(x**2 + 1)), (x, 0, 1)), 15) == NS(5*pi**2/96, 15) # http://mathworld.wolfram.com/AbelsIntegral.html assert NS(Integral(x/((exp(pi*x) - exp( -pi*x))*(x**2 + 1)), (x, 0, oo)), 15) == NS('log(2)/2-1/4', 15) # Complex part trimming # http://mathworld.wolfram.com/VardisIntegral.html assert NS(Integral(log(log(sin(x)/cos(x))), (x, pi/4, pi/2)), 15, chop=True) == \ NS('pi/4*log(4*pi**3/gamma(1/4)**4)', 15) # # Endpoints causing trouble (rounding error in integration points -> complex log) assert NS( 2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 17, chop=True) == NS(2, 17) assert NS( 2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 20, chop=True) == NS(2, 20) assert NS( 2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 22, chop=True) == NS(2, 22) # Needs zero handling assert NS(pi - 4*Integral( 'sqrt(1-x**2)', (x, 0, 1)), 15, maxn=30, chop=True) in ('0.0', '0') # Oscillatory quadrature a = Integral(sin(x)/x**2, (x, 1, oo)).evalf(maxn=15) assert 0.49 < a < 0.51 assert NS( Integral(sin(x)/x**2, (x, 1, oo)), quad='osc') == '0.504067061906928' assert NS(Integral( cos(pi*x + 1)/x, (x, -oo, -1)), quad='osc') == '0.276374705640365' # indefinite integrals aren't evaluated assert NS(Integral(x, x)) == 'Integral(x, x)' assert NS(Integral(x, (x, y))) == 'Integral(x, (x, y))' def test_evalf_issue_939(): # https://github.com/sympy/sympy/issues/4038 # The output form of an integral may differ by a step function between # revisions, making this test a bit useless. This can't be said about # other two tests. For now, all values of this evaluation are used here, # but in future this should be reconsidered. assert NS(integrate(1/(x**5 + 1), x).subs(x, 4), chop=True) in \ ['-0.000976138910649103', '0.965906660135753', '1.93278945918216'] assert NS(Integral(1/(x**5 + 1), (x, 2, 4))) == '0.0144361088886740' assert NS( integrate(1/(x**5 + 1), (x, 2, 4)), chop=True) == '0.0144361088886740' def test_double_previously_failing_integrals(): # Double integrals not implemented <- Sure it is! res = integrate(sqrt(x) + x*y, (x, 1, 2), (y, -1, 1)) # Old numerical test assert NS(res, 15) == '2.43790283299492' # Symbolic test assert res == Rational(-4, 3) + 8*sqrt(2)/3 # double integral + zero detection assert integrate(sin(x + x*y), (x, -1, 1), (y, -1, 1)) is S.Zero def test_integrate_SingularityFunction(): in_1 = SingularityFunction(x, a, 3) + SingularityFunction(x, 5, -1) out_1 = SingularityFunction(x, a, 4)/4 + SingularityFunction(x, 5, 0) assert integrate(in_1, x) == out_1 in_2 = 10*SingularityFunction(x, 4, 0) - 5*SingularityFunction(x, -6, -2) out_2 = 10*SingularityFunction(x, 4, 1) - 5*SingularityFunction(x, -6, -1) assert integrate(in_2, x) == out_2 in_3 = 2*x**2*y -10*SingularityFunction(x, -4, 7) - 2*SingularityFunction(y, 10, -2) out_3_1 = 2*x**3*y/3 - 2*x*SingularityFunction(y, 10, -2) - 5*SingularityFunction(x, -4, 8)/4 out_3_2 = x**2*y**2 - 10*y*SingularityFunction(x, -4, 7) - 2*SingularityFunction(y, 10, -1) assert integrate(in_3, x) == out_3_1 assert integrate(in_3, y) == out_3_2 assert unchanged(Integral, in_3, (x,)) assert Integral(in_3, x) == Integral(in_3, (x,)) assert Integral(in_3, x).doit() == out_3_1 in_4 = 10*SingularityFunction(x, -4, 7) - 2*SingularityFunction(x, 10, -2) out_4 = 5*SingularityFunction(x, -4, 8)/4 - 2*SingularityFunction(x, 10, -1) assert integrate(in_4, (x, -oo, x)) == out_4 assert integrate(SingularityFunction(x, 5, -1), x) == SingularityFunction(x, 5, 0) assert integrate(SingularityFunction(x, 0, -1), (x, -oo, oo)) == 1 assert integrate(5*SingularityFunction(x, 5, -1), (x, -oo, oo)) == 5 assert integrate(SingularityFunction(x, 5, -1) * f(x), (x, -oo, oo)) == f(5) def test_integrate_DiracDelta(): # This is here to check that deltaintegrate is being called, but also # to test definite integrals. More tests are in test_deltafunctions.py assert integrate(DiracDelta(x) * f(x), (x, -oo, oo)) == f(0) assert integrate(DiracDelta(x)**2, (x, -oo, oo)) == DiracDelta(0) # issue 4522 assert integrate(integrate((4 - 4*x + x*y - 4*y) * \ DiracDelta(x)*DiracDelta(y - 1), (x, 0, 1)), (y, 0, 1)) == 0 # issue 5729 p = exp(-(x**2 + y**2))/pi assert integrate(p*DiracDelta(x - 10*y), (x, -oo, oo), (y, -oo, oo)) == \ integrate(p*DiracDelta(x - 10*y), (y, -oo, oo), (x, -oo, oo)) == \ integrate(p*DiracDelta(10*x - y), (x, -oo, oo), (y, -oo, oo)) == \ integrate(p*DiracDelta(10*x - y), (y, -oo, oo), (x, -oo, oo)) == \ 1/sqrt(101*pi) def test_integrate_returns_piecewise(): assert integrate(x**y, x) == Piecewise( (x**(y + 1)/(y + 1), Ne(y, -1)), (log(x), True)) assert integrate(x**y, y) == Piecewise( (x**y/log(x), Ne(log(x), 0)), (y, True)) assert integrate(exp(n*x), x) == Piecewise( (exp(n*x)/n, Ne(n, 0)), (x, True)) assert integrate(x*exp(n*x), x) == Piecewise( ((n*x - 1)*exp(n*x)/n**2, Ne(n**2, 0)), (x**2/2, True)) assert integrate(x**(n*y), x) == Piecewise( (x**(n*y + 1)/(n*y + 1), Ne(n*y, -1)), (log(x), True)) assert integrate(x**(n*y), y) == Piecewise( (x**(n*y)/(n*log(x)), Ne(n*log(x), 0)), (y, True)) assert integrate(cos(n*x), x) == Piecewise( (sin(n*x)/n, Ne(n, 0)), (x, True)) assert integrate(cos(n*x)**2, x) == Piecewise( ((n*x/2 + sin(n*x)*cos(n*x)/2)/n, Ne(n, 0)), (x, True)) assert integrate(x*cos(n*x), x) == Piecewise( (x*sin(n*x)/n + cos(n*x)/n**2, Ne(n, 0)), (x**2/2, True)) assert integrate(sin(n*x), x) == Piecewise( (-cos(n*x)/n, Ne(n, 0)), (0, True)) assert integrate(sin(n*x)**2, x) == Piecewise( ((n*x/2 - sin(n*x)*cos(n*x)/2)/n, Ne(n, 0)), (0, True)) assert integrate(x*sin(n*x), x) == Piecewise( (-x*cos(n*x)/n + sin(n*x)/n**2, Ne(n, 0)), (0, True)) assert integrate(exp(x*y), (x, 0, z)) == Piecewise( (exp(y*z)/y - 1/y, (y > -oo) & (y < oo) & Ne(y, 0)), (z, True)) def test_integrate_max_min(): x = symbols('x', real=True) assert integrate(Min(x, 2), (x, 0, 3)) == 4 assert integrate(Max(x**2, x**3), (x, 0, 2)) == Rational(49, 12) assert integrate(Min(exp(x), exp(-x))**2, x) == Piecewise( \ (exp(2*x)/2, x <= 0), (1 - exp(-2*x)/2, True)) # issue 7907 c = symbols('c', extended_real=True) int1 = integrate(Max(c, x)*exp(-x**2), (x, -oo, oo)) int2 = integrate(c*exp(-x**2), (x, -oo, c)) int3 = integrate(x*exp(-x**2), (x, c, oo)) assert int1 == int2 + int3 == sqrt(pi)*c*erf(c)/2 + \ sqrt(pi)*c/2 + exp(-c**2)/2 def test_integrate_Abs_sign(): assert integrate(Abs(x), (x, -2, 1)) == Rational(5, 2) assert integrate(Abs(x), (x, 0, 1)) == S.Half assert integrate(Abs(x + 1), (x, 0, 1)) == Rational(3, 2) assert integrate(Abs(x**2 - 1), (x, -2, 2)) == 4 assert integrate(Abs(x**2 - 3*x), (x, -15, 15)) == 2259 assert integrate(sign(x), (x, -1, 2)) == 1 assert integrate(sign(x)*sin(x), (x, -pi, pi)) == 4 assert integrate(sign(x - 2) * x**2, (x, 0, 3)) == Rational(11, 3) t, s = symbols('t s', real=True) assert integrate(Abs(t), t) == Piecewise( (-t**2/2, t <= 0), (t**2/2, True)) assert integrate(Abs(2*t - 6), t) == Piecewise( (-t**2 + 6*t, t <= 3), (t**2 - 6*t + 18, True)) assert (integrate(abs(t - s**2), (t, 0, 2)) == 2*s**2*Min(2, s**2) - 2*s**2 - Min(2, s**2)**2 + 2) assert integrate(exp(-Abs(t)), t) == Piecewise( (exp(t), t <= 0), (2 - exp(-t), True)) assert integrate(sign(2*t - 6), t) == Piecewise( (-t, t < 3), (t - 6, True)) assert integrate(2*t*sign(t**2 - 1), t) == Piecewise( (t**2, t < -1), (-t**2 + 2, t < 1), (t**2, True)) assert integrate(sign(t), (t, s + 1)) == Piecewise( (s + 1, s + 1 > 0), (-s - 1, s + 1 < 0), (0, True)) def test_subs1(): e = Integral(exp(x - y), x) assert e.subs(y, 3) == Integral(exp(x - 3), x) e = Integral(exp(x - y), (x, 0, 1)) assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 1)) f = Lambda(x, exp(-x**2)) conv = Integral(f(x - y)*f(y), (y, -oo, oo)) assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo)) def test_subs2(): e = Integral(exp(x - y), x, t) assert e.subs(y, 3) == Integral(exp(x - 3), x, t) e = Integral(exp(x - y), (x, 0, 1), (t, 0, 1)) assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 1), (t, 0, 1)) f = Lambda(x, exp(-x**2)) conv = Integral(f(x - y)*f(y), (y, -oo, oo), (t, 0, 1)) assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1)) def test_subs3(): e = Integral(exp(x - y), (x, 0, y), (t, y, 1)) assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 3), (t, 3, 1)) f = Lambda(x, exp(-x**2)) conv = Integral(f(x - y)*f(y), (y, -oo, oo), (t, x, 1)) assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1)) def test_subs4(): e = Integral(exp(x), (x, 0, y), (t, y, 1)) assert e.subs(y, 3) == Integral(exp(x), (x, 0, 3), (t, 3, 1)) f = Lambda(x, exp(-x**2)) conv = Integral(f(y)*f(y), (y, -oo, oo), (t, x, 1)) assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1)) def test_subs5(): e = Integral(exp(-x**2), (x, -oo, oo)) assert e.subs(x, 5) == e e = Integral(exp(-x**2 + y), x) assert e.subs(y, 5) == Integral(exp(-x**2 + 5), x) e = Integral(exp(-x**2 + y), (x, x)) assert e.subs(x, 5) == Integral(exp(y - x**2), (x, 5)) assert e.subs(y, 5) == Integral(exp(-x**2 + 5), x) e = Integral(exp(-x**2 + y), (y, -oo, oo), (x, -oo, oo)) assert e.subs(x, 5) == e assert e.subs(y, 5) == e # Test evaluation of antiderivatives e = Integral(exp(-x**2), (x, x)) assert e.subs(x, 5) == Integral(exp(-x**2), (x, 5)) e = Integral(exp(x), x) assert (e.subs(x,1) - e.subs(x,0) - Integral(exp(x), (x, 0, 1)) ).doit().is_zero def test_subs6(): a, b = symbols('a b') e = Integral(x*y, (x, f(x), f(y))) assert e.subs(x, 1) == Integral(x*y, (x, f(1), f(y))) assert e.subs(y, 1) == Integral(x, (x, f(x), f(1))) e = Integral(x*y, (x, f(x), f(y)), (y, f(x), f(y))) assert e.subs(x, 1) == Integral(x*y, (x, f(1), f(y)), (y, f(1), f(y))) assert e.subs(y, 1) == Integral(x*y, (x, f(x), f(y)), (y, f(x), f(1))) e = Integral(x*y, (x, f(x), f(a)), (y, f(x), f(a))) assert e.subs(a, 1) == Integral(x*y, (x, f(x), f(1)), (y, f(x), f(1))) def test_subs7(): e = Integral(x, (x, 1, y), (y, 1, 2)) assert e.subs({x: 1, y: 2}) == e e = Integral(sin(x) + sin(y), (x, sin(x), sin(y)), (y, 1, 2)) assert e.subs(sin(y), 1) == e assert e.subs(sin(x), 1) == Integral(sin(x) + sin(y), (x, 1, sin(y)), (y, 1, 2)) def test_expand(): e = Integral(f(x)+f(x**2), (x, 1, y)) assert e.expand() == Integral(f(x), (x, 1, y)) + Integral(f(x**2), (x, 1, y)) def test_integration_variable(): raises(ValueError, lambda: Integral(exp(-x**2), 3)) raises(ValueError, lambda: Integral(exp(-x**2), (3, -oo, oo))) def test_expand_integral(): assert Integral(cos(x**2)*(sin(x**2) + 1), (x, 0, 1)).expand() == \ Integral(cos(x**2)*sin(x**2), (x, 0, 1)) + \ Integral(cos(x**2), (x, 0, 1)) assert Integral(cos(x**2)*(sin(x**2) + 1), x).expand() == \ Integral(cos(x**2)*sin(x**2), x) + \ Integral(cos(x**2), x) def test_as_sum_midpoint1(): e = Integral(sqrt(x**3 + 1), (x, 2, 10)) assert e.as_sum(1, method="midpoint") == 8*sqrt(217) assert e.as_sum(2, method="midpoint") == 4*sqrt(65) + 12*sqrt(57) assert e.as_sum(3, method="midpoint") == 8*sqrt(217)/3 + \ 8*sqrt(3081)/27 + 8*sqrt(52809)/27 assert e.as_sum(4, method="midpoint") == 2*sqrt(730) + \ 4*sqrt(7) + 4*sqrt(86) + 6*sqrt(14) assert abs(e.as_sum(4, method="midpoint").n() - e.n()) < 0.5 e = Integral(sqrt(x**3 + y**3), (x, 2, 10), (y, 0, 10)) raises(NotImplementedError, lambda: e.as_sum(4)) def test_as_sum_midpoint2(): e = Integral((x + y)**2, (x, 0, 1)) n = Symbol('n', positive=True, integer=True) assert e.as_sum(1, method="midpoint").expand() == Rational(1, 4) + y + y**2 assert e.as_sum(2, method="midpoint").expand() == Rational(5, 16) + y + y**2 assert e.as_sum(3, method="midpoint").expand() == Rational(35, 108) + y + y**2 assert e.as_sum(4, method="midpoint").expand() == Rational(21, 64) + y + y**2 assert e.as_sum(n, method="midpoint").expand() == \ y**2 + y + Rational(1, 3) - 1/(12*n**2) def test_as_sum_left(): e = Integral((x + y)**2, (x, 0, 1)) assert e.as_sum(1, method="left").expand() == y**2 assert e.as_sum(2, method="left").expand() == Rational(1, 8) + y/2 + y**2 assert e.as_sum(3, method="left").expand() == Rational(5, 27) + y*Rational(2, 3) + y**2 assert e.as_sum(4, method="left").expand() == Rational(7, 32) + y*Rational(3, 4) + y**2 assert e.as_sum(n, method="left").expand() == \ y**2 + y + Rational(1, 3) - y/n - 1/(2*n) + 1/(6*n**2) assert e.as_sum(10, method="left", evaluate=False).has(Sum) def test_as_sum_right(): e = Integral((x + y)**2, (x, 0, 1)) assert e.as_sum(1, method="right").expand() == 1 + 2*y + y**2 assert e.as_sum(2, method="right").expand() == Rational(5, 8) + y*Rational(3, 2) + y**2 assert e.as_sum(3, method="right").expand() == Rational(14, 27) + y*Rational(4, 3) + y**2 assert e.as_sum(4, method="right").expand() == Rational(15, 32) + y*Rational(5, 4) + y**2 assert e.as_sum(n, method="right").expand() == \ y**2 + y + Rational(1, 3) + y/n + 1/(2*n) + 1/(6*n**2) def test_as_sum_trapezoid(): e = Integral((x + y)**2, (x, 0, 1)) assert e.as_sum(1, method="trapezoid").expand() == y**2 + y + S.Half assert e.as_sum(2, method="trapezoid").expand() == y**2 + y + Rational(3, 8) assert e.as_sum(3, method="trapezoid").expand() == y**2 + y + Rational(19, 54) assert e.as_sum(4, method="trapezoid").expand() == y**2 + y + Rational(11, 32) assert e.as_sum(n, method="trapezoid").expand() == \ y**2 + y + Rational(1, 3) + 1/(6*n**2) assert Integral(sign(x), (x, 0, 1)).as_sum(1, 'trapezoid') == S.Half def test_as_sum_raises(): e = Integral((x + y)**2, (x, 0, 1)) raises(ValueError, lambda: e.as_sum(-1)) raises(ValueError, lambda: e.as_sum(0)) raises(ValueError, lambda: Integral(x).as_sum(3)) raises(ValueError, lambda: e.as_sum(oo)) raises(ValueError, lambda: e.as_sum(3, method='xxxx2')) def test_nested_doit(): e = Integral(Integral(x, x), x) f = Integral(x, x, x) assert e.doit() == f.doit() def test_issue_4665(): # Allow only upper or lower limit evaluation e = Integral(x**2, (x, None, 1)) f = Integral(x**2, (x, 1, None)) assert e.doit() == Rational(1, 3) assert f.doit() == Rational(-1, 3) assert Integral(x*y, (x, None, y)).subs(y, t) == Integral(x*t, (x, None, t)) assert Integral(x*y, (x, y, None)).subs(y, t) == Integral(x*t, (x, t, None)) assert integrate(x**2, (x, None, 1)) == Rational(1, 3) assert integrate(x**2, (x, 1, None)) == Rational(-1, 3) assert integrate("x**2", ("x", "1", None)) == Rational(-1, 3) def test_integral_reconstruct(): e = Integral(x**2, (x, -1, 1)) assert e == Integral(*e.args) def test_doit_integrals(): e = Integral(Integral(2*x), (x, 0, 1)) assert e.doit() == Rational(1, 3) assert e.doit(deep=False) == Rational(1, 3) f = Function('f') # doesn't matter if the integral can't be performed assert Integral(f(x), (x, 1, 1)).doit() == 0 # doesn't matter if the limits can't be evaluated assert Integral(0, (x, 1, Integral(f(x), x))).doit() == 0 assert Integral(x, (a, 0)).doit() == 0 limits = ((a, 1, exp(x)), (x, 0)) assert Integral(a, *limits).doit() == Rational(1, 4) assert Integral(a, *list(reversed(limits))).doit() == 0 def test_issue_4884(): assert integrate(sqrt(x)*(1 + x)) == \ Piecewise( (2*sqrt(x)*(x + 1)**2/5 - 2*sqrt(x)*(x + 1)/15 - 4*sqrt(x)/15, Abs(x + 1) > 1), (2*I*sqrt(-x)*(x + 1)**2/5 - 2*I*sqrt(-x)*(x + 1)/15 - 4*I*sqrt(-x)/15, True)) assert integrate(x**x*(1 + log(x))) == x**x def test_issue_18153(): assert integrate(x**n*log(x),x) == \ Piecewise( (n*x*x**n*log(x)/(n**2 + 2*n + 1) + x*x**n*log(x)/(n**2 + 2*n + 1) - x*x**n/(n**2 + 2*n + 1) , Ne(n, -1)), (log(x)**2/2, True) ) def test_is_number(): from sympy.abc import x, y, z from sympy import cos, sin assert Integral(x).is_number is False assert Integral(1, x).is_number is False assert Integral(1, (x, 1)).is_number is True assert Integral(1, (x, 1, 2)).is_number is True assert Integral(1, (x, 1, y)).is_number is False assert Integral(1, (x, y)).is_number is False assert Integral(x, y).is_number is False assert Integral(x, (y, 1, x)).is_number is False assert Integral(x, (y, 1, 2)).is_number is False assert Integral(x, (x, 1, 2)).is_number is True # `foo.is_number` should always be equivalent to `not foo.free_symbols` # in each of these cases, there are pseudo-free symbols i = Integral(x, (y, 1, 1)) assert i.is_number is False and i.n() == 0 i = Integral(x, (y, z, z)) assert i.is_number is False and i.n() == 0 i = Integral(1, (y, z, z + 2)) assert i.is_number is False and i.n() == 2 assert Integral(x*y, (x, 1, 2), (y, 1, 3)).is_number is True assert Integral(x*y, (x, 1, 2), (y, 1, z)).is_number is False assert Integral(x, (x, 1)).is_number is True assert Integral(x, (x, 1, Integral(y, (y, 1, 2)))).is_number is True assert Integral(Sum(z, (z, 1, 2)), (x, 1, 2)).is_number is True # it is possible to get a false negative if the integrand is # actually an unsimplified zero, but this is true of is_number in general. assert Integral(sin(x)**2 + cos(x)**2 - 1, x).is_number is False assert Integral(f(x), (x, 0, 1)).is_number is True def test_symbols(): from sympy.abc import x, y, z assert Integral(0, x).free_symbols == {x} assert Integral(x).free_symbols == {x} assert Integral(x, (x, None, y)).free_symbols == {y} assert Integral(x, (x, y, None)).free_symbols == {y} assert Integral(x, (x, 1, y)).free_symbols == {y} assert Integral(x, (x, y, 1)).free_symbols == {y} assert Integral(x, (x, x, y)).free_symbols == {x, y} assert Integral(x, x, y).free_symbols == {x, y} assert Integral(x, (x, 1, 2)).free_symbols == set() assert Integral(x, (y, 1, 2)).free_symbols == {x} # pseudo-free in this case assert Integral(x, (y, z, z)).free_symbols == {x, z} assert Integral(x, (y, 1, 2), (y, None, None)).free_symbols == {x, y} assert Integral(x, (y, 1, 2), (x, 1, y)).free_symbols == {y} assert Integral(2, (y, 1, 2), (y, 1, x), (x, 1, 2)).free_symbols == set() assert Integral(2, (y, x, 2), (y, 1, x), (x, 1, 2)).free_symbols == set() assert Integral(2, (x, 1, 2), (y, x, 2), (y, 1, 2)).free_symbols == \ {x} def test_is_zero(): from sympy.abc import x, m assert Integral(0, (x, 1, x)).is_zero assert Integral(1, (x, 1, 1)).is_zero assert Integral(1, (x, 1, 2), (y, 2)).is_zero is False assert Integral(x, (m, 0)).is_zero assert Integral(x + m, (m, 0)).is_zero is None i = Integral(m, (m, 1, exp(x)), (x, 0)) assert i.is_zero is None assert Integral(m, (x, 0), (m, 1, exp(x))).is_zero is True assert Integral(x, (x, oo, oo)).is_zero # issue 8171 assert Integral(x, (x, -oo, -oo)).is_zero # this is zero but is beyond the scope of what is_zero # should be doing assert Integral(sin(x), (x, 0, 2*pi)).is_zero is None def test_series(): from sympy.abc import x i = Integral(cos(x), (x, x)) e = i.lseries(x) assert i.nseries(x, n=8).removeO() == Add(*[next(e) for j in range(4)]) def test_trig_nonelementary_integrals(): x = Symbol('x') assert integrate((1 + sin(x))/x, x) == log(x) + Si(x) # next one comes out as log(x) + log(x**2)/2 + Ci(x) # so not hardcoding this log ugliness assert integrate((cos(x) + 2)/x, x).has(Ci) def test_issue_4403(): x = Symbol('x') y = Symbol('y') z = Symbol('z', positive=True) assert integrate(sqrt(x**2 + z**2), x) == \ z**2*asinh(x/z)/2 + x*sqrt(x**2 + z**2)/2 assert integrate(sqrt(x**2 - z**2), x) == \ -z**2*acosh(x/z)/2 + x*sqrt(x**2 - z**2)/2 x = Symbol('x', real=True) y = Symbol('y', positive=True) assert integrate(1/(x**2 + y**2)**S('3/2'), x) == \ x/(y**2*sqrt(x**2 + y**2)) # If y is real and nonzero, we get x*Abs(y)/(y**3*sqrt(x**2 + y**2)), # which results from sqrt(1 + x**2/y**2) = sqrt(x**2 + y**2)/|y|. def test_issue_4403_2(): assert integrate(sqrt(-x**2 - 4), x) == \ -2*atan(x/sqrt(-4 - x**2)) + x*sqrt(-4 - x**2)/2 def test_issue_4100(): R = Symbol('R', positive=True) assert integrate(sqrt(R**2 - x**2), (x, 0, R)) == pi*R**2/4 def test_issue_5167(): from sympy.abc import w, x, y, z f = Function('f') assert Integral(Integral(f(x), x), x) == Integral(f(x), x, x) assert Integral(f(x)).args == (f(x), Tuple(x)) assert Integral(Integral(f(x))).args == (f(x), Tuple(x), Tuple(x)) assert Integral(Integral(f(x)), y).args == (f(x), Tuple(x), Tuple(y)) assert Integral(Integral(f(x), z), y).args == (f(x), Tuple(z), Tuple(y)) assert Integral(Integral(Integral(f(x), x), y), z).args == \ (f(x), Tuple(x), Tuple(y), Tuple(z)) assert integrate(Integral(f(x), x), x) == Integral(f(x), x, x) assert integrate(Integral(f(x), y), x) == y*Integral(f(x), x) assert integrate(Integral(f(x), x), y) in [Integral(y*f(x), x), y*Integral(f(x), x)] assert integrate(Integral(2, x), x) == x**2 assert integrate(Integral(2, x), y) == 2*x*y # don't re-order given limits assert Integral(1, x, y).args != Integral(1, y, x).args # do as many as possible assert Integral(f(x), y, x, y, x).doit() == y**2*Integral(f(x), x, x)/2 assert Integral(f(x), (x, 1, 2), (w, 1, x), (z, 1, y)).doit() == \ y*(x - 1)*Integral(f(x), (x, 1, 2)) - (x - 1)*Integral(f(x), (x, 1, 2)) def test_issue_4890(): z = Symbol('z', positive=True) assert integrate(exp(-log(x)**2), x) == \ sqrt(pi)*exp(Rational(1, 4))*erf(log(x) - S.Half)/2 assert integrate(exp(log(x)**2), x) == \ sqrt(pi)*exp(Rational(-1, 4))*erfi(log(x)+S.Half)/2 assert integrate(exp(-z*log(x)**2), x) == \ sqrt(pi)*exp(1/(4*z))*erf(sqrt(z)*log(x) - 1/(2*sqrt(z)))/(2*sqrt(z)) def test_issue_4551(): assert not integrate(1/(x*sqrt(1 - x**2)), x).has(Integral) def test_issue_4376(): n = Symbol('n', integer=True, positive=True) assert simplify(integrate(n*(x**(1/n) - 1), (x, 0, S.Half)) - (n**2 - 2**(1/n)*n**2 - n*2**(1/n))/(2**(1 + 1/n) + n*2**(1 + 1/n))) == 0 def test_issue_4517(): assert integrate((sqrt(x) - x**3)/x**Rational(1, 3), x) == \ 6*x**Rational(7, 6)/7 - 3*x**Rational(11, 3)/11 def test_issue_4527(): k, m = symbols('k m', integer=True) assert integrate(sin(k*x)*sin(m*x), (x, 0, pi)).simplify() == \ Piecewise((0, Eq(k, 0) | Eq(m, 0)), (-pi/2, Eq(k, -m) | (Eq(k, 0) & Eq(m, 0))), (pi/2, Eq(k, m) | (Eq(k, 0) & Eq(m, 0))), (0, True)) # Should be possible to further simplify to: # Piecewise( # (0, Eq(k, 0) | Eq(m, 0)), # (-pi/2, Eq(k, -m)), # (pi/2, Eq(k, m)), # (0, True)) assert integrate(sin(k*x)*sin(m*x), (x,)) == Piecewise( (0, And(Eq(k, 0), Eq(m, 0))), (-x*sin(m*x)**2/2 - x*cos(m*x)**2/2 + sin(m*x)*cos(m*x)/(2*m), Eq(k, -m)), (x*sin(m*x)**2/2 + x*cos(m*x)**2/2 - sin(m*x)*cos(m*x)/(2*m), Eq(k, m)), (m*sin(k*x)*cos(m*x)/(k**2 - m**2) - k*sin(m*x)*cos(k*x)/(k**2 - m**2), True)) def test_issue_4199(): ypos = Symbol('y', positive=True) # TODO: Remove conds='none' below, let the assumption take care of it. assert integrate(exp(-I*2*pi*ypos*x)*x, (x, -oo, oo), conds='none') == \ Integral(exp(-I*2*pi*ypos*x)*x, (x, -oo, oo)) def test_issue_3940(): a, b, c, d = symbols('a:d', positive=True, finite=True) assert integrate(exp(-x**2 + I*c*x), x) == \ -sqrt(pi)*exp(-c**2/4)*erf(I*c/2 - x)/2 assert integrate(exp(a*x**2 + b*x + c), x) == \ sqrt(pi)*exp(c)*exp(-b**2/(4*a))*erfi(sqrt(a)*x + b/(2*sqrt(a)))/(2*sqrt(a)) from sympy import expand_mul from sympy.abc import k assert expand_mul(integrate(exp(-x**2)*exp(I*k*x), (x, -oo, oo))) == \ sqrt(pi)*exp(-k**2/4) a, d = symbols('a d', positive=True) assert expand_mul(integrate(exp(-a*x**2 + 2*d*x), (x, -oo, oo))) == \ sqrt(pi)*exp(d**2/a)/sqrt(a) def test_issue_5413(): # Note that this is not the same as testing ratint() because integrate() # pulls out the coefficient. assert integrate(-a/(a**2 + x**2), x) == I*log(-I*a + x)/2 - I*log(I*a + x)/2 def test_issue_4892a(): A, z = symbols('A z') c = Symbol('c', nonzero=True) P1 = -A*exp(-z) P2 = -A/(c*t)*(sin(x)**2 + cos(y)**2) h1 = -sin(x)**2 - cos(y)**2 h2 = -sin(x)**2 + sin(y)**2 - 1 # there is still some non-deterministic behavior in integrate # or trigsimp which permits one of the following assert integrate(c*(P2 - P1), t) in [ c*(-A*(-h1)*log(c*t)/c + A*t*exp(-z)), c*(-A*(-h2)*log(c*t)/c + A*t*exp(-z)), c*( A* h1 *log(c*t)/c + A*t*exp(-z)), c*( A* h2 *log(c*t)/c + A*t*exp(-z)), (A*c*t - A*(-h1)*log(t)*exp(z))*exp(-z), (A*c*t - A*(-h2)*log(t)*exp(z))*exp(-z), ] def test_issue_4892b(): # Issues relating to issue 4596 are making the actual result of this hard # to test. The answer should be something like # # (-sin(y) + sqrt(-72 + 48*cos(y) - 8*cos(y)**2)/2)*log(x + sqrt(-72 + # 48*cos(y) - 8*cos(y)**2)/(2*(3 - cos(y)))) + (-sin(y) - sqrt(-72 + # 48*cos(y) - 8*cos(y)**2)/2)*log(x - sqrt(-72 + 48*cos(y) - # 8*cos(y)**2)/(2*(3 - cos(y)))) + x**2*sin(y)/2 + 2*x*cos(y) expr = (sin(y)*x**3 + 2*cos(y)*x**2 + 12)/(x**2 + 2) assert trigsimp(factor(integrate(expr, x).diff(x) - expr)) == 0 def test_issue_5178(): assert integrate(sin(x)*f(y, z), (x, 0, pi), (y, 0, pi), (z, 0, pi)) == \ 2*Integral(f(y, z), (y, 0, pi), (z, 0, pi)) def test_integrate_series(): f = sin(x).series(x, 0, 10) g = x**2/2 - x**4/24 + x**6/720 - x**8/40320 + x**10/3628800 + O(x**11) assert integrate(f, x) == g assert diff(integrate(f, x), x) == f assert integrate(O(x**5), x) == O(x**6) def test_atom_bug(): from sympy import meijerg from sympy.integrals.heurisch import heurisch assert heurisch(meijerg([], [], [1], [], x), x) is None def test_limit_bug(): z = Symbol('z', zero=False) assert integrate(sin(x*y*z), (x, 0, pi), (y, 0, pi)).together() == \ (log(z) - Ci(pi**2*z) + EulerGamma + 2*log(pi))/z def test_issue_4703(): g = Function('g') assert integrate(exp(x)*g(x), x).has(Integral) def test_issue_1888(): f = Function('f') assert integrate(f(x).diff(x)**2, x).has(Integral) # The following tests work using meijerint. def test_issue_3558(): from sympy import Si assert integrate(cos(x*y), (x, -pi/2, pi/2), (y, 0, pi)) == 2*Si(pi**2/2) def test_issue_4422(): assert integrate(1/sqrt(16 + 4*x**2), x) == asinh(x/2) / 2 def test_issue_4493(): from sympy import simplify assert simplify(integrate(x*sqrt(1 + 2*x), x)) == \ sqrt(2*x + 1)*(6*x**2 + x - 1)/15 def test_issue_4737(): assert integrate(sin(x)/x, (x, -oo, oo)) == pi assert integrate(sin(x)/x, (x, 0, oo)) == pi/2 assert integrate(sin(x)/x, x) == Si(x) def test_issue_4992(): # Note: psi in _check_antecedents becomes NaN. from sympy import simplify, expand_func, polygamma, gamma a = Symbol('a', positive=True) assert simplify(expand_func(integrate(exp(-x)*log(x)*x**a, (x, 0, oo)))) == \ (a*polygamma(0, a) + 1)*gamma(a) def test_issue_4487(): from sympy import lowergamma, simplify assert simplify(integrate(exp(-x)*x**y, x)) == lowergamma(y + 1, x) def test_issue_4215(): x = Symbol("x") assert integrate(1/(x**2), (x, -1, 1)) is oo def test_issue_4400(): n = Symbol('n', integer=True, positive=True) assert integrate((x**n)*log(x), x) == \ n*x*x**n*log(x)/(n**2 + 2*n + 1) + x*x**n*log(x)/(n**2 + 2*n + 1) - \ x*x**n/(n**2 + 2*n + 1) def test_issue_6253(): # Note: this used to raise NotImplementedError # Note: psi in _check_antecedents becomes NaN. assert integrate((sqrt(1 - x) + sqrt(1 + x))**2/x, x, meijerg=True) == \ Integral((sqrt(-x + 1) + sqrt(x + 1))**2/x, x) def test_issue_4153(): assert integrate(1/(1 + x + y + z), (x, 0, 1), (y, 0, 1), (z, 0, 1)) in [ -12*log(3) - 3*log(6)/2 + 3*log(8)/2 + 5*log(2) + 7*log(4), 6*log(2) + 8*log(4) - 27*log(3)/2, 22*log(2) - 27*log(3)/2, -12*log(3) - 3*log(6)/2 + 47*log(2)/2] def test_issue_4326(): R, b, h = symbols('R b h') # It doesn't matter if we can do the integral. Just make sure the result # doesn't contain nan. This is really a test against _eval_interval. e = integrate(((h*(x - R + b))/b)*sqrt(R**2 - x**2), (x, R - b, R)) assert not e.has(nan) # See that it evaluates assert not e.has(Integral) def test_powers(): assert integrate(2**x + 3**x, x) == 2**x/log(2) + 3**x/log(3) def test_manual_option(): raises(ValueError, lambda: integrate(1/x, x, manual=True, meijerg=True)) # an example of a function that manual integration cannot handle assert integrate(log(1+x)/x, (x, 0, 1), manual=True).has(Integral) def test_meijerg_option(): raises(ValueError, lambda: integrate(1/x, x, meijerg=True, risch=True)) # an example of a function that meijerg integration cannot handle assert integrate(tan(x), x, meijerg=True) == Integral(tan(x), x) def test_risch_option(): # risch=True only allowed on indefinite integrals raises(ValueError, lambda: integrate(1/log(x), (x, 0, oo), risch=True)) assert integrate(exp(-x**2), x, risch=True) == NonElementaryIntegral(exp(-x**2), x) assert integrate(log(1/x)*y, x, y, risch=True) == y**2*(x*log(1/x)/2 + x/2) assert integrate(erf(x), x, risch=True) == Integral(erf(x), x) # TODO: How to test risch=False? @slow def test_heurisch_option(): raises(ValueError, lambda: integrate(1/x, x, risch=True, heurisch=True)) # an integral that heurisch can handle assert integrate(exp(x**2), x, heurisch=True) == sqrt(pi)*erfi(x)/2 # an integral that heurisch currently cannot handle assert integrate(exp(x)/x, x, heurisch=True) == Integral(exp(x)/x, x) # an integral where heurisch currently hangs, issue 15471 assert integrate(log(x)*cos(log(x))/x**Rational(3, 4), x, heurisch=False) == ( -128*x**Rational(1, 4)*sin(log(x))/289 + 240*x**Rational(1, 4)*cos(log(x))/289 + (16*x**Rational(1, 4)*sin(log(x))/17 + 4*x**Rational(1, 4)*cos(log(x))/17)*log(x)) def test_issue_6828(): f = 1/(1.08*x**2 - 4.3) g = integrate(f, x).diff(x) assert verify_numerically(f, g, tol=1e-12) def test_issue_4803(): x_max = Symbol("x_max") assert integrate(y/pi*exp(-(x_max - x)/cos(a)), x) == \ y*exp((x - x_max)/cos(a))*cos(a)/pi def test_issue_4234(): assert integrate(1/sqrt(1 + tan(x)**2)) == tan(x)/sqrt(1 + tan(x)**2) def test_issue_4492(): assert simplify(integrate(x**2 * sqrt(5 - x**2), x)) == Piecewise( (I*(2*x**5 - 15*x**3 + 25*x - 25*sqrt(x**2 - 5)*acosh(sqrt(5)*x/5)) / (8*sqrt(x**2 - 5)), 1 < Abs(x**2)/5), ((-2*x**5 + 15*x**3 - 25*x + 25*sqrt(-x**2 + 5)*asin(sqrt(5)*x/5)) / (8*sqrt(-x**2 + 5)), True)) def test_issue_2708(): # This test needs to use an integration function that can # not be evaluated in closed form. Update as needed. f = 1/(a + z + log(z)) integral_f = NonElementaryIntegral(f, (z, 2, 3)) assert Integral(f, (z, 2, 3)).doit() == integral_f assert integrate(f + exp(z), (z, 2, 3)) == integral_f - exp(2) + exp(3) assert integrate(2*f + exp(z), (z, 2, 3)) == \ 2*integral_f - exp(2) + exp(3) assert integrate(exp(1.2*n*s*z*(-t + z)/t), (z, 0, x)) == \ NonElementaryIntegral(exp(-1.2*n*s*z)*exp(1.2*n*s*z**2/t), (z, 0, x)) def test_issue_2884(): f = (4.000002016020*x + 4.000002016020*y + 4.000006024032)*exp(10.0*x) e = integrate(f, (x, 0.1, 0.2)) assert str(e) == '1.86831064982608*y + 2.16387491480008' def test_issue_8368(): assert integrate(exp(-s*x)*cosh(x), (x, 0, oo)) == \ Piecewise( ( pi*Piecewise( ( -s/(pi*(-s**2 + 1)), Abs(s**2) < 1), ( 1/(pi*s*(1 - 1/s**2)), Abs(s**(-2)) < 1), ( meijerg( ((S.Half,), (0, 0)), ((0, S.Half), (0,)), polar_lift(s)**2), True) ), And( Abs(periodic_argument(polar_lift(s)**2, oo)) < pi, cos(Abs(periodic_argument(polar_lift(s)**2, oo))/2)*sqrt(Abs(s**2)) - 1 > 0, Ne(s**2, 1)) ), ( Integral(exp(-s*x)*cosh(x), (x, 0, oo)), True)) assert integrate(exp(-s*x)*sinh(x), (x, 0, oo)) == \ Piecewise( ( -1/(s + 1)/2 - 1/(-s + 1)/2, And( Ne(1/s, 1), Abs(periodic_argument(s, oo)) < pi/2, Abs(periodic_argument(s, oo)) <= pi/2, cos(Abs(periodic_argument(s, oo)))*Abs(s) - 1 > 0)), ( Integral(exp(-s*x)*sinh(x), (x, 0, oo)), True)) def test_issue_8901(): assert integrate(sinh(1.0*x)) == 1.0*cosh(1.0*x) assert integrate(tanh(1.0*x)) == 1.0*x - 1.0*log(tanh(1.0*x) + 1) assert integrate(tanh(x)) == x - log(tanh(x) + 1) @slow def test_issue_8945(): assert integrate(sin(x)**3/x, (x, 0, 1)) == -Si(3)/4 + 3*Si(1)/4 assert integrate(sin(x)**3/x, (x, 0, oo)) == pi/4 assert integrate(cos(x)**2/x**2, x) == -Si(2*x) - cos(2*x)/(2*x) - 1/(2*x) @slow def test_issue_7130(): if ON_TRAVIS: skip("Too slow for travis.") i, L, a, b = symbols('i L a b') integrand = (cos(pi*i*x/L)**2 / (a + b*x)).rewrite(exp) assert x not in integrate(integrand, (x, 0, L)).free_symbols def test_issue_10567(): a, b, c, t = symbols('a b c t') vt = Matrix([a*t, b, c]) assert integrate(vt, t) == Integral(vt, t).doit() assert integrate(vt, t) == Matrix([[a*t**2/2], [b*t], [c*t]]) def test_issue_11856(): t = symbols('t') assert integrate(sinc(pi*t), t) == Si(pi*t)/pi @slow def test_issue_11876(): assert integrate(sqrt(log(1/x)), (x, 0, 1)) == sqrt(pi)/2 def test_issue_4950(): assert integrate((-60*exp(x) - 19.2*exp(4*x))*exp(4*x), x) ==\ -2.4*exp(8*x) - 12.0*exp(5*x) def test_issue_4968(): assert integrate(sin(log(x**2))) == x*sin(log(x**2))/5 - 2*x*cos(log(x**2))/5 def test_singularities(): assert integrate(1/x**2, (x, -oo, oo)) is oo assert integrate(1/x**2, (x, -1, 1)) is oo assert integrate(1/(x - 1)**2, (x, -2, 2)) is oo assert integrate(1/x**2, (x, 1, -1)) is -oo assert integrate(1/(x - 1)**2, (x, 2, -2)) is -oo def test_issue_12645(): x, y = symbols('x y', real=True) assert (integrate(sin(x*x*x + y*y), (x, -sqrt(pi - y*y), sqrt(pi - y*y)), (y, -sqrt(pi), sqrt(pi))) == Integral(sin(x**3 + y**2), (x, -sqrt(-y**2 + pi), sqrt(-y**2 + pi)), (y, -sqrt(pi), sqrt(pi)))) def test_issue_12677(): assert integrate(sin(x) / (cos(x)**3) , (x, 0, pi/6)) == Rational(1,6) def test_issue_14078(): assert integrate((cos(3*x)-cos(x))/x, (x, 0, oo)) == -log(3) def test_issue_14064(): assert integrate(1/cosh(x), (x, 0, oo)) == pi/2 def test_issue_14027(): assert integrate(1/(1 + exp(x - S.Half)/(1 + exp(x))), x) == \ x - exp(S.Half)*log(exp(x) + exp(S.Half)/(1 + exp(S.Half)))/(exp(S.Half) + E) def test_issue_8170(): assert integrate(tan(x), (x, 0, pi/2)) is S.Infinity def test_issue_8440_14040(): assert integrate(1/x, (x, -1, 1)) is S.NaN assert integrate(1/(x + 1), (x, -2, 3)) is S.NaN def test_issue_14096(): assert integrate(1/(x + y)**2, (x, 0, 1)) == -1/(y + 1) + 1/y assert integrate(1/(1 + x + y + z)**2, (x, 0, 1), (y, 0, 1), (z, 0, 1)) == \ -4*log(4) - 6*log(2) + 9*log(3) def test_issue_14144(): assert Abs(integrate(1/sqrt(1 - x**3), (x, 0, 1)).n() - 1.402182) < 1e-6 assert Abs(integrate(sqrt(1 - x**3), (x, 0, 1)).n() - 0.841309) < 1e-6 def test_issue_14375(): # This raised a TypeError. The antiderivative has exp_polar, which # may be possible to unpolarify, so the exact output is not asserted here. assert integrate(exp(I*x)*log(x), x).has(Ei) def test_issue_14437(): f = Function('f')(x, y, z) assert integrate(f, (x, 0, 1), (y, 0, 2), (z, 0, 3)) == \ Integral(f, (x, 0, 1), (y, 0, 2), (z, 0, 3)) def test_issue_14470(): assert integrate(1/sqrt(exp(x) + 1), x) == \ log(-1 + 1/sqrt(exp(x) + 1)) - log(1 + 1/sqrt(exp(x) + 1)) def test_issue_14877(): f = exp(1 - exp(x**2)*x + 2*x**2)*(2*x**3 + x)/(1 - exp(x**2)*x)**2 assert integrate(f, x) == \ -exp(2*x**2 - x*exp(x**2) + 1)/(x*exp(3*x**2) - exp(2*x**2)) def test_issue_14782(): f = sqrt(-x**2 + 1)*(-x**2 + x) assert integrate(f, [x, -1, 1]) == - pi / 8 @slow def test_issue_14782_slow(): f = sqrt(-x**2 + 1)*(-x**2 + x) assert integrate(f, [x, 0, 1]) == S.One / 3 - pi / 16 def test_issue_12081(): f = x**(Rational(-3, 2))*exp(-x) assert integrate(f, [x, 0, oo]) is oo def test_issue_15285(): y = 1/x - 1 f = 4*y*exp(-2*y)/x**2 assert integrate(f, [x, 0, 1]) == 1 def test_issue_15432(): assert integrate(x**n * exp(-x) * log(x), (x, 0, oo)).gammasimp() == Piecewise( (gamma(n + 1)*polygamma(0, n) + gamma(n + 1)/n, re(n) + 1 > 0), (Integral(x**n*exp(-x)*log(x), (x, 0, oo)), True)) def test_issue_15124(): omega = IndexedBase('omega') m, p = symbols('m p', cls=Idx) assert integrate(exp(x*I*(omega[m] + omega[p])), x, conds='none') == \ -I*exp(I*x*omega[m])*exp(I*x*omega[p])/(omega[m] + omega[p]) def test_issue_15218(): with warns_deprecated_sympy(): Integral(Eq(x, y)) with warns_deprecated_sympy(): assert Integral(Eq(x, y), x) == Eq(Integral(x, x), Integral(y, x)) with warns_deprecated_sympy(): assert Integral(Eq(x, y), x).doit() == Eq(x**2/2, x*y) with warns_deprecated_sympy(): assert Eq(x, y).integrate(x) == Eq(x**2/2, x*y) # These are not deprecated because they are definite integrals assert integrate(Eq(x, y), (x, 0, 1)) == Eq(S.Half, y) assert Eq(x, y).integrate((x, 0, 1)) == Eq(S.Half, y) def test_issue_15292(): res = integrate(exp(-x**2*cos(2*t)) * cos(x**2*sin(2*t)), (x, 0, oo)) assert isinstance(res, Piecewise) assert gammasimp((res - sqrt(pi)/2 * cos(t)).subs(t, pi/6)) == 0 def test_issue_4514(): assert integrate(sin(2*x)/sin(x), x) == 2*sin(x) def test_issue_15457(): x, a, b = symbols('x a b', real=True) definite = integrate(exp(Abs(x-2)), (x, a, b)) indefinite = integrate(exp(Abs(x-2)), x) assert definite.subs({a: 1, b: 3}) == -2 + 2*E assert indefinite.subs(x, 3) - indefinite.subs(x, 1) == -2 + 2*E assert definite.subs({a: -3, b: -1}) == -exp(3) + exp(5) assert indefinite.subs(x, -1) - indefinite.subs(x, -3) == -exp(3) + exp(5) def test_issue_15431(): assert integrate(x*exp(x)*log(x), x) == \ (x*exp(x) - exp(x))*log(x) - exp(x) + Ei(x) def test_issue_15640_log_substitutions(): f = x/log(x) F = Ei(2*log(x)) assert integrate(f, x) == F and F.diff(x) == f f = x**3/log(x)**2 F = -x**4/log(x) + 4*Ei(4*log(x)) assert integrate(f, x) == F and F.diff(x) == f f = sqrt(log(x))/x**2 F = -sqrt(pi)*erfc(sqrt(log(x)))/2 - sqrt(log(x))/x assert integrate(f, x) == F and F.diff(x) == f def test_issue_15509(): from sympy.vector import CoordSys3D N = CoordSys3D('N') x = N.x assert integrate(cos(a*x + b), (x, x_1, x_2), heurisch=True) == Piecewise( (-sin(a*x_1 + b)/a + sin(a*x_2 + b)/a, (a > -oo) & (a < oo) & Ne(a, 0)), \ (-x_1*cos(b) + x_2*cos(b), True)) def test_issue_4311_fast(): x = symbols('x', real=True) assert integrate(x*abs(9-x**2), x) == Piecewise( (x**4/4 - 9*x**2/2, x <= -3), (-x**4/4 + 9*x**2/2 - Rational(81, 2), x <= 3), (x**4/4 - 9*x**2/2, True)) def test_integrate_with_complex_constants(): K = Symbol('K', real=True, positive=True) x = Symbol('x', real=True) m = Symbol('m', real=True) t = Symbol('t', real=True) assert integrate(exp(-I*K*x**2+m*x), x) == sqrt(I)*sqrt(pi)*exp(-I*m**2 /(4*K))*erfi((-2*I*K*x + m)/(2*sqrt(K)*sqrt(-I)))/(2*sqrt(K)) assert integrate(1/(1 + I*x**2), x) == (-I*(sqrt(-I)*log(x - I*sqrt(-I))/2 - sqrt(-I)*log(x + I*sqrt(-I))/2)) assert integrate(exp(-I*x**2), x) == sqrt(pi)*erf(sqrt(I)*x)/(2*sqrt(I)) assert integrate((1/(exp(I*t)-2)), t) == -t/2 - I*log(exp(I*t) - 2)/2 assert integrate((1/(exp(I*t)-2)), (t, 0, 2*pi)) == -pi def test_issue_14241(): x = Symbol('x') n = Symbol('n', positive=True, integer=True) assert integrate(n * x ** (n - 1) / (x + 1), x) == \ n**2*x**n*lerchphi(x*exp_polar(I*pi), 1, n)*gamma(n)/gamma(n + 1) def test_issue_13112(): assert integrate(sin(t)**2 / (5 - 4*cos(t)), [t, 0, 2*pi]) == pi / 4 @slow def test_issue_14709b(): h = Symbol('h', positive=True) i = integrate(x*acos(1 - 2*x/h), (x, 0, h)) assert i == 5*h**2*pi/16 def test_issue_8614(): x = Symbol('x') t = Symbol('t') assert integrate(exp(t)/t, (t, -oo, x)) == Ei(x) assert integrate((exp(-x) - exp(-2*x))/x, (x, 0, oo)) == log(2) @slow def test_issue_15494(): s = symbols('s', real=True, positive=True) integrand = (exp(s/2) - 2*exp(1.6*s) + exp(s))*exp(s) solution = integrate(integrand, s) assert solution != S.NaN # Not sure how to test this properly as it is a symbolic expression with floats # assert str(solution) == '0.666666666666667*exp(1.5*s) + 0.5*exp(2.0*s) - 0.769230769230769*exp(2.6*s)' # Maybe assert abs(solution.subs(s, 1) - (-3.67440080236188)) <= 1e-8 integrand = (exp(s/2) - 2*exp(S(8)/5*s) + exp(s))*exp(s) assert integrate(integrand, s) == -10*exp(13*s/5)/13 + 2*exp(3*s/2)/3 + exp(2*s)/2 def test_li_integral(): y = Symbol('y') assert Integral(li(y*x**2), x).doit() == Piecewise((x*li(x**2*y) - \ x*Ei(3*log(x**2*y)/2)/sqrt(x**2*y), Ne(y, 0)), (0, True)) def test_issue_17473(): x = Symbol('x') n = Symbol('n') assert integrate(sin(x**n), x) == \ x*x**n*gamma(S(1)/2 + 1/(2*n))*hyper((S(1)/2 + 1/(2*n),), (S(3)/2, S(3)/2 + 1/(2*n)), -x**(2*n)/4)/(2*n*gamma(S(3)/2 + 1/(2*n))) def test_issue_17671(): assert integrate(log(log(x)) / x**2, [x, 1, oo]) == -EulerGamma assert integrate(log(log(x)) / x**3, [x, 1, oo]) == -log(2)/2 - EulerGamma/2 assert integrate(log(log(x)) / x**10, [x, 1, oo]) == -2*log(3)/9 - EulerGamma/9 def test_issue_2975(): w = Symbol('w') C = Symbol('C') y = Symbol('y') assert integrate(1/(y**2+C)**(S(3)/2), (y, -w/2, w/2)) == w/(C**(S(3)/2)*sqrt(1 + w**2/(4*C))) def test_issue_7827(): x, n, M = symbols('x n M') N = Symbol('N', integer=True) assert integrate(summation(x*n, (n, 1, N)), x) == x**2*(N**2/4 + N/4) assert integrate(summation(x*sin(n), (n,1,N)), x) == \ Sum(x**2*sin(n)/2, (n, 1, N)) assert integrate(summation(sin(n*x), (n,1,N)), x) == \ Sum(Piecewise((-cos(n*x)/n, Ne(n, 0)), (0, True)), (n, 1, N)) assert integrate(integrate(summation(sin(n*x), (n,1,N)), x), x) == \ Piecewise((Sum(Piecewise((-sin(n*x)/n**2, Ne(n, 0)), (-x/n, True)), (n, 1, N)), (n > -oo) & (n < oo) & Ne(n, 0)), (0, True)) assert integrate(Sum(x, (n, 1, M)), x) == M*x**2/2 raises(ValueError, lambda: integrate(Sum(x, (x, y, n)), y)) raises(ValueError, lambda: integrate(Sum(x, (x, 1, n)), n)) raises(ValueError, lambda: integrate(Sum(x, (x, 1, y)), x)) def test_issue_4231(): f = (1 + 2*x + sqrt(x + log(x))*(1 + 3*x) + x**2)/(x*(x + sqrt(x + log(x)))*sqrt(x + log(x))) assert integrate(f, x) == 2*sqrt(x + log(x)) + 2*log(x + sqrt(x + log(x))) def test_issue_17841(): f = diff(1/(x**2+x+I), x) assert integrate(f, x) == 1/(x**2 + x + I) def test_issue_21034(): x = Symbol('x', real=True, nonzero=True) f1 = x*(-x**4/asin(5)**4 - x*sinh(x + log(asin(5))) + 5) f2 = (x + cosh(cos(4)))/(x*(x + 1/(12*x))) assert integrate(f1, x) == \ -x**6/(6*asin(5)**4) - x**2*cosh(x + log(asin(5))) + 5*x**2/2 + 2*x*sinh(x + log(asin(5))) - 2*cosh(x + log(asin(5))) assert integrate(f2, x) == \ log(x**2 + S(1)/12)/2 + 2*sqrt(3)*cosh(cos(4))*atan(2*sqrt(3)*x) def test_issue_4187(): assert integrate(log(x)*exp(-x), x) == Ei(-x) - exp(-x)*log(x) assert integrate(log(x)*exp(-x), (x, 0, oo)) == -EulerGamma def test_issue_21024(): x = Symbol('x', real=True, nonzero=True) f = log(x)*log(4*x) + log(3*x + exp(2)) F = x*log(x)**2 + x*(1 - 2*log(2)) + (-2*x + 2*x*log(2))*log(x) + \ (x + exp(2)/6)*log(3*x + exp(2)) + exp(2)*log(3*x + exp(2))/6 assert F == integrate(f, x) f = (x + exp(3))/x**2 F = log(x) - exp(3)/x assert F == integrate(f, x) f = (x**2 + exp(5))/x F = x**2/2 + exp(5)*log(x) assert F == integrate(f, x) f = x/(2*x + tanh(1)) F = x/2 - log(2*x + tanh(1))*tanh(1)/4 assert F == integrate(f, x) f = x - sinh(4)/x F = x**2/2 - log(x)*sinh(4) assert F == integrate(f, x) f = log(x + exp(5)/x) F = x*log(x + exp(5)/x) - x + 2*exp(Rational(5, 2))*atan(x*exp(Rational(-5, 2))) assert F == integrate(f, x) f = x**5/(x + E) F = x**5/5 - E*x**4/4 + x**3*exp(2)/3 - x**2*exp(3)/2 + x*exp(4) - exp(5)*log(x + E) assert F == integrate(f, x) f = 4*x/(x + sinh(5)) F = 4*x - 4*log(x + sinh(5))*sinh(5) assert F == integrate(f, x) f = x**2/(2*x + sinh(2)) F = x**2/4 - x*sinh(2)/4 + log(2*x + sinh(2))*sinh(2)**2/8 assert F == integrate(f, x) f = -x**2/(x + E) F = -x**2/2 + E*x - exp(2)*log(x + E) assert F == integrate(f, x) f = (2*x + 3)*exp(5)/x F = 2*x*exp(5) + 3*exp(5)*log(x) assert F == integrate(f, x) f = x + 2 + cosh(3)/x F = x**2/2 + 2*x + log(x)*cosh(3) assert F == integrate(f, x) f = x - tanh(1)/x**3 F = x**2/2 + tanh(1)/(2*x**2) assert F == integrate(f, x) f = (3*x - exp(6))/x F = 3*x - exp(6)*log(x) assert F == integrate(f, x) f = x**4/(x + exp(5))**2 + x F = x**3/3 + x**2*(Rational(1, 2) - exp(5)) + 3*x*exp(10) - 4*exp(15)*log(x + exp(5)) - exp(20)/(x + exp(5)) assert F == integrate(f, x) f = x*(x + exp(10)/x**2) + x F = x**3/3 + x**2/2 + exp(10)*log(x) assert F == integrate(f, x) f = x + x/(5*x + sinh(3)) F = x**2/2 + x/5 - log(5*x + sinh(3))*sinh(3)/25 assert F == integrate(f, x) f = (x + exp(3))/(2*x**2 + 2*x) F = exp(3)*log(x)/2 + (Rational(1, 2) - exp(3)/2)*log(x + 1) assert F == integrate(f, x) f = log(x + 4*sinh(4)) F = x*log(x + 4*sinh(4)) - x + 4*log(x + 4*sinh(4))*sinh(4) assert F == integrate(f, x) f = -x + 20*(exp(-5) - atan(4)/x)**3*sin(4)/x F = (-x**2*exp(15)/2 + 20*log(x)*sin(4) - (-180*x**2*exp(5)*sin(4)*atan(4) + 90*x*exp(10)*sin(4)*atan(4)**2 - \ 20*exp(15)*sin(4)*atan(4)**3)/(3*x**3))*exp(-15) assert F == integrate(f, x) f = 2*x**2*exp(-4) + 6/x F_true = (2*x**3/3 + 6*exp(4)*log(x))*exp(-4) assert F_true == integrate(f, x) def test_issue_21831(): theta = symbols('theta') assert integrate(cos(3*theta)/(5-4*cos(theta)), (theta, 0, 2*pi)) == pi/12
d91e60d1f085b7430ba9b3323e7cf27011f84009b146ca451c5c39e487715f33
from sympy import (sin, cos, tan, sec, csc, cot, log, exp, atan, asin, acos, Symbol, Integral, integrate, pi, Dummy, Derivative, diff, I, sqrt, erf, Piecewise, Ne, symbols, Rational, And, Heaviside, S, asinh, acosh, atanh, acoth, expand, Function, jacobi, gegenbauer, chebyshevt, chebyshevu, legendre, hermite, laguerre, assoc_laguerre, uppergamma, li, Ei, Ci, Si, Chi, Shi, fresnels, fresnelc, polylog, erfi, sinh, cosh, elliptic_f, elliptic_e ,asec, acsc, acot ) from sympy.integrals.manualintegrate import (manualintegrate, find_substitutions, _parts_rule, integral_steps, contains_dont_know, manual_subs) from sympy.testing.pytest import raises, slow x, y, z, u, n, a, b, c = symbols('x y z u n a b c') f = Function('f') def test_find_substitutions(): assert find_substitutions((cot(x)**2 + 1)**2*csc(x)**2*cot(x)**2, x, u) == \ [(cot(x), 1, -u**6 - 2*u**4 - u**2)] assert find_substitutions((sec(x)**2 + tan(x) * sec(x)) / (sec(x) + tan(x)), x, u) == [(sec(x) + tan(x), 1, 1/u)] assert find_substitutions(x * exp(-x**2), x, u) == [(-x**2, Rational(-1, 2), exp(u))] def test_manualintegrate_polynomials(): assert manualintegrate(y, x) == x*y assert manualintegrate(exp(2), x) == x * exp(2) assert manualintegrate(x**2, x) == x**3 / 3 assert manualintegrate(3 * x**2 + 4 * x**3, x) == x**3 + x**4 assert manualintegrate((x + 2)**3, x) == (x + 2)**4 / 4 assert manualintegrate((3*x + 4)**2, x) == (3*x + 4)**3 / 9 assert manualintegrate((u + 2)**3, u) == (u + 2)**4 / 4 assert manualintegrate((3*u + 4)**2, u) == (3*u + 4)**3 / 9 def test_manualintegrate_exponentials(): assert manualintegrate(exp(2*x), x) == exp(2*x) / 2 assert manualintegrate(2**x, x) == (2 ** x) / log(2) assert manualintegrate(1 / x, x) == log(x) assert manualintegrate(1 / (2*x + 3), x) == log(2*x + 3) / 2 assert manualintegrate(log(x)**2 / x, x) == log(x)**3 / 3 def test_manualintegrate_parts(): assert manualintegrate(exp(x) * sin(x), x) == \ (exp(x) * sin(x)) / 2 - (exp(x) * cos(x)) / 2 assert manualintegrate(2*x*cos(x), x) == 2*x*sin(x) + 2*cos(x) assert manualintegrate(x * log(x), x) == x**2*log(x)/2 - x**2/4 assert manualintegrate(log(x), x) == x * log(x) - x assert manualintegrate((3*x**2 + 5) * exp(x), x) == \ 3*x**2*exp(x) - 6*x*exp(x) + 11*exp(x) assert manualintegrate(atan(x), x) == x*atan(x) - log(x**2 + 1)/2 # Make sure _parts_rule does not go into an infinite loop here assert manualintegrate(log(1/x)/(x + 1), x).has(Integral) # Make sure _parts_rule doesn't pick u = constant but can pick dv = # constant if necessary, e.g. for integrate(atan(x)) assert _parts_rule(cos(x), x) == None assert _parts_rule(exp(x), x) == None assert _parts_rule(x**2, x) == None result = _parts_rule(atan(x), x) assert result[0] == atan(x) and result[1] == 1 def test_manualintegrate_trigonometry(): assert manualintegrate(sin(x), x) == -cos(x) assert manualintegrate(tan(x), x) == -log(cos(x)) assert manualintegrate(sec(x), x) == log(sec(x) + tan(x)) assert manualintegrate(csc(x), x) == -log(csc(x) + cot(x)) assert manualintegrate(sin(x) * cos(x), x) in [sin(x) ** 2 / 2, -cos(x)**2 / 2] assert manualintegrate(-sec(x) * tan(x), x) == -sec(x) assert manualintegrate(csc(x) * cot(x), x) == -csc(x) assert manualintegrate(sec(x)**2, x) == tan(x) assert manualintegrate(csc(x)**2, x) == -cot(x) assert manualintegrate(x * sec(x**2), x) == log(tan(x**2) + sec(x**2))/2 assert manualintegrate(cos(x)*csc(sin(x)), x) == -log(cot(sin(x)) + csc(sin(x))) assert manualintegrate(cos(3*x)*sec(x), x) == -x + sin(2*x) assert manualintegrate(sin(3*x)*sec(x), x) == \ -3*log(cos(x)) + 2*log(cos(x)**2) - 2*cos(x)**2 @slow def test_manualintegrate_trigpowers(): assert manualintegrate(sin(x)**2 * cos(x), x) == sin(x)**3 / 3 assert manualintegrate(sin(x)**2 * cos(x) **2, x) == \ x / 8 - sin(4*x) / 32 assert manualintegrate(sin(x) * cos(x)**3, x) == -cos(x)**4 / 4 assert manualintegrate(sin(x)**3 * cos(x)**2, x) == \ cos(x)**5 / 5 - cos(x)**3 / 3 assert manualintegrate(tan(x)**3 * sec(x), x) == sec(x)**3/3 - sec(x) assert manualintegrate(tan(x) * sec(x) **2, x) == sec(x)**2/2 assert manualintegrate(cot(x)**5 * csc(x), x) == \ -csc(x)**5/5 + 2*csc(x)**3/3 - csc(x) assert manualintegrate(cot(x)**2 * csc(x)**6, x) == \ -cot(x)**7/7 - 2*cot(x)**5/5 - cot(x)**3/3 @slow def test_manualintegrate_inversetrig(): # atan assert manualintegrate(exp(x) / (1 + exp(2*x)), x) == atan(exp(x)) assert manualintegrate(1 / (4 + 9 * x**2), x) == atan(3 * x/2) / 6 assert manualintegrate(1 / (16 + 16 * x**2), x) == atan(x) / 16 assert manualintegrate(1 / (4 + x**2), x) == atan(x / 2) / 2 assert manualintegrate(1 / (1 + 4 * x**2), x) == atan(2*x) / 2 ra = Symbol('a', real=True) rb = Symbol('b', real=True) assert manualintegrate(1/(ra + rb*x**2), x) == \ Piecewise((atan(x/sqrt(ra/rb))/(rb*sqrt(ra/rb)), ra/rb > 0), (-acoth(x/sqrt(-ra/rb))/(rb*sqrt(-ra/rb)), And(ra/rb < 0, x**2 > -ra/rb)), (-atanh(x/sqrt(-ra/rb))/(rb*sqrt(-ra/rb)), And(ra/rb < 0, x**2 < -ra/rb))) assert manualintegrate(1/(4 + rb*x**2), x) == \ Piecewise((atan(x/(2*sqrt(1/rb)))/(2*rb*sqrt(1/rb)), 4/rb > 0), (-acoth(x/(2*sqrt(-1/rb)))/(2*rb*sqrt(-1/rb)), And(4/rb < 0, x**2 > -4/rb)), (-atanh(x/(2*sqrt(-1/rb)))/(2*rb*sqrt(-1/rb)), And(4/rb < 0, x**2 < -4/rb))) assert manualintegrate(1/(ra + 4*x**2), x) == \ Piecewise((atan(2*x/sqrt(ra))/(2*sqrt(ra)), ra/4 > 0), (-acoth(2*x/sqrt(-ra))/(2*sqrt(-ra)), And(ra/4 < 0, x**2 > -ra/4)), (-atanh(2*x/sqrt(-ra))/(2*sqrt(-ra)), And(ra/4 < 0, x**2 < -ra/4))) assert manualintegrate(1/(4 + 4*x**2), x) == atan(x) / 4 assert manualintegrate(1/(a + b*x**2), x) == atan(x/sqrt(a/b))/(b*sqrt(a/b)) # asin assert manualintegrate(1/sqrt(1-x**2), x) == asin(x) assert manualintegrate(1/sqrt(4-4*x**2), x) == asin(x)/2 assert manualintegrate(3/sqrt(1-9*x**2), x) == asin(3*x) assert manualintegrate(1/sqrt(4-9*x**2), x) == asin(x*Rational(3, 2))/3 # asinh assert manualintegrate(1/sqrt(x**2 + 1), x) == \ asinh(x) assert manualintegrate(1/sqrt(x**2 + 4), x) == \ asinh(x/2) assert manualintegrate(1/sqrt(4*x**2 + 4), x) == \ asinh(x)/2 assert manualintegrate(1/sqrt(4*x**2 + 1), x) == \ asinh(2*x)/2 assert manualintegrate(1/sqrt(a*x**2 + 1), x) == \ Piecewise((sqrt(-1/a)*asin(x*sqrt(-a)), a < 0), (sqrt(1/a)*asinh(sqrt(a)*x), a > 0)) assert manualintegrate(1/sqrt(a + x**2), x) == \ Piecewise((asinh(x*sqrt(1/a)), a > 0), (acosh(x*sqrt(-1/a)), a < 0)) # acosh assert manualintegrate(1/sqrt(x**2 - 1), x) == \ acosh(x) assert manualintegrate(1/sqrt(x**2 - 4), x) == \ acosh(x/2) assert manualintegrate(1/sqrt(4*x**2 - 4), x) == \ acosh(x)/2 assert manualintegrate(1/sqrt(9*x**2 - 1), x) == \ acosh(3*x)/3 assert manualintegrate(1/sqrt(a*x**2 - 4), x) == \ Piecewise((sqrt(1/a)*acosh(sqrt(a)*x/2), a > 0)) assert manualintegrate(1/sqrt(-a + 4*x**2), x) == \ Piecewise((asinh(2*x*sqrt(-1/a))/2, -a > 0), (acosh(2*x*sqrt(1/a))/2, -a < 0)) # From https://www.wikiwand.com/en/List_of_integrals_of_inverse_trigonometric_functions # asin assert manualintegrate(asin(x), x) == x*asin(x) + sqrt(1 - x**2) assert manualintegrate(asin(a*x), x) == Piecewise(((a*x*asin(a*x) + sqrt(-a**2*x**2 + 1))/a, Ne(a, 0)), (0, True)) assert manualintegrate(x*asin(a*x), x) == -a*Integral(x**2/sqrt(-a**2*x**2 + 1), x)/2 + x**2*asin(a*x)/2 # acos assert manualintegrate(acos(x), x) == x*acos(x) - sqrt(1 - x**2) assert manualintegrate(acos(a*x), x) == Piecewise(((a*x*acos(a*x) - sqrt(-a**2*x**2 + 1))/a, Ne(a, 0)), (pi*x/2, True)) assert manualintegrate(x*acos(a*x), x) == a*Integral(x**2/sqrt(-a**2*x**2 + 1), x)/2 + x**2*acos(a*x)/2 # atan assert manualintegrate(atan(x), x) == x*atan(x) - log(x**2 + 1)/2 assert manualintegrate(atan(a*x), x) == Piecewise(((a*x*atan(a*x) - log(a**2*x**2 + 1)/2)/a, Ne(a, 0)), (0, True)) assert manualintegrate(x*atan(a*x), x) == -a*(x/a**2 - atan(x/sqrt(a**(-2)))/(a**4*sqrt(a**(-2))))/2 + x**2*atan(a*x)/2 # acsc assert manualintegrate(acsc(x), x) == x*acsc(x) + Integral(1/(x*sqrt(1 - 1/x**2)), x) assert manualintegrate(acsc(a*x), x) == x*acsc(a*x) + Integral(1/(x*sqrt(1 - 1/(a**2*x**2))), x)/a assert manualintegrate(x*acsc(a*x), x) == x**2*acsc(a*x)/2 + Integral(1/sqrt(1 - 1/(a**2*x**2)), x)/(2*a) # asec assert manualintegrate(asec(x), x) == x*asec(x) - Integral(1/(x*sqrt(1 - 1/x**2)), x) assert manualintegrate(asec(a*x), x) == x*asec(a*x) - Integral(1/(x*sqrt(1 - 1/(a**2*x**2))), x)/a assert manualintegrate(x*asec(a*x), x) == x**2*asec(a*x)/2 - Integral(1/sqrt(1 - 1/(a**2*x**2)), x)/(2*a) # acot assert manualintegrate(acot(x), x) == x*acot(x) + log(x**2 + 1)/2 assert manualintegrate(acot(a*x), x) == Piecewise(((a*x*acot(a*x) + log(a**2*x**2 + 1)/2)/a, Ne(a, 0)), (pi*x/2, True)) assert manualintegrate(x*acot(a*x), x) == a*(x/a**2 - atan(x/sqrt(a**(-2)))/(a**4*sqrt(a**(-2))))/2 + x**2*acot(a*x)/2 # piecewise assert manualintegrate(1/sqrt(a-b*x**2), x) == \ Piecewise((sqrt(a/b)*asin(x*sqrt(b/a))/sqrt(a), And(-b < 0, a > 0)), (sqrt(-a/b)*asinh(x*sqrt(-b/a))/sqrt(a), And(-b > 0, a > 0)), (sqrt(a/b)*acosh(x*sqrt(b/a))/sqrt(-a), And(-b > 0, a < 0))) assert manualintegrate(1/sqrt(a + b*x**2), x) == \ Piecewise((sqrt(-a/b)*asin(x*sqrt(-b/a))/sqrt(a), And(a > 0, b < 0)), (sqrt(a/b)*asinh(x*sqrt(b/a))/sqrt(a), And(a > 0, b > 0)), (sqrt(-a/b)*acosh(x*sqrt(-b/a))/sqrt(-a), And(a < 0, b > 0))) def test_manualintegrate_trig_substitution(): assert manualintegrate(sqrt(16*x**2 - 9)/x, x) == \ Piecewise((sqrt(16*x**2 - 9) - 3*acos(3/(4*x)), And(x < Rational(3, 4), x > Rational(-3, 4)))) assert manualintegrate(1/(x**4 * sqrt(25-x**2)), x) == \ Piecewise((-sqrt(-x**2/25 + 1)/(125*x) - (-x**2/25 + 1)**(3*S.Half)/(15*x**3), And(x < 5, x > -5))) assert manualintegrate(x**7/(49*x**2 + 1)**(3 * S.Half), x) == \ ((49*x**2 + 1)**(5*S.Half)/28824005 - (49*x**2 + 1)**(3*S.Half)/5764801 + 3*sqrt(49*x**2 + 1)/5764801 + 1/(5764801*sqrt(49*x**2 + 1))) def test_manualintegrate_trivial_substitution(): assert manualintegrate((exp(x) - exp(-x))/x, x) == -Ei(-x) + Ei(x) f = Function('f') assert manualintegrate((f(x) - f(-x))/x, x) == \ -Integral(f(-x)/x, x) + Integral(f(x)/x, x) def test_manualintegrate_rational(): assert manualintegrate(1/(4 - x**2), x) == Piecewise((acoth(x/2)/2, x**2 > 4), (atanh(x/2)/2, x**2 < 4)) assert manualintegrate(1/(-1 + x**2), x) == Piecewise((-acoth(x), x**2 > 1), (-atanh(x), x**2 < 1)) def test_manualintegrate_special(): f, F = 4*exp(-x**2/3), 2*sqrt(3)*sqrt(pi)*erf(sqrt(3)*x/3) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = 3*exp(4*x**2), 3*sqrt(pi)*erfi(2*x)/4 assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = x**Rational(1, 3)*exp(-x/8), -16*uppergamma(Rational(4, 3), x/8) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = exp(2*x)/x, Ei(2*x) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = exp(1 + 2*x - x**2), sqrt(pi)*exp(2)*erf(x - 1)/2 assert manualintegrate(f, x) == F and F.diff(x).equals(f) f = sin(x**2 + 4*x + 1) F = (sqrt(2)*sqrt(pi)*(-sin(3)*fresnelc(sqrt(2)*(2*x + 4)/(2*sqrt(pi))) + cos(3)*fresnels(sqrt(2)*(2*x + 4)/(2*sqrt(pi))))/2) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = cos(4*x**2), sqrt(2)*sqrt(pi)*fresnelc(2*sqrt(2)*x/sqrt(pi))/4 assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = sin(3*x + 2)/x, sin(2)*Ci(3*x) + cos(2)*Si(3*x) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = sinh(3*x - 2)/x, -sinh(2)*Chi(3*x) + cosh(2)*Shi(3*x) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = 5*cos(2*x - 3)/x, 5*cos(3)*Ci(2*x) + 5*sin(3)*Si(2*x) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = cosh(x/2)/x, Chi(x/2) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = cos(x**2)/x, Ci(x**2)/2 assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = 1/log(2*x + 1), li(2*x + 1)/2 assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = polylog(2, 5*x)/x, polylog(3, 5*x) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = 5/sqrt(3 - 2*sin(x)**2), 5*sqrt(3)*elliptic_f(x, Rational(2, 3))/3 assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = sqrt(4 + 9*sin(x)**2), 2*elliptic_e(x, Rational(-9, 4)) assert manualintegrate(f, x) == F and F.diff(x).equals(f) def test_manualintegrate_derivative(): assert manualintegrate(pi * Derivative(x**2 + 2*x + 3), x) == \ pi * (x**2 + 2*x + 3) assert manualintegrate(Derivative(x**2 + 2*x + 3, y), x) == \ Integral(Derivative(x**2 + 2*x + 3, y)) assert manualintegrate(Derivative(sin(x), x, x, x, y), x) == \ Derivative(sin(x), x, x, y) def test_manualintegrate_Heaviside(): assert manualintegrate(Heaviside(x), x) == x*Heaviside(x) assert manualintegrate(x*Heaviside(2), x) == x**2/2 assert manualintegrate(x*Heaviside(-2), x) == 0 assert manualintegrate(x*Heaviside( x), x) == x**2*Heaviside( x)/2 assert manualintegrate(x*Heaviside(-x), x) == x**2*Heaviside(-x)/2 assert manualintegrate(Heaviside(2*x + 4), x) == (x+2)*Heaviside(2*x + 4) assert manualintegrate(x*Heaviside(x), x) == x**2*Heaviside(x)/2 assert manualintegrate(Heaviside(x + 1)*Heaviside(1 - x)*x**2, x) == \ ((x**3/3 + Rational(1, 3))*Heaviside(x + 1) - Rational(2, 3))*Heaviside(-x + 1) y = Symbol('y') assert manualintegrate(sin(7 + x)*Heaviside(3*x - 7), x) == \ (- cos(x + 7) + cos(Rational(28, 3)))*Heaviside(3*x - S(7)) assert manualintegrate(sin(y + x)*Heaviside(3*x - y), x) == \ (cos(y*Rational(4, 3)) - cos(x + y))*Heaviside(3*x - y) def test_manualintegrate_orthogonal_poly(): n = symbols('n') a, b = 7, Rational(5, 3) polys = [jacobi(n, a, b, x), gegenbauer(n, a, x), chebyshevt(n, x), chebyshevu(n, x), legendre(n, x), hermite(n, x), laguerre(n, x), assoc_laguerre(n, a, x)] for p in polys: integral = manualintegrate(p, x) for deg in [-2, -1, 0, 1, 3, 5, 8]: # some accept negative "degree", some do not try: p_subbed = p.subs(n, deg) except ValueError: continue assert (integral.subs(n, deg).diff(x) - p_subbed).expand() == 0 # can also integrate simple expressions with these polynomials q = x*p.subs(x, 2*x + 1) integral = manualintegrate(q, x) for deg in [2, 4, 7]: assert (integral.subs(n, deg).diff(x) - q.subs(n, deg)).expand() == 0 # cannot integrate with respect to any other parameter t = symbols('t') for i in range(len(p.args) - 1): new_args = list(p.args) new_args[i] = t assert isinstance(manualintegrate(p.func(*new_args), t), Integral) @slow def test_issue_6799(): r, x, phi = map(Symbol, 'r x phi'.split()) n = Symbol('n', integer=True, positive=True) integrand = (cos(n*(x-phi))*cos(n*x)) limits = (x, -pi, pi) assert manualintegrate(integrand, x) == \ ((n*x/2 + sin(2*n*x)/4)*cos(n*phi) - sin(n*phi)*cos(n*x)**2/2)/n assert r * integrate(integrand, limits).trigsimp() / pi == r * cos(n * phi) assert not integrate(integrand, limits).has(Dummy) def test_issue_12251(): assert manualintegrate(x**y, x) == Piecewise( (x**(y + 1)/(y + 1), Ne(y, -1)), (log(x), True)) def test_issue_3796(): assert manualintegrate(diff(exp(x + x**2)), x) == exp(x + x**2) assert integrate(x * exp(x**4), x, risch=False) == -I*sqrt(pi)*erf(I*x**2)/4 def test_manual_true(): assert integrate(exp(x) * sin(x), x, manual=True) == \ (exp(x) * sin(x)) / 2 - (exp(x) * cos(x)) / 2 assert integrate(sin(x) * cos(x), x, manual=True) in \ [sin(x) ** 2 / 2, -cos(x)**2 / 2] def test_issue_6746(): y = Symbol('y') n = Symbol('n') assert manualintegrate(y**x, x) == Piecewise( (y**x/log(y), Ne(log(y), 0)), (x, True)) assert manualintegrate(y**(n*x), x) == Piecewise( (Piecewise( (y**(n*x)/log(y), Ne(log(y), 0)), (n*x, True) )/n, Ne(n, 0)), (x, True)) assert manualintegrate(exp(n*x), x) == Piecewise( (exp(n*x)/n, Ne(n, 0)), (x, True)) y = Symbol('y', positive=True) assert manualintegrate((y + 1)**x, x) == (y + 1)**x/log(y + 1) y = Symbol('y', zero=True) assert manualintegrate((y + 1)**x, x) == x y = Symbol('y') n = Symbol('n', nonzero=True) assert manualintegrate(y**(n*x), x) == Piecewise( (y**(n*x)/log(y), Ne(log(y), 0)), (n*x, True))/n y = Symbol('y', positive=True) assert manualintegrate((y + 1)**(n*x), x) == \ (y + 1)**(n*x)/(n*log(y + 1)) a = Symbol('a', negative=True) b = Symbol('b') assert manualintegrate(1/(a + b*x**2), x) == atan(x/sqrt(a/b))/(b*sqrt(a/b)) b = Symbol('b', negative=True) assert manualintegrate(1/(a + b*x**2), x) == \ atan(x/(sqrt(-a)*sqrt(-1/b)))/(b*sqrt(-a)*sqrt(-1/b)) assert manualintegrate(1/((x**a + y**b + 4)*sqrt(a*x**2 + 1)), x) == \ y**(-b)*Integral(x**(-a)/(y**(-b)*sqrt(a*x**2 + 1) + x**(-a)*sqrt(a*x**2 + 1) + 4*x**(-a)*y**(-b)*sqrt(a*x**2 + 1)), x) assert manualintegrate(1/((x**2 + 4)*sqrt(4*x**2 + 1)), x) == \ Integral(1/((x**2 + 4)*sqrt(4*x**2 + 1)), x) assert manualintegrate(1/(x - a**x + x*b**2), x) == \ Integral(1/(-a**x + b**2*x + x), x) @slow def test_issue_2850(): assert manualintegrate(asin(x)*log(x), x) == -x*asin(x) - sqrt(-x**2 + 1) \ + (x*asin(x) + sqrt(-x**2 + 1))*log(x) - Integral(sqrt(-x**2 + 1)/x, x) assert manualintegrate(acos(x)*log(x), x) == -x*acos(x) + sqrt(-x**2 + 1) + \ (x*acos(x) - sqrt(-x**2 + 1))*log(x) + Integral(sqrt(-x**2 + 1)/x, x) assert manualintegrate(atan(x)*log(x), x) == -x*atan(x) + (x*atan(x) - \ log(x**2 + 1)/2)*log(x) + log(x**2 + 1)/2 + Integral(log(x**2 + 1)/x, x)/2 def test_issue_9462(): assert manualintegrate(sin(2*x)*exp(x), x) == exp(x)*sin(2*x)/5 - 2*exp(x)*cos(2*x)/5 assert not contains_dont_know(integral_steps(sin(2*x)*exp(x), x)) assert manualintegrate((x - 3) / (x**2 - 2*x + 2)**2, x) == \ Integral(x/(x**4 - 4*x**3 + 8*x**2 - 8*x + 4), x) \ - 3*Integral(1/(x**4 - 4*x**3 + 8*x**2 - 8*x + 4), x) def test_cyclic_parts(): f = cos(x)*exp(x/4) F = 16*exp(x/4)*sin(x)/17 + 4*exp(x/4)*cos(x)/17 assert manualintegrate(f, x) == F and F.diff(x) == f f = x*cos(x)*exp(x/4) F = (x*(16*exp(x/4)*sin(x)/17 + 4*exp(x/4)*cos(x)/17) - 128*exp(x/4)*sin(x)/289 + 240*exp(x/4)*cos(x)/289) assert manualintegrate(f, x) == F and F.diff(x) == f @slow def test_issue_10847_slow(): assert manualintegrate((4*x**4 + 4*x**3 + 16*x**2 + 12*x + 8) / (x**6 + 2*x**5 + 3*x**4 + 4*x**3 + 3*x**2 + 2*x + 1), x) == \ 2*x/(x**2 + 1) + 3*atan(x) - 1/(x**2 + 1) - 3/(x + 1) @slow def test_issue_10847(): assert manualintegrate(x**2 / (x**2 - c), x) == c*atan(x/sqrt(-c))/sqrt(-c) + x rc = Symbol('c', real=True) assert manualintegrate(x**2 / (x**2 - rc), x) == \ rc*Piecewise((atan(x/sqrt(-rc))/sqrt(-rc), -rc > 0), (-acoth(x/sqrt(rc))/sqrt(rc), And(-rc < 0, x**2 > rc)), (-atanh(x/sqrt(rc))/sqrt(rc), And(-rc < 0, x**2 < rc))) + x assert manualintegrate(sqrt(x - y) * log(z / x), x) == \ 4*y**Rational(3, 2)*atan(sqrt(x - y)/sqrt(y))/3 - 4*y*sqrt(x - y)/3 +\ 2*(x - y)**Rational(3, 2)*log(z/x)/3 + 4*(x - y)**Rational(3, 2)/9 ry = Symbol('y', real=True) rz = Symbol('z', real=True) assert manualintegrate(sqrt(x - ry) * log(rz / x), x) == \ 4*ry**2*Piecewise((atan(sqrt(x - ry)/sqrt(ry))/sqrt(ry), ry > 0), (-acoth(sqrt(x - ry)/sqrt(-ry))/sqrt(-ry), And(x - ry > -ry, ry < 0)), (-atanh(sqrt(x - ry)/sqrt(-ry))/sqrt(-ry), And(x - ry < -ry, ry < 0)))/3 \ - 4*ry*sqrt(x - ry)/3 + 2*(x - ry)**Rational(3, 2)*log(rz/x)/3 \ + 4*(x - ry)**Rational(3, 2)/9 assert manualintegrate(sqrt(x) * log(x), x) == 2*x**Rational(3, 2)*log(x)/3 - 4*x**Rational(3, 2)/9 assert manualintegrate(sqrt(a*x + b) / x, x) == \ 2*b*atan(sqrt(a*x + b)/sqrt(-b))/sqrt(-b) + 2*sqrt(a*x + b) ra = Symbol('a', real=True) rb = Symbol('b', real=True) assert manualintegrate(sqrt(ra*x + rb) / x, x) == \ -2*rb*Piecewise((-atan(sqrt(ra*x + rb)/sqrt(-rb))/sqrt(-rb), -rb > 0), (acoth(sqrt(ra*x + rb)/sqrt(rb))/sqrt(rb), And(-rb < 0, ra*x + rb > rb)), (atanh(sqrt(ra*x + rb)/sqrt(rb))/sqrt(rb), And(-rb < 0, ra*x + rb < rb))) \ + 2*sqrt(ra*x + rb) assert expand(manualintegrate(sqrt(ra*x + rb) / (x + rc), x)) == -2*ra*rc*Piecewise((atan(sqrt(ra*x + rb)/sqrt(ra*rc - rb))/sqrt(ra*rc - rb), \ ra*rc - rb > 0), (-acoth(sqrt(ra*x + rb)/sqrt(-ra*rc + rb))/sqrt(-ra*rc + rb), And(ra*rc - rb < 0, ra*x + rb > -ra*rc + rb)), \ (-atanh(sqrt(ra*x + rb)/sqrt(-ra*rc + rb))/sqrt(-ra*rc + rb), And(ra*rc - rb < 0, ra*x + rb < -ra*rc + rb))) \ + 2*rb*Piecewise((atan(sqrt(ra*x + rb)/sqrt(ra*rc - rb))/sqrt(ra*rc - rb), ra*rc - rb > 0), \ (-acoth(sqrt(ra*x + rb)/sqrt(-ra*rc + rb))/sqrt(-ra*rc + rb), And(ra*rc - rb < 0, ra*x + rb > -ra*rc + rb)), \ (-atanh(sqrt(ra*x + rb)/sqrt(-ra*rc + rb))/sqrt(-ra*rc + rb), And(ra*rc - rb < 0, ra*x + rb < -ra*rc + rb))) + 2*sqrt(ra*x + rb) assert manualintegrate(sqrt(2*x + 3) / (x + 1), x) == 2*sqrt(2*x + 3) - log(sqrt(2*x + 3) + 1) + log(sqrt(2*x + 3) - 1) assert manualintegrate(sqrt(2*x + 3) / 2 * x, x) == (2*x + 3)**Rational(5, 2)/20 - (2*x + 3)**Rational(3, 2)/4 assert manualintegrate(x**Rational(3,2) * log(x), x) == 2*x**Rational(5,2)*log(x)/5 - 4*x**Rational(5,2)/25 assert manualintegrate(x**(-3) * log(x), x) == -log(x)/(2*x**2) - 1/(4*x**2) assert manualintegrate(log(y)/(y**2*(1 - 1/y)), y) == \ log(y)*log(-1 + 1/y) - Integral(log(-1 + 1/y)/y, y) def test_issue_12899(): assert manualintegrate(f(x,y).diff(x),y) == Integral(Derivative(f(x,y),x),y) assert manualintegrate(f(x,y).diff(y).diff(x),y) == Derivative(f(x,y),x) def test_constant_independent_of_symbol(): assert manualintegrate(Integral(y, (x, 1, 2)), x) == \ x*Integral(y, (x, 1, 2)) def test_issue_12641(): assert manualintegrate(sin(2*x), x) == -cos(2*x)/2 assert manualintegrate(cos(x)*sin(2*x), x) == -2*cos(x)**3/3 assert manualintegrate((sin(2*x)*cos(x))/(1 + cos(x)), x) == \ -2*log(cos(x) + 1) - cos(x)**2 + 2*cos(x) @slow def test_issue_13297(): assert manualintegrate(sin(x) * cos(x)**5, x) == -cos(x)**6 / 6 def test_issue_14470(): assert manualintegrate(1/(x*sqrt(x + 1)), x) == \ log(-1 + 1/sqrt(x + 1)) - log(1 + 1/sqrt(x + 1)) @slow def test_issue_9858(): assert manualintegrate(exp(x)*cos(exp(x)), x) == sin(exp(x)) assert manualintegrate(exp(2*x)*cos(exp(x)), x) == \ exp(x)*sin(exp(x)) + cos(exp(x)) res = manualintegrate(exp(10*x)*sin(exp(x)), x) assert not res.has(Integral) assert res.diff(x) == exp(10*x)*sin(exp(x)) # an example with many similar integrations by parts assert manualintegrate(sum([x*exp(k*x) for k in range(1, 8)]), x) == ( x*exp(7*x)/7 + x*exp(6*x)/6 + x*exp(5*x)/5 + x*exp(4*x)/4 + x*exp(3*x)/3 + x*exp(2*x)/2 + x*exp(x) - exp(7*x)/49 -exp(6*x)/36 - exp(5*x)/25 - exp(4*x)/16 - exp(3*x)/9 - exp(2*x)/4 - exp(x)) def test_issue_8520(): assert manualintegrate(x/(x**4 + 1), x) == atan(x**2)/2 assert manualintegrate(x**2/(x**6 + 25), x) == atan(x**3/5)/15 f = x/(9*x**4 + 4)**2 assert manualintegrate(f, x).diff(x).factor() == f def test_manual_subs(): x, y = symbols('x y') expr = log(x) + exp(x) # if log(x) is y, then exp(y) is x assert manual_subs(expr, log(x), y) == y + exp(exp(y)) # if exp(x) is y, then log(y) need not be x assert manual_subs(expr, exp(x), y) == log(x) + y raises(ValueError, lambda: manual_subs(expr, x)) raises(ValueError, lambda: manual_subs(expr, exp(x), x, y)) @slow def test_issue_15471(): f = log(x)*cos(log(x))/x**Rational(3, 4) F = -128*x**Rational(1, 4)*sin(log(x))/289 + 240*x**Rational(1, 4)*cos(log(x))/289 + (16*x**Rational(1, 4)*sin(log(x))/17 + 4*x**Rational(1, 4)*cos(log(x))/17)*log(x) assert manualintegrate(f, x) == F and F.diff(x).equals(f) def test_quadratic_denom(): f = (5*x + 2)/(3*x**2 - 2*x + 8) assert manualintegrate(f, x) == 5*log(3*x**2 - 2*x + 8)/6 + 11*sqrt(23)*atan(3*sqrt(23)*(x - Rational(1, 3))/23)/69 g = 3/(2*x**2 + 3*x + 1) assert manualintegrate(g, x) == 3*log(4*x + 2) - 3*log(4*x + 4)
ecaf59a4e389faa0412543bfb5883c00bc5d86b327d65e2af3297480fc32b72f
from sympy.integrals.transforms import (mellin_transform, inverse_mellin_transform, laplace_transform, inverse_laplace_transform, fourier_transform, inverse_fourier_transform, sine_transform, inverse_sine_transform, cosine_transform, inverse_cosine_transform, hankel_transform, inverse_hankel_transform, LaplaceTransform, FourierTransform, SineTransform, CosineTransform, InverseLaplaceTransform, InverseFourierTransform, InverseSineTransform, InverseCosineTransform, IntegralTransformError) from sympy import ( gamma, exp, oo, Heaviside, symbols, Symbol, re, factorial, pi, arg, cos, S, Abs, And, sin, sqrt, I, log, tan, hyperexpand, meijerg, EulerGamma, erf, erfc, besselj, bessely, besseli, besselk, exp_polar, unpolarify, Function, expint, expand_mul, Rational, gammasimp, trigsimp, atan, sinh, cosh, Ne, periodic_argument, atan2) from sympy.testing.pytest import XFAIL, slow, skip, raises, warns_deprecated_sympy from sympy.matrices import Matrix, eye from sympy.abc import x, s, a, b, c, d nu, beta, rho = symbols('nu beta rho') def test_undefined_function(): from sympy import Function, MellinTransform f = Function('f') assert mellin_transform(f(x), x, s) == MellinTransform(f(x), x, s) assert mellin_transform(f(x) + exp(-x), x, s) == \ (MellinTransform(f(x), x, s) + gamma(s), (0, oo), True) assert laplace_transform(2*f(x), x, s) == 2*LaplaceTransform(f(x), x, s) # TODO test derivative and other rules when implemented def test_free_symbols(): from sympy import Function f = Function('f') assert mellin_transform(f(x), x, s).free_symbols == {s} assert mellin_transform(f(x)*a, x, s).free_symbols == {s, a} def test_as_integral(): from sympy import Function, Integral f = Function('f') assert mellin_transform(f(x), x, s).rewrite('Integral') == \ Integral(x**(s - 1)*f(x), (x, 0, oo)) assert fourier_transform(f(x), x, s).rewrite('Integral') == \ Integral(f(x)*exp(-2*I*pi*s*x), (x, -oo, oo)) assert laplace_transform(f(x), x, s).rewrite('Integral') == \ Integral(f(x)*exp(-s*x), (x, 0, oo)) assert str(2*pi*I*inverse_mellin_transform(f(s), s, x, (a, b)).rewrite('Integral')) \ == "Integral(f(s)/x**s, (s, _c - oo*I, _c + oo*I))" assert str(2*pi*I*inverse_laplace_transform(f(s), s, x).rewrite('Integral')) == \ "Integral(f(s)*exp(s*x), (s, _c - oo*I, _c + oo*I))" assert inverse_fourier_transform(f(s), s, x).rewrite('Integral') == \ Integral(f(s)*exp(2*I*pi*s*x), (s, -oo, oo)) # NOTE this is stuck in risch because meijerint cannot handle it @slow @XFAIL def test_mellin_transform_fail(): skip("Risch takes forever.") MT = mellin_transform bpos = symbols('b', positive=True) # bneg = symbols('b', negative=True) expr = (sqrt(x + b**2) + b)**a/sqrt(x + b**2) # TODO does not work with bneg, argument wrong. Needs changes to matching. assert MT(expr.subs(b, -bpos), x, s) == \ ((-1)**(a + 1)*2**(a + 2*s)*bpos**(a + 2*s - 1)*gamma(a + s) *gamma(1 - a - 2*s)/gamma(1 - s), (-re(a), -re(a)/2 + S.Half), True) expr = (sqrt(x + b**2) + b)**a assert MT(expr.subs(b, -bpos), x, s) == \ ( 2**(a + 2*s)*a*bpos**(a + 2*s)*gamma(-a - 2* s)*gamma(a + s)/gamma(-s + 1), (-re(a), -re(a)/2), True) # Test exponent 1: assert MT(expr.subs({b: -bpos, a: 1}), x, s) == \ (-bpos**(2*s + 1)*gamma(s)*gamma(-s - S.Half)/(2*sqrt(pi)), (-1, Rational(-1, 2)), True) def test_mellin_transform(): from sympy import Max, Min MT = mellin_transform bpos = symbols('b', positive=True) # 8.4.2 assert MT(x**nu*Heaviside(x - 1), x, s) == \ (-1/(nu + s), (-oo, -re(nu)), True) assert MT(x**nu*Heaviside(1 - x), x, s) == \ (1/(nu + s), (-re(nu), oo), True) assert MT((1 - x)**(beta - 1)*Heaviside(1 - x), x, s) == \ (gamma(beta)*gamma(s)/gamma(beta + s), (0, oo), re(beta) > 0) assert MT((x - 1)**(beta - 1)*Heaviside(x - 1), x, s) == \ (gamma(beta)*gamma(1 - beta - s)/gamma(1 - s), (-oo, -re(beta) + 1), re(beta) > 0) assert MT((1 + x)**(-rho), x, s) == \ (gamma(s)*gamma(rho - s)/gamma(rho), (0, re(rho)), True) # TODO also the conditions should be simplified, e.g. # And(re(rho) - 1 < 0, re(rho) < 1) should just be # re(rho) < 1 assert MT(abs(1 - x)**(-rho), x, s) == ( 2*sin(pi*rho/2)*gamma(1 - rho)* cos(pi*(rho/2 - s))*gamma(s)*gamma(rho-s)/pi, (0, re(rho)), And(re(rho) - 1 < 0, re(rho) < 1)) mt = MT((1 - x)**(beta - 1)*Heaviside(1 - x) + a*(x - 1)**(beta - 1)*Heaviside(x - 1), x, s) assert mt[1], mt[2] == ((0, -re(beta) + 1), re(beta) > 0) assert MT((x**a - b**a)/(x - b), x, s)[0] == \ pi*b**(a + s - 1)*sin(pi*a)/(sin(pi*s)*sin(pi*(a + s))) assert MT((x**a - bpos**a)/(x - bpos), x, s) == \ (pi*bpos**(a + s - 1)*sin(pi*a)/(sin(pi*s)*sin(pi*(a + s))), (Max(-re(a), 0), Min(1 - re(a), 1)), True) expr = (sqrt(x + b**2) + b)**a assert MT(expr.subs(b, bpos), x, s) == \ (-a*(2*bpos)**(a + 2*s)*gamma(s)*gamma(-a - 2*s)/gamma(-a - s + 1), (0, -re(a)/2), True) expr = (sqrt(x + b**2) + b)**a/sqrt(x + b**2) assert MT(expr.subs(b, bpos), x, s) == \ (2**(a + 2*s)*bpos**(a + 2*s - 1)*gamma(s) *gamma(1 - a - 2*s)/gamma(1 - a - s), (0, -re(a)/2 + S.Half), True) # 8.4.2 assert MT(exp(-x), x, s) == (gamma(s), (0, oo), True) assert MT(exp(-1/x), x, s) == (gamma(-s), (-oo, 0), True) # 8.4.5 assert MT(log(x)**4*Heaviside(1 - x), x, s) == (24/s**5, (0, oo), True) assert MT(log(x)**3*Heaviside(x - 1), x, s) == (6/s**4, (-oo, 0), True) assert MT(log(x + 1), x, s) == (pi/(s*sin(pi*s)), (-1, 0), True) assert MT(log(1/x + 1), x, s) == (pi/(s*sin(pi*s)), (0, 1), True) assert MT(log(abs(1 - x)), x, s) == (pi/(s*tan(pi*s)), (-1, 0), True) assert MT(log(abs(1 - 1/x)), x, s) == (pi/(s*tan(pi*s)), (0, 1), True) # 8.4.14 assert MT(erf(sqrt(x)), x, s) == \ (-gamma(s + S.Half)/(sqrt(pi)*s), (Rational(-1, 2), 0), True) def test_mellin_transform2(): MT = mellin_transform # TODO we cannot currently do these (needs summation of 3F2(-1)) # this also implies that they cannot be written as a single g-function # (although this is possible) mt = MT(log(x)/(x + 1), x, s) assert mt[1:] == ((0, 1), True) assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg) mt = MT(log(x)**2/(x + 1), x, s) assert mt[1:] == ((0, 1), True) assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg) mt = MT(log(x)/(x + 1)**2, x, s) assert mt[1:] == ((0, 2), True) assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg) @slow def test_mellin_transform_bessel(): from sympy import Max MT = mellin_transform # 8.4.19 assert MT(besselj(a, 2*sqrt(x)), x, s) == \ (gamma(a/2 + s)/gamma(a/2 - s + 1), (-re(a)/2, Rational(3, 4)), True) assert MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s) == \ (2**a*gamma(-2*s + S.Half)*gamma(a/2 + s + S.Half)/( gamma(-a/2 - s + 1)*gamma(a - 2*s + 1)), ( -re(a)/2 - S.Half, Rational(1, 4)), True) assert MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s) == \ (2**a*gamma(a/2 + s)*gamma(-2*s + S.Half)/( gamma(-a/2 - s + S.Half)*gamma(a - 2*s + 1)), ( -re(a)/2, Rational(1, 4)), True) assert MT(besselj(a, sqrt(x))**2, x, s) == \ (gamma(a + s)*gamma(S.Half - s) / (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)), (-re(a), S.Half), True) assert MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s) == \ (gamma(s)*gamma(S.Half - s) / (sqrt(pi)*gamma(1 - a - s)*gamma(1 + a - s)), (0, S.Half), True) # NOTE: prudnikov gives the strip below as (1/2 - re(a), 1). As far as # I can see this is wrong (since besselj(z) ~ 1/sqrt(z) for z large) assert MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s) == \ (gamma(1 - s)*gamma(a + s - S.Half) / (sqrt(pi)*gamma(Rational(3, 2) - s)*gamma(a - s + S.Half)), (S.Half - re(a), S.Half), True) assert MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s) == \ (4**s*gamma(1 - 2*s)*gamma((a + b)/2 + s) / (gamma(1 - s + (b - a)/2)*gamma(1 - s + (a - b)/2) *gamma( 1 - s + (a + b)/2)), (-(re(a) + re(b))/2, S.Half), True) assert MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)[1:] == \ ((Max(re(a), -re(a)), S.Half), True) # Section 8.4.20 assert MT(bessely(a, 2*sqrt(x)), x, s) == \ (-cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)/pi, (Max(-re(a)/2, re(a)/2), Rational(3, 4)), True) assert MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s) == \ (-4**s*sin(pi*(a/2 - s))*gamma(S.Half - 2*s) * gamma((1 - a)/2 + s)*gamma((1 + a)/2 + s) / (sqrt(pi)*gamma(1 - s - a/2)*gamma(1 - s + a/2)), (Max(-(re(a) + 1)/2, (re(a) - 1)/2), Rational(1, 4)), True) assert MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s) == \ (-4**s*cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)*gamma(S.Half - 2*s) / (sqrt(pi)*gamma(S.Half - s - a/2)*gamma(S.Half - s + a/2)), (Max(-re(a)/2, re(a)/2), Rational(1, 4)), True) assert MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s) == \ (-cos(pi*s)*gamma(s)*gamma(a + s)*gamma(S.Half - s) / (pi**S('3/2')*gamma(1 + a - s)), (Max(-re(a), 0), S.Half), True) assert MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s) == \ (-4**s*cos(pi*(a/2 - b/2 + s))*gamma(1 - 2*s) * gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s) / (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)), (Max((-re(a) + re(b))/2, (-re(a) - re(b))/2), S.Half), True) # NOTE bessely(a, sqrt(x))**2 and bessely(a, sqrt(x))*bessely(b, sqrt(x)) # are a mess (no matter what way you look at it ...) assert MT(bessely(a, sqrt(x))**2, x, s)[1:] == \ ((Max(-re(a), 0, re(a)), S.Half), True) # Section 8.4.22 # TODO we can't do any of these (delicate cancellation) # Section 8.4.23 assert MT(besselk(a, 2*sqrt(x)), x, s) == \ (gamma( s - a/2)*gamma(s + a/2)/2, (Max(-re(a)/2, re(a)/2), oo), True) assert MT(besselj(a, 2*sqrt(2*sqrt(x)))*besselk( a, 2*sqrt(2*sqrt(x))), x, s) == (4**(-s)*gamma(2*s)* gamma(a/2 + s)/(2*gamma(a/2 - s + 1)), (Max(0, -re(a)/2), oo), True) # TODO bessely(a, x)*besselk(a, x) is a mess assert MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s) == \ (gamma(s)*gamma( a + s)*gamma(-s + S.Half)/(2*sqrt(pi)*gamma(a - s + 1)), (Max(-re(a), 0), S.Half), True) assert MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s) == \ (2**(2*s - 1)*gamma(-2*s + 1)*gamma(-a/2 + b/2 + s)* \ gamma(a/2 + b/2 + s)/(gamma(-a/2 + b/2 - s + 1)* \ gamma(a/2 + b/2 - s + 1)), (Max(-re(a)/2 - re(b)/2, \ re(a)/2 - re(b)/2), S.Half), True) # TODO products of besselk are a mess mt = MT(exp(-x/2)*besselk(a, x/2), x, s) mt0 = gammasimp(trigsimp(gammasimp(mt[0].expand(func=True)))) assert mt0 == 2*pi**Rational(3, 2)*cos(pi*s)*gamma(-s + S.Half)/( (cos(2*pi*a) - cos(2*pi*s))*gamma(-a - s + 1)*gamma(a - s + 1)) assert mt[1:] == ((Max(-re(a), re(a)), oo), True) # TODO exp(x/2)*besselk(a, x/2) [etc] cannot currently be done # TODO various strange products of special orders @slow def test_expint(): from sympy import E1, expint, Max, re, lerchphi, Symbol, simplify, Si, Ci, Ei aneg = Symbol('a', negative=True) u = Symbol('u', polar=True) assert mellin_transform(E1(x), x, s) == (gamma(s)/s, (0, oo), True) assert inverse_mellin_transform(gamma(s)/s, s, x, (0, oo)).rewrite(expint).expand() == E1(x) assert mellin_transform(expint(a, x), x, s) == \ (gamma(s)/(a + s - 1), (Max(1 - re(a), 0), oo), True) # XXX IMT has hickups with complicated strips ... assert simplify(unpolarify( inverse_mellin_transform(gamma(s)/(aneg + s - 1), s, x, (1 - aneg, oo)).rewrite(expint).expand(func=True))) == \ expint(aneg, x) assert mellin_transform(Si(x), x, s) == \ (-2**s*sqrt(pi)*gamma(s/2 + S.Half)/( 2*s*gamma(-s/2 + 1)), (-1, 0), True) assert inverse_mellin_transform(-2**s*sqrt(pi)*gamma((s + 1)/2) /(2*s*gamma(-s/2 + 1)), s, x, (-1, 0)) \ == Si(x) assert mellin_transform(Ci(sqrt(x)), x, s) == \ (-2**(2*s - 1)*sqrt(pi)*gamma(s)/(s*gamma(-s + S.Half)), (0, 1), True) assert inverse_mellin_transform( -4**s*sqrt(pi)*gamma(s)/(2*s*gamma(-s + S.Half)), s, u, (0, 1)).expand() == Ci(sqrt(u)) # TODO LT of Si, Shi, Chi is a mess ... assert laplace_transform(Ci(x), x, s) == (-log(1 + s**2)/2/s, 0, True) assert laplace_transform(expint(a, x), x, s) == \ (lerchphi(s*exp_polar(I*pi), 1, a), 0, re(a) > S.Zero) assert laplace_transform(expint(1, x), x, s) == (log(s + 1)/s, 0, True) assert laplace_transform(expint(2, x), x, s) == \ ((s - log(s + 1))/s**2, 0, True) assert inverse_laplace_transform(-log(1 + s**2)/2/s, s, u).expand() == \ Heaviside(u)*Ci(u) assert inverse_laplace_transform(log(s + 1)/s, s, x).rewrite(expint) == \ Heaviside(x)*E1(x) assert inverse_laplace_transform((s - log(s + 1))/s**2, s, x).rewrite(expint).expand() == \ (expint(2, x)*Heaviside(x)).rewrite(Ei).rewrite(expint).expand() @slow def test_inverse_mellin_transform(): from sympy import (sin, simplify, Max, Min, expand, powsimp, exp_polar, cos, cot) IMT = inverse_mellin_transform assert IMT(gamma(s), s, x, (0, oo)) == exp(-x) assert IMT(gamma(-s), s, x, (-oo, 0)) == exp(-1/x) assert simplify(IMT(s/(2*s**2 - 2), s, x, (2, oo))) == \ (x**2 + 1)*Heaviside(1 - x)/(4*x) # test passing "None" assert IMT(1/(s**2 - 1), s, x, (-1, None)) == \ -x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x) assert IMT(1/(s**2 - 1), s, x, (None, 1)) == \ -x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x) # test expansion of sums assert IMT(gamma(s) + gamma(s - 1), s, x, (1, oo)) == (x + 1)*exp(-x)/x # test factorisation of polys r = symbols('r', real=True) assert IMT(1/(s**2 + 1), s, exp(-x), (None, oo) ).subs(x, r).rewrite(sin).simplify() \ == sin(r)*Heaviside(1 - exp(-r)) # test multiplicative substitution _a, _b = symbols('a b', positive=True) assert IMT(_b**(-s/_a)*factorial(s/_a)/s, s, x, (0, oo)) == exp(-_b*x**_a) assert IMT(factorial(_a/_b + s/_b)/(_a + s), s, x, (-_a, oo)) == x**_a*exp(-x**_b) def simp_pows(expr): return simplify(powsimp(expand_mul(expr, deep=False), force=True)).replace(exp_polar, exp) # Now test the inverses of all direct transforms tested above # Section 8.4.2 nu = symbols('nu', real=True) assert IMT(-1/(nu + s), s, x, (-oo, None)) == x**nu*Heaviside(x - 1) assert IMT(1/(nu + s), s, x, (None, oo)) == x**nu*Heaviside(1 - x) assert simp_pows(IMT(gamma(beta)*gamma(s)/gamma(s + beta), s, x, (0, oo))) \ == (1 - x)**(beta - 1)*Heaviside(1 - x) assert simp_pows(IMT(gamma(beta)*gamma(1 - beta - s)/gamma(1 - s), s, x, (-oo, None))) \ == (x - 1)**(beta - 1)*Heaviside(x - 1) assert simp_pows(IMT(gamma(s)*gamma(rho - s)/gamma(rho), s, x, (0, None))) \ == (1/(x + 1))**rho assert simp_pows(IMT(d**c*d**(s - 1)*sin(pi*c) *gamma(s)*gamma(s + c)*gamma(1 - s)*gamma(1 - s - c)/pi, s, x, (Max(-re(c), 0), Min(1 - re(c), 1)))) \ == (x**c - d**c)/(x - d) assert simplify(IMT(1/sqrt(pi)*(-c/2)*gamma(s)*gamma((1 - c)/2 - s) *gamma(-c/2 - s)/gamma(1 - c - s), s, x, (0, -re(c)/2))) == \ (1 + sqrt(x + 1))**c assert simplify(IMT(2**(a + 2*s)*b**(a + 2*s - 1)*gamma(s)*gamma(1 - a - 2*s) /gamma(1 - a - s), s, x, (0, (-re(a) + 1)/2))) == \ b**(a - 1)*(sqrt(1 + x/b**2) + 1)**(a - 1)*(b**2*sqrt(1 + x/b**2) + b**2 + x)/(b**2 + x) assert simplify(IMT(-2**(c + 2*s)*c*b**(c + 2*s)*gamma(s)*gamma(-c - 2*s) / gamma(-c - s + 1), s, x, (0, -re(c)/2))) == \ b**c*(sqrt(1 + x/b**2) + 1)**c # Section 8.4.5 assert IMT(24/s**5, s, x, (0, oo)) == log(x)**4*Heaviside(1 - x) assert expand(IMT(6/s**4, s, x, (-oo, 0)), force=True) == \ log(x)**3*Heaviside(x - 1) assert IMT(pi/(s*sin(pi*s)), s, x, (-1, 0)) == log(x + 1) assert IMT(pi/(s*sin(pi*s/2)), s, x, (-2, 0)) == log(x**2 + 1) assert IMT(pi/(s*sin(2*pi*s)), s, x, (Rational(-1, 2), 0)) == log(sqrt(x) + 1) assert IMT(pi/(s*sin(pi*s)), s, x, (0, 1)) == log(1 + 1/x) # TODO def mysimp(expr): from sympy import expand, logcombine, powsimp return expand( powsimp(logcombine(expr, force=True), force=True, deep=True), force=True).replace(exp_polar, exp) assert mysimp(mysimp(IMT(pi/(s*tan(pi*s)), s, x, (-1, 0)))) in [ log(1 - x)*Heaviside(1 - x) + log(x - 1)*Heaviside(x - 1), log(x)*Heaviside(x - 1) + log(1 - 1/x)*Heaviside(x - 1) + log(-x + 1)*Heaviside(-x + 1)] # test passing cot assert mysimp(IMT(pi*cot(pi*s)/s, s, x, (0, 1))) in [ log(1/x - 1)*Heaviside(1 - x) + log(1 - 1/x)*Heaviside(x - 1), -log(x)*Heaviside(-x + 1) + log(1 - 1/x)*Heaviside(x - 1) + log(-x + 1)*Heaviside(-x + 1), ] # 8.4.14 assert IMT(-gamma(s + S.Half)/(sqrt(pi)*s), s, x, (Rational(-1, 2), 0)) == \ erf(sqrt(x)) # 8.4.19 assert simplify(IMT(gamma(a/2 + s)/gamma(a/2 - s + 1), s, x, (-re(a)/2, Rational(3, 4)))) \ == besselj(a, 2*sqrt(x)) assert simplify(IMT(2**a*gamma(S.Half - 2*s)*gamma(s + (a + 1)/2) / (gamma(1 - s - a/2)*gamma(1 - 2*s + a)), s, x, (-(re(a) + 1)/2, Rational(1, 4)))) == \ sin(sqrt(x))*besselj(a, sqrt(x)) assert simplify(IMT(2**a*gamma(a/2 + s)*gamma(S.Half - 2*s) / (gamma(S.Half - s - a/2)*gamma(1 - 2*s + a)), s, x, (-re(a)/2, Rational(1, 4)))) == \ cos(sqrt(x))*besselj(a, sqrt(x)) # TODO this comes out as an amazing mess, but simplifies nicely assert simplify(IMT(gamma(a + s)*gamma(S.Half - s) / (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)), s, x, (-re(a), S.Half))) == \ besselj(a, sqrt(x))**2 assert simplify(IMT(gamma(s)*gamma(S.Half - s) / (sqrt(pi)*gamma(1 - s - a)*gamma(1 + a - s)), s, x, (0, S.Half))) == \ besselj(-a, sqrt(x))*besselj(a, sqrt(x)) assert simplify(IMT(4**s*gamma(-2*s + 1)*gamma(a/2 + b/2 + s) / (gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1) *gamma(a/2 + b/2 - s + 1)), s, x, (-(re(a) + re(b))/2, S.Half))) == \ besselj(a, sqrt(x))*besselj(b, sqrt(x)) # Section 8.4.20 # TODO this can be further simplified! assert simplify(IMT(-2**(2*s)*cos(pi*a/2 - pi*b/2 + pi*s)*gamma(-2*s + 1) * gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s) / (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)), s, x, (Max(-re(a)/2 - re(b)/2, -re(a)/2 + re(b)/2), S.Half))) == \ besselj(a, sqrt(x))*-(besselj(-b, sqrt(x)) - besselj(b, sqrt(x))*cos(pi*b))/sin(pi*b) # TODO more # for coverage assert IMT(pi/cos(pi*s), s, x, (0, S.Half)) == sqrt(x)/(x + 1) @slow def test_laplace_transform(): from sympy import fresnels, fresnelc, DiracDelta LT = laplace_transform a, b, c, = symbols('a b c', positive=True) t = symbols('t') w = Symbol("w") f = Function("f") # Test unevaluated form assert laplace_transform(f(t), t, w) == LaplaceTransform(f(t), t, w) assert inverse_laplace_transform( f(w), w, t, plane=0) == InverseLaplaceTransform(f(w), w, t, 0) # test a bug spos = symbols('s', positive=True) assert LT(exp(t), t, spos)[:2] == (1/(spos - 1), 1) # basic tests from wikipedia assert LT((t - a)**b*exp(-c*(t - a))*Heaviside(t - a), t, s) == \ ((s + c)**(-b - 1)*exp(-a*s)*gamma(b + 1), -c, True) assert LT(t**a, t, s) == (s**(-a - 1)*gamma(a + 1), 0, True) assert LT(Heaviside(t), t, s) == (1/s, 0, True) assert LT(Heaviside(t - a), t, s) == (exp(-a*s)/s, 0, True) assert LT(1 - exp(-a*t), t, s) == (a/(s*(a + s)), 0, True) assert LT((exp(2*t) - 1)*exp(-b - t)*Heaviside(t)/2, t, s, noconds=True) \ == exp(-b)/(s**2 - 1) assert LT(exp(t), t, s)[:2] == (1/(s - 1), 1) assert LT(exp(2*t), t, s)[:2] == (1/(s - 2), 2) assert LT(exp(a*t), t, s)[:2] == (1/(s - a), a) assert LT(log(t/a), t, s) == ((log(a*s) + EulerGamma)/s/-1, 0, True) assert LT(erf(t), t, s) == (erfc(s/2)*exp(s**2/4)/s, 0, True) assert LT(sin(a*t), t, s) == (a/(a**2 + s**2), 0, True) assert LT(cos(a*t), t, s) == (s/(a**2 + s**2), 0, True) # TODO would be nice to have these come out better assert LT(exp(-a*t)*sin(b*t), t, s) == (b/(b**2 + (a + s)**2), -a, True) assert LT(exp(-a*t)*cos(b*t), t, s) == \ ((a + s)/(b**2 + (a + s)**2), -a, True) assert LT(besselj(0, t), t, s) == (1/sqrt(1 + s**2), 0, True) assert LT(besselj(1, t), t, s) == (1 - 1/sqrt(1 + 1/s**2), 0, True) # TODO general order works, but is a *mess* # TODO besseli also works, but is an even greater mess # test a bug in conditions processing # TODO the auxiliary condition should be recognised/simplified assert LT(exp(t)*cos(t), t, s)[:-1] in [ ((s - 1)/(s**2 - 2*s + 2), -oo), ((s - 1)/((s - 1)**2 + 1), -oo), ] # DiracDelta function: standard cases assert LT(DiracDelta(t), t, s) == (1, -oo, True) assert LT(DiracDelta(a*t), t, s) == (1/a, -oo, True) assert LT(DiracDelta(t/42), t, s) == (42, -oo, True) assert LT(DiracDelta(t+42), t, s) == (0, -oo, True) assert LT(DiracDelta(t)+DiracDelta(t-42), t, s) == \ (1 + exp(-42*s), -oo, True) assert LT(DiracDelta(t)-a*exp(-a*t), t, s) == (-a/(a + s) + 1, 0, True) assert LT(exp(-t)*(DiracDelta(t)+DiracDelta(t-42)), t, s) == \ (exp(-42*s - 42) + 1, -oo, True) # Collection of cases that cannot be fully evaluated and/or would catch # some common implementation errors assert LT(DiracDelta(t**2), t, s) == LaplaceTransform(DiracDelta(t**2), t, s) assert LT(DiracDelta(t**2 - 1), t, s) == (exp(-s)/2, -oo, True) assert LT(DiracDelta(t*(1 - t)), t, s) == \ LaplaceTransform(DiracDelta(-t**2 + t), t, s) assert LT((DiracDelta(t) + 1)*(DiracDelta(t - 1) + 1), t, s) == \ (LaplaceTransform(DiracDelta(t)*DiracDelta(t - 1), t, s) + \ 1 + exp(-s) + 1/s, 0, True) assert LT(DiracDelta(2*t - 2*exp(a)), t, s) == \ (exp(-s*exp(a))/2, -oo, True) # Fresnel functions assert laplace_transform(fresnels(t), t, s) == \ ((-sin(s**2/(2*pi))*fresnels(s/pi) + sin(s**2/(2*pi))/2 - cos(s**2/(2*pi))*fresnelc(s/pi) + cos(s**2/(2*pi))/2)/s, 0, True) assert laplace_transform(fresnelc(t), t, s) == ( ((2*sin(s**2/(2*pi))*fresnelc(s/pi) - 2*cos(s**2/(2*pi))*fresnels(s/pi) + sqrt(2)*cos(s**2/(2*pi) + pi/4))/(2*s), 0, True)) # What is this testing: Ne(1/s, 1) & (0 < cos(Abs(periodic_argument(s, oo)))*Abs(s) - 1) Mt = Matrix([[exp(t), t*exp(-t)], [t*exp(-t), exp(t)]]) Ms = Matrix([[ 1/(s - 1), (s + 1)**(-2)], [(s + 1)**(-2), 1/(s - 1)]]) # The default behaviour for Laplace tranform of a Matrix returns a Matrix # of Tuples and is deprecated: with warns_deprecated_sympy(): Ms_conds = Matrix([[(1/(s - 1), 1, s > 1), ((s + 1)**(-2), 0, True)], [((s + 1)**(-2), 0, True), (1/(s - 1), 1, s > 1)]]) with warns_deprecated_sympy(): assert LT(Mt, t, s) == Ms_conds # The new behavior is to return a tuple of a Matrix and the convergence # conditions for the matrix as a whole: assert LT(Mt, t, s, legacy_matrix=False) == (Ms, 1, s > 1) # With noconds=True the transformed matrix is returned without conditions # either way: assert LT(Mt, t, s, noconds=True) == Ms assert LT(Mt, t, s, legacy_matrix=False, noconds=True) == Ms @slow def test_issue_8368_7173(): LT = laplace_transform # hyperbolic assert LT(sinh(x), x, s) == (1/(s**2 - 1), 1, s > 1) assert LT(cosh(x), x, s) == (s/(s**2 - 1), 1, s > 1) assert LT(sinh(x + 3), x, s) == ( (-s + (s + 1)*exp(6) + 1)*exp(-3)/(s - 1)/(s + 1)/2, 1, s > 1) assert LT(sinh(x)*cosh(x), x, s) == ( 1/(s**2 - 4), 2, s > 2) # trig (make sure they are not being rewritten in terms of exp) assert LT(cos(x + 3), x, s) == ((s*cos(3) - sin(3))/(s**2 + 1), 0, True) @slow def test_inverse_laplace_transform(): from sympy import sinh, cosh, besselj, besseli, simplify, factor_terms,\ DiracDelta ILT = inverse_laplace_transform a, b, c, = symbols('a b c', positive=True) t = symbols('t') def simp_hyp(expr): return factor_terms(expand_mul(expr)).rewrite(sin) assert ILT(1, s, t) == DiracDelta(t) assert ILT(1/s, s, t) == Heaviside(t) assert ILT(a/(a + s), s, t) == a*exp(-a*t)*Heaviside(t) assert ILT(s/(a + s), s, t) == -a*exp(-a*t)*Heaviside(t) + DiracDelta(t) assert ILT((a + s)**(-2), s, t) == t*exp(-a*t)*Heaviside(t) assert ILT((a + s)**(-5), s, t) == t**4*exp(-a*t)*Heaviside(t)/24 assert ILT(a/(a**2 + s**2), s, t) == sin(a*t)*Heaviside(t) assert ILT(s/(s**2 + a**2), s, t) == cos(a*t)*Heaviside(t) assert ILT(b/(b**2 + (a + s)**2), s, t) == exp(-a*t)*sin(b*t)*Heaviside(t) assert ILT(b*s/(b**2 + (a + s)**2), s, t) +\ (a*sin(b*t) - b*cos(b*t))*exp(-a*t)*Heaviside(t) == 0 assert ILT(exp(-a*s)/s, s, t) == Heaviside(-a + t) assert ILT(exp(-a*s)/(b + s), s, t) == exp(b*(a - t))*Heaviside(-a + t) assert ILT((b + s)/(a**2 + (b + s)**2), s, t) == \ exp(-b*t)*cos(a*t)*Heaviside(t) assert ILT(exp(-a*s)/s**b, s, t) == \ (-a + t)**(b - 1)*Heaviside(-a + t)/gamma(b) assert ILT(exp(-a*s)/sqrt(s**2 + 1), s, t) == \ Heaviside(-a + t)*besselj(0, a - t) assert ILT(1/(s*sqrt(s + 1)), s, t) == Heaviside(t)*erf(sqrt(t)) assert ILT(1/(s**2*(s**2 + 1)), s, t) == (t - sin(t))*Heaviside(t) assert ILT(s**2/(s**2 + 1), s, t) == -sin(t)*Heaviside(t) + DiracDelta(t) assert ILT(1 - 1/(s**2 + 1), s, t) == -sin(t)*Heaviside(t) + DiracDelta(t) assert ILT(1/s**2, s, t) == t*Heaviside(t) assert ILT(1/s**5, s, t) == t**4*Heaviside(t)/24 assert simp_hyp(ILT(a/(s**2 - a**2), s, t)) == sinh(a*t)*Heaviside(t) assert simp_hyp(ILT(s/(s**2 - a**2), s, t)) == cosh(a*t)*Heaviside(t) # TODO sinh/cosh shifted come out a mess. also delayed trig is a mess # TODO should this simplify further? assert ILT(exp(-a*s)/s**b, s, t) == \ (t - a)**(b - 1)*Heaviside(t - a)/gamma(b) assert ILT(exp(-a*s)/sqrt(1 + s**2), s, t) == \ Heaviside(t - a)*besselj(0, a - t) # note: besselj(0, x) is even # XXX ILT turns these branch factor into trig functions ... assert simplify(ILT(a**b*(s + sqrt(s**2 - a**2))**(-b)/sqrt(s**2 - a**2), s, t).rewrite(exp)) == \ Heaviside(t)*besseli(b, a*t) assert ILT(a**b*(s + sqrt(s**2 + a**2))**(-b)/sqrt(s**2 + a**2), s, t).rewrite(exp) == \ Heaviside(t)*besselj(b, a*t) assert ILT(1/(s*sqrt(s + 1)), s, t) == Heaviside(t)*erf(sqrt(t)) # TODO can we make erf(t) work? assert ILT(1/(s**2*(s**2 + 1)),s,t) == (t - sin(t))*Heaviside(t) assert ILT( (s * eye(2) - Matrix([[1, 0], [0, 2]])).inv(), s, t) ==\ Matrix([[exp(t)*Heaviside(t), 0], [0, exp(2*t)*Heaviside(t)]]) def test_inverse_laplace_transform_delta(): from sympy import DiracDelta ILT = inverse_laplace_transform t = symbols('t') assert ILT(2, s, t) == 2*DiracDelta(t) assert ILT(2*exp(3*s) - 5*exp(-7*s), s, t) == \ 2*DiracDelta(t + 3) - 5*DiracDelta(t - 7) a = cos(sin(7)/2) assert ILT(a*exp(-3*s), s, t) == a*DiracDelta(t - 3) assert ILT(exp(2*s), s, t) == DiracDelta(t + 2) r = Symbol('r', real=True) assert ILT(exp(r*s), s, t) == DiracDelta(t + r) def test_inverse_laplace_transform_delta_cond(): from sympy import DiracDelta, Eq, im, Heaviside ILT = inverse_laplace_transform t = symbols('t') r = Symbol('r', real=True) assert ILT(exp(r*s), s, t, noconds=False) == (DiracDelta(t + r), True) z = Symbol('z') assert ILT(exp(z*s), s, t, noconds=False) == \ (DiracDelta(t + z), Eq(im(z), 0)) # inversion does not exist: verify it doesn't evaluate to DiracDelta for z in (Symbol('z', extended_real=False), Symbol('z', imaginary=True, zero=False)): f = ILT(exp(z*s), s, t, noconds=False) f = f[0] if isinstance(f, tuple) else f assert f.func != DiracDelta # issue 15043 assert ILT(1/s + exp(r*s)/s, s, t, noconds=False) == ( Heaviside(t) + Heaviside(r + t), True) def test_fourier_transform(): from sympy import simplify, expand, expand_complex, factor, expand_trig FT = fourier_transform IFT = inverse_fourier_transform def simp(x): return simplify(expand_trig(expand_complex(expand(x)))) def sinc(x): return sin(pi*x)/(pi*x) k = symbols('k', real=True) f = Function("f") # TODO for this to work with real a, need to expand abs(a*x) to abs(a)*abs(x) a = symbols('a', positive=True) b = symbols('b', positive=True) posk = symbols('posk', positive=True) # Test unevaluated form assert fourier_transform(f(x), x, k) == FourierTransform(f(x), x, k) assert inverse_fourier_transform( f(k), k, x) == InverseFourierTransform(f(k), k, x) # basic examples from wikipedia assert simp(FT(Heaviside(1 - abs(2*a*x)), x, k)) == sinc(k/a)/a # TODO IFT is a *mess* assert simp(FT(Heaviside(1 - abs(a*x))*(1 - abs(a*x)), x, k)) == sinc(k/a)**2/a # TODO IFT assert factor(FT(exp(-a*x)*Heaviside(x), x, k), extension=I) == \ 1/(a + 2*pi*I*k) # NOTE: the ift comes out in pieces assert IFT(1/(a + 2*pi*I*x), x, posk, noconds=False) == (exp(-a*posk), True) assert IFT(1/(a + 2*pi*I*x), x, -posk, noconds=False) == (0, True) assert IFT(1/(a + 2*pi*I*x), x, symbols('k', negative=True), noconds=False) == (0, True) # TODO IFT without factoring comes out as meijer g assert factor(FT(x*exp(-a*x)*Heaviside(x), x, k), extension=I) == \ 1/(a + 2*pi*I*k)**2 assert FT(exp(-a*x)*sin(b*x)*Heaviside(x), x, k) == \ b/(b**2 + (a + 2*I*pi*k)**2) assert FT(exp(-a*x**2), x, k) == sqrt(pi)*exp(-pi**2*k**2/a)/sqrt(a) assert IFT(sqrt(pi/a)*exp(-(pi*k)**2/a), k, x) == exp(-a*x**2) assert FT(exp(-a*abs(x)), x, k) == 2*a/(a**2 + 4*pi**2*k**2) # TODO IFT (comes out as meijer G) # TODO besselj(n, x), n an integer > 0 actually can be done... # TODO are there other common transforms (no distributions!)? def test_sine_transform(): from sympy import EulerGamma t = symbols("t") w = symbols("w") a = symbols("a") f = Function("f") # Test unevaluated form assert sine_transform(f(t), t, w) == SineTransform(f(t), t, w) assert inverse_sine_transform( f(w), w, t) == InverseSineTransform(f(w), w, t) assert sine_transform(1/sqrt(t), t, w) == 1/sqrt(w) assert inverse_sine_transform(1/sqrt(w), w, t) == 1/sqrt(t) assert sine_transform((1/sqrt(t))**3, t, w) == 2*sqrt(w) assert sine_transform(t**(-a), t, w) == 2**( -a + S.Half)*w**(a - 1)*gamma(-a/2 + 1)/gamma((a + 1)/2) assert inverse_sine_transform(2**(-a + S( 1)/2)*w**(a - 1)*gamma(-a/2 + 1)/gamma(a/2 + S.Half), w, t) == t**(-a) assert sine_transform( exp(-a*t), t, w) == sqrt(2)*w/(sqrt(pi)*(a**2 + w**2)) assert inverse_sine_transform( sqrt(2)*w/(sqrt(pi)*(a**2 + w**2)), w, t) == exp(-a*t) assert sine_transform( log(t)/t, t, w) == -sqrt(2)*sqrt(pi)*(log(w**2) + 2*EulerGamma)/4 assert sine_transform( t*exp(-a*t**2), t, w) == sqrt(2)*w*exp(-w**2/(4*a))/(4*a**Rational(3, 2)) assert inverse_sine_transform( sqrt(2)*w*exp(-w**2/(4*a))/(4*a**Rational(3, 2)), w, t) == t*exp(-a*t**2) def test_cosine_transform(): from sympy import Si, Ci t = symbols("t") w = symbols("w") a = symbols("a") f = Function("f") # Test unevaluated form assert cosine_transform(f(t), t, w) == CosineTransform(f(t), t, w) assert inverse_cosine_transform( f(w), w, t) == InverseCosineTransform(f(w), w, t) assert cosine_transform(1/sqrt(t), t, w) == 1/sqrt(w) assert inverse_cosine_transform(1/sqrt(w), w, t) == 1/sqrt(t) assert cosine_transform(1/( a**2 + t**2), t, w) == sqrt(2)*sqrt(pi)*exp(-a*w)/(2*a) assert cosine_transform(t**( -a), t, w) == 2**(-a + S.Half)*w**(a - 1)*gamma((-a + 1)/2)/gamma(a/2) assert inverse_cosine_transform(2**(-a + S( 1)/2)*w**(a - 1)*gamma(-a/2 + S.Half)/gamma(a/2), w, t) == t**(-a) assert cosine_transform( exp(-a*t), t, w) == sqrt(2)*a/(sqrt(pi)*(a**2 + w**2)) assert inverse_cosine_transform( sqrt(2)*a/(sqrt(pi)*(a**2 + w**2)), w, t) == exp(-a*t) assert cosine_transform(exp(-a*sqrt(t))*cos(a*sqrt( t)), t, w) == a*exp(-a**2/(2*w))/(2*w**Rational(3, 2)) assert cosine_transform(1/(a + t), t, w) == sqrt(2)*( (-2*Si(a*w) + pi)*sin(a*w)/2 - cos(a*w)*Ci(a*w))/sqrt(pi) assert inverse_cosine_transform(sqrt(2)*meijerg(((S.Half, 0), ()), ( (S.Half, 0, 0), (S.Half,)), a**2*w**2/4)/(2*pi), w, t) == 1/(a + t) assert cosine_transform(1/sqrt(a**2 + t**2), t, w) == sqrt(2)*meijerg( ((S.Half,), ()), ((0, 0), (S.Half,)), a**2*w**2/4)/(2*sqrt(pi)) assert inverse_cosine_transform(sqrt(2)*meijerg(((S.Half,), ()), ((0, 0), (S.Half,)), a**2*w**2/4)/(2*sqrt(pi)), w, t) == 1/(t*sqrt(a**2/t**2 + 1)) def test_hankel_transform(): from sympy import gamma, sqrt, exp r = Symbol("r") k = Symbol("k") nu = Symbol("nu") m = Symbol("m") a = symbols("a") assert hankel_transform(1/r, r, k, 0) == 1/k assert inverse_hankel_transform(1/k, k, r, 0) == 1/r assert hankel_transform( 1/r**m, r, k, 0) == 2**(-m + 1)*k**(m - 2)*gamma(-m/2 + 1)/gamma(m/2) assert inverse_hankel_transform( 2**(-m + 1)*k**(m - 2)*gamma(-m/2 + 1)/gamma(m/2), k, r, 0) == r**(-m) assert hankel_transform(1/r**m, r, k, nu) == ( 2*2**(-m)*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/gamma(m/2 + nu/2)) assert inverse_hankel_transform(2**(-m + 1)*k**( m - 2)*gamma(-m/2 + nu/2 + 1)/gamma(m/2 + nu/2), k, r, nu) == r**(-m) assert hankel_transform(r**nu*exp(-a*r), r, k, nu) == \ 2**(nu + 1)*a*k**(-nu - 3)*(a**2/k**2 + 1)**(-nu - S( 3)/2)*gamma(nu + Rational(3, 2))/sqrt(pi) assert inverse_hankel_transform( 2**(nu + 1)*a*k**(-nu - 3)*(a**2/k**2 + 1)**(-nu - Rational(3, 2))*gamma( nu + Rational(3, 2))/sqrt(pi), k, r, nu) == r**nu*exp(-a*r) def test_issue_7181(): assert mellin_transform(1/(1 - x), x, s) != None def test_issue_8882(): # This is the original test. # from sympy import diff, Integral, integrate # r = Symbol('r') # psi = 1/r*sin(r)*exp(-(a0*r)) # h = -1/2*diff(psi, r, r) - 1/r*psi # f = 4*pi*psi*h*r**2 # assert integrate(f, (r, -oo, 3), meijerg=True).has(Integral) == True # To save time, only the critical part is included. F = -a**(-s + 1)*(4 + 1/a**2)**(-s/2)*sqrt(1/a**2)*exp(-s*I*pi)* \ sin(s*atan(sqrt(1/a**2)/2))*gamma(s) raises(IntegralTransformError, lambda: inverse_mellin_transform(F, s, x, (-1, oo), **{'as_meijerg': True, 'needeval': True})) def test_issue_7173(): from sympy import cse x0, x1, x2, x3 = symbols('x:4') ans = laplace_transform(sinh(a*x)*cosh(a*x), x, s) r, e = cse(ans) assert r == [ (x0, arg(a)), (x1, Abs(x0)), (x2, pi/2), (x3, Abs(x0 + pi))] assert e == [ a/(-4*a**2 + s**2), 0, ((x1 <= x2) | (x1 < x2)) & ((x3 <= x2) | (x3 < x2))] def test_issue_8514(): from sympy import simplify a, b, c, = symbols('a b c', positive=True) t = symbols('t', positive=True) ft = simplify(inverse_laplace_transform(1/(a*s**2+b*s+c),s, t)) assert ft == (I*exp(t*cos(atan2(0, -4*a*c + b**2)/2)*sqrt(Abs(4*a*c - b**2))/a)*sin(t*sin(atan2(0, -4*a*c + b**2)/2)*sqrt(Abs( 4*a*c - b**2))/(2*a)) + exp(t*cos(atan2(0, -4*a*c + b**2) /2)*sqrt(Abs(4*a*c - b**2))/a)*cos(t*sin(atan2(0, -4*a*c + b**2)/2)*sqrt(Abs(4*a*c - b**2))/(2*a)) + I*sin(t*sin( atan2(0, -4*a*c + b**2)/2)*sqrt(Abs(4*a*c - b**2))/(2*a)) - cos(t*sin(atan2(0, -4*a*c + b**2)/2)*sqrt(Abs(4*a*c - b**2))/(2*a)))*exp(-t*(b + cos(atan2(0, -4*a*c + b**2)/2) *sqrt(Abs(4*a*c - b**2)))/(2*a))/sqrt(-4*a*c + b**2) def test_issue_12591(): x, y = symbols("x y", real=True) assert fourier_transform(exp(x), x, y) == FourierTransform(exp(x), x, y) def test_issue_14692(): b = Symbol('b', negative=True) assert laplace_transform(1/(I*x - b), x, s) == \ (-I*exp(I*b*s)*expint(1, b*s*exp_polar(I*pi/2)), 0, True)
dd7da38e3205a9529bb4d3e44fc708032f5555d3ba7316f60945ecf8985ab6b7
"""Test whether all elements of cls.args are instances of Basic. """ # NOTE: keep tests sorted by (module, class name) key. If a class can't # be instantiated, add it here anyway with @SKIP("abstract class) (see # e.g. Function). import os import re from sympy import (Basic, S, symbols, sqrt, sin, oo, Interval, exp, Lambda, pi, Eq, log, Function, Rational, Q) from sympy.testing.pytest import XFAIL, SKIP a, b, c, x, y, z = symbols('a,b,c,x,y,z') whitelist = [ "sympy.assumptions.predicates", # tested by test_predicates() "sympy.assumptions.relation.equality", # tested by test_predicates() ] def test_all_classes_are_tested(): this = os.path.split(__file__)[0] path = os.path.join(this, os.pardir, os.pardir) sympy_path = os.path.abspath(path) prefix = os.path.split(sympy_path)[0] + os.sep re_cls = re.compile(r"^class ([A-Za-z][A-Za-z0-9_]*)\s*\(", re.MULTILINE) modules = {} for root, dirs, files in os.walk(sympy_path): module = root.replace(prefix, "").replace(os.sep, ".") for file in files: if file.startswith(("_", "test_", "bench_")): continue if not file.endswith(".py"): continue with open(os.path.join(root, file), encoding='utf-8') as f: text = f.read() submodule = module + '.' + file[:-3] if any(submodule.startswith(wpath) for wpath in whitelist): continue names = re_cls.findall(text) if not names: continue try: mod = __import__(submodule, fromlist=names) except ImportError: continue def is_Basic(name): cls = getattr(mod, name) if hasattr(cls, '_sympy_deprecated_func'): cls = cls._sympy_deprecated_func if not isinstance(cls, type): # check instance of singleton class with same name cls = type(cls) return issubclass(cls, Basic) names = list(filter(is_Basic, names)) if names: modules[submodule] = names ns = globals() failed = [] for module, names in modules.items(): mod = module.replace('.', '__') for name in names: test = 'test_' + mod + '__' + name if test not in ns: failed.append(module + '.' + name) assert not failed, "Missing classes: %s. Please add tests for these to sympy/core/tests/test_args.py." % ", ".join(failed) def _test_args(obj): all_basic = all(isinstance(arg, Basic) for arg in obj.args) # Ideally obj.func(*obj.args) would always recreate the object, but for # now, we only require it for objects with non-empty .args recreatable = not obj.args or obj.func(*obj.args) == obj return all_basic and recreatable def test_sympy__assumptions__assume__AppliedPredicate(): from sympy.assumptions.assume import AppliedPredicate, Predicate assert _test_args(AppliedPredicate(Predicate("test"), 2)) assert _test_args(Q.is_true(True)) @SKIP("abstract class") def test_sympy__assumptions__assume__Predicate(): pass def test_predicates(): predicates = [ getattr(Q, attr) for attr in Q.__class__.__dict__ if not attr.startswith('__')] for p in predicates: assert _test_args(p) def test_sympy__assumptions__assume__UndefinedPredicate(): from sympy.assumptions.assume import Predicate assert _test_args(Predicate("test")) @SKIP('abstract class') def test_sympy__assumptions__relation__binrel__BinaryRelation(): pass def test_sympy__assumptions__relation__binrel__AppliedBinaryRelation(): assert _test_args(Q.eq(1, 2)) def test_sympy__assumptions__wrapper__AssumptionsWrapper(): from sympy.assumptions.wrapper import AssumptionsWrapper assert _test_args(AssumptionsWrapper(x, Q.positive(x))) @SKIP("abstract Class") def test_sympy__codegen__ast__AssignmentBase(): from sympy.codegen.ast import AssignmentBase assert _test_args(AssignmentBase(x, 1)) @SKIP("abstract Class") def test_sympy__codegen__ast__AugmentedAssignment(): from sympy.codegen.ast import AugmentedAssignment assert _test_args(AugmentedAssignment(x, 1)) def test_sympy__codegen__ast__AddAugmentedAssignment(): from sympy.codegen.ast import AddAugmentedAssignment assert _test_args(AddAugmentedAssignment(x, 1)) def test_sympy__codegen__ast__SubAugmentedAssignment(): from sympy.codegen.ast import SubAugmentedAssignment assert _test_args(SubAugmentedAssignment(x, 1)) def test_sympy__codegen__ast__MulAugmentedAssignment(): from sympy.codegen.ast import MulAugmentedAssignment assert _test_args(MulAugmentedAssignment(x, 1)) def test_sympy__codegen__ast__DivAugmentedAssignment(): from sympy.codegen.ast import DivAugmentedAssignment assert _test_args(DivAugmentedAssignment(x, 1)) def test_sympy__codegen__ast__ModAugmentedAssignment(): from sympy.codegen.ast import ModAugmentedAssignment assert _test_args(ModAugmentedAssignment(x, 1)) def test_sympy__codegen__ast__CodeBlock(): from sympy.codegen.ast import CodeBlock, Assignment assert _test_args(CodeBlock(Assignment(x, 1), Assignment(y, 2))) def test_sympy__codegen__ast__For(): from sympy.codegen.ast import For, CodeBlock, AddAugmentedAssignment from sympy import Range assert _test_args(For(x, Range(10), CodeBlock(AddAugmentedAssignment(y, 1)))) def test_sympy__codegen__ast__Token(): from sympy.codegen.ast import Token assert _test_args(Token()) def test_sympy__codegen__ast__ContinueToken(): from sympy.codegen.ast import ContinueToken assert _test_args(ContinueToken()) def test_sympy__codegen__ast__BreakToken(): from sympy.codegen.ast import BreakToken assert _test_args(BreakToken()) def test_sympy__codegen__ast__NoneToken(): from sympy.codegen.ast import NoneToken assert _test_args(NoneToken()) def test_sympy__codegen__ast__String(): from sympy.codegen.ast import String assert _test_args(String('foobar')) def test_sympy__codegen__ast__QuotedString(): from sympy.codegen.ast import QuotedString assert _test_args(QuotedString('foobar')) def test_sympy__codegen__ast__Comment(): from sympy.codegen.ast import Comment assert _test_args(Comment('this is a comment')) def test_sympy__codegen__ast__Node(): from sympy.codegen.ast import Node assert _test_args(Node()) assert _test_args(Node(attrs={1, 2, 3})) def test_sympy__codegen__ast__Type(): from sympy.codegen.ast import Type assert _test_args(Type('float128')) def test_sympy__codegen__ast__IntBaseType(): from sympy.codegen.ast import IntBaseType assert _test_args(IntBaseType('bigint')) def test_sympy__codegen__ast___SizedIntType(): from sympy.codegen.ast import _SizedIntType assert _test_args(_SizedIntType('int128', 128)) def test_sympy__codegen__ast__SignedIntType(): from sympy.codegen.ast import SignedIntType assert _test_args(SignedIntType('int128_with_sign', 128)) def test_sympy__codegen__ast__UnsignedIntType(): from sympy.codegen.ast import UnsignedIntType assert _test_args(UnsignedIntType('unt128', 128)) def test_sympy__codegen__ast__FloatBaseType(): from sympy.codegen.ast import FloatBaseType assert _test_args(FloatBaseType('positive_real')) def test_sympy__codegen__ast__FloatType(): from sympy.codegen.ast import FloatType assert _test_args(FloatType('float242', 242, nmant=142, nexp=99)) def test_sympy__codegen__ast__ComplexBaseType(): from sympy.codegen.ast import ComplexBaseType assert _test_args(ComplexBaseType('positive_cmplx')) def test_sympy__codegen__ast__ComplexType(): from sympy.codegen.ast import ComplexType assert _test_args(ComplexType('complex42', 42, nmant=15, nexp=5)) def test_sympy__codegen__ast__Attribute(): from sympy.codegen.ast import Attribute assert _test_args(Attribute('noexcept')) def test_sympy__codegen__ast__Variable(): from sympy.codegen.ast import Variable, Type, value_const assert _test_args(Variable(x)) assert _test_args(Variable(y, Type('float32'), {value_const})) assert _test_args(Variable(z, type=Type('float64'))) def test_sympy__codegen__ast__Pointer(): from sympy.codegen.ast import Pointer, Type, pointer_const assert _test_args(Pointer(x)) assert _test_args(Pointer(y, type=Type('float32'))) assert _test_args(Pointer(z, Type('float64'), {pointer_const})) def test_sympy__codegen__ast__Declaration(): from sympy.codegen.ast import Declaration, Variable, Type vx = Variable(x, type=Type('float')) assert _test_args(Declaration(vx)) def test_sympy__codegen__ast__While(): from sympy.codegen.ast import While, AddAugmentedAssignment assert _test_args(While(abs(x) < 1, [AddAugmentedAssignment(x, -1)])) def test_sympy__codegen__ast__Scope(): from sympy.codegen.ast import Scope, AddAugmentedAssignment assert _test_args(Scope([AddAugmentedAssignment(x, -1)])) def test_sympy__codegen__ast__Stream(): from sympy.codegen.ast import Stream assert _test_args(Stream('stdin')) def test_sympy__codegen__ast__Print(): from sympy.codegen.ast import Print assert _test_args(Print([x, y])) assert _test_args(Print([x, y], "%d %d")) def test_sympy__codegen__ast__FunctionPrototype(): from sympy.codegen.ast import FunctionPrototype, real, Declaration, Variable inp_x = Declaration(Variable(x, type=real)) assert _test_args(FunctionPrototype(real, 'pwer', [inp_x])) def test_sympy__codegen__ast__FunctionDefinition(): from sympy.codegen.ast import FunctionDefinition, real, Declaration, Variable, Assignment inp_x = Declaration(Variable(x, type=real)) assert _test_args(FunctionDefinition(real, 'pwer', [inp_x], [Assignment(x, x**2)])) def test_sympy__codegen__ast__Return(): from sympy.codegen.ast import Return assert _test_args(Return(x)) def test_sympy__codegen__ast__FunctionCall(): from sympy.codegen.ast import FunctionCall assert _test_args(FunctionCall('pwer', [x])) def test_sympy__codegen__ast__Element(): from sympy.codegen.ast import Element assert _test_args(Element('x', range(3))) def test_sympy__codegen__cnodes__CommaOperator(): from sympy.codegen.cnodes import CommaOperator assert _test_args(CommaOperator(1, 2)) def test_sympy__codegen__cnodes__goto(): from sympy.codegen.cnodes import goto assert _test_args(goto('early_exit')) def test_sympy__codegen__cnodes__Label(): from sympy.codegen.cnodes import Label assert _test_args(Label('early_exit')) def test_sympy__codegen__cnodes__PreDecrement(): from sympy.codegen.cnodes import PreDecrement assert _test_args(PreDecrement(x)) def test_sympy__codegen__cnodes__PostDecrement(): from sympy.codegen.cnodes import PostDecrement assert _test_args(PostDecrement(x)) def test_sympy__codegen__cnodes__PreIncrement(): from sympy.codegen.cnodes import PreIncrement assert _test_args(PreIncrement(x)) def test_sympy__codegen__cnodes__PostIncrement(): from sympy.codegen.cnodes import PostIncrement assert _test_args(PostIncrement(x)) def test_sympy__codegen__cnodes__struct(): from sympy.codegen.ast import real, Variable from sympy.codegen.cnodes import struct assert _test_args(struct(declarations=[ Variable(x, type=real), Variable(y, type=real) ])) def test_sympy__codegen__cnodes__union(): from sympy.codegen.ast import float32, int32, Variable from sympy.codegen.cnodes import union assert _test_args(union(declarations=[ Variable(x, type=float32), Variable(y, type=int32) ])) def test_sympy__codegen__cxxnodes__using(): from sympy.codegen.cxxnodes import using assert _test_args(using('std::vector')) assert _test_args(using('std::vector', 'vec')) def test_sympy__codegen__fnodes__Program(): from sympy.codegen.fnodes import Program assert _test_args(Program('foobar', [])) def test_sympy__codegen__fnodes__Module(): from sympy.codegen.fnodes import Module assert _test_args(Module('foobar', [], [])) def test_sympy__codegen__fnodes__Subroutine(): from sympy.codegen.fnodes import Subroutine x = symbols('x', real=True) assert _test_args(Subroutine('foo', [x], [])) def test_sympy__codegen__fnodes__GoTo(): from sympy.codegen.fnodes import GoTo assert _test_args(GoTo([10])) assert _test_args(GoTo([10, 20], x > 1)) def test_sympy__codegen__fnodes__FortranReturn(): from sympy.codegen.fnodes import FortranReturn assert _test_args(FortranReturn(10)) def test_sympy__codegen__fnodes__Extent(): from sympy.codegen.fnodes import Extent assert _test_args(Extent()) assert _test_args(Extent(None)) assert _test_args(Extent(':')) assert _test_args(Extent(-3, 4)) assert _test_args(Extent(x, y)) def test_sympy__codegen__fnodes__use_rename(): from sympy.codegen.fnodes import use_rename assert _test_args(use_rename('loc', 'glob')) def test_sympy__codegen__fnodes__use(): from sympy.codegen.fnodes import use assert _test_args(use('modfoo', only='bar')) def test_sympy__codegen__fnodes__SubroutineCall(): from sympy.codegen.fnodes import SubroutineCall assert _test_args(SubroutineCall('foo', ['bar', 'baz'])) def test_sympy__codegen__fnodes__Do(): from sympy.codegen.fnodes import Do assert _test_args(Do([], 'i', 1, 42)) def test_sympy__codegen__fnodes__ImpliedDoLoop(): from sympy.codegen.fnodes import ImpliedDoLoop assert _test_args(ImpliedDoLoop('i', 'i', 1, 42)) def test_sympy__codegen__fnodes__ArrayConstructor(): from sympy.codegen.fnodes import ArrayConstructor assert _test_args(ArrayConstructor([1, 2, 3])) from sympy.codegen.fnodes import ImpliedDoLoop idl = ImpliedDoLoop('i', 'i', 1, 42) assert _test_args(ArrayConstructor([1, idl, 3])) def test_sympy__codegen__fnodes__sum_(): from sympy.codegen.fnodes import sum_ assert _test_args(sum_('arr')) def test_sympy__codegen__fnodes__product_(): from sympy.codegen.fnodes import product_ assert _test_args(product_('arr')) def test_sympy__codegen__numpy_nodes__logaddexp(): from sympy.codegen.numpy_nodes import logaddexp assert _test_args(logaddexp(x, y)) def test_sympy__codegen__numpy_nodes__logaddexp2(): from sympy.codegen.numpy_nodes import logaddexp2 assert _test_args(logaddexp2(x, y)) def test_sympy__codegen__scipy_nodes__cosm1(): from sympy.codegen.scipy_nodes import cosm1 assert _test_args(cosm1(x)) @XFAIL def test_sympy__combinatorics__graycode__GrayCode(): from sympy.combinatorics.graycode import GrayCode # an integer is given and returned from GrayCode as the arg assert _test_args(GrayCode(3, start='100')) assert _test_args(GrayCode(3, rank=1)) def test_sympy__combinatorics__subsets__Subset(): from sympy.combinatorics.subsets import Subset assert _test_args(Subset([0, 1], [0, 1, 2, 3])) assert _test_args(Subset(['c', 'd'], ['a', 'b', 'c', 'd'])) def test_sympy__combinatorics__permutations__Permutation(): from sympy.combinatorics.permutations import Permutation assert _test_args(Permutation([0, 1, 2, 3])) def test_sympy__combinatorics__permutations__AppliedPermutation(): from sympy.combinatorics.permutations import Permutation from sympy.combinatorics.permutations import AppliedPermutation p = Permutation([0, 1, 2, 3]) assert _test_args(AppliedPermutation(p, 1)) def test_sympy__combinatorics__perm_groups__PermutationGroup(): from sympy.combinatorics.permutations import Permutation from sympy.combinatorics.perm_groups import PermutationGroup assert _test_args(PermutationGroup([Permutation([0, 1])])) def test_sympy__combinatorics__polyhedron__Polyhedron(): from sympy.combinatorics.permutations import Permutation from sympy.combinatorics.polyhedron import Polyhedron from sympy.abc import w, x, y, z pgroup = [Permutation([[0, 1, 2], [3]]), Permutation([[0, 1, 3], [2]]), Permutation([[0, 2, 3], [1]]), Permutation([[1, 2, 3], [0]]), Permutation([[0, 1], [2, 3]]), Permutation([[0, 2], [1, 3]]), Permutation([[0, 3], [1, 2]]), Permutation([[0, 1, 2, 3]])] corners = [w, x, y, z] faces = [(w, x, y), (w, y, z), (w, z, x), (x, y, z)] assert _test_args(Polyhedron(corners, faces, pgroup)) @XFAIL def test_sympy__combinatorics__prufer__Prufer(): from sympy.combinatorics.prufer import Prufer assert _test_args(Prufer([[0, 1], [0, 2], [0, 3]], 4)) def test_sympy__combinatorics__partitions__Partition(): from sympy.combinatorics.partitions import Partition assert _test_args(Partition([1])) @XFAIL def test_sympy__combinatorics__partitions__IntegerPartition(): from sympy.combinatorics.partitions import IntegerPartition assert _test_args(IntegerPartition([1])) def test_sympy__concrete__products__Product(): from sympy.concrete.products import Product assert _test_args(Product(x, (x, 0, 10))) assert _test_args(Product(x, (x, 0, y), (y, 0, 10))) @SKIP("abstract Class") def test_sympy__concrete__expr_with_limits__ExprWithLimits(): from sympy.concrete.expr_with_limits import ExprWithLimits assert _test_args(ExprWithLimits(x, (x, 0, 10))) assert _test_args(ExprWithLimits(x*y, (x, 0, 10.),(y,1.,3))) @SKIP("abstract Class") def test_sympy__concrete__expr_with_limits__AddWithLimits(): from sympy.concrete.expr_with_limits import AddWithLimits assert _test_args(AddWithLimits(x, (x, 0, 10))) assert _test_args(AddWithLimits(x*y, (x, 0, 10),(y,1,3))) @SKIP("abstract Class") def test_sympy__concrete__expr_with_intlimits__ExprWithIntLimits(): from sympy.concrete.expr_with_intlimits import ExprWithIntLimits assert _test_args(ExprWithIntLimits(x, (x, 0, 10))) assert _test_args(ExprWithIntLimits(x*y, (x, 0, 10),(y,1,3))) def test_sympy__concrete__summations__Sum(): from sympy.concrete.summations import Sum assert _test_args(Sum(x, (x, 0, 10))) assert _test_args(Sum(x, (x, 0, y), (y, 0, 10))) def test_sympy__core__add__Add(): from sympy.core.add import Add assert _test_args(Add(x, y, z, 2)) def test_sympy__core__basic__Atom(): from sympy.core.basic import Atom assert _test_args(Atom()) def test_sympy__core__basic__Basic(): from sympy.core.basic import Basic assert _test_args(Basic()) def test_sympy__core__containers__Dict(): from sympy.core.containers import Dict assert _test_args(Dict({x: y, y: z})) def test_sympy__core__containers__Tuple(): from sympy.core.containers import Tuple assert _test_args(Tuple(x, y, z, 2)) def test_sympy__core__expr__AtomicExpr(): from sympy.core.expr import AtomicExpr assert _test_args(AtomicExpr()) def test_sympy__core__expr__Expr(): from sympy.core.expr import Expr assert _test_args(Expr()) def test_sympy__core__expr__UnevaluatedExpr(): from sympy.core.expr import UnevaluatedExpr from sympy.abc import x assert _test_args(UnevaluatedExpr(x)) def test_sympy__core__function__Application(): from sympy.core.function import Application assert _test_args(Application(1, 2, 3)) def test_sympy__core__function__AppliedUndef(): from sympy.core.function import AppliedUndef assert _test_args(AppliedUndef(1, 2, 3)) def test_sympy__core__function__Derivative(): from sympy.core.function import Derivative assert _test_args(Derivative(2, x, y, 3)) @SKIP("abstract class") def test_sympy__core__function__Function(): pass def test_sympy__core__function__Lambda(): assert _test_args(Lambda((x, y), x + y + z)) def test_sympy__core__function__Subs(): from sympy.core.function import Subs assert _test_args(Subs(x + y, x, 2)) def test_sympy__core__function__WildFunction(): from sympy.core.function import WildFunction assert _test_args(WildFunction('f')) def test_sympy__core__mod__Mod(): from sympy.core.mod import Mod assert _test_args(Mod(x, 2)) def test_sympy__core__mul__Mul(): from sympy.core.mul import Mul assert _test_args(Mul(2, x, y, z)) def test_sympy__core__numbers__Catalan(): from sympy.core.numbers import Catalan assert _test_args(Catalan()) def test_sympy__core__numbers__ComplexInfinity(): from sympy.core.numbers import ComplexInfinity assert _test_args(ComplexInfinity()) def test_sympy__core__numbers__EulerGamma(): from sympy.core.numbers import EulerGamma assert _test_args(EulerGamma()) def test_sympy__core__numbers__Exp1(): from sympy.core.numbers import Exp1 assert _test_args(Exp1()) def test_sympy__core__numbers__Float(): from sympy.core.numbers import Float assert _test_args(Float(1.23)) def test_sympy__core__numbers__GoldenRatio(): from sympy.core.numbers import GoldenRatio assert _test_args(GoldenRatio()) def test_sympy__core__numbers__TribonacciConstant(): from sympy.core.numbers import TribonacciConstant assert _test_args(TribonacciConstant()) def test_sympy__core__numbers__Half(): from sympy.core.numbers import Half assert _test_args(Half()) def test_sympy__core__numbers__ImaginaryUnit(): from sympy.core.numbers import ImaginaryUnit assert _test_args(ImaginaryUnit()) def test_sympy__core__numbers__Infinity(): from sympy.core.numbers import Infinity assert _test_args(Infinity()) def test_sympy__core__numbers__Integer(): from sympy.core.numbers import Integer assert _test_args(Integer(7)) @SKIP("abstract class") def test_sympy__core__numbers__IntegerConstant(): pass def test_sympy__core__numbers__NaN(): from sympy.core.numbers import NaN assert _test_args(NaN()) def test_sympy__core__numbers__NegativeInfinity(): from sympy.core.numbers import NegativeInfinity assert _test_args(NegativeInfinity()) def test_sympy__core__numbers__NegativeOne(): from sympy.core.numbers import NegativeOne assert _test_args(NegativeOne()) def test_sympy__core__numbers__Number(): from sympy.core.numbers import Number assert _test_args(Number(1, 7)) def test_sympy__core__numbers__NumberSymbol(): from sympy.core.numbers import NumberSymbol assert _test_args(NumberSymbol()) def test_sympy__core__numbers__One(): from sympy.core.numbers import One assert _test_args(One()) def test_sympy__core__numbers__Pi(): from sympy.core.numbers import Pi assert _test_args(Pi()) def test_sympy__core__numbers__Rational(): from sympy.core.numbers import Rational assert _test_args(Rational(1, 7)) @SKIP("abstract class") def test_sympy__core__numbers__RationalConstant(): pass def test_sympy__core__numbers__Zero(): from sympy.core.numbers import Zero assert _test_args(Zero()) @SKIP("abstract class") def test_sympy__core__operations__AssocOp(): pass @SKIP("abstract class") def test_sympy__core__operations__LatticeOp(): pass def test_sympy__core__power__Pow(): from sympy.core.power import Pow assert _test_args(Pow(x, 2)) def test_sympy__algebras__quaternion__Quaternion(): from sympy.algebras.quaternion import Quaternion assert _test_args(Quaternion(x, 1, 2, 3)) def test_sympy__core__relational__Equality(): from sympy.core.relational import Equality assert _test_args(Equality(x, 2)) def test_sympy__core__relational__GreaterThan(): from sympy.core.relational import GreaterThan assert _test_args(GreaterThan(x, 2)) def test_sympy__core__relational__LessThan(): from sympy.core.relational import LessThan assert _test_args(LessThan(x, 2)) @SKIP("abstract class") def test_sympy__core__relational__Relational(): pass def test_sympy__core__relational__StrictGreaterThan(): from sympy.core.relational import StrictGreaterThan assert _test_args(StrictGreaterThan(x, 2)) def test_sympy__core__relational__StrictLessThan(): from sympy.core.relational import StrictLessThan assert _test_args(StrictLessThan(x, 2)) def test_sympy__core__relational__Unequality(): from sympy.core.relational import Unequality assert _test_args(Unequality(x, 2)) def test_sympy__sandbox__indexed_integrals__IndexedIntegral(): from sympy.tensor import IndexedBase, Idx from sympy.sandbox.indexed_integrals import IndexedIntegral A = IndexedBase('A') i, j = symbols('i j', integer=True) a1, a2 = symbols('a1:3', cls=Idx) assert _test_args(IndexedIntegral(A[a1], A[a2])) assert _test_args(IndexedIntegral(A[i], A[j])) def test_sympy__calculus__util__AccumulationBounds(): from sympy.calculus.util import AccumulationBounds assert _test_args(AccumulationBounds(0, 1)) def test_sympy__sets__ordinals__OmegaPower(): from sympy.sets.ordinals import OmegaPower assert _test_args(OmegaPower(1, 1)) def test_sympy__sets__ordinals__Ordinal(): from sympy.sets.ordinals import Ordinal, OmegaPower assert _test_args(Ordinal(OmegaPower(2, 1))) def test_sympy__sets__ordinals__OrdinalOmega(): from sympy.sets.ordinals import OrdinalOmega assert _test_args(OrdinalOmega()) def test_sympy__sets__ordinals__OrdinalZero(): from sympy.sets.ordinals import OrdinalZero assert _test_args(OrdinalZero()) def test_sympy__sets__powerset__PowerSet(): from sympy.sets.powerset import PowerSet from sympy.core.singleton import S assert _test_args(PowerSet(S.EmptySet)) def test_sympy__sets__sets__EmptySet(): from sympy.sets.sets import EmptySet assert _test_args(EmptySet()) def test_sympy__sets__sets__UniversalSet(): from sympy.sets.sets import UniversalSet assert _test_args(UniversalSet()) def test_sympy__sets__sets__FiniteSet(): from sympy.sets.sets import FiniteSet assert _test_args(FiniteSet(x, y, z)) def test_sympy__sets__sets__Interval(): from sympy.sets.sets import Interval assert _test_args(Interval(0, 1)) def test_sympy__sets__sets__ProductSet(): from sympy.sets.sets import ProductSet, Interval assert _test_args(ProductSet(Interval(0, 1), Interval(0, 1))) @SKIP("does it make sense to test this?") def test_sympy__sets__sets__Set(): from sympy.sets.sets import Set assert _test_args(Set()) def test_sympy__sets__sets__Intersection(): from sympy.sets.sets import Intersection, Interval from sympy.core.symbol import Symbol x = Symbol('x') y = Symbol('y') S = Intersection(Interval(0, x), Interval(y, 1)) assert isinstance(S, Intersection) assert _test_args(S) def test_sympy__sets__sets__Union(): from sympy.sets.sets import Union, Interval assert _test_args(Union(Interval(0, 1), Interval(2, 3))) def test_sympy__sets__sets__Complement(): from sympy.sets.sets import Complement assert _test_args(Complement(Interval(0, 2), Interval(0, 1))) def test_sympy__sets__sets__SymmetricDifference(): from sympy.sets.sets import FiniteSet, SymmetricDifference assert _test_args(SymmetricDifference(FiniteSet(1, 2, 3), \ FiniteSet(2, 3, 4))) def test_sympy__sets__sets__DisjointUnion(): from sympy.sets.sets import FiniteSet, DisjointUnion assert _test_args(DisjointUnion(FiniteSet(1, 2, 3), \ FiniteSet(2, 3, 4))) def test_sympy__core__trace__Tr(): from sympy.core.trace import Tr a, b = symbols('a b') assert _test_args(Tr(a + b)) def test_sympy__sets__setexpr__SetExpr(): from sympy.sets.setexpr import SetExpr assert _test_args(SetExpr(Interval(0, 1))) def test_sympy__sets__fancysets__Rationals(): from sympy.sets.fancysets import Rationals assert _test_args(Rationals()) def test_sympy__sets__fancysets__Naturals(): from sympy.sets.fancysets import Naturals assert _test_args(Naturals()) def test_sympy__sets__fancysets__Naturals0(): from sympy.sets.fancysets import Naturals0 assert _test_args(Naturals0()) def test_sympy__sets__fancysets__Integers(): from sympy.sets.fancysets import Integers assert _test_args(Integers()) def test_sympy__sets__fancysets__Reals(): from sympy.sets.fancysets import Reals assert _test_args(Reals()) def test_sympy__sets__fancysets__Complexes(): from sympy.sets.fancysets import Complexes assert _test_args(Complexes()) def test_sympy__sets__fancysets__ComplexRegion(): from sympy.sets.fancysets import ComplexRegion from sympy import S from sympy.sets import Interval a = Interval(0, 1) b = Interval(2, 3) theta = Interval(0, 2*S.Pi) assert _test_args(ComplexRegion(a*b)) assert _test_args(ComplexRegion(a*theta, polar=True)) def test_sympy__sets__fancysets__CartesianComplexRegion(): from sympy.sets.fancysets import CartesianComplexRegion from sympy.sets import Interval a = Interval(0, 1) b = Interval(2, 3) assert _test_args(CartesianComplexRegion(a*b)) def test_sympy__sets__fancysets__PolarComplexRegion(): from sympy.sets.fancysets import PolarComplexRegion from sympy import S from sympy.sets import Interval a = Interval(0, 1) theta = Interval(0, 2*S.Pi) assert _test_args(PolarComplexRegion(a*theta)) def test_sympy__sets__fancysets__ImageSet(): from sympy.sets.fancysets import ImageSet from sympy import S, Symbol x = Symbol('x') assert _test_args(ImageSet(Lambda(x, x**2), S.Naturals)) def test_sympy__sets__fancysets__Range(): from sympy.sets.fancysets import Range assert _test_args(Range(1, 5, 1)) def test_sympy__sets__conditionset__ConditionSet(): from sympy.sets.conditionset import ConditionSet from sympy import S, Symbol x = Symbol('x') assert _test_args(ConditionSet(x, Eq(x**2, 1), S.Reals)) def test_sympy__sets__contains__Contains(): from sympy.sets.fancysets import Range from sympy.sets.contains import Contains assert _test_args(Contains(x, Range(0, 10, 2))) # STATS from sympy.stats.crv_types import NormalDistribution nd = NormalDistribution(0, 1) from sympy.stats.frv_types import DieDistribution die = DieDistribution(6) def test_sympy__stats__crv__ContinuousDomain(): from sympy.stats.crv import ContinuousDomain assert _test_args(ContinuousDomain({x}, Interval(-oo, oo))) def test_sympy__stats__crv__SingleContinuousDomain(): from sympy.stats.crv import SingleContinuousDomain assert _test_args(SingleContinuousDomain(x, Interval(-oo, oo))) def test_sympy__stats__crv__ProductContinuousDomain(): from sympy.stats.crv import SingleContinuousDomain, ProductContinuousDomain D = SingleContinuousDomain(x, Interval(-oo, oo)) E = SingleContinuousDomain(y, Interval(0, oo)) assert _test_args(ProductContinuousDomain(D, E)) def test_sympy__stats__crv__ConditionalContinuousDomain(): from sympy.stats.crv import (SingleContinuousDomain, ConditionalContinuousDomain) D = SingleContinuousDomain(x, Interval(-oo, oo)) assert _test_args(ConditionalContinuousDomain(D, x > 0)) def test_sympy__stats__crv__ContinuousPSpace(): from sympy.stats.crv import ContinuousPSpace, SingleContinuousDomain D = SingleContinuousDomain(x, Interval(-oo, oo)) assert _test_args(ContinuousPSpace(D, nd)) def test_sympy__stats__crv__SingleContinuousPSpace(): from sympy.stats.crv import SingleContinuousPSpace assert _test_args(SingleContinuousPSpace(x, nd)) @SKIP("abstract class") def test_sympy__stats__rv__Distribution(): pass @SKIP("abstract class") def test_sympy__stats__crv__SingleContinuousDistribution(): pass def test_sympy__stats__drv__SingleDiscreteDomain(): from sympy.stats.drv import SingleDiscreteDomain assert _test_args(SingleDiscreteDomain(x, S.Naturals)) def test_sympy__stats__drv__ProductDiscreteDomain(): from sympy.stats.drv import SingleDiscreteDomain, ProductDiscreteDomain X = SingleDiscreteDomain(x, S.Naturals) Y = SingleDiscreteDomain(y, S.Integers) assert _test_args(ProductDiscreteDomain(X, Y)) def test_sympy__stats__drv__SingleDiscretePSpace(): from sympy.stats.drv import SingleDiscretePSpace from sympy.stats.drv_types import PoissonDistribution assert _test_args(SingleDiscretePSpace(x, PoissonDistribution(1))) def test_sympy__stats__drv__DiscretePSpace(): from sympy.stats.drv import DiscretePSpace, SingleDiscreteDomain density = Lambda(x, 2**(-x)) domain = SingleDiscreteDomain(x, S.Naturals) assert _test_args(DiscretePSpace(domain, density)) def test_sympy__stats__drv__ConditionalDiscreteDomain(): from sympy.stats.drv import ConditionalDiscreteDomain, SingleDiscreteDomain X = SingleDiscreteDomain(x, S.Naturals0) assert _test_args(ConditionalDiscreteDomain(X, x > 2)) def test_sympy__stats__joint_rv__JointPSpace(): from sympy.stats.joint_rv import JointPSpace, JointDistribution assert _test_args(JointPSpace('X', JointDistribution(1))) def test_sympy__stats__joint_rv__JointRandomSymbol(): from sympy.stats.joint_rv import JointRandomSymbol assert _test_args(JointRandomSymbol(x)) def test_sympy__stats__joint_rv_types__JointDistributionHandmade(): from sympy import Indexed from sympy.stats.joint_rv_types import JointDistributionHandmade x1, x2 = (Indexed('x', i) for i in (1, 2)) assert _test_args(JointDistributionHandmade(x1 + x2, S.Reals**2)) def test_sympy__stats__joint_rv__MarginalDistribution(): from sympy.stats.rv import RandomSymbol from sympy.stats.joint_rv import MarginalDistribution r = RandomSymbol(S('r')) assert _test_args(MarginalDistribution(r, (r,))) def test_sympy__stats__compound_rv__CompoundDistribution(): from sympy.stats.compound_rv import CompoundDistribution from sympy.stats.drv_types import PoissonDistribution, Poisson r = Poisson('r', 10) assert _test_args(CompoundDistribution(PoissonDistribution(r))) def test_sympy__stats__compound_rv__CompoundPSpace(): from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution from sympy.stats.drv_types import PoissonDistribution, Poisson r = Poisson('r', 5) C = CompoundDistribution(PoissonDistribution(r)) assert _test_args(CompoundPSpace('C', C)) @SKIP("abstract class") def test_sympy__stats__drv__SingleDiscreteDistribution(): pass @SKIP("abstract class") def test_sympy__stats__drv__DiscreteDistribution(): pass @SKIP("abstract class") def test_sympy__stats__drv__DiscreteDomain(): pass def test_sympy__stats__rv__RandomDomain(): from sympy.stats.rv import RandomDomain from sympy.sets.sets import FiniteSet assert _test_args(RandomDomain(FiniteSet(x), FiniteSet(1, 2, 3))) def test_sympy__stats__rv__SingleDomain(): from sympy.stats.rv import SingleDomain from sympy.sets.sets import FiniteSet assert _test_args(SingleDomain(x, FiniteSet(1, 2, 3))) def test_sympy__stats__rv__ConditionalDomain(): from sympy.stats.rv import ConditionalDomain, RandomDomain from sympy.sets.sets import FiniteSet D = RandomDomain(FiniteSet(x), FiniteSet(1, 2)) assert _test_args(ConditionalDomain(D, x > 1)) def test_sympy__stats__rv__MatrixDomain(): from sympy.stats.rv import MatrixDomain from sympy.matrices import MatrixSet from sympy import S assert _test_args(MatrixDomain(x, MatrixSet(2, 2, S.Reals))) def test_sympy__stats__rv__PSpace(): from sympy.stats.rv import PSpace, RandomDomain from sympy import FiniteSet D = RandomDomain(FiniteSet(x), FiniteSet(1, 2, 3, 4, 5, 6)) assert _test_args(PSpace(D, die)) @SKIP("abstract Class") def test_sympy__stats__rv__SinglePSpace(): pass def test_sympy__stats__rv__RandomSymbol(): from sympy.stats.rv import RandomSymbol from sympy.stats.crv import SingleContinuousPSpace A = SingleContinuousPSpace(x, nd) assert _test_args(RandomSymbol(x, A)) @SKIP("abstract Class") def test_sympy__stats__rv__ProductPSpace(): pass def test_sympy__stats__rv__IndependentProductPSpace(): from sympy.stats.rv import IndependentProductPSpace from sympy.stats.crv import SingleContinuousPSpace A = SingleContinuousPSpace(x, nd) B = SingleContinuousPSpace(y, nd) assert _test_args(IndependentProductPSpace(A, B)) def test_sympy__stats__rv__ProductDomain(): from sympy.stats.rv import ProductDomain, SingleDomain D = SingleDomain(x, Interval(-oo, oo)) E = SingleDomain(y, Interval(0, oo)) assert _test_args(ProductDomain(D, E)) def test_sympy__stats__symbolic_probability__Probability(): from sympy.stats.symbolic_probability import Probability from sympy.stats import Normal X = Normal('X', 0, 1) assert _test_args(Probability(X > 0)) def test_sympy__stats__symbolic_probability__Expectation(): from sympy.stats.symbolic_probability import Expectation from sympy.stats import Normal X = Normal('X', 0, 1) assert _test_args(Expectation(X > 0)) def test_sympy__stats__symbolic_probability__Covariance(): from sympy.stats.symbolic_probability import Covariance from sympy.stats import Normal X = Normal('X', 0, 1) Y = Normal('Y', 0, 3) assert _test_args(Covariance(X, Y)) def test_sympy__stats__symbolic_probability__Variance(): from sympy.stats.symbolic_probability import Variance from sympy.stats import Normal X = Normal('X', 0, 1) assert _test_args(Variance(X)) def test_sympy__stats__symbolic_probability__Moment(): from sympy.stats.symbolic_probability import Moment from sympy.stats import Normal X = Normal('X', 0, 1) assert _test_args(Moment(X, 3, 2, X > 3)) def test_sympy__stats__symbolic_probability__CentralMoment(): from sympy.stats.symbolic_probability import CentralMoment from sympy.stats import Normal X = Normal('X', 0, 1) assert _test_args(CentralMoment(X, 2, X > 1)) def test_sympy__stats__frv_types__DiscreteUniformDistribution(): from sympy.stats.frv_types import DiscreteUniformDistribution from sympy.core.containers import Tuple assert _test_args(DiscreteUniformDistribution(Tuple(*list(range(6))))) def test_sympy__stats__frv_types__DieDistribution(): assert _test_args(die) def test_sympy__stats__frv_types__BernoulliDistribution(): from sympy.stats.frv_types import BernoulliDistribution assert _test_args(BernoulliDistribution(S.Half, 0, 1)) def test_sympy__stats__frv_types__BinomialDistribution(): from sympy.stats.frv_types import BinomialDistribution assert _test_args(BinomialDistribution(5, S.Half, 1, 0)) def test_sympy__stats__frv_types__BetaBinomialDistribution(): from sympy.stats.frv_types import BetaBinomialDistribution assert _test_args(BetaBinomialDistribution(5, 1, 1)) def test_sympy__stats__frv_types__HypergeometricDistribution(): from sympy.stats.frv_types import HypergeometricDistribution assert _test_args(HypergeometricDistribution(10, 5, 3)) def test_sympy__stats__frv_types__RademacherDistribution(): from sympy.stats.frv_types import RademacherDistribution assert _test_args(RademacherDistribution()) def test_sympy__stats__frv_types__IdealSolitonDistribution(): from sympy.stats.frv_types import IdealSolitonDistribution assert _test_args(IdealSolitonDistribution(10)) def test_sympy__stats__frv_types__RobustSolitonDistribution(): from sympy.stats.frv_types import RobustSolitonDistribution assert _test_args(RobustSolitonDistribution(1000, 0.5, 0.1)) def test_sympy__stats__frv__FiniteDomain(): from sympy.stats.frv import FiniteDomain assert _test_args(FiniteDomain({(x, 1), (x, 2)})) # x can be 1 or 2 def test_sympy__stats__frv__SingleFiniteDomain(): from sympy.stats.frv import SingleFiniteDomain assert _test_args(SingleFiniteDomain(x, {1, 2})) # x can be 1 or 2 def test_sympy__stats__frv__ProductFiniteDomain(): from sympy.stats.frv import SingleFiniteDomain, ProductFiniteDomain xd = SingleFiniteDomain(x, {1, 2}) yd = SingleFiniteDomain(y, {1, 2}) assert _test_args(ProductFiniteDomain(xd, yd)) def test_sympy__stats__frv__ConditionalFiniteDomain(): from sympy.stats.frv import SingleFiniteDomain, ConditionalFiniteDomain xd = SingleFiniteDomain(x, {1, 2}) assert _test_args(ConditionalFiniteDomain(xd, x > 1)) def test_sympy__stats__frv__FinitePSpace(): from sympy.stats.frv import FinitePSpace, SingleFiniteDomain xd = SingleFiniteDomain(x, {1, 2, 3, 4, 5, 6}) assert _test_args(FinitePSpace(xd, {(x, 1): S.Half, (x, 2): S.Half})) xd = SingleFiniteDomain(x, {1, 2}) assert _test_args(FinitePSpace(xd, {(x, 1): S.Half, (x, 2): S.Half})) def test_sympy__stats__frv__SingleFinitePSpace(): from sympy.stats.frv import SingleFinitePSpace from sympy import Symbol assert _test_args(SingleFinitePSpace(Symbol('x'), die)) def test_sympy__stats__frv__ProductFinitePSpace(): from sympy.stats.frv import SingleFinitePSpace, ProductFinitePSpace from sympy import Symbol xp = SingleFinitePSpace(Symbol('x'), die) yp = SingleFinitePSpace(Symbol('y'), die) assert _test_args(ProductFinitePSpace(xp, yp)) @SKIP("abstract class") def test_sympy__stats__frv__SingleFiniteDistribution(): pass @SKIP("abstract class") def test_sympy__stats__crv__ContinuousDistribution(): pass def test_sympy__stats__frv_types__FiniteDistributionHandmade(): from sympy.stats.frv_types import FiniteDistributionHandmade from sympy import Dict assert _test_args(FiniteDistributionHandmade(Dict({1: 1}))) def test_sympy__stats__crv_types__ContinuousDistributionHandmade(): from sympy.stats.crv_types import ContinuousDistributionHandmade from sympy import Interval, Lambda from sympy.abc import x assert _test_args(ContinuousDistributionHandmade(Lambda(x, 2*x), Interval(0, 1))) def test_sympy__stats__drv_types__DiscreteDistributionHandmade(): from sympy.stats.drv_types import DiscreteDistributionHandmade from sympy import Lambda, FiniteSet from sympy.abc import x assert _test_args(DiscreteDistributionHandmade(Lambda(x, Rational(1, 10)), FiniteSet(*range(10)))) def test_sympy__stats__rv__Density(): from sympy.stats.rv import Density from sympy.stats.crv_types import Normal assert _test_args(Density(Normal('x', 0, 1))) def test_sympy__stats__crv_types__ArcsinDistribution(): from sympy.stats.crv_types import ArcsinDistribution assert _test_args(ArcsinDistribution(0, 1)) def test_sympy__stats__crv_types__BeniniDistribution(): from sympy.stats.crv_types import BeniniDistribution assert _test_args(BeniniDistribution(1, 1, 1)) def test_sympy__stats__crv_types__BetaDistribution(): from sympy.stats.crv_types import BetaDistribution assert _test_args(BetaDistribution(1, 1)) def test_sympy__stats__crv_types__BetaNoncentralDistribution(): from sympy.stats.crv_types import BetaNoncentralDistribution assert _test_args(BetaNoncentralDistribution(1, 1, 1)) def test_sympy__stats__crv_types__BetaPrimeDistribution(): from sympy.stats.crv_types import BetaPrimeDistribution assert _test_args(BetaPrimeDistribution(1, 1)) def test_sympy__stats__crv_types__BoundedParetoDistribution(): from sympy.stats.crv_types import BoundedParetoDistribution assert _test_args(BoundedParetoDistribution(1, 1, 2)) def test_sympy__stats__crv_types__CauchyDistribution(): from sympy.stats.crv_types import CauchyDistribution assert _test_args(CauchyDistribution(0, 1)) def test_sympy__stats__crv_types__ChiDistribution(): from sympy.stats.crv_types import ChiDistribution assert _test_args(ChiDistribution(1)) def test_sympy__stats__crv_types__ChiNoncentralDistribution(): from sympy.stats.crv_types import ChiNoncentralDistribution assert _test_args(ChiNoncentralDistribution(1,1)) def test_sympy__stats__crv_types__ChiSquaredDistribution(): from sympy.stats.crv_types import ChiSquaredDistribution assert _test_args(ChiSquaredDistribution(1)) def test_sympy__stats__crv_types__DagumDistribution(): from sympy.stats.crv_types import DagumDistribution assert _test_args(DagumDistribution(1, 1, 1)) def test_sympy__stats__crv_types__ExGaussianDistribution(): from sympy.stats.crv_types import ExGaussianDistribution assert _test_args(ExGaussianDistribution(1, 1, 1)) def test_sympy__stats__crv_types__ExponentialDistribution(): from sympy.stats.crv_types import ExponentialDistribution assert _test_args(ExponentialDistribution(1)) def test_sympy__stats__crv_types__ExponentialPowerDistribution(): from sympy.stats.crv_types import ExponentialPowerDistribution assert _test_args(ExponentialPowerDistribution(0, 1, 1)) def test_sympy__stats__crv_types__FDistributionDistribution(): from sympy.stats.crv_types import FDistributionDistribution assert _test_args(FDistributionDistribution(1, 1)) def test_sympy__stats__crv_types__FisherZDistribution(): from sympy.stats.crv_types import FisherZDistribution assert _test_args(FisherZDistribution(1, 1)) def test_sympy__stats__crv_types__FrechetDistribution(): from sympy.stats.crv_types import FrechetDistribution assert _test_args(FrechetDistribution(1, 1, 1)) def test_sympy__stats__crv_types__GammaInverseDistribution(): from sympy.stats.crv_types import GammaInverseDistribution assert _test_args(GammaInverseDistribution(1, 1)) def test_sympy__stats__crv_types__GammaDistribution(): from sympy.stats.crv_types import GammaDistribution assert _test_args(GammaDistribution(1, 1)) def test_sympy__stats__crv_types__GumbelDistribution(): from sympy.stats.crv_types import GumbelDistribution assert _test_args(GumbelDistribution(1, 1, False)) def test_sympy__stats__crv_types__GompertzDistribution(): from sympy.stats.crv_types import GompertzDistribution assert _test_args(GompertzDistribution(1, 1)) def test_sympy__stats__crv_types__KumaraswamyDistribution(): from sympy.stats.crv_types import KumaraswamyDistribution assert _test_args(KumaraswamyDistribution(1, 1)) def test_sympy__stats__crv_types__LaplaceDistribution(): from sympy.stats.crv_types import LaplaceDistribution assert _test_args(LaplaceDistribution(0, 1)) def test_sympy__stats__crv_types__LevyDistribution(): from sympy.stats.crv_types import LevyDistribution assert _test_args(LevyDistribution(0, 1)) def test_sympy__stats__crv_types__LogCauchyDistribution(): from sympy.stats.crv_types import LogCauchyDistribution assert _test_args(LogCauchyDistribution(0, 1)) def test_sympy__stats__crv_types__LogisticDistribution(): from sympy.stats.crv_types import LogisticDistribution assert _test_args(LogisticDistribution(0, 1)) def test_sympy__stats__crv_types__LogLogisticDistribution(): from sympy.stats.crv_types import LogLogisticDistribution assert _test_args(LogLogisticDistribution(1, 1)) def test_sympy__stats__crv_types__LogitNormalDistribution(): from sympy.stats.crv_types import LogitNormalDistribution assert _test_args(LogitNormalDistribution(0, 1)) def test_sympy__stats__crv_types__LogNormalDistribution(): from sympy.stats.crv_types import LogNormalDistribution assert _test_args(LogNormalDistribution(0, 1)) def test_sympy__stats__crv_types__LomaxDistribution(): from sympy.stats.crv_types import LomaxDistribution assert _test_args(LomaxDistribution(1, 2)) def test_sympy__stats__crv_types__MaxwellDistribution(): from sympy.stats.crv_types import MaxwellDistribution assert _test_args(MaxwellDistribution(1)) def test_sympy__stats__crv_types__MoyalDistribution(): from sympy.stats.crv_types import MoyalDistribution assert _test_args(MoyalDistribution(1,2)) def test_sympy__stats__crv_types__NakagamiDistribution(): from sympy.stats.crv_types import NakagamiDistribution assert _test_args(NakagamiDistribution(1, 1)) def test_sympy__stats__crv_types__NormalDistribution(): from sympy.stats.crv_types import NormalDistribution assert _test_args(NormalDistribution(0, 1)) def test_sympy__stats__crv_types__GaussianInverseDistribution(): from sympy.stats.crv_types import GaussianInverseDistribution assert _test_args(GaussianInverseDistribution(1, 1)) def test_sympy__stats__crv_types__ParetoDistribution(): from sympy.stats.crv_types import ParetoDistribution assert _test_args(ParetoDistribution(1, 1)) def test_sympy__stats__crv_types__PowerFunctionDistribution(): from sympy.stats.crv_types import PowerFunctionDistribution assert _test_args(PowerFunctionDistribution(2,0,1)) def test_sympy__stats__crv_types__QuadraticUDistribution(): from sympy.stats.crv_types import QuadraticUDistribution assert _test_args(QuadraticUDistribution(1, 2)) def test_sympy__stats__crv_types__RaisedCosineDistribution(): from sympy.stats.crv_types import RaisedCosineDistribution assert _test_args(RaisedCosineDistribution(1, 1)) def test_sympy__stats__crv_types__RayleighDistribution(): from sympy.stats.crv_types import RayleighDistribution assert _test_args(RayleighDistribution(1)) def test_sympy__stats__crv_types__ReciprocalDistribution(): from sympy.stats.crv_types import ReciprocalDistribution assert _test_args(ReciprocalDistribution(5, 30)) def test_sympy__stats__crv_types__ShiftedGompertzDistribution(): from sympy.stats.crv_types import ShiftedGompertzDistribution assert _test_args(ShiftedGompertzDistribution(1, 1)) def test_sympy__stats__crv_types__StudentTDistribution(): from sympy.stats.crv_types import StudentTDistribution assert _test_args(StudentTDistribution(1)) def test_sympy__stats__crv_types__TrapezoidalDistribution(): from sympy.stats.crv_types import TrapezoidalDistribution assert _test_args(TrapezoidalDistribution(1, 2, 3, 4)) def test_sympy__stats__crv_types__TriangularDistribution(): from sympy.stats.crv_types import TriangularDistribution assert _test_args(TriangularDistribution(-1, 0, 1)) def test_sympy__stats__crv_types__UniformDistribution(): from sympy.stats.crv_types import UniformDistribution assert _test_args(UniformDistribution(0, 1)) def test_sympy__stats__crv_types__UniformSumDistribution(): from sympy.stats.crv_types import UniformSumDistribution assert _test_args(UniformSumDistribution(1)) def test_sympy__stats__crv_types__VonMisesDistribution(): from sympy.stats.crv_types import VonMisesDistribution assert _test_args(VonMisesDistribution(1, 1)) def test_sympy__stats__crv_types__WeibullDistribution(): from sympy.stats.crv_types import WeibullDistribution assert _test_args(WeibullDistribution(1, 1)) def test_sympy__stats__crv_types__WignerSemicircleDistribution(): from sympy.stats.crv_types import WignerSemicircleDistribution assert _test_args(WignerSemicircleDistribution(1)) def test_sympy__stats__drv_types__GeometricDistribution(): from sympy.stats.drv_types import GeometricDistribution assert _test_args(GeometricDistribution(.5)) def test_sympy__stats__drv_types__HermiteDistribution(): from sympy.stats.drv_types import HermiteDistribution assert _test_args(HermiteDistribution(1, 2)) def test_sympy__stats__drv_types__LogarithmicDistribution(): from sympy.stats.drv_types import LogarithmicDistribution assert _test_args(LogarithmicDistribution(.5)) def test_sympy__stats__drv_types__NegativeBinomialDistribution(): from sympy.stats.drv_types import NegativeBinomialDistribution assert _test_args(NegativeBinomialDistribution(.5, .5)) def test_sympy__stats__drv_types__FlorySchulzDistribution(): from sympy.stats.drv_types import FlorySchulzDistribution assert _test_args(FlorySchulzDistribution(.5)) def test_sympy__stats__drv_types__PoissonDistribution(): from sympy.stats.drv_types import PoissonDistribution assert _test_args(PoissonDistribution(1)) def test_sympy__stats__drv_types__SkellamDistribution(): from sympy.stats.drv_types import SkellamDistribution assert _test_args(SkellamDistribution(1, 1)) def test_sympy__stats__drv_types__YuleSimonDistribution(): from sympy.stats.drv_types import YuleSimonDistribution assert _test_args(YuleSimonDistribution(.5)) def test_sympy__stats__drv_types__ZetaDistribution(): from sympy.stats.drv_types import ZetaDistribution assert _test_args(ZetaDistribution(1.5)) def test_sympy__stats__joint_rv__JointDistribution(): from sympy.stats.joint_rv import JointDistribution assert _test_args(JointDistribution(1, 2, 3, 4)) def test_sympy__stats__joint_rv_types__MultivariateNormalDistribution(): from sympy.stats.joint_rv_types import MultivariateNormalDistribution assert _test_args( MultivariateNormalDistribution([0, 1], [[1, 0],[0, 1]])) def test_sympy__stats__joint_rv_types__MultivariateLaplaceDistribution(): from sympy.stats.joint_rv_types import MultivariateLaplaceDistribution assert _test_args(MultivariateLaplaceDistribution([0, 1], [[1, 0],[0, 1]])) def test_sympy__stats__joint_rv_types__MultivariateTDistribution(): from sympy.stats.joint_rv_types import MultivariateTDistribution assert _test_args(MultivariateTDistribution([0, 1], [[1, 0],[0, 1]], 1)) def test_sympy__stats__joint_rv_types__NormalGammaDistribution(): from sympy.stats.joint_rv_types import NormalGammaDistribution assert _test_args(NormalGammaDistribution(1, 2, 3, 4)) def test_sympy__stats__joint_rv_types__GeneralizedMultivariateLogGammaDistribution(): from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaDistribution v, l, mu = (4, [1, 2, 3, 4], [1, 2, 3, 4]) assert _test_args(GeneralizedMultivariateLogGammaDistribution(S.Half, v, l, mu)) def test_sympy__stats__joint_rv_types__MultivariateBetaDistribution(): from sympy.stats.joint_rv_types import MultivariateBetaDistribution assert _test_args(MultivariateBetaDistribution([1, 2, 3])) def test_sympy__stats__joint_rv_types__MultivariateEwensDistribution(): from sympy.stats.joint_rv_types import MultivariateEwensDistribution assert _test_args(MultivariateEwensDistribution(5, 1)) def test_sympy__stats__joint_rv_types__MultinomialDistribution(): from sympy.stats.joint_rv_types import MultinomialDistribution assert _test_args(MultinomialDistribution(5, [0.5, 0.1, 0.3])) def test_sympy__stats__joint_rv_types__NegativeMultinomialDistribution(): from sympy.stats.joint_rv_types import NegativeMultinomialDistribution assert _test_args(NegativeMultinomialDistribution(5, [0.5, 0.1, 0.3])) def test_sympy__stats__rv__RandomIndexedSymbol(): from sympy.stats.rv import RandomIndexedSymbol, pspace from sympy.stats.stochastic_process_types import DiscreteMarkovChain X = DiscreteMarkovChain("X") assert _test_args(RandomIndexedSymbol(X[0].symbol, pspace(X[0]))) def test_sympy__stats__rv__RandomMatrixSymbol(): from sympy.stats.rv import RandomMatrixSymbol from sympy.stats.random_matrix import RandomMatrixPSpace pspace = RandomMatrixPSpace('P') assert _test_args(RandomMatrixSymbol('M', 3, 3, pspace)) def test_sympy__stats__stochastic_process__StochasticPSpace(): from sympy.stats.stochastic_process import StochasticPSpace from sympy.stats.stochastic_process_types import StochasticProcess from sympy.stats.frv_types import BernoulliDistribution assert _test_args(StochasticPSpace("Y", StochasticProcess("Y", [1, 2, 3]), BernoulliDistribution(S.Half, 1, 0))) def test_sympy__stats__stochastic_process_types__StochasticProcess(): from sympy.stats.stochastic_process_types import StochasticProcess assert _test_args(StochasticProcess("Y", [1, 2, 3])) def test_sympy__stats__stochastic_process_types__MarkovProcess(): from sympy.stats.stochastic_process_types import MarkovProcess assert _test_args(MarkovProcess("Y", [1, 2, 3])) def test_sympy__stats__stochastic_process_types__DiscreteTimeStochasticProcess(): from sympy.stats.stochastic_process_types import DiscreteTimeStochasticProcess assert _test_args(DiscreteTimeStochasticProcess("Y", [1, 2, 3])) def test_sympy__stats__stochastic_process_types__ContinuousTimeStochasticProcess(): from sympy.stats.stochastic_process_types import ContinuousTimeStochasticProcess assert _test_args(ContinuousTimeStochasticProcess("Y", [1, 2, 3])) def test_sympy__stats__stochastic_process_types__TransitionMatrixOf(): from sympy.stats.stochastic_process_types import TransitionMatrixOf, DiscreteMarkovChain from sympy import MatrixSymbol DMC = DiscreteMarkovChain("Y") assert _test_args(TransitionMatrixOf(DMC, MatrixSymbol('T', 3, 3))) def test_sympy__stats__stochastic_process_types__GeneratorMatrixOf(): from sympy.stats.stochastic_process_types import GeneratorMatrixOf, ContinuousMarkovChain from sympy import MatrixSymbol DMC = ContinuousMarkovChain("Y") assert _test_args(GeneratorMatrixOf(DMC, MatrixSymbol('T', 3, 3))) def test_sympy__stats__stochastic_process_types__StochasticStateSpaceOf(): from sympy.stats.stochastic_process_types import StochasticStateSpaceOf, DiscreteMarkovChain DMC = DiscreteMarkovChain("Y") assert _test_args(StochasticStateSpaceOf(DMC, [0, 1, 2])) def test_sympy__stats__stochastic_process_types__DiscreteMarkovChain(): from sympy.stats.stochastic_process_types import DiscreteMarkovChain from sympy import MatrixSymbol assert _test_args(DiscreteMarkovChain("Y", [0, 1, 2], MatrixSymbol('T', 3, 3))) def test_sympy__stats__stochastic_process_types__ContinuousMarkovChain(): from sympy.stats.stochastic_process_types import ContinuousMarkovChain from sympy import MatrixSymbol assert _test_args(ContinuousMarkovChain("Y", [0, 1, 2], MatrixSymbol('T', 3, 3))) def test_sympy__stats__stochastic_process_types__BernoulliProcess(): from sympy.stats.stochastic_process_types import BernoulliProcess assert _test_args(BernoulliProcess("B", 0.5, 1, 0)) def test_sympy__stats__stochastic_process_types__CountingProcess(): from sympy.stats.stochastic_process_types import CountingProcess assert _test_args(CountingProcess("C")) def test_sympy__stats__stochastic_process_types__PoissonProcess(): from sympy.stats.stochastic_process_types import PoissonProcess assert _test_args(PoissonProcess("X", 2)) def test_sympy__stats__stochastic_process_types__WienerProcess(): from sympy.stats.stochastic_process_types import WienerProcess assert _test_args(WienerProcess("X")) def test_sympy__stats__stochastic_process_types__GammaProcess(): from sympy.stats.stochastic_process_types import GammaProcess assert _test_args(GammaProcess("X", 1, 2)) def test_sympy__stats__random_matrix__RandomMatrixPSpace(): from sympy.stats.random_matrix import RandomMatrixPSpace from sympy.stats.random_matrix_models import RandomMatrixEnsembleModel model = RandomMatrixEnsembleModel('R', 3) assert _test_args(RandomMatrixPSpace('P', model=model)) def test_sympy__stats__random_matrix_models__RandomMatrixEnsembleModel(): from sympy.stats.random_matrix_models import RandomMatrixEnsembleModel assert _test_args(RandomMatrixEnsembleModel('R', 3)) def test_sympy__stats__random_matrix_models__GaussianEnsembleModel(): from sympy.stats.random_matrix_models import GaussianEnsembleModel assert _test_args(GaussianEnsembleModel('G', 3)) def test_sympy__stats__random_matrix_models__GaussianUnitaryEnsembleModel(): from sympy.stats.random_matrix_models import GaussianUnitaryEnsembleModel assert _test_args(GaussianUnitaryEnsembleModel('U', 3)) def test_sympy__stats__random_matrix_models__GaussianOrthogonalEnsembleModel(): from sympy.stats.random_matrix_models import GaussianOrthogonalEnsembleModel assert _test_args(GaussianOrthogonalEnsembleModel('U', 3)) def test_sympy__stats__random_matrix_models__GaussianSymplecticEnsembleModel(): from sympy.stats.random_matrix_models import GaussianSymplecticEnsembleModel assert _test_args(GaussianSymplecticEnsembleModel('U', 3)) def test_sympy__stats__random_matrix_models__CircularEnsembleModel(): from sympy.stats.random_matrix_models import CircularEnsembleModel assert _test_args(CircularEnsembleModel('C', 3)) def test_sympy__stats__random_matrix_models__CircularUnitaryEnsembleModel(): from sympy.stats.random_matrix_models import CircularUnitaryEnsembleModel assert _test_args(CircularUnitaryEnsembleModel('U', 3)) def test_sympy__stats__random_matrix_models__CircularOrthogonalEnsembleModel(): from sympy.stats.random_matrix_models import CircularOrthogonalEnsembleModel assert _test_args(CircularOrthogonalEnsembleModel('O', 3)) def test_sympy__stats__random_matrix_models__CircularSymplecticEnsembleModel(): from sympy.stats.random_matrix_models import CircularSymplecticEnsembleModel assert _test_args(CircularSymplecticEnsembleModel('S', 3)) def test_sympy__stats__symbolic_multivariate_probability__ExpectationMatrix(): from sympy.stats import ExpectationMatrix from sympy.stats.rv import RandomMatrixSymbol assert _test_args(ExpectationMatrix(RandomMatrixSymbol('R', 2, 1))) def test_sympy__stats__symbolic_multivariate_probability__VarianceMatrix(): from sympy.stats import VarianceMatrix from sympy.stats.rv import RandomMatrixSymbol assert _test_args(VarianceMatrix(RandomMatrixSymbol('R', 3, 1))) def test_sympy__stats__symbolic_multivariate_probability__CrossCovarianceMatrix(): from sympy.stats import CrossCovarianceMatrix from sympy.stats.rv import RandomMatrixSymbol assert _test_args(CrossCovarianceMatrix(RandomMatrixSymbol('R', 3, 1), RandomMatrixSymbol('X', 3, 1))) def test_sympy__stats__matrix_distributions__MatrixPSpace(): from sympy.stats.matrix_distributions import MatrixDistribution, MatrixPSpace from sympy import Matrix M = MatrixDistribution(1, Matrix([[1, 0], [0, 1]])) assert _test_args(MatrixPSpace('M', M, 2, 2)) def test_sympy__stats__matrix_distributions__MatrixDistribution(): from sympy.stats.matrix_distributions import MatrixDistribution from sympy import Matrix assert _test_args(MatrixDistribution(1, Matrix([[1, 0], [0, 1]]))) def test_sympy__stats__matrix_distributions__MatrixGammaDistribution(): from sympy.stats.matrix_distributions import MatrixGammaDistribution from sympy import Matrix assert _test_args(MatrixGammaDistribution(3, 4, Matrix([[1, 0], [0, 1]]))) def test_sympy__stats__matrix_distributions__WishartDistribution(): from sympy.stats.matrix_distributions import WishartDistribution from sympy import Matrix assert _test_args(WishartDistribution(3, Matrix([[1, 0], [0, 1]]))) def test_sympy__stats__matrix_distributions__MatrixNormalDistribution(): from sympy.stats.matrix_distributions import MatrixNormalDistribution from sympy import MatrixSymbol L = MatrixSymbol('L', 1, 2) S1 = MatrixSymbol('S1', 1, 1) S2 = MatrixSymbol('S2', 2, 2) assert _test_args(MatrixNormalDistribution(L, S1, S2)) def test_sympy__stats__matrix_distributions__MatrixStudentTDistribution(): from sympy.stats.matrix_distributions import MatrixStudentTDistribution from sympy import MatrixSymbol v = symbols('v', positive=True) Omega = MatrixSymbol('Omega', 3, 3) Sigma = MatrixSymbol('Sigma', 1, 1) Location = MatrixSymbol('Location', 1, 3) assert _test_args(MatrixStudentTDistribution(v, Location, Omega, Sigma)) def test_sympy__utilities__matchpy_connector__WildDot(): from sympy.utilities.matchpy_connector import WildDot assert _test_args(WildDot("w_")) def test_sympy__utilities__matchpy_connector__WildPlus(): from sympy.utilities.matchpy_connector import WildPlus assert _test_args(WildPlus("w__")) def test_sympy__utilities__matchpy_connector__WildStar(): from sympy.utilities.matchpy_connector import WildStar assert _test_args(WildStar("w___")) def test_sympy__core__symbol__Str(): from sympy.core.symbol import Str assert _test_args(Str('t')) def test_sympy__core__symbol__Dummy(): from sympy.core.symbol import Dummy assert _test_args(Dummy('t')) def test_sympy__core__symbol__Symbol(): from sympy.core.symbol import Symbol assert _test_args(Symbol('t')) def test_sympy__core__symbol__Wild(): from sympy.core.symbol import Wild assert _test_args(Wild('x', exclude=[x])) @SKIP("abstract class") def test_sympy__functions__combinatorial__factorials__CombinatorialFunction(): pass def test_sympy__functions__combinatorial__factorials__FallingFactorial(): from sympy.functions.combinatorial.factorials import FallingFactorial assert _test_args(FallingFactorial(2, x)) def test_sympy__functions__combinatorial__factorials__MultiFactorial(): from sympy.functions.combinatorial.factorials import MultiFactorial assert _test_args(MultiFactorial(x)) def test_sympy__functions__combinatorial__factorials__RisingFactorial(): from sympy.functions.combinatorial.factorials import RisingFactorial assert _test_args(RisingFactorial(2, x)) def test_sympy__functions__combinatorial__factorials__binomial(): from sympy.functions.combinatorial.factorials import binomial assert _test_args(binomial(2, x)) def test_sympy__functions__combinatorial__factorials__subfactorial(): from sympy.functions.combinatorial.factorials import subfactorial assert _test_args(subfactorial(1)) def test_sympy__functions__combinatorial__factorials__factorial(): from sympy.functions.combinatorial.factorials import factorial assert _test_args(factorial(x)) def test_sympy__functions__combinatorial__factorials__factorial2(): from sympy.functions.combinatorial.factorials import factorial2 assert _test_args(factorial2(x)) def test_sympy__functions__combinatorial__numbers__bell(): from sympy.functions.combinatorial.numbers import bell assert _test_args(bell(x, y)) def test_sympy__functions__combinatorial__numbers__bernoulli(): from sympy.functions.combinatorial.numbers import bernoulli assert _test_args(bernoulli(x)) def test_sympy__functions__combinatorial__numbers__catalan(): from sympy.functions.combinatorial.numbers import catalan assert _test_args(catalan(x)) def test_sympy__functions__combinatorial__numbers__genocchi(): from sympy.functions.combinatorial.numbers import genocchi assert _test_args(genocchi(x)) def test_sympy__functions__combinatorial__numbers__euler(): from sympy.functions.combinatorial.numbers import euler assert _test_args(euler(x)) def test_sympy__functions__combinatorial__numbers__carmichael(): from sympy.functions.combinatorial.numbers import carmichael assert _test_args(carmichael(x)) def test_sympy__functions__combinatorial__numbers__motzkin(): from sympy.functions.combinatorial.numbers import motzkin assert _test_args(motzkin(5)) def test_sympy__functions__combinatorial__numbers__fibonacci(): from sympy.functions.combinatorial.numbers import fibonacci assert _test_args(fibonacci(x)) def test_sympy__functions__combinatorial__numbers__tribonacci(): from sympy.functions.combinatorial.numbers import tribonacci assert _test_args(tribonacci(x)) def test_sympy__functions__combinatorial__numbers__harmonic(): from sympy.functions.combinatorial.numbers import harmonic assert _test_args(harmonic(x, 2)) def test_sympy__functions__combinatorial__numbers__lucas(): from sympy.functions.combinatorial.numbers import lucas assert _test_args(lucas(x)) def test_sympy__functions__combinatorial__numbers__partition(): from sympy.core.symbol import Symbol from sympy.functions.combinatorial.numbers import partition assert _test_args(partition(Symbol('a', integer=True))) def test_sympy__functions__elementary__complexes__Abs(): from sympy.functions.elementary.complexes import Abs assert _test_args(Abs(x)) def test_sympy__functions__elementary__complexes__adjoint(): from sympy.functions.elementary.complexes import adjoint assert _test_args(adjoint(x)) def test_sympy__functions__elementary__complexes__arg(): from sympy.functions.elementary.complexes import arg assert _test_args(arg(x)) def test_sympy__functions__elementary__complexes__conjugate(): from sympy.functions.elementary.complexes import conjugate assert _test_args(conjugate(x)) def test_sympy__functions__elementary__complexes__im(): from sympy.functions.elementary.complexes import im assert _test_args(im(x)) def test_sympy__functions__elementary__complexes__re(): from sympy.functions.elementary.complexes import re assert _test_args(re(x)) def test_sympy__functions__elementary__complexes__sign(): from sympy.functions.elementary.complexes import sign assert _test_args(sign(x)) def test_sympy__functions__elementary__complexes__polar_lift(): from sympy.functions.elementary.complexes import polar_lift assert _test_args(polar_lift(x)) def test_sympy__functions__elementary__complexes__periodic_argument(): from sympy.functions.elementary.complexes import periodic_argument assert _test_args(periodic_argument(x, y)) def test_sympy__functions__elementary__complexes__principal_branch(): from sympy.functions.elementary.complexes import principal_branch assert _test_args(principal_branch(x, y)) def test_sympy__functions__elementary__complexes__transpose(): from sympy.functions.elementary.complexes import transpose assert _test_args(transpose(x)) def test_sympy__functions__elementary__exponential__LambertW(): from sympy.functions.elementary.exponential import LambertW assert _test_args(LambertW(2)) @SKIP("abstract class") def test_sympy__functions__elementary__exponential__ExpBase(): pass def test_sympy__functions__elementary__exponential__exp(): from sympy.functions.elementary.exponential import exp assert _test_args(exp(2)) def test_sympy__functions__elementary__exponential__exp_polar(): from sympy.functions.elementary.exponential import exp_polar assert _test_args(exp_polar(2)) def test_sympy__functions__elementary__exponential__log(): from sympy.functions.elementary.exponential import log assert _test_args(log(2)) @SKIP("abstract class") def test_sympy__functions__elementary__hyperbolic__HyperbolicFunction(): pass @SKIP("abstract class") def test_sympy__functions__elementary__hyperbolic__ReciprocalHyperbolicFunction(): pass @SKIP("abstract class") def test_sympy__functions__elementary__hyperbolic__InverseHyperbolicFunction(): pass def test_sympy__functions__elementary__hyperbolic__acosh(): from sympy.functions.elementary.hyperbolic import acosh assert _test_args(acosh(2)) def test_sympy__functions__elementary__hyperbolic__acoth(): from sympy.functions.elementary.hyperbolic import acoth assert _test_args(acoth(2)) def test_sympy__functions__elementary__hyperbolic__asinh(): from sympy.functions.elementary.hyperbolic import asinh assert _test_args(asinh(2)) def test_sympy__functions__elementary__hyperbolic__atanh(): from sympy.functions.elementary.hyperbolic import atanh assert _test_args(atanh(2)) def test_sympy__functions__elementary__hyperbolic__asech(): from sympy.functions.elementary.hyperbolic import asech assert _test_args(asech(2)) def test_sympy__functions__elementary__hyperbolic__acsch(): from sympy.functions.elementary.hyperbolic import acsch assert _test_args(acsch(2)) def test_sympy__functions__elementary__hyperbolic__cosh(): from sympy.functions.elementary.hyperbolic import cosh assert _test_args(cosh(2)) def test_sympy__functions__elementary__hyperbolic__coth(): from sympy.functions.elementary.hyperbolic import coth assert _test_args(coth(2)) def test_sympy__functions__elementary__hyperbolic__csch(): from sympy.functions.elementary.hyperbolic import csch assert _test_args(csch(2)) def test_sympy__functions__elementary__hyperbolic__sech(): from sympy.functions.elementary.hyperbolic import sech assert _test_args(sech(2)) def test_sympy__functions__elementary__hyperbolic__sinh(): from sympy.functions.elementary.hyperbolic import sinh assert _test_args(sinh(2)) def test_sympy__functions__elementary__hyperbolic__tanh(): from sympy.functions.elementary.hyperbolic import tanh assert _test_args(tanh(2)) @SKIP("does this work at all?") def test_sympy__functions__elementary__integers__RoundFunction(): from sympy.functions.elementary.integers import RoundFunction assert _test_args(RoundFunction()) def test_sympy__functions__elementary__integers__ceiling(): from sympy.functions.elementary.integers import ceiling assert _test_args(ceiling(x)) def test_sympy__functions__elementary__integers__floor(): from sympy.functions.elementary.integers import floor assert _test_args(floor(x)) def test_sympy__functions__elementary__integers__frac(): from sympy.functions.elementary.integers import frac assert _test_args(frac(x)) def test_sympy__functions__elementary__miscellaneous__IdentityFunction(): from sympy.functions.elementary.miscellaneous import IdentityFunction assert _test_args(IdentityFunction()) def test_sympy__functions__elementary__miscellaneous__Max(): from sympy.functions.elementary.miscellaneous import Max assert _test_args(Max(x, 2)) def test_sympy__functions__elementary__miscellaneous__Min(): from sympy.functions.elementary.miscellaneous import Min assert _test_args(Min(x, 2)) @SKIP("abstract class") def test_sympy__functions__elementary__miscellaneous__MinMaxBase(): pass def test_sympy__functions__elementary__piecewise__ExprCondPair(): from sympy.functions.elementary.piecewise import ExprCondPair assert _test_args(ExprCondPair(1, True)) def test_sympy__functions__elementary__piecewise__Piecewise(): from sympy.functions.elementary.piecewise import Piecewise assert _test_args(Piecewise((1, x >= 0), (0, True))) @SKIP("abstract class") def test_sympy__functions__elementary__trigonometric__TrigonometricFunction(): pass @SKIP("abstract class") def test_sympy__functions__elementary__trigonometric__ReciprocalTrigonometricFunction(): pass @SKIP("abstract class") def test_sympy__functions__elementary__trigonometric__InverseTrigonometricFunction(): pass def test_sympy__functions__elementary__trigonometric__acos(): from sympy.functions.elementary.trigonometric import acos assert _test_args(acos(2)) def test_sympy__functions__elementary__trigonometric__acot(): from sympy.functions.elementary.trigonometric import acot assert _test_args(acot(2)) def test_sympy__functions__elementary__trigonometric__asin(): from sympy.functions.elementary.trigonometric import asin assert _test_args(asin(2)) def test_sympy__functions__elementary__trigonometric__asec(): from sympy.functions.elementary.trigonometric import asec assert _test_args(asec(2)) def test_sympy__functions__elementary__trigonometric__acsc(): from sympy.functions.elementary.trigonometric import acsc assert _test_args(acsc(2)) def test_sympy__functions__elementary__trigonometric__atan(): from sympy.functions.elementary.trigonometric import atan assert _test_args(atan(2)) def test_sympy__functions__elementary__trigonometric__atan2(): from sympy.functions.elementary.trigonometric import atan2 assert _test_args(atan2(2, 3)) def test_sympy__functions__elementary__trigonometric__cos(): from sympy.functions.elementary.trigonometric import cos assert _test_args(cos(2)) def test_sympy__functions__elementary__trigonometric__csc(): from sympy.functions.elementary.trigonometric import csc assert _test_args(csc(2)) def test_sympy__functions__elementary__trigonometric__cot(): from sympy.functions.elementary.trigonometric import cot assert _test_args(cot(2)) def test_sympy__functions__elementary__trigonometric__sin(): assert _test_args(sin(2)) def test_sympy__functions__elementary__trigonometric__sinc(): from sympy.functions.elementary.trigonometric import sinc assert _test_args(sinc(2)) def test_sympy__functions__elementary__trigonometric__sec(): from sympy.functions.elementary.trigonometric import sec assert _test_args(sec(2)) def test_sympy__functions__elementary__trigonometric__tan(): from sympy.functions.elementary.trigonometric import tan assert _test_args(tan(2)) @SKIP("abstract class") def test_sympy__functions__special__bessel__BesselBase(): pass @SKIP("abstract class") def test_sympy__functions__special__bessel__SphericalBesselBase(): pass @SKIP("abstract class") def test_sympy__functions__special__bessel__SphericalHankelBase(): pass def test_sympy__functions__special__bessel__besseli(): from sympy.functions.special.bessel import besseli assert _test_args(besseli(x, 1)) def test_sympy__functions__special__bessel__besselj(): from sympy.functions.special.bessel import besselj assert _test_args(besselj(x, 1)) def test_sympy__functions__special__bessel__besselk(): from sympy.functions.special.bessel import besselk assert _test_args(besselk(x, 1)) def test_sympy__functions__special__bessel__bessely(): from sympy.functions.special.bessel import bessely assert _test_args(bessely(x, 1)) def test_sympy__functions__special__bessel__hankel1(): from sympy.functions.special.bessel import hankel1 assert _test_args(hankel1(x, 1)) def test_sympy__functions__special__bessel__hankel2(): from sympy.functions.special.bessel import hankel2 assert _test_args(hankel2(x, 1)) def test_sympy__functions__special__bessel__jn(): from sympy.functions.special.bessel import jn assert _test_args(jn(0, x)) def test_sympy__functions__special__bessel__yn(): from sympy.functions.special.bessel import yn assert _test_args(yn(0, x)) def test_sympy__functions__special__bessel__hn1(): from sympy.functions.special.bessel import hn1 assert _test_args(hn1(0, x)) def test_sympy__functions__special__bessel__hn2(): from sympy.functions.special.bessel import hn2 assert _test_args(hn2(0, x)) def test_sympy__functions__special__bessel__AiryBase(): pass def test_sympy__functions__special__bessel__airyai(): from sympy.functions.special.bessel import airyai assert _test_args(airyai(2)) def test_sympy__functions__special__bessel__airybi(): from sympy.functions.special.bessel import airybi assert _test_args(airybi(2)) def test_sympy__functions__special__bessel__airyaiprime(): from sympy.functions.special.bessel import airyaiprime assert _test_args(airyaiprime(2)) def test_sympy__functions__special__bessel__airybiprime(): from sympy.functions.special.bessel import airybiprime assert _test_args(airybiprime(2)) def test_sympy__functions__special__bessel__marcumq(): from sympy.functions.special.bessel import marcumq assert _test_args(marcumq(x, y, z)) def test_sympy__functions__special__elliptic_integrals__elliptic_k(): from sympy.functions.special.elliptic_integrals import elliptic_k as K assert _test_args(K(x)) def test_sympy__functions__special__elliptic_integrals__elliptic_f(): from sympy.functions.special.elliptic_integrals import elliptic_f as F assert _test_args(F(x, y)) def test_sympy__functions__special__elliptic_integrals__elliptic_e(): from sympy.functions.special.elliptic_integrals import elliptic_e as E assert _test_args(E(x)) assert _test_args(E(x, y)) def test_sympy__functions__special__elliptic_integrals__elliptic_pi(): from sympy.functions.special.elliptic_integrals import elliptic_pi as P assert _test_args(P(x, y)) assert _test_args(P(x, y, z)) def test_sympy__functions__special__delta_functions__DiracDelta(): from sympy.functions.special.delta_functions import DiracDelta assert _test_args(DiracDelta(x, 1)) def test_sympy__functions__special__singularity_functions__SingularityFunction(): from sympy.functions.special.singularity_functions import SingularityFunction assert _test_args(SingularityFunction(x, y, z)) def test_sympy__functions__special__delta_functions__Heaviside(): from sympy.functions.special.delta_functions import Heaviside assert _test_args(Heaviside(x)) def test_sympy__functions__special__error_functions__erf(): from sympy.functions.special.error_functions import erf assert _test_args(erf(2)) def test_sympy__functions__special__error_functions__erfc(): from sympy.functions.special.error_functions import erfc assert _test_args(erfc(2)) def test_sympy__functions__special__error_functions__erfi(): from sympy.functions.special.error_functions import erfi assert _test_args(erfi(2)) def test_sympy__functions__special__error_functions__erf2(): from sympy.functions.special.error_functions import erf2 assert _test_args(erf2(2, 3)) def test_sympy__functions__special__error_functions__erfinv(): from sympy.functions.special.error_functions import erfinv assert _test_args(erfinv(2)) def test_sympy__functions__special__error_functions__erfcinv(): from sympy.functions.special.error_functions import erfcinv assert _test_args(erfcinv(2)) def test_sympy__functions__special__error_functions__erf2inv(): from sympy.functions.special.error_functions import erf2inv assert _test_args(erf2inv(2, 3)) @SKIP("abstract class") def test_sympy__functions__special__error_functions__FresnelIntegral(): pass def test_sympy__functions__special__error_functions__fresnels(): from sympy.functions.special.error_functions import fresnels assert _test_args(fresnels(2)) def test_sympy__functions__special__error_functions__fresnelc(): from sympy.functions.special.error_functions import fresnelc assert _test_args(fresnelc(2)) def test_sympy__functions__special__error_functions__erfs(): from sympy.functions.special.error_functions import _erfs assert _test_args(_erfs(2)) def test_sympy__functions__special__error_functions__Ei(): from sympy.functions.special.error_functions import Ei assert _test_args(Ei(2)) def test_sympy__functions__special__error_functions__li(): from sympy.functions.special.error_functions import li assert _test_args(li(2)) def test_sympy__functions__special__error_functions__Li(): from sympy.functions.special.error_functions import Li assert _test_args(Li(2)) @SKIP("abstract class") def test_sympy__functions__special__error_functions__TrigonometricIntegral(): pass def test_sympy__functions__special__error_functions__Si(): from sympy.functions.special.error_functions import Si assert _test_args(Si(2)) def test_sympy__functions__special__error_functions__Ci(): from sympy.functions.special.error_functions import Ci assert _test_args(Ci(2)) def test_sympy__functions__special__error_functions__Shi(): from sympy.functions.special.error_functions import Shi assert _test_args(Shi(2)) def test_sympy__functions__special__error_functions__Chi(): from sympy.functions.special.error_functions import Chi assert _test_args(Chi(2)) def test_sympy__functions__special__error_functions__expint(): from sympy.functions.special.error_functions import expint assert _test_args(expint(y, x)) def test_sympy__functions__special__gamma_functions__gamma(): from sympy.functions.special.gamma_functions import gamma assert _test_args(gamma(x)) def test_sympy__functions__special__gamma_functions__loggamma(): from sympy.functions.special.gamma_functions import loggamma assert _test_args(loggamma(2)) def test_sympy__functions__special__gamma_functions__lowergamma(): from sympy.functions.special.gamma_functions import lowergamma assert _test_args(lowergamma(x, 2)) def test_sympy__functions__special__gamma_functions__polygamma(): from sympy.functions.special.gamma_functions import polygamma assert _test_args(polygamma(x, 2)) def test_sympy__functions__special__gamma_functions__digamma(): from sympy.functions.special.gamma_functions import digamma assert _test_args(digamma(x)) def test_sympy__functions__special__gamma_functions__trigamma(): from sympy.functions.special.gamma_functions import trigamma assert _test_args(trigamma(x)) def test_sympy__functions__special__gamma_functions__uppergamma(): from sympy.functions.special.gamma_functions import uppergamma assert _test_args(uppergamma(x, 2)) def test_sympy__functions__special__gamma_functions__multigamma(): from sympy.functions.special.gamma_functions import multigamma assert _test_args(multigamma(x, 1)) def test_sympy__functions__special__beta_functions__beta(): from sympy.functions.special.beta_functions import beta assert _test_args(beta(x)) assert _test_args(beta(x, x)) def test_sympy__functions__special__beta_functions__betainc(): from sympy.functions.special.beta_functions import betainc assert _test_args(betainc(a, b, x, y)) def test_sympy__functions__special__beta_functions__betainc_regularized(): from sympy.functions.special.beta_functions import betainc_regularized assert _test_args(betainc_regularized(a, b, x, y)) def test_sympy__functions__special__mathieu_functions__MathieuBase(): pass def test_sympy__functions__special__mathieu_functions__mathieus(): from sympy.functions.special.mathieu_functions import mathieus assert _test_args(mathieus(1, 1, 1)) def test_sympy__functions__special__mathieu_functions__mathieuc(): from sympy.functions.special.mathieu_functions import mathieuc assert _test_args(mathieuc(1, 1, 1)) def test_sympy__functions__special__mathieu_functions__mathieusprime(): from sympy.functions.special.mathieu_functions import mathieusprime assert _test_args(mathieusprime(1, 1, 1)) def test_sympy__functions__special__mathieu_functions__mathieucprime(): from sympy.functions.special.mathieu_functions import mathieucprime assert _test_args(mathieucprime(1, 1, 1)) @SKIP("abstract class") def test_sympy__functions__special__hyper__TupleParametersBase(): pass @SKIP("abstract class") def test_sympy__functions__special__hyper__TupleArg(): pass def test_sympy__functions__special__hyper__hyper(): from sympy.functions.special.hyper import hyper assert _test_args(hyper([1, 2, 3], [4, 5], x)) def test_sympy__functions__special__hyper__meijerg(): from sympy.functions.special.hyper import meijerg assert _test_args(meijerg([1, 2, 3], [4, 5], [6], [], x)) @SKIP("abstract class") def test_sympy__functions__special__hyper__HyperRep(): pass def test_sympy__functions__special__hyper__HyperRep_power1(): from sympy.functions.special.hyper import HyperRep_power1 assert _test_args(HyperRep_power1(x, y)) def test_sympy__functions__special__hyper__HyperRep_power2(): from sympy.functions.special.hyper import HyperRep_power2 assert _test_args(HyperRep_power2(x, y)) def test_sympy__functions__special__hyper__HyperRep_log1(): from sympy.functions.special.hyper import HyperRep_log1 assert _test_args(HyperRep_log1(x)) def test_sympy__functions__special__hyper__HyperRep_atanh(): from sympy.functions.special.hyper import HyperRep_atanh assert _test_args(HyperRep_atanh(x)) def test_sympy__functions__special__hyper__HyperRep_asin1(): from sympy.functions.special.hyper import HyperRep_asin1 assert _test_args(HyperRep_asin1(x)) def test_sympy__functions__special__hyper__HyperRep_asin2(): from sympy.functions.special.hyper import HyperRep_asin2 assert _test_args(HyperRep_asin2(x)) def test_sympy__functions__special__hyper__HyperRep_sqrts1(): from sympy.functions.special.hyper import HyperRep_sqrts1 assert _test_args(HyperRep_sqrts1(x, y)) def test_sympy__functions__special__hyper__HyperRep_sqrts2(): from sympy.functions.special.hyper import HyperRep_sqrts2 assert _test_args(HyperRep_sqrts2(x, y)) def test_sympy__functions__special__hyper__HyperRep_log2(): from sympy.functions.special.hyper import HyperRep_log2 assert _test_args(HyperRep_log2(x)) def test_sympy__functions__special__hyper__HyperRep_cosasin(): from sympy.functions.special.hyper import HyperRep_cosasin assert _test_args(HyperRep_cosasin(x, y)) def test_sympy__functions__special__hyper__HyperRep_sinasin(): from sympy.functions.special.hyper import HyperRep_sinasin assert _test_args(HyperRep_sinasin(x, y)) def test_sympy__functions__special__hyper__appellf1(): from sympy.functions.special.hyper import appellf1 a, b1, b2, c, x, y = symbols('a b1 b2 c x y') assert _test_args(appellf1(a, b1, b2, c, x, y)) @SKIP("abstract class") def test_sympy__functions__special__polynomials__OrthogonalPolynomial(): pass def test_sympy__functions__special__polynomials__jacobi(): from sympy.functions.special.polynomials import jacobi assert _test_args(jacobi(x, 2, 2, 2)) def test_sympy__functions__special__polynomials__gegenbauer(): from sympy.functions.special.polynomials import gegenbauer assert _test_args(gegenbauer(x, 2, 2)) def test_sympy__functions__special__polynomials__chebyshevt(): from sympy.functions.special.polynomials import chebyshevt assert _test_args(chebyshevt(x, 2)) def test_sympy__functions__special__polynomials__chebyshevt_root(): from sympy.functions.special.polynomials import chebyshevt_root assert _test_args(chebyshevt_root(3, 2)) def test_sympy__functions__special__polynomials__chebyshevu(): from sympy.functions.special.polynomials import chebyshevu assert _test_args(chebyshevu(x, 2)) def test_sympy__functions__special__polynomials__chebyshevu_root(): from sympy.functions.special.polynomials import chebyshevu_root assert _test_args(chebyshevu_root(3, 2)) def test_sympy__functions__special__polynomials__hermite(): from sympy.functions.special.polynomials import hermite assert _test_args(hermite(x, 2)) def test_sympy__functions__special__polynomials__legendre(): from sympy.functions.special.polynomials import legendre assert _test_args(legendre(x, 2)) def test_sympy__functions__special__polynomials__assoc_legendre(): from sympy.functions.special.polynomials import assoc_legendre assert _test_args(assoc_legendre(x, 0, y)) def test_sympy__functions__special__polynomials__laguerre(): from sympy.functions.special.polynomials import laguerre assert _test_args(laguerre(x, 2)) def test_sympy__functions__special__polynomials__assoc_laguerre(): from sympy.functions.special.polynomials import assoc_laguerre assert _test_args(assoc_laguerre(x, 0, y)) def test_sympy__functions__special__spherical_harmonics__Ynm(): from sympy.functions.special.spherical_harmonics import Ynm assert _test_args(Ynm(1, 1, x, y)) def test_sympy__functions__special__spherical_harmonics__Znm(): from sympy.functions.special.spherical_harmonics import Znm assert _test_args(Znm(1, 1, x, y)) def test_sympy__functions__special__tensor_functions__LeviCivita(): from sympy.functions.special.tensor_functions import LeviCivita assert _test_args(LeviCivita(x, y, 2)) def test_sympy__functions__special__tensor_functions__KroneckerDelta(): from sympy.functions.special.tensor_functions import KroneckerDelta assert _test_args(KroneckerDelta(x, y)) def test_sympy__functions__special__zeta_functions__dirichlet_eta(): from sympy.functions.special.zeta_functions import dirichlet_eta assert _test_args(dirichlet_eta(x)) def test_sympy__functions__special__zeta_functions__riemann_xi(): from sympy.functions.special.zeta_functions import riemann_xi assert _test_args(riemann_xi(x)) def test_sympy__functions__special__zeta_functions__zeta(): from sympy.functions.special.zeta_functions import zeta assert _test_args(zeta(101)) def test_sympy__functions__special__zeta_functions__lerchphi(): from sympy.functions.special.zeta_functions import lerchphi assert _test_args(lerchphi(x, y, z)) def test_sympy__functions__special__zeta_functions__polylog(): from sympy.functions.special.zeta_functions import polylog assert _test_args(polylog(x, y)) def test_sympy__functions__special__zeta_functions__stieltjes(): from sympy.functions.special.zeta_functions import stieltjes assert _test_args(stieltjes(x, y)) def test_sympy__integrals__integrals__Integral(): from sympy.integrals.integrals import Integral assert _test_args(Integral(2, (x, 0, 1))) def test_sympy__integrals__risch__NonElementaryIntegral(): from sympy.integrals.risch import NonElementaryIntegral assert _test_args(NonElementaryIntegral(exp(-x**2), x)) @SKIP("abstract class") def test_sympy__integrals__transforms__IntegralTransform(): pass def test_sympy__integrals__transforms__MellinTransform(): from sympy.integrals.transforms import MellinTransform assert _test_args(MellinTransform(2, x, y)) def test_sympy__integrals__transforms__InverseMellinTransform(): from sympy.integrals.transforms import InverseMellinTransform assert _test_args(InverseMellinTransform(2, x, y, 0, 1)) def test_sympy__integrals__transforms__LaplaceTransform(): from sympy.integrals.transforms import LaplaceTransform assert _test_args(LaplaceTransform(2, x, y)) def test_sympy__integrals__transforms__InverseLaplaceTransform(): from sympy.integrals.transforms import InverseLaplaceTransform assert _test_args(InverseLaplaceTransform(2, x, y, 0)) @SKIP("abstract class") def test_sympy__integrals__transforms__FourierTypeTransform(): pass def test_sympy__integrals__transforms__InverseFourierTransform(): from sympy.integrals.transforms import InverseFourierTransform assert _test_args(InverseFourierTransform(2, x, y)) def test_sympy__integrals__transforms__FourierTransform(): from sympy.integrals.transforms import FourierTransform assert _test_args(FourierTransform(2, x, y)) @SKIP("abstract class") def test_sympy__integrals__transforms__SineCosineTypeTransform(): pass def test_sympy__integrals__transforms__InverseSineTransform(): from sympy.integrals.transforms import InverseSineTransform assert _test_args(InverseSineTransform(2, x, y)) def test_sympy__integrals__transforms__SineTransform(): from sympy.integrals.transforms import SineTransform assert _test_args(SineTransform(2, x, y)) def test_sympy__integrals__transforms__InverseCosineTransform(): from sympy.integrals.transforms import InverseCosineTransform assert _test_args(InverseCosineTransform(2, x, y)) def test_sympy__integrals__transforms__CosineTransform(): from sympy.integrals.transforms import CosineTransform assert _test_args(CosineTransform(2, x, y)) @SKIP("abstract class") def test_sympy__integrals__transforms__HankelTypeTransform(): pass def test_sympy__integrals__transforms__InverseHankelTransform(): from sympy.integrals.transforms import InverseHankelTransform assert _test_args(InverseHankelTransform(2, x, y, 0)) def test_sympy__integrals__transforms__HankelTransform(): from sympy.integrals.transforms import HankelTransform assert _test_args(HankelTransform(2, x, y, 0)) @XFAIL def test_sympy__liealgebras__cartan_type__CartanType_generator(): from sympy.liealgebras.cartan_type import CartanType_generator assert _test_args(CartanType_generator("A2")) @XFAIL def test_sympy__liealgebras__cartan_type__Standard_Cartan(): from sympy.liealgebras.cartan_type import Standard_Cartan assert _test_args(Standard_Cartan("A", 2)) @XFAIL def test_sympy__liealgebras__weyl_group__WeylGroup(): from sympy.liealgebras.weyl_group import WeylGroup assert _test_args(WeylGroup("B4")) @XFAIL def test_sympy__liealgebras__root_system__RootSystem(): from sympy.liealgebras.root_system import RootSystem assert _test_args(RootSystem("A2")) @XFAIL def test_sympy__liealgebras__type_a__TypeA(): from sympy.liealgebras.type_a import TypeA assert _test_args(TypeA(2)) @XFAIL def test_sympy__liealgebras__type_b__TypeB(): from sympy.liealgebras.type_b import TypeB assert _test_args(TypeB(4)) @XFAIL def test_sympy__liealgebras__type_c__TypeC(): from sympy.liealgebras.type_c import TypeC assert _test_args(TypeC(4)) @XFAIL def test_sympy__liealgebras__type_d__TypeD(): from sympy.liealgebras.type_d import TypeD assert _test_args(TypeD(4)) @XFAIL def test_sympy__liealgebras__type_e__TypeE(): from sympy.liealgebras.type_e import TypeE assert _test_args(TypeE(6)) @XFAIL def test_sympy__liealgebras__type_f__TypeF(): from sympy.liealgebras.type_f import TypeF assert _test_args(TypeF(4)) @XFAIL def test_sympy__liealgebras__type_g__TypeG(): from sympy.liealgebras.type_g import TypeG assert _test_args(TypeG(2)) def test_sympy__logic__boolalg__And(): from sympy.logic.boolalg import And assert _test_args(And(x, y, 1)) @SKIP("abstract class") def test_sympy__logic__boolalg__Boolean(): pass def test_sympy__logic__boolalg__BooleanFunction(): from sympy.logic.boolalg import BooleanFunction assert _test_args(BooleanFunction(1, 2, 3)) @SKIP("abstract class") def test_sympy__logic__boolalg__BooleanAtom(): pass def test_sympy__logic__boolalg__BooleanTrue(): from sympy.logic.boolalg import true assert _test_args(true) def test_sympy__logic__boolalg__BooleanFalse(): from sympy.logic.boolalg import false assert _test_args(false) def test_sympy__logic__boolalg__Equivalent(): from sympy.logic.boolalg import Equivalent assert _test_args(Equivalent(x, 2)) def test_sympy__logic__boolalg__ITE(): from sympy.logic.boolalg import ITE assert _test_args(ITE(x, y, 1)) def test_sympy__logic__boolalg__Implies(): from sympy.logic.boolalg import Implies assert _test_args(Implies(x, y)) def test_sympy__logic__boolalg__Nand(): from sympy.logic.boolalg import Nand assert _test_args(Nand(x, y, 1)) def test_sympy__logic__boolalg__Nor(): from sympy.logic.boolalg import Nor assert _test_args(Nor(x, y)) def test_sympy__logic__boolalg__Not(): from sympy.logic.boolalg import Not assert _test_args(Not(x)) def test_sympy__logic__boolalg__Or(): from sympy.logic.boolalg import Or assert _test_args(Or(x, y)) def test_sympy__logic__boolalg__Xor(): from sympy.logic.boolalg import Xor assert _test_args(Xor(x, y, 2)) def test_sympy__logic__boolalg__Xnor(): from sympy.logic.boolalg import Xnor assert _test_args(Xnor(x, y, 2)) def test_sympy__logic__boolalg__Exclusive(): from sympy.logic.boolalg import Exclusive assert _test_args(Exclusive(x, y, z)) def test_sympy__matrices__matrices__DeferredVector(): from sympy.matrices.matrices import DeferredVector assert _test_args(DeferredVector("X")) @SKIP("abstract class") def test_sympy__matrices__expressions__matexpr__MatrixBase(): pass @SKIP("abstract class") def test_sympy__matrices__immutable__ImmutableRepMatrix(): pass def test_sympy__matrices__immutable__ImmutableDenseMatrix(): from sympy.matrices.immutable import ImmutableDenseMatrix m = ImmutableDenseMatrix([[1, 2], [3, 4]]) assert _test_args(m) assert _test_args(Basic(*list(m))) m = ImmutableDenseMatrix(1, 1, [1]) assert _test_args(m) assert _test_args(Basic(*list(m))) m = ImmutableDenseMatrix(2, 2, lambda i, j: 1) assert m[0, 0] is S.One m = ImmutableDenseMatrix(2, 2, lambda i, j: 1/(1 + i) + 1/(1 + j)) assert m[1, 1] is S.One # true div. will give 1.0 if i,j not sympified assert _test_args(m) assert _test_args(Basic(*list(m))) def test_sympy__matrices__immutable__ImmutableSparseMatrix(): from sympy.matrices.immutable import ImmutableSparseMatrix m = ImmutableSparseMatrix([[1, 2], [3, 4]]) assert _test_args(m) assert _test_args(Basic(*list(m))) m = ImmutableSparseMatrix(1, 1, {(0, 0): 1}) assert _test_args(m) assert _test_args(Basic(*list(m))) m = ImmutableSparseMatrix(1, 1, [1]) assert _test_args(m) assert _test_args(Basic(*list(m))) m = ImmutableSparseMatrix(2, 2, lambda i, j: 1) assert m[0, 0] is S.One m = ImmutableSparseMatrix(2, 2, lambda i, j: 1/(1 + i) + 1/(1 + j)) assert m[1, 1] is S.One # true div. will give 1.0 if i,j not sympified assert _test_args(m) assert _test_args(Basic(*list(m))) def test_sympy__matrices__expressions__slice__MatrixSlice(): from sympy.matrices.expressions.slice import MatrixSlice from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', 4, 4) assert _test_args(MatrixSlice(X, (0, 2), (0, 2))) def test_sympy__matrices__expressions__applyfunc__ElementwiseApplyFunction(): from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol("X", x, x) func = Lambda(x, x**2) assert _test_args(ElementwiseApplyFunction(func, X)) def test_sympy__matrices__expressions__blockmatrix__BlockDiagMatrix(): from sympy.matrices.expressions.blockmatrix import BlockDiagMatrix from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, x) Y = MatrixSymbol('Y', y, y) assert _test_args(BlockDiagMatrix(X, Y)) def test_sympy__matrices__expressions__blockmatrix__BlockMatrix(): from sympy.matrices.expressions.blockmatrix import BlockMatrix from sympy.matrices.expressions import MatrixSymbol, ZeroMatrix X = MatrixSymbol('X', x, x) Y = MatrixSymbol('Y', y, y) Z = MatrixSymbol('Z', x, y) O = ZeroMatrix(y, x) assert _test_args(BlockMatrix([[X, Z], [O, Y]])) def test_sympy__matrices__expressions__inverse__Inverse(): from sympy.matrices.expressions.inverse import Inverse from sympy.matrices.expressions import MatrixSymbol assert _test_args(Inverse(MatrixSymbol('A', 3, 3))) def test_sympy__matrices__expressions__matadd__MatAdd(): from sympy.matrices.expressions.matadd import MatAdd from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, y) Y = MatrixSymbol('Y', x, y) assert _test_args(MatAdd(X, Y)) @SKIP("abstract class") def test_sympy__matrices__expressions__matexpr__MatrixExpr(): pass def test_sympy__matrices__expressions__matexpr__MatrixElement(): from sympy.matrices.expressions.matexpr import MatrixSymbol, MatrixElement from sympy import S assert _test_args(MatrixElement(MatrixSymbol('A', 3, 5), S(2), S(3))) def test_sympy__matrices__expressions__matexpr__MatrixSymbol(): from sympy.matrices.expressions.matexpr import MatrixSymbol assert _test_args(MatrixSymbol('A', 3, 5)) def test_sympy__matrices__expressions__special__OneMatrix(): from sympy.matrices.expressions.special import OneMatrix assert _test_args(OneMatrix(3, 5)) def test_sympy__matrices__expressions__special__ZeroMatrix(): from sympy.matrices.expressions.special import ZeroMatrix assert _test_args(ZeroMatrix(3, 5)) def test_sympy__matrices__expressions__special__GenericZeroMatrix(): from sympy.matrices.expressions.special import GenericZeroMatrix assert _test_args(GenericZeroMatrix()) def test_sympy__matrices__expressions__special__Identity(): from sympy.matrices.expressions.special import Identity assert _test_args(Identity(3)) def test_sympy__matrices__expressions__special__GenericIdentity(): from sympy.matrices.expressions.special import GenericIdentity assert _test_args(GenericIdentity()) def test_sympy__matrices__expressions__sets__MatrixSet(): from sympy.matrices.expressions.sets import MatrixSet from sympy import S assert _test_args(MatrixSet(2, 2, S.Reals)) def test_sympy__matrices__expressions__matmul__MatMul(): from sympy.matrices.expressions.matmul import MatMul from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, y) Y = MatrixSymbol('Y', y, x) assert _test_args(MatMul(X, Y)) def test_sympy__matrices__expressions__dotproduct__DotProduct(): from sympy.matrices.expressions.dotproduct import DotProduct from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, 1) Y = MatrixSymbol('Y', x, 1) assert _test_args(DotProduct(X, Y)) def test_sympy__matrices__expressions__diagonal__DiagonalMatrix(): from sympy.matrices.expressions.diagonal import DiagonalMatrix from sympy.matrices.expressions import MatrixSymbol x = MatrixSymbol('x', 10, 1) assert _test_args(DiagonalMatrix(x)) def test_sympy__matrices__expressions__diagonal__DiagonalOf(): from sympy.matrices.expressions.diagonal import DiagonalOf from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('x', 10, 10) assert _test_args(DiagonalOf(X)) def test_sympy__matrices__expressions__diagonal__DiagMatrix(): from sympy.matrices.expressions.diagonal import DiagMatrix from sympy.matrices.expressions import MatrixSymbol x = MatrixSymbol('x', 10, 1) assert _test_args(DiagMatrix(x)) def test_sympy__matrices__expressions__hadamard__HadamardProduct(): from sympy.matrices.expressions.hadamard import HadamardProduct from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, y) Y = MatrixSymbol('Y', x, y) assert _test_args(HadamardProduct(X, Y)) def test_sympy__matrices__expressions__hadamard__HadamardPower(): from sympy.matrices.expressions.hadamard import HadamardPower from sympy.matrices.expressions import MatrixSymbol from sympy import Symbol X = MatrixSymbol('X', x, y) n = Symbol("n") assert _test_args(HadamardPower(X, n)) def test_sympy__matrices__expressions__kronecker__KroneckerProduct(): from sympy.matrices.expressions.kronecker import KroneckerProduct from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, y) Y = MatrixSymbol('Y', x, y) assert _test_args(KroneckerProduct(X, Y)) def test_sympy__matrices__expressions__matpow__MatPow(): from sympy.matrices.expressions.matpow import MatPow from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, x) assert _test_args(MatPow(X, 2)) def test_sympy__matrices__expressions__transpose__Transpose(): from sympy.matrices.expressions.transpose import Transpose from sympy.matrices.expressions import MatrixSymbol assert _test_args(Transpose(MatrixSymbol('A', 3, 5))) def test_sympy__matrices__expressions__adjoint__Adjoint(): from sympy.matrices.expressions.adjoint import Adjoint from sympy.matrices.expressions import MatrixSymbol assert _test_args(Adjoint(MatrixSymbol('A', 3, 5))) def test_sympy__matrices__expressions__trace__Trace(): from sympy.matrices.expressions.trace import Trace from sympy.matrices.expressions import MatrixSymbol assert _test_args(Trace(MatrixSymbol('A', 3, 3))) def test_sympy__matrices__expressions__determinant__Determinant(): from sympy.matrices.expressions.determinant import Determinant from sympy.matrices.expressions import MatrixSymbol assert _test_args(Determinant(MatrixSymbol('A', 3, 3))) def test_sympy__matrices__expressions__determinant__Permanent(): from sympy.matrices.expressions.determinant import Permanent from sympy.matrices.expressions import MatrixSymbol assert _test_args(Permanent(MatrixSymbol('A', 3, 4))) def test_sympy__matrices__expressions__funcmatrix__FunctionMatrix(): from sympy.matrices.expressions.funcmatrix import FunctionMatrix from sympy import symbols i, j = symbols('i,j') assert _test_args(FunctionMatrix(3, 3, Lambda((i, j), i - j) )) def test_sympy__matrices__expressions__fourier__DFT(): from sympy.matrices.expressions.fourier import DFT from sympy import S assert _test_args(DFT(S(2))) def test_sympy__matrices__expressions__fourier__IDFT(): from sympy.matrices.expressions.fourier import IDFT from sympy import S assert _test_args(IDFT(S(2))) from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', 10, 10) def test_sympy__matrices__expressions__factorizations__LofLU(): from sympy.matrices.expressions.factorizations import LofLU assert _test_args(LofLU(X)) def test_sympy__matrices__expressions__factorizations__UofLU(): from sympy.matrices.expressions.factorizations import UofLU assert _test_args(UofLU(X)) def test_sympy__matrices__expressions__factorizations__QofQR(): from sympy.matrices.expressions.factorizations import QofQR assert _test_args(QofQR(X)) def test_sympy__matrices__expressions__factorizations__RofQR(): from sympy.matrices.expressions.factorizations import RofQR assert _test_args(RofQR(X)) def test_sympy__matrices__expressions__factorizations__LofCholesky(): from sympy.matrices.expressions.factorizations import LofCholesky assert _test_args(LofCholesky(X)) def test_sympy__matrices__expressions__factorizations__UofCholesky(): from sympy.matrices.expressions.factorizations import UofCholesky assert _test_args(UofCholesky(X)) def test_sympy__matrices__expressions__factorizations__EigenVectors(): from sympy.matrices.expressions.factorizations import EigenVectors assert _test_args(EigenVectors(X)) def test_sympy__matrices__expressions__factorizations__EigenValues(): from sympy.matrices.expressions.factorizations import EigenValues assert _test_args(EigenValues(X)) def test_sympy__matrices__expressions__factorizations__UofSVD(): from sympy.matrices.expressions.factorizations import UofSVD assert _test_args(UofSVD(X)) def test_sympy__matrices__expressions__factorizations__VofSVD(): from sympy.matrices.expressions.factorizations import VofSVD assert _test_args(VofSVD(X)) def test_sympy__matrices__expressions__factorizations__SofSVD(): from sympy.matrices.expressions.factorizations import SofSVD assert _test_args(SofSVD(X)) @SKIP("abstract class") def test_sympy__matrices__expressions__factorizations__Factorization(): pass def test_sympy__matrices__expressions__permutation__PermutationMatrix(): from sympy.combinatorics import Permutation from sympy.matrices.expressions.permutation import PermutationMatrix assert _test_args(PermutationMatrix(Permutation([2, 0, 1]))) def test_sympy__matrices__expressions__permutation__MatrixPermute(): from sympy.combinatorics import Permutation from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.permutation import MatrixPermute A = MatrixSymbol('A', 3, 3) assert _test_args(MatrixPermute(A, Permutation([2, 0, 1]))) def test_sympy__matrices__expressions__companion__CompanionMatrix(): from sympy.core.symbol import Symbol from sympy.matrices.expressions.companion import CompanionMatrix from sympy.polys.polytools import Poly x = Symbol('x') p = Poly([1, 2, 3], x) assert _test_args(CompanionMatrix(p)) def test_sympy__physics__vector__frame__CoordinateSym(): from sympy.physics.vector import CoordinateSym from sympy.physics.vector import ReferenceFrame assert _test_args(CoordinateSym('R_x', ReferenceFrame('R'), 0)) def test_sympy__physics__paulialgebra__Pauli(): from sympy.physics.paulialgebra import Pauli assert _test_args(Pauli(1)) def test_sympy__physics__quantum__anticommutator__AntiCommutator(): from sympy.physics.quantum.anticommutator import AntiCommutator assert _test_args(AntiCommutator(x, y)) def test_sympy__physics__quantum__cartesian__PositionBra3D(): from sympy.physics.quantum.cartesian import PositionBra3D assert _test_args(PositionBra3D(x, y, z)) def test_sympy__physics__quantum__cartesian__PositionKet3D(): from sympy.physics.quantum.cartesian import PositionKet3D assert _test_args(PositionKet3D(x, y, z)) def test_sympy__physics__quantum__cartesian__PositionState3D(): from sympy.physics.quantum.cartesian import PositionState3D assert _test_args(PositionState3D(x, y, z)) def test_sympy__physics__quantum__cartesian__PxBra(): from sympy.physics.quantum.cartesian import PxBra assert _test_args(PxBra(x, y, z)) def test_sympy__physics__quantum__cartesian__PxKet(): from sympy.physics.quantum.cartesian import PxKet assert _test_args(PxKet(x, y, z)) def test_sympy__physics__quantum__cartesian__PxOp(): from sympy.physics.quantum.cartesian import PxOp assert _test_args(PxOp(x, y, z)) def test_sympy__physics__quantum__cartesian__XBra(): from sympy.physics.quantum.cartesian import XBra assert _test_args(XBra(x)) def test_sympy__physics__quantum__cartesian__XKet(): from sympy.physics.quantum.cartesian import XKet assert _test_args(XKet(x)) def test_sympy__physics__quantum__cartesian__XOp(): from sympy.physics.quantum.cartesian import XOp assert _test_args(XOp(x)) def test_sympy__physics__quantum__cartesian__YOp(): from sympy.physics.quantum.cartesian import YOp assert _test_args(YOp(x)) def test_sympy__physics__quantum__cartesian__ZOp(): from sympy.physics.quantum.cartesian import ZOp assert _test_args(ZOp(x)) def test_sympy__physics__quantum__cg__CG(): from sympy.physics.quantum.cg import CG from sympy import S assert _test_args(CG(Rational(3, 2), Rational(3, 2), S.Half, Rational(-1, 2), 1, 1)) def test_sympy__physics__quantum__cg__Wigner3j(): from sympy.physics.quantum.cg import Wigner3j assert _test_args(Wigner3j(6, 0, 4, 0, 2, 0)) def test_sympy__physics__quantum__cg__Wigner6j(): from sympy.physics.quantum.cg import Wigner6j assert _test_args(Wigner6j(1, 2, 3, 2, 1, 2)) def test_sympy__physics__quantum__cg__Wigner9j(): from sympy.physics.quantum.cg import Wigner9j assert _test_args(Wigner9j(2, 1, 1, Rational(3, 2), S.Half, 1, S.Half, S.Half, 0)) def test_sympy__physics__quantum__circuitplot__Mz(): from sympy.physics.quantum.circuitplot import Mz assert _test_args(Mz(0)) def test_sympy__physics__quantum__circuitplot__Mx(): from sympy.physics.quantum.circuitplot import Mx assert _test_args(Mx(0)) def test_sympy__physics__quantum__commutator__Commutator(): from sympy.physics.quantum.commutator import Commutator A, B = symbols('A,B', commutative=False) assert _test_args(Commutator(A, B)) def test_sympy__physics__quantum__constants__HBar(): from sympy.physics.quantum.constants import HBar assert _test_args(HBar()) def test_sympy__physics__quantum__dagger__Dagger(): from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.state import Ket assert _test_args(Dagger(Dagger(Ket('psi')))) def test_sympy__physics__quantum__gate__CGate(): from sympy.physics.quantum.gate import CGate, Gate assert _test_args(CGate((0, 1), Gate(2))) def test_sympy__physics__quantum__gate__CGateS(): from sympy.physics.quantum.gate import CGateS, Gate assert _test_args(CGateS((0, 1), Gate(2))) def test_sympy__physics__quantum__gate__CNotGate(): from sympy.physics.quantum.gate import CNotGate assert _test_args(CNotGate(0, 1)) def test_sympy__physics__quantum__gate__Gate(): from sympy.physics.quantum.gate import Gate assert _test_args(Gate(0)) def test_sympy__physics__quantum__gate__HadamardGate(): from sympy.physics.quantum.gate import HadamardGate assert _test_args(HadamardGate(0)) def test_sympy__physics__quantum__gate__IdentityGate(): from sympy.physics.quantum.gate import IdentityGate assert _test_args(IdentityGate(0)) def test_sympy__physics__quantum__gate__OneQubitGate(): from sympy.physics.quantum.gate import OneQubitGate assert _test_args(OneQubitGate(0)) def test_sympy__physics__quantum__gate__PhaseGate(): from sympy.physics.quantum.gate import PhaseGate assert _test_args(PhaseGate(0)) def test_sympy__physics__quantum__gate__SwapGate(): from sympy.physics.quantum.gate import SwapGate assert _test_args(SwapGate(0, 1)) def test_sympy__physics__quantum__gate__TGate(): from sympy.physics.quantum.gate import TGate assert _test_args(TGate(0)) def test_sympy__physics__quantum__gate__TwoQubitGate(): from sympy.physics.quantum.gate import TwoQubitGate assert _test_args(TwoQubitGate(0)) def test_sympy__physics__quantum__gate__UGate(): from sympy.physics.quantum.gate import UGate from sympy.matrices.immutable import ImmutableDenseMatrix from sympy import Integer, Tuple assert _test_args( UGate(Tuple(Integer(1)), ImmutableDenseMatrix([[1, 0], [0, 2]]))) def test_sympy__physics__quantum__gate__XGate(): from sympy.physics.quantum.gate import XGate assert _test_args(XGate(0)) def test_sympy__physics__quantum__gate__YGate(): from sympy.physics.quantum.gate import YGate assert _test_args(YGate(0)) def test_sympy__physics__quantum__gate__ZGate(): from sympy.physics.quantum.gate import ZGate assert _test_args(ZGate(0)) @SKIP("TODO: sympy.physics") def test_sympy__physics__quantum__grover__OracleGate(): from sympy.physics.quantum.grover import OracleGate assert _test_args(OracleGate()) def test_sympy__physics__quantum__grover__WGate(): from sympy.physics.quantum.grover import WGate assert _test_args(WGate(1)) def test_sympy__physics__quantum__hilbert__ComplexSpace(): from sympy.physics.quantum.hilbert import ComplexSpace assert _test_args(ComplexSpace(x)) def test_sympy__physics__quantum__hilbert__DirectSumHilbertSpace(): from sympy.physics.quantum.hilbert import DirectSumHilbertSpace, ComplexSpace, FockSpace c = ComplexSpace(2) f = FockSpace() assert _test_args(DirectSumHilbertSpace(c, f)) def test_sympy__physics__quantum__hilbert__FockSpace(): from sympy.physics.quantum.hilbert import FockSpace assert _test_args(FockSpace()) def test_sympy__physics__quantum__hilbert__HilbertSpace(): from sympy.physics.quantum.hilbert import HilbertSpace assert _test_args(HilbertSpace()) def test_sympy__physics__quantum__hilbert__L2(): from sympy.physics.quantum.hilbert import L2 from sympy import oo, Interval assert _test_args(L2(Interval(0, oo))) def test_sympy__physics__quantum__hilbert__TensorPowerHilbertSpace(): from sympy.physics.quantum.hilbert import TensorPowerHilbertSpace, FockSpace f = FockSpace() assert _test_args(TensorPowerHilbertSpace(f, 2)) def test_sympy__physics__quantum__hilbert__TensorProductHilbertSpace(): from sympy.physics.quantum.hilbert import TensorProductHilbertSpace, FockSpace, ComplexSpace c = ComplexSpace(2) f = FockSpace() assert _test_args(TensorProductHilbertSpace(f, c)) def test_sympy__physics__quantum__innerproduct__InnerProduct(): from sympy.physics.quantum import Bra, Ket, InnerProduct b = Bra('b') k = Ket('k') assert _test_args(InnerProduct(b, k)) def test_sympy__physics__quantum__operator__DifferentialOperator(): from sympy.physics.quantum.operator import DifferentialOperator from sympy import Derivative, Function f = Function('f') assert _test_args(DifferentialOperator(1/x*Derivative(f(x), x), f(x))) def test_sympy__physics__quantum__operator__HermitianOperator(): from sympy.physics.quantum.operator import HermitianOperator assert _test_args(HermitianOperator('H')) def test_sympy__physics__quantum__operator__IdentityOperator(): from sympy.physics.quantum.operator import IdentityOperator assert _test_args(IdentityOperator(5)) def test_sympy__physics__quantum__operator__Operator(): from sympy.physics.quantum.operator import Operator assert _test_args(Operator('A')) def test_sympy__physics__quantum__operator__OuterProduct(): from sympy.physics.quantum.operator import OuterProduct from sympy.physics.quantum import Ket, Bra b = Bra('b') k = Ket('k') assert _test_args(OuterProduct(k, b)) def test_sympy__physics__quantum__operator__UnitaryOperator(): from sympy.physics.quantum.operator import UnitaryOperator assert _test_args(UnitaryOperator('U')) def test_sympy__physics__quantum__piab__PIABBra(): from sympy.physics.quantum.piab import PIABBra assert _test_args(PIABBra('B')) def test_sympy__physics__quantum__boson__BosonOp(): from sympy.physics.quantum.boson import BosonOp assert _test_args(BosonOp('a')) assert _test_args(BosonOp('a', False)) def test_sympy__physics__quantum__boson__BosonFockKet(): from sympy.physics.quantum.boson import BosonFockKet assert _test_args(BosonFockKet(1)) def test_sympy__physics__quantum__boson__BosonFockBra(): from sympy.physics.quantum.boson import BosonFockBra assert _test_args(BosonFockBra(1)) def test_sympy__physics__quantum__boson__BosonCoherentKet(): from sympy.physics.quantum.boson import BosonCoherentKet assert _test_args(BosonCoherentKet(1)) def test_sympy__physics__quantum__boson__BosonCoherentBra(): from sympy.physics.quantum.boson import BosonCoherentBra assert _test_args(BosonCoherentBra(1)) def test_sympy__physics__quantum__fermion__FermionOp(): from sympy.physics.quantum.fermion import FermionOp assert _test_args(FermionOp('c')) assert _test_args(FermionOp('c', False)) def test_sympy__physics__quantum__fermion__FermionFockKet(): from sympy.physics.quantum.fermion import FermionFockKet assert _test_args(FermionFockKet(1)) def test_sympy__physics__quantum__fermion__FermionFockBra(): from sympy.physics.quantum.fermion import FermionFockBra assert _test_args(FermionFockBra(1)) def test_sympy__physics__quantum__pauli__SigmaOpBase(): from sympy.physics.quantum.pauli import SigmaOpBase assert _test_args(SigmaOpBase()) def test_sympy__physics__quantum__pauli__SigmaX(): from sympy.physics.quantum.pauli import SigmaX assert _test_args(SigmaX()) def test_sympy__physics__quantum__pauli__SigmaY(): from sympy.physics.quantum.pauli import SigmaY assert _test_args(SigmaY()) def test_sympy__physics__quantum__pauli__SigmaZ(): from sympy.physics.quantum.pauli import SigmaZ assert _test_args(SigmaZ()) def test_sympy__physics__quantum__pauli__SigmaMinus(): from sympy.physics.quantum.pauli import SigmaMinus assert _test_args(SigmaMinus()) def test_sympy__physics__quantum__pauli__SigmaPlus(): from sympy.physics.quantum.pauli import SigmaPlus assert _test_args(SigmaPlus()) def test_sympy__physics__quantum__pauli__SigmaZKet(): from sympy.physics.quantum.pauli import SigmaZKet assert _test_args(SigmaZKet(0)) def test_sympy__physics__quantum__pauli__SigmaZBra(): from sympy.physics.quantum.pauli import SigmaZBra assert _test_args(SigmaZBra(0)) def test_sympy__physics__quantum__piab__PIABHamiltonian(): from sympy.physics.quantum.piab import PIABHamiltonian assert _test_args(PIABHamiltonian('P')) def test_sympy__physics__quantum__piab__PIABKet(): from sympy.physics.quantum.piab import PIABKet assert _test_args(PIABKet('K')) def test_sympy__physics__quantum__qexpr__QExpr(): from sympy.physics.quantum.qexpr import QExpr assert _test_args(QExpr(0)) def test_sympy__physics__quantum__qft__Fourier(): from sympy.physics.quantum.qft import Fourier assert _test_args(Fourier(0, 1)) def test_sympy__physics__quantum__qft__IQFT(): from sympy.physics.quantum.qft import IQFT assert _test_args(IQFT(0, 1)) def test_sympy__physics__quantum__qft__QFT(): from sympy.physics.quantum.qft import QFT assert _test_args(QFT(0, 1)) def test_sympy__physics__quantum__qft__RkGate(): from sympy.physics.quantum.qft import RkGate assert _test_args(RkGate(0, 1)) def test_sympy__physics__quantum__qubit__IntQubit(): from sympy.physics.quantum.qubit import IntQubit assert _test_args(IntQubit(0)) def test_sympy__physics__quantum__qubit__IntQubitBra(): from sympy.physics.quantum.qubit import IntQubitBra assert _test_args(IntQubitBra(0)) def test_sympy__physics__quantum__qubit__IntQubitState(): from sympy.physics.quantum.qubit import IntQubitState, QubitState assert _test_args(IntQubitState(QubitState(0, 1))) def test_sympy__physics__quantum__qubit__Qubit(): from sympy.physics.quantum.qubit import Qubit assert _test_args(Qubit(0, 0, 0)) def test_sympy__physics__quantum__qubit__QubitBra(): from sympy.physics.quantum.qubit import QubitBra assert _test_args(QubitBra('1', 0)) def test_sympy__physics__quantum__qubit__QubitState(): from sympy.physics.quantum.qubit import QubitState assert _test_args(QubitState(0, 1)) def test_sympy__physics__quantum__density__Density(): from sympy.physics.quantum.density import Density from sympy.physics.quantum.state import Ket assert _test_args(Density([Ket(0), 0.5], [Ket(1), 0.5])) @SKIP("TODO: sympy.physics.quantum.shor: Cmod Not Implemented") def test_sympy__physics__quantum__shor__CMod(): from sympy.physics.quantum.shor import CMod assert _test_args(CMod()) def test_sympy__physics__quantum__spin__CoupledSpinState(): from sympy.physics.quantum.spin import CoupledSpinState assert _test_args(CoupledSpinState(1, 0, (1, 1))) assert _test_args(CoupledSpinState(1, 0, (1, S.Half, S.Half))) assert _test_args(CoupledSpinState( 1, 0, (1, S.Half, S.Half), ((2, 3, S.Half), (1, 2, 1)) )) j, m, j1, j2, j3, j12, x = symbols('j m j1:4 j12 x') assert CoupledSpinState( j, m, (j1, j2, j3)).subs(j2, x) == CoupledSpinState(j, m, (j1, x, j3)) assert CoupledSpinState(j, m, (j1, j2, j3), ((1, 3, j12), (1, 2, j)) ).subs(j12, x) == \ CoupledSpinState(j, m, (j1, j2, j3), ((1, 3, x), (1, 2, j)) ) def test_sympy__physics__quantum__spin__J2Op(): from sympy.physics.quantum.spin import J2Op assert _test_args(J2Op('J')) def test_sympy__physics__quantum__spin__JminusOp(): from sympy.physics.quantum.spin import JminusOp assert _test_args(JminusOp('J')) def test_sympy__physics__quantum__spin__JplusOp(): from sympy.physics.quantum.spin import JplusOp assert _test_args(JplusOp('J')) def test_sympy__physics__quantum__spin__JxBra(): from sympy.physics.quantum.spin import JxBra assert _test_args(JxBra(1, 0)) def test_sympy__physics__quantum__spin__JxBraCoupled(): from sympy.physics.quantum.spin import JxBraCoupled assert _test_args(JxBraCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JxKet(): from sympy.physics.quantum.spin import JxKet assert _test_args(JxKet(1, 0)) def test_sympy__physics__quantum__spin__JxKetCoupled(): from sympy.physics.quantum.spin import JxKetCoupled assert _test_args(JxKetCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JxOp(): from sympy.physics.quantum.spin import JxOp assert _test_args(JxOp('J')) def test_sympy__physics__quantum__spin__JyBra(): from sympy.physics.quantum.spin import JyBra assert _test_args(JyBra(1, 0)) def test_sympy__physics__quantum__spin__JyBraCoupled(): from sympy.physics.quantum.spin import JyBraCoupled assert _test_args(JyBraCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JyKet(): from sympy.physics.quantum.spin import JyKet assert _test_args(JyKet(1, 0)) def test_sympy__physics__quantum__spin__JyKetCoupled(): from sympy.physics.quantum.spin import JyKetCoupled assert _test_args(JyKetCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JyOp(): from sympy.physics.quantum.spin import JyOp assert _test_args(JyOp('J')) def test_sympy__physics__quantum__spin__JzBra(): from sympy.physics.quantum.spin import JzBra assert _test_args(JzBra(1, 0)) def test_sympy__physics__quantum__spin__JzBraCoupled(): from sympy.physics.quantum.spin import JzBraCoupled assert _test_args(JzBraCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JzKet(): from sympy.physics.quantum.spin import JzKet assert _test_args(JzKet(1, 0)) def test_sympy__physics__quantum__spin__JzKetCoupled(): from sympy.physics.quantum.spin import JzKetCoupled assert _test_args(JzKetCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JzOp(): from sympy.physics.quantum.spin import JzOp assert _test_args(JzOp('J')) def test_sympy__physics__quantum__spin__Rotation(): from sympy.physics.quantum.spin import Rotation assert _test_args(Rotation(pi, 0, pi/2)) def test_sympy__physics__quantum__spin__SpinState(): from sympy.physics.quantum.spin import SpinState assert _test_args(SpinState(1, 0)) def test_sympy__physics__quantum__spin__WignerD(): from sympy.physics.quantum.spin import WignerD assert _test_args(WignerD(0, 1, 2, 3, 4, 5)) def test_sympy__physics__quantum__state__Bra(): from sympy.physics.quantum.state import Bra assert _test_args(Bra(0)) def test_sympy__physics__quantum__state__BraBase(): from sympy.physics.quantum.state import BraBase assert _test_args(BraBase(0)) def test_sympy__physics__quantum__state__Ket(): from sympy.physics.quantum.state import Ket assert _test_args(Ket(0)) def test_sympy__physics__quantum__state__KetBase(): from sympy.physics.quantum.state import KetBase assert _test_args(KetBase(0)) def test_sympy__physics__quantum__state__State(): from sympy.physics.quantum.state import State assert _test_args(State(0)) def test_sympy__physics__quantum__state__StateBase(): from sympy.physics.quantum.state import StateBase assert _test_args(StateBase(0)) def test_sympy__physics__quantum__state__OrthogonalBra(): from sympy.physics.quantum.state import OrthogonalBra assert _test_args(OrthogonalBra(0)) def test_sympy__physics__quantum__state__OrthogonalKet(): from sympy.physics.quantum.state import OrthogonalKet assert _test_args(OrthogonalKet(0)) def test_sympy__physics__quantum__state__OrthogonalState(): from sympy.physics.quantum.state import OrthogonalState assert _test_args(OrthogonalState(0)) def test_sympy__physics__quantum__state__TimeDepBra(): from sympy.physics.quantum.state import TimeDepBra assert _test_args(TimeDepBra('psi', 't')) def test_sympy__physics__quantum__state__TimeDepKet(): from sympy.physics.quantum.state import TimeDepKet assert _test_args(TimeDepKet('psi', 't')) def test_sympy__physics__quantum__state__TimeDepState(): from sympy.physics.quantum.state import TimeDepState assert _test_args(TimeDepState('psi', 't')) def test_sympy__physics__quantum__state__Wavefunction(): from sympy.physics.quantum.state import Wavefunction from sympy.functions import sin from sympy import Piecewise n = 1 L = 1 g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True)) assert _test_args(Wavefunction(g, x)) def test_sympy__physics__quantum__tensorproduct__TensorProduct(): from sympy.physics.quantum.tensorproduct import TensorProduct assert _test_args(TensorProduct(x, y)) def test_sympy__physics__quantum__identitysearch__GateIdentity(): from sympy.physics.quantum.gate import X from sympy.physics.quantum.identitysearch import GateIdentity assert _test_args(GateIdentity(X(0), X(0))) def test_sympy__physics__quantum__sho1d__SHOOp(): from sympy.physics.quantum.sho1d import SHOOp assert _test_args(SHOOp('a')) def test_sympy__physics__quantum__sho1d__RaisingOp(): from sympy.physics.quantum.sho1d import RaisingOp assert _test_args(RaisingOp('a')) def test_sympy__physics__quantum__sho1d__LoweringOp(): from sympy.physics.quantum.sho1d import LoweringOp assert _test_args(LoweringOp('a')) def test_sympy__physics__quantum__sho1d__NumberOp(): from sympy.physics.quantum.sho1d import NumberOp assert _test_args(NumberOp('N')) def test_sympy__physics__quantum__sho1d__Hamiltonian(): from sympy.physics.quantum.sho1d import Hamiltonian assert _test_args(Hamiltonian('H')) def test_sympy__physics__quantum__sho1d__SHOState(): from sympy.physics.quantum.sho1d import SHOState assert _test_args(SHOState(0)) def test_sympy__physics__quantum__sho1d__SHOKet(): from sympy.physics.quantum.sho1d import SHOKet assert _test_args(SHOKet(0)) def test_sympy__physics__quantum__sho1d__SHOBra(): from sympy.physics.quantum.sho1d import SHOBra assert _test_args(SHOBra(0)) def test_sympy__physics__secondquant__AnnihilateBoson(): from sympy.physics.secondquant import AnnihilateBoson assert _test_args(AnnihilateBoson(0)) def test_sympy__physics__secondquant__AnnihilateFermion(): from sympy.physics.secondquant import AnnihilateFermion assert _test_args(AnnihilateFermion(0)) @SKIP("abstract class") def test_sympy__physics__secondquant__Annihilator(): pass def test_sympy__physics__secondquant__AntiSymmetricTensor(): from sympy.physics.secondquant import AntiSymmetricTensor i, j = symbols('i j', below_fermi=True) a, b = symbols('a b', above_fermi=True) assert _test_args(AntiSymmetricTensor('v', (a, i), (b, j))) def test_sympy__physics__secondquant__BosonState(): from sympy.physics.secondquant import BosonState assert _test_args(BosonState((0, 1))) @SKIP("abstract class") def test_sympy__physics__secondquant__BosonicOperator(): pass def test_sympy__physics__secondquant__Commutator(): from sympy.physics.secondquant import Commutator assert _test_args(Commutator(x, y)) def test_sympy__physics__secondquant__CreateBoson(): from sympy.physics.secondquant import CreateBoson assert _test_args(CreateBoson(0)) def test_sympy__physics__secondquant__CreateFermion(): from sympy.physics.secondquant import CreateFermion assert _test_args(CreateFermion(0)) @SKIP("abstract class") def test_sympy__physics__secondquant__Creator(): pass def test_sympy__physics__secondquant__Dagger(): from sympy.physics.secondquant import Dagger from sympy import I assert _test_args(Dagger(2*I)) def test_sympy__physics__secondquant__FermionState(): from sympy.physics.secondquant import FermionState assert _test_args(FermionState((0, 1))) def test_sympy__physics__secondquant__FermionicOperator(): from sympy.physics.secondquant import FermionicOperator assert _test_args(FermionicOperator(0)) def test_sympy__physics__secondquant__FockState(): from sympy.physics.secondquant import FockState assert _test_args(FockState((0, 1))) def test_sympy__physics__secondquant__FockStateBosonBra(): from sympy.physics.secondquant import FockStateBosonBra assert _test_args(FockStateBosonBra((0, 1))) def test_sympy__physics__secondquant__FockStateBosonKet(): from sympy.physics.secondquant import FockStateBosonKet assert _test_args(FockStateBosonKet((0, 1))) def test_sympy__physics__secondquant__FockStateBra(): from sympy.physics.secondquant import FockStateBra assert _test_args(FockStateBra((0, 1))) def test_sympy__physics__secondquant__FockStateFermionBra(): from sympy.physics.secondquant import FockStateFermionBra assert _test_args(FockStateFermionBra((0, 1))) def test_sympy__physics__secondquant__FockStateFermionKet(): from sympy.physics.secondquant import FockStateFermionKet assert _test_args(FockStateFermionKet((0, 1))) def test_sympy__physics__secondquant__FockStateKet(): from sympy.physics.secondquant import FockStateKet assert _test_args(FockStateKet((0, 1))) def test_sympy__physics__secondquant__InnerProduct(): from sympy.physics.secondquant import InnerProduct from sympy.physics.secondquant import FockStateKet, FockStateBra assert _test_args(InnerProduct(FockStateBra((0, 1)), FockStateKet((0, 1)))) def test_sympy__physics__secondquant__NO(): from sympy.physics.secondquant import NO, F, Fd assert _test_args(NO(Fd(x)*F(y))) def test_sympy__physics__secondquant__PermutationOperator(): from sympy.physics.secondquant import PermutationOperator assert _test_args(PermutationOperator(0, 1)) def test_sympy__physics__secondquant__SqOperator(): from sympy.physics.secondquant import SqOperator assert _test_args(SqOperator(0)) def test_sympy__physics__secondquant__TensorSymbol(): from sympy.physics.secondquant import TensorSymbol assert _test_args(TensorSymbol(x)) def test_sympy__physics__control__lti__LinearTimeInvariant(): # Direct instances of LinearTimeInvariant class are not allowed. # func(*args) tests for its derived classes (TransferFunction, # Series, Parallel and TransferFunctionMatrix) should pass. pass def test_sympy__physics__control__lti__SISOLinearTimeInvariant(): # Direct instances of SISOLinearTimeInvariant class are not allowed. pass def test_sympy__physics__control__lti__MIMOLinearTimeInvariant(): # Direct instances of MIMOLinearTimeInvariant class are not allowed. pass def test_sympy__physics__control__lti__TransferFunction(): from sympy.physics.control.lti import TransferFunction assert _test_args(TransferFunction(2, 3, x)) def test_sympy__physics__control__lti__Series(): from sympy.physics.control import Series, TransferFunction tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) assert _test_args(Series(tf1, tf2)) def test_sympy__physics__control__lti__MIMOSeries(): from sympy.physics.control import MIMOSeries, TransferFunction, TransferFunctionMatrix tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) tfm_1 = TransferFunctionMatrix([[tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_3 = TransferFunctionMatrix([[tf1], [tf2]]) assert _test_args(MIMOSeries(tfm_3, tfm_2, tfm_1)) def test_sympy__physics__control__lti__Parallel(): from sympy.physics.control import Parallel, TransferFunction tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) assert _test_args(Parallel(tf1, tf2)) def test_sympy__physics__control__lti__MIMOParallel(): from sympy.physics.control import MIMOParallel, TransferFunction, TransferFunctionMatrix tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) assert _test_args(MIMOParallel(tfm_1, tfm_2)) def test_sympy__physics__control__lti__Feedback(): from sympy.physics.control import TransferFunction, Feedback tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) assert _test_args(Feedback(tf1, tf2)) assert _test_args(Feedback(tf1, tf2, 1)) def test_sympy__physics__control__lti__MIMOFeedback(): from sympy.physics.control import TransferFunction, MIMOFeedback, TransferFunctionMatrix tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) tfm_1 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) tfm_2 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) assert _test_args(MIMOFeedback(tfm_1, tfm_2)) assert _test_args(MIMOFeedback(tfm_1, tfm_2, 1)) def test_sympy__physics__control__lti__TransferFunctionMatrix(): from sympy.physics.control import TransferFunction, TransferFunctionMatrix tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) assert _test_args(TransferFunctionMatrix([[tf1, tf2]])) def test_sympy__physics__units__dimensions__Dimension(): from sympy.physics.units.dimensions import Dimension assert _test_args(Dimension("length", "L")) def test_sympy__physics__units__dimensions__DimensionSystem(): from sympy.physics.units.dimensions import DimensionSystem from sympy.physics.units.definitions.dimension_definitions import length, time, velocity assert _test_args(DimensionSystem((length, time), (velocity,))) def test_sympy__physics__units__quantities__Quantity(): from sympy.physics.units.quantities import Quantity assert _test_args(Quantity("dam")) def test_sympy__physics__units__prefixes__Prefix(): from sympy.physics.units.prefixes import Prefix assert _test_args(Prefix('kilo', 'k', 3)) def test_sympy__core__numbers__AlgebraicNumber(): from sympy.core.numbers import AlgebraicNumber assert _test_args(AlgebraicNumber(sqrt(2), [1, 2, 3])) def test_sympy__polys__polytools__GroebnerBasis(): from sympy.polys.polytools import GroebnerBasis assert _test_args(GroebnerBasis([x, y, z], x, y, z)) def test_sympy__polys__polytools__Poly(): from sympy.polys.polytools import Poly assert _test_args(Poly(2, x, y)) def test_sympy__polys__polytools__PurePoly(): from sympy.polys.polytools import PurePoly assert _test_args(PurePoly(2, x, y)) @SKIP('abstract class') def test_sympy__polys__rootoftools__RootOf(): pass def test_sympy__polys__rootoftools__ComplexRootOf(): from sympy.polys.rootoftools import ComplexRootOf assert _test_args(ComplexRootOf(x**3 + x + 1, 0)) def test_sympy__polys__rootoftools__RootSum(): from sympy.polys.rootoftools import RootSum assert _test_args(RootSum(x**3 + x + 1, sin)) def test_sympy__series__limits__Limit(): from sympy.series.limits import Limit assert _test_args(Limit(x, x, 0, dir='-')) def test_sympy__series__order__Order(): from sympy.series.order import Order assert _test_args(Order(1, x, y)) @SKIP('Abstract Class') def test_sympy__series__sequences__SeqBase(): pass def test_sympy__series__sequences__EmptySequence(): # Need to imort the instance from series not the class from # series.sequence from sympy.series import EmptySequence assert _test_args(EmptySequence) @SKIP('Abstract Class') def test_sympy__series__sequences__SeqExpr(): pass def test_sympy__series__sequences__SeqPer(): from sympy.series.sequences import SeqPer assert _test_args(SeqPer((1, 2, 3), (0, 10))) def test_sympy__series__sequences__SeqFormula(): from sympy.series.sequences import SeqFormula assert _test_args(SeqFormula(x**2, (0, 10))) def test_sympy__series__sequences__RecursiveSeq(): from sympy.series.sequences import RecursiveSeq y = Function("y") n = symbols("n") assert _test_args(RecursiveSeq(y(n - 1) + y(n - 2), y(n), n, (0, 1))) assert _test_args(RecursiveSeq(y(n - 1) + y(n - 2), y(n), n)) def test_sympy__series__sequences__SeqExprOp(): from sympy.series.sequences import SeqExprOp, sequence s1 = sequence((1, 2, 3)) s2 = sequence(x**2) assert _test_args(SeqExprOp(s1, s2)) def test_sympy__series__sequences__SeqAdd(): from sympy.series.sequences import SeqAdd, sequence s1 = sequence((1, 2, 3)) s2 = sequence(x**2) assert _test_args(SeqAdd(s1, s2)) def test_sympy__series__sequences__SeqMul(): from sympy.series.sequences import SeqMul, sequence s1 = sequence((1, 2, 3)) s2 = sequence(x**2) assert _test_args(SeqMul(s1, s2)) @SKIP('Abstract Class') def test_sympy__series__series_class__SeriesBase(): pass def test_sympy__series__fourier__FourierSeries(): from sympy.series.fourier import fourier_series assert _test_args(fourier_series(x, (x, -pi, pi))) def test_sympy__series__fourier__FiniteFourierSeries(): from sympy.series.fourier import fourier_series assert _test_args(fourier_series(sin(pi*x), (x, -1, 1))) def test_sympy__series__formal__FormalPowerSeries(): from sympy.series.formal import fps assert _test_args(fps(log(1 + x), x)) def test_sympy__series__formal__Coeff(): from sympy.series.formal import fps assert _test_args(fps(x**2 + x + 1, x)) @SKIP('Abstract Class') def test_sympy__series__formal__FiniteFormalPowerSeries(): pass def test_sympy__series__formal__FormalPowerSeriesProduct(): from sympy.series.formal import fps f1, f2 = fps(sin(x)), fps(exp(x)) assert _test_args(f1.product(f2, x)) def test_sympy__series__formal__FormalPowerSeriesCompose(): from sympy.series.formal import fps f1, f2 = fps(exp(x)), fps(sin(x)) assert _test_args(f1.compose(f2, x)) def test_sympy__series__formal__FormalPowerSeriesInverse(): from sympy.series.formal import fps f1 = fps(exp(x)) assert _test_args(f1.inverse(x)) def test_sympy__simplify__hyperexpand__Hyper_Function(): from sympy.simplify.hyperexpand import Hyper_Function assert _test_args(Hyper_Function([2], [1])) def test_sympy__simplify__hyperexpand__G_Function(): from sympy.simplify.hyperexpand import G_Function assert _test_args(G_Function([2], [1], [], [])) @SKIP("abstract class") def test_sympy__tensor__array__ndim_array__ImmutableNDimArray(): pass def test_sympy__tensor__array__dense_ndim_array__ImmutableDenseNDimArray(): from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray densarr = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4)) assert _test_args(densarr) def test_sympy__tensor__array__sparse_ndim_array__ImmutableSparseNDimArray(): from sympy.tensor.array.sparse_ndim_array import ImmutableSparseNDimArray sparr = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4)) assert _test_args(sparr) def test_sympy__tensor__array__array_comprehension__ArrayComprehension(): from sympy.tensor.array.array_comprehension import ArrayComprehension arrcom = ArrayComprehension(x, (x, 1, 5)) assert _test_args(arrcom) def test_sympy__tensor__array__array_comprehension__ArrayComprehensionMap(): from sympy.tensor.array.array_comprehension import ArrayComprehensionMap arrcomma = ArrayComprehensionMap(lambda: 0, (x, 1, 5)) assert _test_args(arrcomma) def test_sympy__tensor__array__arrayop__Flatten(): from sympy.tensor.array.arrayop import Flatten from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray fla = Flatten(ImmutableDenseNDimArray(range(24)).reshape(2, 3, 4)) assert _test_args(fla) def test_sympy__tensor__array__array_derivatives__ArrayDerivative(): from sympy.tensor.array.array_derivatives import ArrayDerivative A = MatrixSymbol("A", 2, 2) arrder = ArrayDerivative(A, A, evaluate=False) assert _test_args(arrder) def test_sympy__tensor__array__expressions__array_expressions__ArraySymbol(): from sympy.tensor.array.expressions.array_expressions import ArraySymbol m, n, k = symbols("m n k") array = ArraySymbol("A", m, n, k, 2) assert _test_args(array) def test_sympy__tensor__array__expressions__array_expressions__ArrayElement(): from sympy.tensor.array.expressions.array_expressions import ArrayElement m, n, k = symbols("m n k") ae = ArrayElement("A", (m, n, k, 2)) assert _test_args(ae) def test_sympy__tensor__array__expressions__array_expressions__ZeroArray(): from sympy.tensor.array.expressions.array_expressions import ZeroArray m, n, k = symbols("m n k") za = ZeroArray(m, n, k, 2) assert _test_args(za) def test_sympy__tensor__array__expressions__array_expressions__OneArray(): from sympy.tensor.array.expressions.array_expressions import OneArray m, n, k = symbols("m n k") za = OneArray(m, n, k, 2) assert _test_args(za) def test_sympy__tensor__functions__TensorProduct(): from sympy.tensor.functions import TensorProduct A = MatrixSymbol('A', 3, 3) B = MatrixSymbol('B', 3, 3) tp = TensorProduct(A, B) assert _test_args(tp) def test_sympy__tensor__indexed__Idx(): from sympy.tensor.indexed import Idx assert _test_args(Idx('test')) assert _test_args(Idx(1, (0, 10))) def test_sympy__tensor__indexed__Indexed(): from sympy.tensor.indexed import Indexed, Idx assert _test_args(Indexed('A', Idx('i'), Idx('j'))) def test_sympy__tensor__indexed__IndexedBase(): from sympy.tensor.indexed import IndexedBase assert _test_args(IndexedBase('A', shape=(x, y))) assert _test_args(IndexedBase('A', 1)) assert _test_args(IndexedBase('A')[0, 1]) def test_sympy__tensor__tensor__TensorIndexType(): from sympy.tensor.tensor import TensorIndexType assert _test_args(TensorIndexType('Lorentz')) @SKIP("deprecated class") def test_sympy__tensor__tensor__TensorType(): pass def test_sympy__tensor__tensor__TensorSymmetry(): from sympy.tensor.tensor import TensorSymmetry, get_symmetric_group_sgs assert _test_args(TensorSymmetry(get_symmetric_group_sgs(2))) def test_sympy__tensor__tensor__TensorHead(): from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, TensorHead Lorentz = TensorIndexType('Lorentz', dummy_name='L') sym = TensorSymmetry(get_symmetric_group_sgs(1)) assert _test_args(TensorHead('p', [Lorentz], sym, 0)) def test_sympy__tensor__tensor__TensorIndex(): from sympy.tensor.tensor import TensorIndexType, TensorIndex Lorentz = TensorIndexType('Lorentz', dummy_name='L') assert _test_args(TensorIndex('i', Lorentz)) @SKIP("abstract class") def test_sympy__tensor__tensor__TensExpr(): pass def test_sympy__tensor__tensor__TensAdd(): from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, TensAdd, tensor_heads Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b = tensor_indices('a,b', Lorentz) sym = TensorSymmetry(get_symmetric_group_sgs(1)) p, q = tensor_heads('p,q', [Lorentz], sym) t1 = p(a) t2 = q(a) assert _test_args(TensAdd(t1, t2)) def test_sympy__tensor__tensor__Tensor(): from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, TensorHead Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b = tensor_indices('a,b', Lorentz) sym = TensorSymmetry(get_symmetric_group_sgs(1)) p = TensorHead('p', [Lorentz], sym) assert _test_args(p(a)) def test_sympy__tensor__tensor__TensMul(): from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, tensor_heads Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b = tensor_indices('a,b', Lorentz) sym = TensorSymmetry(get_symmetric_group_sgs(1)) p, q = tensor_heads('p, q', [Lorentz], sym) assert _test_args(3*p(a)*q(b)) def test_sympy__tensor__tensor__TensorElement(): from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorElement L = TensorIndexType("L") A = TensorHead("A", [L, L]) telem = TensorElement(A(x, y), {x: 1}) assert _test_args(telem) def test_sympy__tensor__toperators__PartialDerivative(): from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead from sympy.tensor.toperators import PartialDerivative Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b = tensor_indices('a,b', Lorentz) A = TensorHead("A", [Lorentz]) assert _test_args(PartialDerivative(A(a), A(b))) def test_as_coeff_add(): assert (7, (3*x, 4*x**2)) == (7 + 3*x + 4*x**2).as_coeff_add() def test_sympy__geometry__curve__Curve(): from sympy.geometry.curve import Curve assert _test_args(Curve((x, 1), (x, 0, 1))) def test_sympy__geometry__point__Point(): from sympy.geometry.point import Point assert _test_args(Point(0, 1)) def test_sympy__geometry__point__Point2D(): from sympy.geometry.point import Point2D assert _test_args(Point2D(0, 1)) def test_sympy__geometry__point__Point3D(): from sympy.geometry.point import Point3D assert _test_args(Point3D(0, 1, 2)) def test_sympy__geometry__ellipse__Ellipse(): from sympy.geometry.ellipse import Ellipse assert _test_args(Ellipse((0, 1), 2, 3)) def test_sympy__geometry__ellipse__Circle(): from sympy.geometry.ellipse import Circle assert _test_args(Circle((0, 1), 2)) def test_sympy__geometry__parabola__Parabola(): from sympy.geometry.parabola import Parabola from sympy.geometry.line import Line assert _test_args(Parabola((0, 0), Line((2, 3), (4, 3)))) @SKIP("abstract class") def test_sympy__geometry__line__LinearEntity(): pass def test_sympy__geometry__line__Line(): from sympy.geometry.line import Line assert _test_args(Line((0, 1), (2, 3))) def test_sympy__geometry__line__Ray(): from sympy.geometry.line import Ray assert _test_args(Ray((0, 1), (2, 3))) def test_sympy__geometry__line__Segment(): from sympy.geometry.line import Segment assert _test_args(Segment((0, 1), (2, 3))) @SKIP("abstract class") def test_sympy__geometry__line__LinearEntity2D(): pass def test_sympy__geometry__line__Line2D(): from sympy.geometry.line import Line2D assert _test_args(Line2D((0, 1), (2, 3))) def test_sympy__geometry__line__Ray2D(): from sympy.geometry.line import Ray2D assert _test_args(Ray2D((0, 1), (2, 3))) def test_sympy__geometry__line__Segment2D(): from sympy.geometry.line import Segment2D assert _test_args(Segment2D((0, 1), (2, 3))) @SKIP("abstract class") def test_sympy__geometry__line__LinearEntity3D(): pass def test_sympy__geometry__line__Line3D(): from sympy.geometry.line import Line3D assert _test_args(Line3D((0, 1, 1), (2, 3, 4))) def test_sympy__geometry__line__Segment3D(): from sympy.geometry.line import Segment3D assert _test_args(Segment3D((0, 1, 1), (2, 3, 4))) def test_sympy__geometry__line__Ray3D(): from sympy.geometry.line import Ray3D assert _test_args(Ray3D((0, 1, 1), (2, 3, 4))) def test_sympy__geometry__plane__Plane(): from sympy.geometry.plane import Plane assert _test_args(Plane((1, 1, 1), (-3, 4, -2), (1, 2, 3))) def test_sympy__geometry__polygon__Polygon(): from sympy.geometry.polygon import Polygon assert _test_args(Polygon((0, 1), (2, 3), (4, 5), (6, 7))) def test_sympy__geometry__polygon__RegularPolygon(): from sympy.geometry.polygon import RegularPolygon assert _test_args(RegularPolygon((0, 1), 2, 3, 4)) def test_sympy__geometry__polygon__Triangle(): from sympy.geometry.polygon import Triangle assert _test_args(Triangle((0, 1), (2, 3), (4, 5))) def test_sympy__geometry__entity__GeometryEntity(): from sympy.geometry.entity import GeometryEntity from sympy.geometry.point import Point assert _test_args(GeometryEntity(Point(1, 0), 1, [1, 2])) @SKIP("abstract class") def test_sympy__geometry__entity__GeometrySet(): pass def test_sympy__diffgeom__diffgeom__Manifold(): from sympy.diffgeom import Manifold assert _test_args(Manifold('name', 3)) def test_sympy__diffgeom__diffgeom__Patch(): from sympy.diffgeom import Manifold, Patch assert _test_args(Patch('name', Manifold('name', 3))) def test_sympy__diffgeom__diffgeom__CoordSystem(): from sympy.diffgeom import Manifold, Patch, CoordSystem assert _test_args(CoordSystem('name', Patch('name', Manifold('name', 3)))) assert _test_args(CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])) def test_sympy__diffgeom__diffgeom__CoordinateSymbol(): from sympy.diffgeom import Manifold, Patch, CoordSystem, CoordinateSymbol assert _test_args(CoordinateSymbol(CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]), 0)) def test_sympy__diffgeom__diffgeom__Point(): from sympy.diffgeom import Manifold, Patch, CoordSystem, Point assert _test_args(Point( CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]), [x, y])) def test_sympy__diffgeom__diffgeom__BaseScalarField(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) assert _test_args(BaseScalarField(cs, 0)) def test_sympy__diffgeom__diffgeom__BaseVectorField(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) assert _test_args(BaseVectorField(cs, 0)) def test_sympy__diffgeom__diffgeom__Differential(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) assert _test_args(Differential(BaseScalarField(cs, 0))) def test_sympy__diffgeom__diffgeom__Commutator(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField, Commutator cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) cs1 = CoordSystem('name1', Patch('name', Manifold('name', 3)), [a, b, c]) v = BaseVectorField(cs, 0) v1 = BaseVectorField(cs1, 0) assert _test_args(Commutator(v, v1)) def test_sympy__diffgeom__diffgeom__TensorProduct(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, TensorProduct cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) d = Differential(BaseScalarField(cs, 0)) assert _test_args(TensorProduct(d, d)) def test_sympy__diffgeom__diffgeom__WedgeProduct(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, WedgeProduct cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) d = Differential(BaseScalarField(cs, 0)) d1 = Differential(BaseScalarField(cs, 1)) assert _test_args(WedgeProduct(d, d1)) def test_sympy__diffgeom__diffgeom__LieDerivative(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, BaseVectorField, LieDerivative cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) d = Differential(BaseScalarField(cs, 0)) v = BaseVectorField(cs, 0) assert _test_args(LieDerivative(v, d)) @XFAIL def test_sympy__diffgeom__diffgeom__BaseCovarDerivativeOp(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseCovarDerivativeOp cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) assert _test_args(BaseCovarDerivativeOp(cs, 0, [[[0, ]*3, ]*3, ]*3)) def test_sympy__diffgeom__diffgeom__CovarDerivativeOp(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField, CovarDerivativeOp cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) v = BaseVectorField(cs, 0) _test_args(CovarDerivativeOp(v, [[[0, ]*3, ]*3, ]*3)) def test_sympy__categories__baseclasses__Class(): from sympy.categories.baseclasses import Class assert _test_args(Class()) def test_sympy__categories__baseclasses__Object(): from sympy.categories import Object assert _test_args(Object("A")) @XFAIL def test_sympy__categories__baseclasses__Morphism(): from sympy.categories import Object, Morphism assert _test_args(Morphism(Object("A"), Object("B"))) def test_sympy__categories__baseclasses__IdentityMorphism(): from sympy.categories import Object, IdentityMorphism assert _test_args(IdentityMorphism(Object("A"))) def test_sympy__categories__baseclasses__NamedMorphism(): from sympy.categories import Object, NamedMorphism assert _test_args(NamedMorphism(Object("A"), Object("B"), "f")) def test_sympy__categories__baseclasses__CompositeMorphism(): from sympy.categories import Object, NamedMorphism, CompositeMorphism A = Object("A") B = Object("B") C = Object("C") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") assert _test_args(CompositeMorphism(f, g)) def test_sympy__categories__baseclasses__Diagram(): from sympy.categories import Object, NamedMorphism, Diagram A = Object("A") B = Object("B") f = NamedMorphism(A, B, "f") d = Diagram([f]) assert _test_args(d) def test_sympy__categories__baseclasses__Category(): from sympy.categories import Object, NamedMorphism, Diagram, Category A = Object("A") B = Object("B") C = Object("C") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") d1 = Diagram([f, g]) d2 = Diagram([f]) K = Category("K", commutative_diagrams=[d1, d2]) assert _test_args(K) def test_sympy__ntheory__factor___totient(): from sympy.ntheory.factor_ import totient k = symbols('k', integer=True) t = totient(k) assert _test_args(t) def test_sympy__ntheory__factor___reduced_totient(): from sympy.ntheory.factor_ import reduced_totient k = symbols('k', integer=True) t = reduced_totient(k) assert _test_args(t) def test_sympy__ntheory__factor___divisor_sigma(): from sympy.ntheory.factor_ import divisor_sigma k = symbols('k', integer=True) n = symbols('n', integer=True) t = divisor_sigma(n, k) assert _test_args(t) def test_sympy__ntheory__factor___udivisor_sigma(): from sympy.ntheory.factor_ import udivisor_sigma k = symbols('k', integer=True) n = symbols('n', integer=True) t = udivisor_sigma(n, k) assert _test_args(t) def test_sympy__ntheory__factor___primenu(): from sympy.ntheory.factor_ import primenu n = symbols('n', integer=True) t = primenu(n) assert _test_args(t) def test_sympy__ntheory__factor___primeomega(): from sympy.ntheory.factor_ import primeomega n = symbols('n', integer=True) t = primeomega(n) assert _test_args(t) def test_sympy__ntheory__residue_ntheory__mobius(): from sympy.ntheory import mobius assert _test_args(mobius(2)) def test_sympy__ntheory__generate__primepi(): from sympy.ntheory import primepi n = symbols('n') t = primepi(n) assert _test_args(t) def test_sympy__physics__optics__waves__TWave(): from sympy.physics.optics import TWave A, f, phi = symbols('A, f, phi') assert _test_args(TWave(A, f, phi)) def test_sympy__physics__optics__gaussopt__BeamParameter(): from sympy.physics.optics import BeamParameter assert _test_args(BeamParameter(530e-9, 1, w=1e-3)) def test_sympy__physics__optics__medium__Medium(): from sympy.physics.optics import Medium assert _test_args(Medium('m')) def test_sympy__tensor__array__expressions__array_expressions__ArrayContraction(): from sympy.tensor.array.expressions.array_expressions import ArrayContraction from sympy import IndexedBase A = symbols("A", cls=IndexedBase) assert _test_args(ArrayContraction(A, (0, 1))) def test_sympy__tensor__array__expressions__array_expressions__ArrayDiagonal(): from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal from sympy import IndexedBase A = symbols("A", cls=IndexedBase) assert _test_args(ArrayDiagonal(A, (0, 1))) def test_sympy__tensor__array__expressions__array_expressions__ArrayTensorProduct(): from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct from sympy import IndexedBase A, B = symbols("A B", cls=IndexedBase) assert _test_args(ArrayTensorProduct(A, B)) def test_sympy__tensor__array__expressions__array_expressions__ArrayAdd(): from sympy.tensor.array.expressions.array_expressions import ArrayAdd from sympy import IndexedBase A, B = symbols("A B", cls=IndexedBase) assert _test_args(ArrayAdd(A, B)) def test_sympy__tensor__array__expressions__array_expressions__PermuteDims(): from sympy.tensor.array.expressions.array_expressions import PermuteDims A = MatrixSymbol("A", 4, 4) assert _test_args(PermuteDims(A, (1, 0))) def test_sympy__tensor__array__expressions__array_expressions__ArrayElementwiseApplyFunc(): from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayElementwiseApplyFunc A = ArraySymbol("A", 4) assert _test_args(ArrayElementwiseApplyFunc(exp, A)) def test_sympy__codegen__ast__Assignment(): from sympy.codegen.ast import Assignment assert _test_args(Assignment(x, y)) def test_sympy__codegen__cfunctions__expm1(): from sympy.codegen.cfunctions import expm1 assert _test_args(expm1(x)) def test_sympy__codegen__cfunctions__log1p(): from sympy.codegen.cfunctions import log1p assert _test_args(log1p(x)) def test_sympy__codegen__cfunctions__exp2(): from sympy.codegen.cfunctions import exp2 assert _test_args(exp2(x)) def test_sympy__codegen__cfunctions__log2(): from sympy.codegen.cfunctions import log2 assert _test_args(log2(x)) def test_sympy__codegen__cfunctions__fma(): from sympy.codegen.cfunctions import fma assert _test_args(fma(x, y, z)) def test_sympy__codegen__cfunctions__log10(): from sympy.codegen.cfunctions import log10 assert _test_args(log10(x)) def test_sympy__codegen__cfunctions__Sqrt(): from sympy.codegen.cfunctions import Sqrt assert _test_args(Sqrt(x)) def test_sympy__codegen__cfunctions__Cbrt(): from sympy.codegen.cfunctions import Cbrt assert _test_args(Cbrt(x)) def test_sympy__codegen__cfunctions__hypot(): from sympy.codegen.cfunctions import hypot assert _test_args(hypot(x, y)) def test_sympy__codegen__fnodes__FFunction(): from sympy.codegen.fnodes import FFunction assert _test_args(FFunction('f')) def test_sympy__codegen__fnodes__F95Function(): from sympy.codegen.fnodes import F95Function assert _test_args(F95Function('f')) def test_sympy__codegen__fnodes__isign(): from sympy.codegen.fnodes import isign assert _test_args(isign(1, x)) def test_sympy__codegen__fnodes__dsign(): from sympy.codegen.fnodes import dsign assert _test_args(dsign(1, x)) def test_sympy__codegen__fnodes__cmplx(): from sympy.codegen.fnodes import cmplx assert _test_args(cmplx(x, y)) def test_sympy__codegen__fnodes__kind(): from sympy.codegen.fnodes import kind assert _test_args(kind(x)) def test_sympy__codegen__fnodes__merge(): from sympy.codegen.fnodes import merge assert _test_args(merge(1, 2, Eq(x, 0))) def test_sympy__codegen__fnodes___literal(): from sympy.codegen.fnodes import _literal assert _test_args(_literal(1)) def test_sympy__codegen__fnodes__literal_sp(): from sympy.codegen.fnodes import literal_sp assert _test_args(literal_sp(1)) def test_sympy__codegen__fnodes__literal_dp(): from sympy.codegen.fnodes import literal_dp assert _test_args(literal_dp(1)) def test_sympy__codegen__matrix_nodes__MatrixSolve(): from sympy.matrices import MatrixSymbol from sympy.codegen.matrix_nodes import MatrixSolve A = MatrixSymbol('A', 3, 3) v = MatrixSymbol('x', 3, 1) assert _test_args(MatrixSolve(A, v)) def test_sympy__vector__coordsysrect__CoordSys3D(): from sympy.vector.coordsysrect import CoordSys3D assert _test_args(CoordSys3D('C')) def test_sympy__vector__point__Point(): from sympy.vector.point import Point assert _test_args(Point('P')) def test_sympy__vector__basisdependent__BasisDependent(): #from sympy.vector.basisdependent import BasisDependent #These classes have been created to maintain an OOP hierarchy #for Vectors and Dyadics. Are NOT meant to be initialized pass def test_sympy__vector__basisdependent__BasisDependentMul(): #from sympy.vector.basisdependent import BasisDependentMul #These classes have been created to maintain an OOP hierarchy #for Vectors and Dyadics. Are NOT meant to be initialized pass def test_sympy__vector__basisdependent__BasisDependentAdd(): #from sympy.vector.basisdependent import BasisDependentAdd #These classes have been created to maintain an OOP hierarchy #for Vectors and Dyadics. Are NOT meant to be initialized pass def test_sympy__vector__basisdependent__BasisDependentZero(): #from sympy.vector.basisdependent import BasisDependentZero #These classes have been created to maintain an OOP hierarchy #for Vectors and Dyadics. Are NOT meant to be initialized pass def test_sympy__vector__vector__BaseVector(): from sympy.vector.vector import BaseVector from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(BaseVector(0, C, ' ', ' ')) def test_sympy__vector__vector__VectorAdd(): from sympy.vector.vector import VectorAdd, VectorMul from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') from sympy.abc import a, b, c, x, y, z v1 = a*C.i + b*C.j + c*C.k v2 = x*C.i + y*C.j + z*C.k assert _test_args(VectorAdd(v1, v2)) assert _test_args(VectorMul(x, v1)) def test_sympy__vector__vector__VectorMul(): from sympy.vector.vector import VectorMul from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') from sympy.abc import a assert _test_args(VectorMul(a, C.i)) def test_sympy__vector__vector__VectorZero(): from sympy.vector.vector import VectorZero assert _test_args(VectorZero()) def test_sympy__vector__vector__Vector(): #from sympy.vector.vector import Vector #Vector is never to be initialized using args pass def test_sympy__vector__vector__Cross(): from sympy.vector.vector import Cross from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') _test_args(Cross(C.i, C.j)) def test_sympy__vector__vector__Dot(): from sympy.vector.vector import Dot from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') _test_args(Dot(C.i, C.j)) def test_sympy__vector__dyadic__Dyadic(): #from sympy.vector.dyadic import Dyadic #Dyadic is never to be initialized using args pass def test_sympy__vector__dyadic__BaseDyadic(): from sympy.vector.dyadic import BaseDyadic from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(BaseDyadic(C.i, C.j)) def test_sympy__vector__dyadic__DyadicMul(): from sympy.vector.dyadic import BaseDyadic, DyadicMul from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(DyadicMul(3, BaseDyadic(C.i, C.j))) def test_sympy__vector__dyadic__DyadicAdd(): from sympy.vector.dyadic import BaseDyadic, DyadicAdd from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(2 * DyadicAdd(BaseDyadic(C.i, C.i), BaseDyadic(C.i, C.j))) def test_sympy__vector__dyadic__DyadicZero(): from sympy.vector.dyadic import DyadicZero assert _test_args(DyadicZero()) def test_sympy__vector__deloperator__Del(): from sympy.vector.deloperator import Del assert _test_args(Del()) def test_sympy__vector__implicitregion__ImplicitRegion(): from sympy.vector.implicitregion import ImplicitRegion from sympy.abc import x, y assert _test_args(ImplicitRegion((x, y), y**3 - 4*x)) def test_sympy__vector__integrals__ParametricIntegral(): from sympy.vector.integrals import ParametricIntegral from sympy.vector.parametricregion import ParametricRegion from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(ParametricIntegral(C.y*C.i - 10*C.j,\ ParametricRegion((x, y), (x, 1, 3), (y, -2, 2)))) def test_sympy__vector__operators__Curl(): from sympy.vector.operators import Curl from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(Curl(C.i)) def test_sympy__vector__operators__Laplacian(): from sympy.vector.operators import Laplacian from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(Laplacian(C.i)) def test_sympy__vector__operators__Divergence(): from sympy.vector.operators import Divergence from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(Divergence(C.i)) def test_sympy__vector__operators__Gradient(): from sympy.vector.operators import Gradient from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(Gradient(C.x)) def test_sympy__vector__orienters__Orienter(): #from sympy.vector.orienters import Orienter #Not to be initialized pass def test_sympy__vector__orienters__ThreeAngleOrienter(): #from sympy.vector.orienters import ThreeAngleOrienter #Not to be initialized pass def test_sympy__vector__orienters__AxisOrienter(): from sympy.vector.orienters import AxisOrienter from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(AxisOrienter(x, C.i)) def test_sympy__vector__orienters__BodyOrienter(): from sympy.vector.orienters import BodyOrienter assert _test_args(BodyOrienter(x, y, z, '123')) def test_sympy__vector__orienters__SpaceOrienter(): from sympy.vector.orienters import SpaceOrienter assert _test_args(SpaceOrienter(x, y, z, '123')) def test_sympy__vector__orienters__QuaternionOrienter(): from sympy.vector.orienters import QuaternionOrienter a, b, c, d = symbols('a b c d') assert _test_args(QuaternionOrienter(a, b, c, d)) def test_sympy__vector__parametricregion__ParametricRegion(): from sympy.abc import t from sympy.vector.parametricregion import ParametricRegion assert _test_args(ParametricRegion((t, t**3), (t, 0, 2))) def test_sympy__vector__scalar__BaseScalar(): from sympy.vector.scalar import BaseScalar from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(BaseScalar(0, C, ' ', ' ')) def test_sympy__physics__wigner__Wigner3j(): from sympy.physics.wigner import Wigner3j assert _test_args(Wigner3j(0, 0, 0, 0, 0, 0)) def test_sympy__integrals__rubi__symbol__matchpyWC(): from sympy.integrals.rubi.symbol import matchpyWC assert _test_args(matchpyWC(1, True, 'a')) def test_sympy__integrals__rubi__utility_function__rubi_unevaluated_expr(): from sympy.integrals.rubi.utility_function import rubi_unevaluated_expr a = symbols('a') assert _test_args(rubi_unevaluated_expr(a)) def test_sympy__integrals__rubi__utility_function__rubi_exp(): from sympy.integrals.rubi.utility_function import rubi_exp assert _test_args(rubi_exp(5)) def test_sympy__integrals__rubi__utility_function__rubi_log(): from sympy.integrals.rubi.utility_function import rubi_log assert _test_args(rubi_log(5)) def test_sympy__integrals__rubi__utility_function__Int(): from sympy.integrals.rubi.utility_function import Int assert _test_args(Int(5, x)) def test_sympy__integrals__rubi__utility_function__Util_Coefficient(): from sympy.integrals.rubi.utility_function import Util_Coefficient a, x = symbols('a x') assert _test_args(Util_Coefficient(a, x)) def test_sympy__integrals__rubi__utility_function__Gamma(): from sympy.integrals.rubi.utility_function import Gamma assert _test_args(Gamma(5)) def test_sympy__integrals__rubi__utility_function__Util_Part(): from sympy.integrals.rubi.utility_function import Util_Part a, b = symbols('a b') assert _test_args(Util_Part(a + b, 0)) def test_sympy__integrals__rubi__utility_function__PolyGamma(): from sympy.integrals.rubi.utility_function import PolyGamma assert _test_args(PolyGamma(1, 1)) def test_sympy__integrals__rubi__utility_function__ProductLog(): from sympy.integrals.rubi.utility_function import ProductLog assert _test_args(ProductLog(1)) def test_sympy__combinatorics__schur_number__SchurNumber(): from sympy.combinatorics.schur_number import SchurNumber assert _test_args(SchurNumber(1)) def test_sympy__combinatorics__perm_groups__SymmetricPermutationGroup(): from sympy.combinatorics.perm_groups import SymmetricPermutationGroup assert _test_args(SymmetricPermutationGroup(5)) def test_sympy__combinatorics__perm_groups__Coset(): from sympy.combinatorics.permutations import Permutation from sympy.combinatorics.perm_groups import PermutationGroup, Coset a = Permutation(1, 2) b = Permutation(0, 1) G = PermutationGroup([a, b]) assert _test_args(Coset(a, G))
fde39ccac63530d24f291debac165ce59b543590c503b61a20c1f9c7de595497
from sympy.core import ( Basic, Rational, Symbol, S, Float, Integer, Mul, Number, Pow, Expr, I, nan, pi, symbols, oo, zoo, N) from sympy.core.parameters import global_parameters from sympy.core.tests.test_evalf import NS from sympy.core.function import expand_multinomial from sympy.functions.elementary.miscellaneous import sqrt, cbrt from sympy.functions.elementary.exponential import exp, log from sympy.functions.special.error_functions import erf from sympy.functions.elementary.trigonometric import ( sin, cos, tan, sec, csc, sinh, cosh, tanh, atan) from sympy.polys import Poly from sympy.series.order import O from sympy.sets import FiniteSet from sympy.core.expr import unchanged from sympy.core.power import power from sympy.testing.pytest import warns_deprecated_sympy, _both_exp_pow def test_rational(): a = Rational(1, 5) r = sqrt(5)/5 assert sqrt(a) == r assert 2*sqrt(a) == 2*r r = a*a**S.Half assert a**Rational(3, 2) == r assert 2*a**Rational(3, 2) == 2*r r = a**5*a**Rational(2, 3) assert a**Rational(17, 3) == r assert 2 * a**Rational(17, 3) == 2*r def test_large_rational(): e = (Rational(123712**12 - 1, 7) + Rational(1, 7))**Rational(1, 3) assert e == 234232585392159195136 * (Rational(1, 7)**Rational(1, 3)) def test_negative_real(): def feq(a, b): return abs(a - b) < 1E-10 assert feq(S.One / Float(-0.5), -Integer(2)) def test_expand(): x = Symbol('x') assert (2**(-1 - x)).expand() == S.Half*2**(-x) def test_issue_3449(): #test if powers are simplified correctly #see also issue 3995 x = Symbol('x') assert ((x**Rational(1, 3))**Rational(2)) == x**Rational(2, 3) assert ( (x**Rational(3))**Rational(2, 5)) == (x**Rational(3))**Rational(2, 5) a = Symbol('a', real=True) b = Symbol('b', real=True) assert (a**2)**b == (abs(a)**b)**2 assert sqrt(1/a) != 1/sqrt(a) # e.g. for a = -1 assert (a**3)**Rational(1, 3) != a assert (x**a)**b != x**(a*b) # e.g. x = -1, a=2, b=1/2 assert (x**.5)**b == x**(.5*b) assert (x**.5)**.5 == x**.25 assert (x**2.5)**.5 != x**1.25 # e.g. for x = 5*I k = Symbol('k', integer=True) m = Symbol('m', integer=True) assert (x**k)**m == x**(k*m) assert Number(5)**Rational(2, 3) == Number(25)**Rational(1, 3) assert (x**.5)**2 == x**1.0 assert (x**2)**k == (x**k)**2 == x**(2*k) a = Symbol('a', positive=True) assert (a**3)**Rational(2, 5) == a**Rational(6, 5) assert (a**2)**b == (a**b)**2 assert (a**Rational(2, 3))**x == a**(x*Rational(2, 3)) != (a**x)**Rational(2, 3) def test_issue_3866(): assert --sqrt(sqrt(5) - 1) == sqrt(sqrt(5) - 1) def test_negative_one(): x = Symbol('x', complex=True) y = Symbol('y', complex=True) assert 1/x**y == x**(-y) def test_issue_4362(): neg = Symbol('neg', negative=True) nonneg = Symbol('nonneg', nonnegative=True) any = Symbol('any') num, den = sqrt(1/neg).as_numer_denom() assert num == sqrt(-1) assert den == sqrt(-neg) num, den = sqrt(1/nonneg).as_numer_denom() assert num == 1 assert den == sqrt(nonneg) num, den = sqrt(1/any).as_numer_denom() assert num == sqrt(1/any) assert den == 1 def eqn(num, den, pow): return (num/den)**pow npos = 1 nneg = -1 dpos = 2 - sqrt(3) dneg = 1 - sqrt(3) assert dpos > 0 and dneg < 0 and npos > 0 and nneg < 0 # pos or neg integer eq = eqn(npos, dpos, 2) assert eq.is_Pow and eq.as_numer_denom() == (1, dpos**2) eq = eqn(npos, dneg, 2) assert eq.is_Pow and eq.as_numer_denom() == (1, dneg**2) eq = eqn(nneg, dpos, 2) assert eq.is_Pow and eq.as_numer_denom() == (1, dpos**2) eq = eqn(nneg, dneg, 2) assert eq.is_Pow and eq.as_numer_denom() == (1, dneg**2) eq = eqn(npos, dpos, -2) assert eq.is_Pow and eq.as_numer_denom() == (dpos**2, 1) eq = eqn(npos, dneg, -2) assert eq.is_Pow and eq.as_numer_denom() == (dneg**2, 1) eq = eqn(nneg, dpos, -2) assert eq.is_Pow and eq.as_numer_denom() == (dpos**2, 1) eq = eqn(nneg, dneg, -2) assert eq.is_Pow and eq.as_numer_denom() == (dneg**2, 1) # pos or neg rational pow = S.Half eq = eqn(npos, dpos, pow) assert eq.is_Pow and eq.as_numer_denom() == (npos**pow, dpos**pow) eq = eqn(npos, dneg, pow) assert eq.is_Pow is False and eq.as_numer_denom() == ((-npos)**pow, (-dneg)**pow) eq = eqn(nneg, dpos, pow) assert not eq.is_Pow or eq.as_numer_denom() == (nneg**pow, dpos**pow) eq = eqn(nneg, dneg, pow) assert eq.is_Pow and eq.as_numer_denom() == ((-nneg)**pow, (-dneg)**pow) eq = eqn(npos, dpos, -pow) assert eq.is_Pow and eq.as_numer_denom() == (dpos**pow, npos**pow) eq = eqn(npos, dneg, -pow) assert eq.is_Pow is False and eq.as_numer_denom() == (-(-npos)**pow*(-dneg)**pow, npos) eq = eqn(nneg, dpos, -pow) assert not eq.is_Pow or eq.as_numer_denom() == (dpos**pow, nneg**pow) eq = eqn(nneg, dneg, -pow) assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-nneg)**pow) # unknown exponent pow = 2*any eq = eqn(npos, dpos, pow) assert eq.is_Pow and eq.as_numer_denom() == (npos**pow, dpos**pow) eq = eqn(npos, dneg, pow) assert eq.is_Pow and eq.as_numer_denom() == ((-npos)**pow, (-dneg)**pow) eq = eqn(nneg, dpos, pow) assert eq.is_Pow and eq.as_numer_denom() == (nneg**pow, dpos**pow) eq = eqn(nneg, dneg, pow) assert eq.is_Pow and eq.as_numer_denom() == ((-nneg)**pow, (-dneg)**pow) eq = eqn(npos, dpos, -pow) assert eq.as_numer_denom() == (dpos**pow, npos**pow) eq = eqn(npos, dneg, -pow) assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-npos)**pow) eq = eqn(nneg, dpos, -pow) assert eq.is_Pow and eq.as_numer_denom() == (dpos**pow, nneg**pow) eq = eqn(nneg, dneg, -pow) assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-nneg)**pow) x = Symbol('x') y = Symbol('y') assert ((1/(1 + x/3))**(-S.One)).as_numer_denom() == (3 + x, 3) notp = Symbol('notp', positive=False) # not positive does not imply real b = ((1 + x/notp)**-2) assert (b**(-y)).as_numer_denom() == (1, b**y) assert (b**(-S.One)).as_numer_denom() == ((notp + x)**2, notp**2) nonp = Symbol('nonp', nonpositive=True) assert (((1 + x/nonp)**-2)**(-S.One)).as_numer_denom() == ((-nonp - x)**2, nonp**2) n = Symbol('n', negative=True) assert (x**n).as_numer_denom() == (1, x**-n) assert sqrt(1/n).as_numer_denom() == (S.ImaginaryUnit, sqrt(-n)) n = Symbol('0 or neg', nonpositive=True) # if x and n are split up without negating each term and n is negative # then the answer might be wrong; if n is 0 it won't matter since # 1/oo and 1/zoo are both zero as is sqrt(0)/sqrt(-x) unless x is also # zero (in which case the negative sign doesn't matter): # 1/sqrt(1/-1) = -I but sqrt(-1)/sqrt(1) = I assert (1/sqrt(x/n)).as_numer_denom() == (sqrt(-n), sqrt(-x)) c = Symbol('c', complex=True) e = sqrt(1/c) assert e.as_numer_denom() == (e, 1) i = Symbol('i', integer=True) assert ((1 + x/y)**i).as_numer_denom() == ((x + y)**i, y**i) def test_Pow_Expr_args(): x = Symbol('x') bases = [Basic(), Poly(x, x), FiniteSet(x)] for base in bases: with warns_deprecated_sympy(): Pow(base, S.One) def test_Pow_signs(): """Cf. issues 4595 and 5250""" x = Symbol('x') y = Symbol('y') n = Symbol('n', even=True) assert (3 - y)**2 != (y - 3)**2 assert (3 - y)**n != (y - 3)**n assert (-3 + y - x)**2 != (3 - y + x)**2 assert (y - 3)**3 != -(3 - y)**3 def test_power_with_noncommutative_mul_as_base(): x = Symbol('x', commutative=False) y = Symbol('y', commutative=False) assert not (x*y)**3 == x**3*y**3 assert (2*x*y)**3 == 8*(x*y)**3 @_both_exp_pow def test_power_rewrite_exp(): assert (I**I).rewrite(exp) == exp(-pi/2) expr = (2 + 3*I)**(4 + 5*I) assert expr.rewrite(exp) == exp((4 + 5*I)*(log(sqrt(13)) + I*atan(Rational(3, 2)))) assert expr.rewrite(exp).expand() == \ 169*exp(5*I*log(13)/2)*exp(4*I*atan(Rational(3, 2)))*exp(-5*atan(Rational(3, 2))) assert ((6 + 7*I)**5).rewrite(exp) == 7225*sqrt(85)*exp(5*I*atan(Rational(7, 6))) expr = 5**(6 + 7*I) assert expr.rewrite(exp) == exp((6 + 7*I)*log(5)) assert expr.rewrite(exp).expand() == 15625*exp(7*I*log(5)) assert Pow(123, 789, evaluate=False).rewrite(exp) == 123**789 assert (1**I).rewrite(exp) == 1**I assert (0**I).rewrite(exp) == 0**I expr = (-2)**(2 + 5*I) assert expr.rewrite(exp) == exp((2 + 5*I)*(log(2) + I*pi)) assert expr.rewrite(exp).expand() == 4*exp(-5*pi)*exp(5*I*log(2)) assert ((-2)**S(-5)).rewrite(exp) == (-2)**S(-5) x, y = symbols('x y') assert (x**y).rewrite(exp) == exp(y*log(x)) if global_parameters.exp_is_pow: assert (7**x).rewrite(exp) == Pow(S.Exp1, x*log(7), evaluate=False) else: assert (7**x).rewrite(exp) == exp(x*log(7), evaluate=False) assert ((2 + 3*I)**x).rewrite(exp) == exp(x*(log(sqrt(13)) + I*atan(Rational(3, 2)))) assert (y**(5 + 6*I)).rewrite(exp) == exp(log(y)*(5 + 6*I)) assert all((1/func(x)).rewrite(exp) == 1/(func(x).rewrite(exp)) for func in (sin, cos, tan, sec, csc, sinh, cosh, tanh)) def test_zero(): x = Symbol('x') y = Symbol('y') assert 0**x != 0 assert 0**(2*x) == 0**x assert 0**(1.0*x) == 0**x assert 0**(2.0*x) == 0**x assert (0**(2 - x)).as_base_exp() == (0, 2 - x) assert 0**(x - 2) != S.Infinity**(2 - x) assert 0**(2*x*y) == 0**(x*y) assert 0**(-2*x*y) == S.ComplexInfinity**(x*y) #Test issue 19572 assert 0 ** -oo is zoo assert power(0, -oo) is zoo def test_pow_as_base_exp(): x = Symbol('x') assert (S.Infinity**(2 - x)).as_base_exp() == (S.Infinity, 2 - x) assert (S.Infinity**(x - 2)).as_base_exp() == (S.Infinity, x - 2) p = S.Half**x assert p.base, p.exp == p.as_base_exp() == (S(2), -x) # issue 8344: assert Pow(1, 2, evaluate=False).as_base_exp() == (S.One, S(2)) def test_nseries(): x = Symbol('x') assert sqrt(I*x - 1)._eval_nseries(x, 4, None, 1) == I + x/2 + I*x**2/8 - x**3/16 + O(x**4) assert sqrt(I*x - 1)._eval_nseries(x, 4, None, -1) == -I - x/2 - I*x**2/8 + x**3/16 + O(x**4) assert cbrt(I*x - 1)._eval_nseries(x, 4, None, 1) == (-1)**(S(1)/3) - (-1)**(S(5)/6)*x/3 + \ (-1)**(S(1)/3)*x**2/9 + 5*(-1)**(S(5)/6)*x**3/81 + O(x**4) assert cbrt(I*x - 1)._eval_nseries(x, 4, None, -1) == (-1)**(S(1)/3)*exp(-2*I*pi/3) - \ (-1)**(S(5)/6)*x*exp(-2*I*pi/3)/3 + (-1)**(S(1)/3)*x**2*exp(-2*I*pi/3)/9 + \ 5*(-1)**(S(5)/6)*x**3*exp(-2*I*pi/3)/81 + O(x**4) assert (1 / (exp(-1/x) + 1/x))._eval_nseries(x, 2, None) == x + O(x**2) def test_issue_6100_12942_4473(): x = Symbol('x') y = Symbol('y') assert x**1.0 != x assert x != x**1.0 assert True != x**1.0 assert x**1.0 is not True assert x is not True assert x*y != (x*y)**1.0 # Pow != Symbol assert (x**1.0)**1.0 != x assert (x**1.0)**2.0 != x**2 b = Expr() assert Pow(b, 1.0, evaluate=False) != b # if the following gets distributed as a Mul (x**1.0*y**1.0 then # __eq__ methods could be added to Symbol and Pow to detect the # power-of-1.0 case. assert ((x*y)**1.0).func is Pow def test_issue_6208(): from sympy import root assert sqrt(33**(I*Rational(9, 10))) == -33**(I*Rational(9, 20)) assert root((6*I)**(2*I), 3).as_base_exp()[1] == Rational(1, 3) # != 2*I/3 assert root((6*I)**(I/3), 3).as_base_exp()[1] == I/9 assert sqrt(exp(3*I)) == exp(I*Rational(3, 2)) assert sqrt(-sqrt(3)*(1 + 2*I)) == sqrt(sqrt(3))*sqrt(-1 - 2*I) assert sqrt(exp(5*I)) == -exp(I*Rational(5, 2)) assert root(exp(5*I), 3).exp == Rational(1, 3) def test_issue_6990(): x = Symbol('x') a = Symbol('a') b = Symbol('b') assert (sqrt(a + b*x + x**2)).series(x, 0, 3).removeO() == \ sqrt(a)*x**2*(1/(2*a) - b**2/(8*a**2)) + sqrt(a) + b*x/(2*sqrt(a)) def test_issue_6068(): x = Symbol('x') assert sqrt(sin(x)).series(x, 0, 7) == \ sqrt(x) - x**Rational(5, 2)/12 + x**Rational(9, 2)/1440 - \ x**Rational(13, 2)/24192 + O(x**7) assert sqrt(sin(x)).series(x, 0, 9) == \ sqrt(x) - x**Rational(5, 2)/12 + x**Rational(9, 2)/1440 - \ x**Rational(13, 2)/24192 - 67*x**Rational(17, 2)/29030400 + O(x**9) assert sqrt(sin(x**3)).series(x, 0, 19) == \ x**Rational(3, 2) - x**Rational(15, 2)/12 + x**Rational(27, 2)/1440 + O(x**19) assert sqrt(sin(x**3)).series(x, 0, 20) == \ x**Rational(3, 2) - x**Rational(15, 2)/12 + x**Rational(27, 2)/1440 - \ x**Rational(39, 2)/24192 + O(x**20) def test_issue_6782(): x = Symbol('x') assert sqrt(sin(x**3)).series(x, 0, 7) == x**Rational(3, 2) + O(x**7) assert sqrt(sin(x**4)).series(x, 0, 3) == x**2 + O(x**3) def test_issue_6653(): x = Symbol('x') assert (1 / sqrt(1 + sin(x**2))).series(x, 0, 3) == 1 - x**2/2 + O(x**3) def test_issue_6429(): x = Symbol('x') c = Symbol('c') f = (c**2 + x)**(0.5) assert f.series(x, x0=0, n=1) == (c**2)**0.5 + O(x) assert f.taylor_term(0, x) == (c**2)**0.5 assert f.taylor_term(1, x) == 0.5*x*(c**2)**(-0.5) assert f.taylor_term(2, x) == -0.125*x**2*(c**2)**(-1.5) def test_issue_7638(): f = pi/log(sqrt(2)) assert ((1 + I)**(I*f/2))**0.3 == (1 + I)**(0.15*I*f) # if 1/3 -> 1.0/3 this should fail since it cannot be shown that the # sign will be +/-1; for the previous "small arg" case, it didn't matter # that this could not be proved assert (1 + I)**(4*I*f) == ((1 + I)**(12*I*f))**Rational(1, 3) assert (((1 + I)**(I*(1 + 7*f)))**Rational(1, 3)).exp == Rational(1, 3) r = symbols('r', real=True) assert sqrt(r**2) == abs(r) assert cbrt(r**3) != r assert sqrt(Pow(2*I, 5*S.Half)) != (2*I)**Rational(5, 4) p = symbols('p', positive=True) assert cbrt(p**2) == p**Rational(2, 3) assert NS(((0.2 + 0.7*I)**(0.7 + 1.0*I))**(0.5 - 0.1*I), 1) == '0.4 + 0.2*I' assert sqrt(1/(1 + I)) == sqrt(1 - I)/sqrt(2) # or 1/sqrt(1 + I) e = 1/(1 - sqrt(2)) assert sqrt(e) == I/sqrt(-1 + sqrt(2)) assert e**Rational(-1, 2) == -I*sqrt(-1 + sqrt(2)) assert sqrt((cos(1)**2 + sin(1)**2 - 1)**(3 + I)).exp in [S.Half, Rational(3, 2) + I/2] assert sqrt(r**Rational(4, 3)) != r**Rational(2, 3) assert sqrt((p + I)**Rational(4, 3)) == (p + I)**Rational(2, 3) assert sqrt((p - p**2*I)**2) == p - p**2*I assert sqrt((p + r*I)**2) != p + r*I e = (1 + I/5) assert sqrt(e**5) == e**(5*S.Half) assert sqrt(e**6) == e**3 assert sqrt((1 + I*r)**6) != (1 + I*r)**3 def test_issue_8582(): assert 1**oo is nan assert 1**(-oo) is nan assert 1**zoo is nan assert 1**(oo + I) is nan assert 1**(1 + I*oo) is nan assert 1**(oo + I*oo) is nan def test_issue_8650(): n = Symbol('n', integer=True, nonnegative=True) assert (n**n).is_positive is True x = 5*n + 5 assert (x**(5*(n + 1))).is_positive is True def test_issue_13914(): b = Symbol('b') assert (-1)**zoo is nan assert 2**zoo is nan assert (S.Half)**(1 + zoo) is nan assert I**(zoo + I) is nan assert b**(I + zoo) is nan def test_better_sqrt(): n = Symbol('n', integer=True, nonnegative=True) assert sqrt(3 + 4*I) == 2 + I assert sqrt(3 - 4*I) == 2 - I assert sqrt(-3 - 4*I) == 1 - 2*I assert sqrt(-3 + 4*I) == 1 + 2*I assert sqrt(32 + 24*I) == 6 + 2*I assert sqrt(32 - 24*I) == 6 - 2*I assert sqrt(-32 - 24*I) == 2 - 6*I assert sqrt(-32 + 24*I) == 2 + 6*I # triple (3, 4, 5): # parity of 3 matches parity of 5 and # den, 4, is a square assert sqrt((3 + 4*I)/4) == 1 + I/2 # triple (8, 15, 17) # parity of 8 doesn't match parity of 17 but # den/2, 8/2, is a square assert sqrt((8 + 15*I)/8) == (5 + 3*I)/4 # handle the denominator assert sqrt((3 - 4*I)/25) == (2 - I)/5 assert sqrt((3 - 4*I)/26) == (2 - I)/sqrt(26) # mul # issue #12739 assert sqrt((3 + 4*I)/(3 - 4*I)) == (3 + 4*I)/5 assert sqrt(2/(3 + 4*I)) == sqrt(2)/5*(2 - I) assert sqrt(n/(3 + 4*I)).subs(n, 2) == sqrt(2)/5*(2 - I) assert sqrt(-2/(3 + 4*I)) == sqrt(2)/5*(1 + 2*I) assert sqrt(-n/(3 + 4*I)).subs(n, 2) == sqrt(2)/5*(1 + 2*I) # power assert sqrt(1/(3 + I*4)) == (2 - I)/5 assert sqrt(1/(3 - I)) == sqrt(10)*sqrt(3 + I)/10 # symbolic i = symbols('i', imaginary=True) assert sqrt(3/i) == Mul(sqrt(3), 1/sqrt(i), evaluate=False) # multiples of 1/2; don't make this too automatic assert sqrt(3 + 4*I)**3 == (2 + I)**3 assert Pow(3 + 4*I, Rational(3, 2)) == 2 + 11*I assert Pow(6 + 8*I, Rational(3, 2)) == 2*sqrt(2)*(2 + 11*I) n, d = (3 + 4*I), (3 - 4*I)**3 a = n/d assert a.args == (1/d, n) eq = sqrt(a) assert eq.args == (a, S.Half) assert expand_multinomial(eq) == sqrt((-117 + 44*I)*(3 + 4*I))/125 assert eq.expand() == (7 - 24*I)/125 # issue 12775 # pos im part assert sqrt(2*I) == (1 + I) assert sqrt(2*9*I) == Mul(3, 1 + I, evaluate=False) assert Pow(2*I, 3*S.Half) == (1 + I)**3 # neg im part assert sqrt(-I/2) == Mul(S.Half, 1 - I, evaluate=False) # fractional im part assert Pow(Rational(-9, 2)*I, Rational(3, 2)) == 27*(1 - I)**3/8 def test_issue_2993(): x = Symbol('x') assert str((2.3*x - 4)**0.3) == '1.5157165665104*(0.575*x - 1)**0.3' assert str((2.3*x + 4)**0.3) == '1.5157165665104*(0.575*x + 1)**0.3' assert str((-2.3*x + 4)**0.3) == '1.5157165665104*(1 - 0.575*x)**0.3' assert str((-2.3*x - 4)**0.3) == '1.5157165665104*(-0.575*x - 1)**0.3' assert str((2.3*x - 2)**0.3) == '1.28386201800527*(x - 0.869565217391304)**0.3' assert str((-2.3*x - 2)**0.3) == '1.28386201800527*(-x - 0.869565217391304)**0.3' assert str((-2.3*x + 2)**0.3) == '1.28386201800527*(0.869565217391304 - x)**0.3' assert str((2.3*x + 2)**0.3) == '1.28386201800527*(x + 0.869565217391304)**0.3' assert str((2.3*x - 4)**Rational(1, 3)) == '2**(2/3)*(0.575*x - 1)**(1/3)' eq = (2.3*x + 4) assert eq**2 == 16*(0.575*x + 1)**2 assert (1/eq).args == (eq, -1) # don't change trivial power # issue 17735 q=.5*exp(x) - .5*exp(-x) + 0.1 assert int((q**2).subs(x, 1)) == 1 # issue 17756 y = Symbol('y') assert len(sqrt(x/(x + y)**2 + Float('0.008', 30)).subs(y, pi.n(25)).atoms(Float)) == 2 # issue 17756 a, b, c, d, e, f, g = symbols('a:g') expr = sqrt(1 + a*(c**4 + g*d - 2*g*e - f*(-g + d))**2/ (c**3*b**2*(d - 3*e + 2*f)**2))/2 r = [ (a, N('0.0170992456333788667034850458615', 30)), (b, N('0.0966594956075474769169134801223', 30)), (c, N('0.390911862903463913632151616184', 30)), (d, N('0.152812084558656566271750185933', 30)), (e, N('0.137562344465103337106561623432', 30)), (f, N('0.174259178881496659302933610355', 30)), (g, N('0.220745448491223779615401870086', 30))] tru = expr.n(30, subs=dict(r)) seq = expr.subs(r) # although `tru` is the right way to evaluate # expr with numerical values, `seq` will have # significant loss of precision if extraction of # the largest coefficient of a power's base's terms # is done improperly assert seq == tru def test_issue_17450(): assert (erf(cosh(1)**7)**I).is_real is None assert (erf(cosh(1)**7)**I).is_imaginary is False assert (Pow(exp(1+sqrt(2)), ((1-sqrt(2))*I*pi), evaluate=False)).is_real is None assert ((-10)**(10*I*pi/3)).is_real is False assert ((-5)**(4*I*pi)).is_real is False def test_issue_18190(): assert sqrt(1 / tan(1 + I)) == 1 / sqrt(tan(1 + I)) def test_issue_14815(): x = Symbol('x', real=True) assert sqrt(x).is_extended_negative is False x = Symbol('x', real=False) assert sqrt(x).is_extended_negative is None x = Symbol('x', complex=True) assert sqrt(x).is_extended_negative is False x = Symbol('x', extended_real=True) assert sqrt(x).is_extended_negative is False assert sqrt(zoo, evaluate=False).is_extended_negative is None assert sqrt(nan, evaluate=False).is_extended_negative is None def test_issue_18509(): assert unchanged(Mul, oo, 1/pi**oo) assert (1/pi**oo).is_extended_positive == False def test_issue_18762(): e, p = symbols('e p') g0 = sqrt(1 + e**2 - 2*e*cos(p)) assert len(g0.series(e, 1, 3).args) == 4 def test_issue_21860(): x = Symbol('x') e = 3*2**Rational(66666666667,200000000000)*3**Rational(16666666667,50000000000)*x**Rational(66666666667, 200000000000) ans = Mul(Rational(3, 2), Pow(Integer(2), Rational(33333333333, 100000000000)), Pow(Integer(3), Rational(26666666667, 40000000000))) assert e.xreplace({x: Rational(3,8)}) == ans def test_issue_21647(): x = Symbol('x') e = log((Integer(567)/500)**(811*(Integer(567)/500)**x/100)) ans = log(Mul(Rational(64701150190720499096094005280169087619821081527, 76293945312500000000000000000000000000000000000), Pow(Integer(2), Rational(396204892125479941, 781250000000000000)), Pow(Integer(3), Rational(385045107874520059, 390625000000000000)), Pow(Integer(5), Rational(407364676376439823, 1562500000000000000)), Pow(Integer(7), Rational(385045107874520059, 1562500000000000000)))) assert e.xreplace({x: 6}) == ans def test_issue_21762(): x = Symbol('x') e = (x**2 + 6)**(Integer(33333333333333333)/50000000000000000) ans = Mul(Rational(5, 4), Pow(Integer(2), Rational(16666666666666667, 25000000000000000)), Pow(Integer(5), Rational(8333333333333333, 25000000000000000))) assert e.xreplace({x: S.Half}) == ans def test_rational_powers_larger_than_one(): assert Rational(2, 3)**Rational(3, 2) == 2*sqrt(6)/9 assert Rational(1, 6)**Rational(9, 4) == 6**Rational(3, 4)/216 assert Rational(3, 7)**Rational(7, 3) == 9*3**Rational(1, 3)*7**Rational(2, 3)/343 def test_power_dispatcher(): class NewBase(Expr): pass class NewPow(NewBase, Pow): pass a, b = Symbol('a'), NewBase() @power.register(Expr, NewBase) @power.register(NewBase, Expr) @power.register(NewBase, NewBase) def _(a, b): return NewPow(a, b) # Pow called as fallback assert power(2, 3) == 8*S.One assert power(a, 2) == Pow(a, 2) assert power(a, a) == Pow(a, a) # NewPow called by dispatch assert power(a, b) == NewPow(a, b) assert power(b, a) == NewPow(b, a) assert power(b, b) == NewPow(b, b) def test_powers_of_I(): assert [sqrt(I)**i for i in range(13)] == [ 1, sqrt(I), I, sqrt(I)**3, -1, -sqrt(I), -I, -sqrt(I)**3, 1, sqrt(I), I, sqrt(I)**3, -1] assert sqrt(I)**(S(9)/2) == -I**(S(1)/4)
28dc8f7d18b22e78587cf975c8ec67e214486145e8db397cb876dd5177e47514
from sympy import (Symbol, exp, Integer, Float, sin, cos, log, Poly, Lambda, Function, I, S, sqrt, srepr, Rational, Tuple, Matrix, Interval, Add, Mul, Pow, Or, true, false, Abs, pi, Range, Xor) from sympy.abc import x, y from sympy.core.sympify import (sympify, _sympify, SympifyError, kernS, CantSympify) from sympy.core.decorators import _sympifyit from sympy.external import import_module from sympy.testing.pytest import raises, XFAIL, skip, warns_deprecated_sympy from sympy.utilities.decorator import conserve_mpmath_dps from sympy.geometry import Point, Line from sympy.functions.combinatorial.factorials import factorial, factorial2 from sympy.abc import _clash, _clash1, _clash2 from sympy.core.compatibility import HAS_GMPY from sympy.sets import FiniteSet, EmptySet from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray import mpmath from collections import defaultdict, OrderedDict from mpmath.rational import mpq numpy = import_module('numpy') def test_issue_3538(): v = sympify("exp(x)") assert v == exp(x) assert type(v) == type(exp(x)) assert str(type(v)) == str(type(exp(x))) def test_sympify1(): assert sympify("x") == Symbol("x") assert sympify(" x") == Symbol("x") assert sympify(" x ") == Symbol("x") # issue 4877 n1 = S.Half assert sympify('--.5') == n1 assert sympify('-1/2') == -n1 assert sympify('-+--.5') == -n1 assert sympify('-.[3]') == Rational(-1, 3) assert sympify('.[3]') == Rational(1, 3) assert sympify('+.[3]') == Rational(1, 3) assert sympify('+0.[3]*10**-2') == Rational(1, 300) assert sympify('.[052631578947368421]') == Rational(1, 19) assert sympify('.0[526315789473684210]') == Rational(1, 19) assert sympify('.034[56]') == Rational(1711, 49500) # options to make reals into rationals assert sympify('1.22[345]', rational=True) == \ 1 + Rational(22, 100) + Rational(345, 99900) assert sympify('2/2.6', rational=True) == Rational(10, 13) assert sympify('2.6/2', rational=True) == Rational(13, 10) assert sympify('2.6e2/17', rational=True) == Rational(260, 17) assert sympify('2.6e+2/17', rational=True) == Rational(260, 17) assert sympify('2.6e-2/17', rational=True) == Rational(26, 17000) assert sympify('2.1+3/4', rational=True) == \ Rational(21, 10) + Rational(3, 4) assert sympify('2.234456', rational=True) == Rational(279307, 125000) assert sympify('2.234456e23', rational=True) == 223445600000000000000000 assert sympify('2.234456e-23', rational=True) == \ Rational(279307, 12500000000000000000000000000) assert sympify('-2.234456e-23', rational=True) == \ Rational(-279307, 12500000000000000000000000000) assert sympify('12345678901/17', rational=True) == \ Rational(12345678901, 17) assert sympify('1/.3 + x', rational=True) == Rational(10, 3) + x # make sure longs in fractions work assert sympify('222222222222/11111111111') == \ Rational(222222222222, 11111111111) # ... even if they come from repetend notation assert sympify('1/.2[123456789012]') == Rational(333333333333, 70781892967) # ... or from high precision reals assert sympify('.1234567890123456', rational=True) == \ Rational(19290123283179, 156250000000000) def test_sympify_Fraction(): try: import fractions except ImportError: pass else: value = sympify(fractions.Fraction(101, 127)) assert value == Rational(101, 127) and type(value) is Rational def test_sympify_gmpy(): if HAS_GMPY: if HAS_GMPY == 2: import gmpy2 as gmpy elif HAS_GMPY == 1: import gmpy value = sympify(gmpy.mpz(1000001)) assert value == Integer(1000001) and type(value) is Integer value = sympify(gmpy.mpq(101, 127)) assert value == Rational(101, 127) and type(value) is Rational @conserve_mpmath_dps def test_sympify_mpmath(): value = sympify(mpmath.mpf(1.0)) assert value == Float(1.0) and type(value) is Float mpmath.mp.dps = 12 assert sympify( mpmath.pi).epsilon_eq(Float("3.14159265359"), Float("1e-12")) == True assert sympify( mpmath.pi).epsilon_eq(Float("3.14159265359"), Float("1e-13")) == False mpmath.mp.dps = 6 assert sympify( mpmath.pi).epsilon_eq(Float("3.14159"), Float("1e-5")) == True assert sympify( mpmath.pi).epsilon_eq(Float("3.14159"), Float("1e-6")) == False assert sympify(mpmath.mpc(1.0 + 2.0j)) == Float(1.0) + Float(2.0)*I assert sympify(mpq(1, 2)) == S.Half def test_sympify2(): class A: def _sympy_(self): return Symbol("x")**3 a = A() assert _sympify(a) == x**3 assert sympify(a) == x**3 assert a == x**3 def test_sympify3(): assert sympify("x**3") == x**3 assert sympify("x^3") == x**3 assert sympify("1/2") == Integer(1)/2 raises(SympifyError, lambda: _sympify('x**3')) raises(SympifyError, lambda: _sympify('1/2')) def test_sympify_keywords(): raises(SympifyError, lambda: sympify('if')) raises(SympifyError, lambda: sympify('for')) raises(SympifyError, lambda: sympify('while')) raises(SympifyError, lambda: sympify('lambda')) def test_sympify_float(): assert sympify("1e-64") != 0 assert sympify("1e-20000") != 0 def test_sympify_bool(): assert sympify(True) is true assert sympify(False) is false def test_sympyify_iterables(): ans = [Rational(3, 10), Rational(1, 5)] assert sympify(['.3', '.2'], rational=True) == ans assert sympify(dict(x=0, y=1)) == {x: 0, y: 1} assert sympify(['1', '2', ['3', '4']]) == [S(1), S(2), [S(3), S(4)]] @XFAIL def test_issue_16772(): # because there is a converter for tuple, the # args are only sympified without the flags being passed # along; list, on the other hand, is not converted # with a converter so its args are traversed later ans = [Rational(3, 10), Rational(1, 5)] assert sympify(tuple(['.3', '.2']), rational=True) == Tuple(*ans) def test_issue_16859(): class no(float, CantSympify): pass raises(SympifyError, lambda: sympify(no(1.2))) def test_sympify4(): class A: def _sympy_(self): return Symbol("x") a = A() assert _sympify(a)**3 == x**3 assert sympify(a)**3 == x**3 assert a == x def test_sympify_text(): assert sympify('some') == Symbol('some') assert sympify('core') == Symbol('core') assert sympify('True') is True assert sympify('False') is False assert sympify('Poly') == Poly assert sympify('sin') == sin def test_sympify_function(): assert sympify('factor(x**2-1, x)') == -(1 - x)*(x + 1) assert sympify('sin(pi/2)*cos(pi)') == -Integer(1) def test_sympify_poly(): p = Poly(x**2 + x + 1, x) assert _sympify(p) is p assert sympify(p) is p def test_sympify_factorial(): assert sympify('x!') == factorial(x) assert sympify('(x+1)!') == factorial(x + 1) assert sympify('(1 + y*(x + 1))!') == factorial(1 + y*(x + 1)) assert sympify('(1 + y*(x + 1)!)^2') == (1 + y*factorial(x + 1))**2 assert sympify('y*x!') == y*factorial(x) assert sympify('x!!') == factorial2(x) assert sympify('(x+1)!!') == factorial2(x + 1) assert sympify('(1 + y*(x + 1))!!') == factorial2(1 + y*(x + 1)) assert sympify('(1 + y*(x + 1)!!)^2') == (1 + y*factorial2(x + 1))**2 assert sympify('y*x!!') == y*factorial2(x) assert sympify('factorial2(x)!') == factorial(factorial2(x)) raises(SympifyError, lambda: sympify("+!!")) raises(SympifyError, lambda: sympify(")!!")) raises(SympifyError, lambda: sympify("!")) raises(SympifyError, lambda: sympify("(!)")) raises(SympifyError, lambda: sympify("x!!!")) def test_sage(): # how to effectivelly test for the _sage_() method without having SAGE # installed? assert hasattr(x, "_sage_") assert hasattr(Integer(3), "_sage_") assert hasattr(sin(x), "_sage_") assert hasattr(cos(x), "_sage_") assert hasattr(x**2, "_sage_") assert hasattr(x + y, "_sage_") assert hasattr(exp(x), "_sage_") assert hasattr(log(x), "_sage_") def test_issue_3595(): assert sympify("a_") == Symbol("a_") assert sympify("_a") == Symbol("_a") def test_lambda(): x = Symbol('x') assert sympify('lambda: 1') == Lambda((), 1) assert sympify('lambda x: x') == Lambda(x, x) assert sympify('lambda x: 2*x') == Lambda(x, 2*x) assert sympify('lambda x, y: 2*x+y') == Lambda((x, y), 2*x + y) def test_lambda_raises(): raises(SympifyError, lambda: sympify("lambda *args: args")) # args argument error raises(SympifyError, lambda: sympify("lambda **kwargs: kwargs[0]")) # kwargs argument error raises(SympifyError, lambda: sympify("lambda x = 1: x")) # Keyword argument error with raises(SympifyError): _sympify('lambda: 1') def test_sympify_raises(): raises(SympifyError, lambda: sympify("fx)")) class A: def __str__(self): return 'x' with warns_deprecated_sympy(): assert sympify(A()) == Symbol('x') def test__sympify(): x = Symbol('x') f = Function('f') # positive _sympify assert _sympify(x) is x assert _sympify(1) == Integer(1) assert _sympify(0.5) == Float("0.5") assert _sympify(1 + 1j) == 1.0 + I*1.0 # Function f is not Basic and can't sympify to Basic. We allow it to pass # with sympify but not with _sympify. # https://github.com/sympy/sympy/issues/20124 assert sympify(f) is f raises(SympifyError, lambda: _sympify(f)) class A: def _sympy_(self): return Integer(5) a = A() assert _sympify(a) == Integer(5) # negative _sympify raises(SympifyError, lambda: _sympify('1')) raises(SympifyError, lambda: _sympify([1, 2, 3])) def test_sympifyit(): x = Symbol('x') y = Symbol('y') @_sympifyit('b', NotImplemented) def add(a, b): return a + b assert add(x, 1) == x + 1 assert add(x, 0.5) == x + Float('0.5') assert add(x, y) == x + y assert add(x, '1') == NotImplemented @_sympifyit('b') def add_raises(a, b): return a + b assert add_raises(x, 1) == x + 1 assert add_raises(x, 0.5) == x + Float('0.5') assert add_raises(x, y) == x + y raises(SympifyError, lambda: add_raises(x, '1')) def test_int_float(): class F1_1: def __float__(self): return 1.1 class F1_1b: """ This class is still a float, even though it also implements __int__(). """ def __float__(self): return 1.1 def __int__(self): return 1 class F1_1c: """ This class is still a float, because it implements _sympy_() """ def __float__(self): return 1.1 def __int__(self): return 1 def _sympy_(self): return Float(1.1) class I5: def __int__(self): return 5 class I5b: """ This class implements both __int__() and __float__(), so it will be treated as Float in SymPy. One could change this behavior, by using float(a) == int(a), but deciding that integer-valued floats represent exact numbers is arbitrary and often not correct, so we do not do it. If, in the future, we decide to do it anyway, the tests for I5b need to be changed. """ def __float__(self): return 5.0 def __int__(self): return 5 class I5c: """ This class implements both __int__() and __float__(), but also a _sympy_() method, so it will be Integer. """ def __float__(self): return 5.0 def __int__(self): return 5 def _sympy_(self): return Integer(5) i5 = I5() i5b = I5b() i5c = I5c() f1_1 = F1_1() f1_1b = F1_1b() f1_1c = F1_1c() assert sympify(i5) == 5 assert isinstance(sympify(i5), Integer) assert sympify(i5b) == 5 assert isinstance(sympify(i5b), Float) assert sympify(i5c) == 5 assert isinstance(sympify(i5c), Integer) assert abs(sympify(f1_1) - 1.1) < 1e-5 assert abs(sympify(f1_1b) - 1.1) < 1e-5 assert abs(sympify(f1_1c) - 1.1) < 1e-5 assert _sympify(i5) == 5 assert isinstance(_sympify(i5), Integer) assert _sympify(i5b) == 5 assert isinstance(_sympify(i5b), Float) assert _sympify(i5c) == 5 assert isinstance(_sympify(i5c), Integer) assert abs(_sympify(f1_1) - 1.1) < 1e-5 assert abs(_sympify(f1_1b) - 1.1) < 1e-5 assert abs(_sympify(f1_1c) - 1.1) < 1e-5 def test_evaluate_false(): cases = { '2 + 3': Add(2, 3, evaluate=False), '2**2 / 3': Mul(Pow(2, 2, evaluate=False), Pow(3, -1, evaluate=False), evaluate=False), '2 + 3 * 5': Add(2, Mul(3, 5, evaluate=False), evaluate=False), '2 - 3 * 5': Add(2, Mul(-1, Mul(3, 5,evaluate=False), evaluate=False), evaluate=False), '1 / 3': Mul(1, Pow(3, -1, evaluate=False), evaluate=False), 'True | False': Or(True, False, evaluate=False), '1 + 2 + 3 + 5*3 + integrate(x)': Add(1, 2, 3, Mul(5, 3, evaluate=False), x**2/2, evaluate=False), '2 * 4 * 6 + 8': Add(Mul(2, 4, 6, evaluate=False), 8, evaluate=False), '2 - 8 / 4': Add(2, Mul(-1, Mul(8, Pow(4, -1, evaluate=False), evaluate=False), evaluate=False), evaluate=False), '2 - 2**2': Add(2, Mul(-1, Pow(2, 2, evaluate=False), evaluate=False), evaluate=False), } for case, result in cases.items(): assert sympify(case, evaluate=False) == result def test_issue_4133(): a = sympify('Integer(4)') assert a == Integer(4) assert a.is_Integer def test_issue_3982(): a = [3, 2.0] assert sympify(a) == [Integer(3), Float(2.0)] assert sympify(tuple(a)) == Tuple(Integer(3), Float(2.0)) assert sympify(set(a)) == FiniteSet(Integer(3), Float(2.0)) def test_S_sympify(): assert S(1)/2 == sympify(1)/2 assert (-2)**(S(1)/2) == sqrt(2)*I def test_issue_4788(): assert srepr(S(1.0 + 0J)) == srepr(S(1.0)) == srepr(Float(1.0)) def test_issue_4798_None(): assert S(None) is None def test_issue_3218(): assert sympify("x+\ny") == x + y def test_issue_4988_builtins(): C = Symbol('C') vars = {'C': C} exp1 = sympify('C') assert exp1 == C # Make sure it did not get mixed up with sympy.C exp2 = sympify('C', vars) assert exp2 == C # Make sure it did not get mixed up with sympy.C def test_geometry(): p = sympify(Point(0, 1)) assert p == Point(0, 1) and isinstance(p, Point) L = sympify(Line(p, (1, 0))) assert L == Line((0, 1), (1, 0)) and isinstance(L, Line) def test_kernS(): s = '-1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x)))' # when 1497 is fixed, this no longer should pass: the expression # should be unchanged assert -1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) == -1 # sympification should not allow the constant to enter a Mul # or else the structure can change dramatically ss = kernS(s) assert ss != -1 and ss.simplify() == -1 s = '-1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x)))'.replace( 'x', '_kern') ss = kernS(s) assert ss != -1 and ss.simplify() == -1 # issue 6687 assert (kernS('Interval(-1,-2 - 4*(-3))') == Interval(-1, Add(-2, Mul(12, 1, evaluate=False), evaluate=False))) assert kernS('_kern') == Symbol('_kern') assert kernS('E**-(x)') == exp(-x) e = 2*(x + y)*y assert kernS(['2*(x + y)*y', ('2*(x + y)*y',)]) == [e, (e,)] assert kernS('-(2*sin(x)**2 + 2*sin(x)*cos(x))*y/2') == \ -y*(2*sin(x)**2 + 2*sin(x)*cos(x))/2 # issue 15132 assert kernS('(1 - x)/(1 - x*(1-y))') == kernS('(1-x)/(1-(1-y)*x)') assert kernS('(1-2**-(4+1)*(1-y)*x)') == (1 - x*(1 - y)/32) assert kernS('(1-2**(4+1)*(1-y)*x)') == (1 - 32*x*(1 - y)) assert kernS('(1-2.*(1-y)*x)') == 1 - 2.*x*(1 - y) one = kernS('x - (x - 1)') assert one != 1 and one.expand() == 1 assert kernS("(2*x)/(x-1)") == 2*x/(x-1) def test_issue_6540_6552(): assert S('[[1/3,2], (2/5,)]') == [[Rational(1, 3), 2], (Rational(2, 5),)] assert S('[[2/6,2], (2/4,)]') == [[Rational(1, 3), 2], (S.Half,)] assert S('[[[2*(1)]]]') == [[[2]]] assert S('Matrix([2*(1)])') == Matrix([2]) def test_issue_6046(): assert str(S("Q & C", locals=_clash1)) == 'C & Q' assert str(S('pi(x)', locals=_clash2)) == 'pi(x)' locals = {} exec("from sympy.abc import Q, C", locals) assert str(S('C&Q', locals)) == 'C & Q' # clash can act as Symbol or Function assert str(S('pi(C, Q)', locals=_clash)) == 'pi(C, Q)' assert len(S('pi + x', locals=_clash2).free_symbols) == 2 # but not both raises(TypeError, lambda: S('pi + pi(x)', locals=_clash2)) assert all(set(i.values()) == {None} for i in ( _clash, _clash1, _clash2)) def test_issue_8821_highprec_from_str(): s = str(pi.evalf(128)) p = sympify(s) assert Abs(sin(p)) < 1e-127 def test_issue_10295(): if not numpy: skip("numpy not installed.") A = numpy.array([[1, 3, -1], [0, 1, 7]]) sA = S(A) assert sA.shape == (2, 3) for (ri, ci), val in numpy.ndenumerate(A): assert sA[ri, ci] == val B = numpy.array([-7, x, 3*y**2]) sB = S(B) assert sB.shape == (3,) assert B[0] == sB[0] == -7 assert B[1] == sB[1] == x assert B[2] == sB[2] == 3*y**2 C = numpy.arange(0, 24) C.resize(2,3,4) sC = S(C) assert sC[0, 0, 0].is_integer assert sC[0, 0, 0] == 0 a1 = numpy.array([1, 2, 3]) a2 = numpy.array([i for i in range(24)]) a2.resize(2, 4, 3) assert sympify(a1) == ImmutableDenseNDimArray([1, 2, 3]) assert sympify(a2) == ImmutableDenseNDimArray([i for i in range(24)], (2, 4, 3)) def test_Range(): # Only works in Python 3 where range returns a range type assert sympify(range(10)) == Range(10) assert _sympify(range(10)) == Range(10) def test_sympify_set(): n = Symbol('n') assert sympify({n}) == FiniteSet(n) assert sympify(set()) == EmptySet def test_sympify_numpy(): if not numpy: skip('numpy not installed. Abort numpy tests.') np = numpy def equal(x, y): return x == y and type(x) == type(y) assert sympify(np.bool_(1)) is S(True) try: assert equal( sympify(np.int_(1234567891234567891)), S(1234567891234567891)) assert equal( sympify(np.intp(1234567891234567891)), S(1234567891234567891)) except OverflowError: # May fail on 32-bit systems: Python int too large to convert to C long pass assert equal(sympify(np.intc(1234567891)), S(1234567891)) assert equal(sympify(np.int8(-123)), S(-123)) assert equal(sympify(np.int16(-12345)), S(-12345)) assert equal(sympify(np.int32(-1234567891)), S(-1234567891)) assert equal( sympify(np.int64(-1234567891234567891)), S(-1234567891234567891)) assert equal(sympify(np.uint8(123)), S(123)) assert equal(sympify(np.uint16(12345)), S(12345)) assert equal(sympify(np.uint32(1234567891)), S(1234567891)) assert equal( sympify(np.uint64(1234567891234567891)), S(1234567891234567891)) assert equal(sympify(np.float32(1.123456)), Float(1.123456, precision=24)) assert equal(sympify(np.float64(1.1234567891234)), Float(1.1234567891234, precision=53)) assert equal(sympify(np.longdouble(1.123456789)), Float(1.123456789, precision=80)) assert equal(sympify(np.complex64(1 + 2j)), S(1.0 + 2.0*I)) assert equal(sympify(np.complex128(1 + 2j)), S(1.0 + 2.0*I)) assert equal(sympify(np.longcomplex(1 + 2j)), S(1.0 + 2.0*I)) #float96 does not exist on all platforms if hasattr(np, 'float96'): assert equal(sympify(np.float96(1.123456789)), Float(1.123456789, precision=80)) #float128 does not exist on all platforms if hasattr(np, 'float128'): assert equal(sympify(np.float128(1.123456789123)), Float(1.123456789123, precision=80)) @XFAIL def test_sympify_rational_numbers_set(): ans = [Rational(3, 10), Rational(1, 5)] assert sympify({'.3', '.2'}, rational=True) == FiniteSet(*ans) def test_issue_13924(): if not numpy: skip("numpy not installed.") a = sympify(numpy.array([1])) assert isinstance(a, ImmutableDenseNDimArray) assert a[0] == 1 def test_numpy_sympify_args(): # Issue 15098. Make sure sympify args work with numpy types (like numpy.str_) if not numpy: skip("numpy not installed.") a = sympify(numpy.str_('a')) assert type(a) is Symbol assert a == Symbol('a') class CustomSymbol(Symbol): pass a = sympify(numpy.str_('a'), {"Symbol": CustomSymbol}) assert isinstance(a, CustomSymbol) a = sympify(numpy.str_('x^y')) assert a == x**y a = sympify(numpy.str_('x^y'), convert_xor=False) assert a == Xor(x, y) raises(SympifyError, lambda: sympify(numpy.str_('x'), strict=True)) a = sympify(numpy.str_('1.1')) assert isinstance(a, Float) assert a == 1.1 a = sympify(numpy.str_('1.1'), rational=True) assert isinstance(a, Rational) assert a == Rational(11, 10) a = sympify(numpy.str_('x + x')) assert isinstance(a, Mul) assert a == 2*x a = sympify(numpy.str_('x + x'), evaluate=False) assert isinstance(a, Add) assert a == Add(x, x, evaluate=False) def test_issue_5939(): a = Symbol('a') b = Symbol('b') assert sympify('''a+\nb''') == a + b def test_issue_16759(): d = sympify({.5: 1}) assert S.Half not in d assert Float(.5) in d assert d[.5] is S.One d = sympify(OrderedDict({.5: 1})) assert S.Half not in d assert Float(.5) in d assert d[.5] is S.One d = sympify(defaultdict(int, {.5: 1})) assert S.Half not in d assert Float(.5) in d assert d[.5] is S.One def test_issue_17811(): a = Function('a') assert sympify('a(x)*5', evaluate=False) == Mul(a(x), 5, evaluate=False) def test_issue_14706(): if not numpy: skip("numpy not installed.") z1 = numpy.zeros((1, 1), dtype=numpy.float64) z2 = numpy.zeros((2, 2), dtype=numpy.float64) z3 = numpy.zeros((), dtype=numpy.float64) y1 = numpy.ones((1, 1), dtype=numpy.float64) y2 = numpy.ones((2, 2), dtype=numpy.float64) y3 = numpy.ones((), dtype=numpy.float64) assert numpy.all(x + z1 == numpy.full((1, 1), x)) assert numpy.all(x + z2 == numpy.full((2, 2), x)) assert numpy.all(z1 + x == numpy.full((1, 1), x)) assert numpy.all(z2 + x == numpy.full((2, 2), x)) for z in [z3, numpy.int64(0), numpy.float64(0), numpy.complex64(0)]: assert x + z == x assert z + x == x assert isinstance(x + z, Symbol) assert isinstance(z + x, Symbol) # If these tests fail, then it means that numpy has finally # fixed the issue of scalar conversion for rank>0 arrays # which is mentioned in numpy/numpy#10404. In that case, # some changes have to be made in sympify.py. # Note: For future reference, for anyone who takes up this # issue when numpy has finally fixed their side of the problem, # the changes for this temporary fix were introduced in PR 18651 assert numpy.all(x + y1 == numpy.full((1, 1), x + 1.0)) assert numpy.all(x + y2 == numpy.full((2, 2), x + 1.0)) assert numpy.all(y1 + x == numpy.full((1, 1), x + 1.0)) assert numpy.all(y2 + x == numpy.full((2, 2), x + 1.0)) for y_ in [y3, numpy.int64(1), numpy.float64(1), numpy.complex64(1)]: assert x + y_ == y_ + x assert isinstance(x + y_, Add) assert isinstance(y_ + x, Add) assert x + numpy.array(x) == 2 * x assert x + numpy.array([x]) == numpy.array([2*x], dtype=object) assert sympify(numpy.array([1])) == ImmutableDenseNDimArray([1], 1) assert sympify(numpy.array([[[1]]])) == ImmutableDenseNDimArray([1], (1, 1, 1)) assert sympify(z1) == ImmutableDenseNDimArray([0], (1, 1)) assert sympify(z2) == ImmutableDenseNDimArray([0, 0, 0, 0], (2, 2)) assert sympify(z3) == ImmutableDenseNDimArray([0], ()) assert sympify(z3, strict=True) == 0.0 raises(SympifyError, lambda: sympify(numpy.array([1]), strict=True)) raises(SympifyError, lambda: sympify(z1, strict=True)) raises(SympifyError, lambda: sympify(z2, strict=True)) def test_issue_21536(): #test to check evaluate=False in case of iterable input u = sympify("x+3*x+2", evaluate=False) v = sympify("2*x+4*x+2+4", evaluate=False) assert u.is_Add and set(u.args) == {x, 3*x, 2} assert v.is_Add and set(v.args) == {2*x, 4*x, 2, 4} assert sympify(["x+3*x+2", "2*x+4*x+2+4"], evaluate=False) == [u, v] #test to check evaluate=True in case of iterable input u = sympify("x+3*x+2", evaluate=True) v = sympify("2*x+4*x+2+4", evaluate=True) assert u.is_Add and set(u.args) == {4*x, 2} assert v.is_Add and set(v.args) == {6*x, 6} assert sympify(["x+3*x+2", "2*x+4*x+2+4"], evaluate=True) == [u, v] #test to check evaluate with no input in case of iterable input u = sympify("x+3*x+2") v = sympify("2*x+4*x+2+4") assert u.is_Add and set(u.args) == {4*x, 2} assert v.is_Add and set(v.args) == {6*x, 6} assert sympify(["x+3*x+2", "2*x+4*x+2+4"]) == [u, v]
6d8d39ec80c5c95b3ceb88dc278e992132efe7bc4c28d7c1570042fa69f324b0
"""Tests for tools and arithmetics for monomials of distributed polynomials. """ from sympy.polys.monomials import ( itermonomials, monomial_count, monomial_mul, monomial_div, monomial_gcd, monomial_lcm, monomial_max, monomial_min, monomial_divides, monomial_pow, Monomial, ) from sympy.polys.polyerrors import ExactQuotientFailed from sympy.abc import a, b, c, x, y, z from sympy.core import S, symbols from sympy.testing.pytest import raises def test_monomials(): # total_degree tests assert set(itermonomials([], 0)) == {S.One} assert set(itermonomials([], 1)) == {S.One} assert set(itermonomials([], 2)) == {S.One} assert set(itermonomials([], 0, 0)) == {S.One} assert set(itermonomials([], 1, 0)) == {S.One} assert set(itermonomials([], 2, 0)) == {S.One} raises(StopIteration, lambda: next(itermonomials([], 0, 1))) raises(StopIteration, lambda: next(itermonomials([], 0, 2))) raises(StopIteration, lambda: next(itermonomials([], 0, 3))) assert set(itermonomials([], 0, 1)) == set() assert set(itermonomials([], 0, 2)) == set() assert set(itermonomials([], 0, 3)) == set() raises(ValueError, lambda: set(itermonomials([], -1))) raises(ValueError, lambda: set(itermonomials([x], -1))) raises(ValueError, lambda: set(itermonomials([x, y], -1))) assert set(itermonomials([x], 0)) == {S.One} assert set(itermonomials([x], 1)) == {S.One, x} assert set(itermonomials([x], 2)) == {S.One, x, x**2} assert set(itermonomials([x], 3)) == {S.One, x, x**2, x**3} assert set(itermonomials([x, y], 0)) == {S.One} assert set(itermonomials([x, y], 1)) == {S.One, x, y} assert set(itermonomials([x, y], 2)) == {S.One, x, y, x**2, y**2, x*y} assert set(itermonomials([x, y], 3)) == \ {S.One, x, y, x**2, x**3, y**2, y**3, x*y, x*y**2, y*x**2} i, j, k = symbols('i j k', commutative=False) assert set(itermonomials([i, j, k], 0)) == {S.One} assert set(itermonomials([i, j, k], 1)) == {S.One, i, j, k} assert set(itermonomials([i, j, k], 2)) == \ {S.One, i, j, k, i**2, j**2, k**2, i*j, i*k, j*i, j*k, k*i, k*j} assert set(itermonomials([i, j, k], 3)) == \ {S.One, i, j, k, i**2, j**2, k**2, i*j, i*k, j*i, j*k, k*i, k*j, i**3, j**3, k**3, i**2 * j, i**2 * k, j * i**2, k * i**2, j**2 * i, j**2 * k, i * j**2, k * j**2, k**2 * i, k**2 * j, i * k**2, j * k**2, i*j*i, i*k*i, j*i*j, j*k*j, k*i*k, k*j*k, i*j*k, i*k*j, j*i*k, j*k*i, k*i*j, k*j*i, } assert set(itermonomials([x, i, j], 0)) == {S.One} assert set(itermonomials([x, i, j], 1)) == {S.One, x, i, j} assert set(itermonomials([x, i, j], 2)) == {S.One, x, i, j, x*i, x*j, i*j, j*i, x**2, i**2, j**2} assert set(itermonomials([x, i, j], 3)) == \ {S.One, x, i, j, x*i, x*j, i*j, j*i, x**2, i**2, j**2, x**3, i**3, j**3, x**2 * i, x**2 * j, x * i**2, j * i**2, i**2 * j, i*j*i, x * j**2, i * j**2, j**2 * i, j*i*j, x * i * j, x * j * i } # degree_list tests assert set(itermonomials([], [])) == {S.One} raises(ValueError, lambda: set(itermonomials([], [0]))) raises(ValueError, lambda: set(itermonomials([], [1]))) raises(ValueError, lambda: set(itermonomials([], [2]))) raises(ValueError, lambda: set(itermonomials([x], [1], []))) raises(ValueError, lambda: set(itermonomials([x], [1, 2], []))) raises(ValueError, lambda: set(itermonomials([x], [1, 2, 3], []))) raises(ValueError, lambda: set(itermonomials([x], [], [1]))) raises(ValueError, lambda: set(itermonomials([x], [], [1, 2]))) raises(ValueError, lambda: set(itermonomials([x], [], [1, 2, 3]))) raises(ValueError, lambda: set(itermonomials([x, y], [1, 2], [1, 2, 3]))) raises(ValueError, lambda: set(itermonomials([x, y, z], [1, 2, 3], [0, 1]))) raises(ValueError, lambda: set(itermonomials([x], [1], [-1]))) raises(ValueError, lambda: set(itermonomials([x, y], [1, 2], [1, -1]))) raises(ValueError, lambda: set(itermonomials([], [], 1))) raises(ValueError, lambda: set(itermonomials([], [], 2))) raises(ValueError, lambda: set(itermonomials([], [], 3))) raises(ValueError, lambda: set(itermonomials([x, y], [0, 1], [1, 2]))) raises(ValueError, lambda: set(itermonomials([x, y, z], [0, 0, 3], [0, 1, 2]))) assert set(itermonomials([x], [0])) == {S.One} assert set(itermonomials([x], [1])) == {S.One, x} assert set(itermonomials([x], [2])) == {S.One, x, x**2} assert set(itermonomials([x], [3])) == {S.One, x, x**2, x**3} assert set(itermonomials([x], [3], [1])) == {x, x**3, x**2} assert set(itermonomials([x], [3], [2])) == {x**3, x**2} assert set(itermonomials([x, y], 3, 3)) == {x**3, x**2*y, x*y**2, y**3} assert set(itermonomials([x, y], 3, 2)) == {x**2, x*y, y**2, x**3, x**2*y, x*y**2, y**3} assert set(itermonomials([x, y], [0, 0])) == {S.One} assert set(itermonomials([x, y], [0, 1])) == {S.One, y} assert set(itermonomials([x, y], [0, 2])) == {S.One, y, y**2} assert set(itermonomials([x, y], [0, 2], [0, 1])) == {y, y**2} assert set(itermonomials([x, y], [0, 2], [0, 2])) == {y**2} assert set(itermonomials([x, y], [1, 0])) == {S.One, x} assert set(itermonomials([x, y], [1, 1])) == {S.One, x, y, x*y} assert set(itermonomials([x, y], [1, 2])) == {S.One, x, y, x*y, y**2, x*y**2} assert set(itermonomials([x, y], [1, 2], [1, 1])) == {x*y, x*y**2} assert set(itermonomials([x, y], [1, 2], [1, 2])) == {x*y**2} assert set(itermonomials([x, y], [2, 0])) == {S.One, x, x**2} assert set(itermonomials([x, y], [2, 1])) == {S.One, x, y, x*y, x**2, x**2*y} assert set(itermonomials([x, y], [2, 2])) == \ {S.One, y**2, x*y**2, x, x*y, x**2, x**2*y**2, y, x**2*y} i, j, k = symbols('i j k', commutative=False) assert set(itermonomials([i, j, k], 2, 2)) == \ {k*i, i**2, i*j, j*k, j*i, k**2, j**2, k*j, i*k} assert set(itermonomials([i, j, k], 3, 2)) == \ {j*k**2, i*k**2, k*i*j, k*i**2, k**2, j*k*j, k*j**2, i*k*i, i*j, j**2*k, i**2*j, j*i*k, j**3, i**3, k*j*i, j*k*i, j*i, k**2*j, j*i**2, k*j, k*j*k, i*j*i, j*i*j, i*j**2, j**2, k*i*k, i**2, j*k, i*k, i*k*j, k**3, i**2*k, j**2*i, k**2*i, i*j*k, k*i } assert set(itermonomials([i, j, k], [0, 0, 0])) == {S.One} assert set(itermonomials([i, j, k], [0, 0, 1])) == {1, k} assert set(itermonomials([i, j, k], [0, 1, 0])) == {1, j} assert set(itermonomials([i, j, k], [1, 0, 0])) == {i, 1} assert set(itermonomials([i, j, k], [0, 0, 2])) == {k**2, 1, k} assert set(itermonomials([i, j, k], [0, 2, 0])) == {1, j, j**2} assert set(itermonomials([i, j, k], [2, 0, 0])) == {i, 1, i**2} assert set(itermonomials([i, j, k], [1, 1, 1])) == {1, k, j, j*k, i*k, i, i*j, i*j*k} assert set(itermonomials([i, j, k], [2, 2, 2])) == \ {1, k, i**2*k**2, j*k, j**2, i, i*k, j*k**2, i*j**2*k**2, i**2*j, i**2*j**2, k**2, j**2*k, i*j**2*k, j**2*k**2, i*j, i**2*k, i**2*j**2*k, j, i**2*j*k, i*j**2, i*k**2, i*j*k, i**2*j**2*k**2, i*j*k**2, i**2, i**2*j*k**2 } assert set(itermonomials([x, j, k], [0, 0, 0])) == {S.One} assert set(itermonomials([x, j, k], [0, 0, 1])) == {1, k} assert set(itermonomials([x, j, k], [0, 1, 0])) == {1, j} assert set(itermonomials([x, j, k], [1, 0, 0])) == {x, 1} assert set(itermonomials([x, j, k], [0, 0, 2])) == {k**2, 1, k} assert set(itermonomials([x, j, k], [0, 2, 0])) == {1, j, j**2} assert set(itermonomials([x, j, k], [2, 0, 0])) == {x, 1, x**2} assert set(itermonomials([x, j, k], [1, 1, 1])) == {1, k, j, j*k, x*k, x, x*j, x*j*k} assert set(itermonomials([x, j, k], [2, 2, 2])) == \ {1, k, x**2*k**2, j*k, j**2, x, x*k, j*k**2, x*j**2*k**2, x**2*j, x**2*j**2, k**2, j**2*k, x*j**2*k, j**2*k**2, x*j, x**2*k, x**2*j**2*k, j, x**2*j*k, x*j**2, x*k**2, x*j*k, x**2*j**2*k**2, x*j*k**2, x**2, x**2*j*k**2 } def test_monomial_count(): assert monomial_count(2, 2) == 6 assert monomial_count(2, 3) == 10 def test_monomial_mul(): assert monomial_mul((3, 4, 1), (1, 2, 0)) == (4, 6, 1) def test_monomial_div(): assert monomial_div((3, 4, 1), (1, 2, 0)) == (2, 2, 1) def test_monomial_gcd(): assert monomial_gcd((3, 4, 1), (1, 2, 0)) == (1, 2, 0) def test_monomial_lcm(): assert monomial_lcm((3, 4, 1), (1, 2, 0)) == (3, 4, 1) def test_monomial_max(): assert monomial_max((3, 4, 5), (0, 5, 1), (6, 3, 9)) == (6, 5, 9) def test_monomial_pow(): assert monomial_pow((1, 2, 3), 3) == (3, 6, 9) def test_monomial_min(): assert monomial_min((3, 4, 5), (0, 5, 1), (6, 3, 9)) == (0, 3, 1) def test_monomial_divides(): assert monomial_divides((1, 2, 3), (4, 5, 6)) is True assert monomial_divides((1, 2, 3), (0, 5, 6)) is False def test_Monomial(): m = Monomial((3, 4, 1), (x, y, z)) n = Monomial((1, 2, 0), (x, y, z)) assert m.as_expr() == x**3*y**4*z assert n.as_expr() == x**1*y**2 assert m.as_expr(a, b, c) == a**3*b**4*c assert n.as_expr(a, b, c) == a**1*b**2 assert m.exponents == (3, 4, 1) assert m.gens == (x, y, z) assert n.exponents == (1, 2, 0) assert n.gens == (x, y, z) assert m == (3, 4, 1) assert n != (3, 4, 1) assert m != (1, 2, 0) assert n == (1, 2, 0) assert (m == 1) is False assert m[0] == m[-3] == 3 assert m[1] == m[-2] == 4 assert m[2] == m[-1] == 1 assert n[0] == n[-3] == 1 assert n[1] == n[-2] == 2 assert n[2] == n[-1] == 0 assert m[:2] == (3, 4) assert n[:2] == (1, 2) assert m*n == Monomial((4, 6, 1)) assert m/n == Monomial((2, 2, 1)) assert m*(1, 2, 0) == Monomial((4, 6, 1)) assert m/(1, 2, 0) == Monomial((2, 2, 1)) assert m.gcd(n) == Monomial((1, 2, 0)) assert m.lcm(n) == Monomial((3, 4, 1)) assert m.gcd((1, 2, 0)) == Monomial((1, 2, 0)) assert m.lcm((1, 2, 0)) == Monomial((3, 4, 1)) assert m**0 == Monomial((0, 0, 0)) assert m**1 == m assert m**2 == Monomial((6, 8, 2)) assert m**3 == Monomial((9, 12, 3)) raises(ExactQuotientFailed, lambda: m/Monomial((5, 2, 0))) mm = Monomial((1, 2, 3)) raises(ValueError, lambda: mm.as_expr()) assert str(mm) == 'Monomial((1, 2, 3))' assert str(m) == 'x**3*y**4*z**1' raises(NotImplementedError, lambda: m*1) raises(NotImplementedError, lambda: m/1) raises(ValueError, lambda: m**-1) raises(TypeError, lambda: m.gcd(3)) raises(TypeError, lambda: m.lcm(3))
fc478d0cd7aa2328f4cc7a2f20b89a0a86b75cba125e1ce91b94c158e80ab1e1
from .lti import (TransferFunction, Series, MIMOSeries, Parallel, MIMOParallel, Feedback, MIMOFeedback, TransferFunctionMatrix) from .control_plots import (pole_zero_numerical_data, pole_zero_plot, step_response_numerical_data, step_response_plot, impulse_response_numerical_data, impulse_response_plot, ramp_response_numerical_data, ramp_response_plot, bode_magnitude_numerical_data, bode_phase_numerical_data, bode_magnitude_plot, bode_phase_plot, bode_plot) __all__ = ['TransferFunction', 'Series', 'MIMOSeries', 'Parallel', 'MIMOParallel', 'Feedback', 'MIMOFeedback', 'TransferFunctionMatrix', 'pole_zero_numerical_data', 'pole_zero_plot', 'step_response_numerical_data', 'step_response_plot', 'impulse_response_numerical_data', 'impulse_response_plot', 'ramp_response_numerical_data', 'ramp_response_plot', 'bode_magnitude_numerical_data', 'bode_phase_numerical_data', 'bode_magnitude_plot', 'bode_phase_plot', 'bode_plot']
86d246fd48d839ff64afbbf4ac26732bbc1e8d7f9cca14eafedbd421ec193c5d
from sympy import Basic, Add, Mul, Pow, degree, Symbol, expand, cancel, Expr, roots from sympy.core.containers import Tuple from sympy.core.evalf import EvalfMixin, prec_to_dps from sympy.core.logic import fuzzy_and from sympy.core.numbers import Integer, ComplexInfinity from sympy.core.symbol import Dummy from sympy.core.sympify import sympify, _sympify from sympy.polys import Poly, rootof from sympy.series import limit from sympy.matrices import ImmutableMatrix, eye from sympy.matrices.expressions import MatMul, MatAdd __all__ = ['TransferFunction', 'Series', 'MIMOSeries', 'Parallel', 'MIMOParallel', 'Feedback', 'MIMOFeedback', 'TransferFunctionMatrix'] def _roots(poly, var): """ like roots, but works on higher-order polynomials. """ r = roots(poly, var, multiple=True) n = degree(poly) if len(r) != n: r = [rootof(poly, var, k) for k in range(n)] return r class LinearTimeInvariant(Basic, EvalfMixin): """A common class for all the Linear Time-Invariant Dynamical Systems.""" # Users should not directly interact with this class. def __new__(cls, *system, **kwargs): if cls is LinearTimeInvariant: raise NotImplementedError('The LTICommon class is not meant to be used directly.') return super(LinearTimeInvariant, cls).__new__(cls, *system, **kwargs) @classmethod def _check_args(cls, args): if not args: raise ValueError("Atleast 1 argument must be passed.") if not all(isinstance(arg, cls._clstype) for arg in args): raise TypeError(f"All arguments must be of type {cls._clstype}.") var_set = {arg.var for arg in args} if len(var_set) != 1: raise ValueError("All transfer functions should use the same complex variable" f" of the Laplace transform. {len(var_set)} different values found.") @property def is_SISO(self): """Returns `True` if the passed LTI system is SISO else returns False.""" return self._is_SISO class SISOLinearTimeInvariant(LinearTimeInvariant): """A common class for all the SISO Linear Time-Invariant Dynamical Systems.""" # Users should not directly interact with this class. _is_SISO = True class MIMOLinearTimeInvariant(LinearTimeInvariant): """A common class for all the MIMO Linear Time-Invariant Dynamical Systems.""" # Users should not directly interact with this class. _is_SISO = False SISOLinearTimeInvariant._clstype = SISOLinearTimeInvariant MIMOLinearTimeInvariant._clstype = MIMOLinearTimeInvariant def _check_other_SISO(func): def wrapper(*args, **kwargs): if not isinstance(args[-1], SISOLinearTimeInvariant): return NotImplemented else: return func(*args, **kwargs) return wrapper def _check_other_MIMO(func): def wrapper(*args, **kwargs): if not isinstance(args[-1], MIMOLinearTimeInvariant): return NotImplemented else: return func(*args, **kwargs) return wrapper class TransferFunction(SISOLinearTimeInvariant): r""" A class for representing LTI (Linear, time-invariant) systems that can be strictly described by ratio of polynomials in the Laplace transform complex variable. The arguments are ``num``, ``den``, and ``var``, where ``num`` and ``den`` are numerator and denominator polynomials of the ``TransferFunction`` respectively, and the third argument is a complex variable of the Laplace transform used by these polynomials of the transfer function. ``num`` and ``den`` can be either polynomials or numbers, whereas ``var`` has to be a Symbol. Explanation =========== Generally, a dynamical system representing a physical model can be described in terms of Linear Ordinary Differential Equations like - $\small{b_{m}y^{\left(m\right)}+b_{m-1}y^{\left(m-1\right)}+\dots+b_{1}y^{\left(1\right)}+b_{0}y= a_{n}x^{\left(n\right)}+a_{n-1}x^{\left(n-1\right)}+\dots+a_{1}x^{\left(1\right)}+a_{0}x}$ Here, $x$ is the input signal and $y$ is the output signal and superscript on both is the order of derivative (not exponent). Derivative is taken with respect to the independent variable, $t$. Also, generally $m$ is greater than $n$. It is not feasible to analyse the properties of such systems in their native form therefore, we use mathematical tools like Laplace transform to get a better perspective. Taking the Laplace transform of both the sides in the equation (at zero initial conditions), we get - $\small{\mathcal{L}[b_{m}y^{\left(m\right)}+b_{m-1}y^{\left(m-1\right)}+\dots+b_{1}y^{\left(1\right)}+b_{0}y]= \mathcal{L}[a_{n}x^{\left(n\right)}+a_{n-1}x^{\left(n-1\right)}+\dots+a_{1}x^{\left(1\right)}+a_{0}x]}$ Using the linearity property of Laplace transform and also considering zero initial conditions (i.e. $\small{y(0^{-}) = 0}$, $\small{y'(0^{-}) = 0}$ and so on), the equation above gets translated to - $\small{b_{m}\mathcal{L}[y^{\left(m\right)}]+\dots+b_{1}\mathcal{L}[y^{\left(1\right)}]+b_{0}\mathcal{L}[y]= a_{n}\mathcal{L}[x^{\left(n\right)}]+\dots+a_{1}\mathcal{L}[x^{\left(1\right)}]+a_{0}\mathcal{L}[x]}$ Now, applying Derivative property of Laplace transform, $\small{b_{m}s^{m}\mathcal{L}[y]+\dots+b_{1}s\mathcal{L}[y]+b_{0}\mathcal{L}[y]= a_{n}s^{n}\mathcal{L}[x]+\dots+a_{1}s\mathcal{L}[x]+a_{0}\mathcal{L}[x]}$ Here, the superscript on $s$ is **exponent**. Note that the zero initial conditions assumption, mentioned above, is very important and cannot be ignored otherwise the dynamical system cannot be considered time-independent and the simplified equation above cannot be reached. Collecting $\mathcal{L}[y]$ and $\mathcal{L}[x]$ terms from both the sides and taking the ratio $\frac{ \mathcal{L}\left\{y\right\} }{ \mathcal{L}\left\{x\right\} }$, we get the typical rational form of transfer function. The numerator of the transfer function is, therefore, the Laplace transform of the output signal (The signals are represented as functions of time) and similarly, the denominator of the transfer function is the Laplace transform of the input signal. It is also a convention to denote the input and output signal's Laplace transform with capital alphabets like shown below. $H(s) = \frac{Y(s)}{X(s)} = \frac{ \mathcal{L}\left\{y(t)\right\} }{ \mathcal{L}\left\{x(t)\right\} }$ $s$, also known as complex frequency, is a complex variable in the Laplace domain. It corresponds to the equivalent variable $t$, in the time domain. Transfer functions are sometimes also referred to as the Laplace transform of the system's impulse response. Transfer function, $H$, is represented as a rational function in $s$ like, $H(s) =\ \frac{a_{n}s^{n}+a_{n-1}s^{n-1}+\dots+a_{1}s+a_{0}}{b_{m}s^{m}+b_{m-1}s^{m-1}+\dots+b_{1}s+b_{0}}$ Parameters ========== num : Expr, Number The numerator polynomial of the transfer function. den : Expr, Number The denominator polynomial of the transfer function. var : Symbol Complex variable of the Laplace transform used by the polynomials of the transfer function. Raises ====== TypeError When ``var`` is not a Symbol or when ``num`` or ``den`` is not a number or a polynomial. ValueError When ``den`` is zero. Examples ======== >>> from sympy.abc import s, p, a >>> from sympy.physics.control.lti import TransferFunction >>> tf1 = TransferFunction(s + a, s**2 + s + 1, s) >>> tf1 TransferFunction(a + s, s**2 + s + 1, s) >>> tf1.num a + s >>> tf1.den s**2 + s + 1 >>> tf1.var s >>> tf1.args (a + s, s**2 + s + 1, s) Any complex variable can be used for ``var``. >>> tf2 = TransferFunction(a*p**3 - a*p**2 + s*p, p + a**2, p) >>> tf2 TransferFunction(a*p**3 - a*p**2 + p*s, a**2 + p, p) >>> tf3 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p) >>> tf3 TransferFunction((p - 1)*(p + 3), (p - 1)*(p + 5), p) To negate a transfer function the ``-`` operator can be prepended: >>> tf4 = TransferFunction(-a + s, p**2 + s, p) >>> -tf4 TransferFunction(a - s, p**2 + s, p) >>> tf5 = TransferFunction(s**4 - 2*s**3 + 5*s + 4, s + 4, s) >>> -tf5 TransferFunction(-s**4 + 2*s**3 - 5*s - 4, s + 4, s) You can use a Float or an Integer (or other constants) as numerator and denominator: >>> tf6 = TransferFunction(1/2, 4, s) >>> tf6.num 0.500000000000000 >>> tf6.den 4 >>> tf6.var s >>> tf6.args (0.5, 4, s) You can take the integer power of a transfer function using the ``**`` operator: >>> tf7 = TransferFunction(s + a, s - a, s) >>> tf7**3 TransferFunction((a + s)**3, (-a + s)**3, s) >>> tf7**0 TransferFunction(1, 1, s) >>> tf8 = TransferFunction(p + 4, p - 3, p) >>> tf8**-1 TransferFunction(p - 3, p + 4, p) Addition, subtraction, and multiplication of transfer functions can form unevaluated ``Series`` or ``Parallel`` objects. >>> tf9 = TransferFunction(s + 1, s**2 + s + 1, s) >>> tf10 = TransferFunction(s - p, s + 3, s) >>> tf11 = TransferFunction(4*s**2 + 2*s - 4, s - 1, s) >>> tf12 = TransferFunction(1 - s, s**2 + 4, s) >>> tf9 + tf10 Parallel(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-p + s, s + 3, s)) >>> tf10 - tf11 Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(-4*s**2 - 2*s + 4, s - 1, s)) >>> tf9 * tf10 Series(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-p + s, s + 3, s)) >>> tf10 - (tf9 + tf12) Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(-s - 1, s**2 + s + 1, s), TransferFunction(s - 1, s**2 + 4, s)) >>> tf10 - (tf9 * tf12) Parallel(TransferFunction(-p + s, s + 3, s), Series(TransferFunction(-1, 1, s), TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(1 - s, s**2 + 4, s))) >>> tf11 * tf10 * tf9 Series(TransferFunction(4*s**2 + 2*s - 4, s - 1, s), TransferFunction(-p + s, s + 3, s), TransferFunction(s + 1, s**2 + s + 1, s)) >>> tf9 * tf11 + tf10 * tf12 Parallel(Series(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(4*s**2 + 2*s - 4, s - 1, s)), Series(TransferFunction(-p + s, s + 3, s), TransferFunction(1 - s, s**2 + 4, s))) >>> (tf9 + tf12) * (tf10 + tf11) Series(Parallel(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(1 - s, s**2 + 4, s)), Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(4*s**2 + 2*s - 4, s - 1, s))) These unevaluated ``Series`` or ``Parallel`` objects can convert into the resultant transfer function using ``.doit()`` method or by ``.rewrite(TransferFunction)``. >>> ((tf9 + tf10) * tf12).doit() TransferFunction((1 - s)*((-p + s)*(s**2 + s + 1) + (s + 1)*(s + 3)), (s + 3)*(s**2 + 4)*(s**2 + s + 1), s) >>> (tf9 * tf10 - tf11 * tf12).rewrite(TransferFunction) TransferFunction(-(1 - s)*(s + 3)*(s**2 + s + 1)*(4*s**2 + 2*s - 4) + (-p + s)*(s - 1)*(s + 1)*(s**2 + 4), (s - 1)*(s + 3)*(s**2 + 4)*(s**2 + s + 1), s) See Also ======== Feedback, Series, Parallel References ========== .. [1] https://en.wikipedia.org/wiki/Transfer_function .. [2] https://en.wikipedia.org/wiki/Laplace_transform """ def __new__(cls, num, den, var): num, den = _sympify(num), _sympify(den) if not isinstance(var, Symbol): raise TypeError("Variable input must be a Symbol.") if den == 0: raise ValueError("TransferFunction can't have a zero denominator.") if (((isinstance(num, Expr) and num.has(Symbol)) or num.is_number) and ((isinstance(den, Expr) and den.has(Symbol)) or den.is_number)): obj = super(TransferFunction, cls).__new__(cls, num, den, var) obj._num = num obj._den = den obj._var = var return obj else: raise TypeError("Unsupported type for numerator or denominator of TransferFunction.") @classmethod def from_rational_expression(cls, expr, var=None): r""" Creates a new ``TransferFunction`` efficiently from a rational expression. Parameters ========== expr : Expr, Number The rational expression representing the ``TransferFunction``. var : Symbol, optional Complex variable of the Laplace transform used by the polynomials of the transfer function. Raises ====== ValueError When ``expr`` is of type ``Number`` and optional parameter ``var`` is not passed. When ``expr`` has more than one variables and an optional parameter ``var`` is not passed. ZeroDivisionError When denominator of ``expr`` is zero or it has ``ComplexInfinity`` in its numerator. Examples ======== >>> from sympy.abc import s, p, a >>> from sympy.physics.control.lti import TransferFunction >>> expr1 = (s + 5)/(3*s**2 + 2*s + 1) >>> tf1 = TransferFunction.from_rational_expression(expr1) >>> tf1 TransferFunction(s + 5, 3*s**2 + 2*s + 1, s) >>> expr2 = (a*p**3 - a*p**2 + s*p)/(p + a**2) # Expr with more than one variables >>> tf2 = TransferFunction.from_rational_expression(expr2, p) >>> tf2 TransferFunction(a*p**3 - a*p**2 + p*s, a**2 + p, p) In case of conflict between two or more variables in a expression, SymPy will raise a ``ValueError``, if ``var`` is not passed by the user. >>> tf = TransferFunction.from_rational_expression((a + a*s)/(s**2 + s + 1)) Traceback (most recent call last): ... ValueError: Conflicting values found for positional argument `var` ({a, s}). Specify it manually. This can be corrected by specifying the ``var`` parameter manually. >>> tf = TransferFunction.from_rational_expression((a + a*s)/(s**2 + s + 1), s) >>> tf TransferFunction(a*s + a, s**2 + s + 1, s) ``var`` also need to be specified when ``expr`` is a ``Number`` >>> tf3 = TransferFunction.from_rational_expression(10, s) >>> tf3 TransferFunction(10, 1, s) """ expr = _sympify(expr) if var is None: _free_symbols = expr.free_symbols _len_free_symbols = len(_free_symbols) if _len_free_symbols == 1: var = list(_free_symbols)[0] elif _len_free_symbols == 0: raise ValueError("Positional argument `var` not found in the TransferFunction defined. Specify it manually.") else: raise ValueError("Conflicting values found for positional argument `var` ({}). Specify it manually.".format(_free_symbols)) _num, _den = expr.as_numer_denom() if _den == 0 or _num.has(ComplexInfinity): raise ZeroDivisionError("TransferFunction can't have a zero denominator.") return cls(_num, _den, var) @property def num(self): """ Returns the numerator polynomial of the transfer function. Examples ======== >>> from sympy.abc import s, p >>> from sympy.physics.control.lti import TransferFunction >>> G1 = TransferFunction(s**2 + p*s + 3, s - 4, s) >>> G1.num p*s + s**2 + 3 >>> G2 = TransferFunction((p + 5)*(p - 3), (p - 3)*(p + 1), p) >>> G2.num (p - 3)*(p + 5) """ return self._num @property def den(self): """ Returns the denominator polynomial of the transfer function. Examples ======== >>> from sympy.abc import s, p >>> from sympy.physics.control.lti import TransferFunction >>> G1 = TransferFunction(s + 4, p**3 - 2*p + 4, s) >>> G1.den p**3 - 2*p + 4 >>> G2 = TransferFunction(3, 4, s) >>> G2.den 4 """ return self._den @property def var(self): """ Returns the complex variable of the Laplace transform used by the polynomials of the transfer function. Examples ======== >>> from sympy.abc import s, p >>> from sympy.physics.control.lti import TransferFunction >>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p) >>> G1.var p >>> G2 = TransferFunction(0, s - 5, s) >>> G2.var s """ return self._var def _eval_subs(self, old, new): arg_num = self.num.subs(old, new) arg_den = self.den.subs(old, new) argnew = TransferFunction(arg_num, arg_den, self.var) return self if old == self.var else argnew def _eval_evalf(self, prec): return TransferFunction( self.num._eval_evalf(prec), self.den._eval_evalf(prec), self.var) def _eval_simplify(self, **kwargs): tf = cancel(Mul(self.num, 1/self.den, evaluate=False), expand=False).as_numer_denom() num_, den_ = tf[0], tf[1] return TransferFunction(num_, den_, self.var) def expand(self): """ Returns the transfer function with numerator and denominator in expanded form. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction >>> G1 = TransferFunction((a - s)**2, (s**2 + a)**2, s) >>> G1.expand() TransferFunction(a**2 - 2*a*s + s**2, a**2 + 2*a*s**2 + s**4, s) >>> G2 = TransferFunction((p + 3*b)*(p - b), (p - b)*(p + 2*b), p) >>> G2.expand() TransferFunction(-3*b**2 + 2*b*p + p**2, -2*b**2 + b*p + p**2, p) """ return TransferFunction(expand(self.num), expand(self.den), self.var) def dc_gain(self): """ Computes the gain of the response as the frequency approaches zero. The DC gain is infinite for systems with pure integrators. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction >>> tf1 = TransferFunction(s + 3, s**2 - 9, s) >>> tf1.dc_gain() -1/3 >>> tf2 = TransferFunction(p**2, p - 3 + p**3, p) >>> tf2.dc_gain() 0 >>> tf3 = TransferFunction(a*p**2 - b, s + b, s) >>> tf3.dc_gain() (a*p**2 - b)/b >>> tf4 = TransferFunction(1, s, s) >>> tf4.dc_gain() oo """ m = Mul(self.num, Pow(self.den, -1, evaluate=False), evaluate=False) return limit(m, self.var, 0) def poles(self): """ Returns the poles of a transfer function. Examples ======== >>> from sympy.abc import s, p, a >>> from sympy.physics.control.lti import TransferFunction >>> tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p) >>> tf1.poles() [-5, 1] >>> tf2 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s) >>> tf2.poles() [I, I, -I, -I] >>> tf3 = TransferFunction(s**2, a*s + p, s) >>> tf3.poles() [-p/a] """ return _roots(Poly(self.den, self.var), self.var) def zeros(self): """ Returns the zeros of a transfer function. Examples ======== >>> from sympy.abc import s, p, a >>> from sympy.physics.control.lti import TransferFunction >>> tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p) >>> tf1.zeros() [-3, 1] >>> tf2 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s) >>> tf2.zeros() [1, 1] >>> tf3 = TransferFunction(s**2, a*s + p, s) >>> tf3.zeros() [0, 0] """ return _roots(Poly(self.num, self.var), self.var) def is_stable(self): """ Returns True if the transfer function is asymptotically stable; else False. This would not check the marginal or conditional stability of the system. Examples ======== >>> from sympy.abc import s, p, a >>> from sympy import symbols >>> from sympy.physics.control.lti import TransferFunction >>> q, r = symbols('q, r', negative=True) >>> tf1 = TransferFunction((1 - s)**2, (s + 1)**2, s) >>> tf1.is_stable() True >>> tf2 = TransferFunction((1 - p)**2, (s**2 + 1)**2, s) >>> tf2.is_stable() False >>> tf3 = TransferFunction(4, q*s - r, s) >>> tf3.is_stable() False >>> tf4 = TransferFunction(p + 1, a*p - s**2, p) >>> tf4.is_stable() is None # Not enough info about the symbols to determine stability True """ return fuzzy_and(pole.as_real_imag()[0].is_negative for pole in self.poles()) def __add__(self, other): if isinstance(other, (TransferFunction, Series)): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") return Parallel(self, other) elif isinstance(other, Parallel): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") arg_list = list(other.args) return Parallel(self, *arg_list) else: raise ValueError("TransferFunction cannot be added with {}.". format(type(other))) def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, (TransferFunction, Series)): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") return Parallel(self, -other) elif isinstance(other, Parallel): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") arg_list = [-i for i in list(other.args)] return Parallel(self, *arg_list) else: raise ValueError("{} cannot be subtracted from a TransferFunction." .format(type(other))) def __rsub__(self, other): return -self + other def __mul__(self, other): if isinstance(other, (TransferFunction, Parallel)): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") return Series(self, other) elif isinstance(other, Series): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") arg_list = list(other.args) return Series(self, *arg_list) else: raise ValueError("TransferFunction cannot be multiplied with {}." .format(type(other))) __rmul__ = __mul__ def __truediv__(self, other): if (isinstance(other, Parallel) and len(other.args) == 2 and isinstance(other.args[0], TransferFunction) and isinstance(other.args[1], (Series, TransferFunction))): if not self.var == other.var: raise ValueError("Both TransferFunction and Parallel should use the" " same complex variable of the Laplace transform.") if other.args[1] == self: # plant and controller with unit feedback. return Feedback(self, other.args[0]) other_arg_list = list(other.args[1].args) if isinstance(other.args[1], Series) else other.args[1] if other_arg_list == other.args[1]: return Feedback(self, other_arg_list) elif self in other_arg_list: other_arg_list.remove(self) else: return Feedback(self, Series(*other_arg_list)) if len(other_arg_list) == 1: return Feedback(self, *other_arg_list) else: return Feedback(self, Series(*other_arg_list)) else: raise ValueError("TransferFunction cannot be divided by {}.". format(type(other))) __rtruediv__ = __truediv__ def __pow__(self, p): p = sympify(p) if not isinstance(p, Integer): raise ValueError("Exponent must be an Integer.") if p == 0: return TransferFunction(1, 1, self.var) elif p > 0: num_, den_ = self.num**p, self.den**p else: p = abs(p) num_, den_ = self.den**p, self.num**p return TransferFunction(num_, den_, self.var) def __neg__(self): return TransferFunction(-self.num, self.den, self.var) @property def is_proper(self): """ Returns True if degree of the numerator polynomial is less than or equal to degree of the denominator polynomial, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction >>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s) >>> tf1.is_proper False >>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*p + 2, p) >>> tf2.is_proper True """ return degree(self.num, self.var) <= degree(self.den, self.var) @property def is_strictly_proper(self): """ Returns True if degree of the numerator polynomial is strictly less than degree of the denominator polynomial, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf1.is_strictly_proper False >>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s) >>> tf2.is_strictly_proper True """ return degree(self.num, self.var) < degree(self.den, self.var) @property def is_biproper(self): """ Returns True if degree of the numerator polynomial is equal to degree of the denominator polynomial, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf1.is_biproper True >>> tf2 = TransferFunction(p**2, p + a, p) >>> tf2.is_biproper False """ return degree(self.num, self.var) == degree(self.den, self.var) def to_expr(self): """ Converts a ``TransferFunction`` object to SymPy Expr. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction >>> from sympy import Expr >>> tf1 = TransferFunction(s, a*s**2 + 1, s) >>> tf1.to_expr() s/(a*s**2 + 1) >>> isinstance(_, Expr) True >>> tf2 = TransferFunction(1, (p + 3*b)*(b - p), p) >>> tf2.to_expr() 1/((b - p)*(3*b + p)) >>> tf3 = TransferFunction((s - 2)*(s - 3), (s - 1)*(s - 2)*(s - 3), s) >>> tf3.to_expr() ((s - 3)*(s - 2))/(((s - 3)*(s - 2)*(s - 1))) """ if self.num != 1: return Mul(self.num, Pow(self.den, -1, evaluate=False), evaluate=False) else: return Pow(self.den, -1, evaluate=False) def _flatten_args(args, _cls): temp_args = [] for arg in args: if isinstance(arg, _cls): temp_args.extend(arg.args) else: temp_args.append(arg) return tuple(temp_args) def _dummify_args(_arg, var): dummy_dict = {} dummy_arg_list = [] for arg in _arg: _s = Dummy() dummy_dict[_s] = var dummy_arg = arg.subs({var: _s}) dummy_arg_list.append(dummy_arg) return dummy_arg_list, dummy_dict class Series(SISOLinearTimeInvariant): r""" A class for representing a series configuration of SISO systems. Parameters ========== args : SISOLinearTimeInvariant SISO systems in a series configuration. evaluate : Boolean, Keyword When passed ``True``, returns the equivalent ``Series(*args).doit()``. Set to ``False`` by default. Raises ====== ValueError When no argument is passed. ``var`` attribute is not same for every system. TypeError Any of the passed ``*args`` has unsupported type A combination of SISO and MIMO systems is passed. There should be homogeneity in the type of systems passed, SISO in this case. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Series, Parallel >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s) >>> tf3 = TransferFunction(p**2, p + s, s) >>> S1 = Series(tf1, tf2) >>> S1 Series(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)) >>> S1.var s >>> S2 = Series(tf2, Parallel(tf3, -tf1)) >>> S2 Series(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), Parallel(TransferFunction(p**2, p + s, s), TransferFunction(-a*p**2 - b*s, -p + s, s))) >>> S2.var s >>> S3 = Series(Parallel(tf1, tf2), Parallel(tf2, tf3)) >>> S3 Series(Parallel(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)), Parallel(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), TransferFunction(p**2, p + s, s))) >>> S3.var s You can get the resultant transfer function by using ``.doit()`` method: >>> S3 = Series(tf1, tf2, -tf3) >>> S3.doit() TransferFunction(-p**2*(s**3 - 2)*(a*p**2 + b*s), (-p + s)*(p + s)*(s**4 + 5*s + 6), s) >>> S4 = Series(tf2, Parallel(tf1, -tf3)) >>> S4.doit() TransferFunction((s**3 - 2)*(-p**2*(-p + s) + (p + s)*(a*p**2 + b*s)), (-p + s)*(p + s)*(s**4 + 5*s + 6), s) Notes ===== All the transfer functions should use the same complex variable ``var`` of the Laplace transform. See Also ======== MIMOSeries, Parallel, TransferFunction, Feedback """ def __new__(cls, *args, evaluate=False): args = _flatten_args(args, Series) cls._check_args(args) obj = super().__new__(cls, *args) return obj.doit() if evaluate else obj @property def var(self): """ Returns the complex variable used by all the transfer functions. Examples ======== >>> from sympy.abc import p >>> from sympy.physics.control.lti import TransferFunction, Series, Parallel >>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p) >>> G2 = TransferFunction(p, 4 - p, p) >>> G3 = TransferFunction(0, p**4 - 1, p) >>> Series(G1, G2).var p >>> Series(-G3, Parallel(G1, G2)).var p """ return self.args[0].var def doit(self, **kwargs): """ Returns the resultant transfer function obtained after evaluating the transfer functions in series configuration. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Series >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s) >>> Series(tf2, tf1).doit() TransferFunction((s**3 - 2)*(a*p**2 + b*s), (-p + s)*(s**4 + 5*s + 6), s) >>> Series(-tf1, -tf2).doit() TransferFunction((2 - s**3)*(-a*p**2 - b*s), (-p + s)*(s**4 + 5*s + 6), s) """ _num_arg = (arg.doit().num for arg in self.args) _den_arg = (arg.doit().den for arg in self.args) res_num = Mul(*_num_arg, evaluate=True) res_den = Mul(*_den_arg, evaluate=True) return TransferFunction(res_num, res_den, self.var) def _eval_rewrite_as_TransferFunction(self, *args, **kwargs): return self.doit() @_check_other_SISO def __add__(self, other): if isinstance(other, Parallel): arg_list = list(other.args) return Parallel(self, *arg_list) return Parallel(self, other) __radd__ = __add__ @_check_other_SISO def __sub__(self, other): return self + (-other) def __rsub__(self, other): return -self + other @_check_other_SISO def __mul__(self, other): arg_list = list(self.args) return Series(*arg_list, other) def __truediv__(self, other): if (isinstance(other, Parallel) and len(other.args) == 2 and isinstance(other.args[0], TransferFunction) and isinstance(other.args[1], Series)): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") self_arg_list = set(list(self.args)) other_arg_list = set(list(other.args[1].args)) res = list(self_arg_list ^ other_arg_list) if len(res) == 0: return Feedback(self, other.args[0]) elif len(res) == 1: return Feedback(self, *res) else: return Feedback(self, Series(*res)) else: raise ValueError("This transfer function expression is invalid.") def __neg__(self): return Series(TransferFunction(-1, 1, self.var), self) def to_expr(self): """Returns the equivalent ``Expr`` object.""" return Mul(*(arg.to_expr() for arg in self.args), evaluate=False) @property def is_proper(self): """ Returns True if degree of the numerator polynomial of the resultant transfer function is less than or equal to degree of the denominator polynomial of the same, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Series >>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s) >>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*s + 2, s) >>> tf3 = TransferFunction(s, s**2 + s + 1, s) >>> S1 = Series(-tf2, tf1) >>> S1.is_proper False >>> S2 = Series(tf1, tf2, tf3) >>> S2.is_proper True """ return self.doit().is_proper @property def is_strictly_proper(self): """ Returns True if degree of the numerator polynomial of the resultant transfer function is strictly less than degree of the denominator polynomial of the same, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Series >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(s**3 - 2, s**2 + 5*s + 6, s) >>> tf3 = TransferFunction(1, s**2 + s + 1, s) >>> S1 = Series(tf1, tf2) >>> S1.is_strictly_proper False >>> S2 = Series(tf1, tf2, tf3) >>> S2.is_strictly_proper True """ return self.doit().is_strictly_proper @property def is_biproper(self): r""" Returns True if degree of the numerator polynomial of the resultant transfer function is equal to degree of the denominator polynomial of the same, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Series >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(p, s**2, s) >>> tf3 = TransferFunction(s**2, 1, s) >>> S1 = Series(tf1, -tf2) >>> S1.is_biproper False >>> S2 = Series(tf2, tf3) >>> S2.is_biproper True """ return self.doit().is_biproper def _mat_mul_compatible(*args): """To check whether shapes are compatible for matrix mul.""" return all(args[i].num_outputs == args[i+1].num_inputs for i in range(len(args)-1)) class MIMOSeries(MIMOLinearTimeInvariant): r""" A class for representing a series configuration of MIMO systems. Parameters ========== args : MIMOLinearTimeInvariant MIMO systems in a series configuration. evaluate : Boolean, Keyword When passed ``True``, returns the equivalent ``MIMOSeries(*args).doit()``. Set to ``False`` by default. Raises ====== ValueError When no argument is passed. ``var`` attribute is not same for every system. ``num_outputs`` of the MIMO system is not equal to the ``num_inputs`` of its adjacent MIMO system. (Matrix multiplication constraint, basically) TypeError Any of the passed ``*args`` has unsupported type A combination of SISO and MIMO systems is passed. There should be homogeneity in the type of systems passed, MIMO in this case. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import MIMOSeries, TransferFunctionMatrix >>> from sympy import Matrix, pprint >>> mat_a = Matrix([[5*s], [5]]) # 2 Outputs 1 Input >>> mat_b = Matrix([[5, 1/(6*s**2)]]) # 1 Output 2 Inputs >>> mat_c = Matrix([[1, s], [5/s, 1]]) # 2 Outputs 2 Inputs >>> tfm_a = TransferFunctionMatrix.from_Matrix(mat_a, s) >>> tfm_b = TransferFunctionMatrix.from_Matrix(mat_b, s) >>> tfm_c = TransferFunctionMatrix.from_Matrix(mat_c, s) >>> MIMOSeries(tfm_c, tfm_b, tfm_a) MIMOSeries(TransferFunctionMatrix(((TransferFunction(1, 1, s), TransferFunction(s, 1, s)), (TransferFunction(5, s, s), TransferFunction(1, 1, s)))), TransferFunctionMatrix(((TransferFunction(5, 1, s), TransferFunction(1, 6*s**2, s)),)), TransferFunctionMatrix(((TransferFunction(5*s, 1, s),), (TransferFunction(5, 1, s),)))) >>> pprint(_, use_unicode=False) # For Better Visualization [5*s] [1 s] [---] [5 1 ] [- -] [ 1 ] [- ----] [1 1] [ ] *[1 2] *[ ] [ 5 ] [ 6*s ]{t} [5 1] [ - ] [- -] [ 1 ]{t} [s 1]{t} >>> MIMOSeries(tfm_c, tfm_b, tfm_a).doit() TransferFunctionMatrix(((TransferFunction(150*s**4 + 25*s, 6*s**3, s), TransferFunction(150*s**4 + 5*s, 6*s**2, s)), (TransferFunction(150*s**3 + 25, 6*s**3, s), TransferFunction(150*s**3 + 5, 6*s**2, s)))) >>> pprint(_, use_unicode=False) # (2 Inputs -A-> 2 Outputs) -> (2 Inputs -B-> 1 Output) -> (1 Input -C-> 2 Outputs) is equivalent to (2 Inputs -Series Equivalent-> 2 Outputs). [ 4 4 ] [150*s + 25*s 150*s + 5*s] [------------- ------------] [ 3 2 ] [ 6*s 6*s ] [ ] [ 3 3 ] [ 150*s + 25 150*s + 5 ] [ ----------- ---------- ] [ 3 2 ] [ 6*s 6*s ]{t} Notes ===== All the transfer function matrices should use the same complex variable ``var`` of the Laplace transform. ``MIMOSeries(A, B)`` is not equivalent to ``A*B``. It is always in the reverse order, that is ``B*A``. See Also ======== Series, MIMOParallel """ def __new__(cls, *args, evaluate=False): cls._check_args(args) if _mat_mul_compatible(*args): obj = super().__new__(cls, *args) else: raise ValueError("Number of input signals do not match the number" " of output signals of adjacent systems for some args.") return obj.doit() if evaluate else obj @property def var(self): """ Returns the complex variable used by all the transfer functions. Examples ======== >>> from sympy.abc import p >>> from sympy.physics.control.lti import TransferFunction, MIMOSeries, TransferFunctionMatrix >>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p) >>> G2 = TransferFunction(p, 4 - p, p) >>> G3 = TransferFunction(0, p**4 - 1, p) >>> tfm_1 = TransferFunctionMatrix([[G1, G2, G3]]) >>> tfm_2 = TransferFunctionMatrix([[G1], [G2], [G3]]) >>> MIMOSeries(tfm_2, tfm_1).var p """ return self.args[0].var @property def num_inputs(self): """Returns the number of input signals of the series system.""" return self.args[0].num_inputs @property def num_outputs(self): """Returns the number of output signals of the series system.""" return self.args[-1].num_outputs @property def shape(self): """Returns the shape of the equivalent MIMO system.""" return self.num_outputs, self.num_inputs def doit(self, cancel=False, **kwargs): """ Returns the resultant transfer function matrix obtained after evaluating the MIMO systems arranged in a series configuration. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, MIMOSeries, TransferFunctionMatrix >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s) >>> tfm1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf2]]) >>> tfm2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf1]]) >>> MIMOSeries(tfm2, tfm1).doit() TransferFunctionMatrix(((TransferFunction(2*(-p + s)*(s**3 - 2)*(a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)**2*(s**4 + 5*s + 6)**2, s), TransferFunction((-p + s)**2*(s**3 - 2)*(a*p**2 + b*s) + (-p + s)*(a*p**2 + b*s)**2*(s**4 + 5*s + 6), (-p + s)**3*(s**4 + 5*s + 6), s)), (TransferFunction((-p + s)*(s**3 - 2)**2*(s**4 + 5*s + 6) + (s**3 - 2)*(a*p**2 + b*s)*(s**4 + 5*s + 6)**2, (-p + s)*(s**4 + 5*s + 6)**3, s), TransferFunction(2*(s**3 - 2)*(a*p**2 + b*s), (-p + s)*(s**4 + 5*s + 6), s)))) """ _arg = (arg.doit()._expr_mat for arg in reversed(self.args)) if cancel: res = MatMul(*_arg, evaluate=True) return TransferFunctionMatrix.from_Matrix(res, self.var) _dummy_args, _dummy_dict = _dummify_args(_arg, self.var) res = MatMul(*_dummy_args, evaluate=True) temp_tfm = TransferFunctionMatrix.from_Matrix(res, self.var) return temp_tfm.subs(_dummy_dict) def _eval_rewrite_as_TransferFunctionMatrix(self, *args, **kwargs): return self.doit() @_check_other_MIMO def __add__(self, other): if isinstance(other, MIMOParallel): arg_list = list(other.args) return MIMOParallel(self, *arg_list) return MIMOParallel(self, other) __radd__ = __add__ @_check_other_MIMO def __sub__(self, other): return self + (-other) def __rsub__(self, other): return -self + other @_check_other_MIMO def __mul__(self, other): if isinstance(other, MIMOSeries): self_arg_list = list(self.args) other_arg_list = list(other.args) return MIMOSeries(*other_arg_list, *self_arg_list) # A*B = MIMOSeries(B, A) arg_list = list(self.args) return MIMOSeries(other, *arg_list) def __neg__(self): arg_list = list(self.args) arg_list[0] = -arg_list[0] return MIMOSeries(*arg_list) class Parallel(SISOLinearTimeInvariant): r""" A class for representing a parallel configuration of SISO systems. Parameters ========== args : SISOLinearTimeInvariant SISO systems in a parallel arrangement. evaluate : Boolean, Keyword When passed ``True``, returns the equivalent ``Parallel(*args).doit()``. Set to ``False`` by default. Raises ====== ValueError When no argument is passed. ``var`` attribute is not same for every system. TypeError Any of the passed ``*args`` has unsupported type A combination of SISO and MIMO systems is passed. There should be homogeneity in the type of systems passed. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Parallel, Series >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s) >>> tf3 = TransferFunction(p**2, p + s, s) >>> P1 = Parallel(tf1, tf2) >>> P1 Parallel(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)) >>> P1.var s >>> P2 = Parallel(tf2, Series(tf3, -tf1)) >>> P2 Parallel(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), Series(TransferFunction(p**2, p + s, s), TransferFunction(-a*p**2 - b*s, -p + s, s))) >>> P2.var s >>> P3 = Parallel(Series(tf1, tf2), Series(tf2, tf3)) >>> P3 Parallel(Series(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)), Series(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), TransferFunction(p**2, p + s, s))) >>> P3.var s You can get the resultant transfer function by using ``.doit()`` method: >>> Parallel(tf1, tf2, -tf3).doit() TransferFunction(-p**2*(-p + s)*(s**4 + 5*s + 6) + (-p + s)*(p + s)*(s**3 - 2) + (p + s)*(a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(p + s)*(s**4 + 5*s + 6), s) >>> Parallel(tf2, Series(tf1, -tf3)).doit() TransferFunction(-p**2*(a*p**2 + b*s)*(s**4 + 5*s + 6) + (-p + s)*(p + s)*(s**3 - 2), (-p + s)*(p + s)*(s**4 + 5*s + 6), s) Notes ===== All the transfer functions should use the same complex variable ``var`` of the Laplace transform. See Also ======== Series, TransferFunction, Feedback """ def __new__(cls, *args, evaluate=False): args = _flatten_args(args, Parallel) cls._check_args(args) obj = super().__new__(cls, *args) return obj.doit() if evaluate else obj @property def var(self): """ Returns the complex variable used by all the transfer functions. Examples ======== >>> from sympy.abc import p >>> from sympy.physics.control.lti import TransferFunction, Parallel, Series >>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p) >>> G2 = TransferFunction(p, 4 - p, p) >>> G3 = TransferFunction(0, p**4 - 1, p) >>> Parallel(G1, G2).var p >>> Parallel(-G3, Series(G1, G2)).var p """ return self.args[0].var def doit(self, **kwargs): """ Returns the resultant transfer function obtained after evaluating the transfer functions in parallel configuration. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Parallel >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s) >>> Parallel(tf2, tf1).doit() TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s) >>> Parallel(-tf1, -tf2).doit() TransferFunction((2 - s**3)*(-p + s) + (-a*p**2 - b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s) """ _arg = (arg.doit().to_expr() for arg in self.args) res = Add(*_arg).as_numer_denom() return TransferFunction(*res, self.var) def _eval_rewrite_as_TransferFunction(self, *args, **kwargs): return self.doit() @_check_other_SISO def __add__(self, other): self_arg_list = list(self.args) return Parallel(*self_arg_list, other) __radd__ = __add__ @_check_other_SISO def __sub__(self, other): return self + (-other) def __rsub__(self, other): return -self + other @_check_other_SISO def __mul__(self, other): if isinstance(other, Series): arg_list = list(other.args) return Series(self, *arg_list) return Series(self, other) def __neg__(self): return Series(TransferFunction(-1, 1, self.var), self) def to_expr(self): """Returns the equivalent ``Expr`` object.""" return Add(*(arg.to_expr() for arg in self.args), evaluate=False) @property def is_proper(self): """ Returns True if degree of the numerator polynomial of the resultant transfer function is less than or equal to degree of the denominator polynomial of the same, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Parallel >>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s) >>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*s + 2, s) >>> tf3 = TransferFunction(s, s**2 + s + 1, s) >>> P1 = Parallel(-tf2, tf1) >>> P1.is_proper False >>> P2 = Parallel(tf2, tf3) >>> P2.is_proper True """ return self.doit().is_proper @property def is_strictly_proper(self): """ Returns True if degree of the numerator polynomial of the resultant transfer function is strictly less than degree of the denominator polynomial of the same, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Parallel >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s) >>> tf3 = TransferFunction(s, s**2 + s + 1, s) >>> P1 = Parallel(tf1, tf2) >>> P1.is_strictly_proper False >>> P2 = Parallel(tf2, tf3) >>> P2.is_strictly_proper True """ return self.doit().is_strictly_proper @property def is_biproper(self): """ Returns True if degree of the numerator polynomial of the resultant transfer function is equal to degree of the denominator polynomial of the same, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Parallel >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(p**2, p + s, s) >>> tf3 = TransferFunction(s, s**2 + s + 1, s) >>> P1 = Parallel(tf1, -tf2) >>> P1.is_biproper True >>> P2 = Parallel(tf2, tf3) >>> P2.is_biproper False """ return self.doit().is_biproper class MIMOParallel(MIMOLinearTimeInvariant): r""" A class for representing a parallel configuration of MIMO systems. Parameters ========== args : MIMOLinearTimeInvariant MIMO Systems in a parallel arrangement. evaluate : Boolean, Keyword When passed ``True``, returns the equivalent ``MIMOParallel(*args).doit()``. Set to ``False`` by default. Raises ====== ValueError When no argument is passed. ``var`` attribute is not same for every system. All MIMO systems passed don't have same shape. TypeError Any of the passed ``*args`` has unsupported type A combination of SISO and MIMO systems is passed. There should be homogeneity in the type of systems passed, MIMO in this case. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunctionMatrix, MIMOParallel >>> from sympy import Matrix, pprint >>> expr_1 = 1/s >>> expr_2 = s/(s**2-1) >>> expr_3 = (2 + s)/(s**2 - 1) >>> expr_4 = 5 >>> tfm_a = TransferFunctionMatrix.from_Matrix(Matrix([[expr_1, expr_2], [expr_3, expr_4]]), s) >>> tfm_b = TransferFunctionMatrix.from_Matrix(Matrix([[expr_2, expr_1], [expr_4, expr_3]]), s) >>> tfm_c = TransferFunctionMatrix.from_Matrix(Matrix([[expr_3, expr_4], [expr_1, expr_2]]), s) >>> MIMOParallel(tfm_a, tfm_b, tfm_c) MIMOParallel(TransferFunctionMatrix(((TransferFunction(1, s, s), TransferFunction(s, s**2 - 1, s)), (TransferFunction(s + 2, s**2 - 1, s), TransferFunction(5, 1, s)))), TransferFunctionMatrix(((TransferFunction(s, s**2 - 1, s), TransferFunction(1, s, s)), (TransferFunction(5, 1, s), TransferFunction(s + 2, s**2 - 1, s)))), TransferFunctionMatrix(((TransferFunction(s + 2, s**2 - 1, s), TransferFunction(5, 1, s)), (TransferFunction(1, s, s), TransferFunction(s, s**2 - 1, s))))) >>> pprint(_, use_unicode=False) # For Better Visualization [ 1 s ] [ s 1 ] [s + 2 5 ] [ - ------] [------ - ] [------ - ] [ s 2 ] [ 2 s ] [ 2 1 ] [ s - 1] [s - 1 ] [s - 1 ] [ ] + [ ] + [ ] [s + 2 5 ] [ 5 s + 2 ] [ 1 s ] [------ - ] [ - ------] [ - ------] [ 2 1 ] [ 1 2 ] [ s 2 ] [s - 1 ]{t} [ s - 1]{t} [ s - 1]{t} >>> MIMOParallel(tfm_a, tfm_b, tfm_c).doit() TransferFunctionMatrix(((TransferFunction(s**2 + s*(2*s + 2) - 1, s*(s**2 - 1), s), TransferFunction(2*s**2 + 5*s*(s**2 - 1) - 1, s*(s**2 - 1), s)), (TransferFunction(s**2 + s*(s + 2) + 5*s*(s**2 - 1) - 1, s*(s**2 - 1), s), TransferFunction(5*s**2 + 2*s - 3, s**2 - 1, s)))) >>> pprint(_, use_unicode=False) [ 2 2 / 2 \ ] [ s + s*(2*s + 2) - 1 2*s + 5*s*\s - 1/ - 1] [ -------------------- -----------------------] [ / 2 \ / 2 \ ] [ s*\s - 1/ s*\s - 1/ ] [ ] [ 2 / 2 \ 2 ] [s + s*(s + 2) + 5*s*\s - 1/ - 1 5*s + 2*s - 3 ] [--------------------------------- -------------- ] [ / 2 \ 2 ] [ s*\s - 1/ s - 1 ]{t} Notes ===== All the transfer function matrices should use the same complex variable ``var`` of the Laplace transform. See Also ======== Parallel, MIMOSeries """ def __new__(cls, *args, evaluate=False): args = _flatten_args(args, MIMOParallel) cls._check_args(args) if any(arg.shape != args[0].shape for arg in args): raise TypeError("Shape of all the args is not equal.") obj = super().__new__(cls, *args) return obj.doit() if evaluate else obj @property def var(self): """ Returns the complex variable used by all the systems. Examples ======== >>> from sympy.abc import p >>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOParallel >>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p) >>> G2 = TransferFunction(p, 4 - p, p) >>> G3 = TransferFunction(0, p**4 - 1, p) >>> G4 = TransferFunction(p**2, p**2 - 1, p) >>> tfm_a = TransferFunctionMatrix([[G1, G2], [G3, G4]]) >>> tfm_b = TransferFunctionMatrix([[G2, G1], [G4, G3]]) >>> MIMOParallel(tfm_a, tfm_b).var p """ return self.args[0].var @property def num_inputs(self): """Returns the number of input signals of the parallel system.""" return self.args[0].num_inputs @property def num_outputs(self): """Returns the number of output signals of the parallel system.""" return self.args[0].num_outputs @property def shape(self): """Returns the shape of the equivalent MIMO system.""" return self.num_outputs, self.num_inputs def doit(self, **kwargs): """ Returns the resultant transfer function matrix obtained after evaluating the MIMO systems arranged in a parallel configuration. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, MIMOParallel, TransferFunctionMatrix >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s) >>> tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) >>> tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) >>> MIMOParallel(tfm_1, tfm_2).doit() TransferFunctionMatrix(((TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s), TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s)), (TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s), TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s)))) """ _arg = (arg.doit()._expr_mat for arg in self.args) res = MatAdd(*_arg, evaluate=True) return TransferFunctionMatrix.from_Matrix(res, self.var) def _eval_rewrite_as_TransferFunctionMatrix(self, *args, **kwargs): return self.doit() @_check_other_MIMO def __add__(self, other): self_arg_list = list(self.args) return MIMOParallel(*self_arg_list, other) __radd__ = __add__ @_check_other_MIMO def __sub__(self, other): return self + (-other) def __rsub__(self, other): return -self + other @_check_other_MIMO def __mul__(self, other): if isinstance(other, MIMOSeries): arg_list = list(other.args) return MIMOSeries(*arg_list, self) return MIMOSeries(other, self) def __neg__(self): arg_list = [-arg for arg in list(self.args)] return MIMOParallel(*arg_list) class Feedback(SISOLinearTimeInvariant): r""" A class for representing closed-loop feedback interconnection between two SISO input/output systems. The first argument, ``sys1``, is the feedforward part of the closed-loop system or in simple words, the dynamical model representing the process to be controlled. The second argument, ``sys2``, is the feedback system and controls the fed back signal to ``sys1``. Both ``sys1`` and ``sys2`` can either be ``Series`` or ``TransferFunction`` objects. Parameters ========== sys1 : Series, TransferFunction The feedforward path system. sys2 : Series, TransferFunction, optional The feedback path system (often a feedback controller). It is the model sitting on the feedback path. If not specified explicitly, the sys2 is assumed to be unit (1.0) transfer function. sign : int, optional The sign of feedback. Can either be ``1`` (for positive feedback) or ``-1`` (for negative feedback). Default value is `-1`. Raises ====== ValueError When ``sys1`` and ``sys2`` are not using the same complex variable of the Laplace transform. When a combination of ``sys1`` and ``sys2`` yields zero denominator. TypeError When either ``sys1`` or ``sys2`` is not a ``Series`` or a ``TransferFunction`` object. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction, Feedback >>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s) >>> controller = TransferFunction(5*s - 10, s + 7, s) >>> F1 = Feedback(plant, controller) >>> F1 Feedback(TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s), TransferFunction(5*s - 10, s + 7, s), -1) >>> F1.var s >>> F1.args (TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s), TransferFunction(5*s - 10, s + 7, s), -1) You can get the feedforward and feedback path systems by using ``.sys1`` and ``.sys2`` respectively. >>> F1.sys1 TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s) >>> F1.sys2 TransferFunction(5*s - 10, s + 7, s) You can get the resultant closed loop transfer function obtained by negative feedback interconnection using ``.doit()`` method. >>> F1.doit() TransferFunction((s + 7)*(s**2 - 4*s + 2)*(3*s**2 + 7*s - 3), ((s + 7)*(s**2 - 4*s + 2) + (5*s - 10)*(3*s**2 + 7*s - 3))*(s**2 - 4*s + 2), s) >>> G = TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s) >>> C = TransferFunction(5*s + 10, s + 10, s) >>> F2 = Feedback(G*C, TransferFunction(1, 1, s)) >>> F2.doit() TransferFunction((s + 10)*(5*s + 10)*(s**2 + 2*s + 3)*(2*s**2 + 5*s + 1), (s + 10)*((s + 10)*(s**2 + 2*s + 3) + (5*s + 10)*(2*s**2 + 5*s + 1))*(s**2 + 2*s + 3), s) To negate a ``Feedback`` object, the ``-`` operator can be prepended: >>> -F1 Feedback(TransferFunction(-3*s**2 - 7*s + 3, s**2 - 4*s + 2, s), TransferFunction(10 - 5*s, s + 7, s), -1) >>> -F2 Feedback(Series(TransferFunction(-1, 1, s), TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s), TransferFunction(5*s + 10, s + 10, s)), TransferFunction(-1, 1, s), -1) See Also ======== MIMOFeedback, Series, Parallel """ def __new__(cls, sys1, sys2=None, sign=-1): if not sys2: sys2 = TransferFunction(1, 1, sys1.var) if not (isinstance(sys1, (TransferFunction, Series)) and isinstance(sys2, (TransferFunction, Series))): raise TypeError("Unsupported type for `sys1` or `sys2` of Feedback.") if sign not in [-1, 1]: raise ValueError("Unsupported type for feedback. `sign` arg should " "either be 1 (positive feedback loop) or -1 (negative feedback loop).") if Mul(sys1.to_expr(), sys2.to_expr()).simplify() == sign: raise ValueError("The equivalent system will have zero denominator.") if sys1.var != sys2.var: raise ValueError("Both `sys1` and `sys2` should be using the" " same complex variable.") return super().__new__(cls, sys1, sys2, _sympify(sign)) @property def sys1(self): """ Returns the feedforward system of the feedback interconnection. Examples ======== >>> from sympy.abc import s, p >>> from sympy.physics.control.lti import TransferFunction, Feedback >>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s) >>> controller = TransferFunction(5*s - 10, s + 7, s) >>> F1 = Feedback(plant, controller) >>> F1.sys1 TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s) >>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p) >>> C = TransferFunction(5*p + 10, p + 10, p) >>> P = TransferFunction(1 - s, p + 2, p) >>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P) >>> F2.sys1 TransferFunction(1, 1, p) """ return self.args[0] @property def sys2(self): """ Returns the feedback controller of the feedback interconnection. Examples ======== >>> from sympy.abc import s, p >>> from sympy.physics.control.lti import TransferFunction, Feedback >>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s) >>> controller = TransferFunction(5*s - 10, s + 7, s) >>> F1 = Feedback(plant, controller) >>> F1.sys2 TransferFunction(5*s - 10, s + 7, s) >>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p) >>> C = TransferFunction(5*p + 10, p + 10, p) >>> P = TransferFunction(1 - s, p + 2, p) >>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P) >>> F2.sys2 Series(TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p), TransferFunction(5*p + 10, p + 10, p), TransferFunction(1 - s, p + 2, p)) """ return self.args[1] @property def var(self): """ Returns the complex variable of the Laplace transform used by all the transfer functions involved in the feedback interconnection. Examples ======== >>> from sympy.abc import s, p >>> from sympy.physics.control.lti import TransferFunction, Feedback >>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s) >>> controller = TransferFunction(5*s - 10, s + 7, s) >>> F1 = Feedback(plant, controller) >>> F1.var s >>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p) >>> C = TransferFunction(5*p + 10, p + 10, p) >>> P = TransferFunction(1 - s, p + 2, p) >>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P) >>> F2.var p """ return self.sys1.var @property def sign(self): """ Returns the type of MIMO Feedback model. ``1`` for Positive and ``-1`` for Negative. """ return self.args[2] @property def sensitivity(self): """ Returns the sensitivity function of the feedback loop. Sensitivity of a Feedback system is the ratio of change in the open loop gain to the change in the closed loop gain. .. note:: This method would not return the complementary sensitivity function. Examples ======== >>> from sympy.abc import p >>> from sympy.physics.control.lti import TransferFunction, Feedback >>> C = TransferFunction(5*p + 10, p + 10, p) >>> P = TransferFunction(1 - p, p + 2, p) >>> F_1 = Feedback(P, C) >>> F_1.sensitivity 1/((1 - p)*(5*p + 10)/((p + 2)*(p + 10)) + 1) """ return 1/(1 - self.sign*self.sys1.to_expr()*self.sys2.to_expr()) def doit(self, cancel=False, expand=False, **kwargs): """ Returns the resultant transfer function obtained by the feedback interconnection. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction, Feedback >>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s) >>> controller = TransferFunction(5*s - 10, s + 7, s) >>> F1 = Feedback(plant, controller) >>> F1.doit() TransferFunction((s + 7)*(s**2 - 4*s + 2)*(3*s**2 + 7*s - 3), ((s + 7)*(s**2 - 4*s + 2) + (5*s - 10)*(3*s**2 + 7*s - 3))*(s**2 - 4*s + 2), s) >>> G = TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s) >>> F2 = Feedback(G, TransferFunction(1, 1, s)) >>> F2.doit() TransferFunction((s**2 + 2*s + 3)*(2*s**2 + 5*s + 1), (s**2 + 2*s + 3)*(3*s**2 + 7*s + 4), s) Use kwarg ``expand=True`` to expand the resultant transfer function. Use ``cancel=True`` to cancel out the common terms in numerator and denominator. >>> F2.doit(cancel=True, expand=True) TransferFunction(2*s**2 + 5*s + 1, 3*s**2 + 7*s + 4, s) >>> F2.doit(expand=True) TransferFunction(2*s**4 + 9*s**3 + 17*s**2 + 17*s + 3, 3*s**4 + 13*s**3 + 27*s**2 + 29*s + 12, s) """ arg_list = list(self.sys1.args) if isinstance(self.sys1, Series) else [self.sys1] # F_n and F_d are resultant TFs of num and den of Feedback. F_n, unit = self.sys1.doit(), TransferFunction(1, 1, self.sys1.var) if self.sign == -1: F_d = Parallel(unit, Series(self.sys2, *arg_list)).doit() else: F_d = Parallel(unit, -Series(self.sys2, *arg_list)).doit() _resultant_tf = TransferFunction(F_n.num * F_d.den, F_n.den * F_d.num, F_n.var) if cancel: _resultant_tf = _resultant_tf.simplify() if expand: _resultant_tf = _resultant_tf.expand() return _resultant_tf def _eval_rewrite_as_TransferFunction(self, num, den, sign, **kwargs): return self.doit() def __neg__(self): return Feedback(-self.sys1, -self.sys2, self.sign) def _is_invertible(a, b, sign): """ Checks whether a given pair of MIMO systems passed is invertible or not. """ _mat = eye(a.num_outputs) - sign*(a.doit()._expr_mat)*(b.doit()._expr_mat) _det = _mat.det() return _det != 0 class MIMOFeedback(MIMOLinearTimeInvariant): r""" A class for representing closed-loop feedback interconnection between two MIMO input/output systems. Parameters ========== sys1 : MIMOSeries, TransferFunctionMatrix The MIMO system placed on the feedforward path. sys2 : MIMOSeries, TransferFunctionMatrix The system placed on the feedback path (often a feedback controller). sign : int, optional The sign of feedback. Can either be ``1`` (for positive feedback) or ``-1`` (for negative feedback). Default value is `-1`. Raises ====== ValueError When ``sys1`` and ``sys2`` are not using the same complex variable of the Laplace transform. Forward path model should have an equal number of inputs/outputs to the feedback path outputs/inputs. When product of ``sys1`` and ``sys2`` is not a square matrix. When the equivalent MIMO system is not invertible. TypeError When either ``sys1`` or ``sys2`` is not a ``MIMOSeries`` or a ``TransferFunctionMatrix`` object. Examples ======== >>> from sympy import Matrix, pprint >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunctionMatrix, MIMOFeedback >>> plant_mat = Matrix([[1, 1/s], [0, 1]]) >>> controller_mat = Matrix([[10, 0], [0, 10]]) # Constant Gain >>> plant = TransferFunctionMatrix.from_Matrix(plant_mat, s) >>> controller = TransferFunctionMatrix.from_Matrix(controller_mat, s) >>> feedback = MIMOFeedback(plant, controller) # Negative Feedback (default) >>> pprint(feedback, use_unicode=False) / [1 1] [10 0 ] \-1 [1 1] | [- -] [-- - ] | [- -] | [1 s] [1 1 ] | [1 s] |I + [ ] *[ ] | * [ ] | [0 1] [0 10] | [0 1] | [- -] [- --] | [- -] \ [1 1]{t} [1 1 ]{t}/ [1 1]{t} To get the equivalent system matrix, use either ``doit`` or ``rewrite`` method. >>> pprint(feedback.doit(), use_unicode=False) [1 1 ] [-- -----] [11 121*s] [ ] [0 1 ] [- -- ] [1 11 ]{t} To negate the ``MIMOFeedback`` object, use ``-`` operator. >>> neg_feedback = -feedback >>> pprint(neg_feedback.doit(), use_unicode=False) [-1 -1 ] [--- -----] [ 11 121*s] [ ] [ 0 -1 ] [ - --- ] [ 1 11 ]{t} See Also ======== Feedback, MIMOSeries, MIMOParallel """ def __new__(cls, sys1, sys2, sign=-1): if not (isinstance(sys1, (TransferFunctionMatrix, MIMOSeries)) and isinstance(sys2, (TransferFunctionMatrix, MIMOSeries))): raise TypeError("Unsupported type for `sys1` or `sys2` of MIMO Feedback.") if sys1.num_inputs != sys2.num_outputs or \ sys1.num_outputs != sys2.num_inputs: raise ValueError("Product of `sys1` and `sys2` " "must yield a square matrix.") if sign not in [-1, 1]: raise ValueError("Unsupported type for feedback. `sign` arg should " "either be 1 (positive feedback loop) or -1 (negative feedback loop).") if not _is_invertible(sys1, sys2, sign): raise ValueError("Non-Invertible system inputted.") if sys1.var != sys2.var: raise ValueError("Both `sys1` and `sys2` should be using the" " same complex variable.") return super().__new__(cls, sys1, sys2, _sympify(sign)) @property def sys1(self): r""" Returns the system placed on the feedforward path of the MIMO feedback interconnection. Examples ======== >>> from sympy import pprint >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback >>> tf1 = TransferFunction(s**2 + s + 1, s**2 - s + 1, s) >>> tf2 = TransferFunction(1, s, s) >>> tf3 = TransferFunction(1, 1, s) >>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) >>> sys2 = TransferFunctionMatrix([[tf3, tf3], [tf3, tf2]]) >>> F_1 = MIMOFeedback(sys1, sys2, 1) >>> F_1.sys1 TransferFunctionMatrix(((TransferFunction(s**2 + s + 1, s**2 - s + 1, s), TransferFunction(1, s, s)), (TransferFunction(1, s, s), TransferFunction(s**2 + s + 1, s**2 - s + 1, s)))) >>> pprint(_, use_unicode=False) [ 2 ] [s + s + 1 1 ] [---------- - ] [ 2 s ] [s - s + 1 ] [ ] [ 2 ] [ 1 s + s + 1] [ - ----------] [ s 2 ] [ s - s + 1]{t} """ return self.args[0] @property def sys2(self): r""" Returns the feedback controller of the MIMO feedback interconnection. Examples ======== >>> from sympy import pprint >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback >>> tf1 = TransferFunction(s**2, s**3 - s + 1, s) >>> tf2 = TransferFunction(1, s, s) >>> tf3 = TransferFunction(1, 1, s) >>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) >>> sys2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf2]]) >>> F_1 = MIMOFeedback(sys1, sys2) >>> F_1.sys2 TransferFunctionMatrix(((TransferFunction(s**2, s**3 - s + 1, s), TransferFunction(1, 1, s)), (TransferFunction(1, 1, s), TransferFunction(1, s, s)))) >>> pprint(_, use_unicode=False) [ 2 ] [ s 1] [---------- -] [ 3 1] [s - s + 1 ] [ ] [ 1 1] [ - -] [ 1 s]{t} """ return self.args[1] @property def var(self): r""" Returns the complex variable of the Laplace transform used by all the transfer functions involved in the MIMO feedback loop. Examples ======== >>> from sympy.abc import p >>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback >>> tf1 = TransferFunction(p, 1 - p, p) >>> tf2 = TransferFunction(1, p, p) >>> tf3 = TransferFunction(1, 1, p) >>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) >>> sys2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf2]]) >>> F_1 = MIMOFeedback(sys1, sys2, 1) # Positive feedback >>> F_1.var p """ return self.sys1.var @property def sign(self): r""" Returns the type of feedback interconnection of two models. ``1`` for Positive and ``-1`` for Negative. """ return self.args[2] @property def sensitivity(self): r""" Returns the sensitivity function matrix of the feedback loop. Sensitivity of a closed-loop system is the ratio of change in the open loop gain to the change in the closed loop gain. .. note:: This method would not return the complementary sensitivity function. Examples ======== >>> from sympy import pprint >>> from sympy.abc import p >>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback >>> tf1 = TransferFunction(p, 1 - p, p) >>> tf2 = TransferFunction(1, p, p) >>> tf3 = TransferFunction(1, 1, p) >>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) >>> sys2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf2]]) >>> F_1 = MIMOFeedback(sys1, sys2, 1) # Positive feedback >>> F_2 = MIMOFeedback(sys1, sys2) # Negative feedback >>> pprint(F_1.sensitivity, use_unicode=False) [ 4 3 2 5 4 2 ] [- p + 3*p - 4*p + 3*p - 1 p - 2*p + 3*p - 3*p + 1 ] [---------------------------- -----------------------------] [ 4 3 2 5 4 3 2 ] [ p + 3*p - 8*p + 8*p - 3 p + 3*p - 8*p + 8*p - 3*p] [ ] [ 4 3 2 3 2 ] [ p - p - p + p 3*p - 6*p + 4*p - 1 ] [ -------------------------- -------------------------- ] [ 4 3 2 4 3 2 ] [ p + 3*p - 8*p + 8*p - 3 p + 3*p - 8*p + 8*p - 3 ] >>> pprint(F_2.sensitivity, use_unicode=False) [ 4 3 2 5 4 2 ] [p - 3*p + 2*p + p - 1 p - 2*p + 3*p - 3*p + 1] [------------------------ --------------------------] [ 4 3 5 4 2 ] [ p - 3*p + 2*p - 1 p - 3*p + 2*p - p ] [ ] [ 4 3 2 4 3 ] [ p - p - p + p 2*p - 3*p + 2*p - 1 ] [ ------------------- --------------------- ] [ 4 3 4 3 ] [ p - 3*p + 2*p - 1 p - 3*p + 2*p - 1 ] """ _sys1_mat = self.sys1.doit()._expr_mat _sys2_mat = self.sys2.doit()._expr_mat return (eye(self.sys1.num_inputs) - \ self.sign*_sys1_mat*_sys2_mat).inv() def doit(self, cancel=True, expand=False, **kwargs): r""" Returns the resultant transfer function matrix obtained by the feedback interconnection. Examples ======== >>> from sympy import pprint >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback >>> tf1 = TransferFunction(s, 1 - s, s) >>> tf2 = TransferFunction(1, s, s) >>> tf3 = TransferFunction(5, 1, s) >>> tf4 = TransferFunction(s - 1, s, s) >>> tf5 = TransferFunction(0, 1, s) >>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]]) >>> sys2 = TransferFunctionMatrix([[tf3, tf5], [tf5, tf5]]) >>> F_1 = MIMOFeedback(sys1, sys2, 1) >>> pprint(F_1, use_unicode=False) / [ s 1 ] [5 0] \-1 [ s 1 ] | [----- - ] [- -] | [----- - ] | [1 - s s ] [1 1] | [1 - s s ] |I - [ ] *[ ] | * [ ] | [ 5 s - 1] [0 0] | [ 5 s - 1] | [ - -----] [- -] | [ - -----] \ [ 1 s ]{t} [1 1]{t}/ [ 1 s ]{t} >>> pprint(F_1.doit(), use_unicode=False) [ -s 1 - s ] [ ------- ----------- ] [ 6*s - 1 s*(1 - 6*s) ] [ ] [25*s*(s - 1) + 5*(1 - s)*(6*s - 1) (s - 1)*(6*s + 24)] [---------------------------------- ------------------] [ (1 - s)*(6*s - 1) s*(6*s - 1) ]{t} If the user wants the resultant ``TransferFunctionMatrix`` object without canceling the common factors then the ``cancel`` kwarg should be passed ``False``. >>> pprint(F_1.doit(cancel=False), use_unicode=False) [ 25*s*(1 - s) 25 - 25*s ] [ -------------------- -------------- ] [ 25*(1 - 6*s)*(1 - s) 25*s*(1 - 6*s) ] [ ] [s*(25*s - 25) + 5*(1 - s)*(6*s - 1) s*(s - 1)*(6*s - 1) + s*(25*s - 25)] [----------------------------------- -----------------------------------] [ (1 - s)*(6*s - 1) 2 ] [ s *(6*s - 1) ]{t} If the user wants the expanded form of the resultant transfer function matrix, the ``expand`` kwarg should be passed as ``True``. >>> pprint(F_1.doit(expand=True), use_unicode=False) [ -s 1 - s ] [ ------- ---------- ] [ 6*s - 1 2 ] [ - 6*s + s ] [ ] [ 2 2 ] [- 5*s + 10*s - 5 6*s + 18*s - 24] [----------------- ----------------] [ 2 2 ] [ - 6*s + 7*s - 1 6*s - s ]{t} """ _mat = self.sensitivity * self.sys1.doit()._expr_mat _resultant_tfm = _to_TFM(_mat, self.var) if cancel: _resultant_tfm = _resultant_tfm.simplify() if expand: _resultant_tfm = _resultant_tfm.expand() return _resultant_tfm def _eval_rewrite_as_TransferFunctionMatrix(self, sys1, sys2, sign, **kwargs): return self.doit() def __neg__(self): return MIMOFeedback(-self.sys1, -self.sys2, self.sign) def _to_TFM(mat, var): """Private method to convert ImmutableMatrix to TransferFunctionMatrix efficiently""" to_tf = lambda expr: TransferFunction.from_rational_expression(expr, var) arg = [[to_tf(expr) for expr in row] for row in mat.tolist()] return TransferFunctionMatrix(arg) class TransferFunctionMatrix(MIMOLinearTimeInvariant): r""" A class for representing the MIMO (multiple-input and multiple-output) generalization of the SISO (single-input and single-output) transfer function. It is a matrix of transfer functions (``TransferFunction``, SISO-``Series`` or SISO-``Parallel``). There is only one argument, ``arg`` which is also the compulsory argument. ``arg`` is expected to be strictly of the type list of lists which holds the transfer functions or reducible to transfer functions. Parameters ========== arg : Nested ``List`` (strictly). Users are expected to input a nested list of ``TransferFunction``, ``Series`` and/or ``Parallel`` objects. Examples ======== .. note:: ``pprint()`` can be used for better visualization of ``TransferFunctionMatrix`` objects. >>> from sympy.abc import s, p, a >>> from sympy import pprint >>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, Series, Parallel >>> tf_1 = TransferFunction(s + a, s**2 + s + 1, s) >>> tf_2 = TransferFunction(p**4 - 3*p + 2, s + p, s) >>> tf_3 = TransferFunction(3, s + 2, s) >>> tf_4 = TransferFunction(-a + p, 9*s - 9, s) >>> tfm_1 = TransferFunctionMatrix([[tf_1], [tf_2], [tf_3]]) >>> tfm_1 TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(3, s + 2, s),))) >>> tfm_1.var s >>> tfm_1.num_inputs 1 >>> tfm_1.num_outputs 3 >>> tfm_1.shape (3, 1) >>> tfm_1.args (((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(3, s + 2, s),)),) >>> tfm_2 = TransferFunctionMatrix([[tf_1, -tf_3], [tf_2, -tf_1], [tf_3, -tf_2]]) >>> tfm_2 TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(p**4 - 3*p + 2, p + s, s), TransferFunction(-a - s, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-p**4 + 3*p - 2, p + s, s)))) >>> pprint(tfm_2, use_unicode=False) # pretty-printing for better visualization [ a + s -3 ] [ ---------- ----- ] [ 2 s + 2 ] [ s + s + 1 ] [ ] [ 4 ] [p - 3*p + 2 -a - s ] [------------ ---------- ] [ p + s 2 ] [ s + s + 1 ] [ ] [ 4 ] [ 3 - p + 3*p - 2] [ ----- --------------] [ s + 2 p + s ]{t} TransferFunctionMatrix can be transposed, if user wants to switch the input and output transfer functions >>> tfm_2.transpose() TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(p**4 - 3*p + 2, p + s, s), TransferFunction(3, s + 2, s)), (TransferFunction(-3, s + 2, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(-p**4 + 3*p - 2, p + s, s)))) >>> pprint(_, use_unicode=False) [ 4 ] [ a + s p - 3*p + 2 3 ] [---------- ------------ ----- ] [ 2 p + s s + 2 ] [s + s + 1 ] [ ] [ 4 ] [ -3 -a - s - p + 3*p - 2] [ ----- ---------- --------------] [ s + 2 2 p + s ] [ s + s + 1 ]{t} >>> tf_5 = TransferFunction(5, s, s) >>> tf_6 = TransferFunction(5*s, (2 + s**2), s) >>> tf_7 = TransferFunction(5, (s*(2 + s**2)), s) >>> tf_8 = TransferFunction(5, 1, s) >>> tfm_3 = TransferFunctionMatrix([[tf_5, tf_6], [tf_7, tf_8]]) >>> tfm_3 TransferFunctionMatrix(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)), (TransferFunction(5, s*(s**2 + 2), s), TransferFunction(5, 1, s)))) >>> pprint(tfm_3, use_unicode=False) [ 5 5*s ] [ - ------] [ s 2 ] [ s + 2] [ ] [ 5 5 ] [---------- - ] [ / 2 \ 1 ] [s*\s + 2/ ]{t} >>> tfm_3.var s >>> tfm_3.shape (2, 2) >>> tfm_3.num_outputs 2 >>> tfm_3.num_inputs 2 >>> tfm_3.args (((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)), (TransferFunction(5, s*(s**2 + 2), s), TransferFunction(5, 1, s))),) To access the ``TransferFunction`` at any index in the ``TransferFunctionMatrix``, use the index notation. >>> tfm_3[1, 0] # gives the TransferFunction present at 2nd Row and 1st Col. Similar to that in Matrix classes TransferFunction(5, s*(s**2 + 2), s) >>> tfm_3[0, 0] # gives the TransferFunction present at 1st Row and 1st Col. TransferFunction(5, s, s) >>> tfm_3[:, 0] # gives the first column TransferFunctionMatrix(((TransferFunction(5, s, s),), (TransferFunction(5, s*(s**2 + 2), s),))) >>> pprint(_, use_unicode=False) [ 5 ] [ - ] [ s ] [ ] [ 5 ] [----------] [ / 2 \] [s*\s + 2/]{t} >>> tfm_3[0, :] # gives the first row TransferFunctionMatrix(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)),)) >>> pprint(_, use_unicode=False) [5 5*s ] [- ------] [s 2 ] [ s + 2]{t} To negate a transfer function matrix, ``-`` operator can be prepended: >>> tfm_4 = TransferFunctionMatrix([[tf_2], [-tf_1], [tf_3]]) >>> -tfm_4 TransferFunctionMatrix(((TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(-3, s + 2, s),))) >>> tfm_5 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, -tf_1]]) >>> -tfm_5 TransferFunctionMatrix(((TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(-p**4 + 3*p - 2, p + s, s)), (TransferFunction(-3, s + 2, s), TransferFunction(a + s, s**2 + s + 1, s)))) ``subs()`` returns the ``TransferFunctionMatrix`` object with the value substituted in the expression. This will not mutate your original ``TransferFunctionMatrix``. >>> tfm_2.subs(p, 2) # substituting p everywhere in tfm_2 with 2. TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(12, s + 2, s), TransferFunction(-a - s, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-12, s + 2, s)))) >>> pprint(_, use_unicode=False) [ a + s -3 ] [---------- ----- ] [ 2 s + 2 ] [s + s + 1 ] [ ] [ 12 -a - s ] [ ----- ----------] [ s + 2 2 ] [ s + s + 1] [ ] [ 3 -12 ] [ ----- ----- ] [ s + 2 s + 2 ]{t} >>> pprint(tfm_2, use_unicode=False) # State of tfm_2 is unchanged after substitution [ a + s -3 ] [ ---------- ----- ] [ 2 s + 2 ] [ s + s + 1 ] [ ] [ 4 ] [p - 3*p + 2 -a - s ] [------------ ---------- ] [ p + s 2 ] [ s + s + 1 ] [ ] [ 4 ] [ 3 - p + 3*p - 2] [ ----- --------------] [ s + 2 p + s ]{t} ``subs()`` also supports multiple substitutions. >>> tfm_2.subs({p: 2, a: 1}) # substituting p with 2 and a with 1 TransferFunctionMatrix(((TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(12, s + 2, s), TransferFunction(-s - 1, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-12, s + 2, s)))) >>> pprint(_, use_unicode=False) [ s + 1 -3 ] [---------- ----- ] [ 2 s + 2 ] [s + s + 1 ] [ ] [ 12 -s - 1 ] [ ----- ----------] [ s + 2 2 ] [ s + s + 1] [ ] [ 3 -12 ] [ ----- ----- ] [ s + 2 s + 2 ]{t} Users can reduce the ``Series`` and ``Parallel`` elements of the matrix to ``TransferFunction`` by using ``doit()``. >>> tfm_6 = TransferFunctionMatrix([[Series(tf_3, tf_4), Parallel(tf_3, tf_4)]]) >>> tfm_6 TransferFunctionMatrix(((Series(TransferFunction(3, s + 2, s), TransferFunction(-a + p, 9*s - 9, s)), Parallel(TransferFunction(3, s + 2, s), TransferFunction(-a + p, 9*s - 9, s))),)) >>> pprint(tfm_6, use_unicode=False) [ -a + p 3 -a + p 3 ] [-------*----- ------- + -----] [9*s - 9 s + 2 9*s - 9 s + 2]{t} >>> tfm_6.doit() TransferFunctionMatrix(((TransferFunction(-3*a + 3*p, (s + 2)*(9*s - 9), s), TransferFunction(27*s + (-a + p)*(s + 2) - 27, (s + 2)*(9*s - 9), s)),)) >>> pprint(_, use_unicode=False) [ -3*a + 3*p 27*s + (-a + p)*(s + 2) - 27] [----------------- ----------------------------] [(s + 2)*(9*s - 9) (s + 2)*(9*s - 9) ]{t} >>> tf_9 = TransferFunction(1, s, s) >>> tf_10 = TransferFunction(1, s**2, s) >>> tfm_7 = TransferFunctionMatrix([[Series(tf_9, tf_10), tf_9], [tf_10, Parallel(tf_9, tf_10)]]) >>> tfm_7 TransferFunctionMatrix(((Series(TransferFunction(1, s, s), TransferFunction(1, s**2, s)), TransferFunction(1, s, s)), (TransferFunction(1, s**2, s), Parallel(TransferFunction(1, s, s), TransferFunction(1, s**2, s))))) >>> pprint(tfm_7, use_unicode=False) [ 1 1 ] [---- - ] [ 2 s ] [s*s ] [ ] [ 1 1 1] [ -- -- + -] [ 2 2 s] [ s s ]{t} >>> tfm_7.doit() TransferFunctionMatrix(((TransferFunction(1, s**3, s), TransferFunction(1, s, s)), (TransferFunction(1, s**2, s), TransferFunction(s**2 + s, s**3, s)))) >>> pprint(_, use_unicode=False) [1 1 ] [-- - ] [ 3 s ] [s ] [ ] [ 2 ] [1 s + s] [-- ------] [ 2 3 ] [s s ]{t} Addition, subtraction, and multiplication of transfer function matrices can form unevaluated ``Series`` or ``Parallel`` objects. - For addition and subtraction: All the transfer function matrices must have the same shape. - For multiplication (C = A * B): The number of inputs of the first transfer function matrix (A) must be equal to the number of outputs of the second transfer function matrix (B). Also, use pretty-printing (``pprint``) to analyse better. >>> tfm_8 = TransferFunctionMatrix([[tf_3], [tf_2], [-tf_1]]) >>> tfm_9 = TransferFunctionMatrix([[-tf_3]]) >>> tfm_10 = TransferFunctionMatrix([[tf_1], [tf_2], [tf_4]]) >>> tfm_11 = TransferFunctionMatrix([[tf_4], [-tf_1]]) >>> tfm_12 = TransferFunctionMatrix([[tf_4, -tf_1, tf_3], [-tf_2, -tf_4, -tf_3]]) >>> tfm_8 + tfm_10 MIMOParallel(TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a + p, 9*s - 9, s),)))) >>> pprint(_, use_unicode=False) [ 3 ] [ a + s ] [ ----- ] [ ---------- ] [ s + 2 ] [ 2 ] [ ] [ s + s + 1 ] [ 4 ] [ ] [p - 3*p + 2] [ 4 ] [------------] + [p - 3*p + 2] [ p + s ] [------------] [ ] [ p + s ] [ -a - s ] [ ] [ ---------- ] [ -a + p ] [ 2 ] [ ------- ] [ s + s + 1 ]{t} [ 9*s - 9 ]{t} >>> -tfm_10 - tfm_8 MIMOParallel(TransferFunctionMatrix(((TransferFunction(-a - s, s**2 + s + 1, s),), (TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a - p, 9*s - 9, s),))), TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),), (TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a + s, s**2 + s + 1, s),)))) >>> pprint(_, use_unicode=False) [ -a - s ] [ -3 ] [ ---------- ] [ ----- ] [ 2 ] [ s + 2 ] [ s + s + 1 ] [ ] [ ] [ 4 ] [ 4 ] [- p + 3*p - 2] [- p + 3*p - 2] + [--------------] [--------------] [ p + s ] [ p + s ] [ ] [ ] [ a + s ] [ a - p ] [ ---------- ] [ ------- ] [ 2 ] [ 9*s - 9 ]{t} [ s + s + 1 ]{t} >>> tfm_12 * tfm_8 MIMOSeries(TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(-a + p, 9*s - 9, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(3, s + 2, s)), (TransferFunction(-p**4 + 3*p - 2, p + s, s), TransferFunction(a - p, 9*s - 9, s), TransferFunction(-3, s + 2, s))))) >>> pprint(_, use_unicode=False) [ 3 ] [ ----- ] [ -a + p -a - s 3 ] [ s + 2 ] [ ------- ---------- -----] [ ] [ 9*s - 9 2 s + 2] [ 4 ] [ s + s + 1 ] [p - 3*p + 2] [ ] *[------------] [ 4 ] [ p + s ] [- p + 3*p - 2 a - p -3 ] [ ] [-------------- ------- -----] [ -a - s ] [ p + s 9*s - 9 s + 2]{t} [ ---------- ] [ 2 ] [ s + s + 1 ]{t} >>> tfm_12 * tfm_8 * tfm_9 MIMOSeries(TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),),)), TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(-a + p, 9*s - 9, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(3, s + 2, s)), (TransferFunction(-p**4 + 3*p - 2, p + s, s), TransferFunction(a - p, 9*s - 9, s), TransferFunction(-3, s + 2, s))))) >>> pprint(_, use_unicode=False) [ 3 ] [ ----- ] [ -a + p -a - s 3 ] [ s + 2 ] [ ------- ---------- -----] [ ] [ 9*s - 9 2 s + 2] [ 4 ] [ s + s + 1 ] [p - 3*p + 2] [ -3 ] [ ] *[------------] *[-----] [ 4 ] [ p + s ] [s + 2]{t} [- p + 3*p - 2 a - p -3 ] [ ] [-------------- ------- -----] [ -a - s ] [ p + s 9*s - 9 s + 2]{t} [ ---------- ] [ 2 ] [ s + s + 1 ]{t} >>> tfm_10 + tfm_8*tfm_9 MIMOParallel(TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a + p, 9*s - 9, s),))), MIMOSeries(TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),),)), TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))))) >>> pprint(_, use_unicode=False) [ a + s ] [ 3 ] [ ---------- ] [ ----- ] [ 2 ] [ s + 2 ] [ s + s + 1 ] [ ] [ ] [ 4 ] [ 4 ] [p - 3*p + 2] [ -3 ] [p - 3*p + 2] + [------------] *[-----] [------------] [ p + s ] [s + 2]{t} [ p + s ] [ ] [ ] [ -a - s ] [ -a + p ] [ ---------- ] [ ------- ] [ 2 ] [ 9*s - 9 ]{t} [ s + s + 1 ]{t} These unevaluated ``Series`` or ``Parallel`` objects can convert into the resultant transfer function matrix using ``.doit()`` method or by ``.rewrite(TransferFunctionMatrix)``. >>> (-tfm_8 + tfm_10 + tfm_8*tfm_9).doit() TransferFunctionMatrix(((TransferFunction((a + s)*(s + 2)**3 - 3*(s + 2)**2*(s**2 + s + 1) - 9*(s + 2)*(s**2 + s + 1), (s + 2)**3*(s**2 + s + 1), s),), (TransferFunction((p + s)*(-3*p**4 + 9*p - 6), (p + s)**2*(s + 2), s),), (TransferFunction((-a + p)*(s + 2)*(s**2 + s + 1)**2 + (a + s)*(s + 2)*(9*s - 9)*(s**2 + s + 1) + (3*a + 3*s)*(9*s - 9)*(s**2 + s + 1), (s + 2)*(9*s - 9)*(s**2 + s + 1)**2, s),))) >>> (-tfm_12 * -tfm_8 * -tfm_9).rewrite(TransferFunctionMatrix) TransferFunctionMatrix(((TransferFunction(3*(-3*a + 3*p)*(p + s)*(s + 2)*(s**2 + s + 1)**2 + 3*(-3*a - 3*s)*(p + s)*(s + 2)*(9*s - 9)*(s**2 + s + 1) + 3*(a + s)*(s + 2)**2*(9*s - 9)*(-p**4 + 3*p - 2)*(s**2 + s + 1), (p + s)*(s + 2)**3*(9*s - 9)*(s**2 + s + 1)**2, s),), (TransferFunction(3*(-a + p)*(p + s)*(s + 2)**2*(-p**4 + 3*p - 2)*(s**2 + s + 1) + 3*(3*a + 3*s)*(p + s)**2*(s + 2)*(9*s - 9) + 3*(p + s)*(s + 2)*(9*s - 9)*(-3*p**4 + 9*p - 6)*(s**2 + s + 1), (p + s)**2*(s + 2)**3*(9*s - 9)*(s**2 + s + 1), s),))) See Also ======== TransferFunction, MIMOSeries, MIMOParallel, Feedback """ def __new__(cls, arg): expr_mat_arg = [] try: var = arg[0][0].var except TypeError: raise ValueError("`arg` param in TransferFunctionMatrix should " "strictly be a nested list containing TransferFunction objects.") for row_index, row in enumerate(arg): temp = [] for col_index, element in enumerate(row): if not isinstance(element, SISOLinearTimeInvariant): raise TypeError("Each element is expected to be of type `SISOLinearTimeInvariant`.") if var != element.var: raise ValueError("Conflicting value(s) found for `var`. All TransferFunction instances in " "TransferFunctionMatrix should use the same complex variable in Laplace domain.") temp.append(element.to_expr()) expr_mat_arg.append(temp) if isinstance(arg, (list, Tuple)): # Making nested Tuple (sympy.core.containers.Tuple) from nested list or nested python tuple arg = Tuple(*(Tuple(*r, sympify=False) for r in arg), sympify=False) obj = super(TransferFunctionMatrix, cls).__new__(cls, arg) obj._expr_mat = ImmutableMatrix(expr_mat_arg) return obj @classmethod def from_Matrix(cls, matrix, var): """ Creates a new ``TransferFunctionMatrix`` efficiently from a SymPy Matrix of ``Expr`` objects. Parameters ========== matrix : ``ImmutableMatrix`` having ``Expr``/``Number`` elements. var : Symbol Complex variable of the Laplace transform which will be used by the all the ``TransferFunction`` objects in the ``TransferFunctionMatrix``. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunctionMatrix >>> from sympy import Matrix, pprint >>> M = Matrix([[s, 1/s], [1/(s+1), s]]) >>> M_tf = TransferFunctionMatrix.from_Matrix(M, s) >>> pprint(M_tf, use_unicode=False) [ s 1] [ - -] [ 1 s] [ ] [ 1 s] [----- -] [s + 1 1]{t} >>> M_tf.elem_poles() [[[], [0]], [[-1], []]] >>> M_tf.elem_zeros() [[[0], []], [[], [0]]] """ return _to_TFM(matrix, var) @property def var(self): """ Returns the complex variable used by all the transfer functions or ``Series``/``Parallel`` objects in a transfer function matrix. Examples ======== >>> from sympy.abc import p, s >>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, Series, Parallel >>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p) >>> G2 = TransferFunction(p, 4 - p, p) >>> G3 = TransferFunction(0, p**4 - 1, p) >>> G4 = TransferFunction(s + 1, s**2 + s + 1, s) >>> S1 = Series(G1, G2) >>> S2 = Series(-G3, Parallel(G2, -G1)) >>> tfm1 = TransferFunctionMatrix([[G1], [G2], [G3]]) >>> tfm1.var p >>> tfm2 = TransferFunctionMatrix([[-S1, -S2], [S1, S2]]) >>> tfm2.var p >>> tfm3 = TransferFunctionMatrix([[G4]]) >>> tfm3.var s """ return self.args[0][0][0].var @property def num_inputs(self): """ Returns the number of inputs of the system. Examples ======== >>> from sympy.abc import s, p >>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix >>> G1 = TransferFunction(s + 3, s**2 - 3, s) >>> G2 = TransferFunction(4, s**2, s) >>> G3 = TransferFunction(p**2 + s**2, p - 3, s) >>> tfm_1 = TransferFunctionMatrix([[G2, -G1, G3], [-G2, -G1, -G3]]) >>> tfm_1.num_inputs 3 See Also ======== num_outputs """ return self._expr_mat.shape[1] @property def num_outputs(self): """ Returns the number of outputs of the system. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunctionMatrix >>> from sympy import Matrix >>> M_1 = Matrix([[s], [1/s]]) >>> TFM = TransferFunctionMatrix.from_Matrix(M_1, s) >>> print(TFM) TransferFunctionMatrix(((TransferFunction(s, 1, s),), (TransferFunction(1, s, s),))) >>> TFM.num_outputs 2 See Also ======== num_inputs """ return self._expr_mat.shape[0] @property def shape(self): """ Returns the shape of the transfer function matrix, that is, ``(# of outputs, # of inputs)``. Examples ======== >>> from sympy.abc import s, p >>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix >>> tf1 = TransferFunction(p**2 - 1, s**4 + s**3 - p, p) >>> tf2 = TransferFunction(1 - p, p**2 - 3*p + 7, p) >>> tf3 = TransferFunction(3, 4, p) >>> tfm1 = TransferFunctionMatrix([[tf1, -tf2]]) >>> tfm1.shape (1, 2) >>> tfm2 = TransferFunctionMatrix([[-tf2, tf3], [tf1, -tf1]]) >>> tfm2.shape (2, 2) """ return self._expr_mat.shape def __neg__(self): neg = -self._expr_mat return _to_TFM(neg, self.var) @_check_other_MIMO def __add__(self, other): if not isinstance(other, MIMOParallel): return MIMOParallel(self, other) other_arg_list = list(other.args) return MIMOParallel(self, *other_arg_list) @_check_other_MIMO def __sub__(self, other): return self + (-other) @_check_other_MIMO def __mul__(self, other): if not isinstance(other, MIMOSeries): return MIMOSeries(other, self) other_arg_list = list(other.args) return MIMOSeries(*other_arg_list, self) def __getitem__(self, key): trunc = self._expr_mat.__getitem__(key) if isinstance(trunc, ImmutableMatrix): return _to_TFM(trunc, self.var) return TransferFunction.from_rational_expression(trunc, self.var) def transpose(self): """Returns the transpose of the ``TransferFunctionMatrix`` (switched input and output layers).""" transposed_mat = self._expr_mat.transpose() return _to_TFM(transposed_mat, self.var) def elem_poles(self): """ Returns the poles of each element of the ``TransferFunctionMatrix``. .. note:: Actual poles of a MIMO system are NOT the poles of individual elements. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix >>> tf_1 = TransferFunction(3, (s + 1), s) >>> tf_2 = TransferFunction(s + 6, (s + 1)*(s + 2), s) >>> tf_3 = TransferFunction(s + 3, s**2 + 3*s + 2, s) >>> tf_4 = TransferFunction(s + 2, s**2 + 5*s - 10, s) >>> tfm_1 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, tf_4]]) >>> tfm_1 TransferFunctionMatrix(((TransferFunction(3, s + 1, s), TransferFunction(s + 6, (s + 1)*(s + 2), s)), (TransferFunction(s + 3, s**2 + 3*s + 2, s), TransferFunction(s + 2, s**2 + 5*s - 10, s)))) >>> tfm_1.elem_poles() [[[-1], [-2, -1]], [[-2, -1], [-5/2 + sqrt(65)/2, -sqrt(65)/2 - 5/2]]] See Also ======== elem_zeros """ return [[element.poles() for element in row] for row in self.doit().args[0]] def elem_zeros(self): """ Returns the zeros of each element of the ``TransferFunctionMatrix``. .. note:: Actual zeros of a MIMO system are NOT the zeros of individual elements. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix >>> tf_1 = TransferFunction(3, (s + 1), s) >>> tf_2 = TransferFunction(s + 6, (s + 1)*(s + 2), s) >>> tf_3 = TransferFunction(s + 3, s**2 + 3*s + 2, s) >>> tf_4 = TransferFunction(s**2 - 9*s + 20, s**2 + 5*s - 10, s) >>> tfm_1 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, tf_4]]) >>> tfm_1 TransferFunctionMatrix(((TransferFunction(3, s + 1, s), TransferFunction(s + 6, (s + 1)*(s + 2), s)), (TransferFunction(s + 3, s**2 + 3*s + 2, s), TransferFunction(s**2 - 9*s + 20, s**2 + 5*s - 10, s)))) >>> tfm_1.elem_zeros() [[[], [-6]], [[-3], [4, 5]]] See Also ======== elem_poles """ return [[element.zeros() for element in row] for row in self.doit().args[0]] def _flat(self): """Returns flattened list of args in TransferFunctionMatrix""" return [elem for tup in self.args[0] for elem in tup] def _eval_evalf(self, prec): """Calls evalf() on each transfer function in the transfer function matrix""" mat = self._expr_mat.applyfunc(lambda a: a.evalf(n=prec_to_dps(prec))) return _to_TFM(mat, self.var) def _eval_simplify(self, **kwargs): """Simplifies the transfer function matrix""" simp_mat = self._expr_mat.applyfunc(lambda a: cancel(a, expand=False)) return _to_TFM(simp_mat, self.var) def expand(self, **hints): """Expands the transfer function matrix""" expand_mat = self._expr_mat.expand(**hints) return _to_TFM(expand_mat, self.var)
4fddda2a0103a89f7b82bd45b1abc4b4a1d38c4ff210392c88c45ff7d7e0f26b
from sympy import I, log, apart, exp from sympy.core.symbol import Dummy from sympy.external import import_module from sympy.functions import arg, Abs from sympy.integrals.transforms import _fast_inverse_laplace from sympy.physics.control.lti import SISOLinearTimeInvariant from sympy.plotting.plot import LineOver1DRangeSeries from sympy.polys.polytools import Poly from sympy.printing.latex import latex __all__ = ['pole_zero_numerical_data', 'pole_zero_plot', 'step_response_numerical_data', 'step_response_plot', 'impulse_response_numerical_data', 'impulse_response_plot', 'ramp_response_numerical_data', 'ramp_response_plot', 'bode_magnitude_numerical_data', 'bode_phase_numerical_data', 'bode_magnitude_plot', 'bode_phase_plot', 'bode_plot'] matplotlib = import_module( 'matplotlib', import_kwargs={'fromlist': ['pyplot']}, catch=(RuntimeError,)) numpy = import_module('numpy') if matplotlib: plt = matplotlib.pyplot if numpy: np = numpy # Matplotlib already has numpy as a compulsory dependency. No need to install it separately. def _check_system(system): """Function to check whether the dynamical system passed for plots is compatible or not.""" if not isinstance(system, SISOLinearTimeInvariant): raise NotImplementedError("Only SISO LTI systems are currently supported.") sys = system.to_expr() len_free_symbols = len(sys.free_symbols) if len_free_symbols > 1: raise ValueError("Extra degree of freedom found. Make sure" " that there are no free symbols in the dynamical system other" " than the variable of Laplace transform.") if sys.has(exp): raise NotImplementedError("Time delay terms are not supported.") def pole_zero_numerical_data(system): """ Returns the numerical data of poles and zeros of the system. It is internally used by ``pole_zero_plot`` to get the data for plotting poles and zeros. Users can use this data to further analyse the dynamics of the system or plot using a different backend/plotting-module. Parameters ========== system : SISOLinearTimeInvariant The system for which the pole-zero data is to be computed. Returns ======= tuple : (zeros, poles) zeros = Zeros of the system. NumPy array of complex numbers. poles = Poles of the system. NumPy array of complex numbers. Raises ====== NotImplementedError When a SISO LTI system is not passed. When time delay terms are present in the system. ValueError When more than one free symbol is present in the system. The only variable in the transfer function should be the variable of the Laplace transform. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import pole_zero_numerical_data >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s) >>> pole_zero_numerical_data(tf1) # doctest: +SKIP ([-0.+1.j 0.-1.j], [-2. +0.j -0.5+0.8660254j -0.5-0.8660254j -1. +0.j ]) See Also ======== pole_zero_plot """ _check_system(system) system = system.doit() # Get the equivalent TransferFunction object. num_poly = Poly(system.num, system.var).all_coeffs() den_poly = Poly(system.den, system.var).all_coeffs() num_poly = np.array(num_poly, dtype=np.float64) den_poly = np.array(den_poly, dtype=np.float64) zeros = np.roots(num_poly) poles = np.roots(den_poly) return zeros, poles def pole_zero_plot(system, pole_color='blue', pole_markersize=10, zero_color='orange', zero_markersize=7, grid=True, show_axes=True, show=True, **kwargs): r""" Returns the Pole-Zero plot (also known as PZ Plot or PZ Map) of a system. A Pole-Zero plot is a graphical representation of a system's poles and zeros. It is plotted on a complex plane, with circular markers representing the system's zeros and 'x' shaped markers representing the system's poles. Parameters ========== system : SISOLinearTimeInvariant type systems The system for which the pole-zero plot is to be computed. pole_color : str, tuple, optional The color of the pole points on the plot. Default color is blue. The color can be provided as a matplotlib color string, or a 3-tuple of floats each in the 0-1 range. pole_markersize : Number, optional The size of the markers used to mark the poles in the plot. Default pole markersize is 10. zero_color : str, tuple, optional The color of the zero points on the plot. Default color is orange. The color can be provided as a matplotlib color string, or a 3-tuple of floats each in the 0-1 range. zero_markersize : Number, optional The size of the markers used to mark the zeros in the plot. Default zero markersize is 7. grid : boolean, optional If ``True``, the plot will have a grid. Defaults to True. show_axes : boolean, optional If ``True``, the coordinate axes will be shown. Defaults to False. show : boolean, optional If ``True``, the plot will be displayed otherwise the equivalent matplotlib ``plot`` object will be returned. Defaults to True. Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import pole_zero_plot >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s) >>> pole_zero_plot(tf1) # doctest: +SKIP See Also ======== pole_zero_numerical_data References ========== .. [1] https://en.wikipedia.org/wiki/Pole%E2%80%93zero_plot """ zeros, poles = pole_zero_numerical_data(system) zero_real = np.real(zeros) zero_imag = np.imag(zeros) pole_real = np.real(poles) pole_imag = np.imag(poles) plt.plot(pole_real, pole_imag, 'x', mfc='none', markersize=pole_markersize, color=pole_color) plt.plot(zero_real, zero_imag, 'o', markersize=zero_markersize, color=zero_color) plt.xlabel('Real Axis') plt.ylabel('Imaginary Axis') plt.title(f'Poles and Zeros of ${latex(system)}$', pad=20) if grid: plt.grid() if show_axes: plt.axhline(0, color='black') plt.axvline(0, color='black') if show: plt.show() return return plt def step_response_numerical_data(system, prec=8, lower_limit=0, upper_limit=10, **kwargs): """ Returns the numerical values of the points in the step response plot of a SISO continuous-time system. By default, adaptive sampling is used. If the user wants to instead get an uniformly sampled response, then ``adaptive`` kwarg should be passed ``False`` and ``nb_of_points`` must be passed as additional kwargs. Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries` for more details. Parameters ========== system : SISOLinearTimeInvariant The system for which the unit step response data is to be computed. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. kwargs : Additional keyword arguments are passed to the underlying :class:`sympy.plotting.plot.LineOver1DRangeSeries` class. Returns ======= tuple : (x, y) x = Time-axis values of the points in the step response. NumPy array. y = Amplitude-axis values of the points in the step response. NumPy array. Raises ====== NotImplementedError When a SISO LTI system is not passed. When time delay terms are present in the system. ValueError When more than one free symbol is present in the system. The only variable in the transfer function should be the variable of the Laplace transform. When ``lower_limit`` parameter is less than 0. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import step_response_numerical_data >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s) >>> step_response_numerical_data(tf1) # doctest: +SKIP ([0.0, 0.025413462339411542, 0.0484508722725343, ... , 9.670250533855183, 9.844291913708725, 10.0], [0.0, 0.023844582399907256, 0.042894276802320226, ..., 6.828770759094287e-12, 6.456457160755703e-12]) See Also ======== step_response_plot """ if lower_limit < 0: raise ValueError("Lower limit of time must be greater " "than or equal to zero.") _check_system(system) _x = Dummy("x") expr = system.to_expr()/(system.var) expr = apart(expr, system.var, full=True) _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec) return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit), **kwargs).get_points() def step_response_plot(system, color='b', prec=8, lower_limit=0, upper_limit=10, show_axes=False, grid=True, show=True, **kwargs): r""" Returns the unit step response of a continuous-time system. It is the response of the system when the input signal is a step function. Parameters ========== system : SISOLinearTimeInvariant type The LTI SISO system for which the Step Response is to be computed. color : str, tuple, optional The color of the line. Default is Blue. show : boolean, optional If ``True``, the plot will be displayed otherwise the equivalent matplotlib ``plot`` object will be returned. Defaults to True. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. show_axes : boolean, optional If ``True``, the coordinate axes will be shown. Defaults to False. grid : boolean, optional If ``True``, the plot will have a grid. Defaults to True. Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import step_response_plot >>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s) >>> step_response_plot(tf1) # doctest: +SKIP See Also ======== impulse_response_plot, ramp_response_plot References ========== .. [1] https://www.mathworks.com/help/control/ref/lti.step.html """ x, y = step_response_numerical_data(system, prec=prec, lower_limit=lower_limit, upper_limit=upper_limit, **kwargs) plt.plot(x, y, color=color) plt.xlabel('Time (s)') plt.ylabel('Amplitude') plt.title(f'Unit Step Response of ${latex(system)}$', pad=20) if grid: plt.grid() if show_axes: plt.axhline(0, color='black') plt.axvline(0, color='black') if show: plt.show() return return plt def impulse_response_numerical_data(system, prec=8, lower_limit=0, upper_limit=10, **kwargs): """ Returns the numerical values of the points in the impulse response plot of a SISO continuous-time system. By default, adaptive sampling is used. If the user wants to instead get an uniformly sampled response, then ``adaptive`` kwarg should be passed ``False`` and ``nb_of_points`` must be passed as additional kwargs. Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries` for more details. Parameters ========== system : SISOLinearTimeInvariant The system for which the impulse response data is to be computed. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. kwargs : Additional keyword arguments are passed to the underlying :class:`sympy.plotting.plot.LineOver1DRangeSeries` class. Returns ======= tuple : (x, y) x = Time-axis values of the points in the impulse response. NumPy array. y = Amplitude-axis values of the points in the impulse response. NumPy array. Raises ====== NotImplementedError When a SISO LTI system is not passed. When time delay terms are present in the system. ValueError When more than one free symbol is present in the system. The only variable in the transfer function should be the variable of the Laplace transform. When ``lower_limit`` parameter is less than 0. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import impulse_response_numerical_data >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s) >>> impulse_response_numerical_data(tf1) # doctest: +SKIP ([0.0, 0.06616480200395854,... , 9.854500743565858, 10.0], [0.9999999799999999, 0.7042848373025861,...,7.170748906965121e-13, -5.1901263495547205e-12]) See Also ======== impulse_response_plot """ if lower_limit < 0: raise ValueError("Lower limit of time must be greater " "than or equal to zero.") _check_system(system) _x = Dummy("x") expr = system.to_expr() expr = apart(expr, system.var, full=True) _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec) return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit), **kwargs).get_points() def impulse_response_plot(system, color='b', prec=8, lower_limit=0, upper_limit=10, show_axes=False, grid=True, show=True, **kwargs): r""" Returns the unit impulse response (Input is the Dirac-Delta Function) of a continuous-time system. Parameters ========== system : SISOLinearTimeInvariant type The LTI SISO system for which the Impulse Response is to be computed. color : str, tuple, optional The color of the line. Default is Blue. show : boolean, optional If ``True``, the plot will be displayed otherwise the equivalent matplotlib ``plot`` object will be returned. Defaults to True. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. show_axes : boolean, optional If ``True``, the coordinate axes will be shown. Defaults to False. grid : boolean, optional If ``True``, the plot will have a grid. Defaults to True. Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import impulse_response_plot >>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s) >>> impulse_response_plot(tf1) # doctest: +SKIP See Also ======== step_response_plot, ramp_response_plot References ========== .. [1] https://www.mathworks.com/help/control/ref/lti.impulse.html """ x, y = impulse_response_numerical_data(system, prec=prec, lower_limit=lower_limit, upper_limit=upper_limit, **kwargs) plt.plot(x, y, color=color) plt.xlabel('Time (s)') plt.ylabel('Amplitude') plt.title(f'Impulse Response of ${latex(system)}$', pad=20) if grid: plt.grid() if show_axes: plt.axhline(0, color='black') plt.axvline(0, color='black') if show: plt.show() return return plt def ramp_response_numerical_data(system, slope=1, prec=8, lower_limit=0, upper_limit=10, **kwargs): """ Returns the numerical values of the points in the ramp response plot of a SISO continuous-time system. By default, adaptive sampling is used. If the user wants to instead get an uniformly sampled response, then ``adaptive`` kwarg should be passed ``False`` and ``nb_of_points`` must be passed as additional kwargs. Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries` for more details. Parameters ========== system : SISOLinearTimeInvariant The system for which the ramp response data is to be computed. slope : Number, optional The slope of the input ramp function. Defaults to 1. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. kwargs : Additional keyword arguments are passed to the underlying :class:`sympy.plotting.plot.LineOver1DRangeSeries` class. Returns ======= tuple : (x, y) x = Time-axis values of the points in the ramp response plot. NumPy array. y = Amplitude-axis values of the points in the ramp response plot. NumPy array. Raises ====== NotImplementedError When a SISO LTI system is not passed. When time delay terms are present in the system. ValueError When more than one free symbol is present in the system. The only variable in the transfer function should be the variable of the Laplace transform. When ``lower_limit`` parameter is less than 0. When ``slope`` is negative. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import ramp_response_numerical_data >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s) >>> ramp_response_numerical_data(tf1) # doctest: +SKIP (([0.0, 0.12166980856813935,..., 9.861246379582118, 10.0], [1.4504508011325967e-09, 0.006046440489058766,..., 0.12499999999568202, 0.12499999999661349])) See Also ======== ramp_response_plot """ if slope < 0: raise ValueError("Slope must be greater than or equal" " to zero.") if lower_limit < 0: raise ValueError("Lower limit of time must be greater " "than or equal to zero.") _check_system(system) _x = Dummy("x") expr = (slope*system.to_expr())/((system.var)**2) expr = apart(expr, system.var, full=True) _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec) return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit), **kwargs).get_points() def ramp_response_plot(system, slope=1, color='b', prec=8, lower_limit=0, upper_limit=10, show_axes=False, grid=True, show=True, **kwargs): r""" Returns the ramp response of a continuous-time system. Ramp function is defined as the straight line passing through origin ($f(x) = mx$). The slope of the ramp function can be varied by the user and the default value is 1. Parameters ========== system : SISOLinearTimeInvariant type The LTI SISO system for which the Ramp Response is to be computed. slope : Number, optional The slope of the input ramp function. Defaults to 1. color : str, tuple, optional The color of the line. Default is Blue. show : boolean, optional If ``True``, the plot will be displayed otherwise the equivalent matplotlib ``plot`` object will be returned. Defaults to True. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. show_axes : boolean, optional If ``True``, the coordinate axes will be shown. Defaults to False. grid : boolean, optional If ``True``, the plot will have a grid. Defaults to True. Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import ramp_response_plot >>> tf1 = TransferFunction(s, (s+4)*(s+8), s) >>> ramp_response_plot(tf1, upper_limit=2) # doctest: +SKIP See Also ======== step_response_plot, ramp_response_plot References ========== .. [1] https://en.wikipedia.org/wiki/Ramp_function """ x, y = ramp_response_numerical_data(system, slope=slope, prec=prec, lower_limit=lower_limit, upper_limit=upper_limit, **kwargs) plt.plot(x, y, color=color) plt.xlabel('Time (s)') plt.ylabel('Amplitude') plt.title(f'Ramp Response of ${latex(system)}$ [Slope = {slope}]', pad=20) if grid: plt.grid() if show_axes: plt.axhline(0, color='black') plt.axvline(0, color='black') if show: plt.show() return return plt def bode_magnitude_numerical_data(system, initial_exp=-5, final_exp=5, **kwargs): """ Returns the numerical data of the Bode magnitude plot of the system. It is internally used by ``bode_magnitude_plot`` to get the data for plotting Bode magnitude plot. Users can use this data to further analyse the dynamics of the system or plot using a different backend/plotting-module. Parameters ========== system : SISOLinearTimeInvariant The system for which the data is to be computed. initial_exp : Number, optional The initial exponent of 10 of the semilog plot. Defaults to -5. final_exp : Number, optional The final exponent of 10 of the semilog plot. Defaults to 5. Returns ======= tuple : (x, y) x = x-axis values of the Bode magnitude plot. y = y-axis values of the Bode magnitude plot. Raises ====== NotImplementedError When a SISO LTI system is not passed. When time delay terms are present in the system. ValueError When more than one free symbol is present in the system. The only variable in the transfer function should be the variable of the Laplace transform. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import bode_magnitude_numerical_data >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s) >>> bode_magnitude_numerical_data(tf1) # doctest: +SKIP ([1e-05, 1.5148378120533502e-05,..., 68437.36188804005, 100000.0], [-6.020599914256786, -6.0205999155219505,..., -193.4117304087953, -200.00000000260573]) See Also ======== bode_magnitude_plot, bode_phase_numerical_data """ _check_system(system) expr = system.to_expr() _w = Dummy("w", real=True) w_expr = expr.subs({system.var: I*_w}) mag = 20*log(Abs(w_expr), 10) return LineOver1DRangeSeries(mag, (_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points() def bode_magnitude_plot(system, initial_exp=-5, final_exp=5, color='b', show_axes=False, grid=True, show=True, **kwargs): r""" Returns the Bode magnitude plot of a continuous-time system. See ``bode_plot`` for all the parameters. """ x, y = bode_magnitude_numerical_data(system, initial_exp=initial_exp, final_exp=final_exp) plt.plot(x, y, color=color, **kwargs) plt.xscale('log') plt.xlabel('Frequency (Hz) [Log Scale]') plt.ylabel('Magnitude (dB)') plt.title(f'Bode Plot (Magnitude) of ${latex(system)}$', pad=20) if grid: plt.grid(True) if show_axes: plt.axhline(0, color='black') plt.axvline(0, color='black') if show: plt.show() return return plt def bode_phase_numerical_data(system, initial_exp=-5, final_exp=5, **kwargs): """ Returns the numerical data of the Bode phase plot of the system. It is internally used by ``bode_phase_plot`` to get the data for plotting Bode phase plot. Users can use this data to further analyse the dynamics of the system or plot using a different backend/plotting-module. Parameters ========== system : SISOLinearTimeInvariant The system for which the Bode phase plot data is to be computed. initial_exp : Number, optional The initial exponent of 10 of the semilog plot. Defaults to -5. final_exp : Number, optional The final exponent of 10 of the semilog plot. Defaults to 5. Returns ======= tuple : (x, y) x = x-axis values of the Bode phase plot. y = y-axis values of the Bode phase plot. Raises ====== NotImplementedError When a SISO LTI system is not passed. When time delay terms are present in the system. ValueError When more than one free symbol is present in the system. The only variable in the transfer function should be the variable of the Laplace transform. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import bode_phase_numerical_data >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s) >>> bode_phase_numerical_data(tf1) # doctest: +SKIP ([1e-05, 1.4472354033813751e-05, 2.035581932165858e-05,..., 47577.3248186011, 67884.09326036123, 100000.0], [-2.5000000000291665e-05, -3.6180885085e-05, -5.08895483066e-05,...,-3.1415085799262523, -3.14155265358979]) See Also ======== bode_magnitude_plot, bode_phase_numerical_data """ _check_system(system) expr = system.to_expr() _w = Dummy("w", real=True) w_expr = expr.subs({system.var: I*_w}) phase = arg(w_expr) return LineOver1DRangeSeries(phase, (_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points() def bode_phase_plot(system, initial_exp=-5, final_exp=5, color='b', show_axes=False, grid=True, show=True, **kwargs): r""" Returns the Bode phase plot of a continuous-time system. See ``bode_plot`` for all the parameters. """ x, y = bode_phase_numerical_data(system, initial_exp=initial_exp, final_exp=final_exp) plt.plot(x, y, color=color, **kwargs) plt.xscale('log') plt.xlabel('Frequency (Hz) [Log Scale]') plt.ylabel('Phase (rad)') plt.title(f'Bode Plot (Phase) of ${latex(system)}$', pad=20) if grid: plt.grid(True) if show_axes: plt.axhline(0, color='black') plt.axvline(0, color='black') if show: plt.show() return return plt def bode_plot(system, initial_exp=-5, final_exp=5, grid=True, show_axes=False, show=True, **kwargs): r""" Returns the Bode phase and magnitude plots of a continuous-time system. Parameters ========== system : SISOLinearTimeInvariant type The LTI SISO system for which the Bode Plot is to be computed. initial_exp : Number, optional The initial exponent of 10 of the semilog plot. Defaults to -5. final_exp : Number, optional The final exponent of 10 of the semilog plot. Defaults to 5. show : boolean, optional If ``True``, the plot will be displayed otherwise the equivalent matplotlib ``plot`` object will be returned. Defaults to True. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. grid : boolean, optional If ``True``, the plot will have a grid. Defaults to True. show_axes : boolean, optional If ``True``, the coordinate axes will be shown. Defaults to False. Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import bode_plot >>> tf1 = TransferFunction(1*s**2 + 0.1*s + 7.5, 1*s**4 + 0.12*s**3 + 9*s**2, s) >>> bode_plot(tf1, initial_exp=0.2, final_exp=0.7) # doctest: +SKIP See Also ======== bode_magnitude_plot, bode_phase_plot """ plt.subplot(211) bode_magnitude_plot(system, initial_exp=initial_exp, final_exp=final_exp, show=False, grid=grid, show_axes=show_axes, **kwargs).title(f'Bode Plot of ${latex(system)}$', pad=20) plt.subplot(212) bode_phase_plot(system, initial_exp=initial_exp, final_exp=final_exp, show=False, grid=grid, show_axes=show_axes, **kwargs).title(None) if show: plt.show() return return plt
0f426fe80fde8284e1a261f31a1337f61ecaa0c7c9e4b9bbbaa97c48a01ef837
from sympy.core.backend import Symbol from sympy.physics.vector import Point, Vector, ReferenceFrame from sympy.physics.mechanics import RigidBody, Particle, inertia __all__ = ['Body'] # XXX: We use type:ignore because the classes RigidBody and Particle have # inconsistent parallel axis methods that take different numbers of arguments. class Body(RigidBody, Particle): # type: ignore """ Body is a common representation of either a RigidBody or a Particle SymPy object depending on what is passed in during initialization. If a mass is passed in and central_inertia is left as None, the Particle object is created. Otherwise a RigidBody object will be created. Explanation =========== The attributes that Body possesses will be the same as a Particle instance or a Rigid Body instance depending on which was created. Additional attributes are listed below. Attributes ========== name : string The body's name masscenter : Point The point which represents the center of mass of the rigid body frame : ReferenceFrame The reference frame which the body is fixed in mass : Sympifyable The body's mass inertia : (Dyadic, Point) The body's inertia around its center of mass. This attribute is specific to the rigid body form of Body and is left undefined for the Particle form loads : iterable This list contains information on the different loads acting on the Body. Forces are listed as a (point, vector) tuple and torques are listed as (reference frame, vector) tuples. Parameters ========== name : String Defines the name of the body. It is used as the base for defining body specific properties. masscenter : Point, optional A point that represents the center of mass of the body or particle. If no point is given, a point is generated. mass : Sympifyable, optional A Sympifyable object which represents the mass of the body. If no mass is passed, one is generated. frame : ReferenceFrame, optional The ReferenceFrame that represents the reference frame of the body. If no frame is given, a frame is generated. central_inertia : Dyadic, optional Central inertia dyadic of the body. If none is passed while creating RigidBody, a default inertia is generated. Examples ======== Default behaviour. This results in the creation of a RigidBody object for which the mass, mass center, frame and inertia attributes are given default values. :: >>> from sympy.physics.mechanics import Body >>> body = Body('name_of_body') This next example demonstrates the code required to specify all of the values of the Body object. Note this will also create a RigidBody version of the Body object. :: >>> from sympy import Symbol >>> from sympy.physics.mechanics import ReferenceFrame, Point, inertia >>> from sympy.physics.mechanics import Body >>> mass = Symbol('mass') >>> masscenter = Point('masscenter') >>> frame = ReferenceFrame('frame') >>> ixx = Symbol('ixx') >>> body_inertia = inertia(frame, ixx, 0, 0) >>> body = Body('name_of_body', masscenter, mass, frame, body_inertia) The minimal code required to create a Particle version of the Body object involves simply passing in a name and a mass. :: >>> from sympy import Symbol >>> from sympy.physics.mechanics import Body >>> mass = Symbol('mass') >>> body = Body('name_of_body', mass=mass) The Particle version of the Body object can also receive a masscenter point and a reference frame, just not an inertia. """ def __init__(self, name, masscenter=None, mass=None, frame=None, central_inertia=None): self.name = name self._loads = [] if frame is None: frame = ReferenceFrame(name + '_frame') if masscenter is None: masscenter = Point(name + '_masscenter') if central_inertia is None and mass is None: ixx = Symbol(name + '_ixx') iyy = Symbol(name + '_iyy') izz = Symbol(name + '_izz') izx = Symbol(name + '_izx') ixy = Symbol(name + '_ixy') iyz = Symbol(name + '_iyz') _inertia = (inertia(frame, ixx, iyy, izz, ixy, iyz, izx), masscenter) else: _inertia = (central_inertia, masscenter) if mass is None: _mass = Symbol(name + '_mass') else: _mass = mass masscenter.set_vel(frame, 0) # If user passes masscenter and mass then a particle is created # otherwise a rigidbody. As a result a body may or may not have inertia. if central_inertia is None and mass is not None: self.frame = frame self.masscenter = masscenter Particle.__init__(self, name, masscenter, _mass) self._central_inertia = None else: RigidBody.__init__(self, name, masscenter, frame, _mass, _inertia) @property def loads(self): return self._loads @property def x(self): """The basis Vector for the Body, in the x direction. """ return self.frame.x @property def y(self): """The basis Vector for the Body, in the y direction. """ return self.frame.y @property def z(self): """The basis Vector for the Body, in the z direction. """ return self.frame.z @property def is_rigidbody(self): if self.central_inertia is not None: return True return False def kinetic_energy(self, frame): """Kinetic energy of the body. Parameters ========== frame : ReferenceFrame or Body The Body's angular velocity and the velocity of it's mass center are typically defined with respect to an inertial frame but any relevant frame in which the velocities are known can be supplied. Examples ======== >>> from sympy.physics.mechanics import Body, ReferenceFrame, Point >>> from sympy import symbols >>> m, v, r, omega = symbols('m v r omega') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> P = Body('P', masscenter=O, mass=m) >>> P.masscenter.set_vel(N, v * N.y) >>> P.kinetic_energy(N) m*v**2/2 >>> N = ReferenceFrame('N') >>> b = ReferenceFrame('b') >>> b.set_ang_vel(N, omega * b.x) >>> P = Point('P') >>> P.set_vel(N, v * N.x) >>> B = Body('B', masscenter=P, frame=b) >>> B.kinetic_energy(N) B_ixx*omega**2/2 + B_mass*v**2/2 See Also ======== sympy.physics.mechanics : Particle, RigidBody """ if isinstance(frame, Body): frame = Body.frame if self.is_rigidbody: return RigidBody(self.name, self.masscenter, self.frame, self.mass, (self.central_inertia, self.masscenter)).kinetic_energy(frame) return Particle(self.name, self.masscenter, self.mass).kinetic_energy(frame) def apply_force(self, force, point=None, reaction_body=None, reaction_point=None): """Add force to the body(s). Explanation =========== Applies the force on self or equal and oppposite forces on self and other body if both are given on the desried point on the bodies. The force applied on other body is taken opposite of self, i.e, -force. Parameters ========== force: Vector The force to be applied. point: Point, optional The point on self on which force is applied. By default self's masscenter. reaction_body: Body, optional Second body on which equal and opposite force is to be applied. reaction_point : Point, optional The point on other body on which equal and opposite force is applied. By default masscenter of other body. Example ======= >>> from sympy import symbols >>> from sympy.physics.mechanics import Body, Point, dynamicsymbols >>> m, g = symbols('m g') >>> B = Body('B') >>> force1 = m*g*B.z >>> B.apply_force(force1) #Applying force on B's masscenter >>> B.loads [(B_masscenter, g*m*B_frame.z)] We can also remove some part of force from any point on the body by adding the opposite force to the body on that point. >>> f1, f2 = dynamicsymbols('f1 f2') >>> P = Point('P') #Considering point P on body B >>> B.apply_force(f1*B.x + f2*B.y, P) >>> B.loads [(B_masscenter, g*m*B_frame.z), (P, f1(t)*B_frame.x + f2(t)*B_frame.y)] Let's remove f1 from point P on body B. >>> B.apply_force(-f1*B.x, P) >>> B.loads [(B_masscenter, g*m*B_frame.z), (P, f2(t)*B_frame.y)] To further demonstrate the use of ``apply_force`` attribute, consider two bodies connected through a spring. >>> from sympy.physics.mechanics import Body, dynamicsymbols >>> N = Body('N') #Newtonion Frame >>> x = dynamicsymbols('x') >>> B1 = Body('B1') >>> B2 = Body('B2') >>> spring_force = x*N.x Now let's apply equal and opposite spring force to the bodies. >>> P1 = Point('P1') >>> P2 = Point('P2') >>> B1.apply_force(spring_force, point=P1, reaction_body=B2, reaction_point=P2) We can check the loads(forces) applied to bodies now. >>> B1.loads [(P1, x(t)*N_frame.x)] >>> B2.loads [(P2, - x(t)*N_frame.x)] Notes ===== If a new force is applied to a body on a point which already has some force applied on it, then the new force is added to the already applied force on that point. """ if not isinstance(point, Point): if point is None: point = self.masscenter # masscenter else: raise TypeError("Force must be applied to a point on the body.") if not isinstance(force, Vector): raise TypeError("Force must be a vector.") if reaction_body is not None: reaction_body.apply_force(-force, point=reaction_point) for load in self._loads: if point in load: force += load[1] self._loads.remove(load) break self._loads.append((point, force)) def apply_torque(self, torque, reaction_body=None): """Add torque to the body(s). Explanation =========== Applies the torque on self or equal and oppposite torquess on self and other body if both are given. The torque applied on other body is taken opposite of self, i.e, -torque. Parameters ========== torque: Vector The torque to be applied. reaction_body: Body, optional Second body on which equal and opposite torque is to be applied. Example ======= >>> from sympy import symbols >>> from sympy.physics.mechanics import Body, dynamicsymbols >>> t = symbols('t') >>> B = Body('B') >>> torque1 = t*B.z >>> B.apply_torque(torque1) >>> B.loads [(B_frame, t*B_frame.z)] We can also remove some part of torque from the body by adding the opposite torque to the body. >>> t1, t2 = dynamicsymbols('t1 t2') >>> B.apply_torque(t1*B.x + t2*B.y) >>> B.loads [(B_frame, t1(t)*B_frame.x + t2(t)*B_frame.y + t*B_frame.z)] Let's remove t1 from Body B. >>> B.apply_torque(-t1*B.x) >>> B.loads [(B_frame, t2(t)*B_frame.y + t*B_frame.z)] To further demonstrate the use, let us consider two bodies such that a torque `T` is acting on one body, and `-T` on the other. >>> from sympy.physics.mechanics import Body, dynamicsymbols >>> N = Body('N') #Newtonion frame >>> B1 = Body('B1') >>> B2 = Body('B2') >>> v = dynamicsymbols('v') >>> T = v*N.y #Torque Now let's apply equal and opposite torque to the bodies. >>> B1.apply_torque(T, B2) We can check the loads (torques) applied to bodies now. >>> B1.loads [(B1_frame, v(t)*N_frame.y)] >>> B2.loads [(B2_frame, - v(t)*N_frame.y)] Notes ===== If a new torque is applied on body which already has some torque applied on it, then the new torque is added to the previous torque about the body's frame. """ if not isinstance(torque, Vector): raise TypeError("A Vector must be supplied to add torque.") if reaction_body is not None: reaction_body.apply_torque(-torque) for load in self._loads: if self.frame in load: torque += load[1] self._loads.remove(load) break self._loads.append((self.frame, torque)) def clear_loads(self): """ Clears the Body's loads list. Example ======= >>> from sympy.physics.mechanics import Body >>> B = Body('B') >>> force = B.x + B.y >>> B.apply_force(force) >>> B.loads [(B_masscenter, B_frame.x + B_frame.y)] >>> B.clear_loads() >>> B.loads [] """ self._loads = [] def remove_load(self, about=None): """ Remove load about a point or frame. Parameters ========== about : Point or ReferenceFrame, optional The point about which force is applied, and is to be removed. If about is None, then the torque about self's frame is removed. Example ======= >>> from sympy.physics.mechanics import Body, Point >>> B = Body('B') >>> P = Point('P') >>> f1 = B.x >>> f2 = B.y >>> B.apply_force(f1) >>> B.apply_force(f2, P) >>> B.loads [(B_masscenter, B_frame.x), (P, B_frame.y)] >>> B.remove_load(P) >>> B.loads [(B_masscenter, B_frame.x)] """ if about is not None: if not isinstance(about, Point): raise TypeError('Load is applied about Point or ReferenceFrame.') else: about = self.frame for load in self._loads: if about in load: self._loads.remove(load) break def masscenter_vel(self, body): """ Returns the velocity of the mass center with respect to the provided rigid body or reference frame. Parameters ========== body: Body or ReferenceFrame The rigid body or reference frame to calculate the velocity in. Example ======= >>> from sympy.physics.mechanics import Body >>> A = Body('A') >>> B = Body('B') >>> A.masscenter.set_vel(B.frame, 5*B.frame.x) >>> A.masscenter_vel(B) 5*B_frame.x >>> A.masscenter_vel(B.frame) 5*B_frame.x """ if isinstance(body, ReferenceFrame): frame=body elif isinstance(body, Body): frame = body.frame return self.masscenter.vel(frame) def ang_vel_in(self, body): """ Returns this body's angular velocity with respect to the provided rigid body or reference frame. Parameters ========== body: Body or ReferenceFrame The rigid body or reference frame to calculate the angular velocity in. Example ======= >>> from sympy.physics.mechanics import Body, ReferenceFrame >>> A = Body('A') >>> N = ReferenceFrame('N') >>> B = Body('B', frame=N) >>> A.frame.set_ang_vel(N, 5*N.x) >>> A.ang_vel_in(B) 5*N.x >>> A.ang_vel_in(N) 5*N.x """ if isinstance(body, ReferenceFrame): frame=body elif isinstance(body, Body): frame = body.frame return self.frame.ang_vel_in(frame) def dcm(self, body): """ Returns the direction cosine matrix of this body relative to the provided rigid body or reference frame. Parameters ========== body: Body or ReferenceFrame The rigid body or reference frame to calculate the dcm. Example ======= >>> from sympy.physics.mechanics import Body >>> A = Body('A') >>> B = Body('B') >>> A.frame.orient_axis(B.frame, B.frame.x, 5) >>> A.dcm(B) Matrix([ [1, 0, 0], [0, cos(5), sin(5)], [0, -sin(5), cos(5)]]) >>> A.dcm(B.frame) Matrix([ [1, 0, 0], [0, cos(5), sin(5)], [0, -sin(5), cos(5)]]) """ if isinstance(body, ReferenceFrame): frame=body elif isinstance(body, Body): frame = body.frame return self.frame.dcm(frame)
1526356b6516ce1567fecba6906ddc2e65d13e633688393a0d4f1012f2cfb62a
__all__ = [ 'vector', 'CoordinateSym', 'ReferenceFrame', 'Dyadic', 'Vector', 'Point', 'cross', 'dot', 'express', 'time_derivative', 'outer', 'kinematic_equations', 'get_motion_params', 'partial_velocity', 'dynamicsymbols', 'vprint', 'vsstrrepr', 'vsprint', 'vpprint', 'vlatex', 'init_vprinting', 'curl', 'divergence', 'gradient', 'is_conservative', 'is_solenoidal', 'scalar_potential', 'scalar_potential_difference', 'KanesMethod', 'RigidBody', 'inertia', 'inertia_of_point_mass', 'linear_momentum', 'angular_momentum', 'kinetic_energy', 'potential_energy', 'Lagrangian', 'mechanics_printing', 'mprint', 'msprint', 'mpprint', 'mlatex', 'msubs', 'find_dynamicsymbols', 'Particle', 'LagrangesMethod', 'Linearizer', 'Body', 'SymbolicSystem', 'PinJoint', 'PrismaticJoint', 'JointsMethod' ] from sympy.physics import vector from sympy.physics.vector import (CoordinateSym, ReferenceFrame, Dyadic, Vector, Point, cross, dot, express, time_derivative, outer, kinematic_equations, get_motion_params, partial_velocity, dynamicsymbols, vprint, vsstrrepr, vsprint, vpprint, vlatex, init_vprinting, curl, divergence, gradient, is_conservative, is_solenoidal, scalar_potential, scalar_potential_difference) from .kane import KanesMethod from .rigidbody import RigidBody from .functions import (inertia, inertia_of_point_mass, linear_momentum, angular_momentum, kinetic_energy, potential_energy, Lagrangian, mechanics_printing, mprint, msprint, mpprint, mlatex, msubs, find_dynamicsymbols) from .particle import Particle from .lagrange import LagrangesMethod from .linearize import Linearizer from .body import Body from .system import SymbolicSystem from .jointsmethod import JointsMethod from .joint import PinJoint, PrismaticJoint
c69bddd2b66f454c8ef41f936525cd3938873fcc5833795587b300f6cd3bc4fa
from sympy.core.backend import zeros, Matrix, diff, eye from sympy import solve_linear_system_LU from sympy.utilities import default_sort_key from sympy.physics.vector import (ReferenceFrame, dynamicsymbols, partial_velocity) from sympy.physics.mechanics.method import _Methods from sympy.physics.mechanics.particle import Particle from sympy.physics.mechanics.rigidbody import RigidBody from sympy.physics.mechanics.functions import (msubs, find_dynamicsymbols, _f_list_parser) from sympy.physics.mechanics.linearize import Linearizer from sympy.utilities.iterables import iterable __all__ = ['KanesMethod'] class KanesMethod(_Methods): """Kane's method object. Explanation =========== This object is used to do the "book-keeping" as you go through and form equations of motion in the way Kane presents in: Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill The attributes are for equations in the form [M] udot = forcing. Attributes ========== q, u : Matrix Matrices of the generalized coordinates and speeds bodies : iterable Iterable of Point and RigidBody objects in the system. loads : iterable Iterable of (Point, vector) or (ReferenceFrame, vector) tuples describing the forces on the system. auxiliary : Matrix If applicable, the set of auxiliary Kane's equations used to solve for non-contributing forces. mass_matrix : Matrix The system's mass matrix forcing : Matrix The system's forcing vector mass_matrix_full : Matrix The "mass matrix" for the u's and q's forcing_full : Matrix The "forcing vector" for the u's and q's Examples ======== This is a simple example for a one degree of freedom translational spring-mass-damper. In this example, we first need to do the kinematics. This involves creating generalized speeds and coordinates and their derivatives. Then we create a point and set its velocity in a frame. >>> from sympy import symbols >>> from sympy.physics.mechanics import dynamicsymbols, ReferenceFrame >>> from sympy.physics.mechanics import Point, Particle, KanesMethod >>> q, u = dynamicsymbols('q u') >>> qd, ud = dynamicsymbols('q u', 1) >>> m, c, k = symbols('m c k') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, u * N.x) Next we need to arrange/store information in the way that KanesMethod requires. The kinematic differential equations need to be stored in a dict. A list of forces/torques must be constructed, where each entry in the list is a (Point, Vector) or (ReferenceFrame, Vector) tuple, where the Vectors represent the Force or Torque. Next a particle needs to be created, and it needs to have a point and mass assigned to it. Finally, a list of all bodies and particles needs to be created. >>> kd = [qd - u] >>> FL = [(P, (-k * q - c * u) * N.x)] >>> pa = Particle('pa', P, m) >>> BL = [pa] Finally we can generate the equations of motion. First we create the KanesMethod object and supply an inertial frame, coordinates, generalized speeds, and the kinematic differential equations. Additional quantities such as configuration and motion constraints, dependent coordinates and speeds, and auxiliary speeds are also supplied here (see the online documentation). Next we form FR* and FR to complete: Fr + Fr* = 0. We have the equations of motion at this point. It makes sense to rearrange them though, so we calculate the mass matrix and the forcing terms, for E.o.M. in the form: [MM] udot = forcing, where MM is the mass matrix, udot is a vector of the time derivatives of the generalized speeds, and forcing is a vector representing "forcing" terms. >>> KM = KanesMethod(N, q_ind=[q], u_ind=[u], kd_eqs=kd) >>> (fr, frstar) = KM.kanes_equations(BL, FL) >>> MM = KM.mass_matrix >>> forcing = KM.forcing >>> rhs = MM.inv() * forcing >>> rhs Matrix([[(-c*u(t) - k*q(t))/m]]) >>> KM.linearize(A_and_B=True)[0] Matrix([ [ 0, 1], [-k/m, -c/m]]) Please look at the documentation pages for more information on how to perform linearization and how to deal with dependent coordinates & speeds, and how do deal with bringing non-contributing forces into evidence. """ def __init__(self, frame, q_ind, u_ind, kd_eqs=None, q_dependent=None, configuration_constraints=None, u_dependent=None, velocity_constraints=None, acceleration_constraints=None, u_auxiliary=None, bodies=None, forcelist=None): """Please read the online documentation. """ if not q_ind: q_ind = [dynamicsymbols('dummy_q')] kd_eqs = [dynamicsymbols('dummy_kd')] if not isinstance(frame, ReferenceFrame): raise TypeError('An inertial ReferenceFrame must be supplied') self._inertial = frame self._fr = None self._frstar = None self._forcelist = forcelist self._bodylist = bodies self._initialize_vectors(q_ind, q_dependent, u_ind, u_dependent, u_auxiliary) self._initialize_kindiffeq_matrices(kd_eqs) self._initialize_constraint_matrices(configuration_constraints, velocity_constraints, acceleration_constraints) def _initialize_vectors(self, q_ind, q_dep, u_ind, u_dep, u_aux): """Initialize the coordinate and speed vectors.""" none_handler = lambda x: Matrix(x) if x else Matrix() # Initialize generalized coordinates q_dep = none_handler(q_dep) if not iterable(q_ind): raise TypeError('Generalized coordinates must be an iterable.') if not iterable(q_dep): raise TypeError('Dependent coordinates must be an iterable.') q_ind = Matrix(q_ind) self._qdep = q_dep self._q = Matrix([q_ind, q_dep]) self._qdot = self.q.diff(dynamicsymbols._t) # Initialize generalized speeds u_dep = none_handler(u_dep) if not iterable(u_ind): raise TypeError('Generalized speeds must be an iterable.') if not iterable(u_dep): raise TypeError('Dependent speeds must be an iterable.') u_ind = Matrix(u_ind) self._udep = u_dep self._u = Matrix([u_ind, u_dep]) self._udot = self.u.diff(dynamicsymbols._t) self._uaux = none_handler(u_aux) def _initialize_constraint_matrices(self, config, vel, acc): """Initializes constraint matrices.""" # Define vector dimensions o = len(self.u) m = len(self._udep) p = o - m none_handler = lambda x: Matrix(x) if x else Matrix() # Initialize configuration constraints config = none_handler(config) if len(self._qdep) != len(config): raise ValueError('There must be an equal number of dependent ' 'coordinates and configuration constraints.') self._f_h = none_handler(config) # Initialize velocity and acceleration constraints vel = none_handler(vel) acc = none_handler(acc) if len(vel) != m: raise ValueError('There must be an equal number of dependent ' 'speeds and velocity constraints.') if acc and (len(acc) != m): raise ValueError('There must be an equal number of dependent ' 'speeds and acceleration constraints.') if vel: u_zero = {i: 0 for i in self.u} udot_zero = {i: 0 for i in self._udot} # When calling kanes_equations, another class instance will be # created if auxiliary u's are present. In this case, the # computation of kinetic differential equation matrices will be # skipped as this was computed during the original KanesMethod # object, and the qd_u_map will not be available. if self._qdot_u_map is not None: vel = msubs(vel, self._qdot_u_map) self._f_nh = msubs(vel, u_zero) self._k_nh = (vel - self._f_nh).jacobian(self.u) # If no acceleration constraints given, calculate them. if not acc: _f_dnh = (self._k_nh.diff(dynamicsymbols._t) * self.u + self._f_nh.diff(dynamicsymbols._t)) if self._qdot_u_map is not None: _f_dnh = msubs(_f_dnh, self._qdot_u_map) self._f_dnh = _f_dnh self._k_dnh = self._k_nh else: if self._qdot_u_map is not None: acc = msubs(acc, self._qdot_u_map) self._f_dnh = msubs(acc, udot_zero) self._k_dnh = (acc - self._f_dnh).jacobian(self._udot) # Form of non-holonomic constraints is B*u + C = 0. # We partition B into independent and dependent columns: # Ars is then -B_dep.inv() * B_ind, and it relates dependent speeds # to independent speeds as: udep = Ars*uind, neglecting the C term. B_ind = self._k_nh[:, :p] B_dep = self._k_nh[:, p:o] self._Ars = -B_dep.LUsolve(B_ind) else: self._f_nh = Matrix() self._k_nh = Matrix() self._f_dnh = Matrix() self._k_dnh = Matrix() self._Ars = Matrix() def _initialize_kindiffeq_matrices(self, kdeqs): """Initialize the kinematic differential equation matrices.""" if kdeqs: if len(self.q) != len(kdeqs): raise ValueError('There must be an equal number of kinematic ' 'differential equations and coordinates.') kdeqs = Matrix(kdeqs) u = self.u qdot = self._qdot # Dictionaries setting things to zero u_zero = {i: 0 for i in u} uaux_zero = {i: 0 for i in self._uaux} qdot_zero = {i: 0 for i in qdot} f_k = msubs(kdeqs, u_zero, qdot_zero) k_ku = (msubs(kdeqs, qdot_zero) - f_k).jacobian(u) k_kqdot = (msubs(kdeqs, u_zero) - f_k).jacobian(qdot) f_k = k_kqdot.LUsolve(f_k) k_ku = k_kqdot.LUsolve(k_ku) k_kqdot = eye(len(qdot)) self._qdot_u_map = solve_linear_system_LU( Matrix([k_kqdot.T, -(k_ku * u + f_k).T]).T, qdot) self._f_k = msubs(f_k, uaux_zero) self._k_ku = msubs(k_ku, uaux_zero) self._k_kqdot = k_kqdot else: self._qdot_u_map = None self._f_k = Matrix() self._k_ku = Matrix() self._k_kqdot = Matrix() def _form_fr(self, fl): """Form the generalized active force.""" if fl is not None and (len(fl) == 0 or not iterable(fl)): raise ValueError('Force pairs must be supplied in an ' 'non-empty iterable or None.') N = self._inertial # pull out relevant velocities for constructing partial velocities vel_list, f_list = _f_list_parser(fl, N) vel_list = [msubs(i, self._qdot_u_map) for i in vel_list] f_list = [msubs(i, self._qdot_u_map) for i in f_list] # Fill Fr with dot product of partial velocities and forces o = len(self.u) b = len(f_list) FR = zeros(o, 1) partials = partial_velocity(vel_list, self.u, N) for i in range(o): FR[i] = sum(partials[j][i] & f_list[j] for j in range(b)) # In case there are dependent speeds if self._udep: p = o - len(self._udep) FRtilde = FR[:p, 0] FRold = FR[p:o, 0] FRtilde += self._Ars.T * FRold FR = FRtilde self._forcelist = fl self._fr = FR return FR def _form_frstar(self, bl): """Form the generalized inertia force.""" if not iterable(bl): raise TypeError('Bodies must be supplied in an iterable.') t = dynamicsymbols._t N = self._inertial # Dicts setting things to zero udot_zero = {i: 0 for i in self._udot} uaux_zero = {i: 0 for i in self._uaux} uauxdot = [diff(i, t) for i in self._uaux] uauxdot_zero = {i: 0 for i in uauxdot} # Dictionary of q' and q'' to u and u' q_ddot_u_map = {k.diff(t): v.diff(t) for (k, v) in self._qdot_u_map.items()} q_ddot_u_map.update(self._qdot_u_map) # Fill up the list of partials: format is a list with num elements # equal to number of entries in body list. Each of these elements is a # list - either of length 1 for the translational components of # particles or of length 2 for the translational and rotational # components of rigid bodies. The inner most list is the list of # partial velocities. def get_partial_velocity(body): if isinstance(body, RigidBody): vlist = [body.masscenter.vel(N), body.frame.ang_vel_in(N)] elif isinstance(body, Particle): vlist = [body.point.vel(N),] else: raise TypeError('The body list may only contain either ' 'RigidBody or Particle as list elements.') v = [msubs(vel, self._qdot_u_map) for vel in vlist] return partial_velocity(v, self.u, N) partials = [get_partial_velocity(body) for body in bl] # Compute fr_star in two components: # fr_star = -(MM*u' + nonMM) o = len(self.u) MM = zeros(o, o) nonMM = zeros(o, 1) zero_uaux = lambda expr: msubs(expr, uaux_zero) zero_udot_uaux = lambda expr: msubs(msubs(expr, udot_zero), uaux_zero) for i, body in enumerate(bl): if isinstance(body, RigidBody): M = zero_uaux(body.mass) I = zero_uaux(body.central_inertia) vel = zero_uaux(body.masscenter.vel(N)) omega = zero_uaux(body.frame.ang_vel_in(N)) acc = zero_udot_uaux(body.masscenter.acc(N)) inertial_force = (M.diff(t) * vel + M * acc) inertial_torque = zero_uaux((I.dt(body.frame) & omega) + msubs(I & body.frame.ang_acc_in(N), udot_zero) + (omega ^ (I & omega))) for j in range(o): tmp_vel = zero_uaux(partials[i][0][j]) tmp_ang = zero_uaux(I & partials[i][1][j]) for k in range(o): # translational MM[j, k] += M * (tmp_vel & partials[i][0][k]) # rotational MM[j, k] += (tmp_ang & partials[i][1][k]) nonMM[j] += inertial_force & partials[i][0][j] nonMM[j] += inertial_torque & partials[i][1][j] else: M = zero_uaux(body.mass) vel = zero_uaux(body.point.vel(N)) acc = zero_udot_uaux(body.point.acc(N)) inertial_force = (M.diff(t) * vel + M * acc) for j in range(o): temp = zero_uaux(partials[i][0][j]) for k in range(o): MM[j, k] += M * (temp & partials[i][0][k]) nonMM[j] += inertial_force & partials[i][0][j] # Compose fr_star out of MM and nonMM MM = zero_uaux(msubs(MM, q_ddot_u_map)) nonMM = msubs(msubs(nonMM, q_ddot_u_map), udot_zero, uauxdot_zero, uaux_zero) fr_star = -(MM * msubs(Matrix(self._udot), uauxdot_zero) + nonMM) # If there are dependent speeds, we need to find fr_star_tilde if self._udep: p = o - len(self._udep) fr_star_ind = fr_star[:p, 0] fr_star_dep = fr_star[p:o, 0] fr_star = fr_star_ind + (self._Ars.T * fr_star_dep) # Apply the same to MM MMi = MM[:p, :] MMd = MM[p:o, :] MM = MMi + (self._Ars.T * MMd) self._bodylist = bl self._frstar = fr_star self._k_d = MM self._f_d = -msubs(self._fr + self._frstar, udot_zero) return fr_star def to_linearizer(self): """Returns an instance of the Linearizer class, initiated from the data in the KanesMethod class. This may be more desirable than using the linearize class method, as the Linearizer object will allow more efficient recalculation (i.e. about varying operating points).""" if (self._fr is None) or (self._frstar is None): raise ValueError('Need to compute Fr, Fr* first.') # Get required equation components. The Kane's method class breaks # these into pieces. Need to reassemble f_c = self._f_h if self._f_nh and self._k_nh: f_v = self._f_nh + self._k_nh*Matrix(self.u) else: f_v = Matrix() if self._f_dnh and self._k_dnh: f_a = self._f_dnh + self._k_dnh*Matrix(self._udot) else: f_a = Matrix() # Dicts to sub to zero, for splitting up expressions u_zero = {i: 0 for i in self.u} ud_zero = {i: 0 for i in self._udot} qd_zero = {i: 0 for i in self._qdot} qd_u_zero = {i: 0 for i in Matrix([self._qdot, self.u])} # Break the kinematic differential eqs apart into f_0 and f_1 f_0 = msubs(self._f_k, u_zero) + self._k_kqdot*Matrix(self._qdot) f_1 = msubs(self._f_k, qd_zero) + self._k_ku*Matrix(self.u) # Break the dynamic differential eqs into f_2 and f_3 f_2 = msubs(self._frstar, qd_u_zero) f_3 = msubs(self._frstar, ud_zero) + self._fr f_4 = zeros(len(f_2), 1) # Get the required vector components q = self.q u = self.u if self._qdep: q_i = q[:-len(self._qdep)] else: q_i = q q_d = self._qdep if self._udep: u_i = u[:-len(self._udep)] else: u_i = u u_d = self._udep # Form dictionary to set auxiliary speeds & their derivatives to 0. uaux = self._uaux uauxdot = uaux.diff(dynamicsymbols._t) uaux_zero = {i: 0 for i in Matrix([uaux, uauxdot])} # Checking for dynamic symbols outside the dynamic differential # equations; throws error if there is. sym_list = set(Matrix([q, self._qdot, u, self._udot, uaux, uauxdot])) if any(find_dynamicsymbols(i, sym_list) for i in [self._k_kqdot, self._k_ku, self._f_k, self._k_dnh, self._f_dnh, self._k_d]): raise ValueError('Cannot have dynamicsymbols outside dynamic \ forcing vector.') # Find all other dynamic symbols, forming the forcing vector r. # Sort r to make it canonical. r = list(find_dynamicsymbols(msubs(self._f_d, uaux_zero), sym_list)) r.sort(key=default_sort_key) # Check for any derivatives of variables in r that are also found in r. for i in r: if diff(i, dynamicsymbols._t) in r: raise ValueError('Cannot have derivatives of specified \ quantities when linearizing forcing terms.') return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i, q_d, u_i, u_d, r) # TODO : Remove `new_method` after 1.1 has been released. def linearize(self, *, new_method=None, **kwargs): """ Linearize the equations of motion about a symbolic operating point. Explanation =========== If kwarg A_and_B is False (default), returns M, A, B, r for the linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r. If kwarg A_and_B is True, returns A, B, r for the linearized form dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is computationally intensive if there are many symbolic parameters. For this reason, it may be more desirable to use the default A_and_B=False, returning M, A, and B. Values may then be substituted in to these matrices, and the state space form found as A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat. In both cases, r is found as all dynamicsymbols in the equations of motion that are not part of q, u, q', or u'. They are sorted in canonical form. The operating points may be also entered using the ``op_point`` kwarg. This takes a dictionary of {symbol: value}, or a an iterable of such dictionaries. The values may be numeric or symbolic. The more values you can specify beforehand, the faster this computation will run. For more documentation, please see the ``Linearizer`` class.""" linearizer = self.to_linearizer() result = linearizer.linearize(**kwargs) return result + (linearizer.r,) def kanes_equations(self, bodies=None, loads=None): """ Method to form Kane's equations, Fr + Fr* = 0. Explanation =========== Returns (Fr, Fr*). In the case where auxiliary generalized speeds are present (say, s auxiliary speeds, o generalized speeds, and m motion constraints) the length of the returned vectors will be o - m + s in length. The first o - m equations will be the constrained Kane's equations, then the s auxiliary Kane's equations. These auxiliary equations can be accessed with the auxiliary_eqs(). Parameters ========== bodies : iterable An iterable of all RigidBody's and Particle's in the system. A system must have at least one body. loads : iterable Takes in an iterable of (Particle, Vector) or (ReferenceFrame, Vector) tuples which represent the force at a point or torque on a frame. Must be either a non-empty iterable of tuples or None which corresponds to a system with no constraints. """ if bodies is None: bodies = self.bodies if loads is None and self._forcelist is not None: loads = self._forcelist if loads == []: loads = None if not self._k_kqdot: raise AttributeError('Create an instance of KanesMethod with ' 'kinematic differential equations to use this method.') fr = self._form_fr(loads) frstar = self._form_frstar(bodies) if self._uaux: if not self._udep: km = KanesMethod(self._inertial, self.q, self._uaux, u_auxiliary=self._uaux) else: km = KanesMethod(self._inertial, self.q, self._uaux, u_auxiliary=self._uaux, u_dependent=self._udep, velocity_constraints=(self._k_nh * self.u + self._f_nh)) km._qdot_u_map = self._qdot_u_map self._km = km fraux = km._form_fr(loads) frstaraux = km._form_frstar(bodies) self._aux_eq = fraux + frstaraux self._fr = fr.col_join(fraux) self._frstar = frstar.col_join(frstaraux) return (self._fr, self._frstar) def _form_eoms(self): fr, frstar = self.kanes_equations(self.bodylist, self.forcelist) return fr + frstar def rhs(self, inv_method=None): """Returns the system's equations of motion in first order form. The output is the right hand side of:: x' = |q'| =: f(q, u, r, p, t) |u'| The right hand side is what is needed by most numerical ODE integrators. Parameters ========== inv_method : str The specific sympy inverse matrix calculation method to use. For a list of valid methods, see :meth:`~sympy.matrices.matrices.MatrixBase.inv` """ rhs = zeros(len(self.q) + len(self.u), 1) kdes = self.kindiffdict() for i, q_i in enumerate(self.q): rhs[i] = kdes[q_i.diff()] if inv_method is None: rhs[len(self.q):, 0] = self.mass_matrix.LUsolve(self.forcing) else: rhs[len(self.q):, 0] = (self.mass_matrix.inv(inv_method, try_block_diag=True) * self.forcing) return rhs def kindiffdict(self): """Returns a dictionary mapping q' to u.""" if not self._qdot_u_map: raise AttributeError('Create an instance of KanesMethod with ' 'kinematic differential equations to use this method.') return self._qdot_u_map @property def auxiliary_eqs(self): """A matrix containing the auxiliary equations.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') if not self._uaux: raise ValueError('No auxiliary speeds have been declared.') return self._aux_eq @property def mass_matrix(self): """The mass matrix of the system.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') return Matrix([self._k_d, self._k_dnh]) @property def mass_matrix_full(self): """The mass matrix of the system, augmented by the kinematic differential equations.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') o = len(self.u) n = len(self.q) return ((self._k_kqdot).row_join(zeros(n, o))).col_join((zeros(o, n)).row_join(self.mass_matrix)) @property def forcing(self): """The forcing vector of the system.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') return -Matrix([self._f_d, self._f_dnh]) @property def forcing_full(self): """The forcing vector of the system, augmented by the kinematic differential equations.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') f1 = self._k_ku * Matrix(self.u) + self._f_k return -Matrix([f1, self._f_d, self._f_dnh]) @property def q(self): return self._q @property def u(self): return self._u @property def bodylist(self): return self._bodylist @property def forcelist(self): return self._forcelist @property def bodies(self): return self._bodylist @property def loads(self): return self._forcelist
8b953d611e29259ec460b1aff846c8be45270e603d00d78ac9a979c0d0f00330
from sympy.physics.mechanics import (Body, Lagrangian, KanesMethod, LagrangesMethod, RigidBody, Particle) from sympy.physics.mechanics.method import _Methods __all__ = ['JointsMethod'] class JointsMethod(_Methods): """Method for formulating the equations of motion using a set of interconnected bodies with joints. Parameters ========== newtonion : Body or ReferenceFrame The newtonion(inertial) frame. *joints : Joint The joints in the system Attributes ========== q, u : iterable Iterable of the generalized coordinates and speeds bodies : iterable Iterable of Body objects in the system. loads : iterable Iterable of (Point, vector) or (ReferenceFrame, vector) tuples describing the forces on the system. mass_matrix : Matrix, shape(n, n) The system's mass matrix forcing : Matrix, shape(n, 1) The system's forcing vector mass_matrix_full : Matrix, shape(2*n, 2*n) The "mass matrix" for the u's and q's forcing_full : Matrix, shape(2*n, 1) The "forcing vector" for the u's and q's method : KanesMethod or Lagrange's method Method's object. kdes : iterable Iterable of kde in they system. Examples ======== This is a simple example for a one degree of freedom translational spring-mass-damper. >>> from sympy import symbols >>> from sympy.physics.mechanics import Body, JointsMethod, PrismaticJoint >>> from sympy.physics.vector import dynamicsymbols >>> c, k = symbols('c k') >>> x, v = dynamicsymbols('x v') >>> wall = Body('W') >>> body = Body('B') >>> J = PrismaticJoint('J', wall, body, coordinates=x, speeds=v) >>> wall.apply_force(c*v*wall.x, reaction_body=body) >>> wall.apply_force(k*x*wall.x, reaction_body=body) >>> method = JointsMethod(wall, J) >>> method.form_eoms() Matrix([[-B_mass*Derivative(v(t), t) - c*v(t) - k*x(t)]]) >>> M = method.mass_matrix_full >>> F = method.forcing_full >>> rhs = M.LUsolve(F) >>> rhs Matrix([ [ v(t)], [(-c*v(t) - k*x(t))/B_mass]]) Notes ===== ``JointsMethod`` currently only works with systems that do not have any configuration or motion constraints. """ def __init__(self, newtonion, *joints): if isinstance(newtonion, Body): self.frame = newtonion.frame else: self.frame = newtonion self._joints = joints self._bodies = self._generate_bodylist() self._loads = self._generate_loadlist() self._q = self._generate_q() self._u = self._generate_u() self._kdes = self._generate_kdes() self._method = None @property def bodies(self): """List of bodies in they system.""" return self._bodies @property def loads(self): """List of loads on the system.""" return self._loads @property def q(self): """List of the generalized coordinates.""" return self._q @property def u(self): """List of the generalized speeds.""" return self._u @property def kdes(self): """List of the generalized coordinates.""" return self._kdes @property def forcing_full(self): """The "forcing vector" for the u's and q's.""" return self.method.forcing_full @property def mass_matrix_full(self): """The "mass matrix" for the u's and q's.""" return self.method.mass_matrix_full @property def mass_matrix(self): """The system's mass matrix.""" return self.method.mass_matrix @property def forcing(self): """The system's forcing vector.""" return self.method.forcing @property def method(self): """Object of method used to form equations of systems.""" return self._method def _generate_bodylist(self): bodies = [] for joint in self._joints: if joint.child not in bodies: bodies.append(joint.child) if joint.parent not in bodies: bodies.append(joint.parent) return bodies def _generate_loadlist(self): load_list = [] for body in self.bodies: load_list.extend(body.loads) return load_list def _generate_q(self): q_ind = [] for joint in self._joints: for coordinate in joint.coordinates: if coordinate in q_ind: raise ValueError('Coordinates of joints should be unique.') q_ind.append(coordinate) return q_ind def _generate_u(self): u_ind = [] for joint in self._joints: for speed in joint.speeds: if speed in u_ind: raise ValueError('Speeds of joints should be unique.') u_ind.append(speed) return u_ind def _generate_kdes(self): kd_ind = [] for joint in self._joints: kd_ind.extend(joint.kdes) return kd_ind def _convert_bodies(self): # Convert `Body` to `Particle` and `RigidBody` bodylist = [] for body in self.bodies: if body.is_rigidbody: rb = RigidBody(body.name, body.masscenter, body.frame, body.mass, (body.central_inertia, body.masscenter)) rb.potential_energy = body.potential_energy bodylist.append(rb) else: part = Particle(body.name, body.masscenter, body.mass) part.potential_energy = body.potential_energy bodylist.append(part) return bodylist def form_eoms(self, method=KanesMethod): """Method to form system's equation of motions. Parameters ========== method : Class Class name of method. Returns ======== Matrix Vector of equations of motions. Examples ======== This is a simple example for a one degree of freedom translational spring-mass-damper. >>> from sympy import S, symbols >>> from sympy.physics.mechanics import LagrangesMethod, dynamicsymbols, Body >>> from sympy.physics.mechanics import PrismaticJoint, JointsMethod >>> q = dynamicsymbols('q') >>> qd = dynamicsymbols('q', 1) >>> m, k, b = symbols('m k b') >>> wall = Body('W') >>> part = Body('P', mass=m) >>> part.potential_energy = k * q**2 / S(2) >>> J = PrismaticJoint('J', wall, part, coordinates=q, speeds=qd) >>> wall.apply_force(b * qd * wall.x, reaction_body=part) >>> method = JointsMethod(wall, J) >>> method.form_eoms(LagrangesMethod) Matrix([[b*Derivative(q(t), t) + k*q(t) + m*Derivative(q(t), (t, 2))]]) We can also solve for the states using the 'rhs' method. >>> method.rhs() Matrix([ [ Derivative(q(t), t)], [(-b*Derivative(q(t), t) - k*q(t))/m]]) """ bodylist = self._convert_bodies() if issubclass(method, LagrangesMethod): #LagrangesMethod or similar L = Lagrangian(self.frame, *bodylist) self._method = method(L, self.q, self.loads, bodylist, self.frame) else: #KanesMethod or similar self._method = method(self.frame, q_ind=self.q, u_ind=self.u, kd_eqs=self.kdes, forcelist=self.loads, bodies=bodylist) soln = self.method._form_eoms() return soln def rhs(self, inv_method=None): """Returns equations that can be solved numerically. Parameters ========== inv_method : str The specific sympy inverse matrix calculation method to use. For a list of valid methods, see :meth:`~sympy.matrices.matrices.MatrixBase.inv` Returns ======== Matrix Numerically solveable equations. See Also ======== sympy.physics.mechanics.KanesMethod.rhs(): KanesMethod's rhs function. sympy.physics.mechanics.LagrangesMethod.rhs(): LagrangesMethod's rhs function. """ return self.method.rhs(inv_method=inv_method)
a08a06220b88218b73aea2addcb88e957e7b4d4eae68100dc8362d2d948c1e80
from sympy.core.backend import diff, zeros, Matrix, eye, sympify from sympy.physics.vector import dynamicsymbols, ReferenceFrame from sympy.physics.mechanics.method import _Methods from sympy.physics.mechanics.functions import (find_dynamicsymbols, msubs, _f_list_parser) from sympy.physics.mechanics.linearize import Linearizer from sympy.utilities import default_sort_key from sympy.utilities.iterables import iterable __all__ = ['LagrangesMethod'] class LagrangesMethod(_Methods): """Lagrange's method object. Explanation =========== This object generates the equations of motion in a two step procedure. The first step involves the initialization of LagrangesMethod by supplying the Lagrangian and the generalized coordinates, at the bare minimum. If there are any constraint equations, they can be supplied as keyword arguments. The Lagrange multipliers are automatically generated and are equal in number to the constraint equations. Similarly any non-conservative forces can be supplied in an iterable (as described below and also shown in the example) along with a ReferenceFrame. This is also discussed further in the __init__ method. Attributes ========== q, u : Matrix Matrices of the generalized coordinates and speeds loads : iterable Iterable of (Point, vector) or (ReferenceFrame, vector) tuples describing the forces on the system. bodies : iterable Iterable containing the rigid bodies and particles of the system. mass_matrix : Matrix The system's mass matrix forcing : Matrix The system's forcing vector mass_matrix_full : Matrix The "mass matrix" for the qdot's, qdoubledot's, and the lagrange multipliers (lam) forcing_full : Matrix The forcing vector for the qdot's, qdoubledot's and lagrange multipliers (lam) Examples ======== This is a simple example for a one degree of freedom translational spring-mass-damper. In this example, we first need to do the kinematics. This involves creating generalized coordinates and their derivatives. Then we create a point and set its velocity in a frame. >>> from sympy.physics.mechanics import LagrangesMethod, Lagrangian >>> from sympy.physics.mechanics import ReferenceFrame, Particle, Point >>> from sympy.physics.mechanics import dynamicsymbols >>> from sympy import symbols >>> q = dynamicsymbols('q') >>> qd = dynamicsymbols('q', 1) >>> m, k, b = symbols('m k b') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, qd * N.x) We need to then prepare the information as required by LagrangesMethod to generate equations of motion. First we create the Particle, which has a point attached to it. Following this the lagrangian is created from the kinetic and potential energies. Then, an iterable of nonconservative forces/torques must be constructed, where each item is a (Point, Vector) or (ReferenceFrame, Vector) tuple, with the Vectors representing the nonconservative forces or torques. >>> Pa = Particle('Pa', P, m) >>> Pa.potential_energy = k * q**2 / 2.0 >>> L = Lagrangian(N, Pa) >>> fl = [(P, -b * qd * N.x)] Finally we can generate the equations of motion. First we create the LagrangesMethod object. To do this one must supply the Lagrangian, and the generalized coordinates. The constraint equations, the forcelist, and the inertial frame may also be provided, if relevant. Next we generate Lagrange's equations of motion, such that: Lagrange's equations of motion = 0. We have the equations of motion at this point. >>> l = LagrangesMethod(L, [q], forcelist = fl, frame = N) >>> print(l.form_lagranges_equations()) Matrix([[b*Derivative(q(t), t) + 1.0*k*q(t) + m*Derivative(q(t), (t, 2))]]) We can also solve for the states using the 'rhs' method. >>> print(l.rhs()) Matrix([[Derivative(q(t), t)], [(-b*Derivative(q(t), t) - 1.0*k*q(t))/m]]) Please refer to the docstrings on each method for more details. """ def __init__(self, Lagrangian, qs, forcelist=None, bodies=None, frame=None, hol_coneqs=None, nonhol_coneqs=None): """Supply the following for the initialization of LagrangesMethod. Lagrangian : Sympifyable qs : array_like The generalized coordinates hol_coneqs : array_like, optional The holonomic constraint equations nonhol_coneqs : array_like, optional The nonholonomic constraint equations forcelist : iterable, optional Takes an iterable of (Point, Vector) or (ReferenceFrame, Vector) tuples which represent the force at a point or torque on a frame. This feature is primarily to account for the nonconservative forces and/or moments. bodies : iterable, optional Takes an iterable containing the rigid bodies and particles of the system. frame : ReferenceFrame, optional Supply the inertial frame. This is used to determine the generalized forces due to non-conservative forces. """ self._L = Matrix([sympify(Lagrangian)]) self.eom = None self._m_cd = Matrix() # Mass Matrix of differentiated coneqs self._m_d = Matrix() # Mass Matrix of dynamic equations self._f_cd = Matrix() # Forcing part of the diff coneqs self._f_d = Matrix() # Forcing part of the dynamic equations self.lam_coeffs = Matrix() # The coeffecients of the multipliers forcelist = forcelist if forcelist else [] if not iterable(forcelist): raise TypeError('Force pairs must be supplied in an iterable.') self._forcelist = forcelist if frame and not isinstance(frame, ReferenceFrame): raise TypeError('frame must be a valid ReferenceFrame') self._bodies = bodies self.inertial = frame self.lam_vec = Matrix() self._term1 = Matrix() self._term2 = Matrix() self._term3 = Matrix() self._term4 = Matrix() # Creating the qs, qdots and qdoubledots if not iterable(qs): raise TypeError('Generalized coordinates must be an iterable') self._q = Matrix(qs) self._qdots = self.q.diff(dynamicsymbols._t) self._qdoubledots = self._qdots.diff(dynamicsymbols._t) mat_build = lambda x: Matrix(x) if x else Matrix() hol_coneqs = mat_build(hol_coneqs) nonhol_coneqs = mat_build(nonhol_coneqs) self.coneqs = Matrix([hol_coneqs.diff(dynamicsymbols._t), nonhol_coneqs]) self._hol_coneqs = hol_coneqs def form_lagranges_equations(self): """Method to form Lagrange's equations of motion. Returns a vector of equations of motion using Lagrange's equations of the second kind. """ qds = self._qdots qdd_zero = {i: 0 for i in self._qdoubledots} n = len(self.q) # Internally we represent the EOM as four terms: # EOM = term1 - term2 - term3 - term4 = 0 # First term self._term1 = self._L.jacobian(qds) self._term1 = self._term1.diff(dynamicsymbols._t).T # Second term self._term2 = self._L.jacobian(self.q).T # Third term if self.coneqs: coneqs = self.coneqs m = len(coneqs) # Creating the multipliers self.lam_vec = Matrix(dynamicsymbols('lam1:' + str(m + 1))) self.lam_coeffs = -coneqs.jacobian(qds) self._term3 = self.lam_coeffs.T * self.lam_vec # Extracting the coeffecients of the qdds from the diff coneqs diffconeqs = coneqs.diff(dynamicsymbols._t) self._m_cd = diffconeqs.jacobian(self._qdoubledots) # The remaining terms i.e. the 'forcing' terms in diff coneqs self._f_cd = -diffconeqs.subs(qdd_zero) else: self._term3 = zeros(n, 1) # Fourth term if self.forcelist: N = self.inertial self._term4 = zeros(n, 1) for i, qd in enumerate(qds): flist = zip(*_f_list_parser(self.forcelist, N)) self._term4[i] = sum(v.diff(qd, N) & f for (v, f) in flist) else: self._term4 = zeros(n, 1) # Form the dynamic mass and forcing matrices without_lam = self._term1 - self._term2 - self._term4 self._m_d = without_lam.jacobian(self._qdoubledots) self._f_d = -without_lam.subs(qdd_zero) # Form the EOM self.eom = without_lam - self._term3 return self.eom def _form_eoms(self): return self.form_lagranges_equations() @property def mass_matrix(self): """Returns the mass matrix, which is augmented by the Lagrange multipliers, if necessary. Explanation =========== If the system is described by 'n' generalized coordinates and there are no constraint equations then an n X n matrix is returned. If there are 'n' generalized coordinates and 'm' constraint equations have been supplied during initialization then an n X (n+m) matrix is returned. The (n + m - 1)th and (n + m)th columns contain the coefficients of the Lagrange multipliers. """ if self.eom is None: raise ValueError('Need to compute the equations of motion first') if self.coneqs: return (self._m_d).row_join(self.lam_coeffs.T) else: return self._m_d @property def mass_matrix_full(self): """Augments the coefficients of qdots to the mass_matrix.""" if self.eom is None: raise ValueError('Need to compute the equations of motion first') n = len(self.q) m = len(self.coneqs) row1 = eye(n).row_join(zeros(n, n + m)) row2 = zeros(n, n).row_join(self.mass_matrix) if self.coneqs: row3 = zeros(m, n).row_join(self._m_cd).row_join(zeros(m, m)) return row1.col_join(row2).col_join(row3) else: return row1.col_join(row2) @property def forcing(self): """Returns the forcing vector from 'lagranges_equations' method.""" if self.eom is None: raise ValueError('Need to compute the equations of motion first') return self._f_d @property def forcing_full(self): """Augments qdots to the forcing vector above.""" if self.eom is None: raise ValueError('Need to compute the equations of motion first') if self.coneqs: return self._qdots.col_join(self.forcing).col_join(self._f_cd) else: return self._qdots.col_join(self.forcing) def to_linearizer(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None): """Returns an instance of the Linearizer class, initiated from the data in the LagrangesMethod class. This may be more desirable than using the linearize class method, as the Linearizer object will allow more efficient recalculation (i.e. about varying operating points). Parameters ========== q_ind, qd_ind : array_like, optional The independent generalized coordinates and speeds. q_dep, qd_dep : array_like, optional The dependent generalized coordinates and speeds. """ # Compose vectors t = dynamicsymbols._t q = self.q u = self._qdots ud = u.diff(t) # Get vector of lagrange multipliers lams = self.lam_vec mat_build = lambda x: Matrix(x) if x else Matrix() q_i = mat_build(q_ind) q_d = mat_build(q_dep) u_i = mat_build(qd_ind) u_d = mat_build(qd_dep) # Compose general form equations f_c = self._hol_coneqs f_v = self.coneqs f_a = f_v.diff(t) f_0 = u f_1 = -u f_2 = self._term1 f_3 = -(self._term2 + self._term4) f_4 = -self._term3 # Check that there are an appropriate number of independent and # dependent coordinates if len(q_d) != len(f_c) or len(u_d) != len(f_v): raise ValueError(("Must supply {:} dependent coordinates, and " + "{:} dependent speeds").format(len(f_c), len(f_v))) if set(Matrix([q_i, q_d])) != set(q): raise ValueError("Must partition q into q_ind and q_dep, with " + "no extra or missing symbols.") if set(Matrix([u_i, u_d])) != set(u): raise ValueError("Must partition qd into qd_ind and qd_dep, " + "with no extra or missing symbols.") # Find all other dynamic symbols, forming the forcing vector r. # Sort r to make it canonical. insyms = set(Matrix([q, u, ud, lams])) r = list(find_dynamicsymbols(f_3, insyms)) r.sort(key=default_sort_key) # Check for any derivatives of variables in r that are also found in r. for i in r: if diff(i, dynamicsymbols._t) in r: raise ValueError('Cannot have derivatives of specified \ quantities when linearizing forcing terms.') return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i, q_d, u_i, u_d, r, lams) def linearize(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None, **kwargs): """Linearize the equations of motion about a symbolic operating point. Explanation =========== If kwarg A_and_B is False (default), returns M, A, B, r for the linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r. If kwarg A_and_B is True, returns A, B, r for the linearized form dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is computationally intensive if there are many symbolic parameters. For this reason, it may be more desirable to use the default A_and_B=False, returning M, A, and B. Values may then be substituted in to these matrices, and the state space form found as A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat. In both cases, r is found as all dynamicsymbols in the equations of motion that are not part of q, u, q', or u'. They are sorted in canonical form. The operating points may be also entered using the ``op_point`` kwarg. This takes a dictionary of {symbol: value}, or a an iterable of such dictionaries. The values may be numeric or symbolic. The more values you can specify beforehand, the faster this computation will run. For more documentation, please see the ``Linearizer`` class.""" linearizer = self.to_linearizer(q_ind, qd_ind, q_dep, qd_dep) result = linearizer.linearize(**kwargs) return result + (linearizer.r,) def solve_multipliers(self, op_point=None, sol_type='dict'): """Solves for the values of the lagrange multipliers symbolically at the specified operating point. Parameters ========== op_point : dict or iterable of dicts, optional Point at which to solve at. The operating point is specified as a dictionary or iterable of dictionaries of {symbol: value}. The value may be numeric or symbolic itself. sol_type : str, optional Solution return type. Valid options are: - 'dict': A dict of {symbol : value} (default) - 'Matrix': An ordered column matrix of the solution """ # Determine number of multipliers k = len(self.lam_vec) if k == 0: raise ValueError("System has no lagrange multipliers to solve for.") # Compose dict of operating conditions if isinstance(op_point, dict): op_point_dict = op_point elif iterable(op_point): op_point_dict = {} for op in op_point: op_point_dict.update(op) elif op_point is None: op_point_dict = {} else: raise TypeError("op_point must be either a dictionary or an " "iterable of dictionaries.") # Compose the system to be solved mass_matrix = self.mass_matrix.col_join(-self.lam_coeffs.row_join( zeros(k, k))) force_matrix = self.forcing.col_join(self._f_cd) # Sub in the operating point mass_matrix = msubs(mass_matrix, op_point_dict) force_matrix = msubs(force_matrix, op_point_dict) # Solve for the multipliers sol_list = mass_matrix.LUsolve(-force_matrix)[-k:] if sol_type == 'dict': return dict(zip(self.lam_vec, sol_list)) elif sol_type == 'Matrix': return Matrix(sol_list) else: raise ValueError("Unknown sol_type {:}.".format(sol_type)) def rhs(self, inv_method=None, **kwargs): """Returns equations that can be solved numerically. Parameters ========== inv_method : str The specific sympy inverse matrix calculation method to use. For a list of valid methods, see :meth:`~sympy.matrices.matrices.MatrixBase.inv` """ if inv_method is None: self._rhs = self.mass_matrix_full.LUsolve(self.forcing_full) else: self._rhs = (self.mass_matrix_full.inv(inv_method, try_block_diag=True) * self.forcing_full) return self._rhs @property def q(self): return self._q @property def u(self): return self._qdots @property def bodies(self): return self._bodies @property def forcelist(self): return self._forcelist @property def loads(self): return self._forcelist
daf151840efdadae0747a0335411ccaf7a0d9dcadcaa02cb311a9dca27f40eb2
from abc import ABC, abstractmethod class _Methods(ABC): """Abstract Base Class for all methods.""" @abstractmethod def q(self): pass @abstractmethod def u(self): pass @abstractmethod def bodies(self): pass @abstractmethod def loads(self): pass @abstractmethod def mass_matrix(self): pass @abstractmethod def forcing(self): pass @abstractmethod def mass_matrix_full(self): pass @abstractmethod def forcing_full(self): pass def _form_eoms(self): raise NotImplementedError("Subclasses must implement this.")
ffc4f2a9560b53bc767cf5f5abc2969c8f20d8edd7d00b1dda158f9f2764ce4e
from sympy.physics.matrices import msigma, mgamma, minkowski_tensor, pat_matrix, mdft from sympy import zeros, eye, I, Matrix, sqrt, Rational, S from sympy.testing.pytest import warns_deprecated_sympy def test_parallel_axis_theorem(): # This tests the parallel axis theorem matrix by comparing to test # matrices. # First case, 1 in all directions. mat1 = Matrix(((2, -1, -1), (-1, 2, -1), (-1, -1, 2))) assert pat_matrix(1, 1, 1, 1) == mat1 assert pat_matrix(2, 1, 1, 1) == 2*mat1 # Second case, 1 in x, 0 in all others mat2 = Matrix(((0, 0, 0), (0, 1, 0), (0, 0, 1))) assert pat_matrix(1, 1, 0, 0) == mat2 assert pat_matrix(2, 1, 0, 0) == 2*mat2 # Third case, 1 in y, 0 in all others mat3 = Matrix(((1, 0, 0), (0, 0, 0), (0, 0, 1))) assert pat_matrix(1, 0, 1, 0) == mat3 assert pat_matrix(2, 0, 1, 0) == 2*mat3 # Fourth case, 1 in z, 0 in all others mat4 = Matrix(((1, 0, 0), (0, 1, 0), (0, 0, 0))) assert pat_matrix(1, 0, 0, 1) == mat4 assert pat_matrix(2, 0, 0, 1) == 2*mat4 def test_Pauli(): #this and the following test are testing both Pauli and Dirac matrices #and also that the general Matrix class works correctly in a real world #situation sigma1 = msigma(1) sigma2 = msigma(2) sigma3 = msigma(3) assert sigma1 == sigma1 assert sigma1 != sigma2 # sigma*I -> I*sigma (see #354) assert sigma1*sigma2 == sigma3*I assert sigma3*sigma1 == sigma2*I assert sigma2*sigma3 == sigma1*I assert sigma1*sigma1 == eye(2) assert sigma2*sigma2 == eye(2) assert sigma3*sigma3 == eye(2) assert sigma1*2*sigma1 == 2*eye(2) assert sigma1*sigma3*sigma1 == -sigma3 def test_Dirac(): gamma0 = mgamma(0) gamma1 = mgamma(1) gamma2 = mgamma(2) gamma3 = mgamma(3) gamma5 = mgamma(5) # gamma*I -> I*gamma (see #354) assert gamma5 == gamma0 * gamma1 * gamma2 * gamma3 * I assert gamma1 * gamma2 + gamma2 * gamma1 == zeros(4) assert gamma0 * gamma0 == eye(4) * minkowski_tensor[0, 0] assert gamma2 * gamma2 != eye(4) * minkowski_tensor[0, 0] assert gamma2 * gamma2 == eye(4) * minkowski_tensor[2, 2] assert mgamma(5, True) == \ mgamma(0, True)*mgamma(1, True)*mgamma(2, True)*mgamma(3, True)*I def test_mdft(): with warns_deprecated_sympy(): assert mdft(1) == Matrix([[1]]) with warns_deprecated_sympy(): assert mdft(2) == 1/sqrt(2)*Matrix([[1,1],[1,-1]]) with warns_deprecated_sympy(): assert mdft(4) == Matrix([[S.Half, S.Half, S.Half, S.Half], [S.Half, -I/2, Rational(-1,2), I/2], [S.Half, Rational(-1,2), S.Half, Rational(-1,2)], [S.Half, I/2, Rational(-1,2), -I/2]])
df68db20581eeaef85d1ca8f14cded5a0ee4b04b0a949270c8eff0546f03929a
""" This module can be used to solve 2D beam bending problems with singularity functions in mechanics. """ from sympy.core import S, Symbol, diff, symbols from sympy.solvers import linsolve from sympy.printing import sstr from sympy.functions import SingularityFunction, Piecewise, factorial from sympy.core import sympify from sympy.integrals import integrate from sympy.series import limit from sympy.plotting import plot, PlotGrid from sympy.geometry.entity import GeometryEntity from sympy.external import import_module from sympy import lambdify, Add from sympy.core.compatibility import iterable from sympy.utilities.decorator import doctest_depends_on numpy = import_module('numpy', import_kwargs={'fromlist':['arange']}) class Beam: """ A Beam is a structural element that is capable of withstanding load primarily by resisting against bending. Beams are characterized by their cross sectional profile(Second moment of area), their length and their material. .. note:: While solving a beam bending problem, a user should choose its own sign convention and should stick to it. The results will automatically follow the chosen sign convention. However, the chosen sign convention must respect the rule that, on the positive side of beam's axis (in respect to current section), a loading force giving positive shear yields a negative moment, as below (the curved arrow shows the positive moment and rotation): .. image:: allowed-sign-conventions.png Examples ======== There is a beam of length 4 meters. A constant distributed load of 6 N/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. The deflection of the beam at the end is restricted. Using the sign convention of downwards forces being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols, Piecewise >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(4, E, I) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(6, 2, 0) >>> b.apply_load(R2, 4, -1) >>> b.bc_deflection = [(0, 0), (4, 0)] >>> b.boundary_conditions {'deflection': [(0, 0), (4, 0)], 'slope': []} >>> b.load R1*SingularityFunction(x, 0, -1) + R2*SingularityFunction(x, 4, -1) + 6*SingularityFunction(x, 2, 0) >>> b.solve_for_reaction_loads(R1, R2) >>> b.load -3*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 2, 0) - 9*SingularityFunction(x, 4, -1) >>> b.shear_force() 3*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 2, 1) + 9*SingularityFunction(x, 4, 0) >>> b.bending_moment() 3*SingularityFunction(x, 0, 1) - 3*SingularityFunction(x, 2, 2) + 9*SingularityFunction(x, 4, 1) >>> b.slope() (-3*SingularityFunction(x, 0, 2)/2 + SingularityFunction(x, 2, 3) - 9*SingularityFunction(x, 4, 2)/2 + 7)/(E*I) >>> b.deflection() (7*x - SingularityFunction(x, 0, 3)/2 + SingularityFunction(x, 2, 4)/4 - 3*SingularityFunction(x, 4, 3)/2)/(E*I) >>> b.deflection().rewrite(Piecewise) (7*x - Piecewise((x**3, x > 0), (0, True))/2 - 3*Piecewise(((x - 4)**3, x - 4 > 0), (0, True))/2 + Piecewise(((x - 2)**4, x - 2 > 0), (0, True))/4)/(E*I) """ def __init__(self, length, elastic_modulus, second_moment, area=Symbol('A'), variable=Symbol('x'), base_char='C'): """Initializes the class. Parameters ========== length : Sympifyable A Symbol or value representing the Beam's length. elastic_modulus : Sympifyable A SymPy expression representing the Beam's Modulus of Elasticity. It is a measure of the stiffness of the Beam material. It can also be a continuous function of position along the beam. second_moment : Sympifyable or Geometry object Describes the cross-section of the beam via a SymPy expression representing the Beam's second moment of area. It is a geometrical property of an area which reflects how its points are distributed with respect to its neutral axis. It can also be a continuous function of position along the beam. Alternatively ``second_moment`` can be a shape object such as a ``Polygon`` from the geometry module representing the shape of the cross-section of the beam. In such cases, it is assumed that the x-axis of the shape object is aligned with the bending axis of the beam. The second moment of area will be computed from the shape object internally. area : Symbol/float Represents the cross-section area of beam variable : Symbol, optional A Symbol object that will be used as the variable along the beam while representing the load, shear, moment, slope and deflection curve. By default, it is set to ``Symbol('x')``. base_char : String, optional A String that will be used as base character to generate sequential symbols for integration constants in cases where boundary conditions are not sufficient to solve them. """ self.length = length self.elastic_modulus = elastic_modulus if isinstance(second_moment, GeometryEntity): self.cross_section = second_moment else: self.cross_section = None self.second_moment = second_moment self.variable = variable self._base_char = base_char self._boundary_conditions = {'deflection': [], 'slope': []} self._load = 0 self._area = area self._applied_supports = [] self._support_as_loads = [] self._applied_loads = [] self._reaction_loads = {} self._ild_reactions = {} self._ild_shear = 0 self._ild_moment = 0 # _original_load is a copy of _load equations with unsubstituted reaction # forces. It is used for calculating reaction forces in case of I.L.D. self._original_load = 0 self._composite_type = None self._hinge_position = None def __str__(self): shape_description = self._cross_section if self._cross_section else self._second_moment str_sol = 'Beam({}, {}, {})'.format(sstr(self._length), sstr(self._elastic_modulus), sstr(shape_description)) return str_sol @property def reaction_loads(self): """ Returns the reaction forces in a dictionary.""" return self._reaction_loads @property def ild_shear(self): """ Returns the I.L.D. shear equation.""" return self._ild_shear @property def ild_reactions(self): """ Returns the I.L.D. reaction forces in a dictionary.""" return self._ild_reactions @property def ild_moment(self): """ Returns the I.L.D. moment equation.""" return self._ild_moment @property def length(self): """Length of the Beam.""" return self._length @length.setter def length(self, l): self._length = sympify(l) @property def area(self): """Cross-sectional area of the Beam. """ return self._area @area.setter def area(self, a): self._area = sympify(a) @property def variable(self): """ A symbol that can be used as a variable along the length of the beam while representing load distribution, shear force curve, bending moment, slope curve and the deflection curve. By default, it is set to ``Symbol('x')``, but this property is mutable. Examples ======== >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I, A = symbols('E, I, A') >>> x, y, z = symbols('x, y, z') >>> b = Beam(4, E, I) >>> b.variable x >>> b.variable = y >>> b.variable y >>> b = Beam(4, E, I, A, z) >>> b.variable z """ return self._variable @variable.setter def variable(self, v): if isinstance(v, Symbol): self._variable = v else: raise TypeError("""The variable should be a Symbol object.""") @property def elastic_modulus(self): """Young's Modulus of the Beam. """ return self._elastic_modulus @elastic_modulus.setter def elastic_modulus(self, e): self._elastic_modulus = sympify(e) @property def second_moment(self): """Second moment of area of the Beam. """ return self._second_moment @second_moment.setter def second_moment(self, i): self._cross_section = None if isinstance(i, GeometryEntity): raise ValueError("To update cross-section geometry use `cross_section` attribute") else: self._second_moment = sympify(i) @property def cross_section(self): """Cross-section of the beam""" return self._cross_section @cross_section.setter def cross_section(self, s): if s: self._second_moment = s.second_moment_of_area()[0] self._cross_section = s @property def boundary_conditions(self): """ Returns a dictionary of boundary conditions applied on the beam. The dictionary has three keywords namely moment, slope and deflection. The value of each keyword is a list of tuple, where each tuple contains location and value of a boundary condition in the format (location, value). Examples ======== There is a beam of length 4 meters. The bending moment at 0 should be 4 and at 4 it should be 0. The slope of the beam should be 1 at 0. The deflection should be 2 at 0. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(4, E, I) >>> b.bc_deflection = [(0, 2)] >>> b.bc_slope = [(0, 1)] >>> b.boundary_conditions {'deflection': [(0, 2)], 'slope': [(0, 1)]} Here the deflection of the beam should be ``2`` at ``0``. Similarly, the slope of the beam should be ``1`` at ``0``. """ return self._boundary_conditions @property def bc_slope(self): return self._boundary_conditions['slope'] @bc_slope.setter def bc_slope(self, s_bcs): self._boundary_conditions['slope'] = s_bcs @property def bc_deflection(self): return self._boundary_conditions['deflection'] @bc_deflection.setter def bc_deflection(self, d_bcs): self._boundary_conditions['deflection'] = d_bcs def join(self, beam, via="fixed"): """ This method joins two beams to make a new composite beam system. Passed Beam class instance is attached to the right end of calling object. This method can be used to form beams having Discontinuous values of Elastic modulus or Second moment. Parameters ========== beam : Beam class object The Beam object which would be connected to the right of calling object. via : String States the way two Beam object would get connected - For axially fixed Beams, via="fixed" - For Beams connected via hinge, via="hinge" Examples ======== There is a cantilever beam of length 4 meters. For first 2 meters its moment of inertia is `1.5*I` and `I` for the other end. A pointload of magnitude 4 N is applied from the top at its free end. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b1 = Beam(2, E, 1.5*I) >>> b2 = Beam(2, E, I) >>> b = b1.join(b2, "fixed") >>> b.apply_load(20, 4, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 0, -2) >>> b.bc_slope = [(0, 0)] >>> b.bc_deflection = [(0, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.load 80*SingularityFunction(x, 0, -2) - 20*SingularityFunction(x, 0, -1) + 20*SingularityFunction(x, 4, -1) >>> b.slope() (-((-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))/I + 120/I)/E + 80.0/(E*I))*SingularityFunction(x, 2, 0) - 0.666666666666667*(-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))*SingularityFunction(x, 0, 0)/(E*I) + 0.666666666666667*(-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))*SingularityFunction(x, 2, 0)/(E*I) """ x = self.variable E = self.elastic_modulus new_length = self.length + beam.length if self.second_moment != beam.second_moment: new_second_moment = Piecewise((self.second_moment, x<=self.length), (beam.second_moment, x<=new_length)) else: new_second_moment = self.second_moment if via == "fixed": new_beam = Beam(new_length, E, new_second_moment, x) new_beam._composite_type = "fixed" return new_beam if via == "hinge": new_beam = Beam(new_length, E, new_second_moment, x) new_beam._composite_type = "hinge" new_beam._hinge_position = self.length return new_beam def apply_support(self, loc, type="fixed"): """ This method applies support to a particular beam object. Parameters ========== loc : Sympifyable Location of point at which support is applied. type : String Determines type of Beam support applied. To apply support structure with - zero degree of freedom, type = "fixed" - one degree of freedom, type = "pin" - two degrees of freedom, type = "roller" Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(30, E, I) >>> b.apply_support(10, 'roller') >>> b.apply_support(30, 'roller') >>> b.apply_load(-8, 0, -1) >>> b.apply_load(120, 30, -2) >>> R_10, R_30 = symbols('R_10, R_30') >>> b.solve_for_reaction_loads(R_10, R_30) >>> b.load -8*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 10, -1) + 120*SingularityFunction(x, 30, -2) + 2*SingularityFunction(x, 30, -1) >>> b.slope() (-4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2) + 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + 4000/3)/(E*I) """ loc = sympify(loc) self._applied_supports.append((loc, type)) if type == "pin" or type == "roller": reaction_load = Symbol('R_'+str(loc)) self.apply_load(reaction_load, loc, -1) self.bc_deflection.append((loc, 0)) else: reaction_load = Symbol('R_'+str(loc)) reaction_moment = Symbol('M_'+str(loc)) self.apply_load(reaction_load, loc, -1) self.apply_load(reaction_moment, loc, -2) self.bc_deflection.append((loc, 0)) self.bc_slope.append((loc, 0)) self._support_as_loads.append((reaction_moment, loc, -2, None)) self._support_as_loads.append((reaction_load, loc, -1, None)) def apply_load(self, value, start, order, end=None): """ This method adds up the loads given to a particular beam object. Parameters ========== value : Sympifyable The value inserted should have the units [Force/(Distance**(n+1)] where n is the order of applied load. Units for applied loads: - For moments, unit = kN*m - For point loads, unit = kN - For constant distributed load, unit = kN/m - For ramp loads, unit = kN/m/m - For parabolic ramp loads, unit = kN/m/m/m - ... so on. start : Sympifyable The starting point of the applied load. For point moments and point forces this is the location of application. order : Integer The order of the applied load. - For moments, order = -2 - For point loads, order =-1 - For constant distributed load, order = 0 - For ramp loads, order = 1 - For parabolic ramp loads, order = 2 - ... so on. end : Sympifyable, optional An optional argument that can be used if the load has an end point within the length of the beam. Examples ======== There is a beam of length 4 meters. A moment of magnitude 3 Nm is applied in the clockwise direction at the starting point of the beam. A point load of magnitude 4 N is applied from the top of the beam at 2 meters from the starting point and a parabolic ramp load of magnitude 2 N/m is applied below the beam starting from 2 meters to 3 meters away from the starting point of the beam. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(4, E, I) >>> b.apply_load(-3, 0, -2) >>> b.apply_load(4, 2, -1) >>> b.apply_load(-2, 2, 2, end=3) >>> b.load -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2) """ x = self.variable value = sympify(value) start = sympify(start) order = sympify(order) self._applied_loads.append((value, start, order, end)) self._load += value*SingularityFunction(x, start, order) self._original_load += value*SingularityFunction(x, start, order) if end: # load has an end point within the length of the beam. self._handle_end(x, value, start, order, end, type="apply") def remove_load(self, value, start, order, end=None): """ This method removes a particular load present on the beam object. Returns a ValueError if the load passed as an argument is not present on the beam. Parameters ========== value : Sympifyable The magnitude of an applied load. start : Sympifyable The starting point of the applied load. For point moments and point forces this is the location of application. order : Integer The order of the applied load. - For moments, order= -2 - For point loads, order=-1 - For constant distributed load, order=0 - For ramp loads, order=1 - For parabolic ramp loads, order=2 - ... so on. end : Sympifyable, optional An optional argument that can be used if the load has an end point within the length of the beam. Examples ======== There is a beam of length 4 meters. A moment of magnitude 3 Nm is applied in the clockwise direction at the starting point of the beam. A pointload of magnitude 4 N is applied from the top of the beam at 2 meters from the starting point and a parabolic ramp load of magnitude 2 N/m is applied below the beam starting from 2 meters to 3 meters away from the starting point of the beam. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(4, E, I) >>> b.apply_load(-3, 0, -2) >>> b.apply_load(4, 2, -1) >>> b.apply_load(-2, 2, 2, end=3) >>> b.load -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2) >>> b.remove_load(-2, 2, 2, end = 3) >>> b.load -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) """ x = self.variable value = sympify(value) start = sympify(start) order = sympify(order) if (value, start, order, end) in self._applied_loads: self._load -= value*SingularityFunction(x, start, order) self._original_load -= value*SingularityFunction(x, start, order) self._applied_loads.remove((value, start, order, end)) else: msg = "No such load distribution exists on the beam object." raise ValueError(msg) if end: # load has an end point within the length of the beam. self._handle_end(x, value, start, order, end, type="remove") def _handle_end(self, x, value, start, order, end, type): """ This functions handles the optional `end` value in the `apply_load` and `remove_load` functions. When the value of end is not NULL, this function will be executed. """ if order.is_negative: msg = ("If 'end' is provided the 'order' of the load cannot " "be negative, i.e. 'end' is only valid for distributed " "loads.") raise ValueError(msg) # NOTE : A Taylor series can be used to define the summation of # singularity functions that subtract from the load past the end # point such that it evaluates to zero past 'end'. f = value*x**order if type == "apply": # iterating for "apply_load" method for i in range(0, order + 1): self._load -= (f.diff(x, i).subs(x, end - start) * SingularityFunction(x, end, i)/factorial(i)) self._original_load -= (f.diff(x, i).subs(x, end - start) * SingularityFunction(x, end, i)/factorial(i)) elif type == "remove": # iterating for "remove_load" method for i in range(0, order + 1): self._load += (f.diff(x, i).subs(x, end - start) * SingularityFunction(x, end, i)/factorial(i)) self._original_load += (f.diff(x, i).subs(x, end - start) * SingularityFunction(x, end, i)/factorial(i)) @property def load(self): """ Returns a Singularity Function expression which represents the load distribution curve of the Beam object. Examples ======== There is a beam of length 4 meters. A moment of magnitude 3 Nm is applied in the clockwise direction at the starting point of the beam. A point load of magnitude 4 N is applied from the top of the beam at 2 meters from the starting point and a parabolic ramp load of magnitude 2 N/m is applied below the beam starting from 3 meters away from the starting point of the beam. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(4, E, I) >>> b.apply_load(-3, 0, -2) >>> b.apply_load(4, 2, -1) >>> b.apply_load(-2, 3, 2) >>> b.load -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 3, 2) """ return self._load @property def applied_loads(self): """ Returns a list of all loads applied on the beam object. Each load in the list is a tuple of form (value, start, order, end). Examples ======== There is a beam of length 4 meters. A moment of magnitude 3 Nm is applied in the clockwise direction at the starting point of the beam. A pointload of magnitude 4 N is applied from the top of the beam at 2 meters from the starting point. Another pointload of magnitude 5 N is applied at same position. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(4, E, I) >>> b.apply_load(-3, 0, -2) >>> b.apply_load(4, 2, -1) >>> b.apply_load(5, 2, -1) >>> b.load -3*SingularityFunction(x, 0, -2) + 9*SingularityFunction(x, 2, -1) >>> b.applied_loads [(-3, 0, -2, None), (4, 2, -1, None), (5, 2, -1, None)] """ return self._applied_loads def _solve_hinge_beams(self, *reactions): """Method to find integration constants and reactional variables in a composite beam connected via hinge. This method resolves the composite Beam into its sub-beams and then equations of shear force, bending moment, slope and deflection are evaluated for both of them separately. These equations are then solved for unknown reactions and integration constants using the boundary conditions applied on the Beam. Equal deflection of both sub-beams at the hinge joint gives us another equation to solve the system. Examples ======== A combined beam, with constant fkexural rigidity E*I, is formed by joining a Beam of length 2*l to the right of another Beam of length l. The whole beam is fixed at both of its both end. A point load of magnitude P is also applied from the top at a distance of 2*l from starting point. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> l=symbols('l', positive=True) >>> b1=Beam(l ,E,I) >>> b2=Beam(2*l ,E,I) >>> b=b1.join(b2,"hinge") >>> M1, A1, M2, A2, P = symbols('M1 A1 M2 A2 P') >>> b.apply_load(A1,0,-1) >>> b.apply_load(M1,0,-2) >>> b.apply_load(P,2*l,-1) >>> b.apply_load(A2,3*l,-1) >>> b.apply_load(M2,3*l,-2) >>> b.bc_slope=[(0,0), (3*l, 0)] >>> b.bc_deflection=[(0,0), (3*l, 0)] >>> b.solve_for_reaction_loads(M1, A1, M2, A2) >>> b.reaction_loads {A1: -5*P/18, A2: -13*P/18, M1: 5*P*l/18, M2: -4*P*l/9} >>> b.slope() (5*P*l*SingularityFunction(x, 0, 1)/18 - 5*P*SingularityFunction(x, 0, 2)/36 + 5*P*SingularityFunction(x, l, 2)/36)*SingularityFunction(x, 0, 0)/(E*I) - (5*P*l*SingularityFunction(x, 0, 1)/18 - 5*P*SingularityFunction(x, 0, 2)/36 + 5*P*SingularityFunction(x, l, 2)/36)*SingularityFunction(x, l, 0)/(E*I) + (P*l**2/18 - 4*P*l*SingularityFunction(-l + x, 2*l, 1)/9 - 5*P*SingularityFunction(-l + x, 0, 2)/36 + P*SingularityFunction(-l + x, l, 2)/2 - 13*P*SingularityFunction(-l + x, 2*l, 2)/36)*SingularityFunction(x, l, 0)/(E*I) >>> b.deflection() (5*P*l*SingularityFunction(x, 0, 2)/36 - 5*P*SingularityFunction(x, 0, 3)/108 + 5*P*SingularityFunction(x, l, 3)/108)*SingularityFunction(x, 0, 0)/(E*I) - (5*P*l*SingularityFunction(x, 0, 2)/36 - 5*P*SingularityFunction(x, 0, 3)/108 + 5*P*SingularityFunction(x, l, 3)/108)*SingularityFunction(x, l, 0)/(E*I) + (5*P*l**3/54 + P*l**2*(-l + x)/18 - 2*P*l*SingularityFunction(-l + x, 2*l, 2)/9 - 5*P*SingularityFunction(-l + x, 0, 3)/108 + P*SingularityFunction(-l + x, l, 3)/6 - 13*P*SingularityFunction(-l + x, 2*l, 3)/108)*SingularityFunction(x, l, 0)/(E*I) """ x = self.variable l = self._hinge_position E = self._elastic_modulus I = self._second_moment if isinstance(I, Piecewise): I1 = I.args[0][0] I2 = I.args[1][0] else: I1 = I2 = I load_1 = 0 # Load equation on first segment of composite beam load_2 = 0 # Load equation on second segment of composite beam # Distributing load on both segments for load in self.applied_loads: if load[1] < l: load_1 += load[0]*SingularityFunction(x, load[1], load[2]) if load[2] == 0: load_1 -= load[0]*SingularityFunction(x, load[3], load[2]) elif load[2] > 0: load_1 -= load[0]*SingularityFunction(x, load[3], load[2]) + load[0]*SingularityFunction(x, load[3], 0) elif load[1] == l: load_1 += load[0]*SingularityFunction(x, load[1], load[2]) load_2 += load[0]*SingularityFunction(x, load[1] - l, load[2]) elif load[1] > l: load_2 += load[0]*SingularityFunction(x, load[1] - l, load[2]) if load[2] == 0: load_2 -= load[0]*SingularityFunction(x, load[3] - l, load[2]) elif load[2] > 0: load_2 -= load[0]*SingularityFunction(x, load[3] - l, load[2]) + load[0]*SingularityFunction(x, load[3] - l, 0) h = Symbol('h') # Force due to hinge load_1 += h*SingularityFunction(x, l, -1) load_2 -= h*SingularityFunction(x, 0, -1) eq = [] shear_1 = integrate(load_1, x) shear_curve_1 = limit(shear_1, x, l) eq.append(shear_curve_1) bending_1 = integrate(shear_1, x) moment_curve_1 = limit(bending_1, x, l) eq.append(moment_curve_1) shear_2 = integrate(load_2, x) shear_curve_2 = limit(shear_2, x, self.length - l) eq.append(shear_curve_2) bending_2 = integrate(shear_2, x) moment_curve_2 = limit(bending_2, x, self.length - l) eq.append(moment_curve_2) C1 = Symbol('C1') C2 = Symbol('C2') C3 = Symbol('C3') C4 = Symbol('C4') slope_1 = S.One/(E*I1)*(integrate(bending_1, x) + C1) def_1 = S.One/(E*I1)*(integrate((E*I)*slope_1, x) + C1*x + C2) slope_2 = S.One/(E*I2)*(integrate(integrate(integrate(load_2, x), x), x) + C3) def_2 = S.One/(E*I2)*(integrate((E*I)*slope_2, x) + C4) for position, value in self.bc_slope: if position<l: eq.append(slope_1.subs(x, position) - value) else: eq.append(slope_2.subs(x, position - l) - value) for position, value in self.bc_deflection: if position<l: eq.append(def_1.subs(x, position) - value) else: eq.append(def_2.subs(x, position - l) - value) eq.append(def_1.subs(x, l) - def_2.subs(x, 0)) # Deflection of both the segments at hinge would be equal constants = list(linsolve(eq, C1, C2, C3, C4, h, *reactions)) reaction_values = list(constants[0])[5:] self._reaction_loads = dict(zip(reactions, reaction_values)) self._load = self._load.subs(self._reaction_loads) # Substituting constants and reactional load and moments with their corresponding values slope_1 = slope_1.subs({C1: constants[0][0], h:constants[0][4]}).subs(self._reaction_loads) def_1 = def_1.subs({C1: constants[0][0], C2: constants[0][1], h:constants[0][4]}).subs(self._reaction_loads) slope_2 = slope_2.subs({x: x-l, C3: constants[0][2], h:constants[0][4]}).subs(self._reaction_loads) def_2 = def_2.subs({x: x-l,C3: constants[0][2], C4: constants[0][3], h:constants[0][4]}).subs(self._reaction_loads) self._hinge_beam_slope = slope_1*SingularityFunction(x, 0, 0) - slope_1*SingularityFunction(x, l, 0) + slope_2*SingularityFunction(x, l, 0) self._hinge_beam_deflection = def_1*SingularityFunction(x, 0, 0) - def_1*SingularityFunction(x, l, 0) + def_2*SingularityFunction(x, l, 0) def solve_for_reaction_loads(self, *reactions): """ Solves for the reaction forces. Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(30, E, I) >>> b.apply_load(-8, 0, -1) >>> b.apply_load(R1, 10, -1) # Reaction force at x = 10 >>> b.apply_load(R2, 30, -1) # Reaction force at x = 30 >>> b.apply_load(120, 30, -2) >>> b.bc_deflection = [(10, 0), (30, 0)] >>> b.load R1*SingularityFunction(x, 10, -1) + R2*SingularityFunction(x, 30, -1) - 8*SingularityFunction(x, 0, -1) + 120*SingularityFunction(x, 30, -2) >>> b.solve_for_reaction_loads(R1, R2) >>> b.reaction_loads {R1: 6, R2: 2} >>> b.load -8*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 10, -1) + 120*SingularityFunction(x, 30, -2) + 2*SingularityFunction(x, 30, -1) """ if self._composite_type == "hinge": return self._solve_hinge_beams(*reactions) x = self.variable l = self.length C3 = Symbol('C3') C4 = Symbol('C4') shear_curve = limit(self.shear_force(), x, l) moment_curve = limit(self.bending_moment(), x, l) slope_eqs = [] deflection_eqs = [] slope_curve = integrate(self.bending_moment(), x) + C3 for position, value in self._boundary_conditions['slope']: eqs = slope_curve.subs(x, position) - value slope_eqs.append(eqs) deflection_curve = integrate(slope_curve, x) + C4 for position, value in self._boundary_conditions['deflection']: eqs = deflection_curve.subs(x, position) - value deflection_eqs.append(eqs) solution = list((linsolve([shear_curve, moment_curve] + slope_eqs + deflection_eqs, (C3, C4) + reactions).args)[0]) solution = solution[2:] self._reaction_loads = dict(zip(reactions, solution)) self._load = self._load.subs(self._reaction_loads) def shear_force(self): """ Returns a Singularity Function expression which represents the shear force curve of the Beam object. Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(30, E, I) >>> b.apply_load(-8, 0, -1) >>> b.apply_load(R1, 10, -1) >>> b.apply_load(R2, 30, -1) >>> b.apply_load(120, 30, -2) >>> b.bc_deflection = [(10, 0), (30, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.shear_force() 8*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 10, 0) - 120*SingularityFunction(x, 30, -1) - 2*SingularityFunction(x, 30, 0) """ x = self.variable return -integrate(self.load, x) def max_shear_force(self): """Returns maximum Shear force and its coordinate in the Beam object.""" from sympy import solve, Mul, Interval shear_curve = self.shear_force() x = self.variable terms = shear_curve.args singularity = [] # Points at which shear function changes for term in terms: if isinstance(term, Mul): term = term.args[-1] # SingularityFunction in the term singularity.append(term.args[1]) singularity.sort() singularity = list(set(singularity)) intervals = [] # List of Intervals with discrete value of shear force shear_values = [] # List of values of shear force in each interval for i, s in enumerate(singularity): if s == 0: continue try: shear_slope = Piecewise((float("nan"), x<=singularity[i-1]),(self._load.rewrite(Piecewise), x<s), (float("nan"), True)) points = solve(shear_slope, x) val = [] for point in points: val.append(shear_curve.subs(x, point)) points.extend([singularity[i-1], s]) val.extend([limit(shear_curve, x, singularity[i-1], '+'), limit(shear_curve, x, s, '-')]) val = list(map(abs, val)) max_shear = max(val) shear_values.append(max_shear) intervals.append(points[val.index(max_shear)]) # If shear force in a particular Interval has zero or constant # slope, then above block gives NotImplementedError as # solve can't represent Interval solutions. except NotImplementedError: initial_shear = limit(shear_curve, x, singularity[i-1], '+') final_shear = limit(shear_curve, x, s, '-') # If shear_curve has a constant slope(it is a line). if shear_curve.subs(x, (singularity[i-1] + s)/2) == (initial_shear + final_shear)/2 and initial_shear != final_shear: shear_values.extend([initial_shear, final_shear]) intervals.extend([singularity[i-1], s]) else: # shear_curve has same value in whole Interval shear_values.append(final_shear) intervals.append(Interval(singularity[i-1], s)) shear_values = list(map(abs, shear_values)) maximum_shear = max(shear_values) point = intervals[shear_values.index(maximum_shear)] return (point, maximum_shear) def bending_moment(self): """ Returns a Singularity Function expression which represents the bending moment curve of the Beam object. Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(30, E, I) >>> b.apply_load(-8, 0, -1) >>> b.apply_load(R1, 10, -1) >>> b.apply_load(R2, 30, -1) >>> b.apply_load(120, 30, -2) >>> b.bc_deflection = [(10, 0), (30, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.bending_moment() 8*SingularityFunction(x, 0, 1) - 6*SingularityFunction(x, 10, 1) - 120*SingularityFunction(x, 30, 0) - 2*SingularityFunction(x, 30, 1) """ x = self.variable return integrate(self.shear_force(), x) def max_bmoment(self): """Returns maximum Shear force and its coordinate in the Beam object.""" from sympy import solve, Mul, Interval bending_curve = self.bending_moment() x = self.variable terms = bending_curve.args singularity = [] # Points at which bending moment changes for term in terms: if isinstance(term, Mul): term = term.args[-1] # SingularityFunction in the term singularity.append(term.args[1]) singularity.sort() singularity = list(set(singularity)) intervals = [] # List of Intervals with discrete value of bending moment moment_values = [] # List of values of bending moment in each interval for i, s in enumerate(singularity): if s == 0: continue try: moment_slope = Piecewise((float("nan"), x<=singularity[i-1]),(self.shear_force().rewrite(Piecewise), x<s), (float("nan"), True)) points = solve(moment_slope, x) val = [] for point in points: val.append(bending_curve.subs(x, point)) points.extend([singularity[i-1], s]) val.extend([limit(bending_curve, x, singularity[i-1], '+'), limit(bending_curve, x, s, '-')]) val = list(map(abs, val)) max_moment = max(val) moment_values.append(max_moment) intervals.append(points[val.index(max_moment)]) # If bending moment in a particular Interval has zero or constant # slope, then above block gives NotImplementedError as solve # can't represent Interval solutions. except NotImplementedError: initial_moment = limit(bending_curve, x, singularity[i-1], '+') final_moment = limit(bending_curve, x, s, '-') # If bending_curve has a constant slope(it is a line). if bending_curve.subs(x, (singularity[i-1] + s)/2) == (initial_moment + final_moment)/2 and initial_moment != final_moment: moment_values.extend([initial_moment, final_moment]) intervals.extend([singularity[i-1], s]) else: # bending_curve has same value in whole Interval moment_values.append(final_moment) intervals.append(Interval(singularity[i-1], s)) moment_values = list(map(abs, moment_values)) maximum_moment = max(moment_values) point = intervals[moment_values.index(maximum_moment)] return (point, maximum_moment) def point_cflexure(self): """ Returns a Set of point(s) with zero bending moment and where bending moment curve of the beam object changes its sign from negative to positive or vice versa. Examples ======== There is is 10 meter long overhanging beam. There are two simple supports below the beam. One at the start and another one at a distance of 6 meters from the start. Point loads of magnitude 10KN and 20KN are applied at 2 meters and 4 meters from start respectively. A Uniformly distribute load of magnitude of magnitude 3KN/m is also applied on top starting from 6 meters away from starting point till end. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(10, E, I) >>> b.apply_load(-4, 0, -1) >>> b.apply_load(-46, 6, -1) >>> b.apply_load(10, 2, -1) >>> b.apply_load(20, 4, -1) >>> b.apply_load(3, 6, 0) >>> b.point_cflexure() [10/3] """ from sympy import solve, Piecewise # To restrict the range within length of the Beam moment_curve = Piecewise((float("nan"), self.variable<=0), (self.bending_moment(), self.variable<self.length), (float("nan"), True)) points = solve(moment_curve.rewrite(Piecewise), self.variable, domain=S.Reals) return points def slope(self): """ Returns a Singularity Function expression which represents the slope the elastic curve of the Beam object. Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(30, E, I) >>> b.apply_load(-8, 0, -1) >>> b.apply_load(R1, 10, -1) >>> b.apply_load(R2, 30, -1) >>> b.apply_load(120, 30, -2) >>> b.bc_deflection = [(10, 0), (30, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.slope() (-4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2) + 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + 4000/3)/(E*I) """ x = self.variable E = self.elastic_modulus I = self.second_moment if self._composite_type == "hinge": return self._hinge_beam_slope if not self._boundary_conditions['slope']: return diff(self.deflection(), x) if isinstance(I, Piecewise) and self._composite_type == "fixed": args = I.args slope = 0 prev_slope = 0 prev_end = 0 for i in range(len(args)): if i != 0: prev_end = args[i-1][1].args[1] slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x)) if i != len(args) - 1: slope += (prev_slope + slope_value)*SingularityFunction(x, prev_end, 0) - \ (prev_slope + slope_value)*SingularityFunction(x, args[i][1].args[1], 0) else: slope += (prev_slope + slope_value)*SingularityFunction(x, prev_end, 0) prev_slope = slope_value.subs(x, args[i][1].args[1]) return slope C3 = Symbol('C3') slope_curve = -integrate(S.One/(E*I)*self.bending_moment(), x) + C3 bc_eqs = [] for position, value in self._boundary_conditions['slope']: eqs = slope_curve.subs(x, position) - value bc_eqs.append(eqs) constants = list(linsolve(bc_eqs, C3)) slope_curve = slope_curve.subs({C3: constants[0][0]}) return slope_curve def deflection(self): """ Returns a Singularity Function expression which represents the elastic curve or deflection of the Beam object. Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(30, E, I) >>> b.apply_load(-8, 0, -1) >>> b.apply_load(R1, 10, -1) >>> b.apply_load(R2, 30, -1) >>> b.apply_load(120, 30, -2) >>> b.bc_deflection = [(10, 0), (30, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.deflection() (4000*x/3 - 4*SingularityFunction(x, 0, 3)/3 + SingularityFunction(x, 10, 3) + 60*SingularityFunction(x, 30, 2) + SingularityFunction(x, 30, 3)/3 - 12000)/(E*I) """ x = self.variable E = self.elastic_modulus I = self.second_moment if self._composite_type == "hinge": return self._hinge_beam_deflection if not self._boundary_conditions['deflection'] and not self._boundary_conditions['slope']: if isinstance(I, Piecewise) and self._composite_type == "fixed": args = I.args prev_slope = 0 prev_def = 0 prev_end = 0 deflection = 0 for i in range(len(args)): if i != 0: prev_end = args[i-1][1].args[1] slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x)) recent_segment_slope = prev_slope + slope_value deflection_value = integrate(recent_segment_slope, (x, prev_end, x)) if i != len(args) - 1: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \ - (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0) else: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) prev_slope = slope_value.subs(x, args[i][1].args[1]) prev_def = deflection_value.subs(x, args[i][1].args[1]) return deflection base_char = self._base_char constants = symbols(base_char + '3:5') return S.One/(E*I)*integrate(-integrate(self.bending_moment(), x), x) + constants[0]*x + constants[1] elif not self._boundary_conditions['deflection']: base_char = self._base_char constant = symbols(base_char + '4') return integrate(self.slope(), x) + constant elif not self._boundary_conditions['slope'] and self._boundary_conditions['deflection']: if isinstance(I, Piecewise) and self._composite_type == "fixed": args = I.args prev_slope = 0 prev_def = 0 prev_end = 0 deflection = 0 for i in range(len(args)): if i != 0: prev_end = args[i-1][1].args[1] slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x)) recent_segment_slope = prev_slope + slope_value deflection_value = integrate(recent_segment_slope, (x, prev_end, x)) if i != len(args) - 1: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \ - (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0) else: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) prev_slope = slope_value.subs(x, args[i][1].args[1]) prev_def = deflection_value.subs(x, args[i][1].args[1]) return deflection base_char = self._base_char C3, C4 = symbols(base_char + '3:5') # Integration constants slope_curve = -integrate(self.bending_moment(), x) + C3 deflection_curve = integrate(slope_curve, x) + C4 bc_eqs = [] for position, value in self._boundary_conditions['deflection']: eqs = deflection_curve.subs(x, position) - value bc_eqs.append(eqs) constants = list(linsolve(bc_eqs, (C3, C4))) deflection_curve = deflection_curve.subs({C3: constants[0][0], C4: constants[0][1]}) return S.One/(E*I)*deflection_curve if isinstance(I, Piecewise) and self._composite_type == "fixed": args = I.args prev_slope = 0 prev_def = 0 prev_end = 0 deflection = 0 for i in range(len(args)): if i != 0: prev_end = args[i-1][1].args[1] slope_value = S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x)) recent_segment_slope = prev_slope + slope_value deflection_value = integrate(recent_segment_slope, (x, prev_end, x)) if i != len(args) - 1: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \ - (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0) else: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) prev_slope = slope_value.subs(x, args[i][1].args[1]) prev_def = deflection_value.subs(x, args[i][1].args[1]) return deflection C4 = Symbol('C4') deflection_curve = integrate(self.slope(), x) + C4 bc_eqs = [] for position, value in self._boundary_conditions['deflection']: eqs = deflection_curve.subs(x, position) - value bc_eqs.append(eqs) constants = list(linsolve(bc_eqs, C4)) deflection_curve = deflection_curve.subs({C4: constants[0][0]}) return deflection_curve def max_deflection(self): """ Returns point of max deflection and its corresponding deflection value in a Beam object. """ from sympy import solve, Piecewise # To restrict the range within length of the Beam slope_curve = Piecewise((float("nan"), self.variable<=0), (self.slope(), self.variable<self.length), (float("nan"), True)) points = solve(slope_curve.rewrite(Piecewise), self.variable, domain=S.Reals) deflection_curve = self.deflection() deflections = [deflection_curve.subs(self.variable, x) for x in points] deflections = list(map(abs, deflections)) if len(deflections) != 0: max_def = max(deflections) return (points[deflections.index(max_def)], max_def) else: return None def shear_stress(self): """ Returns an expression representing the Shear Stress curve of the Beam object. """ return self.shear_force()/self._area def plot_shear_stress(self, subs=None): """ Returns a plot of shear stress present in the beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters and area of cross section 2 square meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6), 2) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.plot_shear_stress() Plot object containing: [0]: cartesian line: 6875*SingularityFunction(x, 0, 0) - 2500*SingularityFunction(x, 2, 0) - 5000*SingularityFunction(x, 4, 1) + 15625*SingularityFunction(x, 8, 0) + 5000*SingularityFunction(x, 8, 1) for x over (0.0, 8.0) """ shear_stress = self.shear_stress() x = self.variable length = self.length if subs is None: subs = {} for sym in shear_stress.atoms(Symbol): if sym != x and sym not in subs: raise ValueError('value of %s was not passed.' %sym) if length in subs: length = subs[length] # Returns Plot of Shear Stress return plot (shear_stress.subs(subs), (x, 0, length), title='Shear Stress', xlabel=r'$\mathrm{x}$', ylabel=r'$\tau$', line_color='r') def plot_shear_force(self, subs=None): """ Returns a plot for Shear force present in the Beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6)) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.plot_shear_force() Plot object containing: [0]: cartesian line: 13750*SingularityFunction(x, 0, 0) - 5000*SingularityFunction(x, 2, 0) - 10000*SingularityFunction(x, 4, 1) + 31250*SingularityFunction(x, 8, 0) + 10000*SingularityFunction(x, 8, 1) for x over (0.0, 8.0) """ shear_force = self.shear_force() if subs is None: subs = {} for sym in shear_force.atoms(Symbol): if sym == self.variable: continue if sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(shear_force.subs(subs), (self.variable, 0, length), title='Shear Force', xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{V}$', line_color='g') def plot_bending_moment(self, subs=None): """ Returns a plot for Bending moment present in the Beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6)) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.plot_bending_moment() Plot object containing: [0]: cartesian line: 13750*SingularityFunction(x, 0, 1) - 5000*SingularityFunction(x, 2, 1) - 5000*SingularityFunction(x, 4, 2) + 31250*SingularityFunction(x, 8, 1) + 5000*SingularityFunction(x, 8, 2) for x over (0.0, 8.0) """ bending_moment = self.bending_moment() if subs is None: subs = {} for sym in bending_moment.atoms(Symbol): if sym == self.variable: continue if sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(bending_moment.subs(subs), (self.variable, 0, length), title='Bending Moment', xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{M}$', line_color='b') def plot_slope(self, subs=None): """ Returns a plot for slope of deflection curve of the Beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6)) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.plot_slope() Plot object containing: [0]: cartesian line: -8.59375e-5*SingularityFunction(x, 0, 2) + 3.125e-5*SingularityFunction(x, 2, 2) + 2.08333333333333e-5*SingularityFunction(x, 4, 3) - 0.0001953125*SingularityFunction(x, 8, 2) - 2.08333333333333e-5*SingularityFunction(x, 8, 3) + 0.00138541666666667 for x over (0.0, 8.0) """ slope = self.slope() if subs is None: subs = {} for sym in slope.atoms(Symbol): if sym == self.variable: continue if sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(slope.subs(subs), (self.variable, 0, length), title='Slope', xlabel=r'$\mathrm{x}$', ylabel=r'$\theta$', line_color='m') def plot_deflection(self, subs=None): """ Returns a plot for deflection curve of the Beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6)) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.plot_deflection() Plot object containing: [0]: cartesian line: 0.00138541666666667*x - 2.86458333333333e-5*SingularityFunction(x, 0, 3) + 1.04166666666667e-5*SingularityFunction(x, 2, 3) + 5.20833333333333e-6*SingularityFunction(x, 4, 4) - 6.51041666666667e-5*SingularityFunction(x, 8, 3) - 5.20833333333333e-6*SingularityFunction(x, 8, 4) for x over (0.0, 8.0) """ deflection = self.deflection() if subs is None: subs = {} for sym in deflection.atoms(Symbol): if sym == self.variable: continue if sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(deflection.subs(subs), (self.variable, 0, length), title='Deflection', xlabel=r'$\mathrm{x}$', ylabel=r'$\delta$', line_color='r') def plot_loading_results(self, subs=None): """ Returns a subplot of Shear Force, Bending Moment, Slope and Deflection of the Beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6)) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> axes = b.plot_loading_results() """ length = self.length variable = self.variable if subs is None: subs = {} for sym in self.deflection().atoms(Symbol): if sym == self.variable: continue if sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if length in subs: length = subs[length] ax1 = plot(self.shear_force().subs(subs), (variable, 0, length), title="Shear Force", xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{V}$', line_color='g', show=False) ax2 = plot(self.bending_moment().subs(subs), (variable, 0, length), title="Bending Moment", xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{M}$', line_color='b', show=False) ax3 = plot(self.slope().subs(subs), (variable, 0, length), title="Slope", xlabel=r'$\mathrm{x}$', ylabel=r'$\theta$', line_color='m', show=False) ax4 = plot(self.deflection().subs(subs), (variable, 0, length), title="Deflection", xlabel=r'$\mathrm{x}$', ylabel=r'$\delta$', line_color='r', show=False) return PlotGrid(4, 1, ax1, ax2, ax3, ax4) def _solve_for_ild_equations(self): """ Helper function for I.L.D. It takes the unsubstituted copy of the load equation and uses it to calculate shear force and bending moment equations. """ x = self.variable shear_force = -integrate(self._original_load, x) bending_moment = integrate(shear_force, x) return shear_force, bending_moment def solve_for_ild_reactions(self, value, *reactions): """ Determines the Influence Line Diagram equations for reaction forces under the effect of a moving load. Parameters ========== value : Integer Magnitude of moving load reactions : The reaction forces applied on the beam. Examples ======== There is a beam of length 10 meters. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. Calculate the I.L.D. equations for reaction forces under the effect of a moving load of magnitude 1kN. .. image:: ildreaction.png Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.physics.continuum_mechanics.beam import Beam >>> E, I = symbols('E, I') >>> R_0, R_10 = symbols('R_0, R_10') >>> b = Beam(10, E, I) >>> b.apply_support(0, 'roller') >>> b.apply_support(10, 'roller') >>> b.solve_for_ild_reactions(1,R_0,R_10) >>> b.ild_reactions {R_0: x/10 - 1, R_10: -x/10} """ shear_force, bending_moment = self._solve_for_ild_equations() x = self.variable l = self.length C3 = Symbol('C3') C4 = Symbol('C4') shear_curve = limit(shear_force, x, l) - value moment_curve = limit(bending_moment, x, l) - value*(l-x) slope_eqs = [] deflection_eqs = [] slope_curve = integrate(bending_moment, x) + C3 for position, value in self._boundary_conditions['slope']: eqs = slope_curve.subs(x, position) - value slope_eqs.append(eqs) deflection_curve = integrate(slope_curve, x) + C4 for position, value in self._boundary_conditions['deflection']: eqs = deflection_curve.subs(x, position) - value deflection_eqs.append(eqs) solution = list((linsolve([shear_curve, moment_curve] + slope_eqs + deflection_eqs, (C3, C4) + reactions).args)[0]) solution = solution[2:] # Determining the equations and solving them. self._ild_reactions = dict(zip(reactions, solution)) def plot_ild_reactions(self, subs=None): """ Plots the Influence Line Diagram of Reaction Forces under the effect of a moving load. This function should be called after calling solve_for_ild_reactions(). Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 10 meters. A point load of magnitude 5KN is also applied from top of the beam, at a distance of 4 meters from the starting point. There are two simple supports below the beam, located at the starting point and at a distance of 7 meters from the starting point. Plot the I.L.D. equations for reactions at both support points under the effect of a moving load of magnitude 1kN. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.physics.continuum_mechanics.beam import Beam >>> E, I = symbols('E, I') >>> R_0, R_7 = symbols('R_0, R_7') >>> b = Beam(10, E, I) >>> b.apply_support(0, 'roller') >>> b.apply_support(7, 'roller') >>> b.apply_load(5,4,-1) >>> b.solve_for_ild_reactions(1,R_0,R_7) >>> b.ild_reactions {R_0: x/7 - 22/7, R_7: -x/7 - 20/7} >>> b.plot_ild_reactions() PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: x/7 - 22/7 for x over (0.0, 10.0) Plot[1]:Plot object containing: [0]: cartesian line: -x/7 - 20/7 for x over (0.0, 10.0) """ if not self._ild_reactions: raise ValueError("I.L.D. reaction equations not found. Please use solve_for_ild_reactions() to generate the I.L.D. reaction equations.") x = self.variable ildplots = [] if subs is None: subs = {} for reaction in self._ild_reactions: for sym in self._ild_reactions[reaction].atoms(Symbol): if sym != x and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) for sym in self._length.atoms(Symbol): if sym != x and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) for reaction in self._ild_reactions: ildplots.append(plot(self._ild_reactions[reaction].subs(subs), (x, 0, self._length.subs(subs)), title='I.L.D. for Reactions', xlabel=x, ylabel=reaction, line_color='blue', show=False)) return PlotGrid(len(ildplots), 1, *ildplots) def solve_for_ild_shear(self, distance, value, *reactions): """ Determines the Influence Line Diagram equations for shear at a specified point under the effect of a moving load. Parameters ========== distance : Integer Distance of the point from the start of the beam for which equations are to be determined value : Integer Magnitude of moving load reactions : The reaction forces applied on the beam. Examples ======== There is a beam of length 12 meters. There are two simple supports below the beam, one at the starting point and another at a distance of 8 meters. Calculate the I.L.D. equations for Shear at a distance of 4 meters under the effect of a moving load of magnitude 1kN. .. image:: ildshear.png Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.physics.continuum_mechanics.beam import Beam >>> E, I = symbols('E, I') >>> R_0, R_8 = symbols('R_0, R_8') >>> b = Beam(12, E, I) >>> b.apply_support(0, 'roller') >>> b.apply_support(8, 'roller') >>> b.solve_for_ild_reactions(1, R_0, R_8) >>> b.solve_for_ild_shear(4, 1, R_0, R_8) >>> b.ild_shear Piecewise((x/8, x < 4), (x/8 - 1, x > 4)) """ x = self.variable l = self.length shear_force, _ = self._solve_for_ild_equations() shear_curve1 = value - limit(shear_force, x, distance) shear_curve2 = (limit(shear_force, x, l) - limit(shear_force, x, distance)) - value for reaction in reactions: shear_curve1 = shear_curve1.subs(reaction,self._ild_reactions[reaction]) shear_curve2 = shear_curve2.subs(reaction,self._ild_reactions[reaction]) shear_eq = Piecewise((shear_curve1, x < distance), (shear_curve2, x > distance)) self._ild_shear = shear_eq def plot_ild_shear(self,subs=None): """ Plots the Influence Line Diagram for Shear under the effect of a moving load. This function should be called after calling solve_for_ild_shear(). Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 12 meters. There are two simple supports below the beam, one at the starting point and another at a distance of 8 meters. Plot the I.L.D. for Shear at a distance of 4 meters under the effect of a moving load of magnitude 1kN. .. image:: ildshear.png Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.physics.continuum_mechanics.beam import Beam >>> E, I = symbols('E, I') >>> R_0, R_8 = symbols('R_0, R_8') >>> b = Beam(12, E, I) >>> b.apply_support(0, 'roller') >>> b.apply_support(8, 'roller') >>> b.solve_for_ild_reactions(1, R_0, R_8) >>> b.solve_for_ild_shear(4, 1, R_0, R_8) >>> b.ild_shear Piecewise((x/8, x < 4), (x/8 - 1, x > 4)) >>> b.plot_ild_shear() Plot object containing: [0]: cartesian line: Piecewise((x/8, x < 4), (x/8 - 1, x > 4)) for x over (0.0, 12.0) """ if not self._ild_shear: raise ValueError("I.L.D. shear equation not found. Please use solve_for_ild_shear() to generate the I.L.D. shear equations.") x = self.variable l = self._length if subs is None: subs = {} for sym in self._ild_shear.atoms(Symbol): if sym != x and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) for sym in self._length.atoms(Symbol): if sym != x and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) return plot(self._ild_shear.subs(subs), (x, 0, l), title='I.L.D. for Shear', xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{V}$', line_color='blue',show=True) def solve_for_ild_moment(self, distance, value, *reactions): """ Determines the Influence Line Diagram equations for moment at a specified point under the effect of a moving load. Parameters ========== distance : Integer Distance of the point from the start of the beam for which equations are to be determined value : Integer Magnitude of moving load reactions : The reaction forces applied on the beam. Examples ======== There is a beam of length 12 meters. There are two simple supports below the beam, one at the starting point and another at a distance of 8 meters. Calculate the I.L.D. equations for Moment at a distance of 4 meters under the effect of a moving load of magnitude 1kN. .. image:: ildshear.png Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.physics.continuum_mechanics.beam import Beam >>> E, I = symbols('E, I') >>> R_0, R_8 = symbols('R_0, R_8') >>> b = Beam(12, E, I) >>> b.apply_support(0, 'roller') >>> b.apply_support(8, 'roller') >>> b.solve_for_ild_reactions(1, R_0, R_8) >>> b.solve_for_ild_moment(4, 1, R_0, R_8) >>> b.ild_moment Piecewise((-x/2, x < 4), (x/2 - 4, x > 4)) """ x = self.variable l = self.length _ , moment = self._solve_for_ild_equations() moment_curve1 = value*(distance-x) - limit(moment, x, distance) moment_curve2= (limit(moment, x, l)-limit(moment, x, distance))-value*(l-x) for reaction in reactions: moment_curve1 = moment_curve1.subs(reaction, self._ild_reactions[reaction]) moment_curve2 = moment_curve2.subs(reaction, self._ild_reactions[reaction]) moment_eq = Piecewise((moment_curve1, x < distance), (moment_curve2, x > distance)) self._ild_moment = moment_eq def plot_ild_moment(self,subs=None): """ Plots the Influence Line Diagram for Moment under the effect of a moving load. This function should be called after calling solve_for_ild_moment(). Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 12 meters. There are two simple supports below the beam, one at the starting point and another at a distance of 8 meters. Plot the I.L.D. for Moment at a distance of 4 meters under the effect of a moving load of magnitude 1kN. .. image:: ildshear.png Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.physics.continuum_mechanics.beam import Beam >>> E, I = symbols('E, I') >>> R_0, R_8 = symbols('R_0, R_8') >>> b = Beam(12, E, I) >>> b.apply_support(0, 'roller') >>> b.apply_support(8, 'roller') >>> b.solve_for_ild_reactions(1, R_0, R_8) >>> b.solve_for_ild_moment(4, 1, R_0, R_8) >>> b.ild_moment Piecewise((-x/2, x < 4), (x/2 - 4, x > 4)) >>> b.plot_ild_moment() Plot object containing: [0]: cartesian line: Piecewise((-x/2, x < 4), (x/2 - 4, x > 4)) for x over (0.0, 12.0) """ if not self._ild_moment: raise ValueError("I.L.D. moment equation not found. Please use solve_for_ild_moment() to generate the I.L.D. moment equations.") x = self.variable if subs is None: subs = {} for sym in self._ild_moment.atoms(Symbol): if sym != x and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) for sym in self._length.atoms(Symbol): if sym != x and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) return plot(self._ild_moment.subs(subs), (x, 0, self._length), title='I.L.D. for Moment', xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{M}$', line_color='blue', show=True) @doctest_depends_on(modules=('numpy',)) def draw(self, pictorial=True): """ Returns a plot object representing the beam diagram of the beam. .. note:: The user must be careful while entering load values. The draw function assumes a sign convention which is used for plotting loads. Given a right handed coordinate system with XYZ coordinates, the beam's length is assumed to be along the positive X axis. The draw function recognizes positve loads(with n>-2) as loads acting along negative Y direction and positve moments acting along positive Z direction. Parameters ========== pictorial: Boolean (default=True) Setting ``pictorial=True`` would simply create a pictorial (scaled) view of the beam diagram not with the exact dimensions. Although setting ``pictorial=False`` would create a beam diagram with the exact dimensions on the plot Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> E, I = symbols('E, I') >>> b = Beam(50, 20, 30) >>> b.apply_load(10, 2, -1) >>> b.apply_load(R1, 10, -1) >>> b.apply_load(R2, 30, -1) >>> b.apply_load(90, 5, 0, 23) >>> b.apply_load(10, 30, 1, 50) >>> b.apply_support(50, "pin") >>> b.apply_support(0, "fixed") >>> b.apply_support(20, "roller") >>> p = b.draw() >>> p Plot object containing: [0]: cartesian line: 25*SingularityFunction(x, 5, 0) - 25*SingularityFunction(x, 23, 0) + SingularityFunction(x, 30, 1) - 20*SingularityFunction(x, 50, 0) - SingularityFunction(x, 50, 1) + 5 for x over (0.0, 50.0) [1]: cartesian line: 5 for x over (0.0, 50.0) >>> p.show() """ if not numpy: raise ImportError("To use this function numpy module is required") x = self.variable # checking whether length is an expression in terms of any Symbol. from sympy import Expr if isinstance(self.length, Expr): l = list(self.length.atoms(Symbol)) # assigning every Symbol a default value of 10 l = {i:10 for i in l} length = self.length.subs(l) else: l = {} length = self.length height = length/10 rectangles = [] rectangles.append({'xy':(0, 0), 'width':length, 'height': height, 'facecolor':"brown"}) annotations, markers, load_eq,load_eq1, fill = self._draw_load(pictorial, length, l) support_markers, support_rectangles = self._draw_supports(length, l) rectangles += support_rectangles markers += support_markers sing_plot = plot(height + load_eq, height + load_eq1, (x, 0, length), xlim=(-height, length + height), ylim=(-length, 1.25*length), annotations=annotations, markers=markers, rectangles=rectangles, line_color='brown', fill=fill, axis=False, show=False) return sing_plot def _draw_load(self, pictorial, length, l): loads = list(set(self.applied_loads) - set(self._support_as_loads)) height = length/10 x = self.variable annotations = [] markers = [] load_args = [] scaled_load = 0 load_args1 = [] scaled_load1 = 0 load_eq = 0 # For positive valued higher order loads load_eq1 = 0 # For negative valued higher order loads fill = None plus = 0 # For positive valued higher order loads minus = 0 # For negative valued higher order loads for load in loads: # check if the position of load is in terms of the beam length. if l: pos = load[1].subs(l) else: pos = load[1] # point loads if load[2] == -1: if isinstance(load[0], Symbol) or load[0].is_negative: annotations.append({'s':'', 'xy':(pos, 0), 'xytext':(pos, height - 4*height), 'arrowprops':dict(width= 1.5, headlength=5, headwidth=5, facecolor='black')}) else: annotations.append({'s':'', 'xy':(pos, height), 'xytext':(pos, height*4), 'arrowprops':dict(width= 1.5, headlength=4, headwidth=4, facecolor='black')}) # moment loads elif load[2] == -2: if load[0].is_negative: markers.append({'args':[[pos], [height/2]], 'marker': r'$\circlearrowright$', 'markersize':15}) else: markers.append({'args':[[pos], [height/2]], 'marker': r'$\circlearrowleft$', 'markersize':15}) # higher order loads elif load[2] >= 0: # `fill` will be assigned only when higher order loads are present value, start, order, end = load # Positive loads have their seperate equations if(value>0): plus = 1 # if pictorial is True we remake the load equation again with # some constant magnitude values. if pictorial: value = 10**(1-order) if order > 0 else length/2 scaled_load += value*SingularityFunction(x, start, order) if end: f2 = 10**(1-order)*x**order if order > 0 else length/2*x**order for i in range(0, order + 1): scaled_load -= (f2.diff(x, i).subs(x, end - start)* SingularityFunction(x, end, i)/factorial(i)) if pictorial: if isinstance(scaled_load, Add): load_args = scaled_load.args else: # when the load equation consists of only a single term load_args = (scaled_load,) load_eq = [i.subs(l) for i in load_args] else: if isinstance(self.load, Add): load_args = self.load.args else: load_args = (self.load,) load_eq = [i.subs(l) for i in load_args if list(i.atoms(SingularityFunction))[0].args[2] >= 0] load_eq = Add(*load_eq) # filling higher order loads with colour expr = height + load_eq.rewrite(Piecewise) y1 = lambdify(x, expr, 'numpy') # For loads with negative value else: minus = 1 # if pictorial is True we remake the load equation again with # some constant magnitude values. if pictorial: value = 10**(1-order) if order > 0 else length/2 scaled_load1 += value*SingularityFunction(x, start, order) if end: f2 = 10**(1-order)*x**order if order > 0 else length/2*x**order for i in range(0, order + 1): scaled_load1 -= (f2.diff(x, i).subs(x, end - start)* SingularityFunction(x, end, i)/factorial(i)) if pictorial: if isinstance(scaled_load1, Add): load_args1 = scaled_load1.args else: # when the load equation consists of only a single term load_args1 = (scaled_load1,) load_eq1 = [i.subs(l) for i in load_args1] else: if isinstance(self.load, Add): load_args1 = self.load.args1 else: load_args1 = (self.load,) load_eq1 = [i.subs(l) for i in load_args if list(i.atoms(SingularityFunction))[0].args[2] >= 0] load_eq1 = -Add(*load_eq1)-height # filling higher order loads with colour expr = height + load_eq1.rewrite(Piecewise) y1_ = lambdify(x, expr, 'numpy') y = numpy.arange(0, float(length), 0.001) y2 = float(height) if(plus == 1 and minus == 1): fill = {'x': y, 'y1': y1(y), 'y2': y1_(y), 'color':'darkkhaki'} elif(plus == 1): fill = {'x': y, 'y1': y1(y), 'y2': y2, 'color':'darkkhaki'} else: fill = {'x': y, 'y1': y1_(y), 'y2': y2 , 'color':'darkkhaki'} return annotations, markers, load_eq, load_eq1, fill def _draw_supports(self, length, l): height = float(length/10) support_markers = [] support_rectangles = [] for support in self._applied_supports: if l: pos = support[0].subs(l) else: pos = support[0] if support[1] == "pin": support_markers.append({'args':[pos, [0]], 'marker':6, 'markersize':13, 'color':"black"}) elif support[1] == "roller": support_markers.append({'args':[pos, [-height/2.5]], 'marker':'o', 'markersize':11, 'color':"black"}) elif support[1] == "fixed": if pos == 0: support_rectangles.append({'xy':(0, -3*height), 'width':-length/20, 'height':6*height + height, 'fill':False, 'hatch':'/////'}) else: support_rectangles.append({'xy':(length, -3*height), 'width':length/20, 'height': 6*height + height, 'fill':False, 'hatch':'/////'}) return support_markers, support_rectangles class Beam3D(Beam): """ This class handles loads applied in any direction of a 3D space along with unequal values of Second moment along different axes. .. note:: While solving a beam bending problem, a user should choose its own sign convention and should stick to it. The results will automatically follow the chosen sign convention. This class assumes that any kind of distributed load/moment is applied through out the span of a beam. Examples ======== There is a beam of l meters long. A constant distributed load of magnitude q is applied along y-axis from start till the end of beam. A constant distributed moment of magnitude m is also applied along z-axis from start till the end of beam. Beam is fixed at both of its end. So, deflection of the beam at the both ends is restricted. >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols, simplify, collect, factor >>> l, E, G, I, A = symbols('l, E, G, I, A') >>> b = Beam3D(l, E, G, I, A) >>> x, q, m = symbols('x, q, m') >>> b.apply_load(q, 0, 0, dir="y") >>> b.apply_moment_load(m, 0, -1, dir="z") >>> b.shear_force() [0, -q*x, 0] >>> b.bending_moment() [0, 0, -m*x + q*x**2/2] >>> b.bc_slope = [(0, [0, 0, 0]), (l, [0, 0, 0])] >>> b.bc_deflection = [(0, [0, 0, 0]), (l, [0, 0, 0])] >>> b.solve_slope_deflection() >>> factor(b.slope()) [0, 0, x*(-l + x)*(-A*G*l**3*q + 2*A*G*l**2*q*x - 12*E*I*l*q - 72*E*I*m + 24*E*I*q*x)/(12*E*I*(A*G*l**2 + 12*E*I))] >>> dx, dy, dz = b.deflection() >>> dy = collect(simplify(dy), x) >>> dx == dz == 0 True >>> dy == (x*(12*E*I*l*(A*G*l**2*q - 2*A*G*l*m + 12*E*I*q) ... + x*(A*G*l*(3*l*(A*G*l**2*q - 2*A*G*l*m + 12*E*I*q) + x*(-2*A*G*l**2*q + 4*A*G*l*m - 24*E*I*q)) ... + A*G*(A*G*l**2 + 12*E*I)*(-2*l**2*q + 6*l*m - 4*m*x + q*x**2) ... - 12*E*I*q*(A*G*l**2 + 12*E*I)))/(24*A*E*G*I*(A*G*l**2 + 12*E*I))) True References ========== .. [1] http://homes.civil.aau.dk/jc/FemteSemester/Beams3D.pdf """ def __init__(self, length, elastic_modulus, shear_modulus , second_moment, area, variable=Symbol('x')): """Initializes the class. Parameters ========== length : Sympifyable A Symbol or value representing the Beam's length. elastic_modulus : Sympifyable A SymPy expression representing the Beam's Modulus of Elasticity. It is a measure of the stiffness of the Beam material. shear_modulus : Sympifyable A SymPy expression representing the Beam's Modulus of rigidity. It is a measure of rigidity of the Beam material. second_moment : Sympifyable or list A list of two elements having SymPy expression representing the Beam's Second moment of area. First value represent Second moment across y-axis and second across z-axis. Single SymPy expression can be passed if both values are same area : Sympifyable A SymPy expression representing the Beam's cross-sectional area in a plane prependicular to length of the Beam. variable : Symbol, optional A Symbol object that will be used as the variable along the beam while representing the load, shear, moment, slope and deflection curve. By default, it is set to ``Symbol('x')``. """ super().__init__(length, elastic_modulus, second_moment, variable) self.shear_modulus = shear_modulus self._area = area self._load_vector = [0, 0, 0] self._moment_load_vector = [0, 0, 0] self._load_Singularity = [0, 0, 0] self._slope = [0, 0, 0] self._deflection = [0, 0, 0] @property def shear_modulus(self): """Young's Modulus of the Beam. """ return self._shear_modulus @shear_modulus.setter def shear_modulus(self, e): self._shear_modulus = sympify(e) @property def second_moment(self): """Second moment of area of the Beam. """ return self._second_moment @second_moment.setter def second_moment(self, i): if isinstance(i, list): i = [sympify(x) for x in i] self._second_moment = i else: self._second_moment = sympify(i) @property def area(self): """Cross-sectional area of the Beam. """ return self._area @area.setter def area(self, a): self._area = sympify(a) @property def load_vector(self): """ Returns a three element list representing the load vector. """ return self._load_vector @property def moment_load_vector(self): """ Returns a three element list representing moment loads on Beam. """ return self._moment_load_vector @property def boundary_conditions(self): """ Returns a dictionary of boundary conditions applied on the beam. The dictionary has two keywords namely slope and deflection. The value of each keyword is a list of tuple, where each tuple contains location and value of a boundary condition in the format (location, value). Further each value is a list corresponding to slope or deflection(s) values along three axes at that location. Examples ======== There is a beam of length 4 meters. The slope at 0 should be 4 along the x-axis and 0 along others. At the other end of beam, deflection along all the three axes should be zero. >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(30, E, G, I, A, x) >>> b.bc_slope = [(0, (4, 0, 0))] >>> b.bc_deflection = [(4, [0, 0, 0])] >>> b.boundary_conditions {'deflection': [(4, [0, 0, 0])], 'slope': [(0, (4, 0, 0))]} Here the deflection of the beam should be ``0`` along all the three axes at ``4``. Similarly, the slope of the beam should be ``4`` along x-axis and ``0`` along y and z axis at ``0``. """ return self._boundary_conditions def polar_moment(self): """ Returns the polar moment of area of the beam about the X axis with respect to the centroid. Examples ======== >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A = symbols('l, E, G, I, A') >>> b = Beam3D(l, E, G, I, A) >>> b.polar_moment() 2*I >>> I1 = [9, 15] >>> b = Beam3D(l, E, G, I1, A) >>> b.polar_moment() 24 """ if not iterable(self.second_moment): return 2*self.second_moment return sum(self.second_moment) def apply_load(self, value, start, order, dir="y"): """ This method adds up the force load to a particular beam object. Parameters ========== value : Sympifyable The magnitude of an applied load. dir : String Axis along which load is applied. order : Integer The order of the applied load. - For point loads, order=-1 - For constant distributed load, order=0 - For ramp loads, order=1 - For parabolic ramp loads, order=2 - ... so on. """ x = self.variable value = sympify(value) start = sympify(start) order = sympify(order) if dir == "x": if not order == -1: self._load_vector[0] += value self._load_Singularity[0] += value*SingularityFunction(x, start, order) elif dir == "y": if not order == -1: self._load_vector[1] += value self._load_Singularity[1] += value*SingularityFunction(x, start, order) else: if not order == -1: self._load_vector[2] += value self._load_Singularity[2] += value*SingularityFunction(x, start, order) def apply_moment_load(self, value, start, order, dir="y"): """ This method adds up the moment loads to a particular beam object. Parameters ========== value : Sympifyable The magnitude of an applied moment. dir : String Axis along which moment is applied. order : Integer The order of the applied load. - For point moments, order=-2 - For constant distributed moment, order=-1 - For ramp moments, order=0 - For parabolic ramp moments, order=1 - ... so on. """ x = self.variable value = sympify(value) start = sympify(start) order = sympify(order) if dir == "x": if not order == -2: self._moment_load_vector[0] += value self._load_Singularity[0] += value*SingularityFunction(x, start, order) elif dir == "y": if not order == -2: self._moment_load_vector[1] += value self._load_Singularity[0] += value*SingularityFunction(x, start, order) else: if not order == -2: self._moment_load_vector[2] += value self._load_Singularity[0] += value*SingularityFunction(x, start, order) def apply_support(self, loc, type="fixed"): if type == "pin" or type == "roller": reaction_load = Symbol('R_'+str(loc)) self._reaction_loads[reaction_load] = reaction_load self.bc_deflection.append((loc, [0, 0, 0])) else: reaction_load = Symbol('R_'+str(loc)) reaction_moment = Symbol('M_'+str(loc)) self._reaction_loads[reaction_load] = [reaction_load, reaction_moment] self.bc_deflection.append((loc, [0, 0, 0])) self.bc_slope.append((loc, [0, 0, 0])) def solve_for_reaction_loads(self, *reaction): """ Solves for the reaction forces. Examples ======== There is a beam of length 30 meters. It it supported by rollers at of its end. A constant distributed load of magnitude 8 N is applied from start till its end along y-axis. Another linear load having slope equal to 9 is applied along z-axis. >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(30, E, G, I, A, x) >>> b.apply_load(8, start=0, order=0, dir="y") >>> b.apply_load(9*x, start=0, order=0, dir="z") >>> b.bc_deflection = [(0, [0, 0, 0]), (30, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="y") >>> b.apply_load(R2, start=30, order=-1, dir="y") >>> b.apply_load(R3, start=0, order=-1, dir="z") >>> b.apply_load(R4, start=30, order=-1, dir="z") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.reaction_loads {R1: -120, R2: -120, R3: -1350, R4: -2700} """ x = self.variable l = self.length q = self._load_Singularity shear_curves = [integrate(load, x) for load in q] moment_curves = [integrate(shear, x) for shear in shear_curves] for i in range(3): react = [r for r in reaction if (shear_curves[i].has(r) or moment_curves[i].has(r))] if len(react) == 0: continue shear_curve = limit(shear_curves[i], x, l) moment_curve = limit(moment_curves[i], x, l) sol = list((linsolve([shear_curve, moment_curve], react).args)[0]) sol_dict = dict(zip(react, sol)) reaction_loads = self._reaction_loads # Check if any of the evaluated rection exists in another direction # and if it exists then it should have same value. for key in sol_dict: if key in reaction_loads and sol_dict[key] != reaction_loads[key]: raise ValueError("Ambiguous solution for %s in different directions." % key) self._reaction_loads.update(sol_dict) def shear_force(self): """ Returns a list of three expressions which represents the shear force curve of the Beam object along all three axes. """ x = self.variable q = self._load_vector return [integrate(-q[0], x), integrate(-q[1], x), integrate(-q[2], x)] def axial_force(self): """ Returns expression of Axial shear force present inside the Beam object. """ return self.shear_force()[0] def shear_stress(self): """ Returns a list of three expressions which represents the shear stress curve of the Beam object along all three axes. """ return [self.shear_force()[0]/self._area, self.shear_force()[1]/self._area, self.shear_force()[2]/self._area] def axial_stress(self): """ Returns expression of Axial stress present inside the Beam object. """ return self.axial_force()/self._area def bending_moment(self): """ Returns a list of three expressions which represents the bending moment curve of the Beam object along all three axes. """ x = self.variable m = self._moment_load_vector shear = self.shear_force() return [integrate(-m[0], x), integrate(-m[1] + shear[2], x), integrate(-m[2] - shear[1], x) ] def torsional_moment(self): """ Returns expression of Torsional moment present inside the Beam object. """ return self.bending_moment()[0] def solve_slope_deflection(self): from sympy import dsolve, Function, Derivative, Eq x = self.variable l = self.length E = self.elastic_modulus G = self.shear_modulus I = self.second_moment if isinstance(I, list): I_y, I_z = I[0], I[1] else: I_y = I_z = I A = self._area load = self._load_vector moment = self._moment_load_vector defl = Function('defl') theta = Function('theta') # Finding deflection along x-axis(and corresponding slope value by differentiating it) # Equation used: Derivative(E*A*Derivative(def_x(x), x), x) + load_x = 0 eq = Derivative(E*A*Derivative(defl(x), x), x) + load[0] def_x = dsolve(Eq(eq, 0), defl(x)).args[1] # Solving constants originated from dsolve C1 = Symbol('C1') C2 = Symbol('C2') constants = list((linsolve([def_x.subs(x, 0), def_x.subs(x, l)], C1, C2).args)[0]) def_x = def_x.subs({C1:constants[0], C2:constants[1]}) slope_x = def_x.diff(x) self._deflection[0] = def_x self._slope[0] = slope_x # Finding deflection along y-axis and slope across z-axis. System of equation involved: # 1: Derivative(E*I_z*Derivative(theta_z(x), x), x) + G*A*(Derivative(defl_y(x), x) - theta_z(x)) + moment_z = 0 # 2: Derivative(G*A*(Derivative(defl_y(x), x) - theta_z(x)), x) + load_y = 0 C_i = Symbol('C_i') # Substitute value of `G*A*(Derivative(defl_y(x), x) - theta_z(x))` from (2) in (1) eq1 = Derivative(E*I_z*Derivative(theta(x), x), x) + (integrate(-load[1], x) + C_i) + moment[2] slope_z = dsolve(Eq(eq1, 0)).args[1] # Solve for constants originated from using dsolve on eq1 constants = list((linsolve([slope_z.subs(x, 0), slope_z.subs(x, l)], C1, C2).args)[0]) slope_z = slope_z.subs({C1:constants[0], C2:constants[1]}) # Put value of slope obtained back in (2) to solve for `C_i` and find deflection across y-axis eq2 = G*A*(Derivative(defl(x), x)) + load[1]*x - C_i - G*A*slope_z def_y = dsolve(Eq(eq2, 0), defl(x)).args[1] # Solve for constants originated from using dsolve on eq2 constants = list((linsolve([def_y.subs(x, 0), def_y.subs(x, l)], C1, C_i).args)[0]) self._deflection[1] = def_y.subs({C1:constants[0], C_i:constants[1]}) self._slope[2] = slope_z.subs(C_i, constants[1]) # Finding deflection along z-axis and slope across y-axis. System of equation involved: # 1: Derivative(E*I_y*Derivative(theta_y(x), x), x) - G*A*(Derivative(defl_z(x), x) + theta_y(x)) + moment_y = 0 # 2: Derivative(G*A*(Derivative(defl_z(x), x) + theta_y(x)), x) + load_z = 0 # Substitute value of `G*A*(Derivative(defl_y(x), x) + theta_z(x))` from (2) in (1) eq1 = Derivative(E*I_y*Derivative(theta(x), x), x) + (integrate(load[2], x) - C_i) + moment[1] slope_y = dsolve(Eq(eq1, 0)).args[1] # Solve for constants originated from using dsolve on eq1 constants = list((linsolve([slope_y.subs(x, 0), slope_y.subs(x, l)], C1, C2).args)[0]) slope_y = slope_y.subs({C1:constants[0], C2:constants[1]}) # Put value of slope obtained back in (2) to solve for `C_i` and find deflection across z-axis eq2 = G*A*(Derivative(defl(x), x)) + load[2]*x - C_i + G*A*slope_y def_z = dsolve(Eq(eq2,0)).args[1] # Solve for constants originated from using dsolve on eq2 constants = list((linsolve([def_z.subs(x, 0), def_z.subs(x, l)], C1, C_i).args)[0]) self._deflection[2] = def_z.subs({C1:constants[0], C_i:constants[1]}) self._slope[1] = slope_y.subs(C_i, constants[1]) def slope(self): """ Returns a three element list representing slope of deflection curve along all the three axes. """ return self._slope def deflection(self): """ Returns a three element list representing deflection curve along all the three axes. """ return self._deflection def _plot_shear_force(self, dir, subs=None): shear_force = self.shear_force() if dir == 'x': dir_num = 0 color = 'r' elif dir == 'y': dir_num = 1 color = 'g' elif dir == 'z': dir_num = 2 color = 'b' if subs is None: subs = {} for sym in shear_force[dir_num].atoms(Symbol): if sym != self.variable and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(shear_force[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Shear Force along %c direction'%dir, xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{V(%c)}$'%dir, line_color=color) def plot_shear_force(self, dir="all", subs=None): """ Returns a plot for Shear force along all three directions present in the Beam object. Parameters ========== dir : string (default : "all") Direction along which shear force plot is required. If no direction is specified, all plots are displayed. subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 20 meters. It it supported by rollers at of its end. A linear load having slope equal to 12 is applied along y-axis. A constant distributed load of magnitude 15 N is applied from start till its end along z-axis. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, E, G, I, A, x) >>> b.apply_load(15, start=0, order=0, dir="z") >>> b.apply_load(12*x, start=0, order=0, dir="y") >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="z") >>> b.apply_load(R2, start=20, order=-1, dir="z") >>> b.apply_load(R3, start=0, order=-1, dir="y") >>> b.apply_load(R4, start=20, order=-1, dir="y") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.plot_shear_force() PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: 0 for x over (0.0, 20.0) Plot[1]:Plot object containing: [0]: cartesian line: -6*x**2 for x over (0.0, 20.0) Plot[2]:Plot object containing: [0]: cartesian line: -15*x for x over (0.0, 20.0) """ dir = dir.lower() # For shear force along x direction if dir == "x": Px = self._plot_shear_force('x', subs) return Px.show() # For shear force along y direction elif dir == "y": Py = self._plot_shear_force('y', subs) return Py.show() # For shear force along z direction elif dir == "z": Pz = self._plot_shear_force('z', subs) return Pz.show() # For shear force along all direction else: Px = self._plot_shear_force('x', subs) Py = self._plot_shear_force('y', subs) Pz = self._plot_shear_force('z', subs) return PlotGrid(3, 1, Px, Py, Pz) def _plot_bending_moment(self, dir, subs=None): bending_moment = self.bending_moment() if dir == 'x': dir_num = 0 color = 'g' elif dir == 'y': dir_num = 1 color = 'c' elif dir == 'z': dir_num = 2 color = 'm' if subs is None: subs = {} for sym in bending_moment[dir_num].atoms(Symbol): if sym != self.variable and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(bending_moment[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Bending Moment along %c direction'%dir, xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{M(%c)}$'%dir, line_color=color) def plot_bending_moment(self, dir="all", subs=None): """ Returns a plot for bending moment along all three directions present in the Beam object. Parameters ========== dir : string (default : "all") Direction along which bending moment plot is required. If no direction is specified, all plots are displayed. subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 20 meters. It it supported by rollers at of its end. A linear load having slope equal to 12 is applied along y-axis. A constant distributed load of magnitude 15 N is applied from start till its end along z-axis. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, E, G, I, A, x) >>> b.apply_load(15, start=0, order=0, dir="z") >>> b.apply_load(12*x, start=0, order=0, dir="y") >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="z") >>> b.apply_load(R2, start=20, order=-1, dir="z") >>> b.apply_load(R3, start=0, order=-1, dir="y") >>> b.apply_load(R4, start=20, order=-1, dir="y") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.plot_bending_moment() PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: 0 for x over (0.0, 20.0) Plot[1]:Plot object containing: [0]: cartesian line: -15*x**2/2 for x over (0.0, 20.0) Plot[2]:Plot object containing: [0]: cartesian line: 2*x**3 for x over (0.0, 20.0) """ dir = dir.lower() # For bending moment along x direction if dir == "x": Px = self._plot_bending_moment('x', subs) return Px.show() # For bending moment along y direction elif dir == "y": Py = self._plot_bending_moment('y', subs) return Py.show() # For bending moment along z direction elif dir == "z": Pz = self._plot_bending_moment('z', subs) return Pz.show() # For bending moment along all direction else: Px = self._plot_bending_moment('x', subs) Py = self._plot_bending_moment('y', subs) Pz = self._plot_bending_moment('z', subs) return PlotGrid(3, 1, Px, Py, Pz) def _plot_slope(self, dir, subs=None): slope = self.slope() if dir == 'x': dir_num = 0 color = 'b' elif dir == 'y': dir_num = 1 color = 'm' elif dir == 'z': dir_num = 2 color = 'g' if subs is None: subs = {} for sym in slope[dir_num].atoms(Symbol): if sym != self.variable and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(slope[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Slope along %c direction'%dir, xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{\theta(%c)}$'%dir, line_color=color) def plot_slope(self, dir="all", subs=None): """ Returns a plot for Slope along all three directions present in the Beam object. Parameters ========== dir : string (default : "all") Direction along which Slope plot is required. If no direction is specified, all plots are displayed. subs : dictionary Python dictionary containing Symbols as keys and their corresponding values. Examples ======== There is a beam of length 20 meters. It it supported by rollers at of its end. A linear load having slope equal to 12 is applied along y-axis. A constant distributed load of magnitude 15 N is applied from start till its end along z-axis. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, 40, 21, 100, 25, x) >>> b.apply_load(15, start=0, order=0, dir="z") >>> b.apply_load(12*x, start=0, order=0, dir="y") >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="z") >>> b.apply_load(R2, start=20, order=-1, dir="z") >>> b.apply_load(R3, start=0, order=-1, dir="y") >>> b.apply_load(R4, start=20, order=-1, dir="y") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.solve_slope_deflection() >>> b.plot_slope() PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: 0 for x over (0.0, 20.0) Plot[1]:Plot object containing: [0]: cartesian line: -x**3/1600 + 3*x**2/160 - x/8 for x over (0.0, 20.0) Plot[2]:Plot object containing: [0]: cartesian line: x**4/8000 - 19*x**2/172 + 52*x/43 for x over (0.0, 20.0) """ dir = dir.lower() # For Slope along x direction if dir == "x": Px = self._plot_slope('x', subs) return Px.show() # For Slope along y direction elif dir == "y": Py = self._plot_slope('y', subs) return Py.show() # For Slope along z direction elif dir == "z": Pz = self._plot_slope('z', subs) return Pz.show() # For Slope along all direction else: Px = self._plot_slope('x', subs) Py = self._plot_slope('y', subs) Pz = self._plot_slope('z', subs) return PlotGrid(3, 1, Px, Py, Pz) def _plot_deflection(self, dir, subs=None): deflection = self.deflection() if dir == 'x': dir_num = 0 color = 'm' elif dir == 'y': dir_num = 1 color = 'r' elif dir == 'z': dir_num = 2 color = 'c' if subs is None: subs = {} for sym in deflection[dir_num].atoms(Symbol): if sym != self.variable and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(deflection[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Deflection along %c direction'%dir, xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{\delta(%c)}$'%dir, line_color=color) def plot_deflection(self, dir="all", subs=None): """ Returns a plot for Deflection along all three directions present in the Beam object. Parameters ========== dir : string (default : "all") Direction along which deflection plot is required. If no direction is specified, all plots are displayed. subs : dictionary Python dictionary containing Symbols as keys and their corresponding values. Examples ======== There is a beam of length 20 meters. It it supported by rollers at of its end. A linear load having slope equal to 12 is applied along y-axis. A constant distributed load of magnitude 15 N is applied from start till its end along z-axis. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, 40, 21, 100, 25, x) >>> b.apply_load(15, start=0, order=0, dir="z") >>> b.apply_load(12*x, start=0, order=0, dir="y") >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="z") >>> b.apply_load(R2, start=20, order=-1, dir="z") >>> b.apply_load(R3, start=0, order=-1, dir="y") >>> b.apply_load(R4, start=20, order=-1, dir="y") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.solve_slope_deflection() >>> b.plot_deflection() PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: 0 for x over (0.0, 20.0) Plot[1]:Plot object containing: [0]: cartesian line: x**5/40000 - 4013*x**3/90300 + 26*x**2/43 + 1520*x/903 for x over (0.0, 20.0) Plot[2]:Plot object containing: [0]: cartesian line: x**4/6400 - x**3/160 + 27*x**2/560 + 2*x/7 for x over (0.0, 20.0) """ dir = dir.lower() # For deflection along x direction if dir == "x": Px = self._plot_deflection('x', subs) return Px.show() # For deflection along y direction elif dir == "y": Py = self._plot_deflection('y', subs) return Py.show() # For deflection along z direction elif dir == "z": Pz = self._plot_deflection('z', subs) return Pz.show() # For deflection along all direction else: Px = self._plot_deflection('x', subs) Py = self._plot_deflection('y', subs) Pz = self._plot_deflection('z', subs) return PlotGrid(3, 1, Px, Py, Pz) def plot_loading_results(self, dir='x', subs=None): """ Returns a subplot of Shear Force, Bending Moment, Slope and Deflection of the Beam object along the direction specified. Parameters ========== dir : string (default : "x") Direction along which plots are required. If no direction is specified, plots along x-axis are displayed. subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 20 meters. It it supported by rollers at of its end. A linear load having slope equal to 12 is applied along y-axis. A constant distributed load of magnitude 15 N is applied from start till its end along z-axis. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, E, G, I, A, x) >>> subs = {E:40, G:21, I:100, A:25} >>> b.apply_load(15, start=0, order=0, dir="z") >>> b.apply_load(12*x, start=0, order=0, dir="y") >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="z") >>> b.apply_load(R2, start=20, order=-1, dir="z") >>> b.apply_load(R3, start=0, order=-1, dir="y") >>> b.apply_load(R4, start=20, order=-1, dir="y") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.solve_slope_deflection() >>> b.plot_loading_results('y',subs) PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: -6*x**2 for x over (0.0, 20.0) Plot[1]:Plot object containing: [0]: cartesian line: -15*x**2/2 for x over (0.0, 20.0) Plot[2]:Plot object containing: [0]: cartesian line: -x**3/1600 + 3*x**2/160 - x/8 for x over (0.0, 20.0) Plot[3]:Plot object containing: [0]: cartesian line: x**5/40000 - 4013*x**3/90300 + 26*x**2/43 + 1520*x/903 for x over (0.0, 20.0) """ dir = dir.lower(); if subs is None: subs = {} ax1 = self._plot_shear_force(dir, subs) ax2 = self._plot_bending_moment(dir, subs) ax3 = self._plot_slope(dir, subs) ax4 = self._plot_deflection(dir, subs) return PlotGrid(4, 1, ax1, ax2, ax3, ax4) def _plot_shear_stress(self, dir, subs=None): shear_stress = self.shear_stress() if dir == 'x': dir_num = 0 color = 'r' elif dir == 'y': dir_num = 1 color = 'g' elif dir == 'z': dir_num = 2 color = 'b' if subs is None: subs = {} for sym in shear_stress[dir_num].atoms(Symbol): if sym != self.variable and sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(shear_stress[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Shear stress along %c direction'%dir, xlabel=r'$\mathrm{X}$', ylabel=r'$\tau(%c)$'%dir, line_color=color) def plot_shear_stress(self, dir="all", subs=None): """ Returns a plot for Shear Stress along all three directions present in the Beam object. Parameters ========== dir : string (default : "all") Direction along which shear stress plot is required. If no direction is specified, all plots are displayed. subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 20 meters and area of cross section 2 square meters. It it supported by rollers at of its end. A linear load having slope equal to 12 is applied along y-axis. A constant distributed load of magnitude 15 N is applied from start till its end along z-axis. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, E, G, I, 2, x) >>> b.apply_load(15, start=0, order=0, dir="z") >>> b.apply_load(12*x, start=0, order=0, dir="y") >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="z") >>> b.apply_load(R2, start=20, order=-1, dir="z") >>> b.apply_load(R3, start=0, order=-1, dir="y") >>> b.apply_load(R4, start=20, order=-1, dir="y") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.plot_shear_stress() PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: 0 for x over (0.0, 20.0) Plot[1]:Plot object containing: [0]: cartesian line: -3*x**2 for x over (0.0, 20.0) Plot[2]:Plot object containing: [0]: cartesian line: -15*x/2 for x over (0.0, 20.0) """ dir = dir.lower() # For shear stress along x direction if dir == "x": Px = self._plot_shear_stress('x', subs) return Px.show() # For shear stress along y direction elif dir == "y": Py = self._plot_shear_stress('y', subs) return Py.show() # For shear stress along z direction elif dir == "z": Pz = self._plot_shear_stress('z', subs) return Pz.show() # For shear stress along all direction else: Px = self._plot_shear_stress('x', subs) Py = self._plot_shear_stress('y', subs) Pz = self._plot_shear_stress('z', subs) return PlotGrid(3, 1, Px, Py, Pz)
b89d3648928cf4901c7d6a55420d39fefecc0ebf186138a2f4d2910a468a30c5
from sympy import (symbols, factor, Function, simplify, exp, oo, I, S, Mul, Pow, Add, Rational, sqrt, CRootOf, eye) from sympy.core.containers import Tuple from sympy.matrices import ImmutableMatrix, Matrix from sympy.physics.control import (TransferFunction, Series, Parallel, Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback) from sympy.testing.pytest import raises a, x, b, s, g, d, p, k, a0, a1, a2, b0, b1, b2, tau, zeta, wn = symbols('a, x, b, s, g, d, p, k,\ a0:3, b0:3, tau, zeta, wn') TF1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s) TF2 = TransferFunction(k, 1, s) TF3 = TransferFunction(a2*p - s, a2*s + p, s) def test_TransferFunction_construction(): tf = TransferFunction(s + 1, s**2 + s + 1, s) assert tf.num == (s + 1) assert tf.den == (s**2 + s + 1) assert tf.args == (s + 1, s**2 + s + 1, s) tf1 = TransferFunction(s + 4, s - 5, s) assert tf1.num == (s + 4) assert tf1.den == (s - 5) assert tf1.args == (s + 4, s - 5, s) # using different polynomial variables. tf2 = TransferFunction(p + 3, p**2 - 9, p) assert tf2.num == (p + 3) assert tf2.den == (p**2 - 9) assert tf2.args == (p + 3, p**2 - 9, p) tf3 = TransferFunction(p**3 + 5*p**2 + 4, p**4 + 3*p + 1, p) assert tf3.args == (p**3 + 5*p**2 + 4, p**4 + 3*p + 1, p) # no pole-zero cancellation on its own. tf4 = TransferFunction((s + 3)*(s - 1), (s - 1)*(s + 5), s) assert tf4.den == (s - 1)*(s + 5) assert tf4.args == ((s + 3)*(s - 1), (s - 1)*(s + 5), s) tf4_ = TransferFunction(p + 2, p + 2, p) assert tf4_.args == (p + 2, p + 2, p) tf5 = TransferFunction(s - 1, 4 - p, s) assert tf5.args == (s - 1, 4 - p, s) tf5_ = TransferFunction(s - 1, s - 1, s) assert tf5_.args == (s - 1, s - 1, s) tf6 = TransferFunction(5, 6, s) assert tf6.num == 5 assert tf6.den == 6 assert tf6.args == (5, 6, s) tf6_ = TransferFunction(1/2, 4, s) assert tf6_.num == 0.5 assert tf6_.den == 4 assert tf6_.args == (0.500000000000000, 4, s) tf7 = TransferFunction(3*s**2 + 2*p + 4*s, 8*p**2 + 7*s, s) tf8 = TransferFunction(3*s**2 + 2*p + 4*s, 8*p**2 + 7*s, p) assert not tf7 == tf8 tf7_ = TransferFunction(a0*s + a1*s**2 + a2*s**3, b0*p - b1*s, s) tf8_ = TransferFunction(a0*s + a1*s**2 + a2*s**3, b0*p - b1*s, s) assert tf7_ == tf8_ assert -(-tf7_) == tf7_ == -(-(-(-tf7_))) tf9 = TransferFunction(a*s**3 + b*s**2 + g*s + d, d*p + g*p**2 + g*s, s) assert tf9.args == (a*s**3 + b*s**2 + d + g*s, d*p + g*p**2 + g*s, s) tf10 = TransferFunction(p**3 + d, g*s**2 + d*s + a, p) tf10_ = TransferFunction(p**3 + d, g*s**2 + d*s + a, p) assert tf10.args == (d + p**3, a + d*s + g*s**2, p) assert tf10_ == tf10 tf11 = TransferFunction(a1*s + a0, b2*s**2 + b1*s + b0, s) assert tf11.num == (a0 + a1*s) assert tf11.den == (b0 + b1*s + b2*s**2) assert tf11.args == (a0 + a1*s, b0 + b1*s + b2*s**2, s) # when just the numerator is 0, leave the denominator alone. tf12 = TransferFunction(0, p**2 - p + 1, p) assert tf12.args == (0, p**2 - p + 1, p) tf13 = TransferFunction(0, 1, s) assert tf13.args == (0, 1, s) # float exponents tf14 = TransferFunction(a0*s**0.5 + a2*s**0.6 - a1, a1*p**(-8.7), s) assert tf14.args == (a0*s**0.5 - a1 + a2*s**0.6, a1*p**(-8.7), s) tf15 = TransferFunction(a2**2*p**(1/4) + a1*s**(-4/5), a0*s - p, p) assert tf15.args == (a1*s**(-0.8) + a2**2*p**0.25, a0*s - p, p) omega_o, k_p, k_o, k_i = symbols('omega_o, k_p, k_o, k_i') tf18 = TransferFunction((k_p + k_o*s + k_i/s), s**2 + 2*omega_o*s + omega_o**2, s) assert tf18.num == k_i/s + k_o*s + k_p assert tf18.args == (k_i/s + k_o*s + k_p, omega_o**2 + 2*omega_o*s + s**2, s) # ValueError when denominator is zero. raises(ValueError, lambda: TransferFunction(4, 0, s)) raises(ValueError, lambda: TransferFunction(s, 0, s)) raises(ValueError, lambda: TransferFunction(0, 0, s)) raises(TypeError, lambda: TransferFunction(Matrix([1, 2, 3]), s, s)) raises(TypeError, lambda: TransferFunction(s**2 + 2*s - 1, s + 3, 3)) raises(TypeError, lambda: TransferFunction(p + 1, 5 - p, 4)) raises(TypeError, lambda: TransferFunction(3, 4, 8)) def test_TransferFunction_functions(): # classmethod from_rational_expression expr_1 = Mul(0, Pow(s, -1, evaluate=False), evaluate=False) expr_2 = s/0 expr_3 = (p*s**2 + 5*s)/(s + 1)**3 expr_4 = 6 expr_5 = ((2 + 3*s)*(5 + 2*s))/((9 + 3*s)*(5 + 2*s**2)) expr_6 = (9*s**4 + 4*s**2 + 8)/((s + 1)*(s + 9)) tf = TransferFunction(s + 1, s**2 + 2, s) delay = exp(-s/tau) expr_7 = delay*tf.to_expr() H1 = TransferFunction.from_rational_expression(expr_7, s) H2 = TransferFunction(s + 1, (s**2 + 2)*exp(s/tau), s) expr_8 = Add(2, 3*s/(s**2 + 1), evaluate=False) assert TransferFunction.from_rational_expression(expr_1) == TransferFunction(0, s, s) raises(ZeroDivisionError, lambda: TransferFunction.from_rational_expression(expr_2)) raises(ValueError, lambda: TransferFunction.from_rational_expression(expr_3)) assert TransferFunction.from_rational_expression(expr_3, s) == TransferFunction((p*s**2 + 5*s), (s + 1)**3, s) assert TransferFunction.from_rational_expression(expr_3, p) == TransferFunction((p*s**2 + 5*s), (s + 1)**3, p) raises(ValueError, lambda: TransferFunction.from_rational_expression(expr_4)) assert TransferFunction.from_rational_expression(expr_4, s) == TransferFunction(6, 1, s) assert TransferFunction.from_rational_expression(expr_5, s) == \ TransferFunction((2 + 3*s)*(5 + 2*s), (9 + 3*s)*(5 + 2*s**2), s) assert TransferFunction.from_rational_expression(expr_6, s) == \ TransferFunction((9*s**4 + 4*s**2 + 8), (s + 1)*(s + 9), s) assert H1 == H2 assert TransferFunction.from_rational_expression(expr_8, s) == \ TransferFunction(2*s**2 + 3*s + 2, s**2 + 1, s) # explicitly cancel poles and zeros. tf0 = TransferFunction(s**5 + s**3 + s, s - s**2, s) a = TransferFunction(-(s**4 + s**2 + 1), s - 1, s) assert tf0.simplify() == simplify(tf0) == a tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p) b = TransferFunction(p + 3, p + 5, p) assert tf1.simplify() == simplify(tf1) == b # expand the numerator and the denominator. G1 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s) G2 = TransferFunction(1, -3, p) c = (a2*s**p + a1*s**s + a0*p**p)*(p**s + s**p) d = (b0*s**s + b1*p**s)*(b2*s*p + p**p) e = a0*p**p*p**s + a0*p**p*s**p + a1*p**s*s**s + a1*s**p*s**s + a2*p**s*s**p + a2*s**(2*p) f = b0*b2*p*s*s**s + b0*p**p*s**s + b1*b2*p*p**s*s + b1*p**p*p**s g = a1*a2*s*s**p + a1*p*s + a2*b1*p*s*s**p + b1*p**2*s G3 = TransferFunction(c, d, s) G4 = TransferFunction(a0*s**s - b0*p**p, (a1*s + b1*s*p)*(a2*s**p + p), p) assert G1.expand() == TransferFunction(s**2 - 2*s + 1, s**4 + 2*s**2 + 1, s) assert tf1.expand() == TransferFunction(p**2 + 2*p - 3, p**2 + 4*p - 5, p) assert G2.expand() == G2 assert G3.expand() == TransferFunction(e, f, s) assert G4.expand() == TransferFunction(a0*s**s - b0*p**p, g, p) # purely symbolic polynomials. p1 = a1*s + a0 p2 = b2*s**2 + b1*s + b0 SP1 = TransferFunction(p1, p2, s) expect1 = TransferFunction(2.0*s + 1.0, 5.0*s**2 + 4.0*s + 3.0, s) expect1_ = TransferFunction(2*s + 1, 5*s**2 + 4*s + 3, s) assert SP1.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}) == expect1_ assert SP1.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}).evalf() == expect1 assert expect1_.evalf() == expect1 c1, d0, d1, d2 = symbols('c1, d0:3') p3, p4 = c1*p, d2*p**3 + d1*p**2 - d0 SP2 = TransferFunction(p3, p4, p) expect2 = TransferFunction(2.0*p, 5.0*p**3 + 2.0*p**2 - 3.0, p) expect2_ = TransferFunction(2*p, 5*p**3 + 2*p**2 - 3, p) assert SP2.subs({c1: 2, d0: 3, d1: 2, d2: 5}) == expect2_ assert SP2.subs({c1: 2, d0: 3, d1: 2, d2: 5}).evalf() == expect2 assert expect2_.evalf() == expect2 SP3 = TransferFunction(a0*p**3 + a1*s**2 - b0*s + b1, a1*s + p, s) expect3 = TransferFunction(2.0*p**3 + 4.0*s**2 - s + 5.0, p + 4.0*s, s) expect3_ = TransferFunction(2*p**3 + 4*s**2 - s + 5, p + 4*s, s) assert SP3.subs({a0: 2, a1: 4, b0: 1, b1: 5}) == expect3_ assert SP3.subs({a0: 2, a1: 4, b0: 1, b1: 5}).evalf() == expect3 assert expect3_.evalf() == expect3 SP4 = TransferFunction(s - a1*p**3, a0*s + p, p) expect4 = TransferFunction(7.0*p**3 + s, p - s, p) expect4_ = TransferFunction(7*p**3 + s, p - s, p) assert SP4.subs({a0: -1, a1: -7}) == expect4_ assert SP4.subs({a0: -1, a1: -7}).evalf() == expect4 assert expect4_.evalf() == expect4 # Low-frequency (or DC) gain. assert tf0.dc_gain() == 1 assert tf1.dc_gain() == Rational(3, 5) assert SP2.dc_gain() == 0 assert expect4.dc_gain() == -1 assert expect2_.dc_gain() == 0 assert TransferFunction(1, s, s).dc_gain() == oo # Poles of a transfer function. tf_ = TransferFunction(x**3 - k, k, x) _tf = TransferFunction(k, x**4 - k, x) TF_ = TransferFunction(x**2, x**10 + x + x**2, x) _TF = TransferFunction(x**10 + x + x**2, x**2, x) assert G1.poles() == [I, I, -I, -I] assert G2.poles() == [] assert tf1.poles() == [-5, 1] assert expect4_.poles() == [s] assert SP4.poles() == [-a0*s] assert expect3.poles() == [-0.25*p] assert str(expect2.poles()) == str([0.729001428685125, -0.564500714342563 - 0.710198984796332*I, -0.564500714342563 + 0.710198984796332*I]) assert str(expect1.poles()) == str([-0.4 - 0.66332495807108*I, -0.4 + 0.66332495807108*I]) assert _tf.poles() == [k**(Rational(1, 4)), -k**(Rational(1, 4)), I*k**(Rational(1, 4)), -I*k**(Rational(1, 4))] assert TF_.poles() == [CRootOf(x**9 + x + 1, 0), 0, CRootOf(x**9 + x + 1, 1), CRootOf(x**9 + x + 1, 2), CRootOf(x**9 + x + 1, 3), CRootOf(x**9 + x + 1, 4), CRootOf(x**9 + x + 1, 5), CRootOf(x**9 + x + 1, 6), CRootOf(x**9 + x + 1, 7), CRootOf(x**9 + x + 1, 8)] raises(NotImplementedError, lambda: TransferFunction(x**2, a0*x**10 + x + x**2, x).poles()) # Stability of a transfer function. q, r = symbols('q, r', negative=True) t = symbols('t', positive=True) TF_ = TransferFunction(s**2 + a0 - a1*p, q*s - r, s) stable_tf = TransferFunction(s**2 + a0 - a1*p, q*s - 1, s) stable_tf_ = TransferFunction(s**2 + a0 - a1*p, q*s - t, s) assert G1.is_stable() is False assert G2.is_stable() is True assert tf1.is_stable() is False # as one pole is +ve, and the other is -ve. assert expect2.is_stable() is False assert expect1.is_stable() is True assert stable_tf.is_stable() is True assert stable_tf_.is_stable() is True assert TF_.is_stable() is False assert expect4_.is_stable() is None # no assumption provided for the only pole 's'. assert SP4.is_stable() is None # Zeros of a transfer function. assert G1.zeros() == [1, 1] assert G2.zeros() == [] assert tf1.zeros() == [-3, 1] assert expect4_.zeros() == [7**(Rational(2, 3))*(-s)**(Rational(1, 3))/7, -7**(Rational(2, 3))*(-s)**(Rational(1, 3))/14 - sqrt(3)*7**(Rational(2, 3))*I*(-s)**(Rational(1, 3))/14, -7**(Rational(2, 3))*(-s)**(Rational(1, 3))/14 + sqrt(3)*7**(Rational(2, 3))*I*(-s)**(Rational(1, 3))/14] assert SP4.zeros() == [(s/a1)**(Rational(1, 3)), -(s/a1)**(Rational(1, 3))/2 - sqrt(3)*I*(s/a1)**(Rational(1, 3))/2, -(s/a1)**(Rational(1, 3))/2 + sqrt(3)*I*(s/a1)**(Rational(1, 3))/2] assert str(expect3.zeros()) == str([0.125 - 1.11102430216445*sqrt(-0.405063291139241*p**3 - 1.0), 1.11102430216445*sqrt(-0.405063291139241*p**3 - 1.0) + 0.125]) assert tf_.zeros() == [k**(Rational(1, 3)), -k**(Rational(1, 3))/2 - sqrt(3)*I*k**(Rational(1, 3))/2, -k**(Rational(1, 3))/2 + sqrt(3)*I*k**(Rational(1, 3))/2] assert _TF.zeros() == [CRootOf(x**9 + x + 1, 0), 0, CRootOf(x**9 + x + 1, 1), CRootOf(x**9 + x + 1, 2), CRootOf(x**9 + x + 1, 3), CRootOf(x**9 + x + 1, 4), CRootOf(x**9 + x + 1, 5), CRootOf(x**9 + x + 1, 6), CRootOf(x**9 + x + 1, 7), CRootOf(x**9 + x + 1, 8)] raises(NotImplementedError, lambda: TransferFunction(a0*x**10 + x + x**2, x**2, x).zeros()) # negation of TF. tf2 = TransferFunction(s + 3, s**2 - s**3 + 9, s) tf3 = TransferFunction(-3*p + 3, 1 - p, p) assert -tf2 == TransferFunction(-s - 3, s**2 - s**3 + 9, s) assert -tf3 == TransferFunction(3*p - 3, 1 - p, p) # taking power of a TF. tf4 = TransferFunction(p + 4, p - 3, p) tf5 = TransferFunction(s**2 + 1, 1 - s, s) expect2 = TransferFunction((s**2 + 1)**3, (1 - s)**3, s) expect1 = TransferFunction((p + 4)**2, (p - 3)**2, p) assert (tf4*tf4).doit() == tf4**2 == pow(tf4, 2) == expect1 assert (tf5*tf5*tf5).doit() == tf5**3 == pow(tf5, 3) == expect2 assert tf5**0 == pow(tf5, 0) == TransferFunction(1, 1, s) assert Series(tf4).doit()**-1 == tf4**-1 == pow(tf4, -1) == TransferFunction(p - 3, p + 4, p) assert (tf5*tf5).doit()**-1 == tf5**-2 == pow(tf5, -2) == TransferFunction((1 - s)**2, (s**2 + 1)**2, s) raises(ValueError, lambda: tf4**(s**2 + s - 1)) raises(ValueError, lambda: tf5**s) raises(ValueError, lambda: tf4**tf5) # sympy's own functions. tf = TransferFunction(s - 1, s**2 - 2*s + 1, s) tf6 = TransferFunction(s + p, p**2 - 5, s) assert factor(tf) == TransferFunction(s - 1, (s - 1)**2, s) assert tf.num.subs(s, 2) == tf.den.subs(s, 2) == 1 # subs & xreplace assert tf.subs(s, 2) == TransferFunction(s - 1, s**2 - 2*s + 1, s) assert tf6.subs(p, 3) == TransferFunction(s + 3, 4, s) assert tf3.xreplace({p: s}) == TransferFunction(-3*s + 3, 1 - s, s) raises(TypeError, lambda: tf3.xreplace({p: exp(2)})) assert tf3.subs(p, exp(2)) == tf3 tf7 = TransferFunction(a0*s**p + a1*p**s, a2*p - s, s) assert tf7.xreplace({s: k}) == TransferFunction(a0*k**p + a1*p**k, a2*p - k, k) assert tf7.subs(s, k) == TransferFunction(a0*s**p + a1*p**s, a2*p - s, s) # Conversion to Expr with to_expr() tf8 = TransferFunction(a0*s**5 + 5*s**2 + 3, s**6 - 3, s) tf9 = TransferFunction((5 + s), (5 + s)*(6 + s), s) tf10 = TransferFunction(0, 1, s) tf11 = TransferFunction(1, 1, s) assert tf8.to_expr() == Mul((a0*s**5 + 5*s**2 + 3), Pow((s**6 - 3), -1, evaluate=False), evaluate=False) assert tf9.to_expr() == Mul((s + 5), Pow((5 + s)*(6 + s), -1, evaluate=False), evaluate=False) assert tf10.to_expr() == Mul(S(0), Pow(1, -1, evaluate=False), evaluate=False) assert tf11.to_expr() == Pow(1, -1, evaluate=False) def test_TransferFunction_addition_and_subtraction(): tf1 = TransferFunction(s + 6, s - 5, s) tf2 = TransferFunction(s + 3, s + 1, s) tf3 = TransferFunction(s + 1, s**2 + s + 1, s) tf4 = TransferFunction(p, 2 - p, p) # addition assert tf1 + tf2 == Parallel(tf1, tf2) assert tf3 + tf1 == Parallel(tf3, tf1) assert -tf1 + tf2 + tf3 == Parallel(-tf1, tf2, tf3) assert tf1 + (tf2 + tf3) == Parallel(tf1, tf2, tf3) c = symbols("c", commutative=False) raises(ValueError, lambda: tf1 + Matrix([1, 2, 3])) raises(ValueError, lambda: tf2 + c) raises(ValueError, lambda: tf3 + tf4) raises(ValueError, lambda: tf1 + (s - 1)) raises(ValueError, lambda: tf1 + 8) raises(ValueError, lambda: (1 - p**3) + tf1) # subtraction assert tf1 - tf2 == Parallel(tf1, -tf2) assert tf3 - tf2 == Parallel(tf3, -tf2) assert -tf1 - tf3 == Parallel(-tf1, -tf3) assert tf1 - tf2 + tf3 == Parallel(tf1, -tf2, tf3) raises(ValueError, lambda: tf1 - Matrix([1, 2, 3])) raises(ValueError, lambda: tf3 - tf4) raises(ValueError, lambda: tf1 - (s - 1)) raises(ValueError, lambda: tf1 - 8) raises(ValueError, lambda: (s + 5) - tf2) raises(ValueError, lambda: (1 + p**4) - tf1) def test_TransferFunction_multiplication_and_division(): G1 = TransferFunction(s + 3, -s**3 + 9, s) G2 = TransferFunction(s + 1, s - 5, s) G3 = TransferFunction(p, p**4 - 6, p) G4 = TransferFunction(p + 4, p - 5, p) G5 = TransferFunction(s + 6, s - 5, s) G6 = TransferFunction(s + 3, s + 1, s) G7 = TransferFunction(1, 1, s) # multiplication assert G1*G2 == Series(G1, G2) assert -G1*G5 == Series(-G1, G5) assert -G2*G5*-G6 == Series(-G2, G5, -G6) assert -G1*-G2*-G5*-G6 == Series(-G1, -G2, -G5, -G6) assert G3*G4 == Series(G3, G4) assert (G1*G2)*-(G5*G6) == \ Series(G1, G2, TransferFunction(-1, 1, s), Series(G5, G6)) assert G1*G2*(G5 + G6) == Series(G1, G2, Parallel(G5, G6)) c = symbols("c", commutative=False) raises(ValueError, lambda: G3 * Matrix([1, 2, 3])) raises(ValueError, lambda: G1 * c) raises(ValueError, lambda: G3 * G5) raises(ValueError, lambda: G5 * (s - 1)) raises(ValueError, lambda: 9 * G5) raises(ValueError, lambda: G3 / Matrix([1, 2, 3])) raises(ValueError, lambda: G6 / 0) raises(ValueError, lambda: G3 / G5) raises(ValueError, lambda: G5 / 2) raises(ValueError, lambda: G5 / s**2) raises(ValueError, lambda: (s - 4*s**2) / G2) raises(ValueError, lambda: 0 / G4) raises(ValueError, lambda: G5 / G6) raises(ValueError, lambda: -G3 /G4) raises(ValueError, lambda: G7 / (1 + G6)) raises(ValueError, lambda: G7 / (G5 * G6)) raises(ValueError, lambda: G7 / (G7 + (G5 + G6))) def test_TransferFunction_is_proper(): omega_o, zeta, tau = symbols('omega_o, zeta, tau') G1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o) G2 = TransferFunction(tau - s**3, tau + p**4, tau) G3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p) G4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s) assert G1.is_proper assert G2.is_proper assert G3.is_proper assert not G4.is_proper def test_TransferFunction_is_strictly_proper(): omega_o, zeta, tau = symbols('omega_o, zeta, tau') tf1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o) tf2 = TransferFunction(tau - s**3, tau + p**4, tau) tf3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p) tf4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s) assert not tf1.is_strictly_proper assert not tf2.is_strictly_proper assert tf3.is_strictly_proper assert not tf4.is_strictly_proper def test_TransferFunction_is_biproper(): tau, omega_o, zeta = symbols('tau, omega_o, zeta') tf1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o) tf2 = TransferFunction(tau - s**3, tau + p**4, tau) tf3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p) tf4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s) assert tf1.is_biproper assert tf2.is_biproper assert not tf3.is_biproper assert not tf4.is_biproper def test_Series_construction(): tf = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s) tf2 = TransferFunction(a2*p - s, a2*s + p, s) tf3 = TransferFunction(a0*p + p**a1 - s, p, p) tf4 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s) inp = Function('X_d')(s) out = Function('X')(s) s0 = Series(tf, tf2) assert s0.args == (tf, tf2) assert s0.var == s s1 = Series(Parallel(tf, -tf2), tf2) assert s1.args == (Parallel(tf, -tf2), tf2) assert s1.var == s tf3_ = TransferFunction(inp, 1, s) tf4_ = TransferFunction(-out, 1, s) s2 = Series(tf, Parallel(tf3_, tf4_), tf2) assert s2.args == (tf, Parallel(tf3_, tf4_), tf2) s3 = Series(tf, tf2, tf4) assert s3.args == (tf, tf2, tf4) s4 = Series(tf3_, tf4_) assert s4.args == (tf3_, tf4_) assert s4.var == s s6 = Series(tf2, tf4, Parallel(tf2, -tf), tf4) assert s6.args == (tf2, tf4, Parallel(tf2, -tf), tf4) s7 = Series(tf, tf2) assert s0 == s7 assert not s0 == s2 raises(ValueError, lambda: Series(tf, tf3)) raises(ValueError, lambda: Series(tf, tf2, tf3, tf4)) raises(ValueError, lambda: Series(-tf3, tf2)) raises(TypeError, lambda: Series(2, tf, tf4)) raises(TypeError, lambda: Series(s**2 + p*s, tf3, tf2)) raises(TypeError, lambda: Series(tf3, Matrix([1, 2, 3, 4]))) def test_MIMOSeries_construction(): tf_1 = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s) tf_2 = TransferFunction(a2*p - s, a2*s + p, s) tf_3 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s) tfm_1 = TransferFunctionMatrix([[tf_1, tf_2, tf_3], [-tf_3, -tf_2, tf_1]]) tfm_2 = TransferFunctionMatrix([[-tf_2], [-tf_2], [-tf_3]]) tfm_3 = TransferFunctionMatrix([[-tf_3]]) tfm_4 = TransferFunctionMatrix([[TF3], [TF2], [-TF1]]) tfm_5 = TransferFunctionMatrix.from_Matrix(Matrix([1/p]), p) s8 = MIMOSeries(tfm_2, tfm_1) assert s8.args == (tfm_2, tfm_1) assert s8.var == s assert s8.shape == (s8.num_outputs, s8.num_inputs) == (2, 1) s9 = MIMOSeries(tfm_3, tfm_2, tfm_1) assert s9.args == (tfm_3, tfm_2, tfm_1) assert s9.var == s assert s9.shape == (s9.num_outputs, s9.num_inputs) == (2, 1) s11 = MIMOSeries(tfm_3, MIMOParallel(-tfm_2, -tfm_4), tfm_1) assert s11.args == (tfm_3, MIMOParallel(-tfm_2, -tfm_4), tfm_1) assert s11.shape == (s11.num_outputs, s11.num_inputs) == (2, 1) # arg cannot be empty tuple. raises(ValueError, lambda: MIMOSeries()) # arg cannot contain SISO as well as MIMO systems. raises(TypeError, lambda: MIMOSeries(tfm_1, tf_1)) # for all the adjascent transfer function matrices: # no. of inputs of first TFM must be equal to the no. of outputs of the second TFM. raises(ValueError, lambda: MIMOSeries(tfm_1, tfm_2, -tfm_1)) # all the TFMs must use the same complex variable. raises(ValueError, lambda: MIMOSeries(tfm_3, tfm_5)) # Number or expression not allowed in the arguments. raises(TypeError, lambda: MIMOSeries(2, tfm_2, tfm_3)) raises(TypeError, lambda: MIMOSeries(s**2 + p*s, -tfm_2, tfm_3)) raises(TypeError, lambda: MIMOSeries(Matrix([1/p]), tfm_3)) def test_Series_functions(): tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s) tf2 = TransferFunction(k, 1, s) tf3 = TransferFunction(a2*p - s, a2*s + p, s) tf4 = TransferFunction(a0*p + p**a1 - s, p, p) tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s) assert tf1*tf2*tf3 == Series(tf1, tf2, tf3) == Series(Series(tf1, tf2), tf3) \ == Series(tf1, Series(tf2, tf3)) assert tf1*(tf2 + tf3) == Series(tf1, Parallel(tf2, tf3)) assert tf1*tf2 + tf5 == Parallel(Series(tf1, tf2), tf5) assert tf1*tf2 - tf5 == Parallel(Series(tf1, tf2), -tf5) assert tf1*tf2 + tf3 + tf5 == Parallel(Series(tf1, tf2), tf3, tf5) assert tf1*tf2 - tf3 - tf5 == Parallel(Series(tf1, tf2), -tf3, -tf5) assert tf1*tf2 - tf3 + tf5 == Parallel(Series(tf1, tf2), -tf3, tf5) assert tf1*tf2 + tf3*tf5 == Parallel(Series(tf1, tf2), Series(tf3, tf5)) assert tf1*tf2 - tf3*tf5 == Parallel(Series(tf1, tf2), Series(TransferFunction(-1, 1, s), Series(tf3, tf5))) assert tf2*tf3*(tf2 - tf1)*tf3 == Series(tf2, tf3, Parallel(tf2, -tf1), tf3) assert -tf1*tf2 == Series(-tf1, tf2) assert -(tf1*tf2) == Series(TransferFunction(-1, 1, s), Series(tf1, tf2)) raises(ValueError, lambda: tf1*tf2*tf4) raises(ValueError, lambda: tf1*(tf2 - tf4)) raises(ValueError, lambda: tf3*Matrix([1, 2, 3])) # evaluate=True -> doit() assert Series(tf1, tf2, evaluate=True) == Series(tf1, tf2).doit() == \ TransferFunction(k, s**2 + 2*s*wn*zeta + wn**2, s) assert Series(tf1, tf2, Parallel(tf1, -tf3), evaluate=True) == Series(tf1, tf2, Parallel(tf1, -tf3)).doit() == \ TransferFunction(k*(a2*s + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)**2, s) assert Series(tf2, tf1, -tf3, evaluate=True) == Series(tf2, tf1, -tf3).doit() == \ TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s) assert not Series(tf1, -tf2, evaluate=False) == Series(tf1, -tf2).doit() assert Series(Parallel(tf1, tf2), Parallel(tf2, -tf3)).doit() == \ TransferFunction((k*(s**2 + 2*s*wn*zeta + wn**2) + 1)*(-a2*p + k*(a2*s + p) + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s) assert Series(-tf1, -tf2, -tf3).doit() == \ TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s) assert -Series(tf1, tf2, tf3).doit() == \ TransferFunction(-k*(a2*p - s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s) assert Series(tf2, tf3, Parallel(tf2, -tf1), tf3).doit() == \ TransferFunction(k*(a2*p - s)**2*(k*(s**2 + 2*s*wn*zeta + wn**2) - 1), (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2), s) assert Series(tf1, tf2).rewrite(TransferFunction) == TransferFunction(k, s**2 + 2*s*wn*zeta + wn**2, s) assert Series(tf2, tf1, -tf3).rewrite(TransferFunction) == \ TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s) S1 = Series(Parallel(tf1, tf2), Parallel(tf2, -tf3)) assert S1.is_proper assert not S1.is_strictly_proper assert S1.is_biproper S2 = Series(tf1, tf2, tf3) assert S2.is_proper assert S2.is_strictly_proper assert not S2.is_biproper S3 = Series(tf1, -tf2, Parallel(tf1, -tf3)) assert S3.is_proper assert S3.is_strictly_proper assert not S3.is_biproper def test_MIMOSeries_functions(): tfm1 = TransferFunctionMatrix([[TF1, TF2, TF3], [-TF3, -TF2, TF1]]) tfm2 = TransferFunctionMatrix([[-TF1], [-TF2], [-TF3]]) tfm3 = TransferFunctionMatrix([[-TF1]]) tfm4 = TransferFunctionMatrix([[-TF2, -TF3], [-TF1, TF2]]) tfm5 = TransferFunctionMatrix([[TF2, -TF2], [-TF3, -TF2]]) tfm6 = TransferFunctionMatrix([[-TF3], [TF1]]) tfm7 = TransferFunctionMatrix([[TF1], [-TF2]]) assert tfm1*tfm2 + tfm6 == MIMOParallel(MIMOSeries(tfm2, tfm1), tfm6) assert tfm1*tfm2 + tfm7 + tfm6 == MIMOParallel(MIMOSeries(tfm2, tfm1), tfm7, tfm6) assert tfm1*tfm2 - tfm6 - tfm7 == MIMOParallel(MIMOSeries(tfm2, tfm1), -tfm6, -tfm7) assert tfm4*tfm5 + (tfm4 - tfm5) == MIMOParallel(MIMOSeries(tfm5, tfm4), tfm4, -tfm5) assert tfm4*-tfm6 + (-tfm4*tfm6) == MIMOParallel(MIMOSeries(-tfm6, tfm4), MIMOSeries(tfm6, -tfm4)) raises(ValueError, lambda: tfm1*tfm2 + TF1) raises(TypeError, lambda: tfm1*tfm2 + a0) raises(TypeError, lambda: tfm4*tfm6 - (s - 1)) raises(TypeError, lambda: tfm4*-tfm6 - 8) raises(TypeError, lambda: (-1 + p**5) + tfm1*tfm2) # Shape criteria. raises(TypeError, lambda: -tfm1*tfm2 + tfm4) raises(TypeError, lambda: tfm1*tfm2 - tfm4 + tfm5) raises(TypeError, lambda: tfm1*tfm2 - tfm4*tfm5) assert tfm1*tfm2*-tfm3 == MIMOSeries(-tfm3, tfm2, tfm1) assert (tfm1*-tfm2)*tfm3 == MIMOSeries(tfm3, -tfm2, tfm1) # Multiplication of a Series object with a SISO TF not allowed. raises(ValueError, lambda: tfm4*tfm5*TF1) raises(TypeError, lambda: tfm4*tfm5*a1) raises(TypeError, lambda: tfm4*-tfm5*(s - 2)) raises(TypeError, lambda: tfm5*tfm4*9) raises(TypeError, lambda: (-p**3 + 1)*tfm5*tfm4) # Transfer function matrix in the arguments. assert (MIMOSeries(tfm2, tfm1, evaluate=True) == MIMOSeries(tfm2, tfm1).doit() == TransferFunctionMatrix(((TransferFunction(-k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2)**2 - (a2*s + p)**2, (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2, s),), (TransferFunction(k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*p - s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2, s),)))) # doit() should not cancel poles and zeros. mat_1 = Matrix([[1/(1+s), (1+s)/(1+s**2+2*s)**3]]) mat_2 = Matrix([[(1+s)], [(1+s**2+2*s)**3/(1+s)]]) tm_1, tm_2 = TransferFunctionMatrix.from_Matrix(mat_1, s), TransferFunctionMatrix.from_Matrix(mat_2, s) assert (MIMOSeries(tm_2, tm_1).doit() == TransferFunctionMatrix(((TransferFunction(2*(s + 1)**2*(s**2 + 2*s + 1)**3, (s + 1)**2*(s**2 + 2*s + 1)**3, s),),))) assert MIMOSeries(tm_2, tm_1).doit().simplify() == TransferFunctionMatrix(((TransferFunction(2, 1, s),),)) # calling doit() will expand the internal Series and Parallel objects. assert (MIMOSeries(-tfm3, -tfm2, tfm1, evaluate=True) == MIMOSeries(-tfm3, -tfm2, tfm1).doit() == TransferFunctionMatrix(((TransferFunction(k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (a2*p - s)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (a2*s + p)**2, (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**3, s),), (TransferFunction(-k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*p - s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**3, s),)))) assert (MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5, evaluate=True) == MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5).doit() == TransferFunctionMatrix(((TransferFunction(-k*(-a2*s - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s), TransferFunction(k*(-a2*p - \ k*(a2*s + p) + s), a2*s + p, s)), (TransferFunction(-k*(-a2*s - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s), \ TransferFunction((-a2*p + s)*(-a2*p - k*(a2*s + p) + s), (a2*s + p)**2, s)))) == MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5).rewrite(TransferFunctionMatrix)) def test_Parallel_construction(): tf = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s) tf2 = TransferFunction(a2*p - s, a2*s + p, s) tf3 = TransferFunction(a0*p + p**a1 - s, p, p) tf4 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s) inp = Function('X_d')(s) out = Function('X')(s) p0 = Parallel(tf, tf2) assert p0.args == (tf, tf2) assert p0.var == s p1 = Parallel(Series(tf, -tf2), tf2) assert p1.args == (Series(tf, -tf2), tf2) assert p1.var == s tf3_ = TransferFunction(inp, 1, s) tf4_ = TransferFunction(-out, 1, s) p2 = Parallel(tf, Series(tf3_, -tf4_), tf2) assert p2.args == (tf, Series(tf3_, -tf4_), tf2) p3 = Parallel(tf, tf2, tf4) assert p3.args == (tf, tf2, tf4) p4 = Parallel(tf3_, tf4_) assert p4.args == (tf3_, tf4_) assert p4.var == s p5 = Parallel(tf, tf2) assert p0 == p5 assert not p0 == p1 p6 = Parallel(tf2, tf4, Series(tf2, -tf4)) assert p6.args == (tf2, tf4, Series(tf2, -tf4)) p7 = Parallel(tf2, tf4, Series(tf2, -tf), tf4) assert p7.args == (tf2, tf4, Series(tf2, -tf), tf4) raises(ValueError, lambda: Parallel(tf, tf3)) raises(ValueError, lambda: Parallel(tf, tf2, tf3, tf4)) raises(ValueError, lambda: Parallel(-tf3, tf4)) raises(TypeError, lambda: Parallel(2, tf, tf4)) raises(TypeError, lambda: Parallel(s**2 + p*s, tf3, tf2)) raises(TypeError, lambda: Parallel(tf3, Matrix([1, 2, 3, 4]))) def test_MIMOParallel_construction(): tfm1 = TransferFunctionMatrix([[TF1], [TF2], [TF3]]) tfm2 = TransferFunctionMatrix([[-TF3], [TF2], [TF1]]) tfm3 = TransferFunctionMatrix([[TF1]]) tfm4 = TransferFunctionMatrix([[TF2], [TF1], [TF3]]) tfm5 = TransferFunctionMatrix([[TF1, TF2], [TF2, TF1]]) tfm6 = TransferFunctionMatrix([[TF2, TF1], [TF1, TF2]]) tfm7 = TransferFunctionMatrix.from_Matrix(Matrix([[1/p]]), p) p8 = MIMOParallel(tfm1, tfm2) assert p8.args == (tfm1, tfm2) assert p8.var == s assert p8.shape == (p8.num_outputs, p8.num_inputs) == (3, 1) p9 = MIMOParallel(MIMOSeries(tfm3, tfm1), tfm2) assert p9.args == (MIMOSeries(tfm3, tfm1), tfm2) assert p9.var == s assert p9.shape == (p9.num_outputs, p9.num_inputs) == (3, 1) p10 = MIMOParallel(tfm1, MIMOSeries(tfm3, tfm4), tfm2) assert p10.args == (tfm1, MIMOSeries(tfm3, tfm4), tfm2) assert p10.var == s assert p10.shape == (p10.num_outputs, p10.num_inputs) == (3, 1) p11 = MIMOParallel(tfm2, tfm1, tfm4) assert p11.args == (tfm2, tfm1, tfm4) assert p11.shape == (p11.num_outputs, p11.num_inputs) == (3, 1) p12 = MIMOParallel(tfm6, tfm5) assert p12.args == (tfm6, tfm5) assert p12.shape == (p12.num_outputs, p12.num_inputs) == (2, 2) p13 = MIMOParallel(tfm2, tfm4, MIMOSeries(-tfm3, tfm4), -tfm4) assert p13.args == (tfm2, tfm4, MIMOSeries(-tfm3, tfm4), -tfm4) assert p13.shape == (p13.num_outputs, p13.num_inputs) == (3, 1) # arg cannot be empty tuple. raises(TypeError, lambda: MIMOParallel(())) # arg cannot contain SISO as well as MIMO systems. raises(TypeError, lambda: MIMOParallel(tfm1, tfm2, TF1)) # all TFMs must have same shapes. raises(TypeError, lambda: MIMOParallel(tfm1, tfm3, tfm4)) # all TFMs must be using the same complex variable. raises(ValueError, lambda: MIMOParallel(tfm3, tfm7)) # Number or expression not allowed in the arguments. raises(TypeError, lambda: MIMOParallel(2, tfm1, tfm4)) raises(TypeError, lambda: MIMOParallel(s**2 + p*s, -tfm4, tfm2)) def test_Parallel_functions(): tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s) tf2 = TransferFunction(k, 1, s) tf3 = TransferFunction(a2*p - s, a2*s + p, s) tf4 = TransferFunction(a0*p + p**a1 - s, p, p) tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s) assert tf1 + tf2 + tf3 == Parallel(tf1, tf2, tf3) assert tf1 + tf2 + tf3 + tf5 == Parallel(tf1, tf2, tf3, tf5) assert tf1 + tf2 - tf3 - tf5 == Parallel(tf1, tf2, -tf3, -tf5) assert tf1 + tf2*tf3 == Parallel(tf1, Series(tf2, tf3)) assert tf1 - tf2*tf3 == Parallel(tf1, -Series(tf2,tf3)) assert -tf1 - tf2 == Parallel(-tf1, -tf2) assert -(tf1 + tf2) == Series(TransferFunction(-1, 1, s), Parallel(tf1, tf2)) assert (tf2 + tf3)*tf1 == Series(Parallel(tf2, tf3), tf1) assert (tf1 + tf2)*(tf3*tf5) == Series(Parallel(tf1, tf2), tf3, tf5) assert -(tf2 + tf3)*-tf5 == Series(TransferFunction(-1, 1, s), Parallel(tf2, tf3), -tf5) assert tf2 + tf3 + tf2*tf1 + tf5 == Parallel(tf2, tf3, Series(tf2, tf1), tf5) assert tf2 + tf3 + tf2*tf1 - tf3 == Parallel(tf2, tf3, Series(tf2, tf1), -tf3) assert (tf1 + tf2 + tf5)*(tf3 + tf5) == Series(Parallel(tf1, tf2, tf5), Parallel(tf3, tf5)) raises(ValueError, lambda: tf1 + tf2 + tf4) raises(ValueError, lambda: tf1 - tf2*tf4) raises(ValueError, lambda: tf3 + Matrix([1, 2, 3])) # evaluate=True -> doit() assert Parallel(tf1, tf2, evaluate=True) == Parallel(tf1, tf2).doit() == \ TransferFunction(k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s) assert Parallel(tf1, tf2, Series(-tf1, tf3), evaluate=True) == \ Parallel(tf1, tf2, Series(-tf1, tf3)).doit() == TransferFunction(k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)**2 + \ (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), (a2*s + p)*(s**2 + \ 2*s*wn*zeta + wn**2)**2, s) assert Parallel(tf2, tf1, -tf3, evaluate=True) == Parallel(tf2, tf1, -tf3).doit() == \ TransferFunction(a2*s + k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2) \ , (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s) assert not Parallel(tf1, -tf2, evaluate=False) == Parallel(tf1, -tf2).doit() assert Parallel(Series(tf1, tf2), Series(tf2, tf3)).doit() == \ TransferFunction(k*(a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2) + k*(a2*s + p), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s) assert Parallel(-tf1, -tf2, -tf3).doit() == \ TransferFunction(-a2*s - k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2), \ (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s) assert -Parallel(tf1, tf2, tf3).doit() == \ TransferFunction(-a2*s - k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - p - (a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2), \ (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s) assert Parallel(tf2, tf3, Series(tf2, -tf1), tf3).doit() == \ TransferFunction(k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - k*(a2*s + p) + (2*a2*p - 2*s)*(s**2 + 2*s*wn*zeta \ + wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s) assert Parallel(tf1, tf2).rewrite(TransferFunction) == \ TransferFunction(k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s) assert Parallel(tf2, tf1, -tf3).rewrite(TransferFunction) == \ TransferFunction(a2*s + k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + \ wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s) assert Parallel(tf1, Parallel(tf2, tf3)) == Parallel(tf1, tf2, tf3) == Parallel(Parallel(tf1, tf2), tf3) P1 = Parallel(Series(tf1, tf2), Series(tf2, tf3)) assert P1.is_proper assert not P1.is_strictly_proper assert P1.is_biproper P2 = Parallel(tf1, -tf2, -tf3) assert P2.is_proper assert not P2.is_strictly_proper assert P2.is_biproper P3 = Parallel(tf1, -tf2, Series(tf1, tf3)) assert P3.is_proper assert not P3.is_strictly_proper assert P3.is_biproper def test_MIMOParallel_functions(): tf4 = TransferFunction(a0*p + p**a1 - s, p, p) tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s) tfm1 = TransferFunctionMatrix([[TF1], [TF2], [TF3]]) tfm2 = TransferFunctionMatrix([[-TF2], [tf5], [-TF1]]) tfm3 = TransferFunctionMatrix([[tf5], [-tf5], [TF2]]) tfm4 = TransferFunctionMatrix([[TF2, -tf5], [TF1, tf5]]) tfm5 = TransferFunctionMatrix([[TF1, TF2], [TF3, -tf5]]) tfm6 = TransferFunctionMatrix([[-TF2]]) tfm7 = TransferFunctionMatrix([[tf4], [-tf4], [tf4]]) assert tfm1 + tfm2 + tfm3 == MIMOParallel(tfm1, tfm2, tfm3) == MIMOParallel(MIMOParallel(tfm1, tfm2), tfm3) assert tfm2 - tfm1 - tfm3 == MIMOParallel(tfm2, -tfm1, -tfm3) assert tfm2 - tfm3 + (-tfm1*tfm6*-tfm6) == MIMOParallel(tfm2, -tfm3, MIMOSeries(-tfm6, tfm6, -tfm1)) assert tfm1 + tfm1 - (-tfm1*tfm6) == MIMOParallel(tfm1, tfm1, -MIMOSeries(tfm6, -tfm1)) assert tfm2 - tfm3 - tfm1 + tfm2 == MIMOParallel(tfm2, -tfm3, -tfm1, tfm2) assert tfm1 + tfm2 - tfm3 - tfm1 == MIMOParallel(tfm1, tfm2, -tfm3, -tfm1) raises(ValueError, lambda: tfm1 + tfm2 + TF2) raises(TypeError, lambda: tfm1 - tfm2 - a1) raises(TypeError, lambda: tfm2 - tfm3 - (s - 1)) raises(TypeError, lambda: -tfm3 - tfm2 - 9) raises(TypeError, lambda: (1 - p**3) - tfm3 - tfm2) # All TFMs must use the same complex var. tfm7 uses 'p'. raises(ValueError, lambda: tfm3 - tfm2 - tfm7) raises(ValueError, lambda: tfm2 - tfm1 + tfm7) # (tfm1 +/- tfm2) has (3, 1) shape while tfm4 has (2, 2) shape. raises(TypeError, lambda: tfm1 + tfm2 + tfm4) raises(TypeError, lambda: (tfm1 - tfm2) - tfm4) assert (tfm1 + tfm2)*tfm6 == MIMOSeries(tfm6, MIMOParallel(tfm1, tfm2)) assert (tfm2 - tfm3)*tfm6*-tfm6 == MIMOSeries(-tfm6, tfm6, MIMOParallel(tfm2, -tfm3)) assert (tfm2 - tfm1 - tfm3)*(tfm6 + tfm6) == MIMOSeries(MIMOParallel(tfm6, tfm6), MIMOParallel(tfm2, -tfm1, -tfm3)) raises(ValueError, lambda: (tfm4 + tfm5)*TF1) raises(TypeError, lambda: (tfm2 - tfm3)*a2) raises(TypeError, lambda: (tfm3 + tfm2)*(s - 6)) raises(TypeError, lambda: (tfm1 + tfm2 + tfm3)*0) raises(TypeError, lambda: (1 - p**3)*(tfm1 + tfm3)) # (tfm3 - tfm2) has (3, 1) shape while tfm4*tfm5 has (2, 2) shape. raises(ValueError, lambda: (tfm3 - tfm2)*tfm4*tfm5) # (tfm1 - tfm2) has (3, 1) shape while tfm5 has (2, 2) shape. raises(ValueError, lambda: (tfm1 - tfm2)*tfm5) # TFM in the arguments. assert (MIMOParallel(tfm1, tfm2, evaluate=True) == MIMOParallel(tfm1, tfm2).doit() == MIMOParallel(tfm1, tfm2).rewrite(TransferFunctionMatrix) == TransferFunctionMatrix(((TransferFunction(-k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s),), \ (TransferFunction(-a0 + a1*s**2 + a2*s + k*(a0 + s), a0 + s, s),), (TransferFunction(-a2*s - p + (a2*p - s)* \ (s**2 + 2*s*wn*zeta + wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s),)))) def test_Feedback_construction(): tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s) tf2 = TransferFunction(k, 1, s) tf3 = TransferFunction(a2*p - s, a2*s + p, s) tf4 = TransferFunction(a0*p + p**a1 - s, p, p) tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s) tf6 = TransferFunction(s - p, p + s, p) f1 = Feedback(TransferFunction(1, 1, s), tf1*tf2*tf3) assert f1.args == (TransferFunction(1, 1, s), Series(tf1, tf2, tf3), -1) assert f1.sys1 == TransferFunction(1, 1, s) assert f1.sys2 == Series(tf1, tf2, tf3) assert f1.var == s f2 = Feedback(tf1, tf2*tf3) assert f2.args == (tf1, Series(tf2, tf3), -1) assert f2.sys1 == tf1 assert f2.sys2 == Series(tf2, tf3) assert f2.var == s f3 = Feedback(tf1*tf2, tf5) assert f3.args == (Series(tf1, tf2), tf5, -1) assert f3.sys1 == Series(tf1, tf2) f4 = Feedback(tf4, tf6) assert f4.args == (tf4, tf6, -1) assert f4.sys1 == tf4 assert f4.var == p f5 = Feedback(tf5, TransferFunction(1, 1, s)) assert f5.args == (tf5, TransferFunction(1, 1, s), -1) assert f5.var == s assert f5 == Feedback(tf5) # When sys2 is not passed explicitly, it is assumed to be unit tf. f6 = Feedback(TransferFunction(1, 1, p), tf4) assert f6.args == (TransferFunction(1, 1, p), tf4, -1) assert f6.var == p f7 = -Feedback(tf4*tf6, TransferFunction(1, 1, p)) assert f7.args == (Series(TransferFunction(-1, 1, p), Series(tf4, tf6)), -TransferFunction(1, 1, p), -1) assert f7.sys1 == Series(TransferFunction(-1, 1, p), Series(tf4, tf6)) # denominator can't be a Parallel instance raises(TypeError, lambda: Feedback(tf1, tf2 + tf3)) raises(TypeError, lambda: Feedback(tf1, Matrix([1, 2, 3]))) raises(TypeError, lambda: Feedback(TransferFunction(1, 1, s), s - 1)) raises(TypeError, lambda: Feedback(1, 1)) # raises(ValueError, lambda: Feedback(TransferFunction(1, 1, s), TransferFunction(1, 1, s))) raises(ValueError, lambda: Feedback(tf2, tf4*tf5)) raises(ValueError, lambda: Feedback(tf2, tf1, 1.5)) # `sign` can only be -1 or 1 raises(ValueError, lambda: Feedback(tf1, -tf1**-1)) # denominator can't be zero raises(ValueError, lambda: Feedback(tf4, tf5)) # Both systems should use the same `var` def test_Feedback_functions(): tf = TransferFunction(1, 1, s) tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s) tf2 = TransferFunction(k, 1, s) tf3 = TransferFunction(a2*p - s, a2*s + p, s) tf4 = TransferFunction(a0*p + p**a1 - s, p, p) tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s) tf6 = TransferFunction(s - p, p + s, p) assert tf / (tf + tf1) == Feedback(tf, tf1) assert tf / (tf + tf1*tf2*tf3) == Feedback(tf, tf1*tf2*tf3) assert tf1 / (tf + tf1*tf2*tf3) == Feedback(tf1, tf2*tf3) assert (tf1*tf2) / (tf + tf1*tf2) == Feedback(tf1*tf2, tf) assert (tf1*tf2) / (tf + tf1*tf2*tf5) == Feedback(tf1*tf2, tf5) assert (tf1*tf2) / (tf + tf1*tf2*tf5*tf3) in (Feedback(tf1*tf2, tf5*tf3), Feedback(tf1*tf2, tf3*tf5)) assert tf4 / (TransferFunction(1, 1, p) + tf4*tf6) == Feedback(tf4, tf6) assert tf5 / (tf + tf5) == Feedback(tf5, tf) raises(TypeError, lambda: tf1*tf2*tf3 / (1 + tf1*tf2*tf3)) raises(ValueError, lambda: tf1*tf2*tf3 / tf3*tf5) raises(ValueError, lambda: tf2*tf3 / (tf + tf2*tf3*tf4)) assert Feedback(tf, tf1*tf2*tf3).doit() == \ TransferFunction((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), k*(a2*p - s) + \ (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s) assert Feedback(tf, tf1*tf2*tf3).sensitivity == \ 1/(k*(a2*p - s)/((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)) + 1) assert Feedback(tf1, tf2*tf3).doit() == \ TransferFunction((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), (k*(a2*p - s) + \ (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s) assert Feedback(tf1, tf2*tf3).sensitivity == \ 1/(k*(a2*p - s)/((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)) + 1) assert Feedback(tf1*tf2, tf5).doit() == \ TransferFunction(k*(a0 + s)*(s**2 + 2*s*wn*zeta + wn**2), (k*(-a0 + a1*s**2 + a2*s) + \ (a0 + s)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s) assert Feedback(tf1*tf2, tf5, 1).sensitivity == \ 1/(-k*(-a0 + a1*s**2 + a2*s)/((a0 + s)*(s**2 + 2*s*wn*zeta + wn**2)) + 1) assert Feedback(tf4, tf6).doit() == \ TransferFunction(p*(p + s)*(a0*p + p**a1 - s), p*(p*(p + s) + (-p + s)*(a0*p + p**a1 - s)), p) assert -Feedback(tf4*tf6, TransferFunction(1, 1, p)).doit() == \ TransferFunction(-p*(-p + s)*(p + s)*(a0*p + p**a1 - s), p*(p + s)*(p*(p + s) + (-p + s)*(a0*p + p**a1 - s)), p) assert Feedback(tf, tf).doit() == TransferFunction(1, 2, s) assert Feedback(tf1, tf2*tf5).rewrite(TransferFunction) == \ TransferFunction((a0 + s)*(s**2 + 2*s*wn*zeta + wn**2), (k*(-a0 + a1*s**2 + a2*s) + \ (a0 + s)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s) assert Feedback(TransferFunction(1, 1, p), tf4).rewrite(TransferFunction) == \ TransferFunction(p, a0*p + p + p**a1 - s, p) def test_MIMOFeedback_construction(): tf1 = TransferFunction(1, s, s) tf2 = TransferFunction(s, s**3 - 1, s) tf3 = TransferFunction(s, s + 1, s) tf4 = TransferFunction(s, s**2 + 1, s) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]]) tfm_2 = TransferFunctionMatrix([[tf2, tf3], [tf4, tf1]]) tfm_3 = TransferFunctionMatrix([[tf3, tf4], [tf1, tf2]]) f1 = MIMOFeedback(tfm_1, tfm_2) assert f1.args == (tfm_1, tfm_2, -1) assert f1.sys1 == tfm_1 assert f1.sys2 == tfm_2 assert f1.var == s assert f1.sign == -1 assert -(-f1) == f1 f2 = MIMOFeedback(tfm_2, tfm_1, 1) assert f2.args == (tfm_2, tfm_1, 1) assert f2.sys1 == tfm_2 assert f2.sys2 == tfm_1 assert f2.var == s assert f2.sign == 1 f3 = MIMOFeedback(tfm_1, MIMOSeries(tfm_3, tfm_2)) assert f3.args == (tfm_1, MIMOSeries(tfm_3, tfm_2), -1) assert f3.sys1 == tfm_1 assert f3.sys2 == MIMOSeries(tfm_3, tfm_2) assert f3.var == s assert f3.sign == -1 mat = Matrix([[1, 1/s], [0, 1]]) sys1 = controller = TransferFunctionMatrix.from_Matrix(mat, s) f4 = MIMOFeedback(sys1, controller) assert f4.args == (sys1, controller, -1) assert f4.sys1 == f4.sys2 == sys1 def test_MIMOFeedback_errors(): tf1 = TransferFunction(1, s, s) tf2 = TransferFunction(s, s**3 - 1, s) tf3 = TransferFunction(s, s - 1, s) tf4 = TransferFunction(s, s**2 + 1, s) tf5 = TransferFunction(1, 1, s) tf6 = TransferFunction(-1, s - 1, s) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]]) tfm_2 = TransferFunctionMatrix([[tf2, tf3], [tf4, tf1]]) tfm_3 = TransferFunctionMatrix.from_Matrix(eye(2), var=s) tfm_4 = TransferFunctionMatrix([[tf1, tf5], [tf5, tf5]]) tfm_5 = TransferFunctionMatrix([[-tf3, tf3], [tf3, tf6]]) # tfm_4 is inverse of tfm_5. Therefore tfm_5*tfm_4 = I tfm_6 = TransferFunctionMatrix([[-tf3]]) tfm_7 = TransferFunctionMatrix([[tf3, tf4]]) # Unsupported Types raises(TypeError, lambda: MIMOFeedback(tf1, tf2)) raises(TypeError, lambda: MIMOFeedback(MIMOParallel(tfm_1, tfm_2), tfm_3)) # Shape Errors raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_6, 1)) raises(ValueError, lambda: MIMOFeedback(tfm_7, tfm_7)) # sign not 1/-1 raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_2, -2)) # Non-Invertible Systems raises(ValueError, lambda: MIMOFeedback(tfm_5, tfm_4, 1)) raises(ValueError, lambda: MIMOFeedback(tfm_4, -tfm_5)) raises(ValueError, lambda: MIMOFeedback(tfm_3, tfm_3, 1)) # Variable not same in both the systems tfm_8 = TransferFunctionMatrix.from_Matrix(eye(2), var=p) raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_8, 1)) def test_MIMOFeedback_functions(): tf1 = TransferFunction(1, s, s) tf2 = TransferFunction(s, s - 1, s) tf3 = TransferFunction(1, 1, s) tf4 = TransferFunction(-1, s - 1, s) tfm_1 = TransferFunctionMatrix.from_Matrix(eye(2), var=s) tfm_2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf3]]) tfm_3 = TransferFunctionMatrix([[-tf2, tf2], [tf2, tf4]]) tfm_4 = TransferFunctionMatrix([[tf1, tf2], [-tf2, tf1]]) # sensitivity, doit(), rewrite() F_1 = MIMOFeedback(tfm_2, tfm_3) F_2 = MIMOFeedback(tfm_2, MIMOSeries(tfm_4, -tfm_1), 1) assert F_1.sensitivity == Matrix([[1/2, 0], [0, 1/2]]) assert F_2.sensitivity == Matrix([[(-2*s**4 + s**2)/(s**2 - s + 1), (2*s**3 - s**2)/(s**2 - s + 1)], [-s**2, s]]) assert F_1.doit() == \ TransferFunctionMatrix(((TransferFunction(1, 2*s, s), TransferFunction(1, 2, s)), (TransferFunction(1, 2, s), TransferFunction(1, 2, s)))) == F_1.rewrite(TransferFunctionMatrix) assert F_2.doit(cancel=False, expand=True) == \ TransferFunctionMatrix(((TransferFunction(-s**5 + 2*s**4 - 2*s**3 + s**2, s**5 - 2*s**4 + 3*s**3 - 2*s**2 + s, s), TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)), (TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s)))) assert F_2.doit(cancel=False) == \ TransferFunctionMatrix(((TransferFunction(s*(2*s**3 - s**2)*(s**2 - s + 1) + \ (-2*s**4 + s**2)*(s**2 - s + 1), s*(s**2 - s + 1)**2, s), TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)), (TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s)))) assert F_2.doit() == \ TransferFunctionMatrix(((TransferFunction(s*(-2*s**2 + s*(2*s - 1) + 1), s**2 - s + 1, s), TransferFunction(2*s**3*(1 - s), s**2 - s + 1, s)), (TransferFunction(0, 1, s), TransferFunction(s*(1 - s), 1, s)))) assert F_2.doit(expand=True) == \ TransferFunctionMatrix(((TransferFunction(-s**2 + s, s**2 - s + 1, s), TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)), (TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s)))) assert -(F_1.doit()) == (-F_1).doit() # First negating then calculating vs calculating then negating. def test_TransferFunctionMatrix_construction(): tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s) tf4 = TransferFunction(a0*p + p**a1 - s, p, p) tfm3_ = TransferFunctionMatrix([[-TF3]]) assert tfm3_.shape == (tfm3_.num_outputs, tfm3_.num_inputs) == (1, 1) assert tfm3_.args == Tuple(Tuple(Tuple(-TF3))) assert tfm3_.var == s tfm5 = TransferFunctionMatrix([[TF1, -TF2], [TF3, tf5]]) assert tfm5.shape == (tfm5.num_outputs, tfm5.num_inputs) == (2, 2) assert tfm5.args == Tuple(Tuple(Tuple(TF1, -TF2), Tuple(TF3, tf5))) assert tfm5.var == s tfm7 = TransferFunctionMatrix([[TF1, TF2], [TF3, -tf5], [-tf5, TF2]]) assert tfm7.shape == (tfm7.num_outputs, tfm7.num_inputs) == (3, 2) assert tfm7.args == Tuple(Tuple(Tuple(TF1, TF2), Tuple(TF3, -tf5), Tuple(-tf5, TF2))) assert tfm7.var == s # all transfer functions will use the same complex variable. tf4 uses 'p'. raises(ValueError, lambda: TransferFunctionMatrix([[TF1], [TF2], [tf4]])) raises(ValueError, lambda: TransferFunctionMatrix([[TF1, tf4], [TF3, tf5]])) # length of all the lists in the TFM should be equal. raises(ValueError, lambda: TransferFunctionMatrix([[TF1], [TF3, tf5]])) raises(ValueError, lambda: TransferFunctionMatrix([[TF1, TF3], [tf5]])) # lists should only support transfer functions in them. raises(TypeError, lambda: TransferFunctionMatrix([[TF1, TF2], [TF3, Matrix([1, 2])]])) raises(TypeError, lambda: TransferFunctionMatrix([[TF1, Matrix([1, 2])], [TF3, TF2]])) # `arg` should strictly be nested list of TransferFunction raises(ValueError, lambda: TransferFunctionMatrix([TF1, TF2, tf5])) raises(ValueError, lambda: TransferFunctionMatrix([TF1])) def test_TransferFunctionMatrix_functions(): tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s) # Classmethod (from_matrix) mat_1 = ImmutableMatrix([ [s*(s + 1)*(s - 3)/(s**4 + 1), 2], [p, p*(s + 1)/(s*(s**1 + 1))] ]) mat_2 = ImmutableMatrix([[(2*s + 1)/(s**2 - 9)]]) mat_3 = ImmutableMatrix([[1, 2], [3, 4]]) assert TransferFunctionMatrix.from_Matrix(mat_1, s) == \ TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(p, 1, s), TransferFunction(p, s, s)]]) assert TransferFunctionMatrix.from_Matrix(mat_2, s) == \ TransferFunctionMatrix([[TransferFunction(2*s + 1, s**2 - 9, s)]]) assert TransferFunctionMatrix.from_Matrix(mat_3, p) == \ TransferFunctionMatrix([[TransferFunction(1, 1, p), TransferFunction(2, 1, p)], [TransferFunction(3, 1, p), TransferFunction(4, 1, p)]]) # Negating a TFM tfm1 = TransferFunctionMatrix([[TF1], [TF2]]) assert -tfm1 == TransferFunctionMatrix([[-TF1], [-TF2]]) tfm2 = TransferFunctionMatrix([[TF1, TF2, TF3], [tf5, -TF1, -TF3]]) assert -tfm2 == TransferFunctionMatrix([[-TF1, -TF2, -TF3], [-tf5, TF1, TF3]]) # subs() H_1 = TransferFunctionMatrix.from_Matrix(mat_1, s) H_2 = TransferFunctionMatrix([[TransferFunction(a*p*s, k*s**2, s), TransferFunction(p*s, k*(s**2 - a), s)]]) assert H_1.subs(p, 1) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]]) assert H_1.subs({p: 1}) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]]) assert H_1.subs({p: 1, s: 1}) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]]) # This should ignore `s` as it is `var` assert H_2.subs(p, 2) == TransferFunctionMatrix([[TransferFunction(2*a*s, k*s**2, s), TransferFunction(2*s, k*(-a + s**2), s)]]) assert H_2.subs(k, 1) == TransferFunctionMatrix([[TransferFunction(a*p*s, s**2, s), TransferFunction(p*s, -a + s**2, s)]]) assert H_2.subs(a, 0) == TransferFunctionMatrix([[TransferFunction(0, k*s**2, s), TransferFunction(p*s, k*s**2, s)]]) assert H_2.subs({p: 1, k: 1, a: a0}) == TransferFunctionMatrix([[TransferFunction(a0*s, s**2, s), TransferFunction(s, -a0 + s**2, s)]]) # transpose() assert H_1.transpose() == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(p, 1, s)], [TransferFunction(2, 1, s), TransferFunction(p, s, s)]]) assert H_2.transpose() == TransferFunctionMatrix([[TransferFunction(a*p*s, k*s**2, s)], [TransferFunction(p*s, k*(-a + s**2), s)]]) assert H_1.transpose().transpose() == H_1 assert H_2.transpose().transpose() == H_2 # elem_poles() assert H_1.elem_poles() == [[[-sqrt(2)/2 - sqrt(2)*I/2, -sqrt(2)/2 + sqrt(2)*I/2, sqrt(2)/2 - sqrt(2)*I/2, sqrt(2)/2 + sqrt(2)*I/2], []], [[], [0]]] assert H_2.elem_poles() == [[[0, 0], [sqrt(a), -sqrt(a)]]] assert tfm2.elem_poles() == [[[wn*(-zeta + sqrt((zeta - 1)*(zeta + 1))), wn*(-zeta - sqrt((zeta - 1)*(zeta + 1)))], [], [-p/a2]], [[-a0], [wn*(-zeta + sqrt((zeta - 1)*(zeta + 1))), wn*(-zeta - sqrt((zeta - 1)*(zeta + 1)))], [-p/a2]]] # elem_zeros() assert H_1.elem_zeros() == [[[-1, 0, 3], []], [[], []]] assert H_2.elem_zeros() == [[[0], [0]]] assert tfm2.elem_zeros() == [[[], [], [a2*p]], [[-a2/(2*a1) - sqrt(4*a0*a1 + a2**2)/(2*a1), -a2/(2*a1) + sqrt(4*a0*a1 + a2**2)/(2*a1)], [], [a2*p]]] # doit() H_3 = TransferFunctionMatrix([[Series(TransferFunction(1, s**3 - 3, s), TransferFunction(s**2 - 2*s + 5, 1, s), TransferFunction(1, s, s))]]) H_4 = TransferFunctionMatrix([[Parallel(TransferFunction(s**3 - 3, 4*s**4 - s**2 - 2*s + 5, s), TransferFunction(4 - s**3, 4*s**4 - s**2 - 2*s + 5, s))]]) assert H_3.doit() == TransferFunctionMatrix([[TransferFunction(s**2 - 2*s + 5, s*(s**3 - 3), s)]]) assert H_4.doit() == TransferFunctionMatrix([[TransferFunction(1, 4*s**4 - s**2 - 2*s + 5, s)]]) # _flat() assert H_1._flat() == [TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s), TransferFunction(p, 1, s), TransferFunction(p, s, s)] assert H_2._flat() == [TransferFunction(a*p*s, k*s**2, s), TransferFunction(p*s, k*(-a + s**2), s)] assert H_3._flat() == [Series(TransferFunction(1, s**3 - 3, s), TransferFunction(s**2 - 2*s + 5, 1, s), TransferFunction(1, s, s))] assert H_4._flat() == [Parallel(TransferFunction(s**3 - 3, 4*s**4 - s**2 - 2*s + 5, s), TransferFunction(4 - s**3, 4*s**4 - s**2 - 2*s + 5, s))] # evalf() assert H_1.evalf() == \ TransferFunctionMatrix(((TransferFunction(s*(s - 3.0)*(s + 1.0), s**4 + 1.0, s), TransferFunction(2.0, 1, s)), (TransferFunction(1.0*p, 1, s), TransferFunction(p, s, s)))) assert H_2.subs({a:3.141, p:2.88, k:2}).evalf() == \ TransferFunctionMatrix(((TransferFunction(4.5230399999999999494093572138808667659759521484375, s, s), TransferFunction(2.87999999999999989341858963598497211933135986328125*s, 2.0*s**2 - 6.282000000000000028421709430404007434844970703125, s)),)) # simplify() H_5 = TransferFunctionMatrix([[TransferFunction(s**5 + s**3 + s, s - s**2, s), TransferFunction((s + 3)*(s - 1), (s - 1)*(s + 5), s)]]) assert H_5.simplify() == simplify(H_5) == \ TransferFunctionMatrix(((TransferFunction(-s**4 - s**2 - 1, s - 1, s), TransferFunction(s + 3, s + 5, s)),)) # expand() assert (H_1.expand() == TransferFunctionMatrix(((TransferFunction(s**3 - 2*s**2 - 3*s, s**4 + 1, s), TransferFunction(2, 1, s)), (TransferFunction(p, 1, s), TransferFunction(p, s, s))))) assert H_5.expand() == \ TransferFunctionMatrix(((TransferFunction(s**5 + s**3 + s, -s**2 + s, s), TransferFunction(s**2 + 2*s - 3, s**2 + 4*s - 5, s)),))
f8b5aea73157241f8254420e09fe00f5d306195cf2ee80bd0d7775800eba5f1f
from sympy import Dummy, arg, I, Abs, log from sympy.abc import s, p, a from sympy.external import import_module from sympy.physics.control.control_plots import \ (pole_zero_numerical_data, pole_zero_plot, step_response_numerical_data, step_response_plot, impulse_response_numerical_data, impulse_response_plot, ramp_response_numerical_data, ramp_response_plot, bode_magnitude_numerical_data, bode_phase_numerical_data, bode_plot) from sympy.physics.control.lti import (TransferFunction, Series, Parallel, TransferFunctionMatrix) from sympy.testing.pytest import raises, skip matplotlib = import_module( 'matplotlib', import_kwargs={'fromlist': ['pyplot']}, catch=(RuntimeError,)) numpy = import_module('numpy') tf1 = TransferFunction(1, p**2 + 0.5*p + 2, p) tf2 = TransferFunction(p, 6*p**2 + 3*p + 1, p) tf3 = TransferFunction(p, p**3 - 1, p) tf4 = TransferFunction(10, p**3, p) tf5 = TransferFunction(5, s**2 + 2*s + 10, s) tf6 = TransferFunction(1, 1, s) tf7 = TransferFunction(4*s*3 + 9*s**2 + 0.1*s + 11, 8*s**6 + 9*s**4 + 11, s) ser1 = Series(tf4, TransferFunction(1, p - 5, p)) ser2 = Series(tf3, TransferFunction(p, p + 2, p)) par1 = Parallel(tf1, tf2) par2 = Parallel(tf1, tf2, tf3) def _to_tuple(a, b): return tuple(a), tuple(b) def _trim_tuple(a, b): a, b = _to_tuple(a, b) return tuple(a[0: 2] + a[len(a)//2 : len(a)//2 + 1] + a[-2:]), \ tuple(b[0: 2] + b[len(b)//2 : len(b)//2 + 1] + b[-2:]) def y_coordinate_equality(plot_data_func, evalf_func, system): """Checks whether the y-coordinate value of the plotted data point is equal to the value of the function at a particular x.""" x, y = plot_data_func(system) x, y = _trim_tuple(x, y) y_exp = tuple(evalf_func(system, x_i) for x_i in x) return all(Abs(y_exp_i - y_i) < 1e-8 for y_exp_i, y_i in zip(y_exp, y)) def test_errors(): if not matplotlib: skip("Matplotlib not the default backend") # Invalid `system` check tfm = TransferFunctionMatrix([[tf6, tf5], [tf5, tf6]]) expr = 1/(s**2 - 1) raises(NotImplementedError, lambda: pole_zero_plot(tfm)) raises(NotImplementedError, lambda: pole_zero_numerical_data(expr)) raises(NotImplementedError, lambda: impulse_response_plot(expr)) raises(NotImplementedError, lambda: impulse_response_numerical_data(tfm)) raises(NotImplementedError, lambda: step_response_plot(tfm)) raises(NotImplementedError, lambda: step_response_numerical_data(expr)) raises(NotImplementedError, lambda: ramp_response_plot(expr)) raises(NotImplementedError, lambda: ramp_response_numerical_data(tfm)) raises(NotImplementedError, lambda: bode_plot(tfm)) # More than 1 variables tf_a = TransferFunction(a, s + 1, s) raises(ValueError, lambda: pole_zero_plot(tf_a)) raises(ValueError, lambda: pole_zero_numerical_data(tf_a)) raises(ValueError, lambda: impulse_response_plot(tf_a)) raises(ValueError, lambda: impulse_response_numerical_data(tf_a)) raises(ValueError, lambda: step_response_plot(tf_a)) raises(ValueError, lambda: step_response_numerical_data(tf_a)) raises(ValueError, lambda: ramp_response_plot(tf_a)) raises(ValueError, lambda: ramp_response_numerical_data(tf_a)) raises(ValueError, lambda: bode_plot(tf_a)) # lower_limit > 0 for response plots raises(ValueError, lambda: impulse_response_plot(tf1, lower_limit=-1)) raises(ValueError, lambda: step_response_plot(tf1, lower_limit=-0.1)) raises(ValueError, lambda: ramp_response_plot(tf1, lower_limit=-4/3)) # slope in ramp_response_plot() is negative raises(ValueError, lambda: ramp_response_plot(tf1, slope=-0.1)) def test_pole_zero(): if not matplotlib: skip("Matplotlib not the default backend") assert _to_tuple(*pole_zero_numerical_data(tf1)) == \ ((), ((-0.24999999999999994+1.3919410907075054j), (-0.24999999999999994-1.3919410907075054j))) assert _to_tuple(*pole_zero_numerical_data(tf2)) == \ ((0.0,), ((-0.25+0.3227486121839514j), (-0.25-0.3227486121839514j))) assert _to_tuple(*pole_zero_numerical_data(tf3)) == \ ((0.0,), ((-0.5000000000000004+0.8660254037844395j), (-0.5000000000000004-0.8660254037844395j), (0.9999999999999998+0j))) assert _to_tuple(*pole_zero_numerical_data(tf7)) == \ (((-0.6722222222222222+0.8776898690157247j), (-0.6722222222222222-0.8776898690157247j)), ((2.220446049250313e-16+1.2797182176061541j), (2.220446049250313e-16-1.2797182176061541j), (-0.7657146670186428+0.5744385024099056j), (-0.7657146670186428-0.5744385024099056j), (0.7657146670186427+0.5744385024099052j), (0.7657146670186427-0.5744385024099052j))) assert _to_tuple(*pole_zero_numerical_data(ser1)) == \ ((), (5.0, 0.0, 0.0, 0.0)) assert _to_tuple(*pole_zero_numerical_data(par1)) == \ ((-5.645751311064592, -0.5000000000000008, -0.3542486889354093), ((-0.24999999999999986+1.3919410907075052j), (-0.24999999999999986-1.3919410907075052j), (-0.2499999999999998+0.32274861218395134j), (-0.2499999999999998-0.32274861218395134j))) def test_bode(): if not matplotlib: skip("Matplotlib not the default backend") def bode_phase_evalf(system, point): expr = system.to_expr() _w = Dummy("w", real=True) w_expr = expr.subs({system.var: I*_w}) return arg(w_expr).subs({_w: point}).evalf() def bode_mag_evalf(system, point): expr = system.to_expr() _w = Dummy("w", real=True) w_expr = expr.subs({system.var: I*_w}) return 20*log(Abs(w_expr), 10).subs({_w: point}).evalf() def test_bode_data(sys): return y_coordinate_equality(bode_magnitude_numerical_data, bode_mag_evalf, sys) \ and y_coordinate_equality(bode_phase_numerical_data, bode_phase_evalf, sys) assert test_bode_data(tf1) assert test_bode_data(tf2) assert test_bode_data(tf3) assert test_bode_data(tf4) assert test_bode_data(tf5) def check_point_accuracy(a, b): return all(Abs(a_i - b_i) < 1e-12 for \ a_i, b_i in zip(a, b)) def test_impulse_response(): if not matplotlib: skip("Matplotlib not the default backend") def impulse_res_tester(sys, expected_value): x, y = _to_tuple(*impulse_response_numerical_data(sys, adaptive=False, nb_of_points=10)) x_check = check_point_accuracy(x, expected_value[0]) y_check = check_point_accuracy(y, expected_value[1]) return x_check and y_check exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 0.544019738507865, 0.01993849743234938, -0.31140243360893216, -0.022852779906491996, 0.1778306498155759, 0.01962941084328499, -0.1013115194573652, -0.014975541213105696, 0.0575789724730714)) exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.1666666675, 0.08389223412935855, 0.02338051973475047, -0.014966807776379383, -0.034645954223054234, -0.040560075735512804, -0.037658628907103885, -0.030149507719590022, -0.021162090730736834, -0.012721292737437523)) exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (4.369893391586999e-09, 1.1750333000630964, 3.2922404058312473, 9.432290008148343, 28.37098083007151, 86.18577464367974, 261.90356653762115, 795.6538758627842, 2416.9920942096983, 7342.159505206647)) exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 6.17283950617284, 24.69135802469136, 55.555555555555564, 98.76543209876544, 154.320987654321, 222.22222222222226, 302.46913580246917, 395.0617283950618, 500.0)) exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, -0.10455606138085417, 0.06757671513476461, -0.03234567568833768, 0.013582514927757873, -0.005273419510705473, 0.0019364083003354075, -0.000680070134067832, 0.00022969845960406913, -7.476094359583917e-05)) exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (-6.016699583000218e-09, 0.35039802056107394, 3.3728423827689884, 12.119846079276684, 25.86101014293389, 29.352480635282088, -30.49475907497664, -273.8717189554019, -863.2381702029659, -1747.0262164682233)) exp7 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 18.934638095560974, 5346.93244680907, 1384609.8718249386, 358161126.65801865, 92645770015.70108, 23964739753087.42, 6198974342083139.0, 1.603492601616059e+18, 4.147764422869658e+20)) assert impulse_res_tester(tf1, exp1) assert impulse_res_tester(tf2, exp2) assert impulse_res_tester(tf3, exp3) assert impulse_res_tester(tf4, exp4) assert impulse_res_tester(tf5, exp5) assert impulse_res_tester(tf7, exp6) assert impulse_res_tester(ser1, exp7) def test_step_response(): if not matplotlib: skip("Matplotlib not the default backend") def step_res_tester(sys, expected_value): x, y = _to_tuple(*step_response_numerical_data(sys, adaptive=False, nb_of_points=10)) x_check = check_point_accuracy(x, expected_value[0]) y_check = check_point_accuracy(y, expected_value[1]) return x_check and y_check exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (-1.9193285738516863e-08, 0.42283495488246126, 0.7840485977945262, 0.5546841805655717, 0.33903033806932087, 0.4627251747410237, 0.5909907598988051, 0.5247213989553071, 0.4486997874319281, 0.4839358435839171)) exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 0.13728409095645816, 0.19474559355325086, 0.1974909129243011, 0.16841657696573073, 0.12559777736159378, 0.08153828016664713, 0.04360471317348958, 0.015072994568868221, -0.003636420058445484)) exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 0.6314542141914303, 2.9356520038101035, 9.37731009663807, 28.452300356688376, 86.25721933273988, 261.9236645044672, 795.6435410577224, 2416.9786984578764, 7342.154119725917)) exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 2.286236899862826, 18.28989519890261, 61.72839629629631, 146.31916159122088, 285.7796124828532, 493.8271703703705, 784.1792566529494, 1170.553292729767, 1666.6667)) exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (-3.999999997894577e-09, 0.6720357068882895, 0.4429938256137113, 0.5182010838004518, 0.4944139147159695, 0.5016379853883338, 0.4995466896527733, 0.5001154784851325, 0.49997448824584123, 0.5000039745919259)) exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (-1.5433688493882158e-09, 0.3428705539937336, 1.1253619102202777, 3.1849962651016517, 9.47532757182671, 28.727231099148135, 87.29426924860557, 265.2138681048606, 805.6636260007757, 2447.387582370878)) assert step_res_tester(tf1, exp1) assert step_res_tester(tf2, exp2) assert step_res_tester(tf3, exp3) assert step_res_tester(tf4, exp4) assert step_res_tester(tf5, exp5) assert step_res_tester(ser2, exp6) def test_ramp_response(): if not matplotlib: skip("Matplotlib not the default backend") def ramp_res_tester(sys, num_points, expected_value, slope=1): x, y = _to_tuple(*ramp_response_numerical_data(sys, slope=slope, adaptive=False, nb_of_points=num_points)) x_check = check_point_accuracy(x, expected_value[0]) y_check = check_point_accuracy(y, expected_value[1]) return x_check and y_check exp1 = ((0.0, 2.0, 4.0, 6.0, 8.0, 10.0), (0.0, 0.7324667795033895, 1.9909720978650398, 2.7956587704217783, 3.9224897567931514, 4.85022655284895)) exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (2.4360213402019326e-08, 0.10175320182493253, 0.33057612497658406, 0.5967937263298935, 0.8431511866718248, 1.0398805391471613, 1.1776043125035738, 1.2600994825747305, 1.2981042689274653, 1.304684417610106)) exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (-3.9329040468771836e-08, 0.34686634635794555, 2.9998828170537903, 12.33303690737476, 40.993913948137795, 127.84145222317912, 391.41713691996, 1192.0006858708389, 3623.9808672503405, 11011.728034546572)) exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 1.9051973784484078, 30.483158055174524, 154.32098765432104, 487.7305288827924, 1190.7483615302544, 2469.1358024691367, 4574.3789056546275, 7803.688462124678, 12500.0)) exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 3.8844361856975635, 9.141792069209865, 14.096349157657231, 19.09783068994694, 24.10179770390321, 29.09907319114121, 34.10040420185154, 39.09983919254265, 44.10006013058409)) exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0)) assert ramp_res_tester(tf1, 6, exp1) assert ramp_res_tester(tf2, 10, exp2, 1.2) assert ramp_res_tester(tf3, 10, exp3, 1.5) assert ramp_res_tester(tf4, 10, exp4, 3) assert ramp_res_tester(tf5, 10, exp5, 9) assert ramp_res_tester(tf6, 10, exp6)
9b7c2e8d1c721eaf3b19f74f083365cbd41a4e03f68cca6aefc6ea23435a4376
from sympy.core.backend import (cos, expand, Matrix, sin, symbols, tan, sqrt, S, zeros) from sympy import simplify from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Point, RigidBody, KanesMethod, inertia, Particle, dot) def test_one_dof(): # This is for a 1 dof spring-mass-damper case. # It is described in more detail in the KanesMethod docstring. q, u = dynamicsymbols('q u') qd, ud = dynamicsymbols('q u', 1) m, c, k = symbols('m c k') N = ReferenceFrame('N') P = Point('P') P.set_vel(N, u * N.x) kd = [qd - u] FL = [(P, (-k * q - c * u) * N.x)] pa = Particle('pa', P, m) BL = [pa] KM = KanesMethod(N, [q], [u], kd) KM.kanes_equations(BL, FL) assert KM.bodies == BL assert KM.loads == FL MM = KM.mass_matrix forcing = KM.forcing rhs = MM.inv() * forcing assert expand(rhs[0]) == expand(-(q * k + u * c) / m) assert simplify(KM.rhs() - KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(2, 1) assert (KM.linearize(A_and_B=True, )[0] == Matrix([[0, 1], [-k/m, -c/m]])) def test_two_dof(): # This is for a 2 d.o.f., 2 particle spring-mass-damper. # The first coordinate is the displacement of the first particle, and the # second is the relative displacement between the first and second # particles. Speeds are defined as the time derivatives of the particles. q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2') q1d, q2d, u1d, u2d = dynamicsymbols('q1 q2 u1 u2', 1) m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2') N = ReferenceFrame('N') P1 = Point('P1') P2 = Point('P2') P1.set_vel(N, u1 * N.x) P2.set_vel(N, (u1 + u2) * N.x) kd = [q1d - u1, q2d - u2] # Now we create the list of forces, then assign properties to each # particle, then create a list of all particles. FL = [(P1, (-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2) * N.x), (P2, (-k2 * q2 - c2 * u2) * N.x)] pa1 = Particle('pa1', P1, m) pa2 = Particle('pa2', P2, m) BL = [pa1, pa2] # Finally we create the KanesMethod object, specify the inertial frame, # pass relevant information, and form Fr & Fr*. Then we calculate the mass # matrix and forcing terms, and finally solve for the udots. KM = KanesMethod(N, q_ind=[q1, q2], u_ind=[u1, u2], kd_eqs=kd) KM.kanes_equations(BL, FL) MM = KM.mass_matrix forcing = KM.forcing rhs = MM.inv() * forcing assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m) assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 * c2 * u2) / m) assert simplify(KM.rhs() - KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(4, 1) def test_pend(): q, u = dynamicsymbols('q u') qd, ud = dynamicsymbols('q u', 1) m, l, g = symbols('m l g') N = ReferenceFrame('N') P = Point('P') P.set_vel(N, -l * u * sin(q) * N.x + l * u * cos(q) * N.y) kd = [qd - u] FL = [(P, m * g * N.x)] pa = Particle('pa', P, m) BL = [pa] KM = KanesMethod(N, [q], [u], kd) KM.kanes_equations(BL, FL) MM = KM.mass_matrix forcing = KM.forcing rhs = MM.inv() * forcing rhs.simplify() assert expand(rhs[0]) == expand(-g / l * sin(q)) assert simplify(KM.rhs() - KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(2, 1) def test_rolling_disc(): # Rolling Disc Example # Here the rolling disc is formed from the contact point up, removing the # need to introduce generalized speeds. Only 3 configuration and three # speed variables are need to describe this system, along with the disc's # mass and radius, and the local gravity (note that mass will drop out). q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1 q2 q3 u1 u2 u3') q1d, q2d, q3d, u1d, u2d, u3d = dynamicsymbols('q1 q2 q3 u1 u2 u3', 1) r, m, g = symbols('r m g') # The kinematics are formed by a series of simple rotations. Each simple # rotation creates a new frame, and the next rotation is defined by the new # frame's basis vectors. This example uses a 3-1-2 series of rotations, or # Z, X, Y series of rotations. Angular velocity for this is defined using # the second frame's basis (the lean frame). N = ReferenceFrame('N') Y = N.orientnew('Y', 'Axis', [q1, N.z]) L = Y.orientnew('L', 'Axis', [q2, Y.x]) R = L.orientnew('R', 'Axis', [q3, L.y]) w_R_N_qd = R.ang_vel_in(N) R.set_ang_vel(N, u1 * L.x + u2 * L.y + u3 * L.z) # This is the translational kinematics. We create a point with no velocity # in N; this is the contact point between the disc and ground. Next we form # the position vector from the contact point to the disc's center of mass. # Finally we form the velocity and acceleration of the disc. C = Point('C') C.set_vel(N, 0) Dmc = C.locatenew('Dmc', r * L.z) Dmc.v2pt_theory(C, N, R) # This is a simple way to form the inertia dyadic. I = inertia(L, m / 4 * r**2, m / 2 * r**2, m / 4 * r**2) # Kinematic differential equations; how the generalized coordinate time # derivatives relate to generalized speeds. kd = [dot(R.ang_vel_in(N) - w_R_N_qd, uv) for uv in L] # Creation of the force list; it is the gravitational force at the mass # center of the disc. Then we create the disc by assigning a Point to the # center of mass attribute, a ReferenceFrame to the frame attribute, and mass # and inertia. Then we form the body list. ForceList = [(Dmc, - m * g * Y.z)] BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc)) BodyList = [BodyD] # Finally we form the equations of motion, using the same steps we did # before. Specify inertial frame, supply generalized speeds, supply # kinematic differential equation dictionary, compute Fr from the force # list and Fr* from the body list, compute the mass matrix and forcing # terms, then solve for the u dots (time derivatives of the generalized # speeds). KM = KanesMethod(N, q_ind=[q1, q2, q3], u_ind=[u1, u2, u3], kd_eqs=kd) KM.kanes_equations(BodyList, ForceList) MM = KM.mass_matrix forcing = KM.forcing rhs = MM.inv() * forcing kdd = KM.kindiffdict() rhs = rhs.subs(kdd) rhs.simplify() assert rhs.expand() == Matrix([(6*u2*u3*r - u3**2*r*tan(q2) + 4*g*sin(q2))/(5*r), -2*u1*u3/3, u1*(-2*u2 + u3*tan(q2))]).expand() assert simplify(KM.rhs() - KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(6, 1) # This code tests our output vs. benchmark values. When r=g=m=1, the # critical speed (where all eigenvalues of the linearized equations are 0) # is 1 / sqrt(3) for the upright case. A = KM.linearize(A_and_B=True)[0] A_upright = A.subs({r: 1, g: 1, m: 1}).subs({q1: 0, q2: 0, q3: 0, u1: 0, u3: 0}) import sympy assert sympy.sympify(A_upright.subs({u2: 1 / sqrt(3)})).eigenvals() == {S.Zero: 6} def test_aux(): # Same as above, except we have 2 auxiliary speeds for the ground contact # point, which is known to be zero. In one case, we go through then # substitute the aux. speeds in at the end (they are zero, as well as their # derivative), in the other case, we use the built-in auxiliary speed part # of KanesMethod. The equations from each should be the same. q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1 q2 q3 u1 u2 u3') q1d, q2d, q3d, u1d, u2d, u3d = dynamicsymbols('q1 q2 q3 u1 u2 u3', 1) u4, u5, f1, f2 = dynamicsymbols('u4, u5, f1, f2') u4d, u5d = dynamicsymbols('u4, u5', 1) r, m, g = symbols('r m g') N = ReferenceFrame('N') Y = N.orientnew('Y', 'Axis', [q1, N.z]) L = Y.orientnew('L', 'Axis', [q2, Y.x]) R = L.orientnew('R', 'Axis', [q3, L.y]) w_R_N_qd = R.ang_vel_in(N) R.set_ang_vel(N, u1 * L.x + u2 * L.y + u3 * L.z) C = Point('C') C.set_vel(N, u4 * L.x + u5 * (Y.z ^ L.x)) Dmc = C.locatenew('Dmc', r * L.z) Dmc.v2pt_theory(C, N, R) Dmc.a2pt_theory(C, N, R) I = inertia(L, m / 4 * r**2, m / 2 * r**2, m / 4 * r**2) kd = [dot(R.ang_vel_in(N) - w_R_N_qd, uv) for uv in L] ForceList = [(Dmc, - m * g * Y.z), (C, f1 * L.x + f2 * (Y.z ^ L.x))] BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc)) BodyList = [BodyD] KM = KanesMethod(N, q_ind=[q1, q2, q3], u_ind=[u1, u2, u3, u4, u5], kd_eqs=kd) (fr, frstar) = KM.kanes_equations(BodyList, ForceList) fr = fr.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0}) frstar = frstar.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0}) KM2 = KanesMethod(N, q_ind=[q1, q2, q3], u_ind=[u1, u2, u3], kd_eqs=kd, u_auxiliary=[u4, u5]) (fr2, frstar2) = KM2.kanes_equations(BodyList, ForceList) fr2 = fr2.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0}) frstar2 = frstar2.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0}) frstar.simplify() frstar2.simplify() assert (fr - fr2).expand() == Matrix([0, 0, 0, 0, 0]) assert (frstar - frstar2).expand() == Matrix([0, 0, 0, 0, 0]) def test_parallel_axis(): # This is for a 2 dof inverted pendulum on a cart. # This tests the parallel axis code in KanesMethod. The inertia of the # pendulum is defined about the hinge, not about the center of mass. # Defining the constants and knowns of the system gravity = symbols('g') k, ls = symbols('k ls') a, mA, mC = symbols('a mA mC') F = dynamicsymbols('F') Ix, Iy, Iz = symbols('Ix Iy Iz') # Declaring the Generalized coordinates and speeds q1, q2 = dynamicsymbols('q1 q2') q1d, q2d = dynamicsymbols('q1 q2', 1) u1, u2 = dynamicsymbols('u1 u2') u1d, u2d = dynamicsymbols('u1 u2', 1) # Creating reference frames N = ReferenceFrame('N') A = ReferenceFrame('A') A.orient(N, 'Axis', [-q2, N.z]) A.set_ang_vel(N, -u2 * N.z) # Origin of Newtonian reference frame O = Point('O') # Creating and Locating the positions of the cart, C, and the # center of mass of the pendulum, A C = O.locatenew('C', q1 * N.x) Ao = C.locatenew('Ao', a * A.y) # Defining velocities of the points O.set_vel(N, 0) C.set_vel(N, u1 * N.x) Ao.v2pt_theory(C, N, A) Cart = Particle('Cart', C, mC) Pendulum = RigidBody('Pendulum', Ao, A, mA, (inertia(A, Ix, Iy, Iz), C)) # kinematical differential equations kindiffs = [q1d - u1, q2d - u2] bodyList = [Cart, Pendulum] forceList = [(Ao, -N.y * gravity * mA), (C, -N.y * gravity * mC), (C, -N.x * k * (q1 - ls)), (C, N.x * F)] km = KanesMethod(N, [q1, q2], [u1, u2], kindiffs) (fr, frstar) = km.kanes_equations(bodyList, forceList) mm = km.mass_matrix_full assert mm[3, 3] == Iz def test_input_format(): # 1 dof problem from test_one_dof q, u = dynamicsymbols('q u') qd, ud = dynamicsymbols('q u', 1) m, c, k = symbols('m c k') N = ReferenceFrame('N') P = Point('P') P.set_vel(N, u * N.x) kd = [qd - u] FL = [(P, (-k * q - c * u) * N.x)] pa = Particle('pa', P, m) BL = [pa] KM = KanesMethod(N, [q], [u], kd) # test for input format kane.kanes_equations((body1, body2, particle1)) assert KM.kanes_equations(BL)[0] == Matrix([0]) # test for input format kane.kanes_equations(bodies=(body1, body 2), loads=(load1,load2)) assert KM.kanes_equations(bodies=BL, loads=None)[0] == Matrix([0]) # test for input format kane.kanes_equations(bodies=(body1, body 2), loads=None) assert KM.kanes_equations(BL, loads=None)[0] == Matrix([0]) # test for input format kane.kanes_equations(bodies=(body1, body 2)) assert KM.kanes_equations(BL)[0] == Matrix([0]) # test for input format kane.kanes_equations(bodies=(body1, body2), loads=[]) assert KM.kanes_equations(BL, [])[0] == Matrix([0]) # test for error raised when a wrong force list (in this case a string) is provided from sympy.testing.pytest import raises raises(ValueError, lambda: KM._form_fr('bad input')) # 1 dof problem from test_one_dof with FL & BL in instance KM = KanesMethod(N, [q], [u], kd, bodies=BL, forcelist=FL) assert KM.kanes_equations()[0] == Matrix([-c*u - k*q]) # 2 dof problem from test_two_dof q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2') q1d, q2d, u1d, u2d = dynamicsymbols('q1 q2 u1 u2', 1) m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2') N = ReferenceFrame('N') P1 = Point('P1') P2 = Point('P2') P1.set_vel(N, u1 * N.x) P2.set_vel(N, (u1 + u2) * N.x) kd = [q1d - u1, q2d - u2] FL = ((P1, (-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2) * N.x), (P2, (-k2 * q2 - c2 * u2) * N.x)) pa1 = Particle('pa1', P1, m) pa2 = Particle('pa2', P2, m) BL = (pa1, pa2) KM = KanesMethod(N, q_ind=[q1, q2], u_ind=[u1, u2], kd_eqs=kd) # test for input format # kane.kanes_equations((body1, body2), (load1, load2)) KM.kanes_equations(BL, FL) MM = KM.mass_matrix forcing = KM.forcing rhs = MM.inv() * forcing assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m) assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 * c2 * u2) / m)
3db6d98705d689c0a252d1e96f989945652d415645f4fa970511bd550ca0da09
from sympy import symbols, Matrix, cos, sin, expand, trigsimp from sympy.physics.mechanics import (PinJoint, JointsMethod, Body, KanesMethod, PrismaticJoint, LagrangesMethod, inertia) from sympy.physics.vector import dynamicsymbols, ReferenceFrame from sympy.testing.pytest import raises t = dynamicsymbols._t def test_jointsmethod(): P = Body('P') C = Body('C') Pin = PinJoint('P1', P, C) C_ixx, g = symbols('C_ixx g') theta, omega = dynamicsymbols('theta_P1, omega_P1') P.apply_force(g*P.y) method = JointsMethod(P, Pin) assert method.frame == P.frame assert method.bodies == [C, P] assert method.loads == [(P.masscenter, g*P.frame.y)] assert method.q == [theta] assert method.u == [omega] assert method.kdes == [omega - theta.diff()] soln = method.form_eoms() assert soln == Matrix([[-C_ixx*omega.diff()]]) assert method.forcing_full == Matrix([[omega], [0]]) assert method.mass_matrix_full == Matrix([[1, 0], [0, C_ixx]]) assert isinstance(method.method, KanesMethod) def test_jointmethod_duplicate_coordinates_speeds(): P = Body('P') C = Body('C') T = Body('T') q, u = dynamicsymbols('q u') P1 = PinJoint('P1', P, C, q) P2 = PrismaticJoint('P2', C, T, q) raises(ValueError, lambda: JointsMethod(P, P1, P2)) P1 = PinJoint('P1', P, C, speeds=u) P2 = PrismaticJoint('P2', C, T, speeds=u) raises(ValueError, lambda: JointsMethod(P, P1, P2)) P1 = PinJoint('P1', P, C, q, u) P2 = PrismaticJoint('P2', C, T, q, u) raises(ValueError, lambda: JointsMethod(P, P1, P2)) def test_complete_simple_double_pendulum(): q1, q2 = dynamicsymbols('q1 q2') u1, u2 = dynamicsymbols('u1 u2') m, l, g = symbols('m l g') C = Body('C') # ceiling PartP = Body('P', mass=m) PartR = Body('R', mass=m) J1 = PinJoint('J1', C, PartP, speeds=u1, coordinates=q1, child_joint_pos=-l*PartP.x, parent_axis=C.z, child_axis=PartP.z) J2 = PinJoint('J2', PartP, PartR, speeds=u2, coordinates=q2, child_joint_pos=-l*PartR.x, parent_axis=PartP.z, child_axis=PartR.z) PartP.apply_force(m*g*C.x) PartR.apply_force(m*g*C.x) method = JointsMethod(C, J1, J2) method.form_eoms() assert expand(method.mass_matrix_full) == Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2*l**2*m*cos(q2) + 3*l**2*m, l**2*m*cos(q2) + l**2*m], [0, 0, l**2*m*cos(q2) + l**2*m, l**2*m]]) assert trigsimp(method.forcing_full) == trigsimp(Matrix([[u1], [u2], [-g*l*m*(sin(q1 + q2) + sin(q1)) - g*l*m*sin(q1) + l**2*m*(2*u1 + u2)*u2*sin(q2)], [-g*l*m*sin(q1 + q2) - l**2*m*u1**2*sin(q2)]])) def test_two_dof_joints(): q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2') m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2') W = Body('W') B1 = Body('B1', mass=m) B2 = Body('B2', mass=m) J1 = PrismaticJoint('J1', W, B1, coordinates=q1, speeds=u1) J2 = PrismaticJoint('J2', B1, B2, coordinates=q2, speeds=u2) W.apply_force(k1*q1*W.x, reaction_body=B1) W.apply_force(c1*u1*W.x, reaction_body=B1) B1.apply_force(k2*q2*W.x, reaction_body=B2) B1.apply_force(c2*u2*W.x, reaction_body=B2) method = JointsMethod(W, J1, J2) method.form_eoms() MM = method.mass_matrix forcing = method.forcing rhs = MM.LUsolve(forcing) assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m) assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 * c2 * u2) / m) def test_simple_pedulum(): l, m, g = symbols('l m g') C = Body('C') b = Body('b', mass=m) q = dynamicsymbols('q') P = PinJoint('P', C, b, speeds=q.diff(t), coordinates=q, child_joint_pos = -l*b.x, parent_axis=C.z, child_axis=b.z) b.potential_energy = - m * g * l * cos(q) method = JointsMethod(C, P) method.form_eoms(LagrangesMethod) rhs = method.rhs() assert rhs[1] == -g*sin(q)/l def test_chaos_pendulum(): #https://www.pydy.org/examples/chaos_pendulum.html mA, mB, lA, lB, IAxx, IBxx, IByy, IBzz, g = symbols('mA, mB, lA, lB, IAxx, IBxx, IByy, IBzz, g') theta, phi, omega, alpha = dynamicsymbols('theta phi omega alpha') A = ReferenceFrame('A') B = ReferenceFrame('B') rod = Body('rod', mass=mA, frame=A, central_inertia=inertia(A, IAxx, IAxx, 0)) plate = Body('plate', mass=mB, frame=B, central_inertia=inertia(B, IBxx, IByy, IBzz)) C = Body('C') J1 = PinJoint('J1', C, rod, coordinates=theta, speeds=omega, child_joint_pos=-lA*rod.z, parent_axis=C.y, child_axis=rod.y) J2 = PinJoint('J2', rod, plate, coordinates=phi, speeds=alpha, parent_joint_pos=(lB-lA)*rod.z, parent_axis=rod.z, child_axis=plate.z) rod.apply_force(mA*g*C.z) plate.apply_force(mB*g*C.z) method = JointsMethod(C, J1, J2) method.form_eoms() MM = method.mass_matrix forcing = method.forcing rhs = MM.LUsolve(forcing) xd = (-2 * IBxx * alpha * omega * sin(phi) * cos(phi) + 2 * IByy * alpha * omega * sin(phi) * cos(phi) - g * lA * mA * sin(theta) - g * lB * mB * sin(theta)) / (IAxx + IBxx * sin(phi)**2 + IByy * cos(phi)**2 + lA**2 * mA + lB**2 * mB) assert (rhs[0] - xd).simplify() == 0 xd = (IBxx - IByy) * omega**2 * sin(phi) * cos(phi) / IBzz assert (rhs[1] - xd).simplify() == 0
aef7db49d1fcf8b45f4596b34f712c0b97983bc5c6395662bbd2a5e8b3b3cb41
from sympy.core.backend import Symbol, symbols, sin, cos, Matrix from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols from sympy.physics.mechanics import inertia, Body from sympy.testing.pytest import raises def test_default(): body = Body('body') assert body.name == 'body' assert body.loads == [] point = Point('body_masscenter') point.set_vel(body.frame, 0) com = body.masscenter frame = body.frame assert com.vel(frame) == point.vel(frame) assert body.mass == Symbol('body_mass') ixx, iyy, izz = symbols('body_ixx body_iyy body_izz') ixy, iyz, izx = symbols('body_ixy body_iyz body_izx') assert body.inertia == (inertia(body.frame, ixx, iyy, izz, ixy, iyz, izx), body.masscenter) def test_custom_rigid_body(): # Body with RigidBody. rigidbody_masscenter = Point('rigidbody_masscenter') rigidbody_mass = Symbol('rigidbody_mass') rigidbody_frame = ReferenceFrame('rigidbody_frame') body_inertia = inertia(rigidbody_frame, 1, 0, 0) rigid_body = Body('rigidbody_body', rigidbody_masscenter, rigidbody_mass, rigidbody_frame, body_inertia) com = rigid_body.masscenter frame = rigid_body.frame rigidbody_masscenter.set_vel(rigidbody_frame, 0) assert com.vel(frame) == rigidbody_masscenter.vel(frame) assert com.pos_from(com) == rigidbody_masscenter.pos_from(com) assert rigid_body.mass == rigidbody_mass assert rigid_body.inertia == (body_inertia, rigidbody_masscenter) assert rigid_body.is_rigidbody assert hasattr(rigid_body, 'masscenter') assert hasattr(rigid_body, 'mass') assert hasattr(rigid_body, 'frame') assert hasattr(rigid_body, 'inertia') def test_particle_body(): # Body with Particle particle_masscenter = Point('particle_masscenter') particle_mass = Symbol('particle_mass') particle_frame = ReferenceFrame('particle_frame') particle_body = Body('particle_body', particle_masscenter, particle_mass, particle_frame) com = particle_body.masscenter frame = particle_body.frame particle_masscenter.set_vel(particle_frame, 0) assert com.vel(frame) == particle_masscenter.vel(frame) assert com.pos_from(com) == particle_masscenter.pos_from(com) assert particle_body.mass == particle_mass assert not hasattr(particle_body, "_inertia") assert hasattr(particle_body, 'frame') assert hasattr(particle_body, 'masscenter') assert hasattr(particle_body, 'mass') assert not particle_body.is_rigidbody def test_particle_body_add_force(): # Body with Particle particle_masscenter = Point('particle_masscenter') particle_mass = Symbol('particle_mass') particle_frame = ReferenceFrame('particle_frame') particle_body = Body('particle_body', particle_masscenter, particle_mass, particle_frame) a = Symbol('a') force_vector = a * particle_body.frame.x particle_body.apply_force(force_vector, particle_body.masscenter) assert len(particle_body.loads) == 1 point = particle_body.masscenter.locatenew( particle_body._name + '_point0', 0) point.set_vel(particle_body.frame, 0) force_point = particle_body.loads[0][0] frame = particle_body.frame assert force_point.vel(frame) == point.vel(frame) assert force_point.pos_from(force_point) == point.pos_from(force_point) assert particle_body.loads[0][1] == force_vector def test_body_add_force(): # Body with RigidBody. rigidbody_masscenter = Point('rigidbody_masscenter') rigidbody_mass = Symbol('rigidbody_mass') rigidbody_frame = ReferenceFrame('rigidbody_frame') body_inertia = inertia(rigidbody_frame, 1, 0, 0) rigid_body = Body('rigidbody_body', rigidbody_masscenter, rigidbody_mass, rigidbody_frame, body_inertia) l = Symbol('l') Fa = Symbol('Fa') point = rigid_body.masscenter.locatenew( 'rigidbody_body_point0', l * rigid_body.frame.x) point.set_vel(rigid_body.frame, 0) force_vector = Fa * rigid_body.frame.z # apply_force with point rigid_body.apply_force(force_vector, point) assert len(rigid_body.loads) == 1 force_point = rigid_body.loads[0][0] frame = rigid_body.frame assert force_point.vel(frame) == point.vel(frame) assert force_point.pos_from(force_point) == point.pos_from(force_point) assert rigid_body.loads[0][1] == force_vector # apply_force without point rigid_body.apply_force(force_vector) assert len(rigid_body.loads) == 2 assert rigid_body.loads[1][1] == force_vector # passing something else than point raises(TypeError, lambda: rigid_body.apply_force(force_vector, 0)) raises(TypeError, lambda: rigid_body.apply_force(0)) def test_body_add_torque(): body = Body('body') torque_vector = body.frame.x body.apply_torque(torque_vector) assert len(body.loads) == 1 assert body.loads[0] == (body.frame, torque_vector) raises(TypeError, lambda: body.apply_torque(0)) def test_body_masscenter_vel(): A = Body('A') N = ReferenceFrame('N') B = Body('B', frame=N) A.masscenter.set_vel(N, N.z) assert A.masscenter_vel(B) == N.z assert A.masscenter_vel(N) == N.z def test_body_ang_vel(): A = Body('A') N = ReferenceFrame('N') B = Body('B', frame=N) A.frame.set_ang_vel(N, N.y) assert A.ang_vel_in(B) == N.y assert B.ang_vel_in(A) == -N.y assert A.ang_vel_in(N) == N.y def test_body_dcm(): A = Body('A') B = Body('B') A.frame.orient_axis(B.frame, B.frame.z, 10) assert A.dcm(B) == Matrix([[cos(10), sin(10), 0], [-sin(10), cos(10), 0], [0, 0, 1]]) assert A.dcm(B.frame) == Matrix([[cos(10), sin(10), 0], [-sin(10), cos(10), 0], [0, 0, 1]]) def test_body_axis(): N = ReferenceFrame('N') B = Body('B', frame=N) assert B.x == N.x assert B.y == N.y assert B.z == N.z def test_apply_force_multiple_one_point(): a, b = symbols('a b') P = Point('P') B = Body('B') f1 = a*B.x f2 = b*B.y B.apply_force(f1, P) assert B.loads == [(P, f1)] B.apply_force(f2, P) assert B.loads == [(P, f1+f2)] def test_apply_force(): f, g = symbols('f g') q, x, v1, v2 = dynamicsymbols('q x v1 v2') P1 = Point('P1') P2 = Point('P2') B1 = Body('B1') B2 = Body('B2') N = ReferenceFrame('N') P1.set_vel(B1.frame, v1*B1.x) P2.set_vel(B2.frame, v2*B2.x) force = f*q*N.z # time varying force B1.apply_force(force, P1, B2, P2) #applying equal and opposite force on moving points assert B1.loads == [(P1, force)] assert B2.loads == [(P2, -force)] g1 = B1.mass*g*N.y g2 = B2.mass*g*N.y B1.apply_force(g1) #applying gravity on B1 masscenter B2.apply_force(g2) #applying gravity on B2 masscenter assert B1.loads == [(P1,force), (B1.masscenter, g1)] assert B2.loads == [(P2, -force), (B2.masscenter, g2)] force2 = x*N.x B1.apply_force(force2, reaction_body=B2) #Applying time varying force on masscenter assert B1.loads == [(P1, force), (B1.masscenter, force2+g1)] assert B2.loads == [(P2, -force), (B2.masscenter, -force2+g2)] def test_apply_torque(): t = symbols('t') q = dynamicsymbols('q') B1 = Body('B1') B2 = Body('B2') N = ReferenceFrame('N') torque = t*q*N.x B1.apply_torque(torque, B2) #Applying equal and opposite torque assert B1.loads == [(B1.frame, torque)] assert B2.loads == [(B2.frame, -torque)] torque2 = t*N.y B1.apply_torque(torque2) assert B1.loads == [(B1.frame, torque+torque2)] def test_clear_load(): a = symbols('a') P = Point('P') B = Body('B') force = a*B.z B.apply_force(force, P) assert B.loads == [(P, force)] B.clear_loads() assert B.loads == [] def test_remove_load(): P1 = Point('P1') P2 = Point('P2') B = Body('B') f1 = B.x f2 = B.y B.apply_force(f1, P1) B.apply_force(f2, P2) B.loads == [(P1, f1), (P2, f2)] B.remove_load(P2) B.loads == [(P1, f1)] B.apply_torque(f1.cross(f2)) B.loads == [(P1, f1), (B.frame, f1.cross(f2))] B.remove_load() B.loads == [(P1, f1)] def test_apply_loads_on_multi_degree_freedom_holonomic_system(): """Example based on: https://pydy.readthedocs.io/en/latest/examples/multidof-holonomic.html""" W = Body('W') #Wall B = Body('B') #Block P = Body('P') #Pendulum b = Body('b') #bob q1, q2 = dynamicsymbols('q1 q2') #generalized coordinates k, c, g, kT = symbols('k c g kT') #constants F, T = dynamicsymbols('F T') #Specified forces #Applying forces B.apply_force(F*W.x) W.apply_force(k*q1*W.x, reaction_body=B) #Spring force W.apply_force(c*q1.diff()*W.x, reaction_body=B) #dampner P.apply_force(P.mass*g*W.y) b.apply_force(b.mass*g*W.y) #Applying torques P.apply_torque(kT*q2*W.z, reaction_body=b) P.apply_torque(T*W.z) assert B.loads == [(B.masscenter, (F - k*q1 - c*q1.diff())*W.x)] assert P.loads == [(P.masscenter, P.mass*g*W.y), (P.frame, (T + kT*q2)*W.z)] assert b.loads == [(b.masscenter, b.mass*g*W.y), (b.frame, -kT*q2*W.z)] assert W.loads == [(W.masscenter, (c*q1.diff() + k*q1)*W.x)]
281bcfc8f891954e9924928bbf578a430966ab6ad1fc3516e2be0fb9f16bad44
from sympy import Basic from sympy import S from sympy.core.expr import Expr from sympy.core.numbers import Integer from sympy.core.sympify import sympify from sympy.core.kind import Kind, NumberKind, UndefinedKind from sympy.core.compatibility import SYMPY_INTS from sympy.printing.defaults import Printable import itertools from collections.abc import Iterable class ArrayKind(Kind): """ Kind for N-dimensional array in SymPy. This kind represents the multidimensional array that algebraic operations are defined. Basic class for this kind is ``NDimArray``, but any expression representing the array can have this. Parameters ========== element_kind : Kind Kind of the element. Default is :obj:NumberKind `<sympy.core.kind.NumberKind>`, which means that the array contains only numbers. Examples ======== Any instance of array class has ``ArrayKind``. >>> from sympy import NDimArray >>> NDimArray([1,2,3]).kind ArrayKind(NumberKind) Although expressions representing an array may be not instance of array class, it will have ``ArrayKind`` as well. >>> from sympy import Integral >>> from sympy.tensor.array import NDimArray >>> from sympy.abc import x >>> intA = Integral(NDimArray([1,2,3]), x) >>> isinstance(intA, NDimArray) False >>> intA.kind ArrayKind(NumberKind) Use ``isinstance()`` to check for ``ArrayKind` without specifying the element kind. Use ``is`` with specifying the element kind. >>> from sympy.tensor.array import ArrayKind >>> from sympy.core.kind import NumberKind >>> boolA = NDimArray([True, False]) >>> isinstance(boolA.kind, ArrayKind) True >>> boolA.kind is ArrayKind(NumberKind) False See Also ======== shape : Function to return the shape of objects with ``MatrixKind``. """ def __new__(cls, element_kind=NumberKind): obj = super().__new__(cls, element_kind) obj.element_kind = element_kind return obj def __repr__(self): return "ArrayKind(%s)" % self.element_kind class NDimArray(Printable): """ Examples ======== Create an N-dim array of zeros: >>> from sympy import MutableDenseNDimArray >>> a = MutableDenseNDimArray.zeros(2, 3, 4) >>> a [[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]] Create an N-dim array from a list; >>> a = MutableDenseNDimArray([[2, 3], [4, 5]]) >>> a [[2, 3], [4, 5]] >>> b = MutableDenseNDimArray([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]]) >>> b [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]] Create an N-dim array from a flat list with dimension shape: >>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3)) >>> a [[1, 2, 3], [4, 5, 6]] Create an N-dim array from a matrix: >>> from sympy import Matrix >>> a = Matrix([[1,2],[3,4]]) >>> a Matrix([ [1, 2], [3, 4]]) >>> b = MutableDenseNDimArray(a) >>> b [[1, 2], [3, 4]] Arithmetic operations on N-dim arrays >>> a = MutableDenseNDimArray([1, 1, 1, 1], (2, 2)) >>> b = MutableDenseNDimArray([4, 4, 4, 4], (2, 2)) >>> c = a + b >>> c [[5, 5], [5, 5]] >>> a - b [[-3, -3], [-3, -3]] """ _diff_wrt = True is_scalar = False def __new__(cls, iterable, shape=None, **kwargs): from sympy.tensor.array import ImmutableDenseNDimArray return ImmutableDenseNDimArray(iterable, shape, **kwargs) @property def kind(self): elem_kinds = set(e.kind for e in self._array) if len(elem_kinds) == 1: elemkind, = elem_kinds else: elemkind = UndefinedKind return ArrayKind(elemkind) def _parse_index(self, index): if isinstance(index, (SYMPY_INTS, Integer)): raise ValueError("Only a tuple index is accepted") if self._loop_size == 0: raise ValueError("Index not valide with an empty array") if len(index) != self._rank: raise ValueError('Wrong number of array axes') real_index = 0 # check if input index can exist in current indexing for i in range(self._rank): if (index[i] >= self.shape[i]) or (index[i] < -self.shape[i]): raise ValueError('Index ' + str(index) + ' out of border') if index[i] < 0: real_index += 1 real_index = real_index*self.shape[i] + index[i] return real_index def _get_tuple_index(self, integer_index): index = [] for i, sh in enumerate(reversed(self.shape)): index.append(integer_index % sh) integer_index //= sh index.reverse() return tuple(index) def _check_symbolic_index(self, index): # Check if any index is symbolic: tuple_index = (index if isinstance(index, tuple) else (index,)) if any([(isinstance(i, Expr) and (not i.is_number)) for i in tuple_index]): for i, nth_dim in zip(tuple_index, self.shape): if ((i < 0) == True) or ((i >= nth_dim) == True): raise ValueError("index out of range") from sympy.tensor import Indexed return Indexed(self, *tuple_index) return None def _setter_iterable_check(self, value): from sympy.matrices.matrices import MatrixBase if isinstance(value, (Iterable, MatrixBase, NDimArray)): raise NotImplementedError @classmethod def _scan_iterable_shape(cls, iterable): def f(pointer): if not isinstance(pointer, Iterable): return [pointer], () result = [] elems, shapes = zip(*[f(i) for i in pointer]) if len(set(shapes)) != 1: raise ValueError("could not determine shape unambiguously") for i in elems: result.extend(i) return result, (len(shapes),)+shapes[0] return f(iterable) @classmethod def _handle_ndarray_creation_inputs(cls, iterable=None, shape=None, **kwargs): from sympy.matrices.matrices import MatrixBase from sympy.tensor.array import SparseNDimArray from sympy import Dict, Tuple if shape is None: if iterable is None: shape = () iterable = () # Construction of a sparse array from a sparse array elif isinstance(iterable, SparseNDimArray): return iterable._shape, iterable._sparse_array # Construct N-dim array from another N-dim array: elif isinstance(iterable, NDimArray): shape = iterable.shape # Construct N-dim array from an iterable (numpy arrays included): elif isinstance(iterable, Iterable): iterable, shape = cls._scan_iterable_shape(iterable) # Construct N-dim array from a Matrix: elif isinstance(iterable, MatrixBase): shape = iterable.shape else: shape = () iterable = (iterable,) if isinstance(iterable, (Dict, dict)) and shape is not None: new_dict = iterable.copy() for k, v in new_dict.items(): if isinstance(k, (tuple, Tuple)): new_key = 0 for i, idx in enumerate(k): new_key = new_key * shape[i] + idx iterable[new_key] = iterable[k] del iterable[k] if isinstance(shape, (SYMPY_INTS, Integer)): shape = (shape,) if any([not isinstance(dim, (SYMPY_INTS, Integer)) for dim in shape]): raise TypeError("Shape should contain integers only.") return tuple(shape), iterable def __len__(self): """Overload common function len(). Returns number of elements in array. Examples ======== >>> from sympy import MutableDenseNDimArray >>> a = MutableDenseNDimArray.zeros(3, 3) >>> a [[0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> len(a) 9 """ return self._loop_size @property def shape(self): """ Returns array shape (dimension). Examples ======== >>> from sympy import MutableDenseNDimArray >>> a = MutableDenseNDimArray.zeros(3, 3) >>> a.shape (3, 3) """ return self._shape def rank(self): """ Returns rank of array. Examples ======== >>> from sympy import MutableDenseNDimArray >>> a = MutableDenseNDimArray.zeros(3,4,5,6,3) >>> a.rank() 5 """ return self._rank def diff(self, *args, **kwargs): """ Calculate the derivative of each element in the array. Examples ======== >>> from sympy import ImmutableDenseNDimArray >>> from sympy.abc import x, y >>> M = ImmutableDenseNDimArray([[x, y], [1, x*y]]) >>> M.diff(x) [[1, 0], [0, y]] """ from sympy.tensor.array.array_derivatives import ArrayDerivative kwargs.setdefault('evaluate', True) return ArrayDerivative(self.as_immutable(), *args, **kwargs) def _eval_derivative(self, base): # Types are (base: scalar, self: array) return self.applyfunc(lambda x: base.diff(x)) def _eval_derivative_n_times(self, s, n): return Basic._eval_derivative_n_times(self, s, n) def applyfunc(self, f): """Apply a function to each element of the N-dim array. Examples ======== >>> from sympy import ImmutableDenseNDimArray >>> m = ImmutableDenseNDimArray([i*2+j for i in range(2) for j in range(2)], (2, 2)) >>> m [[0, 1], [2, 3]] >>> m.applyfunc(lambda i: 2*i) [[0, 2], [4, 6]] """ from sympy.tensor.array import SparseNDimArray from sympy.tensor.array.arrayop import Flatten if isinstance(self, SparseNDimArray) and f(S.Zero) == 0: return type(self)({k: f(v) for k, v in self._sparse_array.items() if f(v) != 0}, self.shape) return type(self)(map(f, Flatten(self)), self.shape) def _sympystr(self, printer): def f(sh, shape_left, i, j): if len(shape_left) == 1: return "["+", ".join([printer._print(self[self._get_tuple_index(e)]) for e in range(i, j)])+"]" sh //= shape_left[0] return "[" + ", ".join([f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh) for e in range(shape_left[0])]) + "]" # + "\n"*len(shape_left) if self.rank() == 0: return printer._print(self[()]) return f(self._loop_size, self.shape, 0, self._loop_size) def tolist(self): """ Converting MutableDenseNDimArray to one-dim list Examples ======== >>> from sympy import MutableDenseNDimArray >>> a = MutableDenseNDimArray([1, 2, 3, 4], (2, 2)) >>> a [[1, 2], [3, 4]] >>> b = a.tolist() >>> b [[1, 2], [3, 4]] """ def f(sh, shape_left, i, j): if len(shape_left) == 1: return [self[self._get_tuple_index(e)] for e in range(i, j)] result = [] sh //= shape_left[0] for e in range(shape_left[0]): result.append(f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh)) return result return f(self._loop_size, self.shape, 0, self._loop_size) def __add__(self, other): from sympy.tensor.array.arrayop import Flatten if not isinstance(other, NDimArray): return NotImplemented if self.shape != other.shape: raise ValueError("array shape mismatch") result_list = [i+j for i,j in zip(Flatten(self), Flatten(other))] return type(self)(result_list, self.shape) def __sub__(self, other): from sympy.tensor.array.arrayop import Flatten if not isinstance(other, NDimArray): return NotImplemented if self.shape != other.shape: raise ValueError("array shape mismatch") result_list = [i-j for i,j in zip(Flatten(self), Flatten(other))] return type(self)(result_list, self.shape) def __mul__(self, other): from sympy.matrices.matrices import MatrixBase from sympy.tensor.array import SparseNDimArray from sympy.tensor.array.arrayop import Flatten if isinstance(other, (Iterable, NDimArray, MatrixBase)): raise ValueError("scalar expected, use tensorproduct(...) for tensorial product") other = sympify(other) if isinstance(self, SparseNDimArray): if other.is_zero: return type(self)({}, self.shape) return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape) result_list = [i*other for i in Flatten(self)] return type(self)(result_list, self.shape) def __rmul__(self, other): from sympy.matrices.matrices import MatrixBase from sympy.tensor.array import SparseNDimArray from sympy.tensor.array.arrayop import Flatten if isinstance(other, (Iterable, NDimArray, MatrixBase)): raise ValueError("scalar expected, use tensorproduct(...) for tensorial product") other = sympify(other) if isinstance(self, SparseNDimArray): if other.is_zero: return type(self)({}, self.shape) return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape) result_list = [other*i for i in Flatten(self)] return type(self)(result_list, self.shape) def __truediv__(self, other): from sympy.matrices.matrices import MatrixBase from sympy.tensor.array import SparseNDimArray from sympy.tensor.array.arrayop import Flatten if isinstance(other, (Iterable, NDimArray, MatrixBase)): raise ValueError("scalar expected") other = sympify(other) if isinstance(self, SparseNDimArray) and other != S.Zero: return type(self)({k: v/other for (k, v) in self._sparse_array.items()}, self.shape) result_list = [i/other for i in Flatten(self)] return type(self)(result_list, self.shape) def __rtruediv__(self, other): raise NotImplementedError('unsupported operation on NDimArray') def __neg__(self): from sympy.tensor.array import SparseNDimArray from sympy.tensor.array.arrayop import Flatten if isinstance(self, SparseNDimArray): return type(self)({k: -v for (k, v) in self._sparse_array.items()}, self.shape) result_list = [-i for i in Flatten(self)] return type(self)(result_list, self.shape) def __iter__(self): def iterator(): if self._shape: for i in range(self._shape[0]): yield self[i] else: yield self[()] return iterator() def __eq__(self, other): """ NDimArray instances can be compared to each other. Instances equal if they have same shape and data. Examples ======== >>> from sympy import MutableDenseNDimArray >>> a = MutableDenseNDimArray.zeros(2, 3) >>> b = MutableDenseNDimArray.zeros(2, 3) >>> a == b True >>> c = a.reshape(3, 2) >>> c == b False >>> a[0,0] = 1 >>> b[0,0] = 2 >>> a == b False """ from sympy.tensor.array import SparseNDimArray if not isinstance(other, NDimArray): return False if not self.shape == other.shape: return False if isinstance(self, SparseNDimArray) and isinstance(other, SparseNDimArray): return dict(self._sparse_array) == dict(other._sparse_array) return list(self) == list(other) def __ne__(self, other): return not self == other def _eval_transpose(self): if self.rank() != 2: raise ValueError("array rank not 2") from .arrayop import permutedims return permutedims(self, (1, 0)) def transpose(self): return self._eval_transpose() def _eval_conjugate(self): from sympy.tensor.array.arrayop import Flatten return self.func([i.conjugate() for i in Flatten(self)], self.shape) def conjugate(self): return self._eval_conjugate() def _eval_adjoint(self): return self.transpose().conjugate() def adjoint(self): return self._eval_adjoint() def _slice_expand(self, s, dim): if not isinstance(s, slice): return (s,) start, stop, step = s.indices(dim) return [start + i*step for i in range((stop-start)//step)] def _get_slice_data_for_array_access(self, index): sl_factors = [self._slice_expand(i, dim) for (i, dim) in zip(index, self.shape)] eindices = itertools.product(*sl_factors) return sl_factors, eindices def _get_slice_data_for_array_assignment(self, index, value): if not isinstance(value, NDimArray): value = type(self)(value) sl_factors, eindices = self._get_slice_data_for_array_access(index) slice_offsets = [min(i) if isinstance(i, list) else None for i in sl_factors] # TODO: add checks for dimensions for `value`? return value, eindices, slice_offsets @classmethod def _check_special_bounds(cls, flat_list, shape): if shape == () and len(flat_list) != 1: raise ValueError("arrays without shape need one scalar value") if shape == (0,) and len(flat_list) > 0: raise ValueError("if array shape is (0,) there cannot be elements") def _check_index_for_getitem(self, index): if isinstance(index, (SYMPY_INTS, Integer, slice)): index = (index, ) if len(index) < self.rank(): index = tuple([i for i in index] + \ [slice(None) for i in range(len(index), self.rank())]) if len(index) > self.rank(): raise ValueError('Dimension of index greater than rank of array') return index class ImmutableNDimArray(NDimArray, Basic): _op_priority = 11.0 def __hash__(self): return Basic.__hash__(self) def as_immutable(self): return self def as_mutable(self): raise NotImplementedError("abstract method")
8bf68f2e5d441e91c91844cb11ab5d1d5caa2d392337d77e93ed37f535324c57
from copy import copy from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray from sympy import Symbol, Rational, SparseMatrix, Dict, diff, symbols, Indexed, IndexedBase, S from sympy.matrices import Matrix from sympy.tensor.array.sparse_ndim_array import ImmutableSparseNDimArray from sympy.testing.pytest import raises def test_ndim_array_initiation(): arr_with_no_elements = ImmutableDenseNDimArray([], shape=(0,)) assert len(arr_with_no_elements) == 0 assert arr_with_no_elements.rank() == 1 raises(ValueError, lambda: ImmutableDenseNDimArray([0], shape=(0,))) raises(ValueError, lambda: ImmutableDenseNDimArray([1, 2, 3], shape=(0,))) raises(ValueError, lambda: ImmutableDenseNDimArray([], shape=())) raises(ValueError, lambda: ImmutableSparseNDimArray([0], shape=(0,))) raises(ValueError, lambda: ImmutableSparseNDimArray([1, 2, 3], shape=(0,))) raises(ValueError, lambda: ImmutableSparseNDimArray([], shape=())) arr_with_one_element = ImmutableDenseNDimArray([23]) assert len(arr_with_one_element) == 1 assert arr_with_one_element[0] == 23 assert arr_with_one_element[:] == ImmutableDenseNDimArray([23]) assert arr_with_one_element.rank() == 1 arr_with_symbol_element = ImmutableDenseNDimArray([Symbol('x')]) assert len(arr_with_symbol_element) == 1 assert arr_with_symbol_element[0] == Symbol('x') assert arr_with_symbol_element[:] == ImmutableDenseNDimArray([Symbol('x')]) assert arr_with_symbol_element.rank() == 1 number5 = 5 vector = ImmutableDenseNDimArray.zeros(number5) assert len(vector) == number5 assert vector.shape == (number5,) assert vector.rank() == 1 vector = ImmutableSparseNDimArray.zeros(number5) assert len(vector) == number5 assert vector.shape == (number5,) assert vector._sparse_array == Dict() assert vector.rank() == 1 n_dim_array = ImmutableDenseNDimArray(range(3**4), (3, 3, 3, 3,)) assert len(n_dim_array) == 3 * 3 * 3 * 3 assert n_dim_array.shape == (3, 3, 3, 3) assert n_dim_array.rank() == 4 array_shape = (3, 3, 3, 3) sparse_array = ImmutableSparseNDimArray.zeros(*array_shape) assert len(sparse_array._sparse_array) == 0 assert len(sparse_array) == 3 * 3 * 3 * 3 assert n_dim_array.shape == array_shape assert n_dim_array.rank() == 4 one_dim_array = ImmutableDenseNDimArray([2, 3, 1]) assert len(one_dim_array) == 3 assert one_dim_array.shape == (3,) assert one_dim_array.rank() == 1 assert one_dim_array.tolist() == [2, 3, 1] shape = (3, 3) array_with_many_args = ImmutableSparseNDimArray.zeros(*shape) assert len(array_with_many_args) == 3 * 3 assert array_with_many_args.shape == shape assert array_with_many_args[0, 0] == 0 assert array_with_many_args.rank() == 2 shape = (int(3), int(3)) array_with_long_shape = ImmutableSparseNDimArray.zeros(*shape) assert len(array_with_long_shape) == 3 * 3 assert array_with_long_shape.shape == shape assert array_with_long_shape[int(0), int(0)] == 0 assert array_with_long_shape.rank() == 2 vector_with_long_shape = ImmutableDenseNDimArray(range(5), int(5)) assert len(vector_with_long_shape) == 5 assert vector_with_long_shape.shape == (int(5),) assert vector_with_long_shape.rank() == 1 raises(ValueError, lambda: vector_with_long_shape[int(5)]) from sympy.abc import x for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]: rank_zero_array = ArrayType(x) assert len(rank_zero_array) == 1 assert rank_zero_array.shape == () assert rank_zero_array.rank() == 0 assert rank_zero_array[()] == x raises(ValueError, lambda: rank_zero_array[0]) def test_reshape(): array = ImmutableDenseNDimArray(range(50), 50) assert array.shape == (50,) assert array.rank() == 1 array = array.reshape(5, 5, 2) assert array.shape == (5, 5, 2) assert array.rank() == 3 assert len(array) == 50 def test_getitem(): for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]: array = ArrayType(range(24)).reshape(2, 3, 4) assert array.tolist() == [[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]] assert array[0] == ArrayType([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]) assert array[0, 0] == ArrayType([0, 1, 2, 3]) value = 0 for i in range(2): for j in range(3): for k in range(4): assert array[i, j, k] == value value += 1 raises(ValueError, lambda: array[3, 4, 5]) raises(ValueError, lambda: array[3, 4, 5, 6]) raises(ValueError, lambda: array[3, 4, 5, 3:4]) def test_iterator(): array = ImmutableDenseNDimArray(range(4), (2, 2)) array[0] == ImmutableDenseNDimArray([0, 1]) array[1] == ImmutableDenseNDimArray([2, 3]) array = array.reshape(4) j = 0 for i in array: assert i == j j += 1 def test_sparse(): sparse_array = ImmutableSparseNDimArray([0, 0, 0, 1], (2, 2)) assert len(sparse_array) == 2 * 2 # dictionary where all data is, only non-zero entries are actually stored: assert len(sparse_array._sparse_array) == 1 assert sparse_array.tolist() == [[0, 0], [0, 1]] for i, j in zip(sparse_array, [[0, 0], [0, 1]]): assert i == ImmutableSparseNDimArray(j) def sparse_assignment(): sparse_array[0, 0] = 123 assert len(sparse_array._sparse_array) == 1 raises(TypeError, sparse_assignment) assert len(sparse_array._sparse_array) == 1 assert sparse_array[0, 0] == 0 assert sparse_array/0 == ImmutableSparseNDimArray([[S.NaN, S.NaN], [S.NaN, S.ComplexInfinity]], (2, 2)) # test for large scale sparse array # equality test assert ImmutableSparseNDimArray.zeros(100000, 200000) == ImmutableSparseNDimArray.zeros(100000, 200000) # __mul__ and __rmul__ a = ImmutableSparseNDimArray({200001: 1}, (100000, 200000)) assert a * 3 == ImmutableSparseNDimArray({200001: 3}, (100000, 200000)) assert 3 * a == ImmutableSparseNDimArray({200001: 3}, (100000, 200000)) assert a * 0 == ImmutableSparseNDimArray({}, (100000, 200000)) assert 0 * a == ImmutableSparseNDimArray({}, (100000, 200000)) # __truediv__ assert a/3 == ImmutableSparseNDimArray({200001: Rational(1, 3)}, (100000, 200000)) # __neg__ assert -a == ImmutableSparseNDimArray({200001: -1}, (100000, 200000)) def test_calculation(): a = ImmutableDenseNDimArray([1]*9, (3, 3)) b = ImmutableDenseNDimArray([9]*9, (3, 3)) c = a + b for i in c: assert i == ImmutableDenseNDimArray([10, 10, 10]) assert c == ImmutableDenseNDimArray([10]*9, (3, 3)) assert c == ImmutableSparseNDimArray([10]*9, (3, 3)) c = b - a for i in c: assert i == ImmutableDenseNDimArray([8, 8, 8]) assert c == ImmutableDenseNDimArray([8]*9, (3, 3)) assert c == ImmutableSparseNDimArray([8]*9, (3, 3)) def test_ndim_array_converting(): dense_array = ImmutableDenseNDimArray([1, 2, 3, 4], (2, 2)) alist = dense_array.tolist() alist == [[1, 2], [3, 4]] matrix = dense_array.tomatrix() assert (isinstance(matrix, Matrix)) for i in range(len(dense_array)): assert dense_array[dense_array._get_tuple_index(i)] == matrix[i] assert matrix.shape == dense_array.shape assert ImmutableDenseNDimArray(matrix) == dense_array assert ImmutableDenseNDimArray(matrix.as_immutable()) == dense_array assert ImmutableDenseNDimArray(matrix.as_mutable()) == dense_array sparse_array = ImmutableSparseNDimArray([1, 2, 3, 4], (2, 2)) alist = sparse_array.tolist() assert alist == [[1, 2], [3, 4]] matrix = sparse_array.tomatrix() assert(isinstance(matrix, SparseMatrix)) for i in range(len(sparse_array)): assert sparse_array[sparse_array._get_tuple_index(i)] == matrix[i] assert matrix.shape == sparse_array.shape assert ImmutableSparseNDimArray(matrix) == sparse_array assert ImmutableSparseNDimArray(matrix.as_immutable()) == sparse_array assert ImmutableSparseNDimArray(matrix.as_mutable()) == sparse_array def test_converting_functions(): arr_list = [1, 2, 3, 4] arr_matrix = Matrix(((1, 2), (3, 4))) # list arr_ndim_array = ImmutableDenseNDimArray(arr_list, (2, 2)) assert (isinstance(arr_ndim_array, ImmutableDenseNDimArray)) assert arr_matrix.tolist() == arr_ndim_array.tolist() # Matrix arr_ndim_array = ImmutableDenseNDimArray(arr_matrix) assert (isinstance(arr_ndim_array, ImmutableDenseNDimArray)) assert arr_matrix.tolist() == arr_ndim_array.tolist() assert arr_matrix.shape == arr_ndim_array.shape def test_equality(): first_list = [1, 2, 3, 4] second_list = [1, 2, 3, 4] third_list = [4, 3, 2, 1] assert first_list == second_list assert first_list != third_list first_ndim_array = ImmutableDenseNDimArray(first_list, (2, 2)) second_ndim_array = ImmutableDenseNDimArray(second_list, (2, 2)) fourth_ndim_array = ImmutableDenseNDimArray(first_list, (2, 2)) assert first_ndim_array == second_ndim_array def assignment_attempt(a): a[0, 0] = 0 raises(TypeError, lambda: assignment_attempt(second_ndim_array)) assert first_ndim_array == second_ndim_array assert first_ndim_array == fourth_ndim_array def test_arithmetic(): a = ImmutableDenseNDimArray([3 for i in range(9)], (3, 3)) b = ImmutableDenseNDimArray([7 for i in range(9)], (3, 3)) c1 = a + b c2 = b + a assert c1 == c2 d1 = a - b d2 = b - a assert d1 == d2 * (-1) e1 = a * 5 e2 = 5 * a e3 = copy(a) e3 *= 5 assert e1 == e2 == e3 f1 = a / 5 f2 = copy(a) f2 /= 5 assert f1 == f2 assert f1[0, 0] == f1[0, 1] == f1[0, 2] == f1[1, 0] == f1[1, 1] == \ f1[1, 2] == f1[2, 0] == f1[2, 1] == f1[2, 2] == Rational(3, 5) assert type(a) == type(b) == type(c1) == type(c2) == type(d1) == type(d2) \ == type(e1) == type(e2) == type(e3) == type(f1) z0 = -a assert z0 == ImmutableDenseNDimArray([-3 for i in range(9)], (3, 3)) def test_higher_dimenions(): m3 = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4)) assert m3.tolist() == [[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]] assert m3._get_tuple_index(0) == (0, 0, 0) assert m3._get_tuple_index(1) == (0, 0, 1) assert m3._get_tuple_index(4) == (0, 1, 0) assert m3._get_tuple_index(12) == (1, 0, 0) assert str(m3) == '[[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]]' m3_rebuilt = ImmutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]]) assert m3 == m3_rebuilt m3_other = ImmutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]], (2, 3, 4)) assert m3 == m3_other def test_rebuild_immutable_arrays(): sparr = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4)) densarr = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4)) assert sparr == sparr.func(*sparr.args) assert densarr == densarr.func(*densarr.args) def test_slices(): md = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4)) assert md[:] == ImmutableDenseNDimArray(range(10, 34), (2, 3, 4)) assert md[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]]) assert md[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]]) assert md[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]]) assert md[:, :, :] == md sd = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4)) assert sd == ImmutableSparseNDimArray(md) assert sd[:] == ImmutableSparseNDimArray(range(10, 34), (2, 3, 4)) assert sd[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]]) assert sd[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]]) assert sd[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]]) assert sd[:, :, :] == sd def test_diff_and_applyfunc(): from sympy.abc import x, y, z md = ImmutableDenseNDimArray([[x, y], [x*z, x*y*z]]) assert md.diff(x) == ImmutableDenseNDimArray([[1, 0], [z, y*z]]) assert diff(md, x) == ImmutableDenseNDimArray([[1, 0], [z, y*z]]) sd = ImmutableSparseNDimArray(md) assert sd == ImmutableSparseNDimArray([x, y, x*z, x*y*z], (2, 2)) assert sd.diff(x) == ImmutableSparseNDimArray([[1, 0], [z, y*z]]) assert diff(sd, x) == ImmutableSparseNDimArray([[1, 0], [z, y*z]]) mdn = md.applyfunc(lambda x: x*3) assert mdn == ImmutableDenseNDimArray([[3*x, 3*y], [3*x*z, 3*x*y*z]]) assert md != mdn sdn = sd.applyfunc(lambda x: x/2) assert sdn == ImmutableSparseNDimArray([[x/2, y/2], [x*z/2, x*y*z/2]]) assert sd != sdn sdp = sd.applyfunc(lambda x: x+1) assert sdp == ImmutableSparseNDimArray([[x + 1, y + 1], [x*z + 1, x*y*z + 1]]) assert sd != sdp def test_op_priority(): from sympy.abc import x md = ImmutableDenseNDimArray([1, 2, 3]) e1 = (1+x)*md e2 = md*(1+x) assert e1 == ImmutableDenseNDimArray([1+x, 2+2*x, 3+3*x]) assert e1 == e2 sd = ImmutableSparseNDimArray([1, 2, 3]) e3 = (1+x)*sd e4 = sd*(1+x) assert e3 == ImmutableDenseNDimArray([1+x, 2+2*x, 3+3*x]) assert e3 == e4 def test_symbolic_indexing(): x, y, z, w = symbols("x y z w") M = ImmutableDenseNDimArray([[x, y], [z, w]]) i, j = symbols("i, j") Mij = M[i, j] assert isinstance(Mij, Indexed) Ms = ImmutableSparseNDimArray([[2, 3*x], [4, 5]]) msij = Ms[i, j] assert isinstance(msij, Indexed) for oi, oj in [(0, 0), (0, 1), (1, 0), (1, 1)]: assert Mij.subs({i: oi, j: oj}) == M[oi, oj] assert msij.subs({i: oi, j: oj}) == Ms[oi, oj] A = IndexedBase("A", (0, 2)) assert A[0, 0].subs(A, M) == x assert A[i, j].subs(A, M) == M[i, j] assert M[i, j].subs(M, A) == A[i, j] assert isinstance(M[3 * i - 2, j], Indexed) assert M[3 * i - 2, j].subs({i: 1, j: 0}) == M[1, 0] assert isinstance(M[i, 0], Indexed) assert M[i, 0].subs(i, 0) == M[0, 0] assert M[0, i].subs(i, 1) == M[0, 1] assert M[i, j].diff(x) == ImmutableDenseNDimArray([[1, 0], [0, 0]])[i, j] assert Ms[i, j].diff(x) == ImmutableSparseNDimArray([[0, 3], [0, 0]])[i, j] Mo = ImmutableDenseNDimArray([1, 2, 3]) assert Mo[i].subs(i, 1) == 2 Mos = ImmutableSparseNDimArray([1, 2, 3]) assert Mos[i].subs(i, 1) == 2 raises(ValueError, lambda: M[i, 2]) raises(ValueError, lambda: M[i, -1]) raises(ValueError, lambda: M[2, i]) raises(ValueError, lambda: M[-1, i]) raises(ValueError, lambda: Ms[i, 2]) raises(ValueError, lambda: Ms[i, -1]) raises(ValueError, lambda: Ms[2, i]) raises(ValueError, lambda: Ms[-1, i]) def test_issue_12665(): # Testing Python 3 hash of immutable arrays: arr = ImmutableDenseNDimArray([1, 2, 3]) # This should NOT raise an exception: hash(arr) def test_zeros_without_shape(): arr = ImmutableDenseNDimArray.zeros() assert arr == ImmutableDenseNDimArray(0) def test_issue_21870(): a0 = ImmutableDenseNDimArray(0) assert a0.rank() == 0 a1 = ImmutableDenseNDimArray(a0) assert a1.rank() == 0
001bb9879f8a3ffc6ed50188629133900381ef70482eaea9c811678ce9210fa7
import itertools from typing import Tuple, Optional, List from functools import singledispatch from itertools import accumulate from sympy import Trace, MatrixExpr, Transpose, DiagMatrix, Mul, ZeroMatrix from sympy.combinatorics.permutations import _af_invert, Permutation from sympy.matrices.common import MatrixCommon from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction from sympy.tensor.array.expressions.array_expressions import PermuteDims, ArrayDiagonal, \ ArrayTensorProduct, OneArray, get_rank, _get_subrank, ZeroArray, ArrayContraction, \ ArrayAdd, _CodegenArrayAbstract, get_shape, ArrayElementwiseApplyFunc, _ArrayExpr, _EditArrayContraction, _ArgE from sympy.tensor.array.expressions.utils import _get_mapping_from_subranks def _get_candidate_for_matmul_from_contraction(scan_indices: List[Optional[int]], remaining_args: List[_ArgE]) -> Tuple[Optional[_ArgE], bool, int]: scan_indices = [i for i in scan_indices if i is not None] if len(scan_indices) == 0: return None, False, -1 transpose: bool = False candidate: Optional[_ArgE] = None candidate_index: int = -1 for arg_with_ind2 in remaining_args: if not isinstance(arg_with_ind2.element, MatrixExpr): continue for index in scan_indices: if candidate_index != -1 and candidate_index != index: # A candidate index has already been selected, check # repetitions only for that index: continue if index in arg_with_ind2.indices: if set(arg_with_ind2.indices) == {index}: # Index repeated twice in arg_with_ind2 candidate = None break if candidate is None: candidate = arg_with_ind2 candidate_index = index transpose = (index == arg_with_ind2.indices[1]) else: # Index repeated more than twice, break candidate = None break return candidate, transpose, candidate_index def _insert_candidate_into_editor(editor: _EditArrayContraction, arg_with_ind: _ArgE, candidate: _ArgE, transpose1: bool, transpose2: bool): other = candidate.element other_index: int if transpose2: other = Transpose(other) other_index = candidate.indices[0] else: other_index = candidate.indices[1] new_element = (Transpose(arg_with_ind.element) if transpose1 else arg_with_ind.element) * other editor.args_with_ind.remove(candidate) new_arge = _ArgE(new_element) return new_arge, other_index def _support_function_tp1_recognize(contraction_indices, args): if len(contraction_indices) == 0: return _a2m_tensor_product(*args) ac = ArrayContraction(ArrayTensorProduct(*args), *contraction_indices) editor = _EditArrayContraction(ac) editor.track_permutation_start() while True: flag_stop: bool = True for i, arg_with_ind in enumerate(editor.args_with_ind): if not isinstance(arg_with_ind.element, MatrixExpr): continue first_index = arg_with_ind.indices[0] second_index = arg_with_ind.indices[1] first_frequency = editor.count_args_with_index(first_index) second_frequency = editor.count_args_with_index(second_index) if first_index is not None and first_frequency == 1 and first_index == second_index: flag_stop = False arg_with_ind.element = Trace(arg_with_ind.element)._normalize() arg_with_ind.indices = [] break scan_indices = [] if first_frequency == 2: scan_indices.append(first_index) if second_frequency == 2: scan_indices.append(second_index) candidate, transpose, found_index = _get_candidate_for_matmul_from_contraction(scan_indices, editor.args_with_ind[i+1:]) if candidate is not None: flag_stop = False editor.track_permutation_merge(arg_with_ind, candidate) transpose1 = found_index == first_index new_arge, other_index = _insert_candidate_into_editor(editor, arg_with_ind, candidate, transpose1, transpose) if found_index == first_index: new_arge.indices = [second_index, other_index] else: new_arge.indices = [first_index, other_index] set_indices = set(new_arge.indices) if len(set_indices) == 1 and set_indices != {None}: # This is a trace: new_arge.element = Trace(new_arge.element)._normalize() new_arge.indices = [] editor.args_with_ind[i] = new_arge # TODO: is this break necessary? break if flag_stop: break editor.refresh_indices() return editor.to_array_contraction() @singledispatch def _array2matrix(expr): return expr @_array2matrix.register(ZeroArray) def _(expr: ZeroArray): if get_rank(expr) == 2: return ZeroMatrix(*expr.shape) else: return expr @_array2matrix.register(ArrayTensorProduct) def _(expr: ArrayTensorProduct): return _a2m_tensor_product(*[_array2matrix(arg) for arg in expr.args]) @_array2matrix.register(ArrayContraction) def _(expr: ArrayContraction): expr = expr.flatten_contraction_of_diagonal() expr = expr.split_multiple_contractions() subexpr = expr.expr contraction_indices: Tuple[Tuple[int]] = expr.contraction_indices if isinstance(subexpr, ArrayTensorProduct): newexpr = ArrayContraction(_array2matrix(subexpr), *contraction_indices) contraction_indices = newexpr.contraction_indices if any(i > 2 for i in newexpr.subranks): addends = ArrayAdd(*[_a2m_tensor_product(*j) for j in itertools.product(*[i.args if isinstance(i, ArrayAdd) else [i] for i in expr.expr.args])]) newexpr = ArrayContraction(addends, *contraction_indices) if isinstance(newexpr, ArrayAdd): ret = _array2matrix(newexpr) return ret assert isinstance(newexpr, ArrayContraction) ret = _support_function_tp1_recognize(contraction_indices, list(newexpr.expr.args)) return ret elif not isinstance(subexpr, _CodegenArrayAbstract): ret = _array2matrix(subexpr) if isinstance(ret, MatrixExpr): assert expr.contraction_indices == ((0, 1),) return _a2m_trace(ret) else: return ArrayContraction(ret, *expr.contraction_indices) @_array2matrix.register(ArrayDiagonal) def _(expr: ArrayDiagonal): expr2 = _array2matrix(expr.expr) pexpr = _array_diag2contr_diagmatrix(ArrayDiagonal(expr2, *expr.diagonal_indices)) if expr == pexpr: return expr return _array2matrix(pexpr) @_array2matrix.register(PermuteDims) def _(expr: PermuteDims): if expr.permutation.array_form == [1, 0]: return _a2m_transpose(_array2matrix(expr.expr)) elif isinstance(expr.expr, ArrayTensorProduct): ranks = expr.expr.subranks inv_permutation = expr.permutation**(-1) newrange = [inv_permutation(i) for i in range(sum(ranks))] newpos = [] counter = 0 for rank in ranks: newpos.append(newrange[counter:counter+rank]) counter += rank newargs = [] newperm = [] scalars = [] for pos, arg in zip(newpos, expr.expr.args): if len(pos) == 0: scalars.append(_array2matrix(arg)) elif pos == sorted(pos): newargs.append((_array2matrix(arg), pos[0])) newperm.extend(pos) elif len(pos) == 2: newargs.append((_a2m_transpose(_array2matrix(arg)), pos[0])) newperm.extend(reversed(pos)) else: raise NotImplementedError() newargs = [i[0] for i in newargs] return PermuteDims(_a2m_tensor_product(*scalars, *newargs), _af_invert(newperm)) elif isinstance(expr.expr, ArrayContraction): mat_mul_lines = _array2matrix(expr.expr) if not isinstance(mat_mul_lines, ArrayTensorProduct): flat_cyclic_form = [j for i in expr.permutation.cyclic_form for j in i] expr_shape = get_shape(expr) if all(expr_shape[i] == 1 for i in flat_cyclic_form): return mat_mul_lines return mat_mul_lines # TODO: this assumes that all arguments are matrices, it may not be the case: permutation = Permutation(2*len(mat_mul_lines.args)-1)*expr.permutation permuted = [permutation(i) for i in range(2*len(mat_mul_lines.args))] args_array = [None for i in mat_mul_lines.args] for i in range(len(mat_mul_lines.args)): p1 = permuted[2*i] p2 = permuted[2*i+1] if p1 // 2 != p2 // 2: return PermuteDims(mat_mul_lines, permutation) pos = p1 // 2 if p1 > p2: args_array[i] = _a2m_transpose(mat_mul_lines.args[pos]) else: args_array[i] = mat_mul_lines.args[pos] return _a2m_tensor_product(*args_array) else: raise NotImplementedError() @_array2matrix.register(ArrayAdd) def _(expr: ArrayAdd): addends = [_array2matrix(arg) for arg in expr.args] return _a2m_add(*addends) @_array2matrix.register(ArrayElementwiseApplyFunc) def _(expr: ArrayElementwiseApplyFunc): subexpr = _array2matrix(expr.expr) if isinstance(subexpr, MatrixExpr): return ElementwiseApplyFunction(expr.function, subexpr) else: return ArrayElementwiseApplyFunc(expr.function, subexpr) @singledispatch def _remove_trivial_dims(expr): return expr, [] @_remove_trivial_dims.register(ArrayTensorProduct) def _(expr: ArrayTensorProduct): # Recognize expressions like [x, y] with shape (k, 1, k, 1) as `x*y.T`. # The matrix expression has to be equivalent to the tensor product of the # matrices, with trivial dimensions (i.e. dim=1) dropped. # That is, add contractions over trivial dimensions: removed = [] newargs = [] cumul = list(accumulate([0] + [get_rank(arg) for arg in expr.args])) pending = None prev_i = None for i, arg in enumerate(expr.args): current_range = list(range(cumul[i], cumul[i+1])) if isinstance(arg, OneArray): removed.extend(current_range) continue if not isinstance(arg, (MatrixExpr, MatrixCommon)): rarg, rem = _remove_trivial_dims(arg) removed.extend(rem) newargs.append(rarg) continue elif getattr(arg, "is_Identity", False): if arg.shape == (1, 1): # Ignore identity matrices of shape (1, 1) - they are equivalent to scalar 1. removed.extend(current_range) continue k = arg.shape[0] if pending == k: # OK, there is already removed.extend(current_range) continue elif pending is None: newargs.append(arg) pending = k prev_i = i else: pending = k prev_i = i newargs.append(arg) elif arg.shape == (1, 1): arg, _ = _remove_trivial_dims(arg) # Matrix is equivalent to scalar: if len(newargs) == 0: newargs.append(arg) elif 1 in get_shape(newargs[-1]): if newargs[-1].shape[1] == 1: newargs[-1] = newargs[-1]*arg else: newargs[-1] = arg*newargs[-1] removed.extend(current_range) else: newargs.append(arg) elif 1 in arg.shape: k = [i for i in arg.shape if i != 1][0] if pending is None: pending = k prev_i = i newargs.append(arg) elif pending == k: prev = newargs[-1] if prev.is_Identity: removed.extend([cumul[prev_i], cumul[prev_i]+1]) newargs[-1] = arg prev_i = i continue if prev.shape[0] == 1: d1 = cumul[prev_i] prev = _a2m_transpose(prev) else: d1 = cumul[prev_i] + 1 if arg.shape[1] == 1: d2 = cumul[i] + 1 arg = _a2m_transpose(arg) else: d2 = cumul[i] newargs[-1] = prev*arg pending = None removed.extend([d1, d2]) else: newargs.append(arg) pending = k prev_i = i else: newargs.append(arg) pending = None return _a2m_tensor_product(*newargs), sorted(removed) @_remove_trivial_dims.register(ArrayAdd) def _(expr: ArrayAdd): rec = [_remove_trivial_dims(arg) for arg in expr.args] newargs, removed = zip(*rec) if len(set(map(tuple, removed))) != 1: return expr, [] return _a2m_add(*newargs), removed[0] @_remove_trivial_dims.register(PermuteDims) def _(expr: PermuteDims): subexpr, subremoved = _remove_trivial_dims(expr.expr) p = expr.permutation.array_form pinv = _af_invert(expr.permutation.array_form) shift = list(accumulate([1 if i in subremoved else 0 for i in range(len(p))])) premoved = [pinv[i] for i in subremoved] p2 = [e - shift[e] for i, e in enumerate(p) if e not in subremoved] # TODO: check if subremoved should be permuted as well... newexpr = PermuteDims(subexpr, p2) if newexpr != expr: newexpr = _array2matrix(newexpr) return newexpr, sorted(premoved) @_remove_trivial_dims.register(ArrayContraction) def _(expr: ArrayContraction): newexpr, removed = _remove_trivial_dims(expr.expr) shifts = list(accumulate([1 if i in removed else 0 for i in range(get_rank(expr.expr))])) new_contraction_indices = [tuple(j for j in i if j not in removed) for i in expr.contraction_indices] # Remove possible empty tuples "()": new_contraction_indices = [i for i in new_contraction_indices if len(i) > 0] contraction_indices_flat = [j for i in expr.contraction_indices for j in i] removed = [i for i in removed if i not in contraction_indices_flat] new_contraction_indices = [tuple(j - shifts[j] for j in i) for i in new_contraction_indices] # Shift removed: removed = ArrayContraction._push_indices_up(expr.contraction_indices, removed) return ArrayContraction(newexpr, *new_contraction_indices), list(removed) @_remove_trivial_dims.register(ArrayDiagonal) def _(expr: ArrayDiagonal): newexpr, removed = _remove_trivial_dims(expr.expr) shifts = list(accumulate([0] + [1 if i in removed else 0 for i in range(get_rank(expr.expr))])) new_diag_indices = [tuple(j for j in i if j not in removed) for i in expr.diagonal_indices] new_diag_indices = [tuple(j - shifts[j] for j in i) for i in new_diag_indices] rank = get_rank(expr.expr) removed = ArrayDiagonal._push_indices_up(expr.diagonal_indices, removed, rank) removed = sorted({i for i in removed}) # If there are single axes to diagonalize remaining, it means that their # corresponding dimension has been removed, they no longer need diagonalization: new_diag_indices = [i for i in new_diag_indices if len(i) > 1] return ArrayDiagonal(newexpr, *new_diag_indices), removed @_remove_trivial_dims.register(ElementwiseApplyFunction) def _(expr: ElementwiseApplyFunction): subexpr, removed = _remove_trivial_dims(expr.expr) if subexpr.shape == (1, 1): # TODO: move this to ElementwiseApplyFunction return expr.function(subexpr), removed + [0, 1] return ElementwiseApplyFunction(expr.function, subexpr) @_remove_trivial_dims.register(ArrayElementwiseApplyFunc) def _(expr: ArrayElementwiseApplyFunc): subexpr, removed = _remove_trivial_dims(expr.expr) return ArrayElementwiseApplyFunc(expr.function, subexpr), removed def convert_array_to_matrix(expr): r""" Recognize matrix expressions in codegen objects. If more than one matrix multiplication line have been detected, return a list with the matrix expressions. Examples ======== >>> from sympy.tensor.array.expressions.conv_indexed_to_array import convert_indexed_to_array >>> from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct >>> from sympy import MatrixSymbol, Sum >>> from sympy.abc import i, j, k, l, N >>> from sympy.tensor.array.expressions.array_expressions import ArrayContraction >>> from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array >>> from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix >>> A = MatrixSymbol("A", N, N) >>> B = MatrixSymbol("B", N, N) >>> C = MatrixSymbol("C", N, N) >>> D = MatrixSymbol("D", N, N) >>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1)) >>> cg = convert_indexed_to_array(expr) >>> convert_array_to_matrix(cg) A*B >>> cg = convert_indexed_to_array(expr, first_indices=[k]) >>> convert_array_to_matrix(cg) B.T*A.T Transposition is detected: >>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1)) >>> cg = convert_indexed_to_array(expr) >>> convert_array_to_matrix(cg) A.T*B >>> cg = convert_indexed_to_array(expr, first_indices=[k]) >>> convert_array_to_matrix(cg) B.T*A Detect the trace: >>> expr = Sum(A[i, i], (i, 0, N-1)) >>> cg = convert_indexed_to_array(expr) >>> convert_array_to_matrix(cg) Trace(A) Recognize some more complex traces: >>> expr = Sum(A[i, j]*B[j, i], (i, 0, N-1), (j, 0, N-1)) >>> cg = convert_indexed_to_array(expr) >>> convert_array_to_matrix(cg) Trace(A*B) More complicated expressions: >>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1)) >>> cg = convert_indexed_to_array(expr) >>> convert_array_to_matrix(cg) A*B.T*A.T Expressions constructed from matrix expressions do not contain literal indices, the positions of free indices are returned instead: >>> expr = A*B >>> cg = convert_matrix_to_array(expr) >>> convert_array_to_matrix(cg) A*B If more than one line of matrix multiplications is detected, return separate matrix multiplication factors embedded in a tensor product object: >>> cg = ArrayContraction(ArrayTensorProduct(A, B, C, D), (1, 2), (5, 6)) >>> convert_array_to_matrix(cg) ArrayTensorProduct(A*B, C*D) The two lines have free indices at axes 0, 3 and 4, 7, respectively. """ rec = _array2matrix(expr) rec, removed = _remove_trivial_dims(rec) return rec def _array_diag2contr_diagmatrix(expr: ArrayDiagonal): if isinstance(expr.expr, ArrayTensorProduct): args = list(expr.expr.args) diag_indices = list(expr.diagonal_indices) mapping = _get_mapping_from_subranks([_get_subrank(arg) for arg in args]) tuple_links = [[mapping[j] for j in i] for i in diag_indices] contr_indices = [] total_rank = get_rank(expr) replaced = [False for arg in args] for i, (abs_pos, rel_pos) in enumerate(zip(diag_indices, tuple_links)): if len(abs_pos) != 2: continue (pos1_outer, pos1_inner), (pos2_outer, pos2_inner) = rel_pos arg1 = args[pos1_outer] arg2 = args[pos2_outer] if get_rank(arg1) != 2 or get_rank(arg2) != 2: if replaced[pos1_outer]: diag_indices[i] = None if replaced[pos2_outer]: diag_indices[i] = None continue pos1_in2 = 1 - pos1_inner pos2_in2 = 1 - pos2_inner if arg1.shape[pos1_in2] == 1: darg1 = DiagMatrix(arg1) args.append(darg1) contr_indices.append(((pos2_outer, pos2_inner), (len(args)-1, pos1_inner))) total_rank += 1 diag_indices[i] = None args[pos1_outer] = OneArray(arg1.shape[pos1_in2]) replaced[pos1_outer] = True elif arg2.shape[pos2_in2] == 1: darg2 = DiagMatrix(arg2) args.append(darg2) contr_indices.append(((pos1_outer, pos1_inner), (len(args)-1, pos2_inner))) total_rank += 1 diag_indices[i] = None args[pos2_outer] = OneArray(arg2.shape[pos2_in2]) replaced[pos2_outer] = True diag_indices_new = [i for i in diag_indices if i is not None] cumul = list(accumulate([0] + [get_rank(arg) for arg in args])) contr_indices2 = [tuple(cumul[a] + b for a, b in i) for i in contr_indices] tc = ArrayContraction( ArrayTensorProduct(*args), *contr_indices2 ) td = ArrayDiagonal(tc, *diag_indices_new) return td return expr def _a2m_mul(*args): if all(not isinstance(i, _CodegenArrayAbstract) for i in args): from sympy import MatMul return MatMul(*args).doit() else: return ArrayContraction( ArrayTensorProduct(*args), *[(2*i-1, 2*i) for i in range(1, len(args))] ) def _a2m_tensor_product(*args): scalars = [] arrays = [] for arg in args: if isinstance(arg, (MatrixExpr, _ArrayExpr, _CodegenArrayAbstract)): arrays.append(arg) else: scalars.append(arg) scalar = Mul.fromiter(scalars) if len(arrays) == 0: return scalar if scalar != 1: if isinstance(arrays[0], _CodegenArrayAbstract): arrays = [scalar] + arrays else: arrays[0] *= scalar return ArrayTensorProduct(*arrays) def _a2m_add(*args): if all(not isinstance(i, _CodegenArrayAbstract) for i in args): from sympy import MatAdd return MatAdd(*args).doit() else: return ArrayAdd(*args) def _a2m_trace(arg): if isinstance(arg, _CodegenArrayAbstract): return ArrayContraction(arg, (0, 1)) else: from sympy import Trace return Trace(arg) def _a2m_transpose(arg): if isinstance(arg, _CodegenArrayAbstract): return PermuteDims(arg, [1, 0]) else: from sympy import Transpose return Transpose(arg).doit()
fb185c01aa7f3ff62969aee8d8a17d886b48f08ee20d3dca2867ecbe1734c053
import operator from functools import reduce import itertools from itertools import accumulate from typing import Optional, List, Dict from sympy import Expr, ImmutableDenseNDimArray, S, Symbol, Integer, ZeroMatrix, Basic, tensorproduct, Add, permutedims, \ Tuple, tensordiagonal, Lambda, Dummy, Function, MatrixExpr, NDimArray, Indexed, IndexedBase, default_sort_key, \ tensorcontraction, diagonalize_vector, Mul from sympy.matrices.expressions.matexpr import MatrixElement from sympy.tensor.array.expressions.utils import _apply_recursively_over_nested_lists, _sort_contraction_indices, \ _get_mapping_from_subranks, _build_push_indices_up_func_transformation, _get_contraction_links, \ _build_push_indices_down_func_transformation from sympy.combinatorics import Permutation from sympy.combinatorics.permutations import _af_invert from sympy.core.sympify import _sympify class _ArrayExpr(Expr): pass class ArraySymbol(_ArrayExpr): """ Symbol representing an array expression """ def __new__(cls, symbol, *shape): if isinstance(symbol, str): symbol = Symbol(symbol) # symbol = _sympify(symbol) shape = map(_sympify, shape) obj = Expr.__new__(cls, symbol, *shape) return obj @property def name(self): return self._args[0] @property def shape(self): return self._args[1:] def __getitem__(self, item): return ArrayElement(self, item) def as_explicit(self): if any(not isinstance(i, (int, Integer)) for i in self.shape): raise ValueError("cannot express explicit array with symbolic shape") data = [self[i] for i in itertools.product(*[range(j) for j in self.shape])] return ImmutableDenseNDimArray(data).reshape(*self.shape) class ArrayElement(_ArrayExpr): """ An element of an array. """ def __new__(cls, name, indices): if isinstance(name, str): name = Symbol(name) name = _sympify(name) indices = _sympify(indices) if hasattr(name, "shape"): if any([(i >= s) == True for i, s in zip(indices, name.shape)]): raise ValueError("shape is out of bounds") if any([(i < 0) == True for i in indices]): raise ValueError("shape contains negative values") obj = Expr.__new__(cls, name, indices) return obj @property def name(self): return self._args[0] @property def indices(self): return self._args[1] class ZeroArray(_ArrayExpr): """ Symbolic array of zeros. Equivalent to ``ZeroMatrix`` for matrices. """ def __new__(cls, *shape): if len(shape) == 0: return S.Zero shape = map(_sympify, shape) obj = Expr.__new__(cls, *shape) return obj @property def shape(self): return self._args def as_explicit(self): if any(not i.is_Integer for i in self.shape): raise ValueError("Cannot return explicit form for symbolic shape.") return ImmutableDenseNDimArray.zeros(*self.shape) class OneArray(_ArrayExpr): """ Symbolic array of ones. """ def __new__(cls, *shape): if len(shape) == 0: return S.One shape = map(_sympify, shape) obj = Expr.__new__(cls, *shape) return obj @property def shape(self): return self._args def as_explicit(self): if any(not i.is_Integer for i in self.shape): raise ValueError("Cannot return explicit form for symbolic shape.") return ImmutableDenseNDimArray([S.One for i in range(reduce(operator.mul, self.shape))]).reshape(*self.shape) class _CodegenArrayAbstract(Basic): @property def subranks(self): """ Returns the ranks of the objects in the uppermost tensor product inside the current object. In case no tensor products are contained, return the atomic ranks. Examples ======== >>> from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayContraction >>> from sympy import MatrixSymbol >>> M = MatrixSymbol("M", 3, 3) >>> N = MatrixSymbol("N", 3, 3) >>> P = MatrixSymbol("P", 3, 3) Important: do not confuse the rank of the matrix with the rank of an array. >>> tp = ArrayTensorProduct(M, N, P) >>> tp.subranks [2, 2, 2] >>> co = ArrayContraction(tp, (1, 2), (3, 4)) >>> co.subranks [2, 2, 2] """ return self._subranks[:] def subrank(self): """ The sum of ``subranks``. """ return sum(self.subranks) @property def shape(self): return self._shape class ArrayTensorProduct(_CodegenArrayAbstract): r""" Class to represent the tensor product of array-like objects. """ def __new__(cls, *args): args = [_sympify(arg) for arg in args] args = cls._flatten(args) ranks = [get_rank(arg) for arg in args] # Check if there are nested permutation and lift them up: permutation_cycles = [] for i, arg in enumerate(args): if not isinstance(arg, PermuteDims): continue permutation_cycles.extend([[k + sum(ranks[:i]) for k in j] for j in arg.permutation.cyclic_form]) args[i] = arg.expr if permutation_cycles: return PermuteDims(ArrayTensorProduct(*args), Permutation(sum(ranks)-1)*Permutation(permutation_cycles)) if len(args) == 1: return args[0] # If any object is a ZeroArray, return a ZeroArray: if any(isinstance(arg, (ZeroArray, ZeroMatrix)) for arg in args): shapes = reduce(operator.add, [get_shape(i) for i in args], ()) return ZeroArray(*shapes) # If there are contraction objects inside, transform the whole # expression into `ArrayContraction`: contractions = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayContraction)} if contractions: ranks = [_get_subrank(arg) if isinstance(arg, ArrayContraction) else get_rank(arg) for arg in args] cumulative_ranks = list(accumulate([0] + ranks))[:-1] tp = cls(*[arg.expr if isinstance(arg, ArrayContraction) else arg for arg in args]) contraction_indices = [tuple(cumulative_ranks[i] + k for k in j) for i, arg in contractions.items() for j in arg.contraction_indices] return ArrayContraction(tp, *contraction_indices) diagonals = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayDiagonal)} if diagonals: permutation = [] last_perm = [] ranks = [get_rank(arg) for arg in args] cumulative_ranks = list(accumulate([0] + ranks))[:-1] for i, arg in enumerate(args): if isinstance(arg, ArrayDiagonal): i1 = get_rank(arg) - len(arg.diagonal_indices) i2 = len(arg.diagonal_indices) permutation.extend([cumulative_ranks[i] + j for j in range(i1)]) last_perm.extend([cumulative_ranks[i] + j for j in range(i1, i1 + i2)]) else: permutation.extend([cumulative_ranks[i] + j for j in range(get_rank(arg))]) permutation.extend(last_perm) tp = cls(*[arg.expr if isinstance(arg, ArrayDiagonal) else arg for arg in args]) ranks2 = [_get_subrank(arg) if isinstance(arg, ArrayDiagonal) else get_rank(arg) for arg in args] cumulative_ranks2 = list(accumulate([0] + ranks2))[:-1] diagonal_indices = [tuple(cumulative_ranks2[i] + k for k in j) for i, arg in diagonals.items() for j in arg.diagonal_indices] return PermuteDims(ArrayDiagonal(tp, *diagonal_indices), permutation) obj = Basic.__new__(cls, *args) obj._subranks = ranks shapes = [get_shape(i) for i in args] if any(i is None for i in shapes): obj._shape = None else: obj._shape = tuple(j for i in shapes for j in i) return obj @classmethod def _flatten(cls, args): args = [i for arg in args for i in (arg.args if isinstance(arg, cls) else [arg])] return args def as_explicit(self): return tensorproduct(*[arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args]) class ArrayAdd(_CodegenArrayAbstract): r""" Class for elementwise array additions. """ def __new__(cls, *args): args = [_sympify(arg) for arg in args] ranks = [get_rank(arg) for arg in args] ranks = list(set(ranks)) if len(ranks) != 1: raise ValueError("summing arrays of different ranks") shapes = [arg.shape for arg in args] if len({i for i in shapes if i is not None}) > 1: raise ValueError("mismatching shapes in addition") # Flatten: args = cls._flatten_args(args) args = [arg for arg in args if not isinstance(arg, (ZeroArray, ZeroMatrix))] if len(args) == 0: if any(i for i in shapes if i is None): raise NotImplementedError("cannot handle addition of ZeroMatrix/ZeroArray and undefined shape object") return ZeroArray(*shapes[0]) elif len(args) == 1: return args[0] obj = Basic.__new__(cls, *args) obj._subranks = ranks if any(i is None for i in shapes): obj._shape = None else: obj._shape = shapes[0] return obj @classmethod def _flatten_args(cls, args): new_args = [] for arg in args: if isinstance(arg, ArrayAdd): new_args.extend(arg.args) else: new_args.append(arg) return new_args def as_explicit(self): return Add.fromiter([arg.as_explicit() for arg in self.args]) class PermuteDims(_CodegenArrayAbstract): r""" Class to represent permutation of axes of arrays. Examples ======== >>> from sympy.tensor.array.expressions.array_expressions import PermuteDims >>> from sympy import MatrixSymbol >>> M = MatrixSymbol("M", 3, 3) >>> cg = PermuteDims(M, [1, 0]) The object ``cg`` represents the transposition of ``M``, as the permutation ``[1, 0]`` will act on its indices by switching them: `M_{ij} \Rightarrow M_{ji}` This is evident when transforming back to matrix form: >>> from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix >>> convert_array_to_matrix(cg) M.T >>> N = MatrixSymbol("N", 3, 2) >>> cg = PermuteDims(N, [1, 0]) >>> cg.shape (2, 3) Permutations of tensor products are simplified in order to achieve a standard form: >>> from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct >>> M = MatrixSymbol("M", 4, 5) >>> tp = ArrayTensorProduct(M, N) >>> tp.shape (4, 5, 3, 2) >>> perm1 = PermuteDims(tp, [2, 3, 1, 0]) The args ``(M, N)`` have been sorted and the permutation has been simplified, the expression is equivalent: >>> perm1.expr.args (N, M) >>> perm1.shape (3, 2, 5, 4) >>> perm1.permutation (2 3) The permutation in its array form has been simplified from ``[2, 3, 1, 0]`` to ``[0, 1, 3, 2]``, as the arguments of the tensor product `M` and `N` have been switched: >>> perm1.permutation.array_form [0, 1, 3, 2] We can nest a second permutation: >>> perm2 = PermuteDims(perm1, [1, 0, 2, 3]) >>> perm2.shape (2, 3, 5, 4) >>> perm2.permutation.array_form [1, 0, 3, 2] """ def __new__(cls, expr, permutation, nest_permutation=True): from sympy.combinatorics import Permutation expr = _sympify(expr) permutation = Permutation(permutation) permutation_size = permutation.size expr_rank = get_rank(expr) if permutation_size != expr_rank: raise ValueError("Permutation size must be the length of the shape of expr") if isinstance(expr, PermuteDims): subexpr = expr.expr subperm = expr.permutation permutation = permutation * subperm expr = subexpr if isinstance(expr, ArrayContraction): expr, permutation = cls._handle_nested_contraction(expr, permutation) if isinstance(expr, ArrayTensorProduct): expr, permutation = cls._sort_components(expr, permutation) if isinstance(expr, (ZeroArray, ZeroMatrix)): return ZeroArray(*[expr.shape[i] for i in permutation.array_form]) plist = permutation.array_form if plist == sorted(plist): return expr obj = Basic.__new__(cls, expr, permutation) obj._subranks = [get_rank(expr)] shape = expr.shape if shape is None: obj._shape = None else: obj._shape = tuple(shape[permutation(i)] for i in range(len(shape))) return obj @property def expr(self): return self.args[0] @property def permutation(self): return self.args[1] @classmethod def _sort_components(cls, expr, permutation): # Get the permutation in its image-form: perm_image_form = _af_invert(permutation.array_form) args = list(expr.args) # Starting index global position for every arg: cumul = list(accumulate([0] + expr.subranks)) # Split `perm_image_form` into a list of list corresponding to the indices # of every argument: perm_image_form_in_components = [perm_image_form[cumul[i]:cumul[i+1]] for i in range(len(args))] # Create an index, target-position-key array: ps = [(i, sorted(comp)) for i, comp in enumerate(perm_image_form_in_components)] # Sort the array according to the target-position-key: # In this way, we define a canonical way to sort the arguments according # to the permutation. ps.sort(key=lambda x: x[1]) # Read the inverse-permutation (i.e. image-form) of the args: perm_args_image_form = [i[0] for i in ps] # Apply the args-permutation to the `args`: args_sorted = [args[i] for i in perm_args_image_form] # Apply the args-permutation to the array-form of the permutation of the axes (of `expr`): perm_image_form_sorted_args = [perm_image_form_in_components[i] for i in perm_args_image_form] new_permutation = Permutation(_af_invert([j for i in perm_image_form_sorted_args for j in i])) return ArrayTensorProduct(*args_sorted), new_permutation @classmethod def _handle_nested_contraction(cls, expr, permutation): if not isinstance(expr, ArrayContraction): return expr, permutation if not isinstance(expr.expr, ArrayTensorProduct): return expr, permutation args = expr.expr.args subranks = [get_rank(arg) for arg in expr.expr.args] contraction_indices = expr.contraction_indices contraction_indices_flat = [j for i in contraction_indices for j in i] cumul = list(accumulate([0] + subranks)) # Spread the permutation in its array form across the args in the corresponding # tensor-product arguments with free indices: permutation_array_blocks_up = [] image_form = _af_invert(permutation.array_form) counter = 0 for i, e in enumerate(subranks): current = [] for j in range(cumul[i], cumul[i+1]): if j in contraction_indices_flat: continue current.append(image_form[counter]) counter += 1 permutation_array_blocks_up.append(current) # Get the map of axis repositioning for every argument of tensor-product: index_blocks = [[j for j in range(cumul[i], cumul[i+1])] for i, e in enumerate(expr.subranks)] index_blocks_up = expr._push_indices_up(expr.contraction_indices, index_blocks) inverse_permutation = permutation**(-1) index_blocks_up_permuted = [[inverse_permutation(j) for j in i if j is not None] for i in index_blocks_up] # Sorting key is a list of tuple, first element is the index of `args`, second element of # the tuple is the sorting key to sort `args` of the tensor product: sorting_keys = list(enumerate(index_blocks_up_permuted)) sorting_keys.sort(key=lambda x: x[1]) # Now we can get the permutation acting on the args in its image-form: new_perm_image_form = [i[0] for i in sorting_keys] # Apply the args-level permutation to various elements: new_index_blocks = [index_blocks[i] for i in new_perm_image_form] new_index_perm_array_form = _af_invert([j for i in new_index_blocks for j in i]) new_args = [args[i] for i in new_perm_image_form] new_contraction_indices = [tuple(new_index_perm_array_form[j] for j in i) for i in contraction_indices] new_expr = ArrayContraction(ArrayTensorProduct(*new_args), *new_contraction_indices) new_permutation = Permutation(_af_invert([j for i in [permutation_array_blocks_up[k] for k in new_perm_image_form] for j in i])) return new_expr, new_permutation @classmethod def _check_permutation_mapping(cls, expr, permutation): subranks = expr.subranks index2arg = [i for i, arg in enumerate(expr.args) for j in range(expr.subranks[i])] permuted_indices = [permutation(i) for i in range(expr.subrank())] new_args = list(expr.args) arg_candidate_index = index2arg[permuted_indices[0]] current_indices = [] new_permutation = [] inserted_arg_cand_indices = set([]) for i, idx in enumerate(permuted_indices): if index2arg[idx] != arg_candidate_index: new_permutation.extend(current_indices) current_indices = [] arg_candidate_index = index2arg[idx] current_indices.append(idx) arg_candidate_rank = subranks[arg_candidate_index] if len(current_indices) == arg_candidate_rank: new_permutation.extend(sorted(current_indices)) local_current_indices = [j - min(current_indices) for j in current_indices] i1 = index2arg[i] new_args[i1] = PermuteDims(new_args[i1], Permutation(local_current_indices)) inserted_arg_cand_indices.add(arg_candidate_index) current_indices = [] new_permutation.extend(current_indices) # TODO: swap args positions in order to simplify the expression: # TODO: this should be in a function args_positions = list(range(len(new_args))) # Get possible shifts: maps = {} cumulative_subranks = [0] + list(accumulate(subranks)) for i in range(0, len(subranks)): s = set([index2arg[new_permutation[j]] for j in range(cumulative_subranks[i], cumulative_subranks[i+1])]) if len(s) != 1: continue elem = next(iter(s)) if i != elem: maps[i] = elem # Find cycles in the map: lines = [] current_line = [] while maps: if len(current_line) == 0: k, v = maps.popitem() current_line.append(k) else: k = current_line[-1] if k not in maps: current_line = [] continue v = maps.pop(k) if v in current_line: lines.append(current_line) current_line = [] continue current_line.append(v) for line in lines: for i, e in enumerate(line): args_positions[line[(i + 1) % len(line)]] = e # TODO: function in order to permute the args: permutation_blocks = [[new_permutation[cumulative_subranks[i] + j] for j in range(e)] for i, e in enumerate(subranks)] new_args = [new_args[i] for i in args_positions] new_permutation_blocks = [permutation_blocks[i] for i in args_positions] new_permutation2 = [j for i in new_permutation_blocks for j in i] return ArrayTensorProduct(*new_args), Permutation(new_permutation2) # **(-1) @classmethod def _check_if_there_are_closed_cycles(cls, expr, permutation): args = list(expr.args) subranks = expr.subranks cyclic_form = permutation.cyclic_form cumulative_subranks = [0] + list(accumulate(subranks)) cyclic_min = [min(i) for i in cyclic_form] cyclic_max = [max(i) for i in cyclic_form] cyclic_keep = [] for i, cycle in enumerate(cyclic_form): flag = True for j in range(0, len(cumulative_subranks) - 1): if cyclic_min[i] >= cumulative_subranks[j] and cyclic_max[i] < cumulative_subranks[j+1]: # Found a sinkable cycle. args[j] = PermuteDims(args[j], Permutation([[k - cumulative_subranks[j] for k in cyclic_form[i]]])) flag = False break if flag: cyclic_keep.append(cyclic_form[i]) return ArrayTensorProduct(*args), Permutation(cyclic_keep, size=permutation.size) def nest_permutation(self): r""" DEPRECATED. """ ret = self._nest_permutation(self.expr, self.permutation) if ret is None: return self return ret @classmethod def _nest_permutation(cls, expr, permutation): if isinstance(expr, ArrayTensorProduct): return PermuteDims(*cls._check_if_there_are_closed_cycles(expr, permutation)) elif isinstance(expr, ArrayContraction): # Invert tree hierarchy: put the contraction above. cycles = permutation.cyclic_form newcycles = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *cycles) newpermutation = Permutation(newcycles) new_contr_indices = [tuple(newpermutation(j) for j in i) for i in expr.contraction_indices] return ArrayContraction(PermuteDims(expr.expr, newpermutation), *new_contr_indices) elif isinstance(expr, ArrayAdd): return ArrayAdd(*[PermuteDims(arg, permutation) for arg in expr.args]) return None def as_explicit(self): return permutedims(self.expr.as_explicit(), self.permutation) class ArrayDiagonal(_CodegenArrayAbstract): r""" Class to represent the diagonal operator. Explanation =========== In a 2-dimensional array it returns the diagonal, this looks like the operation: `A_{ij} \rightarrow A_{ii}` The diagonal over axes 1 and 2 (the second and third) of the tensor product of two 2-dimensional arrays `A \otimes B` is `\Big[ A_{ab} B_{cd} \Big]_{abcd} \rightarrow \Big[ A_{ai} B_{id} \Big]_{adi}` In this last example the array expression has been reduced from 4-dimensional to 3-dimensional. Notice that no contraction has occurred, rather there is a new index `i` for the diagonal, contraction would have reduced the array to 2 dimensions. Notice that the diagonalized out dimensions are added as new dimensions at the end of the indices. """ def __new__(cls, expr, *diagonal_indices): expr = _sympify(expr) diagonal_indices = [Tuple(*sorted(i)) for i in diagonal_indices] if isinstance(expr, ArrayAdd): return ArrayAdd(*[ArrayDiagonal(arg, *diagonal_indices) for arg in expr.args]) if isinstance(expr, ArrayDiagonal): return cls._flatten(expr, *diagonal_indices) if isinstance(expr, PermuteDims): return cls._handle_nested_permutedims_in_diag(expr, *diagonal_indices) shape = expr.shape if shape is not None: cls._validate(expr, *diagonal_indices) # Get new shape: positions, shape = cls._get_positions_shape(shape, diagonal_indices) else: positions = None if len(diagonal_indices) == 0: return expr if isinstance(expr, (ZeroArray, ZeroMatrix)): return ZeroArray(*shape) obj = Basic.__new__(cls, expr, *diagonal_indices) obj._positions = positions obj._subranks = _get_subranks(expr) obj._shape = shape return obj @staticmethod def _validate(expr, *diagonal_indices): # Check that no diagonalization happens on indices with mismatched # dimensions: shape = expr.shape for i in diagonal_indices: if len({shape[j] for j in i}) != 1: raise ValueError("diagonalizing indices of different dimensions") if len(i) <= 1: raise ValueError("need at least two axes to diagonalize") @staticmethod def _remove_trivial_dimensions(shape, *diagonal_indices): return [tuple(j for j in i) for i in diagonal_indices if shape[i[0]] != 1] @property def expr(self): return self.args[0] @property def diagonal_indices(self): return self.args[1:] @staticmethod def _flatten(expr, *outer_diagonal_indices): inner_diagonal_indices = expr.diagonal_indices all_inner = [j for i in inner_diagonal_indices for j in i] all_inner.sort() # TODO: add API for total rank and cumulative rank: total_rank = _get_subrank(expr) inner_rank = len(all_inner) outer_rank = total_rank - inner_rank shifts = [0 for i in range(outer_rank)] counter = 0 pointer = 0 for i in range(outer_rank): while pointer < inner_rank and counter >= all_inner[pointer]: counter += 1 pointer += 1 shifts[i] += pointer counter += 1 outer_diagonal_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_diagonal_indices) diagonal_indices = inner_diagonal_indices + outer_diagonal_indices return ArrayDiagonal(expr.expr, *diagonal_indices) @classmethod def _handle_nested_permutedims_in_diag(cls, expr: PermuteDims, *diagonal_indices): back_diagonal_indices = [[expr.permutation(j) for j in i] for i in diagonal_indices] nondiag = [i for i in range(get_rank(expr)) if not any(i in j for j in diagonal_indices)] back_nondiag = [expr.permutation(i) for i in nondiag] remap = {e: i for i, e in enumerate(sorted(back_nondiag))} new_permutation1 = [remap[i] for i in back_nondiag] shift = len(new_permutation1) diag_block_perm = [i + shift for i in range(len(back_diagonal_indices))] new_permutation = new_permutation1 + diag_block_perm return PermuteDims( ArrayDiagonal( expr.expr, *back_diagonal_indices ), new_permutation ) def _push_indices_down_nonstatic(self, indices): transform = lambda x: self._positions[x] if x < len(self._positions) else None return _apply_recursively_over_nested_lists(transform, indices) def _push_indices_up_nonstatic(self, indices): def transform(x): for i, e in enumerate(self._positions): if (isinstance(e, int) and x == e) or (isinstance(e, tuple) and x in e): return i return _apply_recursively_over_nested_lists(transform, indices) @classmethod def _push_indices_down(cls, diagonal_indices, indices, rank): positions, shape = cls._get_positions_shape(range(rank), diagonal_indices) transform = lambda x: positions[x] if x < len(positions) else None return _apply_recursively_over_nested_lists(transform, indices) @classmethod def _push_indices_up(cls, diagonal_indices, indices, rank): positions, shape = cls._get_positions_shape(range(rank), diagonal_indices) def transform(x): for i, e in enumerate(positions): if (isinstance(e, int) and x == e) or (isinstance(e, (tuple, Tuple)) and (x in e)): return i return _apply_recursively_over_nested_lists(transform, indices) @classmethod def _get_positions_shape(cls, shape, diagonal_indices): data1 = tuple((i, shp) for i, shp in enumerate(shape) if not any(i in j for j in diagonal_indices)) pos1, shp1 = zip(*data1) if data1 else ((), ()) data2 = tuple((i, shape[i[0]]) for i in diagonal_indices) pos2, shp2 = zip(*data2) if data2 else ((), ()) positions = pos1 + pos2 shape = shp1 + shp2 return positions, shape def as_explicit(self): return tensordiagonal(self.expr.as_explicit(), *self.diagonal_indices) class ArrayElementwiseApplyFunc(_CodegenArrayAbstract): def __new__(cls, function, element): if not isinstance(function, Lambda): d = Dummy('d') function = Lambda(d, function(d)) obj = _CodegenArrayAbstract.__new__(cls, function, element) obj._subranks = _get_subranks(element) return obj @property def function(self): return self.args[0] @property def expr(self): return self.args[1] @property def shape(self): return self.expr.shape def _get_function_fdiff(self): d = Dummy("d") function = self.function(d) fdiff = function.diff(d) if isinstance(fdiff, Function): fdiff = type(fdiff) else: fdiff = Lambda(d, fdiff) return fdiff class ArrayContraction(_CodegenArrayAbstract): r""" This class is meant to represent contractions of arrays in a form easily processable by the code printers. """ def __new__(cls, expr, *contraction_indices, **kwargs): contraction_indices = _sort_contraction_indices(contraction_indices) expr = _sympify(expr) if len(contraction_indices) == 0: return expr if isinstance(expr, ArrayContraction): return cls._flatten(expr, *contraction_indices) if isinstance(expr, (ZeroArray, ZeroMatrix)): contraction_indices_flat = [j for i in contraction_indices for j in i] shape = [e for i, e in enumerate(expr.shape) if i not in contraction_indices_flat] return ZeroArray(*shape) if isinstance(expr, PermuteDims): return cls._handle_nested_permute_dims(expr, *contraction_indices) if isinstance(expr, ArrayTensorProduct): expr, contraction_indices = cls._sort_fully_contracted_args(expr, contraction_indices) expr, contraction_indices = cls._lower_contraction_to_addends(expr, contraction_indices) if len(contraction_indices) == 0: return expr if isinstance(expr, ArrayDiagonal): return cls._handle_nested_diagonal(expr, *contraction_indices) if isinstance(expr, ArrayAdd): return ArrayAdd(*[ArrayContraction(i, *contraction_indices) for i in expr.args]) obj = Basic.__new__(cls, expr, *contraction_indices) obj._subranks = _get_subranks(expr) obj._mapping = _get_mapping_from_subranks(obj._subranks) free_indices_to_position = {i: i for i in range(sum(obj._subranks)) if all([i not in cind for cind in contraction_indices])} obj._free_indices_to_position = free_indices_to_position shape = expr.shape cls._validate(expr, *contraction_indices) if shape: shape = tuple(shp for i, shp in enumerate(shape) if not any(i in j for j in contraction_indices)) obj._shape = shape return obj def __mul__(self, other): if other == 1: return self else: raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.") def __rmul__(self, other): if other == 1: return self else: raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.") @staticmethod def _validate(expr, *contraction_indices): shape = expr.shape if shape is None: return # Check that no contraction happens when the shape is mismatched: for i in contraction_indices: if len({shape[j] for j in i if shape[j] != -1}) != 1: raise ValueError("contracting indices of different dimensions") @classmethod def _push_indices_down(cls, contraction_indices, indices): flattened_contraction_indices = [j for i in contraction_indices for j in i] flattened_contraction_indices.sort() transform = _build_push_indices_down_func_transformation(flattened_contraction_indices) return _apply_recursively_over_nested_lists(transform, indices) @classmethod def _push_indices_up(cls, contraction_indices, indices): flattened_contraction_indices = [j for i in contraction_indices for j in i] flattened_contraction_indices.sort() transform = _build_push_indices_up_func_transformation(flattened_contraction_indices) return _apply_recursively_over_nested_lists(transform, indices) @classmethod def _lower_contraction_to_addends(cls, expr, contraction_indices): if isinstance(expr, ArrayAdd): raise NotImplementedError() if not isinstance(expr, ArrayTensorProduct): return expr, contraction_indices subranks = expr.subranks cumranks = list(accumulate([0] + subranks)) contraction_indices_remaining = [] contraction_indices_args = [[] for i in expr.args] backshift = set([]) for i, contraction_group in enumerate(contraction_indices): for j in range(len(expr.args)): if not isinstance(expr.args[j], ArrayAdd): continue if all(cumranks[j] <= k < cumranks[j+1] for k in contraction_group): contraction_indices_args[j].append([k - cumranks[j] for k in contraction_group]) backshift.update(contraction_group) break else: contraction_indices_remaining.append(contraction_group) if len(contraction_indices_remaining) == len(contraction_indices): return expr, contraction_indices total_rank = get_rank(expr) shifts = list(accumulate([1 if i in backshift else 0 for i in range(total_rank)])) contraction_indices_remaining = [Tuple.fromiter(j - shifts[j] for j in i) for i in contraction_indices_remaining] ret = ArrayTensorProduct(*[ ArrayContraction(arg, *contr) for arg, contr in zip(expr.args, contraction_indices_args) ]) return ret, contraction_indices_remaining def split_multiple_contractions(self): """ Recognize multiple contractions and attempt at rewriting them as paired-contractions. This allows some contractions involving more than two indices to be rewritten as multiple contractions involving two indices, thus allowing the expression to be rewritten as a matrix multiplication line. Examples: * `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C` Care for: - matrix being diagonalized (i.e. `A_ii`) - vectors being diagonalized (i.e. `a_i0`) Multiple contractions can be split into matrix multiplications if not more than two arguments are non-diagonals or non-vectors. Vectors get diagonalized while diagonal matrices remain diagonal. The non-diagonal matrices can be at the beginning or at the end of the final matrix multiplication line. """ from sympy import ask, Q editor = _EditArrayContraction(self) contraction_indices = self.contraction_indices if isinstance(self.expr, ArrayTensorProduct): args = list(self.expr.args) else: args = [self.expr] # TODO: unify API, best location in ArrayTensorProduct subranks = [get_rank(i) for i in args] # TODO: unify API mapping = _get_mapping_from_subranks(subranks) reverse_mapping = {v: k for k, v in mapping.items()} for indl, links in enumerate(contraction_indices): if len(links) <= 2: continue positions = editor.get_mapping_for_index(indl) # Also consider the case of diagonal matrices being contracted: current_dimension = self.expr.shape[links[0]] not_vectors: Tuple[_ArgE, int] = [] vectors: Tuple[_ArgE, int] = [] for arg_ind, rel_ind in positions: mat = args[arg_ind] other_arg_pos = 1-rel_ind other_arg_abs = reverse_mapping[arg_ind, other_arg_pos] arg = editor.args_with_ind[arg_ind] if (((1 not in mat.shape) and (not ask(Q.diagonal(mat)))) or ((current_dimension == 1) is True and mat.shape != (1, 1)) or any([other_arg_abs in l for li, l in enumerate(contraction_indices) if li != indl]) ): not_vectors.append((arg, rel_ind)) else: vectors.append((arg, rel_ind)) if len(not_vectors) > 2: # If more than two arguments in the multiple contraction are # non-vectors and non-diagonal matrices, we cannot find a way # to split this contraction into a matrix multiplication line: continue # Three cases to handle: # - zero non-vectors # - one non-vector # - two non-vectors for v, rel_ind in vectors: v.element = diagonalize_vector(v.element) vectors_to_loop = not_vectors[:1] + vectors + not_vectors[1:] first_not_vector, rel_ind = vectors_to_loop[0] new_index = first_not_vector.indices[rel_ind] for v, rel_ind in vectors_to_loop[1:-1]: v.indices[rel_ind] = new_index new_index = editor.get_new_contraction_index() assert v.indices.index(None) == 1 - rel_ind v.indices[v.indices.index(None)] = new_index last_vec, rel_ind = vectors_to_loop[-1] last_vec.indices[rel_ind] = new_index return editor.to_array_contraction() def flatten_contraction_of_diagonal(self): if not isinstance(self.expr, ArrayDiagonal): return self contraction_down = self.expr._push_indices_down(self.expr.diagonal_indices, self.contraction_indices) new_contraction_indices = [] diagonal_indices = self.expr.diagonal_indices[:] for i in contraction_down: contraction_group = list(i) for j in i: diagonal_with = [k for k in diagonal_indices if j in k] contraction_group.extend([l for k in diagonal_with for l in k]) diagonal_indices = [k for k in diagonal_indices if k not in diagonal_with] new_contraction_indices.append(sorted(set(contraction_group))) new_contraction_indices = ArrayDiagonal._push_indices_up(diagonal_indices, new_contraction_indices) return ArrayContraction( ArrayDiagonal( self.expr.expr, *diagonal_indices ), *new_contraction_indices ) @staticmethod def _get_free_indices_to_position_map(free_indices, contraction_indices): free_indices_to_position = {} flattened_contraction_indices = [j for i in contraction_indices for j in i] counter = 0 for ind in free_indices: while counter in flattened_contraction_indices: counter += 1 free_indices_to_position[ind] = counter counter += 1 return free_indices_to_position @staticmethod def _get_index_shifts(expr): """ Get the mapping of indices at the positions before the contraction occurs. Examples ======== >>> from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct >>> from sympy.tensor.array.expressions.array_expressions import ArrayContraction >>> from sympy import MatrixSymbol >>> M = MatrixSymbol("M", 3, 3) >>> N = MatrixSymbol("N", 3, 3) >>> cg = ArrayContraction(ArrayTensorProduct(M, N), [1, 2]) >>> cg._get_index_shifts(cg) [0, 2] Indeed, ``cg`` after the contraction has two dimensions, 0 and 1. They need to be shifted by 0 and 2 to get the corresponding positions before the contraction (that is, 0 and 3). """ inner_contraction_indices = expr.contraction_indices all_inner = [j for i in inner_contraction_indices for j in i] all_inner.sort() # TODO: add API for total rank and cumulative rank: total_rank = _get_subrank(expr) inner_rank = len(all_inner) outer_rank = total_rank - inner_rank shifts = [0 for i in range(outer_rank)] counter = 0 pointer = 0 for i in range(outer_rank): while pointer < inner_rank and counter >= all_inner[pointer]: counter += 1 pointer += 1 shifts[i] += pointer counter += 1 return shifts @staticmethod def _convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices): shifts = ArrayContraction._get_index_shifts(expr) outer_contraction_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_contraction_indices) return outer_contraction_indices @staticmethod def _flatten(expr, *outer_contraction_indices): inner_contraction_indices = expr.contraction_indices outer_contraction_indices = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices) contraction_indices = inner_contraction_indices + outer_contraction_indices return ArrayContraction(expr.expr, *contraction_indices) @classmethod def _handle_nested_permute_dims(cls, expr, *contraction_indices): permutation = expr.permutation plist = permutation.array_form new_contraction_indices = [tuple(permutation(j) for j in i) for i in contraction_indices] new_plist = [i for i in plist if all(i not in j for j in new_contraction_indices)] new_plist = cls._push_indices_up(new_contraction_indices, new_plist) return PermuteDims( ArrayContraction(expr.expr, *new_contraction_indices), Permutation(new_plist) ) @classmethod def _handle_nested_diagonal(cls, expr: 'ArrayDiagonal', *contraction_indices): diagonal_indices = list(expr.diagonal_indices) down_contraction_indices = expr._push_indices_down(expr.diagonal_indices, contraction_indices, get_rank(expr.expr)) # Flatten diagonally contracted indices: down_contraction_indices = [[k for j in i for k in (j if isinstance(j, (tuple, Tuple)) else [j])] for i in down_contraction_indices] new_contraction_indices = [] for contr_indgrp in down_contraction_indices: ind = contr_indgrp[:] for j, diag_indgrp in enumerate(diagonal_indices): if diag_indgrp is None: continue if any(i in diag_indgrp for i in contr_indgrp): ind.extend(diag_indgrp) diagonal_indices[j] = None new_contraction_indices.append(sorted(set(ind))) new_diagonal_indices_down = [i for i in diagonal_indices if i is not None] new_diagonal_indices = ArrayContraction._push_indices_up(new_contraction_indices, new_diagonal_indices_down) return ArrayDiagonal( ArrayContraction(expr.expr, *new_contraction_indices), *new_diagonal_indices ) @classmethod def _sort_fully_contracted_args(cls, expr, contraction_indices): if expr.shape is None: return expr, contraction_indices cumul = list(accumulate([0] + expr.subranks)) index_blocks = [list(range(cumul[i], cumul[i+1])) for i in range(len(expr.args))] contraction_indices_flat = {j for i in contraction_indices for j in i} fully_contracted = [all(j in contraction_indices_flat for j in range(cumul[i], cumul[i+1])) for i, arg in enumerate(expr.args)] new_pos = sorted(range(len(expr.args)), key=lambda x: (0, default_sort_key(expr.args[x])) if fully_contracted[x] else (1,)) new_args = [expr.args[i] for i in new_pos] new_index_blocks_flat = [j for i in new_pos for j in index_blocks[i]] index_permutation_array_form = _af_invert(new_index_blocks_flat) new_contraction_indices = [tuple(index_permutation_array_form[j] for j in i) for i in contraction_indices] new_contraction_indices = _sort_contraction_indices(new_contraction_indices) return ArrayTensorProduct(*new_args), new_contraction_indices def _get_contraction_tuples(self): r""" Return tuples containing the argument index and position within the argument of the index position. Examples ======== >>> from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct >>> from sympy import MatrixSymbol >>> from sympy.abc import N >>> from sympy.tensor.array.expressions.array_expressions import ArrayContraction >>> A = MatrixSymbol("A", N, N) >>> B = MatrixSymbol("B", N, N) >>> cg = ArrayContraction(ArrayTensorProduct(A, B), (1, 2)) >>> cg._get_contraction_tuples() [[(0, 1), (1, 0)]] Notes ===== Here the contraction pair `(1, 2)` meaning that the 2nd and 3rd indices of the tensor product `A\otimes B` are contracted, has been transformed into `(0, 1)` and `(1, 0)`, identifying the same indices in a different notation. `(0, 1)` is the second index (1) of the first argument (i.e. 0 or `A`). `(1, 0)` is the first index (i.e. 0) of the second argument (i.e. 1 or `B`). """ mapping = self._mapping return [[mapping[j] for j in i] for i in self.contraction_indices] @staticmethod def _contraction_tuples_to_contraction_indices(expr, contraction_tuples): # TODO: check that `expr` has `.subranks`: ranks = expr.subranks cumulative_ranks = [0] + list(accumulate(ranks)) return [tuple(cumulative_ranks[j]+k for j, k in i) for i in contraction_tuples] @property def free_indices(self): return self._free_indices[:] @property def free_indices_to_position(self): return dict(self._free_indices_to_position) @property def expr(self): return self.args[0] @property def contraction_indices(self): return self.args[1:] def _contraction_indices_to_components(self): expr = self.expr if not isinstance(expr, ArrayTensorProduct): raise NotImplementedError("only for contractions of tensor products") ranks = expr.subranks mapping = {} counter = 0 for i, rank in enumerate(ranks): for j in range(rank): mapping[counter] = (i, j) counter += 1 return mapping def sort_args_by_name(self): """ Sort arguments in the tensor product so that their order is lexicographical. Examples ======== >>> from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array >>> from sympy import MatrixSymbol >>> from sympy.abc import N >>> A = MatrixSymbol("A", N, N) >>> B = MatrixSymbol("B", N, N) >>> C = MatrixSymbol("C", N, N) >>> D = MatrixSymbol("D", N, N) >>> cg = convert_matrix_to_array(C*D*A*B) >>> cg ArrayContraction(ArrayTensorProduct(A, D, C, B), (0, 3), (1, 6), (2, 5)) >>> cg.sort_args_by_name() ArrayContraction(ArrayTensorProduct(A, D, B, C), (0, 3), (1, 4), (2, 7)) """ expr = self.expr if not isinstance(expr, ArrayTensorProduct): return self args = expr.args sorted_data = sorted(enumerate(args), key=lambda x: default_sort_key(x[1])) pos_sorted, args_sorted = zip(*sorted_data) reordering_map = {i: pos_sorted.index(i) for i, arg in enumerate(args)} contraction_tuples = self._get_contraction_tuples() contraction_tuples = [[(reordering_map[j], k) for j, k in i] for i in contraction_tuples] c_tp = ArrayTensorProduct(*args_sorted) new_contr_indices = self._contraction_tuples_to_contraction_indices( c_tp, contraction_tuples ) return ArrayContraction(c_tp, *new_contr_indices) def _get_contraction_links(self): r""" Returns a dictionary of links between arguments in the tensor product being contracted. See the example for an explanation of the values. Examples ======== >>> from sympy import MatrixSymbol >>> from sympy.abc import N >>> from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array >>> A = MatrixSymbol("A", N, N) >>> B = MatrixSymbol("B", N, N) >>> C = MatrixSymbol("C", N, N) >>> D = MatrixSymbol("D", N, N) Matrix multiplications are pairwise contractions between neighboring matrices: `A_{ij} B_{jk} C_{kl} D_{lm}` >>> cg = convert_matrix_to_array(A*B*C*D) >>> cg ArrayContraction(ArrayTensorProduct(B, C, A, D), (0, 5), (1, 2), (3, 6)) >>> cg._get_contraction_links() {0: {0: (2, 1), 1: (1, 0)}, 1: {0: (0, 1), 1: (3, 0)}, 2: {1: (0, 0)}, 3: {0: (1, 1)}} This dictionary is interpreted as follows: argument in position 0 (i.e. matrix `A`) has its second index (i.e. 1) contracted to `(1, 0)`, that is argument in position 1 (matrix `B`) on the first index slot of `B`, this is the contraction provided by the index `j` from `A`. The argument in position 1 (that is, matrix `B`) has two contractions, the ones provided by the indices `j` and `k`, respectively the first and second indices (0 and 1 in the sub-dict). The link `(0, 1)` and `(2, 0)` respectively. `(0, 1)` is the index slot 1 (the 2nd) of argument in position 0 (that is, `A_{\ldot j}`), and so on. """ args, dlinks = _get_contraction_links([self], self.subranks, *self.contraction_indices) return dlinks def as_explicit(self): return tensorcontraction(self.expr.as_explicit(), *self.contraction_indices) class _ArgE: """ The ``_ArgE`` object contains references to the array expression (``.element``) and a list containing the information about index contractions (``.indices``). Index contractions are numbered and contracted indices show the number of the contraction. Uncontracted indices have ``None`` value. For example: ``_ArgE(M, [None, 3])`` This object means that expression ``M`` is part of an array contraction and has two indices, the first is not contracted (value ``None``), the second index is contracted to the 4th (i.e. number ``3``) group of the array contraction object. """ def __init__(self, element): self.element = element self.indices: List[Optional[int]] = [None for i in range(get_rank(element))] def __str__(self): return "_ArgE(%s, %s)" % (self.element, self.indices) __repr__ = __str__ class _IndPos: """ Index position, requiring two integers in the constructor: - arg: the position of the argument in the tensor product, - rel: the relative position of the index inside the argument. """ def __init__(self, arg: int, rel: int): self.arg = arg self.rel = rel def __str__(self): return "_IndPos(%i, %i)" % (self.arg, self.rel) __repr__ = __str__ def __iter__(self): yield from [self.arg, self.rel] class _EditArrayContraction: """ Utility class to help manipulate array contraction objects. This class takes as input an ``ArrayContraction`` object and turns it into an editable object. The field ``args_with_ind`` of this class is a list of ``_ArgE`` objects which can be used to easily edit the contraction structure of the expression. Once editing is finished, the ``ArrayContraction`` object may be recreated by calling the ``.to_array_contraction()`` method. """ def __init__(self, array_contraction: ArrayContraction): expr = array_contraction.expr if isinstance(expr, ArrayTensorProduct): args = list(expr.args) else: args = [expr] args_with_ind: List[_ArgE] = [_ArgE(arg) for arg in args] mapping = _get_mapping_from_subranks(array_contraction.subranks) for i, contraction_tuple in enumerate(array_contraction.contraction_indices): for j in contraction_tuple: arg_pos, rel_pos = mapping[j] args_with_ind[arg_pos].indices[rel_pos] = i self.args_with_ind: List[_ArgE] = args_with_ind self.number_of_contraction_indices: int = len(array_contraction.contraction_indices) def insert_after(self, arg: _ArgE, new_arg: _ArgE): pos = self.args_with_ind.index(arg) self.args_with_ind.insert(pos + 1, new_arg) def get_new_contraction_index(self): self.number_of_contraction_indices += 1 return self.number_of_contraction_indices - 1 def refresh_indices(self): updates: Dict[int, int] = {} for arg_with_ind in self.args_with_ind: updates.update({i: -1 for i in arg_with_ind.indices if i is not None}) for i, e in enumerate(sorted(updates)): updates[e] = i self.number_of_contraction_indices: int = len(updates) for arg_with_ind in self.args_with_ind: arg_with_ind.indices = [updates.get(i, None) for i in arg_with_ind.indices] def merge_scalars(self): scalars = [] for arg_with_ind in self.args_with_ind: if len(arg_with_ind.indices) == 0: scalars.append(arg_with_ind) for i in scalars: self.args_with_ind.remove(i) scalar = Mul.fromiter([i.element for i in scalars]) if len(self.args_with_ind) == 0: self.args_with_ind.append(_ArgE(scalar)) else: from sympy.tensor.array.expressions.conv_array_to_matrix import _a2m_tensor_product self.args_with_ind[0].element = _a2m_tensor_product(scalar, self.args_with_ind[0].element) def to_array_contraction(self): self.merge_scalars() args = [arg.element for arg in self.args_with_ind] contraction_indices = self.get_contraction_indices() expr = ArrayContraction(ArrayTensorProduct(*args), *contraction_indices) if hasattr(self, '_track_permutation'): permutation = _af_invert([j for i in self._track_permutation for j in i]) expr = PermuteDims(expr, permutation) return expr def get_contraction_indices(self) -> List[List[int]]: contraction_indices: List[List[int]] = [[] for i in range(self.number_of_contraction_indices)] current_position: int = 0 for i, arg_with_ind in enumerate(self.args_with_ind): for j in arg_with_ind.indices: if j is not None: contraction_indices[j].append(current_position) current_position += 1 return contraction_indices def get_mapping_for_index(self, ind) -> List[_IndPos]: if ind >= self.number_of_contraction_indices: raise ValueError("index value exceeding the index range") positions: List[_IndPos] = [] for i, arg_with_ind in enumerate(self.args_with_ind): for j, arg_ind in enumerate(arg_with_ind.indices): if ind == arg_ind: positions.append(_IndPos(i, j)) return positions def get_contraction_indices_to_ind_rel_pos(self) -> List[List[_IndPos]]: contraction_indices: List[List[_IndPos]] = [[] for i in range(self.number_of_contraction_indices)] for i, arg_with_ind in enumerate(self.args_with_ind): for j, ind in enumerate(arg_with_ind.indices): if ind is not None: contraction_indices[ind].append(_IndPos(i, j)) return contraction_indices def count_args_with_index(self, index: int) -> int: """ Count the number of arguments that have the given index. """ counter: int = 0 for arg_with_ind in self.args_with_ind: if index in arg_with_ind.indices: counter += 1 return counter def track_permutation_start(self): self._track_permutation = [] counter: int = 0 for arg_with_ind in self.args_with_ind: perm = [] for i in arg_with_ind.indices: if i is not None: continue perm.append(counter) counter += 1 self._track_permutation.append(perm) def track_permutation_merge(self, destination: _ArgE, from_element: _ArgE): index_destination = self.args_with_ind.index(destination) index_element = self.args_with_ind.index(from_element) self._track_permutation[index_destination].extend(self._track_permutation[index_element]) self._track_permutation.pop(index_element) def get_rank(expr): if isinstance(expr, (MatrixExpr, MatrixElement)): return 2 if isinstance(expr, _CodegenArrayAbstract): return len(expr.shape) if isinstance(expr, NDimArray): return expr.rank() if isinstance(expr, Indexed): return expr.rank if isinstance(expr, IndexedBase): shape = expr.shape if shape is None: return -1 else: return len(shape) if hasattr(expr, "shape"): return len(expr.shape) return 0 def _get_subrank(expr): if isinstance(expr, _CodegenArrayAbstract): return expr.subrank() return get_rank(expr) def _get_subranks(expr): if isinstance(expr, _CodegenArrayAbstract): return expr.subranks else: return [get_rank(expr)] def get_shape(expr): if hasattr(expr, "shape"): return expr.shape return () def nest_permutation(expr): if isinstance(expr, PermuteDims): return expr.nest_permutation() else: return expr
7ac44bf5c7aa4e38f39613f41bf11b2378312e46279cbc598bebc3a8d8eb652d
from sympy import ( symbols, Identity, cos, ZeroMatrix, OneMatrix, sqrt) from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array from sympy.tensor.array.expressions.conv_array_to_matrix import _support_function_tp1_recognize, \ _array_diag2contr_diagmatrix, convert_array_to_matrix, _remove_trivial_dims, _array2matrix from sympy import MatrixSymbol from sympy.combinatorics import Permutation from sympy.matrices.expressions.diagonal import DiagMatrix from sympy.matrices import Trace, MatMul, Transpose from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, \ ArrayTensorProduct, ArrayAdd, PermuteDims, ArrayDiagonal, \ ArrayContraction from sympy.testing.pytest import raises i, j, k, l, m, n = symbols("i j k l m n") I = Identity(k) I1 = Identity(1) M = MatrixSymbol("M", k, k) N = MatrixSymbol("N", k, k) P = MatrixSymbol("P", k, k) Q = MatrixSymbol("Q", k, k) A = MatrixSymbol("A", k, k) B = MatrixSymbol("B", k, k) C = MatrixSymbol("C", k, k) D = MatrixSymbol("D", k, k) X = MatrixSymbol("X", k, k) Y = MatrixSymbol("Y", k, k) a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) c = MatrixSymbol("c", k, 1) d = MatrixSymbol("d", k, 1) x = MatrixSymbol("x", k, 1) def test_arrayexpr_convert_array_to_matrix(): cg = ArrayContraction(ArrayTensorProduct(M), (0, 1)) assert convert_array_to_matrix(cg) == Trace(M) cg = ArrayContraction(ArrayTensorProduct(M, N), (0, 1), (2, 3)) assert convert_array_to_matrix(cg) == Trace(M) * Trace(N) cg = ArrayContraction(ArrayTensorProduct(M, N), (0, 3), (1, 2)) assert convert_array_to_matrix(cg) == Trace(M * N) cg = ArrayContraction(ArrayTensorProduct(M, N), (0, 2), (1, 3)) assert convert_array_to_matrix(cg) == Trace(M * N.T) cg = convert_matrix_to_array(M * N * P) assert convert_array_to_matrix(cg) == M * N * P cg = convert_matrix_to_array(M * N.T * P) assert convert_array_to_matrix(cg) == M * N.T * P cg = ArrayContraction(ArrayTensorProduct(M,N,P,Q), (1, 2), (5, 6)) assert convert_array_to_matrix(cg) == ArrayTensorProduct(M * N, P * Q) cg = ArrayContraction(ArrayTensorProduct(-2, M, N), (1, 2)) assert convert_array_to_matrix(cg) == -2 * M * N a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) c = MatrixSymbol("c", k, 1) cg = PermuteDims( ArrayContraction( ArrayTensorProduct( a, ArrayAdd( ArrayTensorProduct(b, c), ArrayTensorProduct(c, b), ) ), (2, 4)), [0, 1, 3, 2]) assert convert_array_to_matrix(cg) == a * (b.T * c + c.T * b) za = ZeroArray(m, n) assert convert_array_to_matrix(za) == ZeroMatrix(m, n) cg = ArrayTensorProduct(3, M) assert convert_array_to_matrix(cg) == 3 * M # Partial conversion to matrix multiplication: expr = ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 2), (1, 4, 6)) assert convert_array_to_matrix(expr) == ArrayContraction(ArrayTensorProduct(M.T*N, P, Q), (0, 2, 4)) # TODO: not yet supported: # cg = ArrayDiagonal(ArrayTensorProduct(M, N, P), (0, 2, 4), (1, 3, 5)) # assert recognize_matrix_expression(cg) == HadamardProduct(M, N, P) # cg = ArrayDiagonal(ArrayTensorProduct(M, N, P), (0, 3, 4), (1, 2, 5)) # assert recognize_matrix_expression(cg) == HadamardProduct(M, N.T, P) x = MatrixSymbol("x", k, 1) cg = PermuteDims( ArrayContraction(ArrayTensorProduct(OneArray(1), x, OneArray(1), DiagMatrix(Identity(1))), (0, 5)), Permutation(1, 2, 3)) assert convert_array_to_matrix(cg) == x expr = ArrayAdd(M, PermuteDims(M, [1, 0])) assert convert_array_to_matrix(expr) == M + Transpose(M) def test_arrayexpr_convert_array_to_matrix2(): cg = ArrayContraction(ArrayTensorProduct(M, N), (1, 3)) assert convert_array_to_matrix(cg) == M * N.T cg = PermuteDims(ArrayTensorProduct(M, N), Permutation([0, 1, 3, 2])) assert convert_array_to_matrix(cg) == ArrayTensorProduct(M, N.T) cg = ArrayTensorProduct(M, PermuteDims(N, Permutation([1, 0]))) assert convert_array_to_matrix(cg) == ArrayTensorProduct(M, N.T) cg = ArrayContraction( PermuteDims( ArrayTensorProduct(M, N, P, Q), Permutation([0, 2, 3, 1, 4, 5, 7, 6])), (1, 2), (3, 5) ) assert convert_array_to_matrix(cg) == ArrayTensorProduct(M * P.T * Trace(N), Q.T) cg = ArrayContraction( ArrayTensorProduct(M, N, P, PermuteDims(Q, Permutation([1, 0]))), (1, 5), (2, 3) ) assert convert_array_to_matrix(cg) == ArrayTensorProduct(M * P.T * Trace(N), Q.T) cg = ArrayTensorProduct(M, PermuteDims(N, [1, 0])) assert convert_array_to_matrix(cg) == ArrayTensorProduct(M, N.T) cg = ArrayTensorProduct(PermuteDims(M, [1, 0]), PermuteDims(N, [1, 0])) assert convert_array_to_matrix(cg) == ArrayTensorProduct(M.T, N.T) cg = ArrayTensorProduct(PermuteDims(N, [1, 0]), PermuteDims(M, [1, 0])) assert convert_array_to_matrix(cg) == ArrayTensorProduct(N.T, M.T) def test_arrayexpr_convert_array_to_diagonalized_vector(): # Check matrix recognition over trivial dimensions: cg = ArrayTensorProduct(a, b) assert convert_array_to_matrix(cg) == a * b.T cg = ArrayTensorProduct(I1, a, b) assert convert_array_to_matrix(cg) == a * b.T # Recognize trace inside a tensor product: cg = ArrayContraction(ArrayTensorProduct(A, B, C), (0, 3), (1, 2)) assert convert_array_to_matrix(cg) == Trace(A * B) * C # Transform diagonal operator to contraction: cg = ArrayDiagonal(ArrayTensorProduct(A, a), (1, 2)) assert _array_diag2contr_diagmatrix(cg) == ArrayContraction(ArrayTensorProduct(A, OneArray(1), DiagMatrix(a)), (1, 3)) assert convert_array_to_matrix(cg) == A * DiagMatrix(a) cg = ArrayDiagonal(ArrayTensorProduct(a, b), (0, 2)) assert _array_diag2contr_diagmatrix(cg) == PermuteDims( ArrayContraction(ArrayTensorProduct(DiagMatrix(a), OneArray(1), b), (0, 3)), [1, 2, 0] ) assert convert_array_to_matrix(cg) == b.T * DiagMatrix(a) cg = ArrayDiagonal(ArrayTensorProduct(A, a), (0, 2)) assert _array_diag2contr_diagmatrix(cg) == ArrayContraction(ArrayTensorProduct(A, OneArray(1), DiagMatrix(a)), (0, 3)) assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a) cg = ArrayDiagonal(ArrayTensorProduct(I, x, I1), (0, 2), (3, 5)) assert _array_diag2contr_diagmatrix(cg) == ArrayContraction(ArrayTensorProduct(I, OneArray(1), I1, DiagMatrix(x)), (0, 5)) assert convert_array_to_matrix(cg) == DiagMatrix(x) cg = ArrayDiagonal(ArrayTensorProduct(I, x, A, B), (1, 2), (5, 6)) assert _array_diag2contr_diagmatrix(cg) == ArrayDiagonal(ArrayContraction(ArrayTensorProduct(I, OneArray(1), A, B, DiagMatrix(x)), (1, 7)), (5, 6)) # TODO: not yet working # assert convert_array_to_matrix(cg) cg = ArrayDiagonal(ArrayTensorProduct(x, I1), (1, 2)) assert isinstance(cg, ArrayDiagonal) assert cg.diagonal_indices == ((1, 2),) assert convert_array_to_matrix(cg) == x cg = ArrayDiagonal(ArrayTensorProduct(x, I), (0, 2)) assert _array_diag2contr_diagmatrix(cg) == ArrayContraction(ArrayTensorProduct(OneArray(1), I, DiagMatrix(x)), (1, 3)) assert convert_array_to_matrix(cg).doit() == DiagMatrix(x) raises(ValueError, lambda: ArrayDiagonal(x, (1,))) # Ignore identity matrices with contractions: cg = ArrayContraction(ArrayTensorProduct(I, A, I, I), (0, 2), (1, 3), (5, 7)) assert cg.split_multiple_contractions() == cg assert convert_array_to_matrix(cg) == Trace(A) * I cg = ArrayContraction(ArrayTensorProduct(Trace(A) * I, I, I), (1, 5), (3, 4)) assert cg.split_multiple_contractions() == cg assert convert_array_to_matrix(cg).doit() == Trace(A) * I # Add DiagMatrix when required: cg = ArrayContraction(ArrayTensorProduct(A, a), (1, 2)) assert cg.split_multiple_contractions() == cg assert convert_array_to_matrix(cg) == A * a cg = ArrayContraction(ArrayTensorProduct(A, a, B), (1, 2, 4)) assert cg.split_multiple_contractions() == ArrayContraction(ArrayTensorProduct(A, DiagMatrix(a), B), (1, 2), (3, 4)) assert convert_array_to_matrix(cg) == A * DiagMatrix(a) * B cg = ArrayContraction(ArrayTensorProduct(A, a, B), (0, 2, 4)) assert cg.split_multiple_contractions() == ArrayContraction(ArrayTensorProduct(A, DiagMatrix(a), B), (0, 2), (3, 4)) assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a) * B cg = ArrayContraction(ArrayTensorProduct(A, a, b, a.T, B), (0, 2, 4, 7, 9)) assert cg.split_multiple_contractions() == ArrayContraction(ArrayTensorProduct(A, DiagMatrix(a), DiagMatrix(b), DiagMatrix(a), B), (0, 2), (3, 4), (5, 7), (6, 9)) assert convert_array_to_matrix(cg).doit() == A.T * DiagMatrix(a) * DiagMatrix(b) * DiagMatrix(a) * B.T cg = ArrayContraction(ArrayTensorProduct(I1, I1, I1), (1, 2, 4)) assert cg.split_multiple_contractions() == ArrayContraction(ArrayTensorProduct(I1, I1, I1), (1, 2), (3, 4)) assert convert_array_to_matrix(cg).doit() == Identity(1) cg = ArrayContraction(ArrayTensorProduct(I, I, I, I, A), (1, 2, 8), (5, 6, 9)) assert convert_array_to_matrix(cg.split_multiple_contractions()).doit() == A cg = ArrayContraction(ArrayTensorProduct(A, a, C, a, B), (1, 2, 4), (5, 6, 8)) expected = ArrayContraction(ArrayTensorProduct(DiagMatrix(a), DiagMatrix(a), C, A, B), (0, 4), (1, 7), (2, 5), (3, 8)) assert cg.split_multiple_contractions() == expected assert convert_array_to_matrix(cg) == A * DiagMatrix(a) * C * DiagMatrix(a) * B cg = ArrayContraction(ArrayTensorProduct(a, I1, b, I1, (a.T*b).applyfunc(cos)), (1, 2, 8), (5, 6, 9)) assert cg.split_multiple_contractions().dummy_eq(ArrayContraction(ArrayTensorProduct((a.T * b).applyfunc(cos), I1, I1, a, b), (0, 2), (1, 4), (3, 7), (5, 9))) assert convert_array_to_matrix(cg).doit().dummy_eq(MatMul(a, (a.T * b).applyfunc(cos), b.T)) def test_arrayexpr_convert_array_contraction_tp_additions(): a = ArrayAdd( ArrayTensorProduct(M, N), ArrayTensorProduct(N, M) ) tp = ArrayTensorProduct(P, a, Q) expr = ArrayContraction(tp, (3, 4)) expected = ArrayTensorProduct( P, ArrayAdd( ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), ArrayContraction(ArrayTensorProduct(N, M), (1, 2)), ), Q ) assert expr == expected assert convert_array_to_matrix(expr) == ArrayTensorProduct(P, M * N + N * M, Q) expr = ArrayContraction(tp, (1, 2), (3, 4), (5, 6)) result = ArrayContraction( ArrayTensorProduct( P, ArrayAdd( ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), ArrayContraction(ArrayTensorProduct(N, M), (1, 2)), ), Q ), (1, 2), (3, 4)) assert expr == result assert convert_array_to_matrix(expr) == P * (M * N + N * M) * Q def test_arrayexpr_convert_array_to_implicit_matmul(): # Trivial dimensions are suppressed, so the result can be expressed in matrix form: cg = ArrayTensorProduct(a, b) assert convert_array_to_matrix(cg) == a * b.T cg = ArrayTensorProduct(a, I, b) assert convert_array_to_matrix(cg) == a * b.T cg = ArrayContraction(ArrayTensorProduct(I, I), (1, 2)) assert convert_array_to_matrix(cg) == I cg = PermuteDims(ArrayTensorProduct(I, Identity(1)), [0, 2, 1, 3]) assert convert_array_to_matrix(cg) == I def test_arrayexpr_convert_array_to_matrix_remove_trivial_dims(): # Tensor Product: assert _remove_trivial_dims(ArrayTensorProduct(a, b)) == (a * b.T, [1, 3]) assert _remove_trivial_dims(ArrayTensorProduct(a.T, b)) == (a * b.T, [0, 3]) assert _remove_trivial_dims(ArrayTensorProduct(a, b.T)) == (a * b.T, [1, 2]) assert _remove_trivial_dims(ArrayTensorProduct(a.T, b.T)) == (a * b.T, [0, 2]) assert _remove_trivial_dims(ArrayTensorProduct(I, a.T, b.T)) == (a * b.T, [0, 1, 2, 4]) assert _remove_trivial_dims(ArrayTensorProduct(a.T, I, b.T)) == (a * b.T, [0, 2, 3, 4]) assert _remove_trivial_dims(ArrayTensorProduct(a, I)) == (a, [2, 3]) assert _remove_trivial_dims(ArrayTensorProduct(I, a)) == (a, [0, 1]) assert _remove_trivial_dims(ArrayTensorProduct(a.T, b.T, c, d)) == ( ArrayTensorProduct(a * b.T, c * d.T), [0, 2, 5, 7]) assert _remove_trivial_dims(ArrayTensorProduct(a.T, I, b.T, c, d, I)) == ( ArrayTensorProduct(a * b.T, c * d.T, I), [0, 2, 3, 4, 7, 9]) # Addition: cg = ArrayAdd(ArrayTensorProduct(a, b), ArrayTensorProduct(c, d)) assert _remove_trivial_dims(cg) == (a * b.T + c * d.T, [1, 3]) # Permute Dims: cg = PermuteDims(ArrayTensorProduct(a, b), Permutation(3)(1, 2)) assert _remove_trivial_dims(cg) == (a * b.T, [2, 3]) cg = PermuteDims(ArrayTensorProduct(a, I, b), Permutation(5)(1, 2, 3, 4)) assert _remove_trivial_dims(cg) == (a * b.T, [1, 2, 4, 5]) cg = PermuteDims(ArrayTensorProduct(I, b, a), Permutation(5)(1, 2, 4, 5, 3)) assert _remove_trivial_dims(cg) == (b * a.T, [0, 3, 4, 5]) # Diagonal: cg = ArrayDiagonal(ArrayTensorProduct(M, a), (1, 2)) assert _remove_trivial_dims(cg) == (cg, []) # Contraction: cg = ArrayContraction(ArrayTensorProduct(M, a), (1, 2)) assert _remove_trivial_dims(cg) == (cg, []) # A few more cases to test the removal and shift of nested removed axes # with array contractions and array diagonals: tp = ArrayTensorProduct( OneMatrix(1, 1), M, x, OneMatrix(1, 1), Identity(1), ) expr = ArrayContraction(tp, (1, 8)) rexpr, removed = _remove_trivial_dims(expr) assert removed == [0, 5, 6, 7] expr = ArrayContraction(tp, (1, 8), (3, 4)) rexpr, removed = _remove_trivial_dims(expr) assert removed == [0, 3, 4, 5] expr = ArrayDiagonal(tp, (1, 8)) rexpr, removed = _remove_trivial_dims(expr) assert removed == [0, 5, 6, 7, 8] expr = ArrayDiagonal(tp, (1, 8), (3, 4)) rexpr, removed = _remove_trivial_dims(expr) assert removed == [0, 3, 4, 5, 6] cg = ArrayDiagonal(ArrayTensorProduct(PermuteDims(ArrayTensorProduct(x, I1), Permutation(1, 2, 3)), (x.T*x).applyfunc(sqrt)), (2, 4), (3, 5)) rexpr, removed = _remove_trivial_dims(cg) assert removed == [1, 2, 3] def test_arrayexpr_convert_array_to_matrix_diag2contraction_diagmatrix(): cg = ArrayDiagonal(ArrayTensorProduct(M, a), (1, 2)) res = _array_diag2contr_diagmatrix(cg) assert res.shape == cg.shape assert res == ArrayContraction(ArrayTensorProduct(M, OneArray(1), DiagMatrix(a)), (1, 3)) raises(ValueError, lambda: ArrayDiagonal(ArrayTensorProduct(a, M), (1, 2))) cg = ArrayDiagonal(ArrayTensorProduct(a.T, M), (1, 2)) res = _array_diag2contr_diagmatrix(cg) assert res.shape == cg.shape assert res == ArrayContraction(ArrayTensorProduct(OneArray(1), M, DiagMatrix(a.T)), (1, 4)) cg = ArrayDiagonal(ArrayTensorProduct(a.T, M, N, b.T), (1, 2), (4, 7)) res = _array_diag2contr_diagmatrix(cg) assert res.shape == cg.shape assert res == ArrayContraction( ArrayTensorProduct(OneArray(1), M, N, OneArray(1), DiagMatrix(a.T), DiagMatrix(b.T)), (1, 7), (3, 9)) cg = ArrayDiagonal(ArrayTensorProduct(a, M, N, b.T), (0, 2), (4, 7)) res = _array_diag2contr_diagmatrix(cg) assert res.shape == cg.shape assert res == ArrayContraction( ArrayTensorProduct(OneArray(1), M, N, OneArray(1), DiagMatrix(a), DiagMatrix(b.T)), (1, 6), (3, 9)) cg = ArrayDiagonal(ArrayTensorProduct(a, M, N, b.T), (0, 4), (3, 7)) res = _array_diag2contr_diagmatrix(cg) assert res.shape == cg.shape assert res == ArrayContraction( ArrayTensorProduct(OneArray(1), M, N, OneArray(1), DiagMatrix(a), DiagMatrix(b.T)), (3, 6), (2, 9)) I1 = Identity(1) x = MatrixSymbol("x", k, 1) A = MatrixSymbol("A", k, k) cg = ArrayDiagonal(ArrayTensorProduct(x, A.T, I1), (0, 2)) assert _array_diag2contr_diagmatrix(cg).shape == cg.shape assert _array2matrix(cg).shape == cg.shape def test_arrayexpr_convert_array_to_matrix_support_function(): assert _support_function_tp1_recognize([], [2 * k]) == 2 * k assert _support_function_tp1_recognize([(1, 2)], [A, 2 * k, B, 3]) == 6 * k * A * B assert _support_function_tp1_recognize([(0, 3), (1, 2)], [A, B]) == Trace(A * B) assert _support_function_tp1_recognize([(1, 2)], [A, B]) == A * B assert _support_function_tp1_recognize([(0, 2)], [A, B]) == A.T * B assert _support_function_tp1_recognize([(1, 3)], [A, B]) == A * B.T assert _support_function_tp1_recognize([(0, 3)], [A, B]) == A.T * B.T assert _support_function_tp1_recognize([(1, 2), (5, 6)], [A, B, C, D]) == ArrayTensorProduct(A * B, C * D) assert _support_function_tp1_recognize([(1, 4), (3, 6)], [A, B, C, D]) == PermuteDims( ArrayTensorProduct(A * C, B * D), [0, 2, 1, 3]) assert _support_function_tp1_recognize([(0, 3), (1, 4)], [A, B, C]) == B * A * C assert _support_function_tp1_recognize([(9, 10), (1, 2), (5, 6), (3, 4), (7, 8)], [X, Y, A, B, C, D]) == X * Y * A * B * C * D assert _support_function_tp1_recognize([(9, 10), (1, 2), (5, 6), (3, 4)], [X, Y, A, B, C, D]) == ArrayTensorProduct(X * Y * A * B, C * D) assert _support_function_tp1_recognize([(1, 7), (3, 8), (4, 11)], [X, Y, A, B, C, D]) == PermuteDims( ArrayTensorProduct(X * B.T, Y * C, A.T * D.T), [0, 2, 4, 1, 3, 5] ) assert _support_function_tp1_recognize([(0, 1), (3, 6), (5, 8)], [X, A, B, C, D]) == PermuteDims( ArrayTensorProduct(Trace(X) * A * C, B * D), [0, 2, 1, 3]) assert _support_function_tp1_recognize([(1, 2), (3, 4), (5, 6), (7, 8)], [A, A, B, C, D]) == A ** 2 * B * C * D assert _support_function_tp1_recognize([(1, 2), (3, 4), (5, 6), (7, 8)], [X, A, B, C, D]) == X * A * B * C * D assert _support_function_tp1_recognize([(1, 6), (3, 8), (5, 10)], [X, Y, A, B, C, D]) == PermuteDims( ArrayTensorProduct(X * B, Y * C, A * D), [0, 2, 4, 1, 3, 5] ) assert _support_function_tp1_recognize([(1, 4), (3, 6)], [A, B, C, D]) == PermuteDims( ArrayTensorProduct(A * C, B * D), [0, 2, 1, 3]) assert _support_function_tp1_recognize([(0, 4), (1, 7), (2, 5), (3, 8)], [X, A, B, C, D]) == C*X.T*B*A*D assert _support_function_tp1_recognize([(0, 4), (1, 7), (2, 5), (3, 8)], [X, A, B, C, D]) == C*X.T*B*A*D
2ff2fceef887a0ee21a66c399a04ae974841eb718446005e6e4e5b94385c4548
import random from sympy import symbols, ImmutableDenseNDimArray, tensorproduct, tensorcontraction, permutedims, MatrixSymbol, \ ZeroMatrix, sin, cos, DiagMatrix from sympy.combinatorics import Permutation from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, ArraySymbol, ArrayElement, \ PermuteDims, ArrayContraction, ArrayTensorProduct, ArrayDiagonal, \ ArrayAdd, nest_permutation, ArrayElementwiseApplyFunc, _EditArrayContraction, _ArgE from sympy.testing.pytest import raises i, j, k, l, m, n = symbols("i j k l m n") M = ArraySymbol("M", k, k) N = ArraySymbol("N", k, k) P = ArraySymbol("P", k, k) Q = ArraySymbol("Q", k, k) A = ArraySymbol("A", k, k) B = ArraySymbol("B", k, k) C = ArraySymbol("C", k, k) D = ArraySymbol("D", k, k) X = ArraySymbol("X", k, k) Y = ArraySymbol("Y", k, k) a = ArraySymbol("a", k, 1) b = ArraySymbol("b", k, 1) c = ArraySymbol("c", k, 1) d = ArraySymbol("d", k, 1) def test_array_symbol_and_element(): A = ArraySymbol("A", 2) A0 = ArrayElement(A, (0,)) A1 = ArrayElement(A, (1,)) assert A.as_explicit() == ImmutableDenseNDimArray([A0, A1]) A2 = tensorproduct(A, A) assert A2.shape == (2, 2) # TODO: not yet supported: # assert A2.as_explicit() == Array([[A[0]*A[0], A[1]*A[0]], [A[0]*A[1], A[1]*A[1]]]) A3 = tensorcontraction(A2, (0, 1)) assert A3.shape == () # TODO: not yet supported: # assert A3.as_explicit() == Array([]) A = ArraySymbol("A", 2, 3, 4) Ae = A.as_explicit() assert Ae == ImmutableDenseNDimArray( [[[ArrayElement(A, (i, j, k)) for k in range(4)] for j in range(3)] for i in range(2)]) p = permutedims(A, Permutation(0, 2, 1)) assert isinstance(p, PermuteDims) def test_zero_array(): assert ZeroArray() == 0 assert ZeroArray().is_Integer za = ZeroArray(3, 2, 4) assert za.shape == (3, 2, 4) za_e = za.as_explicit() assert za_e.shape == (3, 2, 4) m, n, k = symbols("m n k") za = ZeroArray(m, n, k, 2) assert za.shape == (m, n, k, 2) raises(ValueError, lambda: za.as_explicit()) def test_one_array(): assert OneArray() == 1 assert OneArray().is_Integer oa = OneArray(3, 2, 4) assert oa.shape == (3, 2, 4) oa_e = oa.as_explicit() assert oa_e.shape == (3, 2, 4) m, n, k = symbols("m n k") oa = OneArray(m, n, k, 2) assert oa.shape == (m, n, k, 2) raises(ValueError, lambda: oa.as_explicit()) def test_arrayexpr_contraction_construction(): cg = ArrayContraction(A) assert cg == A cg = ArrayContraction(ArrayTensorProduct(A, B), (1, 0)) assert cg == ArrayContraction(ArrayTensorProduct(A, B), (0, 1)) cg = ArrayContraction(ArrayTensorProduct(M, N), (0, 1)) indtup = cg._get_contraction_tuples() assert indtup == [[(0, 0), (0, 1)]] assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(0, 1)] cg = ArrayContraction(ArrayTensorProduct(M, N), (1, 2)) indtup = cg._get_contraction_tuples() assert indtup == [[(0, 1), (1, 0)]] assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(1, 2)] cg = ArrayContraction(ArrayTensorProduct(M, M, N), (1, 4), (2, 5)) indtup = cg._get_contraction_tuples() assert indtup == [[(0, 0), (1, 1)], [(0, 1), (2, 0)]] assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(0, 3), (1, 4)] def test_arrayexpr_array_flatten(): # Flatten nested ArrayTensorProduct objects: expr1 = ArrayTensorProduct(M, N) expr2 = ArrayTensorProduct(P, Q) expr = ArrayTensorProduct(expr1, expr2) assert expr == ArrayTensorProduct(M, N, P, Q) assert expr.args == (M, N, P, Q) # Flatten mixed ArrayTensorProduct and ArrayContraction objects: cg1 = ArrayContraction(expr1, (1, 2)) cg2 = ArrayContraction(expr2, (0, 3)) expr = ArrayTensorProduct(cg1, cg2) assert expr == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (1, 2), (4, 7)) expr = ArrayTensorProduct(M, cg1) assert expr == ArrayContraction(ArrayTensorProduct(M, M, N), (3, 4)) # Flatten nested ArrayContraction objects: cgnested = ArrayContraction(cg1, (0, 1)) assert cgnested == ArrayContraction(ArrayTensorProduct(M, N), (0, 3), (1, 2)) cgnested = ArrayContraction(ArrayTensorProduct(cg1, cg2), (0, 3)) assert cgnested == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 6), (1, 2), (4, 7)) cg3 = ArrayContraction(ArrayTensorProduct(M, N, P, Q), (1, 3), (2, 4)) cgnested = ArrayContraction(cg3, (0, 1)) assert cgnested == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 5), (1, 3), (2, 4)) cgnested = ArrayContraction(cg3, (0, 3), (1, 2)) assert cgnested == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 7), (1, 3), (2, 4), (5, 6)) cg4 = ArrayContraction(ArrayTensorProduct(M, N, P, Q), (1, 5), (3, 7)) cgnested = ArrayContraction(cg4, (0, 1)) assert cgnested == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 2), (1, 5), (3, 7)) cgnested = ArrayContraction(cg4, (0, 1), (2, 3)) assert cgnested == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 2), (1, 5), (3, 7), (4, 6)) cg = ArrayDiagonal(cg4) assert cg == cg4 assert isinstance(cg, type(cg4)) # Flatten nested ArrayDiagonal objects: cg1 = ArrayDiagonal(expr1, (1, 2)) cg2 = ArrayDiagonal(expr2, (0, 3)) cg3 = ArrayDiagonal(ArrayTensorProduct(M, N, P, Q), (1, 3), (2, 4)) cg4 = ArrayDiagonal(ArrayTensorProduct(M, N, P, Q), (1, 5), (3, 7)) cgnested = ArrayDiagonal(cg1, (0, 1)) assert cgnested == ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2), (0, 3)) cgnested = ArrayDiagonal(cg3, (1, 2)) assert cgnested == ArrayDiagonal(ArrayTensorProduct(M, N, P, Q), (1, 3), (2, 4), (5, 6)) cgnested = ArrayDiagonal(cg4, (1, 2)) assert cgnested == ArrayDiagonal(ArrayTensorProduct(M, N, P, Q), (1, 5), (3, 7), (2, 4)) cg = ArrayAdd(M, N) cg2 = ArrayAdd(cg, P) assert isinstance(cg2, ArrayAdd) assert cg2.args == (M, N, P) assert cg2.shape == (k, k) expr = ArrayTensorProduct(ArrayDiagonal(X, (0, 1)), ArrayDiagonal(A, (0, 1))) assert expr == ArrayDiagonal(ArrayTensorProduct(X, A), (0, 1), (2, 3)) expr1 = ArrayDiagonal(ArrayTensorProduct(X, A), (1, 2)) expr2 = ArrayTensorProduct(expr1, a) assert expr2 == PermuteDims(ArrayDiagonal(ArrayTensorProduct(X, A, a), (1, 2)), [0, 1, 3, 4, 2]) expr1 = ArrayContraction(ArrayTensorProduct(X, A), (1, 2)) expr2 = ArrayTensorProduct(expr1, a) assert isinstance(expr2, ArrayContraction) assert isinstance(expr2.expr, ArrayTensorProduct) def test_arrayexpr_array_diagonal(): cg = ArrayDiagonal(M, (1, 0)) assert cg == ArrayDiagonal(M, (0, 1)) cg = ArrayDiagonal(ArrayTensorProduct(M, N, P), (4, 1), (2, 0)) assert cg == ArrayDiagonal(ArrayTensorProduct(M, N, P), (1, 4), (0, 2)) def test_arrayexpr_array_shape(): expr = ArrayTensorProduct(M, N, P, Q) assert expr.shape == (k, k, k, k, k, k, k, k) Z = MatrixSymbol("Z", m, n) expr = ArrayTensorProduct(M, Z) assert expr.shape == (k, k, m, n) expr2 = ArrayContraction(expr, (0, 1)) assert expr2.shape == (m, n) expr2 = ArrayDiagonal(expr, (0, 1)) assert expr2.shape == (m, n, k) exprp = PermuteDims(expr, [2, 1, 3, 0]) assert exprp.shape == (m, k, n, k) expr3 = ArrayTensorProduct(N, Z) expr2 = ArrayAdd(expr, expr3) assert expr2.shape == (k, k, m, n) # Contraction along axes with discordant dimensions: raises(ValueError, lambda: ArrayContraction(expr, (1, 2))) # Also diagonal needs the same dimensions: raises(ValueError, lambda: ArrayDiagonal(expr, (1, 2))) # Diagonal requires at least to axes to compute the diagonal: raises(ValueError, lambda: ArrayDiagonal(expr, (1,))) def test_arrayexpr_permutedims_sink(): cg = PermuteDims(ArrayTensorProduct(M, N), [0, 1, 3, 2], nest_permutation=False) sunk = nest_permutation(cg) assert sunk == ArrayTensorProduct(M, PermuteDims(N, [1, 0])) cg = PermuteDims(ArrayTensorProduct(M, N), [1, 0, 3, 2], nest_permutation=False) sunk = nest_permutation(cg) assert sunk == ArrayTensorProduct(PermuteDims(M, [1, 0]), PermuteDims(N, [1, 0])) cg = PermuteDims(ArrayTensorProduct(M, N), [3, 2, 1, 0], nest_permutation=False) sunk = nest_permutation(cg) assert sunk == ArrayTensorProduct(PermuteDims(N, [1, 0]), PermuteDims(M, [1, 0])) cg = PermuteDims(ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), [1, 0], nest_permutation=False) sunk = nest_permutation(cg) assert sunk == ArrayContraction(PermuteDims(ArrayTensorProduct(M, N), [[0, 3]]), (1, 2)) cg = PermuteDims(ArrayTensorProduct(M, N), [1, 0, 3, 2], nest_permutation=False) sunk = nest_permutation(cg) assert sunk == ArrayTensorProduct(PermuteDims(M, [1, 0]), PermuteDims(N, [1, 0])) cg = PermuteDims(ArrayContraction(ArrayTensorProduct(M, N, P), (1, 2), (3, 4)), [1, 0], nest_permutation=False) sunk = nest_permutation(cg) assert sunk == ArrayContraction(PermuteDims(ArrayTensorProduct(M, N, P), [[0, 5]]), (1, 2), (3, 4)) def test_arrayexpr_push_indices_up_and_down(): indices = list(range(12)) contr_diag_indices = [(0, 6), (2, 8)] assert ArrayContraction._push_indices_down(contr_diag_indices, indices) == (1, 3, 4, 5, 7, 9, 10, 11, 12, 13, 14, 15) assert ArrayContraction._push_indices_up(contr_diag_indices, indices) == (None, 0, None, 1, 2, 3, None, 4, None, 5, 6, 7) assert ArrayDiagonal._push_indices_down(contr_diag_indices, indices, 10) == (1, 3, 4, 5, 7, 9, (0, 6), (2, 8), None, None, None, None) assert ArrayDiagonal._push_indices_up(contr_diag_indices, indices, 10) == (6, 0, 7, 1, 2, 3, 6, 4, 7, 5, None, None) contr_diag_indices = [(1, 2), (7, 8)] assert ArrayContraction._push_indices_down(contr_diag_indices, indices) == (0, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15) assert ArrayContraction._push_indices_up(contr_diag_indices, indices) == (0, None, None, 1, 2, 3, 4, None, None, 5, 6, 7) assert ArrayDiagonal._push_indices_down(contr_diag_indices, indices, 10) == (0, 3, 4, 5, 6, 9, (1, 2), (7, 8), None, None, None, None) assert ArrayDiagonal._push_indices_up(contr_diag_indices, indices, 10) == (0, 6, 6, 1, 2, 3, 4, 7, 7, 5, None, None) def test_arrayexpr_split_multiple_contractions(): a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) A = MatrixSymbol("A", k, k) B = MatrixSymbol("B", k, k) C = MatrixSymbol("C", k, k) X = MatrixSymbol("X", k, k) cg = ArrayContraction(ArrayTensorProduct(A.T, a, b, b.T, (A*X*b).applyfunc(cos)), (1, 2, 8), (5, 6, 9)) assert cg.split_multiple_contractions().dummy_eq(ArrayContraction(ArrayTensorProduct(DiagMatrix(a), (A*X*b).applyfunc(cos), A.T, b, b.T), (0, 2), (1, 5), (3, 7, 8))) # assert recognize_matrix_expression(cg) # Check no overlap of lines: cg = ArrayContraction(ArrayTensorProduct(A, a, C, a, B), (1, 2, 4), (5, 6, 8), (3, 7)) assert cg.split_multiple_contractions() == cg cg = ArrayContraction(ArrayTensorProduct(a, b, A), (0, 2, 4), (1, 3)) assert cg.split_multiple_contractions() == cg def test_arrayexpr_nested_permutations(): cg = PermuteDims(PermuteDims(M, (1, 0)), (1, 0)) assert cg == M times = 3 plist1 = [list(range(6)) for i in range(times)] plist2 = [list(range(6)) for i in range(times)] for i in range(times): random.shuffle(plist1[i]) random.shuffle(plist2[i]) plist1.append([2, 5, 4, 1, 0, 3]) plist2.append([3, 5, 0, 4, 1, 2]) plist1.append([2, 5, 4, 0, 3, 1]) plist2.append([3, 0, 5, 1, 2, 4]) plist1.append([5, 4, 2, 0, 3, 1]) plist2.append([4, 5, 0, 2, 3, 1]) Me = M.subs(k, 3).as_explicit() Ne = N.subs(k, 3).as_explicit() Pe = P.subs(k, 3).as_explicit() cge = tensorproduct(Me, Ne, Pe) for permutation_array1, permutation_array2 in zip(plist1, plist2): p1 = Permutation(permutation_array1) p2 = Permutation(permutation_array2) cg = PermuteDims( PermuteDims( ArrayTensorProduct(M, N, P), p1), p2 ) result = PermuteDims( ArrayTensorProduct(M, N, P), p2*p1 ) assert cg == result # Check that `permutedims` behaves the same way with explicit-component arrays: result1 = permutedims(permutedims(cge, p1), p2) result2 = permutedims(cge, p2*p1) assert result1 == result2 def test_arrayexpr_contraction_permutation_mix(): Me = M.subs(k, 3).as_explicit() Ne = N.subs(k, 3).as_explicit() cg1 = ArrayContraction(PermuteDims(ArrayTensorProduct(M, N), Permutation([0, 2, 1, 3])), (2, 3)) cg2 = ArrayContraction(ArrayTensorProduct(M, N), (1, 3)) assert cg1 == cg2 cge1 = tensorcontraction(permutedims(tensorproduct(Me, Ne), Permutation([0, 2, 1, 3])), (2, 3)) cge2 = tensorcontraction(tensorproduct(Me, Ne), (1, 3)) assert cge1 == cge2 cg1 = PermuteDims(ArrayTensorProduct(M, N), Permutation([0, 1, 3, 2])) cg2 = ArrayTensorProduct(M, PermuteDims(N, Permutation([1, 0]))) assert cg1 == cg2 cg1 = ArrayContraction( PermuteDims( ArrayTensorProduct(M, N, P, Q), Permutation([0, 2, 3, 1, 4, 5, 7, 6])), (1, 2), (3, 5) ) cg2 = ArrayContraction( ArrayTensorProduct(M, N, P, PermuteDims(Q, Permutation([1, 0]))), (1, 5), (2, 3) ) assert cg1 == cg2 cg1 = ArrayContraction( PermuteDims( ArrayTensorProduct(M, N, P, Q), Permutation([1, 0, 4, 6, 2, 7, 5, 3])), (0, 1), (2, 6), (3, 7) ) cg2 = PermuteDims( ArrayContraction( ArrayTensorProduct(M, P, Q, N), (0, 1), (2, 3), (4, 7)), [1, 0] ) assert cg1 == cg2 cg1 = ArrayContraction( PermuteDims( ArrayTensorProduct(M, N, P, Q), Permutation([1, 0, 4, 6, 7, 2, 5, 3])), (0, 1), (2, 6), (3, 7) ) cg2 = PermuteDims( ArrayContraction( ArrayTensorProduct(PermuteDims(M, [1, 0]), N, P, Q), (0, 1), (3, 6), (4, 5) ), Permutation([1, 0]) ) assert cg1 == cg2 def test_arrayexpr_permute_tensor_product(): cg1 = PermuteDims(ArrayTensorProduct(M, N, P, Q), Permutation([2, 3, 1, 0, 5, 4, 6, 7])) cg2 = ArrayTensorProduct(N, PermuteDims(M, [1, 0]), PermuteDims(P, [1, 0]), Q) assert cg1 == cg2 # TODO: reverse operation starting with `PermuteDims` and getting down to `bb`... cg1 = PermuteDims(ArrayTensorProduct(M, N, P, Q), Permutation([2, 3, 4, 5, 0, 1, 6, 7])) cg2 = ArrayTensorProduct(N, P, M, Q) assert cg1 == cg2 cg1 = PermuteDims(ArrayTensorProduct(M, N, P, Q), Permutation([2, 3, 4, 6, 5, 7, 0, 1])) assert cg1.expr == ArrayTensorProduct(N, P, Q, M) assert cg1.permutation == Permutation([0, 1, 2, 4, 3, 5, 6, 7]) cg1 = ArrayContraction( PermuteDims( ArrayTensorProduct(N, Q, Q, M), [2, 1, 5, 4, 0, 3, 6, 7]), [1, 2, 6]) cg2 = PermuteDims(ArrayContraction(ArrayTensorProduct(Q, Q, N, M), (3, 5, 6)), [0, 2, 3, 1, 4]) assert cg1 == cg2 cg1 = ArrayContraction( ArrayContraction( ArrayContraction( ArrayContraction( PermuteDims( ArrayTensorProduct(N, Q, Q, M), [2, 1, 5, 4, 0, 3, 6, 7]), [1, 2, 6]), [1, 3, 4]), [1]), [0]) cg2 = ArrayContraction(ArrayTensorProduct(M, N, Q, Q), (0, 3, 5), (1, 4, 7), (2,), (6,)) assert cg1 == cg2 def test_arrayexpr_normalize_diagonal_permutedims(): tp = ArrayTensorProduct(M, Q, N, P) expr = ArrayDiagonal( PermuteDims(tp, [0, 1, 2, 4, 7, 6, 3, 5]), (2, 4, 5), (6, 7), (0, 3)) result = ArrayDiagonal(tp, (2, 6, 7), (3, 5), (0, 4)) assert expr == result tp = ArrayTensorProduct(M, N, P, Q) expr = ArrayDiagonal(PermuteDims(tp, [0, 5, 2, 4, 1, 6, 3, 7]), (1, 2, 6), (3, 4)) result = ArrayDiagonal(ArrayTensorProduct(M, P, N, Q), (3, 4, 5), (1, 2)) assert expr == result def test_arrayexpr_normalize_diagonal_contraction(): tp = ArrayTensorProduct(M, N, P, Q) expr = ArrayContraction(ArrayDiagonal(tp, (1, 3, 4)), (0, 3)) result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 6)), (0, 2, 3)) assert expr == result expr = ArrayContraction(ArrayDiagonal(tp, (0, 1, 2, 3, 7)), (1, 2, 3)) result = ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 1, 2, 3, 5, 6, 7)) assert expr == result expr = ArrayContraction(ArrayDiagonal(tp, (0, 2, 6, 7)), (1, 2, 3)) result = ArrayDiagonal(ArrayContraction(tp, (3, 4, 5)), (0, 2, 3, 4)) assert expr == result td = ArrayDiagonal(ArrayTensorProduct(M, N, P, Q), (0, 3)) expr = ArrayContraction(td, (2, 1), (0, 4, 6, 5, 3)) result = ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 1, 3, 5, 6, 7), (2, 4)) assert expr == result def test_arrayexpr_array_wrong_permutation_size(): cg = ArrayTensorProduct(M, N) raises(ValueError, lambda: PermuteDims(cg, [1, 0])) raises(ValueError, lambda: PermuteDims(cg, [1, 0, 2, 3, 5, 4])) def test_arrayexpr_nested_array_elementwise_add(): cg = ArrayContraction(ArrayAdd( ArrayTensorProduct(M, N), ArrayTensorProduct(N, M) ), (1, 2)) result = ArrayAdd( ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), ArrayContraction(ArrayTensorProduct(N, M), (1, 2)) ) assert cg == result cg = ArrayDiagonal(ArrayAdd( ArrayTensorProduct(M, N), ArrayTensorProduct(N, M) ), (1, 2)) result = ArrayAdd( ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2)), ArrayDiagonal(ArrayTensorProduct(N, M), (1, 2)) ) assert cg == result def test_arrayexpr_array_expr_zero_array(): za1 = ZeroArray(k, l, m, n) zm1 = ZeroMatrix(m, n) za2 = ZeroArray(k, m, m, n) zm2 = ZeroMatrix(m, m) zm3 = ZeroMatrix(k, k) assert ArrayTensorProduct(M, N, za1) == ZeroArray(k, k, k, k, k, l, m, n) assert ArrayTensorProduct(M, N, zm1) == ZeroArray(k, k, k, k, m, n) assert ArrayContraction(za1, (3,)) == ZeroArray(k, l, m) assert ArrayContraction(zm1, (1,)) == ZeroArray(m) assert ArrayContraction(za2, (1, 2)) == ZeroArray(k, n) assert ArrayContraction(zm2, (0, 1)) == 0 assert ArrayDiagonal(za2, (1, 2)) == ZeroArray(k, n, m) assert ArrayDiagonal(zm2, (0, 1)) == ZeroArray(m) assert PermuteDims(za1, [2, 1, 3, 0]) == ZeroArray(m, l, n, k) assert PermuteDims(zm1, [1, 0]) == ZeroArray(n, m) assert ArrayAdd(za1) == za1 assert ArrayAdd(zm1) == ZeroArray(m, n) tp1 = ArrayTensorProduct(MatrixSymbol("A", k, l), MatrixSymbol("B", m, n)) assert ArrayAdd(tp1, za1) == tp1 tp2 = ArrayTensorProduct(MatrixSymbol("C", k, l), MatrixSymbol("D", m, n)) assert ArrayAdd(tp1, za1, tp2) == ArrayAdd(tp1, tp2) assert ArrayAdd(M, zm3) == M assert ArrayAdd(M, N, zm3) == ArrayAdd(M, N) def test_arrayexpr_array_expr_applyfunc(): A = ArraySymbol("A", 3, k, 2) aaf = ArrayElementwiseApplyFunc(sin, A) assert aaf.shape == (3, k, 2) def test_edit_array_contraction(): cg = ArrayContraction(ArrayTensorProduct(A, B, C, D), (1, 2, 5)) ecg = _EditArrayContraction(cg) assert ecg.to_array_contraction() == cg ecg.args_with_ind[1], ecg.args_with_ind[2] = ecg.args_with_ind[2], ecg.args_with_ind[1] assert ecg.to_array_contraction() == ArrayContraction(ArrayTensorProduct(A, C, B, D), (1, 3, 4)) ci = ecg.get_new_contraction_index() new_arg = _ArgE(X) new_arg.indices = [ci, ci] ecg.args_with_ind.insert(2, new_arg) assert ecg.to_array_contraction() == ArrayContraction(ArrayTensorProduct(A, C, X, B, D), (1, 3, 6), (4, 5)) assert ecg.get_contraction_indices() == [[1, 3, 6], [4, 5]] assert [[tuple(j) for j in i] for i in ecg.get_contraction_indices_to_ind_rel_pos()] == [[(0, 1), (1, 1), (3, 0)], [(2, 0), (2, 1)]] assert [list(i) for i in ecg.get_mapping_for_index(0)] == [[0, 1], [1, 1], [3, 0]] assert [list(i) for i in ecg.get_mapping_for_index(1)] == [[2, 0], [2, 1]] raises(ValueError, lambda: ecg.get_mapping_for_index(2)) ecg.args_with_ind.pop(1) assert ecg.to_array_contraction() == ArrayContraction(ArrayTensorProduct(A, X, B, D), (1, 4), (2, 3)) ecg.args_with_ind[0].indices[1] = ecg.args_with_ind[1].indices[0] ecg.args_with_ind[1].indices[1] = ecg.args_with_ind[2].indices[0] assert ecg.to_array_contraction() == ArrayContraction(ArrayTensorProduct(A, X, B, D), (1, 2), (3, 4)) ecg.insert_after(ecg.args_with_ind[1], _ArgE(C)) assert ecg.to_array_contraction() == ArrayContraction(ArrayTensorProduct(A, X, C, B, D), (1, 2), (3, 6))
8bd0e0810394a1aca1143da09d253381a3b4977132e5f2655982728e90bf78fd
from sympy.matrices.expressions import MatrixExpr from sympy import MatrixBase, Dummy, Lambda, Function, FunctionClass from sympy.core.sympify import sympify, _sympify class ElementwiseApplyFunction(MatrixExpr): r""" Apply function to a matrix elementwise without evaluating. Examples ======== It can be created by calling ``.applyfunc(<function>)`` on a matrix expression: >>> from sympy.matrices.expressions import MatrixSymbol >>> from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction >>> from sympy import exp >>> X = MatrixSymbol("X", 3, 3) >>> X.applyfunc(exp) Lambda(_d, exp(_d)).(X) Otherwise using the class constructor: >>> from sympy import eye >>> expr = ElementwiseApplyFunction(exp, eye(3)) >>> expr Lambda(_d, exp(_d)).(Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]])) >>> expr.doit() Matrix([ [E, 1, 1], [1, E, 1], [1, 1, E]]) Notice the difference with the real mathematical functions: >>> exp(eye(3)) Matrix([ [E, 0, 0], [0, E, 0], [0, 0, E]]) """ def __new__(cls, function, expr): expr = _sympify(expr) if not expr.is_Matrix: raise ValueError("{} must be a matrix instance.".format(expr)) if expr.shape == (1, 1): # Check if the function returns a matrix, in that case, just apply # the function instead of creating an ElementwiseApplyFunc object: ret = function(expr) if isinstance(ret, MatrixExpr): return ret if not isinstance(function, (FunctionClass, Lambda)): d = Dummy('d') function = Lambda(d, function(d)) function = sympify(function) if not isinstance(function, (FunctionClass, Lambda)): raise ValueError( "{} should be compatible with SymPy function classes." .format(function)) if 1 not in function.nargs: raise ValueError( '{} should be able to accept 1 arguments.'.format(function)) if not isinstance(function, Lambda): d = Dummy('d') function = Lambda(d, function(d)) obj = MatrixExpr.__new__(cls, function, expr) return obj @property def function(self): return self.args[0] @property def expr(self): return self.args[1] @property def shape(self): return self.expr.shape def doit(self, **kwargs): deep = kwargs.get("deep", True) expr = self.expr if deep: expr = expr.doit(**kwargs) function = self.function if isinstance(function, Lambda) and function.is_identity: # This is a Lambda containing the identity function. return expr if isinstance(expr, MatrixBase): return expr.applyfunc(self.function) elif isinstance(expr, ElementwiseApplyFunction): return ElementwiseApplyFunction( lambda x: self.function(expr.function(x)), expr.expr ).doit() else: return self def _entry(self, i, j, **kwargs): return self.function(self.expr._entry(i, j, **kwargs)) def _get_function_fdiff(self): d = Dummy("d") function = self.function(d) fdiff = function.diff(d) if isinstance(fdiff, Function): fdiff = type(fdiff) else: fdiff = Lambda(d, fdiff) return fdiff def _eval_derivative(self, x): from sympy import hadamard_product dexpr = self.expr.diff(x) fdiff = self._get_function_fdiff() return hadamard_product( dexpr, ElementwiseApplyFunction(fdiff, self.expr) ) def _eval_derivative_matrix_lines(self, x): from sympy import Identity from sympy.tensor.array.expressions.array_expressions import ArrayContraction from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct from sympy.core.expr import ExprBuilder fdiff = self._get_function_fdiff() lr = self.expr._eval_derivative_matrix_lines(x) ewdiff = ElementwiseApplyFunction(fdiff, self.expr) if 1 in x.shape: # Vector: iscolumn = self.shape[1] == 1 for i in lr: if iscolumn: ptr1 = i.first_pointer ptr2 = Identity(self.shape[1]) else: ptr1 = Identity(self.shape[0]) ptr2 = i.second_pointer subexpr = ExprBuilder( ArrayDiagonal, [ ExprBuilder( ArrayTensorProduct, [ ewdiff, ptr1, ptr2, ] ), (0, 2) if iscolumn else (1, 4) ], validator=ArrayDiagonal._validate ) i._lines = [subexpr] i._first_pointer_parent = subexpr.args[0].args i._first_pointer_index = 1 i._second_pointer_parent = subexpr.args[0].args i._second_pointer_index = 2 else: # Matrix case: for i in lr: ptr1 = i.first_pointer ptr2 = i.second_pointer newptr1 = Identity(ptr1.shape[1]) newptr2 = Identity(ptr2.shape[1]) subexpr = ExprBuilder( ArrayContraction, [ ExprBuilder( ArrayTensorProduct, [ptr1, newptr1, ewdiff, ptr2, newptr2] ), (1, 2, 4), (5, 7, 8), ], validator=ArrayContraction._validate ) i._first_pointer_parent = subexpr.args[0].args i._first_pointer_index = 1 i._second_pointer_parent = subexpr.args[0].args i._second_pointer_index = 4 i._lines = [subexpr] return lr def _eval_transpose(self): from sympy import Transpose return self.func(self.function, Transpose(self.expr).doit())
774bd2591ea72bc3e343d94057c38356c652b5ee82692b22214ebcdad0046722
from sympy.core.sympify import _sympify from sympy.matrices.expressions import MatrixExpr from sympy import S, I, sqrt, exp class DFT(MatrixExpr): r""" Returns a discrete Fourier transform matrix. The matrix is scaled with :math:`\frac{1}{\sqrt{n}}` so that it is unitary. Parameters ========== n : integer or Symbol Size of the transform. Examples ======== >>> from sympy.abc import n >>> from sympy.matrices.expressions.fourier import DFT >>> DFT(3) DFT(3) >>> DFT(3).as_explicit() Matrix([ [sqrt(3)/3, sqrt(3)/3, sqrt(3)/3], [sqrt(3)/3, sqrt(3)*exp(-2*I*pi/3)/3, sqrt(3)*exp(2*I*pi/3)/3], [sqrt(3)/3, sqrt(3)*exp(2*I*pi/3)/3, sqrt(3)*exp(-2*I*pi/3)/3]]) >>> DFT(n).shape (n, n) References ========== .. [1] https://en.wikipedia.org/wiki/DFT_matrix """ def __new__(cls, n): n = _sympify(n) cls._check_dim(n) obj = super().__new__(cls, n) return obj n = property(lambda self: self.args[0]) # type: ignore shape = property(lambda self: (self.n, self.n)) # type: ignore def _entry(self, i, j, **kwargs): w = exp(-2*S.Pi*I/self.n) return w**(i*j) / sqrt(self.n) def _eval_inverse(self): return IDFT(self.n) class IDFT(DFT): r""" Returns an inverse discrete Fourier transform matrix. The matrix is scaled with :math:`\frac{1}{\sqrt{n}}` so that it is unitary. Parameters ========== n : integer or Symbol Size of the transform Examples ======== >>> from sympy.matrices.expressions.fourier import DFT, IDFT >>> IDFT(3) IDFT(3) >>> IDFT(4)*DFT(4) I See Also ======== DFT """ def _entry(self, i, j, **kwargs): w = exp(-2*S.Pi*I/self.n) return w**(-i*j) / sqrt(self.n) def _eval_inverse(self): return DFT(self.n)
9beaebfef3c5f990a010fb48e2082081734b9f6ef63b627e26d628fadb2cc1af
from sympy import Basic, Expr, sympify, S from sympy.matrices.matrices import MatrixBase from sympy.matrices.common import NonSquareMatrixError class Trace(Expr): """Matrix Trace Represents the trace of a matrix expression. Examples ======== >>> from sympy import MatrixSymbol, Trace, eye >>> A = MatrixSymbol('A', 3, 3) >>> Trace(A) Trace(A) >>> Trace(eye(3)) Trace(Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]])) >>> Trace(eye(3)).simplify() 3 """ is_Trace = True is_commutative = True def __new__(cls, mat): mat = sympify(mat) if not mat.is_Matrix: raise TypeError("input to Trace, %s, is not a matrix" % str(mat)) if not mat.is_square: raise NonSquareMatrixError("Trace of a non-square matrix") return Basic.__new__(cls, mat) def _eval_transpose(self): return self def _eval_derivative(self, v): from sympy import Sum from .matexpr import MatrixElement if isinstance(v, MatrixElement): return self.rewrite(Sum).diff(v) expr = self.doit() if isinstance(expr, Trace): # Avoid looping infinitely: raise NotImplementedError return expr._eval_derivative(v) def _eval_derivative_matrix_lines(self, x): from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayContraction from sympy.core.expr import ExprBuilder r = self.args[0]._eval_derivative_matrix_lines(x) for lr in r: if lr.higher == 1: lr.higher = ExprBuilder( ArrayContraction, [ ExprBuilder( ArrayTensorProduct, [ lr._lines[0], lr._lines[1], ] ), (1, 3), ], validator=ArrayContraction._validate ) else: # This is not a matrix line: lr.higher = ExprBuilder( ArrayContraction, [ ExprBuilder( ArrayTensorProduct, [ lr._lines[0], lr._lines[1], lr.higher, ] ), (1, 3), (0, 2) ] ) lr._lines = [S.One, S.One] lr._first_pointer_parent = lr._lines lr._second_pointer_parent = lr._lines lr._first_pointer_index = 0 lr._second_pointer_index = 1 return r @property def arg(self): return self.args[0] def doit(self, **kwargs): if kwargs.get('deep', True): arg = self.arg.doit(**kwargs) try: return arg._eval_trace() except (AttributeError, NotImplementedError): return Trace(arg) else: # _eval_trace would go too deep here if isinstance(self.arg, MatrixBase): return trace(self.arg) else: return Trace(self.arg) def _normalize(self): # Normalization of trace of matrix products. Use transposition and # cyclic properties of traces to make sure the arguments of the matrix # product are sorted and the first argument is not a trasposition. from sympy import MatMul, Transpose, default_sort_key trace_arg = self.arg if isinstance(trace_arg, MatMul): def get_arg_key(x): a = trace_arg.args[x] if isinstance(a, Transpose): a = a.arg return default_sort_key(a) indmin = min(range(len(trace_arg.args)), key=get_arg_key) if isinstance(trace_arg.args[indmin], Transpose): trace_arg = Transpose(trace_arg).doit() indmin = min(range(len(trace_arg.args)), key=lambda x: default_sort_key(trace_arg.args[x])) trace_arg = MatMul.fromiter(trace_arg.args[indmin:] + trace_arg.args[:indmin]) return Trace(trace_arg) return self def _eval_rewrite_as_Sum(self, expr, **kwargs): from sympy import Sum, Dummy i = Dummy('i') return Sum(self.arg[i, i], (i, 0, self.arg.rows-1)).doit() def trace(expr): """Trace of a Matrix. Sum of the diagonal elements. Examples ======== >>> from sympy import trace, Symbol, MatrixSymbol, eye >>> n = Symbol('n') >>> X = MatrixSymbol('X', n, n) # A square matrix >>> trace(2*X) 2*Trace(X) >>> trace(eye(3)) 3 """ return Trace(expr).doit()
521d5661e750b4cd0dce07a27e5945ef3c052ffe45b2d8978632d0741490d861
from sympy import S, I, ask, Q, Abs, simplify, exp, sqrt, Rational from sympy.core.symbol import symbols from sympy.matrices.expressions.fourier import DFT, IDFT from sympy.matrices import det, Matrix, Identity from sympy.testing.pytest import raises def test_dft_creation(): assert DFT(2) assert DFT(0) raises(ValueError, lambda: DFT(-1)) raises(ValueError, lambda: DFT(2.0)) raises(ValueError, lambda: DFT(2 + 1j)) n = symbols('n') assert DFT(n) n = symbols('n', integer=False) raises(ValueError, lambda: DFT(n)) n = symbols('n', negative=True) raises(ValueError, lambda: DFT(n)) def test_dft(): n, i, j = symbols('n i j') assert DFT(4).shape == (4, 4) assert ask(Q.unitary(DFT(4))) assert Abs(simplify(det(Matrix(DFT(4))))) == 1 assert DFT(n)*IDFT(n) == Identity(n) assert DFT(n)[i, j] == exp(-2*S.Pi*I/n)**(i*j) / sqrt(n) def test_dft2(): assert DFT(1).as_explicit() == Matrix([[1]]) assert DFT(2).as_explicit() == 1/sqrt(2)*Matrix([[1,1],[1,-1]]) assert DFT(4).as_explicit() == Matrix([[S.Half, S.Half, S.Half, S.Half], [S.Half, -I/2, Rational(-1,2), I/2], [S.Half, Rational(-1,2), S.Half, Rational(-1,2)], [S.Half, I/2, Rational(-1,2), -I/2]])
1d1bf3d0448f70c12f8e2b8d6d538bb9721e3072da5941a91cadc2cc5b7ed640
from sympy.core.symbol import symbols, Dummy from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction from sympy import Matrix, Lambda, MatrixSymbol, exp, MatMul, sin, simplify from sympy.testing.pytest import raises from sympy.matrices.common import ShapeError X = MatrixSymbol("X", 3, 3) Y = MatrixSymbol("Y", 3, 3) k = symbols("k") Xk = MatrixSymbol("X", k, k) Xd = X.as_explicit() x, y, z, t = symbols("x y z t") def test_applyfunc_matrix(): x = Dummy('x') double = Lambda(x, x**2) expr = ElementwiseApplyFunction(double, Xd) assert isinstance(expr, ElementwiseApplyFunction) assert expr.doit() == Xd.applyfunc(lambda x: x**2) assert expr.shape == (3, 3) assert expr.func(*expr.args) == expr assert simplify(expr) == expr assert expr[0, 0] == double(Xd[0, 0]) expr = ElementwiseApplyFunction(double, X) assert isinstance(expr, ElementwiseApplyFunction) assert isinstance(expr.doit(), ElementwiseApplyFunction) assert expr == X.applyfunc(double) assert expr.func(*expr.args) == expr expr = ElementwiseApplyFunction(exp, X*Y) assert expr.expr == X*Y assert expr.function.dummy_eq(Lambda(x, exp(x))) assert expr.dummy_eq((X*Y).applyfunc(exp)) assert expr.func(*expr.args) == expr assert isinstance(X*expr, MatMul) assert (X*expr).shape == (3, 3) Z = MatrixSymbol("Z", 2, 3) assert (Z*expr).shape == (2, 3) expr = ElementwiseApplyFunction(exp, Z.T)*ElementwiseApplyFunction(exp, Z) assert expr.shape == (3, 3) expr = ElementwiseApplyFunction(exp, Z)*ElementwiseApplyFunction(exp, Z.T) assert expr.shape == (2, 2) raises(ShapeError, lambda: ElementwiseApplyFunction(exp, Z)*ElementwiseApplyFunction(exp, Z)) M = Matrix([[x, y], [z, t]]) expr = ElementwiseApplyFunction(sin, M) assert isinstance(expr, ElementwiseApplyFunction) assert expr.function.dummy_eq(Lambda(x, sin(x))) assert expr.expr == M assert expr.doit() == M.applyfunc(sin) assert expr.doit() == Matrix([[sin(x), sin(y)], [sin(z), sin(t)]]) assert expr.func(*expr.args) == expr expr = ElementwiseApplyFunction(double, Xk) assert expr.doit() == expr assert expr.subs(k, 2).shape == (2, 2) assert (expr*expr).shape == (k, k) M = MatrixSymbol("M", k, t) expr2 = M.T*expr*M assert isinstance(expr2, MatMul) assert expr2.args[1] == expr assert expr2.shape == (t, t) expr3 = expr*M assert expr3.shape == (k, t) raises(ShapeError, lambda: M*expr) expr1 = ElementwiseApplyFunction(lambda x: x+1, Xk) expr2 = ElementwiseApplyFunction(lambda x: x, Xk) assert expr1 != expr2 def test_applyfunc_entry(): af = X.applyfunc(sin) assert af[0, 0] == sin(X[0, 0]) af = Xd.applyfunc(sin) assert af[0, 0] == sin(X[0, 0]) def test_applyfunc_as_explicit(): af = X.applyfunc(sin) assert af.as_explicit() == Matrix([ [sin(X[0, 0]), sin(X[0, 1]), sin(X[0, 2])], [sin(X[1, 0]), sin(X[1, 1]), sin(X[1, 2])], [sin(X[2, 0]), sin(X[2, 1]), sin(X[2, 2])], ]) def test_applyfunc_transpose(): af = Xk.applyfunc(sin) assert af.T.dummy_eq(Xk.T.applyfunc(sin)) def test_applyfunc_shape_11_matrices(): M = MatrixSymbol("M", 1, 1) double = Lambda(x, x*2) expr = M.applyfunc(sin) assert isinstance(expr, ElementwiseApplyFunction) expr = M.applyfunc(double) assert isinstance(expr, MatMul) assert expr == 2*M
59bde399e680cf195b49fd88711d109a51f75114f9a463eb9a1b47389cc3e647
from sympy.core import Lambda, S, symbols from sympy.concrete import Sum from sympy.functions import adjoint, conjugate, transpose from sympy.matrices import eye, Matrix, ShapeError, ImmutableMatrix from sympy.matrices.expressions import ( Adjoint, Identity, FunctionMatrix, MatrixExpr, MatrixSymbol, Trace, ZeroMatrix, trace, MatPow, MatAdd, MatMul ) from sympy.matrices.expressions.special import OneMatrix from sympy.testing.pytest import raises n = symbols('n', integer=True) A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, n) C = MatrixSymbol('C', 3, 4) def test_Trace(): assert isinstance(Trace(A), Trace) assert not isinstance(Trace(A), MatrixExpr) raises(ShapeError, lambda: Trace(C)) assert trace(eye(3)) == 3 assert trace(Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])) == 15 assert adjoint(Trace(A)) == trace(Adjoint(A)) assert conjugate(Trace(A)) == trace(Adjoint(A)) assert transpose(Trace(A)) == Trace(A) A / Trace(A) # Make sure this is possible # Some easy simplifications assert trace(Identity(5)) == 5 assert trace(ZeroMatrix(5, 5)) == 0 assert trace(OneMatrix(1, 1)) == 1 assert trace(OneMatrix(2, 2)) == 2 assert trace(OneMatrix(n, n)) == n assert trace(2*A*B) == 2*Trace(A*B) assert trace(A.T) == trace(A) i, j = symbols('i j') F = FunctionMatrix(3, 3, Lambda((i, j), i + j)) assert trace(F) == (0 + 0) + (1 + 1) + (2 + 2) raises(TypeError, lambda: Trace(S.One)) assert Trace(A).arg is A assert str(trace(A)) == str(Trace(A).doit()) assert Trace(A).is_commutative is True def test_Trace_A_plus_B(): assert trace(A + B) == Trace(A) + Trace(B) assert Trace(A + B).arg == MatAdd(A, B) assert Trace(A + B).doit() == Trace(A) + Trace(B) def test_Trace_MatAdd_doit(): # See issue #9028 X = ImmutableMatrix([[1, 2, 3]]*3) Y = MatrixSymbol('Y', 3, 3) q = MatAdd(X, 2*X, Y, -3*Y) assert Trace(q).arg == q assert Trace(q).doit() == 18 - 2*Trace(Y) def test_Trace_MatPow_doit(): X = Matrix([[1, 2], [3, 4]]) assert Trace(X).doit() == 5 q = MatPow(X, 2) assert Trace(q).arg == q assert Trace(q).doit() == 29 def test_Trace_MutableMatrix_plus(): # See issue #9043 X = Matrix([[1, 2], [3, 4]]) assert Trace(X) + Trace(X) == 2*Trace(X) def test_Trace_doit_deep_False(): X = Matrix([[1, 2], [3, 4]]) q = MatPow(X, 2) assert Trace(q).doit(deep=False).arg == q q = MatAdd(X, 2*X) assert Trace(q).doit(deep=False).arg == q q = MatMul(X, 2*X) assert Trace(q).doit(deep=False).arg == q def test_trace_constant_factor(): # Issue 9052: gave 2*Trace(MatMul(A)) instead of 2*Trace(A) assert trace(2*A) == 2*Trace(A) X = ImmutableMatrix([[1, 2], [3, 4]]) assert trace(MatMul(2, X)) == 10 def test_rewrite(): assert isinstance(trace(A).rewrite(Sum), Sum) def test_trace_normalize(): assert Trace(B*A) != Trace(A*B) assert Trace(B*A)._normalize() == Trace(A*B) assert Trace(B*A.T)._normalize() == Trace(A*B.T)
8e4c3f6a32526779c8c3d18057d5a212ad76b5e21c371c803e7a2c8bc5e17c45
#!/usr/bin/env python """Distutils based setup script for SymPy. This uses Distutils (https://python.org/sigs/distutils-sig/) the standard python mechanism for installing packages. Optionally, you can use Setuptools (https://setuptools.readthedocs.io/en/latest/) to automatically handle dependencies. For the easiest installation just type the command (you'll probably need root privileges for that): python setup.py install This will install the library in the default location. For instructions on how to customize the install procedure read the output of: python setup.py --help install In addition, there are some other commands: python setup.py clean -> will clean all trash (*.pyc and stuff) python setup.py test -> will run the complete test suite python setup.py bench -> will run the complete benchmark suite python setup.py audit -> will run pyflakes checker on source code To get a full list of available commands, read the output of: python setup.py --help-commands Or, if all else fails, feel free to write to the sympy list at [email protected] and ask for help. """ import sys import os import shutil import glob import subprocess from distutils.command.sdist import sdist min_mpmath_version = '0.19' # This directory dir_setup = os.path.dirname(os.path.realpath(__file__)) extra_kwargs = {} try: from setuptools import setup, Command extra_kwargs['zip_safe'] = False extra_kwargs['entry_points'] = { 'console_scripts': [ 'isympy = isympy:main', ] } except ImportError: from distutils.core import setup, Command extra_kwargs['scripts'] = ['bin/isympy'] # handle mpmath deps in the hard way: from sympy.external.importtools import version_tuple try: import mpmath if version_tuple(mpmath.__version__) < version_tuple(min_mpmath_version): raise ImportError except ImportError: print("Please install the mpmath package with a version >= %s" % min_mpmath_version) sys.exit(-1) if sys.version_info < (3, 6): print("SymPy requires Python 3.6 or newer. Python %d.%d detected" % sys.version_info[:2]) sys.exit(-1) # Check that this list is uptodate against the result of the command: # python bin/generate_module_list.py modules = [ 'sympy.algebras', 'sympy.assumptions', 'sympy.assumptions.handlers', 'sympy.assumptions.predicates', 'sympy.assumptions.relation', 'sympy.benchmarks', 'sympy.calculus', 'sympy.categories', 'sympy.codegen', 'sympy.combinatorics', 'sympy.concrete', 'sympy.core', 'sympy.core.benchmarks', 'sympy.crypto', 'sympy.diffgeom', 'sympy.discrete', 'sympy.external', 'sympy.functions', 'sympy.functions.combinatorial', 'sympy.functions.elementary', 'sympy.functions.elementary.benchmarks', 'sympy.functions.special', 'sympy.functions.special.benchmarks', 'sympy.geometry', 'sympy.holonomic', 'sympy.integrals', 'sympy.integrals.benchmarks', 'sympy.integrals.rubi', 'sympy.integrals.rubi.parsetools', 'sympy.integrals.rubi.rubi_tests', 'sympy.integrals.rubi.rules', 'sympy.interactive', 'sympy.liealgebras', 'sympy.logic', 'sympy.logic.algorithms', 'sympy.logic.utilities', 'sympy.matrices', 'sympy.matrices.benchmarks', 'sympy.matrices.expressions', 'sympy.multipledispatch', 'sympy.ntheory', 'sympy.parsing', 'sympy.parsing.autolev', 'sympy.parsing.autolev._antlr', 'sympy.parsing.c', 'sympy.parsing.fortran', 'sympy.parsing.latex', 'sympy.parsing.latex._antlr', 'sympy.physics', 'sympy.physics.continuum_mechanics', 'sympy.physics.control', 'sympy.physics.hep', 'sympy.physics.mechanics', 'sympy.physics.optics', 'sympy.physics.quantum', 'sympy.physics.units', 'sympy.physics.units.definitions', 'sympy.physics.units.systems', 'sympy.physics.vector', 'sympy.plotting', 'sympy.plotting.intervalmath', 'sympy.plotting.pygletplot', 'sympy.polys', 'sympy.polys.agca', 'sympy.polys.benchmarks', 'sympy.polys.domains', 'sympy.polys.matrices', 'sympy.printing', 'sympy.printing.pretty', 'sympy.sandbox', 'sympy.series', 'sympy.series.benchmarks', 'sympy.sets', 'sympy.sets.handlers', 'sympy.simplify', 'sympy.solvers', 'sympy.solvers.benchmarks', 'sympy.solvers.diophantine', 'sympy.solvers.ode', 'sympy.stats', 'sympy.stats.sampling', 'sympy.strategies', 'sympy.strategies.branch', 'sympy.tensor', 'sympy.tensor.array', 'sympy.tensor.array.expressions', 'sympy.testing', 'sympy.unify', 'sympy.utilities', 'sympy.utilities._compilation', 'sympy.utilities.mathml', 'sympy.vector', ] class audit(Command): """Audits SymPy's source code for following issues: - Names which are used but not defined or used before they are defined. - Names which are redefined without having been used. """ description = "Audit SymPy source with PyFlakes" user_options = [] def initialize_options(self): self.all = None def finalize_options(self): pass def run(self): try: import pyflakes.scripts.pyflakes as flakes except ImportError: print("In order to run the audit, you need to have PyFlakes installed.") sys.exit(-1) dirs = (os.path.join(*d) for d in (m.split('.') for m in modules)) warns = 0 for dir in dirs: for filename in os.listdir(dir): if filename.endswith('.py') and filename != '__init__.py': warns += flakes.checkPath(os.path.join(dir, filename)) if warns > 0: print("Audit finished with total %d warnings" % warns) class clean(Command): """Cleans *.pyc and debian trashs, so you should get the same copy as is in the VCS. """ description = "remove build files" user_options = [("all", "a", "the same")] def initialize_options(self): self.all = None def finalize_options(self): pass def run(self): curr_dir = os.getcwd() for root, dirs, files in os.walk(dir_setup): for file in files: if file.endswith('.pyc') and os.path.isfile: os.remove(os.path.join(root, file)) os.chdir(dir_setup) names = ["python-build-stamp-2.4", "MANIFEST", "build", "dist", "doc/_build", "sample.tex"] for f in names: if os.path.isfile(f): os.remove(f) elif os.path.isdir(f): shutil.rmtree(f) for name in glob.glob(os.path.join(dir_setup, "doc", "src", "modules", "physics", "vector", "*.pdf")): if os.path.isfile(name): os.remove(name) os.chdir(curr_dir) class test_sympy(Command): """Runs all tests under the sympy/ folder """ description = "run all tests and doctests; also see bin/test and bin/doctest" user_options = [] # distutils complains if this is not here. def __init__(self, *args): self.args = args[0] # so we can pass it to other classes Command.__init__(self, *args) def initialize_options(self): # distutils wants this pass def finalize_options(self): # this too pass def run(self): from sympy.utilities import runtests runtests.run_all_tests() class run_benchmarks(Command): """Runs all SymPy benchmarks""" description = "run all benchmarks" user_options = [] # distutils complains if this is not here. def __init__(self, *args): self.args = args[0] # so we can pass it to other classes Command.__init__(self, *args) def initialize_options(self): # distutils wants this pass def finalize_options(self): # this too pass # we use py.test like architecture: # # o collector -- collects benchmarks # o runner -- executes benchmarks # o presenter -- displays benchmarks results # # this is done in sympy.utilities.benchmarking on top of py.test def run(self): from sympy.utilities import benchmarking benchmarking.main(['sympy']) class antlr(Command): """Generate code with antlr4""" description = "generate parser code from antlr grammars" user_options = [] # distutils complains if this is not here. def __init__(self, *args): self.args = args[0] # so we can pass it to other classes Command.__init__(self, *args) def initialize_options(self): # distutils wants this pass def finalize_options(self): # this too pass def run(self): from sympy.parsing.latex._build_latex_antlr import build_parser if not build_parser(): sys.exit(-1) class sdist_sympy(sdist): def run(self): # Fetch git commit hash and write down to commit_hash.txt before # shipped in tarball. commit_hash = None commit_hash_filepath = 'doc/commit_hash.txt' try: commit_hash = \ subprocess.check_output(['git', 'rev-parse', 'HEAD']) commit_hash = commit_hash.decode('ascii') commit_hash = commit_hash.rstrip() print('Commit hash found : {}.'.format(commit_hash)) print('Writing it to {}.'.format(commit_hash_filepath)) except: pass if commit_hash: with open(commit_hash_filepath, 'w') as f: f.write(commit_hash) super(sdist_sympy, self).run() try: os.remove(commit_hash_filepath) print( 'Successfully removed temporary file {}.' .format(commit_hash_filepath)) except OSError as e: print("Error deleting %s - %s." % (e.filename, e.strerror)) # Check that this list is uptodate against the result of the command: # python bin/generate_test_list.py tests = [ 'sympy.algebras.tests', 'sympy.assumptions.tests', 'sympy.calculus.tests', 'sympy.categories.tests', 'sympy.codegen.tests', 'sympy.combinatorics.tests', 'sympy.concrete.tests', 'sympy.core.tests', 'sympy.crypto.tests', 'sympy.diffgeom.tests', 'sympy.discrete.tests', 'sympy.external.tests', 'sympy.functions.combinatorial.tests', 'sympy.functions.elementary.tests', 'sympy.functions.special.tests', 'sympy.geometry.tests', 'sympy.holonomic.tests', 'sympy.integrals.rubi.parsetools.tests', 'sympy.integrals.rubi.rubi_tests.tests', 'sympy.integrals.rubi.tests', 'sympy.integrals.tests', 'sympy.interactive.tests', 'sympy.liealgebras.tests', 'sympy.logic.tests', 'sympy.matrices.expressions.tests', 'sympy.matrices.tests', 'sympy.multipledispatch.tests', 'sympy.ntheory.tests', 'sympy.parsing.tests', 'sympy.physics.continuum_mechanics.tests', 'sympy.physics.control.tests', 'sympy.physics.hep.tests', 'sympy.physics.mechanics.tests', 'sympy.physics.optics.tests', 'sympy.physics.quantum.tests', 'sympy.physics.tests', 'sympy.physics.units.tests', 'sympy.physics.vector.tests', 'sympy.plotting.intervalmath.tests', 'sympy.plotting.pygletplot.tests', 'sympy.plotting.tests', 'sympy.polys.agca.tests', 'sympy.polys.domains.tests', 'sympy.polys.matrices.tests', 'sympy.polys.tests', 'sympy.printing.pretty.tests', 'sympy.printing.tests', 'sympy.sandbox.tests', 'sympy.series.tests', 'sympy.sets.tests', 'sympy.simplify.tests', 'sympy.solvers.diophantine.tests', 'sympy.solvers.ode.tests', 'sympy.solvers.tests', 'sympy.stats.sampling.tests', 'sympy.stats.tests', 'sympy.strategies.branch.tests', 'sympy.strategies.tests', 'sympy.tensor.array.expressions.tests', 'sympy.tensor.array.tests', 'sympy.tensor.tests', 'sympy.testing.tests', 'sympy.unify.tests', 'sympy.utilities._compilation.tests', 'sympy.utilities.tests', 'sympy.vector.tests', ] with open(os.path.join(dir_setup, 'sympy', 'release.py')) as f: # Defines __version__ exec(f.read()) if __name__ == '__main__': setup(name='sympy', version=__version__, description='Computer algebra system (CAS) in Python', author='SymPy development team', author_email='[email protected]', license='BSD', keywords="Math CAS", url='https://sympy.org', py_modules=['isympy'], packages=['sympy'] + modules + tests, ext_modules=[], package_data={ 'sympy.utilities.mathml': ['data/*.xsl'], 'sympy.logic.benchmarks': ['input/*.cnf'], 'sympy.parsing.autolev': [ '*.g4', 'test-examples/*.al', 'test-examples/*.py', 'test-examples/pydy-example-repo/*.al', 'test-examples/pydy-example-repo/*.py', 'test-examples/README.txt', ], 'sympy.parsing.latex': ['*.txt', '*.g4'], 'sympy.integrals.rubi.parsetools': ['header.py.txt'], 'sympy.plotting.tests': ['test_region_*.png'], }, data_files=[('share/man/man1', ['doc/man/isympy.1'])], cmdclass={'test': test_sympy, 'bench': run_benchmarks, 'clean': clean, 'audit': audit, 'antlr': antlr, 'sdist': sdist_sympy, }, python_requires='>=3.6', classifiers=[ 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Physics', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], install_requires=[ 'mpmath>=%s' % min_mpmath_version, ], **extra_kwargs )
97edca1aa77b656c8ee3fa51d9361b8c3132c8ea87faff82d96ae303fc2f3166
#!/usr/bin/env python """ Run tests involving symengine These are separate from the other optional dependency tests because they need to be run with the USE_SYMENGINE=1 environment variable set. This script does not set the environment variable by default so that the same tests can be run with and without symengine. Run this as: $ USE_SYMENGINE=1 bin/test_symengine.py """ # Add the local sympy to sys.path (needed for CI) from get_sympy import path_hack path_hack() class TestsFailedError(Exception): pass test_list = [ 'sympy/physics/mechanics', 'sympy/liealgebras', ] print('Testing optional dependencies') # # XXX: The doctests are not tested here but there are many failures when # running them with symengine. # import sympy if not sympy.test(*test_list, verbose=True): raise TestsFailedError('Tests failed')
89e32c873d39e44c1ab105a7a112e66ff7348dc338ad3617c3e6b2993d8b165d
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A tool to generate AUTHORS. We started tracking authors before moving to git, so we have to do some manual rearrangement of the git history authors in order to get the order in AUTHORS. bin/mailmap_update.py should be run before committing the results. """ from __future__ import unicode_literals from __future__ import print_function import codecs import sys import os if sys.version_info < (3, 6): sys.exit("This script requires Python 3.6 or newer") from subprocess import run, PIPE from sympy.external.importtools import version_tuple from collections import OrderedDict def red(text): return "\033[31m%s\033[0m" % text def yellow(text): return "\033[33m%s\033[0m" % text def green(text): return "\033[32m%s\033[0m" % text # put sympy on the path mailmap_update_path = os.path.abspath(__file__) mailmap_update_dir = os.path.dirname(mailmap_update_path) sympy_top = os.path.split(mailmap_update_dir)[0] sympy_dir = os.path.join(sympy_top, 'sympy') if os.path.isdir(sympy_dir): sys.path.insert(0, sympy_top) from sympy.utilities.misc import filldedent # check git version minimal = '1.8.4.2' git_ver = run(['git', '--version'], stdout=PIPE, encoding='utf-8').stdout[12:] if version_tuple(git_ver) < version_tuple(minimal): print(yellow("Please use a git version >= %s" % minimal)) def author_name(line): assert line.count("<") == line.count(">") == 1 assert line.endswith(">") return line.split("<", 1)[0].strip() def move(l, i1, i2, who): x = l.pop(i1) # this will fail if the .mailmap is not right assert who == author_name(x), \ '%s was not found at line %i' % (who, i1) l.insert(i2, x) # find who git knows ahout git_command = ["git", "log", "--topo-order", "--reverse", "--format=%aN <%aE>"] git_people = run(git_command, stdout=PIPE, encoding='utf-8').stdout.strip().split("\n") # remove duplicates, keeping the original order git_people = list(OrderedDict.fromkeys(git_people)) # Do the few changes necessary in order to reproduce AUTHORS: try: move(git_people, 2, 0, 'Ondřej Čertík') move(git_people, 42, 1, 'Fabian Pedregosa') move(git_people, 22, 2, 'Jurjen N.E. Bos') git_people.insert(4, "*Marc-Etienne M.Leveille <[email protected]>") move(git_people, 10, 5, 'Brian Jorgensen') git_people.insert(11, "*Ulrich Hecht <[email protected]>") # this will fail if the .mailmap is not right assert 'Kirill Smelkov' == author_name(git_people.pop(12) ), 'Kirill Smelkov was not found at line 12' move(git_people, 12, 32, 'Sebastian Krämer') move(git_people, 227, 35, 'Case Van Horsen') git_people.insert(43, "*Dan <[email protected]>") move(git_people, 57, 59, 'Aaron Meurer') move(git_people, 58, 57, 'Andrew Docherty') move(git_people, 67, 66, 'Chris Smith') move(git_people, 79, 76, 'Kevin Goodsell') git_people.insert(84, "*Chu-Ching Huang <[email protected]>") move(git_people, 93, 92, 'James Pearson') # this will fail if the .mailmap is not right assert 'Sergey B Kirpichev' == author_name(git_people.pop(226) ), 'Sergey B Kirpichev was not found at line 226.' index = git_people.index( "azure-pipelines[bot] " + "<azure-pipelines[bot]@users.noreply.github.com>") git_people.pop(index) index = git_people.index( "whitesource-bolt-for-github[bot] " + "<whitesource-bolt-for-github[bot]@users.noreply.github.com>") git_people.pop(index) except AssertionError as msg: print(red(msg)) sys.exit(1) # define new lines for the file header = filldedent(""" All people who contributed to SymPy by sending at least a patch or more (in the order of the date of their first contribution), except those who explicitly didn't want to be mentioned. People with a * next to their names are not found in the metadata of the git history. This file is generated automatically by running `./bin/authors_update.py`. """).lstrip() fmt = """There are a total of {authors_count} authors.""" header_extra = fmt.format(authors_count=len(git_people)) lines = header.splitlines() lines.append('') lines.append(header_extra) lines.append('') lines.extend(git_people) # compare to old lines and stop if no changes were made old_lines = codecs.open(os.path.realpath(os.path.join( __file__, os.path.pardir, os.path.pardir, "AUTHORS")), "r", "utf-8").read().splitlines() if old_lines == lines: print(green('No changes made to AUTHORS.')) sys.exit(0) # check for new additions new_authors = [] for i in sorted(set(lines) - set(old_lines)): try: author_name(i) new_authors.append(i) except AssertionError: continue # write the new file with codecs.open(os.path.realpath(os.path.join( __file__, os.path.pardir, os.path.pardir, "AUTHORS")), "w", "utf-8") as fd: fd.write('\n'.join(lines)) fd.write('\n') # warn about additions if new_authors: print(yellow(filldedent(""" The following authors were added to AUTHORS. If mailmap_update.py has already been run and each author appears as desired and is not a duplicate of some other author, then the changes can be committed. Otherwise, see .mailmap for instructions on how to change an author's entry."""))) print() for i in sorted(new_authors, key=lambda x: x.lower()): print('\t%s' % i) else: print(yellow("The AUTHORS file was updated.")) print(red("Changes were made in the authors file")) run(['git', 'diff']) # Show the changes sys.exit(1)
5250bd84e7effce2b00c6d5fa7f098aefd1ac2b15d15d31b656a9f1fcb8c67f1
#!/usr/bin/env python """ Run tests for specific packages that use optional dependencies. The optional dependencies need to be installed before running this. """ # Add the local sympy to sys.path (needed for CI) from get_sympy import path_hack path_hack() class TestsFailedError(Exception): pass print('Testing optional dependencies') import sympy test_list = [ # numpy '*numpy*', 'sympy/core/', 'sympy/matrices/', 'sympy/physics/quantum/', 'sympy/utilities/tests/test_lambdify.py', # scipy '*scipy*', # llvmlite '*llvm*', # aesara '*aesara*', # gmpy 'polys', # autowrap '*autowrap*', # ipython '*ipython*', # antlr, lfortran, clang 'sympy/parsing/', # matchpy '*rubi*', # codegen 'sympy/codegen/', 'sympy/utilities/tests/test_codegen', 'sympy/utilities/_compilation/tests/test_compilation', # cloudpickle 'pickling', # pycosat 'sympy/logic', 'sympy/assumptions', #stats 'sympy/stats', ] blacklist = [ 'sympy/physics/quantum/tests/test_circuitplot.py', ] doctest_list = [ # numpy 'sympy/matrices/', 'sympy/utilities/lambdify.py', # scipy '*scipy*', # llvmlite '*llvm*', # aesara '*aesara*', # gmpy 'polys', # autowrap '*autowrap*', # ipython '*ipython*', # antlr, lfortran, clang 'sympy/parsing/', # matchpy '*rubi*', # codegen 'sympy/codegen/', # pycosat 'sympy/logic', 'sympy/assumptions', #stats 'sympy/stats', ] if not (sympy.test(*test_list, verbose=True, blacklist=blacklist) and sympy.doctest(*doctest_list)): raise TestsFailedError('Tests failed') print('Testing MATPLOTLIB') # Set matplotlib so that it works correctly in headless Travis. We have to do # this here because it doesn't work after the sympy plotting module is # imported. import matplotlib matplotlib.use("Agg") import sympy # Unfortunately, we have to use subprocess=False so that the above will be # applied, so no hash randomization here. if not (sympy.test('sympy/plotting', 'sympy/physics/quantum/tests/test_circuitplot.py', subprocess=False) and sympy.doctest('sympy/plotting', subprocess=False)): raise TestsFailedError('Tests failed')
f8a5fa373c936d909b0ead0ed2104d317f5b15475b46233185c99f0fdc0deb52
#!/usr/bin/env python """ Run tests involving tensorflow These are separate from the other optional dependency tests because tensorflow pins the numpy version. """ # Add the local sympy to sys.path (needed for CI) from get_sympy import path_hack path_hack() class TestsFailedError(Exception): pass test_list = doctest_list = [ 'sympy/printing/tensorflow.py', 'sympy/printing/tests/test_tensorflow.py', 'sympy/stats/sampling', 'sympy/utilities/lambdify.py', 'sympy/utilities/tests/test_lambdify.py', ] print('Testing optional dependencies') import sympy if not (sympy.test(*test_list, verbose=True) and sympy.doctest(*doctest_list)): raise TestsFailedError('Tests failed')
41e7929e49e1f49ae5e44c0d230a162d589b758cd0bf6d7ab5edd8ab45c6b057
#!/usr/bin/env python """ A tool to help keep .mailmap up-to-date with the current git authors. See also bin/authors_update.py """ import codecs import sys import os if sys.version_info < (3, 6): sys.exit("This script requires Python 3.6 or newer") from subprocess import run, PIPE from sympy.external.importtools import version_tuple from collections import defaultdict, OrderedDict def red(text): return "\033[31m%s\033[0m" % text def yellow(text): return "\033[33m%s\033[0m" % text def blue(text): return "\033[34m%s\033[0m" % text # put sympy on the path mailmap_update_path = os.path.abspath(__file__) mailmap_update_dir = os.path.dirname(mailmap_update_path) sympy_top = os.path.split(mailmap_update_dir)[0] sympy_dir = os.path.join(sympy_top, 'sympy') if os.path.isdir(sympy_dir): sys.path.insert(0, sympy_top) from sympy.utilities.misc import filldedent from sympy.utilities.iterables import sift # check git version minimal = '1.8.4.2' git_ver = run(['git', '--version'], stdout=PIPE, encoding='utf-8').stdout[12:] if version_tuple(git_ver) < version_tuple(minimal): print(yellow("Please use a git version >= %s" % minimal)) def author_name(line): assert line.count("<") == line.count(">") == 1 assert line.endswith(">") return line.split("<", 1)[0].strip() def author_email(line): assert line.count("<") == line.count(">") == 1 assert line.endswith(">") return line.split("<", 1)[1][:-1].strip() sysexit = 0 print(blue("checking git authors...")) # read git authors git_command = ['git', 'log', '--format=%aN <%aE>'] git_people = sorted(set(run(git_command, stdout=PIPE, encoding='utf-8').stdout.strip().split("\n"))) # check for ambiguous emails dups = defaultdict(list) near_dups = defaultdict(list) for i in git_people: k = i.split('<')[1] dups[k].append(i) near_dups[k.lower()].append((k, i)) multi = [k for k in dups if len(dups[k]) > 1] if multi: print() print(red(filldedent(""" Ambiguous email address error: each address should refer to a single author. Disambiguate the following in .mailmap. Then re-run this script."""))) for k in multi: print() for e in sorted(dups[k]): print('\t%s' % e) sysexit = 1 # warn for nearly ambiguous email addresses dups = near_dups # some may have been real dups, so disregard those # for which all email addresses were the same multi = [k for k in dups if len(dups[k]) > 1 and len(set([i for i, _ in dups[k]])) > 1] if multi: # not fatal but make it red print() print(red(filldedent(""" Ambiguous email address warning: git treats the following as distinct but .mailmap will treat them the same. If these are not all the same person then, when making an entry in .mailmap, be sure to include both commit name and address (not just the address)."""))) for k in multi: print() for _, e in sorted(dups[k]): print('\t%s' % e) sysexit = 1 # warn for ambiguous names dups = defaultdict(list) for i in git_people: dups[author_name(i)].append(i) multi = [k for k in dups if len(dups[k]) > 1] if multi: print() print(yellow(filldedent(""" Ambiguous name warning: if a person uses more than one email address, entries should be added to .mailmap to merge them into a single canonical address. Then re-run this script. """))) for k in multi: print() for e in sorted(dups[k]): print('\t%s' % e) sysexit = 1 bad_names = [] bad_emails = [] for i in git_people: name = author_name(i) email = author_email(i) if '@' in name: bad_names.append(i) elif '@' not in email: bad_emails.append(i) if bad_names: print() print(yellow(filldedent(""" The following people appear to have an email address listed for their name. Entries should be added to .mailmap so that names are formatted like "Name <email address>". """))) for i in bad_names: print("\t%s" % i) sysexit = 1 # TODO: Should we check for bad emails as well? Some people have empty email # addresses. The above check seems to catch people who get the name and email # backwards, so let's leave this alone for now. # if bad_emails: # print() # print(yellow(filldedent(""" # The following names do not appear to have valid # emails. Entries should be added to .mailmap that # use a proper email address. If there is no email # address for a person, use "[email protected]". # """))) # for i in bad_emails: # print("\t%s" % i) print() print(blue("checking .mailmap...")) # put entries in order -- this will help the user # to see if there are already existing entries for an author file = codecs.open(os.path.realpath(os.path.join( __file__, os.path.pardir, os.path.pardir, ".mailmap")), "r", "utf-8").read() blankline = not file or file.endswith('\n') lines = file.splitlines() def key(line): # return lower case first address on line or # raise an error if not an entry if '#' in line: line = line.split('#')[0] L, R = line.count("<"), line.count(">") assert L == R and L in (1, 2) return line.split(">", 1)[0].split("<")[1].lower() who = OrderedDict() for i, line in enumerate(lines): try: who.setdefault(key(line), []).append(line) except AssertionError: who[i] = [line] out = [] for k in who: # put long entries before short since if they match, the # short entries will be ignored. The ORDER MATTERS # so don't re-order the lines for a given address. # Other tidying up could be done but we won't do that here. def short_entry(line): if line.count('<') == 2: if line.split('>', 1)[1].split('<')[0].strip(): return False return True if len(who[k]) == 1: line = who[k][0] if not line.strip(): continue # ignore blank lines out.append(line) else: uniq = list(OrderedDict.fromkeys(who[k])) short, long = sift(uniq, short_entry, binary=True) out.extend(long) out.extend(short) if out != lines or not blankline: # write lines with codecs.open(os.path.realpath(os.path.join( __file__, os.path.pardir, os.path.pardir, ".mailmap")), "w", "utf-8") as fd: fd.write('\n'.join(out)) fd.write('\n') print() if out != lines: print(yellow('.mailmap lines were re-ordered.')) else: print(yellow('blank line added to end of .mailmap')) sysexit = 1 sys.exit(sysexit)
3ce3da865cccfcd52e47fc8b1e568d5135cab2ff6e2f7dd7e1c42eabc5fa04c2
""" SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python. It depends on mpmath, and other external libraries may be optionally for things like plotting support. See the webpage for more information and documentation: https://sympy.org """ import sys if sys.version_info < (3, 6): raise ImportError("Python version 3.6 or above is required for SymPy.") del sys try: import mpmath except ImportError: raise ImportError("SymPy now depends on mpmath as an external library. " "See https://docs.sympy.org/latest/install.html#mpmath for more information.") del mpmath from sympy.release import __version__ if 'dev' in __version__: def enable_warnings(): import warnings warnings.filterwarnings('default', '.*', DeprecationWarning, module='sympy.*') del warnings enable_warnings() del enable_warnings def __sympy_debug(): # helper function so we don't import os globally import os debug_str = os.getenv('SYMPY_DEBUG', 'False') if debug_str in ('True', 'False'): return eval(debug_str) else: raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" % debug_str) SYMPY_DEBUG = __sympy_debug() # type: bool from .core import (sympify, SympifyError, cacheit, Basic, Atom, preorder_traversal, S, Expr, AtomicExpr, UnevaluatedExpr, Symbol, Wild, Dummy, symbols, var, Number, Float, Rational, Integer, NumberSymbol, RealNumber, igcd, ilcm, seterr, E, I, nan, oo, pi, zoo, AlgebraicNumber, comp, mod_inverse, Pow, integer_nthroot, integer_log, Mul, prod, Add, Mod, Rel, Eq, Ne, Lt, Le, Gt, Ge, Equality, GreaterThan, LessThan, Unequality, StrictGreaterThan, StrictLessThan, vectorize, Lambda, WildFunction, Derivative, diff, FunctionClass, Function, Subs, expand, PoleError, count_ops, expand_mul, expand_log, expand_func, expand_trig, expand_complex, expand_multinomial, nfloat, expand_power_base, expand_power_exp, arity, PrecisionExhausted, N, evalf, Tuple, Dict, gcd_terms, factor_terms, factor_nc, evaluate, Catalan, EulerGamma, GoldenRatio, TribonacciConstant) from .logic import (to_cnf, to_dnf, to_nnf, And, Or, Not, Xor, Nand, Nor, Implies, Equivalent, ITE, POSform, SOPform, simplify_logic, bool_map, true, false, satisfiable) from .assumptions import (AppliedPredicate, Predicate, AssumptionsContext, assuming, Q, ask, register_handler, remove_handler, refine) from .polys import (Poly, PurePoly, poly_from_expr, parallel_poly_from_expr, degree, total_degree, degree_list, LC, LM, LT, pdiv, prem, pquo, pexquo, div, rem, quo, exquo, half_gcdex, gcdex, invert, subresultants, resultant, discriminant, cofactors, gcd_list, gcd, lcm_list, lcm, terms_gcd, trunc, monic, content, primitive, compose, decompose, sturm, gff_list, gff, sqf_norm, sqf_part, sqf_list, sqf, factor_list, factor, intervals, refine_root, count_roots, real_roots, nroots, ground_roots, nth_power_roots_poly, cancel, reduced, groebner, is_zero_dimensional, GroebnerBasis, poly, symmetrize, horner, interpolate, rational_interpolate, viete, together, BasePolynomialError, ExactQuotientFailed, PolynomialDivisionFailed, OperationNotSupported, HeuristicGCDFailed, HomomorphismFailed, IsomorphismFailed, ExtraneousFactors, EvaluationFailed, RefinementFailed, CoercionFailed, NotInvertible, NotReversible, NotAlgebraic, DomainError, PolynomialError, UnificationFailed, GeneratorsError, GeneratorsNeeded, ComputationFailed, UnivariatePolynomialError, MultivariatePolynomialError, PolificationFailed, OptionError, FlagError, minpoly, minimal_polynomial, primitive_element, field_isomorphism, to_number_field, isolate, itermonomials, Monomial, lex, grlex, grevlex, ilex, igrlex, igrevlex, CRootOf, rootof, RootOf, ComplexRootOf, RootSum, roots, Domain, FiniteField, IntegerRing, RationalField, RealField, ComplexField, PythonFiniteField, GMPYFiniteField, PythonIntegerRing, GMPYIntegerRing, PythonRational, GMPYRationalField, AlgebraicField, PolynomialRing, FractionField, ExpressionDomain, FF_python, FF_gmpy, ZZ_python, ZZ_gmpy, QQ_python, QQ_gmpy, GF, FF, ZZ, QQ, ZZ_I, QQ_I, RR, CC, EX, EXRAW, construct_domain, swinnerton_dyer_poly, cyclotomic_poly, symmetric_poly, random_poly, interpolating_poly, jacobi_poly, chebyshevt_poly, chebyshevu_poly, hermite_poly, legendre_poly, laguerre_poly, apart, apart_list, assemble_partfrac_list, Options, ring, xring, vring, sring, field, xfield, vfield, sfield) from .series import (Order, O, limit, Limit, gruntz, series, approximants, residue, EmptySequence, SeqPer, SeqFormula, sequence, SeqAdd, SeqMul, fourier_series, fps, difference_delta, limit_seq) from .functions import (factorial, factorial2, rf, ff, binomial, RisingFactorial, FallingFactorial, subfactorial, carmichael, fibonacci, lucas, motzkin, tribonacci, harmonic, bernoulli, bell, euler, catalan, genocchi, partition, sqrt, root, Min, Max, Id, real_root, cbrt, re, im, sign, Abs, conjugate, arg, polar_lift, periodic_argument, unbranched_argument, principal_branch, transpose, adjoint, polarify, unpolarify, sin, cos, tan, sec, csc, cot, sinc, asin, acos, atan, asec, acsc, acot, atan2, exp_polar, exp, ln, log, LambertW, sinh, cosh, tanh, coth, sech, csch, asinh, acosh, atanh, acoth, asech, acsch, floor, ceiling, frac, Piecewise, piecewise_fold, erf, erfc, erfi, erf2, erfinv, erfcinv, erf2inv, Ei, expint, E1, li, Li, Si, Ci, Shi, Chi, fresnels, fresnelc, gamma, lowergamma, uppergamma, polygamma, loggamma, digamma, trigamma, multigamma, dirichlet_eta, zeta, lerchphi, polylog, stieltjes, Eijk, LeviCivita, KroneckerDelta, SingularityFunction, DiracDelta, Heaviside, bspline_basis, bspline_basis_set, interpolating_spline, besselj, bessely, besseli, besselk, hankel1, hankel2, jn, yn, jn_zeros, hn1, hn2, airyai, airybi, airyaiprime, airybiprime, marcumq, hyper, meijerg, appellf1, legendre, assoc_legendre, hermite, chebyshevt, chebyshevu, chebyshevu_root, chebyshevt_root, laguerre, assoc_laguerre, gegenbauer, jacobi, jacobi_normalized, Ynm, Ynm_c, Znm, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, beta, mathieus, mathieuc, mathieusprime, mathieucprime, riemann_xi, betainc, betainc_regularized) from .ntheory import (nextprime, prevprime, prime, primepi, primerange, randprime, Sieve, sieve, primorial, cycle_length, composite, compositepi, isprime, divisors, proper_divisors, factorint, multiplicity, perfect_power, pollard_pm1, pollard_rho, primefactors, totient, trailing, divisor_count, proper_divisor_count, divisor_sigma, factorrat, reduced_totient, primenu, primeomega, mersenne_prime_exponent, is_perfect, is_mersenne_prime, is_abundant, is_deficient, is_amicable, abundance, npartitions, is_primitive_root, is_quad_residue, legendre_symbol, jacobi_symbol, n_order, sqrt_mod, quadratic_residues, primitive_root, nthroot_mod, is_nthpow_residue, sqrt_mod_iter, mobius, discrete_log, quadratic_congruence, binomial_coefficients, binomial_coefficients_list, multinomial_coefficients, continued_fraction_periodic, continued_fraction_iterator, continued_fraction_reduce, continued_fraction_convergents, continued_fraction, egyptian_fraction) from .concrete import product, Product, summation, Sum from .discrete import (fft, ifft, ntt, intt, fwht, ifwht, mobius_transform, inverse_mobius_transform, convolution, covering_product, intersecting_product) from .simplify import (simplify, hypersimp, hypersimilar, logcombine, separatevars, posify, besselsimp, kroneckersimp, signsimp, bottom_up, nsimplify, FU, fu, sqrtdenest, cse, use, epath, EPath, hyperexpand, collect, rcollect, radsimp, collect_const, fraction, numer, denom, trigsimp, exptrigsimp, powsimp, powdenest, combsimp, gammasimp, ratsimp, ratsimpmodprime) from .sets import (Set, Interval, Union, EmptySet, FiniteSet, ProductSet, Intersection, DisjointUnion, imageset, Complement, SymmetricDifference, ImageSet, Range, ComplexRegion, Reals, Contains, ConditionSet, Ordinal, OmegaPower, ord0, PowerSet, Naturals, Naturals0, UniversalSet, Integers, Rationals) from .solvers import (solve, solve_linear_system, solve_linear_system_LU, solve_undetermined_coeffs, nsolve, solve_linear, checksol, det_quick, inv_quick, check_assumptions, failing_assumptions, diophantine, rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper, checkodesol, classify_ode, dsolve, homogeneous_order, solve_poly_system, solve_triangulated, pde_separate, pde_separate_add, pde_separate_mul, pdsolve, classify_pde, checkpdesol, ode_order, reduce_inequalities, reduce_abs_inequality, reduce_abs_inequalities, solve_poly_inequality, solve_rational_inequalities, solve_univariate_inequality, decompogen, solveset, linsolve, linear_eq_to_matrix, nonlinsolve, substitution, Complexes) from .matrices import (ShapeError, NonSquareMatrixError, GramSchmidt, casoratian, diag, eye, hessian, jordan_cell, list2numpy, matrix2numpy, matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2, rot_axis3, symarray, wronskian, zeros, MutableDenseMatrix, DeferredVector, MatrixBase, Matrix, MutableMatrix, MutableSparseMatrix, banded, ImmutableDenseMatrix, ImmutableSparseMatrix, ImmutableMatrix, SparseMatrix, MatrixSlice, BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity, Inverse, MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace, Transpose, ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols, Adjoint, hadamard_product, HadamardProduct, HadamardPower, Determinant, det, diagonalize_vector, DiagMatrix, DiagonalMatrix, DiagonalOf, trace, DotProduct, kronecker_product, KroneckerProduct, PermutationMatrix, MatrixPermute, Permanent, per) from .geometry import (Point, Point2D, Point3D, Line, Ray, Segment, Line2D, Segment2D, Ray2D, Line3D, Segment3D, Ray3D, Plane, Ellipse, Circle, Polygon, RegularPolygon, Triangle, rad, deg, are_similar, centroid, convex_hull, idiff, intersection, closest_points, farthest_points, GeometryError, Curve, Parabola) from .utilities import (flatten, group, take, subsets, variations, numbered_symbols, cartes, capture, dict_merge, postorder_traversal, interactive_traversal, prefixes, postfixes, sift, topological_sort, unflatten, has_dups, has_variety, reshape, default_sort_key, ordered, rotations, filldedent, lambdify, source, threaded, xthreaded, public, memoize_property, timed) from .integrals import (integrate, Integral, line_integrate, mellin_transform, inverse_mellin_transform, MellinTransform, InverseMellinTransform, laplace_transform, inverse_laplace_transform, LaplaceTransform, InverseLaplaceTransform, fourier_transform, inverse_fourier_transform, FourierTransform, InverseFourierTransform, sine_transform, inverse_sine_transform, SineTransform, InverseSineTransform, cosine_transform, inverse_cosine_transform, CosineTransform, InverseCosineTransform, hankel_transform, inverse_hankel_transform, HankelTransform, InverseHankelTransform, singularityintegrate) from .tensor import (IndexedBase, Idx, Indexed, get_contraction_structure, get_indices, shape, MutableDenseNDimArray, ImmutableDenseNDimArray, MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray, tensorproduct, tensorcontraction, tensordiagonal, derive_by_array, permutedims, Array, DenseNDimArray, SparseNDimArray) from .parsing import parse_expr from .calculus import (euler_equations, singularities, is_increasing, is_strictly_increasing, is_decreasing, is_strictly_decreasing, is_monotonic, finite_diff_weights, apply_finite_diff, as_finite_diff, differentiate_finite, periodicity, not_empty_in, AccumBounds, is_convex, stationary_points, minimum, maximum) from .algebras import Quaternion from .printing import (pager_print, pretty, pretty_print, pprint, pprint_use_unicode, pprint_try_use_unicode, latex, print_latex, multiline_latex, mathml, print_mathml, python, print_python, pycode, ccode, print_ccode, glsl_code, print_glsl, cxxcode, fcode, print_fcode, rcode, print_rcode, jscode, print_jscode, julia_code, mathematica_code, octave_code, rust_code, print_gtk, preview, srepr, print_tree, StrPrinter, sstr, sstrrepr, TableForm, dotprint, maple_code, print_maple_code) from .testing import test, doctest # This module causes conflicts with other modules: # from .stats import * # Adds about .04-.05 seconds of import time # from combinatorics import * # This module is slow to import: #from physics import units from .plotting import plot, textplot, plot_backends, plot_implicit, plot_parametric from .interactive import init_session, init_printing evalf._create_evalf_table() __all__ = [ # sympy.core 'sympify', 'SympifyError', 'cacheit', 'Basic', 'Atom', 'preorder_traversal', 'S', 'Expr', 'AtomicExpr', 'UnevaluatedExpr', 'Symbol', 'Wild', 'Dummy', 'symbols', 'var', 'Number', 'Float', 'Rational', 'Integer', 'NumberSymbol', 'RealNumber', 'igcd', 'ilcm', 'seterr', 'E', 'I', 'nan', 'oo', 'pi', 'zoo', 'AlgebraicNumber', 'comp', 'mod_inverse', 'Pow', 'integer_nthroot', 'integer_log', 'Mul', 'prod', 'Add', 'Mod', 'Rel', 'Eq', 'Ne', 'Lt', 'Le', 'Gt', 'Ge', 'Equality', 'GreaterThan', 'LessThan', 'Unequality', 'StrictGreaterThan', 'StrictLessThan', 'vectorize', 'Lambda', 'WildFunction', 'Derivative', 'diff', 'FunctionClass', 'Function', 'Subs', 'expand', 'PoleError', 'count_ops', 'expand_mul', 'expand_log', 'expand_func', 'expand_trig', 'expand_complex', 'expand_multinomial', 'nfloat', 'expand_power_base', 'expand_power_exp', 'arity', 'PrecisionExhausted', 'N', 'evalf', 'Tuple', 'Dict', 'gcd_terms', 'factor_terms', 'factor_nc', 'evaluate', 'Catalan', 'EulerGamma', 'GoldenRatio', 'TribonacciConstant', # sympy.logic 'to_cnf', 'to_dnf', 'to_nnf', 'And', 'Or', 'Not', 'Xor', 'Nand', 'Nor', 'Implies', 'Equivalent', 'ITE', 'POSform', 'SOPform', 'simplify_logic', 'bool_map', 'true', 'false', 'satisfiable', # sympy.assumptions 'AppliedPredicate', 'Predicate', 'AssumptionsContext', 'assuming', 'Q', 'ask', 'register_handler', 'remove_handler', 'refine', # sympy.polys 'Poly', 'PurePoly', 'poly_from_expr', 'parallel_poly_from_expr', 'degree', 'total_degree', 'degree_list', 'LC', 'LM', 'LT', 'pdiv', 'prem', 'pquo', 'pexquo', 'div', 'rem', 'quo', 'exquo', 'half_gcdex', 'gcdex', 'invert', 'subresultants', 'resultant', 'discriminant', 'cofactors', 'gcd_list', 'gcd', 'lcm_list', 'lcm', 'terms_gcd', 'trunc', 'monic', 'content', 'primitive', 'compose', 'decompose', 'sturm', 'gff_list', 'gff', 'sqf_norm', 'sqf_part', 'sqf_list', 'sqf', 'factor_list', 'factor', 'intervals', 'refine_root', 'count_roots', 'real_roots', 'nroots', 'ground_roots', 'nth_power_roots_poly', 'cancel', 'reduced', 'groebner', 'is_zero_dimensional', 'GroebnerBasis', 'poly', 'symmetrize', 'horner', 'interpolate', 'rational_interpolate', 'viete', 'together', 'BasePolynomialError', 'ExactQuotientFailed', 'PolynomialDivisionFailed', 'OperationNotSupported', 'HeuristicGCDFailed', 'HomomorphismFailed', 'IsomorphismFailed', 'ExtraneousFactors', 'EvaluationFailed', 'RefinementFailed', 'CoercionFailed', 'NotInvertible', 'NotReversible', 'NotAlgebraic', 'DomainError', 'PolynomialError', 'UnificationFailed', 'GeneratorsError', 'GeneratorsNeeded', 'ComputationFailed', 'UnivariatePolynomialError', 'MultivariatePolynomialError', 'PolificationFailed', 'OptionError', 'FlagError', 'minpoly', 'minimal_polynomial', 'primitive_element', 'field_isomorphism', 'to_number_field', 'isolate', 'itermonomials', 'Monomial', 'lex', 'grlex', 'grevlex', 'ilex', 'igrlex', 'igrevlex', 'CRootOf', 'rootof', 'RootOf', 'ComplexRootOf', 'RootSum', 'roots', 'Domain', 'FiniteField', 'IntegerRing', 'RationalField', 'RealField', 'ComplexField', 'PythonFiniteField', 'GMPYFiniteField', 'PythonIntegerRing', 'GMPYIntegerRing', 'PythonRational', 'GMPYRationalField', 'AlgebraicField', 'PolynomialRing', 'FractionField', 'ExpressionDomain', 'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy', 'QQ_python', 'QQ_gmpy', 'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', 'CC', 'EX', 'EXRAW', 'construct_domain', 'swinnerton_dyer_poly', 'cyclotomic_poly', 'symmetric_poly', 'random_poly', 'interpolating_poly', 'jacobi_poly', 'chebyshevt_poly', 'chebyshevu_poly', 'hermite_poly', 'legendre_poly', 'laguerre_poly', 'apart', 'apart_list', 'assemble_partfrac_list', 'Options', 'ring', 'xring', 'vring', 'sring', 'field', 'xfield', 'vfield', 'sfield', # sympy.series 'Order', 'O', 'limit', 'Limit', 'gruntz', 'series', 'approximants', 'residue', 'EmptySequence', 'SeqPer', 'SeqFormula', 'sequence', 'SeqAdd', 'SeqMul', 'fourier_series', 'fps', 'difference_delta', 'limit_seq', # sympy.functions 'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial', 'FallingFactorial', 'subfactorial', 'carmichael', 'fibonacci', 'lucas', 'motzkin', 'tribonacci', 'harmonic', 'bernoulli', 'bell', 'euler', 'catalan', 'genocchi', 'partition', 'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root', 'cbrt', 're', 'im', 'sign', 'Abs', 'conjugate', 'arg', 'polar_lift', 'periodic_argument', 'unbranched_argument', 'principal_branch', 'transpose', 'adjoint', 'polarify', 'unpolarify', 'sin', 'cos', 'tan', 'sec', 'csc', 'cot', 'sinc', 'asin', 'acos', 'atan', 'asec', 'acsc', 'acot', 'atan2', 'exp_polar', 'exp', 'ln', 'log', 'LambertW', 'sinh', 'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh', 'acoth', 'asech', 'acsch', 'floor', 'ceiling', 'frac', 'Piecewise', 'piecewise_fold', 'erf', 'erfc', 'erfi', 'erf2', 'erfinv', 'erfcinv', 'erf2inv', 'Ei', 'expint', 'E1', 'li', 'Li', 'Si', 'Ci', 'Shi', 'Chi', 'fresnels', 'fresnelc', 'gamma', 'lowergamma', 'uppergamma', 'polygamma', 'loggamma', 'digamma', 'trigamma', 'multigamma', 'dirichlet_eta', 'zeta', 'lerchphi', 'polylog', 'stieltjes', 'Eijk', 'LeviCivita', 'KroneckerDelta', 'SingularityFunction', 'DiracDelta', 'Heaviside', 'bspline_basis', 'bspline_basis_set', 'interpolating_spline', 'besselj', 'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn', 'yn', 'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime', 'airybiprime', 'marcumq', 'hyper', 'meijerg', 'appellf1', 'legendre', 'assoc_legendre', 'hermite', 'chebyshevt', 'chebyshevu', 'chebyshevu_root', 'chebyshevt_root', 'laguerre', 'assoc_laguerre', 'gegenbauer', 'jacobi', 'jacobi_normalized', 'Ynm', 'Ynm_c', 'Znm', 'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi', 'beta', 'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime', 'riemann_xi','betainc', 'betainc_regularized', # sympy.ntheory 'nextprime', 'prevprime', 'prime', 'primepi', 'primerange', 'randprime', 'Sieve', 'sieve', 'primorial', 'cycle_length', 'composite', 'compositepi', 'isprime', 'divisors', 'proper_divisors', 'factorint', 'multiplicity', 'perfect_power', 'pollard_pm1', 'pollard_rho', 'primefactors', 'totient', 'trailing', 'divisor_count', 'proper_divisor_count', 'divisor_sigma', 'factorrat', 'reduced_totient', 'primenu', 'primeomega', 'mersenne_prime_exponent', 'is_perfect', 'is_mersenne_prime', 'is_abundant', 'is_deficient', 'is_amicable', 'abundance', 'npartitions', 'is_primitive_root', 'is_quad_residue', 'legendre_symbol', 'jacobi_symbol', 'n_order', 'sqrt_mod', 'quadratic_residues', 'primitive_root', 'nthroot_mod', 'is_nthpow_residue', 'sqrt_mod_iter', 'mobius', 'discrete_log', 'quadratic_congruence', 'binomial_coefficients', 'binomial_coefficients_list', 'multinomial_coefficients', 'continued_fraction_periodic', 'continued_fraction_iterator', 'continued_fraction_reduce', 'continued_fraction_convergents', 'continued_fraction', 'egyptian_fraction', # sympy.concrete 'product', 'Product', 'summation', 'Sum', # sympy.discrete 'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform', 'inverse_mobius_transform', 'convolution', 'covering_product', 'intersecting_product', # sympy.simplify 'simplify', 'hypersimp', 'hypersimilar', 'logcombine', 'separatevars', 'posify', 'besselsimp', 'kroneckersimp', 'signsimp', 'bottom_up', 'nsimplify', 'FU', 'fu', 'sqrtdenest', 'cse', 'use', 'epath', 'EPath', 'hyperexpand', 'collect', 'rcollect', 'radsimp', 'collect_const', 'fraction', 'numer', 'denom', 'trigsimp', 'exptrigsimp', 'powsimp', 'powdenest', 'combsimp', 'gammasimp', 'ratsimp', 'ratsimpmodprime', # sympy.sets 'Set', 'Interval', 'Union', 'EmptySet', 'FiniteSet', 'ProductSet', 'Intersection', 'imageset', 'DisjointUnion', 'Complement', 'SymmetricDifference', 'ImageSet', 'Range', 'ComplexRegion', 'Reals', 'Contains', 'ConditionSet', 'Ordinal', 'OmegaPower', 'ord0', 'PowerSet', 'Reals', 'Naturals', 'Naturals0', 'UniversalSet', 'Integers', 'Rationals', # sympy.solvers 'solve', 'solve_linear_system', 'solve_linear_system_LU', 'solve_undetermined_coeffs', 'nsolve', 'solve_linear', 'checksol', 'det_quick', 'inv_quick', 'check_assumptions', 'failing_assumptions', 'diophantine', 'rsolve', 'rsolve_poly', 'rsolve_ratio', 'rsolve_hyper', 'checkodesol', 'classify_ode', 'dsolve', 'homogeneous_order', 'solve_poly_system', 'solve_triangulated', 'pde_separate', 'pde_separate_add', 'pde_separate_mul', 'pdsolve', 'classify_pde', 'checkpdesol', 'ode_order', 'reduce_inequalities', 'reduce_abs_inequality', 'reduce_abs_inequalities', 'solve_poly_inequality', 'solve_rational_inequalities', 'solve_univariate_inequality', 'decompogen', 'solveset', 'linsolve', 'linear_eq_to_matrix', 'nonlinsolve', 'substitution', 'Complexes', # sympy.matrices 'ShapeError', 'NonSquareMatrixError', 'GramSchmidt', 'casoratian', 'diag', 'eye', 'hessian', 'jordan_cell', 'list2numpy', 'matrix2numpy', 'matrix_multiply_elementwise', 'ones', 'randMatrix', 'rot_axis1', 'rot_axis2', 'rot_axis3', 'symarray', 'wronskian', 'zeros', 'MutableDenseMatrix', 'DeferredVector', 'MatrixBase', 'Matrix', 'MutableMatrix', 'MutableSparseMatrix', 'banded', 'ImmutableDenseMatrix', 'ImmutableSparseMatrix', 'ImmutableMatrix', 'SparseMatrix', 'MatrixSlice', 'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix', 'Identity', 'Inverse', 'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr', 'MatrixSymbol', 'Trace', 'Transpose', 'ZeroMatrix', 'OneMatrix', 'blockcut', 'block_collapse', 'matrix_symbols', 'Adjoint', 'hadamard_product', 'HadamardProduct', 'HadamardPower', 'Determinant', 'det', 'diagonalize_vector', 'DiagMatrix', 'DiagonalMatrix', 'DiagonalOf', 'trace', 'DotProduct', 'kronecker_product', 'KroneckerProduct', 'PermutationMatrix', 'MatrixPermute', 'Permanent', 'per', # sympy.geometry 'Point', 'Point2D', 'Point3D', 'Line', 'Ray', 'Segment', 'Line2D', 'Segment2D', 'Ray2D', 'Line3D', 'Segment3D', 'Ray3D', 'Plane', 'Ellipse', 'Circle', 'Polygon', 'RegularPolygon', 'Triangle', 'rad', 'deg', 'are_similar', 'centroid', 'convex_hull', 'idiff', 'intersection', 'closest_points', 'farthest_points', 'GeometryError', 'Curve', 'Parabola', # sympy.utilities 'flatten', 'group', 'take', 'subsets', 'variations', 'numbered_symbols', 'cartes', 'capture', 'dict_merge', 'postorder_traversal', 'interactive_traversal', 'prefixes', 'postfixes', 'sift', 'topological_sort', 'unflatten', 'has_dups', 'has_variety', 'reshape', 'default_sort_key', 'ordered', 'rotations', 'filldedent', 'lambdify', 'source', 'threaded', 'xthreaded', 'public', 'memoize_property', 'test', 'doctest', 'timed', # sympy.integrals 'integrate', 'Integral', 'line_integrate', 'mellin_transform', 'inverse_mellin_transform', 'MellinTransform', 'InverseMellinTransform', 'laplace_transform', 'inverse_laplace_transform', 'LaplaceTransform', 'InverseLaplaceTransform', 'fourier_transform', 'inverse_fourier_transform', 'FourierTransform', 'InverseFourierTransform', 'sine_transform', 'inverse_sine_transform', 'SineTransform', 'InverseSineTransform', 'cosine_transform', 'inverse_cosine_transform', 'CosineTransform', 'InverseCosineTransform', 'hankel_transform', 'inverse_hankel_transform', 'HankelTransform', 'InverseHankelTransform', 'singularityintegrate', # sympy.tensor 'IndexedBase', 'Idx', 'Indexed', 'get_contraction_structure', 'get_indices', 'shape', 'MutableDenseNDimArray', 'ImmutableDenseNDimArray', 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray', 'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array', 'permutedims', 'Array', 'DenseNDimArray', 'SparseNDimArray', # sympy.parsing 'parse_expr', # sympy.calculus 'euler_equations', 'singularities', 'is_increasing', 'is_strictly_increasing', 'is_decreasing', 'is_strictly_decreasing', 'is_monotonic', 'finite_diff_weights', 'apply_finite_diff', 'as_finite_diff', 'differentiate_finite', 'periodicity', 'not_empty_in', 'AccumBounds', 'is_convex', 'stationary_points', 'minimum', 'maximum', # sympy.algebras 'Quaternion', # sympy.printing 'pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode', 'pprint_try_use_unicode', 'latex', 'print_latex', 'multiline_latex', 'mathml', 'print_mathml', 'python', 'print_python', 'pycode', 'ccode', 'print_ccode', 'glsl_code', 'print_glsl', 'cxxcode', 'fcode', 'print_fcode', 'rcode', 'print_rcode', 'jscode', 'print_jscode', 'julia_code', 'mathematica_code', 'octave_code', 'rust_code', 'print_gtk', 'preview', 'srepr', 'print_tree', 'StrPrinter', 'sstr', 'sstrrepr', 'TableForm', 'dotprint', 'maple_code', 'print_maple_code', # sympy.plotting 'plot', 'textplot', 'plot_backends', 'plot_implicit', 'plot_parametric', # sympy.interactive 'init_session', 'init_printing', # sympy.testing 'test', 'doctest', ] #===========================================================================# # # # XXX: The names below were importable before sympy 1.6 using # # # # from sympy import * # # # # This happened implicitly because there was no __all__ defined in this # # __init__.py file. Not every package is imported. The list matches what # # would have been imported before. It is possible that these packages will # # not be imported by a star-import from sympy in future. # # # #===========================================================================# __all__.extend(( 'algebras', 'assumptions', 'calculus', 'concrete', 'discrete', 'external', 'functions', 'geometry', 'interactive', 'multipledispatch', 'ntheory', 'parsing', 'plotting', 'polys', 'printing', 'release', 'strategies', 'tensor', 'utilities', ))
d577a35adf785a149dbfde37eefc88e8c11094bcbfec5d4a1cb8a75c4d302a6f
import sys sys._running_pytest = True # type: ignore from sympy.external.importtools import version_tuple import pytest from sympy.core.cache import clear_cache import re sp = re.compile(r'([0-9]+)/([1-9][0-9]*)') def process_split(config, items): split = config.getoption("--split") if not split: return m = sp.match(split) if not m: raise ValueError("split must be a string of the form a/b " "where a and b are ints.") i, t = map(int, m.groups()) start, end = (i-1)*len(items)//t, i*len(items)//t if i < t: # remove elements from end of list first del items[end:] del items[:start] def pytest_report_header(config): from sympy.utilities.misc import ARCH s = "architecture: %s\n" % ARCH from sympy.core.cache import USE_CACHE s += "cache: %s\n" % USE_CACHE from sympy.external.gmpy import GROUND_TYPES, HAS_GMPY version = '' if GROUND_TYPES =='gmpy': if HAS_GMPY == 1: import gmpy elif HAS_GMPY == 2: import gmpy2 as gmpy version = gmpy.version() s += "ground types: %s %s\n" % (GROUND_TYPES, version) return s def pytest_terminal_summary(terminalreporter): if (terminalreporter.stats.get('error', None) or terminalreporter.stats.get('failed', None)): terminalreporter.write_sep( ' ', 'DO *NOT* COMMIT!', red=True, bold=True) def pytest_addoption(parser): parser.addoption("--split", action="store", default="", help="split tests") def pytest_collection_modifyitems(config, items): """ pytest hook. """ # handle splits process_split(config, items) @pytest.fixture(autouse=True, scope='module') def file_clear_cache(): clear_cache() @pytest.fixture(autouse=True, scope='module') def check_disabled(request): if getattr(request.module, 'disabled', False): pytest.skip("test requirements not met.") elif getattr(request.module, 'ipython', False): # need to check version and options for ipython tests if (version_tuple(pytest.__version__) < version_tuple('2.6.3') and pytest.config.getvalue('-s') != 'no'): pytest.skip("run py.test with -s or upgrade to newer version.")
6973c034a8d0d4de705591614fd1fe49bd64637650b39155e346c9f83f91a9f3
__version__ = "1.10.dev"
18a32de1284052e5b27d52384ceeba803327e0951fa63265b91255ccd3d8962b
# # SymPy documentation build configuration file, created by # sphinx-quickstart.py on Sat Mar 22 19:34:32 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). # # All configuration values have a default value; values that are commented out # serve to show the default value. import sys import inspect import os import subprocess from datetime import datetime import sympy # If your extensions are in another directory, add it here. sys.path = ['ext'] + sys.path # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.addons.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.linkcode', 'sphinx_math_dollar', 'sphinx.ext.mathjax', 'numpydoc', 'sympylive', 'sphinx_reredirects', 'sphinx.ext.graphviz', 'matplotlib.sphinxext.plot_directive'] redirects = { "install.rst": "getting_started/install.html", "documentation-style-guide.rst": "contributing/documentation-style-guide.html", } # Use this to use pngmath instead #extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.pngmath', ] # Enable warnings for all bad cross references. These are turned into errors # with the -W flag in the Makefile. nitpicky = True nitpick_ignore = [ ('py:class', 'sympy.logic.boolalg.Boolean') ] # To stop docstrings inheritance. autodoc_inherit_docstrings = False # MathJax file, which is free to use. See https://www.mathjax.org/#gettingstarted # As explained in the link using latest.js will get the latest version even # though it says 2.7.5. mathjax_path = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS_HTML-full' # See https://www.sympy.org/sphinx-math-dollar/ mathjax_config = { 'tex2jax': { 'inlineMath': [ ["\\(","\\)"] ], 'displayMath': [["\\[","\\]"] ], }, } # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' suppress_warnings = ['ref.citation', 'ref.footnote'] # General substitutions. project = 'SymPy' copyright = '{} SymPy Development Team'.format(datetime.utcnow().year) # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. # # The short X.Y version. version = sympy.__version__ # The full version, including alpha/beta/rc tags. release = version # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # Don't show the source code hyperlinks when using matplotlib plot directive. plot_html_show_source_link = False # Options for HTML output # ----------------------- # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. html_style = 'default.css' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # was classic html_theme = "classic" html_logo = '_static/sympylogo.png' html_favicon = '../_build/logo/sympy-notailtext-favicon.ico' # See http://www.sphinx-doc.org/en/master/theming.html#builtin-themes # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Content template for the index page. #html_index = '' # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True html_domain_indices = ['py-modindex'] # If true, the reST sources are included in the HTML build as _sources/<name>. #html_copy_source = True # Output file base name for HTML help builder. htmlhelp_basename = 'SymPydoc' # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual], toctree_only). # toctree_only is set to True so that the start file document itself is not included in the # output, only the documents referenced by it via TOC trees. The extra stuff in the master # document is intended to show up in the HTML, but doesn't really belong in the LaTeX output. latex_documents = [('index', 'sympy-%s.tex' % release, 'SymPy Documentation', 'SymPy Development Team', 'manual', True)] # Additional stuff for the LaTeX preamble. # Tweaked to work with XeTeX. latex_elements = { 'babel': '', 'fontenc': r''' % Define version of \LaTeX that is usable in math mode \let\OldLaTeX\LaTeX \renewcommand{\LaTeX}{\text{\OldLaTeX}} \usepackage{bm} \usepackage{amssymb} \usepackage{fontspec} \usepackage[english]{babel} \defaultfontfeatures{Mapping=tex-text} \setmainfont{DejaVu Serif} \setsansfont{DejaVu Sans} \setmonofont{DejaVu Sans Mono} ''', 'fontpkg': '', 'inputenc': '', 'utf8extra': '', 'preamble': r''' ''' } # SymPy logo on title page html_logo = '_static/sympylogo.png' latex_logo = '_static/sympylogo_big.png' # Documents to append as an appendix to all manuals. #latex_appendices = [] # Show page numbers next to internal references latex_show_pagerefs = True # We use False otherwise the module index gets generated twice. latex_use_modindex = False default_role = 'math' pngmath_divpng_args = ['-gamma 1.5', '-D 110'] # Note, this is ignored by the mathjax extension # Any \newcommand should be defined in the file pngmath_latex_preamble = '\\usepackage{amsmath}\n' \ '\\usepackage{bm}\n' \ '\\usepackage{amsfonts}\n' \ '\\usepackage{amssymb}\n' \ '\\setlength{\\parindent}{0pt}\n' texinfo_documents = [ (master_doc, 'sympy', 'SymPy Documentation', 'SymPy Development Team', 'SymPy', 'Computer algebra system (CAS) in Python', 'Programming', 1), ] # Use svg for graphviz graphviz_output_format = 'svg' # Requried for linkcode extension. # Get commit hash from the external file. commit_hash_filepath = '../commit_hash.txt' commit_hash = None if os.path.isfile(commit_hash_filepath): with open(commit_hash_filepath) as f: commit_hash = f.readline() # Get commit hash from the external file. if not commit_hash: try: commit_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD']) commit_hash = commit_hash.decode('ascii') commit_hash = commit_hash.rstrip() except: import warnings warnings.warn( "Failed to get the git commit hash as the command " \ "'git rev-parse HEAD' is not working. The commit hash will be " \ "assumed as the SymPy master, but the lines may be misleading " \ "or nonexistent as it is not the correct branch the doc is " \ "built with. Check your installation of 'git' if you want to " \ "resolve this warning.") commit_hash = 'master' fork = 'sympy' blobpath = \ "https://github.com/{}/sympy/blob/{}/sympy/".format(fork, commit_hash) def linkcode_resolve(domain, info): """Determine the URL corresponding to Python object.""" if domain != 'py': return modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return obj = submod for part in fullname.split('.'): try: obj = getattr(obj, part) except Exception: return # strip decorators, which would resolve to the source of the decorator # possibly an upstream bug in getsourcefile, bpo-1764286 try: unwrap = inspect.unwrap except AttributeError: pass else: obj = unwrap(obj) try: fn = inspect.getsourcefile(obj) except Exception: fn = None if not fn: return try: source, lineno = inspect.getsourcelines(obj) except Exception: lineno = None if lineno: linespec = "#L%d-L%d" % (lineno, lineno + len(source) - 1) else: linespec = "" fn = os.path.relpath(fn, start=os.path.dirname(sympy.__file__)) return blobpath + fn + linespec
0b3d5fb85ee3bd9eb6ce00f8a2998c30e9c093ad8d113e593a0a11b65fa5c8df
""" Continuous Random Variables - Prebuilt variables Contains ======== Arcsin Benini Beta BetaNoncentral BetaPrime BoundedPareto Cauchy Chi ChiNoncentral ChiSquared Dagum Erlang ExGaussian Exponential ExponentialPower FDistribution FisherZ Frechet Gamma GammaInverse Gumbel Gompertz Kumaraswamy Laplace Levy LogCauchy Logistic LogLogistic LogitNormal LogNormal Lomax Maxwell Moyal Nakagami Normal Pareto PowerFunction QuadraticU RaisedCosine Rayleigh Reciprocal ShiftedGompertz StudentT Trapezoidal Triangular Uniform UniformSum VonMises Wald Weibull WignerSemicircle """ from sympy import beta as beta_fn from sympy import cos, sin, tan, atan, exp, besseli, besselj, besselk from sympy import (log, sqrt, pi, S, Dummy, Interval, sympify, gamma, sign, Piecewise, And, Eq, binomial, factorial, Sum, floor, Abs, Lambda, Basic, lowergamma, erf, erfc, erfi, erfinv, I, asin, hyper, uppergamma, sinh, Ne, expint, Rational, integrate) from sympy.matrices import MatrixBase from sympy.stats.crv import SingleContinuousPSpace, SingleContinuousDistribution from sympy.stats.rv import _value_check, is_random oo = S.Infinity __all__ = ['ContinuousRV', 'Arcsin', 'Benini', 'Beta', 'BetaNoncentral', 'BetaPrime', 'BoundedPareto', 'Cauchy', 'Chi', 'ChiNoncentral', 'ChiSquared', 'Dagum', 'Erlang', 'ExGaussian', 'Exponential', 'ExponentialPower', 'FDistribution', 'FisherZ', 'Frechet', 'Gamma', 'GammaInverse', 'Gompertz', 'Gumbel', 'Kumaraswamy', 'Laplace', 'Levy', 'LogCauchy', 'Logistic', 'LogLogistic', 'LogitNormal', 'LogNormal', 'Lomax', 'Maxwell', 'Moyal', 'Nakagami', 'Normal', 'GaussianInverse', 'Pareto', 'PowerFunction', 'QuadraticU', 'RaisedCosine', 'Rayleigh', 'Reciprocal', 'StudentT', 'ShiftedGompertz', 'Trapezoidal', 'Triangular', 'Uniform', 'UniformSum', 'VonMises', 'Wald', 'Weibull', 'WignerSemicircle', ] @is_random.register(MatrixBase) def _(x): return any(is_random(i) for i in x) def rv(symbol, cls, args, **kwargs): args = list(map(sympify, args)) dist = cls(*args) if kwargs.pop('check', True): dist.check(*args) pspace = SingleContinuousPSpace(symbol, dist) if any(is_random(arg) for arg in args): from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution pspace = CompoundPSpace(symbol, CompoundDistribution(dist)) return pspace.value class ContinuousDistributionHandmade(SingleContinuousDistribution): _argnames = ('pdf',) def __new__(cls, pdf, set=Interval(-oo, oo)): return Basic.__new__(cls, pdf, set) @property def set(self): return self.args[1] @staticmethod def check(pdf, set): x = Dummy('x') val = integrate(pdf(x), (x, set)) _value_check(Eq(val, 1) != S.false, "The pdf on the given set is incorrect.") def ContinuousRV(symbol, density, set=Interval(-oo, oo), **kwargs): """ Create a Continuous Random Variable given the following: Parameters ========== symbol : Symbol Represents name of the random variable. density : Expression containing symbol Represents probability density function. set : set/Interval Represents the region where the pdf is valid, by default is real line. check : bool If True, it will check whether the given density integrates to 1 over the given set. If False, it will not perform this check. Default is False. Returns ======= RandomSymbol Many common continuous random variable types are already implemented. This function should be necessary only very rarely. Examples ======== >>> from sympy import Symbol, sqrt, exp, pi >>> from sympy.stats import ContinuousRV, P, E >>> x = Symbol("x") >>> pdf = sqrt(2)*exp(-x**2/2)/(2*sqrt(pi)) # Normal distribution >>> X = ContinuousRV(x, pdf) >>> E(X) 0 >>> P(X>0) 1/2 """ pdf = Piecewise((density, set.as_relational(symbol)), (0, True)) pdf = Lambda(symbol, pdf) # have a default of False while `rv` should have a default of True kwargs['check'] = kwargs.pop('check', False) return rv(symbol.name, ContinuousDistributionHandmade, (pdf, set), **kwargs) ######################################## # Continuous Probability Distributions # ######################################## #------------------------------------------------------------------------------- # Arcsin distribution ---------------------------------------------------------- class ArcsinDistribution(SingleContinuousDistribution): _argnames = ('a', 'b') @property def set(self): return Interval(self.a, self.b) def pdf(self, x): a, b = self.a, self.b return 1/(pi*sqrt((x - a)*(b - x))) def _cdf(self, x): a, b = self.a, self.b return Piecewise( (S.Zero, x < a), (2*asin(sqrt((x - a)/(b - a)))/pi, x <= b), (S.One, True)) def Arcsin(name, a=0, b=1): r""" Create a Continuous Random Variable with an arcsin distribution. The density of the arcsin distribution is given by .. math:: f(x) := \frac{1}{\pi\sqrt{(x-a)(b-x)}} with :math:`x \in (a,b)`. It must hold that :math:`-\infty < a < b < \infty`. Parameters ========== a : Real number, the left interval boundary b : Real number, the right interval boundary Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Arcsin, density, cdf >>> from sympy import Symbol >>> a = Symbol("a", real=True) >>> b = Symbol("b", real=True) >>> z = Symbol("z") >>> X = Arcsin("x", a, b) >>> density(X)(z) 1/(pi*sqrt((-a + z)*(b - z))) >>> cdf(X)(z) Piecewise((0, a > z), (2*asin(sqrt((-a + z)/(-a + b)))/pi, b >= z), (1, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Arcsine_distribution """ return rv(name, ArcsinDistribution, (a, b)) #------------------------------------------------------------------------------- # Benini distribution ---------------------------------------------------------- class BeniniDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta', 'sigma') @staticmethod def check(alpha, beta, sigma): _value_check(alpha > 0, "Shape parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") _value_check(sigma > 0, "Scale parameter Sigma must be positive.") @property def set(self): return Interval(self.sigma, oo) def pdf(self, x): alpha, beta, sigma = self.alpha, self.beta, self.sigma return (exp(-alpha*log(x/sigma) - beta*log(x/sigma)**2) *(alpha/x + 2*beta*log(x/sigma)/x)) def _moment_generating_function(self, t): raise NotImplementedError('The moment generating function of the ' 'Benini distribution does not exist.') def Benini(name, alpha, beta, sigma): r""" Create a Continuous Random Variable with a Benini distribution. The density of the Benini distribution is given by .. math:: f(x) := e^{-\alpha\log{\frac{x}{\sigma}} -\beta\log^2\left[{\frac{x}{\sigma}}\right]} \left(\frac{\alpha}{x}+\frac{2\beta\log{\frac{x}{\sigma}}}{x}\right) This is a heavy-tailed distribution and is also known as the log-Rayleigh distribution. Parameters ========== alpha : Real number, `\alpha > 0`, a shape beta : Real number, `\beta > 0`, a shape sigma : Real number, `\sigma > 0`, a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Benini, density, cdf >>> from sympy import Symbol, pprint >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> sigma = Symbol("sigma", positive=True) >>> z = Symbol("z") >>> X = Benini("x", alpha, beta, sigma) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) / / z \\ / z \ 2/ z \ | 2*beta*log|-----|| - alpha*log|-----| - beta*log |-----| |alpha \sigma/| \sigma/ \sigma/ |----- + -----------------|*e \ z z / >>> cdf(X)(z) Piecewise((1 - exp(-alpha*log(z/sigma) - beta*log(z/sigma)**2), sigma <= z), (0, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Benini_distribution .. [2] http://reference.wolfram.com/legacy/v8/ref/BeniniDistribution.html """ return rv(name, BeniniDistribution, (alpha, beta, sigma)) #------------------------------------------------------------------------------- # Beta distribution ------------------------------------------------------------ class BetaDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta') set = Interval(0, 1) @staticmethod def check(alpha, beta): _value_check(alpha > 0, "Shape parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") def pdf(self, x): alpha, beta = self.alpha, self.beta return x**(alpha - 1) * (1 - x)**(beta - 1) / beta_fn(alpha, beta) def _characteristic_function(self, t): return hyper((self.alpha,), (self.alpha + self.beta,), I*t) def _moment_generating_function(self, t): return hyper((self.alpha,), (self.alpha + self.beta,), t) def Beta(name, alpha, beta): r""" Create a Continuous Random Variable with a Beta distribution. The density of the Beta distribution is given by .. math:: f(x) := \frac{x^{\alpha-1}(1-x)^{\beta-1}} {\mathrm{B}(\alpha,\beta)} with :math:`x \in [0,1]`. Parameters ========== alpha : Real number, `\alpha > 0`, a shape beta : Real number, `\beta > 0`, a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Beta, density, E, variance >>> from sympy import Symbol, simplify, pprint, factor >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> z = Symbol("z") >>> X = Beta("x", alpha, beta) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) alpha - 1 beta - 1 z *(1 - z) -------------------------- B(alpha, beta) >>> simplify(E(X)) alpha/(alpha + beta) >>> factor(simplify(variance(X))) alpha*beta/((alpha + beta)**2*(alpha + beta + 1)) References ========== .. [1] https://en.wikipedia.org/wiki/Beta_distribution .. [2] http://mathworld.wolfram.com/BetaDistribution.html """ return rv(name, BetaDistribution, (alpha, beta)) #------------------------------------------------------------------------------- # Noncentral Beta distribution ------------------------------------------------------------ class BetaNoncentralDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta', 'lamda') set = Interval(0, 1) @staticmethod def check(alpha, beta, lamda): _value_check(alpha > 0, "Shape parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") _value_check(lamda >= 0, "Noncentrality parameter Lambda must be positive") def pdf(self, x): alpha, beta, lamda = self.alpha, self.beta, self.lamda k = Dummy("k") return Sum(exp(-lamda / 2) * (lamda / 2)**k * x**(alpha + k - 1) *( 1 - x)**(beta - 1) / (factorial(k) * beta_fn(alpha + k, beta)), (k, 0, oo)) def BetaNoncentral(name, alpha, beta, lamda): r""" Create a Continuous Random Variable with a Type I Noncentral Beta distribution. The density of the Noncentral Beta distribution is given by .. math:: f(x) := \sum_{k=0}^\infty e^{-\lambda/2}\frac{(\lambda/2)^k}{k!} \frac{x^{\alpha+k-1}(1-x)^{\beta-1}}{\mathrm{B}(\alpha+k,\beta)} with :math:`x \in [0,1]`. Parameters ========== alpha : Real number, `\alpha > 0`, a shape beta : Real number, `\beta > 0`, a shape lamda: Real number, `\lambda >= 0`, noncentrality parameter Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import BetaNoncentral, density, cdf >>> from sympy import Symbol, pprint >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> lamda = Symbol("lamda", nonnegative=True) >>> z = Symbol("z") >>> X = BetaNoncentral("x", alpha, beta, lamda) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) oo _____ \ ` \ -lamda \ k ------- \ k + alpha - 1 /lamda\ beta - 1 2 ) z *|-----| *(1 - z) *e / \ 2 / / ------------------------------------------------ / B(k + alpha, beta)*k! /____, k = 0 Compute cdf with specific 'x', 'alpha', 'beta' and 'lamda' values as follows : >>> cdf(BetaNoncentral("x", 1, 1, 1), evaluate=False)(2).doit() 2*exp(1/2) The argument evaluate=False prevents an attempt at evaluation of the sum for general x, before the argument 2 is passed. References ========== .. [1] https://en.wikipedia.org/wiki/Noncentral_beta_distribution .. [2] https://reference.wolfram.com/language/ref/NoncentralBetaDistribution.html """ return rv(name, BetaNoncentralDistribution, (alpha, beta, lamda)) #------------------------------------------------------------------------------- # Beta prime distribution ------------------------------------------------------ class BetaPrimeDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta') @staticmethod def check(alpha, beta): _value_check(alpha > 0, "Shape parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") set = Interval(0, oo) def pdf(self, x): alpha, beta = self.alpha, self.beta return x**(alpha - 1)*(1 + x)**(-alpha - beta)/beta_fn(alpha, beta) def BetaPrime(name, alpha, beta): r""" Create a continuous random variable with a Beta prime distribution. The density of the Beta prime distribution is given by .. math:: f(x) := \frac{x^{\alpha-1} (1+x)^{-\alpha -\beta}}{B(\alpha,\beta)} with :math:`x > 0`. Parameters ========== alpha : Real number, `\alpha > 0`, a shape beta : Real number, `\beta > 0`, a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import BetaPrime, density >>> from sympy import Symbol, pprint >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> z = Symbol("z") >>> X = BetaPrime("x", alpha, beta) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) alpha - 1 -alpha - beta z *(z + 1) ------------------------------- B(alpha, beta) References ========== .. [1] https://en.wikipedia.org/wiki/Beta_prime_distribution .. [2] http://mathworld.wolfram.com/BetaPrimeDistribution.html """ return rv(name, BetaPrimeDistribution, (alpha, beta)) #------------------------------------------------------------------------------- # Bounded Pareto Distribution -------------------------------------------------- class BoundedParetoDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'left', 'right') @property def set(self): return Interval(self.left , self.right) @staticmethod def check(alpha, left, right): _value_check (alpha.is_positive, "Shape must be positive.") _value_check (left.is_positive, "Left value should be positive.") _value_check (right > left, "Right should be greater than left.") def pdf(self, x): alpha, left, right = self.alpha, self.left, self.right num = alpha * (left**alpha) * x**(- alpha -1) den = 1 - (left/right)**alpha return num/den def BoundedPareto(name, alpha, left, right): r""" Create a continuous random variable with a Bounded Pareto distribution. The density of the Bounded Pareto distribution is given by .. math:: f(x) := \frac{\alpha L^{\alpha}x^{-\alpha-1}}{1-(\frac{L}{H})^{\alpha}} Parameters ========== alpha : Real Number, `alpha > 0` Shape parameter left : Real Number, `left > 0` Location parameter right : Real Number, `right > left` Location parameter Examples ======== >>> from sympy.stats import BoundedPareto, density, cdf, E >>> from sympy import symbols >>> L, H = symbols('L, H', positive=True) >>> X = BoundedPareto('X', 2, L, H) >>> x = symbols('x') >>> density(X)(x) 2*L**2/(x**3*(1 - L**2/H**2)) >>> cdf(X)(x) Piecewise((-H**2*L**2/(x**2*(H**2 - L**2)) + H**2/(H**2 - L**2), L <= x), (0, True)) >>> E(X).simplify() 2*H*L/(H + L) Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Pareto_distribution#Bounded_Pareto_distribution """ return rv (name, BoundedParetoDistribution, (alpha, left, right)) # ------------------------------------------------------------------------------ # Cauchy distribution ---------------------------------------------------------- class CauchyDistribution(SingleContinuousDistribution): _argnames = ('x0', 'gamma') @staticmethod def check(x0, gamma): _value_check(gamma > 0, "Scale parameter Gamma must be positive.") _value_check(x0.is_real, "Location parameter must be real.") def pdf(self, x): return 1/(pi*self.gamma*(1 + ((x - self.x0)/self.gamma)**2)) def _cdf(self, x): x0, gamma = self.x0, self.gamma return (1/pi)*atan((x - x0)/gamma) + S.Half def _characteristic_function(self, t): return exp(self.x0 * I * t - self.gamma * Abs(t)) def _moment_generating_function(self, t): raise NotImplementedError("The moment generating function for the " "Cauchy distribution does not exist.") def _quantile(self, p): return self.x0 + self.gamma*tan(pi*(p - S.Half)) def Cauchy(name, x0, gamma): r""" Create a continuous random variable with a Cauchy distribution. The density of the Cauchy distribution is given by .. math:: f(x) := \frac{1}{\pi \gamma [1 + {(\frac{x-x_0}{\gamma})}^2]} Parameters ========== x0 : Real number, the location gamma : Real number, `\gamma > 0`, a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Cauchy, density >>> from sympy import Symbol >>> x0 = Symbol("x0") >>> gamma = Symbol("gamma", positive=True) >>> z = Symbol("z") >>> X = Cauchy("x", x0, gamma) >>> density(X)(z) 1/(pi*gamma*(1 + (-x0 + z)**2/gamma**2)) References ========== .. [1] https://en.wikipedia.org/wiki/Cauchy_distribution .. [2] http://mathworld.wolfram.com/CauchyDistribution.html """ return rv(name, CauchyDistribution, (x0, gamma)) #------------------------------------------------------------------------------- # Chi distribution ------------------------------------------------------------- class ChiDistribution(SingleContinuousDistribution): _argnames = ('k',) @staticmethod def check(k): _value_check(k > 0, "Number of degrees of freedom (k) must be positive.") _value_check(k.is_integer, "Number of degrees of freedom (k) must be an integer.") set = Interval(0, oo) def pdf(self, x): return 2**(1 - self.k/2)*x**(self.k - 1)*exp(-x**2/2)/gamma(self.k/2) def _characteristic_function(self, t): k = self.k part_1 = hyper((k/2,), (S.Half,), -t**2/2) part_2 = I*t*sqrt(2)*gamma((k+1)/2)/gamma(k/2) part_3 = hyper(((k+1)/2,), (Rational(3, 2),), -t**2/2) return part_1 + part_2*part_3 def _moment_generating_function(self, t): k = self.k part_1 = hyper((k / 2,), (S.Half,), t ** 2 / 2) part_2 = t * sqrt(2) * gamma((k + 1) / 2) / gamma(k / 2) part_3 = hyper(((k + 1) / 2,), (S(3) / 2,), t ** 2 / 2) return part_1 + part_2 * part_3 def Chi(name, k): r""" Create a continuous random variable with a Chi distribution. The density of the Chi distribution is given by .. math:: f(x) := \frac{2^{1-k/2}x^{k-1}e^{-x^2/2}}{\Gamma(k/2)} with :math:`x \geq 0`. Parameters ========== k : Positive integer, The number of degrees of freedom Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Chi, density, E >>> from sympy import Symbol, simplify >>> k = Symbol("k", integer=True) >>> z = Symbol("z") >>> X = Chi("x", k) >>> density(X)(z) 2**(1 - k/2)*z**(k - 1)*exp(-z**2/2)/gamma(k/2) >>> simplify(E(X)) sqrt(2)*gamma(k/2 + 1/2)/gamma(k/2) References ========== .. [1] https://en.wikipedia.org/wiki/Chi_distribution .. [2] http://mathworld.wolfram.com/ChiDistribution.html """ return rv(name, ChiDistribution, (k,)) #------------------------------------------------------------------------------- # Non-central Chi distribution ------------------------------------------------- class ChiNoncentralDistribution(SingleContinuousDistribution): _argnames = ('k', 'l') @staticmethod def check(k, l): _value_check(k > 0, "Number of degrees of freedom (k) must be positive.") _value_check(k.is_integer, "Number of degrees of freedom (k) must be an integer.") _value_check(l > 0, "Shift parameter Lambda must be positive.") set = Interval(0, oo) def pdf(self, x): k, l = self.k, self.l return exp(-(x**2+l**2)/2)*x**k*l / (l*x)**(k/2) * besseli(k/2-1, l*x) def ChiNoncentral(name, k, l): r""" Create a continuous random variable with a non-central Chi distribution. Explanation =========== The density of the non-central Chi distribution is given by .. math:: f(x) := \frac{e^{-(x^2+\lambda^2)/2} x^k\lambda} {(\lambda x)^{k/2}} I_{k/2-1}(\lambda x) with `x \geq 0`. Here, `I_\nu (x)` is the :ref:`modified Bessel function of the first kind <besseli>`. Parameters ========== k : A positive Integer, $k > 0$ The number of degrees of freedom. lambda : Real number, `\lambda > 0` Shift parameter. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import ChiNoncentral, density >>> from sympy import Symbol >>> k = Symbol("k", integer=True) >>> l = Symbol("l") >>> z = Symbol("z") >>> X = ChiNoncentral("x", k, l) >>> density(X)(z) l*z**k*exp(-l**2/2 - z**2/2)*besseli(k/2 - 1, l*z)/(l*z)**(k/2) References ========== .. [1] https://en.wikipedia.org/wiki/Noncentral_chi_distribution """ return rv(name, ChiNoncentralDistribution, (k, l)) #------------------------------------------------------------------------------- # Chi squared distribution ----------------------------------------------------- class ChiSquaredDistribution(SingleContinuousDistribution): _argnames = ('k',) @staticmethod def check(k): _value_check(k > 0, "Number of degrees of freedom (k) must be positive.") _value_check(k.is_integer, "Number of degrees of freedom (k) must be an integer.") set = Interval(0, oo) def pdf(self, x): k = self.k return 1/(2**(k/2)*gamma(k/2))*x**(k/2 - 1)*exp(-x/2) def _cdf(self, x): k = self.k return Piecewise( (S.One/gamma(k/2)*lowergamma(k/2, x/2), x >= 0), (0, True) ) def _characteristic_function(self, t): return (1 - 2*I*t)**(-self.k/2) def _moment_generating_function(self, t): return (1 - 2*t)**(-self.k/2) def ChiSquared(name, k): r""" Create a continuous random variable with a Chi-squared distribution. Explanation =========== The density of the Chi-squared distribution is given by .. math:: f(x) := \frac{1}{2^{\frac{k}{2}}\Gamma\left(\frac{k}{2}\right)} x^{\frac{k}{2}-1} e^{-\frac{x}{2}} with :math:`x \geq 0`. Parameters ========== k : Positive integer The number of degrees of freedom. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import ChiSquared, density, E, variance, moment >>> from sympy import Symbol >>> k = Symbol("k", integer=True, positive=True) >>> z = Symbol("z") >>> X = ChiSquared("x", k) >>> density(X)(z) z**(k/2 - 1)*exp(-z/2)/(2**(k/2)*gamma(k/2)) >>> E(X) k >>> variance(X) 2*k >>> moment(X, 3) k**3 + 6*k**2 + 8*k References ========== .. [1] https://en.wikipedia.org/wiki/Chi_squared_distribution .. [2] http://mathworld.wolfram.com/Chi-SquaredDistribution.html """ return rv(name, ChiSquaredDistribution, (k, )) #------------------------------------------------------------------------------- # Dagum distribution ----------------------------------------------------------- class DagumDistribution(SingleContinuousDistribution): _argnames = ('p', 'a', 'b') set = Interval(0, oo) @staticmethod def check(p, a, b): _value_check(p > 0, "Shape parameter p must be positive.") _value_check(a > 0, "Shape parameter a must be positive.") _value_check(b > 0, "Scale parameter b must be positive.") def pdf(self, x): p, a, b = self.p, self.a, self.b return a*p/x*((x/b)**(a*p)/(((x/b)**a + 1)**(p + 1))) def _cdf(self, x): p, a, b = self.p, self.a, self.b return Piecewise(((S.One + (S(x)/b)**-a)**-p, x>=0), (S.Zero, True)) def Dagum(name, p, a, b): r""" Create a continuous random variable with a Dagum distribution. Explanation =========== The density of the Dagum distribution is given by .. math:: f(x) := \frac{a p}{x} \left( \frac{\left(\tfrac{x}{b}\right)^{a p}} {\left(\left(\tfrac{x}{b}\right)^a + 1 \right)^{p+1}} \right) with :math:`x > 0`. Parameters ========== p : Real number ``p > 0``, a shape. a : Real number ``a > 0``, a shape. b : Real number ``b > 0``, a scale. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Dagum, density, cdf >>> from sympy import Symbol >>> p = Symbol("p", positive=True) >>> a = Symbol("a", positive=True) >>> b = Symbol("b", positive=True) >>> z = Symbol("z") >>> X = Dagum("x", p, a, b) >>> density(X)(z) a*p*(z/b)**(a*p)*((z/b)**a + 1)**(-p - 1)/z >>> cdf(X)(z) Piecewise(((1 + (z/b)**(-a))**(-p), z >= 0), (0, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Dagum_distribution """ return rv(name, DagumDistribution, (p, a, b)) #------------------------------------------------------------------------------- # Erlang distribution ---------------------------------------------------------- def Erlang(name, k, l): r""" Create a continuous random variable with an Erlang distribution. Explanation =========== The density of the Erlang distribution is given by .. math:: f(x) := \frac{\lambda^k x^{k-1} e^{-\lambda x}}{(k-1)!} with :math:`x \in [0,\infty]`. Parameters ========== k : Positive integer l : Real number, `\lambda > 0`, the rate Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Erlang, density, cdf, E, variance >>> from sympy import Symbol, simplify, pprint >>> k = Symbol("k", integer=True, positive=True) >>> l = Symbol("l", positive=True) >>> z = Symbol("z") >>> X = Erlang("x", k, l) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) k k - 1 -l*z l *z *e --------------- Gamma(k) >>> C = cdf(X)(z) >>> pprint(C, use_unicode=False) /lowergamma(k, l*z) |------------------ for z > 0 < Gamma(k) | \ 0 otherwise >>> E(X) k/l >>> simplify(variance(X)) k/l**2 References ========== .. [1] https://en.wikipedia.org/wiki/Erlang_distribution .. [2] http://mathworld.wolfram.com/ErlangDistribution.html """ return rv(name, GammaDistribution, (k, S.One/l)) # ------------------------------------------------------------------------------- # ExGaussian distribution ----------------------------------------------------- class ExGaussianDistribution(SingleContinuousDistribution): _argnames = ('mean', 'std', 'rate') set = Interval(-oo, oo) @staticmethod def check(mean, std, rate): _value_check( std > 0, "Standard deviation of ExGaussian must be positive.") _value_check(rate > 0, "Rate of ExGaussian must be positive.") def pdf(self, x): mean, std, rate = self.mean, self.std, self.rate term1 = rate/2 term2 = exp(rate * (2 * mean + rate * std**2 - 2*x)/2) term3 = erfc((mean + rate*std**2 - x)/(sqrt(2)*std)) return term1*term2*term3 def _cdf(self, x): from sympy.stats import cdf mean, std, rate = self.mean, self.std, self.rate u = rate*(x - mean) v = rate*std GaussianCDF1 = cdf(Normal('x', 0, v))(u) GaussianCDF2 = cdf(Normal('x', v**2, v))(u) return GaussianCDF1 - exp(-u + (v**2/2) + log(GaussianCDF2)) def _characteristic_function(self, t): mean, std, rate = self.mean, self.std, self.rate term1 = (1 - I*t/rate)**(-1) term2 = exp(I*mean*t - std**2*t**2/2) return term1 * term2 def _moment_generating_function(self, t): mean, std, rate = self.mean, self.std, self.rate term1 = (1 - t/rate)**(-1) term2 = exp(mean*t + std**2*t**2/2) return term1*term2 def ExGaussian(name, mean, std, rate): r""" Create a continuous random variable with an Exponentially modified Gaussian (EMG) distribution. Explanation =========== The density of the exponentially modified Gaussian distribution is given by .. math:: f(x) := \frac{\lambda}{2}e^{\frac{\lambda}{2}(2\mu+\lambda\sigma^2-2x)} \text{erfc}(\frac{\mu + \lambda\sigma^2 - x}{\sqrt{2}\sigma}) with $x > 0$. Note that the expected value is `1/\lambda`. Parameters ========== mu : A Real number, the mean of Gaussian component std: A positive Real number, :math: `\sigma^2 > 0` the variance of Gaussian component lambda: A positive Real number, :math: `\lambda > 0` the rate of Exponential component Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import ExGaussian, density, cdf, E >>> from sympy.stats import variance, skewness >>> from sympy import Symbol, pprint, simplify >>> mean = Symbol("mu") >>> std = Symbol("sigma", positive=True) >>> rate = Symbol("lamda", positive=True) >>> z = Symbol("z") >>> X = ExGaussian("x", mean, std, rate) >>> pprint(density(X)(z), use_unicode=False) / 2 \ lamda*\lamda*sigma + 2*mu - 2*z/ --------------------------------- / ___ / 2 \\ 2 |\/ 2 *\lamda*sigma + mu - z/| lamda*e *erfc|-----------------------------| \ 2*sigma / ---------------------------------------------------------------------------- 2 >>> cdf(X)(z) -(erf(sqrt(2)*(-lamda**2*sigma**2 + lamda*(-mu + z))/(2*lamda*sigma))/2 + 1/2)*exp(lamda**2*sigma**2/2 - lamda*(-mu + z)) + erf(sqrt(2)*(-mu + z)/(2*sigma))/2 + 1/2 >>> E(X) (lamda*mu + 1)/lamda >>> simplify(variance(X)) sigma**2 + lamda**(-2) >>> simplify(skewness(X)) 2/(lamda**2*sigma**2 + 1)**(3/2) References ========== .. [1] https://en.wikipedia.org/wiki/Exponentially_modified_Gaussian_distribution """ return rv(name, ExGaussianDistribution, (mean, std, rate)) #------------------------------------------------------------------------------- # Exponential distribution ----------------------------------------------------- class ExponentialDistribution(SingleContinuousDistribution): _argnames = ('rate',) set = Interval(0, oo) @staticmethod def check(rate): _value_check(rate > 0, "Rate must be positive.") def pdf(self, x): return self.rate * exp(-self.rate*x) def _cdf(self, x): return Piecewise( (S.One - exp(-self.rate*x), x >= 0), (0, True), ) def _characteristic_function(self, t): rate = self.rate return rate / (rate - I*t) def _moment_generating_function(self, t): rate = self.rate return rate / (rate - t) def _quantile(self, p): return -log(1-p)/self.rate def Exponential(name, rate): r""" Create a continuous random variable with an Exponential distribution. Explanation =========== The density of the exponential distribution is given by .. math:: f(x) := \lambda \exp(-\lambda x) with $x > 0$. Note that the expected value is `1/\lambda`. Parameters ========== rate : A positive Real number, `\lambda > 0`, the rate (or inverse scale/inverse mean) Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Exponential, density, cdf, E >>> from sympy.stats import variance, std, skewness, quantile >>> from sympy import Symbol >>> l = Symbol("lambda", positive=True) >>> z = Symbol("z") >>> p = Symbol("p") >>> X = Exponential("x", l) >>> density(X)(z) lambda*exp(-lambda*z) >>> cdf(X)(z) Piecewise((1 - exp(-lambda*z), z >= 0), (0, True)) >>> quantile(X)(p) -log(1 - p)/lambda >>> E(X) 1/lambda >>> variance(X) lambda**(-2) >>> skewness(X) 2 >>> X = Exponential('x', 10) >>> density(X)(z) 10*exp(-10*z) >>> E(X) 1/10 >>> std(X) 1/10 References ========== .. [1] https://en.wikipedia.org/wiki/Exponential_distribution .. [2] http://mathworld.wolfram.com/ExponentialDistribution.html """ return rv(name, ExponentialDistribution, (rate, )) # ------------------------------------------------------------------------------- # Exponential Power distribution ----------------------------------------------------- class ExponentialPowerDistribution(SingleContinuousDistribution): _argnames = ('mu', 'alpha', 'beta') set = Interval(-oo, oo) @staticmethod def check(mu, alpha, beta): _value_check(alpha > 0, "Scale parameter alpha must be positive.") _value_check(beta > 0, "Shape parameter beta must be positive.") def pdf(self, x): mu, alpha, beta = self.mu, self.alpha, self.beta num = beta*exp(-(Abs(x - mu)/alpha)**beta) den = 2*alpha*gamma(1/beta) return num/den def _cdf(self, x): mu, alpha, beta = self.mu, self.alpha, self.beta num = lowergamma(1/beta, (Abs(x - mu) / alpha)**beta) den = 2*gamma(1/beta) return sign(x - mu)*num/den + S.Half def ExponentialPower(name, mu, alpha, beta): r""" Create a Continuous Random Variable with Exponential Power distribution. This distribution is known also as Generalized Normal distribution version 1. Explanation =========== The density of the Exponential Power distribution is given by .. math:: f(x) := \frac{\beta}{2\alpha\Gamma(\frac{1}{\beta})} e^{{-(\frac{|x - \mu|}{\alpha})^{\beta}}} with :math:`x \in [ - \infty, \infty ]`. Parameters ========== mu : Real number A location. alpha : Real number,``alpha > 0`` A scale. beta : Real number, ``beta > 0`` A shape. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import ExponentialPower, density, cdf >>> from sympy import Symbol, pprint >>> z = Symbol("z") >>> mu = Symbol("mu") >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> X = ExponentialPower("x", mu, alpha, beta) >>> pprint(density(X)(z), use_unicode=False) beta /|mu - z|\ -|--------| \ alpha / beta*e --------------------- / 1 \ 2*alpha*Gamma|----| \beta/ >>> cdf(X)(z) 1/2 + lowergamma(1/beta, (Abs(mu - z)/alpha)**beta)*sign(-mu + z)/(2*gamma(1/beta)) References ========== .. [1] https://reference.wolfram.com/language/ref/ExponentialPowerDistribution.html .. [2] https://en.wikipedia.org/wiki/Generalized_normal_distribution#Version_1 """ return rv(name, ExponentialPowerDistribution, (mu, alpha, beta)) #------------------------------------------------------------------------------- # F distribution --------------------------------------------------------------- class FDistributionDistribution(SingleContinuousDistribution): _argnames = ('d1', 'd2') set = Interval(0, oo) @staticmethod def check(d1, d2): _value_check((d1 > 0, d1.is_integer), "Degrees of freedom d1 must be positive integer.") _value_check((d2 > 0, d2.is_integer), "Degrees of freedom d2 must be positive integer.") def pdf(self, x): d1, d2 = self.d1, self.d2 return (sqrt((d1*x)**d1*d2**d2 / (d1*x+d2)**(d1+d2)) / (x * beta_fn(d1/2, d2/2))) def _moment_generating_function(self, t): raise NotImplementedError('The moment generating function for the ' 'F-distribution does not exist.') def FDistribution(name, d1, d2): r""" Create a continuous random variable with a F distribution. Explanation =========== The density of the F distribution is given by .. math:: f(x) := \frac{\sqrt{\frac{(d_1 x)^{d_1} d_2^{d_2}} {(d_1 x + d_2)^{d_1 + d_2}}}} {x \mathrm{B} \left(\frac{d_1}{2}, \frac{d_2}{2}\right)} with :math:`x > 0`. Parameters ========== d1 : `d_1 > 0`, where d_1 is the degrees of freedom (n_1 - 1) d2 : `d_2 > 0`, where d_2 is the degrees of freedom (n_2 - 1) Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import FDistribution, density >>> from sympy import Symbol, pprint >>> d1 = Symbol("d1", positive=True) >>> d2 = Symbol("d2", positive=True) >>> z = Symbol("z") >>> X = FDistribution("x", d1, d2) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) d2 -- ______________________________ 2 / d1 -d1 - d2 d2 *\/ (d1*z) *(d1*z + d2) -------------------------------------- /d1 d2\ z*B|--, --| \2 2 / References ========== .. [1] https://en.wikipedia.org/wiki/F-distribution .. [2] http://mathworld.wolfram.com/F-Distribution.html """ return rv(name, FDistributionDistribution, (d1, d2)) #------------------------------------------------------------------------------- # Fisher Z distribution -------------------------------------------------------- class FisherZDistribution(SingleContinuousDistribution): _argnames = ('d1', 'd2') set = Interval(-oo, oo) @staticmethod def check(d1, d2): _value_check(d1 > 0, "Degree of freedom d1 must be positive.") _value_check(d2 > 0, "Degree of freedom d2 must be positive.") def pdf(self, x): d1, d2 = self.d1, self.d2 return (2*d1**(d1/2)*d2**(d2/2) / beta_fn(d1/2, d2/2) * exp(d1*x) / (d1*exp(2*x)+d2)**((d1+d2)/2)) def FisherZ(name, d1, d2): r""" Create a Continuous Random Variable with an Fisher's Z distribution. Explanation =========== The density of the Fisher's Z distribution is given by .. math:: f(x) := \frac{2d_1^{d_1/2} d_2^{d_2/2}} {\mathrm{B}(d_1/2, d_2/2)} \frac{e^{d_1z}}{\left(d_1e^{2z}+d_2\right)^{\left(d_1+d_2\right)/2}} .. TODO - What is the difference between these degrees of freedom? Parameters ========== d1 : ``d_1 > 0`` Degree of freedom. d2 : ``d_2 > 0`` Degree of freedom. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import FisherZ, density >>> from sympy import Symbol, pprint >>> d1 = Symbol("d1", positive=True) >>> d2 = Symbol("d2", positive=True) >>> z = Symbol("z") >>> X = FisherZ("x", d1, d2) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) d1 d2 d1 d2 - -- - -- -- -- 2 2 2 2 / 2*z \ d1*z 2*d1 *d2 *\d1*e + d2/ *e ----------------------------------------- /d1 d2\ B|--, --| \2 2 / References ========== .. [1] https://en.wikipedia.org/wiki/Fisher%27s_z-distribution .. [2] http://mathworld.wolfram.com/Fishersz-Distribution.html """ return rv(name, FisherZDistribution, (d1, d2)) #------------------------------------------------------------------------------- # Frechet distribution --------------------------------------------------------- class FrechetDistribution(SingleContinuousDistribution): _argnames = ('a', 's', 'm') set = Interval(0, oo) @staticmethod def check(a, s, m): _value_check(a > 0, "Shape parameter alpha must be positive.") _value_check(s > 0, "Scale parameter s must be positive.") def __new__(cls, a, s=1, m=0): a, s, m = list(map(sympify, (a, s, m))) return Basic.__new__(cls, a, s, m) def pdf(self, x): a, s, m = self.a, self.s, self.m return a/s * ((x-m)/s)**(-1-a) * exp(-((x-m)/s)**(-a)) def _cdf(self, x): a, s, m = self.a, self.s, self.m return Piecewise((exp(-((x-m)/s)**(-a)), x >= m), (S.Zero, True)) def Frechet(name, a, s=1, m=0): r""" Create a continuous random variable with a Frechet distribution. Explanation =========== The density of the Frechet distribution is given by .. math:: f(x) := \frac{\alpha}{s} \left(\frac{x-m}{s}\right)^{-1-\alpha} e^{-(\frac{x-m}{s})^{-\alpha}} with :math:`x \geq m`. Parameters ========== a : Real number, :math:`a \in \left(0, \infty\right)` the shape s : Real number, :math:`s \in \left(0, \infty\right)` the scale m : Real number, :math:`m \in \left(-\infty, \infty\right)` the minimum Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Frechet, density, cdf >>> from sympy import Symbol >>> a = Symbol("a", positive=True) >>> s = Symbol("s", positive=True) >>> m = Symbol("m", real=True) >>> z = Symbol("z") >>> X = Frechet("x", a, s, m) >>> density(X)(z) a*((-m + z)/s)**(-a - 1)*exp(-1/((-m + z)/s)**a)/s >>> cdf(X)(z) Piecewise((exp(-1/((-m + z)/s)**a), m <= z), (0, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Fr%C3%A9chet_distribution """ return rv(name, FrechetDistribution, (a, s, m)) #------------------------------------------------------------------------------- # Gamma distribution ----------------------------------------------------------- class GammaDistribution(SingleContinuousDistribution): _argnames = ('k', 'theta') set = Interval(0, oo) @staticmethod def check(k, theta): _value_check(k > 0, "k must be positive") _value_check(theta > 0, "Theta must be positive") def pdf(self, x): k, theta = self.k, self.theta return x**(k - 1) * exp(-x/theta) / (gamma(k)*theta**k) def _cdf(self, x): k, theta = self.k, self.theta return Piecewise( (lowergamma(k, S(x)/theta)/gamma(k), x > 0), (S.Zero, True)) def _characteristic_function(self, t): return (1 - self.theta*I*t)**(-self.k) def _moment_generating_function(self, t): return (1- self.theta*t)**(-self.k) def Gamma(name, k, theta): r""" Create a continuous random variable with a Gamma distribution. Explanation =========== The density of the Gamma distribution is given by .. math:: f(x) := \frac{1}{\Gamma(k) \theta^k} x^{k - 1} e^{-\frac{x}{\theta}} with :math:`x \in [0,1]`. Parameters ========== k : Real number, ``k > 0``, a shape theta : Real number, `\theta > 0`, a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Gamma, density, cdf, E, variance >>> from sympy import Symbol, pprint, simplify >>> k = Symbol("k", positive=True) >>> theta = Symbol("theta", positive=True) >>> z = Symbol("z") >>> X = Gamma("x", k, theta) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) -z ----- -k k - 1 theta theta *z *e --------------------- Gamma(k) >>> C = cdf(X, meijerg=True)(z) >>> pprint(C, use_unicode=False) / / z \ |k*lowergamma|k, -----| | \ theta/ <---------------------- for z >= 0 | Gamma(k + 1) | \ 0 otherwise >>> E(X) k*theta >>> V = simplify(variance(X)) >>> pprint(V, use_unicode=False) 2 k*theta References ========== .. [1] https://en.wikipedia.org/wiki/Gamma_distribution .. [2] http://mathworld.wolfram.com/GammaDistribution.html """ return rv(name, GammaDistribution, (k, theta)) #------------------------------------------------------------------------------- # Inverse Gamma distribution --------------------------------------------------- class GammaInverseDistribution(SingleContinuousDistribution): _argnames = ('a', 'b') set = Interval(0, oo) @staticmethod def check(a, b): _value_check(a > 0, "alpha must be positive") _value_check(b > 0, "beta must be positive") def pdf(self, x): a, b = self.a, self.b return b**a/gamma(a) * x**(-a-1) * exp(-b/x) def _cdf(self, x): a, b = self.a, self.b return Piecewise((uppergamma(a,b/x)/gamma(a), x > 0), (S.Zero, True)) def _characteristic_function(self, t): a, b = self.a, self.b return 2 * (-I*b*t)**(a/2) * besselk(a, sqrt(-4*I*b*t)) / gamma(a) def _moment_generating_function(self, t): raise NotImplementedError('The moment generating function for the ' 'gamma inverse distribution does not exist.') def GammaInverse(name, a, b): r""" Create a continuous random variable with an inverse Gamma distribution. Explanation =========== The density of the inverse Gamma distribution is given by .. math:: f(x) := \frac{\beta^\alpha}{\Gamma(\alpha)} x^{-\alpha - 1} \exp\left(\frac{-\beta}{x}\right) with :math:`x > 0`. Parameters ========== a : Real number, `a > 0` a shape b : Real number, `b > 0` a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import GammaInverse, density, cdf >>> from sympy import Symbol, pprint >>> a = Symbol("a", positive=True) >>> b = Symbol("b", positive=True) >>> z = Symbol("z") >>> X = GammaInverse("x", a, b) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) -b --- a -a - 1 z b *z *e --------------- Gamma(a) >>> cdf(X)(z) Piecewise((uppergamma(a, b/z)/gamma(a), z > 0), (0, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Inverse-gamma_distribution """ return rv(name, GammaInverseDistribution, (a, b)) #------------------------------------------------------------------------------- # Gumbel distribution (Maximum and Minimum) -------------------------------------------------------- class GumbelDistribution(SingleContinuousDistribution): _argnames = ('beta', 'mu', 'minimum') set = Interval(-oo, oo) @staticmethod def check(beta, mu, minimum): _value_check(beta > 0, "Scale parameter beta must be positive.") def pdf(self, x): beta, mu = self.beta, self.mu z = (x - mu)/beta f_max = (1/beta)*exp(-z - exp(-z)) f_min = (1/beta)*exp(z - exp(z)) return Piecewise((f_min, self.minimum), (f_max, not self.minimum)) def _cdf(self, x): beta, mu = self.beta, self.mu z = (x - mu)/beta F_max = exp(-exp(-z)) F_min = 1 - exp(-exp(z)) return Piecewise((F_min, self.minimum), (F_max, not self.minimum)) def _characteristic_function(self, t): cf_max = gamma(1 - I*self.beta*t) * exp(I*self.mu*t) cf_min = gamma(1 + I*self.beta*t) * exp(I*self.mu*t) return Piecewise((cf_min, self.minimum), (cf_max, not self.minimum)) def _moment_generating_function(self, t): mgf_max = gamma(1 - self.beta*t) * exp(self.mu*t) mgf_min = gamma(1 + self.beta*t) * exp(self.mu*t) return Piecewise((mgf_min, self.minimum), (mgf_max, not self.minimum)) def Gumbel(name, beta, mu, minimum=False): r""" Create a Continuous Random Variable with Gumbel distribution. Explanation =========== The density of the Gumbel distribution is given by For Maximum .. math:: f(x) := \dfrac{1}{\beta} \exp \left( -\dfrac{x-\mu}{\beta} - \exp \left( -\dfrac{x - \mu}{\beta} \right) \right) with :math:`x \in [ - \infty, \infty ]`. For Minimum .. math:: f(x) := \frac{e^{- e^{\frac{- \mu + x}{\beta}} + \frac{- \mu + x}{\beta}}}{\beta} with :math:`x \in [ - \infty, \infty ]`. Parameters ========== mu : Real number, 'mu' is a location beta : Real number, 'beta > 0' is a scale minimum : Boolean, by default, False, set to True for enabling minimum distribution Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Gumbel, density, cdf >>> from sympy import Symbol >>> x = Symbol("x") >>> mu = Symbol("mu") >>> beta = Symbol("beta", positive=True) >>> X = Gumbel("x", beta, mu) >>> density(X)(x) exp(-exp(-(-mu + x)/beta) - (-mu + x)/beta)/beta >>> cdf(X)(x) exp(-exp(-(-mu + x)/beta)) References ========== .. [1] http://mathworld.wolfram.com/GumbelDistribution.html .. [2] https://en.wikipedia.org/wiki/Gumbel_distribution .. [3] http://www.mathwave.com/help/easyfit/html/analyses/distributions/gumbel_max.html .. [4] http://www.mathwave.com/help/easyfit/html/analyses/distributions/gumbel_min.html """ return rv(name, GumbelDistribution, (beta, mu, minimum)) #------------------------------------------------------------------------------- # Gompertz distribution -------------------------------------------------------- class GompertzDistribution(SingleContinuousDistribution): _argnames = ('b', 'eta') set = Interval(0, oo) @staticmethod def check(b, eta): _value_check(b > 0, "b must be positive") _value_check(eta > 0, "eta must be positive") def pdf(self, x): eta, b = self.eta, self.b return b*eta*exp(b*x)*exp(eta)*exp(-eta*exp(b*x)) def _cdf(self, x): eta, b = self.eta, self.b return 1 - exp(eta)*exp(-eta*exp(b*x)) def _moment_generating_function(self, t): eta, b = self.eta, self.b return eta * exp(eta) * expint(t/b, eta) def Gompertz(name, b, eta): r""" Create a Continuous Random Variable with Gompertz distribution. Explanation =========== The density of the Gompertz distribution is given by .. math:: f(x) := b \eta e^{b x} e^{\eta} \exp \left(-\eta e^{bx} \right) with :math: 'x \in [0, \inf)'. Parameters ========== b: Real number, 'b > 0' a scale eta: Real number, 'eta > 0' a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Gompertz, density >>> from sympy import Symbol >>> b = Symbol("b", positive=True) >>> eta = Symbol("eta", positive=True) >>> z = Symbol("z") >>> X = Gompertz("x", b, eta) >>> density(X)(z) b*eta*exp(eta)*exp(b*z)*exp(-eta*exp(b*z)) References ========== .. [1] https://en.wikipedia.org/wiki/Gompertz_distribution """ return rv(name, GompertzDistribution, (b, eta)) #------------------------------------------------------------------------------- # Kumaraswamy distribution ----------------------------------------------------- class KumaraswamyDistribution(SingleContinuousDistribution): _argnames = ('a', 'b') set = Interval(0, oo) @staticmethod def check(a, b): _value_check(a > 0, "a must be positive") _value_check(b > 0, "b must be positive") def pdf(self, x): a, b = self.a, self.b return a * b * x**(a-1) * (1-x**a)**(b-1) def _cdf(self, x): a, b = self.a, self.b return Piecewise( (S.Zero, x < S.Zero), (1 - (1 - x**a)**b, x <= S.One), (S.One, True)) def Kumaraswamy(name, a, b): r""" Create a Continuous Random Variable with a Kumaraswamy distribution. Explanation =========== The density of the Kumaraswamy distribution is given by .. math:: f(x) := a b x^{a-1} (1-x^a)^{b-1} with :math:`x \in [0,1]`. Parameters ========== a : Real number, ``a > 0`` a shape b : Real number, ``b > 0`` a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Kumaraswamy, density, cdf >>> from sympy import Symbol, pprint >>> a = Symbol("a", positive=True) >>> b = Symbol("b", positive=True) >>> z = Symbol("z") >>> X = Kumaraswamy("x", a, b) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) b - 1 a - 1 / a\ a*b*z *\1 - z / >>> cdf(X)(z) Piecewise((0, z < 0), (1 - (1 - z**a)**b, z <= 1), (1, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Kumaraswamy_distribution """ return rv(name, KumaraswamyDistribution, (a, b)) #------------------------------------------------------------------------------- # Laplace distribution --------------------------------------------------------- class LaplaceDistribution(SingleContinuousDistribution): _argnames = ('mu', 'b') set = Interval(-oo, oo) @staticmethod def check(mu, b): _value_check(b > 0, "Scale parameter b must be positive.") _value_check(mu.is_real, "Location parameter mu should be real") def pdf(self, x): mu, b = self.mu, self.b return 1/(2*b)*exp(-Abs(x - mu)/b) def _cdf(self, x): mu, b = self.mu, self.b return Piecewise( (S.Half*exp((x - mu)/b), x < mu), (S.One - S.Half*exp(-(x - mu)/b), x >= mu) ) def _characteristic_function(self, t): return exp(self.mu*I*t) / (1 + self.b**2*t**2) def _moment_generating_function(self, t): return exp(self.mu*t) / (1 - self.b**2*t**2) def Laplace(name, mu, b): r""" Create a continuous random variable with a Laplace distribution. Explanation =========== The density of the Laplace distribution is given by .. math:: f(x) := \frac{1}{2 b} \exp \left(-\frac{|x-\mu|}b \right) Parameters ========== mu : Real number or a list/matrix, the location (mean) or the location vector b : Real number or a positive definite matrix, representing a scale or the covariance matrix. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Laplace, density, cdf >>> from sympy import Symbol, pprint >>> mu = Symbol("mu") >>> b = Symbol("b", positive=True) >>> z = Symbol("z") >>> X = Laplace("x", mu, b) >>> density(X)(z) exp(-Abs(mu - z)/b)/(2*b) >>> cdf(X)(z) Piecewise((exp((-mu + z)/b)/2, mu > z), (1 - exp((mu - z)/b)/2, True)) >>> L = Laplace('L', [1, 2], [[1, 0], [0, 1]]) >>> pprint(density(L)(1, 2), use_unicode=False) 5 / ____\ e *besselk\0, \/ 35 / --------------------- pi References ========== .. [1] https://en.wikipedia.org/wiki/Laplace_distribution .. [2] http://mathworld.wolfram.com/LaplaceDistribution.html """ if isinstance(mu, (list, MatrixBase)) and\ isinstance(b, (list, MatrixBase)): from sympy.stats.joint_rv_types import MultivariateLaplace return MultivariateLaplace(name, mu, b) return rv(name, LaplaceDistribution, (mu, b)) #------------------------------------------------------------------------------- # Levy distribution --------------------------------------------------------- class LevyDistribution(SingleContinuousDistribution): _argnames = ('mu', 'c') @property def set(self): return Interval(self.mu, oo) @staticmethod def check(mu, c): _value_check(c > 0, "c (scale parameter) must be positive") _value_check(mu.is_real, "mu (location paramater) must be real") def pdf(self, x): mu, c = self.mu, self.c return sqrt(c/(2*pi))*exp(-c/(2*(x - mu)))/((x - mu)**(S.One + S.Half)) def _cdf(self, x): mu, c = self.mu, self.c return erfc(sqrt(c/(2*(x - mu)))) def _characteristic_function(self, t): mu, c = self.mu, self.c return exp(I * mu * t - sqrt(-2 * I * c * t)) def _moment_generating_function(self, t): raise NotImplementedError('The moment generating function of Levy distribution does not exist.') def Levy(name, mu, c): r""" Create a continuous random variable with a Levy distribution. The density of the Levy distribution is given by .. math:: f(x) := \sqrt(\frac{c}{2 \pi}) \frac{\exp -\frac{c}{2 (x - \mu)}}{(x - \mu)^{3/2}} Parameters ========== mu : Real number The location parameter. c : Real number, ``c > 0`` A scale parameter. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Levy, density, cdf >>> from sympy import Symbol >>> mu = Symbol("mu", real=True) >>> c = Symbol("c", positive=True) >>> z = Symbol("z") >>> X = Levy("x", mu, c) >>> density(X)(z) sqrt(2)*sqrt(c)*exp(-c/(-2*mu + 2*z))/(2*sqrt(pi)*(-mu + z)**(3/2)) >>> cdf(X)(z) erfc(sqrt(c)*sqrt(1/(-2*mu + 2*z))) References ========== .. [1] https://en.wikipedia.org/wiki/L%C3%A9vy_distribution .. [2] http://mathworld.wolfram.com/LevyDistribution.html """ return rv(name, LevyDistribution, (mu, c)) #------------------------------------------------------------------------------- # Log-Cauchy distribution -------------------------------------------------------- class LogCauchyDistribution(SingleContinuousDistribution): _argnames = ('mu', 'sigma') set = Interval.open(0, oo) @staticmethod def check(mu, sigma): _value_check((sigma > 0) != False, "Scale parameter Gamma must be positive.") _value_check(mu.is_real != False, "Location parameter must be real.") def pdf(self, x): mu, sigma = self.mu, self.sigma return 1/(x*pi)*(sigma/((log(x) - mu)**2 + sigma**2)) def _cdf(self, x): mu, sigma = self.mu, self.sigma return (1/pi)*atan((log(x) - mu)/sigma) + S.Half def _characteristic_function(self, t): raise NotImplementedError("The characteristic function for the " "Log-Cauchy distribution does not exist.") def _moment_generating_function(self, t): raise NotImplementedError("The moment generating function for the " "Log-Cauchy distribution does not exist.") def LogCauchy(name, mu, sigma): r""" Create a continuous random variable with a Log-Cauchy distribution. The density of the Log-Cauchy distribution is given by .. math:: f(x) := \frac{1}{\pi x} \frac{\sigma}{(log(x)-\mu^2) + \sigma^2} Parameters ========== mu : Real number, the location sigma : Real number, `\sigma > 0`, a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import LogCauchy, density, cdf >>> from sympy import Symbol, S >>> mu = 2 >>> sigma = S.One / 5 >>> z = Symbol("z") >>> X = LogCauchy("x", mu, sigma) >>> density(X)(z) 1/(5*pi*z*((log(z) - 2)**2 + 1/25)) >>> cdf(X)(z) atan(5*log(z) - 10)/pi + 1/2 References ========== .. [1] https://en.wikipedia.org/wiki/Log-Cauchy_distribution """ return rv(name, LogCauchyDistribution, (mu, sigma)) #------------------------------------------------------------------------------- # Logistic distribution -------------------------------------------------------- class LogisticDistribution(SingleContinuousDistribution): _argnames = ('mu', 's') set = Interval(-oo, oo) @staticmethod def check(mu, s): _value_check(s > 0, "Scale parameter s must be positive.") def pdf(self, x): mu, s = self.mu, self.s return exp(-(x - mu)/s)/(s*(1 + exp(-(x - mu)/s))**2) def _cdf(self, x): mu, s = self.mu, self.s return S.One/(1 + exp(-(x - mu)/s)) def _characteristic_function(self, t): return Piecewise((exp(I*t*self.mu) * pi*self.s*t / sinh(pi*self.s*t), Ne(t, 0)), (S.One, True)) def _moment_generating_function(self, t): return exp(self.mu*t) * beta_fn(1 - self.s*t, 1 + self.s*t) def _quantile(self, p): return self.mu - self.s*log(-S.One + S.One/p) def Logistic(name, mu, s): r""" Create a continuous random variable with a logistic distribution. Explanation =========== The density of the logistic distribution is given by .. math:: f(x) := \frac{e^{-(x-\mu)/s}} {s\left(1+e^{-(x-\mu)/s}\right)^2} Parameters ========== mu : Real number, the location (mean) s : Real number, `s > 0` a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Logistic, density, cdf >>> from sympy import Symbol >>> mu = Symbol("mu", real=True) >>> s = Symbol("s", positive=True) >>> z = Symbol("z") >>> X = Logistic("x", mu, s) >>> density(X)(z) exp((mu - z)/s)/(s*(exp((mu - z)/s) + 1)**2) >>> cdf(X)(z) 1/(exp((mu - z)/s) + 1) References ========== .. [1] https://en.wikipedia.org/wiki/Logistic_distribution .. [2] http://mathworld.wolfram.com/LogisticDistribution.html """ return rv(name, LogisticDistribution, (mu, s)) #------------------------------------------------------------------------------- # Log-logistic distribution -------------------------------------------------------- class LogLogisticDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta') set = Interval(0, oo) @staticmethod def check(alpha, beta): _value_check(alpha > 0, "Scale parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") def pdf(self, x): a, b = self.alpha, self.beta return ((b/a)*(x/a)**(b - 1))/(1 + (x/a)**b)**2 def _cdf(self, x): a, b = self.alpha, self.beta return 1/(1 + (x/a)**(-b)) def _quantile(self, p): a, b = self.alpha, self.beta return a*((p/(1 - p))**(1/b)) def expectation(self, expr, var, **kwargs): a, b = self.args return Piecewise((S.NaN, b <= 1), (pi*a/(b*sin(pi/b)), True)) def LogLogistic(name, alpha, beta): r""" Create a continuous random variable with a log-logistic distribution. The distribution is unimodal when ``beta > 1``. Explanation =========== The density of the log-logistic distribution is given by .. math:: f(x) := \frac{(\frac{\beta}{\alpha})(\frac{x}{\alpha})^{\beta - 1}} {(1 + (\frac{x}{\alpha})^{\beta})^2} Parameters ========== alpha : Real number, `\alpha > 0`, scale parameter and median of distribution beta : Real number, `\beta > 0` a shape parameter Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import LogLogistic, density, cdf, quantile >>> from sympy import Symbol, pprint >>> alpha = Symbol("alpha", real=True, positive=True) >>> beta = Symbol("beta", real=True, positive=True) >>> p = Symbol("p") >>> z = Symbol("z", positive=True) >>> X = LogLogistic("x", alpha, beta) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) beta - 1 / z \ beta*|-----| \alpha/ ------------------------ 2 / beta \ |/ z \ | alpha*||-----| + 1| \\alpha/ / >>> cdf(X)(z) 1/(1 + (z/alpha)**(-beta)) >>> quantile(X)(p) alpha*(p/(1 - p))**(1/beta) References ========== .. [1] https://en.wikipedia.org/wiki/Log-logistic_distribution """ return rv(name, LogLogisticDistribution, (alpha, beta)) #------------------------------------------------------------------------------- #Logit-Normal distribution------------------------------------------------------ class LogitNormalDistribution(SingleContinuousDistribution): _argnames = ('mu', 's') set = Interval.open(0, 1) @staticmethod def check(mu, s): _value_check((s ** 2).is_real is not False and s ** 2 > 0, "Squared scale parameter s must be positive.") _value_check(mu.is_real is not False, "Location parameter must be real") def _logit(self, x): return log(x / (1 - x)) def pdf(self, x): mu, s = self.mu, self.s return exp(-(self._logit(x) - mu)**2/(2*s**2))*(S.One/sqrt(2*pi*(s**2)))*(1/(x*(1 - x))) def _cdf(self, x): mu, s = self.mu, self.s return (S.One/2)*(1 + erf((self._logit(x) - mu)/(sqrt(2*s**2)))) def LogitNormal(name, mu, s): r""" Create a continuous random variable with a Logit-Normal distribution. The density of the logistic distribution is given by .. math:: f(x) := \frac{1}{s \sqrt{2 \pi}} \frac{1}{x(1 - x)} e^{- \frac{(logit(x) - \mu)^2}{s^2}} where logit(x) = \log(\frac{x}{1 - x}) Parameters ========== mu : Real number, the location (mean) s : Real number, `s > 0` a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import LogitNormal, density, cdf >>> from sympy import Symbol,pprint >>> mu = Symbol("mu", real=True) >>> s = Symbol("s", positive=True) >>> z = Symbol("z") >>> X = LogitNormal("x",mu,s) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) 2 / / z \\ -|-mu + log|-----|| \ \1 - z// --------------------- 2 ___ 2*s \/ 2 *e ---------------------------- ____ 2*\/ pi *s*z*(1 - z) >>> density(X)(z) sqrt(2)*exp(-(-mu + log(z/(1 - z)))**2/(2*s**2))/(2*sqrt(pi)*s*z*(1 - z)) >>> cdf(X)(z) erf(sqrt(2)*(-mu + log(z/(1 - z)))/(2*s))/2 + 1/2 References ========== .. [1] https://en.wikipedia.org/wiki/Logit-normal_distribution """ return rv(name, LogitNormalDistribution, (mu, s)) #------------------------------------------------------------------------------- # Log Normal distribution ------------------------------------------------------ class LogNormalDistribution(SingleContinuousDistribution): _argnames = ('mean', 'std') set = Interval(0, oo) @staticmethod def check(mean, std): _value_check(std > 0, "Parameter std must be positive.") def pdf(self, x): mean, std = self.mean, self.std return exp(-(log(x) - mean)**2 / (2*std**2)) / (x*sqrt(2*pi)*std) def _cdf(self, x): mean, std = self.mean, self.std return Piecewise( (S.Half + S.Half*erf((log(x) - mean)/sqrt(2)/std), x > 0), (S.Zero, True) ) def _moment_generating_function(self, t): raise NotImplementedError('Moment generating function of the log-normal distribution is not defined.') def LogNormal(name, mean, std): r""" Create a continuous random variable with a log-normal distribution. Explanation =========== The density of the log-normal distribution is given by .. math:: f(x) := \frac{1}{x\sqrt{2\pi\sigma^2}} e^{-\frac{\left(\ln x-\mu\right)^2}{2\sigma^2}} with :math:`x \geq 0`. Parameters ========== mu : Real number The log-scale. sigma : Real number A shape. ($\sigma^2 > 0$) Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import LogNormal, density >>> from sympy import Symbol, pprint >>> mu = Symbol("mu", real=True) >>> sigma = Symbol("sigma", positive=True) >>> z = Symbol("z") >>> X = LogNormal("x", mu, sigma) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) 2 -(-mu + log(z)) ----------------- 2 ___ 2*sigma \/ 2 *e ------------------------ ____ 2*\/ pi *sigma*z >>> X = LogNormal('x', 0, 1) # Mean 0, standard deviation 1 >>> density(X)(z) sqrt(2)*exp(-log(z)**2/2)/(2*sqrt(pi)*z) References ========== .. [1] https://en.wikipedia.org/wiki/Lognormal .. [2] http://mathworld.wolfram.com/LogNormalDistribution.html """ return rv(name, LogNormalDistribution, (mean, std)) #------------------------------------------------------------------------------- # Lomax Distribution ----------------------------------------------------------- class LomaxDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'lamda',) set = Interval(0, oo) @staticmethod def check(alpha, lamda): _value_check(alpha.is_real, "Shape parameter should be real.") _value_check(lamda.is_real, "Scale parameter should be real.") _value_check(alpha.is_positive, "Shape parameter should be positive.") _value_check(lamda.is_positive, "Scale parameter should be positive.") def pdf(self, x): lamba, alpha = self.lamda, self.alpha return (alpha/lamba) * (S.One + x/lamba)**(-alpha-1) def Lomax(name, alpha, lamda): r""" Create a continuous random variable with a Lomax distribution. Explanation =========== The density of the Lomax distribution is given by .. math:: f(x) := \frac{\alpha}{\lambda}\left[1+\frac{x}{\lambda}\right]^{-(\alpha+1)} Parameters ========== alpha : Real Number, `alpha > 0` Shape parameter lamda : Real Number, `lamda > 0` Scale parameter Examples ======== >>> from sympy.stats import Lomax, density, cdf, E >>> from sympy import symbols >>> a, l = symbols('a, l', positive=True) >>> X = Lomax('X', a, l) >>> x = symbols('x') >>> density(X)(x) a*(1 + x/l)**(-a - 1)/l >>> cdf(X)(x) Piecewise((1 - 1/(1 + x/l)**a, x >= 0), (0, True)) >>> a = 2 >>> X = Lomax('X', a, l) >>> E(X) l Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Lomax_distribution """ return rv(name, LomaxDistribution, (alpha, lamda)) #------------------------------------------------------------------------------- # Maxwell distribution --------------------------------------------------------- class MaxwellDistribution(SingleContinuousDistribution): _argnames = ('a',) set = Interval(0, oo) @staticmethod def check(a): _value_check(a > 0, "Parameter a must be positive.") def pdf(self, x): a = self.a return sqrt(2/pi)*x**2*exp(-x**2/(2*a**2))/a**3 def _cdf(self, x): a = self.a return erf(sqrt(2)*x/(2*a)) - sqrt(2)*x*exp(-x**2/(2*a**2))/(sqrt(pi)*a) def Maxwell(name, a): r""" Create a continuous random variable with a Maxwell distribution. Explanation =========== The density of the Maxwell distribution is given by .. math:: f(x) := \sqrt{\frac{2}{\pi}} \frac{x^2 e^{-x^2/(2a^2)}}{a^3} with :math:`x \geq 0`. .. TODO - what does the parameter mean? Parameters ========== a : Real number, `a > 0` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Maxwell, density, E, variance >>> from sympy import Symbol, simplify >>> a = Symbol("a", positive=True) >>> z = Symbol("z") >>> X = Maxwell("x", a) >>> density(X)(z) sqrt(2)*z**2*exp(-z**2/(2*a**2))/(sqrt(pi)*a**3) >>> E(X) 2*sqrt(2)*a/sqrt(pi) >>> simplify(variance(X)) a**2*(-8 + 3*pi)/pi References ========== .. [1] https://en.wikipedia.org/wiki/Maxwell_distribution .. [2] http://mathworld.wolfram.com/MaxwellDistribution.html """ return rv(name, MaxwellDistribution, (a, )) #------------------------------------------------------------------------------- # Moyal Distribution ----------------------------------------------------------- class MoyalDistribution(SingleContinuousDistribution): _argnames = ('mu', 'sigma') @staticmethod def check(mu, sigma): _value_check(mu.is_real, "Location parameter must be real.") _value_check(sigma.is_real and sigma > 0, "Scale parameter must be real\ and positive.") def pdf(self, x): mu, sigma = self.mu, self.sigma num = exp(-(exp(-(x - mu)/sigma) + (x - mu)/(sigma))/2) den = (sqrt(2*pi) * sigma) return num/den def _characteristic_function(self, t): mu, sigma = self.mu, self.sigma term1 = exp(I*t*mu) term2 = (2**(-I*sigma*t) * gamma(Rational(1, 2) - I*t*sigma)) return (term1 * term2)/sqrt(pi) def _moment_generating_function(self, t): mu, sigma = self.mu, self.sigma term1 = exp(t*mu) term2 = (2**(-1*sigma*t) * gamma(Rational(1, 2) - t*sigma)) return (term1 * term2)/sqrt(pi) def Moyal(name, mu, sigma): r""" Create a continuous random variable with a Moyal distribution. Explanation =========== The density of the Moyal distribution is given by .. math:: f(x) := \frac{\exp-\frac{1}{2}\exp-\frac{x-\mu}{\sigma}-\frac{x-\mu}{2\sigma}}{\sqrt{2\pi}\sigma} with :math:`x \in \mathbb{R}`. Parameters ========== mu : Real number Location parameter sigma : Real positive number Scale parameter Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Moyal, density, cdf >>> from sympy import Symbol, simplify >>> mu = Symbol("mu", real=True) >>> sigma = Symbol("sigma", positive=True, real=True) >>> z = Symbol("z") >>> X = Moyal("x", mu, sigma) >>> density(X)(z) sqrt(2)*exp(-exp((mu - z)/sigma)/2 - (-mu + z)/(2*sigma))/(2*sqrt(pi)*sigma) >>> simplify(cdf(X)(z)) 1 - erf(sqrt(2)*exp((mu - z)/(2*sigma))/2) References ========== .. [1] https://reference.wolfram.com/language/ref/MoyalDistribution.html .. [2] http://www.stat.rice.edu/~dobelman/textfiles/DistributionsHandbook.pdf """ return rv(name, MoyalDistribution, (mu, sigma)) #------------------------------------------------------------------------------- # Nakagami distribution -------------------------------------------------------- class NakagamiDistribution(SingleContinuousDistribution): _argnames = ('mu', 'omega') set = Interval(0, oo) @staticmethod def check(mu, omega): _value_check(mu >= S.Half, "Shape parameter mu must be greater than equal to 1/2.") _value_check(omega > 0, "Spread parameter omega must be positive.") def pdf(self, x): mu, omega = self.mu, self.omega return 2*mu**mu/(gamma(mu)*omega**mu)*x**(2*mu - 1)*exp(-mu/omega*x**2) def _cdf(self, x): mu, omega = self.mu, self.omega return Piecewise( (lowergamma(mu, (mu/omega)*x**2)/gamma(mu), x > 0), (S.Zero, True)) def Nakagami(name, mu, omega): r""" Create a continuous random variable with a Nakagami distribution. Explanation =========== The density of the Nakagami distribution is given by .. math:: f(x) := \frac{2\mu^\mu}{\Gamma(\mu)\omega^\mu} x^{2\mu-1} \exp\left(-\frac{\mu}{\omega}x^2 \right) with :math:`x > 0`. Parameters ========== mu : Real number, `\mu \geq \frac{1}{2}` a shape omega : Real number, `\omega > 0`, the spread Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Nakagami, density, E, variance, cdf >>> from sympy import Symbol, simplify, pprint >>> mu = Symbol("mu", positive=True) >>> omega = Symbol("omega", positive=True) >>> z = Symbol("z") >>> X = Nakagami("x", mu, omega) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) 2 -mu*z ------- mu -mu 2*mu - 1 omega 2*mu *omega *z *e ---------------------------------- Gamma(mu) >>> simplify(E(X)) sqrt(mu)*sqrt(omega)*gamma(mu + 1/2)/gamma(mu + 1) >>> V = simplify(variance(X)) >>> pprint(V, use_unicode=False) 2 omega*Gamma (mu + 1/2) omega - ----------------------- Gamma(mu)*Gamma(mu + 1) >>> cdf(X)(z) Piecewise((lowergamma(mu, mu*z**2/omega)/gamma(mu), z > 0), (0, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Nakagami_distribution """ return rv(name, NakagamiDistribution, (mu, omega)) #------------------------------------------------------------------------------- # Normal distribution ---------------------------------------------------------- class NormalDistribution(SingleContinuousDistribution): _argnames = ('mean', 'std') @staticmethod def check(mean, std): _value_check(std > 0, "Standard deviation must be positive") def pdf(self, x): return exp(-(x - self.mean)**2 / (2*self.std**2)) / (sqrt(2*pi)*self.std) def _cdf(self, x): mean, std = self.mean, self.std return erf(sqrt(2)*(-mean + x)/(2*std))/2 + S.Half def _characteristic_function(self, t): mean, std = self.mean, self.std return exp(I*mean*t - std**2*t**2/2) def _moment_generating_function(self, t): mean, std = self.mean, self.std return exp(mean*t + std**2*t**2/2) def _quantile(self, p): mean, std = self.mean, self.std return mean + std*sqrt(2)*erfinv(2*p - 1) def Normal(name, mean, std): r""" Create a continuous random variable with a Normal distribution. Explanation =========== The density of the Normal distribution is given by .. math:: f(x) := \frac{1}{\sigma\sqrt{2\pi}} e^{ -\frac{(x-\mu)^2}{2\sigma^2} } Parameters ========== mu : Real number or a list representing the mean or the mean vector sigma : Real number or a positive definite square matrix, :math:`\sigma^2 > 0` the variance Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Normal, density, E, std, cdf, skewness, quantile, marginal_distribution >>> from sympy import Symbol, simplify, pprint >>> mu = Symbol("mu") >>> sigma = Symbol("sigma", positive=True) >>> z = Symbol("z") >>> y = Symbol("y") >>> p = Symbol("p") >>> X = Normal("x", mu, sigma) >>> density(X)(z) sqrt(2)*exp(-(-mu + z)**2/(2*sigma**2))/(2*sqrt(pi)*sigma) >>> C = simplify(cdf(X))(z) # it needs a little more help... >>> pprint(C, use_unicode=False) / ___ \ |\/ 2 *(-mu + z)| erf|---------------| \ 2*sigma / 1 -------------------- + - 2 2 >>> quantile(X)(p) mu + sqrt(2)*sigma*erfinv(2*p - 1) >>> simplify(skewness(X)) 0 >>> X = Normal("x", 0, 1) # Mean 0, standard deviation 1 >>> density(X)(z) sqrt(2)*exp(-z**2/2)/(2*sqrt(pi)) >>> E(2*X + 1) 1 >>> simplify(std(2*X + 1)) 2 >>> m = Normal('X', [1, 2], [[2, 1], [1, 2]]) >>> pprint(density(m)(y, z), use_unicode=False) 2 2 y y*z z - -- + --- - -- + z - 1 ___ 3 3 3 \/ 3 *e ------------------------------ 6*pi >>> marginal_distribution(m, m[0])(1) 1/(2*sqrt(pi)) References ========== .. [1] https://en.wikipedia.org/wiki/Normal_distribution .. [2] http://mathworld.wolfram.com/NormalDistributionFunction.html """ if isinstance(mean, list) or getattr(mean, 'is_Matrix', False) and\ isinstance(std, list) or getattr(std, 'is_Matrix', False): from sympy.stats.joint_rv_types import MultivariateNormal return MultivariateNormal(name, mean, std) return rv(name, NormalDistribution, (mean, std)) #------------------------------------------------------------------------------- # Inverse Gaussian distribution ---------------------------------------------------------- class GaussianInverseDistribution(SingleContinuousDistribution): _argnames = ('mean', 'shape') @property def set(self): return Interval(0, oo) @staticmethod def check(mean, shape): _value_check(shape > 0, "Shape parameter must be positive") _value_check(mean > 0, "Mean must be positive") def pdf(self, x): mu, s = self.mean, self.shape return exp(-s*(x - mu)**2 / (2*x*mu**2)) * sqrt(s/(2*pi*x**3)) def _cdf(self, x): from sympy.stats import cdf mu, s = self.mean, self.shape stdNormalcdf = cdf(Normal('x', 0, 1)) first_term = stdNormalcdf(sqrt(s/x) * ((x/mu) - S.One)) second_term = exp(2*s/mu) * stdNormalcdf(-sqrt(s/x)*(x/mu + S.One)) return first_term + second_term def _characteristic_function(self, t): mu, s = self.mean, self.shape return exp((s/mu)*(1 - sqrt(1 - (2*mu**2*I*t)/s))) def _moment_generating_function(self, t): mu, s = self.mean, self.shape return exp((s/mu)*(1 - sqrt(1 - (2*mu**2*t)/s))) def GaussianInverse(name, mean, shape): r""" Create a continuous random variable with an Inverse Gaussian distribution. Inverse Gaussian distribution is also known as Wald distribution. Explanation =========== The density of the Inverse Gaussian distribution is given by .. math:: f(x) := \sqrt{\frac{\lambda}{2\pi x^3}} e^{-\frac{\lambda(x-\mu)^2}{2x\mu^2}} Parameters ========== mu : Positive number representing the mean. lambda : Positive number representing the shape parameter. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import GaussianInverse, density, E, std, skewness >>> from sympy import Symbol, pprint >>> mu = Symbol("mu", positive=True) >>> lamda = Symbol("lambda", positive=True) >>> z = Symbol("z", positive=True) >>> X = GaussianInverse("x", mu, lamda) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) 2 -lambda*(-mu + z) ------------------- 2 ___ ________ 2*mu *z \/ 2 *\/ lambda *e ------------------------------------- ____ 3/2 2*\/ pi *z >>> E(X) mu >>> std(X).expand() mu**(3/2)/sqrt(lambda) >>> skewness(X).expand() 3*sqrt(mu)/sqrt(lambda) References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution .. [2] http://mathworld.wolfram.com/InverseGaussianDistribution.html """ return rv(name, GaussianInverseDistribution, (mean, shape)) Wald = GaussianInverse #------------------------------------------------------------------------------- # Pareto distribution ---------------------------------------------------------- class ParetoDistribution(SingleContinuousDistribution): _argnames = ('xm', 'alpha') @property def set(self): return Interval(self.xm, oo) @staticmethod def check(xm, alpha): _value_check(xm > 0, "Xm must be positive") _value_check(alpha > 0, "Alpha must be positive") def pdf(self, x): xm, alpha = self.xm, self.alpha return alpha * xm**alpha / x**(alpha + 1) def _cdf(self, x): xm, alpha = self.xm, self.alpha return Piecewise( (S.One - xm**alpha/x**alpha, x>=xm), (0, True), ) def _moment_generating_function(self, t): xm, alpha = self.xm, self.alpha return alpha * (-xm*t)**alpha * uppergamma(-alpha, -xm*t) def _characteristic_function(self, t): xm, alpha = self.xm, self.alpha return alpha * (-I * xm * t) ** alpha * uppergamma(-alpha, -I * xm * t) def Pareto(name, xm, alpha): r""" Create a continuous random variable with the Pareto distribution. Explanation =========== The density of the Pareto distribution is given by .. math:: f(x) := \frac{\alpha\,x_m^\alpha}{x^{\alpha+1}} with :math:`x \in [x_m,\infty]`. Parameters ========== xm : Real number, `x_m > 0`, a scale alpha : Real number, `\alpha > 0`, a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Pareto, density >>> from sympy import Symbol >>> xm = Symbol("xm", positive=True) >>> beta = Symbol("beta", positive=True) >>> z = Symbol("z") >>> X = Pareto("x", xm, beta) >>> density(X)(z) beta*xm**beta*z**(-beta - 1) References ========== .. [1] https://en.wikipedia.org/wiki/Pareto_distribution .. [2] http://mathworld.wolfram.com/ParetoDistribution.html """ return rv(name, ParetoDistribution, (xm, alpha)) #------------------------------------------------------------------------------- # PowerFunction distribution --------------------------------------------------- class PowerFunctionDistribution(SingleContinuousDistribution): _argnames=('alpha','a','b') @property def set(self): return Interval(self.a, self.b) @staticmethod def check(alpha, a, b): _value_check(a.is_real, "Continuous Boundary parameter should be real.") _value_check(b.is_real, "Continuous Boundary parameter should be real.") _value_check(a < b, " 'a' the left Boundary must be smaller than 'b' the right Boundary." ) _value_check(alpha.is_positive, "Continuous Shape parameter should be positive.") def pdf(self, x): alpha, a, b = self.alpha, self.a, self.b num = alpha*(x - a)**(alpha - 1) den = (b - a)**alpha return num/den def PowerFunction(name, alpha, a, b): r""" Creates a continuous random variable with a Power Function Distribution. Explanation =========== The density of PowerFunction distribution is given by .. math:: f(x) := \frac{{\alpha}(x - a)^{\alpha - 1}}{(b - a)^{\alpha}} with :math:`x \in [a,b]`. Parameters ========== alpha: Positive number, `0 < alpha` the shape paramater a : Real number, :math:`-\infty < a` the left boundary b : Real number, :math:`a < b < \infty` the right boundary Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import PowerFunction, density, cdf, E, variance >>> from sympy import Symbol >>> alpha = Symbol("alpha", positive=True) >>> a = Symbol("a", real=True) >>> b = Symbol("b", real=True) >>> z = Symbol("z") >>> X = PowerFunction("X", 2, a, b) >>> density(X)(z) (-2*a + 2*z)/(-a + b)**2 >>> cdf(X)(z) Piecewise((a**2/(a**2 - 2*a*b + b**2) - 2*a*z/(a**2 - 2*a*b + b**2) + z**2/(a**2 - 2*a*b + b**2), a <= z), (0, True)) >>> alpha = 2 >>> a = 0 >>> b = 1 >>> Y = PowerFunction("Y", alpha, a, b) >>> E(Y) 2/3 >>> variance(Y) 1/18 References ========== .. [1] http://www.mathwave.com/help/easyfit/html/analyses/distributions/power_func.html """ return rv(name, PowerFunctionDistribution, (alpha, a, b)) #------------------------------------------------------------------------------- # QuadraticU distribution ------------------------------------------------------ class QuadraticUDistribution(SingleContinuousDistribution): _argnames = ('a', 'b') @property def set(self): return Interval(self.a, self.b) @staticmethod def check(a, b): _value_check(b > a, "Parameter b must be in range (%s, oo)."%(a)) def pdf(self, x): a, b = self.a, self.b alpha = 12 / (b-a)**3 beta = (a+b) / 2 return Piecewise( (alpha * (x-beta)**2, And(a<=x, x<=b)), (S.Zero, True)) def _moment_generating_function(self, t): a, b = self.a, self.b return -3 * (exp(a*t) * (4 + (a**2 + 2*a*(-2 + b) + b**2) * t) \ - exp(b*t) * (4 + (-4*b + (a + b)**2) * t)) / ((a-b)**3 * t**2) def _characteristic_function(self, t): a, b = self.a, self.b return -3*I*(exp(I*a*t*exp(I*b*t)) * (4*I - (-4*b + (a+b)**2)*t)) \ / ((a-b)**3 * t**2) def QuadraticU(name, a, b): r""" Create a Continuous Random Variable with a U-quadratic distribution. Explanation =========== The density of the U-quadratic distribution is given by .. math:: f(x) := \alpha (x-\beta)^2 with :math:`x \in [a,b]`. Parameters ========== a : Real number b : Real number, :math:`a < b` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import QuadraticU, density >>> from sympy import Symbol, pprint >>> a = Symbol("a", real=True) >>> b = Symbol("b", real=True) >>> z = Symbol("z") >>> X = QuadraticU("x", a, b) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) / 2 | / a b \ |12*|- - - - + z| | \ 2 2 / <----------------- for And(b >= z, a <= z) | 3 | (-a + b) | \ 0 otherwise References ========== .. [1] https://en.wikipedia.org/wiki/U-quadratic_distribution """ return rv(name, QuadraticUDistribution, (a, b)) #------------------------------------------------------------------------------- # RaisedCosine distribution ---------------------------------------------------- class RaisedCosineDistribution(SingleContinuousDistribution): _argnames = ('mu', 's') @property def set(self): return Interval(self.mu - self.s, self.mu + self.s) @staticmethod def check(mu, s): _value_check(s > 0, "s must be positive") def pdf(self, x): mu, s = self.mu, self.s return Piecewise( ((1+cos(pi*(x-mu)/s)) / (2*s), And(mu-s<=x, x<=mu+s)), (S.Zero, True)) def _characteristic_function(self, t): mu, s = self.mu, self.s return Piecewise((exp(-I*pi*mu/s)/2, Eq(t, -pi/s)), (exp(I*pi*mu/s)/2, Eq(t, pi/s)), (pi**2*sin(s*t)*exp(I*mu*t) / (s*t*(pi**2 - s**2*t**2)), True)) def _moment_generating_function(self, t): mu, s = self.mu, self.s return pi**2 * sinh(s*t) * exp(mu*t) / (s*t*(pi**2 + s**2*t**2)) def RaisedCosine(name, mu, s): r""" Create a Continuous Random Variable with a raised cosine distribution. Explanation =========== The density of the raised cosine distribution is given by .. math:: f(x) := \frac{1}{2s}\left(1+\cos\left(\frac{x-\mu}{s}\pi\right)\right) with :math:`x \in [\mu-s,\mu+s]`. Parameters ========== mu : Real number s : Real number, `s > 0` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import RaisedCosine, density >>> from sympy import Symbol, pprint >>> mu = Symbol("mu", real=True) >>> s = Symbol("s", positive=True) >>> z = Symbol("z") >>> X = RaisedCosine("x", mu, s) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) / /pi*(-mu + z)\ |cos|------------| + 1 | \ s / <--------------------- for And(z >= mu - s, z <= mu + s) | 2*s | \ 0 otherwise References ========== .. [1] https://en.wikipedia.org/wiki/Raised_cosine_distribution """ return rv(name, RaisedCosineDistribution, (mu, s)) #------------------------------------------------------------------------------- # Rayleigh distribution -------------------------------------------------------- class RayleighDistribution(SingleContinuousDistribution): _argnames = ('sigma',) set = Interval(0, oo) @staticmethod def check(sigma): _value_check(sigma > 0, "Scale parameter sigma must be positive.") def pdf(self, x): sigma = self.sigma return x/sigma**2*exp(-x**2/(2*sigma**2)) def _cdf(self, x): sigma = self.sigma return 1 - exp(-(x**2/(2*sigma**2))) def _characteristic_function(self, t): sigma = self.sigma return 1 - sigma*t*exp(-sigma**2*t**2/2) * sqrt(pi/2) * (erfi(sigma*t/sqrt(2)) - I) def _moment_generating_function(self, t): sigma = self.sigma return 1 + sigma*t*exp(sigma**2*t**2/2) * sqrt(pi/2) * (erf(sigma*t/sqrt(2)) + 1) def Rayleigh(name, sigma): r""" Create a continuous random variable with a Rayleigh distribution. Explanation =========== The density of the Rayleigh distribution is given by .. math :: f(x) := \frac{x}{\sigma^2} e^{-x^2/2\sigma^2} with :math:`x > 0`. Parameters ========== sigma : Real number, `\sigma > 0` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Rayleigh, density, E, variance >>> from sympy import Symbol >>> sigma = Symbol("sigma", positive=True) >>> z = Symbol("z") >>> X = Rayleigh("x", sigma) >>> density(X)(z) z*exp(-z**2/(2*sigma**2))/sigma**2 >>> E(X) sqrt(2)*sqrt(pi)*sigma/2 >>> variance(X) -pi*sigma**2/2 + 2*sigma**2 References ========== .. [1] https://en.wikipedia.org/wiki/Rayleigh_distribution .. [2] http://mathworld.wolfram.com/RayleighDistribution.html """ return rv(name, RayleighDistribution, (sigma, )) #------------------------------------------------------------------------------- # Reciprocal distribution -------------------------------------------------------- class ReciprocalDistribution(SingleContinuousDistribution): _argnames = ('a', 'b') @property def set(self): return Interval(self.a, self.b) @staticmethod def check(a, b): _value_check(a > 0, "Parameter > 0. a = %s"%a) _value_check((a < b), "Parameter b must be in range (%s, +oo]. b = %s"%(a, b)) def pdf(self, x): a, b = self.a, self.b return 1/(x*(log(b) - log(a))) def Reciprocal(name, a, b): r"""Creates a continuous random variable with a reciprocal distribution. Parameters ========== a : Real number, :math:`0 < a` b : Real number, :math:`a < b` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Reciprocal, density, cdf >>> from sympy import symbols >>> a, b, x = symbols('a, b, x', positive=True) >>> R = Reciprocal('R', a, b) >>> density(R)(x) 1/(x*(-log(a) + log(b))) >>> cdf(R)(x) Piecewise((log(a)/(log(a) - log(b)) - log(x)/(log(a) - log(b)), a <= x), (0, True)) Reference ========= .. [1] https://en.wikipedia.org/wiki/Reciprocal_distribution """ return rv(name, ReciprocalDistribution, (a, b)) #------------------------------------------------------------------------------- # Shifted Gompertz distribution ------------------------------------------------ class ShiftedGompertzDistribution(SingleContinuousDistribution): _argnames = ('b', 'eta') set = Interval(0, oo) @staticmethod def check(b, eta): _value_check(b > 0, "b must be positive") _value_check(eta > 0, "eta must be positive") def pdf(self, x): b, eta = self.b, self.eta return b*exp(-b*x)*exp(-eta*exp(-b*x))*(1+eta*(1-exp(-b*x))) def ShiftedGompertz(name, b, eta): r""" Create a continuous random variable with a Shifted Gompertz distribution. Explanation =========== The density of the Shifted Gompertz distribution is given by .. math:: f(x) := b e^{-b x} e^{-\eta \exp(-b x)} \left[1 + \eta(1 - e^(-bx)) \right] with :math: 'x \in [0, \inf)'. Parameters ========== b: Real number, 'b > 0' a scale eta: Real number, 'eta > 0' a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import ShiftedGompertz, density >>> from sympy import Symbol >>> b = Symbol("b", positive=True) >>> eta = Symbol("eta", positive=True) >>> x = Symbol("x") >>> X = ShiftedGompertz("x", b, eta) >>> density(X)(x) b*(eta*(1 - exp(-b*x)) + 1)*exp(-b*x)*exp(-eta*exp(-b*x)) References ========== .. [1] https://en.wikipedia.org/wiki/Shifted_Gompertz_distribution """ return rv(name, ShiftedGompertzDistribution, (b, eta)) #------------------------------------------------------------------------------- # StudentT distribution -------------------------------------------------------- class StudentTDistribution(SingleContinuousDistribution): _argnames = ('nu',) set = Interval(-oo, oo) @staticmethod def check(nu): _value_check(nu > 0, "Degrees of freedom nu must be positive.") def pdf(self, x): nu = self.nu return 1/(sqrt(nu)*beta_fn(S.Half, nu/2))*(1 + x**2/nu)**(-(nu + 1)/2) def _cdf(self, x): nu = self.nu return S.Half + x*gamma((nu+1)/2)*hyper((S.Half, (nu+1)/2), (Rational(3, 2),), -x**2/nu)/(sqrt(pi*nu)*gamma(nu/2)) def _moment_generating_function(self, t): raise NotImplementedError('The moment generating function for the Student-T distribution is undefined.') def StudentT(name, nu): r""" Create a continuous random variable with a student's t distribution. Explanation =========== The density of the student's t distribution is given by .. math:: f(x) := \frac{\Gamma \left(\frac{\nu+1}{2} \right)} {\sqrt{\nu\pi}\Gamma \left(\frac{\nu}{2} \right)} \left(1+\frac{x^2}{\nu} \right)^{-\frac{\nu+1}{2}} Parameters ========== nu : Real number, `\nu > 0`, the degrees of freedom Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import StudentT, density, cdf >>> from sympy import Symbol, pprint >>> nu = Symbol("nu", positive=True) >>> z = Symbol("z") >>> X = StudentT("x", nu) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) nu 1 - -- - - 2 2 / 2\ | z | |1 + --| \ nu/ ----------------- ____ / nu\ \/ nu *B|1/2, --| \ 2 / >>> cdf(X)(z) 1/2 + z*gamma(nu/2 + 1/2)*hyper((1/2, nu/2 + 1/2), (3/2,), -z**2/nu)/(sqrt(pi)*sqrt(nu)*gamma(nu/2)) References ========== .. [1] https://en.wikipedia.org/wiki/Student_t-distribution .. [2] http://mathworld.wolfram.com/Studentst-Distribution.html """ return rv(name, StudentTDistribution, (nu, )) #------------------------------------------------------------------------------- # Trapezoidal distribution ------------------------------------------------------ class TrapezoidalDistribution(SingleContinuousDistribution): _argnames = ('a', 'b', 'c', 'd') @property def set(self): return Interval(self.a, self.d) @staticmethod def check(a, b, c, d): _value_check(a < d, "Lower bound parameter a < %s. a = %s"%(d, a)) _value_check((a <= b, b < c), "Level start parameter b must be in range [%s, %s). b = %s"%(a, c, b)) _value_check((b < c, c <= d), "Level end parameter c must be in range (%s, %s]. c = %s"%(b, d, c)) _value_check(d >= c, "Upper bound parameter d > %s. d = %s"%(c, d)) def pdf(self, x): a, b, c, d = self.a, self.b, self.c, self.d return Piecewise( (2*(x-a) / ((b-a)*(d+c-a-b)), And(a <= x, x < b)), (2 / (d+c-a-b), And(b <= x, x < c)), (2*(d-x) / ((d-c)*(d+c-a-b)), And(c <= x, x <= d)), (S.Zero, True)) def Trapezoidal(name, a, b, c, d): r""" Create a continuous random variable with a trapezoidal distribution. Explanation =========== The density of the trapezoidal distribution is given by .. math:: f(x) := \begin{cases} 0 & \mathrm{for\ } x < a, \\ \frac{2(x-a)}{(b-a)(d+c-a-b)} & \mathrm{for\ } a \le x < b, \\ \frac{2}{d+c-a-b} & \mathrm{for\ } b \le x < c, \\ \frac{2(d-x)}{(d-c)(d+c-a-b)} & \mathrm{for\ } c \le x < d, \\ 0 & \mathrm{for\ } d < x. \end{cases} Parameters ========== a : Real number, :math:`a < d` b : Real number, :math:`a <= b < c` c : Real number, :math:`b < c <= d` d : Real number Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Trapezoidal, density >>> from sympy import Symbol, pprint >>> a = Symbol("a") >>> b = Symbol("b") >>> c = Symbol("c") >>> d = Symbol("d") >>> z = Symbol("z") >>> X = Trapezoidal("x", a,b,c,d) >>> pprint(density(X)(z), use_unicode=False) / -2*a + 2*z |------------------------- for And(a <= z, b > z) |(-a + b)*(-a - b + c + d) | | 2 | -------------- for And(b <= z, c > z) < -a - b + c + d | | 2*d - 2*z |------------------------- for And(d >= z, c <= z) |(-c + d)*(-a - b + c + d) | \ 0 otherwise References ========== .. [1] https://en.wikipedia.org/wiki/Trapezoidal_distribution """ return rv(name, TrapezoidalDistribution, (a, b, c, d)) #------------------------------------------------------------------------------- # Triangular distribution ------------------------------------------------------ class TriangularDistribution(SingleContinuousDistribution): _argnames = ('a', 'b', 'c') @property def set(self): return Interval(self.a, self.b) @staticmethod def check(a, b, c): _value_check(b > a, "Parameter b > %s. b = %s"%(a, b)) _value_check((a <= c, c <= b), "Parameter c must be in range [%s, %s]. c = %s"%(a, b, c)) def pdf(self, x): a, b, c = self.a, self.b, self.c return Piecewise( (2*(x - a)/((b - a)*(c - a)), And(a <= x, x < c)), (2/(b - a), Eq(x, c)), (2*(b - x)/((b - a)*(b - c)), And(c < x, x <= b)), (S.Zero, True)) def _characteristic_function(self, t): a, b, c = self.a, self.b, self.c return -2 *((b-c) * exp(I*a*t) - (b-a) * exp(I*c*t) + (c-a) * exp(I*b*t)) / ((b-a)*(c-a)*(b-c)*t**2) def _moment_generating_function(self, t): a, b, c = self.a, self.b, self.c return 2 * ((b - c) * exp(a * t) - (b - a) * exp(c * t) + (c - a) * exp(b * t)) / ( (b - a) * (c - a) * (b - c) * t ** 2) def Triangular(name, a, b, c): r""" Create a continuous random variable with a triangular distribution. Explanation =========== The density of the triangular distribution is given by .. math:: f(x) := \begin{cases} 0 & \mathrm{for\ } x < a, \\ \frac{2(x-a)}{(b-a)(c-a)} & \mathrm{for\ } a \le x < c, \\ \frac{2}{b-a} & \mathrm{for\ } x = c, \\ \frac{2(b-x)}{(b-a)(b-c)} & \mathrm{for\ } c < x \le b, \\ 0 & \mathrm{for\ } b < x. \end{cases} Parameters ========== a : Real number, :math:`a \in \left(-\infty, \infty\right)` b : Real number, :math:`a < b` c : Real number, :math:`a \leq c \leq b` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Triangular, density >>> from sympy import Symbol, pprint >>> a = Symbol("a") >>> b = Symbol("b") >>> c = Symbol("c") >>> z = Symbol("z") >>> X = Triangular("x", a,b,c) >>> pprint(density(X)(z), use_unicode=False) / -2*a + 2*z |----------------- for And(a <= z, c > z) |(-a + b)*(-a + c) | | 2 | ------ for c = z < -a + b | | 2*b - 2*z |---------------- for And(b >= z, c < z) |(-a + b)*(b - c) | \ 0 otherwise References ========== .. [1] https://en.wikipedia.org/wiki/Triangular_distribution .. [2] http://mathworld.wolfram.com/TriangularDistribution.html """ return rv(name, TriangularDistribution, (a, b, c)) #------------------------------------------------------------------------------- # Uniform distribution --------------------------------------------------------- class UniformDistribution(SingleContinuousDistribution): _argnames = ('left', 'right') @property def set(self): return Interval(self.left, self.right) @staticmethod def check(left, right): _value_check(left < right, "Lower limit should be less than Upper limit.") def pdf(self, x): left, right = self.left, self.right return Piecewise( (S.One/(right - left), And(left <= x, x <= right)), (S.Zero, True) ) def _cdf(self, x): left, right = self.left, self.right return Piecewise( (S.Zero, x < left), ((x - left)/(right - left), x <= right), (S.One, True) ) def _characteristic_function(self, t): left, right = self.left, self.right return Piecewise(((exp(I*t*right) - exp(I*t*left)) / (I*t*(right - left)), Ne(t, 0)), (S.One, True)) def _moment_generating_function(self, t): left, right = self.left, self.right return Piecewise(((exp(t*right) - exp(t*left)) / (t * (right - left)), Ne(t, 0)), (S.One, True)) def expectation(self, expr, var, **kwargs): from sympy import Max, Min kwargs['evaluate'] = True result = SingleContinuousDistribution.expectation(self, expr, var, **kwargs) result = result.subs({Max(self.left, self.right): self.right, Min(self.left, self.right): self.left}) return result def Uniform(name, left, right): r""" Create a continuous random variable with a uniform distribution. Explanation =========== The density of the uniform distribution is given by .. math:: f(x) := \begin{cases} \frac{1}{b - a} & \text{for } x \in [a,b] \\ 0 & \text{otherwise} \end{cases} with :math:`x \in [a,b]`. Parameters ========== a : Real number, :math:`-\infty < a` the left boundary b : Real number, :math:`a < b < \infty` the right boundary Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Uniform, density, cdf, E, variance >>> from sympy import Symbol, simplify >>> a = Symbol("a", negative=True) >>> b = Symbol("b", positive=True) >>> z = Symbol("z") >>> X = Uniform("x", a, b) >>> density(X)(z) Piecewise((1/(-a + b), (b >= z) & (a <= z)), (0, True)) >>> cdf(X)(z) Piecewise((0, a > z), ((-a + z)/(-a + b), b >= z), (1, True)) >>> E(X) a/2 + b/2 >>> simplify(variance(X)) a**2/12 - a*b/6 + b**2/12 References ========== .. [1] https://en.wikipedia.org/wiki/Uniform_distribution_%28continuous%29 .. [2] http://mathworld.wolfram.com/UniformDistribution.html """ return rv(name, UniformDistribution, (left, right)) #------------------------------------------------------------------------------- # UniformSum distribution ------------------------------------------------------ class UniformSumDistribution(SingleContinuousDistribution): _argnames = ('n',) @property def set(self): return Interval(0, self.n) @staticmethod def check(n): _value_check((n > 0, n.is_integer), "Parameter n must be positive integer.") def pdf(self, x): n = self.n k = Dummy("k") return 1/factorial( n - 1)*Sum((-1)**k*binomial(n, k)*(x - k)**(n - 1), (k, 0, floor(x))) def _cdf(self, x): n = self.n k = Dummy("k") return Piecewise((S.Zero, x < 0), (1/factorial(n)*Sum((-1)**k*binomial(n, k)*(x - k)**(n), (k, 0, floor(x))), x <= n), (S.One, True)) def _characteristic_function(self, t): return ((exp(I*t) - 1) / (I*t))**self.n def _moment_generating_function(self, t): return ((exp(t) - 1) / t)**self.n def UniformSum(name, n): r""" Create a continuous random variable with an Irwin-Hall distribution. Explanation =========== The probability distribution function depends on a single parameter $n$ which is an integer. The density of the Irwin-Hall distribution is given by .. math :: f(x) := \frac{1}{(n-1)!}\sum_{k=0}^{\left\lfloor x\right\rfloor}(-1)^k \binom{n}{k}(x-k)^{n-1} Parameters ========== n : A positive Integer, `n > 0` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import UniformSum, density, cdf >>> from sympy import Symbol, pprint >>> n = Symbol("n", integer=True) >>> z = Symbol("z") >>> X = UniformSum("x", n) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) floor(z) ___ \ ` \ k n - 1 /n\ ) (-1) *(-k + z) *| | / \k/ /__, k = 0 -------------------------------- (n - 1)! >>> cdf(X)(z) Piecewise((0, z < 0), (Sum((-1)**_k*(-_k + z)**n*binomial(n, _k), (_k, 0, floor(z)))/factorial(n), n >= z), (1, True)) Compute cdf with specific 'x' and 'n' values as follows : >>> cdf(UniformSum("x", 5), evaluate=False)(2).doit() 9/40 The argument evaluate=False prevents an attempt at evaluation of the sum for general n, before the argument 2 is passed. References ========== .. [1] https://en.wikipedia.org/wiki/Uniform_sum_distribution .. [2] http://mathworld.wolfram.com/UniformSumDistribution.html """ return rv(name, UniformSumDistribution, (n, )) #------------------------------------------------------------------------------- # VonMises distribution -------------------------------------------------------- class VonMisesDistribution(SingleContinuousDistribution): _argnames = ('mu', 'k') set = Interval(0, 2*pi) @staticmethod def check(mu, k): _value_check(k > 0, "k must be positive") def pdf(self, x): mu, k = self.mu, self.k return exp(k*cos(x-mu)) / (2*pi*besseli(0, k)) def VonMises(name, mu, k): r""" Create a Continuous Random Variable with a von Mises distribution. Explanation =========== The density of the von Mises distribution is given by .. math:: f(x) := \frac{e^{\kappa\cos(x-\mu)}}{2\pi I_0(\kappa)} with :math:`x \in [0,2\pi]`. Parameters ========== mu : Real number Measure of location. k : Real number Measure of concentration. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import VonMises, density >>> from sympy import Symbol, pprint >>> mu = Symbol("mu") >>> k = Symbol("k", positive=True) >>> z = Symbol("z") >>> X = VonMises("x", mu, k) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) k*cos(mu - z) e ------------------ 2*pi*besseli(0, k) References ========== .. [1] https://en.wikipedia.org/wiki/Von_Mises_distribution .. [2] http://mathworld.wolfram.com/vonMisesDistribution.html """ return rv(name, VonMisesDistribution, (mu, k)) #------------------------------------------------------------------------------- # Weibull distribution --------------------------------------------------------- class WeibullDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta') set = Interval(0, oo) @staticmethod def check(alpha, beta): _value_check(alpha > 0, "Alpha must be positive") _value_check(beta > 0, "Beta must be positive") def pdf(self, x): alpha, beta = self.alpha, self.beta return beta * (x/alpha)**(beta - 1) * exp(-(x/alpha)**beta) / alpha def Weibull(name, alpha, beta): r""" Create a continuous random variable with a Weibull distribution. Explanation =========== The density of the Weibull distribution is given by .. math:: f(x) := \begin{cases} \frac{k}{\lambda}\left(\frac{x}{\lambda}\right)^{k-1} e^{-(x/\lambda)^{k}} & x\geq0\\ 0 & x<0 \end{cases} Parameters ========== lambda : Real number, :math:`\lambda > 0` a scale k : Real number, ``k > 0`` a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Weibull, density, E, variance >>> from sympy import Symbol, simplify >>> l = Symbol("lambda", positive=True) >>> k = Symbol("k", positive=True) >>> z = Symbol("z") >>> X = Weibull("x", l, k) >>> density(X)(z) k*(z/lambda)**(k - 1)*exp(-(z/lambda)**k)/lambda >>> simplify(E(X)) lambda*gamma(1 + 1/k) >>> simplify(variance(X)) lambda**2*(-gamma(1 + 1/k)**2 + gamma(1 + 2/k)) References ========== .. [1] https://en.wikipedia.org/wiki/Weibull_distribution .. [2] http://mathworld.wolfram.com/WeibullDistribution.html """ return rv(name, WeibullDistribution, (alpha, beta)) #------------------------------------------------------------------------------- # Wigner semicircle distribution ----------------------------------------------- class WignerSemicircleDistribution(SingleContinuousDistribution): _argnames = ('R',) @property def set(self): return Interval(-self.R, self.R) @staticmethod def check(R): _value_check(R > 0, "Radius R must be positive.") def pdf(self, x): R = self.R return 2/(pi*R**2)*sqrt(R**2 - x**2) def _characteristic_function(self, t): return Piecewise((2 * besselj(1, self.R*t) / (self.R*t), Ne(t, 0)), (S.One, True)) def _moment_generating_function(self, t): return Piecewise((2 * besseli(1, self.R*t) / (self.R*t), Ne(t, 0)), (S.One, True)) def WignerSemicircle(name, R): r""" Create a continuous random variable with a Wigner semicircle distribution. Explanation =========== The density of the Wigner semicircle distribution is given by .. math:: f(x) := \frac2{\pi R^2}\,\sqrt{R^2-x^2} with :math:`x \in [-R,R]`. Parameters ========== R : Real number, `R > 0`, the radius Returns ======= A `RandomSymbol`. Examples ======== >>> from sympy.stats import WignerSemicircle, density, E >>> from sympy import Symbol >>> R = Symbol("R", positive=True) >>> z = Symbol("z") >>> X = WignerSemicircle("x", R) >>> density(X)(z) 2*sqrt(R**2 - z**2)/(pi*R**2) >>> E(X) 0 References ========== .. [1] https://en.wikipedia.org/wiki/Wigner_semicircle_distribution .. [2] http://mathworld.wolfram.com/WignersSemicircleLaw.html """ return rv(name, WignerSemicircleDistribution, (R,))
245a004b765c9f2ccf0eff35f716ef9d2dbc7b6bb821e76b6f4329106e0b4953
""" Finite Discrete Random Variables - Prebuilt variable types Contains ======== FiniteRV DiscreteUniform Die Bernoulli Coin Binomial BetaBinomial Hypergeometric Rademacher IdealSoliton RobustSoliton """ from sympy import (S, sympify, Rational, binomial, cacheit, Integer, Dummy, Eq, Intersection, Interval, log, Range, Symbol, Lambda, Piecewise, Or, Gt, Lt, Ge, Le, Contains) from sympy import beta as beta_fn from sympy.stats.frv import (SingleFiniteDistribution, SingleFinitePSpace) from sympy.stats.rv import _value_check, Density, is_random __all__ = ['FiniteRV', 'DiscreteUniform', 'Die', 'Bernoulli', 'Coin', 'Binomial', 'BetaBinomial', 'Hypergeometric', 'Rademacher', 'IdealSoliton', 'RobustSoliton', ] def rv(name, cls, *args, **kwargs): args = list(map(sympify, args)) dist = cls(*args) if kwargs.pop('check', True): dist.check(*args) pspace = SingleFinitePSpace(name, dist) if any(is_random(arg) for arg in args): from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution pspace = CompoundPSpace(name, CompoundDistribution(dist)) return pspace.value class FiniteDistributionHandmade(SingleFiniteDistribution): @property def dict(self): return self.args[0] def pmf(self, x): x = Symbol('x') return Lambda(x, Piecewise(*( [(v, Eq(k, x)) for k, v in self.dict.items()] + [(S.Zero, True)]))) @property def set(self): return set(self.dict.keys()) @staticmethod def check(density): for p in density.values(): _value_check((p >= 0, p <= 1), "Probability at a point must be between 0 and 1.") val = sum(density.values()) _value_check(Eq(val, 1) != S.false, "Total Probability must be 1.") def FiniteRV(name, density, **kwargs): r""" Create a Finite Random Variable given a dict representing the density. Parameters ========== name : Symbol Represents name of the random variable. density: A dict Dictionary conatining the pdf of finite distribution check : bool If True, it will check whether the given density integrates to 1 over the given set. If False, it will not perform this check. Default is False. Examples ======== >>> from sympy.stats import FiniteRV, P, E >>> density = {0: .1, 1: .2, 2: .3, 3: .4} >>> X = FiniteRV('X', density) >>> E(X) 2.00000000000000 >>> P(X >= 2) 0.700000000000000 Returns ======= RandomSymbol """ # have a default of False while `rv` should have a default of True kwargs['check'] = kwargs.pop('check', False) return rv(name, FiniteDistributionHandmade, density, **kwargs) class DiscreteUniformDistribution(SingleFiniteDistribution): @staticmethod def check(*args): # not using _value_check since there is a # suggestion for the user if len(set(args)) != len(args): from sympy.utilities.iterables import multiset from sympy.utilities.misc import filldedent weights = multiset(args) n = Integer(len(args)) for k in weights: weights[k] /= n raise ValueError(filldedent(""" Repeated args detected but set expected. For a distribution having different weights for each item use the following:""") + ( '\nS("FiniteRV(%s, %s)")' % ("'X'", weights))) @property def p(self): return Rational(1, len(self.args)) @property # type: ignore @cacheit def dict(self): return {k: self.p for k in self.set} @property def set(self): return set(self.args) def pmf(self, x): if x in self.args: return self.p else: return S.Zero def DiscreteUniform(name, items): r""" Create a Finite Random Variable representing a uniform distribution over the input set. Parameters ========== items: list/tuple Items over which Uniform distribution is to be made Examples ======== >>> from sympy.stats import DiscreteUniform, density >>> from sympy import symbols >>> X = DiscreteUniform('X', symbols('a b c')) # equally likely over a, b, c >>> density(X).dict {a: 1/3, b: 1/3, c: 1/3} >>> Y = DiscreteUniform('Y', list(range(5))) # distribution over a range >>> density(Y).dict {0: 1/5, 1: 1/5, 2: 1/5, 3: 1/5, 4: 1/5} Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Discrete_uniform_distribution .. [2] http://mathworld.wolfram.com/DiscreteUniformDistribution.html """ return rv(name, DiscreteUniformDistribution, *items) class DieDistribution(SingleFiniteDistribution): _argnames = ('sides',) @staticmethod def check(sides): _value_check((sides.is_positive, sides.is_integer), "number of sides must be a positive integer.") @property def is_symbolic(self): return not self.sides.is_number @property def high(self): return self.sides @property def low(self): return S.One @property def set(self): if self.is_symbolic: return Intersection(S.Naturals0, Interval(0, self.sides)) return set(map(Integer, list(range(1, self.sides + 1)))) def pmf(self, x): x = sympify(x) if not (x.is_number or x.is_Symbol or is_random(x)): raise ValueError("'x' expected as an argument of type 'number' or 'Symbol' or , " "'RandomSymbol' not %s" % (type(x))) cond = Ge(x, 1) & Le(x, self.sides) & Contains(x, S.Integers) return Piecewise((S.One/self.sides, cond), (S.Zero, True)) def Die(name, sides=6): r""" Create a Finite Random Variable representing a fair die. Parameters ========== sides: Integer Represents the number of sides of the Die, by default is 6 Examples ======== >>> from sympy.stats import Die, density >>> from sympy import Symbol >>> D6 = Die('D6', 6) # Six sided Die >>> density(D6).dict {1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6} >>> D4 = Die('D4', 4) # Four sided Die >>> density(D4).dict {1: 1/4, 2: 1/4, 3: 1/4, 4: 1/4} >>> n = Symbol('n', positive=True, integer=True) >>> Dn = Die('Dn', n) # n sided Die >>> density(Dn).dict Density(DieDistribution(n)) >>> density(Dn).dict.subs(n, 4).doit() {1: 1/4, 2: 1/4, 3: 1/4, 4: 1/4} Returns ======= RandomSymbol """ return rv(name, DieDistribution, sides) class BernoulliDistribution(SingleFiniteDistribution): _argnames = ('p', 'succ', 'fail') @staticmethod def check(p, succ, fail): _value_check((p >= 0, p <= 1), "p should be in range [0, 1].") @property def set(self): return {self.succ, self.fail} def pmf(self, x): if isinstance(self.succ, Symbol) and isinstance(self.fail, Symbol): return Piecewise((self.p, x == self.succ), (1 - self.p, x == self.fail), (S.Zero, True)) return Piecewise((self.p, Eq(x, self.succ)), (1 - self.p, Eq(x, self.fail)), (S.Zero, True)) def Bernoulli(name, p, succ=1, fail=0): r""" Create a Finite Random Variable representing a Bernoulli process. Parameters ========== p : Rational number between 0 and 1 Represents probability of success succ : Integer/symbol/string Represents event of success fail : Integer/symbol/string Represents event of failure Examples ======== >>> from sympy.stats import Bernoulli, density >>> from sympy import S >>> X = Bernoulli('X', S(3)/4) # 1-0 Bernoulli variable, probability = 3/4 >>> density(X).dict {0: 1/4, 1: 3/4} >>> X = Bernoulli('X', S.Half, 'Heads', 'Tails') # A fair coin toss >>> density(X).dict {Heads: 1/2, Tails: 1/2} Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Bernoulli_distribution .. [2] http://mathworld.wolfram.com/BernoulliDistribution.html """ return rv(name, BernoulliDistribution, p, succ, fail) def Coin(name, p=S.Half): r""" Create a Finite Random Variable representing a Coin toss. Parameters ========== p : Rational Numeber between 0 and 1 Represents probability of getting "Heads", by default is Half Examples ======== >>> from sympy.stats import Coin, density >>> from sympy import Rational >>> C = Coin('C') # A fair coin toss >>> density(C).dict {H: 1/2, T: 1/2} >>> C2 = Coin('C2', Rational(3, 5)) # An unfair coin >>> density(C2).dict {H: 3/5, T: 2/5} Returns ======= RandomSymbol See Also ======== sympy.stats.Binomial References ========== .. [1] https://en.wikipedia.org/wiki/Coin_flipping """ return rv(name, BernoulliDistribution, p, 'H', 'T') class BinomialDistribution(SingleFiniteDistribution): _argnames = ('n', 'p', 'succ', 'fail') @staticmethod def check(n, p, succ, fail): _value_check((n.is_integer, n.is_nonnegative), "'n' must be nonnegative integer.") _value_check((p <= 1, p >= 0), "p should be in range [0, 1].") @property def high(self): return self.n @property def low(self): return S.Zero @property def is_symbolic(self): return not self.n.is_number @property def set(self): if self.is_symbolic: return Intersection(S.Naturals0, Interval(0, self.n)) return set(self.dict.keys()) def pmf(self, x): n, p = self.n, self.p x = sympify(x) if not (x.is_number or x.is_Symbol or is_random(x)): raise ValueError("'x' expected as an argument of type 'number' or 'Symbol' or , " "'RandomSymbol' not %s" % (type(x))) cond = Ge(x, 0) & Le(x, n) & Contains(x, S.Integers) return Piecewise((binomial(n, x) * p**x * (1 - p)**(n - x), cond), (S.Zero, True)) @property # type: ignore @cacheit def dict(self): if self.is_symbolic: return Density(self) return {k*self.succ + (self.n-k)*self.fail: self.pmf(k) for k in range(0, self.n + 1)} def Binomial(name, n, p, succ=1, fail=0): r""" Create a Finite Random Variable representing a binomial distribution. Parameters ========== n : Positive Integer Represents number of trials p : Rational Number between 0 and 1 Represents probability of success succ : Integer/symbol/string Represents event of success, by default is 1 fail : Integer/symbol/string Represents event of failure, by default is 0 Examples ======== >>> from sympy.stats import Binomial, density >>> from sympy import S, Symbol >>> X = Binomial('X', 4, S.Half) # Four "coin flips" >>> density(X).dict {0: 1/16, 1: 1/4, 2: 3/8, 3: 1/4, 4: 1/16} >>> n = Symbol('n', positive=True, integer=True) >>> p = Symbol('p', positive=True) >>> X = Binomial('X', n, S.Half) # n "coin flips" >>> density(X).dict Density(BinomialDistribution(n, 1/2, 1, 0)) >>> density(X).dict.subs(n, 4).doit() {0: 1/16, 1: 1/4, 2: 3/8, 3: 1/4, 4: 1/16} Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Binomial_distribution .. [2] http://mathworld.wolfram.com/BinomialDistribution.html """ return rv(name, BinomialDistribution, n, p, succ, fail) #------------------------------------------------------------------------------- # Beta-binomial distribution ---------------------------------------------------------- class BetaBinomialDistribution(SingleFiniteDistribution): _argnames = ('n', 'alpha', 'beta') @staticmethod def check(n, alpha, beta): _value_check((n.is_integer, n.is_nonnegative), "'n' must be nonnegative integer. n = %s." % str(n)) _value_check((alpha > 0), "'alpha' must be: alpha > 0 . alpha = %s" % str(alpha)) _value_check((beta > 0), "'beta' must be: beta > 0 . beta = %s" % str(beta)) @property def high(self): return self.n @property def low(self): return S.Zero @property def is_symbolic(self): return not self.n.is_number @property def set(self): if self.is_symbolic: return Intersection(S.Naturals0, Interval(0, self.n)) return set(map(Integer, list(range(0, self.n + 1)))) def pmf(self, k): n, a, b = self.n, self.alpha, self.beta return binomial(n, k) * beta_fn(k + a, n - k + b) / beta_fn(a, b) def BetaBinomial(name, n, alpha, beta): r""" Create a Finite Random Variable representing a Beta-binomial distribution. Parameters ========== n : Positive Integer Represents number of trials alpha : Real positive number beta : Real positive number Examples ======== >>> from sympy.stats import BetaBinomial, density >>> X = BetaBinomial('X', 2, 1, 1) >>> density(X).dict {0: 1/3, 1: 2*beta(2, 2), 2: 1/3} Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Beta-binomial_distribution .. [2] http://mathworld.wolfram.com/BetaBinomialDistribution.html """ return rv(name, BetaBinomialDistribution, n, alpha, beta) class HypergeometricDistribution(SingleFiniteDistribution): _argnames = ('N', 'm', 'n') @staticmethod def check(n, N, m): _value_check((N.is_integer, N.is_nonnegative), "'N' must be nonnegative integer. N = %s." % str(n)) _value_check((n.is_integer, n.is_nonnegative), "'n' must be nonnegative integer. n = %s." % str(n)) _value_check((m.is_integer, m.is_nonnegative), "'m' must be nonnegative integer. m = %s." % str(n)) @property def is_symbolic(self): return not all(x.is_number for x in (self.N, self.m, self.n)) @property def high(self): return Piecewise((self.n, Lt(self.n, self.m) != False), (self.m, True)) @property def low(self): return Piecewise((0, Gt(0, self.n + self.m - self.N) != False), (self.n + self.m - self.N, True)) @property def set(self): N, m, n = self.N, self.m, self.n if self.is_symbolic: return Intersection(S.Naturals0, Interval(self.low, self.high)) return {i for i in range(max(0, n + m - N), min(n, m) + 1)} def pmf(self, k): N, m, n = self.N, self.m, self.n return S(binomial(m, k) * binomial(N - m, n - k))/binomial(N, n) def Hypergeometric(name, N, m, n): r""" Create a Finite Random Variable representing a hypergeometric distribution. Parameters ========== N : Positive Integer Represents finite population of size N. m : Positive Integer Represents number of trials with required feature. n : Positive Integer Represents numbers of draws. Examples ======== >>> from sympy.stats import Hypergeometric, density >>> X = Hypergeometric('X', 10, 5, 3) # 10 marbles, 5 white (success), 3 draws >>> density(X).dict {0: 1/12, 1: 5/12, 2: 5/12, 3: 1/12} Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Hypergeometric_distribution .. [2] http://mathworld.wolfram.com/HypergeometricDistribution.html """ return rv(name, HypergeometricDistribution, N, m, n) class RademacherDistribution(SingleFiniteDistribution): @property def set(self): return {-1, 1} @property def pmf(self): k = Dummy('k') return Lambda(k, Piecewise((S.Half, Or(Eq(k, -1), Eq(k, 1))), (S.Zero, True))) def Rademacher(name): r""" Create a Finite Random Variable representing a Rademacher distribution. Examples ======== >>> from sympy.stats import Rademacher, density >>> X = Rademacher('X') >>> density(X).dict {-1: 1/2, 1: 1/2} Returns ======= RandomSymbol See Also ======== sympy.stats.Bernoulli References ========== .. [1] https://en.wikipedia.org/wiki/Rademacher_distribution """ return rv(name, RademacherDistribution) class IdealSolitonDistribution(SingleFiniteDistribution): _argnames = ('k',) @staticmethod def check(k): _value_check(k.is_integer and k.is_positive, "'k' must be a positive integer.") @property def low(self): return S.One @property def high(self): return self.k @property def set(self): return set(list(Range(1, self.k+1))) @property @cacheit def dict(self): if self.k.is_Symbol: return Density(self) d = {1: Rational(1, self.k)} d.update(dict((i, Rational(1, i*(i - 1))) for i in range(2, self.k + 1))) return d def pmf(self, x): x = sympify(x) if not (x.is_number or x.is_Symbol or is_random(x)): raise ValueError("'x' expected as an argument of type 'number' or 'Symbol' or , " "'RandomSymbol' not %s" % (type(x))) cond1 = Eq(x, 1) & x.is_integer cond2 = Ge(x, 1) & Le(x, self.k) & x.is_integer return Piecewise((1/self.k, cond1), (1/(x*(x - 1)), cond2), (S.Zero, True)) def IdealSoliton(name, k): r""" Create a Finite Random Variable of Ideal Soliton Distribution Parameters ========== k : Positive Integer Represents the number of input symbols in an LT (Luby Transform) code. Examples ======== >>> from sympy.stats import IdealSoliton, density, P, E >>> sol = IdealSoliton('sol', 5) >>> density(sol).dict {1: 1/5, 2: 1/2, 3: 1/6, 4: 1/12, 5: 1/20} >>> density(sol).set {1, 2, 3, 4, 5} >>> from sympy import Symbol >>> k = Symbol('k', positive=True, integer=True) >>> sol = IdealSoliton('sol', k) >>> density(sol).dict Density(IdealSolitonDistribution(k)) >>> density(sol).dict.subs(k, 10).doit() {1: 1/10, 2: 1/2, 3: 1/6, 4: 1/12, 5: 1/20, 6: 1/30, 7: 1/42, 8: 1/56, 9: 1/72, 10: 1/90} >>> E(sol.subs(k, 10)) 7381/2520 >>> P(sol.subs(k, 4) > 2) 1/4 Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Soliton_distribution#Ideal_distribution .. [2] http://pages.cs.wisc.edu/~suman/courses/740/papers/luby02lt.pdf """ return rv(name, IdealSolitonDistribution, k) class RobustSolitonDistribution(SingleFiniteDistribution): _argnames= ('k', 'delta', 'c') @staticmethod def check(k, delta, c): _value_check(k.is_integer and k.is_positive, "'k' must be a positive integer") _value_check(Gt(delta, 0) and Le(delta, 1), "'delta' must be a real number in the interval (0,1)") _value_check(c.is_positive, "'c' must be a positive real number.") @property def R(self): return self.c * log(self.k/self.delta) * self.k**0.5 @property def Z(self): z = 0 for i in Range(1, round(self.k/self.R)): z += (1/i) z += log(self.R/self.delta) return 1 + z * self.R/self.k @property def low(self): return S.One @property def high(self): return self.k @property def set(self): return set(list(Range(1, self.k+1))) @property def is_symbolic(self): return not (self.k.is_number and self.c.is_number and self.delta.is_number) def pmf(self, x): x = sympify(x) if not (x.is_number or x.is_Symbol or is_random(x)): raise ValueError("'x' expected as an argument of type 'number' or 'Symbol' or , " "'RandomSymbol' not %s" % (type(x))) cond1 = Eq(x, 1) & x.is_integer cond2 = Ge(x, 1) & Le(x, self.k) & x.is_integer rho = Piecewise((Rational(1, self.k), cond1), (Rational(1, x*(x-1)), cond2), (S.Zero, True)) cond1 = Ge(x, 1) & Le(x, round(self.k/self.R)-1) cond2 = Eq(x, round(self.k/self.R)) tau = Piecewise((self.R/(self.k * x), cond1), (self.R * log(self.R/self.delta)/self.k, cond2), (S.Zero, True)) return (rho + tau)/self.Z def RobustSoliton(name, k, delta, c): r''' Create a Finite Random Variable of Robust Soliton Distribution Parameters ========== k : Positive Integer Represents the number of input symbols in an LT (Luby Transform) code. delta : Positive Rational Number Represents the failure probability. Must be in the interval (0,1). c : Positive Rational Number Constant of proportionality. Values close to 1 are recommended Examples ======== >>> from sympy.stats import RobustSoliton, density, P, E >>> robSol = RobustSoliton('robSol', 5, 0.5, 0.01) >>> density(robSol).dict {1: 0.204253668152708, 2: 0.490631107897393, 3: 0.165210624506162, 4: 0.0834387731899302, 5: 0.0505633404760675} >>> density(robSol).set {1, 2, 3, 4, 5} >>> from sympy import Symbol >>> k = Symbol('k', positive=True, integer=True) >>> c = Symbol('c', positive=True) >>> robSol = RobustSoliton('robSol', k, 0.5, c) >>> density(robSol).dict Density(RobustSolitonDistribution(k, 0.5, c)) >>> density(robSol).dict.subs(k, 10).subs(c, 0.03).doit() {1: 0.116641095387194, 2: 0.467045731687165, 3: 0.159984123349381, 4: 0.0821431680681869, 5: 0.0505765646770100, 6: 0.0345781523420719, 7: 0.0253132820710503, 8: 0.0194459129233227, 9: 0.0154831166726115, 10: 0.0126733075238887} >>> E(robSol.subs(k, 10).subs(c, 0.05)) 2.91358846104106 >>> P(robSol.subs(k, 4).subs(c, 0.1) > 2) 0.243650614389834 Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Soliton_distribution#Robust_distribution .. [2] http://www.inference.org.uk/mackay/itprnn/ps/588.596.pdf .. [3] http://pages.cs.wisc.edu/~suman/courses/740/papers/luby02lt.pdf ''' return rv(name, RobustSolitonDistribution, k, delta, c)
059ec38b45f5c7496305284fd025283c77987eb357e81db784d8db7cb51ba9da
from __future__ import print_function, division import random import itertools from typing import Sequence as tSequence, Union as tUnion, List as tList, Tuple as tTuple from sympy import (Matrix, MatrixSymbol, S, Indexed, Basic, Tuple, Range, Set, And, Eq, FiniteSet, ImmutableMatrix, Integer, igcd, Lambda, Mul, Dummy, IndexedBase, Add, Interval, oo, linsolve, eye, Or, Not, Intersection, factorial, Contains, Union, Expr, Function, exp, cacheit, sqrt, pi, gamma, Ge, Piecewise, Symbol, NonSquareMatrixError, EmptySet, ceiling, MatrixBase, ConditionSet, ones, zeros, Identity, Rational, Lt, Gt, Le, Ne, BlockMatrix, Sum) from sympy.core.relational import Relational from sympy.logic.boolalg import Boolean from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy.utilities.iterables import strongly_connected_components from sympy.stats.joint_rv import JointDistribution from sympy.stats.joint_rv_types import JointDistributionHandmade from sympy.stats.rv import (RandomIndexedSymbol, random_symbols, RandomSymbol, _symbol_converter, _value_check, pspace, given, dependent, is_random, sample_iter, Distribution, Density) from sympy.stats.stochastic_process import StochasticPSpace from sympy.stats.symbolic_probability import Probability, Expectation from sympy.stats.frv_types import Bernoulli, BernoulliDistribution, FiniteRV from sympy.stats.drv_types import Poisson, PoissonDistribution from sympy.stats.crv_types import Normal, NormalDistribution, Gamma, GammaDistribution from sympy.core.sympify import _sympify, sympify __all__ = [ 'StochasticProcess', 'DiscreteTimeStochasticProcess', 'DiscreteMarkovChain', 'TransitionMatrixOf', 'StochasticStateSpaceOf', 'GeneratorMatrixOf', 'ContinuousMarkovChain', 'BernoulliProcess', 'PoissonProcess', 'WienerProcess', 'GammaProcess' ] @is_random.register(Indexed) def _(x): return is_random(x.base) @is_random.register(RandomIndexedSymbol) # type: ignore def _(x): return True def _set_converter(itr): """ Helper function for converting list/tuple/set to Set. If parameter is not an instance of list/tuple/set then no operation is performed. Returns ======= Set The argument converted to Set. Raises ====== TypeError If the argument is not an instance of list/tuple/set. """ if isinstance(itr, (list, tuple, set)): itr = FiniteSet(*itr) if not isinstance(itr, Set): raise TypeError("%s is not an instance of list/tuple/set."%(itr)) return itr def _state_converter(itr: tSequence) -> tUnion[Tuple, Range]: """ Helper function for converting list/tuple/set/Range/Tuple/FiniteSet to tuple/Range. """ if isinstance(itr, (Tuple, set, FiniteSet)): itr = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr)) elif isinstance(itr, (list, tuple)): # check if states are unique if len(set(itr)) != len(itr): raise ValueError('The state space must have unique elements.') itr = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr)) elif isinstance(itr, Range): # the only ordered set in sympy I know of # try to convert to tuple try: itr = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr)) except (TypeError, ValueError): pass else: raise TypeError("%s is not an instance of list/tuple/set/Range/Tuple/FiniteSet." % (itr)) return itr def _sym_sympify(arg): """ Converts an arbitrary expression to a type that can be used inside SymPy. As generally strings are unwise to use in the expressions, it returns the Symbol of argument if the string type argument is passed. Parameters ========= arg: The parameter to be converted to be used in Sympy. Returns ======= The converted parameter. """ if isinstance(arg, str): return Symbol(arg) else: return _sympify(arg) def _matrix_checks(matrix): if not isinstance(matrix, (Matrix, MatrixSymbol, ImmutableMatrix)): raise TypeError("Transition probabilities either should " "be a Matrix or a MatrixSymbol.") if matrix.shape[0] != matrix.shape[1]: raise NonSquareMatrixError("%s is not a square matrix"%(matrix)) if isinstance(matrix, Matrix): matrix = ImmutableMatrix(matrix.tolist()) return matrix class StochasticProcess(Basic): """ Base class for all the stochastic processes whether discrete or continuous. Parameters ========== sym: Symbol or str state_space: Set The state space of the stochastic process, by default S.Reals. For discrete sets it is zero indexed. See Also ======== DiscreteTimeStochasticProcess """ index_set = S.Reals def __new__(cls, sym, state_space=S.Reals, **kwargs): sym = _symbol_converter(sym) state_space = _set_converter(state_space) return Basic.__new__(cls, sym, state_space) @property def symbol(self): return self.args[0] @property def state_space(self) -> tUnion[FiniteSet, Range]: if not isinstance(self.args[1], (FiniteSet, Range)): return FiniteSet(*self.args[1]) return self.args[1] def _deprecation_warn_distribution(self): SymPyDeprecationWarning( feature="Calling distribution with RandomIndexedSymbol", useinstead="distribution with just timestamp as argument", issue=20078, deprecated_since_version="1.7.1" ).warn() def distribution(self, key=None): if key is None: self._deprecation_warn_distribution() return Distribution() def density(self, x): return Density() def __call__(self, time): """ Overridden in ContinuousTimeStochasticProcess. """ raise NotImplementedError("Use [] for indexing discrete time stochastic process.") def __getitem__(self, time): """ Overridden in DiscreteTimeStochasticProcess. """ raise NotImplementedError("Use () for indexing continuous time stochastic process.") def probability(self, condition): raise NotImplementedError() def joint_distribution(self, *args): """ Computes the joint distribution of the random indexed variables. Parameters ========== args: iterable The finite list of random indexed variables/the key of a stochastic process whose joint distribution has to be computed. Returns ======= JointDistribution The joint distribution of the list of random indexed variables. An unevaluated object is returned if it is not possible to compute the joint distribution. Raises ====== ValueError: When the arguments passed are not of type RandomIndexSymbol or Number. """ args = list(args) for i, arg in enumerate(args): if S(arg).is_Number: if self.index_set.is_subset(S.Integers): args[i] = self.__getitem__(arg) else: args[i] = self.__call__(arg) elif not isinstance(arg, RandomIndexedSymbol): raise ValueError("Expected a RandomIndexedSymbol or " "key not %s"%(type(arg))) if args[0].pspace.distribution == Distribution(): return JointDistribution(*args) density = Lambda(tuple(args), expr=Mul.fromiter(arg.pspace.process.density(arg) for arg in args)) return JointDistributionHandmade(density) def expectation(self, condition, given_condition): raise NotImplementedError("Abstract method for expectation queries.") def sample(self): raise NotImplementedError("Abstract method for sampling queries.") class DiscreteTimeStochasticProcess(StochasticProcess): """ Base class for all discrete stochastic processes. """ def __getitem__(self, time): """ For indexing discrete time stochastic processes. Returns ======= RandomIndexedSymbol """ time = sympify(time) if not time.is_symbol and time not in self.index_set: raise IndexError("%s is not in the index set of %s"%(time, self.symbol)) idx_obj = Indexed(self.symbol, time) pspace_obj = StochasticPSpace(self.symbol, self, self.distribution(time)) return RandomIndexedSymbol(idx_obj, pspace_obj) class ContinuousTimeStochasticProcess(StochasticProcess): """ Base class for all continuous time stochastic process. """ def __call__(self, time): """ For indexing continuous time stochastic processes. Returns ======= RandomIndexedSymbol """ time = sympify(time) if not time.is_symbol and time not in self.index_set: raise IndexError("%s is not in the index set of %s"%(time, self.symbol)) func_obj = Function(self.symbol)(time) pspace_obj = StochasticPSpace(self.symbol, self, self.distribution(time)) return RandomIndexedSymbol(func_obj, pspace_obj) class TransitionMatrixOf(Boolean): """ Assumes that the matrix is the transition matrix of the process. """ def __new__(cls, process, matrix): if not isinstance(process, DiscreteMarkovChain): raise ValueError("Currently only DiscreteMarkovChain " "support TransitionMatrixOf.") matrix = _matrix_checks(matrix) return Basic.__new__(cls, process, matrix) process = property(lambda self: self.args[0]) matrix = property(lambda self: self.args[1]) class GeneratorMatrixOf(TransitionMatrixOf): """ Assumes that the matrix is the generator matrix of the process. """ def __new__(cls, process, matrix): if not isinstance(process, ContinuousMarkovChain): raise ValueError("Currently only ContinuousMarkovChain " "support GeneratorMatrixOf.") matrix = _matrix_checks(matrix) return Basic.__new__(cls, process, matrix) class StochasticStateSpaceOf(Boolean): def __new__(cls, process, state_space): if not isinstance(process, (DiscreteMarkovChain, ContinuousMarkovChain)): raise ValueError("Currently only DiscreteMarkovChain and ContinuousMarkovChain " "support StochasticStateSpaceOf.") state_space = _state_converter(state_space) if isinstance(state_space, Range): ss_size = ceiling((state_space.stop - state_space.start) / state_space.step) else: ss_size = len(state_space) state_index = Range(ss_size) return Basic.__new__(cls, process, state_index) process = property(lambda self: self.args[0]) state_index = property(lambda self: self.args[1]) class MarkovProcess(StochasticProcess): """ Contains methods that handle queries common to Markov processes. """ @property def number_of_states(self) -> tUnion[Integer, Symbol]: """ The number of states in the Markov Chain. """ return _sympify(self.args[2].shape[0]) @property def _state_index(self) -> Range: """ Returns state index as Range. """ return self.args[1] @classmethod def _sanity_checks(cls, state_space, trans_probs): # Try to never have None as state_space or trans_probs. # This helps a lot if we get it done at the start. if (state_space is None) and (trans_probs is None): _n = Dummy('n', integer=True, nonnegative=True) state_space = _state_converter(Range(_n)) trans_probs = _matrix_checks(MatrixSymbol('_T', _n, _n)) elif state_space is None: trans_probs = _matrix_checks(trans_probs) state_space = _state_converter(Range(trans_probs.shape[0])) elif trans_probs is None: state_space = _state_converter(state_space) if isinstance(state_space, Range): _n = ceiling((state_space.stop - state_space.start) / state_space.step) else: _n = len(state_space) trans_probs = MatrixSymbol('_T', _n, _n) else: state_space = _state_converter(state_space) trans_probs = _matrix_checks(trans_probs) # Range object doesn't want to give a symbolic size # so we do it ourselves. if isinstance(state_space, Range): ss_size = ceiling((state_space.stop - state_space.start) / state_space.step) else: ss_size = len(state_space) if ss_size != trans_probs.shape[0]: raise ValueError('The size of the state space and the number of ' 'rows of the transition matrix must be the same.') return state_space, trans_probs def _extract_information(self, given_condition): """ Helper function to extract information, like, transition matrix/generator matrix, state space, etc. """ if isinstance(self, DiscreteMarkovChain): trans_probs = self.transition_probabilities state_index = self._state_index elif isinstance(self, ContinuousMarkovChain): trans_probs = self.generator_matrix state_index = self._state_index if isinstance(given_condition, And): gcs = given_condition.args given_condition = S.true for gc in gcs: if isinstance(gc, TransitionMatrixOf): trans_probs = gc.matrix if isinstance(gc, StochasticStateSpaceOf): state_index = gc.state_index if isinstance(gc, Relational): given_condition = given_condition & gc if isinstance(given_condition, TransitionMatrixOf): trans_probs = given_condition.matrix given_condition = S.true if isinstance(given_condition, StochasticStateSpaceOf): state_index = given_condition.state_index given_condition = S.true return trans_probs, state_index, given_condition def _check_trans_probs(self, trans_probs, row_sum=1): """ Helper function for checking the validity of transition probabilities. """ if not isinstance(trans_probs, MatrixSymbol): rows = trans_probs.tolist() for row in rows: if (sum(row) - row_sum) != 0: raise ValueError("Values in a row must sum to %s. " "If you are using Float or floats then please use Rational."%(row_sum)) def _work_out_state_index(self, state_index, given_condition, trans_probs): """ Helper function to extract state space if there is a random symbol in the given condition. """ # if given condition is None, then there is no need to work out # state_space from random variables if given_condition != None: rand_var = list(given_condition.atoms(RandomSymbol) - given_condition.atoms(RandomIndexedSymbol)) if len(rand_var) == 1: state_index = rand_var[0].pspace.set # `not None` is `True`. So the old test fails for symbolic sizes. # Need to build the statement differently. sym_cond = not self.number_of_states.is_Integer cond1 = not sym_cond and len(state_index) != trans_probs.shape[0] if cond1: raise ValueError("state space is not compatible with the transition probabilities.") if not isinstance(trans_probs.shape[0], Symbol): state_index = FiniteSet(*[i for i in range(trans_probs.shape[0])]) return state_index @cacheit def _preprocess(self, given_condition, evaluate): """ Helper function for pre-processing the information. """ is_insufficient = False if not evaluate: # avoid pre-processing if the result is not to be evaluated return (True, None, None, None) # extracting transition matrix and state space trans_probs, state_index, given_condition = self._extract_information(given_condition) # given_condition does not have sufficient information # for computations if trans_probs is None or \ given_condition is None: is_insufficient = True else: # checking transition probabilities if isinstance(self, DiscreteMarkovChain): self._check_trans_probs(trans_probs, row_sum=1) elif isinstance(self, ContinuousMarkovChain): self._check_trans_probs(trans_probs, row_sum=0) # working out state space state_index = self._work_out_state_index(state_index, given_condition, trans_probs) return is_insufficient, trans_probs, state_index, given_condition def replace_with_index(self, condition): if isinstance(condition, Relational): lhs, rhs = condition.lhs, condition.rhs if not isinstance(lhs, RandomIndexedSymbol): lhs, rhs = rhs, lhs condition = type(condition)(self.index_of.get(lhs, lhs), self.index_of.get(rhs, rhs)) return condition def probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Handles probability queries for Markov process. Parameters ========== condition: Relational given_condition: Relational/And Returns ======= Probability If the information is not sufficient. Expr In all other cases. Note ==== Any information passed at the time of query overrides any information passed at the time of object creation like transition probabilities, state space. Pass the transition matrix using TransitionMatrixOf, generator matrix using GeneratorMatrixOf and state space using StochasticStateSpaceOf in given_condition using & or And. """ check, mat, state_index, new_given_condition = \ self._preprocess(given_condition, evaluate) rv = list(condition.atoms(RandomIndexedSymbol)) symbolic = False for sym in rv: if sym.key.is_symbol: symbolic = True break if check: return Probability(condition, new_given_condition) if isinstance(self, ContinuousMarkovChain): trans_probs = self.transition_probabilities(mat) elif isinstance(self, DiscreteMarkovChain): trans_probs = mat condition = self.replace_with_index(condition) given_condition = self.replace_with_index(given_condition) new_given_condition = self.replace_with_index(new_given_condition) if isinstance(condition, Relational): if isinstance(new_given_condition, And): gcs = new_given_condition.args else: gcs = (new_given_condition, ) min_key_rv = list(new_given_condition.atoms(RandomIndexedSymbol)) if len(min_key_rv): min_key_rv = min_key_rv[0] for r in rv: if min_key_rv.key.is_symbol or r.key.is_symbol: continue if min_key_rv.key > r.key: return Probability(condition) else: min_key_rv = None return Probability(condition) if symbolic: return self._symbolic_probability(condition, new_given_condition, rv, min_key_rv) if len(rv) > 1: rv[0] = condition.lhs rv[1] = condition.rhs if rv[0].key < rv[1].key: rv[0], rv[1] = rv[1], rv[0] if isinstance(condition, Gt): condition = Lt(condition.lhs, condition.rhs) elif isinstance(condition, Lt): condition = Gt(condition.lhs, condition.rhs) elif isinstance(condition, Ge): condition = Le(condition.lhs, condition.rhs) elif isinstance(condition, Le): condition = Ge(condition.lhs, condition.rhs) s = Rational(0, 1) n = len(self.state_space) if isinstance(condition, Eq) or isinstance(condition, Ne): for i in range(0, n): s += self.probability(Eq(rv[0], i), Eq(rv[1], i)) * self.probability(Eq(rv[1], i), new_given_condition) return s if isinstance(condition, Eq) else 1 - s else: upper = 0 greater = False if isinstance(condition, Ge) or isinstance(condition, Lt): upper = 1 if isinstance(condition, Gt) or isinstance(condition, Ge): greater = True for i in range(0, n): if i <= n//2: for j in range(0, i + upper): s += self.probability(Eq(rv[0], i), Eq(rv[1], j)) * self.probability(Eq(rv[1], j), new_given_condition) else: s += self.probability(Eq(rv[0], i), new_given_condition) for j in range(i + upper, n): s -= self.probability(Eq(rv[0], i), Eq(rv[1], j)) * self.probability(Eq(rv[1], j), new_given_condition) return s if greater else 1 - s rv = rv[0] states = condition.as_set() prob, gstate = dict(), None for gc in gcs: if gc.has(min_key_rv): if gc.has(Probability): p, gp = (gc.rhs, gc.lhs) if isinstance(gc.lhs, Probability) \ else (gc.lhs, gc.rhs) gr = gp.args[0] gset = Intersection(gr.as_set(), state_index) gstate = list(gset)[0] prob[gset] = p else: _, gstate = (gc.lhs.key, gc.rhs) if isinstance(gc.lhs, RandomIndexedSymbol) \ else (gc.rhs.key, gc.lhs) if not all(k in self.index_set for k in (rv.key, min_key_rv.key)): raise IndexError("The timestamps of the process are not in it's index set.") states = Intersection(states, state_index) if not isinstance(self.number_of_states, Symbol) else states for state in Union(states, FiniteSet(gstate)): if not state.is_Integer or Ge(state, mat.shape[0]) is True: raise IndexError("No information is available for (%s, %s) in " "transition probabilities of shape, (%s, %s). " "State space is zero indexed." %(gstate, state, mat.shape[0], mat.shape[1])) if prob: gstates = Union(*prob.keys()) if len(gstates) == 1: gstate = list(gstates)[0] gprob = list(prob.values())[0] prob[gstates] = gprob elif len(gstates) == len(state_index) - 1: gstate = list(state_index - gstates)[0] gprob = S.One - sum(prob.values()) prob[state_index - gstates] = gprob else: raise ValueError("Conflicting information.") else: gprob = S.One if min_key_rv == rv: return sum([prob[FiniteSet(state)] for state in states]) if isinstance(self, ContinuousMarkovChain): return gprob * sum([trans_probs(rv.key - min_key_rv.key).__getitem__((gstate, state)) for state in states]) if isinstance(self, DiscreteMarkovChain): return gprob * sum([(trans_probs**(rv.key - min_key_rv.key)).__getitem__((gstate, state)) for state in states]) if isinstance(condition, Not): expr = condition.args[0] return S.One - self.probability(expr, given_condition, evaluate, **kwargs) if isinstance(condition, And): compute_later, state2cond, conds = [], dict(), condition.args for expr in conds: if isinstance(expr, Relational): ris = list(expr.atoms(RandomIndexedSymbol))[0] if state2cond.get(ris, None) is None: state2cond[ris] = S.true state2cond[ris] &= expr else: compute_later.append(expr) ris = [] for ri in state2cond: ris.append(ri) cset = Intersection(state2cond[ri].as_set(), state_index) if len(cset) == 0: return S.Zero state2cond[ri] = cset.as_relational(ri) sorted_ris = sorted(ris, key=lambda ri: ri.key) prod = self.probability(state2cond[sorted_ris[0]], given_condition, evaluate, **kwargs) for i in range(1, len(sorted_ris)): ri, prev_ri = sorted_ris[i], sorted_ris[i-1] if not isinstance(state2cond[ri], Eq): raise ValueError("The process is in multiple states at %s, unable to determine the probability."%(ri)) mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat) prod *= self.probability(state2cond[ri], state2cond[prev_ri] & mat_of & StochasticStateSpaceOf(self, state_index), evaluate, **kwargs) for expr in compute_later: prod *= self.probability(expr, given_condition, evaluate, **kwargs) return prod if isinstance(condition, Or): return sum([self.probability(expr, given_condition, evaluate, **kwargs) for expr in condition.args]) raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been " "implemented yet."%(condition, given_condition)) def _symbolic_probability(self, condition, new_given_condition, rv, min_key_rv): #Function to calculate probability for queries with symbols if isinstance(condition, Relational): curr_state = new_given_condition.rhs if isinstance(new_given_condition.lhs, RandomIndexedSymbol) \ else new_given_condition.lhs next_state = condition.rhs if isinstance(condition.lhs, RandomIndexedSymbol) \ else condition.lhs if isinstance(condition, Eq) or isinstance(condition, Ne): if isinstance(self, DiscreteMarkovChain): P = self.transition_probabilities**(rv[0].key - min_key_rv.key) else: P = exp(self.generator_matrix*(rv[0].key - min_key_rv.key)) prob = P[curr_state, next_state] if isinstance(condition, Eq) else 1 - P[curr_state, next_state] return Piecewise((prob, rv[0].key > min_key_rv.key), (Probability(condition), True)) else: upper = 1 greater = False if isinstance(condition, Ge) or isinstance(condition, Lt): upper = 0 if isinstance(condition, Gt) or isinstance(condition, Ge): greater = True k = Dummy('k') condition = Eq(condition.lhs, k) if isinstance(condition.lhs, RandomIndexedSymbol)\ else Eq(condition.rhs, k) total = Sum(self.probability(condition, new_given_condition), (k, next_state + upper, self.state_space._sup)) return Piecewise((total, rv[0].key > min_key_rv.key), (Probability(condition), True)) if greater\ else Piecewise((1 - total, rv[0].key > min_key_rv.key), (Probability(condition), True)) else: return Probability(condition, new_given_condition) def expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Handles expectation queries for markov process. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. Returns ======= Expectation Unevaluated object if computations cannot be done due to insufficient information. Expr In all other cases when the computations are successful. Note ==== Any information passed at the time of query overrides any information passed at the time of object creation like transition probabilities, state space. Pass the transition matrix using TransitionMatrixOf, generator matrix using GeneratorMatrixOf and state space using StochasticStateSpaceOf in given_condition using & or And. """ check, mat, state_index, condition = \ self._preprocess(condition, evaluate) if check: return Expectation(expr, condition) rvs = random_symbols(expr) if isinstance(expr, Expr) and isinstance(condition, Eq) \ and len(rvs) == 1: # handle queries similar to E(f(X[i]), Eq(X[i-m], <some-state>)) condition=self.replace_with_index(condition) state_index=self.replace_with_index(state_index) rv = list(rvs)[0] lhsg, rhsg = condition.lhs, condition.rhs if not isinstance(lhsg, RandomIndexedSymbol): lhsg, rhsg = (rhsg, lhsg) if rhsg not in state_index: raise ValueError("%s state is not in the state space."%(rhsg)) if rv.key < lhsg.key: raise ValueError("Incorrect given condition is given, expectation " "time %s < time %s"%(rv.key, rv.key)) mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat) cond = condition & mat_of & \ StochasticStateSpaceOf(self, state_index) func = lambda s: self.probability(Eq(rv, s), cond) * expr.subs(rv, self._state_index[s]) return sum([func(s) for s in state_index]) raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been " "implemented yet."%(expr, condition)) class DiscreteMarkovChain(DiscreteTimeStochasticProcess, MarkovProcess): """ Represents a finite discrete time-homogeneous Markov chain. This type of Markov Chain can be uniquely characterised by its (ordered) state space and its one-step transition probability matrix. Parameters ========== sym: The name given to the Markov Chain state_space: Optional, by default, Range(n) trans_probs: Optional, by default, MatrixSymbol('_T', n, n) Examples ======== >>> from sympy.stats import DiscreteMarkovChain, TransitionMatrixOf, P, E >>> from sympy import Matrix, MatrixSymbol, Eq, symbols >>> T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]]) >>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T) >>> YS = DiscreteMarkovChain("Y") >>> Y.state_space {0, 1, 2} >>> Y.transition_probabilities Matrix([ [0.5, 0.2, 0.3], [0.2, 0.5, 0.3], [0.2, 0.3, 0.5]]) >>> TS = MatrixSymbol('T', 3, 3) >>> P(Eq(YS[3], 2), Eq(YS[1], 1) & TransitionMatrixOf(YS, TS)) T[0, 2]*T[1, 0] + T[1, 1]*T[1, 2] + T[1, 2]*T[2, 2] >>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2) 0.36 Probabilities will be calculated based on indexes rather than state names. For example, with the Sunny-Cloudy-Rainy model with string state names: >>> from sympy.core.symbol import Str >>> Y = DiscreteMarkovChain("Y", [Str('Sunny'), Str('Cloudy'), Str('Rainy')], T) >>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2) 0.36 This gives the same answer as the ``[0, 1, 2]`` state space. Currently, there is no support for state names within probability and expectation statements. Here is a work-around using ``Str``: >>> P(Eq(Str('Rainy'), Y[3]), Eq(Y[1], Str('Cloudy'))).round(2) 0.36 Symbol state names can also be used: >>> sunny, cloudy, rainy = symbols('Sunny, Cloudy, Rainy') >>> Y = DiscreteMarkovChain("Y", [sunny, cloudy, rainy], T) >>> P(Eq(Y[3], rainy), Eq(Y[1], cloudy)).round(2) 0.36 Expectations will be calculated as follows: >>> E(Y[3], Eq(Y[1], cloudy)) 0.38*Cloudy + 0.36*Rainy + 0.26*Sunny Probability of expressions with multiple RandomIndexedSymbols can also be calculated provided there is only 1 RandomIndexedSymbol in the given condition. It is always better to use Rational instead of floating point numbers for the probabilities in the transition matrix to avoid errors. >>> from sympy import Gt, Le, Rational >>> T = Matrix([[Rational(5, 10), Rational(3, 10), Rational(2, 10)], [Rational(2, 10), Rational(7, 10), Rational(1, 10)], [Rational(3, 10), Rational(3, 10), Rational(4, 10)]]) >>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T) >>> P(Eq(Y[3], Y[1]), Eq(Y[0], 0)).round(3) 0.409 >>> P(Gt(Y[3], Y[1]), Eq(Y[0], 0)).round(2) 0.36 >>> P(Le(Y[15], Y[10]), Eq(Y[8], 2)).round(7) 0.6963328 Symbolic probability queries are also supported >>> from sympy import symbols, Matrix, Rational, Eq, Gt >>> from sympy.stats import P, DiscreteMarkovChain >>> a, b, c, d = symbols('a b c d') >>> T = Matrix([[Rational(1, 10), Rational(4, 10), Rational(5, 10)], [Rational(3, 10), Rational(4, 10), Rational(3, 10)], [Rational(7, 10), Rational(2, 10), Rational(1, 10)]]) >>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T) >>> query = P(Eq(Y[a], b), Eq(Y[c], d)) >>> query.subs({a:10 ,b:2, c:5, d:1}).round(4) 0.3096 >>> P(Eq(Y[10], 2), Eq(Y[5], 1)).evalf().round(4) 0.3096 >>> query_gt = P(Gt(Y[a], b), Eq(Y[c], d)) >>> query_gt.subs({a:21, b:0, c:5, d:0}).evalf().round(5) 0.64705 >>> P(Gt(Y[21], 0), Eq(Y[5], 0)).round(5) 0.64705 There is limited support for arbitrarily sized states: >>> n = symbols('n', nonnegative=True, integer=True) >>> T = MatrixSymbol('T', n, n) >>> Y = DiscreteMarkovChain("Y", trans_probs=T) >>> Y.state_space Range(0, n, 1) >>> query = P(Eq(Y[a], b), Eq(Y[c], d)) >>> query.subs({a:10, b:2, c:5, d:1}) (T**5)[1, 2] References ========== .. [1] https://en.wikipedia.org/wiki/Markov_chain#Discrete-time_Markov_chain .. [2] https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf """ index_set = S.Naturals0 def __new__(cls, sym, state_space=None, trans_probs=None): # type: (Basic, tUnion[str, Symbol], tSequence, tUnion[MatrixBase, MatrixSymbol]) -> DiscreteMarkovChain sym = _symbol_converter(sym) state_space, trans_probs = MarkovProcess._sanity_checks(state_space, trans_probs) obj = Basic.__new__(cls, sym, state_space, trans_probs) indices = dict() if isinstance(obj.number_of_states, Integer): for index, state in enumerate(obj._state_index): indices[state] = index obj.index_of = indices return obj @property def transition_probabilities(self) -> tUnion[MatrixBase, MatrixSymbol]: """ Transition probabilities of discrete Markov chain, either an instance of Matrix or MatrixSymbol. """ return self.args[2] def communication_classes(self) -> tList[tTuple[tList[Basic], Boolean, Integer]]: """ Returns the list of communication classes that partition the states of the markov chain. A communication class is defined to be a set of states such that every state in that set is reachable from every other state in that set. Due to its properties this forms a class in the mathematical sense. Communication classes are also known as recurrence classes. Returns ======= classes The ``classes`` are a list of tuples. Each tuple represents a single communication class with its properties. The first element in the tuple is the list of states in the class, the second element is whether the class is recurrent and the third element is the period of the communication class. Examples ======== >>> from sympy.stats import DiscreteMarkovChain >>> from sympy import Matrix >>> T = Matrix([[0, 1, 0], ... [1, 0, 0], ... [1, 0, 0]]) >>> X = DiscreteMarkovChain('X', [1, 2, 3], T) >>> classes = X.communication_classes() >>> for states, is_recurrent, period in classes: ... states, is_recurrent, period ([1, 2], True, 2) ([3], False, 1) From this we can see that states ``1`` and ``2`` communicate, are recurrent and have a period of 2. We can also see state ``3`` is transient with a period of 1. Notes ===== The algorithm used is of order ``O(n**2)`` where ``n`` is the number of states in the markov chain. It uses Tarjan's algorithm to find the classes themselves and then it uses a breadth-first search algorithm to find each class's periodicity. Most of the algorithm's components approach ``O(n)`` as the matrix becomes more and more sparse. References ========== .. [1] http://www.columbia.edu/~ww2040/4701Sum07/4701-06-Notes-MCII.pdf .. [2] http://cecas.clemson.edu/~shierd/Shier/markov.pdf .. [3] https://ujcontent.uj.ac.za/vital/access/services/Download/uj:7506/CONTENT1 .. [4] https://www.mathworks.com/help/econ/dtmc.classify.html """ n = self.number_of_states T = self.transition_probabilities if isinstance(T, MatrixSymbol): raise NotImplementedError("Cannot perform the operation with a symbolic matrix.") # begin Tarjan's algorithm V = Range(n) # don't use state names. Rather use state # indexes since we use them for matrix # indexing here and later onward E = [(i, j) for i in V for j in V if T[i, j] != 0] classes = strongly_connected_components((V, E)) # end Tarjan's algorithm recurrence = [] periods = [] for class_ in classes: # begin recurrent check (similar to self._check_trans_probs()) submatrix = T[class_, class_] # get the submatrix with those states is_recurrent = S.true rows = submatrix.tolist() for row in rows: if (sum(row) - 1) != 0: is_recurrent = S.false break recurrence.append(is_recurrent) # end recurrent check # begin breadth-first search non_tree_edge_values = set() visited = {class_[0]} newly_visited = {class_[0]} level = {class_[0]: 0} current_level = 0 done = False # imitate a do-while loop while not done: # runs at most len(class_) times done = len(visited) == len(class_) current_level += 1 # this loop and the while loop above run a combined len(class_) number of times. # so this triple nested loop runs through each of the n states once. for i in newly_visited: # the loop below runs len(class_) number of times # complexity is around about O(n * avg(len(class_))) newly_visited = {j for j in class_ if T[i, j] != 0} new_tree_edges = newly_visited.difference(visited) for j in new_tree_edges: level[j] = current_level new_non_tree_edges = newly_visited.intersection(visited) new_non_tree_edge_values = {level[i]-level[j]+1 for j in new_non_tree_edges} non_tree_edge_values = non_tree_edge_values.union(new_non_tree_edge_values) visited = visited.union(new_tree_edges) # igcd needs at least 2 arguments positive_ntev = {val_e for val_e in non_tree_edge_values if val_e > 0} if len(positive_ntev) == 0: periods.append(len(class_)) elif len(positive_ntev) == 1: periods.append(positive_ntev.pop()) else: periods.append(igcd(*positive_ntev)) # end breadth-first search # convert back to the user's state names classes = [[self._state_index[i] for i in class_] for class_ in classes] return sympify(list(zip(classes, recurrence, periods))) def fundamental_matrix(self): """ Each entry fundamental matrix can be interpreted as the expected number of times the chains is in state j if it started in state i. References ========== .. [1] https://lips.cs.princeton.edu/the-fundamental-matrix-of-a-finite-markov-chain/ """ _, _, _, Q = self.decompose() if Q.shape[0] > 0: # if non-ergodic I = eye(Q.shape[0]) if (I - Q).det() == 0: raise ValueError("The fundamental matrix doesn't exist.") return (I - Q).inv().as_immutable() else: # if ergodic P = self.transition_probabilities I = eye(P.shape[0]) w = self.fixed_row_vector() W = Matrix([list(w) for i in range(0, P.shape[0])]) if (I - P + W).det() == 0: raise ValueError("The fundamental matrix doesn't exist.") return (I - P + W).inv().as_immutable() def absorbing_probabilities(self): """ Computes the absorbing probabilities, i.e., the ij-th entry of the matrix denotes the probability of Markov chain being absorbed in state j starting from state i. """ _, _, R, _ = self.decompose() N = self.fundamental_matrix() if R is None or N is None: return None return N*R def absorbing_probabilites(self): SymPyDeprecationWarning( feature="absorbing_probabilites", useinstead="absorbing_probabilities", issue=20042, deprecated_since_version="1.7" ).warn() return self.absorbing_probabilities() def is_regular(self): tuples = self.communication_classes() if len(tuples) == 0: return S.false # not defined for a 0x0 matrix classes, _, periods = list(zip(*tuples)) return And(len(classes) == 1, periods[0] == 1) def is_ergodic(self): tuples = self.communication_classes() if len(tuples) == 0: return S.false # not defined for a 0x0 matrix classes, _, _ = list(zip(*tuples)) return S(len(classes) == 1) def is_absorbing_state(self, state): trans_probs = self.transition_probabilities if isinstance(trans_probs, ImmutableMatrix) and \ state < trans_probs.shape[0]: return S(trans_probs[state, state]) is S.One def is_absorbing_chain(self): states, A, B, C = self.decompose() r = A.shape[0] return And(r > 0, A == Identity(r).as_explicit()) def stationary_distribution(self, condition_set=False) -> tUnion[ImmutableMatrix, ConditionSet, Lambda]: """ The stationary distribution is any row vector, p, that solves p = pP, is row stochastic and each element in p must be nonnegative. That means in matrix form: :math:`(P-I)^T p^T = 0` and :math:`(1, ..., 1) p = 1` where ``P`` is the one-step transition matrix. All time-homogeneous Markov Chains with a finite state space have at least one stationary distribution. In addition, if a finite time-homogeneous Markov Chain is irreducible, the stationary distribution is unique. Parameters ========== condition_set : bool If the chain has a symbolic size or transition matrix, it will return a ``Lambda`` if ``False`` and return a ``ConditionSet`` if ``True``. Examples ======== >>> from sympy.stats import DiscreteMarkovChain >>> from sympy import Matrix, S An irreducible Markov Chain >>> T = Matrix([[S(1)/2, S(1)/2, 0], ... [S(4)/5, S(1)/5, 0], ... [1, 0, 0]]) >>> X = DiscreteMarkovChain('X', trans_probs=T) >>> X.stationary_distribution() Matrix([[8/13, 5/13, 0]]) A reducible Markov Chain >>> T = Matrix([[S(1)/2, S(1)/2, 0], ... [S(4)/5, S(1)/5, 0], ... [0, 0, 1]]) >>> X = DiscreteMarkovChain('X', trans_probs=T) >>> X.stationary_distribution() Matrix([[8/13 - 8*tau0/13, 5/13 - 5*tau0/13, tau0]]) >>> Y = DiscreteMarkovChain('Y') >>> Y.stationary_distribution() Lambda((wm, _T), Eq(wm*_T, wm)) >>> Y.stationary_distribution(condition_set=True) ConditionSet(wm, Eq(wm*_T, wm)) References ========== .. [1] https://www.probabilitycourse.com/chapter11/11_2_6_stationary_and_limiting_distributions.php .. [2] https://galton.uchicago.edu/~yibi/teaching/stat317/2014/Lectures/Lecture4_6up.pdf See Also ======== sympy.stats.DiscreteMarkovChain.limiting_distribution """ trans_probs = self.transition_probabilities n = self.number_of_states if n == 0: return ImmutableMatrix(Matrix([[]])) # symbolic matrix version if isinstance(trans_probs, MatrixSymbol): wm = MatrixSymbol('wm', 1, n) if condition_set: return ConditionSet(wm, Eq(wm * trans_probs, wm)) else: return Lambda((wm, trans_probs), Eq(wm * trans_probs, wm)) # numeric matrix version a = Matrix(trans_probs - Identity(n)).T a[0, 0:n] = ones(1, n) b = zeros(n, 1) b[0, 0] = 1 soln = list(linsolve((a, b)))[0] return ImmutableMatrix([[sol for sol in soln]]) def fixed_row_vector(self): """ A wrapper for ``stationary_distribution()``. """ return self.stationary_distribution() @property def limiting_distribution(self): """ The fixed row vector is the limiting distribution of a discrete Markov chain. """ return self.fixed_row_vector() def decompose(self) -> tTuple[tList[Basic], ImmutableMatrix, ImmutableMatrix, ImmutableMatrix]: """ Decomposes the transition matrix into submatrices with special properties. The transition matrix can be decomposed into 4 submatrices: - A - the submatrix from recurrent states to recurrent states. - B - the submatrix from transient to recurrent states. - C - the submatrix from transient to transient states. - O - the submatrix of zeros for recurrent to transient states. Returns ======= states, A, B, C ``states`` - a list of state names with the first being the recurrent states and the last being the transient states in the order of the row names of A and then the row names of C. ``A`` - the submatrix from recurrent states to recurrent states. ``B`` - the submatrix from transient to recurrent states. ``C`` - the submatrix from transient to transient states. Examples ======== >>> from sympy.stats import DiscreteMarkovChain >>> from sympy import Matrix, S One can decompose this chain for example: >>> T = Matrix([[S(1)/2, S(1)/2, 0, 0, 0], ... [S(2)/5, S(1)/5, S(2)/5, 0, 0], ... [0, 0, 1, 0, 0], ... [0, 0, S(1)/2, S(1)/2, 0], ... [S(1)/2, 0, 0, 0, S(1)/2]]) >>> X = DiscreteMarkovChain('X', trans_probs=T) >>> states, A, B, C = X.decompose() >>> states [2, 0, 1, 3, 4] >>> A # recurrent to recurrent Matrix([[1]]) >>> B # transient to recurrent Matrix([ [ 0], [2/5], [1/2], [ 0]]) >>> C # transient to transient Matrix([ [1/2, 1/2, 0, 0], [2/5, 1/5, 0, 0], [ 0, 0, 1/2, 0], [1/2, 0, 0, 1/2]]) This means that state 2 is the only absorbing state (since A is a 1x1 matrix). B is a 4x1 matrix since the 4 remaining transient states all merge into reccurent state 2. And C is the 4x4 matrix that shows how the transient states 0, 1, 3, 4 all interact. See Also ======== sympy.stats.DiscreteMarkovChain.communication_classes sympy.stats.DiscreteMarkovChain.canonical_form References ========== .. [1] https://en.wikipedia.org/wiki/Absorbing_Markov_chain .. [2] http://people.brandeis.edu/~igusa/Math56aS08/Math56a_S08_notes015.pdf """ trans_probs = self.transition_probabilities classes = self.communication_classes() r_states = [] t_states = [] for states, recurrent, period in classes: if recurrent: r_states += states else: t_states += states states = r_states + t_states indexes = [self.index_of[state] for state in states] A = Matrix(len(r_states), len(r_states), lambda i, j: trans_probs[indexes[i], indexes[j]]) B = Matrix(len(t_states), len(r_states), lambda i, j: trans_probs[indexes[len(r_states) + i], indexes[j]]) C = Matrix(len(t_states), len(t_states), lambda i, j: trans_probs[indexes[len(r_states) + i], indexes[len(r_states) + j]]) return states, A.as_immutable(), B.as_immutable(), C.as_immutable() def canonical_form(self) -> tTuple[tList[Basic], ImmutableMatrix]: """ Reorders the one-step transition matrix so that recurrent states appear first and transient states appear last. Other representations include inserting transient states first and recurrent states last. Returns ======= states, P_new ``states`` is the list that describes the order of the new states in the matrix so that the ith element in ``states`` is the state of the ith row of A. ``P_new`` is the new transition matrix in canonical form. Examples ======== >>> from sympy.stats import DiscreteMarkovChain >>> from sympy import Matrix, S You can convert your chain into canonical form: >>> T = Matrix([[S(1)/2, S(1)/2, 0, 0, 0], ... [S(2)/5, S(1)/5, S(2)/5, 0, 0], ... [0, 0, 1, 0, 0], ... [0, 0, S(1)/2, S(1)/2, 0], ... [S(1)/2, 0, 0, 0, S(1)/2]]) >>> X = DiscreteMarkovChain('X', list(range(1, 6)), trans_probs=T) >>> states, new_matrix = X.canonical_form() >>> states [3, 1, 2, 4, 5] >>> new_matrix Matrix([ [ 1, 0, 0, 0, 0], [ 0, 1/2, 1/2, 0, 0], [2/5, 2/5, 1/5, 0, 0], [1/2, 0, 0, 1/2, 0], [ 0, 1/2, 0, 0, 1/2]]) The new states are [3, 1, 2, 4, 5] and you can create a new chain with this and its canonical form will remain the same (since it is already in canonical form). >>> X = DiscreteMarkovChain('X', states, new_matrix) >>> states, new_matrix = X.canonical_form() >>> states [3, 1, 2, 4, 5] >>> new_matrix Matrix([ [ 1, 0, 0, 0, 0], [ 0, 1/2, 1/2, 0, 0], [2/5, 2/5, 1/5, 0, 0], [1/2, 0, 0, 1/2, 0], [ 0, 1/2, 0, 0, 1/2]]) This is not limited to absorbing chains: >>> T = Matrix([[0, 5, 5, 0, 0], ... [0, 0, 0, 10, 0], ... [5, 0, 5, 0, 0], ... [0, 10, 0, 0, 0], ... [0, 3, 0, 3, 4]])/10 >>> X = DiscreteMarkovChain('X', trans_probs=T) >>> states, new_matrix = X.canonical_form() >>> states [1, 3, 0, 2, 4] >>> new_matrix Matrix([ [ 0, 1, 0, 0, 0], [ 1, 0, 0, 0, 0], [ 1/2, 0, 0, 1/2, 0], [ 0, 0, 1/2, 1/2, 0], [3/10, 3/10, 0, 0, 2/5]]) See Also ======== sympy.stats.DiscreteMarkovChain.communication_classes sympy.stats.DiscreteMarkovChain.decompose References ========== .. [1] https://onlinelibrary.wiley.com/doi/pdf/10.1002/9780470316887.app1 .. [2] http://www.columbia.edu/~ww2040/6711F12/lect1023big.pdf """ states, A, B, C = self.decompose() O = zeros(A.shape[0], C.shape[1]) return states, BlockMatrix([[A, O], [B, C]]).as_explicit() def sample(self): """ Returns ======= sample: iterator object iterator object containing the sample """ if not isinstance(self.transition_probabilities, (Matrix, ImmutableMatrix)): raise ValueError("Transition Matrix must be provided for sampling") Tlist = self.transition_probabilities.tolist() samps = [random.choice(list(self.state_space))] yield samps[0] time = 1 densities = {} for state in self.state_space: states = list(self.state_space) densities[state] = {states[i]: Tlist[state][i] for i in range(len(states))} while time < S.Infinity: samps.append((next(sample_iter(FiniteRV("_", densities[samps[time - 1]]))))) yield samps[time] time += 1 class ContinuousMarkovChain(ContinuousTimeStochasticProcess, MarkovProcess): """ Represents continuous time Markov chain. Parameters ========== sym: Symbol/str state_space: Set Optional, by default, S.Reals gen_mat: Matrix/ImmutableMatrix/MatrixSymbol Optional, by default, None Examples ======== >>> from sympy.stats import ContinuousMarkovChain, P >>> from sympy import Matrix, S, Eq, Gt >>> G = Matrix([[-S(1), S(1)], [S(1), -S(1)]]) >>> C = ContinuousMarkovChain('C', state_space=[0, 1], gen_mat=G) >>> C.limiting_distribution() Matrix([[1/2, 1/2]]) >>> C.state_space {0, 1} >>> C.generator_matrix Matrix([ [-1, 1], [ 1, -1]]) Probability queries are supported >>> P(Eq(C(1.96), 0), Eq(C(0.78), 1)).round(5) 0.45279 >>> P(Gt(C(1.7), 0), Eq(C(0.82), 1)).round(5) 0.58602 Probability of expressions with multiple RandomIndexedSymbols can also be calculated provided there is only 1 RandomIndexedSymbol in the given condition. It is always better to use Rational instead of floating point numbers for the probabilities in the generator matrix to avoid errors. >>> from sympy import Gt, Le, Rational >>> G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]]) >>> C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G) >>> P(Eq(C(3.92), C(1.75)), Eq(C(0.46), 0)).round(5) 0.37933 >>> P(Gt(C(3.92), C(1.75)), Eq(C(0.46), 0)).round(5) 0.34211 >>> P(Le(C(1.57), C(3.14)), Eq(C(1.22), 1)).round(4) 0.7143 Symbolic probability queries are also supported >>> from sympy import S, symbols, Matrix, Rational, Eq, Gt >>> from sympy.stats import P, ContinuousMarkovChain >>> a,b,c,d = symbols('a b c d') >>> G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]]) >>> C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G) >>> query = P(Eq(C(a), b), Eq(C(c), d)) >>> query.subs({a:3.65 ,b:2, c:1.78, d:1}).evalf().round(10) 0.4002723175 >>> P(Eq(C(3.65), 2), Eq(C(1.78), 1)).round(10) 0.4002723175 >>> query_gt = P(Gt(C(a), b), Eq(C(c), d)) >>> query_gt.subs({a:43.2 ,b:0, c:3.29, d:2}).evalf().round(10) 0.6832579186 >>> P(Gt(C(43.2), 0), Eq(C(3.29), 2)).round(10) 0.6832579186 References ========== .. [1] https://en.wikipedia.org/wiki/Markov_chain#Continuous-time_Markov_chain .. [2] http://u.math.biu.ac.il/~amirgi/CTMCnotes.pdf """ index_set = S.Reals def __new__(cls, sym, state_space=None, gen_mat=None): sym = _symbol_converter(sym) state_space, gen_mat = MarkovProcess._sanity_checks(state_space, gen_mat) obj = Basic.__new__(cls, sym, state_space, gen_mat) indices = dict() if isinstance(obj.number_of_states, Integer): for index, state in enumerate(obj.state_space): indices[state] = index obj.index_of = indices return obj @property def generator_matrix(self): return self.args[2] @cacheit def transition_probabilities(self, gen_mat=None): t = Dummy('t') if isinstance(gen_mat, (Matrix, ImmutableMatrix)) and \ gen_mat.is_diagonalizable(): # for faster computation use diagonalized generator matrix Q, D = gen_mat.diagonalize() return Lambda(t, Q*exp(t*D)*Q.inv()) if gen_mat != None: return Lambda(t, exp(t*gen_mat)) def limiting_distribution(self): gen_mat = self.generator_matrix if gen_mat is None: return None if isinstance(gen_mat, MatrixSymbol): wm = MatrixSymbol('wm', 1, gen_mat.shape[0]) return Lambda((wm, gen_mat), Eq(wm*gen_mat, wm)) w = IndexedBase('w') wi = [w[i] for i in range(gen_mat.shape[0])] wm = Matrix([wi]) eqs = (wm*gen_mat).tolist()[0] eqs.append(sum(wi) - 1) soln = list(linsolve(eqs, wi))[0] return ImmutableMatrix([[sol for sol in soln]]) class BernoulliProcess(DiscreteTimeStochasticProcess): """ The Bernoulli process consists of repeated independent Bernoulli process trials with the same parameter `p`. It's assumed that the probability `p` applies to every trial and that the outcomes of each trial are independent of all the rest. Therefore Bernoulli Processs is Discrete State and Discrete Time Stochastic Process. Parameters ========== sym: Symbol/str success: Integer/str The event which is considered to be success, by default is 1. failure: Integer/str The event which is considered to be failure, by default is 0. p: Real Number between 0 and 1 Represents the probability of getting success. Examples ======== >>> from sympy.stats import BernoulliProcess, P, E >>> from sympy import Eq, Gt >>> B = BernoulliProcess("B", p=0.7, success=1, failure=0) >>> B.state_space {0, 1} >>> (B.p).round(2) 0.70 >>> B.success 1 >>> B.failure 0 >>> X = B[1] + B[2] + B[3] >>> P(Eq(X, 0)).round(2) 0.03 >>> P(Eq(X, 2)).round(2) 0.44 >>> P(Eq(X, 4)).round(2) 0 >>> P(Gt(X, 1)).round(2) 0.78 >>> P(Eq(B[1], 0) & Eq(B[2], 1) & Eq(B[3], 0) & Eq(B[4], 1)).round(2) 0.04 >>> B.joint_distribution(B[1], B[2]) JointDistributionHandmade(Lambda((B[1], B[2]), Piecewise((0.7, Eq(B[1], 1)), (0.3, Eq(B[1], 0)), (0, True))*Piecewise((0.7, Eq(B[2], 1)), (0.3, Eq(B[2], 0)), (0, True)))) >>> E(2*B[1] + B[2]).round(2) 2.10 >>> P(B[1] < 1).round(2) 0.30 References ========== .. [1] https://en.wikipedia.org/wiki/Bernoulli_process .. [2] https://mathcs.clarku.edu/~djoyce/ma217/bernoulli.pdf """ index_set = S.Naturals0 def __new__(cls, sym, p, success=1, failure=0): _value_check(p >= 0 and p <= 1, 'Value of p must be between 0 and 1.') sym = _symbol_converter(sym) p = _sympify(p) success = _sym_sympify(success) failure = _sym_sympify(failure) return Basic.__new__(cls, sym, p, success, failure) @property def symbol(self): return self.args[0] @property def p(self): return self.args[1] @property def success(self): return self.args[2] @property def failure(self): return self.args[3] @property def state_space(self): return _set_converter([self.success, self.failure]) def distribution(self, key=None): if key is None: self._deprecation_warn_distribution() return BernoulliDistribution(self.p) return BernoulliDistribution(self.p, self.success, self.failure) def simple_rv(self, rv): return Bernoulli(rv.name, p=self.p, succ=self.success, fail=self.failure) def expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Computes expectation. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. Returns ======= Expectation of the RandomIndexedSymbol. """ return _SubstituteRV._expectation(expr, condition, evaluate, **kwargs) def probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Computes probability. Parameters ========== condition: Relational Condition for which probability has to be computed. Must contain a RandomIndexedSymbol of the process. given_condition: Relational/And The given conditions under which computations should be done. Returns ======= Probability of the condition. """ return _SubstituteRV._probability(condition, given_condition, evaluate, **kwargs) def density(self, x): return Piecewise((self.p, Eq(x, self.success)), (1 - self.p, Eq(x, self.failure)), (S.Zero, True)) class _SubstituteRV: """ Internal class to handle the queries of expectation and probability by substitution. """ @staticmethod def _rvindexed_subs(expr, condition=None): """ Substitutes the RandomIndexedSymbol with the RandomSymbol with same name, distribution and probability as RandomIndexedSymbol. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. """ rvs_expr = random_symbols(expr) if len(rvs_expr) != 0: swapdict_expr = {} for rv in rvs_expr: if isinstance(rv, RandomIndexedSymbol): newrv = rv.pspace.process.simple_rv(rv) # substitute with equivalent simple rv swapdict_expr[rv] = newrv expr = expr.subs(swapdict_expr) rvs_cond = random_symbols(condition) if len(rvs_cond)!=0: swapdict_cond = {} for rv in rvs_cond: if isinstance(rv, RandomIndexedSymbol): newrv = rv.pspace.process.simple_rv(rv) swapdict_cond[rv] = newrv condition = condition.subs(swapdict_cond) return expr, condition @classmethod def _expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Internal method for computing expectation of indexed RV. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. Returns ======= Expectation of the RandomIndexedSymbol. """ new_expr, new_condition = self._rvindexed_subs(expr, condition) if not is_random(new_expr): return new_expr new_pspace = pspace(new_expr) if new_condition is not None: new_expr = given(new_expr, new_condition) if new_expr.is_Add: # As E is Linear return Add(*[new_pspace.compute_expectation( expr=arg, evaluate=evaluate, **kwargs) for arg in new_expr.args]) return new_pspace.compute_expectation( new_expr, evaluate=evaluate, **kwargs) @classmethod def _probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Internal method for computing probability of indexed RV Parameters ========== condition: Relational Condition for which probability has to be computed. Must contain a RandomIndexedSymbol of the process. given_condition: Relational/And The given conditions under which computations should be done. Returns ======= Probability of the condition. """ new_condition, new_givencondition = self._rvindexed_subs(condition, given_condition) if isinstance(new_givencondition, RandomSymbol): condrv = random_symbols(new_condition) if len(condrv) == 1 and condrv[0] == new_givencondition: return BernoulliDistribution(self._probability(new_condition), 0, 1) if any(dependent(rv, new_givencondition) for rv in condrv): return Probability(new_condition, new_givencondition) else: return self._probability(new_condition) if new_givencondition is not None and \ not isinstance(new_givencondition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (new_givencondition)) if new_givencondition == False or new_condition == False: return S.Zero if new_condition == True: return S.One if not isinstance(new_condition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (new_condition)) if new_givencondition is not None: # If there is a condition # Recompute on new conditional expr return self._probability(given(new_condition, new_givencondition, **kwargs), **kwargs) result = pspace(new_condition).probability(new_condition, **kwargs) if evaluate and hasattr(result, 'doit'): return result.doit() else: return result def get_timerv_swaps(expr, condition): """ Finds the appropriate interval for each time stamp in expr by parsing the given condition and returns intervals for each timestamp and dictionary that maps variable time-stamped Random Indexed Symbol to its corresponding Random Indexed variable with fixed time stamp. Parameters ========== expr: Sympy Expression Expression containing Random Indexed Symbols with variable time stamps condition: Relational/Boolean Expression Expression containing time bounds of variable time stamps in expr Examples ======== >>> from sympy.stats.stochastic_process_types import get_timerv_swaps, PoissonProcess >>> from sympy import symbols, Contains, Interval >>> x, t, d = symbols('x t d', positive=True) >>> X = PoissonProcess("X", 3) >>> get_timerv_swaps(x*X(t), Contains(t, Interval.Lopen(0, 1))) ([Interval.Lopen(0, 1)], {X(t): X(1)}) >>> get_timerv_swaps((X(t)**2 + X(d)**2), Contains(t, Interval.Lopen(0, 1)) ... & Contains(d, Interval.Ropen(1, 4))) # doctest: +SKIP ([Interval.Ropen(1, 4), Interval.Lopen(0, 1)], {X(d): X(3), X(t): X(1)}) Returns ======= intervals: list List of Intervals/FiniteSet on which each time stamp is defined rv_swap: dict Dictionary mapping variable time Random Indexed Symbol to constant time Random Indexed Variable """ if not isinstance(condition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (condition)) expr_syms = list(expr.atoms(RandomIndexedSymbol)) if isinstance(condition, (And, Or)): given_cond_args = condition.args else: # single condition given_cond_args = (condition, ) rv_swap = {} intervals = [] for expr_sym in expr_syms: for arg in given_cond_args: if arg.has(expr_sym.key) and isinstance(expr_sym.key, Symbol): intv = _set_converter(arg.args[1]) diff_key = intv._sup - intv._inf if diff_key == oo: raise ValueError("%s should have finite bounds" % str(expr_sym.name)) elif diff_key == S.Zero: # has singleton set diff_key = intv._sup rv_swap[expr_sym] = expr_sym.subs({expr_sym.key: diff_key}) intervals.append(intv) return intervals, rv_swap class CountingProcess(ContinuousTimeStochasticProcess): """ This class handles the common methods of the Counting Processes such as Poisson, Wiener and Gamma Processes """ index_set = _set_converter(Interval(0, oo)) @property def symbol(self): return self.args[0] def expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Computes expectation Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Boolean The given conditions under which computations should be done, i.e, the intervals on which each variable time stamp in expr is defined Returns ======= Expectation of the given expr """ if condition is not None: intervals, rv_swap = get_timerv_swaps(expr, condition) # they are independent when they have non-overlapping intervals if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet for intv_comb in itertools.combinations(intervals, 2)): if expr.is_Add: return Add.fromiter(self.expectation(arg, condition) for arg in expr.args) expr = expr.subs(rv_swap) else: return Expectation(expr, condition) return _SubstituteRV._expectation(expr, evaluate=evaluate, **kwargs) def _solve_argwith_tworvs(self, arg): if arg.args[0].key >= arg.args[1].key or isinstance(arg, Eq): diff_key = abs(arg.args[0].key - arg.args[1].key) rv = arg.args[0] arg = arg.__class__(rv.pspace.process(diff_key), 0) else: diff_key = arg.args[1].key - arg.args[0].key rv = arg.args[1] arg = arg.__class__(rv.pspace.process(diff_key), 0) return arg def _solve_numerical(self, condition, given_condition=None): if isinstance(condition, And): args_list = list(condition.args) else: args_list = [condition] if given_condition is not None: if isinstance(given_condition, And): args_list.extend(list(given_condition.args)) else: args_list.extend([given_condition]) # sort the args based on timestamp to get the independent increments in # each segment using all the condition args as well as given_condition args args_list = sorted(args_list, key=lambda x: x.args[0].key) result = [] cond_args = list(condition.args) if isinstance(condition, And) else [condition] if args_list[0] in cond_args and not (is_random(args_list[0].args[0]) and is_random(args_list[0].args[1])): result.append(_SubstituteRV._probability(args_list[0])) if is_random(args_list[0].args[0]) and is_random(args_list[0].args[1]): arg = self._solve_argwith_tworvs(args_list[0]) result.append(_SubstituteRV._probability(arg)) for i in range(len(args_list) - 1): curr, nex = args_list[i], args_list[i + 1] diff_key = nex.args[0].key - curr.args[0].key working_set = curr.args[0].pspace.process.state_space if curr.args[1] > nex.args[1]: #impossible condition so return 0 result.append(0) break if isinstance(curr, Eq): working_set = Intersection(working_set, Interval.Lopen(curr.args[1], oo)) else: working_set = Intersection(working_set, curr.as_set()) if isinstance(nex, Eq): working_set = Intersection(working_set, Interval(-oo, nex.args[1])) else: working_set = Intersection(working_set, nex.as_set()) if working_set == EmptySet: rv = Eq(curr.args[0].pspace.process(diff_key), 0) result.append(_SubstituteRV._probability(rv)) else: if working_set.is_finite_set: if isinstance(curr, Eq) and isinstance(nex, Eq): rv = Eq(curr.args[0].pspace.process(diff_key), len(working_set)) result.append(_SubstituteRV._probability(rv)) elif isinstance(curr, Eq) ^ isinstance(nex, Eq): result.append(Add.fromiter(_SubstituteRV._probability(Eq( curr.args[0].pspace.process(diff_key), x)) for x in range(len(working_set)))) else: n = len(working_set) result.append(Add.fromiter((n - x)*_SubstituteRV._probability(Eq( curr.args[0].pspace.process(diff_key), x)) for x in range(n))) else: result.append(_SubstituteRV._probability( curr.args[0].pspace.process(diff_key) <= working_set._sup - working_set._inf)) return Mul.fromiter(result) def probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Computes probability. Parameters ========== condition: Relational Condition for which probability has to be computed. Must contain a RandomIndexedSymbol of the process. given_condition: Relational, Boolean The given conditions under which computations should be done, i.e, the intervals on which each variable time stamp in expr is defined Returns ======= Probability of the condition """ check_numeric = True if isinstance(condition, (And, Or)): cond_args = condition.args else: cond_args = (condition, ) # check that condition args are numeric or not if not all(arg.args[0].key.is_number for arg in cond_args): check_numeric = False if given_condition is not None: check_given_numeric = True if isinstance(given_condition, (And, Or)): given_cond_args = given_condition.args else: given_cond_args = (given_condition, ) # check that given condition args are numeric or not if given_condition.has(Contains): check_given_numeric = False # Handle numerical queries if check_numeric and check_given_numeric: res = [] if isinstance(condition, Or): res.append(Add.fromiter(self._solve_numerical(arg, given_condition) for arg in condition.args)) if isinstance(given_condition, Or): res.append(Add.fromiter(self._solve_numerical(condition, arg) for arg in given_condition.args)) if res: return Add.fromiter(res) return self._solve_numerical(condition, given_condition) # No numeric queries, go by Contains?... then check that all the # given condition are in form of `Contains` if not all(arg.has(Contains) for arg in given_cond_args): raise ValueError("If given condition is passed with `Contains`, then " "please pass the evaluated condition with its corresponding information " "in terms of intervals of each time stamp to be passed in given condition.") intervals, rv_swap = get_timerv_swaps(condition, given_condition) # they are independent when they have non-overlapping intervals if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet for intv_comb in itertools.combinations(intervals, 2)): if isinstance(condition, And): return Mul.fromiter(self.probability(arg, given_condition) for arg in condition.args) elif isinstance(condition, Or): return Add.fromiter(self.probability(arg, given_condition) for arg in condition.args) condition = condition.subs(rv_swap) else: return Probability(condition, given_condition) if check_numeric: return self._solve_numerical(condition) return _SubstituteRV._probability(condition, evaluate=evaluate, **kwargs) class PoissonProcess(CountingProcess): """ The Poisson process is a counting process. It is usually used in scenarios where we are counting the occurrences of certain events that appear to happen at a certain rate, but completely at random. Parameters ========== sym: Symbol/str lamda: Positive number Rate of the process, ``lamda > 0`` Examples ======== >>> from sympy.stats import PoissonProcess, P, E >>> from sympy import symbols, Eq, Ne, Contains, Interval >>> X = PoissonProcess("X", lamda=3) >>> X.state_space Naturals0 >>> X.lamda 3 >>> t1, t2 = symbols('t1 t2', positive=True) >>> P(X(t1) < 4) (9*t1**3/2 + 9*t1**2/2 + 3*t1 + 1)*exp(-3*t1) >>> P(Eq(X(t1), 2) | Ne(X(t1), 4), Contains(t1, Interval.Ropen(2, 4))) 1 - 36*exp(-6) >>> P(Eq(X(t1), 2) & Eq(X(t2), 3), Contains(t1, Interval.Lopen(0, 2)) ... & Contains(t2, Interval.Lopen(2, 4))) 648*exp(-12) >>> E(X(t1)) 3*t1 >>> E(X(t1)**2 + 2*X(t2), Contains(t1, Interval.Lopen(0, 1)) ... & Contains(t2, Interval.Lopen(1, 2))) 18 >>> P(X(3) < 1, Eq(X(1), 0)) exp(-6) >>> P(Eq(X(4), 3), Eq(X(2), 3)) exp(-6) >>> P(X(2) <= 3, X(1) > 1) 5*exp(-3) Merging two Poisson Processes >>> Y = PoissonProcess("Y", lamda=4) >>> Z = X + Y >>> Z.lamda 7 Splitting a Poisson Process into two independent Poisson Processes >>> N, M = Z.split(l1=2, l2=5) >>> N.lamda, M.lamda (2, 5) References ========== .. [1] https://www.probabilitycourse.com/chapter11/11_0_0_intro.php .. [2] https://en.wikipedia.org/wiki/Poisson_point_process """ def __new__(cls, sym, lamda): _value_check(lamda > 0, 'lamda should be a positive number.') sym = _symbol_converter(sym) lamda = _sympify(lamda) return Basic.__new__(cls, sym, lamda) @property def lamda(self): return self.args[1] @property def state_space(self): return S.Naturals0 def distribution(self, key): if isinstance(key, RandomIndexedSymbol): self._deprecation_warn_distribution() return PoissonDistribution(self.lamda*key.key) return PoissonDistribution(self.lamda*key) def density(self, x): return (self.lamda*x.key)**x / factorial(x) * exp(-(self.lamda*x.key)) def simple_rv(self, rv): return Poisson(rv.name, lamda=self.lamda*rv.key) def __add__(self, other): if not isinstance(other, PoissonProcess): raise ValueError("Only instances of Poisson Process can be merged") return PoissonProcess(Dummy(self.symbol.name + other.symbol.name), self.lamda + other.lamda) def split(self, l1, l2): if _sympify(l1 + l2) != self.lamda: raise ValueError("Sum of l1 and l2 should be %s" % str(self.lamda)) return PoissonProcess(Dummy("l1"), l1), PoissonProcess(Dummy("l2"), l2) class WienerProcess(CountingProcess): """ The Wiener process is a real valued continuous-time stochastic process. In physics it is used to study Brownian motion and therefore also known as Brownian Motion. Parameters ========== sym: Symbol/str Examples ======== >>> from sympy.stats import WienerProcess, P, E >>> from sympy import symbols, Contains, Interval >>> X = WienerProcess("X") >>> X.state_space Reals >>> t1, t2 = symbols('t1 t2', positive=True) >>> P(X(t1) < 7).simplify() erf(7*sqrt(2)/(2*sqrt(t1)))/2 + 1/2 >>> P((X(t1) > 2) | (X(t1) < 4), Contains(t1, Interval.Ropen(2, 4))).simplify() -erf(1)/2 + erf(2)/2 + 1 >>> E(X(t1)) 0 >>> E(X(t1) + 2*X(t2), Contains(t1, Interval.Lopen(0, 1)) ... & Contains(t2, Interval.Lopen(1, 2))) 0 References ========== .. [1] https://www.probabilitycourse.com/chapter11/11_4_0_brownian_motion_wiener_process.php .. [2] https://en.wikipedia.org/wiki/Wiener_process """ def __new__(cls, sym): sym = _symbol_converter(sym) return Basic.__new__(cls, sym) @property def state_space(self): return S.Reals def distribution(self, key): if isinstance(key, RandomIndexedSymbol): self._deprecation_warn_distribution() return NormalDistribution(0, sqrt(key.key)) return NormalDistribution(0, sqrt(key)) def density(self, x): return exp(-x**2/(2*x.key)) / (sqrt(2*pi)*sqrt(x.key)) def simple_rv(self, rv): return Normal(rv.name, 0, sqrt(rv.key)) class GammaProcess(CountingProcess): """ A Gamma process is a random process with independent gamma distributed increments. It is a pure-jump increasing Levy process. Parameters ========== sym: Symbol/str lamda: Positive number Jump size of the process, ``lamda > 0`` gamma: Positive number Rate of jump arrivals, ``gamma > 0`` Examples ======== >>> from sympy.stats import GammaProcess, E, P, variance >>> from sympy import symbols, Contains, Interval, Not >>> t, d, x, l, g = symbols('t d x l g', positive=True) >>> X = GammaProcess("X", l, g) >>> E(X(t)) g*t/l >>> variance(X(t)).simplify() g*t/l**2 >>> X = GammaProcess('X', 1, 2) >>> P(X(t) < 1).simplify() lowergamma(2*t, 1)/gamma(2*t) >>> P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & ... Contains(d, Interval.Lopen(7, 8))).simplify() -4*exp(-3) + 472*exp(-8)/3 + 1 >>> E(X(2) + x*E(X(5))) 10*x + 4 References ========== .. [1] https://en.wikipedia.org/wiki/Gamma_process """ def __new__(cls, sym, lamda, gamma): _value_check(lamda > 0, 'lamda should be a positive number') _value_check(gamma > 0, 'gamma should be a positive number') sym = _symbol_converter(sym) gamma = _sympify(gamma) lamda = _sympify(lamda) return Basic.__new__(cls, sym, lamda, gamma) @property def lamda(self): return self.args[1] @property def gamma(self): return self.args[2] @property def state_space(self): return _set_converter(Interval(0, oo)) def distribution(self, key): if isinstance(key, RandomIndexedSymbol): self._deprecation_warn_distribution() return GammaDistribution(self.gamma*key.key, 1/self.lamda) return GammaDistribution(self.gamma*key, 1/self.lamda) def density(self, x): k = self.gamma*x.key theta = 1/self.lamda return x**(k - 1) * exp(-x/theta) / (gamma(k)*theta**k) def simple_rv(self, rv): return Gamma(rv.name, self.gamma*rv.key, 1/self.lamda)
d646022f432d467f0938dd794d31583328382206bbf02cc8b514b8f3f4fa389c
from sympy.sets import FiniteSet from sympy import (sqrt, log, exp, FallingFactorial, Rational, Eq, Dummy, piecewise_fold, solveset, Integral) from .rv import (probability, expectation, density, where, given, pspace, cdf, PSpace, characteristic_function, sample, sample_iter, random_symbols, independent, dependent, sampling_density, moment_generating_function, quantile, is_random, sample_stochastic_process) __all__ = ['P', 'E', 'H', 'density', 'where', 'given', 'sample', 'cdf', 'characteristic_function', 'pspace', 'sample_iter', 'variance', 'std', 'skewness', 'kurtosis', 'covariance', 'dependent', 'entropy', 'median', 'independent', 'random_symbols', 'correlation', 'factorial_moment', 'moment', 'cmoment', 'sampling_density', 'moment_generating_function', 'smoment', 'quantile', 'sample_stochastic_process'] def moment(X, n, c=0, condition=None, *, evaluate=True, **kwargs): """ Return the nth moment of a random expression about c. .. math:: moment(X, c, n) = E((X-c)^{n}) Default value of c is 0. Examples ======== >>> from sympy.stats import Die, moment, E >>> X = Die('X', 6) >>> moment(X, 1, 6) -5/2 >>> moment(X, 2) 91/6 >>> moment(X, 1) == E(X) True """ from sympy.stats.symbolic_probability import Moment if evaluate: return Moment(X, n, c, condition).doit() return Moment(X, n, c, condition).rewrite(Integral) def variance(X, condition=None, **kwargs): """ Variance of a random expression. .. math:: variance(X) = E((X-E(X))^{2}) Examples ======== >>> from sympy.stats import Die, Bernoulli, variance >>> from sympy import simplify, Symbol >>> X = Die('X', 6) >>> p = Symbol('p') >>> B = Bernoulli('B', p, 1, 0) >>> variance(2*X) 35/3 >>> simplify(variance(B)) p*(1 - p) """ if is_random(X) and pspace(X) == PSpace(): from sympy.stats.symbolic_probability import Variance return Variance(X, condition) return cmoment(X, 2, condition, **kwargs) def standard_deviation(X, condition=None, **kwargs): r""" Standard Deviation of a random expression .. math:: std(X) = \sqrt(E((X-E(X))^{2})) Examples ======== >>> from sympy.stats import Bernoulli, std >>> from sympy import Symbol, simplify >>> p = Symbol('p') >>> B = Bernoulli('B', p, 1, 0) >>> simplify(std(B)) sqrt(p*(1 - p)) """ return sqrt(variance(X, condition, **kwargs)) std = standard_deviation def entropy(expr, condition=None, **kwargs): """ Calculuates entropy of a probability distribution. Parameters ========== expression : the random expression whose entropy is to be calculated condition : optional, to specify conditions on random expression b: base of the logarithm, optional By default, it is taken as Euler's number Returns ======= result : Entropy of the expression, a constant Examples ======== >>> from sympy.stats import Normal, Die, entropy >>> X = Normal('X', 0, 1) >>> entropy(X) log(2)/2 + 1/2 + log(pi)/2 >>> D = Die('D', 4) >>> entropy(D) log(4) References ========== .. [1] https://en.wikipedia.org/wiki/Entropy_(information_theory) .. [2] https://www.crmarsh.com/static/pdf/Charles_Marsh_Continuous_Entropy.pdf .. [3] http://www.math.uconn.edu/~kconrad/blurbs/analysis/entropypost.pdf """ pdf = density(expr, condition, **kwargs) base = kwargs.get('b', exp(1)) if isinstance(pdf, dict): return sum([-prob*log(prob, base) for prob in pdf.values()]) return expectation(-log(pdf(expr), base)) def covariance(X, Y, condition=None, **kwargs): """ Covariance of two random expressions. Explanation =========== The expectation that the two variables will rise and fall together .. math:: covariance(X,Y) = E((X-E(X)) (Y-E(Y))) Examples ======== >>> from sympy.stats import Exponential, covariance >>> from sympy import Symbol >>> rate = Symbol('lambda', positive=True, real=True, finite=True) >>> X = Exponential('X', rate) >>> Y = Exponential('Y', rate) >>> covariance(X, X) lambda**(-2) >>> covariance(X, Y) 0 >>> covariance(X, Y + rate*X) 1/lambda """ if (is_random(X) and pspace(X) == PSpace()) or (is_random(Y) and pspace(Y) == PSpace()): from sympy.stats.symbolic_probability import Covariance return Covariance(X, Y, condition) return expectation( (X - expectation(X, condition, **kwargs)) * (Y - expectation(Y, condition, **kwargs)), condition, **kwargs) def correlation(X, Y, condition=None, **kwargs): r""" Correlation of two random expressions, also known as correlation coefficient or Pearson's correlation. Explanation =========== The normalized expectation that the two variables will rise and fall together .. math:: correlation(X,Y) = E((X-E(X))(Y-E(Y)) / (\sigma_x \sigma_y)) Examples ======== >>> from sympy.stats import Exponential, correlation >>> from sympy import Symbol >>> rate = Symbol('lambda', positive=True, real=True, finite=True) >>> X = Exponential('X', rate) >>> Y = Exponential('Y', rate) >>> correlation(X, X) 1 >>> correlation(X, Y) 0 >>> correlation(X, Y + rate*X) 1/sqrt(1 + lambda**(-2)) """ return covariance(X, Y, condition, **kwargs)/(std(X, condition, **kwargs) * std(Y, condition, **kwargs)) def cmoment(X, n, condition=None, *, evaluate=True, **kwargs): """ Return the nth central moment of a random expression about its mean. .. math:: cmoment(X, n) = E((X - E(X))^{n}) Examples ======== >>> from sympy.stats import Die, cmoment, variance >>> X = Die('X', 6) >>> cmoment(X, 3) 0 >>> cmoment(X, 2) 35/12 >>> cmoment(X, 2) == variance(X) True """ from sympy.stats.symbolic_probability import CentralMoment if evaluate: return CentralMoment(X, n, condition).doit() return CentralMoment(X, n, condition).rewrite(Integral) def smoment(X, n, condition=None, **kwargs): r""" Return the nth Standardized moment of a random expression. .. math:: smoment(X, n) = E(((X - \mu)/\sigma_X)^{n}) Examples ======== >>> from sympy.stats import skewness, Exponential, smoment >>> from sympy import Symbol >>> rate = Symbol('lambda', positive=True, real=True, finite=True) >>> Y = Exponential('Y', rate) >>> smoment(Y, 4) 9 >>> smoment(Y, 4) == smoment(3*Y, 4) True >>> smoment(Y, 3) == skewness(Y) True """ sigma = std(X, condition, **kwargs) return (1/sigma)**n*cmoment(X, n, condition, **kwargs) def skewness(X, condition=None, **kwargs): r""" Measure of the asymmetry of the probability distribution. Explanation =========== Positive skew indicates that most of the values lie to the right of the mean. .. math:: skewness(X) = E(((X - E(X))/\sigma_X)^{3}) Parameters ========== condition : Expr containing RandomSymbols A conditional expression. skewness(X, X>0) is skewness of X given X > 0 Examples ======== >>> from sympy.stats import skewness, Exponential, Normal >>> from sympy import Symbol >>> X = Normal('X', 0, 1) >>> skewness(X) 0 >>> skewness(X, X > 0) # find skewness given X > 0 (-sqrt(2)/sqrt(pi) + 4*sqrt(2)/pi**(3/2))/(1 - 2/pi)**(3/2) >>> rate = Symbol('lambda', positive=True, real=True, finite=True) >>> Y = Exponential('Y', rate) >>> skewness(Y) 2 """ return smoment(X, 3, condition=condition, **kwargs) def kurtosis(X, condition=None, **kwargs): r""" Characterizes the tails/outliers of a probability distribution. Explanation =========== Kurtosis of any univariate normal distribution is 3. Kurtosis less than 3 means that the distribution produces fewer and less extreme outliers than the normal distribution. .. math:: kurtosis(X) = E(((X - E(X))/\sigma_X)^{4}) Parameters ========== condition : Expr containing RandomSymbols A conditional expression. kurtosis(X, X>0) is kurtosis of X given X > 0 Examples ======== >>> from sympy.stats import kurtosis, Exponential, Normal >>> from sympy import Symbol >>> X = Normal('X', 0, 1) >>> kurtosis(X) 3 >>> kurtosis(X, X > 0) # find kurtosis given X > 0 (-4/pi - 12/pi**2 + 3)/(1 - 2/pi)**2 >>> rate = Symbol('lamda', positive=True, real=True, finite=True) >>> Y = Exponential('Y', rate) >>> kurtosis(Y) 9 References ========== .. [1] https://en.wikipedia.org/wiki/Kurtosis .. [2] http://mathworld.wolfram.com/Kurtosis.html """ return smoment(X, 4, condition=condition, **kwargs) def factorial_moment(X, n, condition=None, **kwargs): """ The factorial moment is a mathematical quantity defined as the expectation or average of the falling factorial of a random variable. .. math:: factorial-moment(X, n) = E(X(X - 1)(X - 2)...(X - n + 1)) Parameters ========== n: A natural number, n-th factorial moment. condition : Expr containing RandomSymbols A conditional expression. Examples ======== >>> from sympy.stats import factorial_moment, Poisson, Binomial >>> from sympy import Symbol, S >>> lamda = Symbol('lamda') >>> X = Poisson('X', lamda) >>> factorial_moment(X, 2) lamda**2 >>> Y = Binomial('Y', 2, S.Half) >>> factorial_moment(Y, 2) 1/2 >>> factorial_moment(Y, 2, Y > 1) # find factorial moment for Y > 1 2 References ========== .. [1] https://en.wikipedia.org/wiki/Factorial_moment .. [2] http://mathworld.wolfram.com/FactorialMoment.html """ return expectation(FallingFactorial(X, n), condition=condition, **kwargs) def median(X, evaluate=True, **kwargs): r""" Calculuates the median of the probability distribution. Explanation =========== Mathematically, median of Probability distribution is defined as all those values of `m` for which the following condition is satisfied .. math:: P(X\leq m) \geq \frac{1}{2} \text{ and} \text{ } P(X\geq m)\geq \frac{1}{2} Parameters ========== X: The random expression whose median is to be calculated. Returns ======= The FiniteSet or an Interval which contains the median of the random expression. Examples ======== >>> from sympy.stats import Normal, Die, median >>> N = Normal('N', 3, 1) >>> median(N) {3} >>> D = Die('D') >>> median(D) {3, 4} References ========== .. [1] https://en.wikipedia.org/wiki/Median#Probability_distributions """ if not is_random(X): return X from sympy.stats.crv import ContinuousPSpace from sympy.stats.drv import DiscretePSpace from sympy.stats.frv import FinitePSpace if isinstance(pspace(X), FinitePSpace): cdf = pspace(X).compute_cdf(X) result = [] for key, value in cdf.items(): if value>= Rational(1, 2) and (1 - value) + \ pspace(X).probability(Eq(X, key)) >= Rational(1, 2): result.append(key) return FiniteSet(*result) if isinstance(pspace(X), ContinuousPSpace) or isinstance(pspace(X), DiscretePSpace): cdf = pspace(X).compute_cdf(X) x = Dummy('x') result = solveset(piecewise_fold(cdf(x) - Rational(1, 2)), x, pspace(X).set) return result raise NotImplementedError("The median of %s is not implemeted."%str(pspace(X))) def coskewness(X, Y, Z, condition=None, **kwargs): r""" Calculates the co-skewness of three random variables. Explanation =========== Mathematically Coskewness is defined as .. math:: coskewness(X,Y,Z)=\frac{E[(X-E[X]) * (Y-E[Y]) * (Z-E[Z])]} {\sigma_{X}\sigma_{Y}\sigma_{Z}} Parameters ========== X : RandomSymbol Random Variable used to calculate coskewness Y : RandomSymbol Random Variable used to calculate coskewness Z : RandomSymbol Random Variable used to calculate coskewness condition : Expr containing RandomSymbols A conditional expression Examples ======== >>> from sympy.stats import coskewness, Exponential, skewness >>> from sympy import symbols >>> p = symbols('p', positive=True) >>> X = Exponential('X', p) >>> Y = Exponential('Y', 2*p) >>> coskewness(X, Y, Y) 0 >>> coskewness(X, Y + X, Y + 2*X) 16*sqrt(85)/85 >>> coskewness(X + 2*Y, Y + X, Y + 2*X, X > 3) 9*sqrt(170)/85 >>> coskewness(Y, Y, Y) == skewness(Y) True >>> coskewness(X, Y + p*X, Y + 2*p*X) 4/(sqrt(1 + 1/(4*p**2))*sqrt(4 + 1/(4*p**2))) Returns ======= coskewness : The coskewness of the three random variables References ========== .. [1] https://en.wikipedia.org/wiki/Coskewness """ num = expectation((X - expectation(X, condition, **kwargs)) \ * (Y - expectation(Y, condition, **kwargs)) \ * (Z - expectation(Z, condition, **kwargs)), condition, **kwargs) den = std(X, condition, **kwargs) * std(Y, condition, **kwargs) \ * std(Z, condition, **kwargs) return num/den P = probability E = expectation H = entropy
553dbe80c5e0a90a3ec46e23dbc0676ac43d38d967d510c9adbbca4e6db3c801
""" Main Random Variables Module Defines abstract random variable type. Contains interfaces for probability space object (PSpace) as well as standard operators, P, E, sample, density, where, quantile See Also ======== sympy.stats.crv sympy.stats.frv sympy.stats.rv_interface """ from functools import singledispatch from typing import Tuple as tTuple from sympy import (Basic, S, Expr, Symbol, Tuple, And, Add, Eq, lambdify, Or, Equality, Lambda, sympify, Dummy, Ne, KroneckerDelta, DiracDelta, Mul, Indexed, MatrixSymbol, Function, prod) from sympy.core.relational import Relational from sympy.core.sympify import _sympify from sympy.sets.sets import FiniteSet, ProductSet, Intersection from sympy.solvers.solveset import solveset from sympy.external import import_module from sympy.utilities.misc import filldedent from sympy.utilities.decorator import doctest_depends_on from sympy.utilities.exceptions import SymPyDeprecationWarning import warnings x = Symbol('x') @singledispatch def is_random(x): return False @is_random.register(Basic) def _(x): atoms = x.free_symbols return any(is_random(i) for i in atoms) class RandomDomain(Basic): """ Represents a set of variables and the values which they can take. See Also ======== sympy.stats.crv.ContinuousDomain sympy.stats.frv.FiniteDomain """ is_ProductDomain = False is_Finite = False is_Continuous = False is_Discrete = False def __new__(cls, symbols, *args): symbols = FiniteSet(*symbols) return Basic.__new__(cls, symbols, *args) @property def symbols(self): return self.args[0] @property def set(self): return self.args[1] def __contains__(self, other): raise NotImplementedError() def compute_expectation(self, expr): raise NotImplementedError() class SingleDomain(RandomDomain): """ A single variable and its domain. See Also ======== sympy.stats.crv.SingleContinuousDomain sympy.stats.frv.SingleFiniteDomain """ def __new__(cls, symbol, set): assert symbol.is_Symbol return Basic.__new__(cls, symbol, set) @property def symbol(self): return self.args[0] @property def symbols(self): return FiniteSet(self.symbol) def __contains__(self, other): if len(other) != 1: return False sym, val = tuple(other)[0] return self.symbol == sym and val in self.set class MatrixDomain(RandomDomain): """ A Random Matrix variable and its domain. """ def __new__(cls, symbol, set): symbol, set = _symbol_converter(symbol), _sympify(set) return Basic.__new__(cls, symbol, set) @property def symbol(self): return self.args[0] @property def symbols(self): return FiniteSet(self.symbol) class ConditionalDomain(RandomDomain): """ A RandomDomain with an attached condition. See Also ======== sympy.stats.crv.ConditionalContinuousDomain sympy.stats.frv.ConditionalFiniteDomain """ def __new__(cls, fulldomain, condition): condition = condition.xreplace({rs: rs.symbol for rs in random_symbols(condition)}) return Basic.__new__(cls, fulldomain, condition) @property def symbols(self): return self.fulldomain.symbols @property def fulldomain(self): return self.args[0] @property def condition(self): return self.args[1] @property def set(self): raise NotImplementedError("Set of Conditional Domain not Implemented") def as_boolean(self): return And(self.fulldomain.as_boolean(), self.condition) class PSpace(Basic): """ A Probability Space. Explanation =========== Probability Spaces encode processes that equal different values probabilistically. These underly Random Symbols which occur in SymPy expressions and contain the mechanics to evaluate statistical statements. See Also ======== sympy.stats.crv.ContinuousPSpace sympy.stats.frv.FinitePSpace """ is_Finite = None # type: bool is_Continuous = None # type: bool is_Discrete = None # type: bool is_real = None # type: bool @property def domain(self): return self.args[0] @property def density(self): return self.args[1] @property def values(self): return frozenset(RandomSymbol(sym, self) for sym in self.symbols) @property def symbols(self): return self.domain.symbols def where(self, condition): raise NotImplementedError() def compute_density(self, expr): raise NotImplementedError() def sample(self, size=(), library='scipy', seed=None): raise NotImplementedError() def probability(self, condition): raise NotImplementedError() def compute_expectation(self, expr): raise NotImplementedError() class SinglePSpace(PSpace): """ Represents the probabilities of a set of random events that can be attributed to a single variable/symbol. """ def __new__(cls, s, distribution): s = _symbol_converter(s) return Basic.__new__(cls, s, distribution) @property def value(self): return RandomSymbol(self.symbol, self) @property def symbol(self): return self.args[0] @property def distribution(self): return self.args[1] @property def pdf(self): return self.distribution.pdf(self.symbol) class RandomSymbol(Expr): """ Random Symbols represent ProbabilitySpaces in SymPy Expressions. In principle they can take on any value that their symbol can take on within the associated PSpace with probability determined by the PSpace Density. Explanation =========== Random Symbols contain pspace and symbol properties. The pspace property points to the represented Probability Space The symbol is a standard SymPy Symbol that is used in that probability space for example in defining a density. You can form normal SymPy expressions using RandomSymbols and operate on those expressions with the Functions E - Expectation of a random expression P - Probability of a condition density - Probability Density of an expression given - A new random expression (with new random symbols) given a condition An object of the RandomSymbol type should almost never be created by the user. They tend to be created instead by the PSpace class's value method. Traditionally a user doesn't even do this but instead calls one of the convenience functions Normal, Exponential, Coin, Die, FiniteRV, etc.... """ def __new__(cls, symbol, pspace=None): from sympy.stats.joint_rv import JointRandomSymbol if pspace is None: # Allow single arg, representing pspace == PSpace() pspace = PSpace() symbol = _symbol_converter(symbol) if not isinstance(pspace, PSpace): raise TypeError("pspace variable should be of type PSpace") if cls == JointRandomSymbol and isinstance(pspace, SinglePSpace): cls = RandomSymbol return Basic.__new__(cls, symbol, pspace) is_finite = True is_symbol = True is_Atom = True _diff_wrt = True pspace = property(lambda self: self.args[1]) symbol = property(lambda self: self.args[0]) name = property(lambda self: self.symbol.name) def _eval_is_positive(self): return self.symbol.is_positive def _eval_is_integer(self): return self.symbol.is_integer def _eval_is_real(self): return self.symbol.is_real or self.pspace.is_real @property def is_commutative(self): return self.symbol.is_commutative @property def free_symbols(self): return {self} class RandomIndexedSymbol(RandomSymbol): def __new__(cls, idx_obj, pspace=None): if pspace is None: # Allow single arg, representing pspace == PSpace() pspace = PSpace() if not isinstance(idx_obj, (Indexed, Function)): raise TypeError("An Function or Indexed object is expected not %s"%(idx_obj)) return Basic.__new__(cls, idx_obj, pspace) symbol = property(lambda self: self.args[0]) name = property(lambda self: str(self.args[0])) @property def key(self): if isinstance(self.symbol, Indexed): return self.symbol.args[1] elif isinstance(self.symbol, Function): return self.symbol.args[0] @property def free_symbols(self): if self.key.free_symbols: free_syms = self.key.free_symbols free_syms.add(self) return free_syms return {self} @property def pspace(self): return self.args[1] class RandomMatrixSymbol(RandomSymbol, MatrixSymbol): # type: ignore def __new__(cls, symbol, n, m, pspace=None): n, m = _sympify(n), _sympify(m) symbol = _symbol_converter(symbol) if pspace is None: # Allow single arg, representing pspace == PSpace() pspace = PSpace() return Basic.__new__(cls, symbol, n, m, pspace) symbol = property(lambda self: self.args[0]) pspace = property(lambda self: self.args[3]) class ProductPSpace(PSpace): """ Abstract class for representing probability spaces with multiple random variables. See Also ======== sympy.stats.rv.IndependentProductPSpace sympy.stats.joint_rv.JointPSpace """ pass class IndependentProductPSpace(ProductPSpace): """ A probability space resulting from the merger of two independent probability spaces. Often created using the function, pspace. """ def __new__(cls, *spaces): rs_space_dict = {} for space in spaces: for value in space.values: rs_space_dict[value] = space symbols = FiniteSet(*[val.symbol for val in rs_space_dict.keys()]) # Overlapping symbols from sympy.stats.joint_rv import MarginalDistribution from sympy.stats.compound_rv import CompoundDistribution if len(symbols) < sum(len(space.symbols) for space in spaces if not isinstance(space.distribution, ( CompoundDistribution, MarginalDistribution))): raise ValueError("Overlapping Random Variables") if all(space.is_Finite for space in spaces): from sympy.stats.frv import ProductFinitePSpace cls = ProductFinitePSpace obj = Basic.__new__(cls, *FiniteSet(*spaces)) return obj @property def pdf(self): p = Mul(*[space.pdf for space in self.spaces]) return p.subs({rv: rv.symbol for rv in self.values}) @property def rs_space_dict(self): d = {} for space in self.spaces: for value in space.values: d[value] = space return d @property def symbols(self): return FiniteSet(*[val.symbol for val in self.rs_space_dict.keys()]) @property def spaces(self): return FiniteSet(*self.args) @property def values(self): return sumsets(space.values for space in self.spaces) def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs): rvs = rvs or self.values rvs = frozenset(rvs) for space in self.spaces: expr = space.compute_expectation(expr, rvs & space.values, evaluate=False, **kwargs) if evaluate and hasattr(expr, 'doit'): return expr.doit(**kwargs) return expr @property def domain(self): return ProductDomain(*[space.domain for space in self.spaces]) @property def density(self): raise NotImplementedError("Density not available for ProductSpaces") def sample(self, size=(), library='scipy', seed=None): return {k: v for space in self.spaces for k, v in space.sample(size=size, library=library, seed=seed).items()} def probability(self, condition, **kwargs): cond_inv = False if isinstance(condition, Ne): condition = Eq(condition.args[0], condition.args[1]) cond_inv = True elif isinstance(condition, And): # they are independent return Mul(*[self.probability(arg) for arg in condition.args]) elif isinstance(condition, Or): # they are independent return Add(*[self.probability(arg) for arg in condition.args]) expr = condition.lhs - condition.rhs rvs = random_symbols(expr) dens = self.compute_density(expr) if any(pspace(rv).is_Continuous for rv in rvs): from sympy.stats.crv import SingleContinuousPSpace from sympy.stats.crv_types import ContinuousDistributionHandmade if expr in self.values: # Marginalize all other random symbols out of the density randomsymbols = tuple(set(self.values) - frozenset([expr])) symbols = tuple(rs.symbol for rs in randomsymbols) pdf = self.domain.integrate(self.pdf, symbols, **kwargs) return Lambda(expr.symbol, pdf) dens = ContinuousDistributionHandmade(dens) z = Dummy('z', real=True) space = SingleContinuousPSpace(z, dens) result = space.probability(condition.__class__(space.value, 0)) else: from sympy.stats.drv import SingleDiscretePSpace from sympy.stats.drv_types import DiscreteDistributionHandmade dens = DiscreteDistributionHandmade(dens) z = Dummy('z', integer=True) space = SingleDiscretePSpace(z, dens) result = space.probability(condition.__class__(space.value, 0)) return result if not cond_inv else S.One - result def compute_density(self, expr, **kwargs): rvs = random_symbols(expr) if any(pspace(rv).is_Continuous for rv in rvs): z = Dummy('z', real=True) expr = self.compute_expectation(DiracDelta(expr - z), **kwargs) else: z = Dummy('z', integer=True) expr = self.compute_expectation(KroneckerDelta(expr, z), **kwargs) return Lambda(z, expr) def compute_cdf(self, expr, **kwargs): raise ValueError("CDF not well defined on multivariate expressions") def conditional_space(self, condition, normalize=True, **kwargs): rvs = random_symbols(condition) condition = condition.xreplace({rv: rv.symbol for rv in self.values}) pspaces = [pspace(rv) for rv in rvs] if any(ps.is_Continuous for ps in pspaces): from sympy.stats.crv import (ConditionalContinuousDomain, ContinuousPSpace) space = ContinuousPSpace domain = ConditionalContinuousDomain(self.domain, condition) elif any(ps.is_Discrete for ps in pspaces): from sympy.stats.drv import (ConditionalDiscreteDomain, DiscretePSpace) space = DiscretePSpace domain = ConditionalDiscreteDomain(self.domain, condition) elif all(ps.is_Finite for ps in pspaces): from sympy.stats.frv import FinitePSpace return FinitePSpace.conditional_space(self, condition) if normalize: replacement = {rv: Dummy(str(rv)) for rv in self.symbols} norm = domain.compute_expectation(self.pdf, **kwargs) pdf = self.pdf / norm.xreplace(replacement) # XXX: Converting symbols from set to tuple. The order matters to # Lambda though so we shouldn't be starting with a set here... density = Lambda(tuple(domain.symbols), pdf) return space(domain, density) class ProductDomain(RandomDomain): """ A domain resulting from the merger of two independent domains. See Also ======== sympy.stats.crv.ProductContinuousDomain sympy.stats.frv.ProductFiniteDomain """ is_ProductDomain = True def __new__(cls, *domains): # Flatten any product of products domains2 = [] for domain in domains: if not domain.is_ProductDomain: domains2.append(domain) else: domains2.extend(domain.domains) domains2 = FiniteSet(*domains2) if all(domain.is_Finite for domain in domains2): from sympy.stats.frv import ProductFiniteDomain cls = ProductFiniteDomain if all(domain.is_Continuous for domain in domains2): from sympy.stats.crv import ProductContinuousDomain cls = ProductContinuousDomain if all(domain.is_Discrete for domain in domains2): from sympy.stats.drv import ProductDiscreteDomain cls = ProductDiscreteDomain return Basic.__new__(cls, *domains2) @property def sym_domain_dict(self): return {symbol: domain for domain in self.domains for symbol in domain.symbols} @property def symbols(self): return FiniteSet(*[sym for domain in self.domains for sym in domain.symbols]) @property def domains(self): return self.args @property def set(self): return ProductSet(*(domain.set for domain in self.domains)) def __contains__(self, other): # Split event into each subdomain for domain in self.domains: # Collect the parts of this event which associate to this domain elem = frozenset([item for item in other if sympify(domain.symbols.contains(item[0])) is S.true]) # Test this sub-event if elem not in domain: return False # All subevents passed return True def as_boolean(self): return And(*[domain.as_boolean() for domain in self.domains]) def random_symbols(expr): """ Returns all RandomSymbols within a SymPy Expression. """ atoms = getattr(expr, 'atoms', None) if atoms is not None: comp = lambda rv: rv.symbol.name l = list(atoms(RandomSymbol)) return sorted(l, key=comp) else: return [] def pspace(expr): """ Returns the underlying Probability Space of a random expression. For internal use. Examples ======== >>> from sympy.stats import pspace, Normal >>> X = Normal('X', 0, 1) >>> pspace(2*X + 1) == X.pspace True """ expr = sympify(expr) if isinstance(expr, RandomSymbol) and expr.pspace is not None: return expr.pspace if expr.has(RandomMatrixSymbol): rm = list(expr.atoms(RandomMatrixSymbol))[0] return rm.pspace rvs = random_symbols(expr) if not rvs: raise ValueError("Expression containing Random Variable expected, not %s" % (expr)) # If only one space present if all(rv.pspace == rvs[0].pspace for rv in rvs): return rvs[0].pspace from sympy.stats.compound_rv import CompoundPSpace from sympy.stats.stochastic_process import StochasticPSpace for rv in rvs: if isinstance(rv.pspace, (CompoundPSpace, StochasticPSpace)): return rv.pspace # Otherwise make a product space return IndependentProductPSpace(*[rv.pspace for rv in rvs]) def sumsets(sets): """ Union of sets """ return frozenset().union(*sets) def rs_swap(a, b): """ Build a dictionary to swap RandomSymbols based on their underlying symbol. i.e. if ``X = ('x', pspace1)`` and ``Y = ('x', pspace2)`` then ``X`` and ``Y`` match and the key, value pair ``{X:Y}`` will appear in the result Inputs: collections a and b of random variables which share common symbols Output: dict mapping RVs in a to RVs in b """ d = {} for rsa in a: d[rsa] = [rsb for rsb in b if rsa.symbol == rsb.symbol][0] return d def given(expr, condition=None, **kwargs): r""" Conditional Random Expression. Explanation =========== From a random expression and a condition on that expression creates a new probability space from the condition and returns the same expression on that conditional probability space. Examples ======== >>> from sympy.stats import given, density, Die >>> X = Die('X', 6) >>> Y = given(X, X > 3) >>> density(Y).dict {4: 1/3, 5: 1/3, 6: 1/3} Following convention, if the condition is a random symbol then that symbol is considered fixed. >>> from sympy.stats import Normal >>> from sympy import pprint >>> from sympy.abc import z >>> X = Normal('X', 0, 1) >>> Y = Normal('Y', 0, 1) >>> pprint(density(X + Y, Y)(z), use_unicode=False) 2 -(-Y + z) ----------- ___ 2 \/ 2 *e ------------------ ____ 2*\/ pi """ if not is_random(condition) or pspace_independent(expr, condition): return expr if isinstance(condition, RandomSymbol): condition = Eq(condition, condition.symbol) condsymbols = random_symbols(condition) if (isinstance(condition, Equality) and len(condsymbols) == 1 and not isinstance(pspace(expr).domain, ConditionalDomain)): rv = tuple(condsymbols)[0] results = solveset(condition, rv) if isinstance(results, Intersection) and S.Reals in results.args: results = list(results.args[1]) sums = 0 for res in results: temp = expr.subs(rv, res) if temp == True: return True if temp != False: # XXX: This seems nonsensical but preserves existing behaviour # after the change that Relational is no longer a subclass of # Expr. Here expr is sometimes Relational and sometimes Expr # but we are trying to add them with +=. This needs to be # fixed somehow. if sums == 0 and isinstance(expr, Relational): sums = expr.subs(rv, res) else: sums += expr.subs(rv, res) if sums == 0: return False return sums # Get full probability space of both the expression and the condition fullspace = pspace(Tuple(expr, condition)) # Build new space given the condition space = fullspace.conditional_space(condition, **kwargs) # Dictionary to swap out RandomSymbols in expr with new RandomSymbols # That point to the new conditional space swapdict = rs_swap(fullspace.values, space.values) # Swap random variables in the expression expr = expr.xreplace(swapdict) return expr def expectation(expr, condition=None, numsamples=None, evaluate=True, **kwargs): """ Returns the expected value of a random expression. Parameters ========== expr : Expr containing RandomSymbols The expression of which you want to compute the expectation value given : Expr containing RandomSymbols A conditional expression. E(X, X>0) is expectation of X given X > 0 numsamples : int Enables sampling and approximates the expectation with this many samples evalf : Bool (defaults to True) If sampling return a number rather than a complex expression evaluate : Bool (defaults to True) In case of continuous systems return unevaluated integral Examples ======== >>> from sympy.stats import E, Die >>> X = Die('X', 6) >>> E(X) 7/2 >>> E(2*X + 1) 8 >>> E(X, X > 3) # Expectation of X given that it is above 3 5 """ if not is_random(expr): # expr isn't random? return expr kwargs['numsamples'] = numsamples from sympy.stats.symbolic_probability import Expectation if evaluate: return Expectation(expr, condition).doit(**kwargs) return Expectation(expr, condition) def probability(condition, given_condition=None, numsamples=None, evaluate=True, **kwargs): """ Probability that a condition is true, optionally given a second condition. Parameters ========== condition : Combination of Relationals containing RandomSymbols The condition of which you want to compute the probability given_condition : Combination of Relationals containing RandomSymbols A conditional expression. P(X > 1, X > 0) is expectation of X > 1 given X > 0 numsamples : int Enables sampling and approximates the probability with this many samples evaluate : Bool (defaults to True) In case of continuous systems return unevaluated integral Examples ======== >>> from sympy.stats import P, Die >>> from sympy import Eq >>> X, Y = Die('X', 6), Die('Y', 6) >>> P(X > 3) 1/2 >>> P(Eq(X, 5), X > 2) # Probability that X == 5 given that X > 2 1/4 >>> P(X > Y) 5/12 """ kwargs['numsamples'] = numsamples from sympy.stats.symbolic_probability import Probability if evaluate: return Probability(condition, given_condition).doit(**kwargs) ### TODO: Remove the user warnings in the future releases message = ("Since version 1.7, using `evaluate=False` returns `Probability` " "object. If you want unevaluated Integral/Sum use " "`P(condition, given_condition, evaluate=False).rewrite(Integral)`") warnings.warn(filldedent(message)) return Probability(condition, given_condition) class Density(Basic): expr = property(lambda self: self.args[0]) @property def condition(self): if len(self.args) > 1: return self.args[1] else: return None def doit(self, evaluate=True, **kwargs): from sympy.stats.random_matrix import RandomMatrixPSpace from sympy.stats.joint_rv import JointPSpace from sympy.stats.matrix_distributions import MatrixPSpace from sympy.stats.compound_rv import CompoundPSpace from sympy.stats.frv import SingleFiniteDistribution expr, condition = self.expr, self.condition if isinstance(expr, SingleFiniteDistribution): return expr.dict if condition is not None: # Recompute on new conditional expr expr = given(expr, condition, **kwargs) if not random_symbols(expr): return Lambda(x, DiracDelta(x - expr)) if isinstance(expr, RandomSymbol): if isinstance(expr.pspace, (SinglePSpace, JointPSpace, MatrixPSpace)) and \ hasattr(expr.pspace, 'distribution'): return expr.pspace.distribution elif isinstance(expr.pspace, RandomMatrixPSpace): return expr.pspace.model if isinstance(pspace(expr), CompoundPSpace): kwargs['compound_evaluate'] = evaluate result = pspace(expr).compute_density(expr, **kwargs) if evaluate and hasattr(result, 'doit'): return result.doit() else: return result def density(expr, condition=None, evaluate=True, numsamples=None, **kwargs): """ Probability density of a random expression, optionally given a second condition. Explanation =========== This density will take on different forms for different types of probability spaces. Discrete variables produce Dicts. Continuous variables produce Lambdas. Parameters ========== expr : Expr containing RandomSymbols The expression of which you want to compute the density value condition : Relational containing RandomSymbols A conditional expression. density(X > 1, X > 0) is density of X > 1 given X > 0 numsamples : int Enables sampling and approximates the density with this many samples Examples ======== >>> from sympy.stats import density, Die, Normal >>> from sympy import Symbol >>> x = Symbol('x') >>> D = Die('D', 6) >>> X = Normal(x, 0, 1) >>> density(D).dict {1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6} >>> density(2*D).dict {2: 1/6, 4: 1/6, 6: 1/6, 8: 1/6, 10: 1/6, 12: 1/6} >>> density(X)(x) sqrt(2)*exp(-x**2/2)/(2*sqrt(pi)) """ if numsamples: return sampling_density(expr, condition, numsamples=numsamples, **kwargs) return Density(expr, condition).doit(evaluate=evaluate, **kwargs) def cdf(expr, condition=None, evaluate=True, **kwargs): """ Cumulative Distribution Function of a random expression. optionally given a second condition. Explanation =========== This density will take on different forms for different types of probability spaces. Discrete variables produce Dicts. Continuous variables produce Lambdas. Examples ======== >>> from sympy.stats import density, Die, Normal, cdf >>> D = Die('D', 6) >>> X = Normal('X', 0, 1) >>> density(D).dict {1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6} >>> cdf(D) {1: 1/6, 2: 1/3, 3: 1/2, 4: 2/3, 5: 5/6, 6: 1} >>> cdf(3*D, D > 2) {9: 1/4, 12: 1/2, 15: 3/4, 18: 1} >>> cdf(X) Lambda(_z, erf(sqrt(2)*_z/2)/2 + 1/2) """ if condition is not None: # If there is a condition # Recompute on new conditional expr return cdf(given(expr, condition, **kwargs), **kwargs) # Otherwise pass work off to the ProbabilitySpace result = pspace(expr).compute_cdf(expr, **kwargs) if evaluate and hasattr(result, 'doit'): return result.doit() else: return result def characteristic_function(expr, condition=None, evaluate=True, **kwargs): """ Characteristic function of a random expression, optionally given a second condition. Returns a Lambda. Examples ======== >>> from sympy.stats import Normal, DiscreteUniform, Poisson, characteristic_function >>> X = Normal('X', 0, 1) >>> characteristic_function(X) Lambda(_t, exp(-_t**2/2)) >>> Y = DiscreteUniform('Y', [1, 2, 7]) >>> characteristic_function(Y) Lambda(_t, exp(7*_t*I)/3 + exp(2*_t*I)/3 + exp(_t*I)/3) >>> Z = Poisson('Z', 2) >>> characteristic_function(Z) Lambda(_t, exp(2*exp(_t*I) - 2)) """ if condition is not None: return characteristic_function(given(expr, condition, **kwargs), **kwargs) result = pspace(expr).compute_characteristic_function(expr, **kwargs) if evaluate and hasattr(result, 'doit'): return result.doit() else: return result def moment_generating_function(expr, condition=None, evaluate=True, **kwargs): if condition is not None: return moment_generating_function(given(expr, condition, **kwargs), **kwargs) result = pspace(expr).compute_moment_generating_function(expr, **kwargs) if evaluate and hasattr(result, 'doit'): return result.doit() else: return result def where(condition, given_condition=None, **kwargs): """ Returns the domain where a condition is True. Examples ======== >>> from sympy.stats import where, Die, Normal >>> from sympy import And >>> D1, D2 = Die('a', 6), Die('b', 6) >>> a, b = D1.symbol, D2.symbol >>> X = Normal('x', 0, 1) >>> where(X**2<1) Domain: (-1 < x) & (x < 1) >>> where(X**2<1).set Interval.open(-1, 1) >>> where(And(D1<=D2 , D2<3)) Domain: (Eq(a, 1) & Eq(b, 1)) | (Eq(a, 1) & Eq(b, 2)) | (Eq(a, 2) & Eq(b, 2)) """ if given_condition is not None: # If there is a condition # Recompute on new conditional expr return where(given(condition, given_condition, **kwargs), **kwargs) # Otherwise pass work off to the ProbabilitySpace return pspace(condition).where(condition, **kwargs) @doctest_depends_on(modules=('scipy',)) def sample(expr, condition=None, size=(), library='scipy', numsamples=1, seed=None, **kwargs): """ A realization of the random expression. Parameters ========== expr : Expression of random variables Expression from which sample is extracted condition : Expr containing RandomSymbols A conditional expression size : int, tuple Represents size of each sample in numsamples library : str - 'scipy' : Sample using scipy - 'numpy' : Sample using numpy - 'pymc3' : Sample using PyMC3 Choose any of the available options to sample from as string, by default is 'scipy' numsamples : int Number of samples, each with size as ``size``. The ``numsamples`` parameter is deprecated and is only provided for compatibility with v1.8. Use a list comprehension or an additional dimension in ``size`` instead. seed : An object to be used as seed by the given external library for sampling `expr`. Following is the list of possible types of object for the supported libraries, - 'scipy': int, numpy.random.RandomState, numpy.random.Generator - 'numpy': int, numpy.random.RandomState, numpy.random.Generator - 'pymc3': int Optional, by default None, in which case seed settings related to the given library will be used. No modifications to environment's global seed settings are done by this argument. Returns ======= sample: float/list/numpy.ndarray one sample or a collection of samples of the random expression. - sample(X) returns float/numpy.float64/numpy.int64 object. - sample(X, size=int/tuple) returns numpy.ndarray object. Examples ======== >>> from sympy.stats import Die, sample, Normal, Geometric >>> X, Y, Z = Die('X', 6), Die('Y', 6), Die('Z', 6) # Finite Random Variable >>> die_roll = sample(X + Y + Z) >>> die_roll # doctest: +SKIP 3 >>> N = Normal('N', 3, 4) # Continuous Random Variable >>> samp = sample(N) >>> samp in N.pspace.domain.set True >>> samp = sample(N, N>0) >>> samp > 0 True >>> samp_list = sample(N, size=4) >>> [sam in N.pspace.domain.set for sam in samp_list] [True, True, True, True] >>> sample(N, size = (2,3)) # doctest: +SKIP array([[5.42519758, 6.40207856, 4.94991743], [1.85819627, 6.83403519, 1.9412172 ]]) >>> G = Geometric('G', 0.5) # Discrete Random Variable >>> samp_list = sample(G, size=3) >>> samp_list # doctest: +SKIP [1, 3, 2] >>> [sam in G.pspace.domain.set for sam in samp_list] [True, True, True] >>> MN = Normal("MN", [3, 4], [[2, 1], [1, 2]]) # Joint Random Variable >>> samp_list = sample(MN, size=4) >>> samp_list # doctest: +SKIP [array([2.85768055, 3.38954165]), array([4.11163337, 4.3176591 ]), array([0.79115232, 1.63232916]), array([4.01747268, 3.96716083])] >>> [tuple(sam) in MN.pspace.domain.set for sam in samp_list] [True, True, True, True] .. versionchanged:: 1.7.0 sample used to return an iterator containing the samples instead of value. .. versionchanged:: 1.9.0 sample returns values or array of values instead of an iterator and numsamples is deprecated. """ iterator = sample_iter(expr, condition, size=size, library=library, numsamples=numsamples, seed=seed) if numsamples != 1: SymPyDeprecationWarning( feature="numsamples parameter", issue=21723, deprecated_since_version="1.9", useinstead="a list comprehension or an additional dimension in ``size``").warn() return [next(iterator) for i in range(numsamples)] return next(iterator) def quantile(expr, evaluate=True, **kwargs): r""" Return the :math:`p^{th}` order quantile of a probability distribution. Explanation =========== Quantile is defined as the value at which the probability of the random variable is less than or equal to the given probability. ..math:: Q(p) = inf{x \in (-\infty, \infty) such that p <= F(x)} Examples ======== >>> from sympy.stats import quantile, Die, Exponential >>> from sympy import Symbol, pprint >>> p = Symbol("p") >>> l = Symbol("lambda", positive=True) >>> X = Exponential("x", l) >>> quantile(X)(p) -log(1 - p)/lambda >>> D = Die("d", 6) >>> pprint(quantile(D)(p), use_unicode=False) /nan for Or(p > 1, p < 0) | | 1 for p <= 1/6 | | 2 for p <= 1/3 | < 3 for p <= 1/2 | | 4 for p <= 2/3 | | 5 for p <= 5/6 | \ 6 for p <= 1 """ result = pspace(expr).compute_quantile(expr, **kwargs) if evaluate and hasattr(result, 'doit'): return result.doit() else: return result def sample_iter(expr, condition=None, size=(), library='scipy', numsamples=S.Infinity, seed=None, **kwargs): """ Returns an iterator of realizations from the expression given a condition. Parameters ========== expr: Expr Random expression to be realized condition: Expr, optional A conditional expression size : int, tuple Represents size of each sample in numsamples numsamples: integer, optional Length of the iterator (defaults to infinity) seed : An object to be used as seed by the given external library for sampling `expr`. Following is the list of possible types of object for the supported libraries, - 'scipy': int, numpy.random.RandomState, numpy.random.Generator - 'numpy': int, numpy.random.RandomState, numpy.random.Generator - 'pymc3': int Optional, by default None, in which case seed settings related to the given library will be used. No modifications to environment's global seed settings are done by this argument. Examples ======== >>> from sympy.stats import Normal, sample_iter >>> X = Normal('X', 0, 1) >>> expr = X*X + 3 >>> iterator = sample_iter(expr, numsamples=3) # doctest: +SKIP >>> list(iterator) # doctest: +SKIP [12, 4, 7] Returns ======= sample_iter: iterator object iterator object containing the sample/samples of given expr See Also ======== sample sampling_P sampling_E """ from sympy.stats.joint_rv import JointRandomSymbol if not import_module(library): raise ValueError("Failed to import %s" % library) if condition is not None: ps = pspace(Tuple(expr, condition)) else: ps = pspace(expr) rvs = list(ps.values) if isinstance(expr, JointRandomSymbol): expr = expr.subs({expr: RandomSymbol(expr.symbol, expr.pspace)}) else: sub = {} for arg in expr.args: if isinstance(arg, JointRandomSymbol): sub[arg] = RandomSymbol(arg.symbol, arg.pspace) expr = expr.subs(sub) def fn_subs(*args): return expr.subs({rv: arg for rv, arg in zip(rvs, args)}) def given_fn_subs(*args): if condition is not None: return condition.subs({rv: arg for rv, arg in zip(rvs, args)}) return False if library == 'pymc3': # Currently unable to lambdify in pymc3 # TODO : Remove 'pymc3' when lambdify accepts 'pymc3' as module fn = lambdify(rvs, expr, **kwargs) else: fn = lambdify(rvs, expr, modules=library, **kwargs) if condition is not None: given_fn = lambdify(rvs, condition, **kwargs) def return_generator_infinite(): count = 0 _size = (1,)+((size,) if isinstance(size, int) else size) while count < numsamples: d = ps.sample(size=_size, library=library, seed=seed) # a dictionary that maps RVs to values args = [d[rv][0] for rv in rvs] if condition is not None: # Check that these values satisfy the condition # TODO: Replace the try-except block with only given_fn(*args) # once lambdify works with unevaluated SymPy objects. try: gd = given_fn(*args) except (NameError, TypeError): gd = given_fn_subs(*args) if gd != True and gd != False: raise ValueError( "Conditions must not contain free symbols") if not gd: # If the values don't satisfy then try again continue yield fn(*args) count += 1 def return_generator_finite(): faulty = True while faulty: d = ps.sample(size=(numsamples,) + ((size,) if isinstance(size, int) else size), library=library, seed=seed) # a dictionary that maps RVs to values faulty = False count = 0 while count < numsamples and not faulty: args = [d[rv][count] for rv in rvs] if condition is not None: # Check that these values satisfy the condition # TODO: Replace the try-except block with only given_fn(*args) # once lambdify works with unevaluated SymPy objects. try: gd = given_fn(*args) except (NameError, TypeError): gd = given_fn_subs(*args) if gd != True and gd != False: raise ValueError( "Conditions must not contain free symbols") if not gd: # If the values don't satisfy then try again faulty = True count += 1 count = 0 while count < numsamples: args = [d[rv][count] for rv in rvs] # TODO: Replace the try-except block with only fn(*args) # once lambdify works with unevaluated SymPy objects. try: yield fn(*args) except (NameError, TypeError): yield fn_subs(*args) count += 1 if numsamples is S.Infinity: return return_generator_infinite() return return_generator_finite() def sample_iter_lambdify(expr, condition=None, size=(), numsamples=S.Infinity, seed=None, **kwargs): return sample_iter(expr, condition=condition, size=size, numsamples=numsamples, seed=seed, **kwargs) def sample_iter_subs(expr, condition=None, size=(), numsamples=S.Infinity, seed=None, **kwargs): return sample_iter(expr, condition=condition, size=size, numsamples=numsamples, seed=seed, **kwargs) def sampling_P(condition, given_condition=None, library='scipy', numsamples=1, evalf=True, seed=None, **kwargs): """ Sampling version of P. See Also ======== P sampling_E sampling_density """ count_true = 0 count_false = 0 samples = sample_iter(condition, given_condition, library=library, numsamples=numsamples, seed=seed, **kwargs) for sample in samples: if sample: count_true += 1 else: count_false += 1 result = S(count_true) / numsamples if evalf: return result.evalf() else: return result def sampling_E(expr, given_condition=None, library='scipy', numsamples=1, evalf=True, seed=None, **kwargs): """ Sampling version of E. See Also ======== P sampling_P sampling_density """ samples = list(sample_iter(expr, given_condition, library=library, numsamples=numsamples, seed=seed, **kwargs)) result = Add(*[samp for samp in samples]) / numsamples if evalf: return result.evalf() else: return result def sampling_density(expr, given_condition=None, library='scipy', numsamples=1, seed=None, **kwargs): """ Sampling version of density. See Also ======== density sampling_P sampling_E """ results = {} for result in sample_iter(expr, given_condition, library=library, numsamples=numsamples, seed=seed, **kwargs): results[result] = results.get(result, 0) + 1 return results def dependent(a, b): """ Dependence of two random expressions. Two expressions are independent if knowledge of one does not change computations on the other. Examples ======== >>> from sympy.stats import Normal, dependent, given >>> from sympy import Tuple, Eq >>> X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) >>> dependent(X, Y) False >>> dependent(2*X + Y, -Y) True >>> X, Y = given(Tuple(X, Y), Eq(X + Y, 3)) >>> dependent(X, Y) True See Also ======== independent """ if pspace_independent(a, b): return False z = Symbol('z', real=True) # Dependent if density is unchanged when one is given information about # the other return (density(a, Eq(b, z)) != density(a) or density(b, Eq(a, z)) != density(b)) def independent(a, b): """ Independence of two random expressions. Two expressions are independent if knowledge of one does not change computations on the other. Examples ======== >>> from sympy.stats import Normal, independent, given >>> from sympy import Tuple, Eq >>> X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) >>> independent(X, Y) True >>> independent(2*X + Y, -Y) False >>> X, Y = given(Tuple(X, Y), Eq(X + Y, 3)) >>> independent(X, Y) False See Also ======== dependent """ return not dependent(a, b) def pspace_independent(a, b): """ Tests for independence between a and b by checking if their PSpaces have overlapping symbols. This is a sufficient but not necessary condition for independence and is intended to be used internally. Notes ===== pspace_independent(a, b) implies independent(a, b) independent(a, b) does not imply pspace_independent(a, b) """ a_symbols = set(pspace(b).symbols) b_symbols = set(pspace(a).symbols) if len(set(random_symbols(a)).intersection(random_symbols(b))) != 0: return False if len(a_symbols.intersection(b_symbols)) == 0: return True return None def rv_subs(expr, symbols=None): """ Given a random expression replace all random variables with their symbols. If symbols keyword is given restrict the swap to only the symbols listed. """ if symbols is None: symbols = random_symbols(expr) if not symbols: return expr swapdict = {rv: rv.symbol for rv in symbols} return expr.subs(swapdict) class NamedArgsMixin: _argnames = () # type: tTuple[str, ...] def __getattr__(self, attr): try: return self.args[self._argnames.index(attr)] except ValueError: raise AttributeError("'%s' object has no attribute '%s'" % ( type(self).__name__, attr)) class Distribution(Basic): def sample(self, size=(), library='scipy', seed=None): """ A random realization from the distribution """ module = import_module(library) if library in {'scipy', 'numpy', 'pymc3'} and module is None: raise ValueError("Failed to import %s" % library) if library == 'scipy': # scipy does not require map as it can handle using custom distributions. # However, we will still use a map where we can. # TODO: do this for drv.py and frv.py if necessary. # TODO: add more distributions here if there are more # See links below referring to sections beginning with "A common parametrization..." # I will remove all these comments if everything is ok. from sympy.stats.sampling.sample_scipy import do_sample_scipy import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed samps = do_sample_scipy(self, size, rand_state) elif library == 'numpy': from sympy.stats.sampling.sample_numpy import do_sample_numpy import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed _size = None if size == () else size samps = do_sample_numpy(self, _size, rand_state) elif library == 'pymc3': from sympy.stats.sampling.sample_pymc3 import do_sample_pymc3 import logging logging.getLogger("pymc3").setLevel(logging.ERROR) import pymc3 with pymc3.Model(): if do_sample_pymc3(self): samps = pymc3.sample(draws=prod(size), chains=1, compute_convergence_checks=False, progressbar=False, random_seed=seed, return_inferencedata=False)[:]['X'] samps = samps.reshape(size) else: samps = None else: raise NotImplementedError("Sampling from %s is not supported yet." % str(library)) if samps is not None: return samps raise NotImplementedError( "Sampling for %s is not currently implemented from %s" % (self, library)) def _value_check(condition, message): """ Raise a ValueError with message if condition is False, else return True if all conditions were True, else False. Examples ======== >>> from sympy.stats.rv import _value_check >>> from sympy.abc import a, b, c >>> from sympy import And, Dummy >>> _value_check(2 < 3, '') True Here, the condition is not False, but it doesn't evaluate to True so False is returned (but no error is raised). So checking if the return value is True or False will tell you if all conditions were evaluated. >>> _value_check(a < b, '') False In this case the condition is False so an error is raised: >>> r = Dummy(real=True) >>> _value_check(r < r - 1, 'condition is not true') Traceback (most recent call last): ... ValueError: condition is not true If no condition of many conditions must be False, they can be checked by passing them as an iterable: >>> _value_check((a < 0, b < 0, c < 0), '') False The iterable can be a generator, too: >>> _value_check((i < 0 for i in (a, b, c)), '') False The following are equivalent to the above but do not pass an iterable: >>> all(_value_check(i < 0, '') for i in (a, b, c)) False >>> _value_check(And(a < 0, b < 0, c < 0), '') False """ from sympy.core.compatibility import iterable from sympy.core.logic import fuzzy_and if not iterable(condition): condition = [condition] truth = fuzzy_and(condition) if truth == False: raise ValueError(message) return truth == True def _symbol_converter(sym): """ Casts the parameter to Symbol if it is 'str' otherwise no operation is performed on it. Parameters ========== sym The parameter to be converted. Returns ======= Symbol the parameter converted to Symbol. Raises ====== TypeError If the parameter is not an instance of both str and Symbol. Examples ======== >>> from sympy import Symbol >>> from sympy.stats.rv import _symbol_converter >>> s = _symbol_converter('s') >>> isinstance(s, Symbol) True >>> _symbol_converter(1) Traceback (most recent call last): ... TypeError: 1 is neither a Symbol nor a string >>> r = Symbol('r') >>> isinstance(r, Symbol) True """ if isinstance(sym, str): sym = Symbol(sym) if not isinstance(sym, Symbol): raise TypeError("%s is neither a Symbol nor a string"%(sym)) return sym def sample_stochastic_process(process): """ This function is used to sample from stochastic process. Parameters ========== process: StochasticProcess Process used to extract the samples. It must be an instance of StochasticProcess Examples ======== >>> from sympy.stats import sample_stochastic_process, DiscreteMarkovChain >>> from sympy import Matrix >>> T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]]) >>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T) >>> next(sample_stochastic_process(Y)) in Y.state_space # doctest: +SKIP True >>> next(sample_stochastic_process(Y)) # doctest: +SKIP 0 >>> next(sample_stochastic_process(Y)) # doctest: +SKIP 2 Returns ======= sample: iterator object iterator object containing the sample of given process """ from sympy.stats.stochastic_process_types import StochasticProcess if not isinstance(process, StochasticProcess): raise ValueError("Process must be an instance of Stochastic Process") return process.sample()
5ecc58d3f9d459c05675d3e046bac9a1d0139fc43d893deb3e2a20ddfda3ac96
""" Joint Random Variables Module See Also ======== sympy.stats.rv sympy.stats.frv sympy.stats.crv sympy.stats.drv """ from sympy import (Basic, Lambda, sympify, Indexed, Symbol, ProductSet, S, Dummy, prod) from sympy.concrete.products import Product from sympy.concrete.summations import Sum, summation from sympy.core.compatibility import iterable from sympy.core.containers import Tuple from sympy.integrals.integrals import Integral, integrate from sympy.matrices import ImmutableMatrix, matrix2numpy, list2numpy from sympy.stats.crv import SingleContinuousDistribution, SingleContinuousPSpace from sympy.stats.drv import SingleDiscreteDistribution, SingleDiscretePSpace from sympy.stats.rv import (ProductPSpace, NamedArgsMixin, Distribution, ProductDomain, RandomSymbol, random_symbols, SingleDomain, _symbol_converter) from sympy.utilities.misc import filldedent from sympy.external import import_module # __all__ = ['marginal_distribution'] class JointPSpace(ProductPSpace): """ Represents a joint probability space. Represented using symbols for each component and a distribution. """ def __new__(cls, sym, dist): if isinstance(dist, SingleContinuousDistribution): return SingleContinuousPSpace(sym, dist) if isinstance(dist, SingleDiscreteDistribution): return SingleDiscretePSpace(sym, dist) sym = _symbol_converter(sym) return Basic.__new__(cls, sym, dist) @property def set(self): return self.domain.set @property def symbol(self): return self.args[0] @property def distribution(self): return self.args[1] @property def value(self): return JointRandomSymbol(self.symbol, self) @property def component_count(self): _set = self.distribution.set if isinstance(_set, ProductSet): return S(len(_set.args)) elif isinstance(_set, Product): return _set.limits[0][-1] return S.One @property def pdf(self): sym = [Indexed(self.symbol, i) for i in range(self.component_count)] return self.distribution(*sym) @property def domain(self): rvs = random_symbols(self.distribution) if not rvs: return SingleDomain(self.symbol, self.distribution.set) return ProductDomain(*[rv.pspace.domain for rv in rvs]) def component_domain(self, index): return self.set.args[index] def marginal_distribution(self, *indices): count = self.component_count if count.atoms(Symbol): raise ValueError("Marginal distributions cannot be computed " "for symbolic dimensions. It is a work under progress.") orig = [Indexed(self.symbol, i) for i in range(count)] all_syms = [Symbol(str(i)) for i in orig] replace_dict = dict(zip(all_syms, orig)) sym = tuple(Symbol(str(Indexed(self.symbol, i))) for i in indices) limits = list([i,] for i in all_syms if i not in sym) index = 0 for i in range(count): if i not in indices: limits[index].append(self.distribution.set.args[i]) limits[index] = tuple(limits[index]) index += 1 if self.distribution.is_Continuous: f = Lambda(sym, integrate(self.distribution(*all_syms), *limits)) elif self.distribution.is_Discrete: f = Lambda(sym, summation(self.distribution(*all_syms), *limits)) return f.xreplace(replace_dict) def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs): syms = tuple(self.value[i] for i in range(self.component_count)) rvs = rvs or syms if not any(i in rvs for i in syms): return expr expr = expr*self.pdf for rv in rvs: if isinstance(rv, Indexed): expr = expr.xreplace({rv: Indexed(str(rv.base), rv.args[1])}) elif isinstance(rv, RandomSymbol): expr = expr.xreplace({rv: rv.symbol}) if self.value in random_symbols(expr): raise NotImplementedError(filldedent(''' Expectations of expression with unindexed joint random symbols cannot be calculated yet.''')) limits = tuple((Indexed(str(rv.base),rv.args[1]), self.distribution.set.args[rv.args[1]]) for rv in syms) return Integral(expr, *limits) def where(self, condition): raise NotImplementedError() def compute_density(self, expr): raise NotImplementedError() def sample(self, size=(), library='scipy', seed=None): """ Internal sample method Returns dictionary mapping RandomSymbol to realization value. """ return {RandomSymbol(self.symbol, self): self.distribution.sample(size, library=library, seed=seed)} def probability(self, condition): raise NotImplementedError() class SampleJointScipy: """Returns the sample from scipy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_scipy(dist, size, seed) @classmethod def _sample_scipy(cls, dist, size, seed): """Sample from SciPy.""" import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed from scipy import stats as scipy_stats scipy_rv_map = { 'MultivariateNormalDistribution': lambda dist, size: scipy_stats.multivariate_normal.rvs( mean=matrix2numpy(dist.mu).flatten(), cov=matrix2numpy(dist.sigma), size=size, random_state=rand_state), 'MultivariateBetaDistribution': lambda dist, size: scipy_stats.dirichlet.rvs( alpha=list2numpy(dist.alpha, float).flatten(), size=size, random_state=rand_state), 'MultinomialDistribution': lambda dist, size: scipy_stats.multinomial.rvs( n=int(dist.n), p=list2numpy(dist.p, float).flatten(), size=size, random_state=rand_state) } sample_shape = { 'MultivariateNormalDistribution': lambda dist: matrix2numpy(dist.mu).flatten().shape, 'MultivariateBetaDistribution': lambda dist: list2numpy(dist.alpha).flatten().shape, 'MultinomialDistribution': lambda dist: list2numpy(dist.p).flatten().shape } dist_list = scipy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None samples = scipy_rv_map[dist.__class__.__name__](dist, size) return samples.reshape(size + sample_shape[dist.__class__.__name__](dist)) class SampleJointNumpy: """Returns the sample from numpy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_numpy(dist, size, seed) @classmethod def _sample_numpy(cls, dist, size, seed): """Sample from NumPy.""" import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed numpy_rv_map = { 'MultivariateNormalDistribution': lambda dist, size: rand_state.multivariate_normal( mean=matrix2numpy(dist.mu, float).flatten(), cov=matrix2numpy(dist.sigma, float), size=size), 'MultivariateBetaDistribution': lambda dist, size: rand_state.dirichlet( alpha=list2numpy(dist.alpha, float).flatten(), size=size), 'MultinomialDistribution': lambda dist, size: rand_state.multinomial( n=int(dist.n), pvals=list2numpy(dist.p, float).flatten(), size=size) } sample_shape = { 'MultivariateNormalDistribution': lambda dist: matrix2numpy(dist.mu).flatten().shape, 'MultivariateBetaDistribution': lambda dist: list2numpy(dist.alpha).flatten().shape, 'MultinomialDistribution': lambda dist: list2numpy(dist.p).flatten().shape } dist_list = numpy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None samples = numpy_rv_map[dist.__class__.__name__](dist, prod(size)) return samples.reshape(size + sample_shape[dist.__class__.__name__](dist)) class SampleJointPymc: """Returns the sample from pymc3 of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_pymc3(dist, size, seed) @classmethod def _sample_pymc3(cls, dist, size, seed): """Sample from PyMC3.""" import pymc3 pymc3_rv_map = { 'MultivariateNormalDistribution': lambda dist: pymc3.MvNormal('X', mu=matrix2numpy(dist.mu, float).flatten(), cov=matrix2numpy(dist.sigma, float), shape=(1, dist.mu.shape[0])), 'MultivariateBetaDistribution': lambda dist: pymc3.Dirichlet('X', a=list2numpy(dist.alpha, float).flatten()), 'MultinomialDistribution': lambda dist: pymc3.Multinomial('X', n=int(dist.n), p=list2numpy(dist.p, float).flatten(), shape=(1, len(dist.p))) } sample_shape = { 'MultivariateNormalDistribution': lambda dist: matrix2numpy(dist.mu).flatten().shape, 'MultivariateBetaDistribution': lambda dist: list2numpy(dist.alpha).flatten().shape, 'MultinomialDistribution': lambda dist: list2numpy(dist.p).flatten().shape } dist_list = pymc3_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None import logging logging.getLogger("pymc3").setLevel(logging.ERROR) with pymc3.Model(): pymc3_rv_map[dist.__class__.__name__](dist) samples = pymc3.sample(draws=prod(size), chains=1, progressbar=False, random_seed=seed, return_inferencedata=False, compute_convergence_checks=False)[:]['X'] return samples.reshape(size + sample_shape[dist.__class__.__name__](dist)) _get_sample_class_jrv = { 'scipy': SampleJointScipy, 'pymc3': SampleJointPymc, 'numpy': SampleJointNumpy } class JointDistribution(Distribution, NamedArgsMixin): """ Represented by the random variables part of the joint distribution. Contains methods for PDF, CDF, sampling, marginal densities, etc. """ _argnames = ('pdf', ) def __new__(cls, *args): args = list(map(sympify, args)) for i in range(len(args)): if isinstance(args[i], list): args[i] = ImmutableMatrix(args[i]) return Basic.__new__(cls, *args) @property def domain(self): return ProductDomain(self.symbols) @property def pdf(self): return self.density.args[1] def cdf(self, other): if not isinstance(other, dict): raise ValueError("%s should be of type dict, got %s"%(other, type(other))) rvs = other.keys() _set = self.domain.set.sets expr = self.pdf(tuple(i.args[0] for i in self.symbols)) for i in range(len(other)): if rvs[i].is_Continuous: density = Integral(expr, (rvs[i], _set[i].inf, other[rvs[i]])) elif rvs[i].is_Discrete: density = Sum(expr, (rvs[i], _set[i].inf, other[rvs[i]])) return density def sample(self, size=(), library='scipy', seed=None): """ A random realization from the distribution """ libraries = ['scipy', 'numpy', 'pymc3'] if library not in libraries: raise NotImplementedError("Sampling from %s is not supported yet." % str(library)) if not import_module(library): raise ValueError("Failed to import %s" % library) samps = _get_sample_class_jrv[library](self, size, seed=seed) if samps is not None: return samps raise NotImplementedError( "Sampling for %s is not currently implemented from %s" % (self.__class__.__name__, library) ) def __call__(self, *args): return self.pdf(*args) class JointRandomSymbol(RandomSymbol): """ Representation of random symbols with joint probability distributions to allow indexing." """ def __getitem__(self, key): if isinstance(self.pspace, JointPSpace): if (self.pspace.component_count <= key) == True: raise ValueError("Index keys for %s can only up to %s." % (self.name, self.pspace.component_count - 1)) return Indexed(self, key) class MarginalDistribution(Distribution): """ Represents the marginal distribution of a joint probability space. Initialised using a probability distribution and random variables(or their indexed components) which should be a part of the resultant distribution. """ def __new__(cls, dist, *rvs): if len(rvs) == 1 and iterable(rvs[0]): rvs = tuple(rvs[0]) if not all(isinstance(rv, (Indexed, RandomSymbol)) for rv in rvs): raise ValueError(filldedent('''Marginal distribution can be intitialised only in terms of random variables or indexed random variables''')) rvs = Tuple.fromiter(rv for rv in rvs) if not isinstance(dist, JointDistribution) and len(random_symbols(dist)) == 0: return dist return Basic.__new__(cls, dist, rvs) def check(self): pass @property def set(self): rvs = [i for i in self.args[1] if isinstance(i, RandomSymbol)] return ProductSet(*[rv.pspace.set for rv in rvs]) @property def symbols(self): rvs = self.args[1] return {rv.pspace.symbol for rv in rvs} def pdf(self, *x): expr, rvs = self.args[0], self.args[1] marginalise_out = [i for i in random_symbols(expr) if i not in rvs] if isinstance(expr, JointDistribution): count = len(expr.domain.args) x = Dummy('x', real=True, finite=True) syms = tuple(Indexed(x, i) for i in count) expr = expr.pdf(syms) else: syms = tuple(rv.pspace.symbol if isinstance(rv, RandomSymbol) else rv.args[0] for rv in rvs) return Lambda(syms, self.compute_pdf(expr, marginalise_out))(*x) def compute_pdf(self, expr, rvs): for rv in rvs: lpdf = 1 if isinstance(rv, RandomSymbol): lpdf = rv.pspace.pdf expr = self.marginalise_out(expr*lpdf, rv) return expr def marginalise_out(self, expr, rv): from sympy.concrete.summations import Sum if isinstance(rv, RandomSymbol): dom = rv.pspace.set elif isinstance(rv, Indexed): dom = rv.base.component_domain( rv.pspace.component_domain(rv.args[1])) expr = expr.xreplace({rv: rv.pspace.symbol}) if rv.pspace.is_Continuous: #TODO: Modify to support integration #for all kinds of sets. expr = Integral(expr, (rv.pspace.symbol, dom)) elif rv.pspace.is_Discrete: #incorporate this into `Sum`/`summation` if dom in (S.Integers, S.Naturals, S.Naturals0): dom = (dom.inf, dom.sup) expr = Sum(expr, (rv.pspace.symbol, dom)) return expr def __call__(self, *args): return self.pdf(*args)
37e375d591e1f8233332be843d5e709ae944ad584c3e2dd3f28cd4691c9f47c3
import itertools from sympy import (Expr, Add, Mul, S, Integral, Eq, Sum, Symbol, expand as _expand, Not) from sympy.core.compatibility import default_sort_key from sympy.core.parameters import global_parameters from sympy.core.sympify import _sympify from sympy.core.relational import Relational from sympy.logic.boolalg import Boolean from sympy.stats import variance, covariance from sympy.stats.rv import (RandomSymbol, pspace, dependent, given, sampling_E, RandomIndexedSymbol, is_random, PSpace, sampling_P, random_symbols) __all__ = ['Probability', 'Expectation', 'Variance', 'Covariance'] @is_random.register(Expr) def _(x): atoms = x.free_symbols if len(atoms) == 1 and next(iter(atoms)) == x: return False return any(is_random(i) for i in atoms) @is_random.register(RandomSymbol) # type: ignore def _(x): return True class Probability(Expr): """ Symbolic expression for the probability. Examples ======== >>> from sympy.stats import Probability, Normal >>> from sympy import Integral >>> X = Normal("X", 0, 1) >>> prob = Probability(X > 1) >>> prob Probability(X > 1) Integral representation: >>> prob.rewrite(Integral) Integral(sqrt(2)*exp(-_z**2/2)/(2*sqrt(pi)), (_z, 1, oo)) Evaluation of the integral: >>> prob.evaluate_integral() sqrt(2)*(-sqrt(2)*sqrt(pi)*erf(sqrt(2)/2) + sqrt(2)*sqrt(pi))/(4*sqrt(pi)) """ def __new__(cls, prob, condition=None, **kwargs): prob = _sympify(prob) if condition is None: obj = Expr.__new__(cls, prob) else: condition = _sympify(condition) obj = Expr.__new__(cls, prob, condition) obj._condition = condition return obj def doit(self, **hints): condition = self.args[0] given_condition = self._condition numsamples = hints.get('numsamples', False) for_rewrite = not hints.get('for_rewrite', False) if isinstance(condition, Not): return S.One - self.func(condition.args[0], given_condition, evaluate=for_rewrite).doit(**hints) if condition.has(RandomIndexedSymbol): return pspace(condition).probability(condition, given_condition, evaluate=for_rewrite) if isinstance(given_condition, RandomSymbol): condrv = random_symbols(condition) if len(condrv) == 1 and condrv[0] == given_condition: from sympy.stats.frv_types import BernoulliDistribution return BernoulliDistribution(self.func(condition).doit(**hints), 0, 1) if any(dependent(rv, given_condition) for rv in condrv): return Probability(condition, given_condition) else: return Probability(condition).doit() if given_condition is not None and \ not isinstance(given_condition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (given_condition)) if given_condition == False or condition is S.false: return S.Zero if not isinstance(condition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (condition)) if condition is S.true: return S.One if numsamples: return sampling_P(condition, given_condition, numsamples=numsamples) if given_condition is not None: # If there is a condition # Recompute on new conditional expr return Probability(given(condition, given_condition)).doit() # Otherwise pass work off to the ProbabilitySpace if pspace(condition) == PSpace(): return Probability(condition, given_condition) result = pspace(condition).probability(condition) if hasattr(result, 'doit') and for_rewrite: return result.doit() else: return result def _eval_rewrite_as_Integral(self, arg, condition=None, **kwargs): return self.func(arg, condition=condition).doit(for_rewrite=True) _eval_rewrite_as_Sum = _eval_rewrite_as_Integral def evaluate_integral(self): return self.rewrite(Integral).doit() class Expectation(Expr): """ Symbolic expression for the expectation. Examples ======== >>> from sympy.stats import Expectation, Normal, Probability, Poisson >>> from sympy import symbols, Integral, Sum >>> mu = symbols("mu") >>> sigma = symbols("sigma", positive=True) >>> X = Normal("X", mu, sigma) >>> Expectation(X) Expectation(X) >>> Expectation(X).evaluate_integral().simplify() mu To get the integral expression of the expectation: >>> Expectation(X).rewrite(Integral) Integral(sqrt(2)*X*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)) The same integral expression, in more abstract terms: >>> Expectation(X).rewrite(Probability) Integral(x*Probability(Eq(X, x)), (x, -oo, oo)) To get the Summation expression of the expectation for discrete random variables: >>> lamda = symbols('lamda', positive=True) >>> Z = Poisson('Z', lamda) >>> Expectation(Z).rewrite(Sum) Sum(Z*lamda**Z*exp(-lamda)/factorial(Z), (Z, 0, oo)) This class is aware of some properties of the expectation: >>> from sympy.abc import a >>> Expectation(a*X) Expectation(a*X) >>> Y = Normal("Y", 1, 2) >>> Expectation(X + Y) Expectation(X + Y) To expand the ``Expectation`` into its expression, use ``expand()``: >>> Expectation(X + Y).expand() Expectation(X) + Expectation(Y) >>> Expectation(a*X + Y).expand() a*Expectation(X) + Expectation(Y) >>> Expectation(a*X + Y) Expectation(a*X + Y) >>> Expectation((X + Y)*(X - Y)).expand() Expectation(X**2) - Expectation(Y**2) To evaluate the ``Expectation``, use ``doit()``: >>> Expectation(X + Y).doit() mu + 1 >>> Expectation(X + Expectation(Y + Expectation(2*X))).doit() 3*mu + 1 To prevent evaluating nested ``Expectation``, use ``doit(deep=False)`` >>> Expectation(X + Expectation(Y)).doit(deep=False) mu + Expectation(Expectation(Y)) >>> Expectation(X + Expectation(Y + Expectation(2*X))).doit(deep=False) mu + Expectation(Expectation(Y + Expectation(2*X))) """ def __new__(cls, expr, condition=None, **kwargs): expr = _sympify(expr) if expr.is_Matrix: from sympy.stats.symbolic_multivariate_probability import ExpectationMatrix return ExpectationMatrix(expr, condition) if condition is None: if not is_random(expr): return expr obj = Expr.__new__(cls, expr) else: condition = _sympify(condition) obj = Expr.__new__(cls, expr, condition) obj._condition = condition return obj def expand(self, **hints): expr = self.args[0] condition = self._condition if not is_random(expr): return expr if isinstance(expr, Add): return Add.fromiter(Expectation(a, condition=condition).expand() for a in expr.args) expand_expr = _expand(expr) if isinstance(expand_expr, Add): return Add.fromiter(Expectation(a, condition=condition).expand() for a in expand_expr.args) elif isinstance(expr, Mul): rv = [] nonrv = [] for a in expr.args: if is_random(a): rv.append(a) else: nonrv.append(a) return Mul.fromiter(nonrv)*Expectation(Mul.fromiter(rv), condition=condition) return self def doit(self, **hints): deep = hints.get('deep', True) condition = self._condition expr = self.args[0] numsamples = hints.get('numsamples', False) for_rewrite = not hints.get('for_rewrite', False) if deep: expr = expr.doit(**hints) if not is_random(expr) or isinstance(expr, Expectation): # expr isn't random? return expr if numsamples: # Computing by monte carlo sampling? evalf = hints.get('evalf', True) return sampling_E(expr, condition, numsamples=numsamples, evalf=evalf) if expr.has(RandomIndexedSymbol): return pspace(expr).compute_expectation(expr, condition) # Create new expr and recompute E if condition is not None: # If there is a condition return self.func(given(expr, condition)).doit(**hints) # A few known statements for efficiency if expr.is_Add: # We know that E is Linear return Add(*[self.func(arg, condition).doit(**hints) if not isinstance(arg, Expectation) else self.func(arg, condition) for arg in expr.args]) if expr.is_Mul: if expr.atoms(Expectation): return expr if pspace(expr) == PSpace(): return self.func(expr) # Otherwise case is simple, pass work off to the ProbabilitySpace result = pspace(expr).compute_expectation(expr, evaluate=for_rewrite) if hasattr(result, 'doit') and for_rewrite: return result.doit(**hints) else: return result def _eval_rewrite_as_Probability(self, arg, condition=None, **kwargs): rvs = arg.atoms(RandomSymbol) if len(rvs) > 1: raise NotImplementedError() if len(rvs) == 0: return arg rv = rvs.pop() if rv.pspace is None: raise ValueError("Probability space not known") symbol = rv.symbol if symbol.name[0].isupper(): symbol = Symbol(symbol.name.lower()) else : symbol = Symbol(symbol.name + "_1") if rv.pspace.is_Continuous: return Integral(arg.replace(rv, symbol)*Probability(Eq(rv, symbol), condition), (symbol, rv.pspace.domain.set.inf, rv.pspace.domain.set.sup)) else: if rv.pspace.is_Finite: raise NotImplementedError else: return Sum(arg.replace(rv, symbol)*Probability(Eq(rv, symbol), condition), (symbol, rv.pspace.domain.set.inf, rv.pspace.set.sup)) def _eval_rewrite_as_Integral(self, arg, condition=None, **kwargs): return self.func(arg, condition=condition).doit(deep=False, for_rewrite=True) _eval_rewrite_as_Sum = _eval_rewrite_as_Integral # For discrete this will be Sum def evaluate_integral(self): return self.rewrite(Integral).doit() evaluate_sum = evaluate_integral class Variance(Expr): """ Symbolic expression for the variance. Examples ======== >>> from sympy import symbols, Integral >>> from sympy.stats import Normal, Expectation, Variance, Probability >>> mu = symbols("mu", positive=True) >>> sigma = symbols("sigma", positive=True) >>> X = Normal("X", mu, sigma) >>> Variance(X) Variance(X) >>> Variance(X).evaluate_integral() sigma**2 Integral representation of the underlying calculations: >>> Variance(X).rewrite(Integral) Integral(sqrt(2)*(X - Integral(sqrt(2)*X*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)))**2*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)) Integral representation, without expanding the PDF: >>> Variance(X).rewrite(Probability) -Integral(x*Probability(Eq(X, x)), (x, -oo, oo))**2 + Integral(x**2*Probability(Eq(X, x)), (x, -oo, oo)) Rewrite the variance in terms of the expectation >>> Variance(X).rewrite(Expectation) -Expectation(X)**2 + Expectation(X**2) Some transformations based on the properties of the variance may happen: >>> from sympy.abc import a >>> Y = Normal("Y", 0, 1) >>> Variance(a*X) Variance(a*X) To expand the variance in its expression, use ``expand()``: >>> Variance(a*X).expand() a**2*Variance(X) >>> Variance(X + Y) Variance(X + Y) >>> Variance(X + Y).expand() 2*Covariance(X, Y) + Variance(X) + Variance(Y) """ def __new__(cls, arg, condition=None, **kwargs): arg = _sympify(arg) if arg.is_Matrix: from sympy.stats.symbolic_multivariate_probability import VarianceMatrix return VarianceMatrix(arg, condition) if condition is None: obj = Expr.__new__(cls, arg) else: condition = _sympify(condition) obj = Expr.__new__(cls, arg, condition) obj._condition = condition return obj def expand(self, **hints): arg = self.args[0] condition = self._condition if not is_random(arg): return S.Zero if isinstance(arg, RandomSymbol): return self elif isinstance(arg, Add): rv = [] for a in arg.args: if is_random(a): rv.append(a) variances = Add(*map(lambda xv: Variance(xv, condition).expand(), rv)) map_to_covar = lambda x: 2*Covariance(*x, condition=condition).expand() covariances = Add(*map(map_to_covar, itertools.combinations(rv, 2))) return variances + covariances elif isinstance(arg, Mul): nonrv = [] rv = [] for a in arg.args: if is_random(a): rv.append(a) else: nonrv.append(a**2) if len(rv) == 0: return S.Zero return Mul.fromiter(nonrv)*Variance(Mul.fromiter(rv), condition) # this expression contains a RandomSymbol somehow: return self def _eval_rewrite_as_Expectation(self, arg, condition=None, **kwargs): e1 = Expectation(arg**2, condition) e2 = Expectation(arg, condition)**2 return e1 - e2 def _eval_rewrite_as_Probability(self, arg, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Probability) def _eval_rewrite_as_Integral(self, arg, condition=None, **kwargs): return variance(self.args[0], self._condition, evaluate=False) _eval_rewrite_as_Sum = _eval_rewrite_as_Integral def evaluate_integral(self): return self.rewrite(Integral).doit() class Covariance(Expr): """ Symbolic expression for the covariance. Examples ======== >>> from sympy.stats import Covariance >>> from sympy.stats import Normal >>> X = Normal("X", 3, 2) >>> Y = Normal("Y", 0, 1) >>> Z = Normal("Z", 0, 1) >>> W = Normal("W", 0, 1) >>> cexpr = Covariance(X, Y) >>> cexpr Covariance(X, Y) Evaluate the covariance, `X` and `Y` are independent, therefore zero is the result: >>> cexpr.evaluate_integral() 0 Rewrite the covariance expression in terms of expectations: >>> from sympy.stats import Expectation >>> cexpr.rewrite(Expectation) Expectation(X*Y) - Expectation(X)*Expectation(Y) In order to expand the argument, use ``expand()``: >>> from sympy.abc import a, b, c, d >>> Covariance(a*X + b*Y, c*Z + d*W) Covariance(a*X + b*Y, c*Z + d*W) >>> Covariance(a*X + b*Y, c*Z + d*W).expand() a*c*Covariance(X, Z) + a*d*Covariance(W, X) + b*c*Covariance(Y, Z) + b*d*Covariance(W, Y) This class is aware of some properties of the covariance: >>> Covariance(X, X).expand() Variance(X) >>> Covariance(a*X, b*Y).expand() a*b*Covariance(X, Y) """ def __new__(cls, arg1, arg2, condition=None, **kwargs): arg1 = _sympify(arg1) arg2 = _sympify(arg2) if arg1.is_Matrix or arg2.is_Matrix: from sympy.stats.symbolic_multivariate_probability import CrossCovarianceMatrix return CrossCovarianceMatrix(arg1, arg2, condition) if kwargs.pop('evaluate', global_parameters.evaluate): arg1, arg2 = sorted([arg1, arg2], key=default_sort_key) if condition is None: obj = Expr.__new__(cls, arg1, arg2) else: condition = _sympify(condition) obj = Expr.__new__(cls, arg1, arg2, condition) obj._condition = condition return obj def expand(self, **hints): arg1 = self.args[0] arg2 = self.args[1] condition = self._condition if arg1 == arg2: return Variance(arg1, condition).expand() if not is_random(arg1): return S.Zero if not is_random(arg2): return S.Zero arg1, arg2 = sorted([arg1, arg2], key=default_sort_key) if isinstance(arg1, RandomSymbol) and isinstance(arg2, RandomSymbol): return Covariance(arg1, arg2, condition) coeff_rv_list1 = self._expand_single_argument(arg1.expand()) coeff_rv_list2 = self._expand_single_argument(arg2.expand()) addends = [a*b*Covariance(*sorted([r1, r2], key=default_sort_key), condition=condition) for (a, r1) in coeff_rv_list1 for (b, r2) in coeff_rv_list2] return Add.fromiter(addends) @classmethod def _expand_single_argument(cls, expr): # return (coefficient, random_symbol) pairs: if isinstance(expr, RandomSymbol): return [(S.One, expr)] elif isinstance(expr, Add): outval = [] for a in expr.args: if isinstance(a, Mul): outval.append(cls._get_mul_nonrv_rv_tuple(a)) elif is_random(a): outval.append((S.One, a)) return outval elif isinstance(expr, Mul): return [cls._get_mul_nonrv_rv_tuple(expr)] elif is_random(expr): return [(S.One, expr)] @classmethod def _get_mul_nonrv_rv_tuple(cls, m): rv = [] nonrv = [] for a in m.args: if is_random(a): rv.append(a) else: nonrv.append(a) return (Mul.fromiter(nonrv), Mul.fromiter(rv)) def _eval_rewrite_as_Expectation(self, arg1, arg2, condition=None, **kwargs): e1 = Expectation(arg1*arg2, condition) e2 = Expectation(arg1, condition)*Expectation(arg2, condition) return e1 - e2 def _eval_rewrite_as_Probability(self, arg1, arg2, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Probability) def _eval_rewrite_as_Integral(self, arg1, arg2, condition=None, **kwargs): return covariance(self.args[0], self.args[1], self._condition, evaluate=False) _eval_rewrite_as_Sum = _eval_rewrite_as_Integral def evaluate_integral(self): return self.rewrite(Integral).doit() class Moment(Expr): """ Symbolic class for Moment Examples ======== >>> from sympy import Symbol, Integral >>> from sympy.stats import Normal, Expectation, Probability, Moment >>> mu = Symbol('mu', real=True) >>> sigma = Symbol('sigma', real=True, positive=True) >>> X = Normal('X', mu, sigma) >>> M = Moment(X, 3, 1) To evaluate the result of Moment use `doit`: >>> M.doit() mu**3 - 3*mu**2 + 3*mu*sigma**2 + 3*mu - 3*sigma**2 - 1 Rewrite the Moment expression in terms of Expectation: >>> M.rewrite(Expectation) Expectation((X - 1)**3) Rewrite the Moment expression in terms of Probability: >>> M.rewrite(Probability) Integral((x - 1)**3*Probability(Eq(X, x)), (x, -oo, oo)) Rewrite the Moment expression in terms of Integral: >>> M.rewrite(Integral) Integral(sqrt(2)*(X - 1)**3*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)) """ def __new__(cls, X, n, c=0, condition=None, **kwargs): X = _sympify(X) n = _sympify(n) c = _sympify(c) if condition is not None: condition = _sympify(condition) return super().__new__(cls, X, n, c, condition) else: return super().__new__(cls, X, n, c) def doit(self, **hints): return self.rewrite(Expectation).doit(**hints) def _eval_rewrite_as_Expectation(self, X, n, c=0, condition=None, **kwargs): return Expectation((X - c)**n, condition) def _eval_rewrite_as_Probability(self, X, n, c=0, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Probability) def _eval_rewrite_as_Integral(self, X, n, c=0, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Integral) class CentralMoment(Expr): """ Symbolic class Central Moment Examples ======== >>> from sympy import Symbol, Integral >>> from sympy.stats import Normal, Expectation, Probability, CentralMoment >>> mu = Symbol('mu', real=True) >>> sigma = Symbol('sigma', real=True, positive=True) >>> X = Normal('X', mu, sigma) >>> CM = CentralMoment(X, 4) To evaluate the result of CentralMoment use `doit`: >>> CM.doit().simplify() 3*sigma**4 Rewrite the CentralMoment expression in terms of Expectation: >>> CM.rewrite(Expectation) Expectation((X - Expectation(X))**4) Rewrite the CentralMoment expression in terms of Probability: >>> CM.rewrite(Probability) Integral((x - Integral(x*Probability(True), (x, -oo, oo)))**4*Probability(Eq(X, x)), (x, -oo, oo)) Rewrite the CentralMoment expression in terms of Integral: >>> CM.rewrite(Integral) Integral(sqrt(2)*(X - Integral(sqrt(2)*X*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)))**4*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)) """ def __new__(cls, X, n, condition=None, **kwargs): X = _sympify(X) n = _sympify(n) if condition is not None: condition = _sympify(condition) return super().__new__(cls, X, n, condition) else: return super().__new__(cls, X, n) def doit(self, **hints): return self.rewrite(Expectation).doit(**hints) def _eval_rewrite_as_Expectation(self, X, n, condition=None, **kwargs): mu = Expectation(X, condition, **kwargs) return Moment(X, n, mu, condition, **kwargs).rewrite(Expectation) def _eval_rewrite_as_Probability(self, X, n, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Probability) def _eval_rewrite_as_Integral(self, X, n, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Integral)
515f25204e68748e37bf2ab830cbe0534714ea0dfb05c72b079c6cb6f73c2e9d
from sympy import (Basic, exp, pi, Lambda, Trace, S, MatrixSymbol, Integral, gamma, Product, Dummy, Sum, Abs, IndexedBase, I) from sympy.core.sympify import _sympify from sympy.stats.rv import _symbol_converter, Density, RandomMatrixSymbol, is_random from sympy.stats.joint_rv_types import JointDistributionHandmade from sympy.stats.random_matrix import RandomMatrixPSpace from sympy.tensor.array import ArrayComprehension __all__ = [ 'CircularEnsemble', 'CircularUnitaryEnsemble', 'CircularOrthogonalEnsemble', 'CircularSymplecticEnsemble', 'GaussianEnsemble', 'GaussianUnitaryEnsemble', 'GaussianOrthogonalEnsemble', 'GaussianSymplecticEnsemble', 'joint_eigen_distribution', 'JointEigenDistribution', 'level_spacing_distribution' ] @is_random.register(RandomMatrixSymbol) def _(x): return True class RandomMatrixEnsembleModel(Basic): """ Base class for random matrix ensembles. It acts as an umbrella and contains the methods common to all the ensembles defined in sympy.stats.random_matrix_models. """ def __new__(cls, sym, dim=None): sym, dim = _symbol_converter(sym), _sympify(dim) if dim.is_integer == False: raise ValueError("Dimension of the random matrices must be " "integers, received %s instead."%(dim)) return Basic.__new__(cls, sym, dim) symbol = property(lambda self: self.args[0]) dimension = property(lambda self: self.args[1]) def density(self, expr): return Density(expr) def __call__(self, expr): return self.density(expr) class GaussianEnsembleModel(RandomMatrixEnsembleModel): """ Abstract class for Gaussian ensembles. Contains the properties common to all the gaussian ensembles. References ========== .. [1] https://en.wikipedia.org/wiki/Random_matrix#Gaussian_ensembles .. [2] https://arxiv.org/pdf/1712.07903.pdf """ def _compute_normalization_constant(self, beta, n): """ Helper function for computing normalization constant for joint probability density of eigen values of Gaussian ensembles. References ========== .. [1] https://en.wikipedia.org/wiki/Selberg_integral#Mehta's_integral """ n = S(n) prod_term = lambda j: gamma(1 + beta*S(j)/2)/gamma(S.One + beta/S(2)) j = Dummy('j', integer=True, positive=True) term1 = Product(prod_term(j), (j, 1, n)).doit() term2 = (2/(beta*n))**(beta*n*(n - 1)/4 + n/2) term3 = (2*pi)**(n/2) return term1 * term2 * term3 def _compute_joint_eigen_distribution(self, beta): """ Helper function for computing the joint probability distribution of eigen values of the random matrix. """ n = self.dimension Zbn = self._compute_normalization_constant(beta, n) l = IndexedBase('l') i = Dummy('i', integer=True, positive=True) j = Dummy('j', integer=True, positive=True) k = Dummy('k', integer=True, positive=True) term1 = exp((-S(n)/2) * Sum(l[k]**2, (k, 1, n)).doit()) sub_term = Lambda(i, Product(Abs(l[j] - l[i])**beta, (j, i + 1, n))) term2 = Product(sub_term(i).doit(), (i, 1, n - 1)).doit() syms = ArrayComprehension(l[k], (k, 1, n)).doit() return Lambda(tuple(syms), (term1 * term2)/Zbn) class GaussianUnitaryEnsembleModel(GaussianEnsembleModel): @property def normalization_constant(self): n = self.dimension return 2**(S(n)/2) * pi**(S(n**2)/2) def density(self, expr): n, ZGUE = self.dimension, self.normalization_constant h_pspace = RandomMatrixPSpace('P', model=self) H = RandomMatrixSymbol('H', n, n, pspace=h_pspace) return Lambda(H, exp(-S(n)/2 * Trace(H**2))/ZGUE)(expr) def joint_eigen_distribution(self): return self._compute_joint_eigen_distribution(S(2)) def level_spacing_distribution(self): s = Dummy('s') f = (32/pi**2)*(s**2)*exp((-4/pi)*s**2) return Lambda(s, f) class GaussianOrthogonalEnsembleModel(GaussianEnsembleModel): @property def normalization_constant(self): n = self.dimension _H = MatrixSymbol('_H', n, n) return Integral(exp(-S(n)/4 * Trace(_H**2))) def density(self, expr): n, ZGOE = self.dimension, self.normalization_constant h_pspace = RandomMatrixPSpace('P', model=self) H = RandomMatrixSymbol('H', n, n, pspace=h_pspace) return Lambda(H, exp(-S(n)/4 * Trace(H**2))/ZGOE)(expr) def joint_eigen_distribution(self): return self._compute_joint_eigen_distribution(S.One) def level_spacing_distribution(self): s = Dummy('s') f = (pi/2)*s*exp((-pi/4)*s**2) return Lambda(s, f) class GaussianSymplecticEnsembleModel(GaussianEnsembleModel): @property def normalization_constant(self): n = self.dimension _H = MatrixSymbol('_H', n, n) return Integral(exp(-S(n) * Trace(_H**2))) def density(self, expr): n, ZGSE = self.dimension, self.normalization_constant h_pspace = RandomMatrixPSpace('P', model=self) H = RandomMatrixSymbol('H', n, n, pspace=h_pspace) return Lambda(H, exp(-S(n) * Trace(H**2))/ZGSE)(expr) def joint_eigen_distribution(self): return self._compute_joint_eigen_distribution(S(4)) def level_spacing_distribution(self): s = Dummy('s') f = ((S(2)**18)/((S(3)**6)*(pi**3)))*(s**4)*exp((-64/(9*pi))*s**2) return Lambda(s, f) def GaussianEnsemble(sym, dim): sym, dim = _symbol_converter(sym), _sympify(dim) model = GaussianEnsembleModel(sym, dim) rmp = RandomMatrixPSpace(sym, model=model) return RandomMatrixSymbol(sym, dim, dim, pspace=rmp) def GaussianUnitaryEnsemble(sym, dim): """ Represents Gaussian Unitary Ensembles. Examples ======== >>> from sympy.stats import GaussianUnitaryEnsemble as GUE, density >>> from sympy import MatrixSymbol >>> G = GUE('U', 2) >>> X = MatrixSymbol('X', 2, 2) >>> density(G)(X) exp(-Trace(X**2))/(2*pi**2) """ sym, dim = _symbol_converter(sym), _sympify(dim) model = GaussianUnitaryEnsembleModel(sym, dim) rmp = RandomMatrixPSpace(sym, model=model) return RandomMatrixSymbol(sym, dim, dim, pspace=rmp) def GaussianOrthogonalEnsemble(sym, dim): """ Represents Gaussian Orthogonal Ensembles. Examples ======== >>> from sympy.stats import GaussianOrthogonalEnsemble as GOE, density >>> from sympy import MatrixSymbol >>> G = GOE('U', 2) >>> X = MatrixSymbol('X', 2, 2) >>> density(G)(X) exp(-Trace(X**2)/2)/Integral(exp(-Trace(_H**2)/2), _H) """ sym, dim = _symbol_converter(sym), _sympify(dim) model = GaussianOrthogonalEnsembleModel(sym, dim) rmp = RandomMatrixPSpace(sym, model=model) return RandomMatrixSymbol(sym, dim, dim, pspace=rmp) def GaussianSymplecticEnsemble(sym, dim): """ Represents Gaussian Symplectic Ensembles. Examples ======== >>> from sympy.stats import GaussianSymplecticEnsemble as GSE, density >>> from sympy import MatrixSymbol >>> G = GSE('U', 2) >>> X = MatrixSymbol('X', 2, 2) >>> density(G)(X) exp(-2*Trace(X**2))/Integral(exp(-2*Trace(_H**2)), _H) """ sym, dim = _symbol_converter(sym), _sympify(dim) model = GaussianSymplecticEnsembleModel(sym, dim) rmp = RandomMatrixPSpace(sym, model=model) return RandomMatrixSymbol(sym, dim, dim, pspace=rmp) class CircularEnsembleModel(RandomMatrixEnsembleModel): """ Abstract class for Circular ensembles. Contains the properties and methods common to all the circular ensembles. References ========== .. [1] https://en.wikipedia.org/wiki/Circular_ensemble """ def density(self, expr): # TODO : Add support for Lie groups(as extensions of sympy.diffgeom) # and define measures on them raise NotImplementedError("Support for Haar measure hasn't been " "implemented yet, therefore the density of " "%s cannot be computed."%(self)) def _compute_joint_eigen_distribution(self, beta): """ Helper function to compute the joint distribution of phases of the complex eigen values of matrices belonging to any circular ensembles. """ n = self.dimension Zbn = ((2*pi)**n)*(gamma(beta*n/2 + 1)/S(gamma(beta/2 + 1))**n) t = IndexedBase('t') i, j, k = (Dummy('i', integer=True), Dummy('j', integer=True), Dummy('k', integer=True)) syms = ArrayComprehension(t[i], (i, 1, n)).doit() f = Product(Product(Abs(exp(I*t[k]) - exp(I*t[j]))**beta, (j, k + 1, n)).doit(), (k, 1, n - 1)).doit() return Lambda(tuple(syms), f/Zbn) class CircularUnitaryEnsembleModel(CircularEnsembleModel): def joint_eigen_distribution(self): return self._compute_joint_eigen_distribution(S(2)) class CircularOrthogonalEnsembleModel(CircularEnsembleModel): def joint_eigen_distribution(self): return self._compute_joint_eigen_distribution(S.One) class CircularSymplecticEnsembleModel(CircularEnsembleModel): def joint_eigen_distribution(self): return self._compute_joint_eigen_distribution(S(4)) def CircularEnsemble(sym, dim): sym, dim = _symbol_converter(sym), _sympify(dim) model = CircularEnsembleModel(sym, dim) rmp = RandomMatrixPSpace(sym, model=model) return RandomMatrixSymbol(sym, dim, dim, pspace=rmp) def CircularUnitaryEnsemble(sym, dim): """ Represents Cicular Unitary Ensembles. Examples ======== >>> from sympy.stats import CircularUnitaryEnsemble as CUE >>> from sympy.stats import joint_eigen_distribution >>> C = CUE('U', 1) >>> joint_eigen_distribution(C) Lambda(t[1], Product(Abs(exp(I*t[_j]) - exp(I*t[_k]))**2, (_j, _k + 1, 1), (_k, 1, 0))/(2*pi)) Note ==== As can be seen above in the example, density of CiruclarUnitaryEnsemble is not evaluated becuase the exact definition is based on haar measure of unitary group which is not unique. """ sym, dim = _symbol_converter(sym), _sympify(dim) model = CircularUnitaryEnsembleModel(sym, dim) rmp = RandomMatrixPSpace(sym, model=model) return RandomMatrixSymbol(sym, dim, dim, pspace=rmp) def CircularOrthogonalEnsemble(sym, dim): """ Represents Cicular Orthogonal Ensembles. Examples ======== >>> from sympy.stats import CircularOrthogonalEnsemble as COE >>> from sympy.stats import joint_eigen_distribution >>> C = COE('O', 1) >>> joint_eigen_distribution(C) Lambda(t[1], Product(Abs(exp(I*t[_j]) - exp(I*t[_k])), (_j, _k + 1, 1), (_k, 1, 0))/(2*pi)) Note ==== As can be seen above in the example, density of CiruclarOrthogonalEnsemble is not evaluated becuase the exact definition is based on haar measure of unitary group which is not unique. """ sym, dim = _symbol_converter(sym), _sympify(dim) model = CircularOrthogonalEnsembleModel(sym, dim) rmp = RandomMatrixPSpace(sym, model=model) return RandomMatrixSymbol(sym, dim, dim, pspace=rmp) def CircularSymplecticEnsemble(sym, dim): """ Represents Cicular Symplectic Ensembles. Examples ======== >>> from sympy.stats import CircularSymplecticEnsemble as CSE >>> from sympy.stats import joint_eigen_distribution >>> C = CSE('S', 1) >>> joint_eigen_distribution(C) Lambda(t[1], Product(Abs(exp(I*t[_j]) - exp(I*t[_k]))**4, (_j, _k + 1, 1), (_k, 1, 0))/(2*pi)) Note ==== As can be seen above in the example, density of CiruclarSymplecticEnsemble is not evaluated becuase the exact definition is based on haar measure of unitary group which is not unique. """ sym, dim = _symbol_converter(sym), _sympify(dim) model = CircularSymplecticEnsembleModel(sym, dim) rmp = RandomMatrixPSpace(sym, model=model) return RandomMatrixSymbol(sym, dim, dim, pspace=rmp) def joint_eigen_distribution(mat): """ For obtaining joint probability distribution of eigen values of random matrix. Parameters ========== mat: RandomMatrixSymbol The matrix symbol whose eigen values are to be considered. Returns ======= Lambda Examples ======== >>> from sympy.stats import GaussianUnitaryEnsemble as GUE >>> from sympy.stats import joint_eigen_distribution >>> U = GUE('U', 2) >>> joint_eigen_distribution(U) Lambda((l[1], l[2]), exp(-l[1]**2 - l[2]**2)*Product(Abs(l[_i] - l[_j])**2, (_j, _i + 1, 2), (_i, 1, 1))/pi) """ if not isinstance(mat, RandomMatrixSymbol): raise ValueError("%s is not of type, RandomMatrixSymbol."%(mat)) return mat.pspace.model.joint_eigen_distribution() def JointEigenDistribution(mat): """ Creates joint distribution of eigen values of matrices with random expressions. Parameters ========== mat: Matrix The matrix under consideration. Returns ======= JointDistributionHandmade Examples ======== >>> from sympy.stats import Normal, JointEigenDistribution >>> from sympy import Matrix >>> A = [[Normal('A00', 0, 1), Normal('A01', 0, 1)], ... [Normal('A10', 0, 1), Normal('A11', 0, 1)]] >>> JointEigenDistribution(Matrix(A)) JointDistributionHandmade(-sqrt(A00**2 - 2*A00*A11 + 4*A01*A10 + A11**2)/2 + A00/2 + A11/2, sqrt(A00**2 - 2*A00*A11 + 4*A01*A10 + A11**2)/2 + A00/2 + A11/2) """ eigenvals = mat.eigenvals(multiple=True) if not all(is_random(eigenval) for eigenval in set(eigenvals)): raise ValueError("Eigen values don't have any random expression, " "joint distribution cannot be generated.") return JointDistributionHandmade(*eigenvals) def level_spacing_distribution(mat): """ For obtaining distribution of level spacings. Parameters ========== mat: RandomMatrixSymbol The random matrix symbol whose eigen values are to be considered for finding the level spacings. Returns ======= Lambda Examples ======== >>> from sympy.stats import GaussianUnitaryEnsemble as GUE >>> from sympy.stats import level_spacing_distribution >>> U = GUE('U', 2) >>> level_spacing_distribution(U) Lambda(_s, 32*_s**2*exp(-4*_s**2/pi)/pi**2) References ========== .. [1] https://en.wikipedia.org/wiki/Random_matrix#Distribution_of_level_spacings """ return mat.pspace.model.level_spacing_distribution()
73258ec0c2083c67c0c3f39662dd883c92ad70b70fa1c88a6b336a9923656676
from sympy.core.compatibility import as_int from sympy.core.function import Function from sympy.core.numbers import igcd, igcdex, mod_inverse from sympy.core.power import isqrt from sympy.core.singleton import S from .primetest import isprime from .factor_ import factorint, trailing, totient, multiplicity from random import randint, Random from itertools import product def n_order(a, n): """Returns the order of ``a`` modulo ``n``. The order of ``a`` modulo ``n`` is the smallest integer ``k`` such that ``a**k`` leaves a remainder of 1 with ``n``. Examples ======== >>> from sympy.ntheory import n_order >>> n_order(3, 7) 6 >>> n_order(4, 7) 3 """ from collections import defaultdict a, n = as_int(a), as_int(n) if igcd(a, n) != 1: raise ValueError("The two numbers should be relatively prime") factors = defaultdict(int) f = factorint(n) for px, kx in f.items(): if kx > 1: factors[px] += kx - 1 fpx = factorint(px - 1) for py, ky in fpx.items(): factors[py] += ky group_order = 1 for px, kx in factors.items(): group_order *= px**kx order = 1 if a > n: a = a % n for p, e in factors.items(): exponent = group_order for f in range(e + 1): if pow(a, exponent, n) != 1: order *= p ** (e - f + 1) break exponent = exponent // p return order def _primitive_root_prime_iter(p): """ Generates the primitive roots for a prime ``p`` Examples ======== >>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter >>> list(_primitive_root_prime_iter(19)) [2, 3, 10, 13, 14, 15] References ========== .. [1] W. Stein "Elementary Number Theory" (2011), page 44 """ # it is assumed that p is an int v = [(p - 1) // i for i in factorint(p - 1).keys()] a = 2 while a < p: for pw in v: # a TypeError below may indicate that p was not an int if pow(a, pw, p) == 1: break else: yield a a += 1 def primitive_root(p): """ Returns the smallest primitive root or None Parameters ========== p : positive integer Examples ======== >>> from sympy.ntheory.residue_ntheory import primitive_root >>> primitive_root(19) 2 References ========== .. [1] W. Stein "Elementary Number Theory" (2011), page 44 .. [2] P. Hackman "Elementary Number Theory" (2009), Chapter C """ p = as_int(p) if p < 1: raise ValueError('p is required to be positive') if p <= 2: return 1 f = factorint(p) if len(f) > 2: return None if len(f) == 2: if 2 not in f or f[2] > 1: return None # case p = 2*p1**k, p1 prime for p1, e1 in f.items(): if p1 != 2: break i = 1 while i < p: i += 2 if i % p1 == 0: continue if is_primitive_root(i, p): return i else: if 2 in f: if p == 4: return 3 return None p1, n = list(f.items())[0] if n > 1: # see Ref [2], page 81 g = primitive_root(p1) if is_primitive_root(g, p1**2): return g else: for i in range(2, g + p1 + 1): if igcd(i, p) == 1 and is_primitive_root(i, p): return i return next(_primitive_root_prime_iter(p)) def is_primitive_root(a, p): """ Returns True if ``a`` is a primitive root of ``p`` ``a`` is said to be the primitive root of ``p`` if gcd(a, p) == 1 and totient(p) is the smallest positive number s.t. a**totient(p) cong 1 mod(p) Examples ======== >>> from sympy.ntheory import is_primitive_root, n_order, totient >>> is_primitive_root(3, 10) True >>> is_primitive_root(9, 10) False >>> n_order(3, 10) == totient(10) True >>> n_order(9, 10) == totient(10) False """ a, p = as_int(a), as_int(p) if igcd(a, p) != 1: raise ValueError("The two numbers should be relatively prime") if a > p: a = a % p return n_order(a, p) == totient(p) def _sqrt_mod_tonelli_shanks(a, p): """ Returns the square root in the case of ``p`` prime with ``p == 1 (mod 8)`` References ========== .. [1] R. Crandall and C. Pomerance "Prime Numbers", 2nt Ed., page 101 """ s = trailing(p - 1) t = p >> s # find a non-quadratic residue while 1: d = randint(2, p - 1) r = legendre_symbol(d, p) if r == -1: break #assert legendre_symbol(d, p) == -1 A = pow(a, t, p) D = pow(d, t, p) m = 0 for i in range(s): adm = A*pow(D, m, p) % p adm = pow(adm, 2**(s - 1 - i), p) if adm % p == p - 1: m += 2**i #assert A*pow(D, m, p) % p == 1 x = pow(a, (t + 1)//2, p)*pow(D, m//2, p) % p return x def sqrt_mod(a, p, all_roots=False): """ Find a root of ``x**2 = a mod p`` Parameters ========== a : integer p : positive integer all_roots : if True the list of roots is returned or None Notes ===== If there is no root it is returned None; else the returned root is less or equal to ``p // 2``; in general is not the smallest one. It is returned ``p // 2`` only if it is the only root. Use ``all_roots`` only when it is expected that all the roots fit in memory; otherwise use ``sqrt_mod_iter``. Examples ======== >>> from sympy.ntheory import sqrt_mod >>> sqrt_mod(11, 43) 21 >>> sqrt_mod(17, 32, True) [7, 9, 23, 25] """ if all_roots: return sorted(list(sqrt_mod_iter(a, p))) try: p = abs(as_int(p)) it = sqrt_mod_iter(a, p) r = next(it) if r > p // 2: return p - r elif r < p // 2: return r else: try: r = next(it) if r > p // 2: return p - r except StopIteration: pass return r except StopIteration: return None def _product(*iters): """ Cartesian product generator Notes ===== Unlike itertools.product, it works also with iterables which do not fit in memory. See http://bugs.python.org/issue10109 Author: Fernando Sumudu with small changes """ import itertools inf_iters = tuple(itertools.cycle(enumerate(it)) for it in iters) num_iters = len(inf_iters) cur_val = [None]*num_iters first_v = True while True: i, p = 0, num_iters while p and not i: p -= 1 i, cur_val[p] = next(inf_iters[p]) if not p and not i: if first_v: first_v = False else: break yield cur_val def sqrt_mod_iter(a, p, domain=int): """ Iterate over solutions to ``x**2 = a mod p`` Parameters ========== a : integer p : positive integer domain : integer domain, ``int``, ``ZZ`` or ``Integer`` Examples ======== >>> from sympy.ntheory.residue_ntheory import sqrt_mod_iter >>> list(sqrt_mod_iter(11, 43)) [21, 22] """ from sympy.polys.galoistools import gf_crt1, gf_crt2 from sympy.polys.domains import ZZ a, p = as_int(a), abs(as_int(p)) if isprime(p): a = a % p if a == 0: res = _sqrt_mod1(a, p, 1) else: res = _sqrt_mod_prime_power(a, p, 1) if res: if domain is ZZ: yield from res else: for x in res: yield domain(x) else: f = factorint(p) v = [] pv = [] for px, ex in f.items(): if a % px == 0: rx = _sqrt_mod1(a, px, ex) if not rx: return else: rx = _sqrt_mod_prime_power(a, px, ex) if not rx: return v.append(rx) pv.append(px**ex) mm, e, s = gf_crt1(pv, ZZ) if domain is ZZ: for vx in _product(*v): r = gf_crt2(vx, pv, mm, e, s, ZZ) yield r else: for vx in _product(*v): r = gf_crt2(vx, pv, mm, e, s, ZZ) yield domain(r) def _sqrt_mod_prime_power(a, p, k): """ Find the solutions to ``x**2 = a mod p**k`` when ``a % p != 0`` Parameters ========== a : integer p : prime number k : positive integer Examples ======== >>> from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power >>> _sqrt_mod_prime_power(11, 43, 1) [21, 22] References ========== .. [1] P. Hackman "Elementary Number Theory" (2009), page 160 .. [2] http://www.numbertheory.org/php/squareroot.html .. [3] [Gathen99]_ """ from sympy.core.numbers import igcdex from sympy.polys.domains import ZZ pk = p**k a = a % pk if k == 1: if p == 2: return [ZZ(a)] if not (a % p < 2 or pow(a, (p - 1) // 2, p) == 1): return None if p % 4 == 3: res = pow(a, (p + 1) // 4, p) elif p % 8 == 5: sign = pow(a, (p - 1) // 4, p) if sign == 1: res = pow(a, (p + 3) // 8, p) else: b = pow(4*a, (p - 5) // 8, p) x = (2*a*b) % p if pow(x, 2, p) == a: res = x else: res = _sqrt_mod_tonelli_shanks(a, p) # ``_sqrt_mod_tonelli_shanks(a, p)`` is not deterministic; # sort to get always the same result return sorted([ZZ(res), ZZ(p - res)]) if k > 1: # see Ref.[2] if p == 2: if a % 8 != 1: return None if k <= 3: s = set() for i in range(0, pk, 4): s.add(1 + i) s.add(-1 + i) return list(s) # according to Ref.[2] for k > 2 there are two solutions # (mod 2**k-1), that is four solutions (mod 2**k), which can be # obtained from the roots of x**2 = 0 (mod 8) rv = [ZZ(1), ZZ(3), ZZ(5), ZZ(7)] # hensel lift them to solutions of x**2 = 0 (mod 2**k) # if r**2 - a = 0 mod 2**nx but not mod 2**(nx+1) # then r + 2**(nx - 1) is a root mod 2**(nx+1) n = 3 res = [] for r in rv: nx = n while nx < k: r1 = (r**2 - a) >> nx if r1 % 2: r = r + (1 << (nx - 1)) #assert (r**2 - a)% (1 << (nx + 1)) == 0 nx += 1 if r not in res: res.append(r) x = r + (1 << (k - 1)) #assert (x**2 - a) % pk == 0 if x < (1 << nx) and x not in res: if (x**2 - a) % pk == 0: res.append(x) return res rv = _sqrt_mod_prime_power(a, p, 1) if not rv: return None r = rv[0] fr = r**2 - a # hensel lifting with Newton iteration, see Ref.[3] chapter 9 # with f(x) = x**2 - a; one has f'(a) != 0 (mod p) for p != 2 n = 1 px = p while 1: n1 = n n1 *= 2 if n1 > k: break n = n1 px = px**2 frinv = igcdex(2*r, px)[0] r = (r - fr*frinv) % px fr = r**2 - a if n < k: px = p**k frinv = igcdex(2*r, px)[0] r = (r - fr*frinv) % px return [r, px - r] def _sqrt_mod1(a, p, n): """ Find solution to ``x**2 == a mod p**n`` when ``a % p == 0`` see http://www.numbertheory.org/php/squareroot.html """ pn = p**n a = a % pn if a == 0: # case gcd(a, p**k) = p**n m = n // 2 if n % 2 == 1: pm1 = p**(m + 1) def _iter0a(): i = 0 while i < pn: yield i i += pm1 return _iter0a() else: pm = p**m def _iter0b(): i = 0 while i < pn: yield i i += pm return _iter0b() # case gcd(a, p**k) = p**r, r < n f = factorint(a) r = f[p] if r % 2 == 1: return None m = r // 2 a1 = a >> r if p == 2: if n - r == 1: pnm1 = 1 << (n - m + 1) pm1 = 1 << (m + 1) def _iter1(): k = 1 << (m + 2) i = 1 << m while i < pnm1: j = i while j < pn: yield j j += k i += pm1 return _iter1() if n - r == 2: res = _sqrt_mod_prime_power(a1, p, n - r) if res is None: return None pnm = 1 << (n - m) def _iter2(): s = set() for r in res: i = 0 while i < pn: x = (r << m) + i if x not in s: s.add(x) yield x i += pnm return _iter2() if n - r > 2: res = _sqrt_mod_prime_power(a1, p, n - r) if res is None: return None pnm1 = 1 << (n - m - 1) def _iter3(): s = set() for r in res: i = 0 while i < pn: x = ((r << m) + i) % pn if x not in s: s.add(x) yield x i += pnm1 return _iter3() else: m = r // 2 a1 = a // p**r res1 = _sqrt_mod_prime_power(a1, p, n - r) if res1 is None: return None pm = p**m pnr = p**(n-r) pnm = p**(n-m) def _iter4(): s = set() pm = p**m for rx in res1: i = 0 while i < pnm: x = ((rx + i) % pn) if x not in s: s.add(x) yield x*pm i += pnr return _iter4() def is_quad_residue(a, p): """ Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``, i.e a % p in set([i**2 % p for i in range(p)]). If ``p`` is an odd prime, an iterative method is used to make the determination: >>> from sympy.ntheory import is_quad_residue >>> sorted(set([i**2 % 7 for i in range(7)])) [0, 1, 2, 4] >>> [j for j in range(7) if is_quad_residue(j, 7)] [0, 1, 2, 4] See Also ======== legendre_symbol, jacobi_symbol """ a, p = as_int(a), as_int(p) if p < 1: raise ValueError('p must be > 0') if a >= p or a < 0: a = a % p if a < 2 or p < 3: return True if not isprime(p): if p % 2 and jacobi_symbol(a, p) == -1: return False r = sqrt_mod(a, p) if r is None: return False else: return True return pow(a, (p - 1) // 2, p) == 1 def is_nthpow_residue(a, n, m): """ Returns True if ``x**n == a (mod m)`` has solutions. References ========== .. [1] P. Hackman "Elementary Number Theory" (2009), page 76 """ a = a % m a, n, m = as_int(a), as_int(n), as_int(m) if m <= 0: raise ValueError('m must be > 0') if n < 0: raise ValueError('n must be >= 0') if n == 0: if m == 1: return False return a == 1 if a == 0: return True if n == 1: return True if n == 2: return is_quad_residue(a, m) return _is_nthpow_residue_bign(a, n, m) def _is_nthpow_residue_bign(a, n, m): """Returns True if ``x**n == a (mod m)`` has solutions for n > 2.""" # assert n > 2 # assert a > 0 and m > 0 if primitive_root(m) is None or igcd(a, m) != 1: # assert m >= 8 for prime, power in factorint(m).items(): if not _is_nthpow_residue_bign_prime_power(a, n, prime, power): return False return True f = totient(m) k = f // igcd(f, n) return pow(a, k, m) == 1 def _is_nthpow_residue_bign_prime_power(a, n, p, k): """Returns True/False if a solution for ``x**n == a (mod(p**k))`` does/doesn't exist.""" # assert a > 0 # assert n > 2 # assert p is prime # assert k > 0 if a % p: if p != 2: return _is_nthpow_residue_bign(a, n, pow(p, k)) if n & 1: return True c = trailing(n) return a % pow(2, min(c + 2, k)) == 1 else: a %= pow(p, k) if not a: return True mu = multiplicity(p, a) if mu % n: return False pm = pow(p, mu) return _is_nthpow_residue_bign_prime_power(a//pm, n, p, k - mu) def _nthroot_mod2(s, q, p): f = factorint(q) v = [] for b, e in f.items(): v.extend([b]*e) for qx in v: s = _nthroot_mod1(s, qx, p, False) return s def _nthroot_mod1(s, q, p, all_roots): """ Root of ``x**q = s mod p``, ``p`` prime and ``q`` divides ``p - 1`` References ========== .. [1] A. M. Johnston "A Generalized qth Root Algorithm" """ g = primitive_root(p) if not isprime(q): r = _nthroot_mod2(s, q, p) else: f = p - 1 assert (p - 1) % q == 0 # determine k k = 0 while f % q == 0: k += 1 f = f // q # find z, x, r1 f1 = igcdex(-f, q)[0] % q z = f*f1 x = (1 + z) // q r1 = pow(s, x, p) s1 = pow(s, f, p) h = pow(g, f*q, p) t = discrete_log(p, s1, h) g2 = pow(g, z*t, p) g3 = igcdex(g2, p)[0] r = r1*g3 % p #assert pow(r, q, p) == s res = [r] h = pow(g, (p - 1) // q, p) #assert pow(h, q, p) == 1 hx = r for i in range(q - 1): hx = (hx*h) % p res.append(hx) if all_roots: res.sort() return res return min(res) def _help(m, prime_modulo_method, diff_method, expr_val): """ Helper function for _nthroot_mod_composite and polynomial_congruence. Parameters ========== m : positive integer prime_modulo_method : function to calculate the root of the congruence equation for the prime divisors of m diff_method : function to calculate derivative of expression at any given point expr_val : function to calculate value of the expression at any given point """ from sympy.ntheory.modular import crt f = factorint(m) dd = {} for p, e in f.items(): tot_roots = set() if e == 1: tot_roots.update(prime_modulo_method(p)) else: for root in prime_modulo_method(p): diff = diff_method(root, p) if diff != 0: ppow = p m_inv = mod_inverse(diff, p) for j in range(1, e): ppow *= p root = (root - expr_val(root, ppow) * m_inv) % ppow tot_roots.add(root) else: new_base = p roots_in_base = {root} while new_base < pow(p, e): new_base *= p new_roots = set() for k in roots_in_base: if expr_val(k, new_base)!= 0: continue while k not in new_roots: new_roots.add(k) k = (k + (new_base // p)) % new_base roots_in_base = new_roots tot_roots = tot_roots | roots_in_base if tot_roots == set(): return [] dd[pow(p, e)] = tot_roots a = [] m = [] for x, y in dd.items(): m.append(x) a.append(list(y)) return sorted({crt(m, list(i))[0] for i in product(*a)}) def _nthroot_mod_composite(a, n, m): """ Find the solutions to ``x**n = a mod m`` when m is not prime. """ return _help(m, lambda p: nthroot_mod(a, n, p, True), lambda root, p: (pow(root, n - 1, p) * (n % p)) % p, lambda root, p: (pow(root, n, p) - a) % p) def nthroot_mod(a, n, p, all_roots=False): """ Find the solutions to ``x**n = a mod p`` Parameters ========== a : integer n : positive integer p : positive integer all_roots : if False returns the smallest root, else the list of roots Examples ======== >>> from sympy.ntheory.residue_ntheory import nthroot_mod >>> nthroot_mod(11, 4, 19) 8 >>> nthroot_mod(11, 4, 19, True) [8, 11] >>> nthroot_mod(68, 3, 109) 23 """ from sympy.core.numbers import igcdex a = a % p a, n, p = as_int(a), as_int(n), as_int(p) if n == 2: return sqrt_mod(a, p, all_roots) # see Hackman "Elementary Number Theory" (2009), page 76 if not isprime(p): return _nthroot_mod_composite(a, n, p) if a % p == 0: return [0] if not is_nthpow_residue(a, n, p): return [] if all_roots else None if (p - 1) % n == 0: return _nthroot_mod1(a, n, p, all_roots) # The roots of ``x**n - a = 0 (mod p)`` are roots of # ``gcd(x**n - a, x**(p - 1) - 1) = 0 (mod p)`` pa = n pb = p - 1 b = 1 if pa < pb: a, pa, b, pb = b, pb, a, pa while pb: # x**pa - a = 0; x**pb - b = 0 # x**pa - a = x**(q*pb + r) - a = (x**pb)**q * x**r - a = # b**q * x**r - a; x**r - c = 0; c = b**-q * a mod p q, r = divmod(pa, pb) c = pow(b, q, p) c = igcdex(c, p)[0] c = (c * a) % p pa, pb = pb, r a, b = b, c if pa == 1: if all_roots: res = [a] else: res = a elif pa == 2: return sqrt_mod(a, p , all_roots) else: res = _nthroot_mod1(a, pa, p, all_roots) return res def quadratic_residues(p): """ Returns the list of quadratic residues. Examples ======== >>> from sympy.ntheory.residue_ntheory import quadratic_residues >>> quadratic_residues(7) [0, 1, 2, 4] """ p = as_int(p) r = set() for i in range(p // 2 + 1): r.add(pow(i, 2, p)) return sorted(list(r)) def legendre_symbol(a, p): r""" Returns the Legendre symbol `(a / p)`. For an integer ``a`` and an odd prime ``p``, the Legendre symbol is defined as .. math :: \genfrac(){}{}{a}{p} = \begin{cases} 0 & \text{if } p \text{ divides } a\\ 1 & \text{if } a \text{ is a quadratic residue modulo } p\\ -1 & \text{if } a \text{ is a quadratic nonresidue modulo } p \end{cases} Parameters ========== a : integer p : odd prime Examples ======== >>> from sympy.ntheory import legendre_symbol >>> [legendre_symbol(i, 7) for i in range(7)] [0, 1, 1, -1, 1, -1, -1] >>> sorted(set([i**2 % 7 for i in range(7)])) [0, 1, 2, 4] See Also ======== is_quad_residue, jacobi_symbol """ a, p = as_int(a), as_int(p) if not isprime(p) or p == 2: raise ValueError("p should be an odd prime") a = a % p if not a: return 0 if pow(a, (p - 1) // 2, p) == 1: return 1 return -1 def jacobi_symbol(m, n): r""" Returns the Jacobi symbol `(m / n)`. For any integer ``m`` and any positive odd integer ``n`` the Jacobi symbol is defined as the product of the Legendre symbols corresponding to the prime factors of ``n``: .. math :: \genfrac(){}{}{m}{n} = \genfrac(){}{}{m}{p^{1}}^{\alpha_1} \genfrac(){}{}{m}{p^{2}}^{\alpha_2} ... \genfrac(){}{}{m}{p^{k}}^{\alpha_k} \text{ where } n = p_1^{\alpha_1} p_2^{\alpha_2} ... p_k^{\alpha_k} Like the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = -1` then ``m`` is a quadratic nonresidue modulo ``n``. But, unlike the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = 1` then ``m`` may or may not be a quadratic residue modulo ``n``. Parameters ========== m : integer n : odd positive integer Examples ======== >>> from sympy.ntheory import jacobi_symbol, legendre_symbol >>> from sympy import S >>> jacobi_symbol(45, 77) -1 >>> jacobi_symbol(60, 121) 1 The relationship between the ``jacobi_symbol`` and ``legendre_symbol`` can be demonstrated as follows: >>> L = legendre_symbol >>> S(45).factors() {3: 2, 5: 1} >>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1 True See Also ======== is_quad_residue, legendre_symbol """ m, n = as_int(m), as_int(n) if n < 0 or not n % 2: raise ValueError("n should be an odd positive integer") if m < 0 or m > n: m %= n if not m: return int(n == 1) if n == 1 or m == 1: return 1 if igcd(m, n) != 1: return 0 j = 1 if m < 0: m = -m if n % 4 == 3: j = -j while m != 0: while m % 2 == 0 and m > 0: m >>= 1 if n % 8 in [3, 5]: j = -j m, n = n, m if m % 4 == n % 4 == 3: j = -j m %= n if n != 1: j = 0 return j class mobius(Function): """ Mobius function maps natural number to {-1, 0, 1} It is defined as follows: 1) `1` if `n = 1`. 2) `0` if `n` has a squared prime factor. 3) `(-1)^k` if `n` is a square-free positive integer with `k` number of prime factors. It is an important multiplicative function in number theory and combinatorics. It has applications in mathematical series, algebraic number theory and also physics (Fermion operator has very concrete realization with Mobius Function model). Parameters ========== n : positive integer Examples ======== >>> from sympy.ntheory import mobius >>> mobius(13*7) 1 >>> mobius(1) 1 >>> mobius(13*7*5) -1 >>> mobius(13**2) 0 References ========== .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_function .. [2] Thomas Koshy "Elementary Number Theory with Applications" """ @classmethod def eval(cls, n): if n.is_integer: if n.is_positive is not True: raise ValueError("n should be a positive integer") else: raise TypeError("n should be an integer") if n.is_prime: return S.NegativeOne elif n is S.One: return S.One elif n.is_Integer: a = factorint(n) if any(i > 1 for i in a.values()): return S.Zero return S.NegativeOne**len(a) def _discrete_log_trial_mul(n, a, b, order=None): """ Trial multiplication algorithm for computing the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. The algorithm finds the discrete logarithm using exhaustive search. This naive method is used as fallback algorithm of ``discrete_log`` when the group order is very small. Examples ======== >>> from sympy.ntheory.residue_ntheory import _discrete_log_trial_mul >>> _discrete_log_trial_mul(41, 15, 7) 3 See Also ======== discrete_log References ========== .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & Vanstone, S. A. (1997). """ a %= n b %= n if order is None: order = n x = 1 for i in range(order): if x == a: return i x = x * b % n raise ValueError("Log does not exist") def _discrete_log_shanks_steps(n, a, b, order=None): """ Baby-step giant-step algorithm for computing the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. The algorithm is a time-memory trade-off of the method of exhaustive search. It uses `O(sqrt(m))` memory, where `m` is the group order. Examples ======== >>> from sympy.ntheory.residue_ntheory import _discrete_log_shanks_steps >>> _discrete_log_shanks_steps(41, 15, 7) 3 See Also ======== discrete_log References ========== .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & Vanstone, S. A. (1997). """ a %= n b %= n if order is None: order = n_order(b, n) m = isqrt(order) + 1 T = dict() x = 1 for i in range(m): T[x] = i x = x * b % n z = mod_inverse(b, n) z = pow(z, m, n) x = a for i in range(m): if x in T: return i * m + T[x] x = x * z % n raise ValueError("Log does not exist") def _discrete_log_pollard_rho(n, a, b, order=None, retries=10, rseed=None): """ Pollard's Rho algorithm for computing the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. It is a randomized algorithm with the same expected running time as ``_discrete_log_shanks_steps``, but requires a negligible amount of memory. Examples ======== >>> from sympy.ntheory.residue_ntheory import _discrete_log_pollard_rho >>> _discrete_log_pollard_rho(227, 3**7, 3) 7 See Also ======== discrete_log References ========== .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & Vanstone, S. A. (1997). """ a %= n b %= n if order is None: order = n_order(b, n) prng = Random() if rseed is not None: prng.seed(rseed) for i in range(retries): aa = prng.randint(1, order - 1) ba = prng.randint(1, order - 1) xa = pow(b, aa, n) * pow(a, ba, n) % n c = xa % 3 if c == 0: xb = a * xa % n ab = aa bb = (ba + 1) % order elif c == 1: xb = xa * xa % n ab = (aa + aa) % order bb = (ba + ba) % order else: xb = b * xa % n ab = (aa + 1) % order bb = ba for j in range(order): c = xa % 3 if c == 0: xa = a * xa % n ba = (ba + 1) % order elif c == 1: xa = xa * xa % n aa = (aa + aa) % order ba = (ba + ba) % order else: xa = b * xa % n aa = (aa + 1) % order c = xb % 3 if c == 0: xb = a * xb % n bb = (bb + 1) % order elif c == 1: xb = xb * xb % n ab = (ab + ab) % order bb = (bb + bb) % order else: xb = b * xb % n ab = (ab + 1) % order c = xb % 3 if c == 0: xb = a * xb % n bb = (bb + 1) % order elif c == 1: xb = xb * xb % n ab = (ab + ab) % order bb = (bb + bb) % order else: xb = b * xb % n ab = (ab + 1) % order if xa == xb: r = (ba - bb) % order try: e = mod_inverse(r, order) * (ab - aa) % order if (pow(b, e, n) - a) % n == 0: return e except ValueError: pass break raise ValueError("Pollard's Rho failed to find logarithm") def _discrete_log_pohlig_hellman(n, a, b, order=None): """ Pohlig-Hellman algorithm for computing the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. In order to compute the discrete logarithm, the algorithm takes advantage of the factorization of the group order. It is more efficient when the group order factors into many small primes. Examples ======== >>> from sympy.ntheory.residue_ntheory import _discrete_log_pohlig_hellman >>> _discrete_log_pohlig_hellman(251, 210, 71) 197 See Also ======== discrete_log References ========== .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & Vanstone, S. A. (1997). """ from .modular import crt a %= n b %= n if order is None: order = n_order(b, n) f = factorint(order) l = [0] * len(f) for i, (pi, ri) in enumerate(f.items()): for j in range(ri): gj = pow(b, l[i], n) aj = pow(a * mod_inverse(gj, n), order // pi**(j + 1), n) bj = pow(b, order // pi, n) cj = discrete_log(n, aj, bj, pi, True) l[i] += cj * pi**j d, _ = crt([pi**ri for pi, ri in f.items()], l) return d def discrete_log(n, a, b, order=None, prime_order=None): """ Compute the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. This is a recursive function to reduce the discrete logarithm problem in cyclic groups of composite order to the problem in cyclic groups of prime order. It employs different algorithms depending on the problem (subgroup order size, prime order or not): * Trial multiplication * Baby-step giant-step * Pollard's Rho * Pohlig-Hellman Examples ======== >>> from sympy.ntheory import discrete_log >>> discrete_log(41, 15, 7) 3 References ========== .. [1] http://mathworld.wolfram.com/DiscreteLogarithm.html .. [2] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & Vanstone, S. A. (1997). """ n, a, b = as_int(n), as_int(a), as_int(b) if order is None: order = n_order(b, n) if prime_order is None: prime_order = isprime(order) if order < 1000: return _discrete_log_trial_mul(n, a, b, order) elif prime_order: if order < 1000000000000: return _discrete_log_shanks_steps(n, a, b, order) return _discrete_log_pollard_rho(n, a, b, order) return _discrete_log_pohlig_hellman(n, a, b, order) def quadratic_congruence(a, b, c, p): """ Find the solutions to ``a x**2 + b x + c = 0 mod p a : integer b : integer c : integer p : positive integer """ from sympy.polys.galoistools import linear_congruence a = as_int(a) b = as_int(b) c = as_int(c) p = as_int(p) a = a % p b = b % p c = c % p if a == 0: return linear_congruence(b, -c, p) if p == 2: roots = [] if c % 2 == 0: roots.append(0) if (a + b + c) % 2 == 0: roots.append(1) return roots if isprime(p): inv_a = mod_inverse(a, p) b *= inv_a c *= inv_a if b % 2 == 1: b = b + p d = ((b * b) // 4 - c) % p y = sqrt_mod(d, p, all_roots=True) res = set() for i in y: res.add((i - b // 2) % p) return sorted(res) y = sqrt_mod(b * b - 4 * a * c , 4 * a * p, all_roots=True) res = set() for i in y: root = linear_congruence(2 * a, i - b, 4 * a * p) for j in root: res.add(j % p) return sorted(res) def _polynomial_congruence_prime(coefficients, p): """A helper function used by polynomial_congruence. It returns the root of a polynomial modulo prime number by naive search from [0, p). Parameters ========== coefficients : list of integers p : prime number """ roots = [] rank = len(coefficients) for i in range(0, p): f_val = 0 for coeff in range(0,rank - 1): f_val = (f_val + pow(i, int(rank - coeff - 1), p) * coefficients[coeff]) % p f_val = f_val + coefficients[-1] if f_val % p == 0: roots.append(i) return roots def _diff_poly(root, coefficients, p): """A helper function used by polynomial_congruence. It returns the derivative of the polynomial evaluated at the root (mod p). Parameters ========== coefficients : list of integers p : prime number root : integer """ diff = 0 rank = len(coefficients) for coeff in range(0, rank - 1): if not coefficients[coeff]: continue diff = (diff + pow(root, rank - coeff - 2, p)*(rank - coeff - 1)* coefficients[coeff]) % p return diff % p def _val_poly(root, coefficients, p): """A helper function used by polynomial_congruence. It returns value of the polynomial at root (mod p). Parameters ========== coefficients : list of integers p : prime number root : integer """ rank = len(coefficients) f_val = 0 for coeff in range(0, rank - 1): f_val = (f_val + pow(root, rank - coeff - 1, p)* coefficients[coeff]) % p f_val = f_val + coefficients[-1] return f_val % p def _valid_expr(expr): """ return coefficients of expr if it is a univariate polynomial with integer coefficients else raise a ValueError. """ from sympy import Poly from sympy.polys.domains import ZZ if not expr.is_polynomial(): raise ValueError("The expression should be a polynomial") polynomial = Poly(expr) if not polynomial.is_univariate: raise ValueError("The expression should be univariate") if not polynomial.domain == ZZ: raise ValueError("The expression should should have integer coefficients") return polynomial.all_coeffs() def polynomial_congruence(expr, m): """ Find the solutions to a polynomial congruence equation modulo m. Parameters ========== coefficients : Coefficients of the Polynomial m : positive integer Examples ======== >>> from sympy.ntheory import polynomial_congruence >>> from sympy.abc import x >>> expr = x**6 - 2*x**5 -35 >>> polynomial_congruence(expr, 6125) [3257] """ coefficients = _valid_expr(expr) coefficients = [num % m for num in coefficients] rank = len(coefficients) if rank == 3: return quadratic_congruence(*coefficients, m) if rank == 2: return quadratic_congruence(0, *coefficients, m) if coefficients[0] == 1 and 1 + coefficients[-1] == sum(coefficients): return nthroot_mod(-coefficients[-1], rank - 1, m, True) if isprime(m): return _polynomial_congruence_prime(coefficients, m) return _help(m, lambda p: _polynomial_congruence_prime(coefficients, p), lambda root, p: _diff_poly(root, coefficients, p), lambda root, p: _val_poly(root, coefficients, p))
c3fbba312ca4f04da66e32779af2b0fa907bdc313dee8eee2cd95529db464a4b
""" Primality testing """ from sympy.core.compatibility import as_int from mpmath.libmp import bitcount as _bitlength def _int_tuple(*i): return tuple(int(_) for _ in i) def is_euler_pseudoprime(n, b): """Returns True if n is prime or an Euler pseudoprime to base b, else False. Euler Pseudoprime : In arithmetic, an odd composite integer n is called an euler pseudoprime to base a, if a and n are coprime and satisfy the modular arithmetic congruence relation : a ^ (n-1)/2 = + 1(mod n) or a ^ (n-1)/2 = - 1(mod n) (where mod refers to the modulo operation). Examples ======== >>> from sympy.ntheory.primetest import is_euler_pseudoprime >>> is_euler_pseudoprime(2, 5) True References ========== .. [1] https://en.wikipedia.org/wiki/Euler_pseudoprime """ from sympy.ntheory.factor_ import trailing if not mr(n, [b]): return False n = as_int(n) r = n - 1 c = pow(b, r >> trailing(r), n) if c == 1: return True while True: if c == n - 1: return True c = pow(c, 2, n) if c == 1: return False def is_square(n, prep=True): """Return True if n == a * a for some integer a, else False. If n is suspected of *not* being a square then this is a quick method of confirming that it is not. Examples ======== >>> from sympy.ntheory.primetest import is_square >>> is_square(25) True >>> is_square(2) False References ========== [1] http://mersenneforum.org/showpost.php?p=110896 See Also ======== sympy.core.power.integer_nthroot """ if prep: n = as_int(n) if n < 0: return False if n in (0, 1): return True m = n & 127 if not ((m*0x8bc40d7d) & (m*0xa1e2f5d1) & 0x14020a): m = n % 63 if not ((m*0x3d491df7) & (m*0xc824a9f9) & 0x10f14008): from sympy.core.power import integer_nthroot return integer_nthroot(n, 2)[1] return False def _test(n, base, s, t): """Miller-Rabin strong pseudoprime test for one base. Return False if n is definitely composite, True if n is probably prime, with a probability greater than 3/4. """ # do the Fermat test b = pow(base, t, n) if b == 1 or b == n - 1: return True else: for j in range(1, s): b = pow(b, 2, n) if b == n - 1: return True # see I. Niven et al. "An Introduction to Theory of Numbers", page 78 if b == 1: return False return False def mr(n, bases): """Perform a Miller-Rabin strong pseudoprime test on n using a given list of bases/witnesses. References ========== - Richard Crandall & Carl Pomerance (2005), "Prime Numbers: A Computational Perspective", Springer, 2nd edition, 135-138 A list of thresholds and the bases they require are here: https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants Examples ======== >>> from sympy.ntheory.primetest import mr >>> mr(1373651, [2, 3]) False >>> mr(479001599, [31, 73]) True """ from sympy.ntheory.factor_ import trailing from sympy.polys.domains import ZZ n = as_int(n) if n < 2: return False # remove powers of 2 from n-1 (= t * 2**s) s = trailing(n - 1) t = n >> s for base in bases: # Bases >= n are wrapped, bases < 2 are invalid if base >= n: base %= n if base >= 2: base = ZZ(base) if not _test(n, base, s, t): return False return True def _lucas_sequence(n, P, Q, k): """Return the modular Lucas sequence (U_k, V_k, Q_k). Given a Lucas sequence defined by P, Q, returns the kth values for U and V, along with Q^k, all modulo n. This is intended for use with possibly very large values of n and k, where the combinatorial functions would be completely unusable. The modular Lucas sequences are used in numerous places in number theory, especially in the Lucas compositeness tests and the various n + 1 proofs. Examples ======== >>> from sympy.ntheory.primetest import _lucas_sequence >>> N = 10**2000 + 4561 >>> sol = U, V, Qk = _lucas_sequence(N, 3, 1, N//2); sol (0, 2, 1) """ D = P*P - 4*Q if n < 2: raise ValueError("n must be >= 2") if k < 0: raise ValueError("k must be >= 0") if D == 0: raise ValueError("D must not be zero") if k == 0: return _int_tuple(0, 2, Q) U = 1 V = P Qk = Q b = _bitlength(k) if Q == 1: # Optimization for extra strong tests. while b > 1: U = (U*V) % n V = (V*V - 2) % n b -= 1 if (k >> (b - 1)) & 1: U, V = U*P + V, V*P + U*D if U & 1: U += n if V & 1: V += n U, V = U >> 1, V >> 1 elif P == 1 and Q == -1: # Small optimization for 50% of Selfridge parameters. while b > 1: U = (U*V) % n if Qk == 1: V = (V*V - 2) % n else: V = (V*V + 2) % n Qk = 1 b -= 1 if (k >> (b-1)) & 1: U, V = U + V, V + U*D if U & 1: U += n if V & 1: V += n U, V = U >> 1, V >> 1 Qk = -1 else: # The general case with any P and Q. while b > 1: U = (U*V) % n V = (V*V - 2*Qk) % n Qk *= Qk b -= 1 if (k >> (b - 1)) & 1: U, V = U*P + V, V*P + U*D if U & 1: U += n if V & 1: V += n U, V = U >> 1, V >> 1 Qk *= Q Qk %= n return _int_tuple(U % n, V % n, Qk) def _lucas_selfridge_params(n): """Calculates the Selfridge parameters (D, P, Q) for n. This is method A from page 1401 of Baillie and Wagstaff. References ========== - "Lucas Pseudoprimes", Baillie and Wagstaff, 1980. http://mpqs.free.fr/LucasPseudoprimes.pdf """ from sympy.core import igcd from sympy.ntheory.residue_ntheory import jacobi_symbol D = 5 while True: g = igcd(abs(D), n) if g > 1 and g != n: return (0, 0, 0) if jacobi_symbol(D, n) == -1: break if D > 0: D = -D - 2 else: D = -D + 2 return _int_tuple(D, 1, (1 - D)/4) def _lucas_extrastrong_params(n): """Calculates the "extra strong" parameters (D, P, Q) for n. References ========== - OEIS A217719: Extra Strong Lucas Pseudoprimes https://oeis.org/A217719 - https://en.wikipedia.org/wiki/Lucas_pseudoprime """ from sympy.core import igcd from sympy.ntheory.residue_ntheory import jacobi_symbol P, Q, D = 3, 1, 5 while True: g = igcd(D, n) if g > 1 and g != n: return (0, 0, 0) if jacobi_symbol(D, n) == -1: break P += 1 D = P*P - 4 return _int_tuple(D, P, Q) def is_lucas_prp(n): """Standard Lucas compositeness test with Selfridge parameters. Returns False if n is definitely composite, and True if n is a Lucas probable prime. This is typically used in combination with the Miller-Rabin test. References ========== - "Lucas Pseudoprimes", Baillie and Wagstaff, 1980. http://mpqs.free.fr/LucasPseudoprimes.pdf - OEIS A217120: Lucas Pseudoprimes https://oeis.org/A217120 - https://en.wikipedia.org/wiki/Lucas_pseudoprime Examples ======== >>> from sympy.ntheory.primetest import isprime, is_lucas_prp >>> for i in range(10000): ... if is_lucas_prp(i) and not isprime(i): ... print(i) 323 377 1159 1829 3827 5459 5777 9071 9179 """ n = as_int(n) if n == 2: return True if n < 2 or (n % 2) == 0: return False if is_square(n, False): return False D, P, Q = _lucas_selfridge_params(n) if D == 0: return False U, V, Qk = _lucas_sequence(n, P, Q, n+1) return U == 0 def is_strong_lucas_prp(n): """Strong Lucas compositeness test with Selfridge parameters. Returns False if n is definitely composite, and True if n is a strong Lucas probable prime. This is often used in combination with the Miller-Rabin test, and in particular, when combined with M-R base 2 creates the strong BPSW test. References ========== - "Lucas Pseudoprimes", Baillie and Wagstaff, 1980. http://mpqs.free.fr/LucasPseudoprimes.pdf - OEIS A217255: Strong Lucas Pseudoprimes https://oeis.org/A217255 - https://en.wikipedia.org/wiki/Lucas_pseudoprime - https://en.wikipedia.org/wiki/Baillie-PSW_primality_test Examples ======== >>> from sympy.ntheory.primetest import isprime, is_strong_lucas_prp >>> for i in range(20000): ... if is_strong_lucas_prp(i) and not isprime(i): ... print(i) 5459 5777 10877 16109 18971 """ from sympy.ntheory.factor_ import trailing n = as_int(n) if n == 2: return True if n < 2 or (n % 2) == 0: return False if is_square(n, False): return False D, P, Q = _lucas_selfridge_params(n) if D == 0: return False # remove powers of 2 from n+1 (= k * 2**s) s = trailing(n + 1) k = (n+1) >> s U, V, Qk = _lucas_sequence(n, P, Q, k) if U == 0 or V == 0: return True for r in range(1, s): V = (V*V - 2*Qk) % n if V == 0: return True Qk = pow(Qk, 2, n) return False def is_extra_strong_lucas_prp(n): """Extra Strong Lucas compositeness test. Returns False if n is definitely composite, and True if n is a "extra strong" Lucas probable prime. The parameters are selected using P = 3, Q = 1, then incrementing P until (D|n) == -1. The test itself is as defined in Grantham 2000, from the Mo and Jones preprint. The parameter selection and test are the same as used in OEIS A217719, Perl's Math::Prime::Util, and the Lucas pseudoprime page on Wikipedia. With these parameters, there are no counterexamples below 2^64 nor any known above that range. It is 20-50% faster than the strong test. Because of the different parameters selected, there is no relationship between the strong Lucas pseudoprimes and extra strong Lucas pseudoprimes. In particular, one is not a subset of the other. References ========== - "Frobenius Pseudoprimes", Jon Grantham, 2000. http://www.ams.org/journals/mcom/2001-70-234/S0025-5718-00-01197-2/ - OEIS A217719: Extra Strong Lucas Pseudoprimes https://oeis.org/A217719 - https://en.wikipedia.org/wiki/Lucas_pseudoprime Examples ======== >>> from sympy.ntheory.primetest import isprime, is_extra_strong_lucas_prp >>> for i in range(20000): ... if is_extra_strong_lucas_prp(i) and not isprime(i): ... print(i) 989 3239 5777 10877 """ # Implementation notes: # 1) the parameters differ from Thomas R. Nicely's. His parameter # selection leads to pseudoprimes that overlap M-R tests, and # contradict Baillie and Wagstaff's suggestion of (D|n) = -1. # 2) The MathWorld page as of June 2013 specifies Q=-1. The Lucas # sequence must have Q=1. See Grantham theorem 2.3, any of the # references on the MathWorld page, or run it and see Q=-1 is wrong. from sympy.ntheory.factor_ import trailing n = as_int(n) if n == 2: return True if n < 2 or (n % 2) == 0: return False if is_square(n, False): return False D, P, Q = _lucas_extrastrong_params(n) if D == 0: return False # remove powers of 2 from n+1 (= k * 2**s) s = trailing(n + 1) k = (n+1) >> s U, V, Qk = _lucas_sequence(n, P, Q, k) if U == 0 and (V == 2 or V == n - 2): return True for r in range(1, s): if V == 0: return True V = (V*V - 2) % n return False def isprime(n): """ Test if n is a prime number (True) or not (False). For n < 2^64 the answer is definitive; larger n values have a small probability of actually being pseudoprimes. Negative numbers (e.g. -2) are not considered prime. The first step is looking for trivial factors, which if found enables a quick return. Next, if the sieve is large enough, use bisection search on the sieve. For small numbers, a set of deterministic Miller-Rabin tests are performed with bases that are known to have no counterexamples in their range. Finally if the number is larger than 2^64, a strong BPSW test is performed. While this is a probable prime test and we believe counterexamples exist, there are no known counterexamples. Examples ======== >>> from sympy.ntheory import isprime >>> isprime(13) True >>> isprime(13.0) # limited precision False >>> isprime(15) False Notes ===== This routine is intended only for integer input, not numerical expressions which may represent numbers. Floats are also rejected as input because they represent numbers of limited precision. While it is tempting to permit 7.0 to represent an integer there are errors that may "pass silently" if this is allowed: >>> from sympy import Float, S >>> int(1e3) == 1e3 == 10**3 True >>> int(1e23) == 1e23 True >>> int(1e23) == 10**23 False >>> near_int = 1 + S(1)/10**19 >>> near_int == int(near_int) False >>> n = Float(near_int, 10) # truncated by precision >>> n == int(n) True >>> n = Float(near_int, 20) >>> n == int(n) False See Also ======== sympy.ntheory.generate.primerange : Generates all primes in a given range sympy.ntheory.generate.primepi : Return the number of primes less than or equal to n sympy.ntheory.generate.prime : Return the nth prime References ========== - https://en.wikipedia.org/wiki/Strong_pseudoprime - "Lucas Pseudoprimes", Baillie and Wagstaff, 1980. http://mpqs.free.fr/LucasPseudoprimes.pdf - https://en.wikipedia.org/wiki/Baillie-PSW_primality_test """ try: n = as_int(n) except ValueError: return False # Step 1, do quick composite testing via trial division. The individual # modulo tests benchmark faster than one or two primorial igcds for me. # The point here is just to speedily handle small numbers and many # composites. Step 2 only requires that n <= 2 get handled here. if n in [2, 3, 5]: return True if n < 2 or (n % 2) == 0 or (n % 3) == 0 or (n % 5) == 0: return False if n < 49: return True if (n % 7) == 0 or (n % 11) == 0 or (n % 13) == 0 or (n % 17) == 0 or \ (n % 19) == 0 or (n % 23) == 0 or (n % 29) == 0 or (n % 31) == 0 or \ (n % 37) == 0 or (n % 41) == 0 or (n % 43) == 0 or (n % 47) == 0: return False if n < 2809: return True if n <= 23001: return pow(2, n, n) == 2 and n not in [7957, 8321, 13747, 18721, 19951] # bisection search on the sieve if the sieve is large enough from sympy.ntheory.generate import sieve as s if n <= s._list[-1]: l, u = s.search(n) return l == u # If we have GMPY2, skip straight to step 3 and do a strong BPSW test. # This should be a bit faster than our step 2, and for large values will # be a lot faster than our step 3 (C+GMP vs. Python). from sympy.core.compatibility import HAS_GMPY if HAS_GMPY == 2: from gmpy2 import is_strong_prp, is_strong_selfridge_prp return is_strong_prp(n, 2) and is_strong_selfridge_prp(n) # Step 2: deterministic Miller-Rabin testing for numbers < 2^64. See: # https://miller-rabin.appspot.com/ # for lists. We have made sure the M-R routine will successfully handle # bases larger than n, so we can use the minimal set. if n < 341531: return mr(n, [9345883071009581737]) if n < 885594169: return mr(n, [725270293939359937, 3569819667048198375]) if n < 350269456337: return mr(n, [4230279247111683200, 14694767155120705706, 16641139526367750375]) if n < 55245642489451: return mr(n, [2, 141889084524735, 1199124725622454117, 11096072698276303650]) if n < 7999252175582851: return mr(n, [2, 4130806001517, 149795463772692060, 186635894390467037, 3967304179347715805]) if n < 585226005592931977: return mr(n, [2, 123635709730000, 9233062284813009, 43835965440333360, 761179012939631437, 1263739024124850375]) if n < 18446744073709551616: return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022]) # We could do this instead at any point: #if n < 18446744073709551616: # return mr(n, [2]) and is_extra_strong_lucas_prp(n) # Here are tests that are safe for MR routines that don't understand # large bases. #if n < 9080191: # return mr(n, [31, 73]) #if n < 19471033: # return mr(n, [2, 299417]) #if n < 38010307: # return mr(n, [2, 9332593]) #if n < 316349281: # return mr(n, [11000544, 31481107]) #if n < 4759123141: # return mr(n, [2, 7, 61]) #if n < 105936894253: # return mr(n, [2, 1005905886, 1340600841]) #if n < 31858317218647: # return mr(n, [2, 642735, 553174392, 3046413974]) #if n < 3071837692357849: # return mr(n, [2, 75088, 642735, 203659041, 3613982119]) #if n < 18446744073709551616: # return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022]) # Step 3: BPSW. # # Time for isprime(10**2000 + 4561), no gmpy or gmpy2 installed # 44.0s old isprime using 46 bases # 5.3s strong BPSW + one random base # 4.3s extra strong BPSW + one random base # 4.1s strong BPSW # 3.2s extra strong BPSW # Classic BPSW from page 1401 of the paper. See alternate ideas below. return mr(n, [2]) and is_strong_lucas_prp(n) # Using extra strong test, which is somewhat faster #return mr(n, [2]) and is_extra_strong_lucas_prp(n) # Add a random M-R base #import random #return mr(n, [2, random.randint(3, n-1)]) and is_strong_lucas_prp(n) def is_gaussian_prime(num): r"""Test if num is a Gaussian prime number. References ========== .. [1] https://oeis.org/wiki/Gaussian_primes """ from sympy import sympify num = sympify(num) a, b = num.as_real_imag() a = as_int(a, strict=False) b = as_int(b, strict=False) if a == 0: b = abs(b) return isprime(b) and b % 4 == 3 elif b == 0: a = abs(a) return isprime(a) and a % 4 == 3 return isprime(a**2 + b**2)
847fd80eed87b6c34d89a93707a4598439dff63b2e6472e696ec528423810ecb
from sympy.core.numbers import igcd, mod_inverse from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power from sympy.ntheory import isprime from math import log, sqrt import random rgen = random.Random() class SievePolynomial: def __init__(self, modified_coeff=(), a=None, b=None): """This class denotes the seive polynomial. If ``g(x) = (a*x + b)**2 - N``. `g(x)` can be expanded to ``a*x**2 + 2*a*b*x + b**2 - N``, so the coefficient is stored in the form `[a**2, 2*a*b, b**2 - N]`. This ensures faster `eval` method because we dont have to perform `a**2, 2*a*b, b**2` every time we call the `eval` method. As multiplication is more expensive than addition, by using modified_coefficient we get a faster seiving process. Parameters ========== modified_coeff : modified_coefficient of sieve polynomial a : parameter of the sieve polynomial b : parameter of the sieve polynomial """ self.modified_coeff = modified_coeff self.a = a self.b = b def eval(self, x): """ Compute the value of the sieve polynomial at point x. Parameters ========== x : Integer parameter for sieve polynomial """ ans = 0 for coeff in self.modified_coeff: ans *= x ans += coeff return ans class FactorBaseElem: """This class stores an element of the `factor_base`. """ def __init__(self, prime, tmem_p, log_p): """ Initialization of factor_base_elem. Parameters ========== prime : prime number of the factor_base tmem_p : Integer square root of x**2 = n mod prime log_p : Compute Natural Logarithm of the prime """ self.prime = prime self.tmem_p = tmem_p self.log_p = log_p self.soln1 = None self.soln2 = None self.a_inv = None self.b_ainv = None def _generate_factor_base(prime_bound, n): """Generate `factor_base` for Quadratic Sieve. The `factor_base` consists of all the the points whose ``legendre_symbol(n, p) == 1`` and ``p < num_primes``. Along with the prime `factor_base` also stores natural logarithm of prime and the residue n modulo p. It also returns the of primes numbers in the `factor_base` which are close to 1000 and 5000. Parameters ========== prime_bound : upper prime bound of the factor_base n : integer to be factored """ from sympy import sieve factor_base = [] idx_1000, idx_5000 = None, None for prime in sieve.primerange(1, prime_bound): if pow(n, (prime - 1) // 2, prime) == 1: if prime > 1000 and idx_1000 is None: idx_1000 = len(factor_base) - 1 if prime > 5000 and idx_5000 is None: idx_5000 = len(factor_base) - 1 residue = _sqrt_mod_prime_power(n, prime, 1)[0] log_p = round(log(prime)*2**10) factor_base.append(FactorBaseElem(prime, residue, log_p)) return idx_1000, idx_5000, factor_base def _initialize_first_polynomial(N, M, factor_base, idx_1000, idx_5000, seed=None): """This step is the initialization of the 1st sieve polynomial. Here `a` is selected as a product of several primes of the factor_base such that `a` is about to ``sqrt(2*N) / M``. Other initial values of factor_base elem are also intialized which includes a_inv, b_ainv, soln1, soln2 which are used when the sieve polynomial is changed. The b_ainv is required for fast polynomial change as we don't have to calculate `2*b*mod_inverse(a, prime)` every time. We also ensure that the `factor_base` primes which make `a` are between 1000 and 5000. Parameters ========== N : Number to be factored M : sieve interval factor_base : factor_base primes idx_1000 : index of prime numbe in the factor_base near 1000 idx_5000 : index of primenumber in the factor_base near to 5000 seed : Generate pseudoprime numbers """ if seed is not None: rgen.seed(seed) approx_val = sqrt(2*N) / M # `a` is a parameter of the sieve polynomial and `q` is the prime factors of `a` # randomly search for a combination of primes whose multiplication is close to approx_val # This multiplication of primes will be `a` and the primes will be `q` # `best_a` denotes that `a` is close to approx_val in the random search of combination best_a, best_q, best_ratio = None, None, None start = 0 if idx_1000 is None else idx_1000 end = len(factor_base) - 1 if idx_5000 is None else idx_5000 for _ in range(50): a = 1 q = [] while(a < approx_val): rand_p = 0 while(rand_p == 0 or rand_p in q): rand_p = rgen.randint(start, end) p = factor_base[rand_p].prime a *= p q.append(rand_p) ratio = a / approx_val if best_ratio is None or abs(ratio - 1) < abs(best_ratio - 1): best_q = q best_a = a best_ratio = ratio a = best_a q = best_q B = [] for idx, val in enumerate(q): q_l = factor_base[val].prime gamma = factor_base[val].tmem_p * mod_inverse(a // q_l, q_l) % q_l if gamma > q_l / 2: gamma = q_l - gamma B.append(a//q_l*gamma) b = sum(B) g = SievePolynomial([a*a, 2*a*b, b*b - N], a, b) for fb in factor_base: if a % fb.prime == 0: continue fb.a_inv = mod_inverse(a, fb.prime) fb.b_ainv = [2*b_elem*fb.a_inv % fb.prime for b_elem in B] fb.soln1 = (fb.a_inv*(fb.tmem_p - b)) % fb.prime fb.soln2 = (fb.a_inv*(-fb.tmem_p - b)) % fb.prime return g, B def _initialize_ith_poly(N, factor_base, i, g, B): """Initialization stage of ith poly. After we finish sieving 1`st polynomial here we quickly change to the next polynomial from which we will again start sieving. Suppose we generated ith sieve polynomial and now we want to generate (i + 1)th polynomial, where ``1 <= i <= 2**(j - 1) - 1`` where `j` is the number of prime factors of the coefficient `a` then this function can be used to go to the next polynomial. If ``i = 2**(j - 1) - 1`` then go to _initialize_first_polynomial stage. Parameters ========== N : number to be factored factor_base : factor_base primes i : integer denoting ith polynomial g : (i - 1)th polynomial B : array that stores a//q_l*gamma """ from sympy import ceiling v = 1 j = i while(j % 2 == 0): v += 1 j //= 2 if ceiling(i / (2**v)) % 2 == 1: neg_pow = -1 else: neg_pow = 1 b = g.b + 2*neg_pow*B[v - 1] a = g.a g = SievePolynomial([a*a, 2*a*b, b*b - N], a, b) for fb in factor_base: if a % fb.prime == 0: continue fb.soln1 = (fb.soln1 - neg_pow*fb.b_ainv[v - 1]) % fb.prime fb.soln2 = (fb.soln2 - neg_pow*fb.b_ainv[v - 1]) % fb.prime return g def _gen_sieve_array(M, factor_base): """Sieve Stage of the Quadratic Sieve. For every prime in the factor_base that doesn't divide the coefficient `a` we add log_p over the sieve_array such that ``-M <= soln1 + i*p <= M`` and ``-M <= soln2 + i*p <= M`` where `i` is an integer. When p = 2 then log_p is only added using ``-M <= soln1 + i*p <= M``. Parameters ========== M : sieve interval factor_base : factor_base primes """ sieve_array = [0]*(2*M + 1) for factor in factor_base: if factor.soln1 is None: #The prime does not divides a continue for idx in range((M + factor.soln1) % factor.prime, 2*M, factor.prime): sieve_array[idx] += factor.log_p if factor.prime == 2: continue #if prime is 2 then sieve only with soln_1_p for idx in range((M + factor.soln2) % factor.prime, 2*M, factor.prime): sieve_array[idx] += factor.log_p return sieve_array def _check_smoothness(num, factor_base): """Here we check that if `num` is a smooth number or not. If `a` is a smooth number then it returns a vector of prime exponents modulo 2. For example if a = 2 * 5**2 * 7**3 and the factor base contains {2, 3, 5, 7} then `a` is a smooth number and this function returns ([1, 0, 0, 1], True). If `a` is a partial relation which means that `a` a has one prime factor greater than the `factor_base` then it returns `(a, False)` which denotes `a` is a partial relation. Parameters ========== a : integer whose smootheness is to be checked factor_base : factor_base primes """ vec = [] if num < 0: vec.append(1) num *= -1 else: vec.append(0) #-1 is not included in factor_base add -1 in vector for factor in factor_base: if num % factor.prime != 0: vec.append(0) continue factor_exp = 0 while num % factor.prime == 0: factor_exp += 1 num //= factor.prime vec.append(factor_exp % 2) if num == 1: return vec, True if isprime(num): return num, False return None, None def _trial_division_stage(N, M, factor_base, sieve_array, sieve_poly, partial_relations, ERROR_TERM): """Trial division stage. Here we trial divide the values generetated by sieve_poly in the sieve interval and if it is a smooth number then it is stored in `smooth_relations`. Moreover, if we find two partial relations with same large prime then they are combined to form a smooth relation. First we iterate over sieve array and look for values which are greater than accumulated_val, as these values have a high chance of being smooth number. Then using these values we find smooth relations. In general, let ``t**2 = u*p modN`` and ``r**2 = v*p modN`` be two partial relations with the same large prime p. Then they can be combined ``(t*r/p)**2 = u*v modN`` to form a smooth relation. Parameters ========== N : Number to be factored M : sieve interval factor_base : factor_base primes sieve_array : stores log_p values sieve_poly : polynomial from which we find smooth relations partial_relations : stores partial relations with one large prime ERROR_TERM : error term for accumulated_val """ sqrt_n = sqrt(float(N)) accumulated_val = log(M * sqrt_n)*2**10 - ERROR_TERM smooth_relations = [] proper_factor = set() partial_relation_upper_bound = 128*factor_base[-1].prime for idx, val in enumerate(sieve_array): if val < accumulated_val: continue x = idx - M v = sieve_poly.eval(x) vec, is_smooth = _check_smoothness(v, factor_base) if is_smooth is None:#Neither smooth nor partial continue u = sieve_poly.a*x + sieve_poly.b # Update the partial relation # If 2 partial relation with same large prime is found then generate smooth relation if is_smooth is False:#partial relation found large_prime = vec #Consider the large_primes under 128*F if large_prime > partial_relation_upper_bound: continue if large_prime not in partial_relations: partial_relations[large_prime] = (u, v) continue else: u_prev, v_prev = partial_relations[large_prime] partial_relations.pop(large_prime) try: large_prime_inv = mod_inverse(large_prime, N) except ValueError:#if large_prine divides N proper_factor.add(large_prime) continue u = u*u_prev*large_prime_inv v = v*v_prev // (large_prime*large_prime) vec, is_smooth = _check_smoothness(v, factor_base) #assert u*u % N == v % N smooth_relations.append((u, v, vec)) return smooth_relations, proper_factor #LINEAR ALGEBRA STAGE def _build_matrix(smooth_relations): """Build a 2D matrix from smooth relations. Parameters ========== smooth_relations : Stores smooth relations """ matrix = [] for s_relation in smooth_relations: matrix.append(s_relation[2]) return matrix def _gauss_mod_2(A): """Fast gaussian reduction for modulo 2 matrix. Parameters ========== A : Matrix Examples ======== >>> from sympy.ntheory.qs import _gauss_mod_2 >>> _gauss_mod_2([[0, 1, 1], [1, 0, 1], [0, 1, 0], [1, 1, 1]]) ([[[1, 0, 1], 3]], [True, True, True, False], [[0, 1, 0], [1, 0, 0], [0, 0, 1], [1, 0, 1]]) Reference ========== .. [1] A fast algorithm for gaussian elimination over GF(2) and its implementation on the GAPP. Cetin K.Koc, Sarath N.Arachchige""" import copy matrix = copy.deepcopy(A) row = len(matrix) col = len(matrix[0]) mark = [False]*row for c in range(col): for r in range(row): if matrix[r][c] == 1: break mark[r] = True for c1 in range(col): if c1 == c: continue if matrix[r][c1] == 1: for r2 in range(row): matrix[r2][c1] = (matrix[r2][c1] + matrix[r2][c]) % 2 dependent_row = [] for idx, val in enumerate(mark): if val == False: dependent_row.append([matrix[idx], idx]) return dependent_row, mark, matrix def _find_factor(dependent_rows, mark, gauss_matrix, index, smooth_relations, N): """Finds proper factor of N. Here, transform the dependent rows as a combination of independent rows of the gauss_matrix to form the desired relation of the form ``X**2 = Y**2 modN``. After obtaining the desired relation we obtain a proper factor of N by `gcd(X - Y, N)`. Parameters ========== dependent_rows : denoted dependent rows in the reduced matrix form mark : boolean array to denoted dependent and independent rows gauss_matrix : Reduced form of the smooth relations matrix index : denoted the index of the dependent_rows smooth_relations : Smooth relations vectors matrix N : Number to be factored """ from sympy import integer_nthroot idx_in_smooth = dependent_rows[index][1] independent_u = [smooth_relations[idx_in_smooth][0]] independent_v = [smooth_relations[idx_in_smooth][1]] dept_row = dependent_rows[index][0] for idx, val in enumerate(dept_row): if val == 1: for row in range(len(gauss_matrix)): if gauss_matrix[row][idx] == 1 and mark[row] == True: independent_u.append(smooth_relations[row][0]) independent_v.append(smooth_relations[row][1]) break u = 1 v = 1 for i in independent_u: u *= i for i in independent_v: v *= i #assert u**2 % N == v % N v = integer_nthroot(v, 2)[0] return igcd(u - v, N) def qs(N, prime_bound, M, ERROR_TERM=25, seed=1234): """Performs factorization using Self-Initializing Quadratic Sieve. In SIQS, let N be a number to be factored, and this N should not be a perfect power. If we find two integers such that ``X**2 = Y**2 modN`` and ``X != +-Y modN``, then `gcd(X + Y, N)` will reveal a proper factor of N. In order to find these integers X and Y we try to find relations of form t**2 = u modN where u is a product of small primes. If we have enough of these relations then we can form ``(t1*t2...ti)**2 = u1*u2...ui modN`` such that the right hand side is a square, thus we found a relation of ``X**2 = Y**2 modN``. Here, several optimizations are done like using muliple polynomials for sieving, fast changing between polynomials and using partial relations. The use of partial relations can speeds up the factoring by 2 times. Parameters ========== N : Number to be Factored prime_bound : upper bound for primes in the factor base M : Sieve Interval ERROR_TERM : Error term for checking smoothness threshold : Extra smooth relations for factorization seed : generate pseudo prime numbers Examples ======== >>> from sympy.ntheory import qs >>> qs(25645121643901801, 2000, 10000) {5394769, 4753701529} >>> qs(9804659461513846513, 2000, 10000) {4641991, 2112166839943} References ========== .. [1] https://pdfs.semanticscholar.org/5c52/8a975c1405bd35c65993abf5a4edb667c1db.pdf .. [2] https://www.rieselprime.de/ziki/Self-initializing_quadratic_sieve """ ERROR_TERM*=2**10 rgen.seed(seed) idx_1000, idx_5000, factor_base = _generate_factor_base(prime_bound, N) smooth_relations = [] ith_poly = 0 partial_relations = {} proper_factor = set() threshold = 5*len(factor_base) // 100 while True: if ith_poly == 0: ith_sieve_poly, B_array = _initialize_first_polynomial(N, M, factor_base, idx_1000, idx_5000) else: ith_sieve_poly = _initialize_ith_poly(N, factor_base, ith_poly, ith_sieve_poly, B_array) ith_poly += 1 if ith_poly >= 2**(len(B_array) - 1): # time to start with a new sieve polynomial ith_poly = 0 sieve_array = _gen_sieve_array(M, factor_base) s_rel, p_f = _trial_division_stage(N, M, factor_base, sieve_array, ith_sieve_poly, partial_relations, ERROR_TERM) smooth_relations += s_rel proper_factor |= p_f if len(smooth_relations) >= len(factor_base) + threshold: break matrix = _build_matrix(smooth_relations) dependent_row, mark, gauss_matrix = _gauss_mod_2(matrix) N_copy = N for index in range(len(dependent_row)): factor = _find_factor(dependent_row, mark, gauss_matrix, index, smooth_relations, N) if factor > 1 and factor < N: proper_factor.add(factor) while(N_copy % factor == 0): N_copy //= factor if isprime(N_copy): proper_factor.add(N_copy) break if(N_copy == 1): break return proper_factor
8063127e3cdbbdcd0c8a31dcf37c332f40874ad4488c2680f977f6942ea0aa26
from random import randrange, choice from math import log from sympy.ntheory import primefactors from sympy import multiplicity, factorint, Symbol from sympy.combinatorics import Permutation from sympy.combinatorics.permutations import (_af_commutes_with, _af_invert, _af_rmul, _af_rmuln, _af_pow, Cycle) from sympy.combinatorics.util import (_check_cycles_alt_sym, _distribute_gens_by_base, _orbits_transversals_from_bsgs, _handle_precomputed_bsgs, _base_ordering, _strong_gens_from_distr, _strip, _strip_af) from sympy.core import Basic from sympy.functions.combinatorial.factorials import factorial from sympy.ntheory import sieve from sympy.utilities.iterables import has_variety, is_sequence, uniq from sympy.testing.randtest import _randrange from itertools import islice from sympy.core.sympify import _sympify rmul = Permutation.rmul_with_af _af_new = Permutation._af_new class PermutationGroup(Basic): """The class defining a Permutation group. Explanation =========== PermutationGroup([p1, p2, ..., pn]) returns the permutation group generated by the list of permutations. This group can be supplied to Polyhedron if one desires to decorate the elements to which the indices of the permutation refer. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.polyhedron import Polyhedron >>> from sympy.combinatorics.perm_groups import PermutationGroup The permutations corresponding to motion of the front, right and bottom face of a 2x2 Rubik's cube are defined: >>> F = Permutation(2, 19, 21, 8)(3, 17, 20, 10)(4, 6, 7, 5) >>> R = Permutation(1, 5, 21, 14)(3, 7, 23, 12)(8, 10, 11, 9) >>> D = Permutation(6, 18, 14, 10)(7, 19, 15, 11)(20, 22, 23, 21) These are passed as permutations to PermutationGroup: >>> G = PermutationGroup(F, R, D) >>> G.order() 3674160 The group can be supplied to a Polyhedron in order to track the objects being moved. An example involving the 2x2 Rubik's cube is given there, but here is a simple demonstration: >>> a = Permutation(2, 1) >>> b = Permutation(1, 0) >>> G = PermutationGroup(a, b) >>> P = Polyhedron(list('ABC'), pgroup=G) >>> P.corners (A, B, C) >>> P.rotate(0) # apply permutation 0 >>> P.corners (A, C, B) >>> P.reset() >>> P.corners (A, B, C) Or one can make a permutation as a product of selected permutations and apply them to an iterable directly: >>> P10 = G.make_perm([0, 1]) >>> P10('ABC') ['C', 'A', 'B'] See Also ======== sympy.combinatorics.polyhedron.Polyhedron, sympy.combinatorics.permutations.Permutation References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" .. [2] Seress, A. "Permutation Group Algorithms" .. [3] https://en.wikipedia.org/wiki/Schreier_vector .. [4] https://en.wikipedia.org/wiki/Nielsen_transformation#Product_replacement_algorithm .. [5] Frank Celler, Charles R.Leedham-Green, Scott H.Murray, Alice C.Niemeyer, and E.A.O'Brien. "Generating Random Elements of a Finite Group" .. [6] https://en.wikipedia.org/wiki/Block_%28permutation_group_theory%29 .. [7] http://www.algorithmist.com/index.php/Union_Find .. [8] https://en.wikipedia.org/wiki/Multiply_transitive_group#Multiply_transitive_groups .. [9] https://en.wikipedia.org/wiki/Center_%28group_theory%29 .. [10] https://en.wikipedia.org/wiki/Centralizer_and_normalizer .. [11] http://groupprops.subwiki.org/wiki/Derived_subgroup .. [12] https://en.wikipedia.org/wiki/Nilpotent_group .. [13] http://www.math.colostate.edu/~hulpke/CGT/cgtnotes.pdf .. [14] https://www.gap-system.org/Manuals/doc/ref/manual.pdf """ is_group = True def __new__(cls, *args, dups=True, **kwargs): """The default constructor. Accepts Cycle and Permutation forms. Removes duplicates unless ``dups`` keyword is ``False``. """ if not args: args = [Permutation()] else: args = list(args[0] if is_sequence(args[0]) else args) if not args: args = [Permutation()] if any(isinstance(a, Cycle) for a in args): args = [Permutation(a) for a in args] if has_variety(a.size for a in args): degree = kwargs.pop('degree', None) if degree is None: degree = max(a.size for a in args) for i in range(len(args)): if args[i].size != degree: args[i] = Permutation(args[i], size=degree) if dups: args = list(uniq([_af_new(list(a)) for a in args])) if len(args) > 1: args = [g for g in args if not g.is_identity] obj = Basic.__new__(cls, *args, **kwargs) obj._generators = args obj._order = None obj._center = [] obj._is_abelian = None obj._is_transitive = None obj._is_sym = None obj._is_alt = None obj._is_primitive = None obj._is_nilpotent = None obj._is_solvable = None obj._is_trivial = None obj._transitivity_degree = None obj._max_div = None obj._is_perfect = None obj._is_cyclic = None obj._r = len(obj._generators) obj._degree = obj._generators[0].size # these attributes are assigned after running schreier_sims obj._base = [] obj._strong_gens = [] obj._strong_gens_slp = [] obj._basic_orbits = [] obj._transversals = [] obj._transversal_slp = [] # these attributes are assigned after running _random_pr_init obj._random_gens = [] # finite presentation of the group as an instance of `FpGroup` obj._fp_presentation = None return obj def __getitem__(self, i): return self._generators[i] def __contains__(self, i): """Return ``True`` if *i* is contained in PermutationGroup. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> p = Permutation(1, 2, 3) >>> Permutation(3) in PermutationGroup(p) True """ if not isinstance(i, Permutation): raise TypeError("A PermutationGroup contains only Permutations as " "elements, not elements of type %s" % type(i)) return self.contains(i) def __len__(self): return len(self._generators) def __eq__(self, other): """Return ``True`` if PermutationGroup generated by elements in the group are same i.e they represent the same PermutationGroup. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> p = Permutation(0, 1, 2, 3, 4, 5) >>> G = PermutationGroup([p, p**2]) >>> H = PermutationGroup([p**2, p]) >>> G.generators == H.generators False >>> G == H True """ if not isinstance(other, PermutationGroup): return False set_self_gens = set(self.generators) set_other_gens = set(other.generators) # before reaching the general case there are also certain # optimisation and obvious cases requiring less or no actual # computation. if set_self_gens == set_other_gens: return True # in the most general case it will check that each generator of # one group belongs to the other PermutationGroup and vice-versa for gen1 in set_self_gens: if not other.contains(gen1): return False for gen2 in set_other_gens: if not self.contains(gen2): return False return True def __hash__(self): return super().__hash__() def __mul__(self, other): """ Return the direct product of two permutation groups as a permutation group. Explanation =========== This implementation realizes the direct product by shifting the index set for the generators of the second group: so if we have ``G`` acting on ``n1`` points and ``H`` acting on ``n2`` points, ``G*H`` acts on ``n1 + n2`` points. Examples ======== >>> from sympy.combinatorics.named_groups import CyclicGroup >>> G = CyclicGroup(5) >>> H = G*G >>> H PermutationGroup([ (9)(0 1 2 3 4), (5 6 7 8 9)]) >>> H.order() 25 """ if isinstance(other, Permutation): return Coset(other, self, dir='+') gens1 = [perm._array_form for perm in self.generators] gens2 = [perm._array_form for perm in other.generators] n1 = self._degree n2 = other._degree start = list(range(n1)) end = list(range(n1, n1 + n2)) for i in range(len(gens2)): gens2[i] = [x + n1 for x in gens2[i]] gens2 = [start + gen for gen in gens2] gens1 = [gen + end for gen in gens1] together = gens1 + gens2 gens = [_af_new(x) for x in together] return PermutationGroup(gens) def _random_pr_init(self, r, n, _random_prec_n=None): r"""Initialize random generators for the product replacement algorithm. Explanation =========== The implementation uses a modification of the original product replacement algorithm due to Leedham-Green, as described in [1], pp. 69-71; also, see [2], pp. 27-29 for a detailed theoretical analysis of the original product replacement algorithm, and [4]. The product replacement algorithm is used for producing random, uniformly distributed elements of a group `G` with a set of generators `S`. For the initialization ``_random_pr_init``, a list ``R`` of `\max\{r, |S|\}` group generators is created as the attribute ``G._random_gens``, repeating elements of `S` if necessary, and the identity element of `G` is appended to ``R`` - we shall refer to this last element as the accumulator. Then the function ``random_pr()`` is called ``n`` times, randomizing the list ``R`` while preserving the generation of `G` by ``R``. The function ``random_pr()`` itself takes two random elements ``g, h`` among all elements of ``R`` but the accumulator and replaces ``g`` with a randomly chosen element from `\{gh, g(~h), hg, (~h)g\}`. Then the accumulator is multiplied by whatever ``g`` was replaced by. The new value of the accumulator is then returned by ``random_pr()``. The elements returned will eventually (for ``n`` large enough) become uniformly distributed across `G` ([5]). For practical purposes however, the values ``n = 50, r = 11`` are suggested in [1]. Notes ===== THIS FUNCTION HAS SIDE EFFECTS: it changes the attribute self._random_gens See Also ======== random_pr """ deg = self.degree random_gens = [x._array_form for x in self.generators] k = len(random_gens) if k < r: for i in range(k, r): random_gens.append(random_gens[i - k]) acc = list(range(deg)) random_gens.append(acc) self._random_gens = random_gens # handle randomized input for testing purposes if _random_prec_n is None: for i in range(n): self.random_pr() else: for i in range(n): self.random_pr(_random_prec=_random_prec_n[i]) def _union_find_merge(self, first, second, ranks, parents, not_rep): """Merges two classes in a union-find data structure. Explanation =========== Used in the implementation of Atkinson's algorithm as suggested in [1], pp. 83-87. The class merging process uses union by rank as an optimization. ([7]) Notes ===== THIS FUNCTION HAS SIDE EFFECTS: the list of class representatives, ``parents``, the list of class sizes, ``ranks``, and the list of elements that are not representatives, ``not_rep``, are changed due to class merging. See Also ======== minimal_block, _union_find_rep References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory" .. [7] http://www.algorithmist.com/index.php/Union_Find """ rep_first = self._union_find_rep(first, parents) rep_second = self._union_find_rep(second, parents) if rep_first != rep_second: # union by rank if ranks[rep_first] >= ranks[rep_second]: new_1, new_2 = rep_first, rep_second else: new_1, new_2 = rep_second, rep_first total_rank = ranks[new_1] + ranks[new_2] if total_rank > self.max_div: return -1 parents[new_2] = new_1 ranks[new_1] = total_rank not_rep.append(new_2) return 1 return 0 def _union_find_rep(self, num, parents): """Find representative of a class in a union-find data structure. Explanation =========== Used in the implementation of Atkinson's algorithm as suggested in [1], pp. 83-87. After the representative of the class to which ``num`` belongs is found, path compression is performed as an optimization ([7]). Notes ===== THIS FUNCTION HAS SIDE EFFECTS: the list of class representatives, ``parents``, is altered due to path compression. See Also ======== minimal_block, _union_find_merge References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory" .. [7] http://www.algorithmist.com/index.php/Union_Find """ rep, parent = num, parents[num] while parent != rep: rep = parent parent = parents[rep] # path compression temp, parent = num, parents[num] while parent != rep: parents[temp] = rep temp = parent parent = parents[temp] return rep @property def base(self): """Return a base from the Schreier-Sims algorithm. Explanation =========== For a permutation group `G`, a base is a sequence of points `B = (b_1, b_2, ..., b_k)` such that no element of `G` apart from the identity fixes all the points in `B`. The concepts of a base and strong generating set and their applications are discussed in depth in [1], pp. 87-89 and [2], pp. 55-57. An alternative way to think of `B` is that it gives the indices of the stabilizer cosets that contain more than the identity permutation. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> G = PermutationGroup([Permutation(0, 1, 3)(2, 4)]) >>> G.base [0, 2] See Also ======== strong_gens, basic_transversals, basic_orbits, basic_stabilizers """ if self._base == []: self.schreier_sims() return self._base def baseswap(self, base, strong_gens, pos, randomized=False, transversals=None, basic_orbits=None, strong_gens_distr=None): r"""Swap two consecutive base points in base and strong generating set. Explanation =========== If a base for a group `G` is given by `(b_1, b_2, ..., b_k)`, this function returns a base `(b_1, b_2, ..., b_{i+1}, b_i, ..., b_k)`, where `i` is given by ``pos``, and a strong generating set relative to that base. The original base and strong generating set are not modified. The randomized version (default) is of Las Vegas type. Parameters ========== base, strong_gens The base and strong generating set. pos The position at which swapping is performed. randomized A switch between randomized and deterministic version. transversals The transversals for the basic orbits, if known. basic_orbits The basic orbits, if known. strong_gens_distr The strong generators distributed by basic stabilizers, if known. Returns ======= (base, strong_gens) ``base`` is the new base, and ``strong_gens`` is a generating set relative to it. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.testutil import _verify_bsgs >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> S = SymmetricGroup(4) >>> S.schreier_sims() >>> S.base [0, 1, 2] >>> base, gens = S.baseswap(S.base, S.strong_gens, 1, randomized=False) >>> base, gens ([0, 2, 1], [(0 1 2 3), (3)(0 1), (1 3 2), (2 3), (1 3)]) check that base, gens is a BSGS >>> S1 = PermutationGroup(gens) >>> _verify_bsgs(S1, base, gens) True See Also ======== schreier_sims Notes ===== The deterministic version of the algorithm is discussed in [1], pp. 102-103; the randomized version is discussed in [1], p.103, and [2], p.98. It is of Las Vegas type. Notice that [1] contains a mistake in the pseudocode and discussion of BASESWAP: on line 3 of the pseudocode, `|\beta_{i+1}^{\left\langle T\right\rangle}|` should be replaced by `|\beta_{i}^{\left\langle T\right\rangle}|`, and the same for the discussion of the algorithm. """ # construct the basic orbits, generators for the stabilizer chain # and transversal elements from whatever was provided transversals, basic_orbits, strong_gens_distr = \ _handle_precomputed_bsgs(base, strong_gens, transversals, basic_orbits, strong_gens_distr) base_len = len(base) degree = self.degree # size of orbit of base[pos] under the stabilizer we seek to insert # in the stabilizer chain at position pos + 1 size = len(basic_orbits[pos])*len(basic_orbits[pos + 1]) \ //len(_orbit(degree, strong_gens_distr[pos], base[pos + 1])) # initialize the wanted stabilizer by a subgroup if pos + 2 > base_len - 1: T = [] else: T = strong_gens_distr[pos + 2][:] # randomized version if randomized is True: stab_pos = PermutationGroup(strong_gens_distr[pos]) schreier_vector = stab_pos.schreier_vector(base[pos + 1]) # add random elements of the stabilizer until they generate it while len(_orbit(degree, T, base[pos])) != size: new = stab_pos.random_stab(base[pos + 1], schreier_vector=schreier_vector) T.append(new) # deterministic version else: Gamma = set(basic_orbits[pos]) Gamma.remove(base[pos]) if base[pos + 1] in Gamma: Gamma.remove(base[pos + 1]) # add elements of the stabilizer until they generate it by # ruling out member of the basic orbit of base[pos] along the way while len(_orbit(degree, T, base[pos])) != size: gamma = next(iter(Gamma)) x = transversals[pos][gamma] temp = x._array_form.index(base[pos + 1]) # (~x)(base[pos + 1]) if temp not in basic_orbits[pos + 1]: Gamma = Gamma - _orbit(degree, T, gamma) else: y = transversals[pos + 1][temp] el = rmul(x, y) if el(base[pos]) not in _orbit(degree, T, base[pos]): T.append(el) Gamma = Gamma - _orbit(degree, T, base[pos]) # build the new base and strong generating set strong_gens_new_distr = strong_gens_distr[:] strong_gens_new_distr[pos + 1] = T base_new = base[:] base_new[pos], base_new[pos + 1] = base_new[pos + 1], base_new[pos] strong_gens_new = _strong_gens_from_distr(strong_gens_new_distr) for gen in T: if gen not in strong_gens_new: strong_gens_new.append(gen) return base_new, strong_gens_new @property def basic_orbits(self): """ Return the basic orbits relative to a base and strong generating set. Explanation =========== If `(b_1, b_2, ..., b_k)` is a base for a group `G`, and `G^{(i)} = G_{b_1, b_2, ..., b_{i-1}}` is the ``i``-th basic stabilizer (so that `G^{(1)} = G`), the ``i``-th basic orbit relative to this base is the orbit of `b_i` under `G^{(i)}`. See [1], pp. 87-89 for more information. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(4) >>> S.basic_orbits [[0, 1, 2, 3], [1, 2, 3], [2, 3]] See Also ======== base, strong_gens, basic_transversals, basic_stabilizers """ if self._basic_orbits == []: self.schreier_sims() return self._basic_orbits @property def basic_stabilizers(self): """ Return a chain of stabilizers relative to a base and strong generating set. Explanation =========== The ``i``-th basic stabilizer `G^{(i)}` relative to a base `(b_1, b_2, ..., b_k)` is `G_{b_1, b_2, ..., b_{i-1}}`. For more information, see [1], pp. 87-89. Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> A = AlternatingGroup(4) >>> A.schreier_sims() >>> A.base [0, 1] >>> for g in A.basic_stabilizers: ... print(g) ... PermutationGroup([ (3)(0 1 2), (1 2 3)]) PermutationGroup([ (1 2 3)]) See Also ======== base, strong_gens, basic_orbits, basic_transversals """ if self._transversals == []: self.schreier_sims() strong_gens = self._strong_gens base = self._base if not base: # e.g. if self is trivial return [] strong_gens_distr = _distribute_gens_by_base(base, strong_gens) basic_stabilizers = [] for gens in strong_gens_distr: basic_stabilizers.append(PermutationGroup(gens)) return basic_stabilizers @property def basic_transversals(self): """ Return basic transversals relative to a base and strong generating set. Explanation =========== The basic transversals are transversals of the basic orbits. They are provided as a list of dictionaries, each dictionary having keys - the elements of one of the basic orbits, and values - the corresponding transversal elements. See [1], pp. 87-89 for more information. Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> A = AlternatingGroup(4) >>> A.basic_transversals [{0: (3), 1: (3)(0 1 2), 2: (3)(0 2 1), 3: (0 3 1)}, {1: (3), 2: (1 2 3), 3: (1 3 2)}] See Also ======== strong_gens, base, basic_orbits, basic_stabilizers """ if self._transversals == []: self.schreier_sims() return self._transversals def composition_series(self): r""" Return the composition series for a group as a list of permutation groups. Explanation =========== The composition series for a group `G` is defined as a subnormal series `G = H_0 > H_1 > H_2 \ldots` A composition series is a subnormal series such that each factor group `H(i+1) / H(i)` is simple. A subnormal series is a composition series only if it is of maximum length. The algorithm works as follows: Starting with the derived series the idea is to fill the gap between `G = der[i]` and `H = der[i+1]` for each `i` independently. Since, all subgroups of the abelian group `G/H` are normal so, first step is to take the generators `g` of `G` and add them to generators of `H` one by one. The factor groups formed are not simple in general. Each group is obtained from the previous one by adding one generator `g`, if the previous group is denoted by `H` then the next group `K` is generated by `g` and `H`. The factor group `K/H` is cyclic and it's order is `K.order()//G.order()`. The series is then extended between `K` and `H` by groups generated by powers of `g` and `H`. The series formed is then prepended to the already existing series. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.named_groups import CyclicGroup >>> S = SymmetricGroup(12) >>> G = S.sylow_subgroup(2) >>> C = G.composition_series() >>> [H.order() for H in C] [1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1] >>> G = S.sylow_subgroup(3) >>> C = G.composition_series() >>> [H.order() for H in C] [243, 81, 27, 9, 3, 1] >>> G = CyclicGroup(12) >>> C = G.composition_series() >>> [H.order() for H in C] [12, 6, 3, 1] """ der = self.derived_series() if not all(g.is_identity for g in der[-1].generators): raise NotImplementedError('Group should be solvable') series = [] for i in range(len(der)-1): H = der[i+1] up_seg = [] for g in der[i].generators: K = PermutationGroup([g] + H.generators) order = K.order() // H.order() down_seg = [] for p, e in factorint(order).items(): for j in range(e): down_seg.append(PermutationGroup([g] + H.generators)) g = g**p up_seg = down_seg + up_seg H = K up_seg[0] = der[i] series.extend(up_seg) series.append(der[-1]) return series def coset_transversal(self, H): """Return a transversal of the right cosets of self by its subgroup H using the second method described in [1], Subsection 4.6.7 """ if not H.is_subgroup(self): raise ValueError("The argument must be a subgroup") if H.order() == 1: return self._elements self._schreier_sims(base=H.base) # make G.base an extension of H.base base = self.base base_ordering = _base_ordering(base, self.degree) identity = Permutation(self.degree - 1) transversals = self.basic_transversals[:] # transversals is a list of dictionaries. Get rid of the keys # so that it is a list of lists and sort each list in # the increasing order of base[l]^x for l, t in enumerate(transversals): transversals[l] = sorted(t.values(), key = lambda x: base_ordering[base[l]^x]) orbits = H.basic_orbits h_stabs = H.basic_stabilizers g_stabs = self.basic_stabilizers indices = [x.order()//y.order() for x, y in zip(g_stabs, h_stabs)] # T^(l) should be a right transversal of H^(l) in G^(l) for # 1<=l<=len(base). While H^(l) is the trivial group, T^(l) # contains all the elements of G^(l) so we might just as well # start with l = len(h_stabs)-1 if len(g_stabs) > len(h_stabs): T = g_stabs[len(h_stabs)]._elements else: T = [identity] l = len(h_stabs)-1 t_len = len(T) while l > -1: T_next = [] for u in transversals[l]: if u == identity: continue b = base_ordering[base[l]^u] for t in T: p = t*u if all(base_ordering[h^p] >= b for h in orbits[l]): T_next.append(p) if t_len + len(T_next) == indices[l]: break if t_len + len(T_next) == indices[l]: break T += T_next t_len += len(T_next) l -= 1 T.remove(identity) T = [identity] + T return T def _coset_representative(self, g, H): """Return the representative of Hg from the transversal that would be computed by ``self.coset_transversal(H)``. """ if H.order() == 1: return g # The base of self must be an extension of H.base. if not(self.base[:len(H.base)] == H.base): self._schreier_sims(base=H.base) orbits = H.basic_orbits[:] h_transversals = [list(_.values()) for _ in H.basic_transversals] transversals = [list(_.values()) for _ in self.basic_transversals] base = self.base base_ordering = _base_ordering(base, self.degree) def step(l, x): gamma = sorted(orbits[l], key = lambda y: base_ordering[y^x])[0] i = [base[l]^h for h in h_transversals[l]].index(gamma) x = h_transversals[l][i]*x if l < len(orbits)-1: for u in transversals[l]: if base[l]^u == base[l]^x: break x = step(l+1, x*u**-1)*u return x return step(0, g) def coset_table(self, H): """Return the standardised (right) coset table of self in H as a list of lists. """ # Maybe this should be made to return an instance of CosetTable # from fp_groups.py but the class would need to be changed first # to be compatible with PermutationGroups from itertools import chain, product if not H.is_subgroup(self): raise ValueError("The argument must be a subgroup") T = self.coset_transversal(H) n = len(T) A = list(chain.from_iterable((gen, gen**-1) for gen in self.generators)) table = [] for i in range(n): row = [self._coset_representative(T[i]*x, H) for x in A] row = [T.index(r) for r in row] table.append(row) # standardize (this is the same as the algorithm used in coset_table) # If CosetTable is made compatible with PermutationGroups, this # should be replaced by table.standardize() A = range(len(A)) gamma = 1 for alpha, a in product(range(n), A): beta = table[alpha][a] if beta >= gamma: if beta > gamma: for x in A: z = table[gamma][x] table[gamma][x] = table[beta][x] table[beta][x] = z for i in range(n): if table[i][x] == beta: table[i][x] = gamma elif table[i][x] == gamma: table[i][x] = beta gamma += 1 if gamma >= n-1: return table def center(self): r""" Return the center of a permutation group. Explanation =========== The center for a group `G` is defined as `Z(G) = \{z\in G | \forall g\in G, zg = gz \}`, the set of elements of `G` that commute with all elements of `G`. It is equal to the centralizer of `G` inside `G`, and is naturally a subgroup of `G` ([9]). Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(4) >>> G = D.center() >>> G.order() 2 See Also ======== centralizer Notes ===== This is a naive implementation that is a straightforward application of ``.centralizer()`` """ return self.centralizer(self) def centralizer(self, other): r""" Return the centralizer of a group/set/element. Explanation =========== The centralizer of a set of permutations ``S`` inside a group ``G`` is the set of elements of ``G`` that commute with all elements of ``S``:: `C_G(S) = \{ g \in G | gs = sg \forall s \in S\}` ([10]) Usually, ``S`` is a subset of ``G``, but if ``G`` is a proper subgroup of the full symmetric group, we allow for ``S`` to have elements outside ``G``. It is naturally a subgroup of ``G``; the centralizer of a permutation group is equal to the centralizer of any set of generators for that group, since any element commuting with the generators commutes with any product of the generators. Parameters ========== other a permutation group/list of permutations/single permutation Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... CyclicGroup) >>> S = SymmetricGroup(6) >>> C = CyclicGroup(6) >>> H = S.centralizer(C) >>> H.is_subgroup(C) True See Also ======== subgroup_search Notes ===== The implementation is an application of ``.subgroup_search()`` with tests using a specific base for the group ``G``. """ if hasattr(other, 'generators'): if other.is_trivial or self.is_trivial: return self degree = self.degree identity = _af_new(list(range(degree))) orbits = other.orbits() num_orbits = len(orbits) orbits.sort(key=lambda x: -len(x)) long_base = [] orbit_reps = [None]*num_orbits orbit_reps_indices = [None]*num_orbits orbit_descr = [None]*degree for i in range(num_orbits): orbit = list(orbits[i]) orbit_reps[i] = orbit[0] orbit_reps_indices[i] = len(long_base) for point in orbit: orbit_descr[point] = i long_base = long_base + orbit base, strong_gens = self.schreier_sims_incremental(base=long_base) strong_gens_distr = _distribute_gens_by_base(base, strong_gens) i = 0 for i in range(len(base)): if strong_gens_distr[i] == [identity]: break base = base[:i] base_len = i for j in range(num_orbits): if base[base_len - 1] in orbits[j]: break rel_orbits = orbits[: j + 1] num_rel_orbits = len(rel_orbits) transversals = [None]*num_rel_orbits for j in range(num_rel_orbits): rep = orbit_reps[j] transversals[j] = dict( other.orbit_transversal(rep, pairs=True)) trivial_test = lambda x: True tests = [None]*base_len for l in range(base_len): if base[l] in orbit_reps: tests[l] = trivial_test else: def test(computed_words, l=l): g = computed_words[l] rep_orb_index = orbit_descr[base[l]] rep = orbit_reps[rep_orb_index] im = g._array_form[base[l]] im_rep = g._array_form[rep] tr_el = transversals[rep_orb_index][base[l]] # using the definition of transversal, # base[l]^g = rep^(tr_el*g); # if g belongs to the centralizer, then # base[l]^g = (rep^g)^tr_el return im == tr_el._array_form[im_rep] tests[l] = test def prop(g): return [rmul(g, gen) for gen in other.generators] == \ [rmul(gen, g) for gen in other.generators] return self.subgroup_search(prop, base=base, strong_gens=strong_gens, tests=tests) elif hasattr(other, '__getitem__'): gens = list(other) return self.centralizer(PermutationGroup(gens)) elif hasattr(other, 'array_form'): return self.centralizer(PermutationGroup([other])) def commutator(self, G, H): """ Return the commutator of two subgroups. Explanation =========== For a permutation group ``K`` and subgroups ``G``, ``H``, the commutator of ``G`` and ``H`` is defined as the group generated by all the commutators `[g, h] = hgh^{-1}g^{-1}` for ``g`` in ``G`` and ``h`` in ``H``. It is naturally a subgroup of ``K`` ([1], p.27). Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> S = SymmetricGroup(5) >>> A = AlternatingGroup(5) >>> G = S.commutator(S, A) >>> G.is_subgroup(A) True See Also ======== derived_subgroup Notes ===== The commutator of two subgroups `H, G` is equal to the normal closure of the commutators of all the generators, i.e. `hgh^{-1}g^{-1}` for `h` a generator of `H` and `g` a generator of `G` ([1], p.28) """ ggens = G.generators hgens = H.generators commutators = [] for ggen in ggens: for hgen in hgens: commutator = rmul(hgen, ggen, ~hgen, ~ggen) if commutator not in commutators: commutators.append(commutator) res = self.normal_closure(commutators) return res def coset_factor(self, g, factor_index=False): """Return ``G``'s (self's) coset factorization of ``g`` Explanation =========== If ``g`` is an element of ``G`` then it can be written as the product of permutations drawn from the Schreier-Sims coset decomposition, The permutations returned in ``f`` are those for which the product gives ``g``: ``g = f[n]*...f[1]*f[0]`` where ``n = len(B)`` and ``B = G.base``. f[i] is one of the permutations in ``self._basic_orbits[i]``. If factor_index==True, returns a tuple ``[b[0],..,b[n]]``, where ``b[i]`` belongs to ``self._basic_orbits[i]`` Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation(0, 1, 3, 7, 6, 4)(2, 5) >>> b = Permutation(0, 1, 3, 2)(4, 5, 7, 6) >>> G = PermutationGroup([a, b]) Define g: >>> g = Permutation(7)(1, 2, 4)(3, 6, 5) Confirm that it is an element of G: >>> G.contains(g) True Thus, it can be written as a product of factors (up to 3) drawn from u. See below that a factor from u1 and u2 and the Identity permutation have been used: >>> f = G.coset_factor(g) >>> f[2]*f[1]*f[0] == g True >>> f1 = G.coset_factor(g, True); f1 [0, 4, 4] >>> tr = G.basic_transversals >>> f[0] == tr[0][f1[0]] True If g is not an element of G then [] is returned: >>> c = Permutation(5, 6, 7) >>> G.coset_factor(c) [] See Also ======== sympy.combinatorics.util._strip """ if isinstance(g, (Cycle, Permutation)): g = g.list() if len(g) != self._degree: # this could either adjust the size or return [] immediately # but we don't choose between the two and just signal a possible # error raise ValueError('g should be the same size as permutations of G') I = list(range(self._degree)) basic_orbits = self.basic_orbits transversals = self._transversals factors = [] base = self.base h = g for i in range(len(base)): beta = h[base[i]] if beta == base[i]: factors.append(beta) continue if beta not in basic_orbits[i]: return [] u = transversals[i][beta]._array_form h = _af_rmul(_af_invert(u), h) factors.append(beta) if h != I: return [] if factor_index: return factors tr = self.basic_transversals factors = [tr[i][factors[i]] for i in range(len(base))] return factors def generator_product(self, g, original=False): ''' Return a list of strong generators `[s1, ..., sn]` s.t `g = sn*...*s1`. If `original=True`, make the list contain only the original group generators ''' product = [] if g.is_identity: return [] if g in self.strong_gens: if not original or g in self.generators: return [g] else: slp = self._strong_gens_slp[g] for s in slp: product.extend(self.generator_product(s, original=True)) return product elif g**-1 in self.strong_gens: g = g**-1 if not original or g in self.generators: return [g**-1] else: slp = self._strong_gens_slp[g] for s in slp: product.extend(self.generator_product(s, original=True)) l = len(product) product = [product[l-i-1]**-1 for i in range(l)] return product f = self.coset_factor(g, True) for i, j in enumerate(f): slp = self._transversal_slp[i][j] for s in slp: if not original: product.append(self.strong_gens[s]) else: s = self.strong_gens[s] product.extend(self.generator_product(s, original=True)) return product def coset_rank(self, g): """rank using Schreier-Sims representation. Explanation =========== The coset rank of ``g`` is the ordering number in which it appears in the lexicographic listing according to the coset decomposition The ordering is the same as in G.generate(method='coset'). If ``g`` does not belong to the group it returns None. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation(0, 1, 3, 7, 6, 4)(2, 5) >>> b = Permutation(0, 1, 3, 2)(4, 5, 7, 6) >>> G = PermutationGroup([a, b]) >>> c = Permutation(7)(2, 4)(3, 5) >>> G.coset_rank(c) 16 >>> G.coset_unrank(16) (7)(2 4)(3 5) See Also ======== coset_factor """ factors = self.coset_factor(g, True) if not factors: return None rank = 0 b = 1 transversals = self._transversals base = self._base basic_orbits = self._basic_orbits for i in range(len(base)): k = factors[i] j = basic_orbits[i].index(k) rank += b*j b = b*len(transversals[i]) return rank def coset_unrank(self, rank, af=False): """unrank using Schreier-Sims representation coset_unrank is the inverse operation of coset_rank if 0 <= rank < order; otherwise it returns None. """ if rank < 0 or rank >= self.order(): return None base = self.base transversals = self.basic_transversals basic_orbits = self.basic_orbits m = len(base) v = [0]*m for i in range(m): rank, c = divmod(rank, len(transversals[i])) v[i] = basic_orbits[i][c] a = [transversals[i][v[i]]._array_form for i in range(m)] h = _af_rmuln(*a) if af: return h else: return _af_new(h) @property def degree(self): """Returns the size of the permutations in the group. Explanation =========== The number of permutations comprising the group is given by ``len(group)``; the number of permutations that can be generated by the group is given by ``group.order()``. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([1, 0, 2]) >>> G = PermutationGroup([a]) >>> G.degree 3 >>> len(G) 1 >>> G.order() 2 >>> list(G.generate()) [(2), (2)(0 1)] See Also ======== order """ return self._degree @property def identity(self): ''' Return the identity element of the permutation group. ''' return _af_new(list(range(self.degree))) @property def elements(self): """Returns all the elements of the permutation group as a set Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> p = PermutationGroup(Permutation(1, 3), Permutation(1, 2)) >>> p.elements {(1 2 3), (1 3 2), (1 3), (2 3), (3), (3)(1 2)} """ return set(self._elements) @property def _elements(self): """Returns all the elements of the permutation group as a list Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> p = PermutationGroup(Permutation(1, 3), Permutation(1, 2)) >>> p._elements [(3), (3)(1 2), (1 3), (2 3), (1 2 3), (1 3 2)] """ return list(islice(self.generate(), None)) def derived_series(self): r"""Return the derived series for the group. Explanation =========== The derived series for a group `G` is defined as `G = G_0 > G_1 > G_2 > \ldots` where `G_i = [G_{i-1}, G_{i-1}]`, i.e. `G_i` is the derived subgroup of `G_{i-1}`, for `i\in\mathbb{N}`. When we have `G_k = G_{k-1}` for some `k\in\mathbb{N}`, the series terminates. Returns ======= A list of permutation groups containing the members of the derived series in the order `G = G_0, G_1, G_2, \ldots`. Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup, DihedralGroup) >>> A = AlternatingGroup(5) >>> len(A.derived_series()) 1 >>> S = SymmetricGroup(4) >>> len(S.derived_series()) 4 >>> S.derived_series()[1].is_subgroup(AlternatingGroup(4)) True >>> S.derived_series()[2].is_subgroup(DihedralGroup(2)) True See Also ======== derived_subgroup """ res = [self] current = self next = self.derived_subgroup() while not current.is_subgroup(next): res.append(next) current = next next = next.derived_subgroup() return res def derived_subgroup(self): r"""Compute the derived subgroup. Explanation =========== The derived subgroup, or commutator subgroup is the subgroup generated by all commutators `[g, h] = hgh^{-1}g^{-1}` for `g, h\in G` ; it is equal to the normal closure of the set of commutators of the generators ([1], p.28, [11]). Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([1, 0, 2, 4, 3]) >>> b = Permutation([0, 1, 3, 2, 4]) >>> G = PermutationGroup([a, b]) >>> C = G.derived_subgroup() >>> list(C.generate(af=True)) [[0, 1, 2, 3, 4], [0, 1, 3, 4, 2], [0, 1, 4, 2, 3]] See Also ======== derived_series """ r = self._r gens = [p._array_form for p in self.generators] set_commutators = set() degree = self._degree rng = list(range(degree)) for i in range(r): for j in range(r): p1 = gens[i] p2 = gens[j] c = list(range(degree)) for k in rng: c[p2[p1[k]]] = p1[p2[k]] ct = tuple(c) if not ct in set_commutators: set_commutators.add(ct) cms = [_af_new(p) for p in set_commutators] G2 = self.normal_closure(cms) return G2 def generate(self, method="coset", af=False): """Return iterator to generate the elements of the group. Explanation =========== Iteration is done with one of these methods:: method='coset' using the Schreier-Sims coset representation method='dimino' using the Dimino method If ``af = True`` it yields the array form of the permutations Examples ======== >>> from sympy.combinatorics import PermutationGroup >>> from sympy.combinatorics.polyhedron import tetrahedron The permutation group given in the tetrahedron object is also true groups: >>> G = tetrahedron.pgroup >>> G.is_group True Also the group generated by the permutations in the tetrahedron pgroup -- even the first two -- is a proper group: >>> H = PermutationGroup(G[0], G[1]) >>> J = PermutationGroup(list(H.generate())); J PermutationGroup([ (0 1)(2 3), (1 2 3), (1 3 2), (0 3 1), (0 2 3), (0 3)(1 2), (0 1 3), (3)(0 2 1), (0 3 2), (3)(0 1 2), (0 2)(1 3)]) >>> _.is_group True """ if method == "coset": return self.generate_schreier_sims(af) elif method == "dimino": return self.generate_dimino(af) else: raise NotImplementedError('No generation defined for %s' % method) def generate_dimino(self, af=False): """Yield group elements using Dimino's algorithm. If ``af == True`` it yields the array form of the permutations. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([0, 2, 1, 3]) >>> b = Permutation([0, 2, 3, 1]) >>> g = PermutationGroup([a, b]) >>> list(g.generate_dimino(af=True)) [[0, 1, 2, 3], [0, 2, 1, 3], [0, 2, 3, 1], [0, 1, 3, 2], [0, 3, 2, 1], [0, 3, 1, 2]] References ========== .. [1] The Implementation of Various Algorithms for Permutation Groups in the Computer Algebra System: AXIOM, N.J. Doye, M.Sc. Thesis """ idn = list(range(self.degree)) order = 0 element_list = [idn] set_element_list = {tuple(idn)} if af: yield idn else: yield _af_new(idn) gens = [p._array_form for p in self.generators] for i in range(len(gens)): # D elements of the subgroup G_i generated by gens[:i] D = element_list[:] N = [idn] while N: A = N N = [] for a in A: for g in gens[:i + 1]: ag = _af_rmul(a, g) if tuple(ag) not in set_element_list: # produce G_i*g for d in D: order += 1 ap = _af_rmul(d, ag) if af: yield ap else: p = _af_new(ap) yield p element_list.append(ap) set_element_list.add(tuple(ap)) N.append(ap) self._order = len(element_list) def generate_schreier_sims(self, af=False): """Yield group elements using the Schreier-Sims representation in coset_rank order If ``af = True`` it yields the array form of the permutations Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([0, 2, 1, 3]) >>> b = Permutation([0, 2, 3, 1]) >>> g = PermutationGroup([a, b]) >>> list(g.generate_schreier_sims(af=True)) [[0, 1, 2, 3], [0, 2, 1, 3], [0, 3, 2, 1], [0, 1, 3, 2], [0, 2, 3, 1], [0, 3, 1, 2]] """ n = self._degree u = self.basic_transversals basic_orbits = self._basic_orbits if len(u) == 0: for x in self.generators: if af: yield x._array_form else: yield x return if len(u) == 1: for i in basic_orbits[0]: if af: yield u[0][i]._array_form else: yield u[0][i] return u = list(reversed(u)) basic_orbits = basic_orbits[::-1] # stg stack of group elements stg = [list(range(n))] posmax = [len(x) for x in u] n1 = len(posmax) - 1 pos = [0]*n1 h = 0 while 1: # backtrack when finished iterating over coset if pos[h] >= posmax[h]: if h == 0: return pos[h] = 0 h -= 1 stg.pop() continue p = _af_rmul(u[h][basic_orbits[h][pos[h]]]._array_form, stg[-1]) pos[h] += 1 stg.append(p) h += 1 if h == n1: if af: for i in basic_orbits[-1]: p = _af_rmul(u[-1][i]._array_form, stg[-1]) yield p else: for i in basic_orbits[-1]: p = _af_rmul(u[-1][i]._array_form, stg[-1]) p1 = _af_new(p) yield p1 stg.pop() h -= 1 @property def generators(self): """Returns the generators of the group. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.generators [(1 2), (2)(0 1)] """ return self._generators def contains(self, g, strict=True): """Test if permutation ``g`` belong to self, ``G``. Explanation =========== If ``g`` is an element of ``G`` it can be written as a product of factors drawn from the cosets of ``G``'s stabilizers. To see if ``g`` is one of the actual generators defining the group use ``G.has(g)``. If ``strict`` is not ``True``, ``g`` will be resized, if necessary, to match the size of permutations in ``self``. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation(1, 2) >>> b = Permutation(2, 3, 1) >>> G = PermutationGroup(a, b, degree=5) >>> G.contains(G[0]) # trivial check True >>> elem = Permutation([[2, 3]], size=5) >>> G.contains(elem) True >>> G.contains(Permutation(4)(0, 1, 2, 3)) False If strict is False, a permutation will be resized, if necessary: >>> H = PermutationGroup(Permutation(5)) >>> H.contains(Permutation(3)) False >>> H.contains(Permutation(3), strict=False) True To test if a given permutation is present in the group: >>> elem in G.generators False >>> G.has(elem) False See Also ======== coset_factor, sympy.core.basic.Basic.has, __contains__ """ if not isinstance(g, Permutation): return False if g.size != self.degree: if strict: return False g = Permutation(g, size=self.degree) if g in self.generators: return True return bool(self.coset_factor(g.array_form, True)) @property def is_perfect(self): """Return ``True`` if the group is perfect. A group is perfect if it equals to its derived subgroup. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation(1,2,3)(4,5) >>> b = Permutation(1,2,3,4,5) >>> G = PermutationGroup([a, b]) >>> G.is_perfect False """ if self._is_perfect is None: self._is_perfect = self == self.derived_subgroup() return self._is_perfect @property def is_abelian(self): """Test if the group is Abelian. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.is_abelian False >>> a = Permutation([0, 2, 1]) >>> G = PermutationGroup([a]) >>> G.is_abelian True """ if self._is_abelian is not None: return self._is_abelian self._is_abelian = True gens = [p._array_form for p in self.generators] for x in gens: for y in gens: if y <= x: continue if not _af_commutes_with(x, y): self._is_abelian = False return False return True def abelian_invariants(self): """ Returns the abelian invariants for the given group. Let ``G`` be a nontrivial finite abelian group. Then G is isomorphic to the direct product of finitely many nontrivial cyclic groups of prime-power order. Explanation =========== The prime-powers that occur as the orders of the factors are uniquely determined by G. More precisely, the primes that occur in the orders of the factors in any such decomposition of ``G`` are exactly the primes that divide ``|G|`` and for any such prime ``p``, if the orders of the factors that are p-groups in one such decomposition of ``G`` are ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``, then the orders of the factors that are p-groups in any such decomposition of ``G`` are ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``. The uniquely determined integers ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``, taken for all primes that divide ``|G|`` are called the invariants of the nontrivial group ``G`` as suggested in ([14], p. 542). Notes ===== We adopt the convention that the invariants of a trivial group are []. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.abelian_invariants() [2] >>> from sympy.combinatorics.named_groups import CyclicGroup >>> G = CyclicGroup(7) >>> G.abelian_invariants() [7] """ if self.is_trivial: return [] gns = self.generators inv = [] G = self H = G.derived_subgroup() Hgens = H.generators for p in primefactors(G.order()): ranks = [] while True: pows = [] for g in gns: elm = g**p if not H.contains(elm): pows.append(elm) K = PermutationGroup(Hgens + pows) if pows else H r = G.order()//K.order() G = K gns = pows if r == 1: break; ranks.append(multiplicity(p, r)) if ranks: pows = [1]*ranks[0] for i in ranks: for j in range(0, i): pows[j] = pows[j]*p inv.extend(pows) inv.sort() return inv def is_elementary(self, p): """Return ``True`` if the group is elementary abelian. An elementary abelian group is a finite abelian group, where every nontrivial element has order `p`, where `p` is a prime. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([0, 2, 1]) >>> G = PermutationGroup([a]) >>> G.is_elementary(2) True >>> a = Permutation([0, 2, 1, 3]) >>> b = Permutation([3, 1, 2, 0]) >>> G = PermutationGroup([a, b]) >>> G.is_elementary(2) True >>> G.is_elementary(3) False """ return self.is_abelian and all(g.order() == p for g in self.generators) def _eval_is_alt_sym_naive(self, only_sym=False, only_alt=False): """A naive test using the group order.""" if only_sym and only_alt: raise ValueError( "Both {} and {} cannot be set to True" .format(only_sym, only_alt)) n = self.degree sym_order = 1 for i in range(2, n+1): sym_order *= i order = self.order() if order == sym_order: self._is_sym = True self._is_alt = False if only_alt: return False return True elif 2*order == sym_order: self._is_sym = False self._is_alt = True if only_sym: return False return True return False def _eval_is_alt_sym_monte_carlo(self, eps=0.05, perms=None): """A test using monte-carlo algorithm. Parameters ========== eps : float, optional The criterion for the incorrect ``False`` return. perms : list[Permutation], optional If explicitly given, it tests over the given candidats for testing. If ``None``, it randomly computes ``N_eps`` and chooses ``N_eps`` sample of the permutation from the group. See Also ======== _check_cycles_alt_sym """ if perms is None: n = self.degree if n < 17: c_n = 0.34 else: c_n = 0.57 d_n = (c_n*log(2))/log(n) N_eps = int(-log(eps)/d_n) perms = (self.random_pr() for i in range(N_eps)) return self._eval_is_alt_sym_monte_carlo(perms=perms) for perm in perms: if _check_cycles_alt_sym(perm): return True return False def is_alt_sym(self, eps=0.05, _random_prec=None): r"""Monte Carlo test for the symmetric/alternating group for degrees >= 8. Explanation =========== More specifically, it is one-sided Monte Carlo with the answer True (i.e., G is symmetric/alternating) guaranteed to be correct, and the answer False being incorrect with probability eps. For degree < 8, the order of the group is checked so the test is deterministic. Notes ===== The algorithm itself uses some nontrivial results from group theory and number theory: 1) If a transitive group ``G`` of degree ``n`` contains an element with a cycle of length ``n/2 < p < n-2`` for ``p`` a prime, ``G`` is the symmetric or alternating group ([1], pp. 81-82) 2) The proportion of elements in the symmetric/alternating group having the property described in 1) is approximately `\log(2)/\log(n)` ([1], p.82; [2], pp. 226-227). The helper function ``_check_cycles_alt_sym`` is used to go over the cycles in a permutation and look for ones satisfying 1). Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(10) >>> D.is_alt_sym() False See Also ======== _check_cycles_alt_sym """ if _random_prec is not None: N_eps = _random_prec['N_eps'] perms= (_random_prec[i] for i in range(N_eps)) return self._eval_is_alt_sym_monte_carlo(perms=perms) if self._is_sym or self._is_alt: return True if self._is_sym is False and self._is_alt is False: return False n = self.degree if n < 8: return self._eval_is_alt_sym_naive() elif self.is_transitive(): return self._eval_is_alt_sym_monte_carlo(eps=eps) self._is_sym, self._is_alt = False, False return False @property def is_nilpotent(self): """Test if the group is nilpotent. Explanation =========== A group `G` is nilpotent if it has a central series of finite length. Alternatively, `G` is nilpotent if its lower central series terminates with the trivial group. Every nilpotent group is also solvable ([1], p.29, [12]). Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... CyclicGroup) >>> C = CyclicGroup(6) >>> C.is_nilpotent True >>> S = SymmetricGroup(5) >>> S.is_nilpotent False See Also ======== lower_central_series, is_solvable """ if self._is_nilpotent is None: lcs = self.lower_central_series() terminator = lcs[len(lcs) - 1] gens = terminator.generators degree = self.degree identity = _af_new(list(range(degree))) if all(g == identity for g in gens): self._is_solvable = True self._is_nilpotent = True return True else: self._is_nilpotent = False return False else: return self._is_nilpotent def is_normal(self, gr, strict=True): """Test if ``G=self`` is a normal subgroup of ``gr``. Explanation =========== G is normal in gr if for each g2 in G, g1 in gr, ``g = g1*g2*g1**-1`` belongs to G It is sufficient to check this for each g1 in gr.generators and g2 in G.generators. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([1, 2, 0]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G1 = PermutationGroup([a, Permutation([2, 0, 1])]) >>> G1.is_normal(G) True """ if not self.is_subgroup(gr, strict=strict): return False d_self = self.degree d_gr = gr.degree if self.is_trivial and (d_self == d_gr or not strict): return True if self._is_abelian: return True new_self = self.copy() if not strict and d_self != d_gr: if d_self < d_gr: new_self = PermGroup(new_self.generators + [Permutation(d_gr - 1)]) else: gr = PermGroup(gr.generators + [Permutation(d_self - 1)]) gens2 = [p._array_form for p in new_self.generators] gens1 = [p._array_form for p in gr.generators] for g1 in gens1: for g2 in gens2: p = _af_rmuln(g1, g2, _af_invert(g1)) if not new_self.coset_factor(p, True): return False return True def is_primitive(self, randomized=True): r"""Test if a group is primitive. Explanation =========== A permutation group ``G`` acting on a set ``S`` is called primitive if ``S`` contains no nontrivial block under the action of ``G`` (a block is nontrivial if its cardinality is more than ``1``). Notes ===== The algorithm is described in [1], p.83, and uses the function minimal_block to search for blocks of the form `\{0, k\}` for ``k`` ranging over representatives for the orbits of `G_0`, the stabilizer of ``0``. This algorithm has complexity `O(n^2)` where ``n`` is the degree of the group, and will perform badly if `G_0` is small. There are two implementations offered: one finds `G_0` deterministically using the function ``stabilizer``, and the other (default) produces random elements of `G_0` using ``random_stab``, hoping that they generate a subgroup of `G_0` with not too many more orbits than `G_0` (this is suggested in [1], p.83). Behavior is changed by the ``randomized`` flag. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(10) >>> D.is_primitive() False See Also ======== minimal_block, random_stab """ if self._is_primitive is not None: return self._is_primitive if self.is_transitive() is False: return False if randomized: random_stab_gens = [] v = self.schreier_vector(0) for i in range(len(self)): random_stab_gens.append(self.random_stab(0, v)) stab = PermutationGroup(random_stab_gens) else: stab = self.stabilizer(0) orbits = stab.orbits() for orb in orbits: x = orb.pop() if x != 0 and any(e != 0 for e in self.minimal_block([0, x])): self._is_primitive = False return False self._is_primitive = True return True def minimal_blocks(self, randomized=True): ''' For a transitive group, return the list of all minimal block systems. If a group is intransitive, return `False`. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.named_groups import DihedralGroup >>> DihedralGroup(6).minimal_blocks() [[0, 1, 0, 1, 0, 1], [0, 1, 2, 0, 1, 2]] >>> G = PermutationGroup(Permutation(1,2,5)) >>> G.minimal_blocks() False See Also ======== minimal_block, is_transitive, is_primitive ''' def _number_blocks(blocks): # number the blocks of a block system # in order and return the number of # blocks and the tuple with the # reordering n = len(blocks) appeared = {} m = 0 b = [None]*n for i in range(n): if blocks[i] not in appeared: appeared[blocks[i]] = m b[i] = m m += 1 else: b[i] = appeared[blocks[i]] return tuple(b), m if not self.is_transitive(): return False blocks = [] num_blocks = [] rep_blocks = [] if randomized: random_stab_gens = [] v = self.schreier_vector(0) for i in range(len(self)): random_stab_gens.append(self.random_stab(0, v)) stab = PermutationGroup(random_stab_gens) else: stab = self.stabilizer(0) orbits = stab.orbits() for orb in orbits: x = orb.pop() if x != 0: block = self.minimal_block([0, x]) num_block, m = _number_blocks(block) # a representative block (containing 0) rep = {j for j in range(self.degree) if num_block[j] == 0} # check if the system is minimal with # respect to the already discovere ones minimal = True blocks_remove_mask = [False] * len(blocks) for i, r in enumerate(rep_blocks): if len(r) > len(rep) and rep.issubset(r): # i-th block system is not minimal blocks_remove_mask[i] = True elif len(r) < len(rep) and r.issubset(rep): # the system being checked is not minimal minimal = False break # remove non-minimal representative blocks blocks = [b for i, b in enumerate(blocks) if not blocks_remove_mask[i]] num_blocks = [n for i, n in enumerate(num_blocks) if not blocks_remove_mask[i]] rep_blocks = [r for i, r in enumerate(rep_blocks) if not blocks_remove_mask[i]] if minimal and num_block not in num_blocks: blocks.append(block) num_blocks.append(num_block) rep_blocks.append(rep) return blocks @property def is_solvable(self): """Test if the group is solvable. ``G`` is solvable if its derived series terminates with the trivial group ([1], p.29). Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(3) >>> S.is_solvable True See Also ======== is_nilpotent, derived_series """ if self._is_solvable is None: if self.order() % 2 != 0: return True ds = self.derived_series() terminator = ds[len(ds) - 1] gens = terminator.generators degree = self.degree identity = _af_new(list(range(degree))) if all(g == identity for g in gens): self._is_solvable = True return True else: self._is_solvable = False return False else: return self._is_solvable def is_subgroup(self, G, strict=True): """Return ``True`` if all elements of ``self`` belong to ``G``. If ``strict`` is ``False`` then if ``self``'s degree is smaller than ``G``'s, the elements will be resized to have the same degree. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... CyclicGroup) Testing is strict by default: the degree of each group must be the same: >>> p = Permutation(0, 1, 2, 3, 4, 5) >>> G1 = PermutationGroup([Permutation(0, 1, 2), Permutation(0, 1)]) >>> G2 = PermutationGroup([Permutation(0, 2), Permutation(0, 1, 2)]) >>> G3 = PermutationGroup([p, p**2]) >>> assert G1.order() == G2.order() == G3.order() == 6 >>> G1.is_subgroup(G2) True >>> G1.is_subgroup(G3) False >>> G3.is_subgroup(PermutationGroup(G3[1])) False >>> G3.is_subgroup(PermutationGroup(G3[0])) True To ignore the size, set ``strict`` to ``False``: >>> S3 = SymmetricGroup(3) >>> S5 = SymmetricGroup(5) >>> S3.is_subgroup(S5, strict=False) True >>> C7 = CyclicGroup(7) >>> G = S5*C7 >>> S5.is_subgroup(G, False) True >>> C7.is_subgroup(G, 0) False """ if isinstance(G, SymmetricPermutationGroup): if self.degree != G.degree: return False return True if not isinstance(G, PermutationGroup): return False if self == G or self.generators[0]==Permutation(): return True if G.order() % self.order() != 0: return False if self.degree == G.degree or \ (self.degree < G.degree and not strict): gens = self.generators else: return False return all(G.contains(g, strict=strict) for g in gens) @property def is_polycyclic(self): """Return ``True`` if a group is polycyclic. A group is polycyclic if it has a subnormal series with cyclic factors. For finite groups, this is the same as if the group is solvable. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([0, 2, 1, 3]) >>> b = Permutation([2, 0, 1, 3]) >>> G = PermutationGroup([a, b]) >>> G.is_polycyclic True """ return self.is_solvable def is_transitive(self, strict=True): """Test if the group is transitive. Explanation =========== A group is transitive if it has a single orbit. If ``strict`` is ``False`` the group is transitive if it has a single orbit of length different from 1. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([0, 2, 1, 3]) >>> b = Permutation([2, 0, 1, 3]) >>> G1 = PermutationGroup([a, b]) >>> G1.is_transitive() False >>> G1.is_transitive(strict=False) True >>> c = Permutation([2, 3, 0, 1]) >>> G2 = PermutationGroup([a, c]) >>> G2.is_transitive() True >>> d = Permutation([1, 0, 2, 3]) >>> e = Permutation([0, 1, 3, 2]) >>> G3 = PermutationGroup([d, e]) >>> G3.is_transitive() or G3.is_transitive(strict=False) False """ if self._is_transitive: # strict or not, if True then True return self._is_transitive if strict: if self._is_transitive is not None: # we only store strict=True return self._is_transitive ans = len(self.orbit(0)) == self.degree self._is_transitive = ans return ans got_orb = False for x in self.orbits(): if len(x) > 1: if got_orb: return False got_orb = True return got_orb @property def is_trivial(self): """Test if the group is the trivial group. This is true if the group contains only the identity permutation. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> G = PermutationGroup([Permutation([0, 1, 2])]) >>> G.is_trivial True """ if self._is_trivial is None: self._is_trivial = len(self) == 1 and self[0].is_Identity return self._is_trivial def lower_central_series(self): r"""Return the lower central series for the group. The lower central series for a group `G` is the series `G = G_0 > G_1 > G_2 > \ldots` where `G_k = [G, G_{k-1}]`, i.e. every term after the first is equal to the commutator of `G` and the previous term in `G1` ([1], p.29). Returns ======= A list of permutation groups in the order `G = G_0, G_1, G_2, \ldots` Examples ======== >>> from sympy.combinatorics.named_groups import (AlternatingGroup, ... DihedralGroup) >>> A = AlternatingGroup(4) >>> len(A.lower_central_series()) 2 >>> A.lower_central_series()[1].is_subgroup(DihedralGroup(2)) True See Also ======== commutator, derived_series """ res = [self] current = self next = self.commutator(self, current) while not current.is_subgroup(next): res.append(next) current = next next = self.commutator(self, current) return res @property def max_div(self): """Maximum proper divisor of the degree of a permutation group. Explanation =========== Obviously, this is the degree divided by its minimal proper divisor (larger than ``1``, if one exists). As it is guaranteed to be prime, the ``sieve`` from ``sympy.ntheory`` is used. This function is also used as an optimization tool for the functions ``minimal_block`` and ``_union_find_merge``. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> G = PermutationGroup([Permutation([0, 2, 1, 3])]) >>> G.max_div 2 See Also ======== minimal_block, _union_find_merge """ if self._max_div is not None: return self._max_div n = self.degree if n == 1: return 1 for x in sieve: if n % x == 0: d = n//x self._max_div = d return d def minimal_block(self, points): r"""For a transitive group, finds the block system generated by ``points``. Explanation =========== If a group ``G`` acts on a set ``S``, a nonempty subset ``B`` of ``S`` is called a block under the action of ``G`` if for all ``g`` in ``G`` we have ``gB = B`` (``g`` fixes ``B``) or ``gB`` and ``B`` have no common points (``g`` moves ``B`` entirely). ([1], p.23; [6]). The distinct translates ``gB`` of a block ``B`` for ``g`` in ``G`` partition the set ``S`` and this set of translates is known as a block system. Moreover, we obviously have that all blocks in the partition have the same size, hence the block size divides ``|S|`` ([1], p.23). A ``G``-congruence is an equivalence relation ``~`` on the set ``S`` such that ``a ~ b`` implies ``g(a) ~ g(b)`` for all ``g`` in ``G``. For a transitive group, the equivalence classes of a ``G``-congruence and the blocks of a block system are the same thing ([1], p.23). The algorithm below checks the group for transitivity, and then finds the ``G``-congruence generated by the pairs ``(p_0, p_1), (p_0, p_2), ..., (p_0,p_{k-1})`` which is the same as finding the maximal block system (i.e., the one with minimum block size) such that ``p_0, ..., p_{k-1}`` are in the same block ([1], p.83). It is an implementation of Atkinson's algorithm, as suggested in [1], and manipulates an equivalence relation on the set ``S`` using a union-find data structure. The running time is just above `O(|points||S|)`. ([1], pp. 83-87; [7]). Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(10) >>> D.minimal_block([0, 5]) [0, 1, 2, 3, 4, 0, 1, 2, 3, 4] >>> D.minimal_block([0, 1]) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] See Also ======== _union_find_rep, _union_find_merge, is_transitive, is_primitive """ if not self.is_transitive(): return False n = self.degree gens = self.generators # initialize the list of equivalence class representatives parents = list(range(n)) ranks = [1]*n not_rep = [] k = len(points) # the block size must divide the degree of the group if k > self.max_div: return [0]*n for i in range(k - 1): parents[points[i + 1]] = points[0] not_rep.append(points[i + 1]) ranks[points[0]] = k i = 0 len_not_rep = k - 1 while i < len_not_rep: gamma = not_rep[i] i += 1 for gen in gens: # find has side effects: performs path compression on the list # of representatives delta = self._union_find_rep(gamma, parents) # union has side effects: performs union by rank on the list # of representatives temp = self._union_find_merge(gen(gamma), gen(delta), ranks, parents, not_rep) if temp == -1: return [0]*n len_not_rep += temp for i in range(n): # force path compression to get the final state of the equivalence # relation self._union_find_rep(i, parents) # rewrite result so that block representatives are minimal new_reps = {} return [new_reps.setdefault(r, i) for i, r in enumerate(parents)] def conjugacy_class(self, x): r"""Return the conjugacy class of an element in the group. Explanation =========== The conjugacy class of an element ``g`` in a group ``G`` is the set of elements ``x`` in ``G`` that are conjugate with ``g``, i.e. for which ``g = xax^{-1}`` for some ``a`` in ``G``. Note that conjugacy is an equivalence relation, and therefore that conjugacy classes are partitions of ``G``. For a list of all the conjugacy classes of the group, use the conjugacy_classes() method. In a permutation group, each conjugacy class corresponds to a particular `cycle structure': for example, in ``S_3``, the conjugacy classes are: * the identity class, ``{()}`` * all transpositions, ``{(1 2), (1 3), (2 3)}`` * all 3-cycles, ``{(1 2 3), (1 3 2)}`` Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S3 = SymmetricGroup(3) >>> S3.conjugacy_class(Permutation(0, 1, 2)) {(0 1 2), (0 2 1)} Notes ===== This procedure computes the conjugacy class directly by finding the orbit of the element under conjugation in G. This algorithm is only feasible for permutation groups of relatively small order, but is like the orbit() function itself in that respect. """ # Ref: "Computing the conjugacy classes of finite groups"; Butler, G. # Groups '93 Galway/St Andrews; edited by Campbell, C. M. new_class = {x} last_iteration = new_class while len(last_iteration) > 0: this_iteration = set() for y in last_iteration: for s in self.generators: conjugated = s * y * (~s) if conjugated not in new_class: this_iteration.add(conjugated) new_class.update(last_iteration) last_iteration = this_iteration return new_class def conjugacy_classes(self): r"""Return the conjugacy classes of the group. Explanation =========== As described in the documentation for the .conjugacy_class() function, conjugacy is an equivalence relation on a group G which partitions the set of elements. This method returns a list of all these conjugacy classes of G. Examples ======== >>> from sympy.combinatorics import SymmetricGroup >>> SymmetricGroup(3).conjugacy_classes() [{(2)}, {(0 1 2), (0 2 1)}, {(0 2), (1 2), (2)(0 1)}] """ identity = _af_new(list(range(self.degree))) known_elements = {identity} classes = [known_elements.copy()] for x in self.generate(): if x not in known_elements: new_class = self.conjugacy_class(x) classes.append(new_class) known_elements.update(new_class) return classes def normal_closure(self, other, k=10): r"""Return the normal closure of a subgroup/set of permutations. Explanation =========== If ``S`` is a subset of a group ``G``, the normal closure of ``A`` in ``G`` is defined as the intersection of all normal subgroups of ``G`` that contain ``A`` ([1], p.14). Alternatively, it is the group generated by the conjugates ``x^{-1}yx`` for ``x`` a generator of ``G`` and ``y`` a generator of the subgroup ``\left\langle S\right\rangle`` generated by ``S`` (for some chosen generating set for ``\left\langle S\right\rangle``) ([1], p.73). Parameters ========== other a subgroup/list of permutations/single permutation k an implementation-specific parameter that determines the number of conjugates that are adjoined to ``other`` at once Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... CyclicGroup, AlternatingGroup) >>> S = SymmetricGroup(5) >>> C = CyclicGroup(5) >>> G = S.normal_closure(C) >>> G.order() 60 >>> G.is_subgroup(AlternatingGroup(5)) True See Also ======== commutator, derived_subgroup, random_pr Notes ===== The algorithm is described in [1], pp. 73-74; it makes use of the generation of random elements for permutation groups by the product replacement algorithm. """ if hasattr(other, 'generators'): degree = self.degree identity = _af_new(list(range(degree))) if all(g == identity for g in other.generators): return other Z = PermutationGroup(other.generators[:]) base, strong_gens = Z.schreier_sims_incremental() strong_gens_distr = _distribute_gens_by_base(base, strong_gens) basic_orbits, basic_transversals = \ _orbits_transversals_from_bsgs(base, strong_gens_distr) self._random_pr_init(r=10, n=20) _loop = True while _loop: Z._random_pr_init(r=10, n=10) for i in range(k): g = self.random_pr() h = Z.random_pr() conj = h^g res = _strip(conj, base, basic_orbits, basic_transversals) if res[0] != identity or res[1] != len(base) + 1: gens = Z.generators gens.append(conj) Z = PermutationGroup(gens) strong_gens.append(conj) temp_base, temp_strong_gens = \ Z.schreier_sims_incremental(base, strong_gens) base, strong_gens = temp_base, temp_strong_gens strong_gens_distr = \ _distribute_gens_by_base(base, strong_gens) basic_orbits, basic_transversals = \ _orbits_transversals_from_bsgs(base, strong_gens_distr) _loop = False for g in self.generators: for h in Z.generators: conj = h^g res = _strip(conj, base, basic_orbits, basic_transversals) if res[0] != identity or res[1] != len(base) + 1: _loop = True break if _loop: break return Z elif hasattr(other, '__getitem__'): return self.normal_closure(PermutationGroup(other)) elif hasattr(other, 'array_form'): return self.normal_closure(PermutationGroup([other])) def orbit(self, alpha, action='tuples'): r"""Compute the orbit of alpha `\{g(\alpha) | g \in G\}` as a set. Explanation =========== The time complexity of the algorithm used here is `O(|Orb|*r)` where `|Orb|` is the size of the orbit and ``r`` is the number of generators of the group. For a more detailed analysis, see [1], p.78, [2], pp. 19-21. Here alpha can be a single point, or a list of points. If alpha is a single point, the ordinary orbit is computed. if alpha is a list of points, there are three available options: 'union' - computes the union of the orbits of the points in the list 'tuples' - computes the orbit of the list interpreted as an ordered tuple under the group action ( i.e., g((1,2,3)) = (g(1), g(2), g(3)) ) 'sets' - computes the orbit of the list interpreted as a sets Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([1, 2, 0, 4, 5, 6, 3]) >>> G = PermutationGroup([a]) >>> G.orbit(0) {0, 1, 2} >>> G.orbit([0, 4], 'union') {0, 1, 2, 3, 4, 5, 6} See Also ======== orbit_transversal """ return _orbit(self.degree, self.generators, alpha, action) def orbit_rep(self, alpha, beta, schreier_vector=None): """Return a group element which sends ``alpha`` to ``beta``. Explanation =========== If ``beta`` is not in the orbit of ``alpha``, the function returns ``False``. This implementation makes use of the schreier vector. For a proof of correctness, see [1], p.80 Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> G = AlternatingGroup(5) >>> G.orbit_rep(0, 4) (0 4 1 2 3) See Also ======== schreier_vector """ if schreier_vector is None: schreier_vector = self.schreier_vector(alpha) if schreier_vector[beta] is None: return False k = schreier_vector[beta] gens = [x._array_form for x in self.generators] a = [] while k != -1: a.append(gens[k]) beta = gens[k].index(beta) # beta = (~gens[k])(beta) k = schreier_vector[beta] if a: return _af_new(_af_rmuln(*a)) else: return _af_new(list(range(self._degree))) def orbit_transversal(self, alpha, pairs=False): r"""Computes a transversal for the orbit of ``alpha`` as a set. Explanation =========== For a permutation group `G`, a transversal for the orbit `Orb = \{g(\alpha) | g \in G\}` is a set `\{g_\beta | g_\beta(\alpha) = \beta\}` for `\beta \in Orb`. Note that there may be more than one possible transversal. If ``pairs`` is set to ``True``, it returns the list of pairs `(\beta, g_\beta)`. For a proof of correctness, see [1], p.79 Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> G = DihedralGroup(6) >>> G.orbit_transversal(0) [(5), (0 1 2 3 4 5), (0 5)(1 4)(2 3), (0 2 4)(1 3 5), (5)(0 4)(1 3), (0 3)(1 4)(2 5)] See Also ======== orbit """ return _orbit_transversal(self._degree, self.generators, alpha, pairs) def orbits(self, rep=False): """Return the orbits of ``self``, ordered according to lowest element in each orbit. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation(1, 5)(2, 3)(4, 0, 6) >>> b = Permutation(1, 5)(3, 4)(2, 6, 0) >>> G = PermutationGroup([a, b]) >>> G.orbits() [{0, 2, 3, 4, 6}, {1, 5}] """ return _orbits(self._degree, self._generators) def order(self): """Return the order of the group: the number of permutations that can be generated from elements of the group. The number of permutations comprising the group is given by ``len(group)``; the length of each permutation in the group is given by ``group.size``. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([1, 0, 2]) >>> G = PermutationGroup([a]) >>> G.degree 3 >>> len(G) 1 >>> G.order() 2 >>> list(G.generate()) [(2), (2)(0 1)] >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.order() 6 See Also ======== degree """ if self._order is not None: return self._order if self._is_sym: n = self._degree self._order = factorial(n) return self._order if self._is_alt: n = self._degree self._order = factorial(n)/2 return self._order basic_transversals = self.basic_transversals m = 1 for x in basic_transversals: m *= len(x) self._order = m return m def index(self, H): """ Returns the index of a permutation group. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation(1,2,3) >>> b =Permutation(3) >>> G = PermutationGroup([a]) >>> H = PermutationGroup([b]) >>> G.index(H) 3 """ if H.is_subgroup(self): return self.order()//H.order() @property def is_symmetric(self): """Return ``True`` if the group is symmetric. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> g = SymmetricGroup(5) >>> g.is_symmetric True >>> from sympy.combinatorics import Permutation, PermutationGroup >>> g = PermutationGroup( ... Permutation(0, 1, 2, 3, 4), ... Permutation(2, 3)) >>> g.is_symmetric True Notes ===== This uses a naive test involving the computation of the full group order. If you need more quicker taxonomy for large groups, you can use :meth:`PermutationGroup.is_alt_sym`. However, :meth:`PermutationGroup.is_alt_sym` may not be accurate and is not able to distinguish between an alternating group and a symmetric group. See Also ======== is_alt_sym """ _is_sym = self._is_sym if _is_sym is not None: return _is_sym n = self.degree if n >= 8: if self.is_transitive(): _is_alt_sym = self._eval_is_alt_sym_monte_carlo() if _is_alt_sym: if any(g.is_odd for g in self.generators): self._is_sym, self._is_alt = True, False return True self._is_sym, self._is_alt = False, True return False return self._eval_is_alt_sym_naive(only_sym=True) self._is_sym, self._is_alt = False, False return False return self._eval_is_alt_sym_naive(only_sym=True) @property def is_alternating(self): """Return ``True`` if the group is alternating. Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> g = AlternatingGroup(5) >>> g.is_alternating True >>> from sympy.combinatorics import Permutation, PermutationGroup >>> g = PermutationGroup( ... Permutation(0, 1, 2, 3, 4), ... Permutation(2, 3, 4)) >>> g.is_alternating True Notes ===== This uses a naive test involving the computation of the full group order. If you need more quicker taxonomy for large groups, you can use :meth:`PermutationGroup.is_alt_sym`. However, :meth:`PermutationGroup.is_alt_sym` may not be accurate and is not able to distinguish between an alternating group and a symmetric group. See Also ======== is_alt_sym """ _is_alt = self._is_alt if _is_alt is not None: return _is_alt n = self.degree if n >= 8: if self.is_transitive(): _is_alt_sym = self._eval_is_alt_sym_monte_carlo() if _is_alt_sym: if all(g.is_even for g in self.generators): self._is_sym, self._is_alt = False, True return True self._is_sym, self._is_alt = True, False return False return self._eval_is_alt_sym_naive(only_alt=True) self._is_sym, self._is_alt = False, False return False return self._eval_is_alt_sym_naive(only_alt=True) @classmethod def _distinct_primes_lemma(cls, primes): """Subroutine to test if there is only one cyclic group for the order.""" primes = sorted(primes) l = len(primes) for i in range(l): for j in range(i+1, l): if primes[j] % primes[i] == 1: return None return True @property def is_cyclic(self): r""" Return ``True`` if the group is Cyclic. Examples ======== >>> from sympy.combinatorics.named_groups import AbelianGroup >>> G = AbelianGroup(3, 4) >>> G.is_cyclic True >>> G = AbelianGroup(4, 4) >>> G.is_cyclic False Notes ===== If the order of a group $n$ can be factored into the distinct primes $p_1, p_2, ... , p_s$ and if .. math:: \forall i, j \in \{1, 2, \ldots, s \}: p_i \not \equiv 1 \pmod {p_j} holds true, there is only one group of the order $n$ which is a cyclic group. [1]_ This is a generalization of the lemma that the group of order $15, 35, ...$ are cyclic. And also, these additional lemmas can be used to test if a group is cyclic if the order of the group is already found. - If the group is abelian and the order of the group is square-free, the group is cyclic. - If the order of the group is less than $6$ and is not $4$, the group is cyclic. - If the order of the group is prime, the group is cyclic. References ========== .. [1] 1978: John S. Rose: A Course on Group Theory, Introduction to Finite Group Theory: 1.4 """ if self._is_cyclic is not None: return self._is_cyclic if len(self.generators) == 1: self._is_cyclic = True self._is_abelian = True return True if self._is_abelian is False: self._is_cyclic = False return False order = self.order() if order < 6: self._is_abelian == True if order != 4: self._is_cyclic == True return True factors = factorint(order) if all(v == 1 for v in factors.values()): if self._is_abelian: self._is_cyclic = True return True primes = list(factors.keys()) if PermutationGroup._distinct_primes_lemma(primes) is True: self._is_cyclic = True self._is_abelian = True return True for p in factors: pgens = [] for g in self.generators: pgens.append(g**p) if self.index(self.subgroup(pgens)) != p: self._is_cyclic = False return False self._is_cyclic = True self._is_abelian = True return True def pointwise_stabilizer(self, points, incremental=True): r"""Return the pointwise stabilizer for a set of points. Explanation =========== For a permutation group `G` and a set of points `\{p_1, p_2,\ldots, p_k\}`, the pointwise stabilizer of `p_1, p_2, \ldots, p_k` is defined as `G_{p_1,\ldots, p_k} = \{g\in G | g(p_i) = p_i \forall i\in\{1, 2,\ldots,k\}\}` ([1],p20). It is a subgroup of `G`. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(7) >>> Stab = S.pointwise_stabilizer([2, 3, 5]) >>> Stab.is_subgroup(S.stabilizer(2).stabilizer(3).stabilizer(5)) True See Also ======== stabilizer, schreier_sims_incremental Notes ===== When incremental == True, rather than the obvious implementation using successive calls to ``.stabilizer()``, this uses the incremental Schreier-Sims algorithm to obtain a base with starting segment - the given points. """ if incremental: base, strong_gens = self.schreier_sims_incremental(base=points) stab_gens = [] degree = self.degree for gen in strong_gens: if [gen(point) for point in points] == points: stab_gens.append(gen) if not stab_gens: stab_gens = _af_new(list(range(degree))) return PermutationGroup(stab_gens) else: gens = self._generators degree = self.degree for x in points: gens = _stabilizer(degree, gens, x) return PermutationGroup(gens) def make_perm(self, n, seed=None): """ Multiply ``n`` randomly selected permutations from pgroup together, starting with the identity permutation. If ``n`` is a list of integers, those integers will be used to select the permutations and they will be applied in L to R order: make_perm((A, B, C)) will give CBA(I) where I is the identity permutation. ``seed`` is used to set the seed for the random selection of permutations from pgroup. If this is a list of integers, the corresponding permutations from pgroup will be selected in the order give. This is mainly used for testing purposes. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a, b = [Permutation([1, 0, 3, 2]), Permutation([1, 3, 0, 2])] >>> G = PermutationGroup([a, b]) >>> G.make_perm(1, [0]) (0 1)(2 3) >>> G.make_perm(3, [0, 1, 0]) (0 2 3 1) >>> G.make_perm([0, 1, 0]) (0 2 3 1) See Also ======== random """ if is_sequence(n): if seed is not None: raise ValueError('If n is a sequence, seed should be None') n, seed = len(n), n else: try: n = int(n) except TypeError: raise ValueError('n must be an integer or a sequence.') randrange = _randrange(seed) # start with the identity permutation result = Permutation(list(range(self.degree))) m = len(self) for i in range(n): p = self[randrange(m)] result = rmul(result, p) return result def random(self, af=False): """Return a random group element """ rank = randrange(self.order()) return self.coset_unrank(rank, af) def random_pr(self, gen_count=11, iterations=50, _random_prec=None): """Return a random group element using product replacement. Explanation =========== For the details of the product replacement algorithm, see ``_random_pr_init`` In ``random_pr`` the actual 'product replacement' is performed. Notice that if the attribute ``_random_gens`` is empty, it needs to be initialized by ``_random_pr_init``. See Also ======== _random_pr_init """ if self._random_gens == []: self._random_pr_init(gen_count, iterations) random_gens = self._random_gens r = len(random_gens) - 1 # handle randomized input for testing purposes if _random_prec is None: s = randrange(r) t = randrange(r - 1) if t == s: t = r - 1 x = choice([1, 2]) e = choice([-1, 1]) else: s = _random_prec['s'] t = _random_prec['t'] if t == s: t = r - 1 x = _random_prec['x'] e = _random_prec['e'] if x == 1: random_gens[s] = _af_rmul(random_gens[s], _af_pow(random_gens[t], e)) random_gens[r] = _af_rmul(random_gens[r], random_gens[s]) else: random_gens[s] = _af_rmul(_af_pow(random_gens[t], e), random_gens[s]) random_gens[r] = _af_rmul(random_gens[s], random_gens[r]) return _af_new(random_gens[r]) def random_stab(self, alpha, schreier_vector=None, _random_prec=None): """Random element from the stabilizer of ``alpha``. The schreier vector for ``alpha`` is an optional argument used for speeding up repeated calls. The algorithm is described in [1], p.81 See Also ======== random_pr, orbit_rep """ if schreier_vector is None: schreier_vector = self.schreier_vector(alpha) if _random_prec is None: rand = self.random_pr() else: rand = _random_prec['rand'] beta = rand(alpha) h = self.orbit_rep(alpha, beta, schreier_vector) return rmul(~h, rand) def schreier_sims(self): """Schreier-Sims algorithm. Explanation =========== It computes the generators of the chain of stabilizers `G > G_{b_1} > .. > G_{b1,..,b_r} > 1` in which `G_{b_1,..,b_i}` stabilizes `b_1,..,b_i`, and the corresponding ``s`` cosets. An element of the group can be written as the product `h_1*..*h_s`. We use the incremental Schreier-Sims algorithm. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.schreier_sims() >>> G.basic_transversals [{0: (2)(0 1), 1: (2), 2: (1 2)}, {0: (2), 2: (0 2)}] """ if self._transversals: return self._schreier_sims() return def _schreier_sims(self, base=None): schreier = self.schreier_sims_incremental(base=base, slp_dict=True) base, strong_gens = schreier[:2] self._base = base self._strong_gens = strong_gens self._strong_gens_slp = schreier[2] if not base: self._transversals = [] self._basic_orbits = [] return strong_gens_distr = _distribute_gens_by_base(base, strong_gens) basic_orbits, transversals, slps = _orbits_transversals_from_bsgs(base,\ strong_gens_distr, slp=True) # rewrite the indices stored in slps in terms of strong_gens for i, slp in enumerate(slps): gens = strong_gens_distr[i] for k in slp: slp[k] = [strong_gens.index(gens[s]) for s in slp[k]] self._transversals = transversals self._basic_orbits = [sorted(x) for x in basic_orbits] self._transversal_slp = slps def schreier_sims_incremental(self, base=None, gens=None, slp_dict=False): """Extend a sequence of points and generating set to a base and strong generating set. Parameters ========== base The sequence of points to be extended to a base. Optional parameter with default value ``[]``. gens The generating set to be extended to a strong generating set relative to the base obtained. Optional parameter with default value ``self.generators``. slp_dict If `True`, return a dictionary `{g: gens}` for each strong generator `g` where `gens` is a list of strong generators coming before `g` in `strong_gens`, such that the product of the elements of `gens` is equal to `g`. Returns ======= (base, strong_gens) ``base`` is the base obtained, and ``strong_gens`` is the strong generating set relative to it. The original parameters ``base``, ``gens`` remain unchanged. Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> from sympy.combinatorics.testutil import _verify_bsgs >>> A = AlternatingGroup(7) >>> base = [2, 3] >>> seq = [2, 3] >>> base, strong_gens = A.schreier_sims_incremental(base=seq) >>> _verify_bsgs(A, base, strong_gens) True >>> base[:2] [2, 3] Notes ===== This version of the Schreier-Sims algorithm runs in polynomial time. There are certain assumptions in the implementation - if the trivial group is provided, ``base`` and ``gens`` are returned immediately, as any sequence of points is a base for the trivial group. If the identity is present in the generators ``gens``, it is removed as it is a redundant generator. The implementation is described in [1], pp. 90-93. See Also ======== schreier_sims, schreier_sims_random """ if base is None: base = [] if gens is None: gens = self.generators[:] degree = self.degree id_af = list(range(degree)) # handle the trivial group if len(gens) == 1 and gens[0].is_Identity: if slp_dict: return base, gens, {gens[0]: [gens[0]]} return base, gens # prevent side effects _base, _gens = base[:], gens[:] # remove the identity as a generator _gens = [x for x in _gens if not x.is_Identity] # make sure no generator fixes all base points for gen in _gens: if all(x == gen._array_form[x] for x in _base): for new in id_af: if gen._array_form[new] != new: break else: assert None # can this ever happen? _base.append(new) # distribute generators according to basic stabilizers strong_gens_distr = _distribute_gens_by_base(_base, _gens) strong_gens_slp = [] # initialize the basic stabilizers, basic orbits and basic transversals orbs = {} transversals = {} slps = {} base_len = len(_base) for i in range(base_len): transversals[i], slps[i] = _orbit_transversal(degree, strong_gens_distr[i], _base[i], pairs=True, af=True, slp=True) transversals[i] = dict(transversals[i]) orbs[i] = list(transversals[i].keys()) # main loop: amend the stabilizer chain until we have generators # for all stabilizers i = base_len - 1 while i >= 0: # this flag is used to continue with the main loop from inside # a nested loop continue_i = False # test the generators for being a strong generating set db = {} for beta, u_beta in list(transversals[i].items()): for j, gen in enumerate(strong_gens_distr[i]): gb = gen._array_form[beta] u1 = transversals[i][gb] g1 = _af_rmul(gen._array_form, u_beta) slp = [(i, g) for g in slps[i][beta]] slp = [(i, j)] + slp if g1 != u1: # test if the schreier generator is in the i+1-th # would-be basic stabilizer y = True try: u1_inv = db[gb] except KeyError: u1_inv = db[gb] = _af_invert(u1) schreier_gen = _af_rmul(u1_inv, g1) u1_inv_slp = slps[i][gb][:] u1_inv_slp.reverse() u1_inv_slp = [(i, (g,)) for g in u1_inv_slp] slp = u1_inv_slp + slp h, j, slp = _strip_af(schreier_gen, _base, orbs, transversals, i, slp=slp, slps=slps) if j <= base_len: # new strong generator h at level j y = False elif h: # h fixes all base points y = False moved = 0 while h[moved] == moved: moved += 1 _base.append(moved) base_len += 1 strong_gens_distr.append([]) if y is False: # if a new strong generator is found, update the # data structures and start over h = _af_new(h) strong_gens_slp.append((h, slp)) for l in range(i + 1, j): strong_gens_distr[l].append(h) transversals[l], slps[l] =\ _orbit_transversal(degree, strong_gens_distr[l], _base[l], pairs=True, af=True, slp=True) transversals[l] = dict(transversals[l]) orbs[l] = list(transversals[l].keys()) i = j - 1 # continue main loop using the flag continue_i = True if continue_i is True: break if continue_i is True: break if continue_i is True: continue i -= 1 strong_gens = _gens[:] if slp_dict: # create the list of the strong generators strong_gens and # rewrite the indices of strong_gens_slp in terms of the # elements of strong_gens for k, slp in strong_gens_slp: strong_gens.append(k) for i in range(len(slp)): s = slp[i] if isinstance(s[1], tuple): slp[i] = strong_gens_distr[s[0]][s[1][0]]**-1 else: slp[i] = strong_gens_distr[s[0]][s[1]] strong_gens_slp = dict(strong_gens_slp) # add the original generators for g in _gens: strong_gens_slp[g] = [g] return (_base, strong_gens, strong_gens_slp) strong_gens.extend([k for k, _ in strong_gens_slp]) return _base, strong_gens def schreier_sims_random(self, base=None, gens=None, consec_succ=10, _random_prec=None): r"""Randomized Schreier-Sims algorithm. Explanation =========== The randomized Schreier-Sims algorithm takes the sequence ``base`` and the generating set ``gens``, and extends ``base`` to a base, and ``gens`` to a strong generating set relative to that base with probability of a wrong answer at most `2^{-consec\_succ}`, provided the random generators are sufficiently random. Parameters ========== base The sequence to be extended to a base. gens The generating set to be extended to a strong generating set. consec_succ The parameter defining the probability of a wrong answer. _random_prec An internal parameter used for testing purposes. Returns ======= (base, strong_gens) ``base`` is the base and ``strong_gens`` is the strong generating set relative to it. Examples ======== >>> from sympy.combinatorics.testutil import _verify_bsgs >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(5) >>> base, strong_gens = S.schreier_sims_random(consec_succ=5) >>> _verify_bsgs(S, base, strong_gens) #doctest: +SKIP True Notes ===== The algorithm is described in detail in [1], pp. 97-98. It extends the orbits ``orbs`` and the permutation groups ``stabs`` to basic orbits and basic stabilizers for the base and strong generating set produced in the end. The idea of the extension process is to "sift" random group elements through the stabilizer chain and amend the stabilizers/orbits along the way when a sift is not successful. The helper function ``_strip`` is used to attempt to decompose a random group element according to the current state of the stabilizer chain and report whether the element was fully decomposed (successful sift) or not (unsuccessful sift). In the latter case, the level at which the sift failed is reported and used to amend ``stabs``, ``base``, ``gens`` and ``orbs`` accordingly. The halting condition is for ``consec_succ`` consecutive successful sifts to pass. This makes sure that the current ``base`` and ``gens`` form a BSGS with probability at least `1 - 1/\text{consec\_succ}`. See Also ======== schreier_sims """ if base is None: base = [] if gens is None: gens = self.generators base_len = len(base) n = self.degree # make sure no generator fixes all base points for gen in gens: if all(gen(x) == x for x in base): new = 0 while gen._array_form[new] == new: new += 1 base.append(new) base_len += 1 # distribute generators according to basic stabilizers strong_gens_distr = _distribute_gens_by_base(base, gens) # initialize the basic stabilizers, basic transversals and basic orbits transversals = {} orbs = {} for i in range(base_len): transversals[i] = dict(_orbit_transversal(n, strong_gens_distr[i], base[i], pairs=True)) orbs[i] = list(transversals[i].keys()) # initialize the number of consecutive elements sifted c = 0 # start sifting random elements while the number of consecutive sifts # is less than consec_succ while c < consec_succ: if _random_prec is None: g = self.random_pr() else: g = _random_prec['g'].pop() h, j = _strip(g, base, orbs, transversals) y = True # determine whether a new base point is needed if j <= base_len: y = False elif not h.is_Identity: y = False moved = 0 while h(moved) == moved: moved += 1 base.append(moved) base_len += 1 strong_gens_distr.append([]) # if the element doesn't sift, amend the strong generators and # associated stabilizers and orbits if y is False: for l in range(1, j): strong_gens_distr[l].append(h) transversals[l] = dict(_orbit_transversal(n, strong_gens_distr[l], base[l], pairs=True)) orbs[l] = list(transversals[l].keys()) c = 0 else: c += 1 # build the strong generating set strong_gens = strong_gens_distr[0][:] for gen in strong_gens_distr[1]: if gen not in strong_gens: strong_gens.append(gen) return base, strong_gens def schreier_vector(self, alpha): """Computes the schreier vector for ``alpha``. Explanation =========== The Schreier vector efficiently stores information about the orbit of ``alpha``. It can later be used to quickly obtain elements of the group that send ``alpha`` to a particular element in the orbit. Notice that the Schreier vector depends on the order in which the group generators are listed. For a definition, see [3]. Since list indices start from zero, we adopt the convention to use "None" instead of 0 to signify that an element doesn't belong to the orbit. For the algorithm and its correctness, see [2], pp.78-80. Examples ======== >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.permutations import Permutation >>> a = Permutation([2, 4, 6, 3, 1, 5, 0]) >>> b = Permutation([0, 1, 3, 5, 4, 6, 2]) >>> G = PermutationGroup([a, b]) >>> G.schreier_vector(0) [-1, None, 0, 1, None, 1, 0] See Also ======== orbit """ n = self.degree v = [None]*n v[alpha] = -1 orb = [alpha] used = [False]*n used[alpha] = True gens = self.generators r = len(gens) for b in orb: for i in range(r): temp = gens[i]._array_form[b] if used[temp] is False: orb.append(temp) used[temp] = True v[temp] = i return v def stabilizer(self, alpha): r"""Return the stabilizer subgroup of ``alpha``. Explanation =========== The stabilizer of `\alpha` is the group `G_\alpha = \{g \in G | g(\alpha) = \alpha\}`. For a proof of correctness, see [1], p.79. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> G = DihedralGroup(6) >>> G.stabilizer(5) PermutationGroup([ (5)(0 4)(1 3)]) See Also ======== orbit """ return PermGroup(_stabilizer(self._degree, self._generators, alpha)) @property def strong_gens(self): r"""Return a strong generating set from the Schreier-Sims algorithm. Explanation =========== A generating set `S = \{g_1, g_2, ..., g_t\}` for a permutation group `G` is a strong generating set relative to the sequence of points (referred to as a "base") `(b_1, b_2, ..., b_k)` if, for `1 \leq i \leq k` we have that the intersection of the pointwise stabilizer `G^{(i+1)} := G_{b_1, b_2, ..., b_i}` with `S` generates the pointwise stabilizer `G^{(i+1)}`. The concepts of a base and strong generating set and their applications are discussed in depth in [1], pp. 87-89 and [2], pp. 55-57. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(4) >>> D.strong_gens [(0 1 2 3), (0 3)(1 2), (1 3)] >>> D.base [0, 1] See Also ======== base, basic_transversals, basic_orbits, basic_stabilizers """ if self._strong_gens == []: self.schreier_sims() return self._strong_gens def subgroup(self, gens): """ Return the subgroup generated by `gens` which is a list of elements of the group """ if not all(g in self for g in gens): raise ValueError("The group doesn't contain the supplied generators") G = PermutationGroup(gens) return G def subgroup_search(self, prop, base=None, strong_gens=None, tests=None, init_subgroup=None): """Find the subgroup of all elements satisfying the property ``prop``. Explanation =========== This is done by a depth-first search with respect to base images that uses several tests to prune the search tree. Parameters ========== prop The property to be used. Has to be callable on group elements and always return ``True`` or ``False``. It is assumed that all group elements satisfying ``prop`` indeed form a subgroup. base A base for the supergroup. strong_gens A strong generating set for the supergroup. tests A list of callables of length equal to the length of ``base``. These are used to rule out group elements by partial base images, so that ``tests[l](g)`` returns False if the element ``g`` is known not to satisfy prop base on where g sends the first ``l + 1`` base points. init_subgroup if a subgroup of the sought group is known in advance, it can be passed to the function as this parameter. Returns ======= res The subgroup of all elements satisfying ``prop``. The generating set for this group is guaranteed to be a strong generating set relative to the base ``base``. Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> from sympy.combinatorics.testutil import _verify_bsgs >>> S = SymmetricGroup(7) >>> prop_even = lambda x: x.is_even >>> base, strong_gens = S.schreier_sims_incremental() >>> G = S.subgroup_search(prop_even, base=base, strong_gens=strong_gens) >>> G.is_subgroup(AlternatingGroup(7)) True >>> _verify_bsgs(G, base, G.generators) True Notes ===== This function is extremely lengthy and complicated and will require some careful attention. The implementation is described in [1], pp. 114-117, and the comments for the code here follow the lines of the pseudocode in the book for clarity. The complexity is exponential in general, since the search process by itself visits all members of the supergroup. However, there are a lot of tests which are used to prune the search tree, and users can define their own tests via the ``tests`` parameter, so in practice, and for some computations, it's not terrible. A crucial part in the procedure is the frequent base change performed (this is line 11 in the pseudocode) in order to obtain a new basic stabilizer. The book mentiones that this can be done by using ``.baseswap(...)``, however the current implementation uses a more straightforward way to find the next basic stabilizer - calling the function ``.stabilizer(...)`` on the previous basic stabilizer. """ # initialize BSGS and basic group properties def get_reps(orbits): # get the minimal element in the base ordering return [min(orbit, key = lambda x: base_ordering[x]) \ for orbit in orbits] def update_nu(l): temp_index = len(basic_orbits[l]) + 1 -\ len(res_basic_orbits_init_base[l]) # this corresponds to the element larger than all points if temp_index >= len(sorted_orbits[l]): nu[l] = base_ordering[degree] else: nu[l] = sorted_orbits[l][temp_index] if base is None: base, strong_gens = self.schreier_sims_incremental() base_len = len(base) degree = self.degree identity = _af_new(list(range(degree))) base_ordering = _base_ordering(base, degree) # add an element larger than all points base_ordering.append(degree) # add an element smaller than all points base_ordering.append(-1) # compute BSGS-related structures strong_gens_distr = _distribute_gens_by_base(base, strong_gens) basic_orbits, transversals = _orbits_transversals_from_bsgs(base, strong_gens_distr) # handle subgroup initialization and tests if init_subgroup is None: init_subgroup = PermutationGroup([identity]) if tests is None: trivial_test = lambda x: True tests = [] for i in range(base_len): tests.append(trivial_test) # line 1: more initializations. res = init_subgroup f = base_len - 1 l = base_len - 1 # line 2: set the base for K to the base for G res_base = base[:] # line 3: compute BSGS and related structures for K res_base, res_strong_gens = res.schreier_sims_incremental( base=res_base) res_strong_gens_distr = _distribute_gens_by_base(res_base, res_strong_gens) res_generators = res.generators res_basic_orbits_init_base = \ [_orbit(degree, res_strong_gens_distr[i], res_base[i])\ for i in range(base_len)] # initialize orbit representatives orbit_reps = [None]*base_len # line 4: orbit representatives for f-th basic stabilizer of K orbits = _orbits(degree, res_strong_gens_distr[f]) orbit_reps[f] = get_reps(orbits) # line 5: remove the base point from the representatives to avoid # getting the identity element as a generator for K orbit_reps[f].remove(base[f]) # line 6: more initializations c = [0]*base_len u = [identity]*base_len sorted_orbits = [None]*base_len for i in range(base_len): sorted_orbits[i] = basic_orbits[i][:] sorted_orbits[i].sort(key=lambda point: base_ordering[point]) # line 7: initializations mu = [None]*base_len nu = [None]*base_len # this corresponds to the element smaller than all points mu[l] = degree + 1 update_nu(l) # initialize computed words computed_words = [identity]*base_len # line 8: main loop while True: # apply all the tests while l < base_len - 1 and \ computed_words[l](base[l]) in orbit_reps[l] and \ base_ordering[mu[l]] < \ base_ordering[computed_words[l](base[l])] < \ base_ordering[nu[l]] and \ tests[l](computed_words): # line 11: change the (partial) base of K new_point = computed_words[l](base[l]) res_base[l] = new_point new_stab_gens = _stabilizer(degree, res_strong_gens_distr[l], new_point) res_strong_gens_distr[l + 1] = new_stab_gens # line 12: calculate minimal orbit representatives for the # l+1-th basic stabilizer orbits = _orbits(degree, new_stab_gens) orbit_reps[l + 1] = get_reps(orbits) # line 13: amend sorted orbits l += 1 temp_orbit = [computed_words[l - 1](point) for point in basic_orbits[l]] temp_orbit.sort(key=lambda point: base_ordering[point]) sorted_orbits[l] = temp_orbit # lines 14 and 15: update variables used minimality tests new_mu = degree + 1 for i in range(l): if base[l] in res_basic_orbits_init_base[i]: candidate = computed_words[i](base[i]) if base_ordering[candidate] > base_ordering[new_mu]: new_mu = candidate mu[l] = new_mu update_nu(l) # line 16: determine the new transversal element c[l] = 0 temp_point = sorted_orbits[l][c[l]] gamma = computed_words[l - 1]._array_form.index(temp_point) u[l] = transversals[l][gamma] # update computed words computed_words[l] = rmul(computed_words[l - 1], u[l]) # lines 17 & 18: apply the tests to the group element found g = computed_words[l] temp_point = g(base[l]) if l == base_len - 1 and \ base_ordering[mu[l]] < \ base_ordering[temp_point] < base_ordering[nu[l]] and \ temp_point in orbit_reps[l] and \ tests[l](computed_words) and \ prop(g): # line 19: reset the base of K res_generators.append(g) res_base = base[:] # line 20: recalculate basic orbits (and transversals) res_strong_gens.append(g) res_strong_gens_distr = _distribute_gens_by_base(res_base, res_strong_gens) res_basic_orbits_init_base = \ [_orbit(degree, res_strong_gens_distr[i], res_base[i]) \ for i in range(base_len)] # line 21: recalculate orbit representatives # line 22: reset the search depth orbit_reps[f] = get_reps(orbits) l = f # line 23: go up the tree until in the first branch not fully # searched while l >= 0 and c[l] == len(basic_orbits[l]) - 1: l = l - 1 # line 24: if the entire tree is traversed, return K if l == -1: return PermutationGroup(res_generators) # lines 25-27: update orbit representatives if l < f: # line 26 f = l c[l] = 0 # line 27 temp_orbits = _orbits(degree, res_strong_gens_distr[f]) orbit_reps[f] = get_reps(temp_orbits) # line 28: update variables used for minimality testing mu[l] = degree + 1 temp_index = len(basic_orbits[l]) + 1 - \ len(res_basic_orbits_init_base[l]) if temp_index >= len(sorted_orbits[l]): nu[l] = base_ordering[degree] else: nu[l] = sorted_orbits[l][temp_index] # line 29: set the next element from the current branch and update # accordingly c[l] += 1 if l == 0: gamma = sorted_orbits[l][c[l]] else: gamma = computed_words[l - 1]._array_form.index(sorted_orbits[l][c[l]]) u[l] = transversals[l][gamma] if l == 0: computed_words[l] = u[l] else: computed_words[l] = rmul(computed_words[l - 1], u[l]) @property def transitivity_degree(self): r"""Compute the degree of transitivity of the group. Explanation =========== A permutation group `G` acting on `\Omega = \{0, 1, ..., n-1\}` is ``k``-fold transitive, if, for any k points `(a_1, a_2, ..., a_k)\in\Omega` and any k points `(b_1, b_2, ..., b_k)\in\Omega` there exists `g\in G` such that `g(a_1)=b_1, g(a_2)=b_2, ..., g(a_k)=b_k` The degree of transitivity of `G` is the maximum ``k`` such that `G` is ``k``-fold transitive. ([8]) Examples ======== >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.permutations import Permutation >>> a = Permutation([1, 2, 0]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.transitivity_degree 3 See Also ======== is_transitive, orbit """ if self._transitivity_degree is None: n = self.degree G = self # if G is k-transitive, a tuple (a_0,..,a_k) # can be brought to (b_0,...,b_(k-1), b_k) # where b_0,...,b_(k-1) are fixed points; # consider the group G_k which stabilizes b_0,...,b_(k-1) # if G_k is transitive on the subset excluding b_0,...,b_(k-1) # then G is (k+1)-transitive for i in range(n): orb = G.orbit(i) if len(orb) != n - i: self._transitivity_degree = i return i G = G.stabilizer(i) self._transitivity_degree = n return n else: return self._transitivity_degree def _p_elements_group(G, p): ''' For an abelian p-group G return the subgroup consisting of all elements of order p (and the identity) ''' gens = G.generators[:] gens = sorted(gens, key=lambda x: x.order(), reverse=True) gens_p = [g**(g.order()/p) for g in gens] gens_r = [] for i in range(len(gens)): x = gens[i] x_order = x.order() # x_p has order p x_p = x**(x_order/p) if i > 0: P = PermutationGroup(gens_p[:i]) else: P = PermutationGroup(G.identity) if x**(x_order/p) not in P: gens_r.append(x**(x_order/p)) else: # replace x by an element of order (x.order()/p) # so that gens still generates G g = P.generator_product(x_p, original=True) for s in g: x = x*s**-1 x_order = x_order/p # insert x to gens so that the sorting is preserved del gens[i] del gens_p[i] j = i - 1 while j < len(gens) and gens[j].order() >= x_order: j += 1 gens = gens[:j] + [x] + gens[j:] gens_p = gens_p[:j] + [x] + gens_p[j:] return PermutationGroup(gens_r) def _sylow_alt_sym(self, p): ''' Return a p-Sylow subgroup of a symmetric or an alternating group. Explanation =========== The algorithm for this is hinted at in [1], Chapter 4, Exercise 4. For Sym(n) with n = p^i, the idea is as follows. Partition the interval [0..n-1] into p equal parts, each of length p^(i-1): [0..p^(i-1)-1], [p^(i-1)..2*p^(i-1)-1]...[(p-1)*p^(i-1)..p^i-1]. Find a p-Sylow subgroup of Sym(p^(i-1)) (treated as a subgroup of ``self``) acting on each of the parts. Call the subgroups P_1, P_2...P_p. The generators for the subgroups P_2...P_p can be obtained from those of P_1 by applying a "shifting" permutation to them, that is, a permutation mapping [0..p^(i-1)-1] to the second part (the other parts are obtained by using the shift multiple times). The union of this permutation and the generators of P_1 is a p-Sylow subgroup of ``self``. For n not equal to a power of p, partition [0..n-1] in accordance with how n would be written in base p. E.g. for p=2 and n=11, 11 = 2^3 + 2^2 + 1 so the partition is [[0..7], [8..9], {10}]. To generate a p-Sylow subgroup, take the union of the generators for each of the parts. For the above example, {(0 1), (0 2)(1 3), (0 4), (1 5)(2 7)} from the first part, {(8 9)} from the second part and nothing from the third. This gives 4 generators in total, and the subgroup they generate is p-Sylow. Alternating groups are treated the same except when p=2. In this case, (0 1)(s s+1) should be added for an appropriate s (the start of a part) for each part in the partitions. See Also ======== sylow_subgroup, is_alt_sym ''' n = self.degree gens = [] identity = Permutation(n-1) # the case of 2-sylow subgroups of alternating groups # needs special treatment alt = p == 2 and all(g.is_even for g in self.generators) # find the presentation of n in base p coeffs = [] m = n while m > 0: coeffs.append(m % p) m = m // p power = len(coeffs)-1 # for a symmetric group, gens[:i] is the generating # set for a p-Sylow subgroup on [0..p**(i-1)-1]. For # alternating groups, the same is given by gens[:2*(i-1)] for i in range(1, power+1): if i == 1 and alt: # (0 1) shouldn't be added for alternating groups continue gen = Permutation([(j + p**(i-1)) % p**i for j in range(p**i)]) gens.append(identity*gen) if alt: gen = Permutation(0, 1)*gen*Permutation(0, 1)*gen gens.append(gen) # the first point in the current part (see the algorithm # description in the docstring) start = 0 while power > 0: a = coeffs[power] # make the permutation shifting the start of the first # part ([0..p^i-1] for some i) to the current one for s in range(a): shift = Permutation() if start > 0: for i in range(p**power): shift = shift(i, start + i) if alt: gen = Permutation(0, 1)*shift*Permutation(0, 1)*shift gens.append(gen) j = 2*(power - 1) else: j = power for i, gen in enumerate(gens[:j]): if alt and i % 2 == 1: continue # shift the generator to the start of the # partition part gen = shift*gen*shift gens.append(gen) start += p**power power = power-1 return gens def sylow_subgroup(self, p): ''' Return a p-Sylow subgroup of the group. The algorithm is described in [1], Chapter 4, Section 7 Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> D = DihedralGroup(6) >>> S = D.sylow_subgroup(2) >>> S.order() 4 >>> G = SymmetricGroup(6) >>> S = G.sylow_subgroup(5) >>> S.order() 5 >>> G1 = AlternatingGroup(3) >>> G2 = AlternatingGroup(5) >>> G3 = AlternatingGroup(9) >>> S1 = G1.sylow_subgroup(3) >>> S2 = G2.sylow_subgroup(3) >>> S3 = G3.sylow_subgroup(3) >>> len1 = len(S1.lower_central_series()) >>> len2 = len(S2.lower_central_series()) >>> len3 = len(S3.lower_central_series()) >>> len1 == len2 True >>> len1 < len3 True ''' from sympy.combinatorics.homomorphisms import ( orbit_homomorphism, block_homomorphism) from sympy.ntheory.primetest import isprime if not isprime(p): raise ValueError("p must be a prime") def is_p_group(G): # check if the order of G is a power of p # and return the power m = G.order() n = 0 while m % p == 0: m = m/p n += 1 if m == 1: return True, n return False, n def _sylow_reduce(mu, nu): # reduction based on two homomorphisms # mu and nu with trivially intersecting # kernels Q = mu.image().sylow_subgroup(p) Q = mu.invert_subgroup(Q) nu = nu.restrict_to(Q) R = nu.image().sylow_subgroup(p) return nu.invert_subgroup(R) order = self.order() if order % p != 0: return PermutationGroup([self.identity]) p_group, n = is_p_group(self) if p_group: return self if self.is_alt_sym(): return PermutationGroup(self._sylow_alt_sym(p)) # if there is a non-trivial orbit with size not divisible # by p, the sylow subgroup is contained in its stabilizer # (by orbit-stabilizer theorem) orbits = self.orbits() non_p_orbits = [o for o in orbits if len(o) % p != 0 and len(o) != 1] if non_p_orbits: G = self.stabilizer(list(non_p_orbits[0]).pop()) return G.sylow_subgroup(p) if not self.is_transitive(): # apply _sylow_reduce to orbit actions orbits = sorted(orbits, key = lambda x: len(x)) omega1 = orbits.pop() omega2 = orbits[0].union(*orbits) mu = orbit_homomorphism(self, omega1) nu = orbit_homomorphism(self, omega2) return _sylow_reduce(mu, nu) blocks = self.minimal_blocks() if len(blocks) > 1: # apply _sylow_reduce to block system actions mu = block_homomorphism(self, blocks[0]) nu = block_homomorphism(self, blocks[1]) return _sylow_reduce(mu, nu) elif len(blocks) == 1: block = list(blocks)[0] if any(e != 0 for e in block): # self is imprimitive mu = block_homomorphism(self, block) if not is_p_group(mu.image())[0]: S = mu.image().sylow_subgroup(p) return mu.invert_subgroup(S).sylow_subgroup(p) # find an element of order p g = self.random() g_order = g.order() while g_order % p != 0 or g_order == 0: g = self.random() g_order = g.order() g = g**(g_order // p) if order % p**2 != 0: return PermutationGroup(g) C = self.centralizer(g) while C.order() % p**n != 0: S = C.sylow_subgroup(p) s_order = S.order() Z = S.center() P = Z._p_elements_group(p) h = P.random() C_h = self.centralizer(h) while C_h.order() % p*s_order != 0: h = P.random() C_h = self.centralizer(h) C = C_h return C.sylow_subgroup(p) def _block_verify(H, L, alpha): delta = sorted(list(H.orbit(alpha))) H_gens = H.generators # p[i] will be the number of the block # delta[i] belongs to p = [-1]*len(delta) blocks = [-1]*len(delta) B = [[]] # future list of blocks u = [0]*len(delta) # u[i] in L s.t. alpha^u[i] = B[0][i] t = L.orbit_transversal(alpha, pairs=True) for a, beta in t: B[0].append(a) i_a = delta.index(a) p[i_a] = 0 blocks[i_a] = alpha u[i_a] = beta rho = 0 m = 0 # number of blocks - 1 while rho <= m: beta = B[rho][0] for g in H_gens: d = beta^g i_d = delta.index(d) sigma = p[i_d] if sigma < 0: # define a new block m += 1 sigma = m u[i_d] = u[delta.index(beta)]*g p[i_d] = sigma rep = d blocks[i_d] = rep newb = [rep] for gamma in B[rho][1:]: i_gamma = delta.index(gamma) d = gamma^g i_d = delta.index(d) if p[i_d] < 0: u[i_d] = u[i_gamma]*g p[i_d] = sigma blocks[i_d] = rep newb.append(d) else: # B[rho] is not a block s = u[i_gamma]*g*u[i_d]**(-1) return False, s B.append(newb) else: for h in B[rho][1:]: if not h^g in B[sigma]: # B[rho] is not a block s = u[delta.index(beta)]*g*u[i_d]**(-1) return False, s rho += 1 return True, blocks def _verify(H, K, phi, z, alpha): ''' Return a list of relators ``rels`` in generators ``gens`_h` that are mapped to ``H.generators`` by ``phi`` so that given a finite presentation <gens_k | rels_k> of ``K`` on a subset of ``gens_h`` <gens_h | rels_k + rels> is a finite presentation of ``H``. Explanation =========== ``H`` should be generated by the union of ``K.generators`` and ``z`` (a single generator), and ``H.stabilizer(alpha) == K``; ``phi`` is a canonical injection from a free group into a permutation group containing ``H``. The algorithm is described in [1], Chapter 6. Examples ======== >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.homomorphisms import homomorphism >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup >>> H = PermutationGroup(Permutation(0, 2), Permutation (1, 5)) >>> K = PermutationGroup(Permutation(5)(0, 2)) >>> F = free_group("x_0 x_1")[0] >>> gens = F.generators >>> phi = homomorphism(F, H, F.generators, H.generators) >>> rels_k = [gens[0]**2] # relators for presentation of K >>> z= Permutation(1, 5) >>> check, rels_h = H._verify(K, phi, z, 1) >>> check True >>> rels = rels_k + rels_h >>> G = FpGroup(F, rels) # presentation of H >>> G.order() == H.order() True See also ======== strong_presentation, presentation, stabilizer ''' orbit = H.orbit(alpha) beta = alpha^(z**-1) K_beta = K.stabilizer(beta) # orbit representatives of K_beta gammas = [alpha, beta] orbits = list({tuple(K_beta.orbit(o)) for o in orbit}) orbit_reps = [orb[0] for orb in orbits] for rep in orbit_reps: if rep not in gammas: gammas.append(rep) # orbit transversal of K betas = [alpha, beta] transversal = {alpha: phi.invert(H.identity), beta: phi.invert(z**-1)} for s, g in K.orbit_transversal(beta, pairs=True): if not s in transversal: transversal[s] = transversal[beta]*phi.invert(g) union = K.orbit(alpha).union(K.orbit(beta)) while (len(union) < len(orbit)): for gamma in gammas: if gamma in union: r = gamma^z if r not in union: betas.append(r) transversal[r] = transversal[gamma]*phi.invert(z) for s, g in K.orbit_transversal(r, pairs=True): if not s in transversal: transversal[s] = transversal[r]*phi.invert(g) union = union.union(K.orbit(r)) break # compute relators rels = [] for b in betas: k_gens = K.stabilizer(b).generators for y in k_gens: new_rel = transversal[b] gens = K.generator_product(y, original=True) for g in gens[::-1]: new_rel = new_rel*phi.invert(g) new_rel = new_rel*transversal[b]**-1 perm = phi(new_rel) try: gens = K.generator_product(perm, original=True) except ValueError: return False, perm for g in gens: new_rel = new_rel*phi.invert(g)**-1 if new_rel not in rels: rels.append(new_rel) for gamma in gammas: new_rel = transversal[gamma]*phi.invert(z)*transversal[gamma^z]**-1 perm = phi(new_rel) try: gens = K.generator_product(perm, original=True) except ValueError: return False, perm for g in gens: new_rel = new_rel*phi.invert(g)**-1 if new_rel not in rels: rels.append(new_rel) return True, rels def strong_presentation(G): ''' Return a strong finite presentation of `G`. The generators of the returned group are in the same order as the strong generators of `G`. The algorithm is based on Sims' Verify algorithm described in [1], Chapter 6. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> P = DihedralGroup(4) >>> G = P.strong_presentation() >>> P.order() == G.order() True See Also ======== presentation, _verify ''' from sympy.combinatorics.fp_groups import (FpGroup, simplify_presentation) from sympy.combinatorics.free_groups import free_group from sympy.combinatorics.homomorphisms import (block_homomorphism, homomorphism, GroupHomomorphism) strong_gens = G.strong_gens[:] stabs = G.basic_stabilizers[:] base = G.base[:] # injection from a free group on len(strong_gens) # generators into G gen_syms = [('x_%d'%i) for i in range(len(strong_gens))] F = free_group(', '.join(gen_syms))[0] phi = homomorphism(F, G, F.generators, strong_gens) H = PermutationGroup(G.identity) while stabs: alpha = base.pop() K = H H = stabs.pop() new_gens = [g for g in H.generators if g not in K] if K.order() == 1: z = new_gens.pop() rels = [F.generators[-1]**z.order()] intermediate_gens = [z] K = PermutationGroup(intermediate_gens) # add generators one at a time building up from K to H while new_gens: z = new_gens.pop() intermediate_gens = [z] + intermediate_gens K_s = PermutationGroup(intermediate_gens) orbit = K_s.orbit(alpha) orbit_k = K.orbit(alpha) # split into cases based on the orbit of K_s if orbit_k == orbit: if z in K: rel = phi.invert(z) perm = z else: t = K.orbit_rep(alpha, alpha^z) rel = phi.invert(z)*phi.invert(t)**-1 perm = z*t**-1 for g in K.generator_product(perm, original=True): rel = rel*phi.invert(g)**-1 new_rels = [rel] elif len(orbit_k) == 1: # `success` is always true because `strong_gens` # and `base` are already a verified BSGS. Later # this could be changed to start with a randomly # generated (potential) BSGS, and then new elements # would have to be appended to it when `success` # is false. success, new_rels = K_s._verify(K, phi, z, alpha) else: # K.orbit(alpha) should be a block # under the action of K_s on K_s.orbit(alpha) check, block = K_s._block_verify(K, alpha) if check: # apply _verify to the action of K_s # on the block system; for convenience, # add the blocks as additional points # that K_s should act on t = block_homomorphism(K_s, block) m = t.codomain.degree # number of blocks d = K_s.degree # conjugating with p will shift # permutations in t.image() to # higher numbers, e.g. # p*(0 1)*p = (m m+1) p = Permutation() for i in range(m): p *= Permutation(i, i+d) t_img = t.images # combine generators of K_s with their # action on the block system images = {g: g*p*t_img[g]*p for g in t_img} for g in G.strong_gens[:-len(K_s.generators)]: images[g] = g K_s_act = PermutationGroup(list(images.values())) f = GroupHomomorphism(G, K_s_act, images) K_act = PermutationGroup([f(g) for g in K.generators]) success, new_rels = K_s_act._verify(K_act, f.compose(phi), f(z), d) for n in new_rels: if not n in rels: rels.append(n) K = K_s group = FpGroup(F, rels) return simplify_presentation(group) def presentation(G, eliminate_gens=True): ''' Return an `FpGroup` presentation of the group. The algorithm is described in [1], Chapter 6.1. ''' from sympy.combinatorics.fp_groups import (FpGroup, simplify_presentation) from sympy.combinatorics.coset_table import CosetTable from sympy.combinatorics.free_groups import free_group from sympy.combinatorics.homomorphisms import homomorphism from itertools import product if G._fp_presentation: return G._fp_presentation if G._fp_presentation: return G._fp_presentation def _factor_group_by_rels(G, rels): if isinstance(G, FpGroup): rels.extend(G.relators) return FpGroup(G.free_group, list(set(rels))) return FpGroup(G, rels) gens = G.generators len_g = len(gens) if len_g == 1: order = gens[0].order() # handle the trivial group if order == 1: return free_group([])[0] F, x = free_group('x') return FpGroup(F, [x**order]) if G.order() > 20: half_gens = G.generators[0:(len_g+1)//2] else: half_gens = [] H = PermutationGroup(half_gens) H_p = H.presentation() len_h = len(H_p.generators) C = G.coset_table(H) n = len(C) # subgroup index gen_syms = [('x_%d'%i) for i in range(len(gens))] F = free_group(', '.join(gen_syms))[0] # mapping generators of H_p to those of F images = [F.generators[i] for i in range(len_h)] R = homomorphism(H_p, F, H_p.generators, images, check=False) # rewrite relators rels = R(H_p.relators) G_p = FpGroup(F, rels) # injective homomorphism from G_p into G T = homomorphism(G_p, G, G_p.generators, gens) C_p = CosetTable(G_p, []) C_p.table = [[None]*(2*len_g) for i in range(n)] # initiate the coset transversal transversal = [None]*n transversal[0] = G_p.identity # fill in the coset table as much as possible for i in range(2*len_h): C_p.table[0][i] = 0 gamma = 1 for alpha, x in product(range(0, n), range(2*len_g)): beta = C[alpha][x] if beta == gamma: gen = G_p.generators[x//2]**((-1)**(x % 2)) transversal[beta] = transversal[alpha]*gen C_p.table[alpha][x] = beta C_p.table[beta][x + (-1)**(x % 2)] = alpha gamma += 1 if gamma == n: break C_p.p = list(range(n)) beta = x = 0 while not C_p.is_complete(): # find the first undefined entry while C_p.table[beta][x] == C[beta][x]: x = (x + 1) % (2*len_g) if x == 0: beta = (beta + 1) % n # define a new relator gen = G_p.generators[x//2]**((-1)**(x % 2)) new_rel = transversal[beta]*gen*transversal[C[beta][x]]**-1 perm = T(new_rel) next = G_p.identity for s in H.generator_product(perm, original=True): next = next*T.invert(s)**-1 new_rel = new_rel*next # continue coset enumeration G_p = _factor_group_by_rels(G_p, [new_rel]) C_p.scan_and_fill(0, new_rel) C_p = G_p.coset_enumeration([], strategy="coset_table", draft=C_p, max_cosets=n, incomplete=True) G._fp_presentation = simplify_presentation(G_p) return G._fp_presentation def polycyclic_group(self): """ Return the PolycyclicGroup instance with below parameters: Explanation =========== * ``pc_sequence`` : Polycyclic sequence is formed by collecting all the missing generators between the adjacent groups in the derived series of given permutation group. * ``pc_series`` : Polycyclic series is formed by adding all the missing generators of ``der[i+1]`` in ``der[i]``, where ``der`` represents the derived series. * ``relative_order`` : A list, computed by the ratio of adjacent groups in pc_series. """ from sympy.combinatorics.pc_groups import PolycyclicGroup if not self.is_polycyclic: raise ValueError("The group must be solvable") der = self.derived_series() pc_series = [] pc_sequence = [] relative_order = [] pc_series.append(der[-1]) der.reverse() for i in range(len(der)-1): H = der[i] for g in der[i+1].generators: if g not in H: H = PermutationGroup([g] + H.generators) pc_series.insert(0, H) pc_sequence.insert(0, g) G1 = pc_series[0].order() G2 = pc_series[1].order() relative_order.insert(0, G1 // G2) return PolycyclicGroup(pc_sequence, pc_series, relative_order, collector=None) def _orbit(degree, generators, alpha, action='tuples'): r"""Compute the orbit of alpha `\{g(\alpha) | g \in G\}` as a set. Explanation =========== The time complexity of the algorithm used here is `O(|Orb|*r)` where `|Orb|` is the size of the orbit and ``r`` is the number of generators of the group. For a more detailed analysis, see [1], p.78, [2], pp. 19-21. Here alpha can be a single point, or a list of points. If alpha is a single point, the ordinary orbit is computed. if alpha is a list of points, there are three available options: 'union' - computes the union of the orbits of the points in the list 'tuples' - computes the orbit of the list interpreted as an ordered tuple under the group action ( i.e., g((1, 2, 3)) = (g(1), g(2), g(3)) ) 'sets' - computes the orbit of the list interpreted as a sets Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup, _orbit >>> a = Permutation([1, 2, 0, 4, 5, 6, 3]) >>> G = PermutationGroup([a]) >>> _orbit(G.degree, G.generators, 0) {0, 1, 2} >>> _orbit(G.degree, G.generators, [0, 4], 'union') {0, 1, 2, 3, 4, 5, 6} See Also ======== orbit, orbit_transversal """ if not hasattr(alpha, '__getitem__'): alpha = [alpha] gens = [x._array_form for x in generators] if len(alpha) == 1 or action == 'union': orb = alpha used = [False]*degree for el in alpha: used[el] = True for b in orb: for gen in gens: temp = gen[b] if used[temp] == False: orb.append(temp) used[temp] = True return set(orb) elif action == 'tuples': alpha = tuple(alpha) orb = [alpha] used = {alpha} for b in orb: for gen in gens: temp = tuple([gen[x] for x in b]) if temp not in used: orb.append(temp) used.add(temp) return set(orb) elif action == 'sets': alpha = frozenset(alpha) orb = [alpha] used = {alpha} for b in orb: for gen in gens: temp = frozenset([gen[x] for x in b]) if temp not in used: orb.append(temp) used.add(temp) return {tuple(x) for x in orb} def _orbits(degree, generators): """Compute the orbits of G. If ``rep=False`` it returns a list of sets else it returns a list of representatives of the orbits Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.perm_groups import _orbits >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> _orbits(a.size, [a, b]) [{0, 1, 2}] """ orbs = [] sorted_I = list(range(degree)) I = set(sorted_I) while I: i = sorted_I[0] orb = _orbit(degree, generators, i) orbs.append(orb) # remove all indices that are in this orbit I -= orb sorted_I = [i for i in sorted_I if i not in orb] return orbs def _orbit_transversal(degree, generators, alpha, pairs, af=False, slp=False): r"""Computes a transversal for the orbit of ``alpha`` as a set. Explanation =========== generators generators of the group ``G`` For a permutation group ``G``, a transversal for the orbit `Orb = \{g(\alpha) | g \in G\}` is a set `\{g_\beta | g_\beta(\alpha) = \beta\}` for `\beta \in Orb`. Note that there may be more than one possible transversal. If ``pairs`` is set to ``True``, it returns the list of pairs `(\beta, g_\beta)`. For a proof of correctness, see [1], p.79 if ``af`` is ``True``, the transversal elements are given in array form. If `slp` is `True`, a dictionary `{beta: slp_beta}` is returned for `\beta \in Orb` where `slp_beta` is a list of indices of the generators in `generators` s.t. if `slp_beta = [i_1 ... i_n]` `g_\beta = generators[i_n]*...*generators[i_1]`. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> from sympy.combinatorics.perm_groups import _orbit_transversal >>> G = DihedralGroup(6) >>> _orbit_transversal(G.degree, G.generators, 0, False) [(5), (0 1 2 3 4 5), (0 5)(1 4)(2 3), (0 2 4)(1 3 5), (5)(0 4)(1 3), (0 3)(1 4)(2 5)] """ tr = [(alpha, list(range(degree)))] slp_dict = {alpha: []} used = [False]*degree used[alpha] = True gens = [x._array_form for x in generators] for x, px in tr: px_slp = slp_dict[x] for gen in gens: temp = gen[x] if used[temp] == False: slp_dict[temp] = [gens.index(gen)] + px_slp tr.append((temp, _af_rmul(gen, px))) used[temp] = True if pairs: if not af: tr = [(x, _af_new(y)) for x, y in tr] if not slp: return tr return tr, slp_dict if af: tr = [y for _, y in tr] if not slp: return tr return tr, slp_dict tr = [_af_new(y) for _, y in tr] if not slp: return tr return tr, slp_dict def _stabilizer(degree, generators, alpha): r"""Return the stabilizer subgroup of ``alpha``. Explanation =========== The stabilizer of `\alpha` is the group `G_\alpha = \{g \in G | g(\alpha) = \alpha\}`. For a proof of correctness, see [1], p.79. degree : degree of G generators : generators of G Examples ======== >>> from sympy.combinatorics.perm_groups import _stabilizer >>> from sympy.combinatorics.named_groups import DihedralGroup >>> G = DihedralGroup(6) >>> _stabilizer(G.degree, G.generators, 5) [(5)(0 4)(1 3), (5)] See Also ======== orbit """ orb = [alpha] table = {alpha: list(range(degree))} table_inv = {alpha: list(range(degree))} used = [False]*degree used[alpha] = True gens = [x._array_form for x in generators] stab_gens = [] for b in orb: for gen in gens: temp = gen[b] if used[temp] is False: gen_temp = _af_rmul(gen, table[b]) orb.append(temp) table[temp] = gen_temp table_inv[temp] = _af_invert(gen_temp) used[temp] = True else: schreier_gen = _af_rmuln(table_inv[temp], gen, table[b]) if schreier_gen not in stab_gens: stab_gens.append(schreier_gen) return [_af_new(x) for x in stab_gens] PermGroup = PermutationGroup class SymmetricPermutationGroup(Basic): """ The class defining the lazy form of SymmetricGroup. deg : int """ def __new__(cls, deg): deg = _sympify(deg) obj = Basic.__new__(cls, deg) obj._deg = deg obj._order = None return obj def __contains__(self, i): """Return ``True`` if *i* is contained in SymmetricPermutationGroup. Examples ======== >>> from sympy.combinatorics import Permutation, SymmetricPermutationGroup >>> G = SymmetricPermutationGroup(4) >>> Permutation(1, 2, 3) in G True """ if not isinstance(i, Permutation): raise TypeError("A SymmetricPermutationGroup contains only Permutations as " "elements, not elements of type %s" % type(i)) return i.size == self.degree def order(self): """ Return the order of the SymmetricPermutationGroup. Examples ======== >>> from sympy.combinatorics import SymmetricPermutationGroup >>> G = SymmetricPermutationGroup(4) >>> G.order() 24 """ if self._order is not None: return self._order n = self._deg self._order = factorial(n) return self._order @property def degree(self): """ Return the degree of the SymmetricPermutationGroup. Examples ======== >>> from sympy.combinatorics import SymmetricPermutationGroup >>> G = SymmetricPermutationGroup(4) >>> G.degree 4 """ return self._deg @property def identity(self): ''' Return the identity element of the SymmetricPermutationGroup. Examples ======== >>> from sympy.combinatorics import SymmetricPermutationGroup >>> G = SymmetricPermutationGroup(4) >>> G.identity() (3) ''' return _af_new(list(range(self._deg))) class Coset(Basic): """A left coset of a permutation group with respect to an element. Parameters ========== g : Permutation H : PermutationGroup dir : "+" or "-", If not specified by default it will be "+" here ``dir`` specified the type of coset "+" represent the right coset and "-" represent the left coset. G : PermutationGroup, optional The group which contains *H* as its subgroup and *g* as its element. If not specified, it would automatically become a symmetric group ``SymmetricPermutationGroup(g.size)`` and ``SymmetricPermutationGroup(H.degree)`` if ``g.size`` and ``H.degree`` are matching.``SymmetricPermutationGroup`` is a lazy form of SymmetricGroup used for representation purpose. """ def __new__(cls, g, H, G=None, dir="+"): g = _sympify(g) if not isinstance(g, Permutation): raise NotImplementedError H = _sympify(H) if not isinstance(H, PermutationGroup): raise NotImplementedError if G is not None: G = _sympify(G) if not isinstance(G, PermutationGroup) and not isinstance(G, SymmetricPermutationGroup): raise NotImplementedError if not H.is_subgroup(G): raise ValueError("{} must be a subgroup of {}.".format(H, G)) if g not in G: raise ValueError("{} must be an element of {}.".format(g, G)) else: g_size = g.size h_degree = H.degree if g_size != h_degree: raise ValueError( "The size of the permutation {} and the degree of " "the permutation group {} should be matching " .format(g, H)) G = SymmetricPermutationGroup(g.size) if isinstance(dir, str): dir = Symbol(dir) elif not isinstance(dir, Symbol): raise TypeError("dir must be of type basestring or " "Symbol, not %s" % type(dir)) if str(dir) not in ('+', '-'): raise ValueError("dir must be one of '+' or '-' not %s" % dir) obj = Basic.__new__(cls, g, H, G, dir) obj._dir = dir return obj @property def is_left_coset(self): """ Check if the coset is left coset that is ``gH``. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup, Coset >>> a = Permutation(1, 2) >>> b = Permutation(0, 1) >>> G = PermutationGroup([a, b]) >>> cst = Coset(a, G, dir="-") >>> cst.is_left_coset True """ return str(self._dir) == '-' @property def is_right_coset(self): """ Check if the coset is right coset that is ``Hg``. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup, Coset >>> a = Permutation(1, 2) >>> b = Permutation(0, 1) >>> G = PermutationGroup([a, b]) >>> cst = Coset(a, G, dir="+") >>> cst.is_right_coset True """ return str(self._dir) == '+' def as_list(self): """ Return all the elements of coset in the form of list. """ g = self.args[0] H = self.args[1] cst = [] if str(self._dir) == '+': for h in H.elements: cst.append(h*g) else: for h in H.elements: cst.append(g*h) return cst
2728f15c50a401081edaee5c08abd83a9480b7ab4a174d4589329465e5fd4833
import random from collections import defaultdict from collections.abc import Iterable from functools import reduce from sympy.core.parameters import global_parameters from sympy.core.basic import Atom from sympy.core.expr import Expr from sympy.core.compatibility import \ is_sequence, as_int from sympy.core.numbers import Integer from sympy.core.sympify import _sympify from sympy.matrices import zeros from sympy.polys.polytools import lcm from sympy.utilities.iterables import (flatten, has_variety, minlex, has_dups, runs) from mpmath.libmp.libintmath import ifac from sympy.multipledispatch import dispatch def _af_rmul(a, b): """ Return the product b*a; input and output are array forms. The ith value is a[b[i]]. Examples ======== >>> from sympy.combinatorics.permutations import _af_rmul, Permutation >>> a, b = [1, 0, 2], [0, 2, 1] >>> _af_rmul(a, b) [1, 2, 0] >>> [a[b[i]] for i in range(3)] [1, 2, 0] This handles the operands in reverse order compared to the ``*`` operator: >>> a = Permutation(a) >>> b = Permutation(b) >>> list(a*b) [2, 0, 1] >>> [b(a(i)) for i in range(3)] [2, 0, 1] See Also ======== rmul, _af_rmuln """ return [a[i] for i in b] def _af_rmuln(*abc): """ Given [a, b, c, ...] return the product of ...*c*b*a using array forms. The ith value is a[b[c[i]]]. Examples ======== >>> from sympy.combinatorics.permutations import _af_rmul, Permutation >>> a, b = [1, 0, 2], [0, 2, 1] >>> _af_rmul(a, b) [1, 2, 0] >>> [a[b[i]] for i in range(3)] [1, 2, 0] This handles the operands in reverse order compared to the ``*`` operator: >>> a = Permutation(a); b = Permutation(b) >>> list(a*b) [2, 0, 1] >>> [b(a(i)) for i in range(3)] [2, 0, 1] See Also ======== rmul, _af_rmul """ a = abc m = len(a) if m == 3: p0, p1, p2 = a return [p0[p1[i]] for i in p2] if m == 4: p0, p1, p2, p3 = a return [p0[p1[p2[i]]] for i in p3] if m == 5: p0, p1, p2, p3, p4 = a return [p0[p1[p2[p3[i]]]] for i in p4] if m == 6: p0, p1, p2, p3, p4, p5 = a return [p0[p1[p2[p3[p4[i]]]]] for i in p5] if m == 7: p0, p1, p2, p3, p4, p5, p6 = a return [p0[p1[p2[p3[p4[p5[i]]]]]] for i in p6] if m == 8: p0, p1, p2, p3, p4, p5, p6, p7 = a return [p0[p1[p2[p3[p4[p5[p6[i]]]]]]] for i in p7] if m == 1: return a[0][:] if m == 2: a, b = a return [a[i] for i in b] if m == 0: raise ValueError("String must not be empty") p0 = _af_rmuln(*a[:m//2]) p1 = _af_rmuln(*a[m//2:]) return [p0[i] for i in p1] def _af_parity(pi): """ Computes the parity of a permutation in array form. Explanation =========== The parity of a permutation reflects the parity of the number of inversions in the permutation, i.e., the number of pairs of x and y such that x > y but p[x] < p[y]. Examples ======== >>> from sympy.combinatorics.permutations import _af_parity >>> _af_parity([0, 1, 2, 3]) 0 >>> _af_parity([3, 2, 0, 1]) 1 See Also ======== Permutation """ n = len(pi) a = [0] * n c = 0 for j in range(n): if a[j] == 0: c += 1 a[j] = 1 i = j while pi[i] != j: i = pi[i] a[i] = 1 return (n - c) % 2 def _af_invert(a): """ Finds the inverse, ~A, of a permutation, A, given in array form. Examples ======== >>> from sympy.combinatorics.permutations import _af_invert, _af_rmul >>> A = [1, 2, 0, 3] >>> _af_invert(A) [2, 0, 1, 3] >>> _af_rmul(_, A) [0, 1, 2, 3] See Also ======== Permutation, __invert__ """ inv_form = [0] * len(a) for i, ai in enumerate(a): inv_form[ai] = i return inv_form def _af_pow(a, n): """ Routine for finding powers of a permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation, _af_pow >>> p = Permutation([2, 0, 3, 1]) >>> p.order() 4 >>> _af_pow(p._array_form, 4) [0, 1, 2, 3] """ if n == 0: return list(range(len(a))) if n < 0: return _af_pow(_af_invert(a), -n) if n == 1: return a[:] elif n == 2: b = [a[i] for i in a] elif n == 3: b = [a[a[i]] for i in a] elif n == 4: b = [a[a[a[i]]] for i in a] else: # use binary multiplication b = list(range(len(a))) while 1: if n & 1: b = [b[i] for i in a] n -= 1 if not n: break if n % 4 == 0: a = [a[a[a[i]]] for i in a] n = n // 4 elif n % 2 == 0: a = [a[i] for i in a] n = n // 2 return b def _af_commutes_with(a, b): """ Checks if the two permutations with array forms given by ``a`` and ``b`` commute. Examples ======== >>> from sympy.combinatorics.permutations import _af_commutes_with >>> _af_commutes_with([1, 2, 0], [0, 2, 1]) False See Also ======== Permutation, commutes_with """ return not any(a[b[i]] != b[a[i]] for i in range(len(a) - 1)) class Cycle(dict): """ Wrapper around dict which provides the functionality of a disjoint cycle. Explanation =========== A cycle shows the rule to use to move subsets of elements to obtain a permutation. The Cycle class is more flexible than Permutation in that 1) all elements need not be present in order to investigate how multiple cycles act in sequence and 2) it can contain singletons: >>> from sympy.combinatorics.permutations import Perm, Cycle A Cycle will automatically parse a cycle given as a tuple on the rhs: >>> Cycle(1, 2)(2, 3) (1 3 2) The identity cycle, Cycle(), can be used to start a product: >>> Cycle()(1, 2)(2, 3) (1 3 2) The array form of a Cycle can be obtained by calling the list method (or passing it to the list function) and all elements from 0 will be shown: >>> a = Cycle(1, 2) >>> a.list() [0, 2, 1] >>> list(a) [0, 2, 1] If a larger (or smaller) range is desired use the list method and provide the desired size -- but the Cycle cannot be truncated to a size smaller than the largest element that is out of place: >>> b = Cycle(2, 4)(1, 2)(3, 1, 4)(1, 3) >>> b.list() [0, 2, 1, 3, 4] >>> b.list(b.size + 1) [0, 2, 1, 3, 4, 5] >>> b.list(-1) [0, 2, 1] Singletons are not shown when printing with one exception: the largest element is always shown -- as a singleton if necessary: >>> Cycle(1, 4, 10)(4, 5) (1 5 4 10) >>> Cycle(1, 2)(4)(5)(10) (1 2)(10) The array form can be used to instantiate a Permutation so other properties of the permutation can be investigated: >>> Perm(Cycle(1, 2)(3, 4).list()).transpositions() [(1, 2), (3, 4)] Notes ===== The underlying structure of the Cycle is a dictionary and although the __iter__ method has been redefined to give the array form of the cycle, the underlying dictionary items are still available with the such methods as items(): >>> list(Cycle(1, 2).items()) [(1, 2), (2, 1)] See Also ======== Permutation """ def __missing__(self, arg): """Enter arg into dictionary and return arg.""" return as_int(arg) def __iter__(self): yield from self.list() def __call__(self, *other): """Return product of cycles processed from R to L. Examples ======== >>> from sympy.combinatorics.permutations import Cycle as C >>> C(1, 2)(2, 3) (1 3 2) An instance of a Cycle will automatically parse list-like objects and Permutations that are on the right. It is more flexible than the Permutation in that all elements need not be present: >>> a = C(1, 2) >>> a(2, 3) (1 3 2) >>> a(2, 3)(4, 5) (1 3 2)(4 5) """ rv = Cycle(*other) for k, v in zip(list(self.keys()), [rv[self[k]] for k in self.keys()]): rv[k] = v return rv def list(self, size=None): """Return the cycles as an explicit list starting from 0 up to the greater of the largest value in the cycles and size. Truncation of trailing unmoved items will occur when size is less than the maximum element in the cycle; if this is desired, setting ``size=-1`` will guarantee such trimming. Examples ======== >>> from sympy.combinatorics.permutations import Cycle >>> p = Cycle(2, 3)(4, 5) >>> p.list() [0, 1, 3, 2, 5, 4] >>> p.list(10) [0, 1, 3, 2, 5, 4, 6, 7, 8, 9] Passing a length too small will trim trailing, unchanged elements in the permutation: >>> Cycle(2, 4)(1, 2, 4).list(-1) [0, 2, 1] """ if not self and size is None: raise ValueError('must give size for empty Cycle') if size is not None: big = max([i for i in self.keys() if self[i] != i] + [0]) size = max(size, big + 1) else: size = self.size return [self[i] for i in range(size)] def __repr__(self): """We want it to print as a Cycle, not as a dict. Examples ======== >>> from sympy.combinatorics import Cycle >>> Cycle(1, 2) (1 2) >>> print(_) (1 2) >>> list(Cycle(1, 2).items()) [(1, 2), (2, 1)] """ if not self: return 'Cycle()' cycles = Permutation(self).cyclic_form s = ''.join(str(tuple(c)) for c in cycles) big = self.size - 1 if not any(i == big for c in cycles for i in c): s += '(%s)' % big return 'Cycle%s' % s def __str__(self): """We want it to be printed in a Cycle notation with no comma in-between. Examples ======== >>> from sympy.combinatorics import Cycle >>> Cycle(1, 2) (1 2) >>> Cycle(1, 2, 4)(5, 6) (1 2 4)(5 6) """ if not self: return '()' cycles = Permutation(self).cyclic_form s = ''.join(str(tuple(c)) for c in cycles) big = self.size - 1 if not any(i == big for c in cycles for i in c): s += '(%s)' % big s = s.replace(',', '') return s def __init__(self, *args): """Load up a Cycle instance with the values for the cycle. Examples ======== >>> from sympy.combinatorics.permutations import Cycle >>> Cycle(1, 2, 6) (1 2 6) """ if not args: return if len(args) == 1: if isinstance(args[0], Permutation): for c in args[0].cyclic_form: self.update(self(*c)) return elif isinstance(args[0], Cycle): for k, v in args[0].items(): self[k] = v return args = [as_int(a) for a in args] if any(i < 0 for i in args): raise ValueError('negative integers are not allowed in a cycle.') if has_dups(args): raise ValueError('All elements must be unique in a cycle.') for i in range(-len(args), 0): self[args[i]] = args[i + 1] @property def size(self): if not self: return 0 return max(self.keys()) + 1 def copy(self): return Cycle(self) class Permutation(Atom): """ A permutation, alternatively known as an 'arrangement number' or 'ordering' is an arrangement of the elements of an ordered list into a one-to-one mapping with itself. The permutation of a given arrangement is given by indicating the positions of the elements after re-arrangement [2]_. For example, if one started with elements [x, y, a, b] (in that order) and they were reordered as [x, y, b, a] then the permutation would be [0, 1, 3, 2]. Notice that (in SymPy) the first element is always referred to as 0 and the permutation uses the indices of the elements in the original ordering, not the elements (a, b, etc...) themselves. >>> from sympy.combinatorics import Permutation >>> from sympy.interactive import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) Permutations Notation ===================== Permutations are commonly represented in disjoint cycle or array forms. Array Notation and 2-line Form ------------------------------------ In the 2-line form, the elements and their final positions are shown as a matrix with 2 rows: [0 1 2 ... n-1] [p(0) p(1) p(2) ... p(n-1)] Since the first line is always range(n), where n is the size of p, it is sufficient to represent the permutation by the second line, referred to as the "array form" of the permutation. This is entered in brackets as the argument to the Permutation class: >>> p = Permutation([0, 2, 1]); p Permutation([0, 2, 1]) Given i in range(p.size), the permutation maps i to i^p >>> [i^p for i in range(p.size)] [0, 2, 1] The composite of two permutations p*q means first apply p, then q, so i^(p*q) = (i^p)^q which is i^p^q according to Python precedence rules: >>> q = Permutation([2, 1, 0]) >>> [i^p^q for i in range(3)] [2, 0, 1] >>> [i^(p*q) for i in range(3)] [2, 0, 1] One can use also the notation p(i) = i^p, but then the composition rule is (p*q)(i) = q(p(i)), not p(q(i)): >>> [(p*q)(i) for i in range(p.size)] [2, 0, 1] >>> [q(p(i)) for i in range(p.size)] [2, 0, 1] >>> [p(q(i)) for i in range(p.size)] [1, 2, 0] Disjoint Cycle Notation ----------------------- In disjoint cycle notation, only the elements that have shifted are indicated. In the above case, the 2 and 1 switched places. This can be entered in two ways: >>> Permutation(1, 2) == Permutation([[1, 2]]) == p True Only the relative ordering of elements in a cycle matter: >>> Permutation(1,2,3) == Permutation(2,3,1) == Permutation(3,1,2) True The disjoint cycle notation is convenient when representing permutations that have several cycles in them: >>> Permutation(1, 2)(3, 5) == Permutation([[1, 2], [3, 5]]) True It also provides some economy in entry when computing products of permutations that are written in disjoint cycle notation: >>> Permutation(1, 2)(1, 3)(2, 3) Permutation([0, 3, 2, 1]) >>> _ == Permutation([[1, 2]])*Permutation([[1, 3]])*Permutation([[2, 3]]) True Caution: when the cycles have common elements between them then the order in which the permutations are applied matters. The convention is that the permutations are applied from *right to left*. In the following, the transposition of elements 2 and 3 is followed by the transposition of elements 1 and 2: >>> Permutation(1, 2)(2, 3) == Permutation([(1, 2), (2, 3)]) True >>> Permutation(1, 2)(2, 3).list() [0, 3, 1, 2] If the first and second elements had been swapped first, followed by the swapping of the second and third, the result would have been [0, 2, 3, 1]. If, for some reason, you want to apply the cycles in the order they are entered, you can simply reverse the order of cycles: >>> Permutation([(1, 2), (2, 3)][::-1]).list() [0, 2, 3, 1] Entering a singleton in a permutation is a way to indicate the size of the permutation. The ``size`` keyword can also be used. Array-form entry: >>> Permutation([[1, 2], [9]]) Permutation([0, 2, 1], size=10) >>> Permutation([[1, 2]], size=10) Permutation([0, 2, 1], size=10) Cyclic-form entry: >>> Permutation(1, 2, size=10) Permutation([0, 2, 1], size=10) >>> Permutation(9)(1, 2) Permutation([0, 2, 1], size=10) Caution: no singleton containing an element larger than the largest in any previous cycle can be entered. This is an important difference in how Permutation and Cycle handle the __call__ syntax. A singleton argument at the start of a Permutation performs instantiation of the Permutation and is permitted: >>> Permutation(5) Permutation([], size=6) A singleton entered after instantiation is a call to the permutation -- a function call -- and if the argument is out of range it will trigger an error. For this reason, it is better to start the cycle with the singleton: The following fails because there is no element 3: >>> Permutation(1, 2)(3) Traceback (most recent call last): ... IndexError: list index out of range This is ok: only the call to an out of range singleton is prohibited; otherwise the permutation autosizes: >>> Permutation(3)(1, 2) Permutation([0, 2, 1, 3]) >>> Permutation(1, 2)(3, 4) == Permutation(3, 4)(1, 2) True Equality testing ---------------- The array forms must be the same in order for permutations to be equal: >>> Permutation([1, 0, 2, 3]) == Permutation([1, 0]) False Identity Permutation -------------------- The identity permutation is a permutation in which no element is out of place. It can be entered in a variety of ways. All the following create an identity permutation of size 4: >>> I = Permutation([0, 1, 2, 3]) >>> all(p == I for p in [ ... Permutation(3), ... Permutation(range(4)), ... Permutation([], size=4), ... Permutation(size=4)]) True Watch out for entering the range *inside* a set of brackets (which is cycle notation): >>> I == Permutation([range(4)]) False Permutation Printing ==================== There are a few things to note about how Permutations are printed. 1) If you prefer one form (array or cycle) over another, you can set ``init_printing`` with the ``perm_cyclic`` flag. >>> from sympy import init_printing >>> p = Permutation(1, 2)(4, 5)(3, 4) >>> p Permutation([0, 2, 1, 4, 5, 3]) >>> init_printing(perm_cyclic=True, pretty_print=False) >>> p (1 2)(3 4 5) 2) Regardless of the setting, a list of elements in the array for cyclic form can be obtained and either of those can be copied and supplied as the argument to Permutation: >>> p.array_form [0, 2, 1, 4, 5, 3] >>> p.cyclic_form [[1, 2], [3, 4, 5]] >>> Permutation(_) == p True 3) Printing is economical in that as little as possible is printed while retaining all information about the size of the permutation: >>> init_printing(perm_cyclic=False, pretty_print=False) >>> Permutation([1, 0, 2, 3]) Permutation([1, 0, 2, 3]) >>> Permutation([1, 0, 2, 3], size=20) Permutation([1, 0], size=20) >>> Permutation([1, 0, 2, 4, 3, 5, 6], size=20) Permutation([1, 0, 2, 4, 3], size=20) >>> p = Permutation([1, 0, 2, 3]) >>> init_printing(perm_cyclic=True, pretty_print=False) >>> p (3)(0 1) >>> init_printing(perm_cyclic=False, pretty_print=False) The 2 was not printed but it is still there as can be seen with the array_form and size methods: >>> p.array_form [1, 0, 2, 3] >>> p.size 4 Short introduction to other methods =================================== The permutation can act as a bijective function, telling what element is located at a given position >>> q = Permutation([5, 2, 3, 4, 1, 0]) >>> q.array_form[1] # the hard way 2 >>> q(1) # the easy way 2 >>> {i: q(i) for i in range(q.size)} # showing the bijection {0: 5, 1: 2, 2: 3, 3: 4, 4: 1, 5: 0} The full cyclic form (including singletons) can be obtained: >>> p.full_cyclic_form [[0, 1], [2], [3]] Any permutation can be factored into transpositions of pairs of elements: >>> Permutation([[1, 2], [3, 4, 5]]).transpositions() [(1, 2), (3, 5), (3, 4)] >>> Permutation.rmul(*[Permutation([ti], size=6) for ti in _]).cyclic_form [[1, 2], [3, 4, 5]] The number of permutations on a set of n elements is given by n! and is called the cardinality. >>> p.size 4 >>> p.cardinality 24 A given permutation has a rank among all the possible permutations of the same elements, but what that rank is depends on how the permutations are enumerated. (There are a number of different methods of doing so.) The lexicographic rank is given by the rank method and this rank is used to increment a permutation with addition/subtraction: >>> p.rank() 6 >>> p + 1 Permutation([1, 0, 3, 2]) >>> p.next_lex() Permutation([1, 0, 3, 2]) >>> _.rank() 7 >>> p.unrank_lex(p.size, rank=7) Permutation([1, 0, 3, 2]) The product of two permutations p and q is defined as their composition as functions, (p*q)(i) = q(p(i)) [6]_. >>> p = Permutation([1, 0, 2, 3]) >>> q = Permutation([2, 3, 1, 0]) >>> list(q*p) [2, 3, 0, 1] >>> list(p*q) [3, 2, 1, 0] >>> [q(p(i)) for i in range(p.size)] [3, 2, 1, 0] The permutation can be 'applied' to any list-like object, not only Permutations: >>> p(['zero', 'one', 'four', 'two']) ['one', 'zero', 'four', 'two'] >>> p('zo42') ['o', 'z', '4', '2'] If you have a list of arbitrary elements, the corresponding permutation can be found with the from_sequence method: >>> Permutation.from_sequence('SymPy') Permutation([1, 3, 2, 0, 4]) Checking if a Permutation is contained in a Group ================================================= Generally if you have a group of permutations G on n symbols, and you're checking if a permutation on less than n symbols is part of that group, the check will fail. Here is an example for n=5 and we check if the cycle (1,2,3) is in G: >>> from sympy import init_printing >>> init_printing(perm_cyclic=True, pretty_print=False) >>> from sympy.combinatorics import Cycle, Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> G = PermutationGroup(Cycle(2, 3)(4, 5), Cycle(1, 2, 3, 4, 5)) >>> p1 = Permutation(Cycle(2, 5, 3)) >>> p2 = Permutation(Cycle(1, 2, 3)) >>> a1 = Permutation(Cycle(1, 2, 3).list(6)) >>> a2 = Permutation(Cycle(1, 2, 3)(5)) >>> a3 = Permutation(Cycle(1, 2, 3),size=6) >>> for p in [p1,p2,a1,a2,a3]: p, G.contains(p) ((2 5 3), True) ((1 2 3), False) ((5)(1 2 3), True) ((5)(1 2 3), True) ((5)(1 2 3), True) The check for p2 above will fail. Checking if p1 is in G works because SymPy knows G is a group on 5 symbols, and p1 is also on 5 symbols (its largest element is 5). For ``a1``, the ``.list(6)`` call will extend the permutation to 5 symbols, so the test will work as well. In the case of ``a2`` the permutation is being extended to 5 symbols by using a singleton, and in the case of ``a3`` it's extended through the constructor argument ``size=6``. There is another way to do this, which is to tell the ``contains`` method that the number of symbols the group is on doesn't need to match perfectly the number of symbols for the permutation: >>> G.contains(p2,strict=False) True This can be via the ``strict`` argument to the ``contains`` method, and SymPy will try to extend the permutation on its own and then perform the containment check. See Also ======== Cycle References ========== .. [1] Skiena, S. 'Permutations.' 1.1 in Implementing Discrete Mathematics Combinatorics and Graph Theory with Mathematica. Reading, MA: Addison-Wesley, pp. 3-16, 1990. .. [2] Knuth, D. E. The Art of Computer Programming, Vol. 4: Combinatorial Algorithms, 1st ed. Reading, MA: Addison-Wesley, 2011. .. [3] Wendy Myrvold and Frank Ruskey. 2001. Ranking and unranking permutations in linear time. Inf. Process. Lett. 79, 6 (September 2001), 281-284. DOI=10.1016/S0020-0190(01)00141-7 .. [4] D. L. Kreher, D. R. Stinson 'Combinatorial Algorithms' CRC Press, 1999 .. [5] Graham, R. L.; Knuth, D. E.; and Patashnik, O. Concrete Mathematics: A Foundation for Computer Science, 2nd ed. Reading, MA: Addison-Wesley, 1994. .. [6] https://en.wikipedia.org/wiki/Permutation#Product_and_inverse .. [7] https://en.wikipedia.org/wiki/Lehmer_code """ is_Permutation = True _array_form = None _cyclic_form = None _cycle_structure = None _size = None _rank = None def __new__(cls, *args, size=None, **kwargs): """ Constructor for the Permutation object from a list or a list of lists in which all elements of the permutation may appear only once. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.interactive import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) Permutations entered in array-form are left unaltered: >>> Permutation([0, 2, 1]) Permutation([0, 2, 1]) Permutations entered in cyclic form are converted to array form; singletons need not be entered, but can be entered to indicate the largest element: >>> Permutation([[4, 5, 6], [0, 1]]) Permutation([1, 0, 2, 3, 5, 6, 4]) >>> Permutation([[4, 5, 6], [0, 1], [19]]) Permutation([1, 0, 2, 3, 5, 6, 4], size=20) All manipulation of permutations assumes that the smallest element is 0 (in keeping with 0-based indexing in Python) so if the 0 is missing when entering a permutation in array form, an error will be raised: >>> Permutation([2, 1]) Traceback (most recent call last): ... ValueError: Integers 0 through 2 must be present. If a permutation is entered in cyclic form, it can be entered without singletons and the ``size`` specified so those values can be filled in, otherwise the array form will only extend to the maximum value in the cycles: >>> Permutation([[1, 4], [3, 5, 2]], size=10) Permutation([0, 4, 3, 5, 1, 2], size=10) >>> _.array_form [0, 4, 3, 5, 1, 2, 6, 7, 8, 9] """ if size is not None: size = int(size) #a) () #b) (1) = identity #c) (1, 2) = cycle #d) ([1, 2, 3]) = array form #e) ([[1, 2]]) = cyclic form #f) (Cycle) = conversion to permutation #g) (Permutation) = adjust size or return copy ok = True if not args: # a return cls._af_new(list(range(size or 0))) elif len(args) > 1: # c return cls._af_new(Cycle(*args).list(size)) if len(args) == 1: a = args[0] if isinstance(a, cls): # g if size is None or size == a.size: return a return cls(a.array_form, size=size) if isinstance(a, Cycle): # f return cls._af_new(a.list(size)) if not is_sequence(a): # b if size is not None and a + 1 > size: raise ValueError('size is too small when max is %s' % a) return cls._af_new(list(range(a + 1))) if has_variety(is_sequence(ai) for ai in a): ok = False else: ok = False if not ok: raise ValueError("Permutation argument must be a list of ints, " "a list of lists, Permutation or Cycle.") # safe to assume args are valid; this also makes a copy # of the args args = list(args[0]) is_cycle = args and is_sequence(args[0]) if is_cycle: # e args = [[int(i) for i in c] for c in args] else: # d args = [int(i) for i in args] # if there are n elements present, 0, 1, ..., n-1 should be present # unless a cycle notation has been provided. A 0 will be added # for convenience in case one wants to enter permutations where # counting starts from 1. temp = flatten(args) if has_dups(temp) and not is_cycle: raise ValueError('there were repeated elements.') temp = set(temp) if not is_cycle: if temp != set(range(len(temp))): raise ValueError('Integers 0 through %s must be present.' % max(temp)) if size is not None and temp and max(temp) + 1 > size: raise ValueError('max element should not exceed %s' % (size - 1)) if is_cycle: # it's not necessarily canonical so we won't store # it -- use the array form instead c = Cycle() for ci in args: c = c(*ci) aform = c.list() else: aform = list(args) if size and size > len(aform): # don't allow for truncation of permutation which # might split a cycle and lead to an invalid aform # but do allow the permutation size to be increased aform.extend(list(range(len(aform), size))) return cls._af_new(aform) @classmethod def _af_new(cls, perm): """A method to produce a Permutation object from a list; the list is bound to the _array_form attribute, so it must not be modified; this method is meant for internal use only; the list ``a`` is supposed to be generated as a temporary value in a method, so p = Perm._af_new(a) is the only object to hold a reference to ``a``:: Examples ======== >>> from sympy.combinatorics.permutations import Perm >>> from sympy.interactive import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> a = [2, 1, 3, 0] >>> p = Perm._af_new(a) >>> p Permutation([2, 1, 3, 0]) """ p = super().__new__(cls) p._array_form = perm p._size = len(perm) return p def _hashable_content(self): # the array_form (a list) is the Permutation arg, so we need to # return a tuple, instead return tuple(self.array_form) @property def array_form(self): """ Return a copy of the attribute _array_form Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([[2, 0], [3, 1]]) >>> p.array_form [2, 3, 0, 1] >>> Permutation([[2, 0, 3, 1]]).array_form [3, 2, 0, 1] >>> Permutation([2, 0, 3, 1]).array_form [2, 0, 3, 1] >>> Permutation([[1, 2], [4, 5]]).array_form [0, 2, 1, 3, 5, 4] """ return self._array_form[:] def list(self, size=None): """Return the permutation as an explicit list, possibly trimming unmoved elements if size is less than the maximum element in the permutation; if this is desired, setting ``size=-1`` will guarantee such trimming. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation(2, 3)(4, 5) >>> p.list() [0, 1, 3, 2, 5, 4] >>> p.list(10) [0, 1, 3, 2, 5, 4, 6, 7, 8, 9] Passing a length too small will trim trailing, unchanged elements in the permutation: >>> Permutation(2, 4)(1, 2, 4).list(-1) [0, 2, 1] >>> Permutation(3).list(-1) [] """ if not self and size is None: raise ValueError('must give size for empty Cycle') rv = self.array_form if size is not None: if size > self.size: rv.extend(list(range(self.size, size))) else: # find first value from rhs where rv[i] != i i = self.size - 1 while rv: if rv[-1] != i: break rv.pop() i -= 1 return rv @property def cyclic_form(self): """ This is used to convert to the cyclic notation from the canonical notation. Singletons are omitted. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 3, 1, 2]) >>> p.cyclic_form [[1, 3, 2]] >>> Permutation([1, 0, 2, 4, 3, 5]).cyclic_form [[0, 1], [3, 4]] See Also ======== array_form, full_cyclic_form """ if self._cyclic_form is not None: return list(self._cyclic_form) array_form = self.array_form unchecked = [True] * len(array_form) cyclic_form = [] for i in range(len(array_form)): if unchecked[i]: cycle = [] cycle.append(i) unchecked[i] = False j = i while unchecked[array_form[j]]: j = array_form[j] cycle.append(j) unchecked[j] = False if len(cycle) > 1: cyclic_form.append(cycle) assert cycle == list(minlex(cycle)) cyclic_form.sort() self._cyclic_form = cyclic_form[:] return cyclic_form @property def full_cyclic_form(self): """Return permutation in cyclic form including singletons. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> Permutation([0, 2, 1]).full_cyclic_form [[0], [1, 2]] """ need = set(range(self.size)) - set(flatten(self.cyclic_form)) rv = self.cyclic_form + [[i] for i in need] rv.sort() return rv @property def size(self): """ Returns the number of elements in the permutation. Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation([[3, 2], [0, 1]]).size 4 See Also ======== cardinality, length, order, rank """ return self._size def support(self): """Return the elements in permutation, P, for which P[i] != i. Examples ======== >>> from sympy.combinatorics import Permutation >>> p = Permutation([[3, 2], [0, 1], [4]]) >>> p.array_form [1, 0, 3, 2, 4] >>> p.support() [0, 1, 2, 3] """ a = self.array_form return [i for i, e in enumerate(a) if a[i] != i] def __add__(self, other): """Return permutation that is other higher in rank than self. The rank is the lexicographical rank, with the identity permutation having rank of 0. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> I = Permutation([0, 1, 2, 3]) >>> a = Permutation([2, 1, 3, 0]) >>> I + a.rank() == a True See Also ======== __sub__, inversion_vector """ rank = (self.rank() + other) % self.cardinality rv = self.unrank_lex(self.size, rank) rv._rank = rank return rv def __sub__(self, other): """Return the permutation that is other lower in rank than self. See Also ======== __add__ """ return self.__add__(-other) @staticmethod def rmul(*args): """ Return product of Permutations [a, b, c, ...] as the Permutation whose ith value is a(b(c(i))). a, b, c, ... can be Permutation objects or tuples. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> a, b = [1, 0, 2], [0, 2, 1] >>> a = Permutation(a); b = Permutation(b) >>> list(Permutation.rmul(a, b)) [1, 2, 0] >>> [a(b(i)) for i in range(3)] [1, 2, 0] This handles the operands in reverse order compared to the ``*`` operator: >>> a = Permutation(a); b = Permutation(b) >>> list(a*b) [2, 0, 1] >>> [b(a(i)) for i in range(3)] [2, 0, 1] Notes ===== All items in the sequence will be parsed by Permutation as necessary as long as the first item is a Permutation: >>> Permutation.rmul(a, [0, 2, 1]) == Permutation.rmul(a, b) True The reverse order of arguments will raise a TypeError. """ rv = args[0] for i in range(1, len(args)): rv = args[i]*rv return rv @classmethod def rmul_with_af(cls, *args): """ same as rmul, but the elements of args are Permutation objects which have _array_form """ a = [x._array_form for x in args] rv = cls._af_new(_af_rmuln(*a)) return rv def mul_inv(self, other): """ other*~self, self and other have _array_form """ a = _af_invert(self._array_form) b = other._array_form return self._af_new(_af_rmul(a, b)) def __rmul__(self, other): """This is needed to coerce other to Permutation in rmul.""" cls = type(self) return cls(other)*self def __mul__(self, other): """ Return the product a*b as a Permutation; the ith value is b(a(i)). Examples ======== >>> from sympy.combinatorics.permutations import _af_rmul, Permutation >>> a, b = [1, 0, 2], [0, 2, 1] >>> a = Permutation(a); b = Permutation(b) >>> list(a*b) [2, 0, 1] >>> [b(a(i)) for i in range(3)] [2, 0, 1] This handles operands in reverse order compared to _af_rmul and rmul: >>> al = list(a); bl = list(b) >>> _af_rmul(al, bl) [1, 2, 0] >>> [al[bl[i]] for i in range(3)] [1, 2, 0] It is acceptable for the arrays to have different lengths; the shorter one will be padded to match the longer one: >>> from sympy.interactive import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> b*Permutation([1, 0]) Permutation([1, 2, 0]) >>> Permutation([1, 0])*b Permutation([2, 0, 1]) It is also acceptable to allow coercion to handle conversion of a single list to the left of a Permutation: >>> [0, 1]*a # no change: 2-element identity Permutation([1, 0, 2]) >>> [[0, 1]]*a # exchange first two elements Permutation([0, 1, 2]) You cannot use more than 1 cycle notation in a product of cycles since coercion can only handle one argument to the left. To handle multiple cycles it is convenient to use Cycle instead of Permutation: >>> [[1, 2]]*[[2, 3]]*Permutation([]) # doctest: +SKIP >>> from sympy.combinatorics.permutations import Cycle >>> Cycle(1, 2)(2, 3) (1 3 2) """ from sympy.combinatorics.perm_groups import PermutationGroup, Coset if isinstance(other, PermutationGroup): return Coset(self, other, dir='-') a = self.array_form # __rmul__ makes sure the other is a Permutation b = other.array_form if not b: perm = a else: b.extend(list(range(len(b), len(a)))) perm = [b[i] for i in a] + b[len(a):] return self._af_new(perm) def commutes_with(self, other): """ Checks if the elements are commuting. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> a = Permutation([1, 4, 3, 0, 2, 5]) >>> b = Permutation([0, 1, 2, 3, 4, 5]) >>> a.commutes_with(b) True >>> b = Permutation([2, 3, 5, 4, 1, 0]) >>> a.commutes_with(b) False """ a = self.array_form b = other.array_form return _af_commutes_with(a, b) def __pow__(self, n): """ Routine for finding powers of a permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.interactive import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([2, 0, 3, 1]) >>> p.order() 4 >>> p**4 Permutation([0, 1, 2, 3]) """ if isinstance(n, Permutation): raise NotImplementedError( 'p**p is not defined; do you mean p^p (conjugate)?') n = int(n) return self._af_new(_af_pow(self.array_form, n)) def __rxor__(self, i): """Return self(i) when ``i`` is an int. Examples ======== >>> from sympy.combinatorics import Permutation >>> p = Permutation(1, 2, 9) >>> 2^p == p(2) == 9 True """ if int(i) == i: return self(i) else: raise NotImplementedError( "i^p = p(i) when i is an integer, not %s." % i) def __xor__(self, h): """Return the conjugate permutation ``~h*self*h` `. Explanation =========== If ``a`` and ``b`` are conjugates, ``a = h*b*~h`` and ``b = ~h*a*h`` and both have the same cycle structure. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation(1, 2, 9) >>> q = Permutation(6, 9, 8) >>> p*q != q*p True Calculate and check properties of the conjugate: >>> c = p^q >>> c == ~q*p*q and p == q*c*~q True The expression q^p^r is equivalent to q^(p*r): >>> r = Permutation(9)(4, 6, 8) >>> q^p^r == q^(p*r) True If the term to the left of the conjugate operator, i, is an integer then this is interpreted as selecting the ith element from the permutation to the right: >>> all(i^p == p(i) for i in range(p.size)) True Note that the * operator as higher precedence than the ^ operator: >>> q^r*p^r == q^(r*p)^r == Permutation(9)(1, 6, 4) True Notes ===== In Python the precedence rule is p^q^r = (p^q)^r which differs in general from p^(q^r) >>> q^p^r (9)(1 4 8) >>> q^(p^r) (9)(1 8 6) For a given r and p, both of the following are conjugates of p: ~r*p*r and r*p*~r. But these are not necessarily the same: >>> ~r*p*r == r*p*~r True >>> p = Permutation(1, 2, 9)(5, 6) >>> ~r*p*r == r*p*~r False The conjugate ~r*p*r was chosen so that ``p^q^r`` would be equivalent to ``p^(q*r)`` rather than ``p^(r*q)``. To obtain r*p*~r, pass ~r to this method: >>> p^~r == r*p*~r True """ if self.size != h.size: raise ValueError("The permutations must be of equal size.") a = [None]*self.size h = h._array_form p = self._array_form for i in range(self.size): a[h[i]] = h[p[i]] return self._af_new(a) def transpositions(self): """ Return the permutation decomposed into a list of transpositions. Explanation =========== It is always possible to express a permutation as the product of transpositions, see [1] Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([[1, 2, 3], [0, 4, 5, 6, 7]]) >>> t = p.transpositions() >>> t [(0, 7), (0, 6), (0, 5), (0, 4), (1, 3), (1, 2)] >>> print(''.join(str(c) for c in t)) (0, 7)(0, 6)(0, 5)(0, 4)(1, 3)(1, 2) >>> Permutation.rmul(*[Permutation([ti], size=p.size) for ti in t]) == p True References ========== .. [1] https://en.wikipedia.org/wiki/Transposition_%28mathematics%29#Properties """ a = self.cyclic_form res = [] for x in a: nx = len(x) if nx == 2: res.append(tuple(x)) elif nx > 2: first = x[0] for y in x[nx - 1:0:-1]: res.append((first, y)) return res @classmethod def from_sequence(self, i, key=None): """Return the permutation needed to obtain ``i`` from the sorted elements of ``i``. If custom sorting is desired, a key can be given. Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation.from_sequence('SymPy') (4)(0 1 3) >>> _(sorted("SymPy")) ['S', 'y', 'm', 'P', 'y'] >>> Permutation.from_sequence('SymPy', key=lambda x: x.lower()) (4)(0 2)(1 3) """ ic = list(zip(i, list(range(len(i))))) if key: ic.sort(key=lambda x: key(x[0])) else: ic.sort() return ~Permutation([i[1] for i in ic]) def __invert__(self): """ Return the inverse of the permutation. A permutation multiplied by its inverse is the identity permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.interactive import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([[2, 0], [3, 1]]) >>> ~p Permutation([2, 3, 0, 1]) >>> _ == p**-1 True >>> p*~p == ~p*p == Permutation([0, 1, 2, 3]) True """ return self._af_new(_af_invert(self._array_form)) def __iter__(self): """Yield elements from array form. Examples ======== >>> from sympy.combinatorics import Permutation >>> list(Permutation(range(3))) [0, 1, 2] """ yield from self.array_form def __repr__(self): from sympy.printing.repr import srepr return srepr(self) def __call__(self, *i): """ Allows applying a permutation instance as a bijective function. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([[2, 0], [3, 1]]) >>> p.array_form [2, 3, 0, 1] >>> [p(i) for i in range(4)] [2, 3, 0, 1] If an array is given then the permutation selects the items from the array (i.e. the permutation is applied to the array): >>> from sympy.abc import x >>> p([x, 1, 0, x**2]) [0, x**2, x, 1] """ # list indices can be Integer or int; leave this # as it is (don't test or convert it) because this # gets called a lot and should be fast if len(i) == 1: i = i[0] if not isinstance(i, Iterable): i = as_int(i) if i < 0 or i > self.size: raise TypeError( "{} should be an integer between 0 and {}" .format(i, self.size-1)) return self._array_form[i] # P([a, b, c]) if len(i) != self.size: raise TypeError( "{} should have the length {}.".format(i, self.size)) return [i[j] for j in self._array_form] # P(1, 2, 3) return self*Permutation(Cycle(*i), size=self.size) def atoms(self): """ Returns all the elements of a permutation Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation([0, 1, 2, 3, 4, 5]).atoms() {0, 1, 2, 3, 4, 5} >>> Permutation([[0, 1], [2, 3], [4, 5]]).atoms() {0, 1, 2, 3, 4, 5} """ return set(self.array_form) def apply(self, i): r"""Apply the permutation to an expression. Parameters ========== i : Expr It should be an integer between $0$ and $n-1$ where $n$ is the size of the permutation. If it is a symbol or a symbolic expression that can have integer values, an ``AppliedPermutation`` object will be returned which can represent an unevaluated function. Notes ===== Any permutation can be defined as a bijective function $\sigma : \{ 0, 1, ..., n-1 \} \rightarrow \{ 0, 1, ..., n-1 \}$ where $n$ denotes the size of the permutation. The definition may even be extended for any set with distinctive elements, such that the permutation can even be applied for real numbers or such, however, it is not implemented for now for computational reasons and the integrity with the group theory module. This function is similar to the ``__call__`` magic, however, ``__call__`` magic already has some other applications like permuting an array or attatching new cycles, which would not always be mathematically consistent. This also guarantees that the return type is a SymPy integer, which guarantees the safety to use assumptions. """ i = _sympify(i) if i.is_integer is False: raise NotImplementedError("{} should be an integer.".format(i)) n = self.size if (i < 0) == True or (i >= n) == True: raise NotImplementedError( "{} should be an integer between 0 and {}".format(i, n-1)) if i.is_Integer: return Integer(self._array_form[i]) return AppliedPermutation(self, i) def next_lex(self): """ Returns the next permutation in lexicographical order. If self is the last permutation in lexicographical order it returns None. See [4] section 2.4. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([2, 3, 1, 0]) >>> p = Permutation([2, 3, 1, 0]); p.rank() 17 >>> p = p.next_lex(); p.rank() 18 See Also ======== rank, unrank_lex """ perm = self.array_form[:] n = len(perm) i = n - 2 while perm[i + 1] < perm[i]: i -= 1 if i == -1: return None else: j = n - 1 while perm[j] < perm[i]: j -= 1 perm[j], perm[i] = perm[i], perm[j] i += 1 j = n - 1 while i < j: perm[j], perm[i] = perm[i], perm[j] i += 1 j -= 1 return self._af_new(perm) @classmethod def unrank_nonlex(self, n, r): """ This is a linear time unranking algorithm that does not respect lexicographic order [3]. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.interactive import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> Permutation.unrank_nonlex(4, 5) Permutation([2, 0, 3, 1]) >>> Permutation.unrank_nonlex(4, -1) Permutation([0, 1, 2, 3]) See Also ======== next_nonlex, rank_nonlex """ def _unrank1(n, r, a): if n > 0: a[n - 1], a[r % n] = a[r % n], a[n - 1] _unrank1(n - 1, r//n, a) id_perm = list(range(n)) n = int(n) r = r % ifac(n) _unrank1(n, r, id_perm) return self._af_new(id_perm) def rank_nonlex(self, inv_perm=None): """ This is a linear time ranking algorithm that does not enforce lexicographic order [3]. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.rank_nonlex() 23 See Also ======== next_nonlex, unrank_nonlex """ def _rank1(n, perm, inv_perm): if n == 1: return 0 s = perm[n - 1] t = inv_perm[n - 1] perm[n - 1], perm[t] = perm[t], s inv_perm[n - 1], inv_perm[s] = inv_perm[s], t return s + n*_rank1(n - 1, perm, inv_perm) if inv_perm is None: inv_perm = (~self).array_form if not inv_perm: return 0 perm = self.array_form[:] r = _rank1(len(perm), perm, inv_perm) return r def next_nonlex(self): """ Returns the next permutation in nonlex order [3]. If self is the last permutation in this order it returns None. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.interactive import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([2, 0, 3, 1]); p.rank_nonlex() 5 >>> p = p.next_nonlex(); p Permutation([3, 0, 1, 2]) >>> p.rank_nonlex() 6 See Also ======== rank_nonlex, unrank_nonlex """ r = self.rank_nonlex() if r == ifac(self.size) - 1: return None return self.unrank_nonlex(self.size, r + 1) def rank(self): """ Returns the lexicographic rank of the permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.rank() 0 >>> p = Permutation([3, 2, 1, 0]) >>> p.rank() 23 See Also ======== next_lex, unrank_lex, cardinality, length, order, size """ if not self._rank is None: return self._rank rank = 0 rho = self.array_form[:] n = self.size - 1 size = n + 1 psize = int(ifac(n)) for j in range(size - 1): rank += rho[j]*psize for i in range(j + 1, size): if rho[i] > rho[j]: rho[i] -= 1 psize //= n n -= 1 self._rank = rank return rank @property def cardinality(self): """ Returns the number of all possible permutations. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.cardinality 24 See Also ======== length, order, rank, size """ return int(ifac(self.size)) def parity(self): """ Computes the parity of a permutation. Explanation =========== The parity of a permutation reflects the parity of the number of inversions in the permutation, i.e., the number of pairs of x and y such that ``x > y`` but ``p[x] < p[y]``. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.parity() 0 >>> p = Permutation([3, 2, 0, 1]) >>> p.parity() 1 See Also ======== _af_parity """ if self._cyclic_form is not None: return (self.size - self.cycles) % 2 return _af_parity(self.array_form) @property def is_even(self): """ Checks if a permutation is even. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.is_even True >>> p = Permutation([3, 2, 1, 0]) >>> p.is_even True See Also ======== is_odd """ return not self.is_odd @property def is_odd(self): """ Checks if a permutation is odd. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.is_odd False >>> p = Permutation([3, 2, 0, 1]) >>> p.is_odd True See Also ======== is_even """ return bool(self.parity() % 2) @property def is_Singleton(self): """ Checks to see if the permutation contains only one number and is thus the only possible permutation of this set of numbers Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation([0]).is_Singleton True >>> Permutation([0, 1]).is_Singleton False See Also ======== is_Empty """ return self.size == 1 @property def is_Empty(self): """ Checks to see if the permutation is a set with zero elements Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation([]).is_Empty True >>> Permutation([0]).is_Empty False See Also ======== is_Singleton """ return self.size == 0 @property def is_identity(self): return self.is_Identity @property def is_Identity(self): """ Returns True if the Permutation is an identity permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([]) >>> p.is_Identity True >>> p = Permutation([[0], [1], [2]]) >>> p.is_Identity True >>> p = Permutation([0, 1, 2]) >>> p.is_Identity True >>> p = Permutation([0, 2, 1]) >>> p.is_Identity False See Also ======== order """ af = self.array_form return not af or all(i == af[i] for i in range(self.size)) def ascents(self): """ Returns the positions of ascents in a permutation, ie, the location where p[i] < p[i+1] Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([4, 0, 1, 3, 2]) >>> p.ascents() [1, 2] See Also ======== descents, inversions, min, max """ a = self.array_form pos = [i for i in range(len(a) - 1) if a[i] < a[i + 1]] return pos def descents(self): """ Returns the positions of descents in a permutation, ie, the location where p[i] > p[i+1] Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([4, 0, 1, 3, 2]) >>> p.descents() [0, 3] See Also ======== ascents, inversions, min, max """ a = self.array_form pos = [i for i in range(len(a) - 1) if a[i] > a[i + 1]] return pos def max(self): """ The maximum element moved by the permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([1, 0, 2, 3, 4]) >>> p.max() 1 See Also ======== min, descents, ascents, inversions """ max = 0 a = self.array_form for i in range(len(a)): if a[i] != i and a[i] > max: max = a[i] return max def min(self): """ The minimum element moved by the permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 4, 3, 2]) >>> p.min() 2 See Also ======== max, descents, ascents, inversions """ a = self.array_form min = len(a) for i in range(len(a)): if a[i] != i and a[i] < min: min = a[i] return min def inversions(self): """ Computes the number of inversions of a permutation. Explanation =========== An inversion is where i > j but p[i] < p[j]. For small length of p, it iterates over all i and j values and calculates the number of inversions. For large length of p, it uses a variation of merge sort to calculate the number of inversions. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2, 3, 4, 5]) >>> p.inversions() 0 >>> Permutation([3, 2, 1, 0]).inversions() 6 See Also ======== descents, ascents, min, max References ========== .. [1] http://www.cp.eng.chula.ac.th/~piak/teaching/algo/algo2008/count-inv.htm """ inversions = 0 a = self.array_form n = len(a) if n < 130: for i in range(n - 1): b = a[i] for c in a[i + 1:]: if b > c: inversions += 1 else: k = 1 right = 0 arr = a[:] temp = a[:] while k < n: i = 0 while i + k < n: right = i + k * 2 - 1 if right >= n: right = n - 1 inversions += _merge(arr, temp, i, i + k, right) i = i + k * 2 k = k * 2 return inversions def commutator(self, x): """Return the commutator of ``self`` and ``x``: ``~x*~self*x*self`` If f and g are part of a group, G, then the commutator of f and g is the group identity iff f and g commute, i.e. fg == gf. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.interactive import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([0, 2, 3, 1]) >>> x = Permutation([2, 0, 3, 1]) >>> c = p.commutator(x); c Permutation([2, 1, 3, 0]) >>> c == ~x*~p*x*p True >>> I = Permutation(3) >>> p = [I + i for i in range(6)] >>> for i in range(len(p)): ... for j in range(len(p)): ... c = p[i].commutator(p[j]) ... if p[i]*p[j] == p[j]*p[i]: ... assert c == I ... else: ... assert c != I ... References ========== https://en.wikipedia.org/wiki/Commutator """ a = self.array_form b = x.array_form n = len(a) if len(b) != n: raise ValueError("The permutations must be of equal size.") inva = [None]*n for i in range(n): inva[a[i]] = i invb = [None]*n for i in range(n): invb[b[i]] = i return self._af_new([a[b[inva[i]]] for i in invb]) def signature(self): """ Gives the signature of the permutation needed to place the elements of the permutation in canonical order. The signature is calculated as (-1)^<number of inversions> Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2]) >>> p.inversions() 0 >>> p.signature() 1 >>> q = Permutation([0,2,1]) >>> q.inversions() 1 >>> q.signature() -1 See Also ======== inversions """ if self.is_even: return 1 return -1 def order(self): """ Computes the order of a permutation. When the permutation is raised to the power of its order it equals the identity permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.interactive import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([3, 1, 5, 2, 4, 0]) >>> p.order() 4 >>> (p**(p.order())) Permutation([], size=6) See Also ======== identity, cardinality, length, rank, size """ return reduce(lcm, [len(cycle) for cycle in self.cyclic_form], 1) def length(self): """ Returns the number of integers moved by a permutation. Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation([0, 3, 2, 1]).length() 2 >>> Permutation([[0, 1], [2, 3]]).length() 4 See Also ======== min, max, support, cardinality, order, rank, size """ return len(self.support()) @property def cycle_structure(self): """Return the cycle structure of the permutation as a dictionary indicating the multiplicity of each cycle length. Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation(3).cycle_structure {1: 4} >>> Permutation(0, 4, 3)(1, 2)(5, 6).cycle_structure {2: 2, 3: 1} """ if self._cycle_structure: rv = self._cycle_structure else: rv = defaultdict(int) singletons = self.size for c in self.cyclic_form: rv[len(c)] += 1 singletons -= len(c) if singletons: rv[1] = singletons self._cycle_structure = rv return dict(rv) # make a copy @property def cycles(self): """ Returns the number of cycles contained in the permutation (including singletons). Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation([0, 1, 2]).cycles 3 >>> Permutation([0, 1, 2]).full_cyclic_form [[0], [1], [2]] >>> Permutation(0, 1)(2, 3).cycles 2 See Also ======== sympy.functions.combinatorial.numbers.stirling """ return len(self.full_cyclic_form) def index(self): """ Returns the index of a permutation. The index of a permutation is the sum of all subscripts j such that p[j] is greater than p[j+1]. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([3, 0, 2, 1, 4]) >>> p.index() 2 """ a = self.array_form return sum([j for j in range(len(a) - 1) if a[j] > a[j + 1]]) def runs(self): """ Returns the runs of a permutation. An ascending sequence in a permutation is called a run [5]. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([2, 5, 7, 3, 6, 0, 1, 4, 8]) >>> p.runs() [[2, 5, 7], [3, 6], [0, 1, 4, 8]] >>> q = Permutation([1,3,2,0]) >>> q.runs() [[1, 3], [2], [0]] """ return runs(self.array_form) def inversion_vector(self): """Return the inversion vector of the permutation. The inversion vector consists of elements whose value indicates the number of elements in the permutation that are lesser than it and lie on its right hand side. The inversion vector is the same as the Lehmer encoding of a permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([4, 8, 0, 7, 1, 5, 3, 6, 2]) >>> p.inversion_vector() [4, 7, 0, 5, 0, 2, 1, 1] >>> p = Permutation([3, 2, 1, 0]) >>> p.inversion_vector() [3, 2, 1] The inversion vector increases lexicographically with the rank of the permutation, the -ith element cycling through 0..i. >>> p = Permutation(2) >>> while p: ... print('%s %s %s' % (p, p.inversion_vector(), p.rank())) ... p = p.next_lex() (2) [0, 0] 0 (1 2) [0, 1] 1 (2)(0 1) [1, 0] 2 (0 1 2) [1, 1] 3 (0 2 1) [2, 0] 4 (0 2) [2, 1] 5 See Also ======== from_inversion_vector """ self_array_form = self.array_form n = len(self_array_form) inversion_vector = [0] * (n - 1) for i in range(n - 1): val = 0 for j in range(i + 1, n): if self_array_form[j] < self_array_form[i]: val += 1 inversion_vector[i] = val return inversion_vector def rank_trotterjohnson(self): """ Returns the Trotter Johnson rank, which we get from the minimal change algorithm. See [4] section 2.4. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.rank_trotterjohnson() 0 >>> p = Permutation([0, 2, 1, 3]) >>> p.rank_trotterjohnson() 7 See Also ======== unrank_trotterjohnson, next_trotterjohnson """ if self.array_form == [] or self.is_Identity: return 0 if self.array_form == [1, 0]: return 1 perm = self.array_form n = self.size rank = 0 for j in range(1, n): k = 1 i = 0 while perm[i] != j: if perm[i] < j: k += 1 i += 1 j1 = j + 1 if rank % 2 == 0: rank = j1*rank + j1 - k else: rank = j1*rank + k - 1 return rank @classmethod def unrank_trotterjohnson(cls, size, rank): """ Trotter Johnson permutation unranking. See [4] section 2.4. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.interactive import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> Permutation.unrank_trotterjohnson(5, 10) Permutation([0, 3, 1, 2, 4]) See Also ======== rank_trotterjohnson, next_trotterjohnson """ perm = [0]*size r2 = 0 n = ifac(size) pj = 1 for j in range(2, size + 1): pj *= j r1 = (rank * pj) // n k = r1 - j*r2 if r2 % 2 == 0: for i in range(j - 1, j - k - 1, -1): perm[i] = perm[i - 1] perm[j - k - 1] = j - 1 else: for i in range(j - 1, k, -1): perm[i] = perm[i - 1] perm[k] = j - 1 r2 = r1 return cls._af_new(perm) def next_trotterjohnson(self): """ Returns the next permutation in Trotter-Johnson order. If self is the last permutation it returns None. See [4] section 2.4. If it is desired to generate all such permutations, they can be generated in order more quickly with the ``generate_bell`` function. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.interactive import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([3, 0, 2, 1]) >>> p.rank_trotterjohnson() 4 >>> p = p.next_trotterjohnson(); p Permutation([0, 3, 2, 1]) >>> p.rank_trotterjohnson() 5 See Also ======== rank_trotterjohnson, unrank_trotterjohnson, sympy.utilities.iterables.generate_bell """ pi = self.array_form[:] n = len(pi) st = 0 rho = pi[:] done = False m = n-1 while m > 0 and not done: d = rho.index(m) for i in range(d, m): rho[i] = rho[i + 1] par = _af_parity(rho[:m]) if par == 1: if d == m: m -= 1 else: pi[st + d], pi[st + d + 1] = pi[st + d + 1], pi[st + d] done = True else: if d == 0: m -= 1 st += 1 else: pi[st + d], pi[st + d - 1] = pi[st + d - 1], pi[st + d] done = True if m == 0: return None return self._af_new(pi) def get_precedence_matrix(self): """ Gets the precedence matrix. This is used for computing the distance between two permutations. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.interactive import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation.josephus(3, 6, 1) >>> p Permutation([2, 5, 3, 1, 4, 0]) >>> p.get_precedence_matrix() Matrix([ [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 1, 0], [1, 1, 0, 1, 1, 1], [1, 1, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0], [1, 1, 0, 1, 1, 0]]) See Also ======== get_precedence_distance, get_adjacency_matrix, get_adjacency_distance """ m = zeros(self.size) perm = self.array_form for i in range(m.rows): for j in range(i + 1, m.cols): m[perm[i], perm[j]] = 1 return m def get_precedence_distance(self, other): """ Computes the precedence distance between two permutations. Explanation =========== Suppose p and p' represent n jobs. The precedence metric counts the number of times a job j is preceded by job i in both p and p'. This metric is commutative. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([2, 0, 4, 3, 1]) >>> q = Permutation([3, 1, 2, 4, 0]) >>> p.get_precedence_distance(q) 7 >>> q.get_precedence_distance(p) 7 See Also ======== get_precedence_matrix, get_adjacency_matrix, get_adjacency_distance """ if self.size != other.size: raise ValueError("The permutations must be of equal size.") self_prec_mat = self.get_precedence_matrix() other_prec_mat = other.get_precedence_matrix() n_prec = 0 for i in range(self.size): for j in range(self.size): if i == j: continue if self_prec_mat[i, j] * other_prec_mat[i, j] == 1: n_prec += 1 d = self.size * (self.size - 1)//2 - n_prec return d def get_adjacency_matrix(self): """ Computes the adjacency matrix of a permutation. Explanation =========== If job i is adjacent to job j in a permutation p then we set m[i, j] = 1 where m is the adjacency matrix of p. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation.josephus(3, 6, 1) >>> p.get_adjacency_matrix() Matrix([ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]]) >>> q = Permutation([0, 1, 2, 3]) >>> q.get_adjacency_matrix() Matrix([ [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 0]]) See Also ======== get_precedence_matrix, get_precedence_distance, get_adjacency_distance """ m = zeros(self.size) perm = self.array_form for i in range(self.size - 1): m[perm[i], perm[i + 1]] = 1 return m def get_adjacency_distance(self, other): """ Computes the adjacency distance between two permutations. Explanation =========== This metric counts the number of times a pair i,j of jobs is adjacent in both p and p'. If n_adj is this quantity then the adjacency distance is n - n_adj - 1 [1] [1] Reeves, Colin R. Landscapes, Operators and Heuristic search, Annals of Operational Research, 86, pp 473-490. (1999) Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 3, 1, 2, 4]) >>> q = Permutation.josephus(4, 5, 2) >>> p.get_adjacency_distance(q) 3 >>> r = Permutation([0, 2, 1, 4, 3]) >>> p.get_adjacency_distance(r) 4 See Also ======== get_precedence_matrix, get_precedence_distance, get_adjacency_matrix """ if self.size != other.size: raise ValueError("The permutations must be of the same size.") self_adj_mat = self.get_adjacency_matrix() other_adj_mat = other.get_adjacency_matrix() n_adj = 0 for i in range(self.size): for j in range(self.size): if i == j: continue if self_adj_mat[i, j] * other_adj_mat[i, j] == 1: n_adj += 1 d = self.size - n_adj - 1 return d def get_positional_distance(self, other): """ Computes the positional distance between two permutations. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 3, 1, 2, 4]) >>> q = Permutation.josephus(4, 5, 2) >>> r = Permutation([3, 1, 4, 0, 2]) >>> p.get_positional_distance(q) 12 >>> p.get_positional_distance(r) 12 See Also ======== get_precedence_distance, get_adjacency_distance """ a = self.array_form b = other.array_form if len(a) != len(b): raise ValueError("The permutations must be of the same size.") return sum([abs(a[i] - b[i]) for i in range(len(a))]) @classmethod def josephus(cls, m, n, s=1): """Return as a permutation the shuffling of range(n) using the Josephus scheme in which every m-th item is selected until all have been chosen. The returned permutation has elements listed by the order in which they were selected. The parameter ``s`` stops the selection process when there are ``s`` items remaining and these are selected by continuing the selection, counting by 1 rather than by ``m``. Consider selecting every 3rd item from 6 until only 2 remain:: choices chosen ======== ====== 012345 01 345 2 01 34 25 01 4 253 0 4 2531 0 25314 253140 Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation.josephus(3, 6, 2).array_form [2, 5, 3, 1, 4, 0] References ========== .. [1] https://en.wikipedia.org/wiki/Flavius_Josephus .. [2] https://en.wikipedia.org/wiki/Josephus_problem .. [3] http://www.wou.edu/~burtonl/josephus.html """ from collections import deque m -= 1 Q = deque(list(range(n))) perm = [] while len(Q) > max(s, 1): for dp in range(m): Q.append(Q.popleft()) perm.append(Q.popleft()) perm.extend(list(Q)) return cls(perm) @classmethod def from_inversion_vector(cls, inversion): """ Calculates the permutation from the inversion vector. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.interactive import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> Permutation.from_inversion_vector([3, 2, 1, 0, 0]) Permutation([3, 2, 1, 0, 4, 5]) """ size = len(inversion) N = list(range(size + 1)) perm = [] try: for k in range(size): val = N[inversion[k]] perm.append(val) N.remove(val) except IndexError: raise ValueError("The inversion vector is not valid.") perm.extend(N) return cls._af_new(perm) @classmethod def random(cls, n): """ Generates a random permutation of length ``n``. Uses the underlying Python pseudo-random number generator. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> Permutation.random(2) in (Permutation([1, 0]), Permutation([0, 1])) True """ perm_array = list(range(n)) random.shuffle(perm_array) return cls._af_new(perm_array) @classmethod def unrank_lex(cls, size, rank): """ Lexicographic permutation unranking. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.interactive import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> a = Permutation.unrank_lex(5, 10) >>> a.rank() 10 >>> a Permutation([0, 2, 4, 1, 3]) See Also ======== rank, next_lex """ perm_array = [0] * size psize = 1 for i in range(size): new_psize = psize*(i + 1) d = (rank % new_psize) // psize rank -= d*psize perm_array[size - i - 1] = d for j in range(size - i, size): if perm_array[j] > d - 1: perm_array[j] += 1 psize = new_psize return cls._af_new(perm_array) def resize(self, n): """Resize the permutation to the new size ``n``. Parameters ========== n : int The new size of the permutation. Raises ====== ValueError If the permutation cannot be resized to the given size. This may only happen when resized to a smaller size than the original. Examples ======== >>> from sympy.combinatorics.permutations import Permutation Increasing the size of a permutation: >>> p = Permutation(0, 1, 2) >>> p = p.resize(5) >>> p (4)(0 1 2) Decreasing the size of the permutation: >>> p = p.resize(4) >>> p (3)(0 1 2) If resizing to the specific size breaks the cycles: >>> p.resize(2) Traceback (most recent call last): ... ValueError: The permutation can not be resized to 2 because the cycle (0, 1, 2) may break. """ aform = self.array_form l = len(aform) if n > l: aform += list(range(l, n)) return Permutation._af_new(aform) elif n < l: cyclic_form = self.full_cyclic_form new_cyclic_form = [] for cycle in cyclic_form: cycle_min = min(cycle) cycle_max = max(cycle) if cycle_min <= n-1: if cycle_max > n-1: raise ValueError( "The permutation can not be resized to {} " "because the cycle {} may break." .format(n, tuple(cycle))) new_cyclic_form.append(cycle) return Permutation(new_cyclic_form) return self # XXX Deprecated flag print_cyclic = None def _merge(arr, temp, left, mid, right): """ Merges two sorted arrays and calculates the inversion count. Helper function for calculating inversions. This method is for internal use only. """ i = k = left j = mid inv_count = 0 while i < mid and j <= right: if arr[i] < arr[j]: temp[k] = arr[i] k += 1 i += 1 else: temp[k] = arr[j] k += 1 j += 1 inv_count += (mid -i) while i < mid: temp[k] = arr[i] k += 1 i += 1 if j <= right: k += right - j + 1 j += right - j + 1 arr[left:k + 1] = temp[left:k + 1] else: arr[left:right + 1] = temp[left:right + 1] return inv_count Perm = Permutation _af_new = Perm._af_new class AppliedPermutation(Expr): """A permutation applied to a symbolic variable. Parameters ========== perm : Permutation x : Expr Examples ======== >>> from sympy import Symbol >>> from sympy.combinatorics import Permutation Creating a symbolic permutation function application: >>> x = Symbol('x') >>> p = Permutation(0, 1, 2) >>> p.apply(x) AppliedPermutation((0 1 2), x) >>> _.subs(x, 1) 2 """ def __new__(cls, perm, x, evaluate=None): if evaluate is None: evaluate = global_parameters.evaluate perm = _sympify(perm) x = _sympify(x) if not isinstance(perm, Permutation): raise ValueError("{} must be a Permutation instance." .format(perm)) if evaluate: if x.is_Integer: return perm.apply(x) obj = super().__new__(cls, perm, x) return obj @dispatch(Permutation, Permutation) def _eval_is_eq(lhs, rhs): if lhs._size != rhs._size: return None return lhs._array_form == rhs._array_form
ebbced9caa7ecdbdeef9f55bd99aad4061ae1d57eea3e223408000aea5849f02
from itertools import combinations from sympy.combinatorics.graycode import GrayCode from sympy.core import Basic class Subset(Basic): """ Represents a basic subset object. Explanation =========== We generate subsets using essentially two techniques, binary enumeration and lexicographic enumeration. The Subset class takes two arguments, the first one describes the initial subset to consider and the second describes the superset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.next_binary().subset ['b'] >>> a.prev_binary().subset ['c'] """ _rank_binary = None _rank_lex = None _rank_graycode = None _subset = None _superset = None def __new__(cls, subset, superset): """ Default constructor. It takes the ``subset`` and its ``superset`` as its parameters. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.subset ['c', 'd'] >>> a.superset ['a', 'b', 'c', 'd'] >>> a.size 2 """ if len(subset) > len(superset): raise ValueError('Invalid arguments have been provided. The ' 'superset must be larger than the subset.') for elem in subset: if elem not in superset: raise ValueError('The superset provided is invalid as it does ' 'not contain the element {}'.format(elem)) obj = Basic.__new__(cls) obj._subset = subset obj._superset = superset return obj def iterate_binary(self, k): """ This is a helper function. It iterates over the binary subsets by ``k`` steps. This variable can be both positive or negative. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.iterate_binary(-2).subset ['d'] >>> a = Subset(['a', 'b', 'c'], ['a', 'b', 'c', 'd']) >>> a.iterate_binary(2).subset [] See Also ======== next_binary, prev_binary """ bin_list = Subset.bitlist_from_subset(self.subset, self.superset) n = (int(''.join(bin_list), 2) + k) % 2**self.superset_size bits = bin(n)[2:].rjust(self.superset_size, '0') return Subset.subset_from_bitlist(self.superset, bits) def next_binary(self): """ Generates the next binary ordered subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.next_binary().subset ['b'] >>> a = Subset(['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']) >>> a.next_binary().subset [] See Also ======== prev_binary, iterate_binary """ return self.iterate_binary(1) def prev_binary(self): """ Generates the previous binary ordered subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset([], ['a', 'b', 'c', 'd']) >>> a.prev_binary().subset ['a', 'b', 'c', 'd'] >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.prev_binary().subset ['c'] See Also ======== next_binary, iterate_binary """ return self.iterate_binary(-1) def next_lexicographic(self): """ Generates the next lexicographically ordered subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.next_lexicographic().subset ['d'] >>> a = Subset(['d'], ['a', 'b', 'c', 'd']) >>> a.next_lexicographic().subset [] See Also ======== prev_lexicographic """ i = self.superset_size - 1 indices = Subset.subset_indices(self.subset, self.superset) if i in indices: if i - 1 in indices: indices.remove(i - 1) else: indices.remove(i) i = i - 1 while not i in indices and i >= 0: i = i - 1 if i >= 0: indices.remove(i) indices.append(i+1) else: while i not in indices and i >= 0: i = i - 1 indices.append(i + 1) ret_set = [] super_set = self.superset for i in indices: ret_set.append(super_set[i]) return Subset(ret_set, super_set) def prev_lexicographic(self): """ Generates the previous lexicographically ordered subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset([], ['a', 'b', 'c', 'd']) >>> a.prev_lexicographic().subset ['d'] >>> a = Subset(['c','d'], ['a', 'b', 'c', 'd']) >>> a.prev_lexicographic().subset ['c'] See Also ======== next_lexicographic """ i = self.superset_size - 1 indices = Subset.subset_indices(self.subset, self.superset) while i >= 0 and i not in indices: i = i - 1 if i == 0 or i - 1 in indices: indices.remove(i) else: if i >= 0: indices.remove(i) indices.append(i - 1) indices.append(self.superset_size - 1) ret_set = [] super_set = self.superset for i in indices: ret_set.append(super_set[i]) return Subset(ret_set, super_set) def iterate_graycode(self, k): """ Helper function used for prev_gray and next_gray. It performs ``k`` step overs to get the respective Gray codes. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset([1, 2, 3], [1, 2, 3, 4]) >>> a.iterate_graycode(3).subset [1, 4] >>> a.iterate_graycode(-2).subset [1, 2, 4] See Also ======== next_gray, prev_gray """ unranked_code = GrayCode.unrank(self.superset_size, (self.rank_gray + k) % self.cardinality) return Subset.subset_from_bitlist(self.superset, unranked_code) def next_gray(self): """ Generates the next Gray code ordered subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset([1, 2, 3], [1, 2, 3, 4]) >>> a.next_gray().subset [1, 3] See Also ======== iterate_graycode, prev_gray """ return self.iterate_graycode(1) def prev_gray(self): """ Generates the previous Gray code ordered subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset([2, 3, 4], [1, 2, 3, 4, 5]) >>> a.prev_gray().subset [2, 3, 4, 5] See Also ======== iterate_graycode, next_gray """ return self.iterate_graycode(-1) @property def rank_binary(self): """ Computes the binary ordered rank. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset([], ['a','b','c','d']) >>> a.rank_binary 0 >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.rank_binary 3 See Also ======== iterate_binary, unrank_binary """ if self._rank_binary is None: self._rank_binary = int("".join( Subset.bitlist_from_subset(self.subset, self.superset)), 2) return self._rank_binary @property def rank_lexicographic(self): """ Computes the lexicographic ranking of the subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.rank_lexicographic 14 >>> a = Subset([2, 4, 5], [1, 2, 3, 4, 5, 6]) >>> a.rank_lexicographic 43 """ if self._rank_lex is None: def _ranklex(self, subset_index, i, n): if subset_index == [] or i > n: return 0 if i in subset_index: subset_index.remove(i) return 1 + _ranklex(self, subset_index, i + 1, n) return 2**(n - i - 1) + _ranklex(self, subset_index, i + 1, n) indices = Subset.subset_indices(self.subset, self.superset) self._rank_lex = _ranklex(self, indices, 0, self.superset_size) return self._rank_lex @property def rank_gray(self): """ Computes the Gray code ranking of the subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c','d'], ['a','b','c','d']) >>> a.rank_gray 2 >>> a = Subset([2, 4, 5], [1, 2, 3, 4, 5, 6]) >>> a.rank_gray 27 See Also ======== iterate_graycode, unrank_gray """ if self._rank_graycode is None: bits = Subset.bitlist_from_subset(self.subset, self.superset) self._rank_graycode = GrayCode(len(bits), start=bits).rank return self._rank_graycode @property def subset(self): """ Gets the subset represented by the current instance. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.subset ['c', 'd'] See Also ======== superset, size, superset_size, cardinality """ return self._subset @property def size(self): """ Gets the size of the subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.size 2 See Also ======== subset, superset, superset_size, cardinality """ return len(self.subset) @property def superset(self): """ Gets the superset of the subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.superset ['a', 'b', 'c', 'd'] See Also ======== subset, size, superset_size, cardinality """ return self._superset @property def superset_size(self): """ Returns the size of the superset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.superset_size 4 See Also ======== subset, superset, size, cardinality """ return len(self.superset) @property def cardinality(self): """ Returns the number of all possible subsets. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.cardinality 16 See Also ======== subset, superset, size, superset_size """ return 2**(self.superset_size) @classmethod def subset_from_bitlist(self, super_set, bitlist): """ Gets the subset defined by the bitlist. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> Subset.subset_from_bitlist(['a', 'b', 'c', 'd'], '0011').subset ['c', 'd'] See Also ======== bitlist_from_subset """ if len(super_set) != len(bitlist): raise ValueError("The sizes of the lists are not equal") ret_set = [] for i in range(len(bitlist)): if bitlist[i] == '1': ret_set.append(super_set[i]) return Subset(ret_set, super_set) @classmethod def bitlist_from_subset(self, subset, superset): """ Gets the bitlist corresponding to a subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> Subset.bitlist_from_subset(['c', 'd'], ['a', 'b', 'c', 'd']) '0011' See Also ======== subset_from_bitlist """ bitlist = ['0'] * len(superset) if type(subset) is Subset: subset = subset.subset for i in Subset.subset_indices(subset, superset): bitlist[i] = '1' return ''.join(bitlist) @classmethod def unrank_binary(self, rank, superset): """ Gets the binary ordered subset of the specified rank. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> Subset.unrank_binary(4, ['a', 'b', 'c', 'd']).subset ['b'] See Also ======== iterate_binary, rank_binary """ bits = bin(rank)[2:].rjust(len(superset), '0') return Subset.subset_from_bitlist(superset, bits) @classmethod def unrank_gray(self, rank, superset): """ Gets the Gray code ordered subset of the specified rank. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> Subset.unrank_gray(4, ['a', 'b', 'c']).subset ['a', 'b'] >>> Subset.unrank_gray(0, ['a', 'b', 'c']).subset [] See Also ======== iterate_graycode, rank_gray """ graycode_bitlist = GrayCode.unrank(len(superset), rank) return Subset.subset_from_bitlist(superset, graycode_bitlist) @classmethod def subset_indices(self, subset, superset): """Return indices of subset in superset in a list; the list is empty if all elements of ``subset`` are not in ``superset``. Examples ======== >>> from sympy.combinatorics import Subset >>> superset = [1, 3, 2, 5, 4] >>> Subset.subset_indices([3, 2, 1], superset) [1, 2, 0] >>> Subset.subset_indices([1, 6], superset) [] >>> Subset.subset_indices([], superset) [] """ a, b = superset, subset sb = set(b) d = {} for i, ai in enumerate(a): if ai in sb: d[ai] = i sb.remove(ai) if not sb: break else: return list() return [d[bi] for bi in b] def ksubsets(superset, k): """ Finds the subsets of size ``k`` in lexicographic order. This uses the itertools generator. Examples ======== >>> from sympy.combinatorics.subsets import ksubsets >>> list(ksubsets([1, 2, 3], 2)) [(1, 2), (1, 3), (2, 3)] >>> list(ksubsets([1, 2, 3, 4, 5], 2)) [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), \ (2, 5), (3, 4), (3, 5), (4, 5)] See Also ======== Subset """ return combinations(superset, k)
71743e287c2f0331b2f7fb055dd1aa68d75dad38eaf80ac6530c409e77bcf8e5
from sympy.combinatorics.permutations import Permutation, _af_rmul, \ _af_invert, _af_new from sympy.combinatorics.perm_groups import PermutationGroup, _orbit, \ _orbit_transversal from sympy.combinatorics.util import _distribute_gens_by_base, \ _orbits_transversals_from_bsgs """ References for tensor canonicalization: [1] R. Portugal "Algorithmic simplification of tensor expressions", J. Phys. A 32 (1999) 7779-7789 [2] R. Portugal, B.F. Svaiter "Group-theoretic Approach for Symbolic Tensor Manipulation: I. Free Indices" arXiv:math-ph/0107031v1 [3] L.R.U. Manssur, R. Portugal "Group-theoretic Approach for Symbolic Tensor Manipulation: II. Dummy Indices" arXiv:math-ph/0107032v1 [4] xperm.c part of XPerm written by J. M. Martin-Garcia http://www.xact.es/index.html """ def dummy_sgs(dummies, sym, n): """ Return the strong generators for dummy indices. Parameters ========== dummies : List of dummy indices. `dummies[2k], dummies[2k+1]` are paired indices. In base form, the dummy indices are always in consecutive positions. sym : symmetry under interchange of contracted dummies:: * None no symmetry * 0 commuting * 1 anticommuting n : number of indices Examples ======== >>> from sympy.combinatorics.tensor_can import dummy_sgs >>> dummy_sgs(list(range(2, 8)), 0, 8) [[0, 1, 3, 2, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 5, 4, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 7, 6, 8, 9], [0, 1, 4, 5, 2, 3, 6, 7, 8, 9], [0, 1, 2, 3, 6, 7, 4, 5, 8, 9]] """ if len(dummies) > n: raise ValueError("List too large") res = [] # exchange of contravariant and covariant indices if sym is not None: for j in dummies[::2]: a = list(range(n + 2)) if sym == 1: a[n] = n + 1 a[n + 1] = n a[j], a[j + 1] = a[j + 1], a[j] res.append(a) # rename dummy indices for j in dummies[:-3:2]: a = list(range(n + 2)) a[j:j + 4] = a[j + 2], a[j + 3], a[j], a[j + 1] res.append(a) return res def _min_dummies(dummies, sym, indices): """ Return list of minima of the orbits of indices in group of dummies. See ``double_coset_can_rep`` for the description of ``dummies`` and ``sym``. ``indices`` is the initial list of dummy indices. Examples ======== >>> from sympy.combinatorics.tensor_can import _min_dummies >>> _min_dummies([list(range(2, 8))], [0], list(range(10))) [0, 1, 2, 2, 2, 2, 2, 2, 8, 9] """ num_types = len(sym) m = [] for dx in dummies: if dx: m.append(min(dx)) else: m.append(None) res = indices[:] for i in range(num_types): for c, i in enumerate(indices): for j in range(num_types): if i in dummies[j]: res[c] = m[j] break return res def _trace_S(s, j, b, S_cosets): """ Return the representative h satisfying s[h[b]] == j If there is not such a representative return None """ for h in S_cosets[b]: if s[h[b]] == j: return h return None def _trace_D(gj, p_i, Dxtrav): """ Return the representative h satisfying h[gj] == p_i If there is not such a representative return None """ for h in Dxtrav: if h[gj] == p_i: return h return None def _dumx_remove(dumx, dumx_flat, p0): """ remove p0 from dumx """ res = [] for dx in dumx: if p0 not in dx: res.append(dx) continue k = dx.index(p0) if k % 2 == 0: p0_paired = dx[k + 1] else: p0_paired = dx[k - 1] dx.remove(p0) dx.remove(p0_paired) dumx_flat.remove(p0) dumx_flat.remove(p0_paired) res.append(dx) def transversal2coset(size, base, transversal): a = [] j = 0 for i in range(size): if i in base: a.append(sorted(transversal[j].values())) j += 1 else: a.append([list(range(size))]) j = len(a) - 1 while a[j] == [list(range(size))]: j -= 1 return a[:j + 1] def double_coset_can_rep(dummies, sym, b_S, sgens, S_transversals, g): """ Butler-Portugal algorithm for tensor canonicalization with dummy indices. Parameters ========== dummies list of lists of dummy indices, one list for each type of index; the dummy indices are put in order contravariant, covariant [d0, -d0, d1, -d1, ...]. sym list of the symmetries of the index metric for each type. possible symmetries of the metrics * 0 symmetric * 1 antisymmetric * None no symmetry b_S base of a minimal slot symmetry BSGS. sgens generators of the slot symmetry BSGS. S_transversals transversals for the slot BSGS. g permutation representing the tensor. Returns ======= Return 0 if the tensor is zero, else return the array form of the permutation representing the canonical form of the tensor. Notes ===== A tensor with dummy indices can be represented in a number of equivalent ways which typically grows exponentially with the number of indices. To be able to establish if two tensors with many indices are equal becomes computationally very slow in absence of an efficient algorithm. The Butler-Portugal algorithm [3] is an efficient algorithm to put tensors in canonical form, solving the above problem. Portugal observed that a tensor can be represented by a permutation, and that the class of tensors equivalent to it under slot and dummy symmetries is equivalent to the double coset `D*g*S` (Note: in this documentation we use the conventions for multiplication of permutations p, q with (p*q)(i) = p[q[i]] which is opposite to the one used in the Permutation class) Using the algorithm by Butler to find a representative of the double coset one can find a canonical form for the tensor. To see this correspondence, let `g` be a permutation in array form; a tensor with indices `ind` (the indices including both the contravariant and the covariant ones) can be written as `t = T(ind[g[0]],..., ind[g[n-1]])`, where `n= len(ind)`; `g` has size `n + 2`, the last two indices for the sign of the tensor (trick introduced in [4]). A slot symmetry transformation `s` is a permutation acting on the slots `t -> T(ind[(g*s)[0]],..., ind[(g*s)[n-1]])` A dummy symmetry transformation acts on `ind` `t -> T(ind[(d*g)[0]],..., ind[(d*g)[n-1]])` Being interested only in the transformations of the tensor under these symmetries, one can represent the tensor by `g`, which transforms as `g -> d*g*s`, so it belongs to the coset `D*g*S`, or in other words to the set of all permutations allowed by the slot and dummy symmetries. Let us explain the conventions by an example. Given a tensor `T^{d3 d2 d1}{}_{d1 d2 d3}` with the slot symmetries `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}` `T^{a0 a1 a2 a3 a4 a5} = -T^{a4 a1 a2 a3 a0 a5}` and symmetric metric, find the tensor equivalent to it which is the lowest under the ordering of indices: lexicographic ordering `d1, d2, d3` and then contravariant before covariant index; that is the canonical form of the tensor. The canonical form is `-T^{d1 d2 d3}{}_{d1 d2 d3}` obtained using `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}`. To convert this problem in the input for this function, use the following ordering of the index names (- for covariant for short) `d1, -d1, d2, -d2, d3, -d3` `T^{d3 d2 d1}{}_{d1 d2 d3}` corresponds to `g = [4, 2, 0, 1, 3, 5, 6, 7]` where the last two indices are for the sign `sgens = [Permutation(0, 2)(6, 7), Permutation(0, 4)(6, 7)]` sgens[0] is the slot symmetry `-(0, 2)` `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}` sgens[1] is the slot symmetry `-(0, 4)` `T^{a0 a1 a2 a3 a4 a5} = -T^{a4 a1 a2 a3 a0 a5}` The dummy symmetry group D is generated by the strong base generators `[(0, 1), (2, 3), (4, 5), (0, 2)(1, 3), (0, 4)(1, 5)]` where the first three interchange covariant and contravariant positions of the same index (d1 <-> -d1) and the last two interchange the dummy indices themselves (d1 <-> d2). The dummy symmetry acts from the left `d = [1, 0, 2, 3, 4, 5, 6, 7]` exchange `d1 <-> -d1` `T^{d3 d2 d1}{}_{d1 d2 d3} == T^{d3 d2}{}_{d1}{}^{d1}{}_{d2 d3}` `g=[4, 2, 0, 1, 3, 5, 6, 7] -> [4, 2, 1, 0, 3, 5, 6, 7] = _af_rmul(d, g)` which differs from `_af_rmul(g, d)`. The slot symmetry acts from the right `s = [2, 1, 0, 3, 4, 5, 7, 6]` exchanges slots 0 and 2 and changes sign `T^{d3 d2 d1}{}_{d1 d2 d3} == -T^{d1 d2 d3}{}_{d1 d2 d3}` `g=[4,2,0,1,3,5,6,7] -> [0, 2, 4, 1, 3, 5, 7, 6] = _af_rmul(g, s)` Example in which the tensor is zero, same slot symmetries as above: `T^{d2}{}_{d1 d3}{}^{d1 d3}{}_{d2}` `= -T^{d3}{}_{d1 d3}{}^{d1 d2}{}_{d2}` under slot symmetry `-(0,4)`; `= T_{d3 d1}{}^{d3}{}^{d1 d2}{}_{d2}` under slot symmetry `-(0,2)`; `= T^{d3}{}_{d1 d3}{}^{d1 d2}{}_{d2}` symmetric metric; `= 0` since two of these lines have tensors differ only for the sign. The double coset D*g*S consists of permutations `h = d*g*s` corresponding to equivalent tensors; if there are two `h` which are the same apart from the sign, return zero; otherwise choose as representative the tensor with indices ordered lexicographically according to `[d1, -d1, d2, -d2, d3, -d3]` that is `rep = min(D*g*S) = min([d*g*s for d in D for s in S])` The indices are fixed one by one; first choose the lowest index for slot 0, then the lowest remaining index for slot 1, etc. Doing this one obtains a chain of stabilizers `S -> S_{b0} -> S_{b0,b1} -> ...` and `D -> D_{p0} -> D_{p0,p1} -> ...` where `[b0, b1, ...] = range(b)` is a base of the symmetric group; the strong base `b_S` of S is an ordered sublist of it; therefore it is sufficient to compute once the strong base generators of S using the Schreier-Sims algorithm; the stabilizers of the strong base generators are the strong base generators of the stabilizer subgroup. `dbase = [p0, p1, ...]` is not in general in lexicographic order, so that one must recompute the strong base generators each time; however this is trivial, there is no need to use the Schreier-Sims algorithm for D. The algorithm keeps a TAB of elements `(s_i, d_i, h_i)` where `h_i = d_i*g*s_i` satisfying `h_i[j] = p_j` for `0 <= j < i` starting from `s_0 = id, d_0 = id, h_0 = g`. The equations `h_0[0] = p_0, h_1[1] = p_1,...` are solved in this order, choosing each time the lowest possible value of p_i For `j < i` `d_i*g*s_i*S_{b_0,...,b_{i-1}}*b_j = D_{p_0,...,p_{i-1}}*p_j` so that for dx in `D_{p_0,...,p_{i-1}}` and sx in `S_{base[0],...,base[i-1]}` one has `dx*d_i*g*s_i*sx*b_j = p_j` Search for dx, sx such that this equation holds for `j = i`; it can be written as `s_i*sx*b_j = J, dx*d_i*g*J = p_j` `sx*b_j = s_i**-1*J; sx = trace(s_i**-1, S_{b_0,...,b_{i-1}})` `dx**-1*p_j = d_i*g*J; dx = trace(d_i*g*J, D_{p_0,...,p_{i-1}})` `s_{i+1} = s_i*trace(s_i**-1*J, S_{b_0,...,b_{i-1}})` `d_{i+1} = trace(d_i*g*J, D_{p_0,...,p_{i-1}})**-1*d_i` `h_{i+1}*b_i = d_{i+1}*g*s_{i+1}*b_i = p_i` `h_n*b_j = p_j` for all j, so that `h_n` is the solution. Add the found `(s, d, h)` to TAB1. At the end of the iteration sort TAB1 with respect to the `h`; if there are two consecutive `h` in TAB1 which differ only for the sign, the tensor is zero, so return 0; if there are two consecutive `h` which are equal, keep only one. Then stabilize the slot generators under `i` and the dummy generators under `p_i`. Assign `TAB = TAB1` at the end of the iteration step. At the end `TAB` contains a unique `(s, d, h)`, since all the slots of the tensor `h` have been fixed to have the minimum value according to the symmetries. The algorithm returns `h`. It is important that the slot BSGS has lexicographic minimal base, otherwise there is an `i` which does not belong to the slot base for which `p_i` is fixed by the dummy symmetry only, while `i` is not invariant from the slot stabilizer, so `p_i` is not in general the minimal value. This algorithm differs slightly from the original algorithm [3]: the canonical form is minimal lexicographically, and the BSGS has minimal base under lexicographic order. Equal tensors `h` are eliminated from TAB. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.tensor_can import double_coset_can_rep, get_transversals >>> gens = [Permutation(x) for x in [[2, 1, 0, 3, 4, 5, 7, 6], [4, 1, 2, 3, 0, 5, 7, 6]]] >>> base = [0, 2] >>> g = Permutation([4, 2, 0, 1, 3, 5, 6, 7]) >>> transversals = get_transversals(base, gens) >>> double_coset_can_rep([list(range(6))], [0], base, gens, transversals, g) [0, 1, 2, 3, 4, 5, 7, 6] >>> g = Permutation([4, 1, 3, 0, 5, 2, 6, 7]) >>> double_coset_can_rep([list(range(6))], [0], base, gens, transversals, g) 0 """ size = g.size g = g.array_form num_dummies = size - 2 indices = list(range(num_dummies)) all_metrics_with_sym = not any(_ is None for _ in sym) num_types = len(sym) dumx = dummies[:] dumx_flat = [] for dx in dumx: dumx_flat.extend(dx) b_S = b_S[:] sgensx = [h._array_form for h in sgens] if b_S: S_transversals = transversal2coset(size, b_S, S_transversals) # strong generating set for D dsgsx = [] for i in range(num_types): dsgsx.extend(dummy_sgs(dumx[i], sym[i], num_dummies)) idn = list(range(size)) # TAB = list of entries (s, d, h) where h = _af_rmuln(d,g,s) # for short, in the following d*g*s means _af_rmuln(d,g,s) TAB = [(idn, idn, g)] for i in range(size - 2): b = i testb = b in b_S and sgensx if testb: sgensx1 = [_af_new(_) for _ in sgensx] deltab = _orbit(size, sgensx1, b) else: deltab = {b} # p1 = min(IMAGES) = min(Union D_p*h*deltab for h in TAB) if all_metrics_with_sym: md = _min_dummies(dumx, sym, indices) else: md = [min(_orbit(size, [_af_new( ddx) for ddx in dsgsx], ii)) for ii in range(size - 2)] p_i = min([min([md[h[x]] for x in deltab]) for s, d, h in TAB]) dsgsx1 = [_af_new(_) for _ in dsgsx] Dxtrav = _orbit_transversal(size, dsgsx1, p_i, False, af=True) \ if dsgsx else None if Dxtrav: Dxtrav = [_af_invert(x) for x in Dxtrav] # compute the orbit of p_i for ii in range(num_types): if p_i in dumx[ii]: # the orbit is made by all the indices in dum[ii] if sym[ii] is not None: deltap = dumx[ii] else: # the orbit is made by all the even indices if p_i # is even, by all the odd indices if p_i is odd p_i_index = dumx[ii].index(p_i) % 2 deltap = dumx[ii][p_i_index::2] break else: deltap = [p_i] TAB1 = [] while TAB: s, d, h = TAB.pop() if min([md[h[x]] for x in deltab]) != p_i: continue deltab1 = [x for x in deltab if md[h[x]] == p_i] # NEXT = s*deltab1 intersection (d*g)**-1*deltap dg = _af_rmul(d, g) dginv = _af_invert(dg) sdeltab = [s[x] for x in deltab1] gdeltap = [dginv[x] for x in deltap] NEXT = [x for x in sdeltab if x in gdeltap] # d, s satisfy # d*g*s*base[i-1] = p_{i-1}; using the stabilizers # d*g*s*S_{base[0],...,base[i-1]}*base[i-1] = # D_{p_0,...,p_{i-1}}*p_{i-1} # so that to find d1, s1 satisfying d1*g*s1*b = p_i # one can look for dx in D_{p_0,...,p_{i-1}} and # sx in S_{base[0],...,base[i-1]} # d1 = dx*d; s1 = s*sx # d1*g*s1*b = dx*d*g*s*sx*b = p_i for j in NEXT: if testb: # solve s1*b = j with s1 = s*sx for some element sx # of the stabilizer of ..., base[i-1] # sx*b = s**-1*j; sx = _trace_S(s, j,...) # s1 = s*trace_S(s**-1*j,...) s1 = _trace_S(s, j, b, S_transversals) if not s1: continue else: s1 = [s[ix] for ix in s1] else: s1 = s # assert s1[b] == j # invariant # solve d1*g*j = p_i with d1 = dx*d for some element dg # of the stabilizer of ..., p_{i-1} # dx**-1*p_i = d*g*j; dx**-1 = trace_D(d*g*j,...) # d1 = trace_D(d*g*j,...)**-1*d # to save an inversion in the inner loop; notice we did # Dxtrav = [perm_af_invert(x) for x in Dxtrav] out of the loop if Dxtrav: d1 = _trace_D(dg[j], p_i, Dxtrav) if not d1: continue else: if p_i != dg[j]: continue d1 = idn assert d1[dg[j]] == p_i # invariant d1 = [d1[ix] for ix in d] h1 = [d1[g[ix]] for ix in s1] # assert h1[b] == p_i # invariant TAB1.append((s1, d1, h1)) # if TAB contains equal permutations, keep only one of them; # if TAB contains equal permutations up to the sign, return 0 TAB1.sort(key=lambda x: x[-1]) prev = [0] * size while TAB1: s, d, h = TAB1.pop() if h[:-2] == prev[:-2]: if h[-1] != prev[-1]: return 0 else: TAB.append((s, d, h)) prev = h # stabilize the SGS sgensx = [h for h in sgensx if h[b] == b] if b in b_S: b_S.remove(b) _dumx_remove(dumx, dumx_flat, p_i) dsgsx = [] for i in range(num_types): dsgsx.extend(dummy_sgs(dumx[i], sym[i], num_dummies)) return TAB[0][-1] def canonical_free(base, gens, g, num_free): """ Canonicalization of a tensor with respect to free indices choosing the minimum with respect to lexicographical ordering in the free indices. Explanation =========== ``base``, ``gens`` BSGS for slot permutation group ``g`` permutation representing the tensor ``num_free`` number of free indices The indices must be ordered with first the free indices See explanation in double_coset_can_rep The algorithm is a variation of the one given in [2]. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.tensor_can import canonical_free >>> gens = [[1, 0, 2, 3, 5, 4], [2, 3, 0, 1, 4, 5],[0, 1, 3, 2, 5, 4]] >>> gens = [Permutation(h) for h in gens] >>> base = [0, 2] >>> g = Permutation([2, 1, 0, 3, 4, 5]) >>> canonical_free(base, gens, g, 4) [0, 3, 1, 2, 5, 4] Consider the product of Riemann tensors ``T = R^{a}_{d0}^{d1,d2}*R_{d2,d1}^{d0,b}`` The order of the indices is ``[a, b, d0, -d0, d1, -d1, d2, -d2]`` The permutation corresponding to the tensor is ``g = [0, 3, 4, 6, 7, 5, 2, 1, 8, 9]`` In particular ``a`` is position ``0``, ``b`` is in position ``9``. Use the slot symmetries to get `T` is a form which is the minimal in lexicographic order in the free indices ``a`` and ``b``, e.g. ``-R^{a}_{d0}^{d1,d2}*R^{b,d0}_{d2,d1}`` corresponding to ``[0, 3, 4, 6, 1, 2, 7, 5, 9, 8]`` >>> from sympy.combinatorics.tensor_can import riemann_bsgs, tensor_gens >>> base, gens = riemann_bsgs >>> size, sbase, sgens = tensor_gens(base, gens, [[], []], 0) >>> g = Permutation([0, 3, 4, 6, 7, 5, 2, 1, 8, 9]) >>> canonical_free(sbase, [Permutation(h) for h in sgens], g, 2) [0, 3, 4, 6, 1, 2, 7, 5, 9, 8] """ g = g.array_form size = len(g) if not base: return g[:] transversals = get_transversals(base, gens) for x in sorted(g[:-2]): if x not in base: base.append(x) h = g for i, transv in enumerate(transversals): h_i = [size]*num_free # find the element s in transversals[i] such that # _af_rmul(h, s) has its free elements with the lowest position in h s = None for sk in transv.values(): h1 = _af_rmul(h, sk) hi = [h1.index(ix) for ix in range(num_free)] if hi < h_i: h_i = hi s = sk if s: h = _af_rmul(h, s) return h def _get_map_slots(size, fixed_slots): res = list(range(size)) pos = 0 for i in range(size): if i in fixed_slots: continue res[i] = pos pos += 1 return res def _lift_sgens(size, fixed_slots, free, s): a = [] j = k = 0 fd = list(zip(fixed_slots, free)) fd = [y for x, y in sorted(fd)] num_free = len(free) for i in range(size): if i in fixed_slots: a.append(fd[k]) k += 1 else: a.append(s[j] + num_free) j += 1 return a def canonicalize(g, dummies, msym, *v): """ canonicalize tensor formed by tensors Parameters ========== g : permutation representing the tensor dummies : list representing the dummy indices it can be a list of dummy indices of the same type or a list of lists of dummy indices, one list for each type of index; the dummy indices must come after the free indices, and put in order contravariant, covariant [d0, -d0, d1,-d1,...] msym : symmetry of the metric(s) it can be an integer or a list; in the first case it is the symmetry of the dummy index metric; in the second case it is the list of the symmetries of the index metric for each type v : list, (base_i, gens_i, n_i, sym_i) for tensors of type `i` base_i, gens_i : BSGS for tensors of this type. The BSGS should have minimal base under lexicographic ordering; if not, an attempt is made do get the minimal BSGS; in case of failure, canonicalize_naive is used, which is much slower. n_i : number of tensors of type `i`. sym_i : symmetry under exchange of component tensors of type `i`. Both for msym and sym_i the cases are * None no symmetry * 0 commuting * 1 anticommuting Returns ======= 0 if the tensor is zero, else return the array form of the permutation representing the canonical form of the tensor. Algorithm ========= First one uses canonical_free to get the minimum tensor under lexicographic order, using only the slot symmetries. If the component tensors have not minimal BSGS, it is attempted to find it; if the attempt fails canonicalize_naive is used instead. Compute the residual slot symmetry keeping fixed the free indices using tensor_gens(base, gens, list_free_indices, sym). Reduce the problem eliminating the free indices. Then use double_coset_can_rep and lift back the result reintroducing the free indices. Examples ======== one type of index with commuting metric; `A_{a b}` and `B_{a b}` antisymmetric and commuting `T = A_{d0 d1} * B^{d0}{}_{d2} * B^{d2 d1}` `ord = [d0,-d0,d1,-d1,d2,-d2]` order of the indices g = [1, 3, 0, 5, 4, 2, 6, 7] `T_c = 0` >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, canonicalize, bsgs_direct_product >>> from sympy.combinatorics import Permutation >>> base2a, gens2a = get_symmetric_group_sgs(2, 1) >>> t0 = (base2a, gens2a, 1, 0) >>> t1 = (base2a, gens2a, 2, 0) >>> g = Permutation([1, 3, 0, 5, 4, 2, 6, 7]) >>> canonicalize(g, range(6), 0, t0, t1) 0 same as above, but with `B_{a b}` anticommuting `T_c = -A^{d0 d1} * B_{d0}{}^{d2} * B_{d1 d2}` can = [0,2,1,4,3,5,7,6] >>> t1 = (base2a, gens2a, 2, 1) >>> canonicalize(g, range(6), 0, t0, t1) [0, 2, 1, 4, 3, 5, 7, 6] two types of indices `[a,b,c,d,e,f]` and `[m,n]`, in this order, both with commuting metric `f^{a b c}` antisymmetric, commuting `A_{m a}` no symmetry, commuting `T = f^c{}_{d a} * f^f{}_{e b} * A_m{}^d * A^{m b} * A_n{}^a * A^{n e}` ord = [c,f,a,-a,b,-b,d,-d,e,-e,m,-m,n,-n] g = [0,7,3, 1,9,5, 11,6, 10,4, 13,2, 12,8, 14,15] The canonical tensor is `T_c = -f^{c a b} * f^{f d e} * A^m{}_a * A_{m d} * A^n{}_b * A_{n e}` can = [0,2,4, 1,6,8, 10,3, 11,7, 12,5, 13,9, 15,14] >>> base_f, gens_f = get_symmetric_group_sgs(3, 1) >>> base1, gens1 = get_symmetric_group_sgs(1) >>> base_A, gens_A = bsgs_direct_product(base1, gens1, base1, gens1) >>> t0 = (base_f, gens_f, 2, 0) >>> t1 = (base_A, gens_A, 4, 0) >>> dummies = [range(2, 10), range(10, 14)] >>> g = Permutation([0, 7, 3, 1, 9, 5, 11, 6, 10, 4, 13, 2, 12, 8, 14, 15]) >>> canonicalize(g, dummies, [0, 0], t0, t1) [0, 2, 4, 1, 6, 8, 10, 3, 11, 7, 12, 5, 13, 9, 15, 14] """ from sympy.combinatorics.testutil import canonicalize_naive if not isinstance(msym, list): if not msym in (0, 1, None): raise ValueError('msym must be 0, 1 or None') num_types = 1 else: num_types = len(msym) if not all(msymx in (0, 1, None) for msymx in msym): raise ValueError('msym entries must be 0, 1 or None') if len(dummies) != num_types: raise ValueError( 'dummies and msym must have the same number of elements') size = g.size num_tensors = 0 v1 = [] for i in range(len(v)): base_i, gens_i, n_i, sym_i = v[i] # check that the BSGS is minimal; # this property is used in double_coset_can_rep; # if it is not minimal use canonicalize_naive if not _is_minimal_bsgs(base_i, gens_i): mbsgs = get_minimal_bsgs(base_i, gens_i) if not mbsgs: can = canonicalize_naive(g, dummies, msym, *v) return can base_i, gens_i = mbsgs v1.append((base_i, gens_i, [[]] * n_i, sym_i)) num_tensors += n_i if num_types == 1 and not isinstance(msym, list): dummies = [dummies] msym = [msym] flat_dummies = [] for dumx in dummies: flat_dummies.extend(dumx) if flat_dummies and flat_dummies != list(range(flat_dummies[0], flat_dummies[-1] + 1)): raise ValueError('dummies is not valid') # slot symmetry of the tensor size1, sbase, sgens = gens_products(*v1) if size != size1: raise ValueError( 'g has size %d, generators have size %d' % (size, size1)) free = [i for i in range(size - 2) if i not in flat_dummies] num_free = len(free) # g1 minimal tensor under slot symmetry g1 = canonical_free(sbase, sgens, g, num_free) if not flat_dummies: return g1 # save the sign of g1 sign = 0 if g1[-1] == size - 1 else 1 # the free indices are kept fixed. # Determine free_i, the list of slots of tensors which are fixed # since they are occupied by free indices, which are fixed. start = 0 for i in range(len(v)): free_i = [] base_i, gens_i, n_i, sym_i = v[i] len_tens = gens_i[0].size - 2 # for each component tensor get a list od fixed islots for j in range(n_i): # get the elements corresponding to the component tensor h = g1[start:(start + len_tens)] fr = [] # get the positions of the fixed elements in h for k in free: if k in h: fr.append(h.index(k)) free_i.append(fr) start += len_tens v1[i] = (base_i, gens_i, free_i, sym_i) # BSGS of the tensor with fixed free indices # if tensor_gens fails in gens_product, use canonicalize_naive size, sbase, sgens = gens_products(*v1) # reduce the permutations getting rid of the free indices pos_free = [g1.index(x) for x in range(num_free)] size_red = size - num_free g1_red = [x - num_free for x in g1 if x in flat_dummies] if sign: g1_red.extend([size_red - 1, size_red - 2]) else: g1_red.extend([size_red - 2, size_red - 1]) map_slots = _get_map_slots(size, pos_free) sbase_red = [map_slots[i] for i in sbase if i not in pos_free] sgens_red = [_af_new([map_slots[i] for i in y._array_form if i not in pos_free]) for y in sgens] dummies_red = [[x - num_free for x in y] for y in dummies] transv_red = get_transversals(sbase_red, sgens_red) g1_red = _af_new(g1_red) g2 = double_coset_can_rep( dummies_red, msym, sbase_red, sgens_red, transv_red, g1_red) if g2 == 0: return 0 # lift to the case with the free indices g3 = _lift_sgens(size, pos_free, free, g2) return g3 def perm_af_direct_product(gens1, gens2, signed=True): """ Direct products of the generators gens1 and gens2. Examples ======== >>> from sympy.combinatorics.tensor_can import perm_af_direct_product >>> gens1 = [[1, 0, 2, 3], [0, 1, 3, 2]] >>> gens2 = [[1, 0]] >>> perm_af_direct_product(gens1, gens2, False) [[1, 0, 2, 3, 4, 5], [0, 1, 3, 2, 4, 5], [0, 1, 2, 3, 5, 4]] >>> gens1 = [[1, 0, 2, 3, 5, 4], [0, 1, 3, 2, 4, 5]] >>> gens2 = [[1, 0, 2, 3]] >>> perm_af_direct_product(gens1, gens2, True) [[1, 0, 2, 3, 4, 5, 7, 6], [0, 1, 3, 2, 4, 5, 6, 7], [0, 1, 2, 3, 5, 4, 6, 7]] """ gens1 = [list(x) for x in gens1] gens2 = [list(x) for x in gens2] s = 2 if signed else 0 n1 = len(gens1[0]) - s n2 = len(gens2[0]) - s start = list(range(n1)) end = list(range(n1, n1 + n2)) if signed: gens1 = [gen[:-2] + end + [gen[-2] + n2, gen[-1] + n2] for gen in gens1] gens2 = [start + [x + n1 for x in gen] for gen in gens2] else: gens1 = [gen + end for gen in gens1] gens2 = [start + [x + n1 for x in gen] for gen in gens2] res = gens1 + gens2 return res def bsgs_direct_product(base1, gens1, base2, gens2, signed=True): """ Direct product of two BSGS. Parameters ========== base1 : base of the first BSGS. gens1 : strong generating sequence of the first BSGS. base2, gens2 : similarly for the second BSGS. signed : flag for signed permutations. Examples ======== >>> from sympy.combinatorics.tensor_can import (get_symmetric_group_sgs, bsgs_direct_product) >>> base1, gens1 = get_symmetric_group_sgs(1) >>> base2, gens2 = get_symmetric_group_sgs(2) >>> bsgs_direct_product(base1, gens1, base2, gens2) ([1], [(4)(1 2)]) """ s = 2 if signed else 0 n1 = gens1[0].size - s base = list(base1) base += [x + n1 for x in base2] gens1 = [h._array_form for h in gens1] gens2 = [h._array_form for h in gens2] gens = perm_af_direct_product(gens1, gens2, signed) size = len(gens[0]) id_af = list(range(size)) gens = [h for h in gens if h != id_af] if not gens: gens = [id_af] return base, [_af_new(h) for h in gens] def get_symmetric_group_sgs(n, antisym=False): """ Return base, gens of the minimal BSGS for (anti)symmetric tensor Parameters ========== ``n``: rank of the tensor ``antisym`` : bool ``antisym = False`` symmetric tensor ``antisym = True`` antisymmetric tensor Examples ======== >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs >>> get_symmetric_group_sgs(3) ([0, 1], [(4)(0 1), (4)(1 2)]) """ if n == 1: return [], [_af_new(list(range(3)))] gens = [Permutation(n - 1)(i, i + 1)._array_form for i in range(n - 1)] if antisym == 0: gens = [x + [n, n + 1] for x in gens] else: gens = [x + [n + 1, n] for x in gens] base = list(range(n - 1)) return base, [_af_new(h) for h in gens] riemann_bsgs = [0, 2], [Permutation(0, 1)(4, 5), Permutation(2, 3)(4, 5), Permutation(5)(0, 2)(1, 3)] def get_transversals(base, gens): """ Return transversals for the group with BSGS base, gens """ if not base: return [] stabs = _distribute_gens_by_base(base, gens) orbits, transversals = _orbits_transversals_from_bsgs(base, stabs) transversals = [{x: h._array_form for x, h in y.items()} for y in transversals] return transversals def _is_minimal_bsgs(base, gens): """ Check if the BSGS has minimal base under lexigographic order. base, gens BSGS Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.tensor_can import riemann_bsgs, _is_minimal_bsgs >>> _is_minimal_bsgs(*riemann_bsgs) True >>> riemann_bsgs1 = ([2, 0], ([Permutation(5)(0, 1)(4, 5), Permutation(5)(0, 2)(1, 3)])) >>> _is_minimal_bsgs(*riemann_bsgs1) False """ base1 = [] sgs1 = gens[:] size = gens[0].size for i in range(size): if not all(h._array_form[i] == i for h in sgs1): base1.append(i) sgs1 = [h for h in sgs1 if h._array_form[i] == i] return base1 == base def get_minimal_bsgs(base, gens): """ Compute a minimal GSGS base, gens BSGS If base, gens is a minimal BSGS return it; else return a minimal BSGS if it fails in finding one, it returns None TODO: use baseswap in the case in which if it fails in finding a minimal BSGS Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.tensor_can import get_minimal_bsgs >>> riemann_bsgs1 = ([2, 0], ([Permutation(5)(0, 1)(4, 5), Permutation(5)(0, 2)(1, 3)])) >>> get_minimal_bsgs(*riemann_bsgs1) ([0, 2], [(0 1)(4 5), (5)(0 2)(1 3), (2 3)(4 5)]) """ G = PermutationGroup(gens) base, gens = G.schreier_sims_incremental() if not _is_minimal_bsgs(base, gens): return None return base, gens def tensor_gens(base, gens, list_free_indices, sym=0): """ Returns size, res_base, res_gens BSGS for n tensors of the same type. Explanation =========== base, gens BSGS for tensors of this type list_free_indices list of the slots occupied by fixed indices for each of the tensors sym symmetry under commutation of two tensors sym None no symmetry sym 0 commuting sym 1 anticommuting Examples ======== >>> from sympy.combinatorics.tensor_can import tensor_gens, get_symmetric_group_sgs two symmetric tensors with 3 indices without free indices >>> base, gens = get_symmetric_group_sgs(3) >>> tensor_gens(base, gens, [[], []]) (8, [0, 1, 3, 4], [(7)(0 1), (7)(1 2), (7)(3 4), (7)(4 5), (7)(0 3)(1 4)(2 5)]) two symmetric tensors with 3 indices with free indices in slot 1 and 0 >>> tensor_gens(base, gens, [[1], [0]]) (8, [0, 4], [(7)(0 2), (7)(4 5)]) four symmetric tensors with 3 indices, two of which with free indices """ def _get_bsgs(G, base, gens, free_indices): """ return the BSGS for G.pointwise_stabilizer(free_indices) """ if not free_indices: return base[:], gens[:] else: H = G.pointwise_stabilizer(free_indices) base, sgs = H.schreier_sims_incremental() return base, sgs # if not base there is no slot symmetry for the component tensors # if list_free_indices.count([]) < 2 there is no commutation symmetry # so there is no resulting slot symmetry if not base and list_free_indices.count([]) < 2: n = len(list_free_indices) size = gens[0].size size = n * (size - 2) + 2 return size, [], [_af_new(list(range(size)))] # if any(list_free_indices) one needs to compute the pointwise # stabilizer, so G is needed if any(list_free_indices): G = PermutationGroup(gens) else: G = None # no_free list of lists of indices for component tensors without fixed # indices no_free = [] size = gens[0].size id_af = list(range(size)) num_indices = size - 2 if not list_free_indices[0]: no_free.append(list(range(num_indices))) res_base, res_gens = _get_bsgs(G, base, gens, list_free_indices[0]) for i in range(1, len(list_free_indices)): base1, gens1 = _get_bsgs(G, base, gens, list_free_indices[i]) res_base, res_gens = bsgs_direct_product(res_base, res_gens, base1, gens1, 1) if not list_free_indices[i]: no_free.append(list(range(size - 2, size - 2 + num_indices))) size += num_indices nr = size - 2 res_gens = [h for h in res_gens if h._array_form != id_af] # if sym there are no commuting tensors stop here if sym is None or not no_free: if not res_gens: res_gens = [_af_new(id_af)] return size, res_base, res_gens # if the component tensors have moinimal BSGS, so is their direct # product P; the slot symmetry group is S = P*C, where C is the group # to (anti)commute the component tensors with no free indices # a stabilizer has the property S_i = P_i*C_i; # the BSGS of P*C has SGS_P + SGS_C and the base is # the ordered union of the bases of P and C. # If P has minimal BSGS, so has S with this base. base_comm = [] for i in range(len(no_free) - 1): ind1 = no_free[i] ind2 = no_free[i + 1] a = list(range(ind1[0])) a.extend(ind2) a.extend(ind1) base_comm.append(ind1[0]) a.extend(list(range(ind2[-1] + 1, nr))) if sym == 0: a.extend([nr, nr + 1]) else: a.extend([nr + 1, nr]) res_gens.append(_af_new(a)) res_base = list(res_base) # each base is ordered; order the union of the two bases for i in base_comm: if i not in res_base: res_base.append(i) res_base.sort() if not res_gens: res_gens = [_af_new(id_af)] return size, res_base, res_gens def gens_products(*v): """ Returns size, res_base, res_gens BSGS for n tensors of different types. Explanation =========== v is a sequence of (base_i, gens_i, free_i, sym_i) where base_i, gens_i BSGS of tensor of type `i` free_i list of the fixed slots for each of the tensors of type `i`; if there are `n_i` tensors of type `i` and none of them have fixed slots, `free = [[]]*n_i` sym 0 (1) if the tensors of type `i` (anti)commute among themselves Examples ======== >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, gens_products >>> base, gens = get_symmetric_group_sgs(2) >>> gens_products((base, gens, [[], []], 0)) (6, [0, 2], [(5)(0 1), (5)(2 3), (5)(0 2)(1 3)]) >>> gens_products((base, gens, [[1], []], 0)) (6, [2], [(5)(2 3)]) """ res_size, res_base, res_gens = tensor_gens(*v[0]) for i in range(1, len(v)): size, base, gens = tensor_gens(*v[i]) res_base, res_gens = bsgs_direct_product(res_base, res_gens, base, gens, 1) res_size = res_gens[0].size id_af = list(range(res_size)) res_gens = [h for h in res_gens if h != id_af] if not res_gens: res_gens = [id_af] return res_size, res_base, res_gens
bf205b360d705c971f9310693dd3d0e01ac34251c8cbd1d1ce52c53a3cf73a52
from sympy.combinatorics import Permutation as Perm from sympy.combinatorics.perm_groups import PermutationGroup from sympy.core import Basic, Tuple from sympy.core.compatibility import as_int from sympy.sets import FiniteSet from sympy.utilities.iterables import (minlex, unflatten, flatten, default_sort_key) rmul = Perm.rmul class Polyhedron(Basic): """ Represents the polyhedral symmetry group (PSG). Explanation =========== The PSG is one of the symmetry groups of the Platonic solids. There are three polyhedral groups: the tetrahedral group of order 12, the octahedral group of order 24, and the icosahedral group of order 60. All doctests have been given in the docstring of the constructor of the object. References ========== .. [1] http://mathworld.wolfram.com/PolyhedralGroup.html """ _edges = None def __new__(cls, corners, faces=(), pgroup=()): """ The constructor of the Polyhedron group object. Explanation =========== It takes up to three parameters: the corners, faces, and allowed transformations. The corners/vertices are entered as a list of arbitrary expressions that are used to identify each vertex. The faces are entered as a list of tuples of indices; a tuple of indices identifies the vertices which define the face. They should be entered in a cw or ccw order; they will be standardized by reversal and rotation to be give the lowest lexical ordering. If no faces are given then no edges will be computed. >>> from sympy.combinatorics.polyhedron import Polyhedron >>> Polyhedron(list('abc'), [(1, 2, 0)]).faces {(0, 1, 2)} >>> Polyhedron(list('abc'), [(1, 0, 2)]).faces {(0, 1, 2)} The allowed transformations are entered as allowable permutations of the vertices for the polyhedron. Instance of Permutations (as with faces) should refer to the supplied vertices by index. These permutation are stored as a PermutationGroup. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.interactive import init_printing >>> from sympy.abc import w, x, y, z >>> init_printing(pretty_print=False, perm_cyclic=False) Here we construct the Polyhedron object for a tetrahedron. >>> corners = [w, x, y, z] >>> faces = [(0, 1, 2), (0, 2, 3), (0, 3, 1), (1, 2, 3)] Next, allowed transformations of the polyhedron must be given. This is given as permutations of vertices. Although the vertices of a tetrahedron can be numbered in 24 (4!) different ways, there are only 12 different orientations for a physical tetrahedron. The following permutations, applied once or twice, will generate all 12 of the orientations. (The identity permutation, Permutation(range(4)), is not included since it does not change the orientation of the vertices.) >>> pgroup = [Permutation([[0, 1, 2], [3]]), \ Permutation([[0, 1, 3], [2]]), \ Permutation([[0, 2, 3], [1]]), \ Permutation([[1, 2, 3], [0]]), \ Permutation([[0, 1], [2, 3]]), \ Permutation([[0, 2], [1, 3]]), \ Permutation([[0, 3], [1, 2]])] The Polyhedron is now constructed and demonstrated: >>> tetra = Polyhedron(corners, faces, pgroup) >>> tetra.size 4 >>> tetra.edges {(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)} >>> tetra.corners (w, x, y, z) It can be rotated with an arbitrary permutation of vertices, e.g. the following permutation is not in the pgroup: >>> tetra.rotate(Permutation([0, 1, 3, 2])) >>> tetra.corners (w, x, z, y) An allowed permutation of the vertices can be constructed by repeatedly applying permutations from the pgroup to the vertices. Here is a demonstration that applying p and p**2 for every p in pgroup generates all the orientations of a tetrahedron and no others: >>> all = ( (w, x, y, z), \ (x, y, w, z), \ (y, w, x, z), \ (w, z, x, y), \ (z, w, y, x), \ (w, y, z, x), \ (y, z, w, x), \ (x, z, y, w), \ (z, y, x, w), \ (y, x, z, w), \ (x, w, z, y), \ (z, x, w, y) ) >>> got = [] >>> for p in (pgroup + [p**2 for p in pgroup]): ... h = Polyhedron(corners) ... h.rotate(p) ... got.append(h.corners) ... >>> set(got) == set(all) True The make_perm method of a PermutationGroup will randomly pick permutations, multiply them together, and return the permutation that can be applied to the polyhedron to give the orientation produced by those individual permutations. Here, 3 permutations are used: >>> tetra.pgroup.make_perm(3) # doctest: +SKIP Permutation([0, 3, 1, 2]) To select the permutations that should be used, supply a list of indices to the permutations in pgroup in the order they should be applied: >>> use = [0, 0, 2] >>> p002 = tetra.pgroup.make_perm(3, use) >>> p002 Permutation([1, 0, 3, 2]) Apply them one at a time: >>> tetra.reset() >>> for i in use: ... tetra.rotate(pgroup[i]) ... >>> tetra.vertices (x, w, z, y) >>> sequentially = tetra.vertices Apply the composite permutation: >>> tetra.reset() >>> tetra.rotate(p002) >>> tetra.corners (x, w, z, y) >>> tetra.corners in all and tetra.corners == sequentially True Notes ===== Defining permutation groups --------------------------- It is not necessary to enter any permutations, nor is necessary to enter a complete set of transformations. In fact, for a polyhedron, all configurations can be constructed from just two permutations. For example, the orientations of a tetrahedron can be generated from an axis passing through a vertex and face and another axis passing through a different vertex or from an axis passing through the midpoints of two edges opposite of each other. For simplicity of presentation, consider a square -- not a cube -- with vertices 1, 2, 3, and 4: 1-----2 We could think of axes of rotation being: | | 1) through the face | | 2) from midpoint 1-2 to 3-4 or 1-3 to 2-4 3-----4 3) lines 1-4 or 2-3 To determine how to write the permutations, imagine 4 cameras, one at each corner, labeled A-D: A B A B 1-----2 1-----3 vertex index: | | | | 1 0 | | | | 2 1 3-----4 2-----4 3 2 C D C D 4 3 original after rotation along 1-4 A diagonal and a face axis will be chosen for the "permutation group" from which any orientation can be constructed. >>> pgroup = [] Imagine a clockwise rotation when viewing 1-4 from camera A. The new orientation is (in camera-order): 1, 3, 2, 4 so the permutation is given using the *indices* of the vertices as: >>> pgroup.append(Permutation((0, 2, 1, 3))) Now imagine rotating clockwise when looking down an axis entering the center of the square as viewed. The new camera-order would be 3, 1, 4, 2 so the permutation is (using indices): >>> pgroup.append(Permutation((2, 0, 3, 1))) The square can now be constructed: ** use real-world labels for the vertices, entering them in camera order ** for the faces we use zero-based indices of the vertices in *edge-order* as the face is traversed; neither the direction nor the starting point matter -- the faces are only used to define edges (if so desired). >>> square = Polyhedron((1, 2, 3, 4), [(0, 1, 3, 2)], pgroup) To rotate the square with a single permutation we can do: >>> square.rotate(square.pgroup[0]) >>> square.corners (1, 3, 2, 4) To use more than one permutation (or to use one permutation more than once) it is more convenient to use the make_perm method: >>> p011 = square.pgroup.make_perm([0, 1, 1]) # diag flip + 2 rotations >>> square.reset() # return to initial orientation >>> square.rotate(p011) >>> square.corners (4, 2, 3, 1) Thinking outside the box ------------------------ Although the Polyhedron object has a direct physical meaning, it actually has broader application. In the most general sense it is just a decorated PermutationGroup, allowing one to connect the permutations to something physical. For example, a Rubik's cube is not a proper polyhedron, but the Polyhedron class can be used to represent it in a way that helps to visualize the Rubik's cube. >>> from sympy.utilities.iterables import flatten, unflatten >>> from sympy import symbols >>> from sympy.combinatorics import RubikGroup >>> facelets = flatten([symbols(s+'1:5') for s in 'UFRBLD']) >>> def show(): ... pairs = unflatten(r2.corners, 2) ... print(pairs[::2]) ... print(pairs[1::2]) ... >>> r2 = Polyhedron(facelets, pgroup=RubikGroup(2)) >>> show() [(U1, U2), (F1, F2), (R1, R2), (B1, B2), (L1, L2), (D1, D2)] [(U3, U4), (F3, F4), (R3, R4), (B3, B4), (L3, L4), (D3, D4)] >>> r2.rotate(0) # cw rotation of F >>> show() [(U1, U2), (F3, F1), (U3, R2), (B1, B2), (L1, D1), (R3, R1)] [(L4, L2), (F4, F2), (U4, R4), (B3, B4), (L3, D2), (D3, D4)] Predefined Polyhedra ==================== For convenience, the vertices and faces are defined for the following standard solids along with a permutation group for transformations. When the polyhedron is oriented as indicated below, the vertices in a given horizontal plane are numbered in ccw direction, starting from the vertex that will give the lowest indices in a given face. (In the net of the vertices, indices preceded by "-" indicate replication of the lhs index in the net.) tetrahedron, tetrahedron_faces ------------------------------ 4 vertices (vertex up) net: 0 0-0 1 2 3-1 4 faces: (0, 1, 2) (0, 2, 3) (0, 3, 1) (1, 2, 3) cube, cube_faces ---------------- 8 vertices (face up) net: 0 1 2 3-0 4 5 6 7-4 6 faces: (0, 1, 2, 3) (0, 1, 5, 4) (1, 2, 6, 5) (2, 3, 7, 6) (0, 3, 7, 4) (4, 5, 6, 7) octahedron, octahedron_faces ---------------------------- 6 vertices (vertex up) net: 0 0 0-0 1 2 3 4-1 5 5 5-5 8 faces: (0, 1, 2) (0, 2, 3) (0, 3, 4) (0, 1, 4) (1, 2, 5) (2, 3, 5) (3, 4, 5) (1, 4, 5) dodecahedron, dodecahedron_faces -------------------------------- 20 vertices (vertex up) net: 0 1 2 3 4 -0 5 6 7 8 9 -5 14 10 11 12 13-14 15 16 17 18 19-15 12 faces: (0, 1, 2, 3, 4) (0, 1, 6, 10, 5) (1, 2, 7, 11, 6) (2, 3, 8, 12, 7) (3, 4, 9, 13, 8) (0, 4, 9, 14, 5) (5, 10, 16, 15, 14) (6, 10, 16, 17, 11) (7, 11, 17, 18, 12) (8, 12, 18, 19, 13) (9, 13, 19, 15, 14)(15, 16, 17, 18, 19) icosahedron, icosahedron_faces ------------------------------ 12 vertices (face up) net: 0 0 0 0 -0 1 2 3 4 5 -1 6 7 8 9 10 -6 11 11 11 11 -11 20 faces: (0, 1, 2) (0, 2, 3) (0, 3, 4) (0, 4, 5) (0, 1, 5) (1, 2, 6) (2, 3, 7) (3, 4, 8) (4, 5, 9) (1, 5, 10) (2, 6, 7) (3, 7, 8) (4, 8, 9) (5, 9, 10) (1, 6, 10) (6, 7, 11) (7, 8, 11) (8, 9, 11) (9, 10, 11) (6, 10, 11) >>> from sympy.combinatorics.polyhedron import cube >>> cube.edges {(0, 1), (0, 3), (0, 4), (1, 2), (1, 5), (2, 3), (2, 6), (3, 7), (4, 5), (4, 7), (5, 6), (6, 7)} If you want to use letters or other names for the corners you can still use the pre-calculated faces: >>> corners = list('abcdefgh') >>> Polyhedron(corners, cube.faces).corners (a, b, c, d, e, f, g, h) References ========== .. [1] www.ocf.berkeley.edu/~wwu/articles/platonicsolids.pdf """ faces = [minlex(f, directed=False, key=default_sort_key) for f in faces] corners, faces, pgroup = args = \ [Tuple(*a) for a in (corners, faces, pgroup)] obj = Basic.__new__(cls, *args) obj._corners = tuple(corners) # in order given obj._faces = FiniteSet(*faces) if pgroup and pgroup[0].size != len(corners): raise ValueError("Permutation size unequal to number of corners.") # use the identity permutation if none are given obj._pgroup = PermutationGroup( pgroup or [Perm(range(len(corners)))] ) return obj @property def corners(self): """ Get the corners of the Polyhedron. The method ``vertices`` is an alias for ``corners``. Examples ======== >>> from sympy.combinatorics import Polyhedron >>> from sympy.abc import a, b, c, d >>> p = Polyhedron(list('abcd')) >>> p.corners == p.vertices == (a, b, c, d) True See Also ======== array_form, cyclic_form """ return self._corners vertices = corners @property def array_form(self): """Return the indices of the corners. The indices are given relative to the original position of corners. Examples ======== >>> from sympy.combinatorics.polyhedron import tetrahedron >>> tetrahedron = tetrahedron.copy() >>> tetrahedron.array_form [0, 1, 2, 3] >>> tetrahedron.rotate(0) >>> tetrahedron.array_form [0, 2, 3, 1] >>> tetrahedron.pgroup[0].array_form [0, 2, 3, 1] See Also ======== corners, cyclic_form """ corners = list(self.args[0]) return [corners.index(c) for c in self.corners] @property def cyclic_form(self): """Return the indices of the corners in cyclic notation. The indices are given relative to the original position of corners. See Also ======== corners, array_form """ return Perm._af_new(self.array_form).cyclic_form @property def size(self): """ Get the number of corners of the Polyhedron. """ return len(self._corners) @property def faces(self): """ Get the faces of the Polyhedron. """ return self._faces @property def pgroup(self): """ Get the permutations of the Polyhedron. """ return self._pgroup @property def edges(self): """ Given the faces of the polyhedra we can get the edges. Examples ======== >>> from sympy.combinatorics import Polyhedron >>> from sympy.abc import a, b, c >>> corners = (a, b, c) >>> faces = [(0, 1, 2)] >>> Polyhedron(corners, faces).edges {(0, 1), (0, 2), (1, 2)} """ if self._edges is None: output = set() for face in self.faces: for i in range(len(face)): edge = tuple(sorted([face[i], face[i - 1]])) output.add(edge) self._edges = FiniteSet(*output) return self._edges def rotate(self, perm): """ Apply a permutation to the polyhedron *in place*. The permutation may be given as a Permutation instance or an integer indicating which permutation from pgroup of the Polyhedron should be applied. This is an operation that is analogous to rotation about an axis by a fixed increment. Notes ===== When a Permutation is applied, no check is done to see if that is a valid permutation for the Polyhedron. For example, a cube could be given a permutation which effectively swaps only 2 vertices. A valid permutation (that rotates the object in a physical way) will be obtained if one only uses permutations from the ``pgroup`` of the Polyhedron. On the other hand, allowing arbitrary rotations (applications of permutations) gives a way to follow named elements rather than indices since Polyhedron allows vertices to be named while Permutation works only with indices. Examples ======== >>> from sympy.combinatorics import Polyhedron, Permutation >>> from sympy.combinatorics.polyhedron import cube >>> cube = cube.copy() >>> cube.corners (0, 1, 2, 3, 4, 5, 6, 7) >>> cube.rotate(0) >>> cube.corners (1, 2, 3, 0, 5, 6, 7, 4) A non-physical "rotation" that is not prohibited by this method: >>> cube.reset() >>> cube.rotate(Permutation([[1, 2]], size=8)) >>> cube.corners (0, 2, 1, 3, 4, 5, 6, 7) Polyhedron can be used to follow elements of set that are identified by letters instead of integers: >>> shadow = h5 = Polyhedron(list('abcde')) >>> p = Permutation([3, 0, 1, 2, 4]) >>> h5.rotate(p) >>> h5.corners (d, a, b, c, e) >>> _ == shadow.corners True >>> copy = h5.copy() >>> h5.rotate(p) >>> h5.corners == copy.corners False """ if not isinstance(perm, Perm): perm = self.pgroup[perm] # and we know it's valid else: if perm.size != self.size: raise ValueError('Polyhedron and Permutation sizes differ.') a = perm.array_form corners = [self.corners[a[i]] for i in range(len(self.corners))] self._corners = tuple(corners) def reset(self): """Return corners to their original positions. Examples ======== >>> from sympy.combinatorics.polyhedron import tetrahedron as T >>> T = T.copy() >>> T.corners (0, 1, 2, 3) >>> T.rotate(0) >>> T.corners (0, 2, 3, 1) >>> T.reset() >>> T.corners (0, 1, 2, 3) """ self._corners = self.args[0] def _pgroup_calcs(): """Return the permutation groups for each of the polyhedra and the face definitions: tetrahedron, cube, octahedron, dodecahedron, icosahedron, tetrahedron_faces, cube_faces, octahedron_faces, dodecahedron_faces, icosahedron_faces Explanation =========== (This author didn't find and didn't know of a better way to do it though there likely is such a way.) Although only 2 permutations are needed for a polyhedron in order to generate all the possible orientations, a group of permutations is provided instead. A set of permutations is called a "group" if:: a*b = c (for any pair of permutations in the group, a and b, their product, c, is in the group) a*(b*c) = (a*b)*c (for any 3 permutations in the group associativity holds) there is an identity permutation, I, such that I*a = a*I for all elements in the group a*b = I (the inverse of each permutation is also in the group) None of the polyhedron groups defined follow these definitions of a group. Instead, they are selected to contain those permutations whose powers alone will construct all orientations of the polyhedron, i.e. for permutations ``a``, ``b``, etc... in the group, ``a, a**2, ..., a**o_a``, ``b, b**2, ..., b**o_b``, etc... (where ``o_i`` is the order of permutation ``i``) generate all permutations of the polyhedron instead of mixed products like ``a*b``, ``a*b**2``, etc.... Note that for a polyhedron with n vertices, the valid permutations of the vertices exclude those that do not maintain its faces. e.g. the permutation BCDE of a square's four corners, ABCD, is a valid permutation while CBDE is not (because this would twist the square). Examples ======== The is_group checks for: closure, the presence of the Identity permutation, and the presence of the inverse for each of the elements in the group. This confirms that none of the polyhedra are true groups: >>> from sympy.combinatorics.polyhedron import ( ... tetrahedron, cube, octahedron, dodecahedron, icosahedron) ... >>> polyhedra = (tetrahedron, cube, octahedron, dodecahedron, icosahedron) >>> [h.pgroup.is_group for h in polyhedra] ... [True, True, True, True, True] Although tests in polyhedron's test suite check that powers of the permutations in the groups generate all permutations of the vertices of the polyhedron, here we also demonstrate the powers of the given permutations create a complete group for the tetrahedron: >>> from sympy.combinatorics import Permutation, PermutationGroup >>> for h in polyhedra[:1]: ... G = h.pgroup ... perms = set() ... for g in G: ... for e in range(g.order()): ... p = tuple((g**e).array_form) ... perms.add(p) ... ... perms = [Permutation(p) for p in perms] ... assert PermutationGroup(perms).is_group In addition to doing the above, the tests in the suite confirm that the faces are all present after the application of each permutation. References ========== .. [1] http://dogschool.tripod.com/trianglegroup.html """ def _pgroup_of_double(polyh, ordered_faces, pgroup): n = len(ordered_faces[0]) # the vertices of the double which sits inside a give polyhedron # can be found by tracking the faces of the outer polyhedron. # A map between face and the vertex of the double is made so that # after rotation the position of the vertices can be located fmap = dict(zip(ordered_faces, range(len(ordered_faces)))) flat_faces = flatten(ordered_faces) new_pgroup = [] for i, p in enumerate(pgroup): h = polyh.copy() h.rotate(p) c = h.corners # reorder corners in the order they should appear when # enumerating the faces reorder = unflatten([c[j] for j in flat_faces], n) # make them canonical reorder = [tuple(map(as_int, minlex(f, directed=False))) for f in reorder] # map face to vertex: the resulting list of vertices are the # permutation that we seek for the double new_pgroup.append(Perm([fmap[f] for f in reorder])) return new_pgroup tetrahedron_faces = [ (0, 1, 2), (0, 2, 3), (0, 3, 1), # upper 3 (1, 2, 3), # bottom ] # cw from top # _t_pgroup = [ Perm([[1, 2, 3], [0]]), # cw from top Perm([[0, 1, 2], [3]]), # cw from front face Perm([[0, 3, 2], [1]]), # cw from back right face Perm([[0, 3, 1], [2]]), # cw from back left face Perm([[0, 1], [2, 3]]), # through front left edge Perm([[0, 2], [1, 3]]), # through front right edge Perm([[0, 3], [1, 2]]), # through back edge ] tetrahedron = Polyhedron( range(4), tetrahedron_faces, _t_pgroup) cube_faces = [ (0, 1, 2, 3), # upper (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (0, 3, 7, 4), # middle 4 (4, 5, 6, 7), # lower ] # U, D, F, B, L, R = up, down, front, back, left, right _c_pgroup = [Perm(p) for p in [ [1, 2, 3, 0, 5, 6, 7, 4], # cw from top, U [4, 0, 3, 7, 5, 1, 2, 6], # cw from F face [4, 5, 1, 0, 7, 6, 2, 3], # cw from R face [1, 0, 4, 5, 2, 3, 7, 6], # cw through UF edge [6, 2, 1, 5, 7, 3, 0, 4], # cw through UR edge [6, 7, 3, 2, 5, 4, 0, 1], # cw through UB edge [3, 7, 4, 0, 2, 6, 5, 1], # cw through UL edge [4, 7, 6, 5, 0, 3, 2, 1], # cw through FL edge [6, 5, 4, 7, 2, 1, 0, 3], # cw through FR edge [0, 3, 7, 4, 1, 2, 6, 5], # cw through UFL vertex [5, 1, 0, 4, 6, 2, 3, 7], # cw through UFR vertex [5, 6, 2, 1, 4, 7, 3, 0], # cw through UBR vertex [7, 4, 0, 3, 6, 5, 1, 2], # cw through UBL ]] cube = Polyhedron( range(8), cube_faces, _c_pgroup) octahedron_faces = [ (0, 1, 2), (0, 2, 3), (0, 3, 4), (0, 1, 4), # top 4 (1, 2, 5), (2, 3, 5), (3, 4, 5), (1, 4, 5), # bottom 4 ] octahedron = Polyhedron( range(6), octahedron_faces, _pgroup_of_double(cube, cube_faces, _c_pgroup)) dodecahedron_faces = [ (0, 1, 2, 3, 4), # top (0, 1, 6, 10, 5), (1, 2, 7, 11, 6), (2, 3, 8, 12, 7), # upper 5 (3, 4, 9, 13, 8), (0, 4, 9, 14, 5), (5, 10, 16, 15, 14), (6, 10, 16, 17, 11), (7, 11, 17, 18, 12), # lower 5 (8, 12, 18, 19, 13), (9, 13, 19, 15, 14), (15, 16, 17, 18, 19) # bottom ] def _string_to_perm(s): rv = [Perm(range(20))] p = None for si in s: if si not in '01': count = int(si) - 1 else: count = 1 if si == '0': p = _f0 elif si == '1': p = _f1 rv.extend([p]*count) return Perm.rmul(*rv) # top face cw _f0 = Perm([ 1, 2, 3, 4, 0, 6, 7, 8, 9, 5, 11, 12, 13, 14, 10, 16, 17, 18, 19, 15]) # front face cw _f1 = Perm([ 5, 0, 4, 9, 14, 10, 1, 3, 13, 15, 6, 2, 8, 19, 16, 17, 11, 7, 12, 18]) # the strings below, like 0104 are shorthand for F0*F1*F0**4 and are # the remaining 4 face rotations, 15 edge permutations, and the # 10 vertex rotations. _dodeca_pgroup = [_f0, _f1] + [_string_to_perm(s) for s in ''' 0104 140 014 0410 010 1403 03104 04103 102 120 1304 01303 021302 03130 0412041 041204103 04120410 041204104 041204102 10 01 1402 0140 04102 0412 1204 1302 0130 03120'''.strip().split()] dodecahedron = Polyhedron( range(20), dodecahedron_faces, _dodeca_pgroup) icosahedron_faces = [ (0, 1, 2), (0, 2, 3), (0, 3, 4), (0, 4, 5), (0, 1, 5), (1, 6, 7), (1, 2, 7), (2, 7, 8), (2, 3, 8), (3, 8, 9), (3, 4, 9), (4, 9, 10), (4, 5, 10), (5, 6, 10), (1, 5, 6), (6, 7, 11), (7, 8, 11), (8, 9, 11), (9, 10, 11), (6, 10, 11)] icosahedron = Polyhedron( range(12), icosahedron_faces, _pgroup_of_double( dodecahedron, dodecahedron_faces, _dodeca_pgroup)) return (tetrahedron, cube, octahedron, dodecahedron, icosahedron, tetrahedron_faces, cube_faces, octahedron_faces, dodecahedron_faces, icosahedron_faces) # ----------------------------------------------------------------------- # Standard Polyhedron groups # # These are generated using _pgroup_calcs() above. However to save # import time we encode them explicitly here. # ----------------------------------------------------------------------- tetrahedron = Polyhedron( Tuple(0, 1, 2, 3), Tuple( Tuple(0, 1, 2), Tuple(0, 2, 3), Tuple(0, 1, 3), Tuple(1, 2, 3)), Tuple( Perm(1, 2, 3), Perm(3)(0, 1, 2), Perm(0, 3, 2), Perm(0, 3, 1), Perm(0, 1)(2, 3), Perm(0, 2)(1, 3), Perm(0, 3)(1, 2) )) cube = Polyhedron( Tuple(0, 1, 2, 3, 4, 5, 6, 7), Tuple( Tuple(0, 1, 2, 3), Tuple(0, 1, 5, 4), Tuple(1, 2, 6, 5), Tuple(2, 3, 7, 6), Tuple(0, 3, 7, 4), Tuple(4, 5, 6, 7)), Tuple( Perm(0, 1, 2, 3)(4, 5, 6, 7), Perm(0, 4, 5, 1)(2, 3, 7, 6), Perm(0, 4, 7, 3)(1, 5, 6, 2), Perm(0, 1)(2, 4)(3, 5)(6, 7), Perm(0, 6)(1, 2)(3, 5)(4, 7), Perm(0, 6)(1, 7)(2, 3)(4, 5), Perm(0, 3)(1, 7)(2, 4)(5, 6), Perm(0, 4)(1, 7)(2, 6)(3, 5), Perm(0, 6)(1, 5)(2, 4)(3, 7), Perm(1, 3, 4)(2, 7, 5), Perm(7)(0, 5, 2)(3, 4, 6), Perm(0, 5, 7)(1, 6, 3), Perm(0, 7, 2)(1, 4, 6))) octahedron = Polyhedron( Tuple(0, 1, 2, 3, 4, 5), Tuple( Tuple(0, 1, 2), Tuple(0, 2, 3), Tuple(0, 3, 4), Tuple(0, 1, 4), Tuple(1, 2, 5), Tuple(2, 3, 5), Tuple(3, 4, 5), Tuple(1, 4, 5)), Tuple( Perm(5)(1, 2, 3, 4), Perm(0, 4, 5, 2), Perm(0, 1, 5, 3), Perm(0, 1)(2, 4)(3, 5), Perm(0, 2)(1, 3)(4, 5), Perm(0, 3)(1, 5)(2, 4), Perm(0, 4)(1, 3)(2, 5), Perm(0, 5)(1, 4)(2, 3), Perm(0, 5)(1, 2)(3, 4), Perm(0, 4, 1)(2, 3, 5), Perm(0, 1, 2)(3, 4, 5), Perm(0, 2, 3)(1, 5, 4), Perm(0, 4, 3)(1, 5, 2))) dodecahedron = Polyhedron( Tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19), Tuple( Tuple(0, 1, 2, 3, 4), Tuple(0, 1, 6, 10, 5), Tuple(1, 2, 7, 11, 6), Tuple(2, 3, 8, 12, 7), Tuple(3, 4, 9, 13, 8), Tuple(0, 4, 9, 14, 5), Tuple(5, 10, 16, 15, 14), Tuple(6, 10, 16, 17, 11), Tuple(7, 11, 17, 18, 12), Tuple(8, 12, 18, 19, 13), Tuple(9, 13, 19, 15, 14), Tuple(15, 16, 17, 18, 19)), Tuple( Perm(0, 1, 2, 3, 4)(5, 6, 7, 8, 9)(10, 11, 12, 13, 14)(15, 16, 17, 18, 19), Perm(0, 5, 10, 6, 1)(2, 4, 14, 16, 11)(3, 9, 15, 17, 7)(8, 13, 19, 18, 12), Perm(0, 10, 17, 12, 3)(1, 6, 11, 7, 2)(4, 5, 16, 18, 8)(9, 14, 15, 19, 13), Perm(0, 6, 17, 19, 9)(1, 11, 18, 13, 4)(2, 7, 12, 8, 3)(5, 10, 16, 15, 14), Perm(0, 2, 12, 19, 14)(1, 7, 18, 15, 5)(3, 8, 13, 9, 4)(6, 11, 17, 16, 10), Perm(0, 4, 9, 14, 5)(1, 3, 13, 15, 10)(2, 8, 19, 16, 6)(7, 12, 18, 17, 11), Perm(0, 1)(2, 5)(3, 10)(4, 6)(7, 14)(8, 16)(9, 11)(12, 15)(13, 17)(18, 19), Perm(0, 7)(1, 2)(3, 6)(4, 11)(5, 12)(8, 10)(9, 17)(13, 16)(14, 18)(15, 19), Perm(0, 12)(1, 8)(2, 3)(4, 7)(5, 18)(6, 13)(9, 11)(10, 19)(14, 17)(15, 16), Perm(0, 8)(1, 13)(2, 9)(3, 4)(5, 12)(6, 19)(7, 14)(10, 18)(11, 15)(16, 17), Perm(0, 4)(1, 9)(2, 14)(3, 5)(6, 13)(7, 15)(8, 10)(11, 19)(12, 16)(17, 18), Perm(0, 5)(1, 14)(2, 15)(3, 16)(4, 10)(6, 9)(7, 19)(8, 17)(11, 13)(12, 18), Perm(0, 11)(1, 6)(2, 10)(3, 16)(4, 17)(5, 7)(8, 15)(9, 18)(12, 14)(13, 19), Perm(0, 18)(1, 12)(2, 7)(3, 11)(4, 17)(5, 19)(6, 8)(9, 16)(10, 13)(14, 15), Perm(0, 18)(1, 19)(2, 13)(3, 8)(4, 12)(5, 17)(6, 15)(7, 9)(10, 16)(11, 14), Perm(0, 13)(1, 19)(2, 15)(3, 14)(4, 9)(5, 8)(6, 18)(7, 16)(10, 12)(11, 17), Perm(0, 16)(1, 15)(2, 19)(3, 18)(4, 17)(5, 10)(6, 14)(7, 13)(8, 12)(9, 11), Perm(0, 18)(1, 17)(2, 16)(3, 15)(4, 19)(5, 12)(6, 11)(7, 10)(8, 14)(9, 13), Perm(0, 15)(1, 19)(2, 18)(3, 17)(4, 16)(5, 14)(6, 13)(7, 12)(8, 11)(9, 10), Perm(0, 17)(1, 16)(2, 15)(3, 19)(4, 18)(5, 11)(6, 10)(7, 14)(8, 13)(9, 12), Perm(0, 19)(1, 18)(2, 17)(3, 16)(4, 15)(5, 13)(6, 12)(7, 11)(8, 10)(9, 14), Perm(1, 4, 5)(2, 9, 10)(3, 14, 6)(7, 13, 16)(8, 15, 11)(12, 19, 17), Perm(19)(0, 6, 2)(3, 5, 11)(4, 10, 7)(8, 14, 17)(9, 16, 12)(13, 15, 18), Perm(0, 11, 8)(1, 7, 3)(4, 6, 12)(5, 17, 13)(9, 10, 18)(14, 16, 19), Perm(0, 7, 13)(1, 12, 9)(2, 8, 4)(5, 11, 19)(6, 18, 14)(10, 17, 15), Perm(0, 3, 9)(1, 8, 14)(2, 13, 5)(6, 12, 15)(7, 19, 10)(11, 18, 16), Perm(0, 14, 10)(1, 9, 16)(2, 13, 17)(3, 19, 11)(4, 15, 6)(7, 8, 18), Perm(0, 16, 7)(1, 10, 11)(2, 5, 17)(3, 14, 18)(4, 15, 12)(8, 9, 19), Perm(0, 16, 13)(1, 17, 8)(2, 11, 12)(3, 6, 18)(4, 10, 19)(5, 15, 9), Perm(0, 11, 15)(1, 17, 14)(2, 18, 9)(3, 12, 13)(4, 7, 19)(5, 6, 16), Perm(0, 8, 15)(1, 12, 16)(2, 18, 10)(3, 19, 5)(4, 13, 14)(6, 7, 17))) icosahedron = Polyhedron( Tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), Tuple( Tuple(0, 1, 2), Tuple(0, 2, 3), Tuple(0, 3, 4), Tuple(0, 4, 5), Tuple(0, 1, 5), Tuple(1, 6, 7), Tuple(1, 2, 7), Tuple(2, 7, 8), Tuple(2, 3, 8), Tuple(3, 8, 9), Tuple(3, 4, 9), Tuple(4, 9, 10), Tuple(4, 5, 10), Tuple(5, 6, 10), Tuple(1, 5, 6), Tuple(6, 7, 11), Tuple(7, 8, 11), Tuple(8, 9, 11), Tuple(9, 10, 11), Tuple(6, 10, 11)), Tuple( Perm(11)(1, 2, 3, 4, 5)(6, 7, 8, 9, 10), Perm(0, 5, 6, 7, 2)(3, 4, 10, 11, 8), Perm(0, 1, 7, 8, 3)(4, 5, 6, 11, 9), Perm(0, 2, 8, 9, 4)(1, 7, 11, 10, 5), Perm(0, 3, 9, 10, 5)(1, 2, 8, 11, 6), Perm(0, 4, 10, 6, 1)(2, 3, 9, 11, 7), Perm(0, 1)(2, 5)(3, 6)(4, 7)(8, 10)(9, 11), Perm(0, 2)(1, 3)(4, 7)(5, 8)(6, 9)(10, 11), Perm(0, 3)(1, 9)(2, 4)(5, 8)(6, 11)(7, 10), Perm(0, 4)(1, 9)(2, 10)(3, 5)(6, 8)(7, 11), Perm(0, 5)(1, 4)(2, 10)(3, 6)(7, 9)(8, 11), Perm(0, 6)(1, 5)(2, 10)(3, 11)(4, 7)(8, 9), Perm(0, 7)(1, 2)(3, 6)(4, 11)(5, 8)(9, 10), Perm(0, 8)(1, 9)(2, 3)(4, 7)(5, 11)(6, 10), Perm(0, 9)(1, 11)(2, 10)(3, 4)(5, 8)(6, 7), Perm(0, 10)(1, 9)(2, 11)(3, 6)(4, 5)(7, 8), Perm(0, 11)(1, 6)(2, 10)(3, 9)(4, 8)(5, 7), Perm(0, 11)(1, 8)(2, 7)(3, 6)(4, 10)(5, 9), Perm(0, 11)(1, 10)(2, 9)(3, 8)(4, 7)(5, 6), Perm(0, 11)(1, 7)(2, 6)(3, 10)(4, 9)(5, 8), Perm(0, 11)(1, 9)(2, 8)(3, 7)(4, 6)(5, 10), Perm(0, 5, 1)(2, 4, 6)(3, 10, 7)(8, 9, 11), Perm(0, 1, 2)(3, 5, 7)(4, 6, 8)(9, 10, 11), Perm(0, 2, 3)(1, 8, 4)(5, 7, 9)(6, 11, 10), Perm(0, 3, 4)(1, 8, 10)(2, 9, 5)(6, 7, 11), Perm(0, 4, 5)(1, 3, 10)(2, 9, 6)(7, 8, 11), Perm(0, 10, 7)(1, 5, 6)(2, 4, 11)(3, 9, 8), Perm(0, 6, 8)(1, 7, 2)(3, 5, 11)(4, 10, 9), Perm(0, 7, 9)(1, 11, 4)(2, 8, 3)(5, 6, 10), Perm(0, 8, 10)(1, 7, 6)(2, 11, 5)(3, 9, 4), Perm(0, 9, 6)(1, 3, 11)(2, 8, 7)(4, 10, 5))) tetrahedron_faces = list(tuple(arg) for arg in tetrahedron.faces) cube_faces = list(tuple(arg) for arg in cube.faces) octahedron_faces = list(tuple(arg) for arg in octahedron.faces) dodecahedron_faces = list(tuple(arg) for arg in dodecahedron.faces) icosahedron_faces = list(tuple(arg) for arg in icosahedron.faces)
51d56c9c44aea26b222073bb875b8b63b4d922b50ccb69b553894e6bddb7eaeb
import itertools from sympy.combinatorics.fp_groups import FpGroup, FpSubgroup, simplify_presentation from sympy.combinatorics.free_groups import FreeGroup from sympy.combinatorics.perm_groups import PermutationGroup from sympy.core.numbers import igcd from sympy.ntheory.factor_ import totient from sympy import S class GroupHomomorphism: ''' A class representing group homomorphisms. Instantiate using `homomorphism()`. References ========== .. [1] Holt, D., Eick, B. and O'Brien, E. (2005). Handbook of computational group theory. ''' def __init__(self, domain, codomain, images): self.domain = domain self.codomain = codomain self.images = images self._inverses = None self._kernel = None self._image = None def _invs(self): ''' Return a dictionary with `{gen: inverse}` where `gen` is a rewriting generator of `codomain` (e.g. strong generator for permutation groups) and `inverse` is an element of its preimage ''' image = self.image() inverses = {} for k in list(self.images.keys()): v = self.images[k] if not (v in inverses or v.is_identity): inverses[v] = k if isinstance(self.codomain, PermutationGroup): gens = image.strong_gens else: gens = image.generators for g in gens: if g in inverses or g.is_identity: continue w = self.domain.identity if isinstance(self.codomain, PermutationGroup): parts = image._strong_gens_slp[g][::-1] else: parts = g for s in parts: if s in inverses: w = w*inverses[s] else: w = w*inverses[s**-1]**-1 inverses[g] = w return inverses def invert(self, g): ''' Return an element of the preimage of ``g`` or of each element of ``g`` if ``g`` is a list. Explanation =========== If the codomain is an FpGroup, the inverse for equal elements might not always be the same unless the FpGroup's rewriting system is confluent. However, making a system confluent can be time-consuming. If it's important, try `self.codomain.make_confluent()` first. ''' from sympy.combinatorics import Permutation from sympy.combinatorics.free_groups import FreeGroupElement if isinstance(g, (Permutation, FreeGroupElement)): if isinstance(self.codomain, FpGroup): g = self.codomain.reduce(g) if self._inverses is None: self._inverses = self._invs() image = self.image() w = self.domain.identity if isinstance(self.codomain, PermutationGroup): gens = image.generator_product(g)[::-1] else: gens = g # the following can't be "for s in gens:" # because that would be equivalent to # "for s in gens.array_form:" when g is # a FreeGroupElement. On the other hand, # when you call gens by index, the generator # (or inverse) at position i is returned. for i in range(len(gens)): s = gens[i] if s.is_identity: continue if s in self._inverses: w = w*self._inverses[s] else: w = w*self._inverses[s**-1]**-1 return w elif isinstance(g, list): return [self.invert(e) for e in g] def kernel(self): ''' Compute the kernel of `self`. ''' if self._kernel is None: self._kernel = self._compute_kernel() return self._kernel def _compute_kernel(self): from sympy import S G = self.domain G_order = G.order() if G_order is S.Infinity: raise NotImplementedError( "Kernel computation is not implemented for infinite groups") gens = [] if isinstance(G, PermutationGroup): K = PermutationGroup(G.identity) else: K = FpSubgroup(G, gens, normal=True) i = self.image().order() while K.order()*i != G_order: r = G.random() k = r*self.invert(self(r))**-1 if not k in K: gens.append(k) if isinstance(G, PermutationGroup): K = PermutationGroup(gens) else: K = FpSubgroup(G, gens, normal=True) return K def image(self): ''' Compute the image of `self`. ''' if self._image is None: values = list(set(self.images.values())) if isinstance(self.codomain, PermutationGroup): self._image = self.codomain.subgroup(values) else: self._image = FpSubgroup(self.codomain, values) return self._image def _apply(self, elem): ''' Apply `self` to `elem`. ''' if not elem in self.domain: if isinstance(elem, (list, tuple)): return [self._apply(e) for e in elem] raise ValueError("The supplied element doesn't belong to the domain") if elem.is_identity: return self.codomain.identity else: images = self.images value = self.codomain.identity if isinstance(self.domain, PermutationGroup): gens = self.domain.generator_product(elem, original=True) for g in gens: if g in self.images: value = images[g]*value else: value = images[g**-1]**-1*value else: i = 0 for _, p in elem.array_form: if p < 0: g = elem[i]**-1 else: g = elem[i] value = value*images[g]**p i += abs(p) return value def __call__(self, elem): return self._apply(elem) def is_injective(self): ''' Check if the homomorphism is injective ''' return self.kernel().order() == 1 def is_surjective(self): ''' Check if the homomorphism is surjective ''' from sympy import S im = self.image().order() oth = self.codomain.order() if im is S.Infinity and oth is S.Infinity: return None else: return im == oth def is_isomorphism(self): ''' Check if `self` is an isomorphism. ''' return self.is_injective() and self.is_surjective() def is_trivial(self): ''' Check is `self` is a trivial homomorphism, i.e. all elements are mapped to the identity. ''' return self.image().order() == 1 def compose(self, other): ''' Return the composition of `self` and `other`, i.e. the homomorphism phi such that for all g in the domain of `other`, phi(g) = self(other(g)) ''' if not other.image().is_subgroup(self.domain): raise ValueError("The image of `other` must be a subgroup of " "the domain of `self`") images = {g: self(other(g)) for g in other.images} return GroupHomomorphism(other.domain, self.codomain, images) def restrict_to(self, H): ''' Return the restriction of the homomorphism to the subgroup `H` of the domain. ''' if not isinstance(H, PermutationGroup) or not H.is_subgroup(self.domain): raise ValueError("Given H is not a subgroup of the domain") domain = H images = {g: self(g) for g in H.generators} return GroupHomomorphism(domain, self.codomain, images) def invert_subgroup(self, H): ''' Return the subgroup of the domain that is the inverse image of the subgroup ``H`` of the homomorphism image ''' if not H.is_subgroup(self.image()): raise ValueError("Given H is not a subgroup of the image") gens = [] P = PermutationGroup(self.image().identity) for h in H.generators: h_i = self.invert(h) if h_i not in P: gens.append(h_i) P = PermutationGroup(gens) for k in self.kernel().generators: if k*h_i not in P: gens.append(k*h_i) P = PermutationGroup(gens) return P def homomorphism(domain, codomain, gens, images=(), check=True): ''' Create (if possible) a group homomorphism from the group ``domain`` to the group ``codomain`` defined by the images of the domain's generators ``gens``. ``gens`` and ``images`` can be either lists or tuples of equal sizes. If ``gens`` is a proper subset of the group's generators, the unspecified generators will be mapped to the identity. If the images are not specified, a trivial homomorphism will be created. If the given images of the generators do not define a homomorphism, an exception is raised. If ``check`` is ``False``, don't check whether the given images actually define a homomorphism. ''' if not isinstance(domain, (PermutationGroup, FpGroup, FreeGroup)): raise TypeError("The domain must be a group") if not isinstance(codomain, (PermutationGroup, FpGroup, FreeGroup)): raise TypeError("The codomain must be a group") generators = domain.generators if not all(g in generators for g in gens): raise ValueError("The supplied generators must be a subset of the domain's generators") if not all(g in codomain for g in images): raise ValueError("The images must be elements of the codomain") if images and len(images) != len(gens): raise ValueError("The number of images must be equal to the number of generators") gens = list(gens) images = list(images) images.extend([codomain.identity]*(len(generators)-len(images))) gens.extend([g for g in generators if g not in gens]) images = dict(zip(gens,images)) if check and not _check_homomorphism(domain, codomain, images): raise ValueError("The given images do not define a homomorphism") return GroupHomomorphism(domain, codomain, images) def _check_homomorphism(domain, codomain, images): if hasattr(domain, 'relators'): rels = domain.relators else: gens = domain.presentation().generators rels = domain.presentation().relators identity = codomain.identity def _image(r): if r.is_identity: return identity else: w = identity r_arr = r.array_form i = 0 j = 0 # i is the index for r and j is for # r_arr. r_arr[j] is the tuple (sym, p) # where sym is the generator symbol # and p is the power to which it is # raised while r[i] is a generator # (not just its symbol) or the inverse of # a generator - hence the need for # both indices while i < len(r): power = r_arr[j][1] if isinstance(domain, PermutationGroup) and r[i] in gens: s = domain.generators[gens.index(r[i])] else: s = r[i] if s in images: w = w*images[s]**power elif s**-1 in images: w = w*images[s**-1]**power i += abs(power) j += 1 return w for r in rels: if isinstance(codomain, FpGroup): s = codomain.equals(_image(r), identity) if s is None: # only try to make the rewriting system # confluent when it can't determine the # truth of equality otherwise success = codomain.make_confluent() s = codomain.equals(_image(r), identity) if s is None and not success: raise RuntimeError("Can't determine if the images " "define a homomorphism. Try increasing " "the maximum number of rewriting rules " "(group._rewriting_system.set_max(new_value); " "the current value is stored in group._rewriting" "_system.maxeqns)") else: s = _image(r).is_identity if not s: return False return True def orbit_homomorphism(group, omega): ''' Return the homomorphism induced by the action of the permutation group ``group`` on the set ``omega`` that is closed under the action. ''' from sympy.combinatorics import Permutation from sympy.combinatorics.named_groups import SymmetricGroup codomain = SymmetricGroup(len(omega)) identity = codomain.identity omega = list(omega) images = {g: identity*Permutation([omega.index(o^g) for o in omega]) for g in group.generators} group._schreier_sims(base=omega) H = GroupHomomorphism(group, codomain, images) if len(group.basic_stabilizers) > len(omega): H._kernel = group.basic_stabilizers[len(omega)] else: H._kernel = PermutationGroup([group.identity]) return H def block_homomorphism(group, blocks): ''' Return the homomorphism induced by the action of the permutation group ``group`` on the block system ``blocks``. The latter should be of the same form as returned by the ``minimal_block`` method for permutation groups, namely a list of length ``group.degree`` where the i-th entry is a representative of the block i belongs to. ''' from sympy.combinatorics import Permutation from sympy.combinatorics.named_groups import SymmetricGroup n = len(blocks) # number the blocks; m is the total number, # b is such that b[i] is the number of the block i belongs to, # p is the list of length m such that p[i] is the representative # of the i-th block m = 0 p = [] b = [None]*n for i in range(n): if blocks[i] == i: p.append(i) b[i] = m m += 1 for i in range(n): b[i] = b[blocks[i]] codomain = SymmetricGroup(m) # the list corresponding to the identity permutation in codomain identity = range(m) images = {g: Permutation([b[p[i]^g] for i in identity]) for g in group.generators} H = GroupHomomorphism(group, codomain, images) return H def group_isomorphism(G, H, isomorphism=True): ''' Compute an isomorphism between 2 given groups. Parameters ========== G : A finite ``FpGroup`` or a ``PermutationGroup``. First group. H : A finite ``FpGroup`` or a ``PermutationGroup`` Second group. isomorphism : bool This is used to avoid the computation of homomorphism when the user only wants to check if there exists an isomorphism between the groups. Returns ======= If isomorphism = False -- Returns a boolean. If isomorphism = True -- Returns a boolean and an isomorphism between `G` and `H`. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup >>> from sympy.combinatorics.homomorphisms import group_isomorphism >>> from sympy.combinatorics.named_groups import DihedralGroup, AlternatingGroup >>> D = DihedralGroup(8) >>> p = Permutation(0, 1, 2, 3, 4, 5, 6, 7) >>> P = PermutationGroup(p) >>> group_isomorphism(D, P) (False, None) >>> F, a, b = free_group("a, b") >>> G = FpGroup(F, [a**3, b**3, (a*b)**2]) >>> H = AlternatingGroup(4) >>> (check, T) = group_isomorphism(G, H) >>> check True >>> T(b*a*b**-1*a**-1*b**-1) (0 2 3) Notes ===== Uses the approach suggested by Robert Tarjan to compute the isomorphism between two groups. First, the generators of ``G`` are mapped to the elements of ``H`` and we check if the mapping induces an isomorphism. ''' if not isinstance(G, (PermutationGroup, FpGroup)): raise TypeError("The group must be a PermutationGroup or an FpGroup") if not isinstance(H, (PermutationGroup, FpGroup)): raise TypeError("The group must be a PermutationGroup or an FpGroup") if isinstance(G, FpGroup) and isinstance(H, FpGroup): G = simplify_presentation(G) H = simplify_presentation(H) # Two infinite FpGroups with the same generators are isomorphic # when the relators are same but are ordered differently. if G.generators == H.generators and (G.relators).sort() == (H.relators).sort(): if not isomorphism: return True return (True, homomorphism(G, H, G.generators, H.generators)) # `_H` is the permutation group isomorphic to `H`. _H = H g_order = G.order() h_order = H.order() if g_order is S.Infinity: raise NotImplementedError("Isomorphism methods are not implemented for infinite groups.") if isinstance(H, FpGroup): if h_order is S.Infinity: raise NotImplementedError("Isomorphism methods are not implemented for infinite groups.") _H, h_isomorphism = H._to_perm_group() if (g_order != h_order) or (G.is_abelian != H.is_abelian): if not isomorphism: return False return (False, None) if not isomorphism: # Two groups of the same cyclic numbered order # are isomorphic to each other. n = g_order if (igcd(n, totient(n))) == 1: return True # Match the generators of `G` with subsets of `_H` gens = list(G.generators) for subset in itertools.permutations(_H, len(gens)): images = list(subset) images.extend([_H.identity]*(len(G.generators)-len(images))) _images = dict(zip(gens,images)) if _check_homomorphism(G, _H, _images): if isinstance(H, FpGroup): images = h_isomorphism.invert(images) T = homomorphism(G, H, G.generators, images, check=False) if T.is_isomorphism(): # It is a valid isomorphism if not isomorphism: return True return (True, T) if not isomorphism: return False return (False, None) def is_isomorphic(G, H): ''' Check if the groups are isomorphic to each other Parameters ========== G : A finite ``FpGroup`` or a ``PermutationGroup`` First group. H : A finite ``FpGroup`` or a ``PermutationGroup`` Second group. Returns ======= boolean ''' return group_isomorphism(G, H, isomorphism=False)
0ae4d1af01592d647e88bc2d8a04bfe985cbaecfc8d7811bfad925e097d2f26d
from sympy.core import Basic, Dict, sympify from sympy.core.compatibility import as_int, default_sort_key from sympy.core.sympify import _sympify from sympy.functions.combinatorial.numbers import bell from sympy.matrices import zeros from sympy.sets.sets import FiniteSet, Union from sympy.utilities.iterables import flatten, group from collections import defaultdict class Partition(FiniteSet): """ This class represents an abstract partition. A partition is a set of disjoint sets whose union equals a given set. See Also ======== sympy.utilities.iterables.partitions, sympy.utilities.iterables.multiset_partitions """ _rank = None _partition = None def __new__(cls, *partition): """ Generates a new partition object. This method also verifies if the arguments passed are valid and raises a ValueError if they are not. Examples ======== Creating Partition from Python lists: >>> from sympy.combinatorics.partitions import Partition >>> a = Partition([1, 2], [3]) >>> a Partition({3}, {1, 2}) >>> a.partition [[1, 2], [3]] >>> len(a) 2 >>> a.members (1, 2, 3) Creating Partition from Python sets: >>> Partition({1, 2, 3}, {4, 5}) Partition({4, 5}, {1, 2, 3}) Creating Partition from SymPy finite sets: >>> from sympy.sets.sets import FiniteSet >>> a = FiniteSet(1, 2, 3) >>> b = FiniteSet(4, 5) >>> Partition(a, b) Partition({4, 5}, {1, 2, 3}) """ args = [] dups = False for arg in partition: if isinstance(arg, list): as_set = set(arg) if len(as_set) < len(arg): dups = True break # error below arg = as_set args.append(_sympify(arg)) if not all(isinstance(part, FiniteSet) for part in args): raise ValueError( "Each argument to Partition should be " \ "a list, set, or a FiniteSet") # sort so we have a canonical reference for RGS U = Union(*args) if dups or len(U) < sum(len(arg) for arg in args): raise ValueError("Partition contained duplicate elements.") obj = FiniteSet.__new__(cls, *args) obj.members = tuple(U) obj.size = len(U) return obj def sort_key(self, order=None): """Return a canonical key that can be used for sorting. Ordering is based on the size and sorted elements of the partition and ties are broken with the rank. Examples ======== >>> from sympy.utilities.iterables import default_sort_key >>> from sympy.combinatorics.partitions import Partition >>> from sympy.abc import x >>> a = Partition([1, 2]) >>> b = Partition([3, 4]) >>> c = Partition([1, x]) >>> d = Partition(list(range(4))) >>> l = [d, b, a + 1, a, c] >>> l.sort(key=default_sort_key); l [Partition({1, 2}), Partition({1}, {2}), Partition({1, x}), Partition({3, 4}), Partition({0, 1, 2, 3})] """ if order is None: members = self.members else: members = tuple(sorted(self.members, key=lambda w: default_sort_key(w, order))) return tuple(map(default_sort_key, (self.size, members, self.rank))) @property def partition(self): """Return partition as a sorted list of lists. Examples ======== >>> from sympy.combinatorics.partitions import Partition >>> Partition([1], [2, 3]).partition [[1], [2, 3]] """ if self._partition is None: self._partition = sorted([sorted(p, key=default_sort_key) for p in self.args]) return self._partition def __add__(self, other): """ Return permutation whose rank is ``other`` greater than current rank, (mod the maximum rank for the set). Examples ======== >>> from sympy.combinatorics.partitions import Partition >>> a = Partition([1, 2], [3]) >>> a.rank 1 >>> (a + 1).rank 2 >>> (a + 100).rank 1 """ other = as_int(other) offset = self.rank + other result = RGS_unrank((offset) % RGS_enum(self.size), self.size) return Partition.from_rgs(result, self.members) def __sub__(self, other): """ Return permutation whose rank is ``other`` less than current rank, (mod the maximum rank for the set). Examples ======== >>> from sympy.combinatorics.partitions import Partition >>> a = Partition([1, 2], [3]) >>> a.rank 1 >>> (a - 1).rank 0 >>> (a - 100).rank 1 """ return self.__add__(-other) def __le__(self, other): """ Checks if a partition is less than or equal to the other based on rank. Examples ======== >>> from sympy.combinatorics.partitions import Partition >>> a = Partition([1, 2], [3, 4, 5]) >>> b = Partition([1], [2, 3], [4], [5]) >>> a.rank, b.rank (9, 34) >>> a <= a True >>> a <= b True """ return self.sort_key() <= sympify(other).sort_key() def __lt__(self, other): """ Checks if a partition is less than the other. Examples ======== >>> from sympy.combinatorics.partitions import Partition >>> a = Partition([1, 2], [3, 4, 5]) >>> b = Partition([1], [2, 3], [4], [5]) >>> a.rank, b.rank (9, 34) >>> a < b True """ return self.sort_key() < sympify(other).sort_key() @property def rank(self): """ Gets the rank of a partition. Examples ======== >>> from sympy.combinatorics.partitions import Partition >>> a = Partition([1, 2], [3], [4, 5]) >>> a.rank 13 """ if self._rank is not None: return self._rank self._rank = RGS_rank(self.RGS) return self._rank @property def RGS(self): """ Returns the "restricted growth string" of the partition. Explanation =========== The RGS is returned as a list of indices, L, where L[i] indicates the block in which element i appears. For example, in a partition of 3 elements (a, b, c) into 2 blocks ([c], [a, b]) the RGS is [1, 1, 0]: "a" is in block 1, "b" is in block 1 and "c" is in block 0. Examples ======== >>> from sympy.combinatorics.partitions import Partition >>> a = Partition([1, 2], [3], [4, 5]) >>> a.members (1, 2, 3, 4, 5) >>> a.RGS (0, 0, 1, 2, 2) >>> a + 1 Partition({3}, {4}, {5}, {1, 2}) >>> _.RGS (0, 0, 1, 2, 3) """ rgs = {} partition = self.partition for i, part in enumerate(partition): for j in part: rgs[j] = i return tuple([rgs[i] for i in sorted( [i for p in partition for i in p], key=default_sort_key)]) @classmethod def from_rgs(self, rgs, elements): """ Creates a set partition from a restricted growth string. Explanation =========== The indices given in rgs are assumed to be the index of the element as given in elements *as provided* (the elements are not sorted by this routine). Block numbering starts from 0. If any block was not referenced in ``rgs`` an error will be raised. Examples ======== >>> from sympy.combinatorics.partitions import Partition >>> Partition.from_rgs([0, 1, 2, 0, 1], list('abcde')) Partition({c}, {a, d}, {b, e}) >>> Partition.from_rgs([0, 1, 2, 0, 1], list('cbead')) Partition({e}, {a, c}, {b, d}) >>> a = Partition([1, 4], [2], [3, 5]) >>> Partition.from_rgs(a.RGS, a.members) Partition({2}, {1, 4}, {3, 5}) """ if len(rgs) != len(elements): raise ValueError('mismatch in rgs and element lengths') max_elem = max(rgs) + 1 partition = [[] for i in range(max_elem)] j = 0 for i in rgs: partition[i].append(elements[j]) j += 1 if not all(p for p in partition): raise ValueError('some blocks of the partition were empty.') return Partition(*partition) class IntegerPartition(Basic): """ This class represents an integer partition. Explanation =========== In number theory and combinatorics, a partition of a positive integer, ``n``, also called an integer partition, is a way of writing ``n`` as a list of positive integers that sum to n. Two partitions that differ only in the order of summands are considered to be the same partition; if order matters then the partitions are referred to as compositions. For example, 4 has five partitions: [4], [3, 1], [2, 2], [2, 1, 1], and [1, 1, 1, 1]; the compositions [1, 2, 1] and [1, 1, 2] are the same as partition [2, 1, 1]. See Also ======== sympy.utilities.iterables.partitions, sympy.utilities.iterables.multiset_partitions References ========== https://en.wikipedia.org/wiki/Partition_%28number_theory%29 """ _dict = None _keys = None def __new__(cls, partition, integer=None): """ Generates a new IntegerPartition object from a list or dictionary. Explantion ========== The partition can be given as a list of positive integers or a dictionary of (integer, multiplicity) items. If the partition is preceded by an integer an error will be raised if the partition does not sum to that given integer. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> a = IntegerPartition([5, 4, 3, 1, 1]) >>> a IntegerPartition(14, (5, 4, 3, 1, 1)) >>> print(a) [5, 4, 3, 1, 1] >>> IntegerPartition({1:3, 2:1}) IntegerPartition(5, (2, 1, 1, 1)) If the value that the partition should sum to is given first, a check will be made to see n error will be raised if there is a discrepancy: >>> IntegerPartition(10, [5, 4, 3, 1]) Traceback (most recent call last): ... ValueError: The partition is not valid """ if integer is not None: integer, partition = partition, integer if isinstance(partition, (dict, Dict)): _ = [] for k, v in sorted(list(partition.items()), reverse=True): if not v: continue k, v = as_int(k), as_int(v) _.extend([k]*v) partition = tuple(_) else: partition = tuple(sorted(map(as_int, partition), reverse=True)) sum_ok = False if integer is None: integer = sum(partition) sum_ok = True else: integer = as_int(integer) if not sum_ok and sum(partition) != integer: raise ValueError("Partition did not add to %s" % integer) if any(i < 1 for i in partition): raise ValueError("All integer summands must be greater than one") obj = Basic.__new__(cls, integer, partition) obj.partition = list(partition) obj.integer = integer return obj def prev_lex(self): """Return the previous partition of the integer, n, in lexical order, wrapping around to [1, ..., 1] if the partition is [n]. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> p = IntegerPartition([4]) >>> print(p.prev_lex()) [3, 1] >>> p.partition > p.prev_lex().partition True """ d = defaultdict(int) d.update(self.as_dict()) keys = self._keys if keys == [1]: return IntegerPartition({self.integer: 1}) if keys[-1] != 1: d[keys[-1]] -= 1 if keys[-1] == 2: d[1] = 2 else: d[keys[-1] - 1] = d[1] = 1 else: d[keys[-2]] -= 1 left = d[1] + keys[-2] new = keys[-2] d[1] = 0 while left: new -= 1 if left - new >= 0: d[new] += left//new left -= d[new]*new return IntegerPartition(self.integer, d) def next_lex(self): """Return the next partition of the integer, n, in lexical order, wrapping around to [n] if the partition is [1, ..., 1]. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> p = IntegerPartition([3, 1]) >>> print(p.next_lex()) [4] >>> p.partition < p.next_lex().partition True """ d = defaultdict(int) d.update(self.as_dict()) key = self._keys a = key[-1] if a == self.integer: d.clear() d[1] = self.integer elif a == 1: if d[a] > 1: d[a + 1] += 1 d[a] -= 2 else: b = key[-2] d[b + 1] += 1 d[1] = (d[b] - 1)*b d[b] = 0 else: if d[a] > 1: if len(key) == 1: d.clear() d[a + 1] = 1 d[1] = self.integer - a - 1 else: a1 = a + 1 d[a1] += 1 d[1] = d[a]*a - a1 d[a] = 0 else: b = key[-2] b1 = b + 1 d[b1] += 1 need = d[b]*b + d[a]*a - b1 d[a] = d[b] = 0 d[1] = need return IntegerPartition(self.integer, d) def as_dict(self): """Return the partition as a dictionary whose keys are the partition integers and the values are the multiplicity of that integer. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> IntegerPartition([1]*3 + [2] + [3]*4).as_dict() {1: 3, 2: 1, 3: 4} """ if self._dict is None: groups = group(self.partition, multiple=False) self._keys = [g[0] for g in groups] self._dict = dict(groups) return self._dict @property def conjugate(self): """ Computes the conjugate partition of itself. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> a = IntegerPartition([6, 3, 3, 2, 1]) >>> a.conjugate [5, 4, 3, 1, 1, 1] """ j = 1 temp_arr = list(self.partition) + [0] k = temp_arr[0] b = [0]*k while k > 0: while k > temp_arr[j]: b[k - 1] = j k -= 1 j += 1 return b def __lt__(self, other): """Return True if self is less than other when the partition is listed from smallest to biggest. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> a = IntegerPartition([3, 1]) >>> a < a False >>> b = a.next_lex() >>> a < b True >>> a == b False """ return list(reversed(self.partition)) < list(reversed(other.partition)) def __le__(self, other): """Return True if self is less than other when the partition is listed from smallest to biggest. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> a = IntegerPartition([4]) >>> a <= a True """ return list(reversed(self.partition)) <= list(reversed(other.partition)) def as_ferrers(self, char='#'): """ Prints the ferrer diagram of a partition. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> print(IntegerPartition([1, 1, 5]).as_ferrers()) ##### # # """ return "\n".join([char*i for i in self.partition]) def __str__(self): return str(list(self.partition)) def random_integer_partition(n, seed=None): """ Generates a random integer partition summing to ``n`` as a list of reverse-sorted integers. Examples ======== >>> from sympy.combinatorics.partitions import random_integer_partition For the following, a seed is given so a known value can be shown; in practice, the seed would not be given. >>> random_integer_partition(100, seed=[1, 1, 12, 1, 2, 1, 85, 1]) [85, 12, 2, 1] >>> random_integer_partition(10, seed=[1, 2, 3, 1, 5, 1]) [5, 3, 1, 1] >>> random_integer_partition(1) [1] """ from sympy.testing.randtest import _randint n = as_int(n) if n < 1: raise ValueError('n must be a positive integer') randint = _randint(seed) partition = [] while (n > 0): k = randint(1, n) mult = randint(1, n//k) partition.append((k, mult)) n -= k*mult partition.sort(reverse=True) partition = flatten([[k]*m for k, m in partition]) return partition def RGS_generalized(m): """ Computes the m + 1 generalized unrestricted growth strings and returns them as rows in matrix. Examples ======== >>> from sympy.combinatorics.partitions import RGS_generalized >>> RGS_generalized(6) Matrix([ [ 1, 1, 1, 1, 1, 1, 1], [ 1, 2, 3, 4, 5, 6, 0], [ 2, 5, 10, 17, 26, 0, 0], [ 5, 15, 37, 77, 0, 0, 0], [ 15, 52, 151, 0, 0, 0, 0], [ 52, 203, 0, 0, 0, 0, 0], [203, 0, 0, 0, 0, 0, 0]]) """ d = zeros(m + 1) for i in range(0, m + 1): d[0, i] = 1 for i in range(1, m + 1): for j in range(m): if j <= m - i: d[i, j] = j * d[i - 1, j] + d[i - 1, j + 1] else: d[i, j] = 0 return d def RGS_enum(m): """ RGS_enum computes the total number of restricted growth strings possible for a superset of size m. Examples ======== >>> from sympy.combinatorics.partitions import RGS_enum >>> from sympy.combinatorics.partitions import Partition >>> RGS_enum(4) 15 >>> RGS_enum(5) 52 >>> RGS_enum(6) 203 We can check that the enumeration is correct by actually generating the partitions. Here, the 15 partitions of 4 items are generated: >>> a = Partition(list(range(4))) >>> s = set() >>> for i in range(20): ... s.add(a) ... a += 1 ... >>> assert len(s) == 15 """ if (m < 1): return 0 elif (m == 1): return 1 else: return bell(m) def RGS_unrank(rank, m): """ Gives the unranked restricted growth string for a given superset size. Examples ======== >>> from sympy.combinatorics.partitions import RGS_unrank >>> RGS_unrank(14, 4) [0, 1, 2, 3] >>> RGS_unrank(0, 4) [0, 0, 0, 0] """ if m < 1: raise ValueError("The superset size must be >= 1") if rank < 0 or RGS_enum(m) <= rank: raise ValueError("Invalid arguments") L = [1] * (m + 1) j = 1 D = RGS_generalized(m) for i in range(2, m + 1): v = D[m - i, j] cr = j*v if cr <= rank: L[i] = j + 1 rank -= cr j += 1 else: L[i] = int(rank / v + 1) rank %= v return [x - 1 for x in L[1:]] def RGS_rank(rgs): """ Computes the rank of a restricted growth string. Examples ======== >>> from sympy.combinatorics.partitions import RGS_rank, RGS_unrank >>> RGS_rank([0, 1, 2, 1, 3]) 42 >>> RGS_rank(RGS_unrank(4, 7)) 4 """ rgs_size = len(rgs) rank = 0 D = RGS_generalized(rgs_size) for i in range(1, rgs_size): n = len(rgs[(i + 1):]) m = max(rgs[0:i]) rank += D[n, m + 1] * rgs[i] return rank
1a89e810e6a5a530516a767db1cc79dd6094c0728ae2dfef90112512781cb0ce
"""Finitely Presented Groups and its algorithms. """ from sympy import S from sympy.combinatorics.free_groups import (FreeGroup, FreeGroupElement, free_group) from sympy.combinatorics.rewritingsystem import RewritingSystem from sympy.combinatorics.coset_table import (CosetTable, coset_enumeration_r, coset_enumeration_c) from sympy.combinatorics import PermutationGroup from sympy.printing.defaults import DefaultPrinting from sympy.utilities import public from sympy.utilities.magic import pollute from sympy import symbols from itertools import product @public def fp_group(fr_grp, relators=()): _fp_group = FpGroup(fr_grp, relators) return (_fp_group,) + tuple(_fp_group._generators) @public def xfp_group(fr_grp, relators=()): _fp_group = FpGroup(fr_grp, relators) return (_fp_group, _fp_group._generators) # Does not work. Both symbols and pollute are undefined. Never tested. @public def vfp_group(fr_grpm, relators): _fp_group = FpGroup(symbols, relators) pollute([sym.name for sym in _fp_group.symbols], _fp_group.generators) return _fp_group def _parse_relators(rels): """Parse the passed relators.""" return rels ############################################################################### # FINITELY PRESENTED GROUPS # ############################################################################### class FpGroup(DefaultPrinting): """ The FpGroup would take a FreeGroup and a list/tuple of relators, the relators would be specified in such a way that each of them be equal to the identity of the provided free group. """ is_group = True is_FpGroup = True is_PermutationGroup = False def __init__(self, fr_grp, relators): relators = _parse_relators(relators) self.free_group = fr_grp self.relators = relators self.generators = self._generators() self.dtype = type("FpGroupElement", (FpGroupElement,), {"group": self}) # CosetTable instance on identity subgroup self._coset_table = None # returns whether coset table on identity subgroup # has been standardized self._is_standardized = False self._order = None self._center = None self._rewriting_system = RewritingSystem(self) self._perm_isomorphism = None return def _generators(self): return self.free_group.generators def make_confluent(self): ''' Try to make the group's rewriting system confluent ''' self._rewriting_system.make_confluent() return def reduce(self, word): ''' Return the reduced form of `word` in `self` according to the group's rewriting system. If it's confluent, the reduced form is the unique normal form of the word in the group. ''' return self._rewriting_system.reduce(word) def equals(self, word1, word2): ''' Compare `word1` and `word2` for equality in the group using the group's rewriting system. If the system is confluent, the returned answer is necessarily correct. (If it isn't, `False` could be returned in some cases where in fact `word1 == word2`) ''' if self.reduce(word1*word2**-1) == self.identity: return True elif self._rewriting_system.is_confluent: return False return None @property def identity(self): return self.free_group.identity def __contains__(self, g): return g in self.free_group def subgroup(self, gens, C=None, homomorphism=False): ''' Return the subgroup generated by `gens` using the Reidemeister-Schreier algorithm homomorphism -- When set to True, return a dictionary containing the images of the presentation generators in the original group. Examples ======== >>> from sympy.combinatorics.fp_groups import FpGroup >>> from sympy.combinatorics.free_groups import free_group >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**5, (x*y)**2]) >>> H = [x*y, x**-1*y**-1*x*y*x] >>> K, T = f.subgroup(H, homomorphism=True) >>> T(K.generators) [x*y, x**-1*y**2*x**-1] ''' if not all(isinstance(g, FreeGroupElement) for g in gens): raise ValueError("Generators must be `FreeGroupElement`s") if not all(g.group == self.free_group for g in gens): raise ValueError("Given generators are not members of the group") if homomorphism: g, rels, _gens = reidemeister_presentation(self, gens, C=C, homomorphism=True) else: g, rels = reidemeister_presentation(self, gens, C=C) if g: g = FpGroup(g[0].group, rels) else: g = FpGroup(free_group('')[0], []) if homomorphism: from sympy.combinatorics.homomorphisms import homomorphism return g, homomorphism(g, self, g.generators, _gens, check=False) return g def coset_enumeration(self, H, strategy="relator_based", max_cosets=None, draft=None, incomplete=False): """ Return an instance of ``coset table``, when Todd-Coxeter algorithm is run over the ``self`` with ``H`` as subgroup, using ``strategy`` argument as strategy. The returned coset table is compressed but not standardized. An instance of `CosetTable` for `fp_grp` can be passed as the keyword argument `draft` in which case the coset enumeration will start with that instance and attempt to complete it. When `incomplete` is `True` and the function is unable to complete for some reason, the partially complete table will be returned. """ if not max_cosets: max_cosets = CosetTable.coset_table_max_limit if strategy == 'relator_based': C = coset_enumeration_r(self, H, max_cosets=max_cosets, draft=draft, incomplete=incomplete) else: C = coset_enumeration_c(self, H, max_cosets=max_cosets, draft=draft, incomplete=incomplete) if C.is_complete(): C.compress() return C def standardize_coset_table(self): """ Standardized the coset table ``self`` and makes the internal variable ``_is_standardized`` equal to ``True``. """ self._coset_table.standardize() self._is_standardized = True def coset_table(self, H, strategy="relator_based", max_cosets=None, draft=None, incomplete=False): """ Return the mathematical coset table of ``self`` in ``H``. """ if not H: if self._coset_table is not None: if not self._is_standardized: self.standardize_coset_table() else: C = self.coset_enumeration([], strategy, max_cosets=max_cosets, draft=draft, incomplete=incomplete) self._coset_table = C self.standardize_coset_table() return self._coset_table.table else: C = self.coset_enumeration(H, strategy, max_cosets=max_cosets, draft=draft, incomplete=incomplete) C.standardize() return C.table def order(self, strategy="relator_based"): """ Returns the order of the finitely presented group ``self``. It uses the coset enumeration with identity group as subgroup, i.e ``H=[]``. Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x, y**2]) >>> f.order(strategy="coset_table_based") 2 """ from sympy import S, gcd if self._order is not None: return self._order if self._coset_table is not None: self._order = len(self._coset_table.table) elif len(self.relators) == 0: self._order = self.free_group.order() elif len(self.generators) == 1: self._order = abs(gcd([r.array_form[0][1] for r in self.relators])) elif self._is_infinite(): self._order = S.Infinity else: gens, C = self._finite_index_subgroup() if C: ind = len(C.table) self._order = ind*self.subgroup(gens, C=C).order() else: self._order = self.index([]) return self._order def _is_infinite(self): ''' Test if the group is infinite. Return `True` if the test succeeds and `None` otherwise ''' used_gens = set() for r in self.relators: used_gens.update(r.contains_generators()) if not set(self.generators) <= used_gens: return True # Abelianisation test: check is the abelianisation is infinite abelian_rels = [] from sympy.matrices.normalforms import invariant_factors from sympy.matrices import Matrix for rel in self.relators: abelian_rels.append([rel.exponent_sum(g) for g in self.generators]) m = Matrix(Matrix(abelian_rels)) if 0 in invariant_factors(m): return True else: return None def _finite_index_subgroup(self, s=None): ''' Find the elements of `self` that generate a finite index subgroup and, if found, return the list of elements and the coset table of `self` by the subgroup, otherwise return `(None, None)` ''' gen = self.most_frequent_generator() rels = list(self.generators) rels.extend(self.relators) if not s: if len(self.generators) == 2: s = [gen] + [g for g in self.generators if g != gen] else: rand = self.free_group.identity i = 0 while ((rand in rels or rand**-1 in rels or rand.is_identity) and i<10): rand = self.random() i += 1 s = [gen, rand] + [g for g in self.generators if g != gen] mid = (len(s)+1)//2 half1 = s[:mid] half2 = s[mid:] draft1 = None draft2 = None m = 200 C = None while not C and (m/2 < CosetTable.coset_table_max_limit): m = min(m, CosetTable.coset_table_max_limit) draft1 = self.coset_enumeration(half1, max_cosets=m, draft=draft1, incomplete=True) if draft1.is_complete(): C = draft1 half = half1 else: draft2 = self.coset_enumeration(half2, max_cosets=m, draft=draft2, incomplete=True) if draft2.is_complete(): C = draft2 half = half2 if not C: m *= 2 if not C: return None, None C.compress() return half, C def most_frequent_generator(self): gens = self.generators rels = self.relators freqs = [sum([r.generator_count(g) for r in rels]) for g in gens] return gens[freqs.index(max(freqs))] def random(self): import random r = self.free_group.identity for i in range(random.randint(2,3)): r = r*random.choice(self.generators)**random.choice([1,-1]) return r def index(self, H, strategy="relator_based"): """ Return the index of subgroup ``H`` in group ``self``. Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**5, y**4, y*x*y**3*x**3]) >>> f.index([x]) 4 """ # TODO: use |G:H| = |G|/|H| (currently H can't be made into a group) # when we know |G| and |H| if H == []: return self.order() else: C = self.coset_enumeration(H, strategy) return len(C.table) def __str__(self): if self.free_group.rank > 30: str_form = "<fp group with %s generators>" % self.free_group.rank else: str_form = "<fp group on the generators %s>" % str(self.generators) return str_form __repr__ = __str__ #============================================================================== # PERMUTATION GROUP METHODS #============================================================================== def _to_perm_group(self): ''' Return an isomorphic permutation group and the isomorphism. The implementation is dependent on coset enumeration so will only terminate for finite groups. ''' from sympy.combinatorics import Permutation, PermutationGroup from sympy.combinatorics.homomorphisms import homomorphism if self.order() is S.Infinity: raise NotImplementedError("Permutation presentation of infinite " "groups is not implemented") if self._perm_isomorphism: T = self._perm_isomorphism P = T.image() else: C = self.coset_table([]) gens = self.generators images = [[C[i][2*gens.index(g)] for i in range(len(C))] for g in gens] images = [Permutation(i) for i in images] P = PermutationGroup(images) T = homomorphism(self, P, gens, images, check=False) self._perm_isomorphism = T return P, T def _perm_group_list(self, method_name, *args): ''' Given the name of a `PermutationGroup` method (returning a subgroup or a list of subgroups) and (optionally) additional arguments it takes, return a list or a list of lists containing the generators of this (or these) subgroups in terms of the generators of `self`. ''' P, T = self._to_perm_group() perm_result = getattr(P, method_name)(*args) single = False if isinstance(perm_result, PermutationGroup): perm_result, single = [perm_result], True result = [] for group in perm_result: gens = group.generators result.append(T.invert(gens)) return result[0] if single else result def derived_series(self): ''' Return the list of lists containing the generators of the subgroups in the derived series of `self`. ''' return self._perm_group_list('derived_series') def lower_central_series(self): ''' Return the list of lists containing the generators of the subgroups in the lower central series of `self`. ''' return self._perm_group_list('lower_central_series') def center(self): ''' Return the list of generators of the center of `self`. ''' return self._perm_group_list('center') def derived_subgroup(self): ''' Return the list of generators of the derived subgroup of `self`. ''' return self._perm_group_list('derived_subgroup') def centralizer(self, other): ''' Return the list of generators of the centralizer of `other` (a list of elements of `self`) in `self`. ''' T = self._to_perm_group()[1] other = T(other) return self._perm_group_list('centralizer', other) def normal_closure(self, other): ''' Return the list of generators of the normal closure of `other` (a list of elements of `self`) in `self`. ''' T = self._to_perm_group()[1] other = T(other) return self._perm_group_list('normal_closure', other) def _perm_property(self, attr): ''' Given an attribute of a `PermutationGroup`, return its value for a permutation group isomorphic to `self`. ''' P = self._to_perm_group()[0] return getattr(P, attr) @property def is_abelian(self): ''' Check if `self` is abelian. ''' return self._perm_property("is_abelian") @property def is_nilpotent(self): ''' Check if `self` is nilpotent. ''' return self._perm_property("is_nilpotent") @property def is_solvable(self): ''' Check if `self` is solvable. ''' return self._perm_property("is_solvable") @property def elements(self): ''' List the elements of `self`. ''' P, T = self._to_perm_group() return T.invert(P._elements) @property def is_cyclic(self): """ Return ``True`` if group is Cyclic. """ if len(self.generators) <= 1: return True try: P, T = self._to_perm_group() except NotImplementedError: raise NotImplementedError("Check for infinite Cyclic group " "is not implemented") return P.is_cyclic def abelian_invariants(self): """ Return Abelian Invariants of a group. """ try: P, T = self._to_perm_group() except NotImplementedError: raise NotImplementedError("abelian invariants is not implemented" "for infinite group") return P.abelian_invariants() def composition_series(self): """ Return subnormal series of maximum length for a group. """ try: P, T = self._to_perm_group() except NotImplementedError: raise NotImplementedError("composition series is not implemented" "for infinite group") return P.composition_series() class FpSubgroup(DefaultPrinting): ''' The class implementing a subgroup of an FpGroup or a FreeGroup (only finite index subgroups are supported at this point). This is to be used if one wishes to check if an element of the original group belongs to the subgroup ''' def __init__(self, G, gens, normal=False): super().__init__() self.parent = G self.generators = list({g for g in gens if g != G.identity}) self._min_words = None #for use in __contains__ self.C = None self.normal = normal def __contains__(self, g): if isinstance(self.parent, FreeGroup): if self._min_words is None: # make _min_words - a list of subwords such that # g is in the subgroup if and only if it can be # partitioned into these subwords. Infinite families of # subwords are presented by tuples, e.g. (r, w) # stands for the family of subwords r*w**n*r**-1 def _process(w): # this is to be used before adding new words # into _min_words; if the word w is not cyclically # reduced, it will generate an infinite family of # subwords so should be written as a tuple; # if it is, w**-1 should be added to the list # as well p, r = w.cyclic_reduction(removed=True) if not r.is_identity: return [(r, p)] else: return [w, w**-1] # make the initial list gens = [] for w in self.generators: if self.normal: w = w.cyclic_reduction() gens.extend(_process(w)) for w1 in gens: for w2 in gens: # if w1 and w2 are equal or are inverses, continue if w1 == w2 or (not isinstance(w1, tuple) and w1**-1 == w2): continue # if the start of one word is the inverse of the # end of the other, their multiple should be added # to _min_words because of cancellation if isinstance(w1, tuple): # start, end s1, s2 = w1[0][0], w1[0][0]**-1 else: s1, s2 = w1[0], w1[len(w1)-1] if isinstance(w2, tuple): # start, end r1, r2 = w2[0][0], w2[0][0]**-1 else: r1, r2 = w2[0], w2[len(w1)-1] # p1 and p2 are w1 and w2 or, in case when # w1 or w2 is an infinite family, a representative p1, p2 = w1, w2 if isinstance(w1, tuple): p1 = w1[0]*w1[1]*w1[0]**-1 if isinstance(w2, tuple): p2 = w2[0]*w2[1]*w2[0]**-1 # add the product of the words to the list is necessary if r1**-1 == s2 and not (p1*p2).is_identity: new = _process(p1*p2) if not new in gens: gens.extend(new) if r2**-1 == s1 and not (p2*p1).is_identity: new = _process(p2*p1) if not new in gens: gens.extend(new) self._min_words = gens min_words = self._min_words def _is_subword(w): # check if w is a word in _min_words or one of # the infinite families in it w, r = w.cyclic_reduction(removed=True) if r.is_identity or self.normal: return w in min_words else: t = [s[1] for s in min_words if isinstance(s, tuple) and s[0] == r] return [s for s in t if w.power_of(s)] != [] # store the solution of words for which the result of # _word_break (below) is known known = {} def _word_break(w): # check if w can be written as a product of words # in min_words if len(w) == 0: return True i = 0 while i < len(w): i += 1 prefix = w.subword(0, i) if not _is_subword(prefix): continue rest = w.subword(i, len(w)) if rest not in known: known[rest] = _word_break(rest) if known[rest]: return True return False if self.normal: g = g.cyclic_reduction() return _word_break(g) else: if self.C is None: C = self.parent.coset_enumeration(self.generators) self.C = C i = 0 C = self.C for j in range(len(g)): i = C.table[i][C.A_dict[g[j]]] return i == 0 def order(self): from sympy import S if not self.generators: return 1 if isinstance(self.parent, FreeGroup): return S.Infinity if self.C is None: C = self.parent.coset_enumeration(self.generators) self.C = C # This is valid because `len(self.C.table)` (the index of the subgroup) # will always be finite - otherwise coset enumeration doesn't terminate return self.parent.order()/len(self.C.table) def to_FpGroup(self): if isinstance(self.parent, FreeGroup): gen_syms = [('x_%d'%i) for i in range(len(self.generators))] return free_group(', '.join(gen_syms))[0] return self.parent.subgroup(C=self.C) def __str__(self): if len(self.generators) > 30: str_form = "<fp subgroup with %s generators>" % len(self.generators) else: str_form = "<fp subgroup on the generators %s>" % str(self.generators) return str_form __repr__ = __str__ ############################################################################### # LOW INDEX SUBGROUPS # ############################################################################### def low_index_subgroups(G, N, Y=()): """ Implements the Low Index Subgroups algorithm, i.e find all subgroups of ``G`` upto a given index ``N``. This implements the method described in [Sim94]. This procedure involves a backtrack search over incomplete Coset Tables, rather than over forced coincidences. Parameters ========== G: An FpGroup < X|R > N: positive integer, representing the maximum index value for subgroups Y: (an optional argument) specifying a list of subgroup generators, such that each of the resulting subgroup contains the subgroup generated by Y. Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, low_index_subgroups >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**2, y**3, (x*y)**4]) >>> L = low_index_subgroups(f, 4) >>> for coset_table in L: ... print(coset_table.table) [[0, 0, 0, 0]] [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 3, 3]] [[0, 0, 1, 2], [2, 2, 2, 0], [1, 1, 0, 1]] [[1, 1, 0, 0], [0, 0, 1, 1]] References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" Section 5.4 .. [2] Marston Conder and Peter Dobcsanyi "Applications and Adaptions of the Low Index Subgroups Procedure" """ C = CosetTable(G, []) R = G.relators # length chosen for the length of the short relators len_short_rel = 5 # elements of R2 only checked at the last step for complete # coset tables R2 = {rel for rel in R if len(rel) > len_short_rel} # elements of R1 are used in inner parts of the process to prune # branches of the search tree, R1 = {rel.identity_cyclic_reduction() for rel in set(R) - R2} R1_c_list = C.conjugates(R1) S = [] descendant_subgroups(S, C, R1_c_list, C.A[0], R2, N, Y) return S def descendant_subgroups(S, C, R1_c_list, x, R2, N, Y): A_dict = C.A_dict A_dict_inv = C.A_dict_inv if C.is_complete(): # if C is complete then it only needs to test # whether the relators in R2 are satisfied for w, alpha in product(R2, C.omega): if not C.scan_check(alpha, w): return # relators in R2 are satisfied, append the table to list S.append(C) else: # find the first undefined entry in Coset Table for alpha, x in product(range(len(C.table)), C.A): if C.table[alpha][A_dict[x]] is None: # this is "x" in pseudo-code (using "y" makes it clear) undefined_coset, undefined_gen = alpha, x break # for filling up the undefine entry we try all possible values # of beta in Omega or beta = n where beta^(undefined_gen^-1) is undefined reach = C.omega + [C.n] for beta in reach: if beta < N: if beta == C.n or C.table[beta][A_dict_inv[undefined_gen]] is None: try_descendant(S, C, R1_c_list, R2, N, undefined_coset, \ undefined_gen, beta, Y) def try_descendant(S, C, R1_c_list, R2, N, alpha, x, beta, Y): r""" Solves the problem of trying out each individual possibility for `\alpha^x. """ D = C.copy() if beta == D.n and beta < N: D.table.append([None]*len(D.A)) D.p.append(beta) D.table[alpha][D.A_dict[x]] = beta D.table[beta][D.A_dict_inv[x]] = alpha D.deduction_stack.append((alpha, x)) if not D.process_deductions_check(R1_c_list[D.A_dict[x]], \ R1_c_list[D.A_dict_inv[x]]): return for w in Y: if not D.scan_check(0, w): return if first_in_class(D, Y): descendant_subgroups(S, D, R1_c_list, x, R2, N, Y) def first_in_class(C, Y=()): """ Checks whether the subgroup ``H=G1`` corresponding to the Coset Table could possibly be the canonical representative of its conjugacy class. Parameters ========== C: CosetTable Returns ======= bool: True/False If this returns False, then no descendant of C can have that property, and so we can abandon C. If it returns True, then we need to process further the node of the search tree corresponding to C, and so we call ``descendant_subgroups`` recursively on C. Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, CosetTable, first_in_class >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**2, y**3, (x*y)**4]) >>> C = CosetTable(f, []) >>> C.table = [[0, 0, None, None]] >>> first_in_class(C) True >>> C.table = [[1, 1, 1, None], [0, 0, None, 1]]; C.p = [0, 1] >>> first_in_class(C) True >>> C.table = [[1, 1, 2, 1], [0, 0, 0, None], [None, None, None, 0]] >>> C.p = [0, 1, 2] >>> first_in_class(C) False >>> C.table = [[1, 1, 1, 2], [0, 0, 2, 0], [2, None, 0, 1]] >>> first_in_class(C) False # TODO:: Sims points out in [Sim94] that performance can be improved by # remembering some of the information computed by ``first_in_class``. If # the ``continue alpha`` statement is executed at line 14, then the same thing # will happen for that value of alpha in any descendant of the table C, and so # the values the values of alpha for which this occurs could profitably be # stored and passed through to the descendants of C. Of course this would # make the code more complicated. # The code below is taken directly from the function on page 208 of [Sim94] # nu[alpha] """ n = C.n # lamda is the largest numbered point in Omega_c_alpha which is currently defined lamda = -1 # for alpha in Omega_c, nu[alpha] is the point in Omega_c_alpha corresponding to alpha nu = [None]*n # for alpha in Omega_c_alpha, mu[alpha] is the point in Omega_c corresponding to alpha mu = [None]*n # mutually nu and mu are the mutually-inverse equivalence maps between # Omega_c_alpha and Omega_c next_alpha = False # For each 0!=alpha in [0 .. nc-1], we start by constructing the equivalent # standardized coset table C_alpha corresponding to H_alpha for alpha in range(1, n): # reset nu to "None" after previous value of alpha for beta in range(lamda+1): nu[mu[beta]] = None # we only want to reject our current table in favour of a preceding # table in the ordering in which 1 is replaced by alpha, if the subgroup # G_alpha corresponding to this preceding table definitely contains the # given subgroup for w in Y: # TODO: this should support input of a list of general words # not just the words which are in "A" (i.e gen and gen^-1) if C.table[alpha][C.A_dict[w]] != alpha: # continue with alpha next_alpha = True break if next_alpha: next_alpha = False continue # try alpha as the new point 0 in Omega_C_alpha mu[0] = alpha nu[alpha] = 0 # compare corresponding entries in C and C_alpha lamda = 0 for beta in range(n): for x in C.A: gamma = C.table[beta][C.A_dict[x]] delta = C.table[mu[beta]][C.A_dict[x]] # if either of the entries is undefined, # we move with next alpha if gamma is None or delta is None: # continue with alpha next_alpha = True break if nu[delta] is None: # delta becomes the next point in Omega_C_alpha lamda += 1 nu[delta] = lamda mu[lamda] = delta if nu[delta] < gamma: return False if nu[delta] > gamma: # continue with alpha next_alpha = True break if next_alpha: next_alpha = False break return True #======================================================================== # Simplifying Presentation #======================================================================== def simplify_presentation(*args, change_gens=False): ''' For an instance of `FpGroup`, return a simplified isomorphic copy of the group (e.g. remove redundant generators or relators). Alternatively, a list of generators and relators can be passed in which case the simplified lists will be returned. By default, the generators of the group are unchanged. If you would like to remove redundant generators, set the keyword argument `change_gens = True`. ''' if len(args) == 1: if not isinstance(args[0], FpGroup): raise TypeError("The argument must be an instance of FpGroup") G = args[0] gens, rels = simplify_presentation(G.generators, G.relators, change_gens=change_gens) if gens: return FpGroup(gens[0].group, rels) return FpGroup(FreeGroup([]), []) elif len(args) == 2: gens, rels = args[0][:], args[1][:] if not gens: return gens, rels identity = gens[0].group.identity else: if len(args) == 0: m = "Not enough arguments" else: m = "Too many arguments" raise RuntimeError(m) prev_gens = [] prev_rels = [] while not set(prev_rels) == set(rels): prev_rels = rels while change_gens and not set(prev_gens) == set(gens): prev_gens = gens gens, rels = elimination_technique_1(gens, rels, identity) rels = _simplify_relators(rels, identity) if change_gens: syms = [g.array_form[0][0] for g in gens] F = free_group(syms)[0] identity = F.identity gens = F.generators subs = dict(zip(syms, gens)) for j, r in enumerate(rels): a = r.array_form rel = identity for sym, p in a: rel = rel*subs[sym]**p rels[j] = rel return gens, rels def _simplify_relators(rels, identity): """Relies upon ``_simplification_technique_1`` for its functioning. """ rels = rels[:] rels = list(set(_simplification_technique_1(rels))) rels.sort() rels = [r.identity_cyclic_reduction() for r in rels] try: rels.remove(identity) except ValueError: pass return rels # Pg 350, section 2.5.1 from [2] def elimination_technique_1(gens, rels, identity): rels = rels[:] # the shorter relators are examined first so that generators selected for # elimination will have shorter strings as equivalent rels.sort() gens = gens[:] redundant_gens = {} redundant_rels = [] used_gens = set() # examine each relator in relator list for any generator occurring exactly # once for rel in rels: # don't look for a redundant generator in a relator which # depends on previously found ones contained_gens = rel.contains_generators() if any(g in contained_gens for g in redundant_gens): continue contained_gens = list(contained_gens) contained_gens.sort(reverse = True) for gen in contained_gens: if rel.generator_count(gen) == 1 and gen not in used_gens: k = rel.exponent_sum(gen) gen_index = rel.index(gen**k) bk = rel.subword(gen_index + 1, len(rel)) fw = rel.subword(0, gen_index) chi = bk*fw redundant_gens[gen] = chi**(-1*k) used_gens.update(chi.contains_generators()) redundant_rels.append(rel) break rels = [r for r in rels if r not in redundant_rels] # eliminate the redundant generators from remaining relators rels = [r.eliminate_words(redundant_gens, _all = True).identity_cyclic_reduction() for r in rels] rels = list(set(rels)) try: rels.remove(identity) except ValueError: pass gens = [g for g in gens if g not in redundant_gens] return gens, rels def _simplification_technique_1(rels): """ All relators are checked to see if they are of the form `gen^n`. If any such relators are found then all other relators are processed for strings in the `gen` known order. Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import _simplification_technique_1 >>> F, x, y = free_group("x, y") >>> w1 = [x**2*y**4, x**3] >>> _simplification_technique_1(w1) [x**-1*y**4, x**3] >>> w2 = [x**2*y**-4*x**5, x**3, x**2*y**8, y**5] >>> _simplification_technique_1(w2) [x**-1*y*x**-1, x**3, x**-1*y**-2, y**5] >>> w3 = [x**6*y**4, x**4] >>> _simplification_technique_1(w3) [x**2*y**4, x**4] """ from sympy import gcd rels = rels[:] # dictionary with "gen: n" where gen^n is one of the relators exps = {} for i in range(len(rels)): rel = rels[i] if rel.number_syllables() == 1: g = rel[0] exp = abs(rel.array_form[0][1]) if rel.array_form[0][1] < 0: rels[i] = rels[i]**-1 g = g**-1 if g in exps: exp = gcd(exp, exps[g].array_form[0][1]) exps[g] = g**exp one_syllables_words = exps.values() # decrease some of the exponents in relators, making use of the single # syllable relators for i in range(len(rels)): rel = rels[i] if rel in one_syllables_words: continue rel = rel.eliminate_words(one_syllables_words, _all = True) # if rels[i] contains g**n where abs(n) is greater than half of the power p # of g in exps, g**n can be replaced by g**(n-p) (or g**(p-n) if n<0) for g in rel.contains_generators(): if g in exps: exp = exps[g].array_form[0][1] max_exp = (exp + 1)//2 rel = rel.eliminate_word(g**(max_exp), g**(max_exp-exp), _all = True) rel = rel.eliminate_word(g**(-max_exp), g**(-(max_exp-exp)), _all = True) rels[i] = rel rels = [r.identity_cyclic_reduction() for r in rels] return rels ############################################################################### # SUBGROUP PRESENTATIONS # ############################################################################### # Pg 175 [1] def define_schreier_generators(C, homomorphism=False): ''' Parameters ========== C -- Coset table. homomorphism -- When set to True, return a dictionary containing the images of the presentation generators in the original group. ''' y = [] gamma = 1 f = C.fp_group X = f.generators if homomorphism: # `_gens` stores the elements of the parent group to # to which the schreier generators correspond to. _gens = {} # compute the schreier Traversal tau = {} tau[0] = f.identity C.P = [[None]*len(C.A) for i in range(C.n)] for alpha, x in product(C.omega, C.A): beta = C.table[alpha][C.A_dict[x]] if beta == gamma: C.P[alpha][C.A_dict[x]] = "<identity>" C.P[beta][C.A_dict_inv[x]] = "<identity>" gamma += 1 if homomorphism: tau[beta] = tau[alpha]*x elif x in X and C.P[alpha][C.A_dict[x]] is None: y_alpha_x = '%s_%s' % (x, alpha) y.append(y_alpha_x) C.P[alpha][C.A_dict[x]] = y_alpha_x if homomorphism: _gens[y_alpha_x] = tau[alpha]*x*tau[beta]**-1 grp_gens = list(free_group(', '.join(y))) C._schreier_free_group = grp_gens.pop(0) C._schreier_generators = grp_gens if homomorphism: C._schreier_gen_elem = _gens # replace all elements of P by, free group elements for i, j in product(range(len(C.P)), range(len(C.A))): # if equals "<identity>", replace by identity element if C.P[i][j] == "<identity>": C.P[i][j] = C._schreier_free_group.identity elif isinstance(C.P[i][j], str): r = C._schreier_generators[y.index(C.P[i][j])] C.P[i][j] = r beta = C.table[i][j] C.P[beta][j + 1] = r**-1 def reidemeister_relators(C): R = C.fp_group.relators rels = [rewrite(C, coset, word) for word in R for coset in range(C.n)] order_1_gens = {i for i in rels if len(i) == 1} # remove all the order 1 generators from relators rels = list(filter(lambda rel: rel not in order_1_gens, rels)) # replace order 1 generators by identity element in reidemeister relators for i in range(len(rels)): w = rels[i] w = w.eliminate_words(order_1_gens, _all=True) rels[i] = w C._schreier_generators = [i for i in C._schreier_generators if not (i in order_1_gens or i**-1 in order_1_gens)] # Tietze transformation 1 i.e TT_1 # remove cyclic conjugate elements from relators i = 0 while i < len(rels): w = rels[i] j = i + 1 while j < len(rels): if w.is_cyclic_conjugate(rels[j]): del rels[j] else: j += 1 i += 1 C._reidemeister_relators = rels def rewrite(C, alpha, w): """ Parameters ========== C: CosetTable alpha: A live coset w: A word in `A*` Returns ======= rho(tau(alpha), w) Examples ======== >>> from sympy.combinatorics.fp_groups import FpGroup, CosetTable, define_schreier_generators, rewrite >>> from sympy.combinatorics.free_groups import free_group >>> F, x, y = free_group("x ,y") >>> f = FpGroup(F, [x**2, y**3, (x*y)**6]) >>> C = CosetTable(f, []) >>> C.table = [[1, 1, 2, 3], [0, 0, 4, 5], [4, 4, 3, 0], [5, 5, 0, 2], [2, 2, 5, 1], [3, 3, 1, 4]] >>> C.p = [0, 1, 2, 3, 4, 5] >>> define_schreier_generators(C) >>> rewrite(C, 0, (x*y)**6) x_4*y_2*x_3*x_1*x_2*y_4*x_5 """ v = C._schreier_free_group.identity for i in range(len(w)): x_i = w[i] v = v*C.P[alpha][C.A_dict[x_i]] alpha = C.table[alpha][C.A_dict[x_i]] return v # Pg 350, section 2.5.2 from [2] def elimination_technique_2(C): """ This technique eliminates one generator at a time. Heuristically this seems superior in that we may select for elimination the generator with shortest equivalent string at each stage. >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r, \ reidemeister_relators, define_schreier_generators, elimination_technique_2 >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**5, (x*y)**2]); H = [x*y, x**-1*y**-1*x*y*x] >>> C = coset_enumeration_r(f, H) >>> C.compress(); C.standardize() >>> define_schreier_generators(C) >>> reidemeister_relators(C) >>> elimination_technique_2(C) ([y_1, y_2], [y_2**-3, y_2*y_1*y_2*y_1*y_2*y_1, y_1**2]) """ rels = C._reidemeister_relators rels.sort(reverse=True) gens = C._schreier_generators for i in range(len(gens) - 1, -1, -1): rel = rels[i] for j in range(len(gens) - 1, -1, -1): gen = gens[j] if rel.generator_count(gen) == 1: k = rel.exponent_sum(gen) gen_index = rel.index(gen**k) bk = rel.subword(gen_index + 1, len(rel)) fw = rel.subword(0, gen_index) rep_by = (bk*fw)**(-1*k) del rels[i]; del gens[j] for l in range(len(rels)): rels[l] = rels[l].eliminate_word(gen, rep_by) break C._reidemeister_relators = rels C._schreier_generators = gens return C._schreier_generators, C._reidemeister_relators def reidemeister_presentation(fp_grp, H, C=None, homomorphism=False): """ Parameters ========== fp_group: A finitely presented group, an instance of FpGroup H: A subgroup whose presentation is to be found, given as a list of words in generators of `fp_grp` homomorphism: When set to True, return a homomorphism from the subgroup to the parent group Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, reidemeister_presentation >>> F, x, y = free_group("x, y") Example 5.6 Pg. 177 from [1] >>> f = FpGroup(F, [x**3, y**5, (x*y)**2]) >>> H = [x*y, x**-1*y**-1*x*y*x] >>> reidemeister_presentation(f, H) ((y_1, y_2), (y_1**2, y_2**3, y_2*y_1*y_2*y_1*y_2*y_1)) Example 5.8 Pg. 183 from [1] >>> f = FpGroup(F, [x**3, y**3, (x*y)**3]) >>> H = [x*y, x*y**-1] >>> reidemeister_presentation(f, H) ((x_0, y_0), (x_0**3, y_0**3, x_0*y_0*x_0*y_0*x_0*y_0)) Exercises Q2. Pg 187 from [1] >>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3]) >>> H = [x] >>> reidemeister_presentation(f, H) ((x_0,), (x_0**4,)) Example 5.9 Pg. 183 from [1] >>> f = FpGroup(F, [x**3*y**-3, (x*y)**3, (x*y**-1)**2]) >>> H = [x] >>> reidemeister_presentation(f, H) ((x_0,), (x_0**6,)) """ if not C: C = coset_enumeration_r(fp_grp, H) C.compress(); C.standardize() define_schreier_generators(C, homomorphism=homomorphism) reidemeister_relators(C) gens, rels = C._schreier_generators, C._reidemeister_relators gens, rels = simplify_presentation(gens, rels, change_gens=True) C.schreier_generators = tuple(gens) C.reidemeister_relators = tuple(rels) if homomorphism: _gens = [] for gen in gens: _gens.append(C._schreier_gen_elem[str(gen)]) return C.schreier_generators, C.reidemeister_relators, _gens return C.schreier_generators, C.reidemeister_relators FpGroupElement = FreeGroupElement
5b8abe78c01aeb537f5bdb6ebd61a12c958878e8cf969da1eb6d74078fe5c7a5
from sympy.core.add import Add from sympy.core.compatibility import is_sequence from sympy.core.containers import Tuple from sympy.core.expr import Expr from sympy.core.mul import Mul from sympy.core.relational import Equality, Relational from sympy.core.singleton import S from sympy.core.symbol import Symbol, Dummy from sympy.core.sympify import sympify from sympy.functions.elementary.piecewise import (piecewise_fold, Piecewise) from sympy.logic.boolalg import BooleanFunction from sympy.tensor.indexed import Idx from sympy.sets.sets import Interval from sympy.sets.fancysets import Range from sympy.utilities import flatten from sympy.utilities.iterables import sift from sympy.utilities.exceptions import SymPyDeprecationWarning def _common_new(cls, function, *symbols, **assumptions): """Return either a special return value or the tuple, (function, limits, orientation). This code is common to both ExprWithLimits and AddWithLimits.""" function = sympify(function) if isinstance(function, Equality): # This transforms e.g. Integral(Eq(x, y)) to Eq(Integral(x), Integral(y)) # but that is only valid for definite integrals. limits, orientation = _process_limits(*symbols) if not (limits and all(len(limit) == 3 for limit in limits)): SymPyDeprecationWarning( feature='Integral(Eq(x, y))', useinstead='Eq(Integral(x, z), Integral(y, z))', issue=18053, deprecated_since_version=1.6, ).warn() lhs = function.lhs rhs = function.rhs return Equality(cls(lhs, *symbols, **assumptions), \ cls(rhs, *symbols, **assumptions)) if function is S.NaN: return S.NaN if symbols: limits, orientation = _process_limits(*symbols) for i, li in enumerate(limits): if len(li) == 4: function = function.subs(li[0], li[-1]) limits[i] = Tuple(*li[:-1]) else: # symbol not provided -- we can still try to compute a general form free = function.free_symbols if len(free) != 1: raise ValueError( "specify dummy variables for %s" % function) limits, orientation = [Tuple(s) for s in free], 1 # denest any nested calls while cls == type(function): limits = list(function.limits) + limits function = function.function # Any embedded piecewise functions need to be brought out to the # top level. We only fold Piecewise that contain the integration # variable. reps = {} symbols_of_integration = {i[0] for i in limits} for p in function.atoms(Piecewise): if not p.has(*symbols_of_integration): reps[p] = Dummy() # mask off those that don't function = function.xreplace(reps) # do the fold function = piecewise_fold(function) # remove the masking function = function.xreplace({v: k for k, v in reps.items()}) return function, limits, orientation def _process_limits(*symbols): """Process the list of symbols and convert them to canonical limits, storing them as Tuple(symbol, lower, upper). The orientation of the function is also returned when the upper limit is missing so (x, 1, None) becomes (x, None, 1) and the orientation is changed. """ limits = [] orientation = 1 for V in symbols: if isinstance(V, (Relational, BooleanFunction)): variable = V.atoms(Symbol).pop() V = (variable, V.as_set()) if isinstance(V, Symbol) or getattr(V, '_diff_wrt', False): if isinstance(V, Idx): if V.lower is None or V.upper is None: limits.append(Tuple(V)) else: limits.append(Tuple(V, V.lower, V.upper)) else: limits.append(Tuple(V)) continue elif is_sequence(V, Tuple): if len(V) == 2 and isinstance(V[1], Range): lo = V[1].inf hi = V[1].sup dx = abs(V[1].step) V = [V[0]] + [0, (hi - lo)//dx, dx*V[0] + lo] V = sympify(flatten(V)) # a list of sympified elements if isinstance(V[0], (Symbol, Idx)) or getattr(V[0], '_diff_wrt', False): newsymbol = V[0] if len(V) == 2 and isinstance(V[1], Interval): # 2 -> 3 # Interval V[1:] = [V[1].start, V[1].end] elif len(V) == 3: # general case if V[2] is None and not V[1] is None: orientation *= -1 V = [newsymbol] + [i for i in V[1:] if i is not None] lenV = len(V) if not isinstance(newsymbol, Idx) or lenV == 3: if lenV == 4: limits.append(Tuple(*V)) continue if lenV == 3: if isinstance(newsymbol, Idx): # Idx represents an integer which may have # specified values it can take on; if it is # given such a value, an error is raised here # if the summation would try to give it a larger # or smaller value than permitted. None and Symbolic # values will not raise an error. lo, hi = newsymbol.lower, newsymbol.upper try: if lo is not None and not bool(V[1] >= lo): raise ValueError("Summation will set Idx value too low.") except TypeError: pass try: if hi is not None and not bool(V[2] <= hi): raise ValueError("Summation will set Idx value too high.") except TypeError: pass limits.append(Tuple(*V)) continue if lenV == 1 or (lenV == 2 and V[1] is None): limits.append(Tuple(newsymbol)) continue elif lenV == 2: limits.append(Tuple(newsymbol, V[1])) continue raise ValueError('Invalid limits given: %s' % str(symbols)) return limits, orientation class ExprWithLimits(Expr): __slots__ = ('is_commutative',) def __new__(cls, function, *symbols, **assumptions): pre = _common_new(cls, function, *symbols, **assumptions) if type(pre) is tuple: function, limits, _ = pre else: return pre # limits must have upper and lower bounds; the indefinite form # is not supported. This restriction does not apply to AddWithLimits if any(len(l) != 3 or None in l for l in limits): raise ValueError('ExprWithLimits requires values for lower and upper bounds.') obj = Expr.__new__(cls, **assumptions) arglist = [function] arglist.extend(limits) obj._args = tuple(arglist) obj.is_commutative = function.is_commutative # limits already checked return obj @property def function(self): """Return the function applied across limits. Examples ======== >>> from sympy import Integral >>> from sympy.abc import x >>> Integral(x**2, (x,)).function x**2 See Also ======== limits, variables, free_symbols """ return self._args[0] @property def kind(self): return self.function.kind @property def limits(self): """Return the limits of expression. Examples ======== >>> from sympy import Integral >>> from sympy.abc import x, i >>> Integral(x**i, (i, 1, 3)).limits ((i, 1, 3),) See Also ======== function, variables, free_symbols """ return self._args[1:] @property def variables(self): """Return a list of the limit variables. >>> from sympy import Sum >>> from sympy.abc import x, i >>> Sum(x**i, (i, 1, 3)).variables [i] See Also ======== function, limits, free_symbols as_dummy : Rename dummy variables sympy.integrals.integrals.Integral.transform : Perform mapping on the dummy variable """ return [l[0] for l in self.limits] @property def bound_symbols(self): """Return only variables that are dummy variables. Examples ======== >>> from sympy import Integral >>> from sympy.abc import x, i, j, k >>> Integral(x**i, (i, 1, 3), (j, 2), k).bound_symbols [i, j] See Also ======== function, limits, free_symbols as_dummy : Rename dummy variables sympy.integrals.integrals.Integral.transform : Perform mapping on the dummy variable """ return [l[0] for l in self.limits if len(l) != 1] @property def free_symbols(self): """ This method returns the symbols in the object, excluding those that take on a specific value (i.e. the dummy symbols). Examples ======== >>> from sympy import Sum >>> from sympy.abc import x, y >>> Sum(x, (x, y, 1)).free_symbols {y} """ # don't test for any special values -- nominal free symbols # should be returned, e.g. don't return set() if the # function is zero -- treat it like an unevaluated expression. function, limits = self.function, self.limits isyms = function.free_symbols for xab in limits: if len(xab) == 1: isyms.add(xab[0]) continue # take out the target symbol if xab[0] in isyms: isyms.remove(xab[0]) # add in the new symbols for i in xab[1:]: isyms.update(i.free_symbols) return isyms @property def is_number(self): """Return True if the Sum has no free symbols, else False.""" return not self.free_symbols def _eval_interval(self, x, a, b): limits = [(i if i[0] != x else (x, a, b)) for i in self.limits] integrand = self.function return self.func(integrand, *limits) def _eval_subs(self, old, new): """ Perform substitutions over non-dummy variables of an expression with limits. Also, can be used to specify point-evaluation of an abstract antiderivative. Examples ======== >>> from sympy import Sum, oo >>> from sympy.abc import s, n >>> Sum(1/n**s, (n, 1, oo)).subs(s, 2) Sum(n**(-2), (n, 1, oo)) >>> from sympy import Integral >>> from sympy.abc import x, a >>> Integral(a*x**2, x).subs(x, 4) Integral(a*x**2, (x, 4)) See Also ======== variables : Lists the integration variables transform : Perform mapping on the dummy variable for integrals change_index : Perform mapping on the sum and product dummy variables """ from sympy.core.function import AppliedUndef, UndefinedFunction func, limits = self.function, list(self.limits) # If one of the expressions we are replacing is used as a func index # one of two things happens. # - the old variable first appears as a free variable # so we perform all free substitutions before it becomes # a func index. # - the old variable first appears as a func index, in # which case we ignore. See change_index. # Reorder limits to match standard mathematical practice for scoping limits.reverse() if not isinstance(old, Symbol) or \ old.free_symbols.intersection(self.free_symbols): sub_into_func = True for i, xab in enumerate(limits): if 1 == len(xab) and old == xab[0]: if new._diff_wrt: xab = (new,) else: xab = (old, old) limits[i] = Tuple(xab[0], *[l._subs(old, new) for l in xab[1:]]) if len(xab[0].free_symbols.intersection(old.free_symbols)) != 0: sub_into_func = False break if isinstance(old, AppliedUndef) or isinstance(old, UndefinedFunction): sy2 = set(self.variables).intersection(set(new.atoms(Symbol))) sy1 = set(self.variables).intersection(set(old.args)) if not sy2.issubset(sy1): raise ValueError( "substitution can not create dummy dependencies") sub_into_func = True if sub_into_func: func = func.subs(old, new) else: # old is a Symbol and a dummy variable of some limit for i, xab in enumerate(limits): if len(xab) == 3: limits[i] = Tuple(xab[0], *[l._subs(old, new) for l in xab[1:]]) if old == xab[0]: break # simplify redundant limits (x, x) to (x, ) for i, xab in enumerate(limits): if len(xab) == 2 and (xab[0] - xab[1]).is_zero: limits[i] = Tuple(xab[0], ) # Reorder limits back to representation-form limits.reverse() return self.func(func, *limits) @property def has_finite_limits(self): """ Returns True if the limits are known to be finite, either by the explicit bounds, assumptions on the bounds, or assumptions on the variables. False if known to be infinite, based on the bounds. None if not enough information is available to determine. Examples ======== >>> from sympy import Sum, Integral, Product, oo, Symbol >>> x = Symbol('x') >>> Sum(x, (x, 1, 8)).has_finite_limits True >>> Integral(x, (x, 1, oo)).has_finite_limits False >>> M = Symbol('M') >>> Sum(x, (x, 1, M)).has_finite_limits >>> N = Symbol('N', integer=True) >>> Product(x, (x, 1, N)).has_finite_limits True See Also ======== has_reversed_limits """ ret_None = False for lim in self.limits: if len(lim) == 3: if any(l.is_infinite for l in lim[1:]): # Any of the bounds are +/-oo return False elif any(l.is_infinite is None for l in lim[1:]): # Maybe there are assumptions on the variable? if lim[0].is_infinite is None: ret_None = True else: if lim[0].is_infinite is None: ret_None = True if ret_None: return None return True @property def has_reversed_limits(self): """ Returns True if the limits are known to be in reversed order, either by the explicit bounds, assumptions on the bounds, or assumptions on the variables. False if known to be in normal order, based on the bounds. None if not enough information is available to determine. Examples ======== >>> from sympy import Sum, Integral, Product, oo, Symbol >>> x = Symbol('x') >>> Sum(x, (x, 8, 1)).has_reversed_limits True >>> Sum(x, (x, 1, oo)).has_reversed_limits False >>> M = Symbol('M') >>> Integral(x, (x, 1, M)).has_reversed_limits >>> N = Symbol('N', integer=True, positive=True) >>> Sum(x, (x, 1, N)).has_reversed_limits False >>> Product(x, (x, 2, N)).has_reversed_limits >>> Product(x, (x, 2, N)).subs(N, N + 2).has_reversed_limits False See Also ======== sympy.concrete.expr_with_intlimits.ExprWithIntLimits.has_empty_sequence """ ret_None = False for lim in self.limits: if len(lim) == 3: var, a, b = lim dif = b - a if dif.is_extended_negative: return True elif dif.is_extended_nonnegative: continue else: ret_None = True else: return None if ret_None: return None return False class AddWithLimits(ExprWithLimits): r"""Represents unevaluated oriented additions. Parent class for Integral and Sum. """ def __new__(cls, function, *symbols, **assumptions): pre = _common_new(cls, function, *symbols, **assumptions) if type(pre) is tuple: function, limits, orientation = pre else: return pre obj = Expr.__new__(cls, **assumptions) arglist = [orientation*function] # orientation not used in ExprWithLimits arglist.extend(limits) obj._args = tuple(arglist) obj.is_commutative = function.is_commutative # limits already checked return obj def _eval_adjoint(self): if all(x.is_real for x in flatten(self.limits)): return self.func(self.function.adjoint(), *self.limits) return None def _eval_conjugate(self): if all(x.is_real for x in flatten(self.limits)): return self.func(self.function.conjugate(), *self.limits) return None def _eval_transpose(self): if all(x.is_real for x in flatten(self.limits)): return self.func(self.function.transpose(), *self.limits) return None def _eval_factor(self, **hints): if 1 == len(self.limits): summand = self.function.factor(**hints) if summand.is_Mul: out = sift(summand.args, lambda w: w.is_commutative \ and not set(self.variables) & w.free_symbols) return Mul(*out[True])*self.func(Mul(*out[False]), \ *self.limits) else: summand = self.func(self.function, *self.limits[0:-1]).factor() if not summand.has(self.variables[-1]): return self.func(1, [self.limits[-1]]).doit()*summand elif isinstance(summand, Mul): return self.func(summand, self.limits[-1]).factor() return self def _eval_expand_basic(self, **hints): from sympy.matrices.matrices import MatrixBase summand = self.function.expand(**hints) if summand.is_Add and summand.is_commutative: return Add(*[self.func(i, *self.limits) for i in summand.args]) elif isinstance(summand, MatrixBase): return summand.applyfunc(lambda x: self.func(x, *self.limits)) elif summand != self.function: return self.func(summand, *self.limits) return self
082291307ed02332a30257787858ec406e03817b61975592678979f7c79d51b2
from sympy.calculus.singularities import is_decreasing from sympy.calculus.util import AccumulationBounds from sympy.concrete.expr_with_limits import AddWithLimits from sympy.concrete.expr_with_intlimits import ExprWithIntLimits from sympy.concrete.gosper import gosper_sum from sympy.core.add import Add from sympy.core.function import Derivative from sympy.core.mul import Mul from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import Dummy, Wild, Symbol from sympy.functions.special.zeta_functions import zeta from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import cot, csc from sympy.logic.boolalg import And from sympy.polys import apart, together from sympy.polys.polyerrors import PolynomialError, PolificationFailed from sympy.polys.polytools import parallel_poly_from_expr from sympy.series.limitseq import limit_seq from sympy.series.order import O from sympy.series.residues import residue from sympy.sets.sets import FiniteSet from sympy.simplify import denom from sympy.simplify.combsimp import combsimp from sympy.simplify.powsimp import powsimp from sympy.solvers import solve from sympy.solvers.solveset import solveset from sympy.utilities.iterables import sift import itertools class Sum(AddWithLimits, ExprWithIntLimits): r""" Represents unevaluated summation. Explanation =========== ``Sum`` represents a finite or infinite series, with the first argument being the general form of terms in the series, and the second argument being ``(dummy_variable, start, end)``, with ``dummy_variable`` taking all integer values from ``start`` through ``end``. In accordance with long-standing mathematical convention, the end term is included in the summation. Finite sums =========== For finite sums (and sums with symbolic limits assumed to be finite) we follow the summation convention described by Karr [1], especially definition 3 of section 1.4. The sum: .. math:: \sum_{m \leq i < n} f(i) has *the obvious meaning* for `m < n`, namely: .. math:: \sum_{m \leq i < n} f(i) = f(m) + f(m+1) + \ldots + f(n-2) + f(n-1) with the upper limit value `f(n)` excluded. The sum over an empty set is zero if and only if `m = n`: .. math:: \sum_{m \leq i < n} f(i) = 0 \quad \mathrm{for} \quad m = n Finally, for all other sums over empty sets we assume the following definition: .. math:: \sum_{m \leq i < n} f(i) = - \sum_{n \leq i < m} f(i) \quad \mathrm{for} \quad m > n It is important to note that Karr defines all sums with the upper limit being exclusive. This is in contrast to the usual mathematical notation, but does not affect the summation convention. Indeed we have: .. math:: \sum_{m \leq i < n} f(i) = \sum_{i = m}^{n - 1} f(i) where the difference in notation is intentional to emphasize the meaning, with limits typeset on the top being inclusive. Examples ======== >>> from sympy.abc import i, k, m, n, x >>> from sympy import Sum, factorial, oo, IndexedBase, Function >>> Sum(k, (k, 1, m)) Sum(k, (k, 1, m)) >>> Sum(k, (k, 1, m)).doit() m**2/2 + m/2 >>> Sum(k**2, (k, 1, m)) Sum(k**2, (k, 1, m)) >>> Sum(k**2, (k, 1, m)).doit() m**3/3 + m**2/2 + m/6 >>> Sum(x**k, (k, 0, oo)) Sum(x**k, (k, 0, oo)) >>> Sum(x**k, (k, 0, oo)).doit() Piecewise((1/(1 - x), Abs(x) < 1), (Sum(x**k, (k, 0, oo)), True)) >>> Sum(x**k/factorial(k), (k, 0, oo)).doit() exp(x) Here are examples to do summation with symbolic indices. You can use either Function of IndexedBase classes: >>> f = Function('f') >>> Sum(f(n), (n, 0, 3)).doit() f(0) + f(1) + f(2) + f(3) >>> Sum(f(n), (n, 0, oo)).doit() Sum(f(n), (n, 0, oo)) >>> f = IndexedBase('f') >>> Sum(f[n]**2, (n, 0, 3)).doit() f[0]**2 + f[1]**2 + f[2]**2 + f[3]**2 An example showing that the symbolic result of a summation is still valid for seemingly nonsensical values of the limits. Then the Karr convention allows us to give a perfectly valid interpretation to those sums by interchanging the limits according to the above rules: >>> S = Sum(i, (i, 1, n)).doit() >>> S n**2/2 + n/2 >>> S.subs(n, -4) 6 >>> Sum(i, (i, 1, -4)).doit() 6 >>> Sum(-i, (i, -3, 0)).doit() 6 An explicit example of the Karr summation convention: >>> S1 = Sum(i**2, (i, m, m+n-1)).doit() >>> S1 m**2*n + m*n**2 - m*n + n**3/3 - n**2/2 + n/6 >>> S2 = Sum(i**2, (i, m+n, m-1)).doit() >>> S2 -m**2*n - m*n**2 + m*n - n**3/3 + n**2/2 - n/6 >>> S1 + S2 0 >>> S3 = Sum(i, (i, m, m-1)).doit() >>> S3 0 See Also ======== summation Product, sympy.concrete.products.product References ========== .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM, Volume 28 Issue 2, April 1981, Pages 305-350 http://dl.acm.org/citation.cfm?doid=322248.322255 .. [2] https://en.wikipedia.org/wiki/Summation#Capital-sigma_notation .. [3] https://en.wikipedia.org/wiki/Empty_sum """ __slots__ = ('is_commutative',) def __new__(cls, function, *symbols, **assumptions): obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions) if not hasattr(obj, 'limits'): return obj if any(len(l) != 3 or None in l for l in obj.limits): raise ValueError('Sum requires values for lower and upper bounds.') return obj def _eval_is_zero(self): # a Sum is only zero if its function is zero or if all terms # cancel out. This only answers whether the summand is zero; if # not then None is returned since we don't analyze whether all # terms cancel out. if self.function.is_zero or self.has_empty_sequence: return True def _eval_is_extended_real(self): if self.has_empty_sequence: return True return self.function.is_extended_real def _eval_is_positive(self): if self.has_finite_limits and self.has_reversed_limits is False: return self.function.is_positive def _eval_is_negative(self): if self.has_finite_limits and self.has_reversed_limits is False: return self.function.is_negative def _eval_is_finite(self): if self.has_finite_limits and self.function.is_finite: return True def doit(self, **hints): if hints.get('deep', True): f = self.function.doit(**hints) else: f = self.function # first make sure any definite limits have summation # variables with matching assumptions reps = {} for xab in self.limits: d = _dummy_with_inherited_properties_concrete(xab) if d: reps[xab[0]] = d if reps: undo = {v: k for k, v in reps.items()} did = self.xreplace(reps).doit(**hints) if type(did) is tuple: # when separate=True did = tuple([i.xreplace(undo) for i in did]) elif did is not None: did = did.xreplace(undo) else: did = self return did if self.function.is_Matrix: expanded = self.expand() if self != expanded: return expanded.doit() return _eval_matrix_sum(self) for n, limit in enumerate(self.limits): i, a, b = limit dif = b - a if dif == -1: # Any summation over an empty set is zero return S.Zero if dif.is_integer and dif.is_negative: a, b = b + 1, a - 1 f = -f newf = eval_sum(f, (i, a, b)) if newf is None: if f == self.function: zeta_function = self.eval_zeta_function(f, (i, a, b)) if zeta_function is not None: return zeta_function return self else: return self.func(f, *self.limits[n:]) f = newf if hints.get('deep', True): # eval_sum could return partially unevaluated # result with Piecewise. In this case we won't # doit() recursively. if not isinstance(f, Piecewise): return f.doit(**hints) return f def eval_zeta_function(self, f, limits): """ Check whether the function matches with the zeta function. If it matches, then return a `Piecewise` expression because zeta function does not converge unless `s > 1` and `q > 0` """ i, a, b = limits w, y, z = Wild('w', exclude=[i]), Wild('y', exclude=[i]), Wild('z', exclude=[i]) result = f.match((w * i + y) ** (-z)) if result is not None and b is S.Infinity: coeff = 1 / result[w] ** result[z] s = result[z] q = result[y] / result[w] + a return Piecewise((coeff * zeta(s, q), And(q > 0, s > 1)), (self, True)) def _eval_derivative(self, x): """ Differentiate wrt x as long as x is not in the free symbols of any of the upper or lower limits. Explanation =========== Sum(a*b*x, (x, 1, a)) can be differentiated wrt x or b but not `a` since the value of the sum is discontinuous in `a`. In a case involving a limit variable, the unevaluated derivative is returned. """ # diff already confirmed that x is in the free symbols of self, but we # don't want to differentiate wrt any free symbol in the upper or lower # limits # XXX remove this test for free_symbols when the default _eval_derivative is in if isinstance(x, Symbol) and x not in self.free_symbols: return S.Zero # get limits and the function f, limits = self.function, list(self.limits) limit = limits.pop(-1) if limits: # f is the argument to a Sum f = self.func(f, *limits) _, a, b = limit if x in a.free_symbols or x in b.free_symbols: return None df = Derivative(f, x, evaluate=True) rv = self.func(df, limit) return rv def _eval_difference_delta(self, n, step): k, _, upper = self.args[-1] new_upper = upper.subs(n, n + step) if len(self.args) == 2: f = self.args[0] else: f = self.func(*self.args[:-1]) return Sum(f, (k, upper + 1, new_upper)).doit() def _eval_simplify(self, **kwargs): from sympy.simplify.simplify import factor_sum, sum_combine from sympy.core.function import expand from sympy.core.mul import Mul # split the function into adds terms = Add.make_args(expand(self.function)) s_t = [] # Sum Terms o_t = [] # Other Terms for term in terms: if term.has(Sum): # if there is an embedded sum here # it is of the form x * (Sum(whatever)) # hence we make a Mul out of it, and simplify all interior sum terms subterms = Mul.make_args(expand(term)) out_terms = [] for subterm in subterms: # go through each term if isinstance(subterm, Sum): # if it's a sum, simplify it out_terms.append(subterm._eval_simplify()) else: # otherwise, add it as is out_terms.append(subterm) # turn it back into a Mul s_t.append(Mul(*out_terms)) else: o_t.append(term) # next try to combine any interior sums for further simplification result = Add(sum_combine(s_t), *o_t) return factor_sum(result, limits=self.limits) def is_convergent(self): r""" Checks for the convergence of a Sum. Explanation =========== We divide the study of convergence of infinite sums and products in two parts. First Part: One part is the question whether all the terms are well defined, i.e., they are finite in a sum and also non-zero in a product. Zero is the analogy of (minus) infinity in products as :math:`e^{-\infty} = 0`. Second Part: The second part is the question of convergence after infinities, and zeros in products, have been omitted assuming that their number is finite. This means that we only consider the tail of the sum or product, starting from some point after which all terms are well defined. For example, in a sum of the form: .. math:: \sum_{1 \leq i < \infty} \frac{1}{n^2 + an + b} where a and b are numbers. The routine will return true, even if there are infinities in the term sequence (at most two). An analogous product would be: .. math:: \prod_{1 \leq i < \infty} e^{\frac{1}{n^2 + an + b}} This is how convergence is interpreted. It is concerned with what happens at the limit. Finding the bad terms is another independent matter. Note: It is responsibility of user to see that the sum or product is well defined. There are various tests employed to check the convergence like divergence test, root test, integral test, alternating series test, comparison tests, Dirichlet tests. It returns true if Sum is convergent and false if divergent and NotImplementedError if it can not be checked. References ========== .. [1] https://en.wikipedia.org/wiki/Convergence_tests Examples ======== >>> from sympy import factorial, S, Sum, Symbol, oo >>> n = Symbol('n', integer=True) >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent() True >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent() False >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent() False >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent() True See Also ======== Sum.is_absolutely_convergent() sympy.concrete.products.Product.is_convergent() """ from sympy import Interval, Integral, log, symbols, simplify p, q, r = symbols('p q r', cls=Wild) sym = self.limits[0][0] lower_limit = self.limits[0][1] upper_limit = self.limits[0][2] sequence_term = self.function.simplify() if len(sequence_term.free_symbols) > 1: raise NotImplementedError("convergence checking for more than one symbol " "containing series is not handled") if lower_limit.is_finite and upper_limit.is_finite: return S.true # transform sym -> -sym and swap the upper_limit = S.Infinity # and lower_limit = - upper_limit if lower_limit is S.NegativeInfinity: if upper_limit is S.Infinity: return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \ Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent() sequence_term = simplify(sequence_term.xreplace({sym: -sym})) lower_limit = -upper_limit upper_limit = S.Infinity sym_ = Dummy(sym.name, integer=True, positive=True) sequence_term = sequence_term.xreplace({sym: sym_}) sym = sym_ interval = Interval(lower_limit, upper_limit) # Piecewise function handle if sequence_term.is_Piecewise: for func, cond in sequence_term.args: # see if it represents something going to oo if cond == True or cond.as_set().sup is S.Infinity: s = Sum(func, (sym, lower_limit, upper_limit)) return s.is_convergent() return S.true ### -------- Divergence test ----------- ### try: lim_val = limit_seq(sequence_term, sym) if lim_val is not None and lim_val.is_zero is False: return S.false except NotImplementedError: pass try: lim_val_abs = limit_seq(abs(sequence_term), sym) if lim_val_abs is not None and lim_val_abs.is_zero is False: return S.false except NotImplementedError: pass order = O(sequence_term, (sym, S.Infinity)) ### --------- p-series test (1/n**p) ---------- ### p_series_test = order.expr.match(sym**p) if p_series_test is not None: if p_series_test[p] < -1: return S.true if p_series_test[p] >= -1: return S.false ### ------------- comparison test ------------- ### # 1/(n**p*log(n)**q*log(log(n))**r) comparison n_log_test = order.expr.match(1/(sym**p*log(sym)**q*log(log(sym))**r)) if n_log_test is not None: if (n_log_test[p] > 1 or (n_log_test[p] == 1 and n_log_test[q] > 1) or (n_log_test[p] == n_log_test[q] == 1 and n_log_test[r] > 1)): return S.true return S.false ### ------------- Limit comparison test -----------### # (1/n) comparison try: lim_comp = limit_seq(sym*sequence_term, sym) if lim_comp is not None and lim_comp.is_number and lim_comp > 0: return S.false except NotImplementedError: pass ### ----------- ratio test ---------------- ### next_sequence_term = sequence_term.xreplace({sym: sym + 1}) ratio = combsimp(powsimp(next_sequence_term/sequence_term)) try: lim_ratio = limit_seq(ratio, sym) if lim_ratio is not None and lim_ratio.is_number: if abs(lim_ratio) > 1: return S.false if abs(lim_ratio) < 1: return S.true except NotImplementedError: lim_ratio = None ### ---------- Raabe's test -------------- ### if lim_ratio == 1: # ratio test inconclusive test_val = sym*(sequence_term/ sequence_term.subs(sym, sym + 1) - 1) test_val = test_val.gammasimp() try: lim_val = limit_seq(test_val, sym) if lim_val is not None and lim_val.is_number: if lim_val > 1: return S.true if lim_val < 1: return S.false except NotImplementedError: pass ### ----------- root test ---------------- ### # lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity) try: lim_evaluated = limit_seq(abs(sequence_term)**(1/sym), sym) if lim_evaluated is not None and lim_evaluated.is_number: if lim_evaluated < 1: return S.true if lim_evaluated > 1: return S.false except NotImplementedError: pass ### ------------- alternating series test ----------- ### dict_val = sequence_term.match((-1)**(sym + p)*q) if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval): return S.true ### ------------- integral test -------------- ### check_interval = None maxima = solveset(sequence_term.diff(sym), sym, interval) if not maxima: check_interval = interval elif isinstance(maxima, FiniteSet) and maxima.sup.is_number: check_interval = Interval(maxima.sup, interval.sup) if (check_interval is not None and (is_decreasing(sequence_term, check_interval) or is_decreasing(-sequence_term, check_interval))): integral_val = Integral( sequence_term, (sym, lower_limit, upper_limit)) try: integral_val_evaluated = integral_val.doit() if integral_val_evaluated.is_number: return S(integral_val_evaluated.is_finite) except NotImplementedError: pass ### ----- Dirichlet and bounded times convergent tests ----- ### # TODO # # Dirichlet_test # https://en.wikipedia.org/wiki/Dirichlet%27s_test # # Bounded times convergent test # It is based on comparison theorems for series. # In particular, if the general term of a series can # be written as a product of two terms a_n and b_n # and if a_n is bounded and if Sum(b_n) is absolutely # convergent, then the original series Sum(a_n * b_n) # is absolutely convergent and so convergent. # # The following code can grows like 2**n where n is the # number of args in order.expr # Possibly combined with the potentially slow checks # inside the loop, could make this test extremely slow # for larger summation expressions. if order.expr.is_Mul: args = order.expr.args argset = set(args) ### -------------- Dirichlet tests -------------- ### m = Dummy('m', integer=True) def _dirichlet_test(g_n): try: ing_val = limit_seq(Sum(g_n, (sym, interval.inf, m)).doit(), m) if ing_val is not None and ing_val.is_finite: return S.true except NotImplementedError: pass ### -------- bounded times convergent test ---------### def _bounded_convergent_test(g1_n, g2_n): try: lim_val = limit_seq(g1_n, sym) if lim_val is not None and (lim_val.is_finite or ( isinstance(lim_val, AccumulationBounds) and (lim_val.max - lim_val.min).is_finite)): if Sum(g2_n, (sym, lower_limit, upper_limit)).is_absolutely_convergent(): return S.true except NotImplementedError: pass for n in range(1, len(argset)): for a_tuple in itertools.combinations(args, n): b_set = argset - set(a_tuple) a_n = Mul(*a_tuple) b_n = Mul(*b_set) if is_decreasing(a_n, interval): dirich = _dirichlet_test(b_n) if dirich is not None: return dirich bc_test = _bounded_convergent_test(a_n, b_n) if bc_test is not None: return bc_test _sym = self.limits[0][0] sequence_term = sequence_term.xreplace({sym: _sym}) raise NotImplementedError("The algorithm to find the Sum convergence of %s " "is not yet implemented" % (sequence_term)) def is_absolutely_convergent(self): """ Checks for the absolute convergence of an infinite series. Same as checking convergence of absolute value of sequence_term of an infinite series. References ========== .. [1] https://en.wikipedia.org/wiki/Absolute_convergence Examples ======== >>> from sympy import Sum, Symbol, oo >>> n = Symbol('n', integer=True) >>> Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent() False >>> Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent() True See Also ======== Sum.is_convergent() """ return Sum(abs(self.function), self.limits).is_convergent() def euler_maclaurin(self, m=0, n=0, eps=0, eval_integral=True): """ Return an Euler-Maclaurin approximation of self, where m is the number of leading terms to sum directly and n is the number of terms in the tail. With m = n = 0, this is simply the corresponding integral plus a first-order endpoint correction. Returns (s, e) where s is the Euler-Maclaurin approximation and e is the estimated error (taken to be the magnitude of the first omitted term in the tail): >>> from sympy.abc import k, a, b >>> from sympy import Sum >>> Sum(1/k, (k, 2, 5)).doit().evalf() 1.28333333333333 >>> s, e = Sum(1/k, (k, 2, 5)).euler_maclaurin() >>> s -log(2) + 7/20 + log(5) >>> from sympy import sstr >>> print(sstr((s.evalf(), e.evalf()), full_prec=True)) (1.26629073187415, 0.0175000000000000) The endpoints may be symbolic: >>> s, e = Sum(1/k, (k, a, b)).euler_maclaurin() >>> s -log(a) + log(b) + 1/(2*b) + 1/(2*a) >>> e Abs(1/(12*b**2) - 1/(12*a**2)) If the function is a polynomial of degree at most 2n+1, the Euler-Maclaurin formula becomes exact (and e = 0 is returned): >>> Sum(k, (k, 2, b)).euler_maclaurin() (b**2/2 + b/2 - 1, 0) >>> Sum(k, (k, 2, b)).doit() b**2/2 + b/2 - 1 With a nonzero eps specified, the summation is ended as soon as the remainder term is less than the epsilon. """ from sympy.functions import bernoulli, factorial from sympy.integrals import Integral m = int(m) n = int(n) f = self.function if len(self.limits) != 1: raise ValueError("More than 1 limit") i, a, b = self.limits[0] if (a > b) == True: if a - b == 1: return S.Zero, S.Zero a, b = b + 1, a - 1 f = -f s = S.Zero if m: if b.is_Integer and a.is_Integer: m = min(m, b - a + 1) if not eps or f.is_polynomial(i): for k in range(m): s += f.subs(i, a + k) else: term = f.subs(i, a) if term: test = abs(term.evalf(3)) < eps if test == True: return s, abs(term) elif not (test == False): # a symbolic Relational class, can't go further return term, S.Zero s += term for k in range(1, m): term = f.subs(i, a + k) if abs(term.evalf(3)) < eps and term != 0: return s, abs(term) s += term if b - a + 1 == m: return s, S.Zero a += m x = Dummy('x') I = Integral(f.subs(i, x), (x, a, b)) if eval_integral: I = I.doit() s += I def fpoint(expr): if b is S.Infinity: return expr.subs(i, a), 0 return expr.subs(i, a), expr.subs(i, b) fa, fb = fpoint(f) iterm = (fa + fb)/2 g = f.diff(i) for k in range(1, n + 2): ga, gb = fpoint(g) term = bernoulli(2*k)/factorial(2*k)*(gb - ga) if (eps and term and abs(term.evalf(3)) < eps) or (k > n): break s += term g = g.diff(i, 2, simplify=False) return s + iterm, abs(term) def reverse_order(self, *indices): """ Reverse the order of a limit in a Sum. Explanation =========== ``reverse_order(self, *indices)`` reverses some limits in the expression ``self`` which can be either a ``Sum`` or a ``Product``. The selectors in the argument ``indices`` specify some indices whose limits get reversed. These selectors are either variable names or numerical indices counted starting from the inner-most limit tuple. Examples ======== >>> from sympy import Sum >>> from sympy.abc import x, y, a, b, c, d >>> Sum(x, (x, 0, 3)).reverse_order(x) Sum(-x, (x, 4, -1)) >>> Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(x, y) Sum(x*y, (x, 6, 0), (y, 7, -1)) >>> Sum(x, (x, a, b)).reverse_order(x) Sum(-x, (x, b + 1, a - 1)) >>> Sum(x, (x, a, b)).reverse_order(0) Sum(-x, (x, b + 1, a - 1)) While one should prefer variable names when specifying which limits to reverse, the index counting notation comes in handy in case there are several symbols with the same name. >>> S = Sum(x**2, (x, a, b), (x, c, d)) >>> S Sum(x**2, (x, a, b), (x, c, d)) >>> S0 = S.reverse_order(0) >>> S0 Sum(-x**2, (x, b + 1, a - 1), (x, c, d)) >>> S1 = S0.reverse_order(1) >>> S1 Sum(x**2, (x, b + 1, a - 1), (x, d + 1, c - 1)) Of course we can mix both notations: >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) See Also ======== sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index, reorder_limit, sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder References ========== .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM, Volume 28 Issue 2, April 1981, Pages 305-350 http://dl.acm.org/citation.cfm?doid=322248.322255 """ l_indices = list(indices) for i, indx in enumerate(l_indices): if not isinstance(indx, int): l_indices[i] = self.index(indx) e = 1 limits = [] for i, limit in enumerate(self.limits): l = limit if i in l_indices: e = -e l = (limit[0], limit[2] + 1, limit[1] - 1) limits.append(l) return Sum(e * self.function, *limits) def summation(f, *symbols, **kwargs): r""" Compute the summation of f with respect to symbols. Explanation =========== The notation for symbols is similar to the notation used in Integral. summation(f, (i, a, b)) computes the sum of f with respect to i from a to b, i.e., :: b ____ \ ` summation(f, (i, a, b)) = ) f /___, i = a If it cannot compute the sum, it returns an unevaluated Sum object. Repeated sums can be computed by introducing additional symbols tuples:: Examples ======== >>> from sympy import summation, oo, symbols, log >>> i, n, m = symbols('i n m', integer=True) >>> summation(2*i - 1, (i, 1, n)) n**2 >>> summation(1/2**i, (i, 0, oo)) 2 >>> summation(1/log(n)**n, (n, 2, oo)) Sum(log(n)**(-n), (n, 2, oo)) >>> summation(i, (i, 0, n), (n, 0, m)) m**3/6 + m**2/2 + m/3 >>> from sympy.abc import x >>> from sympy import factorial >>> summation(x**n/factorial(n), (n, 0, oo)) exp(x) See Also ======== Sum Product, sympy.concrete.products.product """ return Sum(f, *symbols, **kwargs).doit(deep=False) def telescopic_direct(L, R, n, limits): """ Returns the direct summation of the terms of a telescopic sum Explanation =========== L is the term with lower index R is the term with higher index n difference between the indexes of L and R Examples ======== >>> from sympy.concrete.summations import telescopic_direct >>> from sympy.abc import k, a, b >>> telescopic_direct(1/k, -1/(k+2), 2, (k, a, b)) -1/(b + 2) - 1/(b + 1) + 1/(a + 1) + 1/a """ (i, a, b) = limits s = 0 for m in range(n): s += L.subs(i, a + m) + R.subs(i, b - m) return s def telescopic(L, R, limits): ''' Tries to perform the summation using the telescopic property. Return None if not possible. ''' (i, a, b) = limits if L.is_Add or R.is_Add: return None # We want to solve(L.subs(i, i + m) + R, m) # First we try a simple match since this does things that # solve doesn't do, e.g. solve(f(k+m)-f(k), m) fails k = Wild("k") sol = (-R).match(L.subs(i, i + k)) s = None if sol and k in sol: s = sol[k] if not (s.is_Integer and L.subs(i, i + s) == -R): # sometimes match fail(f(x+2).match(-f(x+k))->{k: -2 - 2x})) s = None # But there are things that match doesn't do that solve # can do, e.g. determine that 1/(x + m) = 1/(1 - x) when m = 1 if s is None: m = Dummy('m') try: sol = solve(L.subs(i, i + m) + R, m) or [] except NotImplementedError: return None sol = [si for si in sol if si.is_Integer and (L.subs(i, i + si) + R).expand().is_zero] if len(sol) != 1: return None s = sol[0] if s < 0: return telescopic_direct(R, L, abs(s), (i, a, b)) elif s > 0: return telescopic_direct(L, R, s, (i, a, b)) def eval_sum(f, limits): from sympy.concrete.delta import deltasummation, _has_simple_delta from sympy.functions import KroneckerDelta (i, a, b) = limits if f.is_zero: return S.Zero if i not in f.free_symbols: return f*(b - a + 1) if a == b: return f.subs(i, a) if isinstance(f, Piecewise): if not any(i in arg.args[1].free_symbols for arg in f.args): # Piecewise conditions do not depend on the dummy summation variable, # therefore we can fold: Sum(Piecewise((e, c), ...), limits) # --> Piecewise((Sum(e, limits), c), ...) newargs = [] for arg in f.args: newexpr = eval_sum(arg.expr, limits) if newexpr is None: return None newargs.append((newexpr, arg.cond)) return f.func(*newargs) if f.has(KroneckerDelta): f = f.replace( lambda x: isinstance(x, Sum), lambda x: x.factor() ) if _has_simple_delta(f, limits[0]): return deltasummation(f, limits) dif = b - a definite = dif.is_Integer # Doing it directly may be faster if there are very few terms. if definite and (dif < 100): return eval_sum_direct(f, (i, a, b)) if isinstance(f, Piecewise): return None # Try to do it symbolically. Even when the number of terms is known, # this can save time when b-a is big. # We should try to transform to partial fractions value = eval_sum_symbolic(f.expand(), (i, a, b)) if value is not None: return value # Do it directly if definite: return eval_sum_direct(f, (i, a, b)) def eval_sum_direct(expr, limits): """ Evaluate expression directly, but perform some simple checks first to possibly result in a smaller expression and faster execution. """ from sympy.core import Add (i, a, b) = limits dif = b - a # Linearity if expr.is_Mul: # Try factor out everything not including i without_i, with_i = expr.as_independent(i) if without_i != 1: s = eval_sum_direct(with_i, (i, a, b)) if s: r = without_i*s if r is not S.NaN: return r else: # Try term by term L, R = expr.as_two_terms() if not L.has(i): sR = eval_sum_direct(R, (i, a, b)) if sR: return L*sR if not R.has(i): sL = eval_sum_direct(L, (i, a, b)) if sL: return sL*R try: expr = apart(expr, i) # see if it becomes an Add except PolynomialError: pass if expr.is_Add: # Try factor out everything not including i without_i, with_i = expr.as_independent(i) if without_i != 0: s = eval_sum_direct(with_i, (i, a, b)) if s: r = without_i*(dif + 1) + s if r is not S.NaN: return r else: # Try term by term L, R = expr.as_two_terms() lsum = eval_sum_direct(L, (i, a, b)) rsum = eval_sum_direct(R, (i, a, b)) if None not in (lsum, rsum): r = lsum + rsum if r is not S.NaN: return r return Add(*[expr.subs(i, a + j) for j in range(dif + 1)]) def eval_sum_symbolic(f, limits): from sympy.functions import harmonic, bernoulli f_orig = f (i, a, b) = limits if not f.has(i): return f*(b - a + 1) # Linearity if f.is_Mul: # Try factor out everything not including i without_i, with_i = f.as_independent(i) if without_i != 1: s = eval_sum_symbolic(with_i, (i, a, b)) if s: r = without_i*s if r is not S.NaN: return r else: # Try term by term L, R = f.as_two_terms() if not L.has(i): sR = eval_sum_symbolic(R, (i, a, b)) if sR: return L*sR if not R.has(i): sL = eval_sum_symbolic(L, (i, a, b)) if sL: return sL*R try: f = apart(f, i) # see if it becomes an Add except PolynomialError: pass if f.is_Add: L, R = f.as_two_terms() lrsum = telescopic(L, R, (i, a, b)) if lrsum: return lrsum # Try factor out everything not including i without_i, with_i = f.as_independent(i) if without_i != 0: s = eval_sum_symbolic(with_i, (i, a, b)) if s: r = without_i*(b - a + 1) + s if r is not S.NaN: return r else: # Try term by term lsum = eval_sum_symbolic(L, (i, a, b)) rsum = eval_sum_symbolic(R, (i, a, b)) if None not in (lsum, rsum): r = lsum + rsum if r is not S.NaN: return r # Polynomial terms with Faulhaber's formula n = Wild('n') result = f.match(i**n) if result is not None: n = result[n] if n.is_Integer: if n >= 0: if (b is S.Infinity and not a is S.NegativeInfinity) or \ (a is S.NegativeInfinity and not b is S.Infinity): return S.Infinity return ((bernoulli(n + 1, b + 1) - bernoulli(n + 1, a))/(n + 1)).expand() elif a.is_Integer and a >= 1: if n == -1: return harmonic(b) - harmonic(a - 1) else: return harmonic(b, abs(n)) - harmonic(a - 1, abs(n)) if not (a.has(S.Infinity, S.NegativeInfinity) or b.has(S.Infinity, S.NegativeInfinity)): # Geometric terms c1 = Wild('c1', exclude=[i]) c2 = Wild('c2', exclude=[i]) c3 = Wild('c3', exclude=[i]) wexp = Wild('wexp') # Here we first attempt powsimp on f for easier matching with the # exponential pattern, and attempt expansion on the exponent for easier # matching with the linear pattern. e = f.powsimp().match(c1 ** wexp) if e is not None: e_exp = e.pop(wexp).expand().match(c2*i + c3) if e_exp is not None: e.update(e_exp) p = (c1**c3).subs(e) q = (c1**c2).subs(e) r = p*(q**a - q**(b + 1))/(1 - q) l = p*(b - a + 1) return Piecewise((l, Eq(q, S.One)), (r, True)) r = gosper_sum(f, (i, a, b)) if isinstance(r, (Mul,Add)): from sympy import ordered, Tuple non_limit = r.free_symbols - Tuple(*limits[1:]).free_symbols den = denom(together(r)) den_sym = non_limit & den.free_symbols args = [] for v in ordered(den_sym): try: s = solve(den, v) m = Eq(v, s[0]) if s else S.false if m != False: args.append((Sum(f_orig.subs(*m.args), limits).doit(), m)) break except NotImplementedError: continue args.append((r, True)) return Piecewise(*args) if not r in (None, S.NaN): return r h = eval_sum_hyper(f_orig, (i, a, b)) if h is not None: return h r = eval_sum_residue(f_orig, (i, a, b)) if r is not None: return r factored = f_orig.factor() if factored != f_orig: return eval_sum_symbolic(factored, (i, a, b)) def _eval_sum_hyper(f, i, a): """ Returns (res, cond). Sums from a to oo. """ from sympy.functions import hyper from sympy.simplify import hyperexpand, hypersimp, fraction, simplify from sympy.polys.polytools import Poly, factor from sympy.core.numbers import Float if a != 0: return _eval_sum_hyper(f.subs(i, i + a), i, 0) if f.subs(i, 0) == 0: if simplify(f.subs(i, Dummy('i', integer=True, positive=True))) == 0: return S.Zero, True return _eval_sum_hyper(f.subs(i, i + 1), i, 0) hs = hypersimp(f, i) if hs is None: return None if isinstance(hs, Float): from sympy.simplify.simplify import nsimplify hs = nsimplify(hs) numer, denom = fraction(factor(hs)) top, topl = numer.as_coeff_mul(i) bot, botl = denom.as_coeff_mul(i) ab = [top, bot] factors = [topl, botl] params = [[], []] for k in range(2): for fac in factors[k]: mul = 1 if fac.is_Pow: mul = fac.exp fac = fac.base if not mul.is_Integer: return None p = Poly(fac, i) if p.degree() != 1: return None m, n = p.all_coeffs() ab[k] *= m**mul params[k] += [n/m]*mul # Add "1" to numerator parameters, to account for implicit n! in # hypergeometric series. ap = params[0] + [1] bq = params[1] x = ab[0]/ab[1] h = hyper(ap, bq, x) f = combsimp(f) return f.subs(i, 0)*hyperexpand(h), h.convergence_statement def eval_sum_hyper(f, i_a_b): from sympy.logic.boolalg import And i, a, b = i_a_b if (b - a).is_Integer: # We are never going to do better than doing the sum in the obvious way return None old_sum = Sum(f, (i, a, b)) if b != S.Infinity: if a is S.NegativeInfinity: res = _eval_sum_hyper(f.subs(i, -i), i, -b) if res is not None: return Piecewise(res, (old_sum, True)) else: res1 = _eval_sum_hyper(f, i, a) res2 = _eval_sum_hyper(f, i, b + 1) if res1 is None or res2 is None: return None (res1, cond1), (res2, cond2) = res1, res2 cond = And(cond1, cond2) if cond == False: return None return Piecewise((res1 - res2, cond), (old_sum, True)) if a is S.NegativeInfinity: res1 = _eval_sum_hyper(f.subs(i, -i), i, 1) res2 = _eval_sum_hyper(f, i, 0) if res1 is None or res2 is None: return None res1, cond1 = res1 res2, cond2 = res2 cond = And(cond1, cond2) if cond == False or cond.as_set() == S.EmptySet: return None return Piecewise((res1 + res2, cond), (old_sum, True)) # Now b == oo, a != -oo res = _eval_sum_hyper(f, i, a) if res is not None: r, c = res if c == False: if r.is_number: f = f.subs(i, Dummy('i', integer=True, positive=True) + a) if f.is_positive or f.is_zero: return S.Infinity elif f.is_negative: return S.NegativeInfinity return None return Piecewise(res, (old_sum, True)) def eval_sum_residue(f, i_a_b): r"""Compute the infinite summation with residues Notes ===== If $f(n), g(n)$ are polynomials with $\deg(g(n)) - \deg(f(n)) >= 2$, some infinite summations can be computed by the following residue evaluations. .. math:: \sum_{n=-\infty, g(n) \ne 0}^{\infty} \frac{f(n)}{g(n)} = -\pi \sum_{\alpha|g(\alpha)=0} \text{Res}(\cot(\pi x) \frac{f(x)}{g(x)}, \alpha) .. math:: \sum_{n=-\infty, g(n) \ne 0}^{\infty} (-1)^n \frac{f(n)}{g(n)} = -\pi \sum_{\alpha|g(\alpha)=0} \text{Res}(\csc(\pi x) \frac{f(x)}{g(x)}, \alpha) Examples ======== >>> from sympy import Sum, oo, Symbol >>> x = Symbol('x') Doubly infinite series of rational functions. >>> Sum(1 / (x**2 + 1), (x, -oo, oo)).doit() pi/tanh(pi) Doubly infinite alternating series of rational functions. >>> Sum((-1)**x / (x**2 + 1), (x, -oo, oo)).doit() pi/sinh(pi) Infinite series of even rational functions. >>> Sum(1 / (x**2 + 1), (x, 0, oo)).doit() 1/2 + pi/(2*tanh(pi)) Infinite series of alternating even rational functions. >>> Sum((-1)**x / (x**2 + 1), (x, 0, oo)).doit() pi/(2*sinh(pi)) + 1/2 This also have heuristics to transform arbitrarily shifted summand or arbitrarily shifted summation range to the canonical problem the formula can handle. >>> Sum(1 / (x**2 + 2*x + 2), (x, -1, oo)).doit() 1/2 + pi/(2*tanh(pi)) >>> Sum(1 / (x**2 + 4*x + 5), (x, -2, oo)).doit() 1/2 + pi/(2*tanh(pi)) >>> Sum(1 / (x**2 + 1), (x, 1, oo)).doit() -1/2 + pi/(2*tanh(pi)) >>> Sum(1 / (x**2 + 1), (x, 2, oo)).doit() -1 + pi/(2*tanh(pi)) References ========== .. [#] http://www.supermath.info/InfiniteSeriesandtheResidueTheorem.pdf .. [#] Asmar N.H., Grafakos L. (2018) Residue Theory. In: Complex Analysis with Applications. Undergraduate Texts in Mathematics. Springer, Cham. https://doi.org/10.1007/978-3-319-94063-2_5 """ i, a, b = i_a_b def is_even_function(numer, denom): """Test if the rational function is an even function""" numer_even = all(i % 2 == 0 for (i,) in numer.monoms()) denom_even = all(i % 2 == 0 for (i,) in denom.monoms()) numer_odd = all(i % 2 == 1 for (i,) in numer.monoms()) denom_odd = all(i % 2 == 1 for (i,) in denom.monoms()) return (numer_even and denom_even) or (numer_odd and denom_odd) def match_rational(f, i): numer, denom = f.as_numer_denom() try: (numer, denom), opt = parallel_poly_from_expr((numer, denom), i) except (PolificationFailed, PolynomialError): return None return numer, denom def get_poles(denom): roots = denom.sqf_part().all_roots() roots = sift(roots, lambda x: x.is_integer) if None in roots: return None int_roots, nonint_roots = roots[True], roots[False] return int_roots, nonint_roots def get_shift(denom): n = denom.degree(i) a = denom.coeff_monomial(i**n) b = denom.coeff_monomial(i**(n-1)) shift = - b / a / n return shift def get_residue_factor(numer, denom, alternating): if not alternating: residue_factor = (numer.as_expr() / denom.as_expr()) * cot(S.Pi * i) else: residue_factor = (numer.as_expr() / denom.as_expr()) * csc(S.Pi * i) return residue_factor # We don't know how to deal with symbolic constants in summand if f.free_symbols - set([i]): return None if not (a.is_Integer or a in (S.Infinity, S.NegativeInfinity)): return None if not (b.is_Integer or b in (S.Infinity, S.NegativeInfinity)): return None # Quick exit heuristic for the sums which doesn't have infinite range if a != S.NegativeInfinity and b != S.Infinity: return None match = match_rational(f, i) if match: alternating = False numer, denom = match else: match = match_rational(f / (-1)**i, i) if match: alternating = True numer, denom = match else: return None if denom.degree(i) - numer.degree(i) < 2: return None if (a, b) == (S.NegativeInfinity, S.Infinity): poles = get_poles(denom) if poles is None: return None int_roots, nonint_roots = poles if int_roots: return None residue_factor = get_residue_factor(numer, denom, alternating) residues = [residue(residue_factor, i, root) for root in nonint_roots] return -S.Pi * sum(residues) if not (a.is_finite and b is S.Infinity): return None if not is_even_function(numer, denom): # Try shifting summation and check if the summand can be made # and even function from the origin. # Sum(f(n), (n, a, b)) => Sum(f(n + s), (n, a - s, b - s)) shift = get_shift(denom) if not shift.is_Integer: return None if shift == 0: return None numer = numer.shift(shift) denom = denom.shift(shift) if not is_even_function(numer, denom): return None if alternating: f = (-1)**i * ((-1)**shift * numer.as_expr() / denom.as_expr()) else: f = numer.as_expr() / denom.as_expr() return eval_sum_residue(f, (i, a-shift, b-shift)) poles = get_poles(denom) if poles is None: return None int_roots, nonint_roots = poles if int_roots: int_roots = [int(root) for root in int_roots] int_roots_max = max(int_roots) int_roots_min = min(int_roots) # Integer valued poles must be next to each other # and also symmetric from origin (Because the function is even) if not len(int_roots) == int_roots_max - int_roots_min + 1: return None # Check whether the summation indices contain poles if a <= max(int_roots): return None residue_factor = get_residue_factor(numer, denom, alternating) residues = [residue(residue_factor, i, root) for root in int_roots + nonint_roots] full_sum = -S.Pi * sum(residues) if not int_roots: # Compute Sum(f, (i, 0, oo)) by adding a extraneous evaluation # at the origin. half_sum = (full_sum + f.xreplace({i: 0})) / 2 # Add and subtract extraneous evaluations extraneous_neg = [f.xreplace({i: i0}) for i0 in range(int(a), 0)] extraneous_pos = [f.xreplace({i: i0}) for i0 in range(0, int(a))] result = half_sum + sum(extraneous_neg) - sum(extraneous_pos) return result # Compute Sum(f, (i, min(poles) + 1, oo)) half_sum = full_sum / 2 # Subtract extraneous evaluations extraneous = [f.xreplace({i: i0}) for i0 in range(max(int_roots) + 1, int(a))] result = half_sum - sum(extraneous) return result def _eval_matrix_sum(expression): f = expression.function for n, limit in enumerate(expression.limits): i, a, b = limit dif = b - a if dif.is_Integer: if (dif < 0) == True: a, b = b + 1, a - 1 f = -f newf = eval_sum_direct(f, (i, a, b)) if newf is not None: return newf.doit() def _dummy_with_inherited_properties_concrete(limits): """ Return a Dummy symbol that inherits as many assumptions as possible from the provided symbol and limits. If the symbol already has all True assumption shared by the limits then return None. """ x, a, b = limits l = [a, b] assumptions_to_consider = ['extended_nonnegative', 'nonnegative', 'extended_nonpositive', 'nonpositive', 'extended_positive', 'positive', 'extended_negative', 'negative', 'integer', 'rational', 'finite', 'zero', 'real', 'extended_real'] assumptions_to_keep = {} assumptions_to_add = {} for assum in assumptions_to_consider: assum_true = x._assumptions.get(assum, None) if assum_true: assumptions_to_keep[assum] = True elif all(getattr(i, 'is_' + assum) for i in l): assumptions_to_add[assum] = True if assumptions_to_add: assumptions_to_keep.update(assumptions_to_add) return Dummy('d', **assumptions_to_keep)
a8ae6081d6780702315ab2db45d1974e0ef2fd6230441d4f23501e2fe7d5feb8
"""Tools to assist importing optional external modules.""" import sys import re # Override these in the module to change the default warning behavior. # For example, you might set both to False before running the tests so that # warnings are not printed to the console, or set both to True for debugging. WARN_NOT_INSTALLED = None # Default is False WARN_OLD_VERSION = None # Default is True def __sympy_debug(): # helper function from sympy/__init__.py # We don't just import SYMPY_DEBUG from that file because we don't want to # import all of sympy just to use this module. import os debug_str = os.getenv('SYMPY_DEBUG', 'False') if debug_str in ('True', 'False'): return eval(debug_str) else: raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" % debug_str) if __sympy_debug(): WARN_OLD_VERSION = True WARN_NOT_INSTALLED = True _component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE) def version_tuple(vstring): # Parse a version string to a tuple e.g. '1.2' -> (1, 2) # Simplified from distutils.version.LooseVersion which was deprecated in # Python 3.10. components = [] for x in _component_re.split(vstring): if x and x != '.': try: x = int(x) except ValueError: pass components.append(x) return tuple(components) def import_module(module, min_module_version=None, min_python_version=None, warn_not_installed=None, warn_old_version=None, module_version_attr='__version__', module_version_attr_call_args=None, import_kwargs={}, catch=()): """ Import and return a module if it is installed. If the module is not installed, it returns None. A minimum version for the module can be given as the keyword argument min_module_version. This should be comparable against the module version. By default, module.__version__ is used to get the module version. To override this, set the module_version_attr keyword argument. If the attribute of the module to get the version should be called (e.g., module.version()), then set module_version_attr_call_args to the args such that module.module_version_attr(*module_version_attr_call_args) returns the module's version. If the module version is less than min_module_version using the Python < comparison, None will be returned, even if the module is installed. You can use this to keep from importing an incompatible older version of a module. You can also specify a minimum Python version by using the min_python_version keyword argument. This should be comparable against sys.version_info. If the keyword argument warn_not_installed is set to True, the function will emit a UserWarning when the module is not installed. If the keyword argument warn_old_version is set to True, the function will emit a UserWarning when the library is installed, but cannot be imported because of the min_module_version or min_python_version options. Note that because of the way warnings are handled, a warning will be emitted for each module only once. You can change the default warning behavior by overriding the values of WARN_NOT_INSTALLED and WARN_OLD_VERSION in sympy.external.importtools. By default, WARN_NOT_INSTALLED is False and WARN_OLD_VERSION is True. This function uses __import__() to import the module. To pass additional options to __import__(), use the import_kwargs keyword argument. For example, to import a submodule A.B, you must pass a nonempty fromlist option to __import__. See the docstring of __import__(). This catches ImportError to determine if the module is not installed. To catch additional errors, pass them as a tuple to the catch keyword argument. Examples ======== >>> from sympy.external import import_module >>> numpy = import_module('numpy') >>> numpy = import_module('numpy', min_python_version=(2, 7), ... warn_old_version=False) >>> numpy = import_module('numpy', min_module_version='1.5', ... warn_old_version=False) # numpy.__version__ is a string >>> # gmpy does not have __version__, but it does have gmpy.version() >>> gmpy = import_module('gmpy', min_module_version='1.14', ... module_version_attr='version', module_version_attr_call_args=(), ... warn_old_version=False) >>> # To import a submodule, you must pass a nonempty fromlist to >>> # __import__(). The values do not matter. >>> p3 = import_module('mpl_toolkits.mplot3d', ... import_kwargs={'fromlist':['something']}) >>> # matplotlib.pyplot can raise RuntimeError when the display cannot be opened >>> matplotlib = import_module('matplotlib', ... import_kwargs={'fromlist':['pyplot']}, catch=(RuntimeError,)) """ # keyword argument overrides default, and global variable overrides # keyword argument. warn_old_version = (WARN_OLD_VERSION if WARN_OLD_VERSION is not None else warn_old_version or True) warn_not_installed = (WARN_NOT_INSTALLED if WARN_NOT_INSTALLED is not None else warn_not_installed or False) import warnings # Check Python first so we don't waste time importing a module we can't use if min_python_version: if sys.version_info < min_python_version: if warn_old_version: warnings.warn("Python version is too old to use %s " "(%s or newer required)" % ( module, '.'.join(map(str, min_python_version))), UserWarning, stacklevel=2) return # PyPy 1.6 has rudimentary NumPy support and importing it produces errors, so skip it if module == 'numpy' and '__pypy__' in sys.builtin_module_names: return try: mod = __import__(module, **import_kwargs) ## there's something funny about imports with matplotlib and py3k. doing ## from matplotlib import collections ## gives python's stdlib collections module. explicitly re-importing ## the module fixes this. from_list = import_kwargs.get('fromlist', tuple()) for submod in from_list: if submod == 'collections' and mod.__name__ == 'matplotlib': __import__(module + '.' + submod) except ImportError: if warn_not_installed: warnings.warn("%s module is not installed" % module, UserWarning, stacklevel=2) return except catch as e: if warn_not_installed: warnings.warn( "%s module could not be used (%s)" % (module, repr(e)), stacklevel=2) return if min_module_version: modversion = getattr(mod, module_version_attr) if module_version_attr_call_args is not None: modversion = modversion(*module_version_attr_call_args) if version_tuple(modversion) < version_tuple(min_module_version): if warn_old_version: # Attempt to create a pretty string version of the version if isinstance(min_module_version, str): verstr = min_module_version elif isinstance(min_module_version, (tuple, list)): verstr = '.'.join(map(str, min_module_version)) else: # Either don't know what this is. Hopefully # it's something that has a nice str version, like an int. verstr = str(min_module_version) warnings.warn("%s version is too old to use " "(%s or newer required)" % (module, verstr), UserWarning, stacklevel=2) return return mod
6052b33909834221f1c9d00d059b18983fc7b7977a48d34236e296b25f4c7a9f
""" This module implements the Residue function and related tools for working with residues. """ from sympy import sympify from sympy.utilities.timeutils import timethis @timethis('residue') def residue(expr, x, x0): """ Finds the residue of ``expr`` at the point x=x0. The residue is defined as the coefficient of ``1/(x-x0)`` in the power series expansion about ``x=x0``. Examples ======== >>> from sympy import Symbol, residue, sin >>> x = Symbol("x") >>> residue(1/x, x, 0) 1 >>> residue(1/x**2, x, 0) 0 >>> residue(2/sin(x), x, 0) 2 This function is essential for the Residue Theorem [1]. References ========== .. [1] https://en.wikipedia.org/wiki/Residue_theorem """ # The current implementation uses series expansion to # calculate it. A more general implementation is explained in # the section 5.6 of the Bronstein's book {M. Bronstein: # Symbolic Integration I, Springer Verlag (2005)}. For purely # rational functions, the algorithm is much easier. See # sections 2.4, 2.5, and 2.7 (this section actually gives an # algorithm for computing any Laurent series coefficient for # a rational function). The theory in section 2.4 will help to # understand why the resultant works in the general algorithm. # For the definition of a resultant, see section 1.4 (and any # previous sections for more review). from sympy import collect, Mul, Order, S expr = sympify(expr) if x0 != 0: expr = expr.subs(x, x + x0) for n in (0, 1, 2, 4, 8, 16, 32): s = expr.nseries(x, n=n) if not s.has(Order) or s.getn() >= 0: break s = collect(s.removeO(), x) if s.is_Add: args = s.args else: args = [s] res = S.Zero for arg in args: c, m = arg.as_coeff_mul(x) m = Mul(*m) if not (m == 1 or m == x or (m.is_Pow and m.exp.is_Integer)): raise NotImplementedError('term of unexpected form: %s' % m) if m == 1/x: res += c return res
53483098a1f9c82b47ec3e2e86d7bd4c3d6aa081269889282730fbd0adcb6310
from sympy.core import S, sympify, Expr, Dummy from sympy.core import Add, Mul, expand_power_base, expand_log from sympy.core.cache import cacheit from sympy.core.compatibility import default_sort_key, is_sequence from sympy.core.containers import Tuple from sympy.sets.sets import Complement from sympy.utilities.iterables import uniq class Order(Expr): r""" Represents the limiting behavior of some function. Explanation =========== The order of a function characterizes the function based on the limiting behavior of the function as it goes to some limit. Only taking the limit point to be a number is currently supported. This is expressed in big O notation [1]_. The formal definition for the order of a function `g(x)` about a point `a` is such that `g(x) = O(f(x))` as `x \rightarrow a` if and only if for any `\delta > 0` there exists a `M > 0` such that `|g(x)| \leq M|f(x)|` for `|x-a| < \delta`. This is equivalent to `\lim_{x \rightarrow a} \sup |g(x)/f(x)| < \infty`. Let's illustrate it on the following example by taking the expansion of `\sin(x)` about 0: .. math :: \sin(x) = x - x^3/3! + O(x^5) where in this case `O(x^5) = x^5/5! - x^7/7! + \cdots`. By the definition of `O`, for any `\delta > 0` there is an `M` such that: .. math :: |x^5/5! - x^7/7! + ....| <= M|x^5| \text{ for } |x| < \delta or by the alternate definition: .. math :: \lim_{x \rightarrow 0} | (x^5/5! - x^7/7! + ....) / x^5| < \infty which surely is true, because .. math :: \lim_{x \rightarrow 0} | (x^5/5! - x^7/7! + ....) / x^5| = 1/5! As it is usually used, the order of a function can be intuitively thought of representing all terms of powers greater than the one specified. For example, `O(x^3)` corresponds to any terms proportional to `x^3, x^4,\ldots` and any higher power. For a polynomial, this leaves terms proportional to `x^2`, `x` and constants. Examples ======== >>> from sympy import O, oo, cos, pi >>> from sympy.abc import x, y >>> O(x + x**2) O(x) >>> O(x + x**2, (x, 0)) O(x) >>> O(x + x**2, (x, oo)) O(x**2, (x, oo)) >>> O(1 + x*y) O(1, x, y) >>> O(1 + x*y, (x, 0), (y, 0)) O(1, x, y) >>> O(1 + x*y, (x, oo), (y, oo)) O(x*y, (x, oo), (y, oo)) >>> O(1) in O(1, x) True >>> O(1, x) in O(1) False >>> O(x) in O(1, x) True >>> O(x**2) in O(x) True >>> O(x)*x O(x**2) >>> O(x) - O(x) O(x) >>> O(cos(x)) O(1) >>> O(cos(x), (x, pi/2)) O(x - pi/2, (x, pi/2)) References ========== .. [1] `Big O notation <https://en.wikipedia.org/wiki/Big_O_notation>`_ Notes ===== In ``O(f(x), x)`` the expression ``f(x)`` is assumed to have a leading term. ``O(f(x), x)`` is automatically transformed to ``O(f(x).as_leading_term(x),x)``. ``O(expr*f(x), x)`` is ``O(f(x), x)`` ``O(expr, x)`` is ``O(1)`` ``O(0, x)`` is 0. Multivariate O is also supported: ``O(f(x, y), x, y)`` is transformed to ``O(f(x, y).as_leading_term(x,y).as_leading_term(y), x, y)`` In the multivariate case, it is assumed the limits w.r.t. the various symbols commute. If no symbols are passed then all symbols in the expression are used and the limit point is assumed to be zero. """ is_Order = True __slots__ = () @cacheit def __new__(cls, expr, *args, **kwargs): expr = sympify(expr) if not args: if expr.is_Order: variables = expr.variables point = expr.point else: variables = list(expr.free_symbols) point = [S.Zero]*len(variables) else: args = list(args if is_sequence(args) else [args]) variables, point = [], [] if is_sequence(args[0]): for a in args: v, p = list(map(sympify, a)) variables.append(v) point.append(p) else: variables = list(map(sympify, args)) point = [S.Zero]*len(variables) if not all(v.is_symbol for v in variables): raise TypeError('Variables are not symbols, got %s' % variables) if len(list(uniq(variables))) != len(variables): raise ValueError('Variables are supposed to be unique symbols, got %s' % variables) if expr.is_Order: expr_vp = dict(expr.args[1:]) new_vp = dict(expr_vp) vp = dict(zip(variables, point)) for v, p in vp.items(): if v in new_vp.keys(): if p != new_vp[v]: raise NotImplementedError( "Mixing Order at different points is not supported.") else: new_vp[v] = p if set(expr_vp.keys()) == set(new_vp.keys()): return expr else: variables = list(new_vp.keys()) point = [new_vp[v] for v in variables] if expr is S.NaN: return S.NaN if any(x in p.free_symbols for x in variables for p in point): raise ValueError('Got %s as a point.' % point) if variables: if any(p != point[0] for p in point): raise NotImplementedError( "Multivariable orders at different points are not supported.") if point[0] is S.Infinity: s = {k: 1/Dummy() for k in variables} rs = {1/v: 1/k for k, v in s.items()} ps = [S.Zero for p in point] elif point[0] is S.NegativeInfinity: s = {k: -1/Dummy() for k in variables} rs = {-1/v: -1/k for k, v in s.items()} ps = [S.Zero for p in point] elif point[0] is not S.Zero: s = {k: Dummy() + point[0] for k in variables} rs = {(v - point[0]).together(): k - point[0] for k, v in s.items()} ps = [S.Zero for p in point] else: s = () rs = () ps = list(point) expr = expr.subs(s) if expr.is_Add: expr = expr.factor() if s: args = tuple([r[0] for r in rs.items()]) else: args = tuple(variables) if len(variables) > 1: # XXX: better way? We need this expand() to # workaround e.g: expr = x*(x + y). # (x*(x + y)).as_leading_term(x, y) currently returns # x*y (wrong order term!). That's why we want to deal with # expand()'ed expr (handled in "if expr.is_Add" branch below). expr = expr.expand() old_expr = None while old_expr != expr: old_expr = expr if expr.is_Add: lst = expr.extract_leading_order(args) expr = Add(*[f.expr for (e, f) in lst]) elif expr: from sympy import PoleError, Function try: expr = expr.as_leading_term(*args) except PoleError: if isinstance(expr, Function) or\ all(isinstance(arg, Function) for arg in expr.args): # It is not possible to simplify an expression # containing only functions (which raise error on # call to leading term) further pass else: orders = [] pts = tuple(zip(args, ps)) for arg in expr.args: try: lt = arg.as_leading_term(*args) except PoleError: lt = arg if lt not in args: order = Order(lt) else: order = Order(lt, *pts) orders.append(order) if expr.is_Add: new_expr = Order(Add(*orders), *pts) if new_expr.is_Add: new_expr = Order(Add(*[a.expr for a in new_expr.args]), *pts) expr = new_expr.expr elif expr.is_Mul: expr = Mul(*[a.expr for a in orders]) elif expr.is_Pow: expr = orders[0].expr**orders[1].expr expr = expr.as_independent(*args, as_Add=False)[1] expr = expand_power_base(expr) expr = expand_log(expr) if len(args) == 1: # The definition of O(f(x)) symbol explicitly stated that # the argument of f(x) is irrelevant. That's why we can # combine some power exponents (only "on top" of the # expression tree for f(x)), e.g.: # x**p * (-x)**q -> x**(p+q) for real p, q. x = args[0] margs = list(Mul.make_args( expr.as_independent(x, as_Add=False)[1])) for i, t in enumerate(margs): if t.is_Pow: b, q = t.args if b in (x, -x) and q.is_real and not q.has(x): margs[i] = x**q elif b.is_Pow and not b.exp.has(x): b, r = b.args if b in (x, -x) and r.is_real: margs[i] = x**(r*q) elif b.is_Mul and b.args[0] is S.NegativeOne: b = -b if b.is_Pow and not b.exp.has(x): b, r = b.args if b in (x, -x) and r.is_real: margs[i] = x**(r*q) expr = Mul(*margs) expr = expr.subs(rs) if expr.is_Order: expr = expr.expr if not expr.has(*variables) and not expr.is_zero: expr = S.One # create Order instance: vp = dict(zip(variables, point)) variables.sort(key=default_sort_key) point = [vp[v] for v in variables] args = (expr,) + Tuple(*zip(variables, point)) obj = Expr.__new__(cls, *args) return obj def _eval_nseries(self, x, n, logx, cdir=0): return self @property def expr(self): return self.args[0] @property def variables(self): if self.args[1:]: return tuple(x[0] for x in self.args[1:]) else: return () @property def point(self): if self.args[1:]: return tuple(x[1] for x in self.args[1:]) else: return () @property def free_symbols(self): return self.expr.free_symbols | set(self.variables) def _eval_power(b, e): if e.is_Number and e.is_nonnegative: return b.func(b.expr ** e, *b.args[1:]) if e == O(1): return b return def as_expr_variables(self, order_symbols): if order_symbols is None: order_symbols = self.args[1:] else: if (not all(o[1] == order_symbols[0][1] for o in order_symbols) and not all(p == self.point[0] for p in self.point)): # pragma: no cover raise NotImplementedError('Order at points other than 0 ' 'or oo not supported, got %s as a point.' % self.point) if order_symbols and order_symbols[0][1] != self.point[0]: raise NotImplementedError( "Multiplying Order at different points is not supported.") order_symbols = dict(order_symbols) for s, p in dict(self.args[1:]).items(): if s not in order_symbols.keys(): order_symbols[s] = p order_symbols = sorted(order_symbols.items(), key=lambda x: default_sort_key(x[0])) return self.expr, tuple(order_symbols) def removeO(self): return S.Zero def getO(self): return self @cacheit def contains(self, expr): r""" Return True if expr belongs to Order(self.expr, \*self.variables). Return False if self belongs to expr. Return None if the inclusion relation cannot be determined (e.g. when self and expr have different symbols). """ from sympy import powsimp if expr.is_zero: return True if expr is S.NaN: return False point = self.point[0] if self.point else S.Zero if expr.is_Order: if (any(p != point for p in expr.point) or any(p != point for p in self.point)): return None if expr.expr == self.expr: # O(1) + O(1), O(1) + O(1, x), etc. return all(x in self.args[1:] for x in expr.args[1:]) if expr.expr.is_Add: return all(self.contains(x) for x in expr.expr.args) if self.expr.is_Add and point.is_zero: return any(self.func(x, *self.args[1:]).contains(expr) for x in self.expr.args) if self.variables and expr.variables: common_symbols = tuple( [s for s in self.variables if s in expr.variables]) elif self.variables: common_symbols = self.variables else: common_symbols = expr.variables if not common_symbols: return None if (self.expr.is_Pow and len(self.variables) == 1 and self.variables == expr.variables): symbol = self.variables[0] other = expr.expr.as_independent(symbol, as_Add=False)[1] if (other.is_Pow and other.base == symbol and self.expr.base == symbol): if point.is_zero: rv = (self.expr.exp - other.exp).is_nonpositive if point.is_infinite: rv = (self.expr.exp - other.exp).is_nonnegative if rv is not None: return rv r = None ratio = self.expr/expr.expr ratio = powsimp(ratio, deep=True, combine='exp') for s in common_symbols: from sympy.series.limits import Limit l = Limit(ratio, s, point).doit(heuristics=False) if not isinstance(l, Limit): l = l != 0 else: l = None if r is None: r = l else: if r != l: return return r if self.expr.is_Pow and len(self.variables) == 1: symbol = self.variables[0] other = expr.as_independent(symbol, as_Add=False)[1] if (other.is_Pow and other.base == symbol and self.expr.base == symbol): if point.is_zero: rv = (self.expr.exp - other.exp).is_nonpositive if point.is_infinite: rv = (self.expr.exp - other.exp).is_nonnegative if rv is not None: return rv obj = self.func(expr, *self.args[1:]) return self.contains(obj) def __contains__(self, other): result = self.contains(other) if result is None: raise TypeError('contains did not evaluate to a bool') return result def _eval_subs(self, old, new): if old in self.variables: newexpr = self.expr.subs(old, new) i = self.variables.index(old) newvars = list(self.variables) newpt = list(self.point) if new.is_symbol: newvars[i] = new else: syms = new.free_symbols if len(syms) == 1 or old in syms: if old in syms: var = self.variables[i] else: var = syms.pop() # First, try to substitute self.point in the "new" # expr to see if this is a fixed point. # E.g. O(y).subs(y, sin(x)) point = new.subs(var, self.point[i]) if point != self.point[i]: from sympy.solvers.solveset import solveset d = Dummy() sol = solveset(old - new.subs(var, d), d) if isinstance(sol, Complement): e1 = sol.args[0] e2 = sol.args[1] sol = set(e1) - set(e2) res = [dict(zip((d, ), sol))] point = d.subs(res[0]).limit(old, self.point[i]) newvars[i] = var newpt[i] = point elif old not in syms: del newvars[i], newpt[i] if not syms and new == self.point[i]: newvars.extend(syms) newpt.extend([S.Zero]*len(syms)) else: return return Order(newexpr, *zip(newvars, newpt)) def _eval_conjugate(self): expr = self.expr._eval_conjugate() if expr is not None: return self.func(expr, *self.args[1:]) def _eval_derivative(self, x): return self.func(self.expr.diff(x), *self.args[1:]) or self def _eval_transpose(self): expr = self.expr._eval_transpose() if expr is not None: return self.func(expr, *self.args[1:]) def __neg__(self): return self O = Order
820822e4376be0970bd338e0c81d1c2333e62c72a7616e385a02bd767c99ce3a
from collections import defaultdict from sympy import SYMPY_DEBUG from sympy.core import expand_power_base, sympify, Add, S, Mul, Derivative, Pow, symbols, expand_mul from sympy.core.add import _unevaluated_Add from sympy.core.compatibility import iterable, ordered, default_sort_key from sympy.core.parameters import global_parameters from sympy.core.exprtools import Factors, gcd_terms from sympy.core.function import _mexpand from sympy.core.mul import _keep_coeff, _unevaluated_Mul from sympy.core.numbers import Rational, zoo, nan from sympy.functions import exp, sqrt, log from sympy.functions.elementary.complexes import Abs from sympy.polys import gcd from sympy.simplify.sqrtdenest import sqrtdenest def collect(expr, syms, func=None, evaluate=None, exact=False, distribute_order_term=True): """ Collect additive terms of an expression. Explanation =========== This function collects additive terms of an expression with respect to a list of expression up to powers with rational exponents. By the term symbol here are meant arbitrary expressions, which can contain powers, products, sums etc. In other words symbol is a pattern which will be searched for in the expression's terms. The input expression is not expanded by :func:`collect`, so user is expected to provide an expression in an appropriate form. This makes :func:`collect` more predictable as there is no magic happening behind the scenes. However, it is important to note, that powers of products are converted to products of powers using the :func:`~.expand_power_base` function. There are two possible types of output. First, if ``evaluate`` flag is set, this function will return an expression with collected terms or else it will return a dictionary with expressions up to rational powers as keys and collected coefficients as values. Examples ======== >>> from sympy import S, collect, expand, factor, Wild >>> from sympy.abc import a, b, c, x, y This function can collect symbolic coefficients in polynomials or rational expressions. It will manage to find all integer or rational powers of collection variable:: >>> collect(a*x**2 + b*x**2 + a*x - b*x + c, x) c + x**2*(a + b) + x*(a - b) The same result can be achieved in dictionary form:: >>> d = collect(a*x**2 + b*x**2 + a*x - b*x + c, x, evaluate=False) >>> d[x**2] a + b >>> d[x] a - b >>> d[S.One] c You can also work with multivariate polynomials. However, remember that this function is greedy so it will care only about a single symbol at time, in specification order:: >>> collect(x**2 + y*x**2 + x*y + y + a*y, [x, y]) x**2*(y + 1) + x*y + y*(a + 1) Also more complicated expressions can be used as patterns:: >>> from sympy import sin, log >>> collect(a*sin(2*x) + b*sin(2*x), sin(2*x)) (a + b)*sin(2*x) >>> collect(a*x*log(x) + b*(x*log(x)), x*log(x)) x*(a + b)*log(x) You can use wildcards in the pattern:: >>> w = Wild('w1') >>> collect(a*x**y - b*x**y, w**y) x**y*(a - b) It is also possible to work with symbolic powers, although it has more complicated behavior, because in this case power's base and symbolic part of the exponent are treated as a single symbol:: >>> collect(a*x**c + b*x**c, x) a*x**c + b*x**c >>> collect(a*x**c + b*x**c, x**c) x**c*(a + b) However if you incorporate rationals to the exponents, then you will get well known behavior:: >>> collect(a*x**(2*c) + b*x**(2*c), x**c) x**(2*c)*(a + b) Note also that all previously stated facts about :func:`collect` function apply to the exponential function, so you can get:: >>> from sympy import exp >>> collect(a*exp(2*x) + b*exp(2*x), exp(x)) (a + b)*exp(2*x) If you are interested only in collecting specific powers of some symbols then set ``exact`` flag in arguments:: >>> collect(a*x**7 + b*x**7, x, exact=True) a*x**7 + b*x**7 >>> collect(a*x**7 + b*x**7, x**7, exact=True) x**7*(a + b) You can also apply this function to differential equations, where derivatives of arbitrary order can be collected. Note that if you collect with respect to a function or a derivative of a function, all derivatives of that function will also be collected. Use ``exact=True`` to prevent this from happening:: >>> from sympy import Derivative as D, collect, Function >>> f = Function('f') (x) >>> collect(a*D(f,x) + b*D(f,x), D(f,x)) (a + b)*Derivative(f(x), x) >>> collect(a*D(D(f,x),x) + b*D(D(f,x),x), f) (a + b)*Derivative(f(x), (x, 2)) >>> collect(a*D(D(f,x),x) + b*D(D(f,x),x), D(f,x), exact=True) a*Derivative(f(x), (x, 2)) + b*Derivative(f(x), (x, 2)) >>> collect(a*D(f,x) + b*D(f,x) + a*f + b*f, f) (a + b)*f(x) + (a + b)*Derivative(f(x), x) Or you can even match both derivative order and exponent at the same time:: >>> collect(a*D(D(f,x),x)**2 + b*D(D(f,x),x)**2, D(f,x)) (a + b)*Derivative(f(x), (x, 2))**2 Finally, you can apply a function to each of the collected coefficients. For example you can factorize symbolic coefficients of polynomial:: >>> f = expand((x + a + 1)**3) >>> collect(f, x, factor) x**3 + 3*x**2*(a + 1) + 3*x*(a + 1)**2 + (a + 1)**3 .. note:: Arguments are expected to be in expanded form, so you might have to call :func:`~.expand` prior to calling this function. See Also ======== collect_const, collect_sqrt, rcollect """ from sympy.core.assumptions import assumptions from sympy.utilities.iterables import sift from sympy.core.symbol import Dummy, Wild expr = sympify(expr) syms = [sympify(i) for i in (syms if iterable(syms) else [syms])] # replace syms[i] if it is not x, -x or has Wild symbols cond = lambda x: x.is_Symbol or (-x).is_Symbol or bool( x.atoms(Wild)) _, nonsyms = sift(syms, cond, binary=True) if nonsyms: reps = dict(zip(nonsyms, [Dummy(**assumptions(i)) for i in nonsyms])) syms = [reps.get(s, s) for s in syms] rv = collect(expr.subs(reps), syms, func=func, evaluate=evaluate, exact=exact, distribute_order_term=distribute_order_term) urep = {v: k for k, v in reps.items()} if not isinstance(rv, dict): return rv.xreplace(urep) else: return {urep.get(k, k).xreplace(urep): v.xreplace(urep) for k, v in rv.items()} if evaluate is None: evaluate = global_parameters.evaluate def make_expression(terms): product = [] for term, rat, sym, deriv in terms: if deriv is not None: var, order = deriv while order > 0: term, order = Derivative(term, var), order - 1 if sym is None: if rat is S.One: product.append(term) else: product.append(Pow(term, rat)) else: product.append(Pow(term, rat*sym)) return Mul(*product) def parse_derivative(deriv): # scan derivatives tower in the input expression and return # underlying function and maximal differentiation order expr, sym, order = deriv.expr, deriv.variables[0], 1 for s in deriv.variables[1:]: if s == sym: order += 1 else: raise NotImplementedError( 'Improve MV Derivative support in collect') while isinstance(expr, Derivative): s0 = expr.variables[0] for s in expr.variables: if s != s0: raise NotImplementedError( 'Improve MV Derivative support in collect') if s0 == sym: expr, order = expr.expr, order + len(expr.variables) else: break return expr, (sym, Rational(order)) def parse_term(expr): """Parses expression expr and outputs tuple (sexpr, rat_expo, sym_expo, deriv) where: - sexpr is the base expression - rat_expo is the rational exponent that sexpr is raised to - sym_expo is the symbolic exponent that sexpr is raised to - deriv contains the derivatives the the expression For example, the output of x would be (x, 1, None, None) the output of 2**x would be (2, 1, x, None). """ rat_expo, sym_expo = S.One, None sexpr, deriv = expr, None if expr.is_Pow: if isinstance(expr.base, Derivative): sexpr, deriv = parse_derivative(expr.base) else: sexpr = expr.base if expr.base == S.Exp1: arg = expr.exp if arg.is_Rational: sexpr, rat_expo = S.Exp1, arg elif arg.is_Mul: coeff, tail = arg.as_coeff_Mul(rational=True) sexpr, rat_expo = exp(tail), coeff elif expr.exp.is_Number: rat_expo = expr.exp else: coeff, tail = expr.exp.as_coeff_Mul() if coeff.is_Number: rat_expo, sym_expo = coeff, tail else: sym_expo = expr.exp elif isinstance(expr, exp): arg = expr.exp if arg.is_Rational: sexpr, rat_expo = S.Exp1, arg elif arg.is_Mul: coeff, tail = arg.as_coeff_Mul(rational=True) sexpr, rat_expo = exp(tail), coeff elif isinstance(expr, Derivative): sexpr, deriv = parse_derivative(expr) return sexpr, rat_expo, sym_expo, deriv def parse_expression(terms, pattern): """Parse terms searching for a pattern. Terms is a list of tuples as returned by parse_terms; Pattern is an expression treated as a product of factors. """ pattern = Mul.make_args(pattern) if len(terms) < len(pattern): # pattern is longer than matched product # so no chance for positive parsing result return None else: pattern = [parse_term(elem) for elem in pattern] terms = terms[:] # need a copy elems, common_expo, has_deriv = [], None, False for elem, e_rat, e_sym, e_ord in pattern: if elem.is_Number and e_rat == 1 and e_sym is None: # a constant is a match for everything continue for j in range(len(terms)): if terms[j] is None: continue term, t_rat, t_sym, t_ord = terms[j] # keeping track of whether one of the terms had # a derivative or not as this will require rebuilding # the expression later if t_ord is not None: has_deriv = True if (term.match(elem) is not None and (t_sym == e_sym or t_sym is not None and e_sym is not None and t_sym.match(e_sym) is not None)): if exact is False: # we don't have to be exact so find common exponent # for both expression's term and pattern's element expo = t_rat / e_rat if common_expo is None: # first time common_expo = expo else: # common exponent was negotiated before so # there is no chance for a pattern match unless # common and current exponents are equal if common_expo != expo: common_expo = 1 else: # we ought to be exact so all fields of # interest must match in every details if e_rat != t_rat or e_ord != t_ord: continue # found common term so remove it from the expression # and try to match next element in the pattern elems.append(terms[j]) terms[j] = None break else: # pattern element not found return None return [_f for _f in terms if _f], elems, common_expo, has_deriv if evaluate: if expr.is_Add: o = expr.getO() or 0 expr = expr.func(*[ collect(a, syms, func, True, exact, distribute_order_term) for a in expr.args if a != o]) + o elif expr.is_Mul: return expr.func(*[ collect(term, syms, func, True, exact, distribute_order_term) for term in expr.args]) elif expr.is_Pow: b = collect( expr.base, syms, func, True, exact, distribute_order_term) return Pow(b, expr.exp) syms = [expand_power_base(i, deep=False) for i in syms] order_term = None if distribute_order_term: order_term = expr.getO() if order_term is not None: if order_term.has(*syms): order_term = None else: expr = expr.removeO() summa = [expand_power_base(i, deep=False) for i in Add.make_args(expr)] collected, disliked = defaultdict(list), S.Zero for product in summa: c, nc = product.args_cnc(split_1=False) args = list(ordered(c)) + nc terms = [parse_term(i) for i in args] small_first = True for symbol in syms: if SYMPY_DEBUG: print("DEBUG: parsing of expression %s with symbol %s " % ( str(terms), str(symbol)) ) if isinstance(symbol, Derivative) and small_first: terms = list(reversed(terms)) small_first = not small_first result = parse_expression(terms, symbol) if SYMPY_DEBUG: print("DEBUG: returned %s" % str(result)) if result is not None: if not symbol.is_commutative: raise AttributeError("Can not collect noncommutative symbol") terms, elems, common_expo, has_deriv = result # when there was derivative in current pattern we # will need to rebuild its expression from scratch if not has_deriv: margs = [] for elem in elems: if elem[2] is None: e = elem[1] else: e = elem[1]*elem[2] margs.append(Pow(elem[0], e)) index = Mul(*margs) else: index = make_expression(elems) terms = expand_power_base(make_expression(terms), deep=False) index = expand_power_base(index, deep=False) collected[index].append(terms) break else: # none of the patterns matched disliked += product # add terms now for each key collected = {k: Add(*v) for k, v in collected.items()} if disliked is not S.Zero: collected[S.One] = disliked if order_term is not None: for key, val in collected.items(): collected[key] = val + order_term if func is not None: collected = { key: func(val) for key, val in collected.items()} if evaluate: return Add(*[key*val for key, val in collected.items()]) else: return collected def rcollect(expr, *vars): """ Recursively collect sums in an expression. Examples ======== >>> from sympy.simplify import rcollect >>> from sympy.abc import x, y >>> expr = (x**2*y + x*y + x + y)/(x + y) >>> rcollect(expr, y) (x + y*(x**2 + x + 1))/(x + y) See Also ======== collect, collect_const, collect_sqrt """ if expr.is_Atom or not expr.has(*vars): return expr else: expr = expr.__class__(*[rcollect(arg, *vars) for arg in expr.args]) if expr.is_Add: return collect(expr, vars) else: return expr def collect_sqrt(expr, evaluate=None): """Return expr with terms having common square roots collected together. If ``evaluate`` is False a count indicating the number of sqrt-containing terms will be returned and, if non-zero, the terms of the Add will be returned, else the expression itself will be returned as a single term. If ``evaluate`` is True, the expression with any collected terms will be returned. Note: since I = sqrt(-1), it is collected, too. Examples ======== >>> from sympy import sqrt >>> from sympy.simplify.radsimp import collect_sqrt >>> from sympy.abc import a, b >>> r2, r3, r5 = [sqrt(i) for i in [2, 3, 5]] >>> collect_sqrt(a*r2 + b*r2) sqrt(2)*(a + b) >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r3) sqrt(2)*(a + b) + sqrt(3)*(a + b) >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r5) sqrt(3)*a + sqrt(5)*b + sqrt(2)*(a + b) If evaluate is False then the arguments will be sorted and returned as a list and a count of the number of sqrt-containing terms will be returned: >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r5, evaluate=False) ((sqrt(3)*a, sqrt(5)*b, sqrt(2)*(a + b)), 3) >>> collect_sqrt(a*sqrt(2) + b, evaluate=False) ((b, sqrt(2)*a), 1) >>> collect_sqrt(a + b, evaluate=False) ((a + b,), 0) See Also ======== collect, collect_const, rcollect """ if evaluate is None: evaluate = global_parameters.evaluate # this step will help to standardize any complex arguments # of sqrts coeff, expr = expr.as_content_primitive() vars = set() for a in Add.make_args(expr): for m in a.args_cnc()[0]: if m.is_number and ( m.is_Pow and m.exp.is_Rational and m.exp.q == 2 or m is S.ImaginaryUnit): vars.add(m) # we only want radicals, so exclude Number handling; in this case # d will be evaluated d = collect_const(expr, *vars, Numbers=False) hit = expr != d if not evaluate: nrad = 0 # make the evaluated args canonical args = list(ordered(Add.make_args(d))) for i, m in enumerate(args): c, nc = m.args_cnc() for ci in c: # XXX should this be restricted to ci.is_number as above? if ci.is_Pow and ci.exp.is_Rational and ci.exp.q == 2 or \ ci is S.ImaginaryUnit: nrad += 1 break args[i] *= coeff if not (hit or nrad): args = [Add(*args)] return tuple(args), nrad return coeff*d def collect_abs(expr): """Return ``expr`` with arguments of multiple Abs in a term collected under a single instance. Examples ======== >>> from sympy.simplify.radsimp import collect_abs >>> from sympy.abc import x >>> collect_abs(abs(x + 1)/abs(x**2 - 1)) Abs((x + 1)/(x**2 - 1)) >>> collect_abs(abs(1/x)) Abs(1/x) """ def _abs(mul): from sympy.core.mul import _mulsort c, nc = mul.args_cnc() a = [] o = [] for i in c: if isinstance(i, Abs): a.append(i.args[0]) elif isinstance(i, Pow) and isinstance(i.base, Abs) and i.exp.is_real: a.append(i.base.args[0]**i.exp) else: o.append(i) if len(a) < 2 and not any(i.exp.is_negative for i in a if isinstance(i, Pow)): return mul absarg = Mul(*a) A = Abs(absarg) args = [A] args.extend(o) if not A.has(Abs): args.extend(nc) return Mul(*args) if not isinstance(A, Abs): # reevaluate and make it unevaluated A = Abs(absarg, evaluate=False) args[0] = A _mulsort(args) args.extend(nc) # nc always go last return Mul._from_args(args, is_commutative=not nc) return expr.replace( lambda x: isinstance(x, Mul), lambda x: _abs(x)).replace( lambda x: isinstance(x, Pow), lambda x: _abs(x)) def collect_const(expr, *vars, Numbers=True): """A non-greedy collection of terms with similar number coefficients in an Add expr. If ``vars`` is given then only those constants will be targeted. Although any Number can also be targeted, if this is not desired set ``Numbers=False`` and no Float or Rational will be collected. Parameters ========== expr : sympy expression This parameter defines the expression the expression from which terms with similar coefficients are to be collected. A non-Add expression is returned as it is. vars : variable length collection of Numbers, optional Specifies the constants to target for collection. Can be multiple in number. Numbers : bool Specifies to target all instance of :class:`sympy.core.numbers.Number` class. If ``Numbers=False``, then no Float or Rational will be collected. Returns ======= expr : Expr Returns an expression with similar coefficient terms collected. Examples ======== >>> from sympy import sqrt >>> from sympy.abc import s, x, y, z >>> from sympy.simplify.radsimp import collect_const >>> collect_const(sqrt(3) + sqrt(3)*(1 + sqrt(2))) sqrt(3)*(sqrt(2) + 2) >>> collect_const(sqrt(3)*s + sqrt(7)*s + sqrt(3) + sqrt(7)) (sqrt(3) + sqrt(7))*(s + 1) >>> s = sqrt(2) + 2 >>> collect_const(sqrt(3)*s + sqrt(3) + sqrt(7)*s + sqrt(7)) (sqrt(2) + 3)*(sqrt(3) + sqrt(7)) >>> collect_const(sqrt(3)*s + sqrt(3) + sqrt(7)*s + sqrt(7), sqrt(3)) sqrt(7) + sqrt(3)*(sqrt(2) + 3) + sqrt(7)*(sqrt(2) + 2) The collection is sign-sensitive, giving higher precedence to the unsigned values: >>> collect_const(x - y - z) x - (y + z) >>> collect_const(-y - z) -(y + z) >>> collect_const(2*x - 2*y - 2*z, 2) 2*(x - y - z) >>> collect_const(2*x - 2*y - 2*z, -2) 2*x - 2*(y + z) See Also ======== collect, collect_sqrt, rcollect """ if not expr.is_Add: return expr recurse = False if not vars: recurse = True vars = set() for a in expr.args: for m in Mul.make_args(a): if m.is_number: vars.add(m) else: vars = sympify(vars) if not Numbers: vars = [v for v in vars if not v.is_Number] vars = list(ordered(vars)) for v in vars: terms = defaultdict(list) Fv = Factors(v) for m in Add.make_args(expr): f = Factors(m) q, r = f.div(Fv) if r.is_one: # only accept this as a true factor if # it didn't change an exponent from an Integer # to a non-Integer, e.g. 2/sqrt(2) -> sqrt(2) # -- we aren't looking for this sort of change fwas = f.factors.copy() fnow = q.factors if not any(k in fwas and fwas[k].is_Integer and not fnow[k].is_Integer for k in fnow): terms[v].append(q.as_expr()) continue terms[S.One].append(m) args = [] hit = False uneval = False for k in ordered(terms): v = terms[k] if k is S.One: args.extend(v) continue if len(v) > 1: v = Add(*v) hit = True if recurse and v != expr: vars.append(v) else: v = v[0] # be careful not to let uneval become True unless # it must be because it's going to be more expensive # to rebuild the expression as an unevaluated one if Numbers and k.is_Number and v.is_Add: args.append(_keep_coeff(k, v, sign=True)) uneval = True else: args.append(k*v) if hit: if uneval: expr = _unevaluated_Add(*args) else: expr = Add(*args) if not expr.is_Add: break return expr def radsimp(expr, symbolic=True, max_terms=4): r""" Rationalize the denominator by removing square roots. Explanation =========== The expression returned from radsimp must be used with caution since if the denominator contains symbols, it will be possible to make substitutions that violate the assumptions of the simplification process: that for a denominator matching a + b*sqrt(c), a != +/-b*sqrt(c). (If there are no symbols, this assumptions is made valid by collecting terms of sqrt(c) so the match variable ``a`` does not contain ``sqrt(c)``.) If you do not want the simplification to occur for symbolic denominators, set ``symbolic`` to False. If there are more than ``max_terms`` radical terms then the expression is returned unchanged. Examples ======== >>> from sympy import radsimp, sqrt, Symbol, pprint >>> from sympy import factor_terms, fraction, signsimp >>> from sympy.simplify.radsimp import collect_sqrt >>> from sympy.abc import a, b, c >>> radsimp(1/(2 + sqrt(2))) (2 - sqrt(2))/2 >>> x,y = map(Symbol, 'xy') >>> e = ((2 + 2*sqrt(2))*x + (2 + sqrt(8))*y)/(2 + sqrt(2)) >>> radsimp(e) sqrt(2)*(x + y) No simplification beyond removal of the gcd is done. One might want to polish the result a little, however, by collecting square root terms: >>> r2 = sqrt(2) >>> r5 = sqrt(5) >>> ans = radsimp(1/(y*r2 + x*r2 + a*r5 + b*r5)); pprint(ans) ___ ___ ___ ___ \/ 5 *a + \/ 5 *b - \/ 2 *x - \/ 2 *y ------------------------------------------ 2 2 2 2 5*a + 10*a*b + 5*b - 2*x - 4*x*y - 2*y >>> n, d = fraction(ans) >>> pprint(factor_terms(signsimp(collect_sqrt(n))/d, radical=True)) ___ ___ \/ 5 *(a + b) - \/ 2 *(x + y) ------------------------------------------ 2 2 2 2 5*a + 10*a*b + 5*b - 2*x - 4*x*y - 2*y If radicals in the denominator cannot be removed or there is no denominator, the original expression will be returned. >>> radsimp(sqrt(2)*x + sqrt(2)) sqrt(2)*x + sqrt(2) Results with symbols will not always be valid for all substitutions: >>> eq = 1/(a + b*sqrt(c)) >>> eq.subs(a, b*sqrt(c)) 1/(2*b*sqrt(c)) >>> radsimp(eq).subs(a, b*sqrt(c)) nan If ``symbolic=False``, symbolic denominators will not be transformed (but numeric denominators will still be processed): >>> radsimp(eq, symbolic=False) 1/(a + b*sqrt(c)) """ from sympy.simplify.simplify import signsimp syms = symbols("a:d A:D") def _num(rterms): # return the multiplier that will simplify the expression described # by rterms [(sqrt arg, coeff), ... ] a, b, c, d, A, B, C, D = syms if len(rterms) == 2: reps = dict(list(zip([A, a, B, b], [j for i in rterms for j in i]))) return ( sqrt(A)*a - sqrt(B)*b).xreplace(reps) if len(rterms) == 3: reps = dict(list(zip([A, a, B, b, C, c], [j for i in rterms for j in i]))) return ( (sqrt(A)*a + sqrt(B)*b - sqrt(C)*c)*(2*sqrt(A)*sqrt(B)*a*b - A*a**2 - B*b**2 + C*c**2)).xreplace(reps) elif len(rterms) == 4: reps = dict(list(zip([A, a, B, b, C, c, D, d], [j for i in rterms for j in i]))) return ((sqrt(A)*a + sqrt(B)*b - sqrt(C)*c - sqrt(D)*d)*(2*sqrt(A)*sqrt(B)*a*b - A*a**2 - B*b**2 - 2*sqrt(C)*sqrt(D)*c*d + C*c**2 + D*d**2)*(-8*sqrt(A)*sqrt(B)*sqrt(C)*sqrt(D)*a*b*c*d + A**2*a**4 - 2*A*B*a**2*b**2 - 2*A*C*a**2*c**2 - 2*A*D*a**2*d**2 + B**2*b**4 - 2*B*C*b**2*c**2 - 2*B*D*b**2*d**2 + C**2*c**4 - 2*C*D*c**2*d**2 + D**2*d**4)).xreplace(reps) elif len(rterms) == 1: return sqrt(rterms[0][0]) else: raise NotImplementedError def ispow2(d, log2=False): if not d.is_Pow: return False e = d.exp if e.is_Rational and e.q == 2 or symbolic and denom(e) == 2: return True if log2: q = 1 if e.is_Rational: q = e.q elif symbolic: d = denom(e) if d.is_Integer: q = d if q != 1 and log(q, 2).is_Integer: return True return False def handle(expr): # Handle first reduces to the case # expr = 1/d, where d is an add, or d is base**p/2. # We do this by recursively calling handle on each piece. from sympy.simplify.simplify import nsimplify n, d = fraction(expr) if expr.is_Atom or (d.is_Atom and n.is_Atom): return expr elif not n.is_Atom: n = n.func(*[handle(a) for a in n.args]) return _unevaluated_Mul(n, handle(1/d)) elif n is not S.One: return _unevaluated_Mul(n, handle(1/d)) elif d.is_Mul: return _unevaluated_Mul(*[handle(1/d) for d in d.args]) # By this step, expr is 1/d, and d is not a mul. if not symbolic and d.free_symbols: return expr if ispow2(d): d2 = sqrtdenest(sqrt(d.base))**numer(d.exp) if d2 != d: return handle(1/d2) elif d.is_Pow and (d.exp.is_integer or d.base.is_positive): # (1/d**i) = (1/d)**i return handle(1/d.base)**d.exp if not (d.is_Add or ispow2(d)): return 1/d.func(*[handle(a) for a in d.args]) # handle 1/d treating d as an Add (though it may not be) keep = True # keep changes that are made # flatten it and collect radicals after checking for special # conditions d = _mexpand(d) # did it change? if d.is_Atom: return 1/d # is it a number that might be handled easily? if d.is_number: _d = nsimplify(d) if _d.is_Number and _d.equals(d): return 1/_d while True: # collect similar terms collected = defaultdict(list) for m in Add.make_args(d): # d might have become non-Add p2 = [] other = [] for i in Mul.make_args(m): if ispow2(i, log2=True): p2.append(i.base if i.exp is S.Half else i.base**(2*i.exp)) elif i is S.ImaginaryUnit: p2.append(S.NegativeOne) else: other.append(i) collected[tuple(ordered(p2))].append(Mul(*other)) rterms = list(ordered(list(collected.items()))) rterms = [(Mul(*i), Add(*j)) for i, j in rterms] nrad = len(rterms) - (1 if rterms[0][0] is S.One else 0) if nrad < 1: break elif nrad > max_terms: # there may have been invalid operations leading to this point # so don't keep changes, e.g. this expression is troublesome # in collecting terms so as not to raise the issue of 2834: # r = sqrt(sqrt(5) + 5) # eq = 1/(sqrt(5)*r + 2*sqrt(5)*sqrt(-sqrt(5) + 5) + 5*r) keep = False break if len(rterms) > 4: # in general, only 4 terms can be removed with repeated squaring # but other considerations can guide selection of radical terms # so that radicals are removed if all(x.is_Integer and (y**2).is_Rational for x, y in rterms): nd, d = rad_rationalize(S.One, Add._from_args( [sqrt(x)*y for x, y in rterms])) n *= nd else: # is there anything else that might be attempted? keep = False break from sympy.simplify.powsimp import powsimp, powdenest num = powsimp(_num(rterms)) n *= num d *= num d = powdenest(_mexpand(d), force=symbolic) if d.has(S.Zero, nan, zoo): return expr if d.is_Atom: break if not keep: return expr return _unevaluated_Mul(n, 1/d) coeff, expr = expr.as_coeff_Add() expr = expr.normal() old = fraction(expr) n, d = fraction(handle(expr)) if old != (n, d): if not d.is_Atom: was = (n, d) n = signsimp(n, evaluate=False) d = signsimp(d, evaluate=False) u = Factors(_unevaluated_Mul(n, 1/d)) u = _unevaluated_Mul(*[k**v for k, v in u.factors.items()]) n, d = fraction(u) if old == (n, d): n, d = was n = expand_mul(n) if d.is_Number or d.is_Add: n2, d2 = fraction(gcd_terms(_unevaluated_Mul(n, 1/d))) if d2.is_Number or (d2.count_ops() <= d.count_ops()): n, d = [signsimp(i) for i in (n2, d2)] if n.is_Mul and n.args[0].is_Number: n = n.func(*n.args) return coeff + _unevaluated_Mul(n, 1/d) def rad_rationalize(num, den): """ Rationalize ``num/den`` by removing square roots in the denominator; num and den are sum of terms whose squares are positive rationals. Examples ======== >>> from sympy import sqrt >>> from sympy.simplify.radsimp import rad_rationalize >>> rad_rationalize(sqrt(3), 1 + sqrt(2)/3) (-sqrt(3) + sqrt(6)/3, -7/9) """ if not den.is_Add: return num, den g, a, b = split_surds(den) a = a*sqrt(g) num = _mexpand((a - b)*num) den = _mexpand(a**2 - b**2) return rad_rationalize(num, den) def fraction(expr, exact=False): """Returns a pair with expression's numerator and denominator. If the given expression is not a fraction then this function will return the tuple (expr, 1). This function will not make any attempt to simplify nested fractions or to do any term rewriting at all. If only one of the numerator/denominator pair is needed then use numer(expr) or denom(expr) functions respectively. >>> from sympy import fraction, Rational, Symbol >>> from sympy.abc import x, y >>> fraction(x/y) (x, y) >>> fraction(x) (x, 1) >>> fraction(1/y**2) (1, y**2) >>> fraction(x*y/2) (x*y, 2) >>> fraction(Rational(1, 2)) (1, 2) This function will also work fine with assumptions: >>> k = Symbol('k', negative=True) >>> fraction(x * y**k) (x, y**(-k)) If we know nothing about sign of some exponent and ``exact`` flag is unset, then structure this exponent's structure will be analyzed and pretty fraction will be returned: >>> from sympy import exp, Mul >>> fraction(2*x**(-y)) (2, x**y) >>> fraction(exp(-x)) (1, exp(x)) >>> fraction(exp(-x), exact=True) (exp(-x), 1) The ``exact`` flag will also keep any unevaluated Muls from being evaluated: >>> u = Mul(2, x + 1, evaluate=False) >>> fraction(u) (2*x + 2, 1) >>> fraction(u, exact=True) (2*(x + 1), 1) """ expr = sympify(expr) numer, denom = [], [] for term in Mul.make_args(expr): if term.is_commutative and (term.is_Pow or isinstance(term, exp)): b, ex = term.as_base_exp() if ex.is_negative: if ex is S.NegativeOne: denom.append(b) elif exact: if ex.is_constant(): denom.append(Pow(b, -ex)) else: numer.append(term) else: denom.append(Pow(b, -ex)) elif ex.is_positive: numer.append(term) elif not exact and ex.is_Mul: n, d = term.as_numer_denom() if n != 1: numer.append(n) denom.append(d) else: numer.append(term) elif term.is_Rational and not term.is_Integer: if term.p != 1: numer.append(term.p) denom.append(term.q) else: numer.append(term) return Mul(*numer, evaluate=not exact), Mul(*denom, evaluate=not exact) def numer(expr): return fraction(expr)[0] def denom(expr): return fraction(expr)[1] def fraction_expand(expr, **hints): return expr.expand(frac=True, **hints) def numer_expand(expr, **hints): a, b = fraction(expr) return a.expand(numer=True, **hints) / b def denom_expand(expr, **hints): a, b = fraction(expr) return a / b.expand(denom=True, **hints) expand_numer = numer_expand expand_denom = denom_expand expand_fraction = fraction_expand def split_surds(expr): """ Split an expression with terms whose squares are positive rationals into a sum of terms whose surds squared have gcd equal to g and a sum of terms with surds squared prime with g. Examples ======== >>> from sympy import sqrt >>> from sympy.simplify.radsimp import split_surds >>> split_surds(3*sqrt(3) + sqrt(5)/7 + sqrt(6) + sqrt(10) + sqrt(15)) (3, sqrt(2) + sqrt(5) + 3, sqrt(5)/7 + sqrt(10)) """ args = sorted(expr.args, key=default_sort_key) coeff_muls = [x.as_coeff_Mul() for x in args] surds = [x[1]**2 for x in coeff_muls if x[1].is_Pow] surds.sort(key=default_sort_key) g, b1, b2 = _split_gcd(*surds) g2 = g if not b2 and len(b1) >= 2: b1n = [x/g for x in b1] b1n = [x for x in b1n if x != 1] # only a common factor has been factored; split again g1, b1n, b2 = _split_gcd(*b1n) g2 = g*g1 a1v, a2v = [], [] for c, s in coeff_muls: if s.is_Pow and s.exp == S.Half: s1 = s.base if s1 in b1: a1v.append(c*sqrt(s1/g2)) else: a2v.append(c*s) else: a2v.append(c*s) a = Add(*a1v) b = Add(*a2v) return g2, a, b def _split_gcd(*a): """ Split the list of integers ``a`` into a list of integers, ``a1`` having ``g = gcd(a1)``, and a list ``a2`` whose elements are not divisible by ``g``. Returns ``g, a1, a2``. Examples ======== >>> from sympy.simplify.radsimp import _split_gcd >>> _split_gcd(55, 35, 22, 14, 77, 10) (5, [55, 35, 10], [22, 14, 77]) """ g = a[0] b1 = [g] b2 = [] for x in a[1:]: g1 = gcd(g, x) if g1 == 1: b2.append(x) else: g = g1 b1.append(x) return g, b1, b2
4bb6c27bb69d22b53d0144593b5ce7f89cf9fcc368908957fea281efa1a85073
from itertools import combinations_with_replacement from sympy.core import symbols, Add, Dummy from sympy.core.numbers import Rational from sympy.polys import cancel, ComputationFailed, parallel_poly_from_expr, reduced, Poly from sympy.polys.monomials import Monomial, monomial_div from sympy.polys.polyerrors import DomainError, PolificationFailed from sympy.utilities.misc import debug def ratsimp(expr): """ Put an expression over a common denominator, cancel and reduce. Examples ======== >>> from sympy import ratsimp >>> from sympy.abc import x, y >>> ratsimp(1/x + 1/y) (x + y)/(x*y) """ f, g = cancel(expr).as_numer_denom() try: Q, r = reduced(f, [g], field=True, expand=False) except ComputationFailed: return f/g return Add(*Q) + cancel(r/g) def ratsimpmodprime(expr, G, *gens, quick=True, polynomial=False, **args): """ Simplifies a rational expression ``expr`` modulo the prime ideal generated by ``G``. ``G`` should be a Groebner basis of the ideal. Examples ======== >>> from sympy.simplify.ratsimp import ratsimpmodprime >>> from sympy.abc import x, y >>> eq = (x + y**5 + y)/(x - y) >>> ratsimpmodprime(eq, [x*y**5 - x - y], x, y, order='lex') (-x**2 - x*y - x - y)/(-x**2 + x*y) If ``polynomial`` is ``False``, the algorithm computes a rational simplification which minimizes the sum of the total degrees of the numerator and the denominator. If ``polynomial`` is ``True``, this function just brings numerator and denominator into a canonical form. This is much faster, but has potentially worse results. References ========== .. [1] M. Monagan, R. Pearce, Rational Simplification Modulo a Polynomial Ideal, http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.163.6984 (specifically, the second algorithm) """ from sympy import solve debug('ratsimpmodprime', expr) # usual preparation of polynomials: num, denom = cancel(expr).as_numer_denom() try: polys, opt = parallel_poly_from_expr([num, denom] + G, *gens, **args) except PolificationFailed: return expr domain = opt.domain if domain.has_assoc_Field: opt.domain = domain.get_field() else: raise DomainError( "can't compute rational simplification over %s" % domain) # compute only once leading_monomials = [g.LM(opt.order) for g in polys[2:]] tested = set() def staircase(n): """ Compute all monomials with degree less than ``n`` that are not divisible by any element of ``leading_monomials``. """ if n == 0: return [1] S = [] for mi in combinations_with_replacement(range(len(opt.gens)), n): m = [0]*len(opt.gens) for i in mi: m[i] += 1 if all(monomial_div(m, lmg) is None for lmg in leading_monomials): S.append(m) return [Monomial(s).as_expr(*opt.gens) for s in S] + staircase(n - 1) def _ratsimpmodprime(a, b, allsol, N=0, D=0): r""" Computes a rational simplification of ``a/b`` which minimizes the sum of the total degrees of the numerator and the denominator. Explanation =========== The algorithm proceeds by looking at ``a * d - b * c`` modulo the ideal generated by ``G`` for some ``c`` and ``d`` with degree less than ``a`` and ``b`` respectively. The coefficients of ``c`` and ``d`` are indeterminates and thus the coefficients of the normalform of ``a * d - b * c`` are linear polynomials in these indeterminates. If these linear polynomials, considered as system of equations, have a nontrivial solution, then `\frac{a}{b} \equiv \frac{c}{d}` modulo the ideal generated by ``G``. So, by construction, the degree of ``c`` and ``d`` is less than the degree of ``a`` and ``b``, so a simpler representation has been found. After a simpler representation has been found, the algorithm tries to reduce the degree of the numerator and denominator and returns the result afterwards. As an extension, if quick=False, we look at all possible degrees such that the total degree is less than *or equal to* the best current solution. We retain a list of all solutions of minimal degree, and try to find the best one at the end. """ c, d = a, b steps = 0 maxdeg = a.total_degree() + b.total_degree() if quick: bound = maxdeg - 1 else: bound = maxdeg while N + D <= bound: if (N, D) in tested: break tested.add((N, D)) M1 = staircase(N) M2 = staircase(D) debug('%s / %s: %s, %s' % (N, D, M1, M2)) Cs = symbols("c:%d" % len(M1), cls=Dummy) Ds = symbols("d:%d" % len(M2), cls=Dummy) ng = Cs + Ds c_hat = Poly( sum([Cs[i] * M1[i] for i in range(len(M1))]), opt.gens + ng) d_hat = Poly( sum([Ds[i] * M2[i] for i in range(len(M2))]), opt.gens + ng) r = reduced(a * d_hat - b * c_hat, G, opt.gens + ng, order=opt.order, polys=True)[1] S = Poly(r, gens=opt.gens).coeffs() sol = solve(S, Cs + Ds, particular=True, quick=True) if sol and not all(s == 0 for s in sol.values()): c = c_hat.subs(sol) d = d_hat.subs(sol) # The "free" variables occurring before as parameters # might still be in the substituted c, d, so set them # to the value chosen before: c = c.subs(dict(list(zip(Cs + Ds, [1] * (len(Cs) + len(Ds)))))) d = d.subs(dict(list(zip(Cs + Ds, [1] * (len(Cs) + len(Ds)))))) c = Poly(c, opt.gens) d = Poly(d, opt.gens) if d == 0: raise ValueError('Ideal not prime?') allsol.append((c_hat, d_hat, S, Cs + Ds)) if N + D != maxdeg: allsol = [allsol[-1]] break steps += 1 N += 1 D += 1 if steps > 0: c, d, allsol = _ratsimpmodprime(c, d, allsol, N, D - steps) c, d, allsol = _ratsimpmodprime(c, d, allsol, N - steps, D) return c, d, allsol # preprocessing. this improves performance a bit when deg(num) # and deg(denom) are large: num = reduced(num, G, opt.gens, order=opt.order)[1] denom = reduced(denom, G, opt.gens, order=opt.order)[1] if polynomial: return (num/denom).cancel() c, d, allsol = _ratsimpmodprime( Poly(num, opt.gens, domain=opt.domain), Poly(denom, opt.gens, domain=opt.domain), []) if not quick and allsol: debug('Looking for best minimal solution. Got: %s' % len(allsol)) newsol = [] for c_hat, d_hat, S, ng in allsol: sol = solve(S, ng, particular=True, quick=False) newsol.append((c_hat.subs(sol), d_hat.subs(sol))) c, d = min(newsol, key=lambda x: len(x[0].terms()) + len(x[1].terms())) if not domain.is_Field: cn, c = c.clear_denoms(convert=True) dn, d = d.clear_denoms(convert=True) r = Rational(cn, dn) else: r = Rational(1) return (c*r.q)/(d*r.p)
032a5198a23ce8977bb85d70dbe1a18c92569ed6b6a28bfccc67e2a07f1ea19b
r""" This module contains the functionality to arrange the nodes of a diagram on an abstract grid, and then to produce a graphical representation of the grid. The currently supported back-ends are Xy-pic [Xypic]. Layout Algorithm ================ This section provides an overview of the algorithms implemented in :class:`DiagramGrid` to lay out diagrams. The first step of the algorithm is the removal composite and identity morphisms which do not have properties in the supplied diagram. The premises and conclusions of the diagram are then merged. The generic layout algorithm begins with the construction of the "skeleton" of the diagram. The skeleton is an undirected graph which has the objects of the diagram as vertices and has an (undirected) edge between each pair of objects between which there exist morphisms. The direction of the morphisms does not matter at this stage. The skeleton also includes an edge between each pair of vertices `A` and `C` such that there exists an object `B` which is connected via a morphism to `A`, and via a morphism to `C`. The skeleton constructed in this way has the property that every object is a vertex of a triangle formed by three edges of the skeleton. This property lies at the base of the generic layout algorithm. After the skeleton has been constructed, the algorithm lists all triangles which can be formed. Note that some triangles will not have all edges corresponding to morphisms which will actually be drawn. Triangles which have only one edge or less which will actually be drawn are immediately discarded. The list of triangles is sorted according to the number of edges which correspond to morphisms, then the triangle with the least number of such edges is selected. One of such edges is picked and the corresponding objects are placed horizontally, on a grid. This edge is recorded to be in the fringe. The algorithm then finds a "welding" of a triangle to the fringe. A welding is an edge in the fringe where a triangle could be attached. If the algorithm succeeds in finding such a welding, it adds to the grid that vertex of the triangle which was not yet included in any edge in the fringe and records the two new edges in the fringe. This process continues iteratively until all objects of the diagram has been placed or until no more weldings can be found. An edge is only removed from the fringe when a welding to this edge has been found, and there is no room around this edge to place another vertex. When no more weldings can be found, but there are still triangles left, the algorithm searches for a possibility of attaching one of the remaining triangles to the existing structure by a vertex. If such a possibility is found, the corresponding edge of the found triangle is placed in the found space and the iterative process of welding triangles restarts. When logical groups are supplied, each of these groups is laid out independently. Then a diagram is constructed in which groups are objects and any two logical groups between which there exist morphisms are connected via a morphism. This diagram is laid out. Finally, the grid which includes all objects of the initial diagram is constructed by replacing the cells which contain logical groups with the corresponding laid out grids, and by correspondingly expanding the rows and columns. The sequential layout algorithm begins by constructing the underlying undirected graph defined by the morphisms obtained after simplifying premises and conclusions and merging them (see above). The vertex with the minimal degree is then picked up and depth-first search is started from it. All objects which are located at distance `n` from the root in the depth-first search tree, are positioned in the `n`-th column of the resulting grid. The sequential layout will therefore attempt to lay the objects out along a line. References ========== [Xypic] http://xy-pic.sourceforge.net/ """ from sympy.categories import (CompositeMorphism, IdentityMorphism, NamedMorphism, Diagram) from sympy.core import Dict, Symbol from sympy.core.compatibility import iterable from sympy.printing import latex from sympy.sets import FiniteSet from sympy.utilities import default_sort_key from sympy.utilities.decorator import doctest_depends_on from itertools import chain __doctest_requires__ = {('preview_diagram',): 'pyglet'} class _GrowableGrid: """ Holds a growable grid of objects. Explanation =========== It is possible to append or prepend a row or a column to the grid using the corresponding methods. Prepending rows or columns has the effect of changing the coordinates of the already existing elements. This class currently represents a naive implementation of the functionality with little attempt at optimisation. """ def __init__(self, width, height): self._width = width self._height = height self._array = [[None for j in range(width)] for i in range(height)] @property def width(self): return self._width @property def height(self): return self._height def __getitem__(self, i_j): """ Returns the element located at in the i-th line and j-th column. """ i, j = i_j return self._array[i][j] def __setitem__(self, i_j, newvalue): """ Sets the element located at in the i-th line and j-th column. """ i, j = i_j self._array[i][j] = newvalue def append_row(self): """ Appends an empty row to the grid. """ self._height += 1 self._array.append([None for j in range(self._width)]) def append_column(self): """ Appends an empty column to the grid. """ self._width += 1 for i in range(self._height): self._array[i].append(None) def prepend_row(self): """ Prepends the grid with an empty row. """ self._height += 1 self._array.insert(0, [None for j in range(self._width)]) def prepend_column(self): """ Prepends the grid with an empty column. """ self._width += 1 for i in range(self._height): self._array[i].insert(0, None) class DiagramGrid: r""" Constructs and holds the fitting of the diagram into a grid. Explanation =========== The mission of this class is to analyse the structure of the supplied diagram and to place its objects on a grid such that, when the objects and the morphisms are actually drawn, the diagram would be "readable", in the sense that there will not be many intersections of moprhisms. This class does not perform any actual drawing. It does strive nevertheless to offer sufficient metadata to draw a diagram. Consider the following simple diagram. >>> from sympy.categories import Object, NamedMorphism >>> from sympy.categories import Diagram, DiagramGrid >>> from sympy import pprint >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> diagram = Diagram([f, g]) The simplest way to have a diagram laid out is the following: >>> grid = DiagramGrid(diagram) >>> (grid.width, grid.height) (2, 2) >>> pprint(grid) A B <BLANKLINE> C Sometimes one sees the diagram as consisting of logical groups. One can advise ``DiagramGrid`` as to such groups by employing the ``groups`` keyword argument. Consider the following diagram: >>> D = Object("D") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> h = NamedMorphism(D, A, "h") >>> k = NamedMorphism(D, B, "k") >>> diagram = Diagram([f, g, h, k]) Lay it out with generic layout: >>> grid = DiagramGrid(diagram) >>> pprint(grid) A B D <BLANKLINE> C Now, we can group the objects `A` and `D` to have them near one another: >>> grid = DiagramGrid(diagram, groups=[[A, D], B, C]) >>> pprint(grid) B C <BLANKLINE> A D Note how the positioning of the other objects changes. Further indications can be supplied to the constructor of :class:`DiagramGrid` using keyword arguments. The currently supported hints are explained in the following paragraphs. :class:`DiagramGrid` does not automatically guess which layout would suit the supplied diagram better. Consider, for example, the following linear diagram: >>> E = Object("E") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> h = NamedMorphism(C, D, "h") >>> i = NamedMorphism(D, E, "i") >>> diagram = Diagram([f, g, h, i]) When laid out with the generic layout, it does not get to look linear: >>> grid = DiagramGrid(diagram) >>> pprint(grid) A B <BLANKLINE> C D <BLANKLINE> E To get it laid out in a line, use ``layout="sequential"``: >>> grid = DiagramGrid(diagram, layout="sequential") >>> pprint(grid) A B C D E One may sometimes need to transpose the resulting layout. While this can always be done by hand, :class:`DiagramGrid` provides a hint for that purpose: >>> grid = DiagramGrid(diagram, layout="sequential", transpose=True) >>> pprint(grid) A <BLANKLINE> B <BLANKLINE> C <BLANKLINE> D <BLANKLINE> E Separate hints can also be provided for each group. For an example, refer to ``tests/test_drawing.py``, and see the different ways in which the five lemma [FiveLemma] can be laid out. See Also ======== Diagram References ========== .. [FiveLemma] https://en.wikipedia.org/wiki/Five_lemma """ @staticmethod def _simplify_morphisms(morphisms): """ Given a dictionary mapping morphisms to their properties, returns a new dictionary in which there are no morphisms which do not have properties, and which are compositions of other morphisms included in the dictionary. Identities are dropped as well. """ newmorphisms = {} for morphism, props in morphisms.items(): if isinstance(morphism, CompositeMorphism) and not props: continue elif isinstance(morphism, IdentityMorphism): continue else: newmorphisms[morphism] = props return newmorphisms @staticmethod def _merge_premises_conclusions(premises, conclusions): """ Given two dictionaries of morphisms and their properties, produces a single dictionary which includes elements from both dictionaries. If a morphism has some properties in premises and also in conclusions, the properties in conclusions take priority. """ return dict(chain(premises.items(), conclusions.items())) @staticmethod def _juxtapose_edges(edge1, edge2): """ If ``edge1`` and ``edge2`` have precisely one common endpoint, returns an edge which would form a triangle with ``edge1`` and ``edge2``. If ``edge1`` and ``edge2`` don't have a common endpoint, returns ``None``. If ``edge1`` and ``edge`` are the same edge, returns ``None``. """ intersection = edge1 & edge2 if len(intersection) != 1: # The edges either have no common points or are equal. return None # The edges have a common endpoint. Extract the different # endpoints and set up the new edge. return (edge1 - intersection) | (edge2 - intersection) @staticmethod def _add_edge_append(dictionary, edge, elem): """ If ``edge`` is not in ``dictionary``, adds ``edge`` to the dictionary and sets its value to ``[elem]``. Otherwise appends ``elem`` to the value of existing entry. Note that edges are undirected, thus `(A, B) = (B, A)`. """ if edge in dictionary: dictionary[edge].append(elem) else: dictionary[edge] = [elem] @staticmethod def _build_skeleton(morphisms): """ Creates a dictionary which maps edges to corresponding morphisms. Thus for a morphism `f:A\rightarrow B`, the edge `(A, B)` will be associated with `f`. This function also adds to the list those edges which are formed by juxtaposition of two edges already in the list. These new edges are not associated with any morphism and are only added to assure that the diagram can be decomposed into triangles. """ edges = {} # Create edges for morphisms. for morphism in morphisms: DiagramGrid._add_edge_append( edges, frozenset([morphism.domain, morphism.codomain]), morphism) # Create new edges by juxtaposing existing edges. edges1 = dict(edges) for w in edges1: for v in edges1: wv = DiagramGrid._juxtapose_edges(w, v) if wv and wv not in edges: edges[wv] = [] return edges @staticmethod def _list_triangles(edges): """ Builds the set of triangles formed by the supplied edges. The triangles are arbitrary and need not be commutative. A triangle is a set that contains all three of its sides. """ triangles = set() for w in edges: for v in edges: wv = DiagramGrid._juxtapose_edges(w, v) if wv and wv in edges: triangles.add(frozenset([w, v, wv])) return triangles @staticmethod def _drop_redundant_triangles(triangles, skeleton): """ Returns a list which contains only those triangles who have morphisms associated with at least two edges. """ return [tri for tri in triangles if len([e for e in tri if skeleton[e]]) >= 2] @staticmethod def _morphism_length(morphism): """ Returns the length of a morphism. The length of a morphism is the number of components it consists of. A non-composite morphism is of length 1. """ if isinstance(morphism, CompositeMorphism): return len(morphism.components) else: return 1 @staticmethod def _compute_triangle_min_sizes(triangles, edges): r""" Returns a dictionary mapping triangles to their minimal sizes. The minimal size of a triangle is the sum of maximal lengths of morphisms associated to the sides of the triangle. The length of a morphism is the number of components it consists of. A non-composite morphism is of length 1. Sorting triangles by this metric attempts to address two aspects of layout. For triangles with only simple morphisms in the edge, this assures that triangles with all three edges visible will get typeset after triangles with less visible edges, which sometimes minimizes the necessity in diagonal arrows. For triangles with composite morphisms in the edges, this assures that objects connected with shorter morphisms will be laid out first, resulting the visual proximity of those objects which are connected by shorter morphisms. """ triangle_sizes = {} for triangle in triangles: size = 0 for e in triangle: morphisms = edges[e] if morphisms: size += max(DiagramGrid._morphism_length(m) for m in morphisms) triangle_sizes[triangle] = size return triangle_sizes @staticmethod def _triangle_objects(triangle): """ Given a triangle, returns the objects included in it. """ # A triangle is a frozenset of three two-element frozensets # (the edges). This chains the three edges together and # creates a frozenset from the iterator, thus producing a # frozenset of objects of the triangle. return frozenset(chain(*tuple(triangle))) @staticmethod def _other_vertex(triangle, edge): """ Given a triangle and an edge of it, returns the vertex which opposes the edge. """ # This gets the set of objects of the triangle and then # subtracts the set of objects employed in ``edge`` to get the # vertex opposite to ``edge``. return list(DiagramGrid._triangle_objects(triangle) - set(edge))[0] @staticmethod def _empty_point(pt, grid): """ Checks if the cell at coordinates ``pt`` is either empty or out of the bounds of the grid. """ if (pt[0] < 0) or (pt[1] < 0) or \ (pt[0] >= grid.height) or (pt[1] >= grid.width): return True return grid[pt] is None @staticmethod def _put_object(coords, obj, grid, fringe): """ Places an object at the coordinate ``cords`` in ``grid``, growing the grid and updating ``fringe``, if necessary. Returns (0, 0) if no row or column has been prepended, (1, 0) if a row was prepended, (0, 1) if a column was prepended and (1, 1) if both a column and a row were prepended. """ (i, j) = coords offset = (0, 0) if i == -1: grid.prepend_row() i = 0 offset = (1, 0) for k in range(len(fringe)): ((i1, j1), (i2, j2)) = fringe[k] fringe[k] = ((i1 + 1, j1), (i2 + 1, j2)) elif i == grid.height: grid.append_row() if j == -1: j = 0 offset = (offset[0], 1) grid.prepend_column() for k in range(len(fringe)): ((i1, j1), (i2, j2)) = fringe[k] fringe[k] = ((i1, j1 + 1), (i2, j2 + 1)) elif j == grid.width: grid.append_column() grid[i, j] = obj return offset @staticmethod def _choose_target_cell(pt1, pt2, edge, obj, skeleton, grid): """ Given two points, ``pt1`` and ``pt2``, and the welding edge ``edge``, chooses one of the two points to place the opposing vertex ``obj`` of the triangle. If neither of this points fits, returns ``None``. """ pt1_empty = DiagramGrid._empty_point(pt1, grid) pt2_empty = DiagramGrid._empty_point(pt2, grid) if pt1_empty and pt2_empty: # Both cells are empty. Of these two, choose that cell # which will assure that a visible edge of the triangle # will be drawn perpendicularly to the current welding # edge. A = grid[edge[0]] if skeleton.get(frozenset([A, obj])): return pt1 else: return pt2 if pt1_empty: return pt1 elif pt2_empty: return pt2 else: return None @staticmethod def _find_triangle_to_weld(triangles, fringe, grid): """ Finds, if possible, a triangle and an edge in the ``fringe`` to which the triangle could be attached. Returns the tuple containing the triangle and the index of the corresponding edge in the ``fringe``. This function relies on the fact that objects are unique in the diagram. """ for triangle in triangles: for (a, b) in fringe: if frozenset([grid[a], grid[b]]) in triangle: return (triangle, (a, b)) return None @staticmethod def _weld_triangle(tri, welding_edge, fringe, grid, skeleton): """ If possible, welds the triangle ``tri`` to ``fringe`` and returns ``False``. If this method encounters a degenerate situation in the fringe and corrects it such that a restart of the search is required, it returns ``True`` (which means that a restart in finding triangle weldings is required). A degenerate situation is a situation when an edge listed in the fringe does not belong to the visual boundary of the diagram. """ a, b = welding_edge target_cell = None obj = DiagramGrid._other_vertex(tri, (grid[a], grid[b])) # We now have a triangle and an edge where it can be welded to # the fringe. Decide where to place the other vertex of the # triangle and check for degenerate situations en route. if (abs(a[0] - b[0]) == 1) and (abs(a[1] - b[1]) == 1): # A diagonal edge. target_cell = (a[0], b[1]) if grid[target_cell]: # That cell is already occupied. target_cell = (b[0], a[1]) if grid[target_cell]: # Degenerate situation, this edge is not # on the actual fringe. Correct the # fringe and go on. fringe.remove((a, b)) return True elif a[0] == b[0]: # A horizontal edge. We first attempt to build the # triangle in the downward direction. down_left = a[0] + 1, a[1] down_right = a[0] + 1, b[1] target_cell = DiagramGrid._choose_target_cell( down_left, down_right, (a, b), obj, skeleton, grid) if not target_cell: # No room below this edge. Check above. up_left = a[0] - 1, a[1] up_right = a[0] - 1, b[1] target_cell = DiagramGrid._choose_target_cell( up_left, up_right, (a, b), obj, skeleton, grid) if not target_cell: # This edge is not in the fringe, remove it # and restart. fringe.remove((a, b)) return True elif a[1] == b[1]: # A vertical edge. We will attempt to place the other # vertex of the triangle to the right of this edge. right_up = a[0], a[1] + 1 right_down = b[0], a[1] + 1 target_cell = DiagramGrid._choose_target_cell( right_up, right_down, (a, b), obj, skeleton, grid) if not target_cell: # No room to the left. See what's to the right. left_up = a[0], a[1] - 1 left_down = b[0], a[1] - 1 target_cell = DiagramGrid._choose_target_cell( left_up, left_down, (a, b), obj, skeleton, grid) if not target_cell: # This edge is not in the fringe, remove it # and restart. fringe.remove((a, b)) return True # We now know where to place the other vertex of the # triangle. offset = DiagramGrid._put_object(target_cell, obj, grid, fringe) # Take care of the displacement of coordinates if a row or # a column was prepended. target_cell = (target_cell[0] + offset[0], target_cell[1] + offset[1]) a = (a[0] + offset[0], a[1] + offset[1]) b = (b[0] + offset[0], b[1] + offset[1]) fringe.extend([(a, target_cell), (b, target_cell)]) # No restart is required. return False @staticmethod def _triangle_key(tri, triangle_sizes): """ Returns a key for the supplied triangle. It should be the same independently of the hash randomisation. """ objects = sorted( DiagramGrid._triangle_objects(tri), key=default_sort_key) return (triangle_sizes[tri], default_sort_key(objects)) @staticmethod def _pick_root_edge(tri, skeleton): """ For a given triangle always picks the same root edge. The root edge is the edge that will be placed first on the grid. """ candidates = [sorted(e, key=default_sort_key) for e in tri if skeleton[e]] sorted_candidates = sorted(candidates, key=default_sort_key) # Don't forget to assure the proper ordering of the vertices # in this edge. return tuple(sorted(sorted_candidates[0], key=default_sort_key)) @staticmethod def _drop_irrelevant_triangles(triangles, placed_objects): """ Returns only those triangles whose set of objects is not completely included in ``placed_objects``. """ return [tri for tri in triangles if not placed_objects.issuperset( DiagramGrid._triangle_objects(tri))] @staticmethod def _grow_pseudopod(triangles, fringe, grid, skeleton, placed_objects): """ Starting from an object in the existing structure on the ``grid``, adds an edge to which a triangle from ``triangles`` could be welded. If this method has found a way to do so, it returns the object it has just added. This method should be applied when ``_weld_triangle`` cannot find weldings any more. """ for i in range(grid.height): for j in range(grid.width): obj = grid[i, j] if not obj: continue # Here we need to choose a triangle which has only # ``obj`` in common with the existing structure. The # situations when this is not possible should be # handled elsewhere. def good_triangle(tri): objs = DiagramGrid._triangle_objects(tri) return obj in objs and \ placed_objects & (objs - {obj}) == set() tris = [tri for tri in triangles if good_triangle(tri)] if not tris: # This object is not interesting. continue # Pick the "simplest" of the triangles which could be # attached. Remember that the list of triangles is # sorted according to their "simplicity" (see # _compute_triangle_min_sizes for the metric). # # Note that ``tris`` are sequentially built from # ``triangles``, so we don't have to worry about hash # randomisation. tri = tris[0] # We have found a triangle which could be attached to # the existing structure by a vertex. candidates = sorted([e for e in tri if skeleton[e]], key=lambda e: FiniteSet(*e).sort_key()) edges = [e for e in candidates if obj in e] # Note that a meaningful edge (i.e., and edge that is # associated with a morphism) containing ``obj`` # always exists. That's because all triangles are # guaranteed to have at least two meaningful edges. # See _drop_redundant_triangles. # Get the object at the other end of the edge. edge = edges[0] other_obj = tuple(edge - frozenset([obj]))[0] # Now check for free directions. When checking for # free directions, prefer the horizontal and vertical # directions. neighbours = [(i - 1, j), (i, j + 1), (i + 1, j), (i, j - 1), (i - 1, j - 1), (i - 1, j + 1), (i + 1, j - 1), (i + 1, j + 1)] for pt in neighbours: if DiagramGrid._empty_point(pt, grid): # We have a found a place to grow the # pseudopod into. offset = DiagramGrid._put_object( pt, other_obj, grid, fringe) i += offset[0] j += offset[1] pt = (pt[0] + offset[0], pt[1] + offset[1]) fringe.append(((i, j), pt)) return other_obj # This diagram is actually cooler that I can handle. Fail cowardly. return None @staticmethod def _handle_groups(diagram, groups, merged_morphisms, hints): """ Given the slightly preprocessed morphisms of the diagram, produces a grid laid out according to ``groups``. If a group has hints, it is laid out with those hints only, without any influence from ``hints``. Otherwise, it is laid out with ``hints``. """ def lay_out_group(group, local_hints): """ If ``group`` is a set of objects, uses a ``DiagramGrid`` to lay it out and returns the grid. Otherwise returns the object (i.e., ``group``). If ``local_hints`` is not empty, it is supplied to ``DiagramGrid`` as the dictionary of hints. Otherwise, the ``hints`` argument of ``_handle_groups`` is used. """ if isinstance(group, FiniteSet): # Set up the corresponding object-to-group # mappings. for obj in group: obj_groups[obj] = group # Lay out the current group. if local_hints: groups_grids[group] = DiagramGrid( diagram.subdiagram_from_objects(group), **local_hints) else: groups_grids[group] = DiagramGrid( diagram.subdiagram_from_objects(group), **hints) else: obj_groups[group] = group def group_to_finiteset(group): """ Converts ``group`` to a :class:``FiniteSet`` if it is an iterable. """ if iterable(group): return FiniteSet(*group) else: return group obj_groups = {} groups_grids = {} # We would like to support various containers to represent # groups. To achieve that, before laying each group out, it # should be converted to a FiniteSet, because that is what the # following code expects. if isinstance(groups, dict) or isinstance(groups, Dict): finiteset_groups = {} for group, local_hints in groups.items(): finiteset_group = group_to_finiteset(group) finiteset_groups[finiteset_group] = local_hints lay_out_group(group, local_hints) groups = finiteset_groups else: finiteset_groups = [] for group in groups: finiteset_group = group_to_finiteset(group) finiteset_groups.append(finiteset_group) lay_out_group(finiteset_group, None) groups = finiteset_groups new_morphisms = [] for morphism in merged_morphisms: dom = obj_groups[morphism.domain] cod = obj_groups[morphism.codomain] # Note that we are not really interested in morphisms # which do not employ two different groups, because # these do not influence the layout. if dom != cod: # These are essentially unnamed morphisms; they are # not going to mess in the final layout. By giving # them the same names, we avoid unnecessary # duplicates. new_morphisms.append(NamedMorphism(dom, cod, "dummy")) # Lay out the new diagram. Since these are dummy morphisms, # properties and conclusions are irrelevant. top_grid = DiagramGrid(Diagram(new_morphisms)) # We now have to substitute the groups with the corresponding # grids, laid out at the beginning of this function. Compute # the size of each row and column in the grid, so that all # nested grids fit. def group_size(group): """ For the supplied group (or object, eventually), returns the size of the cell that will hold this group (object). """ if group in groups_grids: grid = groups_grids[group] return (grid.height, grid.width) else: return (1, 1) row_heights = [max(group_size(top_grid[i, j])[0] for j in range(top_grid.width)) for i in range(top_grid.height)] column_widths = [max(group_size(top_grid[i, j])[1] for i in range(top_grid.height)) for j in range(top_grid.width)] grid = _GrowableGrid(sum(column_widths), sum(row_heights)) real_row = 0 real_column = 0 for logical_row in range(top_grid.height): for logical_column in range(top_grid.width): obj = top_grid[logical_row, logical_column] if obj in groups_grids: # This is a group. Copy the corresponding grid in # place. local_grid = groups_grids[obj] for i in range(local_grid.height): for j in range(local_grid.width): grid[real_row + i, real_column + j] = local_grid[i, j] else: # This is an object. Just put it there. grid[real_row, real_column] = obj real_column += column_widths[logical_column] real_column = 0 real_row += row_heights[logical_row] return grid @staticmethod def _generic_layout(diagram, merged_morphisms): """ Produces the generic layout for the supplied diagram. """ all_objects = set(diagram.objects) if len(all_objects) == 1: # There only one object in the diagram, just put in on 1x1 # grid. grid = _GrowableGrid(1, 1) grid[0, 0] = tuple(all_objects)[0] return grid skeleton = DiagramGrid._build_skeleton(merged_morphisms) grid = _GrowableGrid(2, 1) if len(skeleton) == 1: # This diagram contains only one morphism. Draw it # horizontally. objects = sorted(all_objects, key=default_sort_key) grid[0, 0] = objects[0] grid[0, 1] = objects[1] return grid triangles = DiagramGrid._list_triangles(skeleton) triangles = DiagramGrid._drop_redundant_triangles(triangles, skeleton) triangle_sizes = DiagramGrid._compute_triangle_min_sizes( triangles, skeleton) triangles = sorted(triangles, key=lambda tri: DiagramGrid._triangle_key(tri, triangle_sizes)) # Place the first edge on the grid. root_edge = DiagramGrid._pick_root_edge(triangles[0], skeleton) grid[0, 0], grid[0, 1] = root_edge fringe = [((0, 0), (0, 1))] # Record which objects we now have on the grid. placed_objects = set(root_edge) while placed_objects != all_objects: welding = DiagramGrid._find_triangle_to_weld( triangles, fringe, grid) if welding: (triangle, welding_edge) = welding restart_required = DiagramGrid._weld_triangle( triangle, welding_edge, fringe, grid, skeleton) if restart_required: continue placed_objects.update( DiagramGrid._triangle_objects(triangle)) else: # No more weldings found. Try to attach triangles by # vertices. new_obj = DiagramGrid._grow_pseudopod( triangles, fringe, grid, skeleton, placed_objects) if not new_obj: # No more triangles can be attached, not even by # the edge. We will set up a new diagram out of # what has been left, laid it out independently, # and then attach it to this one. remaining_objects = all_objects - placed_objects remaining_diagram = diagram.subdiagram_from_objects( FiniteSet(*remaining_objects)) remaining_grid = DiagramGrid(remaining_diagram) # Now, let's glue ``remaining_grid`` to ``grid``. final_width = grid.width + remaining_grid.width final_height = max(grid.height, remaining_grid.height) final_grid = _GrowableGrid(final_width, final_height) for i in range(grid.width): for j in range(grid.height): final_grid[i, j] = grid[i, j] start_j = grid.width for i in range(remaining_grid.height): for j in range(remaining_grid.width): final_grid[i, start_j + j] = remaining_grid[i, j] return final_grid placed_objects.add(new_obj) triangles = DiagramGrid._drop_irrelevant_triangles( triangles, placed_objects) return grid @staticmethod def _get_undirected_graph(objects, merged_morphisms): """ Given the objects and the relevant morphisms of a diagram, returns the adjacency lists of the underlying undirected graph. """ adjlists = {} for obj in objects: adjlists[obj] = [] for morphism in merged_morphisms: adjlists[morphism.domain].append(morphism.codomain) adjlists[morphism.codomain].append(morphism.domain) # Assure that the objects in the adjacency list are always in # the same order. for obj in adjlists.keys(): adjlists[obj].sort(key=default_sort_key) return adjlists @staticmethod def _sequential_layout(diagram, merged_morphisms): r""" Lays out the diagram in "sequential" layout. This method will attempt to produce a result as close to a line as possible. For linear diagrams, the result will actually be a line. """ objects = diagram.objects sorted_objects = sorted(objects, key=default_sort_key) # Set up the adjacency lists of the underlying undirected # graph of ``merged_morphisms``. adjlists = DiagramGrid._get_undirected_graph(objects, merged_morphisms) # Find an object with the minimal degree. This is going to be # the root. root = sorted_objects[0] mindegree = len(adjlists[root]) for obj in sorted_objects: current_degree = len(adjlists[obj]) if current_degree < mindegree: root = obj mindegree = current_degree grid = _GrowableGrid(1, 1) grid[0, 0] = root placed_objects = {root} def place_objects(pt, placed_objects): """ Does depth-first search in the underlying graph of the diagram and places the objects en route. """ # We will start placing new objects from here. new_pt = (pt[0], pt[1] + 1) for adjacent_obj in adjlists[grid[pt]]: if adjacent_obj in placed_objects: # This object has already been placed. continue DiagramGrid._put_object(new_pt, adjacent_obj, grid, []) placed_objects.add(adjacent_obj) placed_objects.update(place_objects(new_pt, placed_objects)) new_pt = (new_pt[0] + 1, new_pt[1]) return placed_objects place_objects((0, 0), placed_objects) return grid @staticmethod def _drop_inessential_morphisms(merged_morphisms): r""" Removes those morphisms which should appear in the diagram, but which have no relevance to object layout. Currently this removes "loop" morphisms: the non-identity morphisms with the same domains and codomains. """ morphisms = [m for m in merged_morphisms if m.domain != m.codomain] return morphisms @staticmethod def _get_connected_components(objects, merged_morphisms): """ Given a container of morphisms, returns a list of connected components formed by these morphisms. A connected component is represented by a diagram consisting of the corresponding morphisms. """ component_index = {} for o in objects: component_index[o] = None # Get the underlying undirected graph of the diagram. adjlist = DiagramGrid._get_undirected_graph(objects, merged_morphisms) def traverse_component(object, current_index): """ Does a depth-first search traversal of the component containing ``object``. """ component_index[object] = current_index for o in adjlist[object]: if component_index[o] is None: traverse_component(o, current_index) # Traverse all components. current_index = 0 for o in adjlist: if component_index[o] is None: traverse_component(o, current_index) current_index += 1 # List the objects of the components. component_objects = [[] for i in range(current_index)] for o, idx in component_index.items(): component_objects[idx].append(o) # Finally, list the morphisms belonging to each component. # # Note: If some objects are isolated, they will not get any # morphisms at this stage, and since the layout algorithm # relies, we are essentially going to lose this object. # Therefore, check if there are isolated objects and, for each # of them, provide the trivial identity morphism. It will get # discarded later, but the object will be there. component_morphisms = [] for component in component_objects: current_morphisms = {} for m in merged_morphisms: if (m.domain in component) and (m.codomain in component): current_morphisms[m] = merged_morphisms[m] if len(component) == 1: # Let's add an identity morphism, for the sake of # surely having morphisms in this component. current_morphisms[IdentityMorphism(component[0])] = FiniteSet() component_morphisms.append(Diagram(current_morphisms)) return component_morphisms def __init__(self, diagram, groups=None, **hints): premises = DiagramGrid._simplify_morphisms(diagram.premises) conclusions = DiagramGrid._simplify_morphisms(diagram.conclusions) all_merged_morphisms = DiagramGrid._merge_premises_conclusions( premises, conclusions) merged_morphisms = DiagramGrid._drop_inessential_morphisms( all_merged_morphisms) # Store the merged morphisms for later use. self._morphisms = all_merged_morphisms components = DiagramGrid._get_connected_components( diagram.objects, all_merged_morphisms) if groups and (groups != diagram.objects): # Lay out the diagram according to the groups. self._grid = DiagramGrid._handle_groups( diagram, groups, merged_morphisms, hints) elif len(components) > 1: # Note that we check for connectedness _before_ checking # the layout hints because the layout strategies don't # know how to deal with disconnected diagrams. # The diagram is disconnected. Lay out the components # independently. grids = [] # Sort the components to eventually get the grids arranged # in a fixed, hash-independent order. components = sorted(components, key=default_sort_key) for component in components: grid = DiagramGrid(component, **hints) grids.append(grid) # Throw the grids together, in a line. total_width = sum(g.width for g in grids) total_height = max(g.height for g in grids) grid = _GrowableGrid(total_width, total_height) start_j = 0 for g in grids: for i in range(g.height): for j in range(g.width): grid[i, start_j + j] = g[i, j] start_j += g.width self._grid = grid elif "layout" in hints: if hints["layout"] == "sequential": self._grid = DiagramGrid._sequential_layout( diagram, merged_morphisms) else: self._grid = DiagramGrid._generic_layout(diagram, merged_morphisms) if hints.get("transpose"): # Transpose the resulting grid. grid = _GrowableGrid(self._grid.height, self._grid.width) for i in range(self._grid.height): for j in range(self._grid.width): grid[j, i] = self._grid[i, j] self._grid = grid @property def width(self): """ Returns the number of columns in this diagram layout. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> from sympy.categories import Diagram, DiagramGrid >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> diagram = Diagram([f, g]) >>> grid = DiagramGrid(diagram) >>> grid.width 2 """ return self._grid.width @property def height(self): """ Returns the number of rows in this diagram layout. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> from sympy.categories import Diagram, DiagramGrid >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> diagram = Diagram([f, g]) >>> grid = DiagramGrid(diagram) >>> grid.height 2 """ return self._grid.height def __getitem__(self, i_j): """ Returns the object placed in the row ``i`` and column ``j``. The indices are 0-based. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> from sympy.categories import Diagram, DiagramGrid >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> diagram = Diagram([f, g]) >>> grid = DiagramGrid(diagram) >>> (grid[0, 0], grid[0, 1]) (Object("A"), Object("B")) >>> (grid[1, 0], grid[1, 1]) (None, Object("C")) """ i, j = i_j return self._grid[i, j] @property def morphisms(self): """ Returns those morphisms (and their properties) which are sufficiently meaningful to be drawn. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> from sympy.categories import Diagram, DiagramGrid >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> diagram = Diagram([f, g]) >>> grid = DiagramGrid(diagram) >>> grid.morphisms {NamedMorphism(Object("A"), Object("B"), "f"): EmptySet, NamedMorphism(Object("B"), Object("C"), "g"): EmptySet} """ return self._morphisms def __str__(self): """ Produces a string representation of this class. This method returns a string representation of the underlying list of lists of objects. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> from sympy.categories import Diagram, DiagramGrid >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> diagram = Diagram([f, g]) >>> grid = DiagramGrid(diagram) >>> print(grid) [[Object("A"), Object("B")], [None, Object("C")]] """ return repr(self._grid._array) class ArrowStringDescription: r""" Stores the information necessary for producing an Xy-pic description of an arrow. The principal goal of this class is to abstract away the string representation of an arrow and to also provide the functionality to produce the actual Xy-pic string. ``unit`` sets the unit which will be used to specify the amount of curving and other distances. ``horizontal_direction`` should be a string of ``"r"`` or ``"l"`` specifying the horizontal offset of the target cell of the arrow relatively to the current one. ``vertical_direction`` should specify the vertical offset using a series of either ``"d"`` or ``"u"``. ``label_position`` should be either ``"^"``, ``"_"``, or ``"|"`` to specify that the label should be positioned above the arrow, below the arrow or just over the arrow, in a break. Note that the notions "above" and "below" are relative to arrow direction. ``label`` stores the morphism label. This works as follows (disregard the yet unexplained arguments): >>> from sympy.categories.diagram_drawing import ArrowStringDescription >>> astr = ArrowStringDescription( ... unit="mm", curving=None, curving_amount=None, ... looping_start=None, looping_end=None, horizontal_direction="d", ... vertical_direction="r", label_position="_", label="f") >>> print(str(astr)) \ar[dr]_{f} ``curving`` should be one of ``"^"``, ``"_"`` to specify in which direction the arrow is going to curve. ``curving_amount`` is a number describing how many ``unit``'s the morphism is going to curve: >>> astr = ArrowStringDescription( ... unit="mm", curving="^", curving_amount=12, ... looping_start=None, looping_end=None, horizontal_direction="d", ... vertical_direction="r", label_position="_", label="f") >>> print(str(astr)) \ar@/^12mm/[dr]_{f} ``looping_start`` and ``looping_end`` are currently only used for loop morphisms, those which have the same domain and codomain. These two attributes should store a valid Xy-pic direction and specify, correspondingly, the direction the arrow gets out into and the direction the arrow gets back from: >>> astr = ArrowStringDescription( ... unit="mm", curving=None, curving_amount=None, ... looping_start="u", looping_end="l", horizontal_direction="", ... vertical_direction="", label_position="_", label="f") >>> print(str(astr)) \ar@(u,l)[]_{f} ``label_displacement`` controls how far the arrow label is from the ends of the arrow. For example, to position the arrow label near the arrow head, use ">": >>> astr = ArrowStringDescription( ... unit="mm", curving="^", curving_amount=12, ... looping_start=None, looping_end=None, horizontal_direction="d", ... vertical_direction="r", label_position="_", label="f") >>> astr.label_displacement = ">" >>> print(str(astr)) \ar@/^12mm/[dr]_>{f} Finally, ``arrow_style`` is used to specify the arrow style. To get a dashed arrow, for example, use "{-->}" as arrow style: >>> astr = ArrowStringDescription( ... unit="mm", curving="^", curving_amount=12, ... looping_start=None, looping_end=None, horizontal_direction="d", ... vertical_direction="r", label_position="_", label="f") >>> astr.arrow_style = "{-->}" >>> print(str(astr)) \ar@/^12mm/@{-->}[dr]_{f} Notes ===== Instances of :class:`ArrowStringDescription` will be constructed by :class:`XypicDiagramDrawer` and provided for further use in formatters. The user is not expected to construct instances of :class:`ArrowStringDescription` themselves. To be able to properly utilise this class, the reader is encouraged to checkout the Xy-pic user guide, available at [Xypic]. See Also ======== XypicDiagramDrawer References ========== [Xypic] http://xy-pic.sourceforge.net/ """ def __init__(self, unit, curving, curving_amount, looping_start, looping_end, horizontal_direction, vertical_direction, label_position, label): self.unit = unit self.curving = curving self.curving_amount = curving_amount self.looping_start = looping_start self.looping_end = looping_end self.horizontal_direction = horizontal_direction self.vertical_direction = vertical_direction self.label_position = label_position self.label = label self.label_displacement = "" self.arrow_style = "" # This flag shows that the position of the label of this # morphism was set while typesetting a curved morphism and # should not be modified later. self.forced_label_position = False def __str__(self): if self.curving: curving_str = "@/%s%d%s/" % (self.curving, self.curving_amount, self.unit) else: curving_str = "" if self.looping_start and self.looping_end: looping_str = "@(%s,%s)" % (self.looping_start, self.looping_end) else: looping_str = "" if self.arrow_style: style_str = "@" + self.arrow_style else: style_str = "" return "\\ar%s%s%s[%s%s]%s%s{%s}" % \ (curving_str, looping_str, style_str, self.horizontal_direction, self.vertical_direction, self.label_position, self.label_displacement, self.label) class XypicDiagramDrawer: r""" Given a :class:`~.Diagram` and the corresponding :class:`DiagramGrid`, produces the Xy-pic representation of the diagram. The most important method in this class is ``draw``. Consider the following triangle diagram: >>> from sympy.categories import Object, NamedMorphism, Diagram >>> from sympy.categories import DiagramGrid, XypicDiagramDrawer >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> diagram = Diagram([f, g], {g * f: "unique"}) To draw this diagram, its objects need to be laid out with a :class:`DiagramGrid`:: >>> grid = DiagramGrid(diagram) Finally, the drawing: >>> drawer = XypicDiagramDrawer() >>> print(drawer.draw(diagram, grid)) \xymatrix{ A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\ C & } For further details see the docstring of this method. To control the appearance of the arrows, formatters are used. The dictionary ``arrow_formatters`` maps morphisms to formatter functions. A formatter is accepts an :class:`ArrowStringDescription` and is allowed to modify any of the arrow properties exposed thereby. For example, to have all morphisms with the property ``unique`` appear as dashed arrows, and to have their names prepended with `\exists !`, the following should be done: >>> def formatter(astr): ... astr.label = r"\exists !" + astr.label ... astr.arrow_style = "{-->}" >>> drawer.arrow_formatters["unique"] = formatter >>> print(drawer.draw(diagram, grid)) \xymatrix{ A \ar@{-->}[d]_{\exists !g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\ C & } To modify the appearance of all arrows in the diagram, set ``default_arrow_formatter``. For example, to place all morphism labels a little bit farther from the arrow head so that they look more centred, do as follows: >>> def default_formatter(astr): ... astr.label_displacement = "(0.45)" >>> drawer.default_arrow_formatter = default_formatter >>> print(drawer.draw(diagram, grid)) \xymatrix{ A \ar@{-->}[d]_(0.45){\exists !g\circ f} \ar[r]^(0.45){f} & B \ar[ld]^(0.45){g} \\ C & } In some diagrams some morphisms are drawn as curved arrows. Consider the following diagram: >>> D = Object("D") >>> E = Object("E") >>> h = NamedMorphism(D, A, "h") >>> k = NamedMorphism(D, B, "k") >>> diagram = Diagram([f, g, h, k]) >>> grid = DiagramGrid(diagram) >>> drawer = XypicDiagramDrawer() >>> print(drawer.draw(diagram, grid)) \xymatrix{ A \ar[r]_{f} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_3mm/[ll]_{h} \\ & C & } To control how far the morphisms are curved by default, one can use the ``unit`` and ``default_curving_amount`` attributes: >>> drawer.unit = "cm" >>> drawer.default_curving_amount = 1 >>> print(drawer.draw(diagram, grid)) \xymatrix{ A \ar[r]_{f} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_1cm/[ll]_{h} \\ & C & } In some diagrams, there are multiple curved morphisms between the same two objects. To control by how much the curving changes between two such successive morphisms, use ``default_curving_step``: >>> drawer.default_curving_step = 1 >>> h1 = NamedMorphism(A, D, "h1") >>> diagram = Diagram([f, g, h, k, h1]) >>> grid = DiagramGrid(diagram) >>> print(drawer.draw(diagram, grid)) \xymatrix{ A \ar[r]_{f} \ar@/^1cm/[rr]^{h_{1}} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_2cm/[ll]_{h} \\ & C & } The default value of ``default_curving_step`` is 4 units. See Also ======== draw, ArrowStringDescription """ def __init__(self): self.unit = "mm" self.default_curving_amount = 3 self.default_curving_step = 4 # This dictionary maps properties to the corresponding arrow # formatters. self.arrow_formatters = {} # This is the default arrow formatter which will be applied to # each arrow independently of its properties. self.default_arrow_formatter = None @staticmethod def _process_loop_morphism(i, j, grid, morphisms_str_info, object_coords): """ Produces the information required for constructing the string representation of a loop morphism. This function is invoked from ``_process_morphism``. See Also ======== _process_morphism """ curving = "" label_pos = "^" looping_start = "" looping_end = "" # This is a loop morphism. Count how many morphisms stick # in each of the four quadrants. Note that straight # vertical and horizontal morphisms count in two quadrants # at the same time (i.e., a morphism going up counts both # in the first and the second quadrants). # The usual numbering (counterclockwise) of quadrants # applies. quadrant = [0, 0, 0, 0] obj = grid[i, j] for m, m_str_info in morphisms_str_info.items(): if (m.domain == obj) and (m.codomain == obj): # That's another loop morphism. Check how it # loops and mark the corresponding quadrants as # busy. (l_s, l_e) = (m_str_info.looping_start, m_str_info.looping_end) if (l_s, l_e) == ("r", "u"): quadrant[0] += 1 elif (l_s, l_e) == ("u", "l"): quadrant[1] += 1 elif (l_s, l_e) == ("l", "d"): quadrant[2] += 1 elif (l_s, l_e) == ("d", "r"): quadrant[3] += 1 continue if m.domain == obj: (end_i, end_j) = object_coords[m.codomain] goes_out = True elif m.codomain == obj: (end_i, end_j) = object_coords[m.domain] goes_out = False else: continue d_i = end_i - i d_j = end_j - j m_curving = m_str_info.curving if (d_i != 0) and (d_j != 0): # This is really a diagonal morphism. Detect the # quadrant. if (d_i > 0) and (d_j > 0): quadrant[0] += 1 elif (d_i > 0) and (d_j < 0): quadrant[1] += 1 elif (d_i < 0) and (d_j < 0): quadrant[2] += 1 elif (d_i < 0) and (d_j > 0): quadrant[3] += 1 elif d_i == 0: # Knowing where the other end of the morphism is # and which way it goes, we now have to decide # which quadrant is now the upper one and which is # the lower one. if d_j > 0: if goes_out: upper_quadrant = 0 lower_quadrant = 3 else: upper_quadrant = 3 lower_quadrant = 0 else: if goes_out: upper_quadrant = 2 lower_quadrant = 1 else: upper_quadrant = 1 lower_quadrant = 2 if m_curving: if m_curving == "^": quadrant[upper_quadrant] += 1 elif m_curving == "_": quadrant[lower_quadrant] += 1 else: # This morphism counts in both upper and lower # quadrants. quadrant[upper_quadrant] += 1 quadrant[lower_quadrant] += 1 elif d_j == 0: # Knowing where the other end of the morphism is # and which way it goes, we now have to decide # which quadrant is now the left one and which is # the right one. if d_i < 0: if goes_out: left_quadrant = 1 right_quadrant = 0 else: left_quadrant = 0 right_quadrant = 1 else: if goes_out: left_quadrant = 3 right_quadrant = 2 else: left_quadrant = 2 right_quadrant = 3 if m_curving: if m_curving == "^": quadrant[left_quadrant] += 1 elif m_curving == "_": quadrant[right_quadrant] += 1 else: # This morphism counts in both upper and lower # quadrants. quadrant[left_quadrant] += 1 quadrant[right_quadrant] += 1 # Pick the freest quadrant to curve our morphism into. freest_quadrant = 0 for i in range(4): if quadrant[i] < quadrant[freest_quadrant]: freest_quadrant = i # Now set up proper looping. (looping_start, looping_end) = [("r", "u"), ("u", "l"), ("l", "d"), ("d", "r")][freest_quadrant] return (curving, label_pos, looping_start, looping_end) @staticmethod def _process_horizontal_morphism(i, j, target_j, grid, morphisms_str_info, object_coords): """ Produces the information required for constructing the string representation of a horizontal morphism. This function is invoked from ``_process_morphism``. See Also ======== _process_morphism """ # The arrow is horizontal. Check if it goes from left to # right (``backwards == False``) or from right to left # (``backwards == True``). backwards = False start = j end = target_j if end < start: (start, end) = (end, start) backwards = True # Let's see which objects are there between ``start`` and # ``end``, and then count how many morphisms stick out # upwards, and how many stick out downwards. # # For example, consider the situation: # # B1 C1 # | | # A--B--C--D # | # B2 # # Between the objects `A` and `D` there are two objects: # `B` and `C`. Further, there are two morphisms which # stick out upward (the ones between `B1` and `B` and # between `C` and `C1`) and one morphism which sticks out # downward (the one between `B and `B2`). # # We need this information to decide how to curve the # arrow between `A` and `D`. First of all, since there # are two objects between `A` and `D``, we must curve the # arrow. Then, we will have it curve downward, because # there is more space (less morphisms stick out downward # than upward). up = [] down = [] straight_horizontal = [] for k in range(start + 1, end): obj = grid[i, k] if not obj: continue for m in morphisms_str_info: if m.domain == obj: (end_i, end_j) = object_coords[m.codomain] elif m.codomain == obj: (end_i, end_j) = object_coords[m.domain] else: continue if end_i > i: down.append(m) elif end_i < i: up.append(m) elif not morphisms_str_info[m].curving: # This is a straight horizontal morphism, # because it has no curving. straight_horizontal.append(m) if len(up) < len(down): # More morphisms stick out downward than upward, let's # curve the morphism up. if backwards: curving = "_" label_pos = "_" else: curving = "^" label_pos = "^" # Assure that the straight horizontal morphisms have # their labels on the lower side of the arrow. for m in straight_horizontal: (i1, j1) = object_coords[m.domain] (i2, j2) = object_coords[m.codomain] m_str_info = morphisms_str_info[m] if j1 < j2: m_str_info.label_position = "_" else: m_str_info.label_position = "^" # Don't allow any further modifications of the # position of this label. m_str_info.forced_label_position = True else: # More morphisms stick out downward than upward, let's # curve the morphism up. if backwards: curving = "^" label_pos = "^" else: curving = "_" label_pos = "_" # Assure that the straight horizontal morphisms have # their labels on the upper side of the arrow. for m in straight_horizontal: (i1, j1) = object_coords[m.domain] (i2, j2) = object_coords[m.codomain] m_str_info = morphisms_str_info[m] if j1 < j2: m_str_info.label_position = "^" else: m_str_info.label_position = "_" # Don't allow any further modifications of the # position of this label. m_str_info.forced_label_position = True return (curving, label_pos) @staticmethod def _process_vertical_morphism(i, j, target_i, grid, morphisms_str_info, object_coords): """ Produces the information required for constructing the string representation of a vertical morphism. This function is invoked from ``_process_morphism``. See Also ======== _process_morphism """ # This arrow is vertical. Check if it goes from top to # bottom (``backwards == False``) or from bottom to top # (``backwards == True``). backwards = False start = i end = target_i if end < start: (start, end) = (end, start) backwards = True # Let's see which objects are there between ``start`` and # ``end``, and then count how many morphisms stick out to # the left, and how many stick out to the right. # # See the corresponding comment in the previous branch of # this if-statement for more details. left = [] right = [] straight_vertical = [] for k in range(start + 1, end): obj = grid[k, j] if not obj: continue for m in morphisms_str_info: if m.domain == obj: (end_i, end_j) = object_coords[m.codomain] elif m.codomain == obj: (end_i, end_j) = object_coords[m.domain] else: continue if end_j > j: right.append(m) elif end_j < j: left.append(m) elif not morphisms_str_info[m].curving: # This is a straight vertical morphism, # because it has no curving. straight_vertical.append(m) if len(left) < len(right): # More morphisms stick out to the left than to the # right, let's curve the morphism to the right. if backwards: curving = "^" label_pos = "^" else: curving = "_" label_pos = "_" # Assure that the straight vertical morphisms have # their labels on the left side of the arrow. for m in straight_vertical: (i1, j1) = object_coords[m.domain] (i2, j2) = object_coords[m.codomain] m_str_info = morphisms_str_info[m] if i1 < i2: m_str_info.label_position = "^" else: m_str_info.label_position = "_" # Don't allow any further modifications of the # position of this label. m_str_info.forced_label_position = True else: # More morphisms stick out to the right than to the # left, let's curve the morphism to the left. if backwards: curving = "_" label_pos = "_" else: curving = "^" label_pos = "^" # Assure that the straight vertical morphisms have # their labels on the right side of the arrow. for m in straight_vertical: (i1, j1) = object_coords[m.domain] (i2, j2) = object_coords[m.codomain] m_str_info = morphisms_str_info[m] if i1 < i2: m_str_info.label_position = "_" else: m_str_info.label_position = "^" # Don't allow any further modifications of the # position of this label. m_str_info.forced_label_position = True return (curving, label_pos) def _process_morphism(self, diagram, grid, morphism, object_coords, morphisms, morphisms_str_info): """ Given the required information, produces the string representation of ``morphism``. """ def repeat_string_cond(times, str_gt, str_lt): """ If ``times > 0``, repeats ``str_gt`` ``times`` times. Otherwise, repeats ``str_lt`` ``-times`` times. """ if times > 0: return str_gt * times else: return str_lt * (-times) def count_morphisms_undirected(A, B): """ Counts how many processed morphisms there are between the two supplied objects. """ return len([m for m in morphisms_str_info if {m.domain, m.codomain} == {A, B}]) def count_morphisms_filtered(dom, cod, curving): """ Counts the processed morphisms which go out of ``dom`` into ``cod`` with curving ``curving``. """ return len([m for m, m_str_info in morphisms_str_info.items() if (m.domain, m.codomain) == (dom, cod) and (m_str_info.curving == curving)]) (i, j) = object_coords[morphism.domain] (target_i, target_j) = object_coords[morphism.codomain] # We now need to determine the direction of # the arrow. delta_i = target_i - i delta_j = target_j - j vertical_direction = repeat_string_cond(delta_i, "d", "u") horizontal_direction = repeat_string_cond(delta_j, "r", "l") curving = "" label_pos = "^" looping_start = "" looping_end = "" if (delta_i == 0) and (delta_j == 0): # This is a loop morphism. (curving, label_pos, looping_start, looping_end) = XypicDiagramDrawer._process_loop_morphism( i, j, grid, morphisms_str_info, object_coords) elif (delta_i == 0) and (abs(j - target_j) > 1): # This is a horizontal morphism. (curving, label_pos) = XypicDiagramDrawer._process_horizontal_morphism( i, j, target_j, grid, morphisms_str_info, object_coords) elif (delta_j == 0) and (abs(i - target_i) > 1): # This is a vertical morphism. (curving, label_pos) = XypicDiagramDrawer._process_vertical_morphism( i, j, target_i, grid, morphisms_str_info, object_coords) count = count_morphisms_undirected(morphism.domain, morphism.codomain) curving_amount = "" if curving: # This morphisms should be curved anyway. curving_amount = self.default_curving_amount + count * \ self.default_curving_step elif count: # There are no objects between the domain and codomain of # the current morphism, but this is not there already are # some morphisms with the same domain and codomain, so we # have to curve this one. curving = "^" filtered_morphisms = count_morphisms_filtered( morphism.domain, morphism.codomain, curving) curving_amount = self.default_curving_amount + \ filtered_morphisms * \ self.default_curving_step # Let's now get the name of the morphism. morphism_name = "" if isinstance(morphism, IdentityMorphism): morphism_name = "id_{%s}" + latex(grid[i, j]) elif isinstance(morphism, CompositeMorphism): component_names = [latex(Symbol(component.name)) for component in morphism.components] component_names.reverse() morphism_name = "\\circ ".join(component_names) elif isinstance(morphism, NamedMorphism): morphism_name = latex(Symbol(morphism.name)) return ArrowStringDescription( self.unit, curving, curving_amount, looping_start, looping_end, horizontal_direction, vertical_direction, label_pos, morphism_name) @staticmethod def _check_free_space_horizontal(dom_i, dom_j, cod_j, grid): """ For a horizontal morphism, checks whether there is free space (i.e., space not occupied by any objects) above the morphism or below it. """ if dom_j < cod_j: (start, end) = (dom_j, cod_j) backwards = False else: (start, end) = (cod_j, dom_j) backwards = True # Check for free space above. if dom_i == 0: free_up = True else: free_up = all(grid[dom_i - 1, j] for j in range(start, end + 1)) # Check for free space below. if dom_i == grid.height - 1: free_down = True else: free_down = not any(grid[dom_i + 1, j] for j in range(start, end + 1)) return (free_up, free_down, backwards) @staticmethod def _check_free_space_vertical(dom_i, cod_i, dom_j, grid): """ For a vertical morphism, checks whether there is free space (i.e., space not occupied by any objects) to the left of the morphism or to the right of it. """ if dom_i < cod_i: (start, end) = (dom_i, cod_i) backwards = False else: (start, end) = (cod_i, dom_i) backwards = True # Check if there's space to the left. if dom_j == 0: free_left = True else: free_left = not any(grid[i, dom_j - 1] for i in range(start, end + 1)) if dom_j == grid.width - 1: free_right = True else: free_right = not any(grid[i, dom_j + 1] for i in range(start, end + 1)) return (free_left, free_right, backwards) @staticmethod def _check_free_space_diagonal(dom_i, cod_i, dom_j, cod_j, grid): """ For a diagonal morphism, checks whether there is free space (i.e., space not occupied by any objects) above the morphism or below it. """ def abs_xrange(start, end): if start < end: return range(start, end + 1) else: return range(end, start + 1) if dom_i < cod_i and dom_j < cod_j: # This morphism goes from top-left to # bottom-right. (start_i, start_j) = (dom_i, dom_j) (end_i, end_j) = (cod_i, cod_j) backwards = False elif dom_i > cod_i and dom_j > cod_j: # This morphism goes from bottom-right to # top-left. (start_i, start_j) = (cod_i, cod_j) (end_i, end_j) = (dom_i, dom_j) backwards = True if dom_i < cod_i and dom_j > cod_j: # This morphism goes from top-right to # bottom-left. (start_i, start_j) = (dom_i, dom_j) (end_i, end_j) = (cod_i, cod_j) backwards = True elif dom_i > cod_i and dom_j < cod_j: # This morphism goes from bottom-left to # top-right. (start_i, start_j) = (cod_i, cod_j) (end_i, end_j) = (dom_i, dom_j) backwards = False # This is an attempt at a fast and furious strategy to # decide where there is free space on the two sides of # a diagonal morphism. For a diagonal morphism # starting at ``(start_i, start_j)`` and ending at # ``(end_i, end_j)`` the rectangle defined by these # two points is considered. The slope of the diagonal # ``alpha`` is then computed. Then, for every cell # ``(i, j)`` within the rectangle, the slope # ``alpha1`` of the line through ``(start_i, # start_j)`` and ``(i, j)`` is considered. If # ``alpha1`` is between 0 and ``alpha``, the point # ``(i, j)`` is above the diagonal, if ``alpha1`` is # between ``alpha`` and infinity, the point is below # the diagonal. Also note that, with some beforehand # precautions, this trick works for both the main and # the secondary diagonals of the rectangle. # I have considered the possibility to only follow the # shorter diagonals immediately above and below the # main (or secondary) diagonal. This, however, # wouldn't have resulted in much performance gain or # better detection of outer edges, because of # relatively small sizes of diagram grids, while the # code would have become harder to understand. alpha = float(end_i - start_i)/(end_j - start_j) free_up = True free_down = True for i in abs_xrange(start_i, end_i): if not free_up and not free_down: break for j in abs_xrange(start_j, end_j): if not free_up and not free_down: break if (i, j) == (start_i, start_j): continue if j == start_j: alpha1 = "inf" else: alpha1 = float(i - start_i)/(j - start_j) if grid[i, j]: if (alpha1 == "inf") or (abs(alpha1) > abs(alpha)): free_down = False elif abs(alpha1) < abs(alpha): free_up = False return (free_up, free_down, backwards) def _push_labels_out(self, morphisms_str_info, grid, object_coords): """ For all straight morphisms which form the visual boundary of the laid out diagram, puts their labels on their outer sides. """ def set_label_position(free1, free2, pos1, pos2, backwards, m_str_info): """ Given the information about room available to one side and to the other side of a morphism (``free1`` and ``free2``), sets the position of the morphism label in such a way that it is on the freer side. This latter operations involves choice between ``pos1`` and ``pos2``, taking ``backwards`` in consideration. Thus this function will do nothing if either both ``free1 == True`` and ``free2 == True`` or both ``free1 == False`` and ``free2 == False``. In either case, choosing one side over the other presents no advantage. """ if backwards: (pos1, pos2) = (pos2, pos1) if free1 and not free2: m_str_info.label_position = pos1 elif free2 and not free1: m_str_info.label_position = pos2 for m, m_str_info in morphisms_str_info.items(): if m_str_info.curving or m_str_info.forced_label_position: # This is either a curved morphism, and curved # morphisms have other magic, or the position of this # label has already been fixed. continue if m.domain == m.codomain: # This is a loop morphism, their labels, again have a # different magic. continue (dom_i, dom_j) = object_coords[m.domain] (cod_i, cod_j) = object_coords[m.codomain] if dom_i == cod_i: # Horizontal morphism. (free_up, free_down, backwards) = XypicDiagramDrawer._check_free_space_horizontal( dom_i, dom_j, cod_j, grid) set_label_position(free_up, free_down, "^", "_", backwards, m_str_info) elif dom_j == cod_j: # Vertical morphism. (free_left, free_right, backwards) = XypicDiagramDrawer._check_free_space_vertical( dom_i, cod_i, dom_j, grid) set_label_position(free_left, free_right, "_", "^", backwards, m_str_info) else: # A diagonal morphism. (free_up, free_down, backwards) = XypicDiagramDrawer._check_free_space_diagonal( dom_i, cod_i, dom_j, cod_j, grid) set_label_position(free_up, free_down, "^", "_", backwards, m_str_info) @staticmethod def _morphism_sort_key(morphism, object_coords): """ Provides a morphism sorting key such that horizontal or vertical morphisms between neighbouring objects come first, then horizontal or vertical morphisms between more far away objects, and finally, all other morphisms. """ (i, j) = object_coords[morphism.domain] (target_i, target_j) = object_coords[morphism.codomain] if morphism.domain == morphism.codomain: # Loop morphisms should get after diagonal morphisms # so that the proper direction in which to curve the # loop can be determined. return (3, 0, default_sort_key(morphism)) if target_i == i: return (1, abs(target_j - j), default_sort_key(morphism)) if target_j == j: return (1, abs(target_i - i), default_sort_key(morphism)) # Diagonal morphism. return (2, 0, default_sort_key(morphism)) @staticmethod def _build_xypic_string(diagram, grid, morphisms, morphisms_str_info, diagram_format): """ Given a collection of :class:`ArrowStringDescription` describing the morphisms of a diagram and the object layout information of a diagram, produces the final Xy-pic picture. """ # Build the mapping between objects and morphisms which have # them as domains. object_morphisms = {} for obj in diagram.objects: object_morphisms[obj] = [] for morphism in morphisms: object_morphisms[morphism.domain].append(morphism) result = "\\xymatrix%s{\n" % diagram_format for i in range(grid.height): for j in range(grid.width): obj = grid[i, j] if obj: result += latex(obj) + " " morphisms_to_draw = object_morphisms[obj] for morphism in morphisms_to_draw: result += str(morphisms_str_info[morphism]) + " " # Don't put the & after the last column. if j < grid.width - 1: result += "& " # Don't put the line break after the last row. if i < grid.height - 1: result += "\\\\" result += "\n" result += "}\n" return result def draw(self, diagram, grid, masked=None, diagram_format=""): r""" Returns the Xy-pic representation of ``diagram`` laid out in ``grid``. Consider the following simple triangle diagram. >>> from sympy.categories import Object, NamedMorphism, Diagram >>> from sympy.categories import DiagramGrid, XypicDiagramDrawer >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> diagram = Diagram([f, g], {g * f: "unique"}) To draw this diagram, its objects need to be laid out with a :class:`DiagramGrid`:: >>> grid = DiagramGrid(diagram) Finally, the drawing: >>> drawer = XypicDiagramDrawer() >>> print(drawer.draw(diagram, grid)) \xymatrix{ A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\ C & } The argument ``masked`` can be used to skip morphisms in the presentation of the diagram: >>> print(drawer.draw(diagram, grid, masked=[g * f])) \xymatrix{ A \ar[r]^{f} & B \ar[ld]^{g} \\ C & } Finally, the ``diagram_format`` argument can be used to specify the format string of the diagram. For example, to increase the spacing by 1 cm, proceeding as follows: >>> print(drawer.draw(diagram, grid, diagram_format="@+1cm")) \xymatrix@+1cm{ A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\ C & } """ # This method works in several steps. It starts by removing # the masked morphisms, if necessary, and then maps objects to # their positions in the grid (coordinate tuples). Remember # that objects are unique in ``Diagram`` and in the layout # produced by ``DiagramGrid``, so every object is mapped to a # single coordinate pair. # # The next step is the central step and is concerned with # analysing the morphisms of the diagram and deciding how to # draw them. For example, how to curve the arrows is decided # at this step. The bulk of the analysis is implemented in # ``_process_morphism``, to the result of which the # appropriate formatters are applied. # # The result of the previous step is a list of # ``ArrowStringDescription``. After the analysis and # application of formatters, some extra logic tries to assure # better positioning of morphism labels (for example, an # attempt is made to avoid the situations when arrows cross # labels). This functionality constitutes the next step and # is implemented in ``_push_labels_out``. Note that label # positions which have been set via a formatter are not # affected in this step. # # Finally, at the closing step, the array of # ``ArrowStringDescription`` and the layout information # incorporated in ``DiagramGrid`` are combined to produce the # resulting Xy-pic picture. This part of code lies in # ``_build_xypic_string``. if not masked: morphisms_props = grid.morphisms else: morphisms_props = {} for m, props in grid.morphisms.items(): if m in masked: continue morphisms_props[m] = props # Build the mapping between objects and their position in the # grid. object_coords = {} for i in range(grid.height): for j in range(grid.width): if grid[i, j]: object_coords[grid[i, j]] = (i, j) morphisms = sorted(morphisms_props, key=lambda m: XypicDiagramDrawer._morphism_sort_key( m, object_coords)) # Build the tuples defining the string representations of # morphisms. morphisms_str_info = {} for morphism in morphisms: string_description = self._process_morphism( diagram, grid, morphism, object_coords, morphisms, morphisms_str_info) if self.default_arrow_formatter: self.default_arrow_formatter(string_description) for prop in morphisms_props[morphism]: # prop is a Symbol. TODO: Find out why. if prop.name in self.arrow_formatters: formatter = self.arrow_formatters[prop.name] formatter(string_description) morphisms_str_info[morphism] = string_description # Reposition the labels a bit. self._push_labels_out(morphisms_str_info, grid, object_coords) return XypicDiagramDrawer._build_xypic_string( diagram, grid, morphisms, morphisms_str_info, diagram_format) def xypic_draw_diagram(diagram, masked=None, diagram_format="", groups=None, **hints): r""" Provides a shortcut combining :class:`DiagramGrid` and :class:`XypicDiagramDrawer`. Returns an Xy-pic presentation of ``diagram``. The argument ``masked`` is a list of morphisms which will be not be drawn. The argument ``diagram_format`` is the format string inserted after "\xymatrix". ``groups`` should be a set of logical groups. The ``hints`` will be passed directly to the constructor of :class:`DiagramGrid`. For more information about the arguments, see the docstrings of :class:`DiagramGrid` and ``XypicDiagramDrawer.draw``. Examples ======== >>> from sympy.categories import Object, NamedMorphism, Diagram >>> from sympy.categories import xypic_draw_diagram >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> diagram = Diagram([f, g], {g * f: "unique"}) >>> print(xypic_draw_diagram(diagram)) \xymatrix{ A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\ C & } See Also ======== XypicDiagramDrawer, DiagramGrid """ grid = DiagramGrid(diagram, groups, **hints) drawer = XypicDiagramDrawer() return drawer.draw(diagram, grid, masked, diagram_format) @doctest_depends_on(exe=('latex', 'dvipng'), modules=('pyglet',)) def preview_diagram(diagram, masked=None, diagram_format="", groups=None, output='png', viewer=None, euler=True, **hints): """ Combines the functionality of ``xypic_draw_diagram`` and ``sympy.printing.preview``. The arguments ``masked``, ``diagram_format``, ``groups``, and ``hints`` are passed to ``xypic_draw_diagram``, while ``output``, ``viewer, and ``euler`` are passed to ``preview``. Examples ======== >>> from sympy.categories import Object, NamedMorphism, Diagram >>> from sympy.categories import preview_diagram >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> d = Diagram([f, g], {g * f: "unique"}) >>> preview_diagram(d) See Also ======== XypicDiagramDrawer """ from sympy.printing import preview latex_output = xypic_draw_diagram(diagram, masked, diagram_format, groups, **hints) preview(latex_output, output, viewer, euler, ("xypic",))
d6d0c60004c02ff1fd79dc08ab8bf4def16b85da3eccadd3606fcf4063df7413
from sympy.core import S, Basic, Dict, Symbol, Tuple, sympify from sympy.core.compatibility import iterable from sympy.core.symbol import Str from sympy.sets import Set, FiniteSet, EmptySet class Class(Set): r""" The base class for any kind of class in the set-theoretic sense. Explanation =========== In axiomatic set theories, everything is a class. A class which can be a member of another class is a set. A class which is not a member of another class is a proper class. The class `\{1, 2\}` is a set; the class of all sets is a proper class. This class is essentially a synonym for :class:`sympy.core.Set`. The goal of this class is to assure easier migration to the eventual proper implementation of set theory. """ is_proper = False class Object(Symbol): """ The base class for any kind of object in an abstract category. Explanation =========== While technically any instance of :class:`~.Basic` will do, this class is the recommended way to create abstract objects in abstract categories. """ class Morphism(Basic): """ The base class for any morphism in an abstract category. Explanation =========== In abstract categories, a morphism is an arrow between two category objects. The object where the arrow starts is called the domain, while the object where the arrow ends is called the codomain. Two morphisms between the same pair of objects are considered to be the same morphisms. To distinguish between morphisms between the same objects use :class:`NamedMorphism`. It is prohibited to instantiate this class. Use one of the derived classes instead. See Also ======== IdentityMorphism, NamedMorphism, CompositeMorphism """ def __new__(cls, domain, codomain): raise(NotImplementedError( "Cannot instantiate Morphism. Use derived classes instead.")) @property def domain(self): """ Returns the domain of the morphism. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> f = NamedMorphism(A, B, "f") >>> f.domain Object("A") """ return self.args[0] @property def codomain(self): """ Returns the codomain of the morphism. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> f = NamedMorphism(A, B, "f") >>> f.codomain Object("B") """ return self.args[1] def compose(self, other): r""" Composes self with the supplied morphism. The order of elements in the composition is the usual order, i.e., to construct `g\circ f` use ``g.compose(f)``. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> g * f CompositeMorphism((NamedMorphism(Object("A"), Object("B"), "f"), NamedMorphism(Object("B"), Object("C"), "g"))) >>> (g * f).domain Object("A") >>> (g * f).codomain Object("C") """ return CompositeMorphism(other, self) def __mul__(self, other): r""" Composes self with the supplied morphism. The semantics of this operation is given by the following equation: ``g * f == g.compose(f)`` for composable morphisms ``g`` and ``f``. See Also ======== compose """ return self.compose(other) class IdentityMorphism(Morphism): """ Represents an identity morphism. Explanation =========== An identity morphism is a morphism with equal domain and codomain, which acts as an identity with respect to composition. Examples ======== >>> from sympy.categories import Object, NamedMorphism, IdentityMorphism >>> A = Object("A") >>> B = Object("B") >>> f = NamedMorphism(A, B, "f") >>> id_A = IdentityMorphism(A) >>> id_B = IdentityMorphism(B) >>> f * id_A == f True >>> id_B * f == f True See Also ======== Morphism """ def __new__(cls, domain): return Basic.__new__(cls, domain) @property def codomain(self): return self.domain class NamedMorphism(Morphism): """ Represents a morphism which has a name. Explanation =========== Names are used to distinguish between morphisms which have the same domain and codomain: two named morphisms are equal if they have the same domains, codomains, and names. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> f = NamedMorphism(A, B, "f") >>> f NamedMorphism(Object("A"), Object("B"), "f") >>> f.name 'f' See Also ======== Morphism """ def __new__(cls, domain, codomain, name): if not name: raise ValueError("Empty morphism names not allowed.") if not isinstance(name, Str): name = Str(name) return Basic.__new__(cls, domain, codomain, name) @property def name(self): """ Returns the name of the morphism. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> f = NamedMorphism(A, B, "f") >>> f.name 'f' """ return self.args[2].name class CompositeMorphism(Morphism): r""" Represents a morphism which is a composition of other morphisms. Explanation =========== Two composite morphisms are equal if the morphisms they were obtained from (components) are the same and were listed in the same order. The arguments to the constructor for this class should be listed in diagram order: to obtain the composition `g\circ f` from the instances of :class:`Morphism` ``g`` and ``f`` use ``CompositeMorphism(f, g)``. Examples ======== >>> from sympy.categories import Object, NamedMorphism, CompositeMorphism >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> g * f CompositeMorphism((NamedMorphism(Object("A"), Object("B"), "f"), NamedMorphism(Object("B"), Object("C"), "g"))) >>> CompositeMorphism(f, g) == g * f True """ @staticmethod def _add_morphism(t, morphism): """ Intelligently adds ``morphism`` to tuple ``t``. Explanation =========== If ``morphism`` is a composite morphism, its components are added to the tuple. If ``morphism`` is an identity, nothing is added to the tuple. No composability checks are performed. """ if isinstance(morphism, CompositeMorphism): # ``morphism`` is a composite morphism; we have to # denest its components. return t + morphism.components elif isinstance(morphism, IdentityMorphism): # ``morphism`` is an identity. Nothing happens. return t else: return t + Tuple(morphism) def __new__(cls, *components): if components and not isinstance(components[0], Morphism): # Maybe the user has explicitly supplied a list of # morphisms. return CompositeMorphism.__new__(cls, *components[0]) normalised_components = Tuple() for current, following in zip(components, components[1:]): if not isinstance(current, Morphism) or \ not isinstance(following, Morphism): raise TypeError("All components must be morphisms.") if current.codomain != following.domain: raise ValueError("Uncomposable morphisms.") normalised_components = CompositeMorphism._add_morphism( normalised_components, current) # We haven't added the last morphism to the list of normalised # components. Add it now. normalised_components = CompositeMorphism._add_morphism( normalised_components, components[-1]) if not normalised_components: # If ``normalised_components`` is empty, only identities # were supplied. Since they all were composable, they are # all the same identities. return components[0] elif len(normalised_components) == 1: # No sense to construct a whole CompositeMorphism. return normalised_components[0] return Basic.__new__(cls, normalised_components) @property def components(self): """ Returns the components of this composite morphism. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> (g * f).components (NamedMorphism(Object("A"), Object("B"), "f"), NamedMorphism(Object("B"), Object("C"), "g")) """ return self.args[0] @property def domain(self): """ Returns the domain of this composite morphism. The domain of the composite morphism is the domain of its first component. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> (g * f).domain Object("A") """ return self.components[0].domain @property def codomain(self): """ Returns the codomain of this composite morphism. The codomain of the composite morphism is the codomain of its last component. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> (g * f).codomain Object("C") """ return self.components[-1].codomain def flatten(self, new_name): """ Forgets the composite structure of this morphism. Explanation =========== If ``new_name`` is not empty, returns a :class:`NamedMorphism` with the supplied name, otherwise returns a :class:`Morphism`. In both cases the domain of the new morphism is the domain of this composite morphism and the codomain of the new morphism is the codomain of this composite morphism. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> (g * f).flatten("h") NamedMorphism(Object("A"), Object("C"), "h") """ return NamedMorphism(self.domain, self.codomain, new_name) class Category(Basic): r""" An (abstract) category. Explanation =========== A category [JoyOfCats] is a quadruple `\mbox{K} = (O, \hom, id, \circ)` consisting of * a (set-theoretical) class `O`, whose members are called `K`-objects, * for each pair `(A, B)` of `K`-objects, a set `\hom(A, B)` whose members are called `K`-morphisms from `A` to `B`, * for a each `K`-object `A`, a morphism `id:A\rightarrow A`, called the `K`-identity of `A`, * a composition law `\circ` associating with every `K`-morphisms `f:A\rightarrow B` and `g:B\rightarrow C` a `K`-morphism `g\circ f:A\rightarrow C`, called the composite of `f` and `g`. Composition is associative, `K`-identities are identities with respect to composition, and the sets `\hom(A, B)` are pairwise disjoint. This class knows nothing about its objects and morphisms. Concrete cases of (abstract) categories should be implemented as classes derived from this one. Certain instances of :class:`Diagram` can be asserted to be commutative in a :class:`Category` by supplying the argument ``commutative_diagrams`` in the constructor. Examples ======== >>> from sympy.categories import Object, NamedMorphism, Diagram, Category >>> from sympy import FiniteSet >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> d = Diagram([f, g]) >>> K = Category("K", commutative_diagrams=[d]) >>> K.commutative_diagrams == FiniteSet(d) True See Also ======== Diagram """ def __new__(cls, name, objects=EmptySet, commutative_diagrams=EmptySet): if not name: raise ValueError("A Category cannot have an empty name.") if not isinstance(name, Str): name = Str(name) if not isinstance(objects, Class): objects = Class(objects) new_category = Basic.__new__(cls, name, objects, FiniteSet(*commutative_diagrams)) return new_category @property def name(self): """ Returns the name of this category. Examples ======== >>> from sympy.categories import Category >>> K = Category("K") >>> K.name 'K' """ return self.args[0].name @property def objects(self): """ Returns the class of objects of this category. Examples ======== >>> from sympy.categories import Object, Category >>> from sympy import FiniteSet >>> A = Object("A") >>> B = Object("B") >>> K = Category("K", FiniteSet(A, B)) >>> K.objects Class({Object("A"), Object("B")}) """ return self.args[1] @property def commutative_diagrams(self): """ Returns the :class:`~.FiniteSet` of diagrams which are known to be commutative in this category. Examples ======== >>> from sympy.categories import Object, NamedMorphism, Diagram, Category >>> from sympy import FiniteSet >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> d = Diagram([f, g]) >>> K = Category("K", commutative_diagrams=[d]) >>> K.commutative_diagrams == FiniteSet(d) True """ return self.args[2] def hom(self, A, B): raise NotImplementedError( "hom-sets are not implemented in Category.") def all_morphisms(self): raise NotImplementedError( "Obtaining the class of morphisms is not implemented in Category.") class Diagram(Basic): r""" Represents a diagram in a certain category. Explanation =========== Informally, a diagram is a collection of objects of a category and certain morphisms between them. A diagram is still a monoid with respect to morphism composition; i.e., identity morphisms, as well as all composites of morphisms included in the diagram belong to the diagram. For a more formal approach to this notion see [Pare1970]. The components of composite morphisms are also added to the diagram. No properties are assigned to such morphisms by default. A commutative diagram is often accompanied by a statement of the following kind: "if such morphisms with such properties exist, then such morphisms which such properties exist and the diagram is commutative". To represent this, an instance of :class:`Diagram` includes a collection of morphisms which are the premises and another collection of conclusions. ``premises`` and ``conclusions`` associate morphisms belonging to the corresponding categories with the :class:`~.FiniteSet`'s of their properties. The set of properties of a composite morphism is the intersection of the sets of properties of its components. The domain and codomain of a conclusion morphism should be among the domains and codomains of the morphisms listed as the premises of a diagram. No checks are carried out of whether the supplied object and morphisms do belong to one and the same category. Examples ======== >>> from sympy.categories import Object, NamedMorphism, Diagram >>> from sympy import pprint, default_sort_key >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> d = Diagram([f, g]) >>> premises_keys = sorted(d.premises.keys(), key=default_sort_key) >>> pprint(premises_keys, use_unicode=False) [g*f:A-->C, id:A-->A, id:B-->B, id:C-->C, f:A-->B, g:B-->C] >>> pprint(d.premises, use_unicode=False) {g*f:A-->C: EmptySet, id:A-->A: EmptySet, id:B-->B: EmptySet, id:C-->C: EmptyS et, f:A-->B: EmptySet, g:B-->C: EmptySet} >>> d = Diagram([f, g], {g * f: "unique"}) >>> pprint(d.conclusions,use_unicode=False) {g*f:A-->C: {unique}} References ========== [Pare1970] B. Pareigis: Categories and functors. Academic Press, 1970. """ @staticmethod def _set_dict_union(dictionary, key, value): """ If ``key`` is in ``dictionary``, set the new value of ``key`` to be the union between the old value and ``value``. Otherwise, set the value of ``key`` to ``value. Returns ``True`` if the key already was in the dictionary and ``False`` otherwise. """ if key in dictionary: dictionary[key] = dictionary[key] | value return True else: dictionary[key] = value return False @staticmethod def _add_morphism_closure(morphisms, morphism, props, add_identities=True, recurse_composites=True): """ Adds a morphism and its attributes to the supplied dictionary ``morphisms``. If ``add_identities`` is True, also adds the identity morphisms for the domain and the codomain of ``morphism``. """ if not Diagram._set_dict_union(morphisms, morphism, props): # We have just added a new morphism. if isinstance(morphism, IdentityMorphism): if props: # Properties for identity morphisms don't really # make sense, because very much is known about # identity morphisms already, so much that they # are trivial. Having properties for identity # morphisms would only be confusing. raise ValueError( "Instances of IdentityMorphism cannot have properties.") return if add_identities: empty = EmptySet id_dom = IdentityMorphism(morphism.domain) id_cod = IdentityMorphism(morphism.codomain) Diagram._set_dict_union(morphisms, id_dom, empty) Diagram._set_dict_union(morphisms, id_cod, empty) for existing_morphism, existing_props in list(morphisms.items()): new_props = existing_props & props if morphism.domain == existing_morphism.codomain: left = morphism * existing_morphism Diagram._set_dict_union(morphisms, left, new_props) if morphism.codomain == existing_morphism.domain: right = existing_morphism * morphism Diagram._set_dict_union(morphisms, right, new_props) if isinstance(morphism, CompositeMorphism) and recurse_composites: # This is a composite morphism, add its components as # well. empty = EmptySet for component in morphism.components: Diagram._add_morphism_closure(morphisms, component, empty, add_identities) def __new__(cls, *args): """ Construct a new instance of Diagram. Explanation =========== If no arguments are supplied, an empty diagram is created. If at least an argument is supplied, ``args[0]`` is interpreted as the premises of the diagram. If ``args[0]`` is a list, it is interpreted as a list of :class:`Morphism`'s, in which each :class:`Morphism` has an empty set of properties. If ``args[0]`` is a Python dictionary or a :class:`Dict`, it is interpreted as a dictionary associating to some :class:`Morphism`'s some properties. If at least two arguments are supplied ``args[1]`` is interpreted as the conclusions of the diagram. The type of ``args[1]`` is interpreted in exactly the same way as the type of ``args[0]``. If only one argument is supplied, the diagram has no conclusions. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> from sympy.categories import IdentityMorphism, Diagram >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> d = Diagram([f, g]) >>> IdentityMorphism(A) in d.premises.keys() True >>> g * f in d.premises.keys() True >>> d = Diagram([f, g], {g * f: "unique"}) >>> d.conclusions[g * f] {unique} """ premises = {} conclusions = {} # Here we will keep track of the objects which appear in the # premises. objects = EmptySet if len(args) >= 1: # We've got some premises in the arguments. premises_arg = args[0] if isinstance(premises_arg, list): # The user has supplied a list of morphisms, none of # which have any attributes. empty = EmptySet for morphism in premises_arg: objects |= FiniteSet(morphism.domain, morphism.codomain) Diagram._add_morphism_closure(premises, morphism, empty) elif isinstance(premises_arg, dict) or isinstance(premises_arg, Dict): # The user has supplied a dictionary of morphisms and # their properties. for morphism, props in premises_arg.items(): objects |= FiniteSet(morphism.domain, morphism.codomain) Diagram._add_morphism_closure( premises, morphism, FiniteSet(*props) if iterable(props) else FiniteSet(props)) if len(args) >= 2: # We also have some conclusions. conclusions_arg = args[1] if isinstance(conclusions_arg, list): # The user has supplied a list of morphisms, none of # which have any attributes. empty = EmptySet for morphism in conclusions_arg: # Check that no new objects appear in conclusions. if ((sympify(objects.contains(morphism.domain)) is S.true) and (sympify(objects.contains(morphism.codomain)) is S.true)): # No need to add identities and recurse # composites this time. Diagram._add_morphism_closure( conclusions, morphism, empty, add_identities=False, recurse_composites=False) elif isinstance(conclusions_arg, dict) or \ isinstance(conclusions_arg, Dict): # The user has supplied a dictionary of morphisms and # their properties. for morphism, props in conclusions_arg.items(): # Check that no new objects appear in conclusions. if (morphism.domain in objects) and \ (morphism.codomain in objects): # No need to add identities and recurse # composites this time. Diagram._add_morphism_closure( conclusions, morphism, FiniteSet(*props) if iterable(props) else FiniteSet(props), add_identities=False, recurse_composites=False) return Basic.__new__(cls, Dict(premises), Dict(conclusions), objects) @property def premises(self): """ Returns the premises of this diagram. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> from sympy.categories import IdentityMorphism, Diagram >>> from sympy import pretty >>> A = Object("A") >>> B = Object("B") >>> f = NamedMorphism(A, B, "f") >>> id_A = IdentityMorphism(A) >>> id_B = IdentityMorphism(B) >>> d = Diagram([f]) >>> print(pretty(d.premises, use_unicode=False)) {id:A-->A: EmptySet, id:B-->B: EmptySet, f:A-->B: EmptySet} """ return self.args[0] @property def conclusions(self): """ Returns the conclusions of this diagram. Examples ======== >>> from sympy.categories import Object, NamedMorphism >>> from sympy.categories import IdentityMorphism, Diagram >>> from sympy import FiniteSet >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> d = Diagram([f, g]) >>> IdentityMorphism(A) in d.premises.keys() True >>> g * f in d.premises.keys() True >>> d = Diagram([f, g], {g * f: "unique"}) >>> d.conclusions[g * f] == FiniteSet("unique") True """ return self.args[1] @property def objects(self): """ Returns the :class:`~.FiniteSet` of objects that appear in this diagram. Examples ======== >>> from sympy.categories import Object, NamedMorphism, Diagram >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> d = Diagram([f, g]) >>> d.objects {Object("A"), Object("B"), Object("C")} """ return self.args[2] def hom(self, A, B): """ Returns a 2-tuple of sets of morphisms between objects ``A`` and ``B``: one set of morphisms listed as premises, and the other set of morphisms listed as conclusions. Examples ======== >>> from sympy.categories import Object, NamedMorphism, Diagram >>> from sympy import pretty >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> d = Diagram([f, g], {g * f: "unique"}) >>> print(pretty(d.hom(A, C), use_unicode=False)) ({g*f:A-->C}, {g*f:A-->C}) See Also ======== Object, Morphism """ premises = EmptySet conclusions = EmptySet for morphism in self.premises.keys(): if (morphism.domain == A) and (morphism.codomain == B): premises |= FiniteSet(morphism) for morphism in self.conclusions.keys(): if (morphism.domain == A) and (morphism.codomain == B): conclusions |= FiniteSet(morphism) return (premises, conclusions) def is_subdiagram(self, diagram): """ Checks whether ``diagram`` is a subdiagram of ``self``. Diagram `D'` is a subdiagram of `D` if all premises (conclusions) of `D'` are contained in the premises (conclusions) of `D`. The morphisms contained both in `D'` and `D` should have the same properties for `D'` to be a subdiagram of `D`. Examples ======== >>> from sympy.categories import Object, NamedMorphism, Diagram >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> d = Diagram([f, g], {g * f: "unique"}) >>> d1 = Diagram([f]) >>> d.is_subdiagram(d1) True >>> d1.is_subdiagram(d) False """ premises = all((m in self.premises) and (diagram.premises[m] == self.premises[m]) for m in diagram.premises) if not premises: return False conclusions = all((m in self.conclusions) and (diagram.conclusions[m] == self.conclusions[m]) for m in diagram.conclusions) # Premises is surely ``True`` here. return conclusions def subdiagram_from_objects(self, objects): """ If ``objects`` is a subset of the objects of ``self``, returns a diagram which has as premises all those premises of ``self`` which have a domains and codomains in ``objects``, likewise for conclusions. Properties are preserved. Examples ======== >>> from sympy.categories import Object, NamedMorphism, Diagram >>> from sympy import FiniteSet >>> A = Object("A") >>> B = Object("B") >>> C = Object("C") >>> f = NamedMorphism(A, B, "f") >>> g = NamedMorphism(B, C, "g") >>> d = Diagram([f, g], {f: "unique", g*f: "veryunique"}) >>> d1 = d.subdiagram_from_objects(FiniteSet(A, B)) >>> d1 == Diagram([f], {f: "unique"}) True """ if not objects.is_subset(self.objects): raise ValueError( "Supplied objects should all belong to the diagram.") new_premises = {} for morphism, props in self.premises.items(): if ((sympify(objects.contains(morphism.domain)) is S.true) and (sympify(objects.contains(morphism.codomain)) is S.true)): new_premises[morphism] = props new_conclusions = {} for morphism, props in self.conclusions.items(): if ((sympify(objects.contains(morphism.domain)) is S.true) and (sympify(objects.contains(morphism.codomain)) is S.true)): new_conclusions[morphism] = props return Diagram(new_premises, new_conclusions)
a9c320b44c3e58cd7b8fb2b4963764b03893a35821e20a6ba4b4d7f11f9695c9
# References : # http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/ # https://en.wikipedia.org/wiki/Quaternion from sympy import S, Rational from sympy import re, im, conjugate, sign from sympy import sqrt, sin, cos, acos, exp, ln from sympy import trigsimp from sympy import integrate from sympy import Matrix from sympy import sympify from sympy.core.evalf import prec_to_dps from sympy.core.expr import Expr class Quaternion(Expr): """Provides basic quaternion operations. Quaternion objects can be instantiated as Quaternion(a, b, c, d) as in (a + b*i + c*j + d*k). Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q 1 + 2*i + 3*j + 4*k Quaternions over complex fields can be defined as : >>> from sympy.algebras.quaternion import Quaternion >>> from sympy import symbols, I >>> x = symbols('x') >>> q1 = Quaternion(x, x**3, x, x**2, real_field = False) >>> q2 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) >>> q1 x + x**3*i + x*j + x**2*k >>> q2 (3 + 4*I) + (2 + 5*I)*i + 0*j + (7 + 8*I)*k """ _op_priority = 11.0 is_commutative = False def __new__(cls, a=0, b=0, c=0, d=0, real_field=True): a = sympify(a) b = sympify(b) c = sympify(c) d = sympify(d) if any(i.is_commutative is False for i in [a, b, c, d]): raise ValueError("arguments have to be commutative") else: obj = Expr.__new__(cls, a, b, c, d) obj._a = a obj._b = b obj._c = c obj._d = d obj._real_field = real_field return obj @property def a(self): return self._a @property def b(self): return self._b @property def c(self): return self._c @property def d(self): return self._d @property def real_field(self): return self._real_field @classmethod def from_axis_angle(cls, vector, angle): """Returns a rotation quaternion given the axis and the angle of rotation. Parameters ========== vector : tuple of three numbers The vector representation of the given axis. angle : number The angle by which axis is rotated (in radians). Returns ======= Quaternion The normalized rotation quaternion calculated from the given axis and the angle of rotation. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> from sympy import pi, sqrt >>> q = Quaternion.from_axis_angle((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), 2*pi/3) >>> q 1/2 + 1/2*i + 1/2*j + 1/2*k """ (x, y, z) = vector norm = sqrt(x**2 + y**2 + z**2) (x, y, z) = (x / norm, y / norm, z / norm) s = sin(angle * S.Half) a = cos(angle * S.Half) b = x * s c = y * s d = z * s # note that this quaternion is already normalized by construction: # c^2 + (s*x)^2 + (s*y)^2 + (s*z)^2 = c^2 + s^2*(x^2 + y^2 + z^2) = c^2 + s^2 * 1 = c^2 + s^2 = 1 # so, what we return is a normalized quaternion return cls(a, b, c, d) @classmethod def from_rotation_matrix(cls, M): """Returns the equivalent quaternion of a matrix. The quaternion will be normalized only if the matrix is special orthogonal (orthogonal and det(M) = 1). Parameters ========== M : Matrix Input matrix to be converted to equivalent quaternion. M must be special orthogonal (orthogonal and det(M) = 1) for the quaternion to be normalized. Returns ======= Quaternion The quaternion equivalent to given matrix. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> from sympy import Matrix, symbols, cos, sin, trigsimp >>> x = symbols('x') >>> M = Matrix([[cos(x), -sin(x), 0], [sin(x), cos(x), 0], [0, 0, 1]]) >>> q = trigsimp(Quaternion.from_rotation_matrix(M)) >>> q sqrt(2)*sqrt(cos(x) + 1)/2 + 0*i + 0*j + sqrt(2 - 2*cos(x))*sign(sin(x))/2*k """ absQ = M.det()**Rational(1, 3) a = sqrt(absQ + M[0, 0] + M[1, 1] + M[2, 2]) / 2 b = sqrt(absQ + M[0, 0] - M[1, 1] - M[2, 2]) / 2 c = sqrt(absQ - M[0, 0] + M[1, 1] - M[2, 2]) / 2 d = sqrt(absQ - M[0, 0] - M[1, 1] + M[2, 2]) / 2 b = b * sign(M[2, 1] - M[1, 2]) c = c * sign(M[0, 2] - M[2, 0]) d = d * sign(M[1, 0] - M[0, 1]) return Quaternion(a, b, c, d) def __add__(self, other): return self.add(other) def __radd__(self, other): return self.add(other) def __sub__(self, other): return self.add(other*-1) def __mul__(self, other): return self._generic_mul(self, other) def __rmul__(self, other): return self._generic_mul(other, self) def __pow__(self, p): return self.pow(p) def __neg__(self): return Quaternion(-self._a, -self._b, -self._c, -self.d) def __truediv__(self, other): return self * sympify(other)**-1 def __rtruediv__(self, other): return sympify(other) * self**-1 def _eval_Integral(self, *args): return self.integrate(*args) def diff(self, *symbols, **kwargs): kwargs.setdefault('evaluate', True) return self.func(*[a.diff(*symbols, **kwargs) for a in self.args]) def add(self, other): """Adds quaternions. Parameters ========== other : Quaternion The quaternion to add to current (self) quaternion. Returns ======= Quaternion The resultant quaternion after adding self to other Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> from sympy import symbols >>> q1 = Quaternion(1, 2, 3, 4) >>> q2 = Quaternion(5, 6, 7, 8) >>> q1.add(q2) 6 + 8*i + 10*j + 12*k >>> q1 + 5 6 + 2*i + 3*j + 4*k >>> x = symbols('x', real = True) >>> q1.add(x) (x + 1) + 2*i + 3*j + 4*k Quaternions over complex fields : >>> from sympy.algebras.quaternion import Quaternion >>> from sympy import I >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) >>> q3.add(2 + 3*I) (5 + 7*I) + (2 + 5*I)*i + 0*j + (7 + 8*I)*k """ q1 = self q2 = sympify(other) # If q2 is a number or a sympy expression instead of a quaternion if not isinstance(q2, Quaternion): if q1.real_field and q2.is_complex: return Quaternion(re(q2) + q1.a, im(q2) + q1.b, q1.c, q1.d) elif q2.is_commutative: return Quaternion(q1.a + q2, q1.b, q1.c, q1.d) else: raise ValueError("Only commutative expressions can be added with a Quaternion.") return Quaternion(q1.a + q2.a, q1.b + q2.b, q1.c + q2.c, q1.d + q2.d) def mul(self, other): """Multiplies quaternions. Parameters ========== other : Quaternion or symbol The quaternion to multiply to current (self) quaternion. Returns ======= Quaternion The resultant quaternion after multiplying self with other Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> from sympy import symbols >>> q1 = Quaternion(1, 2, 3, 4) >>> q2 = Quaternion(5, 6, 7, 8) >>> q1.mul(q2) (-60) + 12*i + 30*j + 24*k >>> q1.mul(2) 2 + 4*i + 6*j + 8*k >>> x = symbols('x', real = True) >>> q1.mul(x) x + 2*x*i + 3*x*j + 4*x*k Quaternions over complex fields : >>> from sympy.algebras.quaternion import Quaternion >>> from sympy import I >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) >>> q3.mul(2 + 3*I) (2 + 3*I)*(3 + 4*I) + (2 + 3*I)*(2 + 5*I)*i + 0*j + (2 + 3*I)*(7 + 8*I)*k """ return self._generic_mul(self, other) @staticmethod def _generic_mul(q1, q2): """Generic multiplication. Parameters ========== q1 : Quaternion or symbol q2 : Quaternion or symbol It's important to note that if neither q1 nor q2 is a Quaternion, this function simply returns q1 * q2. Returns ======= Quaternion The resultant quaternion after multiplying q1 and q2 Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> from sympy import Symbol >>> q1 = Quaternion(1, 2, 3, 4) >>> q2 = Quaternion(5, 6, 7, 8) >>> Quaternion._generic_mul(q1, q2) (-60) + 12*i + 30*j + 24*k >>> Quaternion._generic_mul(q1, 2) 2 + 4*i + 6*j + 8*k >>> x = Symbol('x', real = True) >>> Quaternion._generic_mul(q1, x) x + 2*x*i + 3*x*j + 4*x*k Quaternions over complex fields : >>> from sympy.algebras.quaternion import Quaternion >>> from sympy import I >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) >>> Quaternion._generic_mul(q3, 2 + 3*I) (2 + 3*I)*(3 + 4*I) + (2 + 3*I)*(2 + 5*I)*i + 0*j + (2 + 3*I)*(7 + 8*I)*k """ q1 = sympify(q1) q2 = sympify(q2) # None is a Quaternion: if not isinstance(q1, Quaternion) and not isinstance(q2, Quaternion): return q1 * q2 # If q1 is a number or a sympy expression instead of a quaternion if not isinstance(q1, Quaternion): if q2.real_field and q1.is_complex: return Quaternion(re(q1), im(q1), 0, 0) * q2 elif q1.is_commutative: return Quaternion(q1 * q2.a, q1 * q2.b, q1 * q2.c, q1 * q2.d) else: raise ValueError("Only commutative expressions can be multiplied with a Quaternion.") # If q2 is a number or a sympy expression instead of a quaternion if not isinstance(q2, Quaternion): if q1.real_field and q2.is_complex: return q1 * Quaternion(re(q2), im(q2), 0, 0) elif q2.is_commutative: return Quaternion(q2 * q1.a, q2 * q1.b, q2 * q1.c, q2 * q1.d) else: raise ValueError("Only commutative expressions can be multiplied with a Quaternion.") return Quaternion(-q1.b*q2.b - q1.c*q2.c - q1.d*q2.d + q1.a*q2.a, q1.b*q2.a + q1.c*q2.d - q1.d*q2.c + q1.a*q2.b, -q1.b*q2.d + q1.c*q2.a + q1.d*q2.b + q1.a*q2.c, q1.b*q2.c - q1.c*q2.b + q1.d*q2.a + q1.a * q2.d) def _eval_conjugate(self): """Returns the conjugate of the quaternion.""" q = self return Quaternion(q.a, -q.b, -q.c, -q.d) def norm(self): """Returns the norm of the quaternion.""" q = self # trigsimp is used to simplify sin(x)^2 + cos(x)^2 (these terms # arise when from_axis_angle is used). return sqrt(trigsimp(q.a**2 + q.b**2 + q.c**2 + q.d**2)) def normalize(self): """Returns the normalized form of the quaternion.""" q = self return q * (1/q.norm()) def inverse(self): """Returns the inverse of the quaternion.""" q = self if not q.norm(): raise ValueError("Cannot compute inverse for a quaternion with zero norm") return conjugate(q) * (1/q.norm()**2) def pow(self, p): """Finds the pth power of the quaternion. Parameters ========== p : int Power to be applied on quaternion. Returns ======= Quaternion Returns the p-th power of the current quaternion. Returns the inverse if p = -1. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q.pow(4) 668 + (-224)*i + (-336)*j + (-448)*k """ p = sympify(p) q = self if p == -1: return q.inverse() res = 1 if not p.is_Integer: return NotImplemented if p < 0: q, p = q.inverse(), -p while p > 0: if p % 2 == 1: res = q * res p = p//2 q = q * q return res def exp(self): """Returns the exponential of q (e^q). Returns ======= Quaternion Exponential of q (e^q). Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q.exp() E*cos(sqrt(29)) + 2*sqrt(29)*E*sin(sqrt(29))/29*i + 3*sqrt(29)*E*sin(sqrt(29))/29*j + 4*sqrt(29)*E*sin(sqrt(29))/29*k """ # exp(q) = e^a(cos||v|| + v/||v||*sin||v||) q = self vector_norm = sqrt(q.b**2 + q.c**2 + q.d**2) a = exp(q.a) * cos(vector_norm) b = exp(q.a) * sin(vector_norm) * q.b / vector_norm c = exp(q.a) * sin(vector_norm) * q.c / vector_norm d = exp(q.a) * sin(vector_norm) * q.d / vector_norm return Quaternion(a, b, c, d) def _ln(self): """Returns the natural logarithm of the quaternion (_ln(q)). Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q._ln() log(sqrt(30)) + 2*sqrt(29)*acos(sqrt(30)/30)/29*i + 3*sqrt(29)*acos(sqrt(30)/30)/29*j + 4*sqrt(29)*acos(sqrt(30)/30)/29*k """ # _ln(q) = _ln||q|| + v/||v||*arccos(a/||q||) q = self vector_norm = sqrt(q.b**2 + q.c**2 + q.d**2) q_norm = q.norm() a = ln(q_norm) b = q.b * acos(q.a / q_norm) / vector_norm c = q.c * acos(q.a / q_norm) / vector_norm d = q.d * acos(q.a / q_norm) / vector_norm return Quaternion(a, b, c, d) def _eval_evalf(self, prec): """Returns the floating point approximations (decimal numbers) of the quaternion. Returns ======= Quaternion Floating point approximations of quaternion(self) Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> from sympy import sqrt >>> q = Quaternion(1/sqrt(1), 1/sqrt(2), 1/sqrt(3), 1/sqrt(4)) >>> q.evalf() 1.00000000000000 + 0.707106781186547*i + 0.577350269189626*j + 0.500000000000000*k """ return Quaternion(*[arg.evalf(n=prec_to_dps(prec)) for arg in self.args]) def pow_cos_sin(self, p): """Computes the pth power in the cos-sin form. Parameters ========== p : int Power to be applied on quaternion. Returns ======= Quaternion The p-th power in the cos-sin form. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q.pow_cos_sin(4) 900*cos(4*acos(sqrt(30)/30)) + 1800*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*i + 2700*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*j + 3600*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*k """ # q = ||q||*(cos(a) + u*sin(a)) # q^p = ||q||^p * (cos(p*a) + u*sin(p*a)) q = self (v, angle) = q.to_axis_angle() q2 = Quaternion.from_axis_angle(v, p * angle) return q2 * (q.norm()**p) def integrate(self, *args): """Computes integration of quaternion. Returns ======= Quaternion Integration of the quaternion(self) with the given variable. Examples ======== Indefinite Integral of quaternion : >>> from sympy.algebras.quaternion import Quaternion >>> from sympy.abc import x >>> q = Quaternion(1, 2, 3, 4) >>> q.integrate(x) x + 2*x*i + 3*x*j + 4*x*k Definite integral of quaternion : >>> from sympy.algebras.quaternion import Quaternion >>> from sympy.abc import x >>> q = Quaternion(1, 2, 3, 4) >>> q.integrate((x, 1, 5)) 4 + 8*i + 12*j + 16*k """ # TODO: is this expression correct? return Quaternion(integrate(self.a, *args), integrate(self.b, *args), integrate(self.c, *args), integrate(self.d, *args)) @staticmethod def rotate_point(pin, r): """Returns the coordinates of the point pin(a 3 tuple) after rotation. Parameters ========== pin : tuple A 3-element tuple of coordinates of a point which needs to be rotated. r : Quaternion or tuple Axis and angle of rotation. It's important to note that when r is a tuple, it must be of the form (axis, angle) Returns ======= tuple The coordinates of the point after rotation. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> from sympy import symbols, trigsimp, cos, sin >>> x = symbols('x') >>> q = Quaternion(cos(x/2), 0, 0, sin(x/2)) >>> trigsimp(Quaternion.rotate_point((1, 1, 1), q)) (sqrt(2)*cos(x + pi/4), sqrt(2)*sin(x + pi/4), 1) >>> (axis, angle) = q.to_axis_angle() >>> trigsimp(Quaternion.rotate_point((1, 1, 1), (axis, angle))) (sqrt(2)*cos(x + pi/4), sqrt(2)*sin(x + pi/4), 1) """ if isinstance(r, tuple): # if r is of the form (vector, angle) q = Quaternion.from_axis_angle(r[0], r[1]) else: # if r is a quaternion q = r.normalize() pout = q * Quaternion(0, pin[0], pin[1], pin[2]) * conjugate(q) return (pout.b, pout.c, pout.d) def to_axis_angle(self): """Returns the axis and angle of rotation of a quaternion Returns ======= tuple Tuple of (axis, angle) Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 1, 1, 1) >>> (axis, angle) = q.to_axis_angle() >>> axis (sqrt(3)/3, sqrt(3)/3, sqrt(3)/3) >>> angle 2*pi/3 """ q = self if q.a.is_negative: q = q * -1 q = q.normalize() angle = trigsimp(2 * acos(q.a)) # Since quaternion is normalised, q.a is less than 1. s = sqrt(1 - q.a*q.a) x = trigsimp(q.b / s) y = trigsimp(q.c / s) z = trigsimp(q.d / s) v = (x, y, z) t = (v, angle) return t def to_rotation_matrix(self, v=None): """Returns the equivalent rotation transformation matrix of the quaternion which represents rotation about the origin if v is not passed. Parameters ========== v : tuple or None Default value: None Returns ======= tuple Returns the equivalent rotation transformation matrix of the quaternion which represents rotation about the origin if v is not passed. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> from sympy import symbols, trigsimp, cos, sin >>> x = symbols('x') >>> q = Quaternion(cos(x/2), 0, 0, sin(x/2)) >>> trigsimp(q.to_rotation_matrix()) Matrix([ [cos(x), -sin(x), 0], [sin(x), cos(x), 0], [ 0, 0, 1]]) Generates a 4x4 transformation matrix (used for rotation about a point other than the origin) if the point(v) is passed as an argument. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> from sympy import symbols, trigsimp, cos, sin >>> x = symbols('x') >>> q = Quaternion(cos(x/2), 0, 0, sin(x/2)) >>> trigsimp(q.to_rotation_matrix((1, 1, 1))) Matrix([ [cos(x), -sin(x), 0, sin(x) - cos(x) + 1], [sin(x), cos(x), 0, -sin(x) - cos(x) + 1], [ 0, 0, 1, 0], [ 0, 0, 0, 1]]) """ q = self s = q.norm()**-2 m00 = 1 - 2*s*(q.c**2 + q.d**2) m01 = 2*s*(q.b*q.c - q.d*q.a) m02 = 2*s*(q.b*q.d + q.c*q.a) m10 = 2*s*(q.b*q.c + q.d*q.a) m11 = 1 - 2*s*(q.b**2 + q.d**2) m12 = 2*s*(q.c*q.d - q.b*q.a) m20 = 2*s*(q.b*q.d - q.c*q.a) m21 = 2*s*(q.c*q.d + q.b*q.a) m22 = 1 - 2*s*(q.b**2 + q.c**2) if not v: return Matrix([[m00, m01, m02], [m10, m11, m12], [m20, m21, m22]]) else: (x, y, z) = v m03 = x - x*m00 - y*m01 - z*m02 m13 = y - x*m10 - y*m11 - z*m12 m23 = z - x*m20 - y*m21 - z*m22 m30 = m31 = m32 = 0 m33 = 1 return Matrix([[m00, m01, m02, m03], [m10, m11, m12, m13], [m20, m21, m22, m23], [m30, m31, m32, m33]])
4de0aaf2dff1894f3368d1b5751aa9a6e12386574dae309b16500e31abbaa3b0
""" This file contains some classical ciphers and routines implementing a linear-feedback shift register (LFSR) and the Diffie-Hellman key exchange. .. warning:: This module is intended for educational purposes only. Do not use the functions in this module for real cryptographic applications. If you wish to encrypt real data, we recommend using something like the `cryptography <https://cryptography.io/en/latest/>`_ module. """ from string import whitespace, ascii_uppercase as uppercase, printable from functools import reduce import warnings from itertools import cycle from sympy import nextprime from sympy.core import Rational, Symbol from sympy.core.numbers import igcdex, mod_inverse, igcd from sympy.core.compatibility import as_int from sympy.matrices import Matrix from sympy.ntheory import isprime, primitive_root, factorint from sympy.polys.domains import FF from sympy.polys.polytools import gcd, Poly from sympy.utilities.misc import filldedent, translate from sympy.utilities.iterables import uniq, multiset from sympy.testing.randtest import _randrange, _randint class NonInvertibleCipherWarning(RuntimeWarning): """A warning raised if the cipher is not invertible.""" def __init__(self, msg): self.fullMessage = msg def __str__(self): return '\n\t' + self.fullMessage def warn(self, stacklevel=2): warnings.warn(self, stacklevel=stacklevel) def AZ(s=None): """Return the letters of ``s`` in uppercase. In case more than one string is passed, each of them will be processed and a list of upper case strings will be returned. Examples ======== >>> from sympy.crypto.crypto import AZ >>> AZ('Hello, world!') 'HELLOWORLD' >>> AZ('Hello, world!'.split()) ['HELLO', 'WORLD'] See Also ======== check_and_join """ if not s: return uppercase t = type(s) is str if t: s = [s] rv = [check_and_join(i.upper().split(), uppercase, filter=True) for i in s] if t: return rv[0] return rv bifid5 = AZ().replace('J', '') bifid6 = AZ() + '0123456789' bifid10 = printable def padded_key(key, symbols): """Return a string of the distinct characters of ``symbols`` with those of ``key`` appearing first. A ValueError is raised if a) there are duplicate characters in ``symbols`` or b) there are characters in ``key`` that are not in ``symbols``. Examples ======== >>> from sympy.crypto.crypto import padded_key >>> padded_key('PUPPY', 'OPQRSTUVWXY') 'PUYOQRSTVWX' >>> padded_key('RSA', 'ARTIST') Traceback (most recent call last): ... ValueError: duplicate characters in symbols: T """ syms = list(uniq(symbols)) if len(syms) != len(symbols): extra = ''.join(sorted({ i for i in symbols if symbols.count(i) > 1})) raise ValueError('duplicate characters in symbols: %s' % extra) extra = set(key) - set(syms) if extra: raise ValueError( 'characters in key but not symbols: %s' % ''.join( sorted(extra))) key0 = ''.join(list(uniq(key))) # remove from syms characters in key0 return key0 + translate(''.join(syms), None, key0) def check_and_join(phrase, symbols=None, filter=None): """ Joins characters of ``phrase`` and if ``symbols`` is given, raises an error if any character in ``phrase`` is not in ``symbols``. Parameters ========== phrase String or list of strings to be returned as a string. symbols Iterable of characters allowed in ``phrase``. If ``symbols`` is ``None``, no checking is performed. Examples ======== >>> from sympy.crypto.crypto import check_and_join >>> check_and_join('a phrase') 'a phrase' >>> check_and_join('a phrase'.upper().split()) 'APHRASE' >>> check_and_join('a phrase!'.upper().split(), 'ARE', filter=True) 'ARAE' >>> check_and_join('a phrase!'.upper().split(), 'ARE') Traceback (most recent call last): ... ValueError: characters in phrase but not symbols: "!HPS" """ rv = ''.join(''.join(phrase)) if symbols is not None: symbols = check_and_join(symbols) missing = ''.join(list(sorted(set(rv) - set(symbols)))) if missing: if not filter: raise ValueError( 'characters in phrase but not symbols: "%s"' % missing) rv = translate(rv, None, missing) return rv def _prep(msg, key, alp, default=None): if not alp: if not default: alp = AZ() msg = AZ(msg) key = AZ(key) else: alp = default else: alp = ''.join(alp) key = check_and_join(key, alp, filter=True) msg = check_and_join(msg, alp, filter=True) return msg, key, alp def cycle_list(k, n): """ Returns the elements of the list ``range(n)`` shifted to the left by ``k`` (so the list starts with ``k`` (mod ``n``)). Examples ======== >>> from sympy.crypto.crypto import cycle_list >>> cycle_list(3, 10) [3, 4, 5, 6, 7, 8, 9, 0, 1, 2] """ k = k % n return list(range(k, n)) + list(range(k)) ######## shift cipher examples ############ def encipher_shift(msg, key, symbols=None): """ Performs shift cipher encryption on plaintext msg, and returns the ciphertext. Parameters ========== key : int The secret key. msg : str Plaintext of upper-case letters. Returns ======= str Ciphertext of upper-case letters. Examples ======== >>> from sympy.crypto.crypto import encipher_shift, decipher_shift >>> msg = "GONAVYBEATARMY" >>> ct = encipher_shift(msg, 1); ct 'HPOBWZCFBUBSNZ' To decipher the shifted text, change the sign of the key: >>> encipher_shift(ct, -1) 'GONAVYBEATARMY' There is also a convenience function that does this with the original key: >>> decipher_shift(ct, 1) 'GONAVYBEATARMY' Notes ===== ALGORITHM: STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``msg`` a list ``L1`` of corresponding integers. 2. Compute from the list ``L1`` a new list ``L2``, given by adding ``(k mod 26)`` to each element in ``L1``. 3. Compute from the list ``L2`` a string ``ct`` of corresponding letters. The shift cipher is also called the Caesar cipher, after Julius Caesar, who, according to Suetonius, used it with a shift of three to protect messages of military significance. Caesar's nephew Augustus reportedly used a similar cipher, but with a right shift of 1. References ========== .. [1] https://en.wikipedia.org/wiki/Caesar_cipher .. [2] http://mathworld.wolfram.com/CaesarsMethod.html See Also ======== decipher_shift """ msg, _, A = _prep(msg, '', symbols) shift = len(A) - key % len(A) key = A[shift:] + A[:shift] return translate(msg, key, A) def decipher_shift(msg, key, symbols=None): """ Return the text by shifting the characters of ``msg`` to the left by the amount given by ``key``. Examples ======== >>> from sympy.crypto.crypto import encipher_shift, decipher_shift >>> msg = "GONAVYBEATARMY" >>> ct = encipher_shift(msg, 1); ct 'HPOBWZCFBUBSNZ' To decipher the shifted text, change the sign of the key: >>> encipher_shift(ct, -1) 'GONAVYBEATARMY' Or use this function with the original key: >>> decipher_shift(ct, 1) 'GONAVYBEATARMY' """ return encipher_shift(msg, -key, symbols) def encipher_rot13(msg, symbols=None): """ Performs the ROT13 encryption on a given plaintext ``msg``. Explanation =========== ROT13 is a substitution cipher which substitutes each letter in the plaintext message for the letter furthest away from it in the English alphabet. Equivalently, it is just a Caeser (shift) cipher with a shift key of 13 (midway point of the alphabet). References ========== .. [1] https://en.wikipedia.org/wiki/ROT13 See Also ======== decipher_rot13 encipher_shift """ return encipher_shift(msg, 13, symbols) def decipher_rot13(msg, symbols=None): """ Performs the ROT13 decryption on a given plaintext ``msg``. Explanation ============ ``decipher_rot13`` is equivalent to ``encipher_rot13`` as both ``decipher_shift`` with a key of 13 and ``encipher_shift`` key with a key of 13 will return the same results. Nonetheless, ``decipher_rot13`` has nonetheless been explicitly defined here for consistency. Examples ======== >>> from sympy.crypto.crypto import encipher_rot13, decipher_rot13 >>> msg = 'GONAVYBEATARMY' >>> ciphertext = encipher_rot13(msg);ciphertext 'TBANILORNGNEZL' >>> decipher_rot13(ciphertext) 'GONAVYBEATARMY' >>> encipher_rot13(msg) == decipher_rot13(msg) True >>> msg == decipher_rot13(ciphertext) True """ return decipher_shift(msg, 13, symbols) ######## affine cipher examples ############ def encipher_affine(msg, key, symbols=None, _inverse=False): r""" Performs the affine cipher encryption on plaintext ``msg``, and returns the ciphertext. Explanation =========== Encryption is based on the map `x \rightarrow ax+b` (mod `N`) where ``N`` is the number of characters in the alphabet. Decryption is based on the map `x \rightarrow cx+d` (mod `N`), where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`). In particular, for the map to be invertible, we need `\mathrm{gcd}(a, N) = 1` and an error will be raised if this is not true. Parameters ========== msg : str Characters that appear in ``symbols``. a, b : int, int A pair integers, with ``gcd(a, N) = 1`` (the secret key). symbols String of characters (default = uppercase letters). When no symbols are given, ``msg`` is converted to upper case letters and all other characters are ignored. Returns ======= ct String of characters (the ciphertext message) Notes ===== ALGORITHM: STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``msg`` a list ``L1`` of corresponding integers. 2. Compute from the list ``L1`` a new list ``L2``, given by replacing ``x`` by ``a*x + b (mod N)``, for each element ``x`` in ``L1``. 3. Compute from the list ``L2`` a string ``ct`` of corresponding letters. This is a straightforward generalization of the shift cipher with the added complexity of requiring 2 characters to be deciphered in order to recover the key. References ========== .. [1] https://en.wikipedia.org/wiki/Affine_cipher See Also ======== decipher_affine """ msg, _, A = _prep(msg, '', symbols) N = len(A) a, b = key assert gcd(a, N) == 1 if _inverse: c = mod_inverse(a, N) d = -b*c a, b = c, d B = ''.join([A[(a*i + b) % N] for i in range(N)]) return translate(msg, A, B) def decipher_affine(msg, key, symbols=None): r""" Return the deciphered text that was made from the mapping, `x \rightarrow ax+b` (mod `N`), where ``N`` is the number of characters in the alphabet. Deciphering is done by reciphering with a new key: `x \rightarrow cx+d` (mod `N`), where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`). Examples ======== >>> from sympy.crypto.crypto import encipher_affine, decipher_affine >>> msg = "GO NAVY BEAT ARMY" >>> key = (3, 1) >>> encipher_affine(msg, key) 'TROBMVENBGBALV' >>> decipher_affine(_, key) 'GONAVYBEATARMY' See Also ======== encipher_affine """ return encipher_affine(msg, key, symbols, _inverse=True) def encipher_atbash(msg, symbols=None): r""" Enciphers a given ``msg`` into its Atbash ciphertext and returns it. Explanation =========== Atbash is a substitution cipher originally used to encrypt the Hebrew alphabet. Atbash works on the principle of mapping each alphabet to its reverse / counterpart (i.e. a would map to z, b to y etc.) Atbash is functionally equivalent to the affine cipher with ``a = 25`` and ``b = 25`` See Also ======== decipher_atbash """ return encipher_affine(msg, (25, 25), symbols) def decipher_atbash(msg, symbols=None): r""" Deciphers a given ``msg`` using Atbash cipher and returns it. Explanation =========== ``decipher_atbash`` is functionally equivalent to ``encipher_atbash``. However, it has still been added as a separate function to maintain consistency. Examples ======== >>> from sympy.crypto.crypto import encipher_atbash, decipher_atbash >>> msg = 'GONAVYBEATARMY' >>> encipher_atbash(msg) 'TLMZEBYVZGZINB' >>> decipher_atbash(msg) 'TLMZEBYVZGZINB' >>> encipher_atbash(msg) == decipher_atbash(msg) True >>> msg == encipher_atbash(encipher_atbash(msg)) True References ========== .. [1] https://en.wikipedia.org/wiki/Atbash See Also ======== encipher_atbash """ return decipher_affine(msg, (25, 25), symbols) #################### substitution cipher ########################### def encipher_substitution(msg, old, new=None): r""" Returns the ciphertext obtained by replacing each character that appears in ``old`` with the corresponding character in ``new``. If ``old`` is a mapping, then new is ignored and the replacements defined by ``old`` are used. Explanation =========== This is a more general than the affine cipher in that the key can only be recovered by determining the mapping for each symbol. Though in practice, once a few symbols are recognized the mappings for other characters can be quickly guessed. Examples ======== >>> from sympy.crypto.crypto import encipher_substitution, AZ >>> old = 'OEYAG' >>> new = '034^6' >>> msg = AZ("go navy! beat army!") >>> ct = encipher_substitution(msg, old, new); ct '60N^V4B3^T^RM4' To decrypt a substitution, reverse the last two arguments: >>> encipher_substitution(ct, new, old) 'GONAVYBEATARMY' In the special case where ``old`` and ``new`` are a permutation of order 2 (representing a transposition of characters) their order is immaterial: >>> old = 'NAVY' >>> new = 'ANYV' >>> encipher = lambda x: encipher_substitution(x, old, new) >>> encipher('NAVY') 'ANYV' >>> encipher(_) 'NAVY' The substitution cipher, in general, is a method whereby "units" (not necessarily single characters) of plaintext are replaced with ciphertext according to a regular system. >>> ords = dict(zip('abc', ['\\%i' % ord(i) for i in 'abc'])) >>> print(encipher_substitution('abc', ords)) \97\98\99 References ========== .. [1] https://en.wikipedia.org/wiki/Substitution_cipher """ return translate(msg, old, new) ###################################################################### #################### Vigenere cipher examples ######################## ###################################################################### def encipher_vigenere(msg, key, symbols=None): """ Performs the Vigenere cipher encryption on plaintext ``msg``, and returns the ciphertext. Examples ======== >>> from sympy.crypto.crypto import encipher_vigenere, AZ >>> key = "encrypt" >>> msg = "meet me on monday" >>> encipher_vigenere(msg, key) 'QRGKKTHRZQEBPR' Section 1 of the Kryptos sculpture at the CIA headquarters uses this cipher and also changes the order of the the alphabet [2]_. Here is the first line of that section of the sculpture: >>> from sympy.crypto.crypto import decipher_vigenere, padded_key >>> alp = padded_key('KRYPTOS', AZ()) >>> key = 'PALIMPSEST' >>> msg = 'EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJ' >>> decipher_vigenere(msg, key, alp) 'BETWEENSUBTLESHADINGANDTHEABSENC' Explanation =========== The Vigenere cipher is named after Blaise de Vigenere, a sixteenth century diplomat and cryptographer, by a historical accident. Vigenere actually invented a different and more complicated cipher. The so-called *Vigenere cipher* was actually invented by Giovan Batista Belaso in 1553. This cipher was used in the 1800's, for example, during the American Civil War. The Confederacy used a brass cipher disk to implement the Vigenere cipher (now on display in the NSA Museum in Fort Meade) [1]_. The Vigenere cipher is a generalization of the shift cipher. Whereas the shift cipher shifts each letter by the same amount (that amount being the key of the shift cipher) the Vigenere cipher shifts a letter by an amount determined by the key (which is a word or phrase known only to the sender and receiver). For example, if the key was a single letter, such as "C", then the so-called Vigenere cipher is actually a shift cipher with a shift of `2` (since "C" is the 2nd letter of the alphabet, if you start counting at `0`). If the key was a word with two letters, such as "CA", then the so-called Vigenere cipher will shift letters in even positions by `2` and letters in odd positions are left alone (shifted by `0`, since "A" is the 0th letter, if you start counting at `0`). ALGORITHM: INPUT: ``msg``: string of characters that appear in ``symbols`` (the plaintext) ``key``: a string of characters that appear in ``symbols`` (the secret key) ``symbols``: a string of letters defining the alphabet OUTPUT: ``ct``: string of characters (the ciphertext message) STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``key`` a list ``L1`` of corresponding integers. Let ``n1 = len(L1)``. 2. Compute from the string ``msg`` a list ``L2`` of corresponding integers. Let ``n2 = len(L2)``. 3. Break ``L2`` up sequentially into sublists of size ``n1``; the last sublist may be smaller than ``n1`` 4. For each of these sublists ``L`` of ``L2``, compute a new list ``C`` given by ``C[i] = L[i] + L1[i] (mod N)`` to the ``i``-th element in the sublist, for each ``i``. 5. Assemble these lists ``C`` by concatenation into a new list of length ``n2``. 6. Compute from the new list a string ``ct`` of corresponding letters. Once it is known that the key is, say, `n` characters long, frequency analysis can be applied to every `n`-th letter of the ciphertext to determine the plaintext. This method is called *Kasiski examination* (although it was first discovered by Babbage). If they key is as long as the message and is comprised of randomly selected characters -- a one-time pad -- the message is theoretically unbreakable. The cipher Vigenere actually discovered is an "auto-key" cipher described as follows. ALGORITHM: INPUT: ``key``: a string of letters (the secret key) ``msg``: string of letters (the plaintext message) OUTPUT: ``ct``: string of upper-case letters (the ciphertext message) STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``msg`` a list ``L2`` of corresponding integers. Let ``n2 = len(L2)``. 2. Let ``n1`` be the length of the key. Append to the string ``key`` the first ``n2 - n1`` characters of the plaintext message. Compute from this string (also of length ``n2``) a list ``L1`` of integers corresponding to the letter numbers in the first step. 3. Compute a new list ``C`` given by ``C[i] = L1[i] + L2[i] (mod N)``. 4. Compute from the new list a string ``ct`` of letters corresponding to the new integers. To decipher the auto-key ciphertext, the key is used to decipher the first ``n1`` characters and then those characters become the key to decipher the next ``n1`` characters, etc...: >>> m = AZ('go navy, beat army! yes you can'); m 'GONAVYBEATARMYYESYOUCAN' >>> key = AZ('gold bug'); n1 = len(key); n2 = len(m) >>> auto_key = key + m[:n2 - n1]; auto_key 'GOLDBUGGONAVYBEATARMYYE' >>> ct = encipher_vigenere(m, auto_key); ct 'MCYDWSHKOGAMKZCELYFGAYR' >>> n1 = len(key) >>> pt = [] >>> while ct: ... part, ct = ct[:n1], ct[n1:] ... pt.append(decipher_vigenere(part, key)) ... key = pt[-1] ... >>> ''.join(pt) == m True References ========== .. [1] https://en.wikipedia.org/wiki/Vigenere_cipher .. [2] http://web.archive.org/web/20071116100808/ .. [3] http://filebox.vt.edu/users/batman/kryptos.html (short URL: https://goo.gl/ijr22d) """ msg, key, A = _prep(msg, key, symbols) map = {c: i for i, c in enumerate(A)} key = [map[c] for c in key] N = len(map) k = len(key) rv = [] for i, m in enumerate(msg): rv.append(A[(map[m] + key[i % k]) % N]) rv = ''.join(rv) return rv def decipher_vigenere(msg, key, symbols=None): """ Decode using the Vigenere cipher. Examples ======== >>> from sympy.crypto.crypto import decipher_vigenere >>> key = "encrypt" >>> ct = "QRGK kt HRZQE BPR" >>> decipher_vigenere(ct, key) 'MEETMEONMONDAY' """ msg, key, A = _prep(msg, key, symbols) map = {c: i for i, c in enumerate(A)} N = len(A) # normally, 26 K = [map[c] for c in key] n = len(K) C = [map[c] for c in msg] rv = ''.join([A[(-K[i % n] + c) % N] for i, c in enumerate(C)]) return rv #################### Hill cipher ######################## def encipher_hill(msg, key, symbols=None, pad="Q"): r""" Return the Hill cipher encryption of ``msg``. Explanation =========== The Hill cipher [1]_, invented by Lester S. Hill in the 1920's [2]_, was the first polygraphic cipher in which it was practical (though barely) to operate on more than three symbols at once. The following discussion assumes an elementary knowledge of matrices. First, each letter is first encoded as a number starting with 0. Suppose your message `msg` consists of `n` capital letters, with no spaces. This may be regarded an `n`-tuple M of elements of `Z_{26}` (if the letters are those of the English alphabet). A key in the Hill cipher is a `k x k` matrix `K`, all of whose entries are in `Z_{26}`, such that the matrix `K` is invertible (i.e., the linear transformation `K: Z_{N}^k \rightarrow Z_{N}^k` is one-to-one). Parameters ========== msg Plaintext message of `n` upper-case letters. key A `k \times k` invertible matrix `K`, all of whose entries are in `Z_{26}` (or whatever number of symbols are being used). pad Character (default "Q") to use to make length of text be a multiple of ``k``. Returns ======= ct Ciphertext of upper-case letters. Notes ===== ALGORITHM: STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``msg`` a list ``L`` of corresponding integers. Let ``n = len(L)``. 2. Break the list ``L`` up into ``t = ceiling(n/k)`` sublists ``L_1``, ..., ``L_t`` of size ``k`` (with the last list "padded" to ensure its size is ``k``). 3. Compute new list ``C_1``, ..., ``C_t`` given by ``C[i] = K*L_i`` (arithmetic is done mod N), for each ``i``. 4. Concatenate these into a list ``C = C_1 + ... + C_t``. 5. Compute from ``C`` a string ``ct`` of corresponding letters. This has length ``k*t``. References ========== .. [1] https://en.wikipedia.org/wiki/Hill_cipher .. [2] Lester S. Hill, Cryptography in an Algebraic Alphabet, The American Mathematical Monthly Vol.36, June-July 1929, pp.306-312. See Also ======== decipher_hill """ assert key.is_square assert len(pad) == 1 msg, pad, A = _prep(msg, pad, symbols) map = {c: i for i, c in enumerate(A)} P = [map[c] for c in msg] N = len(A) k = key.cols n = len(P) m, r = divmod(n, k) if r: P = P + [map[pad]]*(k - r) m += 1 rv = ''.join([A[c % N] for j in range(m) for c in list(key*Matrix(k, 1, [P[i] for i in range(k*j, k*(j + 1))]))]) return rv def decipher_hill(msg, key, symbols=None): """ Deciphering is the same as enciphering but using the inverse of the key matrix. Examples ======== >>> from sympy.crypto.crypto import encipher_hill, decipher_hill >>> from sympy import Matrix >>> key = Matrix([[1, 2], [3, 5]]) >>> encipher_hill("meet me on monday", key) 'UEQDUEODOCTCWQ' >>> decipher_hill(_, key) 'MEETMEONMONDAY' When the length of the plaintext (stripped of invalid characters) is not a multiple of the key dimension, extra characters will appear at the end of the enciphered and deciphered text. In order to decipher the text, those characters must be included in the text to be deciphered. In the following, the key has a dimension of 4 but the text is 2 short of being a multiple of 4 so two characters will be added. >>> key = Matrix([[1, 1, 1, 2], [0, 1, 1, 0], ... [2, 2, 3, 4], [1, 1, 0, 1]]) >>> msg = "ST" >>> encipher_hill(msg, key) 'HJEB' >>> decipher_hill(_, key) 'STQQ' >>> encipher_hill(msg, key, pad="Z") 'ISPK' >>> decipher_hill(_, key) 'STZZ' If the last two characters of the ciphertext were ignored in either case, the wrong plaintext would be recovered: >>> decipher_hill("HD", key) 'ORMV' >>> decipher_hill("IS", key) 'UIKY' See Also ======== encipher_hill """ assert key.is_square msg, _, A = _prep(msg, '', symbols) map = {c: i for i, c in enumerate(A)} C = [map[c] for c in msg] N = len(A) k = key.cols n = len(C) m, r = divmod(n, k) if r: C = C + [0]*(k - r) m += 1 key_inv = key.inv_mod(N) rv = ''.join([A[p % N] for j in range(m) for p in list(key_inv*Matrix( k, 1, [C[i] for i in range(k*j, k*(j + 1))]))]) return rv #################### Bifid cipher ######################## def encipher_bifid(msg, key, symbols=None): r""" Performs the Bifid cipher encryption on plaintext ``msg``, and returns the ciphertext. This is the version of the Bifid cipher that uses an `n \times n` Polybius square. Parameters ========== msg Plaintext string. key Short string for key. Duplicate characters are ignored and then it is padded with the characters in ``symbols`` that were not in the short key. symbols `n \times n` characters defining the alphabet. (default is string.printable) Returns ======= ciphertext Ciphertext using Bifid5 cipher without spaces. See Also ======== decipher_bifid, encipher_bifid5, encipher_bifid6 References ========== .. [1] https://en.wikipedia.org/wiki/Bifid_cipher """ msg, key, A = _prep(msg, key, symbols, bifid10) long_key = ''.join(uniq(key)) or A n = len(A)**.5 if n != int(n): raise ValueError( 'Length of alphabet (%s) is not a square number.' % len(A)) N = int(n) if len(long_key) < N**2: long_key = list(long_key) + [x for x in A if x not in long_key] # the fractionalization row_col = {ch: divmod(i, N) for i, ch in enumerate(long_key)} r, c = zip(*[row_col[x] for x in msg]) rc = r + c ch = {i: ch for ch, i in row_col.items()} rv = ''.join(ch[i] for i in zip(rc[::2], rc[1::2])) return rv def decipher_bifid(msg, key, symbols=None): r""" Performs the Bifid cipher decryption on ciphertext ``msg``, and returns the plaintext. This is the version of the Bifid cipher that uses the `n \times n` Polybius square. Parameters ========== msg Ciphertext string. key Short string for key. Duplicate characters are ignored and then it is padded with the characters in symbols that were not in the short key. symbols `n \times n` characters defining the alphabet. (default=string.printable, a `10 \times 10` matrix) Returns ======= deciphered Deciphered text. Examples ======== >>> from sympy.crypto.crypto import ( ... encipher_bifid, decipher_bifid, AZ) Do an encryption using the bifid5 alphabet: >>> alp = AZ().replace('J', '') >>> ct = AZ("meet me on monday!") >>> key = AZ("gold bug") >>> encipher_bifid(ct, key, alp) 'IEILHHFSTSFQYE' When entering the text or ciphertext, spaces are ignored so it can be formatted as desired. Re-entering the ciphertext from the preceding, putting 4 characters per line and padding with an extra J, does not cause problems for the deciphering: >>> decipher_bifid(''' ... IEILH ... HFSTS ... FQYEJ''', key, alp) 'MEETMEONMONDAY' When no alphabet is given, all 100 printable characters will be used: >>> key = '' >>> encipher_bifid('hello world!', key) 'bmtwmg-bIo*w' >>> decipher_bifid(_, key) 'hello world!' If the key is changed, a different encryption is obtained: >>> key = 'gold bug' >>> encipher_bifid('hello world!', 'gold_bug') 'hg2sfuei7t}w' And if the key used to decrypt the message is not exact, the original text will not be perfectly obtained: >>> decipher_bifid(_, 'gold pug') 'heldo~wor6d!' """ msg, _, A = _prep(msg, '', symbols, bifid10) long_key = ''.join(uniq(key)) or A n = len(A)**.5 if n != int(n): raise ValueError( 'Length of alphabet (%s) is not a square number.' % len(A)) N = int(n) if len(long_key) < N**2: long_key = list(long_key) + [x for x in A if x not in long_key] # the reverse fractionalization row_col = { ch: divmod(i, N) for i, ch in enumerate(long_key)} rc = [i for c in msg for i in row_col[c]] n = len(msg) rc = zip(*(rc[:n], rc[n:])) ch = {i: ch for ch, i in row_col.items()} rv = ''.join(ch[i] for i in rc) return rv def bifid_square(key): """Return characters of ``key`` arranged in a square. Examples ======== >>> from sympy.crypto.crypto import ( ... bifid_square, AZ, padded_key, bifid5) >>> bifid_square(AZ().replace('J', '')) Matrix([ [A, B, C, D, E], [F, G, H, I, K], [L, M, N, O, P], [Q, R, S, T, U], [V, W, X, Y, Z]]) >>> bifid_square(padded_key(AZ('gold bug!'), bifid5)) Matrix([ [G, O, L, D, B], [U, A, C, E, F], [H, I, K, M, N], [P, Q, R, S, T], [V, W, X, Y, Z]]) See Also ======== padded_key """ A = ''.join(uniq(''.join(key))) n = len(A)**.5 if n != int(n): raise ValueError( 'Length of alphabet (%s) is not a square number.' % len(A)) n = int(n) f = lambda i, j: Symbol(A[n*i + j]) rv = Matrix(n, n, f) return rv def encipher_bifid5(msg, key): r""" Performs the Bifid cipher encryption on plaintext ``msg``, and returns the ciphertext. Explanation =========== This is the version of the Bifid cipher that uses the `5 \times 5` Polybius square. The letter "J" is ignored so it must be replaced with something else (traditionally an "I") before encryption. ALGORITHM: (5x5 case) STEPS: 0. Create the `5 \times 5` Polybius square ``S`` associated to ``key`` as follows: a) moving from left-to-right, top-to-bottom, place the letters of the key into a `5 \times 5` matrix, b) if the key has less than 25 letters, add the letters of the alphabet not in the key until the `5 \times 5` square is filled. 1. Create a list ``P`` of pairs of numbers which are the coordinates in the Polybius square of the letters in ``msg``. 2. Let ``L1`` be the list of all first coordinates of ``P`` (length of ``L1 = n``), let ``L2`` be the list of all second coordinates of ``P`` (so the length of ``L2`` is also ``n``). 3. Let ``L`` be the concatenation of ``L1`` and ``L2`` (length ``L = 2*n``), except that consecutive numbers are paired ``(L[2*i], L[2*i + 1])``. You can regard ``L`` as a list of pairs of length ``n``. 4. Let ``C`` be the list of all letters which are of the form ``S[i, j]``, for all ``(i, j)`` in ``L``. As a string, this is the ciphertext of ``msg``. Parameters ========== msg : str Plaintext string. Converted to upper case and filtered of anything but all letters except J. key Short string for key; non-alphabetic letters, J and duplicated characters are ignored and then, if the length is less than 25 characters, it is padded with other letters of the alphabet (in alphabetical order). Returns ======= ct Ciphertext (all caps, no spaces). Examples ======== >>> from sympy.crypto.crypto import ( ... encipher_bifid5, decipher_bifid5) "J" will be omitted unless it is replaced with something else: >>> round_trip = lambda m, k: \ ... decipher_bifid5(encipher_bifid5(m, k), k) >>> key = 'a' >>> msg = "JOSIE" >>> round_trip(msg, key) 'OSIE' >>> round_trip(msg.replace("J", "I"), key) 'IOSIE' >>> j = "QIQ" >>> round_trip(msg.replace("J", j), key).replace(j, "J") 'JOSIE' Notes ===== The Bifid cipher was invented around 1901 by Felix Delastelle. It is a *fractional substitution* cipher, where letters are replaced by pairs of symbols from a smaller alphabet. The cipher uses a `5 \times 5` square filled with some ordering of the alphabet, except that "J" is replaced with "I" (this is a so-called Polybius square; there is a `6 \times 6` analog if you add back in "J" and also append onto the usual 26 letter alphabet, the digits 0, 1, ..., 9). According to Helen Gaines' book *Cryptanalysis*, this type of cipher was used in the field by the German Army during World War I. See Also ======== decipher_bifid5, encipher_bifid """ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5) key = padded_key(key, bifid5) return encipher_bifid(msg, '', key) def decipher_bifid5(msg, key): r""" Return the Bifid cipher decryption of ``msg``. Explanation =========== This is the version of the Bifid cipher that uses the `5 \times 5` Polybius square; the letter "J" is ignored unless a ``key`` of length 25 is used. Parameters ========== msg Ciphertext string. key Short string for key; duplicated characters are ignored and if the length is less then 25 characters, it will be padded with other letters from the alphabet omitting "J". Non-alphabetic characters are ignored. Returns ======= plaintext Plaintext from Bifid5 cipher (all caps, no spaces). Examples ======== >>> from sympy.crypto.crypto import encipher_bifid5, decipher_bifid5 >>> key = "gold bug" >>> encipher_bifid5('meet me on friday', key) 'IEILEHFSTSFXEE' >>> encipher_bifid5('meet me on monday', key) 'IEILHHFSTSFQYE' >>> decipher_bifid5(_, key) 'MEETMEONMONDAY' """ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5) key = padded_key(key, bifid5) return decipher_bifid(msg, '', key) def bifid5_square(key=None): r""" 5x5 Polybius square. Produce the Polybius square for the `5 \times 5` Bifid cipher. Examples ======== >>> from sympy.crypto.crypto import bifid5_square >>> bifid5_square("gold bug") Matrix([ [G, O, L, D, B], [U, A, C, E, F], [H, I, K, M, N], [P, Q, R, S, T], [V, W, X, Y, Z]]) """ if not key: key = bifid5 else: _, key, _ = _prep('', key.upper(), None, bifid5) key = padded_key(key, bifid5) return bifid_square(key) def encipher_bifid6(msg, key): r""" Performs the Bifid cipher encryption on plaintext ``msg``, and returns the ciphertext. This is the version of the Bifid cipher that uses the `6 \times 6` Polybius square. Parameters ========== msg Plaintext string (digits okay). key Short string for key (digits okay). If ``key`` is less than 36 characters long, the square will be filled with letters A through Z and digits 0 through 9. Returns ======= ciphertext Ciphertext from Bifid cipher (all caps, no spaces). See Also ======== decipher_bifid6, encipher_bifid """ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6) key = padded_key(key, bifid6) return encipher_bifid(msg, '', key) def decipher_bifid6(msg, key): r""" Performs the Bifid cipher decryption on ciphertext ``msg``, and returns the plaintext. This is the version of the Bifid cipher that uses the `6 \times 6` Polybius square. Parameters ========== msg Ciphertext string (digits okay); converted to upper case key Short string for key (digits okay). If ``key`` is less than 36 characters long, the square will be filled with letters A through Z and digits 0 through 9. All letters are converted to uppercase. Returns ======= plaintext Plaintext from Bifid cipher (all caps, no spaces). Examples ======== >>> from sympy.crypto.crypto import encipher_bifid6, decipher_bifid6 >>> key = "gold bug" >>> encipher_bifid6('meet me on monday at 8am', key) 'KFKLJJHF5MMMKTFRGPL' >>> decipher_bifid6(_, key) 'MEETMEONMONDAYAT8AM' """ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6) key = padded_key(key, bifid6) return decipher_bifid(msg, '', key) def bifid6_square(key=None): r""" 6x6 Polybius square. Produces the Polybius square for the `6 \times 6` Bifid cipher. Assumes alphabet of symbols is "A", ..., "Z", "0", ..., "9". Examples ======== >>> from sympy.crypto.crypto import bifid6_square >>> key = "gold bug" >>> bifid6_square(key) Matrix([ [G, O, L, D, B, U], [A, C, E, F, H, I], [J, K, M, N, P, Q], [R, S, T, V, W, X], [Y, Z, 0, 1, 2, 3], [4, 5, 6, 7, 8, 9]]) """ if not key: key = bifid6 else: _, key, _ = _prep('', key.upper(), None, bifid6) key = padded_key(key, bifid6) return bifid_square(key) #################### RSA ############################# def _decipher_rsa_crt(i, d, factors): """Decipher RSA using chinese remainder theorem from the information of the relatively-prime factors of the modulus. Parameters ========== i : integer Ciphertext d : integer The exponent component. factors : list of relatively-prime integers The integers given must be coprime and the product must equal the modulus component of the original RSA key. Examples ======== How to decrypt RSA with CRT: >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key >>> primes = [61, 53] >>> e = 17 >>> args = primes + [e] >>> puk = rsa_public_key(*args) >>> prk = rsa_private_key(*args) >>> from sympy.crypto.crypto import encipher_rsa, _decipher_rsa_crt >>> msg = 65 >>> crt_primes = primes >>> encrypted = encipher_rsa(msg, puk) >>> decrypted = _decipher_rsa_crt(encrypted, prk[1], primes) >>> decrypted 65 """ from sympy.ntheory.modular import crt moduluses = [pow(i, d, p) for p in factors] result = crt(factors, moduluses) if not result: raise ValueError("CRT failed") return result[0] def _rsa_key(*args, public=True, private=True, totient='Euler', index=None, multipower=None): r"""A private subroutine to generate RSA key Parameters ========== public, private : bool, optional Flag to generate either a public key, a private key. totient : 'Euler' or 'Carmichael' Different notation used for totient. multipower : bool, optional Flag to bypass warning for multipower RSA. """ from sympy.ntheory import totient as _euler from sympy.ntheory import reduced_totient as _carmichael if len(args) < 2: return False if totient not in ('Euler', 'Carmichael'): raise ValueError( "The argument totient={} should either be " \ "'Euler', 'Carmichalel'." \ .format(totient)) if totient == 'Euler': _totient = _euler else: _totient = _carmichael if index is not None: index = as_int(index) if totient != 'Carmichael': raise ValueError( "Setting the 'index' keyword argument requires totient" "notation to be specified as 'Carmichael'.") primes, e = args[:-1], args[-1] if not all(isprime(p) for p in primes): new_primes = [] for i in primes: new_primes.extend(factorint(i, multiple=True)) primes = new_primes n = reduce(lambda i, j: i*j, primes) tally = multiset(primes) if all(v == 1 for v in tally.values()): multiple = list(tally.keys()) phi = _totient._from_distinct_primes(*multiple) else: if not multipower: NonInvertibleCipherWarning( 'Non-distinctive primes found in the factors {}. ' 'The cipher may not be decryptable for some numbers ' 'in the complete residue system Z[{}], but the cipher ' 'can still be valid if you restrict the domain to be ' 'the reduced residue system Z*[{}]. You can pass ' 'the flag multipower=True if you want to suppress this ' 'warning.' .format(primes, n, n) ).warn() phi = _totient._from_factors(tally) if igcd(e, phi) == 1: if public and not private: if isinstance(index, int): e = e % phi e += index * phi return n, e if private and not public: d = mod_inverse(e, phi) if isinstance(index, int): d += index * phi return n, d return False def rsa_public_key(*args, **kwargs): r"""Return the RSA *public key* pair, `(n, e)` Parameters ========== args : naturals If specified as `p, q, e` where `p` and `q` are distinct primes and `e` is a desired public exponent of the RSA, `n = p q` and `e` will be verified against the totient `\phi(n)` (Euler totient) or `\lambda(n)` (Carmichael totient) to be `\gcd(e, \phi(n)) = 1` or `\gcd(e, \lambda(n)) = 1`. If specified as `p_1, p_2, ..., p_n, e` where `p_1, p_2, ..., p_n` are specified as primes, and `e` is specified as a desired public exponent of the RSA, it will be able to form a multi-prime RSA, which is a more generalized form of the popular 2-prime RSA. It can also be possible to form a single-prime RSA by specifying the argument as `p, e`, which can be considered a trivial case of a multiprime RSA. Furthermore, it can be possible to form a multi-power RSA by specifying two or more pairs of the primes to be same. However, unlike the two-distinct prime RSA or multi-prime RSA, not every numbers in the complete residue system (`\mathbb{Z}_n`) will be decryptable since the mapping `\mathbb{Z}_{n} \rightarrow \mathbb{Z}_{n}` will not be bijective. (Only except for the trivial case when `e = 1` or more generally, .. math:: e \in \left \{ 1 + k \lambda(n) \mid k \in \mathbb{Z} \land k \geq 0 \right \} when RSA reduces to the identity.) However, the RSA can still be decryptable for the numbers in the reduced residue system (`\mathbb{Z}_n^{\times}`), since the mapping `\mathbb{Z}_{n}^{\times} \rightarrow \mathbb{Z}_{n}^{\times}` can still be bijective. If you pass a non-prime integer to the arguments `p_1, p_2, ..., p_n`, the particular number will be prime-factored and it will become either a multi-prime RSA or a multi-power RSA in its canonical form, depending on whether the product equals its radical or not. `p_1 p_2 ... p_n = \text{rad}(p_1 p_2 ... p_n)` totient : bool, optional If ``'Euler'``, it uses Euler's totient `\phi(n)` which is :meth:`sympy.ntheory.factor_.totient` in SymPy. If ``'Carmichael'``, it uses Carmichael's totient `\lambda(n)` which is :meth:`sympy.ntheory.factor_.reduced_totient` in SymPy. Unlike private key generation, this is a trivial keyword for public key generation because `\gcd(e, \phi(n)) = 1 \iff \gcd(e, \lambda(n)) = 1`. index : nonnegative integer, optional Returns an arbitrary solution of a RSA public key at the index specified at `0, 1, 2, ...`. This parameter needs to be specified along with ``totient='Carmichael'``. Similarly to the non-uniquenss of a RSA private key as described in the ``index`` parameter documentation in :meth:`rsa_private_key`, RSA public key is also not unique and there is an infinite number of RSA public exponents which can behave in the same manner. From any given RSA public exponent `e`, there are can be an another RSA public exponent `e + k \lambda(n)` where `k` is an integer, `\lambda` is a Carmichael's totient function. However, considering only the positive cases, there can be a principal solution of a RSA public exponent `e_0` in `0 < e_0 < \lambda(n)`, and all the other solutions can be canonicalzed in a form of `e_0 + k \lambda(n)`. ``index`` specifies the `k` notation to yield any possible value an RSA public key can have. An example of computing any arbitrary RSA public key: >>> from sympy.crypto.crypto import rsa_public_key >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=0) (3233, 17) >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=1) (3233, 797) >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=2) (3233, 1577) multipower : bool, optional Any pair of non-distinct primes found in the RSA specification will restrict the domain of the cryptosystem, as noted in the explaination of the parameter ``args``. SymPy RSA key generator may give a warning before dispatching it as a multi-power RSA, however, you can disable the warning if you pass ``True`` to this keyword. Returns ======= (n, e) : int, int `n` is a product of any arbitrary number of primes given as the argument. `e` is relatively prime (coprime) to the Euler totient `\phi(n)`. False Returned if less than two arguments are given, or `e` is not relatively prime to the modulus. Examples ======== >>> from sympy.crypto.crypto import rsa_public_key A public key of a two-prime RSA: >>> p, q, e = 3, 5, 7 >>> rsa_public_key(p, q, e) (15, 7) >>> rsa_public_key(p, q, 30) False A public key of a multiprime RSA: >>> primes = [2, 3, 5, 7, 11, 13] >>> e = 7 >>> args = primes + [e] >>> rsa_public_key(*args) (30030, 7) Notes ===== Although the RSA can be generalized over any modulus `n`, using two large primes had became the most popular specification because a product of two large primes is usually the hardest to factor relatively to the digits of `n` can have. However, it may need further understanding of the time complexities of each prime-factoring algorithms to verify the claim. See Also ======== rsa_private_key encipher_rsa decipher_rsa References ========== .. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29 .. [2] http://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf .. [3] https://link.springer.com/content/pdf/10.1007%2FBFb0055738.pdf .. [4] http://www.itiis.org/digital-library/manuscript/1381 """ return _rsa_key(*args, public=True, private=False, **kwargs) def rsa_private_key(*args, **kwargs): r"""Return the RSA *private key* pair, `(n, d)` Parameters ========== args : naturals The keyword is identical to the ``args`` in :meth:`rsa_public_key`. totient : bool, optional If ``'Euler'``, it uses Euler's totient convention `\phi(n)` which is :meth:`sympy.ntheory.factor_.totient` in SymPy. If ``'Carmichael'``, it uses Carmichael's totient convention `\lambda(n)` which is :meth:`sympy.ntheory.factor_.reduced_totient` in SymPy. There can be some output differences for private key generation as examples below. Example using Euler's totient: >>> from sympy.crypto.crypto import rsa_private_key >>> rsa_private_key(61, 53, 17, totient='Euler') (3233, 2753) Example using Carmichael's totient: >>> from sympy.crypto.crypto import rsa_private_key >>> rsa_private_key(61, 53, 17, totient='Carmichael') (3233, 413) index : nonnegative integer, optional Returns an arbitrary solution of a RSA private key at the index specified at `0, 1, 2, ...`. This parameter needs to be specified along with ``totient='Carmichael'``. RSA private exponent is a non-unique solution of `e d \mod \lambda(n) = 1` and it is possible in any form of `d + k \lambda(n)`, where `d` is an another already-computed private exponent, and `\lambda` is a Carmichael's totient function, and `k` is any integer. However, considering only the positive cases, there can be a principal solution of a RSA private exponent `d_0` in `0 < d_0 < \lambda(n)`, and all the other solutions can be canonicalzed in a form of `d_0 + k \lambda(n)`. ``index`` specifies the `k` notation to yield any possible value an RSA private key can have. An example of computing any arbitrary RSA private key: >>> from sympy.crypto.crypto import rsa_private_key >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=0) (3233, 413) >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=1) (3233, 1193) >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=2) (3233, 1973) multipower : bool, optional The keyword is identical to the ``multipower`` in :meth:`rsa_public_key`. Returns ======= (n, d) : int, int `n` is a product of any arbitrary number of primes given as the argument. `d` is the inverse of `e` (mod `\phi(n)`) where `e` is the exponent given, and `\phi` is a Euler totient. False Returned if less than two arguments are given, or `e` is not relatively prime to the totient of the modulus. Examples ======== >>> from sympy.crypto.crypto import rsa_private_key A private key of a two-prime RSA: >>> p, q, e = 3, 5, 7 >>> rsa_private_key(p, q, e) (15, 7) >>> rsa_private_key(p, q, 30) False A private key of a multiprime RSA: >>> primes = [2, 3, 5, 7, 11, 13] >>> e = 7 >>> args = primes + [e] >>> rsa_private_key(*args) (30030, 823) See Also ======== rsa_public_key encipher_rsa decipher_rsa References ========== .. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29 .. [2] http://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf .. [3] https://link.springer.com/content/pdf/10.1007%2FBFb0055738.pdf .. [4] http://www.itiis.org/digital-library/manuscript/1381 """ return _rsa_key(*args, public=False, private=True, **kwargs) def _encipher_decipher_rsa(i, key, factors=None): n, d = key if not factors: return pow(i, d, n) def _is_coprime_set(l): is_coprime_set = True for i in range(len(l)): for j in range(i+1, len(l)): if igcd(l[i], l[j]) != 1: is_coprime_set = False break return is_coprime_set prod = reduce(lambda i, j: i*j, factors) if prod == n and _is_coprime_set(factors): return _decipher_rsa_crt(i, d, factors) return _encipher_decipher_rsa(i, key, factors=None) def encipher_rsa(i, key, factors=None): r"""Encrypt the plaintext with RSA. Parameters ========== i : integer The plaintext to be encrypted for. key : (n, e) where n, e are integers `n` is the modulus of the key and `e` is the exponent of the key. The encryption is computed by `i^e \bmod n`. The key can either be a public key or a private key, however, the message encrypted by a public key can only be decrypted by a private key, and vice versa, as RSA is an asymmetric cryptography system. factors : list of coprime integers This is identical to the keyword ``factors`` in :meth:`decipher_rsa`. Notes ===== Some specifications may make the RSA not cryptographically meaningful. For example, `0`, `1` will remain always same after taking any number of exponentiation, thus, should be avoided. Furthermore, if `i^e < n`, `i` may easily be figured out by taking `e` th root. And also, specifying the exponent as `1` or in more generalized form as `1 + k \lambda(n)` where `k` is an nonnegative integer, `\lambda` is a carmichael totient, the RSA becomes an identity mapping. Examples ======== >>> from sympy.crypto.crypto import encipher_rsa >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key Public Key Encryption: >>> p, q, e = 3, 5, 7 >>> puk = rsa_public_key(p, q, e) >>> msg = 12 >>> encipher_rsa(msg, puk) 3 Private Key Encryption: >>> p, q, e = 3, 5, 7 >>> prk = rsa_private_key(p, q, e) >>> msg = 12 >>> encipher_rsa(msg, prk) 3 Encryption using chinese remainder theorem: >>> encipher_rsa(msg, prk, factors=[p, q]) 3 """ return _encipher_decipher_rsa(i, key, factors=factors) def decipher_rsa(i, key, factors=None): r"""Decrypt the ciphertext with RSA. Parameters ========== i : integer The ciphertext to be decrypted for. key : (n, d) where n, d are integers `n` is the modulus of the key and `d` is the exponent of the key. The decryption is computed by `i^d \bmod n`. The key can either be a public key or a private key, however, the message encrypted by a public key can only be decrypted by a private key, and vice versa, as RSA is an asymmetric cryptography system. factors : list of coprime integers As the modulus `n` created from RSA key generation is composed of arbitrary prime factors `n = {p_1}^{k_1}{p_2}^{k_2}...{p_n}^{k_n}` where `p_1, p_2, ..., p_n` are distinct primes and `k_1, k_2, ..., k_n` are positive integers, chinese remainder theorem can be used to compute `i^d \bmod n` from the fragmented modulo operations like .. math:: i^d \bmod {p_1}^{k_1}, i^d \bmod {p_2}^{k_2}, ... , i^d \bmod {p_n}^{k_n} or like .. math:: i^d \bmod {p_1}^{k_1}{p_2}^{k_2}, i^d \bmod {p_3}^{k_3}, ... , i^d \bmod {p_n}^{k_n} as long as every moduli does not share any common divisor each other. The raw primes used in generating the RSA key pair can be a good option. Note that the speed advantage of using this is only viable for very large cases (Like 2048-bit RSA keys) since the overhead of using pure python implementation of :meth:`sympy.ntheory.modular.crt` may overcompensate the theoritical speed advantage. Notes ===== See the ``Notes`` section in the documentation of :meth:`encipher_rsa` Examples ======== >>> from sympy.crypto.crypto import decipher_rsa, encipher_rsa >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key Public Key Encryption and Decryption: >>> p, q, e = 3, 5, 7 >>> prk = rsa_private_key(p, q, e) >>> puk = rsa_public_key(p, q, e) >>> msg = 12 >>> new_msg = encipher_rsa(msg, prk) >>> new_msg 3 >>> decipher_rsa(new_msg, puk) 12 Private Key Encryption and Decryption: >>> p, q, e = 3, 5, 7 >>> prk = rsa_private_key(p, q, e) >>> puk = rsa_public_key(p, q, e) >>> msg = 12 >>> new_msg = encipher_rsa(msg, puk) >>> new_msg 3 >>> decipher_rsa(new_msg, prk) 12 Decryption using chinese remainder theorem: >>> decipher_rsa(new_msg, prk, factors=[p, q]) 12 See Also ======== encipher_rsa """ return _encipher_decipher_rsa(i, key, factors=factors) #################### kid krypto (kid RSA) ############################# def kid_rsa_public_key(a, b, A, B): r""" Kid RSA is a version of RSA useful to teach grade school children since it does not involve exponentiation. Explanation =========== Alice wants to talk to Bob. Bob generates keys as follows. Key generation: * Select positive integers `a, b, A, B` at random. * Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`, `n = (e d - 1)//M`. * The *public key* is `(n, e)`. Bob sends these to Alice. * The *private key* is `(n, d)`, which Bob keeps secret. Encryption: If `p` is the plaintext message then the ciphertext is `c = p e \pmod n`. Decryption: If `c` is the ciphertext message then the plaintext is `p = c d \pmod n`. Examples ======== >>> from sympy.crypto.crypto import kid_rsa_public_key >>> a, b, A, B = 3, 4, 5, 6 >>> kid_rsa_public_key(a, b, A, B) (369, 58) """ M = a*b - 1 e = A*M + a d = B*M + b n = (e*d - 1)//M return n, e def kid_rsa_private_key(a, b, A, B): """ Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`, `n = (e d - 1) / M`. The *private key* is `d`, which Bob keeps secret. Examples ======== >>> from sympy.crypto.crypto import kid_rsa_private_key >>> a, b, A, B = 3, 4, 5, 6 >>> kid_rsa_private_key(a, b, A, B) (369, 70) """ M = a*b - 1 e = A*M + a d = B*M + b n = (e*d - 1)//M return n, d def encipher_kid_rsa(msg, key): """ Here ``msg`` is the plaintext and ``key`` is the public key. Examples ======== >>> from sympy.crypto.crypto import ( ... encipher_kid_rsa, kid_rsa_public_key) >>> msg = 200 >>> a, b, A, B = 3, 4, 5, 6 >>> key = kid_rsa_public_key(a, b, A, B) >>> encipher_kid_rsa(msg, key) 161 """ n, e = key return (msg*e) % n def decipher_kid_rsa(msg, key): """ Here ``msg`` is the plaintext and ``key`` is the private key. Examples ======== >>> from sympy.crypto.crypto import ( ... kid_rsa_public_key, kid_rsa_private_key, ... decipher_kid_rsa, encipher_kid_rsa) >>> a, b, A, B = 3, 4, 5, 6 >>> d = kid_rsa_private_key(a, b, A, B) >>> msg = 200 >>> pub = kid_rsa_public_key(a, b, A, B) >>> pri = kid_rsa_private_key(a, b, A, B) >>> ct = encipher_kid_rsa(msg, pub) >>> decipher_kid_rsa(ct, pri) 200 """ n, d = key return (msg*d) % n #################### Morse Code ###################################### morse_char = { ".-": "A", "-...": "B", "-.-.": "C", "-..": "D", ".": "E", "..-.": "F", "--.": "G", "....": "H", "..": "I", ".---": "J", "-.-": "K", ".-..": "L", "--": "M", "-.": "N", "---": "O", ".--.": "P", "--.-": "Q", ".-.": "R", "...": "S", "-": "T", "..-": "U", "...-": "V", ".--": "W", "-..-": "X", "-.--": "Y", "--..": "Z", "-----": "0", ".----": "1", "..---": "2", "...--": "3", "....-": "4", ".....": "5", "-....": "6", "--...": "7", "---..": "8", "----.": "9", ".-.-.-": ".", "--..--": ",", "---...": ":", "-.-.-.": ";", "..--..": "?", "-....-": "-", "..--.-": "_", "-.--.": "(", "-.--.-": ")", ".----.": "'", "-...-": "=", ".-.-.": "+", "-..-.": "/", ".--.-.": "@", "...-..-": "$", "-.-.--": "!"} char_morse = {v: k for k, v in morse_char.items()} def encode_morse(msg, sep='|', mapping=None): """ Encodes a plaintext into popular Morse Code with letters separated by ``sep`` and words by a double ``sep``. Examples ======== >>> from sympy.crypto.crypto import encode_morse >>> msg = 'ATTACK RIGHT FLANK' >>> encode_morse(msg) '.-|-|-|.-|-.-.|-.-||.-.|..|--.|....|-||..-.|.-..|.-|-.|-.-' References ========== .. [1] https://en.wikipedia.org/wiki/Morse_code """ mapping = mapping or char_morse assert sep not in mapping word_sep = 2*sep mapping[" "] = word_sep suffix = msg and msg[-1] in whitespace # normalize whitespace msg = (' ' if word_sep else '').join(msg.split()) # omit unmapped chars chars = set(''.join(msg.split())) ok = set(mapping.keys()) msg = translate(msg, None, ''.join(chars - ok)) morsestring = [] words = msg.split() for word in words: morseword = [] for letter in word: morseletter = mapping[letter] morseword.append(morseletter) word = sep.join(morseword) morsestring.append(word) return word_sep.join(morsestring) + (word_sep if suffix else '') def decode_morse(msg, sep='|', mapping=None): """ Decodes a Morse Code with letters separated by ``sep`` (default is '|') and words by `word_sep` (default is '||) into plaintext. Examples ======== >>> from sympy.crypto.crypto import decode_morse >>> mc = '--|---|...-|.||.|.-|...|-' >>> decode_morse(mc) 'MOVE EAST' References ========== .. [1] https://en.wikipedia.org/wiki/Morse_code """ mapping = mapping or morse_char word_sep = 2*sep characterstring = [] words = msg.strip(word_sep).split(word_sep) for word in words: letters = word.split(sep) chars = [mapping[c] for c in letters] word = ''.join(chars) characterstring.append(word) rv = " ".join(characterstring) return rv #################### LFSRs ########################################## def lfsr_sequence(key, fill, n): r""" This function creates an LFSR sequence. Parameters ========== key : list A list of finite field elements, `[c_0, c_1, \ldots, c_k].` fill : list The list of the initial terms of the LFSR sequence, `[x_0, x_1, \ldots, x_k].` n Number of terms of the sequence that the function returns. Returns ======= L The LFSR sequence defined by `x_{n+1} = c_k x_n + \ldots + c_0 x_{n-k}`, for `n \leq k`. Notes ===== S. Golomb [G]_ gives a list of three statistical properties a sequence of numbers `a = \{a_n\}_{n=1}^\infty`, `a_n \in \{0,1\}`, should display to be considered "random". Define the autocorrelation of `a` to be .. math:: C(k) = C(k,a) = \lim_{N\rightarrow \infty} {1\over N}\sum_{n=1}^N (-1)^{a_n + a_{n+k}}. In the case where `a` is periodic with period `P` then this reduces to .. math:: C(k) = {1\over P}\sum_{n=1}^P (-1)^{a_n + a_{n+k}}. Assume `a` is periodic with period `P`. - balance: .. math:: \left|\sum_{n=1}^P(-1)^{a_n}\right| \leq 1. - low autocorrelation: .. math:: C(k) = \left\{ \begin{array}{cc} 1,& k = 0,\\ \epsilon, & k \ne 0. \end{array} \right. (For sequences satisfying these first two properties, it is known that `\epsilon = -1/P` must hold.) - proportional runs property: In each period, half the runs have length `1`, one-fourth have length `2`, etc. Moreover, there are as many runs of `1`'s as there are of `0`'s. Examples ======== >>> from sympy.crypto.crypto import lfsr_sequence >>> from sympy.polys.domains import FF >>> F = FF(2) >>> fill = [F(1), F(1), F(0), F(1)] >>> key = [F(1), F(0), F(0), F(1)] >>> lfsr_sequence(key, fill, 10) [1 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 1 mod 2, 0 mod 2, 0 mod 2, 1 mod 2] References ========== .. [G] Solomon Golomb, Shift register sequences, Aegean Park Press, Laguna Hills, Ca, 1967 """ if not isinstance(key, list): raise TypeError("key must be a list") if not isinstance(fill, list): raise TypeError("fill must be a list") p = key[0].mod F = FF(p) s = fill k = len(fill) L = [] for i in range(n): s0 = s[:] L.append(s[0]) s = s[1:k] x = sum([int(key[i]*s0[i]) for i in range(k)]) s.append(F(x)) return L # use [x.to_int() for x in L] for int version def lfsr_autocorrelation(L, P, k): """ This function computes the LFSR autocorrelation function. Parameters ========== L A periodic sequence of elements of `GF(2)`. L must have length larger than P. P The period of L. k : int An integer `k` (`0 < k < P`). Returns ======= autocorrelation The k-th value of the autocorrelation of the LFSR L. Examples ======== >>> from sympy.crypto.crypto import ( ... lfsr_sequence, lfsr_autocorrelation) >>> from sympy.polys.domains import FF >>> F = FF(2) >>> fill = [F(1), F(1), F(0), F(1)] >>> key = [F(1), F(0), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_autocorrelation(s, 15, 7) -1/15 >>> lfsr_autocorrelation(s, 15, 0) 1 """ if not isinstance(L, list): raise TypeError("L (=%s) must be a list" % L) P = int(P) k = int(k) L0 = L[:P] # slices makes a copy L1 = L0 + L0[:k] L2 = [(-1)**(L1[i].to_int() + L1[i + k].to_int()) for i in range(P)] tot = sum(L2) return Rational(tot, P) def lfsr_connection_polynomial(s): """ This function computes the LFSR connection polynomial. Parameters ========== s A sequence of elements of even length, with entries in a finite field. Returns ======= C(x) The connection polynomial of a minimal LFSR yielding s. This implements the algorithm in section 3 of J. L. Massey's article [M]_. Examples ======== >>> from sympy.crypto.crypto import ( ... lfsr_sequence, lfsr_connection_polynomial) >>> from sympy.polys.domains import FF >>> F = FF(2) >>> fill = [F(1), F(1), F(0), F(1)] >>> key = [F(1), F(0), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**4 + x + 1 >>> fill = [F(1), F(0), F(0), F(1)] >>> key = [F(1), F(1), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**3 + 1 >>> fill = [F(1), F(0), F(1)] >>> key = [F(1), F(1), F(0)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**3 + x**2 + 1 >>> fill = [F(1), F(0), F(1)] >>> key = [F(1), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**3 + x + 1 References ========== .. [M] James L. Massey, "Shift-Register Synthesis and BCH Decoding." IEEE Trans. on Information Theory, vol. 15(1), pp. 122-127, Jan 1969. """ # Initialization: p = s[0].mod x = Symbol("x") C = 1*x**0 B = 1*x**0 m = 1 b = 1*x**0 L = 0 N = 0 while N < len(s): if L > 0: dC = Poly(C).degree() r = min(L + 1, dC + 1) coeffsC = [C.subs(x, 0)] + [C.coeff(x**i) for i in range(1, dC + 1)] d = (s[N].to_int() + sum([coeffsC[i]*s[N - i].to_int() for i in range(1, r)])) % p if L == 0: d = s[N].to_int()*x**0 if d == 0: m += 1 N += 1 if d > 0: if 2*L > N: C = (C - d*((b**(p - 2)) % p)*x**m*B).expand() m += 1 N += 1 else: T = C C = (C - d*((b**(p - 2)) % p)*x**m*B).expand() L = N + 1 - L m = 1 b = d B = T N += 1 dC = Poly(C).degree() coeffsC = [C.subs(x, 0)] + [C.coeff(x**i) for i in range(1, dC + 1)] return sum([coeffsC[i] % p*x**i for i in range(dC + 1) if coeffsC[i] is not None]) #################### ElGamal ############################# def elgamal_private_key(digit=10, seed=None): r""" Return three number tuple as private key. Explanation =========== Elgamal encryption is based on the mathmatical problem called the Discrete Logarithm Problem (DLP). For example, `a^{b} \equiv c \pmod p` In general, if ``a`` and ``b`` are known, ``ct`` is easily calculated. If ``b`` is unknown, it is hard to use ``a`` and ``ct`` to get ``b``. Parameters ========== digit : int Minimum number of binary digits for key. Returns ======= tuple : (p, r, d) p = prime number. r = primitive root. d = random number. Notes ===== For testing purposes, the ``seed`` parameter may be set to control the output of this routine. See sympy.testing.randtest._randrange. Examples ======== >>> from sympy.crypto.crypto import elgamal_private_key >>> from sympy.ntheory import is_primitive_root, isprime >>> a, b, _ = elgamal_private_key() >>> isprime(a) True >>> is_primitive_root(b, a) True """ randrange = _randrange(seed) p = nextprime(2**digit) return p, primitive_root(p), randrange(2, p) def elgamal_public_key(key): r""" Return three number tuple as public key. Parameters ========== key : (p, r, e) Tuple generated by ``elgamal_private_key``. Returns ======= tuple : (p, r, e) `e = r**d \bmod p` `d` is a random number in private key. Examples ======== >>> from sympy.crypto.crypto import elgamal_public_key >>> elgamal_public_key((1031, 14, 636)) (1031, 14, 212) """ p, r, e = key return p, r, pow(r, e, p) def encipher_elgamal(i, key, seed=None): r""" Encrypt message with public key. Explanation =========== ``i`` is a plaintext message expressed as an integer. ``key`` is public key (p, r, e). In order to encrypt a message, a random number ``a`` in ``range(2, p)`` is generated and the encryped message is returned as `c_{1}` and `c_{2}` where: `c_{1} \equiv r^{a} \pmod p` `c_{2} \equiv m e^{a} \pmod p` Parameters ========== msg int of encoded message. key Public key. Returns ======= tuple : (c1, c2) Encipher into two number. Notes ===== For testing purposes, the ``seed`` parameter may be set to control the output of this routine. See sympy.testing.randtest._randrange. Examples ======== >>> from sympy.crypto.crypto import encipher_elgamal, elgamal_private_key, elgamal_public_key >>> pri = elgamal_private_key(5, seed=[3]); pri (37, 2, 3) >>> pub = elgamal_public_key(pri); pub (37, 2, 8) >>> msg = 36 >>> encipher_elgamal(msg, pub, seed=[3]) (8, 6) """ p, r, e = key if i < 0 or i >= p: raise ValueError( 'Message (%s) should be in range(%s)' % (i, p)) randrange = _randrange(seed) a = randrange(2, p) return pow(r, a, p), i*pow(e, a, p) % p def decipher_elgamal(msg, key): r""" Decrypt message with private key. `msg = (c_{1}, c_{2})` `key = (p, r, d)` According to extended Eucliden theorem, `u c_{1}^{d} + p n = 1` `u \equiv 1/{{c_{1}}^d} \pmod p` `u c_{2} \equiv \frac{1}{c_{1}^d} c_{2} \equiv \frac{1}{r^{ad}} c_{2} \pmod p` `\frac{1}{r^{ad}} m e^a \equiv \frac{1}{r^{ad}} m {r^{d a}} \equiv m \pmod p` Examples ======== >>> from sympy.crypto.crypto import decipher_elgamal >>> from sympy.crypto.crypto import encipher_elgamal >>> from sympy.crypto.crypto import elgamal_private_key >>> from sympy.crypto.crypto import elgamal_public_key >>> pri = elgamal_private_key(5, seed=[3]) >>> pub = elgamal_public_key(pri); pub (37, 2, 8) >>> msg = 17 >>> decipher_elgamal(encipher_elgamal(msg, pub), pri) == msg True """ p, _, d = key c1, c2 = msg u = igcdex(c1**d, p)[0] return u * c2 % p ################ Diffie-Hellman Key Exchange ######################### def dh_private_key(digit=10, seed=None): r""" Return three integer tuple as private key. Explanation =========== Diffie-Hellman key exchange is based on the mathematical problem called the Discrete Logarithm Problem (see ElGamal). Diffie-Hellman key exchange is divided into the following steps: * Alice and Bob agree on a base that consist of a prime ``p`` and a primitive root of ``p`` called ``g`` * Alice choses a number ``a`` and Bob choses a number ``b`` where ``a`` and ``b`` are random numbers in range `[2, p)`. These are their private keys. * Alice then publicly sends Bob `g^{a} \pmod p` while Bob sends Alice `g^{b} \pmod p` * They both raise the received value to their secretly chosen number (``a`` or ``b``) and now have both as their shared key `g^{ab} \pmod p` Parameters ========== digit Minimum number of binary digits required in key. Returns ======= tuple : (p, g, a) p = prime number. g = primitive root of p. a = random number from 2 through p - 1. Notes ===== For testing purposes, the ``seed`` parameter may be set to control the output of this routine. See sympy.testing.randtest._randrange. Examples ======== >>> from sympy.crypto.crypto import dh_private_key >>> from sympy.ntheory import isprime, is_primitive_root >>> p, g, _ = dh_private_key() >>> isprime(p) True >>> is_primitive_root(g, p) True >>> p, g, _ = dh_private_key(5) >>> isprime(p) True >>> is_primitive_root(g, p) True """ p = nextprime(2**digit) g = primitive_root(p) randrange = _randrange(seed) a = randrange(2, p) return p, g, a def dh_public_key(key): r""" Return three number tuple as public key. This is the tuple that Alice sends to Bob. Parameters ========== key : (p, g, a) A tuple generated by ``dh_private_key``. Returns ======= tuple : int, int, int A tuple of `(p, g, g^a \mod p)` with `p`, `g` and `a` given as parameters.s Examples ======== >>> from sympy.crypto.crypto import dh_private_key, dh_public_key >>> p, g, a = dh_private_key(); >>> _p, _g, x = dh_public_key((p, g, a)) >>> p == _p and g == _g True >>> x == pow(g, a, p) True """ p, g, a = key return p, g, pow(g, a, p) def dh_shared_key(key, b): """ Return an integer that is the shared key. This is what Bob and Alice can both calculate using the public keys they received from each other and their private keys. Parameters ========== key : (p, g, x) Tuple `(p, g, x)` generated by ``dh_public_key``. b Random number in the range of `2` to `p - 1` (Chosen by second key exchange member (Bob)). Returns ======= int A shared key. Examples ======== >>> from sympy.crypto.crypto import ( ... dh_private_key, dh_public_key, dh_shared_key) >>> prk = dh_private_key(); >>> p, g, x = dh_public_key(prk); >>> sk = dh_shared_key((p, g, x), 1000) >>> sk == pow(x, 1000, p) True """ p, _, x = key if 1 >= b or b >= p: raise ValueError(filldedent(''' Value of b should be greater 1 and less than prime %s.''' % p)) return pow(x, b, p) ################ Goldwasser-Micali Encryption ######################### def _legendre(a, p): """ Returns the legendre symbol of a and p assuming that p is a prime. i.e. 1 if a is a quadratic residue mod p -1 if a is not a quadratic residue mod p 0 if a is divisible by p Parameters ========== a : int The number to test. p : prime The prime to test ``a`` against. Returns ======= int Legendre symbol (a / p). """ sig = pow(a, (p - 1)//2, p) if sig == 1: return 1 elif sig == 0: return 0 else: return -1 def _random_coprime_stream(n, seed=None): randrange = _randrange(seed) while True: y = randrange(n) if gcd(y, n) == 1: yield y def gm_private_key(p, q, a=None): """ Check if ``p`` and ``q`` can be used as private keys for the Goldwasser-Micali encryption. The method works roughly as follows. Explanation =========== $\\cdot$ Pick two large primes $p$ and $q$. $\\cdot$ Call their product $N$. $\\cdot$ Given a message as an integer $i$, write $i$ in its bit representation $b_0$ , $\\dotsc$ , $b_n$ . $\\cdot$ For each $k$ , if $b_k$ = 0: let $a_k$ be a random square (quadratic residue) modulo $p q$ such that $jacobi \\_symbol(a, p q) = 1$ if $b_k$ = 1: let $a_k$ be a random non-square (non-quadratic residue) modulo $p q$ such that $jacobi \\_ symbol(a, p q) = 1$ returns [$a_1$ , $a_2$ , $\\dotsc$ ] $b_k$ can be recovered by checking whether or not $a_k$ is a residue. And from the $b_k$ 's, the message can be reconstructed. The idea is that, while $jacobi \\_ symbol(a, p q)$ can be easily computed (and when it is equal to $-1$ will tell you that $a$ is not a square mod $p q$ ), quadratic residuosity modulo a composite number is hard to compute without knowing its factorization. Moreover, approximately half the numbers coprime to $p q$ have $jacobi \\_ symbol$ equal to $1$ . And among those, approximately half are residues and approximately half are not. This maximizes the entropy of the code. Parameters ========== p, q, a Initialization variables. Returns ======= tuple : (p, q) The input value ``p`` and ``q``. Raises ====== ValueError If ``p`` and ``q`` are not distinct odd primes. """ if p == q: raise ValueError("expected distinct primes, " "got two copies of %i" % p) elif not isprime(p) or not isprime(q): raise ValueError("first two arguments must be prime, " "got %i of %i" % (p, q)) elif p == 2 or q == 2: raise ValueError("first two arguments must not be even, " "got %i of %i" % (p, q)) return p, q def gm_public_key(p, q, a=None, seed=None): """ Compute public keys for ``p`` and ``q``. Note that in Goldwasser-Micali Encryption, public keys are randomly selected. Parameters ========== p, q, a : int, int, int Initialization variables. Returns ======= tuple : (a, N) ``a`` is the input ``a`` if it is not ``None`` otherwise some random integer coprime to ``p`` and ``q``. ``N`` is the product of ``p`` and ``q``. """ p, q = gm_private_key(p, q) N = p * q if a is None: randrange = _randrange(seed) while True: a = randrange(N) if _legendre(a, p) == _legendre(a, q) == -1: break else: if _legendre(a, p) != -1 or _legendre(a, q) != -1: return False return (a, N) def encipher_gm(i, key, seed=None): """ Encrypt integer 'i' using public_key 'key' Note that gm uses random encryption. Parameters ========== i : int The message to encrypt. key : (a, N) The public key. Returns ======= list : list of int The randomized encrypted message. """ if i < 0: raise ValueError( "message must be a non-negative " "integer: got %d instead" % i) a, N = key bits = [] while i > 0: bits.append(i % 2) i //= 2 gen = _random_coprime_stream(N, seed) rev = reversed(bits) encode = lambda b: next(gen)**2*pow(a, b) % N return [ encode(b) for b in rev ] def decipher_gm(message, key): """ Decrypt message 'message' using public_key 'key'. Parameters ========== message : list of int The randomized encrypted message. key : (p, q) The private key. Returns ======= int The encrypted message. """ p, q = key res = lambda m, p: _legendre(m, p) > 0 bits = [res(m, p) * res(m, q) for m in message] m = 0 for b in bits: m <<= 1 m += not b return m ########### RailFence Cipher ############# def encipher_railfence(message,rails): """ Performs Railfence Encryption on plaintext and returns ciphertext Examples ======== >>> from sympy.crypto.crypto import encipher_railfence >>> message = "hello world" >>> encipher_railfence(message,3) 'horel ollwd' Parameters ========== message : string, the message to encrypt. rails : int, the number of rails. Returns ======= The Encrypted string message. References ========== .. [1] https://en.wikipedia.org/wiki/Rail_fence_cipher """ r = list(range(rails)) p = cycle(r + r[-2:0:-1]) return ''.join(sorted(message, key=lambda i: next(p))) def decipher_railfence(ciphertext,rails): """ Decrypt the message using the given rails Examples ======== >>> from sympy.crypto.crypto import decipher_railfence >>> decipher_railfence("horel ollwd",3) 'hello world' Parameters ========== message : string, the message to encrypt. rails : int, the number of rails. Returns ======= The Decrypted string message. """ r = list(range(rails)) p = cycle(r + r[-2:0:-1]) idx = sorted(range(len(ciphertext)), key=lambda i: next(p)) res = [''] * len(ciphertext) for i, c in zip(idx, ciphertext): res[i] = c return ''.join(res) ################ Blum-Goldwasser cryptosystem ######################### def bg_private_key(p, q): """ Check if p and q can be used as private keys for the Blum-Goldwasser cryptosystem. Explanation =========== The three necessary checks for p and q to pass so that they can be used as private keys: 1. p and q must both be prime 2. p and q must be distinct 3. p and q must be congruent to 3 mod 4 Parameters ========== p, q The keys to be checked. Returns ======= p, q Input values. Raises ====== ValueError If p and q do not pass the above conditions. """ if not isprime(p) or not isprime(q): raise ValueError("the two arguments must be prime, " "got %i and %i" %(p, q)) elif p == q: raise ValueError("the two arguments must be distinct, " "got two copies of %i. " %p) elif (p - 3) % 4 != 0 or (q - 3) % 4 != 0: raise ValueError("the two arguments must be congruent to 3 mod 4, " "got %i and %i" %(p, q)) return p, q def bg_public_key(p, q): """ Calculates public keys from private keys. Explanation =========== The function first checks the validity of private keys passed as arguments and then returns their product. Parameters ========== p, q The private keys. Returns ======= N The public key. """ p, q = bg_private_key(p, q) N = p * q return N def encipher_bg(i, key, seed=None): """ Encrypts the message using public key and seed. Explanation =========== ALGORITHM: 1. Encodes i as a string of L bits, m. 2. Select a random element r, where 1 < r < key, and computes x = r^2 mod key. 3. Use BBS pseudo-random number generator to generate L random bits, b, using the initial seed as x. 4. Encrypted message, c_i = m_i XOR b_i, 1 <= i <= L. 5. x_L = x^(2^L) mod key. 6. Return (c, x_L) Parameters ========== i Message, a non-negative integer key The public key Returns ======= Tuple (encrypted_message, x_L) Raises ====== ValueError If i is negative. """ if i < 0: raise ValueError( "message must be a non-negative " "integer: got %d instead" % i) enc_msg = [] while i > 0: enc_msg.append(i % 2) i //= 2 enc_msg.reverse() L = len(enc_msg) r = _randint(seed)(2, key - 1) x = r**2 % key x_L = pow(int(x), int(2**L), int(key)) rand_bits = [] for _ in range(L): rand_bits.append(x % 2) x = x**2 % key encrypt_msg = [m ^ b for (m, b) in zip(enc_msg, rand_bits)] return (encrypt_msg, x_L) def decipher_bg(message, key): """ Decrypts the message using private keys. Explanation =========== ALGORITHM: 1. Let, c be the encrypted message, y the second number received, and p and q be the private keys. 2. Compute, r_p = y^((p+1)/4 ^ L) mod p and r_q = y^((q+1)/4 ^ L) mod q. 3. Compute x_0 = (q(q^-1 mod p)r_p + p(p^-1 mod q)r_q) mod N. 4. From, recompute the bits using the BBS generator, as in the encryption algorithm. 5. Compute original message by XORing c and b. Parameters ========== message Tuple of encrypted message and a non-negative integer. key Tuple of private keys. Returns ======= orig_msg The original message """ p, q = key encrypt_msg, y = message public_key = p * q L = len(encrypt_msg) p_t = ((p + 1)/4)**L q_t = ((q + 1)/4)**L r_p = pow(int(y), int(p_t), int(p)) r_q = pow(int(y), int(q_t), int(q)) x = (q * mod_inverse(q, p) * r_p + p * mod_inverse(p, q) * r_q) % public_key orig_bits = [] for _ in range(L): orig_bits.append(x % 2) x = x**2 % public_key orig_msg = 0 for (m, b) in zip(encrypt_msg, orig_bits): orig_msg = orig_msg * 2 orig_msg += (m ^ b) return orig_msg
876bcaf9f64db85d403d72f00b778785051c020595bfb9b90656df1c1fe75bdc
""" The classes used here are for the internal use of assumptions system only and should not be used anywhere else as these don't possess the signatures common to SymPy objects. For general use of logic constructs please refer to sympy.logic classes And, Or, Not, etc. """ from itertools import combinations, product from sympy import S, Nor, Nand, Xor, Implies, Equivalent, ITE from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le from sympy.logic.boolalg import Or, And, Not, Xnor from itertools import zip_longest class Literal: """ The smallest element of a CNF object. Parameters ========== lit : Boolean expression is_Not : bool Examples ======== >>> from sympy import Q >>> from sympy.assumptions.cnf import Literal >>> from sympy.abc import x >>> Literal(Q.even(x)) Literal(Q.even(x), False) >>> Literal(~Q.even(x)) Literal(Q.even(x), True) """ def __new__(cls, lit, is_Not=False): if isinstance(lit, Not): lit = lit.args[0] is_Not = True elif isinstance(lit, (AND, OR, Literal)): return ~lit if is_Not else lit obj = super().__new__(cls) obj.lit = lit obj.is_Not = is_Not return obj @property def arg(self): return self.lit def rcall(self, expr): if callable(self.lit): lit = self.lit(expr) else: try: lit = self.lit.apply(expr) except AttributeError: lit = self.lit.rcall(expr) return type(self)(lit, self.is_Not) def __invert__(self): is_Not = not self.is_Not return Literal(self.lit, is_Not) def __str__(self): return '{}({}, {})'.format(type(self).__name__, self.lit, self.is_Not) __repr__ = __str__ def __eq__(self, other): return self.arg == other.arg and self.is_Not == other.is_Not def __hash__(self): h = hash((type(self).__name__, self.arg, self.is_Not)) return h class OR: """ A low-level implementation for Or """ def __init__(self, *args): self._args = args @property def args(self): return sorted(self._args, key=str) def rcall(self, expr): return type(self)(*[arg.rcall(expr) for arg in self._args ]) def __invert__(self): return AND(*[~arg for arg in self._args]) def __hash__(self): return hash((type(self).__name__,) + tuple(self.args)) def __eq__(self, other): return self.args == other.args def __str__(self): s = '(' + ' | '.join([str(arg) for arg in self.args]) + ')' return s __repr__ = __str__ class AND: """ A low-level implementation for And """ def __init__(self, *args): self._args = args def __invert__(self): return OR(*[~arg for arg in self._args]) @property def args(self): return sorted(self._args, key=str) def rcall(self, expr): return type(self)(*[arg.rcall(expr) for arg in self._args ]) def __hash__(self): return hash((type(self).__name__,) + tuple(self.args)) def __eq__(self, other): return self.args == other.args def __str__(self): s = '('+' & '.join([str(arg) for arg in self.args])+')' return s __repr__ = __str__ def to_NNF(expr, composite_map=None): """ Generates the Negation Normal Form of any boolean expression in terms of AND, OR, and Literal objects. Examples ======== >>> from sympy import Q, Eq >>> from sympy.assumptions.cnf import to_NNF >>> from sympy.abc import x, y >>> expr = Q.even(x) & ~Q.positive(x) >>> to_NNF(expr) (Literal(Q.even(x), False) & Literal(Q.positive(x), True)) Supported boolean objects are converted to corresponding predicates. >>> to_NNF(Eq(x, y)) Literal(Q.eq(x, y), False) If ``composite_map`` argument is given, ``to_NNF`` decomposes the specified predicate into a combination of primitive predicates. >>> cmap = {Q.nonpositive: Q.negative | Q.zero} >>> to_NNF(Q.nonpositive, cmap) (Literal(Q.negative, False) | Literal(Q.zero, False)) >>> to_NNF(Q.nonpositive(x), cmap) (Literal(Q.negative(x), False) | Literal(Q.zero(x), False)) """ from sympy.assumptions.ask import Q from sympy.assumptions.assume import AppliedPredicate, Predicate if composite_map is None: composite_map = dict() binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le} if type(expr) in binrelpreds: pred = binrelpreds[type(expr)] expr = pred(*expr.args) if isinstance(expr, Not): arg = expr.args[0] tmp = to_NNF(arg, composite_map) # Strategy: negate the NNF of expr return ~tmp if isinstance(expr, Or): return OR(*[to_NNF(x, composite_map) for x in Or.make_args(expr)]) if isinstance(expr, And): return AND(*[to_NNF(x, composite_map) for x in And.make_args(expr)]) if isinstance(expr, Nand): tmp = AND(*[to_NNF(x, composite_map) for x in expr.args]) return ~tmp if isinstance(expr, Nor): tmp = OR(*[to_NNF(x, composite_map) for x in expr.args]) return ~tmp if isinstance(expr, Xor): cnfs = [] for i in range(0, len(expr.args) + 1, 2): for neg in combinations(expr.args, i): clause = [~to_NNF(s, composite_map) if s in neg else to_NNF(s, composite_map) for s in expr.args] cnfs.append(OR(*clause)) return AND(*cnfs) if isinstance(expr, Xnor): cnfs = [] for i in range(0, len(expr.args) + 1, 2): for neg in combinations(expr.args, i): clause = [~to_NNF(s, composite_map) if s in neg else to_NNF(s, composite_map) for s in expr.args] cnfs.append(OR(*clause)) return ~AND(*cnfs) if isinstance(expr, Implies): L, R = to_NNF(expr.args[0], composite_map), to_NNF(expr.args[1], composite_map) return OR(~L, R) if isinstance(expr, Equivalent): cnfs = [] for a, b in zip_longest(expr.args, expr.args[1:], fillvalue=expr.args[0]): a = to_NNF(a, composite_map) b = to_NNF(b, composite_map) cnfs.append(OR(~a, b)) return AND(*cnfs) if isinstance(expr, ITE): L = to_NNF(expr.args[0], composite_map) M = to_NNF(expr.args[1], composite_map) R = to_NNF(expr.args[2], composite_map) return AND(OR(~L, M), OR(L, R)) if isinstance(expr, AppliedPredicate): pred, args = expr.function, expr.arguments newpred = composite_map.get(pred, None) if newpred is not None: return to_NNF(newpred.rcall(*args), composite_map) if isinstance(expr, Predicate): newpred = composite_map.get(expr, None) if newpred is not None: return to_NNF(newpred, composite_map) return Literal(expr) def distribute_AND_over_OR(expr): """ Distributes AND over OR in the NNF expression. Returns the result( Conjunctive Normal Form of expression) as a CNF object. """ if not isinstance(expr, (AND, OR)): tmp = set() tmp.add(frozenset((expr,))) return CNF(tmp) if isinstance(expr, OR): return CNF.all_or(*[distribute_AND_over_OR(arg) for arg in expr._args]) if isinstance(expr, AND): return CNF.all_and(*[distribute_AND_over_OR(arg) for arg in expr._args]) class CNF: """ Class to represent CNF of a Boolean expression. Consists of set of clauses, which themselves are stored as frozenset of Literal objects. Examples ======== >>> from sympy import Q >>> from sympy.assumptions.cnf import CNF >>> from sympy.abc import x >>> cnf = CNF.from_prop(Q.real(x) & ~Q.zero(x)) >>> cnf.clauses {frozenset({Literal(Q.zero(x), True)}), frozenset({Literal(Q.negative(x), False), Literal(Q.positive(x), False), Literal(Q.zero(x), False)})} """ def __init__(self, clauses=None): if not clauses: clauses = set() self.clauses = clauses def add(self, prop): clauses = CNF.to_CNF(prop).clauses self.add_clauses(clauses) def __str__(self): s = ' & '.join( ['(' + ' | '.join([str(lit) for lit in clause]) +')' for clause in self.clauses] ) return s def extend(self, props): for p in props: self.add(p) return self def copy(self): return CNF(set(self.clauses)) def add_clauses(self, clauses): self.clauses |= clauses @classmethod def from_prop(cls, prop): res = cls() res.add(prop) return res def __iand__(self, other): self.add_clauses(other.clauses) return self def all_predicates(self): predicates = set() for c in self.clauses: predicates |= {arg.lit for arg in c} return predicates def _or(self, cnf): clauses = set() for a, b in product(self.clauses, cnf.clauses): tmp = set(a) for t in b: tmp.add(t) clauses.add(frozenset(tmp)) return CNF(clauses) def _and(self, cnf): clauses = self.clauses.union(cnf.clauses) return CNF(clauses) def _not(self): clss = list(self.clauses) ll = set() for x in clss[-1]: ll.add(frozenset((~x,))) ll = CNF(ll) for rest in clss[:-1]: p = set() for x in rest: p.add(frozenset((~x,))) ll = ll._or(CNF(p)) return ll def rcall(self, expr): clause_list = list() for clause in self.clauses: lits = [arg.rcall(expr) for arg in clause] clause_list.append(OR(*lits)) expr = AND(*clause_list) return distribute_AND_over_OR(expr) @classmethod def all_or(cls, *cnfs): b = cnfs[0].copy() for rest in cnfs[1:]: b = b._or(rest) return b @classmethod def all_and(cls, *cnfs): b = cnfs[0].copy() for rest in cnfs[1:]: b = b._and(rest) return b @classmethod def to_CNF(cls, expr): from sympy.assumptions.facts import get_composite_predicates expr = to_NNF(expr, get_composite_predicates()) expr = distribute_AND_over_OR(expr) return expr @classmethod def CNF_to_cnf(cls, cnf): """ Converts CNF object to SymPy's boolean expression retaining the form of expression. """ def remove_literal(arg): return Not(arg.lit) if arg.is_Not else arg.lit return And(*(Or(*(remove_literal(arg) for arg in clause)) for clause in cnf.clauses)) class EncodedCNF: """ Class for encoding the CNF expression. """ def __init__(self, data=None, encoding=None): if not data and not encoding: data = list() encoding = dict() self.data = data self.encoding = encoding self._symbols = list(encoding.keys()) def from_cnf(self, cnf): self._symbols = list(cnf.all_predicates()) n = len(self._symbols) self.encoding = dict(list(zip(self._symbols, list(range(1, n + 1))))) self.data = [self.encode(clause) for clause in cnf.clauses] @property def symbols(self): return self._symbols @property def variables(self): return range(1, len(self._symbols) + 1) def copy(self): new_data = [set(clause) for clause in self.data] return EncodedCNF(new_data, dict(self.encoding)) def add_prop(self, prop): cnf = CNF.from_prop(prop) self.add_from_cnf(cnf) def add_from_cnf(self, cnf): clauses = [self.encode(clause) for clause in cnf.clauses] self.data += clauses def encode_arg(self, arg): literal = arg.lit value = self.encoding.get(literal, None) if value is None: n = len(self._symbols) self._symbols.append(literal) value = self.encoding[literal] = n + 1 if arg.is_Not: return -value else: return value def encode(self, clause): return {self.encode_arg(arg) if not arg.lit == S.false else 0 for arg in clause}
154341463b68cfdc658b182284aaa440f8174f7ad8e0b60b07a26d7b312d5f71
""" This module contains functions to: - solve a single equation for a single variable, in any domain either real or complex. - solve a single transcendental equation for a single variable in any domain either real or complex. (currently supports solving in real domain only) - solve a system of linear equations with N variables and M equations. - solve a system of Non Linear Equations with N variables and M equations """ from sympy.core.sympify import sympify from sympy.core import (S, Pow, Dummy, pi, Expr, Wild, Mul, Equality, Add) from sympy.core.containers import Tuple from sympy.core.numbers import I, Number, Rational, oo from sympy.core.function import (Lambda, expand_complex, AppliedUndef, expand_log) from sympy.core.mod import Mod from sympy.core.numbers import igcd from sympy.core.relational import Eq, Ne, Relational from sympy.core.symbol import Symbol, _uniquely_named_symbol from sympy.core.sympify import _sympify from sympy.simplify.simplify import simplify, fraction, trigsimp from sympy.simplify import powdenest, logcombine from sympy.functions import (log, Abs, tan, cot, sin, cos, sec, csc, exp, acos, asin, acsc, asec, arg, piecewise_fold, Piecewise) from sympy.functions.elementary.trigonometric import (TrigonometricFunction, HyperbolicFunction) from sympy.functions.elementary.miscellaneous import real_root from sympy.logic.boolalg import And from sympy.sets import (FiniteSet, EmptySet, imageset, Interval, Intersection, Union, ConditionSet, ImageSet, Complement, Contains) from sympy.sets.sets import Set, ProductSet from sympy.matrices import Matrix, MatrixBase from sympy.ntheory import totient from sympy.ntheory.factor_ import divisors from sympy.ntheory.residue_ntheory import discrete_log, nthroot_mod from sympy.polys import (roots, Poly, degree, together, PolynomialError, RootOf, factor, lcm, gcd) from sympy.polys.polyerrors import CoercionFailed from sympy.polys.polytools import invert from sympy.polys.solvers import (sympy_eqs_to_ring, solve_lin_sys, PolyNonlinearError) from sympy.polys.matrices.linsolve import _linsolve from sympy.solvers.solvers import (checksol, denoms, unrad, _simple_dens, recast_to_symbols) from sympy.solvers.polysys import solve_poly_system from sympy.solvers.inequalities import solve_univariate_inequality from sympy.utilities import filldedent from sympy.utilities.iterables import numbered_symbols, has_dups from sympy.calculus.util import periodicity, continuous_domain from sympy.core.compatibility import ordered, default_sort_key, is_sequence from types import GeneratorType from collections import defaultdict class NonlinearError(ValueError): """Raised when unexpectedly encountering nonlinear equations""" pass _rc = Dummy("R", real=True), Dummy("C", complex=True) def _masked(f, *atoms): """Return ``f``, with all objects given by ``atoms`` replaced with Dummy symbols, ``d``, and the list of replacements, ``(d, e)``, where ``e`` is an object of type given by ``atoms`` in which any other instances of atoms have been recursively replaced with Dummy symbols, too. The tuples are ordered so that if they are applied in sequence, the origin ``f`` will be restored. Examples ======== >>> from sympy import cos >>> from sympy.abc import x >>> from sympy.solvers.solveset import _masked >>> f = cos(cos(x) + 1) >>> f, reps = _masked(cos(1 + cos(x)), cos) >>> f _a1 >>> reps [(_a1, cos(_a0 + 1)), (_a0, cos(x))] >>> for d, e in reps: ... f = f.xreplace({d: e}) >>> f cos(cos(x) + 1) """ sym = numbered_symbols('a', cls=Dummy, real=True) mask = [] for a in ordered(f.atoms(*atoms)): for i in mask: a = a.replace(*i) mask.append((a, next(sym))) for i, (o, n) in enumerate(mask): f = f.replace(o, n) mask[i] = (n, o) mask = list(reversed(mask)) return f, mask def _invert(f_x, y, x, domain=S.Complexes): r""" Reduce the complex valued equation ``f(x) = y`` to a set of equations ``{g(x) = h_1(y), g(x) = h_2(y), ..., g(x) = h_n(y) }`` where ``g(x)`` is a simpler function than ``f(x)``. The return value is a tuple ``(g(x), set_h)``, where ``g(x)`` is a function of ``x`` and ``set_h`` is the set of function ``{h_1(y), h_2(y), ..., h_n(y)}``. Here, ``y`` is not necessarily a symbol. The ``set_h`` contains the functions, along with the information about the domain in which they are valid, through set operations. For instance, if ``y = Abs(x) - n`` is inverted in the real domain, then ``set_h`` is not simply `{-n, n}` as the nature of `n` is unknown; rather, it is: `Intersection([0, oo) {n}) U Intersection((-oo, 0], {-n})` By default, the complex domain is used which means that inverting even seemingly simple functions like ``exp(x)`` will give very different results from those obtained in the real domain. (In the case of ``exp(x)``, the inversion via ``log`` is multi-valued in the complex domain, having infinitely many branches.) If you are working with real values only (or you are not sure which function to use) you should probably set the domain to ``S.Reals`` (or use `invert\_real` which does that automatically). Examples ======== >>> from sympy.solvers.solveset import invert_complex, invert_real >>> from sympy.abc import x, y >>> from sympy import exp When does exp(x) == y? >>> invert_complex(exp(x), y, x) (x, ImageSet(Lambda(_n, I*(2*_n*pi + arg(y)) + log(Abs(y))), Integers)) >>> invert_real(exp(x), y, x) (x, Intersection({log(y)}, Reals)) When does exp(x) == 1? >>> invert_complex(exp(x), 1, x) (x, ImageSet(Lambda(_n, 2*_n*I*pi), Integers)) >>> invert_real(exp(x), 1, x) (x, {0}) See Also ======== invert_real, invert_complex """ x = sympify(x) if not x.is_Symbol: raise ValueError("x must be a symbol") f_x = sympify(f_x) if x not in f_x.free_symbols: raise ValueError("Inverse of constant function doesn't exist") y = sympify(y) if x in y.free_symbols: raise ValueError("y should be independent of x ") if domain.is_subset(S.Reals): x1, s = _invert_real(f_x, FiniteSet(y), x) else: x1, s = _invert_complex(f_x, FiniteSet(y), x) if not isinstance(s, FiniteSet) or x1 != x: return x1, s # Avoid adding gratuitous intersections with S.Complexes. Actual # conditions should be handled by the respective inverters. if domain is S.Complexes: return x1, s else: return x1, s.intersection(domain) invert_complex = _invert def invert_real(f_x, y, x): """ Inverts a real-valued function. Same as ``_invert``, but sets the domain to ``S.Reals`` before inverting. """ return _invert(f_x, y, x, S.Reals) def _invert_real(f, g_ys, symbol): """Helper function for _invert.""" if f == symbol: return (f, g_ys) n = Dummy('n', real=True) if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1): return _invert_real(f.exp, imageset(Lambda(n, log(n)), g_ys), symbol) if hasattr(f, 'inverse') and f.inverse() is not None and not isinstance(f, ( TrigonometricFunction, HyperbolicFunction, )): if len(f.args) > 1: raise ValueError("Only functions with one argument are supported.") return _invert_real(f.args[0], imageset(Lambda(n, f.inverse()(n)), g_ys), symbol) if isinstance(f, Abs): return _invert_abs(f.args[0], g_ys, symbol) if f.is_Add: # f = g + h g, h = f.as_independent(symbol) if g is not S.Zero: return _invert_real(h, imageset(Lambda(n, n - g), g_ys), symbol) if f.is_Mul: # f = g*h g, h = f.as_independent(symbol) if g is not S.One: return _invert_real(h, imageset(Lambda(n, n/g), g_ys), symbol) if f.is_Pow: base, expo = f.args base_has_sym = base.has(symbol) expo_has_sym = expo.has(symbol) if not expo_has_sym: if expo.is_rational: num, den = expo.as_numer_denom() if den % 2 == 0 and num % 2 == 1 and den.is_zero is False: root = Lambda(n, real_root(n, expo)) g_ys_pos = g_ys & Interval(0, oo) res = imageset(root, g_ys_pos) base_positive = solveset(base >= 0, symbol, S.Reals) _inv, _set = _invert_real(base, res, symbol) return (_inv, _set.intersect(base_positive)) if den % 2 == 1: root = Lambda(n, real_root(n, expo)) res = imageset(root, g_ys) if num % 2 == 0: neg_res = imageset(Lambda(n, -n), res) return _invert_real(base, res + neg_res, symbol) if num % 2 == 1: return _invert_real(base, res, symbol) elif expo.is_irrational: root = Lambda(n, real_root(n, expo)) g_ys_pos = g_ys & Interval(0, oo) res = imageset(root, g_ys_pos) return _invert_real(base, res, symbol) else: # indeterminate exponent, e.g. Float or parity of # num, den of rational could not be determined pass # use default return if not base_has_sym: rhs = g_ys.args[0] if base.is_positive: return _invert_real(expo, imageset(Lambda(n, log(n, base, evaluate=False)), g_ys), symbol) elif base.is_negative: from sympy.core.power import integer_log s, b = integer_log(rhs, base) if b: return _invert_real(expo, FiniteSet(s), symbol) else: return _invert_real(expo, S.EmptySet, symbol) elif base.is_zero: one = Eq(rhs, 1) if one == S.true: # special case: 0**x - 1 return _invert_real(expo, FiniteSet(0), symbol) elif one == S.false: return _invert_real(expo, S.EmptySet, symbol) if isinstance(f, TrigonometricFunction): if isinstance(g_ys, FiniteSet): def inv(trig): if isinstance(trig, (sin, csc)): F = asin if isinstance(trig, sin) else acsc return (lambda a: n*pi + (-1)**n*F(a),) if isinstance(trig, (cos, sec)): F = acos if isinstance(trig, cos) else asec return ( lambda a: 2*n*pi + F(a), lambda a: 2*n*pi - F(a),) if isinstance(trig, (tan, cot)): return (lambda a: n*pi + trig.inverse()(a),) n = Dummy('n', integer=True) invs = S.EmptySet for L in inv(f): invs += Union(*[imageset(Lambda(n, L(g)), S.Integers) for g in g_ys]) return _invert_real(f.args[0], invs, symbol) return (f, g_ys) def _invert_complex(f, g_ys, symbol): """Helper function for _invert.""" if f == symbol: return (f, g_ys) n = Dummy('n') if f.is_Add: # f = g + h g, h = f.as_independent(symbol) if g is not S.Zero: return _invert_complex(h, imageset(Lambda(n, n - g), g_ys), symbol) if f.is_Mul: # f = g*h g, h = f.as_independent(symbol) if g is not S.One: if g in {S.NegativeInfinity, S.ComplexInfinity, S.Infinity}: return (h, S.EmptySet) return _invert_complex(h, imageset(Lambda(n, n/g), g_ys), symbol) if f.is_Pow: base, expo = f.args # special case: g**r = 0 # Could be improved like `_invert_real` to handle more general cases. if expo.is_Rational and g_ys == FiniteSet(0): if expo.is_positive: return _invert_complex(base, g_ys, symbol) if hasattr(f, 'inverse') and f.inverse() is not None and \ not isinstance(f, TrigonometricFunction) and \ not isinstance(f, HyperbolicFunction) and \ not isinstance(f, exp): if len(f.args) > 1: raise ValueError("Only functions with one argument are supported.") return _invert_complex(f.args[0], imageset(Lambda(n, f.inverse()(n)), g_ys), symbol) if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1): if isinstance(g_ys, ImageSet): # can solve upto `(d*exp(exp(...(exp(a*x + b))...) + c)` format. # Further can be improved to `(d*exp(exp(...(exp(a*x**n + b*x**(n-1) + ... + f))...) + c)`. g_ys_expr = g_ys.lamda.expr g_ys_vars = g_ys.lamda.variables k = Dummy('k{}'.format(len(g_ys_vars))) g_ys_vars_1 = (k,) + g_ys_vars exp_invs = Union(*[imageset(Lambda((g_ys_vars_1,), (I*(2*k*pi + arg(g_ys_expr)) + log(Abs(g_ys_expr)))), S.Integers**(len(g_ys_vars_1)))]) elif isinstance(g_ys, FiniteSet): exp_invs = Union(*[imageset(Lambda(n, I*(2*n*pi + arg(g_y)) + log(Abs(g_y))), S.Integers) for g_y in g_ys if g_y != 0]) return _invert_complex(f.exp, exp_invs, symbol) return (f, g_ys) def _invert_abs(f, g_ys, symbol): """Helper function for inverting absolute value functions. Returns the complete result of inverting an absolute value function along with the conditions which must also be satisfied. If it is certain that all these conditions are met, a `FiniteSet` of all possible solutions is returned. If any condition cannot be satisfied, an `EmptySet` is returned. Otherwise, a `ConditionSet` of the solutions, with all the required conditions specified, is returned. """ if not g_ys.is_FiniteSet: # this could be used for FiniteSet, but the # results are more compact if they aren't, e.g. # ConditionSet(x, Contains(n, Interval(0, oo)), {-n, n}) vs # Union(Intersection(Interval(0, oo), {n}), Intersection(Interval(-oo, 0), {-n})) # for the solution of abs(x) - n pos = Intersection(g_ys, Interval(0, S.Infinity)) parg = _invert_real(f, pos, symbol) narg = _invert_real(-f, pos, symbol) if parg[0] != narg[0]: raise NotImplementedError return parg[0], Union(narg[1], parg[1]) # check conditions: all these must be true. If any are unknown # then return them as conditions which must be satisfied unknown = [] for a in g_ys.args: ok = a.is_nonnegative if a.is_Number else a.is_positive if ok is None: unknown.append(a) elif not ok: return symbol, S.EmptySet if unknown: conditions = And(*[Contains(i, Interval(0, oo)) for i in unknown]) else: conditions = True n = Dummy('n', real=True) # this is slightly different than above: instead of solving # +/-f on positive values, here we solve for f on +/- g_ys g_x, values = _invert_real(f, Union( imageset(Lambda(n, n), g_ys), imageset(Lambda(n, -n), g_ys)), symbol) return g_x, ConditionSet(g_x, conditions, values) def domain_check(f, symbol, p): """Returns False if point p is infinite or any subexpression of f is infinite or becomes so after replacing symbol with p. If none of these conditions is met then True will be returned. Examples ======== >>> from sympy import Mul, oo >>> from sympy.abc import x >>> from sympy.solvers.solveset import domain_check >>> g = 1/(1 + (1/(x + 1))**2) >>> domain_check(g, x, -1) False >>> domain_check(x**2, x, 0) True >>> domain_check(1/x, x, oo) False * The function relies on the assumption that the original form of the equation has not been changed by automatic simplification. >>> domain_check(x/x, x, 0) # x/x is automatically simplified to 1 True * To deal with automatic evaluations use evaluate=False: >>> domain_check(Mul(x, 1/x, evaluate=False), x, 0) False """ f, p = sympify(f), sympify(p) if p.is_infinite: return False return _domain_check(f, symbol, p) def _domain_check(f, symbol, p): # helper for domain check if f.is_Atom and f.is_finite: return True elif f.subs(symbol, p).is_infinite: return False elif isinstance(f, Piecewise): # Check the cases of the Piecewise in turn. There might be invalid # expressions in later cases that don't apply e.g. # solveset(Piecewise((0, Eq(x, 0)), (1/x, True)), x) for expr, cond in f.args: condsubs = cond.subs(symbol, p) if condsubs is S.false: continue elif condsubs is S.true: return _domain_check(expr, symbol, p) else: # We don't know which case of the Piecewise holds. On this # basis we cannot decide whether any solution is in or out of # the domain. Ideally this function would allow returning a # symbolic condition for the validity of the solution that # could be handled in the calling code. In the mean time we'll # give this particular solution the benefit of the doubt and # let it pass. return True else: # TODO : We should not blindly recurse through all args of arbitrary expressions like this return all(_domain_check(g, symbol, p) for g in f.args) def _is_finite_with_finite_vars(f, domain=S.Complexes): """ Return True if the given expression is finite. For symbols that don't assign a value for `complex` and/or `real`, the domain will be used to assign a value; symbols that don't assign a value for `finite` will be made finite. All other assumptions are left unmodified. """ def assumptions(s): A = s.assumptions0 A.setdefault('finite', A.get('finite', True)) if domain.is_subset(S.Reals): # if this gets set it will make complex=True, too A.setdefault('real', True) else: # don't change 'real' because being complex implies # nothing about being real A.setdefault('complex', True) return A reps = {s: Dummy(**assumptions(s)) for s in f.free_symbols} return f.xreplace(reps).is_finite def _is_function_class_equation(func_class, f, symbol): """ Tests whether the equation is an equation of the given function class. The given equation belongs to the given function class if it is comprised of functions of the function class which are multiplied by or added to expressions independent of the symbol. In addition, the arguments of all such functions must be linear in the symbol as well. Examples ======== >>> from sympy.solvers.solveset import _is_function_class_equation >>> from sympy import tan, sin, tanh, sinh, exp >>> from sympy.abc import x >>> from sympy.functions.elementary.trigonometric import (TrigonometricFunction, ... HyperbolicFunction) >>> _is_function_class_equation(TrigonometricFunction, exp(x) + tan(x), x) False >>> _is_function_class_equation(TrigonometricFunction, tan(x) + sin(x), x) True >>> _is_function_class_equation(TrigonometricFunction, tan(x**2), x) False >>> _is_function_class_equation(TrigonometricFunction, tan(x + 2), x) True >>> _is_function_class_equation(HyperbolicFunction, tanh(x) + sinh(x), x) True """ if f.is_Mul or f.is_Add: return all(_is_function_class_equation(func_class, arg, symbol) for arg in f.args) if f.is_Pow: if not f.exp.has(symbol): return _is_function_class_equation(func_class, f.base, symbol) else: return False if not f.has(symbol): return True if isinstance(f, func_class): try: g = Poly(f.args[0], symbol) return g.degree() <= 1 except PolynomialError: return False else: return False def _solve_as_rational(f, symbol, domain): """ solve rational functions""" from sympy.core.function import _mexpand f = together(_mexpand(f, recursive=True), deep=True) g, h = fraction(f) if not h.has(symbol): try: return _solve_as_poly(g, symbol, domain) except NotImplementedError: # The polynomial formed from g could end up having # coefficients in a ring over which finding roots # isn't implemented yet, e.g. ZZ[a] for some symbol a return ConditionSet(symbol, Eq(f, 0), domain) except CoercionFailed: # contained oo, zoo or nan return S.EmptySet else: valid_solns = _solveset(g, symbol, domain) invalid_solns = _solveset(h, symbol, domain) return valid_solns - invalid_solns class _SolveTrig1Error(Exception): """Raised when _solve_trig1 heuristics do not apply""" def _solve_trig(f, symbol, domain): """Function to call other helpers to solve trigonometric equations """ sol = None try: sol = _solve_trig1(f, symbol, domain) except _SolveTrig1Error: try: sol = _solve_trig2(f, symbol, domain) except ValueError: raise NotImplementedError(filldedent(''' Solution to this kind of trigonometric equations is yet to be implemented''')) return sol def _solve_trig1(f, symbol, domain): """Primary solver for trigonometric and hyperbolic equations Returns either the solution set as a ConditionSet (auto-evaluated to a union of ImageSets if no variables besides 'symbol' are involved) or raises _SolveTrig1Error if f == 0 can't be solved. Notes ===== Algorithm: 1. Do a change of variable x -> mu*x in arguments to trigonometric and hyperbolic functions, in order to reduce them to small integers. (This step is crucial to keep the degrees of the polynomials of step 4 low.) 2. Rewrite trigonometric/hyperbolic functions as exponentials. 3. Proceed to a 2nd change of variable, replacing exp(I*x) or exp(x) by y. 4. Solve the resulting rational equation. 5. Use invert_complex or invert_real to return to the original variable. 6. If the coefficients of 'symbol' were symbolic in nature, add the necessary consistency conditions in a ConditionSet. """ # Prepare change of variable x = Dummy('x') if _is_function_class_equation(HyperbolicFunction, f, symbol): cov = exp(x) inverter = invert_real if domain.is_subset(S.Reals) else invert_complex else: cov = exp(I*x) inverter = invert_complex f = trigsimp(f) f_original = f trig_functions = f.atoms(TrigonometricFunction, HyperbolicFunction) trig_arguments = [e.args[0] for e in trig_functions] # trigsimp may have reduced the equation to an expression # that is independent of 'symbol' (e.g. cos**2+sin**2) if not any(a.has(symbol) for a in trig_arguments): return solveset(f_original, symbol, domain) denominators = [] numerators = [] for ar in trig_arguments: try: poly_ar = Poly(ar, symbol) except PolynomialError: raise _SolveTrig1Error("trig argument is not a polynomial") if poly_ar.degree() > 1: # degree >1 still bad raise _SolveTrig1Error("degree of variable must not exceed one") if poly_ar.degree() == 0: # degree 0, don't care continue c = poly_ar.all_coeffs()[0] # got the coefficient of 'symbol' numerators.append(fraction(c)[0]) denominators.append(fraction(c)[1]) mu = lcm(denominators)/gcd(numerators) f = f.subs(symbol, mu*x) f = f.rewrite(exp) f = together(f) g, h = fraction(f) y = Dummy('y') g, h = g.expand(), h.expand() g, h = g.subs(cov, y), h.subs(cov, y) if g.has(x) or h.has(x): raise _SolveTrig1Error("change of variable not possible") solns = solveset_complex(g, y) - solveset_complex(h, y) if isinstance(solns, ConditionSet): raise _SolveTrig1Error("polynomial has ConditionSet solution") if isinstance(solns, FiniteSet): if any(isinstance(s, RootOf) for s in solns): raise _SolveTrig1Error("polynomial results in RootOf object") # revert the change of variable cov = cov.subs(x, symbol/mu) result = Union(*[inverter(cov, s, symbol)[1] for s in solns]) # In case of symbolic coefficients, the solution set is only valid # if numerator and denominator of mu are non-zero. if mu.has(Symbol): syms = (mu).atoms(Symbol) munum, muden = fraction(mu) condnum = munum.as_independent(*syms, as_Add=False)[1] condden = muden.as_independent(*syms, as_Add=False)[1] cond = And(Ne(condnum, 0), Ne(condden, 0)) else: cond = True # Actual conditions are returned as part of the ConditionSet. Adding an # intersection with C would only complicate some solution sets due to # current limitations of intersection code. (e.g. #19154) if domain is S.Complexes: # This is a slight abuse of ConditionSet. Ideally this should # be some kind of "PiecewiseSet". (See #19507 discussion) return ConditionSet(symbol, cond, result) else: return ConditionSet(symbol, cond, Intersection(result, domain)) elif solns is S.EmptySet: return S.EmptySet else: raise _SolveTrig1Error("polynomial solutions must form FiniteSet") def _solve_trig2(f, symbol, domain): """Secondary helper to solve trigonometric equations, called when first helper fails """ from sympy import ilcm, expand_trig f = trigsimp(f) f_original = f trig_functions = f.atoms(sin, cos, tan, sec, cot, csc) trig_arguments = [e.args[0] for e in trig_functions] denominators = [] numerators = [] # todo: This solver can be extended to hyperbolics if the # analogous change of variable to tanh (instead of tan) # is used. if not trig_functions: return ConditionSet(symbol, Eq(f_original, 0), domain) # todo: The pre-processing below (extraction of numerators, denominators, # gcd, lcm, mu, etc.) should be updated to the enhanced version in # _solve_trig1. (See #19507) for ar in trig_arguments: try: poly_ar = Poly(ar, symbol) except PolynomialError: raise ValueError("give up, we can't solve if this is not a polynomial in x") if poly_ar.degree() > 1: # degree >1 still bad raise ValueError("degree of variable inside polynomial should not exceed one") if poly_ar.degree() == 0: # degree 0, don't care continue c = poly_ar.all_coeffs()[0] # got the coefficient of 'symbol' try: numerators.append(Rational(c).p) denominators.append(Rational(c).q) except TypeError: return ConditionSet(symbol, Eq(f_original, 0), domain) x = Dummy('x') # ilcm() and igcd() require more than one argument if len(numerators) > 1: mu = Rational(2)*ilcm(*denominators)/igcd(*numerators) else: assert len(numerators) == 1 mu = Rational(2)*denominators[0]/numerators[0] f = f.subs(symbol, mu*x) f = f.rewrite(tan) f = expand_trig(f) f = together(f) g, h = fraction(f) y = Dummy('y') g, h = g.expand(), h.expand() g, h = g.subs(tan(x), y), h.subs(tan(x), y) if g.has(x) or h.has(x): return ConditionSet(symbol, Eq(f_original, 0), domain) solns = solveset(g, y, S.Reals) - solveset(h, y, S.Reals) if isinstance(solns, FiniteSet): result = Union(*[invert_real(tan(symbol/mu), s, symbol)[1] for s in solns]) dsol = invert_real(tan(symbol/mu), oo, symbol)[1] if degree(h) > degree(g): # If degree(denom)>degree(num) then there result = Union(result, dsol) # would be another sol at Lim(denom-->oo) return Intersection(result, domain) elif solns is S.EmptySet: return S.EmptySet else: return ConditionSet(symbol, Eq(f_original, 0), S.Reals) def _solve_as_poly(f, symbol, domain=S.Complexes): """ Solve the equation using polynomial techniques if it already is a polynomial equation or, with a change of variables, can be made so. """ result = None if f.is_polynomial(symbol): solns = roots(f, symbol, cubics=True, quartics=True, quintics=True, domain='EX') num_roots = sum(solns.values()) if degree(f, symbol) <= num_roots: result = FiniteSet(*solns.keys()) else: poly = Poly(f, symbol) solns = poly.all_roots() if poly.degree() <= len(solns): result = FiniteSet(*solns) else: result = ConditionSet(symbol, Eq(f, 0), domain) else: poly = Poly(f) if poly is None: result = ConditionSet(symbol, Eq(f, 0), domain) gens = [g for g in poly.gens if g.has(symbol)] if len(gens) == 1: poly = Poly(poly, gens[0]) gen = poly.gen deg = poly.degree() poly = Poly(poly.as_expr(), poly.gen, composite=True) poly_solns = FiniteSet(*roots(poly, cubics=True, quartics=True, quintics=True).keys()) if len(poly_solns) < deg: result = ConditionSet(symbol, Eq(f, 0), domain) if gen != symbol: y = Dummy('y') inverter = invert_real if domain.is_subset(S.Reals) else invert_complex lhs, rhs_s = inverter(gen, y, symbol) if lhs == symbol: result = Union(*[rhs_s.subs(y, s) for s in poly_solns]) else: result = ConditionSet(symbol, Eq(f, 0), domain) else: result = ConditionSet(symbol, Eq(f, 0), domain) if result is not None: if isinstance(result, FiniteSet): # this is to simplify solutions like -sqrt(-I) to sqrt(2)/2 # - sqrt(2)*I/2. We are not expanding for solution with symbols # or undefined functions because that makes the solution more complicated. # For example, expand_complex(a) returns re(a) + I*im(a) if all(s.atoms(Symbol, AppliedUndef) == set() and not isinstance(s, RootOf) for s in result): s = Dummy('s') result = imageset(Lambda(s, expand_complex(s)), result) if isinstance(result, FiniteSet) and domain != S.Complexes: # Avoid adding gratuitous intersections with S.Complexes. Actual # conditions should be handled elsewhere. result = result.intersection(domain) return result else: return ConditionSet(symbol, Eq(f, 0), domain) def _solve_radical(f, unradf, symbol, solveset_solver): """ Helper function to solve equations with radicals """ res = unradf eq, cov = res if res else (f, []) if not cov: result = solveset_solver(eq, symbol) - \ Union(*[solveset_solver(g, symbol) for g in denoms(f, symbol)]) else: y, yeq = cov if not solveset_solver(y - I, y): yreal = Dummy('yreal', real=True) yeq = yeq.xreplace({y: yreal}) eq = eq.xreplace({y: yreal}) y = yreal g_y_s = solveset_solver(yeq, symbol) f_y_sols = solveset_solver(eq, y) result = Union(*[imageset(Lambda(y, g_y), f_y_sols) for g_y in g_y_s]) if not isinstance(result, FiniteSet): solution_set = result else: f_set = [] # solutions for FiniteSet c_set = [] # solutions for ConditionSet for s in result: if checksol(f, symbol, s): f_set.append(s) else: c_set.append(s) solution_set = FiniteSet(*f_set) + ConditionSet(symbol, Eq(f, 0), FiniteSet(*c_set)) return solution_set def _solve_abs(f, symbol, domain): """ Helper function to solve equation involving absolute value function """ if not domain.is_subset(S.Reals): raise ValueError(filldedent(''' Absolute values cannot be inverted in the complex domain.''')) p, q, r = Wild('p'), Wild('q'), Wild('r') pattern_match = f.match(p*Abs(q) + r) or {} f_p, f_q, f_r = [pattern_match.get(i, S.Zero) for i in (p, q, r)] if not (f_p.is_zero or f_q.is_zero): domain = continuous_domain(f_q, symbol, domain) q_pos_cond = solve_univariate_inequality(f_q >= 0, symbol, relational=False, domain=domain, continuous=True) q_neg_cond = q_pos_cond.complement(domain) sols_q_pos = solveset_real(f_p*f_q + f_r, symbol).intersect(q_pos_cond) sols_q_neg = solveset_real(f_p*(-f_q) + f_r, symbol).intersect(q_neg_cond) return Union(sols_q_pos, sols_q_neg) else: return ConditionSet(symbol, Eq(f, 0), domain) def solve_decomposition(f, symbol, domain): """ Function to solve equations via the principle of "Decomposition and Rewriting". Examples ======== >>> from sympy import exp, sin, Symbol, pprint, S >>> from sympy.solvers.solveset import solve_decomposition as sd >>> x = Symbol('x') >>> f1 = exp(2*x) - 3*exp(x) + 2 >>> sd(f1, x, S.Reals) {0, log(2)} >>> f2 = sin(x)**2 + 2*sin(x) + 1 >>> pprint(sd(f2, x, S.Reals), use_unicode=False) 3*pi {2*n*pi + ---- | n in Integers} 2 >>> f3 = sin(x + 2) >>> pprint(sd(f3, x, S.Reals), use_unicode=False) {2*n*pi - 2 | n in Integers} U {2*n*pi - 2 + pi | n in Integers} """ from sympy.solvers.decompogen import decompogen from sympy.calculus.util import function_range # decompose the given function g_s = decompogen(f, symbol) # `y_s` represents the set of values for which the function `g` is to be # solved. # `solutions` represent the solutions of the equations `g = y_s` or # `g = 0` depending on the type of `y_s`. # As we are interested in solving the equation: f = 0 y_s = FiniteSet(0) for g in g_s: frange = function_range(g, symbol, domain) y_s = Intersection(frange, y_s) result = S.EmptySet if isinstance(y_s, FiniteSet): for y in y_s: solutions = solveset(Eq(g, y), symbol, domain) if not isinstance(solutions, ConditionSet): result += solutions else: if isinstance(y_s, ImageSet): iter_iset = (y_s,) elif isinstance(y_s, Union): iter_iset = y_s.args elif y_s is EmptySet: # y_s is not in the range of g in g_s, so no solution exists #in the given domain return EmptySet for iset in iter_iset: new_solutions = solveset(Eq(iset.lamda.expr, g), symbol, domain) dummy_var = tuple(iset.lamda.expr.free_symbols)[0] (base_set,) = iset.base_sets if isinstance(new_solutions, FiniteSet): new_exprs = new_solutions elif isinstance(new_solutions, Intersection): if isinstance(new_solutions.args[1], FiniteSet): new_exprs = new_solutions.args[1] for new_expr in new_exprs: result += ImageSet(Lambda(dummy_var, new_expr), base_set) if result is S.EmptySet: return ConditionSet(symbol, Eq(f, 0), domain) y_s = result return y_s def _solveset(f, symbol, domain, _check=False): """Helper for solveset to return a result from an expression that has already been sympify'ed and is known to contain the given symbol.""" # _check controls whether the answer is checked or not from sympy.simplify.simplify import signsimp from sympy.logic.boolalg import BooleanTrue if isinstance(f, BooleanTrue): return domain orig_f = f if f.is_Mul: coeff, f = f.as_independent(symbol, as_Add=False) if coeff in {S.ComplexInfinity, S.NegativeInfinity, S.Infinity}: f = together(orig_f) elif f.is_Add: a, h = f.as_independent(symbol) m, h = h.as_independent(symbol, as_Add=False) if m not in {S.ComplexInfinity, S.Zero, S.Infinity, S.NegativeInfinity}: f = a/m + h # XXX condition `m != 0` should be added to soln # assign the solvers to use solver = lambda f, x, domain=domain: _solveset(f, x, domain) inverter = lambda f, rhs, symbol: _invert(f, rhs, symbol, domain) result = EmptySet if f.expand().is_zero: return domain elif not f.has(symbol): return EmptySet elif f.is_Mul and all(_is_finite_with_finite_vars(m, domain) for m in f.args): # if f(x) and g(x) are both finite we can say that the solution of # f(x)*g(x) == 0 is same as Union(f(x) == 0, g(x) == 0) is not true in # general. g(x) can grow to infinitely large for the values where # f(x) == 0. To be sure that we are not silently allowing any # wrong solutions we are using this technique only if both f and g are # finite for a finite input. result = Union(*[solver(m, symbol) for m in f.args]) elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \ _is_function_class_equation(HyperbolicFunction, f, symbol): result = _solve_trig(f, symbol, domain) elif isinstance(f, arg): from sympy.functions.elementary.complexes import re, im a = f.args[0] result = Intersection(_solveset(re(a) > 0, symbol, domain), _solveset(im(a), symbol, domain)) elif f.is_Piecewise: expr_set_pairs = f.as_expr_set_pairs(domain) for (expr, in_set) in expr_set_pairs: if in_set.is_Relational: in_set = in_set.as_set() solns = solver(expr, symbol, in_set) result += solns elif isinstance(f, Eq): result = solver(Add(f.lhs, - f.rhs, evaluate=False), symbol, domain) elif f.is_Relational: try: result = solve_univariate_inequality( f, symbol, domain=domain, relational=False) except NotImplementedError: result = ConditionSet(symbol, f, domain) return result elif _is_modular(f, symbol): result = _solve_modular(f, symbol, domain) else: lhs, rhs_s = inverter(f, 0, symbol) if lhs == symbol: # do some very minimal simplification since # repeated inversion may have left the result # in a state that other solvers (e.g. poly) # would have simplified; this is done here # rather than in the inverter since here it # is only done once whereas there it would # be repeated for each step of the inversion if isinstance(rhs_s, FiniteSet): rhs_s = FiniteSet(*[Mul(* signsimp(i).as_content_primitive()) for i in rhs_s]) result = rhs_s elif isinstance(rhs_s, FiniteSet): for equation in [lhs - rhs for rhs in rhs_s]: if equation == f: u = unrad(f, symbol) if u: result += _solve_radical(equation, u, symbol, solver) elif equation.has(Abs): result += _solve_abs(f, symbol, domain) else: result_rational = _solve_as_rational(equation, symbol, domain) if not isinstance(result_rational, ConditionSet): result += result_rational else: # may be a transcendental type equation t_result = _transolve(equation, symbol, domain) if isinstance(t_result, ConditionSet): # might need factoring; this is expensive so we # have delayed until now. To avoid recursion # errors look for a non-trivial factoring into # a product of symbol dependent terms; I think # that something that factors as a Pow would # have already been recognized by now. factored = equation.factor() if factored.is_Mul and equation != factored: _, dep = factored.as_independent(symbol) if not dep.is_Add: # non-trivial factoring of equation # but use form with constants # in case they need special handling t_result = solver(factored, symbol) result += t_result else: result += solver(equation, symbol) elif rhs_s is not S.EmptySet: result = ConditionSet(symbol, Eq(f, 0), domain) if isinstance(result, ConditionSet): if isinstance(f, Expr): num, den = f.as_numer_denom() if den.has(symbol): _result = _solveset(num, symbol, domain) if not isinstance(_result, ConditionSet): singularities = _solveset(den, symbol, domain) result = _result - singularities if _check: if isinstance(result, ConditionSet): # it wasn't solved or has enumerated all conditions # -- leave it alone return result # whittle away all but the symbol-containing core # to use this for testing if isinstance(orig_f, Expr): fx = orig_f.as_independent(symbol, as_Add=True)[1] fx = fx.as_independent(symbol, as_Add=False)[1] else: fx = orig_f if isinstance(result, FiniteSet): # check the result for invalid solutions result = FiniteSet(*[s for s in result if isinstance(s, RootOf) or domain_check(fx, symbol, s)]) return result def _is_modular(f, symbol): """ Helper function to check below mentioned types of modular equations. ``A - Mod(B, C) = 0`` A -> This can or cannot be a function of symbol. B -> This is surely a function of symbol. C -> It is an integer. Parameters ========== f : Expr The equation to be checked. symbol : Symbol The concerned variable for which the equation is to be checked. Examples ======== >>> from sympy import symbols, exp, Mod >>> from sympy.solvers.solveset import _is_modular as check >>> x, y = symbols('x y') >>> check(Mod(x, 3) - 1, x) True >>> check(Mod(x, 3) - 1, y) False >>> check(Mod(x, 3)**2 - 5, x) False >>> check(Mod(x, 3)**2 - y, x) False >>> check(exp(Mod(x, 3)) - 1, x) False >>> check(Mod(3, y) - 1, y) False """ if not f.has(Mod): return False # extract modterms from f. modterms = list(f.atoms(Mod)) return (len(modterms) == 1 and # only one Mod should be present modterms[0].args[0].has(symbol) and # B-> function of symbol modterms[0].args[1].is_integer and # C-> to be an integer. any(isinstance(term, Mod) for term in list(_term_factors(f))) # free from other funcs ) def _invert_modular(modterm, rhs, n, symbol): """ Helper function to invert modular equation. ``Mod(a, m) - rhs = 0`` Generally it is inverted as (a, ImageSet(Lambda(n, m*n + rhs), S.Integers)). More simplified form will be returned if possible. If it is not invertible then (modterm, rhs) is returned. The following cases arise while inverting equation ``Mod(a, m) - rhs = 0``: 1. If a is symbol then m*n + rhs is the required solution. 2. If a is an instance of ``Add`` then we try to find two symbol independent parts of a and the symbol independent part gets tranferred to the other side and again the ``_invert_modular`` is called on the symbol dependent part. 3. If a is an instance of ``Mul`` then same as we done in ``Add`` we separate out the symbol dependent and symbol independent parts and transfer the symbol independent part to the rhs with the help of invert and again the ``_invert_modular`` is called on the symbol dependent part. 4. If a is an instance of ``Pow`` then two cases arise as following: - If a is of type (symbol_indep)**(symbol_dep) then the remainder is evaluated with the help of discrete_log function and then the least period is being found out with the help of totient function. period*n + remainder is the required solution in this case. For reference: (https://en.wikipedia.org/wiki/Euler's_theorem) - If a is of type (symbol_dep)**(symbol_indep) then we try to find all primitive solutions list with the help of nthroot_mod function. m*n + rem is the general solution where rem belongs to solutions list from nthroot_mod function. Parameters ========== modterm, rhs : Expr The modular equation to be inverted, ``modterm - rhs = 0`` symbol : Symbol The variable in the equation to be inverted. n : Dummy Dummy variable for output g_n. Returns ======= A tuple (f_x, g_n) is being returned where f_x is modular independent function of symbol and g_n being set of values f_x can have. Examples ======== >>> from sympy import symbols, exp, Mod, Dummy, S >>> from sympy.solvers.solveset import _invert_modular as invert_modular >>> x, y = symbols('x y') >>> n = Dummy('n') >>> invert_modular(Mod(exp(x), 7), S(5), n, x) (Mod(exp(x), 7), 5) >>> invert_modular(Mod(x, 7), S(5), n, x) (x, ImageSet(Lambda(_n, 7*_n + 5), Integers)) >>> invert_modular(Mod(3*x + 8, 7), S(5), n, x) (x, ImageSet(Lambda(_n, 7*_n + 6), Integers)) >>> invert_modular(Mod(x**4, 7), S(5), n, x) (x, EmptySet) >>> invert_modular(Mod(2**(x**2 + x + 1), 7), S(2), n, x) (x**2 + x + 1, ImageSet(Lambda(_n, 3*_n + 1), Naturals0)) """ a, m = modterm.args if rhs.is_real is False or any(term.is_real is False for term in list(_term_factors(a))): # Check for complex arguments return modterm, rhs if abs(rhs) >= abs(m): # if rhs has value greater than value of m. return symbol, EmptySet if a == symbol: return symbol, ImageSet(Lambda(n, m*n + rhs), S.Integers) if a.is_Add: # g + h = a g, h = a.as_independent(symbol) if g is not S.Zero: x_indep_term = rhs - Mod(g, m) return _invert_modular(Mod(h, m), Mod(x_indep_term, m), n, symbol) if a.is_Mul: # g*h = a g, h = a.as_independent(symbol) if g is not S.One: x_indep_term = rhs*invert(g, m) return _invert_modular(Mod(h, m), Mod(x_indep_term, m), n, symbol) if a.is_Pow: # base**expo = a base, expo = a.args if expo.has(symbol) and not base.has(symbol): # remainder -> solution independent of n of equation. # m, rhs are made coprime by dividing igcd(m, rhs) try: remainder = discrete_log(m / igcd(m, rhs), rhs, a.base) except ValueError: # log does not exist return modterm, rhs # period -> coefficient of n in the solution and also referred as # the least period of expo in which it is repeats itself. # (a**(totient(m)) - 1) divides m. Here is link of theorem: # (https://en.wikipedia.org/wiki/Euler's_theorem) period = totient(m) for p in divisors(period): # there might a lesser period exist than totient(m). if pow(a.base, p, m / igcd(m, a.base)) == 1: period = p break # recursion is not applied here since _invert_modular is currently # not smart enough to handle infinite rhs as here expo has infinite # rhs = ImageSet(Lambda(n, period*n + remainder), S.Naturals0). return expo, ImageSet(Lambda(n, period*n + remainder), S.Naturals0) elif base.has(symbol) and not expo.has(symbol): try: remainder_list = nthroot_mod(rhs, expo, m, all_roots=True) if remainder_list == []: return symbol, EmptySet except (ValueError, NotImplementedError): return modterm, rhs g_n = EmptySet for rem in remainder_list: g_n += ImageSet(Lambda(n, m*n + rem), S.Integers) return base, g_n return modterm, rhs def _solve_modular(f, symbol, domain): r""" Helper function for solving modular equations of type ``A - Mod(B, C) = 0``, where A can or cannot be a function of symbol, B is surely a function of symbol and C is an integer. Currently ``_solve_modular`` is only able to solve cases where A is not a function of symbol. Parameters ========== f : Expr The modular equation to be solved, ``f = 0`` symbol : Symbol The variable in the equation to be solved. domain : Set A set over which the equation is solved. It has to be a subset of Integers. Returns ======= A set of integer solutions satisfying the given modular equation. A ``ConditionSet`` if the equation is unsolvable. Examples ======== >>> from sympy.solvers.solveset import _solve_modular as solve_modulo >>> from sympy import S, Symbol, sin, Intersection, Interval >>> from sympy.core.mod import Mod >>> x = Symbol('x') >>> solve_modulo(Mod(5*x - 8, 7) - 3, x, S.Integers) ImageSet(Lambda(_n, 7*_n + 5), Integers) >>> solve_modulo(Mod(5*x - 8, 7) - 3, x, S.Reals) # domain should be subset of integers. ConditionSet(x, Eq(Mod(5*x + 6, 7) - 3, 0), Reals) >>> solve_modulo(-7 + Mod(x, 5), x, S.Integers) EmptySet >>> solve_modulo(Mod(12**x, 21) - 18, x, S.Integers) ImageSet(Lambda(_n, 6*_n + 2), Naturals0) >>> solve_modulo(Mod(sin(x), 7) - 3, x, S.Integers) # not solvable ConditionSet(x, Eq(Mod(sin(x), 7) - 3, 0), Integers) >>> solve_modulo(3 - Mod(x, 5), x, Intersection(S.Integers, Interval(0, 100))) Intersection(ImageSet(Lambda(_n, 5*_n + 3), Integers), Range(0, 101, 1)) """ # extract modterm and g_y from f unsolved_result = ConditionSet(symbol, Eq(f, 0), domain) modterm = list(f.atoms(Mod))[0] rhs = -S.One*(f.subs(modterm, S.Zero)) if f.as_coefficients_dict()[modterm].is_negative: # checks if coefficient of modterm is negative in main equation. rhs *= -S.One if not domain.is_subset(S.Integers): return unsolved_result if rhs.has(symbol): # TODO Case: A-> function of symbol, can be extended here # in future. return unsolved_result n = Dummy('n', integer=True) f_x, g_n = _invert_modular(modterm, rhs, n, symbol) if f_x == modterm and g_n == rhs: return unsolved_result if f_x == symbol: if domain is not S.Integers: return domain.intersect(g_n) return g_n if isinstance(g_n, ImageSet): lamda_expr = g_n.lamda.expr lamda_vars = g_n.lamda.variables base_sets = g_n.base_sets sol_set = _solveset(f_x - lamda_expr, symbol, S.Integers) if isinstance(sol_set, FiniteSet): tmp_sol = EmptySet for sol in sol_set: tmp_sol += ImageSet(Lambda(lamda_vars, sol), *base_sets) sol_set = tmp_sol else: sol_set = ImageSet(Lambda(lamda_vars, sol_set), *base_sets) return domain.intersect(sol_set) return unsolved_result def _term_factors(f): """ Iterator to get the factors of all terms present in the given equation. Parameters ========== f : Expr Equation that needs to be addressed Returns ======= Factors of all terms present in the equation. Examples ======== >>> from sympy import symbols >>> from sympy.solvers.solveset import _term_factors >>> x = symbols('x') >>> list(_term_factors(-2 - x**2 + x*(x + 1))) [-2, -1, x**2, x, x + 1] """ for add_arg in Add.make_args(f): yield from Mul.make_args(add_arg) def _solve_exponential(lhs, rhs, symbol, domain): r""" Helper function for solving (supported) exponential equations. Exponential equations are the sum of (currently) at most two terms with one or both of them having a power with a symbol-dependent exponent. For example .. math:: 5^{2x + 3} - 5^{3x - 1} .. math:: 4^{5 - 9x} - e^{2 - x} Parameters ========== lhs, rhs : Expr The exponential equation to be solved, `lhs = rhs` symbol : Symbol The variable in which the equation is solved domain : Set A set over which the equation is solved. Returns ======= A set of solutions satisfying the given equation. A ``ConditionSet`` if the equation is unsolvable or if the assumptions are not properly defined, in that case a different style of ``ConditionSet`` is returned having the solution(s) of the equation with the desired assumptions. Examples ======== >>> from sympy.solvers.solveset import _solve_exponential as solve_expo >>> from sympy import symbols, S >>> x = symbols('x', real=True) >>> a, b = symbols('a b') >>> solve_expo(2**x + 3**x - 5**x, 0, x, S.Reals) # not solvable ConditionSet(x, Eq(2**x + 3**x - 5**x, 0), Reals) >>> solve_expo(a**x - b**x, 0, x, S.Reals) # solvable but incorrect assumptions ConditionSet(x, (a > 0) & (b > 0), {0}) >>> solve_expo(3**(2*x) - 2**(x + 3), 0, x, S.Reals) {-3*log(2)/(-2*log(3) + log(2))} >>> solve_expo(2**x - 4**x, 0, x, S.Reals) {0} * Proof of correctness of the method The logarithm function is the inverse of the exponential function. The defining relation between exponentiation and logarithm is: .. math:: {\log_b x} = y \enspace if \enspace b^y = x Therefore if we are given an equation with exponent terms, we can convert every term to its corresponding logarithmic form. This is achieved by taking logarithms and expanding the equation using logarithmic identities so that it can easily be handled by ``solveset``. For example: .. math:: 3^{2x} = 2^{x + 3} Taking log both sides will reduce the equation to .. math:: (2x)\log(3) = (x + 3)\log(2) This form can be easily handed by ``solveset``. """ unsolved_result = ConditionSet(symbol, Eq(lhs - rhs, 0), domain) newlhs = powdenest(lhs) if lhs != newlhs: # it may also be advantageous to factor the new expr neweq = factor(newlhs - rhs) if neweq != (lhs - rhs): return _solveset(neweq, symbol, domain) # try again with _solveset if not (isinstance(lhs, Add) and len(lhs.args) == 2): # solving for the sum of more than two powers is possible # but not yet implemented return unsolved_result if rhs != 0: return unsolved_result a, b = list(ordered(lhs.args)) a_term = a.as_independent(symbol)[1] b_term = b.as_independent(symbol)[1] a_base, a_exp = a_term.as_base_exp() b_base, b_exp = b_term.as_base_exp() from sympy.functions.elementary.complexes import im if domain.is_subset(S.Reals): conditions = And( a_base > 0, b_base > 0, Eq(im(a_exp), 0), Eq(im(b_exp), 0)) else: conditions = And( Ne(a_base, 0), Ne(b_base, 0)) L, R = map(lambda i: expand_log(log(i), force=True), (a, -b)) solutions = _solveset(L - R, symbol, domain) return ConditionSet(symbol, conditions, solutions) def _is_exponential(f, symbol): r""" Return ``True`` if one or more terms contain ``symbol`` only in exponents, else ``False``. Parameters ========== f : Expr The equation to be checked symbol : Symbol The variable in which the equation is checked Examples ======== >>> from sympy import symbols, cos, exp >>> from sympy.solvers.solveset import _is_exponential as check >>> x, y = symbols('x y') >>> check(y, y) False >>> check(x**y - 1, y) True >>> check(x**y*2**y - 1, y) True >>> check(exp(x + 3) + 3**x, x) True >>> check(cos(2**x), x) False * Philosophy behind the helper The function extracts each term of the equation and checks if it is of exponential form w.r.t ``symbol``. """ rv = False for expr_arg in _term_factors(f): if symbol not in expr_arg.free_symbols: continue if (isinstance(expr_arg, Pow) and symbol not in expr_arg.base.free_symbols or isinstance(expr_arg, exp)): rv = True # symbol in exponent else: return False # dependent on symbol in non-exponential way return rv def _solve_logarithm(lhs, rhs, symbol, domain): r""" Helper to solve logarithmic equations which are reducible to a single instance of `\log`. Logarithmic equations are (currently) the equations that contains `\log` terms which can be reduced to a single `\log` term or a constant using various logarithmic identities. For example: .. math:: \log(x) + \log(x - 4) can be reduced to: .. math:: \log(x(x - 4)) Parameters ========== lhs, rhs : Expr The logarithmic equation to be solved, `lhs = rhs` symbol : Symbol The variable in which the equation is solved domain : Set A set over which the equation is solved. Returns ======= A set of solutions satisfying the given equation. A ``ConditionSet`` if the equation is unsolvable. Examples ======== >>> from sympy import symbols, log, S >>> from sympy.solvers.solveset import _solve_logarithm as solve_log >>> x = symbols('x') >>> f = log(x - 3) + log(x + 3) >>> solve_log(f, 0, x, S.Reals) {-sqrt(10), sqrt(10)} * Proof of correctness A logarithm is another way to write exponent and is defined by .. math:: {\log_b x} = y \enspace if \enspace b^y = x When one side of the equation contains a single logarithm, the equation can be solved by rewriting the equation as an equivalent exponential equation as defined above. But if one side contains more than one logarithm, we need to use the properties of logarithm to condense it into a single logarithm. Take for example .. math:: \log(2x) - 15 = 0 contains single logarithm, therefore we can directly rewrite it to exponential form as .. math:: x = \frac{e^{15}}{2} But if the equation has more than one logarithm as .. math:: \log(x - 3) + \log(x + 3) = 0 we use logarithmic identities to convert it into a reduced form Using, .. math:: \log(a) + \log(b) = \log(ab) the equation becomes, .. math:: \log((x - 3)(x + 3)) This equation contains one logarithm and can be solved by rewriting to exponents. """ new_lhs = logcombine(lhs, force=True) new_f = new_lhs - rhs return _solveset(new_f, symbol, domain) def _is_logarithmic(f, symbol): r""" Return ``True`` if the equation is in the form `a\log(f(x)) + b\log(g(x)) + ... + c` else ``False``. Parameters ========== f : Expr The equation to be checked symbol : Symbol The variable in which the equation is checked Returns ======= ``True`` if the equation is logarithmic otherwise ``False``. Examples ======== >>> from sympy import symbols, tan, log >>> from sympy.solvers.solveset import _is_logarithmic as check >>> x, y = symbols('x y') >>> check(log(x + 2) - log(x + 3), x) True >>> check(tan(log(2*x)), x) False >>> check(x*log(x), x) False >>> check(x + log(x), x) False >>> check(y + log(x), x) True * Philosophy behind the helper The function extracts each term and checks whether it is logarithmic w.r.t ``symbol``. """ rv = False for term in Add.make_args(f): saw_log = False for term_arg in Mul.make_args(term): if symbol not in term_arg.free_symbols: continue if isinstance(term_arg, log): if saw_log: return False # more than one log in term saw_log = True else: return False # dependent on symbol in non-log way if saw_log: rv = True return rv def _is_lambert(f, symbol): r""" If this returns ``False`` then the Lambert solver (``_solve_lambert``) will not be called. Explanation =========== Quick check for cases that the Lambert solver might be able to handle. 1. Equations containing more than two operands and `symbol`s involving any of `Pow`, `exp`, `HyperbolicFunction`,`TrigonometricFunction`, `log` terms. 2. In `Pow`, `exp` the exponent should have `symbol` whereas for `HyperbolicFunction`,`TrigonometricFunction`, `log` should contain `symbol`. 3. For `HyperbolicFunction`,`TrigonometricFunction` the number of trigonometric functions in equation should be less than number of symbols. (since `A*cos(x) + B*sin(x) - c` is not the Lambert type). Some forms of lambert equations are: 1. X**X = C 2. X*(B*log(X) + D)**A = C 3. A*log(B*X + A) + d*X = C 4. (B*X + A)*exp(d*X + g) = C 5. g*exp(B*X + h) - B*X = C 6. A*D**(E*X + g) - B*X = C 7. A*cos(X) + B*sin(X) - D*X = C 8. A*cosh(X) + B*sinh(X) - D*X = C Where X is any variable, A, B, C, D, E are any constants, g, h are linear functions or log terms. Parameters ========== f : Expr The equation to be checked symbol : Symbol The variable in which the equation is checked Returns ======= If this returns ``False`` then the Lambert solver (``_solve_lambert``) will not be called. Examples ======== >>> from sympy.solvers.solveset import _is_lambert >>> from sympy import symbols, cosh, sinh, log >>> x = symbols('x') >>> _is_lambert(3*log(x) - x*log(3), x) True >>> _is_lambert(log(log(x - 3)) + log(x-3), x) True >>> _is_lambert(cosh(x) - sinh(x), x) False >>> _is_lambert((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1), x) True See Also ======== _solve_lambert """ term_factors = list(_term_factors(f.expand())) # total number of symbols in equation no_of_symbols = len([arg for arg in term_factors if arg.has(symbol)]) # total number of trigonometric terms in equation no_of_trig = len([arg for arg in term_factors \ if arg.has(HyperbolicFunction, TrigonometricFunction)]) if f.is_Add and no_of_symbols >= 2: # `log`, `HyperbolicFunction`, `TrigonometricFunction` should have symbols # and no_of_trig < no_of_symbols lambert_funcs = (log, HyperbolicFunction, TrigonometricFunction) if any(isinstance(arg, lambert_funcs)\ for arg in term_factors if arg.has(symbol)): if no_of_trig < no_of_symbols: return True # here, `Pow`, `exp` exponent should have symbols elif any(isinstance(arg, (Pow, exp)) \ for arg in term_factors if (arg.as_base_exp()[1]).has(symbol)): return True return False def _transolve(f, symbol, domain): r""" Function to solve transcendental equations. It is a helper to ``solveset`` and should be used internally. ``_transolve`` currently supports the following class of equations: - Exponential equations - Logarithmic equations Parameters ========== f : Any transcendental equation that needs to be solved. This needs to be an expression, which is assumed to be equal to ``0``. symbol : The variable for which the equation is solved. This needs to be of class ``Symbol``. domain : A set over which the equation is solved. This needs to be of class ``Set``. Returns ======= Set A set of values for ``symbol`` for which ``f`` is equal to zero. An ``EmptySet`` is returned if ``f`` does not have solutions in respective domain. A ``ConditionSet`` is returned as unsolved object if algorithms to evaluate complete solution are not yet implemented. How to use ``_transolve`` ========================= ``_transolve`` should not be used as an independent function, because it assumes that the equation (``f``) and the ``symbol`` comes from ``solveset`` and might have undergone a few modification(s). To use ``_transolve`` as an independent function the equation (``f``) and the ``symbol`` should be passed as they would have been by ``solveset``. Examples ======== >>> from sympy.solvers.solveset import _transolve as transolve >>> from sympy.solvers.solvers import _tsolve as tsolve >>> from sympy import symbols, S, pprint >>> x = symbols('x', real=True) # assumption added >>> transolve(5**(x - 3) - 3**(2*x + 1), x, S.Reals) {-(log(3) + 3*log(5))/(-log(5) + 2*log(3))} How ``_transolve`` works ======================== ``_transolve`` uses two types of helper functions to solve equations of a particular class: Identifying helpers: To determine whether a given equation belongs to a certain class of equation or not. Returns either ``True`` or ``False``. Solving helpers: Once an equation is identified, a corresponding helper either solves the equation or returns a form of the equation that ``solveset`` might better be able to handle. * Philosophy behind the module The purpose of ``_transolve`` is to take equations which are not already polynomial in their generator(s) and to either recast them as such through a valid transformation or to solve them outright. A pair of helper functions for each class of supported transcendental functions are employed for this purpose. One identifies the transcendental form of an equation and the other either solves it or recasts it into a tractable form that can be solved by ``solveset``. For example, an equation in the form `ab^{f(x)} - cd^{g(x)} = 0` can be transformed to `\log(a) + f(x)\log(b) - \log(c) - g(x)\log(d) = 0` (under certain assumptions) and this can be solved with ``solveset`` if `f(x)` and `g(x)` are in polynomial form. How ``_transolve`` is better than ``_tsolve`` ============================================= 1) Better output ``_transolve`` provides expressions in a more simplified form. Consider a simple exponential equation >>> f = 3**(2*x) - 2**(x + 3) >>> pprint(transolve(f, x, S.Reals), use_unicode=False) -3*log(2) {------------------} -2*log(3) + log(2) >>> pprint(tsolve(f, x), use_unicode=False) / 3 \ | --------| | log(2/9)| [-log\2 /] 2) Extensible The API of ``_transolve`` is designed such that it is easily extensible, i.e. the code that solves a given class of equations is encapsulated in a helper and not mixed in with the code of ``_transolve`` itself. 3) Modular ``_transolve`` is designed to be modular i.e, for every class of equation a separate helper for identification and solving is implemented. This makes it easy to change or modify any of the method implemented directly in the helpers without interfering with the actual structure of the API. 4) Faster Computation Solving equation via ``_transolve`` is much faster as compared to ``_tsolve``. In ``solve``, attempts are made computing every possibility to get the solutions. This series of attempts makes solving a bit slow. In ``_transolve``, computation begins only after a particular type of equation is identified. How to add new class of equations ================================= Adding a new class of equation solver is a three-step procedure: - Identify the type of the equations Determine the type of the class of equations to which they belong: it could be of ``Add``, ``Pow``, etc. types. Separate internal functions are used for each type. Write identification and solving helpers and use them from within the routine for the given type of equation (after adding it, if necessary). Something like: .. code-block:: python def add_type(lhs, rhs, x): .... if _is_exponential(lhs, x): new_eq = _solve_exponential(lhs, rhs, x) .... rhs, lhs = eq.as_independent(x) if lhs.is_Add: result = add_type(lhs, rhs, x) - Define the identification helper. - Define the solving helper. Apart from this, a few other things needs to be taken care while adding an equation solver: - Naming conventions: Name of the identification helper should be as ``_is_class`` where class will be the name or abbreviation of the class of equation. The solving helper will be named as ``_solve_class``. For example: for exponential equations it becomes ``_is_exponential`` and ``_solve_expo``. - The identifying helpers should take two input parameters, the equation to be checked and the variable for which a solution is being sought, while solving helpers would require an additional domain parameter. - Be sure to consider corner cases. - Add tests for each helper. - Add a docstring to your helper that describes the method implemented. The documentation of the helpers should identify: - the purpose of the helper, - the method used to identify and solve the equation, - a proof of correctness - the return values of the helpers """ def add_type(lhs, rhs, symbol, domain): """ Helper for ``_transolve`` to handle equations of ``Add`` type, i.e. equations taking the form as ``a*f(x) + b*g(x) + .... = c``. For example: 4**x + 8**x = 0 """ result = ConditionSet(symbol, Eq(lhs - rhs, 0), domain) # check if it is exponential type equation if _is_exponential(lhs, symbol): result = _solve_exponential(lhs, rhs, symbol, domain) # check if it is logarithmic type equation elif _is_logarithmic(lhs, symbol): result = _solve_logarithm(lhs, rhs, symbol, domain) return result result = ConditionSet(symbol, Eq(f, 0), domain) # invert_complex handles the call to the desired inverter based # on the domain specified. lhs, rhs_s = invert_complex(f, 0, symbol, domain) if isinstance(rhs_s, FiniteSet): assert (len(rhs_s.args)) == 1 rhs = rhs_s.args[0] if lhs.is_Add: result = add_type(lhs, rhs, symbol, domain) else: result = rhs_s return result def solveset(f, symbol=None, domain=S.Complexes): r"""Solves a given inequality or equation with set as output Parameters ========== f : Expr or a relational. The target equation or inequality symbol : Symbol The variable for which the equation is solved domain : Set The domain over which the equation is solved Returns ======= Set A set of values for `symbol` for which `f` is True or is equal to zero. An `EmptySet` is returned if `f` is False or nonzero. A `ConditionSet` is returned as unsolved object if algorithms to evaluate complete solution are not yet implemented. `solveset` claims to be complete in the solution set that it returns. Raises ====== NotImplementedError The algorithms to solve inequalities in complex domain are not yet implemented. ValueError The input is not valid. RuntimeError It is a bug, please report to the github issue tracker. Notes ===== Python interprets 0 and 1 as False and True, respectively, but in this function they refer to solutions of an expression. So 0 and 1 return the Domain and EmptySet, respectively, while True and False return the opposite (as they are assumed to be solutions of relational expressions). See Also ======== solveset_real: solver for real domain solveset_complex: solver for complex domain Examples ======== >>> from sympy import exp, sin, Symbol, pprint, S, Eq >>> from sympy.solvers.solveset import solveset, solveset_real * The default domain is complex. Not specifying a domain will lead to the solving of the equation in the complex domain (and this is not affected by the assumptions on the symbol): >>> x = Symbol('x') >>> pprint(solveset(exp(x) - 1, x), use_unicode=False) {2*n*I*pi | n in Integers} >>> x = Symbol('x', real=True) >>> pprint(solveset(exp(x) - 1, x), use_unicode=False) {2*n*I*pi | n in Integers} * If you want to use `solveset` to solve the equation in the real domain, provide a real domain. (Using ``solveset_real`` does this automatically.) >>> R = S.Reals >>> x = Symbol('x') >>> solveset(exp(x) - 1, x, R) {0} >>> solveset_real(exp(x) - 1, x) {0} The solution is unaffected by assumptions on the symbol: >>> p = Symbol('p', positive=True) >>> pprint(solveset(p**2 - 4)) {-2, 2} When a conditionSet is returned, symbols with assumptions that would alter the set are replaced with more generic symbols: >>> i = Symbol('i', imaginary=True) >>> solveset(Eq(i**2 + i*sin(i), 1), i, domain=S.Reals) ConditionSet(_R, Eq(_R**2 + _R*sin(_R) - 1, 0), Reals) * Inequalities can be solved over the real domain only. Use of a complex domain leads to a NotImplementedError. >>> solveset(exp(x) > 1, x, R) Interval.open(0, oo) """ f = sympify(f) symbol = sympify(symbol) if f is S.true: return domain if f is S.false: return S.EmptySet if not isinstance(f, (Expr, Relational, Number)): raise ValueError("%s is not a valid SymPy expression" % f) if not isinstance(symbol, (Expr, Relational)) and symbol is not None: raise ValueError("%s is not a valid SymPy symbol" % (symbol,)) if not isinstance(domain, Set): raise ValueError("%s is not a valid domain" %(domain)) free_symbols = f.free_symbols if f.has(Piecewise): f = piecewise_fold(f) if symbol is None and not free_symbols: b = Eq(f, 0) if b is S.true: return domain elif b is S.false: return S.EmptySet else: raise NotImplementedError(filldedent(''' relationship between value and 0 is unknown: %s''' % b)) if symbol is None: if len(free_symbols) == 1: symbol = free_symbols.pop() elif free_symbols: raise ValueError(filldedent(''' The independent variable must be specified for a multivariate equation.''')) elif not isinstance(symbol, Symbol): f, s, swap = recast_to_symbols([f], [symbol]) # the xreplace will be needed if a ConditionSet is returned return solveset(f[0], s[0], domain).xreplace(swap) # solveset should ignore assumptions on symbols if symbol not in _rc: x = _rc[0] if domain.is_subset(S.Reals) else _rc[1] rv = solveset(f.xreplace({symbol: x}), x, domain) # try to use the original symbol if possible try: _rv = rv.xreplace({x: symbol}) except TypeError: _rv = rv if rv.dummy_eq(_rv): rv = _rv return rv # Abs has its own handling method which avoids the # rewriting property that the first piece of abs(x) # is for x >= 0 and the 2nd piece for x < 0 -- solutions # can look better if the 2nd condition is x <= 0. Since # the solution is a set, duplication of results is not # an issue, e.g. {y, -y} when y is 0 will be {0} f, mask = _masked(f, Abs) f = f.rewrite(Piecewise) # everything that's not an Abs for d, e in mask: # everything *in* an Abs e = e.func(e.args[0].rewrite(Piecewise)) f = f.xreplace({d: e}) f = piecewise_fold(f) return _solveset(f, symbol, domain, _check=True) def solveset_real(f, symbol): return solveset(f, symbol, S.Reals) def solveset_complex(f, symbol): return solveset(f, symbol, S.Complexes) def _solveset_multi(eqs, syms, domains): '''Basic implementation of a multivariate solveset. For internal use (not ready for public consumption)''' rep = {} for sym, dom in zip(syms, domains): if dom is S.Reals: rep[sym] = Symbol(sym.name, real=True) eqs = [eq.subs(rep) for eq in eqs] syms = [sym.subs(rep) for sym in syms] syms = tuple(syms) if len(eqs) == 0: return ProductSet(*domains) if len(syms) == 1: sym = syms[0] domain = domains[0] solsets = [solveset(eq, sym, domain) for eq in eqs] solset = Intersection(*solsets) return ImageSet(Lambda((sym,), (sym,)), solset).doit() eqs = sorted(eqs, key=lambda eq: len(eq.free_symbols & set(syms))) for n in range(len(eqs)): sols = [] all_handled = True for sym in syms: if sym not in eqs[n].free_symbols: continue sol = solveset(eqs[n], sym, domains[syms.index(sym)]) if isinstance(sol, FiniteSet): i = syms.index(sym) symsp = syms[:i] + syms[i+1:] domainsp = domains[:i] + domains[i+1:] eqsp = eqs[:n] + eqs[n+1:] for s in sol: eqsp_sub = [eq.subs(sym, s) for eq in eqsp] sol_others = _solveset_multi(eqsp_sub, symsp, domainsp) fun = Lambda((symsp,), symsp[:i] + (s,) + symsp[i:]) sols.append(ImageSet(fun, sol_others).doit()) else: all_handled = False if all_handled: return Union(*sols) def solvify(f, symbol, domain): """Solves an equation using solveset and returns the solution in accordance with the `solve` output API. Returns ======= We classify the output based on the type of solution returned by `solveset`. Solution | Output ---------------------------------------- FiniteSet | list ImageSet, | list (if `f` is periodic) Union | Union | list (with FiniteSet) EmptySet | empty list Others | None Raises ====== NotImplementedError A ConditionSet is the input. Examples ======== >>> from sympy.solvers.solveset import solvify >>> from sympy.abc import x >>> from sympy import S, tan, sin, exp >>> solvify(x**2 - 9, x, S.Reals) [-3, 3] >>> solvify(sin(x) - 1, x, S.Reals) [pi/2] >>> solvify(tan(x), x, S.Reals) [0] >>> solvify(exp(x) - 1, x, S.Complexes) >>> solvify(exp(x) - 1, x, S.Reals) [0] """ solution_set = solveset(f, symbol, domain) result = None if solution_set is S.EmptySet: result = [] elif isinstance(solution_set, ConditionSet): raise NotImplementedError('solveset is unable to solve this equation.') elif isinstance(solution_set, FiniteSet): result = list(solution_set) else: period = periodicity(f, symbol) if period is not None: solutions = S.EmptySet iter_solutions = () if isinstance(solution_set, ImageSet): iter_solutions = (solution_set,) elif isinstance(solution_set, Union): if all(isinstance(i, ImageSet) for i in solution_set.args): iter_solutions = solution_set.args for solution in iter_solutions: solutions += solution.intersect(Interval(0, period, False, True)) if isinstance(solutions, FiniteSet): result = list(solutions) else: solution = solution_set.intersect(domain) if isinstance(solution, Union): # concerned about only FiniteSet with Union but not about ImageSet # if required could be extend if any(isinstance(i, FiniteSet) for i in solution.args): result = [sol for soln in solution.args \ for sol in soln.args if isinstance(soln,FiniteSet)] else: return None elif isinstance(solution, FiniteSet): result += solution return result ############################################################################### ################################ LINSOLVE ##################################### ############################################################################### def linear_coeffs(eq, *syms, **_kw): """Return a list whose elements are the coefficients of the corresponding symbols in the sum of terms in ``eq``. The additive constant is returned as the last element of the list. Raises ====== NonlinearError The equation contains a nonlinear term Examples ======== >>> from sympy.solvers.solveset import linear_coeffs >>> from sympy.abc import x, y, z >>> linear_coeffs(3*x + 2*y - 1, x, y) [3, 2, -1] It is not necessary to expand the expression: >>> linear_coeffs(x + y*(z*(x*3 + 2) + 3), x) [3*y*z + 1, y*(2*z + 3)] But if there are nonlinear or cross terms -- even if they would cancel after simplification -- an error is raised so the situation does not pass silently past the caller's attention: >>> eq = 1/x*(x - 1) + 1/x >>> linear_coeffs(eq.expand(), x) [0, 1] >>> linear_coeffs(eq, x) Traceback (most recent call last): ... NonlinearError: nonlinear term encountered: 1/x >>> linear_coeffs(x*(y + 1) - x*y, x, y) Traceback (most recent call last): ... NonlinearError: nonlinear term encountered: x*(y + 1) """ d = defaultdict(list) eq = _sympify(eq) symset = set(syms) has = eq.free_symbols & symset if not has: return [S.Zero]*len(syms) + [eq] c, terms = eq.as_coeff_add(*has) d[0].extend(Add.make_args(c)) for t in terms: m, f = t.as_coeff_mul(*has) if len(f) != 1: break f = f[0] if f in symset: d[f].append(m) elif f.is_Add: d1 = linear_coeffs(f, *has, **{'dict': True}) d[0].append(m*d1.pop(0)) for xf, vf in d1.items(): d[xf].append(m*vf) else: break else: for k, v in d.items(): d[k] = Add(*v) if not _kw: return [d.get(s, S.Zero) for s in syms] + [d[0]] return d # default is still list but this won't matter raise NonlinearError('nonlinear term encountered: %s' % t) def linear_eq_to_matrix(equations, *symbols): r""" Converts a given System of Equations into Matrix form. Here `equations` must be a linear system of equations in `symbols`. Element M[i, j] corresponds to the coefficient of the jth symbol in the ith equation. The Matrix form corresponds to the augmented matrix form. For example: .. math:: 4x + 2y + 3z = 1 .. math:: 3x + y + z = -6 .. math:: 2x + 4y + 9z = 2 This system would return `A` & `b` as given below: :: [ 4 2 3 ] [ 1 ] A = [ 3 1 1 ] b = [-6 ] [ 2 4 9 ] [ 2 ] The only simplification performed is to convert `Eq(a, b) -> a - b`. Raises ====== NonlinearError The equations contain a nonlinear term. ValueError The symbols are not given or are not unique. Examples ======== >>> from sympy import linear_eq_to_matrix, symbols >>> c, x, y, z = symbols('c, x, y, z') The coefficients (numerical or symbolic) of the symbols will be returned as matrices: >>> eqns = [c*x + z - 1 - c, y + z, x - y] >>> A, b = linear_eq_to_matrix(eqns, [x, y, z]) >>> A Matrix([ [c, 0, 1], [0, 1, 1], [1, -1, 0]]) >>> b Matrix([ [c + 1], [ 0], [ 0]]) This routine does not simplify expressions and will raise an error if nonlinearity is encountered: >>> eqns = [ ... (x**2 - 3*x)/(x - 3) - 3, ... y**2 - 3*y - y*(y - 4) + x - 4] >>> linear_eq_to_matrix(eqns, [x, y]) Traceback (most recent call last): ... NonlinearError: The term (x**2 - 3*x)/(x - 3) is nonlinear in {x, y} Simplifying these equations will discard the removable singularity in the first, reveal the linear structure of the second: >>> [e.simplify() for e in eqns] [x - 3, x + y - 4] Any such simplification needed to eliminate nonlinear terms must be done before calling this routine. """ if not symbols: raise ValueError(filldedent(''' Symbols must be given, for which coefficients are to be found. ''')) if hasattr(symbols[0], '__iter__'): symbols = symbols[0] for i in symbols: if not isinstance(i, Symbol): raise ValueError(filldedent(''' Expecting a Symbol but got %s ''' % i)) if has_dups(symbols): raise ValueError('Symbols must be unique') equations = sympify(equations) if isinstance(equations, MatrixBase): equations = list(equations) elif isinstance(equations, (Expr, Eq)): equations = [equations] elif not is_sequence(equations): raise ValueError(filldedent(''' Equation(s) must be given as a sequence, Expr, Eq or Matrix. ''')) A, b = [], [] for i, f in enumerate(equations): if isinstance(f, Equality): f = f.rewrite(Add, evaluate=False) coeff_list = linear_coeffs(f, *symbols) b.append(-coeff_list.pop()) A.append(coeff_list) A, b = map(Matrix, (A, b)) return A, b def linsolve(system, *symbols): r""" Solve system of N linear equations with M variables; both underdetermined and overdetermined systems are supported. The possible number of solutions is zero, one or infinite. Zero solutions throws a ValueError, whereas infinite solutions are represented parametrically in terms of the given symbols. For unique solution a FiniteSet of ordered tuples is returned. All Standard input formats are supported: For the given set of Equations, the respective input types are given below: .. math:: 3x + 2y - z = 1 .. math:: 2x - 2y + 4z = -2 .. math:: 2x - y + 2z = 0 * Augmented Matrix Form, `system` given below: :: [3 2 -1 1] system = [2 -2 4 -2] [2 -1 2 0] * List Of Equations Form `system = [3x + 2y - z - 1, 2x - 2y + 4z + 2, 2x - y + 2z]` * Input A & b Matrix Form (from Ax = b) are given as below: :: [3 2 -1 ] [ 1 ] A = [2 -2 4 ] b = [ -2 ] [2 -1 2 ] [ 0 ] `system = (A, b)` Symbols can always be passed but are actually only needed when 1) a system of equations is being passed and 2) the system is passed as an underdetermined matrix and one wants to control the name of the free variables in the result. An error is raised if no symbols are used for case 1, but if no symbols are provided for case 2, internally generated symbols will be provided. When providing symbols for case 2, there should be at least as many symbols are there are columns in matrix A. The algorithm used here is Gauss-Jordan elimination, which results, after elimination, in a row echelon form matrix. Returns ======= A FiniteSet containing an ordered tuple of values for the unknowns for which the `system` has a solution. (Wrapping the tuple in FiniteSet is used to maintain a consistent output format throughout solveset.) Returns EmptySet, if the linear system is inconsistent. Raises ====== ValueError The input is not valid. The symbols are not given. Examples ======== >>> from sympy import Matrix, linsolve, symbols >>> x, y, z = symbols("x, y, z") >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) >>> b = Matrix([3, 6, 9]) >>> A Matrix([ [1, 2, 3], [4, 5, 6], [7, 8, 10]]) >>> b Matrix([ [3], [6], [9]]) >>> linsolve((A, b), [x, y, z]) {(-1, 2, 0)} * Parametric Solution: In case the system is underdetermined, the function will return a parametric solution in terms of the given symbols. Those that are free will be returned unchanged. e.g. in the system below, `z` is returned as the solution for variable z; it can take on any value. >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> b = Matrix([3, 6, 9]) >>> linsolve((A, b), x, y, z) {(z - 1, 2 - 2*z, z)} If no symbols are given, internally generated symbols will be used. The `tau0` in the 3rd position indicates (as before) that the 3rd variable -- whatever it's named -- can take on any value: >>> linsolve((A, b)) {(tau0 - 1, 2 - 2*tau0, tau0)} * List of Equations as input >>> Eqns = [3*x + 2*y - z - 1, 2*x - 2*y + 4*z + 2, - x + y/2 - z] >>> linsolve(Eqns, x, y, z) {(1, -2, -2)} * Augmented Matrix as input >>> aug = Matrix([[2, 1, 3, 1], [2, 6, 8, 3], [6, 8, 18, 5]]) >>> aug Matrix([ [2, 1, 3, 1], [2, 6, 8, 3], [6, 8, 18, 5]]) >>> linsolve(aug, x, y, z) {(3/10, 2/5, 0)} * Solve for symbolic coefficients >>> a, b, c, d, e, f = symbols('a, b, c, d, e, f') >>> eqns = [a*x + b*y - c, d*x + e*y - f] >>> linsolve(eqns, x, y) {((-b*f + c*e)/(a*e - b*d), (a*f - c*d)/(a*e - b*d))} * A degenerate system returns solution as set of given symbols. >>> system = Matrix(([0, 0, 0], [0, 0, 0], [0, 0, 0])) >>> linsolve(system, x, y) {(x, y)} * For an empty system linsolve returns empty set >>> linsolve([], x) EmptySet * An error is raised if, after expansion, any nonlinearity is detected: >>> linsolve([x*(1/x - 1), (y - 1)**2 - y**2 + 1], x, y) {(1, 1)} >>> linsolve([x**2 - 1], x) Traceback (most recent call last): ... NonlinearError: nonlinear term encountered: x**2 """ if not system: return S.EmptySet # If second argument is an iterable if symbols and hasattr(symbols[0], '__iter__'): symbols = symbols[0] sym_gen = isinstance(symbols, GeneratorType) b = None # if we don't get b the input was bad # unpack system if hasattr(system, '__iter__'): # 1). (A, b) if len(system) == 2 and isinstance(system[0], MatrixBase): A, b = system # 2). (eq1, eq2, ...) if not isinstance(system[0], MatrixBase): if sym_gen or not symbols: raise ValueError(filldedent(''' When passing a system of equations, the explicit symbols for which a solution is being sought must be given as a sequence, too. ''')) # # Pass to the sparse solver implemented in polys. It is important # that we do not attempt to convert the equations to a matrix # because that would be very inefficient for large sparse systems # of equations. # eqs = system eqs = [sympify(eq) for eq in eqs] try: sol = _linsolve(eqs, symbols) except PolyNonlinearError as exc: # e.g. cos(x) contains an element of the set of generators raise NonlinearError(str(exc)) if sol is None: return S.EmptySet sol = FiniteSet(Tuple(*(sol.get(sym, sym) for sym in symbols))) return sol elif isinstance(system, MatrixBase) and not ( symbols and not isinstance(symbols, GeneratorType) and isinstance(symbols[0], MatrixBase)): # 3). A augmented with b A, b = system[:, :-1], system[:, -1:] if b is None: raise ValueError("Invalid arguments") if sym_gen: symbols = [next(symbols) for i in range(A.cols)] if any(set(symbols) & (A.free_symbols | b.free_symbols)): raise ValueError(filldedent(''' At least one of the symbols provided already appears in the system to be solved. One way to avoid this is to use Dummy symbols in the generator, e.g. numbered_symbols('%s', cls=Dummy) ''' % symbols[0].name.rstrip('1234567890'))) if not symbols: symbols = [Dummy() for _ in range(A.cols)] name = _uniquely_named_symbol('tau', (A, b), compare=lambda i: str(i).rstrip('1234567890')).name gen = numbered_symbols(name) else: gen = None # This is just a wrapper for solve_lin_sys eqs = [] rows = A.tolist() for rowi, bi in zip(rows, b): terms = [elem * sym for elem, sym in zip(rowi, symbols) if elem] terms.append(-bi) eqs.append(Add(*terms)) eqs, ring = sympy_eqs_to_ring(eqs, symbols) sol = solve_lin_sys(eqs, ring, _raw=False) if sol is None: return S.EmptySet #sol = {sym:val for sym, val in sol.items() if sym != val} sol = FiniteSet(Tuple(*(sol.get(sym, sym) for sym in symbols))) if gen is not None: solsym = sol.free_symbols rep = {sym: next(gen) for sym in symbols if sym in solsym} sol = sol.subs(rep) return sol ############################################################################## # ------------------------------nonlinsolve ---------------------------------# ############################################################################## def _return_conditionset(eqs, symbols): # return conditionset eqs = (Eq(lhs, 0) for lhs in eqs) condition_set = ConditionSet( Tuple(*symbols), And(*eqs), S.Complexes**len(symbols)) return condition_set def substitution(system, symbols, result=[{}], known_symbols=[], exclude=[], all_symbols=None): r""" Solves the `system` using substitution method. It is used in `nonlinsolve`. This will be called from `nonlinsolve` when any equation(s) is non polynomial equation. Parameters ========== system : list of equations The target system of equations symbols : list of symbols to be solved. The variable(s) for which the system is solved known_symbols : list of solved symbols Values are known for these variable(s) result : An empty list or list of dict If No symbol values is known then empty list otherwise symbol as keys and corresponding value in dict. exclude : Set of expression. Mostly denominator expression(s) of the equations of the system. Final solution should not satisfy these expressions. all_symbols : known_symbols + symbols(unsolved). Returns ======= A FiniteSet of ordered tuple of values of `all_symbols` for which the `system` has solution. Order of values in the tuple is same as symbols present in the parameter `all_symbols`. If parameter `all_symbols` is None then same as symbols present in the parameter `symbols`. Please note that general FiniteSet is unordered, the solution returned here is not simply a FiniteSet of solutions, rather it is a FiniteSet of ordered tuple, i.e. the first & only argument to FiniteSet is a tuple of solutions, which is ordered, & hence the returned solution is ordered. Also note that solution could also have been returned as an ordered tuple, FiniteSet is just a wrapper `{}` around the tuple. It has no other significance except for the fact it is just used to maintain a consistent output format throughout the solveset. Raises ====== ValueError The input is not valid. The symbols are not given. AttributeError The input symbols are not `Symbol` type. Examples ======== >>> from sympy.core.symbol import symbols >>> x, y = symbols('x, y', real=True) >>> from sympy.solvers.solveset import substitution >>> substitution([x + y], [x], [{y: 1}], [y], set([]), [x, y]) {(-1, 1)} * when you want soln should not satisfy eq `x + 1 = 0` >>> substitution([x + y], [x], [{y: 1}], [y], set([x + 1]), [y, x]) EmptySet >>> substitution([x + y], [x], [{y: 1}], [y], set([x - 1]), [y, x]) {(1, -1)} >>> substitution([x + y - 1, y - x**2 + 5], [x, y]) {(-3, 4), (2, -1)} * Returns both real and complex solution >>> x, y, z = symbols('x, y, z') >>> from sympy import exp, sin >>> substitution([exp(x) - sin(y), y**2 - 4], [x, y]) {(ImageSet(Lambda(_n, I*(2*_n*pi + pi) + log(sin(2))), Integers), -2), (ImageSet(Lambda(_n, 2*_n*I*pi + log(sin(2))), Integers), 2)} >>> eqs = [z**2 + exp(2*x) - sin(y), -3 + exp(-y)] >>> substitution(eqs, [y, z]) {(-log(3), -sqrt(-exp(2*x) - sin(log(3)))), (-log(3), sqrt(-exp(2*x) - sin(log(3)))), (ImageSet(Lambda(_n, 2*_n*I*pi - log(3)), Integers), ImageSet(Lambda(_n, -sqrt(-exp(2*x) + sin(2*_n*I*pi - log(3)))), Integers)), (ImageSet(Lambda(_n, 2*_n*I*pi - log(3)), Integers), ImageSet(Lambda(_n, sqrt(-exp(2*x) + sin(2*_n*I*pi - log(3)))), Integers))} """ if not system: return S.EmptySet if not symbols: msg = ('Symbols must be given, for which solution of the ' 'system is to be found.') raise ValueError(filldedent(msg)) if not is_sequence(symbols): msg = ('symbols should be given as a sequence, e.g. a list.' 'Not type %s: %s') raise TypeError(filldedent(msg % (type(symbols), symbols))) if not getattr(symbols[0], 'is_Symbol', False): msg = ('Iterable of symbols must be given as ' 'second argument, not type %s: %s') raise ValueError(filldedent(msg % (type(symbols[0]), symbols[0]))) # By default `all_symbols` will be same as `symbols` if all_symbols is None: all_symbols = symbols old_result = result # storing complements and intersection for particular symbol complements = {} intersections = {} # when total_solveset_call equals total_conditionset # it means that solveset failed to solve all eqs. total_conditionset = -1 total_solveset_call = -1 def _unsolved_syms(eq, sort=False): """Returns the unsolved symbol present in the equation `eq`. """ free = eq.free_symbols unsolved = (free - set(known_symbols)) & set(all_symbols) if sort: unsolved = list(unsolved) unsolved.sort(key=default_sort_key) return unsolved # end of _unsolved_syms() # sort such that equation with the fewest potential symbols is first. # means eq with less number of variable first in the list. eqs_in_better_order = list( ordered(system, lambda _: len(_unsolved_syms(_)))) def add_intersection_complement(result, intersection_dict, complement_dict): # If solveset has returned some intersection/complement # for any symbol, it will be added in the final solution. final_result = [] for res in result: res_copy = res for key_res, value_res in res.items(): intersect_set, complement_set = None, None for key_sym, value_sym in intersection_dict.items(): if key_sym == key_res: intersect_set = value_sym for key_sym, value_sym in complement_dict.items(): if key_sym == key_res: complement_set = value_sym if intersect_set or complement_set: new_value = FiniteSet(value_res) if intersect_set and intersect_set != S.Complexes: new_value = Intersection(new_value, intersect_set) if complement_set: new_value = Complement(new_value, complement_set) if new_value is S.EmptySet: res_copy = None break elif new_value.is_FiniteSet and len(new_value) == 1: res_copy[key_res] = set(new_value).pop() else: res_copy[key_res] = new_value if res_copy is not None: final_result.append(res_copy) return final_result # end of def add_intersection_complement() def _extract_main_soln(sym, sol, soln_imageset): """Separate the Complements, Intersections, ImageSet lambda expr and its base_set. This function returns the unmasks sol from different classes of sets and also returns the appended ImageSet elements in a soln_imageset (dict: where key as unmasked element and value as ImageSet). """ # if there is union, then need to check # Complement, Intersection, Imageset. # Order should not be changed. if isinstance(sol, ConditionSet): # extracts any solution in ConditionSet sol = sol.base_set if isinstance(sol, Complement): # extract solution and complement complements[sym] = sol.args[1] sol = sol.args[0] # complement will be added at the end # using `add_intersection_complement` method # if there is union of Imageset or other in soln. # no testcase is written for this if block if isinstance(sol, Union): sol_args = sol.args sol = S.EmptySet # We need in sequence so append finteset elements # and then imageset or other. for sol_arg2 in sol_args: if isinstance(sol_arg2, FiniteSet): sol += sol_arg2 else: # ImageSet, Intersection, complement then # append them directly sol += FiniteSet(sol_arg2) if isinstance(sol, Intersection): # Interval/Set will be at 0th index always if sol.args[0] not in (S.Reals, S.Complexes): # Sometimes solveset returns soln with intersection # S.Reals or S.Complexes. We don't consider that # intersection. intersections[sym] = sol.args[0] sol = sol.args[1] # after intersection and complement Imageset should # be checked. if isinstance(sol, ImageSet): soln_imagest = sol expr2 = sol.lamda.expr sol = FiniteSet(expr2) soln_imageset[expr2] = soln_imagest if not isinstance(sol, FiniteSet): sol = FiniteSet(sol) return sol, soln_imageset # end of def _extract_main_soln() # helper function for _append_new_soln def _check_exclude(rnew, imgset_yes): rnew_ = rnew if imgset_yes: # replace all dummy variables (Imageset lambda variables) # with zero before `checksol`. Considering fundamental soln # for `checksol`. rnew_copy = rnew.copy() dummy_n = imgset_yes[0] for key_res, value_res in rnew_copy.items(): rnew_copy[key_res] = value_res.subs(dummy_n, 0) rnew_ = rnew_copy # satisfy_exclude == true if it satisfies the expr of `exclude` list. try: # something like : `Mod(-log(3), 2*I*pi)` can't be # simplified right now, so `checksol` returns `TypeError`. # when this issue is fixed this try block should be # removed. Mod(-log(3), 2*I*pi) == -log(3) satisfy_exclude = any( checksol(d, rnew_) for d in exclude) except TypeError: satisfy_exclude = None return satisfy_exclude # end of def _check_exclude() # helper function for _append_new_soln def _restore_imgset(rnew, original_imageset, newresult): restore_sym = set(rnew.keys()) & \ set(original_imageset.keys()) for key_sym in restore_sym: img = original_imageset[key_sym] rnew[key_sym] = img if rnew not in newresult: newresult.append(rnew) # end of def _restore_imgset() def _append_eq(eq, result, res, delete_soln, n=None): u = Dummy('u') if n: eq = eq.subs(n, 0) satisfy = eq if eq in (True, False) else checksol(u, u, eq, minimal=True) if satisfy is False: delete_soln = True res = {} else: result.append(res) return result, res, delete_soln def _append_new_soln(rnew, sym, sol, imgset_yes, soln_imageset, original_imageset, newresult, eq=None): """If `rnew` (A dict <symbol: soln>) contains valid soln append it to `newresult` list. `imgset_yes` is (base, dummy_var) if there was imageset in previously calculated result(otherwise empty tuple). `original_imageset` is dict of imageset expr and imageset from this result. `soln_imageset` dict of imageset expr and imageset of new soln. """ satisfy_exclude = _check_exclude(rnew, imgset_yes) delete_soln = False # soln should not satisfy expr present in `exclude` list. if not satisfy_exclude: local_n = None # if it is imageset if imgset_yes: local_n = imgset_yes[0] base = imgset_yes[1] if sym and sol: # when `sym` and `sol` is `None` means no new # soln. In that case we will append rnew directly after # substituting original imagesets in rnew values if present # (second last line of this function using _restore_imgset) dummy_list = list(sol.atoms(Dummy)) # use one dummy `n` which is in # previous imageset local_n_list = [ local_n for i in range( 0, len(dummy_list))] dummy_zip = zip(dummy_list, local_n_list) lam = Lambda(local_n, sol.subs(dummy_zip)) rnew[sym] = ImageSet(lam, base) if eq is not None: newresult, rnew, delete_soln = _append_eq( eq, newresult, rnew, delete_soln, local_n) elif eq is not None: newresult, rnew, delete_soln = _append_eq( eq, newresult, rnew, delete_soln) elif sol in soln_imageset.keys(): rnew[sym] = soln_imageset[sol] # restore original imageset _restore_imgset(rnew, original_imageset, newresult) else: newresult.append(rnew) elif satisfy_exclude: delete_soln = True rnew = {} _restore_imgset(rnew, original_imageset, newresult) return newresult, delete_soln # end of def _append_new_soln() def _new_order_result(result, eq): # separate first, second priority. `res` that makes `eq` value equals # to zero, should be used first then other result(second priority). # If it is not done then we may miss some soln. first_priority = [] second_priority = [] for res in result: if not any(isinstance(val, ImageSet) for val in res.values()): if eq.subs(res) == 0: first_priority.append(res) else: second_priority.append(res) if first_priority or second_priority: return first_priority + second_priority return result def _solve_using_known_values(result, solver): """Solves the system using already known solution (result contains the dict <symbol: value>). solver is `solveset_complex` or `solveset_real`. """ # stores imageset <expr: imageset(Lambda(n, expr), base)>. soln_imageset = {} total_solvest_call = 0 total_conditionst = 0 # sort such that equation with the fewest potential symbols is first. # means eq with less variable first for index, eq in enumerate(eqs_in_better_order): newresult = [] original_imageset = {} # if imageset expr is used to solve other symbol imgset_yes = False result = _new_order_result(result, eq) for res in result: got_symbol = set() # symbols solved in one iteration # find the imageset and use its expr. for key_res, value_res in res.items(): if isinstance(value_res, ImageSet): res[key_res] = value_res.lamda.expr original_imageset[key_res] = value_res dummy_n = value_res.lamda.expr.atoms(Dummy).pop() (base,) = value_res.base_sets imgset_yes = (dummy_n, base) # update eq with everything that is known so far eq2 = eq.subs(res).expand() unsolved_syms = _unsolved_syms(eq2, sort=True) if not unsolved_syms: if res: newresult, delete_res = _append_new_soln( res, None, None, imgset_yes, soln_imageset, original_imageset, newresult, eq2) if delete_res: # `delete_res` is true, means substituting `res` in # eq2 doesn't return `zero` or deleting the `res` # (a soln) since it staisfies expr of `exclude` # list. result.remove(res) continue # skip as it's independent of desired symbols depen1, depen2 = (eq2.rewrite(Add)).as_independent(*unsolved_syms) if (depen1.has(Abs) or depen2.has(Abs)) and solver == solveset_complex: # Absolute values cannot be inverted in the # complex domain continue soln_imageset = {} for sym in unsolved_syms: not_solvable = False try: soln = solver(eq2, sym) total_solvest_call += 1 soln_new = S.EmptySet if isinstance(soln, Complement): # separate solution and complement complements[sym] = soln.args[1] soln = soln.args[0] # complement will be added at the end if isinstance(soln, Intersection): # Interval will be at 0th index always if soln.args[0] != Interval(-oo, oo): # sometimes solveset returns soln # with intersection S.Reals, to confirm that # soln is in domain=S.Reals intersections[sym] = soln.args[0] soln_new += soln.args[1] soln = soln_new if soln_new else soln if index > 0 and solver == solveset_real: # one symbol's real soln , another symbol may have # corresponding complex soln. if not isinstance(soln, (ImageSet, ConditionSet)): soln += solveset_complex(eq2, sym) except NotImplementedError: # If sovleset is not able to solve equation `eq2`. Next # time we may get soln using next equation `eq2` continue if isinstance(soln, ConditionSet): if soln.base_set in (S.Reals, S.Complexes): soln = S.EmptySet # don't do `continue` we may get soln # in terms of other symbol(s) not_solvable = True total_conditionst += 1 else: soln = soln.base_set if soln is not S.EmptySet: soln, soln_imageset = _extract_main_soln( sym, soln, soln_imageset) for sol in soln: # sol is not a `Union` since we checked it # before this loop sol, soln_imageset = _extract_main_soln( sym, sol, soln_imageset) sol = set(sol).pop() free = sol.free_symbols if got_symbol and any( ss in free for ss in got_symbol ): # sol depends on previously solved symbols # then continue continue rnew = res.copy() # put each solution in res and append the new result # in the new result list (solution for symbol `s`) # along with old results. for k, v in res.items(): if isinstance(v, Expr) and isinstance(sol, Expr): # if any unsolved symbol is present # Then subs known value rnew[k] = v.subs(sym, sol) # and add this new solution if sol in soln_imageset.keys(): # replace all lambda variables with 0. imgst = soln_imageset[sol] rnew[sym] = imgst.lamda( *[0 for i in range(0, len( imgst.lamda.variables))]) else: rnew[sym] = sol newresult, delete_res = _append_new_soln( rnew, sym, sol, imgset_yes, soln_imageset, original_imageset, newresult) if delete_res: # deleting the `res` (a soln) since it staisfies # eq of `exclude` list result.remove(res) # solution got for sym if not not_solvable: got_symbol.add(sym) # next time use this new soln if newresult: result = newresult return result, total_solvest_call, total_conditionst # end def _solve_using_know_values() new_result_real, solve_call1, cnd_call1 = _solve_using_known_values( old_result, solveset_real) new_result_complex, solve_call2, cnd_call2 = _solve_using_known_values( old_result, solveset_complex) # If total_solveset_call is equal to total_conditionset # then solveset failed to solve all of the equations. # In this case we return a ConditionSet here. total_conditionset += (cnd_call1 + cnd_call2) total_solveset_call += (solve_call1 + solve_call2) if total_conditionset == total_solveset_call and total_solveset_call != -1: return _return_conditionset(eqs_in_better_order, all_symbols) # don't keep duplicate solutions filtered_complex = [] for i in list(new_result_complex): for j in list(new_result_real): if i.keys() != j.keys(): continue if all(a.dummy_eq(b) for a, b in zip(i.values(), j.values()) \ if type(a) != int or type(b) != int): break else: filtered_complex.append(i) # overall result result = new_result_real + filtered_complex result_all_variables = [] result_infinite = [] for res in result: if not res: # means {None : None} continue # If length < len(all_symbols) means infinite soln. # Some or all the soln is dependent on 1 symbol. # eg. {x: y+2} then final soln {x: y+2, y: y} if len(res) < len(all_symbols): solved_symbols = res.keys() unsolved = list(filter( lambda x: x not in solved_symbols, all_symbols)) for unsolved_sym in unsolved: res[unsolved_sym] = unsolved_sym result_infinite.append(res) if res not in result_all_variables: result_all_variables.append(res) if result_infinite: # we have general soln # eg : [{x: -1, y : 1}, {x : -y , y: y}] then # return [{x : -y, y : y}] result_all_variables = result_infinite if intersections or complements: result_all_variables = add_intersection_complement( result_all_variables, intersections, complements) # convert to ordered tuple result = S.EmptySet for r in result_all_variables: temp = [r[symb] for symb in all_symbols] result += FiniteSet(tuple(temp)) return result # end of def substitution() def _solveset_work(system, symbols): soln = solveset(system[0], symbols[0]) if isinstance(soln, FiniteSet): _soln = FiniteSet(*[tuple((s,)) for s in soln]) return _soln else: return FiniteSet(tuple(FiniteSet(soln))) def _handle_positive_dimensional(polys, symbols, denominators): from sympy.polys.polytools import groebner # substitution method where new system is groebner basis of the system _symbols = list(symbols) _symbols.sort(key=default_sort_key) basis = groebner(polys, _symbols, polys=True) new_system = [] for poly_eq in basis: new_system.append(poly_eq.as_expr()) result = [{}] result = substitution( new_system, symbols, result, [], denominators) return result # end of def _handle_positive_dimensional() def _handle_zero_dimensional(polys, symbols, system): # solve 0 dimensional poly system using `solve_poly_system` result = solve_poly_system(polys, *symbols) # May be some extra soln is added because # we used `unrad` in `_separate_poly_nonpoly`, so # need to check and remove if it is not a soln. result_update = S.EmptySet for res in result: dict_sym_value = dict(list(zip(symbols, res))) if all(checksol(eq, dict_sym_value) for eq in system): result_update += FiniteSet(res) return result_update # end of def _handle_zero_dimensional() def _separate_poly_nonpoly(system, symbols): polys = [] polys_expr = [] nonpolys = [] denominators = set() poly = None for eq in system: # Store denom expressions that contain symbols denominators.update(_simple_dens(eq, symbols)) # Convert equality to expression if isinstance(eq, Equality): eq = eq.rewrite(Add) # try to remove sqrt and rational power without_radicals = unrad(simplify(eq), *symbols) if without_radicals: eq_unrad, cov = without_radicals if not cov: eq = eq_unrad if isinstance(eq, Expr): eq = eq.as_numer_denom()[0] poly = eq.as_poly(*symbols, extension=True) elif simplify(eq).is_number: continue if poly is not None: polys.append(poly) polys_expr.append(poly.as_expr()) else: nonpolys.append(eq) return polys, polys_expr, nonpolys, denominators # end of def _separate_poly_nonpoly() def nonlinsolve(system, *symbols): r""" Solve system of N nonlinear equations with M variables, which means both under and overdetermined systems are supported. Positive dimensional system is also supported (A system with infinitely many solutions is said to be positive-dimensional). In Positive dimensional system solution will be dependent on at least one symbol. Returns both real solution and complex solution(If system have). The possible number of solutions is zero, one or infinite. Parameters ========== system : list of equations The target system of equations symbols : list of Symbols symbols should be given as a sequence eg. list Returns ======= A FiniteSet of ordered tuple of values of `symbols` for which the `system` has solution. Order of values in the tuple is same as symbols present in the parameter `symbols`. Please note that general FiniteSet is unordered, the solution returned here is not simply a FiniteSet of solutions, rather it is a FiniteSet of ordered tuple, i.e. the first & only argument to FiniteSet is a tuple of solutions, which is ordered, & hence the returned solution is ordered. Also note that solution could also have been returned as an ordered tuple, FiniteSet is just a wrapper `{}` around the tuple. It has no other significance except for the fact it is just used to maintain a consistent output format throughout the solveset. For the given set of Equations, the respective input types are given below: .. math:: x*y - 1 = 0 .. math:: 4*x**2 + y**2 - 5 = 0 `system = [x*y - 1, 4*x**2 + y**2 - 5]` `symbols = [x, y]` Raises ====== ValueError The input is not valid. The symbols are not given. AttributeError The input symbols are not `Symbol` type. Examples ======== >>> from sympy.core.symbol import symbols >>> from sympy.solvers.solveset import nonlinsolve >>> x, y, z = symbols('x, y, z', real=True) >>> nonlinsolve([x*y - 1, 4*x**2 + y**2 - 5], [x, y]) {(-1, -1), (-1/2, -2), (1/2, 2), (1, 1)} 1. Positive dimensional system and complements: >>> from sympy import pprint >>> from sympy.polys.polytools import is_zero_dimensional >>> a, b, c, d = symbols('a, b, c, d', extended_real=True) >>> eq1 = a + b + c + d >>> eq2 = a*b + b*c + c*d + d*a >>> eq3 = a*b*c + b*c*d + c*d*a + d*a*b >>> eq4 = a*b*c*d - 1 >>> system = [eq1, eq2, eq3, eq4] >>> is_zero_dimensional(system) False >>> pprint(nonlinsolve(system, [a, b, c, d]), use_unicode=False) -1 1 1 -1 {(---, -d, -, {d} \ {0}), (-, -d, ---, {d} \ {0})} d d d d >>> nonlinsolve([(x+y)**2 - 4, x + y - 2], [x, y]) {(2 - y, y)} 2. If some of the equations are non-polynomial then `nonlinsolve` will call the `substitution` function and return real and complex solutions, if present. >>> from sympy import exp, sin >>> nonlinsolve([exp(x) - sin(y), y**2 - 4], [x, y]) {(ImageSet(Lambda(_n, I*(2*_n*pi + pi) + log(sin(2))), Integers), -2), (ImageSet(Lambda(_n, 2*_n*I*pi + log(sin(2))), Integers), 2)} 3. If system is non-linear polynomial and zero-dimensional then it returns both solution (real and complex solutions, if present) using `solve_poly_system`: >>> from sympy import sqrt >>> nonlinsolve([x**2 - 2*y**2 -2, x*y - 2], [x, y]) {(-2, -1), (2, 1), (-sqrt(2)*I, sqrt(2)*I), (sqrt(2)*I, -sqrt(2)*I)} 4. `nonlinsolve` can solve some linear (zero or positive dimensional) system (because it uses the `groebner` function to get the groebner basis and then uses the `substitution` function basis as the new `system`). But it is not recommended to solve linear system using `nonlinsolve`, because `linsolve` is better for general linear systems. >>> nonlinsolve([x + 2*y -z - 3, x - y - 4*z + 9 , y + z - 4], [x, y, z]) {(3*z - 5, 4 - z, z)} 5. System having polynomial equations and only real solution is solved using `solve_poly_system`: >>> e1 = sqrt(x**2 + y**2) - 10 >>> e2 = sqrt(y**2 + (-x + 10)**2) - 3 >>> nonlinsolve((e1, e2), (x, y)) {(191/20, -3*sqrt(391)/20), (191/20, 3*sqrt(391)/20)} >>> nonlinsolve([x**2 + 2/y - 2, x + y - 3], [x, y]) {(1, 2), (1 - sqrt(5), 2 + sqrt(5)), (1 + sqrt(5), 2 - sqrt(5))} >>> nonlinsolve([x**2 + 2/y - 2, x + y - 3], [y, x]) {(2, 1), (2 - sqrt(5), 1 + sqrt(5)), (2 + sqrt(5), 1 - sqrt(5))} 6. It is better to use symbols instead of Trigonometric Function or Function (e.g. replace `sin(x)` with symbol, replace `f(x)` with symbol and so on. Get soln from `nonlinsolve` and then using `solveset` get the value of `x`) How nonlinsolve is better than old solver `_solve_system` : =========================================================== 1. A positive dimensional system solver : nonlinsolve can return solution for positive dimensional system. It finds the Groebner Basis of the positive dimensional system(calling it as basis) then we can start solving equation(having least number of variable first in the basis) using solveset and substituting that solved solutions into other equation(of basis) to get solution in terms of minimum variables. Here the important thing is how we are substituting the known values and in which equations. 2. Real and Complex both solutions : nonlinsolve returns both real and complex solution. If all the equations in the system are polynomial then using `solve_poly_system` both real and complex solution is returned. If all the equations in the system are not polynomial equation then goes to `substitution` method with this polynomial and non polynomial equation(s), to solve for unsolved variables. Here to solve for particular variable solveset_real and solveset_complex is used. For both real and complex solution function `_solve_using_know_values` is used inside `substitution` function.(`substitution` function will be called when there is any non polynomial equation(s) is present). When solution is valid then add its general solution in the final result. 3. Complement and Intersection will be added if any : nonlinsolve maintains dict for complements and Intersections. If solveset find complements or/and Intersection with any Interval or set during the execution of `substitution` function ,then complement or/and Intersection for that variable is added before returning final solution. """ from sympy.polys.polytools import is_zero_dimensional if not system: return S.EmptySet if not symbols: msg = ('Symbols must be given, for which solution of the ' 'system is to be found.') raise ValueError(filldedent(msg)) if hasattr(symbols[0], '__iter__'): symbols = symbols[0] if not is_sequence(symbols) or not symbols: msg = ('Symbols must be given, for which solution of the ' 'system is to be found.') raise IndexError(filldedent(msg)) system, symbols, swap = recast_to_symbols(system, symbols) if swap: soln = nonlinsolve(system, symbols) return FiniteSet(*[tuple(i.xreplace(swap) for i in s) for s in soln]) if len(system) == 1 and len(symbols) == 1: return _solveset_work(system, symbols) # main code of def nonlinsolve() starts from here polys, polys_expr, nonpolys, denominators = _separate_poly_nonpoly( system, symbols) if len(symbols) == len(polys): # If all the equations in the system are poly if is_zero_dimensional(polys, symbols): # finite number of soln (Zero dimensional system) try: return _handle_zero_dimensional(polys, symbols, system) except NotImplementedError: # Right now it doesn't fail for any polynomial system of # equation. If `solve_poly_system` fails then `substitution` # method will handle it. result = substitution( polys_expr, symbols, exclude=denominators) return result # positive dimensional system res = _handle_positive_dimensional(polys, symbols, denominators) if res is EmptySet and any(not p.domain.is_Exact for p in polys): raise NotImplementedError("Equation not in exact domain. Try converting to rational") else: return res else: # If all the equations are not polynomial. # Use `substitution` method for the system result = substitution( polys_expr + nonpolys, symbols, exclude=denominators) return result
4abc1642855abec94d2158f43b0aedfe0a87cf919dcad46008dc8786f22fd148
"""Solvers of systems of polynomial equations. """ from sympy.core import S from sympy.polys import Poly, groebner, roots from sympy.polys.polytools import parallel_poly_from_expr from sympy.polys.polyerrors import (ComputationFailed, PolificationFailed, CoercionFailed) from sympy.simplify import rcollect from sympy.utilities import default_sort_key, postfixes from sympy.utilities.misc import filldedent class SolveFailed(Exception): """Raised when solver's conditions weren't met. """ def solve_poly_system(seq, *gens, **args): """ Solve a system of polynomial equations. Parameters ========== seq: a list/tuple/set Listing all the equations that are needed to be solved gens: generators generators of the equations in seq for which we want the solutions args: Keyword arguments Special options for solving the equations Returns ======= List[Tuple] A List of tuples. Solutions for symbols that satisfy the equations listed in seq Examples ======== >>> from sympy import solve_poly_system >>> from sympy.abc import x, y >>> solve_poly_system([x*y - 2*y, 2*y**2 - x**2], x, y) [(0, 0), (2, -sqrt(2)), (2, sqrt(2))] """ try: polys, opt = parallel_poly_from_expr(seq, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('solve_poly_system', len(seq), exc) if len(polys) == len(opt.gens) == 2: f, g = polys if all(i <= 2 for i in f.degree_list() + g.degree_list()): try: return solve_biquadratic(f, g, opt) except SolveFailed: pass return solve_generic(polys, opt) def solve_biquadratic(f, g, opt): """Solve a system of two bivariate quadratic polynomial equations. Parameters ========== f: a single Expr or Poly First equation g: a single Expr or Poly Second Equation opt: an Options object For specifying keyword arguments and generators Returns ======= List[Tuple] A List of tuples. Solutions for symbols that satisfy the equations listed in seq. Examples ======== >>> from sympy.polys import Options, Poly >>> from sympy.abc import x, y >>> from sympy.solvers.polysys import solve_biquadratic >>> NewOption = Options((x, y), {'domain': 'ZZ'}) >>> a = Poly(y**2 - 4 + x, y, x, domain='ZZ') >>> b = Poly(y*2 + 3*x - 7, y, x, domain='ZZ') >>> solve_biquadratic(a, b, NewOption) [(1/3, 3), (41/27, 11/9)] >>> a = Poly(y + x**2 - 3, y, x, domain='ZZ') >>> b = Poly(-y + x - 4, y, x, domain='ZZ') >>> solve_biquadratic(a, b, NewOption) [(7/2 - sqrt(29)/2, -sqrt(29)/2 - 1/2), (sqrt(29)/2 + 7/2, -1/2 + \ sqrt(29)/2)] """ G = groebner([f, g]) if len(G) == 1 and G[0].is_ground: return None if len(G) != 2: raise SolveFailed x, y = opt.gens p, q = G if not p.gcd(q).is_ground: # not 0-dimensional raise SolveFailed p = Poly(p, x, expand=False) p_roots = [rcollect(expr, y) for expr in roots(p).keys()] q = q.ltrim(-1) q_roots = list(roots(q).keys()) solutions = [] for q_root in q_roots: for p_root in p_roots: solution = (p_root.subs(y, q_root), q_root) solutions.append(solution) return sorted(solutions, key=default_sort_key) def solve_generic(polys, opt): """ Solve a generic system of polynomial equations. Returns all possible solutions over C[x_1, x_2, ..., x_m] of a set F = { f_1, f_2, ..., f_n } of polynomial equations, using Groebner basis approach. For now only zero-dimensional systems are supported, which means F can have at most a finite number of solutions. The algorithm works by the fact that, supposing G is the basis of F with respect to an elimination order (here lexicographic order is used), G and F generate the same ideal, they have the same set of solutions. By the elimination property, if G is a reduced, zero-dimensional Groebner basis, then there exists an univariate polynomial in G (in its last variable). This can be solved by computing its roots. Substituting all computed roots for the last (eliminated) variable in other elements of G, new polynomial system is generated. Applying the above procedure recursively, a finite number of solutions can be found. The ability of finding all solutions by this procedure depends on the root finding algorithms. If no solutions were found, it means only that roots() failed, but the system is solvable. To overcome this difficulty use numerical algorithms instead. Parameters ========== polys: a list/tuple/set Listing all the polynomial equations that are needed to be solved opt: an Options object For specifying keyword arguments and generators Returns ======= List[Tuple] A List of tuples. Solutions for symbols that satisfy the equations listed in seq References ========== .. [Buchberger01] B. Buchberger, Groebner Bases: A Short Introduction for Systems Theorists, In: R. Moreno-Diaz, B. Buchberger, J.L. Freire, Proceedings of EUROCAST'01, February, 2001 .. [Cox97] D. Cox, J. Little, D. O'Shea, Ideals, Varieties and Algorithms, Springer, Second Edition, 1997, pp. 112 Examples ======== >>> from sympy.polys import Poly, Options >>> from sympy.solvers.polysys import solve_generic >>> from sympy.abc import x, y >>> NewOption = Options((x, y), {'domain': 'ZZ'}) >>> a = Poly(x - y + 5, x, y, domain='ZZ') >>> b = Poly(x + y - 3, x, y, domain='ZZ') >>> solve_generic([a, b], NewOption) [(-1, 4)] >>> a = Poly(x - 2*y + 5, x, y, domain='ZZ') >>> b = Poly(2*x - y - 3, x, y, domain='ZZ') >>> solve_generic([a, b], NewOption) [(11/3, 13/3)] >>> a = Poly(x**2 + y, x, y, domain='ZZ') >>> b = Poly(x + y*4, x, y, domain='ZZ') >>> solve_generic([a, b], NewOption) [(0, 0), (1/4, -1/16)] """ def _is_univariate(f): """Returns True if 'f' is univariate in its last variable. """ for monom in f.monoms(): if any(monom[:-1]): return False return True def _subs_root(f, gen, zero): """Replace generator with a root so that the result is nice. """ p = f.as_expr({gen: zero}) if f.degree(gen) >= 2: p = p.expand(deep=False) return p def _solve_reduced_system(system, gens, entry=False): """Recursively solves reduced polynomial systems. """ if len(system) == len(gens) == 1: zeros = list(roots(system[0], gens[-1]).keys()) return [(zero,) for zero in zeros] basis = groebner(system, gens, polys=True) if len(basis) == 1 and basis[0].is_ground: if not entry: return [] else: return None univariate = list(filter(_is_univariate, basis)) if len(basis) < len(gens): raise NotImplementedError(filldedent(''' only zero-dimensional systems supported (finite number of solutions) ''')) if len(univariate) == 1: f = univariate.pop() else: raise NotImplementedError(filldedent(''' only zero-dimensional systems supported (finite number of solutions) ''')) gens = f.gens gen = gens[-1] zeros = list(roots(f.ltrim(gen)).keys()) if not zeros: return [] if len(basis) == 1: return [(zero,) for zero in zeros] solutions = [] for zero in zeros: new_system = [] new_gens = gens[:-1] for b in basis[:-1]: eq = _subs_root(b, gen, zero) if eq is not S.Zero: new_system.append(eq) for solution in _solve_reduced_system(new_system, new_gens): solutions.append(solution + (zero,)) if solutions and len(solutions[0]) != len(gens): raise NotImplementedError(filldedent(''' only zero-dimensional systems supported (finite number of solutions) ''')) return solutions try: result = _solve_reduced_system(polys, opt.gens, entry=True) except CoercionFailed: raise NotImplementedError if result is not None: return sorted(result, key=default_sort_key) else: return None def solve_triangulated(polys, *gens, **args): """ Solve a polynomial system using Gianni-Kalkbrenner algorithm. The algorithm proceeds by computing one Groebner basis in the ground domain and then by iteratively computing polynomial factorizations in appropriately constructed algebraic extensions of the ground domain. Parameters ========== polys: a list/tuple/set Listing all the equations that are needed to be solved gens: generators generators of the equations in polys for which we want the solutions args: Keyword arguments Special options for solving the equations Returns ======= List[Tuple] A List of tuples. Solutions for symbols that satisfy the equations listed in polys Examples ======== >>> from sympy.solvers.polysys import solve_triangulated >>> from sympy.abc import x, y, z >>> F = [x**2 + y + z - 1, x + y**2 + z - 1, x + y + z**2 - 1] >>> solve_triangulated(F, x, y, z) [(0, 0, 1), (0, 1, 0), (1, 0, 0)] References ========== 1. Patrizia Gianni, Teo Mora, Algebraic Solution of System of Polynomial Equations using Groebner Bases, AAECC-5 on Applied Algebra, Algebraic Algorithms and Error-Correcting Codes, LNCS 356 247--257, 1989 """ G = groebner(polys, gens, polys=True) G = list(reversed(G)) domain = args.get('domain') if domain is not None: for i, g in enumerate(G): G[i] = g.set_domain(domain) f, G = G[0].ltrim(-1), G[1:] dom = f.get_domain() zeros = f.ground_roots() solutions = set() for zero in zeros: solutions.add(((zero,), dom)) var_seq = reversed(gens[:-1]) vars_seq = postfixes(gens[1:]) for var, vars in zip(var_seq, vars_seq): _solutions = set() for values, dom in solutions: H, mapping = [], list(zip(vars, values)) for g in G: _vars = (var,) + vars if g.has_only_gens(*_vars) and g.degree(var) != 0: h = g.ltrim(var).eval(dict(mapping)) if g.degree(var) == h.degree(): H.append(h) p = min(H, key=lambda h: h.degree()) zeros = p.ground_roots() for zero in zeros: if not zero.is_Rational: dom_zero = dom.algebraic_field(zero) else: dom_zero = dom _solutions.add(((zero,) + values, dom_zero)) solutions = _solutions solutions = list(solutions) for i, (solution, _) in enumerate(solutions): solutions[i] = solution return sorted(solutions, key=default_sort_key)
576c36d6f44b8f72870748d6ba269711156b1a934be0d0e7a377a77eaf8af9f8
"""Tools for solving inequalities and systems of inequalities. """ from sympy.core import Symbol, Dummy, sympify from sympy.core.compatibility import iterable from sympy.core.exprtools import factor_terms from sympy.core.relational import Relational, Eq, Ge, Lt from sympy.sets import Interval from sympy.sets.sets import FiniteSet, Union, EmptySet, Intersection from sympy.core.singleton import S from sympy.core.function import expand_mul from sympy.functions import Abs from sympy.logic import And from sympy.polys import Poly, PolynomialError, parallel_poly_from_expr from sympy.polys.polyutils import _nsort from sympy.utilities.iterables import sift from sympy.utilities.misc import filldedent def solve_poly_inequality(poly, rel): """Solve a polynomial inequality with rational coefficients. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> from sympy.solvers.inequalities import solve_poly_inequality >>> solve_poly_inequality(Poly(x, x, domain='ZZ'), '==') [{0}] >>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '!=') [Interval.open(-oo, -1), Interval.open(-1, 1), Interval.open(1, oo)] >>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '==') [{-1}, {1}] See Also ======== solve_poly_inequalities """ if not isinstance(poly, Poly): raise ValueError( 'For efficiency reasons, `poly` should be a Poly instance') if poly.as_expr().is_number: t = Relational(poly.as_expr(), 0, rel) if t is S.true: return [S.Reals] elif t is S.false: return [S.EmptySet] else: raise NotImplementedError( "could not determine truth value of %s" % t) reals, intervals = poly.real_roots(multiple=False), [] if rel == '==': for root, _ in reals: interval = Interval(root, root) intervals.append(interval) elif rel == '!=': left = S.NegativeInfinity for right, _ in reals + [(S.Infinity, 1)]: interval = Interval(left, right, True, True) intervals.append(interval) left = right else: if poly.LC() > 0: sign = +1 else: sign = -1 eq_sign, equal = None, False if rel == '>': eq_sign = +1 elif rel == '<': eq_sign = -1 elif rel == '>=': eq_sign, equal = +1, True elif rel == '<=': eq_sign, equal = -1, True else: raise ValueError("'%s' is not a valid relation" % rel) right, right_open = S.Infinity, True for left, multiplicity in reversed(reals): if multiplicity % 2: if sign == eq_sign: intervals.insert( 0, Interval(left, right, not equal, right_open)) sign, right, right_open = -sign, left, not equal else: if sign == eq_sign and not equal: intervals.insert( 0, Interval(left, right, True, right_open)) right, right_open = left, True elif sign != eq_sign and equal: intervals.insert(0, Interval(left, left)) if sign == eq_sign: intervals.insert( 0, Interval(S.NegativeInfinity, right, True, right_open)) return intervals def solve_poly_inequalities(polys): """Solve polynomial inequalities with rational coefficients. Examples ======== >>> from sympy.solvers.inequalities import solve_poly_inequalities >>> from sympy.polys import Poly >>> from sympy.abc import x >>> solve_poly_inequalities((( ... Poly(x**2 - 3), ">"), ( ... Poly(-x**2 + 1), ">"))) Union(Interval.open(-oo, -sqrt(3)), Interval.open(-1, 1), Interval.open(sqrt(3), oo)) """ from sympy import Union return Union(*[s for p in polys for s in solve_poly_inequality(*p)]) def solve_rational_inequalities(eqs): """Solve a system of rational inequalities with rational coefficients. Examples ======== >>> from sympy.abc import x >>> from sympy import Poly >>> from sympy.solvers.inequalities import solve_rational_inequalities >>> solve_rational_inequalities([[ ... ((Poly(-x + 1), Poly(1, x)), '>='), ... ((Poly(-x + 1), Poly(1, x)), '<=')]]) {1} >>> solve_rational_inequalities([[ ... ((Poly(x), Poly(1, x)), '!='), ... ((Poly(-x + 1), Poly(1, x)), '>=')]]) Union(Interval.open(-oo, 0), Interval.Lopen(0, 1)) See Also ======== solve_poly_inequality """ result = S.EmptySet for _eqs in eqs: if not _eqs: continue global_intervals = [Interval(S.NegativeInfinity, S.Infinity)] for (numer, denom), rel in _eqs: numer_intervals = solve_poly_inequality(numer*denom, rel) denom_intervals = solve_poly_inequality(denom, '==') intervals = [] for numer_interval in numer_intervals: for global_interval in global_intervals: interval = numer_interval.intersect(global_interval) if interval is not S.EmptySet: intervals.append(interval) global_intervals = intervals intervals = [] for global_interval in global_intervals: for denom_interval in denom_intervals: global_interval -= denom_interval if global_interval is not S.EmptySet: intervals.append(global_interval) global_intervals = intervals if not global_intervals: break for interval in global_intervals: result = result.union(interval) return result def reduce_rational_inequalities(exprs, gen, relational=True): """Reduce a system of rational inequalities with rational coefficients. Examples ======== >>> from sympy import Symbol >>> from sympy.solvers.inequalities import reduce_rational_inequalities >>> x = Symbol('x', real=True) >>> reduce_rational_inequalities([[x**2 <= 0]], x) Eq(x, 0) >>> reduce_rational_inequalities([[x + 2 > 0]], x) -2 < x >>> reduce_rational_inequalities([[(x + 2, ">")]], x) -2 < x >>> reduce_rational_inequalities([[x + 2]], x) Eq(x, -2) This function find the non-infinite solution set so if the unknown symbol is declared as extended real rather than real then the result may include finiteness conditions: >>> y = Symbol('y', extended_real=True) >>> reduce_rational_inequalities([[y + 2 > 0]], y) (-2 < y) & (y < oo) """ exact = True eqs = [] solution = S.Reals if exprs else S.EmptySet 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, '==' if expr is S.true: numer, denom, rel = S.Zero, S.One, '==' elif expr is S.false: numer, denom, rel = S.One, S.One, '==' else: numer, denom = expr.together().as_numer_denom() try: (numer, denom), opt = parallel_poly_from_expr( (numer, denom), gen) except PolynomialError: raise PolynomialError(filldedent(''' 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): expr = numer/denom expr = Relational(expr, 0, rel) solution &= solve_univariate_inequality(expr, gen, relational=False) else: _eqs.append(((numer, denom), rel)) if _eqs: eqs.append(_eqs) if eqs: solution &= solve_rational_inequalities(eqs) exclude = solve_rational_inequalities([[((d, d.one), '==') for i in eqs for ((n, d), _) in i if d.has(gen)]]) solution -= exclude if not exact and solution: solution = solution.evalf() if relational: solution = solution.as_relational(gen) return solution def reduce_abs_inequality(expr, rel, gen): """Reduce an inequality with nested absolute values. Examples ======== >>> from sympy import Abs, Symbol >>> from sympy.solvers.inequalities import reduce_abs_inequality >>> x = Symbol('x', real=True) >>> reduce_abs_inequality(Abs(x - 5) - 3, '<', x) (2 < x) & (x < 8) >>> reduce_abs_inequality(Abs(x + 2)*3 - 13, '<', x) (-19/3 < x) & (x < 7/3) See Also ======== reduce_abs_inequalities """ if gen.is_extended_real is False: raise TypeError(filldedent(''' can't solve inequalities with absolute values containing non-real variables. ''')) def _bottom_up_scan(expr): exprs = [] if expr.is_Add or expr.is_Mul: op = expr.func for arg in expr.args: _exprs = _bottom_up_scan(arg) if not exprs: exprs = _exprs else: args = [] for expr, conds in exprs: for _expr, _conds in _exprs: args.append((op(expr, _expr), conds + _conds)) exprs = args elif expr.is_Pow: n = expr.exp if not n.is_Integer: raise ValueError("Only Integer Powers are allowed on Abs.") _exprs = _bottom_up_scan(expr.base) for expr, conds in _exprs: exprs.append((expr**n, conds)) elif isinstance(expr, Abs): _exprs = _bottom_up_scan(expr.args[0]) for expr, conds in _exprs: exprs.append(( expr, conds + [Ge(expr, 0)])) exprs.append((-expr, conds + [Lt(expr, 0)])) else: exprs = [(expr, [])] return exprs exprs = _bottom_up_scan(expr) mapping = {'<': '>', '<=': '>='} inequalities = [] for expr, conds in exprs: if rel not in mapping.keys(): expr = Relational( expr, 0, rel) else: expr = Relational(-expr, 0, mapping[rel]) inequalities.append([expr] + conds) return reduce_rational_inequalities(inequalities, gen) def reduce_abs_inequalities(exprs, gen): """Reduce a system of inequalities with nested absolute values. Examples ======== >>> from sympy import Abs, Symbol >>> from sympy.solvers.inequalities import reduce_abs_inequalities >>> x = Symbol('x', extended_real=True) >>> reduce_abs_inequalities([(Abs(3*x - 5) - 7, '<'), ... (Abs(x + 25) - 13, '>')], x) (-2/3 < x) & (x < 4) & (((-oo < x) & (x < -38)) | ((-12 < x) & (x < oo))) >>> reduce_abs_inequalities([(Abs(x - 4) + Abs(3*x - 5) - 7, '<')], x) (1/2 < x) & (x < 4) See Also ======== reduce_abs_inequality """ return And(*[ reduce_abs_inequality(expr, rel, gen) for expr, rel in exprs ]) def solve_univariate_inequality(expr, gen, relational=True, domain=S.Reals, continuous=False): """Solves a real univariate inequality. Parameters ========== expr : Relational The target inequality gen : Symbol The variable for which the inequality is solved relational : bool A Relational type output is expected or not domain : Set The domain over which the equation is solved continuous: bool True if expr is known to be continuous over the given domain (and so continuous_domain() doesn't need to be called on it) Raises ====== NotImplementedError The solution of the inequality cannot be determined due to limitation in :func:`sympy.solvers.solveset.solvify`. Notes ===== Currently, we cannot solve all the inequalities due to limitations in :func:`sympy.solvers.solveset.solvify`. Also, the solution returned for trigonometric inequalities are restricted in its periodic interval. See Also ======== sympy.solvers.solveset.solvify: solver returning solveset solutions with solve's output API Examples ======== >>> from sympy.solvers.inequalities import solve_univariate_inequality >>> from sympy import Symbol, sin, Interval, S >>> x = Symbol('x') >>> solve_univariate_inequality(x**2 >= 4, x) ((2 <= x) & (x < oo)) | ((x <= -2) & (-oo < x)) >>> solve_univariate_inequality(x**2 >= 4, x, relational=False) Union(Interval(-oo, -2), Interval(2, oo)) >>> domain = Interval(0, S.Infinity) >>> solve_univariate_inequality(x**2 >= 4, x, False, domain) Interval(2, oo) >>> solve_univariate_inequality(sin(x) > 0, x, relational=False) Interval.open(0, pi) """ from sympy import im from sympy.calculus.util import (continuous_domain, periodicity, function_range) from sympy.solvers.solvers import denoms from sympy.solvers.solveset import solvify, solveset if domain.is_subset(S.Reals) is False: raise NotImplementedError(filldedent(''' Inequalities in the complex domain are not supported. Try the real domain by setting domain=S.Reals''')) elif domain is not S.Reals: rv = solve_univariate_inequality( expr, gen, relational=False, continuous=continuous).intersection(domain) if relational: rv = rv.as_relational(gen) return rv else: pass # continue with attempt to solve in Real domain # This keeps the function independent of the assumptions about `gen`. # `solveset` makes sure this function is called only when the domain is # real. _gen = gen _domain = domain if gen.is_extended_real is False: rv = S.EmptySet return rv if not relational else rv.as_relational(_gen) elif gen.is_extended_real is None: gen = Dummy('gen', extended_real=True) try: expr = expr.xreplace({_gen: gen}) except TypeError: raise TypeError(filldedent(''' When gen is real, the relational has a complex part which leads to an invalid comparison like I < 0. ''')) rv = None if expr is S.true: rv = domain elif expr is S.false: rv = S.EmptySet else: e = expr.lhs - expr.rhs period = periodicity(e, gen) if period == S.Zero: e = expand_mul(e) const = expr.func(e, 0) if const is S.true: rv = domain elif const is S.false: rv = S.EmptySet elif period is not None: frange = function_range(e, gen, domain) rel = expr.rel_op if rel == '<' or rel == '<=': if expr.func(frange.sup, 0): rv = domain elif not expr.func(frange.inf, 0): rv = S.EmptySet elif rel == '>' or rel == '>=': if expr.func(frange.inf, 0): rv = domain elif not expr.func(frange.sup, 0): rv = S.EmptySet inf, sup = domain.inf, domain.sup if sup - inf is S.Infinity: domain = Interval(0, period, False, True).intersect(_domain) _domain = domain if rv is None: n, d = e.as_numer_denom() try: if gen not in n.free_symbols and len(e.free_symbols) > 1: raise ValueError # this might raise ValueError on its own # or it might give None... solns = solvify(e, gen, domain) if solns is None: # in which case we raise ValueError raise ValueError except (ValueError, NotImplementedError): # replace gen with generic x since it's # univariate anyway raise NotImplementedError(filldedent(''' The inequality, %s, cannot be solved using solve_univariate_inequality. ''' % expr.subs(gen, Symbol('x')))) expanded_e = expand_mul(e) def valid(x): # this is used to see if gen=x satisfies the # relational by substituting it into the # expanded form and testing against 0, e.g. # if expr = x*(x + 1) < 2 then e = x*(x + 1) - 2 # and expanded_e = x**2 + x - 2; the test is # whether a given value of x satisfies # x**2 + x - 2 < 0 # # expanded_e, expr and gen used from enclosing scope v = expanded_e.subs(gen, expand_mul(x)) try: r = expr.func(v, 0) except TypeError: r = S.false if r in (S.true, S.false): return r if v.is_extended_real is False: return S.false else: v = v.n(2) if v.is_comparable: return expr.func(v, 0) # not comparable or couldn't be evaluated raise NotImplementedError( 'relationship did not evaluate: %s' % r) singularities = [] for d in denoms(expr, gen): singularities.extend(solvify(d, gen, domain)) if not continuous: domain = continuous_domain(expanded_e, gen, domain) include_x = '=' in expr.rel_op and expr.rel_op != '!=' try: discontinuities = set(domain.boundary - FiniteSet(domain.inf, domain.sup)) # remove points that are not between inf and sup of domain critical_points = FiniteSet(*(solns + singularities + list( discontinuities))).intersection( Interval(domain.inf, domain.sup, domain.inf not in domain, domain.sup not in domain)) if all(r.is_number for r in critical_points): reals = _nsort(critical_points, separated=True)[0] else: sifted = sift(critical_points, lambda x: x.is_extended_real) if sifted[None]: # there were some roots that weren't known # to be real raise NotImplementedError try: reals = sifted[True] if len(reals) > 1: reals = list(sorted(reals)) except TypeError: raise NotImplementedError except NotImplementedError: raise NotImplementedError('sorting of these roots is not supported') # If expr contains imaginary coefficients, only take real # values of x for which the imaginary part is 0 make_real = S.Reals if im(expanded_e) != S.Zero: check = True im_sol = FiniteSet() try: a = solveset(im(expanded_e), gen, domain) if not isinstance(a, Interval): for z in a: if z not in singularities and valid(z) and z.is_extended_real: im_sol += FiniteSet(z) else: start, end = a.inf, a.sup for z in _nsort(critical_points + FiniteSet(end)): valid_start = valid(start) if start != end: valid_z = valid(z) pt = _pt(start, z) if pt not in singularities and pt.is_extended_real and valid(pt): if valid_start and valid_z: im_sol += Interval(start, z) elif valid_start: im_sol += Interval.Ropen(start, z) elif valid_z: im_sol += Interval.Lopen(start, z) else: im_sol += Interval.open(start, z) start = z for s in singularities: im_sol -= FiniteSet(s) except (TypeError): im_sol = S.Reals check = False if isinstance(im_sol, EmptySet): raise ValueError(filldedent(''' %s contains imaginary parts which cannot be made 0 for any value of %s satisfying the inequality, leading to relations like I < 0. ''' % (expr.subs(gen, _gen), _gen))) make_real = make_real.intersect(im_sol) sol_sets = [S.EmptySet] start = domain.inf if start in domain and valid(start) and start.is_finite: sol_sets.append(FiniteSet(start)) for x in reals: end = x if valid(_pt(start, end)): sol_sets.append(Interval(start, end, True, True)) if x in singularities: singularities.remove(x) else: if x in discontinuities: discontinuities.remove(x) _valid = valid(x) else: # it's a solution _valid = include_x if _valid: sol_sets.append(FiniteSet(x)) start = end end = domain.sup if end in domain and valid(end) and end.is_finite: sol_sets.append(FiniteSet(end)) if valid(_pt(start, end)): sol_sets.append(Interval.open(start, end)) if im(expanded_e) != S.Zero and check: rv = (make_real).intersect(_domain) else: rv = Intersection( (Union(*sol_sets)), make_real, _domain).subs(gen, _gen) return rv if not relational else rv.as_relational(_gen) def _pt(start, end): """Return a point between start and end""" if not start.is_infinite and not end.is_infinite: pt = (start + end)/2 elif start.is_infinite and end.is_infinite: pt = S.Zero else: if (start.is_infinite and start.is_extended_positive is None or end.is_infinite and end.is_extended_positive is None): raise ValueError('cannot proceed with unsigned infinite values') if (end.is_infinite and end.is_extended_negative or start.is_infinite and start.is_extended_positive): start, end = end, start # if possible, use a multiple of self which has # better behavior when checking assumptions than # an expression obtained by adding or subtracting 1 if end.is_infinite: if start.is_extended_positive: pt = start*2 elif start.is_extended_negative: pt = start*S.Half else: pt = start + 1 elif start.is_infinite: if end.is_extended_positive: pt = end*S.Half elif end.is_extended_negative: pt = end*2 else: pt = end - 1 return pt def _solve_inequality(ie, s, linear=False): """Return the inequality with s isolated on the left, if possible. If the relationship is non-linear, a solution involving And or Or may be returned. False or True are returned if the relationship is never True or always True, respectively. If `linear` is True (default is False) an `s`-dependent expression will be isolated on the left, if possible but it will not be solved for `s` unless the expression is linear in `s`. Furthermore, only "safe" operations which don't change the sense of the relationship are applied: no division by an unsigned value is attempted unless the relationship involves Eq or Ne and no division by a value not known to be nonzero is ever attempted. Examples ======== >>> from sympy import Eq, Symbol >>> from sympy.solvers.inequalities import _solve_inequality as f >>> from sympy.abc import x, y For linear expressions, the symbol can be isolated: >>> f(x - 2 < 0, x) x < 2 >>> f(-x - 6 < x, x) x > -3 Sometimes nonlinear relationships will be False >>> f(x**2 + 4 < 0, x) False Or they may involve more than one region of values: >>> f(x**2 - 4 < 0, x) (-2 < x) & (x < 2) To restrict the solution to a relational, set linear=True and only the x-dependent portion will be isolated on the left: >>> f(x**2 - 4 < 0, x, linear=True) x**2 < 4 Division of only nonzero quantities is allowed, so x cannot be isolated by dividing by y: >>> y.is_nonzero is None # it is unknown whether it is 0 or not True >>> f(x*y < 1, x) x*y < 1 And while an equality (or inequality) still holds after dividing by a non-zero quantity >>> nz = Symbol('nz', nonzero=True) >>> f(Eq(x*nz, 1), x) Eq(x, 1/nz) the sign must be known for other inequalities involving > or <: >>> f(x*nz <= 1, x) nz*x <= 1 >>> p = Symbol('p', positive=True) >>> f(x*p <= 1, x) x <= 1/p When there are denominators in the original expression that are removed by expansion, conditions for them will be returned as part of the result: >>> f(x < x*(2/x - 1), x) (x < 1) & Ne(x, 0) """ from sympy.solvers.solvers import denoms if s not in ie.free_symbols: return ie if ie.rhs == s: ie = ie.reversed if ie.lhs == s and s not in ie.rhs.free_symbols: return ie def classify(ie, s, i): # return True or False if ie evaluates when substituting s with # i else None (if unevaluated) or NaN (when there is an error # in evaluating) try: v = ie.subs(s, i) if v is S.NaN: return v elif v not in (True, False): return return v except TypeError: return S.NaN rv = None oo = S.Infinity expr = ie.lhs - ie.rhs try: p = Poly(expr, s) if p.degree() == 0: rv = ie.func(p.as_expr(), 0) elif not linear and p.degree() > 1: # handle in except clause raise NotImplementedError except (PolynomialError, NotImplementedError): if not linear: try: rv = reduce_rational_inequalities([[ie]], s) except PolynomialError: rv = solve_univariate_inequality(ie, s) # remove restrictions wrt +/-oo that may have been # applied when using sets to simplify the relationship okoo = classify(ie, s, oo) if okoo is S.true and classify(rv, s, oo) is S.false: rv = rv.subs(s < oo, True) oknoo = classify(ie, s, -oo) if (oknoo is S.true and classify(rv, s, -oo) is S.false): rv = rv.subs(-oo < s, True) rv = rv.subs(s > -oo, True) if rv is S.true: rv = (s <= oo) if okoo is S.true else (s < oo) if oknoo is not S.true: rv = And(-oo < s, rv) else: p = Poly(expr) conds = [] if rv is None: e = p.as_expr() # this is in expanded form # Do a safe inversion of e, moving non-s terms # to the rhs and dividing by a nonzero factor if # the relational is Eq/Ne; for other relationals # the sign must also be positive or negative rhs = 0 b, ax = e.as_independent(s, as_Add=True) e -= b rhs -= b ef = factor_terms(e) a, e = ef.as_independent(s, as_Add=False) if (a.is_zero != False or # don't divide by potential 0 a.is_negative == a.is_positive is None and # if sign is not known then ie.rel_op not in ('!=', '==')): # reject if not Eq/Ne e = ef a = S.One rhs /= a if a.is_positive: rv = ie.func(e, rhs) else: rv = ie.reversed.func(e, rhs) # return conditions under which the value is # valid, too. beginning_denoms = denoms(ie.lhs) | denoms(ie.rhs) current_denoms = denoms(rv) for d in beginning_denoms - current_denoms: c = _solve_inequality(Eq(d, 0), s, linear=linear) if isinstance(c, Eq) and c.lhs == s: if classify(rv, s, c.rhs) is S.true: # rv is permitting this value but it shouldn't conds.append(~c) for i in (-oo, oo): if (classify(rv, s, i) is S.true and classify(ie, s, i) is not S.true): conds.append(s < i if i is oo else i < s) conds.append(rv) return And(*conds) def _reduce_inequalities(inequalities, symbols): # helper for reduce_inequalities poly_part, abs_part = {}, {} other = [] for inequality in inequalities: expr, rel = inequality.lhs, inequality.rel_op # rhs is 0 # check for gens using atoms which is more strict than free_symbols to # guard against EX domain which won't be handled by # reduce_rational_inequalities gens = expr.atoms(Symbol) if len(gens) == 1: gen = gens.pop() else: common = expr.free_symbols & symbols if len(common) == 1: gen = common.pop() other.append(_solve_inequality(Relational(expr, 0, rel), gen)) continue else: raise NotImplementedError(filldedent(''' inequality has more than one symbol of interest. ''')) if expr.is_polynomial(gen): poly_part.setdefault(gen, []).append((expr, rel)) else: components = expr.find(lambda u: u.has(gen) and ( u.is_Function or u.is_Pow and not u.exp.is_Integer)) if components and all(isinstance(i, Abs) for i in components): abs_part.setdefault(gen, []).append((expr, rel)) else: other.append(_solve_inequality(Relational(expr, 0, rel), gen)) poly_reduced = [] abs_reduced = [] for gen, exprs in poly_part.items(): poly_reduced.append(reduce_rational_inequalities([exprs], gen)) for gen, exprs in abs_part.items(): abs_reduced.append(reduce_abs_inequalities(exprs, gen)) return And(*(poly_reduced + abs_reduced + other)) def reduce_inequalities(inequalities, symbols=[]): """Reduce a system of inequalities with rational coefficients. Examples ======== >>> from sympy.abc import x, y >>> from sympy.solvers.inequalities import reduce_inequalities >>> reduce_inequalities(0 <= x + 3, []) (-3 <= x) & (x < oo) >>> reduce_inequalities(0 <= x + y*2 - 1, [x]) (x < oo) & (x >= 1 - 2*y) """ if not iterable(inequalities): inequalities = [inequalities] inequalities = [sympify(i) for i in inequalities] gens = set().union(*[i.free_symbols for i in inequalities]) if not iterable(symbols): symbols = [symbols] symbols = (set(symbols) or gens) & gens if any(i.is_extended_real is False for i in symbols): raise TypeError(filldedent(''' inequalities cannot contain symbols that are not real. ''')) # make vanilla symbol real recast = {i: Dummy(i.name, extended_real=True) for i in gens if i.is_extended_real is None} inequalities = [i.xreplace(recast) for i in inequalities] symbols = {i.xreplace(recast) for i in symbols} # prefilter keep = [] for i in inequalities: if isinstance(i, Relational): i = i.func(i.lhs.as_expr() - i.rhs.as_expr(), 0) elif i not in (True, False): i = Eq(i, 0) if i == True: continue elif i == False: return S.false if i.lhs.is_number: raise NotImplementedError( "could not determine truth value of %s" % i) keep.append(i) inequalities = keep del keep # solve system rv = _reduce_inequalities(inequalities, symbols) # restore original symbols and return return rv.xreplace({v: k for k, v in recast.items()})
9e99ea1c0835367203785e793c387f0a61dada210a85777d68aa44d5886cd42d
""" This module contain solvers for all kinds of equations: - algebraic or transcendental, use solve() - recurrence, use rsolve() - differential, use dsolve() - nonlinear (numerically), use nsolve() (you will need a good starting point) """ from sympy import divisors, binomial, expand_func from sympy.core.assumptions import check_assumptions from sympy.core.compatibility import (iterable, is_sequence, ordered, default_sort_key) from sympy.core.sympify import sympify from sympy.core import (S, Add, Symbol, Equality, Dummy, Expr, Mul, Pow, Unequality, Wild) from sympy.core.exprtools import factor_terms from sympy.core.function import (expand_mul, expand_log, Derivative, AppliedUndef, UndefinedFunction, nfloat, Function, expand_power_exp, _mexpand, expand) from sympy.integrals.integrals import Integral from sympy.core.numbers import ilcm, Float, Rational from sympy.core.relational import Relational from sympy.core.logic import fuzzy_not from sympy.core.power import integer_log from sympy.logic.boolalg import And, Or, BooleanAtom from sympy.core.basic import preorder_traversal from sympy.functions import (log, exp, LambertW, cos, sin, tan, acos, asin, atan, Abs, re, im, arg, sqrt, atan2) from sympy.functions.elementary.trigonometric import (TrigonometricFunction, HyperbolicFunction) from sympy.simplify import (simplify, collect, powsimp, posify, # type: ignore powdenest, nsimplify, denom, logcombine, sqrtdenest, fraction, separatevars) from sympy.simplify.sqrtdenest import sqrt_depth from sympy.simplify.fu import TR1, TR2i from sympy.matrices.common import NonInvertibleMatrixError from sympy.matrices import Matrix, zeros from sympy.polys import roots, cancel, factor, Poly from sympy.polys.polyerrors import GeneratorsNeeded, PolynomialError from sympy.polys.solvers import sympy_eqs_to_ring, solve_lin_sys from sympy.functions.elementary.piecewise import piecewise_fold, Piecewise from sympy.utilities.lambdify import lambdify from sympy.utilities.misc import filldedent from sympy.utilities.iterables import (connected_components, generate_bell, uniq) from sympy.utilities.decorator import conserve_mpmath_dps from mpmath import findroot from sympy.solvers.polysys import solve_poly_system from sympy.solvers.inequalities import reduce_inequalities from types import GeneratorType from collections import defaultdict from itertools import product import warnings def recast_to_symbols(eqs, symbols): """ Return (e, s, d) where e and s are versions of *eqs* and *symbols* in which any non-Symbol objects in *symbols* have been replaced with generic Dummy symbols and d is a dictionary that can be used to restore the original expressions. Examples ======== >>> from sympy.solvers.solvers import recast_to_symbols >>> from sympy import symbols, Function >>> x, y = symbols('x y') >>> fx = Function('f')(x) >>> eqs, syms = [fx + 1, x, y], [fx, y] >>> e, s, d = recast_to_symbols(eqs, syms); (e, s, d) ([_X0 + 1, x, y], [_X0, y], {_X0: f(x)}) The original equations and symbols can be restored using d: >>> assert [i.xreplace(d) for i in eqs] == eqs >>> assert [d.get(i, i) for i in s] == syms """ if not iterable(eqs) and iterable(symbols): raise ValueError('Both eqs and symbols must be iterable') new_symbols = list(symbols) swap_sym = {} for i, s in enumerate(symbols): if not isinstance(s, Symbol) and s not in swap_sym: swap_sym[s] = Dummy('X%d' % i) new_symbols[i] = swap_sym[s] new_f = [] for i in eqs: isubs = getattr(i, 'subs', None) if isubs is not None: new_f.append(isubs(swap_sym)) else: new_f.append(i) swap_sym = {v: k for k, v in swap_sym.items()} return new_f, new_symbols, swap_sym def _ispow(e): """Return True if e is a Pow or is exp.""" return isinstance(e, Expr) and (e.is_Pow or isinstance(e, exp)) def _simple_dens(f, symbols): # when checking if a denominator is zero, we can just check the # base of powers with nonzero exponents since if the base is zero # the power will be zero, too. To keep it simple and fast, we # limit simplification to exponents that are Numbers dens = set() for d in denoms(f, symbols): if d.is_Pow and d.exp.is_Number: if d.exp.is_zero: continue # foo**0 is never 0 d = d.base dens.add(d) return dens def denoms(eq, *symbols): """ Return (recursively) set of all denominators that appear in *eq* that contain any symbol in *symbols*; if *symbols* are not provided then all denominators will be returned. Examples ======== >>> from sympy.solvers.solvers import denoms >>> from sympy.abc import x, y, z >>> denoms(x/y) {y} >>> denoms(x/(y*z)) {y, z} >>> denoms(3/x + y/z) {x, z} >>> denoms(x/2 + y/z) {2, z} If *symbols* are provided then only denominators containing those symbols will be returned: >>> denoms(1/x + 1/y + 1/z, y, z) {y, z} """ pot = preorder_traversal(eq) dens = set() for p in pot: # Here p might be Tuple or Relational # Expr subtrees (e.g. lhs and rhs) will be traversed after by pot if not isinstance(p, Expr): continue den = denom(p) if den is S.One: continue for d in Mul.make_args(den): dens.add(d) if not symbols: return dens elif len(symbols) == 1: if iterable(symbols[0]): symbols = symbols[0] rv = [] for d in dens: free = d.free_symbols if any(s in free for s in symbols): rv.append(d) return set(rv) def checksol(f, symbol, sol=None, **flags): """ Checks whether sol is a solution of equation f == 0. Explanation =========== Input can be either a single symbol and corresponding value or a dictionary of symbols and values. When given as a dictionary and flag ``simplify=True``, the values in the dictionary will be simplified. *f* can be a single equation or an iterable of equations. A solution must satisfy all equations in *f* to be considered valid; if a solution does not satisfy any equation, False is returned; if one or more checks are inconclusive (and none are False) then None is returned. Examples ======== >>> from sympy import symbols >>> from sympy.solvers import checksol >>> x, y = symbols('x,y') >>> checksol(x**4 - 1, x, 1) True >>> checksol(x**4 - 1, x, 0) False >>> checksol(x**2 + y**2 - 5**2, {x: 3, y: 4}) True To check if an expression is zero using ``checksol()``, pass it as *f* and send an empty dictionary for *symbol*: >>> checksol(x**2 + x - x*(x + 1), {}) True None is returned if ``checksol()`` could not conclude. flags: 'numerical=True (default)' do a fast numerical check if ``f`` has only one symbol. 'minimal=True (default is False)' a very fast, minimal testing. 'warn=True (default is False)' show a warning if checksol() could not conclude. 'simplify=True (default)' simplify solution before substituting into function and simplify the function before trying specific simplifications 'force=True (default is False)' make positive all symbols without assumptions regarding sign. """ from sympy.physics.units import Unit minimal = flags.get('minimal', False) if sol is not None: sol = {symbol: sol} elif isinstance(symbol, dict): sol = symbol else: msg = 'Expecting (sym, val) or ({sym: val}, None) but got (%s, %s)' raise ValueError(msg % (symbol, sol)) if iterable(f): if not f: raise ValueError('no functions to check') rv = True for fi in f: check = checksol(fi, sol, **flags) if check: continue if check is False: return False rv = None # don't return, wait to see if there's a False return rv if isinstance(f, Poly): f = f.as_expr() elif isinstance(f, (Equality, Unequality)): if f.rhs in (S.true, S.false): f = f.reversed B, E = f.args if isinstance(B, BooleanAtom): f = f.subs(sol) if not f.is_Boolean: return else: f = f.rewrite(Add, evaluate=False) if isinstance(f, BooleanAtom): return bool(f) elif not f.is_Relational and not f: return True if sol and not f.free_symbols & set(sol.keys()): # if f(y) == 0, x=3 does not set f(y) to zero...nor does it not return None illegal = {S.NaN, S.ComplexInfinity, S.Infinity, S.NegativeInfinity} if any(sympify(v).atoms() & illegal for k, v in sol.items()): return False was = f attempt = -1 numerical = flags.get('numerical', True) while 1: attempt += 1 if attempt == 0: val = f.subs(sol) if isinstance(val, Mul): val = val.as_independent(Unit)[0] if val.atoms() & illegal: return False elif attempt == 1: if not val.is_number: if not val.is_constant(*list(sol.keys()), simplify=not minimal): return False # there are free symbols -- simple expansion might work _, val = val.as_content_primitive() val = _mexpand(val.as_numer_denom()[0], recursive=True) elif attempt == 2: if minimal: return if flags.get('simplify', True): for k in sol: sol[k] = simplify(sol[k]) # start over without the failed expanded form, possibly # with a simplified solution val = simplify(f.subs(sol)) if flags.get('force', True): val, reps = posify(val) # expansion may work now, so try again and check exval = _mexpand(val, recursive=True) if exval.is_number: # we can decide now val = exval else: # if there are no radicals and no functions then this can't be # zero anymore -- can it? pot = preorder_traversal(expand_mul(val)) seen = set() saw_pow_func = False for p in pot: if p in seen: continue seen.add(p) if p.is_Pow and not p.exp.is_Integer: saw_pow_func = True elif p.is_Function: saw_pow_func = True elif isinstance(p, UndefinedFunction): saw_pow_func = True if saw_pow_func: break if saw_pow_func is False: return False if flags.get('force', True): # don't do a zero check with the positive assumptions in place val = val.subs(reps) nz = fuzzy_not(val.is_zero) if nz is not None: # issue 5673: nz may be True even when False # so these are just hacks to keep a false positive # from being returned # HACK 1: LambertW (issue 5673) if val.is_number and val.has(LambertW): # don't eval this to verify solution since if we got here, # numerical must be False return None # add other HACKs here if necessary, otherwise we assume # the nz value is correct return not nz break if val == was: continue elif val.is_Rational: return val == 0 if numerical and val.is_number: return (abs(val.n(18).n(12, chop=True)) < 1e-9) is S.true was = val if flags.get('warn', False): warnings.warn("\n\tWarning: could not verify solution %s." % sol) # returns None if it can't conclude # TODO: improve solution testing def solve(f, *symbols, **flags): r""" Algebraically solves equations and systems of equations. Explanation =========== Currently supported: - polynomial - transcendental - piecewise combinations of the above - systems of linear and polynomial equations - systems containing relational expressions Examples ======== The output varies according to the input and can be seen by example: >>> from sympy import solve, Poly, Eq, Function, exp >>> from sympy.abc import x, y, z, a, b >>> f = Function('f') Boolean or univariate Relational: >>> solve(x < 3) (-oo < x) & (x < 3) To always get a list of solution mappings, use flag dict=True: >>> solve(x - 3, dict=True) [{x: 3}] >>> sol = solve([x - 3, y - 1], dict=True) >>> sol [{x: 3, y: 1}] >>> sol[0][x] 3 >>> sol[0][y] 1 To get a list of *symbols* and set of solution(s) use flag set=True: >>> solve([x**2 - 3, y - 1], set=True) ([x, y], {(-sqrt(3), 1), (sqrt(3), 1)}) Single expression and single symbol that is in the expression: >>> solve(x - y, x) [y] >>> solve(x - 3, x) [3] >>> solve(Eq(x, 3), x) [3] >>> solve(Poly(x - 3), x) [3] >>> solve(x**2 - y**2, x, set=True) ([x], {(-y,), (y,)}) >>> solve(x**4 - 1, x, set=True) ([x], {(-1,), (1,), (-I,), (I,)}) Single expression with no symbol that is in the expression: >>> solve(3, x) [] >>> solve(x - 3, y) [] Single expression with no symbol given. In this case, all free *symbols* will be selected as potential *symbols* to solve for. If the equation is univariate then a list of solutions is returned; otherwise - as is the case when *symbols* are given as an iterable of length greater than 1 - a list of mappings will be returned: >>> solve(x - 3) [3] >>> solve(x**2 - y**2) [{x: -y}, {x: y}] >>> solve(z**2*x**2 - z**2*y**2) [{x: -y}, {x: y}, {z: 0}] >>> solve(z**2*x - z**2*y**2) [{x: y**2}, {z: 0}] When an object other than a Symbol is given as a symbol, it is isolated algebraically and an implicit solution may be obtained. This is mostly provided as a convenience to save you from replacing the object with a Symbol and solving for that Symbol. It will only work if the specified object can be replaced with a Symbol using the subs method: >>> solve(f(x) - x, f(x)) [x] >>> solve(f(x).diff(x) - f(x) - x, f(x).diff(x)) [x + f(x)] >>> solve(f(x).diff(x) - f(x) - x, f(x)) [-x + Derivative(f(x), x)] >>> solve(x + exp(x)**2, exp(x), set=True) ([exp(x)], {(-sqrt(-x),), (sqrt(-x),)}) >>> from sympy import Indexed, IndexedBase, Tuple, sqrt >>> A = IndexedBase('A') >>> eqs = Tuple(A[1] + A[2] - 3, A[1] - A[2] + 1) >>> solve(eqs, eqs.atoms(Indexed)) {A[1]: 1, A[2]: 2} * To solve for a symbol implicitly, use implicit=True: >>> solve(x + exp(x), x) [-LambertW(1)] >>> solve(x + exp(x), x, implicit=True) [-exp(x)] * It is possible to solve for anything that can be targeted with subs: >>> solve(x + 2 + sqrt(3), x + 2) [-sqrt(3)] >>> solve((x + 2 + sqrt(3), x + 4 + y), y, x + 2) {y: -2 + sqrt(3), x + 2: -sqrt(3)} * Nothing heroic is done in this implicit solving so you may end up with a symbol still in the solution: >>> eqs = (x*y + 3*y + sqrt(3), x + 4 + y) >>> solve(eqs, y, x + 2) {y: -sqrt(3)/(x + 3), x + 2: -2*x/(x + 3) - 6/(x + 3) + sqrt(3)/(x + 3)} >>> solve(eqs, y*x, x) {x: -y - 4, x*y: -3*y - sqrt(3)} * If you attempt to solve for a number remember that the number you have obtained does not necessarily mean that the value is equivalent to the expression obtained: >>> solve(sqrt(2) - 1, 1) [sqrt(2)] >>> solve(x - y + 1, 1) # /!\ -1 is targeted, too [x/(y - 1)] >>> [_.subs(z, -1) for _ in solve((x - y + 1).subs(-1, z), 1)] [-x + y] * To solve for a function within a derivative, use ``dsolve``. Single expression and more than one symbol: * When there is a linear solution: >>> solve(x - y**2, x, y) [(y**2, y)] >>> solve(x**2 - y, x, y) [(x, x**2)] >>> solve(x**2 - y, x, y, dict=True) [{y: x**2}] * When undetermined coefficients are identified: * That are linear: >>> solve((a + b)*x - b + 2, a, b) {a: -2, b: 2} * That are nonlinear: >>> solve((a + b)*x - b**2 + 2, a, b, set=True) ([a, b], {(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))}) * If there is no linear solution, then the first successful attempt for a nonlinear solution will be returned: >>> solve(x**2 - y**2, x, y, dict=True) [{x: -y}, {x: y}] >>> solve(x**2 - y**2/exp(x), x, y, dict=True) [{x: 2*LambertW(-y/2)}, {x: 2*LambertW(y/2)}] >>> solve(x**2 - y**2/exp(x), y, x) [(-x*sqrt(exp(x)), x), (x*sqrt(exp(x)), x)] Iterable of one or more of the above: * Involving relationals or bools: >>> solve([x < 3, x - 2]) Eq(x, 2) >>> solve([x > 3, x - 2]) False * When the system is linear: * With a solution: >>> solve([x - 3], x) {x: 3} >>> solve((x + 5*y - 2, -3*x + 6*y - 15), x, y) {x: -3, y: 1} >>> solve((x + 5*y - 2, -3*x + 6*y - 15), x, y, z) {x: -3, y: 1} >>> solve((x + 5*y - 2, -3*x + 6*y - z), z, x, y) {x: 2 - 5*y, z: 21*y - 6} * Without a solution: >>> solve([x + 3, x - 3]) [] * When the system is not linear: >>> solve([x**2 + y -2, y**2 - 4], x, y, set=True) ([x, y], {(-2, -2), (0, 2), (2, -2)}) * If no *symbols* are given, all free *symbols* will be selected and a list of mappings returned: >>> solve([x - 2, x**2 + y]) [{x: 2, y: -4}] >>> solve([x - 2, x**2 + f(x)], {f(x), x}) [{x: 2, f(x): -4}] * If any equation does not depend on the symbol(s) given, it will be eliminated from the equation set and an answer may be given implicitly in terms of variables that were not of interest: >>> solve([x - y, y - 3], x) {x: y} **Additional Examples** ``solve()`` with check=True (default) will run through the symbol tags to elimate unwanted solutions. If no assumptions are included, all possible solutions will be returned: >>> from sympy import Symbol, solve >>> x = Symbol("x") >>> solve(x**2 - 1) [-1, 1] By using the positive tag, only one solution will be returned: >>> pos = Symbol("pos", positive=True) >>> solve(pos**2 - 1) [1] Assumptions are not checked when ``solve()`` input involves relationals or bools. When the solutions are checked, those that make any denominator zero are automatically excluded. If you do not want to exclude such solutions, then use the check=False option: >>> from sympy import sin, limit >>> solve(sin(x)/x) # 0 is excluded [pi] If check=False, then a solution to the numerator being zero is found: x = 0. In this case, this is a spurious solution since $\sin(x)/x$ has the well known limit (without dicontinuity) of 1 at x = 0: >>> solve(sin(x)/x, check=False) [0, pi] In the following case, however, the limit exists and is equal to the value of x = 0 that is excluded when check=True: >>> eq = x**2*(1/x - z**2/x) >>> solve(eq, x) [] >>> solve(eq, x, check=False) [0] >>> limit(eq, x, 0, '-') 0 >>> limit(eq, x, 0, '+') 0 **Disabling High-Order Explicit Solutions** When solving polynomial expressions, you might not want explicit solutions (which can be quite long). If the expression is univariate, ``CRootOf`` instances will be returned instead: >>> solve(x**3 - x + 1) [-1/((-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)) - (-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3, -(-1/2 + sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3 - 1/((-1/2 + sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)), -(3*sqrt(69)/2 + 27/2)**(1/3)/3 - 1/(3*sqrt(69)/2 + 27/2)**(1/3)] >>> solve(x**3 - x + 1, cubics=False) [CRootOf(x**3 - x + 1, 0), CRootOf(x**3 - x + 1, 1), CRootOf(x**3 - x + 1, 2)] If the expression is multivariate, no solution might be returned: >>> solve(x**3 - x + a, x, cubics=False) [] Sometimes solutions will be obtained even when a flag is False because the expression could be factored. In the following example, the equation can be factored as the product of a linear and a quadratic factor so explicit solutions (which did not require solving a cubic expression) are obtained: >>> eq = x**3 + 3*x**2 + x - 1 >>> solve(eq, cubics=False) [-1, -1 + sqrt(2), -sqrt(2) - 1] **Solving Equations Involving Radicals** Because of SymPy's use of the principle root, some solutions to radical equations will be missed unless check=False: >>> from sympy import root >>> eq = root(x**3 - 3*x**2, 3) + 1 - x >>> solve(eq) [] >>> solve(eq, check=False) [1/3] In the above example, there is only a single solution to the equation. Other expressions will yield spurious roots which must be checked manually; roots which give a negative argument to odd-powered radicals will also need special checking: >>> from sympy import real_root, S >>> eq = root(x, 3) - root(x, 5) + S(1)/7 >>> solve(eq) # this gives 2 solutions but misses a 3rd [CRootOf(7*x**5 - 7*x**3 + 1, 1)**15, CRootOf(7*x**5 - 7*x**3 + 1, 2)**15] >>> sol = solve(eq, check=False) >>> [abs(eq.subs(x,i).n(2)) for i in sol] [0.48, 0.e-110, 0.e-110, 0.052, 0.052] The first solution is negative so ``real_root`` must be used to see that it satisfies the expression: >>> abs(real_root(eq.subs(x, sol[0])).n(2)) 0.e-110 If the roots of the equation are not real then more care will be necessary to find the roots, especially for higher order equations. Consider the following expression: >>> expr = root(x, 3) - root(x, 5) We will construct a known value for this expression at x = 3 by selecting the 1-th root for each radical: >>> expr1 = root(x, 3, 1) - root(x, 5, 1) >>> v = expr1.subs(x, -3) The ``solve`` function is unable to find any exact roots to this equation: >>> eq = Eq(expr, v); eq1 = Eq(expr1, v) >>> solve(eq, check=False), solve(eq1, check=False) ([], []) The function ``unrad``, however, can be used to get a form of the equation for which numerical roots can be found: >>> from sympy.solvers.solvers import unrad >>> from sympy import nroots >>> e, (p, cov) = unrad(eq) >>> pvals = nroots(e) >>> inversion = solve(cov, x)[0] >>> xvals = [inversion.subs(p, i) for i in pvals] Although ``eq`` or ``eq1`` could have been used to find ``xvals``, the solution can only be verified with ``expr1``: >>> z = expr - v >>> [xi.n(chop=1e-9) for xi in xvals if abs(z.subs(x, xi).n()) < 1e-9] [] >>> z1 = expr1 - v >>> [xi.n(chop=1e-9) for xi in xvals if abs(z1.subs(x, xi).n()) < 1e-9] [-3.0] Parameters ========== f : - a single Expr or Poly that must be zero - an Equality - a Relational expression - a Boolean - iterable of one or more of the above symbols : (object(s) to solve for) specified as - none given (other non-numeric objects will be used) - single symbol - denested list of symbols (e.g., ``solve(f, x, y)``) - ordered iterable of symbols (e.g., ``solve(f, [x, y])``) flags : dict=True (default is False) Return list (perhaps empty) of solution mappings. set=True (default is False) Return list of symbols and set of tuple(s) of solution(s). exclude=[] (default) Do not try to solve for any of the free symbols in exclude; if expressions are given, the free symbols in them will be extracted automatically. check=True (default) If False, do not do any testing of solutions. This can be useful if you want to include solutions that make any denominator zero. numerical=True (default) Do a fast numerical check if *f* has only one symbol. minimal=True (default is False) A very fast, minimal testing. warn=True (default is False) Show a warning if ``checksol()`` could not conclude. simplify=True (default) Simplify all but polynomials of order 3 or greater before returning them and (if check is not False) use the general simplify function on the solutions and the expression obtained when they are substituted into the function which should be zero. force=True (default is False) Make positive all symbols without assumptions regarding sign. rational=True (default) Recast Floats as Rational; if this option is not used, the system containing Floats may fail to solve because of issues with polys. If rational=None, Floats will be recast as rationals but the answer will be recast as Floats. If the flag is False then nothing will be done to the Floats. manual=True (default is False) Do not use the polys/matrix method to solve a system of equations, solve them one at a time as you might "manually." implicit=True (default is False) Allows ``solve`` to return a solution for a pattern in terms of other functions that contain that pattern; this is only needed if the pattern is inside of some invertible function like cos, exp, ect. particular=True (default is False) Instructs ``solve`` to try to find a particular solution to a linear system with as many zeros as possible; this is very expensive. quick=True (default is False) When using particular=True, use a fast heuristic to find a solution with many zeros (instead of using the very slow method guaranteed to find the largest number of zeros possible). cubics=True (default) Return explicit solutions when cubic expressions are encountered. quartics=True (default) Return explicit solutions when quartic expressions are encountered. quintics=True (default) Return explicit solutions (if possible) when quintic expressions are encountered. See Also ======== rsolve: For solving recurrence relationships dsolve: For solving differential equations """ # keeping track of how f was passed since if it is a list # a dictionary of results will be returned. ########################################################################### def _sympified_list(w): return list(map(sympify, w if iterable(w) else [w])) bare_f = not iterable(f) ordered_symbols = (symbols and symbols[0] and (isinstance(symbols[0], Symbol) or is_sequence(symbols[0], include=GeneratorType) ) ) f, symbols = (_sympified_list(w) for w in [f, symbols]) if isinstance(f, list): f = [s for s in f if s is not S.true and s is not True] implicit = flags.get('implicit', False) # preprocess symbol(s) ########################################################################### if not symbols: # get symbols from equations symbols = set().union(*[fi.free_symbols for fi in f]) if len(symbols) < len(f): for fi in f: pot = preorder_traversal(fi) for p in pot: if isinstance(p, AppliedUndef): flags['dict'] = True # better show symbols symbols.add(p) pot.skip() # don't go any deeper symbols = list(symbols) ordered_symbols = False elif len(symbols) == 1 and iterable(symbols[0]): symbols = symbols[0] # remove symbols the user is not interested in exclude = flags.pop('exclude', set()) if exclude: if isinstance(exclude, Expr): exclude = [exclude] exclude = set().union(*[e.free_symbols for e in sympify(exclude)]) symbols = [s for s in symbols if s not in exclude] # preprocess equation(s) ########################################################################### for i, fi in enumerate(f): if isinstance(fi, (Equality, Unequality)): if 'ImmutableDenseMatrix' in [type(a).__name__ for a in fi.args]: fi = fi.lhs - fi.rhs else: L, R = fi.args if isinstance(R, BooleanAtom): L, R = R, L if isinstance(L, BooleanAtom): if isinstance(fi, Unequality): L = ~L if R.is_Relational: fi = ~R if L is S.false else R elif R.is_Symbol: return L elif R.is_Boolean and (~R).is_Symbol: return ~L else: raise NotImplementedError(filldedent(''' Unanticipated argument of Eq when other arg is True or False. ''')) else: fi = fi.rewrite(Add, evaluate=False) f[i] = fi if fi.is_Relational: return reduce_inequalities(f, symbols=symbols) if isinstance(fi, Poly): f[i] = fi.as_expr() # rewrite hyperbolics in terms of exp f[i] = f[i].replace(lambda w: isinstance(w, HyperbolicFunction) and \ (len(w.free_symbols & set(symbols)) > 0), lambda w: w.rewrite(exp)) # if we have a Matrix, we need to iterate over its elements again if f[i].is_Matrix: bare_f = False f.extend(list(f[i])) f[i] = S.Zero # if we can split it into real and imaginary parts then do so freei = f[i].free_symbols if freei and all(s.is_extended_real or s.is_imaginary for s in freei): fr, fi = f[i].as_real_imag() # accept as long as new re, im, arg or atan2 are not introduced had = f[i].atoms(re, im, arg, atan2) if fr and fi and fr != fi and not any( i.atoms(re, im, arg, atan2) - had for i in (fr, fi)): if bare_f: bare_f = False f[i: i + 1] = [fr, fi] # real/imag handling ----------------------------- if any(isinstance(fi, (bool, BooleanAtom)) for fi in f): if flags.get('set', False): return [], set() return [] for i, fi in enumerate(f): # Abs while True: was = fi fi = fi.replace(Abs, lambda arg: separatevars(Abs(arg)).rewrite(Piecewise) if arg.has(*symbols) else Abs(arg)) if was == fi: break for e in fi.find(Abs): if e.has(*symbols): raise NotImplementedError('solving %s when the argument ' 'is not real or imaginary.' % e) # arg fi = fi.replace(arg, lambda a: arg(a).rewrite(atan2).rewrite(atan)) # save changes f[i] = fi # see if re(s) or im(s) appear freim = [fi for fi in f if fi.has(re, im)] if freim: irf = [] for s in symbols: if s.is_real or s.is_imaginary: continue # neither re(x) nor im(x) will appear # if re(s) or im(s) appear, the auxiliary equation must be present if any(fi.has(re(s), im(s)) for fi in freim): irf.append((s, re(s) + S.ImaginaryUnit*im(s))) if irf: for s, rhs in irf: for i, fi in enumerate(f): f[i] = fi.xreplace({s: rhs}) f.append(s - rhs) symbols.extend([re(s), im(s)]) if bare_f: bare_f = False flags['dict'] = True # end of real/imag handling ----------------------------- symbols = list(uniq(symbols)) if not ordered_symbols: # we do this to make the results returned canonical in case f # contains a system of nonlinear equations; all other cases should # be unambiguous symbols = sorted(symbols, key=default_sort_key) # we can solve for non-symbol entities by replacing them with Dummy symbols f, symbols, swap_sym = recast_to_symbols(f, symbols) # this is needed in the next two events symset = set(symbols) # get rid of equations that have no symbols of interest; we don't # try to solve them because the user didn't ask and they might be # hard to solve; this means that solutions may be given in terms # of the eliminated equations e.g. solve((x-y, y-3), x) -> {x: y} newf = [] for fi in f: # let the solver handle equations that.. # - have no symbols but are expressions # - have symbols of interest # - have no symbols of interest but are constant # but when an expression is not constant and has no symbols of # interest, it can't change what we obtain for a solution from # the remaining equations so we don't include it; and if it's # zero it can be removed and if it's not zero, there is no # solution for the equation set as a whole # # The reason for doing this filtering is to allow an answer # to be obtained to queries like solve((x - y, y), x); without # this mod the return value is [] ok = False if fi.free_symbols & symset: ok = True else: if fi.is_number: if fi.is_Number: if fi.is_zero: continue return [] ok = True else: if fi.is_constant(): ok = True if ok: newf.append(fi) if not newf: return [] f = newf del newf # mask off any Object that we aren't going to invert: Derivative, # Integral, etc... so that solving for anything that they contain will # give an implicit solution seen = set() non_inverts = set() for fi in f: pot = preorder_traversal(fi) for p in pot: if not isinstance(p, Expr) or isinstance(p, Piecewise): pass elif (isinstance(p, bool) or not p.args or p in symset or p.is_Add or p.is_Mul or p.is_Pow and not implicit or p.is_Function and not implicit) and p.func not in (re, im): continue elif not p in seen: seen.add(p) if p.free_symbols & symset: non_inverts.add(p) else: continue pot.skip() del seen non_inverts = dict(list(zip(non_inverts, [Dummy() for _ in non_inverts]))) f = [fi.subs(non_inverts) for fi in f] # Both xreplace and subs are needed below: xreplace to force substitution # inside Derivative, subs to handle non-straightforward substitutions non_inverts = [(v, k.xreplace(swap_sym).subs(swap_sym)) for k, v in non_inverts.items()] # rationalize Floats floats = False if flags.get('rational', True) is not False: for i, fi in enumerate(f): if fi.has(Float): floats = True f[i] = nsimplify(fi, rational=True) # capture any denominators before rewriting since # they may disappear after the rewrite, e.g. issue 14779 flags['_denominators'] = _simple_dens(f[0], symbols) # Any embedded piecewise functions need to be brought out to the # top level so that the appropriate strategy gets selected. # However, this is necessary only if one of the piecewise # functions depends on one of the symbols we are solving for. def _has_piecewise(e): if e.is_Piecewise: return e.has(*symbols) return any(_has_piecewise(a) for a in e.args) for i, fi in enumerate(f): if _has_piecewise(fi): f[i] = piecewise_fold(fi) # # try to get a solution ########################################################################### if bare_f: solution = _solve(f[0], *symbols, **flags) else: solution = _solve_system(f, symbols, **flags) # # postprocessing ########################################################################### # Restore masked-off objects if non_inverts: def _do_dict(solution): return {k: v.subs(non_inverts) for k, v in solution.items()} for i in range(1): if isinstance(solution, dict): solution = _do_dict(solution) break elif solution and isinstance(solution, list): if isinstance(solution[0], dict): solution = [_do_dict(s) for s in solution] break elif isinstance(solution[0], tuple): solution = [tuple([v.subs(non_inverts) for v in s]) for s in solution] break else: solution = [v.subs(non_inverts) for v in solution] break elif not solution: break else: raise NotImplementedError(filldedent(''' no handling of %s was implemented''' % solution)) # Restore original "symbols" if a dictionary is returned. # This is not necessary for # - the single univariate equation case # since the symbol will have been removed from the solution; # - the nonlinear poly_system since that only supports zero-dimensional # systems and those results come back as a list # # ** unless there were Derivatives with the symbols, but those were handled # above. if swap_sym: symbols = [swap_sym.get(k, k) for k in symbols] if isinstance(solution, dict): solution = {swap_sym.get(k, k): v.subs(swap_sym) for k, v in solution.items()} elif solution and isinstance(solution, list) and isinstance(solution[0], dict): for i, sol in enumerate(solution): solution[i] = {swap_sym.get(k, k): v.subs(swap_sym) for k, v in sol.items()} # undo the dictionary solutions returned when the system was only partially # solved with poly-system if all symbols are present if ( not flags.get('dict', False) and solution and ordered_symbols and not isinstance(solution, dict) and all(isinstance(sol, dict) for sol in solution) ): solution = [tuple([r.get(s, s) for s in symbols]) for r in solution] # Get assumptions about symbols, to filter solutions. # Note that if assumptions about a solution can't be verified, it is still # returned. check = flags.get('check', True) # restore floats if floats and solution and flags.get('rational', None) is None: solution = nfloat(solution, exponent=False) if check and solution: # assumption checking warn = flags.get('warn', False) got_None = [] # solutions for which one or more symbols gave None no_False = [] # solutions for which no symbols gave False if isinstance(solution, tuple): # this has already been checked and is in as_set form return solution elif isinstance(solution, list): if isinstance(solution[0], tuple): for sol in solution: for symb, val in zip(symbols, sol): test = check_assumptions(val, **symb.assumptions0) if test is False: break if test is None: got_None.append(sol) else: no_False.append(sol) elif isinstance(solution[0], dict): for sol in solution: a_None = False for symb, val in sol.items(): test = check_assumptions(val, **symb.assumptions0) if test: continue if test is False: break a_None = True else: no_False.append(sol) if a_None: got_None.append(sol) else: # list of expressions for sol in solution: test = check_assumptions(sol, **symbols[0].assumptions0) if test is False: continue no_False.append(sol) if test is None: got_None.append(sol) elif isinstance(solution, dict): a_None = False for symb, val in solution.items(): test = check_assumptions(val, **symb.assumptions0) if test: continue if test is False: no_False = None break a_None = True else: no_False = solution if a_None: got_None.append(solution) elif isinstance(solution, (Relational, And, Or)): if len(symbols) != 1: raise ValueError("Length should be 1") if warn and symbols[0].assumptions0: warnings.warn(filldedent(""" \tWarning: assumptions about variable '%s' are not handled currently.""" % symbols[0])) # TODO: check also variable assumptions for inequalities else: raise TypeError('Unrecognized solution') # improve the checker solution = no_False if warn and got_None: warnings.warn(filldedent(""" \tWarning: assumptions concerning following solution(s) can't be checked:""" + '\n\t' + ', '.join(str(s) for s in got_None))) # # done ########################################################################### as_dict = flags.get('dict', False) as_set = flags.get('set', False) if not as_set and isinstance(solution, list): # Make sure that a list of solutions is ordered in a canonical way. solution.sort(key=default_sort_key) if not as_dict and not as_set: return solution or [] # return a list of mappings or [] if not solution: solution = [] else: if isinstance(solution, dict): solution = [solution] elif iterable(solution[0]): solution = [dict(list(zip(symbols, s))) for s in solution] elif isinstance(solution[0], dict): pass else: if len(symbols) != 1: raise ValueError("Length should be 1") solution = [{symbols[0]: s} for s in solution] if as_dict: return solution assert as_set if not solution: return [], set() k = list(ordered(solution[0].keys())) return k, {tuple([s[ki] for ki in k]) for s in solution} def _solve(f, *symbols, **flags): """ Return a checked solution for *f* in terms of one or more of the symbols. A list should be returned except for the case when a linear undetermined-coefficients equation is encountered (in which case a dictionary is returned). If no method is implemented to solve the equation, a NotImplementedError will be raised. In the case that conversion of an expression to a Poly gives None a ValueError will be raised. """ not_impl_msg = "No algorithms are implemented to solve equation %s" if len(symbols) != 1: soln = None free = f.free_symbols ex = free - set(symbols) if len(ex) != 1: ind, dep = f.as_independent(*symbols) ex = ind.free_symbols & dep.free_symbols if len(ex) == 1: ex = ex.pop() try: # soln may come back as dict, list of dicts or tuples, or # tuple of symbol list and set of solution tuples soln = solve_undetermined_coeffs(f, symbols, ex, **flags) except NotImplementedError: pass if soln: if flags.get('simplify', True): if isinstance(soln, dict): for k in soln: soln[k] = simplify(soln[k]) elif isinstance(soln, list): if isinstance(soln[0], dict): for d in soln: for k in d: d[k] = simplify(d[k]) elif isinstance(soln[0], tuple): soln = [tuple(simplify(i) for i in j) for j in soln] else: raise TypeError('unrecognized args in list') elif isinstance(soln, tuple): sym, sols = soln soln = sym, {tuple(simplify(i) for i in j) for j in sols} else: raise TypeError('unrecognized solution type') return soln # find first successful solution failed = [] got_s = set() result = [] for s in symbols: xi, v = solve_linear(f, symbols=[s]) if xi == s: # no need to check but we should simplify if desired if flags.get('simplify', True): v = simplify(v) vfree = v.free_symbols if got_s and any(ss in vfree for ss in got_s): # sol depends on previously solved symbols: discard it continue got_s.add(xi) result.append({xi: v}) elif xi: # there might be a non-linear solution if xi is not 0 failed.append(s) if not failed: return result for s in failed: try: soln = _solve(f, s, **flags) for sol in soln: if got_s and any(ss in sol.free_symbols for ss in got_s): # sol depends on previously solved symbols: discard it continue got_s.add(s) result.append({s: sol}) except NotImplementedError: continue if got_s: return result else: raise NotImplementedError(not_impl_msg % f) symbol = symbols[0] #expand binomials only if it has the unknown symbol f = f.replace(lambda e: isinstance(e, binomial) and e.has(symbol), lambda e: expand_func(e)) # /!\ capture this flag then set it to False so that no checking in # recursive calls will be done; only the final answer is checked flags['check'] = checkdens = check = flags.pop('check', True) # build up solutions if f is a Mul if f.is_Mul: result = set() for m in f.args: if m in {S.NegativeInfinity, S.ComplexInfinity, S.Infinity}: result = set() break soln = _solve(m, symbol, **flags) result.update(set(soln)) result = list(result) if check: # all solutions have been checked but now we must # check that the solutions do not set denominators # in any factor to zero dens = flags.get('_denominators', _simple_dens(f, symbols)) result = [s for s in result if not any(checksol(den, {symbol: s}, **flags) for den in dens)] # set flags for quick exit at end; solutions for each # factor were already checked and simplified check = False flags['simplify'] = False elif f.is_Piecewise: result = set() for i, (expr, cond) in enumerate(f.args): if expr.is_zero: raise NotImplementedError( 'solve cannot represent interval solutions') candidates = _solve(expr, symbol, **flags) # the explicit condition for this expr is the current cond # and none of the previous conditions args = [~c for _, c in f.args[:i]] + [cond] cond = And(*args) for candidate in candidates: if candidate in result: # an unconditional value was already there continue try: v = cond.subs(symbol, candidate) _eval_simplify = getattr(v, '_eval_simplify', None) if _eval_simplify is not None: # unconditionally take the simpification of v v = _eval_simplify(ratio=2, measure=lambda x: 1) except TypeError: # incompatible type with condition(s) continue if v == False: continue if v == True: result.add(candidate) else: result.add(Piecewise( (candidate, v), (S.NaN, True))) # set flags for quick exit at end; solutions for each # piece were already checked and simplified check = False flags['simplify'] = False else: # first see if it really depends on symbol and whether there # is only a linear solution f_num, sol = solve_linear(f, symbols=symbols) if f_num.is_zero or sol is S.NaN: return [] elif f_num.is_Symbol: # no need to check but simplify if desired if flags.get('simplify', True): sol = simplify(sol) return [sol] poly = None # check for a single non-symbol generator dums = f_num.atoms(Dummy) D = f_num.replace( lambda i: isinstance(i, Add) and symbol in i.free_symbols, lambda i: Dummy()) if not D.is_Dummy: dgen = D.atoms(Dummy) - dums if len(dgen) == 1: d = dgen.pop() w = Wild('g') gen = f_num.match(D.xreplace({d: w}))[w] spart = gen.as_independent(symbol)[1].as_base_exp()[0] if spart == symbol: try: poly = Poly(f_num, spart) except PolynomialError: pass result = False # no solution was obtained msg = '' # there is no failure message # Poly is generally robust enough to convert anything to # a polynomial and tell us the different generators that it # contains, so we will inspect the generators identified by # polys to figure out what to do. # try to identify a single generator that will allow us to solve this # as a polynomial, followed (perhaps) by a change of variables if the # generator is not a symbol try: if poly is None: poly = Poly(f_num) if poly is None: raise ValueError('could not convert %s to Poly' % f_num) except GeneratorsNeeded: simplified_f = simplify(f_num) if simplified_f != f_num: return _solve(simplified_f, symbol, **flags) raise ValueError('expression appears to be a constant') gens = [g for g in poly.gens if g.has(symbol)] def _as_base_q(x): """Return (b**e, q) for x = b**(p*e/q) where p/q is the leading Rational of the exponent of x, e.g. exp(-2*x/3) -> (exp(x), 3) """ b, e = x.as_base_exp() if e.is_Rational: return b, e.q if not e.is_Mul: return x, 1 c, ee = e.as_coeff_Mul() if c.is_Rational and c is not S.One: # c could be a Float return b**ee, c.q return x, 1 if len(gens) > 1: # If there is more than one generator, it could be that the # generators have the same base but different powers, e.g. # >>> Poly(exp(x) + 1/exp(x)) # Poly(exp(-x) + exp(x), exp(-x), exp(x), domain='ZZ') # # If unrad was not disabled then there should be no rational # exponents appearing as in # >>> Poly(sqrt(x) + sqrt(sqrt(x))) # Poly(sqrt(x) + x**(1/4), sqrt(x), x**(1/4), domain='ZZ') bases, qs = list(zip(*[_as_base_q(g) for g in gens])) bases = set(bases) if len(bases) > 1 or not all(q == 1 for q in qs): funcs = {b for b in bases if b.is_Function} trig = {_ for _ in funcs if isinstance(_, TrigonometricFunction)} other = funcs - trig if not other and len(funcs.intersection(trig)) > 1: newf = None if f_num.is_Add and len(f_num.args) == 2: # check for sin(x)**p = cos(x)**p _args = f_num.args t = a, b = [i.atoms(Function).intersection( trig) for i in _args] if all(len(i) == 1 for i in t): a, b = [i.pop() for i in t] if isinstance(a, cos): a, b = b, a _args = _args[::-1] if isinstance(a, sin) and isinstance(b, cos ) and a.args[0] == b.args[0]: # sin(x) + cos(x) = 0 -> tan(x) + 1 = 0 newf, _d = (TR2i(_args[0]/_args[1]) + 1 ).as_numer_denom() if not _d.is_Number: newf = None if newf is None: newf = TR1(f_num).rewrite(tan) if newf != f_num: # don't check the rewritten form --check # solutions in the un-rewritten form below flags['check'] = False result = _solve(newf, symbol, **flags) flags['check'] = check # just a simple case - see if replacement of single function # clears all symbol-dependent functions, e.g. # log(x) - log(log(x) - 1) - 3 can be solved even though it has # two generators. if result is False and funcs: funcs = list(ordered(funcs)) # put shallowest function first f1 = funcs[0] t = Dummy('t') # perform the substitution ftry = f_num.subs(f1, t) # if no Functions left, we can proceed with usual solve if not ftry.has(symbol): cv_sols = _solve(ftry, t, **flags) cv_inv = _solve(t - f1, symbol, **flags)[0] sols = list() for sol in cv_sols: sols.append(cv_inv.subs(t, sol)) result = list(ordered(sols)) if result is False: msg = 'multiple generators %s' % gens else: # e.g. case where gens are exp(x), exp(-x) u = bases.pop() t = Dummy('t') inv = _solve(u - t, symbol, **flags) if isinstance(u, (Pow, exp)): # this will be resolved by factor in _tsolve but we might # as well try a simple expansion here to get things in # order so something like the following will work now without # having to factor: # # >>> eq = (exp(I*(-x-2))+exp(I*(x+2))) # >>> eq.subs(exp(x),y) # fails # exp(I*(-x - 2)) + exp(I*(x + 2)) # >>> eq.expand().subs(exp(x),y) # works # y**I*exp(2*I) + y**(-I)*exp(-2*I) def _expand(p): b, e = p.as_base_exp() e = expand_mul(e) return expand_power_exp(b**e) ftry = f_num.replace( lambda w: w.is_Pow or isinstance(w, exp), _expand).subs(u, t) if not ftry.has(symbol): soln = _solve(ftry, t, **flags) sols = list() for sol in soln: for i in inv: sols.append(i.subs(t, sol)) result = list(ordered(sols)) elif len(gens) == 1: # There is only one generator that we are interested in, but # there may have been more than one generator identified by # polys (e.g. for symbols other than the one we are interested # in) so recast the poly in terms of our generator of interest. # Also use composite=True with f_num since Poly won't update # poly as documented in issue 8810. poly = Poly(f_num, gens[0], composite=True) # if we aren't on the tsolve-pass, use roots if not flags.pop('tsolve', False): soln = None deg = poly.degree() flags['tsolve'] = True solvers = {k: flags.get(k, True) for k in ('cubics', 'quartics', 'quintics')} soln = roots(poly, **solvers) if sum(soln.values()) < deg: # e.g. roots(32*x**5 + 400*x**4 + 2032*x**3 + # 5000*x**2 + 6250*x + 3189) -> {} # so all_roots is used and RootOf instances are # returned *unless* the system is multivariate # or high-order EX domain. try: soln = poly.all_roots() except NotImplementedError: if not flags.get('incomplete', True): raise NotImplementedError( filldedent(''' Neither high-order multivariate polynomials nor sorting of EX-domain polynomials is supported. If you want to see any results, pass keyword incomplete=True to solve; to see numerical values of roots for univariate expressions, use nroots. ''')) else: pass else: soln = list(soln.keys()) if soln is not None: u = poly.gen if u != symbol: try: t = Dummy('t') iv = _solve(u - t, symbol, **flags) soln = list(ordered({i.subs(t, s) for i in iv for s in soln})) except NotImplementedError: # perhaps _tsolve can handle f_num soln = None else: check = False # only dens need to be checked if soln is not None: if len(soln) > 2: # if the flag wasn't set then unset it since high-order # results are quite long. Perhaps one could base this # decision on a certain critical length of the # roots. In addition, wester test M2 has an expression # whose roots can be shown to be real with the # unsimplified form of the solution whereas only one of # the simplified forms appears to be real. flags['simplify'] = flags.get('simplify', False) result = soln # fallback if above fails # ----------------------- if result is False: # try unrad if flags.pop('_unrad', True): try: u = unrad(f_num, symbol) except (ValueError, NotImplementedError): u = False if u: eq, cov = u if cov: isym, ieq = cov inv = _solve(ieq, symbol, **flags)[0] rv = {inv.subs(isym, xi) for xi in _solve(eq, isym, **flags)} else: try: rv = set(_solve(eq, symbol, **flags)) except NotImplementedError: rv = None if rv is not None: result = list(ordered(rv)) # if the flag wasn't set then unset it since unrad results # can be quite long or of very high order flags['simplify'] = flags.get('simplify', False) else: pass # for coverage # try _tsolve if result is False: flags.pop('tsolve', None) # allow tsolve to be used on next pass try: soln = _tsolve(f_num, symbol, **flags) if soln is not None: result = soln except PolynomialError: pass # ----------- end of fallback ---------------------------- if result is False: raise NotImplementedError('\n'.join([msg, not_impl_msg % f])) if flags.get('simplify', True): result = list(map(simplify, result)) # we just simplified the solution so we now set the flag to # False so the simplification doesn't happen again in checksol() flags['simplify'] = False if checkdens: # reject any result that makes any denom. affirmatively 0; # if in doubt, keep it dens = _simple_dens(f, symbols) result = [s for s in result if not any(checksol(d, {symbol: s}, **flags) for d in dens)] if check: # keep only results if the check is not False result = [r for r in result if checksol(f_num, {symbol: r}, **flags) is not False] return result def _solve_system(exprs, symbols, **flags): if not exprs: return [] if flags.pop('_split', True): # Split the system into connected components V = exprs symsset = set(symbols) exprsyms = {e: e.free_symbols & symsset for e in exprs} E = [] sym_indices = {sym: i for i, sym in enumerate(symbols)} for n, e1 in enumerate(exprs): for e2 in exprs[:n]: # Equations are connected if they share a symbol if exprsyms[e1] & exprsyms[e2]: E.append((e1, e2)) G = V, E subexprs = connected_components(G) if len(subexprs) > 1: subsols = [] for subexpr in subexprs: subsyms = set() for e in subexpr: subsyms |= exprsyms[e] subsyms = list(sorted(subsyms, key = lambda x: sym_indices[x])) flags['_split'] = False # skip split step subsol = _solve_system(subexpr, subsyms, **flags) if not isinstance(subsol, list): subsol = [subsol] subsols.append(subsol) # Full solution is cartesion product of subsystems sols = [] for soldicts in product(*subsols): sols.append(dict(item for sd in soldicts for item in sd.items())) # Return a list with one dict as just the dict if len(sols) == 1: return sols[0] return sols polys = [] dens = set() failed = [] result = False linear = False manual = flags.get('manual', False) checkdens = check = flags.get('check', True) for j, g in enumerate(exprs): dens.update(_simple_dens(g, symbols)) i, d = _invert(g, *symbols) g = d - i g = g.as_numer_denom()[0] if manual: failed.append(g) continue poly = g.as_poly(*symbols, extension=True) if poly is not None: polys.append(poly) else: failed.append(g) if not polys: solved_syms = [] else: if all(p.is_linear for p in polys): n, m = len(polys), len(symbols) matrix = zeros(n, m + 1) for i, poly in enumerate(polys): for monom, coeff in poly.terms(): try: j = monom.index(1) matrix[i, j] = coeff except ValueError: matrix[i, m] = -coeff # returns a dictionary ({symbols: values}) or None if flags.pop('particular', False): result = minsolve_linear_system(matrix, *symbols, **flags) else: result = solve_linear_system(matrix, *symbols, **flags) if failed: if result: solved_syms = list(result.keys()) else: solved_syms = [] else: linear = True else: if len(symbols) > len(polys): from sympy.utilities.iterables import subsets free = set().union(*[p.free_symbols for p in polys]) free = list(ordered(free.intersection(symbols))) got_s = set() result = [] for syms in subsets(free, len(polys)): try: # returns [] or list of tuples of solutions for syms res = solve_poly_system(polys, *syms) if res: for r in res: skip = False for r1 in r: if got_s and any(ss in r1.free_symbols for ss in got_s): # sol depends on previously # solved symbols: discard it skip = True if not skip: got_s.update(syms) result.extend([dict(list(zip(syms, r)))]) except NotImplementedError: pass if got_s: solved_syms = list(got_s) else: raise NotImplementedError('no valid subset found') else: try: result = solve_poly_system(polys, *symbols) if result: solved_syms = symbols # we don't know here if the symbols provided # were given or not, so let solve resolve that. # A list of dictionaries is going to always be # returned from here. result = [dict(list(zip(solved_syms, r))) for r in result] except NotImplementedError: failed.extend([g.as_expr() for g in polys]) solved_syms = [] result = None if result: if isinstance(result, dict): result = [result] else: result = [{}] if failed: # For each failed equation, see if we can solve for one of the # remaining symbols from that equation. If so, we update the # solution set and continue with the next failed equation, # repeating until we are done or we get an equation that can't # be solved. def _ok_syms(e, sort=False): rv = (e.free_symbols - solved_syms) & legal # Solve first for symbols that have lower degree in the equation. # Ideally we want to solve firstly for symbols that appear linearly # with rational coefficients e.g. if e = x*y + z then we should # solve for z first. def key(sym): ep = e.as_poly(sym) if ep is None: complexity = (S.Infinity, S.Infinity, S.Infinity) else: coeff_syms = ep.LC().free_symbols complexity = (ep.degree(), len(coeff_syms & rv), len(coeff_syms)) return complexity + (default_sort_key(sym),) if sort: rv = sorted(rv, key=key) return rv solved_syms = set(solved_syms) # set of symbols we have solved for legal = set(symbols) # what we are interested in # sort so equation with the fewest potential symbols is first u = Dummy() # used in solution checking for eq in ordered(failed, lambda _: len(_ok_syms(_))): newresult = [] bad_results = [] got_s = set() hit = False for r in result: # update eq with everything that is known so far eq2 = eq.subs(r) # if check is True then we see if it satisfies this # equation, otherwise we just accept it if check and r: b = checksol(u, u, eq2, minimal=True) if b is not None: # this solution is sufficient to know whether # it is valid or not so we either accept or # reject it, then continue if b: newresult.append(r) else: bad_results.append(r) continue # search for a symbol amongst those available that # can be solved for ok_syms = _ok_syms(eq2, sort=True) if not ok_syms: if r: newresult.append(r) break # skip as it's independent of desired symbols for s in ok_syms: try: soln = _solve(eq2, s, **flags) except NotImplementedError: continue # put each solution in r and append the now-expanded # result in the new result list; use copy since the # solution for s in being added in-place for sol in soln: if got_s and any(ss in sol.free_symbols for ss in got_s): # sol depends on previously solved symbols: discard it continue rnew = r.copy() for k, v in r.items(): rnew[k] = v.subs(s, sol) # and add this new solution rnew[s] = sol # check that it is independent of previous solutions iset = set(rnew.items()) for i in newresult: if len(i) < len(iset) and not set(i.items()) - iset: # this is a superset of a known solution that # is smaller break else: # keep it newresult.append(rnew) hit = True got_s.add(s) if not hit: raise NotImplementedError('could not solve %s' % eq2) else: result = newresult for b in bad_results: if b in result: result.remove(b) default_simplify = bool(failed) # rely on system-solvers to simplify if flags.get('simplify', default_simplify): for r in result: for k in r: r[k] = simplify(r[k]) flags['simplify'] = False # don't need to do so in checksol now if checkdens: result = [r for r in result if not any(checksol(d, r, **flags) for d in dens)] if check and not linear: result = [r for r in result if not any(checksol(e, r, **flags) is False for e in exprs)] result = [r for r in result if r] if linear and result: result = result[0] return result def solve_linear(lhs, rhs=0, symbols=[], exclude=[]): r""" Return a tuple derived from ``f = lhs - rhs`` that is one of the following: ``(0, 1)``, ``(0, 0)``, ``(symbol, solution)``, ``(n, d)``. Explanation =========== ``(0, 1)`` meaning that ``f`` is independent of the symbols in *symbols* that are not in *exclude*. ``(0, 0)`` meaning that there is no solution to the equation amongst the symbols given. If the first element of the tuple is not zero, then the function is guaranteed to be dependent on a symbol in *symbols*. ``(symbol, solution)`` where symbol appears linearly in the numerator of ``f``, is in *symbols* (if given), and is not in *exclude* (if given). No simplification is done to ``f`` other than a ``mul=True`` expansion, so the solution will correspond strictly to a unique solution. ``(n, d)`` where ``n`` and ``d`` are the numerator and denominator of ``f`` when the numerator was not linear in any symbol of interest; ``n`` will never be a symbol unless a solution for that symbol was found (in which case the second element is the solution, not the denominator). Examples ======== >>> from sympy.core.power import Pow >>> from sympy.polys.polytools import cancel ``f`` is independent of the symbols in *symbols* that are not in *exclude*: >>> from sympy.solvers.solvers import solve_linear >>> from sympy.abc import x, y, z >>> from sympy import cos, sin >>> eq = y*cos(x)**2 + y*sin(x)**2 - y # = y*(1 - 1) = 0 >>> solve_linear(eq) (0, 1) >>> eq = cos(x)**2 + sin(x)**2 # = 1 >>> solve_linear(eq) (0, 1) >>> solve_linear(x, exclude=[x]) (0, 1) The variable ``x`` appears as a linear variable in each of the following: >>> solve_linear(x + y**2) (x, -y**2) >>> solve_linear(1/x - y**2) (x, y**(-2)) When not linear in ``x`` or ``y`` then the numerator and denominator are returned: >>> solve_linear(x**2/y**2 - 3) (x**2 - 3*y**2, y**2) If the numerator of the expression is a symbol, then ``(0, 0)`` is returned if the solution for that symbol would have set any denominator to 0: >>> eq = 1/(1/x - 2) >>> eq.as_numer_denom() (x, 1 - 2*x) >>> solve_linear(eq) (0, 0) But automatic rewriting may cause a symbol in the denominator to appear in the numerator so a solution will be returned: >>> (1/x)**-1 x >>> solve_linear((1/x)**-1) (x, 0) Use an unevaluated expression to avoid this: >>> solve_linear(Pow(1/x, -1, evaluate=False)) (0, 0) If ``x`` is allowed to cancel in the following expression, then it appears to be linear in ``x``, but this sort of cancellation is not done by ``solve_linear`` so the solution will always satisfy the original expression without causing a division by zero error. >>> eq = x**2*(1/x - z**2/x) >>> solve_linear(cancel(eq)) (x, 0) >>> solve_linear(eq) (x**2*(1 - z**2), x) A list of symbols for which a solution is desired may be given: >>> solve_linear(x + y + z, symbols=[y]) (y, -x - z) A list of symbols to ignore may also be given: >>> solve_linear(x + y + z, exclude=[x]) (y, -x - z) (A solution for ``y`` is obtained because it is the first variable from the canonically sorted list of symbols that had a linear solution.) """ if isinstance(lhs, Equality): if rhs: raise ValueError(filldedent(''' If lhs is an Equality, rhs must be 0 but was %s''' % rhs)) rhs = lhs.rhs lhs = lhs.lhs dens = None eq = lhs - rhs n, d = eq.as_numer_denom() if not n: return S.Zero, S.One free = n.free_symbols if not symbols: symbols = free else: bad = [s for s in symbols if not s.is_Symbol] if bad: if len(bad) == 1: bad = bad[0] if len(symbols) == 1: eg = 'solve(%s, %s)' % (eq, symbols[0]) else: eg = 'solve(%s, *%s)' % (eq, list(symbols)) raise ValueError(filldedent(''' solve_linear only handles symbols, not %s. To isolate non-symbols use solve, e.g. >>> %s <<<. ''' % (bad, eg))) symbols = free.intersection(symbols) symbols = symbols.difference(exclude) if not symbols: return S.Zero, S.One # derivatives are easy to do but tricky to analyze to see if they # are going to disallow a linear solution, so for simplicity we # just evaluate the ones that have the symbols of interest derivs = defaultdict(list) for der in n.atoms(Derivative): csym = der.free_symbols & symbols for c in csym: derivs[c].append(der) all_zero = True for xi in sorted(symbols, key=default_sort_key): # canonical order # if there are derivatives in this var, calculate them now if isinstance(derivs[xi], list): derivs[xi] = {der: der.doit() for der in derivs[xi]} newn = n.subs(derivs[xi]) dnewn_dxi = newn.diff(xi) # dnewn_dxi can be nonzero if it survives differentation by any # of its free symbols free = dnewn_dxi.free_symbols if dnewn_dxi and (not free or any(dnewn_dxi.diff(s) for s in free) or free == symbols): all_zero = False if dnewn_dxi is S.NaN: break if xi not in dnewn_dxi.free_symbols: vi = -1/dnewn_dxi*(newn.subs(xi, 0)) if dens is None: dens = _simple_dens(eq, symbols) if not any(checksol(di, {xi: vi}, minimal=True) is True for di in dens): # simplify any trivial integral irep = [(i, i.doit()) for i in vi.atoms(Integral) if i.function.is_number] # do a slight bit of simplification vi = expand_mul(vi.subs(irep)) return xi, vi if all_zero: return S.Zero, S.One if n.is_Symbol: # no solution for this symbol was found return S.Zero, S.Zero return n, d def minsolve_linear_system(system, *symbols, **flags): r""" Find a particular solution to a linear system. Explanation =========== In particular, try to find a solution with the minimal possible number of non-zero variables using a naive algorithm with exponential complexity. If ``quick=True``, a heuristic is used. """ quick = flags.get('quick', False) # Check if there are any non-zero solutions at all s0 = solve_linear_system(system, *symbols, **flags) if not s0 or all(v == 0 for v in s0.values()): return s0 if quick: # We just solve the system and try to heuristically find a nice # solution. s = solve_linear_system(system, *symbols) def update(determined, solution): delete = [] for k, v in solution.items(): solution[k] = v.subs(determined) if not solution[k].free_symbols: delete.append(k) determined[k] = solution[k] for k in delete: del solution[k] determined = {} update(determined, s) while s: # NOTE sort by default_sort_key to get deterministic result k = max((k for k in s.values()), key=lambda x: (len(x.free_symbols), default_sort_key(x))) x = max(k.free_symbols, key=default_sort_key) if len(k.free_symbols) != 1: determined[x] = S.Zero else: val = solve(k)[0] if val == 0 and all(v.subs(x, val) == 0 for v in s.values()): determined[x] = S.One else: determined[x] = val update(determined, s) return determined else: # We try to select n variables which we want to be non-zero. # All others will be assumed zero. We try to solve the modified system. # If there is a non-trivial solution, just set the free variables to # one. If we do this for increasing n, trying all combinations of # variables, we will find an optimal solution. # We speed up slightly by starting at one less than the number of # variables the quick method manages. from itertools import combinations from sympy.utilities.misc import debug N = len(symbols) bestsol = minsolve_linear_system(system, *symbols, quick=True) n0 = len([x for x in bestsol.values() if x != 0]) for n in range(n0 - 1, 1, -1): debug('minsolve: %s' % n) thissol = None for nonzeros in combinations(list(range(N)), n): subm = Matrix([system.col(i).T for i in nonzeros] + [system.col(-1).T]).T s = solve_linear_system(subm, *[symbols[i] for i in nonzeros]) if s and not all(v == 0 for v in s.values()): subs = [(symbols[v], S.One) for v in nonzeros] for k, v in s.items(): s[k] = v.subs(subs) for sym in symbols: if sym not in s: if symbols.index(sym) in nonzeros: s[sym] = S.One else: s[sym] = S.Zero thissol = s break if thissol is None: break bestsol = thissol return bestsol def solve_linear_system(system, *symbols, **flags): r""" Solve system of $N$ linear equations with $M$ variables, which means both under- and overdetermined systems are supported. Explanation =========== The possible number of solutions is zero, one, or infinite. Respectively, this procedure will return None or a dictionary with solutions. In the case of underdetermined systems, all arbitrary parameters are skipped. This may cause a situation in which an empty dictionary is returned. In that case, all symbols can be assigned arbitrary values. Input to this function is a $N\times M + 1$ matrix, which means it has to be in augmented form. If you prefer to enter $N$ equations and $M$ unknowns then use ``solve(Neqs, *Msymbols)`` instead. Note: a local copy of the matrix is made by this routine so the matrix that is passed will not be modified. The algorithm used here is fraction-free Gaussian elimination, which results, after elimination, in an upper-triangular matrix. Then solutions are found using back-substitution. This approach is more efficient and compact than the Gauss-Jordan method. Examples ======== >>> from sympy import Matrix, solve_linear_system >>> from sympy.abc import x, y Solve the following system:: x + 4 y == 2 -2 x + y == 14 >>> system = Matrix(( (1, 4, 2), (-2, 1, 14))) >>> solve_linear_system(system, x, y) {x: -6, y: 2} A degenerate system returns an empty dictionary: >>> system = Matrix(( (0,0,0), (0,0,0) )) >>> solve_linear_system(system, x, y) {} """ assert system.shape[1] == len(symbols) + 1 # This is just a wrapper for solve_lin_sys eqs = list(system * Matrix(symbols + (-1,))) eqs, ring = sympy_eqs_to_ring(eqs, symbols) sol = solve_lin_sys(eqs, ring, _raw=False) if sol is not None: sol = {sym:val for sym, val in sol.items() if sym != val} return sol def solve_undetermined_coeffs(equ, coeffs, sym, **flags): r""" Solve equation of a type $p(x; a_1, \ldots, a_k) = q(x)$ where both $p$ and $q$ are univariate polynomials that depend on $k$ parameters. Explanation =========== The result of this function is a dictionary with symbolic values of those parameters with respect to coefficients in $q$. This function accepts both equations class instances and ordinary SymPy expressions. Specification of parameters and variables is obligatory for efficiency and simplicity reasons. Examples ======== >>> from sympy import Eq >>> from sympy.abc import a, b, c, x >>> from sympy.solvers import solve_undetermined_coeffs >>> solve_undetermined_coeffs(Eq(2*a*x + a+b, x), [a, b], x) {a: 1/2, b: -1/2} >>> solve_undetermined_coeffs(Eq(a*c*x + a+b, x), [a, b], x) {a: 1/c, b: -1/c} """ if isinstance(equ, Equality): # got equation, so move all the # terms to the left hand side equ = equ.lhs - equ.rhs equ = cancel(equ).as_numer_denom()[0] system = list(collect(equ.expand(), sym, evaluate=False).values()) if not any(equ.has(sym) for equ in system): # consecutive powers in the input expressions have # been successfully collected, so solve remaining # system using Gaussian elimination algorithm return solve(system, *coeffs, **flags) else: return None # no solutions def solve_linear_system_LU(matrix, syms): """ Solves the augmented matrix system using ``LUsolve`` and returns a dictionary in which solutions are keyed to the symbols of *syms* as ordered. Explanation =========== The matrix must be invertible. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x, y, z >>> from sympy.solvers.solvers import solve_linear_system_LU >>> solve_linear_system_LU(Matrix([ ... [1, 2, 0, 1], ... [3, 2, 2, 1], ... [2, 0, 0, 1]]), [x, y, z]) {x: 1/2, y: 1/4, z: -1/2} See Also ======== LUsolve """ if matrix.rows != matrix.cols - 1: raise ValueError("Rows should be equal to columns - 1") A = matrix[:matrix.rows, :matrix.rows] b = matrix[:, matrix.cols - 1:] soln = A.LUsolve(b) solutions = {} for i in range(soln.rows): solutions[syms[i]] = soln[i, 0] return solutions def det_perm(M): """ Return the determinant of *M* by using permutations to select factors. Explanation =========== For sizes larger than 8 the number of permutations becomes prohibitively large, or if there are no symbols in the matrix, it is better to use the standard determinant routines (e.g., ``M.det()``.) See Also ======== det_minor det_quick """ args = [] s = True n = M.rows list_ = M.flat() for perm in generate_bell(n): fac = [] idx = 0 for j in perm: fac.append(list_[idx + j]) idx += n term = Mul(*fac) # disaster with unevaluated Mul -- takes forever for n=7 args.append(term if s else -term) s = not s return Add(*args) def det_minor(M): """ Return the ``det(M)`` computed from minors without introducing new nesting in products. See Also ======== det_perm det_quick """ n = M.rows if n == 2: return M[0, 0]*M[1, 1] - M[1, 0]*M[0, 1] else: return sum([(1, -1)[i % 2]*Add(*[M[0, i]*d for d in Add.make_args(det_minor(M.minor_submatrix(0, i)))]) if M[0, i] else S.Zero for i in range(n)]) def det_quick(M, method=None): """ Return ``det(M)`` assuming that either there are lots of zeros or the size of the matrix is small. If this assumption is not met, then the normal Matrix.det function will be used with method = ``method``. See Also ======== det_minor det_perm """ if any(i.has(Symbol) for i in M): if M.rows < 8 and all(i.has(Symbol) for i in M): return det_perm(M) return det_minor(M) else: return M.det(method=method) if method else M.det() def inv_quick(M): """Return the inverse of ``M``, assuming that either there are lots of zeros or the size of the matrix is small. """ from sympy.matrices import zeros if not all(i.is_Number for i in M): if not any(i.is_Number for i in M): det = lambda _: det_perm(_) else: det = lambda _: det_minor(_) else: return M.inv() n = M.rows d = det(M) if d == S.Zero: raise NonInvertibleMatrixError("Matrix det == 0; not invertible") ret = zeros(n) s1 = -1 for i in range(n): s = s1 = -s1 for j in range(n): di = det(M.minor_submatrix(i, j)) ret[j, i] = s*di/d s = -s return ret # these are functions that have multiple inverse values per period multi_inverses = { sin: lambda x: (asin(x), S.Pi - asin(x)), cos: lambda x: (acos(x), 2*S.Pi - acos(x)), } def _tsolve(eq, sym, **flags): """ Helper for ``_solve`` that solves a transcendental equation with respect to the given symbol. Various equations containing powers and logarithms, can be solved. There is currently no guarantee that all solutions will be returned or that a real solution will be favored over a complex one. Either a list of potential solutions will be returned or None will be returned (in the case that no method was known to get a solution for the equation). All other errors (like the inability to cast an expression as a Poly) are unhandled. Examples ======== >>> from sympy import log >>> from sympy.solvers.solvers import _tsolve as tsolve >>> from sympy.abc import x >>> tsolve(3**(2*x + 5) - 4, x) [-5/2 + log(2)/log(3), (-5*log(3)/2 + log(2) + I*pi)/log(3)] >>> tsolve(log(x) + 2*x, x) [LambertW(2)/2] """ if 'tsolve_saw' not in flags: flags['tsolve_saw'] = [] if eq in flags['tsolve_saw']: return None else: flags['tsolve_saw'].append(eq) rhs, lhs = _invert(eq, sym) if lhs == sym: return [rhs] try: if lhs.is_Add: # it's time to try factoring; powdenest is used # to try get powers in standard form for better factoring f = factor(powdenest(lhs - rhs)) if f.is_Mul: return _solve(f, sym, **flags) if rhs: f = logcombine(lhs, force=flags.get('force', True)) if f.count(log) != lhs.count(log): if isinstance(f, log): return _solve(f.args[0] - exp(rhs), sym, **flags) return _tsolve(f - rhs, sym, **flags) elif lhs.is_Pow: if lhs.exp.is_Integer: if lhs - rhs != eq: return _solve(lhs - rhs, sym, **flags) if sym not in lhs.exp.free_symbols: return _solve(lhs.base - rhs**(1/lhs.exp), sym, **flags) # _tsolve calls this with Dummy before passing the actual number in. if any(t.is_Dummy for t in rhs.free_symbols): raise NotImplementedError # _tsolve will call here again... # a ** g(x) == 0 if not rhs: # f(x)**g(x) only has solutions where f(x) == 0 and g(x) != 0 at # the same place sol_base = _solve(lhs.base, sym, **flags) return [s for s in sol_base if lhs.exp.subs(sym, s) != 0] # a ** g(x) == b if not lhs.base.has(sym): if lhs.base == 0: return _solve(lhs.exp, sym, **flags) if rhs != 0 else [] # Gets most solutions... if lhs.base == rhs.as_base_exp()[0]: # handles case when bases are equal sol = _solve(lhs.exp - rhs.as_base_exp()[1], sym, **flags) else: # handles cases when bases are not equal and exp # may or may not be equal sol = _solve(exp(log(lhs.base)*lhs.exp)-exp(log(rhs)), sym, **flags) # Check for duplicate solutions def equal(expr1, expr2): _ = Dummy() eq = checksol(expr1 - _, _, expr2) if eq is None: if nsimplify(expr1) != nsimplify(expr2): return False # they might be coincidentally the same # so check more rigorously eq = expr1.equals(expr2) return eq # Guess a rational exponent e_rat = nsimplify(log(abs(rhs))/log(abs(lhs.base))) e_rat = simplify(posify(e_rat)[0]) n, d = fraction(e_rat) if expand(lhs.base**n - rhs**d) == 0: sol = [s for s in sol if not equal(lhs.exp.subs(sym, s), e_rat)] sol.extend(_solve(lhs.exp - e_rat, sym, **flags)) return list(ordered(set(sol))) # f(x) ** g(x) == c else: sol = [] logform = lhs.exp*log(lhs.base) - log(rhs) if logform != lhs - rhs: try: sol.extend(_solve(logform, sym, **flags)) except NotImplementedError: pass # Collect possible solutions and check with substitution later. check = [] if rhs == 1: # f(x) ** g(x) = 1 -- g(x)=0 or f(x)=+-1 check.extend(_solve(lhs.exp, sym, **flags)) check.extend(_solve(lhs.base - 1, sym, **flags)) check.extend(_solve(lhs.base + 1, sym, **flags)) elif rhs.is_Rational: for d in (i for i in divisors(abs(rhs.p)) if i != 1): e, t = integer_log(rhs.p, d) if not t: continue # rhs.p != d**b for s in divisors(abs(rhs.q)): if s**e== rhs.q: r = Rational(d, s) check.extend(_solve(lhs.base - r, sym, **flags)) check.extend(_solve(lhs.base + r, sym, **flags)) check.extend(_solve(lhs.exp - e, sym, **flags)) elif rhs.is_irrational: b_l, e_l = lhs.base.as_base_exp() n, d = (e_l*lhs.exp).as_numer_denom() b, e = sqrtdenest(rhs).as_base_exp() check = [sqrtdenest(i) for i in (_solve(lhs.base - b, sym, **flags))] check.extend([sqrtdenest(i) for i in (_solve(lhs.exp - e, sym, **flags))]) if e_l*d != 1: check.extend(_solve(b_l**n - rhs**(e_l*d), sym, **flags)) for s in check: ok = checksol(eq, sym, s) if ok is None: ok = eq.subs(sym, s).equals(0) if ok: sol.append(s) return list(ordered(set(sol))) elif lhs.is_Function and len(lhs.args) == 1: if lhs.func in multi_inverses: # sin(x) = 1/3 -> x - asin(1/3) & x - (pi - asin(1/3)) soln = [] for i in multi_inverses[lhs.func](rhs): soln.extend(_solve(lhs.args[0] - i, sym, **flags)) return list(ordered(soln)) elif lhs.func == LambertW: return _solve(lhs.args[0] - rhs*exp(rhs), sym, **flags) rewrite = lhs.rewrite(exp) if rewrite != lhs: return _solve(rewrite - rhs, sym, **flags) except NotImplementedError: pass # maybe it is a lambert pattern if flags.pop('bivariate', True): # lambert forms may need some help being recognized, e.g. changing # 2**(3*x) + x**3*log(2)**3 + 3*x**2*log(2)**2 + 3*x*log(2) + 1 # to 2**(3*x) + (x*log(2) + 1)**3 g = _filtered_gens(eq.as_poly(), sym) up_or_log = set() for gi in g: if isinstance(gi, exp) or (gi.is_Pow and gi.base == S.Exp1) or isinstance(gi, log): up_or_log.add(gi) elif gi.is_Pow: gisimp = powdenest(expand_power_exp(gi)) if gisimp.is_Pow and sym in gisimp.exp.free_symbols: up_or_log.add(gi) eq_down = expand_log(expand_power_exp(eq)).subs( dict(list(zip(up_or_log, [0]*len(up_or_log))))) eq = expand_power_exp(factor(eq_down, deep=True) + (eq - eq_down)) rhs, lhs = _invert(eq, sym) if lhs.has(sym): try: poly = lhs.as_poly() g = _filtered_gens(poly, sym) _eq = lhs - rhs sols = _solve_lambert(_eq, sym, g) # use a simplified form if it satisfies eq # and has fewer operations for n, s in enumerate(sols): ns = nsimplify(s) if ns != s and ns.count_ops() <= s.count_ops(): ok = checksol(_eq, sym, ns) if ok is None: ok = _eq.subs(sym, ns).equals(0) if ok: sols[n] = ns return sols except NotImplementedError: # maybe it's a convoluted function if len(g) == 2: try: gpu = bivariate_type(lhs - rhs, *g) if gpu is None: raise NotImplementedError g, p, u = gpu flags['bivariate'] = False inversion = _tsolve(g - u, sym, **flags) if inversion: sol = _solve(p, u, **flags) return list(ordered({i.subs(u, s) for i in inversion for s in sol})) except NotImplementedError: pass else: pass if flags.pop('force', True): flags['force'] = False pos, reps = posify(lhs - rhs) if rhs == S.ComplexInfinity: return [] for u, s in reps.items(): if s == sym: break else: u = sym if pos.has(u): try: soln = _solve(pos, u, **flags) return list(ordered([s.subs(reps) for s in soln])) except NotImplementedError: pass else: pass # here for coverage return # here for coverage # TODO: option for calculating J numerically @conserve_mpmath_dps def nsolve(*args, dict=False, **kwargs): r""" Solve a nonlinear equation system numerically: ``nsolve(f, [args,] x0, modules=['mpmath'], **kwargs)``. Explanation =========== ``f`` is a vector function of symbolic expressions representing the system. *args* are the variables. If there is only one variable, this argument can be omitted. ``x0`` is a starting vector close to a solution. Use the modules keyword to specify which modules should be used to evaluate the function and the Jacobian matrix. Make sure to use a module that supports matrices. For more information on the syntax, please see the docstring of ``lambdify``. If the keyword arguments contain ``dict=True`` (default is False) ``nsolve`` will return a list (perhaps empty) of solution mappings. This might be especially useful if you want to use ``nsolve`` as a fallback to solve since using the dict argument for both methods produces return values of consistent type structure. Please note: to keep this consistent with ``solve``, the solution will be returned in a list even though ``nsolve`` (currently at least) only finds one solution at a time. Overdetermined systems are supported. Examples ======== >>> from sympy import Symbol, nsolve >>> import mpmath >>> mpmath.mp.dps = 15 >>> x1 = Symbol('x1') >>> x2 = Symbol('x2') >>> f1 = 3 * x1**2 - 2 * x2**2 - 1 >>> f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8 >>> print(nsolve((f1, f2), (x1, x2), (-1, 1))) Matrix([[-1.19287309935246], [1.27844411169911]]) For one-dimensional functions the syntax is simplified: >>> from sympy import sin, nsolve >>> from sympy.abc import x >>> nsolve(sin(x), x, 2) 3.14159265358979 >>> nsolve(sin(x), 2) 3.14159265358979 To solve with higher precision than the default, use the prec argument: >>> from sympy import cos >>> nsolve(cos(x) - x, 1) 0.739085133215161 >>> nsolve(cos(x) - x, 1, prec=50) 0.73908513321516064165531208767387340401341175890076 >>> cos(_) 0.73908513321516064165531208767387340401341175890076 To solve for complex roots of real functions, a nonreal initial point must be specified: >>> from sympy import I >>> nsolve(x**2 + 2, I) 1.4142135623731*I ``mpmath.findroot`` is used and you can find their more extensive documentation, especially concerning keyword parameters and available solvers. Note, however, that functions which are very steep near the root, the verification of the solution may fail. In this case you should use the flag ``verify=False`` and independently verify the solution. >>> from sympy import cos, cosh >>> f = cos(x)*cosh(x) - 1 >>> nsolve(f, 3.14*100) Traceback (most recent call last): ... ValueError: Could not find root within given tolerance. (1.39267e+230 > 2.1684e-19) >>> ans = nsolve(f, 3.14*100, verify=False); ans 312.588469032184 >>> f.subs(x, ans).n(2) 2.1e+121 >>> (f/f.diff(x)).subs(x, ans).n(2) 7.4e-15 One might safely skip the verification if bounds of the root are known and a bisection method is used: >>> bounds = lambda i: (3.14*i, 3.14*(i + 1)) >>> nsolve(f, bounds(100), solver='bisect', verify=False) 315.730061685774 Alternatively, a function may be better behaved when the denominator is ignored. Since this is not always the case, however, the decision of what function to use is left to the discretion of the user. >>> eq = x**2/(1 - x)/(1 - 2*x)**2 - 100 >>> nsolve(eq, 0.46) Traceback (most recent call last): ... ValueError: Could not find root within given tolerance. (10000 > 2.1684e-19) Try another starting point or tweak arguments. >>> nsolve(eq.as_numer_denom()[0], 0.46) 0.46792545969349058 """ # there are several other SymPy functions that use method= so # guard against that here if 'method' in kwargs: raise ValueError(filldedent(''' Keyword "method" should not be used in this context. When using some mpmath solvers directly, the keyword "method" is used, but when using nsolve (and findroot) the keyword to use is "solver".''')) if 'prec' in kwargs: prec = kwargs.pop('prec') import mpmath mpmath.mp.dps = prec else: prec = None # keyword argument to return result as a dictionary as_dict = dict from builtins import dict # to unhide the builtin # interpret arguments if len(args) == 3: f = args[0] fargs = args[1] x0 = args[2] if iterable(fargs) and iterable(x0): if len(x0) != len(fargs): raise TypeError('nsolve expected exactly %i guess vectors, got %i' % (len(fargs), len(x0))) elif len(args) == 2: f = args[0] fargs = None x0 = args[1] if iterable(f): raise TypeError('nsolve expected 3 arguments, got 2') elif len(args) < 2: raise TypeError('nsolve expected at least 2 arguments, got %i' % len(args)) else: raise TypeError('nsolve expected at most 3 arguments, got %i' % len(args)) modules = kwargs.get('modules', ['mpmath']) if iterable(f): f = list(f) for i, fi in enumerate(f): if isinstance(fi, Equality): f[i] = fi.lhs - fi.rhs f = Matrix(f).T if iterable(x0): x0 = list(x0) if not isinstance(f, Matrix): # assume it's a sympy expression if isinstance(f, Equality): f = f.lhs - f.rhs syms = f.free_symbols if fargs is None: fargs = syms.copy().pop() if not (len(syms) == 1 and (fargs in syms or fargs[0] in syms)): raise ValueError(filldedent(''' expected a one-dimensional and numerical function''')) # the function is much better behaved if there is no denominator # but sending the numerator is left to the user since sometimes # the function is better behaved when the denominator is present # e.g., issue 11768 f = lambdify(fargs, f, modules) x = sympify(findroot(f, x0, **kwargs)) if as_dict: return [{fargs: x}] return x if len(fargs) > f.cols: raise NotImplementedError(filldedent(''' need at least as many equations as variables''')) verbose = kwargs.get('verbose', False) if verbose: print('f(x):') print(f) # derive Jacobian J = f.jacobian(fargs) if verbose: print('J(x):') print(J) # create functions f = lambdify(fargs, f.T, modules) J = lambdify(fargs, J, modules) # solve the system numerically x = findroot(f, x0, J=J, **kwargs) if as_dict: return [dict(zip(fargs, [sympify(xi) for xi in x]))] return Matrix(x) def _invert(eq, *symbols, **kwargs): """ Return tuple (i, d) where ``i`` is independent of *symbols* and ``d`` contains symbols. Explanation =========== ``i`` and ``d`` are obtained after recursively using algebraic inversion until an uninvertible ``d`` remains. If there are no free symbols then ``d`` will be zero. Some (but not necessarily all) solutions to the expression ``i - d`` will be related to the solutions of the original expression. Examples ======== >>> from sympy.solvers.solvers import _invert as invert >>> from sympy import sqrt, cos >>> from sympy.abc import x, y >>> invert(x - 3) (3, x) >>> invert(3) (3, 0) >>> invert(2*cos(x) - 1) (1/2, cos(x)) >>> invert(sqrt(x) - 3) (3, sqrt(x)) >>> invert(sqrt(x) + y, x) (-y, sqrt(x)) >>> invert(sqrt(x) + y, y) (-sqrt(x), y) >>> invert(sqrt(x) + y, x, y) (0, sqrt(x) + y) If there is more than one symbol in a power's base and the exponent is not an Integer, then the principal root will be used for the inversion: >>> invert(sqrt(x + y) - 2) (4, x + y) >>> invert(sqrt(x + y) - 2) (4, x + y) If the exponent is an Integer, setting ``integer_power`` to True will force the principal root to be selected: >>> invert(x**2 - 4, integer_power=True) (2, x) """ eq = sympify(eq) if eq.args: # make sure we are working with flat eq eq = eq.func(*eq.args) free = eq.free_symbols if not symbols: symbols = free if not free & set(symbols): return eq, S.Zero dointpow = bool(kwargs.get('integer_power', False)) lhs = eq rhs = S.Zero while True: was = lhs while True: indep, dep = lhs.as_independent(*symbols) # dep + indep == rhs if lhs.is_Add: # this indicates we have done it all if indep.is_zero: break lhs = dep rhs -= indep # dep * indep == rhs else: # this indicates we have done it all if indep is S.One: break lhs = dep rhs /= indep # collect like-terms in symbols if lhs.is_Add: terms = {} for a in lhs.args: i, d = a.as_independent(*symbols) terms.setdefault(d, []).append(i) if any(len(v) > 1 for v in terms.values()): args = [] for d, i in terms.items(): if len(i) > 1: args.append(Add(*i)*d) else: args.append(i[0]*d) lhs = Add(*args) # if it's a two-term Add with rhs = 0 and two powers we can get the # dependent terms together, e.g. 3*f(x) + 2*g(x) -> f(x)/g(x) = -2/3 if lhs.is_Add and not rhs and len(lhs.args) == 2 and \ not lhs.is_polynomial(*symbols): a, b = ordered(lhs.args) ai, ad = a.as_independent(*symbols) bi, bd = b.as_independent(*symbols) if any(_ispow(i) for i in (ad, bd)): a_base, a_exp = ad.as_base_exp() b_base, b_exp = bd.as_base_exp() if a_base == b_base: # a = -b lhs = powsimp(powdenest(ad/bd)) rhs = -bi/ai else: rat = ad/bd _lhs = powsimp(ad/bd) if _lhs != rat: lhs = _lhs rhs = -bi/ai elif ai == -bi: if isinstance(ad, Function) and ad.func == bd.func: if len(ad.args) == len(bd.args) == 1: lhs = ad.args[0] - bd.args[0] elif len(ad.args) == len(bd.args): # should be able to solve # f(x, y) - f(2 - x, 0) == 0 -> x == 1 raise NotImplementedError( 'equal function with more than 1 argument') else: raise ValueError( 'function with different numbers of args') elif lhs.is_Mul and any(_ispow(a) for a in lhs.args): lhs = powsimp(powdenest(lhs)) if lhs.is_Function: if hasattr(lhs, 'inverse') and lhs.inverse() is not None and len(lhs.args) == 1: # -1 # f(x) = g -> x = f (g) # # /!\ inverse should not be defined if there are multiple values # for the function -- these are handled in _tsolve # rhs = lhs.inverse()(rhs) lhs = lhs.args[0] elif isinstance(lhs, atan2): y, x = lhs.args lhs = 2*atan(y/(sqrt(x**2 + y**2) + x)) elif lhs.func == rhs.func: if len(lhs.args) == len(rhs.args) == 1: lhs = lhs.args[0] rhs = rhs.args[0] elif len(lhs.args) == len(rhs.args): # should be able to solve # f(x, y) == f(2, 3) -> x == 2 # f(x, x + y) == f(2, 3) -> x == 2 raise NotImplementedError( 'equal function with more than 1 argument') else: raise ValueError( 'function with different numbers of args') if rhs and lhs.is_Pow and lhs.exp.is_Integer and lhs.exp < 0: lhs = 1/lhs rhs = 1/rhs # base**a = b -> base = b**(1/a) if # a is an Integer and dointpow=True (this gives real branch of root) # a is not an Integer and the equation is multivariate and the # base has more than 1 symbol in it # The rationale for this is that right now the multi-system solvers # doesn't try to resolve generators to see, for example, if the whole # system is written in terms of sqrt(x + y) so it will just fail, so we # do that step here. if lhs.is_Pow and ( lhs.exp.is_Integer and dointpow or not lhs.exp.is_Integer and len(symbols) > 1 and len(lhs.base.free_symbols & set(symbols)) > 1): rhs = rhs**(1/lhs.exp) lhs = lhs.base if lhs == was: break return rhs, lhs def unrad(eq, *syms, **flags): """ Remove radicals with symbolic arguments and return (eq, cov), None, or raise an error. Explanation =========== None is returned if there are no radicals to remove. NotImplementedError is raised if there are radicals and they cannot be removed or if the relationship between the original symbols and the change of variable needed to rewrite the system as a polynomial cannot be solved. Otherwise the tuple, ``(eq, cov)``, is returned where: *eq*, ``cov`` *eq* is an equation without radicals (in the symbol(s) of interest) whose solutions are a superset of the solutions to the original expression. *eq* might be rewritten in terms of a new variable; the relationship to the original variables is given by ``cov`` which is a list containing ``v`` and ``v**p - b`` where ``p`` is the power needed to clear the radical and ``b`` is the radical now expressed as a polynomial in the symbols of interest. For example, for sqrt(2 - x) the tuple would be ``(c, c**2 - 2 + x)``. The solutions of *eq* will contain solutions to the original equation (if there are any). *syms* An iterable of symbols which, if provided, will limit the focus of radical removal: only radicals with one or more of the symbols of interest will be cleared. All free symbols are used if *syms* is not set. *flags* are used internally for communication during recursive calls. Two options are also recognized: ``take``, when defined, is interpreted as a single-argument function that returns True if a given Pow should be handled. Radicals can be removed from an expression if: * All bases of the radicals are the same; a change of variables is done in this case. * If all radicals appear in one term of the expression. * There are only four terms with sqrt() factors or there are less than four terms having sqrt() factors. * There are only two terms with radicals. Examples ======== >>> from sympy.solvers.solvers import unrad >>> from sympy.abc import x >>> from sympy import sqrt, Rational, root >>> unrad(sqrt(x)*x**Rational(1, 3) + 2) (x**5 - 64, []) >>> unrad(sqrt(x) + root(x + 1, 3)) (-x**3 + x**2 + 2*x + 1, []) >>> eq = sqrt(x) + root(x, 3) - 2 >>> unrad(eq) (_p**3 + _p**2 - 2, [_p, _p**6 - x]) """ from sympy import Equality as Eq uflags = dict(check=False, simplify=False) def _cov(p, e): if cov: # XXX - uncovered oldp, olde = cov if Poly(e, p).degree(p) in (1, 2): cov[:] = [p, olde.subs(oldp, _solve(e, p, **uflags)[0])] else: raise NotImplementedError else: cov[:] = [p, e] def _canonical(eq, cov): if cov: # change symbol to vanilla so no solutions are eliminated p, e = cov rep = {p: Dummy(p.name)} eq = eq.xreplace(rep) cov = [p.xreplace(rep), e.xreplace(rep)] # remove constants and powers of factors since these don't change # the location of the root; XXX should factor or factor_terms be used? eq = factor_terms(_mexpand(eq.as_numer_denom()[0], recursive=True), clear=True) if eq.is_Mul: args = [] for f in eq.args: if f.is_number: continue if f.is_Pow: args.append(f.base) else: args.append(f) eq = Mul(*args) # leave as Mul for more efficient solving # make the sign canonical margs = list(Mul.make_args(eq)) changed = False for i, m in enumerate(margs): if m.could_extract_minus_sign(): margs[i] = -m changed = True if changed: eq = Mul(*margs, evaluate=False) return eq, cov def _Q(pow): # return leading Rational of denominator of Pow's exponent c = pow.as_base_exp()[1].as_coeff_Mul()[0] if not c.is_Rational: return S.One return c.q # define the _take method that will determine whether a term is of interest def _take(d): # return True if coefficient of any factor's exponent's den is not 1 for pow in Mul.make_args(d): if not pow.is_Pow: continue if _Q(pow) == 1: continue if pow.free_symbols & syms: return True return False _take = flags.setdefault('_take', _take) if isinstance(eq, Eq): eq = eq.lhs - eq.rhs # XXX legacy Eq as Eqn support elif not isinstance(eq, Expr): return cov, nwas, rpt = [flags.setdefault(k, v) for k, v in sorted(dict(cov=[], n=None, rpt=0).items())] # preconditioning eq = powdenest(factor_terms(eq, radical=True, clear=True)) eq = eq.as_numer_denom()[0] eq = _mexpand(eq, recursive=True) if eq.is_number: return # see if there are radicals in symbols of interest syms = set(syms) or eq.free_symbols # _take uses this poly = eq.as_poly() gens = [g for g in poly.gens if _take(g)] if not gens: return # recast poly in terms of eigen-gens poly = eq.as_poly(*gens) # - an exponent has a symbol of interest (don't handle) if any(g.exp.has(*syms) for g in gens): return def _rads_bases_lcm(poly): # if all the bases are the same or all the radicals are in one # term, `lcm` will be the lcm of the denominators of the # exponents of the radicals lcm = 1 rads = set() bases = set() for g in poly.gens: q = _Q(g) if q != 1: rads.add(g) lcm = ilcm(lcm, q) bases.add(g.base) return rads, bases, lcm rads, bases, lcm = _rads_bases_lcm(poly) covsym = Dummy('p', nonnegative=True) # only keep in syms symbols that actually appear in radicals; # and update gens newsyms = set() for r in rads: newsyms.update(syms & r.free_symbols) if newsyms != syms: syms = newsyms # get terms together that have common generators drad = dict(list(zip(rads, list(range(len(rads)))))) rterms = {(): []} args = Add.make_args(poly.as_expr()) for t in args: if _take(t): common = set(t.as_poly().gens).intersection(rads) key = tuple(sorted([drad[i] for i in common])) else: key = () rterms.setdefault(key, []).append(t) others = Add(*rterms.pop(())) rterms = [Add(*rterms[k]) for k in rterms.keys()] # the output will depend on the order terms are processed, so # make it canonical quickly rterms = list(reversed(list(ordered(rterms)))) ok = False # we don't have a solution yet depth = sqrt_depth(eq) if len(rterms) == 1 and not (rterms[0].is_Add and lcm > 2): eq = rterms[0]**lcm - ((-others)**lcm) ok = True else: if len(rterms) == 1 and rterms[0].is_Add: rterms = list(rterms[0].args) if len(bases) == 1: b = bases.pop() if len(syms) > 1: x = b.free_symbols else: x = syms x = list(ordered(x))[0] try: inv = _solve(covsym**lcm - b, x, **uflags) if not inv: raise NotImplementedError eq = poly.as_expr().subs(b, covsym**lcm).subs(x, inv[0]) _cov(covsym, covsym**lcm - b) return _canonical(eq, cov) except NotImplementedError: pass if len(rterms) == 2: if not others: eq = rterms[0]**lcm - (-rterms[1])**lcm ok = True elif not log(lcm, 2).is_Integer: # the lcm-is-power-of-two case is handled below r0, r1 = rterms if flags.get('_reverse', False): r1, r0 = r0, r1 i0 = _rads0, _bases0, lcm0 = _rads_bases_lcm(r0.as_poly()) i1 = _rads1, _bases1, lcm1 = _rads_bases_lcm(r1.as_poly()) for reverse in range(2): if reverse: i0, i1 = i1, i0 r0, r1 = r1, r0 _rads1, _, lcm1 = i1 _rads1 = Mul(*_rads1) t1 = _rads1**lcm1 c = covsym**lcm1 - t1 for x in syms: try: sol = _solve(c, x, **uflags) if not sol: raise NotImplementedError neweq = r0.subs(x, sol[0]) + covsym*r1/_rads1 + \ others tmp = unrad(neweq, covsym) if tmp: eq, newcov = tmp if newcov: newp, newc = newcov _cov(newp, c.subs(covsym, _solve(newc, covsym, **uflags)[0])) else: _cov(covsym, c) else: eq = neweq _cov(covsym, c) ok = True break except NotImplementedError: if reverse: raise NotImplementedError( 'no successful change of variable found') else: pass if ok: break elif len(rterms) == 3: # two cube roots and another with order less than 5 # (so an analytical solution can be found) or a base # that matches one of the cube root bases info = [_rads_bases_lcm(i.as_poly()) for i in rterms] RAD = 0 BASES = 1 LCM = 2 if info[0][LCM] != 3: info.append(info.pop(0)) rterms.append(rterms.pop(0)) elif info[1][LCM] != 3: info.append(info.pop(1)) rterms.append(rterms.pop(1)) if info[0][LCM] == info[1][LCM] == 3: if info[1][BASES] != info[2][BASES]: info[0], info[1] = info[1], info[0] rterms[0], rterms[1] = rterms[1], rterms[0] if info[1][BASES] == info[2][BASES]: eq = rterms[0]**3 + (rterms[1] + rterms[2] + others)**3 ok = True elif info[2][LCM] < 5: # a*root(A, 3) + b*root(B, 3) + others = c a, b, c, d, A, B = [Dummy(i) for i in 'abcdAB'] # zz represents the unraded expression into which the # specifics for this case are substituted zz = (c - d)*(A**3*a**9 + 3*A**2*B*a**6*b**3 - 3*A**2*a**6*c**3 + 9*A**2*a**6*c**2*d - 9*A**2*a**6*c*d**2 + 3*A**2*a**6*d**3 + 3*A*B**2*a**3*b**6 + 21*A*B*a**3*b**3*c**3 - 63*A*B*a**3*b**3*c**2*d + 63*A*B*a**3*b**3*c*d**2 - 21*A*B*a**3*b**3*d**3 + 3*A*a**3*c**6 - 18*A*a**3*c**5*d + 45*A*a**3*c**4*d**2 - 60*A*a**3*c**3*d**3 + 45*A*a**3*c**2*d**4 - 18*A*a**3*c*d**5 + 3*A*a**3*d**6 + B**3*b**9 - 3*B**2*b**6*c**3 + 9*B**2*b**6*c**2*d - 9*B**2*b**6*c*d**2 + 3*B**2*b**6*d**3 + 3*B*b**3*c**6 - 18*B*b**3*c**5*d + 45*B*b**3*c**4*d**2 - 60*B*b**3*c**3*d**3 + 45*B*b**3*c**2*d**4 - 18*B*b**3*c*d**5 + 3*B*b**3*d**6 - c**9 + 9*c**8*d - 36*c**7*d**2 + 84*c**6*d**3 - 126*c**5*d**4 + 126*c**4*d**5 - 84*c**3*d**6 + 36*c**2*d**7 - 9*c*d**8 + d**9) def _t(i): b = Mul(*info[i][RAD]) return cancel(rterms[i]/b), Mul(*info[i][BASES]) aa, AA = _t(0) bb, BB = _t(1) cc = -rterms[2] dd = others eq = zz.xreplace(dict(zip( (a, A, b, B, c, d), (aa, AA, bb, BB, cc, dd)))) ok = True # handle power-of-2 cases if not ok: if log(lcm, 2).is_Integer and (not others and len(rterms) == 4 or len(rterms) < 4): def _norm2(a, b): return a**2 + b**2 + 2*a*b if len(rterms) == 4: # (r0+r1)**2 - (r2+r3)**2 r0, r1, r2, r3 = rterms eq = _norm2(r0, r1) - _norm2(r2, r3) ok = True elif len(rterms) == 3: # (r1+r2)**2 - (r0+others)**2 r0, r1, r2 = rterms eq = _norm2(r1, r2) - _norm2(r0, others) ok = True elif len(rterms) == 2: # r0**2 - (r1+others)**2 r0, r1 = rterms eq = r0**2 - _norm2(r1, others) ok = True new_depth = sqrt_depth(eq) if ok else depth rpt += 1 # XXX how many repeats with others unchanging is enough? if not ok or ( nwas is not None and len(rterms) == nwas and new_depth is not None and new_depth == depth and rpt > 3): raise NotImplementedError('Cannot remove all radicals') flags.update(dict(cov=cov, n=len(rterms), rpt=rpt)) neq = unrad(eq, *syms, **flags) if neq: eq, cov = neq eq, cov = _canonical(eq, cov) return eq, cov from sympy.solvers.bivariate import ( bivariate_type, _solve_lambert, _filtered_gens)
87d9abef62f7db4c2d6d15e403b0b6e905a643778dcfa682ebdee01da76d6c17
""" Singularities ============= This module implements algorithms for finding singularities for a function and identifying types of functions. The differential calculus methods in this module include methods to identify the following function types in the given ``Interval``: - Increasing - Strictly Increasing - Decreasing - Strictly Decreasing - Monotonic """ from sympy import S, Symbol from sympy.core.sympify import sympify from sympy.solvers.solveset import solveset from sympy.utilities.misc import filldedent def singularities(expression, symbol, domain=None): """ Find singularities of a given function. Parameters ========== expression : Expr The target function in which singularities need to be found. symbol : Symbol The symbol over the values of which the singularity in expression in being searched for. Returns ======= Set A set of values for ``symbol`` for which ``expression`` has a singularity. An ``EmptySet`` is returned if ``expression`` has no singularities for any given value of ``Symbol``. Raises ====== NotImplementedError Methods for determining the singularities of this function have not been developed. Notes ===== This function does not find non-isolated singularities nor does it find branch points of the expression. Currently supported functions are: - univariate continuous (real or complex) functions References ========== .. [1] https://en.wikipedia.org/wiki/Mathematical_singularity Examples ======== >>> from sympy.calculus.singularities import singularities >>> from sympy import Symbol, log >>> x = Symbol('x', real=True) >>> y = Symbol('y', real=False) >>> singularities(x**2 + x + 1, x) EmptySet >>> singularities(1/(x + 1), x) {-1} >>> singularities(1/(y**2 + 1), y) {-I, I} >>> singularities(1/(y**3 + 1), y) {-1, 1/2 - sqrt(3)*I/2, 1/2 + sqrt(3)*I/2} >>> singularities(log(x), x) {0} """ from sympy.functions.elementary.exponential import log from sympy.functions.elementary.trigonometric import sec, csc, cot, tan, cos from sympy.core.power import Pow if domain is None: domain = S.Reals if symbol.is_real else S.Complexes try: sings = S.EmptySet for i in expression.rewrite([sec, csc, cot, tan], cos).atoms(Pow): if i.exp.is_infinite: raise NotImplementedError if i.exp.is_negative: sings += solveset(i.base, symbol, domain) for i in expression.atoms(log): sings += solveset(i.args[0], symbol, domain) return sings except NotImplementedError: raise NotImplementedError(filldedent(''' Methods for determining the singularities of this function have not been developed.''')) ########################################################################### # DIFFERENTIAL CALCULUS METHODS # ########################################################################### def monotonicity_helper(expression, predicate, interval=S.Reals, symbol=None): """ Helper function for functions checking function monotonicity. Parameters ========== expression : Expr The target function which is being checked predicate : function The property being tested for. The function takes in an integer and returns a boolean. The integer input is the derivative and the boolean result should be true if the property is being held, and false otherwise. interval : Set, optional The range of values in which we are testing, defaults to all reals. symbol : Symbol, optional The symbol present in expression which gets varied over the given range. It returns a boolean indicating whether the interval in which the function's derivative satisfies given predicate is a superset of the given interval. Returns ======= Boolean True if ``predicate`` is true for all the derivatives when ``symbol`` is varied in ``range``, False otherwise. """ expression = sympify(expression) free = expression.free_symbols if symbol is None: if len(free) > 1: raise NotImplementedError( 'The function has not yet been implemented' ' for all multivariate expressions.' ) variable = symbol or (free.pop() if free else Symbol('x')) derivative = expression.diff(variable) predicate_interval = solveset(predicate(derivative), variable, S.Reals) return interval.is_subset(predicate_interval) def is_increasing(expression, interval=S.Reals, symbol=None): """ Return whether the function is increasing in the given interval. Parameters ========== expression : Expr The target function which is being checked. interval : Set, optional The range of values in which we are testing (defaults to set of all real numbers). symbol : Symbol, optional The symbol present in expression which gets varied over the given range. Returns ======= Boolean True if ``expression`` is increasing (either strictly increasing or constant) in the given ``interval``, False otherwise. Examples ======== >>> from sympy import is_increasing >>> from sympy.abc import x, y >>> from sympy import S, Interval, oo >>> is_increasing(x**3 - 3*x**2 + 4*x, S.Reals) True >>> is_increasing(-x**2, Interval(-oo, 0)) True >>> is_increasing(-x**2, Interval(0, oo)) False >>> is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) False >>> is_increasing(x**2 + y, Interval(1, 2), x) True """ return monotonicity_helper(expression, lambda x: x >= 0, interval, symbol) def is_strictly_increasing(expression, interval=S.Reals, symbol=None): """ Return whether the function is strictly increasing in the given interval. Parameters ========== expression : Expr The target function which is being checked. interval : Set, optional The range of values in which we are testing (defaults to set of all real numbers). symbol : Symbol, optional The symbol present in expression which gets varied over the given range. Returns ======= Boolean True if ``expression`` is strictly increasing in the given ``interval``, False otherwise. Examples ======== >>> from sympy import is_strictly_increasing >>> from sympy.abc import x, y >>> from sympy import Interval, oo >>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2)) True >>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo)) True >>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3)) False >>> is_strictly_increasing(-x**2, Interval(0, oo)) False >>> is_strictly_increasing(-x**2 + y, Interval(-oo, 0), x) False """ return monotonicity_helper(expression, lambda x: x > 0, interval, symbol) def is_decreasing(expression, interval=S.Reals, symbol=None): """ Return whether the function is decreasing in the given interval. Parameters ========== expression : Expr The target function which is being checked. interval : Set, optional The range of values in which we are testing (defaults to set of all real numbers). symbol : Symbol, optional The symbol present in expression which gets varied over the given range. Returns ======= Boolean True if ``expression`` is decreasing (either strictly decreasing or constant) in the given ``interval``, False otherwise. Examples ======== >>> from sympy import is_decreasing >>> from sympy.abc import x, y >>> from sympy import S, Interval, oo >>> is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3)) True >>> is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo)) True >>> is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2)) False >>> is_decreasing(-x**2, Interval(-oo, 0)) False >>> is_decreasing(-x**2 + y, Interval(-oo, 0), x) False """ return monotonicity_helper(expression, lambda x: x <= 0, interval, symbol) def is_strictly_decreasing(expression, interval=S.Reals, symbol=None): """ Return whether the function is strictly decreasing in the given interval. Parameters ========== expression : Expr The target function which is being checked. interval : Set, optional The range of values in which we are testing (defaults to set of all real numbers). symbol : Symbol, optional The symbol present in expression which gets varied over the given range. Returns ======= Boolean True if ``expression`` is strictly decreasing in the given ``interval``, False otherwise. Examples ======== >>> from sympy import is_strictly_decreasing >>> from sympy.abc import x, y >>> from sympy import S, Interval, oo >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo)) True >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2)) False >>> is_strictly_decreasing(-x**2, Interval(-oo, 0)) False >>> is_strictly_decreasing(-x**2 + y, Interval(-oo, 0), x) False """ return monotonicity_helper(expression, lambda x: x < 0, interval, symbol) def is_monotonic(expression, interval=S.Reals, symbol=None): """ Return whether the function is monotonic in the given interval. Parameters ========== expression : Expr The target function which is being checked. interval : Set, optional The range of values in which we are testing (defaults to set of all real numbers). symbol : Symbol, optional The symbol present in expression which gets varied over the given range. Returns ======= Boolean True if ``expression`` is monotonic in the given ``interval``, False otherwise. Raises ====== NotImplementedError Monotonicity check has not been implemented for the queried function. Examples ======== >>> from sympy import is_monotonic >>> from sympy.abc import x, y >>> from sympy import S, Interval, oo >>> is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3)) True >>> is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo)) True >>> is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals) True >>> is_monotonic(-x**2, S.Reals) False >>> is_monotonic(x**2 + y + 1, Interval(1, 2), x) True """ expression = sympify(expression) free = expression.free_symbols if symbol is None and len(free) > 1: raise NotImplementedError( 'is_monotonic has not yet been implemented' ' for all multivariate expressions.' ) variable = symbol or (free.pop() if free else Symbol('x')) turning_points = solveset(expression.diff(variable), variable, interval) return interval.intersection(turning_points) is S.EmptySet
e160007c63cc7057361cf7286d5eed7c933c1c8c58ee1e41b8494279f778d5dc
from sympy import Order, S, log, limit, lcm_list, im, re, Dummy, Piecewise from sympy.core import Add, Mul, Pow from sympy.core.basic import Basic from sympy.core.compatibility import iterable from sympy.core.expr import AtomicExpr, Expr from sympy.core.function import expand_mul from sympy.core.numbers import _sympifyit, oo, zoo from sympy.core.relational import is_le, is_lt, is_ge, is_gt from sympy.core.sympify import _sympify from sympy.functions.elementary.miscellaneous import Min, Max from sympy.logic.boolalg import And from sympy.sets.sets import (Interval, Intersection, FiniteSet, Union, Complement, EmptySet) from sympy.sets.fancysets import ImageSet from sympy.solvers.inequalities import solve_univariate_inequality from sympy.utilities import filldedent from sympy.multipledispatch import dispatch def continuous_domain(f, symbol, domain): """ Returns the intervals in the given domain for which the function is continuous. This method is limited by the ability to determine the various singularities and discontinuities of the given function. Parameters ========== f : Expr The concerned function. symbol : Symbol The variable for which the intervals are to be determined. domain : Interval The domain over which the continuity of the symbol has to be checked. Examples ======== >>> from sympy import Symbol, S, tan, log, pi, sqrt >>> from sympy.sets import Interval >>> from sympy.calculus.util import continuous_domain >>> x = Symbol('x') >>> continuous_domain(1/x, x, S.Reals) Union(Interval.open(-oo, 0), Interval.open(0, oo)) >>> continuous_domain(tan(x), x, Interval(0, pi)) Union(Interval.Ropen(0, pi/2), Interval.Lopen(pi/2, pi)) >>> continuous_domain(sqrt(x - 2), x, Interval(-5, 5)) Interval(2, 5) >>> continuous_domain(log(2*x - 1), x, S.Reals) Interval.open(1/2, oo) Returns ======= Interval Union of all intervals where the function is continuous. Raises ====== NotImplementedError If the method to determine continuity of such a function has not yet been developed. """ from sympy.solvers.inequalities import solve_univariate_inequality from sympy.calculus.singularities import singularities if domain.is_subset(S.Reals): constrained_interval = domain for atom in f.atoms(Pow): den = atom.exp.as_numer_denom()[1] if den.is_even and den.is_nonzero: constraint = solve_univariate_inequality(atom.base >= 0, symbol).as_set() constrained_interval = Intersection(constraint, constrained_interval) for atom in f.atoms(log): constraint = solve_univariate_inequality(atom.args[0] > 0, symbol).as_set() constrained_interval = Intersection(constraint, constrained_interval) return constrained_interval - singularities(f, symbol, domain) def function_range(f, symbol, domain): """ Finds the range of a function in a given domain. This method is limited by the ability to determine the singularities and determine limits. Parameters ========== f : Expr The concerned function. symbol : Symbol The variable for which the range of function is to be determined. domain : Interval The domain under which the range of the function has to be found. Examples ======== >>> from sympy import Symbol, S, exp, log, pi, sqrt, sin, tan >>> from sympy.sets import Interval >>> from sympy.calculus.util import function_range >>> x = Symbol('x') >>> function_range(sin(x), x, Interval(0, 2*pi)) Interval(-1, 1) >>> function_range(tan(x), x, Interval(-pi/2, pi/2)) Interval(-oo, oo) >>> function_range(1/x, x, S.Reals) Union(Interval.open(-oo, 0), Interval.open(0, oo)) >>> function_range(exp(x), x, S.Reals) Interval.open(0, oo) >>> function_range(log(x), x, S.Reals) Interval(-oo, oo) >>> function_range(sqrt(x), x , Interval(-5, 9)) Interval(0, 3) Returns ======= Interval Union of all ranges for all intervals under domain where function is continuous. Raises ====== NotImplementedError If any of the intervals, in the given domain, for which function is continuous are not finite or real, OR if the critical points of the function on the domain can't be found. """ from sympy.solvers.solveset import solveset if isinstance(domain, EmptySet): return S.EmptySet period = periodicity(f, symbol) if period == S.Zero: # the expression is constant wrt symbol return FiniteSet(f.expand()) if period is not None: if isinstance(domain, Interval): if (domain.inf - domain.sup).is_infinite: domain = Interval(0, period) elif isinstance(domain, Union): for sub_dom in domain.args: if isinstance(sub_dom, Interval) and \ ((sub_dom.inf - sub_dom.sup).is_infinite): domain = Interval(0, period) intervals = continuous_domain(f, symbol, domain) range_int = S.EmptySet if isinstance(intervals,(Interval, FiniteSet)): interval_iter = (intervals,) elif isinstance(intervals, Union): interval_iter = intervals.args else: raise NotImplementedError(filldedent(''' Unable to find range for the given domain. ''')) for interval in interval_iter: if isinstance(interval, FiniteSet): for singleton in interval: if singleton in domain: range_int += FiniteSet(f.subs(symbol, singleton)) elif isinstance(interval, Interval): vals = S.EmptySet critical_points = S.EmptySet critical_values = S.EmptySet bounds = ((interval.left_open, interval.inf, '+'), (interval.right_open, interval.sup, '-')) for is_open, limit_point, direction in bounds: if is_open: critical_values += FiniteSet(limit(f, symbol, limit_point, direction)) vals += critical_values else: vals += FiniteSet(f.subs(symbol, limit_point)) solution = solveset(f.diff(symbol), symbol, interval) if not iterable(solution): raise NotImplementedError( 'Unable to find critical points for {}'.format(f)) if isinstance(solution, ImageSet): raise NotImplementedError( 'Infinite number of critical points for {}'.format(f)) critical_points += solution for critical_point in critical_points: vals += FiniteSet(f.subs(symbol, critical_point)) left_open, right_open = False, False if critical_values is not S.EmptySet: if critical_values.inf == vals.inf: left_open = True if critical_values.sup == vals.sup: right_open = True range_int += Interval(vals.inf, vals.sup, left_open, right_open) else: raise NotImplementedError(filldedent(''' Unable to find range for the given domain. ''')) return range_int def not_empty_in(finset_intersection, *syms): """ Finds the domain of the functions in `finite_set` in which the `finite_set` is not-empty Parameters ========== finset_intersection : The unevaluated intersection of FiniteSet containing real-valued functions with Union of Sets syms : Tuple of symbols Symbol for which domain is to be found Raises ====== NotImplementedError The algorithms to find the non-emptiness of the given FiniteSet are not yet implemented. ValueError The input is not valid. RuntimeError It is a bug, please report it to the github issue tracker (https://github.com/sympy/sympy/issues). Examples ======== >>> from sympy import FiniteSet, Interval, not_empty_in, oo >>> from sympy.abc import x >>> not_empty_in(FiniteSet(x/2).intersect(Interval(0, 1)), x) Interval(0, 2) >>> not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) Union(Interval(1, 2), Interval(-sqrt(2), -1)) >>> not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) Union(Interval.Lopen(-2, -1), Interval(2, oo)) """ # TODO: handle piecewise defined functions # TODO: handle transcendental functions # TODO: handle multivariate functions if len(syms) == 0: raise ValueError("One or more symbols must be given in syms.") if finset_intersection is S.EmptySet: return S.EmptySet if isinstance(finset_intersection, Union): elm_in_sets = finset_intersection.args[0] return Union(not_empty_in(finset_intersection.args[1], *syms), elm_in_sets) if isinstance(finset_intersection, FiniteSet): finite_set = finset_intersection _sets = S.Reals else: finite_set = finset_intersection.args[1] _sets = finset_intersection.args[0] if not isinstance(finite_set, FiniteSet): raise ValueError('A FiniteSet must be given, not %s: %s' % (type(finite_set), finite_set)) if len(syms) == 1: symb = syms[0] else: raise NotImplementedError('more than one variables %s not handled' % (syms,)) def elm_domain(expr, intrvl): """ Finds the domain of an expression in any given interval """ from sympy.solvers.solveset import solveset _start = intrvl.start _end = intrvl.end _singularities = solveset(expr.as_numer_denom()[1], symb, domain=S.Reals) if intrvl.right_open: if _end is S.Infinity: _domain1 = S.Reals else: _domain1 = solveset(expr < _end, symb, domain=S.Reals) else: _domain1 = solveset(expr <= _end, symb, domain=S.Reals) if intrvl.left_open: if _start is S.NegativeInfinity: _domain2 = S.Reals else: _domain2 = solveset(expr > _start, symb, domain=S.Reals) else: _domain2 = solveset(expr >= _start, symb, domain=S.Reals) # domain in the interval expr_with_sing = Intersection(_domain1, _domain2) expr_domain = Complement(expr_with_sing, _singularities) return expr_domain if isinstance(_sets, Interval): return Union(*[elm_domain(element, _sets) for element in finite_set]) if isinstance(_sets, Union): _domain = S.EmptySet for intrvl in _sets.args: _domain_element = Union(*[elm_domain(element, intrvl) for element in finite_set]) _domain = Union(_domain, _domain_element) return _domain def periodicity(f, symbol, check=False): """ Tests the given function for periodicity in the given symbol. Parameters ========== f : Expr. The concerned function. symbol : Symbol The variable for which the period is to be determined. check : Boolean, optional The flag to verify whether the value being returned is a period or not. Returns ======= period The period of the function is returned. `None` is returned when the function is aperiodic or has a complex period. The value of `0` is returned as the period of a constant function. Raises ====== NotImplementedError The value of the period computed cannot be verified. Notes ===== Currently, we do not support functions with a complex period. The period of functions having complex periodic values such as `exp`, `sinh` is evaluated to `None`. The value returned might not be the "fundamental" period of the given function i.e. it may not be the smallest periodic value of the function. The verification of the period through the `check` flag is not reliable due to internal simplification of the given expression. Hence, it is set to `False` by default. Examples ======== >>> from sympy import Symbol, sin, cos, tan, exp >>> from sympy.calculus.util import periodicity >>> x = Symbol('x') >>> f = sin(x) + sin(2*x) + sin(3*x) >>> periodicity(f, x) 2*pi >>> periodicity(sin(x)*cos(x), x) pi >>> periodicity(exp(tan(2*x) - 1), x) pi/2 >>> periodicity(sin(4*x)**cos(2*x), x) pi >>> periodicity(exp(x), x) """ from sympy.core.mod import Mod from sympy.core.relational import Relational from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.trigonometric import ( TrigonometricFunction, sin, cos, csc, sec) from sympy.simplify.simplify import simplify from sympy.solvers.decompogen import decompogen from sympy.polys.polytools import degree temp = Dummy('x', real=True) f = f.subs(symbol, temp) symbol = temp def _check(orig_f, period): '''Return the checked period or raise an error.''' new_f = orig_f.subs(symbol, symbol + period) if new_f.equals(orig_f): return period else: raise NotImplementedError(filldedent(''' The period of the given function cannot be verified. When `%s` was replaced with `%s + %s` in `%s`, the result was `%s` which was not recognized as being the same as the original function. So either the period was wrong or the two forms were not recognized as being equal. Set check=False to obtain the value.''' % (symbol, symbol, period, orig_f, new_f))) orig_f = f period = None if isinstance(f, Relational): f = f.lhs - f.rhs f = simplify(f) if symbol not in f.free_symbols: return S.Zero if isinstance(f, TrigonometricFunction): try: period = f.period(symbol) except NotImplementedError: pass if isinstance(f, Abs): arg = f.args[0] if isinstance(arg, (sec, csc, cos)): # all but tan and cot might have a # a period that is half as large # so recast as sin arg = sin(arg.args[0]) period = periodicity(arg, symbol) if period is not None and isinstance(arg, sin): # the argument of Abs was a trigonometric other than # cot or tan; test to see if the half-period # is valid. Abs(arg) has behaviour equivalent to # orig_f, so use that for test: orig_f = Abs(arg) try: return _check(orig_f, period/2) except NotImplementedError as err: if check: raise NotImplementedError(err) # else let new orig_f and period be # checked below if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1): f = Pow(S.Exp1, expand_mul(f.exp)) if im(f) != 0: period_real = periodicity(re(f), symbol) period_imag = periodicity(im(f), symbol) if period_real is not None and period_imag is not None: period = lcim([period_real, period_imag]) if f.is_Pow and f.base != S.Exp1: base, expo = f.args base_has_sym = base.has(symbol) expo_has_sym = expo.has(symbol) if base_has_sym and not expo_has_sym: period = periodicity(base, symbol) elif expo_has_sym and not base_has_sym: period = periodicity(expo, symbol) else: period = _periodicity(f.args, symbol) elif f.is_Mul: coeff, g = f.as_independent(symbol, as_Add=False) if isinstance(g, TrigonometricFunction) or coeff is not S.One: period = periodicity(g, symbol) else: period = _periodicity(g.args, symbol) elif f.is_Add: k, g = f.as_independent(symbol) if k is not S.Zero: return periodicity(g, symbol) period = _periodicity(g.args, symbol) elif isinstance(f, Mod): a, n = f.args if a == symbol: period = n elif isinstance(a, TrigonometricFunction): period = periodicity(a, symbol) #check if 'f' is linear in 'symbol' elif (a.is_polynomial(symbol) and degree(a, symbol) == 1 and symbol not in n.free_symbols): period = Abs(n / a.diff(symbol)) elif isinstance(f, Piecewise): pass # not handling Piecewise yet as the return type is not favorable elif period is None: from sympy.solvers.decompogen import compogen g_s = decompogen(f, symbol) num_of_gs = len(g_s) if num_of_gs > 1: for index, g in enumerate(reversed(g_s)): start_index = num_of_gs - 1 - index g = compogen(g_s[start_index:], symbol) if g != orig_f and g != f: # Fix for issue 12620 period = periodicity(g, symbol) if period is not None: break if period is not None: if check: return _check(orig_f, period) return period return None def _periodicity(args, symbol): """ Helper for `periodicity` to find the period of a list of simpler functions. It uses the `lcim` method to find the least common period of all the functions. Parameters ========== args : Tuple of Symbol All the symbols present in a function. symbol : Symbol The symbol over which the function is to be evaluated. Returns ======= period The least common period of the function for all the symbols of the function. None if for at least one of the symbols the function is aperiodic """ periods = [] for f in args: period = periodicity(f, symbol) if period is None: return None if period is not S.Zero: periods.append(period) if len(periods) > 1: return lcim(periods) if periods: return periods[0] def lcim(numbers): """Returns the least common integral multiple of a list of numbers. The numbers can be rational or irrational or a mixture of both. `None` is returned for incommensurable numbers. Parameters ========== numbers : list Numbers (rational and/or irrational) for which lcim is to be found. Returns ======= number lcim if it exists, otherwise `None` for incommensurable numbers. Examples ======== >>> from sympy import S, pi >>> from sympy.calculus.util import lcim >>> lcim([S(1)/2, S(3)/4, S(5)/6]) 15/2 >>> lcim([2*pi, 3*pi, pi, pi/2]) 6*pi >>> lcim([S(1), 2*pi]) """ result = None if all(num.is_irrational for num in numbers): factorized_nums = list(map(lambda num: num.factor(), numbers)) factors_num = list( map(lambda num: num.as_coeff_Mul(), factorized_nums)) term = factors_num[0][1] if all(factor == term for coeff, factor in factors_num): common_term = term coeffs = [coeff for coeff, factor in factors_num] result = lcm_list(coeffs) * common_term elif all(num.is_rational for num in numbers): result = lcm_list(numbers) else: pass return result def is_convex(f, *syms, domain=S.Reals): """Determines the convexity of the function passed in the argument. Parameters ========== f : Expr The concerned function. syms : Tuple of symbols The variables with respect to which the convexity is to be determined. domain : Interval, optional The domain over which the convexity of the function has to be checked. If unspecified, S.Reals will be the default domain. Returns ======= Boolean The method returns `True` if the function is convex otherwise it returns `False`. Raises ====== NotImplementedError The check for the convexity of multivariate functions is not implemented yet. Notes ===== To determine concavity of a function pass `-f` as the concerned function. To determine logarithmic convexity of a function pass log(f) as concerned function. To determine logartihmic concavity of a function pass -log(f) as concerned function. Currently, convexity check of multivariate functions is not handled. Examples ======== >>> from sympy import symbols, exp, oo, Interval >>> from sympy.calculus.util import is_convex >>> x = symbols('x') >>> is_convex(exp(x), x) True >>> is_convex(x**3, x, domain = Interval(-1, oo)) False References ========== .. [1] https://en.wikipedia.org/wiki/Convex_function .. [2] http://www.ifp.illinois.edu/~angelia/L3_convfunc.pdf .. [3] https://en.wikipedia.org/wiki/Logarithmically_convex_function .. [4] https://en.wikipedia.org/wiki/Logarithmically_concave_function .. [5] https://en.wikipedia.org/wiki/Concave_function """ if len(syms) > 1: raise NotImplementedError( "The check for the convexity of multivariate functions is not implemented yet.") f = _sympify(f) var = syms[0] condition = f.diff(var, 2) < 0 if solve_univariate_inequality(condition, var, False, domain): return False return True def stationary_points(f, symbol, domain=S.Reals): """ Returns the stationary points of a function (where derivative of the function is 0) in the given domain. Parameters ========== f : Expr The concerned function. symbol : Symbol The variable for which the stationary points are to be determined. domain : Interval The domain over which the stationary points have to be checked. If unspecified, S.Reals will be the default domain. Returns ======= Set A set of stationary points for the function. If there are no stationary point, an EmptySet is returned. Examples ======== >>> from sympy import Symbol, S, sin, pi, pprint, stationary_points >>> from sympy.sets import Interval >>> x = Symbol('x') >>> stationary_points(1/x, x, S.Reals) EmptySet >>> pprint(stationary_points(sin(x), x), use_unicode=False) pi 3*pi {2*n*pi + -- | n in Integers} U {2*n*pi + ---- | n in Integers} 2 2 >>> stationary_points(sin(x),x, Interval(0, 4*pi)) {pi/2, 3*pi/2, 5*pi/2, 7*pi/2} """ from sympy import solveset, diff if isinstance(domain, EmptySet): return S.EmptySet domain = continuous_domain(f, symbol, domain) set = solveset(diff(f, symbol), symbol, domain) return set def maximum(f, symbol, domain=S.Reals): """ Returns the maximum value of a function in the given domain. Parameters ========== f : Expr The concerned function. symbol : Symbol The variable for maximum value needs to be determined. domain : Interval The domain over which the maximum have to be checked. If unspecified, then Global maximum is returned. Returns ======= number Maximum value of the function in given domain. Examples ======== >>> from sympy import Symbol, S, sin, cos, pi, maximum >>> from sympy.sets import Interval >>> x = Symbol('x') >>> f = -x**2 + 2*x + 5 >>> maximum(f, x, S.Reals) 6 >>> maximum(sin(x), x, Interval(-pi, pi/4)) sqrt(2)/2 >>> maximum(sin(x)*cos(x), x) 1/2 """ from sympy import Symbol if isinstance(symbol, Symbol): if isinstance(domain, EmptySet): raise ValueError("Maximum value not defined for empty domain.") return function_range(f, symbol, domain).sup else: raise ValueError("%s is not a valid symbol." % symbol) def minimum(f, symbol, domain=S.Reals): """ Returns the minimum value of a function in the given domain. Parameters ========== f : Expr The concerned function. symbol : Symbol The variable for minimum value needs to be determined. domain : Interval The domain over which the minimum have to be checked. If unspecified, then Global minimum is returned. Returns ======= number Minimum value of the function in the given domain. Examples ======== >>> from sympy import Symbol, S, sin, cos, minimum >>> from sympy.sets import Interval >>> x = Symbol('x') >>> f = x**2 + 2*x + 5 >>> minimum(f, x, S.Reals) 4 >>> minimum(sin(x), x, Interval(2, 3)) sin(3) >>> minimum(sin(x)*cos(x), x) -1/2 """ from sympy import Symbol if isinstance(symbol, Symbol): if isinstance(domain, EmptySet): raise ValueError("Minimum value not defined for empty domain.") return function_range(f, symbol, domain).inf else: raise ValueError("%s is not a valid symbol." % symbol) class AccumulationBounds(AtomicExpr): r""" # Note AccumulationBounds has an alias: AccumBounds AccumulationBounds represent an interval `[a, b]`, which is always closed at the ends. Here `a` and `b` can be any value from extended real numbers. The intended meaning of AccummulationBounds is to give an approximate location of the accumulation points of a real function at a limit point. Let `a` and `b` be reals such that a <= b. `\left\langle a, b\right\rangle = \{x \in \mathbb{R} \mid a \le x \le b\}` `\left\langle -\infty, b\right\rangle = \{x \in \mathbb{R} \mid x \le b\} \cup \{-\infty, \infty\}` `\left\langle a, \infty \right\rangle = \{x \in \mathbb{R} \mid a \le x\} \cup \{-\infty, \infty\}` `\left\langle -\infty, \infty \right\rangle = \mathbb{R} \cup \{-\infty, \infty\}` `oo` and `-oo` are added to the second and third definition respectively, since if either `-oo` or `oo` is an argument, then the other one should be included (though not as an end point). This is forced, since we have, for example, `1/AccumBounds(0, 1) = AccumBounds(1, oo)`, and the limit at `0` is not one-sided. As x tends to `0-`, then `1/x -> -oo`, so `-oo` should be interpreted as belonging to `AccumBounds(1, oo)` though it need not appear explicitly. In many cases it suffices to know that the limit set is bounded. However, in some other cases more exact information could be useful. For example, all accumulation values of cos(x) + 1 are non-negative. (AccumBounds(-1, 1) + 1 = AccumBounds(0, 2)) A AccumulationBounds object is defined to be real AccumulationBounds, if its end points are finite reals. Let `X`, `Y` be real AccumulationBounds, then their sum, difference, product are defined to be the following sets: `X + Y = \{ x+y \mid x \in X \cap y \in Y\}` `X - Y = \{ x-y \mid x \in X \cap y \in Y\}` `X * Y = \{ x*y \mid x \in X \cap y \in Y\}` When an AccumBounds is raised to a negative power, if 0 is contained between the bounds then an infinite range is returned, otherwise if an endpoint is 0 then a semi-infinite range with consistent sign will be returned. AccumBounds in expressions behave a lot like Intervals but the semantics are not necessarily the same. Division (or exponentiation to a negative integer power) could be handled with *intervals* by returning a union of the results obtained after splitting the bounds between negatives and positives, but that is not done with AccumBounds. In addition, bounds are assumed to be independent of each other; if the same bound is used in more than one place in an expression, the result may not be the supremum or infimum of the expression (see below). Finally, when a boundary is ``1``, exponentiation to the power of ``oo`` yields ``oo``, neither ``1`` nor ``nan``. Examples ======== >>> from sympy import AccumBounds, sin, exp, log, pi, E, S, oo >>> from sympy.abc import x >>> AccumBounds(0, 1) + AccumBounds(1, 2) AccumBounds(1, 3) >>> AccumBounds(0, 1) - AccumBounds(0, 2) AccumBounds(-2, 1) >>> AccumBounds(-2, 3)*AccumBounds(-1, 1) AccumBounds(-3, 3) >>> AccumBounds(1, 2)*AccumBounds(3, 5) AccumBounds(3, 10) The exponentiation of AccumulationBounds is defined as follows: If 0 does not belong to `X` or `n > 0` then `X^n = \{ x^n \mid x \in X\}` >>> AccumBounds(1, 4)**(S(1)/2) AccumBounds(1, 2) otherwise, an infinite or semi-infinite result is obtained: >>> 1/AccumBounds(-1, 1) AccumBounds(-oo, oo) >>> 1/AccumBounds(0, 2) AccumBounds(1/2, oo) >>> 1/AccumBounds(-oo, 0) AccumBounds(-oo, 0) A boundary of 1 will always generate all nonnegatives: >>> AccumBounds(1, 2)**oo AccumBounds(0, oo) >>> AccumBounds(0, 1)**oo AccumBounds(0, oo) If the exponent is itself an AccumulationBounds or is not an integer then unevaluated results will be returned unless the base values are positive: >>> AccumBounds(2, 3)**AccumBounds(-1, 2) AccumBounds(1/3, 9) >>> AccumBounds(-2, 3)**AccumBounds(-1, 2) AccumBounds(-2, 3)**AccumBounds(-1, 2) >>> AccumBounds(-2, -1)**(S(1)/2) sqrt(AccumBounds(-2, -1)) Note: `<a, b>^2` is not same as `<a, b>*<a, b>` >>> AccumBounds(-1, 1)**2 AccumBounds(0, 1) >>> AccumBounds(1, 3) < 4 True >>> AccumBounds(1, 3) < -1 False Some elementary functions can also take AccumulationBounds as input. A function `f` evaluated for some real AccumulationBounds `<a, b>` is defined as `f(\left\langle a, b\right\rangle) = \{ f(x) \mid a \le x \le b \}` >>> sin(AccumBounds(pi/6, pi/3)) AccumBounds(1/2, sqrt(3)/2) >>> exp(AccumBounds(0, 1)) AccumBounds(1, E) >>> log(AccumBounds(1, E)) AccumBounds(0, 1) Some symbol in an expression can be substituted for a AccumulationBounds object. But it doesn't necessarily evaluate the AccumulationBounds for that expression. The same expression can be evaluated to different values depending upon the form it is used for substitution since each instance of an AccumulationBounds is considered independent. For example: >>> (x**2 + 2*x + 1).subs(x, AccumBounds(-1, 1)) AccumBounds(-1, 4) >>> ((x + 1)**2).subs(x, AccumBounds(-1, 1)) AccumBounds(0, 4) References ========== .. [1] https://en.wikipedia.org/wiki/Interval_arithmetic .. [2] http://fab.cba.mit.edu/classes/S62.12/docs/Hickey_interval.pdf Notes ===== Do not use ``AccumulationBounds`` for floating point interval arithmetic calculations, use ``mpmath.iv`` instead. """ is_extended_real = True def __new__(cls, min, max): min = _sympify(min) max = _sympify(max) # Only allow real intervals (use symbols with 'is_extended_real=True'). if not min.is_extended_real or not max.is_extended_real: raise ValueError("Only real AccumulationBounds are supported") if max == min: return max # Make sure that the created AccumBounds object will be valid. if max.is_number and min.is_number: bad = max.is_comparable and min.is_comparable and max < min else: bad = (max - min).is_extended_negative if bad: raise ValueError( "Lower limit should be smaller than upper limit") return Basic.__new__(cls, min, max) # setting the operation priority _op_priority = 11.0 def _eval_is_real(self): if self.min.is_real and self.max.is_real: return True @property def min(self): """ Returns the minimum possible value attained by AccumulationBounds object. Examples ======== >>> from sympy import AccumBounds >>> AccumBounds(1, 3).min 1 """ return self.args[0] @property def max(self): """ Returns the maximum possible value attained by AccumulationBounds object. Examples ======== >>> from sympy import AccumBounds >>> AccumBounds(1, 3).max 3 """ return self.args[1] @property def delta(self): """ Returns the difference of maximum possible value attained by AccumulationBounds object and minimum possible value attained by AccumulationBounds object. Examples ======== >>> from sympy import AccumBounds >>> AccumBounds(1, 3).delta 2 """ return self.max - self.min @property def mid(self): """ Returns the mean of maximum possible value attained by AccumulationBounds object and minimum possible value attained by AccumulationBounds object. Examples ======== >>> from sympy import AccumBounds >>> AccumBounds(1, 3).mid 2 """ return (self.min + self.max) / 2 @_sympifyit('other', NotImplemented) def _eval_power(self, other): return self.__pow__(other) @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Expr): if isinstance(other, AccumBounds): return AccumBounds( Add(self.min, other.min), Add(self.max, other.max)) if other is S.Infinity and self.min is S.NegativeInfinity or \ other is S.NegativeInfinity and self.max is S.Infinity: return AccumBounds(-oo, oo) elif other.is_extended_real: if self.min is S.NegativeInfinity and self.max is S.Infinity: return AccumBounds(-oo, oo) elif self.min is S.NegativeInfinity: return AccumBounds(-oo, self.max + other) elif self.max is S.Infinity: return AccumBounds(self.min + other, oo) else: return AccumBounds(Add(self.min, other), Add(self.max, other)) return Add(self, other, evaluate=False) return NotImplemented __radd__ = __add__ def __neg__(self): return AccumBounds(-self.max, -self.min) @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Expr): if isinstance(other, AccumBounds): return AccumBounds( Add(self.min, -other.max), Add(self.max, -other.min)) if other is S.NegativeInfinity and self.min is S.NegativeInfinity or \ other is S.Infinity and self.max is S.Infinity: return AccumBounds(-oo, oo) elif other.is_extended_real: if self.min is S.NegativeInfinity and self.max is S.Infinity: return AccumBounds(-oo, oo) elif self.min is S.NegativeInfinity: return AccumBounds(-oo, self.max - other) elif self.max is S.Infinity: return AccumBounds(self.min - other, oo) else: return AccumBounds( Add(self.min, -other), Add(self.max, -other)) return Add(self, -other, evaluate=False) return NotImplemented @_sympifyit('other', NotImplemented) def __rsub__(self, other): return self.__neg__() + other @_sympifyit('other', NotImplemented) def __mul__(self, other): if self.args == (-oo, oo): return self if isinstance(other, Expr): if isinstance(other, AccumBounds): if other.args == (-oo, oo): return other v = set() for i in self.args: vi = other*i for i in vi.args or (vi,): v.add(i) return AccumBounds(Min(*v), Max(*v)) if other is S.Infinity: if self.min.is_zero: return AccumBounds(0, oo) if self.max.is_zero: return AccumBounds(-oo, 0) if other is S.NegativeInfinity: if self.min.is_zero: return AccumBounds(-oo, 0) if self.max.is_zero: return AccumBounds(0, oo) if other.is_extended_real: if other.is_zero: if self.max is S.Infinity: return AccumBounds(0, oo) if self.min is S.NegativeInfinity: return AccumBounds(-oo, 0) return S.Zero if other.is_extended_positive: return AccumBounds( Mul(self.min, other), Mul(self.max, other)) elif other.is_extended_negative: return AccumBounds( Mul(self.max, other), Mul(self.min, other)) if isinstance(other, Order): return other return Mul(self, other, evaluate=False) return NotImplemented __rmul__ = __mul__ @_sympifyit('other', NotImplemented) def __truediv__(self, other): if isinstance(other, Expr): if isinstance(other, AccumBounds): if other.min.is_positive or other.max.is_negative: return self * AccumBounds(1/other.max, 1/other.min) if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative and other.min.is_extended_nonpositive and other.max.is_extended_nonnegative): if self.min.is_zero and other.min.is_zero: return AccumBounds(0, oo) if self.max.is_zero and other.min.is_zero: return AccumBounds(-oo, 0) return AccumBounds(-oo, oo) if self.max.is_extended_negative: if other.min.is_extended_negative: if other.max.is_zero: return AccumBounds(self.max / other.min, oo) if other.max.is_extended_positive: # if we were dealing with intervals we would return # Union(Interval(-oo, self.max/other.max), # Interval(self.max/other.min, oo)) return AccumBounds(-oo, oo) if other.min.is_zero and other.max.is_extended_positive: return AccumBounds(-oo, self.max / other.max) if self.min.is_extended_positive: if other.min.is_extended_negative: if other.max.is_zero: return AccumBounds(-oo, self.min / other.min) if other.max.is_extended_positive: # if we were dealing with intervals we would return # Union(Interval(-oo, self.min/other.min), # Interval(self.min/other.max, oo)) return AccumBounds(-oo, oo) if other.min.is_zero and other.max.is_extended_positive: return AccumBounds(self.min / other.max, oo) elif other.is_extended_real: if other is S.Infinity or other is S.NegativeInfinity: if self == AccumBounds(-oo, oo): return AccumBounds(-oo, oo) if self.max is S.Infinity: return AccumBounds(Min(0, other), Max(0, other)) if self.min is S.NegativeInfinity: return AccumBounds(Min(0, -other), Max(0, -other)) if other.is_extended_positive: return AccumBounds(self.min / other, self.max / other) elif other.is_extended_negative: return AccumBounds(self.max / other, self.min / other) if (1 / other) is S.ComplexInfinity: return Mul(self, 1 / other, evaluate=False) else: return Mul(self, 1 / other) return NotImplemented @_sympifyit('other', NotImplemented) def __rtruediv__(self, other): if isinstance(other, Expr): if other.is_extended_real: if other.is_zero: return S.Zero if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative): if self.min.is_zero: if other.is_extended_positive: return AccumBounds(Mul(other, 1 / self.max), oo) if other.is_extended_negative: return AccumBounds(-oo, Mul(other, 1 / self.max)) if self.max.is_zero: if other.is_extended_positive: return AccumBounds(-oo, Mul(other, 1 / self.min)) if other.is_extended_negative: return AccumBounds(Mul(other, 1 / self.min), oo) return AccumBounds(-oo, oo) else: return AccumBounds(Min(other / self.min, other / self.max), Max(other / self.min, other / self.max)) return Mul(other, 1 / self, evaluate=False) else: return NotImplemented @_sympifyit('other', NotImplemented) def __pow__(self, other): if isinstance(other, Expr): if other is S.Infinity: if self.min.is_extended_nonnegative: if self.max < 1: return S.Zero if self.min > 1: return S.Infinity return AccumBounds(0, oo) elif self.max.is_extended_negative: if self.min > -1: return S.Zero if self.max < -1: return zoo return S.NaN else: if self.min > -1: if self.max < 1: return S.Zero return AccumBounds(0, oo) return AccumBounds(-oo, oo) if other is S.NegativeInfinity: return (1/self)**oo # generically true if (self.max - self.min).is_nonnegative: # well defined if self.min.is_nonnegative: # no 0 to worry about if other.is_nonnegative: # no infinity to worry about return self.func(self.min**other, self.max**other) if other.is_zero: return S.One # x**0 = 1 if other.is_Integer or other.is_integer: if self.min.is_extended_positive: return AccumBounds( Min(self.min**other, self.max**other), Max(self.min**other, self.max**other)) elif self.max.is_extended_negative: return AccumBounds( Min(self.max**other, self.min**other), Max(self.max**other, self.min**other)) if other % 2 == 0: if other.is_extended_negative: if self.min.is_zero: return AccumBounds(self.max**other, oo) if self.max.is_zero: return AccumBounds(self.min**other, oo) return AccumBounds(0, oo) return AccumBounds( S.Zero, Max(self.min**other, self.max**other)) elif other % 2 == 1: if other.is_extended_negative: if self.min.is_zero: return AccumBounds(self.max**other, oo) if self.max.is_zero: return AccumBounds(-oo, self.min**other) return AccumBounds(-oo, oo) return AccumBounds(self.min**other, self.max**other) # non-integer exponent # 0**neg or neg**frac yields complex if (other.is_number or other.is_rational) and ( self.min.is_extended_nonnegative or ( other.is_extended_nonnegative and self.min.is_extended_nonnegative)): num, den = other.as_numer_denom() if num is S.One: return AccumBounds(*[i**(1/den) for i in self.args]) elif den is not S.One: # e.g. if other is not Float return (self**num)**(1/den) # ok for non-negative base if isinstance(other, AccumBounds): if (self.min.is_extended_positive or self.min.is_extended_nonnegative and other.min.is_extended_nonnegative): p = [self**i for i in other.args] if not any(i.is_Pow for i in p): a = [j for i in p for j in i.args or (i,)] try: return self.func(min(a), max(a)) except TypeError: # can't sort pass return Pow(self, other, evaluate=False) return NotImplemented @_sympifyit('other', NotImplemented) def __rpow__(self, other): if other.is_real and other.is_extended_nonnegative and ( self.max - self.min).is_extended_positive: if other is S.One: return S.One if other.is_extended_positive: a, b = [other**i for i in self.args] if min(a, b) != a: a, b = b, a return self.func(a, b) if other.is_zero: if self.min.is_zero: return self.func(0, 1) if self.min.is_extended_positive: return S.Zero return Pow(other, self, evaluate=False) def __abs__(self): if self.max.is_extended_negative: return self.__neg__() elif self.min.is_extended_negative: return AccumBounds(S.Zero, Max(abs(self.min), self.max)) else: return self def __contains__(self, other): """ Returns True if other is contained in self, where other belongs to extended real numbers, False if not contained, otherwise TypeError is raised. Examples ======== >>> from sympy import AccumBounds, oo >>> 1 in AccumBounds(-1, 3) True -oo and oo go together as limits (in AccumulationBounds). >>> -oo in AccumBounds(1, oo) True >>> oo in AccumBounds(-oo, 0) True """ other = _sympify(other) if other is S.Infinity or other is S.NegativeInfinity: if self.min is S.NegativeInfinity or self.max is S.Infinity: return True return False rv = And(self.min <= other, self.max >= other) if rv not in (True, False): raise TypeError("input failed to evaluate") return rv def intersection(self, other): """ Returns the intersection of 'self' and 'other'. Here other can be an instance of FiniteSet or AccumulationBounds. Parameters ========== other: AccumulationBounds Another AccumulationBounds object with which the intersection has to be computed. Returns ======= AccumulationBounds Intersection of 'self' and 'other'. Examples ======== >>> from sympy import AccumBounds, FiniteSet >>> AccumBounds(1, 3).intersection(AccumBounds(2, 4)) AccumBounds(2, 3) >>> AccumBounds(1, 3).intersection(AccumBounds(4, 6)) EmptySet >>> AccumBounds(1, 4).intersection(FiniteSet(1, 2, 5)) {1, 2} """ if not isinstance(other, (AccumBounds, FiniteSet)): raise TypeError( "Input must be AccumulationBounds or FiniteSet object") if isinstance(other, FiniteSet): fin_set = S.EmptySet for i in other: if i in self: fin_set = fin_set + FiniteSet(i) return fin_set if self.max < other.min or self.min > other.max: return S.EmptySet if self.min <= other.min: if self.max <= other.max: return AccumBounds(other.min, self.max) if self.max > other.max: return other if other.min <= self.min: if other.max < self.max: return AccumBounds(self.min, other.max) if other.max > self.max: return self def union(self, other): # TODO : Devise a better method for Union of AccumBounds # this method is not actually correct and # can be made better if not isinstance(other, AccumBounds): raise TypeError( "Input must be AccumulationBounds or FiniteSet object") if self.min <= other.min and self.max >= other.min: return AccumBounds(self.min, Max(self.max, other.max)) if other.min <= self.min and other.max >= self.min: return AccumBounds(other.min, Max(self.max, other.max)) @dispatch(AccumulationBounds, AccumulationBounds) # type: ignore # noqa:F811 def _eval_is_le(lhs, rhs): # noqa:F811 if is_le(lhs.max, rhs.min): return True if is_gt(lhs.min, rhs.max): return False @dispatch(AccumulationBounds, Basic) # type: ignore # noqa:F811 def _eval_is_le(lhs, rhs): # noqa: F811 """ Returns True if range of values attained by `self` AccumulationBounds object is greater than the range of values attained by `other`, where other may be any value of type AccumulationBounds object or extended real number value, False if `other` satisfies the same property, else an unevaluated Relational. Examples ======== >>> from sympy import AccumBounds, oo >>> AccumBounds(1, 3) > AccumBounds(4, oo) False >>> AccumBounds(1, 4) > AccumBounds(3, 4) AccumBounds(1, 4) > AccumBounds(3, 4) >>> AccumBounds(1, oo) > -1 True """ if not rhs.is_extended_real: raise TypeError( "Invalid comparison of %s %s" % (type(rhs), rhs)) elif rhs.is_comparable: if is_le(lhs.max, rhs): return True if is_gt(lhs.min, rhs): return False @dispatch(AccumulationBounds, AccumulationBounds) def _eval_is_ge(lhs, rhs): # noqa:F811 if is_ge(lhs.min, rhs.max): return True if is_lt(lhs.max, rhs.min): return False @dispatch(AccumulationBounds, Expr) # type:ignore def _eval_is_ge(lhs, rhs): # noqa: F811 """ Returns True if range of values attained by `lhs` AccumulationBounds object is less that the range of values attained by `rhs`, where other may be any value of type AccumulationBounds object or extended real number value, False if `rhs` satisfies the same property, else an unevaluated Relational. Examples ======== >>> from sympy import AccumBounds, oo >>> AccumBounds(1, 3) >= AccumBounds(4, oo) False >>> AccumBounds(1, 4) >= AccumBounds(3, 4) AccumBounds(1, 4) >= AccumBounds(3, 4) >>> AccumBounds(1, oo) >= 1 True """ if not rhs.is_extended_real: raise TypeError( "Invalid comparison of %s %s" % (type(rhs), rhs)) elif rhs.is_comparable: if is_ge(lhs.min, rhs): return True if is_lt(lhs.max, rhs): return False @dispatch(Expr, AccumulationBounds) # type:ignore def _eval_is_ge(lhs, rhs): # noqa:F811 if not lhs.is_extended_real: raise TypeError( "Invalid comparison of %s %s" % (type(lhs), lhs)) elif lhs.is_comparable: if is_le(rhs.max, lhs): return True if is_gt(rhs.min, lhs): return False @dispatch(AccumulationBounds, AccumulationBounds) # type:ignore def _eval_is_ge(lhs, rhs): # noqa:F811 if is_ge(lhs.min, rhs.max): return True if is_lt(lhs.max, rhs.min): return False # setting an alias for AccumulationBounds AccumBounds = AccumulationBounds
7719df4c51dcc3ecef49e9bb357264cecd14aa7918ec2dc42ae06132281f615f
""" This module provides convenient functions to transform sympy expressions to lambda functions which can be used to calculate numerical values very fast. """ from typing import Any, Dict, Iterable import builtins import inspect import keyword import textwrap import linecache from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy.core.compatibility import (is_sequence, iterable, NotIterable) from sympy.utilities.misc import filldedent from sympy.utilities.decorator import doctest_depends_on __doctest_requires__ = {('lambdify',): ['numpy', 'tensorflow']} # Default namespaces, letting us define translations that can't be defined # by simple variable maps, like I => 1j MATH_DEFAULT = {} # type: Dict[str, Any] MPMATH_DEFAULT = {} # type: Dict[str, Any] NUMPY_DEFAULT = {"I": 1j} # type: Dict[str, Any] SCIPY_DEFAULT = {"I": 1j} # type: Dict[str, Any] CUPY_DEFAULT = {"I": 1j} # type: Dict[str, Any] TENSORFLOW_DEFAULT = {} # type: Dict[str, Any] SYMPY_DEFAULT = {} # type: Dict[str, Any] NUMEXPR_DEFAULT = {} # type: Dict[str, Any] # These are the namespaces the lambda functions will use. # These are separate from the names above because they are modified # throughout this file, whereas the defaults should remain unmodified. MATH = MATH_DEFAULT.copy() MPMATH = MPMATH_DEFAULT.copy() NUMPY = NUMPY_DEFAULT.copy() SCIPY = SCIPY_DEFAULT.copy() CUPY = CUPY_DEFAULT.copy() TENSORFLOW = TENSORFLOW_DEFAULT.copy() SYMPY = SYMPY_DEFAULT.copy() NUMEXPR = NUMEXPR_DEFAULT.copy() # Mappings between sympy and other modules function names. MATH_TRANSLATIONS = { "ceiling": "ceil", "E": "e", "ln": "log", } # NOTE: This dictionary is reused in Function._eval_evalf to allow subclasses # of Function to automatically evalf. MPMATH_TRANSLATIONS = { "Abs": "fabs", "elliptic_k": "ellipk", "elliptic_f": "ellipf", "elliptic_e": "ellipe", "elliptic_pi": "ellippi", "ceiling": "ceil", "chebyshevt": "chebyt", "chebyshevu": "chebyu", "E": "e", "I": "j", "ln": "log", #"lowergamma":"lower_gamma", "oo": "inf", #"uppergamma":"upper_gamma", "LambertW": "lambertw", "MutableDenseMatrix": "matrix", "ImmutableDenseMatrix": "matrix", "conjugate": "conj", "dirichlet_eta": "altzeta", "Ei": "ei", "Shi": "shi", "Chi": "chi", "Si": "si", "Ci": "ci", "RisingFactorial": "rf", "FallingFactorial": "ff", "betainc_regularized": "betainc", } NUMPY_TRANSLATIONS = { "Heaviside": "heaviside", } # type: Dict[str, str] SCIPY_TRANSLATIONS = {} # type: Dict[str, str] CUPY_TRANSLATIONS = {} # type: Dict[str, str] TENSORFLOW_TRANSLATIONS = {} # type: Dict[str, str] NUMEXPR_TRANSLATIONS = {} # type: Dict[str, str] # Available modules: MODULES = { "math": (MATH, MATH_DEFAULT, MATH_TRANSLATIONS, ("from math import *",)), "mpmath": (MPMATH, MPMATH_DEFAULT, MPMATH_TRANSLATIONS, ("from mpmath import *",)), "numpy": (NUMPY, NUMPY_DEFAULT, NUMPY_TRANSLATIONS, ("import numpy; from numpy import *; from numpy.linalg import *",)), "scipy": (SCIPY, SCIPY_DEFAULT, SCIPY_TRANSLATIONS, ("import numpy; import scipy; from scipy import *; from scipy.special import *",)), "cupy": (CUPY, CUPY_DEFAULT, CUPY_TRANSLATIONS, ("import cupy",)), "tensorflow": (TENSORFLOW, TENSORFLOW_DEFAULT, TENSORFLOW_TRANSLATIONS, ("import tensorflow",)), "sympy": (SYMPY, SYMPY_DEFAULT, {}, ( "from sympy.functions import *", "from sympy.matrices import *", "from sympy import Integral, pi, oo, nan, zoo, E, I",)), "numexpr" : (NUMEXPR, NUMEXPR_DEFAULT, NUMEXPR_TRANSLATIONS, ("import_module('numexpr')", )), } def _import(module, reload=False): """ Creates a global translation dictionary for module. The argument module has to be one of the following strings: "math", "mpmath", "numpy", "sympy", "tensorflow". These dictionaries map names of python functions to their equivalent in other modules. """ # Required despite static analysis claiming it is not used from sympy.external import import_module # noqa:F401 try: namespace, namespace_default, translations, import_commands = MODULES[ module] except KeyError: raise NameError( "'%s' module can't be used for lambdification" % module) # Clear namespace or exit if namespace != namespace_default: # The namespace was already generated, don't do it again if not forced. if reload: namespace.clear() namespace.update(namespace_default) else: return for import_command in import_commands: if import_command.startswith('import_module'): module = eval(import_command) if module is not None: namespace.update(module.__dict__) continue else: try: exec(import_command, {}, namespace) continue except ImportError: pass raise ImportError( "can't import '%s' with '%s' command" % (module, import_command)) # Add translated names to namespace for sympyname, translation in translations.items(): namespace[sympyname] = namespace[translation] # For computing the modulus of a sympy expression we use the builtin abs # function, instead of the previously used fabs function for all # translation modules. This is because the fabs function in the math # module does not accept complex valued arguments. (see issue 9474). The # only exception, where we don't use the builtin abs function is the # mpmath translation module, because mpmath.fabs returns mpf objects in # contrast to abs(). if 'Abs' not in namespace: namespace['Abs'] = abs # Used for dynamically generated filenames that are inserted into the # linecache. _lambdify_generated_counter = 1 @doctest_depends_on(modules=('numpy', 'scipy', 'tensorflow',), python_version=(3,)) def lambdify(args: Iterable, expr, modules=None, printer=None, use_imps=True, dummify=False, cse=False): """Convert a SymPy expression into a function that allows for fast numeric evaluation. .. warning:: This function uses ``exec``, and thus shouldn't be used on unsanitized input. .. versionchanged:: 1.7.0 Passing a set for the *args* parameter is deprecated as sets are unordered. Use an ordered iterable such as a list or tuple. Explanation =========== For example, to convert the SymPy expression ``sin(x) + cos(x)`` to an equivalent NumPy function that numerically evaluates it: >>> from sympy import sin, cos, symbols, lambdify >>> import numpy as np >>> x = symbols('x') >>> expr = sin(x) + cos(x) >>> expr sin(x) + cos(x) >>> f = lambdify(x, expr, 'numpy') >>> a = np.array([1, 2]) >>> f(a) [1.38177329 0.49315059] The primary purpose of this function is to provide a bridge from SymPy expressions to numerical libraries such as NumPy, SciPy, NumExpr, mpmath, and tensorflow. In general, SymPy functions do not work with objects from other libraries, such as NumPy arrays, and functions from numeric libraries like NumPy or mpmath do not work on SymPy expressions. ``lambdify`` bridges the two by converting a SymPy expression to an equivalent numeric function. The basic workflow with ``lambdify`` is to first create a SymPy expression representing whatever mathematical function you wish to evaluate. This should be done using only SymPy functions and expressions. Then, use ``lambdify`` to convert this to an equivalent function for numerical evaluation. For instance, above we created ``expr`` using the SymPy symbol ``x`` and SymPy functions ``sin`` and ``cos``, then converted it to an equivalent NumPy function ``f``, and called it on a NumPy array ``a``. Parameters ========== args : List[Symbol] A variable or a list of variables whose nesting represents the nesting of the arguments that will be passed to the function. Variables can be symbols, undefined functions, or matrix symbols. >>> from sympy import Eq >>> from sympy.abc import x, y, z The list of variables should match the structure of how the arguments will be passed to the function. Simply enclose the parameters as they will be passed in a list. To call a function like ``f(x)`` then ``[x]`` should be the first argument to ``lambdify``; for this case a single ``x`` can also be used: >>> f = lambdify(x, x + 1) >>> f(1) 2 >>> f = lambdify([x], x + 1) >>> f(1) 2 To call a function like ``f(x, y)`` then ``[x, y]`` will be the first argument of the ``lambdify``: >>> f = lambdify([x, y], x + y) >>> f(1, 1) 2 To call a function with a single 3-element tuple like ``f((x, y, z))`` then ``[(x, y, z)]`` will be the first argument of the ``lambdify``: >>> f = lambdify([(x, y, z)], Eq(z**2, x**2 + y**2)) >>> f((3, 4, 5)) True If two args will be passed and the first is a scalar but the second is a tuple with two arguments then the items in the list should match that structure: >>> f = lambdify([x, (y, z)], x + y + z) >>> f(1, (2, 3)) 6 expr : Expr An expression, list of expressions, or matrix to be evaluated. Lists may be nested. If the expression is a list, the output will also be a list. >>> f = lambdify(x, [x, [x + 1, x + 2]]) >>> f(1) [1, [2, 3]] If it is a matrix, an array will be returned (for the NumPy module). >>> from sympy import Matrix >>> f = lambdify(x, Matrix([x, x + 1])) >>> f(1) [[1] [2]] Note that the argument order here (variables then expression) is used to emulate the Python ``lambda`` keyword. ``lambdify(x, expr)`` works (roughly) like ``lambda x: expr`` (see :ref:`lambdify-how-it-works` below). modules : str, optional Specifies the numeric library to use. If not specified, *modules* defaults to: - ``["scipy", "numpy"]`` if SciPy is installed - ``["numpy"]`` if only NumPy is installed - ``["math", "mpmath", "sympy"]`` if neither is installed. That is, SymPy functions are replaced as far as possible by either ``scipy`` or ``numpy`` functions if available, and Python's standard library ``math``, or ``mpmath`` functions otherwise. *modules* can be one of the following types: - The strings ``"math"``, ``"mpmath"``, ``"numpy"``, ``"numexpr"``, ``"scipy"``, ``"sympy"``, or ``"tensorflow"``. This uses the corresponding printer and namespace mapping for that module. - A module (e.g., ``math``). This uses the global namespace of the module. If the module is one of the above known modules, it will also use the corresponding printer and namespace mapping (i.e., ``modules=numpy`` is equivalent to ``modules="numpy"``). - A dictionary that maps names of SymPy functions to arbitrary functions (e.g., ``{'sin': custom_sin}``). - A list that contains a mix of the arguments above, with higher priority given to entries appearing first (e.g., to use the NumPy module but override the ``sin`` function with a custom version, you can use ``[{'sin': custom_sin}, 'numpy']``). dummify : bool, optional Whether or not the variables in the provided expression that are not valid Python identifiers are substituted with dummy symbols. This allows for undefined functions like ``Function('f')(t)`` to be supplied as arguments. By default, the variables are only dummified if they are not valid Python identifiers. Set ``dummify=True`` to replace all arguments with dummy symbols (if ``args`` is not a string) - for example, to ensure that the arguments do not redefine any built-in names. cse : bool, or callable, optional Large expressions can be computed more efficiently when common subexpressions are identified and precomputed before being used multiple time. Finding the subexpressions will make creation of the 'lambdify' function slower, however. When ``True``, ``sympy.simplify.cse`` is used, otherwise (the default) the user may pass a function matching the ``cse`` signature. Examples ======== >>> from sympy.utilities.lambdify import implemented_function >>> from sympy import sqrt, sin, Matrix >>> from sympy import Function >>> from sympy.abc import w, x, y, z >>> f = lambdify(x, x**2) >>> f(2) 4 >>> f = lambdify((x, y, z), [z, y, x]) >>> f(1,2,3) [3, 2, 1] >>> f = lambdify(x, sqrt(x)) >>> f(4) 2.0 >>> f = lambdify((x, y), sin(x*y)**2) >>> f(0, 5) 0.0 >>> row = lambdify((x, y), Matrix((x, x + y)).T, modules='sympy') >>> row(1, 2) Matrix([[1, 3]]) ``lambdify`` can be used to translate SymPy expressions into mpmath functions. This may be preferable to using ``evalf`` (which uses mpmath on the backend) in some cases. >>> f = lambdify(x, sin(x), 'mpmath') >>> f(1) 0.8414709848078965 Tuple arguments are handled and the lambdified function should be called with the same type of arguments as were used to create the function: >>> f = lambdify((x, (y, z)), x + y) >>> f(1, (2, 4)) 3 The ``flatten`` function can be used to always work with flattened arguments: >>> from sympy.utilities.iterables import flatten >>> args = w, (x, (y, z)) >>> vals = 1, (2, (3, 4)) >>> f = lambdify(flatten(args), w + x + y + z) >>> f(*flatten(vals)) 10 Functions present in ``expr`` can also carry their own numerical implementations, in a callable attached to the ``_imp_`` attribute. This can be used with undefined functions using the ``implemented_function`` factory: >>> f = implemented_function(Function('f'), lambda x: x+1) >>> func = lambdify(x, f(x)) >>> func(4) 5 ``lambdify`` always prefers ``_imp_`` implementations to implementations in other namespaces, unless the ``use_imps`` input parameter is False. Usage with Tensorflow: >>> import tensorflow as tf >>> from sympy import Max, sin, lambdify >>> from sympy.abc import x >>> f = Max(x, sin(x)) >>> func = lambdify(x, f, 'tensorflow') After tensorflow v2, eager execution is enabled by default. If you want to get the compatible result across tensorflow v1 and v2 as same as this tutorial, run this line. >>> tf.compat.v1.enable_eager_execution() If you have eager execution enabled, you can get the result out immediately as you can use numpy. If you pass tensorflow objects, you may get an ``EagerTensor`` object instead of value. >>> result = func(tf.constant(1.0)) >>> print(result) tf.Tensor(1.0, shape=(), dtype=float32) >>> print(result.__class__) <class 'tensorflow.python.framework.ops.EagerTensor'> You can use ``.numpy()`` to get the numpy value of the tensor. >>> result.numpy() 1.0 >>> var = tf.Variable(2.0) >>> result = func(var) # also works for tf.Variable and tf.Placeholder >>> result.numpy() 2.0 And it works with any shape array. >>> tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]]) >>> result = func(tensor) >>> result.numpy() [[1. 2.] [3. 4.]] Notes ===== - For functions involving large array calculations, numexpr can provide a significant speedup over numpy. Please note that the available functions for numexpr are more limited than numpy but can be expanded with ``implemented_function`` and user defined subclasses of Function. If specified, numexpr may be the only option in modules. The official list of numexpr functions can be found at: https://numexpr.readthedocs.io/en/latest/user_guide.html#supported-functions - In previous versions of SymPy, ``lambdify`` replaced ``Matrix`` with ``numpy.matrix`` by default. As of SymPy 1.0 ``numpy.array`` is the default. To get the old default behavior you must pass in ``[{'ImmutableDenseMatrix': numpy.matrix}, 'numpy']`` to the ``modules`` kwarg. >>> from sympy import lambdify, Matrix >>> from sympy.abc import x, y >>> import numpy >>> array2mat = [{'ImmutableDenseMatrix': numpy.matrix}, 'numpy'] >>> f = lambdify((x, y), Matrix([x, y]), modules=array2mat) >>> f(1, 2) [[1] [2]] - In the above examples, the generated functions can accept scalar values or numpy arrays as arguments. However, in some cases the generated function relies on the input being a numpy array: >>> from sympy import Piecewise >>> from sympy.testing.pytest import ignore_warnings >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "numpy") >>> with ignore_warnings(RuntimeWarning): ... f(numpy.array([-1, 0, 1, 2])) [-1. 0. 1. 0.5] >>> f(0) Traceback (most recent call last): ... ZeroDivisionError: division by zero In such cases, the input should be wrapped in a numpy array: >>> with ignore_warnings(RuntimeWarning): ... float(f(numpy.array([0]))) 0.0 Or if numpy functionality is not required another module can be used: >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "math") >>> f(0) 0 .. _lambdify-how-it-works: How it works ============ When using this function, it helps a great deal to have an idea of what it is doing. At its core, lambdify is nothing more than a namespace translation, on top of a special printer that makes some corner cases work properly. To understand lambdify, first we must properly understand how Python namespaces work. Say we had two files. One called ``sin_cos_sympy.py``, with .. code:: python # sin_cos_sympy.py from sympy import sin, cos def sin_cos(x): return sin(x) + cos(x) and one called ``sin_cos_numpy.py`` with .. code:: python # sin_cos_numpy.py from numpy import sin, cos def sin_cos(x): return sin(x) + cos(x) The two files define an identical function ``sin_cos``. However, in the first file, ``sin`` and ``cos`` are defined as the SymPy ``sin`` and ``cos``. In the second, they are defined as the NumPy versions. If we were to import the first file and use the ``sin_cos`` function, we would get something like >>> from sin_cos_sympy import sin_cos # doctest: +SKIP >>> sin_cos(1) # doctest: +SKIP cos(1) + sin(1) On the other hand, if we imported ``sin_cos`` from the second file, we would get >>> from sin_cos_numpy import sin_cos # doctest: +SKIP >>> sin_cos(1) # doctest: +SKIP 1.38177329068 In the first case we got a symbolic output, because it used the symbolic ``sin`` and ``cos`` functions from SymPy. In the second, we got a numeric result, because ``sin_cos`` used the numeric ``sin`` and ``cos`` functions from NumPy. But notice that the versions of ``sin`` and ``cos`` that were used was not inherent to the ``sin_cos`` function definition. Both ``sin_cos`` definitions are exactly the same. Rather, it was based on the names defined at the module where the ``sin_cos`` function was defined. The key point here is that when function in Python references a name that is not defined in the function, that name is looked up in the "global" namespace of the module where that function is defined. Now, in Python, we can emulate this behavior without actually writing a file to disk using the ``exec`` function. ``exec`` takes a string containing a block of Python code, and a dictionary that should contain the global variables of the module. It then executes the code "in" that dictionary, as if it were the module globals. The following is equivalent to the ``sin_cos`` defined in ``sin_cos_sympy.py``: >>> import sympy >>> module_dictionary = {'sin': sympy.sin, 'cos': sympy.cos} >>> exec(''' ... def sin_cos(x): ... return sin(x) + cos(x) ... ''', module_dictionary) >>> sin_cos = module_dictionary['sin_cos'] >>> sin_cos(1) cos(1) + sin(1) and similarly with ``sin_cos_numpy``: >>> import numpy >>> module_dictionary = {'sin': numpy.sin, 'cos': numpy.cos} >>> exec(''' ... def sin_cos(x): ... return sin(x) + cos(x) ... ''', module_dictionary) >>> sin_cos = module_dictionary['sin_cos'] >>> sin_cos(1) 1.38177329068 So now we can get an idea of how ``lambdify`` works. The name "lambdify" comes from the fact that we can think of something like ``lambdify(x, sin(x) + cos(x), 'numpy')`` as ``lambda x: sin(x) + cos(x)``, where ``sin`` and ``cos`` come from the ``numpy`` namespace. This is also why the symbols argument is first in ``lambdify``, as opposed to most SymPy functions where it comes after the expression: to better mimic the ``lambda`` keyword. ``lambdify`` takes the input expression (like ``sin(x) + cos(x)``) and 1. Converts it to a string 2. Creates a module globals dictionary based on the modules that are passed in (by default, it uses the NumPy module) 3. Creates the string ``"def func({vars}): return {expr}"``, where ``{vars}`` is the list of variables separated by commas, and ``{expr}`` is the string created in step 1., then ``exec``s that string with the module globals namespace and returns ``func``. In fact, functions returned by ``lambdify`` support inspection. So you can see exactly how they are defined by using ``inspect.getsource``, or ``??`` if you are using IPython or the Jupyter notebook. >>> f = lambdify(x, sin(x) + cos(x)) >>> import inspect >>> print(inspect.getsource(f)) def _lambdifygenerated(x): return sin(x) + cos(x) This shows us the source code of the function, but not the namespace it was defined in. We can inspect that by looking at the ``__globals__`` attribute of ``f``: >>> f.__globals__['sin'] <ufunc 'sin'> >>> f.__globals__['cos'] <ufunc 'cos'> >>> f.__globals__['sin'] is numpy.sin True This shows us that ``sin`` and ``cos`` in the namespace of ``f`` will be ``numpy.sin`` and ``numpy.cos``. Note that there are some convenience layers in each of these steps, but at the core, this is how ``lambdify`` works. Step 1 is done using the ``LambdaPrinter`` printers defined in the printing module (see :mod:`sympy.printing.lambdarepr`). This allows different SymPy expressions to define how they should be converted to a string for different modules. You can change which printer ``lambdify`` uses by passing a custom printer in to the ``printer`` argument. Step 2 is augmented by certain translations. There are default translations for each module, but you can provide your own by passing a list to the ``modules`` argument. For instance, >>> def mysin(x): ... print('taking the sin of', x) ... return numpy.sin(x) ... >>> f = lambdify(x, sin(x), [{'sin': mysin}, 'numpy']) >>> f(1) taking the sin of 1 0.8414709848078965 The globals dictionary is generated from the list by merging the dictionary ``{'sin': mysin}`` and the module dictionary for NumPy. The merging is done so that earlier items take precedence, which is why ``mysin`` is used above instead of ``numpy.sin``. If you want to modify the way ``lambdify`` works for a given function, it is usually easiest to do so by modifying the globals dictionary as such. In more complicated cases, it may be necessary to create and pass in a custom printer. Finally, step 3 is augmented with certain convenience operations, such as the addition of a docstring. Understanding how ``lambdify`` works can make it easier to avoid certain gotchas when using it. For instance, a common mistake is to create a lambdified function for one module (say, NumPy), and pass it objects from another (say, a SymPy expression). For instance, say we create >>> from sympy.abc import x >>> f = lambdify(x, x + 1, 'numpy') Now if we pass in a NumPy array, we get that array plus 1 >>> import numpy >>> a = numpy.array([1, 2]) >>> f(a) [2 3] But what happens if you make the mistake of passing in a SymPy expression instead of a NumPy array: >>> f(x + 1) x + 2 This worked, but it was only by accident. Now take a different lambdified function: >>> from sympy import sin >>> g = lambdify(x, x + sin(x), 'numpy') This works as expected on NumPy arrays: >>> g(a) [1.84147098 2.90929743] But if we try to pass in a SymPy expression, it fails >>> try: ... g(x + 1) ... # NumPy release after 1.17 raises TypeError instead of ... # AttributeError ... except (AttributeError, TypeError): ... raise AttributeError() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... AttributeError: Now, let's look at what happened. The reason this fails is that ``g`` calls ``numpy.sin`` on the input expression, and ``numpy.sin`` does not know how to operate on a SymPy object. **As a general rule, NumPy functions do not know how to operate on SymPy expressions, and SymPy functions do not know how to operate on NumPy arrays. This is why lambdify exists: to provide a bridge between SymPy and NumPy.** However, why is it that ``f`` did work? That's because ``f`` doesn't call any functions, it only adds 1. So the resulting function that is created, ``def _lambdifygenerated(x): return x + 1`` does not depend on the globals namespace it is defined in. Thus it works, but only by accident. A future version of ``lambdify`` may remove this behavior. Be aware that certain implementation details described here may change in future versions of SymPy. The API of passing in custom modules and printers will not change, but the details of how a lambda function is created may change. However, the basic idea will remain the same, and understanding it will be helpful to understanding the behavior of lambdify. **In general: you should create lambdified functions for one module (say, NumPy), and only pass it input types that are compatible with that module (say, NumPy arrays).** Remember that by default, if the ``module`` argument is not provided, ``lambdify`` creates functions using the NumPy and SciPy namespaces. """ from sympy.core.symbol import Symbol # If the user hasn't specified any modules, use what is available. if modules is None: try: _import("scipy") except ImportError: try: _import("numpy") except ImportError: # Use either numpy (if available) or python.math where possible. # XXX: This leads to different behaviour on different systems and # might be the reason for irreproducible errors. modules = ["math", "mpmath", "sympy"] else: modules = ["numpy"] else: modules = ["numpy", "scipy"] # Get the needed namespaces. namespaces = [] # First find any function implementations if use_imps: namespaces.append(_imp_namespace(expr)) # Check for dict before iterating if isinstance(modules, (dict, str)) or not hasattr(modules, '__iter__'): namespaces.append(modules) else: # consistency check if _module_present('numexpr', modules) and len(modules) > 1: raise TypeError("numexpr must be the only item in 'modules'") namespaces += list(modules) # fill namespace with first having highest priority namespace = {} # type: Dict[str, Any] for m in namespaces[::-1]: buf = _get_namespace(m) namespace.update(buf) if hasattr(expr, "atoms"): #Try if you can extract symbols from the expression. #Move on if expr.atoms in not implemented. syms = expr.atoms(Symbol) for term in syms: namespace.update({str(term): term}) if printer is None: if _module_present('mpmath', namespaces): from sympy.printing.pycode import MpmathPrinter as Printer # type: ignore elif _module_present('scipy', namespaces): from sympy.printing.numpy import SciPyPrinter as Printer # type: ignore elif _module_present('numpy', namespaces): from sympy.printing.numpy import NumPyPrinter as Printer # type: ignore elif _module_present('cupy', namespaces): from sympy.printing.numpy import CuPyPrinter as Printer # type: ignore elif _module_present('numexpr', namespaces): from sympy.printing.lambdarepr import NumExprPrinter as Printer # type: ignore elif _module_present('tensorflow', namespaces): from sympy.printing.tensorflow import TensorflowPrinter as Printer # type: ignore elif _module_present('sympy', namespaces): from sympy.printing.pycode import SymPyPrinter as Printer # type: ignore else: from sympy.printing.pycode import PythonCodePrinter as Printer # type: ignore user_functions = {} for m in namespaces[::-1]: if isinstance(m, dict): for k in m: user_functions[k] = k printer = Printer({'fully_qualified_modules': False, 'inline': True, 'allow_unknown_functions': True, 'user_functions': user_functions}) if isinstance(args, set): SymPyDeprecationWarning( feature="The list of arguments is a `set`. This leads to unpredictable results", useinstead=": Convert set into list or tuple", issue=20013, deprecated_since_version="1.6.3" ).warn() # Get the names of the args, for creating a docstring if not iterable(args): args = (args,) names = [] # Grab the callers frame, for getting the names by inspection (if needed) callers_local_vars = inspect.currentframe().f_back.f_locals.items() # type: ignore for n, var in enumerate(args): if hasattr(var, 'name'): names.append(var.name) else: # It's an iterable. Try to get name by inspection of calling frame. name_list = [var_name for var_name, var_val in callers_local_vars if var_val is var] if len(name_list) == 1: names.append(name_list[0]) else: # Cannot infer name with certainty. arg_# will have to do. names.append('arg_' + str(n)) # Create the function definition code and execute it funcname = '_lambdifygenerated' if _module_present('tensorflow', namespaces): funcprinter = _TensorflowEvaluatorPrinter(printer, dummify) # type: _EvaluatorPrinter else: funcprinter = _EvaluatorPrinter(printer, dummify) if cse == True: from sympy.simplify.cse_main import cse cses, _expr = cse(expr, list=False) elif callable(cse): cses, _expr = cse(expr) else: cses, _expr = (), expr funcstr = funcprinter.doprint(funcname, args, _expr, cses=cses) # Collect the module imports from the code printers. imp_mod_lines = [] for mod, keys in (getattr(printer, 'module_imports', None) or {}).items(): for k in keys: if k not in namespace: ln = "from %s import %s" % (mod, k) try: exec(ln, {}, namespace) except ImportError: # Tensorflow 2.0 has issues with importing a specific # function from its submodule. # https://github.com/tensorflow/tensorflow/issues/33022 ln = "%s = %s.%s" % (k, mod, k) exec(ln, {}, namespace) imp_mod_lines.append(ln) # Provide lambda expression with builtins, and compatible implementation of range namespace.update({'builtins':builtins, 'range':range}) funclocals = {} # type: Dict[str, Any] global _lambdify_generated_counter filename = '<lambdifygenerated-%s>' % _lambdify_generated_counter _lambdify_generated_counter += 1 c = compile(funcstr, filename, 'exec') exec(c, namespace, funclocals) # mtime has to be None or else linecache.checkcache will remove it linecache.cache[filename] = (len(funcstr), None, funcstr.splitlines(True), filename) # type: ignore func = funclocals[funcname] # Apply the docstring sig = "func({})".format(", ".join(str(i) for i in names)) sig = textwrap.fill(sig, subsequent_indent=' '*8) expr_str = str(expr) if len(expr_str) > 78: expr_str = textwrap.wrap(expr_str, 75)[0] + '...' func.__doc__ = ( "Created with lambdify. Signature:\n\n" "{sig}\n\n" "Expression:\n\n" "{expr}\n\n" "Source code:\n\n" "{src}\n\n" "Imported modules:\n\n" "{imp_mods}" ).format(sig=sig, expr=expr_str, src=funcstr, imp_mods='\n'.join(imp_mod_lines)) return func def _module_present(modname, modlist): if modname in modlist: return True for m in modlist: if hasattr(m, '__name__') and m.__name__ == modname: return True return False def _get_namespace(m): """ This is used by _lambdify to parse its arguments. """ if isinstance(m, str): _import(m) return MODULES[m][0] elif isinstance(m, dict): return m elif hasattr(m, "__dict__"): return m.__dict__ else: raise TypeError("Argument must be either a string, dict or module but it is: %s" % m) def lambdastr(args, expr, printer=None, dummify=None): """ Returns a string that can be evaluated to a lambda function. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.utilities.lambdify import lambdastr >>> lambdastr(x, x**2) 'lambda x: (x**2)' >>> lambdastr((x,y,z), [z,y,x]) 'lambda x,y,z: ([z, y, x])' Although tuples may not appear as arguments to lambda in Python 3, lambdastr will create a lambda function that will unpack the original arguments so that nested arguments can be handled: >>> lambdastr((x, (y, z)), x + y) 'lambda _0,_1: (lambda x,y,z: (x + y))(_0,_1[0],_1[1])' """ # Transforming everything to strings. from sympy.matrices import DeferredVector from sympy import Dummy, sympify, Symbol, Function, flatten, Derivative, Basic if printer is not None: if inspect.isfunction(printer): lambdarepr = printer else: if inspect.isclass(printer): lambdarepr = lambda expr: printer().doprint(expr) else: lambdarepr = lambda expr: printer.doprint(expr) else: #XXX: This has to be done here because of circular imports from sympy.printing.lambdarepr import lambdarepr def sub_args(args, dummies_dict): if isinstance(args, str): return args elif isinstance(args, DeferredVector): return str(args) elif iterable(args): dummies = flatten([sub_args(a, dummies_dict) for a in args]) return ",".join(str(a) for a in dummies) else: # replace these with Dummy symbols if isinstance(args, (Function, Symbol, Derivative)): dummies = Dummy() dummies_dict.update({args : dummies}) return str(dummies) else: return str(args) def sub_expr(expr, dummies_dict): expr = sympify(expr) # dict/tuple are sympified to Basic if isinstance(expr, Basic): expr = expr.xreplace(dummies_dict) # list is not sympified to Basic elif isinstance(expr, list): expr = [sub_expr(a, dummies_dict) for a in expr] return expr # Transform args def isiter(l): return iterable(l, exclude=(str, DeferredVector, NotIterable)) def flat_indexes(iterable): n = 0 for el in iterable: if isiter(el): for ndeep in flat_indexes(el): yield (n,) + ndeep else: yield (n,) n += 1 if dummify is None: dummify = any(isinstance(a, Basic) and a.atoms(Function, Derivative) for a in ( args if isiter(args) else [args])) if isiter(args) and any(isiter(i) for i in args): dum_args = [str(Dummy(str(i))) for i in range(len(args))] indexed_args = ','.join([ dum_args[ind[0]] + ''.join(["[%s]" % k for k in ind[1:]]) for ind in flat_indexes(args)]) lstr = lambdastr(flatten(args), expr, printer=printer, dummify=dummify) return 'lambda %s: (%s)(%s)' % (','.join(dum_args), lstr, indexed_args) dummies_dict = {} if dummify: args = sub_args(args, dummies_dict) else: if isinstance(args, str): pass elif iterable(args, exclude=DeferredVector): args = ",".join(str(a) for a in args) # Transform expr if dummify: if isinstance(expr, str): pass else: expr = sub_expr(expr, dummies_dict) expr = lambdarepr(expr) return "lambda %s: (%s)" % (args, expr) class _EvaluatorPrinter: def __init__(self, printer=None, dummify=False): self._dummify = dummify #XXX: This has to be done here because of circular imports from sympy.printing.lambdarepr import LambdaPrinter if printer is None: printer = LambdaPrinter() if inspect.isfunction(printer): self._exprrepr = printer else: if inspect.isclass(printer): printer = printer() self._exprrepr = printer.doprint #if hasattr(printer, '_print_Symbol'): # symbolrepr = printer._print_Symbol #if hasattr(printer, '_print_Dummy'): # dummyrepr = printer._print_Dummy # Used to print the generated function arguments in a standard way self._argrepr = LambdaPrinter().doprint def doprint(self, funcname, args, expr, *, cses=()): """ Returns the function definition code as a string. """ from sympy import Dummy funcbody = [] if not iterable(args): args = [args] argstrs, expr = self._preprocess(args, expr) # Generate argument unpacking and final argument list funcargs = [] unpackings = [] for argstr in argstrs: if iterable(argstr): funcargs.append(self._argrepr(Dummy())) unpackings.extend(self._print_unpacking(argstr, funcargs[-1])) else: funcargs.append(argstr) funcsig = 'def {}({}):'.format(funcname, ', '.join(funcargs)) # Wrap input arguments before unpacking funcbody.extend(self._print_funcargwrapping(funcargs)) funcbody.extend(unpackings) funcbody.extend(['{} = {}'.format(s, self._exprrepr(e)) for s, e in cses]) str_expr = self._exprrepr(expr) if '\n' in str_expr: str_expr = '({})'.format(str_expr) funcbody.append('return {}'.format(str_expr)) funclines = [funcsig] funclines.extend([' ' + line for line in funcbody]) return '\n'.join(funclines) + '\n' @classmethod def _is_safe_ident(cls, ident): return isinstance(ident, str) and ident.isidentifier() \ and not keyword.iskeyword(ident) def _preprocess(self, args, expr): """Preprocess args, expr to replace arguments that do not map to valid Python identifiers. Returns string form of args, and updated expr. """ from sympy import Dummy, Function, flatten, Derivative, ordered, Basic from sympy.matrices import DeferredVector from sympy.core.symbol import uniquely_named_symbol from sympy.core.expr import Expr # Args of type Dummy can cause name collisions with args # of type Symbol. Force dummify of everything in this # situation. dummify = self._dummify or any( isinstance(arg, Dummy) for arg in flatten(args)) argstrs = [None]*len(args) for arg, i in reversed(list(ordered(zip(args, range(len(args)))))): if iterable(arg): s, expr = self._preprocess(arg, expr) elif isinstance(arg, DeferredVector): s = str(arg) elif isinstance(arg, Basic) and arg.is_symbol: s = self._argrepr(arg) if dummify or not self._is_safe_ident(s): dummy = Dummy() if isinstance(expr, Expr): dummy = uniquely_named_symbol( dummy.name, expr, modify=lambda s: '_' + s) s = self._argrepr(dummy) expr = self._subexpr(expr, {arg: dummy}) elif dummify or isinstance(arg, (Function, Derivative)): dummy = Dummy() s = self._argrepr(dummy) expr = self._subexpr(expr, {arg: dummy}) else: s = str(arg) argstrs[i] = s return argstrs, expr def _subexpr(self, expr, dummies_dict): from sympy.matrices import DeferredVector from sympy import sympify expr = sympify(expr) xreplace = getattr(expr, 'xreplace', None) if xreplace is not None: expr = xreplace(dummies_dict) else: if isinstance(expr, DeferredVector): pass elif isinstance(expr, dict): k = [self._subexpr(sympify(a), dummies_dict) for a in expr.keys()] v = [self._subexpr(sympify(a), dummies_dict) for a in expr.values()] expr = dict(zip(k, v)) elif isinstance(expr, tuple): expr = tuple(self._subexpr(sympify(a), dummies_dict) for a in expr) elif isinstance(expr, list): expr = [self._subexpr(sympify(a), dummies_dict) for a in expr] return expr def _print_funcargwrapping(self, args): """Generate argument wrapping code. args is the argument list of the generated function (strings). Return value is a list of lines of code that will be inserted at the beginning of the function definition. """ return [] def _print_unpacking(self, unpackto, arg): """Generate argument unpacking code. arg is the function argument to be unpacked (a string), and unpackto is a list or nested lists of the variable names (strings) to unpack to. """ def unpack_lhs(lvalues): return '[{}]'.format(', '.join( unpack_lhs(val) if iterable(val) else val for val in lvalues)) return ['{} = {}'.format(unpack_lhs(unpackto), arg)] class _TensorflowEvaluatorPrinter(_EvaluatorPrinter): def _print_unpacking(self, lvalues, rvalue): """Generate argument unpacking code. This method is used when the input value is not interable, but can be indexed (see issue #14655). """ from sympy import flatten def flat_indexes(elems): n = 0 for el in elems: if iterable(el): for ndeep in flat_indexes(el): yield (n,) + ndeep else: yield (n,) n += 1 indexed = ', '.join('{}[{}]'.format(rvalue, ']['.join(map(str, ind))) for ind in flat_indexes(lvalues)) return ['[{}] = [{}]'.format(', '.join(flatten(lvalues)), indexed)] def _imp_namespace(expr, namespace=None): """ Return namespace dict with function implementations We need to search for functions in anything that can be thrown at us - that is - anything that could be passed as ``expr``. Examples include sympy expressions, as well as tuples, lists and dicts that may contain sympy expressions. Parameters ---------- expr : object Something passed to lambdify, that will generate valid code from ``str(expr)``. namespace : None or mapping Namespace to fill. None results in new empty dict Returns ------- namespace : dict dict with keys of implemented function names within ``expr`` and corresponding values being the numerical implementation of function Examples ======== >>> from sympy.abc import x >>> from sympy.utilities.lambdify import implemented_function, _imp_namespace >>> from sympy import Function >>> f = implemented_function(Function('f'), lambda x: x+1) >>> g = implemented_function(Function('g'), lambda x: x*10) >>> namespace = _imp_namespace(f(g(x))) >>> sorted(namespace.keys()) ['f', 'g'] """ # Delayed import to avoid circular imports from sympy.core.function import FunctionClass if namespace is None: namespace = {} # tuples, lists, dicts are valid expressions if is_sequence(expr): for arg in expr: _imp_namespace(arg, namespace) return namespace elif isinstance(expr, dict): for key, val in expr.items(): # functions can be in dictionary keys _imp_namespace(key, namespace) _imp_namespace(val, namespace) return namespace # sympy expressions may be Functions themselves func = getattr(expr, 'func', None) if isinstance(func, FunctionClass): imp = getattr(func, '_imp_', None) if imp is not None: name = expr.func.__name__ if name in namespace and namespace[name] != imp: raise ValueError('We found more than one ' 'implementation with name ' '"%s"' % name) namespace[name] = imp # and / or they may take Functions as arguments if hasattr(expr, 'args'): for arg in expr.args: _imp_namespace(arg, namespace) return namespace def implemented_function(symfunc, implementation): """ Add numerical ``implementation`` to function ``symfunc``. ``symfunc`` can be an ``UndefinedFunction`` instance, or a name string. In the latter case we create an ``UndefinedFunction`` instance with that name. Be aware that this is a quick workaround, not a general method to create special symbolic functions. If you want to create a symbolic function to be used by all the machinery of SymPy you should subclass the ``Function`` class. Parameters ---------- symfunc : ``str`` or ``UndefinedFunction`` instance If ``str``, then create new ``UndefinedFunction`` with this as name. If ``symfunc`` is an Undefined function, create a new function with the same name and the implemented function attached. implementation : callable numerical implementation to be called by ``evalf()`` or ``lambdify`` Returns ------- afunc : sympy.FunctionClass instance function with attached implementation Examples ======== >>> from sympy.abc import x >>> from sympy.utilities.lambdify import lambdify, implemented_function >>> f = implemented_function('f', lambda x: x+1) >>> lam_f = lambdify(x, f(x)) >>> lam_f(4) 5 """ # Delayed import to avoid circular imports from sympy.core.function import UndefinedFunction # if name, create function to hold implementation kwargs = {} if isinstance(symfunc, UndefinedFunction): kwargs = symfunc._kwargs symfunc = symfunc.__name__ if isinstance(symfunc, str): # Keyword arguments to UndefinedFunction are added as attributes to # the created class. symfunc = UndefinedFunction( symfunc, _imp_=staticmethod(implementation), **kwargs) elif not isinstance(symfunc, UndefinedFunction): raise ValueError(filldedent(''' symfunc should be either a string or an UndefinedFunction instance.''')) return symfunc
c3a38c96c4b3e3f58a7b7852ad3c2489f82228807b3dde79465096559bba7506
from collections import defaultdict, OrderedDict from itertools import ( combinations, combinations_with_replacement, permutations, product ) from itertools import product as cartes # noqa: F401 import random from operator import gt from sympy.core import Basic # this is the logical location of these functions from sympy.core.compatibility import (as_int, is_sequence, iterable, ordered) from sympy.core.compatibility import default_sort_key # noqa: F401 from sympy.utilities.enumerative import ( multiset_partitions_taocp, list_visitor, MultisetPartitionTraverser) def is_palindromic(s, i=0, j=None): """return True if the sequence is the same from left to right as it is from right to left in the whole sequence (default) or in the Python slice ``s[i: j]``; else False. Examples ======== >>> from sympy.utilities.iterables import is_palindromic >>> is_palindromic([1, 0, 1]) True >>> is_palindromic('abcbb') False >>> is_palindromic('abcbb', 1) False Normal Python slicing is performed in place so there is no need to create a slice of the sequence for testing: >>> is_palindromic('abcbb', 1, -1) True >>> is_palindromic('abcbb', -4, -1) True See Also ======== sympy.ntheory.digits.is_palindromic: tests integers """ i, j, _ = slice(i, j).indices(len(s)) m = (j - i)//2 # if length is odd, middle element will be ignored return all(s[i + k] == s[j - 1 - k] for k in range(m)) def flatten(iterable, levels=None, cls=None): """ Recursively denest iterable containers. >>> from sympy.utilities.iterables import flatten >>> flatten([1, 2, 3]) [1, 2, 3] >>> flatten([1, 2, [3]]) [1, 2, 3] >>> flatten([1, [2, 3], [4, 5]]) [1, 2, 3, 4, 5] >>> flatten([1.0, 2, (1, None)]) [1.0, 2, 1, None] If you want to denest only a specified number of levels of nested containers, then set ``levels`` flag to the desired number of levels:: >>> ls = [[(-2, -1), (1, 2)], [(0, 0)]] >>> flatten(ls, levels=1) [(-2, -1), (1, 2), (0, 0)] If cls argument is specified, it will only flatten instances of that class, for example: >>> from sympy.core import Basic >>> class MyOp(Basic): ... pass ... >>> flatten([MyOp(1, MyOp(2, 3))], cls=MyOp) [1, 2, 3] adapted from https://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks """ from sympy.tensor.array import NDimArray if levels is not None: if not levels: return iterable elif levels > 0: levels -= 1 else: raise ValueError( "expected non-negative number of levels, got %s" % levels) if cls is None: reducible = lambda x: is_sequence(x, set) else: reducible = lambda x: isinstance(x, cls) result = [] for el in iterable: if reducible(el): if hasattr(el, 'args') and not isinstance(el, NDimArray): el = el.args result.extend(flatten(el, levels=levels, cls=cls)) else: result.append(el) return result def unflatten(iter, n=2): """Group ``iter`` into tuples of length ``n``. Raise an error if the length of ``iter`` is not a multiple of ``n``. """ if n < 1 or len(iter) % n: raise ValueError('iter length is not a multiple of %i' % n) return list(zip(*(iter[i::n] for i in range(n)))) def reshape(seq, how): """Reshape the sequence according to the template in ``how``. Examples ======== >>> from sympy.utilities import reshape >>> seq = list(range(1, 9)) >>> reshape(seq, [4]) # lists of 4 [[1, 2, 3, 4], [5, 6, 7, 8]] >>> reshape(seq, (4,)) # tuples of 4 [(1, 2, 3, 4), (5, 6, 7, 8)] >>> reshape(seq, (2, 2)) # tuples of 4 [(1, 2, 3, 4), (5, 6, 7, 8)] >>> reshape(seq, (2, [2])) # (i, i, [i, i]) [(1, 2, [3, 4]), (5, 6, [7, 8])] >>> reshape(seq, ((2,), [2])) # etc.... [((1, 2), [3, 4]), ((5, 6), [7, 8])] >>> reshape(seq, (1, [2], 1)) [(1, [2, 3], 4), (5, [6, 7], 8)] >>> reshape(tuple(seq), ([[1], 1, (2,)],)) (([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],)) >>> reshape(tuple(seq), ([1], 1, (2,))) (([1], 2, (3, 4)), ([5], 6, (7, 8))) >>> reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)]) [[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]] """ m = sum(flatten(how)) n, rem = divmod(len(seq), m) if m < 0 or rem: raise ValueError('template must sum to positive number ' 'that divides the length of the sequence') i = 0 container = type(how) rv = [None]*n for k in range(len(rv)): rv[k] = [] for hi in how: if type(hi) is int: rv[k].extend(seq[i: i + hi]) i += hi else: n = sum(flatten(hi)) hi_type = type(hi) rv[k].append(hi_type(reshape(seq[i: i + n], hi)[0])) i += n rv[k] = container(rv[k]) return type(seq)(rv) def group(seq, multiple=True): """ Splits a sequence into a list of lists of equal, adjacent elements. Examples ======== >>> from sympy.utilities.iterables import group >>> group([1, 1, 1, 2, 2, 3]) [[1, 1, 1], [2, 2], [3]] >>> group([1, 1, 1, 2, 2, 3], multiple=False) [(1, 3), (2, 2), (3, 1)] >>> group([1, 1, 3, 2, 2, 1], multiple=False) [(1, 2), (3, 1), (2, 2), (1, 1)] See Also ======== multiset """ if not seq: return [] current, groups = [seq[0]], [] for elem in seq[1:]: if elem == current[-1]: current.append(elem) else: groups.append(current) current = [elem] groups.append(current) if multiple: return groups for i, current in enumerate(groups): groups[i] = (current[0], len(current)) return groups def _iproduct2(iterable1, iterable2): '''Cartesian product of two possibly infinite iterables''' it1 = iter(iterable1) it2 = iter(iterable2) elems1 = [] elems2 = [] sentinel = object() def append(it, elems): e = next(it, sentinel) if e is not sentinel: elems.append(e) n = 0 append(it1, elems1) append(it2, elems2) while n <= len(elems1) + len(elems2): for m in range(n-len(elems1)+1, len(elems2)): yield (elems1[n-m], elems2[m]) n += 1 append(it1, elems1) append(it2, elems2) def iproduct(*iterables): ''' Cartesian product of iterables. Generator of the cartesian product of iterables. This is analogous to itertools.product except that it works with infinite iterables and will yield any item from the infinite product eventually. Examples ======== >>> from sympy.utilities.iterables import iproduct >>> sorted(iproduct([1,2], [3,4])) [(1, 3), (1, 4), (2, 3), (2, 4)] With an infinite iterator: >>> from sympy import S >>> (3,) in iproduct(S.Integers) True >>> (3, 4) in iproduct(S.Integers, S.Integers) True .. seealso:: `itertools.product <https://docs.python.org/3/library/itertools.html#itertools.product>`_ ''' if len(iterables) == 0: yield () return elif len(iterables) == 1: for e in iterables[0]: yield (e,) elif len(iterables) == 2: yield from _iproduct2(*iterables) else: first, others = iterables[0], iterables[1:] for ef, eo in _iproduct2(first, iproduct(*others)): yield (ef,) + eo def multiset(seq): """Return the hashable sequence in multiset form with values being the multiplicity of the item in the sequence. Examples ======== >>> from sympy.utilities.iterables import multiset >>> multiset('mississippi') {'i': 4, 'm': 1, 'p': 2, 's': 4} See Also ======== group """ rv = defaultdict(int) for s in seq: rv[s] += 1 return dict(rv) def postorder_traversal(node, keys=None): """ Do a postorder traversal of a tree. This generator recursively yields nodes that it has visited in a postorder fashion. That is, it descends through the tree depth-first to yield all of a node's children's postorder traversal before yielding the node itself. Parameters ========== node : sympy expression The expression to traverse. keys : (default None) sort key(s) The key(s) used to sort args of Basic objects. When None, args of Basic objects are processed in arbitrary order. If key is defined, it will be passed along to ordered() as the only key(s) to use to sort the arguments; if ``key`` is simply True then the default keys of ``ordered`` will be used (node count and default_sort_key). Yields ====== subtree : sympy expression All of the subtrees in the tree. Examples ======== >>> from sympy.utilities.iterables import postorder_traversal >>> from sympy.abc import w, x, y, z The nodes are returned in the order that they are encountered unless key is given; simply passing key=True will guarantee that the traversal is unique. >>> list(postorder_traversal(w + (x + y)*z)) # doctest: +SKIP [z, y, x, x + y, z*(x + y), w, w + z*(x + y)] >>> list(postorder_traversal(w + (x + y)*z, keys=True)) [w, z, x, y, x + y, z*(x + y), w + z*(x + y)] """ if isinstance(node, Basic): args = node.args if keys: if keys != True: args = ordered(args, keys, default=False) else: args = ordered(args) for arg in args: yield from postorder_traversal(arg, keys) elif iterable(node): for item in node: yield from postorder_traversal(item, keys) yield node def interactive_traversal(expr): """Traverse a tree asking a user which branch to choose. """ from sympy.printing import pprint RED, BRED = '\033[0;31m', '\033[1;31m' GREEN, BGREEN = '\033[0;32m', '\033[1;32m' YELLOW, BYELLOW = '\033[0;33m', '\033[1;33m' # noqa BLUE, BBLUE = '\033[0;34m', '\033[1;34m' # noqa MAGENTA, BMAGENTA = '\033[0;35m', '\033[1;35m'# noqa CYAN, BCYAN = '\033[0;36m', '\033[1;36m' # noqa END = '\033[0m' def cprint(*args): print("".join(map(str, args)) + END) def _interactive_traversal(expr, stage): if stage > 0: print() cprint("Current expression (stage ", BYELLOW, stage, END, "):") print(BCYAN) pprint(expr) print(END) if isinstance(expr, Basic): if expr.is_Add: args = expr.as_ordered_terms() elif expr.is_Mul: args = expr.as_ordered_factors() else: args = expr.args elif hasattr(expr, "__iter__"): args = list(expr) else: return expr n_args = len(args) if not n_args: return expr for i, arg in enumerate(args): cprint(GREEN, "[", BGREEN, i, GREEN, "] ", BLUE, type(arg), END) pprint(arg) print() if n_args == 1: choices = '0' else: choices = '0-%d' % (n_args - 1) try: choice = input("Your choice [%s,f,l,r,d,?]: " % choices) except EOFError: result = expr print() else: if choice == '?': cprint(RED, "%s - select subexpression with the given index" % choices) cprint(RED, "f - select the first subexpression") cprint(RED, "l - select the last subexpression") cprint(RED, "r - select a random subexpression") cprint(RED, "d - done\n") result = _interactive_traversal(expr, stage) elif choice in ('d', ''): result = expr elif choice == 'f': result = _interactive_traversal(args[0], stage + 1) elif choice == 'l': result = _interactive_traversal(args[-1], stage + 1) elif choice == 'r': result = _interactive_traversal(random.choice(args), stage + 1) else: try: choice = int(choice) except ValueError: cprint(BRED, "Choice must be a number in %s range\n" % choices) result = _interactive_traversal(expr, stage) else: if choice < 0 or choice >= n_args: cprint(BRED, "Choice must be in %s range\n" % choices) result = _interactive_traversal(expr, stage) else: result = _interactive_traversal(args[choice], stage + 1) return result return _interactive_traversal(expr, 0) def ibin(n, bits=None, str=False): """Return a list of length ``bits`` corresponding to the binary value of ``n`` with small bits to the right (last). If bits is omitted, the length will be the number required to represent ``n``. If the bits are desired in reversed order, use the ``[::-1]`` slice of the returned list. If a sequence of all bits-length lists starting from ``[0, 0,..., 0]`` through ``[1, 1, ..., 1]`` are desired, pass a non-integer for bits, e.g. ``'all'``. If the bit *string* is desired pass ``str=True``. Examples ======== >>> from sympy.utilities.iterables import ibin >>> ibin(2) [1, 0] >>> ibin(2, 4) [0, 0, 1, 0] If all lists corresponding to 0 to 2**n - 1, pass a non-integer for bits: >>> bits = 2 >>> for i in ibin(2, 'all'): ... print(i) (0, 0) (0, 1) (1, 0) (1, 1) If a bit string is desired of a given length, use str=True: >>> n = 123 >>> bits = 10 >>> ibin(n, bits, str=True) '0001111011' >>> ibin(n, bits, str=True)[::-1] # small bits left '1101111000' >>> list(ibin(3, 'all', str=True)) ['000', '001', '010', '011', '100', '101', '110', '111'] """ if n < 0: raise ValueError("negative numbers are not allowed") n = as_int(n) if bits is None: bits = 0 else: try: bits = as_int(bits) except ValueError: bits = -1 else: if n.bit_length() > bits: raise ValueError( "`bits` must be >= {}".format(n.bit_length())) if not str: if bits >= 0: return [1 if i == "1" else 0 for i in bin(n)[2:].rjust(bits, "0")] else: return variations(list(range(2)), n, repetition=True) else: if bits >= 0: return bin(n)[2:].rjust(bits, "0") else: return (bin(i)[2:].rjust(n, "0") for i in range(2**n)) def variations(seq, n, repetition=False): r"""Returns a generator of the n-sized variations of ``seq`` (size N). ``repetition`` controls whether items in ``seq`` can appear more than once; Examples ======== ``variations(seq, n)`` will return `\frac{N!}{(N - n)!}` permutations without repetition of ``seq``'s elements: >>> from sympy.utilities.iterables import variations >>> list(variations([1, 2], 2)) [(1, 2), (2, 1)] ``variations(seq, n, True)`` will return the `N^n` permutations obtained by allowing repetition of elements: >>> list(variations([1, 2], 2, repetition=True)) [(1, 1), (1, 2), (2, 1), (2, 2)] If you ask for more items than are in the set you get the empty set unless you allow repetitions: >>> list(variations([0, 1], 3, repetition=False)) [] >>> list(variations([0, 1], 3, repetition=True))[:4] [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1)] .. seealso:: `itertools.permutations <https://docs.python.org/3/library/itertools.html#itertools.permutations>`_, `itertools.product <https://docs.python.org/3/library/itertools.html#itertools.product>`_ """ if not repetition: seq = tuple(seq) if len(seq) < n: return yield from permutations(seq, n) else: if n == 0: yield () else: yield from product(seq, repeat=n) def subsets(seq, k=None, repetition=False): r"""Generates all `k`-subsets (combinations) from an `n`-element set, ``seq``. A `k`-subset of an `n`-element set is any subset of length exactly `k`. The number of `k`-subsets of an `n`-element set is given by ``binomial(n, k)``, whereas there are `2^n` subsets all together. If `k` is ``None`` then all `2^n` subsets will be returned from shortest to longest. Examples ======== >>> from sympy.utilities.iterables import subsets ``subsets(seq, k)`` will return the `\frac{n!}{k!(n - k)!}` `k`-subsets (combinations) without repetition, i.e. once an item has been removed, it can no longer be "taken": >>> list(subsets([1, 2], 2)) [(1, 2)] >>> list(subsets([1, 2])) [(), (1,), (2,), (1, 2)] >>> list(subsets([1, 2, 3], 2)) [(1, 2), (1, 3), (2, 3)] ``subsets(seq, k, repetition=True)`` will return the `\frac{(n - 1 + k)!}{k!(n - 1)!}` combinations *with* repetition: >>> list(subsets([1, 2], 2, repetition=True)) [(1, 1), (1, 2), (2, 2)] If you ask for more items than are in the set you get the empty set unless you allow repetitions: >>> list(subsets([0, 1], 3, repetition=False)) [] >>> list(subsets([0, 1], 3, repetition=True)) [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)] """ if k is None: for k in range(len(seq) + 1): yield from subsets(seq, k, repetition) else: if not repetition: yield from combinations(seq, k) else: yield from combinations_with_replacement(seq, k) def filter_symbols(iterator, exclude): """ Only yield elements from `iterator` that do not occur in `exclude`. Parameters ========== iterator : iterable iterator to take elements from exclude : iterable elements to exclude Returns ======= iterator : iterator filtered iterator """ exclude = set(exclude) for s in iterator: if s not in exclude: yield s def numbered_symbols(prefix='x', cls=None, start=0, exclude=(), *args, **assumptions): """ Generate an infinite stream of Symbols consisting of a prefix and increasing subscripts provided that they do not occur in ``exclude``. Parameters ========== prefix : str, optional The prefix to use. By default, this function will generate symbols of the form "x0", "x1", etc. cls : class, optional The class to use. By default, it uses ``Symbol``, but you can also use ``Wild`` or ``Dummy``. start : int, optional The start number. By default, it is 0. Returns ======= sym : Symbol The subscripted symbols. """ exclude = set(exclude or []) if cls is None: # We can't just make the default cls=Symbol because it isn't # imported yet. from sympy.core import Symbol cls = Symbol while True: name = '%s%s' % (prefix, start) s = cls(name, *args, **assumptions) if s not in exclude: yield s start += 1 def capture(func): """Return the printed output of func(). ``func`` should be a function without arguments that produces output with print statements. >>> from sympy.utilities.iterables import capture >>> from sympy import pprint >>> from sympy.abc import x >>> def foo(): ... print('hello world!') ... >>> 'hello' in capture(foo) # foo, not foo() True >>> capture(lambda: pprint(2/x)) '2\\n-\\nx\\n' """ from io import StringIO import sys stdout = sys.stdout sys.stdout = file = StringIO() try: func() finally: sys.stdout = stdout return file.getvalue() def sift(seq, keyfunc, binary=False): """ Sift the sequence, ``seq`` according to ``keyfunc``. Returns ======= When ``binary`` is ``False`` (default), the output is a dictionary where elements of ``seq`` are stored in a list keyed to the value of keyfunc for that element. If ``binary`` is True then a tuple with lists ``T`` and ``F`` are returned where ``T`` is a list containing elements of seq for which ``keyfunc`` was ``True`` and ``F`` containing those elements for which ``keyfunc`` was ``False``; a ValueError is raised if the ``keyfunc`` is not binary. Examples ======== >>> from sympy.utilities import sift >>> from sympy.abc import x, y >>> from sympy import sqrt, exp, pi, Tuple >>> sift(range(5), lambda x: x % 2) {0: [0, 2, 4], 1: [1, 3]} sift() returns a defaultdict() object, so any key that has no matches will give []. >>> sift([x], lambda x: x.is_commutative) {True: [x]} >>> _[False] [] Sometimes you will not know how many keys you will get: >>> sift([sqrt(x), exp(x), (y**x)**2], ... lambda x: x.as_base_exp()[0]) {E: [exp(x)], x: [sqrt(x)], y: [y**(2*x)]} Sometimes you expect the results to be binary; the results can be unpacked by setting ``binary`` to True: >>> sift(range(4), lambda x: x % 2, binary=True) ([1, 3], [0, 2]) >>> sift(Tuple(1, pi), lambda x: x.is_rational, binary=True) ([1], [pi]) A ValueError is raised if the predicate was not actually binary (which is a good test for the logic where sifting is used and binary results were expected): >>> unknown = exp(1) - pi # the rationality of this is unknown >>> args = Tuple(1, pi, unknown) >>> sift(args, lambda x: x.is_rational, binary=True) Traceback (most recent call last): ... ValueError: keyfunc gave non-binary output The non-binary sifting shows that there were 3 keys generated: >>> set(sift(args, lambda x: x.is_rational).keys()) {None, False, True} If you need to sort the sifted items it might be better to use ``ordered`` which can economically apply multiple sort keys to a sequence while sorting. See Also ======== ordered """ if not binary: m = defaultdict(list) for i in seq: m[keyfunc(i)].append(i) return m sift = F, T = [], [] for i in seq: try: sift[keyfunc(i)].append(i) except (IndexError, TypeError): raise ValueError('keyfunc gave non-binary output') return T, F def take(iter, n): """Return ``n`` items from ``iter`` iterator. """ return [ value for _, value in zip(range(n), iter) ] def dict_merge(*dicts): """Merge dictionaries into a single dictionary. """ merged = {} for dict in dicts: merged.update(dict) return merged def common_prefix(*seqs): """Return the subsequence that is a common start of sequences in ``seqs``. >>> from sympy.utilities.iterables import common_prefix >>> common_prefix(list(range(3))) [0, 1, 2] >>> common_prefix(list(range(3)), list(range(4))) [0, 1, 2] >>> common_prefix([1, 2, 3], [1, 2, 5]) [1, 2] >>> common_prefix([1, 2, 3], [1, 3, 5]) [1] """ if not all(seqs): return [] elif len(seqs) == 1: return seqs[0] i = 0 for i in range(min(len(s) for s in seqs)): if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))): break else: i += 1 return seqs[0][:i] def common_suffix(*seqs): """Return the subsequence that is a common ending of sequences in ``seqs``. >>> from sympy.utilities.iterables import common_suffix >>> common_suffix(list(range(3))) [0, 1, 2] >>> common_suffix(list(range(3)), list(range(4))) [] >>> common_suffix([1, 2, 3], [9, 2, 3]) [2, 3] >>> common_suffix([1, 2, 3], [9, 7, 3]) [3] """ if not all(seqs): return [] elif len(seqs) == 1: return seqs[0] i = 0 for i in range(-1, -min(len(s) for s in seqs) - 1, -1): if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))): break else: i -= 1 if i == -1: return [] else: return seqs[0][i + 1:] def prefixes(seq): """ Generate all prefixes of a sequence. Examples ======== >>> from sympy.utilities.iterables import prefixes >>> list(prefixes([1,2,3,4])) [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]] """ n = len(seq) for i in range(n): yield seq[:i + 1] def postfixes(seq): """ Generate all postfixes of a sequence. Examples ======== >>> from sympy.utilities.iterables import postfixes >>> list(postfixes([1,2,3,4])) [[4], [3, 4], [2, 3, 4], [1, 2, 3, 4]] """ n = len(seq) for i in range(n): yield seq[n - i - 1:] def topological_sort(graph, key=None): r""" Topological sort of graph's vertices. Parameters ========== graph : tuple[list, list[tuple[T, T]] A tuple consisting of a list of vertices and a list of edges of a graph to be sorted topologically. key : callable[T] (optional) Ordering key for vertices on the same level. By default the natural (e.g. lexicographic) ordering is used (in this case the base type must implement ordering relations). Examples ======== Consider a graph:: +---+ +---+ +---+ | 7 |\ | 5 | | 3 | +---+ \ +---+ +---+ | _\___/ ____ _/ | | / \___/ \ / | V V V V | +----+ +---+ | | 11 | | 8 | | +----+ +---+ | | | \____ ___/ _ | | \ \ / / \ | V \ V V / V V +---+ \ +---+ | +----+ | 2 | | | 9 | | | 10 | +---+ | +---+ | +----+ \________/ where vertices are integers. This graph can be encoded using elementary Python's data structures as follows:: >>> V = [2, 3, 5, 7, 8, 9, 10, 11] >>> E = [(7, 11), (7, 8), (5, 11), (3, 8), (3, 10), ... (11, 2), (11, 9), (11, 10), (8, 9)] To compute a topological sort for graph ``(V, E)`` issue:: >>> from sympy.utilities.iterables import topological_sort >>> topological_sort((V, E)) [3, 5, 7, 8, 11, 2, 9, 10] If specific tie breaking approach is needed, use ``key`` parameter:: >>> topological_sort((V, E), key=lambda v: -v) [7, 5, 11, 3, 10, 8, 9, 2] Only acyclic graphs can be sorted. If the input graph has a cycle, then ``ValueError`` will be raised:: >>> topological_sort((V, E + [(10, 7)])) Traceback (most recent call last): ... ValueError: cycle detected References ========== .. [1] https://en.wikipedia.org/wiki/Topological_sorting """ V, E = graph L = [] S = set(V) E = list(E) for v, u in E: S.discard(u) if key is None: key = lambda value: value S = sorted(S, key=key, reverse=True) while S: node = S.pop() L.append(node) for u, v in list(E): if u == node: E.remove((u, v)) for _u, _v in E: if v == _v: break else: kv = key(v) for i, s in enumerate(S): ks = key(s) if kv > ks: S.insert(i, v) break else: S.append(v) if E: raise ValueError("cycle detected") else: return L def strongly_connected_components(G): r""" Strongly connected components of a directed graph in reverse topological order. Parameters ========== graph : tuple[list, list[tuple[T, T]] A tuple consisting of a list of vertices and a list of edges of a graph whose strongly connected components are to be found. Examples ======== Consider a directed graph (in dot notation):: digraph { A -> B A -> C B -> C C -> B B -> D } where vertices are the letters A, B, C and D. This graph can be encoded using Python's elementary data structures as follows:: >>> V = ['A', 'B', 'C', 'D'] >>> E = [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'B'), ('B', 'D')] The strongly connected components of this graph can be computed as >>> from sympy.utilities.iterables import strongly_connected_components >>> strongly_connected_components((V, E)) [['D'], ['B', 'C'], ['A']] This also gives the components in reverse topological order. Since the subgraph containing B and C has a cycle they must be together in a strongly connected component. A and D are connected to the rest of the graph but not in a cyclic manner so they appear as their own strongly connected components. Notes ===== The vertices of the graph must be hashable for the data structures used. If the vertices are unhashable replace them with integer indices. This function uses Tarjan's algorithm to compute the strongly connected components in `O(|V|+|E|)` (linear) time. References ========== .. [1] https://en.wikipedia.org/wiki/Strongly_connected_component .. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm See Also ======== sympy.utilities.iterables.connected_components """ # Map from a vertex to its neighbours V, E = G Gmap = {vi: [] for vi in V} for v1, v2 in E: Gmap[v1].append(v2) return _strongly_connected_components(V, Gmap) def _strongly_connected_components(V, Gmap): """More efficient internal routine for strongly_connected_components""" # # Here V is an iterable of vertices and Gmap is a dict mapping each vertex # to a list of neighbours e.g.: # # V = [0, 1, 2, 3] # Gmap = {0: [2, 3], 1: [0]} # # For a large graph these data structures can often be created more # efficiently then those expected by strongly_connected_components() which # in this case would be # # V = [0, 1, 2, 3] # Gmap = [(0, 2), (0, 3), (1, 0)] # # XXX: Maybe this should be the recommended function to use instead... # # Non-recursive Tarjan's algorithm: lowlink = {} indices = {} stack = OrderedDict() callstack = [] components = [] nomore = object() def start(v): index = len(stack) indices[v] = lowlink[v] = index stack[v] = None callstack.append((v, iter(Gmap[v]))) def finish(v1): # Finished a component? if lowlink[v1] == indices[v1]: component = [stack.popitem()[0]] while component[-1] is not v1: component.append(stack.popitem()[0]) components.append(component[::-1]) v2, _ = callstack.pop() if callstack: v1, _ = callstack[-1] lowlink[v1] = min(lowlink[v1], lowlink[v2]) for v in V: if v in indices: continue start(v) while callstack: v1, it1 = callstack[-1] v2 = next(it1, nomore) # Finished children of v1? if v2 is nomore: finish(v1) # Recurse on v2 elif v2 not in indices: start(v2) elif v2 in stack: lowlink[v1] = min(lowlink[v1], indices[v2]) # Reverse topological sort order: return components def connected_components(G): r""" Connected components of an undirected graph or weakly connected components of a directed graph. Parameters ========== graph : tuple[list, list[tuple[T, T]] A tuple consisting of a list of vertices and a list of edges of a graph whose connected components are to be found. Examples ======== Given an undirected graph:: graph { A -- B C -- D } We can find the connected components using this function if we include each edge in both directions:: >>> from sympy.utilities.iterables import connected_components >>> V = ['A', 'B', 'C', 'D'] >>> E = [('A', 'B'), ('B', 'A'), ('C', 'D'), ('D', 'C')] >>> connected_components((V, E)) [['A', 'B'], ['C', 'D']] The weakly connected components of a directed graph can found the same way. Notes ===== The vertices of the graph must be hashable for the data structures used. If the vertices are unhashable replace them with integer indices. This function uses Tarjan's algorithm to compute the connected components in `O(|V|+|E|)` (linear) time. References ========== .. [1] https://en.wikipedia.org/wiki/Connected_component_(graph_theory) .. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm See Also ======== sympy.utilities.iterables.strongly_connected_components """ # Duplicate edges both ways so that the graph is effectively undirected # and return the strongly connected components: V, E = G E_undirected = [] for v1, v2 in E: E_undirected.extend([(v1, v2), (v2, v1)]) return strongly_connected_components((V, E_undirected)) def rotate_left(x, y): """ Left rotates a list x by the number of steps specified in y. Examples ======== >>> from sympy.utilities.iterables import rotate_left >>> a = [0, 1, 2] >>> rotate_left(a, 1) [1, 2, 0] """ if len(x) == 0: return [] y = y % len(x) return x[y:] + x[:y] def rotate_right(x, y): """ Right rotates a list x by the number of steps specified in y. Examples ======== >>> from sympy.utilities.iterables import rotate_right >>> a = [0, 1, 2] >>> rotate_right(a, 1) [2, 0, 1] """ if len(x) == 0: return [] y = len(x) - y % len(x) return x[y:] + x[:y] def least_rotation(x, key=None): ''' Returns the number of steps of left rotation required to obtain lexicographically minimal string/list/tuple, etc. Examples ======== >>> from sympy.utilities.iterables import least_rotation, rotate_left >>> a = [3, 1, 5, 1, 2] >>> least_rotation(a) 3 >>> rotate_left(a, _) [1, 2, 3, 1, 5] References ========== .. [1] https://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation ''' from sympy import Id if key is None: key = Id S = x + x # Concatenate string to it self to avoid modular arithmetic f = [-1] * len(S) # Failure function k = 0 # Least rotation of string found so far for j in range(1,len(S)): sj = S[j] i = f[j-k-1] while i != -1 and sj != S[k+i+1]: if key(sj) < key(S[k+i+1]): k = j-i-1 i = f[i] if sj != S[k+i+1]: if key(sj) < key(S[k]): k = j f[j-k] = -1 else: f[j-k] = i+1 return k def multiset_combinations(m, n, g=None): """ Return the unique combinations of size ``n`` from multiset ``m``. Examples ======== >>> from sympy.utilities.iterables import multiset_combinations >>> from itertools import combinations >>> [''.join(i) for i in multiset_combinations('baby', 3)] ['abb', 'aby', 'bby'] >>> def count(f, s): return len(list(f(s, 3))) The number of combinations depends on the number of letters; the number of unique combinations depends on how the letters are repeated. >>> s1 = 'abracadabra' >>> s2 = 'banana tree' >>> count(combinations, s1), count(multiset_combinations, s1) (165, 23) >>> count(combinations, s2), count(multiset_combinations, s2) (165, 54) """ if g is None: if type(m) is dict: if any(as_int(v) < 0 for v in m.values()): raise ValueError('counts cannot be negative') N = sum(m.values()) if n > N: return g = [[k, m[k]] for k in ordered(m)] else: m = list(m) N = len(m) if n > N: return try: m = multiset(m) g = [(k, m[k]) for k in ordered(m)] except TypeError: m = list(ordered(m)) g = [list(i) for i in group(m, multiple=False)] del m else: # not checking counts since g is intended for internal use N = sum(v for k, v in g) if n > N or not n: yield [] else: for i, (k, v) in enumerate(g): if v >= n: yield [k]*n v = n - 1 for v in range(min(n, v), 0, -1): for j in multiset_combinations(None, n - v, g[i + 1:]): rv = [k]*v + j if len(rv) == n: yield rv def multiset_permutations(m, size=None, g=None): """ Return the unique permutations of multiset ``m``. Examples ======== >>> from sympy.utilities.iterables import multiset_permutations >>> from sympy import factorial >>> [''.join(i) for i in multiset_permutations('aab')] ['aab', 'aba', 'baa'] >>> factorial(len('banana')) 720 >>> len(list(multiset_permutations('banana'))) 60 """ if g is None: if type(m) is dict: if any(as_int(v) < 0 for v in m.values()): raise ValueError('counts cannot be negative') g = [[k, m[k]] for k in ordered(m)] else: m = list(ordered(m)) g = [list(i) for i in group(m, multiple=False)] del m do = [gi for gi in g if gi[1] > 0] SUM = sum([gi[1] for gi in do]) if not do or size is not None and (size > SUM or size < 1): if not do and size is None or size == 0: yield [] return elif size == 1: for k, v in do: yield [k] elif len(do) == 1: k, v = do[0] v = v if size is None else (size if size <= v else 0) yield [k for i in range(v)] elif all(v == 1 for k, v in do): for p in permutations([k for k, v in do], size): yield list(p) else: size = size if size is not None else SUM for i, (k, v) in enumerate(do): do[i][1] -= 1 for j in multiset_permutations(None, size - 1, do): if j: yield [k] + j do[i][1] += 1 def _partition(seq, vector, m=None): """ Return the partition of seq as specified by the partition vector. Examples ======== >>> from sympy.utilities.iterables import _partition >>> _partition('abcde', [1, 0, 1, 2, 0]) [['b', 'e'], ['a', 'c'], ['d']] Specifying the number of bins in the partition is optional: >>> _partition('abcde', [1, 0, 1, 2, 0], 3) [['b', 'e'], ['a', 'c'], ['d']] The output of _set_partitions can be passed as follows: >>> output = (3, [1, 0, 1, 2, 0]) >>> _partition('abcde', *output) [['b', 'e'], ['a', 'c'], ['d']] See Also ======== combinatorics.partitions.Partition.from_rgs """ if m is None: m = max(vector) + 1 elif type(vector) is int: # entered as m, vector vector, m = m, vector p = [[] for i in range(m)] for i, v in enumerate(vector): p[v].append(seq[i]) return p def _set_partitions(n): """Cycle through all partions of n elements, yielding the current number of partitions, ``m``, and a mutable list, ``q`` such that element[i] is in part q[i] of the partition. NOTE: ``q`` is modified in place and generally should not be changed between function calls. Examples ======== >>> from sympy.utilities.iterables import _set_partitions, _partition >>> for m, q in _set_partitions(3): ... print('%s %s %s' % (m, q, _partition('abc', q, m))) 1 [0, 0, 0] [['a', 'b', 'c']] 2 [0, 0, 1] [['a', 'b'], ['c']] 2 [0, 1, 0] [['a', 'c'], ['b']] 2 [0, 1, 1] [['a'], ['b', 'c']] 3 [0, 1, 2] [['a'], ['b'], ['c']] Notes ===== This algorithm is similar to, and solves the same problem as, Algorithm 7.2.1.5H, from volume 4A of Knuth's The Art of Computer Programming. Knuth uses the term "restricted growth string" where this code refers to a "partition vector". In each case, the meaning is the same: the value in the ith element of the vector specifies to which part the ith set element is to be assigned. At the lowest level, this code implements an n-digit big-endian counter (stored in the array q) which is incremented (with carries) to get the next partition in the sequence. A special twist is that a digit is constrained to be at most one greater than the maximum of all the digits to the left of it. The array p maintains this maximum, so that the code can efficiently decide when a digit can be incremented in place or whether it needs to be reset to 0 and trigger a carry to the next digit. The enumeration starts with all the digits 0 (which corresponds to all the set elements being assigned to the same 0th part), and ends with 0123...n, which corresponds to each set element being assigned to a different, singleton, part. This routine was rewritten to use 0-based lists while trying to preserve the beauty and efficiency of the original algorithm. References ========== .. [1] Nijenhuis, Albert and Wilf, Herbert. (1978) Combinatorial Algorithms, 2nd Ed, p 91, algorithm "nexequ". Available online from https://www.math.upenn.edu/~wilf/website/CombAlgDownld.html (viewed November 17, 2012). """ p = [0]*n q = [0]*n nc = 1 yield nc, q while nc != n: m = n while 1: m -= 1 i = q[m] if p[i] != 1: break q[m] = 0 i += 1 q[m] = i m += 1 nc += m - n p[0] += n - m if i == nc: p[nc] = 0 nc += 1 p[i - 1] -= 1 p[i] += 1 yield nc, q def multiset_partitions(multiset, m=None): """ Return unique partitions of the given multiset (in list form). If ``m`` is None, all multisets will be returned, otherwise only partitions with ``m`` parts will be returned. If ``multiset`` is an integer, a range [0, 1, ..., multiset - 1] will be supplied. Examples ======== >>> from sympy.utilities.iterables import multiset_partitions >>> list(multiset_partitions([1, 2, 3, 4], 2)) [[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]], [[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]], [[1], [2, 3, 4]]] >>> list(multiset_partitions([1, 2, 3, 4], 1)) [[[1, 2, 3, 4]]] Only unique partitions are returned and these will be returned in a canonical order regardless of the order of the input: >>> a = [1, 2, 2, 1] >>> ans = list(multiset_partitions(a, 2)) >>> a.sort() >>> list(multiset_partitions(a, 2)) == ans True >>> a = range(3, 1, -1) >>> (list(multiset_partitions(a)) == ... list(multiset_partitions(sorted(a)))) True If m is omitted then all partitions will be returned: >>> list(multiset_partitions([1, 1, 2])) [[[1, 1, 2]], [[1, 1], [2]], [[1, 2], [1]], [[1], [1], [2]]] >>> list(multiset_partitions([1]*3)) [[[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]] Counting ======== The number of partitions of a set is given by the bell number: >>> from sympy import bell >>> len(list(multiset_partitions(5))) == bell(5) == 52 True The number of partitions of length k from a set of size n is given by the Stirling Number of the 2nd kind: >>> from sympy.functions.combinatorial.numbers import stirling >>> stirling(5, 2) == len(list(multiset_partitions(5, 2))) == 15 True These comments on counting apply to *sets*, not multisets. Notes ===== When all the elements are the same in the multiset, the order of the returned partitions is determined by the ``partitions`` routine. If one is counting partitions then it is better to use the ``nT`` function. See Also ======== partitions sympy.combinatorics.partitions.Partition sympy.combinatorics.partitions.IntegerPartition sympy.functions.combinatorial.numbers.nT """ # This function looks at the supplied input and dispatches to # several special-case routines as they apply. if type(multiset) is int: n = multiset if m and m > n: return multiset = list(range(n)) if m == 1: yield [multiset[:]] return # If m is not None, it can sometimes be faster to use # MultisetPartitionTraverser.enum_range() even for inputs # which are sets. Since the _set_partitions code is quite # fast, this is only advantageous when the overall set # partitions outnumber those with the desired number of parts # by a large factor. (At least 60.) Such a switch is not # currently implemented. for nc, q in _set_partitions(n): if m is None or nc == m: rv = [[] for i in range(nc)] for i in range(n): rv[q[i]].append(multiset[i]) yield rv return if len(multiset) == 1 and isinstance(multiset, str): multiset = [multiset] if not has_variety(multiset): # Only one component, repeated n times. The resulting # partitions correspond to partitions of integer n. n = len(multiset) if m and m > n: return if m == 1: yield [multiset[:]] return x = multiset[:1] for size, p in partitions(n, m, size=True): if m is None or size == m: rv = [] for k in sorted(p): rv.extend([x*k]*p[k]) yield rv else: multiset = list(ordered(multiset)) n = len(multiset) if m and m > n: return if m == 1: yield [multiset[:]] return # Split the information of the multiset into two lists - # one of the elements themselves, and one (of the same length) # giving the number of repeats for the corresponding element. elements, multiplicities = zip(*group(multiset, False)) if len(elements) < len(multiset): # General case - multiset with more than one distinct element # and at least one element repeated more than once. if m: mpt = MultisetPartitionTraverser() for state in mpt.enum_range(multiplicities, m-1, m): yield list_visitor(state, elements) else: for state in multiset_partitions_taocp(multiplicities): yield list_visitor(state, elements) else: # Set partitions case - no repeated elements. Pretty much # same as int argument case above, with same possible, but # currently unimplemented optimization for some cases when # m is not None for nc, q in _set_partitions(n): if m is None or nc == m: rv = [[] for i in range(nc)] for i in range(n): rv[q[i]].append(i) yield [[multiset[j] for j in i] for i in rv] def partitions(n, m=None, k=None, size=False): """Generate all partitions of positive integer, n. Parameters ========== m : integer (default gives partitions of all sizes) limits number of parts in partition (mnemonic: m, maximum parts) k : integer (default gives partitions number from 1 through n) limits the numbers that are kept in the partition (mnemonic: k, keys) size : bool (default False, only partition is returned) when ``True`` then (M, P) is returned where M is the sum of the multiplicities and P is the generated partition. Each partition is represented as a dictionary, mapping an integer to the number of copies of that integer in the partition. For example, the first partition of 4 returned is {4: 1}, "4: one of them". Examples ======== >>> from sympy.utilities.iterables import partitions The numbers appearing in the partition (the key of the returned dict) are limited with k: >>> for p in partitions(6, k=2): # doctest: +SKIP ... print(p) {2: 3} {1: 2, 2: 2} {1: 4, 2: 1} {1: 6} The maximum number of parts in the partition (the sum of the values in the returned dict) are limited with m (default value, None, gives partitions from 1 through n): >>> for p in partitions(6, m=2): # doctest: +SKIP ... print(p) ... {6: 1} {1: 1, 5: 1} {2: 1, 4: 1} {3: 2} References ========== .. [1] modified from Tim Peter's version to allow for k and m values: http://code.activestate.com/recipes/218332-generator-for-integer-partitions/ See Also ======== sympy.combinatorics.partitions.Partition sympy.combinatorics.partitions.IntegerPartition """ if (n <= 0 or m is not None and m < 1 or k is not None and k < 1 or m and k and m*k < n): # the empty set is the only way to handle these inputs # and returning {} to represent it is consistent with # the counting convention, e.g. nT(0) == 1. if size: yield 0, {} else: yield {} return if m is None: m = n else: m = min(m, n) k = min(k or n, n) n, m, k = as_int(n), as_int(m), as_int(k) q, r = divmod(n, k) ms = {k: q} keys = [k] # ms.keys(), from largest to smallest if r: ms[r] = 1 keys.append(r) room = m - q - bool(r) if size: yield sum(ms.values()), ms.copy() else: yield ms.copy() while keys != [1]: # Reuse any 1's. if keys[-1] == 1: del keys[-1] reuse = ms.pop(1) room += reuse else: reuse = 0 while 1: # Let i be the smallest key larger than 1. Reuse one # instance of i. i = keys[-1] newcount = ms[i] = ms[i] - 1 reuse += i if newcount == 0: del keys[-1], ms[i] room += 1 # Break the remainder into pieces of size i-1. i -= 1 q, r = divmod(reuse, i) need = q + bool(r) if need > room: if not keys: return continue ms[i] = q keys.append(i) if r: ms[r] = 1 keys.append(r) break room -= need if size: yield sum(ms.values()), ms.copy() else: yield ms.copy() def ordered_partitions(n, m=None, sort=True): """Generates ordered partitions of integer ``n``. Parameters ========== m : integer (default None) The default value gives partitions of all sizes else only those with size m. In addition, if ``m`` is not None then partitions are generated *in place* (see examples). sort : bool (default True) Controls whether partitions are returned in sorted order when ``m`` is not None; when False, the partitions are returned as fast as possible with elements sorted, but when m|n the partitions will not be in ascending lexicographical order. Examples ======== >>> from sympy.utilities.iterables import ordered_partitions All partitions of 5 in ascending lexicographical: >>> for p in ordered_partitions(5): ... print(p) [1, 1, 1, 1, 1] [1, 1, 1, 2] [1, 1, 3] [1, 2, 2] [1, 4] [2, 3] [5] Only partitions of 5 with two parts: >>> for p in ordered_partitions(5, 2): ... print(p) [1, 4] [2, 3] When ``m`` is given, a given list objects will be used more than once for speed reasons so you will not see the correct partitions unless you make a copy of each as it is generated: >>> [p for p in ordered_partitions(7, 3)] [[1, 1, 1], [1, 1, 1], [1, 1, 1], [2, 2, 2]] >>> [list(p) for p in ordered_partitions(7, 3)] [[1, 1, 5], [1, 2, 4], [1, 3, 3], [2, 2, 3]] When ``n`` is a multiple of ``m``, the elements are still sorted but the partitions themselves will be *unordered* if sort is False; the default is to return them in ascending lexicographical order. >>> for p in ordered_partitions(6, 2): ... print(p) [1, 5] [2, 4] [3, 3] But if speed is more important than ordering, sort can be set to False: >>> for p in ordered_partitions(6, 2, sort=False): ... print(p) [1, 5] [3, 3] [2, 4] References ========== .. [1] Generating Integer Partitions, [online], Available: https://jeromekelleher.net/generating-integer-partitions.html .. [2] Jerome Kelleher and Barry O'Sullivan, "Generating All Partitions: A Comparison Of Two Encodings", [online], Available: https://arxiv.org/pdf/0909.2331v2.pdf """ if n < 1 or m is not None and m < 1: # the empty set is the only way to handle these inputs # and returning {} to represent it is consistent with # the counting convention, e.g. nT(0) == 1. yield [] return if m is None: # The list `a`'s leading elements contain the partition in which # y is the biggest element and x is either the same as y or the # 2nd largest element; v and w are adjacent element indices # to which x and y are being assigned, respectively. a = [1]*n y = -1 v = n while v > 0: v -= 1 x = a[v] + 1 while y >= 2 * x: a[v] = x y -= x v += 1 w = v + 1 while x <= y: a[v] = x a[w] = y yield a[:w + 1] x += 1 y -= 1 a[v] = x + y y = a[v] - 1 yield a[:w] elif m == 1: yield [n] elif n == m: yield [1]*n else: # recursively generate partitions of size m for b in range(1, n//m + 1): a = [b]*m x = n - b*m if not x: if sort: yield a elif not sort and x <= m: for ax in ordered_partitions(x, sort=False): mi = len(ax) a[-mi:] = [i + b for i in ax] yield a a[-mi:] = [b]*mi else: for mi in range(1, m): for ax in ordered_partitions(x, mi, sort=True): a[-mi:] = [i + b for i in ax] yield a a[-mi:] = [b]*mi def binary_partitions(n): """ Generates the binary partition of n. A binary partition consists only of numbers that are powers of two. Each step reduces a `2^{k+1}` to `2^k` and `2^k`. Thus 16 is converted to 8 and 8. Examples ======== >>> from sympy.utilities.iterables import binary_partitions >>> for i in binary_partitions(5): ... print(i) ... [4, 1] [2, 2, 1] [2, 1, 1, 1] [1, 1, 1, 1, 1] References ========== .. [1] TAOCP 4, section 7.2.1.5, problem 64 """ from math import ceil, log power = int(2**(ceil(log(n, 2)))) acc = 0 partition = [] while power: if acc + power <= n: partition.append(power) acc += power power >>= 1 last_num = len(partition) - 1 - (n & 1) while last_num >= 0: yield partition if partition[last_num] == 2: partition[last_num] = 1 partition.append(1) last_num -= 1 continue partition.append(1) partition[last_num] >>= 1 x = partition[last_num + 1] = partition[last_num] last_num += 1 while x > 1: if x <= len(partition) - last_num - 1: del partition[-x + 1:] last_num += 1 partition[last_num] = x else: x >>= 1 yield [1]*n def has_dups(seq): """Return True if there are any duplicate elements in ``seq``. Examples ======== >>> from sympy.utilities.iterables import has_dups >>> from sympy import Dict, Set >>> has_dups((1, 2, 1)) True >>> has_dups(range(3)) False >>> all(has_dups(c) is False for c in (set(), Set(), dict(), Dict())) True """ from sympy.core.containers import Dict from sympy.sets.sets import Set if isinstance(seq, (dict, set, Dict, Set)): return False unique = set() return any(True for s in seq if s in unique or unique.add(s)) def has_variety(seq): """Return True if there are any different elements in ``seq``. Examples ======== >>> from sympy.utilities.iterables import has_variety >>> has_variety((1, 2, 1)) True >>> has_variety((1, 1, 1)) False """ for i, s in enumerate(seq): if i == 0: sentinel = s else: if s != sentinel: return True return False def uniq(seq, result=None): """ Yield unique elements from ``seq`` as an iterator. The second parameter ``result`` is used internally; it is not necessary to pass anything for this. Note: changing the sequence during iteration will raise a RuntimeError if the size of the sequence is known; if you pass an iterator and advance the iterator you will change the output of this routine but there will be no warning. Examples ======== >>> from sympy.utilities.iterables import uniq >>> dat = [1, 4, 1, 5, 4, 2, 1, 2] >>> type(uniq(dat)) in (list, tuple) False >>> list(uniq(dat)) [1, 4, 5, 2] >>> list(uniq(x for x in dat)) [1, 4, 5, 2] >>> list(uniq([[1], [2, 1], [1]])) [[1], [2, 1]] """ try: n = len(seq) except TypeError: n = None def check(): # check that size of seq did not change during iteration; # if n == None the object won't support size changing, e.g. # an iterator can't be changed if n is not None and len(seq) != n: raise RuntimeError('sequence changed size during iteration') try: seen = set() result = result or [] for i, s in enumerate(seq): if not (s in seen or seen.add(s)): yield s check() except TypeError: if s not in result: yield s check() result.append(s) if hasattr(seq, '__getitem__'): yield from uniq(seq[i + 1:], result) else: yield from uniq(seq, result) def generate_bell(n): """Return permutations of [0, 1, ..., n - 1] such that each permutation differs from the last by the exchange of a single pair of neighbors. The ``n!`` permutations are returned as an iterator. In order to obtain the next permutation from a random starting permutation, use the ``next_trotterjohnson`` method of the Permutation class (which generates the same sequence in a different manner). Examples ======== >>> from itertools import permutations >>> from sympy.utilities.iterables import generate_bell >>> from sympy import zeros, Matrix This is the sort of permutation used in the ringing of physical bells, and does not produce permutations in lexicographical order. Rather, the permutations differ from each other by exactly one inversion, and the position at which the swapping occurs varies periodically in a simple fashion. Consider the first few permutations of 4 elements generated by ``permutations`` and ``generate_bell``: >>> list(permutations(range(4)))[:5] [(0, 1, 2, 3), (0, 1, 3, 2), (0, 2, 1, 3), (0, 2, 3, 1), (0, 3, 1, 2)] >>> list(generate_bell(4))[:5] [(0, 1, 2, 3), (0, 1, 3, 2), (0, 3, 1, 2), (3, 0, 1, 2), (3, 0, 2, 1)] Notice how the 2nd and 3rd lexicographical permutations have 3 elements out of place whereas each "bell" permutation always has only two elements out of place relative to the previous permutation (and so the signature (+/-1) of a permutation is opposite of the signature of the previous permutation). How the position of inversion varies across the elements can be seen by tracing out where the largest number appears in the permutations: >>> m = zeros(4, 24) >>> for i, p in enumerate(generate_bell(4)): ... m[:, i] = Matrix([j - 3 for j in list(p)]) # make largest zero >>> m.print_nonzero('X') [XXX XXXXXX XXXXXX XXX] [XX XX XXXX XX XXXX XX XX] [X XXXX XX XXXX XX XXXX X] [ XXXXXX XXXXXX XXXXXX ] See Also ======== sympy.combinatorics.permutations.Permutation.next_trotterjohnson References ========== .. [1] https://en.wikipedia.org/wiki/Method_ringing .. [2] https://stackoverflow.com/questions/4856615/recursive-permutation/4857018 .. [3] http://programminggeeks.com/bell-algorithm-for-permutation/ .. [4] https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm .. [5] Generating involutions, derangements, and relatives by ECO Vincent Vajnovszki, DMTCS vol 1 issue 12, 2010 """ n = as_int(n) if n < 1: raise ValueError('n must be a positive integer') if n == 1: yield (0,) elif n == 2: yield (0, 1) yield (1, 0) elif n == 3: yield from [(0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)] else: m = n - 1 op = [0] + [-1]*m l = list(range(n)) while True: yield tuple(l) # find biggest element with op big = None, -1 # idx, value for i in range(n): if op[i] and l[i] > big[1]: big = i, l[i] i, _ = big if i is None: break # there are no ops left # swap it with neighbor in the indicated direction j = i + op[i] l[i], l[j] = l[j], l[i] op[i], op[j] = op[j], op[i] # if it landed at the end or if the neighbor in the same # direction is bigger then turn off op if j == 0 or j == m or l[j + op[j]] > l[j]: op[j] = 0 # any element bigger to the left gets +1 op for i in range(j): if l[i] > l[j]: op[i] = 1 # any element bigger to the right gets -1 op for i in range(j + 1, n): if l[i] > l[j]: op[i] = -1 def generate_involutions(n): """ Generates involutions. An involution is a permutation that when multiplied by itself equals the identity permutation. In this implementation the involutions are generated using Fixed Points. Alternatively, an involution can be considered as a permutation that does not contain any cycles with a length that is greater than two. Examples ======== >>> from sympy.utilities.iterables import generate_involutions >>> list(generate_involutions(3)) [(0, 1, 2), (0, 2, 1), (1, 0, 2), (2, 1, 0)] >>> len(list(generate_involutions(4))) 10 References ========== .. [1] http://mathworld.wolfram.com/PermutationInvolution.html """ idx = list(range(n)) for p in permutations(idx): for i in idx: if p[p[i]] != i: break else: yield p def generate_derangements(perm): """ Routine to generate unique derangements. TODO: This will be rewritten to use the ECO operator approach once the permutations branch is in master. Examples ======== >>> from sympy.utilities.iterables import generate_derangements >>> list(generate_derangements([0, 1, 2])) [[1, 2, 0], [2, 0, 1]] >>> list(generate_derangements([0, 1, 2, 3])) [[1, 0, 3, 2], [1, 2, 3, 0], [1, 3, 0, 2], [2, 0, 3, 1], \ [2, 3, 0, 1], [2, 3, 1, 0], [3, 0, 1, 2], [3, 2, 0, 1], \ [3, 2, 1, 0]] >>> list(generate_derangements([0, 1, 1])) [] See Also ======== sympy.functions.combinatorial.factorials.subfactorial """ for p in multiset_permutations(perm): if not any(i == j for i, j in zip(perm, p)): yield p def necklaces(n, k, free=False): """ A routine to generate necklaces that may (free=True) or may not (free=False) be turned over to be viewed. The "necklaces" returned are comprised of ``n`` integers (beads) with ``k`` different values (colors). Only unique necklaces are returned. Examples ======== >>> from sympy.utilities.iterables import necklaces, bracelets >>> def show(s, i): ... return ''.join(s[j] for j in i) The "unrestricted necklace" is sometimes also referred to as a "bracelet" (an object that can be turned over, a sequence that can be reversed) and the term "necklace" is used to imply a sequence that cannot be reversed. So ACB == ABC for a bracelet (rotate and reverse) while the two are different for a necklace since rotation alone cannot make the two sequences the same. (mnemonic: Bracelets can be viewed Backwards, but Not Necklaces.) >>> B = [show('ABC', i) for i in bracelets(3, 3)] >>> N = [show('ABC', i) for i in necklaces(3, 3)] >>> set(N) - set(B) {'ACB'} >>> list(necklaces(4, 2)) [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 1), (0, 1, 0, 1), (0, 1, 1, 1), (1, 1, 1, 1)] >>> [show('.o', i) for i in bracelets(4, 2)] ['....', '...o', '..oo', '.o.o', '.ooo', 'oooo'] References ========== .. [1] http://mathworld.wolfram.com/Necklace.html """ return uniq(minlex(i, directed=not free) for i in variations(list(range(k)), n, repetition=True)) def bracelets(n, k): """Wrapper to necklaces to return a free (unrestricted) necklace.""" return necklaces(n, k, free=True) def generate_oriented_forest(n): """ This algorithm generates oriented forests. An oriented graph is a directed graph having no symmetric pair of directed edges. A forest is an acyclic graph, i.e., it has no cycles. A forest can also be described as a disjoint union of trees, which are graphs in which any two vertices are connected by exactly one simple path. Examples ======== >>> from sympy.utilities.iterables import generate_oriented_forest >>> list(generate_oriented_forest(4)) [[0, 1, 2, 3], [0, 1, 2, 2], [0, 1, 2, 1], [0, 1, 2, 0], \ [0, 1, 1, 1], [0, 1, 1, 0], [0, 1, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0]] References ========== .. [1] T. Beyer and S.M. Hedetniemi: constant time generation of rooted trees, SIAM J. Computing Vol. 9, No. 4, November 1980 .. [2] https://stackoverflow.com/questions/1633833/oriented-forest-taocp-algorithm-in-python """ P = list(range(-1, n)) while True: yield P[1:] if P[n] > 0: P[n] = P[P[n]] else: for p in range(n - 1, 0, -1): if P[p] != 0: target = P[p] - 1 for q in range(p - 1, 0, -1): if P[q] == target: break offset = p - q for i in range(p, n + 1): P[i] = P[i - offset] break else: break def minlex(seq, directed=True, key=None): """ Return the rotation of the sequence in which the lexically smallest elements appear first, e.g. `cba ->acb`. The sequence returned is a tuple, unless the input sequence is a string in which case a string is returned. If ``directed`` is False then the smaller of the sequence and the reversed sequence is returned, e.g. `cba -> abc`. If ``key`` is not None then it is used to extract a comparison key from each element in iterable. Examples ======== >>> from sympy.combinatorics.polyhedron import minlex >>> minlex((1, 2, 0)) (0, 1, 2) >>> minlex((1, 0, 2)) (0, 2, 1) >>> minlex((1, 0, 2), directed=False) (0, 1, 2) >>> minlex('11010011000', directed=True) '00011010011' >>> minlex('11010011000', directed=False) '00011001011' >>> minlex(('bb', 'aaa', 'c', 'a')) ('a', 'bb', 'aaa', 'c') >>> minlex(('bb', 'aaa', 'c', 'a'), key=len) ('c', 'a', 'bb', 'aaa') """ from sympy import Id if key is None: key = Id best = rotate_left(seq, least_rotation(seq, key=key)) if not directed: rseq = seq[::-1] rbest = rotate_left(rseq, least_rotation(rseq, key=key)) best = min(best, rbest, key=key) # Convert to tuple, unless we started with a string. return tuple(best) if not isinstance(seq, str) else best def runs(seq, op=gt): """Group the sequence into lists in which successive elements all compare the same with the comparison operator, ``op``: op(seq[i + 1], seq[i]) is True from all elements in a run. Examples ======== >>> from sympy.utilities.iterables import runs >>> from operator import ge >>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2]) [[0, 1, 2], [2], [1, 4], [3], [2], [2]] >>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2], op=ge) [[0, 1, 2, 2], [1, 4], [3], [2, 2]] """ cycles = [] seq = iter(seq) try: run = [next(seq)] except StopIteration: return [] while True: try: ei = next(seq) except StopIteration: break if op(ei, run[-1]): run.append(ei) continue else: cycles.append(run) run = [ei] if run: cycles.append(run) return cycles def kbins(l, k, ordered=None): """ Return sequence ``l`` partitioned into ``k`` bins. Examples ======== >>> from __future__ import print_function The default is to give the items in the same order, but grouped into k partitions without any reordering: >>> from sympy.utilities.iterables import kbins >>> for p in kbins(list(range(5)), 2): ... print(p) ... [[0], [1, 2, 3, 4]] [[0, 1], [2, 3, 4]] [[0, 1, 2], [3, 4]] [[0, 1, 2, 3], [4]] The ``ordered`` flag is either None (to give the simple partition of the elements) or is a 2 digit integer indicating whether the order of the bins and the order of the items in the bins matters. Given:: A = [[0], [1, 2]] B = [[1, 2], [0]] C = [[2, 1], [0]] D = [[0], [2, 1]] the following values for ``ordered`` have the shown meanings:: 00 means A == B == C == D 01 means A == B 10 means A == D 11 means A == A >>> for ordered_flag in [None, 0, 1, 10, 11]: ... print('ordered = %s' % ordered_flag) ... for p in kbins(list(range(3)), 2, ordered=ordered_flag): ... print(' %s' % p) ... ordered = None [[0], [1, 2]] [[0, 1], [2]] ordered = 0 [[0, 1], [2]] [[0, 2], [1]] [[0], [1, 2]] ordered = 1 [[0], [1, 2]] [[0], [2, 1]] [[1], [0, 2]] [[1], [2, 0]] [[2], [0, 1]] [[2], [1, 0]] ordered = 10 [[0, 1], [2]] [[2], [0, 1]] [[0, 2], [1]] [[1], [0, 2]] [[0], [1, 2]] [[1, 2], [0]] ordered = 11 [[0], [1, 2]] [[0, 1], [2]] [[0], [2, 1]] [[0, 2], [1]] [[1], [0, 2]] [[1, 0], [2]] [[1], [2, 0]] [[1, 2], [0]] [[2], [0, 1]] [[2, 0], [1]] [[2], [1, 0]] [[2, 1], [0]] See Also ======== partitions, multiset_partitions """ def partition(lista, bins): # EnricoGiampieri's partition generator from # https://stackoverflow.com/questions/13131491/ # partition-n-items-into-k-bins-in-python-lazily if len(lista) == 1 or bins == 1: yield [lista] elif len(lista) > 1 and bins > 1: for i in range(1, len(lista)): for part in partition(lista[i:], bins - 1): if len([lista[:i]] + part) == bins: yield [lista[:i]] + part if ordered is None: yield from partition(l, k) elif ordered == 11: for pl in multiset_permutations(l): pl = list(pl) yield from partition(pl, k) elif ordered == 00: yield from multiset_partitions(l, k) elif ordered == 10: for p in multiset_partitions(l, k): for perm in permutations(p): yield list(perm) elif ordered == 1: for kgot, p in partitions(len(l), k, size=True): if kgot != k: continue for li in multiset_permutations(l): rv = [] i = j = 0 li = list(li) for size, multiplicity in sorted(p.items()): for m in range(multiplicity): j = i + size rv.append(li[i: j]) i = j yield rv else: raise ValueError( 'ordered must be one of 00, 01, 10 or 11, not %s' % ordered) def permute_signs(t): """Return iterator in which the signs of non-zero elements of t are permuted. Examples ======== >>> from sympy.utilities.iterables import permute_signs >>> list(permute_signs((0, 1, 2))) [(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2)] """ for signs in product(*[(1, -1)]*(len(t) - t.count(0))): signs = list(signs) yield type(t)([i*signs.pop() if i else i for i in t]) def signed_permutations(t): """Return iterator in which the signs of non-zero elements of t and the order of the elements are permuted. Examples ======== >>> from sympy.utilities.iterables import signed_permutations >>> list(signed_permutations((0, 1, 2))) [(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2), (0, 2, 1), (0, -2, 1), (0, 2, -1), (0, -2, -1), (1, 0, 2), (-1, 0, 2), (1, 0, -2), (-1, 0, -2), (1, 2, 0), (-1, 2, 0), (1, -2, 0), (-1, -2, 0), (2, 0, 1), (-2, 0, 1), (2, 0, -1), (-2, 0, -1), (2, 1, 0), (-2, 1, 0), (2, -1, 0), (-2, -1, 0)] """ return (type(t)(i) for j in permutations(t) for i in permute_signs(j)) def rotations(s, dir=1): """Return a generator giving the items in s as list where each subsequent list has the items rotated to the left (default) or right (dir=-1) relative to the previous list. Examples ======== >>> from sympy.utilities.iterables import rotations >>> list(rotations([1,2,3])) [[1, 2, 3], [2, 3, 1], [3, 1, 2]] >>> list(rotations([1,2,3], -1)) [[1, 2, 3], [3, 1, 2], [2, 3, 1]] """ seq = list(s) for i in range(len(seq)): yield seq seq = rotate_left(seq, dir) def roundrobin(*iterables): """roundrobin recipe taken from itertools documentation: https://docs.python.org/2/library/itertools.html#recipes roundrobin('ABC', 'D', 'EF') --> A D E B F C Recipe credited to George Sakkis """ import itertools nexts = itertools.cycle(iter(it).__next__ for it in iterables) pending = len(iterables) while pending: try: for nxt in nexts: yield nxt() except StopIteration: pending -= 1 nexts = itertools.cycle(itertools.islice(nexts, pending))
5cd7f9760ea406254daeafb83e029f8f3f22692e3d0fcb8749f5cf58b60481a9
"""Miscellaneous stuff that doesn't really fit anywhere else.""" from typing import List import sys import os import re as _re import struct from textwrap import fill, dedent from sympy.core.compatibility import as_int from sympy.core.decorators import deprecated class Undecidable(ValueError): # an error to be raised when a decision cannot be made definitively # where a definitive answer is needed pass def filldedent(s, w=70): """ Strips leading and trailing empty lines from a copy of `s`, then dedents, fills and returns it. Empty line stripping serves to deal with docstrings like this one that start with a newline after the initial triple quote, inserting an empty line at the beginning of the string. See Also ======== strlines, rawlines """ return '\n' + fill(dedent(str(s)).strip('\n'), width=w) def strlines(s, c=64, short=False): """Return a cut-and-pastable string that, when printed, is equivalent to the input. The lines will be surrounded by parentheses and no line will be longer than c (default 64) characters. If the line contains newlines characters, the `rawlines` result will be returned. If ``short`` is True (default is False) then if there is one line it will be returned without bounding parentheses. Examples ======== >>> from sympy.utilities.misc import strlines >>> q = 'this is a long string that should be broken into shorter lines' >>> print(strlines(q, 40)) ( 'this is a long string that should be b' 'roken into shorter lines' ) >>> q == ( ... 'this is a long string that should be b' ... 'roken into shorter lines' ... ) True See Also ======== filldedent, rawlines """ if type(s) is not str: raise ValueError('expecting string input') if '\n' in s: return rawlines(s) q = '"' if repr(s).startswith('"') else "'" q = (q,)*2 if '\\' in s: # use r-string m = '(\nr%s%%s%s\n)' % q j = '%s\nr%s' % q c -= 3 else: m = '(\n%s%%s%s\n)' % q j = '%s\n%s' % q c -= 2 out = [] while s: out.append(s[:c]) s=s[c:] if short and len(out) == 1: return (m % out[0]).splitlines()[1] # strip bounding (\n...\n) return m % j.join(out) def rawlines(s): """Return a cut-and-pastable string that, when printed, is equivalent to the input. Use this when there is more than one line in the string. The string returned is formatted so it can be indented nicely within tests; in some cases it is wrapped in the dedent function which has to be imported from textwrap. Examples ======== Note: because there are characters in the examples below that need to be escaped because they are themselves within a triple quoted docstring, expressions below look more complicated than they would be if they were printed in an interpreter window. >>> from sympy.utilities.misc import rawlines >>> from sympy import TableForm >>> s = str(TableForm([[1, 10]], headings=(None, ['a', 'bee']))) >>> print(rawlines(s)) ( 'a bee\\n' '-----\\n' '1 10 ' ) >>> print(rawlines('''this ... that''')) dedent('''\\ this that''') >>> print(rawlines('''this ... that ... ''')) dedent('''\\ this that ''') >>> s = \"\"\"this ... is a triple ''' ... \"\"\" >>> print(rawlines(s)) dedent(\"\"\"\\ this is a triple ''' \"\"\") >>> print(rawlines('''this ... that ... ''')) ( 'this\\n' 'that\\n' ' ' ) See Also ======== filldedent, strlines """ lines = s.split('\n') if len(lines) == 1: return repr(lines[0]) triple = ["'''" in s, '"""' in s] if any(li.endswith(' ') for li in lines) or '\\' in s or all(triple): rv = [] # add on the newlines trailing = s.endswith('\n') last = len(lines) - 1 for i, li in enumerate(lines): if i != last or trailing: rv.append(repr(li + '\n')) else: rv.append(repr(li)) return '(\n %s\n)' % '\n '.join(rv) else: rv = '\n '.join(lines) if triple[0]: return 'dedent("""\\\n %s""")' % rv else: return "dedent('''\\\n %s''')" % rv ARCH = str(struct.calcsize('P') * 8) + "-bit" # XXX: PyPy doesn't support hash randomization HASH_RANDOMIZATION = getattr(sys.flags, 'hash_randomization', False) _debug_tmp = [] # type: List[str] _debug_iter = 0 def debug_decorator(func): """If SYMPY_DEBUG is True, it will print a nice execution tree with arguments and results of all decorated functions, else do nothing. """ from sympy import SYMPY_DEBUG if not SYMPY_DEBUG: return func def maketree(f, *args, **kw): global _debug_tmp global _debug_iter oldtmp = _debug_tmp _debug_tmp = [] _debug_iter += 1 def tree(subtrees): def indent(s, variant=1): x = s.split("\n") r = "+-%s\n" % x[0] for a in x[1:]: if a == "": continue if variant == 1: r += "| %s\n" % a else: r += " %s\n" % a return r if len(subtrees) == 0: return "" f = [] for a in subtrees[:-1]: f.append(indent(a)) f.append(indent(subtrees[-1], 2)) return ''.join(f) # If there is a bug and the algorithm enters an infinite loop, enable the # following lines. It will print the names and parameters of all major functions # that are called, *before* they are called #from functools import reduce #print("%s%s %s%s" % (_debug_iter, reduce(lambda x, y: x + y, \ # map(lambda x: '-', range(1, 2 + _debug_iter))), f.__name__, args)) r = f(*args, **kw) _debug_iter -= 1 s = "%s%s = %s\n" % (f.__name__, args, r) if _debug_tmp != []: s += tree(_debug_tmp) _debug_tmp = oldtmp _debug_tmp.append(s) if _debug_iter == 0: print(_debug_tmp[0]) _debug_tmp = [] return r def decorated(*args, **kwargs): return maketree(func, *args, **kwargs) return decorated def debug(*args): """ Print ``*args`` if SYMPY_DEBUG is True, else do nothing. """ from sympy import SYMPY_DEBUG if SYMPY_DEBUG: print(*args, file=sys.stderr) @deprecated( useinstead="the builtin ``shutil.which`` function", issue=19634, deprecated_since_version="1.7") def find_executable(executable, path=None): """Try to find 'executable' in the directories listed in 'path' (a string listing directories separated by 'os.pathsep'; defaults to os.environ['PATH']). Returns the complete filename or None if not found """ if path is None: path = os.environ['PATH'] paths = path.split(os.pathsep) extlist = [''] if os.name == 'os2': (base, ext) = os.path.splitext(executable) # executable files on OS/2 can have an arbitrary extension, but # .exe is automatically appended if no dot is present in the name if not ext: executable = executable + ".exe" elif sys.platform == 'win32': pathext = os.environ['PATHEXT'].lower().split(os.pathsep) (base, ext) = os.path.splitext(executable) if ext.lower() not in pathext: extlist = pathext for ext in extlist: execname = executable + ext if os.path.isfile(execname): return execname else: for p in paths: f = os.path.join(p, execname) if os.path.isfile(f): return f return None def func_name(x, short=False): """Return function name of `x` (if defined) else the `type(x)`. If short is True and there is a shorter alias for the result, return the alias. Examples ======== >>> from sympy.utilities.misc import func_name >>> from sympy import Matrix >>> from sympy.abc import x >>> func_name(Matrix.eye(3)) 'MutableDenseMatrix' >>> func_name(x < 1) 'StrictLessThan' >>> func_name(x < 1, short=True) 'Lt' """ alias = { 'GreaterThan': 'Ge', 'StrictGreaterThan': 'Gt', 'LessThan': 'Le', 'StrictLessThan': 'Lt', 'Equality': 'Eq', 'Unequality': 'Ne', } typ = type(x) if str(typ).startswith("<type '"): typ = str(typ).split("'")[1].split("'")[0] elif str(typ).startswith("<class '"): typ = str(typ).split("'")[1].split("'")[0] rv = getattr(getattr(x, 'func', x), '__name__', typ) if '.' in rv: rv = rv.split('.')[-1] if short: rv = alias.get(rv, rv) return rv def _replace(reps): """Return a function that can make the replacements, given in ``reps``, on a string. The replacements should be given as mapping. Examples ======== >>> from sympy.utilities.misc import _replace >>> f = _replace(dict(foo='bar', d='t')) >>> f('food') 'bart' >>> f = _replace({}) >>> f('food') 'food' """ if not reps: return lambda x: x D = lambda match: reps[match.group(0)] pattern = _re.compile("|".join( [_re.escape(k) for k, v in reps.items()]), _re.M) return lambda string: pattern.sub(D, string) def replace(string, *reps): """Return ``string`` with all keys in ``reps`` replaced with their corresponding values, longer strings first, irrespective of the order they are given. ``reps`` may be passed as tuples or a single mapping. Examples ======== >>> from sympy.utilities.misc import replace >>> replace('foo', {'oo': 'ar', 'f': 'b'}) 'bar' >>> replace("spamham sha", ("spam", "eggs"), ("sha","md5")) 'eggsham md5' There is no guarantee that a unique answer will be obtained if keys in a mapping overlap (i.e. are the same length and have some identical sequence at the beginning/end): >>> reps = [ ... ('ab', 'x'), ... ('bc', 'y')] >>> replace('abc', *reps) in ('xc', 'ay') True References ========== .. [1] https://stackoverflow.com/questions/6116978/python-replace-multiple-strings """ if len(reps) == 1: kv = reps[0] if type(kv) is dict: reps = kv else: return string.replace(*kv) else: reps = dict(reps) return _replace(reps)(string) def translate(s, a, b=None, c=None): """Return ``s`` where characters have been replaced or deleted. SYNTAX ====== translate(s, None, deletechars): all characters in ``deletechars`` are deleted translate(s, map [,deletechars]): all characters in ``deletechars`` (if provided) are deleted then the replacements defined by map are made; if the keys of map are strings then the longer ones are handled first. Multicharacter deletions should have a value of ''. translate(s, oldchars, newchars, deletechars) all characters in ``deletechars`` are deleted then each character in ``oldchars`` is replaced with the corresponding character in ``newchars`` Examples ======== >>> from sympy.utilities.misc import translate >>> abc = 'abc' >>> translate(abc, None, 'a') 'bc' >>> translate(abc, {'a': 'x'}, 'c') 'xb' >>> translate(abc, {'abc': 'x', 'a': 'y'}) 'x' >>> translate('abcd', 'ac', 'AC', 'd') 'AbC' There is no guarantee that a unique answer will be obtained if keys in a mapping overlap are the same length and have some identical sequences at the beginning/end: >>> translate(abc, {'ab': 'x', 'bc': 'y'}) in ('xc', 'ay') True """ mr = {} if a is None: if c is not None: raise ValueError('c should be None when a=None is passed, instead got %s' % c) if b is None: return s c = b a = b = '' else: if type(a) is dict: short = {} for k in list(a.keys()): if len(k) == 1 and len(a[k]) == 1: short[k] = a.pop(k) mr = a c = b if short: a, b = [''.join(i) for i in list(zip(*short.items()))] else: a = b = '' elif len(a) != len(b): raise ValueError('oldchars and newchars have different lengths') if c: val = str.maketrans('', '', c) s = s.translate(val) s = replace(s, mr) n = str.maketrans(a, b) return s.translate(n) def ordinal(num): """Return ordinal number string of num, e.g. 1 becomes 1st. """ # modified from https://codereview.stackexchange.com/questions/41298/producing-ordinal-numbers n = as_int(num) k = abs(n) % 100 if 11 <= k <= 13: suffix = 'th' elif k % 10 == 1: suffix = 'st' elif k % 10 == 2: suffix = 'nd' elif k % 10 == 3: suffix = 'rd' else: suffix = 'th' return str(n) + suffix
d7eb41aa6b65a2820cf29f007a506ca0ce974905969fce227d484f0c5c1558ff
"""A module providing information about the necessity of brackets""" from sympy.core.function import _coeff_isneg # Default precedence values for some basic types PRECEDENCE = { "Lambda": 1, "Xor": 10, "Or": 20, "And": 30, "Relational": 35, "Add": 40, "Mul": 50, "Pow": 60, "Func": 70, "Not": 100, "Atom": 1000, "BitwiseOr": 36, "BitwiseXor": 37, "BitwiseAnd": 38 } # A dictionary assigning precedence values to certain classes. These values are # treated like they were inherited, so not every single class has to be named # here. # Do not use this with printers other than StrPrinter PRECEDENCE_VALUES = { "Equivalent": PRECEDENCE["Xor"], "Xor": PRECEDENCE["Xor"], "Implies": PRECEDENCE["Xor"], "Or": PRECEDENCE["Or"], "And": PRECEDENCE["And"], "Add": PRECEDENCE["Add"], "Pow": PRECEDENCE["Pow"], "Relational": PRECEDENCE["Relational"], "Sub": PRECEDENCE["Add"], "Not": PRECEDENCE["Not"], "Function" : PRECEDENCE["Func"], "NegativeInfinity": PRECEDENCE["Add"], "MatAdd": PRECEDENCE["Add"], "MatPow": PRECEDENCE["Pow"], "MatrixSolve": PRECEDENCE["Mul"], "TensAdd": PRECEDENCE["Add"], # As soon as `TensMul` is a subclass of `Mul`, remove this: "TensMul": PRECEDENCE["Mul"], "HadamardProduct": PRECEDENCE["Mul"], "HadamardPower": PRECEDENCE["Pow"], "KroneckerProduct": PRECEDENCE["Mul"], "Equality": PRECEDENCE["Mul"], "Unequality": PRECEDENCE["Mul"], } # Sometimes it's not enough to assign a fixed precedence value to a # class. Then a function can be inserted in this dictionary that takes # an instance of this class as argument and returns the appropriate # precedence value. # Precedence functions def precedence_Mul(item): if _coeff_isneg(item): return PRECEDENCE["Add"] return PRECEDENCE["Mul"] def precedence_Rational(item): if item.p < 0: return PRECEDENCE["Add"] return PRECEDENCE["Mul"] def precedence_Integer(item): if item.p < 0: return PRECEDENCE["Add"] return PRECEDENCE["Atom"] def precedence_Float(item): if item < 0: return PRECEDENCE["Add"] return PRECEDENCE["Atom"] def precedence_PolyElement(item): if item.is_generator: return PRECEDENCE["Atom"] elif item.is_ground: return precedence(item.coeff(1)) elif item.is_term: return PRECEDENCE["Mul"] else: return PRECEDENCE["Add"] def precedence_FracElement(item): if item.denom == 1: return precedence_PolyElement(item.numer) else: return PRECEDENCE["Mul"] def precedence_UnevaluatedExpr(item): return precedence(item.args[0]) - 0.5 PRECEDENCE_FUNCTIONS = { "Integer": precedence_Integer, "Mul": precedence_Mul, "Rational": precedence_Rational, "Float": precedence_Float, "PolyElement": precedence_PolyElement, "FracElement": precedence_FracElement, "UnevaluatedExpr": precedence_UnevaluatedExpr, } def precedence(item): """Returns the precedence of a given object. This is the precedence for StrPrinter. """ if hasattr(item, "precedence"): return item.precedence try: mro = item.__class__.__mro__ except AttributeError: return PRECEDENCE["Atom"] for i in mro: n = i.__name__ if n in PRECEDENCE_FUNCTIONS: return PRECEDENCE_FUNCTIONS[n](item) elif n in PRECEDENCE_VALUES: return PRECEDENCE_VALUES[n] return PRECEDENCE["Atom"] PRECEDENCE_TRADITIONAL = PRECEDENCE.copy() PRECEDENCE_TRADITIONAL['Integral'] = PRECEDENCE["Mul"] PRECEDENCE_TRADITIONAL['Sum'] = PRECEDENCE["Mul"] PRECEDENCE_TRADITIONAL['Product'] = PRECEDENCE["Mul"] PRECEDENCE_TRADITIONAL['Limit'] = PRECEDENCE["Mul"] PRECEDENCE_TRADITIONAL['Derivative'] = PRECEDENCE["Mul"] PRECEDENCE_TRADITIONAL['TensorProduct'] = PRECEDENCE["Mul"] PRECEDENCE_TRADITIONAL['Transpose'] = PRECEDENCE["Pow"] PRECEDENCE_TRADITIONAL['Adjoint'] = PRECEDENCE["Pow"] PRECEDENCE_TRADITIONAL['Dot'] = PRECEDENCE["Mul"] - 1 PRECEDENCE_TRADITIONAL['Cross'] = PRECEDENCE["Mul"] - 1 PRECEDENCE_TRADITIONAL['Gradient'] = PRECEDENCE["Mul"] - 1 PRECEDENCE_TRADITIONAL['Divergence'] = PRECEDENCE["Mul"] - 1 PRECEDENCE_TRADITIONAL['Curl'] = PRECEDENCE["Mul"] - 1 PRECEDENCE_TRADITIONAL['Laplacian'] = PRECEDENCE["Mul"] - 1 PRECEDENCE_TRADITIONAL['Union'] = PRECEDENCE['Xor'] PRECEDENCE_TRADITIONAL['Intersection'] = PRECEDENCE['Xor'] PRECEDENCE_TRADITIONAL['Complement'] = PRECEDENCE['Xor'] PRECEDENCE_TRADITIONAL['SymmetricDifference'] = PRECEDENCE['Xor'] PRECEDENCE_TRADITIONAL['ProductSet'] = PRECEDENCE['Xor'] def precedence_traditional(item): """Returns the precedence of a given object according to the traditional rules of mathematics. This is the precedence for the LaTeX and pretty printer. """ # Integral, Sum, Product, Limit have the precedence of Mul in LaTeX, # the precedence of Atom for other printers: from sympy.core.expr import UnevaluatedExpr if isinstance(item, UnevaluatedExpr): return precedence_traditional(item.args[0]) n = item.__class__.__name__ if n in PRECEDENCE_TRADITIONAL: return PRECEDENCE_TRADITIONAL[n] return precedence(item)
075bbac7b0491068b4a0caf6faad5caf951d247191558a91fe5ad3e0a98f0b67
from sympy.core import S from .pycode import PythonCodePrinter, _known_functions_math, _print_known_const, _print_known_func, _unpack_integral_limits from .codeprinter import CodePrinter _not_in_numpy = 'erf erfc factorial gamma loggamma'.split() _in_numpy = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_numpy] _known_functions_numpy = dict(_in_numpy, **{ 'acos': 'arccos', 'acosh': 'arccosh', 'asin': 'arcsin', 'asinh': 'arcsinh', 'atan': 'arctan', 'atan2': 'arctan2', 'atanh': 'arctanh', 'exp2': 'exp2', 'sign': 'sign', 'logaddexp': 'logaddexp', 'logaddexp2': 'logaddexp2', }) _known_constants_numpy = { 'Exp1': 'e', 'Pi': 'pi', 'EulerGamma': 'euler_gamma', 'NaN': 'nan', 'Infinity': 'PINF', 'NegativeInfinity': 'NINF' } _numpy_known_functions = {k: 'numpy.' + v for k, v in _known_functions_numpy.items()} _numpy_known_constants = {k: 'numpy.' + v for k, v in _known_constants_numpy.items()} class NumPyPrinter(PythonCodePrinter): """ Numpy printer which handles vectorized piecewise functions, logical operators, etc. """ _module = 'numpy' _kf = _numpy_known_functions _kc = _numpy_known_constants def __init__(self, settings=None): """ `settings` is passed to CodePrinter.__init__() `module` specifies the array module to use, currently 'NumPy' or 'CuPy' """ self.language = "Python with {}".format(self._module) self.printmethod = "_{}code".format(self._module) self._kf = {**PythonCodePrinter._kf, **self._kf} super().__init__(settings=settings) def _print_seq(self, seq): "General sequence printer: converts to tuple" # Print tuples here instead of lists because numba supports # tuples in nopython mode. delimiter=', ' return '({},)'.format(delimiter.join(self._print(item) for item in seq)) def _print_MatMul(self, expr): "Matrix multiplication printer" if expr.as_coeff_matrices()[0] is not S.One: expr_list = expr.as_coeff_matrices()[1]+[(expr.as_coeff_matrices()[0])] return '({})'.format(').dot('.join(self._print(i) for i in expr_list)) return '({})'.format(').dot('.join(self._print(i) for i in expr.args)) def _print_MatPow(self, expr): "Matrix power printer" return '{}({}, {})'.format(self._module_format(self._module + '.linalg.matrix_power'), self._print(expr.args[0]), self._print(expr.args[1])) def _print_Inverse(self, expr): "Matrix inverse printer" return '{}({})'.format(self._module_format(self._module + '.linalg.inv'), self._print(expr.args[0])) def _print_DotProduct(self, expr): # DotProduct allows any shape order, but numpy.dot does matrix # multiplication, so we have to make sure it gets 1 x n by n x 1. arg1, arg2 = expr.args if arg1.shape[0] != 1: arg1 = arg1.T if arg2.shape[1] != 1: arg2 = arg2.T return "%s(%s, %s)" % (self._module_format(self._module + '.dot'), self._print(arg1), self._print(arg2)) def _print_MatrixSolve(self, expr): return "%s(%s, %s)" % (self._module_format(self._module + '.linalg.solve'), self._print(expr.matrix), self._print(expr.vector)) def _print_ZeroMatrix(self, expr): return '{}({})'.format(self._module_format(self._module + '.zeros'), self._print(expr.shape)) def _print_OneMatrix(self, expr): return '{}({})'.format(self._module_format(self._module + '.ones'), self._print(expr.shape)) def _print_FunctionMatrix(self, expr): from sympy.core.function import Lambda from sympy.abc import i, j lamda = expr.lamda if not isinstance(lamda, Lambda): lamda = Lambda((i, j), lamda(i, j)) return '{}(lambda {}: {}, {})'.format(self._module_format(self._module + '.fromfunction'), ', '.join(self._print(arg) for arg in lamda.args[0]), self._print(lamda.args[1]), self._print(expr.shape)) def _print_HadamardProduct(self, expr): func = self._module_format(self._module + '.multiply') return ''.join('{}({}, '.format(func, self._print(arg)) \ for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]), ')' * (len(expr.args) - 1)) def _print_KroneckerProduct(self, expr): func = self._module_format(self._module + '.kron') return ''.join('{}({}, '.format(func, self._print(arg)) \ for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]), ')' * (len(expr.args) - 1)) def _print_Adjoint(self, expr): return '{}({}({}))'.format( self._module_format(self._module + '.conjugate'), self._module_format(self._module + '.transpose'), self._print(expr.args[0])) def _print_DiagonalOf(self, expr): vect = '{}({})'.format( self._module_format(self._module + '.diag'), self._print(expr.arg)) return '{}({}, (-1, 1))'.format( self._module_format(self._module + '.reshape'), vect) def _print_DiagMatrix(self, expr): return '{}({})'.format(self._module_format(self._module + '.diagflat'), self._print(expr.args[0])) def _print_DiagonalMatrix(self, expr): return '{}({}, {}({}, {}))'.format(self._module_format(self._module + '.multiply'), self._print(expr.arg), self._module_format(self._module + '.eye'), self._print(expr.shape[0]), self._print(expr.shape[1])) def _print_Piecewise(self, expr): "Piecewise function printer" exprs = '[{}]'.format(','.join(self._print(arg.expr) for arg in expr.args)) conds = '[{}]'.format(','.join(self._print(arg.cond) for arg in expr.args)) # If [default_value, True] is a (expr, cond) sequence in a Piecewise object # it will behave the same as passing the 'default' kwarg to select() # *as long as* it is the last element in expr.args. # If this is not the case, it may be triggered prematurely. return '{}({}, {}, default={})'.format( self._module_format(self._module + '.select'), conds, exprs, self._print(S.NaN)) def _print_Relational(self, expr): "Relational printer for Equality and Unequality" op = { '==' :'equal', '!=' :'not_equal', '<' :'less', '<=' :'less_equal', '>' :'greater', '>=' :'greater_equal', } if expr.rel_op in op: lhs = self._print(expr.lhs) rhs = self._print(expr.rhs) return '{op}({lhs}, {rhs})'.format(op=self._module_format(self._module + '.'+op[expr.rel_op]), lhs=lhs, rhs=rhs) return super()._print_Relational(expr) def _print_And(self, expr): "Logical And printer" # We have to override LambdaPrinter because it uses Python 'and' keyword. # If LambdaPrinter didn't define it, we could use StrPrinter's # version of the function and add 'logical_and' to NUMPY_TRANSLATIONS. return '{}.reduce(({}))'.format(self._module_format(self._module + '.logical_and'), ','.join(self._print(i) for i in expr.args)) def _print_Or(self, expr): "Logical Or printer" # We have to override LambdaPrinter because it uses Python 'or' keyword. # If LambdaPrinter didn't define it, we could use StrPrinter's # version of the function and add 'logical_or' to NUMPY_TRANSLATIONS. return '{}.reduce(({}))'.format(self._module_format(self._module + '.logical_or'), ','.join(self._print(i) for i in expr.args)) def _print_Not(self, expr): "Logical Not printer" # We have to override LambdaPrinter because it uses Python 'not' keyword. # If LambdaPrinter didn't define it, we would still have to define our # own because StrPrinter doesn't define it. return '{}({})'.format(self._module_format(self._module + '.logical_not'), ','.join(self._print(i) for i in expr.args)) def _print_Pow(self, expr, rational=False): # XXX Workaround for negative integer power error from sympy.core.power import Pow if expr.exp.is_integer and expr.exp.is_negative: expr = Pow(expr.base, expr.exp.evalf(), evaluate=False) return self._hprint_Pow(expr, rational=rational, sqrt=self._module + '.sqrt') def _print_Min(self, expr): return '{}(({}), axis=0)'.format(self._module_format(self._module + '.amin'), ','.join(self._print(i) for i in expr.args)) def _print_Max(self, expr): return '{}(({}), axis=0)'.format(self._module_format(self._module + '.amax'), ','.join(self._print(i) for i in expr.args)) def _print_arg(self, expr): return "%s(%s)" % (self._module_format(self._module + '.angle'), self._print(expr.args[0])) def _print_im(self, expr): return "%s(%s)" % (self._module_format(self._module + '.imag'), self._print(expr.args[0])) def _print_Mod(self, expr): return "%s(%s)" % (self._module_format(self._module + '.mod'), ', '.join( map(lambda arg: self._print(arg), expr.args))) def _print_re(self, expr): return "%s(%s)" % (self._module_format(self._module + '.real'), self._print(expr.args[0])) def _print_sinc(self, expr): return "%s(%s)" % (self._module_format(self._module + '.sinc'), self._print(expr.args[0]/S.Pi)) def _print_MatrixBase(self, expr): func = self.known_functions.get(expr.__class__.__name__, None) if func is None: func = self._module_format(self._module + '.array') return "%s(%s)" % (func, self._print(expr.tolist())) def _print_Identity(self, expr): shape = expr.shape if all(dim.is_Integer for dim in shape): return "%s(%s)" % (self._module_format(self._module + '.eye'), self._print(expr.shape[0])) else: raise NotImplementedError("Symbolic matrix dimensions are not yet supported for identity matrices") def _print_BlockMatrix(self, expr): return '{}({})'.format(self._module_format(self._module + '.block'), self._print(expr.args[0].tolist())) def _print_ArrayTensorProduct(self, expr): array_list = [j for i, arg in enumerate(expr.args) for j in (self._print(arg), "[%i, %i]" % (2*i, 2*i+1))] return "%s(%s)" % (self._module_format(self._module + '.einsum'), ", ".join(array_list)) def _print_ArrayContraction(self, expr): from ..tensor.array.expressions.array_expressions import ArrayTensorProduct base = expr.expr contraction_indices = expr.contraction_indices if not contraction_indices: return self._print(base) if isinstance(base, ArrayTensorProduct): counter = 0 d = {j: min(i) for i in contraction_indices for j in i} indices = [] for rank_arg in base.subranks: lindices = [] for i in range(rank_arg): if counter in d: lindices.append(d[counter]) else: lindices.append(counter) counter += 1 indices.append(lindices) elems = ["%s, %s" % (self._print(arg), ind) for arg, ind in zip(base.args, indices)] return "%s(%s)" % ( self._module_format(self._module + '.einsum'), ", ".join(elems) ) raise NotImplementedError() def _print_ArrayDiagonal(self, expr): diagonal_indices = list(expr.diagonal_indices) if len(diagonal_indices) > 1: # TODO: this should be handled in sympy.codegen.array_utils, # possibly by creating the possibility of unfolding the # ArrayDiagonal object into nested ones. Same reasoning for # the array contraction. raise NotImplementedError if len(diagonal_indices[0]) != 2: raise NotImplementedError return "%s(%s, 0, axis1=%s, axis2=%s)" % ( self._module_format("numpy.diagonal"), self._print(expr.expr), diagonal_indices[0][0], diagonal_indices[0][1], ) def _print_PermuteDims(self, expr): return "%s(%s, %s)" % ( self._module_format("numpy.transpose"), self._print(expr.expr), self._print(expr.permutation.array_form), ) def _print_ArrayAdd(self, expr): return self._expand_fold_binary_op(self._module + '.add', expr.args) _print_lowergamma = CodePrinter._print_not_supported _print_uppergamma = CodePrinter._print_not_supported _print_fresnelc = CodePrinter._print_not_supported _print_fresnels = CodePrinter._print_not_supported for func in _numpy_known_functions: setattr(NumPyPrinter, f'_print_{func}', _print_known_func) for const in _numpy_known_constants: setattr(NumPyPrinter, f'_print_{const}', _print_known_const) _known_functions_scipy_special = { 'erf': 'erf', 'erfc': 'erfc', 'besselj': 'jv', 'bessely': 'yv', 'besseli': 'iv', 'besselk': 'kv', 'cosm1': 'cosm1', 'factorial': 'factorial', 'gamma': 'gamma', 'loggamma': 'gammaln', 'digamma': 'psi', 'RisingFactorial': 'poch', 'jacobi': 'eval_jacobi', 'gegenbauer': 'eval_gegenbauer', 'chebyshevt': 'eval_chebyt', 'chebyshevu': 'eval_chebyu', 'legendre': 'eval_legendre', 'hermite': 'eval_hermite', 'laguerre': 'eval_laguerre', 'assoc_laguerre': 'eval_genlaguerre', 'beta': 'beta', 'LambertW' : 'lambertw', } _known_constants_scipy_constants = { 'GoldenRatio': 'golden_ratio', 'Pi': 'pi', } _scipy_known_functions = {k : "scipy.special." + v for k, v in _known_functions_scipy_special.items()} _scipy_known_constants = {k : "scipy.constants." + v for k, v in _known_constants_scipy_constants.items()} class SciPyPrinter(NumPyPrinter): _kf = {**NumPyPrinter._kf, **_scipy_known_functions} _kc = {**NumPyPrinter._kc, **_scipy_known_constants} def __init__(self, settings=None): super().__init__(settings=settings) self.language = "Python with SciPy and NumPy" def _print_SparseMatrix(self, expr): i, j, data = [], [], [] for (r, c), v in expr.todok().items(): i.append(r) j.append(c) data.append(v) return "{name}(({data}, ({i}, {j})), shape={shape})".format( name=self._module_format('scipy.sparse.coo_matrix'), data=data, i=i, j=j, shape=expr.shape ) _print_ImmutableSparseMatrix = _print_SparseMatrix # SciPy's lpmv has a different order of arguments from assoc_legendre def _print_assoc_legendre(self, expr): return "{0}({2}, {1}, {3})".format( self._module_format('scipy.special.lpmv'), self._print(expr.args[0]), self._print(expr.args[1]), self._print(expr.args[2])) def _print_lowergamma(self, expr): return "{0}({2})*{1}({2}, {3})".format( self._module_format('scipy.special.gamma'), self._module_format('scipy.special.gammainc'), self._print(expr.args[0]), self._print(expr.args[1])) def _print_uppergamma(self, expr): return "{0}({2})*{1}({2}, {3})".format( self._module_format('scipy.special.gamma'), self._module_format('scipy.special.gammaincc'), self._print(expr.args[0]), self._print(expr.args[1])) def _print_betainc(self, expr): betainc = self._module_format('scipy.special.betainc') beta = self._module_format('scipy.special.beta') args = [self._print(arg) for arg in expr.args] return f"({betainc}({args[0]}, {args[1]}, {args[3]}) - {betainc}({args[0]}, {args[1]}, {args[2]})) \ * {beta}({args[0]}, {args[1]})" def _print_betainc_regularized(self, expr): return "{0}({1}, {2}, {4}) - {0}({1}, {2}, {3})".format( self._module_format('scipy.special.betainc'), self._print(expr.args[0]), self._print(expr.args[1]), self._print(expr.args[2]), self._print(expr.args[3])) def _print_fresnels(self, expr): return "{}({})[0]".format( self._module_format("scipy.special.fresnel"), self._print(expr.args[0])) def _print_fresnelc(self, expr): return "{}({})[1]".format( self._module_format("scipy.special.fresnel"), self._print(expr.args[0])) def _print_airyai(self, expr): return "{}({})[0]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_airyaiprime(self, expr): return "{}({})[1]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_airybi(self, expr): return "{}({})[2]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_airybiprime(self, expr): return "{}({})[3]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_Integral(self, e): integration_vars, limits = _unpack_integral_limits(e) if len(limits) == 1: # nicer (but not necessary) to prefer quad over nquad for 1D case module_str = self._module_format("scipy.integrate.quad") limit_str = "%s, %s" % tuple(map(self._print, limits[0])) else: module_str = self._module_format("scipy.integrate.nquad") limit_str = "({})".format(", ".join( "(%s, %s)" % tuple(map(self._print, l)) for l in limits)) return "{}(lambda {}: {}, {})[0]".format( module_str, ", ".join(map(self._print, integration_vars)), self._print(e.args[0]), limit_str) for func in _scipy_known_functions: setattr(SciPyPrinter, f'_print_{func}', _print_known_func) for const in _scipy_known_constants: setattr(SciPyPrinter, f'_print_{const}', _print_known_const) _cupy_known_functions = {k : "cupy." + v for k, v in _known_functions_numpy.items()} _cupy_known_constants = {k : "cupy." + v for k, v in _known_constants_numpy.items()} class CuPyPrinter(NumPyPrinter): """ CuPy printer which handles vectorized piecewise functions, logical operators, etc. """ _module = 'cupy' _kf = _cupy_known_functions _kc = _cupy_known_constants def __init__(self, settings=None): super().__init__(settings=settings) for func in _cupy_known_functions: setattr(CuPyPrinter, f'_print_{func}', _print_known_func) for const in _cupy_known_constants: setattr(CuPyPrinter, f'_print_{const}', _print_known_const)
87b3b55341cfe26d214daa7a86366f71678f754f8adb75efca8243e57904aa5e
""" Python code printers This module contains python code printers for plain python as well as NumPy & SciPy enabled code. """ from collections import defaultdict from itertools import chain from sympy.core import S from .precedence import precedence from .codeprinter import CodePrinter _kw_py2and3 = { 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield', 'None' # 'None' is actually not in Python 2's keyword.kwlist } _kw_only_py2 = {'exec', 'print'} _kw_only_py3 = {'False', 'nonlocal', 'True'} _known_functions = { 'Abs': 'abs', } _known_functions_math = { 'acos': 'acos', 'acosh': 'acosh', 'asin': 'asin', 'asinh': 'asinh', 'atan': 'atan', 'atan2': 'atan2', 'atanh': 'atanh', 'ceiling': 'ceil', 'cos': 'cos', 'cosh': 'cosh', 'erf': 'erf', 'erfc': 'erfc', 'exp': 'exp', 'expm1': 'expm1', 'factorial': 'factorial', 'floor': 'floor', 'gamma': 'gamma', 'hypot': 'hypot', 'loggamma': 'lgamma', 'log': 'log', 'ln': 'log', 'log10': 'log10', 'log1p': 'log1p', 'log2': 'log2', 'sin': 'sin', 'sinh': 'sinh', 'Sqrt': 'sqrt', 'tan': 'tan', 'tanh': 'tanh' } # Not used from ``math``: [copysign isclose isfinite isinf isnan ldexp frexp pow modf # radians trunc fmod fsum gcd degrees fabs] _known_constants_math = { 'Exp1': 'e', 'Pi': 'pi', 'E': 'e' # Only in python >= 3.5: # 'Infinity': 'inf', # 'NaN': 'nan' } def _print_known_func(self, expr): known = self.known_functions[expr.__class__.__name__] return '{name}({args})'.format(name=self._module_format(known), args=', '.join(map(lambda arg: self._print(arg), expr.args))) def _print_known_const(self, expr): known = self.known_constants[expr.__class__.__name__] return self._module_format(known) class AbstractPythonCodePrinter(CodePrinter): printmethod = "_pythoncode" language = "Python" reserved_words = _kw_py2and3.union(_kw_only_py3) modules = None # initialized to a set in __init__ tab = ' ' _kf = dict(chain( _known_functions.items(), [(k, 'math.' + v) for k, v in _known_functions_math.items()] )) _kc = {k: 'math.'+v for k, v in _known_constants_math.items()} _operators = {'and': 'and', 'or': 'or', 'not': 'not'} _default_settings = dict( CodePrinter._default_settings, user_functions={}, precision=17, inline=True, fully_qualified_modules=True, contract=False, standard='python3', ) def __init__(self, settings=None): super().__init__(settings) # Python standard handler std = self._settings['standard'] if std is None: import sys std = 'python{}'.format(sys.version_info.major) if std not in ('python2', 'python3'): raise ValueError('Unrecognized python standard : {}'.format(std)) self.standard = std self.module_imports = defaultdict(set) # Known functions and constants handler self.known_functions = dict(self._kf, **(settings or {}).get( 'user_functions', {})) self.known_constants = dict(self._kc, **(settings or {}).get( 'user_constants', {})) def _declare_number_const(self, name, value): return "%s = %s" % (name, value) def _module_format(self, fqn, register=True): parts = fqn.split('.') if register and len(parts) > 1: self.module_imports['.'.join(parts[:-1])].add(parts[-1]) if self._settings['fully_qualified_modules']: return fqn else: return fqn.split('(')[0].split('[')[0].split('.')[-1] def _format_code(self, lines): return lines def _get_statement(self, codestring): return "{}".format(codestring) def _get_comment(self, text): return " # {}".format(text) def _expand_fold_binary_op(self, op, args): """ This method expands a fold on binary operations. ``functools.reduce`` is an example of a folded operation. For example, the expression `A + B + C + D` is folded into `((A + B) + C) + D` """ if len(args) == 1: return self._print(args[0]) else: return "%s(%s, %s)" % ( self._module_format(op), self._expand_fold_binary_op(op, args[:-1]), self._print(args[-1]), ) def _expand_reduce_binary_op(self, op, args): """ This method expands a reductin on binary operations. Notice: this is NOT the same as ``functools.reduce``. For example, the expression `A + B + C + D` is reduced into: `(A + B) + (C + D)` """ if len(args) == 1: return self._print(args[0]) else: N = len(args) Nhalf = N // 2 return "%s(%s, %s)" % ( self._module_format(op), self._expand_reduce_binary_op(args[:Nhalf]), self._expand_reduce_binary_op(args[Nhalf:]), ) def _get_einsum_string(self, subranks, contraction_indices): letters = self._get_letter_generator_for_einsum() contraction_string = "" counter = 0 d = {j: min(i) for i in contraction_indices for j in i} indices = [] for rank_arg in subranks: lindices = [] for i in range(rank_arg): if counter in d: lindices.append(d[counter]) else: lindices.append(counter) counter += 1 indices.append(lindices) mapping = {} letters_free = [] letters_dum = [] for i in indices: for j in i: if j not in mapping: l = next(letters) mapping[j] = l else: l = mapping[j] contraction_string += l if j in d: if l not in letters_dum: letters_dum.append(l) else: letters_free.append(l) contraction_string += "," contraction_string = contraction_string[:-1] return contraction_string, letters_free, letters_dum def _print_NaN(self, expr): return "float('nan')" def _print_Infinity(self, expr): return "float('inf')" def _print_NegativeInfinity(self, expr): return "float('-inf')" def _print_ComplexInfinity(self, expr): return self._print_NaN(expr) def _print_Mod(self, expr): PREC = precedence(expr) return ('{} % {}'.format(*map(lambda x: self.parenthesize(x, PREC), expr.args))) def _print_Piecewise(self, expr): result = [] i = 0 for arg in expr.args: e = arg.expr c = arg.cond if i == 0: result.append('(') result.append('(') result.append(self._print(e)) result.append(')') result.append(' if ') result.append(self._print(c)) result.append(' else ') i += 1 result = result[:-1] if result[-1] == 'True': result = result[:-2] result.append(')') else: result.append(' else None)') return ''.join(result) def _print_Relational(self, expr): "Relational printer for Equality and Unequality" op = { '==' :'equal', '!=' :'not_equal', '<' :'less', '<=' :'less_equal', '>' :'greater', '>=' :'greater_equal', } if expr.rel_op in op: lhs = self._print(expr.lhs) rhs = self._print(expr.rhs) return '({lhs} {op} {rhs})'.format(op=expr.rel_op, lhs=lhs, rhs=rhs) return super()._print_Relational(expr) def _print_ITE(self, expr): from sympy.functions.elementary.piecewise import Piecewise return self._print(expr.rewrite(Piecewise)) def _print_Sum(self, expr): loops = ( 'for {i} in range({a}, {b}+1)'.format( i=self._print(i), a=self._print(a), b=self._print(b)) for i, a, b in expr.limits) return '(builtins.sum({function} {loops}))'.format( function=self._print(expr.function), loops=' '.join(loops)) def _print_ImaginaryUnit(self, expr): return '1j' def _print_KroneckerDelta(self, expr): a, b = expr.args return '(1 if {a} == {b} else 0)'.format( a = self._print(a), b = self._print(b) ) def _print_MatrixBase(self, expr): name = expr.__class__.__name__ func = self.known_functions.get(name, name) return "%s(%s)" % (func, self._print(expr.tolist())) _print_SparseMatrix = \ _print_MutableSparseMatrix = \ _print_ImmutableSparseMatrix = \ _print_Matrix = \ _print_DenseMatrix = \ _print_MutableDenseMatrix = \ _print_ImmutableMatrix = \ _print_ImmutableDenseMatrix = \ lambda self, expr: self._print_MatrixBase(expr) def _indent_codestring(self, codestring): return '\n'.join([self.tab + line for line in codestring.split('\n')]) def _print_FunctionDefinition(self, fd): body = '\n'.join(map(lambda arg: self._print(arg), fd.body)) return "def {name}({parameters}):\n{body}".format( name=self._print(fd.name), parameters=', '.join([self._print(var.symbol) for var in fd.parameters]), body=self._indent_codestring(body) ) def _print_While(self, whl): body = '\n'.join(map(lambda arg: self._print(arg), whl.body)) return "while {cond}:\n{body}".format( cond=self._print(whl.condition), body=self._indent_codestring(body) ) def _print_Declaration(self, decl): return '%s = %s' % ( self._print(decl.variable.symbol), self._print(decl.variable.value) ) def _print_Return(self, ret): arg, = ret.args return 'return %s' % self._print(arg) def _print_Print(self, prnt): print_args = ', '.join(map(lambda arg: self._print(arg), prnt.print_args)) if prnt.format_string != None: # Must be '!= None', cannot be 'is not None' print_args = '{} % ({})'.format( self._print(prnt.format_string), print_args) if prnt.file != None: # Must be '!= None', cannot be 'is not None' print_args += ', file=%s' % self._print(prnt.file) if self.standard == 'python2': return 'print %s' % print_args return 'print(%s)' % print_args def _print_Stream(self, strm): if str(strm.name) == 'stdout': return self._module_format('sys.stdout') elif str(strm.name) == 'stderr': return self._module_format('sys.stderr') else: return self._print(strm.name) def _print_NoneToken(self, arg): return 'None' def _hprint_Pow(self, expr, rational=False, sqrt='math.sqrt'): """Printing helper function for ``Pow`` Notes ===== This only preprocesses the ``sqrt`` as math formatter Examples ======== >>> from sympy.functions import sqrt >>> from sympy.printing.pycode import PythonCodePrinter >>> from sympy.abc import x Python code printer automatically looks up ``math.sqrt``. >>> printer = PythonCodePrinter({'standard':'python3'}) >>> printer._hprint_Pow(sqrt(x), rational=True) 'x**(1/2)' >>> printer._hprint_Pow(sqrt(x), rational=False) 'math.sqrt(x)' >>> printer._hprint_Pow(1/sqrt(x), rational=True) 'x**(-1/2)' >>> printer._hprint_Pow(1/sqrt(x), rational=False) '1/math.sqrt(x)' Using sqrt from numpy or mpmath >>> printer._hprint_Pow(sqrt(x), sqrt='numpy.sqrt') 'numpy.sqrt(x)' >>> printer._hprint_Pow(sqrt(x), sqrt='mpmath.sqrt') 'mpmath.sqrt(x)' See Also ======== sympy.printing.str.StrPrinter._print_Pow """ PREC = precedence(expr) if expr.exp == S.Half and not rational: func = self._module_format(sqrt) arg = self._print(expr.base) return '{func}({arg})'.format(func=func, arg=arg) if expr.is_commutative: if -expr.exp is S.Half and not rational: func = self._module_format(sqrt) num = self._print(S.One) arg = self._print(expr.base) return "{num}/{func}({arg})".format( num=num, func=func, arg=arg) base_str = self.parenthesize(expr.base, PREC, strict=False) exp_str = self.parenthesize(expr.exp, PREC, strict=False) return "{}**{}".format(base_str, exp_str) class PythonCodePrinter(AbstractPythonCodePrinter): def _print_sign(self, e): return '(0.0 if {e} == 0 else {f}(1, {e}))'.format( f=self._module_format('math.copysign'), e=self._print(e.args[0])) def _print_Not(self, expr): PREC = precedence(expr) return self._operators['not'] + self.parenthesize(expr.args[0], PREC) def _print_Indexed(self, expr): base = expr.args[0] index = expr.args[1:] return "{}[{}]".format(str(base), ", ".join([self._print(ind) for ind in index])) def _print_Pow(self, expr, rational=False): return self._hprint_Pow(expr, rational=rational) def _print_Rational(self, expr): if self.standard == 'python2': return '{}./{}.'.format(expr.p, expr.q) return '{}/{}'.format(expr.p, expr.q) def _print_Half(self, expr): return self._print_Rational(expr) def _print_frac(self, expr): from sympy import Mod return self._print_Mod(Mod(expr.args[0], 1)) def _print_Symbol(self, expr): name = super()._print_Symbol(expr) if name in self.reserved_words: if self._settings['error_on_reserved']: msg = ('This expression includes the symbol "{}" which is a ' 'reserved keyword in this language.') raise ValueError(msg.format(name)) return name + self._settings['reserved_word_suffix'] elif '{' in name: # Remove curly braces from subscripted variables return name.replace('{', '').replace('}', '') else: return name _print_lowergamma = CodePrinter._print_not_supported _print_uppergamma = CodePrinter._print_not_supported _print_fresnelc = CodePrinter._print_not_supported _print_fresnels = CodePrinter._print_not_supported for k in PythonCodePrinter._kf: setattr(PythonCodePrinter, '_print_%s' % k, _print_known_func) for k in _known_constants_math: setattr(PythonCodePrinter, '_print_%s' % k, _print_known_const) def pycode(expr, **settings): """ Converts an expr to a string of Python code Parameters ========== expr : Expr A SymPy expression. fully_qualified_modules : bool Whether or not to write out full module names of functions (``math.sin`` vs. ``sin``). default: ``True``. standard : str or None, optional If 'python2', Python 2 sematics will be used. If 'python3', Python 3 sematics will be used. If None, the standard will be automatically detected. Default is 'python3'. And this parameter may be removed in the future. Examples ======== >>> from sympy import tan, Symbol >>> from sympy.printing.pycode import pycode >>> pycode(tan(Symbol('x')) + 1) 'math.tan(x) + 1' """ return PythonCodePrinter(settings).doprint(expr) _not_in_mpmath = 'log1p log2'.split() _in_mpmath = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_mpmath] _known_functions_mpmath = dict(_in_mpmath, **{ 'beta': 'beta', 'frac': 'frac', 'fresnelc': 'fresnelc', 'fresnels': 'fresnels', 'sign': 'sign', 'loggamma': 'loggamma', }) _known_constants_mpmath = { 'Exp1': 'e', 'Pi': 'pi', 'GoldenRatio': 'phi', 'EulerGamma': 'euler', 'Catalan': 'catalan', 'NaN': 'nan', 'Infinity': 'inf', 'NegativeInfinity': 'ninf' } def _unpack_integral_limits(integral_expr): """ helper function for _print_Integral that - accepts an Integral expression - returns a tuple of - a list variables of integration - a list of tuples of the upper and lower limits of integration """ integration_vars = [] limits = [] for integration_range in integral_expr.limits: if len(integration_range) == 3: integration_var, lower_limit, upper_limit = integration_range else: raise NotImplementedError("Only definite integrals are supported") integration_vars.append(integration_var) limits.append((lower_limit, upper_limit)) return integration_vars, limits class MpmathPrinter(PythonCodePrinter): """ Lambda printer for mpmath which maintains precision for floats """ printmethod = "_mpmathcode" language = "Python with mpmath" _kf = dict(chain( _known_functions.items(), [(k, 'mpmath.' + v) for k, v in _known_functions_mpmath.items()] )) _kc = {k: 'mpmath.'+v for k, v in _known_constants_mpmath.items()} def _print_Float(self, e): # XXX: This does not handle setting mpmath.mp.dps. It is assumed that # the caller of the lambdified function will have set it to sufficient # precision to match the Floats in the expression. # Remove 'mpz' if gmpy is installed. args = str(tuple(map(int, e._mpf_))) return '{func}({args})'.format(func=self._module_format('mpmath.mpf'), args=args) def _print_Rational(self, e): return "{func}({p})/{func}({q})".format( func=self._module_format('mpmath.mpf'), q=self._print(e.q), p=self._print(e.p) ) def _print_Half(self, e): return self._print_Rational(e) def _print_uppergamma(self, e): return "{}({}, {}, {})".format( self._module_format('mpmath.gammainc'), self._print(e.args[0]), self._print(e.args[1]), self._module_format('mpmath.inf')) def _print_lowergamma(self, e): return "{}({}, 0, {})".format( self._module_format('mpmath.gammainc'), self._print(e.args[0]), self._print(e.args[1])) def _print_log2(self, e): return '{0}({1})/{0}(2)'.format( self._module_format('mpmath.log'), self._print(e.args[0])) def _print_log1p(self, e): return '{}({}+1)'.format( self._module_format('mpmath.log'), self._print(e.args[0])) def _print_Pow(self, expr, rational=False): return self._hprint_Pow(expr, rational=rational, sqrt='mpmath.sqrt') def _print_Integral(self, e): integration_vars, limits = _unpack_integral_limits(e) return "{}(lambda {}: {}, {})".format( self._module_format("mpmath.quad"), ", ".join(map(self._print, integration_vars)), self._print(e.args[0]), ", ".join("(%s, %s)" % tuple(map(self._print, l)) for l in limits)) for k in MpmathPrinter._kf: setattr(MpmathPrinter, '_print_%s' % k, _print_known_func) for k in _known_constants_mpmath: setattr(MpmathPrinter, '_print_%s' % k, _print_known_const) class SymPyPrinter(AbstractPythonCodePrinter): language = "Python with SymPy" def _print_Function(self, expr): mod = expr.func.__module__ or '' return '%s(%s)' % (self._module_format(mod + ('.' if mod else '') + expr.func.__name__), ', '.join(map(lambda arg: self._print(arg), expr.args))) def _print_Pow(self, expr, rational=False): return self._hprint_Pow(expr, rational=rational, sqrt='sympy.sqrt')
f65fc8a15054868f7c114f5190d4c7ac88cd47d1547ef984118e2de79f57feee
""" A Printer for generating readable representation of most sympy classes. """ from typing import Any, Dict from sympy.core import S, Rational, Pow, Basic, Mul, Number from sympy.core.mul import _keep_coeff from sympy.core.function import _coeff_isneg from sympy.sets.sets import FiniteSet from .printer import Printer, print_function from sympy.printing.precedence import precedence, PRECEDENCE from mpmath.libmp import prec_to_dps, to_str as mlib_to_str from sympy.utilities import default_sort_key, sift class StrPrinter(Printer): printmethod = "_sympystr" _default_settings = { "order": None, "full_prec": "auto", "sympy_integers": False, "abbrev": False, "perm_cyclic": True, "min": None, "max": None, } # type: Dict[str, Any] _relationals = dict() # type: Dict[str, str] def parenthesize(self, item, level, strict=False): if (precedence(item) < level) or ((not strict) and precedence(item) <= level): return "(%s)" % self._print(item) else: return self._print(item) def stringify(self, args, sep, level=0): return sep.join([self.parenthesize(item, level) for item in args]) def emptyPrinter(self, expr): if isinstance(expr, str): return expr elif isinstance(expr, Basic): return repr(expr) else: return str(expr) def _print_Add(self, expr, order=None): terms = self._as_ordered_terms(expr, order=order) PREC = precedence(expr) l = [] for term in terms: t = self._print(term) if t.startswith('-'): sign = "-" t = t[1:] else: sign = "+" if precedence(term) < PREC: l.extend([sign, "(%s)" % t]) else: l.extend([sign, t]) sign = l.pop(0) if sign == '+': sign = "" return sign + ' '.join(l) def _print_BooleanTrue(self, expr): return "True" def _print_BooleanFalse(self, expr): return "False" def _print_Not(self, expr): return '~%s' %(self.parenthesize(expr.args[0],PRECEDENCE["Not"])) def _print_And(self, expr): return self.stringify(expr.args, " & ", PRECEDENCE["BitwiseAnd"]) def _print_Or(self, expr): return self.stringify(expr.args, " | ", PRECEDENCE["BitwiseOr"]) def _print_Xor(self, expr): return self.stringify(expr.args, " ^ ", PRECEDENCE["BitwiseXor"]) def _print_AppliedPredicate(self, expr): return '%s(%s)' % ( self._print(expr.function), self.stringify(expr.arguments, ", ")) def _print_Basic(self, expr): l = [self._print(o) for o in expr.args] return expr.__class__.__name__ + "(%s)" % ", ".join(l) def _print_BlockMatrix(self, B): if B.blocks.shape == (1, 1): self._print(B.blocks[0, 0]) return self._print(B.blocks) def _print_Catalan(self, expr): return 'Catalan' def _print_ComplexInfinity(self, expr): return 'zoo' def _print_ConditionSet(self, s): args = tuple([self._print(i) for i in (s.sym, s.condition)]) if s.base_set is S.UniversalSet: return 'ConditionSet(%s, %s)' % args args += (self._print(s.base_set),) return 'ConditionSet(%s, %s, %s)' % args def _print_Derivative(self, expr): dexpr = expr.expr dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count] return 'Derivative(%s)' % ", ".join(map(lambda arg: self._print(arg), [dexpr] + dvars)) def _print_dict(self, d): keys = sorted(d.keys(), key=default_sort_key) items = [] for key in keys: item = "%s: %s" % (self._print(key), self._print(d[key])) items.append(item) return "{%s}" % ", ".join(items) def _print_Dict(self, expr): return self._print_dict(expr) def _print_RandomDomain(self, d): if hasattr(d, 'as_boolean'): return 'Domain: ' + self._print(d.as_boolean()) elif hasattr(d, 'set'): return ('Domain: ' + self._print(d.symbols) + ' in ' + self._print(d.set)) else: return 'Domain on ' + self._print(d.symbols) def _print_Dummy(self, expr): return '_' + expr.name def _print_EulerGamma(self, expr): return 'EulerGamma' def _print_Exp1(self, expr): return 'E' def _print_ExprCondPair(self, expr): return '(%s, %s)' % (self._print(expr.expr), self._print(expr.cond)) def _print_Function(self, expr): return expr.func.__name__ + "(%s)" % self.stringify(expr.args, ", ") def _print_GoldenRatio(self, expr): return 'GoldenRatio' def _print_TribonacciConstant(self, expr): return 'TribonacciConstant' def _print_ImaginaryUnit(self, expr): return 'I' def _print_Infinity(self, expr): return 'oo' def _print_Integral(self, expr): def _xab_tostr(xab): if len(xab) == 1: return self._print(xab[0]) else: return self._print((xab[0],) + tuple(xab[1:])) L = ', '.join([_xab_tostr(l) for l in expr.limits]) return 'Integral(%s, %s)' % (self._print(expr.function), L) def _print_Interval(self, i): fin = 'Interval{m}({a}, {b})' a, b, l, r = i.args if a.is_infinite and b.is_infinite: m = '' elif a.is_infinite and not r: m = '' elif b.is_infinite and not l: m = '' elif not l and not r: m = '' elif l and r: m = '.open' elif l: m = '.Lopen' else: m = '.Ropen' return fin.format(**{'a': a, 'b': b, 'm': m}) def _print_AccumulationBounds(self, i): return "AccumBounds(%s, %s)" % (self._print(i.min), self._print(i.max)) def _print_Inverse(self, I): return "%s**(-1)" % self.parenthesize(I.arg, PRECEDENCE["Pow"]) def _print_Lambda(self, obj): expr = obj.expr sig = obj.signature if len(sig) == 1 and sig[0].is_symbol: sig = sig[0] return "Lambda(%s, %s)" % (self._print(sig), self._print(expr)) def _print_LatticeOp(self, expr): args = sorted(expr.args, key=default_sort_key) return expr.func.__name__ + "(%s)" % ", ".join(self._print(arg) for arg in args) def _print_Limit(self, expr): e, z, z0, dir = expr.args if str(dir) == "+": return "Limit(%s, %s, %s)" % tuple(map(self._print, (e, z, z0))) else: return "Limit(%s, %s, %s, dir='%s')" % tuple(map(self._print, (e, z, z0, dir))) def _print_list(self, expr): return "[%s]" % self.stringify(expr, ", ") def _print_MatrixBase(self, expr): return expr._format_str(self) def _print_MatrixElement(self, expr): return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \ + '[%s, %s]' % (self._print(expr.i), self._print(expr.j)) def _print_MatrixSlice(self, expr): def strslice(x, dim): x = list(x) if x[2] == 1: del x[2] if x[0] == 0: x[0] = '' if x[1] == dim: x[1] = '' return ':'.join(map(lambda arg: self._print(arg), x)) return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + '[' + strslice(expr.rowslice, expr.parent.rows) + ', ' + strslice(expr.colslice, expr.parent.cols) + ']') def _print_DeferredVector(self, expr): return expr.name def _print_Mul(self, expr): prec = precedence(expr) # Check for unevaluated Mul. In this case we need to make sure the # identities are visible, multiple Rational factors are not combined # etc so we display in a straight-forward form that fully preserves all # args and their order. args = expr.args if args[0] is S.One or any( isinstance(a, Number) or a.is_Pow and all(ai.is_Integer for ai in a.args) for a in args[1:]): d, n = sift(args, lambda x: isinstance(x, Pow) and bool(x.exp.as_coeff_Mul()[0] < 0), binary=True) for i, di in enumerate(d): if di.exp.is_Number: e = -di.exp else: dargs = list(di.exp.args) dargs[0] = -dargs[0] e = Mul._from_args(dargs) d[i] = Pow(di.base, e, evaluate=False) if e - 1 else di.base # don't parenthesize first factor if negative if _coeff_isneg(n[0]): pre = [str(n.pop(0))] else: pre = [] nfactors = pre + [self.parenthesize(a, prec, strict=False) for a in n] # don't parenthesize first of denominator unless singleton if len(d) > 1 and _coeff_isneg(d[0]): pre = [str(d.pop(0))] else: pre = [] dfactors = pre + [self.parenthesize(a, prec, strict=False) for a in d] n = '*'.join(nfactors) d = '*'.join(dfactors) if len(dfactors) > 1: return '%s/(%s)' % (n, d) elif dfactors: return '%s/%s' % (n, d) return n c, e = expr.as_coeff_Mul() if c < 0: expr = _keep_coeff(-c, e) sign = "-" else: sign = "" a = [] # items in the numerator b = [] # items that are in the denominator (if any) pow_paren = [] # Will collect all pow with more than one base element and exp = -1 if self.order not in ('old', 'none'): args = expr.as_ordered_factors() else: # use make_args in case expr was something like -x -> x args = Mul.make_args(expr) # Gather args for numerator/denominator def apow(i): b, e = i.as_base_exp() eargs = list(Mul.make_args(e)) if eargs[0] is S.NegativeOne: eargs = eargs[1:] else: eargs[0] = -eargs[0] e = Mul._from_args(eargs) if isinstance(i, Pow): return i.func(b, e, evaluate=False) return i.func(e, evaluate=False) for item in args: if (item.is_commutative and isinstance(item, Pow) and bool(item.exp.as_coeff_Mul()[0] < 0)): if item.exp is not S.NegativeOne: b.append(apow(item)) else: if (len(item.args[0].args) != 1 and isinstance(item.base, (Mul, Pow))): # To avoid situations like #14160 pow_paren.append(item) b.append(item.base) elif item.is_Rational and item is not S.Infinity: if item.p != 1: a.append(Rational(item.p)) if item.q != 1: b.append(Rational(item.q)) else: a.append(item) a = a or [S.One] a_str = [self.parenthesize(x, prec, strict=False) for x in a] b_str = [self.parenthesize(x, prec, strict=False) for x in b] # To parenthesize Pow with exp = -1 and having more than one Symbol for item in pow_paren: if item.base in b: b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)] if not b: return sign + '*'.join(a_str) elif len(b) == 1: return sign + '*'.join(a_str) + "/" + b_str[0] else: return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str) def _print_MatMul(self, expr): c, m = expr.as_coeff_mmul() sign = "" if c.is_number: re, im = c.as_real_imag() if im.is_zero and re.is_negative: expr = _keep_coeff(-c, m) sign = "-" elif re.is_zero and im.is_negative: expr = _keep_coeff(-c, m) sign = "-" return sign + '*'.join( [self.parenthesize(arg, precedence(expr)) for arg in expr.args] ) def _print_ElementwiseApplyFunction(self, expr): return "{}.({})".format( expr.function, self._print(expr.expr), ) def _print_NaN(self, expr): return 'nan' def _print_NegativeInfinity(self, expr): return '-oo' def _print_Order(self, expr): if not expr.variables or all(p is S.Zero for p in expr.point): if len(expr.variables) <= 1: return 'O(%s)' % self._print(expr.expr) else: return 'O(%s)' % self.stringify((expr.expr,) + expr.variables, ', ', 0) else: return 'O(%s)' % self.stringify(expr.args, ', ', 0) def _print_Ordinal(self, expr): return expr.__str__() def _print_Cycle(self, expr): return expr.__str__() def _print_Permutation(self, expr): from sympy.combinatorics.permutations import Permutation, Cycle from sympy.utilities.exceptions import SymPyDeprecationWarning perm_cyclic = Permutation.print_cyclic if perm_cyclic is not None: SymPyDeprecationWarning( feature="Permutation.print_cyclic = {}".format(perm_cyclic), useinstead="init_printing(perm_cyclic={})" .format(perm_cyclic), issue=15201, deprecated_since_version="1.6").warn() else: perm_cyclic = self._settings.get("perm_cyclic", True) if perm_cyclic: if not expr.size: return '()' # before taking Cycle notation, see if the last element is # a singleton and move it to the head of the string s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):] last = s.rfind('(') if not last == 0 and ',' not in s[last:]: s = s[last:] + s[:last] s = s.replace(',', '') return s else: s = expr.support() if not s: if expr.size < 5: return 'Permutation(%s)' % self._print(expr.array_form) return 'Permutation([], size=%s)' % self._print(expr.size) trim = self._print(expr.array_form[:s[-1] + 1]) + ', size=%s' % self._print(expr.size) use = full = self._print(expr.array_form) if len(trim) < len(full): use = trim return 'Permutation(%s)' % use def _print_Subs(self, obj): expr, old, new = obj.args if len(obj.point) == 1: old = old[0] new = new[0] return "Subs(%s, %s, %s)" % ( self._print(expr), self._print(old), self._print(new)) def _print_TensorIndex(self, expr): return expr._print() def _print_TensorHead(self, expr): return expr._print() def _print_Tensor(self, expr): return expr._print() def _print_TensMul(self, expr): # prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)" sign, args = expr._get_args_for_traditional_printer() return sign + "*".join( [self.parenthesize(arg, precedence(expr)) for arg in args] ) def _print_TensAdd(self, expr): return expr._print() def _print_ArraySymbol(self, expr): return self._print(expr.name) def _print_ArrayElement(self, expr): return "%s[%s]" % (expr.name, ", ".join([self._print(i) for i in expr.indices])) def _print_PermutationGroup(self, expr): p = [' %s' % self._print(a) for a in expr.args] return 'PermutationGroup([\n%s])' % ',\n'.join(p) def _print_Pi(self, expr): return 'pi' def _print_PolyRing(self, ring): return "Polynomial ring in %s over %s with %s order" % \ (", ".join(map(lambda rs: self._print(rs), ring.symbols)), self._print(ring.domain), self._print(ring.order)) def _print_FracField(self, field): return "Rational function field in %s over %s with %s order" % \ (", ".join(map(lambda fs: self._print(fs), field.symbols)), self._print(field.domain), self._print(field.order)) def _print_FreeGroupElement(self, elm): return elm.__str__() def _print_GaussianElement(self, poly): return "(%s + %s*I)" % (poly.x, poly.y) def _print_PolyElement(self, poly): return poly.str(self, PRECEDENCE, "%s**%s", "*") def _print_FracElement(self, frac): if frac.denom == 1: return self._print(frac.numer) else: numer = self.parenthesize(frac.numer, PRECEDENCE["Mul"], strict=True) denom = self.parenthesize(frac.denom, PRECEDENCE["Atom"], strict=True) return numer + "/" + denom def _print_Poly(self, expr): ATOM_PREC = PRECEDENCE["Atom"] - 1 terms, gens = [], [ self.parenthesize(s, ATOM_PREC) for s in expr.gens ] for monom, coeff in expr.terms(): s_monom = [] for i, e in enumerate(monom): if e > 0: if e == 1: s_monom.append(gens[i]) else: s_monom.append(gens[i] + "**%d" % e) s_monom = "*".join(s_monom) if coeff.is_Add: if s_monom: s_coeff = "(" + self._print(coeff) + ")" else: s_coeff = self._print(coeff) else: if s_monom: if coeff is S.One: terms.extend(['+', s_monom]) continue if coeff is S.NegativeOne: terms.extend(['-', s_monom]) continue s_coeff = self._print(coeff) if not s_monom: s_term = s_coeff else: s_term = s_coeff + "*" + s_monom if s_term.startswith('-'): terms.extend(['-', s_term[1:]]) else: terms.extend(['+', s_term]) if terms[0] in ('-', '+'): modifier = terms.pop(0) if modifier == '-': terms[0] = '-' + terms[0] format = expr.__class__.__name__ + "(%s, %s" from sympy.polys.polyerrors import PolynomialError try: format += ", modulus=%s" % expr.get_modulus() except PolynomialError: format += ", domain='%s'" % expr.get_domain() format += ")" for index, item in enumerate(gens): if len(item) > 2 and (item[:1] == "(" and item[len(item) - 1:] == ")"): gens[index] = item[1:len(item) - 1] return format % (' '.join(terms), ', '.join(gens)) def _print_UniversalSet(self, p): return 'UniversalSet' def _print_AlgebraicNumber(self, expr): if expr.is_aliased: return self._print(expr.as_poly().as_expr()) else: return self._print(expr.as_expr()) def _print_Pow(self, expr, rational=False): """Printing helper function for ``Pow`` Parameters ========== rational : bool, optional If ``True``, it will not attempt printing ``sqrt(x)`` or ``x**S.Half`` as ``sqrt``, and will use ``x**(1/2)`` instead. See examples for additional details Examples ======== >>> from sympy.functions import sqrt >>> from sympy.printing.str import StrPrinter >>> from sympy.abc import x How ``rational`` keyword works with ``sqrt``: >>> printer = StrPrinter() >>> printer._print_Pow(sqrt(x), rational=True) 'x**(1/2)' >>> printer._print_Pow(sqrt(x), rational=False) 'sqrt(x)' >>> printer._print_Pow(1/sqrt(x), rational=True) 'x**(-1/2)' >>> printer._print_Pow(1/sqrt(x), rational=False) '1/sqrt(x)' Notes ===== ``sqrt(x)`` is canonicalized as ``Pow(x, S.Half)`` in SymPy, so there is no need of defining a separate printer for ``sqrt``. Instead, it should be handled here as well. """ PREC = precedence(expr) if expr.exp is S.Half and not rational: return "sqrt(%s)" % self._print(expr.base) if expr.is_commutative: if -expr.exp is S.Half and not rational: # Note: Don't test "expr.exp == -S.Half" here, because that will # match -0.5, which we don't want. return "%s/sqrt(%s)" % tuple(map(lambda arg: self._print(arg), (S.One, expr.base))) if expr.exp is -S.One: # Similarly to the S.Half case, don't test with "==" here. return '%s/%s' % (self._print(S.One), self.parenthesize(expr.base, PREC, strict=False)) e = self.parenthesize(expr.exp, PREC, strict=False) if self.printmethod == '_sympyrepr' and expr.exp.is_Rational and expr.exp.q != 1: # the parenthesized exp should be '(Rational(a, b))' so strip parens, # but just check to be sure. if e.startswith('(Rational'): return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e[1:-1]) return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e) def _print_UnevaluatedExpr(self, expr): return self._print(expr.args[0]) def _print_MatPow(self, expr): PREC = precedence(expr) return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), self.parenthesize(expr.exp, PREC, strict=False)) def _print_Integer(self, expr): if self._settings.get("sympy_integers", False): return "S(%s)" % (expr) return str(expr.p) def _print_Integers(self, expr): return 'Integers' def _print_Naturals(self, expr): return 'Naturals' def _print_Naturals0(self, expr): return 'Naturals0' def _print_Rationals(self, expr): return 'Rationals' def _print_Reals(self, expr): return 'Reals' def _print_Complexes(self, expr): return 'Complexes' def _print_EmptySet(self, expr): return 'EmptySet' def _print_EmptySequence(self, expr): return 'EmptySequence' def _print_int(self, expr): return str(expr) def _print_mpz(self, expr): return str(expr) def _print_Rational(self, expr): if expr.q == 1: return str(expr.p) else: if self._settings.get("sympy_integers", False): return "S(%s)/%s" % (expr.p, expr.q) return "%s/%s" % (expr.p, expr.q) def _print_PythonRational(self, expr): if expr.q == 1: return str(expr.p) else: return "%d/%d" % (expr.p, expr.q) def _print_Fraction(self, expr): if expr.denominator == 1: return str(expr.numerator) else: return "%s/%s" % (expr.numerator, expr.denominator) def _print_mpq(self, expr): if expr.denominator == 1: return str(expr.numerator) else: return "%s/%s" % (expr.numerator, expr.denominator) def _print_Float(self, expr): prec = expr._prec if prec < 5: dps = 0 else: dps = prec_to_dps(expr._prec) if self._settings["full_prec"] is True: strip = False elif self._settings["full_prec"] is False: strip = True elif self._settings["full_prec"] == "auto": strip = self._print_level > 1 low = self._settings["min"] if "min" in self._settings else None high = self._settings["max"] if "max" in self._settings else None rv = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high) if rv.startswith('-.0'): rv = '-0.' + rv[3:] elif rv.startswith('.0'): rv = '0.' + rv[2:] if rv.startswith('+'): # e.g., +inf -> inf rv = rv[1:] return rv def _print_Relational(self, expr): charmap = { "==": "Eq", "!=": "Ne", ":=": "Assignment", '+=': "AddAugmentedAssignment", "-=": "SubAugmentedAssignment", "*=": "MulAugmentedAssignment", "/=": "DivAugmentedAssignment", "%=": "ModAugmentedAssignment", } if expr.rel_op in charmap: return '%s(%s, %s)' % (charmap[expr.rel_op], self._print(expr.lhs), self._print(expr.rhs)) return '%s %s %s' % (self.parenthesize(expr.lhs, precedence(expr)), self._relationals.get(expr.rel_op) or expr.rel_op, self.parenthesize(expr.rhs, precedence(expr))) def _print_ComplexRootOf(self, expr): return "CRootOf(%s, %d)" % (self._print_Add(expr.expr, order='lex'), expr.index) def _print_RootSum(self, expr): args = [self._print_Add(expr.expr, order='lex')] if expr.fun is not S.IdentityFunction: args.append(self._print(expr.fun)) return "RootSum(%s)" % ", ".join(args) def _print_GroebnerBasis(self, basis): cls = basis.__class__.__name__ exprs = [self._print_Add(arg, order=basis.order) for arg in basis.exprs] exprs = "[%s]" % ", ".join(exprs) gens = [ self._print(gen) for gen in basis.gens ] domain = "domain='%s'" % self._print(basis.domain) order = "order='%s'" % self._print(basis.order) args = [exprs] + gens + [domain, order] return "%s(%s)" % (cls, ", ".join(args)) def _print_set(self, s): items = sorted(s, key=default_sort_key) args = ', '.join(self._print(item) for item in items) if not args: return "set()" return '{%s}' % args def _print_FiniteSet(self, s): items = sorted(s, key=default_sort_key) args = ', '.join(self._print(item) for item in items) if any(item.has(FiniteSet) for item in items): return 'FiniteSet({})'.format(args) return '{{{}}}'.format(args) def _print_Partition(self, s): items = sorted(s, key=default_sort_key) args = ', '.join(self._print(arg) for arg in items) return 'Partition({})'.format(args) def _print_frozenset(self, s): if not s: return "frozenset()" return "frozenset(%s)" % self._print_set(s) def _print_Sum(self, expr): def _xab_tostr(xab): if len(xab) == 1: return self._print(xab[0]) else: return self._print((xab[0],) + tuple(xab[1:])) L = ', '.join([_xab_tostr(l) for l in expr.limits]) return 'Sum(%s, %s)' % (self._print(expr.function), L) def _print_Symbol(self, expr): return expr.name _print_MatrixSymbol = _print_Symbol _print_RandomSymbol = _print_Symbol def _print_Identity(self, expr): return "I" def _print_ZeroMatrix(self, expr): return "0" def _print_OneMatrix(self, expr): return "1" def _print_Predicate(self, expr): return "Q.%s" % expr.name def _print_str(self, expr): return str(expr) def _print_tuple(self, expr): if len(expr) == 1: return "(%s,)" % self._print(expr[0]) else: return "(%s)" % self.stringify(expr, ", ") def _print_Tuple(self, expr): return self._print_tuple(expr) def _print_Transpose(self, T): return "%s.T" % self.parenthesize(T.arg, PRECEDENCE["Pow"]) def _print_Uniform(self, expr): return "Uniform(%s, %s)" % (self._print(expr.a), self._print(expr.b)) def _print_Quantity(self, expr): if self._settings.get("abbrev", False): return "%s" % expr.abbrev return "%s" % expr.name def _print_Quaternion(self, expr): s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True) for i in expr.args] a = [s[0]] + [i+"*"+j for i, j in zip(s[1:], "ijk")] return " + ".join(a) def _print_Dimension(self, expr): return str(expr) def _print_Wild(self, expr): return expr.name + '_' def _print_WildFunction(self, expr): return expr.name + '_' def _print_WildDot(self, expr): return expr.name def _print_WildPlus(self, expr): return expr.name def _print_WildStar(self, expr): return expr.name def _print_Zero(self, expr): if self._settings.get("sympy_integers", False): return "S(0)" return "0" def _print_DMP(self, p): from sympy.core.sympify import SympifyError try: if p.ring is not None: # TODO incorporate order return self._print(p.ring.to_sympy(p)) except SympifyError: pass cls = p.__class__.__name__ rep = self._print(p.rep) dom = self._print(p.dom) ring = self._print(p.ring) return "%s(%s, %s, %s)" % (cls, rep, dom, ring) def _print_DMF(self, expr): return self._print_DMP(expr) def _print_Object(self, obj): return 'Object("%s")' % obj.name def _print_IdentityMorphism(self, morphism): return 'IdentityMorphism(%s)' % morphism.domain def _print_NamedMorphism(self, morphism): return 'NamedMorphism(%s, %s, "%s")' % \ (morphism.domain, morphism.codomain, morphism.name) def _print_Category(self, category): return 'Category("%s")' % category.name def _print_Manifold(self, manifold): return manifold.name.name def _print_Patch(self, patch): return patch.name.name def _print_CoordSystem(self, coords): return coords.name.name def _print_BaseScalarField(self, field): return field._coord_sys.symbols[field._index].name def _print_BaseVectorField(self, field): return 'e_%s' % field._coord_sys.symbols[field._index].name def _print_Differential(self, diff): field = diff._form_field if hasattr(field, '_coord_sys'): return 'd%s' % field._coord_sys.symbols[field._index].name else: return 'd(%s)' % self._print(field) def _print_Tr(self, expr): #TODO : Handle indices return "%s(%s)" % ("Tr", self._print(expr.args[0])) def _print_Str(self, s): return self._print(s.name) def _print_AppliedBinaryRelation(self, expr): rel = expr.function return '%s(%s, %s)' % (self._print(rel), self._print(expr.lhs), self._print(expr.rhs)) @print_function(StrPrinter) def sstr(expr, **settings): """Returns the expression as a string. For large expressions where speed is a concern, use the setting order='none'. If abbrev=True setting is used then units are printed in abbreviated form. Examples ======== >>> from sympy import symbols, Eq, sstr >>> a, b = symbols('a b') >>> sstr(Eq(a + b, 0)) 'Eq(a + b, 0)' """ p = StrPrinter(settings) s = p.doprint(expr) return s class StrReprPrinter(StrPrinter): """(internal) -- see sstrrepr""" def _print_str(self, s): return repr(s) def _print_Str(self, s): # Str does not to be printed same as str here return "%s(%s)" % (s.__class__.__name__, self._print(s.name)) @print_function(StrReprPrinter) def sstrrepr(expr, **settings): """return expr in mixed str/repr form i.e. strings are returned in repr form with quotes, and everything else is returned in str form. This function could be useful for hooking into sys.displayhook """ p = StrReprPrinter(settings) s = p.doprint(expr) return s
41992b7b85a98538d70273009681424ad0c1c62c22c7bb4bcf5aaa5e17b59699
''' Use llvmlite to create executable functions from Sympy expressions This module requires llvmlite (https://github.com/numba/llvmlite). ''' import ctypes from sympy.external import import_module from sympy.printing.printer import Printer from sympy import S, IndexedBase from sympy.utilities.decorator import doctest_depends_on llvmlite = import_module('llvmlite') if llvmlite: ll = import_module('llvmlite.ir').ir llvm = import_module('llvmlite.binding').binding llvm.initialize() llvm.initialize_native_target() llvm.initialize_native_asmprinter() __doctest_requires__ = {('llvm_callable'): ['llvmlite']} class LLVMJitPrinter(Printer): '''Convert expressions to LLVM IR''' def __init__(self, module, builder, fn, *args, **kwargs): self.func_arg_map = kwargs.pop("func_arg_map", {}) if not llvmlite: raise ImportError("llvmlite is required for LLVMJITPrinter") super().__init__(*args, **kwargs) self.fp_type = ll.DoubleType() self.module = module self.builder = builder self.fn = fn self.ext_fn = {} # keep track of wrappers to external functions self.tmp_var = {} def _add_tmp_var(self, name, value): self.tmp_var[name] = value def _print_Number(self, n): return ll.Constant(self.fp_type, float(n)) def _print_Integer(self, expr): return ll.Constant(self.fp_type, float(expr.p)) def _print_Symbol(self, s): val = self.tmp_var.get(s) if not val: # look up parameter with name s val = self.func_arg_map.get(s) if not val: raise LookupError("Symbol not found: %s" % s) return val def _print_Pow(self, expr): base0 = self._print(expr.base) if expr.exp == S.NegativeOne: return self.builder.fdiv(ll.Constant(self.fp_type, 1.0), base0) if expr.exp == S.Half: fn = self.ext_fn.get("sqrt") if not fn: fn_type = ll.FunctionType(self.fp_type, [self.fp_type]) fn = ll.Function(self.module, fn_type, "sqrt") self.ext_fn["sqrt"] = fn return self.builder.call(fn, [base0], "sqrt") if expr.exp == 2: return self.builder.fmul(base0, base0) exp0 = self._print(expr.exp) fn = self.ext_fn.get("pow") if not fn: fn_type = ll.FunctionType(self.fp_type, [self.fp_type, self.fp_type]) fn = ll.Function(self.module, fn_type, "pow") self.ext_fn["pow"] = fn return self.builder.call(fn, [base0, exp0], "pow") def _print_Mul(self, expr): nodes = [self._print(a) for a in expr.args] e = nodes[0] for node in nodes[1:]: e = self.builder.fmul(e, node) return e def _print_Add(self, expr): nodes = [self._print(a) for a in expr.args] e = nodes[0] for node in nodes[1:]: e = self.builder.fadd(e, node) return e # TODO - assumes all called functions take one double precision argument. # Should have a list of math library functions to validate this. def _print_Function(self, expr): name = expr.func.__name__ e0 = self._print(expr.args[0]) fn = self.ext_fn.get(name) if not fn: fn_type = ll.FunctionType(self.fp_type, [self.fp_type]) fn = ll.Function(self.module, fn_type, name) self.ext_fn[name] = fn return self.builder.call(fn, [e0], name) def emptyPrinter(self, expr): raise TypeError("Unsupported type for LLVM JIT conversion: %s" % type(expr)) # Used when parameters are passed by array. Often used in callbacks to # handle a variable number of parameters. class LLVMJitCallbackPrinter(LLVMJitPrinter): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _print_Indexed(self, expr): array, idx = self.func_arg_map[expr.base] offset = int(expr.indices[0].evalf()) array_ptr = self.builder.gep(array, [ll.Constant(ll.IntType(32), offset)]) fp_array_ptr = self.builder.bitcast(array_ptr, ll.PointerType(self.fp_type)) value = self.builder.load(fp_array_ptr) return value def _print_Symbol(self, s): val = self.tmp_var.get(s) if val: return val array, idx = self.func_arg_map.get(s, [None, 0]) if not array: raise LookupError("Symbol not found: %s" % s) array_ptr = self.builder.gep(array, [ll.Constant(ll.IntType(32), idx)]) fp_array_ptr = self.builder.bitcast(array_ptr, ll.PointerType(self.fp_type)) value = self.builder.load(fp_array_ptr) return value # ensure lifetime of the execution engine persists (else call to compiled # function will seg fault) exe_engines = [] # ensure names for generated functions are unique link_names = set() current_link_suffix = 0 class LLVMJitCode: def __init__(self, signature): self.signature = signature self.fp_type = ll.DoubleType() self.module = ll.Module('mod1') self.fn = None self.llvm_arg_types = [] self.llvm_ret_type = self.fp_type self.param_dict = {} # map symbol name to LLVM function argument self.link_name = '' def _from_ctype(self, ctype): if ctype == ctypes.c_int: return ll.IntType(32) if ctype == ctypes.c_double: return self.fp_type if ctype == ctypes.POINTER(ctypes.c_double): return ll.PointerType(self.fp_type) if ctype == ctypes.c_void_p: return ll.PointerType(ll.IntType(32)) if ctype == ctypes.py_object: return ll.PointerType(ll.IntType(32)) print("Unhandled ctype = %s" % str(ctype)) def _create_args(self, func_args): """Create types for function arguments""" self.llvm_ret_type = self._from_ctype(self.signature.ret_type) self.llvm_arg_types = \ [self._from_ctype(a) for a in self.signature.arg_ctypes] def _create_function_base(self): """Create function with name and type signature""" global link_names, current_link_suffix default_link_name = 'jit_func' current_link_suffix += 1 self.link_name = default_link_name + str(current_link_suffix) link_names.add(self.link_name) fn_type = ll.FunctionType(self.llvm_ret_type, self.llvm_arg_types) self.fn = ll.Function(self.module, fn_type, name=self.link_name) def _create_param_dict(self, func_args): """Mapping of symbolic values to function arguments""" for i, a in enumerate(func_args): self.fn.args[i].name = str(a) self.param_dict[a] = self.fn.args[i] def _create_function(self, expr): """Create function body and return LLVM IR""" bb_entry = self.fn.append_basic_block('entry') builder = ll.IRBuilder(bb_entry) lj = LLVMJitPrinter(self.module, builder, self.fn, func_arg_map=self.param_dict) ret = self._convert_expr(lj, expr) lj.builder.ret(self._wrap_return(lj, ret)) strmod = str(self.module) return strmod def _wrap_return(self, lj, vals): # Return a single double if there is one return value, # else return a tuple of doubles. # Don't wrap return value in this case if self.signature.ret_type == ctypes.c_double: return vals[0] # Use this instead of a real PyObject* void_ptr = ll.PointerType(ll.IntType(32)) # Create a wrapped double: PyObject* PyFloat_FromDouble(double v) wrap_type = ll.FunctionType(void_ptr, [self.fp_type]) wrap_fn = ll.Function(lj.module, wrap_type, "PyFloat_FromDouble") wrapped_vals = [lj.builder.call(wrap_fn, [v]) for v in vals] if len(vals) == 1: final_val = wrapped_vals[0] else: # Create a tuple: PyObject* PyTuple_Pack(Py_ssize_t n, ...) # This should be Py_ssize_t tuple_arg_types = [ll.IntType(32)] tuple_arg_types.extend([void_ptr]*len(vals)) tuple_type = ll.FunctionType(void_ptr, tuple_arg_types) tuple_fn = ll.Function(lj.module, tuple_type, "PyTuple_Pack") tuple_args = [ll.Constant(ll.IntType(32), len(wrapped_vals))] tuple_args.extend(wrapped_vals) final_val = lj.builder.call(tuple_fn, tuple_args) return final_val def _convert_expr(self, lj, expr): try: # Match CSE return data structure. if len(expr) == 2: tmp_exprs = expr[0] final_exprs = expr[1] if len(final_exprs) != 1 and self.signature.ret_type == ctypes.c_double: raise NotImplementedError("Return of multiple expressions not supported for this callback") for name, e in tmp_exprs: val = lj._print(e) lj._add_tmp_var(name, val) except TypeError: final_exprs = [expr] vals = [lj._print(e) for e in final_exprs] return vals def _compile_function(self, strmod): global exe_engines llmod = llvm.parse_assembly(strmod) pmb = llvm.create_pass_manager_builder() pmb.opt_level = 2 pass_manager = llvm.create_module_pass_manager() pmb.populate(pass_manager) pass_manager.run(llmod) target_machine = \ llvm.Target.from_default_triple().create_target_machine() exe_eng = llvm.create_mcjit_compiler(llmod, target_machine) exe_eng.finalize_object() exe_engines.append(exe_eng) if False: print("Assembly") print(target_machine.emit_assembly(llmod)) fptr = exe_eng.get_function_address(self.link_name) return fptr class LLVMJitCodeCallback(LLVMJitCode): def __init__(self, signature): super().__init__(signature) def _create_param_dict(self, func_args): for i, a in enumerate(func_args): if isinstance(a, IndexedBase): self.param_dict[a] = (self.fn.args[i], i) self.fn.args[i].name = str(a) else: self.param_dict[a] = (self.fn.args[self.signature.input_arg], i) def _create_function(self, expr): """Create function body and return LLVM IR""" bb_entry = self.fn.append_basic_block('entry') builder = ll.IRBuilder(bb_entry) lj = LLVMJitCallbackPrinter(self.module, builder, self.fn, func_arg_map=self.param_dict) ret = self._convert_expr(lj, expr) if self.signature.ret_arg: output_fp_ptr = builder.bitcast(self.fn.args[self.signature.ret_arg], ll.PointerType(self.fp_type)) for i, val in enumerate(ret): index = ll.Constant(ll.IntType(32), i) output_array_ptr = builder.gep(output_fp_ptr, [index]) builder.store(val, output_array_ptr) builder.ret(ll.Constant(ll.IntType(32), 0)) # return success else: lj.builder.ret(self._wrap_return(lj, ret)) strmod = str(self.module) return strmod class CodeSignature: def __init__(self, ret_type): self.ret_type = ret_type self.arg_ctypes = [] # Input argument array element index self.input_arg = 0 # For the case output value is referenced through a parameter rather # than the return value self.ret_arg = None def _llvm_jit_code(args, expr, signature, callback_type): """Create a native code function from a Sympy expression""" if callback_type is None: jit = LLVMJitCode(signature) else: jit = LLVMJitCodeCallback(signature) jit._create_args(args) jit._create_function_base() jit._create_param_dict(args) strmod = jit._create_function(expr) if False: print("LLVM IR") print(strmod) fptr = jit._compile_function(strmod) return fptr @doctest_depends_on(modules=('llvmlite', 'scipy')) def llvm_callable(args, expr, callback_type=None): '''Compile function from a Sympy expression Expressions are evaluated using double precision arithmetic. Some single argument math functions (exp, sin, cos, etc.) are supported in expressions. Parameters ========== args : List of Symbol Arguments to the generated function. Usually the free symbols in the expression. Currently each one is assumed to convert to a double precision scalar. expr : Expr, or (Replacements, Expr) as returned from 'cse' Expression to compile. callback_type : string Create function with signature appropriate to use as a callback. Currently supported: 'scipy.integrate' 'scipy.integrate.test' 'cubature' Returns ======= Compiled function that can evaluate the expression. Examples ======== >>> import sympy.printing.llvmjitcode as jit >>> from sympy.abc import a >>> e = a*a + a + 1 >>> e1 = jit.llvm_callable([a], e) >>> e.subs(a, 1.1) # Evaluate via substitution 3.31000000000000 >>> e1(1.1) # Evaluate using JIT-compiled code 3.3100000000000005 Callbacks for integration functions can be JIT compiled. >>> import sympy.printing.llvmjitcode as jit >>> from sympy.abc import a >>> from sympy import integrate >>> from scipy.integrate import quad >>> e = a*a >>> e1 = jit.llvm_callable([a], e, callback_type='scipy.integrate') >>> integrate(e, (a, 0.0, 2.0)) 2.66666666666667 >>> quad(e1, 0.0, 2.0)[0] 2.66666666666667 The 'cubature' callback is for the Python wrapper around the cubature package ( https://github.com/saullocastro/cubature ) and ( http://ab-initio.mit.edu/wiki/index.php/Cubature ) There are two signatures for the SciPy integration callbacks. The first ('scipy.integrate') is the function to be passed to the integration routine, and will pass the signature checks. The second ('scipy.integrate.test') is only useful for directly calling the function using ctypes variables. It will not pass the signature checks for scipy.integrate. The return value from the cse module can also be compiled. This can improve the performance of the compiled function. If multiple expressions are given to cse, the compiled function returns a tuple. The 'cubature' callback handles multiple expressions (set `fdim` to match in the integration call.) >>> import sympy.printing.llvmjitcode as jit >>> from sympy import cse >>> from sympy.abc import x,y >>> e1 = x*x + y*y >>> e2 = 4*(x*x + y*y) + 8.0 >>> after_cse = cse([e1,e2]) >>> after_cse ([(x0, x**2), (x1, y**2)], [x0 + x1, 4*x0 + 4*x1 + 8.0]) >>> j1 = jit.llvm_callable([x,y], after_cse) # doctest: +SKIP >>> j1(1.0, 2.0) # doctest: +SKIP (5.0, 28.0) ''' if not llvmlite: raise ImportError("llvmlite is required for llvmjitcode") signature = CodeSignature(ctypes.py_object) arg_ctypes = [] if callback_type is None: for _ in args: arg_ctype = ctypes.c_double arg_ctypes.append(arg_ctype) elif callback_type == 'scipy.integrate' or callback_type == 'scipy.integrate.test': signature.ret_type = ctypes.c_double arg_ctypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_double)] arg_ctypes_formal = [ctypes.c_int, ctypes.c_double] signature.input_arg = 1 elif callback_type == 'cubature': arg_ctypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_double), ctypes.c_void_p, ctypes.c_int, ctypes.POINTER(ctypes.c_double) ] signature.ret_type = ctypes.c_int signature.input_arg = 1 signature.ret_arg = 4 else: raise ValueError("Unknown callback type: %s" % callback_type) signature.arg_ctypes = arg_ctypes fptr = _llvm_jit_code(args, expr, signature, callback_type) if callback_type and callback_type == 'scipy.integrate': arg_ctypes = arg_ctypes_formal cfunc = ctypes.CFUNCTYPE(signature.ret_type, *arg_ctypes)(fptr) return cfunc
5b2ec6c1d1e2bb6bb4dc6dbfc9df556b7a3326b6c5faa5cbbd3df8b7b11fe36c
""" A Printer which converts an expression into its LaTeX equivalent. """ from typing import Any, Dict import itertools from sympy.core import Add, Float, Mod, Mul, Number, S, Symbol from sympy.core.alphabets import greeks from sympy.core.containers import Tuple from sympy.core.function import _coeff_isneg, AppliedUndef, Derivative from sympy.core.operations import AssocOp from sympy.core.sympify import SympifyError from sympy.logic.boolalg import true # sympy.printing imports from sympy.printing.precedence import precedence_traditional from sympy.printing.printer import Printer, print_function from sympy.printing.conventions import split_super_sub, requires_partial from sympy.printing.precedence import precedence, PRECEDENCE import mpmath.libmp as mlib from mpmath.libmp import prec_to_dps from sympy.core.compatibility import default_sort_key from sympy.utilities.iterables import has_variety import re # Hand-picked functions which can be used directly in both LaTeX and MathJax # Complete list at # https://docs.mathjax.org/en/latest/tex.html#supported-latex-commands # This variable only contains those functions which sympy uses. accepted_latex_functions = ['arcsin', 'arccos', 'arctan', 'sin', 'cos', 'tan', 'sinh', 'cosh', 'tanh', 'sqrt', 'ln', 'log', 'sec', 'csc', 'cot', 'coth', 're', 'im', 'frac', 'root', 'arg', ] tex_greek_dictionary = { 'Alpha': 'A', 'Beta': 'B', 'Gamma': r'\Gamma', 'Delta': r'\Delta', 'Epsilon': 'E', 'Zeta': 'Z', 'Eta': 'H', 'Theta': r'\Theta', 'Iota': 'I', 'Kappa': 'K', 'Lambda': r'\Lambda', 'Mu': 'M', 'Nu': 'N', 'Xi': r'\Xi', 'omicron': 'o', 'Omicron': 'O', 'Pi': r'\Pi', 'Rho': 'P', 'Sigma': r'\Sigma', 'Tau': 'T', 'Upsilon': r'\Upsilon', 'Phi': r'\Phi', 'Chi': 'X', 'Psi': r'\Psi', 'Omega': r'\Omega', 'lamda': r'\lambda', 'Lamda': r'\Lambda', 'khi': r'\chi', 'Khi': r'X', 'varepsilon': r'\varepsilon', 'varkappa': r'\varkappa', 'varphi': r'\varphi', 'varpi': r'\varpi', 'varrho': r'\varrho', 'varsigma': r'\varsigma', 'vartheta': r'\vartheta', } other_symbols = {'aleph', 'beth', 'daleth', 'gimel', 'ell', 'eth', 'hbar', 'hslash', 'mho', 'wp'} # Variable name modifiers modifier_dict = { # Accents 'mathring': lambda s: r'\mathring{'+s+r'}', 'ddddot': lambda s: r'\ddddot{'+s+r'}', 'dddot': lambda s: r'\dddot{'+s+r'}', 'ddot': lambda s: r'\ddot{'+s+r'}', 'dot': lambda s: r'\dot{'+s+r'}', 'check': lambda s: r'\check{'+s+r'}', 'breve': lambda s: r'\breve{'+s+r'}', 'acute': lambda s: r'\acute{'+s+r'}', 'grave': lambda s: r'\grave{'+s+r'}', 'tilde': lambda s: r'\tilde{'+s+r'}', 'hat': lambda s: r'\hat{'+s+r'}', 'bar': lambda s: r'\bar{'+s+r'}', 'vec': lambda s: r'\vec{'+s+r'}', 'prime': lambda s: "{"+s+"}'", 'prm': lambda s: "{"+s+"}'", # Faces 'bold': lambda s: r'\boldsymbol{'+s+r'}', 'bm': lambda s: r'\boldsymbol{'+s+r'}', 'cal': lambda s: r'\mathcal{'+s+r'}', 'scr': lambda s: r'\mathscr{'+s+r'}', 'frak': lambda s: r'\mathfrak{'+s+r'}', # Brackets 'norm': lambda s: r'\left\|{'+s+r'}\right\|', 'avg': lambda s: r'\left\langle{'+s+r'}\right\rangle', 'abs': lambda s: r'\left|{'+s+r'}\right|', 'mag': lambda s: r'\left|{'+s+r'}\right|', } greek_letters_set = frozenset(greeks) _between_two_numbers_p = ( re.compile(r'[0-9][} ]*$'), # search re.compile(r'[{ ]*[-+0-9]'), # match ) def latex_escape(s): """ Escape a string such that latex interprets it as plaintext. We can't use verbatim easily with mathjax, so escaping is easier. Rules from https://tex.stackexchange.com/a/34586/41112. """ s = s.replace('\\', r'\textbackslash') for c in '&%$#_{}': s = s.replace(c, '\\' + c) s = s.replace('~', r'\textasciitilde') s = s.replace('^', r'\textasciicircum') return s class LatexPrinter(Printer): printmethod = "_latex" _default_settings = { "full_prec": False, "fold_frac_powers": False, "fold_func_brackets": False, "fold_short_frac": None, "inv_trig_style": "abbreviated", "itex": False, "ln_notation": False, "long_frac_ratio": None, "mat_delim": "[", "mat_str": None, "mode": "plain", "mul_symbol": None, "order": None, "symbol_names": {}, "root_notation": True, "mat_symbol_style": "plain", "imaginary_unit": "i", "gothic_re_im": False, "decimal_separator": "period", "perm_cyclic": True, "parenthesize_super": True, "min": None, "max": None, } # type: Dict[str, Any] def __init__(self, settings=None): Printer.__init__(self, settings) if 'mode' in self._settings: valid_modes = ['inline', 'plain', 'equation', 'equation*'] if self._settings['mode'] not in valid_modes: raise ValueError("'mode' must be one of 'inline', 'plain', " "'equation' or 'equation*'") if self._settings['fold_short_frac'] is None and \ self._settings['mode'] == 'inline': self._settings['fold_short_frac'] = True mul_symbol_table = { None: r" ", "ldot": r" \,.\, ", "dot": r" \cdot ", "times": r" \times " } try: self._settings['mul_symbol_latex'] = \ mul_symbol_table[self._settings['mul_symbol']] except KeyError: self._settings['mul_symbol_latex'] = \ self._settings['mul_symbol'] try: self._settings['mul_symbol_latex_numbers'] = \ mul_symbol_table[self._settings['mul_symbol'] or 'dot'] except KeyError: if (self._settings['mul_symbol'].strip() in ['', ' ', '\\', '\\,', '\\:', '\\;', '\\quad']): self._settings['mul_symbol_latex_numbers'] = \ mul_symbol_table['dot'] else: self._settings['mul_symbol_latex_numbers'] = \ self._settings['mul_symbol'] self._delim_dict = {'(': ')', '[': ']'} imaginary_unit_table = { None: r"i", "i": r"i", "ri": r"\mathrm{i}", "ti": r"\text{i}", "j": r"j", "rj": r"\mathrm{j}", "tj": r"\text{j}", } try: self._settings['imaginary_unit_latex'] = \ imaginary_unit_table[self._settings['imaginary_unit']] except KeyError: self._settings['imaginary_unit_latex'] = \ self._settings['imaginary_unit'] def _add_parens(self, s): return r"\left({}\right)".format(s) # TODO: merge this with the above, which requires a lot of test changes def _add_parens_lspace(self, s): return r"\left( {}\right)".format(s) def parenthesize(self, item, level, is_neg=False, strict=False): prec_val = precedence_traditional(item) if is_neg and strict: return self._add_parens(self._print(item)) if (prec_val < level) or ((not strict) and prec_val <= level): return self._add_parens(self._print(item)) else: return self._print(item) def parenthesize_super(self, s): """ Protect superscripts in s If the parenthesize_super option is set, protect with parentheses, else wrap in braces. """ if "^" in s: if self._settings['parenthesize_super']: return self._add_parens(s) else: return "{{{}}}".format(s) return s def doprint(self, expr): tex = Printer.doprint(self, expr) if self._settings['mode'] == 'plain': return tex elif self._settings['mode'] == 'inline': return r"$%s$" % tex elif self._settings['itex']: return r"$$%s$$" % tex else: env_str = self._settings['mode'] return r"\begin{%s}%s\end{%s}" % (env_str, tex, env_str) def _needs_brackets(self, expr): """ Returns True if the expression needs to be wrapped in brackets when printed, False otherwise. For example: a + b => True; a => False; 10 => False; -10 => True. """ return not ((expr.is_Integer and expr.is_nonnegative) or (expr.is_Atom and (expr is not S.NegativeOne and expr.is_Rational is False))) def _needs_function_brackets(self, expr): """ Returns True if the expression needs to be wrapped in brackets when passed as an argument to a function, False otherwise. This is a more liberal version of _needs_brackets, in that many expressions which need to be wrapped in brackets when added/subtracted/raised to a power do not need them when passed to a function. Such an example is a*b. """ if not self._needs_brackets(expr): return False else: # Muls of the form a*b*c... can be folded if expr.is_Mul and not self._mul_is_clean(expr): return True # Pows which don't need brackets can be folded elif expr.is_Pow and not self._pow_is_clean(expr): return True # Add and Function always need brackets elif expr.is_Add or expr.is_Function: return True else: return False def _needs_mul_brackets(self, expr, first=False, last=False): """ Returns True if the expression needs to be wrapped in brackets when printed as part of a Mul, False otherwise. This is True for Add, but also for some container objects that would not need brackets when appearing last in a Mul, e.g. an Integral. ``last=True`` specifies that this expr is the last to appear in a Mul. ``first=True`` specifies that this expr is the first to appear in a Mul. """ from sympy import Integral, Product, Sum if expr.is_Mul: if not first and _coeff_isneg(expr): return True elif precedence_traditional(expr) < PRECEDENCE["Mul"]: return True elif expr.is_Relational: return True if expr.is_Piecewise: return True if any(expr.has(x) for x in (Mod,)): return True if (not last and any(expr.has(x) for x in (Integral, Product, Sum))): return True return False def _needs_add_brackets(self, expr): """ Returns True if the expression needs to be wrapped in brackets when printed as part of an Add, False otherwise. This is False for most things. """ if expr.is_Relational: return True if any(expr.has(x) for x in (Mod,)): return True if expr.is_Add: return True return False def _mul_is_clean(self, expr): for arg in expr.args: if arg.is_Function: return False return True def _pow_is_clean(self, expr): return not self._needs_brackets(expr.base) def _do_exponent(self, expr, exp): if exp is not None: return r"\left(%s\right)^{%s}" % (expr, exp) else: return expr def _print_Basic(self, expr): ls = [self._print(o) for o in expr.args] return self._deal_with_super_sub(expr.__class__.__name__) + \ r"\left(%s\right)" % ", ".join(ls) def _print_bool(self, e): return r"\text{%s}" % e _print_BooleanTrue = _print_bool _print_BooleanFalse = _print_bool def _print_NoneType(self, e): return r"\text{%s}" % e def _print_Add(self, expr, order=None): terms = self._as_ordered_terms(expr, order=order) tex = "" for i, term in enumerate(terms): if i == 0: pass elif _coeff_isneg(term): tex += " - " term = -term else: tex += " + " term_tex = self._print(term) if self._needs_add_brackets(term): term_tex = r"\left(%s\right)" % term_tex tex += term_tex return tex def _print_Cycle(self, expr): from sympy.combinatorics.permutations import Permutation if expr.size == 0: return r"\left( \right)" expr = Permutation(expr) expr_perm = expr.cyclic_form siz = expr.size if expr.array_form[-1] == siz - 1: expr_perm = expr_perm + [[siz - 1]] term_tex = '' for i in expr_perm: term_tex += str(i).replace(',', r"\;") term_tex = term_tex.replace('[', r"\left( ") term_tex = term_tex.replace(']', r"\right)") return term_tex def _print_Permutation(self, expr): from sympy.combinatorics.permutations import Permutation from sympy.utilities.exceptions import SymPyDeprecationWarning perm_cyclic = Permutation.print_cyclic if perm_cyclic is not None: SymPyDeprecationWarning( feature="Permutation.print_cyclic = {}".format(perm_cyclic), useinstead="init_printing(perm_cyclic={})" .format(perm_cyclic), issue=15201, deprecated_since_version="1.6").warn() else: perm_cyclic = self._settings.get("perm_cyclic", True) if perm_cyclic: return self._print_Cycle(expr) if expr.size == 0: return r"\left( \right)" lower = [self._print(arg) for arg in expr.array_form] upper = [self._print(arg) for arg in range(len(lower))] row1 = " & ".join(upper) row2 = " & ".join(lower) mat = r" \\ ".join((row1, row2)) return r"\begin{pmatrix} %s \end{pmatrix}" % mat def _print_AppliedPermutation(self, expr): perm, var = expr.args return r"\sigma_{%s}(%s)" % (self._print(perm), self._print(var)) def _print_Float(self, expr): # Based off of that in StrPrinter dps = prec_to_dps(expr._prec) strip = False if self._settings['full_prec'] else True low = self._settings["min"] if "min" in self._settings else None high = self._settings["max"] if "max" in self._settings else None str_real = mlib.to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high) # Must always have a mul symbol (as 2.5 10^{20} just looks odd) # thus we use the number separator separator = self._settings['mul_symbol_latex_numbers'] if 'e' in str_real: (mant, exp) = str_real.split('e') if exp[0] == '+': exp = exp[1:] if self._settings['decimal_separator'] == 'comma': mant = mant.replace('.','{,}') return r"%s%s10^{%s}" % (mant, separator, exp) elif str_real == "+inf": return r"\infty" elif str_real == "-inf": return r"- \infty" else: if self._settings['decimal_separator'] == 'comma': str_real = str_real.replace('.','{,}') return str_real def _print_Cross(self, expr): vec1 = expr._expr1 vec2 = expr._expr2 return r"%s \times %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']), self.parenthesize(vec2, PRECEDENCE['Mul'])) def _print_Curl(self, expr): vec = expr._expr return r"\nabla\times %s" % self.parenthesize(vec, PRECEDENCE['Mul']) def _print_Divergence(self, expr): vec = expr._expr return r"\nabla\cdot %s" % self.parenthesize(vec, PRECEDENCE['Mul']) def _print_Dot(self, expr): vec1 = expr._expr1 vec2 = expr._expr2 return r"%s \cdot %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']), self.parenthesize(vec2, PRECEDENCE['Mul'])) def _print_Gradient(self, expr): func = expr._expr return r"\nabla %s" % self.parenthesize(func, PRECEDENCE['Mul']) def _print_Laplacian(self, expr): func = expr._expr return r"\triangle %s" % self.parenthesize(func, PRECEDENCE['Mul']) def _print_Mul(self, expr): from sympy.core.power import Pow from sympy.physics.units import Quantity from sympy.simplify import fraction separator = self._settings['mul_symbol_latex'] numbersep = self._settings['mul_symbol_latex_numbers'] def convert(expr): if not expr.is_Mul: return str(self._print(expr)) else: if self.order not in ('old', 'none'): args = expr.as_ordered_factors() else: args = list(expr.args) # If quantities are present append them at the back args = sorted(args, key=lambda x: isinstance(x, Quantity) or (isinstance(x, Pow) and isinstance(x.base, Quantity))) return convert_args(args) def convert_args(args): _tex = last_term_tex = "" for i, term in enumerate(args): term_tex = self._print(term) if self._needs_mul_brackets(term, first=(i == 0), last=(i == len(args) - 1)): term_tex = r"\left(%s\right)" % term_tex if _between_two_numbers_p[0].search(last_term_tex) and \ _between_two_numbers_p[1].match(term_tex): # between two numbers _tex += numbersep elif _tex: _tex += separator _tex += term_tex last_term_tex = term_tex return _tex # Check for unevaluated Mul. In this case we need to make sure the # identities are visible, multiple Rational factors are not combined # etc so we display in a straight-forward form that fully preserves all # args and their order. # XXX: _print_Pow calls this routine with instances of Pow... if isinstance(expr, Mul): args = expr.args if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]): return convert_args(args) include_parens = False if _coeff_isneg(expr): expr = -expr tex = "- " if expr.is_Add: tex += "(" include_parens = True else: tex = "" numer, denom = fraction(expr, exact=True) if denom is S.One and Pow(1, -1, evaluate=False) not in expr.args: # use the original expression here, since fraction() may have # altered it when producing numer and denom tex += convert(expr) else: snumer = convert(numer) sdenom = convert(denom) ldenom = len(sdenom.split()) ratio = self._settings['long_frac_ratio'] if self._settings['fold_short_frac'] and ldenom <= 2 and \ "^" not in sdenom: # handle short fractions if self._needs_mul_brackets(numer, last=False): tex += r"\left(%s\right) / %s" % (snumer, sdenom) else: tex += r"%s / %s" % (snumer, sdenom) elif ratio is not None and \ len(snumer.split()) > ratio*ldenom: # handle long fractions if self._needs_mul_brackets(numer, last=True): tex += r"\frac{1}{%s}%s\left(%s\right)" \ % (sdenom, separator, snumer) elif numer.is_Mul: # split a long numerator a = S.One b = S.One for x in numer.args: if self._needs_mul_brackets(x, last=False) or \ len(convert(a*x).split()) > ratio*ldenom or \ (b.is_commutative is x.is_commutative is False): b *= x else: a *= x if self._needs_mul_brackets(b, last=True): tex += r"\frac{%s}{%s}%s\left(%s\right)" \ % (convert(a), sdenom, separator, convert(b)) else: tex += r"\frac{%s}{%s}%s%s" \ % (convert(a), sdenom, separator, convert(b)) else: tex += r"\frac{1}{%s}%s%s" % (sdenom, separator, snumer) else: tex += r"\frac{%s}{%s}" % (snumer, sdenom) if include_parens: tex += ")" return tex def _print_Pow(self, expr): # Treat x**Rational(1,n) as special case if expr.exp.is_Rational and abs(expr.exp.p) == 1 and expr.exp.q != 1 \ and self._settings['root_notation']: base = self._print(expr.base) expq = expr.exp.q if expq == 2: tex = r"\sqrt{%s}" % base elif self._settings['itex']: tex = r"\root{%d}{%s}" % (expq, base) else: tex = r"\sqrt[%d]{%s}" % (expq, base) if expr.exp.is_negative: return r"\frac{1}{%s}" % tex else: return tex elif self._settings['fold_frac_powers'] \ and expr.exp.is_Rational \ and expr.exp.q != 1: base = self.parenthesize(expr.base, PRECEDENCE['Pow']) p, q = expr.exp.p, expr.exp.q # issue #12886: add parentheses for superscripts raised to powers if expr.base.is_Symbol: base = self.parenthesize_super(base) if expr.base.is_Function: return self._print(expr.base, exp="%s/%s" % (p, q)) return r"%s^{%s/%s}" % (base, p, q) elif expr.exp.is_Rational and expr.exp.is_negative and \ expr.base.is_commutative: # special case for 1^(-x), issue 9216 if expr.base == 1: return r"%s^{%s}" % (expr.base, expr.exp) # special case for (1/x)^(-y) and (-1/-x)^(-y), issue 20252 if expr.base.is_Rational and \ expr.base.p*expr.base.q == abs(expr.base.q): if expr.exp == -1: return r"\frac{1}{\frac{%s}{%s}}" % (expr.base.p, expr.base.q) else: return r"\frac{1}{(\frac{%s}{%s})^{%s}}" % (expr.base.p, expr.base.q, abs(expr.exp)) # things like 1/x return self._print_Mul(expr) else: if expr.base.is_Function: return self._print(expr.base, exp=self._print(expr.exp)) else: tex = r"%s^{%s}" return self._helper_print_standard_power(expr, tex) def _helper_print_standard_power(self, expr, template): exp = self._print(expr.exp) # issue #12886: add parentheses around superscripts raised # to powers base = self.parenthesize(expr.base, PRECEDENCE['Pow']) if expr.base.is_Symbol: base = self.parenthesize_super(base) elif (isinstance(expr.base, Derivative) and base.startswith(r'\left(') and re.match(r'\\left\(\\d?d?dot', base) and base.endswith(r'\right)')): # don't use parentheses around dotted derivative base = base[6: -7] # remove outermost added parens return template % (base, exp) def _print_UnevaluatedExpr(self, expr): return self._print(expr.args[0]) def _print_Sum(self, expr): if len(expr.limits) == 1: tex = r"\sum_{%s=%s}^{%s} " % \ tuple([self._print(i) for i in expr.limits[0]]) else: def _format_ineq(l): return r"%s \leq %s \leq %s" % \ tuple([self._print(s) for s in (l[1], l[0], l[2])]) tex = r"\sum_{\substack{%s}} " % \ str.join('\\\\', [_format_ineq(l) for l in expr.limits]) if isinstance(expr.function, Add): tex += r"\left(%s\right)" % self._print(expr.function) else: tex += self._print(expr.function) return tex def _print_Product(self, expr): if len(expr.limits) == 1: tex = r"\prod_{%s=%s}^{%s} " % \ tuple([self._print(i) for i in expr.limits[0]]) else: def _format_ineq(l): return r"%s \leq %s \leq %s" % \ tuple([self._print(s) for s in (l[1], l[0], l[2])]) tex = r"\prod_{\substack{%s}} " % \ str.join('\\\\', [_format_ineq(l) for l in expr.limits]) if isinstance(expr.function, Add): tex += r"\left(%s\right)" % self._print(expr.function) else: tex += self._print(expr.function) return tex def _print_BasisDependent(self, expr): from sympy.vector import Vector o1 = [] if expr == expr.zero: return expr.zero._latex_form if isinstance(expr, Vector): items = expr.separate().items() else: items = [(0, expr)] for system, vect in items: inneritems = list(vect.components.items()) inneritems.sort(key=lambda x: x[0].__str__()) for k, v in inneritems: if v == 1: o1.append(' + ' + k._latex_form) elif v == -1: o1.append(' - ' + k._latex_form) else: arg_str = '(' + self._print(v) + ')' o1.append(' + ' + arg_str + k._latex_form) outstr = (''.join(o1)) if outstr[1] != '-': outstr = outstr[3:] else: outstr = outstr[1:] return outstr def _print_Indexed(self, expr): tex_base = self._print(expr.base) tex = '{'+tex_base+'}'+'_{%s}' % ','.join( map(self._print, expr.indices)) return tex def _print_IndexedBase(self, expr): return self._print(expr.label) def _print_Derivative(self, expr): if requires_partial(expr.expr): diff_symbol = r'\partial' else: diff_symbol = r'd' tex = "" dim = 0 for x, num in reversed(expr.variable_count): dim += num if num == 1: tex += r"%s %s" % (diff_symbol, self._print(x)) else: tex += r"%s %s^{%s}" % (diff_symbol, self.parenthesize_super(self._print(x)), self._print(num)) if dim == 1: tex = r"\frac{%s}{%s}" % (diff_symbol, tex) else: tex = r"\frac{%s^{%s}}{%s}" % (diff_symbol, self._print(dim), tex) if any(_coeff_isneg(i) for i in expr.args): return r"%s %s" % (tex, self.parenthesize(expr.expr, PRECEDENCE["Mul"], is_neg=True, strict=True)) return r"%s %s" % (tex, self.parenthesize(expr.expr, PRECEDENCE["Mul"], is_neg=False, strict=True)) def _print_Subs(self, subs): expr, old, new = subs.args latex_expr = self._print(expr) latex_old = (self._print(e) for e in old) latex_new = (self._print(e) for e in new) latex_subs = r'\\ '.join( e[0] + '=' + e[1] for e in zip(latex_old, latex_new)) return r'\left. %s \right|_{\substack{ %s }}' % (latex_expr, latex_subs) def _print_Integral(self, expr): tex, symbols = "", [] # Only up to \iiiint exists if len(expr.limits) <= 4 and all(len(lim) == 1 for lim in expr.limits): # Use len(expr.limits)-1 so that syntax highlighters don't think # \" is an escaped quote tex = r"\i" + "i"*(len(expr.limits) - 1) + "nt" symbols = [r"\, d%s" % self._print(symbol[0]) for symbol in expr.limits] else: for lim in reversed(expr.limits): symbol = lim[0] tex += r"\int" if len(lim) > 1: if self._settings['mode'] != 'inline' \ and not self._settings['itex']: tex += r"\limits" if len(lim) == 3: tex += "_{%s}^{%s}" % (self._print(lim[1]), self._print(lim[2])) if len(lim) == 2: tex += "^{%s}" % (self._print(lim[1])) symbols.insert(0, r"\, d%s" % self._print(symbol)) return r"%s %s%s" % (tex, self.parenthesize(expr.function, PRECEDENCE["Mul"], is_neg=any(_coeff_isneg(i) for i in expr.args), strict=True), "".join(symbols)) def _print_Limit(self, expr): e, z, z0, dir = expr.args tex = r"\lim_{%s \to " % self._print(z) if str(dir) == '+-' or z0 in (S.Infinity, S.NegativeInfinity): tex += r"%s}" % self._print(z0) else: tex += r"%s^%s}" % (self._print(z0), self._print(dir)) if isinstance(e, AssocOp): return r"%s\left(%s\right)" % (tex, self._print(e)) else: return r"%s %s" % (tex, self._print(e)) def _hprint_Function(self, func): r''' Logic to decide how to render a function to latex - if it is a recognized latex name, use the appropriate latex command - if it is a single letter, just use that letter - if it is a longer name, then put \operatorname{} around it and be mindful of undercores in the name ''' func = self._deal_with_super_sub(func) if func in accepted_latex_functions: name = r"\%s" % func elif len(func) == 1 or func.startswith('\\'): name = func else: name = r"\operatorname{%s}" % func return name def _print_Function(self, expr, exp=None): r''' Render functions to LaTeX, handling functions that LaTeX knows about e.g., sin, cos, ... by using the proper LaTeX command (\sin, \cos, ...). For single-letter function names, render them as regular LaTeX math symbols. For multi-letter function names that LaTeX does not know about, (e.g., Li, sech) use \operatorname{} so that the function name is rendered in Roman font and LaTeX handles spacing properly. expr is the expression involving the function exp is an exponent ''' func = expr.func.__name__ if hasattr(self, '_print_' + func) and \ not isinstance(expr, AppliedUndef): return getattr(self, '_print_' + func)(expr, exp) else: args = [str(self._print(arg)) for arg in expr.args] # How inverse trig functions should be displayed, formats are: # abbreviated: asin, full: arcsin, power: sin^-1 inv_trig_style = self._settings['inv_trig_style'] # If we are dealing with a power-style inverse trig function inv_trig_power_case = False # If it is applicable to fold the argument brackets can_fold_brackets = self._settings['fold_func_brackets'] and \ len(args) == 1 and \ not self._needs_function_brackets(expr.args[0]) inv_trig_table = [ "asin", "acos", "atan", "acsc", "asec", "acot", "asinh", "acosh", "atanh", "acsch", "asech", "acoth", ] # If the function is an inverse trig function, handle the style if func in inv_trig_table: if inv_trig_style == "abbreviated": pass elif inv_trig_style == "full": func = "arc" + func[1:] elif inv_trig_style == "power": func = func[1:] inv_trig_power_case = True # Can never fold brackets if we're raised to a power if exp is not None: can_fold_brackets = False if inv_trig_power_case: if func in accepted_latex_functions: name = r"\%s^{-1}" % func else: name = r"\operatorname{%s}^{-1}" % func elif exp is not None: func_tex = self._hprint_Function(func) func_tex = self.parenthesize_super(func_tex) name = r'%s^{%s}' % (func_tex, exp) else: name = self._hprint_Function(func) if can_fold_brackets: if func in accepted_latex_functions: # Wrap argument safely to avoid parse-time conflicts # with the function name itself name += r" {%s}" else: name += r"%s" else: name += r"{\left(%s \right)}" if inv_trig_power_case and exp is not None: name += r"^{%s}" % exp return name % ",".join(args) def _print_UndefinedFunction(self, expr): return self._hprint_Function(str(expr)) def _print_ElementwiseApplyFunction(self, expr): return r"{%s}_{\circ}\left({%s}\right)" % ( self._print(expr.function), self._print(expr.expr), ) @property def _special_function_classes(self): from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.functions.special.gamma_functions import gamma, lowergamma from sympy.functions.special.beta_functions import beta from sympy.functions.special.delta_functions import DiracDelta from sympy.functions.special.error_functions import Chi return {KroneckerDelta: r'\delta', gamma: r'\Gamma', lowergamma: r'\gamma', beta: r'\operatorname{B}', DiracDelta: r'\delta', Chi: r'\operatorname{Chi}'} def _print_FunctionClass(self, expr): for cls in self._special_function_classes: if issubclass(expr, cls) and expr.__name__ == cls.__name__: return self._special_function_classes[cls] return self._hprint_Function(str(expr)) def _print_Lambda(self, expr): symbols, expr = expr.args if len(symbols) == 1: symbols = self._print(symbols[0]) else: symbols = self._print(tuple(symbols)) tex = r"\left( %s \mapsto %s \right)" % (symbols, self._print(expr)) return tex def _print_IdentityFunction(self, expr): return r"\left( x \mapsto x \right)" def _hprint_variadic_function(self, expr, exp=None): args = sorted(expr.args, key=default_sort_key) texargs = [r"%s" % self._print(symbol) for symbol in args] tex = r"\%s\left(%s\right)" % (str(expr.func).lower(), ", ".join(texargs)) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex _print_Min = _print_Max = _hprint_variadic_function def _print_floor(self, expr, exp=None): tex = r"\left\lfloor{%s}\right\rfloor" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_ceiling(self, expr, exp=None): tex = r"\left\lceil{%s}\right\rceil" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_log(self, expr, exp=None): if not self._settings["ln_notation"]: tex = r"\log{\left(%s \right)}" % self._print(expr.args[0]) else: tex = r"\ln{\left(%s \right)}" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_Abs(self, expr, exp=None): tex = r"\left|{%s}\right|" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex _print_Determinant = _print_Abs def _print_re(self, expr, exp=None): if self._settings['gothic_re_im']: tex = r"\Re{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom']) else: tex = r"\operatorname{{re}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom'])) return self._do_exponent(tex, exp) def _print_im(self, expr, exp=None): if self._settings['gothic_re_im']: tex = r"\Im{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom']) else: tex = r"\operatorname{{im}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom'])) return self._do_exponent(tex, exp) def _print_Not(self, e): from sympy import Equivalent, Implies if isinstance(e.args[0], Equivalent): return self._print_Equivalent(e.args[0], r"\not\Leftrightarrow") if isinstance(e.args[0], Implies): return self._print_Implies(e.args[0], r"\not\Rightarrow") if (e.args[0].is_Boolean): return r"\neg \left(%s\right)" % self._print(e.args[0]) else: return r"\neg %s" % self._print(e.args[0]) def _print_LogOp(self, args, char): arg = args[0] if arg.is_Boolean and not arg.is_Not: tex = r"\left(%s\right)" % self._print(arg) else: tex = r"%s" % self._print(arg) for arg in args[1:]: if arg.is_Boolean and not arg.is_Not: tex += r" %s \left(%s\right)" % (char, self._print(arg)) else: tex += r" %s %s" % (char, self._print(arg)) return tex def _print_And(self, e): args = sorted(e.args, key=default_sort_key) return self._print_LogOp(args, r"\wedge") def _print_Or(self, e): args = sorted(e.args, key=default_sort_key) return self._print_LogOp(args, r"\vee") def _print_Xor(self, e): args = sorted(e.args, key=default_sort_key) return self._print_LogOp(args, r"\veebar") def _print_Implies(self, e, altchar=None): return self._print_LogOp(e.args, altchar or r"\Rightarrow") def _print_Equivalent(self, e, altchar=None): args = sorted(e.args, key=default_sort_key) return self._print_LogOp(args, altchar or r"\Leftrightarrow") def _print_conjugate(self, expr, exp=None): tex = r"\overline{%s}" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_polar_lift(self, expr, exp=None): func = r"\operatorname{polar\_lift}" arg = r"{\left(%s \right)}" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}%s" % (func, exp, arg) else: return r"%s%s" % (func, arg) def _print_ExpBase(self, expr, exp=None): # TODO should exp_polar be printed differently? # what about exp_polar(0), exp_polar(1)? tex = r"e^{%s}" % self._print(expr.args[0]) return self._do_exponent(tex, exp) def _print_Exp1(self, expr, exp=None): return "e" def _print_elliptic_k(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"K^{%s}%s" % (exp, tex) else: return r"K%s" % tex def _print_elliptic_f(self, expr, exp=None): tex = r"\left(%s\middle| %s\right)" % \ (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"F^{%s}%s" % (exp, tex) else: return r"F%s" % tex def _print_elliptic_e(self, expr, exp=None): if len(expr.args) == 2: tex = r"\left(%s\middle| %s\right)" % \ (self._print(expr.args[0]), self._print(expr.args[1])) else: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"E^{%s}%s" % (exp, tex) else: return r"E%s" % tex def _print_elliptic_pi(self, expr, exp=None): if len(expr.args) == 3: tex = r"\left(%s; %s\middle| %s\right)" % \ (self._print(expr.args[0]), self._print(expr.args[1]), self._print(expr.args[2])) else: tex = r"\left(%s\middle| %s\right)" % \ (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"\Pi^{%s}%s" % (exp, tex) else: return r"\Pi%s" % tex def _print_beta(self, expr, exp=None): tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"\operatorname{B}^{%s}%s" % (exp, tex) else: return r"\operatorname{B}%s" % tex def _print_betainc(self, expr, exp=None, operator='B'): largs = [self._print(arg) for arg in expr.args] tex = r"\left(%s, %s\right)" % (largs[0], largs[1]) if exp is not None: return r"\operatorname{%s}_{(%s, %s)}^{%s}%s" % (operator, largs[2], largs[3], exp, tex) else: return r"\operatorname{%s}_{(%s, %s)}%s" % (operator, largs[2], largs[3], tex) def _print_betainc_regularized(self, expr, exp=None): return self._print_betainc(expr, exp, operator='I') def _print_uppergamma(self, expr, exp=None): tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"\Gamma^{%s}%s" % (exp, tex) else: return r"\Gamma%s" % tex def _print_lowergamma(self, expr, exp=None): tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"\gamma^{%s}%s" % (exp, tex) else: return r"\gamma%s" % tex def _hprint_one_arg_func(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}%s" % (self._print(expr.func), exp, tex) else: return r"%s%s" % (self._print(expr.func), tex) _print_gamma = _hprint_one_arg_func def _print_Chi(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"\operatorname{Chi}^{%s}%s" % (exp, tex) else: return r"\operatorname{Chi}%s" % tex def _print_expint(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[1]) nu = self._print(expr.args[0]) if exp is not None: return r"\operatorname{E}_{%s}^{%s}%s" % (nu, exp, tex) else: return r"\operatorname{E}_{%s}%s" % (nu, tex) def _print_fresnels(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"S^{%s}%s" % (exp, tex) else: return r"S%s" % tex def _print_fresnelc(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"C^{%s}%s" % (exp, tex) else: return r"C%s" % tex def _print_subfactorial(self, expr, exp=None): tex = r"!%s" % self.parenthesize(expr.args[0], PRECEDENCE["Func"]) if exp is not None: return r"\left(%s\right)^{%s}" % (tex, exp) else: return tex def _print_factorial(self, expr, exp=None): tex = r"%s!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_factorial2(self, expr, exp=None): tex = r"%s!!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_binomial(self, expr, exp=None): tex = r"{\binom{%s}{%s}}" % (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_RisingFactorial(self, expr, exp=None): n, k = expr.args base = r"%s" % self.parenthesize(n, PRECEDENCE['Func']) tex = r"{%s}^{\left(%s\right)}" % (base, self._print(k)) return self._do_exponent(tex, exp) def _print_FallingFactorial(self, expr, exp=None): n, k = expr.args sub = r"%s" % self.parenthesize(k, PRECEDENCE['Func']) tex = r"{\left(%s\right)}_{%s}" % (self._print(n), sub) return self._do_exponent(tex, exp) def _hprint_BesselBase(self, expr, exp, sym): tex = r"%s" % (sym) need_exp = False if exp is not None: if tex.find('^') == -1: tex = r"%s^{%s}" % (tex, exp) else: need_exp = True tex = r"%s_{%s}\left(%s\right)" % (tex, self._print(expr.order), self._print(expr.argument)) if need_exp: tex = self._do_exponent(tex, exp) return tex def _hprint_vec(self, vec): if not vec: return "" s = "" for i in vec[:-1]: s += "%s, " % self._print(i) s += self._print(vec[-1]) return s def _print_besselj(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'J') def _print_besseli(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'I') def _print_besselk(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'K') def _print_bessely(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'Y') def _print_yn(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'y') def _print_jn(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'j') def _print_hankel1(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'H^{(1)}') def _print_hankel2(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'H^{(2)}') def _print_hn1(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'h^{(1)}') def _print_hn2(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'h^{(2)}') def _hprint_airy(self, expr, exp=None, notation=""): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}%s" % (notation, exp, tex) else: return r"%s%s" % (notation, tex) def _hprint_airy_prime(self, expr, exp=None, notation=""): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"{%s^\prime}^{%s}%s" % (notation, exp, tex) else: return r"%s^\prime%s" % (notation, tex) def _print_airyai(self, expr, exp=None): return self._hprint_airy(expr, exp, 'Ai') def _print_airybi(self, expr, exp=None): return self._hprint_airy(expr, exp, 'Bi') def _print_airyaiprime(self, expr, exp=None): return self._hprint_airy_prime(expr, exp, 'Ai') def _print_airybiprime(self, expr, exp=None): return self._hprint_airy_prime(expr, exp, 'Bi') def _print_hyper(self, expr, exp=None): tex = r"{{}_{%s}F_{%s}\left(\begin{matrix} %s \\ %s \end{matrix}" \ r"\middle| {%s} \right)}" % \ (self._print(len(expr.ap)), self._print(len(expr.bq)), self._hprint_vec(expr.ap), self._hprint_vec(expr.bq), self._print(expr.argument)) if exp is not None: tex = r"{%s}^{%s}" % (tex, exp) return tex def _print_meijerg(self, expr, exp=None): tex = r"{G_{%s, %s}^{%s, %s}\left(\begin{matrix} %s & %s \\" \ r"%s & %s \end{matrix} \middle| {%s} \right)}" % \ (self._print(len(expr.ap)), self._print(len(expr.bq)), self._print(len(expr.bm)), self._print(len(expr.an)), self._hprint_vec(expr.an), self._hprint_vec(expr.aother), self._hprint_vec(expr.bm), self._hprint_vec(expr.bother), self._print(expr.argument)) if exp is not None: tex = r"{%s}^{%s}" % (tex, exp) return tex def _print_dirichlet_eta(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"\eta^{%s}%s" % (exp, tex) return r"\eta%s" % tex def _print_zeta(self, expr, exp=None): if len(expr.args) == 2: tex = r"\left(%s, %s\right)" % tuple(map(self._print, expr.args)) else: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"\zeta^{%s}%s" % (exp, tex) return r"\zeta%s" % tex def _print_stieltjes(self, expr, exp=None): if len(expr.args) == 2: tex = r"_{%s}\left(%s\right)" % tuple(map(self._print, expr.args)) else: tex = r"_{%s}" % self._print(expr.args[0]) if exp is not None: return r"\gamma%s^{%s}" % (tex, exp) return r"\gamma%s" % tex def _print_lerchphi(self, expr, exp=None): tex = r"\left(%s, %s, %s\right)" % tuple(map(self._print, expr.args)) if exp is None: return r"\Phi%s" % tex return r"\Phi^{%s}%s" % (exp, tex) def _print_polylog(self, expr, exp=None): s, z = map(self._print, expr.args) tex = r"\left(%s\right)" % z if exp is None: return r"\operatorname{Li}_{%s}%s" % (s, tex) return r"\operatorname{Li}_{%s}^{%s}%s" % (s, exp, tex) def _print_jacobi(self, expr, exp=None): n, a, b, x = map(self._print, expr.args) tex = r"P_{%s}^{\left(%s,%s\right)}\left(%s\right)" % (n, a, b, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_gegenbauer(self, expr, exp=None): n, a, x = map(self._print, expr.args) tex = r"C_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_chebyshevt(self, expr, exp=None): n, x = map(self._print, expr.args) tex = r"T_{%s}\left(%s\right)" % (n, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_chebyshevu(self, expr, exp=None): n, x = map(self._print, expr.args) tex = r"U_{%s}\left(%s\right)" % (n, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_legendre(self, expr, exp=None): n, x = map(self._print, expr.args) tex = r"P_{%s}\left(%s\right)" % (n, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_assoc_legendre(self, expr, exp=None): n, a, x = map(self._print, expr.args) tex = r"P_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_hermite(self, expr, exp=None): n, x = map(self._print, expr.args) tex = r"H_{%s}\left(%s\right)" % (n, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_laguerre(self, expr, exp=None): n, x = map(self._print, expr.args) tex = r"L_{%s}\left(%s\right)" % (n, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_assoc_laguerre(self, expr, exp=None): n, a, x = map(self._print, expr.args) tex = r"L_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_Ynm(self, expr, exp=None): n, m, theta, phi = map(self._print, expr.args) tex = r"Y_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_Znm(self, expr, exp=None): n, m, theta, phi = map(self._print, expr.args) tex = r"Z_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def __print_mathieu_functions(self, character, args, prime=False, exp=None): a, q, z = map(self._print, args) sup = r"^{\prime}" if prime else "" exp = "" if not exp else "^{%s}" % exp return r"%s%s\left(%s, %s, %s\right)%s" % (character, sup, a, q, z, exp) def _print_mathieuc(self, expr, exp=None): return self.__print_mathieu_functions("C", expr.args, exp=exp) def _print_mathieus(self, expr, exp=None): return self.__print_mathieu_functions("S", expr.args, exp=exp) def _print_mathieucprime(self, expr, exp=None): return self.__print_mathieu_functions("C", expr.args, prime=True, exp=exp) def _print_mathieusprime(self, expr, exp=None): return self.__print_mathieu_functions("S", expr.args, prime=True, exp=exp) def _print_Rational(self, expr): if expr.q != 1: sign = "" p = expr.p if expr.p < 0: sign = "- " p = -p if self._settings['fold_short_frac']: return r"%s%d / %d" % (sign, p, expr.q) return r"%s\frac{%d}{%d}" % (sign, p, expr.q) else: return self._print(expr.p) def _print_Order(self, expr): s = self._print(expr.expr) if expr.point and any(p != S.Zero for p in expr.point) or \ len(expr.variables) > 1: s += '; ' if len(expr.variables) > 1: s += self._print(expr.variables) elif expr.variables: s += self._print(expr.variables[0]) s += r'\rightarrow ' if len(expr.point) > 1: s += self._print(expr.point) else: s += self._print(expr.point[0]) return r"O\left(%s\right)" % s def _print_Symbol(self, expr, style='plain'): if expr in self._settings['symbol_names']: return self._settings['symbol_names'][expr] return self._deal_with_super_sub(expr.name, style=style) _print_RandomSymbol = _print_Symbol def _deal_with_super_sub(self, string, style='plain'): if '{' in string: name, supers, subs = string, [], [] else: name, supers, subs = split_super_sub(string) name = translate(name) supers = [translate(sup) for sup in supers] subs = [translate(sub) for sub in subs] # apply the style only to the name if style == 'bold': name = "\\mathbf{{{}}}".format(name) # glue all items together: if supers: name += "^{%s}" % " ".join(supers) if subs: name += "_{%s}" % " ".join(subs) return name def _print_Relational(self, expr): if self._settings['itex']: gt = r"\gt" lt = r"\lt" else: gt = ">" lt = "<" charmap = { "==": "=", ">": gt, "<": lt, ">=": r"\geq", "<=": r"\leq", "!=": r"\neq", } return "%s %s %s" % (self._print(expr.lhs), charmap[expr.rel_op], self._print(expr.rhs)) def _print_Piecewise(self, expr): ecpairs = [r"%s & \text{for}\: %s" % (self._print(e), self._print(c)) for e, c in expr.args[:-1]] if expr.args[-1].cond == true: ecpairs.append(r"%s & \text{otherwise}" % self._print(expr.args[-1].expr)) else: ecpairs.append(r"%s & \text{for}\: %s" % (self._print(expr.args[-1].expr), self._print(expr.args[-1].cond))) tex = r"\begin{cases} %s \end{cases}" return tex % r" \\".join(ecpairs) def _print_MatrixBase(self, expr): lines = [] for line in range(expr.rows): # horrible, should be 'rows' lines.append(" & ".join([self._print(i) for i in expr[line, :]])) mat_str = self._settings['mat_str'] if mat_str is None: if self._settings['mode'] == 'inline': mat_str = 'smallmatrix' else: if (expr.cols <= 10) is True: mat_str = 'matrix' else: mat_str = 'array' out_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}' out_str = out_str.replace('%MATSTR%', mat_str) if mat_str == 'array': out_str = out_str.replace('%s', '{' + 'c'*expr.cols + '}%s') if self._settings['mat_delim']: left_delim = self._settings['mat_delim'] right_delim = self._delim_dict[left_delim] out_str = r'\left' + left_delim + out_str + \ r'\right' + right_delim return out_str % r"\\".join(lines) def _print_MatrixElement(self, expr): return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True)\ + '_{%s, %s}' % (self._print(expr.i), self._print(expr.j)) def _print_MatrixSlice(self, expr): def latexslice(x, dim): x = list(x) if x[2] == 1: del x[2] if x[0] == 0: x[0] = None if x[1] == dim: x[1] = None return ':'.join(self._print(xi) if xi is not None else '' for xi in x) return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + r'\left[' + latexslice(expr.rowslice, expr.parent.rows) + ', ' + latexslice(expr.colslice, expr.parent.cols) + r'\right]') def _print_BlockMatrix(self, expr): return self._print(expr.blocks) def _print_Transpose(self, expr): mat = expr.arg from sympy.matrices import MatrixSymbol if not isinstance(mat, MatrixSymbol): return r"\left(%s\right)^{T}" % self._print(mat) else: return "%s^{T}" % self.parenthesize(mat, precedence_traditional(expr), True) def _print_Trace(self, expr): mat = expr.arg return r"\operatorname{tr}\left(%s \right)" % self._print(mat) def _print_Adjoint(self, expr): mat = expr.arg from sympy.matrices import MatrixSymbol if not isinstance(mat, MatrixSymbol): return r"\left(%s\right)^{\dagger}" % self._print(mat) else: return r"%s^{\dagger}" % self._print(mat) def _print_MatMul(self, expr): from sympy import MatMul, Mul parens = lambda x: self.parenthesize(x, precedence_traditional(expr), False) args = expr.args if isinstance(args[0], Mul): args = args[0].as_ordered_factors() + list(args[1:]) else: args = list(args) if isinstance(expr, MatMul) and _coeff_isneg(expr): if args[0] == -1: args = args[1:] else: args[0] = -args[0] return '- ' + ' '.join(map(parens, args)) else: return ' '.join(map(parens, args)) def _print_Mod(self, expr, exp=None): if exp is not None: return r'\left(%s\bmod{%s}\right)^{%s}' % \ (self.parenthesize(expr.args[0], PRECEDENCE['Mul'], strict=True), self._print(expr.args[1]), exp) return r'%s\bmod{%s}' % (self.parenthesize(expr.args[0], PRECEDENCE['Mul'], strict=True), self._print(expr.args[1])) def _print_HadamardProduct(self, expr): args = expr.args prec = PRECEDENCE['Pow'] parens = self.parenthesize return r' \circ '.join( map(lambda arg: parens(arg, prec, strict=True), args)) def _print_HadamardPower(self, expr): if precedence_traditional(expr.exp) < PRECEDENCE["Mul"]: template = r"%s^{\circ \left({%s}\right)}" else: template = r"%s^{\circ {%s}}" return self._helper_print_standard_power(expr, template) def _print_KroneckerProduct(self, expr): args = expr.args prec = PRECEDENCE['Pow'] parens = self.parenthesize return r' \otimes '.join( map(lambda arg: parens(arg, prec, strict=True), args)) def _print_MatPow(self, expr): base, exp = expr.base, expr.exp from sympy.matrices import MatrixSymbol if not isinstance(base, MatrixSymbol): return "\\left(%s\\right)^{%s}" % (self._print(base), self._print(exp)) else: return "%s^{%s}" % (self._print(base), self._print(exp)) def _print_MatrixSymbol(self, expr): return self._print_Symbol(expr, style=self._settings[ 'mat_symbol_style']) def _print_ZeroMatrix(self, Z): return r"\mathbb{0}" if self._settings[ 'mat_symbol_style'] == 'plain' else r"\mathbf{0}" def _print_OneMatrix(self, O): return r"\mathbb{1}" if self._settings[ 'mat_symbol_style'] == 'plain' else r"\mathbf{1}" def _print_Identity(self, I): return r"\mathbb{I}" if self._settings[ 'mat_symbol_style'] == 'plain' else r"\mathbf{I}" def _print_PermutationMatrix(self, P): perm_str = self._print(P.args[0]) return "P_{%s}" % perm_str def _print_NDimArray(self, expr): if expr.rank() == 0: return self._print(expr[()]) mat_str = self._settings['mat_str'] if mat_str is None: if self._settings['mode'] == 'inline': mat_str = 'smallmatrix' else: if (expr.rank() == 0) or (expr.shape[-1] <= 10): mat_str = 'matrix' else: mat_str = 'array' block_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}' block_str = block_str.replace('%MATSTR%', mat_str) if self._settings['mat_delim']: left_delim = self._settings['mat_delim'] right_delim = self._delim_dict[left_delim] block_str = r'\left' + left_delim + block_str + \ r'\right' + right_delim if expr.rank() == 0: return block_str % "" level_str = [[]] + [[] for i in range(expr.rank())] shape_ranges = [list(range(i)) for i in expr.shape] for outer_i in itertools.product(*shape_ranges): level_str[-1].append(self._print(expr[outer_i])) even = True for back_outer_i in range(expr.rank()-1, -1, -1): if len(level_str[back_outer_i+1]) < expr.shape[back_outer_i]: break if even: level_str[back_outer_i].append( r" & ".join(level_str[back_outer_i+1])) else: level_str[back_outer_i].append( block_str % (r"\\".join(level_str[back_outer_i+1]))) if len(level_str[back_outer_i+1]) == 1: level_str[back_outer_i][-1] = r"\left[" + \ level_str[back_outer_i][-1] + r"\right]" even = not even level_str[back_outer_i+1] = [] out_str = level_str[0][0] if expr.rank() % 2 == 1: out_str = block_str % out_str return out_str def _printer_tensor_indices(self, name, indices, index_map={}): out_str = self._print(name) last_valence = None prev_map = None for index in indices: new_valence = index.is_up if ((index in index_map) or prev_map) and \ last_valence == new_valence: out_str += "," if last_valence != new_valence: if last_valence is not None: out_str += "}" if index.is_up: out_str += "{}^{" else: out_str += "{}_{" out_str += self._print(index.args[0]) if index in index_map: out_str += "=" out_str += self._print(index_map[index]) prev_map = True else: prev_map = False last_valence = new_valence if last_valence is not None: out_str += "}" return out_str def _print_Tensor(self, expr): name = expr.args[0].args[0] indices = expr.get_indices() return self._printer_tensor_indices(name, indices) def _print_TensorElement(self, expr): name = expr.expr.args[0].args[0] indices = expr.expr.get_indices() index_map = expr.index_map return self._printer_tensor_indices(name, indices, index_map) def _print_TensMul(self, expr): # prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)" sign, args = expr._get_args_for_traditional_printer() return sign + "".join( [self.parenthesize(arg, precedence(expr)) for arg in args] ) def _print_TensAdd(self, expr): a = [] args = expr.args for x in args: a.append(self.parenthesize(x, precedence(expr))) a.sort() s = ' + '.join(a) s = s.replace('+ -', '- ') return s def _print_TensorIndex(self, expr): return "{}%s{%s}" % ( "^" if expr.is_up else "_", self._print(expr.args[0]) ) def _print_PartialDerivative(self, expr): if len(expr.variables) == 1: return r"\frac{\partial}{\partial {%s}}{%s}" % ( self._print(expr.variables[0]), self.parenthesize(expr.expr, PRECEDENCE["Mul"], False) ) else: return r"\frac{\partial^{%s}}{%s}{%s}" % ( len(expr.variables), " ".join([r"\partial {%s}" % self._print(i) for i in expr.variables]), self.parenthesize(expr.expr, PRECEDENCE["Mul"], False) ) def _print_ArraySymbol(self, expr): return self._print(expr.name) def _print_ArrayElement(self, expr): return "{{%s}_{%s}}" % (expr.name, ", ".join([f"{self._print(i)}" for i in expr.indices])) def _print_UniversalSet(self, expr): return r"\mathbb{U}" def _print_frac(self, expr, exp=None): if exp is None: return r"\operatorname{frac}{\left(%s\right)}" % self._print(expr.args[0]) else: return r"\operatorname{frac}{\left(%s\right)}^{%s}" % ( self._print(expr.args[0]), exp) def _print_tuple(self, expr): if self._settings['decimal_separator'] == 'comma': sep = ";" elif self._settings['decimal_separator'] == 'period': sep = "," else: raise ValueError('Unknown Decimal Separator') if len(expr) == 1: # 1-tuple needs a trailing separator return self._add_parens_lspace(self._print(expr[0]) + sep) else: return self._add_parens_lspace( (sep + r" \ ").join([self._print(i) for i in expr])) def _print_TensorProduct(self, expr): elements = [self._print(a) for a in expr.args] return r' \otimes '.join(elements) def _print_WedgeProduct(self, expr): elements = [self._print(a) for a in expr.args] return r' \wedge '.join(elements) def _print_Tuple(self, expr): return self._print_tuple(expr) def _print_list(self, expr): if self._settings['decimal_separator'] == 'comma': return r"\left[ %s\right]" % \ r"; \ ".join([self._print(i) for i in expr]) elif self._settings['decimal_separator'] == 'period': return r"\left[ %s\right]" % \ r", \ ".join([self._print(i) for i in expr]) else: raise ValueError('Unknown Decimal Separator') def _print_dict(self, d): keys = sorted(d.keys(), key=default_sort_key) items = [] for key in keys: val = d[key] items.append("%s : %s" % (self._print(key), self._print(val))) return r"\left\{ %s\right\}" % r", \ ".join(items) def _print_Dict(self, expr): return self._print_dict(expr) def _print_DiracDelta(self, expr, exp=None): if len(expr.args) == 1 or expr.args[1] == 0: tex = r"\delta\left(%s\right)" % self._print(expr.args[0]) else: tex = r"\delta^{\left( %s \right)}\left( %s \right)" % ( self._print(expr.args[1]), self._print(expr.args[0])) if exp: tex = r"\left(%s\right)^{%s}" % (tex, exp) return tex def _print_SingularityFunction(self, expr, exp=None): shift = self._print(expr.args[0] - expr.args[1]) power = self._print(expr.args[2]) tex = r"{\left\langle %s \right\rangle}^{%s}" % (shift, power) if exp is not None: tex = r"{\left({\langle %s \rangle}^{%s}\right)}^{%s}" % (shift, power, exp) return tex def _print_Heaviside(self, expr, exp=None): tex = r"\theta\left(%s\right)" % self._print(expr.args[0]) if exp: tex = r"\left(%s\right)^{%s}" % (tex, exp) return tex def _print_KroneckerDelta(self, expr, exp=None): i = self._print(expr.args[0]) j = self._print(expr.args[1]) if expr.args[0].is_Atom and expr.args[1].is_Atom: tex = r'\delta_{%s %s}' % (i, j) else: tex = r'\delta_{%s, %s}' % (i, j) if exp is not None: tex = r'\left(%s\right)^{%s}' % (tex, exp) return tex def _print_LeviCivita(self, expr, exp=None): indices = map(self._print, expr.args) if all(x.is_Atom for x in expr.args): tex = r'\varepsilon_{%s}' % " ".join(indices) else: tex = r'\varepsilon_{%s}' % ", ".join(indices) if exp: tex = r'\left(%s\right)^{%s}' % (tex, exp) return tex def _print_RandomDomain(self, d): if hasattr(d, 'as_boolean'): return '\\text{Domain: }' + self._print(d.as_boolean()) elif hasattr(d, 'set'): return ('\\text{Domain: }' + self._print(d.symbols) + '\\text{ in }' + self._print(d.set)) elif hasattr(d, 'symbols'): return '\\text{Domain on }' + self._print(d.symbols) else: return self._print(None) def _print_FiniteSet(self, s): items = sorted(s.args, key=default_sort_key) return self._print_set(items) def _print_set(self, s): items = sorted(s, key=default_sort_key) if self._settings['decimal_separator'] == 'comma': items = "; ".join(map(self._print, items)) elif self._settings['decimal_separator'] == 'period': items = ", ".join(map(self._print, items)) else: raise ValueError('Unknown Decimal Separator') return r"\left\{%s\right\}" % items _print_frozenset = _print_set def _print_Range(self, s): dots = object() if s.has(Symbol): return self._print_Basic(s) if s.start.is_infinite and s.stop.is_infinite: if s.step.is_positive: printset = dots, -1, 0, 1, dots else: printset = dots, 1, 0, -1, dots elif s.start.is_infinite: printset = dots, s[-1] - s.step, s[-1] elif s.stop.is_infinite: it = iter(s) printset = next(it), next(it), dots elif len(s) > 4: it = iter(s) printset = next(it), next(it), dots, s[-1] else: printset = tuple(s) return (r"\left\{" + r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) + r"\right\}") def __print_number_polynomial(self, expr, letter, exp=None): if len(expr.args) == 2: if exp is not None: return r"%s_{%s}^{%s}\left(%s\right)" % (letter, self._print(expr.args[0]), exp, self._print(expr.args[1])) return r"%s_{%s}\left(%s\right)" % (letter, self._print(expr.args[0]), self._print(expr.args[1])) tex = r"%s_{%s}" % (letter, self._print(expr.args[0])) if exp is not None: tex = r"%s^{%s}" % (tex, exp) return tex def _print_bernoulli(self, expr, exp=None): return self.__print_number_polynomial(expr, "B", exp) def _print_bell(self, expr, exp=None): if len(expr.args) == 3: tex1 = r"B_{%s, %s}" % (self._print(expr.args[0]), self._print(expr.args[1])) tex2 = r"\left(%s\right)" % r", ".join(self._print(el) for el in expr.args[2]) if exp is not None: tex = r"%s^{%s}%s" % (tex1, exp, tex2) else: tex = tex1 + tex2 return tex return self.__print_number_polynomial(expr, "B", exp) def _print_fibonacci(self, expr, exp=None): return self.__print_number_polynomial(expr, "F", exp) def _print_lucas(self, expr, exp=None): tex = r"L_{%s}" % self._print(expr.args[0]) if exp is not None: tex = r"%s^{%s}" % (tex, exp) return tex def _print_tribonacci(self, expr, exp=None): return self.__print_number_polynomial(expr, "T", exp) def _print_SeqFormula(self, s): dots = object() if len(s.start.free_symbols) > 0 or len(s.stop.free_symbols) > 0: return r"\left\{%s\right\}_{%s=%s}^{%s}" % ( self._print(s.formula), self._print(s.variables[0]), self._print(s.start), self._print(s.stop) ) if s.start is S.NegativeInfinity: stop = s.stop printset = (dots, s.coeff(stop - 3), s.coeff(stop - 2), s.coeff(stop - 1), s.coeff(stop)) elif s.stop is S.Infinity or s.length > 4: printset = s[:4] printset.append(dots) else: printset = tuple(s) return (r"\left[" + r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) + r"\right]") _print_SeqPer = _print_SeqFormula _print_SeqAdd = _print_SeqFormula _print_SeqMul = _print_SeqFormula def _print_Interval(self, i): if i.start == i.end: return r"\left\{%s\right\}" % self._print(i.start) else: if i.left_open: left = '(' else: left = '[' if i.right_open: right = ')' else: right = ']' return r"\left%s%s, %s\right%s" % \ (left, self._print(i.start), self._print(i.end), right) def _print_AccumulationBounds(self, i): return r"\left\langle %s, %s\right\rangle" % \ (self._print(i.min), self._print(i.max)) def _print_Union(self, u): prec = precedence_traditional(u) args_str = [self.parenthesize(i, prec) for i in u.args] return r" \cup ".join(args_str) def _print_Complement(self, u): prec = precedence_traditional(u) args_str = [self.parenthesize(i, prec) for i in u.args] return r" \setminus ".join(args_str) def _print_Intersection(self, u): prec = precedence_traditional(u) args_str = [self.parenthesize(i, prec) for i in u.args] return r" \cap ".join(args_str) def _print_SymmetricDifference(self, u): prec = precedence_traditional(u) args_str = [self.parenthesize(i, prec) for i in u.args] return r" \triangle ".join(args_str) def _print_ProductSet(self, p): prec = precedence_traditional(p) if len(p.sets) >= 1 and not has_variety(p.sets): return self.parenthesize(p.sets[0], prec) + "^{%d}" % len(p.sets) return r" \times ".join( self.parenthesize(set, prec) for set in p.sets) def _print_EmptySet(self, e): return r"\emptyset" def _print_Naturals(self, n): return r"\mathbb{N}" def _print_Naturals0(self, n): return r"\mathbb{N}_0" def _print_Integers(self, i): return r"\mathbb{Z}" def _print_Rationals(self, i): return r"\mathbb{Q}" def _print_Reals(self, i): return r"\mathbb{R}" def _print_Complexes(self, i): return r"\mathbb{C}" def _print_ImageSet(self, s): expr = s.lamda.expr sig = s.lamda.signature xys = ((self._print(x), self._print(y)) for x, y in zip(sig, s.base_sets)) xinys = r" , ".join(r"%s \in %s" % xy for xy in xys) return r"\left\{%s\; \middle|\; %s\right\}" % (self._print(expr), xinys) def _print_ConditionSet(self, s): vars_print = ', '.join([self._print(var) for var in Tuple(s.sym)]) if s.base_set is S.UniversalSet: return r"\left\{%s\; \middle|\; %s \right\}" % \ (vars_print, self._print(s.condition)) return r"\left\{%s\; \middle|\; %s \in %s \wedge %s \right\}" % ( vars_print, vars_print, self._print(s.base_set), self._print(s.condition)) def _print_ComplexRegion(self, s): vars_print = ', '.join([self._print(var) for var in s.variables]) return r"\left\{%s\; \middle|\; %s \in %s \right\}" % ( self._print(s.expr), vars_print, self._print(s.sets)) def _print_Contains(self, e): return r"%s \in %s" % tuple(self._print(a) for a in e.args) def _print_FourierSeries(self, s): return self._print_Add(s.truncate()) + r' + \ldots' def _print_FormalPowerSeries(self, s): return self._print_Add(s.infinite) def _print_FiniteField(self, expr): return r"\mathbb{F}_{%s}" % expr.mod def _print_IntegerRing(self, expr): return r"\mathbb{Z}" def _print_RationalField(self, expr): return r"\mathbb{Q}" def _print_RealField(self, expr): return r"\mathbb{R}" def _print_ComplexField(self, expr): return r"\mathbb{C}" def _print_PolynomialRing(self, expr): domain = self._print(expr.domain) symbols = ", ".join(map(self._print, expr.symbols)) return r"%s\left[%s\right]" % (domain, symbols) def _print_FractionField(self, expr): domain = self._print(expr.domain) symbols = ", ".join(map(self._print, expr.symbols)) return r"%s\left(%s\right)" % (domain, symbols) def _print_PolynomialRingBase(self, expr): domain = self._print(expr.domain) symbols = ", ".join(map(self._print, expr.symbols)) inv = "" if not expr.is_Poly: inv = r"S_<^{-1}" return r"%s%s\left[%s\right]" % (inv, domain, symbols) def _print_Poly(self, poly): cls = poly.__class__.__name__ terms = [] for monom, coeff in poly.terms(): s_monom = '' for i, exp in enumerate(monom): if exp > 0: if exp == 1: s_monom += self._print(poly.gens[i]) else: s_monom += self._print(pow(poly.gens[i], exp)) if coeff.is_Add: if s_monom: s_coeff = r"\left(%s\right)" % self._print(coeff) else: s_coeff = self._print(coeff) else: if s_monom: if coeff is S.One: terms.extend(['+', s_monom]) continue if coeff is S.NegativeOne: terms.extend(['-', s_monom]) continue s_coeff = self._print(coeff) if not s_monom: s_term = s_coeff else: s_term = s_coeff + " " + s_monom if s_term.startswith('-'): terms.extend(['-', s_term[1:]]) else: terms.extend(['+', s_term]) if terms[0] in ('-', '+'): modifier = terms.pop(0) if modifier == '-': terms[0] = '-' + terms[0] expr = ' '.join(terms) gens = list(map(self._print, poly.gens)) domain = "domain=%s" % self._print(poly.get_domain()) args = ", ".join([expr] + gens + [domain]) if cls in accepted_latex_functions: tex = r"\%s {\left(%s \right)}" % (cls, args) else: tex = r"\operatorname{%s}{\left( %s \right)}" % (cls, args) return tex def _print_ComplexRootOf(self, root): cls = root.__class__.__name__ if cls == "ComplexRootOf": cls = "CRootOf" expr = self._print(root.expr) index = root.index if cls in accepted_latex_functions: return r"\%s {\left(%s, %d\right)}" % (cls, expr, index) else: return r"\operatorname{%s} {\left(%s, %d\right)}" % (cls, expr, index) def _print_RootSum(self, expr): cls = expr.__class__.__name__ args = [self._print(expr.expr)] if expr.fun is not S.IdentityFunction: args.append(self._print(expr.fun)) if cls in accepted_latex_functions: return r"\%s {\left(%s\right)}" % (cls, ", ".join(args)) else: return r"\operatorname{%s} {\left(%s\right)}" % (cls, ", ".join(args)) def _print_PolyElement(self, poly): mul_symbol = self._settings['mul_symbol_latex'] return poly.str(self, PRECEDENCE, "{%s}^{%d}", mul_symbol) def _print_FracElement(self, frac): if frac.denom == 1: return self._print(frac.numer) else: numer = self._print(frac.numer) denom = self._print(frac.denom) return r"\frac{%s}{%s}" % (numer, denom) def _print_euler(self, expr, exp=None): m, x = (expr.args[0], None) if len(expr.args) == 1 else expr.args tex = r"E_{%s}" % self._print(m) if exp is not None: tex = r"%s^{%s}" % (tex, exp) if x is not None: tex = r"%s\left(%s\right)" % (tex, self._print(x)) return tex def _print_catalan(self, expr, exp=None): tex = r"C_{%s}" % self._print(expr.args[0]) if exp is not None: tex = r"%s^{%s}" % (tex, exp) return tex def _print_UnifiedTransform(self, expr, s, inverse=False): return r"\mathcal{{{}}}{}_{{{}}}\left[{}\right]\left({}\right)".format(s, '^{-1}' if inverse else '', self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2])) def _print_MellinTransform(self, expr): return self._print_UnifiedTransform(expr, 'M') def _print_InverseMellinTransform(self, expr): return self._print_UnifiedTransform(expr, 'M', True) def _print_LaplaceTransform(self, expr): return self._print_UnifiedTransform(expr, 'L') def _print_InverseLaplaceTransform(self, expr): return self._print_UnifiedTransform(expr, 'L', True) def _print_FourierTransform(self, expr): return self._print_UnifiedTransform(expr, 'F') def _print_InverseFourierTransform(self, expr): return self._print_UnifiedTransform(expr, 'F', True) def _print_SineTransform(self, expr): return self._print_UnifiedTransform(expr, 'SIN') def _print_InverseSineTransform(self, expr): return self._print_UnifiedTransform(expr, 'SIN', True) def _print_CosineTransform(self, expr): return self._print_UnifiedTransform(expr, 'COS') def _print_InverseCosineTransform(self, expr): return self._print_UnifiedTransform(expr, 'COS', True) def _print_DMP(self, p): try: if p.ring is not None: # TODO incorporate order return self._print(p.ring.to_sympy(p)) except SympifyError: pass return self._print(repr(p)) def _print_DMF(self, p): return self._print_DMP(p) def _print_Object(self, object): return self._print(Symbol(object.name)) def _print_LambertW(self, expr, exp=None): arg0 = self._print(expr.args[0]) exp = r"^{%s}" % (exp,) if exp is not None else "" if len(expr.args) == 1: result = r"W%s\left(%s\right)" % (exp, arg0) else: arg1 = self._print(expr.args[1]) result = "W{0}_{{{1}}}\\left({2}\\right)".format(exp, arg1, arg0) return result def _print_Morphism(self, morphism): domain = self._print(morphism.domain) codomain = self._print(morphism.codomain) return "%s\\rightarrow %s" % (domain, codomain) def _print_TransferFunction(self, expr): num, den = self._print(expr.num), self._print(expr.den) return r"\frac{%s}{%s}" % (num, den) def _print_Series(self, expr): args = list(expr.args) parens = lambda x: self.parenthesize(x, precedence_traditional(expr), False) return ' '.join(map(parens, args)) def _print_MIMOSeries(self, expr): from sympy.physics.control.lti import MIMOParallel args = list(expr.args)[::-1] parens = lambda x: self.parenthesize(x, precedence_traditional(expr), False) if isinstance(x, MIMOParallel) else self._print(x) return r"\cdot".join(map(parens, args)) def _print_Parallel(self, expr): args = list(expr.args) func = lambda x: self._print(x) return ' + '.join(map(func, args)) def _print_MIMOParallel(self, expr): args = list(expr.args) func = lambda x: self._print(x) return ' + '.join(map(func, args)) def _print_Feedback(self, expr): from sympy.physics.control import TransferFunction, Series num, tf = expr.sys1, TransferFunction(1, 1, expr.var) num_arg_list = list(num.args) if isinstance(num, Series) else [num] den_arg_list = list(expr.sys2.args) if \ isinstance(expr.sys2, Series) else [expr.sys2] den_term_1 = tf if isinstance(num, Series) and isinstance(expr.sys2, Series): den_term_2 = Series(*num_arg_list, *den_arg_list) elif isinstance(num, Series) and isinstance(expr.sys2, TransferFunction): if expr.sys2 == tf: den_term_2 = Series(*num_arg_list) else: den_term_2 = tf, Series(*num_arg_list, expr.sys2) elif isinstance(num, TransferFunction) and isinstance(expr.sys2, Series): if num == tf: den_term_2 = Series(*den_arg_list) else: den_term_2 = Series(num, *den_arg_list) else: if num == tf: den_term_2 = Series(*den_arg_list) elif expr.sys2 == tf: den_term_2 = Series(*num_arg_list) else: den_term_2 = Series(*num_arg_list, *den_arg_list) numer = self._print(num) denom_1 = self._print(den_term_1) denom_2 = self._print(den_term_2) _sign = "+" if expr.sign == -1 else "-" return r"\frac{%s}{%s %s %s}" % (numer, denom_1, _sign, denom_2) def _print_MIMOFeedback(self, expr): from sympy.physics.control import MIMOSeries inv_mat = self._print(MIMOSeries(expr.sys2, expr.sys1)) sys1 = self._print(expr.sys1) _sign = "+" if expr.sign == -1 else "-" return r"\left(I_{\tau} %s %s\right)^{-1} \cdot %s" % (_sign, inv_mat, sys1) def _print_TransferFunctionMatrix(self, expr): mat = self._print(expr._expr_mat) return r"%s_\tau" % mat def _print_NamedMorphism(self, morphism): pretty_name = self._print(Symbol(morphism.name)) pretty_morphism = self._print_Morphism(morphism) return "%s:%s" % (pretty_name, pretty_morphism) def _print_IdentityMorphism(self, morphism): from sympy.categories import NamedMorphism return self._print_NamedMorphism(NamedMorphism( morphism.domain, morphism.codomain, "id")) def _print_CompositeMorphism(self, morphism): # All components of the morphism have names and it is thus # possible to build the name of the composite. component_names_list = [self._print(Symbol(component.name)) for component in morphism.components] component_names_list.reverse() component_names = "\\circ ".join(component_names_list) + ":" pretty_morphism = self._print_Morphism(morphism) return component_names + pretty_morphism def _print_Category(self, morphism): return r"\mathbf{{{}}}".format(self._print(Symbol(morphism.name))) def _print_Diagram(self, diagram): if not diagram.premises: # This is an empty diagram. return self._print(S.EmptySet) latex_result = self._print(diagram.premises) if diagram.conclusions: latex_result += "\\Longrightarrow %s" % \ self._print(diagram.conclusions) return latex_result def _print_DiagramGrid(self, grid): latex_result = "\\begin{array}{%s}\n" % ("c" * grid.width) for i in range(grid.height): for j in range(grid.width): if grid[i, j]: latex_result += latex(grid[i, j]) latex_result += " " if j != grid.width - 1: latex_result += "& " if i != grid.height - 1: latex_result += "\\\\" latex_result += "\n" latex_result += "\\end{array}\n" return latex_result def _print_FreeModule(self, M): return '{{{}}}^{{{}}}'.format(self._print(M.ring), self._print(M.rank)) def _print_FreeModuleElement(self, m): # Print as row vector for convenience, for now. return r"\left[ {} \right]".format(",".join( '{' + self._print(x) + '}' for x in m)) def _print_SubModule(self, m): return r"\left\langle {} \right\rangle".format(",".join( '{' + self._print(x) + '}' for x in m.gens)) def _print_ModuleImplementedIdeal(self, m): return r"\left\langle {} \right\rangle".format(",".join( '{' + self._print(x) + '}' for [x] in m._module.gens)) def _print_Quaternion(self, expr): # TODO: This expression is potentially confusing, # shall we print it as `Quaternion( ... )`? s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True) for i in expr.args] a = [s[0]] + [i+" "+j for i, j in zip(s[1:], "ijk")] return " + ".join(a) def _print_QuotientRing(self, R): # TODO nicer fractions for few generators... return r"\frac{{{}}}{{{}}}".format(self._print(R.ring), self._print(R.base_ideal)) def _print_QuotientRingElement(self, x): return r"{{{}}} + {{{}}}".format(self._print(x.data), self._print(x.ring.base_ideal)) def _print_QuotientModuleElement(self, m): return r"{{{}}} + {{{}}}".format(self._print(m.data), self._print(m.module.killed_module)) def _print_QuotientModule(self, M): # TODO nicer fractions for few generators... return r"\frac{{{}}}{{{}}}".format(self._print(M.base), self._print(M.killed_module)) def _print_MatrixHomomorphism(self, h): return r"{{{}}} : {{{}}} \to {{{}}}".format(self._print(h._sympy_matrix()), self._print(h.domain), self._print(h.codomain)) def _print_Manifold(self, manifold): string = manifold.name.name if '{' in string: name, supers, subs = string, [], [] else: name, supers, subs = split_super_sub(string) name = translate(name) supers = [translate(sup) for sup in supers] subs = [translate(sub) for sub in subs] name = r'\text{%s}' % name if supers: name += "^{%s}" % " ".join(supers) if subs: name += "_{%s}" % " ".join(subs) return name def _print_Patch(self, patch): return r'\text{%s}_{%s}' % (self._print(patch.name), self._print(patch.manifold)) def _print_CoordSystem(self, coordsys): return r'\text{%s}^{\text{%s}}_{%s}' % ( self._print(coordsys.name), self._print(coordsys.patch.name), self._print(coordsys.manifold) ) def _print_CovarDerivativeOp(self, cvd): return r'\mathbb{\nabla}_{%s}' % self._print(cvd._wrt) def _print_BaseScalarField(self, field): string = field._coord_sys.symbols[field._index].name return r'\mathbf{{{}}}'.format(self._print(Symbol(string))) def _print_BaseVectorField(self, field): string = field._coord_sys.symbols[field._index].name return r'\partial_{{{}}}'.format(self._print(Symbol(string))) def _print_Differential(self, diff): field = diff._form_field if hasattr(field, '_coord_sys'): string = field._coord_sys.symbols[field._index].name return r'\operatorname{{d}}{}'.format(self._print(Symbol(string))) else: string = self._print(field) return r'\operatorname{{d}}\left({}\right)'.format(string) def _print_Tr(self, p): # TODO: Handle indices contents = self._print(p.args[0]) return r'\operatorname{{tr}}\left({}\right)'.format(contents) def _print_totient(self, expr, exp=None): if exp is not None: return r'\left(\phi\left(%s\right)\right)^{%s}' % \ (self._print(expr.args[0]), exp) return r'\phi\left(%s\right)' % self._print(expr.args[0]) def _print_reduced_totient(self, expr, exp=None): if exp is not None: return r'\left(\lambda\left(%s\right)\right)^{%s}' % \ (self._print(expr.args[0]), exp) return r'\lambda\left(%s\right)' % self._print(expr.args[0]) def _print_divisor_sigma(self, expr, exp=None): if len(expr.args) == 2: tex = r"_%s\left(%s\right)" % tuple(map(self._print, (expr.args[1], expr.args[0]))) else: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"\sigma^{%s}%s" % (exp, tex) return r"\sigma%s" % tex def _print_udivisor_sigma(self, expr, exp=None): if len(expr.args) == 2: tex = r"_%s\left(%s\right)" % tuple(map(self._print, (expr.args[1], expr.args[0]))) else: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"\sigma^*^{%s}%s" % (exp, tex) return r"\sigma^*%s" % tex def _print_primenu(self, expr, exp=None): if exp is not None: return r'\left(\nu\left(%s\right)\right)^{%s}' % \ (self._print(expr.args[0]), exp) return r'\nu\left(%s\right)' % self._print(expr.args[0]) def _print_primeomega(self, expr, exp=None): if exp is not None: return r'\left(\Omega\left(%s\right)\right)^{%s}' % \ (self._print(expr.args[0]), exp) return r'\Omega\left(%s\right)' % self._print(expr.args[0]) def _print_Str(self, s): return str(s.name) def _print_float(self, expr): return self._print(Float(expr)) def _print_int(self, expr): return str(expr) def _print_mpz(self, expr): return str(expr) def _print_mpq(self, expr): return str(expr) def _print_Predicate(self, expr): return str(expr) def _print_AppliedPredicate(self, expr): pred = expr.function args = expr.arguments pred_latex = self._print(pred) args_latex = ', '.join([self._print(a) for a in args]) return '%s(%s)' % (pred_latex, args_latex) def emptyPrinter(self, expr): # default to just printing as monospace, like would normally be shown s = super().emptyPrinter(expr) return r"\mathtt{\text{%s}}" % latex_escape(s) def translate(s): r''' Check for a modifier ending the string. If present, convert the modifier to latex and translate the rest recursively. Given a description of a Greek letter or other special character, return the appropriate latex. Let everything else pass as given. >>> from sympy.printing.latex import translate >>> translate('alphahatdotprime') "{\\dot{\\hat{\\alpha}}}'" ''' # Process the rest tex = tex_greek_dictionary.get(s) if tex: return tex elif s.lower() in greek_letters_set: return "\\" + s.lower() elif s in other_symbols: return "\\" + s else: # Process modifiers, if any, and recurse for key in sorted(modifier_dict.keys(), key=lambda k:len(k), reverse=True): if s.lower().endswith(key) and len(s) > len(key): return modifier_dict[key](translate(s[:-len(key)])) return s @print_function(LatexPrinter) def latex(expr, **settings): r"""Convert the given expression to LaTeX string representation. Parameters ========== full_prec: boolean, optional If set to True, a floating point number is printed with full precision. fold_frac_powers : boolean, optional Emit ``^{p/q}`` instead of ``^{\frac{p}{q}}`` for fractional powers. fold_func_brackets : boolean, optional Fold function brackets where applicable. fold_short_frac : boolean, optional Emit ``p / q`` instead of ``\frac{p}{q}`` when the denominator is simple enough (at most two terms and no powers). The default value is ``True`` for inline mode, ``False`` otherwise. inv_trig_style : string, optional How inverse trig functions should be displayed. Can be one of ``abbreviated``, ``full``, or ``power``. Defaults to ``abbreviated``. itex : boolean, optional Specifies if itex-specific syntax is used, including emitting ``$$...$$``. ln_notation : boolean, optional If set to ``True``, ``\ln`` is used instead of default ``\log``. long_frac_ratio : float or None, optional The allowed ratio of the width of the numerator to the width of the denominator before the printer breaks off long fractions. If ``None`` (the default value), long fractions are not broken up. mat_delim : string, optional The delimiter to wrap around matrices. Can be one of ``[``, ``(``, or the empty string. Defaults to ``[``. mat_str : string, optional Which matrix environment string to emit. ``smallmatrix``, ``matrix``, ``array``, etc. Defaults to ``smallmatrix`` for inline mode, ``matrix`` for matrices of no more than 10 columns, and ``array`` otherwise. mode: string, optional Specifies how the generated code will be delimited. ``mode`` can be one of ``plain``, ``inline``, ``equation`` or ``equation*``. If ``mode`` is set to ``plain``, then the resulting code will not be delimited at all (this is the default). If ``mode`` is set to ``inline`` then inline LaTeX ``$...$`` will be used. If ``mode`` is set to ``equation`` or ``equation*``, the resulting code will be enclosed in the ``equation`` or ``equation*`` environment (remember to import ``amsmath`` for ``equation*``), unless the ``itex`` option is set. In the latter case, the ``$$...$$`` syntax is used. mul_symbol : string or None, optional The symbol to use for multiplication. Can be one of ``None``, ``ldot``, ``dot``, or ``times``. order: string, optional Any of the supported monomial orderings (currently ``lex``, ``grlex``, or ``grevlex``), ``old``, and ``none``. This parameter does nothing for Mul objects. Setting order to ``old`` uses the compatibility ordering for Add defined in Printer. For very large expressions, set the ``order`` keyword to ``none`` if speed is a concern. symbol_names : dictionary of strings mapped to symbols, optional Dictionary of symbols and the custom strings they should be emitted as. root_notation : boolean, optional If set to ``False``, exponents of the form 1/n are printed in fractonal form. Default is ``True``, to print exponent in root form. mat_symbol_style : string, optional Can be either ``plain`` (default) or ``bold``. If set to ``bold``, a MatrixSymbol A will be printed as ``\mathbf{A}``, otherwise as ``A``. imaginary_unit : string, optional String to use for the imaginary unit. Defined options are "i" (default) and "j". Adding "r" or "t" in front gives ``\mathrm`` or ``\text``, so "ri" leads to ``\mathrm{i}`` which gives `\mathrm{i}`. gothic_re_im : boolean, optional If set to ``True``, `\Re` and `\Im` is used for ``re`` and ``im``, respectively. The default is ``False`` leading to `\operatorname{re}` and `\operatorname{im}`. decimal_separator : string, optional Specifies what separator to use to separate the whole and fractional parts of a floating point number as in `2.5` for the default, ``period`` or `2{,}5` when ``comma`` is specified. Lists, sets, and tuple are printed with semicolon separating the elements when ``comma`` is chosen. For example, [1; 2; 3] when ``comma`` is chosen and [1,2,3] for when ``period`` is chosen. parenthesize_super : boolean, optional If set to ``False``, superscripted expressions will not be parenthesized when powered. Default is ``True``, which parenthesizes the expression when powered. min: Integer or None, optional Sets the lower bound for the exponent to print floating point numbers in fixed-point format. max: Integer or None, optional Sets the upper bound for the exponent to print floating point numbers in fixed-point format. Notes ===== Not using a print statement for printing, results in double backslashes for latex commands since that's the way Python escapes backslashes in strings. >>> from sympy import latex, Rational >>> from sympy.abc import tau >>> latex((2*tau)**Rational(7,2)) '8 \\sqrt{2} \\tau^{\\frac{7}{2}}' >>> print(latex((2*tau)**Rational(7,2))) 8 \sqrt{2} \tau^{\frac{7}{2}} Examples ======== >>> from sympy import latex, pi, sin, asin, Integral, Matrix, Rational, log >>> from sympy.abc import x, y, mu, r, tau Basic usage: >>> print(latex((2*tau)**Rational(7,2))) 8 \sqrt{2} \tau^{\frac{7}{2}} ``mode`` and ``itex`` options: >>> print(latex((2*mu)**Rational(7,2), mode='plain')) 8 \sqrt{2} \mu^{\frac{7}{2}} >>> print(latex((2*tau)**Rational(7,2), mode='inline')) $8 \sqrt{2} \tau^{7 / 2}$ >>> print(latex((2*mu)**Rational(7,2), mode='equation*')) \begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*} >>> print(latex((2*mu)**Rational(7,2), mode='equation')) \begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation} >>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True)) $$8 \sqrt{2} \mu^{\frac{7}{2}}$$ >>> print(latex((2*mu)**Rational(7,2), mode='plain')) 8 \sqrt{2} \mu^{\frac{7}{2}} >>> print(latex((2*tau)**Rational(7,2), mode='inline')) $8 \sqrt{2} \tau^{7 / 2}$ >>> print(latex((2*mu)**Rational(7,2), mode='equation*')) \begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*} >>> print(latex((2*mu)**Rational(7,2), mode='equation')) \begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation} >>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True)) $$8 \sqrt{2} \mu^{\frac{7}{2}}$$ Fraction options: >>> print(latex((2*tau)**Rational(7,2), fold_frac_powers=True)) 8 \sqrt{2} \tau^{7/2} >>> print(latex((2*tau)**sin(Rational(7,2)))) \left(2 \tau\right)^{\sin{\left(\frac{7}{2} \right)}} >>> print(latex((2*tau)**sin(Rational(7,2)), fold_func_brackets=True)) \left(2 \tau\right)^{\sin {\frac{7}{2}}} >>> print(latex(3*x**2/y)) \frac{3 x^{2}}{y} >>> print(latex(3*x**2/y, fold_short_frac=True)) 3 x^{2} / y >>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=2)) \frac{\int r\, dr}{2 \pi} >>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=0)) \frac{1}{2 \pi} \int r\, dr Multiplication options: >>> print(latex((2*tau)**sin(Rational(7,2)), mul_symbol="times")) \left(2 \times \tau\right)^{\sin{\left(\frac{7}{2} \right)}} Trig options: >>> print(latex(asin(Rational(7,2)))) \operatorname{asin}{\left(\frac{7}{2} \right)} >>> print(latex(asin(Rational(7,2)), inv_trig_style="full")) \arcsin{\left(\frac{7}{2} \right)} >>> print(latex(asin(Rational(7,2)), inv_trig_style="power")) \sin^{-1}{\left(\frac{7}{2} \right)} Matrix options: >>> print(latex(Matrix(2, 1, [x, y]))) \left[\begin{matrix}x\\y\end{matrix}\right] >>> print(latex(Matrix(2, 1, [x, y]), mat_str = "array")) \left[\begin{array}{c}x\\y\end{array}\right] >>> print(latex(Matrix(2, 1, [x, y]), mat_delim="(")) \left(\begin{matrix}x\\y\end{matrix}\right) Custom printing of symbols: >>> print(latex(x**2, symbol_names={x: 'x_i'})) x_i^{2} Logarithms: >>> print(latex(log(10))) \log{\left(10 \right)} >>> print(latex(log(10), ln_notation=True)) \ln{\left(10 \right)} ``latex()`` also supports the builtin container types :class:`list`, :class:`tuple`, and :class:`dict`: >>> print(latex([2/x, y], mode='inline')) $\left[ 2 / x, \ y\right]$ Unsupported types are rendered as monospaced plaintext: >>> print(latex(int)) \mathtt{\text{<class 'int'>}} >>> print(latex("plain % text")) \mathtt{\text{plain \% text}} See :ref:`printer_method_example` for an example of how to override this behavior for your own types by implementing ``_latex``. .. versionchanged:: 1.7.0 Unsupported types no longer have their ``str`` representation treated as valid latex. """ return LatexPrinter(settings).doprint(expr) def print_latex(expr, **settings): """Prints LaTeX representation of the given expression. Takes the same settings as ``latex()``.""" print(latex(expr, **settings)) def multiline_latex(lhs, rhs, terms_per_line=1, environment="align*", use_dots=False, **settings): r""" This function generates a LaTeX equation with a multiline right-hand side in an ``align*``, ``eqnarray`` or ``IEEEeqnarray`` environment. Parameters ========== lhs : Expr Left-hand side of equation rhs : Expr Right-hand side of equation terms_per_line : integer, optional Number of terms per line to print. Default is 1. environment : "string", optional Which LaTeX wnvironment to use for the output. Options are "align*" (default), "eqnarray", and "IEEEeqnarray". use_dots : boolean, optional If ``True``, ``\\dots`` is added to the end of each line. Default is ``False``. Examples ======== >>> from sympy import multiline_latex, symbols, sin, cos, exp, log, I >>> x, y, alpha = symbols('x y alpha') >>> expr = sin(alpha*y) + exp(I*alpha) - cos(log(y)) >>> print(multiline_latex(x, expr)) \begin{align*} x = & e^{i \alpha} \\ & + \sin{\left(\alpha y \right)} \\ & - \cos{\left(\log{\left(y \right)} \right)} \end{align*} Using at most two terms per line: >>> print(multiline_latex(x, expr, 2)) \begin{align*} x = & e^{i \alpha} + \sin{\left(\alpha y \right)} \\ & - \cos{\left(\log{\left(y \right)} \right)} \end{align*} Using ``eqnarray`` and dots: >>> print(multiline_latex(x, expr, terms_per_line=2, environment="eqnarray", use_dots=True)) \begin{eqnarray} x & = & e^{i \alpha} + \sin{\left(\alpha y \right)} \dots\nonumber\\ & & - \cos{\left(\log{\left(y \right)} \right)} \end{eqnarray} Using ``IEEEeqnarray``: >>> print(multiline_latex(x, expr, environment="IEEEeqnarray")) \begin{IEEEeqnarray}{rCl} x & = & e^{i \alpha} \nonumber\\ & & + \sin{\left(\alpha y \right)} \nonumber\\ & & - \cos{\left(\log{\left(y \right)} \right)} \end{IEEEeqnarray} Notes ===== All optional parameters from ``latex`` can also be used. """ # Based on code from https://github.com/sympy/sympy/issues/3001 l = LatexPrinter(**settings) if environment == "eqnarray": result = r'\begin{eqnarray}' + '\n' first_term = '& = &' nonumber = r'\nonumber' end_term = '\n\\end{eqnarray}' doubleet = True elif environment == "IEEEeqnarray": result = r'\begin{IEEEeqnarray}{rCl}' + '\n' first_term = '& = &' nonumber = r'\nonumber' end_term = '\n\\end{IEEEeqnarray}' doubleet = True elif environment == "align*": result = r'\begin{align*}' + '\n' first_term = '= &' nonumber = '' end_term = '\n\\end{align*}' doubleet = False else: raise ValueError("Unknown environment: {}".format(environment)) dots = '' if use_dots: dots=r'\dots' terms = rhs.as_ordered_terms() n_terms = len(terms) term_count = 1 for i in range(n_terms): term = terms[i] term_start = '' term_end = '' sign = '+' if term_count > terms_per_line: if doubleet: term_start = '& & ' else: term_start = '& ' term_count = 1 if term_count == terms_per_line: # End of line if i < n_terms-1: # There are terms remaining term_end = dots + nonumber + r'\\' + '\n' else: term_end = '' if term.as_ordered_factors()[0] == -1: term = -1*term sign = r'-' if i == 0: # beginning if sign == '+': sign = '' result += r'{:s} {:s}{:s} {:s} {:s}'.format(l.doprint(lhs), first_term, sign, l.doprint(term), term_end) else: result += r'{:s}{:s} {:s} {:s}'.format(term_start, sign, l.doprint(term), term_end) term_count += 1 result += end_term return result
0251d991cae4dc526d474dcc45bd81e1fa3c932c42c28fbc0b191dd51fcf8634
"""Printing subsystem driver SymPy's printing system works the following way: Any expression can be passed to a designated Printer who then is responsible to return an adequate representation of that expression. **The basic concept is the following:** 1. Let the object print itself if it knows how. 2. Take the best fitting method defined in the printer. 3. As fall-back use the emptyPrinter method for the printer. Which Method is Responsible for Printing? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The whole printing process is started by calling ``.doprint(expr)`` on the printer which you want to use. This method looks for an appropriate method which can print the given expression in the given style that the printer defines. While looking for the method, it follows these steps: 1. **Let the object print itself if it knows how.** The printer looks for a specific method in every object. The name of that method depends on the specific printer and is defined under ``Printer.printmethod``. For example, StrPrinter calls ``_sympystr`` and LatexPrinter calls ``_latex``. Look at the documentation of the printer that you want to use. The name of the method is specified there. This was the original way of doing printing in sympy. Every class had its own latex, mathml, str and repr methods, but it turned out that it is hard to produce a high quality printer, if all the methods are spread out that far. Therefore all printing code was combined into the different printers, which works great for built-in sympy objects, but not that good for user defined classes where it is inconvenient to patch the printers. 2. **Take the best fitting method defined in the printer.** The printer loops through expr classes (class + its bases), and tries to dispatch the work to ``_print_<EXPR_CLASS>`` e.g., suppose we have the following class hierarchy:: Basic | Atom | Number | Rational then, for ``expr=Rational(...)``, the Printer will try to call printer methods in the order as shown in the figure below:: p._print(expr) | |-- p._print_Rational(expr) | |-- p._print_Number(expr) | |-- p._print_Atom(expr) | `-- p._print_Basic(expr) if ``._print_Rational`` method exists in the printer, then it is called, and the result is returned back. Otherwise, the printer tries to call ``._print_Number`` and so on. 3. **As a fall-back use the emptyPrinter method for the printer.** As fall-back ``self.emptyPrinter`` will be called with the expression. If not defined in the Printer subclass this will be the same as ``str(expr)``. .. _printer_example: Example of Custom Printer ^^^^^^^^^^^^^^^^^^^^^^^^^ In the example below, we have a printer which prints the derivative of a function in a shorter form. .. code-block:: python from sympy import Symbol from sympy.printing.latex import LatexPrinter, print_latex from sympy.core.function import UndefinedFunction, Function class MyLatexPrinter(LatexPrinter): \"\"\"Print derivative of a function of symbols in a shorter form. \"\"\" def _print_Derivative(self, expr): function, *vars = expr.args if not isinstance(type(function), UndefinedFunction) or \\ not all(isinstance(i, Symbol) for i in vars): return super()._print_Derivative(expr) # If you want the printer to work correctly for nested # expressions then use self._print() instead of str() or latex(). # See the example of nested modulo below in the custom printing # method section. return "{}_{{{}}}".format( self._print(Symbol(function.func.__name__)), ''.join(self._print(i) for i in vars)) def print_my_latex(expr): \"\"\" Most of the printers define their own wrappers for print(). These wrappers usually take printer settings. Our printer does not have any settings. \"\"\" print(MyLatexPrinter().doprint(expr)) y = Symbol("y") x = Symbol("x") f = Function("f") expr = f(x, y).diff(x, y) # Print the expression using the normal latex printer and our custom # printer. print_latex(expr) print_my_latex(expr) The output of the code above is:: \\frac{\\partial^{2}}{\\partial x\\partial y} f{\\left(x,y \\right)} f_{xy} .. _printer_method_example: Example of Custom Printing Method ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In the example below, the latex printing of the modulo operator is modified. This is done by overriding the method ``_latex`` of ``Mod``. >>> from sympy import Symbol, Mod, Integer >>> from sympy.printing.latex import print_latex >>> # Always use printer._print() >>> class ModOp(Mod): ... def _latex(self, printer): ... a, b = [printer._print(i) for i in self.args] ... return r"\\operatorname{Mod}{\\left( %s,%s \\right)}" % (a,b) Comparing the output of our custom operator to the builtin one: >>> x = Symbol('x') >>> m = Symbol('m') >>> print_latex(Mod(x, m)) x\\bmod{m} >>> print_latex(ModOp(x, m)) \\operatorname{Mod}{\\left( x,m \\right)} Common mistakes ~~~~~~~~~~~~~~~ It's important to always use ``self._print(obj)`` to print subcomponents of an expression when customizing a printer. Mistakes include: 1. Using ``self.doprint(obj)`` instead: >>> # This example does not work properly, as only the outermost call may use >>> # doprint. >>> class ModOpModeWrong(Mod): ... def _latex(self, printer): ... a, b = [printer.doprint(i) for i in self.args] ... return r"\\operatorname{Mod}{\\left( %s,%s \\right)}" % (a,b) This fails when the `mode` argument is passed to the printer: >>> print_latex(ModOp(x, m), mode='inline') # ok $\\operatorname{Mod}{\\left( x,m \\right)}$ >>> print_latex(ModOpModeWrong(x, m), mode='inline') # bad $\\operatorname{Mod}{\\left( $x$,$m$ \\right)}$ 2. Using ``str(obj)`` instead: >>> class ModOpNestedWrong(Mod): ... def _latex(self, printer): ... a, b = [str(i) for i in self.args] ... return r"\\operatorname{Mod}{\\left( %s,%s \\right)}" % (a,b) This fails on nested objects: >>> # Nested modulo. >>> print_latex(ModOp(ModOp(x, m), Integer(7))) # ok \\operatorname{Mod}{\\left( \\operatorname{Mod}{\\left( x,m \\right)},7 \\right)} >>> print_latex(ModOpNestedWrong(ModOpNestedWrong(x, m), Integer(7))) # bad \\operatorname{Mod}{\\left( ModOpNestedWrong(x, m),7 \\right)} 3. Using ``LatexPrinter()._print(obj)`` instead. >>> from sympy.printing.latex import LatexPrinter >>> class ModOpSettingsWrong(Mod): ... def _latex(self, printer): ... a, b = [LatexPrinter()._print(i) for i in self.args] ... return r"\\operatorname{Mod}{\\left( %s,%s \\right)}" % (a,b) This causes all the settings to be discarded in the subobjects. As an example, the ``full_prec`` setting which shows floats to full precision is ignored: >>> from sympy import Float >>> print_latex(ModOp(Float(1) * x, m), full_prec=True) # ok \\operatorname{Mod}{\\left( 1.00000000000000 x,m \\right)} >>> print_latex(ModOpSettingsWrong(Float(1) * x, m), full_prec=True) # bad \\operatorname{Mod}{\\left( 1.0 x,m \\right)} """ import sys from typing import Any, Dict, Type import inspect from contextlib import contextmanager from functools import cmp_to_key, update_wrapper from sympy import Basic, Add from sympy.core.core import BasicMeta from sympy.core.function import AppliedUndef, UndefinedFunction, Function @contextmanager def printer_context(printer, **kwargs): original = printer._context.copy() try: printer._context.update(kwargs) yield finally: printer._context = original class Printer: """ Generic printer Its job is to provide infrastructure for implementing new printers easily. If you want to define your custom Printer or your custom printing method for your custom class then see the example above: printer_example_ . """ _global_settings = {} # type: Dict[str, Any] _default_settings = {} # type: Dict[str, Any] printmethod = None # type: str @classmethod def _get_initial_settings(cls): settings = cls._default_settings.copy() for key, val in cls._global_settings.items(): if key in cls._default_settings: settings[key] = val return settings def __init__(self, settings=None): self._str = str self._settings = self._get_initial_settings() self._context = dict() # mutable during printing if settings is not None: self._settings.update(settings) if len(self._settings) > len(self._default_settings): for key in self._settings: if key not in self._default_settings: raise TypeError("Unknown setting '%s'." % key) # _print_level is the number of times self._print() was recursively # called. See StrPrinter._print_Float() for an example of usage self._print_level = 0 @classmethod def set_global_settings(cls, **settings): """Set system-wide printing settings. """ for key, val in settings.items(): if val is not None: cls._global_settings[key] = val @property def order(self): if 'order' in self._settings: return self._settings['order'] else: raise AttributeError("No order defined.") def doprint(self, expr): """Returns printer's representation for expr (as a string)""" return self._str(self._print(expr)) def _print(self, expr, **kwargs): """Internal dispatcher Tries the following concepts to print an expression: 1. Let the object print itself if it knows how. 2. Take the best fitting method defined in the printer. 3. As fall-back use the emptyPrinter method for the printer. """ self._print_level += 1 try: # If the printer defines a name for a printing method # (Printer.printmethod) and the object knows for itself how it # should be printed, use that method. if (self.printmethod and hasattr(expr, self.printmethod) and not isinstance(expr, BasicMeta)): return getattr(expr, self.printmethod)(self, **kwargs) # See if the class of expr is known, or if one of its super # classes is known, and use that print function # Exception: ignore the subclasses of Undefined, so that, e.g., # Function('gamma') does not get dispatched to _print_gamma classes = type(expr).__mro__ if AppliedUndef in classes: classes = classes[classes.index(AppliedUndef):] if UndefinedFunction in classes: classes = classes[classes.index(UndefinedFunction):] # Another exception: if someone subclasses a known function, e.g., # gamma, and changes the name, then ignore _print_gamma if Function in classes: i = classes.index(Function) classes = tuple(c for c in classes[:i] if \ c.__name__ == classes[0].__name__ or \ c.__name__.endswith("Base")) + classes[i:] for cls in classes: printmethod = '_print_' + cls.__name__ if hasattr(self, printmethod): return getattr(self, printmethod)(expr, **kwargs) # Unknown object, fall back to the emptyPrinter. return self.emptyPrinter(expr) finally: self._print_level -= 1 def emptyPrinter(self, expr): return str(expr) def _as_ordered_terms(self, expr, order=None): """A compatibility function for ordering terms in Add. """ order = order or self.order if order == 'old': return sorted(Add.make_args(expr), key=cmp_to_key(Basic._compare_pretty)) elif order == 'none': return list(expr.args) else: return expr.as_ordered_terms(order=order) class _PrintFunction: """ Function wrapper to replace ``**settings`` in the signature with printer defaults """ def __init__(self, f, print_cls: Type[Printer]): # find all the non-setting arguments params = list(inspect.signature(f).parameters.values()) assert params.pop(-1).kind == inspect.Parameter.VAR_KEYWORD self.__other_params = params self.__print_cls = print_cls update_wrapper(self, f) def __reduce__(self): # Since this is used as a decorator, it replaces the original function. # The default pickling will try to pickle self.__wrapped__ and fail # because the wrapped function can't be retrieved by name. return self.__wrapped__.__qualname__ def __call__(self, *args, **kwargs): return self.__wrapped__(*args, **kwargs) @property def __signature__(self) -> inspect.Signature: settings = self.__print_cls._get_initial_settings() return inspect.Signature( parameters=self.__other_params + [ inspect.Parameter(k, inspect.Parameter.KEYWORD_ONLY, default=v) for k, v in settings.items() ], return_annotation=self.__wrapped__.__annotations__.get('return', inspect.Signature.empty) # type:ignore ) def print_function(print_cls): """ A decorator to replace kwargs with the printer settings in __signature__ """ def decorator(f): if sys.version_info < (3, 9): # We have to create a subclass so that `help` actually shows the docstring in older python versions. # IPython and Sphinx do not need this, only a raw python console. cls = type(f'{f.__qualname__}_PrintFunction', (_PrintFunction,), dict(__doc__=f.__doc__)) else: cls = _PrintFunction return cls(f, print_cls) return decorator
65bb8970d8110a8603247ec53138755a847e6e172217517276f9ea6760e9afff
""" Octave (and Matlab) code printer The `OctaveCodePrinter` converts SymPy expressions into Octave expressions. It uses a subset of the Octave language for Matlab compatibility. A complete code generator, which uses `octave_code` extensively, can be found in `sympy.utilities.codegen`. The `codegen` module can be used to generate complete source code files. """ from typing import Any, Dict from sympy.core import Mul, Pow, S, Rational from sympy.core.mul import _keep_coeff from sympy.printing.codeprinter import CodePrinter from sympy.printing.precedence import precedence, PRECEDENCE from re import search # List of known functions. First, those that have the same name in # SymPy and Octave. This is almost certainly incomplete! known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc", "asin", "acos", "acot", "atan", "atan2", "asec", "acsc", "sinh", "cosh", "tanh", "coth", "csch", "sech", "asinh", "acosh", "atanh", "acoth", "asech", "acsch", "erfc", "erfi", "erf", "erfinv", "erfcinv", "besseli", "besselj", "besselk", "bessely", "bernoulli", "beta", "euler", "exp", "factorial", "floor", "fresnelc", "fresnels", "gamma", "harmonic", "log", "polylog", "sign", "zeta", "legendre"] # These functions have different names ("Sympy": "Octave"), more # generally a mapping to (argument_conditions, octave_function). known_fcns_src2 = { "Abs": "abs", "arg": "angle", # arg/angle ok in Octave but only angle in Matlab "binomial": "bincoeff", "ceiling": "ceil", "chebyshevu": "chebyshevU", "chebyshevt": "chebyshevT", "Chi": "coshint", "Ci": "cosint", "conjugate": "conj", "DiracDelta": "dirac", "Heaviside": "heaviside", "im": "imag", "laguerre": "laguerreL", "LambertW": "lambertw", "li": "logint", "loggamma": "gammaln", "Max": "max", "Min": "min", "Mod": "mod", "polygamma": "psi", "re": "real", "RisingFactorial": "pochhammer", "Shi": "sinhint", "Si": "sinint", } class OctaveCodePrinter(CodePrinter): """ A printer to convert expressions to strings of Octave/Matlab code. """ printmethod = "_octave" language = "Octave" _operators = { 'and': '&', 'or': '|', 'not': '~', } _default_settings = { 'order': None, 'full_prec': 'auto', 'precision': 17, 'user_functions': {}, 'human': True, 'allow_unknown_functions': False, 'contract': True, 'inline': True, } # type: Dict[str, Any] # Note: contract is for expressing tensors as loops (if True), or just # assignment (if False). FIXME: this should be looked a more carefully # for Octave. def __init__(self, settings={}): super().__init__(settings) self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1)) self.known_functions.update(dict(known_fcns_src2)) userfuncs = settings.get('user_functions', {}) self.known_functions.update(userfuncs) def _rate_index_position(self, p): return p*5 def _get_statement(self, codestring): return "%s;" % codestring def _get_comment(self, text): return "% {}".format(text) def _declare_number_const(self, name, value): return "{} = {};".format(name, value) def _format_code(self, lines): return self.indent_code(lines) def _traverse_matrix_indices(self, mat): # Octave uses Fortran order (column-major) rows, cols = mat.shape return ((i, j) for j in range(cols) for i in range(rows)) def _get_loop_opening_ending(self, indices): open_lines = [] close_lines = [] for i in indices: # Octave arrays start at 1 and end at dimension var, start, stop = map(self._print, [i.label, i.lower + 1, i.upper + 1]) open_lines.append("for %s = %s:%s" % (var, start, stop)) close_lines.append("end") return open_lines, close_lines def _print_Mul(self, expr): # print complex numbers nicely in Octave if (expr.is_number and expr.is_imaginary and (S.ImaginaryUnit*expr).is_Integer): return "%si" % self._print(-S.ImaginaryUnit*expr) # cribbed from str.py prec = precedence(expr) c, e = expr.as_coeff_Mul() if c < 0: expr = _keep_coeff(-c, e) sign = "-" else: sign = "" a = [] # items in the numerator b = [] # items that are in the denominator (if any) pow_paren = [] # Will collect all pow with more than one base element and exp = -1 if self.order not in ('old', 'none'): args = expr.as_ordered_factors() else: # use make_args in case expr was something like -x -> x args = Mul.make_args(expr) # Gather args for numerator/denominator for item in args: if (item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative): if item.exp != -1: b.append(Pow(item.base, -item.exp, evaluate=False)) else: if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160 pow_paren.append(item) b.append(Pow(item.base, -item.exp)) elif item.is_Rational and item is not S.Infinity: if item.p != 1: a.append(Rational(item.p)) if item.q != 1: b.append(Rational(item.q)) else: a.append(item) a = a or [S.One] a_str = [self.parenthesize(x, prec) for x in a] b_str = [self.parenthesize(x, prec) for x in b] # To parenthesize Pow with exp = -1 and having more than one Symbol for item in pow_paren: if item.base in b: b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)] # from here it differs from str.py to deal with "*" and ".*" def multjoin(a, a_str): # here we probably are assuming the constants will come first r = a_str[0] for i in range(1, len(a)): mulsym = '*' if a[i-1].is_number else '.*' r = r + mulsym + a_str[i] return r if not b: return sign + multjoin(a, a_str) elif len(b) == 1: divsym = '/' if b[0].is_number else './' return sign + multjoin(a, a_str) + divsym + b_str[0] else: divsym = '/' if all(bi.is_number for bi in b) else './' return (sign + multjoin(a, a_str) + divsym + "(%s)" % multjoin(b, b_str)) def _print_Relational(self, expr): lhs_code = self._print(expr.lhs) rhs_code = self._print(expr.rhs) op = expr.rel_op return "{} {} {}".format(lhs_code, op, rhs_code) def _print_Pow(self, expr): powsymbol = '^' if all(x.is_number for x in expr.args) else '.^' PREC = precedence(expr) if expr.exp == S.Half: return "sqrt(%s)" % self._print(expr.base) if expr.is_commutative: if expr.exp == -S.Half: sym = '/' if expr.base.is_number else './' return "1" + sym + "sqrt(%s)" % self._print(expr.base) if expr.exp == -S.One: sym = '/' if expr.base.is_number else './' return "1" + sym + "%s" % self.parenthesize(expr.base, PREC) return '%s%s%s' % (self.parenthesize(expr.base, PREC), powsymbol, self.parenthesize(expr.exp, PREC)) def _print_MatPow(self, expr): PREC = precedence(expr) return '%s^%s' % (self.parenthesize(expr.base, PREC), self.parenthesize(expr.exp, PREC)) def _print_MatrixSolve(self, expr): PREC = precedence(expr) return "%s \\ %s" % (self.parenthesize(expr.matrix, PREC), self.parenthesize(expr.vector, PREC)) def _print_Pi(self, expr): return 'pi' def _print_ImaginaryUnit(self, expr): return "1i" def _print_Exp1(self, expr): return "exp(1)" def _print_GoldenRatio(self, expr): # FIXME: how to do better, e.g., for octave_code(2*GoldenRatio)? #return self._print((1+sqrt(S(5)))/2) return "(1+sqrt(5))/2" def _print_Assignment(self, expr): from sympy.codegen.ast import Assignment from sympy.functions.elementary.piecewise import Piecewise from sympy.tensor.indexed import IndexedBase # Copied from codeprinter, but remove special MatrixSymbol treatment lhs = expr.lhs rhs = expr.rhs # We special case assignments that take multiple lines if not self._settings["inline"] and isinstance(expr.rhs, Piecewise): # Here we modify Piecewise so each expression is now # an Assignment, and then continue on the print. expressions = [] conditions = [] for (e, c) in rhs.args: expressions.append(Assignment(lhs, e)) conditions.append(c) temp = Piecewise(*zip(expressions, conditions)) return self._print(temp) if self._settings["contract"] and (lhs.has(IndexedBase) or rhs.has(IndexedBase)): # Here we check if there is looping to be done, and if so # print the required loops. return self._doprint_loops(rhs, lhs) else: lhs_code = self._print(lhs) rhs_code = self._print(rhs) return self._get_statement("%s = %s" % (lhs_code, rhs_code)) def _print_Infinity(self, expr): return 'inf' def _print_NegativeInfinity(self, expr): return '-inf' def _print_NaN(self, expr): return 'NaN' def _print_list(self, expr): return '{' + ', '.join(self._print(a) for a in expr) + '}' _print_tuple = _print_list _print_Tuple = _print_list def _print_BooleanTrue(self, expr): return "true" def _print_BooleanFalse(self, expr): return "false" def _print_bool(self, expr): return str(expr).lower() # Could generate quadrature code for definite Integrals? #_print_Integral = _print_not_supported def _print_MatrixBase(self, A): # Handle zero dimensions: if (A.rows, A.cols) == (0, 0): return '[]' elif A.rows == 0 or A.cols == 0: return 'zeros(%s, %s)' % (A.rows, A.cols) elif (A.rows, A.cols) == (1, 1): # Octave does not distinguish between scalars and 1x1 matrices return self._print(A[0, 0]) return "[%s]" % "; ".join(" ".join([self._print(a) for a in A[r, :]]) for r in range(A.rows)) def _print_SparseMatrix(self, A): from sympy.matrices import Matrix L = A.col_list(); # make row vectors of the indices and entries I = Matrix([[k[0] + 1 for k in L]]) J = Matrix([[k[1] + 1 for k in L]]) AIJ = Matrix([[k[2] for k in L]]) return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J), self._print(AIJ), A.rows, A.cols) def _print_MatrixElement(self, expr): return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \ + '(%s, %s)' % (expr.i + 1, expr.j + 1) def _print_MatrixSlice(self, expr): def strslice(x, lim): l = x[0] + 1 h = x[1] step = x[2] lstr = self._print(l) hstr = 'end' if h == lim else self._print(h) if step == 1: if l == 1 and h == lim: return ':' if l == h: return lstr else: return lstr + ':' + hstr else: return ':'.join((lstr, self._print(step), hstr)) return (self._print(expr.parent) + '(' + strslice(expr.rowslice, expr.parent.shape[0]) + ', ' + strslice(expr.colslice, expr.parent.shape[1]) + ')') def _print_Indexed(self, expr): inds = [ self._print(i) for i in expr.indices ] return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds)) def _print_Idx(self, expr): return self._print(expr.label) def _print_KroneckerDelta(self, expr): prec = PRECEDENCE["Pow"] return "double(%s == %s)" % tuple(self.parenthesize(x, prec) for x in expr.args) def _print_HadamardProduct(self, expr): return '.*'.join([self.parenthesize(arg, precedence(expr)) for arg in expr.args]) def _print_HadamardPower(self, expr): PREC = precedence(expr) return '.**'.join([ self.parenthesize(expr.base, PREC), self.parenthesize(expr.exp, PREC) ]) def _print_Identity(self, expr): shape = expr.shape if len(shape) == 2 and shape[0] == shape[1]: shape = [shape[0]] s = ", ".join(self._print(n) for n in shape) return "eye(" + s + ")" def _print_lowergamma(self, expr): # Octave implements regularized incomplete gamma function return "(gammainc({1}, {0}).*gamma({0}))".format( self._print(expr.args[0]), self._print(expr.args[1])) def _print_uppergamma(self, expr): return "(gammainc({1}, {0}, 'upper').*gamma({0}))".format( self._print(expr.args[0]), self._print(expr.args[1])) def _print_sinc(self, expr): #Note: Divide by pi because Octave implements normalized sinc function. return "sinc(%s)" % self._print(expr.args[0]/S.Pi) def _print_hankel1(self, expr): return "besselh(%s, 1, %s)" % (self._print(expr.order), self._print(expr.argument)) def _print_hankel2(self, expr): return "besselh(%s, 2, %s)" % (self._print(expr.order), self._print(expr.argument)) # Note: as of 2015, Octave doesn't have spherical Bessel functions def _print_jn(self, expr): from sympy.functions import sqrt, besselj x = expr.argument expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x) return self._print(expr2) def _print_yn(self, expr): from sympy.functions import sqrt, bessely x = expr.argument expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x) return self._print(expr2) def _print_airyai(self, expr): return "airy(0, %s)" % self._print(expr.args[0]) def _print_airyaiprime(self, expr): return "airy(1, %s)" % self._print(expr.args[0]) def _print_airybi(self, expr): return "airy(2, %s)" % self._print(expr.args[0]) def _print_airybiprime(self, expr): return "airy(3, %s)" % self._print(expr.args[0]) def _print_expint(self, expr): mu, x = expr.args if mu != 1: return self._print_not_supported(expr) return "expint(%s)" % self._print(x) def _one_or_two_reversed_args(self, expr): assert len(expr.args) <= 2 return '{name}({args})'.format( name=self.known_functions[expr.__class__.__name__], args=", ".join([self._print(x) for x in reversed(expr.args)]) ) _print_DiracDelta = _print_LambertW = _one_or_two_reversed_args def _nested_binary_math_func(self, expr): return '{name}({arg1}, {arg2})'.format( name=self.known_functions[expr.__class__.__name__], arg1=self._print(expr.args[0]), arg2=self._print(expr.func(*expr.args[1:])) ) _print_Max = _print_Min = _nested_binary_math_func def _print_Piecewise(self, expr): if expr.args[-1].cond != True: # We need the last conditional to be a True, otherwise the resulting # function may not return a result. raise ValueError("All Piecewise expressions must contain an " "(expr, True) statement to be used as a default " "condition. Without one, the generated " "expression may not evaluate to anything under " "some condition.") lines = [] if self._settings["inline"]: # Express each (cond, expr) pair in a nested Horner form: # (condition) .* (expr) + (not cond) .* (<others>) # Expressions that result in multiple statements won't work here. ecpairs = ["({0}).*({1}) + (~({0})).*(".format (self._print(c), self._print(e)) for e, c in expr.args[:-1]] elast = "%s" % self._print(expr.args[-1].expr) pw = " ...\n".join(ecpairs) + elast + ")"*len(ecpairs) # Note: current need these outer brackets for 2*pw. Would be # nicer to teach parenthesize() to do this for us when needed! return "(" + pw + ")" else: for i, (e, c) in enumerate(expr.args): if i == 0: lines.append("if (%s)" % self._print(c)) elif i == len(expr.args) - 1 and c == True: lines.append("else") else: lines.append("elseif (%s)" % self._print(c)) code0 = self._print(e) lines.append(code0) if i == len(expr.args) - 1: lines.append("end") return "\n".join(lines) def _print_zeta(self, expr): if len(expr.args) == 1: return "zeta(%s)" % self._print(expr.args[0]) else: # Matlab two argument zeta is not equivalent to SymPy's return self._print_not_supported(expr) def indent_code(self, code): """Accepts a string of code or a list of code lines""" # code mostly copied from ccode if isinstance(code, str): code_lines = self.indent_code(code.splitlines(True)) return ''.join(code_lines) tab = " " inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ') dec_regex = ('^end$', '^elseif ', '^else$') # pre-strip left-space from the code code = [ line.lstrip(' \t') for line in code ] increase = [ int(any(search(re, line) for re in inc_regex)) for line in code ] decrease = [ int(any(search(re, line) for re in dec_regex)) for line in code ] pretty = [] level = 0 for n, line in enumerate(code): if line == '' or line == '\n': pretty.append(line) continue level -= decrease[n] pretty.append("%s%s" % (tab*level, line)) level += increase[n] return pretty def octave_code(expr, assign_to=None, **settings): r"""Converts `expr` to a string of Octave (or Matlab) code. The string uses a subset of the Octave language for Matlab compatibility. Parameters ========== expr : Expr A sympy expression to be converted. assign_to : optional When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for expressions that generate multi-line statements. precision : integer, optional The precision for numbers such as pi [default=16]. user_functions : dict, optional A dictionary where keys are ``FunctionClass`` instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. inline: bool, optional If True, we try to create single-statement code instead of multiple statements. [default=True]. Examples ======== >>> from sympy import octave_code, symbols, sin, pi >>> x = symbols('x') >>> octave_code(sin(x).series(x).removeO()) 'x.^5/120 - x.^3/6 + x' >>> from sympy import Rational, ceiling >>> x, y, tau = symbols("x, y, tau") >>> octave_code((2*tau)**Rational(7, 2)) '8*sqrt(2)*tau.^(7/2)' Note that element-wise (Hadamard) operations are used by default between symbols. This is because its very common in Octave to write "vectorized" code. It is harmless if the values are scalars. >>> octave_code(sin(pi*x*y), assign_to="s") 's = sin(pi*x.*y);' If you need a matrix product "*" or matrix power "^", you can specify the symbol as a ``MatrixSymbol``. >>> from sympy import Symbol, MatrixSymbol >>> n = Symbol('n', integer=True, positive=True) >>> A = MatrixSymbol('A', n, n) >>> octave_code(3*pi*A**3) '(3*pi)*A^3' This class uses several rules to decide which symbol to use a product. Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*". A HadamardProduct can be used to specify componentwise multiplication ".*" of two MatrixSymbols. There is currently there is no easy way to specify scalar symbols, so sometimes the code might have some minor cosmetic issues. For example, suppose x and y are scalars and A is a Matrix, then while a human programmer might write "(x^2*y)*A^3", we generate: >>> octave_code(x**2*y*A**3) '(x.^2.*y)*A^3' Matrices are supported using Octave inline notation. When using ``assign_to`` with matrices, the name can be specified either as a string or as a ``MatrixSymbol``. The dimensions must align in the latter case. >>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([[x**2, sin(x), ceiling(x)]]) >>> octave_code(mat, assign_to='A') 'A = [x.^2 sin(x) ceil(x)];' ``Piecewise`` expressions are implemented with logical masking by default. Alternatively, you can pass "inline=False" to use if-else conditionals. Note that if the ``Piecewise`` lacks a default term, represented by ``(expr, True)`` then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything. >>> from sympy import Piecewise >>> pw = Piecewise((x + 1, x > 0), (x, True)) >>> octave_code(pw, assign_to=tau) 'tau = ((x > 0).*(x + 1) + (~(x > 0)).*(x));' Note that any expression that can be generated normally can also exist inside a Matrix: >>> mat = Matrix([[x**2, pw, sin(x)]]) >>> octave_code(mat, assign_to='A') 'A = [x.^2 ((x > 0).*(x + 1) + (~(x > 0)).*(x)) sin(x)];' Custom printing can be defined for certain types by passing a dictionary of "type" : "function" to the ``user_functions`` kwarg. Alternatively, the dictionary value can be a list of tuples i.e., [(argument_test, cfunction_string)]. This can be used to call a custom Octave function. >>> from sympy import Function >>> f = Function('f') >>> g = Function('g') >>> custom_functions = { ... "f": "existing_octave_fcn", ... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"), ... (lambda x: not x.is_Matrix, "my_fcn")] ... } >>> mat = Matrix([[1, x]]) >>> octave_code(f(x) + g(x) + g(mat), user_functions=custom_functions) 'existing_octave_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])' Support for loops is provided through ``Indexed`` types. With ``contract=True`` these expressions will be turned into loops, whereas ``contract=False`` will just print the assignment expression that should be looped over: >>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', shape=(len_y,)) >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) >>> i = Idx('i', len_y-1) >>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) >>> octave_code(e.rhs, assign_to=e.lhs, contract=False) 'Dy(i) = (y(i + 1) - y(i))./(t(i + 1) - t(i));' """ return OctaveCodePrinter(settings).doprint(expr, assign_to) def print_octave_code(expr, **settings): """Prints the Octave (or Matlab) representation of the given expression. See `octave_code` for the meaning of the optional arguments. """ print(octave_code(expr, **settings))