hash
stringlengths
64
64
content
stringlengths
0
1.51M
ffc3c602158c43f0347f60d02dd0de32ba71635f7cf3d3f9221f47e354599fcb
from sympy.printing.tree import tree from sympy.testing.pytest import XFAIL # Remove this flag after making _assumptions cache deterministic. @XFAIL def test_print_tree_MatAdd(): from sympy.matrices.expressions import MatrixSymbol A = MatrixSymbol('A', 3, 3) B = MatrixSymbol('B', 3, 3) test_str = [ 'MatAdd: A + B\n', 'algebraic: False\n', 'commutative: False\n', 'complex: False\n', 'composite: False\n', 'even: False\n', 'extended_negative: False\n', 'extended_nonnegative: False\n', 'extended_nonpositive: False\n', 'extended_nonzero: False\n', 'extended_positive: False\n', 'extended_real: False\n', 'imaginary: False\n', 'integer: False\n', 'irrational: False\n', 'negative: False\n', 'noninteger: False\n', 'nonnegative: False\n', 'nonpositive: False\n', 'nonzero: False\n', 'odd: False\n', 'positive: False\n', 'prime: False\n', 'rational: False\n', 'real: False\n', 'transcendental: False\n', 'zero: False\n', '+-MatrixSymbol: A\n', '| algebraic: False\n', '| commutative: False\n', '| complex: False\n', '| composite: False\n', '| even: False\n', '| extended_negative: False\n', '| extended_nonnegative: False\n', '| extended_nonpositive: False\n', '| extended_nonzero: False\n', '| extended_positive: False\n', '| extended_real: False\n', '| imaginary: False\n', '| integer: False\n', '| irrational: False\n', '| negative: False\n', '| noninteger: False\n', '| nonnegative: False\n', '| nonpositive: False\n', '| nonzero: False\n', '| odd: False\n', '| positive: False\n', '| prime: False\n', '| rational: False\n', '| real: False\n', '| transcendental: False\n', '| zero: False\n', '| +-Symbol: A\n', '| | commutative: True\n', '| +-Integer: 3\n', '| | algebraic: True\n', '| | commutative: True\n', '| | complex: True\n', '| | extended_negative: False\n', '| | extended_nonnegative: True\n', '| | extended_real: True\n', '| | finite: True\n', '| | hermitian: True\n', '| | imaginary: False\n', '| | infinite: False\n', '| | integer: True\n', '| | irrational: False\n', '| | negative: False\n', '| | noninteger: False\n', '| | nonnegative: True\n', '| | rational: True\n', '| | real: True\n', '| | transcendental: False\n', '| +-Integer: 3\n', '| algebraic: True\n', '| commutative: True\n', '| complex: True\n', '| extended_negative: False\n', '| extended_nonnegative: True\n', '| extended_real: True\n', '| finite: True\n', '| hermitian: True\n', '| imaginary: False\n', '| infinite: False\n', '| integer: True\n', '| irrational: False\n', '| negative: False\n', '| noninteger: False\n', '| nonnegative: True\n', '| rational: True\n', '| real: True\n', '| transcendental: False\n', '+-MatrixSymbol: B\n', ' algebraic: False\n', ' commutative: False\n', ' complex: False\n', ' composite: False\n', ' even: False\n', ' extended_negative: False\n', ' extended_nonnegative: False\n', ' extended_nonpositive: False\n', ' extended_nonzero: False\n', ' extended_positive: False\n', ' extended_real: False\n', ' imaginary: False\n', ' integer: False\n', ' irrational: False\n', ' negative: False\n', ' noninteger: False\n', ' nonnegative: False\n', ' nonpositive: False\n', ' nonzero: False\n', ' odd: False\n', ' positive: False\n', ' prime: False\n', ' rational: False\n', ' real: False\n', ' transcendental: False\n', ' zero: False\n', ' +-Symbol: B\n', ' | commutative: True\n', ' +-Integer: 3\n', ' | algebraic: True\n', ' | commutative: True\n', ' | complex: True\n', ' | extended_negative: False\n', ' | extended_nonnegative: True\n', ' | extended_real: True\n', ' | finite: True\n', ' | hermitian: True\n', ' | imaginary: False\n', ' | infinite: False\n', ' | integer: True\n', ' | irrational: False\n', ' | negative: False\n', ' | noninteger: False\n', ' | nonnegative: True\n', ' | rational: True\n', ' | real: True\n', ' | transcendental: False\n', ' +-Integer: 3\n', ' algebraic: True\n', ' commutative: True\n', ' complex: True\n', ' extended_negative: False\n', ' extended_nonnegative: True\n', ' extended_real: True\n', ' finite: True\n', ' hermitian: True\n', ' imaginary: False\n', ' infinite: False\n', ' integer: True\n', ' irrational: False\n', ' negative: False\n', ' noninteger: False\n', ' nonnegative: True\n', ' rational: True\n', ' real: True\n', ' transcendental: False\n' ] assert tree(A + B) == "".join(test_str) def test_print_tree_MatAdd_noassumptions(): from sympy.matrices.expressions import MatrixSymbol A = MatrixSymbol('A', 3, 3) B = MatrixSymbol('B', 3, 3) test_str = \ """MatAdd: A + B +-MatrixSymbol: A | +-Str: A | +-Integer: 3 | +-Integer: 3 +-MatrixSymbol: B +-Str: B +-Integer: 3 +-Integer: 3 """ assert tree(A + B, assumptions=False) == test_str
b8ab7e289b6b4e93b4d9453a830d257f6e52d5b9b85645dd8749cabe4ac0df35
from sympy import diff, Integral, Limit, sin, Symbol, Integer, Rational, cos, \ tan, asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh, E, I, oo, \ pi, GoldenRatio, EulerGamma, Sum, Eq, Ne, Ge, Lt, Float, Matrix, Basic, \ S, MatrixSymbol, Function, Derivative, log, true, false, Range, Min, Max, \ Lambda, IndexedBase, symbols, zoo, elliptic_f, elliptic_e, elliptic_pi, Ei, \ expint, jacobi, gegenbauer, chebyshevt, chebyshevu, legendre, assoc_legendre, \ laguerre, assoc_laguerre, hermite, euler, stieltjes, mathieuc, mathieus, \ mathieucprime, mathieusprime, TribonacciConstant, Contains, LambertW, \ cot, coth, acot, acoth, csc, acsc, csch, acsch, sec, asec, sech, asech from sympy import elliptic_k, totient, reduced_totient, primenu, primeomega, \ fresnelc, fresnels, Heaviside from sympy.calculus.util import AccumBounds from sympy.core.containers import Tuple from sympy.functions.combinatorial.factorials import factorial, factorial2, \ binomial from sympy.functions.combinatorial.numbers import bernoulli, bell, lucas, \ fibonacci, tribonacci, catalan from sympy.functions.elementary.complexes import re, im, Abs, conjugate from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.integers import floor, ceiling from sympy.functions.special.gamma_functions import gamma, lowergamma, uppergamma from sympy.functions.special.singularity_functions import SingularityFunction from sympy.functions.special.zeta_functions import polylog, lerchphi, zeta, dirichlet_eta from sympy.logic.boolalg import And, Or, Implies, Equivalent, Xor, Not from sympy.matrices.expressions.determinant import Determinant from sympy.physics.quantum import ComplexSpace, HilbertSpace, FockSpace, hbar, Dagger from sympy.printing.mathml import mathml, MathMLContentPrinter, \ MathMLPresentationPrinter, MathMLPrinter from sympy.sets.sets import FiniteSet, Union, Intersection, Complement, \ SymmetricDifference, Interval, EmptySet, ProductSet from sympy.stats.rv import RandomSymbol from sympy.testing.pytest import raises from sympy.vector import CoordSys3D, Cross, Curl, Dot, Divergence, Gradient, Laplacian x, y, z, a, b, c, d, e, n = symbols('x:z a:e n') mp = MathMLContentPrinter() mpp = MathMLPresentationPrinter() def test_mathml_printer(): m = MathMLPrinter() assert m.doprint(1+x) == mp.doprint(1+x) def test_content_printmethod(): assert mp.doprint(1 + x) == '<apply><plus/><ci>x</ci><cn>1</cn></apply>' def test_content_mathml_core(): mml_1 = mp._print(1 + x) assert mml_1.nodeName == 'apply' nodes = mml_1.childNodes assert len(nodes) == 3 assert nodes[0].nodeName == 'plus' assert nodes[0].hasChildNodes() is False assert nodes[0].nodeValue is None assert nodes[1].nodeName in ['cn', 'ci'] if nodes[1].nodeName == 'cn': assert nodes[1].childNodes[0].nodeValue == '1' assert nodes[2].childNodes[0].nodeValue == 'x' else: assert nodes[1].childNodes[0].nodeValue == 'x' assert nodes[2].childNodes[0].nodeValue == '1' mml_2 = mp._print(x**2) assert mml_2.nodeName == 'apply' nodes = mml_2.childNodes assert nodes[1].childNodes[0].nodeValue == 'x' assert nodes[2].childNodes[0].nodeValue == '2' mml_3 = mp._print(2*x) assert mml_3.nodeName == 'apply' nodes = mml_3.childNodes assert nodes[0].nodeName == 'times' assert nodes[1].childNodes[0].nodeValue == '2' assert nodes[2].childNodes[0].nodeValue == 'x' mml = mp._print(Float(1.0, 2)*x) assert mml.nodeName == 'apply' nodes = mml.childNodes assert nodes[0].nodeName == 'times' assert nodes[1].childNodes[0].nodeValue == '1.0' assert nodes[2].childNodes[0].nodeValue == 'x' def test_content_mathml_functions(): mml_1 = mp._print(sin(x)) assert mml_1.nodeName == 'apply' assert mml_1.childNodes[0].nodeName == 'sin' assert mml_1.childNodes[1].nodeName == 'ci' mml_2 = mp._print(diff(sin(x), x, evaluate=False)) assert mml_2.nodeName == 'apply' assert mml_2.childNodes[0].nodeName == 'diff' assert mml_2.childNodes[1].nodeName == 'bvar' assert mml_2.childNodes[1].childNodes[ 0].nodeName == 'ci' # below bvar there's <ci>x/ci> mml_3 = mp._print(diff(cos(x*y), x, evaluate=False)) assert mml_3.nodeName == 'apply' assert mml_3.childNodes[0].nodeName == 'partialdiff' assert mml_3.childNodes[1].nodeName == 'bvar' assert mml_3.childNodes[1].childNodes[ 0].nodeName == 'ci' # below bvar there's <ci>x/ci> def test_content_mathml_limits(): # XXX No unevaluated limits lim_fun = sin(x)/x mml_1 = mp._print(Limit(lim_fun, x, 0)) assert mml_1.childNodes[0].nodeName == 'limit' assert mml_1.childNodes[1].nodeName == 'bvar' assert mml_1.childNodes[2].nodeName == 'lowlimit' assert mml_1.childNodes[3].toxml() == mp._print(lim_fun).toxml() def test_content_mathml_integrals(): integrand = x mml_1 = mp._print(Integral(integrand, (x, 0, 1))) assert mml_1.childNodes[0].nodeName == 'int' assert mml_1.childNodes[1].nodeName == 'bvar' assert mml_1.childNodes[2].nodeName == 'lowlimit' assert mml_1.childNodes[3].nodeName == 'uplimit' assert mml_1.childNodes[4].toxml() == mp._print(integrand).toxml() def test_content_mathml_matrices(): A = Matrix([1, 2, 3]) B = Matrix([[0, 5, 4], [2, 3, 1], [9, 7, 9]]) mll_1 = mp._print(A) assert mll_1.childNodes[0].nodeName == 'matrixrow' assert mll_1.childNodes[0].childNodes[0].nodeName == 'cn' assert mll_1.childNodes[0].childNodes[0].childNodes[0].nodeValue == '1' assert mll_1.childNodes[1].nodeName == 'matrixrow' assert mll_1.childNodes[1].childNodes[0].nodeName == 'cn' assert mll_1.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2' assert mll_1.childNodes[2].nodeName == 'matrixrow' assert mll_1.childNodes[2].childNodes[0].nodeName == 'cn' assert mll_1.childNodes[2].childNodes[0].childNodes[0].nodeValue == '3' mll_2 = mp._print(B) assert mll_2.childNodes[0].nodeName == 'matrixrow' assert mll_2.childNodes[0].childNodes[0].nodeName == 'cn' assert mll_2.childNodes[0].childNodes[0].childNodes[0].nodeValue == '0' assert mll_2.childNodes[0].childNodes[1].nodeName == 'cn' assert mll_2.childNodes[0].childNodes[1].childNodes[0].nodeValue == '5' assert mll_2.childNodes[0].childNodes[2].nodeName == 'cn' assert mll_2.childNodes[0].childNodes[2].childNodes[0].nodeValue == '4' assert mll_2.childNodes[1].nodeName == 'matrixrow' assert mll_2.childNodes[1].childNodes[0].nodeName == 'cn' assert mll_2.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2' assert mll_2.childNodes[1].childNodes[1].nodeName == 'cn' assert mll_2.childNodes[1].childNodes[1].childNodes[0].nodeValue == '3' assert mll_2.childNodes[1].childNodes[2].nodeName == 'cn' assert mll_2.childNodes[1].childNodes[2].childNodes[0].nodeValue == '1' assert mll_2.childNodes[2].nodeName == 'matrixrow' assert mll_2.childNodes[2].childNodes[0].nodeName == 'cn' assert mll_2.childNodes[2].childNodes[0].childNodes[0].nodeValue == '9' assert mll_2.childNodes[2].childNodes[1].nodeName == 'cn' assert mll_2.childNodes[2].childNodes[1].childNodes[0].nodeValue == '7' assert mll_2.childNodes[2].childNodes[2].nodeName == 'cn' assert mll_2.childNodes[2].childNodes[2].childNodes[0].nodeValue == '9' def test_content_mathml_sums(): summand = x mml_1 = mp._print(Sum(summand, (x, 1, 10))) assert mml_1.childNodes[0].nodeName == 'sum' assert mml_1.childNodes[1].nodeName == 'bvar' assert mml_1.childNodes[2].nodeName == 'lowlimit' assert mml_1.childNodes[3].nodeName == 'uplimit' assert mml_1.childNodes[4].toxml() == mp._print(summand).toxml() def test_content_mathml_tuples(): mml_1 = mp._print([2]) assert mml_1.nodeName == 'list' assert mml_1.childNodes[0].nodeName == 'cn' assert len(mml_1.childNodes) == 1 mml_2 = mp._print([2, Integer(1)]) assert mml_2.nodeName == 'list' assert mml_2.childNodes[0].nodeName == 'cn' assert mml_2.childNodes[1].nodeName == 'cn' assert len(mml_2.childNodes) == 2 def test_content_mathml_add(): mml = mp._print(x**5 - x**4 + x) assert mml.childNodes[0].nodeName == 'plus' assert mml.childNodes[1].childNodes[0].nodeName == 'minus' assert mml.childNodes[1].childNodes[1].nodeName == 'apply' def test_content_mathml_Rational(): mml_1 = mp._print(Rational(1, 1)) """should just return a number""" assert mml_1.nodeName == 'cn' mml_2 = mp._print(Rational(2, 5)) assert mml_2.childNodes[0].nodeName == 'divide' def test_content_mathml_constants(): mml = mp._print(I) assert mml.nodeName == 'imaginaryi' mml = mp._print(E) assert mml.nodeName == 'exponentiale' mml = mp._print(oo) assert mml.nodeName == 'infinity' mml = mp._print(pi) assert mml.nodeName == 'pi' assert mathml(GoldenRatio) == '<cn>&#966;</cn>' mml = mathml(EulerGamma) assert mml == '<eulergamma/>' mml = mathml(EmptySet()) assert mml == '<emptyset/>' mml = mathml(S.true) assert mml == '<true/>' mml = mathml(S.false) assert mml == '<false/>' mml = mathml(S.NaN) assert mml == '<notanumber/>' def test_content_mathml_trig(): mml = mp._print(sin(x)) assert mml.childNodes[0].nodeName == 'sin' mml = mp._print(cos(x)) assert mml.childNodes[0].nodeName == 'cos' mml = mp._print(tan(x)) assert mml.childNodes[0].nodeName == 'tan' mml = mp._print(cot(x)) assert mml.childNodes[0].nodeName == 'cot' mml = mp._print(csc(x)) assert mml.childNodes[0].nodeName == 'csc' mml = mp._print(sec(x)) assert mml.childNodes[0].nodeName == 'sec' mml = mp._print(asin(x)) assert mml.childNodes[0].nodeName == 'arcsin' mml = mp._print(acos(x)) assert mml.childNodes[0].nodeName == 'arccos' mml = mp._print(atan(x)) assert mml.childNodes[0].nodeName == 'arctan' mml = mp._print(acot(x)) assert mml.childNodes[0].nodeName == 'arccot' mml = mp._print(acsc(x)) assert mml.childNodes[0].nodeName == 'arccsc' mml = mp._print(asec(x)) assert mml.childNodes[0].nodeName == 'arcsec' mml = mp._print(sinh(x)) assert mml.childNodes[0].nodeName == 'sinh' mml = mp._print(cosh(x)) assert mml.childNodes[0].nodeName == 'cosh' mml = mp._print(tanh(x)) assert mml.childNodes[0].nodeName == 'tanh' mml = mp._print(coth(x)) assert mml.childNodes[0].nodeName == 'coth' mml = mp._print(csch(x)) assert mml.childNodes[0].nodeName == 'csch' mml = mp._print(sech(x)) assert mml.childNodes[0].nodeName == 'sech' mml = mp._print(asinh(x)) assert mml.childNodes[0].nodeName == 'arcsinh' mml = mp._print(atanh(x)) assert mml.childNodes[0].nodeName == 'arctanh' mml = mp._print(acosh(x)) assert mml.childNodes[0].nodeName == 'arccosh' mml = mp._print(acoth(x)) assert mml.childNodes[0].nodeName == 'arccoth' mml = mp._print(acsch(x)) assert mml.childNodes[0].nodeName == 'arccsch' mml = mp._print(asech(x)) assert mml.childNodes[0].nodeName == 'arcsech' def test_content_mathml_relational(): mml_1 = mp._print(Eq(x, 1)) assert mml_1.nodeName == 'apply' assert mml_1.childNodes[0].nodeName == 'eq' assert mml_1.childNodes[1].nodeName == 'ci' assert mml_1.childNodes[1].childNodes[0].nodeValue == 'x' assert mml_1.childNodes[2].nodeName == 'cn' assert mml_1.childNodes[2].childNodes[0].nodeValue == '1' mml_2 = mp._print(Ne(1, x)) assert mml_2.nodeName == 'apply' assert mml_2.childNodes[0].nodeName == 'neq' assert mml_2.childNodes[1].nodeName == 'cn' assert mml_2.childNodes[1].childNodes[0].nodeValue == '1' assert mml_2.childNodes[2].nodeName == 'ci' assert mml_2.childNodes[2].childNodes[0].nodeValue == 'x' mml_3 = mp._print(Ge(1, x)) assert mml_3.nodeName == 'apply' assert mml_3.childNodes[0].nodeName == 'geq' assert mml_3.childNodes[1].nodeName == 'cn' assert mml_3.childNodes[1].childNodes[0].nodeValue == '1' assert mml_3.childNodes[2].nodeName == 'ci' assert mml_3.childNodes[2].childNodes[0].nodeValue == 'x' mml_4 = mp._print(Lt(1, x)) assert mml_4.nodeName == 'apply' assert mml_4.childNodes[0].nodeName == 'lt' assert mml_4.childNodes[1].nodeName == 'cn' assert mml_4.childNodes[1].childNodes[0].nodeValue == '1' assert mml_4.childNodes[2].nodeName == 'ci' assert mml_4.childNodes[2].childNodes[0].nodeValue == 'x' def test_content_symbol(): mml = mp._print(x) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeValue == 'x' del mml mml = mp._print(Symbol("x^2")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mp._print(Symbol("x__2")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mp._print(Symbol("x_2")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msub' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mp._print(Symbol("x^3_2")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msubsup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2' assert mml.childNodes[0].childNodes[2].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[2].childNodes[0].nodeValue == '3' del mml mml = mp._print(Symbol("x__3_2")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msubsup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2' assert mml.childNodes[0].childNodes[2].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[2].childNodes[0].nodeValue == '3' del mml mml = mp._print(Symbol("x_2_a")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msub' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mrow' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].childNodes[ 0].nodeValue == '2' assert mml.childNodes[0].childNodes[1].childNodes[1].nodeName == 'mml:mo' assert mml.childNodes[0].childNodes[1].childNodes[1].childNodes[ 0].nodeValue == ' ' assert mml.childNodes[0].childNodes[1].childNodes[2].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[2].childNodes[ 0].nodeValue == 'a' del mml mml = mp._print(Symbol("x^2^a")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mrow' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].childNodes[ 0].nodeValue == '2' assert mml.childNodes[0].childNodes[1].childNodes[1].nodeName == 'mml:mo' assert mml.childNodes[0].childNodes[1].childNodes[1].childNodes[ 0].nodeValue == ' ' assert mml.childNodes[0].childNodes[1].childNodes[2].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[2].childNodes[ 0].nodeValue == 'a' del mml mml = mp._print(Symbol("x__2__a")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mrow' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].childNodes[ 0].nodeValue == '2' assert mml.childNodes[0].childNodes[1].childNodes[1].nodeName == 'mml:mo' assert mml.childNodes[0].childNodes[1].childNodes[1].childNodes[ 0].nodeValue == ' ' assert mml.childNodes[0].childNodes[1].childNodes[2].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[2].childNodes[ 0].nodeValue == 'a' del mml def test_content_mathml_greek(): mml = mp._print(Symbol('alpha')) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeValue == '\N{GREEK SMALL LETTER ALPHA}' assert mp.doprint(Symbol('alpha')) == '<ci>&#945;</ci>' assert mp.doprint(Symbol('beta')) == '<ci>&#946;</ci>' assert mp.doprint(Symbol('gamma')) == '<ci>&#947;</ci>' assert mp.doprint(Symbol('delta')) == '<ci>&#948;</ci>' assert mp.doprint(Symbol('epsilon')) == '<ci>&#949;</ci>' assert mp.doprint(Symbol('zeta')) == '<ci>&#950;</ci>' assert mp.doprint(Symbol('eta')) == '<ci>&#951;</ci>' assert mp.doprint(Symbol('theta')) == '<ci>&#952;</ci>' assert mp.doprint(Symbol('iota')) == '<ci>&#953;</ci>' assert mp.doprint(Symbol('kappa')) == '<ci>&#954;</ci>' assert mp.doprint(Symbol('lambda')) == '<ci>&#955;</ci>' assert mp.doprint(Symbol('mu')) == '<ci>&#956;</ci>' assert mp.doprint(Symbol('nu')) == '<ci>&#957;</ci>' assert mp.doprint(Symbol('xi')) == '<ci>&#958;</ci>' assert mp.doprint(Symbol('omicron')) == '<ci>&#959;</ci>' assert mp.doprint(Symbol('pi')) == '<ci>&#960;</ci>' assert mp.doprint(Symbol('rho')) == '<ci>&#961;</ci>' assert mp.doprint(Symbol('varsigma')) == '<ci>&#962;</ci>' assert mp.doprint(Symbol('sigma')) == '<ci>&#963;</ci>' assert mp.doprint(Symbol('tau')) == '<ci>&#964;</ci>' assert mp.doprint(Symbol('upsilon')) == '<ci>&#965;</ci>' assert mp.doprint(Symbol('phi')) == '<ci>&#966;</ci>' assert mp.doprint(Symbol('chi')) == '<ci>&#967;</ci>' assert mp.doprint(Symbol('psi')) == '<ci>&#968;</ci>' assert mp.doprint(Symbol('omega')) == '<ci>&#969;</ci>' assert mp.doprint(Symbol('Alpha')) == '<ci>&#913;</ci>' assert mp.doprint(Symbol('Beta')) == '<ci>&#914;</ci>' assert mp.doprint(Symbol('Gamma')) == '<ci>&#915;</ci>' assert mp.doprint(Symbol('Delta')) == '<ci>&#916;</ci>' assert mp.doprint(Symbol('Epsilon')) == '<ci>&#917;</ci>' assert mp.doprint(Symbol('Zeta')) == '<ci>&#918;</ci>' assert mp.doprint(Symbol('Eta')) == '<ci>&#919;</ci>' assert mp.doprint(Symbol('Theta')) == '<ci>&#920;</ci>' assert mp.doprint(Symbol('Iota')) == '<ci>&#921;</ci>' assert mp.doprint(Symbol('Kappa')) == '<ci>&#922;</ci>' assert mp.doprint(Symbol('Lambda')) == '<ci>&#923;</ci>' assert mp.doprint(Symbol('Mu')) == '<ci>&#924;</ci>' assert mp.doprint(Symbol('Nu')) == '<ci>&#925;</ci>' assert mp.doprint(Symbol('Xi')) == '<ci>&#926;</ci>' assert mp.doprint(Symbol('Omicron')) == '<ci>&#927;</ci>' assert mp.doprint(Symbol('Pi')) == '<ci>&#928;</ci>' assert mp.doprint(Symbol('Rho')) == '<ci>&#929;</ci>' assert mp.doprint(Symbol('Sigma')) == '<ci>&#931;</ci>' assert mp.doprint(Symbol('Tau')) == '<ci>&#932;</ci>' assert mp.doprint(Symbol('Upsilon')) == '<ci>&#933;</ci>' assert mp.doprint(Symbol('Phi')) == '<ci>&#934;</ci>' assert mp.doprint(Symbol('Chi')) == '<ci>&#935;</ci>' assert mp.doprint(Symbol('Psi')) == '<ci>&#936;</ci>' assert mp.doprint(Symbol('Omega')) == '<ci>&#937;</ci>' def test_content_mathml_order(): expr = x**3 + x**2*y + 3*x*y**3 + y**4 mp = MathMLContentPrinter({'order': 'lex'}) mml = mp._print(expr) assert mml.childNodes[1].childNodes[0].nodeName == 'power' assert mml.childNodes[1].childNodes[1].childNodes[0].data == 'x' assert mml.childNodes[1].childNodes[2].childNodes[0].data == '3' assert mml.childNodes[4].childNodes[0].nodeName == 'power' assert mml.childNodes[4].childNodes[1].childNodes[0].data == 'y' assert mml.childNodes[4].childNodes[2].childNodes[0].data == '4' mp = MathMLContentPrinter({'order': 'rev-lex'}) mml = mp._print(expr) assert mml.childNodes[1].childNodes[0].nodeName == 'power' assert mml.childNodes[1].childNodes[1].childNodes[0].data == 'y' assert mml.childNodes[1].childNodes[2].childNodes[0].data == '4' assert mml.childNodes[4].childNodes[0].nodeName == 'power' assert mml.childNodes[4].childNodes[1].childNodes[0].data == 'x' assert mml.childNodes[4].childNodes[2].childNodes[0].data == '3' def test_content_settings(): raises(TypeError, lambda: mathml(x, method="garbage")) def test_content_mathml_logic(): assert mathml(And(x, y)) == '<apply><and/><ci>x</ci><ci>y</ci></apply>' assert mathml(Or(x, y)) == '<apply><or/><ci>x</ci><ci>y</ci></apply>' assert mathml(Xor(x, y)) == '<apply><xor/><ci>x</ci><ci>y</ci></apply>' assert mathml(Implies(x, y)) == '<apply><implies/><ci>x</ci><ci>y</ci></apply>' assert mathml(Not(x)) == '<apply><not/><ci>x</ci></apply>' def test_content_finite_sets(): assert mathml(FiniteSet(a)) == '<set><ci>a</ci></set>' assert mathml(FiniteSet(a, b)) == '<set><ci>a</ci><ci>b</ci></set>' assert mathml(FiniteSet(FiniteSet(a, b), c)) == \ '<set><ci>c</ci><set><ci>a</ci><ci>b</ci></set></set>' 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) # XXX ProductSet does not support evaluate keyword P1 = ProductSet(A, B) P2 = ProductSet(C, D) assert mathml(U1) == \ '<apply><union/><set><ci>a</ci></set><set><ci>b</ci></set></apply>' assert mathml(I1) == \ '<apply><intersect/><set><ci>a</ci></set><set><ci>b</ci></set>' \ '</apply>' assert mathml(C1) == \ '<apply><setdiff/><set><ci>a</ci></set><set><ci>b</ci></set></apply>' assert mathml(P1) == \ '<apply><cartesianproduct/><set><ci>a</ci></set><set><ci>b</ci>' \ '</set></apply>' assert mathml(Intersection(A, U2, evaluate=False)) == \ '<apply><intersect/><set><ci>a</ci></set><apply><union/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(Intersection(U1, U2, evaluate=False)) == \ '<apply><intersect/><apply><union/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><union/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' # XXX Does the parenthesis appear correctly for these examples in mathjax? assert mathml(Intersection(C1, C2, evaluate=False)) == \ '<apply><intersect/><apply><setdiff/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><setdiff/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(Intersection(P1, P2, evaluate=False)) == \ '<apply><intersect/><apply><cartesianproduct/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><cartesianproduct/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(Union(A, I2, evaluate=False)) == \ '<apply><union/><set><ci>a</ci></set><apply><intersect/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(Union(I1, I2, evaluate=False)) == \ '<apply><union/><apply><intersect/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><intersect/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(Union(C1, C2, evaluate=False)) == \ '<apply><union/><apply><setdiff/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><setdiff/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(Union(P1, P2, evaluate=False)) == \ '<apply><union/><apply><cartesianproduct/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><cartesianproduct/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(Complement(A, C2, evaluate=False)) == \ '<apply><setdiff/><set><ci>a</ci></set><apply><setdiff/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(Complement(U1, U2, evaluate=False)) == \ '<apply><setdiff/><apply><union/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><union/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(Complement(I1, I2, evaluate=False)) == \ '<apply><setdiff/><apply><intersect/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><intersect/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(Complement(P1, P2, evaluate=False)) == \ '<apply><setdiff/><apply><cartesianproduct/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><cartesianproduct/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(ProductSet(A, P2)) == \ '<apply><cartesianproduct/><set><ci>a</ci></set>' \ '<apply><cartesianproduct/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(ProductSet(U1, U2)) == \ '<apply><cartesianproduct/><apply><union/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><union/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(ProductSet(I1, I2)) == \ '<apply><cartesianproduct/><apply><intersect/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><intersect/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(ProductSet(C1, C2)) == \ '<apply><cartesianproduct/><apply><setdiff/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><setdiff/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' def test_presentation_printmethod(): assert mpp.doprint(1 + x) == '<mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow>' assert mpp.doprint(x**2) == '<msup><mi>x</mi><mn>2</mn></msup>' assert mpp.doprint(x**-1) == '<mfrac><mn>1</mn><mi>x</mi></mfrac>' assert mpp.doprint(x**-2) == \ '<mfrac><mn>1</mn><msup><mi>x</mi><mn>2</mn></msup></mfrac>' assert mpp.doprint(2*x) == \ '<mrow><mn>2</mn><mo>&InvisibleTimes;</mo><mi>x</mi></mrow>' def test_presentation_mathml_core(): mml_1 = mpp._print(1 + x) assert mml_1.nodeName == 'mrow' nodes = mml_1.childNodes assert len(nodes) == 3 assert nodes[0].nodeName in ['mi', 'mn'] assert nodes[1].nodeName == 'mo' if nodes[0].nodeName == 'mn': assert nodes[0].childNodes[0].nodeValue == '1' assert nodes[2].childNodes[0].nodeValue == 'x' else: assert nodes[0].childNodes[0].nodeValue == 'x' assert nodes[2].childNodes[0].nodeValue == '1' mml_2 = mpp._print(x**2) assert mml_2.nodeName == 'msup' nodes = mml_2.childNodes assert nodes[0].childNodes[0].nodeValue == 'x' assert nodes[1].childNodes[0].nodeValue == '2' mml_3 = mpp._print(2*x) assert mml_3.nodeName == 'mrow' nodes = mml_3.childNodes assert nodes[0].childNodes[0].nodeValue == '2' assert nodes[1].childNodes[0].nodeValue == '&InvisibleTimes;' assert nodes[2].childNodes[0].nodeValue == 'x' mml = mpp._print(Float(1.0, 2)*x) assert mml.nodeName == 'mrow' nodes = mml.childNodes assert nodes[0].childNodes[0].nodeValue == '1.0' assert nodes[1].childNodes[0].nodeValue == '&InvisibleTimes;' assert nodes[2].childNodes[0].nodeValue == 'x' def test_presentation_mathml_functions(): mml_1 = mpp._print(sin(x)) assert mml_1.childNodes[0].childNodes[0 ].nodeValue == 'sin' assert mml_1.childNodes[1].childNodes[0 ].childNodes[0].nodeValue == 'x' mml_2 = mpp._print(diff(sin(x), x, evaluate=False)) assert mml_2.nodeName == 'mrow' assert mml_2.childNodes[0].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '&dd;' assert mml_2.childNodes[1].childNodes[1 ].nodeName == 'mfenced' assert mml_2.childNodes[0].childNodes[1 ].childNodes[0].childNodes[0].nodeValue == '&dd;' mml_3 = mpp._print(diff(cos(x*y), x, evaluate=False)) assert mml_3.childNodes[0].nodeName == 'mfrac' assert mml_3.childNodes[0].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '&#x2202;' assert mml_3.childNodes[1].childNodes[0 ].childNodes[0].nodeValue == 'cos' def test_print_derivative(): f = Function('f') d = Derivative(f(x, y, z), x, z, x, z, z, y) assert mathml(d) == \ '<apply><partialdiff/><bvar><ci>y</ci><ci>z</ci><degree><cn>2</cn></degree><ci>x</ci><ci>z</ci><ci>x</ci></bvar><apply><f/><ci>x</ci><ci>y</ci><ci>z</ci></apply></apply>' assert mathml(d, printer='presentation') == \ '<mrow><mfrac><mrow><msup><mo>&#x2202;</mo><mn>6</mn></msup></mrow><mrow><mo>&#x2202;</mo><mi>y</mi><msup><mo>&#x2202;</mo><mn>2</mn></msup><mi>z</mi><mo>&#x2202;</mo><mi>x</mi><mo>&#x2202;</mo><mi>z</mi><mo>&#x2202;</mo><mi>x</mi></mrow></mfrac><mrow><mi>f</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow></mrow>' def test_presentation_mathml_limits(): lim_fun = sin(x)/x mml_1 = mpp._print(Limit(lim_fun, x, 0)) assert mml_1.childNodes[0].nodeName == 'munder' assert mml_1.childNodes[0].childNodes[0 ].childNodes[0].nodeValue == 'lim' assert mml_1.childNodes[0].childNodes[1 ].childNodes[0].childNodes[0 ].nodeValue == 'x' assert mml_1.childNodes[0].childNodes[1 ].childNodes[1].childNodes[0 ].nodeValue == '&#x2192;' assert mml_1.childNodes[0].childNodes[1 ].childNodes[2].childNodes[0 ].nodeValue == '0' def test_presentation_mathml_integrals(): assert mpp.doprint(Integral(x, (x, 0, 1))) == \ '<mrow><msubsup><mo>&#x222B;</mo><mn>0</mn><mn>1</mn></msubsup>'\ '<mi>x</mi><mo>&dd;</mo><mi>x</mi></mrow>' assert mpp.doprint(Integral(log(x), x)) == \ '<mrow><mo>&#x222B;</mo><mrow><mi>log</mi><mfenced><mi>x</mi>'\ '</mfenced></mrow><mo>&dd;</mo><mi>x</mi></mrow>' assert mpp.doprint(Integral(x*y, x, y)) == \ '<mrow><mo>&#x222C;</mo><mrow><mi>x</mi><mo>&InvisibleTimes;</mo>'\ '<mi>y</mi></mrow><mo>&dd;</mo><mi>y</mi><mo>&dd;</mo><mi>x</mi></mrow>' z, w = symbols('z w') assert mpp.doprint(Integral(x*y*z, x, y, z)) == \ '<mrow><mo>&#x222D;</mo><mrow><mi>x</mi><mo>&InvisibleTimes;</mo>'\ '<mi>y</mi><mo>&InvisibleTimes;</mo><mi>z</mi></mrow><mo>&dd;</mo>'\ '<mi>z</mi><mo>&dd;</mo><mi>y</mi><mo>&dd;</mo><mi>x</mi></mrow>' assert mpp.doprint(Integral(x*y*z*w, x, y, z, w)) == \ '<mrow><mo>&#x222B;</mo><mo>&#x222B;</mo><mo>&#x222B;</mo>'\ '<mo>&#x222B;</mo><mrow><mi>w</mi><mo>&InvisibleTimes;</mo>'\ '<mi>x</mi><mo>&InvisibleTimes;</mo><mi>y</mi>'\ '<mo>&InvisibleTimes;</mo><mi>z</mi></mrow><mo>&dd;</mo><mi>w</mi>'\ '<mo>&dd;</mo><mi>z</mi><mo>&dd;</mo><mi>y</mi><mo>&dd;</mo><mi>x</mi></mrow>' assert mpp.doprint(Integral(x, x, y, (z, 0, 1))) == \ '<mrow><msubsup><mo>&#x222B;</mo><mn>0</mn><mn>1</mn></msubsup>'\ '<mo>&#x222B;</mo><mo>&#x222B;</mo><mi>x</mi><mo>&dd;</mo><mi>z</mi>'\ '<mo>&dd;</mo><mi>y</mi><mo>&dd;</mo><mi>x</mi></mrow>' assert mpp.doprint(Integral(x, (x, 0))) == \ '<mrow><msup><mo>&#x222B;</mo><mn>0</mn></msup><mi>x</mi><mo>&dd;</mo>'\ '<mi>x</mi></mrow>' def test_presentation_mathml_matrices(): A = Matrix([1, 2, 3]) B = Matrix([[0, 5, 4], [2, 3, 1], [9, 7, 9]]) mll_1 = mpp._print(A) assert mll_1.childNodes[0].nodeName == 'mtable' assert mll_1.childNodes[0].childNodes[0].nodeName == 'mtr' assert len(mll_1.childNodes[0].childNodes) == 3 assert mll_1.childNodes[0].childNodes[0].childNodes[0].nodeName == 'mtd' assert len(mll_1.childNodes[0].childNodes[0].childNodes) == 1 assert mll_1.childNodes[0].childNodes[0].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '1' assert mll_1.childNodes[0].childNodes[1].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '2' assert mll_1.childNodes[0].childNodes[2].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '3' mll_2 = mpp._print(B) assert mll_2.childNodes[0].nodeName == 'mtable' assert mll_2.childNodes[0].childNodes[0].nodeName == 'mtr' assert len(mll_2.childNodes[0].childNodes) == 3 assert mll_2.childNodes[0].childNodes[0].childNodes[0].nodeName == 'mtd' assert len(mll_2.childNodes[0].childNodes[0].childNodes) == 3 assert mll_2.childNodes[0].childNodes[0].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '0' assert mll_2.childNodes[0].childNodes[0].childNodes[1 ].childNodes[0].childNodes[0].nodeValue == '5' assert mll_2.childNodes[0].childNodes[0].childNodes[2 ].childNodes[0].childNodes[0].nodeValue == '4' assert mll_2.childNodes[0].childNodes[1].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '2' assert mll_2.childNodes[0].childNodes[1].childNodes[1 ].childNodes[0].childNodes[0].nodeValue == '3' assert mll_2.childNodes[0].childNodes[1].childNodes[2 ].childNodes[0].childNodes[0].nodeValue == '1' assert mll_2.childNodes[0].childNodes[2].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '9' assert mll_2.childNodes[0].childNodes[2].childNodes[1 ].childNodes[0].childNodes[0].nodeValue == '7' assert mll_2.childNodes[0].childNodes[2].childNodes[2 ].childNodes[0].childNodes[0].nodeValue == '9' def test_presentation_mathml_sums(): summand = x mml_1 = mpp._print(Sum(summand, (x, 1, 10))) assert mml_1.childNodes[0].nodeName == 'munderover' assert len(mml_1.childNodes[0].childNodes) == 3 assert mml_1.childNodes[0].childNodes[0].childNodes[0 ].nodeValue == '&#x2211;' assert len(mml_1.childNodes[0].childNodes[1].childNodes) == 3 assert mml_1.childNodes[0].childNodes[2].childNodes[0 ].nodeValue == '10' assert mml_1.childNodes[1].childNodes[0].nodeValue == 'x' def test_presentation_mathml_add(): mml = mpp._print(x**5 - x**4 + x) assert len(mml.childNodes) == 5 assert mml.childNodes[0].childNodes[0].childNodes[0 ].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].childNodes[0 ].nodeValue == '5' assert mml.childNodes[1].childNodes[0].nodeValue == '-' assert mml.childNodes[2].childNodes[0].childNodes[0 ].nodeValue == 'x' assert mml.childNodes[2].childNodes[1].childNodes[0 ].nodeValue == '4' assert mml.childNodes[3].childNodes[0].nodeValue == '+' assert mml.childNodes[4].childNodes[0].nodeValue == 'x' def test_presentation_mathml_Rational(): mml_1 = mpp._print(Rational(1, 1)) assert mml_1.nodeName == 'mn' mml_2 = mpp._print(Rational(2, 5)) assert mml_2.nodeName == 'mfrac' assert mml_2.childNodes[0].childNodes[0].nodeValue == '2' assert mml_2.childNodes[1].childNodes[0].nodeValue == '5' def test_presentation_mathml_constants(): mml = mpp._print(I) assert mml.childNodes[0].nodeValue == '&ImaginaryI;' mml = mpp._print(E) assert mml.childNodes[0].nodeValue == '&ExponentialE;' mml = mpp._print(oo) assert mml.childNodes[0].nodeValue == '&#x221E;' mml = mpp._print(pi) assert mml.childNodes[0].nodeValue == '&pi;' assert mathml(GoldenRatio, printer='presentation') == '<mi>&#x3A6;</mi>' assert mathml(zoo, printer='presentation') == \ '<mover><mo>&#x221E;</mo><mo>~</mo></mover>' assert mathml(S.NaN, printer='presentation') == '<mi>NaN</mi>' def test_presentation_mathml_trig(): mml = mpp._print(sin(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'sin' mml = mpp._print(cos(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'cos' mml = mpp._print(tan(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'tan' mml = mpp._print(asin(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arcsin' mml = mpp._print(acos(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arccos' mml = mpp._print(atan(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arctan' mml = mpp._print(sinh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'sinh' mml = mpp._print(cosh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'cosh' mml = mpp._print(tanh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'tanh' mml = mpp._print(asinh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arcsinh' mml = mpp._print(atanh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arctanh' mml = mpp._print(acosh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arccosh' def test_presentation_mathml_relational(): mml_1 = mpp._print(Eq(x, 1)) assert len(mml_1.childNodes) == 3 assert mml_1.childNodes[0].nodeName == 'mi' assert mml_1.childNodes[0].childNodes[0].nodeValue == 'x' assert mml_1.childNodes[1].nodeName == 'mo' assert mml_1.childNodes[1].childNodes[0].nodeValue == '=' assert mml_1.childNodes[2].nodeName == 'mn' assert mml_1.childNodes[2].childNodes[0].nodeValue == '1' mml_2 = mpp._print(Ne(1, x)) assert len(mml_2.childNodes) == 3 assert mml_2.childNodes[0].nodeName == 'mn' assert mml_2.childNodes[0].childNodes[0].nodeValue == '1' assert mml_2.childNodes[1].nodeName == 'mo' assert mml_2.childNodes[1].childNodes[0].nodeValue == '&#x2260;' assert mml_2.childNodes[2].nodeName == 'mi' assert mml_2.childNodes[2].childNodes[0].nodeValue == 'x' mml_3 = mpp._print(Ge(1, x)) assert len(mml_3.childNodes) == 3 assert mml_3.childNodes[0].nodeName == 'mn' assert mml_3.childNodes[0].childNodes[0].nodeValue == '1' assert mml_3.childNodes[1].nodeName == 'mo' assert mml_3.childNodes[1].childNodes[0].nodeValue == '&#x2265;' assert mml_3.childNodes[2].nodeName == 'mi' assert mml_3.childNodes[2].childNodes[0].nodeValue == 'x' mml_4 = mpp._print(Lt(1, x)) assert len(mml_4.childNodes) == 3 assert mml_4.childNodes[0].nodeName == 'mn' assert mml_4.childNodes[0].childNodes[0].nodeValue == '1' assert mml_4.childNodes[1].nodeName == 'mo' assert mml_4.childNodes[1].childNodes[0].nodeValue == '<' assert mml_4.childNodes[2].nodeName == 'mi' assert mml_4.childNodes[2].childNodes[0].nodeValue == 'x' def test_presentation_symbol(): mml = mpp._print(x) assert mml.nodeName == 'mi' assert mml.childNodes[0].nodeValue == 'x' del mml mml = mpp._print(Symbol("x^2")) assert mml.nodeName == 'msup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mpp._print(Symbol("x__2")) assert mml.nodeName == 'msup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mpp._print(Symbol("x_2")) assert mml.nodeName == 'msub' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mpp._print(Symbol("x^3_2")) assert mml.nodeName == 'msubsup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].nodeValue == '2' assert mml.childNodes[2].nodeName == 'mi' assert mml.childNodes[2].childNodes[0].nodeValue == '3' del mml mml = mpp._print(Symbol("x__3_2")) assert mml.nodeName == 'msubsup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].nodeValue == '2' assert mml.childNodes[2].nodeName == 'mi' assert mml.childNodes[2].childNodes[0].nodeValue == '3' del mml mml = mpp._print(Symbol("x_2_a")) assert mml.nodeName == 'msub' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mrow' assert mml.childNodes[1].childNodes[0].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2' assert mml.childNodes[1].childNodes[1].nodeName == 'mo' assert mml.childNodes[1].childNodes[1].childNodes[0].nodeValue == ' ' assert mml.childNodes[1].childNodes[2].nodeName == 'mi' assert mml.childNodes[1].childNodes[2].childNodes[0].nodeValue == 'a' del mml mml = mpp._print(Symbol("x^2^a")) assert mml.nodeName == 'msup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mrow' assert mml.childNodes[1].childNodes[0].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2' assert mml.childNodes[1].childNodes[1].nodeName == 'mo' assert mml.childNodes[1].childNodes[1].childNodes[0].nodeValue == ' ' assert mml.childNodes[1].childNodes[2].nodeName == 'mi' assert mml.childNodes[1].childNodes[2].childNodes[0].nodeValue == 'a' del mml mml = mpp._print(Symbol("x__2__a")) assert mml.nodeName == 'msup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mrow' assert mml.childNodes[1].childNodes[0].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2' assert mml.childNodes[1].childNodes[1].nodeName == 'mo' assert mml.childNodes[1].childNodes[1].childNodes[0].nodeValue == ' ' assert mml.childNodes[1].childNodes[2].nodeName == 'mi' assert mml.childNodes[1].childNodes[2].childNodes[0].nodeValue == 'a' del mml def test_presentation_mathml_greek(): mml = mpp._print(Symbol('alpha')) assert mml.nodeName == 'mi' assert mml.childNodes[0].nodeValue == '\N{GREEK SMALL LETTER ALPHA}' assert mpp.doprint(Symbol('alpha')) == '<mi>&#945;</mi>' assert mpp.doprint(Symbol('beta')) == '<mi>&#946;</mi>' assert mpp.doprint(Symbol('gamma')) == '<mi>&#947;</mi>' assert mpp.doprint(Symbol('delta')) == '<mi>&#948;</mi>' assert mpp.doprint(Symbol('epsilon')) == '<mi>&#949;</mi>' assert mpp.doprint(Symbol('zeta')) == '<mi>&#950;</mi>' assert mpp.doprint(Symbol('eta')) == '<mi>&#951;</mi>' assert mpp.doprint(Symbol('theta')) == '<mi>&#952;</mi>' assert mpp.doprint(Symbol('iota')) == '<mi>&#953;</mi>' assert mpp.doprint(Symbol('kappa')) == '<mi>&#954;</mi>' assert mpp.doprint(Symbol('lambda')) == '<mi>&#955;</mi>' assert mpp.doprint(Symbol('mu')) == '<mi>&#956;</mi>' assert mpp.doprint(Symbol('nu')) == '<mi>&#957;</mi>' assert mpp.doprint(Symbol('xi')) == '<mi>&#958;</mi>' assert mpp.doprint(Symbol('omicron')) == '<mi>&#959;</mi>' assert mpp.doprint(Symbol('pi')) == '<mi>&#960;</mi>' assert mpp.doprint(Symbol('rho')) == '<mi>&#961;</mi>' assert mpp.doprint(Symbol('varsigma')) == '<mi>&#962;</mi>' assert mpp.doprint(Symbol('sigma')) == '<mi>&#963;</mi>' assert mpp.doprint(Symbol('tau')) == '<mi>&#964;</mi>' assert mpp.doprint(Symbol('upsilon')) == '<mi>&#965;</mi>' assert mpp.doprint(Symbol('phi')) == '<mi>&#966;</mi>' assert mpp.doprint(Symbol('chi')) == '<mi>&#967;</mi>' assert mpp.doprint(Symbol('psi')) == '<mi>&#968;</mi>' assert mpp.doprint(Symbol('omega')) == '<mi>&#969;</mi>' assert mpp.doprint(Symbol('Alpha')) == '<mi>&#913;</mi>' assert mpp.doprint(Symbol('Beta')) == '<mi>&#914;</mi>' assert mpp.doprint(Symbol('Gamma')) == '<mi>&#915;</mi>' assert mpp.doprint(Symbol('Delta')) == '<mi>&#916;</mi>' assert mpp.doprint(Symbol('Epsilon')) == '<mi>&#917;</mi>' assert mpp.doprint(Symbol('Zeta')) == '<mi>&#918;</mi>' assert mpp.doprint(Symbol('Eta')) == '<mi>&#919;</mi>' assert mpp.doprint(Symbol('Theta')) == '<mi>&#920;</mi>' assert mpp.doprint(Symbol('Iota')) == '<mi>&#921;</mi>' assert mpp.doprint(Symbol('Kappa')) == '<mi>&#922;</mi>' assert mpp.doprint(Symbol('Lambda')) == '<mi>&#923;</mi>' assert mpp.doprint(Symbol('Mu')) == '<mi>&#924;</mi>' assert mpp.doprint(Symbol('Nu')) == '<mi>&#925;</mi>' assert mpp.doprint(Symbol('Xi')) == '<mi>&#926;</mi>' assert mpp.doprint(Symbol('Omicron')) == '<mi>&#927;</mi>' assert mpp.doprint(Symbol('Pi')) == '<mi>&#928;</mi>' assert mpp.doprint(Symbol('Rho')) == '<mi>&#929;</mi>' assert mpp.doprint(Symbol('Sigma')) == '<mi>&#931;</mi>' assert mpp.doprint(Symbol('Tau')) == '<mi>&#932;</mi>' assert mpp.doprint(Symbol('Upsilon')) == '<mi>&#933;</mi>' assert mpp.doprint(Symbol('Phi')) == '<mi>&#934;</mi>' assert mpp.doprint(Symbol('Chi')) == '<mi>&#935;</mi>' assert mpp.doprint(Symbol('Psi')) == '<mi>&#936;</mi>' assert mpp.doprint(Symbol('Omega')) == '<mi>&#937;</mi>' def test_presentation_mathml_order(): expr = x**3 + x**2*y + 3*x*y**3 + y**4 mp = MathMLPresentationPrinter({'order': 'lex'}) mml = mp._print(expr) assert mml.childNodes[0].nodeName == 'msup' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '3' assert mml.childNodes[6].nodeName == 'msup' assert mml.childNodes[6].childNodes[0].childNodes[0].nodeValue == 'y' assert mml.childNodes[6].childNodes[1].childNodes[0].nodeValue == '4' mp = MathMLPresentationPrinter({'order': 'rev-lex'}) mml = mp._print(expr) assert mml.childNodes[0].nodeName == 'msup' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'y' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '4' assert mml.childNodes[6].nodeName == 'msup' assert mml.childNodes[6].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[6].childNodes[1].childNodes[0].nodeValue == '3' def test_print_intervals(): a = Symbol('a', real=True) assert mpp.doprint(Interval(0, a)) == \ '<mrow><mfenced close="]" open="["><mn>0</mn><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Interval(0, a, False, False)) == \ '<mrow><mfenced close="]" open="["><mn>0</mn><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Interval(0, a, True, False)) == \ '<mrow><mfenced close="]" open="("><mn>0</mn><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Interval(0, a, False, True)) == \ '<mrow><mfenced close=")" open="["><mn>0</mn><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Interval(0, a, True, True)) == \ '<mrow><mfenced close=")" open="("><mn>0</mn><mi>a</mi></mfenced></mrow>' def test_print_tuples(): assert mpp.doprint(Tuple(0,)) == \ '<mrow><mfenced><mn>0</mn></mfenced></mrow>' assert mpp.doprint(Tuple(0, a)) == \ '<mrow><mfenced><mn>0</mn><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Tuple(0, a, a)) == \ '<mrow><mfenced><mn>0</mn><mi>a</mi><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Tuple(0, 1, 2, 3, 4)) == \ '<mrow><mfenced><mn>0</mn><mn>1</mn><mn>2</mn><mn>3</mn><mn>4</mn></mfenced></mrow>' assert mpp.doprint(Tuple(0, 1, Tuple(2, 3, 4))) == \ '<mrow><mfenced><mn>0</mn><mn>1</mn><mrow><mfenced><mn>2</mn><mn>3'\ '</mn><mn>4</mn></mfenced></mrow></mfenced></mrow>' def test_print_re_im(): assert mpp.doprint(re(x)) == \ '<mrow><mi mathvariant="fraktur">R</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(im(x)) == \ '<mrow><mi mathvariant="fraktur">I</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(re(x + 1)) == \ '<mrow><mrow><mi mathvariant="fraktur">R</mi><mfenced><mi>x</mi>'\ '</mfenced></mrow><mo>+</mo><mn>1</mn></mrow>' assert mpp.doprint(im(x + 1)) == \ '<mrow><mi mathvariant="fraktur">I</mi><mfenced><mi>x</mi></mfenced></mrow>' def test_print_Abs(): assert mpp.doprint(Abs(x)) == \ '<mrow><mfenced close="|" open="|"><mi>x</mi></mfenced></mrow>' assert mpp.doprint(Abs(x + 1)) == \ '<mrow><mfenced close="|" open="|"><mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow></mfenced></mrow>' def test_print_Determinant(): assert mpp.doprint(Determinant(Matrix([[1, 2], [3, 4]]))) == \ '<mrow><mfenced close="|" open="|"><mfenced close="]" open="["><mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd></mtr><mtr><mtd><mn>3</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable></mfenced></mfenced></mrow>' def test_presentation_settings(): raises(TypeError, lambda: mathml(x, printer='presentation', method="garbage")) def test_toprettyxml_hooking(): # test that the patch doesn't influence the behavior of the standard # library import xml.dom.minidom doc1 = xml.dom.minidom.parseString( "<apply><plus/><ci>x</ci><cn>1</cn></apply>") doc2 = xml.dom.minidom.parseString( "<mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow>") prettyxml_old1 = doc1.toprettyxml() prettyxml_old2 = doc2.toprettyxml() mp.apply_patch() mp.restore_patch() assert prettyxml_old1 == doc1.toprettyxml() assert prettyxml_old2 == doc2.toprettyxml() def test_print_domains(): from sympy import Complexes, Integers, Naturals, Naturals0, Reals assert mpp.doprint(Complexes) == '<mi mathvariant="normal">&#x2102;</mi>' assert mpp.doprint(Integers) == '<mi mathvariant="normal">&#x2124;</mi>' assert mpp.doprint(Naturals) == '<mi mathvariant="normal">&#x2115;</mi>' assert mpp.doprint(Naturals0) == \ '<msub><mi mathvariant="normal">&#x2115;</mi><mn>0</mn></msub>' assert mpp.doprint(Reals) == '<mi mathvariant="normal">&#x211D;</mi>' def test_print_expression_with_minus(): assert mpp.doprint(-x) == '<mrow><mo>-</mo><mi>x</mi></mrow>' assert mpp.doprint(-x/y) == \ '<mrow><mo>-</mo><mfrac><mi>x</mi><mi>y</mi></mfrac></mrow>' assert mpp.doprint(-Rational(1, 2)) == \ '<mrow><mo>-</mo><mfrac><mn>1</mn><mn>2</mn></mfrac></mrow>' def test_print_AssocOp(): from sympy.core.operations import AssocOp class TestAssocOp(AssocOp): identity = 0 expr = TestAssocOp(1, 2) mpp.doprint(expr) == \ '<mrow><mi>testassocop</mi><mn>2</mn><mn>1</mn></mrow>' def test_print_basic(): expr = Basic(1, 2) assert mpp.doprint(expr) == \ '<mrow><mi>basic</mi><mfenced><mn>1</mn><mn>2</mn></mfenced></mrow>' assert mp.doprint(expr) == '<basic><cn>1</cn><cn>2</cn></basic>' def test_mat_delim_print(): expr = Matrix([[1, 2], [3, 4]]) assert mathml(expr, printer='presentation', mat_delim='[') == \ '<mfenced close="]" open="["><mtable><mtr><mtd><mn>1</mn></mtd><mtd>'\ '<mn>2</mn></mtd></mtr><mtr><mtd><mn>3</mn></mtd><mtd><mn>4</mn>'\ '</mtd></mtr></mtable></mfenced>' assert mathml(expr, printer='presentation', mat_delim='(') == \ '<mfenced><mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd>'\ '</mtr><mtr><mtd><mn>3</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable></mfenced>' assert mathml(expr, printer='presentation', mat_delim='') == \ '<mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd></mtr><mtr>'\ '<mtd><mn>3</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable>' def test_ln_notation_print(): expr = log(x) assert mathml(expr, printer='presentation') == \ '<mrow><mi>log</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(expr, printer='presentation', ln_notation=False) == \ '<mrow><mi>log</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(expr, printer='presentation', ln_notation=True) == \ '<mrow><mi>ln</mi><mfenced><mi>x</mi></mfenced></mrow>' def test_mul_symbol_print(): expr = x * y assert mathml(expr, printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mi>y</mi></mrow>' assert mathml(expr, printer='presentation', mul_symbol=None) == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mi>y</mi></mrow>' assert mathml(expr, printer='presentation', mul_symbol='dot') == \ '<mrow><mi>x</mi><mo>&#xB7;</mo><mi>y</mi></mrow>' assert mathml(expr, printer='presentation', mul_symbol='ldot') == \ '<mrow><mi>x</mi><mo>&#x2024;</mo><mi>y</mi></mrow>' assert mathml(expr, printer='presentation', mul_symbol='times') == \ '<mrow><mi>x</mi><mo>&#xD7;</mo><mi>y</mi></mrow>' def test_print_lerchphi(): assert mpp.doprint(lerchphi(1, 2, 3)) == \ '<mrow><mi>&#x3A6;</mi><mfenced><mn>1</mn><mn>2</mn><mn>3</mn></mfenced></mrow>' def test_print_polylog(): assert mp.doprint(polylog(x, y)) == \ '<apply><polylog/><ci>x</ci><ci>y</ci></apply>' assert mpp.doprint(polylog(x, y)) == \ '<mrow><msub><mi>Li</mi><mi>x</mi></msub><mfenced><mi>y</mi></mfenced></mrow>' def test_print_set_frozenset(): f = frozenset({1, 5, 3}) assert mpp.doprint(f) == \ '<mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mn>5</mn></mfenced>' s = set({1, 2, 3}) assert mpp.doprint(s) == \ '<mfenced close="}" open="{"><mn>1</mn><mn>2</mn><mn>3</mn></mfenced>' def test_print_FiniteSet(): f1 = FiniteSet(x, 1, 3) assert mpp.doprint(f1) == \ '<mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi></mfenced>' def test_print_LambertW(): assert mpp.doprint(LambertW(x)) == '<mrow><mi>W</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(LambertW(x, y)) == '<mrow><mi>W</mi><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' def test_print_EmptySet(): assert mpp.doprint(EmptySet()) == '<mo>&#x2205;</mo>' def test_print_UniversalSet(): assert mpp.doprint(S.UniversalSet) == '<mo>&#x1D54C;</mo>' def test_print_spaces(): assert mpp.doprint(HilbertSpace()) == '<mi>&#x210B;</mi>' assert mpp.doprint(ComplexSpace(2)) == '<msup>&#x1D49E;<mn>2</mn></msup>' assert mpp.doprint(FockSpace()) == '<mi>&#x2131;</mi>' def test_print_constants(): assert mpp.doprint(hbar) == '<mi>&#x210F;</mi>' assert mpp.doprint(TribonacciConstant) == '<mi>TribonacciConstant</mi>' assert mpp.doprint(EulerGamma) == '<mi>&#x3B3;</mi>' def test_print_Contains(): assert mpp.doprint(Contains(x, S.Naturals)) == \ '<mrow><mi>x</mi><mo>&#x2208;</mo><mi mathvariant="normal">&#x2115;</mi></mrow>' def test_print_Dagger(): assert mpp.doprint(Dagger(x)) == '<msup><mi>x</mi>&#x2020;</msup>' def test_print_SetOp(): f1 = FiniteSet(x, 1, 3) f2 = FiniteSet(y, 2, 4) prntr = lambda x: mathml(x, printer='presentation') assert prntr(Union(f1, f2, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi>'\ '</mfenced><mo>&#x222A;</mo><mfenced close="}" open="{"><mn>2</mn>'\ '<mn>4</mn><mi>y</mi></mfenced></mrow>' assert prntr(Intersection(f1, f2, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi>'\ '</mfenced><mo>&#x2229;</mo><mfenced close="}" open="{"><mn>2</mn>'\ '<mn>4</mn><mi>y</mi></mfenced></mrow>' assert prntr(Complement(f1, f2, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi>'\ '</mfenced><mo>&#x2216;</mo><mfenced close="}" open="{"><mn>2</mn>'\ '<mn>4</mn><mi>y</mi></mfenced></mrow>' assert prntr(SymmetricDifference(f1, f2, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi>'\ '</mfenced><mo>&#x2206;</mo><mfenced close="}" open="{"><mn>2</mn>'\ '<mn>4</mn><mi>y</mi></mfenced></mrow>' A = FiniteSet(a) C = FiniteSet(c) D = FiniteSet(d) U1 = Union(C, D, evaluate=False) I1 = Intersection(C, D, evaluate=False) C1 = Complement(C, D, evaluate=False) D1 = SymmetricDifference(C, D, evaluate=False) # XXX ProductSet does not support evaluate keyword P1 = ProductSet(C, D) assert prntr(Union(A, I1, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mi>a</mi></mfenced>' \ '<mo>&#x222A;</mo><mfenced><mrow><mfenced close="}" open="{">' \ '<mi>c</mi></mfenced><mo>&#x2229;</mo><mfenced close="}" open="{">' \ '<mi>d</mi></mfenced></mrow></mfenced></mrow>' assert prntr(Intersection(A, C1, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mi>a</mi></mfenced>' \ '<mo>&#x2229;</mo><mfenced><mrow><mfenced close="}" open="{">' \ '<mi>c</mi></mfenced><mo>&#x2216;</mo><mfenced close="}" open="{">' \ '<mi>d</mi></mfenced></mrow></mfenced></mrow>' assert prntr(Complement(A, D1, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mi>a</mi></mfenced>' \ '<mo>&#x2216;</mo><mfenced><mrow><mfenced close="}" open="{">' \ '<mi>c</mi></mfenced><mo>&#x2206;</mo><mfenced close="}" open="{">' \ '<mi>d</mi></mfenced></mrow></mfenced></mrow>' assert prntr(SymmetricDifference(A, P1, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mi>a</mi></mfenced>' \ '<mo>&#x2206;</mo><mfenced><mrow><mfenced close="}" open="{">' \ '<mi>c</mi></mfenced><mo>&#x00d7;</mo><mfenced close="}" open="{">' \ '<mi>d</mi></mfenced></mrow></mfenced></mrow>' assert prntr(ProductSet(A, U1)) == \ '<mrow><mfenced close="}" open="{"><mi>a</mi></mfenced>' \ '<mo>&#x00d7;</mo><mfenced><mrow><mfenced close="}" open="{">' \ '<mi>c</mi></mfenced><mo>&#x222A;</mo><mfenced close="}" open="{">' \ '<mi>d</mi></mfenced></mrow></mfenced></mrow>' def test_print_logic(): assert mpp.doprint(And(x, y)) == \ '<mrow><mi>x</mi><mo>&#x2227;</mo><mi>y</mi></mrow>' assert mpp.doprint(Or(x, y)) == \ '<mrow><mi>x</mi><mo>&#x2228;</mo><mi>y</mi></mrow>' assert mpp.doprint(Xor(x, y)) == \ '<mrow><mi>x</mi><mo>&#x22BB;</mo><mi>y</mi></mrow>' assert mpp.doprint(Implies(x, y)) == \ '<mrow><mi>x</mi><mo>&#x21D2;</mo><mi>y</mi></mrow>' assert mpp.doprint(Equivalent(x, y)) == \ '<mrow><mi>x</mi><mo>&#x21D4;</mo><mi>y</mi></mrow>' assert mpp.doprint(And(Eq(x, y), x > 4)) == \ '<mrow><mrow><mi>x</mi><mo>=</mo><mi>y</mi></mrow><mo>&#x2227;</mo>'\ '<mrow><mi>x</mi><mo>></mo><mn>4</mn></mrow></mrow>' assert mpp.doprint(And(Eq(x, 3), y < 3, x > y + 1)) == \ '<mrow><mrow><mi>x</mi><mo>=</mo><mn>3</mn></mrow><mo>&#x2227;</mo>'\ '<mrow><mi>x</mi><mo>></mo><mrow><mi>y</mi><mo>+</mo><mn>1</mn></mrow>'\ '</mrow><mo>&#x2227;</mo><mrow><mi>y</mi><mo><</mo><mn>3</mn></mrow></mrow>' assert mpp.doprint(Or(Eq(x, y), x > 4)) == \ '<mrow><mrow><mi>x</mi><mo>=</mo><mi>y</mi></mrow><mo>&#x2228;</mo>'\ '<mrow><mi>x</mi><mo>></mo><mn>4</mn></mrow></mrow>' assert mpp.doprint(And(Eq(x, 3), Or(y < 3, x > y + 1))) == \ '<mrow><mrow><mi>x</mi><mo>=</mo><mn>3</mn></mrow><mo>&#x2227;</mo>'\ '<mfenced><mrow><mrow><mi>x</mi><mo>></mo><mrow><mi>y</mi><mo>+</mo>'\ '<mn>1</mn></mrow></mrow><mo>&#x2228;</mo><mrow><mi>y</mi><mo><</mo>'\ '<mn>3</mn></mrow></mrow></mfenced></mrow>' assert mpp.doprint(Not(x)) == '<mrow><mo>&#xAC;</mo><mi>x</mi></mrow>' assert mpp.doprint(Not(And(x, y))) == \ '<mrow><mo>&#xAC;</mo><mfenced><mrow><mi>x</mi><mo>&#x2227;</mo>'\ '<mi>y</mi></mrow></mfenced></mrow>' def test_root_notation_print(): assert mathml(x**(S.One/3), printer='presentation') == \ '<mroot><mi>x</mi><mn>3</mn></mroot>' assert mathml(x**(S.One/3), printer='presentation', root_notation=False) ==\ '<msup><mi>x</mi><mfrac><mn>1</mn><mn>3</mn></mfrac></msup>' assert mathml(x**(S.One/3), printer='content') == \ '<apply><root/><degree><ci>3</ci></degree><ci>x</ci></apply>' assert mathml(x**(S.One/3), printer='content', root_notation=False) == \ '<apply><power/><ci>x</ci><apply><divide/><cn>1</cn><cn>3</cn></apply></apply>' assert mathml(x**(Rational(-1, 3)), printer='presentation') == \ '<mfrac><mn>1</mn><mroot><mi>x</mi><mn>3</mn></mroot></mfrac>' assert mathml(x**(Rational(-1, 3)), printer='presentation', root_notation=False) \ == '<mfrac><mn>1</mn><msup><mi>x</mi><mfrac><mn>1</mn><mn>3</mn></mfrac></msup></mfrac>' def test_fold_frac_powers_print(): expr = x ** Rational(5, 2) assert mathml(expr, printer='presentation') == \ '<msup><mi>x</mi><mfrac><mn>5</mn><mn>2</mn></mfrac></msup>' assert mathml(expr, printer='presentation', fold_frac_powers=True) == \ '<msup><mi>x</mi><mfrac bevelled="true"><mn>5</mn><mn>2</mn></mfrac></msup>' assert mathml(expr, printer='presentation', fold_frac_powers=False) == \ '<msup><mi>x</mi><mfrac><mn>5</mn><mn>2</mn></mfrac></msup>' def test_fold_short_frac_print(): expr = Rational(2, 5) assert mathml(expr, printer='presentation') == \ '<mfrac><mn>2</mn><mn>5</mn></mfrac>' assert mathml(expr, printer='presentation', fold_short_frac=True) == \ '<mfrac bevelled="true"><mn>2</mn><mn>5</mn></mfrac>' assert mathml(expr, printer='presentation', fold_short_frac=False) == \ '<mfrac><mn>2</mn><mn>5</mn></mfrac>' def test_print_factorials(): assert mpp.doprint(factorial(x)) == '<mrow><mi>x</mi><mo>!</mo></mrow>' assert mpp.doprint(factorial(x + 1)) == \ '<mrow><mfenced><mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow></mfenced><mo>!</mo></mrow>' assert mpp.doprint(factorial2(x)) == '<mrow><mi>x</mi><mo>!!</mo></mrow>' assert mpp.doprint(factorial2(x + 1)) == \ '<mrow><mfenced><mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow></mfenced><mo>!!</mo></mrow>' assert mpp.doprint(binomial(x, y)) == \ '<mfenced><mfrac linethickness="0"><mi>x</mi><mi>y</mi></mfrac></mfenced>' assert mpp.doprint(binomial(4, x + y)) == \ '<mfenced><mfrac linethickness="0"><mn>4</mn><mrow><mi>x</mi>'\ '<mo>+</mo><mi>y</mi></mrow></mfrac></mfenced>' def test_print_floor(): expr = floor(x) assert mathml(expr, printer='presentation') == \ '<mrow><mfenced close="&#8971;" open="&#8970;"><mi>x</mi></mfenced></mrow>' def test_print_ceiling(): expr = ceiling(x) assert mathml(expr, printer='presentation') == \ '<mrow><mfenced close="&#8969;" open="&#8968;"><mi>x</mi></mfenced></mrow>' def test_print_Lambda(): expr = Lambda(x, x+1) assert mathml(expr, printer='presentation') == \ '<mfenced><mrow><mi>x</mi><mo>&#x21A6;</mo><mrow><mi>x</mi><mo>+</mo>'\ '<mn>1</mn></mrow></mrow></mfenced>' expr = Lambda((x, y), x + y) assert mathml(expr, printer='presentation') == \ '<mfenced><mrow><mrow><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>'\ '<mo>&#x21A6;</mo><mrow><mi>x</mi><mo>+</mo><mi>y</mi></mrow></mrow></mfenced>' def test_print_conjugate(): assert mpp.doprint(conjugate(x)) == \ '<menclose notation="top"><mi>x</mi></menclose>' assert mpp.doprint(conjugate(x + 1)) == \ '<mrow><menclose notation="top"><mi>x</mi></menclose><mo>+</mo><mn>1</mn></mrow>' def test_print_AccumBounds(): a = Symbol('a', real=True) assert mpp.doprint(AccumBounds(0, 1)) == '<mfenced close="&#10217;" open="&#10216;"><mn>0</mn><mn>1</mn></mfenced>' assert mpp.doprint(AccumBounds(0, a)) == '<mfenced close="&#10217;" open="&#10216;"><mn>0</mn><mi>a</mi></mfenced>' assert mpp.doprint(AccumBounds(a + 1, a + 2)) == '<mfenced close="&#10217;" open="&#10216;"><mrow><mi>a</mi><mo>+</mo><mn>1</mn></mrow><mrow><mi>a</mi><mo>+</mo><mn>2</mn></mrow></mfenced>' def test_print_Float(): assert mpp.doprint(Float(1e100)) == '<mrow><mn>1.0</mn><mo>&#xB7;</mo><msup><mn>10</mn><mn>100</mn></msup></mrow>' assert mpp.doprint(Float(1e-100)) == '<mrow><mn>1.0</mn><mo>&#xB7;</mo><msup><mn>10</mn><mn>-100</mn></msup></mrow>' assert mpp.doprint(Float(-1e100)) == '<mrow><mn>-1.0</mn><mo>&#xB7;</mo><msup><mn>10</mn><mn>100</mn></msup></mrow>' assert mpp.doprint(Float(1.0*oo)) == '<mi>&#x221E;</mi>' assert mpp.doprint(Float(-1.0*oo)) == '<mrow><mo>-</mo><mi>&#x221E;</mi></mrow>' def test_print_different_functions(): assert mpp.doprint(gamma(x)) == '<mrow><mi>&#x393;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(lowergamma(x, y)) == '<mrow><mi>&#x3B3;</mi><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mpp.doprint(uppergamma(x, y)) == '<mrow><mi>&#x393;</mi><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mpp.doprint(zeta(x)) == '<mrow><mi>&#x3B6;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(zeta(x, y)) == '<mrow><mi>&#x3B6;</mi><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mpp.doprint(dirichlet_eta(x)) == '<mrow><mi>&#x3B7;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(elliptic_k(x)) == '<mrow><mi>&#x39A;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(totient(x)) == '<mrow><mi>&#x3D5;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(reduced_totient(x)) == '<mrow><mi>&#x3BB;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(primenu(x)) == '<mrow><mi>&#x3BD;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(primeomega(x)) == '<mrow><mi>&#x3A9;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(fresnels(x)) == '<mrow><mi>S</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(fresnelc(x)) == '<mrow><mi>C</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(Heaviside(x)) == '<mrow><mi>&#x398;</mi><mfenced><mi>x</mi></mfenced></mrow>' def test_mathml_builtins(): assert mpp.doprint(None) == '<mi>None</mi>' assert mpp.doprint(true) == '<mi>True</mi>' assert mpp.doprint(false) == '<mi>False</mi>' def test_mathml_Range(): assert mpp.doprint(Range(1, 51)) == \ '<mfenced close="}" open="{"><mn>1</mn><mn>2</mn><mi>&#8230;</mi><mn>50</mn></mfenced>' assert mpp.doprint(Range(1, 4)) == \ '<mfenced close="}" open="{"><mn>1</mn><mn>2</mn><mn>3</mn></mfenced>' assert mpp.doprint(Range(0, 3, 1)) == \ '<mfenced close="}" open="{"><mn>0</mn><mn>1</mn><mn>2</mn></mfenced>' assert mpp.doprint(Range(0, 30, 1)) == \ '<mfenced close="}" open="{"><mn>0</mn><mn>1</mn><mi>&#8230;</mi><mn>29</mn></mfenced>' assert mpp.doprint(Range(30, 1, -1)) == \ '<mfenced close="}" open="{"><mn>30</mn><mn>29</mn><mi>&#8230;</mi>'\ '<mn>2</mn></mfenced>' assert mpp.doprint(Range(0, oo, 2)) == \ '<mfenced close="}" open="{"><mn>0</mn><mn>2</mn><mi>&#8230;</mi></mfenced>' assert mpp.doprint(Range(oo, -2, -2)) == \ '<mfenced close="}" open="{"><mi>&#8230;</mi><mn>2</mn><mn>0</mn></mfenced>' assert mpp.doprint(Range(-2, -oo, -1)) == \ '<mfenced close="}" open="{"><mn>-2</mn><mn>-3</mn><mi>&#8230;</mi></mfenced>' def test_print_exp(): assert mpp.doprint(exp(x)) == \ '<msup><mi>&ExponentialE;</mi><mi>x</mi></msup>' assert mpp.doprint(exp(1) + exp(2)) == \ '<mrow><mi>&ExponentialE;</mi><mo>+</mo><msup><mi>&ExponentialE;</mi><mn>2</mn></msup></mrow>' def test_print_MinMax(): assert mpp.doprint(Min(x, y)) == \ '<mrow><mo>min</mo><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mpp.doprint(Min(x, 2, x**3)) == \ '<mrow><mo>min</mo><mfenced><mn>2</mn><mi>x</mi><msup><mi>x</mi>'\ '<mn>3</mn></msup></mfenced></mrow>' assert mpp.doprint(Max(x, y)) == \ '<mrow><mo>max</mo><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mpp.doprint(Max(x, 2, x**3)) == \ '<mrow><mo>max</mo><mfenced><mn>2</mn><mi>x</mi><msup><mi>x</mi>'\ '<mn>3</mn></msup></mfenced></mrow>' def test_mathml_presentation_numbers(): n = Symbol('n') assert mathml(catalan(n), printer='presentation') == \ '<msub><mi>C</mi><mi>n</mi></msub>' assert mathml(bernoulli(n), printer='presentation') == \ '<msub><mi>B</mi><mi>n</mi></msub>' assert mathml(bell(n), printer='presentation') == \ '<msub><mi>B</mi><mi>n</mi></msub>' assert mathml(euler(n), printer='presentation') == \ '<msub><mi>E</mi><mi>n</mi></msub>' assert mathml(fibonacci(n), printer='presentation') == \ '<msub><mi>F</mi><mi>n</mi></msub>' assert mathml(lucas(n), printer='presentation') == \ '<msub><mi>L</mi><mi>n</mi></msub>' assert mathml(tribonacci(n), printer='presentation') == \ '<msub><mi>T</mi><mi>n</mi></msub>' assert mathml(bernoulli(n, x), printer='presentation') == \ '<mrow><msub><mi>B</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(bell(n, x), printer='presentation') == \ '<mrow><msub><mi>B</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(euler(n, x), printer='presentation') == \ '<mrow><msub><mi>E</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(fibonacci(n, x), printer='presentation') == \ '<mrow><msub><mi>F</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(tribonacci(n, x), printer='presentation') == \ '<mrow><msub><mi>T</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_mathml_presentation_mathieu(): assert mathml(mathieuc(x, y, z), printer='presentation') == \ '<mrow><mi>C</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>' assert mathml(mathieus(x, y, z), printer='presentation') == \ '<mrow><mi>S</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>' assert mathml(mathieucprime(x, y, z), printer='presentation') == \ '<mrow><mi>C&#x2032;</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>' assert mathml(mathieusprime(x, y, z), printer='presentation') == \ '<mrow><mi>S&#x2032;</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>' def test_mathml_presentation_stieltjes(): assert mathml(stieltjes(n), printer='presentation') == \ '<msub><mi>&#x03B3;</mi><mi>n</mi></msub>' assert mathml(stieltjes(n, x), printer='presentation') == \ '<mrow><msub><mi>&#x03B3;</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_print_matrix_symbol(): A = MatrixSymbol('A', 1, 2) assert mpp.doprint(A) == '<mi>A</mi>' assert mp.doprint(A) == '<ci>A</ci>' assert mathml(A, printer='presentation', mat_symbol_style="bold") == \ '<mi mathvariant="bold">A</mi>' # No effect in content printer assert mathml(A, mat_symbol_style="bold") == '<ci>A</ci>' def test_print_hadamard(): from sympy.matrices.expressions import HadamardProduct from sympy.matrices.expressions import Transpose X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert mathml(HadamardProduct(X, Y*Y), printer="presentation") == \ '<mrow>' \ '<mi>X</mi>' \ '<mo>&#x2218;</mo>' \ '<msup><mi>Y</mi><mn>2</mn></msup>' \ '</mrow>' assert mathml(HadamardProduct(X, Y)*Y, printer="presentation") == \ '<mrow>' \ '<mfenced>' \ '<mrow><mi>X</mi><mo>&#x2218;</mo><mi>Y</mi></mrow>' \ '</mfenced>' \ '<mo>&InvisibleTimes;</mo><mi>Y</mi>' \ '</mrow>' assert mathml(HadamardProduct(X, Y, Y), printer="presentation") == \ '<mrow>' \ '<mi>X</mi><mo>&#x2218;</mo>' \ '<mi>Y</mi><mo>&#x2218;</mo>' \ '<mi>Y</mi>' \ '</mrow>' assert mathml( Transpose(HadamardProduct(X, Y)), printer="presentation") == \ '<msup>' \ '<mfenced>' \ '<mrow><mi>X</mi><mo>&#x2218;</mo><mi>Y</mi></mrow>' \ '</mfenced>' \ '<mo>T</mo>' \ '</msup>' def test_print_random_symbol(): R = RandomSymbol(Symbol('R')) assert mpp.doprint(R) == '<mi>R</mi>' assert mp.doprint(R) == '<ci>R</ci>' def test_print_IndexedBase(): assert mathml(IndexedBase(a)[b], printer='presentation') == \ '<msub><mi>a</mi><mi>b</mi></msub>' assert mathml(IndexedBase(a)[b, c, d], printer='presentation') == \ '<msub><mi>a</mi><mfenced><mi>b</mi><mi>c</mi><mi>d</mi></mfenced></msub>' assert mathml(IndexedBase(a)[b]*IndexedBase(c)[d]*IndexedBase(e), printer='presentation') == \ '<mrow><msub><mi>a</mi><mi>b</mi></msub><mo>&InvisibleTimes;'\ '</mo><msub><mi>c</mi><mi>d</mi></msub><mo>&InvisibleTimes;</mo><mi>e</mi></mrow>' def test_print_Indexed(): assert mathml(IndexedBase(a), printer='presentation') == '<mi>a</mi>' assert mathml(IndexedBase(a/b), printer='presentation') == \ '<mrow><mfrac><mi>a</mi><mi>b</mi></mfrac></mrow>' assert mathml(IndexedBase((a, b)), printer='presentation') == \ '<mrow><mfenced><mi>a</mi><mi>b</mi></mfenced></mrow>' def test_print_MatrixElement(): i, j = symbols('i j') A = MatrixSymbol('A', i, j) assert mathml(A[0,0],printer = 'presentation') == \ '<msub><mi>A</mi><mfenced close="" open=""><mn>0</mn><mn>0</mn></mfenced></msub>' assert mathml(A[i,j], printer = 'presentation') == \ '<msub><mi>A</mi><mfenced close="" open=""><mi>i</mi><mi>j</mi></mfenced></msub>' assert mathml(A[i*j,0], printer = 'presentation') == \ '<msub><mi>A</mi><mfenced close="" open=""><mrow><mi>i</mi><mo>&InvisibleTimes;</mo><mi>j</mi></mrow><mn>0</mn></mfenced></msub>' def test_print_Vector(): ACS = CoordSys3D('A') assert mathml(Cross(ACS.i, ACS.j*ACS.x*3 + ACS.k), printer='presentation') == \ '<mrow><msub><mover><mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xD7;</mo><mfenced><mrow>'\ '<mfenced><mrow><mn>3</mn><mo>&InvisibleTimes;</mo><msub>'\ '<mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi></msub>'\ '</mrow></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>+</mo><msub><mover>'\ '<mi mathvariant="bold">k</mi><mo>^</mo></mover><mi mathvariant="bold">'\ 'A</mi></msub></mrow></mfenced></mrow>' assert mathml(Cross(ACS.i, ACS.j), printer='presentation') == \ '<mrow><msub><mover><mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xD7;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow>' assert mathml(x*Cross(ACS.i, ACS.j), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><msub><mover>'\ '<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xD7;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Cross(x*ACS.i, ACS.j), printer='presentation') == \ '<mrow><mo>-</mo><mrow><msub><mover><mi mathvariant="bold">j</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub>'\ '<mo>&#xD7;</mo><mfenced><mrow><mfenced><mi>x</mi></mfenced>'\ '<mo>&InvisibleTimes;</mo><msub><mover><mi mathvariant="bold">i</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow>'\ '</mfenced></mrow></mrow>' assert mathml(Curl(3*ACS.x*ACS.j), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mo>&#xD7;</mo><mfenced><mrow><mfenced><mrow>'\ '<mn>3</mn><mo>&InvisibleTimes;</mo><msub>'\ '<mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi></msub>'\ '</mrow></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Curl(3*x*ACS.x*ACS.j), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mo>&#xD7;</mo><mfenced><mrow><mfenced><mrow>'\ '<mn>3</mn><mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">x'\ '</mi><mi mathvariant="bold">A</mi></msub><mo>&InvisibleTimes;</mo>'\ '<mi>x</mi></mrow></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(x*Curl(3*ACS.x*ACS.j), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><mo>&#x2207;</mo>'\ '<mo>&#xD7;</mo><mfenced><mrow><mfenced><mrow><mn>3</mn>'\ '<mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">x</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced>'\ '<mo>&InvisibleTimes;</mo><msub><mover><mi mathvariant="bold">j</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow>'\ '</mfenced></mrow></mfenced></mrow>' assert mathml(Curl(3*x*ACS.x*ACS.j + ACS.i), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mo>&#xD7;</mo><mfenced><mrow><msub><mover>'\ '<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>+</mo><mfenced><mrow>'\ '<mn>3</mn><mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">x'\ '</mi><mi mathvariant="bold">A</mi></msub><mo>&InvisibleTimes;</mo>'\ '<mi>x</mi></mrow></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Divergence(3*ACS.x*ACS.j), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mo>&#xB7;</mo><mfenced><mrow><mfenced><mrow>'\ '<mn>3</mn><mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">x'\ '</mi><mi mathvariant="bold">A</mi></msub></mrow></mfenced>'\ '<mo>&InvisibleTimes;</mo><msub><mover><mi mathvariant="bold">j</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(x*Divergence(3*ACS.x*ACS.j), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><mo>&#x2207;</mo>'\ '<mo>&#xB7;</mo><mfenced><mrow><mfenced><mrow><mn>3</mn>'\ '<mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">x</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced>'\ '<mo>&InvisibleTimes;</mo><msub><mover><mi mathvariant="bold">j</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow>'\ '</mfenced></mrow></mfenced></mrow>' assert mathml(Divergence(3*x*ACS.x*ACS.j + ACS.i), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mo>&#xB7;</mo><mfenced><mrow><msub><mover>'\ '<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>+</mo><mfenced><mrow>'\ '<mn>3</mn><mo>&InvisibleTimes;</mo><msub>'\ '<mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi></msub>'\ '<mo>&InvisibleTimes;</mo><mi>x</mi></mrow></mfenced>'\ '<mo>&InvisibleTimes;</mo><msub><mover><mi mathvariant="bold">j</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Dot(ACS.i, ACS.j*ACS.x*3+ACS.k), printer='presentation') == \ '<mrow><msub><mover><mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xB7;</mo><mfenced><mrow>'\ '<mfenced><mrow><mn>3</mn><mo>&InvisibleTimes;</mo><msub>'\ '<mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi></msub>'\ '</mrow></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>+</mo><msub><mover>'\ '<mi mathvariant="bold">k</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Dot(ACS.i, ACS.j), printer='presentation') == \ '<mrow><msub><mover><mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xB7;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow>' assert mathml(Dot(x*ACS.i, ACS.j), printer='presentation') == \ '<mrow><msub><mover><mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xB7;</mo><mfenced><mrow>'\ '<mfenced><mi>x</mi></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(x*Dot(ACS.i, ACS.j), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><msub><mover>'\ '<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xB7;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Gradient(ACS.x), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><msub><mi mathvariant="bold">x</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow>' assert mathml(Gradient(ACS.x + 3*ACS.y), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mfenced><mrow><msub><mi mathvariant="bold">'\ 'x</mi><mi mathvariant="bold">A</mi></msub><mo>+</mo><mrow><mn>3</mn>'\ '<mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">y</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mrow></mfenced></mrow>' assert mathml(x*Gradient(ACS.x), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><mo>&#x2207;</mo>'\ '<msub><mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi>'\ '</msub></mrow></mfenced></mrow>' assert mathml(Gradient(x*ACS.x), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mfenced><mrow><msub><mi mathvariant="bold">'\ 'x</mi><mi mathvariant="bold">A</mi></msub><mo>&InvisibleTimes;</mo>'\ '<mi>x</mi></mrow></mfenced></mrow>' assert mathml(Cross(ACS.x, ACS.z) + Cross(ACS.z, ACS.x), printer='presentation') == \ '<mover><mi mathvariant="bold">0</mi><mo>^</mo></mover>' assert mathml(Cross(ACS.z, ACS.x), printer='presentation') == \ '<mrow><mo>-</mo><mrow><msub><mi mathvariant="bold">x</mi>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xD7;</mo><msub>'\ '<mi mathvariant="bold">z</mi><mi mathvariant="bold">A</mi></msub></mrow></mrow>' assert mathml(Laplacian(ACS.x), printer='presentation') == \ '<mrow><mo>&#x2206;</mo><msub><mi mathvariant="bold">x</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow>' assert mathml(Laplacian(ACS.x + 3*ACS.y), printer='presentation') == \ '<mrow><mo>&#x2206;</mo><mfenced><mrow><msub><mi mathvariant="bold">'\ 'x</mi><mi mathvariant="bold">A</mi></msub><mo>+</mo><mrow><mn>3</mn>'\ '<mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">y</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mrow></mfenced></mrow>' assert mathml(x*Laplacian(ACS.x), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><mo>&#x2206;</mo>'\ '<msub><mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi>'\ '</msub></mrow></mfenced></mrow>' assert mathml(Laplacian(x*ACS.x), printer='presentation') == \ '<mrow><mo>&#x2206;</mo><mfenced><mrow><msub><mi mathvariant="bold">'\ 'x</mi><mi mathvariant="bold">A</mi></msub><mo>&InvisibleTimes;</mo>'\ '<mi>x</mi></mrow></mfenced></mrow>' def test_print_elliptic_f(): assert mathml(elliptic_f(x, y), printer = 'presentation') == \ '<mrow><mi>&#x1d5a5;</mi><mfenced separators="|"><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mathml(elliptic_f(x/y, y), printer = 'presentation') == \ '<mrow><mi>&#x1d5a5;</mi><mfenced separators="|"><mrow><mfrac><mi>x</mi><mi>y</mi></mfrac></mrow><mi>y</mi></mfenced></mrow>' def test_print_elliptic_e(): assert mathml(elliptic_e(x), printer = 'presentation') == \ '<mrow><mi>&#x1d5a4;</mi><mfenced separators="|"><mi>x</mi></mfenced></mrow>' assert mathml(elliptic_e(x, y), printer = 'presentation') == \ '<mrow><mi>&#x1d5a4;</mi><mfenced separators="|"><mi>x</mi><mi>y</mi></mfenced></mrow>' def test_print_elliptic_pi(): assert mathml(elliptic_pi(x, y), printer = 'presentation') == \ '<mrow><mi>&#x1d6f1;</mi><mfenced separators="|"><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mathml(elliptic_pi(x, y, z), printer = 'presentation') == \ '<mrow><mi>&#x1d6f1;</mi><mfenced separators=";|"><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>' def test_print_Ei(): assert mathml(Ei(x), printer = 'presentation') == \ '<mrow><mi>Ei</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(Ei(x**y), printer = 'presentation') == \ '<mrow><mi>Ei</mi><mfenced><msup><mi>x</mi><mi>y</mi></msup></mfenced></mrow>' def test_print_expint(): assert mathml(expint(x, y), printer = 'presentation') == \ '<mrow><msub><mo>E</mo><mi>x</mi></msub><mfenced><mi>y</mi></mfenced></mrow>' assert mathml(expint(IndexedBase(x)[1], IndexedBase(x)[2]), printer = 'presentation') == \ '<mrow><msub><mo>E</mo><msub><mi>x</mi><mn>1</mn></msub></msub><mfenced><msub><mi>x</mi><mn>2</mn></msub></mfenced></mrow>' def test_print_jacobi(): assert mathml(jacobi(n, a, b, x), printer = 'presentation') == \ '<mrow><msubsup><mo>P</mo><mi>n</mi><mfenced><mi>a</mi><mi>b</mi></mfenced></msubsup><mfenced><mi>x</mi></mfenced></mrow>' def test_print_gegenbauer(): assert mathml(gegenbauer(n, a, x), printer = 'presentation') == \ '<mrow><msubsup><mo>C</mo><mi>n</mi><mfenced><mi>a</mi></mfenced></msubsup><mfenced><mi>x</mi></mfenced></mrow>' def test_print_chebyshevt(): assert mathml(chebyshevt(n, x), printer = 'presentation') == \ '<mrow><msub><mo>T</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_print_chebyshevu(): assert mathml(chebyshevu(n, x), printer = 'presentation') == \ '<mrow><msub><mo>U</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_print_legendre(): assert mathml(legendre(n, x), printer = 'presentation') == \ '<mrow><msub><mo>P</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_print_assoc_legendre(): assert mathml(assoc_legendre(n, a, x), printer = 'presentation') == \ '<mrow><msubsup><mo>P</mo><mi>n</mi><mfenced><mi>a</mi></mfenced></msubsup><mfenced><mi>x</mi></mfenced></mrow>' def test_print_laguerre(): assert mathml(laguerre(n, x), printer = 'presentation') == \ '<mrow><msub><mo>L</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_print_assoc_laguerre(): assert mathml(assoc_laguerre(n, a, x), printer = 'presentation') == \ '<mrow><msubsup><mo>L</mo><mi>n</mi><mfenced><mi>a</mi></mfenced></msubsup><mfenced><mi>x</mi></mfenced></mrow>' def test_print_hermite(): assert mathml(hermite(n, x), printer = 'presentation') == \ '<mrow><msub><mo>H</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_mathml_SingularityFunction(): assert mathml(SingularityFunction(x, 4, 5), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mrow><mi>x</mi>' \ '<mo>-</mo><mn>4</mn></mrow></mfenced><mn>5</mn></msup>' assert mathml(SingularityFunction(x, -3, 4), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mrow><mi>x</mi>' \ '<mo>+</mo><mn>3</mn></mrow></mfenced><mn>4</mn></msup>' assert mathml(SingularityFunction(x, 0, 4), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mi>x</mi></mfenced>' \ '<mn>4</mn></msup>' assert mathml(SingularityFunction(x, a, n), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mrow><mrow>' \ '<mo>-</mo><mi>a</mi></mrow><mo>+</mo><mi>x</mi></mrow></mfenced>' \ '<mi>n</mi></msup>' assert mathml(SingularityFunction(x, 4, -2), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mrow><mi>x</mi>' \ '<mo>-</mo><mn>4</mn></mrow></mfenced><mn>-2</mn></msup>' assert mathml(SingularityFunction(x, 4, -1), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mrow><mi>x</mi>' \ '<mo>-</mo><mn>4</mn></mrow></mfenced><mn>-1</mn></msup>' def test_mathml_matrix_functions(): from sympy.matrices import MatrixSymbol, Adjoint, Inverse, Transpose X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert mathml(Adjoint(X), printer='presentation') == \ '<msup><mi>X</mi><mo>&#x2020;</mo></msup>' assert mathml(Adjoint(X + Y), printer='presentation') == \ '<msup><mfenced><mrow><mi>X</mi><mo>+</mo><mi>Y</mi></mrow></mfenced><mo>&#x2020;</mo></msup>' assert mathml(Adjoint(X) + Adjoint(Y), printer='presentation') == \ '<mrow><msup><mi>X</mi><mo>&#x2020;</mo></msup><mo>+</mo><msup>' \ '<mi>Y</mi><mo>&#x2020;</mo></msup></mrow>' assert mathml(Adjoint(X*Y), printer='presentation') == \ '<msup><mfenced><mrow><mi>X</mi><mo>&InvisibleTimes;</mo>' \ '<mi>Y</mi></mrow></mfenced><mo>&#x2020;</mo></msup>' assert mathml(Adjoint(Y)*Adjoint(X), printer='presentation') == \ '<mrow><msup><mi>Y</mi><mo>&#x2020;</mo></msup><mo>&InvisibleTimes;' \ '</mo><msup><mi>X</mi><mo>&#x2020;</mo></msup></mrow>' assert mathml(Adjoint(X**2), printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mn>2</mn></msup></mfenced><mo>&#x2020;</mo></msup>' assert mathml(Adjoint(X)**2, printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mo>&#x2020;</mo></msup></mfenced><mn>2</mn></msup>' assert mathml(Adjoint(Inverse(X)), printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mn>-1</mn></msup></mfenced><mo>&#x2020;</mo></msup>' assert mathml(Inverse(Adjoint(X)), printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mo>&#x2020;</mo></msup></mfenced><mn>-1</mn></msup>' assert mathml(Adjoint(Transpose(X)), printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mo>T</mo></msup></mfenced><mo>&#x2020;</mo></msup>' assert mathml(Transpose(Adjoint(X)), printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mo>&#x2020;</mo></msup></mfenced><mo>T</mo></msup>' assert mathml(Transpose(Adjoint(X) + Y), printer='presentation') == \ '<msup><mfenced><mrow><msup><mi>X</mi><mo>&#x2020;</mo></msup>' \ '<mo>+</mo><mi>Y</mi></mrow></mfenced><mo>T</mo></msup>' assert mathml(Transpose(X), printer='presentation') == \ '<msup><mi>X</mi><mo>T</mo></msup>' assert mathml(Transpose(X + Y), printer='presentation') == \ '<msup><mfenced><mrow><mi>X</mi><mo>+</mo><mi>Y</mi></mrow></mfenced><mo>T</mo></msup>' def test_mathml_special_matrices(): from sympy.matrices import Identity, ZeroMatrix, OneMatrix assert mathml(Identity(4), printer='presentation') == '<mi>&#x1D540;</mi>' assert mathml(ZeroMatrix(2, 2), printer='presentation') == '<mn>&#x1D7D8</mn>' assert mathml(OneMatrix(2, 2), printer='presentation') == '<mn>&#x1D7D9</mn>' def test_mathml_piecewise(): from sympy import Piecewise # Content MathML assert mathml(Piecewise((x, x <= 1), (x**2, True))) == \ '<piecewise><piece><ci>x</ci><apply><leq/><ci>x</ci><cn>1</cn></apply></piece><otherwise><apply><power/><ci>x</ci><cn>2</cn></apply></otherwise></piecewise>' raises(ValueError, lambda: mathml(Piecewise((x, x <= 1)))) def test_issue_17857(): assert mathml(Range(-oo, oo), printer='presentation') == \ '<mfenced close="}" open="{"><mi>&#8230;</mi><mn>-1</mn><mn>0</mn><mn>1</mn><mi>&#8230;</mi></mfenced>' assert mathml(Range(oo, -oo, -1), printer='presentation') == \ '<mfenced close="}" open="{"><mi>&#8230;</mi><mn>1</mn><mn>0</mn><mn>-1</mn><mi>&#8230;</mi></mfenced>'
3f2e9916df6ff8786fac12f45de3bafcc6a100da78f64ff060c24ffca884e2fe
from sympy.printing.dot import (purestr, styleof, attrprint, dotnode, dotedges, dotprint) from sympy import Symbol, Integer, Basic, Expr, srepr, Float, symbols from sympy.abc import x def test_purestr(): assert purestr(Symbol('x')) == "Symbol('x')" assert purestr(Basic(1, 2)) == "Basic(1, 2)" assert purestr(Float(2)) == "Float('2.0', precision=53)" assert purestr(Symbol('x'), with_args=True) == ("Symbol('x')", ()) assert purestr(Basic(1, 2), with_args=True) == ('Basic(1, 2)', ('1', '2')) assert purestr(Float(2), with_args=True) == \ ("Float('2.0', precision=53)", ()) def test_styleof(): styles = [(Basic, {'color': 'blue', 'shape': 'ellipse'}), (Expr, {'color': 'black'})] assert styleof(Basic(1), styles) == {'color': 'blue', 'shape': 'ellipse'} assert styleof(x + 1, styles) == {'color': 'black', 'shape': 'ellipse'} def test_attrprint(): assert attrprint({'color': 'blue', 'shape': 'ellipse'}) == \ '"color"="blue", "shape"="ellipse"' def test_dotnode(): assert dotnode(x, repeat=False) == \ '"Symbol(\'x\')" ["color"="black", "label"="x", "shape"="ellipse"];' assert dotnode(x+2, repeat=False) == \ '"Add(Integer(2), Symbol(\'x\'))" ' \ '["color"="black", "label"="Add", "shape"="ellipse"];', \ dotnode(x+2,repeat=0) assert dotnode(x + x**2, repeat=False) == \ '"Add(Symbol(\'x\'), Pow(Symbol(\'x\'), Integer(2)))" ' \ '["color"="black", "label"="Add", "shape"="ellipse"];' assert dotnode(x + x**2, repeat=True) == \ '"Add(Symbol(\'x\'), Pow(Symbol(\'x\'), Integer(2)))_()" ' \ '["color"="black", "label"="Add", "shape"="ellipse"];' def test_dotedges(): assert sorted(dotedges(x+2, repeat=False)) == [ '"Add(Integer(2), Symbol(\'x\'))" -> "Integer(2)";', '"Add(Integer(2), Symbol(\'x\'))" -> "Symbol(\'x\')";' ] assert sorted(dotedges(x + 2, repeat=True)) == [ '"Add(Integer(2), Symbol(\'x\'))_()" -> "Integer(2)_(0,)";', '"Add(Integer(2), Symbol(\'x\'))_()" -> "Symbol(\'x\')_(1,)";' ] def test_dotprint(): text = dotprint(x+2, repeat=False) assert all(e in text for e in dotedges(x+2, repeat=False)) assert all( n in text for n in [dotnode(expr, repeat=False) for expr in (x, Integer(2), x+2)]) assert 'digraph' in text text = dotprint(x+x**2, repeat=False) assert all(e in text for e in dotedges(x+x**2, repeat=False)) assert all( n in text for n in [dotnode(expr, repeat=False) for expr in (x, Integer(2), x**2)]) assert 'digraph' in text text = dotprint(x+x**2, repeat=True) assert all(e in text for e in dotedges(x+x**2, repeat=True)) assert all( n in text for n in [dotnode(expr, pos=()) for expr in [x + x**2]]) text = dotprint(x**x, repeat=True) assert all(e in text for e in dotedges(x**x, repeat=True)) assert all( n in text for n in [dotnode(x, pos=(0,)), dotnode(x, pos=(1,))]) assert 'digraph' in text def test_dotprint_depth(): text = dotprint(3*x+2, depth=1) assert dotnode(3*x+2) in text assert dotnode(x) not in text text = dotprint(3*x+2) assert "depth" not in text def test_Matrix_and_non_basics(): from sympy import MatrixSymbol n = Symbol('n') assert dotprint(MatrixSymbol('X', n, n)) == \ """digraph{ # Graph style "ordering"="out" "rankdir"="TD" ######### # Nodes # ######### "MatrixSymbol(Str('X'), Symbol('n'), Symbol('n'))_()" ["color"="black", "label"="MatrixSymbol", "shape"="ellipse"]; "Str('X')_(0,)" ["color"="blue", "label"="X", "shape"="ellipse"]; "Symbol('n')_(1,)" ["color"="black", "label"="n", "shape"="ellipse"]; "Symbol('n')_(2,)" ["color"="black", "label"="n", "shape"="ellipse"]; ######### # Edges # ######### "MatrixSymbol(Str('X'), Symbol('n'), Symbol('n'))_()" -> "Str('X')_(0,)"; "MatrixSymbol(Str('X'), Symbol('n'), Symbol('n'))_()" -> "Symbol('n')_(1,)"; "MatrixSymbol(Str('X'), Symbol('n'), Symbol('n'))_()" -> "Symbol('n')_(2,)"; }""" def test_labelfunc(): text = dotprint(x + 2, labelfunc=srepr) assert "Symbol('x')" in text assert "Integer(2)" in text def test_commutative(): x, y = symbols('x y', commutative=False) assert dotprint(x + y) == dotprint(y + x) assert dotprint(x*y) != dotprint(y*x)
fc164c355f1248a5270e6d7edc9ba3667ffb7c7ebb985ab74df427f14e806261
# -*- 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, Series, Parallel, Feedback 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 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 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\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] 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) 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⎠\ """ 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 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) 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⎠\ """ 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 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\ """ 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 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(set([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 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}' def test_pretty_ComplexRegion(): from sympy import ComplexRegion ucode_str = '{x + y⋅ⅈ | x, y ∊ [3, 5] × [4, 6]}' assert upretty(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == ucode_str ucode_str = '{r⋅(ⅈ⋅sin(θ) + cos(θ)) | r, θ ∊ [0, 1] × [0, 2⋅π)}' assert upretty(ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == 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 sympy.core.compatibility 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(object): 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))) == '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_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"
04cc556457d07d08cfca2d78ac39effa974ad4b050c1c277bdd29f70042e6a73
from sympy import sqrt, Abs from sympy.core import S, Rational from sympy.integrals.intpoly import (decompose, best_origin, distance_to_side, polytope_integrate, point_sort, hyperplane_parameters, main_integrate3d, main_integrate, polygon_integrate, lineseg_integrate, integration_reduction, integration_reduction_dynamic, is_vertex) from sympy.geometry.line import Segment2D from sympy.geometry.polygon import Polygon from sympy.geometry.point import Point, Point2D from sympy.abc import x, y, z from sympy.testing.pytest import slow def test_decompose(): assert decompose(x) == {1: x} assert decompose(x**2) == {2: x**2} assert decompose(x*y) == {2: x*y} assert decompose(x + y) == {1: x + y} assert decompose(x**2 + y) == {1: y, 2: x**2} assert decompose(8*x**2 + 4*y + 7) == {0: 7, 1: 4*y, 2: 8*x**2} assert decompose(x**2 + 3*y*x) == {2: x**2 + 3*x*y} assert decompose(9*x**2 + y + 4*x + x**3 + y**2*x + 3) ==\ {0: 3, 1: 4*x + y, 2: 9*x**2, 3: x**3 + x*y**2} assert decompose(x, True) == {x} assert decompose(x ** 2, True) == {x**2} assert decompose(x * y, True) == {x * y} assert decompose(x + y, True) == {x, y} assert decompose(x ** 2 + y, True) == {y, x ** 2} assert decompose(8 * x ** 2 + 4 * y + 7, True) == {7, 4*y, 8*x**2} assert decompose(x ** 2 + 3 * y * x, True) == {x ** 2, 3 * x * y} assert decompose(9 * x ** 2 + y + 4 * x + x ** 3 + y ** 2 * x + 3, True) == \ {3, y, 4*x, 9*x**2, x*y**2, x**3} def test_best_origin(): expr1 = y ** 2 * x ** 5 + y ** 5 * x ** 7 + 7 * x + x ** 12 + y ** 7 * x l1 = Segment2D(Point(0, 3), Point(1, 1)) l2 = Segment2D(Point(S(3) / 2, 0), Point(S(3) / 2, 3)) l3 = Segment2D(Point(0, S(3) / 2), Point(3, S(3) / 2)) l4 = Segment2D(Point(0, 2), Point(2, 0)) l5 = Segment2D(Point(0, 2), Point(1, 1)) l6 = Segment2D(Point(2, 0), Point(1, 1)) assert best_origin((2, 1), 3, l1, expr1) == (0, 3) assert best_origin((2, 0), 3, l2, x ** 7) == (S(3) / 2, 0) assert best_origin((0, 2), 3, l3, x ** 7) == (0, S(3) / 2) assert best_origin((1, 1), 2, l4, x ** 7 * y ** 3) == (0, 2) assert best_origin((1, 1), 2, l4, x ** 3 * y ** 7) == (2, 0) assert best_origin((1, 1), 2, l5, x ** 2 * y ** 9) == (0, 2) assert best_origin((1, 1), 2, l6, x ** 9 * y ** 2) == (2, 0) @slow def test_polytope_integrate(): # Convex 2-Polytopes # Vertex representation assert polytope_integrate(Polygon(Point(0, 0), Point(0, 2), Point(4, 0)), 1) == 4 assert polytope_integrate(Polygon(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0)), x * y) ==\ Rational(1, 4) assert polytope_integrate(Polygon(Point(0, 3), Point(5, 3), Point(1, 1)), 6*x**2 - 40*y) == Rational(-935, 3) assert polytope_integrate(Polygon(Point(0, 0), Point(0, sqrt(3)), Point(sqrt(3), sqrt(3)), Point(sqrt(3), 0)), 1) == 3 hexagon = Polygon(Point(0, 0), Point(-sqrt(3) / 2, S.Half), Point(-sqrt(3) / 2, S(3) / 2), Point(0, 2), Point(sqrt(3) / 2, S(3) / 2), Point(sqrt(3) / 2, S.Half)) assert polytope_integrate(hexagon, 1) == S(3*sqrt(3)) / 2 # Hyperplane representation assert polytope_integrate([((-1, 0), 0), ((1, 2), 4), ((0, -1), 0)], 1) == 4 assert polytope_integrate([((-1, 0), 0), ((0, 1), 1), ((1, 0), 1), ((0, -1), 0)], x * y) == Rational(1, 4) assert polytope_integrate([((0, 1), 3), ((1, -2), -1), ((-2, -1), -3)], 6*x**2 - 40*y) == Rational(-935, 3) assert polytope_integrate([((-1, 0), 0), ((0, sqrt(3)), 3), ((sqrt(3), 0), 3), ((0, -1), 0)], 1) == 3 hexagon = [((Rational(-1, 2), -sqrt(3) / 2), 0), ((-1, 0), sqrt(3) / 2), ((Rational(-1, 2), sqrt(3) / 2), sqrt(3)), ((S.Half, sqrt(3) / 2), sqrt(3)), ((1, 0), sqrt(3) / 2), ((S.Half, -sqrt(3) / 2), 0)] assert polytope_integrate(hexagon, 1) == S(3*sqrt(3)) / 2 # Non-convex polytopes # Vertex representation assert polytope_integrate(Polygon(Point(-1, -1), Point(-1, 1), Point(1, 1), Point(0, 0), Point(1, -1)), 1) == 3 assert polytope_integrate(Polygon(Point(-1, -1), Point(-1, 1), Point(0, 0), Point(1, 1), Point(1, -1), Point(0, 0)), 1) == 2 # Hyperplane representation assert polytope_integrate([((-1, 0), 1), ((0, 1), 1), ((1, -1), 0), ((1, 1), 0), ((0, -1), 1)], 1) == 3 assert polytope_integrate([((-1, 0), 1), ((1, 1), 0), ((-1, 1), 0), ((1, 0), 1), ((-1, -1), 0), ((1, -1), 0)], 1) == 2 # Tests for 2D polytopes mentioned in Chin et al(Page 10): # http://dilbert.engr.ucdavis.edu/~suku/quadrature/cls-integration.pdf fig1 = Polygon(Point(1.220, -0.827), Point(-1.490, -4.503), Point(-3.766, -1.622), Point(-4.240, -0.091), Point(-3.160, 4), Point(-0.981, 4.447), Point(0.132, 4.027)) assert polytope_integrate(fig1, x**2 + x*y + y**2) ==\ S(2031627344735367)/(8*10**12) fig2 = Polygon(Point(4.561, 2.317), Point(1.491, -1.315), Point(-3.310, -3.164), Point(-4.845, -3.110), Point(-4.569, 1.867)) assert polytope_integrate(fig2, x**2 + x*y + y**2) ==\ S(517091313866043)/(16*10**11) fig3 = Polygon(Point(-2.740, -1.888), Point(-3.292, 4.233), Point(-2.723, -0.697), Point(-0.643, -3.151)) assert polytope_integrate(fig3, x**2 + x*y + y**2) ==\ S(147449361647041)/(8*10**12) fig4 = Polygon(Point(0.211, -4.622), Point(-2.684, 3.851), Point(0.468, 4.879), Point(4.630, -1.325), Point(-0.411, -1.044)) assert polytope_integrate(fig4, x**2 + x*y + y**2) ==\ S(180742845225803)/(10**12) # Tests for many polynomials with maximum degree given(2D case). tri = Polygon(Point(0, 3), Point(5, 3), Point(1, 1)) polys = [] expr1 = x**9*y + x**7*y**3 + 2*x**2*y**8 expr2 = x**6*y**4 + x**5*y**5 + 2*y**10 expr3 = x**10 + x**9*y + x**8*y**2 + x**5*y**5 polys.extend((expr1, expr2, expr3)) result_dict = polytope_integrate(tri, polys, max_degree=10) assert result_dict[expr1] == Rational(615780107, 594) assert result_dict[expr2] == Rational(13062161, 27) assert result_dict[expr3] == Rational(1946257153, 924) # Tests when all integral of all monomials up to a max_degree is to be # calculated. assert polytope_integrate(Polygon(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0)), max_degree=4) == {0: 0, 1: 1, x: S.Half, x ** 2 * y ** 2: S.One / 9, x ** 4: S.One / 5, y ** 4: S.One / 5, y: S.Half, x * y ** 2: S.One / 6, y ** 2: S.One / 3, x ** 3: S.One / 4, x ** 2 * y: S.One / 6, x ** 3 * y: S.One / 8, x * y: S.One / 4, y ** 3: S.One / 4, x ** 2: S.One / 3, x * y ** 3: S.One / 8} # Tests for 3D polytopes cube1 = [[(0, 0, 0), (0, 6, 6), (6, 6, 6), (3, 6, 0), (0, 6, 0), (6, 0, 6), (3, 0, 0), (0, 0, 6)], [1, 2, 3, 4], [3, 2, 5, 6], [1, 7, 5, 2], [0, 6, 5, 7], [1, 4, 0, 7], [0, 4, 3, 6]] assert polytope_integrate(cube1, 1) == S(162) # 3D Test cases in Chin et al(2015) cube2 = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0), (5, 0, 5), (5, 5, 0), (5, 5, 5)], [3, 7, 6, 2], [1, 5, 7, 3], [5, 4, 6, 7], [0, 4, 5, 1], [2, 0, 1, 3], [2, 6, 4, 0]] cube3 = [[(0, 0, 0), (5, 0, 0), (5, 4, 0), (3, 2, 0), (3, 5, 0), (0, 5, 0), (0, 0, 5), (5, 0, 5), (5, 4, 5), (3, 2, 5), (3, 5, 5), (0, 5, 5)], [6, 11, 5, 0], [1, 7, 6, 0], [5, 4, 3, 2, 1, 0], [11, 10, 4, 5], [10, 9, 3, 4], [9, 8, 2, 3], [8, 7, 1, 2], [7, 8, 9, 10, 11, 6]] cube4 = [[(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (S.One / 4, S.One / 4, S.One / 4)], [0, 2, 1], [1, 3, 0], [4, 2, 3], [4, 3, 1], [0, 1, 2], [2, 4, 1], [0, 3, 2]] assert polytope_integrate(cube2, x ** 2 + y ** 2 + x * y + z ** 2) ==\ Rational(15625, 4) assert polytope_integrate(cube3, x ** 2 + y ** 2 + x * y + z ** 2) ==\ S(33835) / 12 assert polytope_integrate(cube4, x ** 2 + y ** 2 + x * y + z ** 2) ==\ S(37) / 960 # Test cases from Mathematica's PolyhedronData library octahedron = [[(S.NegativeOne / sqrt(2), 0, 0), (0, S.One / sqrt(2), 0), (0, 0, S.NegativeOne / sqrt(2)), (0, 0, S.One / sqrt(2)), (0, S.NegativeOne / sqrt(2), 0), (S.One / sqrt(2), 0, 0)], [3, 4, 5], [3, 5, 1], [3, 1, 0], [3, 0, 4], [4, 0, 2], [4, 2, 5], [2, 0, 1], [5, 2, 1]] assert polytope_integrate(octahedron, 1) == sqrt(2) / 3 great_stellated_dodecahedron =\ [[(-0.32491969623290634095, 0, 0.42532540417601993887), (0.32491969623290634095, 0, -0.42532540417601993887), (-0.52573111211913359231, 0, 0.10040570794311363956), (0.52573111211913359231, 0, -0.10040570794311363956), (-0.10040570794311363956, -0.3090169943749474241, 0.42532540417601993887), (-0.10040570794311363956, 0.30901699437494742410, 0.42532540417601993887), (0.10040570794311363956, -0.3090169943749474241, -0.42532540417601993887), (0.10040570794311363956, 0.30901699437494742410, -0.42532540417601993887), (-0.16245984811645317047, -0.5, 0.10040570794311363956), (-0.16245984811645317047, 0.5, 0.10040570794311363956), (0.16245984811645317047, -0.5, -0.10040570794311363956), (0.16245984811645317047, 0.5, -0.10040570794311363956), (-0.42532540417601993887, -0.3090169943749474241, -0.10040570794311363956), (-0.42532540417601993887, 0.30901699437494742410, -0.10040570794311363956), (-0.26286555605956679615, 0.1909830056250525759, -0.42532540417601993887), (-0.26286555605956679615, -0.1909830056250525759, -0.42532540417601993887), (0.26286555605956679615, 0.1909830056250525759, 0.42532540417601993887), (0.26286555605956679615, -0.1909830056250525759, 0.42532540417601993887), (0.42532540417601993887, -0.3090169943749474241, 0.10040570794311363956), (0.42532540417601993887, 0.30901699437494742410, 0.10040570794311363956)], [12, 3, 0, 6, 16], [17, 7, 0, 3, 13], [9, 6, 0, 7, 8], [18, 2, 1, 4, 14], [15, 5, 1, 2, 19], [11, 4, 1, 5, 10], [8, 19, 2, 18, 9], [10, 13, 3, 12, 11], [16, 14, 4, 11, 12], [13, 10, 5, 15, 17], [14, 16, 6, 9, 18], [19, 8, 7, 17, 15]] # Actual volume is : 0.163118960624632 assert Abs(polytope_integrate(great_stellated_dodecahedron, 1) -\ 0.163118960624632) < 1e-12 expr = x **2 + y ** 2 + z ** 2 octahedron_five_compound = [[(0, -0.7071067811865475244, 0), (0, 0.70710678118654752440, 0), (0.1148764602736805918, -0.35355339059327376220, -0.60150095500754567366), (0.1148764602736805918, 0.35355339059327376220, -0.60150095500754567366), (0.18587401723009224507, -0.57206140281768429760, 0.37174803446018449013), (0.18587401723009224507, 0.57206140281768429760, 0.37174803446018449013), (0.30075047750377283683, -0.21850801222441053540, 0.60150095500754567366), (0.30075047750377283683, 0.21850801222441053540, 0.60150095500754567366), (0.48662449473386508189, -0.35355339059327376220, -0.37174803446018449013), (0.48662449473386508189, 0.35355339059327376220, -0.37174803446018449013), (-0.60150095500754567366, 0, -0.37174803446018449013), (-0.30075047750377283683, -0.21850801222441053540, -0.60150095500754567366), (-0.30075047750377283683, 0.21850801222441053540, -0.60150095500754567366), (0.60150095500754567366, 0, 0.37174803446018449013), (0.4156269377774534286, -0.57206140281768429760, 0), (0.4156269377774534286, 0.57206140281768429760, 0), (0.37174803446018449013, 0, -0.60150095500754567366), (-0.4156269377774534286, -0.57206140281768429760, 0), (-0.4156269377774534286, 0.57206140281768429760, 0), (-0.67249851196395732696, -0.21850801222441053540, 0), (-0.67249851196395732696, 0.21850801222441053540, 0), (0.67249851196395732696, -0.21850801222441053540, 0), (0.67249851196395732696, 0.21850801222441053540, 0), (-0.37174803446018449013, 0, 0.60150095500754567366), (-0.48662449473386508189, -0.35355339059327376220, 0.37174803446018449013), (-0.48662449473386508189, 0.35355339059327376220, 0.37174803446018449013), (-0.18587401723009224507, -0.57206140281768429760, -0.37174803446018449013), (-0.18587401723009224507, 0.57206140281768429760, -0.37174803446018449013), (-0.11487646027368059176, -0.35355339059327376220, 0.60150095500754567366), (-0.11487646027368059176, 0.35355339059327376220, 0.60150095500754567366)], [0, 10, 16], [23, 10, 0], [16, 13, 0], [0, 13, 23], [16, 10, 1], [1, 10, 23], [1, 13, 16], [23, 13, 1], [2, 4, 19], [22, 4, 2], [2, 19, 27], [27, 22, 2], [20, 5, 3], [3, 5, 21], [26, 20, 3], [3, 21, 26], [29, 19, 4], [4, 22, 29], [5, 20, 28], [28, 21, 5], [6, 8, 15], [17, 8, 6], [6, 15, 25], [25, 17, 6], [14, 9, 7], [7, 9, 18], [24, 14, 7], [7, 18, 24], [8, 12, 15], [17, 12, 8], [14, 11, 9], [9, 11, 18], [11, 14, 24], [24, 18, 11], [25, 15, 12], [12, 17, 25], [29, 27, 19], [20, 26, 28], [28, 26, 21], [22, 27, 29]] assert Abs(polytope_integrate(octahedron_five_compound, expr)) - 0.353553\ < 1e-6 cube_five_compound = [[(-0.1624598481164531631, -0.5, -0.6881909602355867691), (-0.1624598481164531631, 0.5, -0.6881909602355867691), (0.1624598481164531631, -0.5, 0.68819096023558676910), (0.1624598481164531631, 0.5, 0.68819096023558676910), (-0.52573111211913359231, 0, -0.6881909602355867691), (0.52573111211913359231, 0, 0.68819096023558676910), (-0.26286555605956679615, -0.8090169943749474241, -0.1624598481164531631), (-0.26286555605956679615, 0.8090169943749474241, -0.1624598481164531631), (0.26286555605956680301, -0.8090169943749474241, 0.1624598481164531631), (0.26286555605956680301, 0.8090169943749474241, 0.1624598481164531631), (-0.42532540417601993887, -0.3090169943749474241, 0.68819096023558676910), (-0.42532540417601993887, 0.30901699437494742410, 0.68819096023558676910), (0.42532540417601996609, -0.3090169943749474241, -0.6881909602355867691), (0.42532540417601996609, 0.30901699437494742410, -0.6881909602355867691), (-0.6881909602355867691, -0.5, 0.1624598481164531631), (-0.6881909602355867691, 0.5, 0.1624598481164531631), (0.68819096023558676910, -0.5, -0.1624598481164531631), (0.68819096023558676910, 0.5, -0.1624598481164531631), (-0.85065080835203998877, 0, -0.1624598481164531631), (0.85065080835203993218, 0, 0.1624598481164531631)], [18, 10, 3, 7], [13, 19, 8, 0], [18, 0, 8, 10], [3, 19, 13, 7], [18, 7, 13, 0], [8, 19, 3, 10], [6, 2, 11, 18], [1, 9, 19, 12], [11, 9, 1, 18], [6, 12, 19, 2], [1, 12, 6, 18], [11, 2, 19, 9], [4, 14, 11, 7], [17, 5, 8, 12], [4, 12, 8, 14], [11, 5, 17, 7], [4, 7, 17, 12], [8, 5, 11, 14], [6, 10, 15, 4], [13, 9, 5, 16], [15, 9, 13, 4], [6, 16, 5, 10], [13, 16, 6, 4], [15, 10, 5, 9], [14, 15, 1, 0], [16, 17, 3, 2], [14, 2, 3, 15], [1, 17, 16, 0], [14, 0, 16, 2], [3, 17, 1, 15]] assert Abs(polytope_integrate(cube_five_compound, expr) - 1.25) < 1e-12 echidnahedron = [[(0, 0, -2.4898982848827801995), (0, 0, 2.4898982848827802734), (0, -4.2360679774997896964, -2.4898982848827801995), (0, -4.2360679774997896964, 2.4898982848827802734), (0, 4.2360679774997896964, -2.4898982848827801995), (0, 4.2360679774997896964, 2.4898982848827802734), (-4.0287400534704067567, -1.3090169943749474241, -2.4898982848827801995), (-4.0287400534704067567, -1.3090169943749474241, 2.4898982848827802734), (-4.0287400534704067567, 1.3090169943749474241, -2.4898982848827801995), (-4.0287400534704067567, 1.3090169943749474241, 2.4898982848827802734), (4.0287400534704069747, -1.3090169943749474241, -2.4898982848827801995), (4.0287400534704069747, -1.3090169943749474241, 2.4898982848827802734), (4.0287400534704069747, 1.3090169943749474241, -2.4898982848827801995), (4.0287400534704069747, 1.3090169943749474241, 2.4898982848827802734), (-2.4898982848827801995, -3.4270509831248422723, -2.4898982848827801995), (-2.4898982848827801995, -3.4270509831248422723, 2.4898982848827802734), (-2.4898982848827801995, 3.4270509831248422723, -2.4898982848827801995), (-2.4898982848827801995, 3.4270509831248422723, 2.4898982848827802734), (2.4898982848827802734, -3.4270509831248422723, -2.4898982848827801995), (2.4898982848827802734, -3.4270509831248422723, 2.4898982848827802734), (2.4898982848827802734, 3.4270509831248422723, -2.4898982848827801995), (2.4898982848827802734, 3.4270509831248422723, 2.4898982848827802734), (-4.7169310137059934362, -0.8090169943749474241, -1.1135163644116066184), (-4.7169310137059934362, 0.8090169943749474241, -1.1135163644116066184), (4.7169310137059937438, -0.8090169943749474241, 1.11351636441160673519), (4.7169310137059937438, 0.8090169943749474241, 1.11351636441160673519), (-4.2916056095299737777, -2.1180339887498948482, 1.11351636441160673519), (-4.2916056095299737777, 2.1180339887498948482, 1.11351636441160673519), (4.2916056095299737777, -2.1180339887498948482, -1.1135163644116066184), (4.2916056095299737777, 2.1180339887498948482, -1.1135163644116066184), (-3.6034146492943870399, 0, -3.3405490932348205213), (3.6034146492943870399, 0, 3.3405490932348202056), (-3.3405490932348205213, -3.4270509831248422723, 1.11351636441160673519), (-3.3405490932348205213, 3.4270509831248422723, 1.11351636441160673519), (3.3405490932348202056, -3.4270509831248422723, -1.1135163644116066184), (3.3405490932348202056, 3.4270509831248422723, -1.1135163644116066184), (-2.9152236890588002395, -2.1180339887498948482, 3.3405490932348202056), (-2.9152236890588002395, 2.1180339887498948482, 3.3405490932348202056), (2.9152236890588002395, -2.1180339887498948482, -3.3405490932348205213), (2.9152236890588002395, 2.1180339887498948482, -3.3405490932348205213), (-2.2270327288232132368, 0, -1.1135163644116066184), (-2.2270327288232132368, -4.2360679774997896964, -1.1135163644116066184), (-2.2270327288232132368, 4.2360679774997896964, -1.1135163644116066184), (2.2270327288232134704, 0, 1.11351636441160673519), (2.2270327288232134704, -4.2360679774997896964, 1.11351636441160673519), (2.2270327288232134704, 4.2360679774997896964, 1.11351636441160673519), (-1.8017073246471935200, -1.3090169943749474241, 1.11351636441160673519), (-1.8017073246471935200, 1.3090169943749474241, 1.11351636441160673519), (1.8017073246471935043, -1.3090169943749474241, -1.1135163644116066184), (1.8017073246471935043, 1.3090169943749474241, -1.1135163644116066184), (-1.3763819204711735382, 0, -4.7169310137059934362), (-1.3763819204711735382, 0, 0.26286555605956679615), (1.37638192047117353821, 0, 4.7169310137059937438), (1.37638192047117353821, 0, -0.26286555605956679615), (-1.1135163644116066184, -3.4270509831248422723, -3.3405490932348205213), (-1.1135163644116066184, -0.8090169943749474241, 4.7169310137059937438), (-1.1135163644116066184, -0.8090169943749474241, -0.26286555605956679615), (-1.1135163644116066184, 0.8090169943749474241, 4.7169310137059937438), (-1.1135163644116066184, 0.8090169943749474241, -0.26286555605956679615), (-1.1135163644116066184, 3.4270509831248422723, -3.3405490932348205213), (1.11351636441160673519, -3.4270509831248422723, 3.3405490932348202056), (1.11351636441160673519, -0.8090169943749474241, -4.7169310137059934362), (1.11351636441160673519, -0.8090169943749474241, 0.26286555605956679615), (1.11351636441160673519, 0.8090169943749474241, -4.7169310137059934362), (1.11351636441160673519, 0.8090169943749474241, 0.26286555605956679615), (1.11351636441160673519, 3.4270509831248422723, 3.3405490932348202056), (-0.85065080835203998877, 0, 1.11351636441160673519), (0.85065080835203993218, 0, -1.1135163644116066184), (-0.6881909602355867691, -0.5, -1.1135163644116066184), (-0.6881909602355867691, 0.5, -1.1135163644116066184), (-0.6881909602355867691, -4.7360679774997896964, -1.1135163644116066184), (-0.6881909602355867691, -2.1180339887498948482, -1.1135163644116066184), (-0.6881909602355867691, 2.1180339887498948482, -1.1135163644116066184), (-0.6881909602355867691, 4.7360679774997896964, -1.1135163644116066184), (0.68819096023558676910, -0.5, 1.11351636441160673519), (0.68819096023558676910, 0.5, 1.11351636441160673519), (0.68819096023558676910, -4.7360679774997896964, 1.11351636441160673519), (0.68819096023558676910, -2.1180339887498948482, 1.11351636441160673519), (0.68819096023558676910, 2.1180339887498948482, 1.11351636441160673519), (0.68819096023558676910, 4.7360679774997896964, 1.11351636441160673519), (-0.42532540417601993887, -1.3090169943749474241, -4.7169310137059934362), (-0.42532540417601993887, -1.3090169943749474241, 0.26286555605956679615), (-0.42532540417601993887, 1.3090169943749474241, -4.7169310137059934362), (-0.42532540417601993887, 1.3090169943749474241, 0.26286555605956679615), (-0.26286555605956679615, -0.8090169943749474241, 1.11351636441160673519), (-0.26286555605956679615, 0.8090169943749474241, 1.11351636441160673519), (0.26286555605956679615, -0.8090169943749474241, -1.1135163644116066184), (0.26286555605956679615, 0.8090169943749474241, -1.1135163644116066184), (0.42532540417601996609, -1.3090169943749474241, 4.7169310137059937438), (0.42532540417601996609, -1.3090169943749474241, -0.26286555605956679615), (0.42532540417601996609, 1.3090169943749474241, 4.7169310137059937438), (0.42532540417601996609, 1.3090169943749474241, -0.26286555605956679615)], [9, 66, 47], [44, 62, 77], [20, 91, 49], [33, 47, 83], [3, 77, 84], [12, 49, 53], [36, 84, 66], [28, 53, 62], [73, 83, 91], [15, 84, 46], [25, 64, 43], [16, 58, 72], [26, 46, 51], [11, 43, 74], [4, 72, 91], [60, 74, 84], [35, 91, 64], [23, 51, 58], [19, 74, 77], [79, 83, 78], [6, 56, 40], [76, 77, 81], [21, 78, 75], [8, 40, 58], [31, 75, 74], [42, 58, 83], [41, 81, 56], [13, 75, 43], [27, 51, 47], [2, 89, 71], [24, 43, 62], [17, 47, 85], [14, 71, 56], [65, 85, 75], [22, 56, 51], [34, 62, 89], [5, 85, 78], [32, 81, 46], [10, 53, 48], [45, 78, 64], [7, 46, 66], [18, 48, 89], [37, 66, 85], [70, 89, 81], [29, 64, 53], [88, 74, 1], [38, 67, 48], [42, 83, 72], [57, 1, 85], [34, 48, 62], [59, 72, 87], [19, 62, 74], [63, 87, 67], [17, 85, 83], [52, 75, 1], [39, 87, 49], [22, 51, 40], [55, 1, 66], [29, 49, 64], [30, 40, 69], [13, 64, 75], [82, 69, 87], [7, 66, 51], [90, 85, 1], [59, 69, 72], [70, 81, 71], [88, 1, 84], [73, 72, 83], [54, 71, 68], [5, 83, 85], [50, 68, 69], [3, 84, 81], [57, 66, 1], [30, 68, 40], [28, 62, 48], [52, 1, 74], [23, 40, 51], [38, 48, 86], [9, 51, 66], [80, 86, 68], [11, 74, 62], [55, 84, 1], [54, 86, 71], [35, 64, 49], [90, 1, 75], [41, 71, 81], [39, 49, 67], [15, 81, 84], [61, 67, 86], [21, 75, 64], [24, 53, 43], [50, 69, 0], [37, 85, 47], [31, 43, 75], [61, 0, 67], [27, 47, 58], [10, 67, 53], [8, 58, 69], [90, 75, 85], [45, 91, 78], [80, 68, 0], [36, 66, 46], [65, 78, 85], [63, 0, 87], [32, 46, 56], [20, 87, 91], [14, 56, 68], [57, 85, 66], [33, 58, 47], [61, 86, 0], [60, 84, 77], [37, 47, 66], [82, 0, 69], [44, 77, 89], [16, 69, 58], [18, 89, 86], [55, 66, 84], [26, 56, 46], [63, 67, 0], [31, 74, 43], [36, 46, 84], [50, 0, 68], [25, 43, 53], [6, 68, 56], [12, 53, 67], [88, 84, 74], [76, 89, 77], [82, 87, 0], [65, 75, 78], [60, 77, 74], [80, 0, 86], [79, 78, 91], [2, 86, 89], [4, 91, 87], [52, 74, 75], [21, 64, 78], [18, 86, 48], [23, 58, 40], [5, 78, 83], [28, 48, 53], [6, 40, 68], [25, 53, 64], [54, 68, 86], [33, 83, 58], [17, 83, 47], [12, 67, 49], [41, 56, 71], [9, 47, 51], [35, 49, 91], [2, 71, 86], [79, 91, 83], [38, 86, 67], [26, 51, 56], [7, 51, 46], [4, 87, 72], [34, 89, 48], [15, 46, 81], [42, 72, 58], [10, 48, 67], [27, 58, 51], [39, 67, 87], [76, 81, 89], [3, 81, 77], [8, 69, 40], [29, 53, 49], [19, 77, 62], [22, 40, 56], [20, 49, 87], [32, 56, 81], [59, 87, 69], [24, 62, 53], [11, 62, 43], [14, 68, 71], [73, 91, 72], [13, 43, 64], [70, 71, 89], [16, 72, 69], [44, 89, 62], [30, 69, 68], [45, 64, 91]] # Actual volume is : 51.405764746872634 assert Abs(polytope_integrate(echidnahedron, 1) - 51.4057647468726) < 1e-12 assert Abs(polytope_integrate(echidnahedron, expr) - 253.569603474519) <\ 1e-12 # Tests for many polynomials with maximum degree given(2D case). assert polytope_integrate(cube2, [x**2, y*z], max_degree=2) == \ {y * z: 3125 / S(4), x ** 2: 3125 / S(3)} assert polytope_integrate(cube2, max_degree=2) == \ {1: 125, x: 625 / S(2), x * z: 3125 / S(4), y: 625 / S(2), y * z: 3125 / S(4), z ** 2: 3125 / S(3), y ** 2: 3125 / S(3), z: 625 / S(2), x * y: 3125 / S(4), x ** 2: 3125 / S(3)} def test_point_sort(): assert point_sort([Point(0, 0), Point(1, 0), Point(1, 1)]) == \ [Point2D(1, 1), Point2D(1, 0), Point2D(0, 0)] fig6 = Polygon((0, 0), (1, 0), (1, 1)) assert polytope_integrate(fig6, x*y) == Rational(-1, 8) assert polytope_integrate(fig6, x*y, clockwise = True) == Rational(1, 8) def test_polytopes_intersecting_sides(): fig5 = Polygon(Point(-4.165, -0.832), Point(-3.668, 1.568), Point(-3.266, 1.279), Point(-1.090, -2.080), Point(3.313, -0.683), Point(3.033, -4.845), Point(-4.395, 4.840), Point(-1.007, -3.328)) assert polytope_integrate(fig5, x**2 + x*y + y**2) ==\ S(1633405224899363)/(24*10**12) fig6 = Polygon(Point(-3.018, -4.473), Point(-0.103, 2.378), Point(-1.605, -2.308), Point(4.516, -0.771), Point(4.203, 0.478)) assert polytope_integrate(fig6, x**2 + x*y + y**2) ==\ S(88161333955921)/(3*10**12) def test_max_degree(): polygon = Polygon((0, 0), (0, 1), (1, 1), (1, 0)) polys = [1, x, y, x*y, x**2*y, x*y**2] assert polytope_integrate(polygon, polys, max_degree=3) == \ {1: 1, x: S.Half, y: S.Half, x*y: Rational(1, 4), x**2*y: Rational(1, 6), x*y**2: Rational(1, 6)} def test_main_integrate3d(): cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\ (5, 0, 5), (5, 5, 0), (5, 5, 5)],\ [2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\ [3, 1, 0, 2], [0, 4, 6, 2]] vertices = cube[0] faces = cube[1:] hp_params = hyperplane_parameters(faces, vertices) assert main_integrate3d(1, faces, vertices, hp_params) == -125 assert main_integrate3d(1, faces, vertices, hp_params, max_degree=1) == \ {1: -125, y: Rational(-625, 2), z: Rational(-625, 2), x: Rational(-625, 2)} def test_main_integrate(): triangle = Polygon((0, 3), (5, 3), (1, 1)) facets = triangle.sides hp_params = hyperplane_parameters(triangle) assert main_integrate(x**2 + y**2, facets, hp_params) == Rational(325, 6) assert main_integrate(x**2 + y**2, facets, hp_params, max_degree=1) == \ {0: 0, 1: 5, y: Rational(35, 3), x: 10} def test_polygon_integrate(): cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\ (5, 0, 5), (5, 5, 0), (5, 5, 5)],\ [2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\ [3, 1, 0, 2], [0, 4, 6, 2]] facet = cube[1] facets = cube[1:] vertices = cube[0] assert polygon_integrate(facet, [(0, 1, 0), 5], 0, facets, vertices, 1, 0) == -25 def test_distance_to_side(): point = (0, 0, 0) assert distance_to_side(point, [(0, 0, 1), (0, 1, 0)], (1, 0, 0)) == -sqrt(2)/2 def test_lineseg_integrate(): polygon = [(0, 5, 0), (5, 5, 0), (5, 5, 5), (0, 5, 5)] line_seg = [(0, 5, 0), (5, 5, 0)] assert lineseg_integrate(polygon, 0, line_seg, 1, 0) == 5 assert lineseg_integrate(polygon, 0, line_seg, 0, 0) == 0 def test_integration_reduction(): triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1)) facets = triangle.sides a, b = hyperplane_parameters(triangle)[0] assert integration_reduction(facets, 0, a, b, 1, (x, y), 0) == 5 assert integration_reduction(facets, 0, a, b, 0, (x, y), 0) == 0 def test_integration_reduction_dynamic(): triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1)) facets = triangle.sides a, b = hyperplane_parameters(triangle)[0] x0 = facets[0].points[0] monomial_values = [[0, 0, 0, 0], [1, 0, 0, 5],\ [y, 0, 1, 15], [x, 1, 0, None]] assert integration_reduction_dynamic(facets, 0, a, b, x, 1, (x, y), 1,\ 0, 1, x0, monomial_values, 3) == Rational(25, 2) assert integration_reduction_dynamic(facets, 0, a, b, 0, 1, (x, y), 1,\ 0, 1, x0, monomial_values, 3) == 0 def test_is_vertex(): assert is_vertex(2) is False assert is_vertex((2, 3)) is True assert is_vertex(Point(2, 3)) is True assert is_vertex((2, 3, 4)) is True assert is_vertex((2, 3, 4, 5)) is False
20f9cf6533908f6fd981a5410d7fc5406d4b065a47927665f34c85faca4159ba
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 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 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) 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) 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) 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)) 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)
f68104ed629c936fe161d1666ad44a2ba39704710685d5c59ee7fbbac8be7eb3
from sympy import (Add, Basic, Expr, S, Symbol, Wild, Float, Integer, Rational, I, sin, cos, tan, exp, log, nan, oo, sqrt, symbols, Integral, sympify, WildFunction, Poly, Function, Derivative, Number, pi, NumberSymbol, zoo, Piecewise, Mul, Pow, nsimplify, ratsimp, trigsimp, radsimp, powsimp, simplify, together, collect, factorial, apart, combsimp, factor, refine, cancel, Tuple, default_sort_key, DiracDelta, gamma, Dummy, Sum, E, exp_polar, expand, diff, O, Heaviside, Si, Max, UnevaluatedExpr, integrate, gammasimp, Gt) from sympy.core.expr import ExprBuilder, unchanged from sympy.core.function import AppliedUndef from sympy.physics.secondquant import FockState from sympy.physics.units import meter from sympy.testing.pytest import raises, XFAIL from sympy.abc import a, b, c, n, t, u, x, y, z class DummyNumber: """ Minimal implementation of a number that works with SymPy. If one has a Number class (e.g. Sage Integer, or some other custom class) that one wants to work well with SymPy, one has to implement at least the methods of this class DummyNumber, resp. its subclasses I5 and F1_1. Basically, one just needs to implement either __int__() or __float__() and then one needs to make sure that the class works with Python integers and with itself. """ def __radd__(self, a): if isinstance(a, (int, float)): return a + self.number return NotImplemented def __add__(self, a): if isinstance(a, (int, float, DummyNumber)): return self.number + a return NotImplemented def __rsub__(self, a): if isinstance(a, (int, float)): return a - self.number return NotImplemented def __sub__(self, a): if isinstance(a, (int, float, DummyNumber)): return self.number - a return NotImplemented def __rmul__(self, a): if isinstance(a, (int, float)): return a * self.number return NotImplemented def __mul__(self, a): if isinstance(a, (int, float, DummyNumber)): return self.number * a return NotImplemented def __rtruediv__(self, a): if isinstance(a, (int, float)): return a / self.number return NotImplemented def __truediv__(self, a): if isinstance(a, (int, float, DummyNumber)): return self.number / a return NotImplemented def __rpow__(self, a): if isinstance(a, (int, float)): return a ** self.number return NotImplemented def __pow__(self, a): if isinstance(a, (int, float, DummyNumber)): return self.number ** a return NotImplemented def __pos__(self): return self.number def __neg__(self): return - self.number class I5(DummyNumber): number = 5 def __int__(self): return self.number class F1_1(DummyNumber): number = 1.1 def __float__(self): return self.number i5 = I5() f1_1 = F1_1() # basic sympy objects basic_objs = [ Rational(2), Float("1.3"), x, y, pow(x, y)*y, ] # all supported objects all_objs = basic_objs + [ 5, 5.5, i5, f1_1 ] def dotest(s): for xo in all_objs: for yo in all_objs: s(xo, yo) return True def test_basic(): def j(a, b): x = a x = +a x = -a x = a + b x = a - b x = a*b x = a/b x = a**b del x assert dotest(j) def test_ibasic(): def s(a, b): x = a x += b x = a x -= b x = a x *= b x = a x /= b assert dotest(s) class NonBasic: '''This class represents an object that knows how to implement binary operations like +, -, etc with Expr but is not a subclass of Basic itself. The NonExpr subclass below does subclass Basic but not Expr. For both NonBasic and NonExpr it should be possible for them to override Expr.__add__ etc because Expr.__add__ should be returning NotImplemented for non Expr classes. Otherwise Expr.__add__ would create meaningless objects like Add(Integer(1), FiniteSet(2)) and it wouldn't be possible for other classes to override these operations when interacting with Expr. ''' def __add__(self, other): return SpecialOp('+', self, other) def __radd__(self, other): return SpecialOp('+', other, self) def __sub__(self, other): return SpecialOp('-', self, other) def __rsub__(self, other): return SpecialOp('-', other, self) def __mul__(self, other): return SpecialOp('*', self, other) def __rmul__(self, other): return SpecialOp('*', other, self) def __truediv__(self, other): return SpecialOp('/', self, other) def __rtruediv__(self, other): return SpecialOp('/', other, self) def __floordiv__(self, other): return SpecialOp('//', self, other) def __rfloordiv__(self, other): return SpecialOp('//', other, self) def __mod__(self, other): return SpecialOp('%', self, other) def __rmod__(self, other): return SpecialOp('%', other, self) def __divmod__(self, other): return SpecialOp('divmod', self, other) def __rdivmod__(self, other): return SpecialOp('divmod', other, self) def __pow__(self, other): return SpecialOp('**', self, other) def __rpow__(self, other): return SpecialOp('**', other, self) def __lt__(self, other): return SpecialOp('<', self, other) def __gt__(self, other): return SpecialOp('>', self, other) def __le__(self, other): return SpecialOp('<=', self, other) def __ge__(self, other): return SpecialOp('>=', self, other) class NonExpr(Basic, NonBasic): '''Like NonBasic above except this is a subclass of Basic but not Expr''' pass class SpecialOp(Basic): '''Represents the results of operations with NonBasic and NonExpr''' def __new__(cls, op, arg1, arg2): return Basic.__new__(cls, op, arg1, arg2) class NonArithmetic(Basic): '''Represents a Basic subclass that does not support arithmetic operations''' pass def test_cooperative_operations(): '''Tests that Expr uses binary operations cooperatively. In particular it should be possible for non-Expr classes to override binary operators like +, - etc when used with Expr instances. This should work for non-Expr classes whether they are Basic subclasses or not. Also non-Expr classes that do not define binary operators with Expr should give TypeError. ''' # A bunch of instances of Expr subclasses exprs = [ Expr(), S.Zero, S.One, S.Infinity, S.NegativeInfinity, S.ComplexInfinity, S.Half, Float(0.5), Integer(2), Symbol('x'), Mul(2, Symbol('x')), Add(2, Symbol('x')), Pow(2, Symbol('x')), ] for e in exprs: # Test that these classes can override arithmetic operations in # combination with various Expr types. for ne in [NonBasic(), NonExpr()]: results = [ (ne + e, ('+', ne, e)), (e + ne, ('+', e, ne)), (ne - e, ('-', ne, e)), (e - ne, ('-', e, ne)), (ne * e, ('*', ne, e)), (e * ne, ('*', e, ne)), (ne / e, ('/', ne, e)), (e / ne, ('/', e, ne)), (ne // e, ('//', ne, e)), (e // ne, ('//', e, ne)), (ne % e, ('%', ne, e)), (e % ne, ('%', e, ne)), (divmod(ne, e), ('divmod', ne, e)), (divmod(e, ne), ('divmod', e, ne)), (ne ** e, ('**', ne, e)), (e ** ne, ('**', e, ne)), (e < ne, ('>', ne, e)), (ne < e, ('<', ne, e)), (e > ne, ('<', ne, e)), (ne > e, ('>', ne, e)), (e <= ne, ('>=', ne, e)), (ne <= e, ('<=', ne, e)), (e >= ne, ('<=', ne, e)), (ne >= e, ('>=', ne, e)), ] for res, args in results: assert type(res) is SpecialOp and res.args == args # These classes do not support binary operators with Expr. Every # operation should raise in combination with any of the Expr types. for na in [NonArithmetic(), object()]: raises(TypeError, lambda : e + na) raises(TypeError, lambda : na + e) raises(TypeError, lambda : e - na) raises(TypeError, lambda : na - e) raises(TypeError, lambda : e * na) raises(TypeError, lambda : na * e) raises(TypeError, lambda : e / na) raises(TypeError, lambda : na / e) raises(TypeError, lambda : e // na) raises(TypeError, lambda : na // e) raises(TypeError, lambda : e % na) raises(TypeError, lambda : na % e) raises(TypeError, lambda : divmod(e, na)) raises(TypeError, lambda : divmod(na, e)) raises(TypeError, lambda : e ** na) raises(TypeError, lambda : na ** e) raises(TypeError, lambda : e > na) raises(TypeError, lambda : na > e) raises(TypeError, lambda : e < na) raises(TypeError, lambda : na < e) raises(TypeError, lambda : e >= na) raises(TypeError, lambda : na >= e) raises(TypeError, lambda : e <= na) raises(TypeError, lambda : na <= e) def test_relational(): from sympy import Lt assert (pi < 3) is S.false assert (pi <= 3) is S.false assert (pi > 3) is S.true assert (pi >= 3) is S.true assert (-pi < 3) is S.true assert (-pi <= 3) is S.true assert (-pi > 3) is S.false assert (-pi >= 3) is S.false r = Symbol('r', real=True) assert (r - 2 < r - 3) is S.false assert Lt(x + I, x + I + 2).func == Lt # issue 8288 def test_relational_assumptions(): from sympy import Lt, Gt, Le, Ge m1 = Symbol("m1", nonnegative=False) m2 = Symbol("m2", positive=False) m3 = Symbol("m3", nonpositive=False) m4 = Symbol("m4", negative=False) assert (m1 < 0) == Lt(m1, 0) assert (m2 <= 0) == Le(m2, 0) assert (m3 > 0) == Gt(m3, 0) assert (m4 >= 0) == Ge(m4, 0) m1 = Symbol("m1", nonnegative=False, real=True) m2 = Symbol("m2", positive=False, real=True) m3 = Symbol("m3", nonpositive=False, real=True) m4 = Symbol("m4", negative=False, real=True) assert (m1 < 0) is S.true assert (m2 <= 0) is S.true assert (m3 > 0) is S.true assert (m4 >= 0) is S.true m1 = Symbol("m1", negative=True) m2 = Symbol("m2", nonpositive=True) m3 = Symbol("m3", positive=True) m4 = Symbol("m4", nonnegative=True) assert (m1 < 0) is S.true assert (m2 <= 0) is S.true assert (m3 > 0) is S.true assert (m4 >= 0) is S.true m1 = Symbol("m1", negative=False, real=True) m2 = Symbol("m2", nonpositive=False, real=True) m3 = Symbol("m3", positive=False, real=True) m4 = Symbol("m4", nonnegative=False, real=True) assert (m1 < 0) is S.false assert (m2 <= 0) is S.false assert (m3 > 0) is S.false assert (m4 >= 0) is S.false # See https://github.com/sympy/sympy/issues/17708 #def test_relational_noncommutative(): # from sympy import Lt, Gt, Le, Ge # A, B = symbols('A,B', commutative=False) # assert (A < B) == Lt(A, B) # assert (A <= B) == Le(A, B) # assert (A > B) == Gt(A, B) # assert (A >= B) == Ge(A, B) def test_basic_nostr(): for obj in basic_objs: raises(TypeError, lambda: obj + '1') raises(TypeError, lambda: obj - '1') if obj == 2: assert obj * '1' == '11' else: raises(TypeError, lambda: obj * '1') raises(TypeError, lambda: obj / '1') raises(TypeError, lambda: obj ** '1') def test_series_expansion_for_uniform_order(): assert (1/x + y + x).series(x, 0, 0) == 1/x + O(1, x) assert (1/x + y + x).series(x, 0, 1) == 1/x + y + O(x) assert (1/x + 1 + x).series(x, 0, 0) == 1/x + O(1, x) assert (1/x + 1 + x).series(x, 0, 1) == 1/x + 1 + O(x) assert (1/x + x).series(x, 0, 0) == 1/x + O(1, x) assert (1/x + y + y*x + x).series(x, 0, 0) == 1/x + O(1, x) assert (1/x + y + y*x + x).series(x, 0, 1) == 1/x + y + O(x) def test_leadterm(): assert (3 + 2*x**(log(3)/log(2) - 1)).leadterm(x) == (3, 0) assert (1/x**2 + 1 + x + x**2).leadterm(x)[1] == -2 assert (1/x + 1 + x + x**2).leadterm(x)[1] == -1 assert (x**2 + 1/x).leadterm(x)[1] == -1 assert (1 + x**2).leadterm(x)[1] == 0 assert (x + 1).leadterm(x)[1] == 0 assert (x + x**2).leadterm(x)[1] == 1 assert (x**2).leadterm(x)[1] == 2 def test_as_leading_term(): assert (3 + 2*x**(log(3)/log(2) - 1)).as_leading_term(x) == 3 assert (1/x**2 + 1 + x + x**2).as_leading_term(x) == 1/x**2 assert (1/x + 1 + x + x**2).as_leading_term(x) == 1/x assert (x**2 + 1/x).as_leading_term(x) == 1/x assert (1 + x**2).as_leading_term(x) == 1 assert (x + 1).as_leading_term(x) == 1 assert (x + x**2).as_leading_term(x) == x assert (x**2).as_leading_term(x) == x**2 assert (x + oo).as_leading_term(x) is oo raises(ValueError, lambda: (x + 1).as_leading_term(1)) def test_leadterm2(): assert (x*cos(1)*cos(1 + sin(1)) + sin(1 + sin(1))).leadterm(x) == \ (sin(1 + sin(1)), 0) def test_leadterm3(): assert (y + z + x).leadterm(x) == (y + z, 0) def test_as_leading_term2(): assert (x*cos(1)*cos(1 + sin(1)) + sin(1 + sin(1))).as_leading_term(x) == \ sin(1 + sin(1)) def test_as_leading_term3(): assert (2 + pi + x).as_leading_term(x) == 2 + pi assert (2*x + pi*x + x**2).as_leading_term(x) == (2 + pi)*x def test_as_leading_term4(): # see issue 6843 n = Symbol('n', integer=True, positive=True) r = -n**3/(2*n**2 + 4*n + 2) - n**2/(n**2 + 2*n + 1) + \ n**2/(n + 1) - n/(2*n**2 + 4*n + 2) + n/(n*x + x) + 2*n/(n + 1) - \ 1 + 1/(n*x + x) + 1/(n + 1) - 1/x assert r.as_leading_term(x).cancel() == n/2 def test_as_leading_term_stub(): class foo(Function): pass assert foo(1/x).as_leading_term(x) == foo(1/x) assert foo(1).as_leading_term(x) == foo(1) raises(NotImplementedError, lambda: foo(x).as_leading_term(x)) def test_as_leading_term_deriv_integral(): # related to issue 11313 assert Derivative(x ** 3, x).as_leading_term(x) == 3*x**2 assert Derivative(x ** 3, y).as_leading_term(x) == 0 assert Integral(x ** 3, x).as_leading_term(x) == x**4/4 assert Integral(x ** 3, y).as_leading_term(x) == y*x**3 assert Derivative(exp(x), x).as_leading_term(x) == 1 assert Derivative(log(x), x).as_leading_term(x) == (1/x).as_leading_term(x) def test_atoms(): assert x.atoms() == {x} assert (1 + x).atoms() == {x, S.One} assert (1 + 2*cos(x)).atoms(Symbol) == {x} assert (1 + 2*cos(x)).atoms(Symbol, Number) == {S.One, S(2), x} assert (2*(x**(y**x))).atoms() == {S(2), x, y} assert S.Half.atoms() == {S.Half} assert S.Half.atoms(Symbol) == set() assert sin(oo).atoms(oo) == set() assert Poly(0, x).atoms() == {S.Zero, x} assert Poly(1, x).atoms() == {S.One, x} assert Poly(x, x).atoms() == {x} assert Poly(x, x, y).atoms() == {x, y} assert Poly(x + y, x, y).atoms() == {x, y} assert Poly(x + y, x, y, z).atoms() == {x, y, z} assert Poly(x + y*t, x, y, z).atoms() == {t, x, y, z} assert (I*pi).atoms(NumberSymbol) == {pi} assert (I*pi).atoms(NumberSymbol, I) == \ (I*pi).atoms(I, NumberSymbol) == {pi, I} assert exp(exp(x)).atoms(exp) == {exp(exp(x)), exp(x)} assert (1 + x*(2 + y) + exp(3 + z)).atoms(Add) == \ {1 + x*(2 + y) + exp(3 + z), 2 + y, 3 + z} # issue 6132 f = Function('f') e = (f(x) + sin(x) + 2) assert e.atoms(AppliedUndef) == \ {f(x)} assert e.atoms(AppliedUndef, Function) == \ {f(x), sin(x)} assert e.atoms(Function) == \ {f(x), sin(x)} assert e.atoms(AppliedUndef, Number) == \ {f(x), S(2)} assert e.atoms(Function, Number) == \ {S(2), sin(x), f(x)} def test_is_polynomial(): k = Symbol('k', nonnegative=True, integer=True) assert Rational(2).is_polynomial(x, y, z) is True assert (S.Pi).is_polynomial(x, y, z) is True assert x.is_polynomial(x) is True assert x.is_polynomial(y) is True assert (x**2).is_polynomial(x) is True assert (x**2).is_polynomial(y) is True assert (x**(-2)).is_polynomial(x) is False assert (x**(-2)).is_polynomial(y) is True assert (2**x).is_polynomial(x) is False assert (2**x).is_polynomial(y) is True assert (x**k).is_polynomial(x) is False assert (x**k).is_polynomial(k) is False assert (x**x).is_polynomial(x) is False assert (k**k).is_polynomial(k) is False assert (k**x).is_polynomial(k) is False assert (x**(-k)).is_polynomial(x) is False assert ((2*x)**k).is_polynomial(x) is False assert (x**2 + 3*x - 8).is_polynomial(x) is True assert (x**2 + 3*x - 8).is_polynomial(y) is True assert (x**2 + 3*x - 8).is_polynomial() is True assert sqrt(x).is_polynomial(x) is False assert (sqrt(x)**3).is_polynomial(x) is False assert (x**2 + 3*x*sqrt(y) - 8).is_polynomial(x) is True assert (x**2 + 3*x*sqrt(y) - 8).is_polynomial(y) is False assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(2)).is_polynomial() is True assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(x)).is_polynomial() is False assert ( (x**2)*(y**2) + x*(y**2) + y*x + exp(2)).is_polynomial(x, y) is True assert ( (x**2)*(y**2) + x*(y**2) + y*x + exp(x)).is_polynomial(x, y) is False def test_is_rational_function(): assert Integer(1).is_rational_function() is True assert Integer(1).is_rational_function(x) is True assert Rational(17, 54).is_rational_function() is True assert Rational(17, 54).is_rational_function(x) is True assert (12/x).is_rational_function() is True assert (12/x).is_rational_function(x) is True assert (x/y).is_rational_function() is True assert (x/y).is_rational_function(x) is True assert (x/y).is_rational_function(x, y) is True assert (x**2 + 1/x/y).is_rational_function() is True assert (x**2 + 1/x/y).is_rational_function(x) is True assert (x**2 + 1/x/y).is_rational_function(x, y) is True assert (sin(y)/x).is_rational_function() is False assert (sin(y)/x).is_rational_function(y) is False assert (sin(y)/x).is_rational_function(x) is True assert (sin(y)/x).is_rational_function(x, y) is False assert (S.NaN).is_rational_function() is False assert (S.Infinity).is_rational_function() is False assert (S.NegativeInfinity).is_rational_function() is False assert (S.ComplexInfinity).is_rational_function() is False def test_is_meromorphic(): f = a/x**2 + b + x + c*x**2 assert f.is_meromorphic(x, 0) is True assert f.is_meromorphic(x, 1) is True assert f.is_meromorphic(x, zoo) is True g = 3 + 2*x**(log(3)/log(2) - 1) assert g.is_meromorphic(x, 0) is False assert g.is_meromorphic(x, 1) is True assert g.is_meromorphic(x, zoo) is False n = Symbol('n', integer=True) h = sin(1/x)**n*x assert h.is_meromorphic(x, 0) is False assert h.is_meromorphic(x, 1) is True assert h.is_meromorphic(x, zoo) is False e = log(x)**pi assert e.is_meromorphic(x, 0) is False assert e.is_meromorphic(x, 1) is False assert e.is_meromorphic(x, 2) is True assert e.is_meromorphic(x, zoo) is False assert (log(x)**a).is_meromorphic(x, 0) is False assert (log(x)**a).is_meromorphic(x, 1) is False assert (a**log(x)).is_meromorphic(x, 0) is None assert (3**log(x)).is_meromorphic(x, 0) is False assert (3**log(x)).is_meromorphic(x, 1) is True def test_is_algebraic_expr(): assert sqrt(3).is_algebraic_expr(x) is True assert sqrt(3).is_algebraic_expr() is True eq = ((1 + x**2)/(1 - y**2))**(S.One/3) assert eq.is_algebraic_expr(x) is True assert eq.is_algebraic_expr(y) is True assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr(x) is True assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr(y) is True assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr() is True assert (cos(y)/sqrt(x)).is_algebraic_expr() is False assert (cos(y)/sqrt(x)).is_algebraic_expr(x) is True assert (cos(y)/sqrt(x)).is_algebraic_expr(y) is False assert (cos(y)/sqrt(x)).is_algebraic_expr(x, y) is False def test_SAGE1(): #see https://github.com/sympy/sympy/issues/3346 class MyInt: def _sympy_(self): return Integer(5) m = MyInt() e = Rational(2)*m assert e == 10 raises(TypeError, lambda: Rational(2)*MyInt) def test_SAGE2(): class MyInt: def __int__(self): return 5 assert sympify(MyInt()) == 5 e = Rational(2)*MyInt() assert e == 10 raises(TypeError, lambda: Rational(2)*MyInt) def test_SAGE3(): class MySymbol: def __rmul__(self, other): return ('mys', other, self) o = MySymbol() e = x*o assert e == ('mys', x, o) def test_len(): e = x*y assert len(e.args) == 2 e = x + y + z assert len(e.args) == 3 def test_doit(): a = Integral(x**2, x) assert isinstance(a.doit(), Integral) is False assert isinstance(a.doit(integrals=True), Integral) is False assert isinstance(a.doit(integrals=False), Integral) is True assert (2*Integral(x, x)).doit() == x**2 def test_attribute_error(): raises(AttributeError, lambda: x.cos()) raises(AttributeError, lambda: x.sin()) raises(AttributeError, lambda: x.exp()) def test_args(): assert (x*y).args in ((x, y), (y, x)) assert (x + y).args in ((x, y), (y, x)) assert (x*y + 1).args in ((x*y, 1), (1, x*y)) assert sin(x*y).args == (x*y,) assert sin(x*y).args[0] == x*y assert (x**y).args == (x, y) assert (x**y).args[0] == x assert (x**y).args[1] == y def test_noncommutative_expand_issue_3757(): A, B, C = symbols('A,B,C', commutative=False) assert A*B - B*A != 0 assert (A*(A + B)*B).expand() == A**2*B + A*B**2 assert (A*(A + B + C)*B).expand() == A**2*B + A*B**2 + A*C*B def test_as_numer_denom(): a, b, c = symbols('a, b, c') assert nan.as_numer_denom() == (nan, 1) assert oo.as_numer_denom() == (oo, 1) assert (-oo).as_numer_denom() == (-oo, 1) assert zoo.as_numer_denom() == (zoo, 1) assert (-zoo).as_numer_denom() == (zoo, 1) assert x.as_numer_denom() == (x, 1) assert (1/x).as_numer_denom() == (1, x) assert (x/y).as_numer_denom() == (x, y) assert (x/2).as_numer_denom() == (x, 2) assert (x*y/z).as_numer_denom() == (x*y, z) assert (x/(y*z)).as_numer_denom() == (x, y*z) assert S.Half.as_numer_denom() == (1, 2) assert (1/y**2).as_numer_denom() == (1, y**2) assert (x/y**2).as_numer_denom() == (x, y**2) assert ((x**2 + 1)/y).as_numer_denom() == (x**2 + 1, y) assert (x*(y + 1)/y**7).as_numer_denom() == (x*(y + 1), y**7) assert (x**-2).as_numer_denom() == (1, x**2) assert (a/x + b/2/x + c/3/x).as_numer_denom() == \ (6*a + 3*b + 2*c, 6*x) assert (a/x + b/2/x + c/3/y).as_numer_denom() == \ (2*c*x + y*(6*a + 3*b), 6*x*y) assert (a/x + b/2/x + c/.5/x).as_numer_denom() == \ (2*a + b + 4.0*c, 2*x) # this should take no more than a few seconds assert int(log(Add(*[Dummy()/i/x for i in range(1, 705)] ).as_numer_denom()[1]/x).n(4)) == 705 for i in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]: assert (i + x/3).as_numer_denom() == \ (x + i, 3) assert (S.Infinity + x/3 + y/4).as_numer_denom() == \ (4*x + 3*y + S.Infinity, 12) assert (oo*x + zoo*y).as_numer_denom() == \ (zoo*y + oo*x, 1) A, B, C = symbols('A,B,C', commutative=False) assert (A*B*C**-1).as_numer_denom() == (A*B*C**-1, 1) assert (A*B*C**-1/x).as_numer_denom() == (A*B*C**-1, x) assert (C**-1*A*B).as_numer_denom() == (C**-1*A*B, 1) assert (C**-1*A*B/x).as_numer_denom() == (C**-1*A*B, x) assert ((A*B*C)**-1).as_numer_denom() == ((A*B*C)**-1, 1) assert ((A*B*C)**-1/x).as_numer_denom() == ((A*B*C)**-1, x) def test_trunc(): import math x, y = symbols('x y') assert math.trunc(2) == 2 assert math.trunc(4.57) == 4 assert math.trunc(-5.79) == -5 assert math.trunc(pi) == 3 assert math.trunc(log(7)) == 1 assert math.trunc(exp(5)) == 148 assert math.trunc(cos(pi)) == -1 assert math.trunc(sin(5)) == 0 raises(TypeError, lambda: math.trunc(x)) raises(TypeError, lambda: math.trunc(x + y**2)) raises(TypeError, lambda: math.trunc(oo)) def test_as_independent(): assert S.Zero.as_independent(x, as_Add=True) == (0, 0) assert S.Zero.as_independent(x, as_Add=False) == (0, 0) assert (2*x*sin(x) + y + x).as_independent(x) == (y, x + 2*x*sin(x)) assert (2*x*sin(x) + y + x).as_independent(y) == (x + 2*x*sin(x), y) assert (2*x*sin(x) + y + x).as_independent(x, y) == (0, y + x + 2*x*sin(x)) assert (x*sin(x)*cos(y)).as_independent(x) == (cos(y), x*sin(x)) assert (x*sin(x)*cos(y)).as_independent(y) == (x*sin(x), cos(y)) assert (x*sin(x)*cos(y)).as_independent(x, y) == (1, x*sin(x)*cos(y)) assert (sin(x)).as_independent(x) == (1, sin(x)) assert (sin(x)).as_independent(y) == (sin(x), 1) assert (2*sin(x)).as_independent(x) == (2, sin(x)) assert (2*sin(x)).as_independent(y) == (2*sin(x), 1) # issue 4903 = 1766b n1, n2, n3 = symbols('n1 n2 n3', commutative=False) assert (n1 + n1*n2).as_independent(n2) == (n1, n1*n2) assert (n2*n1 + n1*n2).as_independent(n2) == (0, n1*n2 + n2*n1) assert (n1*n2*n1).as_independent(n2) == (n1, n2*n1) assert (n1*n2*n1).as_independent(n1) == (1, n1*n2*n1) assert (3*x).as_independent(x, as_Add=True) == (0, 3*x) assert (3*x).as_independent(x, as_Add=False) == (3, x) assert (3 + x).as_independent(x, as_Add=True) == (3, x) assert (3 + x).as_independent(x, as_Add=False) == (1, 3 + x) # issue 5479 assert (3*x).as_independent(Symbol) == (3, x) # issue 5648 assert (n1*x*y).as_independent(x) == (n1*y, x) assert ((x + n1)*(x - y)).as_independent(x) == (1, (x + n1)*(x - y)) assert ((x + n1)*(x - y)).as_independent(y) == (x + n1, x - y) assert (DiracDelta(x - n1)*DiracDelta(x - y)).as_independent(x) \ == (1, DiracDelta(x - n1)*DiracDelta(x - y)) assert (x*y*n1*n2*n3).as_independent(n2) == (x*y*n1, n2*n3) assert (x*y*n1*n2*n3).as_independent(n1) == (x*y, n1*n2*n3) assert (x*y*n1*n2*n3).as_independent(n3) == (x*y*n1*n2, n3) assert (DiracDelta(x - n1)*DiracDelta(y - n1)*DiracDelta(x - n2)).as_independent(y) == \ (DiracDelta(x - n1)*DiracDelta(x - n2), DiracDelta(y - n1)) # issue 5784 assert (x + Integral(x, (x, 1, 2))).as_independent(x, strict=True) == \ (Integral(x, (x, 1, 2)), x) eq = Add(x, -x, 2, -3, evaluate=False) assert eq.as_independent(x) == (-1, Add(x, -x, evaluate=False)) eq = Mul(x, 1/x, 2, -3, evaluate=False) eq.as_independent(x) == (-6, Mul(x, 1/x, evaluate=False)) assert (x*y).as_independent(z, as_Add=True) == (x*y, 0) @XFAIL def test_call_2(): # TODO UndefinedFunction does not subclass Expr f = Function('f') assert (2*f)(x) == 2*f(x) def test_replace(): f = log(sin(x)) + tan(sin(x**2)) assert f.replace(sin, cos) == log(cos(x)) + tan(cos(x**2)) assert f.replace( sin, lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2)) a = Wild('a') b = Wild('b') assert f.replace(sin(a), cos(a)) == log(cos(x)) + tan(cos(x**2)) assert f.replace( sin(a), lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2)) # test exact assert (2*x).replace(a*x + b, b - a, exact=True) == 2*x assert (2*x).replace(a*x + b, b - a) == 2*x assert (2*x).replace(a*x + b, b - a, exact=False) == 2/x assert (2*x).replace(a*x + b, lambda a, b: b - a, exact=True) == 2*x assert (2*x).replace(a*x + b, lambda a, b: b - a) == 2*x assert (2*x).replace(a*x + b, lambda a, b: b - a, exact=False) == 2/x g = 2*sin(x**3) assert g.replace( lambda expr: expr.is_Number, lambda expr: expr**2) == 4*sin(x**9) assert cos(x).replace(cos, sin, map=True) == (sin(x), {cos(x): sin(x)}) assert sin(x).replace(cos, sin) == sin(x) cond, func = lambda x: x.is_Mul, lambda x: 2*x assert (x*y).replace(cond, func, map=True) == (2*x*y, {x*y: 2*x*y}) assert (x*(1 + x*y)).replace(cond, func, map=True) == \ (2*x*(2*x*y + 1), {x*(2*x*y + 1): 2*x*(2*x*y + 1), x*y: 2*x*y}) assert (y*sin(x)).replace(sin, lambda expr: sin(expr)/y, map=True) == \ (sin(x), {sin(x): sin(x)/y}) # if not simultaneous then y*sin(x) -> y*sin(x)/y = sin(x) -> sin(x)/y assert (y*sin(x)).replace(sin, lambda expr: sin(expr)/y, simultaneous=False) == sin(x)/y assert (x**2 + O(x**3)).replace(Pow, lambda b, e: b**e/e ) == x**2/2 + O(x**3) assert (x**2 + O(x**3)).replace(Pow, lambda b, e: b**e/e, simultaneous=False) == x**2/2 + O(x**3) assert (x*(x*y + 3)).replace(lambda x: x.is_Mul, lambda x: 2 + x) == \ x*(x*y + 5) + 2 e = (x*y + 1)*(2*x*y + 1) + 1 assert e.replace(cond, func, map=True) == ( 2*((2*x*y + 1)*(4*x*y + 1)) + 1, {2*x*y: 4*x*y, x*y: 2*x*y, (2*x*y + 1)*(4*x*y + 1): 2*((2*x*y + 1)*(4*x*y + 1))}) assert x.replace(x, y) == y assert (x + 1).replace(1, 2) == x + 2 # https://groups.google.com/forum/#!topic/sympy/8wCgeC95tz0 n1, n2, n3 = symbols('n1:4', commutative=False) f = Function('f') assert (n1*f(n2)).replace(f, lambda x: x) == n1*n2 assert (n3*f(n2)).replace(f, lambda x: x) == n3*n2 # issue 16725 assert S.Zero.replace(Wild('x'), 1) == 1 # let the user override the default decision of False assert S.Zero.replace(Wild('x'), 1, exact=True) == 0 def test_find(): expr = (x + y + 2 + sin(3*x)) assert expr.find(lambda u: u.is_Integer) == {S(2), S(3)} assert expr.find(lambda u: u.is_Symbol) == {x, y} assert expr.find(lambda u: u.is_Integer, group=True) == {S(2): 1, S(3): 1} assert expr.find(lambda u: u.is_Symbol, group=True) == {x: 2, y: 1} assert expr.find(Integer) == {S(2), S(3)} assert expr.find(Symbol) == {x, y} assert expr.find(Integer, group=True) == {S(2): 1, S(3): 1} assert expr.find(Symbol, group=True) == {x: 2, y: 1} a = Wild('a') expr = sin(sin(x)) + sin(x) + cos(x) + x assert expr.find(lambda u: type(u) is sin) == {sin(x), sin(sin(x))} assert expr.find( lambda u: type(u) is sin, group=True) == {sin(x): 2, sin(sin(x)): 1} assert expr.find(sin(a)) == {sin(x), sin(sin(x))} assert expr.find(sin(a), group=True) == {sin(x): 2, sin(sin(x)): 1} assert expr.find(sin) == {sin(x), sin(sin(x))} assert expr.find(sin, group=True) == {sin(x): 2, sin(sin(x)): 1} def test_count(): expr = (x + y + 2 + sin(3*x)) assert expr.count(lambda u: u.is_Integer) == 2 assert expr.count(lambda u: u.is_Symbol) == 3 assert expr.count(Integer) == 2 assert expr.count(Symbol) == 3 assert expr.count(2) == 1 a = Wild('a') assert expr.count(sin) == 1 assert expr.count(sin(a)) == 1 assert expr.count(lambda u: type(u) is sin) == 1 f = Function('f') assert f(x).count(f(x)) == 1 assert f(x).diff(x).count(f(x)) == 1 assert f(x).diff(x).count(x) == 2 def test_has_basics(): f = Function('f') g = Function('g') p = Wild('p') assert sin(x).has(x) assert sin(x).has(sin) assert not sin(x).has(y) assert not sin(x).has(cos) assert f(x).has(x) assert f(x).has(f) assert not f(x).has(y) assert not f(x).has(g) assert f(x).diff(x).has(x) assert f(x).diff(x).has(f) assert f(x).diff(x).has(Derivative) assert not f(x).diff(x).has(y) assert not f(x).diff(x).has(g) assert not f(x).diff(x).has(sin) assert (x**2).has(Symbol) assert not (x**2).has(Wild) assert (2*p).has(Wild) assert not x.has() def test_has_multiple(): f = x**2*y + sin(2**t + log(z)) assert f.has(x) assert f.has(y) assert f.has(z) assert f.has(t) assert not f.has(u) assert f.has(x, y, z, t) assert f.has(x, y, z, t, u) i = Integer(4400) assert not i.has(x) assert (i*x**i).has(x) assert not (i*y**i).has(x) assert (i*y**i).has(x, y) assert not (i*y**i).has(x, z) def test_has_piecewise(): f = (x*y + 3/y)**(3 + 2) g = Function('g') h = Function('h') p = Piecewise((g(x), x < -1), (1, x <= 1), (f, True)) assert p.has(x) assert p.has(y) assert not p.has(z) assert p.has(1) assert p.has(3) assert not p.has(4) assert p.has(f) assert p.has(g) assert not p.has(h) def test_has_iterative(): A, B, C = symbols('A,B,C', commutative=False) f = x*gamma(x)*sin(x)*exp(x*y)*A*B*C*cos(x*A*B) assert f.has(x) assert f.has(x*y) assert f.has(x*sin(x)) assert not f.has(x*sin(y)) assert f.has(x*A) assert f.has(x*A*B) assert not f.has(x*A*C) assert f.has(x*A*B*C) assert not f.has(x*A*C*B) assert f.has(x*sin(x)*A*B*C) assert not f.has(x*sin(x)*A*C*B) assert not f.has(x*sin(y)*A*B*C) assert f.has(x*gamma(x)) assert not f.has(x + sin(x)) assert (x & y & z).has(x & z) def test_has_integrals(): f = Integral(x**2 + sin(x*y*z), (x, 0, x + y + z)) assert f.has(x + y) assert f.has(x + z) assert f.has(y + z) assert f.has(x*y) assert f.has(x*z) assert f.has(y*z) assert not f.has(2*x + y) assert not f.has(2*x*y) def test_has_tuple(): f = Function('f') g = Function('g') h = Function('h') assert Tuple(x, y).has(x) assert not Tuple(x, y).has(z) assert Tuple(f(x), g(x)).has(x) assert not Tuple(f(x), g(x)).has(y) assert Tuple(f(x), g(x)).has(f) assert Tuple(f(x), g(x)).has(f(x)) assert not Tuple(f, g).has(x) assert Tuple(f, g).has(f) assert not Tuple(f, g).has(h) assert Tuple(True).has(True) is True # .has(1) will also be True def test_has_units(): from sympy.physics.units import m, s assert (x*m/s).has(x) assert (x*m/s).has(y, z) is False def test_has_polys(): poly = Poly(x**2 + x*y*sin(z), x, y, t) assert poly.has(x) assert poly.has(x, y, z) assert poly.has(x, y, z, t) def test_has_physics(): assert FockState((x, y)).has(x) def test_as_poly_as_expr(): f = x**2 + 2*x*y assert f.as_poly().as_expr() == f assert f.as_poly(x, y).as_expr() == f assert (f + sin(x)).as_poly(x, y) is None p = Poly(f, x, y) assert p.as_poly() == p raises(AttributeError, lambda: Tuple(x, x).as_poly(x)) raises(AttributeError, lambda: Tuple(x ** 2, x, y).as_poly(x)) def test_nonzero(): assert bool(S.Zero) is False assert bool(S.One) is True assert bool(x) is True assert bool(x + y) is True assert bool(x - x) is False assert bool(x*y) is True assert bool(x*1) is True assert bool(x*0) is False def test_is_number(): assert Float(3.14).is_number is True assert Integer(737).is_number is True assert Rational(3, 2).is_number is True assert Rational(8).is_number is True assert x.is_number is False assert (2*x).is_number is False assert (x + y).is_number is False assert log(2).is_number is True assert log(x).is_number is False assert (2 + log(2)).is_number is True assert (8 + log(2)).is_number is True assert (2 + log(x)).is_number is False assert (8 + log(2) + x).is_number is False assert (1 + x**2/x - x).is_number is True assert Tuple(Integer(1)).is_number is False assert Add(2, x).is_number is False assert Mul(3, 4).is_number is True assert Pow(log(2), 2).is_number is True assert oo.is_number is True g = WildFunction('g') assert g.is_number is False assert (2*g).is_number is False assert (x**2).subs(x, 3).is_number is True # test extensibility of .is_number # on subinstances of Basic class A(Basic): pass a = A() assert a.is_number is False def test_as_coeff_add(): assert S(2).as_coeff_add() == (2, ()) assert S(3.0).as_coeff_add() == (0, (S(3.0),)) assert S(-3.0).as_coeff_add() == (0, (S(-3.0),)) assert x.as_coeff_add() == (0, (x,)) assert (x - 1).as_coeff_add() == (-1, (x,)) assert (x + 1).as_coeff_add() == (1, (x,)) assert (x + 2).as_coeff_add() == (2, (x,)) assert (x + y).as_coeff_add(y) == (x, (y,)) assert (3*x).as_coeff_add(y) == (3*x, ()) # don't do expansion e = (x + y)**2 assert e.as_coeff_add(y) == (0, (e,)) def test_as_coeff_mul(): assert S(2).as_coeff_mul() == (2, ()) assert S(3.0).as_coeff_mul() == (1, (S(3.0),)) assert S(-3.0).as_coeff_mul() == (-1, (S(3.0),)) assert S(-3.0).as_coeff_mul(rational=False) == (-S(3.0), ()) assert x.as_coeff_mul() == (1, (x,)) assert (-x).as_coeff_mul() == (-1, (x,)) assert (2*x).as_coeff_mul() == (2, (x,)) assert (x*y).as_coeff_mul(y) == (x, (y,)) assert (3 + x).as_coeff_mul() == (1, (3 + x,)) assert (3 + x).as_coeff_mul(y) == (3 + x, ()) # don't do expansion e = exp(x + y) assert e.as_coeff_mul(y) == (1, (e,)) e = 2**(x + y) assert e.as_coeff_mul(y) == (1, (e,)) assert (1.1*x).as_coeff_mul(rational=False) == (1.1, (x,)) assert (1.1*x).as_coeff_mul() == (1, (1.1, x)) assert (-oo*x).as_coeff_mul(rational=True) == (-1, (oo, x)) def test_as_coeff_exponent(): assert (3*x**4).as_coeff_exponent(x) == (3, 4) assert (2*x**3).as_coeff_exponent(x) == (2, 3) assert (4*x**2).as_coeff_exponent(x) == (4, 2) assert (6*x**1).as_coeff_exponent(x) == (6, 1) assert (3*x**0).as_coeff_exponent(x) == (3, 0) assert (2*x**0).as_coeff_exponent(x) == (2, 0) assert (1*x**0).as_coeff_exponent(x) == (1, 0) assert (0*x**0).as_coeff_exponent(x) == (0, 0) assert (-1*x**0).as_coeff_exponent(x) == (-1, 0) assert (-2*x**0).as_coeff_exponent(x) == (-2, 0) assert (2*x**3 + pi*x**3).as_coeff_exponent(x) == (2 + pi, 3) assert (x*log(2)/(2*x + pi*x)).as_coeff_exponent(x) == \ (log(2)/(2 + pi), 0) # issue 4784 D = Derivative f = Function('f') fx = D(f(x), x) assert fx.as_coeff_exponent(f(x)) == (fx, 0) def test_extractions(): assert ((x*y)**3).extract_multiplicatively(x**2 * y) == x*y**2 assert ((x*y)**3).extract_multiplicatively(x**4 * y) is None assert (2*x).extract_multiplicatively(2) == x assert (2*x).extract_multiplicatively(3) is None assert (2*x).extract_multiplicatively(-1) is None assert (S.Half*x).extract_multiplicatively(3) == x/6 assert (sqrt(x)).extract_multiplicatively(x) is None assert (sqrt(x)).extract_multiplicatively(1/x) is None assert x.extract_multiplicatively(-x) is None assert (-2 - 4*I).extract_multiplicatively(-2) == 1 + 2*I assert (-2 - 4*I).extract_multiplicatively(3) is None assert (-2*x - 4*y - 8).extract_multiplicatively(-2) == x + 2*y + 4 assert (-2*x*y - 4*x**2*y).extract_multiplicatively(-2*y) == 2*x**2 + x assert (2*x*y + 4*x**2*y).extract_multiplicatively(2*y) == 2*x**2 + x assert (-4*y**2*x).extract_multiplicatively(-3*y) is None assert (2*x).extract_multiplicatively(1) == 2*x assert (-oo).extract_multiplicatively(5) is -oo assert (oo).extract_multiplicatively(5) is oo assert ((x*y)**3).extract_additively(1) is None assert (x + 1).extract_additively(x) == 1 assert (x + 1).extract_additively(2*x) is None assert (x + 1).extract_additively(-x) is None assert (-x + 1).extract_additively(2*x) is None assert (2*x + 3).extract_additively(x) == x + 3 assert (2*x + 3).extract_additively(2) == 2*x + 1 assert (2*x + 3).extract_additively(3) == 2*x assert (2*x + 3).extract_additively(-2) is None assert (2*x + 3).extract_additively(3*x) is None assert (2*x + 3).extract_additively(2*x) == 3 assert x.extract_additively(0) == x assert S(2).extract_additively(x) is None assert S(2.).extract_additively(2) is S.Zero assert S(2*x + 3).extract_additively(x + 1) == x + 2 assert S(2*x + 3).extract_additively(y + 1) is None assert S(2*x - 3).extract_additively(x + 1) is None assert S(2*x - 3).extract_additively(y + z) is None assert ((a + 1)*x*4 + y).extract_additively(x).expand() == \ 4*a*x + 3*x + y assert ((a + 1)*x*4 + 3*y).extract_additively(x + 2*y).expand() == \ 4*a*x + 3*x + y assert (y*(x + 1)).extract_additively(x + 1) is None assert ((y + 1)*(x + 1) + 3).extract_additively(x + 1) == \ y*(x + 1) + 3 assert ((x + y)*(x + 1) + x + y + 3).extract_additively(x + y) == \ x*(x + y) + 3 assert (x + y + 2*((x + y)*(x + 1)) + 3).extract_additively((x + y)*(x + 1)) == \ x + y + (x + 1)*(x + y) + 3 assert ((y + 1)*(x + 2*y + 1) + 3).extract_additively(y + 1) == \ (x + 2*y)*(y + 1) + 3 n = Symbol("n", integer=True) assert (Integer(-3)).could_extract_minus_sign() is True assert (-n*x + x).could_extract_minus_sign() != \ (n*x - x).could_extract_minus_sign() assert (x - y).could_extract_minus_sign() != \ (-x + y).could_extract_minus_sign() assert (1 - x - y).could_extract_minus_sign() is True assert (1 - x + y).could_extract_minus_sign() is False assert ((-x - x*y)/y).could_extract_minus_sign() is True assert (-(x + x*y)/y).could_extract_minus_sign() is True assert ((x + x*y)/(-y)).could_extract_minus_sign() is True assert ((x + x*y)/y).could_extract_minus_sign() is False assert (x*(-x - x**3)).could_extract_minus_sign() is True assert ((-x - y)/(x + y)).could_extract_minus_sign() is True class sign_invariant(Function, Expr): nargs = 1 def __neg__(self): return self foo = sign_invariant(x) assert foo == -foo assert foo.could_extract_minus_sign() is False # The results of each of these will vary on different machines, e.g. # the first one might be False and the other (then) is true or vice versa, # so both are included. assert ((-x - y)/(x - y)).could_extract_minus_sign() is False or \ ((-x - y)/(y - x)).could_extract_minus_sign() is False assert (x - y).could_extract_minus_sign() is False assert (-x + y).could_extract_minus_sign() is True # check that result is canonical eq = (3*x + 15*y).extract_multiplicatively(3) assert eq.args == eq.func(*eq.args).args def test_nan_extractions(): for r in (1, 0, I, nan): assert nan.extract_additively(r) is None assert nan.extract_multiplicatively(r) is None def test_coeff(): assert (x + 1).coeff(x + 1) == 1 assert (3*x).coeff(0) == 0 assert (z*(1 + x)*x**2).coeff(1 + x) == z*x**2 assert (1 + 2*x*x**(1 + x)).coeff(x*x**(1 + x)) == 2 assert (1 + 2*x**(y + z)).coeff(x**(y + z)) == 2 assert (3 + 2*x + 4*x**2).coeff(1) == 0 assert (3 + 2*x + 4*x**2).coeff(-1) == 0 assert (3 + 2*x + 4*x**2).coeff(x) == 2 assert (3 + 2*x + 4*x**2).coeff(x**2) == 4 assert (3 + 2*x + 4*x**2).coeff(x**3) == 0 assert (-x/8 + x*y).coeff(x) == Rational(-1, 8) + y assert (-x/8 + x*y).coeff(-x) == S.One/8 assert (4*x).coeff(2*x) == 0 assert (2*x).coeff(2*x) == 1 assert (-oo*x).coeff(x*oo) == -1 assert (10*x).coeff(x, 0) == 0 assert (10*x).coeff(10*x, 0) == 0 n1, n2 = symbols('n1 n2', commutative=False) assert (n1*n2).coeff(n1) == 1 assert (n1*n2).coeff(n2) == n1 assert (n1*n2 + x*n1).coeff(n1) == 1 # 1*n1*(n2+x) assert (n2*n1 + x*n1).coeff(n1) == n2 + x assert (n2*n1 + x*n1**2).coeff(n1) == n2 assert (n1**x).coeff(n1) == 0 assert (n1*n2 + n2*n1).coeff(n1) == 0 assert (2*(n1 + n2)*n2).coeff(n1 + n2, right=1) == n2 assert (2*(n1 + n2)*n2).coeff(n1 + n2, right=0) == 2 f = Function('f') assert (2*f(x) + 3*f(x).diff(x)).coeff(f(x)) == 2 expr = z*(x + y)**2 expr2 = z*(x + y)**2 + z*(2*x + 2*y)**2 assert expr.coeff(z) == (x + y)**2 assert expr.coeff(x + y) == 0 assert expr2.coeff(z) == (x + y)**2 + (2*x + 2*y)**2 assert (x + y + 3*z).coeff(1) == x + y assert (-x + 2*y).coeff(-1) == x assert (x - 2*y).coeff(-1) == 2*y assert (3 + 2*x + 4*x**2).coeff(1) == 0 assert (-x - 2*y).coeff(2) == -y assert (x + sqrt(2)*x).coeff(sqrt(2)) == x assert (3 + 2*x + 4*x**2).coeff(x) == 2 assert (3 + 2*x + 4*x**2).coeff(x**2) == 4 assert (3 + 2*x + 4*x**2).coeff(x**3) == 0 assert (z*(x + y)**2).coeff((x + y)**2) == z assert (z*(x + y)**2).coeff(x + y) == 0 assert (2 + 2*x + (x + 1)*y).coeff(x + 1) == y assert (x + 2*y + 3).coeff(1) == x assert (x + 2*y + 3).coeff(x, 0) == 2*y + 3 assert (x**2 + 2*y + 3*x).coeff(x**2, 0) == 2*y + 3*x assert x.coeff(0, 0) == 0 assert x.coeff(x, 0) == 0 n, m, o, l = symbols('n m o l', commutative=False) assert n.coeff(n) == 1 assert y.coeff(n) == 0 assert (3*n).coeff(n) == 3 assert (2 + n).coeff(x*m) == 0 assert (2*x*n*m).coeff(x) == 2*n*m assert (2 + n).coeff(x*m*n + y) == 0 assert (2*x*n*m).coeff(3*n) == 0 assert (n*m + m*n*m).coeff(n) == 1 + m assert (n*m + m*n*m).coeff(n, right=True) == m # = (1 + m)*n*m assert (n*m + m*n).coeff(n) == 0 assert (n*m + o*m*n).coeff(m*n) == o assert (n*m + o*m*n).coeff(m*n, right=1) == 1 assert (n*m + n*m*n).coeff(n*m, right=1) == 1 + n # = n*m*(n + 1) assert (x*y).coeff(z, 0) == x*y def test_coeff2(): r, kappa = symbols('r, kappa') psi = Function("psi") g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2)) g = g.expand() assert g.coeff(psi(r).diff(r)) == 2/r def test_coeff2_0(): r, kappa = symbols('r, kappa') psi = Function("psi") g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2)) g = g.expand() assert g.coeff(psi(r).diff(r, 2)) == 1 def test_coeff_expand(): expr = z*(x + y)**2 expr2 = z*(x + y)**2 + z*(2*x + 2*y)**2 assert expr.coeff(z) == (x + y)**2 assert expr2.coeff(z) == (x + y)**2 + (2*x + 2*y)**2 def test_integrate(): assert x.integrate(x) == x**2/2 assert x.integrate((x, 0, 1)) == S.Half def test_as_base_exp(): assert x.as_base_exp() == (x, S.One) assert (x*y*z).as_base_exp() == (x*y*z, S.One) assert (x + y + z).as_base_exp() == (x + y + z, S.One) assert ((x + y)**z).as_base_exp() == (x + y, z) def test_issue_4963(): assert hasattr(Mul(x, y), "is_commutative") assert hasattr(Mul(x, y, evaluate=False), "is_commutative") assert hasattr(Pow(x, y), "is_commutative") assert hasattr(Pow(x, y, evaluate=False), "is_commutative") expr = Mul(Pow(2, 2, evaluate=False), 3, evaluate=False) + 1 assert hasattr(expr, "is_commutative") def test_action_verbs(): assert nsimplify(1/(exp(3*pi*x/5) + 1)) == \ (1/(exp(3*pi*x/5) + 1)).nsimplify() assert ratsimp(1/x + 1/y) == (1/x + 1/y).ratsimp() assert trigsimp(log(x), deep=True) == (log(x)).trigsimp(deep=True) assert radsimp(1/(2 + sqrt(2))) == (1/(2 + sqrt(2))).radsimp() assert radsimp(1/(a + b*sqrt(c)), symbolic=False) == \ (1/(a + b*sqrt(c))).radsimp(symbolic=False) assert powsimp(x**y*x**z*y**z, combine='all') == \ (x**y*x**z*y**z).powsimp(combine='all') assert (x**t*y**t).powsimp(force=True) == (x*y)**t assert simplify(x**y*x**z*y**z) == (x**y*x**z*y**z).simplify() assert together(1/x + 1/y) == (1/x + 1/y).together() assert collect(a*x**2 + b*x**2 + a*x - b*x + c, x) == \ (a*x**2 + b*x**2 + a*x - b*x + c).collect(x) assert apart(y/(y + 2)/(y + 1), y) == (y/(y + 2)/(y + 1)).apart(y) assert combsimp(y/(x + 2)/(x + 1)) == (y/(x + 2)/(x + 1)).combsimp() assert gammasimp(gamma(x)/gamma(x-5)) == (gamma(x)/gamma(x-5)).gammasimp() assert factor(x**2 + 5*x + 6) == (x**2 + 5*x + 6).factor() assert refine(sqrt(x**2)) == sqrt(x**2).refine() assert cancel((x**2 + 5*x + 6)/(x + 2)) == ((x**2 + 5*x + 6)/(x + 2)).cancel() def test_as_powers_dict(): assert x.as_powers_dict() == {x: 1} assert (x**y*z).as_powers_dict() == {x: y, z: 1} assert Mul(2, 2, evaluate=False).as_powers_dict() == {S(2): S(2)} assert (x*y).as_powers_dict()[z] == 0 assert (x + y).as_powers_dict()[z] == 0 def test_as_coefficients_dict(): check = [S.One, x, y, x*y, 1] assert [Add(3*x, 2*x, y, 3).as_coefficients_dict()[i] for i in check] == \ [3, 5, 1, 0, 3] assert [Add(3*x, 2*x, y, 3, evaluate=False).as_coefficients_dict()[i] for i in check] == [3, 5, 1, 0, 3] assert [(3*x*y).as_coefficients_dict()[i] for i in check] == \ [0, 0, 0, 3, 0] assert [(3.0*x*y).as_coefficients_dict()[i] for i in check] == \ [0, 0, 0, 3.0, 0] assert (3.0*x*y).as_coefficients_dict()[3.0*x*y] == 0 def test_args_cnc(): A = symbols('A', commutative=False) assert (x + A).args_cnc() == \ [[], [x + A]] assert (x + a).args_cnc() == \ [[a + x], []] assert (x*a).args_cnc() == \ [[a, x], []] assert (x*y*A*(A + 1)).args_cnc(cset=True) == \ [{x, y}, [A, 1 + A]] assert Mul(x, x, evaluate=False).args_cnc(cset=True, warn=False) == \ [{x}, []] assert Mul(x, x**2, evaluate=False).args_cnc(cset=True, warn=False) == \ [{x, x**2}, []] raises(ValueError, lambda: Mul(x, x, evaluate=False).args_cnc(cset=True)) assert Mul(x, y, x, evaluate=False).args_cnc() == \ [[x, y, x], []] # always split -1 from leading number assert (-1.*x).args_cnc() == [[-1, 1.0, x], []] def test_new_rawargs(): n = Symbol('n', commutative=False) a = x + n assert a.is_commutative is False assert a._new_rawargs(x).is_commutative assert a._new_rawargs(x, y).is_commutative assert a._new_rawargs(x, n).is_commutative is False assert a._new_rawargs(x, y, n).is_commutative is False m = x*n assert m.is_commutative is False assert m._new_rawargs(x).is_commutative assert m._new_rawargs(n).is_commutative is False assert m._new_rawargs(x, y).is_commutative assert m._new_rawargs(x, n).is_commutative is False assert m._new_rawargs(x, y, n).is_commutative is False assert m._new_rawargs(x, n, reeval=False).is_commutative is False assert m._new_rawargs(S.One) is S.One def test_issue_5226(): assert Add(evaluate=False) == 0 assert Mul(evaluate=False) == 1 assert Mul(x + y, evaluate=False).is_Add def test_free_symbols(): # free_symbols should return the free symbols of an object assert S.One.free_symbols == set() assert x.free_symbols == {x} assert Integral(x, (x, 1, y)).free_symbols == {y} assert (-Integral(x, (x, 1, y))).free_symbols == {y} assert meter.free_symbols == set() assert (meter**x).free_symbols == {x} def test_issue_5300(): x = Symbol('x', commutative=False) assert x*sqrt(2)/sqrt(6) == x*sqrt(3)/3 def test_floordiv(): from sympy.functions.elementary.integers import floor assert x // y == floor(x / y) def test_as_coeff_Mul(): assert S.Zero.as_coeff_Mul() == (S.One, S.Zero) assert Integer(3).as_coeff_Mul() == (Integer(3), Integer(1)) assert Rational(3, 4).as_coeff_Mul() == (Rational(3, 4), Integer(1)) assert Float(5.0).as_coeff_Mul() == (Float(5.0), Integer(1)) assert (Integer(3)*x).as_coeff_Mul() == (Integer(3), x) assert (Rational(3, 4)*x).as_coeff_Mul() == (Rational(3, 4), x) assert (Float(5.0)*x).as_coeff_Mul() == (Float(5.0), x) assert (Integer(3)*x*y).as_coeff_Mul() == (Integer(3), x*y) assert (Rational(3, 4)*x*y).as_coeff_Mul() == (Rational(3, 4), x*y) assert (Float(5.0)*x*y).as_coeff_Mul() == (Float(5.0), x*y) assert (x).as_coeff_Mul() == (S.One, x) assert (x*y).as_coeff_Mul() == (S.One, x*y) assert (-oo*x).as_coeff_Mul(rational=True) == (-1, oo*x) def test_as_coeff_Add(): assert Integer(3).as_coeff_Add() == (Integer(3), Integer(0)) assert Rational(3, 4).as_coeff_Add() == (Rational(3, 4), Integer(0)) assert Float(5.0).as_coeff_Add() == (Float(5.0), Integer(0)) assert (Integer(3) + x).as_coeff_Add() == (Integer(3), x) assert (Rational(3, 4) + x).as_coeff_Add() == (Rational(3, 4), x) assert (Float(5.0) + x).as_coeff_Add() == (Float(5.0), x) assert (Float(5.0) + x).as_coeff_Add(rational=True) == (0, Float(5.0) + x) assert (Integer(3) + x + y).as_coeff_Add() == (Integer(3), x + y) assert (Rational(3, 4) + x + y).as_coeff_Add() == (Rational(3, 4), x + y) assert (Float(5.0) + x + y).as_coeff_Add() == (Float(5.0), x + y) assert (x).as_coeff_Add() == (S.Zero, x) assert (x*y).as_coeff_Add() == (S.Zero, x*y) def test_expr_sorting(): f, g = symbols('f,g', cls=Function) exprs = [1/x**2, 1/x, sqrt(sqrt(x)), sqrt(x), x, sqrt(x)**3, x**2] assert sorted(exprs, key=default_sort_key) == exprs exprs = [x, 2*x, 2*x**2, 2*x**3, x**n, 2*x**n, sin(x), sin(x)**n, sin(x**2), cos(x), cos(x**2), tan(x)] assert sorted(exprs, key=default_sort_key) == exprs exprs = [x + 1, x**2 + x + 1, x**3 + x**2 + x + 1] assert sorted(exprs, key=default_sort_key) == exprs exprs = [S(4), x - 3*I/2, x + 3*I/2, x - 4*I + 1, x + 4*I + 1] assert sorted(exprs, key=default_sort_key) == exprs exprs = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)] assert sorted(exprs, key=default_sort_key) == exprs exprs = [f(x), g(x), exp(x), sin(x), cos(x), factorial(x)] assert sorted(exprs, key=default_sort_key) == exprs exprs = [Tuple(x, y), Tuple(x, z), Tuple(x, y, z)] assert sorted(exprs, key=default_sort_key) == exprs exprs = [[3], [1, 2]] assert sorted(exprs, key=default_sort_key) == exprs exprs = [[1, 2], [2, 3]] assert sorted(exprs, key=default_sort_key) == exprs exprs = [[1, 2], [1, 2, 3]] assert sorted(exprs, key=default_sort_key) == exprs exprs = [{x: -y}, {x: y}] assert sorted(exprs, key=default_sort_key) == exprs exprs = [{1}, {1, 2}] assert sorted(exprs, key=default_sort_key) == exprs a, b = exprs = [Dummy('x'), Dummy('x')] assert sorted([b, a], key=default_sort_key) == exprs def test_as_ordered_factors(): f, g = symbols('f,g', cls=Function) assert x.as_ordered_factors() == [x] assert (2*x*x**n*sin(x)*cos(x)).as_ordered_factors() \ == [Integer(2), x, x**n, sin(x), cos(x)] args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)] expr = Mul(*args) assert expr.as_ordered_factors() == args A, B = symbols('A,B', commutative=False) assert (A*B).as_ordered_factors() == [A, B] assert (B*A).as_ordered_factors() == [B, A] def test_as_ordered_terms(): f, g = symbols('f,g', cls=Function) assert x.as_ordered_terms() == [x] assert (sin(x)**2*cos(x) + sin(x)*cos(x)**2 + 1).as_ordered_terms() \ == [sin(x)**2*cos(x), sin(x)*cos(x)**2, 1] args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)] expr = Add(*args) assert expr.as_ordered_terms() == args assert (1 + 4*sqrt(3)*pi*x).as_ordered_terms() == [4*pi*x*sqrt(3), 1] assert ( 2 + 3*I).as_ordered_terms() == [2, 3*I] assert (-2 + 3*I).as_ordered_terms() == [-2, 3*I] assert ( 2 - 3*I).as_ordered_terms() == [2, -3*I] assert (-2 - 3*I).as_ordered_terms() == [-2, -3*I] assert ( 4 + 3*I).as_ordered_terms() == [4, 3*I] assert (-4 + 3*I).as_ordered_terms() == [-4, 3*I] assert ( 4 - 3*I).as_ordered_terms() == [4, -3*I] assert (-4 - 3*I).as_ordered_terms() == [-4, -3*I] f = x**2*y**2 + x*y**4 + y + 2 assert f.as_ordered_terms(order="lex") == [x**2*y**2, x*y**4, y, 2] assert f.as_ordered_terms(order="grlex") == [x*y**4, x**2*y**2, y, 2] assert f.as_ordered_terms(order="rev-lex") == [2, y, x*y**4, x**2*y**2] assert f.as_ordered_terms(order="rev-grlex") == [2, y, x**2*y**2, x*y**4] k = symbols('k') assert k.as_ordered_terms(data=True) == ([(k, ((1.0, 0.0), (1,), ()))], [k]) def test_sort_key_atomic_expr(): from sympy.physics.units import m, s assert sorted([-m, s], key=lambda arg: arg.sort_key()) == [-m, s] def test_eval_interval(): assert exp(x)._eval_interval(*Tuple(x, 0, 1)) == exp(1) - exp(0) # issue 4199 # first subs and limit gives NaN a = x/y assert a._eval_interval(x, S.Zero, oo)._eval_interval(y, oo, S.Zero) is S.NaN # second subs and limit gives NaN assert a._eval_interval(x, S.Zero, oo)._eval_interval(y, S.Zero, oo) is S.NaN # difference gives S.NaN a = x - y assert a._eval_interval(x, S.One, oo)._eval_interval(y, oo, S.One) is S.NaN raises(ValueError, lambda: x._eval_interval(x, None, None)) a = -y*Heaviside(x - y) assert a._eval_interval(x, -oo, oo) == -y assert a._eval_interval(x, oo, -oo) == y def test_eval_interval_zoo(): # Test that limit is used when zoo is returned assert Si(1/x)._eval_interval(x, S.Zero, S.One) == -pi/2 + Si(1) def test_primitive(): assert (3*(x + 1)**2).primitive() == (3, (x + 1)**2) assert (6*x + 2).primitive() == (2, 3*x + 1) assert (x/2 + 3).primitive() == (S.Half, x + 6) eq = (6*x + 2)*(x/2 + 3) assert eq.primitive()[0] == 1 eq = (2 + 2*x)**2 assert eq.primitive()[0] == 1 assert (4.0*x).primitive() == (1, 4.0*x) assert (4.0*x + y/2).primitive() == (S.Half, 8.0*x + y) assert (-2*x).primitive() == (2, -x) assert Add(5*z/7, 0.5*x, 3*y/2, evaluate=False).primitive() == \ (S.One/14, 7.0*x + 21*y + 10*z) for i in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]: assert (i + x/3).primitive() == \ (S.One/3, i + x) assert (S.Infinity + 2*x/3 + 4*y/7).primitive() == \ (S.One/21, 14*x + 12*y + oo) assert S.Zero.primitive() == (S.One, S.Zero) def test_issue_5843(): a = 1 + x assert (2*a).extract_multiplicatively(a) == 2 assert (4*a).extract_multiplicatively(2*a) == 2 assert ((3*a)*(2*a)).extract_multiplicatively(a) == 6*a def test_is_constant(): from sympy.solvers.solvers import checksol Sum(x, (x, 1, 10)).is_constant() is True Sum(x, (x, 1, n)).is_constant() is False Sum(x, (x, 1, n)).is_constant(y) is True Sum(x, (x, 1, n)).is_constant(n) is False Sum(x, (x, 1, n)).is_constant(x) is True eq = a*cos(x)**2 + a*sin(x)**2 - a eq.is_constant() is True assert eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0 assert x.is_constant() is False assert x.is_constant(y) is True assert checksol(x, x, Sum(x, (x, 1, n))) is False assert checksol(x, x, Sum(x, (x, 1, n))) is False f = Function('f') assert f(1).is_constant assert checksol(x, x, f(x)) is False assert Pow(x, S.Zero, evaluate=False).is_constant() is True # == 1 assert Pow(S.Zero, x, evaluate=False).is_constant() is False # == 0 or 1 assert (2**x).is_constant() is False assert Pow(S(2), S(3), evaluate=False).is_constant() is True z1, z2 = symbols('z1 z2', zero=True) assert (z1 + 2*z2).is_constant() is True assert meter.is_constant() is True assert (3*meter).is_constant() is True assert (x*meter).is_constant() is False def test_equals(): assert (-3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2).equals(0) assert (x**2 - 1).equals((x + 1)*(x - 1)) assert (cos(x)**2 + sin(x)**2).equals(1) assert (a*cos(x)**2 + a*sin(x)**2).equals(a) r = sqrt(2) assert (-1/(r + r*x) + 1/r/(1 + x)).equals(0) assert factorial(x + 1).equals((x + 1)*factorial(x)) assert sqrt(3).equals(2*sqrt(3)) is False assert (sqrt(5)*sqrt(3)).equals(sqrt(3)) is False assert (sqrt(5) + sqrt(3)).equals(0) is False assert (sqrt(5) + pi).equals(0) is False assert meter.equals(0) is False assert (3*meter**2).equals(0) is False eq = -(-1)**(S(3)/4)*6**(S.One/4) + (-6)**(S.One/4)*I if eq != 0: # if canonicalization makes this zero, skip the test assert eq.equals(0) assert sqrt(x).equals(0) is False # from integrate(x*sqrt(1 + 2*x), x); # diff is zero only when assumptions allow i = 2*sqrt(2)*x**(S(5)/2)*(1 + 1/(2*x))**(S(5)/2)/5 + \ 2*sqrt(2)*x**(S(3)/2)*(1 + 1/(2*x))**(S(5)/2)/(-6 - 3/x) ans = sqrt(2*x + 1)*(6*x**2 + x - 1)/15 diff = i - ans assert diff.equals(0) is False assert diff.subs(x, Rational(-1, 2)/2) == 7*sqrt(2)/120 # there are regions for x for which the expression is True, for # example, when x < -1/2 or x > 0 the expression is zero p = Symbol('p', positive=True) assert diff.subs(x, p).equals(0) is True assert diff.subs(x, -1).equals(0) is True # prove via minimal_polynomial or self-consistency eq = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3)) assert eq.equals(0) q = 3**Rational(1, 3) + 3 p = expand(q**3)**Rational(1, 3) assert (p - q).equals(0) # issue 6829 # eq = q*x + q/4 + x**4 + x**3 + 2*x**2 - S.One/3 # z = eq.subs(x, solve(eq, x)[0]) q = symbols('q') z = (q*(-sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q - S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/6)/2 - S.One/4) + q/4 + (-sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q - S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/6)/2 - S.One/4)**4 + (-sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q - S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/6)/2 - S.One/4)**3 + 2*(-sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q - S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/6)/2 - S.One/4)**2 - Rational(1, 3)) assert z.equals(0) def test_random(): from sympy import posify, lucas assert posify(x)[0]._random() is not None assert lucas(n)._random(2, -2, 0, -1, 1) is None # issue 8662 assert Piecewise((Max(x, y), z))._random() is None def test_round(): from sympy.abc import x assert str(Float('0.1249999').round(2)) == '0.12' d20 = 12345678901234567890 ans = S(d20).round(2) assert ans.is_Integer and ans == d20 ans = S(d20).round(-2) assert ans.is_Integer and ans == 12345678901234567900 assert str(S('1/7').round(4)) == '0.1429' assert str(S('.[12345]').round(4)) == '0.1235' assert str(S('.1349').round(2)) == '0.13' n = S(12345) ans = n.round() assert ans.is_Integer assert ans == n ans = n.round(1) assert ans.is_Integer assert ans == n ans = n.round(4) assert ans.is_Integer assert ans == n assert n.round(-1) == 12340 r = Float(str(n)).round(-4) assert r == 10000 assert n.round(-5) == 0 assert str((pi + sqrt(2)).round(2)) == '4.56' assert (10*(pi + sqrt(2))).round(-1) == 50 raises(TypeError, lambda: round(x + 2, 2)) assert str(S(2.3).round(1)) == '2.3' # rounding in SymPy (as in Decimal) should be # exact for the given precision; we check here # that when a 5 follows the last digit that # the rounded digit will be even. for i in range(-99, 100): # construct a decimal that ends in 5, e.g. 123 -> 0.1235 s = str(abs(i)) p = len(s) # we are going to round to the last digit of i n = '0.%s5' % s # put a 5 after i's digits j = p + 2 # 2 for '0.' if i < 0: # 1 for '-' j += 1 n = '-' + n v = str(Float(n).round(p))[:j] # pertinent digits if v.endswith('.'): continue # it ends with 0 which is even L = int(v[-1]) # last digit assert L % 2 == 0, (n, '->', v) assert (Float(.3, 3) + 2*pi).round() == 7 assert (Float(.3, 3) + 2*pi*100).round() == 629 assert (pi + 2*E*I).round() == 3 + 5*I # don't let request for extra precision give more than # what is known (in this case, only 3 digits) assert str((Float(.03, 3) + 2*pi/100).round(5)) == '0.0928' assert str((Float(.03, 3) + 2*pi/100).round(4)) == '0.0928' assert S.Zero.round() == 0 a = (Add(1, Float('1.' + '9'*27, ''), evaluate=0)) assert a.round(10) == Float('3.0000000000', '') assert a.round(25) == Float('3.0000000000000000000000000', '') assert a.round(26) == Float('3.00000000000000000000000000', '') assert a.round(27) == Float('2.999999999999999999999999999', '') assert a.round(30) == Float('2.999999999999999999999999999', '') raises(TypeError, lambda: x.round()) f = Function('f') raises(TypeError, lambda: f(1).round()) # exact magnitude of 10 assert str(S.One.round()) == '1' assert str(S(100).round()) == '100' # applied to real and imaginary portions assert (2*pi + E*I).round() == 6 + 3*I assert (2*pi + I/10).round() == 6 assert (pi/10 + 2*I).round() == 2*I # the lhs re and im parts are Float with dps of 2 # and those on the right have dps of 15 so they won't compare # equal unless we use string or compare components (which will # then coerce the floats to the same precision) or re-create # the floats assert str((pi/10 + E*I).round(2)) == '0.31 + 2.72*I' assert str((pi/10 + E*I).round(2).as_real_imag()) == '(0.31, 2.72)' assert str((pi/10 + E*I).round(2)) == '0.31 + 2.72*I' # issue 6914 assert (I**(I + 3)).round(3) == Float('-0.208', '')*I # issue 8720 assert S(-123.6).round() == -124 assert S(-1.5).round() == -2 assert S(-100.5).round() == -100 assert S(-1.5 - 10.5*I).round() == -2 - 10*I # issue 7961 assert str(S(0.006).round(2)) == '0.01' assert str(S(0.00106).round(4)) == '0.0011' # issue 8147 assert S.NaN.round() is S.NaN assert S.Infinity.round() is S.Infinity assert S.NegativeInfinity.round() is S.NegativeInfinity assert S.ComplexInfinity.round() is S.ComplexInfinity # check that types match for i in range(2): f = float(i) # 2 args assert all(type(round(i, p)) is int for p in (-1, 0, 1)) assert all(S(i).round(p).is_Integer for p in (-1, 0, 1)) assert all(type(round(f, p)) is float for p in (-1, 0, 1)) assert all(S(f).round(p).is_Float for p in (-1, 0, 1)) # 1 arg (p is None) assert type(round(i)) is int assert S(i).round().is_Integer assert type(round(f)) is int assert S(f).round().is_Integer def test_held_expression_UnevaluatedExpr(): x = symbols("x") he = UnevaluatedExpr(1/x) e1 = x*he assert isinstance(e1, Mul) assert e1.args == (x, he) assert e1.doit() == 1 assert UnevaluatedExpr(Derivative(x, x)).doit(deep=False ) == Derivative(x, x) assert UnevaluatedExpr(Derivative(x, x)).doit() == 1 xx = Mul(x, x, evaluate=False) assert xx != x**2 ue2 = UnevaluatedExpr(xx) assert isinstance(ue2, UnevaluatedExpr) assert ue2.args == (xx,) assert ue2.doit() == x**2 assert ue2.doit(deep=False) == xx x2 = UnevaluatedExpr(2)*2 assert type(x2) is Mul assert x2.args == (2, UnevaluatedExpr(2)) def test_round_exception_nostr(): # Don't use the string form of the expression in the round exception, as # it's too slow s = Symbol('bad') try: s.round() except TypeError as e: assert 'bad' not in str(e) else: # Did not raise raise AssertionError("Did not raise") def test_extract_branch_factor(): assert exp_polar(2.0*I*pi).extract_branch_factor() == (1, 1) def test_identity_removal(): assert Add.make_args(x + 0) == (x,) assert Mul.make_args(x*1) == (x,) def test_float_0(): assert Float(0.0) + 1 == Float(1.0) @XFAIL def test_float_0_fail(): assert Float(0.0)*x == Float(0.0) assert (x + Float(0.0)).is_Add def test_issue_6325(): ans = (b**2 + z**2 - (b*(a + b*t) + z*(c + t*z))**2/( (a + b*t)**2 + (c + t*z)**2))/sqrt((a + b*t)**2 + (c + t*z)**2) e = sqrt((a + b*t)**2 + (c + z*t)**2) assert diff(e, t, 2) == ans e.diff(t, 2) == ans assert diff(e, t, 2, simplify=False) != ans def test_issue_7426(): f1 = a % c f2 = x % z assert f1.equals(f2) is None def test_issue_11122(): x = Symbol('x', extended_positive=False) assert unchanged(Gt, x, 0) # (x > 0) # (x > 0) should remain unevaluated after PR #16956 x = Symbol('x', positive=False, real=True) assert (x > 0) is S.false def test_issue_10651(): x = Symbol('x', real=True) e1 = (-1 + x)/(1 - x) e3 = (4*x**2 - 4)/((1 - x)*(1 + x)) e4 = 1/(cos(x)**2) - (tan(x))**2 x = Symbol('x', positive=True) e5 = (1 + x)/x assert e1.is_constant() is None assert e3.is_constant() is None assert e4.is_constant() is None assert e5.is_constant() is False def test_issue_10161(): x = symbols('x', real=True) assert x*abs(x)*abs(x) == x**3 def test_issue_10755(): x = symbols('x') raises(TypeError, lambda: int(log(x))) raises(TypeError, lambda: log(x).round(2)) def test_issue_11877(): x = symbols('x') assert integrate(log(S.Half - x), (x, 0, S.Half)) == Rational(-1, 2) -log(2)/2 def test_normal(): x = symbols('x') e = Mul(S.Half, 1 + x, evaluate=False) assert e.normal() == e def test_expr(): x = symbols('x') raises(TypeError, lambda: tan(x).series(x, 2, oo, "+")) def test_ExprBuilder(): eb = ExprBuilder(Mul) eb.args.extend([x, x]) assert eb.build() == x**2 def test_non_string_equality(): # Expressions should not compare equal to strings x = symbols('x') one = sympify(1) assert (x == 'x') is False assert (x != 'x') is True assert (one == '1') is False assert (one != '1') is True assert (x + 1 == 'x + 1') is False assert (x + 1 != 'x + 1') is True # Make sure == doesn't try to convert the resulting expression to a string # (e.g., by calling sympify() instead of _sympify()) class BadRepr: def __repr__(self): raise RuntimeError assert (x == BadRepr()) is False assert (x != BadRepr()) is True
048562cf0a901305e49e9d0f3afffbfde37d4a627df121b410ef22536475f80e
"""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) from sympy.testing.pytest import XFAIL, SKIP a, b, c, x, y, z = symbols('a,b,c,x,y,z') 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), "r", encoding='utf-8') as f: text = f.read() submodule = module + '.' + file[:-3] 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 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 from sympy import Q assert _test_args(AppliedPredicate(Predicate("test"), 2)) assert _test_args(Q.is_true(True)) def test_sympy__assumptions__assume__Predicate(): from sympy.assumptions.assume import Predicate assert _test_args(Predicate("test")) def test_sympy__assumptions__sathandlers__UnevaluatedOnFree(): from sympy.assumptions.sathandlers import UnevaluatedOnFree from sympy import Q assert _test_args(UnevaluatedOnFree(Q.positive)) def test_sympy__assumptions__sathandlers__AllArgs(): from sympy.assumptions.sathandlers import AllArgs from sympy import Q assert _test_args(AllArgs(Q.positive)) def test_sympy__assumptions__sathandlers__AnyArgs(): from sympy.assumptions.sathandlers import AnyArgs from sympy import Q assert _test_args(AnyArgs(Q.positive)) def test_sympy__assumptions__sathandlers__ExactlyOneArg(): from sympy.assumptions.sathandlers import ExactlyOneArg from sympy import Q assert _test_args(ExactlyOneArg(Q.positive)) def test_sympy__assumptions__sathandlers__CheckOldAssump(): from sympy.assumptions.sathandlers import CheckOldAssump from sympy import Q assert _test_args(CheckOldAssump(Q.positive)) def test_sympy__assumptions__sathandlers__CheckIsPrime(): from sympy.assumptions.sathandlers import CheckIsPrime from sympy import Q # Input must be a number assert _test_args(CheckIsPrime(Q.positive)) @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__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__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__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__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__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__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__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, x)) 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__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__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 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__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__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__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__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)) 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__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__codegen__array_utils__CodegenArrayContraction(): from sympy.codegen.array_utils import CodegenArrayContraction from sympy import IndexedBase A = symbols("A", cls=IndexedBase) assert _test_args(CodegenArrayContraction(A, (0, 1))) def test_sympy__codegen__array_utils__CodegenArrayDiagonal(): from sympy.codegen.array_utils import CodegenArrayDiagonal from sympy import IndexedBase A = symbols("A", cls=IndexedBase) assert _test_args(CodegenArrayDiagonal(A, (0, 1))) def test_sympy__codegen__array_utils__CodegenArrayTensorProduct(): from sympy.codegen.array_utils import CodegenArrayTensorProduct from sympy import IndexedBase A, B = symbols("A B", cls=IndexedBase) assert _test_args(CodegenArrayTensorProduct(A, B)) def test_sympy__codegen__array_utils__CodegenArrayElementwiseAdd(): from sympy.codegen.array_utils import CodegenArrayElementwiseAdd from sympy import IndexedBase A, B = symbols("A B", cls=IndexedBase) assert _test_args(CodegenArrayElementwiseAdd(A, B)) def test_sympy__codegen__array_utils__CodegenArrayPermuteDims(): from sympy.codegen.array_utils import CodegenArrayPermuteDims from sympy import IndexedBase A = symbols("A", cls=IndexedBase) assert _test_args(CodegenArrayPermuteDims(A, (1, 0))) 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))
c3186071c0c115ecea2178749c843f021daa2c7711ff55da8617be4f30229df2
import numbers as nums import decimal from sympy import (Rational, Symbol, Float, I, sqrt, cbrt, oo, nan, pi, E, Integer, S, factorial, Catalan, EulerGamma, GoldenRatio, TribonacciConstant, cos, exp, Number, zoo, log, Mul, Pow, Tuple, latex, Gt, Lt, Ge, Le, AlgebraicNumber, simplify, sin, fibonacci, RealField, sympify, srepr, Dummy, Sum) from sympy.core.logic import fuzzy_not from sympy.core.numbers import (igcd, ilcm, igcdex, seterr, igcd2, igcd_lehmer, mpf_norm, comp, mod_inverse) from sympy.core.power import integer_nthroot, isqrt, integer_log from sympy.polys.domains.groundtypes import PythonRational from sympy.utilities.decorator import conserve_mpmath_dps from sympy.utilities.iterables import permutations from sympy.testing.pytest import XFAIL, raises from mpmath import mpf from mpmath.rational import mpq import mpmath from sympy.core import numbers t = Symbol('t', real=False) _ninf = float(-oo) _inf = float(oo) def same_and_same_prec(a, b): # stricter matching for Floats return a == b and a._prec == b._prec def test_seterr(): seterr(divide=True) raises(ValueError, lambda: S.Zero/S.Zero) seterr(divide=False) assert S.Zero / S.Zero is S.NaN def test_mod(): x = S.Half y = Rational(3, 4) z = Rational(5, 18043) assert x % x == 0 assert x % y == S.Half assert x % z == Rational(3, 36086) assert y % x == Rational(1, 4) assert y % y == 0 assert y % z == Rational(9, 72172) assert z % x == Rational(5, 18043) assert z % y == Rational(5, 18043) assert z % z == 0 a = Float(2.6) assert (a % .2) == 0.0 assert (a % 2).round(15) == 0.6 assert (a % 0.5).round(15) == 0.1 p = Symbol('p', infinite=True) assert oo % oo is nan assert zoo % oo is nan assert 5 % oo is nan assert p % 5 is nan # In these two tests, if the precision of m does # not match the precision of the ans, then it is # likely that the change made now gives an answer # with degraded accuracy. r = Rational(500, 41) f = Float('.36', 3) m = r % f ans = Float(r % Rational(f), 3) assert m == ans and m._prec == ans._prec f = Float('8.36', 3) m = f % r ans = Float(Rational(f) % r, 3) assert m == ans and m._prec == ans._prec s = S.Zero assert s % float(1) == 0.0 # No rounding required since these numbers can be represented # exactly. assert Rational(3, 4) % Float(1.1) == 0.75 assert Float(1.5) % Rational(5, 4) == 0.25 assert Rational(5, 4).__rmod__(Float('1.5')) == 0.25 assert Float('1.5').__rmod__(Float('2.75')) == Float('1.25') assert 2.75 % Float('1.5') == Float('1.25') a = Integer(7) b = Integer(4) assert type(a % b) == Integer assert a % b == Integer(3) assert Integer(1) % Rational(2, 3) == Rational(1, 3) assert Rational(7, 5) % Integer(1) == Rational(2, 5) assert Integer(2) % 1.5 == 0.5 assert Integer(3).__rmod__(Integer(10)) == Integer(1) assert Integer(10) % 4 == Integer(2) assert 15 % Integer(4) == Integer(3) def test_divmod(): assert divmod(S(12), S(8)) == Tuple(1, 4) assert divmod(-S(12), S(8)) == Tuple(-2, 4) assert divmod(S.Zero, S.One) == Tuple(0, 0) raises(ZeroDivisionError, lambda: divmod(S.Zero, S.Zero)) raises(ZeroDivisionError, lambda: divmod(S.One, S.Zero)) assert divmod(S(12), 8) == Tuple(1, 4) assert divmod(12, S(8)) == Tuple(1, 4) assert divmod(S("2"), S("3/2")) == Tuple(S("1"), S("1/2")) assert divmod(S("3/2"), S("2")) == Tuple(S("0"), S("3/2")) assert divmod(S("2"), S("3.5")) == Tuple(S("0"), S("2")) assert divmod(S("3.5"), S("2")) == Tuple(S("1"), S("1.5")) assert divmod(S("2"), S("1/3")) == Tuple(S("6"), S("0")) assert divmod(S("1/3"), S("2")) == Tuple(S("0"), S("1/3")) assert divmod(S("2"), S("1/10")) == Tuple(S("20"), S("0")) assert divmod(S("2"), S(".1"))[0] == 19 assert divmod(S("0.1"), S("2")) == Tuple(S("0"), S("0.1")) assert divmod(S("2"), 2) == Tuple(S("1"), S("0")) assert divmod(2, S("2")) == Tuple(S("1"), S("0")) assert divmod(S("2"), 1.5) == Tuple(S("1"), S("0.5")) assert divmod(1.5, S("2")) == Tuple(S("0"), S("1.5")) assert divmod(0.3, S("2")) == Tuple(S("0"), S("0.3")) assert divmod(S("3/2"), S("3.5")) == Tuple(S("0"), S("3/2")) assert divmod(S("3.5"), S("3/2")) == Tuple(S("2"), S("0.5")) assert divmod(S("3/2"), S("1/3")) == Tuple(S("4"), S("1/6")) assert divmod(S("1/3"), S("3/2")) == Tuple(S("0"), S("1/3")) assert divmod(S("3/2"), S("0.1"))[0] == 14 assert divmod(S("0.1"), S("3/2")) == Tuple(S("0"), S("0.1")) assert divmod(S("3/2"), 2) == Tuple(S("0"), S("3/2")) assert divmod(2, S("3/2")) == Tuple(S("1"), S("1/2")) assert divmod(S("3/2"), 1.5) == Tuple(S("1"), S("0")) assert divmod(1.5, S("3/2")) == Tuple(S("1"), S("0")) assert divmod(S("3/2"), 0.3) == Tuple(S("5"), S("0")) assert divmod(0.3, S("3/2")) == Tuple(S("0"), S("0.3")) assert divmod(S("1/3"), S("3.5")) == Tuple(S("0"), S("1/3")) assert divmod(S("3.5"), S("0.1")) == Tuple(S("35"), S("0")) assert divmod(S("0.1"), S("3.5")) == Tuple(S("0"), S("0.1")) assert divmod(S("3.5"), 2) == Tuple(S("1"), S("1.5")) assert divmod(2, S("3.5")) == Tuple(S("0"), S("2")) assert divmod(S("3.5"), 1.5) == Tuple(S("2"), S("0.5")) assert divmod(1.5, S("3.5")) == Tuple(S("0"), S("1.5")) assert divmod(0.3, S("3.5")) == Tuple(S("0"), S("0.3")) assert divmod(S("0.1"), S("1/3")) == Tuple(S("0"), S("0.1")) assert divmod(S("1/3"), 2) == Tuple(S("0"), S("1/3")) assert divmod(2, S("1/3")) == Tuple(S("6"), S("0")) assert divmod(S("1/3"), 1.5) == Tuple(S("0"), S("1/3")) assert divmod(0.3, S("1/3")) == Tuple(S("0"), S("0.3")) assert divmod(S("0.1"), 2) == Tuple(S("0"), S("0.1")) assert divmod(2, S("0.1"))[0] == 19 assert divmod(S("0.1"), 1.5) == Tuple(S("0"), S("0.1")) assert divmod(1.5, S("0.1")) == Tuple(S("15"), S("0")) assert divmod(S("0.1"), 0.3) == Tuple(S("0"), S("0.1")) assert str(divmod(S("2"), 0.3)) == '(6, 0.2)' assert str(divmod(S("3.5"), S("1/3"))) == '(10, 0.166666666666667)' assert str(divmod(S("3.5"), 0.3)) == '(11, 0.2)' assert str(divmod(S("1/3"), S("0.1"))) == '(3, 0.0333333333333333)' assert str(divmod(1.5, S("1/3"))) == '(4, 0.166666666666667)' assert str(divmod(S("1/3"), 0.3)) == '(1, 0.0333333333333333)' assert str(divmod(0.3, S("0.1"))) == '(2, 0.1)' assert divmod(-3, S(2)) == (-2, 1) assert divmod(S(-3), S(2)) == (-2, 1) assert divmod(S(-3), 2) == (-2, 1) assert divmod(S(4), S(-3.1)) == Tuple(-2, -2.2) assert divmod(S(4), S(-2.1)) == divmod(4, -2.1) assert divmod(S(-8), S(-2.5) ) == Tuple(3 , -0.5) assert divmod(oo, 1) == (S.NaN, S.NaN) assert divmod(S.NaN, 1) == (S.NaN, S.NaN) assert divmod(1, S.NaN) == (S.NaN, S.NaN) ans = [(-1, oo), (-1, oo), (0, 0), (0, 1), (0, 2)] OO = float('inf') ANS = [tuple(map(float, i)) for i in ans] assert [divmod(i, oo) for i in range(-2, 3)] == ans ans = [(0, -2), (0, -1), (0, 0), (-1, -oo), (-1, -oo)] ANS = [tuple(map(float, i)) for i in ans] assert [divmod(i, -oo) for i in range(-2, 3)] == ans assert [divmod(i, -OO) for i in range(-2, 3)] == ANS assert divmod(S(3.5), S(-2)) == divmod(3.5, -2) assert divmod(-S(3.5), S(-2)) == divmod(-3.5, -2) assert divmod(S(0.0), S(9)) == divmod(0.0, 9) assert divmod(S(0), S(9.0)) == divmod(0, 9.0) def test_igcd(): assert igcd(0, 0) == 0 assert igcd(0, 1) == 1 assert igcd(1, 0) == 1 assert igcd(0, 7) == 7 assert igcd(7, 0) == 7 assert igcd(7, 1) == 1 assert igcd(1, 7) == 1 assert igcd(-1, 0) == 1 assert igcd(0, -1) == 1 assert igcd(-1, -1) == 1 assert igcd(-1, 7) == 1 assert igcd(7, -1) == 1 assert igcd(8, 2) == 2 assert igcd(4, 8) == 4 assert igcd(8, 16) == 8 assert igcd(7, -3) == 1 assert igcd(-7, 3) == 1 assert igcd(-7, -3) == 1 assert igcd(*[10, 20, 30]) == 10 raises(TypeError, lambda: igcd()) raises(TypeError, lambda: igcd(2)) raises(ValueError, lambda: igcd(0, None)) raises(ValueError, lambda: igcd(1, 2.2)) for args in permutations((45.1, 1, 30)): raises(ValueError, lambda: igcd(*args)) for args in permutations((1, 2, None)): raises(ValueError, lambda: igcd(*args)) def test_igcd_lehmer(): a, b = fibonacci(10001), fibonacci(10000) # len(str(a)) == 2090 # small divisors, long Euclidean sequence assert igcd_lehmer(a, b) == 1 c = fibonacci(100) assert igcd_lehmer(a*c, b*c) == c # big divisor assert igcd_lehmer(a, 10**1000) == 1 # swapping argmument assert igcd_lehmer(1, 2) == igcd_lehmer(2, 1) def test_igcd2(): # short loop assert igcd2(2**100 - 1, 2**99 - 1) == 1 # Lehmer's algorithm a, b = int(fibonacci(10001)), int(fibonacci(10000)) assert igcd2(a, b) == 1 def test_ilcm(): assert ilcm(0, 0) == 0 assert ilcm(1, 0) == 0 assert ilcm(0, 1) == 0 assert ilcm(1, 1) == 1 assert ilcm(2, 1) == 2 assert ilcm(8, 2) == 8 assert ilcm(8, 6) == 24 assert ilcm(8, 7) == 56 assert ilcm(*[10, 20, 30]) == 60 raises(ValueError, lambda: ilcm(8.1, 7)) raises(ValueError, lambda: ilcm(8, 7.1)) raises(TypeError, lambda: ilcm(8)) def test_igcdex(): assert igcdex(2, 3) == (-1, 1, 1) assert igcdex(10, 12) == (-1, 1, 2) assert igcdex(100, 2004) == (-20, 1, 4) assert igcdex(0, 0) == (0, 1, 0) assert igcdex(1, 0) == (1, 0, 1) def _strictly_equal(a, b): return (a.p, a.q, type(a.p), type(a.q)) == \ (b.p, b.q, type(b.p), type(b.q)) def _test_rational_new(cls): """ Tests that are common between Integer and Rational. """ assert cls(0) is S.Zero assert cls(1) is S.One assert cls(-1) is S.NegativeOne # These look odd, but are similar to int(): assert cls('1') is S.One assert cls('-1') is S.NegativeOne i = Integer(10) assert _strictly_equal(i, cls('10')) assert _strictly_equal(i, cls('10')) assert _strictly_equal(i, cls(int(10))) assert _strictly_equal(i, cls(i)) raises(TypeError, lambda: cls(Symbol('x'))) def test_Integer_new(): """ Test for Integer constructor """ _test_rational_new(Integer) assert _strictly_equal(Integer(0.9), S.Zero) assert _strictly_equal(Integer(10.5), Integer(10)) raises(ValueError, lambda: Integer("10.5")) assert Integer(Rational('1.' + '9'*20)) == 1 def test_Rational_new(): """" Test for Rational constructor """ _test_rational_new(Rational) n1 = S.Half assert n1 == Rational(Integer(1), 2) assert n1 == Rational(Integer(1), Integer(2)) assert n1 == Rational(1, Integer(2)) assert n1 == Rational(S.Half) assert 1 == Rational(n1, n1) assert Rational(3, 2) == Rational(S.Half, Rational(1, 3)) assert Rational(3, 1) == Rational(1, Rational(1, 3)) n3_4 = Rational(3, 4) assert Rational('3/4') == n3_4 assert -Rational('-3/4') == n3_4 assert Rational('.76').limit_denominator(4) == n3_4 assert Rational(19, 25).limit_denominator(4) == n3_4 assert Rational('19/25').limit_denominator(4) == n3_4 assert Rational(1.0, 3) == Rational(1, 3) assert Rational(1, 3.0) == Rational(1, 3) assert Rational(Float(0.5)) == S.Half assert Rational('1e2/1e-2') == Rational(10000) assert Rational('1 234') == Rational(1234) assert Rational('1/1 234') == Rational(1, 1234) assert Rational(-1, 0) is S.ComplexInfinity assert Rational(1, 0) is S.ComplexInfinity # Make sure Rational doesn't lose precision on Floats assert Rational(pi.evalf(100)).evalf(100) == pi.evalf(100) raises(TypeError, lambda: Rational('3**3')) raises(TypeError, lambda: Rational('1/2 + 2/3')) # handle fractions.Fraction instances try: import fractions assert Rational(fractions.Fraction(1, 2)) == S.Half except ImportError: pass assert Rational(mpq(2, 6)) == Rational(1, 3) assert Rational(PythonRational(2, 6)) == Rational(1, 3) def test_Number_new(): """" Test for Number constructor """ # Expected behavior on numbers and strings assert Number(1) is S.One assert Number(2).__class__ is Integer assert Number(-622).__class__ is Integer assert Number(5, 3).__class__ is Rational assert Number(5.3).__class__ is Float assert Number('1') is S.One assert Number('2').__class__ is Integer assert Number('-622').__class__ is Integer assert Number('5/3').__class__ is Rational assert Number('5.3').__class__ is Float raises(ValueError, lambda: Number('cos')) raises(TypeError, lambda: Number(cos)) a = Rational(3, 5) assert Number(a) is a # Check idempotence on Numbers u = ['inf', '-inf', 'nan', 'iNF', '+inf'] v = [oo, -oo, nan, oo, oo] for i, a in zip(u, v): assert Number(i) is a, (i, Number(i), a) def test_Number_cmp(): n1 = Number(1) n2 = Number(2) n3 = Number(-3) assert n1 < n2 assert n1 <= n2 assert n3 < n1 assert n2 > n3 assert n2 >= n3 raises(TypeError, lambda: n1 < S.NaN) raises(TypeError, lambda: n1 <= S.NaN) raises(TypeError, lambda: n1 > S.NaN) raises(TypeError, lambda: n1 >= S.NaN) def test_Rational_cmp(): n1 = Rational(1, 4) n2 = Rational(1, 3) n3 = Rational(2, 4) n4 = Rational(2, -4) n5 = Rational(0) n6 = Rational(1) n7 = Rational(3) n8 = Rational(-3) assert n8 < n5 assert n5 < n6 assert n6 < n7 assert n8 < n7 assert n7 > n8 assert (n1 + 1)**n2 < 2 assert ((n1 + n6)/n7) < 1 assert n4 < n3 assert n2 < n3 assert n1 < n2 assert n3 > n1 assert not n3 < n1 assert not (Rational(-1) > 0) assert Rational(-1) < 0 raises(TypeError, lambda: n1 < S.NaN) raises(TypeError, lambda: n1 <= S.NaN) raises(TypeError, lambda: n1 > S.NaN) raises(TypeError, lambda: n1 >= S.NaN) def test_Float(): def eq(a, b): t = Float("1.0E-15") return (-t < a - b < t) zeros = (0, S.Zero, 0., Float(0)) for i, j in permutations(zeros, 2): assert i == j for z in zeros: assert z in zeros assert S.Zero.is_zero a = Float(2) ** Float(3) assert eq(a.evalf(), Float(8)) assert eq((pi ** -1).evalf(), Float("0.31830988618379067")) a = Float(2) ** Float(4) assert eq(a.evalf(), Float(16)) assert (S(.3) == S(.5)) is False mpf = (0, 5404319552844595, -52, 53) x_str = Float((0, '13333333333333', -52, 53)) x2_str = Float((0, '26666666666666', -53, 54)) x_hex = Float((0, int(0x13333333333333), -52, 53)) x_dec = Float(mpf) assert x_str == x_hex == x_dec == Float(1.2) # x2_str was entered slightly malformed in that the mantissa # was even -- it should be odd and the even part should be # included with the exponent, but this is resolved by normalization # ONLY IF REQUIREMENTS of mpf_norm are met: the bitcount must # be exact: double the mantissa ==> increase bc by 1 assert Float(1.2)._mpf_ == mpf assert x2_str._mpf_ == mpf assert Float((0, int(0), -123, -1)) is S.NaN assert Float((0, int(0), -456, -2)) is S.Infinity assert Float((1, int(0), -789, -3)) is S.NegativeInfinity # if you don't give the full signature, it's not special assert Float((0, int(0), -123)) == Float(0) assert Float((0, int(0), -456)) == Float(0) assert Float((1, int(0), -789)) == Float(0) raises(ValueError, lambda: Float((0, 7, 1, 3), '')) assert Float('0.0').is_finite is True assert Float('0.0').is_negative is False assert Float('0.0').is_positive is False assert Float('0.0').is_infinite is False assert Float('0.0').is_zero is True # rationality properties # if the integer test fails then the use of intlike # should be removed from gamma_functions.py assert Float(1).is_integer is False assert Float(1).is_rational is None assert Float(1).is_irrational is None assert sqrt(2).n(15).is_rational is None assert sqrt(2).n(15).is_irrational is None # do not automatically evalf def teq(a): assert (a.evalf() == a) is False assert (a.evalf() != a) is True assert (a == a.evalf()) is False assert (a != a.evalf()) is True teq(pi) teq(2*pi) teq(cos(0.1, evaluate=False)) # long integer i = 12345678901234567890 assert same_and_same_prec(Float(12, ''), Float('12', '')) assert same_and_same_prec(Float(Integer(i), ''), Float(i, '')) assert same_and_same_prec(Float(i, ''), Float(str(i), 20)) assert same_and_same_prec(Float(str(i)), Float(i, '')) assert same_and_same_prec(Float(i), Float(i, '')) # inexact floats (repeating binary = denom not multiple of 2) # cannot have precision greater than 15 assert Float(.125, 22) == .125 assert Float(2.0, 22) == 2 assert float(Float('.12500000000000001', '')) == .125 raises(ValueError, lambda: Float(.12500000000000001, '')) # allow spaces Float('123 456.123 456') == Float('123456.123456') Integer('123 456') == Integer('123456') Rational('123 456.123 456') == Rational('123456.123456') assert Float(' .3e2') == Float('0.3e2') # allow underscore assert Float('1_23.4_56') == Float('123.456') assert Float('1_23.4_5_6', 12) == Float('123.456', 12) # ...but not in all cases (per Py 3.6) raises(ValueError, lambda: Float('_1')) raises(ValueError, lambda: Float('1_')) raises(ValueError, lambda: Float('1_.')) raises(ValueError, lambda: Float('1._')) raises(ValueError, lambda: Float('1__2')) raises(ValueError, lambda: Float('_inf')) # allow auto precision detection assert Float('.1', '') == Float(.1, 1) assert Float('.125', '') == Float(.125, 3) assert Float('.100', '') == Float(.1, 3) assert Float('2.0', '') == Float('2', 2) raises(ValueError, lambda: Float("12.3d-4", "")) raises(ValueError, lambda: Float(12.3, "")) raises(ValueError, lambda: Float('.')) raises(ValueError, lambda: Float('-.')) zero = Float('0.0') assert Float('-0') == zero assert Float('.0') == zero assert Float('-.0') == zero assert Float('-0.0') == zero assert Float(0.0) == zero assert Float(0) == zero assert Float(0, '') == Float('0', '') assert Float(1) == Float(1.0) assert Float(S.Zero) == zero assert Float(S.One) == Float(1.0) assert Float(decimal.Decimal('0.1'), 3) == Float('.1', 3) assert Float(decimal.Decimal('nan')) is S.NaN assert Float(decimal.Decimal('Infinity')) is S.Infinity assert Float(decimal.Decimal('-Infinity')) is S.NegativeInfinity assert '{:.3f}'.format(Float(4.236622)) == '4.237' assert '{:.35f}'.format(Float(pi.n(40), 40)) == \ '3.14159265358979323846264338327950288' # unicode assert Float('0.73908513321516064100000000') == \ Float('0.73908513321516064100000000') assert Float('0.73908513321516064100000000', 28) == \ Float('0.73908513321516064100000000', 28) # binary precision # Decimal value 0.1 cannot be expressed precisely as a base 2 fraction a = Float(S.One/10, dps=15) b = Float(S.One/10, dps=16) p = Float(S.One/10, precision=53) q = Float(S.One/10, precision=54) assert a._mpf_ == p._mpf_ assert not a._mpf_ == q._mpf_ assert not b._mpf_ == q._mpf_ # Precision specifying errors raises(ValueError, lambda: Float("1.23", dps=3, precision=10)) raises(ValueError, lambda: Float("1.23", dps="", precision=10)) raises(ValueError, lambda: Float("1.23", dps=3, precision="")) raises(ValueError, lambda: Float("1.23", dps="", precision="")) # from NumberSymbol assert same_and_same_prec(Float(pi, 32), pi.evalf(32)) assert same_and_same_prec(Float(Catalan), Catalan.evalf()) # oo and nan u = ['inf', '-inf', 'nan', 'iNF', '+inf'] v = [oo, -oo, nan, oo, oo] for i, a in zip(u, v): assert Float(i) is a @conserve_mpmath_dps def test_float_mpf(): import mpmath mpmath.mp.dps = 100 mp_pi = mpmath.pi() assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100) mpmath.mp.dps = 15 assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100) def test_Float_RealElement(): repi = RealField(dps=100)(pi.evalf(100)) # We still have to pass the precision because Float doesn't know what # RealElement is, but make sure it keeps full precision from the result. assert Float(repi, 100) == pi.evalf(100) def test_Float_default_to_highprec_from_str(): s = str(pi.evalf(128)) assert same_and_same_prec(Float(s), Float(s, '')) def test_Float_eval(): a = Float(3.2) assert (a**2).is_Float def test_Float_issue_2107(): a = Float(0.1, 10) b = Float("0.1", 10) assert a - a == 0 assert a + (-a) == 0 assert S.Zero + a - a == 0 assert S.Zero + a + (-a) == 0 assert b - b == 0 assert b + (-b) == 0 assert S.Zero + b - b == 0 assert S.Zero + b + (-b) == 0 def test_issue_14289(): from sympy.polys.numberfields import to_number_field a = 1 - sqrt(2) b = to_number_field(a) assert b.as_expr() == a assert b.minpoly(a).expand() == 0 def test_Float_from_tuple(): a = Float((0, '1L', 0, 1)) b = Float((0, '1', 0, 1)) assert a == b def test_Infinity(): assert oo != 1 assert 1*oo is oo assert 1 != oo assert oo != -oo assert oo != Symbol("x")**3 assert oo + 1 is oo assert 2 + oo is oo assert 3*oo + 2 is oo assert S.Half**oo == 0 assert S.Half**(-oo) is oo assert -oo*3 is -oo assert oo + oo is oo assert -oo + oo*(-5) is -oo assert 1/oo == 0 assert 1/(-oo) == 0 assert 8/oo == 0 assert oo % 2 is nan assert 2 % oo is nan assert oo/oo is nan assert oo/-oo is nan assert -oo/oo is nan assert -oo/-oo is nan assert oo - oo is nan assert oo - -oo is oo assert -oo - oo is -oo assert -oo - -oo is nan assert oo + -oo is nan assert -oo + oo is nan assert oo + oo is oo assert -oo + oo is nan assert oo + -oo is nan assert -oo + -oo is -oo assert oo*oo is oo assert -oo*oo is -oo assert oo*-oo is -oo assert -oo*-oo is oo assert oo/0 is oo assert -oo/0 is -oo assert 0/oo == 0 assert 0/-oo == 0 assert oo*0 is nan assert -oo*0 is nan assert 0*oo is nan assert 0*-oo is nan assert oo + 0 is oo assert -oo + 0 is -oo assert 0 + oo is oo assert 0 + -oo is -oo assert oo - 0 is oo assert -oo - 0 is -oo assert 0 - oo is -oo assert 0 - -oo is oo assert oo/2 is oo assert -oo/2 is -oo assert oo/-2 is -oo assert -oo/-2 is oo assert oo*2 is oo assert -oo*2 is -oo assert oo*-2 is -oo assert 2/oo == 0 assert 2/-oo == 0 assert -2/oo == 0 assert -2/-oo == 0 assert 2*oo is oo assert 2*-oo is -oo assert -2*oo is -oo assert -2*-oo is oo assert 2 + oo is oo assert 2 - oo is -oo assert -2 + oo is oo assert -2 - oo is -oo assert 2 + -oo is -oo assert 2 - -oo is oo assert -2 + -oo is -oo assert -2 - -oo is oo assert S(2) + oo is oo assert S(2) - oo is -oo assert oo/I == -oo*I assert -oo/I == oo*I assert oo*float(1) == _inf and (oo*float(1)) is oo assert -oo*float(1) == _ninf and (-oo*float(1)) is -oo assert oo/float(1) == _inf and (oo/float(1)) is oo assert -oo/float(1) == _ninf and (-oo/float(1)) is -oo assert oo*float(-1) == _ninf and (oo*float(-1)) is -oo assert -oo*float(-1) == _inf and (-oo*float(-1)) is oo assert oo/float(-1) == _ninf and (oo/float(-1)) is -oo assert -oo/float(-1) == _inf and (-oo/float(-1)) is oo assert oo + float(1) == _inf and (oo + float(1)) is oo assert -oo + float(1) == _ninf and (-oo + float(1)) is -oo assert oo - float(1) == _inf and (oo - float(1)) is oo assert -oo - float(1) == _ninf and (-oo - float(1)) is -oo assert float(1)*oo == _inf and (float(1)*oo) is oo assert float(1)*-oo == _ninf and (float(1)*-oo) is -oo assert float(1)/oo == 0 assert float(1)/-oo == 0 assert float(-1)*oo == _ninf and (float(-1)*oo) is -oo assert float(-1)*-oo == _inf and (float(-1)*-oo) is oo assert float(-1)/oo == 0 assert float(-1)/-oo == 0 assert float(1) + oo is oo assert float(1) + -oo is -oo assert float(1) - oo is -oo assert float(1) - -oo is oo assert oo == float(oo) assert (oo != float(oo)) is False assert type(float(oo)) is float assert -oo == float(-oo) assert (-oo != float(-oo)) is False assert type(float(-oo)) is float assert Float('nan') is nan assert nan*1.0 is nan assert -1.0*nan is nan assert nan*oo is nan assert nan*-oo is nan assert nan/oo is nan assert nan/-oo is nan assert nan + oo is nan assert nan + -oo is nan assert nan - oo is nan assert nan - -oo is nan assert -oo * S.Zero is nan assert oo*nan is nan assert -oo*nan is nan assert oo/nan is nan assert -oo/nan is nan assert oo + nan is nan assert -oo + nan is nan assert oo - nan is nan assert -oo - nan is nan assert S.Zero * oo is nan assert oo.is_Rational is False assert isinstance(oo, Rational) is False assert S.One/oo == 0 assert -S.One/oo == 0 assert S.One/-oo == 0 assert -S.One/-oo == 0 assert S.One*oo is oo assert -S.One*oo is -oo assert S.One*-oo is -oo assert -S.One*-oo is oo assert S.One/nan is nan assert S.One - -oo is oo assert S.One + nan is nan assert S.One - nan is nan assert nan - S.One is nan assert nan/S.One is nan assert -oo - S.One is -oo def test_Infinity_2(): x = Symbol('x') assert oo*x != oo assert oo*(pi - 1) is oo assert oo*(1 - pi) is -oo assert (-oo)*x != -oo assert (-oo)*(pi - 1) is -oo assert (-oo)*(1 - pi) is oo assert (-1)**S.NaN is S.NaN assert oo - _inf is S.NaN assert oo + _ninf is S.NaN assert oo*0 is S.NaN assert oo/_inf is S.NaN assert oo/_ninf is S.NaN assert oo**S.NaN is S.NaN assert -oo + _inf is S.NaN assert -oo - _ninf is S.NaN assert -oo*S.NaN is S.NaN assert -oo*0 is S.NaN assert -oo/_inf is S.NaN assert -oo/_ninf is S.NaN assert -oo/S.NaN is S.NaN assert abs(-oo) is oo assert all((-oo)**i is S.NaN for i in (oo, -oo, S.NaN)) assert (-oo)**3 is -oo assert (-oo)**2 is oo assert abs(S.ComplexInfinity) is oo def test_Mul_Infinity_Zero(): assert Float(0)*_inf is nan assert Float(0)*_ninf is nan assert Float(0)*_inf is nan assert Float(0)*_ninf is nan assert _inf*Float(0) is nan assert _ninf*Float(0) is nan assert _inf*Float(0) is nan assert _ninf*Float(0) is nan def test_Div_By_Zero(): assert 1/S.Zero is zoo assert 1/Float(0) is zoo assert 0/S.Zero is nan assert 0/Float(0) is nan assert S.Zero/0 is nan assert Float(0)/0 is nan assert -1/S.Zero is zoo assert -1/Float(0) is zoo def test_Infinity_inequations(): assert oo > pi assert not (oo < pi) assert exp(-3) < oo assert _inf > pi assert not (_inf < pi) assert exp(-3) < _inf raises(TypeError, lambda: oo < I) raises(TypeError, lambda: oo <= I) raises(TypeError, lambda: oo > I) raises(TypeError, lambda: oo >= I) raises(TypeError, lambda: -oo < I) raises(TypeError, lambda: -oo <= I) raises(TypeError, lambda: -oo > I) raises(TypeError, lambda: -oo >= I) raises(TypeError, lambda: I < oo) raises(TypeError, lambda: I <= oo) raises(TypeError, lambda: I > oo) raises(TypeError, lambda: I >= oo) raises(TypeError, lambda: I < -oo) raises(TypeError, lambda: I <= -oo) raises(TypeError, lambda: I > -oo) raises(TypeError, lambda: I >= -oo) assert oo > -oo and oo >= -oo assert (oo < -oo) == False and (oo <= -oo) == False assert -oo < oo and -oo <= oo assert (-oo > oo) == False and (-oo >= oo) == False assert (oo < oo) == False # issue 7775 assert (oo > oo) == False assert (-oo > -oo) == False and (-oo < -oo) == False assert oo >= oo and oo <= oo and -oo >= -oo and -oo <= -oo assert (-oo < -_inf) == False assert (oo > _inf) == False assert -oo >= -_inf assert oo <= _inf x = Symbol('x') b = Symbol('b', finite=True, real=True) assert (x < oo) == Lt(x, oo) # issue 7775 assert b < oo and b > -oo and b <= oo and b >= -oo assert oo > b and oo >= b and (oo < b) == False and (oo <= b) == False assert (-oo > b) == False and (-oo >= b) == False and -oo < b and -oo <= b assert (oo < x) == Lt(oo, x) and (oo > x) == Gt(oo, x) assert (oo <= x) == Le(oo, x) and (oo >= x) == Ge(oo, x) assert (-oo < x) == Lt(-oo, x) and (-oo > x) == Gt(-oo, x) assert (-oo <= x) == Le(-oo, x) and (-oo >= x) == Ge(-oo, x) def test_NaN(): assert nan is nan assert nan != 1 assert 1*nan is nan assert 1 != nan assert -nan is nan assert oo != Symbol("x")**3 assert 2 + nan is nan assert 3*nan + 2 is nan assert -nan*3 is nan assert nan + nan is nan assert -nan + nan*(-5) is nan assert 8/nan is nan raises(TypeError, lambda: nan > 0) raises(TypeError, lambda: nan < 0) raises(TypeError, lambda: nan >= 0) raises(TypeError, lambda: nan <= 0) raises(TypeError, lambda: 0 < nan) raises(TypeError, lambda: 0 > nan) raises(TypeError, lambda: 0 <= nan) raises(TypeError, lambda: 0 >= nan) assert nan**0 == 1 # as per IEEE 754 assert 1**nan is nan # IEEE 754 is not the best choice for symbolic work # test Pow._eval_power's handling of NaN assert Pow(nan, 0, evaluate=False)**2 == 1 for n in (1, 1., S.One, S.NegativeOne, Float(1)): assert n + nan is nan assert n - nan is nan assert nan + n is nan assert nan - n is nan assert n/nan is nan assert nan/n is nan def test_special_numbers(): assert isinstance(S.NaN, Number) is True assert isinstance(S.Infinity, Number) is True assert isinstance(S.NegativeInfinity, Number) is True assert S.NaN.is_number is True assert S.Infinity.is_number is True assert S.NegativeInfinity.is_number is True assert S.ComplexInfinity.is_number is True assert isinstance(S.NaN, Rational) is False assert isinstance(S.Infinity, Rational) is False assert isinstance(S.NegativeInfinity, Rational) is False assert S.NaN.is_rational is not True assert S.Infinity.is_rational is not True assert S.NegativeInfinity.is_rational is not True def test_powers(): assert integer_nthroot(1, 2) == (1, True) assert integer_nthroot(1, 5) == (1, True) assert integer_nthroot(2, 1) == (2, True) assert integer_nthroot(2, 2) == (1, False) assert integer_nthroot(2, 5) == (1, False) assert integer_nthroot(4, 2) == (2, True) assert integer_nthroot(123**25, 25) == (123, True) assert integer_nthroot(123**25 + 1, 25) == (123, False) assert integer_nthroot(123**25 - 1, 25) == (122, False) assert integer_nthroot(1, 1) == (1, True) assert integer_nthroot(0, 1) == (0, True) assert integer_nthroot(0, 3) == (0, True) assert integer_nthroot(10000, 1) == (10000, True) assert integer_nthroot(4, 2) == (2, True) assert integer_nthroot(16, 2) == (4, True) assert integer_nthroot(26, 2) == (5, False) assert integer_nthroot(1234567**7, 7) == (1234567, True) assert integer_nthroot(1234567**7 + 1, 7) == (1234567, False) assert integer_nthroot(1234567**7 - 1, 7) == (1234566, False) b = 25**1000 assert integer_nthroot(b, 1000) == (25, True) assert integer_nthroot(b + 1, 1000) == (25, False) assert integer_nthroot(b - 1, 1000) == (24, False) c = 10**400 c2 = c**2 assert integer_nthroot(c2, 2) == (c, True) assert integer_nthroot(c2 + 1, 2) == (c, False) assert integer_nthroot(c2 - 1, 2) == (c - 1, False) assert integer_nthroot(2, 10**10) == (1, False) p, r = integer_nthroot(int(factorial(10000)), 100) assert p % (10**10) == 5322420655 assert not r # Test that this is fast assert integer_nthroot(2, 10**10) == (1, False) # output should be int if possible assert type(integer_nthroot(2**61, 2)[0]) is int def test_integer_nthroot_overflow(): assert integer_nthroot(10**(50*50), 50) == (10**50, True) assert integer_nthroot(10**100000, 10000) == (10**10, True) def test_integer_log(): raises(ValueError, lambda: integer_log(2, 1)) raises(ValueError, lambda: integer_log(0, 2)) raises(ValueError, lambda: integer_log(1.1, 2)) raises(ValueError, lambda: integer_log(1, 2.2)) assert integer_log(1, 2) == (0, True) assert integer_log(1, 3) == (0, True) assert integer_log(2, 3) == (0, False) assert integer_log(3, 3) == (1, True) assert integer_log(3*2, 3) == (1, False) assert integer_log(3**2, 3) == (2, True) assert integer_log(3*4, 3) == (2, False) assert integer_log(3**3, 3) == (3, True) assert integer_log(27, 5) == (2, False) assert integer_log(2, 3) == (0, False) assert integer_log(-4, -2) == (2, False) assert integer_log(27, -3) == (3, False) assert integer_log(-49, 7) == (0, False) assert integer_log(-49, -7) == (2, False) def test_isqrt(): from math import sqrt as _sqrt limit = 4503599761588223 assert int(_sqrt(limit)) == integer_nthroot(limit, 2)[0] assert int(_sqrt(limit + 1)) != integer_nthroot(limit + 1, 2)[0] assert isqrt(limit + 1) == integer_nthroot(limit + 1, 2)[0] assert isqrt(limit + S.Half) == integer_nthroot(limit, 2)[0] assert isqrt(limit + 1 + S.Half) == integer_nthroot(limit + 1, 2)[0] assert isqrt(limit + 2 + S.Half) == integer_nthroot(limit + 2, 2)[0] # Regression tests for https://github.com/sympy/sympy/issues/17034 assert isqrt(4503599761588224) == 67108864 assert isqrt(9999999999999999) == 99999999 # Other corner cases, especially involving non-integers. raises(ValueError, lambda: isqrt(-1)) raises(ValueError, lambda: isqrt(-10**1000)) raises(ValueError, lambda: isqrt(Rational(-1, 2))) tiny = Rational(1, 10**1000) raises(ValueError, lambda: isqrt(-tiny)) assert isqrt(1-tiny) == 0 assert isqrt(4503599761588224-tiny) == 67108864 assert isqrt(10**100 - tiny) == 10**50 - 1 # Check that using an inaccurate math.sqrt doesn't affect the results. from sympy.core import power old_sqrt = power._sqrt power._sqrt = lambda x: 2.999999999 try: assert isqrt(9) == 3 assert isqrt(10000) == 100 finally: power._sqrt = old_sqrt def test_powers_Integer(): """Test Integer._eval_power""" # check infinity assert S.One ** S.Infinity is S.NaN assert S.NegativeOne** S.Infinity is S.NaN assert S(2) ** S.Infinity is S.Infinity assert S(-2)** S.Infinity == S.Infinity + S.Infinity * S.ImaginaryUnit assert S(0) ** S.Infinity is S.Zero # check Nan assert S.One ** S.NaN is S.NaN assert S.NegativeOne ** S.NaN is S.NaN # check for exact roots assert S.NegativeOne ** Rational(6, 5) == - (-1)**(S.One/5) assert sqrt(S(4)) == 2 assert sqrt(S(-4)) == I * 2 assert S(16) ** Rational(1, 4) == 2 assert S(-16) ** Rational(1, 4) == 2 * (-1)**Rational(1, 4) assert S(9) ** Rational(3, 2) == 27 assert S(-9) ** Rational(3, 2) == -27*I assert S(27) ** Rational(2, 3) == 9 assert S(-27) ** Rational(2, 3) == 9 * (S.NegativeOne ** Rational(2, 3)) assert (-2) ** Rational(-2, 1) == Rational(1, 4) # not exact roots assert sqrt(-3) == I*sqrt(3) assert (3) ** (Rational(3, 2)) == 3 * sqrt(3) assert (-3) ** (Rational(3, 2)) == - 3 * sqrt(-3) assert (-3) ** (Rational(5, 2)) == 9 * I * sqrt(3) assert (-3) ** (Rational(7, 2)) == - I * 27 * sqrt(3) assert (2) ** (Rational(3, 2)) == 2 * sqrt(2) assert (2) ** (Rational(-3, 2)) == sqrt(2) / 4 assert (81) ** (Rational(2, 3)) == 9 * (S(3) ** (Rational(2, 3))) assert (-81) ** (Rational(2, 3)) == 9 * (S(-3) ** (Rational(2, 3))) assert (-3) ** Rational(-7, 3) == \ -(-1)**Rational(2, 3)*3**Rational(2, 3)/27 assert (-3) ** Rational(-2, 3) == \ -(-1)**Rational(1, 3)*3**Rational(1, 3)/3 # join roots assert sqrt(6) + sqrt(24) == 3*sqrt(6) assert sqrt(2) * sqrt(3) == sqrt(6) # separate symbols & constansts x = Symbol("x") assert sqrt(49 * x) == 7 * sqrt(x) assert sqrt((3 - sqrt(pi)) ** 2) == 3 - sqrt(pi) # check that it is fast for big numbers assert (2**64 + 1) ** Rational(4, 3) assert (2**64 + 1) ** Rational(17, 25) # negative rational power and negative base assert (-3) ** Rational(-7, 3) == \ -(-1)**Rational(2, 3)*3**Rational(2, 3)/27 assert (-3) ** Rational(-2, 3) == \ -(-1)**Rational(1, 3)*3**Rational(1, 3)/3 assert (-2) ** Rational(-10, 3) == \ (-1)**Rational(2, 3)*2**Rational(2, 3)/16 assert abs(Pow(-2, Rational(-10, 3)).n() - Pow(-2, Rational(-10, 3), evaluate=False).n()) < 1e-16 # negative base and rational power with some simplification assert (-8) ** Rational(2, 5) == \ 2*(-1)**Rational(2, 5)*2**Rational(1, 5) assert (-4) ** Rational(9, 5) == \ -8*(-1)**Rational(4, 5)*2**Rational(3, 5) assert S(1234).factors() == {617: 1, 2: 1} assert Rational(2*3, 3*5*7).factors() == {2: 1, 5: -1, 7: -1} # test that eval_power factors numbers bigger than # the current limit in factor_trial_division (2**15) from sympy import nextprime n = nextprime(2**15) assert sqrt(n**2) == n assert sqrt(n**3) == n*sqrt(n) assert sqrt(4*n) == 2*sqrt(n) # check that factors of base with powers sharing gcd with power are removed assert (2**4*3)**Rational(1, 6) == 2**Rational(2, 3)*3**Rational(1, 6) assert (2**4*3)**Rational(5, 6) == 8*2**Rational(1, 3)*3**Rational(5, 6) # check that bases sharing a gcd are exptracted assert 2**Rational(1, 3)*3**Rational(1, 4)*6**Rational(1, 5) == \ 2**Rational(8, 15)*3**Rational(9, 20) assert sqrt(8)*24**Rational(1, 3)*6**Rational(1, 5) == \ 4*2**Rational(7, 10)*3**Rational(8, 15) assert sqrt(8)*(-24)**Rational(1, 3)*(-6)**Rational(1, 5) == \ 4*(-3)**Rational(8, 15)*2**Rational(7, 10) assert 2**Rational(1, 3)*2**Rational(8, 9) == 2*2**Rational(2, 9) assert 2**Rational(2, 3)*6**Rational(1, 3) == 2*3**Rational(1, 3) assert 2**Rational(2, 3)*6**Rational(8, 9) == \ 2*2**Rational(5, 9)*3**Rational(8, 9) assert (-2)**Rational(2, S(3))*(-4)**Rational(1, S(3)) == -2*2**Rational(1, 3) assert 3*Pow(3, 2, evaluate=False) == 3**3 assert 3*Pow(3, Rational(-1, 3), evaluate=False) == 3**Rational(2, 3) assert (-2)**Rational(1, 3)*(-3)**Rational(1, 4)*(-5)**Rational(5, 6) == \ -(-1)**Rational(5, 12)*2**Rational(1, 3)*3**Rational(1, 4) * \ 5**Rational(5, 6) assert Integer(-2)**Symbol('', even=True) == \ Integer(2)**Symbol('', even=True) assert (-1)**Float(.5) == 1.0*I def test_powers_Rational(): """Test Rational._eval_power""" # check infinity assert S.Half ** S.Infinity == 0 assert Rational(3, 2) ** S.Infinity is S.Infinity assert Rational(-1, 2) ** S.Infinity == 0 assert Rational(-3, 2) ** S.Infinity == \ S.Infinity + S.Infinity * S.ImaginaryUnit # check Nan assert Rational(3, 4) ** S.NaN is S.NaN assert Rational(-2, 3) ** S.NaN is S.NaN # exact roots on numerator assert sqrt(Rational(4, 3)) == 2 * sqrt(3) / 3 assert Rational(4, 3) ** Rational(3, 2) == 8 * sqrt(3) / 9 assert sqrt(Rational(-4, 3)) == I * 2 * sqrt(3) / 3 assert Rational(-4, 3) ** Rational(3, 2) == - I * 8 * sqrt(3) / 9 assert Rational(27, 2) ** Rational(1, 3) == 3 * (2 ** Rational(2, 3)) / 2 assert Rational(5**3, 8**3) ** Rational(4, 3) == Rational(5**4, 8**4) # exact root on denominator assert sqrt(Rational(1, 4)) == S.Half assert sqrt(Rational(1, -4)) == I * S.Half assert sqrt(Rational(3, 4)) == sqrt(3) / 2 assert sqrt(Rational(3, -4)) == I * sqrt(3) / 2 assert Rational(5, 27) ** Rational(1, 3) == (5 ** Rational(1, 3)) / 3 # not exact roots assert sqrt(S.Half) == sqrt(2) / 2 assert sqrt(Rational(-4, 7)) == I * sqrt(Rational(4, 7)) assert Rational(-3, 2)**Rational(-7, 3) == \ -4*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/27 assert Rational(-3, 2)**Rational(-2, 3) == \ -(-1)**Rational(1, 3)*2**Rational(2, 3)*3**Rational(1, 3)/3 assert Rational(-3, 2)**Rational(-10, 3) == \ 8*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/81 assert abs(Pow(Rational(-2, 3), Rational(-7, 4)).n() - Pow(Rational(-2, 3), Rational(-7, 4), evaluate=False).n()) < 1e-16 # negative integer power and negative rational base assert Rational(-2, 3) ** Rational(-2, 1) == Rational(9, 4) a = Rational(1, 10) assert a**Float(a, 2) == Float(a, 2)**Float(a, 2) assert Rational(-2, 3)**Symbol('', even=True) == \ Rational(2, 3)**Symbol('', even=True) def test_powers_Float(): assert str((S('-1/10')**S('3/10')).n()) == str(Float(-.1)**(.3)) def test_abs1(): assert Rational(1, 6) != Rational(-1, 6) assert abs(Rational(1, 6)) == abs(Rational(-1, 6)) def test_accept_int(): assert Float(4) == 4 def test_dont_accept_str(): assert Float("0.2") != "0.2" assert not (Float("0.2") == "0.2") def test_int(): a = Rational(5) assert int(a) == 5 a = Rational(9, 10) assert int(a) == int(-a) == 0 assert 1/(-1)**Rational(2, 3) == -(-1)**Rational(1, 3) assert int(pi) == 3 assert int(E) == 2 assert int(GoldenRatio) == 1 assert int(TribonacciConstant) == 2 # issue 10368 a = Rational(32442016954, 78058255275) assert type(int(a)) is type(int(-a)) is int def test_real_bug(): x = Symbol("x") assert str(2.0*x*x) in ["(2.0*x)*x", "2.0*x**2", "2.00000000000000*x**2"] assert str(2.1*x*x) != "(2.0*x)*x" def test_bug_sqrt(): assert ((sqrt(Rational(2)) + 1)*(sqrt(Rational(2)) - 1)).expand() == 1 def test_pi_Pi(): "Test that pi (instance) is imported, but Pi (class) is not" from sympy import pi # noqa with raises(ImportError): from sympy import Pi # noqa def test_no_len(): # there should be no len for numbers raises(TypeError, lambda: len(Rational(2))) raises(TypeError, lambda: len(Rational(2, 3))) raises(TypeError, lambda: len(Integer(2))) def test_issue_3321(): assert sqrt(Rational(1, 5)) == Rational(1, 5)**S.Half assert 5 * sqrt(Rational(1, 5)) == sqrt(5) def test_issue_3692(): assert ((-1)**Rational(1, 6)).expand(complex=True) == I/2 + sqrt(3)/2 assert ((-5)**Rational(1, 6)).expand(complex=True) == \ 5**Rational(1, 6)*I/2 + 5**Rational(1, 6)*sqrt(3)/2 assert ((-64)**Rational(1, 6)).expand(complex=True) == I + sqrt(3) def test_issue_3423(): x = Symbol("x") assert sqrt(x - 1).as_base_exp() == (x - 1, S.Half) assert sqrt(x - 1) != I*sqrt(1 - x) def test_issue_3449(): x = Symbol("x") assert sqrt(x - 1).subs(x, 5) == 2 def test_issue_13890(): x = Symbol("x") e = (-x/4 - S.One/12)**x - 1 f = simplify(e) a = Rational(9, 5) assert abs(e.subs(x,a).evalf() - f.subs(x,a).evalf()) < 1e-15 def test_Integer_factors(): def F(i): return Integer(i).factors() assert F(1) == {} assert F(2) == {2: 1} assert F(3) == {3: 1} assert F(4) == {2: 2} assert F(5) == {5: 1} assert F(6) == {2: 1, 3: 1} assert F(7) == {7: 1} assert F(8) == {2: 3} assert F(9) == {3: 2} assert F(10) == {2: 1, 5: 1} assert F(11) == {11: 1} assert F(12) == {2: 2, 3: 1} assert F(13) == {13: 1} assert F(14) == {2: 1, 7: 1} assert F(15) == {3: 1, 5: 1} assert F(16) == {2: 4} assert F(17) == {17: 1} assert F(18) == {2: 1, 3: 2} assert F(19) == {19: 1} assert F(20) == {2: 2, 5: 1} assert F(21) == {3: 1, 7: 1} assert F(22) == {2: 1, 11: 1} assert F(23) == {23: 1} assert F(24) == {2: 3, 3: 1} assert F(25) == {5: 2} assert F(26) == {2: 1, 13: 1} assert F(27) == {3: 3} assert F(28) == {2: 2, 7: 1} assert F(29) == {29: 1} assert F(30) == {2: 1, 3: 1, 5: 1} assert F(31) == {31: 1} assert F(32) == {2: 5} assert F(33) == {3: 1, 11: 1} assert F(34) == {2: 1, 17: 1} assert F(35) == {5: 1, 7: 1} assert F(36) == {2: 2, 3: 2} assert F(37) == {37: 1} assert F(38) == {2: 1, 19: 1} assert F(39) == {3: 1, 13: 1} assert F(40) == {2: 3, 5: 1} assert F(41) == {41: 1} assert F(42) == {2: 1, 3: 1, 7: 1} assert F(43) == {43: 1} assert F(44) == {2: 2, 11: 1} assert F(45) == {3: 2, 5: 1} assert F(46) == {2: 1, 23: 1} assert F(47) == {47: 1} assert F(48) == {2: 4, 3: 1} assert F(49) == {7: 2} assert F(50) == {2: 1, 5: 2} assert F(51) == {3: 1, 17: 1} def test_Rational_factors(): def F(p, q, visual=None): return Rational(p, q).factors(visual=visual) assert F(2, 3) == {2: 1, 3: -1} assert F(2, 9) == {2: 1, 3: -2} assert F(2, 15) == {2: 1, 3: -1, 5: -1} assert F(6, 10) == {3: 1, 5: -1} def test_issue_4107(): assert pi*(E + 10) + pi*(-E - 10) != 0 assert pi*(E + 10**10) + pi*(-E - 10**10) != 0 assert pi*(E + 10**20) + pi*(-E - 10**20) != 0 assert pi*(E + 10**80) + pi*(-E - 10**80) != 0 assert (pi*(E + 10) + pi*(-E - 10)).expand() == 0 assert (pi*(E + 10**10) + pi*(-E - 10**10)).expand() == 0 assert (pi*(E + 10**20) + pi*(-E - 10**20)).expand() == 0 assert (pi*(E + 10**80) + pi*(-E - 10**80)).expand() == 0 def test_IntegerInteger(): a = Integer(4) b = Integer(a) assert a == b def test_Rational_gcd_lcm_cofactors(): assert Integer(4).gcd(2) == Integer(2) assert Integer(4).lcm(2) == Integer(4) assert Integer(4).gcd(Integer(2)) == Integer(2) assert Integer(4).lcm(Integer(2)) == Integer(4) a, b = 720**99911, 480**12342 assert Integer(a).lcm(b) == a*b/Integer(a).gcd(b) assert Integer(4).gcd(3) == Integer(1) assert Integer(4).lcm(3) == Integer(12) assert Integer(4).gcd(Integer(3)) == Integer(1) assert Integer(4).lcm(Integer(3)) == Integer(12) assert Rational(4, 3).gcd(2) == Rational(2, 3) assert Rational(4, 3).lcm(2) == Integer(4) assert Rational(4, 3).gcd(Integer(2)) == Rational(2, 3) assert Rational(4, 3).lcm(Integer(2)) == Integer(4) assert Integer(4).gcd(Rational(2, 9)) == Rational(2, 9) assert Integer(4).lcm(Rational(2, 9)) == Integer(4) assert Rational(4, 3).gcd(Rational(2, 9)) == Rational(2, 9) assert Rational(4, 3).lcm(Rational(2, 9)) == Rational(4, 3) assert Rational(4, 5).gcd(Rational(2, 9)) == Rational(2, 45) assert Rational(4, 5).lcm(Rational(2, 9)) == Integer(4) assert Rational(5, 9).lcm(Rational(3, 7)) == Rational(Integer(5).lcm(3),Integer(9).gcd(7)) assert Integer(4).cofactors(2) == (Integer(2), Integer(2), Integer(1)) assert Integer(4).cofactors(Integer(2)) == \ (Integer(2), Integer(2), Integer(1)) assert Integer(4).gcd(Float(2.0)) == S.One assert Integer(4).lcm(Float(2.0)) == Float(8.0) assert Integer(4).cofactors(Float(2.0)) == (S.One, Integer(4), Float(2.0)) assert S.Half.gcd(Float(2.0)) == S.One assert S.Half.lcm(Float(2.0)) == Float(1.0) assert S.Half.cofactors(Float(2.0)) == \ (S.One, S.Half, Float(2.0)) def test_Float_gcd_lcm_cofactors(): assert Float(2.0).gcd(Integer(4)) == S.One assert Float(2.0).lcm(Integer(4)) == Float(8.0) assert Float(2.0).cofactors(Integer(4)) == (S.One, Float(2.0), Integer(4)) assert Float(2.0).gcd(S.Half) == S.One assert Float(2.0).lcm(S.Half) == Float(1.0) assert Float(2.0).cofactors(S.Half) == \ (S.One, Float(2.0), S.Half) def test_issue_4611(): assert abs(pi._evalf(50) - 3.14159265358979) < 1e-10 assert abs(E._evalf(50) - 2.71828182845905) < 1e-10 assert abs(Catalan._evalf(50) - 0.915965594177219) < 1e-10 assert abs(EulerGamma._evalf(50) - 0.577215664901533) < 1e-10 assert abs(GoldenRatio._evalf(50) - 1.61803398874989) < 1e-10 assert abs(TribonacciConstant._evalf(50) - 1.83928675521416) < 1e-10 x = Symbol("x") assert (pi + x).evalf() == pi.evalf() + x assert (E + x).evalf() == E.evalf() + x assert (Catalan + x).evalf() == Catalan.evalf() + x assert (EulerGamma + x).evalf() == EulerGamma.evalf() + x assert (GoldenRatio + x).evalf() == GoldenRatio.evalf() + x assert (TribonacciConstant + x).evalf() == TribonacciConstant.evalf() + x @conserve_mpmath_dps def test_conversion_to_mpmath(): assert mpmath.mpmathify(Integer(1)) == mpmath.mpf(1) assert mpmath.mpmathify(S.Half) == mpmath.mpf(0.5) assert mpmath.mpmathify(Float('1.23', 15)) == mpmath.mpf('1.23') assert mpmath.mpmathify(I) == mpmath.mpc(1j) assert mpmath.mpmathify(1 + 2*I) == mpmath.mpc(1 + 2j) assert mpmath.mpmathify(1.0 + 2*I) == mpmath.mpc(1 + 2j) assert mpmath.mpmathify(1 + 2.0*I) == mpmath.mpc(1 + 2j) assert mpmath.mpmathify(1.0 + 2.0*I) == mpmath.mpc(1 + 2j) assert mpmath.mpmathify(S.Half + S.Half*I) == mpmath.mpc(0.5 + 0.5j) assert mpmath.mpmathify(2*I) == mpmath.mpc(2j) assert mpmath.mpmathify(2.0*I) == mpmath.mpc(2j) assert mpmath.mpmathify(S.Half*I) == mpmath.mpc(0.5j) mpmath.mp.dps = 100 assert mpmath.mpmathify(pi.evalf(100) + pi.evalf(100)*I) == mpmath.pi + mpmath.pi*mpmath.j assert mpmath.mpmathify(pi.evalf(100)*I) == mpmath.pi*mpmath.j def test_relational(): # real x = S(.1) assert (x != cos) is True assert (x == cos) is False # rational x = Rational(1, 3) assert (x != cos) is True assert (x == cos) is False # integer defers to rational so these tests are omitted # number symbol x = pi assert (x != cos) is True assert (x == cos) is False def test_Integer_as_index(): assert 'hello'[Integer(2):] == 'llo' def test_Rational_int(): assert int( Rational(7, 5)) == 1 assert int( S.Half) == 0 assert int(Rational(-1, 2)) == 0 assert int(-Rational(7, 5)) == -1 def test_zoo(): b = Symbol('b', finite=True) nz = Symbol('nz', nonzero=True) p = Symbol('p', positive=True) n = Symbol('n', negative=True) im = Symbol('i', imaginary=True) c = Symbol('c', complex=True) pb = Symbol('pb', positive=True, finite=True) nb = Symbol('nb', negative=True, finite=True) imb = Symbol('ib', imaginary=True, finite=True) for i in [I, S.Infinity, S.NegativeInfinity, S.Zero, S.One, S.Pi, S.Half, S(3), log(3), b, nz, p, n, im, pb, nb, imb, c]: if i.is_finite and (i.is_real or i.is_imaginary): assert i + zoo is zoo assert i - zoo is zoo assert zoo + i is zoo assert zoo - i is zoo elif i.is_finite is not False: assert (i + zoo).is_Add assert (i - zoo).is_Add assert (zoo + i).is_Add assert (zoo - i).is_Add else: assert (i + zoo) is S.NaN assert (i - zoo) is S.NaN assert (zoo + i) is S.NaN assert (zoo - i) is S.NaN if fuzzy_not(i.is_zero) and (i.is_extended_real or i.is_imaginary): assert i*zoo is zoo assert zoo*i is zoo elif i.is_zero: assert i*zoo is S.NaN assert zoo*i is S.NaN else: assert (i*zoo).is_Mul assert (zoo*i).is_Mul if fuzzy_not((1/i).is_zero) and (i.is_real or i.is_imaginary): assert zoo/i is zoo elif (1/i).is_zero: assert zoo/i is S.NaN elif i.is_zero: assert zoo/i is zoo else: assert (zoo/i).is_Mul assert (I*oo).is_Mul # allow directed infinity assert zoo + zoo is S.NaN assert zoo * zoo is zoo assert zoo - zoo is S.NaN assert zoo/zoo is S.NaN assert zoo**zoo is S.NaN assert zoo**0 is S.One assert zoo**2 is zoo assert 1/zoo is S.Zero assert Mul.flatten([S.NegativeOne, oo, S(0)]) == ([S.NaN], [], None) def test_issue_4122(): x = Symbol('x', nonpositive=True) assert oo + x is oo x = Symbol('x', extended_nonpositive=True) assert (oo + x).is_Add x = Symbol('x', finite=True) assert (oo + x).is_Add # x could be imaginary x = Symbol('x', nonnegative=True) assert oo + x is oo x = Symbol('x', extended_nonnegative=True) assert oo + x is oo x = Symbol('x', finite=True, real=True) assert oo + x is oo # similarly for negative infinity x = Symbol('x', nonnegative=True) assert -oo + x is -oo x = Symbol('x', extended_nonnegative=True) assert (-oo + x).is_Add x = Symbol('x', finite=True) assert (-oo + x).is_Add x = Symbol('x', nonpositive=True) assert -oo + x is -oo x = Symbol('x', extended_nonpositive=True) assert -oo + x is -oo x = Symbol('x', finite=True, real=True) assert -oo + x is -oo def test_GoldenRatio_expand(): assert GoldenRatio.expand(func=True) == S.Half + sqrt(5)/2 def test_TribonacciConstant_expand(): assert TribonacciConstant.expand(func=True) == \ (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3 def test_as_content_primitive(): assert S.Zero.as_content_primitive() == (1, 0) assert S.Half.as_content_primitive() == (S.Half, 1) assert (Rational(-1, 2)).as_content_primitive() == (S.Half, -1) assert S(3).as_content_primitive() == (3, 1) assert S(3.1).as_content_primitive() == (1, 3.1) def test_hashing_sympy_integers(): # Test for issue 5072 assert {Integer(3)} == {int(3)} assert hash(Integer(4)) == hash(int(4)) def test_rounding_issue_4172(): assert int((E**100).round()) == \ 26881171418161354484126255515800135873611119 assert int((pi**100).round()) == \ 51878483143196131920862615246303013562686760680406 assert int((Rational(1)/EulerGamma**100).round()) == \ 734833795660954410469466 @XFAIL def test_mpmath_issues(): from mpmath.libmp.libmpf import _normalize import mpmath.libmp as mlib rnd = mlib.round_nearest mpf = (0, int(0), -123, -1, 53, rnd) # nan assert _normalize(mpf, 53) != (0, int(0), 0, 0) mpf = (0, int(0), -456, -2, 53, rnd) # +inf assert _normalize(mpf, 53) != (0, int(0), 0, 0) mpf = (1, int(0), -789, -3, 53, rnd) # -inf assert _normalize(mpf, 53) != (0, int(0), 0, 0) from mpmath.libmp.libmpf import fnan assert mlib.mpf_eq(fnan, fnan) def test_Catalan_EulerGamma_prec(): n = GoldenRatio f = Float(n.n(), 5) assert f._mpf_ == (0, int(212079), -17, 18) assert f._prec == 20 assert n._as_mpf_val(20) == f._mpf_ n = EulerGamma f = Float(n.n(), 5) assert f._mpf_ == (0, int(302627), -19, 19) assert f._prec == 20 assert n._as_mpf_val(20) == f._mpf_ def test_Catalan_rewrite(): k = Dummy('k', integer=True, nonnegative=True) assert Catalan.rewrite(Sum).dummy_eq( Sum((-1)**k/(2*k + 1)**2, (k, 0, oo))) assert Catalan.rewrite() == Catalan def test_bool_eq(): assert 0 == False assert S(0) == False assert S(0) != S.false assert 1 == True assert S.One == True assert S.One != S.true def test_Float_eq(): # all .5 values are the same assert Float(.5, 10) == Float(.5, 11) == Float(.5, 1) # but floats that aren't exact in base-2 still # don't compare the same because they have different # underlying mpf values assert Float(.12, 3) != Float(.12, 4) assert Float(.12, 3) != .12 assert 0.12 != Float(.12, 3) assert Float('.12', 22) != .12 # issue 11707 # but Float/Rational -- except for 0 -- # are exact so Rational(x) = Float(y) only if # Rational(x) == Rational(Float(y)) assert Float('1.1') != Rational(11, 10) assert Rational(11, 10) != Float('1.1') # coverage assert not Float(3) == 2 assert not Float(2**2) == S.Half assert Float(2**2) == 4 assert not Float(2**-2) == 1 assert Float(2**-1) == S.Half assert not Float(2*3) == 3 assert not Float(2*3) == S.Half assert Float(2*3) == 6 assert not Float(2*3) == 8 assert Float(.75) == Rational(3, 4) assert Float(5/18) == 5/18 # 4473 assert Float(2.) != 3 assert Float((0,1,-3)) == S.One/8 assert Float((0,1,-3)) != S.One/9 # 16196 assert 2 == Float(2) # as per Python # but in a computation... assert t**2 != t**2.0 def test_int_NumberSymbols(): assert [int(i) for i in [pi, EulerGamma, E, GoldenRatio, Catalan]] == \ [3, 0, 2, 1, 0] def test_issue_6640(): from mpmath.libmp.libmpf import finf, fninf # fnan is not included because Float no longer returns fnan, # but otherwise, the same sort of test could apply assert Float(finf).is_zero is False assert Float(fninf).is_zero is False assert bool(Float(0)) is False def test_issue_6349(): assert Float('23.e3', '')._prec == 10 assert Float('23e3', '')._prec == 20 assert Float('23000', '')._prec == 20 assert Float('-23000', '')._prec == 20 def test_mpf_norm(): assert mpf_norm((1, 0, 1, 0), 10) == mpf('0')._mpf_ assert Float._new((1, 0, 1, 0), 10)._mpf_ == mpf('0')._mpf_ def test_latex(): assert latex(pi) == r"\pi" assert latex(E) == r"e" assert latex(GoldenRatio) == r"\phi" assert latex(TribonacciConstant) == r"\text{TribonacciConstant}" assert latex(EulerGamma) == r"\gamma" assert latex(oo) == r"\infty" assert latex(-oo) == r"-\infty" assert latex(zoo) == r"\tilde{\infty}" assert latex(nan) == r"\text{NaN}" assert latex(I) == r"i" def test_issue_7742(): assert -oo % 1 is nan def test_simplify_AlgebraicNumber(): A = AlgebraicNumber e = 3**(S.One/6)*(3 + (135 + 78*sqrt(3))**Rational(2, 3))/(45 + 26*sqrt(3))**(S.One/3) assert simplify(A(e)) == A(12) # wester test_C20 e = (41 + 29*sqrt(2))**(S.One/5) assert simplify(A(e)) == A(1 + sqrt(2)) # wester test_C21 e = (3 + 4*I)**Rational(3, 2) assert simplify(A(e)) == A(2 + 11*I) # issue 4401 def test_Float_idempotence(): x = Float('1.23', '') y = Float(x) z = Float(x, 15) assert same_and_same_prec(y, x) assert not same_and_same_prec(z, x) x = Float(10**20) y = Float(x) z = Float(x, 15) assert same_and_same_prec(y, x) assert not same_and_same_prec(z, x) def test_comp1(): # sqrt(2) = 1.414213 5623730950... a = sqrt(2).n(7) assert comp(a, 1.4142129) is False assert comp(a, 1.4142130) # ... assert comp(a, 1.4142141) assert comp(a, 1.4142142) is False assert comp(sqrt(2).n(2), '1.4') assert comp(sqrt(2).n(2), Float(1.4, 2), '') assert comp(sqrt(2).n(2), 1.4, '') assert comp(sqrt(2).n(2), Float(1.4, 3), '') is False assert comp(sqrt(2) + sqrt(3)*I, 1.4 + 1.7*I, .1) assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.89, .1) assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.90, .1) assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.07, .1) assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.08, .1) assert [(i, j) for i in range(130, 150) for j in range(170, 180) if comp((sqrt(2)+ I*sqrt(3)).n(3), i/100. + I*j/100.)] == [ (141, 173), (142, 173)] raises(ValueError, lambda: comp(t, '1')) raises(ValueError, lambda: comp(t, 1)) assert comp(0, 0.0) assert comp(.5, S.Half) assert comp(2 + sqrt(2), 2.0 + sqrt(2)) assert not comp(0, 1) assert not comp(2, sqrt(2)) assert not comp(2 + I, 2.0 + sqrt(2)) assert not comp(2.0 + sqrt(2), 2 + I) assert not comp(2.0 + sqrt(2), sqrt(3)) assert comp(1/pi.n(4), 0.3183, 1e-5) assert not comp(1/pi.n(4), 0.3183, 8e-6) def test_issue_9491(): assert oo**zoo is nan def test_issue_10063(): assert 2**Float(3) == Float(8) def test_issue_10020(): assert oo**I is S.NaN assert oo**(1 + I) is S.ComplexInfinity assert oo**(-1 + I) is S.Zero assert (-oo)**I is S.NaN assert (-oo)**(-1 + I) is S.Zero assert oo**t == Pow(oo, t, evaluate=False) assert (-oo)**t == Pow(-oo, t, evaluate=False) def test_invert_numbers(): assert S(2).invert(5) == 3 assert S(2).invert(Rational(5, 2)) == S.Half assert S(2).invert(5.) == 0.5 assert S(2).invert(S(5)) == 3 assert S(2.).invert(5) == 0.5 assert S(sqrt(2)).invert(5) == 1/sqrt(2) assert S(sqrt(2)).invert(sqrt(3)) == 1/sqrt(2) def test_mod_inverse(): assert mod_inverse(3, 11) == 4 assert mod_inverse(5, 11) == 9 assert mod_inverse(21124921, 521512) == 7713 assert mod_inverse(124215421, 5125) == 2981 assert mod_inverse(214, 12515) == 1579 assert mod_inverse(5823991, 3299) == 1442 assert mod_inverse(123, 44) == 39 assert mod_inverse(2, 5) == 3 assert mod_inverse(-2, 5) == 2 assert mod_inverse(2, -5) == -2 assert mod_inverse(-2, -5) == -3 assert mod_inverse(-3, -7) == -5 x = Symbol('x') assert S(2).invert(x) == S.Half raises(TypeError, lambda: mod_inverse(2, x)) raises(ValueError, lambda: mod_inverse(2, S.Half)) raises(ValueError, lambda: mod_inverse(2, cos(1)**2 + sin(1)**2)) def test_golden_ratio_rewrite_as_sqrt(): assert GoldenRatio.rewrite(sqrt) == S.Half + sqrt(5)*S.Half def test_tribonacci_constant_rewrite_as_sqrt(): assert TribonacciConstant.rewrite(sqrt) == \ (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3 def test_comparisons_with_unknown_type(): class Foo: """ Class that is unaware of Basic, and relies on both classes returning the NotImplemented singleton for equivalence to evaluate to False. """ ni, nf, nr = Integer(3), Float(1.0), Rational(1, 3) foo = Foo() for n in ni, nf, nr, oo, -oo, zoo, nan: assert n != foo assert foo != n assert not n == foo assert not foo == n raises(TypeError, lambda: n < foo) raises(TypeError, lambda: foo > n) raises(TypeError, lambda: n > foo) raises(TypeError, lambda: foo < n) raises(TypeError, lambda: n <= foo) raises(TypeError, lambda: foo >= n) raises(TypeError, lambda: n >= foo) raises(TypeError, lambda: foo <= n) class Bar: """ Class that considers itself equal to any instance of Number except infinities and nans, and relies on sympy types returning the NotImplemented singleton for symmetric equality relations. """ def __eq__(self, other): if other in (oo, -oo, zoo, nan): return False if isinstance(other, Number): return True return NotImplemented def __ne__(self, other): return not self == other bar = Bar() for n in ni, nf, nr: assert n == bar assert bar == n assert not n != bar assert not bar != n for n in oo, -oo, zoo, nan: assert n != bar assert bar != n assert not n == bar assert not bar == n for n in ni, nf, nr, oo, -oo, zoo, nan: raises(TypeError, lambda: n < bar) raises(TypeError, lambda: bar > n) raises(TypeError, lambda: n > bar) raises(TypeError, lambda: bar < n) raises(TypeError, lambda: n <= bar) raises(TypeError, lambda: bar >= n) raises(TypeError, lambda: n >= bar) raises(TypeError, lambda: bar <= n) def test_NumberSymbol_comparison(): from sympy.core.tests.test_relational import rel_check rpi = Rational('905502432259640373/288230376151711744') fpi = Float(float(pi)) assert rel_check(rpi, fpi) def test_Integer_precision(): # Make sure Integer inputs for keyword args work assert Float('1.0', dps=Integer(15))._prec == 53 assert Float('1.0', precision=Integer(15))._prec == 15 assert type(Float('1.0', precision=Integer(15))._prec) == int assert sympify(srepr(Float('1.0', precision=15))) == Float('1.0', precision=15) def test_numpy_to_float(): from sympy.testing.pytest import skip from sympy.external import import_module np = import_module('numpy') if not np: skip('numpy not installed. Abort numpy tests.') def check_prec_and_relerr(npval, ratval): prec = np.finfo(npval).nmant + 1 x = Float(npval) assert x._prec == prec y = Float(ratval, precision=prec) assert abs((x - y)/y) < 2**(-(prec + 1)) check_prec_and_relerr(np.float16(2.0/3), Rational(2, 3)) check_prec_and_relerr(np.float32(2.0/3), Rational(2, 3)) check_prec_and_relerr(np.float64(2.0/3), Rational(2, 3)) # extended precision, on some arch/compilers: x = np.longdouble(2)/3 check_prec_and_relerr(x, Rational(2, 3)) y = Float(x, precision=10) assert same_and_same_prec(y, Float(Rational(2, 3), precision=10)) raises(TypeError, lambda: Float(np.complex64(1+2j))) raises(TypeError, lambda: Float(np.complex128(1+2j))) def test_Integer_ceiling_floor(): a = Integer(4) assert a.floor() == a assert a.ceiling() == a def test_ComplexInfinity(): assert zoo.floor() is zoo assert zoo.ceiling() is zoo assert zoo**zoo is S.NaN def test_Infinity_floor_ceiling_power(): assert oo.floor() is oo assert oo.ceiling() is oo assert oo**S.NaN is S.NaN assert oo**zoo is S.NaN def test_One_power(): assert S.One**12 is S.One assert S.NegativeOne**S.NaN is S.NaN def test_NegativeInfinity(): assert (-oo).floor() is -oo assert (-oo).ceiling() is -oo assert (-oo)**11 is -oo assert (-oo)**12 is oo def test_issue_6133(): raises(TypeError, lambda: (-oo < None)) raises(TypeError, lambda: (S(-2) < None)) raises(TypeError, lambda: (oo < None)) raises(TypeError, lambda: (oo > None)) raises(TypeError, lambda: (S(2) < None)) def test_abc(): x = numbers.Float(5) assert(isinstance(x, nums.Number)) assert(isinstance(x, numbers.Number)) assert(isinstance(x, nums.Real)) y = numbers.Rational(1, 3) assert(isinstance(y, nums.Number)) assert(y.numerator() == 1) assert(y.denominator() == 3) assert(isinstance(y, nums.Rational)) z = numbers.Integer(3) assert(isinstance(z, nums.Number)) def test_floordiv(): assert S(2)//S.Half == 4
f3c659be4317a22204e9ed72b7676274b96a5cad6271605326150a9dccc62445
from sympy import (Lambda, Symbol, Function, Derivative, Subs, sqrt, log, exp, Rational, Float, sin, cos, acos, diff, I, re, im, E, expand, pi, O, Sum, S, polygamma, loggamma, expint, Tuple, Dummy, Eq, Expr, symbols, nfloat, Piecewise, Indexed, Matrix, Basic, Dict, oo, zoo, nan, Pow) from sympy.core.basic import _aresame from sympy.core.cache import clear_cache from sympy.core.expr import unchanged from sympy.core.function import (PoleError, _mexpand, arity, BadSignatureError, BadArgumentsError) from sympy.core.sympify import sympify from sympy.matrices import MutableMatrix, ImmutableMatrix from sympy.sets.sets import FiniteSet from sympy.solvers.solveset import solveset from sympy.tensor.array import NDimArray from sympy.utilities.iterables import subsets, variations from sympy.testing.pytest import XFAIL, raises, warns_deprecated_sympy from sympy.abc import t, w, x, y, z f, g, h = symbols('f g h', cls=Function) _xi_1, _xi_2, _xi_3 = [Dummy() for i in range(3)] def test_f_expand_complex(): x = Symbol('x', real=True) assert f(x).expand(complex=True) == I*im(f(x)) + re(f(x)) assert exp(x).expand(complex=True) == exp(x) assert exp(I*x).expand(complex=True) == cos(x) + I*sin(x) assert exp(z).expand(complex=True) == cos(im(z))*exp(re(z)) + \ I*sin(im(z))*exp(re(z)) def test_bug1(): e = sqrt(-log(w)) assert e.subs(log(w), -x) == sqrt(x) e = sqrt(-5*log(w)) assert e.subs(log(w), -x) == sqrt(5*x) def test_general_function(): nu = Function('nu') e = nu(x) edx = e.diff(x) edy = e.diff(y) edxdx = e.diff(x).diff(x) edxdy = e.diff(x).diff(y) assert e == nu(x) assert edx != nu(x) assert edx == diff(nu(x), x) assert edy == 0 assert edxdx == diff(diff(nu(x), x), x) assert edxdy == 0 def test_general_function_nullary(): nu = Function('nu') e = nu() edx = e.diff(x) edxdx = e.diff(x).diff(x) assert e == nu() assert edx != nu() assert edx == 0 assert edxdx == 0 def test_derivative_subs_bug(): e = diff(g(x), x) assert e.subs(g(x), f(x)) != e assert e.subs(g(x), f(x)) == Derivative(f(x), x) assert e.subs(g(x), -f(x)) == Derivative(-f(x), x) assert e.subs(x, y) == Derivative(g(y), y) def test_derivative_subs_self_bug(): d = diff(f(x), x) assert d.subs(d, y) == y def test_derivative_linearity(): assert diff(-f(x), x) == -diff(f(x), x) assert diff(8*f(x), x) == 8*diff(f(x), x) assert diff(8*f(x), x) != 7*diff(f(x), x) assert diff(8*f(x)*x, x) == 8*f(x) + 8*x*diff(f(x), x) assert diff(8*f(x)*y*x, x).expand() == 8*y*f(x) + 8*y*x*diff(f(x), x) def test_derivative_evaluate(): assert Derivative(sin(x), x) != diff(sin(x), x) assert Derivative(sin(x), x).doit() == diff(sin(x), x) assert Derivative(Derivative(f(x), x), x) == diff(f(x), x, x) assert Derivative(sin(x), x, 0) == sin(x) assert Derivative(sin(x), (x, y), (x, -y)) == sin(x) def test_diff_symbols(): assert diff(f(x, y, z), x, y, z) == Derivative(f(x, y, z), x, y, z) assert diff(f(x, y, z), x, x, x) == Derivative(f(x, y, z), x, x, x) == Derivative(f(x, y, z), (x, 3)) assert diff(f(x, y, z), x, 3) == Derivative(f(x, y, z), x, 3) # issue 5028 assert [diff(-z + x/y, sym) for sym in (z, x, y)] == [-1, 1/y, -x/y**2] assert diff(f(x, y, z), x, y, z, 2) == Derivative(f(x, y, z), x, y, z, z) assert diff(f(x, y, z), x, y, z, 2, evaluate=False) == \ Derivative(f(x, y, z), x, y, z, z) assert Derivative(f(x, y, z), x, y, z)._eval_derivative(z) == \ Derivative(f(x, y, z), x, y, z, z) assert Derivative(Derivative(f(x, y, z), x), y)._eval_derivative(z) == \ Derivative(f(x, y, z), x, y, z) raises(TypeError, lambda: cos(x).diff((x, y)).variables) assert cos(x).diff((x, y))._wrt_variables == [x] def test_Function(): class myfunc(Function): @classmethod def eval(cls): # zero args return assert myfunc.nargs == FiniteSet(0) assert myfunc().nargs == FiniteSet(0) raises(TypeError, lambda: myfunc(x).nargs) class myfunc(Function): @classmethod def eval(cls, x): # one arg return assert myfunc.nargs == FiniteSet(1) assert myfunc(x).nargs == FiniteSet(1) raises(TypeError, lambda: myfunc(x, y).nargs) class myfunc(Function): @classmethod def eval(cls, *x): # star args return assert myfunc.nargs == S.Naturals0 assert myfunc(x).nargs == S.Naturals0 def test_nargs(): f = Function('f') assert f.nargs == S.Naturals0 assert f(1).nargs == S.Naturals0 assert Function('f', nargs=2)(1, 2).nargs == FiniteSet(2) assert sin.nargs == FiniteSet(1) assert sin(2).nargs == FiniteSet(1) assert log.nargs == FiniteSet(1, 2) assert log(2).nargs == FiniteSet(1, 2) assert Function('f', nargs=2).nargs == FiniteSet(2) assert Function('f', nargs=0).nargs == FiniteSet(0) assert Function('f', nargs=(0, 1)).nargs == FiniteSet(0, 1) assert Function('f', nargs=None).nargs == S.Naturals0 raises(ValueError, lambda: Function('f', nargs=())) def test_nargs_inheritance(): class f1(Function): nargs = 2 class f2(f1): pass class f3(f2): pass class f4(f3): nargs = 1,2 class f5(f4): pass class f6(f5): pass class f7(f6): nargs=None class f8(f7): pass class f9(f8): pass class f10(f9): nargs = 1 class f11(f10): pass assert f1.nargs == FiniteSet(2) assert f2.nargs == FiniteSet(2) assert f3.nargs == FiniteSet(2) assert f4.nargs == FiniteSet(1, 2) assert f5.nargs == FiniteSet(1, 2) assert f6.nargs == FiniteSet(1, 2) assert f7.nargs == S.Naturals0 assert f8.nargs == S.Naturals0 assert f9.nargs == S.Naturals0 assert f10.nargs == FiniteSet(1) assert f11.nargs == FiniteSet(1) def test_arity(): f = lambda x, y: 1 assert arity(f) == 2 def f(x, y, z=None): pass assert arity(f) == (2, 3) assert arity(lambda *x: x) is None assert arity(log) == (1, 2) def test_Lambda(): e = Lambda(x, x**2) assert e(4) == 16 assert e(x) == x**2 assert e(y) == y**2 assert Lambda((), 42)() == 42 assert unchanged(Lambda, (), 42) assert Lambda((), 42) != Lambda((), 43) assert Lambda((), f(x))() == f(x) assert Lambda((), 42).nargs == FiniteSet(0) assert unchanged(Lambda, (x,), x**2) assert Lambda(x, x**2) == Lambda((x,), x**2) assert Lambda(x, x**2) != Lambda(x, x**2 + 1) assert Lambda((x, y), x**y) != Lambda((y, x), y**x) assert Lambda((x, y), x**y) != Lambda((x, y), y**x) assert Lambda((x, y), x**y)(x, y) == x**y assert Lambda((x, y), x**y)(3, 3) == 3**3 assert Lambda((x, y), x**y)(x, 3) == x**3 assert Lambda((x, y), x**y)(3, y) == 3**y assert Lambda(x, f(x))(x) == f(x) assert Lambda(x, x**2)(e(x)) == x**4 assert e(e(x)) == x**4 x1, x2 = (Indexed('x', i) for i in (1, 2)) assert Lambda((x1, x2), x1 + x2)(x, y) == x + y assert Lambda((x, y), x + y).nargs == FiniteSet(2) p = x, y, z, t assert Lambda(p, t*(x + y + z))(*p) == t * (x + y + z) eq = Lambda(x, 2*x) + Lambda(y, 2*y) assert eq != 2*Lambda(x, 2*x) assert eq.as_dummy() == 2*Lambda(x, 2*x).as_dummy() assert Lambda(x, 2*x) not in [ Lambda(x, x) ] raises(BadSignatureError, lambda: Lambda(1, x)) assert Lambda(x, 1)(1) is S.One raises(BadSignatureError, lambda: Lambda((x, x), x + 2)) raises(BadSignatureError, lambda: Lambda(((x, x), y), x)) raises(BadSignatureError, lambda: Lambda(((y, x), x), x)) raises(BadSignatureError, lambda: Lambda(((y, 1), 2), x)) with warns_deprecated_sympy(): assert Lambda([x, y], x+y) == Lambda((x, y), x+y) flam = Lambda( ((x, y),) , x + y) assert flam((2, 3)) == 5 flam = Lambda( ((x, y), z) , x + y + z) assert flam((2, 3), 1) == 6 flam = Lambda( (((x,y),z),) , x+y+z) assert flam( ((2,3),1) ) == 6 raises(BadArgumentsError, lambda: flam(1, 2, 3)) flam = Lambda( (x,), (x, x)) assert flam(1,) == (1, 1) assert flam((1,)) == ((1,), (1,)) flam = Lambda( ((x,),) , (x, x)) raises(BadArgumentsError, lambda: flam(1)) assert flam((1,)) == (1, 1) # Previously TypeError was raised so this is potentially needed for # backwards compatibility. assert issubclass(BadSignatureError, TypeError) assert issubclass(BadArgumentsError, TypeError) # These are tested to see they don't raise: hash(Lambda(x, 2*x)) hash(Lambda(x, x)) # IdentityFunction subclass def test_IdentityFunction(): assert Lambda(x, x) is Lambda(y, y) is S.IdentityFunction assert Lambda(x, 2*x) is not S.IdentityFunction assert Lambda((x, y), x) is not S.IdentityFunction def test_Lambda_symbols(): assert Lambda(x, 2*x).free_symbols == set() assert Lambda(x, x*y).free_symbols == {y} assert Lambda((), 42).free_symbols == set() assert Lambda((), x*y).free_symbols == {x,y} def test_functionclas_symbols(): assert f.free_symbols == set() def test_Lambda_arguments(): raises(TypeError, lambda: Lambda(x, 2*x)(x, y)) raises(TypeError, lambda: Lambda((x, y), x + y)(x)) raises(TypeError, lambda: Lambda((), 42)(x)) def test_Lambda_equality(): assert Lambda((x, y), 2*x) == Lambda((x, y), 2*x) # these, of course, should never be equal assert Lambda(x, 2*x) != Lambda((x, y), 2*x) assert Lambda(x, 2*x) != 2*x # But it is tempting to want expressions that differ only # in bound symbols to compare the same. But this is not what # Python's `==` is intended to do; two objects that compare # as equal means that they are indistibguishable and cache to the # same value. We wouldn't want to expression that are # mathematically the same but written in different variables to be # interchanged else what is the point of allowing for different # variable names? assert Lambda(x, 2*x) != Lambda(y, 2*y) def test_Subs(): assert Subs(1, (), ()) is S.One # check null subs influence on hashing assert Subs(x, y, z) != Subs(x, y, 1) # neutral subs works assert Subs(x, x, 1).subs(x, y).has(y) # self mapping var/point assert Subs(Derivative(f(x), (x, 2)), x, x).doit() == f(x).diff(x, x) assert Subs(x, x, 0).has(x) # it's a structural answer assert not Subs(x, x, 0).free_symbols assert Subs(Subs(x + y, x, 2), y, 1) == Subs(x + y, (x, y), (2, 1)) assert Subs(x, (x,), (0,)) == Subs(x, x, 0) assert Subs(x, x, 0) == Subs(y, y, 0) assert Subs(x, x, 0).subs(x, 1) == Subs(x, x, 0) assert Subs(y, x, 0).subs(y, 1) == Subs(1, x, 0) assert Subs(f(x), x, 0).doit() == f(0) assert Subs(f(x**2), x**2, 0).doit() == f(0) assert Subs(f(x, y, z), (x, y, z), (0, 1, 1)) != \ Subs(f(x, y, z), (x, y, z), (0, 0, 1)) assert Subs(x, y, 2).subs(x, y).doit() == 2 assert Subs(f(x, y), (x, y, z), (0, 1, 1)) != \ Subs(f(x, y) + z, (x, y, z), (0, 1, 0)) assert Subs(f(x, y), (x, y), (0, 1)).doit() == f(0, 1) assert Subs(Subs(f(x, y), x, 0), y, 1).doit() == f(0, 1) raises(ValueError, lambda: Subs(f(x, y), (x, y), (0, 0, 1))) raises(ValueError, lambda: Subs(f(x, y), (x, x, y), (0, 0, 1))) assert len(Subs(f(x, y), (x, y), (0, 1)).variables) == 2 assert Subs(f(x, y), (x, y), (0, 1)).point == Tuple(0, 1) assert Subs(f(x), x, 0) == Subs(f(y), y, 0) assert Subs(f(x, y), (x, y), (0, 1)) == Subs(f(x, y), (y, x), (1, 0)) assert Subs(f(x)*y, (x, y), (0, 1)) == Subs(f(y)*x, (y, x), (0, 1)) assert Subs(f(x)*y, (x, y), (1, 1)) == Subs(f(y)*x, (x, y), (1, 1)) assert Subs(f(x), x, 0).subs(x, 1).doit() == f(0) assert Subs(f(x), x, y).subs(y, 0) == Subs(f(x), x, 0) assert Subs(y*f(x), x, y).subs(y, 2) == Subs(2*f(x), x, 2) assert (2 * Subs(f(x), x, 0)).subs(Subs(f(x), x, 0), y) == 2*y assert Subs(f(x), x, 0).free_symbols == set() assert Subs(f(x, y), x, z).free_symbols == {y, z} assert Subs(f(x).diff(x), x, 0).doit(), Subs(f(x).diff(x), x, 0) assert Subs(1 + f(x).diff(x), x, 0).doit(), 1 + Subs(f(x).diff(x), x, 0) assert Subs(y*f(x, y).diff(x), (x, y), (0, 2)).doit() == \ 2*Subs(Derivative(f(x, 2), x), x, 0) assert Subs(y**2*f(x), x, 0).diff(y) == 2*y*f(0) e = Subs(y**2*f(x), x, y) assert e.diff(y) == e.doit().diff(y) == y**2*Derivative(f(y), y) + 2*y*f(y) assert Subs(f(x), x, 0) + Subs(f(x), x, 0) == 2*Subs(f(x), x, 0) e1 = Subs(z*f(x), x, 1) e2 = Subs(z*f(y), y, 1) assert e1 + e2 == 2*e1 assert e1.__hash__() == e2.__hash__() assert Subs(z*f(x + 1), x, 1) not in [ e1, e2 ] assert Derivative(f(x), x).subs(x, g(x)) == Derivative(f(g(x)), g(x)) assert Derivative(f(x), x).subs(x, x + y) == Subs(Derivative(f(x), x), x, x + y) assert Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).n(2) == \ Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).evalf(2) == \ z + Rational('1/2').n(2)*f(0) assert f(x).diff(x).subs(x, 0).subs(x, y) == f(x).diff(x).subs(x, 0) assert (x*f(x).diff(x).subs(x, 0)).subs(x, y) == y*f(x).diff(x).subs(x, 0) assert Subs(Derivative(g(x)**2, g(x), x), g(x), exp(x) ).doit() == 2*exp(x) assert Subs(Derivative(g(x)**2, g(x), x), g(x), exp(x) ).doit(deep=False) == 2*Derivative(exp(x), x) assert Derivative(f(x, g(x)), x).doit() == Derivative( f(x, g(x)), g(x))*Derivative(g(x), x) + Subs(Derivative( f(y, g(x)), y), y, x) def test_doitdoit(): done = Derivative(f(x, g(x)), x, g(x)).doit() assert done == done.doit() @XFAIL def test_Subs2(): # this reflects a limitation of subs(), probably won't fix assert Subs(f(x), x**2, x).doit() == f(sqrt(x)) def test_expand_function(): assert expand(x + y) == x + y assert expand(x + y, complex=True) == I*im(x) + I*im(y) + re(x) + re(y) assert expand((x + y)**11, modulus=11) == x**11 + y**11 def test_function_comparable(): assert sin(x).is_comparable is False assert cos(x).is_comparable is False assert sin(Float('0.1')).is_comparable is True assert cos(Float('0.1')).is_comparable is True assert sin(E).is_comparable is True assert cos(E).is_comparable is True assert sin(Rational(1, 3)).is_comparable is True assert cos(Rational(1, 3)).is_comparable is True def test_function_comparable_infinities(): assert sin(oo).is_comparable is False assert sin(-oo).is_comparable is False assert sin(zoo).is_comparable is False assert sin(nan).is_comparable is False def test_deriv1(): # These all require derivatives evaluated at a point (issue 4719) to work. # See issue 4624 assert f(2*x).diff(x) == 2*Subs(Derivative(f(x), x), x, 2*x) assert (f(x)**3).diff(x) == 3*f(x)**2*f(x).diff(x) assert (f(2*x)**3).diff(x) == 6*f(2*x)**2*Subs( Derivative(f(x), x), x, 2*x) assert f(2 + x).diff(x) == Subs(Derivative(f(x), x), x, x + 2) assert f(2 + 3*x).diff(x) == 3*Subs( Derivative(f(x), x), x, 3*x + 2) assert f(3*sin(x)).diff(x) == 3*cos(x)*Subs( Derivative(f(x), x), x, 3*sin(x)) # See issue 8510 assert f(x, x + z).diff(x) == ( Subs(Derivative(f(y, x + z), y), y, x) + Subs(Derivative(f(x, y), y), y, x + z)) assert f(x, x**2).diff(x) == ( 2*x*Subs(Derivative(f(x, y), y), y, x**2) + Subs(Derivative(f(y, x**2), y), y, x)) # but Subs is not always necessary assert f(x, g(y)).diff(g(y)) == Derivative(f(x, g(y)), g(y)) def test_deriv2(): assert (x**3).diff(x) == 3*x**2 assert (x**3).diff(x, evaluate=False) != 3*x**2 assert (x**3).diff(x, evaluate=False) == Derivative(x**3, x) assert diff(x**3, x) == 3*x**2 assert diff(x**3, x, evaluate=False) != 3*x**2 assert diff(x**3, x, evaluate=False) == Derivative(x**3, x) def test_func_deriv(): assert f(x).diff(x) == Derivative(f(x), x) # issue 4534 assert f(x, y).diff(x, y) - f(x, y).diff(y, x) == 0 assert Derivative(f(x, y), x, y).args[1:] == ((x, 1), (y, 1)) assert Derivative(f(x, y), y, x).args[1:] == ((y, 1), (x, 1)) assert (Derivative(f(x, y), x, y) - Derivative(f(x, y), y, x)).doit() == 0 def test_suppressed_evaluation(): a = sin(0, evaluate=False) assert a != 0 assert a.func is sin assert a.args == (0,) def test_function_evalf(): def eq(a, b, eps): return abs(a - b) < eps assert eq(sin(1).evalf(15), Float("0.841470984807897"), 1e-13) assert eq( sin(2).evalf(25), Float("0.9092974268256816953960199", 25), 1e-23) assert eq(sin(1 + I).evalf( 15), Float("1.29845758141598") + Float("0.634963914784736")*I, 1e-13) assert eq(exp(1 + I).evalf(15), Float( "1.46869393991588") + Float("2.28735528717884239")*I, 1e-13) assert eq(exp(-0.5 + 1.5*I).evalf(15), Float( "0.0429042815937374") + Float("0.605011292285002")*I, 1e-13) assert eq(log(pi + sqrt(2)*I).evalf( 15), Float("1.23699044022052") + Float("0.422985442737893")*I, 1e-13) assert eq(cos(100).evalf(15), Float("0.86231887228768"), 1e-13) def test_extensibility_eval(): class MyFunc(Function): @classmethod def eval(cls, *args): return (0, 0, 0) assert MyFunc(0) == (0, 0, 0) def test_function_non_commutative(): x = Symbol('x', commutative=False) assert f(x).is_commutative is False assert sin(x).is_commutative is False assert exp(x).is_commutative is False assert log(x).is_commutative is False assert f(x).is_complex is False assert sin(x).is_complex is False assert exp(x).is_complex is False assert log(x).is_complex is False def test_function_complex(): x = Symbol('x', complex=True) xzf = Symbol('x', complex=True, zero=False) assert f(x).is_commutative is True assert sin(x).is_commutative is True assert exp(x).is_commutative is True assert log(x).is_commutative is True assert f(x).is_complex is None assert sin(x).is_complex is True assert exp(x).is_complex is True assert log(x).is_complex is None assert log(xzf).is_complex is True def test_function__eval_nseries(): n = Symbol('n') assert sin(x)._eval_nseries(x, 2, None) == x + O(x**2) assert sin(x + 1)._eval_nseries(x, 2, None) == x*cos(1) + sin(1) + O(x**2) assert sin(pi*(1 - x))._eval_nseries(x, 2, None) == pi*x + O(x**2) assert acos(1 - x**2)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(x**2) + O(x**2) assert polygamma(n, x + 1)._eval_nseries(x, 2, None) == \ polygamma(n, 1) + polygamma(n + 1, 1)*x + O(x**2) raises(PoleError, lambda: sin(1/x)._eval_nseries(x, 2, None)) assert acos(1 - x)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(x) + sqrt(2)*x**(S(3)/2)/12 + O(x**2) assert acos(1 + x)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(-x) + sqrt(2)*(-x)**(S(3)/2)/12 + O(x**2) assert loggamma(1/x)._eval_nseries(x, 0, None) == \ log(x)/2 - log(x)/x - 1/x + O(1, x) assert loggamma(log(1/x)).nseries(x, n=1, logx=y) == loggamma(-y) # issue 6725: assert expint(Rational(3, 2), -x)._eval_nseries(x, 5, None) == \ 2 - 2*sqrt(pi)*sqrt(-x) - 2*x + x**2 + x**3/3 + x**4/12 + 4*I*x**(S(3)/2)*sqrt(-x)/3 + \ 2*I*x**(S(5)/2)*sqrt(-x)/5 + 2*I*x**(S(7)/2)*sqrt(-x)/21 + O(x**5) assert sin(sqrt(x))._eval_nseries(x, 3, None) == \ sqrt(x) - x**Rational(3, 2)/6 + x**Rational(5, 2)/120 + O(x**3) # issue 19065: s1 = f(x,y).series(y, n=2) assert {i.name for i in s1.atoms(Symbol)} == {'x', 'xi', 'y'} xi = Symbol('xi') s2 = f(xi, y).series(y, n=2) assert {i.name for i in s2.atoms(Symbol)} == {'xi', 'xi0', 'y'} def test_doit(): n = Symbol('n', integer=True) f = Sum(2 * n * x, (n, 1, 3)) d = Derivative(f, x) assert d.doit() == 12 assert d.doit(deep=False) == Sum(2*n, (n, 1, 3)) def test_evalf_default(): from sympy.functions.special.gamma_functions import polygamma assert type(sin(4.0)) == Float assert type(re(sin(I + 1.0))) == Float assert type(im(sin(I + 1.0))) == Float assert type(sin(4)) == sin assert type(polygamma(2.0, 4.0)) == Float assert type(sin(Rational(1, 4))) == sin def test_issue_5399(): args = [x, y, S(2), S.Half] def ok(a): """Return True if the input args for diff are ok""" if not a: return False if a[0].is_Symbol is False: return False s_at = [i for i in range(len(a)) if a[i].is_Symbol] n_at = [i for i in range(len(a)) if not a[i].is_Symbol] # every symbol is followed by symbol or int # every number is followed by a symbol return (all(a[i + 1].is_Symbol or a[i + 1].is_Integer for i in s_at if i + 1 < len(a)) and all(a[i + 1].is_Symbol for i in n_at if i + 1 < len(a))) eq = x**10*y**8 for a in subsets(args): for v in variations(a, len(a)): if ok(v): eq.diff(*v) # does not raise else: raises(ValueError, lambda: eq.diff(*v)) def test_derivative_numerically(): from random import random z0 = random() + I*random() assert abs(Derivative(sin(x), x).doit_numerically(z0) - cos(z0)) < 1e-15 def test_fdiff_argument_index_error(): from sympy.core.function import ArgumentIndexError class myfunc(Function): nargs = 1 # define since there is no eval routine def fdiff(self, idx): raise ArgumentIndexError mf = myfunc(x) assert mf.diff(x) == Derivative(mf, x) raises(TypeError, lambda: myfunc(x, x)) def test_deriv_wrt_function(): x = f(t) xd = diff(x, t) xdd = diff(xd, t) y = g(t) yd = diff(y, t) assert diff(x, t) == xd assert diff(2 * x + 4, t) == 2 * xd assert diff(2 * x + 4 + y, t) == 2 * xd + yd assert diff(2 * x + 4 + y * x, t) == 2 * xd + x * yd + xd * y assert diff(2 * x + 4 + y * x, x) == 2 + y assert (diff(4 * x**2 + 3 * x + x * y, t) == 3 * xd + x * yd + xd * y + 8 * x * xd) assert (diff(4 * x**2 + 3 * xd + x * y, t) == 3 * xdd + x * yd + xd * y + 8 * x * xd) assert diff(4 * x**2 + 3 * xd + x * y, xd) == 3 assert diff(4 * x**2 + 3 * xd + x * y, xdd) == 0 assert diff(sin(x), t) == xd * cos(x) assert diff(exp(x), t) == xd * exp(x) assert diff(sqrt(x), t) == xd / (2 * sqrt(x)) def test_diff_wrt_value(): assert Expr()._diff_wrt is False assert x._diff_wrt is True assert f(x)._diff_wrt is True assert Derivative(f(x), x)._diff_wrt is True assert Derivative(x**2, x)._diff_wrt is False def test_diff_wrt(): fx = f(x) dfx = diff(f(x), x) ddfx = diff(f(x), x, x) assert diff(sin(fx) + fx**2, fx) == cos(fx) + 2*fx assert diff(sin(dfx) + dfx**2, dfx) == cos(dfx) + 2*dfx assert diff(sin(ddfx) + ddfx**2, ddfx) == cos(ddfx) + 2*ddfx assert diff(fx**2, dfx) == 0 assert diff(fx**2, ddfx) == 0 assert diff(dfx**2, fx) == 0 assert diff(dfx**2, ddfx) == 0 assert diff(ddfx**2, dfx) == 0 assert diff(fx*dfx*ddfx, fx) == dfx*ddfx assert diff(fx*dfx*ddfx, dfx) == fx*ddfx assert diff(fx*dfx*ddfx, ddfx) == fx*dfx assert diff(f(x), x).diff(f(x)) == 0 assert (sin(f(x)) - cos(diff(f(x), x))).diff(f(x)) == cos(f(x)) assert diff(sin(fx), fx, x) == diff(sin(fx), x, fx) # Chain rule cases assert f(g(x)).diff(x) == \ Derivative(g(x), x)*Derivative(f(g(x)), g(x)) assert diff(f(g(x), h(y)), x) == \ Derivative(g(x), x)*Derivative(f(g(x), h(y)), g(x)) assert diff(f(g(x), h(x)), x) == ( Derivative(f(g(x), h(x)), g(x))*Derivative(g(x), x) + Derivative(f(g(x), h(x)), h(x))*Derivative(h(x), x)) assert f( sin(x)).diff(x) == cos(x)*Subs(Derivative(f(x), x), x, sin(x)) assert diff(f(g(x)), g(x)) == Derivative(f(g(x)), g(x)) def test_diff_wrt_func_subs(): assert f(g(x)).diff(x).subs(g, Lambda(x, 2*x)).doit() == f(2*x).diff(x) def test_subs_in_derivative(): expr = sin(x*exp(y)) u = Function('u') v = Function('v') assert Derivative(expr, y).subs(expr, y) == Derivative(y, y) assert Derivative(expr, y).subs(y, x).doit() == \ Derivative(expr, y).doit().subs(y, x) assert Derivative(f(x, y), y).subs(y, x) == Subs(Derivative(f(x, y), y), y, x) assert Derivative(f(x, y), y).subs(x, y) == Subs(Derivative(f(x, y), y), x, y) assert Derivative(f(x, y), y).subs(y, g(x, y)) == Subs(Derivative(f(x, y), y), y, g(x, y)).doit() assert Derivative(f(x, y), y).subs(x, g(x, y)) == Subs(Derivative(f(x, y), y), x, g(x, y)) assert Derivative(f(x, y), g(y)).subs(x, g(x, y)) == Derivative(f(g(x, y), y), g(y)) assert Derivative(f(u(x), h(y)), h(y)).subs(h(y), g(x, y)) == \ Subs(Derivative(f(u(x), h(y)), h(y)), h(y), g(x, y)).doit() assert Derivative(f(x, y), y).subs(y, z) == Derivative(f(x, z), z) assert Derivative(f(x, y), y).subs(y, g(y)) == Derivative(f(x, g(y)), g(y)) assert Derivative(f(g(x), h(y)), h(y)).subs(h(y), u(y)) == \ Derivative(f(g(x), u(y)), u(y)) assert Derivative(f(x, f(x, x)), f(x, x)).subs( f, Lambda((x, y), x + y)) == Subs( Derivative(z + x, z), z, 2*x) assert Subs(Derivative(f(f(x)), x), f, cos).doit() == sin(x)*sin(cos(x)) assert Subs(Derivative(f(f(x)), f(x)), f, cos).doit() == -sin(cos(x)) # Issue 13791. No comparison (it's a long formula) but this used to raise an exception. assert isinstance(v(x, y, u(x, y)).diff(y).diff(x).diff(y), Expr) # This is also related to issues 13791 and 13795; issue 15190 F = Lambda((x, y), exp(2*x + 3*y)) abstract = f(x, f(x, x)).diff(x, 2) concrete = F(x, F(x, x)).diff(x, 2) assert (abstract.subs(f, F).doit() - concrete).simplify() == 0 # don't introduce a new symbol if not necessary assert x in f(x).diff(x).subs(x, 0).atoms() # case (4) assert Derivative(f(x,f(x,y)), x, y).subs(x, g(y) ) == Subs(Derivative(f(x, f(x, y)), x, y), x, g(y)) assert Derivative(f(x, x), x).subs(x, 0 ) == Subs(Derivative(f(x, x), x), x, 0) # issue 15194 assert Derivative(f(y, g(x)), (x, z)).subs(z, x ) == Derivative(f(y, g(x)), (x, x)) df = f(x).diff(x) assert df.subs(df, 1) is S.One assert df.diff(df) is S.One dxy = Derivative(f(x, y), x, y) dyx = Derivative(f(x, y), y, x) assert dxy.subs(Derivative(f(x, y), y, x), 1) is S.One assert dxy.diff(dyx) is S.One assert Derivative(f(x, y), x, 2, y, 3).subs( dyx, g(x, y)) == Derivative(g(x, y), x, 1, y, 2) assert Derivative(f(x, x - y), y).subs(x, x + y) == Subs( Derivative(f(x, x - y), y), x, x + y) def test_diff_wrt_not_allowed(): # issue 7027 included for wrt in ( cos(x), re(x), x**2, x*y, 1 + x, Derivative(cos(x), x), Derivative(f(f(x)), x)): raises(ValueError, lambda: diff(f(x), wrt)) # if we don't differentiate wrt then don't raise error assert diff(exp(x*y), x*y, 0) == exp(x*y) def test_klein_gordon_lagrangian(): m = Symbol('m') phi = f(x, t) L = -(diff(phi, t)**2 - diff(phi, x)**2 - m**2*phi**2)/2 eqna = Eq( diff(L, phi) - diff(L, diff(phi, x), x) - diff(L, diff(phi, t), t), 0) eqnb = Eq(diff(phi, t, t) - diff(phi, x, x) + m**2*phi, 0) assert eqna == eqnb def test_sho_lagrangian(): m = Symbol('m') k = Symbol('k') x = f(t) L = m*diff(x, t)**2/2 - k*x**2/2 eqna = Eq(diff(L, x), diff(L, diff(x, t), t)) eqnb = Eq(-k*x, m*diff(x, t, t)) assert eqna == eqnb assert diff(L, x, t) == diff(L, t, x) assert diff(L, diff(x, t), t) == m*diff(x, t, 2) assert diff(L, t, diff(x, t)) == -k*x + m*diff(x, t, 2) def test_straight_line(): F = f(x) Fd = F.diff(x) L = sqrt(1 + Fd**2) assert diff(L, F) == 0 assert diff(L, Fd) == Fd/sqrt(1 + Fd**2) def test_sort_variable(): vsort = Derivative._sort_variable_count def vsort0(*v, reverse=False): return [i[0] for i in vsort([(i, 0) for i in ( reversed(v) if reverse else v)])] for R in range(2): assert vsort0(y, x, reverse=R) == [x, y] assert vsort0(f(x), x, reverse=R) == [x, f(x)] assert vsort0(f(y), f(x), reverse=R) == [f(x), f(y)] assert vsort0(g(x), f(y), reverse=R) == [f(y), g(x)] assert vsort0(f(x, y), f(x), reverse=R) == [f(x), f(x, y)] fx = f(x).diff(x) assert vsort0(fx, y, reverse=R) == [y, fx] fy = f(y).diff(y) assert vsort0(fy, fx, reverse=R) == [fx, fy] fxx = fx.diff(x) assert vsort0(fxx, fx, reverse=R) == [fx, fxx] assert vsort0(Basic(x), f(x), reverse=R) == [f(x), Basic(x)] assert vsort0(Basic(y), Basic(x), reverse=R) == [Basic(x), Basic(y)] assert vsort0(Basic(y, z), Basic(x), reverse=R) == [ Basic(x), Basic(y, z)] assert vsort0(fx, x, reverse=R) == [ x, fx] if R else [fx, x] assert vsort0(Basic(x), x, reverse=R) == [ x, Basic(x)] if R else [Basic(x), x] assert vsort0(Basic(f(x)), f(x), reverse=R) == [ f(x), Basic(f(x))] if R else [Basic(f(x)), f(x)] assert vsort0(Basic(x, z), Basic(x), reverse=R) == [ Basic(x), Basic(x, z)] if R else [Basic(x, z), Basic(x)] assert vsort([]) == [] assert _aresame(vsort([(x, 1)]), [Tuple(x, 1)]) assert vsort([(x, y), (x, z)]) == [(x, y + z)] assert vsort([(y, 1), (x, 1 + y)]) == [(x, 1 + y), (y, 1)] # coverage complete; legacy tests below assert vsort([(x, 3), (y, 2), (z, 1)]) == [(x, 3), (y, 2), (z, 1)] assert vsort([(h(x), 1), (g(x), 1), (f(x), 1)]) == [ (f(x), 1), (g(x), 1), (h(x), 1)] assert vsort([(z, 1), (y, 2), (x, 3), (h(x), 1), (g(x), 1), (f(x), 1)]) == [(x, 3), (y, 2), (z, 1), (f(x), 1), (g(x), 1), (h(x), 1)] assert vsort([(x, 1), (f(x), 1), (y, 1), (f(y), 1)]) == [(x, 1), (y, 1), (f(x), 1), (f(y), 1)] assert vsort([(y, 1), (x, 2), (g(x), 1), (f(x), 1), (z, 1), (h(x), 1), (y, 2), (x, 1)]) == [(x, 3), (y, 3), (z, 1), (f(x), 1), (g(x), 1), (h(x), 1)] assert vsort([(z, 1), (y, 1), (f(x), 1), (x, 1), (f(x), 1), (g(x), 1)]) == [(x, 1), (y, 1), (z, 1), (f(x), 2), (g(x), 1)] assert vsort([(z, 1), (y, 2), (f(x), 1), (x, 2), (f(x), 2), (g(x), 1), (z, 2), (z, 1), (y, 1), (x, 1)]) == [(x, 3), (y, 3), (z, 4), (f(x), 3), (g(x), 1)] assert vsort(((y, 2), (x, 1), (y, 1), (x, 1))) == [(x, 2), (y, 3)] assert isinstance(vsort([(x, 3), (y, 2), (z, 1)])[0], Tuple) assert vsort([(x, 1), (f(x), 1), (x, 1)]) == [(x, 2), (f(x), 1)] assert vsort([(y, 2), (x, 3), (z, 1)]) == [(x, 3), (y, 2), (z, 1)] assert vsort([(h(y), 1), (g(x), 1), (f(x), 1)]) == [ (f(x), 1), (g(x), 1), (h(y), 1)] assert vsort([(x, 1), (y, 1), (x, 1)]) == [(x, 2), (y, 1)] assert vsort([(f(x), 1), (f(y), 1), (f(x), 1)]) == [ (f(x), 2), (f(y), 1)] dfx = f(x).diff(x) self = [(dfx, 1), (x, 1)] assert vsort(self) == self assert vsort([ (dfx, 1), (y, 1), (f(x), 1), (x, 1), (f(y), 1), (x, 1)]) == [ (y, 1), (f(x), 1), (f(y), 1), (dfx, 1), (x, 2)] dfy = f(y).diff(y) assert vsort([(dfy, 1), (dfx, 1)]) == [(dfx, 1), (dfy, 1)] d2fx = dfx.diff(x) assert vsort([(d2fx, 1), (dfx, 1)]) == [(dfx, 1), (d2fx, 1)] def test_multiple_derivative(): # Issue #15007 assert f(x, y).diff(y, y, x, y, x ) == Derivative(f(x, y), (x, 2), (y, 3)) def test_unhandled(): class MyExpr(Expr): def _eval_derivative(self, s): if not s.name.startswith('xi'): return self else: return None eq = MyExpr(f(x), y, z) assert diff(eq, x, y, f(x), z) == Derivative(eq, f(x)) assert diff(eq, f(x), x) == Derivative(eq, f(x)) assert f(x, y).diff(x,(y, z)) == Derivative(f(x, y), x, (y, z)) assert f(x, y).diff(x,(y, 0)) == Derivative(f(x, y), x) def test_nfloat(): from sympy.core.basic import _aresame from sympy.polys.rootoftools import rootof x = Symbol("x") eq = x**Rational(4, 3) + 4*x**(S.One/3)/3 assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0/3)*x**(S.One/3)) assert _aresame(nfloat(eq, exponent=True), x**(4.0/3) + (4.0/3)*x**(1.0/3)) eq = x**Rational(4, 3) + 4*x**(x/3)/3 assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0/3)*x**(x/3)) big = 12345678901234567890 # specify precision to match value used in nfloat Float_big = Float(big, 15) assert _aresame(nfloat(big), Float_big) assert _aresame(nfloat(big*x), Float_big*x) assert _aresame(nfloat(x**big, exponent=True), x**Float_big) assert nfloat(cos(x + sqrt(2))) == cos(x + nfloat(sqrt(2))) # issue 6342 f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4') assert not any(a.free_symbols for a in solveset(f.subs(x, -0.139))) # issue 6632 assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \ 9.99999999800000e-11 # issue 7122 eq = cos(3*x**4 + y)*rootof(x**5 + 3*x**3 + 1, 0) assert str(nfloat(eq, exponent=False, n=1)) == '-0.7*cos(3.0*x**4 + y)' # issue 10933 for ti in (dict, Dict): d = ti({S.Half: S.Half}) n = nfloat(d) assert isinstance(n, ti) assert _aresame(list(n.items()).pop(), (S.Half, Float(.5))) for ti in (dict, Dict): d = ti({S.Half: S.Half}) n = nfloat(d, dkeys=True) assert isinstance(n, ti) assert _aresame(list(n.items()).pop(), (Float(.5), Float(.5))) d = [S.Half] n = nfloat(d) assert type(n) is list assert _aresame(n[0], Float(.5)) assert _aresame(nfloat(Eq(x, S.Half)).rhs, Float(.5)) assert _aresame(nfloat(S(True)), S(True)) assert _aresame(nfloat(Tuple(S.Half))[0], Float(.5)) assert nfloat(Eq((3 - I)**2/2 + I, 0)) == S.false # pass along kwargs assert nfloat([{S.Half: x}], dkeys=True) == [{Float(0.5): x}] # Issue 17706 A = MutableMatrix([[1, 2], [3, 4]]) B = MutableMatrix( [[Float('1.0', precision=53), Float('2.0', precision=53)], [Float('3.0', precision=53), Float('4.0', precision=53)]]) assert _aresame(nfloat(A), B) A = ImmutableMatrix([[1, 2], [3, 4]]) B = ImmutableMatrix( [[Float('1.0', precision=53), Float('2.0', precision=53)], [Float('3.0', precision=53), Float('4.0', precision=53)]]) assert _aresame(nfloat(A), B) def test_issue_7068(): from sympy.abc import a, b f = Function('f') y1 = Dummy('y') y2 = Dummy('y') func1 = f(a + y1 * b) func2 = f(a + y2 * b) func1_y = func1.diff(y1) func2_y = func2.diff(y2) assert func1_y != func2_y z1 = Subs(f(a), a, y1) z2 = Subs(f(a), a, y2) assert z1 != z2 def test_issue_7231(): from sympy.abc import a ans1 = f(x).series(x, a) res = (f(a) + (-a + x)*Subs(Derivative(f(y), y), y, a) + (-a + x)**2*Subs(Derivative(f(y), y, y), y, a)/2 + (-a + x)**3*Subs(Derivative(f(y), y, y, y), y, a)/6 + (-a + x)**4*Subs(Derivative(f(y), y, y, y, y), y, a)/24 + (-a + x)**5*Subs(Derivative(f(y), y, y, y, y, y), y, a)/120 + O((-a + x)**6, (x, a))) assert res == ans1 ans2 = f(x).series(x, a) assert res == ans2 def test_issue_7687(): from sympy.core.function import Function from sympy.abc import x f = Function('f')(x) ff = Function('f')(x) match_with_cache = ff.matches(f) assert isinstance(f, type(ff)) clear_cache() ff = Function('f')(x) assert isinstance(f, type(ff)) assert match_with_cache == ff.matches(f) def test_issue_7688(): from sympy.core.function import Function, UndefinedFunction f = Function('f') # actually an UndefinedFunction clear_cache() class A(UndefinedFunction): pass a = A('f') assert isinstance(a, type(f)) def test_mexpand(): from sympy.abc import x assert _mexpand(None) is None assert _mexpand(1) is S.One assert _mexpand(x*(x + 1)**2) == (x*(x + 1)**2).expand() def test_issue_8469(): # This should not take forever to run N = 40 def g(w, theta): return 1/(1+exp(w-theta)) ws = symbols(['w%i'%i for i in range(N)]) import functools expr = functools.reduce(g, ws) assert isinstance(expr, Pow) def test_issue_12996(): # foo=True imitates the sort of arguments that Derivative can get # from Integral when it passes doit to the expression assert Derivative(im(x), x).doit(foo=True) == Derivative(im(x), x) def test_should_evalf(): # This should not take forever to run (see #8506) assert isinstance(sin((1.0 + 1.0*I)**10000 + 1), sin) def test_Derivative_as_finite_difference(): # Central 1st derivative at gridpoint x, h = symbols('x h', real=True) dfdx = f(x).diff(x) assert (dfdx.as_finite_difference([x-2, x-1, x, x+1, x+2]) - (S.One/12*(f(x-2)-f(x+2)) + Rational(2, 3)*(f(x+1)-f(x-1)))).simplify() == 0 # Central 1st derivative "half-way" assert (dfdx.as_finite_difference() - (f(x + S.Half)-f(x - S.Half))).simplify() == 0 assert (dfdx.as_finite_difference(h) - (f(x + h/S(2))-f(x - h/S(2)))/h).simplify() == 0 assert (dfdx.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) - (S(9)/(8*2*h)*(f(x+h) - f(x-h)) + S.One/(24*2*h)*(f(x - 3*h) - f(x + 3*h)))).simplify() == 0 # One sided 1st derivative at gridpoint assert (dfdx.as_finite_difference([0, 1, 2], 0) - (Rational(-3, 2)*f(0) + 2*f(1) - f(2)/2)).simplify() == 0 assert (dfdx.as_finite_difference([x, x+h], x) - (f(x+h) - f(x))/h).simplify() == 0 assert (dfdx.as_finite_difference([x-h, x, x+h], x-h) - (-S(3)/(2*h)*f(x-h) + 2/h*f(x) - S.One/(2*h)*f(x+h))).simplify() == 0 # One sided 1st derivative "half-way" assert (dfdx.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h, x + 7*h]) - 1/(2*h)*(-S(11)/(12)*f(x-h) + S(17)/(24)*f(x+h) + Rational(3, 8)*f(x + 3*h) - Rational(5, 24)*f(x + 5*h) + S.One/24*f(x + 7*h))).simplify() == 0 d2fdx2 = f(x).diff(x, 2) # Central 2nd derivative at gridpoint assert (d2fdx2.as_finite_difference([x-h, x, x+h]) - h**-2 * (f(x-h) + f(x+h) - 2*f(x))).simplify() == 0 assert (d2fdx2.as_finite_difference([x - 2*h, x-h, x, x+h, x + 2*h]) - h**-2 * (Rational(-1, 12)*(f(x - 2*h) + f(x + 2*h)) + Rational(4, 3)*(f(x+h) + f(x-h)) - Rational(5, 2)*f(x))).simplify() == 0 # Central 2nd derivative "half-way" assert (d2fdx2.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) - (2*h)**-2 * (S.Half*(f(x - 3*h) + f(x + 3*h)) - S.Half*(f(x+h) + f(x-h)))).simplify() == 0 # One sided 2nd derivative at gridpoint assert (d2fdx2.as_finite_difference([x, x+h, x + 2*h, x + 3*h]) - h**-2 * (2*f(x) - 5*f(x+h) + 4*f(x+2*h) - f(x+3*h))).simplify() == 0 # One sided 2nd derivative at "half-way" assert (d2fdx2.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h]) - (2*h)**-2 * (Rational(3, 2)*f(x-h) - Rational(7, 2)*f(x+h) + Rational(5, 2)*f(x + 3*h) - S.Half*f(x + 5*h))).simplify() == 0 d3fdx3 = f(x).diff(x, 3) # Central 3rd derivative at gridpoint assert (d3fdx3.as_finite_difference() - (-f(x - Rational(3, 2)) + 3*f(x - S.Half) - 3*f(x + S.Half) + f(x + Rational(3, 2)))).simplify() == 0 assert (d3fdx3.as_finite_difference( [x - 3*h, x - 2*h, x-h, x, x+h, x + 2*h, x + 3*h]) - h**-3 * (S.One/8*(f(x - 3*h) - f(x + 3*h)) - f(x - 2*h) + f(x + 2*h) + Rational(13, 8)*(f(x-h) - f(x+h)))).simplify() == 0 # Central 3rd derivative at "half-way" assert (d3fdx3.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) - (2*h)**-3 * (f(x + 3*h)-f(x - 3*h) + 3*(f(x-h)-f(x+h)))).simplify() == 0 # One sided 3rd derivative at gridpoint assert (d3fdx3.as_finite_difference([x, x+h, x + 2*h, x + 3*h]) - h**-3 * (f(x + 3*h)-f(x) + 3*(f(x+h)-f(x + 2*h)))).simplify() == 0 # One sided 3rd derivative at "half-way" assert (d3fdx3.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h]) - (2*h)**-3 * (f(x + 5*h)-f(x-h) + 3*(f(x+h)-f(x + 3*h)))).simplify() == 0 # issue 11007 y = Symbol('y', real=True) d2fdxdy = f(x, y).diff(x, y) ref0 = Derivative(f(x + S.Half, y), y) - Derivative(f(x - S.Half, y), y) assert (d2fdxdy.as_finite_difference(wrt=x) - ref0).simplify() == 0 half = S.Half xm, xp, ym, yp = x-half, x+half, y-half, y+half ref2 = f(xm, ym) + f(xp, yp) - f(xp, ym) - f(xm, yp) assert (d2fdxdy.as_finite_difference() - ref2).simplify() == 0 def test_issue_11159(): # Tests Application._eval_subs expr1 = E expr0 = expr1 * expr1 expr1 = expr0.subs(expr1,expr0) assert expr0 == expr1 def test_issue_12005(): e1 = Subs(Derivative(f(x), x), x, x) assert e1.diff(x) == Derivative(f(x), x, x) e2 = Subs(Derivative(f(x), x), x, x**2 + 1) assert e2.diff(x) == 2*x*Subs(Derivative(f(x), x, x), x, x**2 + 1) e3 = Subs(Derivative(f(x) + y**2 - y, y), y, y**2) assert e3.diff(y) == 4*y e4 = Subs(Derivative(f(x + y), y), y, (x**2)) assert e4.diff(y) is S.Zero e5 = Subs(Derivative(f(x), x), (y, z), (y, z)) assert e5.diff(x) == Derivative(f(x), x, x) assert f(g(x)).diff(g(x), g(x)) == Derivative(f(g(x)), g(x), g(x)) def test_issue_13843(): x = symbols('x') f = Function('f') m, n = symbols('m n', integer=True) assert Derivative(Derivative(f(x), (x, m)), (x, n)) == Derivative(f(x), (x, m + n)) assert Derivative(Derivative(f(x), (x, m+5)), (x, n+3)) == Derivative(f(x), (x, m + n + 8)) assert Derivative(f(x), (x, n)).doit() == Derivative(f(x), (x, n)) def test_order_could_be_zero(): x, y = symbols('x, y') n = symbols('n', integer=True, nonnegative=True) m = symbols('m', integer=True, positive=True) assert diff(y, (x, n)) == Piecewise((y, Eq(n, 0)), (0, True)) assert diff(y, (x, n + 1)) is S.Zero assert diff(y, (x, m)) is S.Zero def test_undefined_function_eq(): f = Function('f') f2 = Function('f') g = Function('g') f_real = Function('f', is_real=True) # This test may only be meaningful if the cache is turned off assert f == f2 assert hash(f) == hash(f2) assert f == f assert f != g assert f != f_real def test_function_assumptions(): x = Symbol('x') f = Function('f') f_real = Function('f', real=True) f_real1 = Function('f', real=1) f_real_inherit = Function(Symbol('f', real=True)) assert f_real == f_real1 # assumptions are sanitized assert f != f_real assert f(x) != f_real(x) assert f(x).is_real is None assert f_real(x).is_real is True assert f_real_inherit(x).is_real is True and f_real_inherit.name == 'f' # Can also do it this way, but it won't be equal to f_real because of the # way UndefinedFunction.__new__ works. Any non-recognized assumptions # are just added literally as something which is used in the hash f_real2 = Function('f', is_real=True) assert f_real2(x).is_real is True def test_undef_fcn_float_issue_6938(): f = Function('ceil') assert not f(0.3).is_number f = Function('sin') assert not f(0.3).is_number assert not f(pi).evalf().is_number x = Symbol('x') assert not f(x).evalf(subs={x:1.2}).is_number def test_undefined_function_eval(): # Issue 15170. Make sure UndefinedFunction with eval defined works # properly. The issue there was that the hash was determined before _nargs # was set, which is included in the hash, hence changing the hash. The # class is added to sympy.core.core.all_classes before the hash is # changed, meaning "temp in all_classes" would fail, causing sympify(temp(t)) # to give a new class. We will eventually remove all_classes, but make # sure this continues to work. fdiff = lambda self, argindex=1: cos(self.args[argindex - 1]) eval = classmethod(lambda cls, t: None) _imp_ = classmethod(lambda cls, t: sin(t)) temp = Function('temp', fdiff=fdiff, eval=eval, _imp_=_imp_) expr = temp(t) assert sympify(expr) == expr assert type(sympify(expr)).fdiff.__name__ == "<lambda>" assert expr.diff(t) == cos(t) def test_issue_15241(): F = f(x) Fx = F.diff(x) assert (F + x*Fx).diff(x, Fx) == 2 assert (F + x*Fx).diff(Fx, x) == 1 assert (x*F + x*Fx*F).diff(F, x) == x*Fx.diff(x) + Fx + 1 assert (x*F + x*Fx*F).diff(x, F) == x*Fx.diff(x) + Fx + 1 y = f(x) G = f(y) Gy = G.diff(y) assert (G + y*Gy).diff(y, Gy) == 2 assert (G + y*Gy).diff(Gy, y) == 1 assert (y*G + y*Gy*G).diff(G, y) == y*Gy.diff(y) + Gy + 1 assert (y*G + y*Gy*G).diff(y, G) == y*Gy.diff(y) + Gy + 1 def test_issue_15226(): assert Subs(Derivative(f(y), x, y), y, g(x)).doit() != 0 def test_issue_7027(): for wrt in (cos(x), re(x), Derivative(cos(x), x)): raises(ValueError, lambda: diff(f(x), wrt)) def test_derivative_quick_exit(): assert f(x).diff(y) == 0 assert f(x).diff(y, f(x)) == 0 assert f(x).diff(x, f(y)) == 0 assert f(f(x)).diff(x, f(x), f(y)) == 0 assert f(f(x)).diff(x, f(x), y) == 0 assert f(x).diff(g(x)) == 0 assert f(x).diff(x, f(x).diff(x)) == 1 df = f(x).diff(x) assert f(x).diff(df) == 0 dg = g(x).diff(x) assert dg.diff(df).doit() == 0 def test_issue_15084_13166(): eq = f(x, g(x)) assert eq.diff((g(x), y)) == Derivative(f(x, g(x)), (g(x), y)) # issue 13166 assert eq.diff(x, 2).doit() == ( (Derivative(f(x, g(x)), (g(x), 2))*Derivative(g(x), x) + Subs(Derivative(f(x, _xi_2), _xi_2, x), _xi_2, g(x)))*Derivative(g(x), x) + Derivative(f(x, g(x)), g(x))*Derivative(g(x), (x, 2)) + Derivative(g(x), x)*Subs(Derivative(f(_xi_1, g(x)), _xi_1, g(x)), _xi_1, x) + Subs(Derivative(f(_xi_1, g(x)), (_xi_1, 2)), _xi_1, x)) # issue 6681 assert diff(f(x, t, g(x, t)), x).doit() == ( Derivative(f(x, t, g(x, t)), g(x, t))*Derivative(g(x, t), x) + Subs(Derivative(f(_xi_1, t, g(x, t)), _xi_1), _xi_1, x)) # make sure the order doesn't matter when using diff assert eq.diff(x, g(x)) == eq.diff(g(x), x) def test_negative_counts(): # issue 13873 raises(ValueError, lambda: sin(x).diff(x, -1)) def test_Derivative__new__(): raises(TypeError, lambda: f(x).diff((x, 2), 0)) assert f(x, y).diff([(x, y), 0]) == f(x, y) assert f(x, y).diff([(x, y), 1]) == NDimArray([ Derivative(f(x, y), x), Derivative(f(x, y), y)]) assert f(x,y).diff(y, (x, z), y, x) == Derivative( f(x, y), (x, z + 1), (y, 2)) assert Matrix([x]).diff(x, 2) == Matrix([0]) # is_zero exit def test_issue_14719_10150(): class V(Expr): _diff_wrt = True is_scalar = False assert V().diff(V()) == Derivative(V(), V()) assert (2*V()).diff(V()) == 2*Derivative(V(), V()) class X(Expr): _diff_wrt = True assert X().diff(X()) == 1 assert (2*X()).diff(X()) == 2 def test_noncommutative_issue_15131(): x = Symbol('x', commutative=False) t = Symbol('t', commutative=False) fx = Function('Fx', commutative=False)(x) ft = Function('Ft', commutative=False)(t) A = Symbol('A', commutative=False) eq = fx * A * ft eqdt = eq.diff(t) assert eqdt.args[-1] == ft.diff(t) def test_Subs_Derivative(): a = Derivative(f(g(x), h(x)), g(x), h(x),x) b = Derivative(Derivative(f(g(x), h(x)), g(x), h(x)),x) c = f(g(x), h(x)).diff(g(x), h(x), x) d = f(g(x), h(x)).diff(g(x), h(x)).diff(x) e = Derivative(f(g(x), h(x)), x) eqs = (a, b, c, d, e) subs = lambda arg: arg.subs(f, Lambda((x, y), exp(x + y)) ).subs(g(x), 1/x).subs(h(x), x**3) ans = 3*x**2*exp(1/x)*exp(x**3) - exp(1/x)*exp(x**3)/x**2 assert all(subs(i).doit().expand() == ans for i in eqs) assert all(subs(i.doit()).doit().expand() == ans for i in eqs) def test_issue_15360(): f = Function('f') assert f.name == 'f' def test_issue_15947(): assert f._diff_wrt is False raises(TypeError, lambda: f(f)) raises(TypeError, lambda: f(x).diff(f)) def test_Derivative_free_symbols(): f = Function('f') n = Symbol('n', integer=True, positive=True) assert diff(f(x), (x, n)).free_symbols == {n, x} def test_issue_10503(): f = exp(x**3)*cos(x**6) assert f.series(x, 0, 14) == 1 + x**3 + x**6/2 + x**9/6 - 11*x**12/24 + O(x**14)
a55dd24e97975e8673fbc863b6085a0243d7bd48ca3a2e91affaa272e16b99a0
from sympy import Integer, S, Symbol, symbols, Expr from sympy.core.operations import AssocOp, LatticeOp from sympy.testing.pytest import raises from sympy.core.sympify import SympifyError from sympy.core.add import Add, add from sympy.core.mul import Mul, mul # create the simplest possible Lattice class class join(LatticeOp): zero = Integer(0) identity = Integer(1) def test_lattice_simple(): assert join(join(2, 3), 4) == join(2, join(3, 4)) assert join(2, 3) == join(3, 2) assert join(0, 2) == 0 assert join(1, 2) == 2 assert join(2, 2) == 2 assert join(join(2, 3), 4) == join(2, 3, 4) assert join() == 1 assert join(4) == 4 assert join(1, 4, 2, 3, 1, 3, 2) == join(2, 3, 4) def test_lattice_shortcircuit(): raises(SympifyError, lambda: join(object)) assert join(0, object) == 0 def test_lattice_print(): assert str(join(5, 4, 3, 2)) == 'join(2, 3, 4, 5)' def test_lattice_make_args(): assert join.make_args(join(2, 3, 4)) == {S(2), S(3), S(4)} assert join.make_args(0) == {0} assert list(join.make_args(0))[0] is S.Zero assert Add.make_args(0)[0] is S.Zero def test_issue_14025(): a, b, c, d = symbols('a,b,c,d', commutative=False) assert Mul(a, b, c).has(c*b) == False assert Mul(a, b, c).has(b*c) == True assert Mul(a, b, c, d).has(b*c*d) == True def test_AssocOp_flatten(): a, b, c, d = symbols('a,b,c,d') class MyAssoc(AssocOp): identity = S.One assert MyAssoc(a, MyAssoc(b, c)).args == \ MyAssoc(MyAssoc(a, b), c).args == \ MyAssoc(MyAssoc(a, b, c)).args == \ MyAssoc(a, b, c).args == \ (a, b, c) u = MyAssoc(b, c) v = MyAssoc(u, d, evaluate=False) assert v.args == (u, d) # like Add, any unevaluated outer call will flatten inner args assert MyAssoc(a, v).args == (a, b, c, d) def test_add_dispatcher(): class NewBase(Expr): @property def _add_handler(self): return NewAdd class NewAdd(NewBase, Add): pass add.register_handlerclass((Add, NewAdd), NewAdd) a, b = Symbol('a'), NewBase() # Add called as fallback assert add(1, 2) == Add(1, 2) assert add(a, a) == Add(a, a) # selection by registered priority assert add(a,b,a) == NewAdd(2*a, b) def test_mul_dispatcher(): class NewBase(Expr): @property def _mul_handler(self): return NewMul class NewMul(NewBase, Mul): pass mul.register_handlerclass((Mul, NewMul), NewMul) a, b = Symbol('a'), NewBase() # Mul called as fallback assert mul(1, 2) == Mul(1, 2) assert mul(a, a) == Mul(a, a) # selection by registered priority assert mul(a,b,a) == NewMul(a**2, b)
83d7465bea93eb8ef22f8ba4d43fefdccd92f2b815d568b8241505c934b052de
from sympy.core.decorators import call_highest_priority from sympy.core.expr import Expr from sympy.core.mod import Mod from sympy.core.numbers import Integer from sympy.core.symbol import Symbol from sympy.functions.elementary.integers import floor class Higher(Integer): ''' Integer of value 1 and _op_priority 20 Operations handled by this class return 1 and reverse operations return 2 ''' _op_priority = 20.0 result = 1 def __new__(cls): obj = Expr.__new__(cls) obj.p = 1 return obj @call_highest_priority('__rmul__') def __mul__(self, other): return self.result @call_highest_priority('__mul__') def __rmul__(self, other): return 2*self.result @call_highest_priority('__radd__') def __add__(self, other): return self.result @call_highest_priority('__add__') def __radd__(self, other): return 2*self.result @call_highest_priority('__rsub__') def __sub__(self, other): return self.result @call_highest_priority('__sub__') def __rsub__(self, other): return 2*self.result @call_highest_priority('__rpow__') def __pow__(self, other): return self.result @call_highest_priority('__pow__') def __rpow__(self, other): return 2*self.result @call_highest_priority('__rtruediv__') def __truediv__(self, other): return self.result @call_highest_priority('__truediv__') def __rtruediv__(self, other): return 2*self.result @call_highest_priority('__rmod__') def __mod__(self, other): return self.result @call_highest_priority('__mod__') def __rmod__(self, other): return 2*self.result @call_highest_priority('__rfloordiv__') def __floordiv__(self, other): return self.result @call_highest_priority('__floordiv__') def __rfloordiv__(self, other): return 2*self.result class Lower(Higher): ''' Integer of value -1 and _op_priority 5 Operations handled by this class return -1 and reverse operations return -2 ''' _op_priority = 5.0 result = -1 def __new__(cls): obj = Expr.__new__(cls) obj.p = -1 return obj x = Symbol('x') h = Higher() l = Lower() def test_mul(): assert h*l == h*x == 1 assert l*h == x*h == 2 assert x*l == l*x == -x def test_add(): assert h + l == h + x == 1 assert l + h == x + h == 2 assert x + l == l + x == x - 1 def test_sub(): assert h - l == h - x == 1 assert l - h == x - h == 2 assert x - l == -(l - x) == x + 1 def test_pow(): assert h**l == h**x == 1 assert l**h == x**h == 2 assert (x**l).args == (1/x).args and (x**l).is_Pow assert (l**x).args == ((-1)**x).args and (l**x).is_Pow def test_div(): assert h/l == h/x == 1 assert l/h == x/h == 2 assert x/l == 1/(l/x) == -x def test_mod(): assert h%l == h%x == 1 assert l%h == x%h == 2 assert x%l == Mod(x, -1) assert l%x == Mod(-1, x) def test_floordiv(): assert h//l == h//x == 1 assert l//h == x//h == 2 assert x//l == floor(-x) assert l//x == floor(-1/x)
17f56223e306a70c9df740eaf3acebe64dfc3a0784d4b3739402f3412c67c532
from sympy.core import ( Basic, Rational, Symbol, S, Float, Integer, Mul, Number, Pow, Expr, I, nan, pi, symbols, oo, zoo, N) 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 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 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)) 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) 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**2*exp(-1/x) + x 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, Rational I = S.ImaginaryUnit 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_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)
f24aa9527bbcaf567ee0b74205fc3f5c07394e2630523f1b36532bca4e8f521e
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 exec_, 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)' assert str(S('pi(C, Q)', locals=_clash)) == 'pi(C, Q)' locals = {} exec_("from sympy.abc import Q, C", locals) assert str(S('C&Q', locals)) == 'C & Q' 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.float) z2 = numpy.zeros((2, 2), dtype=numpy.float) z3 = numpy.zeros((), dtype=numpy.float) y1 = numpy.ones((1, 1), dtype=numpy.float) y2 = numpy.ones((2, 2), dtype=numpy.float) y3 = numpy.ones((), dtype=numpy.float) 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.int(0), numpy.float(0), numpy.complex(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.int(1), numpy.float(1), numpy.complex(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))
b3c400446f967ea05c49110b2b10cf3f915ac6556ce999e000fd5fbd430270ce
from sympy import (Basic, Symbol, sin, cos, atan, exp, sqrt, Rational, Float, re, pi, sympify, Add, Mul, Pow, Mod, I, log, S, Max, symbols, oo, zoo, Integer, sign, im, nan, Dummy, factorial, comp, floor, Poly, FiniteSet ) from sympy.core.parameters import distribute from sympy.core.expr import unchanged from sympy.utilities.iterables import cartes from sympy.testing.pytest import XFAIL, raises, warns_deprecated_sympy from sympy.testing.randtest import verify_numerically a, c, x, y, z = symbols('a,c,x,y,z') b = Symbol("b", positive=True) def same_and_same_prec(a, b): # stricter matching for Floats return a == b and a._prec == b._prec def test_bug1(): assert re(x) != x x.series(x, 0, 1) assert re(x) != x def test_Symbol(): e = a*b assert e == a*b assert a*b*b == a*b**2 assert a*b*b + c == c + a*b**2 assert a*b*b - c == -c + a*b**2 x = Symbol('x', complex=True, real=False) assert x.is_imaginary is None # could be I or 1 + I x = Symbol('x', complex=True, imaginary=False) assert x.is_real is None # could be 1 or 1 + I x = Symbol('x', real=True) assert x.is_complex x = Symbol('x', imaginary=True) assert x.is_complex x = Symbol('x', real=False, imaginary=False) assert x.is_complex is None # might be a non-number def test_arit0(): p = Rational(5) e = a*b assert e == a*b e = a*b + b*a assert e == 2*a*b e = a*b + b*a + a*b + p*b*a assert e == 8*a*b e = a*b + b*a + a*b + p*b*a + a assert e == a + 8*a*b e = a + a assert e == 2*a e = a + b + a assert e == b + 2*a e = a + b*b + a + b*b assert e == 2*a + 2*b**2 e = a + Rational(2) + b*b + a + b*b + p assert e == 7 + 2*a + 2*b**2 e = (a + b*b + a + b*b)*p assert e == 5*(2*a + 2*b**2) e = (a*b*c + c*b*a + b*a*c)*p assert e == 15*a*b*c e = (a*b*c + c*b*a + b*a*c)*p - Rational(15)*a*b*c assert e == Rational(0) e = Rational(50)*(a - a) assert e == Rational(0) e = b*a - b - a*b + b assert e == Rational(0) e = a*b + c**p assert e == a*b + c**5 e = a/b assert e == a*b**(-1) e = a*2*2 assert e == 4*a e = 2 + a*2/2 assert e == 2 + a e = 2 - a - 2 assert e == -a e = 2*a*2 assert e == 4*a e = 2/a/2 assert e == a**(-1) e = 2**a**2 assert e == 2**(a**2) e = -(1 + a) assert e == -1 - a e = S.Half*(1 + a) assert e == S.Half + a/2 def test_div(): e = a/b assert e == a*b**(-1) e = a/b + c/2 assert e == a*b**(-1) + Rational(1)/2*c e = (1 - b)/(b - 1) assert e == (1 + -b)*((-1) + b)**(-1) def test_pow(): n1 = Rational(1) n2 = Rational(2) n5 = Rational(5) e = a*a assert e == a**2 e = a*a*a assert e == a**3 e = a*a*a*a**Rational(6) assert e == a**9 e = a*a*a*a**Rational(6) - a**Rational(9) assert e == Rational(0) e = a**(b - b) assert e == Rational(1) e = (a + Rational(1) - a)**b assert e == Rational(1) e = (a + b + c)**n2 assert e == (a + b + c)**2 assert e.expand() == 2*b*c + 2*a*c + 2*a*b + a**2 + c**2 + b**2 e = (a + b)**n2 assert e == (a + b)**2 assert e.expand() == 2*a*b + a**2 + b**2 e = (a + b)**(n1/n2) assert e == sqrt(a + b) assert e.expand() == sqrt(a + b) n = n5**(n1/n2) assert n == sqrt(5) e = n*a*b - n*b*a assert e == Rational(0) e = n*a*b + n*b*a assert e == 2*a*b*sqrt(5) assert e.diff(a) == 2*b*sqrt(5) assert e.diff(a) == 2*b*sqrt(5) e = a/b**2 assert e == a*b**(-2) assert sqrt(2*(1 + sqrt(2))) == (2*(1 + 2**S.Half))**S.Half x = Symbol('x') y = Symbol('y') assert ((x*y)**3).expand() == y**3 * x**3 assert ((x*y)**-3).expand() == y**-3 * x**-3 assert (x**5*(3*x)**(3)).expand() == 27 * x**8 assert (x**5*(-3*x)**(3)).expand() == -27 * x**8 assert (x**5*(3*x)**(-3)).expand() == x**2 * Rational(1, 27) assert (x**5*(-3*x)**(-3)).expand() == x**2 * Rational(-1, 27) # expand_power_exp assert (x**(y**(x + exp(x + y)) + z)).expand(deep=False) == \ x**z*x**(y**(x + exp(x + y))) assert (x**(y**(x + exp(x + y)) + z)).expand() == \ x**z*x**(y**x*y**(exp(x)*exp(y))) n = Symbol('n', even=False) k = Symbol('k', even=True) o = Symbol('o', odd=True) assert unchanged(Pow, -1, x) assert unchanged(Pow, -1, n) assert (-2)**k == 2**k assert (-1)**k == 1 assert (-1)**o == -1 def test_pow2(): # x**(2*y) is always (x**y)**2 but is only (x**2)**y if # x.is_positive or y.is_integer # let x = 1 to see why the following are not true. assert (-x)**Rational(2, 3) != x**Rational(2, 3) assert (-x)**Rational(5, 7) != -x**Rational(5, 7) assert ((-x)**2)**Rational(1, 3) != ((-x)**Rational(1, 3))**2 assert sqrt(x**2) != x def test_pow3(): assert sqrt(2)**3 == 2 * sqrt(2) assert sqrt(2)**3 == sqrt(8) def test_mod_pow(): for s, t, u, v in [(4, 13, 497, 445), (4, -3, 497, 365), (3.2, 2.1, 1.9, 0.1031015682350942), (S(3)/2, 5, S(5)/6, S(3)/32)]: assert pow(S(s), t, u) == v assert pow(S(s), S(t), u) == v assert pow(S(s), t, S(u)) == v assert pow(S(s), S(t), S(u)) == v assert pow(S(2), S(10000000000), S(3)) == 1 assert pow(x, y, z) == x**y%z raises(TypeError, lambda: pow(S(4), "13", 497)) raises(TypeError, lambda: pow(S(4), 13, "497")) def test_pow_E(): assert 2**(y/log(2)) == S.Exp1**y assert 2**(y/log(2)/3) == S.Exp1**(y/3) assert 3**(1/log(-3)) != S.Exp1 assert (3 + 2*I)**(1/(log(-3 - 2*I) + I*pi)) == S.Exp1 assert (4 + 2*I)**(1/(log(-4 - 2*I) + I*pi)) == S.Exp1 assert (3 + 2*I)**(1/(log(-3 - 2*I, 3)/2 + I*pi/log(3)/2)) == 9 assert (3 + 2*I)**(1/(log(3 + 2*I, 3)/2)) == 9 # every time tests are run they will affirm with a different random # value that this identity holds while 1: b = x._random() r, i = b.as_real_imag() if i: break assert verify_numerically(b**(1/(log(-b) + sign(i)*I*pi).n()), S.Exp1) def test_pow_issue_3516(): assert 4**Rational(1, 4) == sqrt(2) def test_pow_im(): for m in (-2, -1, 2): for d in (3, 4, 5): b = m*I for i in range(1, 4*d + 1): e = Rational(i, d) assert (b**e - b.n()**e.n()).n(2, chop=1e-10) == 0 e = Rational(7, 3) assert (2*x*I)**e == 4*2**Rational(1, 3)*(I*x)**e # same as Wolfram Alpha im = symbols('im', imaginary=True) assert (2*im*I)**e == 4*2**Rational(1, 3)*(I*im)**e args = [I, I, I, I, 2] e = Rational(1, 3) ans = 2**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args = [I, I, I, 2] e = Rational(1, 3) ans = 2**e*(-I)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args.append(-3) ans = (6*I)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args.append(-1) ans = (-6*I)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args = [I, I, 2] e = Rational(1, 3) ans = (-2)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args.append(-3) ans = (6)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args.append(-1) ans = (-6)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans assert Mul(Pow(-1, Rational(3, 2), evaluate=False), I, I) == I assert Mul(I*Pow(I, S.Half, evaluate=False)) == sqrt(I)*I def test_real_mul(): assert Float(0) * pi * x == 0 assert set((Float(1) * pi * x).args) == {Float(1), pi, x} def test_ncmul(): A = Symbol("A", commutative=False) B = Symbol("B", commutative=False) C = Symbol("C", commutative=False) assert A*B != B*A assert A*B*C != C*B*A assert A*b*B*3*C == 3*b*A*B*C assert A*b*B*3*C != 3*b*B*A*C assert A*b*B*3*C == 3*A*B*C*b assert A + B == B + A assert (A + B)*C != C*(A + B) assert C*(A + B)*C != C*C*(A + B) assert A*A == A**2 assert (A + B)*(A + B) == (A + B)**2 assert A**-1 * A == 1 assert A/A == 1 assert A/(A**2) == 1/A assert A/(1 + A) == A/(1 + A) assert set((A + B + 2*(A + B)).args) == \ {A, B, 2*(A + B)} def test_mul_add_identity(): m = Mul(1, 2) assert isinstance(m, Rational) and m.p == 2 and m.q == 1 m = Mul(1, 2, evaluate=False) assert isinstance(m, Mul) and m.args == (1, 2) m = Mul(0, 1) assert m is S.Zero m = Mul(0, 1, evaluate=False) assert isinstance(m, Mul) and m.args == (0, 1) m = Add(0, 1) assert m is S.One m = Add(0, 1, evaluate=False) assert isinstance(m, Add) and m.args == (0, 1) def test_ncpow(): x = Symbol('x', commutative=False) y = Symbol('y', commutative=False) z = Symbol('z', commutative=False) a = Symbol('a') b = Symbol('b') c = Symbol('c') assert (x**2)*(y**2) != (y**2)*(x**2) assert (x**-2)*y != y*(x**2) assert 2**x*2**y != 2**(x + y) assert 2**x*2**y*2**z != 2**(x + y + z) assert 2**x*2**(2*x) == 2**(3*x) assert 2**x*2**(2*x)*2**x == 2**(4*x) assert exp(x)*exp(y) != exp(y)*exp(x) assert exp(x)*exp(y)*exp(z) != exp(y)*exp(x)*exp(z) assert exp(x)*exp(y)*exp(z) != exp(x + y + z) assert x**a*x**b != x**(a + b) assert x**a*x**b*x**c != x**(a + b + c) assert x**3*x**4 == x**7 assert x**3*x**4*x**2 == x**9 assert x**a*x**(4*a) == x**(5*a) assert x**a*x**(4*a)*x**a == x**(6*a) def test_powerbug(): x = Symbol("x") assert x**1 != (-x)**1 assert x**2 == (-x)**2 assert x**3 != (-x)**3 assert x**4 == (-x)**4 assert x**5 != (-x)**5 assert x**6 == (-x)**6 assert x**128 == (-x)**128 assert x**129 != (-x)**129 assert (2*x)**2 == (-2*x)**2 def test_Mul_doesnt_expand_exp(): x = Symbol('x') y = Symbol('y') assert unchanged(Mul, exp(x), exp(y)) assert unchanged(Mul, 2**x, 2**y) assert x**2*x**3 == x**5 assert 2**x*3**x == 6**x assert x**(y)*x**(2*y) == x**(3*y) assert sqrt(2)*sqrt(2) == 2 assert 2**x*2**(2*x) == 2**(3*x) assert sqrt(2)*2**Rational(1, 4)*5**Rational(3, 4) == 10**Rational(3, 4) assert (x**(-log(5)/log(3))*x)/(x*x**( - log(5)/log(3))) == sympify(1) def test_Mul_is_integer(): k = Symbol('k', integer=True) n = Symbol('n', integer=True) nr = Symbol('nr', rational=False) nz = Symbol('nz', integer=True, zero=False) nze = Symbol('nze', even=True, zero=False) e = Symbol('e', even=True) o = Symbol('o', odd=True) i2 = Symbol('2', prime=True, even=True) assert (k/3).is_integer is None assert (nz/3).is_integer is None assert (nr/3).is_integer is False assert (x*k*n).is_integer is None assert (e/o).is_integer is None assert (o/e).is_integer is False assert (o/i2).is_integer is False assert Mul(o, 1/o, evaluate=False).is_integer is True assert Mul(k, 1/k, evaluate=False).is_integer is None assert Mul(nze, 1/nze, evaluate=False).is_integer is True assert Mul(2., S.Half, evaluate=False).is_integer is False s = 2**2**2**Pow(2, 1000, evaluate=False) m = Mul(s, s, evaluate=False) assert m.is_integer def test_Add_Mul_is_integer(): x = Symbol('x') k = Symbol('k', integer=True) n = Symbol('n', integer=True) nk = Symbol('nk', integer=False) nr = Symbol('nr', rational=False) nz = Symbol('nz', integer=True, zero=False) assert (-nk).is_integer is None assert (-nr).is_integer is False assert (2*k).is_integer is True assert (-k).is_integer is True assert (k + nk).is_integer is False assert (k + n).is_integer is True assert (k + x).is_integer is None assert (k + n*x).is_integer is None assert (k + n/3).is_integer is None assert (k + nz/3).is_integer is None assert (k + nr/3).is_integer is False assert ((1 + sqrt(3))*(-sqrt(3) + 1)).is_integer is not False assert (1 + (1 + sqrt(3))*(-sqrt(3) + 1)).is_integer is not False def test_Add_Mul_is_finite(): x = Symbol('x', extended_real=True, finite=False) assert sin(x).is_finite is True assert (x*sin(x)).is_finite is None assert (x*atan(x)).is_finite is False assert (1024*sin(x)).is_finite is True assert (sin(x)*exp(x)).is_finite is None assert (sin(x)*cos(x)).is_finite is True assert (x*sin(x)*exp(x)).is_finite is None assert (sin(x) - 67).is_finite is True assert (sin(x) + exp(x)).is_finite is not True assert (1 + x).is_finite is False assert (1 + x**2 + (1 + x)*(1 - x)).is_finite is None assert (sqrt(2)*(1 + x)).is_finite is False assert (sqrt(2)*(1 + x)*(1 - x)).is_finite is False def test_Mul_is_even_odd(): x = Symbol('x', integer=True) y = Symbol('y', integer=True) k = Symbol('k', odd=True) n = Symbol('n', odd=True) m = Symbol('m', even=True) assert (2*x).is_even is True assert (2*x).is_odd is False assert (3*x).is_even is None assert (3*x).is_odd is None assert (k/3).is_integer is None assert (k/3).is_even is None assert (k/3).is_odd is None assert (2*n).is_even is True assert (2*n).is_odd is False assert (2*m).is_even is True assert (2*m).is_odd is False assert (-n).is_even is False assert (-n).is_odd is True assert (k*n).is_even is False assert (k*n).is_odd is True assert (k*m).is_even is True assert (k*m).is_odd is False assert (k*n*m).is_even is True assert (k*n*m).is_odd is False assert (k*m*x).is_even is True assert (k*m*x).is_odd is False # issue 6791: assert (x/2).is_integer is None assert (k/2).is_integer is False assert (m/2).is_integer is True assert (x*y).is_even is None assert (x*x).is_even is None assert (x*(x + k)).is_even is True assert (x*(x + m)).is_even is None assert (x*y).is_odd is None assert (x*x).is_odd is None assert (x*(x + k)).is_odd is False assert (x*(x + m)).is_odd is None @XFAIL def test_evenness_in_ternary_integer_product_with_odd(): # Tests that oddness inference is independent of term ordering. # Term ordering at the point of testing depends on SymPy's symbol order, so # we try to force a different order by modifying symbol names. x = Symbol('x', integer=True) y = Symbol('y', integer=True) k = Symbol('k', odd=True) assert (x*y*(y + k)).is_even is True assert (y*x*(x + k)).is_even is True def test_evenness_in_ternary_integer_product_with_even(): x = Symbol('x', integer=True) y = Symbol('y', integer=True) m = Symbol('m', even=True) assert (x*y*(y + m)).is_even is None @XFAIL def test_oddness_in_ternary_integer_product_with_odd(): # Tests that oddness inference is independent of term ordering. # Term ordering at the point of testing depends on SymPy's symbol order, so # we try to force a different order by modifying symbol names. x = Symbol('x', integer=True) y = Symbol('y', integer=True) k = Symbol('k', odd=True) assert (x*y*(y + k)).is_odd is False assert (y*x*(x + k)).is_odd is False def test_oddness_in_ternary_integer_product_with_even(): x = Symbol('x', integer=True) y = Symbol('y', integer=True) m = Symbol('m', even=True) assert (x*y*(y + m)).is_odd is None def test_Mul_is_rational(): x = Symbol('x') n = Symbol('n', integer=True) m = Symbol('m', integer=True, nonzero=True) assert (n/m).is_rational is True assert (x/pi).is_rational is None assert (x/n).is_rational is None assert (m/pi).is_rational is False r = Symbol('r', rational=True) assert (pi*r).is_rational is None # issue 8008 z = Symbol('z', zero=True) i = Symbol('i', imaginary=True) assert (z*i).is_rational is True bi = Symbol('i', imaginary=True, finite=True) assert (z*bi).is_zero is True def test_Add_is_rational(): x = Symbol('x') n = Symbol('n', rational=True) m = Symbol('m', rational=True) assert (n + m).is_rational is True assert (x + pi).is_rational is None assert (x + n).is_rational is None assert (n + pi).is_rational is False def test_Add_is_even_odd(): x = Symbol('x', integer=True) k = Symbol('k', odd=True) n = Symbol('n', odd=True) m = Symbol('m', even=True) assert (k + 7).is_even is True assert (k + 7).is_odd is False assert (-k + 7).is_even is True assert (-k + 7).is_odd is False assert (k - 12).is_even is False assert (k - 12).is_odd is True assert (-k - 12).is_even is False assert (-k - 12).is_odd is True assert (k + n).is_even is True assert (k + n).is_odd is False assert (k + m).is_even is False assert (k + m).is_odd is True assert (k + n + m).is_even is True assert (k + n + m).is_odd is False assert (k + n + x + m).is_even is None assert (k + n + x + m).is_odd is None def test_Mul_is_negative_positive(): x = Symbol('x', real=True) y = Symbol('y', extended_real=False, complex=True) z = Symbol('z', zero=True) e = 2*z assert e.is_Mul and e.is_positive is False and e.is_negative is False neg = Symbol('neg', negative=True) pos = Symbol('pos', positive=True) nneg = Symbol('nneg', nonnegative=True) npos = Symbol('npos', nonpositive=True) assert neg.is_negative is True assert (-neg).is_negative is False assert (2*neg).is_negative is True assert (2*pos)._eval_is_extended_negative() is False assert (2*pos).is_negative is False assert pos.is_negative is False assert (-pos).is_negative is True assert (2*pos).is_negative is False assert (pos*neg).is_negative is True assert (2*pos*neg).is_negative is True assert (-pos*neg).is_negative is False assert (pos*neg*y).is_negative is False # y.is_real=F; !real -> !neg assert nneg.is_negative is False assert (-nneg).is_negative is None assert (2*nneg).is_negative is False assert npos.is_negative is None assert (-npos).is_negative is False assert (2*npos).is_negative is None assert (nneg*npos).is_negative is None assert (neg*nneg).is_negative is None assert (neg*npos).is_negative is False assert (pos*nneg).is_negative is False assert (pos*npos).is_negative is None assert (npos*neg*nneg).is_negative is False assert (npos*pos*nneg).is_negative is None assert (-npos*neg*nneg).is_negative is None assert (-npos*pos*nneg).is_negative is False assert (17*npos*neg*nneg).is_negative is False assert (17*npos*pos*nneg).is_negative is None assert (neg*npos*pos*nneg).is_negative is False assert (x*neg).is_negative is None assert (nneg*npos*pos*x*neg).is_negative is None assert neg.is_positive is False assert (-neg).is_positive is True assert (2*neg).is_positive is False assert pos.is_positive is True assert (-pos).is_positive is False assert (2*pos).is_positive is True assert (pos*neg).is_positive is False assert (2*pos*neg).is_positive is False assert (-pos*neg).is_positive is True assert (-pos*neg*y).is_positive is False # y.is_real=F; !real -> !neg assert nneg.is_positive is None assert (-nneg).is_positive is False assert (2*nneg).is_positive is None assert npos.is_positive is False assert (-npos).is_positive is None assert (2*npos).is_positive is False assert (nneg*npos).is_positive is False assert (neg*nneg).is_positive is False assert (neg*npos).is_positive is None assert (pos*nneg).is_positive is None assert (pos*npos).is_positive is False assert (npos*neg*nneg).is_positive is None assert (npos*pos*nneg).is_positive is False assert (-npos*neg*nneg).is_positive is False assert (-npos*pos*nneg).is_positive is None assert (17*npos*neg*nneg).is_positive is None assert (17*npos*pos*nneg).is_positive is False assert (neg*npos*pos*nneg).is_positive is None assert (x*neg).is_positive is None assert (nneg*npos*pos*x*neg).is_positive is None def test_Mul_is_negative_positive_2(): a = Symbol('a', nonnegative=True) b = Symbol('b', nonnegative=True) c = Symbol('c', nonpositive=True) d = Symbol('d', nonpositive=True) assert (a*b).is_nonnegative is True assert (a*b).is_negative is False assert (a*b).is_zero is None assert (a*b).is_positive is None assert (c*d).is_nonnegative is True assert (c*d).is_negative is False assert (c*d).is_zero is None assert (c*d).is_positive is None assert (a*c).is_nonpositive is True assert (a*c).is_positive is False assert (a*c).is_zero is None assert (a*c).is_negative is None def test_Mul_is_nonpositive_nonnegative(): x = Symbol('x', real=True) k = Symbol('k', negative=True) n = Symbol('n', positive=True) u = Symbol('u', nonnegative=True) v = Symbol('v', nonpositive=True) assert k.is_nonpositive is True assert (-k).is_nonpositive is False assert (2*k).is_nonpositive is True assert n.is_nonpositive is False assert (-n).is_nonpositive is True assert (2*n).is_nonpositive is False assert (n*k).is_nonpositive is True assert (2*n*k).is_nonpositive is True assert (-n*k).is_nonpositive is False assert u.is_nonpositive is None assert (-u).is_nonpositive is True assert (2*u).is_nonpositive is None assert v.is_nonpositive is True assert (-v).is_nonpositive is None assert (2*v).is_nonpositive is True assert (u*v).is_nonpositive is True assert (k*u).is_nonpositive is True assert (k*v).is_nonpositive is None assert (n*u).is_nonpositive is None assert (n*v).is_nonpositive is True assert (v*k*u).is_nonpositive is None assert (v*n*u).is_nonpositive is True assert (-v*k*u).is_nonpositive is True assert (-v*n*u).is_nonpositive is None assert (17*v*k*u).is_nonpositive is None assert (17*v*n*u).is_nonpositive is True assert (k*v*n*u).is_nonpositive is None assert (x*k).is_nonpositive is None assert (u*v*n*x*k).is_nonpositive is None assert k.is_nonnegative is False assert (-k).is_nonnegative is True assert (2*k).is_nonnegative is False assert n.is_nonnegative is True assert (-n).is_nonnegative is False assert (2*n).is_nonnegative is True assert (n*k).is_nonnegative is False assert (2*n*k).is_nonnegative is False assert (-n*k).is_nonnegative is True assert u.is_nonnegative is True assert (-u).is_nonnegative is None assert (2*u).is_nonnegative is True assert v.is_nonnegative is None assert (-v).is_nonnegative is True assert (2*v).is_nonnegative is None assert (u*v).is_nonnegative is None assert (k*u).is_nonnegative is None assert (k*v).is_nonnegative is True assert (n*u).is_nonnegative is True assert (n*v).is_nonnegative is None assert (v*k*u).is_nonnegative is True assert (v*n*u).is_nonnegative is None assert (-v*k*u).is_nonnegative is None assert (-v*n*u).is_nonnegative is True assert (17*v*k*u).is_nonnegative is True assert (17*v*n*u).is_nonnegative is None assert (k*v*n*u).is_nonnegative is True assert (x*k).is_nonnegative is None assert (u*v*n*x*k).is_nonnegative is None def test_Add_is_negative_positive(): x = Symbol('x', real=True) k = Symbol('k', negative=True) n = Symbol('n', positive=True) u = Symbol('u', nonnegative=True) v = Symbol('v', nonpositive=True) assert (k - 2).is_negative is True assert (k + 17).is_negative is None assert (-k - 5).is_negative is None assert (-k + 123).is_negative is False assert (k - n).is_negative is True assert (k + n).is_negative is None assert (-k - n).is_negative is None assert (-k + n).is_negative is False assert (k - n - 2).is_negative is True assert (k + n + 17).is_negative is None assert (-k - n - 5).is_negative is None assert (-k + n + 123).is_negative is False assert (-2*k + 123*n + 17).is_negative is False assert (k + u).is_negative is None assert (k + v).is_negative is True assert (n + u).is_negative is False assert (n + v).is_negative is None assert (u - v).is_negative is False assert (u + v).is_negative is None assert (-u - v).is_negative is None assert (-u + v).is_negative is None assert (u - v + n + 2).is_negative is False assert (u + v + n + 2).is_negative is None assert (-u - v + n + 2).is_negative is None assert (-u + v + n + 2).is_negative is None assert (k + x).is_negative is None assert (k + x - n).is_negative is None assert (k - 2).is_positive is False assert (k + 17).is_positive is None assert (-k - 5).is_positive is None assert (-k + 123).is_positive is True assert (k - n).is_positive is False assert (k + n).is_positive is None assert (-k - n).is_positive is None assert (-k + n).is_positive is True assert (k - n - 2).is_positive is False assert (k + n + 17).is_positive is None assert (-k - n - 5).is_positive is None assert (-k + n + 123).is_positive is True assert (-2*k + 123*n + 17).is_positive is True assert (k + u).is_positive is None assert (k + v).is_positive is False assert (n + u).is_positive is True assert (n + v).is_positive is None assert (u - v).is_positive is None assert (u + v).is_positive is None assert (-u - v).is_positive is None assert (-u + v).is_positive is False assert (u - v - n - 2).is_positive is None assert (u + v - n - 2).is_positive is None assert (-u - v - n - 2).is_positive is None assert (-u + v - n - 2).is_positive is False assert (n + x).is_positive is None assert (n + x - k).is_positive is None z = (-3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2) assert z.is_zero z = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3)) assert z.is_zero def test_Add_is_nonpositive_nonnegative(): x = Symbol('x', real=True) k = Symbol('k', negative=True) n = Symbol('n', positive=True) u = Symbol('u', nonnegative=True) v = Symbol('v', nonpositive=True) assert (u - 2).is_nonpositive is None assert (u + 17).is_nonpositive is False assert (-u - 5).is_nonpositive is True assert (-u + 123).is_nonpositive is None assert (u - v).is_nonpositive is None assert (u + v).is_nonpositive is None assert (-u - v).is_nonpositive is None assert (-u + v).is_nonpositive is True assert (u - v - 2).is_nonpositive is None assert (u + v + 17).is_nonpositive is None assert (-u - v - 5).is_nonpositive is None assert (-u + v - 123).is_nonpositive is True assert (-2*u + 123*v - 17).is_nonpositive is True assert (k + u).is_nonpositive is None assert (k + v).is_nonpositive is True assert (n + u).is_nonpositive is False assert (n + v).is_nonpositive is None assert (k - n).is_nonpositive is True assert (k + n).is_nonpositive is None assert (-k - n).is_nonpositive is None assert (-k + n).is_nonpositive is False assert (k - n + u + 2).is_nonpositive is None assert (k + n + u + 2).is_nonpositive is None assert (-k - n + u + 2).is_nonpositive is None assert (-k + n + u + 2).is_nonpositive is False assert (u + x).is_nonpositive is None assert (v - x - n).is_nonpositive is None assert (u - 2).is_nonnegative is None assert (u + 17).is_nonnegative is True assert (-u - 5).is_nonnegative is False assert (-u + 123).is_nonnegative is None assert (u - v).is_nonnegative is True assert (u + v).is_nonnegative is None assert (-u - v).is_nonnegative is None assert (-u + v).is_nonnegative is None assert (u - v + 2).is_nonnegative is True assert (u + v + 17).is_nonnegative is None assert (-u - v - 5).is_nonnegative is None assert (-u + v - 123).is_nonnegative is False assert (2*u - 123*v + 17).is_nonnegative is True assert (k + u).is_nonnegative is None assert (k + v).is_nonnegative is False assert (n + u).is_nonnegative is True assert (n + v).is_nonnegative is None assert (k - n).is_nonnegative is False assert (k + n).is_nonnegative is None assert (-k - n).is_nonnegative is None assert (-k + n).is_nonnegative is True assert (k - n - u - 2).is_nonnegative is False assert (k + n - u - 2).is_nonnegative is None assert (-k - n - u - 2).is_nonnegative is None assert (-k + n - u - 2).is_nonnegative is None assert (u - x).is_nonnegative is None assert (v + x + n).is_nonnegative is None def test_Pow_is_integer(): x = Symbol('x') k = Symbol('k', integer=True) n = Symbol('n', integer=True, nonnegative=True) m = Symbol('m', integer=True, positive=True) assert (k**2).is_integer is True assert (k**(-2)).is_integer is None assert ((m + 1)**(-2)).is_integer is False assert (m**(-1)).is_integer is None # issue 8580 assert (2**k).is_integer is None assert (2**(-k)).is_integer is None assert (2**n).is_integer is True assert (2**(-n)).is_integer is None assert (2**m).is_integer is True assert (2**(-m)).is_integer is False assert (x**2).is_integer is None assert (2**x).is_integer is None assert (k**n).is_integer is True assert (k**(-n)).is_integer is None assert (k**x).is_integer is None assert (x**k).is_integer is None assert (k**(n*m)).is_integer is True assert (k**(-n*m)).is_integer is None assert sqrt(3).is_integer is False assert sqrt(.3).is_integer is False assert Pow(3, 2, evaluate=False).is_integer is True assert Pow(3, 0, evaluate=False).is_integer is True assert Pow(3, -2, evaluate=False).is_integer is False assert Pow(S.Half, 3, evaluate=False).is_integer is False # decided by re-evaluating assert Pow(3, S.Half, evaluate=False).is_integer is False assert Pow(3, S.Half, evaluate=False).is_integer is False assert Pow(4, S.Half, evaluate=False).is_integer is True assert Pow(S.Half, -2, evaluate=False).is_integer is True assert ((-1)**k).is_integer # issue 8641 x = Symbol('x', real=True, integer=False) assert (x**2).is_integer is None # issue 10458 x = Symbol('x', positive=True) assert (1/(x + 1)).is_integer is False assert (1/(-x - 1)).is_integer is False def test_Pow_is_real(): x = Symbol('x', real=True) y = Symbol('y', real=True, positive=True) assert (x**2).is_real is True assert (x**3).is_real is True assert (x**x).is_real is None assert (y**x).is_real is True assert (x**Rational(1, 3)).is_real is None assert (y**Rational(1, 3)).is_real is True assert sqrt(-1 - sqrt(2)).is_real is False i = Symbol('i', imaginary=True) assert (i**i).is_real is None assert (I**i).is_extended_real is True assert ((-I)**i).is_extended_real is True assert (2**i).is_real is None # (2**(pi/log(2) * I)) is real, 2**I is not assert (2**I).is_real is False assert (2**-I).is_real is False assert (i**2).is_extended_real is True assert (i**3).is_extended_real is False assert (i**x).is_real is None # could be (-I)**(2/3) e = Symbol('e', even=True) o = Symbol('o', odd=True) k = Symbol('k', integer=True) assert (i**e).is_extended_real is True assert (i**o).is_extended_real is False assert (i**k).is_real is None assert (i**(4*k)).is_extended_real is True x = Symbol("x", nonnegative=True) y = Symbol("y", nonnegative=True) assert im(x**y).expand(complex=True) is S.Zero assert (x**y).is_real is True i = Symbol('i', imaginary=True) assert (exp(i)**I).is_extended_real is True assert log(exp(i)).is_imaginary is None # i could be 2*pi*I c = Symbol('c', complex=True) assert log(c).is_real is None # c could be 0 or 2, too assert log(exp(c)).is_real is None # log(0), log(E), ... n = Symbol('n', negative=False) assert log(n).is_real is None n = Symbol('n', nonnegative=True) assert log(n).is_real is None assert sqrt(-I).is_real is False # issue 7843 i = Symbol('i', integer=True) assert (1/(i-1)).is_real is None assert (1/(i-1)).is_extended_real is None def test_real_Pow(): k = Symbol('k', integer=True, nonzero=True) assert (k**(I*pi/log(k))).is_real def test_Pow_is_finite(): xe = Symbol('xe', extended_real=True) xr = Symbol('xr', real=True) p = Symbol('p', positive=True) n = Symbol('n', negative=True) i = Symbol('i', integer=True) assert (xe**2).is_finite is None # xe could be oo assert (xr**2).is_finite is True assert (xe**xe).is_finite is None assert (xr**xe).is_finite is None assert (xe**xr).is_finite is None # FIXME: The line below should be True rather than None # assert (xr**xr).is_finite is True assert (xr**xr).is_finite is None assert (p**xe).is_finite is None assert (p**xr).is_finite is True assert (n**xe).is_finite is None assert (n**xr).is_finite is True assert (sin(xe)**2).is_finite is True assert (sin(xr)**2).is_finite is True assert (sin(xe)**xe).is_finite is None # xe, xr could be -pi assert (sin(xr)**xr).is_finite is None # FIXME: Should the line below be True rather than None? assert (sin(xe)**exp(xe)).is_finite is None assert (sin(xr)**exp(xr)).is_finite is True assert (1/sin(xe)).is_finite is None # if zero, no, otherwise yes assert (1/sin(xr)).is_finite is None assert (1/exp(xe)).is_finite is None # xe could be -oo assert (1/exp(xr)).is_finite is True assert (1/S.Pi).is_finite is True assert (1/(i-1)).is_finite is None def test_Pow_is_even_odd(): x = Symbol('x') k = Symbol('k', even=True) n = Symbol('n', odd=True) m = Symbol('m', integer=True, nonnegative=True) p = Symbol('p', integer=True, positive=True) assert ((-1)**n).is_odd assert ((-1)**k).is_odd assert ((-1)**(m - p)).is_odd assert (k**2).is_even is True assert (n**2).is_even is False assert (2**k).is_even is None assert (x**2).is_even is None assert (k**m).is_even is None assert (n**m).is_even is False assert (k**p).is_even is True assert (n**p).is_even is False assert (m**k).is_even is None assert (p**k).is_even is None assert (m**n).is_even is None assert (p**n).is_even is None assert (k**x).is_even is None assert (n**x).is_even is None assert (k**2).is_odd is False assert (n**2).is_odd is True assert (3**k).is_odd is None assert (k**m).is_odd is None assert (n**m).is_odd is True assert (k**p).is_odd is False assert (n**p).is_odd is True assert (m**k).is_odd is None assert (p**k).is_odd is None assert (m**n).is_odd is None assert (p**n).is_odd is None assert (k**x).is_odd is None assert (n**x).is_odd is None def test_Pow_is_negative_positive(): r = Symbol('r', real=True) k = Symbol('k', integer=True, positive=True) n = Symbol('n', even=True) m = Symbol('m', odd=True) x = Symbol('x') assert (2**r).is_positive is True assert ((-2)**r).is_positive is None assert ((-2)**n).is_positive is True assert ((-2)**m).is_positive is False assert (k**2).is_positive is True assert (k**(-2)).is_positive is True assert (k**r).is_positive is True assert ((-k)**r).is_positive is None assert ((-k)**n).is_positive is True assert ((-k)**m).is_positive is False assert (2**r).is_negative is False assert ((-2)**r).is_negative is None assert ((-2)**n).is_negative is False assert ((-2)**m).is_negative is True assert (k**2).is_negative is False assert (k**(-2)).is_negative is False assert (k**r).is_negative is False assert ((-k)**r).is_negative is None assert ((-k)**n).is_negative is False assert ((-k)**m).is_negative is True assert (2**x).is_positive is None assert (2**x).is_negative is None def test_Pow_is_zero(): z = Symbol('z', zero=True) e = z**2 assert e.is_zero assert e.is_positive is False assert e.is_negative is False assert Pow(0, 0, evaluate=False).is_zero is False assert Pow(0, 3, evaluate=False).is_zero assert Pow(0, oo, evaluate=False).is_zero assert Pow(0, -3, evaluate=False).is_zero is False assert Pow(0, -oo, evaluate=False).is_zero is False assert Pow(2, 2, evaluate=False).is_zero is False a = Symbol('a', zero=False) assert Pow(a, 3).is_zero is False # issue 7965 assert Pow(2, oo, evaluate=False).is_zero is False assert Pow(2, -oo, evaluate=False).is_zero assert Pow(S.Half, oo, evaluate=False).is_zero assert Pow(S.Half, -oo, evaluate=False).is_zero is False # All combinations of real/complex base/exponent h = S.Half T = True F = False N = None pow_iszero = [ ['**', 0, h, 1, 2, -h, -1,-2,-2*I,-I/2,I/2,1+I,oo,-oo,zoo], [ 0, F, T, T, T, F, F, F, F, F, F, N, T, F, N], [ h, F, F, F, F, F, F, F, F, F, F, F, T, F, N], [ 1, F, F, F, F, F, F, F, F, F, F, F, F, F, N], [ 2, F, F, F, F, F, F, F, F, F, F, F, F, T, N], [ -h, F, F, F, F, F, F, F, F, F, F, F, T, F, N], [ -1, F, F, F, F, F, F, F, F, F, F, F, F, F, N], [ -2, F, F, F, F, F, F, F, F, F, F, F, F, T, N], [-2*I, F, F, F, F, F, F, F, F, F, F, F, F, T, N], [-I/2, F, F, F, F, F, F, F, F, F, F, F, T, F, N], [ I/2, F, F, F, F, F, F, F, F, F, F, F, T, F, N], [ 1+I, F, F, F, F, F, F, F, F, F, F, F, F, T, N], [ oo, F, F, F, F, T, T, T, F, F, F, F, F, T, N], [ -oo, F, F, F, F, T, T, T, F, F, F, F, F, T, N], [ zoo, F, F, F, F, T, T, T, N, N, N, N, F, T, N] ] def test_table(table): n = len(table[0]) for row in range(1, n): base = table[row][0] for col in range(1, n): exp = table[0][col] is_zero = table[row][col] # The actual test here: assert Pow(base, exp, evaluate=False).is_zero is is_zero test_table(pow_iszero) # A zero symbol... zo, zo2 = symbols('zo, zo2', zero=True) # All combinations of finite symbols zf, zf2 = symbols('zf, zf2', finite=True) wf, wf2 = symbols('wf, wf2', nonzero=True) xf, xf2 = symbols('xf, xf2', real=True) yf, yf2 = symbols('yf, yf2', nonzero=True) af, af2 = symbols('af, af2', positive=True) bf, bf2 = symbols('bf, bf2', nonnegative=True) cf, cf2 = symbols('cf, cf2', negative=True) df, df2 = symbols('df, df2', nonpositive=True) # Without finiteness: zi, zi2 = symbols('zi, zi2') wi, wi2 = symbols('wi, wi2', zero=False) xi, xi2 = symbols('xi, xi2', extended_real=True) yi, yi2 = symbols('yi, yi2', zero=False, extended_real=True) ai, ai2 = symbols('ai, ai2', extended_positive=True) bi, bi2 = symbols('bi, bi2', extended_nonnegative=True) ci, ci2 = symbols('ci, ci2', extended_negative=True) di, di2 = symbols('di, di2', extended_nonpositive=True) pow_iszero_sym = [ ['**',zo,wf,yf,af,cf,zf,xf,bf,df,zi,wi,xi,yi,ai,bi,ci,di], [ zo2, F, N, N, T, F, N, N, N, F, N, N, N, N, T, N, F, F], [ wf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N], [ yf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N], [ af2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N], [ cf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N], [ zf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N], [ xf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N], [ bf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N], [ df2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N], [ zi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N], [ wi2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N], [ xi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N], [ yi2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N], [ ai2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N], [ bi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N], [ ci2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N], [ di2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N] ] test_table(pow_iszero_sym) # In some cases (x**x).is_zero is different from (x**y).is_zero even if y # has the same assumptions as x. assert (zo ** zo).is_zero is False assert (wf ** wf).is_zero is False assert (yf ** yf).is_zero is False assert (af ** af).is_zero is False assert (cf ** cf).is_zero is False assert (zf ** zf).is_zero is None assert (xf ** xf).is_zero is None assert (bf ** bf).is_zero is False # None in table assert (df ** df).is_zero is None assert (zi ** zi).is_zero is None assert (wi ** wi).is_zero is None assert (xi ** xi).is_zero is None assert (yi ** yi).is_zero is None assert (ai ** ai).is_zero is False # None in table assert (bi ** bi).is_zero is False # None in table assert (ci ** ci).is_zero is None assert (di ** di).is_zero is None def test_Pow_is_nonpositive_nonnegative(): x = Symbol('x', real=True) k = Symbol('k', integer=True, nonnegative=True) l = Symbol('l', integer=True, positive=True) n = Symbol('n', even=True) m = Symbol('m', odd=True) assert (x**(4*k)).is_nonnegative is True assert (2**x).is_nonnegative is True assert ((-2)**x).is_nonnegative is None assert ((-2)**n).is_nonnegative is True assert ((-2)**m).is_nonnegative is False assert (k**2).is_nonnegative is True assert (k**(-2)).is_nonnegative is None assert (k**k).is_nonnegative is True assert (k**x).is_nonnegative is None # NOTE (0**x).is_real = U assert (l**x).is_nonnegative is True assert (l**x).is_positive is True assert ((-k)**x).is_nonnegative is None assert ((-k)**m).is_nonnegative is None assert (2**x).is_nonpositive is False assert ((-2)**x).is_nonpositive is None assert ((-2)**n).is_nonpositive is False assert ((-2)**m).is_nonpositive is True assert (k**2).is_nonpositive is None assert (k**(-2)).is_nonpositive is None assert (k**x).is_nonpositive is None assert ((-k)**x).is_nonpositive is None assert ((-k)**n).is_nonpositive is None assert (x**2).is_nonnegative is True i = symbols('i', imaginary=True) assert (i**2).is_nonpositive is True assert (i**4).is_nonpositive is False assert (i**3).is_nonpositive is False assert (I**i).is_nonnegative is True assert (exp(I)**i).is_nonnegative is True assert ((-l)**n).is_nonnegative is True assert ((-l)**m).is_nonpositive is True assert ((-k)**n).is_nonnegative is None assert ((-k)**m).is_nonpositive is None def test_Mul_is_imaginary_real(): r = Symbol('r', real=True) p = Symbol('p', positive=True) i1 = Symbol('i1', imaginary=True) i2 = Symbol('i2', imaginary=True) x = Symbol('x') assert I.is_imaginary is True assert I.is_real is False assert (-I).is_imaginary is True assert (-I).is_real is False assert (3*I).is_imaginary is True assert (3*I).is_real is False assert (I*I).is_imaginary is False assert (I*I).is_real is True e = (p + p*I) j = Symbol('j', integer=True, zero=False) assert (e**j).is_real is None assert (e**(2*j)).is_real is None assert (e**j).is_imaginary is None assert (e**(2*j)).is_imaginary is None assert (e**-1).is_imaginary is False assert (e**2).is_imaginary assert (e**3).is_imaginary is False assert (e**4).is_imaginary is False assert (e**5).is_imaginary is False assert (e**-1).is_real is False assert (e**2).is_real is False assert (e**3).is_real is False assert (e**4).is_real is True assert (e**5).is_real is False assert (e**3).is_complex assert (r*i1).is_imaginary is None assert (r*i1).is_real is None assert (x*i1).is_imaginary is None assert (x*i1).is_real is None assert (i1*i2).is_imaginary is False assert (i1*i2).is_real is True assert (r*i1*i2).is_imaginary is False assert (r*i1*i2).is_real is True # Github's issue 5874: nr = Symbol('nr', real=False, complex=True) # e.g. I or 1 + I a = Symbol('a', real=True, nonzero=True) b = Symbol('b', real=True) assert (i1*nr).is_real is None assert (a*nr).is_real is False assert (b*nr).is_real is None ni = Symbol('ni', imaginary=False, complex=True) # e.g. 2 or 1 + I a = Symbol('a', real=True, nonzero=True) b = Symbol('b', real=True) assert (i1*ni).is_real is False assert (a*ni).is_real is None assert (b*ni).is_real is None def test_Mul_hermitian_antihermitian(): a = Symbol('a', hermitian=True, zero=False) b = Symbol('b', hermitian=True) c = Symbol('c', hermitian=False) d = Symbol('d', antihermitian=True) e1 = Mul(a, b, c, evaluate=False) e2 = Mul(b, a, c, evaluate=False) e3 = Mul(a, b, c, d, evaluate=False) e4 = Mul(b, a, c, d, evaluate=False) e5 = Mul(a, c, evaluate=False) e6 = Mul(a, c, d, evaluate=False) assert e1.is_hermitian is None assert e2.is_hermitian is None assert e1.is_antihermitian is None assert e2.is_antihermitian is None assert e3.is_antihermitian is None assert e4.is_antihermitian is None assert e5.is_antihermitian is None assert e6.is_antihermitian is None def test_Add_is_comparable(): assert (x + y).is_comparable is False assert (x + 1).is_comparable is False assert (Rational(1, 3) - sqrt(8)).is_comparable is True def test_Mul_is_comparable(): assert (x*y).is_comparable is False assert (x*2).is_comparable is False assert (sqrt(2)*Rational(1, 3)).is_comparable is True def test_Pow_is_comparable(): assert (x**y).is_comparable is False assert (x**2).is_comparable is False assert (sqrt(Rational(1, 3))).is_comparable is True def test_Add_is_positive_2(): e = Rational(1, 3) - sqrt(8) assert e.is_positive is False assert e.is_negative is True e = pi - 1 assert e.is_positive is True assert e.is_negative is False def test_Add_is_irrational(): i = Symbol('i', irrational=True) assert i.is_irrational is True assert i.is_rational is False assert (i + 1).is_irrational is True assert (i + 1).is_rational is False def test_Mul_is_irrational(): expr = Mul(1, 2, 3, evaluate=False) assert expr.is_irrational is False expr = Mul(1, I, I, evaluate=False) assert expr.is_rational is None # I * I = -1 but *no evaluation allowed* # sqrt(2) * I * I = -sqrt(2) is irrational but # this can't be determined without evaluating the # expression and the eval_is routines shouldn't do that expr = Mul(sqrt(2), I, I, evaluate=False) assert expr.is_irrational is None def test_issue_3531(): # https://github.com/sympy/sympy/issues/3531 # https://github.com/sympy/sympy/pull/18116 class MightyNumeric(tuple): def __rtruediv__(self, other): return "something" assert sympify(1)/MightyNumeric((1, 2)) == "something" def test_issue_3531b(): class Foo: def __init__(self): self.field = 1.0 def __mul__(self, other): self.field = self.field * other def __rmul__(self, other): self.field = other * self.field f = Foo() x = Symbol("x") assert f*x == x*f def test_bug3(): a = Symbol("a") b = Symbol("b", positive=True) e = 2*a + b f = b + 2*a assert e == f def test_suppressed_evaluation(): a = Add(0, 3, 2, evaluate=False) b = Mul(1, 3, 2, evaluate=False) c = Pow(3, 2, evaluate=False) assert a != 6 assert a.func is Add assert a.args == (0, 3, 2) assert b != 6 assert b.func is Mul assert b.args == (1, 3, 2) assert c != 9 assert c.func is Pow assert c.args == (3, 2) def test_AssocOp_doit(): a = Add(x,x, evaluate=False) b = Mul(y,y, evaluate=False) c = Add(b,b, evaluate=False) d = Mul(a,a, evaluate=False) assert c.doit(deep=False).func == Mul assert c.doit(deep=False).args == (2,y,y) assert c.doit().func == Mul assert c.doit().args == (2, Pow(y,2)) assert d.doit(deep=False).func == Pow assert d.doit(deep=False).args == (a, 2*S.One) assert d.doit().func == Mul assert d.doit().args == (4*S.One, Pow(x,2)) def test_Add_Mul_Expr_args(): nonexpr = [Basic(), Poly(x, x), FiniteSet(x)] for typ in [Add, Mul]: for obj in nonexpr: with warns_deprecated_sympy(): typ(obj, 1) def test_Add_as_coeff_mul(): # issue 5524. These should all be (1, self) assert (x + 1).as_coeff_mul() == (1, (x + 1,)) assert (x + 2).as_coeff_mul() == (1, (x + 2,)) assert (x + 3).as_coeff_mul() == (1, (x + 3,)) assert (x - 1).as_coeff_mul() == (1, (x - 1,)) assert (x - 2).as_coeff_mul() == (1, (x - 2,)) assert (x - 3).as_coeff_mul() == (1, (x - 3,)) n = Symbol('n', integer=True) assert (n + 1).as_coeff_mul() == (1, (n + 1,)) assert (n + 2).as_coeff_mul() == (1, (n + 2,)) assert (n + 3).as_coeff_mul() == (1, (n + 3,)) assert (n - 1).as_coeff_mul() == (1, (n - 1,)) assert (n - 2).as_coeff_mul() == (1, (n - 2,)) assert (n - 3).as_coeff_mul() == (1, (n - 3,)) def test_Pow_as_coeff_mul_doesnt_expand(): assert exp(x + y).as_coeff_mul() == (1, (exp(x + y),)) assert exp(x + exp(x + y)) != exp(x + exp(x)*exp(y)) def test_issue_3514_18626(): assert sqrt(S.Half) * sqrt(6) == 2 * sqrt(3)/2 assert S.Half*sqrt(6)*sqrt(2) == sqrt(3) assert sqrt(6)/2*sqrt(2) == sqrt(3) assert sqrt(6)*sqrt(2)/2 == sqrt(3) assert sqrt(8)**Rational(2, 3) == 2 def test_make_args(): assert Add.make_args(x) == (x,) assert Mul.make_args(x) == (x,) assert Add.make_args(x*y*z) == (x*y*z,) assert Mul.make_args(x*y*z) == (x*y*z).args assert Add.make_args(x + y + z) == (x + y + z).args assert Mul.make_args(x + y + z) == (x + y + z,) assert Add.make_args((x + y)**z) == ((x + y)**z,) assert Mul.make_args((x + y)**z) == ((x + y)**z,) def test_issue_5126(): assert (-2)**x*(-3)**x != 6**x i = Symbol('i', integer=1) assert (-2)**i*(-3)**i == 6**i def test_Rational_as_content_primitive(): c, p = S.One, S.Zero assert (c*p).as_content_primitive() == (c, p) c, p = S.Half, S.One assert (c*p).as_content_primitive() == (c, p) def test_Add_as_content_primitive(): assert (x + 2).as_content_primitive() == (1, x + 2) assert (3*x + 2).as_content_primitive() == (1, 3*x + 2) assert (3*x + 3).as_content_primitive() == (3, x + 1) assert (3*x + 6).as_content_primitive() == (3, x + 2) assert (3*x + 2*y).as_content_primitive() == (1, 3*x + 2*y) assert (3*x + 3*y).as_content_primitive() == (3, x + y) assert (3*x + 6*y).as_content_primitive() == (3, x + 2*y) assert (3/x + 2*x*y*z**2).as_content_primitive() == (1, 3/x + 2*x*y*z**2) assert (3/x + 3*x*y*z**2).as_content_primitive() == (3, 1/x + x*y*z**2) assert (3/x + 6*x*y*z**2).as_content_primitive() == (3, 1/x + 2*x*y*z**2) assert (2*x/3 + 4*y/9).as_content_primitive() == \ (Rational(2, 9), 3*x + 2*y) assert (2*x/3 + 2.5*y).as_content_primitive() == \ (Rational(1, 3), 2*x + 7.5*y) # the coefficient may sort to a position other than 0 p = 3 + x + y assert (2*p).expand().as_content_primitive() == (2, p) assert (2.0*p).expand().as_content_primitive() == (1, 2.*p) p *= -1 assert (2*p).expand().as_content_primitive() == (2, p) def test_Mul_as_content_primitive(): assert (2*x).as_content_primitive() == (2, x) assert (x*(2 + 2*x)).as_content_primitive() == (2, x*(1 + x)) assert (x*(2 + 2*y)*(3*x + 3)**2).as_content_primitive() == \ (18, x*(1 + y)*(x + 1)**2) assert ((2 + 2*x)**2*(3 + 6*x) + S.Half).as_content_primitive() == \ (S.Half, 24*(x + 1)**2*(2*x + 1) + 1) def test_Pow_as_content_primitive(): assert (x**y).as_content_primitive() == (1, x**y) assert ((2*x + 2)**y).as_content_primitive() == \ (1, (Mul(2, (x + 1), evaluate=False))**y) assert ((2*x + 2)**3).as_content_primitive() == (8, (x + 1)**3) def test_issue_5460(): u = Mul(2, (1 + x), evaluate=False) assert (2 + u).args == (2, u) def test_product_irrational(): from sympy import I, pi assert (I*pi).is_irrational is False # The following used to be deduced from the above bug: assert (I*pi).is_positive is False def test_issue_5919(): assert (x/(y*(1 + y))).expand() == x/(y**2 + y) def test_Mod(): assert Mod(x, 1).func is Mod assert pi % pi is S.Zero assert Mod(5, 3) == 2 assert Mod(-5, 3) == 1 assert Mod(5, -3) == -1 assert Mod(-5, -3) == -2 assert type(Mod(3.2, 2, evaluate=False)) == Mod assert 5 % x == Mod(5, x) assert x % 5 == Mod(x, 5) assert x % y == Mod(x, y) assert (x % y).subs({x: 5, y: 3}) == 2 assert Mod(nan, 1) is nan assert Mod(1, nan) is nan assert Mod(nan, nan) is nan Mod(0, x) == 0 with raises(ZeroDivisionError): Mod(x, 0) k = Symbol('k', integer=True) m = Symbol('m', integer=True, positive=True) assert (x**m % x).func is Mod assert (k**(-m) % k).func is Mod assert k**m % k == 0 assert (-2*k)**m % k == 0 # Float handling point3 = Float(3.3) % 1 assert (x - 3.3) % 1 == Mod(1.*x + 1 - point3, 1) assert Mod(-3.3, 1) == 1 - point3 assert Mod(0.7, 1) == Float(0.7) e = Mod(1.3, 1) assert comp(e, .3) and e.is_Float e = Mod(1.3, .7) assert comp(e, .6) and e.is_Float e = Mod(1.3, Rational(7, 10)) assert comp(e, .6) and e.is_Float e = Mod(Rational(13, 10), 0.7) assert comp(e, .6) and e.is_Float e = Mod(Rational(13, 10), Rational(7, 10)) assert comp(e, .6) and e.is_Rational # check that sign is right r2 = sqrt(2) r3 = sqrt(3) for i in [-r3, -r2, r2, r3]: for j in [-r3, -r2, r2, r3]: assert verify_numerically(i % j, i.n() % j.n()) for _x in range(4): for _y in range(9): reps = [(x, _x), (y, _y)] assert Mod(3*x + y, 9).subs(reps) == (3*_x + _y) % 9 # denesting t = Symbol('t', real=True) assert Mod(Mod(x, t), t) == Mod(x, t) assert Mod(-Mod(x, t), t) == Mod(-x, t) assert Mod(Mod(x, 2*t), t) == Mod(x, t) assert Mod(-Mod(x, 2*t), t) == Mod(-x, t) assert Mod(Mod(x, t), 2*t) == Mod(x, t) assert Mod(-Mod(x, t), -2*t) == -Mod(x, t) for i in [-4, -2, 2, 4]: for j in [-4, -2, 2, 4]: for k in range(4): assert Mod(Mod(x, i), j).subs({x: k}) == (k % i) % j assert Mod(-Mod(x, i), j).subs({x: k}) == -(k % i) % j # known difference assert Mod(5*sqrt(2), sqrt(5)) == 5*sqrt(2) - 3*sqrt(5) p = symbols('p', positive=True) assert Mod(2, p + 3) == 2 assert Mod(-2, p + 3) == p + 1 assert Mod(2, -p - 3) == -p - 1 assert Mod(-2, -p - 3) == -2 assert Mod(p + 5, p + 3) == 2 assert Mod(-p - 5, p + 3) == p + 1 assert Mod(p + 5, -p - 3) == -p - 1 assert Mod(-p - 5, -p - 3) == -2 assert Mod(p + 1, p - 1).func is Mod # handling sums assert (x + 3) % 1 == Mod(x, 1) assert (x + 3.0) % 1 == Mod(1.*x, 1) assert (x - S(33)/10) % 1 == Mod(x + S(7)/10, 1) a = Mod(.6*x + y, .3*y) b = Mod(0.1*y + 0.6*x, 0.3*y) # Test that a, b are equal, with 1e-14 accuracy in coefficients eps = 1e-14 assert abs((a.args[0] - b.args[0]).subs({x: 1, y: 1})) < eps assert abs((a.args[1] - b.args[1]).subs({x: 1, y: 1})) < eps assert (x + 1) % x == 1 % x assert (x + y) % x == y % x assert (x + y + 2) % x == (y + 2) % x assert (a + 3*x + 1) % (2*x) == Mod(a + x + 1, 2*x) assert (12*x + 18*y) % (3*x) == 3*Mod(6*y, x) # gcd extraction assert (-3*x) % (-2*y) == -Mod(3*x, 2*y) assert (.6*pi) % (.3*x*pi) == 0.3*pi*Mod(2, x) assert (.6*pi) % (.31*x*pi) == pi*Mod(0.6, 0.31*x) assert (6*pi) % (.3*x*pi) == 0.3*pi*Mod(20, x) assert (6*pi) % (.31*x*pi) == pi*Mod(6, 0.31*x) assert (6*pi) % (.42*x*pi) == pi*Mod(6, 0.42*x) assert (12*x) % (2*y) == 2*Mod(6*x, y) assert (12*x) % (3*5*y) == 3*Mod(4*x, 5*y) assert (12*x) % (15*x*y) == 3*x*Mod(4, 5*y) assert (-2*pi) % (3*pi) == pi assert (2*x + 2) % (x + 1) == 0 assert (x*(x + 1)) % (x + 1) == (x + 1)*Mod(x, 1) assert Mod(5.0*x, 0.1*y) == 0.1*Mod(50*x, y) i = Symbol('i', integer=True) assert (3*i*x) % (2*i*y) == i*Mod(3*x, 2*y) assert Mod(4*i, 4) == 0 # issue 8677 n = Symbol('n', integer=True, positive=True) assert factorial(n) % n == 0 assert factorial(n + 2) % n == 0 assert (factorial(n + 4) % (n + 5)).func is Mod # Wilson's theorem factorial(18042, evaluate=False) % 18043 == 18042 p = Symbol('n', prime=True) factorial(p - 1) % p == p - 1 factorial(p - 1) % -p == -1 (factorial(3, evaluate=False) % 4).doit() == 2 n = Symbol('n', composite=True, odd=True) factorial(n - 1) % n == 0 # symbolic with known parity n = Symbol('n', even=True) assert Mod(n, 2) == 0 n = Symbol('n', odd=True) assert Mod(n, 2) == 1 # issue 10963 assert (x**6000%400).args[1] == 400 #issue 13543 assert Mod(Mod(x + 1, 2) + 1 , 2) == Mod(x,2) assert Mod(Mod(x + 2, 4)*(x + 4), 4) == Mod(x*(x + 2), 4) assert Mod(Mod(x + 2, 4)*4, 4) == 0 # issue 15493 i, j = symbols('i j', integer=True, positive=True) assert Mod(3*i, 2) == Mod(i, 2) assert Mod(8*i/j, 4) == 4*Mod(2*i/j, 1) assert Mod(8*i, 4) == 0 # rewrite assert Mod(x, y).rewrite(floor) == x - y*floor(x/y) assert ((x - Mod(x, y))/y).rewrite(floor) == floor(x/y) def test_Mod_Pow(): # modular exponentiation assert isinstance(Mod(Pow(2, 2, evaluate=False), 3), Integer) assert Mod(Pow(4, 13, evaluate=False), 497) == Mod(Pow(4, 13), 497) assert Mod(Pow(2, 10000000000, evaluate=False), 3) == 1 assert Mod(Pow(32131231232, 9**10**6, evaluate=False),10**12) == \ pow(32131231232,9**10**6,10**12) assert Mod(Pow(33284959323, 123**999, evaluate=False),11**13) == \ pow(33284959323,123**999,11**13) assert Mod(Pow(78789849597, 333**555, evaluate=False),12**9) == \ pow(78789849597,333**555,12**9) # modular nested exponentiation expr = Pow(2, 2, evaluate=False) expr = Pow(2, expr, evaluate=False) assert Mod(expr, 3**10) == 16 expr = Pow(2, expr, evaluate=False) assert Mod(expr, 3**10) == 6487 expr = Pow(2, expr, evaluate=False) assert Mod(expr, 3**10) == 32191 expr = Pow(2, expr, evaluate=False) assert Mod(expr, 3**10) == 18016 expr = Pow(2, expr, evaluate=False) assert Mod(expr, 3**10) == 5137 expr = Pow(2, 2, evaluate=False) expr = Pow(expr, 2, evaluate=False) assert Mod(expr, 3**10) == 16 expr = Pow(expr, 2, evaluate=False) assert Mod(expr, 3**10) == 256 expr = Pow(expr, 2, evaluate=False) assert Mod(expr, 3**10) == 6487 expr = Pow(expr, 2, evaluate=False) assert Mod(expr, 3**10) == 38281 expr = Pow(expr, 2, evaluate=False) assert Mod(expr, 3**10) == 15928 expr = Pow(2, 2, evaluate=False) expr = Pow(expr, expr, evaluate=False) assert Mod(expr, 3**10) == 256 expr = Pow(expr, expr, evaluate=False) assert Mod(expr, 3**10) == 9229 expr = Pow(expr, expr, evaluate=False) assert Mod(expr, 3**10) == 25708 expr = Pow(expr, expr, evaluate=False) assert Mod(expr, 3**10) == 26608 expr = Pow(expr, expr, evaluate=False) # XXX This used to fail in a nondeterministic way because of overflow # error. assert Mod(expr, 3**10) == 1966 def test_Mod_is_integer(): p = Symbol('p', integer=True) q1 = Symbol('q1', integer=True) q2 = Symbol('q2', integer=True, nonzero=True) assert Mod(x, y).is_integer is None assert Mod(p, q1).is_integer is None assert Mod(x, q2).is_integer is None assert Mod(p, q2).is_integer def test_Mod_is_nonposneg(): n = Symbol('n', integer=True) k = Symbol('k', integer=True, positive=True) assert (n%3).is_nonnegative assert Mod(n, -3).is_nonpositive assert Mod(n, k).is_nonnegative assert Mod(n, -k).is_nonpositive assert Mod(k, n).is_nonnegative is None def test_issue_6001(): A = Symbol("A", commutative=False) eq = A + A**2 # it doesn't matter whether it's True or False; they should # just all be the same assert ( eq.is_commutative == (eq + 1).is_commutative == (A + 1).is_commutative) B = Symbol("B", commutative=False) # Although commutative terms could cancel we return True # meaning "there are non-commutative symbols; aftersubstitution # that definition can change, e.g. (A*B).subs(B,A**-1) -> 1 assert (sqrt(2)*A).is_commutative is False assert (sqrt(2)*A*B).is_commutative is False def test_polar(): from sympy import polar_lift p = Symbol('p', polar=True) x = Symbol('x') assert p.is_polar assert x.is_polar is None assert S.One.is_polar is None assert (p**x).is_polar is True assert (x**p).is_polar is None assert ((2*p)**x).is_polar is True assert (2*p).is_polar is True assert (-2*p).is_polar is not True assert (polar_lift(-2)*p).is_polar is True q = Symbol('q', polar=True) assert (p*q)**2 == p**2 * q**2 assert (2*q)**2 == 4 * q**2 assert ((p*q)**x).expand() == p**x * q**x def test_issue_6040(): a, b = Pow(1, 2, evaluate=False), S.One assert a != b assert b != a assert not (a == b) assert not (b == a) def test_issue_6082(): # Comparison is symmetric assert Basic.compare(Max(x, 1), Max(x, 2)) == \ - Basic.compare(Max(x, 2), Max(x, 1)) # Equal expressions compare equal assert Basic.compare(Max(x, 1), Max(x, 1)) == 0 # Basic subtypes (such as Max) compare different than standard types assert Basic.compare(Max(1, x), frozenset((1, x))) != 0 def test_issue_6077(): assert x**2.0/x == x**1.0 assert x/x**2.0 == x**-1.0 assert x*x**2.0 == x**3.0 assert x**1.5*x**2.5 == x**4.0 assert 2**(2.0*x)/2**x == 2**(1.0*x) assert 2**x/2**(2.0*x) == 2**(-1.0*x) assert 2**x*2**(2.0*x) == 2**(3.0*x) assert 2**(1.5*x)*2**(2.5*x) == 2**(4.0*x) def test_mul_flatten_oo(): p = symbols('p', positive=True) n, m = symbols('n,m', negative=True) x_im = symbols('x_im', imaginary=True) assert n*oo is -oo assert n*m*oo is oo assert p*oo is oo assert x_im*oo != I*oo # i could be +/- 3*I -> +/-oo def test_add_flatten(): # see https://github.com/sympy/sympy/issues/2633#issuecomment-29545524 a = oo + I*oo b = oo - I*oo assert a + b is nan assert a - b is nan # FIXME: This evaluates as: # >>> 1/a # 0*(oo + oo*I) # which should not simplify to 0. Should be fixed in Pow.eval #assert (1/a).simplify() == (1/b).simplify() == 0 a = Pow(2, 3, evaluate=False) assert a + a == 16 def test_issue_5160_6087_6089_6090(): # issue 6087 assert ((-2*x*y**y)**3.2).n(2) == (2**3.2*(-x*y**y)**3.2).n(2) # issue 6089 A, B, C = symbols('A,B,C', commutative=False) assert (2.*B*C)**3 == 8.0*(B*C)**3 assert (-2.*B*C)**3 == -8.0*(B*C)**3 assert (-2*B*C)**2 == 4*(B*C)**2 # issue 5160 assert sqrt(-1.0*x) == 1.0*sqrt(-x) assert sqrt(1.0*x) == 1.0*sqrt(x) # issue 6090 assert (-2*x*y*A*B)**2 == 4*x**2*y**2*(A*B)**2 def test_float_int_round(): assert int(float(sqrt(10))) == int(sqrt(10)) assert int(pi**1000) % 10 == 2 assert int(Float('1.123456789012345678901234567890e20', '')) == \ int(112345678901234567890) assert int(Float('1.123456789012345678901234567890e25', '')) == \ int(11234567890123456789012345) # decimal forces float so it's not an exact integer ending in 000000 assert int(Float('1.123456789012345678901234567890e35', '')) == \ 112345678901234567890123456789000192 assert int(Float('123456789012345678901234567890e5', '')) == \ 12345678901234567890123456789000000 assert Integer(Float('1.123456789012345678901234567890e20', '')) == \ 112345678901234567890 assert Integer(Float('1.123456789012345678901234567890e25', '')) == \ 11234567890123456789012345 # decimal forces float so it's not an exact integer ending in 000000 assert Integer(Float('1.123456789012345678901234567890e35', '')) == \ 112345678901234567890123456789000192 assert Integer(Float('123456789012345678901234567890e5', '')) == \ 12345678901234567890123456789000000 assert same_and_same_prec(Float('123000e-2',''), Float('1230.00', '')) assert same_and_same_prec(Float('123000e2',''), Float('12300000', '')) assert int(1 + Rational('.9999999999999999999999999')) == 1 assert int(pi/1e20) == 0 assert int(1 + pi/1e20) == 1 assert int(Add(1.2, -2, evaluate=False)) == int(1.2 - 2) assert int(Add(1.2, +2, evaluate=False)) == int(1.2 + 2) assert int(Add(1 + Float('.99999999999999999', ''), evaluate=False)) == 1 raises(TypeError, lambda: float(x)) raises(TypeError, lambda: float(sqrt(-1))) assert int(12345678901234567890 + cos(1)**2 + sin(1)**2) == \ 12345678901234567891 def test_issue_6611a(): assert Mul.flatten([3**Rational(1, 3), Pow(-Rational(1, 9), Rational(2, 3), evaluate=False)]) == \ ([Rational(1, 3), (-1)**Rational(2, 3)], [], None) def test_denest_add_mul(): # when working with evaluated expressions make sure they denest eq = x + 1 eq = Add(eq, 2, evaluate=False) eq = Add(eq, 2, evaluate=False) assert Add(*eq.args) == x + 5 eq = x*2 eq = Mul(eq, 2, evaluate=False) eq = Mul(eq, 2, evaluate=False) assert Mul(*eq.args) == 8*x # but don't let them denest unecessarily eq = Mul(-2, x - 2, evaluate=False) assert 2*eq == Mul(-4, x - 2, evaluate=False) assert -eq == Mul(2, x - 2, evaluate=False) def test_mul_coeff(): # It is important that all Numbers be removed from the seq; # This can be tricky when powers combine to produce those numbers p = exp(I*pi/3) assert p**2*x*p*y*p*x*p**2 == x**2*y def test_mul_zero_detection(): nz = Dummy(real=True, zero=False) r = Dummy(extended_real=True) c = Dummy(real=False, complex=True) c2 = Dummy(real=False, complex=True) i = Dummy(imaginary=True) e = nz*r*c assert e.is_imaginary is None assert e.is_extended_real is None e = nz*c assert e.is_imaginary is None assert e.is_extended_real is False e = nz*i*c assert e.is_imaginary is False assert e.is_extended_real is None # check for more than one complex; it is important to use # uniquely named Symbols to ensure that two factors appear # e.g. if the symbols have the same name they just become # a single factor, a power. e = nz*i*c*c2 assert e.is_imaginary is None assert e.is_extended_real is None # _eval_is_extended_real and _eval_is_zero both employ trapping of the # zero value so args should be tested in both directions and # TO AVOID GETTING THE CACHED RESULT, Dummy MUST BE USED # real is unknown def test(z, b, e): if z.is_zero and b.is_finite: assert e.is_extended_real and e.is_zero else: assert e.is_extended_real is None if b.is_finite: if z.is_zero: assert e.is_zero else: assert e.is_zero is None elif b.is_finite is False: if z.is_zero is None: assert e.is_zero is None else: assert e.is_zero is False for iz, ib in cartes(*[[True, False, None]]*2): z = Dummy('z', nonzero=iz) b = Dummy('f', finite=ib) e = Mul(z, b, evaluate=False) test(z, b, e) z = Dummy('nz', nonzero=iz) b = Dummy('f', finite=ib) e = Mul(b, z, evaluate=False) test(z, b, e) # real is True def test(z, b, e): if z.is_zero and not b.is_finite: assert e.is_extended_real is None else: assert e.is_extended_real is True for iz, ib in cartes(*[[True, False, None]]*2): z = Dummy('z', nonzero=iz, extended_real=True) b = Dummy('b', finite=ib, extended_real=True) e = Mul(z, b, evaluate=False) test(z, b, e) z = Dummy('z', nonzero=iz, extended_real=True) b = Dummy('b', finite=ib, extended_real=True) e = Mul(b, z, evaluate=False) test(z, b, e) def test_Mul_with_zero_infinite(): zer = Dummy(zero=True) inf = Dummy(finite=False) e = Mul(zer, inf, evaluate=False) assert e.is_extended_positive is None assert e.is_hermitian is None e = Mul(inf, zer, evaluate=False) assert e.is_extended_positive is None assert e.is_hermitian is None def test_Mul_does_not_cancel_infinities(): a, b = symbols('a b') assert ((zoo + 3*a)/(3*a + zoo)) is nan assert ((b - oo)/(b - oo)) is nan # issue 13904 expr = (1/(a+b) + 1/(a-b))/(1/(a+b) - 1/(a-b)) assert expr.subs(b, a) is nan def test_Mul_does_not_distribute_infinity(): a, b = symbols('a b') assert ((1 + I)*oo).is_Mul assert ((a + b)*(-oo)).is_Mul assert ((a + 1)*zoo).is_Mul assert ((1 + I)*oo).is_finite is False z = (1 + I)*oo assert ((1 - I)*z).expand() is oo def test_issue_8247_8354(): from sympy import tan z = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3)) assert z.is_positive is False # it's 0 z = S('''-2**(1/3)*(3*sqrt(93) + 29)**2 - 4*(3*sqrt(93) + 29)**(4/3) + 12*sqrt(93)*(3*sqrt(93) + 29)**(1/3) + 116*(3*sqrt(93) + 29)**(1/3) + 174*2**(1/3)*sqrt(93) + 1678*2**(1/3)''') assert z.is_positive is False # it's 0 z = 2*(-3*tan(19*pi/90) + sqrt(3))*cos(11*pi/90)*cos(19*pi/90) - \ sqrt(3)*(-3 + 4*cos(19*pi/90)**2) assert z.is_positive is not True # it's zero and it shouldn't hang z = S('''9*(3*sqrt(93) + 29)**(2/3)*((3*sqrt(93) + 29)**(1/3)*(-2**(2/3)*(3*sqrt(93) + 29)**(1/3) - 2) - 2*2**(1/3))**3 + 72*(3*sqrt(93) + 29)**(2/3)*(81*sqrt(93) + 783) + (162*sqrt(93) + 1566)*((3*sqrt(93) + 29)**(1/3)*(-2**(2/3)*(3*sqrt(93) + 29)**(1/3) - 2) - 2*2**(1/3))**2''') assert z.is_positive is False # it's 0 (and a single _mexpand isn't enough) def test_Add_is_zero(): x, y = symbols('x y', zero=True) assert (x + y).is_zero # Issue 15873 e = -2*I + (1 + I)**2 assert e.is_zero is None def test_issue_14392(): assert (sin(zoo)**2).as_real_imag() == (nan, nan) def test_divmod(): assert divmod(x, y) == (x//y, x % y) assert divmod(x, 3) == (x//3, x % 3) assert divmod(3, x) == (3//x, 3 % x) def test__neg__(): assert -(x*y) == -x*y assert -(-x*y) == x*y assert -(1.*x) == -1.*x assert -(-1.*x) == 1.*x assert -(2.*x) == -2.*x assert -(-2.*x) == 2.*x with distribute(False): eq = -(x + y) assert eq.is_Mul and eq.args == (-1, x + y) def test_issue_18507(): assert Mul(zoo, zoo, 0) is nan
8f75141d9eb66b3a253b9fd7a6a5763d2add7b07fec95bacbb6ec3739faed070
"""Implementation of :class:`Ring` class. """ from __future__ import print_function, division from sympy.polys.domains.domain import Domain from sympy.polys.polyerrors import ExactQuotientFailed, NotInvertible, NotReversible from sympy.utilities import public @public class Ring(Domain): """Represents a ring domain. """ is_Ring = True def get_ring(self): """Returns a ring associated with ``self``. """ return self def exquo(self, a, b): """Exact quotient of ``a`` and ``b``, implies ``__floordiv__``. """ if a % b: raise ExactQuotientFailed(a, b, self) else: return a // b def quo(self, a, b): """Quotient of ``a`` and ``b``, implies ``__floordiv__``. """ return a // b def rem(self, a, b): """Remainder of ``a`` and ``b``, implies ``__mod__``. """ return a % b def div(self, a, b): """Division of ``a`` and ``b``, implies ``__divmod__``. """ return divmod(a, b) def invert(self, a, b): """Returns inversion of ``a mod b``. """ s, t, h = self.gcdex(a, b) if self.is_one(h): return s % b else: raise NotInvertible("zero divisor") def revert(self, a): """Returns ``a**(-1)`` if possible. """ if self.is_one(a): return a else: raise NotReversible('only unity is reversible in a ring') def is_unit(self, a): try: self.revert(a) return True except NotReversible: return False def numer(self, a): """Returns numerator of ``a``. """ return a def denom(self, a): """Returns denominator of `a`. """ return self.one def free_module(self, rank): """ Generate a free module of rank ``rank`` over self. >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).free_module(2) QQ[x]**2 """ raise NotImplementedError def ideal(self, *gens): """ Generate an ideal of ``self``. >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).ideal(x**2) <x**2> """ from sympy.polys.agca.ideals import ModuleImplementedIdeal return ModuleImplementedIdeal(self, self.free_module(1).submodule( *[[x] for x in gens])) def quotient_ring(self, e): """ Form a quotient ring of ``self``. Here ``e`` can be an ideal or an iterable. >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).quotient_ring(QQ.old_poly_ring(x).ideal(x**2)) QQ[x]/<x**2> >>> QQ.old_poly_ring(x).quotient_ring([x**2]) QQ[x]/<x**2> The division operator has been overloaded for this: >>> QQ.old_poly_ring(x)/[x**2] QQ[x]/<x**2> """ from sympy.polys.agca.ideals import Ideal from sympy.polys.domains.quotientring import QuotientRing if not isinstance(e, Ideal): e = self.ideal(*e) return QuotientRing(self, e) def __truediv__(self, e): return self.quotient_ring(e)
5e03ddc3efca5035a7e7ad880becfed9a40785268cf071e0c943051167e78f3f
"""Rational number type based on Python integers. """ from __future__ import print_function, division import operator from sympy.core.numbers import Rational, Integer from sympy.core.sympify import converter from sympy.polys.polyutils import PicklableWithSlots from sympy.polys.domains.domainelement import DomainElement from sympy.printing.defaults import DefaultPrinting from sympy.utilities import public @public class PythonRational(DefaultPrinting, PicklableWithSlots, DomainElement): """ Rational number type based on Python integers. This was supposed to be needed for compatibility with older Python versions which don't support Fraction. However, Fraction is very slow so we don't use it anyway. Examples ======== >>> from sympy.polys.domains import PythonRational >>> PythonRational(1) 1 >>> PythonRational(2, 3) 2/3 >>> PythonRational(14, 10) 7/5 """ __slots__ = ('p', 'q') def parent(self): from sympy.polys.domains import PythonRationalField return PythonRationalField() def __init__(self, p, q=1, _gcd=True): from sympy.polys.domains.groundtypes import python_gcd as gcd if isinstance(p, Integer): p = p.p elif isinstance(p, Rational): p, q = p.p, p.q if not q: raise ZeroDivisionError('rational number') elif q < 0: p, q = -p, -q if not p: self.p = 0 self.q = 1 elif p == 1 or q == 1: self.p = p self.q = q else: if _gcd: x = gcd(p, q) if x != 1: p //= x q //= x self.p = p self.q = q @classmethod def new(cls, p, q): obj = object.__new__(cls) obj.p = p obj.q = q return obj def __hash__(self): if self.q == 1: return hash(self.p) else: return hash((self.p, self.q)) def __int__(self): p, q = self.p, self.q if p < 0: return -(-p//q) return p//q def __float__(self): return float(self.p)/self.q def __abs__(self): return self.new(abs(self.p), self.q) def __pos__(self): return self.new(+self.p, self.q) def __neg__(self): return self.new(-self.p, self.q) def __add__(self, other): from sympy.polys.domains.groundtypes import python_gcd as gcd if isinstance(other, PythonRational): ap, aq, bp, bq = self.p, self.q, other.p, other.q g = gcd(aq, bq) if g == 1: p = ap*bq + aq*bp q = bq*aq else: q1, q2 = aq//g, bq//g p, q = ap*q2 + bp*q1, q1*q2 g2 = gcd(p, g) p, q = (p // g2), q * (g // g2) elif isinstance(other, int): p = self.p + self.q*other q = self.q else: return NotImplemented return self.__class__(p, q, _gcd=False) def __radd__(self, other): if not isinstance(other, int): return NotImplemented p = self.p + self.q*other q = self.q return self.__class__(p, q, _gcd=False) def __sub__(self, other): from sympy.polys.domains.groundtypes import python_gcd as gcd if isinstance(other, PythonRational): ap, aq, bp, bq = self.p, self.q, other.p, other.q g = gcd(aq, bq) if g == 1: p = ap*bq - aq*bp q = bq*aq else: q1, q2 = aq//g, bq//g p, q = ap*q2 - bp*q1, q1*q2 g2 = gcd(p, g) p, q = (p // g2), q * (g // g2) elif isinstance(other, int): p = self.p - self.q*other q = self.q else: return NotImplemented return self.__class__(p, q, _gcd=False) def __rsub__(self, other): if not isinstance(other, int): return NotImplemented p = self.q*other - self.p q = self.q return self.__class__(p, q, _gcd=False) def __mul__(self, other): from sympy.polys.domains.groundtypes import python_gcd as gcd if isinstance(other, PythonRational): ap, aq, bp, bq = self.p, self.q, other.p, other.q x1 = gcd(ap, bq) x2 = gcd(bp, aq) p, q = ((ap//x1)*(bp//x2), (aq//x2)*(bq//x1)) elif isinstance(other, int): x = gcd(other, self.q) p = self.p*(other//x) q = self.q//x else: return NotImplemented return self.__class__(p, q, _gcd=False) def __rmul__(self, other): from sympy.polys.domains.groundtypes import python_gcd as gcd if not isinstance(other, int): return NotImplemented x = gcd(self.q, other) p = self.p*(other//x) q = self.q//x return self.__class__(p, q, _gcd=False) def __truediv__(self, other): from sympy.polys.domains.groundtypes import python_gcd as gcd if isinstance(other, PythonRational): ap, aq, bp, bq = self.p, self.q, other.p, other.q x1 = gcd(ap, bp) x2 = gcd(bq, aq) p, q = ((ap//x1)*(bq//x2), (aq//x2)*(bp//x1)) elif isinstance(other, int): x = gcd(other, self.p) p = self.p//x q = self.q*(other//x) else: return NotImplemented return self.__class__(p, q, _gcd=False) def __rtruediv__(self, other): from sympy.polys.domains.groundtypes import python_gcd as gcd if not isinstance(other, int): return NotImplemented x = gcd(self.p, other) p = self.q*(other//x) q = self.p//x return self.__class__(p, q) def __mod__(self, other): return self.__class__(0) def __divmod__(self, other): return (self//other, self % other) def __pow__(self, exp): p, q = self.p, self.q if exp < 0: p, q, exp = q, p, -exp return self.__class__(p**exp, q**exp, _gcd=False) def __bool__(self): return self.p != 0 def __eq__(self, other): if isinstance(other, PythonRational): return self.q == other.q and self.p == other.p elif isinstance(other, int): return self.q == 1 and self.p == other else: return NotImplemented def __ne__(self, other): return not self == other def _cmp(self, other, op): try: diff = self - other except TypeError: return NotImplemented else: return op(diff.p, 0) def __lt__(self, other): return self._cmp(other, operator.lt) def __le__(self, other): return self._cmp(other, operator.le) def __gt__(self, other): return self._cmp(other, operator.gt) def __ge__(self, other): return self._cmp(other, operator.ge) @property def numer(self): return self.p @property def denom(self): return self.q numerator = numer denominator = denom def sympify_pythonrational(arg): return Rational(arg.p, arg.q) converter[PythonRational] = sympify_pythonrational
46191f37eb12fca79def72cce827b8a8f30609a7befcb9ad3d33c44649914c9b
"""Implementation of :class:`GMPYRationalField` class. """ from __future__ import print_function, division from sympy.polys.domains.groundtypes import ( GMPYRational, SymPyRational, gmpy_numer, gmpy_denom, gmpy_factorial, ) from sympy.polys.domains.rationalfield import RationalField from sympy.polys.polyerrors import CoercionFailed from sympy.utilities import public @public class GMPYRationalField(RationalField): """Rational field based on GMPY mpq class. """ dtype = GMPYRational zero = dtype(0) one = dtype(1) tp = type(one) alias = 'QQ_gmpy' def __init__(self): pass def get_ring(self): """Returns ring associated with ``self``. """ from sympy.polys.domains import GMPYIntegerRing return GMPYIntegerRing() def to_sympy(self, a): """Convert `a` to a SymPy object. """ return SymPyRational(int(gmpy_numer(a)), int(gmpy_denom(a))) def from_sympy(self, a): """Convert SymPy's Integer to `dtype`. """ if a.is_Rational: return GMPYRational(a.p, a.q) elif a.is_Float: from sympy.polys.domains import RR return GMPYRational(*map(int, RR.to_rational(a))) else: raise CoercionFailed("expected `Rational` object, got %s" % a) def from_ZZ_python(K1, a, K0): """Convert a Python `int` object to `dtype`. """ return GMPYRational(a) def from_QQ_python(K1, a, K0): """Convert a Python `Fraction` object to `dtype`. """ return GMPYRational(a.numerator, a.denominator) def from_ZZ_gmpy(K1, a, K0): """Convert a GMPY `mpz` object to `dtype`. """ return GMPYRational(a) def from_QQ_gmpy(K1, a, K0): """Convert a GMPY `mpq` object to `dtype`. """ return a def from_GaussianRationalField(K1, a, K0): """Convert a `GaussianElement` object to `dtype`. """ if a.y == 0: return GMPYRational(a.x) def from_RealField(K1, a, K0): """Convert a mpmath `mpf` object to `dtype`. """ return GMPYRational(*map(int, K0.to_rational(a))) def exquo(self, a, b): """Exact quotient of `a` and `b`, implies `__truediv__`. """ return GMPYRational(a) / GMPYRational(b) def quo(self, a, b): """Quotient of `a` and `b`, implies `__truediv__`. """ return GMPYRational(a) / GMPYRational(b) def rem(self, a, b): """Remainder of `a` and `b`, implies nothing. """ return self.zero def div(self, a, b): """Division of `a` and `b`, implies `__truediv__`. """ return GMPYRational(a) / GMPYRational(b), self.zero def numer(self, a): """Returns numerator of `a`. """ return a.numerator def denom(self, a): """Returns denominator of `a`. """ return a.denominator def factorial(self, a): """Returns factorial of `a`. """ return GMPYRational(gmpy_factorial(int(a)))
547eaae229ae2a9cf2131432e691b9386d7c9c3924a8b0f8aa36cf749dd0b00d
"""Implementation of :class:`QuotientRing` class.""" from __future__ import print_function, division from sympy.polys.agca.modules import FreeModuleQuotientRing from sympy.polys.domains.ring import Ring from sympy.polys.polyerrors import NotReversible, CoercionFailed from sympy.utilities import public # TODO # - successive quotients (when quotient ideals are implemented) # - poly rings over quotients? # - division by non-units in integral domains? @public class QuotientRingElement(object): """ Class representing elements of (commutative) quotient rings. Attributes: - ring - containing ring - data - element of ring.ring (i.e. base ring) representing self """ def __init__(self, ring, data): self.ring = ring self.data = data def __str__(self): from sympy import sstr return sstr(self.data) + " + " + str(self.ring.base_ideal) def __add__(self, om): if not isinstance(om, self.__class__) or om.ring != self.ring: try: om = self.ring.convert(om) except (NotImplementedError, CoercionFailed): return NotImplemented return self.ring(self.data + om.data) __radd__ = __add__ def __neg__(self): return self.ring(self.data*self.ring.ring.convert(-1)) def __sub__(self, om): return self.__add__(-om) def __rsub__(self, om): return (-self).__add__(om) def __mul__(self, o): if not isinstance(o, self.__class__): try: o = self.ring.convert(o) except (NotImplementedError, CoercionFailed): return NotImplemented return self.ring(self.data*o.data) __rmul__ = __mul__ def __rtruediv__(self, o): return self.ring.revert(self)*o def __truediv__(self, o): if not isinstance(o, self.__class__): try: o = self.ring.convert(o) except (NotImplementedError, CoercionFailed): return NotImplemented return self.ring.revert(o)*self def __pow__(self, oth): return self.ring(self.data**oth) def __eq__(self, om): if not isinstance(om, self.__class__) or om.ring != self.ring: return False return self.ring.is_zero(self - om) def __ne__(self, om): return not self == om class QuotientRing(Ring): """ Class representing (commutative) quotient rings. You should not usually instantiate this by hand, instead use the constructor from the base ring in the construction. >>> from sympy.abc import x >>> from sympy import QQ >>> I = QQ.old_poly_ring(x).ideal(x**3 + 1) >>> QQ.old_poly_ring(x).quotient_ring(I) QQ[x]/<x**3 + 1> Shorter versions are possible: >>> QQ.old_poly_ring(x)/I QQ[x]/<x**3 + 1> >>> QQ.old_poly_ring(x)/[x**3 + 1] QQ[x]/<x**3 + 1> Attributes: - ring - the base ring - base_ideal - the ideal used to form the quotient """ has_assoc_Ring = True has_assoc_Field = False dtype = QuotientRingElement def __init__(self, ring, ideal): if not ideal.ring == ring: raise ValueError('Ideal must belong to %s, got %s' % (ring, ideal)) self.ring = ring self.base_ideal = ideal self.zero = self(self.ring.zero) self.one = self(self.ring.one) def __str__(self): return str(self.ring) + "/" + str(self.base_ideal) def __hash__(self): return hash((self.__class__.__name__, self.dtype, self.ring, self.base_ideal)) def new(self, a): """Construct an element of `self` domain from `a`. """ if not isinstance(a, self.ring.dtype): a = self.ring(a) # TODO optionally disable reduction? return self.dtype(self, self.base_ideal.reduce_element(a)) def __eq__(self, other): """Returns `True` if two domains are equivalent. """ return isinstance(other, QuotientRing) and \ self.ring == other.ring and self.base_ideal == other.base_ideal def from_ZZ_python(K1, a, K0): """Convert a Python `int` object to `dtype`. """ return K1(K1.ring.convert(a, K0)) from_QQ_python = from_ZZ_python from_ZZ_gmpy = from_ZZ_python from_QQ_gmpy = from_ZZ_python from_RealField = from_ZZ_python from_GlobalPolynomialRing = from_ZZ_python from_FractionField = from_ZZ_python def from_sympy(self, a): return self(self.ring.from_sympy(a)) def to_sympy(self, a): return self.ring.to_sympy(a.data) def from_QuotientRing(self, a, K0): if K0 == self: return a def poly_ring(self, *gens): """Returns a polynomial ring, i.e. `K[X]`. """ raise NotImplementedError('nested domains not allowed') def frac_field(self, *gens): """Returns a fraction field, i.e. `K(X)`. """ raise NotImplementedError('nested domains not allowed') def revert(self, a): """ Compute a**(-1), if possible. """ I = self.ring.ideal(a.data) + self.base_ideal try: return self(I.in_terms_of_generators(1)[0]) except ValueError: # 1 not in I raise NotReversible('%s not a unit in %r' % (a, self)) def is_zero(self, a): return self.base_ideal.contains(a.data) def free_module(self, rank): """ Generate a free module of rank ``rank`` over ``self``. >>> from sympy.abc import x >>> from sympy import QQ >>> (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2) (QQ[x]/<x**2 + 1>)**2 """ return FreeModuleQuotientRing(self, rank)
62441ae068d8580e5ef6c991aa73a1568cf7272e5ac4d53a097efe08c0cb49b6
"""Implementation of :class:`Field` class. """ from __future__ import print_function, division from sympy.polys.domains.ring import Ring from sympy.polys.polyerrors import NotReversible, DomainError from sympy.utilities import public @public class Field(Ring): """Represents a field domain. """ is_Field = True is_PID = True def get_ring(self): """Returns a ring associated with ``self``. """ raise DomainError('there is no ring associated with %s' % self) def get_field(self): """Returns a field associated with ``self``. """ return self def exquo(self, a, b): """Exact quotient of ``a`` and ``b``, implies ``__truediv__``. """ return a / b def quo(self, a, b): """Quotient of ``a`` and ``b``, implies ``__truediv__``. """ return a / b def rem(self, a, b): """Remainder of ``a`` and ``b``, implies nothing. """ return self.zero def div(self, a, b): """Division of ``a`` and ``b``, implies ``__truediv__``. """ return a / b, self.zero def gcd(self, a, b): """ Returns GCD of ``a`` and ``b``. This definition of GCD over fields allows to clear denominators in `primitive()`. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy import S, gcd, primitive >>> from sympy.abc import x >>> QQ.gcd(QQ(2, 3), QQ(4, 9)) 2/9 >>> gcd(S(2)/3, S(4)/9) 2/9 >>> primitive(2*x/3 + S(4)/9) (2/9, 3*x + 2) """ try: ring = self.get_ring() except DomainError: return self.one p = ring.gcd(self.numer(a), self.numer(b)) q = ring.lcm(self.denom(a), self.denom(b)) return self.convert(p, ring)/q def lcm(self, a, b): """ Returns LCM of ``a`` and ``b``. >>> from sympy.polys.domains import QQ >>> from sympy import S, lcm >>> QQ.lcm(QQ(2, 3), QQ(4, 9)) 4/3 >>> lcm(S(2)/3, S(4)/9) 4/3 """ try: ring = self.get_ring() except DomainError: return a*b p = ring.lcm(self.numer(a), self.numer(b)) q = ring.gcd(self.denom(a), self.denom(b)) return self.convert(p, ring)/q def revert(self, a): """Returns ``a**(-1)`` if possible. """ if a: return 1/a else: raise NotReversible('zero is not reversible')
844adb1845d651f619e56d2e6b814392f2d0b032345f84f7e9f1a08e18ccf113
"""Implementation of :class:`ExpressionDomain` class. """ from __future__ import print_function, division from sympy.core import sympify, SympifyError from sympy.polys.domains.characteristiczero import CharacteristicZero from sympy.polys.domains.field import Field from sympy.polys.domains.simpledomain import SimpleDomain from sympy.polys.polyutils import PicklableWithSlots from sympy.utilities import public eflags = dict(deep=False, mul=True, power_exp=False, power_base=False, basic=False, multinomial=False, log=False) @public class ExpressionDomain(Field, CharacteristicZero, SimpleDomain): """A class for arbitrary expressions. """ is_SymbolicDomain = is_EX = True class Expression(PicklableWithSlots): """An arbitrary expression. """ __slots__ = ('ex',) def __init__(self, ex): if not isinstance(ex, self.__class__): self.ex = sympify(ex) else: self.ex = ex.ex def __repr__(f): return 'EX(%s)' % repr(f.ex) def __str__(f): return 'EX(%s)' % str(f.ex) def __hash__(self): return hash((self.__class__.__name__, self.ex)) def as_expr(f): return f.ex def numer(f): return f.__class__(f.ex.as_numer_denom()[0]) def denom(f): return f.__class__(f.ex.as_numer_denom()[1]) def simplify(f, ex): return f.__class__(ex.cancel().expand(**eflags)) def __abs__(f): return f.__class__(abs(f.ex)) def __neg__(f): return f.__class__(-f.ex) def _to_ex(f, g): try: return f.__class__(g) except SympifyError: return None def __add__(f, g): g = f._to_ex(g) if g is not None: return f.simplify(f.ex + g.ex) else: return NotImplemented def __radd__(f, g): return f.simplify(f.__class__(g).ex + f.ex) def __sub__(f, g): g = f._to_ex(g) if g is not None: return f.simplify(f.ex - g.ex) else: return NotImplemented def __rsub__(f, g): return f.simplify(f.__class__(g).ex - f.ex) def __mul__(f, g): g = f._to_ex(g) if g is not None: return f.simplify(f.ex*g.ex) else: return NotImplemented def __rmul__(f, g): return f.simplify(f.__class__(g).ex*f.ex) def __pow__(f, n): n = f._to_ex(n) if n is not None: return f.simplify(f.ex**n.ex) else: return NotImplemented def __truediv__(f, g): g = f._to_ex(g) if g is not None: return f.simplify(f.ex/g.ex) else: return NotImplemented def __rtruediv__(f, g): return f.simplify(f.__class__(g).ex/f.ex) def __eq__(f, g): return f.ex == f.__class__(g).ex def __ne__(f, g): return not f == g def __bool__(f): return f.ex != 0 def gcd(f, g): from sympy.polys import gcd return f.__class__(gcd(f.ex, f.__class__(g).ex)) def lcm(f, g): from sympy.polys import lcm return f.__class__(lcm(f.ex, f.__class__(g).ex)) dtype = Expression zero = Expression(0) one = Expression(1) rep = 'EX' has_assoc_Ring = False has_assoc_Field = True def __init__(self): pass def to_sympy(self, a): """Convert ``a`` to a SymPy object. """ return a.as_expr() def from_sympy(self, a): """Convert SymPy's expression to ``dtype``. """ return self.dtype(a) def from_ZZ_python(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_QQ_python(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_ZZ_gmpy(K1, a, K0): """Convert a GMPY ``mpz`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_QQ_gmpy(K1, a, K0): """Convert a GMPY ``mpq`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_GaussianIntegerRing(K1, a, K0): """Convert a ``GaussianRational`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_GaussianRationalField(K1, a, K0): """Convert a ``GaussianRational`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_RealField(K1, a, K0): """Convert a mpmath ``mpf`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_PolynomialRing(K1, a, K0): """Convert a ``DMP`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_FractionField(K1, a, K0): """Convert a ``DMF`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_ExpressionDomain(K1, a, K0): """Convert a ``EX`` object to ``dtype``. """ return a def get_ring(self): """Returns a ring associated with ``self``. """ return self # XXX: EX is not a ring but we don't have much choice here. def get_field(self): """Returns a field associated with ``self``. """ return self def is_positive(self, a): """Returns True if ``a`` is positive. """ return a.ex.as_coeff_mul()[0].is_positive def is_negative(self, a): """Returns True if ``a`` is negative. """ return a.ex.could_extract_minus_sign() def is_nonpositive(self, a): """Returns True if ``a`` is non-positive. """ return a.ex.as_coeff_mul()[0].is_nonpositive def is_nonnegative(self, a): """Returns True if ``a`` is non-negative. """ return a.ex.as_coeff_mul()[0].is_nonnegative def numer(self, a): """Returns numerator of ``a``. """ return a.numer() def denom(self, a): """Returns denominator of ``a``. """ return a.denom() def gcd(self, a, b): return self(1) def lcm(self, a, b): return a.lcm(b)
0c808b87a171a5a2021eb80b59bccacba020d7d53585f767d9e20e5d6a35944f
"""Implementation of :class:`ModularInteger` class. """ from __future__ import print_function, division # from typing import Any, Dict, Tuple, Type import operator from sympy.polys.polyutils import PicklableWithSlots from sympy.polys.polyerrors import CoercionFailed from sympy.polys.domains.domainelement import DomainElement from sympy.utilities import public @public class ModularInteger(PicklableWithSlots, DomainElement): """A class representing a modular integer. """ mod, dom, sym, _parent = None, None, None, None __slots__ = ('val',) def parent(self): return self._parent def __init__(self, val): if isinstance(val, self.__class__): self.val = val.val % self.mod else: self.val = self.dom.convert(val) % self.mod def __hash__(self): return hash((self.val, self.mod)) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, self.val) def __str__(self): return "%s mod %s" % (self.val, self.mod) def __int__(self): return int(self.to_int()) def to_int(self): if self.sym: if self.val <= self.mod // 2: return self.val else: return self.val - self.mod else: return self.val def __pos__(self): return self def __neg__(self): return self.__class__(-self.val) @classmethod def _get_val(cls, other): if isinstance(other, cls): return other.val else: try: return cls.dom.convert(other) except CoercionFailed: return None def __add__(self, other): val = self._get_val(other) if val is not None: return self.__class__(self.val + val) else: return NotImplemented def __radd__(self, other): return self.__add__(other) def __sub__(self, other): val = self._get_val(other) if val is not None: return self.__class__(self.val - val) else: return NotImplemented def __rsub__(self, other): return (-self).__add__(other) def __mul__(self, other): val = self._get_val(other) if val is not None: return self.__class__(self.val * val) else: return NotImplemented def __rmul__(self, other): return self.__mul__(other) def __truediv__(self, other): val = self._get_val(other) if val is not None: return self.__class__(self.val * self._invert(val)) else: return NotImplemented def __rtruediv__(self, other): return self.invert().__mul__(other) def __mod__(self, other): val = self._get_val(other) if val is not None: return self.__class__(self.val % val) else: return NotImplemented def __rmod__(self, other): val = self._get_val(other) if val is not None: return self.__class__(val % self.val) else: return NotImplemented def __pow__(self, exp): if not exp: return self.__class__(self.dom.one) if exp < 0: val, exp = self.invert().val, -exp else: val = self.val return self.__class__(pow(val, int(exp), self.mod)) def _compare(self, other, op): val = self._get_val(other) if val is not None: return op(self.val, val % self.mod) else: return NotImplemented def __eq__(self, other): return self._compare(other, operator.eq) def __ne__(self, other): return self._compare(other, operator.ne) def __lt__(self, other): return self._compare(other, operator.lt) def __le__(self, other): return self._compare(other, operator.le) def __gt__(self, other): return self._compare(other, operator.gt) def __ge__(self, other): return self._compare(other, operator.ge) def __bool__(self): return bool(self.val) @classmethod def _invert(cls, value): return cls.dom.invert(value, cls.mod) def invert(self): return self.__class__(self._invert(self.val)) _modular_integer_cache = {} ## type: Dict[Tuple[Any, Any, Any], Type[ModularInteger]] def ModularIntegerFactory(_mod, _dom, _sym, parent): """Create custom class for specific integer modulus.""" try: _mod = _dom.convert(_mod) except CoercionFailed: ok = False else: ok = True if not ok or _mod < 1: raise ValueError("modulus must be a positive integer, got %s" % _mod) key = _mod, _dom, _sym try: cls = _modular_integer_cache[key] except KeyError: class cls(ModularInteger): mod, dom, sym = _mod, _dom, _sym _parent = parent if _sym: cls.__name__ = "SymmetricModularIntegerMod%s" % _mod else: cls.__name__ = "ModularIntegerMod%s" % _mod _modular_integer_cache[key] = cls return cls
36cdf3439ade7c6c1592cfe904bfb298faedc1f807ea2d43dd88cd4a091d727e
"""Implementation of :class:`Domain` class. """ from __future__ import print_function, division from typing import Any, Optional from sympy.core import Basic, sympify from sympy.core.compatibility import HAS_GMPY, is_sequence from sympy.core.decorators import deprecated from sympy.polys.domains.domainelement import DomainElement from sympy.polys.orderings import lex from sympy.polys.polyerrors import UnificationFailed, CoercionFailed, DomainError from sympy.polys.polyutils import _unify_gens, _not_a_coeff from sympy.utilities import default_sort_key, public @public class Domain(object): """Represents an abstract domain. """ dtype = None ## type: Optional[Type] zero = None # type: Optional[Any] one = None # type: Optional[Any] is_Ring = False is_Field = False has_assoc_Ring = False has_assoc_Field = False is_FiniteField = is_FF = False is_IntegerRing = is_ZZ = False is_RationalField = is_QQ = False is_GaussianRing = is_ZZ_I = False is_GaussianField = is_QQ_I = False is_RealField = is_RR = False is_ComplexField = is_CC = False is_AlgebraicField = is_Algebraic = False is_PolynomialRing = is_Poly = False is_FractionField = is_Frac = False is_SymbolicDomain = is_EX = False is_Exact = True is_Numerical = False is_Simple = False is_Composite = False is_PID = False has_CharacteristicZero = False rep = None # type: Optional[str] alias = None # type: Optional[str] @property # type: ignore @deprecated(useinstead="is_Field", issue=12723, deprecated_since_version="1.1") def has_Field(self): return self.is_Field @property # type: ignore @deprecated(useinstead="is_Ring", issue=12723, deprecated_since_version="1.1") def has_Ring(self): return self.is_Ring def __init__(self): raise NotImplementedError def __str__(self): return self.rep def __repr__(self): return str(self) def __hash__(self): return hash((self.__class__.__name__, self.dtype)) def new(self, *args): return self.dtype(*args) @property def tp(self): return self.dtype def __call__(self, *args): """Construct an element of ``self`` domain from ``args``. """ return self.new(*args) def normal(self, *args): return self.dtype(*args) def convert_from(self, element, base): """Convert ``element`` to ``self.dtype`` given the base domain. """ if base.alias is not None: method = "from_" + base.alias else: method = "from_" + base.__class__.__name__ _convert = getattr(self, method) if _convert is not None: result = _convert(element, base) if result is not None: return result raise CoercionFailed("can't convert %s of type %s from %s to %s" % (element, type(element), base, self)) def convert(self, element, base=None): """Convert ``element`` to ``self.dtype``. """ if _not_a_coeff(element): raise CoercionFailed('%s is not in any domain' % element) if base is not None: return self.convert_from(element, base) if self.of_type(element): return element from sympy.polys.domains import PythonIntegerRing, GMPYIntegerRing, GMPYRationalField, RealField, ComplexField if isinstance(element, int): return self.convert_from(element, PythonIntegerRing()) if HAS_GMPY: integers = GMPYIntegerRing() if isinstance(element, integers.tp): return self.convert_from(element, integers) rationals = GMPYRationalField() if isinstance(element, rationals.tp): return self.convert_from(element, rationals) if isinstance(element, float): parent = RealField(tol=False) return self.convert_from(parent(element), parent) if isinstance(element, complex): parent = ComplexField(tol=False) return self.convert_from(parent(element), parent) if isinstance(element, DomainElement): return self.convert_from(element, element.parent()) # TODO: implement this in from_ methods if self.is_Numerical and getattr(element, 'is_ground', False): return self.convert(element.LC()) if isinstance(element, Basic): try: return self.from_sympy(element) except (TypeError, ValueError): pass else: # TODO: remove this branch if not is_sequence(element): try: element = sympify(element, strict=True) if isinstance(element, Basic): return self.from_sympy(element) except (TypeError, ValueError): pass raise CoercionFailed("can't convert %s of type %s to %s" % (element, type(element), self)) def of_type(self, element): """Check if ``a`` is of type ``dtype``. """ return isinstance(element, self.tp) # XXX: this isn't correct, e.g. PolyElement def __contains__(self, a): """Check if ``a`` belongs to this domain. """ try: if _not_a_coeff(a): raise CoercionFailed self.convert(a) # this might raise, too except CoercionFailed: return False return True def to_sympy(self, a): """Convert ``a`` to a SymPy object. """ raise NotImplementedError def from_sympy(self, a): """Convert a SymPy object to ``dtype``. """ raise NotImplementedError def from_FF_python(K1, a, K0): """Convert ``ModularInteger(int)`` to ``dtype``. """ return None def from_ZZ_python(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return None def from_QQ_python(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return None def from_FF_gmpy(K1, a, K0): """Convert ``ModularInteger(mpz)`` to ``dtype``. """ return None def from_ZZ_gmpy(K1, a, K0): """Convert a GMPY ``mpz`` object to ``dtype``. """ return None def from_QQ_gmpy(K1, a, K0): """Convert a GMPY ``mpq`` object to ``dtype``. """ return None def from_RealField(K1, a, K0): """Convert a real element object to ``dtype``. """ return None def from_ComplexField(K1, a, K0): """Convert a complex element to ``dtype``. """ return None def from_AlgebraicField(K1, a, K0): """Convert an algebraic number to ``dtype``. """ return None def from_PolynomialRing(K1, a, K0): """Convert a polynomial to ``dtype``. """ if a.is_ground: return K1.convert(a.LC, K0.dom) def from_FractionField(K1, a, K0): """Convert a rational function to ``dtype``. """ return None def from_ExpressionDomain(K1, a, K0): """Convert a ``EX`` object to ``dtype``. """ return K1.from_sympy(a.ex) def from_GlobalPolynomialRing(K1, a, K0): """Convert a polynomial to ``dtype``. """ if a.degree() <= 0: return K1.convert(a.LC(), K0.dom) def from_GeneralizedPolynomialRing(K1, a, K0): return K1.from_FractionField(a, K0) def unify_with_symbols(K0, K1, symbols): if (K0.is_Composite and (set(K0.symbols) & set(symbols))) or (K1.is_Composite and (set(K1.symbols) & set(symbols))): raise UnificationFailed("can't unify %s with %s, given %s generators" % (K0, K1, tuple(symbols))) return K0.unify(K1) def unify(K0, K1, symbols=None): """ Construct a minimal domain that contains elements of ``K0`` and ``K1``. Known domains (from smallest to largest): - ``GF(p)`` - ``ZZ`` - ``QQ`` - ``RR(prec, tol)`` - ``CC(prec, tol)`` - ``ALG(a, b, c)`` - ``K[x, y, z]`` - ``K(x, y, z)`` - ``EX`` """ if symbols is not None: return K0.unify_with_symbols(K1, symbols) if K0 == K1: return K0 if K0.is_EX: return K0 if K1.is_EX: return K1 if K0.is_Composite or K1.is_Composite: K0_ground = K0.dom if K0.is_Composite else K0 K1_ground = K1.dom if K1.is_Composite else K1 K0_symbols = K0.symbols if K0.is_Composite else () K1_symbols = K1.symbols if K1.is_Composite else () domain = K0_ground.unify(K1_ground) symbols = _unify_gens(K0_symbols, K1_symbols) order = K0.order if K0.is_Composite else K1.order if ((K0.is_FractionField and K1.is_PolynomialRing or K1.is_FractionField and K0.is_PolynomialRing) and (not K0_ground.is_Field or not K1_ground.is_Field) and domain.is_Field): domain = domain.get_ring() if K0.is_Composite and (not K1.is_Composite or K0.is_FractionField or K1.is_PolynomialRing): cls = K0.__class__ else: cls = K1.__class__ from sympy.polys.domains.old_polynomialring import GlobalPolynomialRing if cls == GlobalPolynomialRing: return cls(domain, symbols) return cls(domain, symbols, order) def mkinexact(cls, K0, K1): prec = max(K0.precision, K1.precision) tol = max(K0.tolerance, K1.tolerance) return cls(prec=prec, tol=tol) if K1.is_ComplexField: K0, K1 = K1, K0 if K0.is_ComplexField: if K1.is_ComplexField or K1.is_RealField: return mkinexact(K0.__class__, K0, K1) else: return K0 if K1.is_RealField: K0, K1 = K1, K0 if K0.is_RealField: if K1.is_RealField: return mkinexact(K0.__class__, K0, K1) elif K1.is_GaussianRing or K1.is_GaussianField: from sympy.polys.domains.complexfield import ComplexField return ComplexField(prec=K0.precision, tol=K0.tolerance) else: return K0 if K1.is_AlgebraicField: K0, K1 = K1, K0 if K0.is_AlgebraicField: if K1.is_GaussianRing: K1 = K1.get_field() if K1.is_GaussianField: K1 = K1.as_AlgebraicField() if K1.is_AlgebraicField: return K0.__class__(K0.dom.unify(K1.dom), *_unify_gens(K0.orig_ext, K1.orig_ext)) else: return K0 if K0.is_GaussianField: return K0 if K1.is_GaussianField: return K1 if K0.is_GaussianRing: if K1.is_RationalField: K0 = K0.get_field() return K0 if K1.is_GaussianRing: if K0.is_RationalField: K1 = K1.get_field() return K1 if K0.is_RationalField: return K0 if K1.is_RationalField: return K1 if K0.is_IntegerRing: return K0 if K1.is_IntegerRing: return K1 if K0.is_FiniteField and K1.is_FiniteField: return K0.__class__(max(K0.mod, K1.mod, key=default_sort_key)) from sympy.polys.domains import EX return EX def __eq__(self, other): """Returns ``True`` if two domains are equivalent. """ return isinstance(other, Domain) and self.dtype == other.dtype def __ne__(self, other): """Returns ``False`` if two domains are equivalent. """ return not self == other def map(self, seq): """Rersively apply ``self`` to all elements of ``seq``. """ result = [] for elt in seq: if isinstance(elt, list): result.append(self.map(elt)) else: result.append(self(elt)) return result def get_ring(self): """Returns a ring associated with ``self``. """ raise DomainError('there is no ring associated with %s' % self) def get_field(self): """Returns a field associated with ``self``. """ raise DomainError('there is no field associated with %s' % self) def get_exact(self): """Returns an exact domain associated with ``self``. """ return self def __getitem__(self, symbols): """The mathematical way to make a polynomial ring. """ if hasattr(symbols, '__iter__'): return self.poly_ring(*symbols) else: return self.poly_ring(symbols) def poly_ring(self, *symbols, order=lex): """Returns a polynomial ring, i.e. `K[X]`. """ from sympy.polys.domains.polynomialring import PolynomialRing return PolynomialRing(self, symbols, order) def frac_field(self, *symbols, order=lex): """Returns a fraction field, i.e. `K(X)`. """ from sympy.polys.domains.fractionfield import FractionField return FractionField(self, symbols, order) def old_poly_ring(self, *symbols, **kwargs): """Returns a polynomial ring, i.e. `K[X]`. """ from sympy.polys.domains.old_polynomialring import PolynomialRing return PolynomialRing(self, *symbols, **kwargs) def old_frac_field(self, *symbols, **kwargs): """Returns a fraction field, i.e. `K(X)`. """ from sympy.polys.domains.old_fractionfield import FractionField return FractionField(self, *symbols, **kwargs) def algebraic_field(self, *extension): r"""Returns an algebraic field, i.e. `K(\alpha, \ldots)`. """ raise DomainError("can't create algebraic field over %s" % self) def inject(self, *symbols): """Inject generators into this domain. """ raise NotImplementedError def is_zero(self, a): """Returns True if ``a`` is zero. """ return not a def is_one(self, a): """Returns True if ``a`` is one. """ return a == self.one def is_positive(self, a): """Returns True if ``a`` is positive. """ return a > 0 def is_negative(self, a): """Returns True if ``a`` is negative. """ return a < 0 def is_nonpositive(self, a): """Returns True if ``a`` is non-positive. """ return a <= 0 def is_nonnegative(self, a): """Returns True if ``a`` is non-negative. """ return a >= 0 def abs(self, a): """Absolute value of ``a``, implies ``__abs__``. """ return abs(a) def neg(self, a): """Returns ``a`` negated, implies ``__neg__``. """ return -a def pos(self, a): """Returns ``a`` positive, implies ``__pos__``. """ return +a def add(self, a, b): """Sum of ``a`` and ``b``, implies ``__add__``. """ return a + b def sub(self, a, b): """Difference of ``a`` and ``b``, implies ``__sub__``. """ return a - b def mul(self, a, b): """Product of ``a`` and ``b``, implies ``__mul__``. """ return a * b def pow(self, a, b): """Raise ``a`` to power ``b``, implies ``__pow__``. """ return a ** b def exquo(self, a, b): """Exact quotient of ``a`` and ``b``, implies something. """ raise NotImplementedError def quo(self, a, b): """Quotient of ``a`` and ``b``, implies something. """ raise NotImplementedError def rem(self, a, b): """Remainder of ``a`` and ``b``, implies ``__mod__``. """ raise NotImplementedError def div(self, a, b): """Division of ``a`` and ``b``, implies something. """ raise NotImplementedError def invert(self, a, b): """Returns inversion of ``a mod b``, implies something. """ raise NotImplementedError def revert(self, a): """Returns ``a**(-1)`` if possible. """ raise NotImplementedError def numer(self, a): """Returns numerator of ``a``. """ raise NotImplementedError def denom(self, a): """Returns denominator of ``a``. """ raise NotImplementedError def half_gcdex(self, a, b): """Half extended GCD of ``a`` and ``b``. """ s, t, h = self.gcdex(a, b) return s, h def gcdex(self, a, b): """Extended GCD of ``a`` and ``b``. """ raise NotImplementedError def cofactors(self, a, b): """Returns GCD and cofactors of ``a`` and ``b``. """ gcd = self.gcd(a, b) cfa = self.quo(a, gcd) cfb = self.quo(b, gcd) return gcd, cfa, cfb def gcd(self, a, b): """Returns GCD of ``a`` and ``b``. """ raise NotImplementedError def lcm(self, a, b): """Returns LCM of ``a`` and ``b``. """ raise NotImplementedError def log(self, a, b): """Returns b-base logarithm of ``a``. """ raise NotImplementedError def sqrt(self, a): """Returns square root of ``a``. """ raise NotImplementedError def evalf(self, a, prec=None, **options): """Returns numerical approximation of ``a``. """ return self.to_sympy(a).evalf(prec, **options) n = evalf def real(self, a): return a def imag(self, a): return self.zero def almosteq(self, a, b, tolerance=None): """Check if ``a`` and ``b`` are almost equal. """ return a == b def characteristic(self): """Return the characteristic of this domain. """ raise NotImplementedError('characteristic()') __all__ = ['Domain']
f61a8768268eb11f5720ab910b22bf7f75796a1def89e3fa5b105cba047279d9
"""Test sparse polynomials. """ from operator import add, mul from sympy.polys.rings import ring, xring, sring, PolyRing, PolyElement from sympy.polys.fields import field, FracField from sympy.polys.domains import ZZ, QQ, RR, FF, EX from sympy.polys.orderings import lex, grlex from sympy.polys.polyerrors import GeneratorsError, \ ExactQuotientFailed, MultivariatePolynomialError, CoercionFailed from sympy.testing.pytest import raises from sympy.core import Symbol, symbols from sympy.core.compatibility import reduce from sympy import sqrt, pi, oo def test_PolyRing___init__(): x, y, z, t = map(Symbol, "xyzt") assert len(PolyRing("x,y,z", ZZ, lex).gens) == 3 assert len(PolyRing(x, ZZ, lex).gens) == 1 assert len(PolyRing(("x", "y", "z"), ZZ, lex).gens) == 3 assert len(PolyRing((x, y, z), ZZ, lex).gens) == 3 assert len(PolyRing("", ZZ, lex).gens) == 0 assert len(PolyRing([], ZZ, lex).gens) == 0 raises(GeneratorsError, lambda: PolyRing(0, ZZ, lex)) assert PolyRing("x", ZZ[t], lex).domain == ZZ[t] assert PolyRing("x", 'ZZ[t]', lex).domain == ZZ[t] assert PolyRing("x", PolyRing("t", ZZ, lex), lex).domain == ZZ[t] raises(GeneratorsError, lambda: PolyRing("x", PolyRing("x", ZZ, lex), lex)) _lex = Symbol("lex") assert PolyRing("x", ZZ, lex).order == lex assert PolyRing("x", ZZ, _lex).order == lex assert PolyRing("x", ZZ, 'lex').order == lex R1 = PolyRing("x,y", ZZ, lex) R2 = PolyRing("x,y", ZZ, lex) R3 = PolyRing("x,y,z", ZZ, lex) assert R1.x == R1.gens[0] assert R1.y == R1.gens[1] assert R1.x == R2.x assert R1.y == R2.y assert R1.x != R3.x assert R1.y != R3.y def test_PolyRing___hash__(): R, x, y, z = ring("x,y,z", QQ) assert hash(R) def test_PolyRing___eq__(): assert ring("x,y,z", QQ)[0] == ring("x,y,z", QQ)[0] assert ring("x,y,z", QQ)[0] is ring("x,y,z", QQ)[0] assert ring("x,y,z", QQ)[0] != ring("x,y,z", ZZ)[0] assert ring("x,y,z", QQ)[0] is not ring("x,y,z", ZZ)[0] assert ring("x,y,z", ZZ)[0] != ring("x,y,z", QQ)[0] assert ring("x,y,z", ZZ)[0] is not ring("x,y,z", QQ)[0] assert ring("x,y,z", QQ)[0] != ring("x,y", QQ)[0] assert ring("x,y,z", QQ)[0] is not ring("x,y", QQ)[0] assert ring("x,y", QQ)[0] != ring("x,y,z", QQ)[0] assert ring("x,y", QQ)[0] is not ring("x,y,z", QQ)[0] def test_PolyRing_ring_new(): R, x, y, z = ring("x,y,z", QQ) assert R.ring_new(7) == R(7) assert R.ring_new(7*x*y*z) == 7*x*y*z f = x**2 + 2*x*y + 3*x + 4*z**2 + 5*z + 6 assert R.ring_new([[[1]], [[2], [3]], [[4, 5, 6]]]) == f assert R.ring_new({(2, 0, 0): 1, (1, 1, 0): 2, (1, 0, 0): 3, (0, 0, 2): 4, (0, 0, 1): 5, (0, 0, 0): 6}) == f assert R.ring_new([((2, 0, 0), 1), ((1, 1, 0), 2), ((1, 0, 0), 3), ((0, 0, 2), 4), ((0, 0, 1), 5), ((0, 0, 0), 6)]) == f R, = ring("", QQ) assert R.ring_new([((), 7)]) == R(7) def test_PolyRing_drop(): R, x,y,z = ring("x,y,z", ZZ) assert R.drop(x) == PolyRing("y,z", ZZ, lex) assert R.drop(y) == PolyRing("x,z", ZZ, lex) assert R.drop(z) == PolyRing("x,y", ZZ, lex) assert R.drop(0) == PolyRing("y,z", ZZ, lex) assert R.drop(0).drop(0) == PolyRing("z", ZZ, lex) assert R.drop(0).drop(0).drop(0) == ZZ assert R.drop(1) == PolyRing("x,z", ZZ, lex) assert R.drop(2) == PolyRing("x,y", ZZ, lex) assert R.drop(2).drop(1) == PolyRing("x", ZZ, lex) assert R.drop(2).drop(1).drop(0) == ZZ raises(ValueError, lambda: R.drop(3)) raises(ValueError, lambda: R.drop(x).drop(y)) def test_PolyRing___getitem__(): R, x,y,z = ring("x,y,z", ZZ) assert R[0:] == PolyRing("x,y,z", ZZ, lex) assert R[1:] == PolyRing("y,z", ZZ, lex) assert R[2:] == PolyRing("z", ZZ, lex) assert R[3:] == ZZ def test_PolyRing_is_(): R = PolyRing("x", QQ, lex) assert R.is_univariate is True assert R.is_multivariate is False R = PolyRing("x,y,z", QQ, lex) assert R.is_univariate is False assert R.is_multivariate is True R = PolyRing("", QQ, lex) assert R.is_univariate is False assert R.is_multivariate is False def test_PolyRing_add(): R, x = ring("x", ZZ) F = [ x**2 + 2*i + 3 for i in range(4) ] assert R.add(F) == reduce(add, F) == 4*x**2 + 24 R, = ring("", ZZ) assert R.add([2, 5, 7]) == 14 def test_PolyRing_mul(): R, x = ring("x", ZZ) F = [ x**2 + 2*i + 3 for i in range(4) ] assert R.mul(F) == reduce(mul, F) == x**8 + 24*x**6 + 206*x**4 + 744*x**2 + 945 R, = ring("", ZZ) assert R.mul([2, 3, 5]) == 30 def test_sring(): x, y, z, t = symbols("x,y,z,t") R = PolyRing("x,y,z", ZZ, lex) assert sring(x + 2*y + 3*z) == (R, R.x + 2*R.y + 3*R.z) R = PolyRing("x,y,z", QQ, lex) assert sring(x + 2*y + z/3) == (R, R.x + 2*R.y + R.z/3) assert sring([x, 2*y, z/3]) == (R, [R.x, 2*R.y, R.z/3]) Rt = PolyRing("t", ZZ, lex) R = PolyRing("x,y,z", Rt, lex) assert sring(x + 2*t*y + 3*t**2*z, x, y, z) == (R, R.x + 2*Rt.t*R.y + 3*Rt.t**2*R.z) Rt = PolyRing("t", QQ, lex) R = PolyRing("x,y,z", Rt, lex) assert sring(x + t*y/2 + t**2*z/3, x, y, z) == (R, R.x + Rt.t*R.y/2 + Rt.t**2*R.z/3) Rt = FracField("t", ZZ, lex) R = PolyRing("x,y,z", Rt, lex) assert sring(x + 2*y/t + t**2*z/3, x, y, z) == (R, R.x + 2*R.y/Rt.t + Rt.t**2*R.z/3) r = sqrt(2) - sqrt(3) R, a = sring(r, extension=True) assert R.domain == QQ.algebraic_field(r) assert R.gens == () assert a == R.domain.from_sympy(r) def test_PolyElement___hash__(): R, x, y, z = ring("x,y,z", QQ) assert hash(x*y*z) def test_PolyElement___eq__(): R, x, y = ring("x,y", ZZ, lex) assert ((x*y + 5*x*y) == 6) == False assert ((x*y + 5*x*y) == 6*x*y) == True assert (6 == (x*y + 5*x*y)) == False assert (6*x*y == (x*y + 5*x*y)) == True assert ((x*y - x*y) == 0) == True assert (0 == (x*y - x*y)) == True assert ((x*y - x*y) == 1) == False assert (1 == (x*y - x*y)) == False assert ((x*y - x*y) == 1) == False assert (1 == (x*y - x*y)) == False assert ((x*y + 5*x*y) != 6) == True assert ((x*y + 5*x*y) != 6*x*y) == False assert (6 != (x*y + 5*x*y)) == True assert (6*x*y != (x*y + 5*x*y)) == False assert ((x*y - x*y) != 0) == False assert (0 != (x*y - x*y)) == False assert ((x*y - x*y) != 1) == True assert (1 != (x*y - x*y)) == True assert R.one == QQ(1, 1) == R.one assert R.one == 1 == R.one Rt, t = ring("t", ZZ) R, x, y = ring("x,y", Rt) assert (t**3*x/x == t**3) == True assert (t**3*x/x == t**4) == False def test_PolyElement__lt_le_gt_ge__(): R, x, y = ring("x,y", ZZ) assert R(1) < x < x**2 < x**3 assert R(1) <= x <= x**2 <= x**3 assert x**3 > x**2 > x > R(1) assert x**3 >= x**2 >= x >= R(1) def test_PolyElement_copy(): R, x, y, z = ring("x,y,z", ZZ) f = x*y + 3*z g = f.copy() assert f == g g[(1, 1, 1)] = 7 assert f != g def test_PolyElement_as_expr(): R, x, y, z = ring("x,y,z", ZZ) f = 3*x**2*y - x*y*z + 7*z**3 + 1 X, Y, Z = R.symbols g = 3*X**2*Y - X*Y*Z + 7*Z**3 + 1 assert f != g assert f.as_expr() == g X, Y, Z = symbols("x,y,z") g = 3*X**2*Y - X*Y*Z + 7*Z**3 + 1 assert f != g assert f.as_expr(X, Y, Z) == g raises(ValueError, lambda: f.as_expr(X)) R, = ring("", ZZ) R(3).as_expr() == 3 def test_PolyElement_from_expr(): x, y, z = symbols("x,y,z") R, X, Y, Z = ring((x, y, z), ZZ) f = R.from_expr(1) assert f == 1 and isinstance(f, R.dtype) f = R.from_expr(x) assert f == X and isinstance(f, R.dtype) f = R.from_expr(x*y*z) assert f == X*Y*Z and isinstance(f, R.dtype) f = R.from_expr(x*y*z + x*y + x) assert f == X*Y*Z + X*Y + X and isinstance(f, R.dtype) f = R.from_expr(x**3*y*z + x**2*y**7 + 1) assert f == X**3*Y*Z + X**2*Y**7 + 1 and isinstance(f, R.dtype) raises(ValueError, lambda: R.from_expr(1/x)) raises(ValueError, lambda: R.from_expr(2**x)) raises(ValueError, lambda: R.from_expr(7*x + sqrt(2))) R, = ring("", ZZ) f = R.from_expr(1) assert f == 1 and isinstance(f, R.dtype) def test_PolyElement_degree(): R, x,y,z = ring("x,y,z", ZZ) assert R(0).degree() is -oo assert R(1).degree() == 0 assert (x + 1).degree() == 1 assert (2*y**3 + z).degree() == 0 assert (x*y**3 + z).degree() == 1 assert (x**5*y**3 + z).degree() == 5 assert R(0).degree(x) is -oo assert R(1).degree(x) == 0 assert (x + 1).degree(x) == 1 assert (2*y**3 + z).degree(x) == 0 assert (x*y**3 + z).degree(x) == 1 assert (7*x**5*y**3 + z).degree(x) == 5 assert R(0).degree(y) is -oo assert R(1).degree(y) == 0 assert (x + 1).degree(y) == 0 assert (2*y**3 + z).degree(y) == 3 assert (x*y**3 + z).degree(y) == 3 assert (7*x**5*y**3 + z).degree(y) == 3 assert R(0).degree(z) is -oo assert R(1).degree(z) == 0 assert (x + 1).degree(z) == 0 assert (2*y**3 + z).degree(z) == 1 assert (x*y**3 + z).degree(z) == 1 assert (7*x**5*y**3 + z).degree(z) == 1 R, = ring("", ZZ) assert R(0).degree() is -oo assert R(1).degree() == 0 def test_PolyElement_tail_degree(): R, x,y,z = ring("x,y,z", ZZ) assert R(0).tail_degree() is -oo assert R(1).tail_degree() == 0 assert (x + 1).tail_degree() == 0 assert (2*y**3 + x**3*z).tail_degree() == 0 assert (x*y**3 + x**3*z).tail_degree() == 1 assert (x**5*y**3 + x**3*z).tail_degree() == 3 assert R(0).tail_degree(x) is -oo assert R(1).tail_degree(x) == 0 assert (x + 1).tail_degree(x) == 0 assert (2*y**3 + x**3*z).tail_degree(x) == 0 assert (x*y**3 + x**3*z).tail_degree(x) == 1 assert (7*x**5*y**3 + x**3*z).tail_degree(x) == 3 assert R(0).tail_degree(y) is -oo assert R(1).tail_degree(y) == 0 assert (x + 1).tail_degree(y) == 0 assert (2*y**3 + x**3*z).tail_degree(y) == 0 assert (x*y**3 + x**3*z).tail_degree(y) == 0 assert (7*x**5*y**3 + x**3*z).tail_degree(y) == 0 assert R(0).tail_degree(z) is -oo assert R(1).tail_degree(z) == 0 assert (x + 1).tail_degree(z) == 0 assert (2*y**3 + x**3*z).tail_degree(z) == 0 assert (x*y**3 + x**3*z).tail_degree(z) == 0 assert (7*x**5*y**3 + x**3*z).tail_degree(z) == 0 R, = ring("", ZZ) assert R(0).tail_degree() is -oo assert R(1).tail_degree() == 0 def test_PolyElement_degrees(): R, x,y,z = ring("x,y,z", ZZ) assert R(0).degrees() == (-oo, -oo, -oo) assert R(1).degrees() == (0, 0, 0) assert (x**2*y + x**3*z**2).degrees() == (3, 1, 2) def test_PolyElement_tail_degrees(): R, x,y,z = ring("x,y,z", ZZ) assert R(0).tail_degrees() == (-oo, -oo, -oo) assert R(1).tail_degrees() == (0, 0, 0) assert (x**2*y + x**3*z**2).tail_degrees() == (2, 0, 0) def test_PolyElement_coeff(): R, x, y, z = ring("x,y,z", ZZ, lex) f = 3*x**2*y - x*y*z + 7*z**3 + 23 assert f.coeff(1) == 23 raises(ValueError, lambda: f.coeff(3)) assert f.coeff(x) == 0 assert f.coeff(y) == 0 assert f.coeff(z) == 0 assert f.coeff(x**2*y) == 3 assert f.coeff(x*y*z) == -1 assert f.coeff(z**3) == 7 raises(ValueError, lambda: f.coeff(3*x**2*y)) raises(ValueError, lambda: f.coeff(-x*y*z)) raises(ValueError, lambda: f.coeff(7*z**3)) R, = ring("", ZZ) R(3).coeff(1) == 3 def test_PolyElement_LC(): R, x, y = ring("x,y", QQ, lex) assert R(0).LC == QQ(0) assert (QQ(1,2)*x).LC == QQ(1, 2) assert (QQ(1,4)*x*y + QQ(1,2)*x).LC == QQ(1, 4) def test_PolyElement_LM(): R, x, y = ring("x,y", QQ, lex) assert R(0).LM == (0, 0) assert (QQ(1,2)*x).LM == (1, 0) assert (QQ(1,4)*x*y + QQ(1,2)*x).LM == (1, 1) def test_PolyElement_LT(): R, x, y = ring("x,y", QQ, lex) assert R(0).LT == ((0, 0), QQ(0)) assert (QQ(1,2)*x).LT == ((1, 0), QQ(1, 2)) assert (QQ(1,4)*x*y + QQ(1,2)*x).LT == ((1, 1), QQ(1, 4)) R, = ring("", ZZ) assert R(0).LT == ((), 0) assert R(1).LT == ((), 1) def test_PolyElement_leading_monom(): R, x, y = ring("x,y", QQ, lex) assert R(0).leading_monom() == 0 assert (QQ(1,2)*x).leading_monom() == x assert (QQ(1,4)*x*y + QQ(1,2)*x).leading_monom() == x*y def test_PolyElement_leading_term(): R, x, y = ring("x,y", QQ, lex) assert R(0).leading_term() == 0 assert (QQ(1,2)*x).leading_term() == QQ(1,2)*x assert (QQ(1,4)*x*y + QQ(1,2)*x).leading_term() == QQ(1,4)*x*y def test_PolyElement_terms(): R, x,y,z = ring("x,y,z", QQ) terms = (x**2/3 + y**3/4 + z**4/5).terms() assert terms == [((2,0,0), QQ(1,3)), ((0,3,0), QQ(1,4)), ((0,0,4), QQ(1,5))] R, x,y = ring("x,y", ZZ, lex) f = x*y**7 + 2*x**2*y**3 assert f.terms() == f.terms(lex) == f.terms('lex') == [((2, 3), 2), ((1, 7), 1)] assert f.terms(grlex) == f.terms('grlex') == [((1, 7), 1), ((2, 3), 2)] R, x,y = ring("x,y", ZZ, grlex) f = x*y**7 + 2*x**2*y**3 assert f.terms() == f.terms(grlex) == f.terms('grlex') == [((1, 7), 1), ((2, 3), 2)] assert f.terms(lex) == f.terms('lex') == [((2, 3), 2), ((1, 7), 1)] R, = ring("", ZZ) assert R(3).terms() == [((), 3)] def test_PolyElement_monoms(): R, x,y,z = ring("x,y,z", QQ) monoms = (x**2/3 + y**3/4 + z**4/5).monoms() assert monoms == [(2,0,0), (0,3,0), (0,0,4)] R, x,y = ring("x,y", ZZ, lex) f = x*y**7 + 2*x**2*y**3 assert f.monoms() == f.monoms(lex) == f.monoms('lex') == [(2, 3), (1, 7)] assert f.monoms(grlex) == f.monoms('grlex') == [(1, 7), (2, 3)] R, x,y = ring("x,y", ZZ, grlex) f = x*y**7 + 2*x**2*y**3 assert f.monoms() == f.monoms(grlex) == f.monoms('grlex') == [(1, 7), (2, 3)] assert f.monoms(lex) == f.monoms('lex') == [(2, 3), (1, 7)] def test_PolyElement_coeffs(): R, x,y,z = ring("x,y,z", QQ) coeffs = (x**2/3 + y**3/4 + z**4/5).coeffs() assert coeffs == [QQ(1,3), QQ(1,4), QQ(1,5)] R, x,y = ring("x,y", ZZ, lex) f = x*y**7 + 2*x**2*y**3 assert f.coeffs() == f.coeffs(lex) == f.coeffs('lex') == [2, 1] assert f.coeffs(grlex) == f.coeffs('grlex') == [1, 2] R, x,y = ring("x,y", ZZ, grlex) f = x*y**7 + 2*x**2*y**3 assert f.coeffs() == f.coeffs(grlex) == f.coeffs('grlex') == [1, 2] assert f.coeffs(lex) == f.coeffs('lex') == [2, 1] def test_PolyElement___add__(): Rt, t = ring("t", ZZ) Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) assert dict(x + 3*y) == {(1, 0, 0): 1, (0, 1, 0): 3} assert dict(u + x) == dict(x + u) == {(1, 0, 0): 1, (0, 0, 0): u} assert dict(u + x*y) == dict(x*y + u) == {(1, 1, 0): 1, (0, 0, 0): u} assert dict(u + x*y + z) == dict(x*y + z + u) == {(1, 1, 0): 1, (0, 0, 1): 1, (0, 0, 0): u} assert dict(u*x + x) == dict(x + u*x) == {(1, 0, 0): u + 1} assert dict(u*x + x*y) == dict(x*y + u*x) == {(1, 1, 0): 1, (1, 0, 0): u} assert dict(u*x + x*y + z) == dict(x*y + z + u*x) == {(1, 1, 0): 1, (0, 0, 1): 1, (1, 0, 0): u} raises(TypeError, lambda: t + x) raises(TypeError, lambda: x + t) raises(TypeError, lambda: t + u) raises(TypeError, lambda: u + t) Fuv, u,v = field("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Fuv) assert dict(u + x) == dict(x + u) == {(1, 0, 0): 1, (0, 0, 0): u} Rxyz, x,y,z = ring("x,y,z", EX) assert dict(EX(pi) + x*y*z) == dict(x*y*z + EX(pi)) == {(1, 1, 1): EX(1), (0, 0, 0): EX(pi)} def test_PolyElement___sub__(): Rt, t = ring("t", ZZ) Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) assert dict(x - 3*y) == {(1, 0, 0): 1, (0, 1, 0): -3} assert dict(-u + x) == dict(x - u) == {(1, 0, 0): 1, (0, 0, 0): -u} assert dict(-u + x*y) == dict(x*y - u) == {(1, 1, 0): 1, (0, 0, 0): -u} assert dict(-u + x*y + z) == dict(x*y + z - u) == {(1, 1, 0): 1, (0, 0, 1): 1, (0, 0, 0): -u} assert dict(-u*x + x) == dict(x - u*x) == {(1, 0, 0): -u + 1} assert dict(-u*x + x*y) == dict(x*y - u*x) == {(1, 1, 0): 1, (1, 0, 0): -u} assert dict(-u*x + x*y + z) == dict(x*y + z - u*x) == {(1, 1, 0): 1, (0, 0, 1): 1, (1, 0, 0): -u} raises(TypeError, lambda: t - x) raises(TypeError, lambda: x - t) raises(TypeError, lambda: t - u) raises(TypeError, lambda: u - t) Fuv, u,v = field("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Fuv) assert dict(-u + x) == dict(x - u) == {(1, 0, 0): 1, (0, 0, 0): -u} Rxyz, x,y,z = ring("x,y,z", EX) assert dict(-EX(pi) + x*y*z) == dict(x*y*z - EX(pi)) == {(1, 1, 1): EX(1), (0, 0, 0): -EX(pi)} def test_PolyElement___mul__(): Rt, t = ring("t", ZZ) Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) assert dict(u*x) == dict(x*u) == {(1, 0, 0): u} assert dict(2*u*x + z) == dict(x*2*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1} assert dict(u*2*x + z) == dict(2*x*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1} assert dict(2*u*x + z) == dict(x*2*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1} assert dict(u*x*2 + z) == dict(x*u*2 + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1} assert dict(2*u*x*y + z) == dict(x*y*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(u*2*x*y + z) == dict(2*x*y*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(2*u*x*y + z) == dict(x*y*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(u*x*y*2 + z) == dict(x*y*u*2 + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(2*u*y*x + z) == dict(y*x*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(u*2*y*x + z) == dict(2*y*x*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(2*u*y*x + z) == dict(y*x*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(u*y*x*2 + z) == dict(y*x*u*2 + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(3*u*(x + y) + z) == dict((x + y)*3*u + z) == {(1, 0, 0): 3*u, (0, 1, 0): 3*u, (0, 0, 1): 1} raises(TypeError, lambda: t*x + z) raises(TypeError, lambda: x*t + z) raises(TypeError, lambda: t*u + z) raises(TypeError, lambda: u*t + z) Fuv, u,v = field("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Fuv) assert dict(u*x) == dict(x*u) == {(1, 0, 0): u} Rxyz, x,y,z = ring("x,y,z", EX) assert dict(EX(pi)*x*y*z) == dict(x*y*z*EX(pi)) == {(1, 1, 1): EX(pi)} def test_PolyElement___truediv__(): R, x,y,z = ring("x,y,z", ZZ) assert (2*x**2 - 4)/2 == x**2 - 2 assert (2*x**2 - 3)/2 == x**2 assert (x**2 - 1).quo(x) == x assert (x**2 - x).quo(x) == x - 1 assert (x**2 - 1)/x == x - x**(-1) assert (x**2 - x)/x == x - 1 assert (x**2 - 1)/(2*x) == x/2 - x**(-1)/2 assert (x**2 - 1).quo(2*x) == 0 assert (x**2 - x)/(x - 1) == (x**2 - x).quo(x - 1) == x R, x,y,z = ring("x,y,z", ZZ) assert len((x**2/3 + y**3/4 + z**4/5).terms()) == 0 R, x,y,z = ring("x,y,z", QQ) assert len((x**2/3 + y**3/4 + z**4/5).terms()) == 3 Rt, t = ring("t", ZZ) Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) assert dict((u**2*x + u)/u) == {(1, 0, 0): u, (0, 0, 0): 1} raises(TypeError, lambda: u/(u**2*x + u)) raises(TypeError, lambda: t/x) raises(TypeError, lambda: x/t) raises(TypeError, lambda: t/u) raises(TypeError, lambda: u/t) R, x = ring("x", ZZ) f, g = x**2 + 2*x + 3, R(0) raises(ZeroDivisionError, lambda: f.div(g)) raises(ZeroDivisionError, lambda: divmod(f, g)) raises(ZeroDivisionError, lambda: f.rem(g)) raises(ZeroDivisionError, lambda: f % g) raises(ZeroDivisionError, lambda: f.quo(g)) raises(ZeroDivisionError, lambda: f / g) raises(ZeroDivisionError, lambda: f.exquo(g)) R, x, y = ring("x,y", ZZ) f, g = x*y + 2*x + 3, R(0) raises(ZeroDivisionError, lambda: f.div(g)) raises(ZeroDivisionError, lambda: divmod(f, g)) raises(ZeroDivisionError, lambda: f.rem(g)) raises(ZeroDivisionError, lambda: f % g) raises(ZeroDivisionError, lambda: f.quo(g)) raises(ZeroDivisionError, lambda: f / g) raises(ZeroDivisionError, lambda: f.exquo(g)) R, x = ring("x", ZZ) f, g = x**2 + 1, 2*x - 4 q, r = R(0), x**2 + 1 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = 3*x**3 + x**2 + x + 5, 5*x**2 - 3*x + 1 q, r = R(0), f assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = 5*x**4 + 4*x**3 + 3*x**2 + 2*x + 1, x**2 + 2*x + 3 q, r = 5*x**2 - 6*x, 20*x + 1 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = 5*x**5 + 4*x**4 + 3*x**3 + 2*x**2 + x, x**4 + 2*x**3 + 9 q, r = 5*x - 6, 15*x**3 + 2*x**2 - 44*x + 54 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) R, x = ring("x", QQ) f, g = x**2 + 1, 2*x - 4 q, r = x/2 + 1, R(5) assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = 3*x**3 + x**2 + x + 5, 5*x**2 - 3*x + 1 q, r = QQ(3, 5)*x + QQ(14, 25), QQ(52, 25)*x + QQ(111, 25) assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) R, x,y = ring("x,y", ZZ) f, g = x**2 - y**2, x - y q, r = x + y, R(0) assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q assert f.exquo(g) == q f, g = x**2 + y**2, x - y q, r = x + y, 2*y**2 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = x**2 + y**2, -x + y q, r = -x - y, 2*y**2 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = x**2 + y**2, 2*x - 2*y q, r = R(0), f assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) R, x,y = ring("x,y", QQ) f, g = x**2 - y**2, x - y q, r = x + y, R(0) assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q assert f.exquo(g) == q f, g = x**2 + y**2, x - y q, r = x + y, 2*y**2 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = x**2 + y**2, -x + y q, r = -x - y, 2*y**2 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = x**2 + y**2, 2*x - 2*y q, r = x/2 + y/2, 2*y**2 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) def test_PolyElement___pow__(): R, x = ring("x", ZZ, grlex) f = 2*x + 3 assert f**0 == 1 assert f**1 == f raises(ValueError, lambda: f**(-1)) assert x**(-1) == x**(-1) assert f**2 == f._pow_generic(2) == f._pow_multinomial(2) == 4*x**2 + 12*x + 9 assert f**3 == f._pow_generic(3) == f._pow_multinomial(3) == 8*x**3 + 36*x**2 + 54*x + 27 assert f**4 == f._pow_generic(4) == f._pow_multinomial(4) == 16*x**4 + 96*x**3 + 216*x**2 + 216*x + 81 assert f**5 == f._pow_generic(5) == f._pow_multinomial(5) == 32*x**5 + 240*x**4 + 720*x**3 + 1080*x**2 + 810*x + 243 R, x,y,z = ring("x,y,z", ZZ, grlex) f = x**3*y - 2*x*y**2 - 3*z + 1 g = x**6*y**2 - 4*x**4*y**3 - 6*x**3*y*z + 2*x**3*y + 4*x**2*y**4 + 12*x*y**2*z - 4*x*y**2 + 9*z**2 - 6*z + 1 assert f**2 == f._pow_generic(2) == f._pow_multinomial(2) == g R, t = ring("t", ZZ) f = -11200*t**4 - 2604*t**2 + 49 g = 15735193600000000*t**16 + 14633730048000000*t**14 + 4828147466240000*t**12 \ + 598976863027200*t**10 + 3130812416256*t**8 - 2620523775744*t**6 \ + 92413760096*t**4 - 1225431984*t**2 + 5764801 assert f**4 == f._pow_generic(4) == f._pow_multinomial(4) == g def test_PolyElement_div(): R, x = ring("x", ZZ, grlex) f = x**3 - 12*x**2 - 42 g = x - 3 q = x**2 - 9*x - 27 r = -123 assert f.div([g]) == ([q], r) R, x = ring("x", ZZ, grlex) f = x**2 + 2*x + 2 assert f.div([R(1)]) == ([f], 0) R, x = ring("x", QQ, grlex) f = x**2 + 2*x + 2 assert f.div([R(2)]) == ([QQ(1,2)*x**2 + x + 1], 0) R, x,y = ring("x,y", ZZ, grlex) f = 4*x**2*y - 2*x*y + 4*x - 2*y + 8 assert f.div([R(2)]) == ([2*x**2*y - x*y + 2*x - y + 4], 0) assert f.div([2*y]) == ([2*x**2 - x - 1], 4*x + 8) f = x - 1 g = y - 1 assert f.div([g]) == ([0], f) f = x*y**2 + 1 G = [x*y + 1, y + 1] Q = [y, -1] r = 2 assert f.div(G) == (Q, r) f = x**2*y + x*y**2 + y**2 G = [x*y - 1, y**2 - 1] Q = [x + y, 1] r = x + y + 1 assert f.div(G) == (Q, r) G = [y**2 - 1, x*y - 1] Q = [x + 1, x] r = 2*x + 1 assert f.div(G) == (Q, r) R, = ring("", ZZ) assert R(3).div(R(2)) == (0, 3) R, = ring("", QQ) assert R(3).div(R(2)) == (QQ(3, 2), 0) def test_PolyElement_rem(): R, x = ring("x", ZZ, grlex) f = x**3 - 12*x**2 - 42 g = x - 3 r = -123 assert f.rem([g]) == f.div([g])[1] == r R, x,y = ring("x,y", ZZ, grlex) f = 4*x**2*y - 2*x*y + 4*x - 2*y + 8 assert f.rem([R(2)]) == f.div([R(2)])[1] == 0 assert f.rem([2*y]) == f.div([2*y])[1] == 4*x + 8 f = x - 1 g = y - 1 assert f.rem([g]) == f.div([g])[1] == f f = x*y**2 + 1 G = [x*y + 1, y + 1] r = 2 assert f.rem(G) == f.div(G)[1] == r f = x**2*y + x*y**2 + y**2 G = [x*y - 1, y**2 - 1] r = x + y + 1 assert f.rem(G) == f.div(G)[1] == r G = [y**2 - 1, x*y - 1] r = 2*x + 1 assert f.rem(G) == f.div(G)[1] == r def test_PolyElement_deflate(): R, x = ring("x", ZZ) assert (2*x**2).deflate(x**4 + 4*x**2 + 1) == ((2,), [2*x, x**2 + 4*x + 1]) R, x,y = ring("x,y", ZZ) assert R(0).deflate(R(0)) == ((1, 1), [0, 0]) assert R(1).deflate(R(0)) == ((1, 1), [1, 0]) assert R(1).deflate(R(2)) == ((1, 1), [1, 2]) assert R(1).deflate(2*y) == ((1, 1), [1, 2*y]) assert (2*y).deflate(2*y) == ((1, 1), [2*y, 2*y]) assert R(2).deflate(2*y**2) == ((1, 2), [2, 2*y]) assert (2*y**2).deflate(2*y**2) == ((1, 2), [2*y, 2*y]) f = x**4*y**2 + x**2*y + 1 g = x**2*y**3 + x**2*y + 1 assert f.deflate(g) == ((2, 1), [x**2*y**2 + x*y + 1, x*y**3 + x*y + 1]) def test_PolyElement_clear_denoms(): R, x,y = ring("x,y", QQ) assert R(1).clear_denoms() == (ZZ(1), 1) assert R(7).clear_denoms() == (ZZ(1), 7) assert R(QQ(7,3)).clear_denoms() == (3, 7) assert R(QQ(7,3)).clear_denoms() == (3, 7) assert (3*x**2 + x).clear_denoms() == (1, 3*x**2 + x) assert (x**2 + QQ(1,2)*x).clear_denoms() == (2, 2*x**2 + x) rQQ, x,t = ring("x,t", QQ, lex) rZZ, X,T = ring("x,t", ZZ, lex) F = [x - QQ(17824537287975195925064602467992950991718052713078834557692023531499318507213727406844943097,413954288007559433755329699713866804710749652268151059918115348815925474842910720000)*t**7 - QQ(4882321164854282623427463828745855894130208215961904469205260756604820743234704900167747753,12936071500236232304854053116058337647210926633379720622441104650497671088840960000)*t**6 - QQ(36398103304520066098365558157422127347455927422509913596393052633155821154626830576085097433,25872143000472464609708106232116675294421853266759441244882209300995342177681920000)*t**5 - QQ(168108082231614049052707339295479262031324376786405372698857619250210703675982492356828810819,58212321751063045371843239022262519412449169850208742800984970927239519899784320000)*t**4 - QQ(5694176899498574510667890423110567593477487855183144378347226247962949388653159751849449037,1617008937529529038106756639507292205901365829172465077805138081312208886105120000)*t**3 - QQ(154482622347268833757819824809033388503591365487934245386958884099214649755244381307907779,60637835157357338929003373981523457721301218593967440417692678049207833228942000)*t**2 - QQ(2452813096069528207645703151222478123259511586701148682951852876484544822947007791153163,2425513406294293557160134959260938308852048743758697616707707121968313329157680)*t - QQ(34305265428126440542854669008203683099323146152358231964773310260498715579162112959703,202126117191191129763344579938411525737670728646558134725642260164026110763140), t**8 + QQ(693749860237914515552,67859264524169150569)*t**7 + QQ(27761407182086143225024,610733380717522355121)*t**6 + QQ(7785127652157884044288,67859264524169150569)*t**5 + QQ(36567075214771261409792,203577793572507451707)*t**4 + QQ(36336335165196147384320,203577793572507451707)*t**3 + QQ(7452455676042754048000,67859264524169150569)*t**2 + QQ(2593331082514399232000,67859264524169150569)*t + QQ(390399197427343360000,67859264524169150569)] G = [3725588592068034903797967297424801242396746870413359539263038139343329273586196480000*X - 160420835591776763325581422211936558925462474417709511019228211783493866564923546661604487873*T**7 - 1406108495478033395547109582678806497509499966197028487131115097902188374051595011248311352864*T**6 - 5241326875850889518164640374668786338033653548841427557880599579174438246266263602956254030352*T**5 - 10758917262823299139373269714910672770004760114329943852726887632013485035262879510837043892416*T**4 - 13119383576444715672578819534846747735372132018341964647712009275306635391456880068261130581248*T**3 - 9491412317016197146080450036267011389660653495578680036574753839055748080962214787557853941760*T**2 - 3767520915562795326943800040277726397326609797172964377014046018280260848046603967211258368000*T - 632314652371226552085897259159210286886724229880266931574701654721512325555116066073245696000, 610733380717522355121*T**8 + 6243748742141230639968*T**7 + 27761407182086143225024*T**6 + 70066148869420956398592*T**5 + 109701225644313784229376*T**4 + 109009005495588442152960*T**3 + 67072101084384786432000*T**2 + 23339979742629593088000*T + 3513592776846090240000] assert [ f.clear_denoms()[1].set_ring(rZZ) for f in F ] == G def test_PolyElement_cofactors(): R, x, y = ring("x,y", ZZ) f, g = R(0), R(0) assert f.cofactors(g) == (0, 0, 0) f, g = R(2), R(0) assert f.cofactors(g) == (2, 1, 0) f, g = R(-2), R(0) assert f.cofactors(g) == (2, -1, 0) f, g = R(0), R(-2) assert f.cofactors(g) == (2, 0, -1) f, g = R(0), 2*x + 4 assert f.cofactors(g) == (2*x + 4, 0, 1) f, g = 2*x + 4, R(0) assert f.cofactors(g) == (2*x + 4, 1, 0) f, g = R(2), R(2) assert f.cofactors(g) == (2, 1, 1) f, g = R(-2), R(2) assert f.cofactors(g) == (2, -1, 1) f, g = R(2), R(-2) assert f.cofactors(g) == (2, 1, -1) f, g = R(-2), R(-2) assert f.cofactors(g) == (2, -1, -1) f, g = x**2 + 2*x + 1, R(1) assert f.cofactors(g) == (1, x**2 + 2*x + 1, 1) f, g = x**2 + 2*x + 1, R(2) assert f.cofactors(g) == (1, x**2 + 2*x + 1, 2) f, g = 2*x**2 + 4*x + 2, R(2) assert f.cofactors(g) == (2, x**2 + 2*x + 1, 1) f, g = R(2), 2*x**2 + 4*x + 2 assert f.cofactors(g) == (2, 1, x**2 + 2*x + 1) f, g = 2*x**2 + 4*x + 2, x + 1 assert f.cofactors(g) == (x + 1, 2*x + 2, 1) f, g = x + 1, 2*x**2 + 4*x + 2 assert f.cofactors(g) == (x + 1, 1, 2*x + 2) R, x, y, z, t = ring("x,y,z,t", ZZ) f, g = t**2 + 2*t + 1, 2*t + 2 assert f.cofactors(g) == (t + 1, t + 1, 2) f, g = z**2*t**2 + 2*z**2*t + z**2 + z*t + z, t**2 + 2*t + 1 h, cff, cfg = t + 1, z**2*t + z**2 + z, t + 1 assert f.cofactors(g) == (h, cff, cfg) assert g.cofactors(f) == (h, cfg, cff) R, x, y = ring("x,y", QQ) f = QQ(1,2)*x**2 + x + QQ(1,2) g = QQ(1,2)*x + QQ(1,2) h = x + 1 assert f.cofactors(g) == (h, g, QQ(1,2)) assert g.cofactors(f) == (h, QQ(1,2), g) R, x, y = ring("x,y", RR) f = 2.1*x*y**2 - 2.1*x*y + 2.1*x g = 2.1*x**3 h = 1.0*x assert f.cofactors(g) == (h, f/h, g/h) assert g.cofactors(f) == (h, g/h, f/h) def test_PolyElement_gcd(): R, x, y = ring("x,y", QQ) f = QQ(1,2)*x**2 + x + QQ(1,2) g = QQ(1,2)*x + QQ(1,2) assert f.gcd(g) == x + 1 def test_PolyElement_cancel(): R, x, y = ring("x,y", ZZ) f = 2*x**3 + 4*x**2 + 2*x g = 3*x**2 + 3*x F = 2*x + 2 G = 3 assert f.cancel(g) == (F, G) assert (-f).cancel(g) == (-F, G) assert f.cancel(-g) == (-F, G) R, x, y = ring("x,y", QQ) f = QQ(1,2)*x**3 + x**2 + QQ(1,2)*x g = QQ(1,3)*x**2 + QQ(1,3)*x F = 3*x + 3 G = 2 assert f.cancel(g) == (F, G) assert (-f).cancel(g) == (-F, G) assert f.cancel(-g) == (-F, G) Fx, x = field("x", ZZ) Rt, t = ring("t", Fx) f = (-x**2 - 4)/4*t g = t**2 + (x**2 + 2)/2 assert f.cancel(g) == ((-x**2 - 4)*t, 4*t**2 + 2*x**2 + 4) def test_PolyElement_max_norm(): R, x, y = ring("x,y", ZZ) assert R(0).max_norm() == 0 assert R(1).max_norm() == 1 assert (x**3 + 4*x**2 + 2*x + 3).max_norm() == 4 def test_PolyElement_l1_norm(): R, x, y = ring("x,y", ZZ) assert R(0).l1_norm() == 0 assert R(1).l1_norm() == 1 assert (x**3 + 4*x**2 + 2*x + 3).l1_norm() == 10 def test_PolyElement_diff(): R, X = xring("x:11", QQ) f = QQ(288,5)*X[0]**8*X[1]**6*X[4]**3*X[10]**2 + 8*X[0]**2*X[2]**3*X[4]**3 +2*X[0]**2 - 2*X[1]**2 assert f.diff(X[0]) == QQ(2304,5)*X[0]**7*X[1]**6*X[4]**3*X[10]**2 + 16*X[0]*X[2]**3*X[4]**3 + 4*X[0] assert f.diff(X[4]) == QQ(864,5)*X[0]**8*X[1]**6*X[4]**2*X[10]**2 + 24*X[0]**2*X[2]**3*X[4]**2 assert f.diff(X[10]) == QQ(576,5)*X[0]**8*X[1]**6*X[4]**3*X[10] def test_PolyElement___call__(): R, x = ring("x", ZZ) f = 3*x + 1 assert f(0) == 1 assert f(1) == 4 raises(ValueError, lambda: f()) raises(ValueError, lambda: f(0, 1)) raises(CoercionFailed, lambda: f(QQ(1,7))) R, x,y = ring("x,y", ZZ) f = 3*x + y**2 + 1 assert f(0, 0) == 1 assert f(1, 7) == 53 Ry = R.drop(x) assert f(0) == Ry.y**2 + 1 assert f(1) == Ry.y**2 + 4 raises(ValueError, lambda: f()) raises(ValueError, lambda: f(0, 1, 2)) raises(CoercionFailed, lambda: f(1, QQ(1,7))) raises(CoercionFailed, lambda: f(QQ(1,7), 1)) raises(CoercionFailed, lambda: f(QQ(1,7), QQ(1,7))) def test_PolyElement_evaluate(): R, x = ring("x", ZZ) f = x**3 + 4*x**2 + 2*x + 3 r = f.evaluate(x, 0) assert r == 3 and not isinstance(r, PolyElement) raises(CoercionFailed, lambda: f.evaluate(x, QQ(1,7))) R, x, y, z = ring("x,y,z", ZZ) f = (x*y)**3 + 4*(x*y)**2 + 2*x*y + 3 r = f.evaluate(x, 0) assert r == 3 and isinstance(r, R.drop(x).dtype) r = f.evaluate([(x, 0), (y, 0)]) assert r == 3 and isinstance(r, R.drop(x, y).dtype) r = f.evaluate(y, 0) assert r == 3 and isinstance(r, R.drop(y).dtype) r = f.evaluate([(y, 0), (x, 0)]) assert r == 3 and isinstance(r, R.drop(y, x).dtype) r = f.evaluate([(x, 0), (y, 0), (z, 0)]) assert r == 3 and not isinstance(r, PolyElement) raises(CoercionFailed, lambda: f.evaluate([(x, 1), (y, QQ(1,7))])) raises(CoercionFailed, lambda: f.evaluate([(x, QQ(1,7)), (y, 1)])) raises(CoercionFailed, lambda: f.evaluate([(x, QQ(1,7)), (y, QQ(1,7))])) def test_PolyElement_subs(): R, x = ring("x", ZZ) f = x**3 + 4*x**2 + 2*x + 3 r = f.subs(x, 0) assert r == 3 and isinstance(r, R.dtype) raises(CoercionFailed, lambda: f.subs(x, QQ(1,7))) R, x, y, z = ring("x,y,z", ZZ) f = x**3 + 4*x**2 + 2*x + 3 r = f.subs(x, 0) assert r == 3 and isinstance(r, R.dtype) r = f.subs([(x, 0), (y, 0)]) assert r == 3 and isinstance(r, R.dtype) raises(CoercionFailed, lambda: f.subs([(x, 1), (y, QQ(1,7))])) raises(CoercionFailed, lambda: f.subs([(x, QQ(1,7)), (y, 1)])) raises(CoercionFailed, lambda: f.subs([(x, QQ(1,7)), (y, QQ(1,7))])) def test_PolyElement_compose(): R, x = ring("x", ZZ) f = x**3 + 4*x**2 + 2*x + 3 r = f.compose(x, 0) assert r == 3 and isinstance(r, R.dtype) assert f.compose(x, x) == f assert f.compose(x, x**2) == x**6 + 4*x**4 + 2*x**2 + 3 raises(CoercionFailed, lambda: f.compose(x, QQ(1,7))) R, x, y, z = ring("x,y,z", ZZ) f = x**3 + 4*x**2 + 2*x + 3 r = f.compose(x, 0) assert r == 3 and isinstance(r, R.dtype) r = f.compose([(x, 0), (y, 0)]) assert r == 3 and isinstance(r, R.dtype) r = (x**3 + 4*x**2 + 2*x*y*z + 3).compose(x, y*z**2 - 1) q = (y*z**2 - 1)**3 + 4*(y*z**2 - 1)**2 + 2*(y*z**2 - 1)*y*z + 3 assert r == q and isinstance(r, R.dtype) def test_PolyElement_is_(): R, x,y,z = ring("x,y,z", QQ) assert (x - x).is_generator == False assert (x - x).is_ground == True assert (x - x).is_monomial == True assert (x - x).is_term == True assert (x - x + 1).is_generator == False assert (x - x + 1).is_ground == True assert (x - x + 1).is_monomial == True assert (x - x + 1).is_term == True assert x.is_generator == True assert x.is_ground == False assert x.is_monomial == True assert x.is_term == True assert (x*y).is_generator == False assert (x*y).is_ground == False assert (x*y).is_monomial == True assert (x*y).is_term == True assert (3*x).is_generator == False assert (3*x).is_ground == False assert (3*x).is_monomial == False assert (3*x).is_term == True assert (3*x + 1).is_generator == False assert (3*x + 1).is_ground == False assert (3*x + 1).is_monomial == False assert (3*x + 1).is_term == False assert R(0).is_zero is True assert R(1).is_zero is False assert R(0).is_one is False assert R(1).is_one is True assert (x - 1).is_monic is True assert (2*x - 1).is_monic is False assert (3*x + 2).is_primitive is True assert (4*x + 2).is_primitive is False assert (x + y + z + 1).is_linear is True assert (x*y*z + 1).is_linear is False assert (x*y + z + 1).is_quadratic is True assert (x*y*z + 1).is_quadratic is False assert (x - 1).is_squarefree is True assert ((x - 1)**2).is_squarefree is False assert (x**2 + x + 1).is_irreducible is True assert (x**2 + 2*x + 1).is_irreducible is False _, t = ring("t", FF(11)) assert (7*t + 3).is_irreducible is True assert (7*t**2 + 3*t + 1).is_irreducible is False _, u = ring("u", ZZ) f = u**16 + u**14 - u**10 - u**8 - u**6 + u**2 assert f.is_cyclotomic is False assert (f + 1).is_cyclotomic is True raises(MultivariatePolynomialError, lambda: x.is_cyclotomic) R, = ring("", ZZ) assert R(4).is_squarefree is True assert R(6).is_irreducible is True def test_PolyElement_drop(): R, x,y,z = ring("x,y,z", ZZ) assert R(1).drop(0).ring == PolyRing("y,z", ZZ, lex) assert R(1).drop(0).drop(0).ring == PolyRing("z", ZZ, lex) assert isinstance(R(1).drop(0).drop(0).drop(0), R.dtype) is False raises(ValueError, lambda: z.drop(0).drop(0).drop(0)) raises(ValueError, lambda: x.drop(0)) def test_PolyElement_pdiv(): _, x, y = ring("x,y", ZZ) f, g = x**2 - y**2, x - y q, r = x + y, 0 assert f.pdiv(g) == (q, r) assert f.prem(g) == r assert f.pquo(g) == q assert f.pexquo(g) == q def test_PolyElement_gcdex(): _, x = ring("x", QQ) f, g = 2*x, x**2 - 16 s, t, h = x/32, -QQ(1, 16), 1 assert f.half_gcdex(g) == (s, h) assert f.gcdex(g) == (s, t, h) def test_PolyElement_subresultants(): _, x = ring("x", ZZ) f, g, h = x**2 - 2*x + 1, x**2 - 1, 2*x - 2 assert f.subresultants(g) == [f, g, h] def test_PolyElement_resultant(): _, x = ring("x", ZZ) f, g, h = x**2 - 2*x + 1, x**2 - 1, 0 assert f.resultant(g) == h def test_PolyElement_discriminant(): _, x = ring("x", ZZ) f, g = x**3 + 3*x**2 + 9*x - 13, -11664 assert f.discriminant() == g F, a, b, c = ring("a,b,c", ZZ) _, x = ring("x", F) f, g = a*x**2 + b*x + c, b**2 - 4*a*c assert f.discriminant() == g def test_PolyElement_decompose(): _, x = ring("x", ZZ) f = x**12 + 20*x**10 + 150*x**8 + 500*x**6 + 625*x**4 - 2*x**3 - 10*x + 9 g = x**4 - 2*x + 9 h = x**3 + 5*x assert g.compose(x, h) == f assert f.decompose() == [g, h] def test_PolyElement_shift(): _, x = ring("x", ZZ) assert (x**2 - 2*x + 1).shift(2) == x**2 + 2*x + 1 def test_PolyElement_sturm(): F, t = field("t", ZZ) _, x = ring("x", F) f = 1024/(15625*t**8)*x**5 - 4096/(625*t**8)*x**4 + 32/(15625*t**4)*x**3 - 128/(625*t**4)*x**2 + F(1)/62500*x - F(1)/625 assert f.sturm() == [ x**3 - 100*x**2 + t**4/64*x - 25*t**4/16, 3*x**2 - 200*x + t**4/64, (-t**4/96 + F(20000)/9)*x + 25*t**4/18, (-9*t**12 - 11520000*t**8 - 3686400000000*t**4)/(576*t**8 - 245760000*t**4 + 26214400000000), ] def test_PolyElement_gff_list(): _, x = ring("x", ZZ) f = x**5 + 2*x**4 - x**3 - 2*x**2 assert f.gff_list() == [(x, 1), (x + 2, 4)] f = x*(x - 1)**3*(x - 2)**2*(x - 4)**2*(x - 5) assert f.gff_list() == [(x**2 - 5*x + 4, 1), (x**2 - 5*x + 4, 2), (x, 3)] def test_PolyElement_sqf_norm(): R, x = ring("x", QQ.algebraic_field(sqrt(3))) X = R.to_ground().x assert (x**2 - 2).sqf_norm() == (1, x**2 - 2*sqrt(3)*x + 1, X**4 - 10*X**2 + 1) R, x = ring("x", QQ.algebraic_field(sqrt(2))) X = R.to_ground().x assert (x**2 - 3).sqf_norm() == (1, x**2 - 2*sqrt(2)*x - 1, X**4 - 10*X**2 + 1) def test_PolyElement_sqf_list(): _, x = ring("x", ZZ) f = x**5 - x**3 - x**2 + 1 g = x**3 + 2*x**2 + 2*x + 1 h = x - 1 p = x**4 + x**3 - x - 1 assert f.sqf_part() == p assert f.sqf_list() == (1, [(g, 1), (h, 2)]) def test_PolyElement_factor_list(): _, x = ring("x", ZZ) f = x**5 - x**3 - x**2 + 1 u = x + 1 v = x - 1 w = x**2 + x + 1 assert f.factor_list() == (1, [(u, 1), (v, 2), (w, 1)])
ee4d62828f717cdf5ba46b719ce778b99dd28e4360df3334ee0a958fb77d12ca
"""Test sparse rational functions. """ from sympy.polys.fields import field, sfield, FracField, FracElement from sympy.polys.rings import ring from sympy.polys.domains import ZZ, QQ from sympy.polys.orderings import lex from sympy.testing.pytest import raises, XFAIL from sympy.core import symbols, E from sympy import sqrt, Rational, exp, log def test_FracField___init__(): F1 = FracField("x,y", ZZ, lex) F2 = FracField("x,y", ZZ, lex) F3 = FracField("x,y,z", ZZ, lex) assert F1.x == F1.gens[0] assert F1.y == F1.gens[1] assert F1.x == F2.x assert F1.y == F2.y assert F1.x != F3.x assert F1.y != F3.y def test_FracField___hash__(): F, x, y, z = field("x,y,z", QQ) assert hash(F) def test_FracField___eq__(): assert field("x,y,z", QQ)[0] == field("x,y,z", QQ)[0] assert field("x,y,z", QQ)[0] is field("x,y,z", QQ)[0] assert field("x,y,z", QQ)[0] != field("x,y,z", ZZ)[0] assert field("x,y,z", QQ)[0] is not field("x,y,z", ZZ)[0] assert field("x,y,z", ZZ)[0] != field("x,y,z", QQ)[0] assert field("x,y,z", ZZ)[0] is not field("x,y,z", QQ)[0] assert field("x,y,z", QQ)[0] != field("x,y", QQ)[0] assert field("x,y,z", QQ)[0] is not field("x,y", QQ)[0] assert field("x,y", QQ)[0] != field("x,y,z", QQ)[0] assert field("x,y", QQ)[0] is not field("x,y,z", QQ)[0] def test_sfield(): x = symbols("x") F = FracField((E, exp(exp(x)), exp(x)), ZZ, lex) e, exex, ex = F.gens assert sfield(exp(x)*exp(exp(x) + 1 + log(exp(x) + 3)/2)**2/(exp(x) + 3)) \ == (F, e**2*exex**2*ex) F = FracField((x, exp(1/x), log(x), x**QQ(1, 3)), ZZ, lex) _, ex, lg, x3 = F.gens assert sfield(((x-3)*log(x)+4*x**2)*exp(1/x+log(x)/3)/x**2) == \ (F, (4*F.x**2*ex + F.x*ex*lg - 3*ex*lg)/x3**5) F = FracField((x, log(x), sqrt(x + log(x))), ZZ, lex) _, lg, srt = F.gens assert sfield((x + 1) / (x * (x + log(x))**QQ(3, 2)) - 1/(x * log(x)**2)) \ == (F, (F.x*lg**2 - F.x*srt + lg**2 - lg*srt)/ (F.x**2*lg**2*srt + F.x*lg**3*srt)) def test_FracElement___hash__(): F, x, y, z = field("x,y,z", QQ) assert hash(x*y/z) def test_FracElement_copy(): F, x, y, z = field("x,y,z", ZZ) f = x*y/3*z g = f.copy() assert f == g g.numer[(1, 1, 1)] = 7 assert f != g def test_FracElement_as_expr(): F, x, y, z = field("x,y,z", ZZ) f = (3*x**2*y - x*y*z)/(7*z**3 + 1) X, Y, Z = F.symbols g = (3*X**2*Y - X*Y*Z)/(7*Z**3 + 1) assert f != g assert f.as_expr() == g X, Y, Z = symbols("x,y,z") g = (3*X**2*Y - X*Y*Z)/(7*Z**3 + 1) assert f != g assert f.as_expr(X, Y, Z) == g raises(ValueError, lambda: f.as_expr(X)) def test_FracElement_from_expr(): x, y, z = symbols("x,y,z") F, X, Y, Z = field((x, y, z), ZZ) f = F.from_expr(1) assert f == 1 and isinstance(f, F.dtype) f = F.from_expr(Rational(3, 7)) assert f == F(3)/7 and isinstance(f, F.dtype) f = F.from_expr(x) assert f == X and isinstance(f, F.dtype) f = F.from_expr(Rational(3,7)*x) assert f == X*Rational(3, 7) and isinstance(f, F.dtype) f = F.from_expr(1/x) assert f == 1/X and isinstance(f, F.dtype) f = F.from_expr(x*y*z) assert f == X*Y*Z and isinstance(f, F.dtype) f = F.from_expr(x*y/z) assert f == X*Y/Z and isinstance(f, F.dtype) f = F.from_expr(x*y*z + x*y + x) assert f == X*Y*Z + X*Y + X and isinstance(f, F.dtype) f = F.from_expr((x*y*z + x*y + x)/(x*y + 7)) assert f == (X*Y*Z + X*Y + X)/(X*Y + 7) and isinstance(f, F.dtype) f = F.from_expr(x**3*y*z + x**2*y**7 + 1) assert f == X**3*Y*Z + X**2*Y**7 + 1 and isinstance(f, F.dtype) raises(ValueError, lambda: F.from_expr(2**x)) raises(ValueError, lambda: F.from_expr(7*x + sqrt(2))) assert isinstance(ZZ[2**x].get_field().convert(2**(-x)), FracElement) assert isinstance(ZZ[x**2].get_field().convert(x**(-6)), FracElement) assert isinstance(ZZ[exp(Rational(1, 3))].get_field().convert(E), FracElement) def test_FracField_nested(): a, b, x = symbols('a b x') F1 = ZZ.frac_field(a, b) F2 = F1.frac_field(x) frac = F2(a + b) assert frac.numer == F1.poly_ring(x)(a + b) assert frac.numer.coeffs() == [F1(a + b)] assert frac.denom == F1.poly_ring(x)(1) F3 = ZZ.poly_ring(a, b) F4 = F3.frac_field(x) frac = F4(a + b) assert frac.numer == F3.poly_ring(x)(a + b) assert frac.numer.coeffs() == [F3(a + b)] assert frac.denom == F3.poly_ring(x)(1) frac = F2(F3(a + b)) assert frac.numer == F1.poly_ring(x)(a + b) assert frac.numer.coeffs() == [F1(a + b)] assert frac.denom == F1.poly_ring(x)(1) frac = F4(F1(a + b)) assert frac.numer == F3.poly_ring(x)(a + b) assert frac.numer.coeffs() == [F3(a + b)] assert frac.denom == F3.poly_ring(x)(1) def test_FracElement__lt_le_gt_ge__(): F, x, y = field("x,y", ZZ) assert F(1) < 1/x < 1/x**2 < 1/x**3 assert F(1) <= 1/x <= 1/x**2 <= 1/x**3 assert -7/x < 1/x < 3/x < y/x < 1/x**2 assert -7/x <= 1/x <= 3/x <= y/x <= 1/x**2 assert 1/x**3 > 1/x**2 > 1/x > F(1) assert 1/x**3 >= 1/x**2 >= 1/x >= F(1) assert 1/x**2 > y/x > 3/x > 1/x > -7/x assert 1/x**2 >= y/x >= 3/x >= 1/x >= -7/x def test_FracElement___neg__(): F, x,y = field("x,y", QQ) f = (7*x - 9)/y g = (-7*x + 9)/y assert -f == g assert -g == f def test_FracElement___add__(): F, x,y = field("x,y", QQ) f, g = 1/x, 1/y assert f + g == g + f == (x + y)/(x*y) assert x + F.ring.gens[0] == F.ring.gens[0] + x == 2*x F, x,y = field("x,y", ZZ) assert x + 3 == 3 + x assert x + QQ(3,7) == QQ(3,7) + x == (7*x + 3)/7 Fuv, u,v = field("u,v", ZZ) Fxyzt, x,y,z,t = field("x,y,z,t", Fuv) f = (u*v + x)/(y + u*v) assert dict(f.numer) == {(1, 0, 0, 0): 1, (0, 0, 0, 0): u*v} assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0): u*v} Ruv, u,v = ring("u,v", ZZ) Fxyzt, x,y,z,t = field("x,y,z,t", Ruv) f = (u*v + x)/(y + u*v) assert dict(f.numer) == {(1, 0, 0, 0): 1, (0, 0, 0, 0): u*v} assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0): u*v} def test_FracElement___sub__(): F, x,y = field("x,y", QQ) f, g = 1/x, 1/y assert f - g == (-x + y)/(x*y) assert x - F.ring.gens[0] == F.ring.gens[0] - x == 0 F, x,y = field("x,y", ZZ) assert x - 3 == -(3 - x) assert x - QQ(3,7) == -(QQ(3,7) - x) == (7*x - 3)/7 Fuv, u,v = field("u,v", ZZ) Fxyzt, x,y,z,t = field("x,y,z,t", Fuv) f = (u*v - x)/(y - u*v) assert dict(f.numer) == {(1, 0, 0, 0):-1, (0, 0, 0, 0): u*v} assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0):-u*v} Ruv, u,v = ring("u,v", ZZ) Fxyzt, x,y,z,t = field("x,y,z,t", Ruv) f = (u*v - x)/(y - u*v) assert dict(f.numer) == {(1, 0, 0, 0):-1, (0, 0, 0, 0): u*v} assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0):-u*v} def test_FracElement___mul__(): F, x,y = field("x,y", QQ) f, g = 1/x, 1/y assert f*g == g*f == 1/(x*y) assert x*F.ring.gens[0] == F.ring.gens[0]*x == x**2 F, x,y = field("x,y", ZZ) assert x*3 == 3*x assert x*QQ(3,7) == QQ(3,7)*x == x*Rational(3, 7) Fuv, u,v = field("u,v", ZZ) Fxyzt, x,y,z,t = field("x,y,z,t", Fuv) f = ((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1) assert dict(f.numer) == {(1, 1, 0, 0): u + 1, (0, 0, 0, 0): 1} assert dict(f.denom) == {(0, 0, 1, 0): v - 1, (0, 0, 0, 1): -u*v, (0, 0, 0, 0): -1} Ruv, u,v = ring("u,v", ZZ) Fxyzt, x,y,z,t = field("x,y,z,t", Ruv) f = ((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1) assert dict(f.numer) == {(1, 1, 0, 0): u + 1, (0, 0, 0, 0): 1} assert dict(f.denom) == {(0, 0, 1, 0): v - 1, (0, 0, 0, 1): -u*v, (0, 0, 0, 0): -1} def test_FracElement___truediv__(): F, x,y = field("x,y", QQ) f, g = 1/x, 1/y assert f/g == y/x assert x/F.ring.gens[0] == F.ring.gens[0]/x == 1 F, x,y = field("x,y", ZZ) assert x*3 == 3*x assert x/QQ(3,7) == (QQ(3,7)/x)**-1 == x*Rational(7, 3) raises(ZeroDivisionError, lambda: x/0) raises(ZeroDivisionError, lambda: 1/(x - x)) raises(ZeroDivisionError, lambda: x/(x - x)) Fuv, u,v = field("u,v", ZZ) Fxyzt, x,y,z,t = field("x,y,z,t", Fuv) f = (u*v)/(x*y) assert dict(f.numer) == {(0, 0, 0, 0): u*v} assert dict(f.denom) == {(1, 1, 0, 0): 1} g = (x*y)/(u*v) assert dict(g.numer) == {(1, 1, 0, 0): 1} assert dict(g.denom) == {(0, 0, 0, 0): u*v} Ruv, u,v = ring("u,v", ZZ) Fxyzt, x,y,z,t = field("x,y,z,t", Ruv) f = (u*v)/(x*y) assert dict(f.numer) == {(0, 0, 0, 0): u*v} assert dict(f.denom) == {(1, 1, 0, 0): 1} g = (x*y)/(u*v) assert dict(g.numer) == {(1, 1, 0, 0): 1} assert dict(g.denom) == {(0, 0, 0, 0): u*v} def test_FracElement___pow__(): F, x,y = field("x,y", QQ) f, g = 1/x, 1/y assert f**3 == 1/x**3 assert g**3 == 1/y**3 assert (f*g)**3 == 1/(x**3*y**3) assert (f*g)**-3 == (x*y)**3 raises(ZeroDivisionError, lambda: (x - x)**-3) def test_FracElement_diff(): F, x,y,z = field("x,y,z", ZZ) assert ((x**2 + y)/(z + 1)).diff(x) == 2*x/(z + 1) @XFAIL def test_FracElement___call__(): F, x,y,z = field("x,y,z", ZZ) f = (x**2 + 3*y)/z r = f(1, 1, 1) assert r == 4 and not isinstance(r, FracElement) raises(ZeroDivisionError, lambda: f(1, 1, 0)) def test_FracElement_evaluate(): F, x,y,z = field("x,y,z", ZZ) Fyz = field("y,z", ZZ)[0] f = (x**2 + 3*y)/z assert f.evaluate(x, 0) == 3*Fyz.y/Fyz.z raises(ZeroDivisionError, lambda: f.evaluate(z, 0)) def test_FracElement_subs(): F, x,y,z = field("x,y,z", ZZ) f = (x**2 + 3*y)/z assert f.subs(x, 0) == 3*y/z raises(ZeroDivisionError, lambda: f.subs(z, 0)) def test_FracElement_compose(): pass
e2931bca5b708a7c1176cfc4ee111001069c240d18feb6ba83a478a7e9152832
"""Tests for PythonRational type. """ from sympy.polys.domains import PythonRational as QQ from sympy.testing.pytest import raises def test_PythonRational__init__(): assert QQ(0).p == 0 assert QQ(0).q == 1 assert QQ(0, 1).p == 0 assert QQ(0, 1).q == 1 assert QQ(0, -1).p == 0 assert QQ(0, -1).q == 1 assert QQ(1).p == 1 assert QQ(1).q == 1 assert QQ(1, 1).p == 1 assert QQ(1, 1).q == 1 assert QQ(-1, -1).p == 1 assert QQ(-1, -1).q == 1 assert QQ(-1).p == -1 assert QQ(-1).q == 1 assert QQ(-1, 1).p == -1 assert QQ(-1, 1).q == 1 assert QQ( 1, -1).p == -1 assert QQ( 1, -1).q == 1 assert QQ(1, 2).p == 1 assert QQ(1, 2).q == 2 assert QQ(3, 4).p == 3 assert QQ(3, 4).q == 4 assert QQ(2, 2).p == 1 assert QQ(2, 2).q == 1 assert QQ(2, 4).p == 1 assert QQ(2, 4).q == 2 def test_PythonRational__hash__(): assert hash(QQ(0)) == hash(0) assert hash(QQ(1)) == hash(1) assert hash(QQ(117)) == hash(117) def test_PythonRational__int__(): assert int(QQ(-1, 4)) == 0 assert int(QQ( 1, 4)) == 0 assert int(QQ(-5, 4)) == -1 assert int(QQ( 5, 4)) == 1 def test_PythonRational__float__(): assert float(QQ(-1, 2)) == -0.5 assert float(QQ( 1, 2)) == 0.5 def test_PythonRational__abs__(): assert abs(QQ(-1, 2)) == QQ(1, 2) assert abs(QQ( 1, 2)) == QQ(1, 2) def test_PythonRational__pos__(): assert +QQ(-1, 2) == QQ(-1, 2) assert +QQ( 1, 2) == QQ( 1, 2) def test_PythonRational__neg__(): assert -QQ(-1, 2) == QQ( 1, 2) assert -QQ( 1, 2) == QQ(-1, 2) def test_PythonRational__add__(): assert QQ(-1, 2) + QQ( 1, 2) == QQ(0) assert QQ( 1, 2) + QQ(-1, 2) == QQ(0) assert QQ(1, 2) + QQ(1, 2) == QQ(1) assert QQ(1, 2) + QQ(3, 2) == QQ(2) assert QQ(3, 2) + QQ(1, 2) == QQ(2) assert QQ(3, 2) + QQ(3, 2) == QQ(3) assert 1 + QQ(1, 2) == QQ(3, 2) assert QQ(1, 2) + 1 == QQ(3, 2) def test_PythonRational__sub__(): assert QQ(-1, 2) - QQ( 1, 2) == QQ(-1) assert QQ( 1, 2) - QQ(-1, 2) == QQ( 1) assert QQ(1, 2) - QQ(1, 2) == QQ( 0) assert QQ(1, 2) - QQ(3, 2) == QQ(-1) assert QQ(3, 2) - QQ(1, 2) == QQ( 1) assert QQ(3, 2) - QQ(3, 2) == QQ( 0) assert 1 - QQ(1, 2) == QQ( 1, 2) assert QQ(1, 2) - 1 == QQ(-1, 2) def test_PythonRational__mul__(): assert QQ(-1, 2) * QQ( 1, 2) == QQ(-1, 4) assert QQ( 1, 2) * QQ(-1, 2) == QQ(-1, 4) assert QQ(1, 2) * QQ(1, 2) == QQ(1, 4) assert QQ(1, 2) * QQ(3, 2) == QQ(3, 4) assert QQ(3, 2) * QQ(1, 2) == QQ(3, 4) assert QQ(3, 2) * QQ(3, 2) == QQ(9, 4) assert 2 * QQ(1, 2) == QQ(1) assert QQ(1, 2) * 2 == QQ(1) def test_PythonRational__truediv__(): assert QQ(-1, 2) / QQ( 1, 2) == QQ(-1) assert QQ( 1, 2) / QQ(-1, 2) == QQ(-1) assert QQ(1, 2) / QQ(1, 2) == QQ(1) assert QQ(1, 2) / QQ(3, 2) == QQ(1, 3) assert QQ(3, 2) / QQ(1, 2) == QQ(3) assert QQ(3, 2) / QQ(3, 2) == QQ(1) assert 2 / QQ(1, 2) == QQ(4) assert QQ(1, 2) / 2 == QQ(1, 4) raises(ZeroDivisionError, lambda: QQ(1, 2) / QQ(0)) raises(ZeroDivisionError, lambda: QQ(1, 2) / 0) def test_PythonRational__pow__(): assert QQ(1)**10 == QQ(1) assert QQ(2)**10 == QQ(1024) assert QQ(1)**(-10) == QQ(1) assert QQ(2)**(-10) == QQ(1, 1024) def test_PythonRational__eq__(): assert (QQ(1, 2) == QQ(1, 2)) is True assert (QQ(1, 2) != QQ(1, 2)) is False assert (QQ(1, 2) == QQ(1, 3)) is False assert (QQ(1, 2) != QQ(1, 3)) is True def test_PythonRational__lt_le_gt_ge__(): assert (QQ(1, 2) < QQ(1, 4)) is False assert (QQ(1, 2) <= QQ(1, 4)) is False assert (QQ(1, 2) > QQ(1, 4)) is True assert (QQ(1, 2) >= QQ(1, 4)) is True assert (QQ(1, 4) < QQ(1, 2)) is True assert (QQ(1, 4) <= QQ(1, 2)) is True assert (QQ(1, 4) > QQ(1, 2)) is False assert (QQ(1, 4) >= QQ(1, 2)) is False
6ce434dce228f9622855378e9b1b072487d438da52cee73a8010b36c045fe623
""" Computations with modules over polynomial rings. This module implements various classes that encapsulate groebner basis computations for modules. Most of them should not be instantiated by hand. Instead, use the constructing routines on objects you already have. For example, to construct a free module over ``QQ[x, y]``, call ``QQ[x, y].free_module(rank)`` instead of the ``FreeModule`` constructor. In fact ``FreeModule`` is an abstract base class that should not be instantiated, the ``free_module`` method instead returns the implementing class ``FreeModulePolyRing``. In general, the abstract base classes implement most functionality in terms of a few non-implemented methods. The concrete base classes supply only these non-implemented methods. They may also supply new implementations of the convenience methods, for example if there are faster algorithms available. """ from __future__ import print_function, division from copy import copy from sympy.core.compatibility import iterable, reduce from sympy.polys.agca.ideals import Ideal from sympy.polys.domains.field import Field from sympy.polys.orderings import ProductOrder, monomial_key from sympy.polys.polyerrors import CoercionFailed from sympy.core.basic import _aresame # TODO # - module saturation # - module quotient/intersection for quotient rings # - free resoltutions / syzygies # - finding small/minimal generating sets # - ... ########################################################################## ## Abstract base classes ################################################# ########################################################################## class Module(object): """ Abstract base class for modules. Do not instantiate - use ring explicit constructors instead: >>> from sympy import QQ >>> from sympy.abc import x >>> QQ.old_poly_ring(x).free_module(2) QQ[x]**2 Attributes: - dtype - type of elements - ring - containing ring Non-implemented methods: - submodule - quotient_module - is_zero - is_submodule - multiply_ideal The method convert likely needs to be changed in subclasses. """ def __init__(self, ring): self.ring = ring def convert(self, elem, M=None): """ Convert ``elem`` into internal representation of this module. If ``M`` is not None, it should be a module containing it. """ if not isinstance(elem, self.dtype): raise CoercionFailed return elem def submodule(self, *gens): """Generate a submodule.""" raise NotImplementedError def quotient_module(self, other): """Generate a quotient module.""" raise NotImplementedError def __truediv__(self, e): if not isinstance(e, Module): e = self.submodule(*e) return self.quotient_module(e) def contains(self, elem): """Return True if ``elem`` is an element of this module.""" try: self.convert(elem) return True except CoercionFailed: return False def __contains__(self, elem): return self.contains(elem) def subset(self, other): """ Returns True if ``other`` is is a subset of ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> F.subset([(1, x), (x, 2)]) True >>> F.subset([(1/x, x), (x, 2)]) False """ return all(self.contains(x) for x in other) def __eq__(self, other): return self.is_submodule(other) and other.is_submodule(self) def __ne__(self, other): return not (self == other) def is_zero(self): """Returns True if ``self`` is a zero module.""" raise NotImplementedError def is_submodule(self, other): """Returns True if ``other`` is a submodule of ``self``.""" raise NotImplementedError def multiply_ideal(self, other): """ Multiply ``self`` by the ideal ``other``. """ raise NotImplementedError def __mul__(self, e): if not isinstance(e, Ideal): try: e = self.ring.ideal(e) except (CoercionFailed, NotImplementedError): return NotImplemented return self.multiply_ideal(e) __rmul__ = __mul__ def identity_hom(self): """Return the identity homomorphism on ``self``.""" raise NotImplementedError class ModuleElement(object): """ Base class for module element wrappers. Use this class to wrap primitive data types as module elements. It stores a reference to the containing module, and implements all the arithmetic operators. Attributes: - module - containing module - data - internal data Methods that likely need change in subclasses: - add - mul - div - eq """ def __init__(self, module, data): self.module = module self.data = data def add(self, d1, d2): """Add data ``d1`` and ``d2``.""" return d1 + d2 def mul(self, m, d): """Multiply module data ``m`` by coefficient d.""" return m * d def div(self, m, d): """Divide module data ``m`` by coefficient d.""" return m / d def eq(self, d1, d2): """Return true if d1 and d2 represent the same element.""" return d1 == d2 def __add__(self, om): if not isinstance(om, self.__class__) or om.module != self.module: try: om = self.module.convert(om) except CoercionFailed: return NotImplemented return self.__class__(self.module, self.add(self.data, om.data)) __radd__ = __add__ def __neg__(self): return self.__class__(self.module, self.mul(self.data, self.module.ring.convert(-1))) def __sub__(self, om): if not isinstance(om, self.__class__) or om.module != self.module: try: om = self.module.convert(om) except CoercionFailed: return NotImplemented return self.__add__(-om) def __rsub__(self, om): return (-self).__add__(om) def __mul__(self, o): if not isinstance(o, self.module.ring.dtype): try: o = self.module.ring.convert(o) except CoercionFailed: return NotImplemented return self.__class__(self.module, self.mul(self.data, o)) __rmul__ = __mul__ def __truediv__(self, o): if not isinstance(o, self.module.ring.dtype): try: o = self.module.ring.convert(o) except CoercionFailed: return NotImplemented return self.__class__(self.module, self.div(self.data, o)) def __eq__(self, om): if not isinstance(om, self.__class__) or om.module != self.module: try: om = self.module.convert(om) except CoercionFailed: return False return self.eq(self.data, om.data) def __ne__(self, om): return not self == om ########################################################################## ## Free Modules ########################################################## ########################################################################## class FreeModuleElement(ModuleElement): """Element of a free module. Data stored as a tuple.""" def add(self, d1, d2): return tuple(x + y for x, y in zip(d1, d2)) def mul(self, d, p): return tuple(x * p for x in d) def div(self, d, p): return tuple(x / p for x in d) def __repr__(self): from sympy import sstr return '[' + ', '.join(sstr(x) for x in self.data) + ']' def __iter__(self): return self.data.__iter__() def __getitem__(self, idx): return self.data[idx] class FreeModule(Module): """ Abstract base class for free modules. Additional attributes: - rank - rank of the free module Non-implemented methods: - submodule """ dtype = FreeModuleElement def __init__(self, ring, rank): Module.__init__(self, ring) self.rank = rank def __repr__(self): return repr(self.ring) + "**" + repr(self.rank) def is_submodule(self, other): """ Returns True if ``other`` is a submodule of ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> M = F.submodule([2, x]) >>> F.is_submodule(F) True >>> F.is_submodule(M) True >>> M.is_submodule(F) False """ if isinstance(other, SubModule): return other.container == self if isinstance(other, FreeModule): return other.ring == self.ring and other.rank == self.rank return False def convert(self, elem, M=None): """ Convert ``elem`` into the internal representation. This method is called implicitly whenever computations involve elements not in the internal representation. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> F.convert([1, 0]) [1, 0] """ if isinstance(elem, FreeModuleElement): if elem.module is self: return elem if elem.module.rank != self.rank: raise CoercionFailed return FreeModuleElement(self, tuple(self.ring.convert(x, elem.module.ring) for x in elem.data)) elif iterable(elem): tpl = tuple(self.ring.convert(x) for x in elem) if len(tpl) != self.rank: raise CoercionFailed return FreeModuleElement(self, tpl) elif _aresame(elem, 0): return FreeModuleElement(self, (self.ring.convert(0),)*self.rank) else: raise CoercionFailed def is_zero(self): """ Returns True if ``self`` is a zero module. (If, as this implementation assumes, the coefficient ring is not the zero ring, then this is equivalent to the rank being zero.) Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).free_module(0).is_zero() True >>> QQ.old_poly_ring(x).free_module(1).is_zero() False """ return self.rank == 0 def basis(self): """ Return a set of basis elements. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).free_module(3).basis() ([1, 0, 0], [0, 1, 0], [0, 0, 1]) """ from sympy.matrices import eye M = eye(self.rank) return tuple(self.convert(M.row(i)) for i in range(self.rank)) def quotient_module(self, submodule): """ Return a quotient module. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> M = QQ.old_poly_ring(x).free_module(2) >>> M.quotient_module(M.submodule([1, x], [x, 2])) QQ[x]**2/<[1, x], [x, 2]> Or more conicisely, using the overloaded division operator: >>> QQ.old_poly_ring(x).free_module(2) / [[1, x], [x, 2]] QQ[x]**2/<[1, x], [x, 2]> """ return QuotientModule(self.ring, self, submodule) def multiply_ideal(self, other): """ Multiply ``self`` by the ideal ``other``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> I = QQ.old_poly_ring(x).ideal(x) >>> F = QQ.old_poly_ring(x).free_module(2) >>> F.multiply_ideal(I) <[x, 0], [0, x]> """ return self.submodule(*self.basis()).multiply_ideal(other) def identity_hom(self): """ Return the identity homomorphism on ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).free_module(2).identity_hom() Matrix([ [1, 0], : QQ[x]**2 -> QQ[x]**2 [0, 1]]) """ from sympy.polys.agca.homomorphisms import homomorphism return homomorphism(self, self, self.basis()) class FreeModulePolyRing(FreeModule): """ Free module over a generalized polynomial ring. Do not instantiate this, use the constructor method of the ring instead: Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(3) >>> F QQ[x]**3 >>> F.contains([x, 1, 0]) True >>> F.contains([1/x, 0, 1]) False """ def __init__(self, ring, rank): from sympy.polys.domains.old_polynomialring import PolynomialRingBase FreeModule.__init__(self, ring, rank) if not isinstance(ring, PolynomialRingBase): raise NotImplementedError('This implementation only works over ' + 'polynomial rings, got %s' % ring) if not isinstance(ring.dom, Field): raise NotImplementedError('Ground domain must be a field, ' + 'got %s' % ring.dom) def submodule(self, *gens, **opts): """ Generate a submodule. Examples ======== >>> from sympy.abc import x, y >>> from sympy import QQ >>> M = QQ.old_poly_ring(x, y).free_module(2).submodule([x, x + y]) >>> M <[x, x + y]> >>> M.contains([2*x, 2*x + 2*y]) True >>> M.contains([x, y]) False """ return SubModulePolyRing(gens, self, **opts) class FreeModuleQuotientRing(FreeModule): """ Free module over a quotient ring. Do not instantiate this, use the constructor method of the ring instead: Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(3) >>> F (QQ[x]/<x**2 + 1>)**3 Attributes - quot - the quotient module `R^n / IR^n`, where `R/I` is our ring """ def __init__(self, ring, rank): from sympy.polys.domains.quotientring import QuotientRing FreeModule.__init__(self, ring, rank) if not isinstance(ring, QuotientRing): raise NotImplementedError('This implementation only works over ' + 'quotient rings, got %s' % ring) F = self.ring.ring.free_module(self.rank) self.quot = F / (self.ring.base_ideal*F) def __repr__(self): return "(" + repr(self.ring) + ")" + "**" + repr(self.rank) def submodule(self, *gens, **opts): """ Generate a submodule. Examples ======== >>> from sympy.abc import x, y >>> from sympy import QQ >>> M = (QQ.old_poly_ring(x, y)/[x**2 - y**2]).free_module(2).submodule([x, x + y]) >>> M <[x + <x**2 - y**2>, x + y + <x**2 - y**2>]> >>> M.contains([y**2, x**2 + x*y]) True >>> M.contains([x, y]) False """ return SubModuleQuotientRing(gens, self, **opts) def lift(self, elem): """ Lift the element ``elem`` of self to the module self.quot. Note that self.quot is the same set as self, just as an R-module and not as an R/I-module, so this makes sense. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2) >>> e = F.convert([1, 0]) >>> e [1 + <x**2 + 1>, 0 + <x**2 + 1>] >>> L = F.quot >>> l = F.lift(e) >>> l [1, 0] + <[x**2 + 1, 0], [0, x**2 + 1]> >>> L.contains(l) True """ return self.quot.convert([x.data for x in elem]) def unlift(self, elem): """ Push down an element of self.quot to self. This undoes ``lift``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2) >>> e = F.convert([1, 0]) >>> l = F.lift(e) >>> e == l False >>> e == F.unlift(l) True """ return self.convert(elem.data) ########################################################################## ## Submodules and subquotients ########################################### ########################################################################## class SubModule(Module): """ Base class for submodules. Attributes: - container - containing module - gens - generators (subset of containing module) - rank - rank of containing module Non-implemented methods: - _contains - _syzygies - _in_terms_of_generators - _intersect - _module_quotient Methods that likely need change in subclasses: - reduce_element """ def __init__(self, gens, container): Module.__init__(self, container.ring) self.gens = tuple(container.convert(x) for x in gens) self.container = container self.rank = container.rank self.ring = container.ring self.dtype = container.dtype def __repr__(self): return "<" + ", ".join(repr(x) for x in self.gens) + ">" def _contains(self, other): """Implementation of containment. Other is guaranteed to be FreeModuleElement.""" raise NotImplementedError def _syzygies(self): """Implementation of syzygy computation wrt self generators.""" raise NotImplementedError def _in_terms_of_generators(self, e): """Implementation of expression in terms of generators.""" raise NotImplementedError def convert(self, elem, M=None): """ Convert ``elem`` into the internal represantition. Mostly called implicitly. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> M = QQ.old_poly_ring(x).free_module(2).submodule([1, x]) >>> M.convert([2, 2*x]) [2, 2*x] """ if isinstance(elem, self.container.dtype) and elem.module is self: return elem r = copy(self.container.convert(elem, M)) r.module = self if not self._contains(r): raise CoercionFailed return r def _intersect(self, other): """Implementation of intersection. Other is guaranteed to be a submodule of same free module.""" raise NotImplementedError def _module_quotient(self, other): """Implementation of quotient. Other is guaranteed to be a submodule of same free module.""" raise NotImplementedError def intersect(self, other, **options): """ Returns the intersection of ``self`` with submodule ``other``. Examples ======== >>> from sympy.abc import x, y >>> from sympy import QQ >>> F = QQ.old_poly_ring(x, y).free_module(2) >>> F.submodule([x, x]).intersect(F.submodule([y, y])) <[x*y, x*y]> Some implementation allow further options to be passed. Currently, to only one implemented is ``relations=True``, in which case the function will return a triple ``(res, rela, relb)``, where ``res`` is the intersection module, and ``rela`` and ``relb`` are lists of coefficient vectors, expressing the generators of ``res`` in terms of the generators of ``self`` (``rela``) and ``other`` (``relb``). >>> F.submodule([x, x]).intersect(F.submodule([y, y]), relations=True) (<[x*y, x*y]>, [(y,)], [(x,)]) The above result says: the intersection module is generated by the single element `(-xy, -xy) = -y (x, x) = -x (y, y)`, where `(x, x)` and `(y, y)` respectively are the unique generators of the two modules being intersected. """ if not isinstance(other, SubModule): raise TypeError('%s is not a SubModule' % other) if other.container != self.container: raise ValueError( '%s is contained in a different free module' % other) return self._intersect(other, **options) def module_quotient(self, other, **options): r""" Returns the module quotient of ``self`` by submodule ``other``. That is, if ``self`` is the module `M` and ``other`` is `N`, then return the ideal `\{f \in R | fN \subset M\}`. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x, y >>> F = QQ.old_poly_ring(x, y).free_module(2) >>> S = F.submodule([x*y, x*y]) >>> T = F.submodule([x, x]) >>> S.module_quotient(T) <y> Some implementations allow further options to be passed. Currently, the only one implemented is ``relations=True``, which may only be passed if ``other`` is principal. In this case the function will return a pair ``(res, rel)`` where ``res`` is the ideal, and ``rel`` is a list of coefficient vectors, expressing the generators of the ideal, multiplied by the generator of ``other`` in terms of generators of ``self``. >>> S.module_quotient(T, relations=True) (<y>, [[1]]) This means that the quotient ideal is generated by the single element `y`, and that `y (x, x) = 1 (xy, xy)`, `(x, x)` and `(xy, xy)` being the generators of `T` and `S`, respectively. """ if not isinstance(other, SubModule): raise TypeError('%s is not a SubModule' % other) if other.container != self.container: raise ValueError( '%s is contained in a different free module' % other) return self._module_quotient(other, **options) def union(self, other): """ Returns the module generated by the union of ``self`` and ``other``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(1) >>> M = F.submodule([x**2 + x]) # <x(x+1)> >>> N = F.submodule([x**2 - 1]) # <(x-1)(x+1)> >>> M.union(N) == F.submodule([x+1]) True """ if not isinstance(other, SubModule): raise TypeError('%s is not a SubModule' % other) if other.container != self.container: raise ValueError( '%s is contained in a different free module' % other) return self.__class__(self.gens + other.gens, self.container) def is_zero(self): """ Return True if ``self`` is a zero module. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> F.submodule([x, 1]).is_zero() False >>> F.submodule([0, 0]).is_zero() True """ return all(x == 0 for x in self.gens) def submodule(self, *gens): """ Generate a submodule. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> M = QQ.old_poly_ring(x).free_module(2).submodule([x, 1]) >>> M.submodule([x**2, x]) <[x**2, x]> """ if not self.subset(gens): raise ValueError('%s not a subset of %s' % (gens, self)) return self.__class__(gens, self.container) def is_full_module(self): """ Return True if ``self`` is the entire free module. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> F.submodule([x, 1]).is_full_module() False >>> F.submodule([1, 1], [1, 2]).is_full_module() True """ return all(self.contains(x) for x in self.container.basis()) def is_submodule(self, other): """ Returns True if ``other`` is a submodule of ``self``. >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> M = F.submodule([2, x]) >>> N = M.submodule([2*x, x**2]) >>> M.is_submodule(M) True >>> M.is_submodule(N) True >>> N.is_submodule(M) False """ if isinstance(other, SubModule): return self.container == other.container and \ all(self.contains(x) for x in other.gens) if isinstance(other, (FreeModule, QuotientModule)): return self.container == other and self.is_full_module() return False def syzygy_module(self, **opts): r""" Compute the syzygy module of the generators of ``self``. Suppose `M` is generated by `f_1, \ldots, f_n` over the ring `R`. Consider the homomorphism `\phi: R^n \to M`, given by sending `(r_1, \ldots, r_n) \to r_1 f_1 + \cdots + r_n f_n`. The syzygy module is defined to be the kernel of `\phi`. Examples ======== The syzygy module is zero iff the generators generate freely a free submodule: >>> from sympy.abc import x, y >>> from sympy import QQ >>> QQ.old_poly_ring(x).free_module(2).submodule([1, 0], [1, 1]).syzygy_module().is_zero() True A slightly more interesting example: >>> M = QQ.old_poly_ring(x, y).free_module(2).submodule([x, 2*x], [y, 2*y]) >>> S = QQ.old_poly_ring(x, y).free_module(2).submodule([y, -x]) >>> M.syzygy_module() == S True """ F = self.ring.free_module(len(self.gens)) # NOTE we filter out zero syzygies. This is for convenience of the # _syzygies function and not meant to replace any real "generating set # reduction" algorithm return F.submodule(*[x for x in self._syzygies() if F.convert(x) != 0], **opts) def in_terms_of_generators(self, e): """ Express element ``e`` of ``self`` in terms of the generators. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> M = F.submodule([1, 0], [1, 1]) >>> M.in_terms_of_generators([x, x**2]) [-x**2 + x, x**2] """ try: e = self.convert(e) except CoercionFailed: raise ValueError('%s is not an element of %s' % (e, self)) return self._in_terms_of_generators(e) def reduce_element(self, x): """ Reduce the element ``x`` of our ring modulo the ideal ``self``. Here "reduce" has no specific meaning, it could return a unique normal form, simplify the expression a bit, or just do nothing. """ return x def quotient_module(self, other, **opts): """ Return a quotient module. This is the same as taking a submodule of a quotient of the containing module. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> S1 = F.submodule([x, 1]) >>> S2 = F.submodule([x**2, x]) >>> S1.quotient_module(S2) <[x, 1] + <[x**2, x]>> Or more coincisely, using the overloaded division operator: >>> F.submodule([x, 1]) / [(x**2, x)] <[x, 1] + <[x**2, x]>> """ if not self.is_submodule(other): raise ValueError('%s not a submodule of %s' % (other, self)) return SubQuotientModule(self.gens, self.container.quotient_module(other), **opts) def __add__(self, oth): return self.container.quotient_module(self).convert(oth) __radd__ = __add__ def multiply_ideal(self, I): """ Multiply ``self`` by the ideal ``I``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> I = QQ.old_poly_ring(x).ideal(x**2) >>> M = QQ.old_poly_ring(x).free_module(2).submodule([1, 1]) >>> I*M <[x**2, x**2]> """ return self.submodule(*[x*g for [x] in I._module.gens for g in self.gens]) def inclusion_hom(self): """ Return a homomorphism representing the inclusion map of ``self``. That is, the natural map from ``self`` to ``self.container``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).free_module(2).submodule([x, x]).inclusion_hom() Matrix([ [1, 0], : <[x, x]> -> QQ[x]**2 [0, 1]]) """ return self.container.identity_hom().restrict_domain(self) def identity_hom(self): """ Return the identity homomorphism on ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).free_module(2).submodule([x, x]).identity_hom() Matrix([ [1, 0], : <[x, x]> -> <[x, x]> [0, 1]]) """ return self.container.identity_hom().restrict_domain( self).restrict_codomain(self) class SubQuotientModule(SubModule): """ Submodule of a quotient module. Equivalently, quotient module of a submodule. Do not instantiate this, instead use the submodule or quotient_module constructing methods: >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> S = F.submodule([1, 0], [1, x]) >>> Q = F/[(1, 0)] >>> S/[(1, 0)] == Q.submodule([5, x]) True Attributes: - base - base module we are quotient of - killed_module - submodule used to form the quotient """ def __init__(self, gens, container, **opts): SubModule.__init__(self, gens, container) self.killed_module = self.container.killed_module # XXX it is important for some code below that the generators of base # are in this particular order! self.base = self.container.base.submodule( *[x.data for x in self.gens], **opts).union(self.killed_module) def _contains(self, elem): return self.base.contains(elem.data) def _syzygies(self): # let N = self.killed_module be generated by e_1, ..., e_r # let F = self.base be generated by f_1, ..., f_s and e_1, ..., e_r # Then self = F/N. # Let phi: R**s --> self be the evident surjection. # Similarly psi: R**(s + r) --> F. # We need to find generators for ker(phi). Let chi: R**s --> F be the # evident lift of phi. For X in R**s, phi(X) = 0 iff chi(X) is # contained in N, iff there exists Y in R**r such that # psi(X, Y) = 0. # Hence if alpha: R**(s + r) --> R**s is the projection map, then # ker(phi) = alpha ker(psi). return [X[:len(self.gens)] for X in self.base._syzygies()] def _in_terms_of_generators(self, e): return self.base._in_terms_of_generators(e.data)[:len(self.gens)] def is_full_module(self): """ Return True if ``self`` is the entire free module. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> F.submodule([x, 1]).is_full_module() False >>> F.submodule([1, 1], [1, 2]).is_full_module() True """ return self.base.is_full_module() def quotient_hom(self): """ Return the quotient homomorphism to self. That is, return the natural map from ``self.base`` to ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> M = (QQ.old_poly_ring(x).free_module(2) / [(1, x)]).submodule([1, 0]) >>> M.quotient_hom() Matrix([ [1, 0], : <[1, 0], [1, x]> -> <[1, 0] + <[1, x]>, [1, x] + <[1, x]>> [0, 1]]) """ return self.base.identity_hom().quotient_codomain(self.killed_module) _subs0 = lambda x: x[0] _subs1 = lambda x: x[1:] class ModuleOrder(ProductOrder): """A product monomial order with a zeroth term as module index.""" def __init__(self, o1, o2, TOP): if TOP: ProductOrder.__init__(self, (o2, _subs1), (o1, _subs0)) else: ProductOrder.__init__(self, (o1, _subs0), (o2, _subs1)) class SubModulePolyRing(SubModule): """ Submodule of a free module over a generalized polynomial ring. Do not instantiate this, use the constructor method of FreeModule instead: >>> from sympy.abc import x, y >>> from sympy import QQ >>> F = QQ.old_poly_ring(x, y).free_module(2) >>> F.submodule([x, y], [1, 0]) <[x, y], [1, 0]> Attributes: - order - monomial order used """ #self._gb - cached groebner basis #self._gbe - cached groebner basis relations def __init__(self, gens, container, order="lex", TOP=True): SubModule.__init__(self, gens, container) if not isinstance(container, FreeModulePolyRing): raise NotImplementedError('This implementation is for submodules of ' + 'FreeModulePolyRing, got %s' % container) self.order = ModuleOrder(monomial_key(order), self.ring.order, TOP) self._gb = None self._gbe = None def __eq__(self, other): if isinstance(other, SubModulePolyRing) and self.order != other.order: return False return SubModule.__eq__(self, other) def _groebner(self, extended=False): """Returns a standard basis in sdm form.""" from sympy.polys.distributedmodules import sdm_groebner, sdm_nf_mora if self._gbe is None and extended: gb, gbe = sdm_groebner( [self.ring._vector_to_sdm(x, self.order) for x in self.gens], sdm_nf_mora, self.order, self.ring.dom, extended=True) self._gb, self._gbe = tuple(gb), tuple(gbe) if self._gb is None: self._gb = tuple(sdm_groebner( [self.ring._vector_to_sdm(x, self.order) for x in self.gens], sdm_nf_mora, self.order, self.ring.dom)) if extended: return self._gb, self._gbe else: return self._gb def _groebner_vec(self, extended=False): """Returns a standard basis in element form.""" if not extended: return [self.convert(self.ring._sdm_to_vector(x, self.rank)) for x in self._groebner()] gb, gbe = self._groebner(extended=True) return ([self.convert(self.ring._sdm_to_vector(x, self.rank)) for x in gb], [self.ring._sdm_to_vector(x, len(self.gens)) for x in gbe]) def _contains(self, x): from sympy.polys.distributedmodules import sdm_zero, sdm_nf_mora return sdm_nf_mora(self.ring._vector_to_sdm(x, self.order), self._groebner(), self.order, self.ring.dom) == \ sdm_zero() def _syzygies(self): """Compute syzygies. See [SCA, algorithm 2.5.4].""" # NOTE if self.gens is a standard basis, this can be done more # efficiently using Schreyer's theorem from sympy.matrices import eye # First bullet point k = len(self.gens) r = self.rank im = eye(k) Rkr = self.ring.free_module(r + k) newgens = [] for j, f in enumerate(self.gens): m = [0]*(r + k) for i, v in enumerate(f): m[i] = f[i] for i in range(k): m[r + i] = im[j, i] newgens.append(Rkr.convert(m)) # Note: we need *descending* order on module index, and TOP=False to # get an elimination order F = Rkr.submodule(*newgens, order='ilex', TOP=False) # Second bullet point: standard basis of F G = F._groebner_vec() # Third bullet point: G0 = G intersect the new k components G0 = [x[r:] for x in G if all(y == self.ring.convert(0) for y in x[:r])] # Fourth and fifth bullet points: we are done return G0 def _in_terms_of_generators(self, e): """Expression in terms of generators. See [SCA, 2.8.1].""" # NOTE: if gens is a standard basis, this can be done more efficiently M = self.ring.free_module(self.rank).submodule(*((e,) + self.gens)) S = M.syzygy_module( order="ilex", TOP=False) # We want decreasing order! G = S._groebner_vec() # This list cannot not be empty since e is an element e = [x for x in G if self.ring.is_unit(x[0])][0] return [-x/e[0] for x in e[1:]] def reduce_element(self, x, NF=None): """ Reduce the element ``x`` of our container modulo ``self``. This applies the normal form ``NF`` to ``x``. If ``NF`` is passed as none, the default Mora normal form is used (which is not unique!). """ from sympy.polys.distributedmodules import sdm_nf_mora if NF is None: NF = sdm_nf_mora return self.container.convert(self.ring._sdm_to_vector(NF( self.ring._vector_to_sdm(x, self.order), self._groebner(), self.order, self.ring.dom), self.rank)) def _intersect(self, other, relations=False): # See: [SCA, section 2.8.2] fi = self.gens hi = other.gens r = self.rank ci = [[0]*(2*r) for _ in range(r)] for k in range(r): ci[k][k] = 1 ci[k][r + k] = 1 di = [list(f) + [0]*r for f in fi] ei = [[0]*r + list(h) for h in hi] syz = self.ring.free_module(2*r).submodule(*(ci + di + ei))._syzygies() nonzero = [x for x in syz if any(y != self.ring.zero for y in x[:r])] res = self.container.submodule(*([-y for y in x[:r]] for x in nonzero)) reln1 = [x[r:r + len(fi)] for x in nonzero] reln2 = [x[r + len(fi):] for x in nonzero] if relations: return res, reln1, reln2 return res def _module_quotient(self, other, relations=False): # See: [SCA, section 2.8.4] if relations and len(other.gens) != 1: raise NotImplementedError if len(other.gens) == 0: return self.ring.ideal(1) elif len(other.gens) == 1: # We do some trickery. Let f be the (vector!) generating ``other`` # and f1, .., fn be the (vectors) generating self. # Consider the submodule of R^{r+1} generated by (f, 1) and # {(fi, 0) | i}. Then the intersection with the last module # component yields the quotient. g1 = list(other.gens[0]) + [1] gi = [list(x) + [0] for x in self.gens] # NOTE: We *need* to use an elimination order M = self.ring.free_module(self.rank + 1).submodule(*([g1] + gi), order='ilex', TOP=False) if not relations: return self.ring.ideal(*[x[-1] for x in M._groebner_vec() if all(y == self.ring.zero for y in x[:-1])]) else: G, R = M._groebner_vec(extended=True) indices = [i for i, x in enumerate(G) if all(y == self.ring.zero for y in x[:-1])] return (self.ring.ideal(*[G[i][-1] for i in indices]), [[-x for x in R[i][1:]] for i in indices]) # For more generators, we use I : <h1, .., hn> = intersection of # {I : <hi> | i} # TODO this can be done more efficiently return reduce(lambda x, y: x.intersect(y), (self._module_quotient(self.container.submodule(x)) for x in other.gens)) class SubModuleQuotientRing(SubModule): """ Class for submodules of free modules over quotient rings. Do not instantiate this. Instead use the submodule methods. >>> from sympy.abc import x, y >>> from sympy import QQ >>> M = (QQ.old_poly_ring(x, y)/[x**2 - y**2]).free_module(2).submodule([x, x + y]) >>> M <[x + <x**2 - y**2>, x + y + <x**2 - y**2>]> >>> M.contains([y**2, x**2 + x*y]) True >>> M.contains([x, y]) False Attributes: - quot - the subquotient of `R^n/IR^n` generated by lifts of our generators """ def __init__(self, gens, container): SubModule.__init__(self, gens, container) self.quot = self.container.quot.submodule( *[self.container.lift(x) for x in self.gens]) def _contains(self, elem): return self.quot._contains(self.container.lift(elem)) def _syzygies(self): return [tuple(self.ring.convert(y, self.quot.ring) for y in x) for x in self.quot._syzygies()] def _in_terms_of_generators(self, elem): return [self.ring.convert(x, self.quot.ring) for x in self.quot._in_terms_of_generators(self.container.lift(elem))] ########################################################################## ## Quotient Modules ###################################################### ########################################################################## class QuotientModuleElement(ModuleElement): """Element of a quotient module.""" def eq(self, d1, d2): """Equality comparison.""" return self.module.killed_module.contains(d1 - d2) def __repr__(self): return repr(self.data) + " + " + repr(self.module.killed_module) class QuotientModule(Module): """ Class for quotient modules. Do not instantiate this directly. For subquotients, see the SubQuotientModule class. Attributes: - base - the base module we are a quotient of - killed_module - the submodule used to form the quotient - rank of the base """ dtype = QuotientModuleElement def __init__(self, ring, base, submodule): Module.__init__(self, ring) if not base.is_submodule(submodule): raise ValueError('%s is not a submodule of %s' % (submodule, base)) self.base = base self.killed_module = submodule self.rank = base.rank def __repr__(self): return repr(self.base) + "/" + repr(self.killed_module) def is_zero(self): """ Return True if ``self`` is a zero module. This happens if and only if the base module is the same as the submodule being killed. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> (F/[(1, 0)]).is_zero() False >>> (F/[(1, 0), (0, 1)]).is_zero() True """ return self.base == self.killed_module def is_submodule(self, other): """ Return True if ``other`` is a submodule of ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> Q = QQ.old_poly_ring(x).free_module(2) / [(x, x)] >>> S = Q.submodule([1, 0]) >>> Q.is_submodule(S) True >>> S.is_submodule(Q) False """ if isinstance(other, QuotientModule): return self.killed_module == other.killed_module and \ self.base.is_submodule(other.base) if isinstance(other, SubQuotientModule): return other.container == self return False def submodule(self, *gens, **opts): """ Generate a submodule. This is the same as taking a quotient of a submodule of the base module. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> Q = QQ.old_poly_ring(x).free_module(2) / [(x, x)] >>> Q.submodule([x, 0]) <[x, 0] + <[x, x]>> """ return SubQuotientModule(gens, self, **opts) def convert(self, elem, M=None): """ Convert ``elem`` into the internal representation. This method is called implicitly whenever computations involve elements not in the internal representation. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)] >>> F.convert([1, 0]) [1, 0] + <[1, 2], [1, x]> """ if isinstance(elem, QuotientModuleElement): if elem.module is self: return elem if self.killed_module.is_submodule(elem.module.killed_module): return QuotientModuleElement(self, self.base.convert(elem.data)) raise CoercionFailed return QuotientModuleElement(self, self.base.convert(elem)) def identity_hom(self): """ Return the identity homomorphism on ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> M = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)] >>> M.identity_hom() Matrix([ [1, 0], : QQ[x]**2/<[1, 2], [1, x]> -> QQ[x]**2/<[1, 2], [1, x]> [0, 1]]) """ return self.base.identity_hom().quotient_codomain( self.killed_module).quotient_domain(self.killed_module) def quotient_hom(self): """ Return the quotient homomorphism to ``self``. That is, return a homomorphism representing the natural map from ``self.base`` to ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> M = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)] >>> M.quotient_hom() Matrix([ [1, 0], : QQ[x]**2 -> QQ[x]**2/<[1, 2], [1, x]> [0, 1]]) """ return self.base.identity_hom().quotient_codomain( self.killed_module)
10a7f344b23f4c99dc2b996c0d32375357b05c2b66cbd9b1e317c6ca6bb0cf93
""" Computations with homomorphisms of modules and rings. This module implements classes for representing homomorphisms of rings and their modules. Instead of instantiating the classes directly, you should use the function ``homomorphism(from, to, matrix)`` to create homomorphism objects. """ from __future__ import print_function, division from sympy.polys.agca.modules import (Module, FreeModule, QuotientModule, SubModule, SubQuotientModule) from sympy.polys.polyerrors import CoercionFailed # The main computational task for module homomorphisms is kernels. # For this reason, the concrete classes are organised by domain module type. class ModuleHomomorphism(object): """ Abstract base class for module homomoprhisms. Do not instantiate. Instead, use the ``homomorphism`` function: >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> homomorphism(F, F, [[1, 0], [0, 1]]) Matrix([ [1, 0], : QQ[x]**2 -> QQ[x]**2 [0, 1]]) Attributes: - ring - the ring over which we are considering modules - domain - the domain module - codomain - the codomain module - _ker - cached kernel - _img - cached image Non-implemented methods: - _kernel - _image - _restrict_domain - _restrict_codomain - _quotient_domain - _quotient_codomain - _apply - _mul_scalar - _compose - _add """ def __init__(self, domain, codomain): if not isinstance(domain, Module): raise TypeError('Source must be a module, got %s' % domain) if not isinstance(codomain, Module): raise TypeError('Target must be a module, got %s' % codomain) if domain.ring != codomain.ring: raise ValueError('Source and codomain must be over same ring, ' 'got %s != %s' % (domain, codomain)) self.domain = domain self.codomain = codomain self.ring = domain.ring self._ker = None self._img = None def kernel(self): r""" Compute the kernel of ``self``. That is, if ``self`` is the homomorphism `\phi: M \to N`, then compute `ker(\phi) = \{x \in M | \phi(x) = 0\}`. This is a submodule of `M`. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> homomorphism(F, F, [[1, 0], [x, 0]]).kernel() <[x, -1]> """ if self._ker is None: self._ker = self._kernel() return self._ker def image(self): r""" Compute the image of ``self``. That is, if ``self`` is the homomorphism `\phi: M \to N`, then compute `im(\phi) = \{\phi(x) | x \in M \}`. This is a submodule of `N`. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> homomorphism(F, F, [[1, 0], [x, 0]]).image() == F.submodule([1, 0]) True """ if self._img is None: self._img = self._image() return self._img def _kernel(self): """Compute the kernel of ``self``.""" raise NotImplementedError def _image(self): """Compute the image of ``self``.""" raise NotImplementedError def _restrict_domain(self, sm): """Implementation of domain restriction.""" raise NotImplementedError def _restrict_codomain(self, sm): """Implementation of codomain restriction.""" raise NotImplementedError def _quotient_domain(self, sm): """Implementation of domain quotient.""" raise NotImplementedError def _quotient_codomain(self, sm): """Implementation of codomain quotient.""" raise NotImplementedError def restrict_domain(self, sm): """ Return ``self``, with the domain restricted to ``sm``. Here ``sm`` has to be a submodule of ``self.domain``. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) >>> h Matrix([ [1, x], : QQ[x]**2 -> QQ[x]**2 [0, 0]]) >>> h.restrict_domain(F.submodule([1, 0])) Matrix([ [1, x], : <[1, 0]> -> QQ[x]**2 [0, 0]]) This is the same as just composing on the right with the submodule inclusion: >>> h * F.submodule([1, 0]).inclusion_hom() Matrix([ [1, x], : <[1, 0]> -> QQ[x]**2 [0, 0]]) """ if not self.domain.is_submodule(sm): raise ValueError('sm must be a submodule of %s, got %s' % (self.domain, sm)) if sm == self.domain: return self return self._restrict_domain(sm) def restrict_codomain(self, sm): """ Return ``self``, with codomain restricted to to ``sm``. Here ``sm`` has to be a submodule of ``self.codomain`` containing the image. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) >>> h Matrix([ [1, x], : QQ[x]**2 -> QQ[x]**2 [0, 0]]) >>> h.restrict_codomain(F.submodule([1, 0])) Matrix([ [1, x], : QQ[x]**2 -> <[1, 0]> [0, 0]]) """ if not sm.is_submodule(self.image()): raise ValueError('the image %s must contain sm, got %s' % (self.image(), sm)) if sm == self.codomain: return self return self._restrict_codomain(sm) def quotient_domain(self, sm): """ Return ``self`` with domain replaced by ``domain/sm``. Here ``sm`` must be a submodule of ``self.kernel()``. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) >>> h Matrix([ [1, x], : QQ[x]**2 -> QQ[x]**2 [0, 0]]) >>> h.quotient_domain(F.submodule([-x, 1])) Matrix([ [1, x], : QQ[x]**2/<[-x, 1]> -> QQ[x]**2 [0, 0]]) """ if not self.kernel().is_submodule(sm): raise ValueError('kernel %s must contain sm, got %s' % (self.kernel(), sm)) if sm.is_zero(): return self return self._quotient_domain(sm) def quotient_codomain(self, sm): """ Return ``self`` with codomain replaced by ``codomain/sm``. Here ``sm`` must be a submodule of ``self.codomain``. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) >>> h Matrix([ [1, x], : QQ[x]**2 -> QQ[x]**2 [0, 0]]) >>> h.quotient_codomain(F.submodule([1, 1])) Matrix([ [1, x], : QQ[x]**2 -> QQ[x]**2/<[1, 1]> [0, 0]]) This is the same as composing with the quotient map on the left: >>> (F/[(1, 1)]).quotient_hom() * h Matrix([ [1, x], : QQ[x]**2 -> QQ[x]**2/<[1, 1]> [0, 0]]) """ if not self.codomain.is_submodule(sm): raise ValueError('sm must be a submodule of codomain %s, got %s' % (self.codomain, sm)) if sm.is_zero(): return self return self._quotient_codomain(sm) def _apply(self, elem): """Apply ``self`` to ``elem``.""" raise NotImplementedError def __call__(self, elem): return self.codomain.convert(self._apply(self.domain.convert(elem))) def _compose(self, oth): """ Compose ``self`` with ``oth``, that is, return the homomorphism obtained by first applying then ``self``, then ``oth``. (This method is private since in this syntax, it is non-obvious which homomorphism is executed first.) """ raise NotImplementedError def _mul_scalar(self, c): """Scalar multiplication. ``c`` is guaranteed in self.ring.""" raise NotImplementedError def _add(self, oth): """ Homomorphism addition. ``oth`` is guaranteed to be a homomorphism with same domain/codomain. """ raise NotImplementedError def _check_hom(self, oth): """Helper to check that oth is a homomorphism with same domain/codomain.""" if not isinstance(oth, ModuleHomomorphism): return False return oth.domain == self.domain and oth.codomain == self.codomain def __mul__(self, oth): if isinstance(oth, ModuleHomomorphism) and self.domain == oth.codomain: return oth._compose(self) try: return self._mul_scalar(self.ring.convert(oth)) except CoercionFailed: return NotImplemented # NOTE: _compose will never be called from rmul __rmul__ = __mul__ def __truediv__(self, oth): try: return self._mul_scalar(1/self.ring.convert(oth)) except CoercionFailed: return NotImplemented def __add__(self, oth): if self._check_hom(oth): return self._add(oth) return NotImplemented def __sub__(self, oth): if self._check_hom(oth): return self._add(oth._mul_scalar(self.ring.convert(-1))) return NotImplemented def is_injective(self): """ Return True if ``self`` is injective. That is, check if the elements of the domain are mapped to the same codomain element. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) >>> h.is_injective() False >>> h.quotient_domain(h.kernel()).is_injective() True """ return self.kernel().is_zero() def is_surjective(self): """ Return True if ``self`` is surjective. That is, check if every element of the codomain has at least one preimage. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) >>> h.is_surjective() False >>> h.restrict_codomain(h.image()).is_surjective() True """ return self.image() == self.codomain def is_isomorphism(self): """ Return True if ``self`` is an isomorphism. That is, check if every element of the codomain has precisely one preimage. Equivalently, ``self`` is both injective and surjective. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) >>> h = h.restrict_codomain(h.image()) >>> h.is_isomorphism() False >>> h.quotient_domain(h.kernel()).is_isomorphism() True """ return self.is_injective() and self.is_surjective() def is_zero(self): """ Return True if ``self`` is a zero morphism. That is, check if every element of the domain is mapped to zero under self. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) >>> h.is_zero() False >>> h.restrict_domain(F.submodule()).is_zero() True >>> h.quotient_codomain(h.image()).is_zero() True """ return self.image().is_zero() def __eq__(self, oth): try: return (self - oth).is_zero() except TypeError: return False def __ne__(self, oth): return not (self == oth) class MatrixHomomorphism(ModuleHomomorphism): r""" Helper class for all homomoprhisms which are expressed via a matrix. That is, for such homomorphisms ``domain`` is contained in a module generated by finitely many elements `e_1, \ldots, e_n`, so that the homomorphism is determined uniquely by its action on the `e_i`. It can thus be represented as a vector of elements of the codomain module, or potentially a supermodule of the codomain module (and hence conventionally as a matrix, if there is a similar interpretation for elements of the codomain module). Note that this class does *not* assume that the `e_i` freely generate a submodule, nor that ``domain`` is even all of this submodule. It exists only to unify the interface. Do not instantiate. Attributes: - matrix - the list of images determining the homomorphism. NOTE: the elements of matrix belong to either self.codomain or self.codomain.container Still non-implemented methods: - kernel - _apply """ def __init__(self, domain, codomain, matrix): ModuleHomomorphism.__init__(self, domain, codomain) if len(matrix) != domain.rank: raise ValueError('Need to provide %s elements, got %s' % (domain.rank, len(matrix))) converter = self.codomain.convert if isinstance(self.codomain, (SubModule, SubQuotientModule)): converter = self.codomain.container.convert self.matrix = tuple(converter(x) for x in matrix) def _sympy_matrix(self): """Helper function which returns a sympy matrix ``self.matrix``.""" from sympy.matrices import Matrix c = lambda x: x if isinstance(self.codomain, (QuotientModule, SubQuotientModule)): c = lambda x: x.data return Matrix([[self.ring.to_sympy(y) for y in c(x)] for x in self.matrix]).T def __repr__(self): lines = repr(self._sympy_matrix()).split('\n') t = " : %s -> %s" % (self.domain, self.codomain) s = ' '*len(t) n = len(lines) for i in range(n // 2): lines[i] += s lines[n // 2] += t for i in range(n//2 + 1, n): lines[i] += s return '\n'.join(lines) def _restrict_domain(self, sm): """Implementation of domain restriction.""" return SubModuleHomomorphism(sm, self.codomain, self.matrix) def _restrict_codomain(self, sm): """Implementation of codomain restriction.""" return self.__class__(self.domain, sm, self.matrix) def _quotient_domain(self, sm): """Implementation of domain quotient.""" return self.__class__(self.domain/sm, self.codomain, self.matrix) def _quotient_codomain(self, sm): """Implementation of codomain quotient.""" Q = self.codomain/sm converter = Q.convert if isinstance(self.codomain, SubModule): converter = Q.container.convert return self.__class__(self.domain, self.codomain/sm, [converter(x) for x in self.matrix]) def _add(self, oth): return self.__class__(self.domain, self.codomain, [x + y for x, y in zip(self.matrix, oth.matrix)]) def _mul_scalar(self, c): return self.__class__(self.domain, self.codomain, [c*x for x in self.matrix]) def _compose(self, oth): return self.__class__(self.domain, oth.codomain, [oth(x) for x in self.matrix]) class FreeModuleHomomorphism(MatrixHomomorphism): """ Concrete class for homomorphisms with domain a free module or a quotient thereof. Do not instantiate; the constructor does not check that your data is well defined. Use the ``homomorphism`` function instead: >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> homomorphism(F, F, [[1, 0], [0, 1]]) Matrix([ [1, 0], : QQ[x]**2 -> QQ[x]**2 [0, 1]]) """ def _apply(self, elem): if isinstance(self.domain, QuotientModule): elem = elem.data return sum(x * e for x, e in zip(elem, self.matrix)) def _image(self): return self.codomain.submodule(*self.matrix) def _kernel(self): # The domain is either a free module or a quotient thereof. # It does not matter if it is a quotient, because that won't increase # the kernel. # Our generators {e_i} are sent to the matrix entries {b_i}. # The kernel is essentially the syzygy module of these {b_i}. syz = self.image().syzygy_module() return self.domain.submodule(*syz.gens) class SubModuleHomomorphism(MatrixHomomorphism): """ Concrete class for homomorphism with domain a submodule of a free module or a quotient thereof. Do not instantiate; the constructor does not check that your data is well defined. Use the ``homomorphism`` function instead: >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> M = QQ.old_poly_ring(x).free_module(2)*x >>> homomorphism(M, M, [[1, 0], [0, 1]]) Matrix([ [1, 0], : <[x, 0], [0, x]> -> <[x, 0], [0, x]> [0, 1]]) """ def _apply(self, elem): if isinstance(self.domain, SubQuotientModule): elem = elem.data return sum(x * e for x, e in zip(elem, self.matrix)) def _image(self): return self.codomain.submodule(*[self(x) for x in self.domain.gens]) def _kernel(self): syz = self.image().syzygy_module() return self.domain.submodule( *[sum(xi*gi for xi, gi in zip(s, self.domain.gens)) for s in syz.gens]) def homomorphism(domain, codomain, matrix): r""" Create a homomorphism object. This function tries to build a homomorphism from ``domain`` to ``codomain`` via the matrix ``matrix``. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> R = QQ.old_poly_ring(x) >>> T = R.free_module(2) If ``domain`` is a free module generated by `e_1, \ldots, e_n`, then ``matrix`` should be an n-element iterable `(b_1, \ldots, b_n)` where the `b_i` are elements of ``codomain``. The constructed homomorphism is the unique homomorphism sending `e_i` to `b_i`. >>> F = R.free_module(2) >>> h = homomorphism(F, T, [[1, x], [x**2, 0]]) >>> h Matrix([ [1, x**2], : QQ[x]**2 -> QQ[x]**2 [x, 0]]) >>> h([1, 0]) [1, x] >>> h([0, 1]) [x**2, 0] >>> h([1, 1]) [x**2 + 1, x] If ``domain`` is a submodule of a free module, them ``matrix`` determines a homomoprhism from the containing free module to ``codomain``, and the homomorphism returned is obtained by restriction to ``domain``. >>> S = F.submodule([1, 0], [0, x]) >>> homomorphism(S, T, [[1, x], [x**2, 0]]) Matrix([ [1, x**2], : <[1, 0], [0, x]> -> QQ[x]**2 [x, 0]]) If ``domain`` is a (sub)quotient `N/K`, then ``matrix`` determines a homomorphism from `N` to ``codomain``. If the kernel contains `K`, this homomorphism descends to ``domain`` and is returned; otherwise an exception is raised. >>> homomorphism(S/[(1, 0)], T, [0, [x**2, 0]]) Matrix([ [0, x**2], : <[1, 0] + <[1, 0]>, [0, x] + <[1, 0]>, [1, 0] + <[1, 0]>> -> QQ[x]**2 [0, 0]]) >>> homomorphism(S/[(0, x)], T, [0, [x**2, 0]]) Traceback (most recent call last): ... ValueError: kernel <[1, 0], [0, 0]> must contain sm, got <[0,x]> """ def freepres(module): """ Return a tuple ``(F, S, Q, c)`` where ``F`` is a free module, ``S`` is a submodule of ``F``, and ``Q`` a submodule of ``S``, such that ``module = S/Q``, and ``c`` is a conversion function. """ if isinstance(module, FreeModule): return module, module, module.submodule(), lambda x: module.convert(x) if isinstance(module, QuotientModule): return (module.base, module.base, module.killed_module, lambda x: module.convert(x).data) if isinstance(module, SubQuotientModule): return (module.base.container, module.base, module.killed_module, lambda x: module.container.convert(x).data) # an ordinary submodule return (module.container, module, module.submodule(), lambda x: module.container.convert(x)) SF, SS, SQ, _ = freepres(domain) TF, TS, TQ, c = freepres(codomain) # NOTE this is probably a bit inefficient (redundant checks) return FreeModuleHomomorphism(SF, TF, [c(x) for x in matrix] ).restrict_domain(SS).restrict_codomain(TS ).quotient_codomain(TQ).quotient_domain(SQ)
bedd847fc6ea993e4290e374592f56c19e0f0ed57f0a4ffaaa06487635e7620c
from sympy import Add, Basic, symbols, Symbol, And from sympy.core.symbol import Str from sympy.unify.core import Compound, Variable from sympy.unify.usympy import (deconstruct, construct, unify, is_associative, is_commutative) from sympy.abc import x, y, z, n def test_deconstruct(): expr = Basic(1, 2, 3) expected = Compound(Basic, (1, 2, 3)) assert deconstruct(expr) == expected assert deconstruct(1) == 1 assert deconstruct(x) == x assert deconstruct(x, variables=(x,)) == Variable(x) assert deconstruct(Add(1, x, evaluate=False)) == Compound(Add, (1, x)) assert deconstruct(Add(1, x, evaluate=False), variables=(x,)) == \ Compound(Add, (1, Variable(x))) def test_construct(): expr = Compound(Basic, (1, 2, 3)) expected = Basic(1, 2, 3) assert construct(expr) == expected def test_nested(): expr = Basic(1, Basic(2), 3) cmpd = Compound(Basic, (1, Compound(Basic, (2,)), 3)) assert deconstruct(expr) == cmpd assert construct(cmpd) == expr def test_unify(): expr = Basic(1, 2, 3) a, b, c = map(Symbol, 'abc') pattern = Basic(a, b, c) assert list(unify(expr, pattern, {}, (a, b, c))) == [{a: 1, b: 2, c: 3}] assert list(unify(expr, pattern, variables=(a, b, c))) == \ [{a: 1, b: 2, c: 3}] def test_unify_variables(): assert list(unify(Basic(1, 2), Basic(1, x), {}, variables=(x,))) == [{x: 2}] def test_s_input(): expr = Basic(1, 2) a, b = map(Symbol, 'ab') pattern = Basic(a, b) assert list(unify(expr, pattern, {}, (a, b))) == [{a: 1, b: 2}] assert list(unify(expr, pattern, {a: 5}, (a, b))) == [] def iterdicteq(a, b): a = tuple(a) b = tuple(b) return len(a) == len(b) and all(x in b for x in a) def test_unify_commutative(): expr = Add(1, 2, 3, evaluate=False) a, b, c = map(Symbol, 'abc') pattern = Add(a, b, c, evaluate=False) result = tuple(unify(expr, pattern, {}, (a, b, c))) expected = ({a: 1, b: 2, c: 3}, {a: 1, b: 3, c: 2}, {a: 2, b: 1, c: 3}, {a: 2, b: 3, c: 1}, {a: 3, b: 1, c: 2}, {a: 3, b: 2, c: 1}) assert iterdicteq(result, expected) def test_unify_iter(): expr = Add(1, 2, 3, evaluate=False) a, b, c = map(Symbol, 'abc') pattern = Add(a, c, evaluate=False) assert is_associative(deconstruct(pattern)) assert is_commutative(deconstruct(pattern)) result = list(unify(expr, pattern, {}, (a, c))) expected = [{a: 1, c: Add(2, 3, evaluate=False)}, {a: 1, c: Add(3, 2, evaluate=False)}, {a: 2, c: Add(1, 3, evaluate=False)}, {a: 2, c: Add(3, 1, evaluate=False)}, {a: 3, c: Add(1, 2, evaluate=False)}, {a: 3, c: Add(2, 1, evaluate=False)}, {a: Add(1, 2, evaluate=False), c: 3}, {a: Add(2, 1, evaluate=False), c: 3}, {a: Add(1, 3, evaluate=False), c: 2}, {a: Add(3, 1, evaluate=False), c: 2}, {a: Add(2, 3, evaluate=False), c: 1}, {a: Add(3, 2, evaluate=False), c: 1}] assert iterdicteq(result, expected) def test_hard_match(): from sympy import sin, cos expr = sin(x) + cos(x)**2 p, q = map(Symbol, 'pq') pattern = sin(p) + cos(p)**2 assert list(unify(expr, pattern, {}, (p, q))) == [{p: x}] def test_matrix(): from sympy import MatrixSymbol X = MatrixSymbol('X', n, n) Y = MatrixSymbol('Y', 2, 2) Z = MatrixSymbol('Z', 2, 3) assert list(unify(X, Y, {}, variables=[n, Str('X')])) == [{Str('X'): Str('Y'), n: 2}] assert list(unify(X, Z, {}, variables=[n, Str('X')])) == [] def test_non_frankenAdds(): # the is_commutative property used to fail because of Basic.__new__ # This caused is_commutative and str calls to fail expr = x+y*2 rebuilt = construct(deconstruct(expr)) # Ensure that we can run these commands without causing an error str(rebuilt) rebuilt.is_commutative def test_FiniteSet_commutivity(): from sympy import FiniteSet a, b, c, x, y = symbols('a,b,c,x,y') s = FiniteSet(a, b, c) t = FiniteSet(x, y) variables = (x, y) assert {x: FiniteSet(a, c), y: b} in tuple(unify(s, t, variables=variables)) def test_FiniteSet_complex(): from sympy import FiniteSet a, b, c, x, y, z = symbols('a,b,c,x,y,z') expr = FiniteSet(Basic(1, x), y, Basic(x, z)) pattern = FiniteSet(a, Basic(x, b)) variables = a, b expected = tuple([{b: 1, a: FiniteSet(y, Basic(x, z))}, {b: z, a: FiniteSet(y, Basic(1, x))}]) assert iterdicteq(unify(expr, pattern, variables=variables), expected) def test_and(): variables = x, y expected = tuple([{x: z > 0, y: n < 3}]) assert iterdicteq(unify((z>0) & (n<3), And(x, y), variables=variables), expected) def test_Union(): from sympy import Interval assert list(unify(Interval(0, 1) + Interval(10, 11), Interval(0, 1) + Interval(12, 13), variables=(Interval(12, 13),))) def test_is_commutative(): assert is_commutative(deconstruct(x+y)) assert is_commutative(deconstruct(x*y)) assert not is_commutative(deconstruct(x**y)) def test_commutative_in_commutative(): from sympy.abc import a,b,c,d from sympy import sin, cos eq = sin(3)*sin(4)*sin(5) + 4*cos(3)*cos(4) pat = a*cos(b)*cos(c) + d*sin(b)*sin(c) assert next(unify(eq, pat, variables=(a,b,c,d)))
88c948be4d41132100ce55db291728d3f71eaafae5cd7fb8cb1411909b56160f
from sympy import sin, cos, pi, S, sqrt from sympy.testing.pytest import raises from sympy.vector.coordsysrect import CoordSys3D from sympy.vector.integrals import ParametricIntegral, vector_integrate from sympy.vector.parametricregion import ParametricRegion from sympy.vector.implicitregion import ImplicitRegion from sympy.abc import x, y, z, u, v, r, t, theta, phi from sympy.geometry import Point, Segment, Curve, Circle, Polygon, Plane C = CoordSys3D('C') def test_parametric_lineintegrals(): halfcircle = ParametricRegion((4*cos(theta), 4*sin(theta)), (theta, -pi/2, pi/2)) assert ParametricIntegral(C.x*C.y**4, halfcircle) == S(8192)/5 curve = ParametricRegion((t, t**2, t**3), (t, 0, 1)) field1 = 8*C.x**2*C.y*C.z*C.i + 5*C.z*C.j - 4*C.x*C.y*C.k assert ParametricIntegral(field1, curve) == 1 line = ParametricRegion((4*t - 1, 2 - 2*t, t), (t, 0, 1)) assert ParametricIntegral(C.x*C.z*C.i - C.y*C.z*C.k, line) == 3 assert ParametricIntegral(4*C.x**3, ParametricRegion((1, t), (t, 0, 2))) == 8 helix = ParametricRegion((cos(t), sin(t), 3*t), (t, 0, 4*pi)) assert ParametricIntegral(C.x*C.y*C.z, helix) == -3*sqrt(10)*pi field2 = C.y*C.i + C.z*C.j + C.z*C.k assert ParametricIntegral(field2, ParametricRegion((cos(t), sin(t), t**2), (t, 0, pi))) == -5*pi/2 + pi**4/2 def test_parametric_surfaceintegrals(): semisphere = ParametricRegion((2*sin(phi)*cos(theta), 2*sin(phi)*sin(theta), 2*cos(phi)),\ (theta, 0, 2*pi), (phi, 0, pi/2)) assert ParametricIntegral(C.z, semisphere) == 8*pi cylinder = ParametricRegion((sqrt(3)*cos(theta), sqrt(3)*sin(theta), z), (z, 0, 6), (theta, 0, 2*pi)) assert ParametricIntegral(C.y, cylinder) == 0 cone = ParametricRegion((v*cos(u), v*sin(u), v), (u, 0, 2*pi), (v, 0, 1)) assert ParametricIntegral(C.x*C.i + C.y*C.j + C.z**4*C.k, cone) == pi/3 triangle1 = ParametricRegion((x, y), (x, 0, 2), (y, 0, 10 - 5*x)) triangle2 = ParametricRegion((x, y), (y, 0, 10 - 5*x), (x, 0, 2)) assert ParametricIntegral(-15.6*C.y*C.k, triangle1) == ParametricIntegral(-15.6*C.y*C.k, triangle2) assert ParametricIntegral(C.z, triangle1) == 10*C.z def test_parametric_volumeintegrals(): cube = ParametricRegion((x, y, z), (x, 0, 1), (y, 0, 1), (z, 0, 1)) assert ParametricIntegral(1, cube) == 1 solidsphere1 = ParametricRegion((r*sin(phi)*cos(theta), r*sin(phi)*sin(theta), r*cos(phi)),\ (r, 0, 2), (theta, 0, 2*pi), (phi, 0, pi)) solidsphere2 = ParametricRegion((r*sin(phi)*cos(theta), r*sin(phi)*sin(theta), r*cos(phi)),\ (r, 0, 2), (phi, 0, pi), (theta, 0, 2*pi)) assert ParametricIntegral(C.x**2 + C.y**2, solidsphere1) == -256*pi/15 assert ParametricIntegral(C.x**2 + C.y**2, solidsphere2) == 256*pi/15 region_under_plane1 = ParametricRegion((x, y, z), (x, 0, 3), (y, 0, -2*x/3 + 2),\ (z, 0, 6 - 2*x - 3*y)) region_under_plane2 = ParametricRegion((x, y, z), (x, 0, 3), (z, 0, 6 - 2*x - 3*y),\ (y, 0, -2*x/3 + 2)) assert ParametricIntegral(C.x*C.i + C.j - 100*C.k, region_under_plane1) == \ ParametricIntegral(C.x*C.i + C.j - 100*C.k, region_under_plane2) assert ParametricIntegral(2*C.x, region_under_plane2) == -9 def test_vector_integrate(): halfdisc = ParametricRegion((r*cos(theta), r* sin(theta)), (r, -2, 2), (theta, 0, pi)) assert vector_integrate(C.x**2, halfdisc) == 4*pi vector_integrate(C.x, ParametricRegion((t, t**2), (t, 2, 3))) == -17*sqrt(17)/12 + 37*sqrt(37)/12 assert vector_integrate(C.y**3*C.z, (C.x, 0, 3), (C.y, -1, 4)) == 765*C.z/4 s1 = Segment(Point(0, 0), Point(0, 1)) assert vector_integrate(-15*C.y, s1) == S(-15)/2 s2 = Segment(Point(4, 3, 9), Point(1, 1, 7)) assert vector_integrate(C.y*C.i, s2) == -6 curve = Curve((sin(t), cos(t)), (t, 0, 2)) assert vector_integrate(5*C.z, curve) == 10*C.z c1 = Circle(Point(2, 3), 6) assert vector_integrate(C.x*C.y, c1) == 72*pi c2 = Circle(Point(0, 0), Point(1, 1), Point(1, 0)) assert vector_integrate(1, c2) == c2.circumference triangle = Polygon((0, 0), (1, 0), (1, 1)) assert vector_integrate(C.x*C.i - 14*C.y*C.j, triangle) == 0 p1, p2, p3, p4 = [(0, 0), (1, 0), (5, 1), (0, 1)] poly = Polygon(p1, p2, p3, p4) assert vector_integrate(-23*C.z, poly) == -161*C.z - 23*sqrt(17)*C.z point = Point(2, 3) assert vector_integrate(C.i*C.y - C.z, point) == ParametricIntegral(C.y*C.i, ParametricRegion((2, 3))) c3 = ImplicitRegion((x, y), x**2 + y**2 - 4) assert vector_integrate(45, c3) == 360*pi c4 = ImplicitRegion((x, y), (x - 3)**2 + (y - 4)**2 - 9) assert vector_integrate(1, c4) == 12*pi pl = Plane(Point(1, 1, 1), Point(2, 3, 4), Point(2, 2, 2)) raises(ValueError, lambda: vector_integrate(C.x*C.z*C.i + C.k, pl))
36a3f17a0b1b663a77d4799a16f5628e2f1311b43805c7e896e76964facbea14
from sympy import Eq, S, sqrt from sympy.abc import x, y, z, s, t from sympy.sets import FiniteSet, EmptySet from sympy.geometry import Point from sympy.vector import ImplicitRegion from sympy.testing.pytest import raises def test_ImplicitRegion(): ellipse = ImplicitRegion((x, y), (x**2/4 + y**2/16 - 1)) assert ellipse.equation == x**2/4 + y**2/16 - 1 assert ellipse.variables == (x, y) assert ellipse.degree == 2 r = ImplicitRegion((x, y, z), Eq(x**4 + y**2 - x*y, 6)) assert r.equation == x**4 + y**2 - x*y - 6 assert r.variables == (x, y, z) assert r.degree == 4 def test_regular_point(): r1 = ImplicitRegion((x,), x**2 - 16) r1.regular_point() == (-4,) c1 = ImplicitRegion((x, y), x**2 + y**2 - 4) c1.regular_point() == (2, 0) c2 = ImplicitRegion((x, y), (x - S(5)/2)**2 + y**2 - (S(1)/4)**2) c2.regular_point() == (11/4, 0) c3 = ImplicitRegion((x, y), (y - 5)**2 - 16*(x - 5)) c3.regular_point() == (5, 5) r2 = ImplicitRegion((x, y), x**2 - 4*x*y - 3*y**2 + 4*x + 8*y - 5) r2.regular_point == (4/7, 13/21) r3 = ImplicitRegion((x, y), x**2 - 2*x*y + 3*y**2 - 2*x - 5*y + 3/2) raises(ValueError, lambda: r3.regular_point()) def test_singular_points_and_multiplicty(): r1 = ImplicitRegion((x, y, z), Eq(x + y + z, 0)) assert r1.singular_points() == FiniteSet((-y - z, y, z)) assert r1.multiplicity((0, 0, 0)) == 1 assert r1.multiplicity((-y - z, y, z)) == 1 r2 = ImplicitRegion((x, y, z), x*y*z + y**4 -x**2*z**2) assert r2.singular_points() == FiniteSet((0, 0, z), ((-y*sqrt(4*y**2 + 1)/2 + y/2)/z, y, z),\ ((y*sqrt(4*y**2 + 1)/2 + y/2)/z, y, z)) assert r2.multiplicity((0, 0, 0)) == 3 assert r2.multiplicity((0, 0, 6)) == 2 r3 = ImplicitRegion((x, y, z), z**2 - x**2 - y**2) assert r3.singular_points() == FiniteSet((0, 0, 0)) assert r3.multiplicity((0, 0, 0)) == 2 r4 = ImplicitRegion((x, y), x**2 + y**2 - 2*x) assert r4.singular_points() == EmptySet assert r4.multiplicity(Point(1, 3)) == 0 def test_rational_parametrization(): p = ImplicitRegion((x,), x - 2) assert p.rational_parametrization() == (x - 2,) line = ImplicitRegion((x, y), Eq(y, 3*x + 2)) assert line.rational_parametrization() == (x, 3*x + 2) circle1 = ImplicitRegion((x, y), (x-2)**2 + (y+3)**2 - 4) assert circle1.rational_parametrization(parameters=t) == (4*t/(t**2 + 1) + 2, 4*t**2/(t**2 + 1) - 5) circle2 = ImplicitRegion((x, y), (x - S.Half)**2 + y**2 - (S(1)/2)**2) assert circle2.rational_parametrization(parameters=t) == (t/(t**2 + 1) + S(1)/2, t**2/(t**2 + 1) - S(1)/2) circle3 = ImplicitRegion((x, y), Eq(x**2 + y**2, 2*x)) assert circle3.rational_parametrization(parameters=(t,)) == (2*t/(t**2 + 1) + 1, 2*t**2/(t**2 + 1) - 1) parabola = ImplicitRegion((x, y), (y - 3)**2 - 4*(x + 6)) assert parabola.rational_parametrization(t) == (-6 + 4/t**2, 3 + 4/t) rect_hyperbola = ImplicitRegion((x, y), x*y - 1) assert rect_hyperbola.rational_parametrization(t) == (-1 + (t + 1)/t, t) cubic_curve = ImplicitRegion((x, y), x**3 + x**2 - y**2) assert cubic_curve.rational_parametrization(parameters=(t)) == (t**2 - 1, t*(t**2 - 1)) cuspidal = ImplicitRegion((x, y), (x**3 - y**2)) assert cuspidal.rational_parametrization(t) == (t**2, t**3) I = ImplicitRegion((x, y), x**3 + x**2 - y**2) assert I.rational_parametrization(t) == (t**2 - 1, t*(t**2 - 1)) sphere = ImplicitRegion((x, y, z), Eq(x**2 + y**2 + z**2, 2*x)) assert sphere.rational_parametrization(parameters=(s, t)) == (2/(s**2 + t**2 + 1), 2*t/(s**2 + t**2 + 1), 2*s/(s**2 + t**2 + 1)) conic = ImplicitRegion((x, y), Eq(x**2 + 4*x*y + 3*y**2 + x - y + 10, 0)) conic.rational_parametrization(t) == (17/2 + 4/(3*t**2 + 4*t + 1), 4*t/(3*t**2 + 4*t + 1) - 11/2) r1 = ImplicitRegion((x, y), y**2 - x**3 + x) raises(NotImplementedError, lambda: r1.rational_parametrization()) r2 = ImplicitRegion((x, y), y**2 - x**3 - x**2 + 1) raises(NotImplementedError, lambda: r2.rational_parametrization())
0a33f63ec0ddeed5b02f4c2573d56ba708f02732315d819e08aeb38f3b043720
# -*- coding: utf-8 -*- from sympy import Integral, latex, Function from sympy import pretty as xpretty from sympy.vector import CoordSys3D, Vector, express from sympy.abc import a, b, c from sympy.testing.pytest import XFAIL def pretty(expr): """ASCII pretty-printing""" return xpretty(expr, use_unicode=False, wrap_line=False) def upretty(expr): """Unicode pretty-printing""" return xpretty(expr, use_unicode=True, wrap_line=False) # Initialize the basic and tedious vector/dyadic expressions # needed for testing. # Some of the pretty forms shown denote how the expressions just # above them should look with pretty printing. N = CoordSys3D('N') C = N.orient_new_axis('C', a, N.k) # type: ignore v = [] d = [] v.append(Vector.zero) v.append(N.i) # type: ignore v.append(-N.i) # type: ignore v.append(N.i + N.j) # type: ignore v.append(a*N.i) # type: ignore v.append(a*N.i - b*N.j) # type: ignore v.append((a**2 + N.x)*N.i + N.k) # type: ignore v.append((a**2 + b)*N.i + 3*(C.y - c)*N.k) # type: ignore f = Function('f') v.append(N.j - (Integral(f(b)) - C.x**2)*N.k) # type: ignore upretty_v_8 = """\ ⎛ 2 ⌠ ⎞ \n\ j_N + ⎜x_C - ⎮ f(b) db⎟ k_N\n\ ⎝ ⌡ ⎠ \ """ pretty_v_8 = """\ j_N + / / \\\n\ | 2 | |\n\ |x_C - | f(b) db|\n\ | | |\n\ \\ / / \ """ v.append(N.i + C.k) # type: ignore v.append(express(N.i, C)) # type: ignore v.append((a**2 + b)*N.i + (Integral(f(b)))*N.k) # type: ignore upretty_v_11 = """\ ⎛ 2 ⎞ ⎛⌠ ⎞ \n\ ⎝a + b⎠ i_N + ⎜⎮ f(b) db⎟ k_N\n\ ⎝⌡ ⎠ \ """ pretty_v_11 = """\ / 2 \\ + / / \\\n\ \\a + b/ i_N| | |\n\ | | f(b) db|\n\ | | |\n\ \\/ / \ """ for x in v: d.append(x | N.k) # type: ignore s = 3*N.x**2*C.y # type: ignore upretty_s = """\ 2\n\ 3⋅y_C⋅x_N \ """ pretty_s = """\ 2\n\ 3*y_C*x_N \ """ # This is the pretty form for ((a**2 + b)*N.i + 3*(C.y - c)*N.k) | N.k upretty_d_7 = """\ ⎛ 2 ⎞ \n\ ⎝a + b⎠ (i_N|k_N) + (3⋅y_C - 3⋅c) (k_N|k_N)\ """ pretty_d_7 = """\ / 2 \\ (i_N|k_N) + (3*y_C - 3*c) (k_N|k_N)\n\ \\a + b/ \ """ def test_str_printing(): assert str(v[0]) == '0' assert str(v[1]) == 'N.i' assert str(v[2]) == '(-1)*N.i' assert str(v[3]) == 'N.i + N.j' assert str(v[8]) == 'N.j + (C.x**2 - Integral(f(b), b))*N.k' assert str(v[9]) == 'C.k + N.i' assert str(s) == '3*C.y*N.x**2' assert str(d[0]) == '0' assert str(d[1]) == '(N.i|N.k)' assert str(d[4]) == 'a*(N.i|N.k)' assert str(d[5]) == 'a*(N.i|N.k) + (-b)*(N.j|N.k)' assert str(d[8]) == ('(N.j|N.k) + (C.x**2 - ' + 'Integral(f(b), b))*(N.k|N.k)') @XFAIL def test_pretty_printing_ascii(): assert pretty(v[0]) == '0' assert pretty(v[1]) == 'i_N' assert pretty(v[5]) == '(a) i_N + (-b) j_N' assert pretty(v[8]) == pretty_v_8 assert pretty(v[2]) == '(-1) i_N' assert pretty(v[11]) == pretty_v_11 assert pretty(s) == pretty_s assert pretty(d[0]) == '(0|0)' assert pretty(d[5]) == '(a) (i_N|k_N) + (-b) (j_N|k_N)' assert pretty(d[7]) == pretty_d_7 assert pretty(d[10]) == '(cos(a)) (i_C|k_N) + (-sin(a)) (j_C|k_N)' def test_pretty_print_unicode_v(): assert upretty(v[0]) == '0' assert upretty(v[1]) == 'i_N' assert upretty(v[5]) == '(a) i_N + (-b) j_N' # Make sure the printing works in other objects assert upretty(v[5].args) == '((a) i_N, (-b) j_N)' assert upretty(v[8]) == upretty_v_8 assert upretty(v[2]) == '(-1) i_N' assert upretty(v[11]) == upretty_v_11 assert upretty(s) == upretty_s assert upretty(d[0]) == '(0|0)' assert upretty(d[5]) == '(a) (i_N|k_N) + (-b) (j_N|k_N)' assert upretty(d[7]) == upretty_d_7 assert upretty(d[10]) == '(cos(a)) (i_C|k_N) + (-sin(a)) (j_C|k_N)' def test_latex_printing(): assert latex(v[0]) == '\\mathbf{\\hat{0}}' assert latex(v[1]) == '\\mathbf{\\hat{i}_{N}}' assert latex(v[2]) == '- \\mathbf{\\hat{i}_{N}}' assert latex(v[5]) == ('(a)\\mathbf{\\hat{i}_{N}} + ' + '(- b)\\mathbf{\\hat{j}_{N}}') assert latex(v[6]) == ('(\\mathbf{{x}_{N}} + a^{2})\\mathbf{\\hat{i}_' + '{N}} + \\mathbf{\\hat{k}_{N}}') assert latex(v[8]) == ('\\mathbf{\\hat{j}_{N}} + (\\mathbf{{x}_' + '{C}}^{2} - \\int f{\\left(b \\right)}\\,' + ' db)\\mathbf{\\hat{k}_{N}}') assert latex(s) == '3 \\mathbf{{y}_{C}} \\mathbf{{x}_{N}}^{2}' assert latex(d[0]) == '(\\mathbf{\\hat{0}}|\\mathbf{\\hat{0}})' assert latex(d[4]) == ('(a)(\\mathbf{\\hat{i}_{N}}{|}\\mathbf' + '{\\hat{k}_{N}})') assert latex(d[9]) == ('(\\mathbf{\\hat{k}_{C}}{|}\\mathbf{\\' + 'hat{k}_{N}}) + (\\mathbf{\\hat{i}_{N}}{|' + '}\\mathbf{\\hat{k}_{N}})') assert latex(d[11]) == ('(a^{2} + b)(\\mathbf{\\hat{i}_{N}}{|}\\' + 'mathbf{\\hat{k}_{N}}) + (\\int f{\\left(' + 'b \\right)}\\, db)(\\mathbf{\\hat{k}_{N}' + '}{|}\\mathbf{\\hat{k}_{N}})') def test_custom_names(): A = CoordSys3D('A', vector_names=['x', 'y', 'z'], variable_names=['i', 'j', 'k']) assert A.i.__str__() == 'A.i' assert A.x.__str__() == 'A.x' assert A.i._pretty_form == 'i_A' assert A.x._pretty_form == 'x_A' assert A.i._latex_form == r'\mathbf{{i}_{A}}' assert A.x._latex_form == r"\mathbf{\hat{x}_{A}}"
be3ff5d302a3d602ede21f672a8acf94cb7f2b314ac9bfd748a46703837ba0a6
from sympy import Eq, Rational, S, Symbol, symbols, pi, sqrt, oo, Point2D, Segment2D, Abs, sec from sympy.geometry import (Circle, Ellipse, GeometryError, Line, Point, Polygon, Ray, RegularPolygon, Segment, Triangle, intersection) from sympy.testing.pytest import raises, slow from sympy import integrate from sympy.functions.special.elliptic_integrals import elliptic_e from sympy.functions.elementary.miscellaneous import Max def test_ellipse_equation_using_slope(): from sympy.abc import x, y e1 = Ellipse(Point(1, 0), 3, 2) assert str(e1.equation(_slope=1)) == str((-x + y + 1)**2/8 + (x + y - 1)**2/18 - 1) e2 = Ellipse(Point(0, 0), 4, 1) assert str(e2.equation(_slope=1)) == str((-x + y)**2/2 + (x + y)**2/32 - 1) e3 = Ellipse(Point(1, 5), 6, 2) assert str(e3.equation(_slope=2)) == str((-2*x + y - 3)**2/20 + (x + 2*y - 11)**2/180 - 1) def test_object_from_equation(): from sympy.abc import x, y, a, b assert Circle(x**2 + y**2 + 3*x + 4*y - 8) == Circle(Point2D(S(-3) / 2, -2), sqrt(57) / 2) assert Circle(x**2 + y**2 + 6*x + 8*y + 25) == Circle(Point2D(-3, -4), 0) assert Circle(a**2 + b**2 + 6*a + 8*b + 25, x='a', y='b') == Circle(Point2D(-3, -4), 0) assert Circle(x**2 + y**2 - 25) == Circle(Point2D(0, 0), 5) assert Circle(x**2 + y**2) == Circle(Point2D(0, 0), 0) assert Circle(a**2 + b**2, x='a', y='b') == Circle(Point2D(0, 0), 0) assert Circle(x**2 + y**2 + 6*x + 8) == Circle(Point2D(-3, 0), 1) assert Circle(x**2 + y**2 + 6*y + 8) == Circle(Point2D(0, -3), 1) assert Circle(6*(x**2) + 6*(y**2) + 6*x + 8*y - 25) == Circle(Point2D(Rational(-1, 2), Rational(-2, 3)), 5*sqrt(37)/6) assert Circle(Eq(a**2 + b**2, 25), x='a', y=b) == Circle(Point2D(0, 0), 5) raises(GeometryError, lambda: Circle(x**2 + y**2 + 3*x + 4*y + 26)) raises(GeometryError, lambda: Circle(x**2 + y**2 + 25)) raises(GeometryError, lambda: Circle(a**2 + b**2 + 25, x='a', y='b')) raises(GeometryError, lambda: Circle(x**2 + 6*y + 8)) raises(GeometryError, lambda: Circle(6*(x ** 2) + 4*(y**2) + 6*x + 8*y + 25)) raises(ValueError, lambda: Circle(a**2 + b**2 + 3*a + 4*b - 8)) @slow def test_ellipse_geom(): x = Symbol('x', real=True) y = Symbol('y', real=True) t = Symbol('t', real=True) y1 = Symbol('y1', real=True) half = S.Half p1 = Point(0, 0) p2 = Point(1, 1) p4 = Point(0, 1) e1 = Ellipse(p1, 1, 1) e2 = Ellipse(p2, half, 1) e3 = Ellipse(p1, y1, y1) c1 = Circle(p1, 1) c2 = Circle(p2, 1) c3 = Circle(Point(sqrt(2), sqrt(2)), 1) l1 = Line(p1, p2) # Test creation with three points cen, rad = Point(3*half, 2), 5*half assert Circle(Point(0, 0), Point(3, 0), Point(0, 4)) == Circle(cen, rad) assert Circle(Point(0, 0), Point(1, 1), Point(2, 2)) == Segment2D(Point2D(0, 0), Point2D(2, 2)) raises(ValueError, lambda: Ellipse(None, None, None, 1)) raises(GeometryError, lambda: Circle(Point(0, 0))) # Basic Stuff assert Ellipse(None, 1, 1).center == Point(0, 0) assert e1 == c1 assert e1 != e2 assert e1 != l1 assert p4 in e1 assert p2 not in e2 assert e1.area == pi assert e2.area == pi/2 assert e3.area == pi*y1*abs(y1) assert c1.area == e1.area assert c1.circumference == e1.circumference assert e3.circumference == 2*pi*y1 assert e1.plot_interval() == e2.plot_interval() == [t, -pi, pi] assert e1.plot_interval(x) == e2.plot_interval(x) == [x, -pi, pi] assert c1.minor == 1 assert c1.major == 1 assert c1.hradius == 1 assert c1.vradius == 1 assert Ellipse((1, 1), 0, 0) == Point(1, 1) assert Ellipse((1, 1), 1, 0) == Segment(Point(0, 1), Point(2, 1)) assert Ellipse((1, 1), 0, 1) == Segment(Point(1, 0), Point(1, 2)) # Private Functions assert hash(c1) == hash(Circle(Point(1, 0), Point(0, 1), Point(0, -1))) assert c1 in e1 assert (Line(p1, p2) in e1) is False assert e1.__cmp__(e1) == 0 assert e1.__cmp__(Point(0, 0)) > 0 # Encloses assert e1.encloses(Segment(Point(-0.5, -0.5), Point(0.5, 0.5))) is True assert e1.encloses(Line(p1, p2)) is False assert e1.encloses(Ray(p1, p2)) is False assert e1.encloses(e1) is False assert e1.encloses( Polygon(Point(-0.5, -0.5), Point(-0.5, 0.5), Point(0.5, 0.5))) is True assert e1.encloses(RegularPolygon(p1, 0.5, 3)) is True assert e1.encloses(RegularPolygon(p1, 5, 3)) is False assert e1.encloses(RegularPolygon(p2, 5, 3)) is False assert e2.arbitrary_point() in e2 # Foci f1, f2 = Point(sqrt(12), 0), Point(-sqrt(12), 0) ef = Ellipse(Point(0, 0), 4, 2) assert ef.foci in [(f1, f2), (f2, f1)] # Tangents v = sqrt(2) / 2 p1_1 = Point(v, v) p1_2 = p2 + Point(half, 0) p1_3 = p2 + Point(0, 1) assert e1.tangent_lines(p4) == c1.tangent_lines(p4) assert e2.tangent_lines(p1_2) == [Line(Point(Rational(3, 2), 1), Point(Rational(3, 2), S.Half))] assert e2.tangent_lines(p1_3) == [Line(Point(1, 2), Point(Rational(5, 4), 2))] assert c1.tangent_lines(p1_1) != [Line(p1_1, Point(0, sqrt(2)))] assert c1.tangent_lines(p1) == [] assert e2.is_tangent(Line(p1_2, p2 + Point(half, 1))) assert e2.is_tangent(Line(p1_3, p2 + Point(half, 1))) assert c1.is_tangent(Line(p1_1, Point(0, sqrt(2)))) assert e1.is_tangent(Line(Point(0, 0), Point(1, 1))) is False assert c1.is_tangent(e1) is True assert c1.is_tangent(Ellipse(Point(2, 0), 1, 1)) is True assert c1.is_tangent( Polygon(Point(1, 1), Point(1, -1), Point(2, 0))) is True assert c1.is_tangent( Polygon(Point(1, 1), Point(1, 0), Point(2, 0))) is False assert Circle(Point(5, 5), 3).is_tangent(Circle(Point(0, 5), 1)) is False assert Ellipse(Point(5, 5), 2, 1).tangent_lines(Point(0, 0)) == \ [Line(Point(0, 0), Point(Rational(77, 25), Rational(132, 25))), Line(Point(0, 0), Point(Rational(33, 5), Rational(22, 5)))] assert Ellipse(Point(5, 5), 2, 1).tangent_lines(Point(3, 4)) == \ [Line(Point(3, 4), Point(4, 4)), Line(Point(3, 4), Point(3, 5))] assert Circle(Point(5, 5), 2).tangent_lines(Point(3, 3)) == \ [Line(Point(3, 3), Point(4, 3)), Line(Point(3, 3), Point(3, 4))] assert Circle(Point(5, 5), 2).tangent_lines(Point(5 - 2*sqrt(2), 5)) == \ [Line(Point(5 - 2*sqrt(2), 5), Point(5 - sqrt(2), 5 - sqrt(2))), Line(Point(5 - 2*sqrt(2), 5), Point(5 - sqrt(2), 5 + sqrt(2))), ] # for numerical calculations, we shouldn't demand exact equality, # so only test up to the desired precision def lines_close(l1, l2, prec): """ tests whether l1 and 12 are within 10**(-prec) of each other """ return abs(l1.p1 - l2.p1) < 10**(-prec) and abs(l1.p2 - l2.p2) < 10**(-prec) def line_list_close(ll1, ll2, prec): return all(lines_close(l1, l2, prec) for l1, l2 in zip(ll1, ll2)) e = Ellipse(Point(0, 0), 2, 1) assert e.normal_lines(Point(0, 0)) == \ [Line(Point(0, 0), Point(0, 1)), Line(Point(0, 0), Point(1, 0))] assert e.normal_lines(Point(1, 0)) == \ [Line(Point(0, 0), Point(1, 0))] assert e.normal_lines((0, 1)) == \ [Line(Point(0, 0), Point(0, 1))] assert line_list_close(e.normal_lines(Point(1, 1), 2), [ Line(Point(Rational(-51, 26), Rational(-1, 5)), Point(Rational(-25, 26), Rational(17, 83))), Line(Point(Rational(28, 29), Rational(-7, 8)), Point(Rational(57, 29), Rational(-9, 2)))], 2) # test the failure of Poly.intervals and checks a point on the boundary p = Point(sqrt(3), S.Half) assert p in e assert line_list_close(e.normal_lines(p, 2), [ Line(Point(Rational(-341, 171), Rational(-1, 13)), Point(Rational(-170, 171), Rational(5, 64))), Line(Point(Rational(26, 15), Rational(-1, 2)), Point(Rational(41, 15), Rational(-43, 26)))], 2) # be sure to use the slope that isn't undefined on boundary e = Ellipse((0, 0), 2, 2*sqrt(3)/3) assert line_list_close(e.normal_lines((1, 1), 2), [ Line(Point(Rational(-64, 33), Rational(-20, 71)), Point(Rational(-31, 33), Rational(2, 13))), Line(Point(1, -1), Point(2, -4))], 2) # general ellipse fails except under certain conditions e = Ellipse((0, 0), x, 1) assert e.normal_lines((x + 1, 0)) == [Line(Point(0, 0), Point(1, 0))] raises(NotImplementedError, lambda: e.normal_lines((x + 1, 1))) # Properties major = 3 minor = 1 e4 = Ellipse(p2, minor, major) assert e4.focus_distance == sqrt(major**2 - minor**2) ecc = e4.focus_distance / major assert e4.eccentricity == ecc assert e4.periapsis == major*(1 - ecc) assert e4.apoapsis == major*(1 + ecc) assert e4.semilatus_rectum == major*(1 - ecc ** 2) # independent of orientation e4 = Ellipse(p2, major, minor) assert e4.focus_distance == sqrt(major**2 - minor**2) ecc = e4.focus_distance / major assert e4.eccentricity == ecc assert e4.periapsis == major*(1 - ecc) assert e4.apoapsis == major*(1 + ecc) # Intersection l1 = Line(Point(1, -5), Point(1, 5)) l2 = Line(Point(-5, -1), Point(5, -1)) l3 = Line(Point(-1, -1), Point(1, 1)) l4 = Line(Point(-10, 0), Point(0, 10)) pts_c1_l3 = [Point(sqrt(2)/2, sqrt(2)/2), Point(-sqrt(2)/2, -sqrt(2)/2)] assert intersection(e2, l4) == [] assert intersection(c1, Point(1, 0)) == [Point(1, 0)] assert intersection(c1, l1) == [Point(1, 0)] assert intersection(c1, l2) == [Point(0, -1)] assert intersection(c1, l3) in [pts_c1_l3, [pts_c1_l3[1], pts_c1_l3[0]]] assert intersection(c1, c2) == [Point(0, 1), Point(1, 0)] assert intersection(c1, c3) == [Point(sqrt(2)/2, sqrt(2)/2)] assert e1.intersection(l1) == [Point(1, 0)] assert e2.intersection(l4) == [] assert e1.intersection(Circle(Point(0, 2), 1)) == [Point(0, 1)] assert e1.intersection(Circle(Point(5, 0), 1)) == [] assert e1.intersection(Ellipse(Point(2, 0), 1, 1)) == [Point(1, 0)] assert e1.intersection(Ellipse(Point(5, 0), 1, 1)) == [] assert e1.intersection(Point(2, 0)) == [] assert e1.intersection(e1) == e1 assert intersection(Ellipse(Point(0, 0), 2, 1), Ellipse(Point(3, 0), 1, 2)) == [Point(2, 0)] assert intersection(Circle(Point(0, 0), 2), Circle(Point(3, 0), 1)) == [Point(2, 0)] assert intersection(Circle(Point(0, 0), 2), Circle(Point(7, 0), 1)) == [] assert intersection(Ellipse(Point(0, 0), 5, 17), Ellipse(Point(4, 0), 1, 0.2)) == [Point(5, 0)] assert intersection(Ellipse(Point(0, 0), 5, 17), Ellipse(Point(4, 0), 0.999, 0.2)) == [] assert Circle((0, 0), S.Half).intersection( Triangle((-1, 0), (1, 0), (0, 1))) == [ Point(Rational(-1, 2), 0), Point(S.Half, 0)] raises(TypeError, lambda: intersection(e2, Line((0, 0, 0), (0, 0, 1)))) raises(TypeError, lambda: intersection(e2, Rational(12))) # some special case intersections csmall = Circle(p1, 3) cbig = Circle(p1, 5) cout = Circle(Point(5, 5), 1) # one circle inside of another assert csmall.intersection(cbig) == [] # separate circles assert csmall.intersection(cout) == [] # coincident circles assert csmall.intersection(csmall) == csmall v = sqrt(2) t1 = Triangle(Point(0, v), Point(0, -v), Point(v, 0)) points = intersection(t1, c1) assert len(points) == 4 assert Point(0, 1) in points assert Point(0, -1) in points assert Point(v/2, v/2) in points assert Point(v/2, -v/2) in points circ = Circle(Point(0, 0), 5) elip = Ellipse(Point(0, 0), 5, 20) assert intersection(circ, elip) in \ [[Point(5, 0), Point(-5, 0)], [Point(-5, 0), Point(5, 0)]] assert elip.tangent_lines(Point(0, 0)) == [] elip = Ellipse(Point(0, 0), 3, 2) assert elip.tangent_lines(Point(3, 0)) == \ [Line(Point(3, 0), Point(3, -12))] e1 = Ellipse(Point(0, 0), 5, 10) e2 = Ellipse(Point(2, 1), 4, 8) a = Rational(53, 17) c = 2*sqrt(3991)/17 ans = [Point(a - c/8, a/2 + c), Point(a + c/8, a/2 - c)] assert e1.intersection(e2) == ans e2 = Ellipse(Point(x, y), 4, 8) c = sqrt(3991) ans = [Point(-c/68 + a, c*Rational(2, 17) + a/2), Point(c/68 + a, c*Rational(-2, 17) + a/2)] assert [p.subs({x: 2, y:1}) for p in e1.intersection(e2)] == ans # Combinations of above assert e3.is_tangent(e3.tangent_lines(p1 + Point(y1, 0))[0]) e = Ellipse((1, 2), 3, 2) assert e.tangent_lines(Point(10, 0)) == \ [Line(Point(10, 0), Point(1, 0)), Line(Point(10, 0), Point(Rational(14, 5), Rational(18, 5)))] # encloses_point e = Ellipse((0, 0), 1, 2) assert e.encloses_point(e.center) assert e.encloses_point(e.center + Point(0, e.vradius - Rational(1, 10))) assert e.encloses_point(e.center + Point(e.hradius - Rational(1, 10), 0)) assert e.encloses_point(e.center + Point(e.hradius, 0)) is False assert e.encloses_point( e.center + Point(e.hradius + Rational(1, 10), 0)) is False e = Ellipse((0, 0), 2, 1) assert e.encloses_point(e.center) assert e.encloses_point(e.center + Point(0, e.vradius - Rational(1, 10))) assert e.encloses_point(e.center + Point(e.hradius - Rational(1, 10), 0)) assert e.encloses_point(e.center + Point(e.hradius, 0)) is False assert e.encloses_point( e.center + Point(e.hradius + Rational(1, 10), 0)) is False assert c1.encloses_point(Point(1, 0)) is False assert c1.encloses_point(Point(0.3, 0.4)) is True assert e.scale(2, 3) == Ellipse((0, 0), 4, 3) assert e.scale(3, 6) == Ellipse((0, 0), 6, 6) assert e.rotate(pi) == e assert e.rotate(pi, (1, 2)) == Ellipse(Point(2, 4), 2, 1) raises(NotImplementedError, lambda: e.rotate(pi/3)) # Circle rotation tests (Issue #11743) # Link - https://github.com/sympy/sympy/issues/11743 cir = Circle(Point(1, 0), 1) assert cir.rotate(pi/2) == Circle(Point(0, 1), 1) assert cir.rotate(pi/3) == Circle(Point(S.Half, sqrt(3)/2), 1) assert cir.rotate(pi/3, Point(1, 0)) == Circle(Point(1, 0), 1) assert cir.rotate(pi/3, Point(0, 1)) == Circle(Point(S.Half + sqrt(3)/2, S.Half + sqrt(3)/2), 1) def test_construction(): e1 = Ellipse(hradius=2, vradius=1, eccentricity=None) assert e1.eccentricity == sqrt(3)/2 e2 = Ellipse(hradius=2, vradius=None, eccentricity=sqrt(3)/2) assert e2.vradius == 1 e3 = Ellipse(hradius=None, vradius=1, eccentricity=sqrt(3)/2) assert e3.hradius == 2 # filter(None, iterator) filters out anything falsey, including 0 # eccentricity would be filtered out in this case and the constructor would throw an error e4 = Ellipse(Point(0, 0), hradius=1, eccentricity=0) assert e4.vradius == 1 #tests for eccentricity > 1 raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity = S(3)/2)) raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity=sec(5))) raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity=S.Pi-S(2))) #tests for eccentricity = 1 #if vradius is not defined assert Ellipse(None, 1, None, 1).length == 2 #if hradius is not defined raises(GeometryError, lambda: Ellipse(None, None, 1, eccentricity = 1)) #tests for eccentricity < 0 raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity = -3)) raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity = -0.5)) def test_ellipse_random_point(): y1 = Symbol('y1', real=True) e3 = Ellipse(Point(0, 0), y1, y1) rx, ry = Symbol('rx'), Symbol('ry') for ind in range(0, 5): r = e3.random_point() # substitution should give zero*y1**2 assert e3.equation(rx, ry).subs(zip((rx, ry), r.args)).equals(0) def test_repr(): assert repr(Circle((0, 1), 2)) == 'Circle(Point2D(0, 1), 2)' def test_transform(): c = Circle((1, 1), 2) assert c.scale(-1) == Circle((-1, 1), 2) assert c.scale(y=-1) == Circle((1, -1), 2) assert c.scale(2) == Ellipse((2, 1), 4, 2) assert Ellipse((0, 0), 2, 3).scale(2, 3, (4, 5)) == \ Ellipse(Point(-4, -10), 4, 9) assert Circle((0, 0), 2).scale(2, 3, (4, 5)) == \ Ellipse(Point(-4, -10), 4, 6) assert Ellipse((0, 0), 2, 3).scale(3, 3, (4, 5)) == \ Ellipse(Point(-8, -10), 6, 9) assert Circle((0, 0), 2).scale(3, 3, (4, 5)) == \ Circle(Point(-8, -10), 6) assert Circle(Point(-8, -10), 6).scale(Rational(1, 3), Rational(1, 3), (4, 5)) == \ Circle((0, 0), 2) assert Circle((0, 0), 2).translate(4, 5) == \ Circle((4, 5), 2) assert Circle((0, 0), 2).scale(3, 3) == \ Circle((0, 0), 6) def test_bounds(): e1 = Ellipse(Point(0, 0), 3, 5) e2 = Ellipse(Point(2, -2), 7, 7) c1 = Circle(Point(2, -2), 7) c2 = Circle(Point(-2, 0), Point(0, 2), Point(2, 0)) assert e1.bounds == (-3, -5, 3, 5) assert e2.bounds == (-5, -9, 9, 5) assert c1.bounds == (-5, -9, 9, 5) assert c2.bounds == (-2, -2, 2, 2) def test_reflect(): b = Symbol('b') m = Symbol('m') l = Line((0, b), slope=m) t1 = Triangle((0, 0), (1, 0), (2, 3)) assert t1.area == -t1.reflect(l).area e = Ellipse((1, 0), 1, 2) assert e.area == -e.reflect(Line((1, 0), slope=0)).area assert e.area == -e.reflect(Line((1, 0), slope=oo)).area raises(NotImplementedError, lambda: e.reflect(Line((1, 0), slope=m))) def test_is_tangent(): e1 = Ellipse(Point(0, 0), 3, 5) c1 = Circle(Point(2, -2), 7) assert e1.is_tangent(Point(0, 0)) is False assert e1.is_tangent(Point(3, 0)) is False assert e1.is_tangent(e1) is True assert e1.is_tangent(Ellipse((0, 0), 1, 2)) is False assert e1.is_tangent(Ellipse((0, 0), 3, 2)) is True assert c1.is_tangent(Ellipse((2, -2), 7, 1)) is True assert c1.is_tangent(Circle((11, -2), 2)) is True assert c1.is_tangent(Circle((7, -2), 2)) is True assert c1.is_tangent(Ray((-5, -2), (-15, -20))) is False assert c1.is_tangent(Ray((-3, -2), (-15, -20))) is False assert c1.is_tangent(Ray((-3, -22), (15, 20))) is False assert c1.is_tangent(Ray((9, 20), (9, -20))) is True assert e1.is_tangent(Segment((2, 2), (-7, 7))) is False assert e1.is_tangent(Segment((0, 0), (1, 2))) is False assert c1.is_tangent(Segment((0, 0), (-5, -2))) is False assert e1.is_tangent(Segment((3, 0), (12, 12))) is False assert e1.is_tangent(Segment((12, 12), (3, 0))) is False assert e1.is_tangent(Segment((-3, 0), (3, 0))) is False assert e1.is_tangent(Segment((-3, 5), (3, 5))) is True assert e1.is_tangent(Line((0, 0), (1, 1))) is False assert e1.is_tangent(Line((-3, 0), (-2.99, -0.001))) is False assert e1.is_tangent(Line((-3, 0), (-3, 1))) is True assert e1.is_tangent(Polygon((0, 0), (5, 5), (5, -5))) is False assert e1.is_tangent(Polygon((-100, -50), (-40, -334), (-70, -52))) is False assert e1.is_tangent(Polygon((-3, 0), (3, 0), (0, 1))) is False assert e1.is_tangent(Polygon((-3, 0), (3, 0), (0, 5))) is False assert e1.is_tangent(Polygon((-3, 0), (0, -5), (3, 0), (0, 5))) is False assert e1.is_tangent(Polygon((-3, -5), (-3, 5), (3, 5), (3, -5))) is True assert c1.is_tangent(Polygon((-3, -5), (-3, 5), (3, 5), (3, -5))) is False assert e1.is_tangent(Polygon((0, 0), (3, 0), (7, 7), (0, 5))) is False assert e1.is_tangent(Polygon((3, 12), (3, -12), (6, 5))) is True assert e1.is_tangent(Polygon((3, 12), (3, -12), (0, -5), (0, 5))) is False assert e1.is_tangent(Polygon((3, 0), (5, 7), (6, -5))) is False raises(TypeError, lambda: e1.is_tangent(Point(0, 0, 0))) raises(TypeError, lambda: e1.is_tangent(Rational(5))) def test_parameter_value(): t = Symbol('t') e = Ellipse(Point(0, 0), 3, 5) assert e.parameter_value((3, 0), t) == {t: 0} raises(ValueError, lambda: e.parameter_value((4, 0), t)) @slow def test_second_moment_of_area(): x, y = symbols('x, y') e = Ellipse(Point(0, 0), 5, 4) I_yy = 2*4*integrate(sqrt(25 - x**2)*x**2, (x, -5, 5))/5 I_xx = 2*5*integrate(sqrt(16 - y**2)*y**2, (y, -4, 4))/4 Y = 3*sqrt(1 - x**2/5**2) I_xy = integrate(integrate(y, (y, -Y, Y))*x, (x, -5, 5)) assert I_yy == e.second_moment_of_area()[1] assert I_xx == e.second_moment_of_area()[0] assert I_xy == e.second_moment_of_area()[2] #checking for other point t1 = e.second_moment_of_area(Point(6,5)) t2 = (580*pi, 845*pi, 600*pi) assert t1==t2 def test_section_modulus_and_polar_second_moment_of_area(): d = Symbol('d', positive=True) c = Circle((3, 7), 8) assert c.polar_second_moment_of_area() == 2048*pi assert c.section_modulus() == (128*pi, 128*pi) c = Circle((2, 9), d/2) assert c.polar_second_moment_of_area() == pi*d**3*Abs(d)/64 + pi*d*Abs(d)**3/64 assert c.section_modulus() == (pi*d**3/S(32), pi*d**3/S(32)) a, b = symbols('a, b', positive=True) e = Ellipse((4, 6), a, b) assert e.section_modulus() == (pi*a*b**2/S(4), pi*a**2*b/S(4)) assert e.polar_second_moment_of_area() == pi*a**3*b/S(4) + pi*a*b**3/S(4) e = e.rotate(pi/2) # no change in polar and section modulus assert e.section_modulus() == (pi*a**2*b/S(4), pi*a*b**2/S(4)) assert e.polar_second_moment_of_area() == pi*a**3*b/S(4) + pi*a*b**3/S(4) e = Ellipse((a, b), 2, 6) assert e.section_modulus() == (18*pi, 6*pi) assert e.polar_second_moment_of_area() == 120*pi e = Ellipse(Point(0, 0), 2, 2) assert e.section_modulus() == (2*pi, 2*pi) assert e.section_modulus(Point(2, 2)) == (2*pi, 2*pi) assert e.section_modulus((2, 2)) == (2*pi, 2*pi) def test_circumference(): M = Symbol('M') m = Symbol('m') assert Ellipse(Point(0, 0), M, m).circumference == 4 * M * elliptic_e((M ** 2 - m ** 2) / M**2) assert Ellipse(Point(0, 0), 5, 4).circumference == 20 * elliptic_e(S(9) / 25) # circle assert Ellipse(None, 1, None, 0).circumference == 2*pi # test numerically assert abs(Ellipse(None, hradius=5, vradius=3).circumference.evalf(16) - 25.52699886339813) < 1e-10 def test_issue_15259(): assert Circle((1, 2), 0) == Point(1, 2) def test_issue_15797_equals(): Ri = 0.024127189424130748 Ci = (0.0864931002830291, 0.0819863295239654) A = Point(0, 0.0578591400998346) c = Circle(Ci, Ri) # evaluated assert c.is_tangent(c.tangent_lines(A)[0]) == True assert c.center.x.is_Rational assert c.center.y.is_Rational assert c.radius.is_Rational u = Circle(Ci, Ri, evaluate=False) # unevaluated assert u.center.x.is_Float assert u.center.y.is_Float assert u.radius.is_Float def test_auxiliary_circle(): x, y, a, b = symbols('x y a b') e = Ellipse((x, y), a, b) # the general result assert e.auxiliary_circle() == Circle((x, y), Max(a, b)) # a special case where Ellipse is a Circle assert Circle((3, 4), 8).auxiliary_circle() == Circle((3, 4), 8) def test_director_circle(): x, y, a, b = symbols('x y a b') e = Ellipse((x, y), a, b) # the general result assert e.director_circle() == Circle((x, y), sqrt(a**2 + b**2)) # a special case where Ellipse is a Circle assert Circle((3, 4), 8).director_circle() == Circle((3, 4), 8*sqrt(2)) def test_evolute(): #ellipse centered at h,k x, y, h, k = symbols('x y h k',real = True) a, b = symbols('a b') e = Ellipse(Point(h, k), a, b) t1 = (e.hradius*(x - e.center.x))**Rational(2, 3) t2 = (e.vradius*(y - e.center.y))**Rational(2, 3) E = t1 + t2 - (e.hradius**2 - e.vradius**2)**Rational(2, 3) assert e.evolute() == E #Numerical Example e = Ellipse(Point(1, 1), 6, 3) t1 = (6*(x - 1))**Rational(2, 3) t2 = (3*(y - 1))**Rational(2, 3) E = t1 + t2 - (27)**Rational(2, 3) assert e.evolute() == E def test_svg(): e1 = Ellipse(Point(1, 0), 3, 2) assert e1._svg(2, "#FFAAFF") == '<ellipse fill="#FFAAFF" stroke="#555555" stroke-width="4.0" opacity="0.6" cx="1.00000000000000" cy="0" rx="3.00000000000000" ry="2.00000000000000"/>'
a2d1a2040993f4bc613b8732cbb4c23101d9eeefc8f89125718a8679deb37503
# -*- coding: utf-8 -*- import sys from sympy.core import Symbol, Function, Float, Rational, Integer, I, Mul, Pow, Eq from sympy.functions import exp, factorial, factorial2, sin from sympy.logic import And from sympy.series import Limit from sympy.testing.pytest import raises, skip from sympy.parsing.sympy_parser import ( parse_expr, standard_transformations, rationalize, TokenError, split_symbols, implicit_multiplication, convert_equals_signs, convert_xor, function_exponentiation, implicit_multiplication_application, ) def test_sympy_parser(): x = Symbol('x') inputs = { '2*x': 2 * x, '3.00': Float(3), '22/7': Rational(22, 7), '2+3j': 2 + 3*I, 'exp(x)': exp(x), 'x!': factorial(x), 'x!!': factorial2(x), '(x + 1)! - 1': factorial(x + 1) - 1, '3.[3]': Rational(10, 3), '.0[3]': Rational(1, 30), '3.2[3]': Rational(97, 30), '1.3[12]': Rational(433, 330), '1 + 3.[3]': Rational(13, 3), '1 + .0[3]': Rational(31, 30), '1 + 3.2[3]': Rational(127, 30), '.[0011]': Rational(1, 909), '0.1[00102] + 1': Rational(366697, 333330), '1.[0191]': Rational(10190, 9999), '10!': 3628800, '-(2)': -Integer(2), '[-1, -2, 3]': [Integer(-1), Integer(-2), Integer(3)], 'Symbol("x").free_symbols': x.free_symbols, "S('S(3).n(n=3)')": 3.00, 'factorint(12, visual=True)': Mul( Pow(2, 2, evaluate=False), Pow(3, 1, evaluate=False), evaluate=False), 'Limit(sin(x), x, 0, dir="-")': Limit(sin(x), x, 0, dir='-'), } for text, result in inputs.items(): assert parse_expr(text) == result raises(TypeError, lambda: parse_expr('x', standard_transformations)) raises(TypeError, lambda: parse_expr('x', transformations=lambda x,y: 1)) raises(TypeError, lambda: parse_expr('x', transformations=(lambda x,y: 1,))) raises(TypeError, lambda: parse_expr('x', transformations=((),))) raises(TypeError, lambda: parse_expr('x', {}, [], [])) raises(TypeError, lambda: parse_expr('x', [], [], {})) raises(TypeError, lambda: parse_expr('x', [], [], {})) def test_rationalize(): inputs = { '0.123': Rational(123, 1000) } transformations = standard_transformations + (rationalize,) for text, result in inputs.items(): assert parse_expr(text, transformations=transformations) == result def test_factorial_fail(): inputs = ['x!!!', 'x!!!!', '(!)'] for text in inputs: try: parse_expr(text) assert False except TokenError: assert True def test_repeated_fail(): inputs = ['1[1]', '.1e1[1]', '0x1[1]', '1.1j[1]', '1.1[1 + 1]', '0.1[[1]]', '0x1.1[1]'] # All are valid Python, so only raise TypeError for invalid indexing for text in inputs: raises(TypeError, lambda: parse_expr(text)) inputs = ['0.1[', '0.1[1', '0.1[]'] for text in inputs: raises((TokenError, SyntaxError), lambda: parse_expr(text)) def test_repeated_dot_only(): assert parse_expr('.[1]') == Rational(1, 9) assert parse_expr('1 + .[1]') == Rational(10, 9) def test_local_dict(): local_dict = { 'my_function': lambda x: x + 2 } inputs = { 'my_function(2)': Integer(4) } for text, result in inputs.items(): assert parse_expr(text, local_dict=local_dict) == result def test_local_dict_split_implmult(): t = standard_transformations + (split_symbols, implicit_multiplication,) w = Symbol('w', real=True) y = Symbol('y') assert parse_expr('yx', local_dict={'x':w}, transformations=t) == y*w def test_local_dict_symbol_to_fcn(): x = Symbol('x') d = {'foo': Function('bar')} assert parse_expr('foo(x)', local_dict=d) == d['foo'](x) # XXX: bit odd, but would be error if parser left the Symbol d = {'foo': Symbol('baz')} assert parse_expr('foo(x)', local_dict=d) == Function('baz')(x) def test_global_dict(): global_dict = { 'Symbol': Symbol } inputs = { 'Q & S': And(Symbol('Q'), Symbol('S')) } for text, result in inputs.items(): assert parse_expr(text, global_dict=global_dict) == result def test_issue_2515(): raises(TokenError, lambda: parse_expr('(()')) raises(TokenError, lambda: parse_expr('"""')) def test_issue_7663(): x = Symbol('x') e = '2*(x+1)' assert parse_expr(e, evaluate=0) == parse_expr(e, evaluate=False) assert parse_expr(e, evaluate=0).equals(2*(x+1)) def test_issue_10560(): inputs = { '4*-3' : '(-3)*4', '-4*3' : '(-4)*3', } for text, result in inputs.items(): assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False) def test_issue_10773(): inputs = { '-10/5': '(-10)/5', '-10/-5' : '(-10)/(-5)', } for text, result in inputs.items(): assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False) def test_split_symbols(): transformations = standard_transformations + \ (split_symbols, implicit_multiplication,) x = Symbol('x') y = Symbol('y') xy = Symbol('xy') assert parse_expr("xy") == xy assert parse_expr("xy", transformations=transformations) == x*y def test_split_symbols_function(): transformations = standard_transformations + \ (split_symbols, implicit_multiplication,) x = Symbol('x') y = Symbol('y') a = Symbol('a') f = Function('f') assert parse_expr("ay(x+1)", transformations=transformations) == a*y*(x+1) assert parse_expr("af(x+1)", transformations=transformations, local_dict={'f':f}) == a*f(x+1) def test_functional_exponent(): t = standard_transformations + (convert_xor, function_exponentiation) x = Symbol('x') y = Symbol('y') a = Symbol('a') yfcn = Function('y') assert parse_expr("sin^2(x)", transformations=t) == (sin(x))**2 assert parse_expr("sin^y(x)", transformations=t) == (sin(x))**y assert parse_expr("exp^y(x)", transformations=t) == (exp(x))**y assert parse_expr("E^y(x)", transformations=t) == exp(yfcn(x)) assert parse_expr("a^y(x)", transformations=t) == a**(yfcn(x)) def test_match_parentheses_implicit_multiplication(): transformations = standard_transformations + \ (implicit_multiplication,) raises(TokenError, lambda: parse_expr('(1,2),(3,4]',transformations=transformations)) def test_convert_equals_signs(): transformations = standard_transformations + \ (convert_equals_signs, ) x = Symbol('x') y = Symbol('y') assert parse_expr("1*2=x", transformations=transformations) == Eq(2, x) assert parse_expr("y = x", transformations=transformations) == Eq(y, x) assert parse_expr("(2*y = x) = False", transformations=transformations) == Eq(Eq(2*y, x), False) def test_parse_function_issue_3539(): x = Symbol('x') f = Function('f') assert parse_expr('f(x)') == f(x) def test_split_symbols_numeric(): transformations = ( standard_transformations + (implicit_multiplication_application,)) n = Symbol('n') expr1 = parse_expr('2**n * 3**n') expr2 = parse_expr('2**n3**n', transformations=transformations) assert expr1 == expr2 == 2**n*3**n expr1 = parse_expr('n12n34', transformations=transformations) assert expr1 == n*12*n*34 def test_unicode_names(): assert parse_expr('α') == Symbol('α') def test_python3_features(): # Make sure the tokenizer can handle Python 3-only features if sys.version_info < (3, 6): skip("test_python3_features requires Python 3.6 or newer") assert parse_expr("123_456") == 123456 assert parse_expr("1.2[3_4]") == parse_expr("1.2[34]") == Rational(611, 495) assert parse_expr("1.2[012_012]") == parse_expr("1.2[012012]") == Rational(400, 333) assert parse_expr('.[3_4]') == parse_expr('.[34]') == Rational(34, 99) assert parse_expr('.1[3_4]') == parse_expr('.1[34]') == Rational(133, 990) assert parse_expr('123_123.123_123[3_4]') == parse_expr('123123.123123[34]') == Rational(12189189189211, 99000000)
3adb16bf25f7dee323a2cfde3f4123f6dc494c579fcc0160dd9842adf6bbc576
from sympy.testing.pytest import raises, XFAIL from sympy.external import import_module from sympy import ( Symbol, Mul, Add, Eq, Abs, sin, asin, cos, Pow, csc, sec, Limit, oo, Derivative, Integral, factorial, sqrt, root, StrictLessThan, LessThan, StrictGreaterThan, GreaterThan, Sum, Product, E, log, tan, Function, binomial, exp, Unequality, ) from sympy.abc import x, y, z, a, b, c, t, k, n antlr4 = import_module("antlr4") # disable tests if antlr4-python*-runtime is not present if not antlr4: disabled = True theta = Symbol('theta') f = Function('f') # shorthand definitions def _Add(a, b): return Add(a, b, evaluate=False) def _Mul(a, b): return Mul(a, b, evaluate=False) def _Pow(a, b): return Pow(a, b, evaluate=False) def _Abs(a): return Abs(a, evaluate=False) def _factorial(a): return factorial(a, evaluate=False) def _exp(a): return exp(a, evaluate=False) def _log(a, b): return log(a, b, evaluate=False) def _binomial(n, k): return binomial(n, k, evaluate=False) def test_import(): from sympy.parsing.latex._build_latex_antlr import ( build_parser, check_antlr_version, dir_latex_antlr ) # XXX: It would be better to come up with a test for these... del build_parser, check_antlr_version, dir_latex_antlr # These LaTeX strings should parse to the corresponding SymPy expression GOOD_PAIRS = [ ("0", 0), ("1", 1), ("-3.14", _Mul(-1, 3.14)), ("(-7.13)(1.5)", _Mul(_Mul(-1, 7.13), 1.5)), ("x", x), ("2x", 2*x), ("x^2", x**2), ("x^{3 + 1}", x**_Add(3, 1)), ("-c", -c), ("a \\cdot b", a * b), ("a / b", a / b), ("a \\div b", a / b), ("a + b", a + b), ("a + b - a", _Add(a+b, -a)), ("a^2 + b^2 = c^2", Eq(a**2 + b**2, c**2)), ("(x + y) z", _Mul(_Add(x, y), z)), ("\\left(x + y\\right) z", _Mul(_Add(x, y), z)), ("\\left( x + y\\right ) z", _Mul(_Add(x, y), z)), ("\\left( x + y\\right ) z", _Mul(_Add(x, y), z)), ("\\left[x + y\\right] z", _Mul(_Add(x, y), z)), ("\\left\\{x + y\\right\\} z", _Mul(_Add(x, y), z)), ("1+1", Add(1, 1, evaluate=False)), ("0+1", Add(0, 1, evaluate=False)), ("1*2", Mul(1, 2, evaluate=False)), ("0*1", Mul(0, 1, evaluate=False)), ("\\sin \\theta", sin(theta)), ("\\sin(\\theta)", sin(theta)), ("\\sin^{-1} a", asin(a)), ("\\sin a \\cos b", _Mul(sin(a), cos(b))), ("\\sin \\cos \\theta", sin(cos(theta))), ("\\sin(\\cos \\theta)", sin(cos(theta))), ("\\frac{a}{b}", a / b), ("\\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))), ("\\frac{7}{3}", _Mul(7, _Pow(3, -1))), ("(\\csc x)(\\sec y)", csc(x)*sec(y)), ("\\lim_{x \\to 3} a", Limit(a, x, 3)), ("\\lim_{x \\rightarrow 3} a", Limit(a, x, 3)), ("\\lim_{x \\Rightarrow 3} a", Limit(a, x, 3)), ("\\lim_{x \\longrightarrow 3} a", Limit(a, x, 3)), ("\\lim_{x \\Longrightarrow 3} a", Limit(a, x, 3)), ("\\lim_{x \\to 3^{+}} a", Limit(a, x, 3, dir='+')), ("\\lim_{x \\to 3^{-}} a", Limit(a, x, 3, dir='-')), ("\\infty", oo), ("\\lim_{x \\to \\infty} \\frac{1}{x}", Limit(_Pow(x, -1), x, oo)), ("\\frac{d}{dx} x", Derivative(x, x)), ("\\frac{d}{dt} x", Derivative(x, t)), ("f(x)", f(x)), ("f(x, y)", f(x, y)), ("f(x, y, z)", f(x, y, z)), ("\\frac{d f(x)}{dx}", Derivative(f(x), x)), ("\\frac{d\\theta(x)}{dx}", Derivative(Function('theta')(x), x)), ("x \\neq y", Unequality(x, y)), ("|x|", _Abs(x)), ("||x||", _Abs(Abs(x))), ("|x||y|", _Abs(x)*_Abs(y)), ("||x||y||", _Abs(_Abs(x)*_Abs(y))), ("\\pi^{|xy|}", Symbol('pi')**_Abs(x*y)), ("\\int x dx", Integral(x, x)), ("\\int x d\\theta", Integral(x, theta)), ("\\int (x^2 - y)dx", Integral(x**2 - y, x)), ("\\int x + a dx", Integral(_Add(x, a), x)), ("\\int da", Integral(1, a)), ("\\int_0^7 dx", Integral(1, (x, 0, 7))), ("\\int_a^b x dx", Integral(x, (x, a, b))), ("\\int^b_a x dx", Integral(x, (x, a, b))), ("\\int_{a}^b x dx", Integral(x, (x, a, b))), ("\\int^{b}_a x dx", Integral(x, (x, a, b))), ("\\int_{a}^{b} x dx", Integral(x, (x, a, b))), ("\\int^{b}_{a} x dx", Integral(x, (x, a, b))), ("\\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))), ("\\int (x+a)", Integral(_Add(x, a), x)), ("\\int a + b + c dx", Integral(_Add(_Add(a, b), c), x)), ("\\int \\frac{dz}{z}", Integral(Pow(z, -1), z)), ("\\int \\frac{3 dz}{z}", Integral(3*Pow(z, -1), z)), ("\\int \\frac{1}{x} dx", Integral(Pow(x, -1), x)), ("\\int \\frac{1}{a} + \\frac{1}{b} dx", Integral(_Add(_Pow(a, -1), Pow(b, -1)), x)), ("\\int \\frac{3 \\cdot d\\theta}{\\theta}", Integral(3*_Pow(theta, -1), theta)), ("\\int \\frac{1}{x} + 1 dx", Integral(_Add(_Pow(x, -1), 1), x)), ("x_0", Symbol('x_{0}')), ("x_{1}", Symbol('x_{1}')), ("x_a", Symbol('x_{a}')), ("x_{b}", Symbol('x_{b}')), ("h_\\theta", Symbol('h_{theta}')), ("h_{\\theta}", Symbol('h_{theta}')), ("h_{\\theta}(x_0, x_1)", Function('h_{theta}')(Symbol('x_{0}'), Symbol('x_{1}'))), ("x!", _factorial(x)), ("100!", _factorial(100)), ("\\theta!", _factorial(theta)), ("(x + 1)!", _factorial(_Add(x, 1))), ("(x!)!", _factorial(_factorial(x))), ("x!!!", _factorial(_factorial(_factorial(x)))), ("5!7!", _Mul(_factorial(5), _factorial(7))), ("\\sqrt{x}", sqrt(x)), ("\\sqrt{x + b}", sqrt(_Add(x, b))), ("\\sqrt[3]{\\sin x}", root(sin(x), 3)), ("\\sqrt[y]{\\sin x}", root(sin(x), y)), ("\\sqrt[\\theta]{\\sin x}", root(sin(x), theta)), ("x < y", StrictLessThan(x, y)), ("x \\leq y", LessThan(x, y)), ("x > y", StrictGreaterThan(x, y)), ("x \\geq y", GreaterThan(x, y)), ("\\mathit{x}", Symbol('x')), ("\\mathit{test}", Symbol('test')), ("\\mathit{TEST}", Symbol('TEST')), ("\\mathit{HELLO world}", Symbol('HELLO world')), ("\\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))), ("\\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))), ("\\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))), ("\\sum^3_{k = 1} c", Sum(c, (k, 1, 3))), ("\\sum_{k = 1}^{10} k^2", Sum(k**2, (k, 1, 10))), ("\\sum_{n = 0}^{\\infty} \\frac{1}{n!}", Sum(_Pow(_factorial(n), -1), (n, 0, oo))), ("\\prod_{a = b}^{c} x", Product(x, (a, b, c))), ("\\prod_{a = b}^c x", Product(x, (a, b, c))), ("\\prod^{c}_{a = b} x", Product(x, (a, b, c))), ("\\prod^c_{a = b} x", Product(x, (a, b, c))), ("\\exp x", _exp(x)), ("\\exp(x)", _exp(x)), ("\\ln x", _log(x, E)), ("\\ln xy", _log(x*y, E)), ("\\log x", _log(x, 10)), ("\\log xy", _log(x*y, 10)), ("\\log_{2} x", _log(x, 2)), ("\\log_{a} x", _log(x, a)), ("\\log_{11} x", _log(x, 11)), ("\\log_{a^2} x", _log(x, _Pow(a, 2))), ("[x]", x), ("[a + b]", _Add(a, b)), ("\\frac{d}{dx} [ \\tan x ]", Derivative(tan(x), x)), ("\\binom{n}{k}", _binomial(n, k)), ("\\tbinom{n}{k}", _binomial(n, k)), ("\\dbinom{n}{k}", _binomial(n, k)), ("\\binom{n}{0}", _binomial(n, 0)), ("a \\, b", _Mul(a, b)), ("a \\thinspace b", _Mul(a, b)), ("a \\: b", _Mul(a, b)), ("a \\medspace b", _Mul(a, b)), ("a \\; b", _Mul(a, b)), ("a \\thickspace b", _Mul(a, b)), ("a \\quad b", _Mul(a, b)), ("a \\qquad b", _Mul(a, b)), ("a \\! b", _Mul(a, b)), ("a \\negthinspace b", _Mul(a, b)), ("a \\negmedspace b", _Mul(a, b)), ("a \\negthickspace b", _Mul(a, b)), ("\\int x \\, dx", Integral(x, x)), ] def test_parseable(): from sympy.parsing.latex import parse_latex for latex_str, sympy_expr in GOOD_PAIRS: assert parse_latex(latex_str) == sympy_expr # At time of migration from latex2sympy, should work but doesn't FAILING_PAIRS = [ ("\\log_2 x", _log(x, 2)), ("\\log_a x", _log(x, a)), ] def test_failing_parseable(): from sympy.parsing.latex import parse_latex for latex_str, sympy_expr in FAILING_PAIRS: with raises(Exception): assert parse_latex(latex_str) == sympy_expr # These bad LaTeX strings should raise a LaTeXParsingError when parsed BAD_STRINGS = [ "(", ")", "\\frac{d}{dx}", "(\\frac{d}{dx})" "\\sqrt{}", "\\sqrt", "{", "}", "\\mathit{x + y}", "\\mathit{21}", "\\frac{2}{}", "\\frac{}{2}", "\\int", "!", "!0", "_", "^", "|", "||x|", "()", "((((((((((((((((()))))))))))))))))", "-", "\\frac{d}{dx} + \\frac{d}{dt}", "f(x,,y)", "f(x,y,", "\\sin^x", "\\cos^2", "@", "#", "$", "%", "&", "*", "\\", "~", "\\frac{(2 + x}{1 - x)}" ] def test_not_parseable(): from sympy.parsing.latex import parse_latex, LaTeXParsingError for latex_str in BAD_STRINGS: with raises(LaTeXParsingError): parse_latex(latex_str) # At time of migration from latex2sympy, should fail but doesn't FAILING_BAD_STRINGS = [ "\\cos 1 \\cos", "f(,", "f()", "a \\div \\div b", "a \\cdot \\cdot b", "a // b", "a +", "1.1.1", "1 +", "a / b /", ] @XFAIL def test_failing_not_parseable(): from sympy.parsing.latex import parse_latex, LaTeXParsingError for latex_str in FAILING_BAD_STRINGS: with raises(LaTeXParsingError): parse_latex(latex_str)
919ba77b1ca2a879cec408d847da535a7e9051e60e67373f056633922531d057
# Ported from latex2sympy by @augustt198 # https://github.com/augustt198/latex2sympy # See license in LICENSE.txt import sympy from sympy.external import import_module from sympy.printing.str import StrPrinter from .errors import LaTeXParsingError LaTeXParser = LaTeXLexer = MathErrorListener = None try: LaTeXParser = import_module('sympy.parsing.latex._antlr.latexparser', import_kwargs={'fromlist': ['LaTeXParser']}).LaTeXParser LaTeXLexer = import_module('sympy.parsing.latex._antlr.latexlexer', import_kwargs={'fromlist': ['LaTeXLexer']}).LaTeXLexer except Exception: pass ErrorListener = import_module('antlr4.error.ErrorListener', warn_not_installed=True, import_kwargs={'fromlist': ['ErrorListener']} ) if ErrorListener: class MathErrorListener(ErrorListener.ErrorListener): # type: ignore def __init__(self, src): super(ErrorListener.ErrorListener, self).__init__() self.src = src def syntaxError(self, recog, symbol, line, col, msg, e): fmt = "%s\n%s\n%s" marker = "~" * col + "^" if msg.startswith("missing"): err = fmt % (msg, self.src, marker) elif msg.startswith("no viable"): err = fmt % ("I expected something else here", self.src, marker) elif msg.startswith("mismatched"): names = LaTeXParser.literalNames expected = [ names[i] for i in e.getExpectedTokens() if i < len(names) ] if len(expected) < 10: expected = " ".join(expected) err = (fmt % ("I expected one of these: " + expected, self.src, marker)) else: err = (fmt % ("I expected something else here", self.src, marker)) else: err = fmt % ("I don't understand this", self.src, marker) raise LaTeXParsingError(err) def parse_latex(sympy): antlr4 = import_module('antlr4', warn_not_installed=True) if None in [antlr4, MathErrorListener]: raise ImportError("LaTeX parsing requires the antlr4 python package," " provided by pip (antlr4-python2-runtime or" " antlr4-python3-runtime) or" " conda (antlr-python-runtime)") matherror = MathErrorListener(sympy) stream = antlr4.InputStream(sympy) lex = LaTeXLexer(stream) lex.removeErrorListeners() lex.addErrorListener(matherror) tokens = antlr4.CommonTokenStream(lex) parser = LaTeXParser(tokens) # remove default console error listener parser.removeErrorListeners() parser.addErrorListener(matherror) relation = parser.math().relation() expr = convert_relation(relation) return expr def convert_relation(rel): if rel.expr(): return convert_expr(rel.expr()) lh = convert_relation(rel.relation(0)) rh = convert_relation(rel.relation(1)) if rel.LT(): return sympy.StrictLessThan(lh, rh) elif rel.LTE(): return sympy.LessThan(lh, rh) elif rel.GT(): return sympy.StrictGreaterThan(lh, rh) elif rel.GTE(): return sympy.GreaterThan(lh, rh) elif rel.EQUAL(): return sympy.Eq(lh, rh) elif rel.NEQ(): return sympy.Ne(lh, rh) def convert_expr(expr): return convert_add(expr.additive()) def convert_add(add): if add.ADD(): lh = convert_add(add.additive(0)) rh = convert_add(add.additive(1)) return sympy.Add(lh, rh, evaluate=False) elif add.SUB(): lh = convert_add(add.additive(0)) rh = convert_add(add.additive(1)) return sympy.Add(lh, -1 * rh, evaluate=False) else: return convert_mp(add.mp()) def convert_mp(mp): if hasattr(mp, 'mp'): mp_left = mp.mp(0) mp_right = mp.mp(1) else: mp_left = mp.mp_nofunc(0) mp_right = mp.mp_nofunc(1) if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) return sympy.Mul(lh, rh, evaluate=False) elif mp.DIV() or mp.CMD_DIV() or mp.COLON(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) return sympy.Mul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False) else: if hasattr(mp, 'unary'): return convert_unary(mp.unary()) else: return convert_unary(mp.unary_nofunc()) def convert_unary(unary): if hasattr(unary, 'unary'): nested_unary = unary.unary() else: nested_unary = unary.unary_nofunc() if hasattr(unary, 'postfix_nofunc'): first = unary.postfix() tail = unary.postfix_nofunc() postfix = [first] + tail else: postfix = unary.postfix() if unary.ADD(): return convert_unary(nested_unary) elif unary.SUB(): numabs = convert_unary(nested_unary) if numabs == 1: # Use Integer(-1) instead of Mul(-1, 1) return -numabs else: return sympy.Mul(-1, convert_unary(nested_unary), evaluate=False) elif postfix: return convert_postfix_list(postfix) def convert_postfix_list(arr, i=0): if i >= len(arr): raise LaTeXParsingError("Index out of bounds") res = convert_postfix(arr[i]) if isinstance(res, sympy.Expr): if i == len(arr) - 1: return res # nothing to multiply by else: if i > 0: left = convert_postfix(arr[i - 1]) right = convert_postfix(arr[i + 1]) if isinstance(left, sympy.Expr) and isinstance( right, sympy.Expr): left_syms = convert_postfix(arr[i - 1]).atoms(sympy.Symbol) right_syms = convert_postfix(arr[i + 1]).atoms( sympy.Symbol) # if the left and right sides contain no variables and the # symbol in between is 'x', treat as multiplication. if len(left_syms) == 0 and len(right_syms) == 0 and str( res) == "x": return convert_postfix_list(arr, i + 1) # multiply by next return sympy.Mul( res, convert_postfix_list(arr, i + 1), evaluate=False) else: # must be derivative wrt = res[0] if i == len(arr) - 1: raise LaTeXParsingError("Expected expression for derivative") else: expr = convert_postfix_list(arr, i + 1) return sympy.Derivative(expr, wrt) def do_subs(expr, at): if at.expr(): at_expr = convert_expr(at.expr()) syms = at_expr.atoms(sympy.Symbol) if len(syms) == 0: return expr elif len(syms) > 0: sym = next(iter(syms)) return expr.subs(sym, at_expr) elif at.equality(): lh = convert_expr(at.equality().expr(0)) rh = convert_expr(at.equality().expr(1)) return expr.subs(lh, rh) def convert_postfix(postfix): if hasattr(postfix, 'exp'): exp_nested = postfix.exp() else: exp_nested = postfix.exp_nofunc() exp = convert_exp(exp_nested) for op in postfix.postfix_op(): if op.BANG(): if isinstance(exp, list): raise LaTeXParsingError("Cannot apply postfix to derivative") exp = sympy.factorial(exp, evaluate=False) elif op.eval_at(): ev = op.eval_at() at_b = None at_a = None if ev.eval_at_sup(): at_b = do_subs(exp, ev.eval_at_sup()) if ev.eval_at_sub(): at_a = do_subs(exp, ev.eval_at_sub()) if at_b is not None and at_a is not None: exp = sympy.Add(at_b, -1 * at_a, evaluate=False) elif at_b is not None: exp = at_b elif at_a is not None: exp = at_a return exp def convert_exp(exp): if hasattr(exp, 'exp'): exp_nested = exp.exp() else: exp_nested = exp.exp_nofunc() if exp_nested: base = convert_exp(exp_nested) if isinstance(base, list): raise LaTeXParsingError("Cannot raise derivative to power") if exp.atom(): exponent = convert_atom(exp.atom()) elif exp.expr(): exponent = convert_expr(exp.expr()) return sympy.Pow(base, exponent, evaluate=False) else: if hasattr(exp, 'comp'): return convert_comp(exp.comp()) else: return convert_comp(exp.comp_nofunc()) def convert_comp(comp): if comp.group(): return convert_expr(comp.group().expr()) elif comp.abs_group(): return sympy.Abs(convert_expr(comp.abs_group().expr()), evaluate=False) elif comp.atom(): return convert_atom(comp.atom()) elif comp.frac(): return convert_frac(comp.frac()) elif comp.binom(): return convert_binom(comp.binom()) elif comp.func(): return convert_func(comp.func()) def convert_atom(atom): if atom.LETTER(): subscriptName = '' if atom.subexpr(): subscript = None if atom.subexpr().expr(): # subscript is expr subscript = convert_expr(atom.subexpr().expr()) else: # subscript is atom subscript = convert_atom(atom.subexpr().atom()) subscriptName = '_{' + StrPrinter().doprint(subscript) + '}' return sympy.Symbol(atom.LETTER().getText() + subscriptName) elif atom.SYMBOL(): s = atom.SYMBOL().getText()[1:] if s == "infty": return sympy.oo else: if atom.subexpr(): subscript = None if atom.subexpr().expr(): # subscript is expr subscript = convert_expr(atom.subexpr().expr()) else: # subscript is atom subscript = convert_atom(atom.subexpr().atom()) subscriptName = StrPrinter().doprint(subscript) s += '_{' + subscriptName + '}' return sympy.Symbol(s) elif atom.NUMBER(): s = atom.NUMBER().getText().replace(",", "") return sympy.Number(s) elif atom.DIFFERENTIAL(): var = get_differential_var(atom.DIFFERENTIAL()) return sympy.Symbol('d' + var.name) elif atom.mathit(): text = rule2text(atom.mathit().mathit_text()) return sympy.Symbol(text) def rule2text(ctx): stream = ctx.start.getInputStream() # starting index of starting token startIdx = ctx.start.start # stopping index of stopping token stopIdx = ctx.stop.stop return stream.getText(startIdx, stopIdx) def convert_frac(frac): diff_op = False partial_op = False lower_itv = frac.lower.getSourceInterval() lower_itv_len = lower_itv[1] - lower_itv[0] + 1 if (frac.lower.start == frac.lower.stop and frac.lower.start.type == LaTeXLexer.DIFFERENTIAL): wrt = get_differential_var_str(frac.lower.start.text) diff_op = True elif (lower_itv_len == 2 and frac.lower.start.type == LaTeXLexer.SYMBOL and frac.lower.start.text == '\\partial' and (frac.lower.stop.type == LaTeXLexer.LETTER or frac.lower.stop.type == LaTeXLexer.SYMBOL)): partial_op = True wrt = frac.lower.stop.text if frac.lower.stop.type == LaTeXLexer.SYMBOL: wrt = wrt[1:] if diff_op or partial_op: wrt = sympy.Symbol(wrt) if (diff_op and frac.upper.start == frac.upper.stop and frac.upper.start.type == LaTeXLexer.LETTER and frac.upper.start.text == 'd'): return [wrt] elif (partial_op and frac.upper.start == frac.upper.stop and frac.upper.start.type == LaTeXLexer.SYMBOL and frac.upper.start.text == '\\partial'): return [wrt] upper_text = rule2text(frac.upper) expr_top = None if diff_op and upper_text.startswith('d'): expr_top = parse_latex(upper_text[1:]) elif partial_op and frac.upper.start.text == '\\partial': expr_top = parse_latex(upper_text[len('\\partial'):]) if expr_top: return sympy.Derivative(expr_top, wrt) expr_top = convert_expr(frac.upper) expr_bot = convert_expr(frac.lower) inverse_denom = sympy.Pow(expr_bot, -1, evaluate=False) if expr_top == 1: return inverse_denom else: return sympy.Mul(expr_top, inverse_denom, evaluate=False) def convert_binom(binom): expr_n = convert_expr(binom.n) expr_k = convert_expr(binom.k) return sympy.binomial(expr_n, expr_k, evaluate=False) def convert_func(func): if func.func_normal(): if func.L_PAREN(): # function called with parenthesis arg = convert_func_arg(func.func_arg()) else: arg = convert_func_arg(func.func_arg_noparens()) name = func.func_normal().start.text[1:] # change arc<trig> -> a<trig> if name in [ "arcsin", "arccos", "arctan", "arccsc", "arcsec", "arccot" ]: name = "a" + name[3:] expr = getattr(sympy.functions, name)(arg, evaluate=False) if name in ["arsinh", "arcosh", "artanh"]: name = "a" + name[2:] expr = getattr(sympy.functions, name)(arg, evaluate=False) if name == "exp": expr = sympy.exp(arg, evaluate=False) if (name == "log" or name == "ln"): if func.subexpr(): base = convert_expr(func.subexpr().expr()) elif name == "log": base = 10 elif name == "ln": base = sympy.E expr = sympy.log(arg, base, evaluate=False) func_pow = None should_pow = True if func.supexpr(): if func.supexpr().expr(): func_pow = convert_expr(func.supexpr().expr()) else: func_pow = convert_atom(func.supexpr().atom()) if name in [ "sin", "cos", "tan", "csc", "sec", "cot", "sinh", "cosh", "tanh" ]: if func_pow == -1: name = "a" + name should_pow = False expr = getattr(sympy.functions, name)(arg, evaluate=False) if func_pow and should_pow: expr = sympy.Pow(expr, func_pow, evaluate=False) return expr elif func.LETTER() or func.SYMBOL(): if func.LETTER(): fname = func.LETTER().getText() elif func.SYMBOL(): fname = func.SYMBOL().getText()[1:] fname = str(fname) # can't be unicode if func.subexpr(): subscript = None if func.subexpr().expr(): # subscript is expr subscript = convert_expr(func.subexpr().expr()) else: # subscript is atom subscript = convert_atom(func.subexpr().atom()) subscriptName = StrPrinter().doprint(subscript) fname += '_{' + subscriptName + '}' input_args = func.args() output_args = [] while input_args.args(): # handle multiple arguments to function output_args.append(convert_expr(input_args.expr())) input_args = input_args.args() output_args.append(convert_expr(input_args.expr())) return sympy.Function(fname)(*output_args) elif func.FUNC_INT(): return handle_integral(func) elif func.FUNC_SQRT(): expr = convert_expr(func.base) if func.root: r = convert_expr(func.root) return sympy.root(expr, r) else: return sympy.sqrt(expr) elif func.FUNC_SUM(): return handle_sum_or_prod(func, "summation") elif func.FUNC_PROD(): return handle_sum_or_prod(func, "product") elif func.FUNC_LIM(): return handle_limit(func) def convert_func_arg(arg): if hasattr(arg, 'expr'): return convert_expr(arg.expr()) else: return convert_mp(arg.mp_nofunc()) def handle_integral(func): if func.additive(): integrand = convert_add(func.additive()) elif func.frac(): integrand = convert_frac(func.frac()) else: integrand = 1 int_var = None if func.DIFFERENTIAL(): int_var = get_differential_var(func.DIFFERENTIAL()) else: for sym in integrand.atoms(sympy.Symbol): s = str(sym) if len(s) > 1 and s[0] == 'd': if s[1] == '\\': int_var = sympy.Symbol(s[2:]) else: int_var = sympy.Symbol(s[1:]) int_sym = sym if int_var: integrand = integrand.subs(int_sym, 1) else: # Assume dx by default int_var = sympy.Symbol('x') if func.subexpr(): if func.subexpr().atom(): lower = convert_atom(func.subexpr().atom()) else: lower = convert_expr(func.subexpr().expr()) if func.supexpr().atom(): upper = convert_atom(func.supexpr().atom()) else: upper = convert_expr(func.supexpr().expr()) return sympy.Integral(integrand, (int_var, lower, upper)) else: return sympy.Integral(integrand, int_var) def handle_sum_or_prod(func, name): val = convert_mp(func.mp()) iter_var = convert_expr(func.subeq().equality().expr(0)) start = convert_expr(func.subeq().equality().expr(1)) if func.supexpr().expr(): # ^{expr} end = convert_expr(func.supexpr().expr()) else: # ^atom end = convert_atom(func.supexpr().atom()) if name == "summation": return sympy.Sum(val, (iter_var, start, end)) elif name == "product": return sympy.Product(val, (iter_var, start, end)) def handle_limit(func): sub = func.limit_sub() if sub.LETTER(): var = sympy.Symbol(sub.LETTER().getText()) elif sub.SYMBOL(): var = sympy.Symbol(sub.SYMBOL().getText()[1:]) else: var = sympy.Symbol('x') if sub.SUB(): direction = "-" else: direction = "+" approaching = convert_expr(sub.expr()) content = convert_mp(func.mp()) return sympy.Limit(content, var, approaching, direction) def get_differential_var(d): text = get_differential_var_str(d.getText()) return sympy.Symbol(text) def get_differential_var_str(text): for i in range(1, len(text)): c = text[i] if not (c == " " or c == "\r" or c == "\n" or c == "\t"): idx = i break text = text[idx:] if text[0] == "\\": text = text[1:] return text
5ebfd3e5cd90cc43d665e60e27014e50185cbbe79892169712ab7c783f1a554e
# encoding: utf-8 # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND *** # # Generated from ../LaTeX.g4, derived from latex2sympy # latex2sympy is licensed under the MIT license # https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt # # Generated with antlr4 # antlr4 is licensed under the BSD-3-Clause License # https://github.com/antlr/antlr4/blob/master/LICENSE.txt from __future__ import print_function from antlr4 import * from io import StringIO import sys def serializedATN(): with StringIO() as buf: buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2") buf.write(u"P\u02e8\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4") buf.write(u"\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r") buf.write(u"\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22") buf.write(u"\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4") buf.write(u"\30\t\30\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35") buf.write(u"\t\35\4\36\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4") buf.write(u"$\t$\4%\t%\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t") buf.write(u",\4-\t-\4.\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63") buf.write(u"\t\63\4\64\t\64\4\65\t\65\4\66\t\66\4\67\t\67\48\t8\4") buf.write(u"9\t9\4:\t:\4;\t;\4<\t<\4=\t=\4>\t>\4?\t?\4@\t@\4A\tA") buf.write(u"\4B\tB\4C\tC\4D\tD\4E\tE\4F\tF\4G\tG\4H\tH\4I\tI\4J\t") buf.write(u"J\4K\tK\4L\tL\4M\tM\4N\tN\4O\tO\4P\tP\4Q\tQ\3\2\3\2\3") buf.write(u"\3\6\3\u00a7\n\3\r\3\16\3\u00a8\3\3\3\3\3\4\3\4\3\4\3") buf.write(u"\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\5\4\u00b9\n\4\3\4") buf.write(u"\3\4\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5\5\5") buf.write(u"\u00c8\n\5\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3") buf.write(u"\6\3\6\3\6\3\6\3\6\5\6\u00d9\n\6\3\6\3\6\3\7\3\7\3\7") buf.write(u"\3\7\3\7\3\7\3\7\3\7\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b") buf.write(u"\3\b\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t") buf.write(u"\3\t\3\t\3\t\5\t\u00fd\n\t\3\t\3\t\3\n\3\n\3\n\3\n\3") buf.write(u"\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\13\3\13") buf.write(u"\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3") buf.write(u"\13\3\13\3\13\3\13\3\13\3\f\3\f\3\r\3\r\3\16\3\16\3\17") buf.write(u"\3\17\3\20\3\20\3\21\3\21\3\22\3\22\3\23\3\23\3\24\3") buf.write(u"\24\3\24\3\25\3\25\3\25\3\26\3\26\3\27\3\27\3\30\3\30") buf.write(u"\3\30\3\30\3\30\3\30\3\30\3\30\3\31\3\31\3\31\3\31\3") buf.write(u"\31\3\31\3\31\3\31\3\31\3\32\3\32\3\33\3\33\3\33\3\33") buf.write(u"\3\33\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3") buf.write(u"\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34") buf.write(u"\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3") buf.write(u"\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34") buf.write(u"\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3") buf.write(u"\34\3\34\3\34\3\34\5\34\u018a\n\34\3\35\3\35\3\35\3\35") buf.write(u"\3\35\3\36\3\36\3\36\3\36\3\36\3\37\3\37\3\37\3\37\3") buf.write(u"\37\3\37\3 \3 \3 \3 \3 \3!\3!\3!\3!\3!\3\"\3\"\3\"\3") buf.write(u"\"\3#\3#\3#\3#\3#\3$\3$\3$\3$\3$\3%\3%\3%\3%\3%\3&\3") buf.write(u"&\3&\3&\3&\3\'\3\'\3\'\3\'\3\'\3(\3(\3(\3(\3(\3)\3)\3") buf.write(u")\3)\3)\3)\3)\3)\3*\3*\3*\3*\3*\3*\3*\3*\3+\3+\3+\3+") buf.write(u"\3+\3+\3+\3+\3,\3,\3,\3,\3,\3,\3,\3,\3-\3-\3-\3-\3-\3") buf.write(u"-\3-\3-\3.\3.\3.\3.\3.\3.\3.\3.\3/\3/\3/\3/\3/\3/\3\60") buf.write(u"\3\60\3\60\3\60\3\60\3\60\3\61\3\61\3\61\3\61\3\61\3") buf.write(u"\61\3\62\3\62\3\62\3\62\3\62\3\62\3\62\3\62\3\63\3\63") buf.write(u"\3\63\3\63\3\63\3\63\3\63\3\63\3\64\3\64\3\64\3\64\3") buf.write(u"\64\3\64\3\64\3\64\3\65\3\65\3\65\3\65\3\65\3\65\3\66") buf.write(u"\3\66\3\66\3\66\3\66\3\66\3\66\3\67\3\67\3\67\3\67\3") buf.write(u"\67\3\67\38\38\38\38\38\39\39\39\39\39\39\3:\3:\3:\3") buf.write(u":\3:\3:\3:\3;\3;\3;\3;\3;\3;\3;\3;\3<\3<\3<\3<\3<\3<") buf.write(u"\3<\3<\3=\3=\3=\3=\3=\3=\3=\3=\3>\3>\3?\3?\3@\3@\3A\3") buf.write(u"A\3B\3B\7B\u0269\nB\fB\16B\u026c\13B\3B\3B\3B\6B\u0271") buf.write(u"\nB\rB\16B\u0272\5B\u0275\nB\3C\3C\3D\3D\3E\6E\u027c") buf.write(u"\nE\rE\16E\u027d\3E\3E\3E\3E\3E\7E\u0285\nE\fE\16E\u0288") buf.write(u"\13E\3E\7E\u028b\nE\fE\16E\u028e\13E\3E\3E\3E\3E\3E\7") buf.write(u"E\u0295\nE\fE\16E\u0298\13E\3E\3E\6E\u029c\nE\rE\16E") buf.write(u"\u029d\5E\u02a0\nE\3F\3F\3G\3G\3G\3G\3G\3H\3H\3I\3I\3") buf.write(u"I\3I\3I\3I\3I\3I\5I\u02b3\nI\3J\3J\3J\3J\3J\3J\3K\3K") buf.write(u"\3K\3K\3K\3K\3K\3K\3K\3K\3L\3L\3M\3M\3M\3M\3M\3M\3M\3") buf.write(u"M\5M\u02cf\nM\3N\3N\3N\3N\3N\3N\3O\3O\3O\3O\3O\3O\3O") buf.write(u"\3O\3O\3O\3P\3P\3Q\3Q\6Q\u02e5\nQ\rQ\16Q\u02e6\3\u026a") buf.write(u"\2R\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27") buf.write(u"\r\31\16\33\17\35\20\37\21!\22#\23%\24\'\25)\26+\27-") buf.write(u"\30/\31\61\32\63\33\65\34\67\359\36;\37= ?!A\"C#E$G%") buf.write(u"I&K\'M(O)Q*S+U,W-Y.[/]\60_\61a\62c\63e\64g\65i\66k\67") buf.write(u"m8o9q:s;u<w=y>{?}@\177A\u0081\2\u0083B\u0085C\u0087\2") buf.write(u"\u0089D\u008bE\u008dF\u008fG\u0091H\u0093I\u0095J\u0097") buf.write(u"K\u0099L\u009bM\u009dN\u009fO\u00a1P\3\2\5\5\2\13\f\17") buf.write(u"\17\"\"\4\2C\\c|\3\2\62;\2\u02fe\2\3\3\2\2\2\2\5\3\2") buf.write(u"\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2") buf.write(u"\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2") buf.write(u"\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\2\35\3\2\2\2") buf.write(u"\2\37\3\2\2\2\2!\3\2\2\2\2#\3\2\2\2\2%\3\2\2\2\2\'\3") buf.write(u"\2\2\2\2)\3\2\2\2\2+\3\2\2\2\2-\3\2\2\2\2/\3\2\2\2\2") buf.write(u"\61\3\2\2\2\2\63\3\2\2\2\2\65\3\2\2\2\2\67\3\2\2\2\2") buf.write(u"9\3\2\2\2\2;\3\2\2\2\2=\3\2\2\2\2?\3\2\2\2\2A\3\2\2\2") buf.write(u"\2C\3\2\2\2\2E\3\2\2\2\2G\3\2\2\2\2I\3\2\2\2\2K\3\2\2") buf.write(u"\2\2M\3\2\2\2\2O\3\2\2\2\2Q\3\2\2\2\2S\3\2\2\2\2U\3\2") buf.write(u"\2\2\2W\3\2\2\2\2Y\3\2\2\2\2[\3\2\2\2\2]\3\2\2\2\2_\3") buf.write(u"\2\2\2\2a\3\2\2\2\2c\3\2\2\2\2e\3\2\2\2\2g\3\2\2\2\2") buf.write(u"i\3\2\2\2\2k\3\2\2\2\2m\3\2\2\2\2o\3\2\2\2\2q\3\2\2\2") buf.write(u"\2s\3\2\2\2\2u\3\2\2\2\2w\3\2\2\2\2y\3\2\2\2\2{\3\2\2") buf.write(u"\2\2}\3\2\2\2\2\177\3\2\2\2\2\u0083\3\2\2\2\2\u0085\3") buf.write(u"\2\2\2\2\u0089\3\2\2\2\2\u008b\3\2\2\2\2\u008d\3\2\2") buf.write(u"\2\2\u008f\3\2\2\2\2\u0091\3\2\2\2\2\u0093\3\2\2\2\2") buf.write(u"\u0095\3\2\2\2\2\u0097\3\2\2\2\2\u0099\3\2\2\2\2\u009b") buf.write(u"\3\2\2\2\2\u009d\3\2\2\2\2\u009f\3\2\2\2\2\u00a1\3\2") buf.write(u"\2\2\3\u00a3\3\2\2\2\5\u00a6\3\2\2\2\7\u00b8\3\2\2\2") buf.write(u"\t\u00c7\3\2\2\2\13\u00d8\3\2\2\2\r\u00dc\3\2\2\2\17") buf.write(u"\u00e4\3\2\2\2\21\u00fc\3\2\2\2\23\u0100\3\2\2\2\25\u010f") buf.write(u"\3\2\2\2\27\u0120\3\2\2\2\31\u0122\3\2\2\2\33\u0124\3") buf.write(u"\2\2\2\35\u0126\3\2\2\2\37\u0128\3\2\2\2!\u012a\3\2\2") buf.write(u"\2#\u012c\3\2\2\2%\u012e\3\2\2\2\'\u0130\3\2\2\2)\u0133") buf.write(u"\3\2\2\2+\u0136\3\2\2\2-\u0138\3\2\2\2/\u013a\3\2\2\2") buf.write(u"\61\u0142\3\2\2\2\63\u014b\3\2\2\2\65\u014d\3\2\2\2\67") buf.write(u"\u0189\3\2\2\29\u018b\3\2\2\2;\u0190\3\2\2\2=\u0195\3") buf.write(u"\2\2\2?\u019b\3\2\2\2A\u01a0\3\2\2\2C\u01a5\3\2\2\2E") buf.write(u"\u01a9\3\2\2\2G\u01ae\3\2\2\2I\u01b3\3\2\2\2K\u01b8\3") buf.write(u"\2\2\2M\u01bd\3\2\2\2O\u01c2\3\2\2\2Q\u01c7\3\2\2\2S") buf.write(u"\u01cf\3\2\2\2U\u01d7\3\2\2\2W\u01df\3\2\2\2Y\u01e7\3") buf.write(u"\2\2\2[\u01ef\3\2\2\2]\u01f7\3\2\2\2_\u01fd\3\2\2\2a") buf.write(u"\u0203\3\2\2\2c\u0209\3\2\2\2e\u0211\3\2\2\2g\u0219\3") buf.write(u"\2\2\2i\u0221\3\2\2\2k\u0227\3\2\2\2m\u022e\3\2\2\2o") buf.write(u"\u0234\3\2\2\2q\u0239\3\2\2\2s\u023f\3\2\2\2u\u0246\3") buf.write(u"\2\2\2w\u024e\3\2\2\2y\u0256\3\2\2\2{\u025e\3\2\2\2}") buf.write(u"\u0260\3\2\2\2\177\u0262\3\2\2\2\u0081\u0264\3\2\2\2") buf.write(u"\u0083\u0266\3\2\2\2\u0085\u0276\3\2\2\2\u0087\u0278") buf.write(u"\3\2\2\2\u0089\u029f\3\2\2\2\u008b\u02a1\3\2\2\2\u008d") buf.write(u"\u02a3\3\2\2\2\u008f\u02a8\3\2\2\2\u0091\u02b2\3\2\2") buf.write(u"\2\u0093\u02b4\3\2\2\2\u0095\u02ba\3\2\2\2\u0097\u02c4") buf.write(u"\3\2\2\2\u0099\u02ce\3\2\2\2\u009b\u02d0\3\2\2\2\u009d") buf.write(u"\u02d6\3\2\2\2\u009f\u02e0\3\2\2\2\u00a1\u02e2\3\2\2") buf.write(u"\2\u00a3\u00a4\7.\2\2\u00a4\4\3\2\2\2\u00a5\u00a7\t\2") buf.write(u"\2\2\u00a6\u00a5\3\2\2\2\u00a7\u00a8\3\2\2\2\u00a8\u00a6") buf.write(u"\3\2\2\2\u00a8\u00a9\3\2\2\2\u00a9\u00aa\3\2\2\2\u00aa") buf.write(u"\u00ab\b\3\2\2\u00ab\6\3\2\2\2\u00ac\u00ad\7^\2\2\u00ad") buf.write(u"\u00b9\7.\2\2\u00ae\u00af\7^\2\2\u00af\u00b0\7v\2\2\u00b0") buf.write(u"\u00b1\7j\2\2\u00b1\u00b2\7k\2\2\u00b2\u00b3\7p\2\2\u00b3") buf.write(u"\u00b4\7u\2\2\u00b4\u00b5\7r\2\2\u00b5\u00b6\7c\2\2\u00b6") buf.write(u"\u00b7\7e\2\2\u00b7\u00b9\7g\2\2\u00b8\u00ac\3\2\2\2") buf.write(u"\u00b8\u00ae\3\2\2\2\u00b9\u00ba\3\2\2\2\u00ba\u00bb") buf.write(u"\b\4\2\2\u00bb\b\3\2\2\2\u00bc\u00bd\7^\2\2\u00bd\u00c8") buf.write(u"\7<\2\2\u00be\u00bf\7^\2\2\u00bf\u00c0\7o\2\2\u00c0\u00c1") buf.write(u"\7g\2\2\u00c1\u00c2\7f\2\2\u00c2\u00c3\7u\2\2\u00c3\u00c4") buf.write(u"\7r\2\2\u00c4\u00c5\7c\2\2\u00c5\u00c6\7e\2\2\u00c6\u00c8") buf.write(u"\7g\2\2\u00c7\u00bc\3\2\2\2\u00c7\u00be\3\2\2\2\u00c8") buf.write(u"\u00c9\3\2\2\2\u00c9\u00ca\b\5\2\2\u00ca\n\3\2\2\2\u00cb") buf.write(u"\u00cc\7^\2\2\u00cc\u00d9\7=\2\2\u00cd\u00ce\7^\2\2\u00ce") buf.write(u"\u00cf\7v\2\2\u00cf\u00d0\7j\2\2\u00d0\u00d1\7k\2\2\u00d1") buf.write(u"\u00d2\7e\2\2\u00d2\u00d3\7m\2\2\u00d3\u00d4\7u\2\2\u00d4") buf.write(u"\u00d5\7r\2\2\u00d5\u00d6\7c\2\2\u00d6\u00d7\7e\2\2\u00d7") buf.write(u"\u00d9\7g\2\2\u00d8\u00cb\3\2\2\2\u00d8\u00cd\3\2\2\2") buf.write(u"\u00d9\u00da\3\2\2\2\u00da\u00db\b\6\2\2\u00db\f\3\2") buf.write(u"\2\2\u00dc\u00dd\7^\2\2\u00dd\u00de\7s\2\2\u00de\u00df") buf.write(u"\7w\2\2\u00df\u00e0\7c\2\2\u00e0\u00e1\7f\2\2\u00e1\u00e2") buf.write(u"\3\2\2\2\u00e2\u00e3\b\7\2\2\u00e3\16\3\2\2\2\u00e4\u00e5") buf.write(u"\7^\2\2\u00e5\u00e6\7s\2\2\u00e6\u00e7\7s\2\2\u00e7\u00e8") buf.write(u"\7w\2\2\u00e8\u00e9\7c\2\2\u00e9\u00ea\7f\2\2\u00ea\u00eb") buf.write(u"\3\2\2\2\u00eb\u00ec\b\b\2\2\u00ec\20\3\2\2\2\u00ed\u00ee") buf.write(u"\7^\2\2\u00ee\u00fd\7#\2\2\u00ef\u00f0\7^\2\2\u00f0\u00f1") buf.write(u"\7p\2\2\u00f1\u00f2\7g\2\2\u00f2\u00f3\7i\2\2\u00f3\u00f4") buf.write(u"\7v\2\2\u00f4\u00f5\7j\2\2\u00f5\u00f6\7k\2\2\u00f6\u00f7") buf.write(u"\7p\2\2\u00f7\u00f8\7u\2\2\u00f8\u00f9\7r\2\2\u00f9\u00fa") buf.write(u"\7c\2\2\u00fa\u00fb\7e\2\2\u00fb\u00fd\7g\2\2\u00fc\u00ed") buf.write(u"\3\2\2\2\u00fc\u00ef\3\2\2\2\u00fd\u00fe\3\2\2\2\u00fe") buf.write(u"\u00ff\b\t\2\2\u00ff\22\3\2\2\2\u0100\u0101\7^\2\2\u0101") buf.write(u"\u0102\7p\2\2\u0102\u0103\7g\2\2\u0103\u0104\7i\2\2\u0104") buf.write(u"\u0105\7o\2\2\u0105\u0106\7g\2\2\u0106\u0107\7f\2\2\u0107") buf.write(u"\u0108\7u\2\2\u0108\u0109\7r\2\2\u0109\u010a\7c\2\2\u010a") buf.write(u"\u010b\7e\2\2\u010b\u010c\7g\2\2\u010c\u010d\3\2\2\2") buf.write(u"\u010d\u010e\b\n\2\2\u010e\24\3\2\2\2\u010f\u0110\7^") buf.write(u"\2\2\u0110\u0111\7p\2\2\u0111\u0112\7g\2\2\u0112\u0113") buf.write(u"\7i\2\2\u0113\u0114\7v\2\2\u0114\u0115\7j\2\2\u0115\u0116") buf.write(u"\7k\2\2\u0116\u0117\7e\2\2\u0117\u0118\7m\2\2\u0118\u0119") buf.write(u"\7u\2\2\u0119\u011a\7r\2\2\u011a\u011b\7c\2\2\u011b\u011c") buf.write(u"\7e\2\2\u011c\u011d\7g\2\2\u011d\u011e\3\2\2\2\u011e") buf.write(u"\u011f\b\13\2\2\u011f\26\3\2\2\2\u0120\u0121\7-\2\2\u0121") buf.write(u"\30\3\2\2\2\u0122\u0123\7/\2\2\u0123\32\3\2\2\2\u0124") buf.write(u"\u0125\7,\2\2\u0125\34\3\2\2\2\u0126\u0127\7\61\2\2\u0127") buf.write(u"\36\3\2\2\2\u0128\u0129\7*\2\2\u0129 \3\2\2\2\u012a\u012b") buf.write(u"\7+\2\2\u012b\"\3\2\2\2\u012c\u012d\7}\2\2\u012d$\3\2") buf.write(u"\2\2\u012e\u012f\7\177\2\2\u012f&\3\2\2\2\u0130\u0131") buf.write(u"\7^\2\2\u0131\u0132\7}\2\2\u0132(\3\2\2\2\u0133\u0134") buf.write(u"\7^\2\2\u0134\u0135\7\177\2\2\u0135*\3\2\2\2\u0136\u0137") buf.write(u"\7]\2\2\u0137,\3\2\2\2\u0138\u0139\7_\2\2\u0139.\3\2") buf.write(u"\2\2\u013a\u013b\7^\2\2\u013b\u013c\7n\2\2\u013c\u013d") buf.write(u"\7g\2\2\u013d\u013e\7h\2\2\u013e\u013f\7v\2\2\u013f\u0140") buf.write(u"\3\2\2\2\u0140\u0141\b\30\2\2\u0141\60\3\2\2\2\u0142") buf.write(u"\u0143\7^\2\2\u0143\u0144\7t\2\2\u0144\u0145\7k\2\2\u0145") buf.write(u"\u0146\7i\2\2\u0146\u0147\7j\2\2\u0147\u0148\7v\2\2\u0148") buf.write(u"\u0149\3\2\2\2\u0149\u014a\b\31\2\2\u014a\62\3\2\2\2") buf.write(u"\u014b\u014c\7~\2\2\u014c\64\3\2\2\2\u014d\u014e\7^\2") buf.write(u"\2\u014e\u014f\7n\2\2\u014f\u0150\7k\2\2\u0150\u0151") buf.write(u"\7o\2\2\u0151\66\3\2\2\2\u0152\u0153\7^\2\2\u0153\u0154") buf.write(u"\7v\2\2\u0154\u018a\7q\2\2\u0155\u0156\7^\2\2\u0156\u0157") buf.write(u"\7t\2\2\u0157\u0158\7k\2\2\u0158\u0159\7i\2\2\u0159\u015a") buf.write(u"\7j\2\2\u015a\u015b\7v\2\2\u015b\u015c\7c\2\2\u015c\u015d") buf.write(u"\7t\2\2\u015d\u015e\7t\2\2\u015e\u015f\7q\2\2\u015f\u018a") buf.write(u"\7y\2\2\u0160\u0161\7^\2\2\u0161\u0162\7T\2\2\u0162\u0163") buf.write(u"\7k\2\2\u0163\u0164\7i\2\2\u0164\u0165\7j\2\2\u0165\u0166") buf.write(u"\7v\2\2\u0166\u0167\7c\2\2\u0167\u0168\7t\2\2\u0168\u0169") buf.write(u"\7t\2\2\u0169\u016a\7q\2\2\u016a\u018a\7y\2\2\u016b\u016c") buf.write(u"\7^\2\2\u016c\u016d\7n\2\2\u016d\u016e\7q\2\2\u016e\u016f") buf.write(u"\7p\2\2\u016f\u0170\7i\2\2\u0170\u0171\7t\2\2\u0171\u0172") buf.write(u"\7k\2\2\u0172\u0173\7i\2\2\u0173\u0174\7j\2\2\u0174\u0175") buf.write(u"\7v\2\2\u0175\u0176\7c\2\2\u0176\u0177\7t\2\2\u0177\u0178") buf.write(u"\7t\2\2\u0178\u0179\7q\2\2\u0179\u018a\7y\2\2\u017a\u017b") buf.write(u"\7^\2\2\u017b\u017c\7N\2\2\u017c\u017d\7q\2\2\u017d\u017e") buf.write(u"\7p\2\2\u017e\u017f\7i\2\2\u017f\u0180\7t\2\2\u0180\u0181") buf.write(u"\7k\2\2\u0181\u0182\7i\2\2\u0182\u0183\7j\2\2\u0183\u0184") buf.write(u"\7v\2\2\u0184\u0185\7c\2\2\u0185\u0186\7t\2\2\u0186\u0187") buf.write(u"\7t\2\2\u0187\u0188\7q\2\2\u0188\u018a\7y\2\2\u0189\u0152") buf.write(u"\3\2\2\2\u0189\u0155\3\2\2\2\u0189\u0160\3\2\2\2\u0189") buf.write(u"\u016b\3\2\2\2\u0189\u017a\3\2\2\2\u018a8\3\2\2\2\u018b") buf.write(u"\u018c\7^\2\2\u018c\u018d\7k\2\2\u018d\u018e\7p\2\2\u018e") buf.write(u"\u018f\7v\2\2\u018f:\3\2\2\2\u0190\u0191\7^\2\2\u0191") buf.write(u"\u0192\7u\2\2\u0192\u0193\7w\2\2\u0193\u0194\7o\2\2\u0194") buf.write(u"<\3\2\2\2\u0195\u0196\7^\2\2\u0196\u0197\7r\2\2\u0197") buf.write(u"\u0198\7t\2\2\u0198\u0199\7q\2\2\u0199\u019a\7f\2\2\u019a") buf.write(u">\3\2\2\2\u019b\u019c\7^\2\2\u019c\u019d\7g\2\2\u019d") buf.write(u"\u019e\7z\2\2\u019e\u019f\7r\2\2\u019f@\3\2\2\2\u01a0") buf.write(u"\u01a1\7^\2\2\u01a1\u01a2\7n\2\2\u01a2\u01a3\7q\2\2\u01a3") buf.write(u"\u01a4\7i\2\2\u01a4B\3\2\2\2\u01a5\u01a6\7^\2\2\u01a6") buf.write(u"\u01a7\7n\2\2\u01a7\u01a8\7p\2\2\u01a8D\3\2\2\2\u01a9") buf.write(u"\u01aa\7^\2\2\u01aa\u01ab\7u\2\2\u01ab\u01ac\7k\2\2\u01ac") buf.write(u"\u01ad\7p\2\2\u01adF\3\2\2\2\u01ae\u01af\7^\2\2\u01af") buf.write(u"\u01b0\7e\2\2\u01b0\u01b1\7q\2\2\u01b1\u01b2\7u\2\2\u01b2") buf.write(u"H\3\2\2\2\u01b3\u01b4\7^\2\2\u01b4\u01b5\7v\2\2\u01b5") buf.write(u"\u01b6\7c\2\2\u01b6\u01b7\7p\2\2\u01b7J\3\2\2\2\u01b8") buf.write(u"\u01b9\7^\2\2\u01b9\u01ba\7e\2\2\u01ba\u01bb\7u\2\2\u01bb") buf.write(u"\u01bc\7e\2\2\u01bcL\3\2\2\2\u01bd\u01be\7^\2\2\u01be") buf.write(u"\u01bf\7u\2\2\u01bf\u01c0\7g\2\2\u01c0\u01c1\7e\2\2\u01c1") buf.write(u"N\3\2\2\2\u01c2\u01c3\7^\2\2\u01c3\u01c4\7e\2\2\u01c4") buf.write(u"\u01c5\7q\2\2\u01c5\u01c6\7v\2\2\u01c6P\3\2\2\2\u01c7") buf.write(u"\u01c8\7^\2\2\u01c8\u01c9\7c\2\2\u01c9\u01ca\7t\2\2\u01ca") buf.write(u"\u01cb\7e\2\2\u01cb\u01cc\7u\2\2\u01cc\u01cd\7k\2\2\u01cd") buf.write(u"\u01ce\7p\2\2\u01ceR\3\2\2\2\u01cf\u01d0\7^\2\2\u01d0") buf.write(u"\u01d1\7c\2\2\u01d1\u01d2\7t\2\2\u01d2\u01d3\7e\2\2\u01d3") buf.write(u"\u01d4\7e\2\2\u01d4\u01d5\7q\2\2\u01d5\u01d6\7u\2\2\u01d6") buf.write(u"T\3\2\2\2\u01d7\u01d8\7^\2\2\u01d8\u01d9\7c\2\2\u01d9") buf.write(u"\u01da\7t\2\2\u01da\u01db\7e\2\2\u01db\u01dc\7v\2\2\u01dc") buf.write(u"\u01dd\7c\2\2\u01dd\u01de\7p\2\2\u01deV\3\2\2\2\u01df") buf.write(u"\u01e0\7^\2\2\u01e0\u01e1\7c\2\2\u01e1\u01e2\7t\2\2\u01e2") buf.write(u"\u01e3\7e\2\2\u01e3\u01e4\7e\2\2\u01e4\u01e5\7u\2\2\u01e5") buf.write(u"\u01e6\7e\2\2\u01e6X\3\2\2\2\u01e7\u01e8\7^\2\2\u01e8") buf.write(u"\u01e9\7c\2\2\u01e9\u01ea\7t\2\2\u01ea\u01eb\7e\2\2\u01eb") buf.write(u"\u01ec\7u\2\2\u01ec\u01ed\7g\2\2\u01ed\u01ee\7e\2\2\u01ee") buf.write(u"Z\3\2\2\2\u01ef\u01f0\7^\2\2\u01f0\u01f1\7c\2\2\u01f1") buf.write(u"\u01f2\7t\2\2\u01f2\u01f3\7e\2\2\u01f3\u01f4\7e\2\2\u01f4") buf.write(u"\u01f5\7q\2\2\u01f5\u01f6\7v\2\2\u01f6\\\3\2\2\2\u01f7") buf.write(u"\u01f8\7^\2\2\u01f8\u01f9\7u\2\2\u01f9\u01fa\7k\2\2\u01fa") buf.write(u"\u01fb\7p\2\2\u01fb\u01fc\7j\2\2\u01fc^\3\2\2\2\u01fd") buf.write(u"\u01fe\7^\2\2\u01fe\u01ff\7e\2\2\u01ff\u0200\7q\2\2\u0200") buf.write(u"\u0201\7u\2\2\u0201\u0202\7j\2\2\u0202`\3\2\2\2\u0203") buf.write(u"\u0204\7^\2\2\u0204\u0205\7v\2\2\u0205\u0206\7c\2\2\u0206") buf.write(u"\u0207\7p\2\2\u0207\u0208\7j\2\2\u0208b\3\2\2\2\u0209") buf.write(u"\u020a\7^\2\2\u020a\u020b\7c\2\2\u020b\u020c\7t\2\2\u020c") buf.write(u"\u020d\7u\2\2\u020d\u020e\7k\2\2\u020e\u020f\7p\2\2\u020f") buf.write(u"\u0210\7j\2\2\u0210d\3\2\2\2\u0211\u0212\7^\2\2\u0212") buf.write(u"\u0213\7c\2\2\u0213\u0214\7t\2\2\u0214\u0215\7e\2\2\u0215") buf.write(u"\u0216\7q\2\2\u0216\u0217\7u\2\2\u0217\u0218\7j\2\2\u0218") buf.write(u"f\3\2\2\2\u0219\u021a\7^\2\2\u021a\u021b\7c\2\2\u021b") buf.write(u"\u021c\7t\2\2\u021c\u021d\7v\2\2\u021d\u021e\7c\2\2\u021e") buf.write(u"\u021f\7p\2\2\u021f\u0220\7j\2\2\u0220h\3\2\2\2\u0221") buf.write(u"\u0222\7^\2\2\u0222\u0223\7u\2\2\u0223\u0224\7s\2\2\u0224") buf.write(u"\u0225\7t\2\2\u0225\u0226\7v\2\2\u0226j\3\2\2\2\u0227") buf.write(u"\u0228\7^\2\2\u0228\u0229\7v\2\2\u0229\u022a\7k\2\2\u022a") buf.write(u"\u022b\7o\2\2\u022b\u022c\7g\2\2\u022c\u022d\7u\2\2\u022d") buf.write(u"l\3\2\2\2\u022e\u022f\7^\2\2\u022f\u0230\7e\2\2\u0230") buf.write(u"\u0231\7f\2\2\u0231\u0232\7q\2\2\u0232\u0233\7v\2\2\u0233") buf.write(u"n\3\2\2\2\u0234\u0235\7^\2\2\u0235\u0236\7f\2\2\u0236") buf.write(u"\u0237\7k\2\2\u0237\u0238\7x\2\2\u0238p\3\2\2\2\u0239") buf.write(u"\u023a\7^\2\2\u023a\u023b\7h\2\2\u023b\u023c\7t\2\2\u023c") buf.write(u"\u023d\7c\2\2\u023d\u023e\7e\2\2\u023er\3\2\2\2\u023f") buf.write(u"\u0240\7^\2\2\u0240\u0241\7d\2\2\u0241\u0242\7k\2\2\u0242") buf.write(u"\u0243\7p\2\2\u0243\u0244\7q\2\2\u0244\u0245\7o\2\2\u0245") buf.write(u"t\3\2\2\2\u0246\u0247\7^\2\2\u0247\u0248\7f\2\2\u0248") buf.write(u"\u0249\7d\2\2\u0249\u024a\7k\2\2\u024a\u024b\7p\2\2\u024b") buf.write(u"\u024c\7q\2\2\u024c\u024d\7o\2\2\u024dv\3\2\2\2\u024e") buf.write(u"\u024f\7^\2\2\u024f\u0250\7v\2\2\u0250\u0251\7d\2\2\u0251") buf.write(u"\u0252\7k\2\2\u0252\u0253\7p\2\2\u0253\u0254\7q\2\2\u0254") buf.write(u"\u0255\7o\2\2\u0255x\3\2\2\2\u0256\u0257\7^\2\2\u0257") buf.write(u"\u0258\7o\2\2\u0258\u0259\7c\2\2\u0259\u025a\7v\2\2\u025a") buf.write(u"\u025b\7j\2\2\u025b\u025c\7k\2\2\u025c\u025d\7v\2\2\u025d") buf.write(u"z\3\2\2\2\u025e\u025f\7a\2\2\u025f|\3\2\2\2\u0260\u0261") buf.write(u"\7`\2\2\u0261~\3\2\2\2\u0262\u0263\7<\2\2\u0263\u0080") buf.write(u"\3\2\2\2\u0264\u0265\t\2\2\2\u0265\u0082\3\2\2\2\u0266") buf.write(u"\u026a\7f\2\2\u0267\u0269\5\u0081A\2\u0268\u0267\3\2") buf.write(u"\2\2\u0269\u026c\3\2\2\2\u026a\u026b\3\2\2\2\u026a\u0268") buf.write(u"\3\2\2\2\u026b\u0274\3\2\2\2\u026c\u026a\3\2\2\2\u026d") buf.write(u"\u0275\t\3\2\2\u026e\u0270\7^\2\2\u026f\u0271\t\3\2\2") buf.write(u"\u0270\u026f\3\2\2\2\u0271\u0272\3\2\2\2\u0272\u0270") buf.write(u"\3\2\2\2\u0272\u0273\3\2\2\2\u0273\u0275\3\2\2\2\u0274") buf.write(u"\u026d\3\2\2\2\u0274\u026e\3\2\2\2\u0275\u0084\3\2\2") buf.write(u"\2\u0276\u0277\t\3\2\2\u0277\u0086\3\2\2\2\u0278\u0279") buf.write(u"\t\4\2\2\u0279\u0088\3\2\2\2\u027a\u027c\5\u0087D\2\u027b") buf.write(u"\u027a\3\2\2\2\u027c\u027d\3\2\2\2\u027d\u027b\3\2\2") buf.write(u"\2\u027d\u027e\3\2\2\2\u027e\u0286\3\2\2\2\u027f\u0280") buf.write(u"\7.\2\2\u0280\u0281\5\u0087D\2\u0281\u0282\5\u0087D\2") buf.write(u"\u0282\u0283\5\u0087D\2\u0283\u0285\3\2\2\2\u0284\u027f") buf.write(u"\3\2\2\2\u0285\u0288\3\2\2\2\u0286\u0284\3\2\2\2\u0286") buf.write(u"\u0287\3\2\2\2\u0287\u02a0\3\2\2\2\u0288\u0286\3\2\2") buf.write(u"\2\u0289\u028b\5\u0087D\2\u028a\u0289\3\2\2\2\u028b\u028e") buf.write(u"\3\2\2\2\u028c\u028a\3\2\2\2\u028c\u028d\3\2\2\2\u028d") buf.write(u"\u0296\3\2\2\2\u028e\u028c\3\2\2\2\u028f\u0290\7.\2\2") buf.write(u"\u0290\u0291\5\u0087D\2\u0291\u0292\5\u0087D\2\u0292") buf.write(u"\u0293\5\u0087D\2\u0293\u0295\3\2\2\2\u0294\u028f\3\2") buf.write(u"\2\2\u0295\u0298\3\2\2\2\u0296\u0294\3\2\2\2\u0296\u0297") buf.write(u"\3\2\2\2\u0297\u0299\3\2\2\2\u0298\u0296\3\2\2\2\u0299") buf.write(u"\u029b\7\60\2\2\u029a\u029c\5\u0087D\2\u029b\u029a\3") buf.write(u"\2\2\2\u029c\u029d\3\2\2\2\u029d\u029b\3\2\2\2\u029d") buf.write(u"\u029e\3\2\2\2\u029e\u02a0\3\2\2\2\u029f\u027b\3\2\2") buf.write(u"\2\u029f\u028c\3\2\2\2\u02a0\u008a\3\2\2\2\u02a1\u02a2") buf.write(u"\7?\2\2\u02a2\u008c\3\2\2\2\u02a3\u02a4\7^\2\2\u02a4") buf.write(u"\u02a5\7p\2\2\u02a5\u02a6\7g\2\2\u02a6\u02a7\7s\2\2\u02a7") buf.write(u"\u008e\3\2\2\2\u02a8\u02a9\7>\2\2\u02a9\u0090\3\2\2\2") buf.write(u"\u02aa\u02ab\7^\2\2\u02ab\u02ac\7n\2\2\u02ac\u02ad\7") buf.write(u"g\2\2\u02ad\u02b3\7s\2\2\u02ae\u02af\7n\2\2\u02af\u02b3") buf.write(u"\7g\2\2\u02b0\u02b3\5\u0093J\2\u02b1\u02b3\5\u0095K\2") buf.write(u"\u02b2\u02aa\3\2\2\2\u02b2\u02ae\3\2\2\2\u02b2\u02b0") buf.write(u"\3\2\2\2\u02b2\u02b1\3\2\2\2\u02b3\u0092\3\2\2\2\u02b4") buf.write(u"\u02b5\7^\2\2\u02b5\u02b6\7n\2\2\u02b6\u02b7\7g\2\2\u02b7") buf.write(u"\u02b8\7s\2\2\u02b8\u02b9\7s\2\2\u02b9\u0094\3\2\2\2") buf.write(u"\u02ba\u02bb\7^\2\2\u02bb\u02bc\7n\2\2\u02bc\u02bd\7") buf.write(u"g\2\2\u02bd\u02be\7s\2\2\u02be\u02bf\7u\2\2\u02bf\u02c0") buf.write(u"\7n\2\2\u02c0\u02c1\7c\2\2\u02c1\u02c2\7p\2\2\u02c2\u02c3") buf.write(u"\7v\2\2\u02c3\u0096\3\2\2\2\u02c4\u02c5\7@\2\2\u02c5") buf.write(u"\u0098\3\2\2\2\u02c6\u02c7\7^\2\2\u02c7\u02c8\7i\2\2") buf.write(u"\u02c8\u02c9\7g\2\2\u02c9\u02cf\7s\2\2\u02ca\u02cb\7") buf.write(u"i\2\2\u02cb\u02cf\7g\2\2\u02cc\u02cf\5\u009bN\2\u02cd") buf.write(u"\u02cf\5\u009dO\2\u02ce\u02c6\3\2\2\2\u02ce\u02ca\3\2") buf.write(u"\2\2\u02ce\u02cc\3\2\2\2\u02ce\u02cd\3\2\2\2\u02cf\u009a") buf.write(u"\3\2\2\2\u02d0\u02d1\7^\2\2\u02d1\u02d2\7i\2\2\u02d2") buf.write(u"\u02d3\7g\2\2\u02d3\u02d4\7s\2\2\u02d4\u02d5\7s\2\2\u02d5") buf.write(u"\u009c\3\2\2\2\u02d6\u02d7\7^\2\2\u02d7\u02d8\7i\2\2") buf.write(u"\u02d8\u02d9\7g\2\2\u02d9\u02da\7s\2\2\u02da\u02db\7") buf.write(u"u\2\2\u02db\u02dc\7n\2\2\u02dc\u02dd\7c\2\2\u02dd\u02de") buf.write(u"\7p\2\2\u02de\u02df\7v\2\2\u02df\u009e\3\2\2\2\u02e0") buf.write(u"\u02e1\7#\2\2\u02e1\u00a0\3\2\2\2\u02e2\u02e4\7^\2\2") buf.write(u"\u02e3\u02e5\t\3\2\2\u02e4\u02e3\3\2\2\2\u02e5\u02e6") buf.write(u"\3\2\2\2\u02e6\u02e4\3\2\2\2\u02e6\u02e7\3\2\2\2\u02e7") buf.write(u"\u00a2\3\2\2\2\25\2\u00a8\u00b8\u00c7\u00d8\u00fc\u0189") buf.write(u"\u026a\u0272\u0274\u027d\u0286\u028c\u0296\u029d\u029f") buf.write(u"\u02b2\u02ce\u02e6\3\b\2\2") return buf.getvalue() class LaTeXLexer(Lexer): atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] T__0 = 1 WS = 2 THINSPACE = 3 MEDSPACE = 4 THICKSPACE = 5 QUAD = 6 QQUAD = 7 NEGTHINSPACE = 8 NEGMEDSPACE = 9 NEGTHICKSPACE = 10 ADD = 11 SUB = 12 MUL = 13 DIV = 14 L_PAREN = 15 R_PAREN = 16 L_BRACE = 17 R_BRACE = 18 L_BRACE_LITERAL = 19 R_BRACE_LITERAL = 20 L_BRACKET = 21 R_BRACKET = 22 CMD_LEFT = 23 CMD_RIGHT = 24 BAR = 25 FUNC_LIM = 26 LIM_APPROACH_SYM = 27 FUNC_INT = 28 FUNC_SUM = 29 FUNC_PROD = 30 FUNC_EXP = 31 FUNC_LOG = 32 FUNC_LN = 33 FUNC_SIN = 34 FUNC_COS = 35 FUNC_TAN = 36 FUNC_CSC = 37 FUNC_SEC = 38 FUNC_COT = 39 FUNC_ARCSIN = 40 FUNC_ARCCOS = 41 FUNC_ARCTAN = 42 FUNC_ARCCSC = 43 FUNC_ARCSEC = 44 FUNC_ARCCOT = 45 FUNC_SINH = 46 FUNC_COSH = 47 FUNC_TANH = 48 FUNC_ARSINH = 49 FUNC_ARCOSH = 50 FUNC_ARTANH = 51 FUNC_SQRT = 52 CMD_TIMES = 53 CMD_CDOT = 54 CMD_DIV = 55 CMD_FRAC = 56 CMD_BINOM = 57 CMD_DBINOM = 58 CMD_TBINOM = 59 CMD_MATHIT = 60 UNDERSCORE = 61 CARET = 62 COLON = 63 DIFFERENTIAL = 64 LETTER = 65 NUMBER = 66 EQUAL = 67 NEQ = 68 LT = 69 LTE = 70 LTE_Q = 71 LTE_S = 72 GT = 73 GTE = 74 GTE_Q = 75 GTE_S = 76 BANG = 77 SYMBOL = 78 channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ] modeNames = [ u"DEFAULT_MODE" ] literalNames = [ u"<INVALID>", u"','", u"'\\quad'", u"'\\qquad'", u"'\\negmedspace'", u"'\\negthickspace'", u"'+'", u"'-'", u"'*'", u"'/'", u"'('", u"')'", u"'{'", u"'}'", u"'\\{'", u"'\\}'", u"'['", u"']'", u"'\\left'", u"'\\right'", u"'|'", u"'\\lim'", u"'\\int'", u"'\\sum'", u"'\\prod'", u"'\\exp'", u"'\\log'", u"'\\ln'", u"'\\sin'", u"'\\cos'", u"'\\tan'", u"'\\csc'", u"'\\sec'", u"'\\cot'", u"'\\arcsin'", u"'\\arccos'", u"'\\arctan'", u"'\\arccsc'", u"'\\arcsec'", u"'\\arccot'", u"'\\sinh'", u"'\\cosh'", u"'\\tanh'", u"'\\arsinh'", u"'\\arcosh'", u"'\\artanh'", u"'\\sqrt'", u"'\\times'", u"'\\cdot'", u"'\\div'", u"'\\frac'", u"'\\binom'", u"'\\dbinom'", u"'\\tbinom'", u"'\\mathit'", u"'_'", u"'^'", u"':'", u"'='", u"'\\neq'", u"'<'", u"'\\leqq'", u"'\\leqslant'", u"'>'", u"'\\geqq'", u"'\\geqslant'", u"'!'" ] symbolicNames = [ u"<INVALID>", u"WS", u"THINSPACE", u"MEDSPACE", u"THICKSPACE", u"QUAD", u"QQUAD", u"NEGTHINSPACE", u"NEGMEDSPACE", u"NEGTHICKSPACE", u"ADD", u"SUB", u"MUL", u"DIV", u"L_PAREN", u"R_PAREN", u"L_BRACE", u"R_BRACE", u"L_BRACE_LITERAL", u"R_BRACE_LITERAL", u"L_BRACKET", u"R_BRACKET", u"CMD_LEFT", u"CMD_RIGHT", u"BAR", u"FUNC_LIM", u"LIM_APPROACH_SYM", u"FUNC_INT", u"FUNC_SUM", u"FUNC_PROD", u"FUNC_EXP", u"FUNC_LOG", u"FUNC_LN", u"FUNC_SIN", u"FUNC_COS", u"FUNC_TAN", u"FUNC_CSC", u"FUNC_SEC", u"FUNC_COT", u"FUNC_ARCSIN", u"FUNC_ARCCOS", u"FUNC_ARCTAN", u"FUNC_ARCCSC", u"FUNC_ARCSEC", u"FUNC_ARCCOT", u"FUNC_SINH", u"FUNC_COSH", u"FUNC_TANH", u"FUNC_ARSINH", u"FUNC_ARCOSH", u"FUNC_ARTANH", u"FUNC_SQRT", u"CMD_TIMES", u"CMD_CDOT", u"CMD_DIV", u"CMD_FRAC", u"CMD_BINOM", u"CMD_DBINOM", u"CMD_TBINOM", u"CMD_MATHIT", u"UNDERSCORE", u"CARET", u"COLON", u"DIFFERENTIAL", u"LETTER", u"NUMBER", u"EQUAL", u"NEQ", u"LT", u"LTE", u"LTE_Q", u"LTE_S", u"GT", u"GTE", u"GTE_Q", u"GTE_S", u"BANG", u"SYMBOL" ] ruleNames = [ u"T__0", u"WS", u"THINSPACE", u"MEDSPACE", u"THICKSPACE", u"QUAD", u"QQUAD", u"NEGTHINSPACE", u"NEGMEDSPACE", u"NEGTHICKSPACE", u"ADD", u"SUB", u"MUL", u"DIV", u"L_PAREN", u"R_PAREN", u"L_BRACE", u"R_BRACE", u"L_BRACE_LITERAL", u"R_BRACE_LITERAL", u"L_BRACKET", u"R_BRACKET", u"CMD_LEFT", u"CMD_RIGHT", u"BAR", u"FUNC_LIM", u"LIM_APPROACH_SYM", u"FUNC_INT", u"FUNC_SUM", u"FUNC_PROD", u"FUNC_EXP", u"FUNC_LOG", u"FUNC_LN", u"FUNC_SIN", u"FUNC_COS", u"FUNC_TAN", u"FUNC_CSC", u"FUNC_SEC", u"FUNC_COT", u"FUNC_ARCSIN", u"FUNC_ARCCOS", u"FUNC_ARCTAN", u"FUNC_ARCCSC", u"FUNC_ARCSEC", u"FUNC_ARCCOT", u"FUNC_SINH", u"FUNC_COSH", u"FUNC_TANH", u"FUNC_ARSINH", u"FUNC_ARCOSH", u"FUNC_ARTANH", u"FUNC_SQRT", u"CMD_TIMES", u"CMD_CDOT", u"CMD_DIV", u"CMD_FRAC", u"CMD_BINOM", u"CMD_DBINOM", u"CMD_TBINOM", u"CMD_MATHIT", u"UNDERSCORE", u"CARET", u"COLON", u"WS_CHAR", u"DIFFERENTIAL", u"LETTER", u"DIGIT", u"NUMBER", u"EQUAL", u"NEQ", u"LT", u"LTE", u"LTE_Q", u"LTE_S", u"GT", u"GTE", u"GTE_Q", u"GTE_S", u"BANG", u"SYMBOL" ] grammarFileName = u"LaTeX.g4" def __init__(self, input=None, output=sys.stdout): super(LaTeXLexer, self).__init__(input, output=output) self.checkVersion("4.7.2") self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache()) self._actions = None self._predicates = None
be7173262c40e13cd48299fe0f760ea416fe95ff7a44a8a3cad1499ecd785ef3
# encoding: utf-8 # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND *** # # Generated from ../LaTeX.g4, derived from latex2sympy # latex2sympy is licensed under the MIT license # https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt # # Generated with antlr4 # antlr4 is licensed under the BSD-3-Clause License # https://github.com/antlr/antlr4/blob/master/LICENSE.txt from __future__ import print_function from antlr4 import * from io import StringIO import sys def serializedATN(): with StringIO() as buf: buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3") buf.write(u"P\u01b2\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t") buf.write(u"\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r") buf.write(u"\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4") buf.write(u"\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30") buf.write(u"\t\30\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t") buf.write(u"\35\4\36\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$") buf.write(u"\t$\4%\t%\3\2\3\2\3\3\3\3\3\3\3\3\3\3\3\3\7\3S\n\3\f") buf.write(u"\3\16\3V\13\3\3\4\3\4\3\4\3\4\3\5\3\5\3\6\3\6\3\6\3\6") buf.write(u"\3\6\3\6\7\6d\n\6\f\6\16\6g\13\6\3\7\3\7\3\7\3\7\3\7") buf.write(u"\3\7\7\7o\n\7\f\7\16\7r\13\7\3\b\3\b\3\b\3\b\3\b\3\b") buf.write(u"\7\bz\n\b\f\b\16\b}\13\b\3\t\3\t\3\t\6\t\u0082\n\t\r") buf.write(u"\t\16\t\u0083\5\t\u0086\n\t\3\n\3\n\3\n\3\n\7\n\u008c") buf.write(u"\n\n\f\n\16\n\u008f\13\n\5\n\u0091\n\n\3\13\3\13\7\13") buf.write(u"\u0095\n\13\f\13\16\13\u0098\13\13\3\f\3\f\7\f\u009c") buf.write(u"\n\f\f\f\16\f\u009f\13\f\3\r\3\r\5\r\u00a3\n\r\3\16\3") buf.write(u"\16\3\16\3\16\3\16\3\16\5\16\u00ab\n\16\3\17\3\17\3\17") buf.write(u"\3\17\5\17\u00b1\n\17\3\17\3\17\3\20\3\20\3\20\3\20\5") buf.write(u"\20\u00b9\n\20\3\20\3\20\3\21\3\21\3\21\3\21\3\21\3\21") buf.write(u"\3\21\3\21\3\21\3\21\5\21\u00c7\n\21\3\21\5\21\u00ca") buf.write(u"\n\21\7\21\u00cc\n\21\f\21\16\21\u00cf\13\21\3\22\3\22") buf.write(u"\3\22\3\22\3\22\3\22\3\22\3\22\3\22\3\22\5\22\u00db\n") buf.write(u"\22\3\22\5\22\u00de\n\22\7\22\u00e0\n\22\f\22\16\22\u00e3") buf.write(u"\13\22\3\23\3\23\3\23\3\23\3\23\3\23\5\23\u00eb\n\23") buf.write(u"\3\24\3\24\3\24\3\24\3\24\5\24\u00f2\n\24\3\25\3\25\3") buf.write(u"\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25") buf.write(u"\3\25\3\25\3\25\5\25\u0104\n\25\3\26\3\26\3\26\3\26\3") buf.write(u"\27\3\27\5\27\u010c\n\27\3\27\3\27\3\27\5\27\u0111\n") buf.write(u"\27\3\30\3\30\3\30\3\30\3\30\3\31\7\31\u0119\n\31\f\31") buf.write(u"\16\31\u011c\13\31\3\32\3\32\3\32\3\32\3\32\3\32\3\32") buf.write(u"\3\32\3\33\3\33\3\33\3\33\3\33\3\33\3\33\3\33\3\34\3") buf.write(u"\34\3\35\3\35\5\35\u0132\n\35\3\35\5\35\u0135\n\35\3") buf.write(u"\35\5\35\u0138\n\35\3\35\5\35\u013b\n\35\5\35\u013d\n") buf.write(u"\35\3\35\3\35\3\35\3\35\3\35\5\35\u0144\n\35\3\35\3\35") buf.write(u"\5\35\u0148\n\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3") buf.write(u"\35\3\35\3\35\3\35\5\35\u0155\n\35\3\35\5\35\u0158\n") buf.write(u"\35\3\35\3\35\3\35\5\35\u015d\n\35\3\35\3\35\3\35\3\35") buf.write(u"\3\35\5\35\u0164\n\35\3\35\3\35\3\35\3\35\3\35\3\35\3") buf.write(u"\35\3\35\3\35\3\35\3\35\5\35\u0171\n\35\3\35\3\35\3\35") buf.write(u"\3\35\3\35\3\35\5\35\u0179\n\35\3\36\3\36\3\36\3\36\3") buf.write(u"\36\5\36\u0180\n\36\3\37\3\37\3\37\3\37\3\37\3\37\3\37") buf.write(u"\3\37\3\37\5\37\u018b\n\37\3\37\3\37\3 \3 \3 \3 \3 \5") buf.write(u" \u0194\n \3!\3!\3\"\3\"\3\"\3\"\3\"\3\"\5\"\u019e\n") buf.write(u"\"\3#\3#\3#\3#\3#\3#\5#\u01a6\n#\3$\3$\3$\3$\3$\3%\3") buf.write(u"%\3%\3%\3%\3%\2\b\4\n\f\16 \"&\2\4\6\b\n\f\16\20\22\24") buf.write(u"\26\30\32\34\36 \"$&(*,.\60\62\64\668:<>@BDFH\2\t\4\2") buf.write(u"EHKL\3\2\r\16\5\2\17\20\679AA\4\2CCPP\3\2;=\3\2!\65\3") buf.write(u"\2\37 \2\u01cb\2J\3\2\2\2\4L\3\2\2\2\6W\3\2\2\2\b[\3") buf.write(u"\2\2\2\n]\3\2\2\2\fh\3\2\2\2\16s\3\2\2\2\20\u0085\3\2") buf.write(u"\2\2\22\u0090\3\2\2\2\24\u0092\3\2\2\2\26\u0099\3\2\2") buf.write(u"\2\30\u00a2\3\2\2\2\32\u00a4\3\2\2\2\34\u00ac\3\2\2\2") buf.write(u"\36\u00b4\3\2\2\2 \u00bc\3\2\2\2\"\u00d0\3\2\2\2$\u00ea") buf.write(u"\3\2\2\2&\u00f1\3\2\2\2(\u0103\3\2\2\2*\u0105\3\2\2\2") buf.write(u",\u0110\3\2\2\2.\u0112\3\2\2\2\60\u011a\3\2\2\2\62\u011d") buf.write(u"\3\2\2\2\64\u0125\3\2\2\2\66\u012d\3\2\2\28\u0178\3\2") buf.write(u"\2\2:\u017f\3\2\2\2<\u0181\3\2\2\2>\u0193\3\2\2\2@\u0195") buf.write(u"\3\2\2\2B\u0197\3\2\2\2D\u019f\3\2\2\2F\u01a7\3\2\2\2") buf.write(u"H\u01ac\3\2\2\2JK\5\4\3\2K\3\3\2\2\2LM\b\3\1\2MN\5\b") buf.write(u"\5\2NT\3\2\2\2OP\f\4\2\2PQ\t\2\2\2QS\5\4\3\5RO\3\2\2") buf.write(u"\2SV\3\2\2\2TR\3\2\2\2TU\3\2\2\2U\5\3\2\2\2VT\3\2\2\2") buf.write(u"WX\5\b\5\2XY\7E\2\2YZ\5\b\5\2Z\7\3\2\2\2[\\\5\n\6\2\\") buf.write(u"\t\3\2\2\2]^\b\6\1\2^_\5\f\7\2_e\3\2\2\2`a\f\4\2\2ab") buf.write(u"\t\3\2\2bd\5\n\6\5c`\3\2\2\2dg\3\2\2\2ec\3\2\2\2ef\3") buf.write(u"\2\2\2f\13\3\2\2\2ge\3\2\2\2hi\b\7\1\2ij\5\20\t\2jp\3") buf.write(u"\2\2\2kl\f\4\2\2lm\t\4\2\2mo\5\f\7\5nk\3\2\2\2or\3\2") buf.write(u"\2\2pn\3\2\2\2pq\3\2\2\2q\r\3\2\2\2rp\3\2\2\2st\b\b\1") buf.write(u"\2tu\5\22\n\2u{\3\2\2\2vw\f\4\2\2wx\t\4\2\2xz\5\16\b") buf.write(u"\5yv\3\2\2\2z}\3\2\2\2{y\3\2\2\2{|\3\2\2\2|\17\3\2\2") buf.write(u"\2}{\3\2\2\2~\177\t\3\2\2\177\u0086\5\20\t\2\u0080\u0082") buf.write(u"\5\24\13\2\u0081\u0080\3\2\2\2\u0082\u0083\3\2\2\2\u0083") buf.write(u"\u0081\3\2\2\2\u0083\u0084\3\2\2\2\u0084\u0086\3\2\2") buf.write(u"\2\u0085~\3\2\2\2\u0085\u0081\3\2\2\2\u0086\21\3\2\2") buf.write(u"\2\u0087\u0088\t\3\2\2\u0088\u0091\5\22\n\2\u0089\u008d") buf.write(u"\5\24\13\2\u008a\u008c\5\26\f\2\u008b\u008a\3\2\2\2\u008c") buf.write(u"\u008f\3\2\2\2\u008d\u008b\3\2\2\2\u008d\u008e\3\2\2") buf.write(u"\2\u008e\u0091\3\2\2\2\u008f\u008d\3\2\2\2\u0090\u0087") buf.write(u"\3\2\2\2\u0090\u0089\3\2\2\2\u0091\23\3\2\2\2\u0092\u0096") buf.write(u"\5 \21\2\u0093\u0095\5\30\r\2\u0094\u0093\3\2\2\2\u0095") buf.write(u"\u0098\3\2\2\2\u0096\u0094\3\2\2\2\u0096\u0097\3\2\2") buf.write(u"\2\u0097\25\3\2\2\2\u0098\u0096\3\2\2\2\u0099\u009d\5") buf.write(u"\"\22\2\u009a\u009c\5\30\r\2\u009b\u009a\3\2\2\2\u009c") buf.write(u"\u009f\3\2\2\2\u009d\u009b\3\2\2\2\u009d\u009e\3\2\2") buf.write(u"\2\u009e\27\3\2\2\2\u009f\u009d\3\2\2\2\u00a0\u00a3\7") buf.write(u"O\2\2\u00a1\u00a3\5\32\16\2\u00a2\u00a0\3\2\2\2\u00a2") buf.write(u"\u00a1\3\2\2\2\u00a3\31\3\2\2\2\u00a4\u00aa\7\33\2\2") buf.write(u"\u00a5\u00ab\5\36\20\2\u00a6\u00ab\5\34\17\2\u00a7\u00a8") buf.write(u"\5\36\20\2\u00a8\u00a9\5\34\17\2\u00a9\u00ab\3\2\2\2") buf.write(u"\u00aa\u00a5\3\2\2\2\u00aa\u00a6\3\2\2\2\u00aa\u00a7") buf.write(u"\3\2\2\2\u00ab\33\3\2\2\2\u00ac\u00ad\7?\2\2\u00ad\u00b0") buf.write(u"\7\23\2\2\u00ae\u00b1\5\b\5\2\u00af\u00b1\5\6\4\2\u00b0") buf.write(u"\u00ae\3\2\2\2\u00b0\u00af\3\2\2\2\u00b1\u00b2\3\2\2") buf.write(u"\2\u00b2\u00b3\7\24\2\2\u00b3\35\3\2\2\2\u00b4\u00b5") buf.write(u"\7@\2\2\u00b5\u00b8\7\23\2\2\u00b6\u00b9\5\b\5\2\u00b7") buf.write(u"\u00b9\5\6\4\2\u00b8\u00b6\3\2\2\2\u00b8\u00b7\3\2\2") buf.write(u"\2\u00b9\u00ba\3\2\2\2\u00ba\u00bb\7\24\2\2\u00bb\37") buf.write(u"\3\2\2\2\u00bc\u00bd\b\21\1\2\u00bd\u00be\5$\23\2\u00be") buf.write(u"\u00cd\3\2\2\2\u00bf\u00c0\f\4\2\2\u00c0\u00c6\7@\2\2") buf.write(u"\u00c1\u00c7\5,\27\2\u00c2\u00c3\7\23\2\2\u00c3\u00c4") buf.write(u"\5\b\5\2\u00c4\u00c5\7\24\2\2\u00c5\u00c7\3\2\2\2\u00c6") buf.write(u"\u00c1\3\2\2\2\u00c6\u00c2\3\2\2\2\u00c7\u00c9\3\2\2") buf.write(u"\2\u00c8\u00ca\5B\"\2\u00c9\u00c8\3\2\2\2\u00c9\u00ca") buf.write(u"\3\2\2\2\u00ca\u00cc\3\2\2\2\u00cb\u00bf\3\2\2\2\u00cc") buf.write(u"\u00cf\3\2\2\2\u00cd\u00cb\3\2\2\2\u00cd\u00ce\3\2\2") buf.write(u"\2\u00ce!\3\2\2\2\u00cf\u00cd\3\2\2\2\u00d0\u00d1\b\22") buf.write(u"\1\2\u00d1\u00d2\5&\24\2\u00d2\u00e1\3\2\2\2\u00d3\u00d4") buf.write(u"\f\4\2\2\u00d4\u00da\7@\2\2\u00d5\u00db\5,\27\2\u00d6") buf.write(u"\u00d7\7\23\2\2\u00d7\u00d8\5\b\5\2\u00d8\u00d9\7\24") buf.write(u"\2\2\u00d9\u00db\3\2\2\2\u00da\u00d5\3\2\2\2\u00da\u00d6") buf.write(u"\3\2\2\2\u00db\u00dd\3\2\2\2\u00dc\u00de\5B\"\2\u00dd") buf.write(u"\u00dc\3\2\2\2\u00dd\u00de\3\2\2\2\u00de\u00e0\3\2\2") buf.write(u"\2\u00df\u00d3\3\2\2\2\u00e0\u00e3\3\2\2\2\u00e1\u00df") buf.write(u"\3\2\2\2\u00e1\u00e2\3\2\2\2\u00e2#\3\2\2\2\u00e3\u00e1") buf.write(u"\3\2\2\2\u00e4\u00eb\5(\25\2\u00e5\u00eb\5*\26\2\u00e6") buf.write(u"\u00eb\58\35\2\u00e7\u00eb\5,\27\2\u00e8\u00eb\5\62\32") buf.write(u"\2\u00e9\u00eb\5\64\33\2\u00ea\u00e4\3\2\2\2\u00ea\u00e5") buf.write(u"\3\2\2\2\u00ea\u00e6\3\2\2\2\u00ea\u00e7\3\2\2\2\u00ea") buf.write(u"\u00e8\3\2\2\2\u00ea\u00e9\3\2\2\2\u00eb%\3\2\2\2\u00ec") buf.write(u"\u00f2\5(\25\2\u00ed\u00f2\5*\26\2\u00ee\u00f2\5,\27") buf.write(u"\2\u00ef\u00f2\5\62\32\2\u00f0\u00f2\5\64\33\2\u00f1") buf.write(u"\u00ec\3\2\2\2\u00f1\u00ed\3\2\2\2\u00f1\u00ee\3\2\2") buf.write(u"\2\u00f1\u00ef\3\2\2\2\u00f1\u00f0\3\2\2\2\u00f2\'\3") buf.write(u"\2\2\2\u00f3\u00f4\7\21\2\2\u00f4\u00f5\5\b\5\2\u00f5") buf.write(u"\u00f6\7\22\2\2\u00f6\u0104\3\2\2\2\u00f7\u00f8\7\27") buf.write(u"\2\2\u00f8\u00f9\5\b\5\2\u00f9\u00fa\7\30\2\2\u00fa\u0104") buf.write(u"\3\2\2\2\u00fb\u00fc\7\23\2\2\u00fc\u00fd\5\b\5\2\u00fd") buf.write(u"\u00fe\7\24\2\2\u00fe\u0104\3\2\2\2\u00ff\u0100\7\25") buf.write(u"\2\2\u0100\u0101\5\b\5\2\u0101\u0102\7\26\2\2\u0102\u0104") buf.write(u"\3\2\2\2\u0103\u00f3\3\2\2\2\u0103\u00f7\3\2\2\2\u0103") buf.write(u"\u00fb\3\2\2\2\u0103\u00ff\3\2\2\2\u0104)\3\2\2\2\u0105") buf.write(u"\u0106\7\33\2\2\u0106\u0107\5\b\5\2\u0107\u0108\7\33") buf.write(u"\2\2\u0108+\3\2\2\2\u0109\u010b\t\5\2\2\u010a\u010c\5") buf.write(u"B\"\2\u010b\u010a\3\2\2\2\u010b\u010c\3\2\2\2\u010c\u0111") buf.write(u"\3\2\2\2\u010d\u0111\7D\2\2\u010e\u0111\7B\2\2\u010f") buf.write(u"\u0111\5.\30\2\u0110\u0109\3\2\2\2\u0110\u010d\3\2\2") buf.write(u"\2\u0110\u010e\3\2\2\2\u0110\u010f\3\2\2\2\u0111-\3\2") buf.write(u"\2\2\u0112\u0113\7>\2\2\u0113\u0114\7\23\2\2\u0114\u0115") buf.write(u"\5\60\31\2\u0115\u0116\7\24\2\2\u0116/\3\2\2\2\u0117") buf.write(u"\u0119\7C\2\2\u0118\u0117\3\2\2\2\u0119\u011c\3\2\2\2") buf.write(u"\u011a\u0118\3\2\2\2\u011a\u011b\3\2\2\2\u011b\61\3\2") buf.write(u"\2\2\u011c\u011a\3\2\2\2\u011d\u011e\7:\2\2\u011e\u011f") buf.write(u"\7\23\2\2\u011f\u0120\5\b\5\2\u0120\u0121\7\24\2\2\u0121") buf.write(u"\u0122\7\23\2\2\u0122\u0123\5\b\5\2\u0123\u0124\7\24") buf.write(u"\2\2\u0124\63\3\2\2\2\u0125\u0126\t\6\2\2\u0126\u0127") buf.write(u"\7\23\2\2\u0127\u0128\5\b\5\2\u0128\u0129\7\24\2\2\u0129") buf.write(u"\u012a\7\23\2\2\u012a\u012b\5\b\5\2\u012b\u012c\7\24") buf.write(u"\2\2\u012c\65\3\2\2\2\u012d\u012e\t\7\2\2\u012e\67\3") buf.write(u"\2\2\2\u012f\u013c\5\66\34\2\u0130\u0132\5B\"\2\u0131") buf.write(u"\u0130\3\2\2\2\u0131\u0132\3\2\2\2\u0132\u0134\3\2\2") buf.write(u"\2\u0133\u0135\5D#\2\u0134\u0133\3\2\2\2\u0134\u0135") buf.write(u"\3\2\2\2\u0135\u013d\3\2\2\2\u0136\u0138\5D#\2\u0137") buf.write(u"\u0136\3\2\2\2\u0137\u0138\3\2\2\2\u0138\u013a\3\2\2") buf.write(u"\2\u0139\u013b\5B\"\2\u013a\u0139\3\2\2\2\u013a\u013b") buf.write(u"\3\2\2\2\u013b\u013d\3\2\2\2\u013c\u0131\3\2\2\2\u013c") buf.write(u"\u0137\3\2\2\2\u013d\u0143\3\2\2\2\u013e\u013f\7\21\2") buf.write(u"\2\u013f\u0140\5> \2\u0140\u0141\7\22\2\2\u0141\u0144") buf.write(u"\3\2\2\2\u0142\u0144\5@!\2\u0143\u013e\3\2\2\2\u0143") buf.write(u"\u0142\3\2\2\2\u0144\u0179\3\2\2\2\u0145\u0147\t\5\2") buf.write(u"\2\u0146\u0148\5B\"\2\u0147\u0146\3\2\2\2\u0147\u0148") buf.write(u"\3\2\2\2\u0148\u0149\3\2\2\2\u0149\u014a\7\21\2\2\u014a") buf.write(u"\u014b\5:\36\2\u014b\u014c\7\22\2\2\u014c\u0179\3\2\2") buf.write(u"\2\u014d\u0154\7\36\2\2\u014e\u014f\5B\"\2\u014f\u0150") buf.write(u"\5D#\2\u0150\u0155\3\2\2\2\u0151\u0152\5D#\2\u0152\u0153") buf.write(u"\5B\"\2\u0153\u0155\3\2\2\2\u0154\u014e\3\2\2\2\u0154") buf.write(u"\u0151\3\2\2\2\u0154\u0155\3\2\2\2\u0155\u015c\3\2\2") buf.write(u"\2\u0156\u0158\5\n\6\2\u0157\u0156\3\2\2\2\u0157\u0158") buf.write(u"\3\2\2\2\u0158\u0159\3\2\2\2\u0159\u015d\7B\2\2\u015a") buf.write(u"\u015d\5\62\32\2\u015b\u015d\5\n\6\2\u015c\u0157\3\2") buf.write(u"\2\2\u015c\u015a\3\2\2\2\u015c\u015b\3\2\2\2\u015d\u0179") buf.write(u"\3\2\2\2\u015e\u0163\7\66\2\2\u015f\u0160\7\27\2\2\u0160") buf.write(u"\u0161\5\b\5\2\u0161\u0162\7\30\2\2\u0162\u0164\3\2\2") buf.write(u"\2\u0163\u015f\3\2\2\2\u0163\u0164\3\2\2\2\u0164\u0165") buf.write(u"\3\2\2\2\u0165\u0166\7\23\2\2\u0166\u0167\5\b\5\2\u0167") buf.write(u"\u0168\7\24\2\2\u0168\u0179\3\2\2\2\u0169\u0170\t\b\2") buf.write(u"\2\u016a\u016b\5F$\2\u016b\u016c\5D#\2\u016c\u0171\3") buf.write(u"\2\2\2\u016d\u016e\5D#\2\u016e\u016f\5F$\2\u016f\u0171") buf.write(u"\3\2\2\2\u0170\u016a\3\2\2\2\u0170\u016d\3\2\2\2\u0171") buf.write(u"\u0172\3\2\2\2\u0172\u0173\5\f\7\2\u0173\u0179\3\2\2") buf.write(u"\2\u0174\u0175\7\34\2\2\u0175\u0176\5<\37\2\u0176\u0177") buf.write(u"\5\f\7\2\u0177\u0179\3\2\2\2\u0178\u012f\3\2\2\2\u0178") buf.write(u"\u0145\3\2\2\2\u0178\u014d\3\2\2\2\u0178\u015e\3\2\2") buf.write(u"\2\u0178\u0169\3\2\2\2\u0178\u0174\3\2\2\2\u01799\3\2") buf.write(u"\2\2\u017a\u017b\5\b\5\2\u017b\u017c\7\3\2\2\u017c\u017d") buf.write(u"\5:\36\2\u017d\u0180\3\2\2\2\u017e\u0180\5\b\5\2\u017f") buf.write(u"\u017a\3\2\2\2\u017f\u017e\3\2\2\2\u0180;\3\2\2\2\u0181") buf.write(u"\u0182\7?\2\2\u0182\u0183\7\23\2\2\u0183\u0184\t\5\2") buf.write(u"\2\u0184\u0185\7\35\2\2\u0185\u018a\5\b\5\2\u0186\u0187") buf.write(u"\7@\2\2\u0187\u0188\7\23\2\2\u0188\u0189\t\3\2\2\u0189") buf.write(u"\u018b\7\24\2\2\u018a\u0186\3\2\2\2\u018a\u018b\3\2\2") buf.write(u"\2\u018b\u018c\3\2\2\2\u018c\u018d\7\24\2\2\u018d=\3") buf.write(u"\2\2\2\u018e\u0194\5\b\5\2\u018f\u0190\5\b\5\2\u0190") buf.write(u"\u0191\7\3\2\2\u0191\u0192\5> \2\u0192\u0194\3\2\2\2") buf.write(u"\u0193\u018e\3\2\2\2\u0193\u018f\3\2\2\2\u0194?\3\2\2") buf.write(u"\2\u0195\u0196\5\16\b\2\u0196A\3\2\2\2\u0197\u019d\7") buf.write(u"?\2\2\u0198\u019e\5,\27\2\u0199\u019a\7\23\2\2\u019a") buf.write(u"\u019b\5\b\5\2\u019b\u019c\7\24\2\2\u019c\u019e\3\2\2") buf.write(u"\2\u019d\u0198\3\2\2\2\u019d\u0199\3\2\2\2\u019eC\3\2") buf.write(u"\2\2\u019f\u01a5\7@\2\2\u01a0\u01a6\5,\27\2\u01a1\u01a2") buf.write(u"\7\23\2\2\u01a2\u01a3\5\b\5\2\u01a3\u01a4\7\24\2\2\u01a4") buf.write(u"\u01a6\3\2\2\2\u01a5\u01a0\3\2\2\2\u01a5\u01a1\3\2\2") buf.write(u"\2\u01a6E\3\2\2\2\u01a7\u01a8\7?\2\2\u01a8\u01a9\7\23") buf.write(u"\2\2\u01a9\u01aa\5\6\4\2\u01aa\u01ab\7\24\2\2\u01abG") buf.write(u"\3\2\2\2\u01ac\u01ad\7?\2\2\u01ad\u01ae\7\23\2\2\u01ae") buf.write(u"\u01af\5\6\4\2\u01af\u01b0\7\24\2\2\u01b0I\3\2\2\2.T") buf.write(u"ep{\u0083\u0085\u008d\u0090\u0096\u009d\u00a2\u00aa\u00b0") buf.write(u"\u00b8\u00c6\u00c9\u00cd\u00da\u00dd\u00e1\u00ea\u00f1") buf.write(u"\u0103\u010b\u0110\u011a\u0131\u0134\u0137\u013a\u013c") buf.write(u"\u0143\u0147\u0154\u0157\u015c\u0163\u0170\u0178\u017f") buf.write(u"\u018a\u0193\u019d\u01a5") return buf.getvalue() class LaTeXParser ( Parser ): grammarFileName = "LaTeX.g4" atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] sharedContextCache = PredictionContextCache() literalNames = [ u"<INVALID>", u"','", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"'\\quad'", u"'\\qquad'", u"<INVALID>", u"'\\negmedspace'", u"'\\negthickspace'", u"'+'", u"'-'", u"'*'", u"'/'", u"'('", u"')'", u"'{'", u"'}'", u"'\\{'", u"'\\}'", u"'['", u"']'", u"'\\left'", u"'\\right'", u"'|'", u"'\\lim'", u"<INVALID>", u"'\\int'", u"'\\sum'", u"'\\prod'", u"'\\exp'", u"'\\log'", u"'\\ln'", u"'\\sin'", u"'\\cos'", u"'\\tan'", u"'\\csc'", u"'\\sec'", u"'\\cot'", u"'\\arcsin'", u"'\\arccos'", u"'\\arctan'", u"'\\arccsc'", u"'\\arcsec'", u"'\\arccot'", u"'\\sinh'", u"'\\cosh'", u"'\\tanh'", u"'\\arsinh'", u"'\\arcosh'", u"'\\artanh'", u"'\\sqrt'", u"'\\times'", u"'\\cdot'", u"'\\div'", u"'\\frac'", u"'\\binom'", u"'\\dbinom'", u"'\\tbinom'", u"'\\mathit'", u"'_'", u"'^'", u"':'", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"'='", u"'\\neq'", u"'<'", u"<INVALID>", u"'\\leqq'", u"'\\leqslant'", u"'>'", u"<INVALID>", u"'\\geqq'", u"'\\geqslant'", u"'!'" ] symbolicNames = [ u"<INVALID>", u"<INVALID>", u"WS", u"THINSPACE", u"MEDSPACE", u"THICKSPACE", u"QUAD", u"QQUAD", u"NEGTHINSPACE", u"NEGMEDSPACE", u"NEGTHICKSPACE", u"ADD", u"SUB", u"MUL", u"DIV", u"L_PAREN", u"R_PAREN", u"L_BRACE", u"R_BRACE", u"L_BRACE_LITERAL", u"R_BRACE_LITERAL", u"L_BRACKET", u"R_BRACKET", u"CMD_LEFT", u"CMD_RIGHT", u"BAR", u"FUNC_LIM", u"LIM_APPROACH_SYM", u"FUNC_INT", u"FUNC_SUM", u"FUNC_PROD", u"FUNC_EXP", u"FUNC_LOG", u"FUNC_LN", u"FUNC_SIN", u"FUNC_COS", u"FUNC_TAN", u"FUNC_CSC", u"FUNC_SEC", u"FUNC_COT", u"FUNC_ARCSIN", u"FUNC_ARCCOS", u"FUNC_ARCTAN", u"FUNC_ARCCSC", u"FUNC_ARCSEC", u"FUNC_ARCCOT", u"FUNC_SINH", u"FUNC_COSH", u"FUNC_TANH", u"FUNC_ARSINH", u"FUNC_ARCOSH", u"FUNC_ARTANH", u"FUNC_SQRT", u"CMD_TIMES", u"CMD_CDOT", u"CMD_DIV", u"CMD_FRAC", u"CMD_BINOM", u"CMD_DBINOM", u"CMD_TBINOM", u"CMD_MATHIT", u"UNDERSCORE", u"CARET", u"COLON", u"DIFFERENTIAL", u"LETTER", u"NUMBER", u"EQUAL", u"NEQ", u"LT", u"LTE", u"LTE_Q", u"LTE_S", u"GT", u"GTE", u"GTE_Q", u"GTE_S", u"BANG", u"SYMBOL" ] RULE_math = 0 RULE_relation = 1 RULE_equality = 2 RULE_expr = 3 RULE_additive = 4 RULE_mp = 5 RULE_mp_nofunc = 6 RULE_unary = 7 RULE_unary_nofunc = 8 RULE_postfix = 9 RULE_postfix_nofunc = 10 RULE_postfix_op = 11 RULE_eval_at = 12 RULE_eval_at_sub = 13 RULE_eval_at_sup = 14 RULE_exp = 15 RULE_exp_nofunc = 16 RULE_comp = 17 RULE_comp_nofunc = 18 RULE_group = 19 RULE_abs_group = 20 RULE_atom = 21 RULE_mathit = 22 RULE_mathit_text = 23 RULE_frac = 24 RULE_binom = 25 RULE_func_normal = 26 RULE_func = 27 RULE_args = 28 RULE_limit_sub = 29 RULE_func_arg = 30 RULE_func_arg_noparens = 31 RULE_subexpr = 32 RULE_supexpr = 33 RULE_subeq = 34 RULE_supeq = 35 ruleNames = [ u"math", u"relation", u"equality", u"expr", u"additive", u"mp", u"mp_nofunc", u"unary", u"unary_nofunc", u"postfix", u"postfix_nofunc", u"postfix_op", u"eval_at", u"eval_at_sub", u"eval_at_sup", u"exp", u"exp_nofunc", u"comp", u"comp_nofunc", u"group", u"abs_group", u"atom", u"mathit", u"mathit_text", u"frac", u"binom", u"func_normal", u"func", u"args", u"limit_sub", u"func_arg", u"func_arg_noparens", u"subexpr", u"supexpr", u"subeq", u"supeq" ] EOF = Token.EOF T__0=1 WS=2 THINSPACE=3 MEDSPACE=4 THICKSPACE=5 QUAD=6 QQUAD=7 NEGTHINSPACE=8 NEGMEDSPACE=9 NEGTHICKSPACE=10 ADD=11 SUB=12 MUL=13 DIV=14 L_PAREN=15 R_PAREN=16 L_BRACE=17 R_BRACE=18 L_BRACE_LITERAL=19 R_BRACE_LITERAL=20 L_BRACKET=21 R_BRACKET=22 CMD_LEFT=23 CMD_RIGHT=24 BAR=25 FUNC_LIM=26 LIM_APPROACH_SYM=27 FUNC_INT=28 FUNC_SUM=29 FUNC_PROD=30 FUNC_EXP=31 FUNC_LOG=32 FUNC_LN=33 FUNC_SIN=34 FUNC_COS=35 FUNC_TAN=36 FUNC_CSC=37 FUNC_SEC=38 FUNC_COT=39 FUNC_ARCSIN=40 FUNC_ARCCOS=41 FUNC_ARCTAN=42 FUNC_ARCCSC=43 FUNC_ARCSEC=44 FUNC_ARCCOT=45 FUNC_SINH=46 FUNC_COSH=47 FUNC_TANH=48 FUNC_ARSINH=49 FUNC_ARCOSH=50 FUNC_ARTANH=51 FUNC_SQRT=52 CMD_TIMES=53 CMD_CDOT=54 CMD_DIV=55 CMD_FRAC=56 CMD_BINOM=57 CMD_DBINOM=58 CMD_TBINOM=59 CMD_MATHIT=60 UNDERSCORE=61 CARET=62 COLON=63 DIFFERENTIAL=64 LETTER=65 NUMBER=66 EQUAL=67 NEQ=68 LT=69 LTE=70 LTE_Q=71 LTE_S=72 GT=73 GTE=74 GTE_Q=75 GTE_S=76 BANG=77 SYMBOL=78 def __init__(self, input, output=sys.stdout): super(LaTeXParser, self).__init__(input, output=output) self.checkVersion("4.7.2") self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache) self._predicates = None class MathContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.MathContext, self).__init__(parent, invokingState) self.parser = parser def relation(self): return self.getTypedRuleContext(LaTeXParser.RelationContext,0) def getRuleIndex(self): return LaTeXParser.RULE_math def math(self): localctx = LaTeXParser.MathContext(self, self._ctx, self.state) self.enterRule(localctx, 0, self.RULE_math) try: self.enterOuterAlt(localctx, 1) self.state = 72 self.relation(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class RelationContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.RelationContext, self).__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def relation(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.RelationContext) else: return self.getTypedRuleContext(LaTeXParser.RelationContext,i) def EQUAL(self): return self.getToken(LaTeXParser.EQUAL, 0) def LT(self): return self.getToken(LaTeXParser.LT, 0) def LTE(self): return self.getToken(LaTeXParser.LTE, 0) def GT(self): return self.getToken(LaTeXParser.GT, 0) def GTE(self): return self.getToken(LaTeXParser.GTE, 0) def NEQ(self): return self.getToken(LaTeXParser.NEQ, 0) def getRuleIndex(self): return LaTeXParser.RULE_relation def relation(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.RelationContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 2 self.enterRecursionRule(localctx, 2, self.RULE_relation, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 75 self.expr() self._ctx.stop = self._input.LT(-1) self.state = 82 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,0,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.RelationContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_relation) self.state = 77 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 78 _la = self._input.LA(1) if not(((((_la - 67)) & ~0x3f) == 0 and ((1 << (_la - 67)) & ((1 << (LaTeXParser.EQUAL - 67)) | (1 << (LaTeXParser.NEQ - 67)) | (1 << (LaTeXParser.LT - 67)) | (1 << (LaTeXParser.LTE - 67)) | (1 << (LaTeXParser.GT - 67)) | (1 << (LaTeXParser.GTE - 67)))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 79 self.relation(3) self.state = 84 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,0,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class EqualityContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.EqualityContext, self).__init__(parent, invokingState) self.parser = parser def expr(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.ExprContext) else: return self.getTypedRuleContext(LaTeXParser.ExprContext,i) def EQUAL(self): return self.getToken(LaTeXParser.EQUAL, 0) def getRuleIndex(self): return LaTeXParser.RULE_equality def equality(self): localctx = LaTeXParser.EqualityContext(self, self._ctx, self.state) self.enterRule(localctx, 4, self.RULE_equality) try: self.enterOuterAlt(localctx, 1) self.state = 85 self.expr() self.state = 86 self.match(LaTeXParser.EQUAL) self.state = 87 self.expr() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExprContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.ExprContext, self).__init__(parent, invokingState) self.parser = parser def additive(self): return self.getTypedRuleContext(LaTeXParser.AdditiveContext,0) def getRuleIndex(self): return LaTeXParser.RULE_expr def expr(self): localctx = LaTeXParser.ExprContext(self, self._ctx, self.state) self.enterRule(localctx, 6, self.RULE_expr) try: self.enterOuterAlt(localctx, 1) self.state = 89 self.additive(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AdditiveContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.AdditiveContext, self).__init__(parent, invokingState) self.parser = parser def mp(self): return self.getTypedRuleContext(LaTeXParser.MpContext,0) def additive(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.AdditiveContext) else: return self.getTypedRuleContext(LaTeXParser.AdditiveContext,i) def ADD(self): return self.getToken(LaTeXParser.ADD, 0) def SUB(self): return self.getToken(LaTeXParser.SUB, 0) def getRuleIndex(self): return LaTeXParser.RULE_additive def additive(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.AdditiveContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 8 self.enterRecursionRule(localctx, 8, self.RULE_additive, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 92 self.mp(0) self._ctx.stop = self._input.LT(-1) self.state = 99 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,1,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.AdditiveContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_additive) self.state = 94 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 95 _la = self._input.LA(1) if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 96 self.additive(3) self.state = 101 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,1,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class MpContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.MpContext, self).__init__(parent, invokingState) self.parser = parser def unary(self): return self.getTypedRuleContext(LaTeXParser.UnaryContext,0) def mp(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.MpContext) else: return self.getTypedRuleContext(LaTeXParser.MpContext,i) def MUL(self): return self.getToken(LaTeXParser.MUL, 0) def CMD_TIMES(self): return self.getToken(LaTeXParser.CMD_TIMES, 0) def CMD_CDOT(self): return self.getToken(LaTeXParser.CMD_CDOT, 0) def DIV(self): return self.getToken(LaTeXParser.DIV, 0) def CMD_DIV(self): return self.getToken(LaTeXParser.CMD_DIV, 0) def COLON(self): return self.getToken(LaTeXParser.COLON, 0) def getRuleIndex(self): return LaTeXParser.RULE_mp def mp(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.MpContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 10 self.enterRecursionRule(localctx, 10, self.RULE_mp, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 103 self.unary() self._ctx.stop = self._input.LT(-1) self.state = 110 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,2,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.MpContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_mp) self.state = 105 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 106 _la = self._input.LA(1) if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << LaTeXParser.MUL) | (1 << LaTeXParser.DIV) | (1 << LaTeXParser.CMD_TIMES) | (1 << LaTeXParser.CMD_CDOT) | (1 << LaTeXParser.CMD_DIV) | (1 << LaTeXParser.COLON))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 107 self.mp(3) self.state = 112 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,2,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class Mp_nofuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Mp_nofuncContext, self).__init__(parent, invokingState) self.parser = parser def unary_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Unary_nofuncContext,0) def mp_nofunc(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.Mp_nofuncContext) else: return self.getTypedRuleContext(LaTeXParser.Mp_nofuncContext,i) def MUL(self): return self.getToken(LaTeXParser.MUL, 0) def CMD_TIMES(self): return self.getToken(LaTeXParser.CMD_TIMES, 0) def CMD_CDOT(self): return self.getToken(LaTeXParser.CMD_CDOT, 0) def DIV(self): return self.getToken(LaTeXParser.DIV, 0) def CMD_DIV(self): return self.getToken(LaTeXParser.CMD_DIV, 0) def COLON(self): return self.getToken(LaTeXParser.COLON, 0) def getRuleIndex(self): return LaTeXParser.RULE_mp_nofunc def mp_nofunc(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.Mp_nofuncContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 12 self.enterRecursionRule(localctx, 12, self.RULE_mp_nofunc, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 114 self.unary_nofunc() self._ctx.stop = self._input.LT(-1) self.state = 121 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,3,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.Mp_nofuncContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_mp_nofunc) self.state = 116 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 117 _la = self._input.LA(1) if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << LaTeXParser.MUL) | (1 << LaTeXParser.DIV) | (1 << LaTeXParser.CMD_TIMES) | (1 << LaTeXParser.CMD_CDOT) | (1 << LaTeXParser.CMD_DIV) | (1 << LaTeXParser.COLON))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 118 self.mp_nofunc(3) self.state = 123 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,3,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class UnaryContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.UnaryContext, self).__init__(parent, invokingState) self.parser = parser def unary(self): return self.getTypedRuleContext(LaTeXParser.UnaryContext,0) def ADD(self): return self.getToken(LaTeXParser.ADD, 0) def SUB(self): return self.getToken(LaTeXParser.SUB, 0) def postfix(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.PostfixContext) else: return self.getTypedRuleContext(LaTeXParser.PostfixContext,i) def getRuleIndex(self): return LaTeXParser.RULE_unary def unary(self): localctx = LaTeXParser.UnaryContext(self, self._ctx, self.state) self.enterRule(localctx, 14, self.RULE_unary) self._la = 0 # Token type try: self.state = 131 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.ADD, LaTeXParser.SUB]: self.enterOuterAlt(localctx, 1) self.state = 124 _la = self._input.LA(1) if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 125 self.unary() pass elif token in [LaTeXParser.L_PAREN, LaTeXParser.L_BRACE, LaTeXParser.L_BRACE_LITERAL, LaTeXParser.L_BRACKET, LaTeXParser.BAR, LaTeXParser.FUNC_LIM, LaTeXParser.FUNC_INT, LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD, LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH, LaTeXParser.FUNC_SQRT, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.enterOuterAlt(localctx, 2) self.state = 127 self._errHandler.sync(self) _alt = 1 while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt == 1: self.state = 126 self.postfix() else: raise NoViableAltException(self) self.state = 129 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,4,self._ctx) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Unary_nofuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Unary_nofuncContext, self).__init__(parent, invokingState) self.parser = parser def unary_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Unary_nofuncContext,0) def ADD(self): return self.getToken(LaTeXParser.ADD, 0) def SUB(self): return self.getToken(LaTeXParser.SUB, 0) def postfix(self): return self.getTypedRuleContext(LaTeXParser.PostfixContext,0) def postfix_nofunc(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.Postfix_nofuncContext) else: return self.getTypedRuleContext(LaTeXParser.Postfix_nofuncContext,i) def getRuleIndex(self): return LaTeXParser.RULE_unary_nofunc def unary_nofunc(self): localctx = LaTeXParser.Unary_nofuncContext(self, self._ctx, self.state) self.enterRule(localctx, 16, self.RULE_unary_nofunc) self._la = 0 # Token type try: self.state = 142 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.ADD, LaTeXParser.SUB]: self.enterOuterAlt(localctx, 1) self.state = 133 _la = self._input.LA(1) if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 134 self.unary_nofunc() pass elif token in [LaTeXParser.L_PAREN, LaTeXParser.L_BRACE, LaTeXParser.L_BRACE_LITERAL, LaTeXParser.L_BRACKET, LaTeXParser.BAR, LaTeXParser.FUNC_LIM, LaTeXParser.FUNC_INT, LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD, LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH, LaTeXParser.FUNC_SQRT, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.enterOuterAlt(localctx, 2) self.state = 135 self.postfix() self.state = 139 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,6,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 136 self.postfix_nofunc() self.state = 141 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,6,self._ctx) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class PostfixContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.PostfixContext, self).__init__(parent, invokingState) self.parser = parser def exp(self): return self.getTypedRuleContext(LaTeXParser.ExpContext,0) def postfix_op(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.Postfix_opContext) else: return self.getTypedRuleContext(LaTeXParser.Postfix_opContext,i) def getRuleIndex(self): return LaTeXParser.RULE_postfix def postfix(self): localctx = LaTeXParser.PostfixContext(self, self._ctx, self.state) self.enterRule(localctx, 18, self.RULE_postfix) try: self.enterOuterAlt(localctx, 1) self.state = 144 self.exp(0) self.state = 148 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,8,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 145 self.postfix_op() self.state = 150 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,8,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Postfix_nofuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Postfix_nofuncContext, self).__init__(parent, invokingState) self.parser = parser def exp_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Exp_nofuncContext,0) def postfix_op(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.Postfix_opContext) else: return self.getTypedRuleContext(LaTeXParser.Postfix_opContext,i) def getRuleIndex(self): return LaTeXParser.RULE_postfix_nofunc def postfix_nofunc(self): localctx = LaTeXParser.Postfix_nofuncContext(self, self._ctx, self.state) self.enterRule(localctx, 20, self.RULE_postfix_nofunc) try: self.enterOuterAlt(localctx, 1) self.state = 151 self.exp_nofunc(0) self.state = 155 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,9,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 152 self.postfix_op() self.state = 157 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,9,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Postfix_opContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Postfix_opContext, self).__init__(parent, invokingState) self.parser = parser def BANG(self): return self.getToken(LaTeXParser.BANG, 0) def eval_at(self): return self.getTypedRuleContext(LaTeXParser.Eval_atContext,0) def getRuleIndex(self): return LaTeXParser.RULE_postfix_op def postfix_op(self): localctx = LaTeXParser.Postfix_opContext(self, self._ctx, self.state) self.enterRule(localctx, 22, self.RULE_postfix_op) try: self.state = 160 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.BANG]: self.enterOuterAlt(localctx, 1) self.state = 158 self.match(LaTeXParser.BANG) pass elif token in [LaTeXParser.BAR]: self.enterOuterAlt(localctx, 2) self.state = 159 self.eval_at() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Eval_atContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Eval_atContext, self).__init__(parent, invokingState) self.parser = parser def BAR(self): return self.getToken(LaTeXParser.BAR, 0) def eval_at_sup(self): return self.getTypedRuleContext(LaTeXParser.Eval_at_supContext,0) def eval_at_sub(self): return self.getTypedRuleContext(LaTeXParser.Eval_at_subContext,0) def getRuleIndex(self): return LaTeXParser.RULE_eval_at def eval_at(self): localctx = LaTeXParser.Eval_atContext(self, self._ctx, self.state) self.enterRule(localctx, 24, self.RULE_eval_at) try: self.enterOuterAlt(localctx, 1) self.state = 162 self.match(LaTeXParser.BAR) self.state = 168 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,11,self._ctx) if la_ == 1: self.state = 163 self.eval_at_sup() pass elif la_ == 2: self.state = 164 self.eval_at_sub() pass elif la_ == 3: self.state = 165 self.eval_at_sup() self.state = 166 self.eval_at_sub() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Eval_at_subContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Eval_at_subContext, self).__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def equality(self): return self.getTypedRuleContext(LaTeXParser.EqualityContext,0) def getRuleIndex(self): return LaTeXParser.RULE_eval_at_sub def eval_at_sub(self): localctx = LaTeXParser.Eval_at_subContext(self, self._ctx, self.state) self.enterRule(localctx, 26, self.RULE_eval_at_sub) try: self.enterOuterAlt(localctx, 1) self.state = 170 self.match(LaTeXParser.UNDERSCORE) self.state = 171 self.match(LaTeXParser.L_BRACE) self.state = 174 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,12,self._ctx) if la_ == 1: self.state = 172 self.expr() pass elif la_ == 2: self.state = 173 self.equality() pass self.state = 176 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Eval_at_supContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Eval_at_supContext, self).__init__(parent, invokingState) self.parser = parser def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def equality(self): return self.getTypedRuleContext(LaTeXParser.EqualityContext,0) def getRuleIndex(self): return LaTeXParser.RULE_eval_at_sup def eval_at_sup(self): localctx = LaTeXParser.Eval_at_supContext(self, self._ctx, self.state) self.enterRule(localctx, 28, self.RULE_eval_at_sup) try: self.enterOuterAlt(localctx, 1) self.state = 178 self.match(LaTeXParser.CARET) self.state = 179 self.match(LaTeXParser.L_BRACE) self.state = 182 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,13,self._ctx) if la_ == 1: self.state = 180 self.expr() pass elif la_ == 2: self.state = 181 self.equality() pass self.state = 184 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExpContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.ExpContext, self).__init__(parent, invokingState) self.parser = parser def comp(self): return self.getTypedRuleContext(LaTeXParser.CompContext,0) def exp(self): return self.getTypedRuleContext(LaTeXParser.ExpContext,0) def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def subexpr(self): return self.getTypedRuleContext(LaTeXParser.SubexprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_exp def exp(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.ExpContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 30 self.enterRecursionRule(localctx, 30, self.RULE_exp, _p) try: self.enterOuterAlt(localctx, 1) self.state = 187 self.comp() self._ctx.stop = self._input.LT(-1) self.state = 203 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,16,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.ExpContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_exp) self.state = 189 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 190 self.match(LaTeXParser.CARET) self.state = 196 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.state = 191 self.atom() pass elif token in [LaTeXParser.L_BRACE]: self.state = 192 self.match(LaTeXParser.L_BRACE) self.state = 193 self.expr() self.state = 194 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) self.state = 199 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,15,self._ctx) if la_ == 1: self.state = 198 self.subexpr() self.state = 205 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,16,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class Exp_nofuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Exp_nofuncContext, self).__init__(parent, invokingState) self.parser = parser def comp_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Comp_nofuncContext,0) def exp_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Exp_nofuncContext,0) def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def subexpr(self): return self.getTypedRuleContext(LaTeXParser.SubexprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_exp_nofunc def exp_nofunc(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.Exp_nofuncContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 32 self.enterRecursionRule(localctx, 32, self.RULE_exp_nofunc, _p) try: self.enterOuterAlt(localctx, 1) self.state = 207 self.comp_nofunc() self._ctx.stop = self._input.LT(-1) self.state = 223 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,19,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.Exp_nofuncContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_exp_nofunc) self.state = 209 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 210 self.match(LaTeXParser.CARET) self.state = 216 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.state = 211 self.atom() pass elif token in [LaTeXParser.L_BRACE]: self.state = 212 self.match(LaTeXParser.L_BRACE) self.state = 213 self.expr() self.state = 214 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) self.state = 219 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,18,self._ctx) if la_ == 1: self.state = 218 self.subexpr() self.state = 225 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,19,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class CompContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.CompContext, self).__init__(parent, invokingState) self.parser = parser def group(self): return self.getTypedRuleContext(LaTeXParser.GroupContext,0) def abs_group(self): return self.getTypedRuleContext(LaTeXParser.Abs_groupContext,0) def func(self): return self.getTypedRuleContext(LaTeXParser.FuncContext,0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def frac(self): return self.getTypedRuleContext(LaTeXParser.FracContext,0) def binom(self): return self.getTypedRuleContext(LaTeXParser.BinomContext,0) def getRuleIndex(self): return LaTeXParser.RULE_comp def comp(self): localctx = LaTeXParser.CompContext(self, self._ctx, self.state) self.enterRule(localctx, 34, self.RULE_comp) try: self.state = 232 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,20,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 226 self.group() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 227 self.abs_group() pass elif la_ == 3: self.enterOuterAlt(localctx, 3) self.state = 228 self.func() pass elif la_ == 4: self.enterOuterAlt(localctx, 4) self.state = 229 self.atom() pass elif la_ == 5: self.enterOuterAlt(localctx, 5) self.state = 230 self.frac() pass elif la_ == 6: self.enterOuterAlt(localctx, 6) self.state = 231 self.binom() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Comp_nofuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Comp_nofuncContext, self).__init__(parent, invokingState) self.parser = parser def group(self): return self.getTypedRuleContext(LaTeXParser.GroupContext,0) def abs_group(self): return self.getTypedRuleContext(LaTeXParser.Abs_groupContext,0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def frac(self): return self.getTypedRuleContext(LaTeXParser.FracContext,0) def binom(self): return self.getTypedRuleContext(LaTeXParser.BinomContext,0) def getRuleIndex(self): return LaTeXParser.RULE_comp_nofunc def comp_nofunc(self): localctx = LaTeXParser.Comp_nofuncContext(self, self._ctx, self.state) self.enterRule(localctx, 36, self.RULE_comp_nofunc) try: self.state = 239 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.L_PAREN, LaTeXParser.L_BRACE, LaTeXParser.L_BRACE_LITERAL, LaTeXParser.L_BRACKET]: self.enterOuterAlt(localctx, 1) self.state = 234 self.group() pass elif token in [LaTeXParser.BAR]: self.enterOuterAlt(localctx, 2) self.state = 235 self.abs_group() pass elif token in [LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.enterOuterAlt(localctx, 3) self.state = 236 self.atom() pass elif token in [LaTeXParser.CMD_FRAC]: self.enterOuterAlt(localctx, 4) self.state = 237 self.frac() pass elif token in [LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM]: self.enterOuterAlt(localctx, 5) self.state = 238 self.binom() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class GroupContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.GroupContext, self).__init__(parent, invokingState) self.parser = parser def L_PAREN(self): return self.getToken(LaTeXParser.L_PAREN, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_PAREN(self): return self.getToken(LaTeXParser.R_PAREN, 0) def L_BRACKET(self): return self.getToken(LaTeXParser.L_BRACKET, 0) def R_BRACKET(self): return self.getToken(LaTeXParser.R_BRACKET, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def L_BRACE_LITERAL(self): return self.getToken(LaTeXParser.L_BRACE_LITERAL, 0) def R_BRACE_LITERAL(self): return self.getToken(LaTeXParser.R_BRACE_LITERAL, 0) def getRuleIndex(self): return LaTeXParser.RULE_group def group(self): localctx = LaTeXParser.GroupContext(self, self._ctx, self.state) self.enterRule(localctx, 38, self.RULE_group) try: self.state = 257 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.L_PAREN]: self.enterOuterAlt(localctx, 1) self.state = 241 self.match(LaTeXParser.L_PAREN) self.state = 242 self.expr() self.state = 243 self.match(LaTeXParser.R_PAREN) pass elif token in [LaTeXParser.L_BRACKET]: self.enterOuterAlt(localctx, 2) self.state = 245 self.match(LaTeXParser.L_BRACKET) self.state = 246 self.expr() self.state = 247 self.match(LaTeXParser.R_BRACKET) pass elif token in [LaTeXParser.L_BRACE]: self.enterOuterAlt(localctx, 3) self.state = 249 self.match(LaTeXParser.L_BRACE) self.state = 250 self.expr() self.state = 251 self.match(LaTeXParser.R_BRACE) pass elif token in [LaTeXParser.L_BRACE_LITERAL]: self.enterOuterAlt(localctx, 4) self.state = 253 self.match(LaTeXParser.L_BRACE_LITERAL) self.state = 254 self.expr() self.state = 255 self.match(LaTeXParser.R_BRACE_LITERAL) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Abs_groupContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Abs_groupContext, self).__init__(parent, invokingState) self.parser = parser def BAR(self, i=None): if i is None: return self.getTokens(LaTeXParser.BAR) else: return self.getToken(LaTeXParser.BAR, i) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_abs_group def abs_group(self): localctx = LaTeXParser.Abs_groupContext(self, self._ctx, self.state) self.enterRule(localctx, 40, self.RULE_abs_group) try: self.enterOuterAlt(localctx, 1) self.state = 259 self.match(LaTeXParser.BAR) self.state = 260 self.expr() self.state = 261 self.match(LaTeXParser.BAR) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AtomContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.AtomContext, self).__init__(parent, invokingState) self.parser = parser def LETTER(self): return self.getToken(LaTeXParser.LETTER, 0) def SYMBOL(self): return self.getToken(LaTeXParser.SYMBOL, 0) def subexpr(self): return self.getTypedRuleContext(LaTeXParser.SubexprContext,0) def NUMBER(self): return self.getToken(LaTeXParser.NUMBER, 0) def DIFFERENTIAL(self): return self.getToken(LaTeXParser.DIFFERENTIAL, 0) def mathit(self): return self.getTypedRuleContext(LaTeXParser.MathitContext,0) def getRuleIndex(self): return LaTeXParser.RULE_atom def atom(self): localctx = LaTeXParser.AtomContext(self, self._ctx, self.state) self.enterRule(localctx, 42, self.RULE_atom) self._la = 0 # Token type try: self.state = 270 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.LETTER, LaTeXParser.SYMBOL]: self.enterOuterAlt(localctx, 1) self.state = 263 _la = self._input.LA(1) if not(_la==LaTeXParser.LETTER or _la==LaTeXParser.SYMBOL): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 265 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,23,self._ctx) if la_ == 1: self.state = 264 self.subexpr() pass elif token in [LaTeXParser.NUMBER]: self.enterOuterAlt(localctx, 2) self.state = 267 self.match(LaTeXParser.NUMBER) pass elif token in [LaTeXParser.DIFFERENTIAL]: self.enterOuterAlt(localctx, 3) self.state = 268 self.match(LaTeXParser.DIFFERENTIAL) pass elif token in [LaTeXParser.CMD_MATHIT]: self.enterOuterAlt(localctx, 4) self.state = 269 self.mathit() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class MathitContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.MathitContext, self).__init__(parent, invokingState) self.parser = parser def CMD_MATHIT(self): return self.getToken(LaTeXParser.CMD_MATHIT, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def mathit_text(self): return self.getTypedRuleContext(LaTeXParser.Mathit_textContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_mathit def mathit(self): localctx = LaTeXParser.MathitContext(self, self._ctx, self.state) self.enterRule(localctx, 44, self.RULE_mathit) try: self.enterOuterAlt(localctx, 1) self.state = 272 self.match(LaTeXParser.CMD_MATHIT) self.state = 273 self.match(LaTeXParser.L_BRACE) self.state = 274 self.mathit_text() self.state = 275 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Mathit_textContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Mathit_textContext, self).__init__(parent, invokingState) self.parser = parser def LETTER(self, i=None): if i is None: return self.getTokens(LaTeXParser.LETTER) else: return self.getToken(LaTeXParser.LETTER, i) def getRuleIndex(self): return LaTeXParser.RULE_mathit_text def mathit_text(self): localctx = LaTeXParser.Mathit_textContext(self, self._ctx, self.state) self.enterRule(localctx, 46, self.RULE_mathit_text) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 280 self._errHandler.sync(self) _la = self._input.LA(1) while _la==LaTeXParser.LETTER: self.state = 277 self.match(LaTeXParser.LETTER) self.state = 282 self._errHandler.sync(self) _la = self._input.LA(1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class FracContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.FracContext, self).__init__(parent, invokingState) self.parser = parser self.upper = None # ExprContext self.lower = None # ExprContext def CMD_FRAC(self): return self.getToken(LaTeXParser.CMD_FRAC, 0) def L_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.L_BRACE) else: return self.getToken(LaTeXParser.L_BRACE, i) def R_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.R_BRACE) else: return self.getToken(LaTeXParser.R_BRACE, i) def expr(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.ExprContext) else: return self.getTypedRuleContext(LaTeXParser.ExprContext,i) def getRuleIndex(self): return LaTeXParser.RULE_frac def frac(self): localctx = LaTeXParser.FracContext(self, self._ctx, self.state) self.enterRule(localctx, 48, self.RULE_frac) try: self.enterOuterAlt(localctx, 1) self.state = 283 self.match(LaTeXParser.CMD_FRAC) self.state = 284 self.match(LaTeXParser.L_BRACE) self.state = 285 localctx.upper = self.expr() self.state = 286 self.match(LaTeXParser.R_BRACE) self.state = 287 self.match(LaTeXParser.L_BRACE) self.state = 288 localctx.lower = self.expr() self.state = 289 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class BinomContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.BinomContext, self).__init__(parent, invokingState) self.parser = parser self.n = None # ExprContext self.k = None # ExprContext def L_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.L_BRACE) else: return self.getToken(LaTeXParser.L_BRACE, i) def R_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.R_BRACE) else: return self.getToken(LaTeXParser.R_BRACE, i) def CMD_BINOM(self): return self.getToken(LaTeXParser.CMD_BINOM, 0) def CMD_DBINOM(self): return self.getToken(LaTeXParser.CMD_DBINOM, 0) def CMD_TBINOM(self): return self.getToken(LaTeXParser.CMD_TBINOM, 0) def expr(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.ExprContext) else: return self.getTypedRuleContext(LaTeXParser.ExprContext,i) def getRuleIndex(self): return LaTeXParser.RULE_binom def binom(self): localctx = LaTeXParser.BinomContext(self, self._ctx, self.state) self.enterRule(localctx, 50, self.RULE_binom) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 291 _la = self._input.LA(1) if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << LaTeXParser.CMD_BINOM) | (1 << LaTeXParser.CMD_DBINOM) | (1 << LaTeXParser.CMD_TBINOM))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 292 self.match(LaTeXParser.L_BRACE) self.state = 293 localctx.n = self.expr() self.state = 294 self.match(LaTeXParser.R_BRACE) self.state = 295 self.match(LaTeXParser.L_BRACE) self.state = 296 localctx.k = self.expr() self.state = 297 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Func_normalContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Func_normalContext, self).__init__(parent, invokingState) self.parser = parser def FUNC_EXP(self): return self.getToken(LaTeXParser.FUNC_EXP, 0) def FUNC_LOG(self): return self.getToken(LaTeXParser.FUNC_LOG, 0) def FUNC_LN(self): return self.getToken(LaTeXParser.FUNC_LN, 0) def FUNC_SIN(self): return self.getToken(LaTeXParser.FUNC_SIN, 0) def FUNC_COS(self): return self.getToken(LaTeXParser.FUNC_COS, 0) def FUNC_TAN(self): return self.getToken(LaTeXParser.FUNC_TAN, 0) def FUNC_CSC(self): return self.getToken(LaTeXParser.FUNC_CSC, 0) def FUNC_SEC(self): return self.getToken(LaTeXParser.FUNC_SEC, 0) def FUNC_COT(self): return self.getToken(LaTeXParser.FUNC_COT, 0) def FUNC_ARCSIN(self): return self.getToken(LaTeXParser.FUNC_ARCSIN, 0) def FUNC_ARCCOS(self): return self.getToken(LaTeXParser.FUNC_ARCCOS, 0) def FUNC_ARCTAN(self): return self.getToken(LaTeXParser.FUNC_ARCTAN, 0) def FUNC_ARCCSC(self): return self.getToken(LaTeXParser.FUNC_ARCCSC, 0) def FUNC_ARCSEC(self): return self.getToken(LaTeXParser.FUNC_ARCSEC, 0) def FUNC_ARCCOT(self): return self.getToken(LaTeXParser.FUNC_ARCCOT, 0) def FUNC_SINH(self): return self.getToken(LaTeXParser.FUNC_SINH, 0) def FUNC_COSH(self): return self.getToken(LaTeXParser.FUNC_COSH, 0) def FUNC_TANH(self): return self.getToken(LaTeXParser.FUNC_TANH, 0) def FUNC_ARSINH(self): return self.getToken(LaTeXParser.FUNC_ARSINH, 0) def FUNC_ARCOSH(self): return self.getToken(LaTeXParser.FUNC_ARCOSH, 0) def FUNC_ARTANH(self): return self.getToken(LaTeXParser.FUNC_ARTANH, 0) def getRuleIndex(self): return LaTeXParser.RULE_func_normal def func_normal(self): localctx = LaTeXParser.Func_normalContext(self, self._ctx, self.state) self.enterRule(localctx, 52, self.RULE_func_normal) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 299 _la = self._input.LA(1) if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << LaTeXParser.FUNC_EXP) | (1 << LaTeXParser.FUNC_LOG) | (1 << LaTeXParser.FUNC_LN) | (1 << LaTeXParser.FUNC_SIN) | (1 << LaTeXParser.FUNC_COS) | (1 << LaTeXParser.FUNC_TAN) | (1 << LaTeXParser.FUNC_CSC) | (1 << LaTeXParser.FUNC_SEC) | (1 << LaTeXParser.FUNC_COT) | (1 << LaTeXParser.FUNC_ARCSIN) | (1 << LaTeXParser.FUNC_ARCCOS) | (1 << LaTeXParser.FUNC_ARCTAN) | (1 << LaTeXParser.FUNC_ARCCSC) | (1 << LaTeXParser.FUNC_ARCSEC) | (1 << LaTeXParser.FUNC_ARCCOT) | (1 << LaTeXParser.FUNC_SINH) | (1 << LaTeXParser.FUNC_COSH) | (1 << LaTeXParser.FUNC_TANH) | (1 << LaTeXParser.FUNC_ARSINH) | (1 << LaTeXParser.FUNC_ARCOSH) | (1 << LaTeXParser.FUNC_ARTANH))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class FuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.FuncContext, self).__init__(parent, invokingState) self.parser = parser self.root = None # ExprContext self.base = None # ExprContext def func_normal(self): return self.getTypedRuleContext(LaTeXParser.Func_normalContext,0) def L_PAREN(self): return self.getToken(LaTeXParser.L_PAREN, 0) def func_arg(self): return self.getTypedRuleContext(LaTeXParser.Func_argContext,0) def R_PAREN(self): return self.getToken(LaTeXParser.R_PAREN, 0) def func_arg_noparens(self): return self.getTypedRuleContext(LaTeXParser.Func_arg_noparensContext,0) def subexpr(self): return self.getTypedRuleContext(LaTeXParser.SubexprContext,0) def supexpr(self): return self.getTypedRuleContext(LaTeXParser.SupexprContext,0) def args(self): return self.getTypedRuleContext(LaTeXParser.ArgsContext,0) def LETTER(self): return self.getToken(LaTeXParser.LETTER, 0) def SYMBOL(self): return self.getToken(LaTeXParser.SYMBOL, 0) def FUNC_INT(self): return self.getToken(LaTeXParser.FUNC_INT, 0) def DIFFERENTIAL(self): return self.getToken(LaTeXParser.DIFFERENTIAL, 0) def frac(self): return self.getTypedRuleContext(LaTeXParser.FracContext,0) def additive(self): return self.getTypedRuleContext(LaTeXParser.AdditiveContext,0) def FUNC_SQRT(self): return self.getToken(LaTeXParser.FUNC_SQRT, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def expr(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.ExprContext) else: return self.getTypedRuleContext(LaTeXParser.ExprContext,i) def L_BRACKET(self): return self.getToken(LaTeXParser.L_BRACKET, 0) def R_BRACKET(self): return self.getToken(LaTeXParser.R_BRACKET, 0) def mp(self): return self.getTypedRuleContext(LaTeXParser.MpContext,0) def FUNC_SUM(self): return self.getToken(LaTeXParser.FUNC_SUM, 0) def FUNC_PROD(self): return self.getToken(LaTeXParser.FUNC_PROD, 0) def subeq(self): return self.getTypedRuleContext(LaTeXParser.SubeqContext,0) def FUNC_LIM(self): return self.getToken(LaTeXParser.FUNC_LIM, 0) def limit_sub(self): return self.getTypedRuleContext(LaTeXParser.Limit_subContext,0) def getRuleIndex(self): return LaTeXParser.RULE_func def func(self): localctx = LaTeXParser.FuncContext(self, self._ctx, self.state) self.enterRule(localctx, 54, self.RULE_func) self._la = 0 # Token type try: self.state = 374 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH]: self.enterOuterAlt(localctx, 1) self.state = 301 self.func_normal() self.state = 314 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,30,self._ctx) if la_ == 1: self.state = 303 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.UNDERSCORE: self.state = 302 self.subexpr() self.state = 306 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.CARET: self.state = 305 self.supexpr() pass elif la_ == 2: self.state = 309 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.CARET: self.state = 308 self.supexpr() self.state = 312 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.UNDERSCORE: self.state = 311 self.subexpr() pass self.state = 321 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,31,self._ctx) if la_ == 1: self.state = 316 self.match(LaTeXParser.L_PAREN) self.state = 317 self.func_arg() self.state = 318 self.match(LaTeXParser.R_PAREN) pass elif la_ == 2: self.state = 320 self.func_arg_noparens() pass pass elif token in [LaTeXParser.LETTER, LaTeXParser.SYMBOL]: self.enterOuterAlt(localctx, 2) self.state = 323 _la = self._input.LA(1) if not(_la==LaTeXParser.LETTER or _la==LaTeXParser.SYMBOL): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 325 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.UNDERSCORE: self.state = 324 self.subexpr() self.state = 327 self.match(LaTeXParser.L_PAREN) self.state = 328 self.args() self.state = 329 self.match(LaTeXParser.R_PAREN) pass elif token in [LaTeXParser.FUNC_INT]: self.enterOuterAlt(localctx, 3) self.state = 331 self.match(LaTeXParser.FUNC_INT) self.state = 338 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.UNDERSCORE]: self.state = 332 self.subexpr() self.state = 333 self.supexpr() pass elif token in [LaTeXParser.CARET]: self.state = 335 self.supexpr() self.state = 336 self.subexpr() pass elif token in [LaTeXParser.ADD, LaTeXParser.SUB, LaTeXParser.L_PAREN, LaTeXParser.L_BRACE, LaTeXParser.L_BRACE_LITERAL, LaTeXParser.L_BRACKET, LaTeXParser.BAR, LaTeXParser.FUNC_LIM, LaTeXParser.FUNC_INT, LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD, LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH, LaTeXParser.FUNC_SQRT, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: pass else: pass self.state = 346 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,35,self._ctx) if la_ == 1: self.state = 341 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,34,self._ctx) if la_ == 1: self.state = 340 self.additive(0) self.state = 343 self.match(LaTeXParser.DIFFERENTIAL) pass elif la_ == 2: self.state = 344 self.frac() pass elif la_ == 3: self.state = 345 self.additive(0) pass pass elif token in [LaTeXParser.FUNC_SQRT]: self.enterOuterAlt(localctx, 4) self.state = 348 self.match(LaTeXParser.FUNC_SQRT) self.state = 353 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.L_BRACKET: self.state = 349 self.match(LaTeXParser.L_BRACKET) self.state = 350 localctx.root = self.expr() self.state = 351 self.match(LaTeXParser.R_BRACKET) self.state = 355 self.match(LaTeXParser.L_BRACE) self.state = 356 localctx.base = self.expr() self.state = 357 self.match(LaTeXParser.R_BRACE) pass elif token in [LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD]: self.enterOuterAlt(localctx, 5) self.state = 359 _la = self._input.LA(1) if not(_la==LaTeXParser.FUNC_SUM or _la==LaTeXParser.FUNC_PROD): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 366 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.UNDERSCORE]: self.state = 360 self.subeq() self.state = 361 self.supexpr() pass elif token in [LaTeXParser.CARET]: self.state = 363 self.supexpr() self.state = 364 self.subeq() pass else: raise NoViableAltException(self) self.state = 368 self.mp(0) pass elif token in [LaTeXParser.FUNC_LIM]: self.enterOuterAlt(localctx, 6) self.state = 370 self.match(LaTeXParser.FUNC_LIM) self.state = 371 self.limit_sub() self.state = 372 self.mp(0) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ArgsContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.ArgsContext, self).__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def args(self): return self.getTypedRuleContext(LaTeXParser.ArgsContext,0) def getRuleIndex(self): return LaTeXParser.RULE_args def args(self): localctx = LaTeXParser.ArgsContext(self, self._ctx, self.state) self.enterRule(localctx, 56, self.RULE_args) try: self.state = 381 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,39,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 376 self.expr() self.state = 377 self.match(LaTeXParser.T__0) self.state = 378 self.args() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 380 self.expr() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Limit_subContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Limit_subContext, self).__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def L_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.L_BRACE) else: return self.getToken(LaTeXParser.L_BRACE, i) def LIM_APPROACH_SYM(self): return self.getToken(LaTeXParser.LIM_APPROACH_SYM, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.R_BRACE) else: return self.getToken(LaTeXParser.R_BRACE, i) def LETTER(self): return self.getToken(LaTeXParser.LETTER, 0) def SYMBOL(self): return self.getToken(LaTeXParser.SYMBOL, 0) def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def ADD(self): return self.getToken(LaTeXParser.ADD, 0) def SUB(self): return self.getToken(LaTeXParser.SUB, 0) def getRuleIndex(self): return LaTeXParser.RULE_limit_sub def limit_sub(self): localctx = LaTeXParser.Limit_subContext(self, self._ctx, self.state) self.enterRule(localctx, 58, self.RULE_limit_sub) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 383 self.match(LaTeXParser.UNDERSCORE) self.state = 384 self.match(LaTeXParser.L_BRACE) self.state = 385 _la = self._input.LA(1) if not(_la==LaTeXParser.LETTER or _la==LaTeXParser.SYMBOL): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 386 self.match(LaTeXParser.LIM_APPROACH_SYM) self.state = 387 self.expr() self.state = 392 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.CARET: self.state = 388 self.match(LaTeXParser.CARET) self.state = 389 self.match(LaTeXParser.L_BRACE) self.state = 390 _la = self._input.LA(1) if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 391 self.match(LaTeXParser.R_BRACE) self.state = 394 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Func_argContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Func_argContext, self).__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def func_arg(self): return self.getTypedRuleContext(LaTeXParser.Func_argContext,0) def getRuleIndex(self): return LaTeXParser.RULE_func_arg def func_arg(self): localctx = LaTeXParser.Func_argContext(self, self._ctx, self.state) self.enterRule(localctx, 60, self.RULE_func_arg) try: self.state = 401 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,41,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 396 self.expr() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 397 self.expr() self.state = 398 self.match(LaTeXParser.T__0) self.state = 399 self.func_arg() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Func_arg_noparensContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Func_arg_noparensContext, self).__init__(parent, invokingState) self.parser = parser def mp_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Mp_nofuncContext,0) def getRuleIndex(self): return LaTeXParser.RULE_func_arg_noparens def func_arg_noparens(self): localctx = LaTeXParser.Func_arg_noparensContext(self, self._ctx, self.state) self.enterRule(localctx, 62, self.RULE_func_arg_noparens) try: self.enterOuterAlt(localctx, 1) self.state = 403 self.mp_nofunc(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SubexprContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.SubexprContext, self).__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_subexpr def subexpr(self): localctx = LaTeXParser.SubexprContext(self, self._ctx, self.state) self.enterRule(localctx, 64, self.RULE_subexpr) try: self.enterOuterAlt(localctx, 1) self.state = 405 self.match(LaTeXParser.UNDERSCORE) self.state = 411 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.state = 406 self.atom() pass elif token in [LaTeXParser.L_BRACE]: self.state = 407 self.match(LaTeXParser.L_BRACE) self.state = 408 self.expr() self.state = 409 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SupexprContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.SupexprContext, self).__init__(parent, invokingState) self.parser = parser def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_supexpr def supexpr(self): localctx = LaTeXParser.SupexprContext(self, self._ctx, self.state) self.enterRule(localctx, 66, self.RULE_supexpr) try: self.enterOuterAlt(localctx, 1) self.state = 413 self.match(LaTeXParser.CARET) self.state = 419 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.state = 414 self.atom() pass elif token in [LaTeXParser.L_BRACE]: self.state = 415 self.match(LaTeXParser.L_BRACE) self.state = 416 self.expr() self.state = 417 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SubeqContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.SubeqContext, self).__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def equality(self): return self.getTypedRuleContext(LaTeXParser.EqualityContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_subeq def subeq(self): localctx = LaTeXParser.SubeqContext(self, self._ctx, self.state) self.enterRule(localctx, 68, self.RULE_subeq) try: self.enterOuterAlt(localctx, 1) self.state = 421 self.match(LaTeXParser.UNDERSCORE) self.state = 422 self.match(LaTeXParser.L_BRACE) self.state = 423 self.equality() self.state = 424 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SupeqContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.SupeqContext, self).__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def equality(self): return self.getTypedRuleContext(LaTeXParser.EqualityContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_supeq def supeq(self): localctx = LaTeXParser.SupeqContext(self, self._ctx, self.state) self.enterRule(localctx, 70, self.RULE_supeq) try: self.enterOuterAlt(localctx, 1) self.state = 426 self.match(LaTeXParser.UNDERSCORE) self.state = 427 self.match(LaTeXParser.L_BRACE) self.state = 428 self.equality() self.state = 429 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx def sempred(self, localctx, ruleIndex, predIndex): if self._predicates == None: self._predicates = dict() self._predicates[1] = self.relation_sempred self._predicates[4] = self.additive_sempred self._predicates[5] = self.mp_sempred self._predicates[6] = self.mp_nofunc_sempred self._predicates[15] = self.exp_sempred self._predicates[16] = self.exp_nofunc_sempred pred = self._predicates.get(ruleIndex, None) if pred is None: raise Exception("No predicate with index:" + str(ruleIndex)) else: return pred(localctx, predIndex) def relation_sempred(self, localctx, predIndex): if predIndex == 0: return self.precpred(self._ctx, 2) def additive_sempred(self, localctx, predIndex): if predIndex == 1: return self.precpred(self._ctx, 2) def mp_sempred(self, localctx, predIndex): if predIndex == 2: return self.precpred(self._ctx, 2) def mp_nofunc_sempred(self, localctx, predIndex): if predIndex == 3: return self.precpred(self._ctx, 2) def exp_sempred(self, localctx, predIndex): if predIndex == 4: return self.precpred(self._ctx, 2) def exp_nofunc_sempred(self, localctx, predIndex): if predIndex == 5: return self.precpred(self._ctx, 2)
3c323fbff1fbbd7a87ad64d148b5814fb5954dd7fef1b7292cc5062e7ad20fe2
from sympy import Basic, Mul, Pow, degree, Symbol, expand, cancel, Expr, exp, roots from sympy.core.evalf import EvalfMixin from sympy.core.logic import fuzzy_and from sympy.core.numbers import Integer from sympy.core.sympify import sympify, _sympify from sympy.polys import Poly, rootof from sympy.series import limit __all__ = ['TransferFunction', 'Series', 'Parallel', 'Feedback'] 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 TransferFunction(Basic, EvalfMixin): """ 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. 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. Also, when ``num`` or ``den`` has a time delay term. 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), Series(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 """ 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) and not num.has(exp)) or num.is_number) and ((isinstance(den, Expr) and den.has(Symbol) and not den.has(exp)) 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.") @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.core.symbol import symbols >>> q, r = symbols('q, r', negative=True) >>> from sympy.physics.control.lti import TransferFunction >>> 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) class Series(Basic): """ A class for representing product of transfer functions or transfer functions in a series configuration. 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 ======== Parallel, TransferFunction, Feedback """ def __new__(cls, *args, evaluate=False): if not all(isinstance(arg, (TransferFunction, Parallel, Series)) for arg in args): raise TypeError("Unsupported type of argument(s) for Series.") obj = super(Series, cls).__new__(cls, *args) obj._var = None for arg in args: if obj._var is None: obj._var = arg.var elif obj._var != arg.var: raise ValueError("All transfer functions should use the same complex" " variable of the Laplace transform.") if evaluate: return obj.doit() return 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._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) """ res = None for arg in self.args: arg = arg.doit() if res is None: res = arg else: num_ = arg.num * res.num den_ = arg.den * res.den res = TransferFunction(num_, den_, self.var) return res def _eval_rewrite_as_TransferFunction(self, *args, **kwargs): return self.doit() 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("This transfer function expression is invalid.") __radd__ = __add__ 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("This transfer function expression is invalid.") 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.") arg_list = list(self.args) return Series(*arg_list, 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.") self_arg_list = list(self.args) other_arg_list = list(other.args) return Series(*self_arg_list, *other_arg_list) else: raise ValueError("This transfer function expression is invalid.") 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) @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 class Parallel(Basic): """ A class for representing addition of transfer functions or transfer functions in a parallel configuration. 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) + (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): if not all(isinstance(arg, (TransferFunction, Series, Parallel)) for arg in args): raise TypeError("Unsupported type of argument(s) for Parallel.") obj = super(Parallel, cls).__new__(cls, *args) obj._var = None for arg in args: if obj._var is None: obj._var = arg.var elif obj._var != arg.var: raise ValueError("All transfer functions should use the same complex" " variable of the Laplace transform.") if evaluate: return obj.doit() return 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._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) """ res = None for arg in self.args: arg = arg.doit() if res is None: res = arg else: num_ = res.num * arg.den + res.den * arg.num den_ = res.den * arg.den res = TransferFunction(num_, den_, self.var) return res def _eval_rewrite_as_TransferFunction(self, *args, **kwargs): return self.doit() 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.") arg_list = list(self.args) arg_list.append(other) return Parallel(*arg_list) 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.") self_arg_list = list(self.args) other_arg_list = list(other.args) for elem in other_arg_list: self_arg_list.append(elem) return Parallel(*self_arg_list) else: raise ValueError("This transfer function expression is invalid.") 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.") arg_list = list(self.args) arg_list.append(-other) return Parallel(*arg_list) 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.") self_arg_list = list(self.args) other_arg_list = list(other.args) for elem in other_arg_list: self_arg_list.append(-elem) return Parallel(*self_arg_list) else: raise ValueError("This transfer function expression is invalid.") 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("This transfer function expression is invalid.") def __neg__(self): return Series(TransferFunction(-1, 1, self.var), self) @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 Feedback(Basic): """ A class for representing negative feedback interconnection between two input/output systems. The first argument, ``num``, is called as the primary plant or the numerator, and the second argument, ``den``, is called as the feedback plant (which is often a feedback controller) or the denominator. Both ``num`` and ``den`` can either be ``Series`` or ``TransferFunction`` objects. Parameters ========== num : Series, TransferFunction The primary plant. den : Series, TransferFunction The feedback plant (often a feedback controller). Raises ====== ValueError When ``num`` is equal to ``den`` or when they are not using the same complex variable of the Laplace transform. TypeError When either ``num`` or ``den`` 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)) >>> 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)) You can get the primary and the feedback plant using ``.num`` and ``.den`` respectively. >>> F1.num TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s) >>> F1.den 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(5*s - 10, s + 7, s)) >>> -F2 Feedback(Series(TransferFunction(-1, 1, s), Series(TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s), TransferFunction(5*s + 10, s + 10, s))), TransferFunction(1, 1, s)) See Also ======== TransferFunction, Series, Parallel """ def __new__(cls, num, den): if not (isinstance(num, (TransferFunction, Series)) and isinstance(den, (TransferFunction, Series))): raise TypeError("Unsupported type for numerator or denominator of Feedback.") if num == den: raise ValueError("The numerator cannot be equal to the denominator.") if not num.var == den.var: raise ValueError("Both numerator and denominator should be using the" " same complex variable.") obj = super(Feedback, cls).__new__(cls, num, den) obj._num = num obj._den = den obj._var = num.var return obj @property def num(self): """ Returns the primary plant of the negative feedback closed loop. 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.num 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.num TransferFunction(1, 1, p) """ return self._num @property def den(self): """ Returns the feedback plant (often a feedback controller) of the negative feedback closed loop. 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.den 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.den 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._den @property def var(self): """ Returns the complex variable of the Laplace transform used by all the transfer functions involved in the negative feedback closed loop. 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._var def doit(self, **kwargs): """ Returns the resultant closed loop transfer function obtained by the negative 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) """ arg_list = list(self.num.args) if isinstance(self.num, Series) else [self.num] # F_n and F_d are resultant TFs of num and den of Feedback. F_n, tf = self.num.doit(), TransferFunction(1, 1, self.num.var) F_d = Parallel(tf, Series(self.den, *arg_list)).doit() return TransferFunction(F_n.num*F_d.den, F_n.den*F_d.num, F_n.var) def _eval_rewrite_as_TransferFunction(self, num, den, **kwargs): return self.doit() def __neg__(self): return Feedback(-self.num, self.den)
29e1339bc0f5308b5f9af37ce72d7c7dd5708db1893b861ef9d2e78763df26e4
"""An implementation of qubits and gates acting on them. Todo: * Update docstrings. * Update tests. * Implement apply using decompose. * Implement represent using decompose or something smarter. For this to work we first have to implement represent for SWAP. * Decide if we want upper index to be inclusive in the constructor. * Fix the printing of Rk gates in plotting. """ from __future__ import print_function, division from sympy import Expr, Matrix, exp, I, pi, Integer, Symbol from sympy.functions import sqrt from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.qexpr import QuantumError, QExpr from sympy.matrices import eye from sympy.physics.quantum.tensorproduct import matrix_tensor_product from sympy.physics.quantum.gate import ( Gate, HadamardGate, SwapGate, OneQubitGate, CGate, PhaseGate, TGate, ZGate ) __all__ = [ 'QFT', 'IQFT', 'RkGate', 'Rk' ] #----------------------------------------------------------------------------- # Fourier stuff #----------------------------------------------------------------------------- class RkGate(OneQubitGate): """This is the R_k gate of the QTF.""" gate_name = 'Rk' gate_name_latex = 'R' def __new__(cls, *args): if len(args) != 2: raise QuantumError( 'Rk gates only take two arguments, got: %r' % args ) # For small k, Rk gates simplify to other gates, using these # substitutions give us familiar results for the QFT for small numbers # of qubits. target = args[0] k = args[1] if k == 1: return ZGate(target) elif k == 2: return PhaseGate(target) elif k == 3: return TGate(target) args = cls._eval_args(args) inst = Expr.__new__(cls, *args) inst.hilbert_space = cls._eval_hilbert_space(args) return inst @classmethod def _eval_args(cls, args): # Fall back to this, because Gate._eval_args assumes that args is # all targets and can't contain duplicates. return QExpr._eval_args(args) @property def k(self): return self.label[1] @property def targets(self): return self.label[:1] @property def gate_name_plot(self): return r'$%s_%s$' % (self.gate_name_latex, str(self.k)) def get_target_matrix(self, format='sympy'): if format == 'sympy': return Matrix([[1, 0], [0, exp(Integer(2)*pi*I/(Integer(2)**self.k))]]) raise NotImplementedError( 'Invalid format for the R_k gate: %r' % format) Rk = RkGate class Fourier(Gate): """Superclass of Quantum Fourier and Inverse Quantum Fourier Gates.""" @classmethod def _eval_args(self, args): if len(args) != 2: raise QuantumError( 'QFT/IQFT only takes two arguments, got: %r' % args ) if args[0] >= args[1]: raise QuantumError("Start must be smaller than finish") return Gate._eval_args(args) def _represent_default_basis(self, **options): return self._represent_ZGate(None, **options) def _represent_ZGate(self, basis, **options): """ Represents the (I)QFT In the Z Basis """ nqubits = options.get('nqubits', 0) if nqubits == 0: raise QuantumError( 'The number of qubits must be given as nqubits.') if nqubits < self.min_qubits: raise QuantumError( 'The number of qubits %r is too small for the gate.' % nqubits ) size = self.size omega = self.omega #Make a matrix that has the basic Fourier Transform Matrix arrayFT = [[omega**( i*j % size)/sqrt(size) for i in range(size)] for j in range(size)] matrixFT = Matrix(arrayFT) #Embed the FT Matrix in a higher space, if necessary if self.label[0] != 0: matrixFT = matrix_tensor_product(eye(2**self.label[0]), matrixFT) if self.min_qubits < nqubits: matrixFT = matrix_tensor_product( matrixFT, eye(2**(nqubits - self.min_qubits))) return matrixFT @property def targets(self): return range(self.label[0], self.label[1]) @property def min_qubits(self): return self.label[1] @property def size(self): """Size is the size of the QFT matrix""" return 2**(self.label[1] - self.label[0]) @property def omega(self): return Symbol('omega') class QFT(Fourier): """The forward quantum Fourier transform.""" gate_name = 'QFT' gate_name_latex = 'QFT' def decompose(self): """Decomposes QFT into elementary gates.""" start = self.label[0] finish = self.label[1] circuit = 1 for level in reversed(range(start, finish)): circuit = HadamardGate(level)*circuit for i in range(level - start): circuit = CGate(level - i - 1, RkGate(level, i + 2))*circuit for i in range((finish - start)//2): circuit = SwapGate(i + start, finish - i - 1)*circuit return circuit def _apply_operator_Qubit(self, qubits, **options): return qapply(self.decompose()*qubits) def _eval_inverse(self): return IQFT(*self.args) @property def omega(self): return exp(2*pi*I/self.size) class IQFT(Fourier): """The inverse quantum Fourier transform.""" gate_name = 'IQFT' gate_name_latex = '{QFT^{-1}}' def decompose(self): """Decomposes IQFT into elementary gates.""" start = self.args[0] finish = self.args[1] circuit = 1 for i in range((finish - start)//2): circuit = SwapGate(i + start, finish - i - 1)*circuit for level in range(start, finish): for i in reversed(range(level - start)): circuit = CGate(level - i - 1, RkGate(level, -i - 2))*circuit circuit = HadamardGate(level)*circuit return circuit def _eval_inverse(self): return QFT(*self.args) @property def omega(self): return exp(-2*pi*I/self.size)
6094ce714b0d0ef42f2a717d11c1a2ee680171afff9614fd04be2fe5777039f6
"""Abstract tensor product.""" from __future__ import print_function, division from sympy import Expr, Add, Mul, Matrix, Pow, sympify from sympy.core.trace import Tr from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.state import Ket, Bra from sympy.physics.quantum.matrixutils import ( numpy_ndarray, scipy_sparse_matrix, matrix_tensor_product ) __all__ = [ 'TensorProduct', 'tensor_product_simp' ] #----------------------------------------------------------------------------- # Tensor product #----------------------------------------------------------------------------- _combined_printing = False def combined_tensor_printing(combined): """Set flag controlling whether tensor products of states should be printed as a combined bra/ket or as an explicit tensor product of different bra/kets. This is a global setting for all TensorProduct class instances. Parameters ---------- combine : bool When true, tensor product states are combined into one ket/bra, and when false explicit tensor product notation is used between each ket/bra. """ global _combined_printing _combined_printing = combined class TensorProduct(Expr): """The tensor product of two or more arguments. For matrices, this uses ``matrix_tensor_product`` to compute the Kronecker or tensor product matrix. For other objects a symbolic ``TensorProduct`` instance is returned. The tensor product is a non-commutative multiplication that is used primarily with operators and states in quantum mechanics. Currently, the tensor product distinguishes between commutative and non-commutative arguments. Commutative arguments are assumed to be scalars and are pulled out in front of the ``TensorProduct``. Non-commutative arguments remain in the resulting ``TensorProduct``. Parameters ========== args : tuple A sequence of the objects to take the tensor product of. Examples ======== Start with a simple tensor product of sympy matrices:: >>> from sympy import Matrix >>> from sympy.physics.quantum import TensorProduct >>> m1 = Matrix([[1,2],[3,4]]) >>> m2 = Matrix([[1,0],[0,1]]) >>> TensorProduct(m1, m2) Matrix([ [1, 0, 2, 0], [0, 1, 0, 2], [3, 0, 4, 0], [0, 3, 0, 4]]) >>> TensorProduct(m2, m1) Matrix([ [1, 2, 0, 0], [3, 4, 0, 0], [0, 0, 1, 2], [0, 0, 3, 4]]) We can also construct tensor products of non-commutative symbols: >>> from sympy import Symbol >>> A = Symbol('A',commutative=False) >>> B = Symbol('B',commutative=False) >>> tp = TensorProduct(A, B) >>> tp AxB We can take the dagger of a tensor product (note the order does NOT reverse like the dagger of a normal product): >>> from sympy.physics.quantum import Dagger >>> Dagger(tp) Dagger(A)xDagger(B) Expand can be used to distribute a tensor product across addition: >>> C = Symbol('C',commutative=False) >>> tp = TensorProduct(A+B,C) >>> tp (A + B)xC >>> tp.expand(tensorproduct=True) AxC + BxC """ is_commutative = False def __new__(cls, *args): if isinstance(args[0], (Matrix, numpy_ndarray, scipy_sparse_matrix)): return matrix_tensor_product(*args) c_part, new_args = cls.flatten(sympify(args)) c_part = Mul(*c_part) if len(new_args) == 0: return c_part elif len(new_args) == 1: return c_part * new_args[0] else: tp = Expr.__new__(cls, *new_args) return c_part * tp @classmethod def flatten(cls, args): # TODO: disallow nested TensorProducts. c_part = [] nc_parts = [] for arg in args: cp, ncp = arg.args_cnc() c_part.extend(list(cp)) nc_parts.append(Mul._from_args(ncp)) return c_part, nc_parts def _eval_adjoint(self): return TensorProduct(*[Dagger(i) for i in self.args]) def _eval_rewrite(self, pattern, rule, **hints): sargs = self.args terms = [t._eval_rewrite(pattern, rule, **hints) for t in sargs] return TensorProduct(*terms).expand(tensorproduct=True) def _sympystr(self, printer, *args): length = len(self.args) s = '' for i in range(length): if isinstance(self.args[i], (Add, Pow, Mul)): s = s + '(' s = s + printer._print(self.args[i]) if isinstance(self.args[i], (Add, Pow, Mul)): s = s + ')' if i != length - 1: s = s + 'x' return s def _pretty(self, printer, *args): if (_combined_printing and (all([isinstance(arg, Ket) for arg in self.args]) or all([isinstance(arg, Bra) for arg in self.args]))): length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print('', *args) length_i = len(self.args[i].args) for j in range(length_i): part_pform = printer._print(self.args[i].args[j], *args) next_pform = prettyForm(*next_pform.right(part_pform)) if j != length_i - 1: next_pform = prettyForm(*next_pform.right(', ')) if len(self.args[i].args) > 1: next_pform = prettyForm( *next_pform.parens(left='{', right='}')) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: pform = prettyForm(*pform.right(',' + ' ')) pform = prettyForm(*pform.left(self.args[0].lbracket)) pform = prettyForm(*pform.right(self.args[0].rbracket)) return pform length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print(self.args[i], *args) if isinstance(self.args[i], (Add, Mul)): next_pform = prettyForm( *next_pform.parens(left='(', right=')') ) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: if printer._use_unicode: pform = prettyForm(*pform.right('\N{N-ARY CIRCLED TIMES OPERATOR}' + ' ')) else: pform = prettyForm(*pform.right('x' + ' ')) return pform def _latex(self, printer, *args): if (_combined_printing and (all([isinstance(arg, Ket) for arg in self.args]) or all([isinstance(arg, Bra) for arg in self.args]))): def _label_wrap(label, nlabels): return label if nlabels == 1 else r"\left\{%s\right\}" % label s = r", ".join([_label_wrap(arg._print_label_latex(printer, *args), len(arg.args)) for arg in self.args]) return r"{%s%s%s}" % (self.args[0].lbracket_latex, s, self.args[0].rbracket_latex) length = len(self.args) s = '' for i in range(length): if isinstance(self.args[i], (Add, Mul)): s = s + '\\left(' # The extra {} brackets are needed to get matplotlib's latex # rendered to render this properly. s = s + '{' + printer._print(self.args[i], *args) + '}' if isinstance(self.args[i], (Add, Mul)): s = s + '\\right)' if i != length - 1: s = s + '\\otimes ' return s def doit(self, **hints): return TensorProduct(*[item.doit(**hints) for item in self.args]) def _eval_expand_tensorproduct(self, **hints): """Distribute TensorProducts across addition.""" args = self.args add_args = [] for i in range(len(args)): if isinstance(args[i], Add): for aa in args[i].args: tp = TensorProduct(*args[:i] + (aa,) + args[i + 1:]) if isinstance(tp, TensorProduct): tp = tp._eval_expand_tensorproduct() add_args.append(tp) break if add_args: return Add(*add_args) else: return self def _eval_trace(self, **kwargs): indices = kwargs.get('indices', None) exp = tensor_product_simp(self) if indices is None or len(indices) == 0: return Mul(*[Tr(arg).doit() for arg in exp.args]) else: return Mul(*[Tr(value).doit() if idx in indices else value for idx, value in enumerate(exp.args)]) def tensor_product_simp_Mul(e): """Simplify a Mul with TensorProducts. Current the main use of this is to simplify a ``Mul`` of ``TensorProduct``s to a ``TensorProduct`` of ``Muls``. It currently only works for relatively simple cases where the initial ``Mul`` only has scalars and raw ``TensorProduct``s, not ``Add``, ``Pow``, ``Commutator``s of ``TensorProduct``s. Parameters ========== e : Expr A ``Mul`` of ``TensorProduct``s to be simplified. Returns ======= e : Expr A ``TensorProduct`` of ``Mul``s. Examples ======== This is an example of the type of simplification that this function performs:: >>> from sympy.physics.quantum.tensorproduct import \ tensor_product_simp_Mul, TensorProduct >>> from sympy import Symbol >>> A = Symbol('A',commutative=False) >>> B = Symbol('B',commutative=False) >>> C = Symbol('C',commutative=False) >>> D = Symbol('D',commutative=False) >>> e = TensorProduct(A,B)*TensorProduct(C,D) >>> e AxB*CxD >>> tensor_product_simp_Mul(e) (A*C)x(B*D) """ # TODO: This won't work with Muls that have other composites of # TensorProducts, like an Add, Commutator, etc. # TODO: This only works for the equivalent of single Qbit gates. if not isinstance(e, Mul): return e c_part, nc_part = e.args_cnc() n_nc = len(nc_part) if n_nc == 0: return e elif n_nc == 1: if isinstance(nc_part[0], Pow): return Mul(*c_part) * tensor_product_simp_Pow(nc_part[0]) return e elif e.has(TensorProduct): current = nc_part[0] if not isinstance(current, TensorProduct): if isinstance(current, Pow): if isinstance(current.base, TensorProduct): current = tensor_product_simp_Pow(current) else: raise TypeError('TensorProduct expected, got: %r' % current) n_terms = len(current.args) new_args = list(current.args) for next in nc_part[1:]: # TODO: check the hilbert spaces of next and current here. if isinstance(next, TensorProduct): if n_terms != len(next.args): raise QuantumError( 'TensorProducts of different lengths: %r and %r' % (current, next) ) for i in range(len(new_args)): new_args[i] = new_args[i] * next.args[i] else: if isinstance(next, Pow): if isinstance(next.base, TensorProduct): new_tp = tensor_product_simp_Pow(next) for i in range(len(new_args)): new_args[i] = new_args[i] * new_tp.args[i] else: raise TypeError('TensorProduct expected, got: %r' % next) else: raise TypeError('TensorProduct expected, got: %r' % next) current = next return Mul(*c_part) * TensorProduct(*new_args) elif e.has(Pow): new_args = [ tensor_product_simp_Pow(nc) for nc in nc_part ] return tensor_product_simp_Mul(Mul(*c_part) * TensorProduct(*new_args)) else: return e def tensor_product_simp_Pow(e): """Evaluates ``Pow`` expressions whose base is ``TensorProduct``""" if not isinstance(e, Pow): return e if isinstance(e.base, TensorProduct): return TensorProduct(*[ b**e.exp for b in e.base.args]) else: return e def tensor_product_simp(e, **hints): """Try to simplify and combine TensorProducts. In general this will try to pull expressions inside of ``TensorProducts``. It currently only works for relatively simple cases where the products have only scalars, raw ``TensorProducts``, not ``Add``, ``Pow``, ``Commutators`` of ``TensorProducts``. It is best to see what it does by showing examples. Examples ======== >>> from sympy.physics.quantum import tensor_product_simp >>> from sympy.physics.quantum import TensorProduct >>> from sympy import Symbol >>> A = Symbol('A',commutative=False) >>> B = Symbol('B',commutative=False) >>> C = Symbol('C',commutative=False) >>> D = Symbol('D',commutative=False) First see what happens to products of tensor products: >>> e = TensorProduct(A,B)*TensorProduct(C,D) >>> e AxB*CxD >>> tensor_product_simp(e) (A*C)x(B*D) This is the core logic of this function, and it works inside, powers, sums, commutators and anticommutators as well: >>> tensor_product_simp(e**2) (A*C)x(B*D)**2 """ if isinstance(e, Add): return Add(*[tensor_product_simp(arg) for arg in e.args]) elif isinstance(e, Pow): if isinstance(e.base, TensorProduct): return tensor_product_simp_Pow(e) else: return tensor_product_simp(e.base) ** e.exp elif isinstance(e, Mul): return tensor_product_simp_Mul(e) elif isinstance(e, Commutator): return Commutator(*[tensor_product_simp(arg) for arg in e.args]) elif isinstance(e, AntiCommutator): return AntiCommutator(*[tensor_product_simp(arg) for arg in e.args]) else: return e
1c87c51a64a7dc3210fc05e215e9ad1b2df3e3d260605a9c5fbff1ee723cc2da
"""The anti-commutator: ``{A,B} = A*B + B*A``.""" from __future__ import print_function, division from sympy import S, Expr, Mul, Integer from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.operator import Operator from sympy.physics.quantum.dagger import Dagger __all__ = [ 'AntiCommutator' ] #----------------------------------------------------------------------------- # Anti-commutator #----------------------------------------------------------------------------- class AntiCommutator(Expr): """The standard anticommutator, in an unevaluated state. Evaluating an anticommutator is defined [1]_ as: ``{A, B} = A*B + B*A``. This class returns the anticommutator in an unevaluated form. To evaluate the anticommutator, use the ``.doit()`` method. Canonical ordering of an anticommutator is ``{A, B}`` for ``A < B``. The arguments of the anticommutator are put into canonical order using ``__cmp__``. If ``B < A``, then ``{A, B}`` is returned as ``{B, A}``. Parameters ========== A : Expr The first argument of the anticommutator {A,B}. B : Expr The second argument of the anticommutator {A,B}. Examples ======== >>> from sympy import symbols >>> from sympy.physics.quantum import AntiCommutator >>> from sympy.physics.quantum import Operator, Dagger >>> x, y = symbols('x,y') >>> A = Operator('A') >>> B = Operator('B') Create an anticommutator and use ``doit()`` to multiply them out. >>> ac = AntiCommutator(A,B); ac {A,B} >>> ac.doit() A*B + B*A The commutator orders it arguments in canonical order: >>> ac = AntiCommutator(B,A); ac {A,B} Commutative constants are factored out: >>> AntiCommutator(3*x*A,x*y*B) 3*x**2*y*{A,B} Adjoint operations applied to the anticommutator are properly applied to the arguments: >>> Dagger(AntiCommutator(A,B)) {Dagger(A),Dagger(B)} References ========== .. [1] https://en.wikipedia.org/wiki/Commutator """ is_commutative = False def __new__(cls, A, B): r = cls.eval(A, B) if r is not None: return r obj = Expr.__new__(cls, A, B) return obj @classmethod def eval(cls, a, b): if not (a and b): return S.Zero if a == b: return Integer(2)*a**2 if a.is_commutative or b.is_commutative: return Integer(2)*a*b # [xA,yB] -> xy*[A,B] ca, nca = a.args_cnc() cb, ncb = b.args_cnc() c_part = ca + cb if c_part: return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb))) # Canonical ordering of arguments #The Commutator [A,B] is on canonical form if A < B. if a.compare(b) == 1: return cls(b, a) def doit(self, **hints): """ Evaluate anticommutator """ A = self.args[0] B = self.args[1] if isinstance(A, Operator) and isinstance(B, Operator): try: comm = A._eval_anticommutator(B, **hints) except NotImplementedError: try: comm = B._eval_anticommutator(A, **hints) except NotImplementedError: comm = None if comm is not None: return comm.doit(**hints) return (A*B + B*A).doit(**hints) def _eval_adjoint(self): return AntiCommutator(Dagger(self.args[0]), Dagger(self.args[1])) def _sympyrepr(self, printer, *args): return "%s(%s,%s)" % ( self.__class__.__name__, printer._print( self.args[0]), printer._print(self.args[1]) ) def _sympystr(self, printer, *args): return "{%s,%s}" % ( printer._print(self.args[0]), printer._print(self.args[1])) def _pretty(self, printer, *args): pform = printer._print(self.args[0], *args) pform = prettyForm(*pform.right((prettyForm(',')))) pform = prettyForm(*pform.right((printer._print(self.args[1], *args)))) pform = prettyForm(*pform.parens(left='{', right='}')) return pform def _latex(self, printer, *args): return "\\left\\{%s,%s\\right\\}" % tuple([ printer._print(arg, *args) for arg in self.args])
82e2c3e12c0c0ea4d79c45a2e92c21ad1c10e8476435b7add5ac7297f29811bc
"""Dirac notation for states.""" from __future__ import print_function, division from sympy import (cacheit, conjugate, Expr, Function, integrate, oo, sqrt, Tuple) from sympy.printing.pretty.stringpict import stringPict from sympy.physics.quantum.qexpr import QExpr, dispatch_method __all__ = [ 'KetBase', 'BraBase', 'StateBase', 'State', 'Ket', 'Bra', 'TimeDepState', 'TimeDepBra', 'TimeDepKet', 'OrthogonalKet', 'OrthogonalBra', 'OrthogonalState', 'Wavefunction' ] #----------------------------------------------------------------------------- # States, bras and kets. #----------------------------------------------------------------------------- # ASCII brackets _lbracket = "<" _rbracket = ">" _straight_bracket = "|" # Unicode brackets # MATHEMATICAL ANGLE BRACKETS _lbracket_ucode = "\N{MATHEMATICAL LEFT ANGLE BRACKET}" _rbracket_ucode = "\N{MATHEMATICAL RIGHT ANGLE BRACKET}" # LIGHT VERTICAL BAR _straight_bracket_ucode = "\N{LIGHT VERTICAL BAR}" # Other options for unicode printing of <, > and | for Dirac notation. # LEFT-POINTING ANGLE BRACKET # _lbracket = "\u2329" # _rbracket = "\u232A" # LEFT ANGLE BRACKET # _lbracket = "\u3008" # _rbracket = "\u3009" # VERTICAL LINE # _straight_bracket = "\u007C" class StateBase(QExpr): """Abstract base class for general abstract states in quantum mechanics. All other state classes defined will need to inherit from this class. It carries the basic structure for all other states such as dual, _eval_adjoint and label. This is an abstract base class and you should not instantiate it directly, instead use State. """ @classmethod def _operators_to_state(self, ops, **options): """ Returns the eigenstate instance for the passed operators. This method should be overridden in subclasses. It will handle being passed either an Operator instance or set of Operator instances. It should return the corresponding state INSTANCE or simply raise a NotImplementedError. See cartesian.py for an example. """ raise NotImplementedError("Cannot map operators to states in this class. Method not implemented!") def _state_to_operators(self, op_classes, **options): """ Returns the operators which this state instance is an eigenstate of. This method should be overridden in subclasses. It will be called on state instances and be passed the operator classes that we wish to make into instances. The state instance will then transform the classes appropriately, or raise a NotImplementedError if it cannot return operator instances. See cartesian.py for examples, """ raise NotImplementedError( "Cannot map this state to operators. Method not implemented!") @property def operators(self): """Return the operator(s) that this state is an eigenstate of""" from .operatorset import state_to_operators # import internally to avoid circular import errors return state_to_operators(self) def _enumerate_state(self, num_states, **options): raise NotImplementedError("Cannot enumerate this state!") def _represent_default_basis(self, **options): return self._represent(basis=self.operators) #------------------------------------------------------------------------- # Dagger/dual #------------------------------------------------------------------------- @property def dual(self): """Return the dual state of this one.""" return self.dual_class()._new_rawargs(self.hilbert_space, *self.args) @classmethod def dual_class(self): """Return the class used to construct the dual.""" raise NotImplementedError( 'dual_class must be implemented in a subclass' ) def _eval_adjoint(self): """Compute the dagger of this state using the dual.""" return self.dual #------------------------------------------------------------------------- # Printing #------------------------------------------------------------------------- def _pretty_brackets(self, height, use_unicode=True): # Return pretty printed brackets for the state # Ideally, this could be done by pform.parens but it does not support the angled < and > # Setup for unicode vs ascii if use_unicode: lbracket, rbracket = self.lbracket_ucode, self.rbracket_ucode slash, bslash, vert = '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT}', \ '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT}', \ '\N{BOX DRAWINGS LIGHT VERTICAL}' else: lbracket, rbracket = self.lbracket, self.rbracket slash, bslash, vert = '/', '\\', '|' # If height is 1, just return brackets if height == 1: return stringPict(lbracket), stringPict(rbracket) # Make height even height += (height % 2) brackets = [] for bracket in lbracket, rbracket: # Create left bracket if bracket in {_lbracket, _lbracket_ucode}: bracket_args = [ ' ' * (height//2 - i - 1) + slash for i in range(height // 2)] bracket_args.extend( [ ' ' * i + bslash for i in range(height // 2)]) # Create right bracket elif bracket in {_rbracket, _rbracket_ucode}: bracket_args = [ ' ' * i + bslash for i in range(height // 2)] bracket_args.extend([ ' ' * ( height//2 - i - 1) + slash for i in range(height // 2)]) # Create straight bracket elif bracket in {_straight_bracket, _straight_bracket_ucode}: bracket_args = [vert for i in range(height)] else: raise ValueError(bracket) brackets.append( stringPict('\n'.join(bracket_args), baseline=height//2)) return brackets def _sympystr(self, printer, *args): contents = self._print_contents(printer, *args) return '%s%s%s' % (self.lbracket, contents, self.rbracket) def _pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm # Get brackets pform = self._print_contents_pretty(printer, *args) lbracket, rbracket = self._pretty_brackets( pform.height(), printer._use_unicode) # Put together state pform = prettyForm(*pform.left(lbracket)) pform = prettyForm(*pform.right(rbracket)) return pform def _latex(self, printer, *args): contents = self._print_contents_latex(printer, *args) # The extra {} brackets are needed to get matplotlib's latex # rendered to render this properly. return '{%s%s%s}' % (self.lbracket_latex, contents, self.rbracket_latex) class KetBase(StateBase): """Base class for Kets. This class defines the dual property and the brackets for printing. This is an abstract base class and you should not instantiate it directly, instead use Ket. """ lbracket = _straight_bracket rbracket = _rbracket lbracket_ucode = _straight_bracket_ucode rbracket_ucode = _rbracket_ucode lbracket_latex = r'\left|' rbracket_latex = r'\right\rangle ' @classmethod def default_args(self): return ("psi",) @classmethod def dual_class(self): return BraBase def __mul__(self, other): """KetBase*other""" from sympy.physics.quantum.operator import OuterProduct if isinstance(other, BraBase): return OuterProduct(self, other) else: return Expr.__mul__(self, other) def __rmul__(self, other): """other*KetBase""" from sympy.physics.quantum.innerproduct import InnerProduct if isinstance(other, BraBase): return InnerProduct(other, self) else: return Expr.__rmul__(self, other) #------------------------------------------------------------------------- # _eval_* methods #------------------------------------------------------------------------- def _eval_innerproduct(self, bra, **hints): """Evaluate the inner product between this ket and a bra. This is called to compute <bra|ket>, where the ket is ``self``. This method will dispatch to sub-methods having the format:: ``def _eval_innerproduct_BraClass(self, **hints):`` Subclasses should define these methods (one for each BraClass) to teach the ket how to take inner products with bras. """ return dispatch_method(self, '_eval_innerproduct', bra, **hints) def _apply_operator(self, op, **options): """Apply an Operator to this Ket. This method will dispatch to methods having the format:: ``def _apply_operator_OperatorName(op, **options):`` Subclasses should define these methods (one for each OperatorName) to teach the Ket how operators act on it. Parameters ========== op : Operator The Operator that is acting on the Ket. options : dict A dict of key/value pairs that control how the operator is applied to the Ket. """ return dispatch_method(self, '_apply_operator', op, **options) class BraBase(StateBase): """Base class for Bras. This class defines the dual property and the brackets for printing. This is an abstract base class and you should not instantiate it directly, instead use Bra. """ lbracket = _lbracket rbracket = _straight_bracket lbracket_ucode = _lbracket_ucode rbracket_ucode = _straight_bracket_ucode lbracket_latex = r'\left\langle ' rbracket_latex = r'\right|' @classmethod def _operators_to_state(self, ops, **options): state = self.dual_class()._operators_to_state(ops, **options) return state.dual def _state_to_operators(self, op_classes, **options): return self.dual._state_to_operators(op_classes, **options) def _enumerate_state(self, num_states, **options): dual_states = self.dual._enumerate_state(num_states, **options) return [x.dual for x in dual_states] @classmethod def default_args(self): return self.dual_class().default_args() @classmethod def dual_class(self): return KetBase def __mul__(self, other): """BraBase*other""" from sympy.physics.quantum.innerproduct import InnerProduct if isinstance(other, KetBase): return InnerProduct(self, other) else: return Expr.__mul__(self, other) def __rmul__(self, other): """other*BraBase""" from sympy.physics.quantum.operator import OuterProduct if isinstance(other, KetBase): return OuterProduct(other, self) else: return Expr.__rmul__(self, other) def _represent(self, **options): """A default represent that uses the Ket's version.""" from sympy.physics.quantum.dagger import Dagger return Dagger(self.dual._represent(**options)) class State(StateBase): """General abstract quantum state used as a base class for Ket and Bra.""" pass class Ket(State, KetBase): """A general time-independent Ket in quantum mechanics. Inherits from State and KetBase. This class should be used as the base class for all physical, time-independent Kets in a system. This class and its subclasses will be the main classes that users will use for expressing Kets in Dirac notation [1]_. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time. Examples ======== Create a simple Ket and looking at its properties:: >>> from sympy.physics.quantum import Ket >>> from sympy import symbols, I >>> k = Ket('psi') >>> k |psi> >>> k.hilbert_space H >>> k.is_commutative False >>> k.label (psi,) Ket's know about their associated bra:: >>> k.dual <psi| >>> k.dual_class() <class 'sympy.physics.quantum.state.Bra'> Take a linear combination of two kets:: >>> k0 = Ket(0) >>> k1 = Ket(1) >>> 2*I*k0 - 4*k1 2*I*|0> - 4*|1> Compound labels are passed as tuples:: >>> n, m = symbols('n,m') >>> k = Ket(n,m) >>> k |nm> References ========== .. [1] https://en.wikipedia.org/wiki/Bra-ket_notation """ @classmethod def dual_class(self): return Bra class Bra(State, BraBase): """A general time-independent Bra in quantum mechanics. Inherits from State and BraBase. A Bra is the dual of a Ket [1]_. This class and its subclasses will be the main classes that users will use for expressing Bras in Dirac notation. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time. Examples ======== Create a simple Bra and look at its properties:: >>> from sympy.physics.quantum import Bra >>> from sympy import symbols, I >>> b = Bra('psi') >>> b <psi| >>> b.hilbert_space H >>> b.is_commutative False Bra's know about their dual Ket's:: >>> b.dual |psi> >>> b.dual_class() <class 'sympy.physics.quantum.state.Ket'> Like Kets, Bras can have compound labels and be manipulated in a similar manner:: >>> n, m = symbols('n,m') >>> b = Bra(n,m) - I*Bra(m,n) >>> b -I*<mn| + <nm| Symbols in a Bra can be substituted using ``.subs``:: >>> b.subs(n,m) <mm| - I*<mm| References ========== .. [1] https://en.wikipedia.org/wiki/Bra-ket_notation """ @classmethod def dual_class(self): return Ket #----------------------------------------------------------------------------- # Time dependent states, bras and kets. #----------------------------------------------------------------------------- class TimeDepState(StateBase): """Base class for a general time-dependent quantum state. This class is used as a base class for any time-dependent state. The main difference between this class and the time-independent state is that this class takes a second argument that is the time in addition to the usual label argument. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time as the final argument. """ #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def default_args(self): return ("psi", "t") #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def label(self): """The label of the state.""" return self.args[:-1] @property def time(self): """The time of the state.""" return self.args[-1] #------------------------------------------------------------------------- # Printing #------------------------------------------------------------------------- def _print_time(self, printer, *args): return printer._print(self.time, *args) _print_time_repr = _print_time _print_time_latex = _print_time def _print_time_pretty(self, printer, *args): pform = printer._print(self.time, *args) return pform def _print_contents(self, printer, *args): label = self._print_label(printer, *args) time = self._print_time(printer, *args) return '%s;%s' % (label, time) def _print_label_repr(self, printer, *args): label = self._print_sequence(self.label, ',', printer, *args) time = self._print_time_repr(printer, *args) return '%s,%s' % (label, time) def _print_contents_pretty(self, printer, *args): label = self._print_label_pretty(printer, *args) time = self._print_time_pretty(printer, *args) return printer._print_seq((label, time), delimiter=';') def _print_contents_latex(self, printer, *args): label = self._print_sequence( self.label, self._label_separator, printer, *args) time = self._print_time_latex(printer, *args) return '%s;%s' % (label, time) class TimeDepKet(TimeDepState, KetBase): """General time-dependent Ket in quantum mechanics. This inherits from ``TimeDepState`` and ``KetBase`` and is the main class that should be used for Kets that vary with time. Its dual is a ``TimeDepBra``. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time as the final argument. Examples ======== Create a TimeDepKet and look at its attributes:: >>> from sympy.physics.quantum import TimeDepKet >>> k = TimeDepKet('psi', 't') >>> k |psi;t> >>> k.time t >>> k.label (psi,) >>> k.hilbert_space H TimeDepKets know about their dual bra:: >>> k.dual <psi;t| >>> k.dual_class() <class 'sympy.physics.quantum.state.TimeDepBra'> """ @classmethod def dual_class(self): return TimeDepBra class TimeDepBra(TimeDepState, BraBase): """General time-dependent Bra in quantum mechanics. This inherits from TimeDepState and BraBase and is the main class that should be used for Bras that vary with time. Its dual is a TimeDepBra. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time as the final argument. Examples ======== >>> from sympy.physics.quantum import TimeDepBra >>> b = TimeDepBra('psi', 't') >>> b <psi;t| >>> b.time t >>> b.label (psi,) >>> b.hilbert_space H >>> b.dual |psi;t> """ @classmethod def dual_class(self): return TimeDepKet class OrthogonalState(State, StateBase): """General abstract quantum state used as a base class for Ket and Bra.""" pass class OrthogonalKet(OrthogonalState, KetBase): """Orthogonal Ket in quantum mechanics. The inner product of two states with different labels will give zero, states with the same label will give one. >>> from sympy.physics.quantum import OrthogonalBra, OrthogonalKet >>> from sympy.abc import m, n >>> (OrthogonalBra(n)*OrthogonalKet(n)).doit() 1 >>> (OrthogonalBra(n)*OrthogonalKet(n+1)).doit() 0 >>> (OrthogonalBra(n)*OrthogonalKet(m)).doit() <n|m> """ @classmethod def dual_class(self): return OrthogonalBra def _eval_innerproduct(self, bra, **hints): if len(self.args) != len(bra.args): raise ValueError('Cannot multiply a ket that has a different number of labels.') for i in range(len(self.args)): diff = self.args[i] - bra.args[i] diff = diff.expand() if diff.is_zero is False: return 0 if diff.is_zero is None: return None return 1 class OrthogonalBra(OrthogonalState, BraBase): """Orthogonal Bra in quantum mechanics. """ @classmethod def dual_class(self): return OrthogonalKet class Wavefunction(Function): """Class for representations in continuous bases This class takes an expression and coordinates in its constructor. It can be used to easily calculate normalizations and probabilities. Parameters ========== expr : Expr The expression representing the functional form of the w.f. coords : Symbol or tuple The coordinates to be integrated over, and their bounds Examples ======== Particle in a box, specifying bounds in the more primitive way of using Piecewise: >>> from sympy import Symbol, Piecewise, pi, N >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x = Symbol('x', real=True) >>> n = 1 >>> L = 1 >>> g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True)) >>> f = Wavefunction(g, x) >>> f.norm 1 >>> f.is_normalized True >>> p = f.prob() >>> p(0) 0 >>> p(L) 0 >>> p(0.5) 2 >>> p(0.85*L) 2*sin(0.85*pi)**2 >>> N(p(0.85*L)) 0.412214747707527 Additionally, you can specify the bounds of the function and the indices in a more compact way: >>> from sympy import symbols, pi, diff >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x, L = symbols('x,L', positive=True) >>> n = symbols('n', integer=True, positive=True) >>> g = sqrt(2/L)*sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.norm 1 >>> f(L+1) 0 >>> f(L-1) sqrt(2)*sin(pi*n*(L - 1)/L)/sqrt(L) >>> f(-1) 0 >>> f(0.85) sqrt(2)*sin(0.85*pi*n/L)/sqrt(L) >>> f(0.85, n=1, L=1) sqrt(2)*sin(0.85*pi) >>> f.is_commutative False All arguments are automatically sympified, so you can define the variables as strings rather than symbols: >>> expr = x**2 >>> f = Wavefunction(expr, 'x') >>> type(f.variables[0]) <class 'sympy.core.symbol.Symbol'> Derivatives of Wavefunctions will return Wavefunctions: >>> diff(f, x) Wavefunction(2*x, x) """ #Any passed tuples for coordinates and their bounds need to be #converted to Tuples before Function's constructor is called, to #avoid errors from calling is_Float in the constructor def __new__(cls, *args, **options): new_args = [None for i in args] ct = 0 for arg in args: if isinstance(arg, tuple): new_args[ct] = Tuple(*arg) else: new_args[ct] = arg ct += 1 return super(Wavefunction, cls).__new__(cls, *new_args, **options) def __call__(self, *args, **options): var = self.variables if len(args) != len(var): raise NotImplementedError( "Incorrect number of arguments to function!") ct = 0 #If the passed value is outside the specified bounds, return 0 for v in var: lower, upper = self.limits[v] #Do the comparison to limits only if the passed symbol is actually #a symbol present in the limits; #Had problems with a comparison of x > L if isinstance(args[ct], Expr) and \ not (lower in args[ct].free_symbols or upper in args[ct].free_symbols): continue if (args[ct] < lower) == True or (args[ct] > upper) == True: return 0 ct += 1 expr = self.expr #Allows user to make a call like f(2, 4, m=1, n=1) for symbol in list(expr.free_symbols): if str(symbol) in options.keys(): val = options[str(symbol)] expr = expr.subs(symbol, val) return expr.subs(zip(var, args)) def _eval_derivative(self, symbol): expr = self.expr deriv = expr._eval_derivative(symbol) return Wavefunction(deriv, *self.args[1:]) def _eval_conjugate(self): return Wavefunction(conjugate(self.expr), *self.args[1:]) def _eval_transpose(self): return self @property def free_symbols(self): return self.expr.free_symbols @property def is_commutative(self): """ Override Function's is_commutative so that order is preserved in represented expressions """ return False @classmethod def eval(self, *args): return None @property def variables(self): """ Return the coordinates which the wavefunction depends on Examples ======== >>> from sympy.physics.quantum.state import Wavefunction >>> from sympy import symbols >>> x,y = symbols('x,y') >>> f = Wavefunction(x*y, x, y) >>> f.variables (x, y) >>> g = Wavefunction(x*y, x) >>> g.variables (x,) """ var = [g[0] if isinstance(g, Tuple) else g for g in self._args[1:]] return tuple(var) @property def limits(self): """ Return the limits of the coordinates which the w.f. depends on If no limits are specified, defaults to ``(-oo, oo)``. Examples ======== >>> from sympy.physics.quantum.state import Wavefunction >>> from sympy import symbols >>> x, y = symbols('x, y') >>> f = Wavefunction(x**2, (x, 0, 1)) >>> f.limits {x: (0, 1)} >>> f = Wavefunction(x**2, x) >>> f.limits {x: (-oo, oo)} >>> f = Wavefunction(x**2 + y**2, x, (y, -1, 2)) >>> f.limits {x: (-oo, oo), y: (-1, 2)} """ limits = [(g[1], g[2]) if isinstance(g, Tuple) else (-oo, oo) for g in self._args[1:]] return dict(zip(self.variables, tuple(limits))) @property def expr(self): """ Return the expression which is the functional form of the Wavefunction Examples ======== >>> from sympy.physics.quantum.state import Wavefunction >>> from sympy import symbols >>> x, y = symbols('x, y') >>> f = Wavefunction(x**2, x) >>> f.expr x**2 """ return self._args[0] @property def is_normalized(self): """ Returns true if the Wavefunction is properly normalized Examples ======== >>> from sympy import symbols, pi >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x, L = symbols('x,L', positive=True) >>> n = symbols('n', integer=True, positive=True) >>> g = sqrt(2/L)*sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.is_normalized True """ return (self.norm == 1.0) @property # type: ignore @cacheit def norm(self): """ Return the normalization of the specified functional form. This function integrates over the coordinates of the Wavefunction, with the bounds specified. Examples ======== >>> from sympy import symbols, pi >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x, L = symbols('x,L', positive=True) >>> n = symbols('n', integer=True, positive=True) >>> g = sqrt(2/L)*sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.norm 1 >>> g = sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.norm sqrt(2)*sqrt(L)/2 """ exp = self.expr*conjugate(self.expr) var = self.variables limits = self.limits for v in var: curr_limits = limits[v] exp = integrate(exp, (v, curr_limits[0], curr_limits[1])) return sqrt(exp) def normalize(self): """ Return a normalized version of the Wavefunction Examples ======== >>> from sympy import symbols, pi >>> from sympy.functions import sin >>> from sympy.physics.quantum.state import Wavefunction >>> x = symbols('x', real=True) >>> L = symbols('L', positive=True) >>> n = symbols('n', integer=True, positive=True) >>> g = sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.normalize() Wavefunction(sqrt(2)*sin(pi*n*x/L)/sqrt(L), (x, 0, L)) """ const = self.norm if const is oo: raise NotImplementedError("The function is not normalizable!") else: return Wavefunction((const)**(-1)*self.expr, *self.args[1:]) def prob(self): r""" Return the absolute magnitude of the w.f., `|\psi(x)|^2` Examples ======== >>> from sympy import symbols, pi >>> from sympy.functions import sin >>> from sympy.physics.quantum.state import Wavefunction >>> x, L = symbols('x,L', real=True) >>> n = symbols('n', integer=True) >>> g = sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.prob() Wavefunction(sin(pi*n*x/L)**2, x) """ return Wavefunction(self.expr*conjugate(self.expr), *self.variables)
228e57c0fe3d511b2bf6705215df50664f40cf87f6b2a17760d338ad65785323
"""Operators and states for 1D cartesian position and momentum. TODO: * Add 3D classes to mappings in operatorset.py """ from __future__ import print_function, division from sympy import DiracDelta, exp, I, Interval, pi, S, sqrt from sympy.physics.quantum.constants import hbar from sympy.physics.quantum.hilbert import L2 from sympy.physics.quantum.operator import DifferentialOperator, HermitianOperator from sympy.physics.quantum.state import Ket, Bra, State __all__ = [ 'XOp', 'YOp', 'ZOp', 'PxOp', 'X', 'Y', 'Z', 'Px', 'XKet', 'XBra', 'PxKet', 'PxBra', 'PositionState3D', 'PositionKet3D', 'PositionBra3D' ] #------------------------------------------------------------------------- # Position operators #------------------------------------------------------------------------- class XOp(HermitianOperator): """1D cartesian position operator.""" @classmethod def default_args(self): return ("X",) @classmethod def _eval_hilbert_space(self, args): return L2(Interval(S.NegativeInfinity, S.Infinity)) def _eval_commutator_PxOp(self, other): return I*hbar def _apply_operator_XKet(self, ket): return ket.position*ket def _apply_operator_PositionKet3D(self, ket): return ket.position_x*ket def _represent_PxKet(self, basis, *, index=1, **options): states = basis._enumerate_state(2, start_index=index) coord1 = states[0].momentum coord2 = states[1].momentum d = DifferentialOperator(coord1) delta = DiracDelta(coord1 - coord2) return I*hbar*(d*delta) class YOp(HermitianOperator): """ Y cartesian coordinate operator (for 2D or 3D systems) """ @classmethod def default_args(self): return ("Y",) @classmethod def _eval_hilbert_space(self, args): return L2(Interval(S.NegativeInfinity, S.Infinity)) def _apply_operator_PositionKet3D(self, ket): return ket.position_y*ket class ZOp(HermitianOperator): """ Z cartesian coordinate operator (for 3D systems) """ @classmethod def default_args(self): return ("Z",) @classmethod def _eval_hilbert_space(self, args): return L2(Interval(S.NegativeInfinity, S.Infinity)) def _apply_operator_PositionKet3D(self, ket): return ket.position_z*ket #------------------------------------------------------------------------- # Momentum operators #------------------------------------------------------------------------- class PxOp(HermitianOperator): """1D cartesian momentum operator.""" @classmethod def default_args(self): return ("Px",) @classmethod def _eval_hilbert_space(self, args): return L2(Interval(S.NegativeInfinity, S.Infinity)) def _apply_operator_PxKet(self, ket): return ket.momentum*ket def _represent_XKet(self, basis, *, index=1, **options): states = basis._enumerate_state(2, start_index=index) coord1 = states[0].position coord2 = states[1].position d = DifferentialOperator(coord1) delta = DiracDelta(coord1 - coord2) return -I*hbar*(d*delta) X = XOp('X') Y = YOp('Y') Z = ZOp('Z') Px = PxOp('Px') #------------------------------------------------------------------------- # Position eigenstates #------------------------------------------------------------------------- class XKet(Ket): """1D cartesian position eigenket.""" @classmethod def _operators_to_state(self, op, **options): return self.__new__(self, *_lowercase_labels(op), **options) def _state_to_operators(self, op_class, **options): return op_class.__new__(op_class, *_uppercase_labels(self), **options) @classmethod def default_args(self): return ("x",) @classmethod def dual_class(self): return XBra @property def position(self): """The position of the state.""" return self.label[0] def _enumerate_state(self, num_states, **options): return _enumerate_continuous_1D(self, num_states, **options) def _eval_innerproduct_XBra(self, bra, **hints): return DiracDelta(self.position - bra.position) def _eval_innerproduct_PxBra(self, bra, **hints): return exp(-I*self.position*bra.momentum/hbar)/sqrt(2*pi*hbar) class XBra(Bra): """1D cartesian position eigenbra.""" @classmethod def default_args(self): return ("x",) @classmethod def dual_class(self): return XKet @property def position(self): """The position of the state.""" return self.label[0] class PositionState3D(State): """ Base class for 3D cartesian position eigenstates """ @classmethod def _operators_to_state(self, op, **options): return self.__new__(self, *_lowercase_labels(op), **options) def _state_to_operators(self, op_class, **options): return op_class.__new__(op_class, *_uppercase_labels(self), **options) @classmethod def default_args(self): return ("x", "y", "z") @property def position_x(self): """ The x coordinate of the state """ return self.label[0] @property def position_y(self): """ The y coordinate of the state """ return self.label[1] @property def position_z(self): """ The z coordinate of the state """ return self.label[2] class PositionKet3D(Ket, PositionState3D): """ 3D cartesian position eigenket """ def _eval_innerproduct_PositionBra3D(self, bra, **options): x_diff = self.position_x - bra.position_x y_diff = self.position_y - bra.position_y z_diff = self.position_z - bra.position_z return DiracDelta(x_diff)*DiracDelta(y_diff)*DiracDelta(z_diff) @classmethod def dual_class(self): return PositionBra3D # XXX: The type:ignore here is because mypy gives Definition of # "_state_to_operators" in base class "PositionState3D" is incompatible with # definition in base class "BraBase" class PositionBra3D(Bra, PositionState3D): # type: ignore """ 3D cartesian position eigenbra """ @classmethod def dual_class(self): return PositionKet3D #------------------------------------------------------------------------- # Momentum eigenstates #------------------------------------------------------------------------- class PxKet(Ket): """1D cartesian momentum eigenket.""" @classmethod def _operators_to_state(self, op, **options): return self.__new__(self, *_lowercase_labels(op), **options) def _state_to_operators(self, op_class, **options): return op_class.__new__(op_class, *_uppercase_labels(self), **options) @classmethod def default_args(self): return ("px",) @classmethod def dual_class(self): return PxBra @property def momentum(self): """The momentum of the state.""" return self.label[0] def _enumerate_state(self, *args, **options): return _enumerate_continuous_1D(self, *args, **options) def _eval_innerproduct_XBra(self, bra, **hints): return exp(I*self.momentum*bra.position/hbar)/sqrt(2*pi*hbar) def _eval_innerproduct_PxBra(self, bra, **hints): return DiracDelta(self.momentum - bra.momentum) class PxBra(Bra): """1D cartesian momentum eigenbra.""" @classmethod def default_args(self): return ("px",) @classmethod def dual_class(self): return PxKet @property def momentum(self): """The momentum of the state.""" return self.label[0] #------------------------------------------------------------------------- # Global helper functions #------------------------------------------------------------------------- def _enumerate_continuous_1D(*args, **options): state = args[0] num_states = args[1] state_class = state.__class__ index_list = options.pop('index_list', []) if len(index_list) == 0: start_index = options.pop('start_index', 1) index_list = list(range(start_index, start_index + num_states)) enum_states = [0 for i in range(len(index_list))] for i, ind in enumerate(index_list): label = state.args[0] enum_states[i] = state_class(str(label) + "_" + str(ind), **options) return enum_states def _lowercase_labels(ops): if not isinstance(ops, set): ops = [ops] return [str(arg.label[0]).lower() for arg in ops] def _uppercase_labels(ops): if not isinstance(ops, set): ops = [ops] new_args = [str(arg.label[0])[0].upper() + str(arg.label[0])[1:] for arg in ops] return new_args
4fff05179b70435ad0c2aa7f8f9fb953cacc246422640fb3d6c0d1d31bcd4bc7
"""An implementation of gates that act on qubits. Gates are unitary operators that act on the space of qubits. Medium Term Todo: * Optimize Gate._apply_operators_Qubit to remove the creation of many intermediate Qubit objects. * Add commutation relationships to all operators and use this in gate_sort. * Fix gate_sort and gate_simp. * Get multi-target UGates plotting properly. * Get UGate to work with either sympy/numpy matrices and output either format. This should also use the matrix slots. """ from __future__ import print_function, division from itertools import chain import random from sympy import Add, I, Integer, Mul, Pow, sqrt, Tuple from sympy.core.numbers import Number from sympy.core.compatibility import is_sequence from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.operator import (UnitaryOperator, Operator, HermitianOperator) from sympy.physics.quantum.matrixutils import matrix_tensor_product, matrix_eye from sympy.physics.quantum.matrixcache import matrix_cache from sympy.matrices.matrices import MatrixBase from sympy.utilities import default_sort_key __all__ = [ 'Gate', 'CGate', 'UGate', 'OneQubitGate', 'TwoQubitGate', 'IdentityGate', 'HadamardGate', 'XGate', 'YGate', 'ZGate', 'TGate', 'PhaseGate', 'SwapGate', 'CNotGate', # Aliased gate names 'CNOT', 'SWAP', 'H', 'X', 'Y', 'Z', 'T', 'S', 'Phase', 'normalized', 'gate_sort', 'gate_simp', 'random_circuit', 'CPHASE', 'CGateS', ] #----------------------------------------------------------------------------- # Gate Super-Classes #----------------------------------------------------------------------------- _normalized = True def _max(*args, **kwargs): if "key" not in kwargs: kwargs["key"] = default_sort_key return max(*args, **kwargs) def _min(*args, **kwargs): if "key" not in kwargs: kwargs["key"] = default_sort_key return min(*args, **kwargs) def normalized(normalize): """Set flag controlling normalization of Hadamard gates by 1/sqrt(2). This is a global setting that can be used to simplify the look of various expressions, by leaving off the leading 1/sqrt(2) of the Hadamard gate. Parameters ---------- normalize : bool Should the Hadamard gate include the 1/sqrt(2) normalization factor? When True, the Hadamard gate will have the 1/sqrt(2). When False, the Hadamard gate will not have this factor. """ global _normalized _normalized = normalize def _validate_targets_controls(tandc): tandc = list(tandc) # Check for integers for bit in tandc: if not bit.is_Integer and not bit.is_Symbol: raise TypeError('Integer expected, got: %r' % tandc[bit]) # Detect duplicates if len(list(set(tandc))) != len(tandc): raise QuantumError( 'Target/control qubits in a gate cannot be duplicated' ) class Gate(UnitaryOperator): """Non-controlled unitary gate operator that acts on qubits. This is a general abstract gate that needs to be subclassed to do anything useful. Parameters ---------- label : tuple, int A list of the target qubits (as ints) that the gate will apply to. Examples ======== """ _label_separator = ',' gate_name = 'G' gate_name_latex = 'G' #------------------------------------------------------------------------- # Initialization/creation #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): args = Tuple(*UnitaryOperator._eval_args(args)) _validate_targets_controls(args) return args @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(_max(args) + 1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def nqubits(self): """The total number of qubits this gate acts on. For controlled gate subclasses this includes both target and control qubits, so that, for examples the CNOT gate acts on 2 qubits. """ return len(self.targets) @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return _max(self.targets) + 1 @property def targets(self): """A tuple of target qubits.""" return self.label @property def gate_name_plot(self): return r'$%s$' % self.gate_name_latex #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): """The matrix rep. of the target part of the gate. Parameters ---------- format : str The format string ('sympy','numpy', etc.) """ raise NotImplementedError( 'get_target_matrix is not implemented in Gate.') #------------------------------------------------------------------------- # Apply #------------------------------------------------------------------------- def _apply_operator_IntQubit(self, qubits, **options): """Redirect an apply from IntQubit to Qubit""" return self._apply_operator_Qubit(qubits, **options) def _apply_operator_Qubit(self, qubits, **options): """Apply this gate to a Qubit.""" # Check number of qubits this gate acts on. if qubits.nqubits < self.min_qubits: raise QuantumError( 'Gate needs a minimum of %r qubits to act on, got: %r' % (self.min_qubits, qubits.nqubits) ) # If the controls are not met, just return if isinstance(self, CGate): if not self.eval_controls(qubits): return qubits targets = self.targets target_matrix = self.get_target_matrix(format='sympy') # Find which column of the target matrix this applies to. column_index = 0 n = 1 for target in targets: column_index += n*qubits[target] n = n << 1 column = target_matrix[:, int(column_index)] # Now apply each column element to the qubit. result = 0 for index in range(column.rows): # TODO: This can be optimized to reduce the number of Qubit # creations. We should simply manipulate the raw list of qubit # values and then build the new Qubit object once. # Make a copy of the incoming qubits. new_qubit = qubits.__class__(*qubits.args) # Flip the bits that need to be flipped. for bit in range(len(targets)): if new_qubit[targets[bit]] != (index >> bit) & 1: new_qubit = new_qubit.flip(targets[bit]) # The value in that row and column times the flipped-bit qubit # is the result for that part. result += column[index]*new_qubit return result #------------------------------------------------------------------------- # Represent #------------------------------------------------------------------------- def _represent_default_basis(self, **options): return self._represent_ZGate(None, **options) def _represent_ZGate(self, basis, **options): format = options.get('format', 'sympy') nqubits = options.get('nqubits', 0) if nqubits == 0: raise QuantumError( 'The number of qubits must be given as nqubits.') # Make sure we have enough qubits for the gate. if nqubits < self.min_qubits: raise QuantumError( 'The number of qubits %r is too small for the gate.' % nqubits ) target_matrix = self.get_target_matrix(format) targets = self.targets if isinstance(self, CGate): controls = self.controls else: controls = [] m = represent_zbasis( controls, targets, target_matrix, nqubits, format ) return m #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _sympystr(self, printer, *args): label = self._print_label(printer, *args) return '%s(%s)' % (self.gate_name, label) def _pretty(self, printer, *args): a = stringPict(self.gate_name) b = self._print_label_pretty(printer, *args) return self._print_subscript_pretty(a, b) def _latex(self, printer, *args): label = self._print_label(printer, *args) return '%s_{%s}' % (self.gate_name_latex, label) def plot_gate(self, axes, gate_idx, gate_grid, wire_grid): raise NotImplementedError('plot_gate is not implemented.') class CGate(Gate): """A general unitary gate with control qubits. A general control gate applies a target gate to a set of targets if all of the control qubits have a particular values (set by ``CGate.control_value``). Parameters ---------- label : tuple The label in this case has the form (controls, gate), where controls is a tuple/list of control qubits (as ints) and gate is a ``Gate`` instance that is the target operator. Examples ======== """ gate_name = 'C' gate_name_latex = 'C' # The values this class controls for. control_value = Integer(1) simplify_cgate=False #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): # _eval_args has the right logic for the controls argument. controls = args[0] gate = args[1] if not is_sequence(controls): controls = (controls,) controls = UnitaryOperator._eval_args(controls) _validate_targets_controls(chain(controls, gate.targets)) return (Tuple(*controls), gate) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**_max(_max(args[0]) + 1, args[1].min_qubits) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def nqubits(self): """The total number of qubits this gate acts on. For controlled gate subclasses this includes both target and control qubits, so that, for examples the CNOT gate acts on 2 qubits. """ return len(self.targets) + len(self.controls) @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return _max(_max(self.controls), _max(self.targets)) + 1 @property def targets(self): """A tuple of target qubits.""" return self.gate.targets @property def controls(self): """A tuple of control qubits.""" return tuple(self.label[0]) @property def gate(self): """The non-controlled gate that will be applied to the targets.""" return self.label[1] #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): return self.gate.get_target_matrix(format) def eval_controls(self, qubit): """Return True/False to indicate if the controls are satisfied.""" return all(qubit[bit] == self.control_value for bit in self.controls) def decompose(self, **options): """Decompose the controlled gate into CNOT and single qubits gates.""" if len(self.controls) == 1: c = self.controls[0] t = self.gate.targets[0] if isinstance(self.gate, YGate): g1 = PhaseGate(t) g2 = CNotGate(c, t) g3 = PhaseGate(t) g4 = ZGate(t) return g1*g2*g3*g4 if isinstance(self.gate, ZGate): g1 = HadamardGate(t) g2 = CNotGate(c, t) g3 = HadamardGate(t) return g1*g2*g3 else: return self #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _print_label(self, printer, *args): controls = self._print_sequence(self.controls, ',', printer, *args) gate = printer._print(self.gate, *args) return '(%s),%s' % (controls, gate) def _pretty(self, printer, *args): controls = self._print_sequence_pretty( self.controls, ',', printer, *args) gate = printer._print(self.gate) gate_name = stringPict(self.gate_name) first = self._print_subscript_pretty(gate_name, controls) gate = self._print_parens_pretty(gate) final = prettyForm(*first.right((gate))) return final def _latex(self, printer, *args): controls = self._print_sequence(self.controls, ',', printer, *args) gate = printer._print(self.gate, *args) return r'%s_{%s}{\left(%s\right)}' % \ (self.gate_name_latex, controls, gate) def plot_gate(self, circ_plot, gate_idx): """ Plot the controlled gate. If *simplify_cgate* is true, simplify C-X and C-Z gates into their more familiar forms. """ min_wire = int(_min(chain(self.controls, self.targets))) max_wire = int(_max(chain(self.controls, self.targets))) circ_plot.control_line(gate_idx, min_wire, max_wire) for c in self.controls: circ_plot.control_point(gate_idx, int(c)) if self.simplify_cgate: if self.gate.gate_name == 'X': self.gate.plot_gate_plus(circ_plot, gate_idx) elif self.gate.gate_name == 'Z': circ_plot.control_point(gate_idx, self.targets[0]) else: self.gate.plot_gate(circ_plot, gate_idx) else: self.gate.plot_gate(circ_plot, gate_idx) #------------------------------------------------------------------------- # Miscellaneous #------------------------------------------------------------------------- def _eval_dagger(self): if isinstance(self.gate, HermitianOperator): return self else: return Gate._eval_dagger(self) def _eval_inverse(self): if isinstance(self.gate, HermitianOperator): return self else: return Gate._eval_inverse(self) def _eval_power(self, exp): if isinstance(self.gate, HermitianOperator): if exp == -1: return Gate._eval_power(self, exp) elif abs(exp) % 2 == 0: return self*(Gate._eval_inverse(self)) else: return self else: return Gate._eval_power(self, exp) class CGateS(CGate): """Version of CGate that allows gate simplifications. I.e. cnot looks like an oplus, cphase has dots, etc. """ simplify_cgate=True class UGate(Gate): """General gate specified by a set of targets and a target matrix. Parameters ---------- label : tuple A tuple of the form (targets, U), where targets is a tuple of the target qubits and U is a unitary matrix with dimension of len(targets). """ gate_name = 'U' gate_name_latex = 'U' #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): targets = args[0] if not is_sequence(targets): targets = (targets,) targets = Gate._eval_args(targets) _validate_targets_controls(targets) mat = args[1] if not isinstance(mat, MatrixBase): raise TypeError('Matrix expected, got: %r' % mat) dim = 2**len(targets) if not all(dim == shape for shape in mat.shape): raise IndexError( 'Number of targets must match the matrix size: %r %r' % (targets, mat) ) return (targets, mat) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(_max(args[0]) + 1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def targets(self): """A tuple of target qubits.""" return tuple(self.label[0]) #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): """The matrix rep. of the target part of the gate. Parameters ---------- format : str The format string ('sympy','numpy', etc.) """ return self.label[1] #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _pretty(self, printer, *args): targets = self._print_sequence_pretty( self.targets, ',', printer, *args) gate_name = stringPict(self.gate_name) return self._print_subscript_pretty(gate_name, targets) def _latex(self, printer, *args): targets = self._print_sequence(self.targets, ',', printer, *args) return r'%s_{%s}' % (self.gate_name_latex, targets) def plot_gate(self, circ_plot, gate_idx): circ_plot.one_qubit_box( self.gate_name_plot, gate_idx, int(self.targets[0]) ) class OneQubitGate(Gate): """A single qubit unitary gate base class.""" nqubits = Integer(1) def plot_gate(self, circ_plot, gate_idx): circ_plot.one_qubit_box( self.gate_name_plot, gate_idx, int(self.targets[0]) ) def _eval_commutator(self, other, **hints): if isinstance(other, OneQubitGate): if self.targets != other.targets or self.__class__ == other.__class__: return Integer(0) return Operator._eval_commutator(self, other, **hints) def _eval_anticommutator(self, other, **hints): if isinstance(other, OneQubitGate): if self.targets != other.targets or self.__class__ == other.__class__: return Integer(2)*self*other return Operator._eval_anticommutator(self, other, **hints) class TwoQubitGate(Gate): """A two qubit unitary gate base class.""" nqubits = Integer(2) #----------------------------------------------------------------------------- # Single Qubit Gates #----------------------------------------------------------------------------- class IdentityGate(OneQubitGate): """The single qubit identity gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = '1' gate_name_latex = '1' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('eye2', format) def _eval_commutator(self, other, **hints): return Integer(0) def _eval_anticommutator(self, other, **hints): return Integer(2)*other class HadamardGate(HermitianOperator, OneQubitGate): """The single qubit Hadamard gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== >>> from sympy import sqrt >>> from sympy.physics.quantum.qubit import Qubit >>> from sympy.physics.quantum.gate import HadamardGate >>> from sympy.physics.quantum.qapply import qapply >>> qapply(HadamardGate(0)*Qubit('1')) sqrt(2)*|0>/2 - sqrt(2)*|1>/2 >>> # Hadamard on bell state, applied on 2 qubits. >>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11')) >>> qapply(HadamardGate(0)*HadamardGate(1)*psi) sqrt(2)*|00>/2 + sqrt(2)*|11>/2 """ gate_name = 'H' gate_name_latex = 'H' def get_target_matrix(self, format='sympy'): if _normalized: return matrix_cache.get_matrix('H', format) else: return matrix_cache.get_matrix('Hsqrt2', format) def _eval_commutator_XGate(self, other, **hints): return I*sqrt(2)*YGate(self.targets[0]) def _eval_commutator_YGate(self, other, **hints): return I*sqrt(2)*(ZGate(self.targets[0]) - XGate(self.targets[0])) def _eval_commutator_ZGate(self, other, **hints): return -I*sqrt(2)*YGate(self.targets[0]) def _eval_anticommutator_XGate(self, other, **hints): return sqrt(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0) def _eval_anticommutator_ZGate(self, other, **hints): return sqrt(2)*IdentityGate(self.targets[0]) class XGate(HermitianOperator, OneQubitGate): """The single qubit X, or NOT, gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = 'X' gate_name_latex = 'X' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('X', format) def plot_gate(self, circ_plot, gate_idx): OneQubitGate.plot_gate(self,circ_plot,gate_idx) def plot_gate_plus(self, circ_plot, gate_idx): circ_plot.not_point( gate_idx, int(self.label[0]) ) def _eval_commutator_YGate(self, other, **hints): return Integer(2)*I*ZGate(self.targets[0]) def _eval_anticommutator_XGate(self, other, **hints): return Integer(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0) def _eval_anticommutator_ZGate(self, other, **hints): return Integer(0) class YGate(HermitianOperator, OneQubitGate): """The single qubit Y gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = 'Y' gate_name_latex = 'Y' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('Y', format) def _eval_commutator_ZGate(self, other, **hints): return Integer(2)*I*XGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_ZGate(self, other, **hints): return Integer(0) class ZGate(HermitianOperator, OneQubitGate): """The single qubit Z gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = 'Z' gate_name_latex = 'Z' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('Z', format) def _eval_commutator_XGate(self, other, **hints): return Integer(2)*I*YGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0) class PhaseGate(OneQubitGate): """The single qubit phase, or S, gate. This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and does nothing if the state is ``|0>``. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = 'S' gate_name_latex = 'S' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('S', format) def _eval_commutator_ZGate(self, other, **hints): return Integer(0) def _eval_commutator_TGate(self, other, **hints): return Integer(0) class TGate(OneQubitGate): """The single qubit pi/8 gate. This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and does nothing if the state is ``|0>``. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = 'T' gate_name_latex = 'T' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('T', format) def _eval_commutator_ZGate(self, other, **hints): return Integer(0) def _eval_commutator_PhaseGate(self, other, **hints): return Integer(0) # Aliases for gate names. H = HadamardGate X = XGate Y = YGate Z = ZGate T = TGate Phase = S = PhaseGate #----------------------------------------------------------------------------- # 2 Qubit Gates #----------------------------------------------------------------------------- class CNotGate(HermitianOperator, CGate, TwoQubitGate): """Two qubit controlled-NOT. This gate performs the NOT or X gate on the target qubit if the control qubits all have the value 1. Parameters ---------- label : tuple A tuple of the form (control, target). Examples ======== >>> from sympy.physics.quantum.gate import CNOT >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.qubit import Qubit >>> c = CNOT(1,0) >>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left |11> """ gate_name = 'CNOT' gate_name_latex = 'CNOT' simplify_cgate = True #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): args = Gate._eval_args(args) return args @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(_max(args) + 1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return _max(self.label) + 1 @property def targets(self): """A tuple of target qubits.""" return (self.label[1],) @property def controls(self): """A tuple of control qubits.""" return (self.label[0],) @property def gate(self): """The non-controlled gate that will be applied to the targets.""" return XGate(self.label[1]) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- # The default printing of Gate works better than those of CGate, so we # go around the overridden methods in CGate. def _print_label(self, printer, *args): return Gate._print_label(self, printer, *args) def _pretty(self, printer, *args): return Gate._pretty(self, printer, *args) def _latex(self, printer, *args): return Gate._latex(self, printer, *args) #------------------------------------------------------------------------- # Commutator/AntiCommutator #------------------------------------------------------------------------- def _eval_commutator_ZGate(self, other, **hints): """[CNOT(i, j), Z(i)] == 0.""" if self.controls[0] == other.targets[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other) def _eval_commutator_TGate(self, other, **hints): """[CNOT(i, j), T(i)] == 0.""" return self._eval_commutator_ZGate(other, **hints) def _eval_commutator_PhaseGate(self, other, **hints): """[CNOT(i, j), S(i)] == 0.""" return self._eval_commutator_ZGate(other, **hints) def _eval_commutator_XGate(self, other, **hints): """[CNOT(i, j), X(j)] == 0.""" if self.targets[0] == other.targets[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other) def _eval_commutator_CNotGate(self, other, **hints): """[CNOT(i, j), CNOT(i,k)] == 0.""" if self.controls[0] == other.controls[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other) class SwapGate(TwoQubitGate): """Two qubit SWAP gate. This gate swap the values of the two qubits. Parameters ---------- label : tuple A tuple of the form (target1, target2). Examples ======== """ gate_name = 'SWAP' gate_name_latex = 'SWAP' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('SWAP', format) def decompose(self, **options): """Decompose the SWAP gate into CNOT gates.""" i, j = self.targets[0], self.targets[1] g1 = CNotGate(i, j) g2 = CNotGate(j, i) return g1*g2*g1 def plot_gate(self, circ_plot, gate_idx): min_wire = int(_min(self.targets)) max_wire = int(_max(self.targets)) circ_plot.control_line(gate_idx, min_wire, max_wire) circ_plot.swap_point(gate_idx, min_wire) circ_plot.swap_point(gate_idx, max_wire) def _represent_ZGate(self, basis, **options): """Represent the SWAP gate in the computational basis. The following representation is used to compute this: SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0| """ format = options.get('format', 'sympy') targets = [int(t) for t in self.targets] min_target = _min(targets) max_target = _max(targets) nqubits = options.get('nqubits', self.min_qubits) op01 = matrix_cache.get_matrix('op01', format) op10 = matrix_cache.get_matrix('op10', format) op11 = matrix_cache.get_matrix('op11', format) op00 = matrix_cache.get_matrix('op00', format) eye2 = matrix_cache.get_matrix('eye2', format) result = None for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)): product = nqubits*[eye2] product[nqubits - min_target - 1] = i product[nqubits - max_target - 1] = j new_result = matrix_tensor_product(*product) if result is None: result = new_result else: result = result + new_result return result # Aliases for gate names. CNOT = CNotGate SWAP = SwapGate def CPHASE(a,b): return CGateS((a,),Z(b)) #----------------------------------------------------------------------------- # Represent #----------------------------------------------------------------------------- def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'): """Represent a gate with controls, targets and target_matrix. This function does the low-level work of representing gates as matrices in the standard computational basis (ZGate). Currently, we support two main cases: 1. One target qubit and no control qubits. 2. One target qubits and multiple control qubits. For the base of multiple controls, we use the following expression [1]: 1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2}) Parameters ---------- controls : list, tuple A sequence of control qubits. targets : list, tuple A sequence of target qubits. target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse The matrix form of the transformation to be performed on the target qubits. The format of this matrix must match that passed into the `format` argument. nqubits : int The total number of qubits used for the representation. format : str The format of the final matrix ('sympy', 'numpy', 'scipy.sparse'). Examples ======== References ---------- [1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html. """ controls = [int(x) for x in controls] targets = [int(x) for x in targets] nqubits = int(nqubits) # This checks for the format as well. op11 = matrix_cache.get_matrix('op11', format) eye2 = matrix_cache.get_matrix('eye2', format) # Plain single qubit case if len(controls) == 0 and len(targets) == 1: product = [] bit = targets[0] # Fill product with [I1,Gate,I2] such that the unitaries, # I, cause the gate to be applied to the correct Qubit if bit != nqubits - 1: product.append(matrix_eye(2**(nqubits - bit - 1), format=format)) product.append(target_matrix) if bit != 0: product.append(matrix_eye(2**bit, format=format)) return matrix_tensor_product(*product) # Single target, multiple controls. elif len(targets) == 1 and len(controls) >= 1: target = targets[0] # Build the non-trivial part. product2 = [] for i in range(nqubits): product2.append(matrix_eye(2, format=format)) for control in controls: product2[nqubits - 1 - control] = op11 product2[nqubits - 1 - target] = target_matrix - eye2 return matrix_eye(2**nqubits, format=format) + \ matrix_tensor_product(*product2) # Multi-target, multi-control is not yet implemented. else: raise NotImplementedError( 'The representation of multi-target, multi-control gates ' 'is not implemented.' ) #----------------------------------------------------------------------------- # Gate manipulation functions. #----------------------------------------------------------------------------- def gate_simp(circuit): """Simplifies gates symbolically It first sorts gates using gate_sort. It then applies basic simplification rules to the circuit, e.g., XGate**2 = Identity """ # Bubble sort out gates that commute. circuit = gate_sort(circuit) # Do simplifications by subing a simplification into the first element # which can be simplified. We recursively call gate_simp with new circuit # as input more simplifications exist. if isinstance(circuit, Add): return sum(gate_simp(t) for t in circuit.args) elif isinstance(circuit, Mul): circuit_args = circuit.args elif isinstance(circuit, Pow): b, e = circuit.as_base_exp() circuit_args = (gate_simp(b)**e,) else: return circuit # Iterate through each element in circuit, simplify if possible. for i in range(len(circuit_args)): # H,X,Y or Z squared is 1. # T**2 = S, S**2 = Z if isinstance(circuit_args[i], Pow): if isinstance(circuit_args[i].base, (HadamardGate, XGate, YGate, ZGate)) \ and isinstance(circuit_args[i].exp, Number): # Build a new circuit taking replacing the # H,X,Y,Z squared with one. newargs = (circuit_args[:i] + (circuit_args[i].base**(circuit_args[i].exp % 2),) + circuit_args[i + 1:]) # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break elif isinstance(circuit_args[i].base, PhaseGate): # Build a new circuit taking old circuit but splicing # in simplification. newargs = circuit_args[:i] # Replace PhaseGate**2 with ZGate. newargs = newargs + (ZGate(circuit_args[i].base.args[0])** (Integer(circuit_args[i].exp/2)), circuit_args[i].base** (circuit_args[i].exp % 2)) # Append the last elements. newargs = newargs + circuit_args[i + 1:] # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break elif isinstance(circuit_args[i].base, TGate): # Build a new circuit taking all the old elements. newargs = circuit_args[:i] # Put an Phasegate in place of any TGate**2. newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])** Integer(circuit_args[i].exp/2), circuit_args[i].base** (circuit_args[i].exp % 2)) # Append the last elements. newargs = newargs + circuit_args[i + 1:] # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break return circuit def gate_sort(circuit): """Sorts the gates while keeping track of commutation relations This function uses a bubble sort to rearrange the order of gate application. Keeps track of Quantum computations special commutation relations (e.g. things that apply to the same Qubit do not commute with each other) circuit is the Mul of gates that are to be sorted. """ # Make sure we have an Add or Mul. if isinstance(circuit, Add): return sum(gate_sort(t) for t in circuit.args) if isinstance(circuit, Pow): return gate_sort(circuit.base)**circuit.exp elif isinstance(circuit, Gate): return circuit if not isinstance(circuit, Mul): return circuit changes = True while changes: changes = False circ_array = circuit.args for i in range(len(circ_array) - 1): # Go through each element and switch ones that are in wrong order if isinstance(circ_array[i], (Gate, Pow)) and \ isinstance(circ_array[i + 1], (Gate, Pow)): # If we have a Pow object, look at only the base first_base, first_exp = circ_array[i].as_base_exp() second_base, second_exp = circ_array[i + 1].as_base_exp() # Use sympy's hash based sorting. This is not mathematical # sorting, but is rather based on comparing hashes of objects. # See Basic.compare for details. if first_base.compare(second_base) > 0: if Commutator(first_base, second_base).doit() == 0: new_args = (circuit.args[:i] + (circuit.args[i + 1],) + (circuit.args[i],) + circuit.args[i + 2:]) circuit = Mul(*new_args) changes = True break if AntiCommutator(first_base, second_base).doit() == 0: new_args = (circuit.args[:i] + (circuit.args[i + 1],) + (circuit.args[i],) + circuit.args[i + 2:]) sign = Integer(-1)**(first_exp*second_exp) circuit = sign*Mul(*new_args) changes = True break return circuit #----------------------------------------------------------------------------- # Utility functions #----------------------------------------------------------------------------- def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)): """Return a random circuit of ngates and nqubits. This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP) gates. Parameters ---------- ngates : int The number of gates in the circuit. nqubits : int The number of qubits in the circuit. gate_space : tuple A tuple of the gate classes that will be used in the circuit. Repeating gate classes multiple times in this tuple will increase the frequency they appear in the random circuit. """ qubit_space = range(nqubits) result = [] for i in range(ngates): g = random.choice(gate_space) if g == CNotGate or g == SwapGate: qubits = random.sample(qubit_space, 2) g = g(*qubits) else: qubit = random.choice(qubit_space) g = g(qubit) result.append(g) return Mul(*result) def zx_basis_transform(self, format='sympy'): """Transformation matrix from Z to X basis.""" return matrix_cache.get_matrix('ZX', format) def zy_basis_transform(self, format='sympy'): """Transformation matrix from Z to Y basis.""" return matrix_cache.get_matrix('ZY', format)
612c3dfab6dd1a4445e56f3fa14fcf4229d0a93e557a7f2a30cec15b135d1a82
"""Logic for representing operators in state in various bases. TODO: * Get represent working with continuous hilbert spaces. * Document default basis functionality. """ from __future__ import print_function, division from sympy import Add, Expr, I, integrate, Mul, Pow from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.innerproduct import InnerProduct from sympy.physics.quantum.qexpr import QExpr from sympy.physics.quantum.tensorproduct import TensorProduct from sympy.physics.quantum.matrixutils import flatten_scalar from sympy.physics.quantum.state import KetBase, BraBase, StateBase from sympy.physics.quantum.operator import Operator, OuterProduct from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.operatorset import operators_to_state, state_to_operators __all__ = [ 'represent', 'rep_innerproduct', 'rep_expectation', 'integrate_result', 'get_basis', 'enumerate_states' ] #----------------------------------------------------------------------------- # Represent #----------------------------------------------------------------------------- def _sympy_to_scalar(e): """Convert from a sympy scalar to a Python scalar.""" if isinstance(e, Expr): if e.is_Integer: return int(e) elif e.is_Float: return float(e) elif e.is_Rational: return float(e) elif e.is_Number or e.is_NumberSymbol or e == I: return complex(e) raise TypeError('Expected number, got: %r' % e) def represent(expr, **options): """Represent the quantum expression in the given basis. In quantum mechanics abstract states and operators can be represented in various basis sets. Under this operation the follow transforms happen: * Ket -> column vector or function * Bra -> row vector of function * Operator -> matrix or differential operator This function is the top-level interface for this action. This function walks the sympy expression tree looking for ``QExpr`` instances that have a ``_represent`` method. This method is then called and the object is replaced by the representation returned by this method. By default, the ``_represent`` method will dispatch to other methods that handle the representation logic for a particular basis set. The naming convention for these methods is the following:: def _represent_FooBasis(self, e, basis, **options) This function will have the logic for representing instances of its class in the basis set having a class named ``FooBasis``. Parameters ========== expr : Expr The expression to represent. basis : Operator, basis set An object that contains the information about the basis set. If an operator is used, the basis is assumed to be the orthonormal eigenvectors of that operator. In general though, the basis argument can be any object that contains the basis set information. options : dict Key/value pairs of options that are passed to the underlying method that finds the representation. These options can be used to control how the representation is done. For example, this is where the size of the basis set would be set. Returns ======= e : Expr The SymPy expression of the represented quantum expression. Examples ======== Here we subclass ``Operator`` and ``Ket`` to create the z-spin operator and its spin 1/2 up eigenstate. By defining the ``_represent_SzOp`` method, the ket can be represented in the z-spin basis. >>> from sympy.physics.quantum import Operator, represent, Ket >>> from sympy import Matrix >>> class SzUpKet(Ket): ... def _represent_SzOp(self, basis, **options): ... return Matrix([1,0]) ... >>> class SzOp(Operator): ... pass ... >>> sz = SzOp('Sz') >>> up = SzUpKet('up') >>> represent(up, basis=sz) Matrix([ [1], [0]]) Here we see an example of representations in a continuous basis. We see that the result of representing various combinations of cartesian position operators and kets give us continuous expressions involving DiracDelta functions. >>> from sympy.physics.quantum.cartesian import XOp, XKet, XBra >>> X = XOp() >>> x = XKet() >>> y = XBra('y') >>> represent(X*x) x*DiracDelta(x - x_2) >>> represent(X*x*y) x*DiracDelta(x - x_3)*DiracDelta(x_1 - y) """ format = options.get('format', 'sympy') if isinstance(expr, QExpr) and not isinstance(expr, OuterProduct): options['replace_none'] = False temp_basis = get_basis(expr, **options) if temp_basis is not None: options['basis'] = temp_basis try: return expr._represent(**options) except NotImplementedError as strerr: #If no _represent_FOO method exists, map to the #appropriate basis state and try #the other methods of representation options['replace_none'] = True if isinstance(expr, (KetBase, BraBase)): try: return rep_innerproduct(expr, **options) except NotImplementedError: raise NotImplementedError(strerr) elif isinstance(expr, Operator): try: return rep_expectation(expr, **options) except NotImplementedError: raise NotImplementedError(strerr) else: raise NotImplementedError(strerr) elif isinstance(expr, Add): result = represent(expr.args[0], **options) for args in expr.args[1:]: # scipy.sparse doesn't support += so we use plain = here. result = result + represent(args, **options) return result elif isinstance(expr, Pow): base, exp = expr.as_base_exp() if format == 'numpy' or format == 'scipy.sparse': exp = _sympy_to_scalar(exp) base = represent(base, **options) # scipy.sparse doesn't support negative exponents # and warns when inverting a matrix in csr format. if format == 'scipy.sparse' and exp < 0: from scipy.sparse.linalg import inv exp = - exp base = inv(base.tocsc()).tocsr() return base ** exp elif isinstance(expr, TensorProduct): new_args = [represent(arg, **options) for arg in expr.args] return TensorProduct(*new_args) elif isinstance(expr, Dagger): return Dagger(represent(expr.args[0], **options)) elif isinstance(expr, Commutator): A = represent(expr.args[0], **options) B = represent(expr.args[1], **options) return A*B - B*A elif isinstance(expr, AntiCommutator): A = represent(expr.args[0], **options) B = represent(expr.args[1], **options) return A*B + B*A elif isinstance(expr, InnerProduct): return represent(Mul(expr.bra, expr.ket), **options) elif not (isinstance(expr, Mul) or isinstance(expr, OuterProduct)): # For numpy and scipy.sparse, we can only handle numerical prefactors. if format == 'numpy' or format == 'scipy.sparse': return _sympy_to_scalar(expr) return expr if not (isinstance(expr, Mul) or isinstance(expr, OuterProduct)): raise TypeError('Mul expected, got: %r' % expr) if "index" in options: options["index"] += 1 else: options["index"] = 1 if not "unities" in options: options["unities"] = [] result = represent(expr.args[-1], **options) last_arg = expr.args[-1] for arg in reversed(expr.args[:-1]): if isinstance(last_arg, Operator): options["index"] += 1 options["unities"].append(options["index"]) elif isinstance(last_arg, BraBase) and isinstance(arg, KetBase): options["index"] += 1 elif isinstance(last_arg, KetBase) and isinstance(arg, Operator): options["unities"].append(options["index"]) elif isinstance(last_arg, KetBase) and isinstance(arg, BraBase): options["unities"].append(options["index"]) result = represent(arg, **options)*result last_arg = arg # All three matrix formats create 1 by 1 matrices when inner products of # vectors are taken. In these cases, we simply return a scalar. result = flatten_scalar(result) result = integrate_result(expr, result, **options) return result def rep_innerproduct(expr, **options): """ Returns an innerproduct like representation (e.g. ``<x'|x>``) for the given state. Attempts to calculate inner product with a bra from the specified basis. Should only be passed an instance of KetBase or BraBase Parameters ========== expr : KetBase or BraBase The expression to be represented Examples ======== >>> from sympy.physics.quantum.represent import rep_innerproduct >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet >>> rep_innerproduct(XKet()) DiracDelta(x - x_1) >>> rep_innerproduct(XKet(), basis=PxOp()) sqrt(2)*exp(-I*px_1*x/hbar)/(2*sqrt(hbar)*sqrt(pi)) >>> rep_innerproduct(PxKet(), basis=XOp()) sqrt(2)*exp(I*px*x_1/hbar)/(2*sqrt(hbar)*sqrt(pi)) """ if not isinstance(expr, (KetBase, BraBase)): raise TypeError("expr passed is not a Bra or Ket") basis = get_basis(expr, **options) if not isinstance(basis, StateBase): raise NotImplementedError("Can't form this representation!") if not "index" in options: options["index"] = 1 basis_kets = enumerate_states(basis, options["index"], 2) if isinstance(expr, BraBase): bra = expr ket = (basis_kets[1] if basis_kets[0].dual == expr else basis_kets[0]) else: bra = (basis_kets[1].dual if basis_kets[0] == expr else basis_kets[0].dual) ket = expr prod = InnerProduct(bra, ket) result = prod.doit() format = options.get('format', 'sympy') return expr._format_represent(result, format) def rep_expectation(expr, **options): """ Returns an ``<x'|A|x>`` type representation for the given operator. Parameters ========== expr : Operator Operator to be represented in the specified basis Examples ======== >>> from sympy.physics.quantum.cartesian import XOp, PxOp, PxKet >>> from sympy.physics.quantum.represent import rep_expectation >>> rep_expectation(XOp()) x_1*DiracDelta(x_1 - x_2) >>> rep_expectation(XOp(), basis=PxOp()) <px_2|*X*|px_1> >>> rep_expectation(XOp(), basis=PxKet()) <px_2|*X*|px_1> """ if not "index" in options: options["index"] = 1 if not isinstance(expr, Operator): raise TypeError("The passed expression is not an operator") basis_state = get_basis(expr, **options) if basis_state is None or not isinstance(basis_state, StateBase): raise NotImplementedError("Could not get basis kets for this operator") basis_kets = enumerate_states(basis_state, options["index"], 2) bra = basis_kets[1].dual ket = basis_kets[0] return qapply(bra*expr*ket) def integrate_result(orig_expr, result, **options): """ Returns the result of integrating over any unities ``(|x><x|)`` in the given expression. Intended for integrating over the result of representations in continuous bases. This function integrates over any unities that may have been inserted into the quantum expression and returns the result. It uses the interval of the Hilbert space of the basis state passed to it in order to figure out the limits of integration. The unities option must be specified for this to work. Note: This is mostly used internally by represent(). Examples are given merely to show the use cases. Parameters ========== orig_expr : quantum expression The original expression which was to be represented result: Expr The resulting representation that we wish to integrate over Examples ======== >>> from sympy import symbols, DiracDelta >>> from sympy.physics.quantum.represent import integrate_result >>> from sympy.physics.quantum.cartesian import XOp, XKet >>> x_ket = XKet() >>> X_op = XOp() >>> x, x_1, x_2 = symbols('x, x_1, x_2') >>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2)) x*DiracDelta(x - x_1)*DiracDelta(x_1 - x_2) >>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2), ... unities=[1]) x*DiracDelta(x - x_2) """ if not isinstance(result, Expr): return result options['replace_none'] = True if not "basis" in options: arg = orig_expr.args[-1] options["basis"] = get_basis(arg, **options) elif not isinstance(options["basis"], StateBase): options["basis"] = get_basis(orig_expr, **options) basis = options.pop("basis", None) if basis is None: return result unities = options.pop("unities", []) if len(unities) == 0: return result kets = enumerate_states(basis, unities) coords = [k.label[0] for k in kets] for coord in coords: if coord in result.free_symbols: #TODO: Add support for sets of operators basis_op = state_to_operators(basis) start = basis_op.hilbert_space.interval.start end = basis_op.hilbert_space.interval.end result = integrate(result, (coord, start, end)) return result def get_basis(expr, *, basis=None, replace_none=True, **options): """ Returns a basis state instance corresponding to the basis specified in options=s. If no basis is specified, the function tries to form a default basis state of the given expression. There are three behaviors: 1. The basis specified in options is already an instance of StateBase. If this is the case, it is simply returned. If the class is specified but not an instance, a default instance is returned. 2. The basis specified is an operator or set of operators. If this is the case, the operator_to_state mapping method is used. 3. No basis is specified. If expr is a state, then a default instance of its class is returned. If expr is an operator, then it is mapped to the corresponding state. If it is neither, then we cannot obtain the basis state. If the basis cannot be mapped, then it is not changed. This will be called from within represent, and represent will only pass QExpr's. TODO (?): Support for Muls and other types of expressions? Parameters ========== expr : Operator or StateBase Expression whose basis is sought Examples ======== >>> from sympy.physics.quantum.represent import get_basis >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet >>> x = XKet() >>> X = XOp() >>> get_basis(x) |x> >>> get_basis(X) |x> >>> get_basis(x, basis=PxOp()) |px> >>> get_basis(x, basis=PxKet) |px> """ if basis is None and not replace_none: return None if basis is None: if isinstance(expr, KetBase): return _make_default(expr.__class__) elif isinstance(expr, BraBase): return _make_default((expr.dual_class())) elif isinstance(expr, Operator): state_inst = operators_to_state(expr) return (state_inst if state_inst is not None else None) else: return None elif (isinstance(basis, Operator) or (not isinstance(basis, StateBase) and issubclass(basis, Operator))): state = operators_to_state(basis) if state is None: return None elif isinstance(state, StateBase): return state else: return _make_default(state) elif isinstance(basis, StateBase): return basis elif issubclass(basis, StateBase): return _make_default(basis) else: return None def _make_default(expr): # XXX: Catching TypeError like this is a bad way of distinguishing # instances from classes. The logic using this function should be # rewritten somehow. try: expr = expr() except TypeError: return expr return expr def enumerate_states(*args, **options): """ Returns instances of the given state with dummy indices appended Operates in two different modes: 1. Two arguments are passed to it. The first is the base state which is to be indexed, and the second argument is a list of indices to append. 2. Three arguments are passed. The first is again the base state to be indexed. The second is the start index for counting. The final argument is the number of kets you wish to receive. Tries to call state._enumerate_state. If this fails, returns an empty list Parameters ========== args : list See list of operation modes above for explanation Examples ======== >>> from sympy.physics.quantum.cartesian import XBra, XKet >>> from sympy.physics.quantum.represent import enumerate_states >>> test = XKet('foo') >>> enumerate_states(test, 1, 3) [|foo_1>, |foo_2>, |foo_3>] >>> test2 = XBra('bar') >>> enumerate_states(test2, [4, 5, 10]) [<bar_4|, <bar_5|, <bar_10|] """ state = args[0] if not (len(args) == 2 or len(args) == 3): raise NotImplementedError("Wrong number of arguments!") if not isinstance(state, StateBase): raise TypeError("First argument is not a state!") if len(args) == 3: num_states = args[2] options['start_index'] = args[1] else: num_states = len(args[1]) options['index_list'] = args[1] try: ret = state._enumerate_state(num_states, **options) except NotImplementedError: ret = [] return ret
f831d166c6a3df841cdc4c602e7f5fa4d87a48a230e8b1a506539b58bb0211e8
from __future__ import print_function, division from sympy import Expr, sympify, Symbol, Matrix from sympy.printing.pretty.stringpict import prettyForm from sympy.core.containers import Tuple from sympy.core.compatibility import is_sequence from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.matrixutils import ( numpy_ndarray, scipy_sparse_matrix, to_sympy, to_numpy, to_scipy_sparse ) __all__ = [ 'QuantumError', 'QExpr' ] #----------------------------------------------------------------------------- # Error handling #----------------------------------------------------------------------------- class QuantumError(Exception): pass def _qsympify_sequence(seq): """Convert elements of a sequence to standard form. This is like sympify, but it performs special logic for arguments passed to QExpr. The following conversions are done: * (list, tuple, Tuple) => _qsympify_sequence each element and convert sequence to a Tuple. * basestring => Symbol * Matrix => Matrix * other => sympify Strings are passed to Symbol, not sympify to make sure that variables like 'pi' are kept as Symbols, not the SymPy built-in number subclasses. Examples ======== >>> from sympy.physics.quantum.qexpr import _qsympify_sequence >>> _qsympify_sequence((1,2,[3,4,[1,]])) (1, 2, (3, 4, (1,))) """ return tuple(__qsympify_sequence_helper(seq)) def __qsympify_sequence_helper(seq): """ Helper function for _qsympify_sequence This function does the actual work. """ #base case. If not a list, do Sympification if not is_sequence(seq): if isinstance(seq, Matrix): return seq elif isinstance(seq, str): return Symbol(seq) else: return sympify(seq) # base condition, when seq is QExpr and also # is iterable. if isinstance(seq, QExpr): return seq #if list, recurse on each item in the list result = [__qsympify_sequence_helper(item) for item in seq] return Tuple(*result) #----------------------------------------------------------------------------- # Basic Quantum Expression from which all objects descend #----------------------------------------------------------------------------- class QExpr(Expr): """A base class for all quantum object like operators and states.""" # In sympy, slots are for instance attributes that are computed # dynamically by the __new__ method. They are not part of args, but they # derive from args. # The Hilbert space a quantum Object belongs to. __slots__ = ('hilbert_space') is_commutative = False # The separator used in printing the label. _label_separator = u'' @property def free_symbols(self): return {self} def __new__(cls, *args, **kwargs): """Construct a new quantum object. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the quantum object. For a state, this will be its symbol or its set of quantum numbers. Examples ======== >>> from sympy.physics.quantum.qexpr import QExpr >>> q = QExpr(0) >>> q 0 >>> q.label (0,) >>> q.hilbert_space H >>> q.args (0,) >>> q.is_commutative False """ # First compute args and call Expr.__new__ to create the instance args = cls._eval_args(args, **kwargs) if len(args) == 0: args = cls._eval_args(tuple(cls.default_args()), **kwargs) inst = Expr.__new__(cls, *args) # Now set the slots on the instance inst.hilbert_space = cls._eval_hilbert_space(args) return inst @classmethod def _new_rawargs(cls, hilbert_space, *args, **old_assumptions): """Create new instance of this class with hilbert_space and args. This is used to bypass the more complex logic in the ``__new__`` method in cases where you already have the exact ``hilbert_space`` and ``args``. This should be used when you are positive these arguments are valid, in their final, proper form and want to optimize the creation of the object. """ obj = Expr.__new__(cls, *args, **old_assumptions) obj.hilbert_space = hilbert_space return obj #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def label(self): """The label is the unique set of identifiers for the object. Usually, this will include all of the information about the state *except* the time (in the case of time-dependent objects). This must be a tuple, rather than a Tuple. """ if len(self.args) == 0: # If there is no label specified, return the default return self._eval_args(list(self.default_args())) else: return self.args @property def is_symbolic(self): return True @classmethod def default_args(self): """If no arguments are specified, then this will return a default set of arguments to be run through the constructor. NOTE: Any classes that override this MUST return a tuple of arguments. Should be overridden by subclasses to specify the default arguments for kets and operators """ raise NotImplementedError("No default arguments for this class!") #------------------------------------------------------------------------- # _eval_* methods #------------------------------------------------------------------------- def _eval_adjoint(self): obj = Expr._eval_adjoint(self) if obj is None: obj = Expr.__new__(Dagger, self) if isinstance(obj, QExpr): obj.hilbert_space = self.hilbert_space return obj @classmethod def _eval_args(cls, args): """Process the args passed to the __new__ method. This simply runs args through _qsympify_sequence. """ return _qsympify_sequence(args) @classmethod def _eval_hilbert_space(cls, args): """Compute the Hilbert space instance from the args. """ from sympy.physics.quantum.hilbert import HilbertSpace return HilbertSpace() #------------------------------------------------------------------------- # Printing #------------------------------------------------------------------------- # Utilities for printing: these operate on raw sympy objects def _print_sequence(self, seq, sep, printer, *args): result = [] for item in seq: result.append(printer._print(item, *args)) return sep.join(result) def _print_sequence_pretty(self, seq, sep, printer, *args): pform = printer._print(seq[0], *args) for item in seq[1:]: pform = prettyForm(*pform.right((sep))) pform = prettyForm(*pform.right((printer._print(item, *args)))) return pform # Utilities for printing: these operate prettyForm objects def _print_subscript_pretty(self, a, b): top = prettyForm(*b.left(' '*a.width())) bot = prettyForm(*a.right(' '*b.width())) return prettyForm(binding=prettyForm.POW, *bot.below(top)) def _print_superscript_pretty(self, a, b): return a**b def _print_parens_pretty(self, pform, left='(', right=')'): return prettyForm(*pform.parens(left=left, right=right)) # Printing of labels (i.e. args) def _print_label(self, printer, *args): """Prints the label of the QExpr This method prints self.label, using self._label_separator to separate the elements. This method should not be overridden, instead, override _print_contents to change printing behavior. """ return self._print_sequence( self.label, self._label_separator, printer, *args ) def _print_label_repr(self, printer, *args): return self._print_sequence( self.label, ',', printer, *args ) def _print_label_pretty(self, printer, *args): return self._print_sequence_pretty( self.label, self._label_separator, printer, *args ) def _print_label_latex(self, printer, *args): return self._print_sequence( self.label, self._label_separator, printer, *args ) # Printing of contents (default to label) def _print_contents(self, printer, *args): """Printer for contents of QExpr Handles the printing of any unique identifying contents of a QExpr to print as its contents, such as any variables or quantum numbers. The default is to print the label, which is almost always the args. This should not include printing of any brackets or parenteses. """ return self._print_label(printer, *args) def _print_contents_pretty(self, printer, *args): return self._print_label_pretty(printer, *args) def _print_contents_latex(self, printer, *args): return self._print_label_latex(printer, *args) # Main printing methods def _sympystr(self, printer, *args): """Default printing behavior of QExpr objects Handles the default printing of a QExpr. To add other things to the printing of the object, such as an operator name to operators or brackets to states, the class should override the _print/_pretty/_latex functions directly and make calls to _print_contents where appropriate. This allows things like InnerProduct to easily control its printing the printing of contents. """ return self._print_contents(printer, *args) def _sympyrepr(self, printer, *args): classname = self.__class__.__name__ label = self._print_label_repr(printer, *args) return '%s(%s)' % (classname, label) def _pretty(self, printer, *args): pform = self._print_contents_pretty(printer, *args) return pform def _latex(self, printer, *args): return self._print_contents_latex(printer, *args) #------------------------------------------------------------------------- # Methods from Basic and Expr #------------------------------------------------------------------------- def doit(self, **kw_args): return self #------------------------------------------------------------------------- # Represent #------------------------------------------------------------------------- def _represent_default_basis(self, **options): raise NotImplementedError('This object does not have a default basis') def _represent(self, *, basis=None, **options): """Represent this object in a given basis. This method dispatches to the actual methods that perform the representation. Subclases of QExpr should define various methods to determine how the object will be represented in various bases. The format of these methods is:: def _represent_BasisName(self, basis, **options): Thus to define how a quantum object is represented in the basis of the operator Position, you would define:: def _represent_Position(self, basis, **options): Usually, basis object will be instances of Operator subclasses, but there is a chance we will relax this in the future to accommodate other types of basis sets that are not associated with an operator. If the ``format`` option is given it can be ("sympy", "numpy", "scipy.sparse"). This will ensure that any matrices that result from representing the object are returned in the appropriate matrix format. Parameters ========== basis : Operator The Operator whose basis functions will be used as the basis for representation. options : dict A dictionary of key/value pairs that give options and hints for the representation, such as the number of basis functions to be used. """ if basis is None: result = self._represent_default_basis(**options) else: result = dispatch_method(self, '_represent', basis, **options) # If we get a matrix representation, convert it to the right format. format = options.get('format', 'sympy') result = self._format_represent(result, format) return result def _format_represent(self, result, format): if format == 'sympy' and not isinstance(result, Matrix): return to_sympy(result) elif format == 'numpy' and not isinstance(result, numpy_ndarray): return to_numpy(result) elif format == 'scipy.sparse' and \ not isinstance(result, scipy_sparse_matrix): return to_scipy_sparse(result) return result def split_commutative_parts(e): """Split into commutative and non-commutative parts.""" c_part, nc_part = e.args_cnc() c_part = list(c_part) return c_part, nc_part def split_qexpr_parts(e): """Split an expression into Expr and noncommutative QExpr parts.""" expr_part = [] qexpr_part = [] for arg in e.args: if not isinstance(arg, QExpr): expr_part.append(arg) else: qexpr_part.append(arg) return expr_part, qexpr_part def dispatch_method(self, basename, arg, **options): """Dispatch a method to the proper handlers.""" method_name = '%s_%s' % (basename, arg.__class__.__name__) if hasattr(self, method_name): f = getattr(self, method_name) # This can raise and we will allow it to propagate. result = f(arg, **options) if result is not None: return result raise NotImplementedError( "%s.%s can't handle: %r" % (self.__class__.__name__, basename, arg) )
4061c526078967aee5682b35dd584a80ec57bde82c59a7603a9a39a4176a2d92
"""Grover's algorithm and helper functions. Todo: * W gate construction (or perhaps -W gate based on Mermin's book) * Generalize the algorithm for an unknown function that returns 1 on multiple qubit states, not just one. * Implement _represent_ZGate in OracleGate """ from __future__ import print_function, division from sympy import floor, pi, sqrt, sympify, eye from sympy.core.numbers import NegativeOne from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.operator import UnitaryOperator from sympy.physics.quantum.gate import Gate from sympy.physics.quantum.qubit import IntQubit __all__ = [ 'OracleGate', 'WGate', 'superposition_basis', 'grover_iteration', 'apply_grover' ] def superposition_basis(nqubits): """Creates an equal superposition of the computational basis. Parameters ========== nqubits : int The number of qubits. Returns ======= state : Qubit An equal superposition of the computational basis with nqubits. Examples ======== Create an equal superposition of 2 qubits:: >>> from sympy.physics.quantum.grover import superposition_basis >>> superposition_basis(2) |0>/2 + |1>/2 + |2>/2 + |3>/2 """ amp = 1/sqrt(2**nqubits) return sum([amp*IntQubit(n, nqubits=nqubits) for n in range(2**nqubits)]) class OracleGate(Gate): """A black box gate. The gate marks the desired qubits of an unknown function by flipping the sign of the qubits. The unknown function returns true when it finds its desired qubits and false otherwise. Parameters ========== qubits : int Number of qubits. oracle : callable A callable function that returns a boolean on a computational basis. Examples ======== Apply an Oracle gate that flips the sign of ``|2>`` on different qubits:: >>> from sympy.physics.quantum.qubit import IntQubit >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.grover import OracleGate >>> f = lambda qubits: qubits == IntQubit(2) >>> v = OracleGate(2, f) >>> qapply(v*IntQubit(2)) -|2> >>> qapply(v*IntQubit(3)) |3> """ gate_name = 'V' gate_name_latex = 'V' #------------------------------------------------------------------------- # Initialization/creation #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): # TODO: args[1] is not a subclass of Basic if len(args) != 2: raise QuantumError( 'Insufficient/excessive arguments to Oracle. Please ' + 'supply the number of qubits and an unknown function.' ) sub_args = (args[0],) sub_args = UnitaryOperator._eval_args(sub_args) if not sub_args[0].is_Integer: raise TypeError('Integer expected, got: %r' % sub_args[0]) if not callable(args[1]): raise TypeError('Callable expected, got: %r' % args[1]) return (sub_args[0], args[1]) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**args[0] #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def search_function(self): """The unknown function that helps find the sought after qubits.""" return self.label[1] @property def targets(self): """A tuple of target qubits.""" return sympify(tuple(range(self.args[0]))) #------------------------------------------------------------------------- # Apply #------------------------------------------------------------------------- def _apply_operator_Qubit(self, qubits, **options): """Apply this operator to a Qubit subclass. Parameters ========== qubits : Qubit The qubit subclass to apply this operator to. Returns ======= state : Expr The resulting quantum state. """ if qubits.nqubits != self.nqubits: raise QuantumError( 'OracleGate operates on %r qubits, got: %r' % (self.nqubits, qubits.nqubits) ) # If function returns 1 on qubits # return the negative of the qubits (flip the sign) if self.search_function(qubits): return -qubits else: return qubits #------------------------------------------------------------------------- # Represent #------------------------------------------------------------------------- def _represent_ZGate(self, basis, **options): """ Represent the OracleGate in the computational basis. """ nbasis = 2**self.nqubits # compute it only once matrixOracle = eye(nbasis) # Flip the sign given the output of the oracle function for i in range(nbasis): if self.search_function(IntQubit(i, nqubits=self.nqubits)): matrixOracle[i, i] = NegativeOne() return matrixOracle class WGate(Gate): """General n qubit W Gate in Grover's algorithm. The gate performs the operation ``2|phi><phi| - 1`` on some qubits. ``|phi> = (tensor product of n Hadamards)*(|0> with n qubits)`` Parameters ========== nqubits : int The number of qubits to operate on """ gate_name = 'W' gate_name_latex = 'W' @classmethod def _eval_args(cls, args): if len(args) != 1: raise QuantumError( 'Insufficient/excessive arguments to W gate. Please ' + 'supply the number of qubits to operate on.' ) args = UnitaryOperator._eval_args(args) if not args[0].is_Integer: raise TypeError('Integer expected, got: %r' % args[0]) return args #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def targets(self): return sympify(tuple(reversed(range(self.args[0])))) #------------------------------------------------------------------------- # Apply #------------------------------------------------------------------------- def _apply_operator_Qubit(self, qubits, **options): """ qubits: a set of qubits (Qubit) Returns: quantum object (quantum expression - QExpr) """ if qubits.nqubits != self.nqubits: raise QuantumError( 'WGate operates on %r qubits, got: %r' % (self.nqubits, qubits.nqubits) ) # See 'Quantum Computer Science' by David Mermin p.92 -> W|a> result # Return (2/(sqrt(2^n)))|phi> - |a> where |a> is the current basis # state and phi is the superposition of basis states (see function # create_computational_basis above) basis_states = superposition_basis(self.nqubits) change_to_basis = (2/sqrt(2**self.nqubits))*basis_states return change_to_basis - qubits def grover_iteration(qstate, oracle): """Applies one application of the Oracle and W Gate, WV. Parameters ========== qstate : Qubit A superposition of qubits. oracle : OracleGate The black box operator that flips the sign of the desired basis qubits. Returns ======= Qubit : The qubits after applying the Oracle and W gate. Examples ======== Perform one iteration of grover's algorithm to see a phase change:: >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.qubit import IntQubit >>> from sympy.physics.quantum.grover import OracleGate >>> from sympy.physics.quantum.grover import superposition_basis >>> from sympy.physics.quantum.grover import grover_iteration >>> numqubits = 2 >>> basis_states = superposition_basis(numqubits) >>> f = lambda qubits: qubits == IntQubit(2) >>> v = OracleGate(numqubits, f) >>> qapply(grover_iteration(basis_states, v)) |2> """ wgate = WGate(oracle.nqubits) return wgate*oracle*qstate def apply_grover(oracle, nqubits, iterations=None): """Applies grover's algorithm. Parameters ========== oracle : callable The unknown callable function that returns true when applied to the desired qubits and false otherwise. Returns ======= state : Expr The resulting state after Grover's algorithm has been iterated. Examples ======== Apply grover's algorithm to an even superposition of 2 qubits:: >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.qubit import IntQubit >>> from sympy.physics.quantum.grover import apply_grover >>> f = lambda qubits: qubits == IntQubit(2) >>> qapply(apply_grover(f, 2)) |2> """ if nqubits <= 0: raise QuantumError( 'Grover\'s algorithm needs nqubits > 0, received %r qubits' % nqubits ) if iterations is None: iterations = floor(sqrt(2**nqubits)*(pi/4)) v = OracleGate(nqubits, oracle) iterated = superposition_basis(nqubits) for iter in range(iterations): iterated = grover_iteration(iterated, v) iterated = qapply(iterated) return iterated
01cca235073eccdad8080d60bb4d7f0ab76e9252f0ee21ce2b9ac164061bf28b
"""The commutator: [A,B] = A*B - B*A.""" from __future__ import print_function, division from sympy import S, Expr, Mul, Add, Pow from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.operator import Operator __all__ = [ 'Commutator' ] #----------------------------------------------------------------------------- # Commutator #----------------------------------------------------------------------------- class Commutator(Expr): """The standard commutator, in an unevaluated state. Evaluating a commutator is defined [1]_ as: ``[A, B] = A*B - B*A``. This class returns the commutator in an unevaluated form. To evaluate the commutator, use the ``.doit()`` method. Canonical ordering of a commutator is ``[A, B]`` for ``A < B``. The arguments of the commutator are put into canonical order using ``__cmp__``. If ``B < A``, then ``[B, A]`` is returned as ``-[A, B]``. Parameters ========== A : Expr The first argument of the commutator [A,B]. B : Expr The second argument of the commutator [A,B]. Examples ======== >>> from sympy.physics.quantum import Commutator, Dagger, Operator >>> from sympy.abc import x, y >>> A = Operator('A') >>> B = Operator('B') >>> C = Operator('C') Create a commutator and use ``.doit()`` to evaluate it: >>> comm = Commutator(A, B) >>> comm [A,B] >>> comm.doit() A*B - B*A The commutator orders it arguments in canonical order: >>> comm = Commutator(B, A); comm -[A,B] Commutative constants are factored out: >>> Commutator(3*x*A, x*y*B) 3*x**2*y*[A,B] Using ``.expand(commutator=True)``, the standard commutator expansion rules can be applied: >>> Commutator(A+B, C).expand(commutator=True) [A,C] + [B,C] >>> Commutator(A, B+C).expand(commutator=True) [A,B] + [A,C] >>> Commutator(A*B, C).expand(commutator=True) [A,C]*B + A*[B,C] >>> Commutator(A, B*C).expand(commutator=True) [A,B]*C + B*[A,C] Adjoint operations applied to the commutator are properly applied to the arguments: >>> Dagger(Commutator(A, B)) -[Dagger(A),Dagger(B)] References ========== .. [1] https://en.wikipedia.org/wiki/Commutator """ is_commutative = False def __new__(cls, A, B): r = cls.eval(A, B) if r is not None: return r obj = Expr.__new__(cls, A, B) return obj @classmethod def eval(cls, a, b): if not (a and b): return S.Zero if a == b: return S.Zero if a.is_commutative or b.is_commutative: return S.Zero # [xA,yB] -> xy*[A,B] ca, nca = a.args_cnc() cb, ncb = b.args_cnc() c_part = ca + cb if c_part: return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb))) # Canonical ordering of arguments # The Commutator [A, B] is in canonical form if A < B. if a.compare(b) == 1: return S.NegativeOne*cls(b, a) def _expand_pow(self, A, B, sign): exp = A.exp if not exp.is_integer or not exp.is_constant() or abs(exp) <= 1: # nothing to do return self base = A.base if exp.is_negative: base = A.base**-1 exp = -exp comm = Commutator(base, B).expand(commutator=True) result = base**(exp - 1) * comm for i in range(1, exp): result += base**(exp - 1 - i) * comm * base**i return sign*result.expand() def _eval_expand_commutator(self, **hints): A = self.args[0] B = self.args[1] if isinstance(A, Add): # [A + B, C] -> [A, C] + [B, C] sargs = [] for term in A.args: comm = Commutator(term, B) if isinstance(comm, Commutator): comm = comm._eval_expand_commutator() sargs.append(comm) return Add(*sargs) elif isinstance(B, Add): # [A, B + C] -> [A, B] + [A, C] sargs = [] for term in B.args: comm = Commutator(A, term) if isinstance(comm, Commutator): comm = comm._eval_expand_commutator() sargs.append(comm) return Add(*sargs) elif isinstance(A, Mul): # [A*B, C] -> A*[B, C] + [A, C]*B a = A.args[0] b = Mul(*A.args[1:]) c = B comm1 = Commutator(b, c) comm2 = Commutator(a, c) if isinstance(comm1, Commutator): comm1 = comm1._eval_expand_commutator() if isinstance(comm2, Commutator): comm2 = comm2._eval_expand_commutator() first = Mul(a, comm1) second = Mul(comm2, b) return Add(first, second) elif isinstance(B, Mul): # [A, B*C] -> [A, B]*C + B*[A, C] a = A b = B.args[0] c = Mul(*B.args[1:]) comm1 = Commutator(a, b) comm2 = Commutator(a, c) if isinstance(comm1, Commutator): comm1 = comm1._eval_expand_commutator() if isinstance(comm2, Commutator): comm2 = comm2._eval_expand_commutator() first = Mul(comm1, c) second = Mul(b, comm2) return Add(first, second) elif isinstance(A, Pow): # [A**n, C] -> A**(n - 1)*[A, C] + A**(n - 2)*[A, C]*A + ... + [A, C]*A**(n-1) return self._expand_pow(A, B, 1) elif isinstance(B, Pow): # [A, C**n] -> C**(n - 1)*[C, A] + C**(n - 2)*[C, A]*C + ... + [C, A]*C**(n-1) return self._expand_pow(B, A, -1) # No changes, so return self return self def doit(self, **hints): """ Evaluate commutator """ A = self.args[0] B = self.args[1] if isinstance(A, Operator) and isinstance(B, Operator): try: comm = A._eval_commutator(B, **hints) except NotImplementedError: try: comm = -1*B._eval_commutator(A, **hints) except NotImplementedError: comm = None if comm is not None: return comm.doit(**hints) return (A*B - B*A).doit(**hints) def _eval_adjoint(self): return Commutator(Dagger(self.args[1]), Dagger(self.args[0])) def _sympyrepr(self, printer, *args): return "%s(%s,%s)" % ( self.__class__.__name__, printer._print( self.args[0]), printer._print(self.args[1]) ) def _sympystr(self, printer, *args): return "[%s,%s]" % ( printer._print(self.args[0]), printer._print(self.args[1])) def _pretty(self, printer, *args): pform = printer._print(self.args[0], *args) pform = prettyForm(*pform.right((prettyForm(',')))) pform = prettyForm(*pform.right((printer._print(self.args[1], *args)))) pform = prettyForm(*pform.parens(left='[', right=']')) return pform def _latex(self, printer, *args): return "\\left[%s,%s\\right]" % tuple([ printer._print(arg, *args) for arg in self.args])
c47bfbb0c6eccb654550121c3bba57f5a8520a19a64ad18a7754fcbd25a3e980
"""Quantum mechanical angular momemtum.""" from __future__ import print_function, division from sympy import (Add, binomial, cos, exp, Expr, factorial, I, Integer, Mul, pi, Rational, S, sin, simplify, sqrt, Sum, symbols, sympify, Tuple, Dummy) from sympy.matrices import zeros from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.printing.pretty.pretty_symbology import pretty_symbol from sympy.physics.quantum.qexpr import QExpr from sympy.physics.quantum.operator import (HermitianOperator, Operator, UnitaryOperator) from sympy.physics.quantum.state import Bra, Ket, State from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.physics.quantum.constants import hbar from sympy.physics.quantum.hilbert import ComplexSpace, DirectSumHilbertSpace from sympy.physics.quantum.tensorproduct import TensorProduct from sympy.physics.quantum.cg import CG from sympy.physics.quantum.qapply import qapply __all__ = [ 'm_values', 'Jplus', 'Jminus', 'Jx', 'Jy', 'Jz', 'J2', 'Rotation', 'WignerD', 'JxKet', 'JxBra', 'JyKet', 'JyBra', 'JzKet', 'JzBra', 'JzOp', 'J2Op', 'JxKetCoupled', 'JxBraCoupled', 'JyKetCoupled', 'JyBraCoupled', 'JzKetCoupled', 'JzBraCoupled', 'couple', 'uncouple' ] def m_values(j): j = sympify(j) size = 2*j + 1 if not size.is_Integer or not size > 0: raise ValueError( 'Only integer or half-integer values allowed for j, got: : %r' % j ) return size, [j - i for i in range(int(2*j + 1))] #----------------------------------------------------------------------------- # Spin Operators #----------------------------------------------------------------------------- class SpinOpBase(object): """Base class for spin operators.""" @classmethod def _eval_hilbert_space(cls, label): # We consider all j values so our space is infinite. return ComplexSpace(S.Infinity) @property def name(self): return self.args[0] def _print_contents(self, printer, *args): return '%s%s' % (self.name, self._coord) def _print_contents_pretty(self, printer, *args): a = stringPict(str(self.name)) b = stringPict(self._coord) return self._print_subscript_pretty(a, b) def _print_contents_latex(self, printer, *args): return r'%s_%s' % ((self.name, self._coord)) def _represent_base(self, basis, **options): j = options.get('j', S.Half) size, mvals = m_values(j) result = zeros(size, size) for p in range(size): for q in range(size): me = self.matrix_element(j, mvals[p], j, mvals[q]) result[p, q] = me return result def _apply_op(self, ket, orig_basis, **options): state = ket.rewrite(self.basis) # If the state has only one term if isinstance(state, State): ret = (hbar*state.m)*state # state is a linear combination of states elif isinstance(state, Sum): ret = self._apply_operator_Sum(state, **options) else: ret = qapply(self*state) if ret == self*state: raise NotImplementedError return ret.rewrite(orig_basis) def _apply_operator_JxKet(self, ket, **options): return self._apply_op(ket, 'Jx', **options) def _apply_operator_JxKetCoupled(self, ket, **options): return self._apply_op(ket, 'Jx', **options) def _apply_operator_JyKet(self, ket, **options): return self._apply_op(ket, 'Jy', **options) def _apply_operator_JyKetCoupled(self, ket, **options): return self._apply_op(ket, 'Jy', **options) def _apply_operator_JzKet(self, ket, **options): return self._apply_op(ket, 'Jz', **options) def _apply_operator_JzKetCoupled(self, ket, **options): return self._apply_op(ket, 'Jz', **options) def _apply_operator_TensorProduct(self, tp, **options): # Uncoupling operator is only easily found for coordinate basis spin operators # TODO: add methods for uncoupling operators if not (isinstance(self, JxOp) or isinstance(self, JyOp) or isinstance(self, JzOp)): raise NotImplementedError result = [] for n in range(len(tp.args)): arg = [] arg.extend(tp.args[:n]) arg.append(self._apply_operator(tp.args[n])) arg.extend(tp.args[n + 1:]) result.append(tp.__class__(*arg)) return Add(*result).expand() # TODO: move this to qapply_Mul def _apply_operator_Sum(self, s, **options): new_func = qapply(self*s.function) if new_func == self*s.function: raise NotImplementedError return Sum(new_func, *s.limits) def _eval_trace(self, **options): #TODO: use options to use different j values #For now eval at default basis # is it efficient to represent each time # to do a trace? return self._represent_default_basis().trace() class JplusOp(SpinOpBase, Operator): """The J+ operator.""" _coord = '+' basis = 'Jz' def _eval_commutator_JminusOp(self, other): return 2*hbar*JzOp(self.name) def _apply_operator_JzKet(self, ket, **options): j = ket.j m = ket.m if m.is_Number and j.is_Number: if m >= j: return S.Zero return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKet(j, m + S.One) def _apply_operator_JzKetCoupled(self, ket, **options): j = ket.j m = ket.m jn = ket.jn coupling = ket.coupling if m.is_Number and j.is_Number: if m >= j: return S.Zero return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKetCoupled(j, m + S.One, jn, coupling) def matrix_element(self, j, m, jp, mp): result = hbar*sqrt(j*(j + S.One) - mp*(mp + S.One)) result *= KroneckerDelta(m, mp + 1) result *= KroneckerDelta(j, jp) return result def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(basis, **options) def _eval_rewrite_as_xyz(self, *args, **kwargs): return JxOp(args[0]) + I*JyOp(args[0]) class JminusOp(SpinOpBase, Operator): """The J- operator.""" _coord = '-' basis = 'Jz' def _apply_operator_JzKet(self, ket, **options): j = ket.j m = ket.m if m.is_Number and j.is_Number: if m <= -j: return S.Zero return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKet(j, m - S.One) def _apply_operator_JzKetCoupled(self, ket, **options): j = ket.j m = ket.m jn = ket.jn coupling = ket.coupling if m.is_Number and j.is_Number: if m <= -j: return S.Zero return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKetCoupled(j, m - S.One, jn, coupling) def matrix_element(self, j, m, jp, mp): result = hbar*sqrt(j*(j + S.One) - mp*(mp - S.One)) result *= KroneckerDelta(m, mp - 1) result *= KroneckerDelta(j, jp) return result def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(basis, **options) def _eval_rewrite_as_xyz(self, *args, **kwargs): return JxOp(args[0]) - I*JyOp(args[0]) class JxOp(SpinOpBase, HermitianOperator): """The Jx operator.""" _coord = 'x' basis = 'Jx' def _eval_commutator_JyOp(self, other): return I*hbar*JzOp(self.name) def _eval_commutator_JzOp(self, other): return -I*hbar*JyOp(self.name) def _apply_operator_JzKet(self, ket, **options): jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options) jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options) return (jp + jm)/Integer(2) def _apply_operator_JzKetCoupled(self, ket, **options): jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options) jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options) return (jp + jm)/Integer(2) def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): jp = JplusOp(self.name)._represent_JzOp(basis, **options) jm = JminusOp(self.name)._represent_JzOp(basis, **options) return (jp + jm)/Integer(2) def _eval_rewrite_as_plusminus(self, *args, **kwargs): return (JplusOp(args[0]) + JminusOp(args[0]))/2 class JyOp(SpinOpBase, HermitianOperator): """The Jy operator.""" _coord = 'y' basis = 'Jy' def _eval_commutator_JzOp(self, other): return I*hbar*JxOp(self.name) def _eval_commutator_JxOp(self, other): return -I*hbar*J2Op(self.name) def _apply_operator_JzKet(self, ket, **options): jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options) jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options) return (jp - jm)/(Integer(2)*I) def _apply_operator_JzKetCoupled(self, ket, **options): jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options) jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options) return (jp - jm)/(Integer(2)*I) def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): jp = JplusOp(self.name)._represent_JzOp(basis, **options) jm = JminusOp(self.name)._represent_JzOp(basis, **options) return (jp - jm)/(Integer(2)*I) def _eval_rewrite_as_plusminus(self, *args, **kwargs): return (JplusOp(args[0]) - JminusOp(args[0]))/(2*I) class JzOp(SpinOpBase, HermitianOperator): """The Jz operator.""" _coord = 'z' basis = 'Jz' def _eval_commutator_JxOp(self, other): return I*hbar*JyOp(self.name) def _eval_commutator_JyOp(self, other): return -I*hbar*JxOp(self.name) def _eval_commutator_JplusOp(self, other): return hbar*JplusOp(self.name) def _eval_commutator_JminusOp(self, other): return -hbar*JminusOp(self.name) def matrix_element(self, j, m, jp, mp): result = hbar*mp result *= KroneckerDelta(m, mp) result *= KroneckerDelta(j, jp) return result def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(basis, **options) class J2Op(SpinOpBase, HermitianOperator): """The J^2 operator.""" _coord = '2' def _eval_commutator_JxOp(self, other): return S.Zero def _eval_commutator_JyOp(self, other): return S.Zero def _eval_commutator_JzOp(self, other): return S.Zero def _eval_commutator_JplusOp(self, other): return S.Zero def _eval_commutator_JminusOp(self, other): return S.Zero def _apply_operator_JxKet(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def _apply_operator_JxKetCoupled(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def _apply_operator_JyKet(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def _apply_operator_JyKetCoupled(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def _apply_operator_JzKet(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def _apply_operator_JzKetCoupled(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def matrix_element(self, j, m, jp, mp): result = (hbar**2)*j*(j + 1) result *= KroneckerDelta(m, mp) result *= KroneckerDelta(j, jp) return result def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(basis, **options) def _print_contents_pretty(self, printer, *args): a = prettyForm(str(self.name)) b = prettyForm('2') return a**b def _print_contents_latex(self, printer, *args): return r'%s^2' % str(self.name) def _eval_rewrite_as_xyz(self, *args, **kwargs): return JxOp(args[0])**2 + JyOp(args[0])**2 + JzOp(args[0])**2 def _eval_rewrite_as_plusminus(self, *args, **kwargs): a = args[0] return JzOp(a)**2 + \ S.Half*(JplusOp(a)*JminusOp(a) + JminusOp(a)*JplusOp(a)) class Rotation(UnitaryOperator): """Wigner D operator in terms of Euler angles. Defines the rotation operator in terms of the Euler angles defined by the z-y-z convention for a passive transformation. That is the coordinate axes are rotated first about the z-axis, giving the new x'-y'-z' axes. Then this new coordinate system is rotated about the new y'-axis, giving new x''-y''-z'' axes. Then this new coordinate system is rotated about the z''-axis. Conventions follow those laid out in [1]_. Parameters ========== alpha : Number, Symbol First Euler Angle beta : Number, Symbol Second Euler angle gamma : Number, Symbol Third Euler angle Examples ======== A simple example rotation operator: >>> from sympy import pi >>> from sympy.physics.quantum.spin import Rotation >>> Rotation(pi, 0, pi/2) R(pi,0,pi/2) With symbolic Euler angles and calculating the inverse rotation operator: >>> from sympy import symbols >>> a, b, c = symbols('a b c') >>> Rotation(a, b, c) R(a,b,c) >>> Rotation(a, b, c).inverse() R(-c,-b,-a) See Also ======== WignerD: Symbolic Wigner-D function D: Wigner-D function d: Wigner small-d function References ========== .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988. """ @classmethod def _eval_args(cls, args): args = QExpr._eval_args(args) if len(args) != 3: raise ValueError('3 Euler angles required, got: %r' % args) return args @classmethod def _eval_hilbert_space(cls, label): # We consider all j values so our space is infinite. return ComplexSpace(S.Infinity) @property def alpha(self): return self.label[0] @property def beta(self): return self.label[1] @property def gamma(self): return self.label[2] def _print_operator_name(self, printer, *args): return 'R' def _print_operator_name_pretty(self, printer, *args): if printer._use_unicode: return prettyForm('\N{SCRIPT CAPITAL R}' + ' ') else: return prettyForm("R ") def _print_operator_name_latex(self, printer, *args): return r'\mathcal{R}' def _eval_inverse(self): return Rotation(-self.gamma, -self.beta, -self.alpha) @classmethod def D(cls, j, m, mp, alpha, beta, gamma): """Wigner D-function. Returns an instance of the WignerD class corresponding to the Wigner-D function specified by the parameters. Parameters =========== j : Number Total angular momentum m : Number Eigenvalue of angular momentum along axis after rotation mp : Number Eigenvalue of angular momentum along rotated axis alpha : Number, Symbol First Euler angle of rotation beta : Number, Symbol Second Euler angle of rotation gamma : Number, Symbol Third Euler angle of rotation Examples ======== Return the Wigner-D matrix element for a defined rotation, both numerical and symbolic: >>> from sympy.physics.quantum.spin import Rotation >>> from sympy import pi, symbols >>> alpha, beta, gamma = symbols('alpha beta gamma') >>> Rotation.D(1, 1, 0,pi, pi/2,-pi) WignerD(1, 1, 0, pi, pi/2, -pi) See Also ======== WignerD: Symbolic Wigner-D function """ return WignerD(j, m, mp, alpha, beta, gamma) @classmethod def d(cls, j, m, mp, beta): """Wigner small-d function. Returns an instance of the WignerD class corresponding to the Wigner-D function specified by the parameters with the alpha and gamma angles given as 0. Parameters =========== j : Number Total angular momentum m : Number Eigenvalue of angular momentum along axis after rotation mp : Number Eigenvalue of angular momentum along rotated axis beta : Number, Symbol Second Euler angle of rotation Examples ======== Return the Wigner-D matrix element for a defined rotation, both numerical and symbolic: >>> from sympy.physics.quantum.spin import Rotation >>> from sympy import pi, symbols >>> beta = symbols('beta') >>> Rotation.d(1, 1, 0, pi/2) WignerD(1, 1, 0, 0, pi/2, 0) See Also ======== WignerD: Symbolic Wigner-D function """ return WignerD(j, m, mp, 0, beta, 0) def matrix_element(self, j, m, jp, mp): result = self.__class__.D( jp, m, mp, self.alpha, self.beta, self.gamma ) result *= KroneckerDelta(j, jp) return result def _represent_base(self, basis, **options): j = sympify(options.get('j', S.Half)) # TODO: move evaluation up to represent function/implement elsewhere evaluate = sympify(options.get('doit')) size, mvals = m_values(j) result = zeros(size, size) for p in range(size): for q in range(size): me = self.matrix_element(j, mvals[p], j, mvals[q]) if evaluate: result[p, q] = me.doit() else: result[p, q] = me return result def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(basis, **options) def _apply_operator_uncoupled(self, state, ket, *, dummy=True, **options): a = self.alpha b = self.beta g = self.gamma j = ket.j m = ket.m if j.is_number: s = [] size = m_values(j) sz = size[1] for mp in sz: r = Rotation.D(j, m, mp, a, b, g) z = r.doit() s.append(z*state(j, mp)) return Add(*s) else: if dummy: mp = Dummy('mp') else: mp = symbols('mp') return Sum(Rotation.D(j, m, mp, a, b, g)*state(j, mp), (mp, -j, j)) def _apply_operator_JxKet(self, ket, **options): return self._apply_operator_uncoupled(JxKet, ket, **options) def _apply_operator_JyKet(self, ket, **options): return self._apply_operator_uncoupled(JyKet, ket, **options) def _apply_operator_JzKet(self, ket, **options): return self._apply_operator_uncoupled(JzKet, ket, **options) def _apply_operator_coupled(self, state, ket, *, dummy=True, **options): a = self.alpha b = self.beta g = self.gamma j = ket.j m = ket.m jn = ket.jn coupling = ket.coupling if j.is_number: s = [] size = m_values(j) sz = size[1] for mp in sz: r = Rotation.D(j, m, mp, a, b, g) z = r.doit() s.append(z*state(j, mp, jn, coupling)) return Add(*s) else: if dummy: mp = Dummy('mp') else: mp = symbols('mp') return Sum(Rotation.D(j, m, mp, a, b, g)*state( j, mp, jn, coupling), (mp, -j, j)) def _apply_operator_JxKetCoupled(self, ket, **options): return self._apply_operator_coupled(JxKetCoupled, ket, **options) def _apply_operator_JyKetCoupled(self, ket, **options): return self._apply_operator_coupled(JyKetCoupled, ket, **options) def _apply_operator_JzKetCoupled(self, ket, **options): return self._apply_operator_coupled(JzKetCoupled, ket, **options) class WignerD(Expr): r"""Wigner-D function The Wigner D-function gives the matrix elements of the rotation operator in the jm-representation. For the Euler angles `\alpha`, `\beta`, `\gamma`, the D-function is defined such that: .. math :: <j,m| \mathcal{R}(\alpha, \beta, \gamma ) |j',m'> = \delta_{jj'} D(j, m, m', \alpha, \beta, \gamma) Where the rotation operator is as defined by the Rotation class [1]_. The Wigner D-function defined in this way gives: .. math :: D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma} Where d is the Wigner small-d function, which is given by Rotation.d. The Wigner small-d function gives the component of the Wigner D-function that is determined by the second Euler angle. That is the Wigner D-function is: .. math :: D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma} Where d is the small-d function. The Wigner D-function is given by Rotation.D. Note that to evaluate the D-function, the j, m and mp parameters must be integer or half integer numbers. Parameters ========== j : Number Total angular momentum m : Number Eigenvalue of angular momentum along axis after rotation mp : Number Eigenvalue of angular momentum along rotated axis alpha : Number, Symbol First Euler angle of rotation beta : Number, Symbol Second Euler angle of rotation gamma : Number, Symbol Third Euler angle of rotation Examples ======== Evaluate the Wigner-D matrix elements of a simple rotation: >>> from sympy.physics.quantum.spin import Rotation >>> from sympy import pi >>> rot = Rotation.D(1, 1, 0, pi, pi/2, 0) >>> rot WignerD(1, 1, 0, pi, pi/2, 0) >>> rot.doit() sqrt(2)/2 Evaluate the Wigner-d matrix elements of a simple rotation >>> rot = Rotation.d(1, 1, 0, pi/2) >>> rot WignerD(1, 1, 0, 0, pi/2, 0) >>> rot.doit() -sqrt(2)/2 See Also ======== Rotation: Rotation operator References ========== .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988. """ is_commutative = True def __new__(cls, *args, **hints): if not len(args) == 6: raise ValueError('6 parameters expected, got %s' % args) args = sympify(args) evaluate = hints.get('evaluate', False) if evaluate: return Expr.__new__(cls, *args)._eval_wignerd() return Expr.__new__(cls, *args) @property def j(self): return self.args[0] @property def m(self): return self.args[1] @property def mp(self): return self.args[2] @property def alpha(self): return self.args[3] @property def beta(self): return self.args[4] @property def gamma(self): return self.args[5] def _latex(self, printer, *args): if self.alpha == 0 and self.gamma == 0: return r'd^{%s}_{%s,%s}\left(%s\right)' % \ ( printer._print(self.j), printer._print( self.m), printer._print(self.mp), printer._print(self.beta) ) return r'D^{%s}_{%s,%s}\left(%s,%s,%s\right)' % \ ( printer._print( self.j), printer._print(self.m), printer._print(self.mp), printer._print(self.alpha), printer._print(self.beta), printer._print(self.gamma) ) def _pretty(self, printer, *args): top = printer._print(self.j) bot = printer._print(self.m) bot = prettyForm(*bot.right(',')) bot = prettyForm(*bot.right(printer._print(self.mp))) pad = max(top.width(), bot.width()) top = prettyForm(*top.left(' ')) bot = prettyForm(*bot.left(' ')) if pad > top.width(): top = prettyForm(*top.right(' '*(pad - top.width()))) if pad > bot.width(): bot = prettyForm(*bot.right(' '*(pad - bot.width()))) if self.alpha == 0 and self.gamma == 0: args = printer._print(self.beta) s = stringPict('d' + ' '*pad) else: args = printer._print(self.alpha) args = prettyForm(*args.right(',')) args = prettyForm(*args.right(printer._print(self.beta))) args = prettyForm(*args.right(',')) args = prettyForm(*args.right(printer._print(self.gamma))) s = stringPict('D' + ' '*pad) args = prettyForm(*args.parens()) s = prettyForm(*s.above(top)) s = prettyForm(*s.below(bot)) s = prettyForm(*s.right(args)) return s def doit(self, **hints): hints['evaluate'] = True return WignerD(*self.args, **hints) def _eval_wignerd(self): j = sympify(self.j) m = sympify(self.m) mp = sympify(self.mp) alpha = sympify(self.alpha) beta = sympify(self.beta) gamma = sympify(self.gamma) if not j.is_number: raise ValueError( 'j parameter must be numerical to evaluate, got %s' % j) r = 0 if beta == pi/2: # Varshalovich Equation (5), Section 4.16, page 113, setting # alpha=gamma=0. for k in range(2*j + 1): if k > j + mp or k > j - m or k < mp - m: continue r += (S.NegativeOne)**k*binomial(j + mp, k)*binomial(j - mp, k + m - mp) r *= (S.NegativeOne)**(m - mp) / 2**j*sqrt(factorial(j + m) * factorial(j - m) / (factorial(j + mp)*factorial(j - mp))) else: # Varshalovich Equation(5), Section 4.7.2, page 87, where we set # beta1=beta2=pi/2, and we get alpha=gamma=pi/2 and beta=phi+pi, # then we use the Eq. (1), Section 4.4. page 79, to simplify: # d(j, m, mp, beta+pi) = (-1)**(j-mp)*d(j, m, -mp, beta) # This happens to be almost the same as in Eq.(10), Section 4.16, # except that we need to substitute -mp for mp. size, mvals = m_values(j) for mpp in mvals: r += Rotation.d(j, m, mpp, pi/2).doit()*(cos(-mpp*beta) + I*sin(-mpp*beta))*\ Rotation.d(j, mpp, -mp, pi/2).doit() # Empirical normalization factor so results match Varshalovich # Tables 4.3-4.12 # Note that this exact normalization does not follow from the # above equations r = r*I**(2*j - m - mp)*(-1)**(2*m) # Finally, simplify the whole expression r = simplify(r) r *= exp(-I*m*alpha)*exp(-I*mp*gamma) return r Jx = JxOp('J') Jy = JyOp('J') Jz = JzOp('J') J2 = J2Op('J') Jplus = JplusOp('J') Jminus = JminusOp('J') #----------------------------------------------------------------------------- # Spin States #----------------------------------------------------------------------------- class SpinState(State): """Base class for angular momentum states.""" _label_separator = ',' def __new__(cls, j, m): j = sympify(j) m = sympify(m) if j.is_number: if 2*j != int(2*j): raise ValueError( 'j must be integer or half-integer, got: %s' % j) if j < 0: raise ValueError('j must be >= 0, got: %s' % j) if m.is_number: if 2*m != int(2*m): raise ValueError( 'm must be integer or half-integer, got: %s' % m) if j.is_number and m.is_number: if abs(m) > j: raise ValueError('Allowed values for m are -j <= m <= j, got j, m: %s, %s' % (j, m)) if int(j - m) != j - m: raise ValueError('Both j and m must be integer or half-integer, got j, m: %s, %s' % (j, m)) return State.__new__(cls, j, m) @property def j(self): return self.label[0] @property def m(self): return self.label[1] @classmethod def _eval_hilbert_space(cls, label): return ComplexSpace(2*label[0] + 1) def _represent_base(self, **options): j = self.j m = self.m alpha = sympify(options.get('alpha', 0)) beta = sympify(options.get('beta', 0)) gamma = sympify(options.get('gamma', 0)) size, mvals = m_values(j) result = zeros(size, 1) # TODO: Use KroneckerDelta if all Euler angles == 0 # breaks finding angles on L930 for p, mval in enumerate(mvals): if m.is_number: result[p, 0] = Rotation.D( self.j, mval, self.m, alpha, beta, gamma).doit() else: result[p, 0] = Rotation.D(self.j, mval, self.m, alpha, beta, gamma) return result def _eval_rewrite_as_Jx(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jx, JxBra, **options) return self._rewrite_basis(Jx, JxKet, **options) def _eval_rewrite_as_Jy(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jy, JyBra, **options) return self._rewrite_basis(Jy, JyKet, **options) def _eval_rewrite_as_Jz(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jz, JzBra, **options) return self._rewrite_basis(Jz, JzKet, **options) def _rewrite_basis(self, basis, evect, **options): from sympy.physics.quantum.represent import represent j = self.j args = self.args[2:] if j.is_number: if isinstance(self, CoupledSpinState): if j == int(j): start = j**2 else: start = (2*j - 1)*(2*j + 1)/4 else: start = 0 vect = represent(self, basis=basis, **options) result = Add( *[vect[start + i]*evect(j, j - i, *args) for i in range(2*j + 1)]) if isinstance(self, CoupledSpinState) and options.get('coupled') is False: return uncouple(result) return result else: i = 0 mi = symbols('mi') # make sure not to introduce a symbol already in the state while self.subs(mi, 0) != self: i += 1 mi = symbols('mi%d' % i) break # TODO: better way to get angles of rotation if isinstance(self, CoupledSpinState): test_args = (0, mi, (0, 0)) else: test_args = (0, mi) if isinstance(self, Ket): angles = represent( self.__class__(*test_args), basis=basis)[0].args[3:6] else: angles = represent(self.__class__( *test_args), basis=basis)[0].args[0].args[3:6] if angles == (0, 0, 0): return self else: state = evect(j, mi, *args) lt = Rotation.D(j, mi, self.m, *angles) return Sum(lt*state, (mi, -j, j)) def _eval_innerproduct_JxBra(self, bra, **hints): result = KroneckerDelta(self.j, bra.j) if bra.dual_class() is not self.__class__: result *= self._represent_JxOp(None)[bra.j - bra.m] else: result *= KroneckerDelta( self.j, bra.j)*KroneckerDelta(self.m, bra.m) return result def _eval_innerproduct_JyBra(self, bra, **hints): result = KroneckerDelta(self.j, bra.j) if bra.dual_class() is not self.__class__: result *= self._represent_JyOp(None)[bra.j - bra.m] else: result *= KroneckerDelta( self.j, bra.j)*KroneckerDelta(self.m, bra.m) return result def _eval_innerproduct_JzBra(self, bra, **hints): result = KroneckerDelta(self.j, bra.j) if bra.dual_class() is not self.__class__: result *= self._represent_JzOp(None)[bra.j - bra.m] else: result *= KroneckerDelta( self.j, bra.j)*KroneckerDelta(self.m, bra.m) return result def _eval_trace(self, bra, **hints): # One way to implement this method is to assume the basis set k is # passed. # Then we can apply the discrete form of Trace formula here # Tr(|i><j| ) = \Sum_k <k|i><j|k> #then we do qapply() on each each inner product and sum over them. # OR # Inner product of |i><j| = Trace(Outer Product). # we could just use this unless there are cases when this is not true return (bra*self).doit() class JxKet(SpinState, Ket): """Eigenket of Jx. See JzKet for the usage of spin eigenstates. See Also ======== JzKet: Usage of spin states """ @classmethod def dual_class(self): return JxBra @classmethod def coupled_class(self): return JxKetCoupled def _represent_default_basis(self, **options): return self._represent_JxOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_base(**options) def _represent_JyOp(self, basis, **options): return self._represent_base(alpha=pi*Rational(3, 2), **options) def _represent_JzOp(self, basis, **options): return self._represent_base(beta=pi/2, **options) class JxBra(SpinState, Bra): """Eigenbra of Jx. See JzKet for the usage of spin eigenstates. See Also ======== JzKet: Usage of spin states """ @classmethod def dual_class(self): return JxKet @classmethod def coupled_class(self): return JxBraCoupled class JyKet(SpinState, Ket): """Eigenket of Jy. See JzKet for the usage of spin eigenstates. See Also ======== JzKet: Usage of spin states """ @classmethod def dual_class(self): return JyBra @classmethod def coupled_class(self): return JyKetCoupled def _represent_default_basis(self, **options): return self._represent_JyOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_base(gamma=pi/2, **options) def _represent_JyOp(self, basis, **options): return self._represent_base(**options) def _represent_JzOp(self, basis, **options): return self._represent_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options) class JyBra(SpinState, Bra): """Eigenbra of Jy. See JzKet for the usage of spin eigenstates. See Also ======== JzKet: Usage of spin states """ @classmethod def dual_class(self): return JyKet @classmethod def coupled_class(self): return JyBraCoupled class JzKet(SpinState, Ket): """Eigenket of Jz. Spin state which is an eigenstate of the Jz operator. Uncoupled states, that is states representing the interaction of multiple separate spin states, are defined as a tensor product of states. Parameters ========== j : Number, Symbol Total spin angular momentum m : Number, Symbol Eigenvalue of the Jz spin operator Examples ======== *Normal States:* Defining simple spin states, both numerical and symbolic: >>> from sympy.physics.quantum.spin import JzKet, JxKet >>> from sympy import symbols >>> JzKet(1, 0) |1,0> >>> j, m = symbols('j m') >>> JzKet(j, m) |j,m> Rewriting the JzKet in terms of eigenkets of the Jx operator: Note: that the resulting eigenstates are JxKet's >>> JzKet(1,1).rewrite("Jx") |1,-1>/2 - sqrt(2)*|1,0>/2 + |1,1>/2 Get the vector representation of a state in terms of the basis elements of the Jx operator: >>> from sympy.physics.quantum.represent import represent >>> from sympy.physics.quantum.spin import Jx, Jz >>> represent(JzKet(1,-1), basis=Jx) Matrix([ [ 1/2], [sqrt(2)/2], [ 1/2]]) Apply innerproducts between states: >>> from sympy.physics.quantum.innerproduct import InnerProduct >>> from sympy.physics.quantum.spin import JxBra >>> i = InnerProduct(JxBra(1,1), JzKet(1,1)) >>> i <1,1|1,1> >>> i.doit() 1/2 *Uncoupled States:* Define an uncoupled state as a TensorProduct between two Jz eigenkets: >>> from sympy.physics.quantum.tensorproduct import TensorProduct >>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2') >>> TensorProduct(JzKet(1,0), JzKet(1,1)) |1,0>x|1,1> >>> TensorProduct(JzKet(j1,m1), JzKet(j2,m2)) |j1,m1>x|j2,m2> A TensorProduct can be rewritten, in which case the eigenstates that make up the tensor product is rewritten to the new basis: >>> TensorProduct(JzKet(1,1),JxKet(1,1)).rewrite('Jz') |1,1>x|1,-1>/2 + sqrt(2)*|1,1>x|1,0>/2 + |1,1>x|1,1>/2 The represent method for TensorProduct's gives the vector representation of the state. Note that the state in the product basis is the equivalent of the tensor product of the vector representation of the component eigenstates: >>> represent(TensorProduct(JzKet(1,0),JzKet(1,1))) Matrix([ [0], [0], [0], [1], [0], [0], [0], [0], [0]]) >>> represent(TensorProduct(JzKet(1,1),JxKet(1,1)), basis=Jz) Matrix([ [ 1/2], [sqrt(2)/2], [ 1/2], [ 0], [ 0], [ 0], [ 0], [ 0], [ 0]]) See Also ======== JzKetCoupled: Coupled eigenstates sympy.physics.quantum.tensorproduct.TensorProduct: Used to specify uncoupled states uncouple: Uncouples states given coupling parameters couple: Couples uncoupled states """ @classmethod def dual_class(self): return JzBra @classmethod def coupled_class(self): return JzKetCoupled def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_base(beta=pi*Rational(3, 2), **options) def _represent_JyOp(self, basis, **options): return self._represent_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(**options) class JzBra(SpinState, Bra): """Eigenbra of Jz. See the JzKet for the usage of spin eigenstates. See Also ======== JzKet: Usage of spin states """ @classmethod def dual_class(self): return JzKet @classmethod def coupled_class(self): return JzBraCoupled # Method used primarily to create coupled_n and coupled_jn by __new__ in # CoupledSpinState # This same method is also used by the uncouple method, and is separated from # the CoupledSpinState class to maintain consistency in defining coupling def _build_coupled(jcoupling, length): n_list = [ [n + 1] for n in range(length) ] coupled_jn = [] coupled_n = [] for n1, n2, j_new in jcoupling: coupled_jn.append(j_new) coupled_n.append( (n_list[n1 - 1], n_list[n2 - 1]) ) n_sort = sorted(n_list[n1 - 1] + n_list[n2 - 1]) n_list[n_sort[0] - 1] = n_sort return coupled_n, coupled_jn class CoupledSpinState(SpinState): """Base class for coupled angular momentum states.""" def __new__(cls, j, m, jn, *jcoupling): # Check j and m values using SpinState SpinState(j, m) # Build and check coupling scheme from arguments if len(jcoupling) == 0: # Use default coupling scheme jcoupling = [] for n in range(2, len(jn)): jcoupling.append( (1, n, Add(*[jn[i] for i in range(n)])) ) jcoupling.append( (1, len(jn), j) ) elif len(jcoupling) == 1: # Use specified coupling scheme jcoupling = jcoupling[0] else: raise TypeError("CoupledSpinState only takes 3 or 4 arguments, got: %s" % (len(jcoupling) + 3) ) # Check arguments have correct form if not (isinstance(jn, list) or isinstance(jn, tuple) or isinstance(jn, Tuple)): raise TypeError('jn must be Tuple, list or tuple, got %s' % jn.__class__.__name__) if not (isinstance(jcoupling, list) or isinstance(jcoupling, tuple) or isinstance(jcoupling, Tuple)): raise TypeError('jcoupling must be Tuple, list or tuple, got %s' % jcoupling.__class__.__name__) if not all(isinstance(term, list) or isinstance(term, tuple) or isinstance(term, Tuple) for term in jcoupling): raise TypeError( 'All elements of jcoupling must be list, tuple or Tuple') if not len(jn) - 1 == len(jcoupling): raise ValueError('jcoupling must have length of %d, got %d' % (len(jn) - 1, len(jcoupling))) if not all(len(x) == 3 for x in jcoupling): raise ValueError('All elements of jcoupling must have length 3') # Build sympified args j = sympify(j) m = sympify(m) jn = Tuple( *[sympify(ji) for ji in jn] ) jcoupling = Tuple( *[Tuple(sympify( n1), sympify(n2), sympify(ji)) for (n1, n2, ji) in jcoupling] ) # Check values in coupling scheme give physical state if any(2*ji != int(2*ji) for ji in jn if ji.is_number): raise ValueError('All elements of jn must be integer or half-integer, got: %s' % jn) if any(n1 != int(n1) or n2 != int(n2) for (n1, n2, _) in jcoupling): raise ValueError('Indices in jcoupling must be integers') if any(n1 < 1 or n2 < 1 or n1 > len(jn) or n2 > len(jn) for (n1, n2, _) in jcoupling): raise ValueError('Indices must be between 1 and the number of coupled spin spaces') if any(2*ji != int(2*ji) for (_, _, ji) in jcoupling if ji.is_number): raise ValueError('All coupled j values in coupling scheme must be integer or half-integer') coupled_n, coupled_jn = _build_coupled(jcoupling, len(jn)) jvals = list(jn) for n, (n1, n2) in enumerate(coupled_n): j1 = jvals[min(n1) - 1] j2 = jvals[min(n2) - 1] j3 = coupled_jn[n] if sympify(j1).is_number and sympify(j2).is_number and sympify(j3).is_number: if j1 + j2 < j3: raise ValueError('All couplings must have j1+j2 >= j3, ' 'in coupling number %d got j1,j2,j3: %d,%d,%d' % (n + 1, j1, j2, j3)) if abs(j1 - j2) > j3: raise ValueError("All couplings must have |j1+j2| <= j3, " "in coupling number %d got j1,j2,j3: %d,%d,%d" % (n + 1, j1, j2, j3)) if int(j1 + j2) == j1 + j2: pass jvals[min(n1 + n2) - 1] = j3 if len(jcoupling) > 0 and jcoupling[-1][2] != j: raise ValueError('Last j value coupled together must be the final j of the state') # Return state return State.__new__(cls, j, m, jn, jcoupling) def _print_label(self, printer, *args): label = [printer._print(self.j), printer._print(self.m)] for i, ji in enumerate(self.jn, start=1): label.append('j%d=%s' % ( i, printer._print(ji) )) for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]): label.append('j(%s)=%s' % ( ','.join(str(i) for i in sorted(n1 + n2)), printer._print(jn) )) return ','.join(label) def _print_label_pretty(self, printer, *args): label = [self.j, self.m] for i, ji in enumerate(self.jn, start=1): symb = 'j%d' % i symb = pretty_symbol(symb) symb = prettyForm(symb + '=') item = prettyForm(*symb.right(printer._print(ji))) label.append(item) for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]): n = ','.join(pretty_symbol("j%d" % i)[-1] for i in sorted(n1 + n2)) symb = prettyForm('j' + n + '=') item = prettyForm(*symb.right(printer._print(jn))) label.append(item) return self._print_sequence_pretty( label, self._label_separator, printer, *args ) def _print_label_latex(self, printer, *args): label = [ printer._print(self.j, *args), printer._print(self.m, *args) ] for i, ji in enumerate(self.jn, start=1): label.append('j_{%d}=%s' % (i, printer._print(ji, *args)) ) for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]): n = ','.join(str(i) for i in sorted(n1 + n2)) label.append('j_{%s}=%s' % (n, printer._print(jn, *args)) ) return self._label_separator.join(label) @property def jn(self): return self.label[2] @property def coupling(self): return self.label[3] @property def coupled_jn(self): return _build_coupled(self.label[3], len(self.label[2]))[1] @property def coupled_n(self): return _build_coupled(self.label[3], len(self.label[2]))[0] @classmethod def _eval_hilbert_space(cls, label): j = Add(*label[2]) if j.is_number: return DirectSumHilbertSpace(*[ ComplexSpace(x) for x in range(int(2*j + 1), 0, -2) ]) else: # TODO: Need hilbert space fix, see issue 5732 # Desired behavior: #ji = symbols('ji') #ret = Sum(ComplexSpace(2*ji + 1), (ji, 0, j)) # Temporary fix: return ComplexSpace(2*j + 1) def _represent_coupled_base(self, **options): evect = self.uncoupled_class() if not self.j.is_number: raise ValueError( 'State must not have symbolic j value to represent') if not self.hilbert_space.dimension.is_number: raise ValueError( 'State must not have symbolic j values to represent') result = zeros(self.hilbert_space.dimension, 1) if self.j == int(self.j): start = self.j**2 else: start = (2*self.j - 1)*(1 + 2*self.j)/4 result[start:start + 2*self.j + 1, 0] = evect( self.j, self.m)._represent_base(**options) return result def _eval_rewrite_as_Jx(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jx, JxBraCoupled, **options) return self._rewrite_basis(Jx, JxKetCoupled, **options) def _eval_rewrite_as_Jy(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jy, JyBraCoupled, **options) return self._rewrite_basis(Jy, JyKetCoupled, **options) def _eval_rewrite_as_Jz(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jz, JzBraCoupled, **options) return self._rewrite_basis(Jz, JzKetCoupled, **options) class JxKetCoupled(CoupledSpinState, Ket): """Coupled eigenket of Jx. See JzKetCoupled for the usage of coupled spin eigenstates. See Also ======== JzKetCoupled: Usage of coupled spin states """ @classmethod def dual_class(self): return JxBraCoupled @classmethod def uncoupled_class(self): return JxKet def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_coupled_base(**options) def _represent_JyOp(self, basis, **options): return self._represent_coupled_base(alpha=pi*Rational(3, 2), **options) def _represent_JzOp(self, basis, **options): return self._represent_coupled_base(beta=pi/2, **options) class JxBraCoupled(CoupledSpinState, Bra): """Coupled eigenbra of Jx. See JzKetCoupled for the usage of coupled spin eigenstates. See Also ======== JzKetCoupled: Usage of coupled spin states """ @classmethod def dual_class(self): return JxKetCoupled @classmethod def uncoupled_class(self): return JxBra class JyKetCoupled(CoupledSpinState, Ket): """Coupled eigenket of Jy. See JzKetCoupled for the usage of coupled spin eigenstates. See Also ======== JzKetCoupled: Usage of coupled spin states """ @classmethod def dual_class(self): return JyBraCoupled @classmethod def uncoupled_class(self): return JyKet def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_coupled_base(gamma=pi/2, **options) def _represent_JyOp(self, basis, **options): return self._represent_coupled_base(**options) def _represent_JzOp(self, basis, **options): return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options) class JyBraCoupled(CoupledSpinState, Bra): """Coupled eigenbra of Jy. See JzKetCoupled for the usage of coupled spin eigenstates. See Also ======== JzKetCoupled: Usage of coupled spin states """ @classmethod def dual_class(self): return JyKetCoupled @classmethod def uncoupled_class(self): return JyBra class JzKetCoupled(CoupledSpinState, Ket): r"""Coupled eigenket of Jz Spin state that is an eigenket of Jz which represents the coupling of separate spin spaces. The arguments for creating instances of JzKetCoupled are ``j``, ``m``, ``jn`` and an optional ``jcoupling`` argument. The ``j`` and ``m`` options are the total angular momentum quantum numbers, as used for normal states (e.g. JzKet). The other required parameter in ``jn``, which is a tuple defining the `j_n` angular momentum quantum numbers of the product spaces. So for example, if a state represented the coupling of the product basis state `\left|j_1,m_1\right\rangle\times\left|j_2,m_2\right\rangle`, the ``jn`` for this state would be ``(j1,j2)``. The final option is ``jcoupling``, which is used to define how the spaces specified by ``jn`` are coupled, which includes both the order these spaces are coupled together and the quantum numbers that arise from these couplings. The ``jcoupling`` parameter itself is a list of lists, such that each of the sublists defines a single coupling between the spin spaces. If there are N coupled angular momentum spaces, that is ``jn`` has N elements, then there must be N-1 sublists. Each of these sublists making up the ``jcoupling`` parameter have length 3. The first two elements are the indices of the product spaces that are considered to be coupled together. For example, if we want to couple `j_1` and `j_4`, the indices would be 1 and 4. If a state has already been coupled, it is referenced by the smallest index that is coupled, so if `j_2` and `j_4` has already been coupled to some `j_{24}`, then this value can be coupled by referencing it with index 2. The final element of the sublist is the quantum number of the coupled state. So putting everything together, into a valid sublist for ``jcoupling``, if `j_1` and `j_2` are coupled to an angular momentum space with quantum number `j_{12}` with the value ``j12``, the sublist would be ``(1,2,j12)``, N-1 of these sublists are used in the list for ``jcoupling``. Note the ``jcoupling`` parameter is optional, if it is not specified, the default coupling is taken. This default value is to coupled the spaces in order and take the quantum number of the coupling to be the maximum value. For example, if the spin spaces are `j_1`, `j_2`, `j_3`, `j_4`, then the default coupling couples `j_1` and `j_2` to `j_{12}=j_1+j_2`, then, `j_{12}` and `j_3` are coupled to `j_{123}=j_{12}+j_3`, and finally `j_{123}` and `j_4` to `j=j_{123}+j_4`. The jcoupling value that would correspond to this is: ``((1,2,j1+j2),(1,3,j1+j2+j3))`` Parameters ========== args : tuple The arguments that must be passed are ``j``, ``m``, ``jn``, and ``jcoupling``. The ``j`` value is the total angular momentum. The ``m`` value is the eigenvalue of the Jz spin operator. The ``jn`` list are the j values of argular momentum spaces coupled together. The ``jcoupling`` parameter is an optional parameter defining how the spaces are coupled together. See the above description for how these coupling parameters are defined. Examples ======== Defining simple spin states, both numerical and symbolic: >>> from sympy.physics.quantum.spin import JzKetCoupled >>> from sympy import symbols >>> JzKetCoupled(1, 0, (1, 1)) |1,0,j1=1,j2=1> >>> j, m, j1, j2 = symbols('j m j1 j2') >>> JzKetCoupled(j, m, (j1, j2)) |j,m,j1=j1,j2=j2> Defining coupled spin states for more than 2 coupled spaces with various coupling parameters: >>> JzKetCoupled(2, 1, (1, 1, 1)) |2,1,j1=1,j2=1,j3=1,j(1,2)=2> >>> JzKetCoupled(2, 1, (1, 1, 1), ((1,2,2),(1,3,2)) ) |2,1,j1=1,j2=1,j3=1,j(1,2)=2> >>> JzKetCoupled(2, 1, (1, 1, 1), ((2,3,1),(1,2,2)) ) |2,1,j1=1,j2=1,j3=1,j(2,3)=1> Rewriting the JzKetCoupled in terms of eigenkets of the Jx operator: Note: that the resulting eigenstates are JxKetCoupled >>> JzKetCoupled(1,1,(1,1)).rewrite("Jx") |1,-1,j1=1,j2=1>/2 - sqrt(2)*|1,0,j1=1,j2=1>/2 + |1,1,j1=1,j2=1>/2 The rewrite method can be used to convert a coupled state to an uncoupled state. This is done by passing coupled=False to the rewrite function: >>> JzKetCoupled(1, 0, (1, 1)).rewrite('Jz', coupled=False) -sqrt(2)*|1,-1>x|1,1>/2 + sqrt(2)*|1,1>x|1,-1>/2 Get the vector representation of a state in terms of the basis elements of the Jx operator: >>> from sympy.physics.quantum.represent import represent >>> from sympy.physics.quantum.spin import Jx >>> from sympy import S >>> represent(JzKetCoupled(1,-1,(S(1)/2,S(1)/2)), basis=Jx) Matrix([ [ 0], [ 1/2], [sqrt(2)/2], [ 1/2]]) See Also ======== JzKet: Normal spin eigenstates uncouple: Uncoupling of coupling spin states couple: Coupling of uncoupled spin states """ @classmethod def dual_class(self): return JzBraCoupled @classmethod def uncoupled_class(self): return JzKet def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_coupled_base(beta=pi*Rational(3, 2), **options) def _represent_JyOp(self, basis, **options): return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options) def _represent_JzOp(self, basis, **options): return self._represent_coupled_base(**options) class JzBraCoupled(CoupledSpinState, Bra): """Coupled eigenbra of Jz. See the JzKetCoupled for the usage of coupled spin eigenstates. See Also ======== JzKetCoupled: Usage of coupled spin states """ @classmethod def dual_class(self): return JzKetCoupled @classmethod def uncoupled_class(self): return JzBra #----------------------------------------------------------------------------- # Coupling/uncoupling #----------------------------------------------------------------------------- def couple(expr, jcoupling_list=None): """ Couple a tensor product of spin states This function can be used to couple an uncoupled tensor product of spin states. All of the eigenstates to be coupled must be of the same class. It will return a linear combination of eigenstates that are subclasses of CoupledSpinState determined by Clebsch-Gordan angular momentum coupling coefficients. Parameters ========== expr : Expr An expression involving TensorProducts of spin states to be coupled. Each state must be a subclass of SpinState and they all must be the same class. jcoupling_list : list or tuple Elements of this list are sub-lists of length 2 specifying the order of the coupling of the spin spaces. The length of this must be N-1, where N is the number of states in the tensor product to be coupled. The elements of this sublist are the same as the first two elements of each sublist in the ``jcoupling`` parameter defined for JzKetCoupled. If this parameter is not specified, the default value is taken, which couples the first and second product basis spaces, then couples this new coupled space to the third product space, etc Examples ======== Couple a tensor product of numerical states for two spaces: >>> from sympy.physics.quantum.spin import JzKet, couple >>> from sympy.physics.quantum.tensorproduct import TensorProduct >>> couple(TensorProduct(JzKet(1,0), JzKet(1,1))) -sqrt(2)*|1,1,j1=1,j2=1>/2 + sqrt(2)*|2,1,j1=1,j2=1>/2 Numerical coupling of three spaces using the default coupling method, i.e. first and second spaces couple, then this couples to the third space: >>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0))) sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,2)=2>/3 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,2)=2>/3 Perform this same coupling, but we define the coupling to first couple the first and third spaces: >>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)), ((1,3),(1,2)) ) sqrt(2)*|2,2,j1=1,j2=1,j3=1,j(1,3)=1>/2 - sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,3)=2>/6 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,3)=2>/3 Couple a tensor product of symbolic states: >>> from sympy import symbols >>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2') >>> couple(TensorProduct(JzKet(j1,m1), JzKet(j2,m2))) Sum(CG(j1, m1, j2, m2, j, m1 + m2)*|j,m1 + m2,j1=j1,j2=j2>, (j, m1 + m2, j1 + j2)) """ a = expr.atoms(TensorProduct) for tp in a: # Allow other tensor products to be in expression if not all([ isinstance(state, SpinState) for state in tp.args]): continue # If tensor product has all spin states, raise error for invalid tensor product state if not all([state.__class__ is tp.args[0].__class__ for state in tp.args]): raise TypeError('All states must be the same basis') expr = expr.subs(tp, _couple(tp, jcoupling_list)) return expr def _couple(tp, jcoupling_list): states = tp.args coupled_evect = states[0].coupled_class() # Define default coupling if none is specified if jcoupling_list is None: jcoupling_list = [] for n in range(1, len(states)): jcoupling_list.append( (1, n + 1) ) # Check jcoupling_list valid if not len(jcoupling_list) == len(states) - 1: raise TypeError('jcoupling_list must be length %d, got %d' % (len(states) - 1, len(jcoupling_list))) if not all( len(coupling) == 2 for coupling in jcoupling_list): raise ValueError('Each coupling must define 2 spaces') if any([n1 == n2 for n1, n2 in jcoupling_list]): raise ValueError('Spin spaces cannot couple to themselves') if all([sympify(n1).is_number and sympify(n2).is_number for n1, n2 in jcoupling_list]): j_test = [0]*len(states) for n1, n2 in jcoupling_list: if j_test[n1 - 1] == -1 or j_test[n2 - 1] == -1: raise ValueError('Spaces coupling j_n\'s are referenced by smallest n value') j_test[max(n1, n2) - 1] = -1 # j values of states to be coupled together jn = [state.j for state in states] mn = [state.m for state in states] # Create coupling_list, which defines all the couplings between all # the spaces from jcoupling_list coupling_list = [] n_list = [ [i + 1] for i in range(len(states)) ] for j_coupling in jcoupling_list: # Least n for all j_n which is coupled as first and second spaces n1, n2 = j_coupling # List of all n's coupled in first and second spaces j1_n = list(n_list[n1 - 1]) j2_n = list(n_list[n2 - 1]) coupling_list.append( (j1_n, j2_n) ) # Set new j_n to be coupling of all j_n in both first and second spaces n_list[ min(n1, n2) - 1 ] = sorted(j1_n + j2_n) if all(state.j.is_number and state.m.is_number for state in states): # Numerical coupling # Iterate over difference between maximum possible j value of each coupling and the actual value diff_max = [ Add( *[ jn[n - 1] - mn[n - 1] for n in coupling[0] + coupling[1] ] ) for coupling in coupling_list ] result = [] for diff in range(diff_max[-1] + 1): # Determine available configurations n = len(coupling_list) tot = binomial(diff + n - 1, diff) for config_num in range(tot): diff_list = _confignum_to_difflist(config_num, diff, n) # Skip the configuration if non-physical # This is a lazy check for physical states given the loose restrictions of diff_max if any( [ d > m for d, m in zip(diff_list, diff_max) ] ): continue # Determine term cg_terms = [] coupled_j = list(jn) jcoupling = [] for (j1_n, j2_n), coupling_diff in zip(coupling_list, diff_list): j1 = coupled_j[ min(j1_n) - 1 ] j2 = coupled_j[ min(j2_n) - 1 ] j3 = j1 + j2 - coupling_diff coupled_j[ min(j1_n + j2_n) - 1 ] = j3 m1 = Add( *[ mn[x - 1] for x in j1_n] ) m2 = Add( *[ mn[x - 1] for x in j2_n] ) m3 = m1 + m2 cg_terms.append( (j1, m1, j2, m2, j3, m3) ) jcoupling.append( (min(j1_n), min(j2_n), j3) ) # Better checks that state is physical if any([ abs(term[5]) > term[4] for term in cg_terms ]): continue if any([ term[0] + term[2] < term[4] for term in cg_terms ]): continue if any([ abs(term[0] - term[2]) > term[4] for term in cg_terms ]): continue coeff = Mul( *[ CG(*term).doit() for term in cg_terms] ) state = coupled_evect(j3, m3, jn, jcoupling) result.append(coeff*state) return Add(*result) else: # Symbolic coupling cg_terms = [] jcoupling = [] sum_terms = [] coupled_j = list(jn) for j1_n, j2_n in coupling_list: j1 = coupled_j[ min(j1_n) - 1 ] j2 = coupled_j[ min(j2_n) - 1 ] if len(j1_n + j2_n) == len(states): j3 = symbols('j') else: j3_name = 'j' + ''.join(["%s" % n for n in j1_n + j2_n]) j3 = symbols(j3_name) coupled_j[ min(j1_n + j2_n) - 1 ] = j3 m1 = Add( *[ mn[x - 1] for x in j1_n] ) m2 = Add( *[ mn[x - 1] for x in j2_n] ) m3 = m1 + m2 cg_terms.append( (j1, m1, j2, m2, j3, m3) ) jcoupling.append( (min(j1_n), min(j2_n), j3) ) sum_terms.append((j3, m3, j1 + j2)) coeff = Mul( *[ CG(*term) for term in cg_terms] ) state = coupled_evect(j3, m3, jn, jcoupling) return Sum(coeff*state, *sum_terms) def uncouple(expr, jn=None, jcoupling_list=None): """ Uncouple a coupled spin state Gives the uncoupled representation of a coupled spin state. Arguments must be either a spin state that is a subclass of CoupledSpinState or a spin state that is a subclass of SpinState and an array giving the j values of the spaces that are to be coupled Parameters ========== expr : Expr The expression containing states that are to be coupled. If the states are a subclass of SpinState, the ``jn`` and ``jcoupling`` parameters must be defined. If the states are a subclass of CoupledSpinState, ``jn`` and ``jcoupling`` will be taken from the state. jn : list or tuple The list of the j-values that are coupled. If state is a CoupledSpinState, this parameter is ignored. This must be defined if state is not a subclass of CoupledSpinState. The syntax of this parameter is the same as the ``jn`` parameter of JzKetCoupled. jcoupling_list : list or tuple The list defining how the j-values are coupled together. If state is a CoupledSpinState, this parameter is ignored. This must be defined if state is not a subclass of CoupledSpinState. The syntax of this parameter is the same as the ``jcoupling`` parameter of JzKetCoupled. Examples ======== Uncouple a numerical state using a CoupledSpinState state: >>> from sympy.physics.quantum.spin import JzKetCoupled, uncouple >>> from sympy import S >>> uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2))) sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2 Perform the same calculation using a SpinState state: >>> from sympy.physics.quantum.spin import JzKet >>> uncouple(JzKet(1, 0), (S(1)/2, S(1)/2)) sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2 Uncouple a numerical state of three coupled spaces using a CoupledSpinState state: >>> uncouple(JzKetCoupled(1, 1, (1, 1, 1), ((1,3,1),(1,2,1)) )) |1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2 Perform the same calculation using a SpinState state: >>> uncouple(JzKet(1, 1), (1, 1, 1), ((1,3,1),(1,2,1)) ) |1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2 Uncouple a symbolic state using a CoupledSpinState state: >>> from sympy import symbols >>> j,m,j1,j2 = symbols('j m j1 j2') >>> uncouple(JzKetCoupled(j, m, (j1, j2))) Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2)) Perform the same calculation using a SpinState state >>> uncouple(JzKet(j, m), (j1, j2)) Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2)) """ a = expr.atoms(SpinState) for state in a: expr = expr.subs(state, _uncouple(state, jn, jcoupling_list)) return expr def _uncouple(state, jn, jcoupling_list): if isinstance(state, CoupledSpinState): jn = state.jn coupled_n = state.coupled_n coupled_jn = state.coupled_jn evect = state.uncoupled_class() elif isinstance(state, SpinState): if jn is None: raise ValueError("Must specify j-values for coupled state") if not (isinstance(jn, list) or isinstance(jn, tuple)): raise TypeError("jn must be list or tuple") if jcoupling_list is None: # Use default jcoupling_list = [] for i in range(1, len(jn)): jcoupling_list.append( (1, 1 + i, Add(*[jn[j] for j in range(i + 1)])) ) if not (isinstance(jcoupling_list, list) or isinstance(jcoupling_list, tuple)): raise TypeError("jcoupling must be a list or tuple") if not len(jcoupling_list) == len(jn) - 1: raise ValueError("Must specify 2 fewer coupling terms than the number of j values") coupled_n, coupled_jn = _build_coupled(jcoupling_list, len(jn)) evect = state.__class__ else: raise TypeError("state must be a spin state") j = state.j m = state.m coupling_list = [] j_list = list(jn) # Create coupling, which defines all the couplings between all the spaces for j3, (n1, n2) in zip(coupled_jn, coupled_n): # j's which are coupled as first and second spaces j1 = j_list[n1[0] - 1] j2 = j_list[n2[0] - 1] # Build coupling list coupling_list.append( (n1, n2, j1, j2, j3) ) # Set new value in j_list j_list[min(n1 + n2) - 1] = j3 if j.is_number and m.is_number: diff_max = [ 2*x for x in jn ] diff = Add(*jn) - m n = len(jn) tot = binomial(diff + n - 1, diff) result = [] for config_num in range(tot): diff_list = _confignum_to_difflist(config_num, diff, n) if any( [ d > p for d, p in zip(diff_list, diff_max) ] ): continue cg_terms = [] for coupling in coupling_list: j1_n, j2_n, j1, j2, j3 = coupling m1 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j1_n ] ) m2 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j2_n ] ) m3 = m1 + m2 cg_terms.append( (j1, m1, j2, m2, j3, m3) ) coeff = Mul( *[ CG(*term).doit() for term in cg_terms ] ) state = TensorProduct( *[ evect(j, j - d) for j, d in zip(jn, diff_list) ] ) result.append(coeff*state) return Add(*result) else: # Symbolic coupling m_str = "m1:%d" % (len(jn) + 1) mvals = symbols(m_str) cg_terms = [(j1, Add(*[mvals[n - 1] for n in j1_n]), j2, Add(*[mvals[n - 1] for n in j2_n]), j3, Add(*[mvals[n - 1] for n in j1_n + j2_n])) for j1_n, j2_n, j1, j2, j3 in coupling_list[:-1] ] cg_terms.append(*[(j1, Add(*[mvals[n - 1] for n in j1_n]), j2, Add(*[mvals[n - 1] for n in j2_n]), j, m) for j1_n, j2_n, j1, j2, j3 in [coupling_list[-1]] ]) cg_coeff = Mul(*[CG(*cg_term) for cg_term in cg_terms]) sum_terms = [ (m, -j, j) for j, m in zip(jn, mvals) ] state = TensorProduct( *[ evect(j, m) for j, m in zip(jn, mvals) ] ) return Sum(cg_coeff*state, *sum_terms) def _confignum_to_difflist(config_num, diff, list_len): # Determines configuration of diffs into list_len number of slots diff_list = [] for n in range(list_len): prev_diff = diff # Number of spots after current one rem_spots = list_len - n - 1 # Number of configurations of distributing diff among the remaining spots rem_configs = binomial(diff + rem_spots - 1, diff) while config_num >= rem_configs: config_num -= rem_configs diff -= 1 rem_configs = binomial(diff + rem_spots - 1, diff) diff_list.append(prev_diff - diff) return diff_list
f018afd5ce46e69d51b8374038d136ad0a26d2c542cf293cd9afc2e6e61b6c8e
"""Constants (like hbar) related to quantum mechanics.""" from __future__ import print_function, division from sympy.core.numbers import NumberSymbol from sympy.core.singleton import Singleton from sympy.printing.pretty.stringpict import prettyForm import mpmath.libmp as mlib #----------------------------------------------------------------------------- # Constants #----------------------------------------------------------------------------- __all__ = [ 'hbar', 'HBar', ] class HBar(NumberSymbol, metaclass=Singleton): """Reduced Plank's constant in numerical and symbolic form [1]_. Examples ======== >>> from sympy.physics.quantum.constants import hbar >>> hbar.evalf() 1.05457162000000e-34 References ========== .. [1] https://en.wikipedia.org/wiki/Planck_constant """ is_real = True is_positive = True is_negative = False is_irrational = True __slots__ = () def _as_mpf_val(self, prec): return mlib.from_float(1.05457162e-34, prec) def _sympyrepr(self, printer, *args): return 'HBar()' def _sympystr(self, printer, *args): return 'hbar' def _pretty(self, printer, *args): if printer._use_unicode: return prettyForm('\N{PLANCK CONSTANT OVER TWO PI}') return prettyForm('hbar') def _latex(self, printer, *args): return r'\hbar' # Create an instance for everyone to use. hbar = HBar()
7f4a94e855b421a9177609b0b0c5d93a056eb14f5b194a2539ad303bf8871ae0
"""Matplotlib based plotting of quantum circuits. Todo: * Optimize printing of large circuits. * Get this to work with single gates. * Do a better job checking the form of circuits to make sure it is a Mul of Gates. * Get multi-target gates plotting. * Get initial and final states to plot. * Get measurements to plot. Might need to rethink measurement as a gate issue. * Get scale and figsize to be handled in a better way. * Write some tests/examples! """ from typing import List, Dict from sympy import Mul from sympy.external import import_module from sympy.physics.quantum.gate import Gate, OneQubitGate, CGate, CGateS from sympy.core.core import BasicMeta from sympy.core.assumptions import ManagedProperties __all__ = [ 'CircuitPlot', 'circuit_plot', 'labeller', 'Mz', 'Mx', 'CreateOneQubitGate', 'CreateCGate', ] np = import_module('numpy') matplotlib = import_module( 'matplotlib', import_kwargs={'fromlist': ['pyplot']}, catch=(RuntimeError,)) # This is raised in environments that have no display. if np and matplotlib: pyplot = matplotlib.pyplot Line2D = matplotlib.lines.Line2D Circle = matplotlib.patches.Circle #from matplotlib import rc #rc('text',usetex=True) class CircuitPlot(object): """A class for managing a circuit plot.""" scale = 1.0 fontsize = 20.0 linewidth = 1.0 control_radius = 0.05 not_radius = 0.15 swap_delta = 0.05 labels = [] # type: List[str] inits = {} # type: Dict[str, str] label_buffer = 0.5 def __init__(self, c, nqubits, **kwargs): if not np or not matplotlib: raise ImportError('numpy or matplotlib not available.') self.circuit = c self.ngates = len(self.circuit.args) self.nqubits = nqubits self.update(kwargs) self._create_grid() self._create_figure() self._plot_wires() self._plot_gates() self._finish() def update(self, kwargs): """Load the kwargs into the instance dict.""" self.__dict__.update(kwargs) def _create_grid(self): """Create the grid of wires.""" scale = self.scale wire_grid = np.arange(0.0, self.nqubits*scale, scale, dtype=float) gate_grid = np.arange(0.0, self.ngates*scale, scale, dtype=float) self._wire_grid = wire_grid self._gate_grid = gate_grid def _create_figure(self): """Create the main matplotlib figure.""" self._figure = pyplot.figure( figsize=(self.ngates*self.scale, self.nqubits*self.scale), facecolor='w', edgecolor='w' ) ax = self._figure.add_subplot( 1, 1, 1, frameon=True ) ax.set_axis_off() offset = 0.5*self.scale ax.set_xlim(self._gate_grid[0] - offset, self._gate_grid[-1] + offset) ax.set_ylim(self._wire_grid[0] - offset, self._wire_grid[-1] + offset) ax.set_aspect('equal') self._axes = ax def _plot_wires(self): """Plot the wires of the circuit diagram.""" xstart = self._gate_grid[0] xstop = self._gate_grid[-1] xdata = (xstart - self.scale, xstop + self.scale) for i in range(self.nqubits): ydata = (self._wire_grid[i], self._wire_grid[i]) line = Line2D( xdata, ydata, color='k', lw=self.linewidth ) self._axes.add_line(line) if self.labels: init_label_buffer = 0 if self.inits.get(self.labels[i]): init_label_buffer = 0.25 self._axes.text( xdata[0]-self.label_buffer-init_label_buffer,ydata[0], render_label(self.labels[i],self.inits), size=self.fontsize, color='k',ha='center',va='center') self._plot_measured_wires() def _plot_measured_wires(self): ismeasured = self._measurements() xstop = self._gate_grid[-1] dy = 0.04 # amount to shift wires when doubled # Plot doubled wires after they are measured for im in ismeasured: xdata = (self._gate_grid[ismeasured[im]],xstop+self.scale) ydata = (self._wire_grid[im]+dy,self._wire_grid[im]+dy) line = Line2D( xdata, ydata, color='k', lw=self.linewidth ) self._axes.add_line(line) # Also double any controlled lines off these wires for i,g in enumerate(self._gates()): if isinstance(g, CGate) or isinstance(g, CGateS): wires = g.controls + g.targets for wire in wires: if wire in ismeasured and \ self._gate_grid[i] > self._gate_grid[ismeasured[wire]]: ydata = min(wires), max(wires) xdata = self._gate_grid[i]-dy, self._gate_grid[i]-dy line = Line2D( xdata, ydata, color='k', lw=self.linewidth ) self._axes.add_line(line) def _gates(self): """Create a list of all gates in the circuit plot.""" gates = [] if isinstance(self.circuit, Mul): for g in reversed(self.circuit.args): if isinstance(g, Gate): gates.append(g) elif isinstance(self.circuit, Gate): gates.append(self.circuit) return gates def _plot_gates(self): """Iterate through the gates and plot each of them.""" for i, gate in enumerate(self._gates()): gate.plot_gate(self, i) def _measurements(self): """Return a dict {i:j} where i is the index of the wire that has been measured, and j is the gate where the wire is measured. """ ismeasured = {} for i,g in enumerate(self._gates()): if getattr(g,'measurement',False): for target in g.targets: if target in ismeasured: if ismeasured[target] > i: ismeasured[target] = i else: ismeasured[target] = i return ismeasured def _finish(self): # Disable clipping to make panning work well for large circuits. for o in self._figure.findobj(): o.set_clip_on(False) def one_qubit_box(self, t, gate_idx, wire_idx): """Draw a box for a single qubit gate.""" x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx] self._axes.text( x, y, t, color='k', ha='center', va='center', bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth), size=self.fontsize ) def two_qubit_box(self, t, gate_idx, wire_idx): """Draw a box for a two qubit gate. Doesn't work yet. """ # x = self._gate_grid[gate_idx] # y = self._wire_grid[wire_idx]+0.5 print(self._gate_grid) print(self._wire_grid) # unused: # obj = self._axes.text( # x, y, t, # color='k', # ha='center', # va='center', # bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth), # size=self.fontsize # ) def control_line(self, gate_idx, min_wire, max_wire): """Draw a vertical control line.""" xdata = (self._gate_grid[gate_idx], self._gate_grid[gate_idx]) ydata = (self._wire_grid[min_wire], self._wire_grid[max_wire]) line = Line2D( xdata, ydata, color='k', lw=self.linewidth ) self._axes.add_line(line) def control_point(self, gate_idx, wire_idx): """Draw a control point.""" x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx] radius = self.control_radius c = Circle( (x, y), radius*self.scale, ec='k', fc='k', fill=True, lw=self.linewidth ) self._axes.add_patch(c) def not_point(self, gate_idx, wire_idx): """Draw a NOT gates as the circle with plus in the middle.""" x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx] radius = self.not_radius c = Circle( (x, y), radius, ec='k', fc='w', fill=False, lw=self.linewidth ) self._axes.add_patch(c) l = Line2D( (x, x), (y - radius, y + radius), color='k', lw=self.linewidth ) self._axes.add_line(l) def swap_point(self, gate_idx, wire_idx): """Draw a swap point as a cross.""" x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx] d = self.swap_delta l1 = Line2D( (x - d, x + d), (y - d, y + d), color='k', lw=self.linewidth ) l2 = Line2D( (x - d, x + d), (y + d, y - d), color='k', lw=self.linewidth ) self._axes.add_line(l1) self._axes.add_line(l2) def circuit_plot(c, nqubits, **kwargs): """Draw the circuit diagram for the circuit with nqubits. Parameters ========== c : circuit The circuit to plot. Should be a product of Gate instances. nqubits : int The number of qubits to include in the circuit. Must be at least as big as the largest `min_qubits`` of the gates. """ return CircuitPlot(c, nqubits, **kwargs) def render_label(label, inits={}): """Slightly more flexible way to render labels. >>> from sympy.physics.quantum.circuitplot import render_label >>> render_label('q0') '$\\\\left|q0\\\\right\\\\rangle$' >>> render_label('q0', {'q0':'0'}) '$\\\\left|q0\\\\right\\\\rangle=\\\\left|0\\\\right\\\\rangle$' """ init = inits.get(label) if init: return r'$\left|%s\right\rangle=\left|%s\right\rangle$' % (label, init) return r'$\left|%s\right\rangle$' % label def labeller(n, symbol='q'): """Autogenerate labels for wires of quantum circuits. Parameters ========== n : int number of qubits in the circuit symbol : string A character string to precede all gate labels. E.g. 'q_0', 'q_1', etc. >>> from sympy.physics.quantum.circuitplot import labeller >>> labeller(2) ['q_1', 'q_0'] >>> labeller(3,'j') ['j_2', 'j_1', 'j_0'] """ return ['%s_%d' % (symbol,n-i-1) for i in range(n)] class Mz(OneQubitGate): """Mock-up of a z measurement gate. This is in circuitplot rather than gate.py because it's not a real gate, it just draws one. """ measurement = True gate_name='Mz' gate_name_latex='M_z' class Mx(OneQubitGate): """Mock-up of an x measurement gate. This is in circuitplot rather than gate.py because it's not a real gate, it just draws one. """ measurement = True gate_name='Mx' gate_name_latex='M_x' class CreateOneQubitGate(ManagedProperties): def __new__(mcl, name, latexname=None): if not latexname: latexname = name return BasicMeta.__new__(mcl, name + "Gate", (OneQubitGate,), {'gate_name': name, 'gate_name_latex': latexname}) def CreateCGate(name, latexname=None): """Use a lexical closure to make a controlled gate. """ if not latexname: latexname = name onequbitgate = CreateOneQubitGate(name, latexname) def ControlledGate(ctrls,target): return CGate(tuple(ctrls),onequbitgate(target)) return ControlledGate
16d0a63078425351d9428d816f3a56648d35051d4685f5f40d2fcd48dd511be3
"""Fermionic quantum operators.""" from sympy import Integer from sympy.physics.quantum import Operator from sympy.physics.quantum import HilbertSpace, Ket, Bra from sympy.functions.special.tensor_functions import KroneckerDelta __all__ = [ 'FermionOp', 'FermionFockKet', 'FermionFockBra' ] class FermionOp(Operator): """A fermionic operator that satisfies {c, Dagger(c)} == 1. Parameters ========== name : str A string that labels the fermionic mode. annihilation : bool A bool that indicates if the fermionic operator is an annihilation (True, default value) or creation operator (False) Examples ======== >>> from sympy.physics.quantum import Dagger, AntiCommutator >>> from sympy.physics.quantum.fermion import FermionOp >>> c = FermionOp("c") >>> AntiCommutator(c, Dagger(c)).doit() 1 """ @property def name(self): return self.args[0] @property def is_annihilation(self): return bool(self.args[1]) @classmethod def default_args(self): return ("c", True) def __new__(cls, *args, **hints): if not len(args) in [1, 2]: raise ValueError('1 or 2 parameters expected, got %s' % args) if len(args) == 1: args = (args[0], Integer(1)) if len(args) == 2: args = (args[0], Integer(args[1])) return Operator.__new__(cls, *args) def _eval_commutator_FermionOp(self, other, **hints): if 'independent' in hints and hints['independent']: # [c, d] = 0 return Integer(0) return None def _eval_anticommutator_FermionOp(self, other, **hints): if self.name == other.name: # {a^\dagger, a} = 1 if not self.is_annihilation and other.is_annihilation: return Integer(1) elif 'independent' in hints and hints['independent']: # {c, d} = 2 * c * d, because [c, d] = 0 for independent operators return 2 * self * other return None def _eval_anticommutator_BosonOp(self, other, **hints): # because fermions and bosons commute return 2 * self * other def _eval_commutator_BosonOp(self, other, **hints): return Integer(0) def _eval_adjoint(self): return FermionOp(str(self.name), not self.is_annihilation) def _print_contents_latex(self, printer, *args): if self.is_annihilation: return r'{%s}' % str(self.name) else: return r'{{%s}^\dagger}' % str(self.name) def _print_contents(self, printer, *args): if self.is_annihilation: return r'%s' % str(self.name) else: return r'Dagger(%s)' % str(self.name) def _print_contents_pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm pform = printer._print(self.args[0], *args) if self.is_annihilation: return pform else: return pform**prettyForm('\N{DAGGER}') class FermionFockKet(Ket): """Fock state ket for a fermionic mode. Parameters ========== n : Number The Fock state number. """ def __new__(cls, n): if n not in [0, 1]: raise ValueError("n must be 0 or 1") return Ket.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return FermionFockBra @classmethod def _eval_hilbert_space(cls, label): return HilbertSpace() def _eval_innerproduct_FermionFockBra(self, bra, **hints): return KroneckerDelta(self.n, bra.n) def _apply_operator_FermionOp(self, op, **options): if op.is_annihilation: if self.n == 1: return FermionFockKet(0) else: return Integer(0) else: if self.n == 0: return FermionFockKet(1) else: return Integer(0) class FermionFockBra(Bra): """Fock state bra for a fermionic mode. Parameters ========== n : Number The Fock state number. """ def __new__(cls, n): if n not in [0, 1]: raise ValueError("n must be 0 or 1") return Bra.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return FermionFockKet
f11cd9945236d14fe62d2ff90bfd06545e3ca60b7e34bf6ce147e13796265438
"""Hilbert spaces for quantum mechanics. Authors: * Brian Granger * Matt Curry """ from __future__ import print_function, division from sympy import Basic, Interval, oo, sympify from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.qexpr import QuantumError from sympy.core.compatibility import reduce __all__ = [ 'HilbertSpaceError', 'HilbertSpace', 'TensorProductHilbertSpace', 'TensorPowerHilbertSpace', 'DirectSumHilbertSpace', 'ComplexSpace', 'L2', 'FockSpace' ] #----------------------------------------------------------------------------- # Main objects #----------------------------------------------------------------------------- class HilbertSpaceError(QuantumError): pass #----------------------------------------------------------------------------- # Main objects #----------------------------------------------------------------------------- class HilbertSpace(Basic): """An abstract Hilbert space for quantum mechanics. In short, a Hilbert space is an abstract vector space that is complete with inner products defined [1]_. Examples ======== >>> from sympy.physics.quantum.hilbert import HilbertSpace >>> hs = HilbertSpace() >>> hs H References ========== .. [1] https://en.wikipedia.org/wiki/Hilbert_space """ def __new__(cls): obj = Basic.__new__(cls) return obj @property def dimension(self): """Return the Hilbert dimension of the space.""" raise NotImplementedError('This Hilbert space has no dimension.') def __add__(self, other): return DirectSumHilbertSpace(self, other) def __radd__(self, other): return DirectSumHilbertSpace(other, self) def __mul__(self, other): return TensorProductHilbertSpace(self, other) def __rmul__(self, other): return TensorProductHilbertSpace(other, self) def __pow__(self, other, mod=None): if mod is not None: raise ValueError('The third argument to __pow__ is not supported \ for Hilbert spaces.') return TensorPowerHilbertSpace(self, other) def __contains__(self, other): """Is the operator or state in this Hilbert space. This is checked by comparing the classes of the Hilbert spaces, not the instances. This is to allow Hilbert Spaces with symbolic dimensions. """ if other.hilbert_space.__class__ == self.__class__: return True else: return False def _sympystr(self, printer, *args): return 'H' def _pretty(self, printer, *args): ustr = '\N{LATIN CAPITAL LETTER H}' return prettyForm(ustr) def _latex(self, printer, *args): return r'\mathcal{H}' class ComplexSpace(HilbertSpace): """Finite dimensional Hilbert space of complex vectors. The elements of this Hilbert space are n-dimensional complex valued vectors with the usual inner product that takes the complex conjugate of the vector on the right. A classic example of this type of Hilbert space is spin-1/2, which is ``ComplexSpace(2)``. Generalizing to spin-s, the space is ``ComplexSpace(2*s+1)``. Quantum computing with N qubits is done with the direct product space ``ComplexSpace(2)**N``. Examples ======== >>> from sympy import symbols >>> from sympy.physics.quantum.hilbert import ComplexSpace >>> c1 = ComplexSpace(2) >>> c1 C(2) >>> c1.dimension 2 >>> n = symbols('n') >>> c2 = ComplexSpace(n) >>> c2 C(n) >>> c2.dimension n """ def __new__(cls, dimension): dimension = sympify(dimension) r = cls.eval(dimension) if isinstance(r, Basic): return r obj = Basic.__new__(cls, dimension) return obj @classmethod def eval(cls, dimension): if len(dimension.atoms()) == 1: if not (dimension.is_Integer and dimension > 0 or dimension is oo or dimension.is_Symbol): raise TypeError('The dimension of a ComplexSpace can only' 'be a positive integer, oo, or a Symbol: %r' % dimension) else: for dim in dimension.atoms(): if not (dim.is_Integer or dim is oo or dim.is_Symbol): raise TypeError('The dimension of a ComplexSpace can only' ' contain integers, oo, or a Symbol: %r' % dim) @property def dimension(self): return self.args[0] def _sympyrepr(self, printer, *args): return "%s(%s)" % (self.__class__.__name__, printer._print(self.dimension, *args)) def _sympystr(self, printer, *args): return "C(%s)" % printer._print(self.dimension, *args) def _pretty(self, printer, *args): ustr = '\N{LATIN CAPITAL LETTER C}' pform_exp = printer._print(self.dimension, *args) pform_base = prettyForm(ustr) return pform_base**pform_exp def _latex(self, printer, *args): return r'\mathcal{C}^{%s}' % printer._print(self.dimension, *args) class L2(HilbertSpace): """The Hilbert space of square integrable functions on an interval. An L2 object takes in a single sympy Interval argument which represents the interval its functions (vectors) are defined on. Examples ======== >>> from sympy import Interval, oo >>> from sympy.physics.quantum.hilbert import L2 >>> hs = L2(Interval(0,oo)) >>> hs L2(Interval(0, oo)) >>> hs.dimension oo >>> hs.interval Interval(0, oo) """ def __new__(cls, interval): if not isinstance(interval, Interval): raise TypeError('L2 interval must be an Interval instance: %r' % interval) obj = Basic.__new__(cls, interval) return obj @property def dimension(self): return oo @property def interval(self): return self.args[0] def _sympyrepr(self, printer, *args): return "L2(%s)" % printer._print(self.interval, *args) def _sympystr(self, printer, *args): return "L2(%s)" % printer._print(self.interval, *args) def _pretty(self, printer, *args): pform_exp = prettyForm('2') pform_base = prettyForm('L') return pform_base**pform_exp def _latex(self, printer, *args): interval = printer._print(self.interval, *args) return r'{\mathcal{L}^2}\left( %s \right)' % interval class FockSpace(HilbertSpace): """The Hilbert space for second quantization. Technically, this Hilbert space is a infinite direct sum of direct products of single particle Hilbert spaces [1]_. This is a mess, so we have a class to represent it directly. Examples ======== >>> from sympy.physics.quantum.hilbert import FockSpace >>> hs = FockSpace() >>> hs F >>> hs.dimension oo References ========== .. [1] https://en.wikipedia.org/wiki/Fock_space """ def __new__(cls): obj = Basic.__new__(cls) return obj @property def dimension(self): return oo def _sympyrepr(self, printer, *args): return "FockSpace()" def _sympystr(self, printer, *args): return "F" def _pretty(self, printer, *args): ustr = '\N{LATIN CAPITAL LETTER F}' return prettyForm(ustr) def _latex(self, printer, *args): return r'\mathcal{F}' class TensorProductHilbertSpace(HilbertSpace): """A tensor product of Hilbert spaces [1]_. The tensor product between Hilbert spaces is represented by the operator ``*`` Products of the same Hilbert space will be combined into tensor powers. A ``TensorProductHilbertSpace`` object takes in an arbitrary number of ``HilbertSpace`` objects as its arguments. In addition, multiplication of ``HilbertSpace`` objects will automatically return this tensor product object. Examples ======== >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace >>> from sympy import symbols >>> c = ComplexSpace(2) >>> f = FockSpace() >>> hs = c*f >>> hs C(2)*F >>> hs.dimension oo >>> hs.spaces (C(2), F) >>> c1 = ComplexSpace(2) >>> n = symbols('n') >>> c2 = ComplexSpace(n) >>> hs = c1*c2 >>> hs C(2)*C(n) >>> hs.dimension 2*n References ========== .. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products """ def __new__(cls, *args): r = cls.eval(args) if isinstance(r, Basic): return r obj = Basic.__new__(cls, *args) return obj @classmethod def eval(cls, args): """Evaluates the direct product.""" new_args = [] recall = False #flatten arguments for arg in args: if isinstance(arg, TensorProductHilbertSpace): new_args.extend(arg.args) recall = True elif isinstance(arg, (HilbertSpace, TensorPowerHilbertSpace)): new_args.append(arg) else: raise TypeError('Hilbert spaces can only be multiplied by \ other Hilbert spaces: %r' % arg) #combine like arguments into direct powers comb_args = [] prev_arg = None for new_arg in new_args: if prev_arg is not None: if isinstance(new_arg, TensorPowerHilbertSpace) and \ isinstance(prev_arg, TensorPowerHilbertSpace) and \ new_arg.base == prev_arg.base: prev_arg = new_arg.base**(new_arg.exp + prev_arg.exp) elif isinstance(new_arg, TensorPowerHilbertSpace) and \ new_arg.base == prev_arg: prev_arg = prev_arg**(new_arg.exp + 1) elif isinstance(prev_arg, TensorPowerHilbertSpace) and \ new_arg == prev_arg.base: prev_arg = new_arg**(prev_arg.exp + 1) elif new_arg == prev_arg: prev_arg = new_arg**2 else: comb_args.append(prev_arg) prev_arg = new_arg elif prev_arg is None: prev_arg = new_arg comb_args.append(prev_arg) if recall: return TensorProductHilbertSpace(*comb_args) elif len(comb_args) == 1: return TensorPowerHilbertSpace(comb_args[0].base, comb_args[0].exp) else: return None @property def dimension(self): arg_list = [arg.dimension for arg in self.args] if oo in arg_list: return oo else: return reduce(lambda x, y: x*y, arg_list) @property def spaces(self): """A tuple of the Hilbert spaces in this tensor product.""" return self.args def _spaces_printer(self, printer, *args): spaces_strs = [] for arg in self.args: s = printer._print(arg, *args) if isinstance(arg, DirectSumHilbertSpace): s = '(%s)' % s spaces_strs.append(s) return spaces_strs def _sympyrepr(self, printer, *args): spaces_reprs = self._spaces_printer(printer, *args) return "TensorProductHilbertSpace(%s)" % ','.join(spaces_reprs) def _sympystr(self, printer, *args): spaces_strs = self._spaces_printer(printer, *args) return '*'.join(spaces_strs) def _pretty(self, printer, *args): length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print(self.args[i], *args) if isinstance(self.args[i], (DirectSumHilbertSpace, TensorProductHilbertSpace)): next_pform = prettyForm( *next_pform.parens(left='(', right=')') ) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: if printer._use_unicode: pform = prettyForm(*pform.right(' ' + '\N{N-ARY CIRCLED TIMES OPERATOR}' + ' ')) else: pform = prettyForm(*pform.right(' x ')) return pform def _latex(self, printer, *args): length = len(self.args) s = '' for i in range(length): arg_s = printer._print(self.args[i], *args) if isinstance(self.args[i], (DirectSumHilbertSpace, TensorProductHilbertSpace)): arg_s = r'\left(%s\right)' % arg_s s = s + arg_s if i != length - 1: s = s + r'\otimes ' return s class DirectSumHilbertSpace(HilbertSpace): """A direct sum of Hilbert spaces [1]_. This class uses the ``+`` operator to represent direct sums between different Hilbert spaces. A ``DirectSumHilbertSpace`` object takes in an arbitrary number of ``HilbertSpace`` objects as its arguments. Also, addition of ``HilbertSpace`` objects will automatically return a direct sum object. Examples ======== >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace >>> c = ComplexSpace(2) >>> f = FockSpace() >>> hs = c+f >>> hs C(2)+F >>> hs.dimension oo >>> list(hs.spaces) [C(2), F] References ========== .. [1] https://en.wikipedia.org/wiki/Hilbert_space#Direct_sums """ def __new__(cls, *args): r = cls.eval(args) if isinstance(r, Basic): return r obj = Basic.__new__(cls, *args) return obj @classmethod def eval(cls, args): """Evaluates the direct product.""" new_args = [] recall = False #flatten arguments for arg in args: if isinstance(arg, DirectSumHilbertSpace): new_args.extend(arg.args) recall = True elif isinstance(arg, HilbertSpace): new_args.append(arg) else: raise TypeError('Hilbert spaces can only be summed with other \ Hilbert spaces: %r' % arg) if recall: return DirectSumHilbertSpace(*new_args) else: return None @property def dimension(self): arg_list = [arg.dimension for arg in self.args] if oo in arg_list: return oo else: return reduce(lambda x, y: x + y, arg_list) @property def spaces(self): """A tuple of the Hilbert spaces in this direct sum.""" return self.args def _sympyrepr(self, printer, *args): spaces_reprs = [printer._print(arg, *args) for arg in self.args] return "DirectSumHilbertSpace(%s)" % ','.join(spaces_reprs) def _sympystr(self, printer, *args): spaces_strs = [printer._print(arg, *args) for arg in self.args] return '+'.join(spaces_strs) def _pretty(self, printer, *args): length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print(self.args[i], *args) if isinstance(self.args[i], (DirectSumHilbertSpace, TensorProductHilbertSpace)): next_pform = prettyForm( *next_pform.parens(left='(', right=')') ) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: if printer._use_unicode: pform = prettyForm(*pform.right(' \N{CIRCLED PLUS} ')) else: pform = prettyForm(*pform.right(' + ')) return pform def _latex(self, printer, *args): length = len(self.args) s = '' for i in range(length): arg_s = printer._print(self.args[i], *args) if isinstance(self.args[i], (DirectSumHilbertSpace, TensorProductHilbertSpace)): arg_s = r'\left(%s\right)' % arg_s s = s + arg_s if i != length - 1: s = s + r'\oplus ' return s class TensorPowerHilbertSpace(HilbertSpace): """An exponentiated Hilbert space [1]_. Tensor powers (repeated tensor products) are represented by the operator ``**`` Identical Hilbert spaces that are multiplied together will be automatically combined into a single tensor power object. Any Hilbert space, product, or sum may be raised to a tensor power. The ``TensorPowerHilbertSpace`` takes two arguments: the Hilbert space; and the tensor power (number). Examples ======== >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace >>> from sympy import symbols >>> n = symbols('n') >>> c = ComplexSpace(2) >>> hs = c**n >>> hs C(2)**n >>> hs.dimension 2**n >>> c = ComplexSpace(2) >>> c*c C(2)**2 >>> f = FockSpace() >>> c*f*f C(2)*F**2 References ========== .. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products """ def __new__(cls, *args): r = cls.eval(args) if isinstance(r, Basic): return r return Basic.__new__(cls, *r) @classmethod def eval(cls, args): new_args = args[0], sympify(args[1]) exp = new_args[1] #simplify hs**1 -> hs if exp == 1: return args[0] #simplify hs**0 -> 1 if exp == 0: return sympify(1) #check (and allow) for hs**(x+42+y...) case if len(exp.atoms()) == 1: if not (exp.is_Integer and exp >= 0 or exp.is_Symbol): raise ValueError('Hilbert spaces can only be raised to \ positive integers or Symbols: %r' % exp) else: for power in exp.atoms(): if not (power.is_Integer or power.is_Symbol): raise ValueError('Tensor powers can only contain integers \ or Symbols: %r' % power) return new_args @property def base(self): return self.args[0] @property def exp(self): return self.args[1] @property def dimension(self): if self.base.dimension is oo: return oo else: return self.base.dimension**self.exp def _sympyrepr(self, printer, *args): return "TensorPowerHilbertSpace(%s,%s)" % (printer._print(self.base, *args), printer._print(self.exp, *args)) def _sympystr(self, printer, *args): return "%s**%s" % (printer._print(self.base, *args), printer._print(self.exp, *args)) def _pretty(self, printer, *args): pform_exp = printer._print(self.exp, *args) if printer._use_unicode: pform_exp = prettyForm(*pform_exp.left(prettyForm('\N{N-ARY CIRCLED TIMES OPERATOR}'))) else: pform_exp = prettyForm(*pform_exp.left(prettyForm('x'))) pform_base = printer._print(self.base, *args) return pform_base**pform_exp def _latex(self, printer, *args): base = printer._print(self.base, *args) exp = printer._print(self.exp, *args) return r'{%s}^{\otimes %s}' % (base, exp)
9b9b50aa5ff0dc4ae66ea2b15ed3b6f9e61a5414143bd348eb436eb934ef5520
"""Bosonic quantum operators.""" from sympy import Mul, Integer, exp, sqrt, conjugate from sympy.physics.quantum import Operator from sympy.physics.quantum import HilbertSpace, FockSpace, Ket, Bra, IdentityOperator from sympy.functions.special.tensor_functions import KroneckerDelta __all__ = [ 'BosonOp', 'BosonFockKet', 'BosonFockBra', 'BosonCoherentKet', 'BosonCoherentBra' ] class BosonOp(Operator): """A bosonic operator that satisfies [a, Dagger(a)] == 1. Parameters ========== name : str A string that labels the bosonic mode. annihilation : bool A bool that indicates if the bosonic operator is an annihilation (True, default value) or creation operator (False) Examples ======== >>> from sympy.physics.quantum import Dagger, Commutator >>> from sympy.physics.quantum.boson import BosonOp >>> a = BosonOp("a") >>> Commutator(a, Dagger(a)).doit() 1 """ @property def name(self): return self.args[0] @property def is_annihilation(self): return bool(self.args[1]) @classmethod def default_args(self): return ("a", True) def __new__(cls, *args, **hints): if not len(args) in [1, 2]: raise ValueError('1 or 2 parameters expected, got %s' % args) if len(args) == 1: args = (args[0], Integer(1)) if len(args) == 2: args = (args[0], Integer(args[1])) return Operator.__new__(cls, *args) def _eval_commutator_BosonOp(self, other, **hints): if self.name == other.name: # [a^\dagger, a] = -1 if not self.is_annihilation and other.is_annihilation: return Integer(-1) elif 'independent' in hints and hints['independent']: # [a, b] = 0 return Integer(0) return None def _eval_commutator_FermionOp(self, other, **hints): return Integer(0) def _eval_anticommutator_BosonOp(self, other, **hints): if 'independent' in hints and hints['independent']: # {a, b} = 2 * a * b, because [a, b] = 0 return 2 * self * other return None def _eval_adjoint(self): return BosonOp(str(self.name), not self.is_annihilation) def __mul__(self, other): if other == IdentityOperator(2): return self if isinstance(other, Mul): args1 = tuple(arg for arg in other.args if arg.is_commutative) args2 = tuple(arg for arg in other.args if not arg.is_commutative) x = self for y in args2: x = x * y return Mul(*args1) * x return Mul(self, other) def _print_contents_latex(self, printer, *args): if self.is_annihilation: return r'{%s}' % str(self.name) else: return r'{{%s}^\dagger}' % str(self.name) def _print_contents(self, printer, *args): if self.is_annihilation: return r'%s' % str(self.name) else: return r'Dagger(%s)' % str(self.name) def _print_contents_pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm pform = printer._print(self.args[0], *args) if self.is_annihilation: return pform else: return pform**prettyForm('\N{DAGGER}') class BosonFockKet(Ket): """Fock state ket for a bosonic mode. Parameters ========== n : Number The Fock state number. """ def __new__(cls, n): return Ket.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return BosonFockBra @classmethod def _eval_hilbert_space(cls, label): return FockSpace() def _eval_innerproduct_BosonFockBra(self, bra, **hints): return KroneckerDelta(self.n, bra.n) def _apply_operator_BosonOp(self, op, **options): if op.is_annihilation: return sqrt(self.n) * BosonFockKet(self.n - 1) else: return sqrt(self.n + 1) * BosonFockKet(self.n + 1) class BosonFockBra(Bra): """Fock state bra for a bosonic mode. Parameters ========== n : Number The Fock state number. """ def __new__(cls, n): return Bra.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return BosonFockKet @classmethod def _eval_hilbert_space(cls, label): return FockSpace() class BosonCoherentKet(Ket): """Coherent state ket for a bosonic mode. Parameters ========== alpha : Number, Symbol The complex amplitude of the coherent state. """ def __new__(cls, alpha): return Ket.__new__(cls, alpha) @property def alpha(self): return self.label[0] @classmethod def dual_class(self): return BosonCoherentBra @classmethod def _eval_hilbert_space(cls, label): return HilbertSpace() def _eval_innerproduct_BosonCoherentBra(self, bra, **hints): if self.alpha == bra.alpha: return Integer(1) else: return exp(-(abs(self.alpha)**2 + abs(bra.alpha)**2 - 2 * conjugate(bra.alpha) * self.alpha)/2) def _apply_operator_BosonOp(self, op, **options): if op.is_annihilation: return self.alpha * self else: return None class BosonCoherentBra(Bra): """Coherent state bra for a bosonic mode. Parameters ========== alpha : Number, Symbol The complex amplitude of the coherent state. """ def __new__(cls, alpha): return Bra.__new__(cls, alpha) @property def alpha(self): return self.label[0] @classmethod def dual_class(self): return BosonCoherentKet def _apply_operator_BosonOp(self, op, **options): if not op.is_annihilation: return self.alpha * self else: return None
eb8bacf861b4db2089ad79eb3b7c2dffc17544d4bed43a401c03504d71aeb740
"""Simple Harmonic Oscillator 1-Dimension""" from __future__ import print_function, division from sympy import sqrt, I, Symbol, Integer, S from sympy.physics.quantum.constants import hbar from sympy.physics.quantum.operator import Operator from sympy.physics.quantum.state import Bra, Ket, State from sympy.physics.quantum.qexpr import QExpr from sympy.physics.quantum.cartesian import X, Px from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.matrixutils import matrix_zeros #------------------------------------------------------------------------------ class SHOOp(Operator): """A base class for the SHO Operators. We are limiting the number of arguments to be 1. """ @classmethod def _eval_args(cls, args): args = QExpr._eval_args(args) if len(args) == 1: return args else: raise ValueError("Too many arguments") @classmethod def _eval_hilbert_space(cls, label): return ComplexSpace(S.Infinity) class RaisingOp(SHOOp): """The Raising Operator or a^dagger. When a^dagger acts on a state it raises the state up by one. Taking the adjoint of a^dagger returns 'a', the Lowering Operator. a^dagger can be rewritten in terms of position and momentum. We can represent a^dagger as a matrix, which will be its default basis. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. Examples ======== Create a Raising Operator and rewrite it in terms of position and momentum, and show that taking its adjoint returns 'a': >>> from sympy.physics.quantum.sho1d import RaisingOp >>> from sympy.physics.quantum import Dagger >>> ad = RaisingOp('a') >>> ad.rewrite('xp').doit() sqrt(2)*(m*omega*X - I*Px)/(2*sqrt(hbar)*sqrt(m*omega)) >>> Dagger(ad) a Taking the commutator of a^dagger with other Operators: >>> from sympy.physics.quantum import Commutator >>> from sympy.physics.quantum.sho1d import RaisingOp, LoweringOp >>> from sympy.physics.quantum.sho1d import NumberOp >>> ad = RaisingOp('a') >>> a = LoweringOp('a') >>> N = NumberOp('N') >>> Commutator(ad, a).doit() -1 >>> Commutator(ad, N).doit() -RaisingOp(a) Apply a^dagger to a state: >>> from sympy.physics.quantum import qapply >>> from sympy.physics.quantum.sho1d import RaisingOp, SHOKet >>> ad = RaisingOp('a') >>> k = SHOKet('k') >>> qapply(ad*k) sqrt(k + 1)*|k + 1> Matrix Representation >>> from sympy.physics.quantum.sho1d import RaisingOp >>> from sympy.physics.quantum.represent import represent >>> ad = RaisingOp('a') >>> represent(ad, basis=N, ndim=4, format='sympy') Matrix([ [0, 0, 0, 0], [1, 0, 0, 0], [0, sqrt(2), 0, 0], [0, 0, sqrt(3), 0]]) """ def _eval_rewrite_as_xp(self, *args, **kwargs): return (Integer(1)/sqrt(Integer(2)*hbar*m*omega))*( Integer(-1)*I*Px + m*omega*X) def _eval_adjoint(self): return LoweringOp(*self.args) def _eval_commutator_LoweringOp(self, other): return Integer(-1) def _eval_commutator_NumberOp(self, other): return Integer(-1)*self def _apply_operator_SHOKet(self, ket): temp = ket.n + Integer(1) return sqrt(temp)*SHOKet(temp) def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_XOp(self, basis, **options): # This logic is good but the underlying position # representation logic is broken. # temp = self.rewrite('xp').doit() # result = represent(temp, basis=X) # return result raise NotImplementedError('Position representation is not implemented') def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format','sympy') matrix = matrix_zeros(ndim_info, ndim_info, **options) for i in range(ndim_info - 1): value = sqrt(i + 1) if format == 'scipy.sparse': value = float(value) matrix[i + 1, i] = value if format == 'scipy.sparse': matrix = matrix.tocsr() return matrix #-------------------------------------------------------------------------- # Printing Methods #-------------------------------------------------------------------------- def _print_contents(self, printer, *args): arg0 = printer._print(self.args[0], *args) return '%s(%s)' % (self.__class__.__name__, arg0) def _print_contents_pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm pform = printer._print(self.args[0], *args) pform = pform**prettyForm('\N{DAGGER}') return pform def _print_contents_latex(self, printer, *args): arg = printer._print(self.args[0]) return '%s^{\\dagger}' % arg class LoweringOp(SHOOp): """The Lowering Operator or 'a'. When 'a' acts on a state it lowers the state up by one. Taking the adjoint of 'a' returns a^dagger, the Raising Operator. 'a' can be rewritten in terms of position and momentum. We can represent 'a' as a matrix, which will be its default basis. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. Examples ======== Create a Lowering Operator and rewrite it in terms of position and momentum, and show that taking its adjoint returns a^dagger: >>> from sympy.physics.quantum.sho1d import LoweringOp >>> from sympy.physics.quantum import Dagger >>> a = LoweringOp('a') >>> a.rewrite('xp').doit() sqrt(2)*(m*omega*X + I*Px)/(2*sqrt(hbar)*sqrt(m*omega)) >>> Dagger(a) RaisingOp(a) Taking the commutator of 'a' with other Operators: >>> from sympy.physics.quantum import Commutator >>> from sympy.physics.quantum.sho1d import LoweringOp, RaisingOp >>> from sympy.physics.quantum.sho1d import NumberOp >>> a = LoweringOp('a') >>> ad = RaisingOp('a') >>> N = NumberOp('N') >>> Commutator(a, ad).doit() 1 >>> Commutator(a, N).doit() a Apply 'a' to a state: >>> from sympy.physics.quantum import qapply >>> from sympy.physics.quantum.sho1d import LoweringOp, SHOKet >>> a = LoweringOp('a') >>> k = SHOKet('k') >>> qapply(a*k) sqrt(k)*|k - 1> Taking 'a' of the lowest state will return 0: >>> from sympy.physics.quantum import qapply >>> from sympy.physics.quantum.sho1d import LoweringOp, SHOKet >>> a = LoweringOp('a') >>> k = SHOKet(0) >>> qapply(a*k) 0 Matrix Representation >>> from sympy.physics.quantum.sho1d import LoweringOp >>> from sympy.physics.quantum.represent import represent >>> a = LoweringOp('a') >>> represent(a, basis=N, ndim=4, format='sympy') Matrix([ [0, 1, 0, 0], [0, 0, sqrt(2), 0], [0, 0, 0, sqrt(3)], [0, 0, 0, 0]]) """ def _eval_rewrite_as_xp(self, *args, **kwargs): return (Integer(1)/sqrt(Integer(2)*hbar*m*omega))*( I*Px + m*omega*X) def _eval_adjoint(self): return RaisingOp(*self.args) def _eval_commutator_RaisingOp(self, other): return Integer(1) def _eval_commutator_NumberOp(self, other): return Integer(1)*self def _apply_operator_SHOKet(self, ket): temp = ket.n - Integer(1) if ket.n == Integer(0): return Integer(0) else: return sqrt(ket.n)*SHOKet(temp) def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_XOp(self, basis, **options): # This logic is good but the underlying position # representation logic is broken. # temp = self.rewrite('xp').doit() # result = represent(temp, basis=X) # return result raise NotImplementedError('Position representation is not implemented') def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') matrix = matrix_zeros(ndim_info, ndim_info, **options) for i in range(ndim_info - 1): value = sqrt(i + 1) if format == 'scipy.sparse': value = float(value) matrix[i,i + 1] = value if format == 'scipy.sparse': matrix = matrix.tocsr() return matrix class NumberOp(SHOOp): """The Number Operator is simply a^dagger*a It is often useful to write a^dagger*a as simply the Number Operator because the Number Operator commutes with the Hamiltonian. And can be expressed using the Number Operator. Also the Number Operator can be applied to states. We can represent the Number Operator as a matrix, which will be its default basis. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. Examples ======== Create a Number Operator and rewrite it in terms of the ladder operators, position and momentum operators, and Hamiltonian: >>> from sympy.physics.quantum.sho1d import NumberOp >>> N = NumberOp('N') >>> N.rewrite('a').doit() RaisingOp(a)*a >>> N.rewrite('xp').doit() -1/2 + (m**2*omega**2*X**2 + Px**2)/(2*hbar*m*omega) >>> N.rewrite('H').doit() -1/2 + H/(hbar*omega) Take the Commutator of the Number Operator with other Operators: >>> from sympy.physics.quantum import Commutator >>> from sympy.physics.quantum.sho1d import NumberOp, Hamiltonian >>> from sympy.physics.quantum.sho1d import RaisingOp, LoweringOp >>> N = NumberOp('N') >>> H = Hamiltonian('H') >>> ad = RaisingOp('a') >>> a = LoweringOp('a') >>> Commutator(N,H).doit() 0 >>> Commutator(N,ad).doit() RaisingOp(a) >>> Commutator(N,a).doit() -a Apply the Number Operator to a state: >>> from sympy.physics.quantum import qapply >>> from sympy.physics.quantum.sho1d import NumberOp, SHOKet >>> N = NumberOp('N') >>> k = SHOKet('k') >>> qapply(N*k) k*|k> Matrix Representation >>> from sympy.physics.quantum.sho1d import NumberOp >>> from sympy.physics.quantum.represent import represent >>> N = NumberOp('N') >>> represent(N, basis=N, ndim=4, format='sympy') Matrix([ [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]) """ def _eval_rewrite_as_a(self, *args, **kwargs): return ad*a def _eval_rewrite_as_xp(self, *args, **kwargs): return (Integer(1)/(Integer(2)*m*hbar*omega))*(Px**2 + ( m*omega*X)**2) - Integer(1)/Integer(2) def _eval_rewrite_as_H(self, *args, **kwargs): return H/(hbar*omega) - Integer(1)/Integer(2) def _apply_operator_SHOKet(self, ket): return ket.n*ket def _eval_commutator_Hamiltonian(self, other): return Integer(0) def _eval_commutator_RaisingOp(self, other): return other def _eval_commutator_LoweringOp(self, other): return Integer(-1)*other def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_XOp(self, basis, **options): # This logic is good but the underlying position # representation logic is broken. # temp = self.rewrite('xp').doit() # result = represent(temp, basis=X) # return result raise NotImplementedError('Position representation is not implemented') def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') matrix = matrix_zeros(ndim_info, ndim_info, **options) for i in range(ndim_info): value = i if format == 'scipy.sparse': value = float(value) matrix[i,i] = value if format == 'scipy.sparse': matrix = matrix.tocsr() return matrix class Hamiltonian(SHOOp): """The Hamiltonian Operator. The Hamiltonian is used to solve the time-independent Schrodinger equation. The Hamiltonian can be expressed using the ladder operators, as well as by position and momentum. We can represent the Hamiltonian Operator as a matrix, which will be its default basis. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. Examples ======== Create a Hamiltonian Operator and rewrite it in terms of the ladder operators, position and momentum, and the Number Operator: >>> from sympy.physics.quantum.sho1d import Hamiltonian >>> H = Hamiltonian('H') >>> H.rewrite('a').doit() hbar*omega*(1/2 + RaisingOp(a)*a) >>> H.rewrite('xp').doit() (m**2*omega**2*X**2 + Px**2)/(2*m) >>> H.rewrite('N').doit() hbar*omega*(1/2 + N) Take the Commutator of the Hamiltonian and the Number Operator: >>> from sympy.physics.quantum import Commutator >>> from sympy.physics.quantum.sho1d import Hamiltonian, NumberOp >>> H = Hamiltonian('H') >>> N = NumberOp('N') >>> Commutator(H,N).doit() 0 Apply the Hamiltonian Operator to a state: >>> from sympy.physics.quantum import qapply >>> from sympy.physics.quantum.sho1d import Hamiltonian, SHOKet >>> H = Hamiltonian('H') >>> k = SHOKet('k') >>> qapply(H*k) hbar*k*omega*|k> + hbar*omega*|k>/2 Matrix Representation >>> from sympy.physics.quantum.sho1d import Hamiltonian >>> from sympy.physics.quantum.represent import represent >>> H = Hamiltonian('H') >>> represent(H, basis=N, ndim=4, format='sympy') Matrix([ [hbar*omega/2, 0, 0, 0], [ 0, 3*hbar*omega/2, 0, 0], [ 0, 0, 5*hbar*omega/2, 0], [ 0, 0, 0, 7*hbar*omega/2]]) """ def _eval_rewrite_as_a(self, *args, **kwargs): return hbar*omega*(ad*a + Integer(1)/Integer(2)) def _eval_rewrite_as_xp(self, *args, **kwargs): return (Integer(1)/(Integer(2)*m))*(Px**2 + (m*omega*X)**2) def _eval_rewrite_as_N(self, *args, **kwargs): return hbar*omega*(N + Integer(1)/Integer(2)) def _apply_operator_SHOKet(self, ket): return (hbar*omega*(ket.n + Integer(1)/Integer(2)))*ket def _eval_commutator_NumberOp(self, other): return Integer(0) def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_XOp(self, basis, **options): # This logic is good but the underlying position # representation logic is broken. # temp = self.rewrite('xp').doit() # result = represent(temp, basis=X) # return result raise NotImplementedError('Position representation is not implemented') def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') matrix = matrix_zeros(ndim_info, ndim_info, **options) for i in range(ndim_info): value = i + Integer(1)/Integer(2) if format == 'scipy.sparse': value = float(value) matrix[i,i] = value if format == 'scipy.sparse': matrix = matrix.tocsr() return hbar*omega*matrix #------------------------------------------------------------------------------ class SHOState(State): """State class for SHO states""" @classmethod def _eval_hilbert_space(cls, label): return ComplexSpace(S.Infinity) @property def n(self): return self.args[0] class SHOKet(SHOState, Ket): """1D eigenket. Inherits from SHOState and Ket. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket This is usually its quantum numbers or its symbol. Examples ======== Ket's know about their associated bra: >>> from sympy.physics.quantum.sho1d import SHOKet >>> k = SHOKet('k') >>> k.dual <k| >>> k.dual_class() <class 'sympy.physics.quantum.sho1d.SHOBra'> Take the Inner Product with a bra: >>> from sympy.physics.quantum import InnerProduct >>> from sympy.physics.quantum.sho1d import SHOKet, SHOBra >>> k = SHOKet('k') >>> b = SHOBra('b') >>> InnerProduct(b,k).doit() KroneckerDelta(b, k) Vector representation of a numerical state ket: >>> from sympy.physics.quantum.sho1d import SHOKet, NumberOp >>> from sympy.physics.quantum.represent import represent >>> k = SHOKet(3) >>> N = NumberOp('N') >>> represent(k, basis=N, ndim=4) Matrix([ [0], [0], [0], [1]]) """ @classmethod def dual_class(self): return SHOBra def _eval_innerproduct_SHOBra(self, bra, **hints): result = KroneckerDelta(self.n, bra.n) return result def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') options['spmatrix'] = 'lil' vector = matrix_zeros(ndim_info, 1, **options) if isinstance(self.n, Integer): if self.n >= ndim_info: return ValueError("N-Dimension too small") if format == 'scipy.sparse': vector[int(self.n), 0] = 1.0 vector = vector.tocsr() elif format == 'numpy': vector[int(self.n), 0] = 1.0 else: vector[self.n, 0] = Integer(1) return vector else: return ValueError("Not Numerical State") class SHOBra(SHOState, Bra): """A time-independent Bra in SHO. Inherits from SHOState and Bra. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket This is usually its quantum numbers or its symbol. Examples ======== Bra's know about their associated ket: >>> from sympy.physics.quantum.sho1d import SHOBra >>> b = SHOBra('b') >>> b.dual |b> >>> b.dual_class() <class 'sympy.physics.quantum.sho1d.SHOKet'> Vector representation of a numerical state bra: >>> from sympy.physics.quantum.sho1d import SHOBra, NumberOp >>> from sympy.physics.quantum.represent import represent >>> b = SHOBra(3) >>> N = NumberOp('N') >>> represent(b, basis=N, ndim=4) Matrix([[0, 0, 0, 1]]) """ @classmethod def dual_class(self): return SHOKet def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') options['spmatrix'] = 'lil' vector = matrix_zeros(1, ndim_info, **options) if isinstance(self.n, Integer): if self.n >= ndim_info: return ValueError("N-Dimension too small") if format == 'scipy.sparse': vector[0, int(self.n)] = 1.0 vector = vector.tocsr() elif format == 'numpy': vector[0, int(self.n)] = 1.0 else: vector[0, self.n] = Integer(1) return vector else: return ValueError("Not Numerical State") ad = RaisingOp('a') a = LoweringOp('a') H = Hamiltonian('H') N = NumberOp('N') omega = Symbol('omega') m = Symbol('m')
2758df06011f839c4ccf56b17bbf7e60f0893eded6c964493e942a57c179c4a2
from __future__ import print_function, division 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.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.exceptions import SymPyDeprecationWarning from sympy.utilities.iterables import iterable __all__ = ['KanesMethod'] class KanesMethod(object): """Kane's method object. 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 bodylist : iterable Iterable of Point and RigidBody objects in the system. forcelist : 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): """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 = None self._bodylist = None 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 = dict((i, 0) for i in self.u) udot_zero = dict((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 = dict((i, 0) for i in u) uaux_zero = dict((i, 0) for i in self._uaux) qdot_zero = dict((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 = dict((i, 0) for i in self._udot) uaux_zero = dict((i, 0) for i in self._uaux) uauxdot = [diff(i, t) for i in self._uaux] uauxdot_zero = dict((i, 0) for i in uauxdot) # Dictionary of q' and q'' to u and u' q_ddot_u_map = dict((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 = dict((i, 0) for i in self.u) ud_zero = dict((i, 0) for i in self._udot) qd_zero = dict((i, 0) for i in self._qdot) qd_u_zero = dict((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 = dict((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. 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, loads=None): """ Method to form Kane's equations, Fr + Fr* = 0. 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 and loads is not None) or isinstance(bodies[0], tuple): # This switches the order if they use the old way. bodies, loads = loads, bodies SymPyDeprecationWarning(value='The API for kanes_equations() has changed such ' 'that the loads (forces and torques) are now the second argument ' 'and is optional with None being the default.', feature='The kanes_equation() argument order', useinstead='switched argument order to update your code, For example: ' 'kanes_equations(loads, bodies) > kanes_equations(bodies, loads).', issue=10945, deprecated_since_version="1.1").warn() 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 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
a5294c6ec7f028bc1234caf1a27203ea5ca0530061658e76a8bd074b0ff3f391
from __future__ import print_function, division from sympy.utilities import dict_merge from sympy.utilities.iterables import iterable from sympy.physics.vector import (Dyadic, Vector, ReferenceFrame, Point, dynamicsymbols) from sympy.physics.vector.printing import (vprint, vsprint, vpprint, vlatex, init_vprinting) from sympy.physics.mechanics.particle import Particle from sympy.physics.mechanics.rigidbody import RigidBody from sympy import simplify from sympy.core.backend import (Matrix, sympify, Mul, Derivative, sin, cos, tan, AppliedUndef, S) __all__ = ['inertia', 'inertia_of_point_mass', 'linear_momentum', 'angular_momentum', 'kinetic_energy', 'potential_energy', 'Lagrangian', 'mechanics_printing', 'mprint', 'msprint', 'mpprint', 'mlatex', 'msubs', 'find_dynamicsymbols'] # These are functions that we've moved and renamed during extracting the # basic vector calculus code from the mechanics packages. mprint = vprint msprint = vsprint mpprint = vpprint mlatex = vlatex def mechanics_printing(**kwargs): """ Initializes time derivative printing for all SymPy objects in mechanics module. """ init_vprinting(**kwargs) mechanics_printing.__doc__ = init_vprinting.__doc__ def inertia(frame, ixx, iyy, izz, ixy=0, iyz=0, izx=0): """Simple way to create inertia Dyadic object. If you don't know what a Dyadic is, just treat this like the inertia tensor. Then, do the easy thing and define it in a body-fixed frame. Parameters ========== frame : ReferenceFrame The frame the inertia is defined in ixx : Sympifyable the xx element in the inertia dyadic iyy : Sympifyable the yy element in the inertia dyadic izz : Sympifyable the zz element in the inertia dyadic ixy : Sympifyable the xy element in the inertia dyadic iyz : Sympifyable the yz element in the inertia dyadic izx : Sympifyable the zx element in the inertia dyadic Examples ======== >>> from sympy.physics.mechanics import ReferenceFrame, inertia >>> N = ReferenceFrame('N') >>> inertia(N, 1, 2, 3) (N.x|N.x) + 2*(N.y|N.y) + 3*(N.z|N.z) """ if not isinstance(frame, ReferenceFrame): raise TypeError('Need to define the inertia in a frame') ol = sympify(ixx) * (frame.x | frame.x) ol += sympify(ixy) * (frame.x | frame.y) ol += sympify(izx) * (frame.x | frame.z) ol += sympify(ixy) * (frame.y | frame.x) ol += sympify(iyy) * (frame.y | frame.y) ol += sympify(iyz) * (frame.y | frame.z) ol += sympify(izx) * (frame.z | frame.x) ol += sympify(iyz) * (frame.z | frame.y) ol += sympify(izz) * (frame.z | frame.z) return ol def inertia_of_point_mass(mass, pos_vec, frame): """Inertia dyadic of a point mass relative to point O. Parameters ========== mass : Sympifyable Mass of the point mass pos_vec : Vector Position from point O to point mass frame : ReferenceFrame Reference frame to express the dyadic in Examples ======== >>> from sympy import symbols >>> from sympy.physics.mechanics import ReferenceFrame, inertia_of_point_mass >>> N = ReferenceFrame('N') >>> r, m = symbols('r m') >>> px = r * N.x >>> inertia_of_point_mass(m, px, N) m*r**2*(N.y|N.y) + m*r**2*(N.z|N.z) """ return mass * (((frame.x | frame.x) + (frame.y | frame.y) + (frame.z | frame.z)) * (pos_vec & pos_vec) - (pos_vec | pos_vec)) def linear_momentum(frame, *body): """Linear momentum of the system. This function returns the linear momentum of a system of Particle's and/or RigidBody's. The linear momentum of a system is equal to the vector sum of the linear momentum of its constituents. Consider a system, S, comprised of a rigid body, A, and a particle, P. The linear momentum of the system, L, is equal to the vector sum of the linear momentum of the particle, L1, and the linear momentum of the rigid body, L2, i.e. L = L1 + L2 Parameters ========== frame : ReferenceFrame The frame in which linear momentum is desired. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose linear momentum is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, linear_momentum >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = Point('Ac') >>> Ac.set_vel(N, 25 * N.y) >>> I = outer(N.x, N.x) >>> A = RigidBody('A', Ac, N, 20, (I, Ac)) >>> linear_momentum(N, A, Pa) 10*N.x + 500*N.y """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please specify a valid ReferenceFrame') else: linear_momentum_sys = Vector(0) for e in body: if isinstance(e, (RigidBody, Particle)): linear_momentum_sys += e.linear_momentum(frame) else: raise TypeError('*body must have only Particle or RigidBody') return linear_momentum_sys def angular_momentum(point, frame, *body): """Angular momentum of a system This function returns the angular momentum of a system of Particle's and/or RigidBody's. The angular momentum of such a system is equal to the vector sum of the angular momentum of its constituents. Consider a system, S, comprised of a rigid body, A, and a particle, P. The angular momentum of the system, H, is equal to the vector sum of the angular momentum of the particle, H1, and the angular momentum of the rigid body, H2, i.e. H = H1 + H2 Parameters ========== point : Point The point about which angular momentum of the system is desired. frame : ReferenceFrame The frame in which angular momentum is desired. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose angular momentum is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, angular_momentum >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> Ac.set_vel(N, 5 * N.y) >>> a = ReferenceFrame('a') >>> a.set_ang_vel(N, 10 * N.z) >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) >>> angular_momentum(O, N, Pa, A) 10*N.z """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please enter a valid ReferenceFrame') if not isinstance(point, Point): raise TypeError('Please specify a valid Point') else: angular_momentum_sys = Vector(0) for e in body: if isinstance(e, (RigidBody, Particle)): angular_momentum_sys += e.angular_momentum(point, frame) else: raise TypeError('*body must have only Particle or RigidBody') return angular_momentum_sys def kinetic_energy(frame, *body): """Kinetic energy of a multibody system. This function returns the kinetic energy of a system of Particle's and/or RigidBody's. The kinetic energy of such a system is equal to the sum of the kinetic energies of its constituents. Consider a system, S, comprising a rigid body, A, and a particle, P. The kinetic energy of the system, T, is equal to the vector sum of the kinetic energy of the particle, T1, and the kinetic energy of the rigid body, T2, i.e. T = T1 + T2 Kinetic energy is a scalar. Parameters ========== frame : ReferenceFrame The frame in which the velocity or angular velocity of the body is defined. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose kinetic energy is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, kinetic_energy >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> Ac.set_vel(N, 5 * N.y) >>> a = ReferenceFrame('a') >>> a.set_ang_vel(N, 10 * N.z) >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) >>> kinetic_energy(N, Pa, A) 350 """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please enter a valid ReferenceFrame') ke_sys = S.Zero for e in body: if isinstance(e, (RigidBody, Particle)): ke_sys += e.kinetic_energy(frame) else: raise TypeError('*body must have only Particle or RigidBody') return ke_sys def potential_energy(*body): """Potential energy of a multibody system. This function returns the potential energy of a system of Particle's and/or RigidBody's. The potential energy of such a system is equal to the sum of the potential energy of its constituents. Consider a system, S, comprising a rigid body, A, and a particle, P. The potential energy of the system, V, is equal to the vector sum of the potential energy of the particle, V1, and the potential energy of the rigid body, V2, i.e. V = V1 + V2 Potential energy is a scalar. Parameters ========== body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose potential energy is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, potential_energy >>> from sympy import symbols >>> M, m, g, h = symbols('M m g h') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> Pa = Particle('Pa', P, m) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> a = ReferenceFrame('a') >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, M, (I, Ac)) >>> Pa.potential_energy = m * g * h >>> A.potential_energy = M * g * h >>> potential_energy(Pa, A) M*g*h + g*h*m """ pe_sys = S.Zero for e in body: if isinstance(e, (RigidBody, Particle)): pe_sys += e.potential_energy else: raise TypeError('*body must have only Particle or RigidBody') return pe_sys def gravity(acceleration, *bodies): """ Returns a list of gravity forces given the acceleration due to gravity and any number of particles or rigidbodies. Example ======= >>> from sympy.physics.mechanics import ReferenceFrame, Point, Particle, outer, RigidBody >>> from sympy.physics.mechanics.functions import gravity >>> from sympy import symbols >>> N = ReferenceFrame('N') >>> m, M, g = symbols('m M g') >>> F1, F2 = symbols('F1 F2') >>> po = Point('po') >>> pa = Particle('pa', po, m) >>> A = ReferenceFrame('A') >>> P = Point('P') >>> I = outer(A.x, A.x) >>> B = RigidBody('B', P, A, M, (I, P)) >>> forceList = [(po, F1), (P, F2)] >>> forceList.extend(gravity(g*N.y, pa, B)) >>> forceList [(po, F1), (P, F2), (po, g*m*N.y), (P, M*g*N.y)] """ gravity_force = [] if not bodies: raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.") for e in bodies: point = getattr(e, 'masscenter', None) if point is None: point = e.point gravity_force.append((point, e.mass*acceleration)) return gravity_force def center_of_mass(point, *bodies): """ Returns the position vector from the given point to the center of mass of the given bodies(particles or rigidbodies). Example ======= >>> from sympy import symbols, S >>> from sympy.physics.vector import Point >>> from sympy.physics.mechanics import Particle, ReferenceFrame, RigidBody, outer >>> from sympy.physics.mechanics.functions import center_of_mass >>> a = ReferenceFrame('a') >>> m = symbols('m', real=True) >>> p1 = Particle('p1', Point('p1_pt'), S(1)) >>> p2 = Particle('p2', Point('p2_pt'), S(2)) >>> p3 = Particle('p3', Point('p3_pt'), S(3)) >>> p4 = Particle('p4', Point('p4_pt'), m) >>> b_f = ReferenceFrame('b_f') >>> b_cm = Point('b_cm') >>> mb = symbols('mb') >>> b = RigidBody('b', b_cm, b_f, mb, (outer(b_f.x, b_f.x), b_cm)) >>> p2.point.set_pos(p1.point, a.x) >>> p3.point.set_pos(p1.point, a.x + a.y) >>> p4.point.set_pos(p1.point, a.y) >>> b.masscenter.set_pos(p1.point, a.y + a.z) >>> point_o=Point('o') >>> point_o.set_pos(p1.point, center_of_mass(p1.point, p1, p2, p3, p4, b)) >>> expr = 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z >>> point_o.pos_from(p1.point) 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z """ if not bodies: raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.") total_mass = 0 vec = Vector(0) for i in bodies: total_mass += i.mass masscenter = getattr(i, 'masscenter', None) if masscenter is None: masscenter = i.point vec += i.mass*masscenter.pos_from(point) return vec/total_mass def Lagrangian(frame, *body): """Lagrangian of a multibody system. This function returns the Lagrangian of a system of Particle's and/or RigidBody's. The Lagrangian of such a system is equal to the difference between the kinetic energies and potential energies of its constituents. If T and V are the kinetic and potential energies of a system then it's Lagrangian, L, is defined as L = T - V The Lagrangian is a scalar. Parameters ========== frame : ReferenceFrame The frame in which the velocity or angular velocity of the body is defined to determine the kinetic energy. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose Lagrangian is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, Lagrangian >>> from sympy import symbols >>> M, m, g, h = symbols('M m g h') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> Ac.set_vel(N, 5 * N.y) >>> a = ReferenceFrame('a') >>> a.set_ang_vel(N, 10 * N.z) >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) >>> Pa.potential_energy = m * g * h >>> A.potential_energy = M * g * h >>> Lagrangian(N, Pa, A) -M*g*h - g*h*m + 350 """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please supply a valid ReferenceFrame') for e in body: if not isinstance(e, (RigidBody, Particle)): raise TypeError('*body must have only Particle or RigidBody') return kinetic_energy(frame, *body) - potential_energy(*body) def find_dynamicsymbols(expression, exclude=None, reference_frame=None): """Find all dynamicsymbols in expression. If the optional ``exclude`` kwarg is used, only dynamicsymbols not in the iterable ``exclude`` are returned. If we intend to apply this function on a vector, the optional ''reference_frame'' is also used to inform about the corresponding frame with respect to which the dynamic symbols of the given vector is to be determined. Parameters ========== expression : sympy expression exclude : iterable of dynamicsymbols, optional reference_frame : ReferenceFrame, optional The frame with respect to which the dynamic symbols of the given vector is to be determined. Examples ======== >>> from sympy.physics.mechanics import dynamicsymbols, find_dynamicsymbols >>> from sympy.physics.mechanics import ReferenceFrame >>> x, y = dynamicsymbols('x, y') >>> expr = x + x.diff()*y >>> find_dynamicsymbols(expr) {x(t), y(t), Derivative(x(t), t)} >>> find_dynamicsymbols(expr, exclude=[x, y]) {Derivative(x(t), t)} >>> a, b, c = dynamicsymbols('a, b, c') >>> A = ReferenceFrame('A') >>> v = a * A.x + b * A.y + c * A.z >>> find_dynamicsymbols(v, reference_frame=A) {a(t), b(t), c(t)} """ t_set = {dynamicsymbols._t} if exclude: if iterable(exclude): exclude_set = set(exclude) else: raise TypeError("exclude kwarg must be iterable") else: exclude_set = set() if isinstance(expression, Vector): if reference_frame is None: raise ValueError("You must provide reference_frame when passing a " "vector expression, got %s." % reference_frame) else: expression = expression.to_matrix(reference_frame) return set([i for i in expression.atoms(AppliedUndef, Derivative) if i.free_symbols == t_set]) - exclude_set def msubs(expr, *sub_dicts, smart=False, **kwargs): """A custom subs for use on expressions derived in physics.mechanics. Traverses the expression tree once, performing the subs found in sub_dicts. Terms inside ``Derivative`` expressions are ignored: >>> from sympy.physics.mechanics import dynamicsymbols, msubs >>> x = dynamicsymbols('x') >>> msubs(x.diff() + x, {x: 1}) Derivative(x(t), t) + 1 Note that sub_dicts can be a single dictionary, or several dictionaries: >>> x, y, z = dynamicsymbols('x, y, z') >>> sub1 = {x: 1, y: 2} >>> sub2 = {z: 3, x.diff(): 4} >>> msubs(x.diff() + x + y + z, sub1, sub2) 10 If smart=True (default False), also checks for conditions that may result in ``nan``, but if simplified would yield a valid expression. For example: >>> from sympy import sin, tan >>> (sin(x)/tan(x)).subs(x, 0) nan >>> msubs(sin(x)/tan(x), {x: 0}, smart=True) 1 It does this by first replacing all ``tan`` with ``sin/cos``. Then each node is traversed. If the node is a fraction, subs is first evaluated on the denominator. If this results in 0, simplification of the entire fraction is attempted. Using this selective simplification, only subexpressions that result in 1/0 are targeted, resulting in faster performance. """ sub_dict = dict_merge(*sub_dicts) if smart: func = _smart_subs elif hasattr(expr, 'msubs'): return expr.msubs(sub_dict) else: func = lambda expr, sub_dict: _crawl(expr, _sub_func, sub_dict) if isinstance(expr, (Matrix, Vector, Dyadic)): return expr.applyfunc(lambda x: func(x, sub_dict)) else: return func(expr, sub_dict) def _crawl(expr, func, *args, **kwargs): """Crawl the expression tree, and apply func to every node.""" val = func(expr, *args, **kwargs) if val is not None: return val new_args = (_crawl(arg, func, *args, **kwargs) for arg in expr.args) return expr.func(*new_args) def _sub_func(expr, sub_dict): """Perform direct matching substitution, ignoring derivatives.""" if expr in sub_dict: return sub_dict[expr] elif not expr.args or expr.is_Derivative: return expr def _tan_repl_func(expr): """Replace tan with sin/cos.""" if isinstance(expr, tan): return sin(*expr.args) / cos(*expr.args) elif not expr.args or expr.is_Derivative: return expr def _smart_subs(expr, sub_dict): """Performs subs, checking for conditions that may result in `nan` or `oo`, and attempts to simplify them out. The expression tree is traversed twice, and the following steps are performed on each expression node: - First traverse: Replace all `tan` with `sin/cos`. - Second traverse: If node is a fraction, check if the denominator evaluates to 0. If so, attempt to simplify it out. Then if node is in sub_dict, sub in the corresponding value.""" expr = _crawl(expr, _tan_repl_func) def _recurser(expr, sub_dict): # Decompose the expression into num, den num, den = _fraction_decomp(expr) if den != 1: # If there is a non trivial denominator, we need to handle it denom_subbed = _recurser(den, sub_dict) if denom_subbed.evalf() == 0: # If denom is 0 after this, attempt to simplify the bad expr expr = simplify(expr) else: # Expression won't result in nan, find numerator num_subbed = _recurser(num, sub_dict) return num_subbed / denom_subbed # We have to crawl the tree manually, because `expr` may have been # modified in the simplify step. First, perform subs as normal: val = _sub_func(expr, sub_dict) if val is not None: return val new_args = (_recurser(arg, sub_dict) for arg in expr.args) return expr.func(*new_args) return _recurser(expr, sub_dict) def _fraction_decomp(expr): """Return num, den such that expr = num/den""" if not isinstance(expr, Mul): return expr, 1 num = [] den = [] for a in expr.args: if a.is_Pow and a.args[1] < 0: den.append(1 / a) else: num.append(a) if not den: return expr, 1 num = Mul(*num) den = Mul(*den) return num, den def _f_list_parser(fl, ref_frame): """Parses the provided forcelist composed of items of the form (obj, force). Returns a tuple containing: vel_list: The velocity (ang_vel for Frames, vel for Points) in the provided reference frame. f_list: The forces. Used internally in the KanesMethod and LagrangesMethod classes. """ def flist_iter(): for pair in fl: obj, force = pair if isinstance(obj, ReferenceFrame): yield obj.ang_vel_in(ref_frame), force elif isinstance(obj, Point): yield obj.vel(ref_frame), force else: raise TypeError('First entry in each forcelist pair must ' 'be a point or frame.') if not fl: vel_list, f_list = (), () else: unzip = lambda l: list(zip(*l)) if l[0] else [(), ()] vel_list, f_list = unzip(list(flist_iter())) return vel_list, f_list
7040b98ab8b847670addafadf980e8e594904ccbeaf6e9ec1869eb6b8cf8d5cb
""" Definition of physical dimensions. Unit systems will be constructed on top of these dimensions. Most of the examples in the doc use MKS system and are presented from the computer point of view: from a human point, adding length to time is not legal in MKS but it is in natural system; for a computer in natural system there is no time dimension (but a velocity dimension instead) - in the basis - so the question of adding time to length has no meaning. """ from __future__ import division from typing import Dict as tDict import collections from sympy import (Integer, Matrix, S, Symbol, sympify, Basic, Tuple, Dict, default_sort_key) from sympy.core.compatibility import reduce from sympy.core.expr import Expr from sympy.core.power import Pow from sympy.utilities.exceptions import SymPyDeprecationWarning class _QuantityMapper(object): _quantity_scale_factors_global = {} # type: tDict[Expr, Expr] _quantity_dimensional_equivalence_map_global = {} # type: tDict[Expr, Expr] _quantity_dimension_global = {} # type: tDict[Expr, Expr] def __init__(self, *args, **kwargs): self._quantity_dimension_map = {} self._quantity_scale_factors = {} def set_quantity_dimension(self, unit, dimension): from sympy.physics.units import Quantity dimension = sympify(dimension) if not isinstance(dimension, Dimension): if dimension == 1: dimension = Dimension(1) else: raise ValueError("expected dimension or 1") elif isinstance(dimension, Quantity): dimension = self.get_quantity_dimension(dimension) self._quantity_dimension_map[unit] = dimension def set_quantity_scale_factor(self, unit, scale_factor): from sympy.physics.units import Quantity from sympy.physics.units.prefixes import Prefix scale_factor = sympify(scale_factor) # replace all prefixes by their ratio to canonical units: scale_factor = scale_factor.replace( lambda x: isinstance(x, Prefix), lambda x: x.scale_factor ) # replace all quantities by their ratio to canonical units: scale_factor = scale_factor.replace( lambda x: isinstance(x, Quantity), lambda x: self.get_quantity_scale_factor(x) ) self._quantity_scale_factors[unit] = scale_factor def get_quantity_dimension(self, unit): from sympy.physics.units import Quantity # First look-up the local dimension map, then the global one: if unit in self._quantity_dimension_map: return self._quantity_dimension_map[unit] if unit in self._quantity_dimension_global: return self._quantity_dimension_global[unit] if unit in self._quantity_dimensional_equivalence_map_global: dep_unit = self._quantity_dimensional_equivalence_map_global[unit] if isinstance(dep_unit, Quantity): return self.get_quantity_dimension(dep_unit) else: return Dimension(self.get_dimensional_expr(dep_unit)) if isinstance(unit, Quantity): return Dimension(unit.name) else: return Dimension(1) def get_quantity_scale_factor(self, unit): if unit in self._quantity_scale_factors: return self._quantity_scale_factors[unit] if unit in self._quantity_scale_factors_global: mul_factor, other_unit = self._quantity_scale_factors_global[unit] return mul_factor*self.get_quantity_scale_factor(other_unit) return S.One class Dimension(Expr): """ This class represent the dimension of a physical quantities. The ``Dimension`` constructor takes as parameters a name and an optional symbol. For example, in classical mechanics we know that time is different from temperature and dimensions make this difference (but they do not provide any measure of these quantites. >>> from sympy.physics.units import Dimension >>> length = Dimension('length') >>> length Dimension(length) >>> time = Dimension('time') >>> time Dimension(time) Dimensions can be composed using multiplication, division and exponentiation (by a number) to give new dimensions. Addition and subtraction is defined only when the two objects are the same dimension. >>> velocity = length / time >>> velocity Dimension(length/time) It is possible to use a dimension system object to get the dimensionsal dependencies of a dimension, for example the dimension system used by the SI units convention can be used: >>> from sympy.physics.units.systems.si import dimsys_SI >>> dimsys_SI.get_dimensional_dependencies(velocity) {'length': 1, 'time': -1} >>> length + length Dimension(length) >>> l2 = length**2 >>> l2 Dimension(length**2) >>> dimsys_SI.get_dimensional_dependencies(l2) {'length': 2} """ _op_priority = 13.0 # XXX: This doesn't seem to be used anywhere... _dimensional_dependencies = dict() # type: ignore is_commutative = True is_number = False # make sqrt(M**2) --> M is_positive = True is_real = True def __new__(cls, name, symbol=None): if isinstance(name, str): name = Symbol(name) else: name = sympify(name) if not isinstance(name, Expr): raise TypeError("Dimension name needs to be a valid math expression") if isinstance(symbol, str): symbol = Symbol(symbol) elif symbol is not None: assert isinstance(symbol, Symbol) if symbol is not None: obj = Expr.__new__(cls, name, symbol) else: obj = Expr.__new__(cls, name) obj._name = name obj._symbol = symbol return obj @property def name(self): return self._name @property def symbol(self): return self._symbol def __hash__(self): return Expr.__hash__(self) def __eq__(self, other): if isinstance(other, Dimension): return self.name == other.name return False def __str__(self): """ Display the string representation of the dimension. """ if self.symbol is None: return "Dimension(%s)" % (self.name) else: return "Dimension(%s, %s)" % (self.name, self.symbol) def __repr__(self): return self.__str__() def __neg__(self): return self def __add__(self, other): from sympy.physics.units.quantities import Quantity other = sympify(other) if isinstance(other, Basic): if other.has(Quantity): raise TypeError("cannot sum dimension and quantity") if isinstance(other, Dimension) and self == other: return self return super(Dimension, self).__add__(other) return self def __radd__(self, other): return self.__add__(other) def __sub__(self, other): # there is no notion of ordering (or magnitude) among dimension, # subtraction is equivalent to addition when the operation is legal return self + other def __rsub__(self, other): # there is no notion of ordering (or magnitude) among dimension, # subtraction is equivalent to addition when the operation is legal return self + other def __pow__(self, other): return self._eval_power(other) def _eval_power(self, other): other = sympify(other) return Dimension(self.name**other) def __mul__(self, other): from sympy.physics.units.quantities import Quantity if isinstance(other, Basic): if other.has(Quantity): raise TypeError("cannot sum dimension and quantity") if isinstance(other, Dimension): return Dimension(self.name*other.name) if not other.free_symbols: # other.is_number cannot be used return self return super(Dimension, self).__mul__(other) return self def __rmul__(self, other): return self.__mul__(other) def __truediv__(self, other): return self*Pow(other, -1) def __rtruediv__(self, other): return other * pow(self, -1) @classmethod def _from_dimensional_dependencies(cls, dependencies): return reduce(lambda x, y: x * y, ( Dimension(d)**e for d, e in dependencies.items() )) @classmethod def _get_dimensional_dependencies_for_name(cls, name): from sympy.physics.units.systems.si import dimsys_default SymPyDeprecationWarning( deprecated_since_version="1.2", issue=13336, feature="do not call from `Dimension` objects.", useinstead="DimensionSystem" ).warn() return dimsys_default.get_dimensional_dependencies(name) @property def is_dimensionless(self): """ Check if the dimension object really has a dimension. A dimension should have at least one component with non-zero power. """ if self.name == 1: return True from sympy.physics.units.systems.si import dimsys_default SymPyDeprecationWarning( deprecated_since_version="1.2", issue=13336, feature="wrong class", ).warn() dimensional_dependencies=dimsys_default return dimensional_dependencies.get_dimensional_dependencies(self) == {} def has_integer_powers(self, dim_sys): """ Check if the dimension object has only integer powers. All the dimension powers should be integers, but rational powers may appear in intermediate steps. This method may be used to check that the final result is well-defined. """ for dpow in dim_sys.get_dimensional_dependencies(self).values(): if not isinstance(dpow, (int, Integer)): return False return True # Create dimensions according the the base units in MKSA. # For other unit systems, they can be derived by transforming the base # dimensional dependency dictionary. class DimensionSystem(Basic, _QuantityMapper): r""" DimensionSystem represents a coherent set of dimensions. The constructor takes three parameters: - base dimensions; - derived dimensions: these are defined in terms of the base dimensions (for example velocity is defined from the division of length by time); - dependency of dimensions: how the derived dimensions depend on the base dimensions. Optionally either the ``derived_dims`` or the ``dimensional_dependencies`` may be omitted. """ def __new__(cls, base_dims, derived_dims=[], dimensional_dependencies={}, name=None, descr=None): dimensional_dependencies = dict(dimensional_dependencies) if (name is not None) or (descr is not None): SymPyDeprecationWarning( deprecated_since_version="1.2", issue=13336, useinstead="do not define a `name` or `descr`", ).warn() def parse_dim(dim): if isinstance(dim, str): dim = Dimension(Symbol(dim)) elif isinstance(dim, Dimension): pass elif isinstance(dim, Symbol): dim = Dimension(dim) else: raise TypeError("%s wrong type" % dim) return dim base_dims = [parse_dim(i) for i in base_dims] derived_dims = [parse_dim(i) for i in derived_dims] for dim in base_dims: dim = dim.name if (dim in dimensional_dependencies and (len(dimensional_dependencies[dim]) != 1 or dimensional_dependencies[dim].get(dim, None) != 1)): raise IndexError("Repeated value in base dimensions") dimensional_dependencies[dim] = Dict({dim: 1}) def parse_dim_name(dim): if isinstance(dim, Dimension): return dim.name elif isinstance(dim, str): return Symbol(dim) elif isinstance(dim, Symbol): return dim else: raise TypeError("unrecognized type %s for %s" % (type(dim), dim)) for dim in dimensional_dependencies.keys(): dim = parse_dim(dim) if (dim not in derived_dims) and (dim not in base_dims): derived_dims.append(dim) def parse_dict(d): return Dict({parse_dim_name(i): j for i, j in d.items()}) # Make sure everything is a SymPy type: dimensional_dependencies = {parse_dim_name(i): parse_dict(j) for i, j in dimensional_dependencies.items()} for dim in derived_dims: if dim in base_dims: raise ValueError("Dimension %s both in base and derived" % dim) if dim.name not in dimensional_dependencies: # TODO: should this raise a warning? dimensional_dependencies[dim.name] = Dict({dim.name: 1}) base_dims.sort(key=default_sort_key) derived_dims.sort(key=default_sort_key) base_dims = Tuple(*base_dims) derived_dims = Tuple(*derived_dims) dimensional_dependencies = Dict({i: Dict(j) for i, j in dimensional_dependencies.items()}) obj = Basic.__new__(cls, base_dims, derived_dims, dimensional_dependencies) return obj @property def base_dims(self): return self.args[0] @property def derived_dims(self): return self.args[1] @property def dimensional_dependencies(self): return self.args[2] def _get_dimensional_dependencies_for_name(self, name): if isinstance(name, Dimension): name = name.name if isinstance(name, str): name = Symbol(name) if name.is_Symbol: # Dimensions not included in the dependencies are considered # as base dimensions: return dict(self.dimensional_dependencies.get(name, {name: 1})) if name.is_Number: return {} get_for_name = self._get_dimensional_dependencies_for_name if name.is_Mul: ret = collections.defaultdict(int) dicts = [get_for_name(i) for i in name.args] for d in dicts: for k, v in d.items(): ret[k] += v return {k: v for (k, v) in ret.items() if v != 0} if name.is_Add: dicts = [get_for_name(i) for i in name.args] if all([d == dicts[0] for d in dicts[1:]]): return dicts[0] raise TypeError("Only equivalent dimensions can be added or subtracted.") if name.is_Pow: dim = get_for_name(name.base) return {k: v*name.exp for (k, v) in dim.items()} if name.is_Function: args = (Dimension._from_dimensional_dependencies( get_for_name(arg)) for arg in name.args) result = name.func(*args) if isinstance(result, Dimension): return self.get_dimensional_dependencies(result) elif result.func == name.func: return {} else: return get_for_name(result) raise TypeError("Type {0} not implemented for get_dimensional_dependencies".format(type(name))) def get_dimensional_dependencies(self, name, mark_dimensionless=False): dimdep = self._get_dimensional_dependencies_for_name(name) if mark_dimensionless and dimdep == {}: return {'dimensionless': 1} return {str(i): j for i, j in dimdep.items()} def equivalent_dims(self, dim1, dim2): deps1 = self.get_dimensional_dependencies(dim1) deps2 = self.get_dimensional_dependencies(dim2) return deps1 == deps2 def extend(self, new_base_dims, new_derived_dims=[], new_dim_deps={}, name=None, description=None): if (name is not None) or (description is not None): SymPyDeprecationWarning( deprecated_since_version="1.2", issue=13336, feature="name and descriptions of DimensionSystem", useinstead="do not specify `name` or `description`", ).warn() deps = dict(self.dimensional_dependencies) deps.update(new_dim_deps) new_dim_sys = DimensionSystem( tuple(self.base_dims) + tuple(new_base_dims), tuple(self.derived_dims) + tuple(new_derived_dims), deps ) new_dim_sys._quantity_dimension_map.update(self._quantity_dimension_map) new_dim_sys._quantity_scale_factors.update(self._quantity_scale_factors) return new_dim_sys @staticmethod def sort_dims(dims): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Sort dimensions given in argument using their str function. This function will ensure that we get always the same tuple for a given set of dimensions. """ SymPyDeprecationWarning( deprecated_since_version="1.2", issue=13336, feature="sort_dims", useinstead="sorted(..., key=default_sort_key)", ).warn() return tuple(sorted(dims, key=str)) def __getitem__(self, key): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Shortcut to the get_dim method, using key access. """ SymPyDeprecationWarning( deprecated_since_version="1.2", issue=13336, feature="the get [ ] operator", useinstead="the dimension definition", ).warn() d = self.get_dim(key) #TODO: really want to raise an error? if d is None: raise KeyError(key) return d def __call__(self, unit): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Wrapper to the method print_dim_base """ SymPyDeprecationWarning( deprecated_since_version="1.2", issue=13336, feature="call DimensionSystem", useinstead="the dimension definition", ).warn() return self.print_dim_base(unit) def is_dimensionless(self, dimension): """ Check if the dimension object really has a dimension. A dimension should have at least one component with non-zero power. """ if dimension.name == 1: return True return self.get_dimensional_dependencies(dimension) == {} @property def list_can_dims(self): """ Useless method, kept for compatibility with previous versions. DO NOT USE. List all canonical dimension names. """ dimset = set([]) for i in self.base_dims: dimset.update(set(self.get_dimensional_dependencies(i).keys())) return tuple(sorted(dimset, key=str)) @property def inv_can_transf_matrix(self): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Compute the inverse transformation matrix from the base to the canonical dimension basis. It corresponds to the matrix where columns are the vector of base dimensions in canonical basis. This matrix will almost never be used because dimensions are always defined with respect to the canonical basis, so no work has to be done to get them in this basis. Nonetheless if this matrix is not square (or not invertible) it means that we have chosen a bad basis. """ matrix = reduce(lambda x, y: x.row_join(y), [self.dim_can_vector(d) for d in self.base_dims]) return matrix @property def can_transf_matrix(self): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Return the canonical transformation matrix from the canonical to the base dimension basis. It is the inverse of the matrix computed with inv_can_transf_matrix(). """ #TODO: the inversion will fail if the system is inconsistent, for # example if the matrix is not a square return reduce(lambda x, y: x.row_join(y), [self.dim_can_vector(d) for d in sorted(self.base_dims, key=str)] ).inv() def dim_can_vector(self, dim): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Dimensional representation in terms of the canonical base dimensions. """ vec = [] for d in self.list_can_dims: vec.append(self.get_dimensional_dependencies(dim).get(d, 0)) return Matrix(vec) def dim_vector(self, dim): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Vector representation in terms of the base dimensions. """ return self.can_transf_matrix * Matrix(self.dim_can_vector(dim)) def print_dim_base(self, dim): """ Give the string expression of a dimension in term of the basis symbols. """ dims = self.dim_vector(dim) symbols = [i.symbol if i.symbol is not None else i.name for i in self.base_dims] res = S.One for (s, p) in zip(symbols, dims): res *= s**p return res @property def dim(self): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Give the dimension of the system. That is return the number of dimensions forming the basis. """ return len(self.base_dims) @property def is_consistent(self): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Check if the system is well defined. """ # not enough or too many base dimensions compared to independent # dimensions # in vector language: the set of vectors do not form a basis return self.inv_can_transf_matrix.is_square
53502efd21e983963f1dd0220eafd5eac7f68179c4bbdae36c4a01f85c0e2cc4
""" Module defining unit prefixe class and some constants. Constant dict for SI and binary prefixes are defined as PREFIXES and BIN_PREFIXES. """ from sympy import Expr, sympify class Prefix(Expr): """ This class represent prefixes, with their name, symbol and factor. Prefixes are used to create derived units from a given unit. They should always be encapsulated into units. The factor is constructed from a base (default is 10) to some power, and it gives the total multiple or fraction. For example the kilometer km is constructed from the meter (factor 1) and the kilo (10 to the power 3, i.e. 1000). The base can be changed to allow e.g. binary prefixes. A prefix multiplied by something will always return the product of this other object times the factor, except if the other object: - is a prefix and they can be combined into a new prefix; - defines multiplication with prefixes (which is the case for the Unit class). """ _op_priority = 13.0 is_commutative = True def __new__(cls, name, abbrev, exponent, base=sympify(10)): name = sympify(name) abbrev = sympify(abbrev) exponent = sympify(exponent) base = sympify(base) obj = Expr.__new__(cls, name, abbrev, exponent, base) obj._name = name obj._abbrev = abbrev obj._scale_factor = base**exponent obj._exponent = exponent obj._base = base return obj @property def name(self): return self._name @property def abbrev(self): return self._abbrev @property def scale_factor(self): return self._scale_factor @property def base(self): return self._base def __str__(self): # TODO: add proper printers and tests: if self.base == 10: return "Prefix(%r, %r, %r)" % ( str(self.name), str(self.abbrev), self._exponent) else: return "Prefix(%r, %r, %r, %r)" % ( str(self.name), str(self.abbrev), self._exponent, self.base) __repr__ = __str__ def __mul__(self, other): from sympy.physics.units import Quantity if not isinstance(other, (Quantity, Prefix)): return super(Prefix, self).__mul__(other) fact = self.scale_factor * other.scale_factor if fact == 1: return 1 elif isinstance(other, Prefix): # simplify prefix for p in PREFIXES: if PREFIXES[p].scale_factor == fact: return PREFIXES[p] return fact return self.scale_factor * other def __truediv__(self, other): if not hasattr(other, "scale_factor"): return super(Prefix, self).__truediv__(other) fact = self.scale_factor / other.scale_factor if fact == 1: return 1 elif isinstance(other, Prefix): for p in PREFIXES: if PREFIXES[p].scale_factor == fact: return PREFIXES[p] return fact return self.scale_factor / other def __rtruediv__(self, other): if other == 1: for p in PREFIXES: if PREFIXES[p].scale_factor == 1 / self.scale_factor: return PREFIXES[p] return other / self.scale_factor def prefix_unit(unit, prefixes): """ Return a list of all units formed by unit and the given prefixes. You can use the predefined PREFIXES or BIN_PREFIXES, but you can also pass as argument a subdict of them if you don't want all prefixed units. >>> from sympy.physics.units.prefixes import (PREFIXES, ... prefix_unit) >>> from sympy.physics.units import m >>> pref = {"m": PREFIXES["m"], "c": PREFIXES["c"], "d": PREFIXES["d"]} >>> prefix_unit(m, pref) # doctest: +SKIP [millimeter, centimeter, decimeter] """ from sympy.physics.units.quantities import Quantity from sympy.physics.units import UnitSystem prefixed_units = [] for prefix_abbr, prefix in prefixes.items(): quantity = Quantity( "%s%s" % (prefix.name, unit.name), abbrev=("%s%s" % (prefix.abbrev, unit.abbrev)) ) UnitSystem._quantity_dimensional_equivalence_map_global[quantity] = unit UnitSystem._quantity_scale_factors_global[quantity] = (prefix.scale_factor, unit) prefixed_units.append(quantity) return prefixed_units yotta = Prefix('yotta', 'Y', 24) zetta = Prefix('zetta', 'Z', 21) exa = Prefix('exa', 'E', 18) peta = Prefix('peta', 'P', 15) tera = Prefix('tera', 'T', 12) giga = Prefix('giga', 'G', 9) mega = Prefix('mega', 'M', 6) kilo = Prefix('kilo', 'k', 3) hecto = Prefix('hecto', 'h', 2) deca = Prefix('deca', 'da', 1) deci = Prefix('deci', 'd', -1) centi = Prefix('centi', 'c', -2) milli = Prefix('milli', 'm', -3) micro = Prefix('micro', 'mu', -6) nano = Prefix('nano', 'n', -9) pico = Prefix('pico', 'p', -12) femto = Prefix('femto', 'f', -15) atto = Prefix('atto', 'a', -18) zepto = Prefix('zepto', 'z', -21) yocto = Prefix('yocto', 'y', -24) # http://physics.nist.gov/cuu/Units/prefixes.html PREFIXES = { 'Y': yotta, 'Z': zetta, 'E': exa, 'P': peta, 'T': tera, 'G': giga, 'M': mega, 'k': kilo, 'h': hecto, 'da': deca, 'd': deci, 'c': centi, 'm': milli, 'mu': micro, 'n': nano, 'p': pico, 'f': femto, 'a': atto, 'z': zepto, 'y': yocto, } kibi = Prefix('kibi', 'Y', 10, 2) mebi = Prefix('mebi', 'Y', 20, 2) gibi = Prefix('gibi', 'Y', 30, 2) tebi = Prefix('tebi', 'Y', 40, 2) pebi = Prefix('pebi', 'Y', 50, 2) exbi = Prefix('exbi', 'Y', 60, 2) # http://physics.nist.gov/cuu/Units/binary.html BIN_PREFIXES = { 'Ki': kibi, 'Mi': mebi, 'Gi': gibi, 'Ti': tebi, 'Pi': pebi, 'Ei': exbi, }
1b4eaa58761584ee3e763baa65473e2ef8fc8baf219965bf1e5490cc59da1c63
from sympy import Derivative from sympy.core.function import UndefinedFunction, AppliedUndef from sympy.core.symbol import Symbol from sympy.interactive.printing import init_printing from sympy.printing.latex import LatexPrinter from sympy.printing.pretty.pretty import PrettyPrinter from sympy.printing.pretty.pretty_symbology import center_accent from sympy.printing.str import StrPrinter from sympy.printing.precedence import PRECEDENCE __all__ = ['vprint', 'vsstrrepr', 'vsprint', 'vpprint', 'vlatex', 'init_vprinting'] class VectorStrPrinter(StrPrinter): """String Printer for vector expressions. """ def _print_Derivative(self, e): from sympy.physics.vector.functions import dynamicsymbols t = dynamicsymbols._t if (bool(sum([i == t for i in e.variables])) & isinstance(type(e.args[0]), UndefinedFunction)): ol = str(e.args[0].func) for i, v in enumerate(e.variables): ol += dynamicsymbols._str return ol else: return StrPrinter().doprint(e) def _print_Function(self, e): from sympy.physics.vector.functions import dynamicsymbols t = dynamicsymbols._t if isinstance(type(e), UndefinedFunction): return StrPrinter().doprint(e).replace("(%s)" % t, '') return e.func.__name__ + "(%s)" % self.stringify(e.args, ", ") class VectorStrReprPrinter(VectorStrPrinter): """String repr printer for vector expressions.""" def _print_str(self, s): return repr(s) class VectorLatexPrinter(LatexPrinter): """Latex Printer for vector expressions. """ def _print_Function(self, expr, exp=None): from sympy.physics.vector.functions import dynamicsymbols func = expr.func.__name__ t = dynamicsymbols._t if hasattr(self, '_print_' + func) and \ not isinstance(type(expr), UndefinedFunction): return getattr(self, '_print_' + func)(expr, exp) elif isinstance(type(expr), UndefinedFunction) and (expr.args == (t,)): # treat this function like a symbol expr = Symbol(func) if exp is not None: # copied from LatexPrinter._helper_print_standard_power, which # we can't call because we only have exp as a string. base = self.parenthesize(expr, PRECEDENCE['Pow']) base = self.parenthesize_super(base) return r"%s^{%s}" % (base, exp) else: return super()._print(expr) else: return super()._print_Function(expr, exp) def _print_Derivative(self, der_expr): from sympy.physics.vector.functions import dynamicsymbols # make sure it is in the right form der_expr = der_expr.doit() if not isinstance(der_expr, Derivative): return r"\left(%s\right)" % self.doprint(der_expr) # check if expr is a dynamicsymbol t = dynamicsymbols._t expr = der_expr.expr red = expr.atoms(AppliedUndef) syms = der_expr.variables test1 = not all([True for i in red if i.free_symbols == {t}]) test2 = not all([(t == i) for i in syms]) if test1 or test2: return super()._print_Derivative(der_expr) # done checking dots = len(syms) base = self._print_Function(expr) base_split = base.split('_', 1) base = base_split[0] if dots == 1: base = r"\dot{%s}" % base elif dots == 2: base = r"\ddot{%s}" % base elif dots == 3: base = r"\dddot{%s}" % base elif dots == 4: base = r"\ddddot{%s}" % base else: # Fallback to standard printing return super()._print_Derivative(der_expr) if len(base_split) != 1: base += '_' + base_split[1] return base class VectorPrettyPrinter(PrettyPrinter): """Pretty Printer for vectorialexpressions. """ def _print_Derivative(self, deriv): from sympy.physics.vector.functions import dynamicsymbols # XXX use U('PARTIAL DIFFERENTIAL') here ? t = dynamicsymbols._t dot_i = 0 syms = list(reversed(deriv.variables)) while len(syms) > 0: if syms[-1] == t: syms.pop() dot_i += 1 else: return super(VectorPrettyPrinter, self)._print_Derivative(deriv) if not (isinstance(type(deriv.expr), UndefinedFunction) and (deriv.expr.args == (t,))): return super(VectorPrettyPrinter, self)._print_Derivative(deriv) else: pform = self._print_Function(deriv.expr) # the following condition would happen with some sort of non-standard # dynamic symbol I guess, so we'll just print the SymPy way if len(pform.picture) > 1: return super(VectorPrettyPrinter, self)._print_Derivative(deriv) # There are only special symbols up to fourth-order derivatives if dot_i >= 5: return super(VectorPrettyPrinter, self)._print_Derivative(deriv) # Deal with special symbols dots = {0 : "", 1 : "\N{COMBINING DOT ABOVE}", 2 : "\N{COMBINING DIAERESIS}", 3 : "\N{COMBINING THREE DOTS ABOVE}", 4 : "\N{COMBINING FOUR DOTS ABOVE}"} d = pform.__dict__ #if unicode is false then calculate number of apostrophes needed and add to output if not self._use_unicode: apostrophes = "" for i in range(0, dot_i): apostrophes += "'" d['picture'][0] += apostrophes + "(t)" else: d['picture'] = [center_accent(d['picture'][0], dots[dot_i])] return pform def _print_Function(self, e): from sympy.physics.vector.functions import dynamicsymbols t = dynamicsymbols._t # XXX works only for applied functions func = e.func args = e.args func_name = func.__name__ pform = self._print_Symbol(Symbol(func_name)) # If this function is an Undefined function of t, it is probably a # dynamic symbol, so we'll skip the (t). The rest of the code is # identical to the normal PrettyPrinter code if not (isinstance(func, UndefinedFunction) and (args == (t,))): return super(VectorPrettyPrinter, self)._print_Function(e) return pform def vprint(expr, **settings): r"""Function for printing of expressions generated in the sympy.physics vector package. Extends SymPy's StrPrinter, takes the same setting accepted by SymPy's :func:`~.sstr`, and is equivalent to ``print(sstr(foo))``. Parameters ========== expr : valid SymPy object SymPy expression to print. settings : args Same as the settings accepted by SymPy's sstr(). Examples ======== >>> from sympy.physics.vector import vprint, dynamicsymbols >>> u1 = dynamicsymbols('u1') >>> print(u1) u1(t) >>> vprint(u1) u1 """ outstr = vsprint(expr, **settings) from sympy.core.compatibility import builtins if (outstr != 'None'): builtins._ = outstr print(outstr) def vsstrrepr(expr, **settings): """Function for displaying expression representation's with vector printing enabled. Parameters ========== expr : valid SymPy object SymPy expression to print. settings : args Same as the settings accepted by SymPy's sstrrepr(). """ p = VectorStrReprPrinter(settings) return p.doprint(expr) def vsprint(expr, **settings): r"""Function for displaying expressions generated in the sympy.physics vector package. Returns the output of vprint() as a string. Parameters ========== expr : valid SymPy object SymPy expression to print settings : args Same as the settings accepted by SymPy's sstr(). Examples ======== >>> from sympy.physics.vector import vsprint, dynamicsymbols >>> u1, u2 = dynamicsymbols('u1 u2') >>> u2d = dynamicsymbols('u2', level=1) >>> print("%s = %s" % (u1, u2 + u2d)) u1(t) = u2(t) + Derivative(u2(t), t) >>> print("%s = %s" % (vsprint(u1), vsprint(u2 + u2d))) u1 = u2 + u2' """ string_printer = VectorStrPrinter(settings) return string_printer.doprint(expr) def vpprint(expr, **settings): r"""Function for pretty printing of expressions generated in the sympy.physics vector package. Mainly used for expressions not inside a vector; the output of running scripts and generating equations of motion. Takes the same options as SymPy's :func:`~.pretty_print`; see that function for more information. Parameters ========== expr : valid SymPy object SymPy expression to pretty print settings : args Same as those accepted by SymPy's pretty_print. """ pp = VectorPrettyPrinter(settings) # Note that this is copied from sympy.printing.pretty.pretty_print: # XXX: this is an ugly hack, but at least it works use_unicode = pp._settings['use_unicode'] from sympy.printing.pretty.pretty_symbology import pretty_use_unicode uflag = pretty_use_unicode(use_unicode) try: return pp.doprint(expr) finally: pretty_use_unicode(uflag) def vlatex(expr, **settings): r"""Function for printing latex representation of sympy.physics.vector objects. For latex representation of Vectors, Dyadics, and dynamicsymbols. Takes the same options as SymPy's :func:`~.latex`; see that function for more information; Parameters ========== expr : valid SymPy object SymPy expression to represent in LaTeX form settings : args Same as latex() Examples ======== >>> from sympy.physics.vector import vlatex, ReferenceFrame, dynamicsymbols >>> N = ReferenceFrame('N') >>> q1, q2 = dynamicsymbols('q1 q2') >>> q1d, q2d = dynamicsymbols('q1 q2', 1) >>> q1dd, q2dd = dynamicsymbols('q1 q2', 2) >>> vlatex(N.x + N.y) '\\mathbf{\\hat{n}_x} + \\mathbf{\\hat{n}_y}' >>> vlatex(q1 + q2) 'q_{1} + q_{2}' >>> vlatex(q1d) '\\dot{q}_{1}' >>> vlatex(q1 * q2d) 'q_{1} \\dot{q}_{2}' >>> vlatex(q1dd * q1 / q1d) '\\frac{q_{1} \\ddot{q}_{1}}{\\dot{q}_{1}}' """ latex_printer = VectorLatexPrinter(settings) return latex_printer.doprint(expr) def init_vprinting(**kwargs): """Initializes time derivative printing for all SymPy objects, i.e. any functions of time will be displayed in a more compact notation. The main benefit of this is for printing of time derivatives; instead of displaying as ``Derivative(f(t),t)``, it will display ``f'``. This is only actually needed for when derivatives are present and are not in a physics.vector.Vector or physics.vector.Dyadic object. This function is a light wrapper to :func:`~.init_printing`. Any keyword arguments for it are valid here. {0} Examples ======== >>> from sympy import Function, symbols >>> t, x = symbols('t, x') >>> omega = Function('omega') >>> omega(x).diff() Derivative(omega(x), x) >>> omega(t).diff() Derivative(omega(t), t) Now use the string printer: >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> omega(x).diff() Derivative(omega(x), x) >>> omega(t).diff() omega' """ kwargs['str_printer'] = vsstrrepr kwargs['pretty_printer'] = vpprint kwargs['latex_printer'] = vlatex init_printing(**kwargs) params = init_printing.__doc__.split('Examples\n ========')[0] # type: ignore init_vprinting.__doc__ = init_vprinting.__doc__.format(params) # type: ignore
16983bc82bfe9d2d6d86341a4dc9dc2b2f03923ad94e382074336413705ff875
from sympy.core.backend import (S, sympify, expand, sqrt, Add, zeros, ImmutableMatrix as Matrix) from sympy import trigsimp from sympy.printing.defaults import Printable from sympy.utilities.misc import filldedent __all__ = ['Vector'] class Vector(Printable): """The class used to define vectors. It along with ReferenceFrame are the building blocks of describing a classical mechanics system in PyDy and sympy.physics.vector. Attributes ========== simp : Boolean Let certain methods use trigsimp on their outputs """ simp = False def __init__(self, inlist): """This is the constructor for the Vector class. You shouldn't be calling this, it should only be used by other functions. You should be treating Vectors like you would with if you were doing the math by hand, and getting the first 3 from the standard basis vectors from a ReferenceFrame. The only exception is to create a zero vector: zv = Vector(0) """ self.args = [] if inlist == 0: inlist = [] if isinstance(inlist, dict): d = inlist else: d = {} for inp in inlist: if inp[1] in d: d[inp[1]] += inp[0] else: d[inp[1]] = inp[0] for k, v in d.items(): if v != Matrix([0, 0, 0]): self.args.append((v, k)) def __hash__(self): return hash(tuple(self.args)) def __add__(self, other): """The add operator for Vector. """ if other == 0: return self other = _check_vector(other) return Vector(self.args + other.args) def __and__(self, other): """Dot product of two vectors. Returns a scalar, the dot product of the two Vectors Parameters ========== other : Vector The Vector which we are dotting with Examples ======== >>> from sympy.physics.vector import ReferenceFrame, dot >>> from sympy import symbols >>> q1 = symbols('q1') >>> N = ReferenceFrame('N') >>> dot(N.x, N.x) 1 >>> dot(N.x, N.y) 0 >>> A = N.orientnew('A', 'Axis', [q1, N.x]) >>> dot(N.y, A.y) cos(q1) """ from sympy.physics.vector.dyadic import Dyadic if isinstance(other, Dyadic): return NotImplemented other = _check_vector(other) out = S.Zero for i, v1 in enumerate(self.args): for j, v2 in enumerate(other.args): out += ((v2[0].T) * (v2[1].dcm(v1[1])) * (v1[0]))[0] if Vector.simp: return trigsimp(sympify(out), recursive=True) else: return sympify(out) def __truediv__(self, other): """This uses mul and inputs self and 1 divided by other. """ return self.__mul__(sympify(1) / other) def __eq__(self, other): """Tests for equality. It is very import to note that this is only as good as the SymPy equality test; False does not always mean they are not equivalent Vectors. If other is 0, and self is empty, returns True. If other is 0 and self is not empty, returns False. If none of the above, only accepts other as a Vector. """ if other == 0: other = Vector(0) try: other = _check_vector(other) except TypeError: return False if (self.args == []) and (other.args == []): return True elif (self.args == []) or (other.args == []): return False frame = self.args[0][1] for v in frame: if expand((self - other) & v) != 0: return False return True def __mul__(self, other): """Multiplies the Vector by a sympifyable expression. Parameters ========== other : Sympifyable The scalar to multiply this Vector with Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> from sympy import Symbol >>> N = ReferenceFrame('N') >>> b = Symbol('b') >>> V = 10 * b * N.x >>> print(V) 10*b*N.x """ newlist = [v for v in self.args] for i, v in enumerate(newlist): newlist[i] = (sympify(other) * newlist[i][0], newlist[i][1]) return Vector(newlist) def __ne__(self, other): return not self == other def __neg__(self): return self * -1 def __or__(self, other): """Outer product between two Vectors. A rank increasing operation, which returns a Dyadic from two Vectors Parameters ========== other : Vector The Vector to take the outer product with Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer >>> N = ReferenceFrame('N') >>> outer(N.x, N.x) (N.x|N.x) """ from sympy.physics.vector.dyadic import Dyadic other = _check_vector(other) ol = Dyadic(0) for i, v in enumerate(self.args): for i2, v2 in enumerate(other.args): # it looks this way because if we are in the same frame and # use the enumerate function on the same frame in a nested # fashion, then bad things happen ol += Dyadic([(v[0][0] * v2[0][0], v[1].x, v2[1].x)]) ol += Dyadic([(v[0][0] * v2[0][1], v[1].x, v2[1].y)]) ol += Dyadic([(v[0][0] * v2[0][2], v[1].x, v2[1].z)]) ol += Dyadic([(v[0][1] * v2[0][0], v[1].y, v2[1].x)]) ol += Dyadic([(v[0][1] * v2[0][1], v[1].y, v2[1].y)]) ol += Dyadic([(v[0][1] * v2[0][2], v[1].y, v2[1].z)]) ol += Dyadic([(v[0][2] * v2[0][0], v[1].z, v2[1].x)]) ol += Dyadic([(v[0][2] * v2[0][1], v[1].z, v2[1].y)]) ol += Dyadic([(v[0][2] * v2[0][2], v[1].z, v2[1].z)]) return ol def _latex(self, printer): """Latex Printing method. """ ar = self.args # just to shorten things if len(ar) == 0: return str(0) ol = [] # output list, to be concatenated to a string for i, v in enumerate(ar): for j in 0, 1, 2: # if the coef of the basis vector is 1, we skip the 1 if ar[i][0][j] == 1: ol.append(' + ' + ar[i][1].latex_vecs[j]) # if the coef of the basis vector is -1, we skip the 1 elif ar[i][0][j] == -1: ol.append(' - ' + ar[i][1].latex_vecs[j]) elif ar[i][0][j] != 0: # If the coefficient of the basis vector is not 1 or -1; # also, we might wrap it in parentheses, for readability. arg_str = printer._print(ar[i][0][j]) if isinstance(ar[i][0][j], Add): arg_str = "(%s)" % arg_str if arg_str[0] == '-': arg_str = arg_str[1:] str_start = ' - ' else: str_start = ' + ' ol.append(str_start + arg_str + ar[i][1].latex_vecs[j]) outstr = ''.join(ol) if outstr.startswith(' + '): outstr = outstr[3:] elif outstr.startswith(' '): outstr = outstr[1:] return outstr def _pretty(self, printer): """Pretty Printing method. """ from sympy.printing.pretty.stringpict import prettyForm e = self class Fake(object): def render(self, *args, **kwargs): ar = e.args # just to shorten things if len(ar) == 0: return str(0) pforms = [] # output list, to be concatenated to a string for i, v in enumerate(ar): for j in 0, 1, 2: # if the coef of the basis vector is 1, we skip the 1 if ar[i][0][j] == 1: pform = printer._print(ar[i][1].pretty_vecs[j]) # if the coef of the basis vector is -1, we skip the 1 elif ar[i][0][j] == -1: pform = printer._print(ar[i][1].pretty_vecs[j]) pform = prettyForm(*pform.left(" - ")) bin = prettyForm.NEG pform = prettyForm(binding=bin, *pform) elif ar[i][0][j] != 0: # If the basis vector coeff is not 1 or -1, # we might wrap it in parentheses, for readability. pform = printer._print(ar[i][0][j]) if isinstance(ar[i][0][j], Add): tmp = pform.parens() pform = prettyForm(tmp[0], tmp[1]) pform = prettyForm(*pform.right(" ", ar[i][1].pretty_vecs[j])) else: continue pforms.append(pform) pform = prettyForm.__add__(*pforms) kwargs["wrap_line"] = kwargs.get("wrap_line") kwargs["num_columns"] = kwargs.get("num_columns") out_str = pform.render(*args, **kwargs) mlines = [line.rstrip() for line in out_str.split("\n")] return "\n".join(mlines) return Fake() def __ror__(self, other): """Outer product between two Vectors. A rank increasing operation, which returns a Dyadic from two Vectors Parameters ========== other : Vector The Vector to take the outer product with Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer >>> N = ReferenceFrame('N') >>> outer(N.x, N.x) (N.x|N.x) """ from sympy.physics.vector.dyadic import Dyadic other = _check_vector(other) ol = Dyadic(0) for i, v in enumerate(other.args): for i2, v2 in enumerate(self.args): # it looks this way because if we are in the same frame and # use the enumerate function on the same frame in a nested # fashion, then bad things happen ol += Dyadic([(v[0][0] * v2[0][0], v[1].x, v2[1].x)]) ol += Dyadic([(v[0][0] * v2[0][1], v[1].x, v2[1].y)]) ol += Dyadic([(v[0][0] * v2[0][2], v[1].x, v2[1].z)]) ol += Dyadic([(v[0][1] * v2[0][0], v[1].y, v2[1].x)]) ol += Dyadic([(v[0][1] * v2[0][1], v[1].y, v2[1].y)]) ol += Dyadic([(v[0][1] * v2[0][2], v[1].y, v2[1].z)]) ol += Dyadic([(v[0][2] * v2[0][0], v[1].z, v2[1].x)]) ol += Dyadic([(v[0][2] * v2[0][1], v[1].z, v2[1].y)]) ol += Dyadic([(v[0][2] * v2[0][2], v[1].z, v2[1].z)]) return ol def __rsub__(self, other): return (-1 * self) + other def _sympystr(self, printer, order=True): """Printing method. """ if not order or len(self.args) == 1: ar = list(self.args) elif len(self.args) == 0: return printer._print(0) else: d = {v[1]: v[0] for v in self.args} keys = sorted(d.keys(), key=lambda x: x.index) ar = [] for key in keys: ar.append((d[key], key)) ol = [] # output list, to be concatenated to a string for i, v in enumerate(ar): for j in 0, 1, 2: # if the coef of the basis vector is 1, we skip the 1 if ar[i][0][j] == 1: ol.append(' + ' + ar[i][1].str_vecs[j]) # if the coef of the basis vector is -1, we skip the 1 elif ar[i][0][j] == -1: ol.append(' - ' + ar[i][1].str_vecs[j]) elif ar[i][0][j] != 0: # If the coefficient of the basis vector is not 1 or -1; # also, we might wrap it in parentheses, for readability. arg_str = printer._print(ar[i][0][j]) if isinstance(ar[i][0][j], Add): arg_str = "(%s)" % arg_str if arg_str[0] == '-': arg_str = arg_str[1:] str_start = ' - ' else: str_start = ' + ' ol.append(str_start + arg_str + '*' + ar[i][1].str_vecs[j]) outstr = ''.join(ol) if outstr.startswith(' + '): outstr = outstr[3:] elif outstr.startswith(' '): outstr = outstr[1:] return outstr def __sub__(self, other): """The subtraction operator. """ return self.__add__(other * -1) def __xor__(self, other): """The cross product operator for two Vectors. Returns a Vector, expressed in the same ReferenceFrames as self. Parameters ========== other : Vector The Vector which we are crossing with Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> from sympy import symbols >>> q1 = symbols('q1') >>> N = ReferenceFrame('N') >>> N.x ^ N.y N.z >>> A = N.orientnew('A', 'Axis', [q1, N.x]) >>> A.x ^ N.y N.z >>> N.y ^ A.x - sin(q1)*A.y - cos(q1)*A.z """ from sympy.physics.vector.dyadic import Dyadic if isinstance(other, Dyadic): return NotImplemented other = _check_vector(other) if other.args == []: return Vector(0) def _det(mat): """This is needed as a little method for to find the determinant of a list in python; needs to work for a 3x3 list. SymPy's Matrix won't take in Vector, so need a custom function. You shouldn't be calling this. """ return (mat[0][0] * (mat[1][1] * mat[2][2] - mat[1][2] * mat[2][1]) + mat[0][1] * (mat[1][2] * mat[2][0] - mat[1][0] * mat[2][2]) + mat[0][2] * (mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0])) outlist = [] ar = other.args # For brevity for i, v in enumerate(ar): tempx = v[1].x tempy = v[1].y tempz = v[1].z tempm = ([[tempx, tempy, tempz], [self & tempx, self & tempy, self & tempz], [Vector([ar[i]]) & tempx, Vector([ar[i]]) & tempy, Vector([ar[i]]) & tempz]]) outlist += _det(tempm).args return Vector(outlist) __radd__ = __add__ __rand__ = __and__ __rmul__ = __mul__ def separate(self): """ The constituents of this vector in different reference frames, as per its definition. Returns a dict mapping each ReferenceFrame to the corresponding constituent Vector. Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> R1 = ReferenceFrame('R1') >>> R2 = ReferenceFrame('R2') >>> v = R1.x + R2.x >>> v.separate() == {R1: R1.x, R2: R2.x} True """ components = {} for x in self.args: components[x[1]] = Vector([x]) return components def dot(self, other): return self & other dot.__doc__ = __and__.__doc__ def cross(self, other): return self ^ other cross.__doc__ = __xor__.__doc__ def outer(self, other): return self | other outer.__doc__ = __or__.__doc__ def diff(self, var, frame, var_in_dcm=True): """Returns the partial derivative of the vector with respect to a variable in the provided reference frame. Parameters ========== var : Symbol What the partial derivative is taken with respect to. frame : ReferenceFrame The reference frame that the partial derivative is taken in. var_in_dcm : boolean If true, the differentiation algorithm assumes that the variable may be present in any of the direction cosine matrices that relate the frame to the frames of any component of the vector. But if it is known that the variable is not present in the direction cosine matrices, false can be set to skip full reexpression in the desired frame. Examples ======== >>> from sympy import Symbol >>> from sympy.physics.vector import dynamicsymbols, ReferenceFrame >>> from sympy.physics.vector import Vector >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> Vector.simp = True >>> t = Symbol('t') >>> q1 = dynamicsymbols('q1') >>> N = ReferenceFrame('N') >>> A = N.orientnew('A', 'Axis', [q1, N.y]) >>> A.x.diff(t, N) - q1'*A.z >>> B = ReferenceFrame('B') >>> u1, u2 = dynamicsymbols('u1, u2') >>> v = u1 * A.x + u2 * B.y >>> v.diff(u2, N, var_in_dcm=False) B.y """ from sympy.physics.vector.frame import _check_frame var = sympify(var) _check_frame(frame) inlist = [] for vector_component in self.args: measure_number = vector_component[0] component_frame = vector_component[1] if component_frame == frame: inlist += [(measure_number.diff(var), frame)] else: # If the direction cosine matrix relating the component frame # with the derivative frame does not contain the variable. if not var_in_dcm or (frame.dcm(component_frame).diff(var) == zeros(3, 3)): inlist += [(measure_number.diff(var), component_frame)] else: # else express in the frame reexp_vec_comp = Vector([vector_component]).express(frame) deriv = reexp_vec_comp.args[0][0].diff(var) inlist += Vector([(deriv, frame)]).express(component_frame).args return Vector(inlist) def express(self, otherframe, variables=False): """ Returns a Vector equivalent to this one, expressed in otherframe. Uses the global express method. Parameters ========== otherframe : ReferenceFrame The frame for this Vector to be described in variables : boolean If True, the coordinate symbols(if present) in this Vector are re-expressed in terms otherframe Examples ======== >>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> q1 = dynamicsymbols('q1') >>> N = ReferenceFrame('N') >>> A = N.orientnew('A', 'Axis', [q1, N.y]) >>> A.x.express(N) cos(q1)*N.x - sin(q1)*N.z """ from sympy.physics.vector import express return express(self, otherframe, variables=variables) def to_matrix(self, reference_frame): """Returns the matrix form of the vector with respect to the given frame. Parameters ---------- reference_frame : ReferenceFrame The reference frame that the rows of the matrix correspond to. Returns ------- matrix : ImmutableMatrix, shape(3,1) The matrix that gives the 1D vector. Examples ======== >>> from sympy import symbols >>> from sympy.physics.vector import ReferenceFrame >>> a, b, c = symbols('a, b, c') >>> N = ReferenceFrame('N') >>> vector = a * N.x + b * N.y + c * N.z >>> vector.to_matrix(N) Matrix([ [a], [b], [c]]) >>> beta = symbols('beta') >>> A = N.orientnew('A', 'Axis', (beta, N.x)) >>> vector.to_matrix(A) Matrix([ [ a], [ b*cos(beta) + c*sin(beta)], [-b*sin(beta) + c*cos(beta)]]) """ return Matrix([self.dot(unit_vec) for unit_vec in reference_frame]).reshape(3, 1) def doit(self, **hints): """Calls .doit() on each term in the Vector""" d = {} for v in self.args: d[v[1]] = v[0].applyfunc(lambda x: x.doit(**hints)) return Vector(d) def dt(self, otherframe): """ Returns a Vector which is the time derivative of the self Vector, taken in frame otherframe. Calls the global time_derivative method Parameters ========== otherframe : ReferenceFrame The frame to calculate the time derivative in """ from sympy.physics.vector import time_derivative return time_derivative(self, otherframe) def simplify(self): """Returns a simplified Vector.""" d = {} for v in self.args: d[v[1]] = v[0].simplify() return Vector(d) def subs(self, *args, **kwargs): """Substitution on the Vector. Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> from sympy import Symbol >>> N = ReferenceFrame('N') >>> s = Symbol('s') >>> a = N.x * s >>> a.subs({s: 2}) 2*N.x """ d = {} for v in self.args: d[v[1]] = v[0].subs(*args, **kwargs) return Vector(d) def magnitude(self): """Returns the magnitude (Euclidean norm) of self.""" return sqrt(self & self) def normalize(self): """Returns a Vector of magnitude 1, codirectional with self.""" return Vector(self.args + []) / self.magnitude() def applyfunc(self, f): """Apply a function to each component of a vector.""" if not callable(f): raise TypeError("`f` must be callable.") d = {} for v in self.args: d[v[1]] = v[0].applyfunc(f) return Vector(d) def free_symbols(self, reference_frame): """ Returns the free symbols in the measure numbers of the vector expressed in the given reference frame. Parameter ========= reference_frame : ReferenceFrame The frame with respect to which the free symbols of the given vector is to be determined. """ return self.to_matrix(reference_frame).free_symbols class VectorTypeError(TypeError): def __init__(self, other, want): msg = filldedent("Expected an instance of %s, but received object " "'%s' of %s." % (type(want), other, type(other))) super(VectorTypeError, self).__init__(msg) def _check_vector(other): if not isinstance(other, Vector): raise TypeError('A Vector must be supplied') return other
f2c947f7d5fe598d19961f7ab146bcc59a75f8b13697c5ae49d93961361f3537
from __future__ import print_function, division from .vector import Vector, _check_vector from .frame import _check_frame __all__ = ['Point'] class Point(object): """This object represents a point in a dynamic system. It stores the: position, velocity, and acceleration of a point. The position is a vector defined as the vector distance from a parent point to this point. Parameters ========== name : string The display name of the Point Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> N = ReferenceFrame('N') >>> O = Point('O') >>> P = Point('P') >>> u1, u2, u3 = dynamicsymbols('u1 u2 u3') >>> O.set_vel(N, u1 * N.x + u2 * N.y + u3 * N.z) >>> O.acc(N) u1'*N.x + u2'*N.y + u3'*N.z symbols() can be used to create multiple Points in a single step, for example: >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> from sympy import symbols >>> N = ReferenceFrame('N') >>> u1, u2 = dynamicsymbols('u1 u2') >>> A, B = symbols('A B', cls=Point) >>> type(A) <class 'sympy.physics.vector.point.Point'> >>> A.set_vel(N, u1 * N.x + u2 * N.y) >>> B.set_vel(N, u2 * N.x + u1 * N.y) >>> A.acc(N) - B.acc(N) (u1' - u2')*N.x + (-u1' + u2')*N.y """ def __init__(self, name): """Initialization of a Point object. """ self.name = name self._pos_dict = {} self._vel_dict = {} self._acc_dict = {} self._pdlist = [self._pos_dict, self._vel_dict, self._acc_dict] def __str__(self): return self.name __repr__ = __str__ def _check_point(self, other): if not isinstance(other, Point): raise TypeError('A Point must be supplied') def _pdict_list(self, other, num): """Returns a list of points that gives the shortest path with respect to position, velocity, or acceleration from this point to the provided point. Parameters ========== other : Point A point that may be related to this point by position, velocity, or acceleration. num : integer 0 for searching the position tree, 1 for searching the velocity tree, and 2 for searching the acceleration tree. Returns ======= list of Points A sequence of points from self to other. Notes ===== It isn't clear if num = 1 or num = 2 actually works because the keys to ``_vel_dict`` and ``_acc_dict`` are :class:`ReferenceFrame` objects which do not have the ``_pdlist`` attribute. """ outlist = [[self]] oldlist = [[]] while outlist != oldlist: oldlist = outlist[:] for i, v in enumerate(outlist): templist = v[-1]._pdlist[num].keys() for i2, v2 in enumerate(templist): if not v.__contains__(v2): littletemplist = v + [v2] if not outlist.__contains__(littletemplist): outlist.append(littletemplist) for i, v in enumerate(oldlist): if v[-1] != other: outlist.remove(v) outlist.sort(key=len) if len(outlist) != 0: return outlist[0] raise ValueError('No Connecting Path found between ' + other.name + ' and ' + self.name) def a1pt_theory(self, otherpoint, outframe, interframe): """Sets the acceleration of this point with the 1-point theory. The 1-point theory for point acceleration looks like this: ^N a^P = ^B a^P + ^N a^O + ^N alpha^B x r^OP + ^N omega^B x (^N omega^B x r^OP) + 2 ^N omega^B x ^B v^P where O is a point fixed in B, P is a point moving in B, and B is rotating in frame N. Parameters ========== otherpoint : Point The first point of the 1-point theory (O) outframe : ReferenceFrame The frame we want this point's acceleration defined in (N) fixedframe : ReferenceFrame The intermediate frame in this calculation (B) Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> from sympy.physics.vector import dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> q = dynamicsymbols('q') >>> q2 = dynamicsymbols('q2') >>> qd = dynamicsymbols('q', 1) >>> q2d = dynamicsymbols('q2', 1) >>> N = ReferenceFrame('N') >>> B = ReferenceFrame('B') >>> B.set_ang_vel(N, 5 * B.y) >>> O = Point('O') >>> P = O.locatenew('P', q * B.x) >>> P.set_vel(B, qd * B.x + q2d * B.y) >>> O.set_vel(N, 0) >>> P.a1pt_theory(O, N, B) (-25*q + q'')*B.x + q2''*B.y - 10*q'*B.z """ _check_frame(outframe) _check_frame(interframe) self._check_point(otherpoint) dist = self.pos_from(otherpoint) v = self.vel(interframe) a1 = otherpoint.acc(outframe) a2 = self.acc(interframe) omega = interframe.ang_vel_in(outframe) alpha = interframe.ang_acc_in(outframe) self.set_acc(outframe, a2 + 2 * (omega ^ v) + a1 + (alpha ^ dist) + (omega ^ (omega ^ dist))) return self.acc(outframe) def a2pt_theory(self, otherpoint, outframe, fixedframe): """Sets the acceleration of this point with the 2-point theory. The 2-point theory for point acceleration looks like this: ^N a^P = ^N a^O + ^N alpha^B x r^OP + ^N omega^B x (^N omega^B x r^OP) where O and P are both points fixed in frame B, which is rotating in frame N. Parameters ========== otherpoint : Point The first point of the 2-point theory (O) outframe : ReferenceFrame The frame we want this point's acceleration defined in (N) fixedframe : ReferenceFrame The frame in which both points are fixed (B) Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> q = dynamicsymbols('q') >>> qd = dynamicsymbols('q', 1) >>> N = ReferenceFrame('N') >>> B = N.orientnew('B', 'Axis', [q, N.z]) >>> O = Point('O') >>> P = O.locatenew('P', 10 * B.x) >>> O.set_vel(N, 5 * N.x) >>> P.a2pt_theory(O, N, B) - 10*q'**2*B.x + 10*q''*B.y """ _check_frame(outframe) _check_frame(fixedframe) self._check_point(otherpoint) dist = self.pos_from(otherpoint) a = otherpoint.acc(outframe) omega = fixedframe.ang_vel_in(outframe) alpha = fixedframe.ang_acc_in(outframe) self.set_acc(outframe, a + (alpha ^ dist) + (omega ^ (omega ^ dist))) return self.acc(outframe) def acc(self, frame): """The acceleration Vector of this Point in a ReferenceFrame. Parameters ========== frame : ReferenceFrame The frame in which the returned acceleration vector will be defined in Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p1.set_acc(N, 10 * N.x) >>> p1.acc(N) 10*N.x """ _check_frame(frame) if not (frame in self._acc_dict): if self._vel_dict[frame] != 0: return (self._vel_dict[frame]).dt(frame) else: return Vector(0) return self._acc_dict[frame] def locatenew(self, name, value): """Creates a new point with a position defined from this point. Parameters ========== name : str The name for the new point value : Vector The position of the new point relative to this point Examples ======== >>> from sympy.physics.vector import ReferenceFrame, Point >>> N = ReferenceFrame('N') >>> P1 = Point('P1') >>> P2 = P1.locatenew('P2', 10 * N.x) """ if not isinstance(name, str): raise TypeError('Must supply a valid name') if value == 0: value = Vector(0) value = _check_vector(value) p = Point(name) p.set_pos(self, value) self.set_pos(p, -value) return p def pos_from(self, otherpoint): """Returns a Vector distance between this Point and the other Point. Parameters ========== otherpoint : Point The otherpoint we are locating this one relative to Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p2 = Point('p2') >>> p1.set_pos(p2, 10 * N.x) >>> p1.pos_from(p2) 10*N.x """ outvec = Vector(0) plist = self._pdict_list(otherpoint, 0) for i in range(len(plist) - 1): outvec += plist[i]._pos_dict[plist[i + 1]] return outvec def set_acc(self, frame, value): """Used to set the acceleration of this Point in a ReferenceFrame. Parameters ========== frame : ReferenceFrame The frame in which this point's acceleration is defined value : Vector The vector value of this point's acceleration in the frame Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p1.set_acc(N, 10 * N.x) >>> p1.acc(N) 10*N.x """ if value == 0: value = Vector(0) value = _check_vector(value) _check_frame(frame) self._acc_dict.update({frame: value}) def set_pos(self, otherpoint, value): """Used to set the position of this point w.r.t. another point. Parameters ========== otherpoint : Point The other point which this point's location is defined relative to value : Vector The vector which defines the location of this point Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p2 = Point('p2') >>> p1.set_pos(p2, 10 * N.x) >>> p1.pos_from(p2) 10*N.x """ if value == 0: value = Vector(0) value = _check_vector(value) self._check_point(otherpoint) self._pos_dict.update({otherpoint: value}) otherpoint._pos_dict.update({self: -value}) def set_vel(self, frame, value): """Sets the velocity Vector of this Point in a ReferenceFrame. Parameters ========== frame : ReferenceFrame The frame in which this point's velocity is defined value : Vector The vector value of this point's velocity in the frame Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p1.set_vel(N, 10 * N.x) >>> p1.vel(N) 10*N.x """ if value == 0: value = Vector(0) value = _check_vector(value) _check_frame(frame) self._vel_dict.update({frame: value}) def v1pt_theory(self, otherpoint, outframe, interframe): """Sets the velocity of this point with the 1-point theory. The 1-point theory for point velocity looks like this: ^N v^P = ^B v^P + ^N v^O + ^N omega^B x r^OP where O is a point fixed in B, P is a point moving in B, and B is rotating in frame N. Parameters ========== otherpoint : Point The first point of the 2-point theory (O) outframe : ReferenceFrame The frame we want this point's velocity defined in (N) interframe : ReferenceFrame The intermediate frame in this calculation (B) Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> from sympy.physics.vector import dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> q = dynamicsymbols('q') >>> q2 = dynamicsymbols('q2') >>> qd = dynamicsymbols('q', 1) >>> q2d = dynamicsymbols('q2', 1) >>> N = ReferenceFrame('N') >>> B = ReferenceFrame('B') >>> B.set_ang_vel(N, 5 * B.y) >>> O = Point('O') >>> P = O.locatenew('P', q * B.x) >>> P.set_vel(B, qd * B.x + q2d * B.y) >>> O.set_vel(N, 0) >>> P.v1pt_theory(O, N, B) q'*B.x + q2'*B.y - 5*q*B.z """ _check_frame(outframe) _check_frame(interframe) self._check_point(otherpoint) dist = self.pos_from(otherpoint) v1 = self.vel(interframe) v2 = otherpoint.vel(outframe) omega = interframe.ang_vel_in(outframe) self.set_vel(outframe, v1 + v2 + (omega ^ dist)) return self.vel(outframe) def v2pt_theory(self, otherpoint, outframe, fixedframe): """Sets the velocity of this point with the 2-point theory. The 2-point theory for point velocity looks like this: ^N v^P = ^N v^O + ^N omega^B x r^OP where O and P are both points fixed in frame B, which is rotating in frame N. Parameters ========== otherpoint : Point The first point of the 2-point theory (O) outframe : ReferenceFrame The frame we want this point's velocity defined in (N) fixedframe : ReferenceFrame The frame in which both points are fixed (B) Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> q = dynamicsymbols('q') >>> qd = dynamicsymbols('q', 1) >>> N = ReferenceFrame('N') >>> B = N.orientnew('B', 'Axis', [q, N.z]) >>> O = Point('O') >>> P = O.locatenew('P', 10 * B.x) >>> O.set_vel(N, 5 * N.x) >>> P.v2pt_theory(O, N, B) 5*N.x + 10*q'*B.y """ _check_frame(outframe) _check_frame(fixedframe) self._check_point(otherpoint) dist = self.pos_from(otherpoint) v = otherpoint.vel(outframe) omega = fixedframe.ang_vel_in(outframe) self.set_vel(outframe, v + (omega ^ dist)) return self.vel(outframe) def vel(self, frame): """The velocity Vector of this Point in the ReferenceFrame. Parameters ========== frame : ReferenceFrame The frame in which the returned velocity vector will be defined in Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p1.set_vel(N, 10 * N.x) >>> p1.vel(N) 10*N.x Velocities will be automatically calculated if possible, otherwise a ``ValueError`` will be returned. If it is possible to calculate multiple different velocities from the relative points, the points defined most directly relative to this point will be used. In the case of inconsistent relative positions of points, incorrect velocities may be returned. It is up to the user to define prior relative positions and velocities of points in a self-consistent way. >>> p = Point('p') >>> q = dynamicsymbols('q') >>> p.set_vel(N, 10 * N.x) >>> p2 = Point('p2') >>> p2.set_pos(p, q*N.x) >>> p2.vel(N) (Derivative(q(t), t) + 10)*N.x """ _check_frame(frame) if not (frame in self._vel_dict): visited = [] queue = [self] while queue: #BFS to find nearest point node = queue.pop(0) if node not in visited: visited.append(node) for neighbor, neighbor_pos in node._pos_dict.items(): try: neighbor_pos.express(frame) #Checks if pos vector is valid except ValueError: continue try : neighbor_velocity = neighbor._vel_dict[frame] #Checks if point has its vel defined in req frame except KeyError: queue.append(neighbor) continue self.set_vel(frame, self.pos_from(neighbor).dt(frame) + neighbor_velocity) return self._vel_dict[frame] else: raise ValueError('Velocity of point ' + self.name + ' has not been' ' defined in ReferenceFrame ' + frame.name) return self._vel_dict[frame] def partial_velocity(self, frame, *gen_speeds): """Returns the partial velocities of the linear velocity vector of this point in the given frame with respect to one or more provided generalized speeds. Parameters ========== frame : ReferenceFrame The frame with which the velocity is defined in. gen_speeds : functions of time The generalized speeds. Returns ======= partial_velocities : tuple of Vector The partial velocity vectors corresponding to the provided generalized speeds. Examples ======== >>> from sympy.physics.vector import ReferenceFrame, Point >>> from sympy.physics.vector import dynamicsymbols >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> p = Point('p') >>> u1, u2 = dynamicsymbols('u1, u2') >>> p.set_vel(N, u1 * N.x + u2 * A.y) >>> p.partial_velocity(N, u1) N.x >>> p.partial_velocity(N, u1, u2) (N.x, A.y) """ partials = [self.vel(frame).diff(speed, frame, var_in_dcm=False) for speed in gen_speeds] if len(partials) == 1: return partials[0] else: return tuple(partials)
1e062a43ee29cd287e74515db4fd0a613793eaeaea9b6bab134f5031de335c0f
from sympy.core.backend import (diff, expand, sin, cos, sympify, eye, symbols, ImmutableMatrix as Matrix, MatrixBase) from sympy import (trigsimp, solve, Symbol, Dummy) from sympy.physics.vector.vector import Vector, _check_vector from sympy.utilities.misc import translate __all__ = ['CoordinateSym', 'ReferenceFrame'] class CoordinateSym(Symbol): """ A coordinate symbol/base scalar associated wrt a Reference Frame. Ideally, users should not instantiate this class. Instances of this class must only be accessed through the corresponding frame as 'frame[index]'. CoordinateSyms having the same frame and index parameters are equal (even though they may be instantiated separately). Parameters ========== name : string The display name of the CoordinateSym frame : ReferenceFrame The reference frame this base scalar belongs to index : 0, 1 or 2 The index of the dimension denoted by this coordinate variable Examples ======== >>> from sympy.physics.vector import ReferenceFrame, CoordinateSym >>> A = ReferenceFrame('A') >>> A[1] A_y >>> type(A[0]) <class 'sympy.physics.vector.frame.CoordinateSym'> >>> a_y = CoordinateSym('a_y', A, 1) >>> a_y == A[1] True """ def __new__(cls, name, frame, index): # We can't use the cached Symbol.__new__ because this class depends on # frame and index, which are not passed to Symbol.__xnew__. assumptions = {} super(CoordinateSym, cls)._sanitize(assumptions, cls) obj = super(CoordinateSym, cls).__xnew__(cls, name, **assumptions) _check_frame(frame) if index not in range(0, 3): raise ValueError("Invalid index specified") obj._id = (frame, index) return obj @property def frame(self): return self._id[0] def __eq__(self, other): #Check if the other object is a CoordinateSym of the same frame #and same index if isinstance(other, CoordinateSym): if other._id == self._id: return True return False def __ne__(self, other): return not self == other def __hash__(self): return tuple((self._id[0].__hash__(), self._id[1])).__hash__() class ReferenceFrame(object): """A reference frame in classical mechanics. ReferenceFrame is a class used to represent a reference frame in classical mechanics. It has a standard basis of three unit vectors in the frame's x, y, and z directions. It also can have a rotation relative to a parent frame; this rotation is defined by a direction cosine matrix relating this frame's basis vectors to the parent frame's basis vectors. It can also have an angular velocity vector, defined in another frame. """ _count = 0 def __init__(self, name, indices=None, latexs=None, variables=None): """ReferenceFrame initialization method. A ReferenceFrame has a set of orthonormal basis vectors, along with orientations relative to other ReferenceFrames and angular velocities relative to other ReferenceFrames. Parameters ========== indices : tuple of str Enables the reference frame's basis unit vectors to be accessed by Python's square bracket indexing notation using the provided three indice strings and alters the printing of the unit vectors to reflect this choice. latexs : tuple of str Alters the LaTeX printing of the reference frame's basis unit vectors to the provided three valid LaTeX strings. Examples ======== >>> from sympy.physics.vector import ReferenceFrame, vlatex >>> N = ReferenceFrame('N') >>> N.x N.x >>> O = ReferenceFrame('O', indices=('1', '2', '3')) >>> O.x O['1'] >>> O['1'] O['1'] >>> P = ReferenceFrame('P', latexs=('A1', 'A2', 'A3')) >>> vlatex(P.x) 'A1' symbols() can be used to create multiple Reference Frames in one step, for example: >>> from sympy.physics.vector import ReferenceFrame >>> from sympy import symbols >>> A, B, C = symbols('A B C', cls=ReferenceFrame) >>> D, E = symbols('D E', cls=ReferenceFrame, indices=('1', '2', '3')) >>> A[0] A_x >>> D.x D['1'] >>> E.y E['2'] >>> type(A) == type(D) True """ if not isinstance(name, str): raise TypeError('Need to supply a valid name') # The if statements below are for custom printing of basis-vectors for # each frame. # First case, when custom indices are supplied if indices is not None: if not isinstance(indices, (tuple, list)): raise TypeError('Supply the indices as a list') if len(indices) != 3: raise ValueError('Supply 3 indices') for i in indices: if not isinstance(i, str): raise TypeError('Indices must be strings') self.str_vecs = [(name + '[\'' + indices[0] + '\']'), (name + '[\'' + indices[1] + '\']'), (name + '[\'' + indices[2] + '\']')] self.pretty_vecs = [(name.lower() + "_" + indices[0]), (name.lower() + "_" + indices[1]), (name.lower() + "_" + indices[2])] self.latex_vecs = [(r"\mathbf{\hat{%s}_{%s}}" % (name.lower(), indices[0])), (r"\mathbf{\hat{%s}_{%s}}" % (name.lower(), indices[1])), (r"\mathbf{\hat{%s}_{%s}}" % (name.lower(), indices[2]))] self.indices = indices # Second case, when no custom indices are supplied else: self.str_vecs = [(name + '.x'), (name + '.y'), (name + '.z')] self.pretty_vecs = [name.lower() + "_x", name.lower() + "_y", name.lower() + "_z"] self.latex_vecs = [(r"\mathbf{\hat{%s}_x}" % name.lower()), (r"\mathbf{\hat{%s}_y}" % name.lower()), (r"\mathbf{\hat{%s}_z}" % name.lower())] self.indices = ['x', 'y', 'z'] # Different step, for custom latex basis vectors if latexs is not None: if not isinstance(latexs, (tuple, list)): raise TypeError('Supply the indices as a list') if len(latexs) != 3: raise ValueError('Supply 3 indices') for i in latexs: if not isinstance(i, str): raise TypeError('Latex entries must be strings') self.latex_vecs = latexs self.name = name self._var_dict = {} #The _dcm_dict dictionary will only store the dcms of parent-child #relationships. The _dcm_cache dictionary will work as the dcm #cache. self._dcm_dict = {} self._dcm_cache = {} self._ang_vel_dict = {} self._ang_acc_dict = {} self._dlist = [self._dcm_dict, self._ang_vel_dict, self._ang_acc_dict] self._cur = 0 self._x = Vector([(Matrix([1, 0, 0]), self)]) self._y = Vector([(Matrix([0, 1, 0]), self)]) self._z = Vector([(Matrix([0, 0, 1]), self)]) #Associate coordinate symbols wrt this frame if variables is not None: if not isinstance(variables, (tuple, list)): raise TypeError('Supply the variable names as a list/tuple') if len(variables) != 3: raise ValueError('Supply 3 variable names') for i in variables: if not isinstance(i, str): raise TypeError('Variable names must be strings') else: variables = [name + '_x', name + '_y', name + '_z'] self.varlist = (CoordinateSym(variables[0], self, 0), \ CoordinateSym(variables[1], self, 1), \ CoordinateSym(variables[2], self, 2)) ReferenceFrame._count += 1 self.index = ReferenceFrame._count def __getitem__(self, ind): """ Returns basis vector for the provided index, if the index is a string. If the index is a number, returns the coordinate variable correspon- -ding to that index. """ if not isinstance(ind, str): if ind < 3: return self.varlist[ind] else: raise ValueError("Invalid index provided") if self.indices[0] == ind: return self.x if self.indices[1] == ind: return self.y if self.indices[2] == ind: return self.z else: raise ValueError('Not a defined index') def __iter__(self): return iter([self.x, self.y, self.z]) def __str__(self): """Returns the name of the frame. """ return self.name __repr__ = __str__ def _dict_list(self, other, num): """Creates a list from self to other using _dcm_dict. """ outlist = [[self]] oldlist = [[]] while outlist != oldlist: oldlist = outlist[:] for i, v in enumerate(outlist): templist = v[-1]._dlist[num].keys() for i2, v2 in enumerate(templist): if not v.__contains__(v2): littletemplist = v + [v2] if not outlist.__contains__(littletemplist): outlist.append(littletemplist) for i, v in enumerate(oldlist): if v[-1] != other: outlist.remove(v) outlist.sort(key=len) if len(outlist) != 0: return outlist[0] raise ValueError('No Connecting Path found between ' + self.name + ' and ' + other.name) def _w_diff_dcm(self, otherframe): """Angular velocity from time differentiating the DCM. """ from sympy.physics.vector.functions import dynamicsymbols dcm2diff = otherframe.dcm(self) diffed = dcm2diff.diff(dynamicsymbols._t) angvelmat = diffed * dcm2diff.T w1 = trigsimp(expand(angvelmat[7]), recursive=True) w2 = trigsimp(expand(angvelmat[2]), recursive=True) w3 = trigsimp(expand(angvelmat[3]), recursive=True) return Vector([(Matrix([w1, w2, w3]), otherframe)]) def variable_map(self, otherframe): """ Returns a dictionary which expresses the coordinate variables of this frame in terms of the variables of otherframe. If Vector.simp is True, returns a simplified version of the mapped values. Else, returns them without simplification. Simplification of the expressions may take time. Parameters ========== otherframe : ReferenceFrame The other frame to map the variables to Examples ======== >>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols >>> A = ReferenceFrame('A') >>> q = dynamicsymbols('q') >>> B = A.orientnew('B', 'Axis', [q, A.z]) >>> A.variable_map(B) {A_x: B_x*cos(q(t)) - B_y*sin(q(t)), A_y: B_x*sin(q(t)) + B_y*cos(q(t)), A_z: B_z} """ _check_frame(otherframe) if (otherframe, Vector.simp) in self._var_dict: return self._var_dict[(otherframe, Vector.simp)] else: vars_matrix = self.dcm(otherframe) * Matrix(otherframe.varlist) mapping = {} for i, x in enumerate(self): if Vector.simp: mapping[self.varlist[i]] = trigsimp(vars_matrix[i], method='fu') else: mapping[self.varlist[i]] = vars_matrix[i] self._var_dict[(otherframe, Vector.simp)] = mapping return mapping def ang_acc_in(self, otherframe): """Returns the angular acceleration Vector of the ReferenceFrame. Effectively returns the Vector: ^N alpha ^B which represent the angular acceleration of B in N, where B is self, and N is otherframe. Parameters ========== otherframe : ReferenceFrame The ReferenceFrame which the angular acceleration is returned in. Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> V = 10 * N.x >>> A.set_ang_acc(N, V) >>> A.ang_acc_in(N) 10*N.x """ _check_frame(otherframe) if otherframe in self._ang_acc_dict: return self._ang_acc_dict[otherframe] else: return self.ang_vel_in(otherframe).dt(otherframe) def ang_vel_in(self, otherframe): """Returns the angular velocity Vector of the ReferenceFrame. Effectively returns the Vector: ^N omega ^B which represent the angular velocity of B in N, where B is self, and N is otherframe. Parameters ========== otherframe : ReferenceFrame The ReferenceFrame which the angular velocity is returned in. Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> V = 10 * N.x >>> A.set_ang_vel(N, V) >>> A.ang_vel_in(N) 10*N.x """ _check_frame(otherframe) flist = self._dict_list(otherframe, 1) outvec = Vector(0) for i in range(len(flist) - 1): outvec += flist[i]._ang_vel_dict[flist[i + 1]] return outvec def dcm(self, otherframe): r"""Returns the direction cosine matrix relative to the provided reference frame. The returned matrix can be used to express the orthogonal unit vectors of this frame in terms of the orthogonal unit vectors of ``otherframe``. Parameters ========== otherframe : ReferenceFrame The reference frame which the direction cosine matrix of this frame is formed relative to. Examples ======== The following example rotates the reference frame A relative to N by a simple rotation and then calculates the direction cosine matrix of N relative to A. >>> from sympy import symbols, sin, cos >>> from sympy.physics.vector import ReferenceFrame >>> q1 = symbols('q1') >>> N = ReferenceFrame('N') >>> A = N.orientnew('A', 'Axis', (q1, N.x)) >>> N.dcm(A) Matrix([ [1, 0, 0], [0, cos(q1), -sin(q1)], [0, sin(q1), cos(q1)]]) The second row of the above direction cosine matrix represents the ``N.y`` unit vector in N expressed in A. Like so: >>> Ny = 0*A.x + cos(q1)*A.y - sin(q1)*A.z Thus, expressing ``N.y`` in A should return the same result: >>> N.y.express(A) cos(q1)*A.y - sin(q1)*A.z Notes ===== It is import to know what form of the direction cosine matrix is returned. If ``B.dcm(A)`` is called, it means the "direction cosine matrix of B relative to A". This is the matrix :math:`{}^A\mathbf{R}^B` shown in the following relationship: .. math:: \begin{bmatrix} \hat{\mathbf{b}}_1 \\ \hat{\mathbf{b}}_2 \\ \hat{\mathbf{b}}_3 \end{bmatrix} = {}^A\mathbf{R}^B \begin{bmatrix} \hat{\mathbf{a}}_1 \\ \hat{\mathbf{a}}_2 \\ \hat{\mathbf{a}}_3 \end{bmatrix}. :math:`^{}A\mathbf{R}^B` is the matrix that expresses the B unit vectors in terms of the A unit vectors. """ _check_frame(otherframe) # Check if the dcm wrt that frame has already been calculated if otherframe in self._dcm_cache: return self._dcm_cache[otherframe] flist = self._dict_list(otherframe, 0) outdcm = eye(3) for i in range(len(flist) - 1): outdcm = outdcm * flist[i]._dcm_dict[flist[i + 1]] # After calculation, store the dcm in dcm cache for faster future # retrieval self._dcm_cache[otherframe] = outdcm otherframe._dcm_cache[self] = outdcm.T return outdcm def orient(self, parent, rot_type, amounts, rot_order=''): """Sets the orientation of this reference frame relative to another (parent) reference frame. Parameters ========== parent : ReferenceFrame Reference frame that this reference frame will be rotated relative to. rot_type : str The method used to generate the direction cosine matrix. Supported methods are: - ``'Axis'``: simple rotations about a single common axis - ``'DCM'``: for setting the direction cosine matrix directly - ``'Body'``: three successive rotations about new intermediate axes, also called "Euler and Tait-Bryan angles" - ``'Space'``: three successive rotations about the parent frames' unit vectors - ``'Quaternion'``: rotations defined by four parameters which result in a singularity free direction cosine matrix amounts : Expressions defining the rotation angles or direction cosine matrix. These must match the ``rot_type``. See examples below for details. The input types are: - ``'Axis'``: 2-tuple (expr/sym/func, Vector) - ``'DCM'``: Matrix, shape(3,3) - ``'Body'``: 3-tuple of expressions, symbols, or functions - ``'Space'``: 3-tuple of expressions, symbols, or functions - ``'Quaternion'``: 4-tuple of expressions, symbols, or functions rot_order : str or int, optional If applicable, the order of the successive of rotations. The string ``'123'`` and integer ``123`` are equivalent, for example. Required for ``'Body'`` and ``'Space'``. Examples ======== Setup variables for the examples: >>> from sympy import symbols >>> from sympy.physics.vector import ReferenceFrame >>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3') >>> N = ReferenceFrame('N') >>> B = ReferenceFrame('B') >>> B1 = ReferenceFrame('B') >>> B2 = ReferenceFrame('B2') Axis ---- ``rot_type='Axis'`` creates a direction cosine matrix defined by a simple rotation about a single axis fixed in both reference frames. This is a rotation about an arbitrary, non-time-varying axis by some angle. The axis is supplied as a Vector. This is how simple rotations are defined. >>> B.orient(N, 'Axis', (q1, N.x)) The ``orient()`` method generates a direction cosine matrix and its transpose which defines the orientation of B relative to N and vice versa. Once orient is called, ``dcm()`` outputs the appropriate direction cosine matrix. >>> B.dcm(N) Matrix([ [1, 0, 0], [0, cos(q1), sin(q1)], [0, -sin(q1), cos(q1)]]) The following two lines show how the sense of the rotation can be defined. Both lines produce the same result. >>> B.orient(N, 'Axis', (q1, -N.x)) >>> B.orient(N, 'Axis', (-q1, N.x)) The axis does not have to be defined by a unit vector, it can be any vector in the parent frame. >>> B.orient(N, 'Axis', (q1, N.x + 2 * N.y)) DCM --- The direction cosine matrix can be set directly. The orientation of a frame A can be set to be the same as the frame B above like so: >>> B.orient(N, 'Axis', (q1, N.x)) >>> A = ReferenceFrame('A') >>> A.orient(N, 'DCM', N.dcm(B)) >>> A.dcm(N) Matrix([ [1, 0, 0], [0, cos(q1), sin(q1)], [0, -sin(q1), cos(q1)]]) **Note carefully that** ``N.dcm(B)`` **was passed into** ``orient()`` **for** ``A.dcm(N)`` **to match** ``B.dcm(N)``. Body ---- ``rot_type='Body'`` rotates this reference frame relative to the provided reference frame by rotating through three successive simple rotations. Each subsequent axis of rotation is about the "body fixed" unit vectors of the new intermediate reference frame. This type of rotation is also referred to rotating through the `Euler and Tait-Bryan Angles <https://en.wikipedia.org/wiki/Euler_angles>`_. For example, the classic Euler Angle rotation can be done by: >>> B.orient(N, 'Body', (q1, q2, q3), 'XYX') >>> B.dcm(N) Matrix([ [ cos(q2), sin(q1)*sin(q2), -sin(q2)*cos(q1)], [sin(q2)*sin(q3), -sin(q1)*sin(q3)*cos(q2) + cos(q1)*cos(q3), sin(q1)*cos(q3) + sin(q3)*cos(q1)*cos(q2)], [sin(q2)*cos(q3), -sin(q1)*cos(q2)*cos(q3) - sin(q3)*cos(q1), -sin(q1)*sin(q3) + cos(q1)*cos(q2)*cos(q3)]]) This rotates B relative to N through ``q1`` about ``N.x``, then rotates B again through q2 about B.y, and finally through q3 about B.x. It is equivalent to: >>> B1.orient(N, 'Axis', (q1, N.x)) >>> B2.orient(B1, 'Axis', (q2, B1.y)) >>> B.orient(B2, 'Axis', (q3, B2.x)) >>> B.dcm(N) Matrix([ [ cos(q2), sin(q1)*sin(q2), -sin(q2)*cos(q1)], [sin(q2)*sin(q3), -sin(q1)*sin(q3)*cos(q2) + cos(q1)*cos(q3), sin(q1)*cos(q3) + sin(q3)*cos(q1)*cos(q2)], [sin(q2)*cos(q3), -sin(q1)*cos(q2)*cos(q3) - sin(q3)*cos(q1), -sin(q1)*sin(q3) + cos(q1)*cos(q2)*cos(q3)]]) Acceptable rotation orders are of length 3, expressed in as a string ``'XYZ'`` or ``'123'`` or integer ``123``. Rotations about an axis twice in a row are prohibited. >>> B.orient(N, 'Body', (q1, q2, 0), 'ZXZ') >>> B.orient(N, 'Body', (q1, q2, 0), '121') >>> B.orient(N, 'Body', (q1, q2, q3), 123) Space ----- ``rot_type='Space'`` also rotates the reference frame in three successive simple rotations but the axes of rotation are the "Space-fixed" axes. For example: >>> B.orient(N, 'Space', (q1, q2, q3), '312') >>> B.dcm(N) Matrix([ [ sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1)], [-sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3)], [ sin(q3)*cos(q2), -sin(q2), cos(q2)*cos(q3)]]) is equivalent to: >>> B1.orient(N, 'Axis', (q1, N.z)) >>> B2.orient(B1, 'Axis', (q2, N.x)) >>> B.orient(B2, 'Axis', (q3, N.y)) >>> B.dcm(N).simplify() # doctest: +SKIP Matrix([ [ sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1)], [-sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3)], [ sin(q3)*cos(q2), -sin(q2), cos(q2)*cos(q3)]]) It is worth noting that space-fixed and body-fixed rotations are related by the order of the rotations, i.e. the reverse order of body fixed will give space fixed and vice versa. >>> B.orient(N, 'Space', (q1, q2, q3), '231') >>> B.dcm(N) Matrix([ [cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), -sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)], [ -sin(q2), cos(q2)*cos(q3), sin(q3)*cos(q2)], [sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3)]]) >>> B.orient(N, 'Body', (q3, q2, q1), '132') >>> B.dcm(N) Matrix([ [cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), -sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)], [ -sin(q2), cos(q2)*cos(q3), sin(q3)*cos(q2)], [sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3)]]) Quaternion ---------- ``rot_type='Quaternion'`` orients the reference frame using quaternions. Quaternion rotation is defined as a finite rotation about lambda, a unit vector, by an amount theta. This orientation is described by four parameters: - ``q0 = cos(theta/2)`` - ``q1 = lambda_x sin(theta/2)`` - ``q2 = lambda_y sin(theta/2)`` - ``q3 = lambda_z sin(theta/2)`` This type does not need a ``rot_order``. >>> B.orient(N, 'Quaternion', (q0, q1, q2, q3)) >>> B.dcm(N) Matrix([ [q0**2 + q1**2 - q2**2 - q3**2, 2*q0*q3 + 2*q1*q2, -2*q0*q2 + 2*q1*q3], [ -2*q0*q3 + 2*q1*q2, q0**2 - q1**2 + q2**2 - q3**2, 2*q0*q1 + 2*q2*q3], [ 2*q0*q2 + 2*q1*q3, -2*q0*q1 + 2*q2*q3, q0**2 - q1**2 - q2**2 + q3**2]]) """ from sympy.physics.vector.functions import dynamicsymbols _check_frame(parent) # Allow passing a rotation matrix manually. if rot_type == 'DCM': # When rot_type == 'DCM', then amounts must be a Matrix type object # (e.g. sympy.matrices.dense.MutableDenseMatrix). if not isinstance(amounts, MatrixBase): raise TypeError("Amounts must be a sympy Matrix type object.") else: amounts = list(amounts) for i, v in enumerate(amounts): if not isinstance(v, Vector): amounts[i] = sympify(v) def _rot(axis, angle): """DCM for simple axis 1,2,or 3 rotations. """ if axis == 1: return Matrix([[1, 0, 0], [0, cos(angle), -sin(angle)], [0, sin(angle), cos(angle)]]) elif axis == 2: return Matrix([[cos(angle), 0, sin(angle)], [0, 1, 0], [-sin(angle), 0, cos(angle)]]) elif axis == 3: return Matrix([[cos(angle), -sin(angle), 0], [sin(angle), cos(angle), 0], [0, 0, 1]]) approved_orders = ('123', '231', '312', '132', '213', '321', '121', '131', '212', '232', '313', '323', '') # make sure XYZ => 123 and rot_type is in upper case rot_order = translate(str(rot_order), 'XYZxyz', '123123') rot_type = rot_type.upper() if rot_order not in approved_orders: raise TypeError('The supplied order is not an approved type') parent_orient = [] if rot_type == 'AXIS': if not rot_order == '': raise TypeError('Axis orientation takes no rotation order') if not (isinstance(amounts, (list, tuple)) & (len(amounts) == 2)): raise TypeError('Amounts are a list or tuple of length 2') theta = amounts[0] axis = amounts[1] axis = _check_vector(axis) if not axis.dt(parent) == 0: raise ValueError('Axis cannot be time-varying') axis = axis.express(parent).normalize() axis = axis.args[0][0] parent_orient = ((eye(3) - axis * axis.T) * cos(theta) + Matrix([[0, -axis[2], axis[1]], [axis[2], 0, -axis[0]], [-axis[1], axis[0], 0]]) * sin(theta) + axis * axis.T) elif rot_type == 'QUATERNION': if not rot_order == '': raise TypeError( 'Quaternion orientation takes no rotation order') if not (isinstance(amounts, (list, tuple)) & (len(amounts) == 4)): raise TypeError('Amounts are a list or tuple of length 4') q0, q1, q2, q3 = amounts parent_orient = (Matrix([[q0**2 + q1**2 - q2**2 - q3**2, 2 * (q1 * q2 - q0 * q3), 2 * (q0 * q2 + q1 * q3)], [2 * (q1 * q2 + q0 * q3), q0**2 - q1**2 + q2**2 - q3**2, 2 * (q2 * q3 - q0 * q1)], [2 * (q1 * q3 - q0 * q2), 2 * (q0 * q1 + q2 * q3), q0**2 - q1**2 - q2**2 + q3**2]])) elif rot_type == 'BODY': if not (len(amounts) == 3 & len(rot_order) == 3): raise TypeError('Body orientation takes 3 values & 3 orders') a1 = int(rot_order[0]) a2 = int(rot_order[1]) a3 = int(rot_order[2]) parent_orient = (_rot(a1, amounts[0]) * _rot(a2, amounts[1]) * _rot(a3, amounts[2])) elif rot_type == 'SPACE': if not (len(amounts) == 3 & len(rot_order) == 3): raise TypeError('Space orientation takes 3 values & 3 orders') a1 = int(rot_order[0]) a2 = int(rot_order[1]) a3 = int(rot_order[2]) parent_orient = (_rot(a3, amounts[2]) * _rot(a2, amounts[1]) * _rot(a1, amounts[0])) elif rot_type == 'DCM': parent_orient = amounts else: raise NotImplementedError('That is not an implemented rotation') # Reset the _dcm_cache of this frame, and remove it from the # _dcm_caches of the frames it is linked to. Also remove it from the # _dcm_dict of its parent frames = self._dcm_cache.keys() dcm_dict_del = [] dcm_cache_del = [] for frame in frames: if frame in self._dcm_dict: dcm_dict_del += [frame] dcm_cache_del += [frame] for frame in dcm_dict_del: del frame._dcm_dict[self] for frame in dcm_cache_del: del frame._dcm_cache[self] # Add the dcm relationship to _dcm_dict self._dcm_dict = self._dlist[0] = {} self._dcm_dict.update({parent: parent_orient.T}) parent._dcm_dict.update({self: parent_orient}) # Also update the dcm cache after resetting it self._dcm_cache = {} self._dcm_cache.update({parent: parent_orient.T}) parent._dcm_cache.update({self: parent_orient}) if rot_type == 'QUATERNION': t = dynamicsymbols._t q0, q1, q2, q3 = amounts q0d = diff(q0, t) q1d = diff(q1, t) q2d = diff(q2, t) q3d = diff(q3, t) w1 = 2 * (q1d * q0 + q2d * q3 - q3d * q2 - q0d * q1) w2 = 2 * (q2d * q0 + q3d * q1 - q1d * q3 - q0d * q2) w3 = 2 * (q3d * q0 + q1d * q2 - q2d * q1 - q0d * q3) wvec = Vector([(Matrix([w1, w2, w3]), self)]) elif rot_type == 'AXIS': thetad = (amounts[0]).diff(dynamicsymbols._t) wvec = thetad * amounts[1].express(parent).normalize() elif rot_type == 'DCM': wvec = self._w_diff_dcm(parent) else: try: from sympy.polys.polyerrors import CoercionFailed from sympy.physics.vector.functions import kinematic_equations q1, q2, q3 = amounts u1, u2, u3 = symbols('u1, u2, u3', cls=Dummy) templist = kinematic_equations([u1, u2, u3], [q1, q2, q3], rot_type, rot_order) templist = [expand(i) for i in templist] td = solve(templist, [u1, u2, u3]) u1 = expand(td[u1]) u2 = expand(td[u2]) u3 = expand(td[u3]) wvec = u1 * self.x + u2 * self.y + u3 * self.z except (CoercionFailed, AssertionError): wvec = self._w_diff_dcm(parent) self._ang_vel_dict.update({parent: wvec}) parent._ang_vel_dict.update({self: -wvec}) self._var_dict = {} def orientnew(self, newname, rot_type, amounts, rot_order='', variables=None, indices=None, latexs=None): r"""Returns a new reference frame oriented with respect to this reference frame. See ``ReferenceFrame.orient()`` for detailed examples of how to orient reference frames. Parameters ========== newname : str Name for the new reference frame. rot_type : str The method used to generate the direction cosine matrix. Supported methods are: - ``'Axis'``: simple rotations about a single common axis - ``'DCM'``: for setting the direction cosine matrix directly - ``'Body'``: three successive rotations about new intermediate axes, also called "Euler and Tait-Bryan angles" - ``'Space'``: three successive rotations about the parent frames' unit vectors - ``'Quaternion'``: rotations defined by four parameters which result in a singularity free direction cosine matrix amounts : Expressions defining the rotation angles or direction cosine matrix. These must match the ``rot_type``. See examples below for details. The input types are: - ``'Axis'``: 2-tuple (expr/sym/func, Vector) - ``'DCM'``: Matrix, shape(3,3) - ``'Body'``: 3-tuple of expressions, symbols, or functions - ``'Space'``: 3-tuple of expressions, symbols, or functions - ``'Quaternion'``: 4-tuple of expressions, symbols, or functions rot_order : str or int, optional If applicable, the order of the successive of rotations. The string ``'123'`` and integer ``123`` are equivalent, for example. Required for ``'Body'`` and ``'Space'``. indices : tuple of str Enables the reference frame's basis unit vectors to be accessed by Python's square bracket indexing notation using the provided three indice strings and alters the printing of the unit vectors to reflect this choice. latexs : tuple of str Alters the LaTeX printing of the reference frame's basis unit vectors to the provided three valid LaTeX strings. Examples ======== >>> from sympy import symbols >>> from sympy.physics.vector import ReferenceFrame, vlatex >>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3') >>> N = ReferenceFrame('N') Create a new reference frame A rotated relative to N through a simple rotation. >>> A = N.orientnew('A', 'Axis', (q0, N.x)) Create a new reference frame B rotated relative to N through body-fixed rotations. >>> B = N.orientnew('B', 'Body', (q1, q2, q3), '123') Create a new reference frame C rotated relative to N through a simple rotation with unique indices and LaTeX printing. >>> C = N.orientnew('C', 'Axis', (q0, N.x), indices=('1', '2', '3'), ... latexs=(r'\hat{\mathbf{c}}_1',r'\hat{\mathbf{c}}_2', ... r'\hat{\mathbf{c}}_3')) >>> C['1'] C['1'] >>> print(vlatex(C['1'])) \hat{\mathbf{c}}_1 """ newframe = self.__class__(newname, variables=variables, indices=indices, latexs=latexs) newframe.orient(self, rot_type, amounts, rot_order) return newframe def set_ang_acc(self, otherframe, value): """Define the angular acceleration Vector in a ReferenceFrame. Defines the angular acceleration of this ReferenceFrame, in another. Angular acceleration can be defined with respect to multiple different ReferenceFrames. Care must be taken to not create loops which are inconsistent. Parameters ========== otherframe : ReferenceFrame A ReferenceFrame to define the angular acceleration in value : Vector The Vector representing angular acceleration Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> V = 10 * N.x >>> A.set_ang_acc(N, V) >>> A.ang_acc_in(N) 10*N.x """ if value == 0: value = Vector(0) value = _check_vector(value) _check_frame(otherframe) self._ang_acc_dict.update({otherframe: value}) otherframe._ang_acc_dict.update({self: -value}) def set_ang_vel(self, otherframe, value): """Define the angular velocity vector in a ReferenceFrame. Defines the angular velocity of this ReferenceFrame, in another. Angular velocity can be defined with respect to multiple different ReferenceFrames. Care must be taken to not create loops which are inconsistent. Parameters ========== otherframe : ReferenceFrame A ReferenceFrame to define the angular velocity in value : Vector The Vector representing angular velocity Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> V = 10 * N.x >>> A.set_ang_vel(N, V) >>> A.ang_vel_in(N) 10*N.x """ if value == 0: value = Vector(0) value = _check_vector(value) _check_frame(otherframe) self._ang_vel_dict.update({otherframe: value}) otherframe._ang_vel_dict.update({self: -value}) @property def x(self): """The basis Vector for the ReferenceFrame, in the x direction. """ return self._x @property def y(self): """The basis Vector for the ReferenceFrame, in the y direction. """ return self._y @property def z(self): """The basis Vector for the ReferenceFrame, in the z direction. """ return self._z def partial_velocity(self, frame, *gen_speeds): """Returns the partial angular velocities of this frame in the given frame with respect to one or more provided generalized speeds. Parameters ========== frame : ReferenceFrame The frame with which the angular velocity is defined in. gen_speeds : functions of time The generalized speeds. Returns ======= partial_velocities : tuple of Vector The partial angular velocity vectors corresponding to the provided generalized speeds. Examples ======== >>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> u1, u2 = dynamicsymbols('u1, u2') >>> A.set_ang_vel(N, u1 * A.x + u2 * N.y) >>> A.partial_velocity(N, u1) A.x >>> A.partial_velocity(N, u1, u2) (A.x, N.y) """ partials = [self.ang_vel_in(frame).diff(speed, frame, var_in_dcm=False) for speed in gen_speeds] if len(partials) == 1: return partials[0] else: return tuple(partials) def _check_frame(other): from .vector import VectorTypeError if not isinstance(other, ReferenceFrame): raise VectorTypeError(other, ReferenceFrame('A'))
96b99cafcb5512dc51dd7b67136bf56d7ab4ce580dd945cfc3a6a13f8f441645
from sympy.core.backend import sympify, Add, ImmutableMatrix as Matrix from sympy.printing.defaults import Printable __all__ = ['Dyadic'] class Dyadic(Printable): """A Dyadic object. See: https://en.wikipedia.org/wiki/Dyadic_tensor Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill A more powerful way to represent a rigid body's inertia. While it is more complex, by choosing Dyadic components to be in body fixed basis vectors, the resulting matrix is equivalent to the inertia tensor. """ def __init__(self, inlist): """ Just like Vector's init, you shouldn't call this unless creating a zero dyadic. zd = Dyadic(0) Stores a Dyadic as a list of lists; the inner list has the measure number and the two unit vectors; the outerlist holds each unique unit vector pair. """ self.args = [] if inlist == 0: inlist = [] while len(inlist) != 0: added = 0 for i, v in enumerate(self.args): if ((str(inlist[0][1]) == str(self.args[i][1])) and (str(inlist[0][2]) == str(self.args[i][2]))): self.args[i] = (self.args[i][0] + inlist[0][0], inlist[0][1], inlist[0][2]) inlist.remove(inlist[0]) added = 1 break if added != 1: self.args.append(inlist[0]) inlist.remove(inlist[0]) i = 0 # This code is to remove empty parts from the list while i < len(self.args): if ((self.args[i][0] == 0) | (self.args[i][1] == 0) | (self.args[i][2] == 0)): self.args.remove(self.args[i]) i -= 1 i += 1 def __add__(self, other): """The add operator for Dyadic. """ other = _check_dyadic(other) return Dyadic(self.args + other.args) def __and__(self, other): """The inner product operator for a Dyadic and a Dyadic or Vector. Parameters ========== other : Dyadic or Vector The other Dyadic or Vector to take the inner product with Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer >>> N = ReferenceFrame('N') >>> D1 = outer(N.x, N.y) >>> D2 = outer(N.y, N.y) >>> D1.dot(D2) (N.x|N.y) >>> D1.dot(N.y) N.x """ from sympy.physics.vector.vector import Vector, _check_vector if isinstance(other, Dyadic): other = _check_dyadic(other) ol = Dyadic(0) for i, v in enumerate(self.args): for i2, v2 in enumerate(other.args): ol += v[0] * v2[0] * (v[2] & v2[1]) * (v[1] | v2[2]) else: other = _check_vector(other) ol = Vector(0) for i, v in enumerate(self.args): ol += v[0] * v[1] * (v[2] & other) return ol def __truediv__(self, other): """Divides the Dyadic by a sympifyable expression. """ return self.__mul__(1 / other) def __eq__(self, other): """Tests for equality. Is currently weak; needs stronger comparison testing """ if other == 0: other = Dyadic(0) other = _check_dyadic(other) if (self.args == []) and (other.args == []): return True elif (self.args == []) or (other.args == []): return False return set(self.args) == set(other.args) def __mul__(self, other): """Multiplies the Dyadic by a sympifyable expression. Parameters ========== other : Sympafiable The scalar to multiply this Dyadic with Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer >>> N = ReferenceFrame('N') >>> d = outer(N.x, N.x) >>> 5 * d 5*(N.x|N.x) """ newlist = [v for v in self.args] for i, v in enumerate(newlist): newlist[i] = (sympify(other) * newlist[i][0], newlist[i][1], newlist[i][2]) return Dyadic(newlist) def __ne__(self, other): return not self == other def __neg__(self): return self * -1 def _latex(self, printer): ar = self.args # just to shorten things if len(ar) == 0: return str(0) ol = [] # output list, to be concatenated to a string for i, v in enumerate(ar): # if the coef of the dyadic is 1, we skip the 1 if ar[i][0] == 1: ol.append(' + ' + printer._print(ar[i][1]) + r"\otimes " + printer._print(ar[i][2])) # if the coef of the dyadic is -1, we skip the 1 elif ar[i][0] == -1: ol.append(' - ' + printer._print(ar[i][1]) + r"\otimes " + printer._print(ar[i][2])) # If the coefficient of the dyadic is not 1 or -1, # we might wrap it in parentheses, for readability. elif ar[i][0] != 0: arg_str = printer._print(ar[i][0]) if isinstance(ar[i][0], Add): arg_str = '(%s)' % arg_str if arg_str.startswith('-'): arg_str = arg_str[1:] str_start = ' - ' else: str_start = ' + ' ol.append(str_start + arg_str + printer._print(ar[i][1]) + r"\otimes " + printer._print(ar[i][2])) outstr = ''.join(ol) if outstr.startswith(' + '): outstr = outstr[3:] elif outstr.startswith(' '): outstr = outstr[1:] return outstr def _pretty(self, printer): e = self class Fake(object): baseline = 0 def render(self, *args, **kwargs): ar = e.args # just to shorten things mpp = printer if len(ar) == 0: return str(0) bar = "\N{CIRCLED TIMES}" if printer._use_unicode else "|" ol = [] # output list, to be concatenated to a string for i, v in enumerate(ar): # if the coef of the dyadic is 1, we skip the 1 if ar[i][0] == 1: ol.extend([" + ", mpp.doprint(ar[i][1]), bar, mpp.doprint(ar[i][2])]) # if the coef of the dyadic is -1, we skip the 1 elif ar[i][0] == -1: ol.extend([" - ", mpp.doprint(ar[i][1]), bar, mpp.doprint(ar[i][2])]) # If the coefficient of the dyadic is not 1 or -1, # we might wrap it in parentheses, for readability. elif ar[i][0] != 0: if isinstance(ar[i][0], Add): arg_str = mpp._print( ar[i][0]).parens()[0] else: arg_str = mpp.doprint(ar[i][0]) if arg_str.startswith("-"): arg_str = arg_str[1:] str_start = " - " else: str_start = " + " ol.extend([str_start, arg_str, " ", mpp.doprint(ar[i][1]), bar, mpp.doprint(ar[i][2])]) outstr = "".join(ol) if outstr.startswith(" + "): outstr = outstr[3:] elif outstr.startswith(" "): outstr = outstr[1:] return outstr return Fake() def __rand__(self, other): """The inner product operator for a Vector or Dyadic, and a Dyadic This is for: Vector dot Dyadic Parameters ========== other : Vector The vector we are dotting with Examples ======== >>> from sympy.physics.vector import ReferenceFrame, dot, outer >>> N = ReferenceFrame('N') >>> d = outer(N.x, N.x) >>> dot(N.x, d) N.x """ from sympy.physics.vector.vector import Vector, _check_vector other = _check_vector(other) ol = Vector(0) for i, v in enumerate(self.args): ol += v[0] * v[2] * (v[1] & other) return ol def __rsub__(self, other): return (-1 * self) + other def __rxor__(self, other): """For a cross product in the form: Vector x Dyadic Parameters ========== other : Vector The Vector that we are crossing this Dyadic with Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer, cross >>> N = ReferenceFrame('N') >>> d = outer(N.x, N.x) >>> cross(N.y, d) - (N.z|N.x) """ from sympy.physics.vector.vector import _check_vector other = _check_vector(other) ol = Dyadic(0) for i, v in enumerate(self.args): ol += v[0] * ((other ^ v[1]) | v[2]) return ol def _sympystr(self, printer): """Printing method. """ ar = self.args # just to shorten things if len(ar) == 0: return printer._print(0) ol = [] # output list, to be concatenated to a string for i, v in enumerate(ar): # if the coef of the dyadic is 1, we skip the 1 if ar[i][0] == 1: ol.append(' + (' + printer._print(ar[i][1]) + '|' + printer._print(ar[i][2]) + ')') # if the coef of the dyadic is -1, we skip the 1 elif ar[i][0] == -1: ol.append(' - (' + printer._print(ar[i][1]) + '|' + printer._print(ar[i][2]) + ')') # If the coefficient of the dyadic is not 1 or -1, # we might wrap it in parentheses, for readability. elif ar[i][0] != 0: arg_str = printer._print(ar[i][0]) if isinstance(ar[i][0], Add): arg_str = "(%s)" % arg_str if arg_str[0] == '-': arg_str = arg_str[1:] str_start = ' - ' else: str_start = ' + ' ol.append(str_start + arg_str + '*(' + printer._print(ar[i][1]) + '|' + printer._print(ar[i][2]) + ')') outstr = ''.join(ol) if outstr.startswith(' + '): outstr = outstr[3:] elif outstr.startswith(' '): outstr = outstr[1:] return outstr def __sub__(self, other): """The subtraction operator. """ return self.__add__(other * -1) def __xor__(self, other): """For a cross product in the form: Dyadic x Vector. Parameters ========== other : Vector The Vector that we are crossing this Dyadic with Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer, cross >>> N = ReferenceFrame('N') >>> d = outer(N.x, N.x) >>> cross(d, N.y) (N.x|N.z) """ from sympy.physics.vector.vector import _check_vector other = _check_vector(other) ol = Dyadic(0) for i, v in enumerate(self.args): ol += v[0] * (v[1] | (v[2] ^ other)) return ol __radd__ = __add__ __rmul__ = __mul__ def express(self, frame1, frame2=None): """Expresses this Dyadic in alternate frame(s) The first frame is the list side expression, the second frame is the right side; if Dyadic is in form A.x|B.y, you can express it in two different frames. If no second frame is given, the Dyadic is expressed in only one frame. Calls the global express function Parameters ========== frame1 : ReferenceFrame The frame to express the left side of the Dyadic in frame2 : ReferenceFrame If provided, the frame to express the right side of the Dyadic in Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> N = ReferenceFrame('N') >>> q = dynamicsymbols('q') >>> B = N.orientnew('B', 'Axis', [q, N.z]) >>> d = outer(N.x, N.x) >>> d.express(B, N) cos(q)*(B.x|N.x) - sin(q)*(B.y|N.x) """ from sympy.physics.vector.functions import express return express(self, frame1, frame2) def to_matrix(self, reference_frame, second_reference_frame=None): """Returns the matrix form of the dyadic with respect to one or two reference frames. Parameters ---------- reference_frame : ReferenceFrame The reference frame that the rows and columns of the matrix correspond to. If a second reference frame is provided, this only corresponds to the rows of the matrix. second_reference_frame : ReferenceFrame, optional, default=None The reference frame that the columns of the matrix correspond to. Returns ------- matrix : ImmutableMatrix, shape(3,3) The matrix that gives the 2D tensor form. Examples ======== >>> from sympy import symbols >>> from sympy.physics.vector import ReferenceFrame, Vector >>> Vector.simp = True >>> from sympy.physics.mechanics import inertia >>> Ixx, Iyy, Izz, Ixy, Iyz, Ixz = symbols('Ixx, Iyy, Izz, Ixy, Iyz, Ixz') >>> N = ReferenceFrame('N') >>> inertia_dyadic = inertia(N, Ixx, Iyy, Izz, Ixy, Iyz, Ixz) >>> inertia_dyadic.to_matrix(N) Matrix([ [Ixx, Ixy, Ixz], [Ixy, Iyy, Iyz], [Ixz, Iyz, Izz]]) >>> beta = symbols('beta') >>> A = N.orientnew('A', 'Axis', (beta, N.x)) >>> inertia_dyadic.to_matrix(A) Matrix([ [ Ixx, Ixy*cos(beta) + Ixz*sin(beta), -Ixy*sin(beta) + Ixz*cos(beta)], [ Ixy*cos(beta) + Ixz*sin(beta), Iyy*cos(2*beta)/2 + Iyy/2 + Iyz*sin(2*beta) - Izz*cos(2*beta)/2 + Izz/2, -Iyy*sin(2*beta)/2 + Iyz*cos(2*beta) + Izz*sin(2*beta)/2], [-Ixy*sin(beta) + Ixz*cos(beta), -Iyy*sin(2*beta)/2 + Iyz*cos(2*beta) + Izz*sin(2*beta)/2, -Iyy*cos(2*beta)/2 + Iyy/2 - Iyz*sin(2*beta) + Izz*cos(2*beta)/2 + Izz/2]]) """ if second_reference_frame is None: second_reference_frame = reference_frame return Matrix([i.dot(self).dot(j) for i in reference_frame for j in second_reference_frame]).reshape(3, 3) def doit(self, **hints): """Calls .doit() on each term in the Dyadic""" return sum([Dyadic([(v[0].doit(**hints), v[1], v[2])]) for v in self.args], Dyadic(0)) def dt(self, frame): """Take the time derivative of this Dyadic in a frame. This function calls the global time_derivative method Parameters ========== frame : ReferenceFrame The frame to take the time derivative in Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> N = ReferenceFrame('N') >>> q = dynamicsymbols('q') >>> B = N.orientnew('B', 'Axis', [q, N.z]) >>> d = outer(N.x, N.x) >>> d.dt(B) - q'*(N.y|N.x) - q'*(N.x|N.y) """ from sympy.physics.vector.functions import time_derivative return time_derivative(self, frame) def simplify(self): """Returns a simplified Dyadic.""" out = Dyadic(0) for v in self.args: out += Dyadic([(v[0].simplify(), v[1], v[2])]) return out def subs(self, *args, **kwargs): """Substitution on the Dyadic. Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> from sympy import Symbol >>> N = ReferenceFrame('N') >>> s = Symbol('s') >>> a = s*(N.x|N.x) >>> a.subs({s: 2}) 2*(N.x|N.x) """ return sum([Dyadic([(v[0].subs(*args, **kwargs), v[1], v[2])]) for v in self.args], Dyadic(0)) def applyfunc(self, f): """Apply a function to each component of a Dyadic.""" if not callable(f): raise TypeError("`f` must be callable.") out = Dyadic(0) for a, b, c in self.args: out += f(a) * (b|c) return out dot = __and__ cross = __xor__ def _check_dyadic(other): if not isinstance(other, Dyadic): raise TypeError('A Dyadic must be supplied') return other
9d9124545e8f7489eb7271091c44b013b0548ea1fb9606aa8dfebe1c4d007252
#!/usr/bin/env python # -*- coding: utf-8 -*- u""" The module implements routines to model the polarization of optical fields and can be used to calculate the effects of polarization optical elements on the fields. - Jones vectors. - Stokes vectors. - Jones matrices. - Mueller matrices. Examples -------- We calculate a generic Jones vector: >>> from sympy import symbols, pprint, zeros, simplify >>> from sympy.physics.optics.polarization import (jones_vector, stokes_vector, ... half_wave_retarder, polarizing_beam_splitter, jones_2_stokes) >>> psi, chi, p, I0 = symbols("psi, chi, p, I0", real=True) >>> x0 = jones_vector(psi, chi) >>> pprint(x0, use_unicode=True) ⎡-ⅈ⋅sin(χ)⋅sin(ψ) + cos(χ)⋅cos(ψ)⎤ ⎢ ⎥ ⎣ⅈ⋅sin(χ)⋅cos(ψ) + sin(ψ)⋅cos(χ) ⎦ And the more general Stokes vector: >>> s0 = stokes_vector(psi, chi, p, I0) >>> pprint(s0, use_unicode=True) ⎡ I₀ ⎤ ⎢ ⎥ ⎢I₀⋅p⋅cos(2⋅χ)⋅cos(2⋅ψ)⎥ ⎢ ⎥ ⎢I₀⋅p⋅sin(2⋅ψ)⋅cos(2⋅χ)⎥ ⎢ ⎥ ⎣ I₀⋅p⋅sin(2⋅χ) ⎦ We calculate how the Jones vector is modified by a half-wave plate: >>> alpha = symbols("alpha", real=True) >>> HWP = half_wave_retarder(alpha) >>> x1 = simplify(HWP*x0) We calculate the very common operation of passing a beam through a half-wave plate and then through a polarizing beam-splitter. We do this by putting this Jones vector as the first entry of a two-Jones-vector state that is transformed by a 4x4 Jones matrix modelling the polarizing beam-splitter to get the transmitted and reflected Jones vectors: >>> PBS = polarizing_beam_splitter() >>> X1 = zeros(4, 1) >>> X1[:2, :] = x1 >>> X2 = PBS*X1 >>> transmitted_port = X2[:2, :] >>> reflected_port = X2[2:, :] This allows us to calculate how the power in both ports depends on the initial polarization: >>> transmitted_power = jones_2_stokes(transmitted_port)[0] >>> reflected_power = jones_2_stokes(reflected_port)[0] >>> print(transmitted_power) cos(-2*alpha + chi + psi)**2/2 + cos(2*alpha + chi - psi)**2/2 >>> print(reflected_power) sin(-2*alpha + chi + psi)**2/2 + sin(2*alpha + chi - psi)**2/2 Please see the description of the individual functions for further details and examples. References ========== .. [1] https://en.wikipedia.org/wiki/Jones_calculus .. [2] https://en.wikipedia.org/wiki/Mueller_calculus .. [3] https://en.wikipedia.org/wiki/Stokes_parameters """ from sympy import sin, cos, exp, I, pi, sqrt, Matrix, Abs, re, im, simplify from sympy.physics.quantum import TensorProduct def jones_vector(psi, chi): u"""A Jones vector corresponding to a polarization ellipse with `psi` tilt, and `chi` circularity. Parameters ---------- ``psi`` : numeric type or sympy Symbol The tilt of the polarization relative to the `x` axis. ``chi`` : numeric type or sympy Symbol The angle adjacent to the mayor axis of the polarization ellipse. Returns ------- Matrix A Jones vector. Examples -------- The axes on the Poincaré sphere. >>> from sympy import pprint, symbols, pi >>> from sympy.physics.optics.polarization import jones_vector >>> psi, chi = symbols("psi, chi", real=True) A general Jones vector. >>> pprint(jones_vector(psi, chi), use_unicode=True) ⎡-ⅈ⋅sin(χ)⋅sin(ψ) + cos(χ)⋅cos(ψ)⎤ ⎢ ⎥ ⎣ⅈ⋅sin(χ)⋅cos(ψ) + sin(ψ)⋅cos(χ) ⎦ Horizontal polarization. >>> pprint(jones_vector(0, 0), use_unicode=True) ⎡1⎤ ⎢ ⎥ ⎣0⎦ Vertical polarization. >>> pprint(jones_vector(pi/2, 0), use_unicode=True) ⎡0⎤ ⎢ ⎥ ⎣1⎦ Diagonal polarization. >>> pprint(jones_vector(pi/4, 0), use_unicode=True) ⎡√2⎤ ⎢──⎥ ⎢2 ⎥ ⎢ ⎥ ⎢√2⎥ ⎢──⎥ ⎣2 ⎦ Anti-diagonal polarization. >>> pprint(jones_vector(-pi/4, 0), use_unicode=True) ⎡ √2 ⎤ ⎢ ── ⎥ ⎢ 2 ⎥ ⎢ ⎥ ⎢-√2 ⎥ ⎢────⎥ ⎣ 2 ⎦ Right-hand circular polarization. >>> pprint(jones_vector(0, pi/4), use_unicode=True) ⎡ √2 ⎤ ⎢ ── ⎥ ⎢ 2 ⎥ ⎢ ⎥ ⎢√2⋅ⅈ⎥ ⎢────⎥ ⎣ 2 ⎦ Left-hand circular polarization. >>> pprint(jones_vector(0, -pi/4), use_unicode=True) ⎡ √2 ⎤ ⎢ ── ⎥ ⎢ 2 ⎥ ⎢ ⎥ ⎢-√2⋅ⅈ ⎥ ⎢──────⎥ ⎣ 2 ⎦ """ return Matrix([-I*sin(chi)*sin(psi) + cos(chi)*cos(psi), I*sin(chi)*cos(psi) + sin(psi)*cos(chi)]) def stokes_vector(psi, chi, p=1, I=1): u"""A Stokes vector corresponding to a polarization ellipse with `psi` tilt, and `chi` circularity. Parameters ---------- ``psi`` : numeric type or sympy Symbol The tilt of the polarization relative to the `x` axis. ``chi`` : numeric type or sympy Symbol The angle adjacent to the mayor axis of the polarization ellipse. ``p`` : numeric type or sympy Symbol The degree of polarization. ``I`` : numeric type or sympy Symbol The intensity of the field. Returns ------- Matrix A Stokes vector. Examples -------- The axes on the Poincaré sphere. >>> from sympy import pprint, symbols, pi >>> from sympy.physics.optics.polarization import stokes_vector >>> psi, chi, p, I = symbols("psi, chi, p, I", real=True) >>> pprint(stokes_vector(psi, chi, p, I), use_unicode=True) ⎡ I ⎤ ⎢ ⎥ ⎢I⋅p⋅cos(2⋅χ)⋅cos(2⋅ψ)⎥ ⎢ ⎥ ⎢I⋅p⋅sin(2⋅ψ)⋅cos(2⋅χ)⎥ ⎢ ⎥ ⎣ I⋅p⋅sin(2⋅χ) ⎦ Horizontal polarization >>> pprint(stokes_vector(0, 0), use_unicode=True) ⎡1⎤ ⎢ ⎥ ⎢1⎥ ⎢ ⎥ ⎢0⎥ ⎢ ⎥ ⎣0⎦ Vertical polarization >>> pprint(stokes_vector(pi/2, 0), use_unicode=True) ⎡1 ⎤ ⎢ ⎥ ⎢-1⎥ ⎢ ⎥ ⎢0 ⎥ ⎢ ⎥ ⎣0 ⎦ Diagonal polarization >>> pprint(stokes_vector(pi/4, 0), use_unicode=True) ⎡1⎤ ⎢ ⎥ ⎢0⎥ ⎢ ⎥ ⎢1⎥ ⎢ ⎥ ⎣0⎦ Anti-diagonal polarization >>> pprint(stokes_vector(-pi/4, 0), use_unicode=True) ⎡1 ⎤ ⎢ ⎥ ⎢0 ⎥ ⎢ ⎥ ⎢-1⎥ ⎢ ⎥ ⎣0 ⎦ Right-hand circular polarization >>> pprint(stokes_vector(0, pi/4), use_unicode=True) ⎡1⎤ ⎢ ⎥ ⎢0⎥ ⎢ ⎥ ⎢0⎥ ⎢ ⎥ ⎣1⎦ Left-hand circular polarization >>> pprint(stokes_vector(0, -pi/4), use_unicode=True) ⎡1 ⎤ ⎢ ⎥ ⎢0 ⎥ ⎢ ⎥ ⎢0 ⎥ ⎢ ⎥ ⎣-1⎦ Unpolarized light >>> pprint(stokes_vector(0, 0, 0), use_unicode=True) ⎡1⎤ ⎢ ⎥ ⎢0⎥ ⎢ ⎥ ⎢0⎥ ⎢ ⎥ ⎣0⎦ """ S0 = I S1 = I*p*cos(2*psi)*cos(2*chi) S2 = I*p*sin(2*psi)*cos(2*chi) S3 = I*p*sin(2*chi) return Matrix([S0, S1, S2, S3]) def jones_2_stokes(e): """Return the Stokes vector for a Jones vector `e`. Parameters ---------- ``e`` : sympy Matrix A Jones vector. Returns ------- sympy Matrix A Jones vector. Examples -------- The axes on the Poincaré sphere. >>> from sympy import pprint, pi >>> from sympy.physics.optics.polarization import jones_vector >>> from sympy.physics.optics.polarization import jones_2_stokes >>> H = jones_vector(0, 0) >>> V = jones_vector(pi/2, 0) >>> D = jones_vector(pi/4, 0) >>> A = jones_vector(-pi/4, 0) >>> R = jones_vector(0, pi/4) >>> L = jones_vector(0, -pi/4) >>> pprint([jones_2_stokes(e) for e in [H, V, D, A, R, L]], ... use_unicode=True) ⎡⎡1⎤ ⎡1 ⎤ ⎡1⎤ ⎡1 ⎤ ⎡1⎤ ⎡1 ⎤⎤ ⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎥ ⎢⎢1⎥ ⎢-1⎥ ⎢0⎥ ⎢0 ⎥ ⎢0⎥ ⎢0 ⎥⎥ ⎢⎢ ⎥, ⎢ ⎥, ⎢ ⎥, ⎢ ⎥, ⎢ ⎥, ⎢ ⎥⎥ ⎢⎢0⎥ ⎢0 ⎥ ⎢1⎥ ⎢-1⎥ ⎢0⎥ ⎢0 ⎥⎥ ⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎥ ⎣⎣0⎦ ⎣0 ⎦ ⎣0⎦ ⎣0 ⎦ ⎣1⎦ ⎣-1⎦⎦ """ ex, ey = e return Matrix([Abs(ex)**2 + Abs(ey)**2, Abs(ex)**2 - Abs(ey)**2, 2*re(ex*ey.conjugate()), -2*im(ex*ey.conjugate())]) def linear_polarizer(theta=0): u"""A linear polarizer Jones matrix with transmission axis at an angle `theta`. Parameters ---------- ``theta`` : numeric type or sympy Symbol The angle of the transmission axis relative to the horizontal plane. Returns ------- sympy Matrix A Jones matrix representing the polarizer. Examples -------- A generic polarizer. >>> from sympy import pprint, symbols >>> from sympy.physics.optics.polarization import linear_polarizer >>> theta = symbols("theta", real=True) >>> J = linear_polarizer(theta) >>> pprint(J, use_unicode=True) ⎡ 2 ⎤ ⎢ cos (θ) sin(θ)⋅cos(θ)⎥ ⎢ ⎥ ⎢ 2 ⎥ ⎣sin(θ)⋅cos(θ) sin (θ) ⎦ """ M = Matrix([[cos(theta)**2, sin(theta)*cos(theta)], [sin(theta)*cos(theta), sin(theta)**2]]) return M def phase_retarder(theta=0, delta=0): u"""A phase retarder Jones matrix with retardance `delta` at angle `theta`. Parameters ---------- ``theta`` : numeric type or sympy Symbol The angle of the fast axis relative to the horizontal plane. ``delta`` : numeric type or sympy Symbol The phase difference between the fast and slow axes of the transmitted light. Returns ------- sympy Matrix A Jones matrix representing the retarder. Examples -------- A generic retarder. >>> from sympy import pprint, symbols >>> from sympy.physics.optics.polarization import phase_retarder >>> theta, delta = symbols("theta, delta", real=True) >>> R = phase_retarder(theta, delta) >>> pprint(R, use_unicode=True) ⎡ -ⅈ⋅δ -ⅈ⋅δ ⎤ ⎢ ───── ───── ⎥ ⎢⎛ ⅈ⋅δ 2 2 ⎞ 2 ⎛ ⅈ⋅δ⎞ 2 ⎥ ⎢⎝ℯ ⋅sin (θ) + cos (θ)⎠⋅ℯ ⎝1 - ℯ ⎠⋅ℯ ⋅sin(θ)⋅cos(θ)⎥ ⎢ ⎥ ⎢ -ⅈ⋅δ -ⅈ⋅δ ⎥ ⎢ ───── ─────⎥ ⎢⎛ ⅈ⋅δ⎞ 2 ⎛ ⅈ⋅δ 2 2 ⎞ 2 ⎥ ⎣⎝1 - ℯ ⎠⋅ℯ ⋅sin(θ)⋅cos(θ) ⎝ℯ ⋅cos (θ) + sin (θ)⎠⋅ℯ ⎦ """ R = Matrix([[cos(theta)**2 + exp(I*delta)*sin(theta)**2, (1-exp(I*delta))*cos(theta)*sin(theta)], [(1-exp(I*delta))*cos(theta)*sin(theta), sin(theta)**2 + exp(I*delta)*cos(theta)**2]]) return R*exp(-I*delta/2) def half_wave_retarder(theta): u"""A half-wave retarder Jones matrix at angle `theta`. Parameters ---------- ``theta`` : numeric type or sympy Symbol The angle of the fast axis relative to the horizontal plane. Returns ------- sympy Matrix A Jones matrix representing the retarder. Examples -------- A generic half-wave plate. >>> from sympy import pprint, symbols >>> from sympy.physics.optics.polarization import half_wave_retarder >>> theta= symbols("theta", real=True) >>> HWP = half_wave_retarder(theta) >>> pprint(HWP, use_unicode=True) ⎡ ⎛ 2 2 ⎞ ⎤ ⎢-ⅈ⋅⎝- sin (θ) + cos (θ)⎠ -2⋅ⅈ⋅sin(θ)⋅cos(θ) ⎥ ⎢ ⎥ ⎢ ⎛ 2 2 ⎞⎥ ⎣ -2⋅ⅈ⋅sin(θ)⋅cos(θ) -ⅈ⋅⎝sin (θ) - cos (θ)⎠⎦ """ return phase_retarder(theta, pi) def quarter_wave_retarder(theta): u"""A quarter-wave retarder Jones matrix at angle `theta`. Parameters ---------- ``theta`` : numeric type or sympy Symbol The angle of the fast axis relative to the horizontal plane. Returns ------- sympy Matrix A Jones matrix representing the retarder. Examples -------- A generic quarter-wave plate. >>> from sympy import pprint, symbols >>> from sympy.physics.optics.polarization import quarter_wave_retarder >>> theta= symbols("theta", real=True) >>> QWP = quarter_wave_retarder(theta) >>> pprint(QWP, use_unicode=True) ⎡ -ⅈ⋅π -ⅈ⋅π ⎤ ⎢ ───── ───── ⎥ ⎢⎛ 2 2 ⎞ 4 4 ⎥ ⎢⎝ⅈ⋅sin (θ) + cos (θ)⎠⋅ℯ (1 - ⅈ)⋅ℯ ⋅sin(θ)⋅cos(θ)⎥ ⎢ ⎥ ⎢ -ⅈ⋅π -ⅈ⋅π ⎥ ⎢ ───── ─────⎥ ⎢ 4 ⎛ 2 2 ⎞ 4 ⎥ ⎣(1 - ⅈ)⋅ℯ ⋅sin(θ)⋅cos(θ) ⎝sin (θ) + ⅈ⋅cos (θ)⎠⋅ℯ ⎦ """ return phase_retarder(theta, pi/2) def transmissive_filter(T): u"""An attenuator Jones matrix with transmittance `T`. Parameters ---------- ``T`` : numeric type or sympy Symbol The transmittance of the attenuator. Returns ------- sympy Matrix A Jones matrix representing the filter. Examples -------- A generic filter. >>> from sympy import pprint, symbols >>> from sympy.physics.optics.polarization import transmissive_filter >>> T = symbols("T", real=True) >>> NDF = transmissive_filter(T) >>> pprint(NDF, use_unicode=True) ⎡√T 0 ⎤ ⎢ ⎥ ⎣0 √T⎦ """ return Matrix([[sqrt(T), 0], [0, sqrt(T)]]) def reflective_filter(R): u"""A reflective filter Jones matrix with reflectance `R`. Parameters ---------- ``R`` : numeric type or sympy Symbol The reflectance of the filter. Returns ------- sympy Matrix A Jones matrix representing the filter. Examples -------- A generic filter. >>> from sympy import pprint, symbols >>> from sympy.physics.optics.polarization import reflective_filter >>> R = symbols("R", real=True) >>> pprint(reflective_filter(R), use_unicode=True) ⎡√R 0 ⎤ ⎢ ⎥ ⎣0 -√R⎦ """ return Matrix([[sqrt(R), 0], [0, -sqrt(R)]]) def mueller_matrix(J): u"""The Mueller matrix corresponding to Jones matrix `J`. Parameters ---------- ``J`` : sympy Matrix A Jones matrix. Returns ------- sympy Matrix The corresponding Mueller matrix. Examples -------- Generic optical components. >>> from sympy import pprint, symbols >>> from sympy.physics.optics.polarization import (mueller_matrix, ... linear_polarizer, half_wave_retarder, quarter_wave_retarder) >>> theta = symbols("theta", real=True) A linear_polarizer >>> pprint(mueller_matrix(linear_polarizer(theta)), use_unicode=True) ⎡ cos(2⋅θ) sin(2⋅θ) ⎤ ⎢ 1/2 ──────── ──────── 0⎥ ⎢ 2 2 ⎥ ⎢ ⎥ ⎢cos(2⋅θ) cos(4⋅θ) 1 sin(4⋅θ) ⎥ ⎢──────── ──────── + ─ ──────── 0⎥ ⎢ 2 4 4 4 ⎥ ⎢ ⎥ ⎢sin(2⋅θ) sin(4⋅θ) 1 cos(4⋅θ) ⎥ ⎢──────── ──────── ─ - ──────── 0⎥ ⎢ 2 4 4 4 ⎥ ⎢ ⎥ ⎣ 0 0 0 0⎦ A half-wave plate >>> pprint(mueller_matrix(half_wave_retarder(theta)), use_unicode=True) ⎡1 0 0 0 ⎤ ⎢ ⎥ ⎢ 4 2 ⎥ ⎢0 8⋅sin (θ) - 8⋅sin (θ) + 1 sin(4⋅θ) 0 ⎥ ⎢ ⎥ ⎢ 4 2 ⎥ ⎢0 sin(4⋅θ) - 8⋅sin (θ) + 8⋅sin (θ) - 1 0 ⎥ ⎢ ⎥ ⎣0 0 0 -1⎦ A quarter-wave plate >>> pprint(mueller_matrix(quarter_wave_retarder(theta)), use_unicode=True) ⎡1 0 0 0 ⎤ ⎢ ⎥ ⎢ cos(4⋅θ) 1 sin(4⋅θ) ⎥ ⎢0 ──────── + ─ ──────── -sin(2⋅θ)⎥ ⎢ 2 2 2 ⎥ ⎢ ⎥ ⎢ sin(4⋅θ) 1 cos(4⋅θ) ⎥ ⎢0 ──────── ─ - ──────── cos(2⋅θ) ⎥ ⎢ 2 2 2 ⎥ ⎢ ⎥ ⎣0 sin(2⋅θ) -cos(2⋅θ) 0 ⎦ """ A = Matrix([[1, 0, 0, 1], [1, 0, 0, -1], [0, 1, 1, 0], [0, -I, I, 0]]) return simplify(A*TensorProduct(J, J.conjugate())*A.inv()) def polarizing_beam_splitter(Tp=1, Rs=1, Ts=0, Rp=0, phia=0, phib=0): r"""A polarizing beam splitter Jones matrix at angle `theta`. Parameters ---------- ``J`` : sympy Matrix A Jones matrix. ``Tp`` : numeric type or sympy Symbol The transmissivity of the P-polarized component. ``Rs`` : numeric type or sympy Symbol The reflectivity of the S-polarized component. ``Ts`` : numeric type or sympy Symbol The transmissivity of the S-polarized component. ``Rp`` : numeric type or sympy Symbol The reflectivity of the P-polarized component. ``phia`` : numeric type or sympy Symbol The phase difference between transmitted and reflected component for output mode a. ``phib`` : numeric type or sympy Symbol The phase difference between transmitted and reflected component for output mode b. Returns ------- sympy Matrix A 4x4 matrix representing the PBS. This matrix acts on a 4x1 vector whose first two entries are the Jones vector on one of the PBS ports, and the last two entries the Jones vector on the other port. Examples -------- Generic polarizing beam-splitter. >>> from sympy import pprint, symbols >>> from sympy.physics.optics.polarization import polarizing_beam_splitter >>> Ts, Rs, Tp, Rp = symbols(r"Ts, Rs, Tp, Rp", positive=True) >>> phia, phib = symbols("phi_a, phi_b", real=True) >>> PBS = polarizing_beam_splitter(Tp, Rs, Ts, Rp, phia, phib) >>> pprint(PBS, use_unicode=False) [ ____ ____ ] [ \/ Tp 0 I*\/ Rp 0 ] [ ] [ ____ ____ I*phi_a] [ 0 \/ Ts 0 -I*\/ Rs *e ] [ ] [ ____ ____ ] [I*\/ Rp 0 \/ Tp 0 ] [ ] [ ____ I*phi_b ____ ] [ 0 -I*\/ Rs *e 0 \/ Ts ] """ PBS = Matrix([[sqrt(Tp), 0, I*sqrt(Rp), 0], [0, sqrt(Ts), 0, -I*sqrt(Rs)*exp(I*phia)], [I*sqrt(Rp), 0, sqrt(Tp), 0], [0, -I*sqrt(Rs)*exp(I*phib), 0, sqrt(Ts)]]) return PBS
db6ab755fbc3f4c0a019527e9514607198e517b6e515619eb310d0fbbe053002
from sympy import symbols, Matrix, factor, Function, simplify, exp, pi, oo, I, \ Rational, sqrt, CRootOf from sympy.physics.control.lti import TransferFunction, Series, Parallel, Feedback from sympy.testing.pytest import raises a, x, b, s, g, d, p, k, a0, a1, a2, b0, b1, b2 = symbols('a, x, b, s, g, d, p, k, a0:3, b0:3') 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**pi*exp(s), 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(): # 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) 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(): zeta, wn = symbols('zeta, wn') 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_Series_functions(): zeta, wn = symbols('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) 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) 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_Parallel_construction(): zeta, wn = symbols('zeta, wn') 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_Parallel_functions(): zeta, wn = symbols('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) 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((-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2) + \ (a2*s + p)*(k*(s**2 + 2*s*wn*zeta + wn**2) + 1)*(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*p - s)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*s + p)*(k*(s**2 + 2*s*wn*zeta + wn**2) + 1), \ (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*p - s)*(s**2 + 2*s*wn*zeta + wn**2) + \ (a2*s + p)*(-k*(s**2 + 2*s*wn*zeta + wn**2) - 1), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s) assert -Parallel(tf1, tf2, tf3).doit() == \ TransferFunction(-((a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*s + p)*(k*(s**2 + 2*s*wn*zeta + wn**2) + 1)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s) assert Parallel(tf2, tf3, Series(tf2, -tf1), tf3).doit() == \ TransferFunction((a2*p - s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*s + p)*(-k*(a2*s + p) + \ (s**2 + 2*s*wn*zeta + wn**2)*(a2*p + k*(a2*s + p) - s)), (a2*s + p)**2*(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*p - s)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*s + p)*(k*(s**2 + 2*s*wn*zeta + wn**2) + 1), \ (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s) 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_Feedback_construction(): zeta, wn = symbols('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) 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)) assert f1.num == TransferFunction(1, 1, s) assert f1.den == Series(tf1, tf2, tf3) assert f1.var == s f2 = Feedback(tf1, tf2*tf3) assert f2.args == (tf1, Series(tf2, tf3)) assert f2.num == tf1 assert f2.den == Series(tf2, tf3) assert f2.var == s f3 = Feedback(tf1*tf2, tf5) assert f3.args == (Series(tf1, tf2), tf5) assert f3.num == Series(tf1, tf2) f4 = Feedback(tf4, tf6) assert f4.args == (tf4, tf6) assert f4.num == tf4 assert f4.var == p f5 = Feedback(tf5, TransferFunction(1, 1, s)) assert f5.args == (tf5, TransferFunction(1, 1, s)) assert f5.var == s f6 = Feedback(TransferFunction(1, 1, p), tf4) assert f6.args == (TransferFunction(1, 1, p), tf4) 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)) assert f7.num == 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)) def test_Feedback_functions(): zeta, wn = symbols('zeta, wn') 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(ValueError, 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(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, 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(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(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)
a69ba9ee065672f16fda2425a232f529e9b0eff37b242fb2fb466b1348858372
# -*- encoding: utf-8 -*- """ TODO: * Address Issue 2251, printing of spin states """ from typing import Dict, Any from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.cg import CG, Wigner3j, Wigner6j, Wigner9j from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.constants import hbar from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.gate import CGate, CNotGate, IdentityGate, UGate, XGate from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace, HilbertSpace, L2 from sympy.physics.quantum.innerproduct import InnerProduct from sympy.physics.quantum.operator import Operator, OuterProduct, DifferentialOperator from sympy.physics.quantum.qexpr import QExpr from sympy.physics.quantum.qubit import Qubit, IntQubit from sympy.physics.quantum.spin import Jz, J2, JzBra, JzBraCoupled, JzKet, JzKetCoupled, Rotation, WignerD from sympy.physics.quantum.state import Bra, Ket, TimeDepBra, TimeDepKet from sympy.physics.quantum.tensorproduct import TensorProduct from sympy.physics.quantum.sho1d import RaisingOp from sympy import Derivative, Function, Interval, Matrix, Pow, S, symbols, Symbol, oo from sympy.core.compatibility import exec_ from sympy.testing.pytest import XFAIL # Imports used in srepr strings from sympy.physics.quantum.spin import JzOp from sympy.printing import srepr from sympy.printing.pretty import pretty as xpretty from sympy.printing.latex import latex MutableDenseMatrix = Matrix ENV = {} # type: Dict[str, Any] exec_('from sympy import *', ENV) exec_('from sympy.physics.quantum import *', ENV) exec_('from sympy.physics.quantum.cg import *', ENV) exec_('from sympy.physics.quantum.spin import *', ENV) exec_('from sympy.physics.quantum.hilbert import *', ENV) exec_('from sympy.physics.quantum.qubit import *', ENV) exec_('from sympy.physics.quantum.qexpr import *', ENV) exec_('from sympy.physics.quantum.gate import *', ENV) exec_('from sympy.physics.quantum.constants import *', ENV) def sT(expr, string): """ sT := sreprTest from sympy/printing/tests/test_repr.py """ assert srepr(expr) == string assert eval(string, ENV) == expr def pretty(expr): """ASCII pretty-printing""" return xpretty(expr, use_unicode=False, wrap_line=False) def upretty(expr): """Unicode pretty-printing""" return xpretty(expr, use_unicode=True, wrap_line=False) def test_anticommutator(): A = Operator('A') B = Operator('B') ac = AntiCommutator(A, B) ac_tall = AntiCommutator(A**2, B) assert str(ac) == '{A,B}' assert pretty(ac) == '{A,B}' assert upretty(ac) == '{A,B}' assert latex(ac) == r'\left\{A,B\right\}' sT(ac, "AntiCommutator(Operator(Symbol('A')),Operator(Symbol('B')))") assert str(ac_tall) == '{A**2,B}' ascii_str = \ """\ / 2 \\\n\ <A ,B>\n\ \\ /\ """ ucode_str = \ """\ ⎧ 2 ⎫\n\ ⎨A ,B⎬\n\ ⎩ ⎭\ """ assert pretty(ac_tall) == ascii_str assert upretty(ac_tall) == ucode_str assert latex(ac_tall) == r'\left\{A^{2},B\right\}' sT(ac_tall, "AntiCommutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))") def test_cg(): cg = CG(1, 2, 3, 4, 5, 6) wigner3j = Wigner3j(1, 2, 3, 4, 5, 6) wigner6j = Wigner6j(1, 2, 3, 4, 5, 6) wigner9j = Wigner9j(1, 2, 3, 4, 5, 6, 7, 8, 9) assert str(cg) == 'CG(1, 2, 3, 4, 5, 6)' ascii_str = \ """\ 5,6 \n\ C \n\ 1,2,3,4\ """ ucode_str = \ """\ 5,6 \n\ C \n\ 1,2,3,4\ """ assert pretty(cg) == ascii_str assert upretty(cg) == ucode_str assert latex(cg) == r'C^{5,6}_{1,2,3,4}' sT(cg, "CG(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))") assert str(wigner3j) == 'Wigner3j(1, 2, 3, 4, 5, 6)' ascii_str = \ """\ /1 3 5\\\n\ | |\n\ \\2 4 6/\ """ ucode_str = \ """\ ⎛1 3 5⎞\n\ ⎜ ⎟\n\ ⎝2 4 6⎠\ """ assert pretty(wigner3j) == ascii_str assert upretty(wigner3j) == ucode_str assert latex(wigner3j) == \ r'\left(\begin{array}{ccc} 1 & 3 & 5 \\ 2 & 4 & 6 \end{array}\right)' sT(wigner3j, "Wigner3j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))") assert str(wigner6j) == 'Wigner6j(1, 2, 3, 4, 5, 6)' ascii_str = \ """\ /1 2 3\\\n\ < >\n\ \\4 5 6/\ """ ucode_str = \ """\ ⎧1 2 3⎫\n\ ⎨ ⎬\n\ ⎩4 5 6⎭\ """ assert pretty(wigner6j) == ascii_str assert upretty(wigner6j) == ucode_str assert latex(wigner6j) == \ r'\left\{\begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \end{array}\right\}' sT(wigner6j, "Wigner6j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))") assert str(wigner9j) == 'Wigner9j(1, 2, 3, 4, 5, 6, 7, 8, 9)' ascii_str = \ """\ /1 2 3\\\n\ | |\n\ <4 5 6>\n\ | |\n\ \\7 8 9/\ """ ucode_str = \ """\ ⎧1 2 3⎫\n\ ⎪ ⎪\n\ ⎨4 5 6⎬\n\ ⎪ ⎪\n\ ⎩7 8 9⎭\ """ assert pretty(wigner9j) == ascii_str assert upretty(wigner9j) == ucode_str assert latex(wigner9j) == \ r'\left\{\begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{array}\right\}' sT(wigner9j, "Wigner9j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6), Integer(7), Integer(8), Integer(9))") def test_commutator(): A = Operator('A') B = Operator('B') c = Commutator(A, B) c_tall = Commutator(A**2, B) assert str(c) == '[A,B]' assert pretty(c) == '[A,B]' assert upretty(c) == '[A,B]' assert latex(c) == r'\left[A,B\right]' sT(c, "Commutator(Operator(Symbol('A')),Operator(Symbol('B')))") assert str(c_tall) == '[A**2,B]' ascii_str = \ """\ [ 2 ]\n\ [A ,B]\ """ ucode_str = \ """\ ⎡ 2 ⎤\n\ ⎣A ,B⎦\ """ assert pretty(c_tall) == ascii_str assert upretty(c_tall) == ucode_str assert latex(c_tall) == r'\left[A^{2},B\right]' sT(c_tall, "Commutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))") def test_constants(): assert str(hbar) == 'hbar' assert pretty(hbar) == 'hbar' assert upretty(hbar) == 'ℏ' assert latex(hbar) == r'\hbar' sT(hbar, "HBar()") def test_dagger(): x = symbols('x') expr = Dagger(x) assert str(expr) == 'Dagger(x)' ascii_str = \ """\ +\n\ x \ """ ucode_str = \ """\ †\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str assert latex(expr) == r'x^{\dagger}' sT(expr, "Dagger(Symbol('x'))") @XFAIL def test_gate_failing(): a, b, c, d = symbols('a,b,c,d') uMat = Matrix([[a, b], [c, d]]) g = UGate((0,), uMat) assert str(g) == 'U(0)' def test_gate(): a, b, c, d = symbols('a,b,c,d') uMat = Matrix([[a, b], [c, d]]) q = Qubit(1, 0, 1, 0, 1) g1 = IdentityGate(2) g2 = CGate((3, 0), XGate(1)) g3 = CNotGate(1, 0) g4 = UGate((0,), uMat) assert str(g1) == '1(2)' assert pretty(g1) == '1 \n 2' assert upretty(g1) == '1 \n 2' assert latex(g1) == r'1_{2}' sT(g1, "IdentityGate(Integer(2))") assert str(g1*q) == '1(2)*|10101>' ascii_str = \ """\ 1 *|10101>\n\ 2 \ """ ucode_str = \ """\ 1 ⋅❘10101⟩\n\ 2 \ """ assert pretty(g1*q) == ascii_str assert upretty(g1*q) == ucode_str assert latex(g1*q) == r'1_{2} {\left|10101\right\rangle }' sT(g1*q, "Mul(IdentityGate(Integer(2)), Qubit(Integer(1),Integer(0),Integer(1),Integer(0),Integer(1)))") assert str(g2) == 'C((3,0),X(1))' ascii_str = \ """\ C /X \\\n\ 3,0\\ 1/\ """ ucode_str = \ """\ C ⎛X ⎞\n\ 3,0⎝ 1⎠\ """ assert pretty(g2) == ascii_str assert upretty(g2) == ucode_str assert latex(g2) == r'C_{3,0}{\left(X_{1}\right)}' sT(g2, "CGate(Tuple(Integer(3), Integer(0)),XGate(Integer(1)))") assert str(g3) == 'CNOT(1,0)' ascii_str = \ """\ CNOT \n\ 1,0\ """ ucode_str = \ """\ CNOT \n\ 1,0\ """ assert pretty(g3) == ascii_str assert upretty(g3) == ucode_str assert latex(g3) == r'CNOT_{1,0}' sT(g3, "CNotGate(Integer(1),Integer(0))") ascii_str = \ """\ U \n\ 0\ """ ucode_str = \ """\ U \n\ 0\ """ assert str(g4) == \ """\ U((0,),Matrix([\n\ [a, b],\n\ [c, d]]))\ """ assert pretty(g4) == ascii_str assert upretty(g4) == ucode_str assert latex(g4) == r'U_{0}' sT(g4, "UGate(Tuple(Integer(0)),MutableDenseMatrix([[Symbol('a'), Symbol('b')], [Symbol('c'), Symbol('d')]]))") def test_hilbert(): h1 = HilbertSpace() h2 = ComplexSpace(2) h3 = FockSpace() h4 = L2(Interval(0, oo)) assert str(h1) == 'H' assert pretty(h1) == 'H' assert upretty(h1) == 'H' assert latex(h1) == r'\mathcal{H}' sT(h1, "HilbertSpace()") assert str(h2) == 'C(2)' ascii_str = \ """\ 2\n\ C \ """ ucode_str = \ """\ 2\n\ C \ """ assert pretty(h2) == ascii_str assert upretty(h2) == ucode_str assert latex(h2) == r'\mathcal{C}^{2}' sT(h2, "ComplexSpace(Integer(2))") assert str(h3) == 'F' assert pretty(h3) == 'F' assert upretty(h3) == 'F' assert latex(h3) == r'\mathcal{F}' sT(h3, "FockSpace()") assert str(h4) == 'L2(Interval(0, oo))' ascii_str = \ """\ 2\n\ L \ """ ucode_str = \ """\ 2\n\ L \ """ assert pretty(h4) == ascii_str assert upretty(h4) == ucode_str assert latex(h4) == r'{\mathcal{L}^2}\left( \left[0, \infty\right) \right)' sT(h4, "L2(Interval(Integer(0), oo, false, true))") assert str(h1 + h2) == 'H+C(2)' ascii_str = \ """\ 2\n\ H + C \ """ ucode_str = \ """\ 2\n\ H ⊕ C \ """ assert pretty(h1 + h2) == ascii_str assert upretty(h1 + h2) == ucode_str assert latex(h1 + h2) sT(h1 + h2, "DirectSumHilbertSpace(HilbertSpace(),ComplexSpace(Integer(2)))") assert str(h1*h2) == "H*C(2)" ascii_str = \ """\ 2\n\ H x C \ """ ucode_str = \ """\ 2\n\ H ⨂ C \ """ assert pretty(h1*h2) == ascii_str assert upretty(h1*h2) == ucode_str assert latex(h1*h2) sT(h1*h2, "TensorProductHilbertSpace(HilbertSpace(),ComplexSpace(Integer(2)))") assert str(h1**2) == 'H**2' ascii_str = \ """\ x2\n\ H \ """ ucode_str = \ """\ ⨂2\n\ H \ """ assert pretty(h1**2) == ascii_str assert upretty(h1**2) == ucode_str assert latex(h1**2) == r'{\mathcal{H}}^{\otimes 2}' sT(h1**2, "TensorPowerHilbertSpace(HilbertSpace(),Integer(2))") def test_innerproduct(): x = symbols('x') ip1 = InnerProduct(Bra(), Ket()) ip2 = InnerProduct(TimeDepBra(), TimeDepKet()) ip3 = InnerProduct(JzBra(1, 1), JzKet(1, 1)) ip4 = InnerProduct(JzBraCoupled(1, 1, (1, 1)), JzKetCoupled(1, 1, (1, 1))) ip_tall1 = InnerProduct(Bra(x/2), Ket(x/2)) ip_tall2 = InnerProduct(Bra(x), Ket(x/2)) ip_tall3 = InnerProduct(Bra(x/2), Ket(x)) assert str(ip1) == '<psi|psi>' assert pretty(ip1) == '<psi|psi>' assert upretty(ip1) == '⟨ψ❘ψ⟩' assert latex( ip1) == r'\left\langle \psi \right. {\left|\psi\right\rangle }' sT(ip1, "InnerProduct(Bra(Symbol('psi')),Ket(Symbol('psi')))") assert str(ip2) == '<psi;t|psi;t>' assert pretty(ip2) == '<psi;t|psi;t>' assert upretty(ip2) == '⟨ψ;t❘ψ;t⟩' assert latex(ip2) == \ r'\left\langle \psi;t \right. {\left|\psi;t\right\rangle }' sT(ip2, "InnerProduct(TimeDepBra(Symbol('psi'),Symbol('t')),TimeDepKet(Symbol('psi'),Symbol('t')))") assert str(ip3) == "<1,1|1,1>" assert pretty(ip3) == '<1,1|1,1>' assert upretty(ip3) == '⟨1,1❘1,1⟩' assert latex(ip3) == r'\left\langle 1,1 \right. {\left|1,1\right\rangle }' sT(ip3, "InnerProduct(JzBra(Integer(1),Integer(1)),JzKet(Integer(1),Integer(1)))") assert str(ip4) == "<1,1,j1=1,j2=1|1,1,j1=1,j2=1>" assert pretty(ip4) == '<1,1,j1=1,j2=1|1,1,j1=1,j2=1>' assert upretty(ip4) == '⟨1,1,j₁=1,j₂=1❘1,1,j₁=1,j₂=1⟩' assert latex(ip4) == \ r'\left\langle 1,1,j_{1}=1,j_{2}=1 \right. {\left|1,1,j_{1}=1,j_{2}=1\right\rangle }' sT(ip4, "InnerProduct(JzBraCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))),JzKetCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))))") assert str(ip_tall1) == '<x/2|x/2>' ascii_str = \ """\ / | \\ \n\ / x|x \\\n\ \\ -|- /\n\ \\2|2/ \ """ ucode_str = \ """\ ╱ │ ╲ \n\ ╱ x│x ╲\n\ ╲ ─│─ ╱\n\ ╲2│2╱ \ """ assert pretty(ip_tall1) == ascii_str assert upretty(ip_tall1) == ucode_str assert latex(ip_tall1) == \ r'\left\langle \frac{x}{2} \right. {\left|\frac{x}{2}\right\rangle }' sT(ip_tall1, "InnerProduct(Bra(Mul(Rational(1, 2), Symbol('x'))),Ket(Mul(Rational(1, 2), Symbol('x'))))") assert str(ip_tall2) == '<x|x/2>' ascii_str = \ """\ / | \\ \n\ / |x \\\n\ \\ x|- /\n\ \\ |2/ \ """ ucode_str = \ """\ ╱ │ ╲ \n\ ╱ │x ╲\n\ ╲ x│─ ╱\n\ ╲ │2╱ \ """ assert pretty(ip_tall2) == ascii_str assert upretty(ip_tall2) == ucode_str assert latex(ip_tall2) == \ r'\left\langle x \right. {\left|\frac{x}{2}\right\rangle }' sT(ip_tall2, "InnerProduct(Bra(Symbol('x')),Ket(Mul(Rational(1, 2), Symbol('x'))))") assert str(ip_tall3) == '<x/2|x>' ascii_str = \ """\ / | \\ \n\ / x| \\\n\ \\ -|x /\n\ \\2| / \ """ ucode_str = \ """\ ╱ │ ╲ \n\ ╱ x│ ╲\n\ ╲ ─│x ╱\n\ ╲2│ ╱ \ """ assert pretty(ip_tall3) == ascii_str assert upretty(ip_tall3) == ucode_str assert latex(ip_tall3) == \ r'\left\langle \frac{x}{2} \right. {\left|x\right\rangle }' sT(ip_tall3, "InnerProduct(Bra(Mul(Rational(1, 2), Symbol('x'))),Ket(Symbol('x')))") def test_operator(): a = Operator('A') b = Operator('B', Symbol('t'), S.Half) inv = a.inv() f = Function('f') x = symbols('x') d = DifferentialOperator(Derivative(f(x), x), f(x)) op = OuterProduct(Ket(), Bra()) assert str(a) == 'A' assert pretty(a) == 'A' assert upretty(a) == 'A' assert latex(a) == 'A' sT(a, "Operator(Symbol('A'))") assert str(inv) == 'A**(-1)' ascii_str = \ """\ -1\n\ A \ """ ucode_str = \ """\ -1\n\ A \ """ assert pretty(inv) == ascii_str assert upretty(inv) == ucode_str assert latex(inv) == r'A^{-1}' sT(inv, "Pow(Operator(Symbol('A')), Integer(-1))") assert str(d) == 'DifferentialOperator(Derivative(f(x), x),f(x))' ascii_str = \ """\ /d \\\n\ DifferentialOperator|--(f(x)),f(x)|\n\ \\dx /\ """ ucode_str = \ """\ ⎛d ⎞\n\ DifferentialOperator⎜──(f(x)),f(x)⎟\n\ ⎝dx ⎠\ """ assert pretty(d) == ascii_str assert upretty(d) == ucode_str assert latex(d) == \ r'DifferentialOperator\left(\frac{d}{d x} f{\left(x \right)},f{\left(x \right)}\right)' sT(d, "DifferentialOperator(Derivative(Function('f')(Symbol('x')), Tuple(Symbol('x'), Integer(1))),Function('f')(Symbol('x')))") assert str(b) == 'Operator(B,t,1/2)' assert pretty(b) == 'Operator(B,t,1/2)' assert upretty(b) == 'Operator(B,t,1/2)' assert latex(b) == r'Operator\left(B,t,\frac{1}{2}\right)' sT(b, "Operator(Symbol('B'),Symbol('t'),Rational(1, 2))") assert str(op) == '|psi><psi|' assert pretty(op) == '|psi><psi|' assert upretty(op) == '❘ψ⟩⟨ψ❘' assert latex(op) == r'{\left|\psi\right\rangle }{\left\langle \psi\right|}' sT(op, "OuterProduct(Ket(Symbol('psi')),Bra(Symbol('psi')))") def test_qexpr(): q = QExpr('q') assert str(q) == 'q' assert pretty(q) == 'q' assert upretty(q) == 'q' assert latex(q) == r'q' sT(q, "QExpr(Symbol('q'))") def test_qubit(): q1 = Qubit('0101') q2 = IntQubit(8) assert str(q1) == '|0101>' assert pretty(q1) == '|0101>' assert upretty(q1) == '❘0101⟩' assert latex(q1) == r'{\left|0101\right\rangle }' sT(q1, "Qubit(Integer(0),Integer(1),Integer(0),Integer(1))") assert str(q2) == '|8>' assert pretty(q2) == '|8>' assert upretty(q2) == '❘8⟩' assert latex(q2) == r'{\left|8\right\rangle }' sT(q2, "IntQubit(8)") def test_spin(): lz = JzOp('L') ket = JzKet(1, 0) bra = JzBra(1, 0) cket = JzKetCoupled(1, 0, (1, 2)) cbra = JzBraCoupled(1, 0, (1, 2)) cket_big = JzKetCoupled(1, 0, (1, 2, 3)) cbra_big = JzBraCoupled(1, 0, (1, 2, 3)) rot = Rotation(1, 2, 3) bigd = WignerD(1, 2, 3, 4, 5, 6) smalld = WignerD(1, 2, 3, 0, 4, 0) assert str(lz) == 'Lz' ascii_str = \ """\ L \n\ z\ """ ucode_str = \ """\ L \n\ z\ """ assert pretty(lz) == ascii_str assert upretty(lz) == ucode_str assert latex(lz) == 'L_z' sT(lz, "JzOp(Symbol('L'))") assert str(J2) == 'J2' ascii_str = \ """\ 2\n\ J \ """ ucode_str = \ """\ 2\n\ J \ """ assert pretty(J2) == ascii_str assert upretty(J2) == ucode_str assert latex(J2) == r'J^2' sT(J2, "J2Op(Symbol('J'))") assert str(Jz) == 'Jz' ascii_str = \ """\ J \n\ z\ """ ucode_str = \ """\ J \n\ z\ """ assert pretty(Jz) == ascii_str assert upretty(Jz) == ucode_str assert latex(Jz) == 'J_z' sT(Jz, "JzOp(Symbol('J'))") assert str(ket) == '|1,0>' assert pretty(ket) == '|1,0>' assert upretty(ket) == '❘1,0⟩' assert latex(ket) == r'{\left|1,0\right\rangle }' sT(ket, "JzKet(Integer(1),Integer(0))") assert str(bra) == '<1,0|' assert pretty(bra) == '<1,0|' assert upretty(bra) == '⟨1,0❘' assert latex(bra) == r'{\left\langle 1,0\right|}' sT(bra, "JzBra(Integer(1),Integer(0))") assert str(cket) == '|1,0,j1=1,j2=2>' assert pretty(cket) == '|1,0,j1=1,j2=2>' assert upretty(cket) == '❘1,0,j₁=1,j₂=2⟩' assert latex(cket) == r'{\left|1,0,j_{1}=1,j_{2}=2\right\rangle }' sT(cket, "JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))") assert str(cbra) == '<1,0,j1=1,j2=2|' assert pretty(cbra) == '<1,0,j1=1,j2=2|' assert upretty(cbra) == '⟨1,0,j₁=1,j₂=2❘' assert latex(cbra) == r'{\left\langle 1,0,j_{1}=1,j_{2}=2\right|}' sT(cbra, "JzBraCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))") assert str(cket_big) == '|1,0,j1=1,j2=2,j3=3,j(1,2)=3>' # TODO: Fix non-unicode pretty printing # i.e. j1,2 -> j(1,2) assert pretty(cket_big) == '|1,0,j1=1,j2=2,j3=3,j1,2=3>' assert upretty(cket_big) == '❘1,0,j₁=1,j₂=2,j₃=3,j₁,₂=3⟩' assert latex(cket_big) == \ r'{\left|1,0,j_{1}=1,j_{2}=2,j_{3}=3,j_{1,2}=3\right\rangle }' sT(cket_big, "JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2), Integer(3)),Tuple(Tuple(Integer(1), Integer(2), Integer(3)), Tuple(Integer(1), Integer(3), Integer(1))))") assert str(cbra_big) == '<1,0,j1=1,j2=2,j3=3,j(1,2)=3|' assert pretty(cbra_big) == '<1,0,j1=1,j2=2,j3=3,j1,2=3|' assert upretty(cbra_big) == '⟨1,0,j₁=1,j₂=2,j₃=3,j₁,₂=3❘' assert latex(cbra_big) == \ r'{\left\langle 1,0,j_{1}=1,j_{2}=2,j_{3}=3,j_{1,2}=3\right|}' sT(cbra_big, "JzBraCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2), Integer(3)),Tuple(Tuple(Integer(1), Integer(2), Integer(3)), Tuple(Integer(1), Integer(3), Integer(1))))") assert str(rot) == 'R(1,2,3)' assert pretty(rot) == 'R (1,2,3)' assert upretty(rot) == 'ℛ (1,2,3)' assert latex(rot) == r'\mathcal{R}\left(1,2,3\right)' sT(rot, "Rotation(Integer(1),Integer(2),Integer(3))") assert str(bigd) == 'WignerD(1, 2, 3, 4, 5, 6)' ascii_str = \ """\ 1 \n\ D (4,5,6)\n\ 2,3 \ """ ucode_str = \ """\ 1 \n\ D (4,5,6)\n\ 2,3 \ """ assert pretty(bigd) == ascii_str assert upretty(bigd) == ucode_str assert latex(bigd) == r'D^{1}_{2,3}\left(4,5,6\right)' sT(bigd, "WignerD(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))") assert str(smalld) == 'WignerD(1, 2, 3, 0, 4, 0)' ascii_str = \ """\ 1 \n\ d (4)\n\ 2,3 \ """ ucode_str = \ """\ 1 \n\ d (4)\n\ 2,3 \ """ assert pretty(smalld) == ascii_str assert upretty(smalld) == ucode_str assert latex(smalld) == r'd^{1}_{2,3}\left(4\right)' sT(smalld, "WignerD(Integer(1), Integer(2), Integer(3), Integer(0), Integer(4), Integer(0))") def test_state(): x = symbols('x') bra = Bra() ket = Ket() bra_tall = Bra(x/2) ket_tall = Ket(x/2) tbra = TimeDepBra() tket = TimeDepKet() assert str(bra) == '<psi|' assert pretty(bra) == '<psi|' assert upretty(bra) == '⟨ψ❘' assert latex(bra) == r'{\left\langle \psi\right|}' sT(bra, "Bra(Symbol('psi'))") assert str(ket) == '|psi>' assert pretty(ket) == '|psi>' assert upretty(ket) == '❘ψ⟩' assert latex(ket) == r'{\left|\psi\right\rangle }' sT(ket, "Ket(Symbol('psi'))") assert str(bra_tall) == '<x/2|' ascii_str = \ """\ / |\n\ / x|\n\ \\ -|\n\ \\2|\ """ ucode_str = \ """\ ╱ │\n\ ╱ x│\n\ ╲ ─│\n\ ╲2│\ """ assert pretty(bra_tall) == ascii_str assert upretty(bra_tall) == ucode_str assert latex(bra_tall) == r'{\left\langle \frac{x}{2}\right|}' sT(bra_tall, "Bra(Mul(Rational(1, 2), Symbol('x')))") assert str(ket_tall) == '|x/2>' ascii_str = \ """\ | \\ \n\ |x \\\n\ |- /\n\ |2/ \ """ ucode_str = \ """\ │ ╲ \n\ │x ╲\n\ │─ ╱\n\ │2╱ \ """ assert pretty(ket_tall) == ascii_str assert upretty(ket_tall) == ucode_str assert latex(ket_tall) == r'{\left|\frac{x}{2}\right\rangle }' sT(ket_tall, "Ket(Mul(Rational(1, 2), Symbol('x')))") assert str(tbra) == '<psi;t|' assert pretty(tbra) == '<psi;t|' assert upretty(tbra) == '⟨ψ;t❘' assert latex(tbra) == r'{\left\langle \psi;t\right|}' sT(tbra, "TimeDepBra(Symbol('psi'),Symbol('t'))") assert str(tket) == '|psi;t>' assert pretty(tket) == '|psi;t>' assert upretty(tket) == '❘ψ;t⟩' assert latex(tket) == r'{\left|\psi;t\right\rangle }' sT(tket, "TimeDepKet(Symbol('psi'),Symbol('t'))") def test_tensorproduct(): tp = TensorProduct(JzKet(1, 1), JzKet(1, 0)) assert str(tp) == '|1,1>x|1,0>' assert pretty(tp) == '|1,1>x |1,0>' assert upretty(tp) == '❘1,1⟩⨂ ❘1,0⟩' assert latex(tp) == \ r'{{\left|1,1\right\rangle }}\otimes {{\left|1,0\right\rangle }}' sT(tp, "TensorProduct(JzKet(Integer(1),Integer(1)), JzKet(Integer(1),Integer(0)))") def test_big_expr(): f = Function('f') x = symbols('x') e1 = Dagger(AntiCommutator(Operator('A') + Operator('B'), Pow(DifferentialOperator(Derivative(f(x), x), f(x)), 3))*TensorProduct(Jz**2, Operator('A') + Operator('B')))*(JzBra(1, 0) + JzBra(1, 1))*(JzKet(0, 0) + JzKet(1, -1)) e2 = Commutator(Jz**2, Operator('A') + Operator('B'))*AntiCommutator(Dagger(Operator('C')*Operator('D')), Operator('E').inv()**2)*Dagger(Commutator(Jz, J2)) e3 = Wigner3j(1, 2, 3, 4, 5, 6)*TensorProduct(Commutator(Operator('A') + Dagger(Operator('B')), Operator('C') + Operator('D')), Jz - J2)*Dagger(OuterProduct(Dagger(JzBra(1, 1)), JzBra(1, 0)))*TensorProduct(JzKetCoupled(1, 1, (1, 1)) + JzKetCoupled(1, 0, (1, 1)), JzKetCoupled(1, -1, (1, 1))) e4 = (ComplexSpace(1)*ComplexSpace(2) + FockSpace()**2)*(L2(Interval( 0, oo)) + HilbertSpace()) assert str(e1) == '(Jz**2)x(Dagger(A) + Dagger(B))*{Dagger(DifferentialOperator(Derivative(f(x), x),f(x)))**3,Dagger(A) + Dagger(B)}*(<1,0| + <1,1|)*(|0,0> + |1,-1>)' ascii_str = \ """\ / 3 \\ \n\ |/ +\\ | \n\ 2 / + +\\ <| /d \\ | + +> \n\ /J \\ x \\A + B /*||DifferentialOperator|--(f(x)),f(x)| | ,A + B |*(<1,0| + <1,1|)*(|0,0> + |1,-1>)\n\ \\ z/ \\\\ \\dx / / / \ """ ucode_str = \ """\ ⎧ 3 ⎫ \n\ ⎪⎛ †⎞ ⎪ \n\ 2 ⎛ † †⎞ ⎨⎜ ⎛d ⎞ ⎟ † †⎬ \n\ ⎛J ⎞ ⨂ ⎝A + B ⎠⋅⎪⎜DifferentialOperator⎜──(f(x)),f(x)⎟ ⎟ ,A + B ⎪⋅(⟨1,0❘ + ⟨1,1❘)⋅(❘0,0⟩ + ❘1,-1⟩)\n\ ⎝ z⎠ ⎩⎝ ⎝dx ⎠ ⎠ ⎭ \ """ assert pretty(e1) == ascii_str assert upretty(e1) == ucode_str assert latex(e1) == \ r'{J_z^{2}}\otimes \left({A^{\dagger} + B^{\dagger}}\right) \left\{\left(DifferentialOperator\left(\frac{d}{d x} f{\left(x \right)},f{\left(x \right)}\right)^{\dagger}\right)^{3},A^{\dagger} + B^{\dagger}\right\} \left({\left\langle 1,0\right|} + {\left\langle 1,1\right|}\right) \left({\left|0,0\right\rangle } + {\left|1,-1\right\rangle }\right)' sT(e1, "Mul(TensorProduct(Pow(JzOp(Symbol('J')), Integer(2)), Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), AntiCommutator(Pow(Dagger(DifferentialOperator(Derivative(Function('f')(Symbol('x')), Tuple(Symbol('x'), Integer(1))),Function('f')(Symbol('x')))), Integer(3)),Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), Add(JzBra(Integer(1),Integer(0)), JzBra(Integer(1),Integer(1))), Add(JzKet(Integer(0),Integer(0)), JzKet(Integer(1),Integer(-1))))") assert str(e2) == '[Jz**2,A + B]*{E**(-2),Dagger(D)*Dagger(C)}*[J2,Jz]' ascii_str = \ """\ [ 2 ] / -2 + +\\ [ 2 ]\n\ [/J \\ ,A + B]*<E ,D *C >*[J ,J ]\n\ [\\ z/ ] \\ / [ z]\ """ ucode_str = \ """\ ⎡ 2 ⎤ ⎧ -2 † †⎫ ⎡ 2 ⎤\n\ ⎢⎛J ⎞ ,A + B⎥⋅⎨E ,D ⋅C ⎬⋅⎢J ,J ⎥\n\ ⎣⎝ z⎠ ⎦ ⎩ ⎭ ⎣ z⎦\ """ assert pretty(e2) == ascii_str assert upretty(e2) == ucode_str assert latex(e2) == \ r'\left[J_z^{2},A + B\right] \left\{E^{-2},D^{\dagger} C^{\dagger}\right\} \left[J^2,J_z\right]' sT(e2, "Mul(Commutator(Pow(JzOp(Symbol('J')), Integer(2)),Add(Operator(Symbol('A')), Operator(Symbol('B')))), AntiCommutator(Pow(Operator(Symbol('E')), Integer(-2)),Mul(Dagger(Operator(Symbol('D'))), Dagger(Operator(Symbol('C'))))), Commutator(J2Op(Symbol('J')),JzOp(Symbol('J'))))") assert str(e3) == \ "Wigner3j(1, 2, 3, 4, 5, 6)*[Dagger(B) + A,C + D]x(-J2 + Jz)*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x|1,-1,j1=1,j2=1>" ascii_str = \ """\ [ + ] / 2 \\ \n\ /1 3 5\\*[B + A,C + D]x |- J + J |*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x |1,-1,j1=1,j2=1>\n\ | | \\ z/ \n\ \\2 4 6/ \ """ ucode_str = \ """\ ⎡ † ⎤ ⎛ 2 ⎞ \n\ ⎛1 3 5⎞⋅⎣B + A,C + D⎦⨂ ⎜- J + J ⎟⋅❘1,0⟩⟨1,1❘⋅(❘1,0,j₁=1,j₂=1⟩ + ❘1,1,j₁=1,j₂=1⟩)⨂ ❘1,-1,j₁=1,j₂=1⟩\n\ ⎜ ⎟ ⎝ z⎠ \n\ ⎝2 4 6⎠ \ """ assert pretty(e3) == ascii_str assert upretty(e3) == ucode_str assert latex(e3) == \ r'\left(\begin{array}{ccc} 1 & 3 & 5 \\ 2 & 4 & 6 \end{array}\right) {\left[B^{\dagger} + A,C + D\right]}\otimes \left({- J^2 + J_z}\right) {\left|1,0\right\rangle }{\left\langle 1,1\right|} \left({{\left|1,0,j_{1}=1,j_{2}=1\right\rangle } + {\left|1,1,j_{1}=1,j_{2}=1\right\rangle }}\right)\otimes {{\left|1,-1,j_{1}=1,j_{2}=1\right\rangle }}' sT(e3, "Mul(Wigner3j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6)), TensorProduct(Commutator(Add(Dagger(Operator(Symbol('B'))), Operator(Symbol('A'))),Add(Operator(Symbol('C')), Operator(Symbol('D')))), Add(Mul(Integer(-1), J2Op(Symbol('J'))), JzOp(Symbol('J')))), OuterProduct(JzKet(Integer(1),Integer(0)),JzBra(Integer(1),Integer(1))), TensorProduct(Add(JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))), JzKetCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))), JzKetCoupled(Integer(1),Integer(-1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))))") assert str(e4) == '(C(1)*C(2)+F**2)*(L2(Interval(0, oo))+H)' ascii_str = \ """\ // 1 2\\ x2\\ / 2 \\\n\ \\\\C x C / + F / x \\L + H/\ """ ucode_str = \ """\ ⎛⎛ 1 2⎞ ⨂2⎞ ⎛ 2 ⎞\n\ ⎝⎝C ⨂ C ⎠ ⊕ F ⎠ ⨂ ⎝L ⊕ H⎠\ """ assert pretty(e4) == ascii_str assert upretty(e4) == ucode_str assert latex(e4) == \ r'\left(\left(\mathcal{C}^{1}\otimes \mathcal{C}^{2}\right)\oplus {\mathcal{F}}^{\otimes 2}\right)\otimes \left({\mathcal{L}^2}\left( \left[0, \infty\right) \right)\oplus \mathcal{H}\right)' sT(e4, "TensorProductHilbertSpace((DirectSumHilbertSpace(TensorProductHilbertSpace(ComplexSpace(Integer(1)),ComplexSpace(Integer(2))),TensorPowerHilbertSpace(FockSpace(),Integer(2)))),(DirectSumHilbertSpace(L2(Interval(Integer(0), oo, false, true)),HilbertSpace())))") def _test_sho1d(): ad = RaisingOp('a') assert pretty(ad) == ' \N{DAGGER}\na ' assert latex(ad) == 'a^{\\dagger}'
e7468bf18c9c3fbaa6345fd76250fab76947ce9538a517b85aca0b0bb2b68543
from sympy.physics.vector import dynamicsymbols, Point, ReferenceFrame from sympy.testing.pytest import raises def test_point_v1pt_theorys(): q, q2 = dynamicsymbols('q q2') qd, q2d = dynamicsymbols('q q2', 1) qdd, q2dd = dynamicsymbols('q q2', 2) N = ReferenceFrame('N') B = ReferenceFrame('B') B.set_ang_vel(N, qd * B.z) O = Point('O') P = O.locatenew('P', B.x) P.set_vel(B, 0) O.set_vel(N, 0) assert P.v1pt_theory(O, N, B) == qd * B.y O.set_vel(N, N.x) assert P.v1pt_theory(O, N, B) == N.x + qd * B.y P.set_vel(B, B.z) assert P.v1pt_theory(O, N, B) == B.z + N.x + qd * B.y def test_point_a1pt_theorys(): q, q2 = dynamicsymbols('q q2') qd, q2d = dynamicsymbols('q q2', 1) qdd, q2dd = dynamicsymbols('q q2', 2) N = ReferenceFrame('N') B = ReferenceFrame('B') B.set_ang_vel(N, qd * B.z) O = Point('O') P = O.locatenew('P', B.x) P.set_vel(B, 0) O.set_vel(N, 0) assert P.a1pt_theory(O, N, B) == -(qd**2) * B.x + qdd * B.y P.set_vel(B, q2d * B.z) assert P.a1pt_theory(O, N, B) == -(qd**2) * B.x + qdd * B.y + q2dd * B.z O.set_vel(N, q2d * B.x) assert P.a1pt_theory(O, N, B) == ((q2dd - qd**2) * B.x + (q2d * qd + qdd) * B.y + q2dd * B.z) def test_point_v2pt_theorys(): q = dynamicsymbols('q') qd = dynamicsymbols('q', 1) N = ReferenceFrame('N') B = N.orientnew('B', 'Axis', [q, N.z]) O = Point('O') P = O.locatenew('P', 0) O.set_vel(N, 0) assert P.v2pt_theory(O, N, B) == 0 P = O.locatenew('P', B.x) assert P.v2pt_theory(O, N, B) == (qd * B.z ^ B.x) O.set_vel(N, N.x) assert P.v2pt_theory(O, N, B) == N.x + qd * B.y def test_point_a2pt_theorys(): q = dynamicsymbols('q') qd = dynamicsymbols('q', 1) qdd = dynamicsymbols('q', 2) N = ReferenceFrame('N') B = N.orientnew('B', 'Axis', [q, N.z]) O = Point('O') P = O.locatenew('P', 0) O.set_vel(N, 0) assert P.a2pt_theory(O, N, B) == 0 P.set_pos(O, B.x) assert P.a2pt_theory(O, N, B) == (-qd**2) * B.x + (qdd) * B.y def test_point_funcs(): q, q2 = dynamicsymbols('q q2') qd, q2d = dynamicsymbols('q q2', 1) qdd, q2dd = dynamicsymbols('q q2', 2) N = ReferenceFrame('N') B = ReferenceFrame('B') B.set_ang_vel(N, 5 * B.y) O = Point('O') P = O.locatenew('P', q * B.x) assert P.pos_from(O) == q * B.x P.set_vel(B, qd * B.x + q2d * B.y) assert P.vel(B) == qd * B.x + q2d * B.y O.set_vel(N, 0) assert O.vel(N) == 0 assert P.a1pt_theory(O, N, B) == ((-25 * q + qdd) * B.x + (q2dd) * B.y + (-10 * qd) * B.z) B = N.orientnew('B', 'Axis', [q, N.z]) O = Point('O') P = O.locatenew('P', 10 * B.x) O.set_vel(N, 5 * N.x) assert O.vel(N) == 5 * N.x assert P.a2pt_theory(O, N, B) == (-10 * qd**2) * B.x + (10 * qdd) * B.y B.set_ang_vel(N, 5 * B.y) O = Point('O') P = O.locatenew('P', q * B.x) P.set_vel(B, qd * B.x + q2d * B.y) O.set_vel(N, 0) assert P.v1pt_theory(O, N, B) == qd * B.x + q2d * B.y - 5 * q * B.z def test_point_pos(): q = dynamicsymbols('q') N = ReferenceFrame('N') B = N.orientnew('B', 'Axis', [q, N.z]) O = Point('O') P = O.locatenew('P', 10 * N.x + 5 * B.x) assert P.pos_from(O) == 10 * N.x + 5 * B.x Q = P.locatenew('Q', 10 * N.y + 5 * B.y) assert Q.pos_from(P) == 10 * N.y + 5 * B.y assert Q.pos_from(O) == 10 * N.x + 10 * N.y + 5 * B.x + 5 * B.y assert O.pos_from(Q) == -10 * N.x - 10 * N.y - 5 * B.x - 5 * B.y def test_point_partial_velocity(): N = ReferenceFrame('N') A = ReferenceFrame('A') p = Point('p') u1, u2 = dynamicsymbols('u1, u2') p.set_vel(N, u1 * A.x + u2 * N.y) assert p.partial_velocity(N, u1) == A.x assert p.partial_velocity(N, u1, u2) == (A.x, N.y) raises(ValueError, lambda: p.partial_velocity(A, u1)) def test_point_vel(): #Basic functionality q1, q2 = dynamicsymbols('q1 q2') N = ReferenceFrame('N') B = ReferenceFrame('B') Q = Point('Q') O = Point('O') Q.set_pos(O, q1 * N.x) raises(ValueError , lambda: Q.vel(N)) # Velocity of O in N is not defined O.set_vel(N, q2 * N.y) assert O.vel(N) == q2 * N.y raises(ValueError , lambda : O.vel(B)) #Velocity of O is not defined in B def test_auto_point_vel(): t = dynamicsymbols._t q1, q2 = dynamicsymbols('q1 q2') N = ReferenceFrame('N') B = ReferenceFrame('B') O = Point('O') Q = Point('Q') Q.set_pos(O, q1 * N.x) O.set_vel(N, q2 * N.y) assert Q.vel(N) == q1.diff(t) * N.x + q2 * N.y # Velocity of Q using O P1 = Point('P1') P1.set_pos(O, q1 * B.x) P2 = Point('P2') P2.set_pos(P1, q2 * B.z) raises(ValueError, lambda : P2.vel(B)) # O's velocity is defined in different frame, and no #point in between has its velocity defined raises(ValueError, lambda: P2.vel(N)) # Velocity of O not defined in N def test_auto_point_vel_multiple_point_path(): t = dynamicsymbols._t q1, q2 = dynamicsymbols('q1 q2') B = ReferenceFrame('B') P = Point('P') P.set_vel(B, q1 * B.x) P1 = Point('P1') P1.set_pos(P, q2 * B.y) P1.set_vel(B, q1 * B.z) P2 = Point('P2') P2.set_pos(P1, q1 * B.z) P3 = Point('P3') P3.set_pos(P2, 10 * q1 * B.y) assert P3.vel(B) == 10 * q1.diff(t) * B.y + (q1 + q1.diff(t)) * B.z def test_auto_vel_dont_overwrite(): t = dynamicsymbols._t q1, q2, u1 = dynamicsymbols('q1, q2, u1') N = ReferenceFrame('N') P = Point('P1') P.set_vel(N, u1 * N.x) P1 = Point('P1') P1.set_pos(P, q2 * N.y) assert P1.vel(N) == q2.diff(t) * N.y + u1 * N.x assert P.vel(N) == u1 * N.x P1.set_vel(N, u1 * N.z) assert P1.vel(N) == u1 * N.z def test_auto_point_vel_if_tree_has_vel_but_inappropriate_pos_vector(): q1, q2 = dynamicsymbols('q1 q2') B = ReferenceFrame('B') S = ReferenceFrame('S') P = Point('P') P.set_vel(B, q1 * B.x) P1 = Point('P1') P1.set_pos(P, S.y) raises(ValueError, lambda : P1.vel(B)) # P1.pos_from(P) can't be expressed in B raises(ValueError, lambda : P1.vel(S)) # P.vel(S) not defined def test_auto_point_vel_shortest_path(): t = dynamicsymbols._t q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2') B = ReferenceFrame('B') P = Point('P') P.set_vel(B, u1 * B.x) P1 = Point('P1') P1.set_pos(P, q2 * B.y) P1.set_vel(B, q1 * B.z) P2 = Point('P2') P2.set_pos(P1, q1 * B.z) P3 = Point('P3') P3.set_pos(P2, 10 * q1 * B.y) P4 = Point('P4') P4.set_pos(P3, q1 * B.x) O = Point('O') O.set_vel(B, u2 * B.y) O1 = Point('O1') O1.set_pos(O, q2 * B.z) P4.set_pos(O1, q1 * B.x + q2 * B.z) assert P4.vel(B) == q1.diff(t) * B.x + u2 * B.y + 2 * q2.diff(t) * B.z def test_auto_point_vel_connected_frames(): t = dynamicsymbols._t q, q1, q2, u = dynamicsymbols('q q1 q2 u') N = ReferenceFrame('N') B = ReferenceFrame('B') O = Point('O') O.set_vel(N, u * N.x) P = Point('P') P.set_pos(O, q1 * N.x + q2 * B.y) raises(ValueError, lambda: P.vel(N)) N.orient(B, 'Axis', (q, B.x)) assert P.vel(N) == (u + q1.diff(t)) * N.x + q2.diff(t) * B.y - q2 * q.diff(t) * B.z
0786f15e2cd481148668c388c2dfbf98abb66a141c17afae0b6890e26b47cb20
# -*- coding: utf-8 -*- from sympy import symbols, sin, asin, cos, sqrt, Function from sympy.physics.vector import ReferenceFrame, dynamicsymbols, Dyadic from sympy.physics.vector.printing import (VectorLatexPrinter, vpprint, vsprint, vsstrrepr, vlatex) a, b, c = symbols('a, b, c') alpha, omega, beta = dynamicsymbols('alpha, omega, beta') A = ReferenceFrame('A') N = ReferenceFrame('N') v = a ** 2 * N.x + b * N.y + c * sin(alpha) * N.z w = alpha * N.x + sin(omega) * N.y + alpha * beta * N.z ww = alpha * N.x + asin(omega) * N.y - alpha.diff() * beta * N.z o = a/b * N.x + (c+b)/a * N.y + c**2/b * N.z y = a ** 2 * (N.x | N.y) + b * (N.y | N.y) + c * sin(alpha) * (N.z | N.y) x = alpha * (N.x | N.x) + sin(omega) * (N.y | N.z) + alpha * beta * (N.z | N.x) xx = N.x | (-N.y - N.z) xx2 = N.x | (N.y + N.z) def ascii_vpretty(expr): return vpprint(expr, use_unicode=False, wrap_line=False) def unicode_vpretty(expr): return vpprint(expr, use_unicode=True, wrap_line=False) def test_latex_printer(): r = Function('r')('t') assert VectorLatexPrinter().doprint(r ** 2) == "r^{2}" r2 = Function('r^2')('t') assert VectorLatexPrinter().doprint(r2.diff()) == r'\dot{r^{2}}' ra = Function('r__a')('t') assert VectorLatexPrinter().doprint(ra.diff().diff()) == r'\ddot{r^{a}}' def test_vector_pretty_print(): # TODO : The unit vectors should print with subscripts but they just # print as `n_x` instead of making `x` a subscript with unicode. # TODO : The pretty print division does not print correctly here: # w = alpha * N.x + sin(omega) * N.y + alpha / beta * N.z expected = """\ 2 a n_x + b n_y + c*sin(alpha) n_z\ """ uexpected = """\ 2 a n_x + b n_y + c⋅sin(α) n_z\ """ assert ascii_vpretty(v) == expected assert unicode_vpretty(v) == uexpected expected = 'alpha n_x + sin(omega) n_y + alpha*beta n_z' uexpected = 'α n_x + sin(ω) n_y + α⋅β n_z' assert ascii_vpretty(w) == expected assert unicode_vpretty(w) == uexpected expected = """\ 2 a b + c c - n_x + ----- n_y + -- n_z b a b\ """ uexpected = """\ 2 a b + c c ─ n_x + ───── n_y + ── n_z b a b\ """ assert ascii_vpretty(o) == expected assert unicode_vpretty(o) == uexpected def test_vector_latex(): a, b, c, d, omega = symbols('a, b, c, d, omega') v = (a ** 2 + b / c) * A.x + sqrt(d) * A.y + cos(omega) * A.z assert vlatex(v) == (r'(a^{2} + \frac{b}{c})\mathbf{\hat{a}_x} + ' r'\sqrt{d}\mathbf{\hat{a}_y} + ' r'\cos{\left(\omega \right)}' r'\mathbf{\hat{a}_z}') theta, omega, alpha, q = dynamicsymbols('theta, omega, alpha, q') v = theta * A.x + omega * omega * A.y + (q * alpha) * A.z assert vlatex(v) == (r'\theta\mathbf{\hat{a}_x} + ' r'\omega^{2}\mathbf{\hat{a}_y} + ' r'\alpha q\mathbf{\hat{a}_z}') phi1, phi2, phi3 = dynamicsymbols('phi1, phi2, phi3') theta1, theta2, theta3 = symbols('theta1, theta2, theta3') v = (sin(theta1) * A.x + cos(phi1) * cos(phi2) * A.y + cos(theta1 + phi3) * A.z) assert vlatex(v) == (r'\sin{\left(\theta_{1} \right)}' r'\mathbf{\hat{a}_x} + \cos{' r'\left(\phi_{1} \right)} \cos{' r'\left(\phi_{2} \right)}\mathbf{\hat{a}_y} + ' r'\cos{\left(\theta_{1} + ' r'\phi_{3} \right)}\mathbf{\hat{a}_z}') N = ReferenceFrame('N') a, b, c, d, omega = symbols('a, b, c, d, omega') v = (a ** 2 + b / c) * N.x + sqrt(d) * N.y + cos(omega) * N.z expected = (r'(a^{2} + \frac{b}{c})\mathbf{\hat{n}_x} + ' r'\sqrt{d}\mathbf{\hat{n}_y} + ' r'\cos{\left(\omega \right)}' r'\mathbf{\hat{n}_z}') assert vlatex(v) == expected # Try custom unit vectors. N = ReferenceFrame('N', latexs=(r'\hat{i}', r'\hat{j}', r'\hat{k}')) v = (a ** 2 + b / c) * N.x + sqrt(d) * N.y + cos(omega) * N.z expected = (r'(a^{2} + \frac{b}{c})\hat{i} + ' r'\sqrt{d}\hat{j} + ' r'\cos{\left(\omega \right)}\hat{k}') assert vlatex(v) == expected expected = r'\alpha\mathbf{\hat{n}_x} + \operatorname{asin}{\left(\omega ' \ r'\right)}\mathbf{\hat{n}_y} - \beta \dot{\alpha}\mathbf{\hat{n}_z}' assert vlatex(ww) == expected expected = r'- \mathbf{\hat{n}_x}\otimes \mathbf{\hat{n}_y} - ' \ r'\mathbf{\hat{n}_x}\otimes \mathbf{\hat{n}_z}' assert vlatex(xx) == expected expected = r'\mathbf{\hat{n}_x}\otimes \mathbf{\hat{n}_y} + ' \ r'\mathbf{\hat{n}_x}\otimes \mathbf{\hat{n}_z}' assert vlatex(xx2) == expected def test_vector_latex_arguments(): assert vlatex(N.x * 3.0, full_prec=False) == r'3.0\mathbf{\hat{n}_x}' assert vlatex(N.x * 3.0, full_prec=True) == r'3.00000000000000\mathbf{\hat{n}_x}' def test_vector_latex_with_functions(): N = ReferenceFrame('N') omega, alpha = dynamicsymbols('omega, alpha') v = omega.diff() * N.x assert vlatex(v) == r'\dot{\omega}\mathbf{\hat{n}_x}' v = omega.diff() ** alpha * N.x assert vlatex(v) == (r'\dot{\omega}^{\alpha}' r'\mathbf{\hat{n}_x}') def test_dyadic_pretty_print(): expected = """\ 2 a n_x|n_y + b n_y|n_y + c*sin(alpha) n_z|n_y\ """ uexpected = """\ 2 a n_x⊗n_y + b n_y⊗n_y + c⋅sin(α) n_z⊗n_y\ """ assert ascii_vpretty(y) == expected assert unicode_vpretty(y) == uexpected expected = 'alpha n_x|n_x + sin(omega) n_y|n_z + alpha*beta n_z|n_x' uexpected = 'α n_x⊗n_x + sin(ω) n_y⊗n_z + α⋅β n_z⊗n_x' assert ascii_vpretty(x) == expected assert unicode_vpretty(x) == uexpected assert ascii_vpretty(Dyadic([])) == '0' assert unicode_vpretty(Dyadic([])) == '0' assert ascii_vpretty(xx) == '- n_x|n_y - n_x|n_z' assert unicode_vpretty(xx) == '- n_x⊗n_y - n_x⊗n_z' assert ascii_vpretty(xx2) == 'n_x|n_y + n_x|n_z' assert unicode_vpretty(xx2) == 'n_x⊗n_y + n_x⊗n_z' def test_dyadic_latex(): expected = (r'a^{2}\mathbf{\hat{n}_x}\otimes \mathbf{\hat{n}_y} + ' r'b\mathbf{\hat{n}_y}\otimes \mathbf{\hat{n}_y} + ' r'c \sin{\left(\alpha \right)}' r'\mathbf{\hat{n}_z}\otimes \mathbf{\hat{n}_y}') assert vlatex(y) == expected expected = (r'\alpha\mathbf{\hat{n}_x}\otimes \mathbf{\hat{n}_x} + ' r'\sin{\left(\omega \right)}\mathbf{\hat{n}_y}' r'\otimes \mathbf{\hat{n}_z} + ' r'\alpha \beta\mathbf{\hat{n}_z}\otimes \mathbf{\hat{n}_x}') assert vlatex(x) == expected assert vlatex(Dyadic([])) == '0' def test_dyadic_str(): assert vsprint(Dyadic([])) == '0' assert vsprint(y) == 'a**2*(N.x|N.y) + b*(N.y|N.y) + c*sin(alpha)*(N.z|N.y)' assert vsprint(x) == 'alpha*(N.x|N.x) + sin(omega)*(N.y|N.z) + alpha*beta*(N.z|N.x)' assert vsprint(ww) == "alpha*N.x + asin(omega)*N.y - beta*alpha'*N.z" assert vsprint(xx) == '- (N.x|N.y) - (N.x|N.z)' assert vsprint(xx2) == '(N.x|N.y) + (N.x|N.z)' def test_vlatex(): # vlatex is broken #12078 from sympy.physics.vector import vlatex x = symbols('x') J = symbols('J') f = Function('f') g = Function('g') h = Function('h') expected = r'J \left(\frac{d}{d x} g{\left(x \right)} - \frac{d}{d x} h{\left(x \right)}\right)' expr = J*f(x).diff(x).subs(f(x), g(x)-h(x)) assert vlatex(expr) == expected def test_issue_13354(): """ Test for proper pretty printing of physics vectors with ADD instances in arguments. Test is exactly the one suggested in the original bug report by @moorepants. """ a, b, c = symbols('a, b, c') A = ReferenceFrame('A') v = a * A.x + b * A.y + c * A.z w = b * A.x + c * A.y + a * A.z z = w + v expected = """(a + b) a_x + (b + c) a_y + (a + c) a_z""" assert ascii_vpretty(z) == expected def test_vector_derivative_printing(): # First order v = omega.diff() * N.x assert unicode_vpretty(v) == 'ω̇ n_x' assert ascii_vpretty(v) == "omega'(t) n_x" # Second order v = omega.diff().diff() * N.x assert vlatex(v) == r'\ddot{\omega}\mathbf{\hat{n}_x}' assert unicode_vpretty(v) == 'ω̈ n_x' assert ascii_vpretty(v) == "omega''(t) n_x" # Third order v = omega.diff().diff().diff() * N.x assert vlatex(v) == r'\dddot{\omega}\mathbf{\hat{n}_x}' assert unicode_vpretty(v) == 'ω⃛ n_x' assert ascii_vpretty(v) == "omega'''(t) n_x" # Fourth order v = omega.diff().diff().diff().diff() * N.x assert vlatex(v) == r'\ddddot{\omega}\mathbf{\hat{n}_x}' assert unicode_vpretty(v) == 'ω⃜ n_x' assert ascii_vpretty(v) == "omega''''(t) n_x" # Fifth order v = omega.diff().diff().diff().diff().diff() * N.x assert vlatex(v) == r'\frac{d^{5}}{d t^{5}} \omega\mathbf{\hat{n}_x}' assert unicode_vpretty(v) == ' 5\n d\n───(ω) n_x\n 5\ndt' assert ascii_vpretty(v) == ' 5\n d\n---(omega) n_x\n 5\ndt' def test_vector_str_printing(): assert vsprint(w) == 'alpha*N.x + sin(omega)*N.y + alpha*beta*N.z' assert vsprint(omega.diff() * N.x) == "omega'*N.x" assert vsstrrepr(w) == 'alpha*N.x + sin(omega)*N.y + alpha*beta*N.z' def test_vector_str_arguments(): assert vsprint(N.x * 3.0, full_prec=False) == '3.0*N.x' assert vsprint(N.x * 3.0, full_prec=True) == '3.00000000000000*N.x' def test_issue_14041(): import sympy.physics.mechanics as me A_frame = me.ReferenceFrame('A') thetad, phid = me.dynamicsymbols('theta, phi', 1) L = symbols('L') assert vlatex(L*(phid + thetad)**2*A_frame.x) == \ r"L \left(\dot{\phi} + \dot{\theta}\right)^{2}\mathbf{\hat{a}_x}" assert vlatex((phid + thetad)**2*A_frame.x) == \ r"\left(\dot{\phi} + \dot{\theta}\right)^{2}\mathbf{\hat{a}_x}" assert vlatex((phid*thetad)**a*A_frame.x) == \ r"\left(\dot{\phi} \dot{\theta}\right)^{a}\mathbf{\hat{a}_x}"
af26d18110e6ec6c6188e2b87ddd3909831e32129cbdc0c48fac99b20979c0b0
from sympy import Derivative, Integer, Expr from sympy.matrices.common import MatrixCommon from .ndim_array import NDimArray from .arrayop import derive_by_array from sympy import MatrixExpr from sympy import ZeroMatrix from sympy.matrices.expressions.matexpr import _matrix_derivative class ArrayDerivative(Derivative): is_scalar = False def __new__(cls, expr, *variables, **kwargs): obj = super(ArrayDerivative, cls).__new__(cls, expr, *variables, **kwargs) if isinstance(obj, ArrayDerivative): obj._shape = obj._get_shape() return obj def _get_shape(self): shape = () for v, count in self.variable_count: if hasattr(v, "shape"): for i in range(count): shape += v.shape if hasattr(self.expr, "shape"): shape += self.expr.shape return shape @property def shape(self): return self._shape @classmethod def _get_zero_with_shape_like(cls, expr): if isinstance(expr, (MatrixCommon, NDimArray)): return expr.zeros(*expr.shape) elif isinstance(expr, MatrixExpr): return ZeroMatrix(*expr.shape) else: raise RuntimeError("Unable to determine shape of array-derivative.") @staticmethod def _call_derive_scalar_by_matrix(expr, v): # type: (Expr, MatrixCommon) -> Expr return v.applyfunc(lambda x: expr.diff(x)) @staticmethod def _call_derive_scalar_by_matexpr(expr, v): # type: (Expr, MatrixExpr) -> Expr if expr.has(v): return _matrix_derivative(expr, v) else: return ZeroMatrix(*v.shape) @staticmethod def _call_derive_scalar_by_array(expr, v): # type: (Expr, NDimArray) -> Expr return v.applyfunc(lambda x: expr.diff(x)) @staticmethod def _call_derive_matrix_by_scalar(expr, v): # type: (MatrixCommon, Expr) -> Expr return _matrix_derivative(expr, v) @staticmethod def _call_derive_matexpr_by_scalar(expr, v): # type: (MatrixExpr, Expr) -> Expr return expr._eval_derivative(v) @staticmethod def _call_derive_array_by_scalar(expr, v): # type: (NDimArray, Expr) -> Expr return expr.applyfunc(lambda x: x.diff(v)) @staticmethod def _call_derive_default(expr, v): # type: (Expr, Expr) -> Expr if expr.has(v): return _matrix_derivative(expr, v) else: return None @classmethod def _dispatch_eval_derivative_n_times(cls, expr, v, count): # Evaluate the derivative `n` times. If # `_eval_derivative_n_times` is not overridden by the current # object, the default in `Basic` will call a loop over # `_eval_derivative`: if not isinstance(count, (int, Integer)) or ((count <= 0) == True): return None # TODO: this could be done with multiple-dispatching: if expr.is_scalar: if isinstance(v, MatrixCommon): result = cls._call_derive_scalar_by_matrix(expr, v) elif isinstance(v, MatrixExpr): result = cls._call_derive_scalar_by_matexpr(expr, v) elif isinstance(v, NDimArray): result = cls._call_derive_scalar_by_array(expr, v) elif v.is_scalar: # scalar by scalar has a special return super(ArrayDerivative, cls)._dispatch_eval_derivative_n_times(expr, v, count) else: return None elif v.is_scalar: if isinstance(expr, MatrixCommon): result = cls._call_derive_matrix_by_scalar(expr, v) elif isinstance(expr, MatrixExpr): result = cls._call_derive_matexpr_by_scalar(expr, v) elif isinstance(expr, NDimArray): result = cls._call_derive_array_by_scalar(expr, v) else: return None else: # Both `expr` and `v` are some array/matrix type: if isinstance(expr, MatrixCommon) or isinstance(expr, MatrixCommon): result = derive_by_array(expr, v) elif isinstance(expr, MatrixExpr) and isinstance(v, MatrixExpr): result = cls._call_derive_default(expr, v) elif isinstance(expr, MatrixExpr) or isinstance(v, MatrixExpr): # if one expression is a symbolic matrix expression while the other isn't, don't evaluate: return None else: result = derive_by_array(expr, v) if result is None: return None if count == 1: return result else: return cls._dispatch_eval_derivative_n_times(result, v, count - 1)
96de920d389b95d1ea833d5c37c95d6ce66d4ed50e1c3c09b14f94e1768f8457
import itertools from sympy import S, Tuple, diff, Basic from sympy.core.compatibility import Iterable from sympy.tensor.array.ndim_array import NDimArray from sympy.tensor.array.dense_ndim_array import DenseNDimArray, ImmutableDenseNDimArray from sympy.tensor.array.sparse_ndim_array import SparseNDimArray def _arrayfy(a): from sympy.matrices import MatrixBase if isinstance(a, NDimArray): return a if isinstance(a, (MatrixBase, list, tuple, Tuple)): return ImmutableDenseNDimArray(a) return a def tensorproduct(*args): """ Tensor product among scalars or array-like objects. Examples ======== >>> from sympy.tensor.array import tensorproduct, Array >>> from sympy.abc import x, y, z, t >>> A = Array([[1, 2], [3, 4]]) >>> B = Array([x, y]) >>> tensorproduct(A, B) [[[x, y], [2*x, 2*y]], [[3*x, 3*y], [4*x, 4*y]]] >>> tensorproduct(A, x) [[x, 2*x], [3*x, 4*x]] >>> tensorproduct(A, B, B) [[[[x**2, x*y], [x*y, y**2]], [[2*x**2, 2*x*y], [2*x*y, 2*y**2]]], [[[3*x**2, 3*x*y], [3*x*y, 3*y**2]], [[4*x**2, 4*x*y], [4*x*y, 4*y**2]]]] Applying this function on two matrices will result in a rank 4 array. >>> from sympy import Matrix, eye >>> m = Matrix([[x, y], [z, t]]) >>> p = tensorproduct(eye(3), m) >>> p [[[[x, y], [z, t]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[x, y], [z, t]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[x, y], [z, t]]]] """ from sympy.tensor.array import SparseNDimArray, ImmutableSparseNDimArray if len(args) == 0: return S.One if len(args) == 1: return _arrayfy(args[0]) if len(args) > 2: return tensorproduct(tensorproduct(args[0], args[1]), *args[2:]) # length of args is 2: a, b = map(_arrayfy, args) if not isinstance(a, NDimArray) or not isinstance(b, NDimArray): return a*b if isinstance(a, SparseNDimArray) and isinstance(b, SparseNDimArray): lp = len(b) new_array = {k1*lp + k2: v1*v2 for k1, v1 in a._sparse_array.items() for k2, v2 in b._sparse_array.items()} return ImmutableSparseNDimArray(new_array, a.shape + b.shape) product_list = [i*j for i in Flatten(a) for j in Flatten(b)] return ImmutableDenseNDimArray(product_list, a.shape + b.shape) def tensorcontraction(array, *contraction_axes): """ Contraction of an array-like object on the specified axes. Examples ======== >>> from sympy import Array, tensorcontraction >>> from sympy import Matrix, eye >>> tensorcontraction(eye(3), (0, 1)) 3 >>> A = Array(range(18), (3, 2, 3)) >>> A [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]] >>> tensorcontraction(A, (0, 2)) [21, 30] Matrix multiplication may be emulated with a proper combination of ``tensorcontraction`` and ``tensorproduct`` >>> from sympy import tensorproduct >>> from sympy.abc import a,b,c,d,e,f,g,h >>> m1 = Matrix([[a, b], [c, d]]) >>> m2 = Matrix([[e, f], [g, h]]) >>> p = tensorproduct(m1, m2) >>> p [[[[a*e, a*f], [a*g, a*h]], [[b*e, b*f], [b*g, b*h]]], [[[c*e, c*f], [c*g, c*h]], [[d*e, d*f], [d*g, d*h]]]] >>> tensorcontraction(p, (1, 2)) [[a*e + b*g, a*f + b*h], [c*e + d*g, c*f + d*h]] >>> m1*m2 Matrix([ [a*e + b*g, a*f + b*h], [c*e + d*g, c*f + d*h]]) """ array = _arrayfy(array) # Verify contraction_axes: taken_dims = set([]) for axes_group in contraction_axes: if not isinstance(axes_group, Iterable): raise ValueError("collections of contraction axes expected") dim = array.shape[axes_group[0]] for d in axes_group: if d in taken_dims: raise ValueError("dimension specified more than once") if dim != array.shape[d]: raise ValueError("cannot contract between axes of different dimension") taken_dims.add(d) rank = array.rank() remaining_shape = [dim for i, dim in enumerate(array.shape) if i not in taken_dims] cum_shape = [0]*rank _cumul = 1 for i in range(rank): cum_shape[rank - i - 1] = _cumul _cumul *= int(array.shape[rank - i - 1]) # DEFINITION: by absolute position it is meant the position along the one # dimensional array containing all the tensor components. # Possible future work on this module: move computation of absolute # positions to a class method. # Determine absolute positions of the uncontracted indices: remaining_indices = [[cum_shape[i]*j for j in range(array.shape[i])] for i in range(rank) if i not in taken_dims] # Determine absolute positions of the contracted indices: summed_deltas = [] for axes_group in contraction_axes: lidx = [] for js in range(array.shape[axes_group[0]]): lidx.append(sum([cum_shape[ig] * js for ig in axes_group])) summed_deltas.append(lidx) # Compute the contracted array: # # 1. external for loops on all uncontracted indices. # Uncontracted indices are determined by the combinatorial product of # the absolute positions of the remaining indices. # 2. internal loop on all contracted indices. # It sum the values of the absolute contracted index and the absolute # uncontracted index for the external loop. contracted_array = [] for icontrib in itertools.product(*remaining_indices): index_base_position = sum(icontrib) isum = S.Zero for sum_to_index in itertools.product(*summed_deltas): idx = array._get_tuple_index(index_base_position + sum(sum_to_index)) isum += array[idx] contracted_array.append(isum) if len(remaining_indices) == 0: assert len(contracted_array) == 1 return contracted_array[0] return type(array)(contracted_array, remaining_shape) def derive_by_array(expr, dx): r""" Derivative by arrays. Supports both arrays and scalars. Given the array `A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}` this function will return a new array `B` defined by `B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}` Examples ======== >>> from sympy import derive_by_array >>> from sympy.abc import x, y, z, t >>> from sympy import cos >>> derive_by_array(cos(x*t), x) -t*sin(t*x) >>> derive_by_array(cos(x*t), [x, y, z, t]) [-t*sin(t*x), 0, 0, -x*sin(t*x)] >>> derive_by_array([x, y**2*z], [[x, y], [z, t]]) [[[1, 0], [0, 2*y*z]], [[0, y**2], [0, 0]]] """ from sympy.matrices import MatrixBase from sympy.tensor.array import SparseNDimArray array_types = (Iterable, MatrixBase, NDimArray) if isinstance(dx, array_types): dx = ImmutableDenseNDimArray(dx) for i in dx: if not i._diff_wrt: raise ValueError("cannot derive by this array") if isinstance(expr, array_types): if isinstance(expr, NDimArray): expr = expr.as_immutable() else: expr = ImmutableDenseNDimArray(expr) if isinstance(dx, array_types): if isinstance(expr, SparseNDimArray): lp = len(expr) new_array = {k + i*lp: v for i, x in enumerate(Flatten(dx)) for k, v in expr.diff(x)._sparse_array.items()} else: new_array = [[y.diff(x) for y in Flatten(expr)] for x in Flatten(dx)] return type(expr)(new_array, dx.shape + expr.shape) else: return expr.diff(dx) else: if isinstance(dx, array_types): return ImmutableDenseNDimArray([expr.diff(i) for i in Flatten(dx)], dx.shape) else: return diff(expr, dx) def permutedims(expr, perm): """ Permutes the indices of an array. Parameter specifies the permutation of the indices. Examples ======== >>> from sympy.abc import x, y, z, t >>> from sympy import sin >>> from sympy import Array, permutedims >>> a = Array([[x, y, z], [t, sin(x), 0]]) >>> a [[x, y, z], [t, sin(x), 0]] >>> permutedims(a, (1, 0)) [[x, t], [y, sin(x)], [z, 0]] If the array is of second order, ``transpose`` can be used: >>> from sympy import transpose >>> transpose(a) [[x, t], [y, sin(x)], [z, 0]] Examples on higher dimensions: >>> b = Array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) >>> permutedims(b, (2, 1, 0)) [[[1, 5], [3, 7]], [[2, 6], [4, 8]]] >>> permutedims(b, (1, 2, 0)) [[[1, 5], [2, 6]], [[3, 7], [4, 8]]] ``Permutation`` objects are also allowed: >>> from sympy.combinatorics import Permutation >>> permutedims(b, Permutation([1, 2, 0])) [[[1, 5], [2, 6]], [[3, 7], [4, 8]]] """ from sympy.tensor.array import SparseNDimArray if not isinstance(expr, NDimArray): raise TypeError("expression has to be an N-dim array") from sympy.combinatorics import Permutation if not isinstance(perm, Permutation): perm = Permutation(list(perm)) if perm.size != expr.rank(): raise ValueError("wrong permutation size") # Get the inverse permutation: iperm = ~perm new_shape = perm(expr.shape) if isinstance(expr, SparseNDimArray): return type(expr)({tuple(perm(expr._get_tuple_index(k))): v for k, v in expr._sparse_array.items()}, new_shape) indices_span = perm([range(i) for i in expr.shape]) new_array = [None]*len(expr) for i, idx in enumerate(itertools.product(*indices_span)): t = iperm(idx) new_array[i] = expr[t] return type(expr)(new_array, new_shape) class Flatten(Basic): ''' Flatten an iterable object to a list in a lazy-evaluation way. Notes ===== This class is an iterator with which the memory cost can be economised. Optimisation has been considered to ameliorate the performance for some specific data types like DenseNDimArray and SparseNDimArray. Examples ======== >>> from sympy.tensor.array.arrayop import Flatten >>> from sympy.tensor.array import Array >>> A = Array(range(6)).reshape(2, 3) >>> Flatten(A) Flatten([[0, 1, 2], [3, 4, 5]]) >>> [i for i in Flatten(A)] [0, 1, 2, 3, 4, 5] ''' def __init__(self, iterable): from sympy.matrices.matrices import MatrixBase from sympy.tensor.array import NDimArray if not isinstance(iterable, (Iterable, MatrixBase)): raise NotImplementedError("Data type not yet supported") if isinstance(iterable, list): iterable = NDimArray(iterable) self._iter = iterable self._idx = 0 def __iter__(self): return self def __next__(self): from sympy.matrices.matrices import MatrixBase if len(self._iter) > self._idx: if isinstance(self._iter, DenseNDimArray): result = self._iter._array[self._idx] elif isinstance(self._iter, SparseNDimArray): if self._idx in self._iter._sparse_array: result = self._iter._sparse_array[self._idx] else: result = 0 elif isinstance(self._iter, MatrixBase): result = self._iter[self._idx] elif hasattr(self._iter, '__next__'): result = next(self._iter) else: result = self._iter[self._idx] else: raise StopIteration self._idx += 1 return result def next(self): return self.__next__()
efe70eac2445b07a26fb5c4548cc748ddea4923b00c9fbee99a7b6814e241353
from __future__ import print_function, division 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.compatibility import SYMPY_INTS, Iterable from sympy.printing.defaults import Printable import itertools 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) 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 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 # Construct N-dim array from another N-dim array: elif isinstance(iterable, NDimArray): 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): raise TypeError(str(other)) 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): raise TypeError(str(other)) 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")
d2b2f58252232ac5eadd666103ee95d5ad7606ad7993f57c74df36504e09676d
from functools import wraps from sympy import Matrix, eye, Integer, expand, Indexed, Sum from sympy.combinatorics import Permutation from sympy.core import S, Rational, Symbol, Basic, Add from sympy.core.containers import Tuple from sympy.core.symbol import symbols from sympy.functions.elementary.miscellaneous import sqrt from sympy.tensor.array import Array from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorSymmetry, \ get_symmetric_group_sgs, TensorIndex, tensor_mul, TensAdd, \ riemann_cyclic_replace, riemann_cyclic, TensMul, tensor_heads, \ TensorManager, TensExpr, TensorHead, canon_bp, \ tensorhead, tensorsymmetry, TensorType, substitute_indices from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy, ignore_warnings from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy.matrices import diag def filter_warnings_decorator(f): @wraps(f) def wrapper(): with ignore_warnings(SymPyDeprecationWarning): f() return wrapper def _is_equal(arg1, arg2): if isinstance(arg1, TensExpr): return arg1.equals(arg2) elif isinstance(arg2, TensExpr): return arg2.equals(arg1) return arg1 == arg2 #################### Tests from tensor_can.py ####################### def test_canonicalize_no_slot_sym(): # A_d0 * B^d0; T_c = A^d0*B_d0 Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b, d0, d1 = tensor_indices('a,b,d0,d1', Lorentz) A, B = tensor_heads('A,B', [Lorentz], TensorSymmetry.no_symmetry(1)) t = A(-d0)*B(d0) tc = t.canon_bp() assert str(tc) == 'A(L_0)*B(-L_0)' # A^a * B^b; T_c = T t = A(a)*B(b) tc = t.canon_bp() assert tc == t # B^b * A^a t1 = B(b)*A(a) tc = t1.canon_bp() assert str(tc) == 'A(a)*B(b)' # A symmetric # A^{b}_{d0}*A^{d0, a}; T_c = A^{a d0}*A{b}_{d0} A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) t = A(b, -d0)*A(d0, a) tc = t.canon_bp() assert str(tc) == 'A(a, L_0)*A(b, -L_0)' # A^{d1}_{d0}*B^d0*C_d1 # T_c = A^{d0 d1}*B_d0*C_d1 B, C = tensor_heads('B,C', [Lorentz], TensorSymmetry.no_symmetry(1)) t = A(d1, -d0)*B(d0)*C(-d1) tc = t.canon_bp() assert str(tc) == 'A(L_0, L_1)*B(-L_0)*C(-L_1)' # A without symmetry # A^{d1}_{d0}*B^d0*C_d1 ord=[d0,-d0,d1,-d1]; g = [2,1,0,3,4,5] # T_c = A^{d0 d1}*B_d1*C_d0; can = [0,2,3,1,4,5] A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2)) t = A(d1, -d0)*B(d0)*C(-d1) tc = t.canon_bp() assert str(tc) == 'A(L_0, L_1)*B(-L_1)*C(-L_0)' # A, B without symmetry # A^{d1}_{d0}*B_{d1}^{d0} # T_c = A^{d0 d1}*B_{d0 d1} B = TensorHead('B', [Lorentz]*2, TensorSymmetry.no_symmetry(2)) t = A(d1, -d0)*B(-d1, d0) tc = t.canon_bp() assert str(tc) == 'A(L_0, L_1)*B(-L_0, -L_1)' # A_{d0}^{d1}*B_{d1}^{d0} # T_c = A^{d0 d1}*B_{d1 d0} t = A(-d0, d1)*B(-d1, d0) tc = t.canon_bp() assert str(tc) == 'A(L_0, L_1)*B(-L_1, -L_0)' # A, B, C without symmetry # A^{d1 d0}*B_{a d0}*C_{d1 b} # T_c=A^{d0 d1}*B_{a d1}*C_{d0 b} C = TensorHead('C', [Lorentz]*2, TensorSymmetry.no_symmetry(2)) t = A(d1, d0)*B(-a, -d0)*C(-d1, -b) tc = t.canon_bp() assert str(tc) == 'A(L_0, L_1)*B(-a, -L_1)*C(-L_0, -b)' # A symmetric, B and C without symmetry # A^{d1 d0}*B_{a d0}*C_{d1 b} # T_c = A^{d0 d1}*B_{a d0}*C_{d1 b} A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) t = A(d1, d0)*B(-a, -d0)*C(-d1, -b) tc = t.canon_bp() assert str(tc) == 'A(L_0, L_1)*B(-a, -L_0)*C(-L_1, -b)' # A and C symmetric, B without symmetry # A^{d1 d0}*B_{a d0}*C_{d1 b} ord=[a,b,d0,-d0,d1,-d1] # T_c = A^{d0 d1}*B_{a d0}*C_{b d1} C = TensorHead('C', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) t = A(d1, d0)*B(-a, -d0)*C(-d1, -b) tc = t.canon_bp() assert str(tc) == 'A(L_0, L_1)*B(-a, -L_0)*C(-b, -L_1)' def test_canonicalize_no_dummies(): Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b, c, d = tensor_indices('a, b, c, d', Lorentz) # A commuting # A^c A^b A^a # T_c = A^a A^b A^c A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1)) t = A(c)*A(b)*A(a) tc = t.canon_bp() assert str(tc) == 'A(a)*A(b)*A(c)' # A anticommuting # A^c A^b A^a # T_c = -A^a A^b A^c A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1), 1) t = A(c)*A(b)*A(a) tc = t.canon_bp() assert str(tc) == '-A(a)*A(b)*A(c)' # A commuting and symmetric # A^{b,d}*A^{c,a} # T_c = A^{a c}*A^{b d} A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) t = A(b, d)*A(c, a) tc = t.canon_bp() assert str(tc) == 'A(a, c)*A(b, d)' # A anticommuting and symmetric # A^{b,d}*A^{c,a} # T_c = -A^{a c}*A^{b d} A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2), 1) t = A(b, d)*A(c, a) tc = t.canon_bp() assert str(tc) == '-A(a, c)*A(b, d)' # A^{c,a}*A^{b,d} # T_c = A^{a c}*A^{b d} t = A(c, a)*A(b, d) tc = t.canon_bp() assert str(tc) == 'A(a, c)*A(b, d)' def test_tensorhead_construction_without_symmetry(): L = TensorIndexType('Lorentz') A1 = TensorHead('A', [L, L]) A2 = TensorHead('A', [L, L], TensorSymmetry.no_symmetry(2)) assert A1 == A2 A3 = TensorHead('A', [L, L], TensorSymmetry.fully_symmetric(2)) # Symmetric assert A1 != A3 def test_no_metric_symmetry(): # no metric symmetry; A no symmetry # A^d1_d0 * A^d0_d1 # T_c = A^d0_d1 * A^d1_d0 Lorentz = TensorIndexType('Lorentz', dummy_name='L', metric_symmetry=0) d0, d1, d2, d3 = tensor_indices('d:4', Lorentz) A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2)) t = A(d1, -d0)*A(d0, -d1) tc = t.canon_bp() assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_0)' # A^d1_d2 * A^d0_d3 * A^d2_d1 * A^d3_d0 # T_c = A^d0_d1 * A^d1_d0 * A^d2_d3 * A^d3_d2 t = A(d1, -d2)*A(d0, -d3)*A(d2, -d1)*A(d3, -d0) tc = t.canon_bp() assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_0)*A(L_2, -L_3)*A(L_3, -L_2)' # A^d0_d2 * A^d1_d3 * A^d3_d0 * A^d2_d1 # T_c = A^d0_d1 * A^d1_d2 * A^d2_d3 * A^d3_d0 t = A(d0, -d1)*A(d1, -d2)*A(d2, -d3)*A(d3, -d0) tc = t.canon_bp() assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_2)*A(L_2, -L_3)*A(L_3, -L_0)' def test_canonicalize1(): Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \ tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Lorentz) # A_d0*A^d0; ord = [d0,-d0] # T_c = A^d0*A_d0 A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1)) t = A(-d0)*A(d0) tc = t.canon_bp() assert str(tc) == 'A(L_0)*A(-L_0)' # A commuting # A_d0*A_d1*A_d2*A^d2*A^d1*A^d0 # T_c = A^d0*A_d0*A^d1*A_d1*A^d2*A_d2 t = A(-d0)*A(-d1)*A(-d2)*A(d2)*A(d1)*A(d0) tc = t.canon_bp() assert str(tc) == 'A(L_0)*A(-L_0)*A(L_1)*A(-L_1)*A(L_2)*A(-L_2)' # A anticommuting # A_d0*A_d1*A_d2*A^d2*A^d1*A^d0 # T_c 0 A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1), 1) t = A(-d0)*A(-d1)*A(-d2)*A(d2)*A(d1)*A(d0) tc = t.canon_bp() assert tc == 0 # A commuting symmetric # A^{d0 b}*A^a_d1*A^d1_d0 # T_c = A^{a d0}*A^{b d1}*A_{d0 d1} A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) t = A(d0, b)*A(a, -d1)*A(d1, -d0) tc = t.canon_bp() assert str(tc) == 'A(a, L_0)*A(b, L_1)*A(-L_0, -L_1)' # A, B commuting symmetric # A^{d0 b}*A^d1_d0*B^a_d1 # T_c = A^{b d0}*A_d0^d1*B^a_d1 B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) t = A(d0, b)*A(d1, -d0)*B(a, -d1) tc = t.canon_bp() assert str(tc) == 'A(b, L_0)*A(-L_0, L_1)*B(a, -L_1)' # A commuting symmetric # A^{d1 d0 b}*A^{a}_{d1 d0}; ord=[a,b, d0,-d0,d1,-d1] # T_c = A^{a d0 d1}*A^{b}_{d0 d1} A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3)) t = A(d1, d0, b)*A(a, -d1, -d0) tc = t.canon_bp() assert str(tc) == 'A(a, L_0, L_1)*A(b, -L_0, -L_1)' # A^{d3 d0 d2}*A^a0_{d1 d2}*A^d1_d3^a1*A^{a2 a3}_d0 # T_c = A^{a0 d0 d1}*A^a1_d0^d2*A^{a2 a3 d3}*A_{d1 d2 d3} t = A(d3, d0, d2)*A(a0, -d1, -d2)*A(d1, -d3, a1)*A(a2, a3, -d0) tc = t.canon_bp() assert str(tc) == 'A(a0, L_0, L_1)*A(a1, -L_0, L_2)*A(a2, a3, L_3)*A(-L_1, -L_2, -L_3)' # A commuting symmetric, B antisymmetric # A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3 # in this esxample and in the next three, # renaming dummy indices and using symmetry of A, # T = A^{d0 d1 d2} * A_{d0 d1 d3} * B_d2^d3 # can = 0 A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3)) B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2)) t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3) tc = t.canon_bp() assert tc == 0 # A anticommuting symmetric, B antisymmetric # A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3 # T_c = A^{d0 d1 d2} * A_{d0 d1}^d3 * B_{d2 d3} A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3), 1) B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2)) t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3) tc = t.canon_bp() assert str(tc) == 'A(L_0, L_1, L_2)*A(-L_0, -L_1, L_3)*B(-L_2, -L_3)' # A anticommuting symmetric, B antisymmetric commuting, antisymmetric metric # A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3 # T_c = -A^{d0 d1 d2} * A_{d0 d1}^d3 * B_{d2 d3} Spinor = TensorIndexType('Spinor', dummy_name='S', metric_symmetry=-1) a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \ tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Spinor) A = TensorHead('A', [Spinor]*3, TensorSymmetry.fully_symmetric(3), 1) B = TensorHead('B', [Spinor]*2, TensorSymmetry.fully_symmetric(-2)) t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3) tc = t.canon_bp() assert str(tc) == '-A(S_0, S_1, S_2)*A(-S_0, -S_1, S_3)*B(-S_2, -S_3)' # A anticommuting symmetric, B antisymmetric anticommuting, # no metric symmetry # A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3 # T_c = A^{d0 d1 d2} * A_{d0 d1 d3} * B_d2^d3 Mat = TensorIndexType('Mat', metric_symmetry=0, dummy_name='M') a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \ tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Mat) A = TensorHead('A', [Mat]*3, TensorSymmetry.fully_symmetric(3), 1) B = TensorHead('B', [Mat]*2, TensorSymmetry.fully_symmetric(-2)) t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3) tc = t.canon_bp() assert str(tc) == 'A(M_0, M_1, M_2)*A(-M_0, -M_1, -M_3)*B(-M_2, M_3)' # Gamma anticommuting # Gamma_{mu nu} * gamma^rho * Gamma^{nu mu alpha} # T_c = -Gamma^{mu nu} * gamma^rho * Gamma_{alpha mu nu} alpha, beta, gamma, mu, nu, rho = \ tensor_indices('alpha,beta,gamma,mu,nu,rho', Lorentz) Gamma = TensorHead('Gamma', [Lorentz], TensorSymmetry.fully_symmetric(1), 2) Gamma2 = TensorHead('Gamma', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2), 2) Gamma3 = TensorHead('Gamma', [Lorentz]*3, TensorSymmetry.fully_symmetric(-3), 2) t = Gamma2(-mu, -nu)*Gamma(rho)*Gamma3(nu, mu, alpha) tc = t.canon_bp() assert str(tc) == '-Gamma(L_0, L_1)*Gamma(rho)*Gamma(alpha, -L_0, -L_1)' # Gamma_{mu nu} * Gamma^{gamma beta} * gamma_rho * Gamma^{nu mu alpha} # T_c = Gamma^{mu nu} * Gamma^{beta gamma} * gamma_rho * Gamma^alpha_{mu nu} t = Gamma2(mu, nu)*Gamma2(beta, gamma)*Gamma(-rho)*Gamma3(alpha, -mu, -nu) tc = t.canon_bp() assert str(tc) == 'Gamma(L_0, L_1)*Gamma(beta, gamma)*Gamma(-rho)*Gamma(alpha, -L_0, -L_1)' # f^a_{b,c} antisymmetric in b,c; A_mu^a no symmetry # f^c_{d a} * f_{c e b} * A_mu^d * A_nu^a * A^{nu e} * A^{mu b} # g = [8,11,5, 9,13,7, 1,10, 3,4, 2,12, 0,6, 14,15] # T_c = -f^{a b c} * f_a^{d e} * A^mu_b * A_{mu d} * A^nu_c * A_{nu e} Flavor = TensorIndexType('Flavor', dummy_name='F') a, b, c, d, e, ff = tensor_indices('a,b,c,d,e,f', Flavor) mu, nu = tensor_indices('mu,nu', Lorentz) f = TensorHead('f', [Flavor]*3, TensorSymmetry.direct_product(1, -2)) A = TensorHead('A', [Lorentz, Flavor], TensorSymmetry.no_symmetry(2)) t = f(c, -d, -a)*f(-c, -e, -b)*A(-mu, d)*A(-nu, a)*A(nu, e)*A(mu, b) tc = t.canon_bp() assert str(tc) == '-f(F_0, F_1, F_2)*f(-F_0, F_3, F_4)*A(L_0, -F_1)*A(-L_0, -F_3)*A(L_1, -F_2)*A(-L_1, -F_4)' def test_bug_correction_tensor_indices(): # to make sure that tensor_indices does not return a list if creating # only one index: A = TensorIndexType("A") i = tensor_indices('i', A) assert not isinstance(i, (tuple, list)) assert isinstance(i, TensorIndex) def test_riemann_invariants(): Lorentz = TensorIndexType('Lorentz', dummy_name='L') d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11 = \ tensor_indices('d0:12', Lorentz) # R^{d0 d1}_{d1 d0}; ord = [d0,-d0,d1,-d1] # T_c = -R^{d0 d1}_{d0 d1} R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann()) t = R(d0, d1, -d1, -d0) tc = t.canon_bp() assert str(tc) == '-R(L_0, L_1, -L_0, -L_1)' # R_d11^d1_d0^d5 * R^{d6 d4 d0}_d5 * R_{d7 d2 d8 d9} * # R_{d10 d3 d6 d4} * R^{d2 d7 d11}_d1 * R^{d8 d9 d3 d10} # can = [0,2,4,6, 1,3,8,10, 5,7,12,14, 9,11,16,18, 13,15,20,22, # 17,19,21<F10,23, 24,25] # T_c = R^{d0 d1 d2 d3} * R_{d0 d1}^{d4 d5} * R_{d2 d3}^{d6 d7} * # R_{d4 d5}^{d8 d9} * R_{d6 d7}^{d10 d11} * R_{d8 d9 d10 d11} t = R(-d11,d1,-d0,d5)*R(d6,d4,d0,-d5)*R(-d7,-d2,-d8,-d9)* \ R(-d10,-d3,-d6,-d4)*R(d2,d7,d11,-d1)*R(d8,d9,d3,d10) tc = t.canon_bp() assert str(tc) == 'R(L_0, L_1, L_2, L_3)*R(-L_0, -L_1, L_4, L_5)*R(-L_2, -L_3, L_6, L_7)*R(-L_4, -L_5, L_8, L_9)*R(-L_6, -L_7, L_10, L_11)*R(-L_8, -L_9, -L_10, -L_11)' def test_riemann_products(): Lorentz = TensorIndexType('Lorentz', dummy_name='L') d0, d1, d2, d3, d4, d5, d6 = tensor_indices('d0:7', Lorentz) a0, a1, a2, a3, a4, a5 = tensor_indices('a0:6', Lorentz) a, b = tensor_indices('a,b', Lorentz) R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann()) # R^{a b d0}_d0 = 0 t = R(a, b, d0, -d0) tc = t.canon_bp() assert tc == 0 # R^{d0 b a}_d0 # T_c = -R^{a d0 b}_d0 t = R(d0, b, a, -d0) tc = t.canon_bp() assert str(tc) == '-R(a, L_0, b, -L_0)' # R^d1_d2^b_d0 * R^{d0 a}_d1^d2; ord=[a,b,d0,-d0,d1,-d1,d2,-d2] # T_c = -R^{a d0 d1 d2}* R^b_{d0 d1 d2} t = R(d1, -d2, b, -d0)*R(d0, a, -d1, d2) tc = t.canon_bp() assert str(tc) == '-R(a, L_0, L_1, L_2)*R(b, -L_0, -L_1, -L_2)' # A symmetric commuting # R^{d6 d5}_d2^d1 * R^{d4 d0 d2 d3} * A_{d6 d0} A_{d3 d1} * A_{d4 d5} # g = [12,10,5,2, 8,0,4,6, 13,1, 7,3, 9,11,14,15] # T_c = -R^{d0 d1 d2 d3} * R_d0^{d4 d5 d6} * A_{d1 d4}*A_{d2 d5}*A_{d3 d6} V = TensorHead('V', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) t = R(d6, d5, -d2, d1)*R(d4, d0, d2, d3)*V(-d6, -d0)*V(-d3, -d1)*V(-d4, -d5) tc = t.canon_bp() assert str(tc) == '-R(L_0, L_1, L_2, L_3)*R(-L_0, L_4, L_5, L_6)*V(-L_1, -L_4)*V(-L_2, -L_5)*V(-L_3, -L_6)' # R^{d2 a0 a2 d0} * R^d1_d2^{a1 a3} * R^{a4 a5}_{d0 d1} # T_c = R^{a0 d0 a2 d1}*R^{a1 a3}_d0^d2*R^{a4 a5}_{d1 d2} t = R(d2, a0, a2, d0)*R(d1, -d2, a1, a3)*R(a4, a5, -d0, -d1) tc = t.canon_bp() assert str(tc) == 'R(a0, L_0, a2, L_1)*R(a1, a3, -L_0, L_2)*R(a4, a5, -L_1, -L_2)' ###################################################################### def test_canonicalize2(): D = Symbol('D') Eucl = TensorIndexType('Eucl', metric_symmetry=1, dim=D, dummy_name='E') i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14 = \ tensor_indices('i0:15', Eucl) A = TensorHead('A', [Eucl]*3, TensorSymmetry.fully_symmetric(-3)) # two examples from Cvitanovic, Group Theory page 59 # of identities for antisymmetric tensors of rank 3 # contracted according to the Kuratowski graph eq.(6.59) t = A(i0,i1,i2)*A(-i1,i3,i4)*A(-i3,i7,i5)*A(-i2,-i5,i6)*A(-i4,-i6,i8) t1 = t.canon_bp() assert t1 == 0 # eq.(6.60) #t = A(i0,i1,i2)*A(-i1,i3,i4)*A(-i2,i5,i6)*A(-i3,i7,i8)*A(-i6,-i7,i9)* # A(-i8,i10,i13)*A(-i5,-i10,i11)*A(-i4,-i11,i12)*A(-i3,-i12,i14) t = A(i0,i1,i2)*A(-i1,i3,i4)*A(-i2,i5,i6)*A(-i3,i7,i8)*A(-i6,-i7,i9)*\ A(-i8,i10,i13)*A(-i5,-i10,i11)*A(-i4,-i11,i12)*A(-i9,-i12,i14) t1 = t.canon_bp() assert t1 == 0 def test_canonicalize3(): D = Symbol('D') Spinor = TensorIndexType('Spinor', dim=D, metric_symmetry=-1, dummy_name='S') a0,a1,a2,a3,a4 = tensor_indices('a0:5', Spinor) chi, psi = tensor_heads('chi,psi', [Spinor], TensorSymmetry.no_symmetry(1), 1) t = chi(a1)*psi(a0) t1 = t.canon_bp() assert t1 == t t = psi(a1)*chi(a0) t1 = t.canon_bp() assert t1 == -chi(a0)*psi(a1) def test_TensorIndexType(): D = Symbol('D') Lorentz = TensorIndexType('Lorentz', metric_name='g', metric_symmetry=1, dim=D, dummy_name='L') m0, m1, m2, m3, m4 = tensor_indices('m0:5', Lorentz) sym2 = TensorSymmetry.fully_symmetric(2) sym2n = TensorSymmetry(*get_symmetric_group_sgs(2)) assert sym2 == sym2n g = Lorentz.metric assert str(g) == 'g(Lorentz,Lorentz)' assert Lorentz.eps_dim == Lorentz.dim TSpace = TensorIndexType('TSpace', dummy_name = 'TSpace') i0, i1 = tensor_indices('i0 i1', TSpace) g = TSpace.metric A = TensorHead('A', [TSpace]*2, sym2) assert str(A(i0,-i0).canon_bp()) == 'A(TSpace_0, -TSpace_0)' def test_indices(): Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b, c, d = tensor_indices('a,b,c,d', Lorentz) assert a.tensor_index_type == Lorentz assert a != -a A, B = tensor_heads('A B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) t = A(a,b)*B(-b,c) indices = t.get_indices() L_0 = TensorIndex('L_0', Lorentz) assert indices == [a, L_0, -L_0, c] raises(ValueError, lambda: tensor_indices(3, Lorentz)) raises(ValueError, lambda: A(a,b,c)) def test_TensorSymmetry(): assert TensorSymmetry.fully_symmetric(2) == \ TensorSymmetry(get_symmetric_group_sgs(2)) assert TensorSymmetry.fully_symmetric(-3) == \ TensorSymmetry(get_symmetric_group_sgs(3, True)) assert TensorSymmetry.direct_product(-4) == \ TensorSymmetry.fully_symmetric(-4) assert TensorSymmetry.fully_symmetric(-1) == \ TensorSymmetry.fully_symmetric(1) assert TensorSymmetry.direct_product(1, -1, 1) == \ TensorSymmetry.no_symmetry(3) assert TensorSymmetry(get_symmetric_group_sgs(2)) == \ TensorSymmetry(*get_symmetric_group_sgs(2)) # TODO: add check for *get_symmetric_group_sgs(0) sym = TensorSymmetry.fully_symmetric(-3) assert sym.rank == 3 assert sym.base == Tuple(0, 1) assert sym.generators == Tuple(Permutation(0, 1)(3, 4), Permutation(1, 2)(3, 4)) def test_TensExpr(): Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b, c, d = tensor_indices('a,b,c,d', Lorentz) g = Lorentz.metric A, B = tensor_heads('A B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) raises(ValueError, lambda: g(c, d)/g(a, b)) raises(ValueError, lambda: S.One/g(a, b)) raises(ValueError, lambda: (A(c, d) + g(c, d))/g(a, b)) raises(ValueError, lambda: S.One/(A(c, d) + g(c, d))) raises(ValueError, lambda: A(a, b) + A(a, c)) A(a, b) + B(a, b) # assigned to t for below #raises(NotImplementedError, lambda: TensExpr.__mul__(t, 'a')) #raises(NotImplementedError, lambda: TensExpr.__add__(t, 'a')) #raises(NotImplementedError, lambda: TensExpr.__radd__(t, 'a')) #raises(NotImplementedError, lambda: TensExpr.__sub__(t, 'a')) #raises(NotImplementedError, lambda: TensExpr.__rsub__(t, 'a')) #raises(NotImplementedError, lambda: TensExpr.__truediv__(t, 'a')) #raises(NotImplementedError, lambda: TensExpr.__rtruediv__(t, 'a')) with ignore_warnings(SymPyDeprecationWarning): # DO NOT REMOVE THIS AFTER DEPRECATION REMOVED: raises(ValueError, lambda: A(a, b)**2) raises(NotImplementedError, lambda: 2**A(a, b)) raises(NotImplementedError, lambda: abs(A(a, b))) def test_TensorHead(): # simple example of algebraic expression Lorentz = TensorIndexType('Lorentz', dummy_name='L') A = TensorHead('A', [Lorentz]*2) assert A.name == 'A' assert A.index_types == [Lorentz, Lorentz] assert A.rank == 2 assert A.symmetry == TensorSymmetry.no_symmetry(2) assert A.comm == 0 def test_add1(): assert TensAdd().args == () assert TensAdd().doit() == 0 # simple example of algebraic expression Lorentz = TensorIndexType('Lorentz', dummy_name='L') a,b,d0,d1,i,j,k = tensor_indices('a,b,d0,d1,i,j,k', Lorentz) # A, B symmetric A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) t1 = A(b, -d0)*B(d0, a) assert TensAdd(t1).equals(t1) t2a = B(d0, a) + A(d0, a) t2 = A(b, -d0)*t2a assert str(t2) == 'A(b, -L_0)*(A(L_0, a) + B(L_0, a))' t2 = t2.expand() assert str(t2) == 'A(b, -L_0)*A(L_0, a) + A(b, -L_0)*B(L_0, a)' t2 = t2.canon_bp() assert str(t2) == 'A(a, L_0)*A(b, -L_0) + A(b, L_0)*B(a, -L_0)' t2b = t2 + t1 assert str(t2b) == 'A(a, L_0)*A(b, -L_0) + A(b, -L_0)*B(L_0, a) + A(b, L_0)*B(a, -L_0)' t2b = t2b.canon_bp() assert str(t2b) == 'A(a, L_0)*A(b, -L_0) + 2*A(b, L_0)*B(a, -L_0)' p, q, r = tensor_heads('p,q,r', [Lorentz]) t = q(d0)*2 assert str(t) == '2*q(d0)' t = 2*q(d0) assert str(t) == '2*q(d0)' t1 = p(d0) + 2*q(d0) assert str(t1) == '2*q(d0) + p(d0)' t2 = p(-d0) + 2*q(-d0) assert str(t2) == '2*q(-d0) + p(-d0)' t1 = p(d0) t3 = t1*t2 assert str(t3) == 'p(L_0)*(2*q(-L_0) + p(-L_0))' t3 = t3.expand() assert str(t3) == 'p(L_0)*p(-L_0) + 2*p(L_0)*q(-L_0)' t3 = t2*t1 t3 = t3.expand() assert str(t3) == 'p(-L_0)*p(L_0) + 2*q(-L_0)*p(L_0)' t3 = t3.canon_bp() assert str(t3) == 'p(L_0)*p(-L_0) + 2*p(L_0)*q(-L_0)' t1 = p(d0) + 2*q(d0) t3 = t1*t2 t3 = t3.canon_bp() assert str(t3) == 'p(L_0)*p(-L_0) + 4*p(L_0)*q(-L_0) + 4*q(L_0)*q(-L_0)' t1 = p(d0) - 2*q(d0) assert str(t1) == '-2*q(d0) + p(d0)' t2 = p(-d0) + 2*q(-d0) t3 = t1*t2 t3 = t3.canon_bp() assert t3 == p(d0)*p(-d0) - 4*q(d0)*q(-d0) t = p(i)*p(j)*(p(k) + q(k)) + p(i)*(p(j) + q(j))*(p(k) - 3*q(k)) t = t.canon_bp() assert t == 2*p(i)*p(j)*p(k) - 2*p(i)*p(j)*q(k) + p(i)*p(k)*q(j) - 3*p(i)*q(j)*q(k) t1 = (p(i) + q(i) + 2*r(i))*(p(j) - q(j)) t2 = (p(j) + q(j) + 2*r(j))*(p(i) - q(i)) t = t1 + t2 t = t.canon_bp() assert t == 2*p(i)*p(j) + 2*p(i)*r(j) + 2*p(j)*r(i) - 2*q(i)*q(j) - 2*q(i)*r(j) - 2*q(j)*r(i) t = p(i)*q(j)/2 assert 2*t == p(i)*q(j) t = (p(i) + q(i))/2 assert 2*t == p(i) + q(i) t = S.One - p(i)*p(-i) t = t.canon_bp() tz1 = t + p(-j)*p(j) assert tz1 != 1 tz1 = tz1.canon_bp() assert tz1.equals(1) t = S.One + p(i)*p(-i) assert (t - p(-j)*p(j)).canon_bp().equals(1) t = A(a, b) + B(a, b) assert t.rank == 2 t1 = t - A(a, b) - B(a, b) assert t1 == 0 t = 1 - (A(a, -a) + B(a, -a)) t1 = 1 + (A(a, -a) + B(a, -a)) assert (t + t1).expand().equals(2) t2 = 1 + A(a, -a) assert t1 != t2 assert t2 != TensMul.from_data(0, [], [], []) def test_special_eq_ne(): # test special equality cases: Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b, d0, d1, i, j, k = tensor_indices('a,b,d0,d1,i,j,k', Lorentz) # A, B symmetric A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) p, q, r = tensor_heads('p,q,r', [Lorentz]) t = 0*A(a, b) assert _is_equal(t, 0) assert _is_equal(t, S.Zero) assert p(i) != A(a, b) assert A(a, -a) != A(a, b) assert 0*(A(a, b) + B(a, b)) == 0 assert 0*(A(a, b) + B(a, b)) is S.Zero assert 3*(A(a, b) - A(a, b)) is S.Zero assert p(i) + q(i) != A(a, b) assert p(i) + q(i) != A(a, b) + B(a, b) assert p(i) - p(i) == 0 assert p(i) - p(i) is S.Zero assert _is_equal(A(a, b), A(b, a)) def test_add2(): Lorentz = TensorIndexType('Lorentz', dummy_name='L') m, n, p, q = tensor_indices('m,n,p,q', Lorentz) R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann()) A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(-3)) t1 = 2*R(m, n, p, q) - R(m, q, n, p) + R(m, p, n, q) t2 = t1*A(-n, -p, -q) t2 = t2.canon_bp() assert t2 == 0 t1 = Rational(2, 3)*R(m,n,p,q) - Rational(1, 3)*R(m,q,n,p) + Rational(1, 3)*R(m,p,n,q) t2 = t1*A(-n, -p, -q) t2 = t2.canon_bp() assert t2 == 0 t = A(m, -m, n) + A(n, p, -p) t = t.canon_bp() assert t == 0 def test_add3(): Lorentz = TensorIndexType('Lorentz', dummy_name='L') i0, i1 = tensor_indices('i0:2', Lorentz) E, px, py, pz = symbols('E px py pz') A = TensorHead('A', [Lorentz]) B = TensorHead('B', [Lorentz]) expr1 = A(i0)*A(-i0) - (E**2 - px**2 - py**2 - pz**2) assert expr1.args == (-E**2, px**2, py**2, pz**2, A(i0)*A(-i0)) expr2 = E**2 - px**2 - py**2 - pz**2 - A(i0)*A(-i0) assert expr2.args == (E**2, -px**2, -py**2, -pz**2, -A(i0)*A(-i0)) expr3 = A(i0)*A(-i0) - E**2 + px**2 + py**2 + pz**2 assert expr3.args == (-E**2, px**2, py**2, pz**2, A(i0)*A(-i0)) expr4 = B(i1)*B(-i1) + 2*E**2 - 2*px**2 - 2*py**2 - 2*pz**2 - A(i0)*A(-i0) assert expr4.args == (2*E**2, -2*px**2, -2*py**2, -2*pz**2, B(i1)*B(-i1), -A(i0)*A(-i0)) def test_mul(): from sympy.abc import x Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b, c, d = tensor_indices('a,b,c,d', Lorentz) t = TensMul.from_data(S.One, [], [], []) assert str(t) == '1' A, B = tensor_heads('A B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) t = (1 + x)*A(a, b) assert str(t) == '(x + 1)*A(a, b)' assert t.index_types == [Lorentz, Lorentz] assert t.rank == 2 assert t.dum == [] assert t.coeff == 1 + x assert sorted(t.free) == [(a, 0), (b, 1)] assert t.components == [A] ts = A(a, b) assert str(ts) == 'A(a, b)' assert ts.index_types == [Lorentz, Lorentz] assert ts.rank == 2 assert ts.dum == [] assert ts.coeff == 1 assert sorted(ts.free) == [(a, 0), (b, 1)] assert ts.components == [A] t = A(-b, a)*B(-a, c)*A(-c, d) t1 = tensor_mul(*t.split()) assert t == t1 assert tensor_mul(*[]) == TensMul.from_data(S.One, [], [], []) t = TensMul.from_data(1, [], [], []) C = TensorHead('C', []) assert str(C()) == 'C' assert str(t) == '1' assert t == 1 raises(ValueError, lambda: A(a, b)*A(a, c)) def test_substitute_indices(): Lorentz = TensorIndexType('Lorentz', dummy_name='L') i, j, k, l, m, n, p, q = tensor_indices('i,j,k,l,m,n,p,q', Lorentz) A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) p = TensorHead('p', [Lorentz]) t = p(i) t1 = t.substitute_indices((j, k)) assert t1 == t t1 = t.substitute_indices((i, j)) assert t1 == p(j) t1 = t.substitute_indices((i, -j)) assert t1 == p(-j) t1 = t.substitute_indices((-i, j)) assert t1 == p(-j) t1 = t.substitute_indices((-i, -j)) assert t1 == p(j) t = A(m, n) t1 = t.substitute_indices((m, i), (n, -i)) assert t1 == A(n, -n) t1 = substitute_indices(t, (m, i), (n, -i)) assert t1 == A(n, -n) t = A(i, k)*B(-k, -j) t1 = t.substitute_indices((i, j), (j, k)) t1a = A(j, l)*B(-l, -k) assert t1 == t1a t1 = substitute_indices(t, (i, j), (j, k)) assert t1 == t1a t = A(i, j) + B(i, j) t1 = t.substitute_indices((j, -i)) t1a = A(i, -i) + B(i, -i) assert t1 == t1a t1 = substitute_indices(t, (j, -i)) assert t1 == t1a def test_riemann_cyclic_replace(): Lorentz = TensorIndexType('Lorentz', dummy_name='L') m0, m1, m2, m3 = tensor_indices('m:4', Lorentz) R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann()) t = R(m0, m2, m1, m3) t1 = riemann_cyclic_replace(t) t1a = Rational(-1, 3)*R(m0, m3, m2, m1) + Rational(1, 3)*R(m0, m1, m2, m3) + Rational(2, 3)*R(m0, m2, m1, m3) assert t1 == t1a def test_riemann_cyclic(): Lorentz = TensorIndexType('Lorentz', dummy_name='L') i, j, k, l, m, n, p, q = tensor_indices('i,j,k,l,m,n,p,q', Lorentz) R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann()) t = R(i,j,k,l) + R(i,l,j,k) + R(i,k,l,j) - \ R(i,j,l,k) - R(i,l,k,j) - R(i,k,j,l) t2 = t*R(-i,-j,-k,-l) t3 = riemann_cyclic(t2) assert t3 == 0 t = R(i,j,k,l)*(R(-i,-j,-k,-l) - 2*R(-i,-k,-j,-l)) t1 = riemann_cyclic(t) assert t1 == 0 t = R(i,j,k,l) t1 = riemann_cyclic(t) assert t1 == Rational(-1, 3)*R(i, l, j, k) + Rational(1, 3)*R(i, k, j, l) + Rational(2, 3)*R(i, j, k, l) t = R(i,j,k,l)*R(-k,-l,m,n)*(R(-m,-n,-i,-j) + 2*R(-m,-j,-n,-i)) t1 = riemann_cyclic(t) assert t1 == 0 @XFAIL def test_div(): Lorentz = TensorIndexType('Lorentz', dummy_name='L') m0, m1, m2, m3 = tensor_indices('m0:4', Lorentz) R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann()) t = R(m0,m1,-m1,m3) t1 = t/S(4) assert str(t1) == '(1/4)*R(m0, L_0, -L_0, m3)' t = t.canon_bp() assert not t1._is_canon_bp t1 = t*4 assert t1._is_canon_bp t1 = t1/4 assert t1._is_canon_bp def test_contract_metric1(): D = Symbol('D') Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L') a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz) g = Lorentz.metric p = TensorHead('p', [Lorentz]) t = g(a, b)*p(-b) t1 = t.contract_metric(g) assert t1 == p(a) A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) # case with g with all free indices t1 = A(a,b)*B(-b,c)*g(d, e) t2 = t1.contract_metric(g) assert t1 == t2 # case of g(d, -d) t1 = A(a,b)*B(-b,c)*g(-d, d) t2 = t1.contract_metric(g) assert t2 == D*A(a, d)*B(-d, c) # g with one free index t1 = A(a,b)*B(-b,-c)*g(c, d) t2 = t1.contract_metric(g) assert t2 == A(a, c)*B(-c, d) # g with both indices contracted with another tensor t1 = A(a,b)*B(-b,-c)*g(c, -a) t2 = t1.contract_metric(g) assert _is_equal(t2, A(a, b)*B(-b, -a)) t1 = A(a,b)*B(-b,-c)*g(c, d)*g(-a, -d) t2 = t1.contract_metric(g) assert _is_equal(t2, A(a,b)*B(-b,-a)) t1 = A(a,b)*g(-a,-b) t2 = t1.contract_metric(g) assert _is_equal(t2, A(a, -a)) assert not t2.free Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b = tensor_indices('a,b', Lorentz) g = Lorentz.metric assert _is_equal(g(a, -a).contract_metric(g), Lorentz.dim) # no dim def test_contract_metric2(): D = Symbol('D') Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L') a, b, c, d, e, L_0 = tensor_indices('a,b,c,d,e,L_0', Lorentz) g = Lorentz.metric p, q = tensor_heads('p,q', [Lorentz]) t1 = g(a,b)*p(c)*p(-c) t2 = 3*g(-a,-b)*q(c)*q(-c) t = t1*t2 t = t.contract_metric(g) assert t == 3*D*p(a)*p(-a)*q(b)*q(-b) t1 = g(a,b)*p(c)*p(-c) t2 = 3*q(-a)*q(-b) t = t1*t2 t = t.contract_metric(g) t = t.canon_bp() assert t == 3*p(a)*p(-a)*q(b)*q(-b) t1 = 2*g(a,b)*p(c)*p(-c) t2 = - 3*g(-a,-b)*q(c)*q(-c) t = t1*t2 t = t.contract_metric(g) t = 6*g(a,b)*g(-a,-b)*p(c)*p(-c)*q(d)*q(-d) t = t.contract_metric(g) t1 = 2*g(a,b)*p(c)*p(-c) t2 = q(-a)*q(-b) + 3*g(-a,-b)*q(c)*q(-c) t = t1*t2 t = t.contract_metric(g) assert t == (2 + 6*D)*p(a)*p(-a)*q(b)*q(-b) t1 = p(a)*p(b) + p(a)*q(b) + 2*g(a,b)*p(c)*p(-c) t2 = q(-a)*q(-b) - g(-a,-b)*q(c)*q(-c) t = t1*t2 t = t.contract_metric(g) t1 = (1 - 2*D)*p(a)*p(-a)*q(b)*q(-b) + p(a)*q(-a)*p(b)*q(-b) assert canon_bp(t - t1) == 0 t = g(a,b)*g(c,d)*g(-b,-c) t1 = t.contract_metric(g) assert t1 == g(a, d) t1 = g(a,b)*g(c,d) + g(a,c)*g(b,d) + g(a,d)*g(b,c) t2 = t1.substitute_indices((a,-a),(b,-b),(c,-c),(d,-d)) t = t1*t2 t = t.contract_metric(g) assert t.equals(3*D**2 + 6*D) t = 2*p(a)*g(b,-b) t1 = t.contract_metric(g) assert t1.equals(2*D*p(a)) t = 2*p(a)*g(b,-a) t1 = t.contract_metric(g) assert t1 == 2*p(b) M = Symbol('M') t = (p(a)*p(b) + g(a, b)*M**2)*g(-a, -b) - D*M**2 t1 = t.contract_metric(g) assert t1 == p(a)*p(-a) A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) t = A(a, b)*p(L_0)*g(-a, -b) t1 = t.contract_metric(g) assert str(t1) == 'A(L_1, -L_1)*p(L_0)' or str(t1) == 'A(-L_1, L_1)*p(L_0)' def test_metric_contract3(): D = Symbol('D') Spinor = TensorIndexType('Spinor', dim=D, metric_symmetry=-1, dummy_name='S') a0, a1, a2, a3, a4 = tensor_indices('a0:5', Spinor) C = Spinor.metric chi, psi = tensor_heads('chi,psi', [Spinor], TensorSymmetry.no_symmetry(1), 1) B = TensorHead('B', [Spinor]*2, TensorSymmetry.no_symmetry(2)) t = C(a0,-a0) t1 = t.contract_metric(C) assert t1.equals(-D) t = C(-a0,a0) t1 = t.contract_metric(C) assert t1.equals(D) t = C(a0,a1)*C(-a0,-a1) t1 = t.contract_metric(C) assert t1.equals(D) t = C(a1,a0)*C(-a0,-a1) t1 = t.contract_metric(C) assert t1.equals(-D) t = C(-a0,a1)*C(a0,-a1) t1 = t.contract_metric(C) assert t1.equals(-D) t = C(a1,-a0)*C(a0,-a1) t1 = t.contract_metric(C) assert t1.equals(D) t = C(a0,a1)*B(-a1,-a0) t1 = t.contract_metric(C) t1 = t1.canon_bp() assert _is_equal(t1, B(a0,-a0)) t = C(a1,a0)*B(-a1,-a0) t1 = t.contract_metric(C) assert _is_equal(t1, -B(a0,-a0)) t = C(a0,-a1)*B(a1,-a0) t1 = t.contract_metric(C) assert _is_equal(t1, -B(a0,-a0)) t = C(-a0,a1)*B(-a1,a0) t1 = t.contract_metric(C) assert _is_equal(t1, -B(a0,-a0)) t = C(-a0,-a1)*B(a1,a0) t1 = t.contract_metric(C) assert _is_equal(t1, B(a0,-a0)) t = C(-a1, a0)*B(a1,-a0) t1 = t.contract_metric(C) assert _is_equal(t1, B(a0,-a0)) t = C(a0,a1)*psi(-a1) t1 = t.contract_metric(C) assert _is_equal(t1, psi(a0)) t = C(a1,a0)*psi(-a1) t1 = t.contract_metric(C) assert _is_equal(t1, -psi(a0)) t = C(a0,a1)*chi(-a0)*psi(-a1) t1 = t.contract_metric(C) assert _is_equal(t1, -chi(a1)*psi(-a1)) t = C(a1,a0)*chi(-a0)*psi(-a1) t1 = t.contract_metric(C) assert _is_equal(t1, chi(a1)*psi(-a1)) t = C(-a1,a0)*chi(-a0)*psi(a1) t1 = t.contract_metric(C) assert _is_equal(t1, chi(-a1)*psi(a1)) t = C(a0,-a1)*chi(-a0)*psi(a1) t1 = t.contract_metric(C) assert _is_equal(t1, -chi(-a1)*psi(a1)) t = C(-a0,-a1)*chi(a0)*psi(a1) t1 = t.contract_metric(C) assert _is_equal(t1, chi(-a1)*psi(a1)) t = C(-a1,-a0)*chi(a0)*psi(a1) t1 = t.contract_metric(C) assert _is_equal(t1, -chi(-a1)*psi(a1)) t = C(-a1,-a0)*B(a0,a2)*psi(a1) t1 = t.contract_metric(C) assert _is_equal(t1, -B(-a1,a2)*psi(a1)) t = C(a1,a0)*B(-a2,-a0)*psi(-a1) t1 = t.contract_metric(C) assert _is_equal(t1, B(-a2,a1)*psi(-a1)) def test_epsilon(): Lorentz = TensorIndexType('Lorentz', dim=4, dummy_name='L') a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz) epsilon = Lorentz.epsilon p, q, r, s = tensor_heads('p,q,r,s', [Lorentz]) t = epsilon(b,a,c,d) t1 = t.canon_bp() assert t1 == -epsilon(a,b,c,d) t = epsilon(c,b,d,a) t1 = t.canon_bp() assert t1 == epsilon(a,b,c,d) t = epsilon(c,a,d,b) t1 = t.canon_bp() assert t1 == -epsilon(a,b,c,d) t = epsilon(a,b,c,d)*p(-a)*q(-b) t1 = t.canon_bp() assert t1 == epsilon(c,d,a,b)*p(-a)*q(-b) t = epsilon(c,b,d,a)*p(-a)*q(-b) t1 = t.canon_bp() assert t1 == epsilon(c,d,a,b)*p(-a)*q(-b) t = epsilon(c,a,d,b)*p(-a)*q(-b) t1 = t.canon_bp() assert t1 == -epsilon(c,d,a,b)*p(-a)*q(-b) t = epsilon(c,a,d,b)*p(-a)*p(-b) t1 = t.canon_bp() assert t1 == 0 t = epsilon(c,a,d,b)*p(-a)*q(-b) + epsilon(a,b,c,d)*p(-b)*q(-a) t1 = t.canon_bp() assert t1 == -2*epsilon(c,d,a,b)*p(-a)*q(-b) # Test that epsilon can be create with a SymPy integer: Lorentz = TensorIndexType('Lorentz', dim=Integer(4), dummy_name='L') epsilon = Lorentz.epsilon assert isinstance(epsilon, TensorHead) def test_contract_delta1(): # see Group Theory by Cvitanovic page 9 n = Symbol('n') Color = TensorIndexType('Color', dim=n, dummy_name='C') a, b, c, d, e, f = tensor_indices('a,b,c,d,e,f', Color) delta = Color.delta def idn(a, b, d, c): assert a.is_up and d.is_up assert not (b.is_up or c.is_up) return delta(a,c)*delta(d,b) def T(a, b, d, c): assert a.is_up and d.is_up assert not (b.is_up or c.is_up) return delta(a,b)*delta(d,c) def P1(a, b, c, d): return idn(a,b,c,d) - 1/n*T(a,b,c,d) def P2(a, b, c, d): return 1/n*T(a,b,c,d) t = P1(a, -b, e, -f)*P1(f, -e, d, -c) t1 = t.contract_delta(delta) assert canon_bp(t1 - P1(a, -b, d, -c)) == 0 t = P2(a, -b, e, -f)*P2(f, -e, d, -c) t1 = t.contract_delta(delta) assert t1 == P2(a, -b, d, -c) t = P1(a, -b, e, -f)*P2(f, -e, d, -c) t1 = t.contract_delta(delta) assert t1 == 0 t = P1(a, -b, b, -a) t1 = t.contract_delta(delta) assert t1.equals(n**2 - 1) @filter_warnings_decorator def test_fun(): D = Symbol('D') Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L') a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz) g = Lorentz.metric p, q = tensor_heads('p q', [Lorentz]) t = q(c)*p(a)*q(b) + g(a,b)*g(c,d)*q(-d) assert t(a,b,c) == t assert canon_bp(t - t(b,a,c) - q(c)*p(a)*q(b) + q(c)*p(b)*q(a)) == 0 assert t(b,c,d) == q(d)*p(b)*q(c) + g(b,c)*g(d,e)*q(-e) t1 = t.substitute_indices((a,b),(b,a)) assert canon_bp(t1 - q(c)*p(b)*q(a) - g(a,b)*g(c,d)*q(-d)) == 0 # check that g_{a b; c} = 0 # example taken from L. Brewin # "A brief introduction to Cadabra" arxiv:0903.2085 # dg_{a b c} = \partial_{a} g_{b c} is symmetric in b, c dg = TensorHead('dg', [Lorentz]*3, TensorSymmetry.direct_product(1, 2)) # gamma^a_{b c} is the Christoffel symbol gamma = S.Half*g(a,d)*(dg(-b,-d,-c) + dg(-c,-b,-d) - dg(-d,-b,-c)) # t = g_{a b; c} t = dg(-c,-a,-b) - g(-a,-d)*gamma(d,-b,-c) - g(-b,-d)*gamma(d,-a,-c) t = t.contract_metric(g) assert t == 0 t = q(c)*p(a)*q(b) assert t(b,c,d) == q(d)*p(b)*q(c) def test_TensorManager(): Lorentz = TensorIndexType('Lorentz', dummy_name='L') LorentzH = TensorIndexType('LorentzH', dummy_name='LH') i, j = tensor_indices('i,j', Lorentz) ih, jh = tensor_indices('ih,jh', LorentzH) p, q = tensor_heads('p q', [Lorentz]) ph, qh = tensor_heads('ph qh', [LorentzH]) Gsymbol = Symbol('Gsymbol') GHsymbol = Symbol('GHsymbol') TensorManager.set_comm(Gsymbol, GHsymbol, 0) G = TensorHead('G', [Lorentz], TensorSymmetry.no_symmetry(1), Gsymbol) assert TensorManager._comm_i2symbol[G.comm] == Gsymbol GH = TensorHead('GH', [LorentzH], TensorSymmetry.no_symmetry(1), GHsymbol) ps = G(i)*p(-i) psh = GH(ih)*ph(-ih) t = ps + psh t1 = t*t assert canon_bp(t1 - ps*ps - 2*ps*psh - psh*psh) == 0 qs = G(i)*q(-i) qsh = GH(ih)*qh(-ih) assert _is_equal(ps*qsh, qsh*ps) assert not _is_equal(ps*qs, qs*ps) n = TensorManager.comm_symbols2i(Gsymbol) assert TensorManager.comm_i2symbol(n) == Gsymbol assert GHsymbol in TensorManager._comm_symbols2i raises(ValueError, lambda: TensorManager.set_comm(GHsymbol, 1, 2)) TensorManager.set_comms((Gsymbol,GHsymbol,0),(Gsymbol,1,1)) assert TensorManager.get_comm(n, 1) == TensorManager.get_comm(1, n) == 1 TensorManager.clear() assert TensorManager.comm == [{0:0, 1:0, 2:0}, {0:0, 1:1, 2:None}, {0:0, 1:None}] assert GHsymbol not in TensorManager._comm_symbols2i nh = TensorManager.comm_symbols2i(GHsymbol) assert TensorManager.comm_i2symbol(nh) == GHsymbol assert GHsymbol in TensorManager._comm_symbols2i def test_hash(): D = Symbol('D') Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L') a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz) g = Lorentz.metric p, q = tensor_heads('p q', [Lorentz]) p_type = p.args[1] t1 = p(a)*q(b) t2 = p(a)*p(b) assert hash(t1) != hash(t2) t3 = p(a)*p(b) + g(a,b) t4 = p(a)*p(b) - g(a,b) assert hash(t3) != hash(t4) assert a.func(*a.args) == a assert Lorentz.func(*Lorentz.args) == Lorentz assert g.func(*g.args) == g assert p.func(*p.args) == p assert p_type.func(*p_type.args) == p_type assert p(a).func(*(p(a)).args) == p(a) assert t1.func(*t1.args) == t1 assert t2.func(*t2.args) == t2 assert t3.func(*t3.args) == t3 assert t4.func(*t4.args) == t4 assert hash(a.func(*a.args)) == hash(a) assert hash(Lorentz.func(*Lorentz.args)) == hash(Lorentz) assert hash(g.func(*g.args)) == hash(g) assert hash(p.func(*p.args)) == hash(p) assert hash(p_type.func(*p_type.args)) == hash(p_type) assert hash(p(a).func(*(p(a)).args)) == hash(p(a)) assert hash(t1.func(*t1.args)) == hash(t1) assert hash(t2.func(*t2.args)) == hash(t2) assert hash(t3.func(*t3.args)) == hash(t3) assert hash(t4.func(*t4.args)) == hash(t4) def check_all(obj): return all([isinstance(_, Basic) for _ in obj.args]) assert check_all(a) assert check_all(Lorentz) assert check_all(g) assert check_all(p) assert check_all(p_type) assert check_all(p(a)) assert check_all(t1) assert check_all(t2) assert check_all(t3) assert check_all(t4) tsymmetry = TensorSymmetry.direct_product(-2, 1, 3) assert tsymmetry.func(*tsymmetry.args) == tsymmetry assert hash(tsymmetry.func(*tsymmetry.args)) == hash(tsymmetry) assert check_all(tsymmetry) ### TEST VALUED TENSORS ### def _get_valued_base_test_variables(): minkowski = Matrix(( (1, 0, 0, 0), (0, -1, 0, 0), (0, 0, -1, 0), (0, 0, 0, -1), )) Lorentz = TensorIndexType('Lorentz', dim=4) Lorentz.data = minkowski i0, i1, i2, i3, i4 = tensor_indices('i0:5', Lorentz) E, px, py, pz = symbols('E px py pz') A = TensorHead('A', [Lorentz]) A.data = [E, px, py, pz] B = TensorHead('B', [Lorentz], TensorSymmetry.no_symmetry(1), 'Gcomm') B.data = range(4) AB = TensorHead("AB", [Lorentz]*2) AB.data = minkowski ba_matrix = Matrix(( (1, 2, 3, 4), (5, 6, 7, 8), (9, 0, -1, -2), (-3, -4, -5, -6), )) BA = TensorHead("BA", [Lorentz]*2) BA.data = ba_matrix # Let's test the diagonal metric, with inverted Minkowski metric: LorentzD = TensorIndexType('LorentzD') LorentzD.data = [-1, 1, 1, 1] mu0, mu1, mu2 = tensor_indices('mu0:3', LorentzD) C = TensorHead('C', [LorentzD]) C.data = [E, px, py, pz] ### non-diagonal metric ### ndm_matrix = ( (1, 1, 0,), (1, 0, 1), (0, 1, 0,), ) ndm = TensorIndexType("ndm") ndm.data = ndm_matrix n0, n1, n2 = tensor_indices('n0:3', ndm) NA = TensorHead('NA', [ndm]) NA.data = range(10, 13) NB = TensorHead('NB', [ndm]*2) NB.data = [[i+j for j in range(10, 13)] for i in range(10, 13)] NC = TensorHead('NC', [ndm]*3) NC.data = [[[i+j+k for k in range(4, 7)] for j in range(1, 4)] for i in range(2, 5)] return (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1, n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) @filter_warnings_decorator def test_valued_tensor_iter(): (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1, n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables() list_BA = [Array([1, 2, 3, 4]), Array([5, 6, 7, 8]), Array([9, 0, -1, -2]), Array([-3, -4, -5, -6])] # iteration on VTensorHead assert list(A) == [E, px, py, pz] assert list(ba_matrix) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, -1, -2, -3, -4, -5, -6] assert list(BA) == list_BA # iteration on VTensMul assert list(A(i1)) == [E, px, py, pz] assert list(BA(i1, i2)) == list_BA assert list(3 * BA(i1, i2)) == [3 * i for i in list_BA] assert list(-5 * BA(i1, i2)) == [-5 * i for i in list_BA] # iteration on VTensAdd # A(i1) + A(i1) assert list(A(i1) + A(i1)) == [2*E, 2*px, 2*py, 2*pz] assert BA(i1, i2) - BA(i1, i2) == 0 assert list(BA(i1, i2) - 2 * BA(i1, i2)) == [-i for i in list_BA] @filter_warnings_decorator def test_valued_tensor_covariant_contravariant_elements(): (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1, n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables() assert A(-i0)[0] == A(i0)[0] assert A(-i0)[1] == -A(i0)[1] assert AB(i0, i1)[1, 1] == -1 assert AB(i0, -i1)[1, 1] == 1 assert AB(-i0, -i1)[1, 1] == -1 assert AB(-i0, i1)[1, 1] == 1 @filter_warnings_decorator def test_valued_tensor_get_matrix(): (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1, n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables() matab = AB(i0, i1).get_matrix() assert matab == Matrix([ [1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1], ]) # when alternating contravariant/covariant with [1, -1, -1, -1] metric # it becomes the identity matrix: assert AB(i0, -i1).get_matrix() == eye(4) # covariant and contravariant forms: assert A(i0).get_matrix() == Matrix([E, px, py, pz]) assert A(-i0).get_matrix() == Matrix([E, -px, -py, -pz]) @filter_warnings_decorator def test_valued_tensor_contraction(): (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1, n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables() assert (A(i0) * A(-i0)).data == E ** 2 - px ** 2 - py ** 2 - pz ** 2 assert (A(i0) * A(-i0)).data == A ** 2 assert (A(i0) * A(-i0)).data == A(i0) ** 2 assert (A(i0) * B(-i0)).data == -px - 2 * py - 3 * pz for i in range(4): for j in range(4): assert (A(i0) * B(-i1))[i, j] == [E, px, py, pz][i] * [0, -1, -2, -3][j] # test contraction on the alternative Minkowski metric: [-1, 1, 1, 1] assert (C(mu0) * C(-mu0)).data == -E ** 2 + px ** 2 + py ** 2 + pz ** 2 contrexp = A(i0) * AB(i1, -i0) assert A(i0).rank == 1 assert AB(i1, -i0).rank == 2 assert contrexp.rank == 1 for i in range(4): assert contrexp[i] == [E, px, py, pz][i] @filter_warnings_decorator def test_valued_tensor_self_contraction(): (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1, n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables() assert AB(i0, -i0).data == 4 assert BA(i0, -i0).data == 2 @filter_warnings_decorator def test_valued_tensor_pow(): (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1, n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables() assert C**2 == -E**2 + px**2 + py**2 + pz**2 assert C**1 == sqrt(-E**2 + px**2 + py**2 + pz**2) assert C(mu0)**2 == C**2 assert C(mu0)**1 == C**1 @filter_warnings_decorator def test_valued_tensor_expressions(): (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1, n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables() x1, x2, x3 = symbols('x1:4') # test coefficient in contraction: rank2coeff = x1 * A(i3) * B(i2) assert rank2coeff[1, 1] == x1 * px assert rank2coeff[3, 3] == 3 * pz * x1 coeff_expr = ((x1 * A(i4)) * (B(-i4) / x2)).data assert coeff_expr.expand() == -px*x1/x2 - 2*py*x1/x2 - 3*pz*x1/x2 add_expr = A(i0) + B(i0) assert add_expr[0] == E assert add_expr[1] == px + 1 assert add_expr[2] == py + 2 assert add_expr[3] == pz + 3 sub_expr = A(i0) - B(i0) assert sub_expr[0] == E assert sub_expr[1] == px - 1 assert sub_expr[2] == py - 2 assert sub_expr[3] == pz - 3 assert (add_expr * B(-i0)).data == -px - 2*py - 3*pz - 14 expr1 = x1*A(i0) + x2*B(i0) expr2 = expr1 * B(i1) * (-4) expr3 = expr2 + 3*x3*AB(i0, i1) expr4 = expr3 / 2 assert expr4 * 2 == expr3 expr5 = (expr4 * BA(-i1, -i0)) assert expr5.data.expand() == 28*E*x1 + 12*px*x1 + 20*py*x1 + 28*pz*x1 + 136*x2 + 3*x3 @filter_warnings_decorator def test_valued_tensor_add_scalar(): (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1, n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables() # one scalar summand after the contracted tensor expr1 = A(i0)*A(-i0) - (E**2 - px**2 - py**2 - pz**2) assert expr1.data == 0 # multiple scalar summands in front of the contracted tensor expr2 = E**2 - px**2 - py**2 - pz**2 - A(i0)*A(-i0) assert expr2.data == 0 # multiple scalar summands after the contracted tensor expr3 = A(i0)*A(-i0) - E**2 + px**2 + py**2 + pz**2 assert expr3.data == 0 # multiple scalar summands and multiple tensors expr4 = C(mu0)*C(-mu0) + 2*E**2 - 2*px**2 - 2*py**2 - 2*pz**2 - A(i0)*A(-i0) assert expr4.data == 0 @filter_warnings_decorator def test_noncommuting_components(): (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1, n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables() euclid = TensorIndexType('Euclidean') euclid.data = [1, 1] i1, i2, i3 = tensor_indices('i1:4', euclid) a, b, c, d = symbols('a b c d', commutative=False) V1 = TensorHead('V1', [euclid]*2) V1.data = [[a, b], (c, d)] V2 = TensorHead('V2', [euclid]*2) V2.data = [[a, c], [b, d]] vtp = V1(i1, i2) * V2(-i2, -i1) assert vtp.data == a**2 + b**2 + c**2 + d**2 assert vtp.data != a**2 + 2*b*c + d**2 vtp2 = V1(i1, i2)*V1(-i2, -i1) assert vtp2.data == a**2 + b*c + c*b + d**2 assert vtp2.data != a**2 + 2*b*c + d**2 Vc = (b * V1(i1, -i1)).data assert Vc.expand() == b * a + b * d @filter_warnings_decorator def test_valued_non_diagonal_metric(): (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1, n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables() mmatrix = Matrix(ndm_matrix) assert (NA(n0)*NA(-n0)).data == (NA(n0).get_matrix().T * mmatrix * NA(n0).get_matrix())[0, 0] @filter_warnings_decorator def test_valued_assign_numpy_ndarray(): (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1, n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables() # this is needed to make sure that a numpy.ndarray can be assigned to a # tensor. arr = [E+1, px-1, py, pz] A.data = Array(arr) for i in range(4): assert A(i0).data[i] == arr[i] qx, qy, qz = symbols('qx qy qz') A(-i0).data = Array([E, qx, qy, qz]) for i in range(4): assert A(i0).data[i] == [E, -qx, -qy, -qz][i] assert A.data[i] == [E, -qx, -qy, -qz][i] # test on multi-indexed tensors. random_4x4_data = [[(i**3-3*i**2)%(j+7) for i in range(4)] for j in range(4)] AB(-i0, -i1).data = random_4x4_data for i in range(4): for j in range(4): assert AB(i0, i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)*(-1 if j else 1) assert AB(-i0, i1).data[i, j] == random_4x4_data[i][j]*(-1 if j else 1) assert AB(i0, -i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1) assert AB(-i0, -i1).data[i, j] == random_4x4_data[i][j] AB(-i0, i1).data = random_4x4_data for i in range(4): for j in range(4): assert AB(i0, i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1) assert AB(-i0, i1).data[i, j] == random_4x4_data[i][j] assert AB(i0, -i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)*(-1 if j else 1) assert AB(-i0, -i1).data[i, j] == random_4x4_data[i][j]*(-1 if j else 1) @filter_warnings_decorator def test_valued_metric_inverse(): (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1, n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables() # let's assign some fancy matrix, just to verify it: # (this has no physical sense, it's just testing sympy); # it is symmetrical: md = [[2, 2, 2, 1], [2, 3, 1, 0], [2, 1, 2, 3], [1, 0, 3, 2]] Lorentz.data = md m = Matrix(md) metric = Lorentz.metric minv = m.inv() meye = eye(4) # the Kronecker Delta: KD = Lorentz.get_kronecker_delta() for i in range(4): for j in range(4): assert metric(i0, i1).data[i, j] == m[i, j] assert metric(-i0, -i1).data[i, j] == minv[i, j] assert metric(i0, -i1).data[i, j] == meye[i, j] assert metric(-i0, i1).data[i, j] == meye[i, j] assert metric(i0, i1)[i, j] == m[i, j] assert metric(-i0, -i1)[i, j] == minv[i, j] assert metric(i0, -i1)[i, j] == meye[i, j] assert metric(-i0, i1)[i, j] == meye[i, j] assert KD(i0, -i1)[i, j] == meye[i, j] @filter_warnings_decorator def test_valued_canon_bp_swapaxes(): (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1, n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables() e1 = A(i1)*A(i0) e2 = e1.canon_bp() assert e2 == A(i0)*A(i1) for i in range(4): for j in range(4): assert e1[i, j] == e2[j, i] o1 = B(i2)*A(i1)*B(i0) o2 = o1.canon_bp() for i in range(4): for j in range(4): for k in range(4): assert o1[i, j, k] == o2[j, i, k] @filter_warnings_decorator def test_valued_components_with_wrong_symmetry(): IT = TensorIndexType('IT', dim=3) i0, i1, i2, i3 = tensor_indices('i0:4', IT) IT.data = [1, 1, 1] A_nosym = TensorHead('A', [IT]*2) A_sym = TensorHead('A', [IT]*2, TensorSymmetry.fully_symmetric(2)) A_antisym = TensorHead('A', [IT]*2, TensorSymmetry.fully_symmetric(-2)) mat_nosym = Matrix([[1,2,3],[4,5,6],[7,8,9]]) mat_sym = mat_nosym + mat_nosym.T mat_antisym = mat_nosym - mat_nosym.T A_nosym.data = mat_nosym A_nosym.data = mat_sym A_nosym.data = mat_antisym def assign(A, dat): A.data = dat A_sym.data = mat_sym raises(ValueError, lambda: assign(A_sym, mat_nosym)) raises(ValueError, lambda: assign(A_sym, mat_antisym)) A_antisym.data = mat_antisym raises(ValueError, lambda: assign(A_antisym, mat_sym)) raises(ValueError, lambda: assign(A_antisym, mat_nosym)) A_sym.data = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] A_antisym.data = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] @filter_warnings_decorator def test_issue_10972_TensMul_data(): Lorentz = TensorIndexType('Lorentz', metric_symmetry=1, dummy_name='i', dim=2) Lorentz.data = [-1, 1] mu, nu, alpha, beta = tensor_indices('\\mu, \\nu, \\alpha, \\beta', Lorentz) u = TensorHead('u', [Lorentz]) u.data = [1, 0] F = TensorHead('F', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2)) F.data = [[0, 1], [-1, 0]] mul_1 = F(mu, alpha) * u(-alpha) * F(nu, beta) * u(-beta) assert (mul_1.data == Array([[0, 0], [0, 1]])) mul_2 = F(mu, alpha) * F(nu, beta) * u(-alpha) * u(-beta) assert (mul_2.data == mul_1.data) assert ((mul_1 + mul_1).data == 2 * mul_1.data) @filter_warnings_decorator def test_TensMul_data(): Lorentz = TensorIndexType('Lorentz', metric_symmetry=1, dummy_name='L', dim=4) Lorentz.data = [-1, 1, 1, 1] mu, nu, alpha, beta = tensor_indices('\\mu, \\nu, \\alpha, \\beta', Lorentz) u = TensorHead('u', [Lorentz]) u.data = [1, 0, 0, 0] F = TensorHead('F', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2)) Ex, Ey, Ez, Bx, By, Bz = symbols('E_x E_y E_z B_x B_y B_z') F.data = [ [0, Ex, Ey, Ez], [-Ex, 0, Bz, -By], [-Ey, -Bz, 0, Bx], [-Ez, By, -Bx, 0]] E = F(mu, nu) * u(-nu) assert ((E(mu) * E(nu)).data == Array([[0, 0, 0, 0], [0, Ex ** 2, Ex * Ey, Ex * Ez], [0, Ex * Ey, Ey ** 2, Ey * Ez], [0, Ex * Ez, Ey * Ez, Ez ** 2]]) ) assert ((E(mu) * E(nu)).canon_bp().data == (E(mu) * E(nu)).data) assert ((F(mu, alpha) * F(beta, nu) * u(-alpha) * u(-beta)).data == - (E(mu) * E(nu)).data ) assert ((F(alpha, mu) * F(beta, nu) * u(-alpha) * u(-beta)).data == (E(mu) * E(nu)).data ) g = TensorHead('g', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) g.data = Lorentz.data # tensor 'perp' is orthogonal to vector 'u' perp = u(mu) * u(nu) + g(mu, nu) mul_1 = u(-mu) * perp(mu, nu) assert (mul_1.data == Array([0, 0, 0, 0])) mul_2 = u(-mu) * perp(mu, alpha) * perp(nu, beta) assert (mul_2.data == Array.zeros(4, 4, 4)) Fperp = perp(mu, alpha) * perp(nu, beta) * F(-alpha, -beta) assert (Fperp.data[0, :] == Array([0, 0, 0, 0])) assert (Fperp.data[:, 0] == Array([0, 0, 0, 0])) mul_3 = u(-mu) * Fperp(mu, nu) assert (mul_3.data == Array([0, 0, 0, 0])) @filter_warnings_decorator def test_issue_11020_TensAdd_data(): Lorentz = TensorIndexType('Lorentz', metric_symmetry=1, dummy_name='i', dim=2) Lorentz.data = [-1, 1] a, b, c, d = tensor_indices('a, b, c, d', Lorentz) i0, i1 = tensor_indices('i_0:2', Lorentz) # metric tensor g = TensorHead('g', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) g.data = Lorentz.data u = TensorHead('u', [Lorentz]) u.data = [1, 0] add_1 = g(b, c) * g(d, i0) * u(-i0) - g(b, c) * u(d) assert (add_1.data == Array.zeros(2, 2, 2)) # Now let us replace index `d` with `a`: add_2 = g(b, c) * g(a, i0) * u(-i0) - g(b, c) * u(a) assert (add_2.data == Array.zeros(2, 2, 2)) # some more tests # perp is tensor orthogonal to u^\mu perp = u(a) * u(b) + g(a, b) mul_1 = u(-a) * perp(a, b) assert (mul_1.data == Array([0, 0])) mul_2 = u(-c) * perp(c, a) * perp(d, b) assert (mul_2.data == Array.zeros(2, 2, 2)) def test_index_iteration(): L = TensorIndexType("Lorentz", dummy_name="L") i0, i1, i2, i3, i4 = tensor_indices('i0:5', L) L0 = tensor_indices('L_0', L) L1 = tensor_indices('L_1', L) A = TensorHead("A", [L, L]) B = TensorHead("B", [L, L], TensorSymmetry.fully_symmetric(2)) e1 = A(i0,i2) e2 = A(i0,-i0) e3 = A(i0,i1)*B(i2,i3) e4 = A(i0,i1)*B(i2,-i1) e5 = A(i0,i1)*B(-i0,-i1) e6 = e1 + e4 assert list(e1._iterate_free_indices) == [(i0, (1, 0)), (i2, (1, 1))] assert list(e1._iterate_dummy_indices) == [] assert list(e1._iterate_indices) == [(i0, (1, 0)), (i2, (1, 1))] assert list(e2._iterate_free_indices) == [] assert list(e2._iterate_dummy_indices) == [(L0, (1, 0)), (-L0, (1, 1))] assert list(e2._iterate_indices) == [(L0, (1, 0)), (-L0, (1, 1))] assert list(e3._iterate_free_indices) == [(i0, (0, 1, 0)), (i1, (0, 1, 1)), (i2, (1, 1, 0)), (i3, (1, 1, 1))] assert list(e3._iterate_dummy_indices) == [] assert list(e3._iterate_indices) == [(i0, (0, 1, 0)), (i1, (0, 1, 1)), (i2, (1, 1, 0)), (i3, (1, 1, 1))] assert list(e4._iterate_free_indices) == [(i0, (0, 1, 0)), (i2, (1, 1, 0))] assert list(e4._iterate_dummy_indices) == [(L0, (0, 1, 1)), (-L0, (1, 1, 1))] assert list(e4._iterate_indices) == [(i0, (0, 1, 0)), (L0, (0, 1, 1)), (i2, (1, 1, 0)), (-L0, (1, 1, 1))] assert list(e5._iterate_free_indices) == [] assert list(e5._iterate_dummy_indices) == [(L0, (0, 1, 0)), (L1, (0, 1, 1)), (-L0, (1, 1, 0)), (-L1, (1, 1, 1))] assert list(e5._iterate_indices) == [(L0, (0, 1, 0)), (L1, (0, 1, 1)), (-L0, (1, 1, 0)), (-L1, (1, 1, 1))] assert list(e6._iterate_free_indices) == [(i0, (0, 0, 1, 0)), (i2, (0, 1, 1, 0)), (i0, (1, 1, 0)), (i2, (1, 1, 1))] assert list(e6._iterate_dummy_indices) == [(L0, (0, 0, 1, 1)), (-L0, (0, 1, 1, 1))] assert list(e6._iterate_indices) == [(i0, (0, 0, 1, 0)), (L0, (0, 0, 1, 1)), (i2, (0, 1, 1, 0)), (-L0, (0, 1, 1, 1)), (i0, (1, 1, 0)), (i2, (1, 1, 1))] assert e1.get_indices() == [i0, i2] assert e1.get_free_indices() == [i0, i2] assert e2.get_indices() == [L0, -L0] assert e2.get_free_indices() == [] assert e3.get_indices() == [i0, i1, i2, i3] assert e3.get_free_indices() == [i0, i1, i2, i3] assert e4.get_indices() == [i0, L0, i2, -L0] assert e4.get_free_indices() == [i0, i2] assert e5.get_indices() == [L0, L1, -L0, -L1] assert e5.get_free_indices() == [] def test_tensor_expand(): L = TensorIndexType("L") i, j, k = tensor_indices("i j k", L) L_0 = TensorIndex("L_0", L) A, B, C, D = tensor_heads("A B C D", [L]) assert isinstance(Add(A(i), B(i)), TensAdd) assert isinstance(expand(A(i)+B(i)), TensAdd) expr = A(i)*(A(-i)+B(-i)) assert expr.args == (A(L_0), A(-L_0) + B(-L_0)) assert expr != A(i)*A(-i) + A(i)*B(-i) assert expr.expand() == A(i)*A(-i) + A(i)*B(-i) assert str(expr) == "A(L_0)*(A(-L_0) + B(-L_0))" expr = A(i)*A(j) + A(i)*B(j) assert str(expr) == "A(i)*A(j) + A(i)*B(j)" expr = A(-i)*(A(i)*A(j) + A(i)*B(j)*C(k)*C(-k)) assert expr != A(-i)*A(i)*A(j) + A(-i)*A(i)*B(j)*C(k)*C(-k) assert expr.expand() == A(-i)*A(i)*A(j) + A(-i)*A(i)*B(j)*C(k)*C(-k) assert str(expr) == "A(-L_0)*(A(L_0)*A(j) + A(L_0)*B(j)*C(L_1)*C(-L_1))" assert str(expr.canon_bp()) == 'A(j)*A(L_0)*A(-L_0) + A(L_0)*A(-L_0)*B(j)*C(L_1)*C(-L_1)' expr = A(-i)*(2*A(i)*A(j) + A(i)*B(j)) assert expr.expand() == 2*A(-i)*A(i)*A(j) + A(-i)*A(i)*B(j) expr = 2*A(i)*A(-i) assert expr.coeff == 2 expr = A(i)*(B(j)*C(k) + C(j)*(A(k) + D(k))) assert str(expr) == "A(i)*(B(j)*C(k) + C(j)*(A(k) + D(k)))" assert str(expr.expand()) == "A(i)*B(j)*C(k) + A(i)*C(j)*A(k) + A(i)*C(j)*D(k)" assert isinstance(TensMul(3), TensMul) tm = TensMul(3).doit() assert tm == 3 assert isinstance(tm, Integer) p1 = B(j)*B(-j) + B(j)*C(-j) p2 = C(-i)*p1 p3 = A(i)*p2 assert p3.expand() == A(i)*C(-i)*B(j)*B(-j) + A(i)*C(-i)*B(j)*C(-j) expr = A(i)*(B(-i) + C(-i)*(B(j)*B(-j) + B(j)*C(-j))) assert expr.expand() == A(i)*B(-i) + A(i)*C(-i)*B(j)*B(-j) + A(i)*C(-i)*B(j)*C(-j) expr = C(-i)*(B(j)*B(-j) + B(j)*C(-j)) assert expr.expand() == C(-i)*B(j)*B(-j) + C(-i)*B(j)*C(-j) def test_tensor_alternative_construction(): L = TensorIndexType("L") i0, i1, i2, i3 = tensor_indices('i0:4', L) A = TensorHead("A", [L]) x, y = symbols("x y") assert A(i0) == A(Symbol("i0")) assert A(-i0) == A(-Symbol("i0")) raises(TypeError, lambda: A(x+y)) raises(ValueError, lambda: A(2*x)) def test_tensor_replacement(): L = TensorIndexType("L") L2 = TensorIndexType("L2", dim=2) i, j, k, l = tensor_indices("i j k l", L) A, B, C, D = tensor_heads("A B C D", [L]) H = TensorHead("H", [L, L]) K = TensorHead("K", [L]*4) expr = H(i, j) repl = {H(i,-j): [[1,2],[3,4]], L: diag(1, -1)} assert expr._extract_data(repl) == ([i, j], Array([[1, -2], [3, -4]])) assert expr.replace_with_arrays(repl) == Array([[1, -2], [3, -4]]) assert expr.replace_with_arrays(repl, [i, j]) == Array([[1, -2], [3, -4]]) assert expr.replace_with_arrays(repl, [i, -j]) == Array([[1, 2], [3, 4]]) assert expr.replace_with_arrays(repl, [-i, j]) == Array([[1, -2], [-3, 4]]) assert expr.replace_with_arrays(repl, [-i, -j]) == Array([[1, 2], [-3, -4]]) assert expr.replace_with_arrays(repl, [j, i]) == Array([[1, 3], [-2, -4]]) assert expr.replace_with_arrays(repl, [j, -i]) == Array([[1, -3], [-2, 4]]) assert expr.replace_with_arrays(repl, [-j, i]) == Array([[1, 3], [2, 4]]) assert expr.replace_with_arrays(repl, [-j, -i]) == Array([[1, -3], [2, -4]]) # Test stability of optional parameter 'indices' assert expr.replace_with_arrays(repl) == Array([[1, -2], [3, -4]]) expr = H(i,j) repl = {H(i,j): [[1,2],[3,4]], L: diag(1, -1)} assert expr._extract_data(repl) == ([i, j], Array([[1, 2], [3, 4]])) assert expr.replace_with_arrays(repl) == Array([[1, 2], [3, 4]]) assert expr.replace_with_arrays(repl, [i, j]) == Array([[1, 2], [3, 4]]) assert expr.replace_with_arrays(repl, [i, -j]) == Array([[1, -2], [3, -4]]) assert expr.replace_with_arrays(repl, [-i, j]) == Array([[1, 2], [-3, -4]]) assert expr.replace_with_arrays(repl, [-i, -j]) == Array([[1, -2], [-3, 4]]) assert expr.replace_with_arrays(repl, [j, i]) == Array([[1, 3], [2, 4]]) assert expr.replace_with_arrays(repl, [j, -i]) == Array([[1, -3], [2, -4]]) assert expr.replace_with_arrays(repl, [-j, i]) == Array([[1, 3], [-2, -4]]) assert expr.replace_with_arrays(repl, [-j, -i]) == Array([[1, -3], [-2, 4]]) # Not the same indices: expr = H(i,k) repl = {H(i,j): [[1,2],[3,4]], L: diag(1, -1)} assert expr._extract_data(repl) == ([i, k], Array([[1, 2], [3, 4]])) expr = A(i)*A(-i) repl = {A(i): [1,2], L: diag(1, -1)} assert expr._extract_data(repl) == ([], -3) assert expr.replace_with_arrays(repl, []) == -3 expr = K(i, j, -j, k)*A(-i)*A(-k) repl = {A(i): [1, 2], K(i,j,k,l): Array([1]*2**4).reshape(2,2,2,2), L: diag(1, -1)} assert expr._extract_data(repl) expr = H(j, k) repl = {H(i,j): [[1,2],[3,4]], L: diag(1, -1)} raises(ValueError, lambda: expr._extract_data(repl)) expr = A(i) repl = {B(i): [1, 2]} raises(ValueError, lambda: expr._extract_data(repl)) expr = A(i) repl = {A(i): [[1, 2], [3, 4]]} raises(ValueError, lambda: expr._extract_data(repl)) # TensAdd: expr = A(k)*H(i, j) + B(k)*H(i, j) repl = {A(k): [1], B(k): [1], H(i, j): [[1, 2],[3,4]], L:diag(1,1)} assert expr._extract_data(repl) == ([k, i, j], Array([[[2, 4], [6, 8]]])) assert expr.replace_with_arrays(repl, [k, i, j]) == Array([[[2, 4], [6, 8]]]) assert expr.replace_with_arrays(repl, [k, j, i]) == Array([[[2, 6], [4, 8]]]) expr = A(k)*A(-k) + 100 repl = {A(k): [2, 3], L: diag(1, 1)} assert expr.replace_with_arrays(repl, []) == 113 ## Symmetrization: expr = H(i, j) + H(j, i) repl = {H(i, j): [[1, 2], [3, 4]]} assert expr._extract_data(repl) == ([i, j], Array([[2, 5], [5, 8]])) assert expr.replace_with_arrays(repl, [i, j]) == Array([[2, 5], [5, 8]]) assert expr.replace_with_arrays(repl, [j, i]) == Array([[2, 5], [5, 8]]) ## Anti-symmetrization: expr = H(i, j) - H(j, i) repl = {H(i, j): [[1, 2], [3, 4]]} assert expr.replace_with_arrays(repl, [i, j]) == Array([[0, -1], [1, 0]]) assert expr.replace_with_arrays(repl, [j, i]) == Array([[0, 1], [-1, 0]]) # Tensors with contractions in replacements: expr = K(i, j, k, -k) repl = {K(i, j, k, -k): [[1, 2], [3, 4]]} assert expr._extract_data(repl) == ([i, j], Array([[1, 2], [3, 4]])) expr = H(i, -i) repl = {H(i, -i): 42} assert expr._extract_data(repl) == ([], 42) expr = H(i, -i) repl = { H(-i, -j): Array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]]), L: Array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]]), } assert expr._extract_data(repl) == ([], 4) # Replace with array, raise exception if indices are not compatible: expr = A(i)*A(j) repl = {A(i): [1, 2]} raises(ValueError, lambda: expr.replace_with_arrays(repl, [j])) # Raise exception if array dimension is not compatible: expr = A(i) repl = {A(i): [[1, 2]]} raises(ValueError, lambda: expr.replace_with_arrays(repl, [i])) # TensorIndexType with dimension, wrong dimension in replacement array: u1, u2, u3 = tensor_indices("u1:4", L2) U = TensorHead("U", [L2]) expr = U(u1)*U(-u2) repl = {U(u1): [[1]]} raises(ValueError, lambda: expr.replace_with_arrays(repl, [u1, -u2])) def test_rewrite_tensor_to_Indexed(): L = TensorIndexType("L", dim=4) A = TensorHead("A", [L]*4) B = TensorHead("B", [L]) i0, i1, i2, i3 = symbols("i0:4") L_0, L_1 = symbols("L_0:2") a1 = A(i0, i1, i2, i3) assert a1.rewrite(Indexed) == Indexed(Symbol("A"), i0, i1, i2, i3) a2 = A(i0, -i0, i2, i3) assert a2.rewrite(Indexed) == Sum(Indexed(Symbol("A"), L_0, L_0, i2, i3), (L_0, 0, 3)) a3 = a2 + A(i2, i3, i0, -i0) assert a3.rewrite(Indexed) == \ Sum(Indexed(Symbol("A"), L_0, L_0, i2, i3), (L_0, 0, 3)) +\ Sum(Indexed(Symbol("A"), i2, i3, L_0, L_0), (L_0, 0, 3)) b1 = B(-i0)*a1 assert b1.rewrite(Indexed) == Sum(Indexed(Symbol("B"), L_0)*Indexed(Symbol("A"), L_0, i1, i2, i3), (L_0, 0, 3)) b2 = B(-i3)*a2 assert b2.rewrite(Indexed) == Sum(Indexed(Symbol("B"), L_1)*Indexed(Symbol("A"), L_0, L_0, i2, L_1), (L_0, 0, 3), (L_1, 0, 3)) def test_tensorsymmetry(): with warns_deprecated_sympy(): tensorsymmetry([1]*2) def test_tensorhead(): with warns_deprecated_sympy(): tensorhead('A', []) def test_TensorType(): with warns_deprecated_sympy(): sym2 = TensorSymmetry.fully_symmetric(2) Lorentz = TensorIndexType('Lorentz') S2 = TensorType([Lorentz]*2, sym2) assert isinstance(S2, TensorType)
a61537673aeecc050218848af85bd982d57e942c82ddc9480c293ea269314edd
from sympy import Matrix, symbols, MatrixSymbol, NDimArray from sympy.matrices.common import MatrixCommon from sympy.tensor.array.array_derivatives import ArrayDerivative x, y, z, t = symbols("x y z t") m = Matrix([[x, y], [z, t]]) M = MatrixSymbol("M", 3, 2) N = MatrixSymbol("N", 4, 3) def test_array_derivative_construction(): d = ArrayDerivative(x, m, evaluate=False) assert d.shape == (2, 2) expr = d.doit() assert isinstance(expr, MatrixCommon) assert expr.shape == (2, 2) d = ArrayDerivative(m, m, evaluate=False) assert d.shape == (2, 2, 2, 2) expr = d.doit() assert isinstance(expr, NDimArray) assert expr.shape == (2, 2, 2, 2) d = ArrayDerivative(m, x, evaluate=False) assert d.shape == (2, 2) expr = d.doit() assert isinstance(expr, MatrixCommon) assert expr.shape == (2, 2) d = ArrayDerivative(M, N, evaluate=False) assert d.shape == (4, 3, 3, 2) expr = d.doit() assert isinstance(expr, ArrayDerivative) assert expr.shape == (4, 3, 3, 2) d = ArrayDerivative(M, (N, 2), evaluate=False) assert d.shape == (4, 3, 4, 3, 3, 2) expr = d.doit() assert isinstance(expr, ArrayDerivative) assert expr.shape == (4, 3, 4, 3, 3, 2) d = ArrayDerivative(M.as_explicit(), (N.as_explicit(), 2), evaluate=False) assert d.doit().shape == (4, 3, 4, 3, 3, 2) expr = d.doit() assert isinstance(expr, ArrayDerivative) assert expr.shape == (4, 3, 4, 3, 3, 2)
81d722ee5ef7503f127544b850a8432e34a52fcbb4faa6f4e38ada6341da32af
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)
9806364bcd70884898fd26e24c8b7bedf49dadc5fe6212796322444542a4af56
from copy import copy from sympy.tensor.array.dense_ndim_array import MutableDenseNDimArray from sympy import Symbol, Rational, SparseMatrix, diff, sympify, S from sympy.matrices import Matrix from sympy.tensor.array.sparse_ndim_array import MutableSparseNDimArray from sympy.testing.pytest import raises def test_ndim_array_initiation(): arr_with_one_element = MutableDenseNDimArray([23]) assert len(arr_with_one_element) == 1 assert arr_with_one_element[0] == 23 assert arr_with_one_element.rank() == 1 raises(ValueError, lambda: arr_with_one_element[1]) arr_with_symbol_element = MutableDenseNDimArray([Symbol('x')]) assert len(arr_with_symbol_element) == 1 assert arr_with_symbol_element[0] == Symbol('x') assert arr_with_symbol_element.rank() == 1 number5 = 5 vector = MutableDenseNDimArray.zeros(number5) assert len(vector) == number5 assert vector.shape == (number5,) assert vector.rank() == 1 raises(ValueError, lambda: arr_with_one_element[5]) vector = MutableSparseNDimArray.zeros(number5) assert len(vector) == number5 assert vector.shape == (number5,) assert vector._sparse_array == {} assert vector.rank() == 1 n_dim_array = MutableDenseNDimArray(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 raises(ValueError, lambda: n_dim_array[0, 0, 0, 3]) raises(ValueError, lambda: n_dim_array[3, 0, 0, 0]) raises(ValueError, lambda: n_dim_array[3**4]) array_shape = (3, 3, 3, 3) sparse_array = MutableSparseNDimArray.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 = MutableDenseNDimArray([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 = MutableSparseNDimArray.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 = MutableSparseNDimArray.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 = MutableDenseNDimArray(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 [MutableDenseNDimArray, MutableSparseNDimArray]: 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_sympify(): from sympy.abc import x, y, z, t arr = MutableDenseNDimArray([[x, y], [1, z*t]]) arr_other = sympify(arr) assert arr_other.shape == (2, 2) assert arr_other == arr def test_reshape(): array = MutableDenseNDimArray(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_iterator(): array = MutableDenseNDimArray(range(4), (2, 2)) array[0] == MutableDenseNDimArray([0, 1]) array[1] == MutableDenseNDimArray([2, 3]) array = array.reshape(4) j = 0 for i in array: assert i == j j += 1 def test_getitem(): for ArrayType in [MutableDenseNDimArray, MutableSparseNDimArray]: 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_sparse(): sparse_array = MutableSparseNDimArray([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 == MutableSparseNDimArray(j) sparse_array[0, 0] = 123 assert len(sparse_array._sparse_array) == 2 assert sparse_array[0, 0] == 123 assert sparse_array/0 == MutableSparseNDimArray([[S.ComplexInfinity, S.NaN], [S.NaN, S.ComplexInfinity]], (2, 2)) # when element in sparse array become zero it will disappear from # dictionary sparse_array[0, 0] = 0 assert len(sparse_array._sparse_array) == 1 sparse_array[1, 1] = 0 assert len(sparse_array._sparse_array) == 0 assert sparse_array[0, 0] == 0 # test for large scale sparse array # equality test a = MutableSparseNDimArray.zeros(100000, 200000) b = MutableSparseNDimArray.zeros(100000, 200000) assert a == b a[1, 1] = 1 b[1, 1] = 2 assert a != b # __mul__ and __rmul__ assert a * 3 == MutableSparseNDimArray({200001: 3}, (100000, 200000)) assert 3 * a == MutableSparseNDimArray({200001: 3}, (100000, 200000)) assert a * 0 == MutableSparseNDimArray({}, (100000, 200000)) assert 0 * a == MutableSparseNDimArray({}, (100000, 200000)) # __truediv__ assert a/3 == MutableSparseNDimArray({200001: Rational(1, 3)}, (100000, 200000)) # __neg__ assert -a == MutableSparseNDimArray({200001: -1}, (100000, 200000)) def test_calculation(): a = MutableDenseNDimArray([1]*9, (3, 3)) b = MutableDenseNDimArray([9]*9, (3, 3)) c = a + b for i in c: assert i == MutableDenseNDimArray([10, 10, 10]) assert c == MutableDenseNDimArray([10]*9, (3, 3)) assert c == MutableSparseNDimArray([10]*9, (3, 3)) c = b - a for i in c: assert i == MutableSparseNDimArray([8, 8, 8]) assert c == MutableDenseNDimArray([8]*9, (3, 3)) assert c == MutableSparseNDimArray([8]*9, (3, 3)) def test_ndim_array_converting(): dense_array = MutableDenseNDimArray([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 MutableDenseNDimArray(matrix) == dense_array assert MutableDenseNDimArray(matrix.as_immutable()) == dense_array assert MutableDenseNDimArray(matrix.as_mutable()) == dense_array sparse_array = MutableSparseNDimArray([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 MutableSparseNDimArray(matrix) == sparse_array assert MutableSparseNDimArray(matrix.as_immutable()) == sparse_array assert MutableSparseNDimArray(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 = MutableDenseNDimArray(arr_list, (2, 2)) assert (isinstance(arr_ndim_array, MutableDenseNDimArray)) assert arr_matrix.tolist() == arr_ndim_array.tolist() # Matrix arr_ndim_array = MutableDenseNDimArray(arr_matrix) assert (isinstance(arr_ndim_array, MutableDenseNDimArray)) 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 = MutableDenseNDimArray(first_list, (2, 2)) second_ndim_array = MutableDenseNDimArray(second_list, (2, 2)) third_ndim_array = MutableDenseNDimArray(third_list, (2, 2)) fourth_ndim_array = MutableDenseNDimArray(first_list, (2, 2)) assert first_ndim_array == second_ndim_array second_ndim_array[0, 0] = 0 assert first_ndim_array != second_ndim_array assert first_ndim_array != third_ndim_array assert first_ndim_array == fourth_ndim_array def test_arithmetic(): a = MutableDenseNDimArray([3 for i in range(9)], (3, 3)) b = MutableDenseNDimArray([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 == MutableDenseNDimArray([-3 for i in range(9)], (3, 3)) def test_higher_dimenions(): m3 = MutableDenseNDimArray(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 = MutableDenseNDimArray([[[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 = MutableDenseNDimArray([[[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_slices(): md = MutableDenseNDimArray(range(10, 34), (2, 3, 4)) assert md[:] == MutableDenseNDimArray(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 = MutableSparseNDimArray(range(10, 34), (2, 3, 4)) assert sd == MutableSparseNDimArray(md) assert sd[:] == MutableSparseNDimArray(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_slices_assign(): a = MutableDenseNDimArray(range(12), shape=(4, 3)) b = MutableSparseNDimArray(range(12), shape=(4, 3)) for i in [a, b]: assert i.tolist() == [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]] i[0, :] = [2, 2, 2] assert i.tolist() == [[2, 2, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]] i[0, 1:] = [8, 8] assert i.tolist() == [[2, 8, 8], [3, 4, 5], [6, 7, 8], [9, 10, 11]] i[1:3, 1] = [20, 44] assert i.tolist() == [[2, 8, 8], [3, 20, 5], [6, 44, 8], [9, 10, 11]] def test_diff(): from sympy.abc import x, y, z md = MutableDenseNDimArray([[x, y], [x*z, x*y*z]]) assert md.diff(x) == MutableDenseNDimArray([[1, 0], [z, y*z]]) assert diff(md, x) == MutableDenseNDimArray([[1, 0], [z, y*z]]) sd = MutableSparseNDimArray(md) assert sd == MutableSparseNDimArray([x, y, x*z, x*y*z], (2, 2)) assert sd.diff(x) == MutableSparseNDimArray([[1, 0], [z, y*z]]) assert diff(sd, x) == MutableSparseNDimArray([[1, 0], [z, y*z]])
1b2239c09db3500dcd61c454b540c9131f48ff067041f81541ecb107f63262ed
from typing import Dict, Any from sympy.multipledispatch import dispatch from sympy.multipledispatch.conflict import AmbiguityWarning from sympy.testing.pytest import raises, warns from functools import partial test_namespace = dict() # type: Dict[str, Any] orig_dispatch = dispatch dispatch = partial(dispatch, namespace=test_namespace) def test_singledispatch(): @dispatch(int) def f(x): # noqa:F811 return x + 1 @dispatch(int) def g(x): # noqa:F811 return x + 2 @dispatch(float) # noqa:F811 def f(x): # noqa:F811 return x - 1 assert f(1) == 2 assert g(1) == 3 assert f(1.0) == 0 assert raises(NotImplementedError, lambda: f('hello')) def test_multipledispatch(): @dispatch(int, int) def f(x, y): # noqa:F811 return x + y @dispatch(float, float) # noqa:F811 def f(x, y): # noqa:F811 return x - y assert f(1, 2) == 3 assert f(1.0, 2.0) == -1.0 class A: pass class B: pass class C(A): pass class D(C): pass class E(C): pass def test_inheritance(): @dispatch(A) def f(x): # noqa:F811 return 'a' @dispatch(B) # noqa:F811 def f(x): # noqa:F811 return 'b' assert f(A()) == 'a' assert f(B()) == 'b' assert f(C()) == 'a' def test_inheritance_and_multiple_dispatch(): @dispatch(A, A) def f(x, y): # noqa:F811 return type(x), type(y) @dispatch(A, B) # noqa:F811 def f(x, y): # noqa:F811 return 0 assert f(A(), A()) == (A, A) assert f(A(), C()) == (A, C) assert f(A(), B()) == 0 assert f(C(), B()) == 0 assert raises(NotImplementedError, lambda: f(B(), B())) def test_competing_solutions(): @dispatch(A) def h(x): # noqa:F811 return 1 @dispatch(C) # noqa:F811 def h(x): # noqa:F811 return 2 assert h(D()) == 2 def test_competing_multiple(): @dispatch(A, B) def h(x, y): # noqa:F811 return 1 @dispatch(C, B) # noqa:F811 def h(x, y): # noqa:F811 return 2 assert h(D(), B()) == 2 def test_competing_ambiguous(): test_namespace = dict() dispatch = partial(orig_dispatch, namespace=test_namespace) @dispatch(A, C) def f(x, y): # noqa:F811 return 2 with warns(AmbiguityWarning): @dispatch(C, A) # noqa:F811 def f(x, y): # noqa:F811 return 2 assert f(A(), C()) == f(C(), A()) == 2 # assert raises(Warning, lambda : f(C(), C())) def test_caching_correct_behavior(): @dispatch(A) def f(x): # noqa:F811 return 1 assert f(C()) == 1 @dispatch(C) def f(x): # noqa:F811 return 2 assert f(C()) == 2 def test_union_types(): @dispatch((A, C)) def f(x): # noqa:F811 return 1 assert f(A()) == 1 assert f(C()) == 1 def test_namespaces(): ns1 = dict() ns2 = dict() def foo(x): return 1 foo1 = orig_dispatch(int, namespace=ns1)(foo) def foo(x): return 2 foo2 = orig_dispatch(int, namespace=ns2)(foo) assert foo1(0) == 1 assert foo2(0) == 2 """ Fails def test_dispatch_on_dispatch(): @dispatch(A) @dispatch(C) def q(x): # noqa:F811 return 1 assert q(A()) == 1 assert q(C()) == 1 """ def test_methods(): class Foo: @dispatch(float) def f(self, x): # noqa:F811 return x - 1 @dispatch(int) # noqa:F811 def f(self, x): # noqa:F811 return x + 1 @dispatch(int) def g(self, x): # noqa:F811 return x + 3 foo = Foo() assert foo.f(1) == 2 assert foo.f(1.0) == 0.0 assert foo.g(1) == 4 def test_methods_multiple_dispatch(): class Foo: @dispatch(A, A) def f(x, y): # noqa:F811 return 1 @dispatch(A, C) # noqa:F811 def f(x, y): # noqa:F811 return 2 foo = Foo() assert foo.f(A(), A()) == 1 assert foo.f(A(), C()) == 2 assert foo.f(C(), C()) == 2
ac8ec57a56d2503099064d19f4f93886d6a6897c88d6c47621b52b3bd3afd711
from sympy.multipledispatch.dispatcher import (Dispatcher, MDNotImplementedError, MethodDispatcher, halt_ordering, restart_ordering, ambiguity_register_error_ignore_dup) from sympy.testing.pytest import raises, warns def identity(x): return x def inc(x): return x + 1 def dec(x): return x - 1 def test_dispatcher(): f = Dispatcher('f') f.add((int,), inc) f.add((float,), dec) with warns(DeprecationWarning): assert f.resolve((int,)) == inc assert f.dispatch(int) is inc assert f(1) == 2 assert f(1.0) == 0.0 def test_union_types(): f = Dispatcher('f') f.register((int, float))(inc) assert f(1) == 2 assert f(1.0) == 2.0 def test_dispatcher_as_decorator(): f = Dispatcher('f') @f.register(int) def inc(x): # noqa:F811 return x + 1 @f.register(float) # noqa:F811 def inc(x): # noqa:F811 return x - 1 assert f(1) == 2 assert f(1.0) == 0.0 def test_register_instance_method(): class Test: __init__ = MethodDispatcher('f') @__init__.register(list) def _init_list(self, data): self.data = data @__init__.register(object) def _init_obj(self, datum): self.data = [datum] a = Test(3) b = Test([3]) assert a.data == b.data def test_on_ambiguity(): f = Dispatcher('f') def identity(x): return x ambiguities = [False] def on_ambiguity(dispatcher, amb): ambiguities[0] = True f.add((object, object), identity, on_ambiguity=on_ambiguity) assert not ambiguities[0] f.add((object, float), identity, on_ambiguity=on_ambiguity) assert not ambiguities[0] f.add((float, object), identity, on_ambiguity=on_ambiguity) assert ambiguities[0] def test_raise_error_on_non_class(): f = Dispatcher('f') assert raises(TypeError, lambda: f.add((1,), inc)) def test_docstring(): def one(x, y): """ Docstring number one """ return x + y def two(x, y): """ Docstring number two """ return x + y def three(x, y): return x + y master_doc = 'Doc of the multimethod itself' f = Dispatcher('f', doc=master_doc) f.add((object, object), one) f.add((int, int), two) f.add((float, float), three) assert one.__doc__.strip() in f.__doc__ assert two.__doc__.strip() in f.__doc__ assert f.__doc__.find(one.__doc__.strip()) < \ f.__doc__.find(two.__doc__.strip()) assert 'object, object' in f.__doc__ assert master_doc in f.__doc__ def test_help(): def one(x, y): """ Docstring number one """ return x + y def two(x, y): """ Docstring number two """ return x + y def three(x, y): """ Docstring number three """ return x + y master_doc = 'Doc of the multimethod itself' f = Dispatcher('f', doc=master_doc) f.add((object, object), one) f.add((int, int), two) f.add((float, float), three) assert f._help(1, 1) == two.__doc__ assert f._help(1.0, 2.0) == three.__doc__ def test_source(): def one(x, y): """ Docstring number one """ return x + y def two(x, y): """ Docstring number two """ return x - y master_doc = 'Doc of the multimethod itself' f = Dispatcher('f', doc=master_doc) f.add((int, int), one) f.add((float, float), two) assert 'x + y' in f._source(1, 1) assert 'x - y' in f._source(1.0, 1.0) def test_source_raises_on_missing_function(): f = Dispatcher('f') assert raises(TypeError, lambda: f.source(1)) def test_halt_method_resolution(): g = [0] def on_ambiguity(a, b): g[0] += 1 f = Dispatcher('f') halt_ordering() def func(*args): pass f.add((int, object), func) f.add((object, int), func) assert g == [0] restart_ordering(on_ambiguity=on_ambiguity) assert g == [1] assert set(f.ordering) == {(int, object), (object, int)} def test_no_implementations(): f = Dispatcher('f') assert raises(NotImplementedError, lambda: f('hello')) def test_register_stacking(): f = Dispatcher('f') @f.register(list) @f.register(tuple) def rev(x): return x[::-1] assert f((1, 2, 3)) == (3, 2, 1) assert f([1, 2, 3]) == [3, 2, 1] assert raises(NotImplementedError, lambda: f('hello')) assert rev('hello') == 'olleh' def test_dispatch_method(): f = Dispatcher('f') @f.register(list) def rev(x): return x[::-1] @f.register(int, int) def add(x, y): return x + y class MyList(list): pass assert f.dispatch(list) is rev assert f.dispatch(MyList) is rev assert f.dispatch(int, int) is add def test_not_implemented(): f = Dispatcher('f') @f.register(object) def _(x): return 'default' @f.register(int) def _(x): if x % 2 == 0: return 'even' else: raise MDNotImplementedError() assert f('hello') == 'default' # default behavior assert f(2) == 'even' # specialized behavior assert f(3) == 'default' # fall bac to default behavior assert raises(NotImplementedError, lambda: f(1, 2)) def test_not_implemented_error(): f = Dispatcher('f') @f.register(float) def _(a): raise MDNotImplementedError() assert raises(NotImplementedError, lambda: f(1.0)) def test_ambiguity_register_error_ignore_dup(): f = Dispatcher('f') class A: pass class B(A): pass class C(A): pass # suppress warning for registering ambiguous signal f.add((A, B), lambda x,y: None, ambiguity_register_error_ignore_dup) f.add((B, A), lambda x,y: None, ambiguity_register_error_ignore_dup) f.add((A, C), lambda x,y: None, ambiguity_register_error_ignore_dup) f.add((C, A), lambda x,y: None, ambiguity_register_error_ignore_dup) # raises error if ambiguous signal is passed assert raises(NotImplementedError, lambda: f(B(), C()))
8845fe40a1d2bb2a895823639105db41a465b7342d0638335911e74eec01c577
from sympy import ( I, Rational, S, Symbol, simplify, symbols, sympify, expand_mul) from sympy.matrices.matrices import (ShapeError, NonSquareMatrixError) from sympy.matrices import ( ImmutableMatrix, Matrix, eye, ones, ImmutableDenseMatrix, dotprodsimp) from sympy.testing.pytest import raises from sympy.matrices.common import NonInvertibleMatrixError from sympy.abc import x, y def test_issue_17247_expression_blowup_29(): M = Matrix(S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.gauss_jordan_solve(ones(4, 1)) == (Matrix(S('''[ [ -32549314808672/3306971225785 - 17397006745216*I/3306971225785], [ 67439348256/3306971225785 - 9167503335872*I/3306971225785], [-15091965363354518272/21217636514687010905 + 16890163109293858304*I/21217636514687010905], [ -11328/952745 + 87616*I/952745]]''')), Matrix(0, 1, [])) def test_issue_17247_expression_blowup_30(): M = Matrix(S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.cholesky_solve(ones(4, 1)) == Matrix(S('''[ [ -32549314808672/3306971225785 - 17397006745216*I/3306971225785], [ 67439348256/3306971225785 - 9167503335872*I/3306971225785], [-15091965363354518272/21217636514687010905 + 16890163109293858304*I/21217636514687010905], [ -11328/952745 + 87616*I/952745]]''')) # @XFAIL # This calculation hangs with dotprodsimp. # def test_issue_17247_expression_blowup_31(): # M = Matrix([ # [x + 1, 1 - x, 0, 0], # [1 - x, x + 1, 0, x + 1], # [ 0, 1 - x, x + 1, 0], # [ 0, 0, 0, x + 1]]) # with dotprodsimp(True): # assert M.LDLsolve(ones(4, 1)) == Matrix([ # [(x + 1)/(4*x)], # [(x - 1)/(4*x)], # [(x + 1)/(4*x)], # [ 1/(x + 1)]]) def test_issue_17247_expression_blowup_32(): M = Matrix([ [x + 1, 1 - x, 0, 0], [1 - x, x + 1, 0, x + 1], [ 0, 1 - x, x + 1, 0], [ 0, 0, 0, x + 1]]) with dotprodsimp(True): assert M.LUsolve(ones(4, 1)) == Matrix([ [(x + 1)/(4*x)], [(x - 1)/(4*x)], [(x + 1)/(4*x)], [ 1/(x + 1)]]) def test_LUsolve(): A = Matrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]]) x = Matrix(3, 1, [3, 7, 5]) b = A*x soln = A.LUsolve(b) assert soln == x A = Matrix([[0, -1, 2], [5, 10, 7], [8, 3, 4]]) x = Matrix(3, 1, [-1, 2, 5]) b = A*x soln = A.LUsolve(b) assert soln == x A = Matrix([[2, 1], [1, 0], [1, 0]]) # issue 14548 b = Matrix([3, 1, 1]) assert A.LUsolve(b) == Matrix([1, 1]) b = Matrix([3, 1, 2]) # inconsistent raises(ValueError, lambda: A.LUsolve(b)) A = Matrix([[0, -1, 2], [5, 10, 7], [8, 3, 4], [2, 3, 5], [3, 6, 2], [8, 3, 6]]) x = Matrix([2, 1, -4]) b = A*x soln = A.LUsolve(b) assert soln == x A = Matrix([[0, -1, 2], [5, 10, 7]]) # underdetermined x = Matrix([-1, 2, 0]) b = A*x raises(NotImplementedError, lambda: A.LUsolve(b)) A = Matrix(4, 4, lambda i, j: 1/(i+j+1) if i != 3 else 0) b = Matrix.zeros(4, 1) raises(NonInvertibleMatrixError, lambda: A.LUsolve(b)) def test_QRsolve(): A = Matrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]]) x = Matrix(3, 1, [3, 7, 5]) b = A*x soln = A.QRsolve(b) assert soln == x x = Matrix([[1, 2], [3, 4], [5, 6]]) b = A*x soln = A.QRsolve(b) assert soln == x A = Matrix([[0, -1, 2], [5, 10, 7], [8, 3, 4]]) x = Matrix(3, 1, [-1, 2, 5]) b = A*x soln = A.QRsolve(b) assert soln == x x = Matrix([[7, 8], [9, 10], [11, 12]]) b = A*x soln = A.QRsolve(b) assert soln == x def test_errors(): raises(ShapeError, lambda: Matrix([1]).LUsolve(Matrix([[1, 2], [3, 4]]))) def test_cholesky_solve(): A = Matrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]]) x = Matrix(3, 1, [3, 7, 5]) b = A*x soln = A.cholesky_solve(b) assert soln == x A = Matrix([[0, -1, 2], [5, 10, 7], [8, 3, 4]]) x = Matrix(3, 1, [-1, 2, 5]) b = A*x soln = A.cholesky_solve(b) assert soln == x A = Matrix(((1, 5), (5, 1))) x = Matrix((4, -3)) b = A*x soln = A.cholesky_solve(b) assert soln == x A = Matrix(((9, 3*I), (-3*I, 5))) x = Matrix((-2, 1)) b = A*x soln = A.cholesky_solve(b) assert expand_mul(soln) == x A = Matrix(((9*I, 3), (-3 + I, 5))) x = Matrix((2 + 3*I, -1)) b = A*x soln = A.cholesky_solve(b) assert expand_mul(soln) == x a00, a01, a11, b0, b1 = symbols('a00, a01, a11, b0, b1') A = Matrix(((a00, a01), (a01, a11))) b = Matrix((b0, b1)) x = A.cholesky_solve(b) assert simplify(A*x) == b def test_LDLsolve(): A = Matrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]]) x = Matrix(3, 1, [3, 7, 5]) b = A*x soln = A.LDLsolve(b) assert soln == x A = Matrix([[0, -1, 2], [5, 10, 7], [8, 3, 4]]) x = Matrix(3, 1, [-1, 2, 5]) b = A*x soln = A.LDLsolve(b) assert soln == x A = Matrix(((9, 3*I), (-3*I, 5))) x = Matrix((-2, 1)) b = A*x soln = A.LDLsolve(b) assert expand_mul(soln) == x A = Matrix(((9*I, 3), (-3 + I, 5))) x = Matrix((2 + 3*I, -1)) b = A*x soln = A.LDLsolve(b) assert expand_mul(soln) == x A = Matrix(((9, 3), (3, 9))) x = Matrix((1, 1)) b = A * x soln = A.LDLsolve(b) assert expand_mul(soln) == x A = Matrix([[-5, -3, -4], [-3, -7, 7]]) x = Matrix([[8], [7], [-2]]) b = A * x raises(NotImplementedError, lambda: A.LDLsolve(b)) def test_lower_triangular_solve(): raises(NonSquareMatrixError, lambda: Matrix([1, 0]).lower_triangular_solve(Matrix([0, 1]))) raises(ShapeError, lambda: Matrix([[1, 0], [0, 1]]).lower_triangular_solve(Matrix([1]))) raises(ValueError, lambda: Matrix([[2, 1], [1, 2]]).lower_triangular_solve( Matrix([[1, 0], [0, 1]]))) A = Matrix([[1, 0], [0, 1]]) B = Matrix([[x, y], [y, x]]) C = Matrix([[4, 8], [2, 9]]) assert A.lower_triangular_solve(B) == B assert A.lower_triangular_solve(C) == C def test_upper_triangular_solve(): raises(NonSquareMatrixError, lambda: Matrix([1, 0]).upper_triangular_solve(Matrix([0, 1]))) raises(ShapeError, lambda: Matrix([[1, 0], [0, 1]]).upper_triangular_solve(Matrix([1]))) raises(TypeError, lambda: Matrix([[2, 1], [1, 2]]).upper_triangular_solve( Matrix([[1, 0], [0, 1]]))) A = Matrix([[1, 0], [0, 1]]) B = Matrix([[x, y], [y, x]]) C = Matrix([[2, 4], [3, 8]]) assert A.upper_triangular_solve(B) == B assert A.upper_triangular_solve(C) == C def test_diagonal_solve(): raises(TypeError, lambda: Matrix([1, 1]).diagonal_solve(Matrix([1]))) A = Matrix([[1, 0], [0, 1]])*2 B = Matrix([[x, y], [y, x]]) assert A.diagonal_solve(B) == B/2 A = Matrix([[1, 0], [1, 2]]) raises(TypeError, lambda: A.diagonal_solve(B)) def test_pinv_solve(): # Fully determined system (unique result, identical to other solvers). A = Matrix([[1, 5], [7, 9]]) B = Matrix([12, 13]) assert A.pinv_solve(B) == A.cholesky_solve(B) assert A.pinv_solve(B) == A.LDLsolve(B) assert A.pinv_solve(B) == Matrix([sympify('-43/26'), sympify('71/26')]) assert A * A.pinv() * B == B # Fully determined, with two-dimensional B matrix. B = Matrix([[12, 13, 14], [15, 16, 17]]) assert A.pinv_solve(B) == A.cholesky_solve(B) assert A.pinv_solve(B) == A.LDLsolve(B) assert A.pinv_solve(B) == Matrix([[-33, -37, -41], [69, 75, 81]]) / 26 assert A * A.pinv() * B == B # Underdetermined system (infinite results). A = Matrix([[1, 0, 1], [0, 1, 1]]) B = Matrix([5, 7]) solution = A.pinv_solve(B) w = {} for s in solution.atoms(Symbol): # Extract dummy symbols used in the solution. w[s.name] = s assert solution == Matrix([[w['w0_0']/3 + w['w1_0']/3 - w['w2_0']/3 + 1], [w['w0_0']/3 + w['w1_0']/3 - w['w2_0']/3 + 3], [-w['w0_0']/3 - w['w1_0']/3 + w['w2_0']/3 + 4]]) assert A * A.pinv() * B == B # Overdetermined system (least squares results). A = Matrix([[1, 0], [0, 0], [0, 1]]) B = Matrix([3, 2, 1]) assert A.pinv_solve(B) == Matrix([3, 1]) # Proof the solution is not exact. assert A * A.pinv() * B != B def test_pinv_rank_deficient(): # Test the four properties of the pseudoinverse for various matrices. As = [Matrix([[1, 1, 1], [2, 2, 2]]), Matrix([[1, 0], [0, 0]]), Matrix([[1, 2], [2, 4], [3, 6]])] for A in As: A_pinv = A.pinv(method="RD") AAp = A * A_pinv ApA = A_pinv * A assert simplify(AAp * A) == A assert simplify(ApA * A_pinv) == A_pinv assert AAp.H == AAp assert ApA.H == ApA for A in As: A_pinv = A.pinv(method="ED") AAp = A * A_pinv ApA = A_pinv * A assert simplify(AAp * A) == A assert simplify(ApA * A_pinv) == A_pinv assert AAp.H == AAp assert ApA.H == ApA # Test solving with rank-deficient matrices. A = Matrix([[1, 0], [0, 0]]) # Exact, non-unique solution. B = Matrix([3, 0]) solution = A.pinv_solve(B) w1 = solution.atoms(Symbol).pop() assert w1.name == 'w1_0' assert solution == Matrix([3, w1]) assert A * A.pinv() * B == B # Least squares, non-unique solution. B = Matrix([3, 1]) solution = A.pinv_solve(B) w1 = solution.atoms(Symbol).pop() assert w1.name == 'w1_0' assert solution == Matrix([3, w1]) assert A * A.pinv() * B != B def test_gauss_jordan_solve(): # Square, full rank, unique solution A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) b = Matrix([3, 6, 9]) sol, params = A.gauss_jordan_solve(b) assert sol == Matrix([[-1], [2], [0]]) assert params == Matrix(0, 1, []) # Square, full rank, unique solution, B has more columns than rows A = eye(3) B = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) sol, params = A.gauss_jordan_solve(B) assert sol == B assert params == Matrix(0, 4, []) # Square, reduced rank, parametrized solution A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) b = Matrix([3, 6, 9]) sol, params, freevar = A.gauss_jordan_solve(b, freevar=True) w = {} for s in sol.atoms(Symbol): # Extract dummy symbols used in the solution. w[s.name] = s assert sol == Matrix([[w['tau0'] - 1], [-2*w['tau0'] + 2], [w['tau0']]]) assert params == Matrix([[w['tau0']]]) assert freevar == [2] # Square, reduced rank, parametrized solution, B has two columns A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) B = Matrix([[3, 4], [6, 8], [9, 12]]) sol, params, freevar = A.gauss_jordan_solve(B, freevar=True) w = {} for s in sol.atoms(Symbol): # Extract dummy symbols used in the solution. w[s.name] = s assert sol == Matrix([[w['tau0'] - 1, w['tau1'] - Rational(4, 3)], [-2*w['tau0'] + 2, -2*w['tau1'] + Rational(8, 3)], [w['tau0'], w['tau1']],]) assert params == Matrix([[w['tau0'], w['tau1']]]) assert freevar == [2] # Square, reduced rank, parametrized solution A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]]) b = Matrix([0, 0, 0]) sol, params = A.gauss_jordan_solve(b) w = {} for s in sol.atoms(Symbol): w[s.name] = s assert sol == Matrix([[-2*w['tau0'] - 3*w['tau1']], [w['tau0']], [w['tau1']]]) assert params == Matrix([[w['tau0']], [w['tau1']]]) # Square, reduced rank, parametrized solution A = Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) b = Matrix([0, 0, 0]) sol, params = A.gauss_jordan_solve(b) w = {} for s in sol.atoms(Symbol): w[s.name] = s assert sol == Matrix([[w['tau0']], [w['tau1']], [w['tau2']]]) assert params == Matrix([[w['tau0']], [w['tau1']], [w['tau2']]]) # Square, reduced rank, no solution A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]]) b = Matrix([0, 0, 1]) raises(ValueError, lambda: A.gauss_jordan_solve(b)) # Rectangular, tall, full rank, unique solution A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]]) b = Matrix([0, 0, 1, 0]) sol, params = A.gauss_jordan_solve(b) assert sol == Matrix([[Rational(-1, 2)], [0], [Rational(1, 6)]]) assert params == Matrix(0, 1, []) # Rectangular, tall, full rank, unique solution, B has less columns than rows A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]]) B = Matrix([[0,0], [0, 0], [1, 2], [0, 0]]) sol, params = A.gauss_jordan_solve(B) assert sol == Matrix([[Rational(-1, 2), Rational(-2, 2)], [0, 0], [Rational(1, 6), Rational(2, 6)]]) assert params == Matrix(0, 2, []) # Rectangular, tall, full rank, no solution A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]]) b = Matrix([0, 0, 0, 1]) raises(ValueError, lambda: A.gauss_jordan_solve(b)) # Rectangular, tall, full rank, no solution, B has two columns (2nd has no solution) A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]]) B = Matrix([[0,0], [0, 0], [1, 0], [0, 1]]) raises(ValueError, lambda: A.gauss_jordan_solve(B)) # Rectangular, tall, full rank, no solution, B has two columns (1st has no solution) A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]]) B = Matrix([[0,0], [0, 0], [0, 1], [1, 0]]) raises(ValueError, lambda: A.gauss_jordan_solve(B)) # Rectangular, tall, reduced rank, parametrized solution A = Matrix([[1, 5, 3], [2, 10, 6], [3, 15, 9], [1, 4, 3]]) b = Matrix([0, 0, 0, 1]) sol, params = A.gauss_jordan_solve(b) w = {} for s in sol.atoms(Symbol): w[s.name] = s assert sol == Matrix([[-3*w['tau0'] + 5], [-1], [w['tau0']]]) assert params == Matrix([[w['tau0']]]) # Rectangular, tall, reduced rank, no solution A = Matrix([[1, 5, 3], [2, 10, 6], [3, 15, 9], [1, 4, 3]]) b = Matrix([0, 0, 1, 1]) raises(ValueError, lambda: A.gauss_jordan_solve(b)) # Rectangular, wide, full rank, parametrized solution A = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 1, 12]]) b = Matrix([1, 1, 1]) sol, params = A.gauss_jordan_solve(b) w = {} for s in sol.atoms(Symbol): w[s.name] = s assert sol == Matrix([[2*w['tau0'] - 1], [-3*w['tau0'] + 1], [0], [w['tau0']]]) assert params == Matrix([[w['tau0']]]) # Rectangular, wide, reduced rank, parametrized solution A = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [2, 4, 6, 8]]) b = Matrix([0, 1, 0]) sol, params = A.gauss_jordan_solve(b) w = {} for s in sol.atoms(Symbol): w[s.name] = s assert sol == Matrix([[w['tau0'] + 2*w['tau1'] + S.Half], [-2*w['tau0'] - 3*w['tau1'] - Rational(1, 4)], [w['tau0']], [w['tau1']]]) assert params == Matrix([[w['tau0']], [w['tau1']]]) # watch out for clashing symbols x0, x1, x2, _x0 = symbols('_tau0 _tau1 _tau2 tau1') M = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]]) A = M[:, :-1] b = M[:, -1:] sol, params = A.gauss_jordan_solve(b) assert params == Matrix(3, 1, [x0, x1, x2]) assert sol == Matrix(5, 1, [x0, 0, x1, _x0, x2]) # Rectangular, wide, reduced rank, no solution A = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [2, 4, 6, 8]]) b = Matrix([1, 1, 1]) raises(ValueError, lambda: A.gauss_jordan_solve(b)) # Test for immutable matrix A = ImmutableMatrix([[1, 0], [0, 1]]) B = ImmutableMatrix([1, 2]) sol, params = A.gauss_jordan_solve(B) assert sol == ImmutableMatrix([1, 2]) assert params == ImmutableMatrix(0, 1, []) assert sol.__class__ == ImmutableDenseMatrix assert params.__class__ == ImmutableDenseMatrix # Test placement of free variables A = Matrix([[1, 0, 0, 0], [0, 0, 0, 1]]) b = Matrix([1, 1]) sol, params = A.gauss_jordan_solve(b) w = {} for s in sol.atoms(Symbol): w[s.name] = s assert sol == Matrix([[1], [w['tau0']], [w['tau1']], [1]]) assert params == Matrix([[w['tau0']], [w['tau1']]]) def test_issue_19815(): #Test placement of free variables as per issue 19815 A = Matrix([[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]]) B = Matrix([1, 2, 1, 1, 1, 1, 1, 2]) sol, params = A.gauss_jordan_solve(B) w = {} for s in sol.atoms(Symbol): w[s.name] = s assert params == Matrix([[w['tau0']], [w['tau1']], [w['tau2']], [w['tau3']], [w['tau4']], [w['tau5']]]) assert sol == Matrix([[1 - 1*w['tau2']], [w['tau2']], [1 - 1*w['tau0'] + w['tau1']], [w['tau0']], [w['tau3'] + w['tau4']], [-1*w['tau3'] - 1*w['tau4'] - 1*w['tau1']], [1 - 1*w['tau2']], [w['tau1']], [w['tau2']], [w['tau3']], [w['tau4']], [1 - 1*w['tau5']], [w['tau5']], [1]]) def test_solve(): A = Matrix([[1,2], [2,4]]) b = Matrix([[3], [4]]) raises(ValueError, lambda: A.solve(b)) #no solution b = Matrix([[ 4], [8]]) raises(ValueError, lambda: A.solve(b)) #infinite solution
2a157c28352c5a779d7aec742922433f11b26f60373f6560aecf20f6a7ff77a0
from sympy.assumptions import Q from sympy.core.expr import Expr from sympy.core.add import Add from sympy.core.function import Function from sympy.core.numbers import I, Integer, oo, pi, Rational from sympy.core.singleton import S from sympy.core.symbol import Symbol, symbols from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import cos, sin from sympy.matrices.common import (ShapeError, NonSquareMatrixError, _MinimalMatrix, _CastableMatrix, MatrixShaping, MatrixProperties, MatrixOperations, MatrixArithmetic, MatrixSpecial) from sympy.matrices.matrices import MatrixCalculus from sympy.matrices import (Matrix, diag, eye, matrix_multiply_elementwise, ones, zeros, SparseMatrix, banded, MutableDenseMatrix, MutableSparseMatrix, ImmutableDenseMatrix, ImmutableSparseMatrix) from sympy.polys.polytools import Poly from sympy.utilities.iterables import flatten from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy from sympy.abc import x, y, z # classes to test the basic matrix classes class ShapingOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixShaping): pass def eye_Shaping(n): return ShapingOnlyMatrix(n, n, lambda i, j: int(i == j)) def zeros_Shaping(n): return ShapingOnlyMatrix(n, n, lambda i, j: 0) class PropertiesOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixProperties): pass def eye_Properties(n): return PropertiesOnlyMatrix(n, n, lambda i, j: int(i == j)) def zeros_Properties(n): return PropertiesOnlyMatrix(n, n, lambda i, j: 0) class OperationsOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixOperations): pass def eye_Operations(n): return OperationsOnlyMatrix(n, n, lambda i, j: int(i == j)) def zeros_Operations(n): return OperationsOnlyMatrix(n, n, lambda i, j: 0) class ArithmeticOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixArithmetic): pass def eye_Arithmetic(n): return ArithmeticOnlyMatrix(n, n, lambda i, j: int(i == j)) def zeros_Arithmetic(n): return ArithmeticOnlyMatrix(n, n, lambda i, j: 0) class SpecialOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixSpecial): pass class CalculusOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixCalculus): pass def test__MinimalMatrix(): x = _MinimalMatrix(2, 3, [1, 2, 3, 4, 5, 6]) assert x.rows == 2 assert x.cols == 3 assert x[2] == 3 assert x[1, 1] == 5 assert list(x) == [1, 2, 3, 4, 5, 6] assert list(x[1, :]) == [4, 5, 6] assert list(x[:, 1]) == [2, 5] assert list(x[:, :]) == list(x) assert x[:, :] == x assert _MinimalMatrix(x) == x assert _MinimalMatrix([[1, 2, 3], [4, 5, 6]]) == x assert _MinimalMatrix(([1, 2, 3], [4, 5, 6])) == x assert _MinimalMatrix([(1, 2, 3), (4, 5, 6)]) == x assert _MinimalMatrix(((1, 2, 3), (4, 5, 6))) == x assert not (_MinimalMatrix([[1, 2], [3, 4], [5, 6]]) == x) # ShapingOnlyMatrix tests def test_vec(): m = ShapingOnlyMatrix(2, 2, [1, 3, 2, 4]) m_vec = m.vec() assert m_vec.cols == 1 for i in range(4): assert m_vec[i] == i + 1 def test_todok(): a, b, c, d = symbols('a:d') m1 = MutableDenseMatrix([[a, b], [c, d]]) m2 = ImmutableDenseMatrix([[a, b], [c, d]]) m3 = MutableSparseMatrix([[a, b], [c, d]]) m4 = ImmutableSparseMatrix([[a, b], [c, d]]) assert m1.todok() == m2.todok() == m3.todok() == m4.todok() == \ {(0, 0): a, (0, 1): b, (1, 0): c, (1, 1): d} def test_tolist(): lst = [[S.One, S.Half, x*y, S.Zero], [x, y, z, x**2], [y, -S.One, z*x, 3]] flat_lst = [S.One, S.Half, x*y, S.Zero, x, y, z, x**2, y, -S.One, z*x, 3] m = ShapingOnlyMatrix(3, 4, flat_lst) assert m.tolist() == lst def test_row_col_del(): e = ShapingOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9]) raises(IndexError, lambda: e.row_del(5)) raises(IndexError, lambda: e.row_del(-5)) raises(IndexError, lambda: e.col_del(5)) raises(IndexError, lambda: e.col_del(-5)) assert e.row_del(2) == e.row_del(-1) == Matrix([[1, 2, 3], [4, 5, 6]]) assert e.col_del(2) == e.col_del(-1) == Matrix([[1, 2], [4, 5], [7, 8]]) assert e.row_del(1) == e.row_del(-2) == Matrix([[1, 2, 3], [7, 8, 9]]) assert e.col_del(1) == e.col_del(-2) == Matrix([[1, 3], [4, 6], [7, 9]]) def test_get_diag_blocks1(): a = Matrix([[1, 2], [2, 3]]) b = Matrix([[3, x], [y, 3]]) c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]]) assert a.get_diag_blocks() == [a] assert b.get_diag_blocks() == [b] assert c.get_diag_blocks() == [c] def test_get_diag_blocks2(): a = Matrix([[1, 2], [2, 3]]) b = Matrix([[3, x], [y, 3]]) c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]]) A, B, C, D = diag(a, b, b), diag(a, b, c), diag(a, c, b), diag(c, c, b) A = ShapingOnlyMatrix(A.rows, A.cols, A) B = ShapingOnlyMatrix(B.rows, B.cols, B) C = ShapingOnlyMatrix(C.rows, C.cols, C) D = ShapingOnlyMatrix(D.rows, D.cols, D) assert A.get_diag_blocks() == [a, b, b] assert B.get_diag_blocks() == [a, b, c] assert C.get_diag_blocks() == [a, c, b] assert D.get_diag_blocks() == [c, c, b] def test_shape(): m = ShapingOnlyMatrix(1, 2, [0, 0]) m.shape == (1, 2) def test_reshape(): m0 = eye_Shaping(3) assert m0.reshape(1, 9) == Matrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1)) m1 = ShapingOnlyMatrix(3, 4, lambda i, j: i + j) assert m1.reshape( 4, 3) == Matrix(((0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5))) assert m1.reshape(2, 6) == Matrix(((0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5))) def test_row_col(): m = ShapingOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9]) assert m.row(0) == Matrix(1, 3, [1, 2, 3]) assert m.col(0) == Matrix(3, 1, [1, 4, 7]) def test_row_join(): assert eye_Shaping(3).row_join(Matrix([7, 7, 7])) == \ Matrix([[1, 0, 0, 7], [0, 1, 0, 7], [0, 0, 1, 7]]) def test_col_join(): assert eye_Shaping(3).col_join(Matrix([[7, 7, 7]])) == \ Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1], [7, 7, 7]]) def test_row_insert(): r4 = Matrix([[4, 4, 4]]) for i in range(-4, 5): l = [1, 0, 0] l.insert(i, 4) assert flatten(eye_Shaping(3).row_insert(i, r4).col(0).tolist()) == l def test_col_insert(): c4 = Matrix([4, 4, 4]) for i in range(-4, 5): l = [0, 0, 0] l.insert(i, 4) assert flatten(zeros_Shaping(3).col_insert(i, c4).row(0).tolist()) == l # issue 13643 assert eye_Shaping(6).col_insert(3, Matrix([[2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2]])) == \ Matrix([[1, 0, 0, 2, 2, 0, 0, 0], [0, 1, 0, 2, 2, 0, 0, 0], [0, 0, 1, 2, 2, 0, 0, 0], [0, 0, 0, 2, 2, 1, 0, 0], [0, 0, 0, 2, 2, 0, 1, 0], [0, 0, 0, 2, 2, 0, 0, 1]]) def test_extract(): m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j) assert m.extract([0, 1, 3], [0, 1]) == Matrix(3, 2, [0, 1, 3, 4, 9, 10]) assert m.extract([0, 3], [0, 0, 2]) == Matrix(2, 3, [0, 0, 2, 9, 9, 11]) assert m.extract(range(4), range(3)) == m raises(IndexError, lambda: m.extract([4], [0])) raises(IndexError, lambda: m.extract([0], [3])) def test_hstack(): m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j) m2 = ShapingOnlyMatrix(3, 4, lambda i, j: i*3 + j) assert m == m.hstack(m) assert m.hstack(m, m, m) == ShapingOnlyMatrix.hstack(m, m, m) == Matrix([ [0, 1, 2, 0, 1, 2, 0, 1, 2], [3, 4, 5, 3, 4, 5, 3, 4, 5], [6, 7, 8, 6, 7, 8, 6, 7, 8], [9, 10, 11, 9, 10, 11, 9, 10, 11]]) raises(ShapeError, lambda: m.hstack(m, m2)) assert Matrix.hstack() == Matrix() # test regression #12938 M1 = Matrix.zeros(0, 0) M2 = Matrix.zeros(0, 1) M3 = Matrix.zeros(0, 2) M4 = Matrix.zeros(0, 3) m = ShapingOnlyMatrix.hstack(M1, M2, M3, M4) assert m.rows == 0 and m.cols == 6 def test_vstack(): m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j) m2 = ShapingOnlyMatrix(3, 4, lambda i, j: i*3 + j) assert m == m.vstack(m) assert m.vstack(m, m, m) == ShapingOnlyMatrix.vstack(m, m, m) == Matrix([ [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]) raises(ShapeError, lambda: m.vstack(m, m2)) assert Matrix.vstack() == Matrix() # PropertiesOnlyMatrix tests def test_atoms(): m = PropertiesOnlyMatrix(2, 2, [1, 2, x, 1 - 1/x]) assert m.atoms() == {S.One, S(2), S.NegativeOne, x} assert m.atoms(Symbol) == {x} def test_free_symbols(): assert PropertiesOnlyMatrix([[x], [0]]).free_symbols == {x} def test_has(): A = PropertiesOnlyMatrix(((x, y), (2, 3))) assert A.has(x) assert not A.has(z) assert A.has(Symbol) A = PropertiesOnlyMatrix(((2, y), (2, 3))) assert not A.has(x) def test_is_anti_symmetric(): x = symbols('x') assert PropertiesOnlyMatrix(2, 1, [1, 2]).is_anti_symmetric() is False m = PropertiesOnlyMatrix(3, 3, [0, x**2 + 2*x + 1, y, -(x + 1)**2, 0, x*y, -y, -x*y, 0]) assert m.is_anti_symmetric() is True assert m.is_anti_symmetric(simplify=False) is False assert m.is_anti_symmetric(simplify=lambda x: x) is False m = PropertiesOnlyMatrix(3, 3, [x.expand() for x in m]) assert m.is_anti_symmetric(simplify=False) is True m = PropertiesOnlyMatrix(3, 3, [x.expand() for x in [S.One] + list(m)[1:]]) assert m.is_anti_symmetric() is False def test_diagonal_symmetrical(): m = PropertiesOnlyMatrix(2, 2, [0, 1, 1, 0]) assert not m.is_diagonal() assert m.is_symmetric() assert m.is_symmetric(simplify=False) m = PropertiesOnlyMatrix(2, 2, [1, 0, 0, 1]) assert m.is_diagonal() m = PropertiesOnlyMatrix(3, 3, diag(1, 2, 3)) assert m.is_diagonal() assert m.is_symmetric() m = PropertiesOnlyMatrix(3, 3, [1, 0, 0, 0, 2, 0, 0, 0, 3]) assert m == diag(1, 2, 3) m = PropertiesOnlyMatrix(2, 3, zeros(2, 3)) assert not m.is_symmetric() assert m.is_diagonal() m = PropertiesOnlyMatrix(((5, 0), (0, 6), (0, 0))) assert m.is_diagonal() m = PropertiesOnlyMatrix(((5, 0, 0), (0, 6, 0))) assert m.is_diagonal() m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3]) assert m.is_symmetric() assert not m.is_symmetric(simplify=False) assert m.expand().is_symmetric(simplify=False) def test_is_hermitian(): a = PropertiesOnlyMatrix([[1, I], [-I, 1]]) assert a.is_hermitian a = PropertiesOnlyMatrix([[2*I, I], [-I, 1]]) assert a.is_hermitian is False a = PropertiesOnlyMatrix([[x, I], [-I, 1]]) assert a.is_hermitian is None a = PropertiesOnlyMatrix([[x, 1], [-I, 1]]) assert a.is_hermitian is False def test_is_Identity(): assert eye_Properties(3).is_Identity assert not PropertiesOnlyMatrix(zeros(3)).is_Identity assert not PropertiesOnlyMatrix(ones(3)).is_Identity # issue 6242 assert not PropertiesOnlyMatrix([[1, 0, 0]]).is_Identity def test_is_symbolic(): a = PropertiesOnlyMatrix([[x, x], [x, x]]) assert a.is_symbolic() is True a = PropertiesOnlyMatrix([[1, 2, 3, 4], [5, 6, 7, 8]]) assert a.is_symbolic() is False a = PropertiesOnlyMatrix([[1, 2, 3, 4], [5, 6, x, 8]]) assert a.is_symbolic() is True a = PropertiesOnlyMatrix([[1, x, 3]]) assert a.is_symbolic() is True a = PropertiesOnlyMatrix([[1, 2, 3]]) assert a.is_symbolic() is False a = PropertiesOnlyMatrix([[1], [x], [3]]) assert a.is_symbolic() is True a = PropertiesOnlyMatrix([[1], [2], [3]]) assert a.is_symbolic() is False def test_is_upper(): a = PropertiesOnlyMatrix([[1, 2, 3]]) assert a.is_upper is True a = PropertiesOnlyMatrix([[1], [2], [3]]) assert a.is_upper is False def test_is_lower(): a = PropertiesOnlyMatrix([[1, 2, 3]]) assert a.is_lower is False a = PropertiesOnlyMatrix([[1], [2], [3]]) assert a.is_lower is True def test_is_square(): m = PropertiesOnlyMatrix([[1], [1]]) m2 = PropertiesOnlyMatrix([[2, 2], [2, 2]]) assert not m.is_square assert m2.is_square def test_is_symmetric(): m = PropertiesOnlyMatrix(2, 2, [0, 1, 1, 0]) assert m.is_symmetric() m = PropertiesOnlyMatrix(2, 2, [0, 1, 0, 1]) assert not m.is_symmetric() def test_is_hessenberg(): A = PropertiesOnlyMatrix([[3, 4, 1], [2, 4, 5], [0, 1, 2]]) assert A.is_upper_hessenberg A = PropertiesOnlyMatrix(3, 3, [3, 2, 0, 4, 4, 1, 1, 5, 2]) assert A.is_lower_hessenberg A = PropertiesOnlyMatrix(3, 3, [3, 2, -1, 4, 4, 1, 1, 5, 2]) assert A.is_lower_hessenberg is False assert A.is_upper_hessenberg is False A = PropertiesOnlyMatrix([[3, 4, 1], [2, 4, 5], [3, 1, 2]]) assert not A.is_upper_hessenberg def test_is_zero(): assert PropertiesOnlyMatrix(0, 0, []).is_zero_matrix assert PropertiesOnlyMatrix([[0, 0], [0, 0]]).is_zero_matrix assert PropertiesOnlyMatrix(zeros(3, 4)).is_zero_matrix assert not PropertiesOnlyMatrix(eye(3)).is_zero_matrix assert PropertiesOnlyMatrix([[x, 0], [0, 0]]).is_zero_matrix == None assert PropertiesOnlyMatrix([[x, 1], [0, 0]]).is_zero_matrix == False a = Symbol('a', nonzero=True) assert PropertiesOnlyMatrix([[a, 0], [0, 0]]).is_zero_matrix == False def test_values(): assert set(PropertiesOnlyMatrix(2, 2, [0, 1, 2, 3] ).values()) == {1, 2, 3} x = Symbol('x', real=True) assert set(PropertiesOnlyMatrix(2, 2, [x, 0, 0, 1] ).values()) == {x, 1} # OperationsOnlyMatrix tests def test_applyfunc(): m0 = OperationsOnlyMatrix(eye(3)) assert m0.applyfunc(lambda x: 2*x) == eye(3)*2 assert m0.applyfunc(lambda x: 0) == zeros(3) assert m0.applyfunc(lambda x: 1) == ones(3) def test_adjoint(): dat = [[0, I], [1, 0]] ans = OperationsOnlyMatrix([[0, 1], [-I, 0]]) assert ans.adjoint() == Matrix(dat) def test_as_real_imag(): m1 = OperationsOnlyMatrix(2, 2, [1, 2, 3, 4]) m3 = OperationsOnlyMatrix(2, 2, [1 + S.ImaginaryUnit, 2 + 2*S.ImaginaryUnit, 3 + 3*S.ImaginaryUnit, 4 + 4*S.ImaginaryUnit]) a, b = m3.as_real_imag() assert a == m1 assert b == m1 def test_conjugate(): M = OperationsOnlyMatrix([[0, I, 5], [1, 2, 0]]) assert M.T == Matrix([[0, 1], [I, 2], [5, 0]]) assert M.C == Matrix([[0, -I, 5], [1, 2, 0]]) assert M.C == M.conjugate() assert M.H == M.T.C assert M.H == Matrix([[ 0, 1], [-I, 2], [ 5, 0]]) def test_doit(): a = OperationsOnlyMatrix([[Add(x, x, evaluate=False)]]) assert a[0] != 2*x assert a.doit() == Matrix([[2*x]]) def test_evalf(): a = OperationsOnlyMatrix(2, 1, [sqrt(5), 6]) assert all(a.evalf()[i] == a[i].evalf() for i in range(2)) assert all(a.evalf(2)[i] == a[i].evalf(2) for i in range(2)) assert all(a.n(2)[i] == a[i].n(2) for i in range(2)) def test_expand(): m0 = OperationsOnlyMatrix([[x*(x + y), 2], [((x + y)*y)*x, x*(y + x*(x + y))]]) # Test if expand() returns a matrix m1 = m0.expand() assert m1 == Matrix( [[x*y + x**2, 2], [x*y**2 + y*x**2, x*y + y*x**2 + x**3]]) a = Symbol('a', real=True) assert OperationsOnlyMatrix(1, 1, [exp(I*a)]).expand(complex=True) == \ Matrix([cos(a) + I*sin(a)]) def test_refine(): m0 = OperationsOnlyMatrix([[Abs(x)**2, sqrt(x**2)], [sqrt(x**2)*Abs(y)**2, sqrt(y**2)*Abs(x)**2]]) m1 = m0.refine(Q.real(x) & Q.real(y)) assert m1 == Matrix([[x**2, Abs(x)], [y**2*Abs(x), x**2*Abs(y)]]) m1 = m0.refine(Q.positive(x) & Q.positive(y)) assert m1 == Matrix([[x**2, x], [x*y**2, x**2*y]]) m1 = m0.refine(Q.negative(x) & Q.negative(y)) assert m1 == Matrix([[x**2, -x], [-x*y**2, -x**2*y]]) def test_replace(): F, G = symbols('F, G', cls=Function) K = OperationsOnlyMatrix(2, 2, lambda i, j: G(i+j)) M = OperationsOnlyMatrix(2, 2, lambda i, j: F(i+j)) N = M.replace(F, G) assert N == K def test_replace_map(): F, G = symbols('F, G', cls=Function) K = OperationsOnlyMatrix(2, 2, [(G(0), {F(0): G(0)}), (G(1), {F(1): G(1)}), (G(1), {F(1) \ : G(1)}), (G(2), {F(2): G(2)})]) M = OperationsOnlyMatrix(2, 2, lambda i, j: F(i+j)) N = M.replace(F, G, True) assert N == K def test_rot90(): A = Matrix([[1, 2], [3, 4]]) assert A == A.rot90(0) == A.rot90(4) assert A.rot90(2) == A.rot90(-2) == A.rot90(6) == Matrix(((4, 3), (2, 1))) assert A.rot90(3) == A.rot90(-1) == A.rot90(7) == Matrix(((2, 4), (1, 3))) assert A.rot90() == A.rot90(-7) == A.rot90(-3) == Matrix(((3, 1), (4, 2))) def test_simplify(): n = Symbol('n') f = Function('f') M = OperationsOnlyMatrix([[ 1/x + 1/y, (x + x*y) / x ], [ (f(x) + y*f(x))/f(x), 2 * (1/n - cos(n * pi)/n) / pi ]]) assert M.simplify() == Matrix([[ (x + y)/(x * y), 1 + y ], [ 1 + y, 2*((1 - 1*cos(pi*n))/(pi*n)) ]]) eq = (1 + x)**2 M = OperationsOnlyMatrix([[eq]]) assert M.simplify() == Matrix([[eq]]) assert M.simplify(ratio=oo) == Matrix([[eq.simplify(ratio=oo)]]) def test_subs(): assert OperationsOnlyMatrix([[1, x], [x, 4]]).subs(x, 5) == Matrix([[1, 5], [5, 4]]) assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs([[x, -1], [y, -2]]) == \ Matrix([[-1, 2], [-3, 4]]) assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs([(x, -1), (y, -2)]) == \ Matrix([[-1, 2], [-3, 4]]) assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs({x: -1, y: -2}) == \ Matrix([[-1, 2], [-3, 4]]) assert OperationsOnlyMatrix([[x*y]]).subs({x: y - 1, y: x - 1}, simultaneous=True) == \ Matrix([[(x - 1)*(y - 1)]]) def test_trace(): M = OperationsOnlyMatrix([[1, 0, 0], [0, 5, 0], [0, 0, 8]]) assert M.trace() == 14 def test_xreplace(): assert OperationsOnlyMatrix([[1, x], [x, 4]]).xreplace({x: 5}) == \ Matrix([[1, 5], [5, 4]]) assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).xreplace({x: -1, y: -2}) == \ Matrix([[-1, 2], [-3, 4]]) def test_permute(): a = OperationsOnlyMatrix(3, 4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) raises(IndexError, lambda: a.permute([[0, 5]])) raises(ValueError, lambda: a.permute(Symbol('x'))) b = a.permute_rows([[0, 2], [0, 1]]) assert a.permute([[0, 2], [0, 1]]) == b == Matrix([ [5, 6, 7, 8], [9, 10, 11, 12], [1, 2, 3, 4]]) b = a.permute_cols([[0, 2], [0, 1]]) assert a.permute([[0, 2], [0, 1]], orientation='cols') == b ==\ Matrix([ [ 2, 3, 1, 4], [ 6, 7, 5, 8], [10, 11, 9, 12]]) b = a.permute_cols([[0, 2], [0, 1]], direction='backward') assert a.permute([[0, 2], [0, 1]], orientation='cols', direction='backward') == b ==\ Matrix([ [ 3, 1, 2, 4], [ 7, 5, 6, 8], [11, 9, 10, 12]]) assert a.permute([1, 2, 0, 3]) == Matrix([ [5, 6, 7, 8], [9, 10, 11, 12], [1, 2, 3, 4]]) from sympy.combinatorics import Permutation assert a.permute(Permutation([1, 2, 0, 3])) == Matrix([ [5, 6, 7, 8], [9, 10, 11, 12], [1, 2, 3, 4]]) # ArithmeticOnlyMatrix tests def test_abs(): m = ArithmeticOnlyMatrix([[1, -2], [x, y]]) assert abs(m) == ArithmeticOnlyMatrix([[1, 2], [Abs(x), Abs(y)]]) def test_add(): m = ArithmeticOnlyMatrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]]) assert m + m == ArithmeticOnlyMatrix([[2, 4, 6], [2*x, 2*y, 2*x], [4*y, -100, 2*z*x]]) n = ArithmeticOnlyMatrix(1, 2, [1, 2]) raises(ShapeError, lambda: m + n) def test_multiplication(): a = ArithmeticOnlyMatrix(( (1, 2), (3, 1), (0, 6), )) b = ArithmeticOnlyMatrix(( (1, 2), (3, 0), )) raises(ShapeError, lambda: b*a) raises(TypeError, lambda: a*{}) c = a*b assert c[0, 0] == 7 assert c[0, 1] == 2 assert c[1, 0] == 6 assert c[1, 1] == 6 assert c[2, 0] == 18 assert c[2, 1] == 0 try: eval('c = a @ b') except SyntaxError: pass else: assert c[0, 0] == 7 assert c[0, 1] == 2 assert c[1, 0] == 6 assert c[1, 1] == 6 assert c[2, 0] == 18 assert c[2, 1] == 0 h = a.multiply_elementwise(c) assert h == matrix_multiply_elementwise(a, c) assert h[0, 0] == 7 assert h[0, 1] == 4 assert h[1, 0] == 18 assert h[1, 1] == 6 assert h[2, 0] == 0 assert h[2, 1] == 0 raises(ShapeError, lambda: a.multiply_elementwise(b)) c = b * Symbol("x") assert isinstance(c, ArithmeticOnlyMatrix) assert c[0, 0] == x assert c[0, 1] == 2*x assert c[1, 0] == 3*x assert c[1, 1] == 0 c2 = x * b assert c == c2 c = 5 * b assert isinstance(c, ArithmeticOnlyMatrix) assert c[0, 0] == 5 assert c[0, 1] == 2*5 assert c[1, 0] == 3*5 assert c[1, 1] == 0 try: eval('c = 5 @ b') except SyntaxError: pass else: assert isinstance(c, ArithmeticOnlyMatrix) assert c[0, 0] == 5 assert c[0, 1] == 2*5 assert c[1, 0] == 3*5 assert c[1, 1] == 0 def test_matmul(): a = Matrix([[1, 2], [3, 4]]) assert a.__matmul__(2) == NotImplemented assert a.__rmatmul__(2) == NotImplemented #This is done this way because @ is only supported in Python 3.5+ #To check 2@a case try: eval('2 @ a') except SyntaxError: pass except TypeError: #TypeError is raised in case of NotImplemented is returned pass #Check a@2 case try: eval('a @ 2') except SyntaxError: pass except TypeError: #TypeError is raised in case of NotImplemented is returned pass def test_non_matmul(): """ Test that if explicitly specified as non-matrix, mul reverts to scalar multiplication. """ class foo(Expr): is_Matrix=False is_MatrixLike=False shape = (1, 1) A = Matrix([[1, 2], [3, 4]]) b = foo() assert b*A == Matrix([[b, 2*b], [3*b, 4*b]]) assert A*b == Matrix([[b, 2*b], [3*b, 4*b]]) def test_power(): raises(NonSquareMatrixError, lambda: Matrix((1, 2))**2) A = ArithmeticOnlyMatrix([[2, 3], [4, 5]]) assert (A**5)[:] == (6140, 8097, 10796, 14237) A = ArithmeticOnlyMatrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]]) assert (A**3)[:] == (290, 262, 251, 448, 440, 368, 702, 954, 433) assert A**0 == eye(3) assert A**1 == A assert (ArithmeticOnlyMatrix([[2]]) ** 100)[0, 0] == 2**100 assert ArithmeticOnlyMatrix([[1, 2], [3, 4]])**Integer(2) == ArithmeticOnlyMatrix([[7, 10], [15, 22]]) A = Matrix([[1,2],[4,5]]) assert A.pow(20, method='cayley') == A.pow(20, method='multiply') def test_neg(): n = ArithmeticOnlyMatrix(1, 2, [1, 2]) assert -n == ArithmeticOnlyMatrix(1, 2, [-1, -2]) def test_sub(): n = ArithmeticOnlyMatrix(1, 2, [1, 2]) assert n - n == ArithmeticOnlyMatrix(1, 2, [0, 0]) def test_div(): n = ArithmeticOnlyMatrix(1, 2, [1, 2]) assert n/2 == ArithmeticOnlyMatrix(1, 2, [S.Half, S(2)/2]) # SpecialOnlyMatrix tests def test_eye(): assert list(SpecialOnlyMatrix.eye(2, 2)) == [1, 0, 0, 1] assert list(SpecialOnlyMatrix.eye(2)) == [1, 0, 0, 1] assert type(SpecialOnlyMatrix.eye(2)) == SpecialOnlyMatrix assert type(SpecialOnlyMatrix.eye(2, cls=Matrix)) == Matrix def test_ones(): assert list(SpecialOnlyMatrix.ones(2, 2)) == [1, 1, 1, 1] assert list(SpecialOnlyMatrix.ones(2)) == [1, 1, 1, 1] assert SpecialOnlyMatrix.ones(2, 3) == Matrix([[1, 1, 1], [1, 1, 1]]) assert type(SpecialOnlyMatrix.ones(2)) == SpecialOnlyMatrix assert type(SpecialOnlyMatrix.ones(2, cls=Matrix)) == Matrix def test_zeros(): assert list(SpecialOnlyMatrix.zeros(2, 2)) == [0, 0, 0, 0] assert list(SpecialOnlyMatrix.zeros(2)) == [0, 0, 0, 0] assert SpecialOnlyMatrix.zeros(2, 3) == Matrix([[0, 0, 0], [0, 0, 0]]) assert type(SpecialOnlyMatrix.zeros(2)) == SpecialOnlyMatrix assert type(SpecialOnlyMatrix.zeros(2, cls=Matrix)) == Matrix def test_diag_make(): diag = SpecialOnlyMatrix.diag a = Matrix([[1, 2], [2, 3]]) b = Matrix([[3, x], [y, 3]]) c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]]) assert diag(a, b, b) == Matrix([ [1, 2, 0, 0, 0, 0], [2, 3, 0, 0, 0, 0], [0, 0, 3, x, 0, 0], [0, 0, y, 3, 0, 0], [0, 0, 0, 0, 3, x], [0, 0, 0, 0, y, 3], ]) assert diag(a, b, c) == Matrix([ [1, 2, 0, 0, 0, 0, 0], [2, 3, 0, 0, 0, 0, 0], [0, 0, 3, x, 0, 0, 0], [0, 0, y, 3, 0, 0, 0], [0, 0, 0, 0, 3, x, 3], [0, 0, 0, 0, y, 3, z], [0, 0, 0, 0, x, y, z], ]) assert diag(a, c, b) == Matrix([ [1, 2, 0, 0, 0, 0, 0], [2, 3, 0, 0, 0, 0, 0], [0, 0, 3, x, 3, 0, 0], [0, 0, y, 3, z, 0, 0], [0, 0, x, y, z, 0, 0], [0, 0, 0, 0, 0, 3, x], [0, 0, 0, 0, 0, y, 3], ]) a = Matrix([x, y, z]) b = Matrix([[1, 2], [3, 4]]) c = Matrix([[5, 6]]) # this "wandering diagonal" is what makes this # a block diagonal where each block is independent # of the others assert diag(a, 7, b, c) == Matrix([ [x, 0, 0, 0, 0, 0], [y, 0, 0, 0, 0, 0], [z, 0, 0, 0, 0, 0], [0, 7, 0, 0, 0, 0], [0, 0, 1, 2, 0, 0], [0, 0, 3, 4, 0, 0], [0, 0, 0, 0, 5, 6]]) raises(ValueError, lambda: diag(a, 7, b, c, rows=5)) assert diag(1) == Matrix([[1]]) assert diag(1, rows=2) == Matrix([[1, 0], [0, 0]]) assert diag(1, cols=2) == Matrix([[1, 0], [0, 0]]) assert diag(1, rows=3, cols=2) == Matrix([[1, 0], [0, 0], [0, 0]]) assert diag(*[2, 3]) == Matrix([ [2, 0], [0, 3]]) assert diag(Matrix([2, 3])) == Matrix([ [2], [3]]) assert diag([1, [2, 3], 4], unpack=False) == \ diag([[1], [2, 3], [4]], unpack=False) == Matrix([ [1, 0], [2, 3], [4, 0]]) assert type(diag(1)) == SpecialOnlyMatrix assert type(diag(1, cls=Matrix)) == Matrix assert Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3) assert Matrix.diag([1, 2, 3], unpack=False).shape == (3, 1) assert Matrix.diag([[1, 2, 3]]).shape == (3, 1) assert Matrix.diag([[1, 2, 3]], unpack=False).shape == (1, 3) assert Matrix.diag([[[1, 2, 3]]]).shape == (1, 3) # kerning can be used to move the starting point assert Matrix.diag(ones(0, 2), 1, 2) == Matrix([ [0, 0, 1, 0], [0, 0, 0, 2]]) assert Matrix.diag(ones(2, 0), 1, 2) == Matrix([ [0, 0], [0, 0], [1, 0], [0, 2]]) def test_diagonal(): m = Matrix(3, 3, range(9)) d = m.diagonal() assert d == m.diagonal(0) assert tuple(d) == (0, 4, 8) assert tuple(m.diagonal(1)) == (1, 5) assert tuple(m.diagonal(-1)) == (3, 7) assert tuple(m.diagonal(2)) == (2,) assert type(m.diagonal()) == type(m) s = SparseMatrix(3, 3, {(1, 1): 1}) assert type(s.diagonal()) == type(s) assert type(m) != type(s) raises(ValueError, lambda: m.diagonal(3)) raises(ValueError, lambda: m.diagonal(-3)) raises(ValueError, lambda: m.diagonal(pi)) M = ones(2, 3) assert banded({i: list(M.diagonal(i)) for i in range(1-M.rows, M.cols)}) == M def test_jordan_block(): assert SpecialOnlyMatrix.jordan_block(3, 2) == SpecialOnlyMatrix.jordan_block(3, eigenvalue=2) \ == SpecialOnlyMatrix.jordan_block(size=3, eigenvalue=2) \ == SpecialOnlyMatrix.jordan_block(3, 2, band='upper') \ == SpecialOnlyMatrix.jordan_block( size=3, eigenval=2, eigenvalue=2) \ == Matrix([ [2, 1, 0], [0, 2, 1], [0, 0, 2]]) assert SpecialOnlyMatrix.jordan_block(3, 2, band='lower') == Matrix([ [2, 0, 0], [1, 2, 0], [0, 1, 2]]) # missing eigenvalue raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(2)) # non-integral size raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(3.5, 2)) # size not specified raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(eigenvalue=2)) # inconsistent eigenvalue raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block( eigenvalue=2, eigenval=4)) # Deprecated feature with warns_deprecated_sympy(): assert (SpecialOnlyMatrix.jordan_block(cols=3, eigenvalue=2) == SpecialOnlyMatrix(3, 3, (2, 1, 0, 0, 2, 1, 0, 0, 2))) with warns_deprecated_sympy(): assert (SpecialOnlyMatrix.jordan_block(rows=3, eigenvalue=2) == SpecialOnlyMatrix(3, 3, (2, 1, 0, 0, 2, 1, 0, 0, 2))) with warns_deprecated_sympy(): assert SpecialOnlyMatrix.jordan_block(3, 2) == \ SpecialOnlyMatrix.jordan_block(cols=3, eigenvalue=2) == \ SpecialOnlyMatrix.jordan_block(rows=3, eigenvalue=2) with warns_deprecated_sympy(): assert SpecialOnlyMatrix.jordan_block( rows=4, cols=3, eigenvalue=2) == \ Matrix([ [2, 1, 0], [0, 2, 1], [0, 0, 2], [0, 0, 0]]) # Using alias keyword assert SpecialOnlyMatrix.jordan_block(size=3, eigenvalue=2) == \ SpecialOnlyMatrix.jordan_block(size=3, eigenval=2) def test_orthogonalize(): m = Matrix([[1, 2], [3, 4]]) assert m.orthogonalize(Matrix([[2], [1]])) == [Matrix([[2], [1]])] assert m.orthogonalize(Matrix([[2], [1]]), normalize=True) == \ [Matrix([[2*sqrt(5)/5], [sqrt(5)/5]])] assert m.orthogonalize(Matrix([[1], [2]]), Matrix([[-1], [4]])) == \ [Matrix([[1], [2]]), Matrix([[Rational(-12, 5)], [Rational(6, 5)]])] assert m.orthogonalize(Matrix([[0], [0]]), Matrix([[-1], [4]])) == \ [Matrix([[-1], [4]])] assert m.orthogonalize(Matrix([[0], [0]])) == [] n = Matrix([[9, 1, 9], [3, 6, 10], [8, 5, 2]]) vecs = [Matrix([[-5], [1]]), Matrix([[-5], [2]]), Matrix([[-5], [-2]])] assert n.orthogonalize(*vecs) == \ [Matrix([[-5], [1]]), Matrix([[Rational(5, 26)], [Rational(25, 26)]])] vecs = [Matrix([0, 0, 0]), Matrix([1, 2, 3]), Matrix([1, 4, 5])] raises(ValueError, lambda: Matrix.orthogonalize(*vecs, rankcheck=True)) vecs = [Matrix([1, 2, 3]), Matrix([4, 5, 6]), Matrix([7, 8, 9])] raises(ValueError, lambda: Matrix.orthogonalize(*vecs, rankcheck=True)) # CalculusOnlyMatrix tests @XFAIL def test_diff(): x, y = symbols('x y') m = CalculusOnlyMatrix(2, 1, [x, y]) # TODO: currently not working as ``_MinimalMatrix`` cannot be sympified: assert m.diff(x) == Matrix(2, 1, [1, 0]) def test_integrate(): x, y = symbols('x y') m = CalculusOnlyMatrix(2, 1, [x, y]) assert m.integrate(x) == Matrix(2, 1, [x**2/2, y*x]) def test_jacobian2(): rho, phi = symbols("rho,phi") X = CalculusOnlyMatrix(3, 1, [rho*cos(phi), rho*sin(phi), rho**2]) Y = CalculusOnlyMatrix(2, 1, [rho, phi]) J = Matrix([ [cos(phi), -rho*sin(phi)], [sin(phi), rho*cos(phi)], [ 2*rho, 0], ]) assert X.jacobian(Y) == J m = CalculusOnlyMatrix(2, 2, [1, 2, 3, 4]) m2 = CalculusOnlyMatrix(4, 1, [1, 2, 3, 4]) raises(TypeError, lambda: m.jacobian(Matrix([1, 2]))) raises(TypeError, lambda: m2.jacobian(m)) def test_limit(): x, y = symbols('x y') m = CalculusOnlyMatrix(2, 1, [1/x, y]) assert m.limit(x, 5) == Matrix(2, 1, [Rational(1, 5), y]) def test_issue_13774(): M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) v = [1, 1, 1] raises(TypeError, lambda: M*v) raises(TypeError, lambda: v*M) def test_companion(): x = Symbol('x') y = Symbol('y') raises(ValueError, lambda: Matrix.companion(1)) raises(ValueError, lambda: Matrix.companion(Poly([1], x))) raises(ValueError, lambda: Matrix.companion(Poly([2, 1], x))) raises(ValueError, lambda: Matrix.companion(Poly(x*y, [x, y]))) c0, c1, c2 = symbols('c0:3') assert Matrix.companion(Poly([1, c0], x)) == Matrix([-c0]) assert Matrix.companion(Poly([1, c1, c0], x)) == \ Matrix([[0, -c0], [1, -c1]]) assert Matrix.companion(Poly([1, c2, c1, c0], x)) == \ Matrix([[0, 0, -c0], [1, 0, -c1], [0, 1, -c2]]) def test_issue_10589(): x, y, z = symbols("x, y z") M1 = Matrix([x, y, z]) M1 = M1.subs(zip([x, y, z], [1, 2, 3])) assert M1 == Matrix([[1], [2], [3]]) M2 = Matrix([[x, x, x, x, x], [x, x, x, x, x], [x, x, x, x, x]]) M2 = M2.subs(zip([x], [1])) assert M2 == Matrix([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]) def test_rmul_pr19860(): class Foo(ImmutableDenseMatrix): _op_priority = MutableDenseMatrix._op_priority + 0.01 a = Matrix(2, 2, [1, 2, 3, 4]) b = Foo(2, 2, [1, 2, 3, 4]) # This would throw a RecursionError: maximum recursion depth # since b always has higher priority even after a.as_mutable() c = a*b assert isinstance(c, Foo) assert c == Matrix([[7, 10], [15, 22]])
7d8dc6cc8113f2bc652f48ed3c19d41b2f29a881479f268d6d53d4000be745de
import random import concurrent.futures from sympy import ( Abs, Add, E, Float, I, Integer, Max, Min, Poly, Pow, PurePoly, Rational, S, Symbol, cos, exp, log, oo, pi, signsimp, simplify, sin, sqrt, symbols, sympify, trigsimp, tan, sstr, diff, Function, expand) from sympy.matrices.matrices import (ShapeError, MatrixError, NonSquareMatrixError, DeferredVector, _find_reasonable_pivot_naive, _simplify) from sympy.matrices import ( GramSchmidt, ImmutableMatrix, ImmutableSparseMatrix, Matrix, SparseMatrix, casoratian, diag, eye, hessian, matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2, rot_axis3, wronskian, zeros, MutableDenseMatrix, ImmutableDenseMatrix, MatrixSymbol, dotprodsimp) from sympy.matrices.utilities import _dotprodsimp_state from sympy.core.compatibility import iterable, Hashable from sympy.core import Tuple, Wild from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.utilities.iterables import flatten, capture from sympy.testing.pytest import raises, XFAIL, skip, warns_deprecated_sympy from sympy.assumptions import Q from sympy.tensor.array import Array from sympy.matrices.expressions import MatPow from sympy.abc import a, b, c, d, x, y, z, t # don't re-order this list classes = (Matrix, SparseMatrix, ImmutableMatrix, ImmutableSparseMatrix) def test_args(): for n, cls in enumerate(classes): m = cls.zeros(3, 2) # all should give back the same type of arguments, e.g. ints for shape assert m.shape == (3, 2) and all(type(i) is int for i in m.shape) assert m.rows == 3 and type(m.rows) is int assert m.cols == 2 and type(m.cols) is int if not n % 2: assert type(m._mat) in (list, tuple, Tuple) else: assert type(m._smat) is dict def test_division(): v = Matrix(1, 2, [x, y]) assert v/z == Matrix(1, 2, [x/z, y/z]) def test_sum(): m = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]]) assert m + m == Matrix([[2, 4, 6], [2*x, 2*y, 2*x], [4*y, -100, 2*z*x]]) n = Matrix(1, 2, [1, 2]) raises(ShapeError, lambda: m + n) def test_abs(): m = Matrix(1, 2, [-3, x]) n = Matrix(1, 2, [3, Abs(x)]) assert abs(m) == n def test_addition(): a = Matrix(( (1, 2), (3, 1), )) b = Matrix(( (1, 2), (3, 0), )) assert a + b == a.add(b) == Matrix([[2, 4], [6, 1]]) def test_fancy_index_matrix(): for M in (Matrix, SparseMatrix): a = M(3, 3, range(9)) assert a == a[:, :] assert a[1, :] == Matrix(1, 3, [3, 4, 5]) assert a[:, 1] == Matrix([1, 4, 7]) assert a[[0, 1], :] == Matrix([[0, 1, 2], [3, 4, 5]]) assert a[[0, 1], 2] == a[[0, 1], [2]] assert a[2, [0, 1]] == a[[2], [0, 1]] assert a[:, [0, 1]] == Matrix([[0, 1], [3, 4], [6, 7]]) assert a[0, 0] == 0 assert a[0:2, :] == Matrix([[0, 1, 2], [3, 4, 5]]) assert a[:, 0:2] == Matrix([[0, 1], [3, 4], [6, 7]]) assert a[::2, 1] == a[[0, 2], 1] assert a[1, ::2] == a[1, [0, 2]] a = M(3, 3, range(9)) assert a[[0, 2, 1, 2, 1], :] == Matrix([ [0, 1, 2], [6, 7, 8], [3, 4, 5], [6, 7, 8], [3, 4, 5]]) assert a[:, [0,2,1,2,1]] == Matrix([ [0, 2, 1, 2, 1], [3, 5, 4, 5, 4], [6, 8, 7, 8, 7]]) a = SparseMatrix.zeros(3) a[1, 2] = 2 a[0, 1] = 3 a[2, 0] = 4 assert a.extract([1, 1], [2]) == Matrix([ [2], [2]]) assert a.extract([1, 0], [2, 2, 2]) == Matrix([ [2, 2, 2], [0, 0, 0]]) assert a.extract([1, 0, 1, 2], [2, 0, 1, 0]) == Matrix([ [2, 0, 0, 0], [0, 0, 3, 0], [2, 0, 0, 0], [0, 4, 0, 4]]) def test_multiplication(): a = Matrix(( (1, 2), (3, 1), (0, 6), )) b = Matrix(( (1, 2), (3, 0), )) c = a*b assert c[0, 0] == 7 assert c[0, 1] == 2 assert c[1, 0] == 6 assert c[1, 1] == 6 assert c[2, 0] == 18 assert c[2, 1] == 0 try: eval('c = a @ b') except SyntaxError: pass else: assert c[0, 0] == 7 assert c[0, 1] == 2 assert c[1, 0] == 6 assert c[1, 1] == 6 assert c[2, 0] == 18 assert c[2, 1] == 0 h = matrix_multiply_elementwise(a, c) assert h == a.multiply_elementwise(c) assert h[0, 0] == 7 assert h[0, 1] == 4 assert h[1, 0] == 18 assert h[1, 1] == 6 assert h[2, 0] == 0 assert h[2, 1] == 0 raises(ShapeError, lambda: matrix_multiply_elementwise(a, b)) c = b * Symbol("x") assert isinstance(c, Matrix) assert c[0, 0] == x assert c[0, 1] == 2*x assert c[1, 0] == 3*x assert c[1, 1] == 0 c2 = x * b assert c == c2 c = 5 * b assert isinstance(c, Matrix) assert c[0, 0] == 5 assert c[0, 1] == 2*5 assert c[1, 0] == 3*5 assert c[1, 1] == 0 try: eval('c = 5 @ b') except SyntaxError: pass else: assert isinstance(c, Matrix) assert c[0, 0] == 5 assert c[0, 1] == 2*5 assert c[1, 0] == 3*5 assert c[1, 1] == 0 def test_power(): raises(NonSquareMatrixError, lambda: Matrix((1, 2))**2) R = Rational A = Matrix([[2, 3], [4, 5]]) assert (A**-3)[:] == [R(-269)/8, R(153)/8, R(51)/2, R(-29)/2] assert (A**5)[:] == [6140, 8097, 10796, 14237] A = Matrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]]) assert (A**3)[:] == [290, 262, 251, 448, 440, 368, 702, 954, 433] assert A**0 == eye(3) assert A**1 == A assert (Matrix([[2]]) ** 100)[0, 0] == 2**100 assert eye(2)**10000000 == eye(2) assert Matrix([[1, 2], [3, 4]])**Integer(2) == Matrix([[7, 10], [15, 22]]) A = Matrix([[33, 24], [48, 57]]) assert (A**S.Half)[:] == [5, 2, 4, 7] A = Matrix([[0, 4], [-1, 5]]) assert (A**S.Half)**2 == A assert Matrix([[1, 0], [1, 1]])**S.Half == Matrix([[1, 0], [S.Half, 1]]) assert Matrix([[1, 0], [1, 1]])**0.5 == Matrix([[1.0, 0], [0.5, 1.0]]) from sympy.abc import a, b, n assert Matrix([[1, a], [0, 1]])**n == Matrix([[1, a*n], [0, 1]]) assert Matrix([[b, a], [0, b]])**n == Matrix([[b**n, a*b**(n-1)*n], [0, b**n]]) assert Matrix([ [a**n, a**(n - 1)*n, (a**n*n**2 - a**n*n)/(2*a**2)], [ 0, a**n, a**(n - 1)*n], [ 0, 0, a**n]]) assert Matrix([[a, 1, 0], [0, a, 0], [0, 0, b]])**n == Matrix([ [a**n, a**(n-1)*n, 0], [0, a**n, 0], [0, 0, b**n]]) A = Matrix([[1, 0], [1, 7]]) assert A._matrix_pow_by_jordan_blocks(S(3)) == A._eval_pow_by_recursion(3) A = Matrix([[2]]) assert A**10 == Matrix([[2**10]]) == A._matrix_pow_by_jordan_blocks(S(10)) == \ A._eval_pow_by_recursion(10) # testing a matrix that cannot be jordan blocked issue 11766 m = Matrix([[3, 0, 0, 0, -3], [0, -3, -3, 0, 3], [0, 3, 0, 3, 0], [0, 0, 3, 0, 3], [3, 0, 0, 3, 0]]) raises(MatrixError, lambda: m._matrix_pow_by_jordan_blocks(S(10))) # test issue 11964 raises(MatrixError, lambda: Matrix([[1, 1], [3, 3]])._matrix_pow_by_jordan_blocks(S(-10))) A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 0]]) # Nilpotent jordan block size 3 assert A**10.0 == Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) raises(ValueError, lambda: A**2.1) raises(ValueError, lambda: A**Rational(3, 2)) A = Matrix([[8, 1], [3, 2]]) assert A**10.0 == Matrix([[1760744107, 272388050], [817164150, 126415807]]) A = Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]]) # Nilpotent jordan block size 1 assert A**10.0 == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]]) A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 1]]) # Nilpotent jordan block size 2 assert A**10.0 == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]]) n = Symbol('n', integer=True) assert isinstance(A**n, MatPow) n = Symbol('n', integer=True, negative=True) raises(ValueError, lambda: A**n) n = Symbol('n', integer=True, nonnegative=True) assert A**n == Matrix([ [KroneckerDelta(0, n), KroneckerDelta(1, n), -KroneckerDelta(0, n) - KroneckerDelta(1, n) + 1], [ 0, KroneckerDelta(0, n), 1 - KroneckerDelta(0, n)], [ 0, 0, 1]]) assert A**(n + 2) == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]]) raises(ValueError, lambda: A**Rational(3, 2)) A = Matrix([[0, 0, 1], [3, 0, 1], [4, 3, 1]]) assert A**5.0 == Matrix([[168, 72, 89], [291, 144, 161], [572, 267, 329]]) assert A**5.0 == A**5 A = Matrix([[0, 1, 0],[-1, 0, 0],[0, 0, 0]]) n = Symbol("n") An = A**n assert An.subs(n, 2).doit() == A**2 raises(ValueError, lambda: An.subs(n, -2).doit()) assert An * An == A**(2*n) # concretizing behavior for non-integer and complex powers A = Matrix([[0,0,0],[0,0,0],[0,0,0]]) n = Symbol('n', integer=True, positive=True) assert A**n == A n = Symbol('n', integer=True, nonnegative=True) assert A**n == diag(0**n, 0**n, 0**n) assert (A**n).subs(n, 0) == eye(3) assert (A**n).subs(n, 1) == zeros(3) A = Matrix ([[2,0,0],[0,2,0],[0,0,2]]) assert A**2.1 == diag (2**2.1, 2**2.1, 2**2.1) assert A**I == diag (2**I, 2**I, 2**I) A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 1]]) raises(ValueError, lambda: A**2.1) raises(ValueError, lambda: A**I) A = Matrix([[S.Half, S.Half], [S.Half, S.Half]]) assert A**S.Half == A A = Matrix([[1, 1],[3, 3]]) assert A**S.Half == Matrix ([[S.Half, S.Half], [3*S.Half, 3*S.Half]]) def test_issue_17247_expression_blowup_1(): M = Matrix([[1+x, 1-x], [1-x, 1+x]]) with dotprodsimp(True): assert M.exp().expand() == Matrix([ [ (exp(2*x) + exp(2))/2, (-exp(2*x) + exp(2))/2], [(-exp(2*x) + exp(2))/2, (exp(2*x) + exp(2))/2]]) def test_issue_17247_expression_blowup_2(): M = Matrix([[1+x, 1-x], [1-x, 1+x]]) with dotprodsimp(True): P, J = M.jordan_form () assert P*J*P.inv() def test_issue_17247_expression_blowup_3(): M = Matrix([[1+x, 1-x], [1-x, 1+x]]) with dotprodsimp(True): assert M**100 == Matrix([ [633825300114114700748351602688*x**100 + 633825300114114700748351602688, 633825300114114700748351602688 - 633825300114114700748351602688*x**100], [633825300114114700748351602688 - 633825300114114700748351602688*x**100, 633825300114114700748351602688*x**100 + 633825300114114700748351602688]]) def test_issue_17247_expression_blowup_4(): # This matrix takes extremely long on current master even with intermediate simplification so an abbreviated version is used. It is left here for test in case of future optimizations. # M = Matrix(S('''[ # [ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128, 3/64 + 13*I/64, -23/32 - 59*I/256, 15/128 - 3*I/32, 19/256 + 551*I/1024], # [-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024, 119/128 + 143*I/128, -10879/2048 + 4343*I/4096, 129/256 - 549*I/512, 42533/16384 + 29103*I/8192], # [ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128, 3/64 + 13*I/64, -23/32 - 59*I/256], # [ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024, 119/128 + 143*I/128, -10879/2048 + 4343*I/4096], # [ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128], # [ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024], # [ -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64], # [ 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512], # [ -4*I, 27/2 + 6*I, -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64], # [ 1/4 + 5*I/2, -23/8 - 57*I/16, 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128], # [ -4, 9 - 5*I, -4*I, 27/2 + 6*I, -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16], # [ -2*I, 119/8 + 29*I/4, 1/4 + 5*I/2, -23/8 - 57*I/16, 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]''')) # assert M**10 == Matrix([ # [ 7*(-221393644768594642173548179825793834595 - 1861633166167425978847110897013541127952*I)/9671406556917033397649408, 15*(31670992489131684885307005100073928751695 + 10329090958303458811115024718207404523808*I)/77371252455336267181195264, 7*(-3710978679372178839237291049477017392703 + 1377706064483132637295566581525806894169*I)/19342813113834066795298816, (9727707023582419994616144751727760051598 - 59261571067013123836477348473611225724433*I)/9671406556917033397649408, (31896723509506857062605551443641668183707 + 54643444538699269118869436271152084599580*I)/38685626227668133590597632, (-2024044860947539028275487595741003997397402 + 130959428791783397562960461903698670485863*I)/309485009821345068724781056, 3*(26190251453797590396533756519358368860907 - 27221191754180839338002754608545400941638*I)/77371252455336267181195264, (1154643595139959842768960128434994698330461 + 3385496216250226964322872072260446072295634*I)/618970019642690137449562112, 3*(-31849347263064464698310044805285774295286 - 11877437776464148281991240541742691164309*I)/77371252455336267181195264, (4661330392283532534549306589669150228040221 - 4171259766019818631067810706563064103956871*I)/1237940039285380274899124224, (9598353794289061833850770474812760144506 + 358027153990999990968244906482319780943983*I)/309485009821345068724781056, (-9755135335127734571547571921702373498554177 - 4837981372692695195747379349593041939686540*I)/2475880078570760549798248448], # [(-379516731607474268954110071392894274962069 - 422272153179747548473724096872271700878296*I)/77371252455336267181195264, (41324748029613152354787280677832014263339501 - 12715121258662668420833935373453570749288074*I)/1237940039285380274899124224, (-339216903907423793947110742819264306542397 + 494174755147303922029979279454787373566517*I)/77371252455336267181195264, (-18121350839962855576667529908850640619878381 - 37413012454129786092962531597292531089199003*I)/1237940039285380274899124224, (2489661087330511608618880408199633556675926 + 1137821536550153872137379935240732287260863*I)/309485009821345068724781056, (-136644109701594123227587016790354220062972119 + 110130123468183660555391413889600443583585272*I)/4951760157141521099596496896, (1488043981274920070468141664150073426459593 - 9691968079933445130866371609614474474327650*I)/1237940039285380274899124224, 27*(4636797403026872518131756991410164760195942 + 3369103221138229204457272860484005850416533*I)/4951760157141521099596496896, (-8534279107365915284081669381642269800472363 + 2241118846262661434336333368511372725482742*I)/1237940039285380274899124224, (60923350128174260992536531692058086830950875 - 263673488093551053385865699805250505661590126*I)/9903520314283042199192993792, (18520943561240714459282253753348921824172569 + 24846649186468656345966986622110971925703604*I)/4951760157141521099596496896, (-232781130692604829085973604213529649638644431 + 35981505277760667933017117949103953338570617*I)/9903520314283042199192993792], # [ (8742968295129404279528270438201520488950 + 3061473358639249112126847237482570858327*I)/4835703278458516698824704, (-245657313712011778432792959787098074935273 + 253113767861878869678042729088355086740856*I)/38685626227668133590597632, (1947031161734702327107371192008011621193 - 19462330079296259148177542369999791122762*I)/9671406556917033397649408, (552856485625209001527688949522750288619217 + 392928441196156725372494335248099016686580*I)/77371252455336267181195264, (-44542866621905323121630214897126343414629 + 3265340021421335059323962377647649632959*I)/19342813113834066795298816, (136272594005759723105646069956434264218730 - 330975364731707309489523680957584684763587*I)/38685626227668133590597632, (27392593965554149283318732469825168894401 + 75157071243800133880129376047131061115278*I)/38685626227668133590597632, 7*(-357821652913266734749960136017214096276154 - 45509144466378076475315751988405961498243*I)/309485009821345068724781056, (104485001373574280824835174390219397141149 - 99041000529599568255829489765415726168162*I)/77371252455336267181195264, (1198066993119982409323525798509037696321291 + 4249784165667887866939369628840569844519936*I)/618970019642690137449562112, (-114985392587849953209115599084503853611014 - 52510376847189529234864487459476242883449*I)/77371252455336267181195264, (6094620517051332877965959223269600650951573 - 4683469779240530439185019982269137976201163*I)/1237940039285380274899124224], # [ (611292255597977285752123848828590587708323 - 216821743518546668382662964473055912169502*I)/77371252455336267181195264, (-1144023204575811464652692396337616594307487 + 12295317806312398617498029126807758490062855*I)/309485009821345068724781056, (-374093027769390002505693378578475235158281 - 573533923565898290299607461660384634333639*I)/77371252455336267181195264, (47405570632186659000138546955372796986832987 - 2837476058950808941605000274055970055096534*I)/1237940039285380274899124224, (-571573207393621076306216726219753090535121 + 533381457185823100878764749236639320783831*I)/77371252455336267181195264, (-7096548151856165056213543560958582513797519 - 24035731898756040059329175131592138642195366*I)/618970019642690137449562112, (2396762128833271142000266170154694033849225 + 1448501087375679588770230529017516492953051*I)/309485009821345068724781056, (-150609293845161968447166237242456473262037053 + 92581148080922977153207018003184520294188436*I)/4951760157141521099596496896, 5*(270278244730804315149356082977618054486347 - 1997830155222496880429743815321662710091562*I)/1237940039285380274899124224, (62978424789588828258068912690172109324360330 + 44803641177219298311493356929537007630129097*I)/2475880078570760549798248448, 19*(-451431106327656743945775812536216598712236 + 114924966793632084379437683991151177407937*I)/1237940039285380274899124224, (63417747628891221594106738815256002143915995 - 261508229397507037136324178612212080871150958*I)/9903520314283042199192993792], # [ (-2144231934021288786200752920446633703357 + 2305614436009705803670842248131563850246*I)/1208925819614629174706176, (-90720949337459896266067589013987007078153 - 221951119475096403601562347412753844534569*I)/19342813113834066795298816, (11590973613116630788176337262688659880376 + 6514520676308992726483494976339330626159*I)/4835703278458516698824704, 3*(-131776217149000326618649542018343107657237 + 79095042939612668486212006406818285287004*I)/38685626227668133590597632, (10100577916793945997239221374025741184951 - 28631383488085522003281589065994018550748*I)/9671406556917033397649408, 67*(10090295594251078955008130473573667572549 + 10449901522697161049513326446427839676762*I)/77371252455336267181195264, (-54270981296988368730689531355811033930513 - 3413683117592637309471893510944045467443*I)/19342813113834066795298816, (440372322928679910536575560069973699181278 - 736603803202303189048085196176918214409081*I)/77371252455336267181195264, (33220374714789391132887731139763250155295 + 92055083048787219934030779066298919603554*I)/38685626227668133590597632, 5*(-594638554579967244348856981610805281527116 - 82309245323128933521987392165716076704057*I)/309485009821345068724781056, (128056368815300084550013708313312073721955 - 114619107488668120303579745393765245911404*I)/77371252455336267181195264, 21*(59839959255173222962789517794121843393573 + 241507883613676387255359616163487405826334*I)/618970019642690137449562112], # [ (-13454485022325376674626653802541391955147 + 184471402121905621396582628515905949793486*I)/19342813113834066795298816, (-6158730123400322562149780662133074862437105 - 3416173052604643794120262081623703514107476*I)/154742504910672534362390528, (770558003844914708453618983120686116100419 - 127758381209767638635199674005029818518766*I)/77371252455336267181195264, (-4693005771813492267479835161596671660631703 + 12703585094750991389845384539501921531449948*I)/309485009821345068724781056, (-295028157441149027913545676461260860036601 - 841544569970643160358138082317324743450770*I)/77371252455336267181195264, (56716442796929448856312202561538574275502893 + 7216818824772560379753073185990186711454778*I)/1237940039285380274899124224, 15*(-87061038932753366532685677510172566368387 + 61306141156647596310941396434445461895538*I)/154742504910672534362390528, (-3455315109680781412178133042301025723909347 - 24969329563196972466388460746447646686670670*I)/618970019642690137449562112, (2453418854160886481106557323699250865361849 + 1497886802326243014471854112161398141242514*I)/309485009821345068724781056, (-151343224544252091980004429001205664193082173 + 90471883264187337053549090899816228846836628*I)/4951760157141521099596496896, (1652018205533026103358164026239417416432989 - 9959733619236515024261775397109724431400162*I)/1237940039285380274899124224, 3*(40676374242956907656984876692623172736522006 + 31023357083037817469535762230872667581366205*I)/4951760157141521099596496896], # [ (-1226990509403328460274658603410696548387 - 4131739423109992672186585941938392788458*I)/1208925819614629174706176, (162392818524418973411975140074368079662703 + 23706194236915374831230612374344230400704*I)/9671406556917033397649408, (-3935678233089814180000602553655565621193 + 2283744757287145199688061892165659502483*I)/1208925819614629174706176, (-2400210250844254483454290806930306285131 - 315571356806370996069052930302295432758205*I)/19342813113834066795298816, (13365917938215281056563183751673390817910 + 15911483133819801118348625831132324863881*I)/4835703278458516698824704, 3*(-215950551370668982657516660700301003897855 + 51684341999223632631602864028309400489378*I)/38685626227668133590597632, (20886089946811765149439844691320027184765 - 30806277083146786592790625980769214361844*I)/9671406556917033397649408, (562180634592713285745940856221105667874855 + 1031543963988260765153550559766662245114916*I)/77371252455336267181195264, (-65820625814810177122941758625652476012867 - 12429918324787060890804395323920477537595*I)/19342813113834066795298816, (319147848192012911298771180196635859221089 - 402403304933906769233365689834404519960394*I)/38685626227668133590597632, (23035615120921026080284733394359587955057 + 115351677687031786114651452775242461310624*I)/38685626227668133590597632, (-3426830634881892756966440108592579264936130 - 1022954961164128745603407283836365128598559*I)/309485009821345068724781056], # [ (-192574788060137531023716449082856117537757 - 69222967328876859586831013062387845780692*I)/19342813113834066795298816, (2736383768828013152914815341491629299773262 - 2773252698016291897599353862072533475408743*I)/77371252455336267181195264, (-23280005281223837717773057436155921656805 + 214784953368021840006305033048142888879224*I)/19342813113834066795298816, (-3035247484028969580570400133318947903462326 - 2195168903335435855621328554626336958674325*I)/77371252455336267181195264, (984552428291526892214541708637840971548653 - 64006622534521425620714598573494988589378*I)/77371252455336267181195264, (-3070650452470333005276715136041262898509903 + 7286424705750810474140953092161794621989080*I)/154742504910672534362390528, (-147848877109756404594659513386972921139270 - 416306113044186424749331418059456047650861*I)/38685626227668133590597632, (55272118474097814260289392337160619494260781 + 7494019668394781211907115583302403519488058*I)/1237940039285380274899124224, (-581537886583682322424771088996959213068864 + 542191617758465339135308203815256798407429*I)/77371252455336267181195264, (-6422548983676355789975736799494791970390991 - 23524183982209004826464749309156698827737702*I)/618970019642690137449562112, 7*(180747195387024536886923192475064903482083 + 84352527693562434817771649853047924991804*I)/154742504910672534362390528, (-135485179036717001055310712747643466592387031 + 102346575226653028836678855697782273460527608*I)/4951760157141521099596496896], # [ (3384238362616083147067025892852431152105 + 156724444932584900214919898954874618256*I)/604462909807314587353088, (-59558300950677430189587207338385764871866 + 114427143574375271097298201388331237478857*I)/4835703278458516698824704, (-1356835789870635633517710130971800616227 - 7023484098542340388800213478357340875410*I)/1208925819614629174706176, (234884918567993750975181728413524549575881 + 79757294640629983786895695752733890213506*I)/9671406556917033397649408, (-7632732774935120473359202657160313866419 + 2905452608512927560554702228553291839465*I)/1208925819614629174706176, (52291747908702842344842889809762246649489 - 520996778817151392090736149644507525892649*I)/19342813113834066795298816, (17472406829219127839967951180375981717322 + 23464704213841582137898905375041819568669*I)/4835703278458516698824704, (-911026971811893092350229536132730760943307 + 150799318130900944080399439626714846752360*I)/38685626227668133590597632, (26234457233977042811089020440646443590687 - 45650293039576452023692126463683727692890*I)/9671406556917033397649408, 3*(288348388717468992528382586652654351121357 + 454526517721403048270274049572136109264668*I)/77371252455336267181195264, (-91583492367747094223295011999405657956347 - 12704691128268298435362255538069612411331*I)/19342813113834066795298816, (411208730251327843849027957710164064354221 - 569898526380691606955496789378230959965898*I)/38685626227668133590597632], # [ (27127513117071487872628354831658811211795 - 37765296987901990355760582016892124833857*I)/4835703278458516698824704, (1741779916057680444272938534338833170625435 + 3083041729779495966997526404685535449810378*I)/77371252455336267181195264, 3*(-60642236251815783728374561836962709533401 - 24630301165439580049891518846174101510744*I)/19342813113834066795298816, 3*(445885207364591681637745678755008757483408 - 350948497734812895032502179455610024541643*I)/38685626227668133590597632, (-47373295621391195484367368282471381775684 + 219122969294089357477027867028071400054973*I)/19342813113834066795298816, (-2801565819673198722993348253876353741520438 - 2250142129822658548391697042460298703335701*I)/77371252455336267181195264, (801448252275607253266997552356128790317119 - 50890367688077858227059515894356594900558*I)/77371252455336267181195264, (-5082187758525931944557763799137987573501207 + 11610432359082071866576699236013484487676124*I)/309485009821345068724781056, (-328925127096560623794883760398247685166830 - 643447969697471610060622160899409680422019*I)/77371252455336267181195264, 15*(2954944669454003684028194956846659916299765 + 33434406416888505837444969347824812608566*I)/1237940039285380274899124224, (-415749104352001509942256567958449835766827 + 479330966144175743357171151440020955412219*I)/77371252455336267181195264, 3*(-4639987285852134369449873547637372282914255 - 11994411888966030153196659207284951579243273*I)/1237940039285380274899124224], # [ (-478846096206269117345024348666145495601 + 1249092488629201351470551186322814883283*I)/302231454903657293676544, (-17749319421930878799354766626365926894989 - 18264580106418628161818752318217357231971*I)/1208925819614629174706176, (2801110795431528876849623279389579072819 + 363258850073786330770713557775566973248*I)/604462909807314587353088, (-59053496693129013745775512127095650616252 + 78143588734197260279248498898321500167517*I)/4835703278458516698824704, (-283186724922498212468162690097101115349 - 6443437753863179883794497936345437398276*I)/1208925819614629174706176, (188799118826748909206887165661384998787543 + 84274736720556630026311383931055307398820*I)/9671406556917033397649408, (-5482217151670072904078758141270295025989 + 1818284338672191024475557065444481298568*I)/1208925819614629174706176, (56564463395350195513805521309731217952281 - 360208541416798112109946262159695452898431*I)/19342813113834066795298816, 11*(1259539805728870739006416869463689438068 + 1409136581547898074455004171305324917387*I)/4835703278458516698824704, 5*(-123701190701414554945251071190688818343325 + 30997157322590424677294553832111902279712*I)/38685626227668133590597632, (16130917381301373033736295883982414239781 - 32752041297570919727145380131926943374516*I)/9671406556917033397649408, (650301385108223834347093740500375498354925 + 899526407681131828596801223402866051809258*I)/77371252455336267181195264], # [ (9011388245256140876590294262420614839483 + 8167917972423946282513000869327525382672*I)/1208925819614629174706176, (-426393174084720190126376382194036323028924 + 180692224825757525982858693158209545430621*I)/9671406556917033397649408, (24588556702197802674765733448108154175535 - 45091766022876486566421953254051868331066*I)/4835703278458516698824704, (1872113939365285277373877183750416985089691 + 3030392393733212574744122057679633775773130*I)/77371252455336267181195264, (-222173405538046189185754954524429864167549 - 75193157893478637039381059488387511299116*I)/19342813113834066795298816, (2670821320766222522963689317316937579844558 - 2645837121493554383087981511645435472169191*I)/77371252455336267181195264, 5*(-2100110309556476773796963197283876204940 + 41957457246479840487980315496957337371937*I)/19342813113834066795298816, (-5733743755499084165382383818991531258980593 - 3328949988392698205198574824396695027195732*I)/154742504910672534362390528, (707827994365259025461378911159398206329247 - 265730616623227695108042528694302299777294*I)/77371252455336267181195264, (-1442501604682933002895864804409322823788319 + 11504137805563265043376405214378288793343879*I)/309485009821345068724781056, (-56130472299445561499538726459719629522285 - 61117552419727805035810982426639329818864*I)/9671406556917033397649408, (39053692321126079849054272431599539429908717 - 10209127700342570953247177602860848130710666*I)/1237940039285380274899124224]]) M = Matrix(S('''[ [ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512], [ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64], [ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128], [ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16], [ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M**10 == Matrix(S('''[ [ 7369525394972778926719607798014571861/604462909807314587353088 - 229284202061790301477392339912557559*I/151115727451828646838272, -19704281515163975949388435612632058035/1208925819614629174706176 + 14319858347987648723768698170712102887*I/302231454903657293676544, -3623281909451783042932142262164941211/604462909807314587353088 - 6039240602494288615094338643452320495*I/604462909807314587353088, 109260497799140408739847239685705357695/2417851639229258349412352 - 7427566006564572463236368211555511431*I/2417851639229258349412352, -16095803767674394244695716092817006641/2417851639229258349412352 + 10336681897356760057393429626719177583*I/1208925819614629174706176, -42207883340488041844332828574359769743/2417851639229258349412352 - 182332262671671273188016400290188468499*I/4835703278458516698824704], [50566491050825573392726324995779608259/1208925819614629174706176 - 90047007594468146222002432884052362145*I/2417851639229258349412352, 74273703462900000967697427843983822011/1208925819614629174706176 + 265947522682943571171988741842776095421*I/1208925819614629174706176, -116900341394390200556829767923360888429/2417851639229258349412352 - 53153263356679268823910621474478756845*I/2417851639229258349412352, 195407378023867871243426523048612490249/1208925819614629174706176 - 1242417915995360200584837585002906728929*I/9671406556917033397649408, -863597594389821970177319682495878193/302231454903657293676544 + 476936100741548328800725360758734300481*I/9671406556917033397649408, -3154451590535653853562472176601754835575/19342813113834066795298816 - 232909875490506237386836489998407329215*I/2417851639229258349412352], [ -1715444997702484578716037230949868543/302231454903657293676544 + 5009695651321306866158517287924120777*I/302231454903657293676544, -30551582497996879620371947949342101301/604462909807314587353088 - 7632518367986526187139161303331519629*I/151115727451828646838272, 312680739924495153190604170938220575/18889465931478580854784 - 108664334509328818765959789219208459*I/75557863725914323419136, -14693696966703036206178521686918865509/604462909807314587353088 + 72345386220900843930147151999899692401*I/1208925819614629174706176, -8218872496728882299722894680635296519/1208925819614629174706176 - 16776782833358893712645864791807664983*I/1208925819614629174706176, 143237839169380078671242929143670635137/2417851639229258349412352 + 2883817094806115974748882735218469447*I/2417851639229258349412352], [ 3087979417831061365023111800749855987/151115727451828646838272 + 34441942370802869368851419102423997089*I/604462909807314587353088, -148309181940158040917731426845476175667/604462909807314587353088 - 263987151804109387844966835369350904919*I/9671406556917033397649408, 50259518594816377378747711930008883165/1208925819614629174706176 - 95713974916869240305450001443767979653*I/2417851639229258349412352, 153466447023875527996457943521467271119/2417851639229258349412352 + 517285524891117105834922278517084871349*I/2417851639229258349412352, -29184653615412989036678939366291205575/604462909807314587353088 - 27551322282526322041080173287022121083*I/1208925819614629174706176, 196404220110085511863671393922447671649/1208925819614629174706176 - 1204712019400186021982272049902206202145*I/9671406556917033397649408], [ -2632581805949645784625606590600098779/151115727451828646838272 - 589957435912868015140272627522612771*I/37778931862957161709568, 26727850893953715274702844733506310247/302231454903657293676544 - 10825791956782128799168209600694020481*I/302231454903657293676544, -1036348763702366164044671908440791295/151115727451828646838272 + 3188624571414467767868303105288107375*I/151115727451828646838272, -36814959939970644875593411585393242449/604462909807314587353088 - 18457555789119782404850043842902832647*I/302231454903657293676544, 12454491297984637815063964572803058647/604462909807314587353088 - 340489532842249733975074349495329171*I/302231454903657293676544, -19547211751145597258386735573258916681/604462909807314587353088 + 87299583775782199663414539883938008933*I/1208925819614629174706176], [ -40281994229560039213253423262678393183/604462909807314587353088 - 2939986850065527327299273003299736641*I/604462909807314587353088, 331940684638052085845743020267462794181/2417851639229258349412352 - 284574901963624403933361315517248458969*I/1208925819614629174706176, 6453843623051745485064693628073010961/302231454903657293676544 + 36062454107479732681350914931391590957*I/604462909807314587353088, -147665869053634695632880753646441962067/604462909807314587353088 - 305987938660447291246597544085345123927*I/9671406556917033397649408, 107821369195275772166593879711259469423/2417851639229258349412352 - 11645185518211204108659001435013326687*I/302231454903657293676544, 64121228424717666402009446088588091619/1208925819614629174706176 + 265557133337095047883844369272389762133*I/1208925819614629174706176]]''')) def test_issue_17247_expression_blowup_5(): M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I) with dotprodsimp(True): assert M.charpoly('x') == PurePoly(x**6 + (-6 - 6*I)*x**5 + 36*I*x**4, x, domain='EX') def test_issue_17247_expression_blowup_6(): M = Matrix(8, 8, [x+i for i in range (64)]) with dotprodsimp(True): assert M.det('bareiss') == 0 def test_issue_17247_expression_blowup_7(): M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I) with dotprodsimp(True): assert M.det('berkowitz') == 0 @XFAIL # dotprodsimp is not on by default in this function def test_issue_17247_expression_blowup_8(): M = Matrix(8, 8, [x+i for i in range (64)]) with dotprodsimp(True): assert M.det('lu') == 0 def test_issue_17247_expression_blowup_9(): M = Matrix(8, 8, [x+i for i in range (64)]) with dotprodsimp(True): assert M.rref() == (Matrix([ [1, 0, -1, -2, -3, -4, -5, -6], [0, 1, 2, 3, 4, 5, 6, 7], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]), (0, 1)) def test_issue_17247_expression_blowup_10(): M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I) with dotprodsimp(True): assert M.cofactor(0, 0) == 0 def test_issue_17247_expression_blowup_11(): M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I) with dotprodsimp(True): assert M.cofactor_matrix() == Matrix(6, 6, [0]*36) def test_issue_17247_expression_blowup_12(): M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I) with dotprodsimp(True): assert M.eigenvals() == {6: 1, 6*I: 1, 0: 4} def test_issue_17247_expression_blowup_13(): M = Matrix([ [ 0, 1 - x, x + 1, 1 - x], [1 - x, x + 1, 0, x + 1], [ 0, 1 - x, x + 1, 1 - x], [ 0, 0, 1 - x, 0]]) with dotprodsimp(True): ev = M.eigenvects() assert ev[0][:2] == (0, 2) assert ev[0][2][0] == Matrix([[0],[-1],[0],[1]]) assert ev[1][:2] == (x - sqrt(2)*(x - 1) + 1, 1) assert (ev[1][2][0] - Matrix([ [-(-17*x**4 + 12*sqrt(2)*x**4 - 4*sqrt(2)*x**3 + 6*x**3 - 6*x - 4*sqrt(2)*x + 12*sqrt(2) + 17)/(-7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 + 8*x**3 - 2*x**2 + 8*x + 6*sqrt(2)*x - 5*sqrt(2) - 7)], [ (-7*x**3 + 5*sqrt(2)*x**3 - x**2 + sqrt(2)*x**2 - sqrt(2)*x - x - 5*sqrt(2) - 7)/(-3*x**3 + 2*sqrt(2)*x**3 - 2*sqrt(2)*x**2 + 3*x**2 + 2*sqrt(2)*x + 3*x - 3 - 2*sqrt(2))], [ -(-3*x**2 + 2*sqrt(2)*x**2 + 2*x - 3 - 2*sqrt(2))/(-x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x + 1 + sqrt(2))], [ 1]])).expand() == Matrix([[0],[0],[0],[0]]) assert ev[2][:2] == (x + sqrt(2)*(x - 1) + 1, 1) assert (ev[2][2][0] - Matrix([ [-(12*sqrt(2)*x**4 + 17*x**4 - 6*x**3 - 4*sqrt(2)*x**3 - 4*sqrt(2)*x + 6*x - 17 + 12*sqrt(2))/(7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 - 8*x**3 + 2*x**2 - 8*x + 6*sqrt(2)*x - 5*sqrt(2) + 7)], [ (7*x**3 + 5*sqrt(2)*x**3 + x**2 + sqrt(2)*x**2 - sqrt(2)*x + x - 5*sqrt(2) + 7)/(2*sqrt(2)*x**3 + 3*x**3 - 3*x**2 - 2*sqrt(2)*x**2 - 3*x + 2*sqrt(2)*x - 2*sqrt(2) + 3)], [ -(2*sqrt(2)*x**2 + 3*x**2 - 2*x - 2*sqrt(2) + 3)/(x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x - 1 + sqrt(2))], [ 1]])).expand() == Matrix([[0],[0],[0],[0]]) def test_issue_17247_expression_blowup_14(): M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4) with dotprodsimp(True): assert M.echelon_form() == Matrix([ [x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x], [ 0, 4*x, 0, 4*x, 0, 4*x, 0, 4*x], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0]]) def test_issue_17247_expression_blowup_15(): M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4) with dotprodsimp(True): assert M.rowspace() == [Matrix([[x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x]]), Matrix([[0, 4*x, 0, 4*x, 0, 4*x, 0, 4*x]])] def test_issue_17247_expression_blowup_16(): M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4) with dotprodsimp(True): assert M.columnspace() == [Matrix([[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x]]), Matrix([[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1]])] def test_issue_17247_expression_blowup_17(): M = Matrix(8, 8, [x+i for i in range (64)]) with dotprodsimp(True): assert M.nullspace() == [ Matrix([[1],[-2],[1],[0],[0],[0],[0],[0]]), Matrix([[2],[-3],[0],[1],[0],[0],[0],[0]]), Matrix([[3],[-4],[0],[0],[1],[0],[0],[0]]), Matrix([[4],[-5],[0],[0],[0],[1],[0],[0]]), Matrix([[5],[-6],[0],[0],[0],[0],[1],[0]]), Matrix([[6],[-7],[0],[0],[0],[0],[0],[1]])] def test_issue_17247_expression_blowup_18(): M = Matrix(6, 6, ([1+x, 1-x]*3 + [1-x, 1+x]*3)*3) with dotprodsimp(True): assert not M.is_nilpotent() def test_issue_17247_expression_blowup_19(): M = Matrix(S('''[ [ -3/4, 0, 1/4 + I/2, 0], [ 0, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 1/2 - I, 0, 0, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert not M.is_diagonalizable() def test_issue_17247_expression_blowup_20(): M = Matrix([ [x + 1, 1 - x, 0, 0], [1 - x, x + 1, 0, x + 1], [ 0, 1 - x, x + 1, 0], [ 0, 0, 0, x + 1]]) with dotprodsimp(True): assert M.diagonalize() == (Matrix([ [1, 1, 0, (x + 1)/(x - 1)], [1, -1, 0, 0], [1, 1, 1, 0], [0, 0, 0, 1]]), Matrix([ [2, 0, 0, 0], [0, 2*x, 0, 0], [0, 0, x + 1, 0], [0, 0, 0, x + 1]])) def test_issue_17247_expression_blowup_21(): M = Matrix(S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.inv(method='GE') == Matrix(S('''[ [-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785], [4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785], [-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905], [0, 0, 0, -11328/952745 + 87616*I/952745]]''')) @XFAIL # dotprodsimp is not on by default in this function def test_issue_17247_expression_blowup_22(): M = Matrix(S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.inv(method='LU') == Matrix(S('''[ [-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785], [4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785], [-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905], [0, 0, 0, -11328/952745 + 87616*I/952745]]''')) def test_issue_17247_expression_blowup_23(): M = Matrix(S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.inv(method='ADJ').expand() == Matrix(S('''[ [-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785], [4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785], [-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905], [0, 0, 0, -11328/952745 + 87616*I/952745]]''')) @XFAIL # dotprodsimp is not on by default in this function def test_issue_17247_expression_blowup_24(): M = SparseMatrix(S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.inv(method='CH') == Matrix(S('''[ [-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785], [4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785], [-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905], [0, 0, 0, -11328/952745 + 87616*I/952745]]''')) @XFAIL # dotprodsimp is not on by default in this function def test_issue_17247_expression_blowup_25(): M = SparseMatrix(S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.inv(method='LDL') == Matrix(S('''[ [-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785], [4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785], [-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905], [0, 0, 0, -11328/952745 + 87616*I/952745]]''')) def test_issue_17247_expression_blowup_26(): M = Matrix(S('''[ [ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024], [ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64], [ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512], [ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64], [ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128], [ -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16], [ 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.rank() == 4 def test_issue_17247_expression_blowup_27(): M = Matrix([ [ 0, 1 - x, x + 1, 1 - x], [1 - x, x + 1, 0, x + 1], [ 0, 1 - x, x + 1, 1 - x], [ 0, 0, 1 - x, 0]]) with dotprodsimp(True): P, J = M.jordan_form() assert P.expand() == Matrix(S('''[ [ 0, 4*x/(x**2 - 2*x + 1), -(-17*x**4 + 12*sqrt(2)*x**4 - 4*sqrt(2)*x**3 + 6*x**3 - 6*x - 4*sqrt(2)*x + 12*sqrt(2) + 17)/(-7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 + 8*x**3 - 2*x**2 + 8*x + 6*sqrt(2)*x - 5*sqrt(2) - 7), -(12*sqrt(2)*x**4 + 17*x**4 - 6*x**3 - 4*sqrt(2)*x**3 - 4*sqrt(2)*x + 6*x - 17 + 12*sqrt(2))/(7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 - 8*x**3 + 2*x**2 - 8*x + 6*sqrt(2)*x - 5*sqrt(2) + 7)], [x - 1, x/(x - 1) + 1/(x - 1), (-7*x**3 + 5*sqrt(2)*x**3 - x**2 + sqrt(2)*x**2 - sqrt(2)*x - x - 5*sqrt(2) - 7)/(-3*x**3 + 2*sqrt(2)*x**3 - 2*sqrt(2)*x**2 + 3*x**2 + 2*sqrt(2)*x + 3*x - 3 - 2*sqrt(2)), (7*x**3 + 5*sqrt(2)*x**3 + x**2 + sqrt(2)*x**2 - sqrt(2)*x + x - 5*sqrt(2) + 7)/(2*sqrt(2)*x**3 + 3*x**3 - 3*x**2 - 2*sqrt(2)*x**2 - 3*x + 2*sqrt(2)*x - 2*sqrt(2) + 3)], [ 0, 1, -(-3*x**2 + 2*sqrt(2)*x**2 + 2*x - 3 - 2*sqrt(2))/(-x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x + 1 + sqrt(2)), -(2*sqrt(2)*x**2 + 3*x**2 - 2*x - 2*sqrt(2) + 3)/(x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x - 1 + sqrt(2))], [1 - x, 0, 1, 1]]''')).expand() assert J == Matrix(S('''[ [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, x - sqrt(2)*(x - 1) + 1, 0], [0, 0, 0, x + sqrt(2)*(x - 1) + 1]]''')) def test_issue_17247_expression_blowup_28(): M = Matrix(S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.singular_values() == S('''[ sqrt(14609315/131072 + sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) + 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2 + sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2), sqrt(14609315/131072 - sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) + 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2 + sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2), sqrt(14609315/131072 - sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2 + sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) - 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2), sqrt(14609315/131072 - sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2 - sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) - 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2)]''') def test_issue_16823(): # This still needs to be fixed if not using dotprodsimp. M = Matrix(S('''[ [1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I,3/64+13/64*I,-23/32-59/256*I,15/128-3/32*I,19/256+551/1024*I], [21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I,119/128+143/128*I,-10879/2048+4343/4096*I,129/256-549/512*I,42533/16384+29103/8192*I], [-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I,3/64+13/64*I,-23/32-59/256*I], [1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I,119/128+143/128*I,-10879/2048+4343/4096*I], [-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I], [1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I], [-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I], [-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I], [0,-6,-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I], [1,-9/4+3*I,-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I], [0,-4*I,0,-6,-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I], [0,1/4+1/2*I,1,-9/4+3*I,-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I]]''')) with dotprodsimp(True): assert M.rank() == 8 def test_issue_18531(): # solve_linear_system still needs fixing but the rref works. M = Matrix([ [1, 1, 1, 1, 1, 0, 1, 0, 0], [1 + sqrt(2), -1 + sqrt(2), 1 - sqrt(2), -sqrt(2) - 1, 1, 1, -1, 1, 1], [-5 + 2*sqrt(2), -5 - 2*sqrt(2), -5 - 2*sqrt(2), -5 + 2*sqrt(2), -7, 2, -7, -2, 0], [-3*sqrt(2) - 1, 1 - 3*sqrt(2), -1 + 3*sqrt(2), 1 + 3*sqrt(2), -7, -5, 7, -5, 3], [7 - 4*sqrt(2), 4*sqrt(2) + 7, 4*sqrt(2) + 7, 7 - 4*sqrt(2), 7, -12, 7, 12, 0], [-1 + 3*sqrt(2), 1 + 3*sqrt(2), -3*sqrt(2) - 1, 1 - 3*sqrt(2), 7, -5, -7, -5, 3], [-3 + 2*sqrt(2), -3 - 2*sqrt(2), -3 - 2*sqrt(2), -3 + 2*sqrt(2), -1, 2, -1, -2, 0], [1 - sqrt(2), -sqrt(2) - 1, 1 + sqrt(2), -1 + sqrt(2), -1, 1, 1, 1, 1] ]) with dotprodsimp(True): assert M.rref() == (Matrix([ [1, 0, 0, 0, 0, 0, 0, 0, 1/2], [0, 1, 0, 0, 0, 0, 0, 0, -1/2], [0, 0, 1, 0, 0, 0, 0, 0, 1/2], [0, 0, 0, 1, 0, 0, 0, 0, -1/2], [0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, -1/2], [0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, -1/2]]), (0, 1, 2, 3, 4, 5, 6, 7)) def test_creation(): raises(ValueError, lambda: Matrix(5, 5, range(20))) raises(ValueError, lambda: Matrix(5, -1, [])) raises(IndexError, lambda: Matrix((1, 2))[2]) with raises(IndexError): Matrix((1, 2))[1:2] = 5 with raises(IndexError): Matrix((1, 2))[3] = 5 assert Matrix() == Matrix([]) == Matrix([[]]) == Matrix(0, 0, []) # anything can go into a matrix (laplace_transform uses tuples) assert Matrix([[[], ()]]).tolist() == [[[], ()]] assert Matrix([[[], ()]]).T.tolist() == [[[]], [()]] a = Matrix([[x, 0], [0, 0]]) m = a assert m.cols == m.rows assert m.cols == 2 assert m[:] == [x, 0, 0, 0] b = Matrix(2, 2, [x, 0, 0, 0]) m = b assert m.cols == m.rows assert m.cols == 2 assert m[:] == [x, 0, 0, 0] assert a == b assert Matrix(b) == b c23 = Matrix(2, 3, range(1, 7)) c13 = Matrix(1, 3, range(7, 10)) c = Matrix([c23, c13]) assert c.cols == 3 assert c.rows == 3 assert c[:] == [1, 2, 3, 4, 5, 6, 7, 8, 9] assert Matrix(eye(2)) == eye(2) assert ImmutableMatrix(ImmutableMatrix(eye(2))) == ImmutableMatrix(eye(2)) assert ImmutableMatrix(c) == c.as_immutable() assert Matrix(ImmutableMatrix(c)) == ImmutableMatrix(c).as_mutable() assert c is not Matrix(c) dat = [[ones(3,2), ones(3,3)*2], [ones(2,3)*3, ones(2,2)*4]] M = Matrix(dat) assert M == Matrix([ [1, 1, 2, 2, 2], [1, 1, 2, 2, 2], [1, 1, 2, 2, 2], [3, 3, 3, 4, 4], [3, 3, 3, 4, 4]]) assert M.tolist() != dat # keep block form if evaluate=False assert Matrix(dat, evaluate=False).tolist() == dat A = MatrixSymbol("A", 2, 2) dat = [ones(2), A] assert Matrix(dat) == Matrix([ [ 1, 1], [ 1, 1], [A[0, 0], A[0, 1]], [A[1, 0], A[1, 1]]]) assert Matrix(dat, evaluate=False).tolist() == [[i] for i in dat] # 0-dim tolerance assert Matrix([ones(2), ones(0)]) == Matrix([ones(2)]) raises(ValueError, lambda: Matrix([ones(2), ones(0, 3)])) raises(ValueError, lambda: Matrix([ones(2), ones(3, 0)])) def test_irregular_block(): assert Matrix.irregular(3, ones(2,1), ones(3,3)*2, ones(2,2)*3, ones(1,1)*4, ones(2,2)*5, ones(1,2)*6, ones(1,2)*7) == Matrix([ [1, 2, 2, 2, 3, 3], [1, 2, 2, 2, 3, 3], [4, 2, 2, 2, 5, 5], [6, 6, 7, 7, 5, 5]]) def test_tolist(): lst = [[S.One, S.Half, x*y, S.Zero], [x, y, z, x**2], [y, -S.One, z*x, 3]] m = Matrix(lst) assert m.tolist() == lst def test_as_mutable(): assert zeros(0, 3).as_mutable() == zeros(0, 3) assert zeros(0, 3).as_immutable() == ImmutableMatrix(zeros(0, 3)) assert zeros(3, 0).as_immutable() == ImmutableMatrix(zeros(3, 0)) def test_slicing(): m0 = eye(4) assert m0[:3, :3] == eye(3) assert m0[2:4, 0:2] == zeros(2) m1 = Matrix(3, 3, lambda i, j: i + j) assert m1[0, :] == Matrix(1, 3, (0, 1, 2)) assert m1[1:3, 1] == Matrix(2, 1, (2, 3)) m2 = Matrix([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]) assert m2[:, -1] == Matrix(4, 1, [3, 7, 11, 15]) assert m2[-2:, :] == Matrix([[8, 9, 10, 11], [12, 13, 14, 15]]) def test_submatrix_assignment(): m = zeros(4) m[2:4, 2:4] = eye(2) assert m == Matrix(((0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1))) m[:2, :2] = eye(2) assert m == eye(4) m[:, 0] = Matrix(4, 1, (1, 2, 3, 4)) assert m == Matrix(((1, 0, 0, 0), (2, 1, 0, 0), (3, 0, 1, 0), (4, 0, 0, 1))) m[:, :] = zeros(4) assert m == zeros(4) m[:, :] = [(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)] assert m == Matrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16))) m[:2, 0] = [0, 0] assert m == Matrix(((0, 2, 3, 4), (0, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16))) def test_extract(): m = Matrix(4, 3, lambda i, j: i*3 + j) assert m.extract([0, 1, 3], [0, 1]) == Matrix(3, 2, [0, 1, 3, 4, 9, 10]) assert m.extract([0, 3], [0, 0, 2]) == Matrix(2, 3, [0, 0, 2, 9, 9, 11]) assert m.extract(range(4), range(3)) == m raises(IndexError, lambda: m.extract([4], [0])) raises(IndexError, lambda: m.extract([0], [3])) def test_reshape(): m0 = eye(3) assert m0.reshape(1, 9) == Matrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1)) m1 = Matrix(3, 4, lambda i, j: i + j) assert m1.reshape( 4, 3) == Matrix(((0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5))) assert m1.reshape(2, 6) == Matrix(((0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5))) def test_applyfunc(): m0 = eye(3) assert m0.applyfunc(lambda x: 2*x) == eye(3)*2 assert m0.applyfunc(lambda x: 0) == zeros(3) def test_expand(): m0 = Matrix([[x*(x + y), 2], [((x + y)*y)*x, x*(y + x*(x + y))]]) # Test if expand() returns a matrix m1 = m0.expand() assert m1 == Matrix( [[x*y + x**2, 2], [x*y**2 + y*x**2, x*y + y*x**2 + x**3]]) a = Symbol('a', real=True) assert Matrix([exp(I*a)]).expand(complex=True) == \ Matrix([cos(a) + I*sin(a)]) assert Matrix([[0, 1, 2], [0, 0, -1], [0, 0, 0]]).exp() == Matrix([ [1, 1, Rational(3, 2)], [0, 1, -1], [0, 0, 1]] ) def test_refine(): m0 = Matrix([[Abs(x)**2, sqrt(x**2)], [sqrt(x**2)*Abs(y)**2, sqrt(y**2)*Abs(x)**2]]) m1 = m0.refine(Q.real(x) & Q.real(y)) assert m1 == Matrix([[x**2, Abs(x)], [y**2*Abs(x), x**2*Abs(y)]]) m1 = m0.refine(Q.positive(x) & Q.positive(y)) assert m1 == Matrix([[x**2, x], [x*y**2, x**2*y]]) m1 = m0.refine(Q.negative(x) & Q.negative(y)) assert m1 == Matrix([[x**2, -x], [-x*y**2, -x**2*y]]) def test_random(): M = randMatrix(3, 3) M = randMatrix(3, 3, seed=3) assert M == randMatrix(3, 3, seed=3) M = randMatrix(3, 4, 0, 150) M = randMatrix(3, seed=4, symmetric=True) assert M == randMatrix(3, seed=4, symmetric=True) S = M.copy() S.simplify() assert S == M # doesn't fail when elements are Numbers, not int rng = random.Random(4) assert M == randMatrix(3, symmetric=True, prng=rng) # Ensure symmetry for size in (10, 11): # Test odd and even for percent in (100, 70, 30): M = randMatrix(size, symmetric=True, percent=percent, prng=rng) assert M == M.T M = randMatrix(10, min=1, percent=70) zero_count = 0 for i in range(M.shape[0]): for j in range(M.shape[1]): if M[i, j] == 0: zero_count += 1 assert zero_count == 30 def test_inverse(): A = eye(4) assert A.inv() == eye(4) assert A.inv(method="LU") == eye(4) assert A.inv(method="ADJ") == eye(4) assert A.inv(method="CH") == eye(4) assert A.inv(method="LDL") == eye(4) assert A.inv(method="QR") == eye(4) A = Matrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]]) Ainv = A.inv() assert A*Ainv == eye(3) assert A.inv(method="LU") == Ainv assert A.inv(method="ADJ") == Ainv assert A.inv(method="CH") == Ainv assert A.inv(method="LDL") == Ainv assert A.inv(method="QR") == Ainv AA = Matrix([[0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0], [1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], [1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], [1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0], [1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1], [0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0], [1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1], [0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1], [1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0], [1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0], [0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1], [1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0], [0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0], [1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1], [0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1], [1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1], [0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1], [0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0]]) assert AA.inv(method="BLOCK") * AA == eye(AA.shape[0]) # test that immutability is not a problem cls = ImmutableMatrix m = cls([[48, 49, 31], [ 9, 71, 94], [59, 28, 65]]) assert all(type(m.inv(s)) is cls for s in 'GE ADJ LU CH LDL QR'.split()) cls = ImmutableSparseMatrix m = cls([[48, 49, 31], [ 9, 71, 94], [59, 28, 65]]) assert all(type(m.inv(s)) is cls for s in 'GE ADJ LU CH LDL QR'.split()) def test_matrix_inverse_mod(): A = Matrix(2, 1, [1, 0]) raises(NonSquareMatrixError, lambda: A.inv_mod(2)) A = Matrix(2, 2, [1, 0, 0, 0]) raises(ValueError, lambda: A.inv_mod(2)) A = Matrix(2, 2, [1, 2, 3, 4]) Ai = Matrix(2, 2, [1, 1, 0, 1]) assert A.inv_mod(3) == Ai A = Matrix(2, 2, [1, 0, 0, 1]) assert A.inv_mod(2) == A A = Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9]) raises(ValueError, lambda: A.inv_mod(5)) A = Matrix(3, 3, [5, 1, 3, 2, 6, 0, 2, 1, 1]) Ai = Matrix(3, 3, [6, 8, 0, 1, 5, 6, 5, 6, 4]) assert A.inv_mod(9) == Ai A = Matrix(3, 3, [1, 6, -3, 4, 1, -5, 3, -5, 5]) Ai = Matrix(3, 3, [4, 3, 3, 1, 2, 5, 1, 5, 1]) assert A.inv_mod(6) == Ai A = Matrix(3, 3, [1, 6, 1, 4, 1, 5, 3, 2, 5]) Ai = Matrix(3, 3, [6, 0, 3, 6, 6, 4, 1, 6, 1]) assert A.inv_mod(7) == Ai def test_jacobian_hessian(): L = Matrix(1, 2, [x**2*y, 2*y**2 + x*y]) syms = [x, y] assert L.jacobian(syms) == Matrix([[2*x*y, x**2], [y, 4*y + x]]) L = Matrix(1, 2, [x, x**2*y**3]) assert L.jacobian(syms) == Matrix([[1, 0], [2*x*y**3, x**2*3*y**2]]) f = x**2*y syms = [x, y] assert hessian(f, syms) == Matrix([[2*y, 2*x], [2*x, 0]]) f = x**2*y**3 assert hessian(f, syms) == \ Matrix([[2*y**3, 6*x*y**2], [6*x*y**2, 6*x**2*y]]) f = z + x*y**2 g = x**2 + 2*y**3 ans = Matrix([[0, 2*y], [2*y, 2*x]]) assert ans == hessian(f, Matrix([x, y])) assert ans == hessian(f, Matrix([x, y]).T) assert hessian(f, (y, x), [g]) == Matrix([ [ 0, 6*y**2, 2*x], [6*y**2, 2*x, 2*y], [ 2*x, 2*y, 0]]) def test_wronskian(): assert wronskian([cos(x), sin(x)], x) == cos(x)**2 + sin(x)**2 assert wronskian([exp(x), exp(2*x)], x) == exp(3*x) assert wronskian([exp(x), x], x) == exp(x) - x*exp(x) assert wronskian([1, x, x**2], x) == 2 w1 = -6*exp(x)*sin(x)*x + 6*cos(x)*exp(x)*x**2 - 6*exp(x)*cos(x)*x - \ exp(x)*cos(x)*x**3 + exp(x)*sin(x)*x**3 assert wronskian([exp(x), cos(x), x**3], x).expand() == w1 assert wronskian([exp(x), cos(x), x**3], x, method='berkowitz').expand() \ == w1 w2 = -x**3*cos(x)**2 - x**3*sin(x)**2 - 6*x*cos(x)**2 - 6*x*sin(x)**2 assert wronskian([sin(x), cos(x), x**3], x).expand() == w2 assert wronskian([sin(x), cos(x), x**3], x, method='berkowitz').expand() \ == w2 assert wronskian([], x) == 1 def test_subs(): assert Matrix([[1, x], [x, 4]]).subs(x, 5) == Matrix([[1, 5], [5, 4]]) assert Matrix([[x, 2], [x + y, 4]]).subs([[x, -1], [y, -2]]) == \ Matrix([[-1, 2], [-3, 4]]) assert Matrix([[x, 2], [x + y, 4]]).subs([(x, -1), (y, -2)]) == \ Matrix([[-1, 2], [-3, 4]]) assert Matrix([[x, 2], [x + y, 4]]).subs({x: -1, y: -2}) == \ Matrix([[-1, 2], [-3, 4]]) assert Matrix([x*y]).subs({x: y - 1, y: x - 1}, simultaneous=True) == \ Matrix([(x - 1)*(y - 1)]) for cls in classes: assert Matrix([[2, 0], [0, 2]]) == cls.eye(2).subs(1, 2) def test_xreplace(): assert Matrix([[1, x], [x, 4]]).xreplace({x: 5}) == \ Matrix([[1, 5], [5, 4]]) assert Matrix([[x, 2], [x + y, 4]]).xreplace({x: -1, y: -2}) == \ Matrix([[-1, 2], [-3, 4]]) for cls in classes: assert Matrix([[2, 0], [0, 2]]) == cls.eye(2).xreplace({1: 2}) def test_simplify(): n = Symbol('n') f = Function('f') M = Matrix([[ 1/x + 1/y, (x + x*y) / x ], [ (f(x) + y*f(x))/f(x), 2 * (1/n - cos(n * pi)/n) / pi ]]) M.simplify() assert M == Matrix([[ (x + y)/(x * y), 1 + y ], [ 1 + y, 2*((1 - 1*cos(pi*n))/(pi*n)) ]]) eq = (1 + x)**2 M = Matrix([[eq]]) M.simplify() assert M == Matrix([[eq]]) M.simplify(ratio=oo) == M assert M == Matrix([[eq.simplify(ratio=oo)]]) def test_transpose(): M = Matrix([[1, 2, 3, 4, 5, 6, 7, 8, 9, 0], [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]]) assert M.T == Matrix( [ [1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7], [8, 8], [9, 9], [0, 0] ]) assert M.T.T == M assert M.T == M.transpose() def test_conjugate(): M = Matrix([[0, I, 5], [1, 2, 0]]) assert M.T == Matrix([[0, 1], [I, 2], [5, 0]]) assert M.C == Matrix([[0, -I, 5], [1, 2, 0]]) assert M.C == M.conjugate() assert M.H == M.T.C assert M.H == Matrix([[ 0, 1], [-I, 2], [ 5, 0]]) def test_conj_dirac(): raises(AttributeError, lambda: eye(3).D) M = Matrix([[1, I, I, I], [0, 1, I, I], [0, 0, 1, I], [0, 0, 0, 1]]) assert M.D == Matrix([[ 1, 0, 0, 0], [-I, 1, 0, 0], [-I, -I, -1, 0], [-I, -I, I, -1]]) def test_trace(): M = Matrix([[1, 0, 0], [0, 5, 0], [0, 0, 8]]) assert M.trace() == 14 def test_shape(): M = Matrix([[x, 0, 0], [0, y, 0]]) assert M.shape == (2, 3) def test_col_row_op(): M = Matrix([[x, 0, 0], [0, y, 0]]) M.row_op(1, lambda r, j: r + j + 1) assert M == Matrix([[x, 0, 0], [1, y + 2, 3]]) M.col_op(0, lambda c, j: c + y**j) assert M == Matrix([[x + 1, 0, 0], [1 + y, y + 2, 3]]) # neither row nor slice give copies that allow the original matrix to # be changed assert M.row(0) == Matrix([[x + 1, 0, 0]]) r1 = M.row(0) r1[0] = 42 assert M[0, 0] == x + 1 r1 = M[0, :-1] # also testing negative slice r1[0] = 42 assert M[0, 0] == x + 1 c1 = M.col(0) assert c1 == Matrix([x + 1, 1 + y]) c1[0] = 0 assert M[0, 0] == x + 1 c1 = M[:, 0] c1[0] = 42 assert M[0, 0] == x + 1 def test_zip_row_op(): for cls in classes[:2]: # XXX: immutable matrices don't support row ops M = cls.eye(3) M.zip_row_op(1, 0, lambda v, u: v + 2*u) assert M == cls([[1, 0, 0], [2, 1, 0], [0, 0, 1]]) M = cls.eye(3)*2 M[0, 1] = -1 M.zip_row_op(1, 0, lambda v, u: v + 2*u); M assert M == cls([[2, -1, 0], [4, 0, 0], [0, 0, 2]]) def test_issue_3950(): m = Matrix([1, 2, 3]) a = Matrix([1, 2, 3]) b = Matrix([2, 2, 3]) assert not (m in []) assert not (m in [1]) assert m != 1 assert m == a assert m != b def test_issue_3981(): class Index1: def __index__(self): return 1 class Index2: def __index__(self): return 2 index1 = Index1() index2 = Index2() m = Matrix([1, 2, 3]) assert m[index2] == 3 m[index2] = 5 assert m[2] == 5 m = Matrix([[1, 2, 3], [4, 5, 6]]) assert m[index1, index2] == 6 assert m[1, index2] == 6 assert m[index1, 2] == 6 m[index1, index2] = 4 assert m[1, 2] == 4 m[1, index2] = 6 assert m[1, 2] == 6 m[index1, 2] = 8 assert m[1, 2] == 8 def test_evalf(): a = Matrix([sqrt(5), 6]) assert all(a.evalf()[i] == a[i].evalf() for i in range(2)) assert all(a.evalf(2)[i] == a[i].evalf(2) for i in range(2)) assert all(a.n(2)[i] == a[i].n(2) for i in range(2)) def test_is_symbolic(): a = Matrix([[x, x], [x, x]]) assert a.is_symbolic() is True a = Matrix([[1, 2, 3, 4], [5, 6, 7, 8]]) assert a.is_symbolic() is False a = Matrix([[1, 2, 3, 4], [5, 6, x, 8]]) assert a.is_symbolic() is True a = Matrix([[1, x, 3]]) assert a.is_symbolic() is True a = Matrix([[1, 2, 3]]) assert a.is_symbolic() is False a = Matrix([[1], [x], [3]]) assert a.is_symbolic() is True a = Matrix([[1], [2], [3]]) assert a.is_symbolic() is False def test_is_upper(): a = Matrix([[1, 2, 3]]) assert a.is_upper is True a = Matrix([[1], [2], [3]]) assert a.is_upper is False a = zeros(4, 2) assert a.is_upper is True def test_is_lower(): a = Matrix([[1, 2, 3]]) assert a.is_lower is False a = Matrix([[1], [2], [3]]) assert a.is_lower is True def test_is_nilpotent(): a = Matrix(4, 4, [0, 2, 1, 6, 0, 0, 1, 2, 0, 0, 0, 3, 0, 0, 0, 0]) assert a.is_nilpotent() a = Matrix([[1, 0], [0, 1]]) assert not a.is_nilpotent() a = Matrix([]) assert a.is_nilpotent() def test_zeros_ones_fill(): n, m = 3, 5 a = zeros(n, m) a.fill( 5 ) b = 5 * ones(n, m) assert a == b assert a.rows == b.rows == 3 assert a.cols == b.cols == 5 assert a.shape == b.shape == (3, 5) assert zeros(2) == zeros(2, 2) assert ones(2) == ones(2, 2) assert zeros(2, 3) == Matrix(2, 3, [0]*6) assert ones(2, 3) == Matrix(2, 3, [1]*6) def test_empty_zeros(): a = zeros(0) assert a == Matrix() a = zeros(0, 2) assert a.rows == 0 assert a.cols == 2 a = zeros(2, 0) assert a.rows == 2 assert a.cols == 0 def test_issue_3749(): a = Matrix([[x**2, x*y], [x*sin(y), x*cos(y)]]) assert a.diff(x) == Matrix([[2*x, y], [sin(y), cos(y)]]) assert Matrix([ [x, -x, x**2], [exp(x), 1/x - exp(-x), x + 1/x]]).limit(x, oo) == \ Matrix([[oo, -oo, oo], [oo, 0, oo]]) assert Matrix([ [(exp(x) - 1)/x, 2*x + y*x, x**x ], [1/x, abs(x), abs(sin(x + 1))]]).limit(x, 0) == \ Matrix([[1, 0, 1], [oo, 0, sin(1)]]) assert a.integrate(x) == Matrix([ [Rational(1, 3)*x**3, y*x**2/2], [x**2*sin(y)/2, x**2*cos(y)/2]]) def test_inv_iszerofunc(): A = eye(4) A.col_swap(0, 1) for method in "GE", "LU": assert A.inv(method=method, iszerofunc=lambda x: x == 0) == \ A.inv(method="ADJ") def test_jacobian_metrics(): rho, phi = symbols("rho,phi") X = Matrix([rho*cos(phi), rho*sin(phi)]) Y = Matrix([rho, phi]) J = X.jacobian(Y) assert J == X.jacobian(Y.T) assert J == (X.T).jacobian(Y) assert J == (X.T).jacobian(Y.T) g = J.T*eye(J.shape[0])*J g = g.applyfunc(trigsimp) assert g == Matrix([[1, 0], [0, rho**2]]) def test_jacobian2(): rho, phi = symbols("rho,phi") X = Matrix([rho*cos(phi), rho*sin(phi), rho**2]) Y = Matrix([rho, phi]) J = Matrix([ [cos(phi), -rho*sin(phi)], [sin(phi), rho*cos(phi)], [ 2*rho, 0], ]) assert X.jacobian(Y) == J def test_issue_4564(): X = Matrix([exp(x + y + z), exp(x + y + z), exp(x + y + z)]) Y = Matrix([x, y, z]) for i in range(1, 3): for j in range(1, 3): X_slice = X[:i, :] Y_slice = Y[:j, :] J = X_slice.jacobian(Y_slice) assert J.rows == i assert J.cols == j for k in range(j): assert J[:, k] == X_slice def test_nonvectorJacobian(): X = Matrix([[exp(x + y + z), exp(x + y + z)], [exp(x + y + z), exp(x + y + z)]]) raises(TypeError, lambda: X.jacobian(Matrix([x, y, z]))) X = X[0, :] Y = Matrix([[x, y], [x, z]]) raises(TypeError, lambda: X.jacobian(Y)) raises(TypeError, lambda: X.jacobian(Matrix([ [x, y], [x, z] ]))) def test_vec(): m = Matrix([[1, 3], [2, 4]]) m_vec = m.vec() assert m_vec.cols == 1 for i in range(4): assert m_vec[i] == i + 1 def test_vech(): m = Matrix([[1, 2], [2, 3]]) m_vech = m.vech() assert m_vech.cols == 1 for i in range(3): assert m_vech[i] == i + 1 m_vech = m.vech(diagonal=False) assert m_vech[0] == 2 m = Matrix([[1, x*(x + y)], [y*x + x**2, 1]]) m_vech = m.vech(diagonal=False) assert m_vech[0] == y*x + x**2 m = Matrix([[1, x*(x + y)], [y*x, 1]]) m_vech = m.vech(diagonal=False, check_symmetry=False) assert m_vech[0] == y*x raises(ShapeError, lambda: Matrix([[1, 3]]).vech()) raises(ValueError, lambda: Matrix([[1, 3], [2, 4]]).vech()) raises(ShapeError, lambda: Matrix([[1, 3]]).vech()) raises(ValueError, lambda: Matrix([[1, 3], [2, 4]]).vech()) def test_diag(): # mostly tested in testcommonmatrix.py assert diag([1, 2, 3]) == Matrix([1, 2, 3]) m = [1, 2, [3]] raises(ValueError, lambda: diag(m)) assert diag(m, strict=False) == Matrix([1, 2, 3]) def test_get_diag_blocks1(): a = Matrix([[1, 2], [2, 3]]) b = Matrix([[3, x], [y, 3]]) c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]]) assert a.get_diag_blocks() == [a] assert b.get_diag_blocks() == [b] assert c.get_diag_blocks() == [c] def test_get_diag_blocks2(): a = Matrix([[1, 2], [2, 3]]) b = Matrix([[3, x], [y, 3]]) c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]]) assert diag(a, b, b).get_diag_blocks() == [a, b, b] assert diag(a, b, c).get_diag_blocks() == [a, b, c] assert diag(a, c, b).get_diag_blocks() == [a, c, b] assert diag(c, c, b).get_diag_blocks() == [c, c, b] def test_inv_block(): a = Matrix([[1, 2], [2, 3]]) b = Matrix([[3, x], [y, 3]]) c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]]) A = diag(a, b, b) assert A.inv(try_block_diag=True) == diag(a.inv(), b.inv(), b.inv()) A = diag(a, b, c) assert A.inv(try_block_diag=True) == diag(a.inv(), b.inv(), c.inv()) A = diag(a, c, b) assert A.inv(try_block_diag=True) == diag(a.inv(), c.inv(), b.inv()) A = diag(a, a, b, a, c, a) assert A.inv(try_block_diag=True) == diag( a.inv(), a.inv(), b.inv(), a.inv(), c.inv(), a.inv()) assert A.inv(try_block_diag=True, method="ADJ") == diag( a.inv(method="ADJ"), a.inv(method="ADJ"), b.inv(method="ADJ"), a.inv(method="ADJ"), c.inv(method="ADJ"), a.inv(method="ADJ")) def test_creation_args(): """ Check that matrix dimensions can be specified using any reasonable type (see issue 4614). """ raises(ValueError, lambda: zeros(3, -1)) raises(TypeError, lambda: zeros(1, 2, 3, 4)) assert zeros(int(3)) == zeros(3) assert zeros(Integer(3)) == zeros(3) raises(ValueError, lambda: zeros(3.)) assert eye(int(3)) == eye(3) assert eye(Integer(3)) == eye(3) raises(ValueError, lambda: eye(3.)) assert ones(int(3), Integer(4)) == ones(3, 4) raises(TypeError, lambda: Matrix(5)) raises(TypeError, lambda: Matrix(1, 2)) raises(ValueError, lambda: Matrix([1, [2]])) def test_diagonal_symmetrical(): m = Matrix(2, 2, [0, 1, 1, 0]) assert not m.is_diagonal() assert m.is_symmetric() assert m.is_symmetric(simplify=False) m = Matrix(2, 2, [1, 0, 0, 1]) assert m.is_diagonal() m = diag(1, 2, 3) assert m.is_diagonal() assert m.is_symmetric() m = Matrix(3, 3, [1, 0, 0, 0, 2, 0, 0, 0, 3]) assert m == diag(1, 2, 3) m = Matrix(2, 3, zeros(2, 3)) assert not m.is_symmetric() assert m.is_diagonal() m = Matrix(((5, 0), (0, 6), (0, 0))) assert m.is_diagonal() m = Matrix(((5, 0, 0), (0, 6, 0))) assert m.is_diagonal() m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3]) assert m.is_symmetric() assert not m.is_symmetric(simplify=False) assert m.expand().is_symmetric(simplify=False) def test_diagonalization(): m = Matrix([[1, 2+I], [2-I, 3]]) assert m.is_diagonalizable() m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10]) assert not m.is_diagonalizable() assert not m.is_symmetric() raises(NonSquareMatrixError, lambda: m.diagonalize()) # diagonalizable m = diag(1, 2, 3) (P, D) = m.diagonalize() assert P == eye(3) assert D == m m = Matrix(2, 2, [0, 1, 1, 0]) assert m.is_symmetric() assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D m = Matrix(2, 2, [1, 0, 0, 3]) assert m.is_symmetric() assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D assert P == eye(2) assert D == m m = Matrix(2, 2, [1, 1, 0, 0]) assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D m = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2]) assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D for i in P: assert i.as_numer_denom()[1] == 1 m = Matrix(2, 2, [1, 0, 0, 0]) assert m.is_diagonal() assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D assert P == Matrix([[0, 1], [1, 0]]) # diagonalizable, complex only m = Matrix(2, 2, [0, 1, -1, 0]) assert not m.is_diagonalizable(True) raises(MatrixError, lambda: m.diagonalize(True)) assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D # not diagonalizable m = Matrix(2, 2, [0, 1, 0, 0]) assert not m.is_diagonalizable() raises(MatrixError, lambda: m.diagonalize()) m = Matrix(3, 3, [-3, 1, -3, 20, 3, 10, 2, -2, 4]) assert not m.is_diagonalizable() raises(MatrixError, lambda: m.diagonalize()) # symbolic a, b, c, d = symbols('a b c d') m = Matrix(2, 2, [a, c, c, b]) assert m.is_symmetric() assert m.is_diagonalizable() def test_issue_15887(): # Mutable matrix should not use cache a = MutableDenseMatrix([[0, 1], [1, 0]]) assert a.is_diagonalizable() is True a[1, 0] = 0 assert a.is_diagonalizable() is False a = MutableDenseMatrix([[0, 1], [1, 0]]) a.diagonalize() a[1, 0] = 0 raises(MatrixError, lambda: a.diagonalize()) # Test deprecated cache and kwargs with warns_deprecated_sympy(): a.is_diagonalizable(clear_cache=True) with warns_deprecated_sympy(): a.is_diagonalizable(clear_subproducts=True) def test_jordan_form(): m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10]) raises(NonSquareMatrixError, lambda: m.jordan_form()) # diagonalizable m = Matrix(3, 3, [7, -12, 6, 10, -19, 10, 12, -24, 13]) Jmust = Matrix(3, 3, [-1, 0, 0, 0, 1, 0, 0, 0, 1]) P, J = m.jordan_form() assert Jmust == J assert Jmust == m.diagonalize()[1] # m = Matrix(3, 3, [0, 6, 3, 1, 3, 1, -2, 2, 1]) # m.jordan_form() # very long # m.jordan_form() # # diagonalizable, complex only # Jordan cells # complexity: one of eigenvalues is zero m = Matrix(3, 3, [0, 1, 0, -4, 4, 0, -2, 1, 2]) # The blocks are ordered according to the value of their eigenvalues, # in order to make the matrix compatible with .diagonalize() Jmust = Matrix(3, 3, [2, 1, 0, 0, 2, 0, 0, 0, 2]) P, J = m.jordan_form() assert Jmust == J # complexity: all of eigenvalues are equal m = Matrix(3, 3, [2, 6, -15, 1, 1, -5, 1, 2, -6]) # Jmust = Matrix(3, 3, [-1, 0, 0, 0, -1, 1, 0, 0, -1]) # same here see 1456ff Jmust = Matrix(3, 3, [-1, 1, 0, 0, -1, 0, 0, 0, -1]) P, J = m.jordan_form() assert Jmust == J # complexity: two of eigenvalues are zero m = Matrix(3, 3, [4, -5, 2, 5, -7, 3, 6, -9, 4]) Jmust = Matrix(3, 3, [0, 1, 0, 0, 0, 0, 0, 0, 1]) P, J = m.jordan_form() assert Jmust == J m = Matrix(4, 4, [6, 5, -2, -3, -3, -1, 3, 3, 2, 1, -2, -3, -1, 1, 5, 5]) Jmust = Matrix(4, 4, [2, 1, 0, 0, 0, 2, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2] ) P, J = m.jordan_form() assert Jmust == J m = Matrix(4, 4, [6, 2, -8, -6, -3, 2, 9, 6, 2, -2, -8, -6, -1, 0, 3, 4]) # Jmust = Matrix(4, 4, [2, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2, 0, 0, 0, 0, -2]) # same here see 1456ff Jmust = Matrix(4, 4, [-2, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2, 0, 0, 0, 0, 2]) P, J = m.jordan_form() assert Jmust == J m = Matrix(4, 4, [5, 4, 2, 1, 0, 1, -1, -1, -1, -1, 3, 0, 1, 1, -1, 2]) assert not m.is_diagonalizable() Jmust = Matrix(4, 4, [1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 4, 1, 0, 0, 0, 4]) P, J = m.jordan_form() assert Jmust == J # checking for maximum precision to remain unchanged m = Matrix([[Float('1.0', precision=110), Float('2.0', precision=110)], [Float('3.14159265358979323846264338327', precision=110), Float('4.0', precision=110)]]) P, J = m.jordan_form() for term in J._mat: if isinstance(term, Float): assert term._prec == 110 def test_jordan_form_complex_issue_9274(): A = Matrix([[ 2, 4, 1, 0], [-4, 2, 0, 1], [ 0, 0, 2, 4], [ 0, 0, -4, 2]]) p = 2 - 4*I; q = 2 + 4*I; Jmust1 = Matrix([[p, 1, 0, 0], [0, p, 0, 0], [0, 0, q, 1], [0, 0, 0, q]]) Jmust2 = Matrix([[q, 1, 0, 0], [0, q, 0, 0], [0, 0, p, 1], [0, 0, 0, p]]) P, J = A.jordan_form() assert J == Jmust1 or J == Jmust2 assert simplify(P*J*P.inv()) == A def test_issue_10220(): # two non-orthogonal Jordan blocks with eigenvalue 1 M = Matrix([[1, 0, 0, 1], [0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1]]) P, J = M.jordan_form() assert P == Matrix([[0, 1, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]]) assert J == Matrix([ [1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) def test_jordan_form_issue_15858(): A = Matrix([ [1, 1, 1, 0], [-2, -1, 0, -1], [0, 0, -1, -1], [0, 0, 2, 1]]) (P, J) = A.jordan_form() assert P.expand() == Matrix([ [ -I, -I/2, I, I/2], [-1 + I, 0, -1 - I, 0], [ 0, -S(1)/2 - I/2, 0, -S(1)/2 + I/2], [ 0, 1, 0, 1]]) assert J == Matrix([ [-I, 1, 0, 0], [0, -I, 0, 0], [0, 0, I, 1], [0, 0, 0, I]]) def test_Matrix_berkowitz_charpoly(): UA, K_i, K_w = symbols('UA K_i K_w') A = Matrix([[-K_i - UA + K_i**2/(K_i + K_w), K_i*K_w/(K_i + K_w)], [ K_i*K_w/(K_i + K_w), -K_w + K_w**2/(K_i + K_w)]]) charpoly = A.charpoly(x) assert charpoly == \ Poly(x**2 + (K_i*UA + K_w*UA + 2*K_i*K_w)/(K_i + K_w)*x + K_i*K_w*UA/(K_i + K_w), x, domain='ZZ(K_i,K_w,UA)') assert type(charpoly) is PurePoly A = Matrix([[1, 3], [2, 0]]) assert A.charpoly() == A.charpoly(x) == PurePoly(x**2 - x - 6) A = Matrix([[1, 2], [x, 0]]) p = A.charpoly(x) assert p.gen != x assert p.as_expr().subs(p.gen, x) == x**2 - 3*x def test_exp_jordan_block(): l = Symbol('lamda') m = Matrix.jordan_block(1, l) assert m._eval_matrix_exp_jblock() == Matrix([[exp(l)]]) m = Matrix.jordan_block(3, l) assert m._eval_matrix_exp_jblock() == \ Matrix([ [exp(l), exp(l), exp(l)/2], [0, exp(l), exp(l)], [0, 0, exp(l)]]) def test_exp(): m = Matrix([[3, 4], [0, -2]]) m_exp = Matrix([[exp(3), -4*exp(-2)/5 + 4*exp(3)/5], [0, exp(-2)]]) assert m.exp() == m_exp assert exp(m) == m_exp m = Matrix([[1, 0], [0, 1]]) assert m.exp() == Matrix([[E, 0], [0, E]]) assert exp(m) == Matrix([[E, 0], [0, E]]) m = Matrix([[1, -1], [1, 1]]) assert m.exp() == Matrix([[E*cos(1), -E*sin(1)], [E*sin(1), E*cos(1)]]) def test_log(): l = Symbol('lamda') m = Matrix.jordan_block(1, l) assert m._eval_matrix_log_jblock() == Matrix([[log(l)]]) m = Matrix.jordan_block(4, l) assert m._eval_matrix_log_jblock() == \ Matrix( [ [log(l), 1/l, -1/(2*l**2), 1/(3*l**3)], [0, log(l), 1/l, -1/(2*l**2)], [0, 0, log(l), 1/l], [0, 0, 0, log(l)] ] ) m = Matrix( [[0, 0, 1], [0, 0, 0], [-1, 0, 0]] ) raises(MatrixError, lambda: m.log()) def test_has(): A = Matrix(((x, y), (2, 3))) assert A.has(x) assert not A.has(z) assert A.has(Symbol) A = A.subs(x, 2) assert not A.has(x) def test_find_reasonable_pivot_naive_finds_guaranteed_nonzero1(): # Test if matrices._find_reasonable_pivot_naive() # finds a guaranteed non-zero pivot when the # some of the candidate pivots are symbolic expressions. # Keyword argument: simpfunc=None indicates that no simplifications # should be performed during the search. x = Symbol('x') column = Matrix(3, 1, [x, cos(x)**2 + sin(x)**2, S.Half]) pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\ _find_reasonable_pivot_naive(column) assert pivot_val == S.Half def test_find_reasonable_pivot_naive_finds_guaranteed_nonzero2(): # Test if matrices._find_reasonable_pivot_naive() # finds a guaranteed non-zero pivot when the # some of the candidate pivots are symbolic expressions. # Keyword argument: simpfunc=_simplify indicates that the search # should attempt to simplify candidate pivots. x = Symbol('x') column = Matrix(3, 1, [x, cos(x)**2+sin(x)**2+x**2, cos(x)**2+sin(x)**2]) pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\ _find_reasonable_pivot_naive(column, simpfunc=_simplify) assert pivot_val == 1 def test_find_reasonable_pivot_naive_simplifies(): # Test if matrices._find_reasonable_pivot_naive() # simplifies candidate pivots, and reports # their offsets correctly. x = Symbol('x') column = Matrix(3, 1, [x, cos(x)**2+sin(x)**2+x, cos(x)**2+sin(x)**2]) pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\ _find_reasonable_pivot_naive(column, simpfunc=_simplify) assert len(simplified) == 2 assert simplified[0][0] == 1 assert simplified[0][1] == 1+x assert simplified[1][0] == 2 assert simplified[1][1] == 1 def test_errors(): raises(ValueError, lambda: Matrix([[1, 2], [1]])) raises(IndexError, lambda: Matrix([[1, 2]])[1.2, 5]) raises(IndexError, lambda: Matrix([[1, 2]])[1, 5.2]) raises(ValueError, lambda: randMatrix(3, c=4, symmetric=True)) raises(ValueError, lambda: Matrix([1, 2]).reshape(4, 6)) raises(ShapeError, lambda: Matrix([[1, 2], [3, 4]]).copyin_matrix([1, 0], Matrix([1, 2]))) raises(TypeError, lambda: Matrix([[1, 2], [3, 4]]).copyin_list([0, 1], set())) raises(NonSquareMatrixError, lambda: Matrix([[1, 2, 3], [2, 3, 0]]).inv()) raises(ShapeError, lambda: Matrix(1, 2, [1, 2]).row_join(Matrix([[1, 2], [3, 4]]))) raises( ShapeError, lambda: Matrix([1, 2]).col_join(Matrix([[1, 2], [3, 4]]))) raises(ShapeError, lambda: Matrix([1]).row_insert(1, Matrix([[1, 2], [3, 4]]))) raises(ShapeError, lambda: Matrix([1]).col_insert(1, Matrix([[1, 2], [3, 4]]))) raises(NonSquareMatrixError, lambda: Matrix([1, 2]).trace()) raises(TypeError, lambda: Matrix([1]).applyfunc(1)) raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).minor(4, 5)) raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).minor_submatrix(4, 5)) raises(TypeError, lambda: Matrix([1, 2, 3]).cross(1)) raises(TypeError, lambda: Matrix([1, 2, 3]).dot(1)) raises(ShapeError, lambda: Matrix([1, 2, 3]).dot(Matrix([1, 2]))) raises(ShapeError, lambda: Matrix([1, 2]).dot([])) raises(TypeError, lambda: Matrix([1, 2]).dot('a')) with warns_deprecated_sympy(): Matrix([[1, 2], [3, 4]]).dot(Matrix([[4, 3], [1, 2]])) raises(ShapeError, lambda: Matrix([1, 2]).dot([1, 2, 3])) raises(NonSquareMatrixError, lambda: Matrix([1, 2, 3]).exp()) raises(ShapeError, lambda: Matrix([[1, 2], [3, 4]]).normalized()) raises(ValueError, lambda: Matrix([1, 2]).inv(method='not a method')) raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_GE()) raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inverse_GE()) raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_ADJ()) raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inverse_ADJ()) raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_LU()) raises(NonSquareMatrixError, lambda: Matrix([1, 2]).is_nilpotent()) raises(NonSquareMatrixError, lambda: Matrix([1, 2]).det()) raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).det(method='Not a real method')) raises(ValueError, lambda: Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]).det(iszerofunc="Not function")) raises(ValueError, lambda: Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]).det(iszerofunc=False)) raises(ValueError, lambda: hessian(Matrix([[1, 2], [3, 4]]), Matrix([[1, 2], [2, 1]]))) raises(ValueError, lambda: hessian(Matrix([[1, 2], [3, 4]]), [])) raises(ValueError, lambda: hessian(Symbol('x')**2, 'a')) raises(IndexError, lambda: eye(3)[5, 2]) raises(IndexError, lambda: eye(3)[2, 5]) M = Matrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16))) raises(ValueError, lambda: M.det('method=LU_decomposition()')) V = Matrix([[10, 10, 10]]) M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) raises(ValueError, lambda: M.row_insert(4.7, V)) M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) raises(ValueError, lambda: M.col_insert(-4.2, V)) def test_len(): assert len(Matrix()) == 0 assert len(Matrix([[1, 2]])) == len(Matrix([[1], [2]])) == 2 assert len(Matrix(0, 2, lambda i, j: 0)) == \ len(Matrix(2, 0, lambda i, j: 0)) == 0 assert len(Matrix([[0, 1, 2], [3, 4, 5]])) == 6 assert Matrix([1]) == Matrix([[1]]) assert not Matrix() assert Matrix() == Matrix([]) def test_integrate(): A = Matrix(((1, 4, x), (y, 2, 4), (10, 5, x**2))) assert A.integrate(x) == \ Matrix(((x, 4*x, x**2/2), (x*y, 2*x, 4*x), (10*x, 5*x, x**3/3))) assert A.integrate(y) == \ Matrix(((y, 4*y, x*y), (y**2/2, 2*y, 4*y), (10*y, 5*y, y*x**2))) def test_limit(): A = Matrix(((1, 4, sin(x)/x), (y, 2, 4), (10, 5, x**2 + 1))) assert A.limit(x, 0) == Matrix(((1, 4, 1), (y, 2, 4), (10, 5, 1))) def test_diff(): A = MutableDenseMatrix(((1, 4, x), (y, 2, 4), (10, 5, x**2 + 1))) assert isinstance(A.diff(x), type(A)) assert A.diff(x) == MutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x))) assert A.diff(y) == MutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0))) assert diff(A, x) == MutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x))) assert diff(A, y) == MutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0))) A_imm = A.as_immutable() assert isinstance(A_imm.diff(x), type(A_imm)) assert A_imm.diff(x) == ImmutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x))) assert A_imm.diff(y) == ImmutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0))) assert diff(A_imm, x) == ImmutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x))) assert diff(A_imm, y) == ImmutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0))) def test_diff_by_matrix(): # Derive matrix by matrix: A = MutableDenseMatrix([[x, y], [z, t]]) assert A.diff(A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]]) assert diff(A, A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]]) A_imm = A.as_immutable() assert A_imm.diff(A_imm) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]]) assert diff(A_imm, A_imm) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]]) # Derive a constant matrix: assert A.diff(a) == MutableDenseMatrix([[0, 0], [0, 0]]) B = ImmutableDenseMatrix([a, b]) assert A.diff(B) == Array.zeros(2, 1, 2, 2) assert A.diff(A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]]) # Test diff with tuples: dB = B.diff([[a, b]]) assert dB.shape == (2, 2, 1) assert dB == Array([[[1], [0]], [[0], [1]]]) f = Function("f") fxyz = f(x, y, z) assert fxyz.diff([[x, y, z]]) == Array([fxyz.diff(x), fxyz.diff(y), fxyz.diff(z)]) assert fxyz.diff(([x, y, z], 2)) == Array([ [fxyz.diff(x, 2), fxyz.diff(x, y), fxyz.diff(x, z)], [fxyz.diff(x, y), fxyz.diff(y, 2), fxyz.diff(y, z)], [fxyz.diff(x, z), fxyz.diff(z, y), fxyz.diff(z, 2)], ]) expr = sin(x)*exp(y) assert expr.diff([[x, y]]) == Array([cos(x)*exp(y), sin(x)*exp(y)]) assert expr.diff(y, ((x, y),)) == Array([cos(x)*exp(y), sin(x)*exp(y)]) assert expr.diff(x, ((x, y),)) == Array([-sin(x)*exp(y), cos(x)*exp(y)]) assert expr.diff(((y, x),), [[x, y]]) == Array([[cos(x)*exp(y), -sin(x)*exp(y)], [sin(x)*exp(y), cos(x)*exp(y)]]) # Test different notations: fxyz.diff(x).diff(y).diff(x) == fxyz.diff(((x, y, z),), 3)[0, 1, 0] fxyz.diff(z).diff(y).diff(x) == fxyz.diff(((x, y, z),), 3)[2, 1, 0] fxyz.diff([[x, y, z]], ((z, y, x),)) == Array([[fxyz.diff(i).diff(j) for i in (x, y, z)] for j in (z, y, x)]) # Test scalar derived by matrix remains matrix: res = x.diff(Matrix([[x, y]])) assert isinstance(res, ImmutableDenseMatrix) assert res == Matrix([[1, 0]]) res = (x**3).diff(Matrix([[x, y]])) assert isinstance(res, ImmutableDenseMatrix) assert res == Matrix([[3*x**2, 0]]) def test_getattr(): A = Matrix(((1, 4, x), (y, 2, 4), (10, 5, x**2 + 1))) raises(AttributeError, lambda: A.nonexistantattribute) assert getattr(A, 'diff')(x) == Matrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x))) def test_hessenberg(): A = Matrix([[3, 4, 1], [2, 4, 5], [0, 1, 2]]) assert A.is_upper_hessenberg A = A.T assert A.is_lower_hessenberg A[0, -1] = 1 assert A.is_lower_hessenberg is False A = Matrix([[3, 4, 1], [2, 4, 5], [3, 1, 2]]) assert not A.is_upper_hessenberg A = zeros(5, 2) assert A.is_upper_hessenberg def test_cholesky(): raises(NonSquareMatrixError, lambda: Matrix((1, 2)).cholesky()) raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).cholesky()) raises(ValueError, lambda: Matrix(((5 + I, 0), (0, 1))).cholesky()) raises(ValueError, lambda: Matrix(((1, 5), (5, 1))).cholesky()) raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).cholesky(hermitian=False)) assert Matrix(((5 + I, 0), (0, 1))).cholesky(hermitian=False) == Matrix([ [sqrt(5 + I), 0], [0, 1]]) A = Matrix(((1, 5), (5, 1))) L = A.cholesky(hermitian=False) assert L == Matrix([[1, 0], [5, 2*sqrt(6)*I]]) assert L*L.T == A A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) L = A.cholesky() assert L * L.T == A assert L.is_lower assert L == Matrix([[5, 0, 0], [3, 3, 0], [-1, 1, 3]]) A = Matrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11))) assert A.cholesky().expand() == Matrix(((2, 0, 0), (I, 1, 0), (1 - I, 0, 3))) raises(NonSquareMatrixError, lambda: SparseMatrix((1, 2)).cholesky()) raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).cholesky()) raises(ValueError, lambda: SparseMatrix(((5 + I, 0), (0, 1))).cholesky()) raises(ValueError, lambda: SparseMatrix(((1, 5), (5, 1))).cholesky()) raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).cholesky(hermitian=False)) assert SparseMatrix(((5 + I, 0), (0, 1))).cholesky(hermitian=False) == Matrix([ [sqrt(5 + I), 0], [0, 1]]) A = SparseMatrix(((1, 5), (5, 1))) L = A.cholesky(hermitian=False) assert L == Matrix([[1, 0], [5, 2*sqrt(6)*I]]) assert L*L.T == A A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) L = A.cholesky() assert L * L.T == A assert L.is_lower assert L == Matrix([[5, 0, 0], [3, 3, 0], [-1, 1, 3]]) A = SparseMatrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11))) assert A.cholesky() == Matrix(((2, 0, 0), (I, 1, 0), (1 - I, 0, 3))) def test_matrix_norm(): # Vector Tests # Test columns and symbols x = Symbol('x', real=True) v = Matrix([cos(x), sin(x)]) assert trigsimp(v.norm(2)) == 1 assert v.norm(10) == Pow(cos(x)**10 + sin(x)**10, Rational(1, 10)) # Test Rows A = Matrix([[5, Rational(3, 2)]]) assert A.norm() == Pow(25 + Rational(9, 4), S.Half) assert A.norm(oo) == max(A._mat) assert A.norm(-oo) == min(A._mat) # Matrix Tests # Intuitive test A = Matrix([[1, 1], [1, 1]]) assert A.norm(2) == 2 assert A.norm(-2) == 0 assert A.norm('frobenius') == 2 assert eye(10).norm(2) == eye(10).norm(-2) == 1 assert A.norm(oo) == 2 # Test with Symbols and more complex entries A = Matrix([[3, y, y], [x, S.Half, -pi]]) assert (A.norm('fro') == sqrt(Rational(37, 4) + 2*abs(y)**2 + pi**2 + x**2)) # Check non-square A = Matrix([[1, 2, -3], [4, 5, Rational(13, 2)]]) assert A.norm(2) == sqrt(Rational(389, 8) + sqrt(78665)/8) assert A.norm(-2) is S.Zero assert A.norm('frobenius') == sqrt(389)/2 # Test properties of matrix norms # https://en.wikipedia.org/wiki/Matrix_norm#Definition # Two matrices A = Matrix([[1, 2], [3, 4]]) B = Matrix([[5, 5], [-2, 2]]) C = Matrix([[0, -I], [I, 0]]) D = Matrix([[1, 0], [0, -1]]) L = [A, B, C, D] alpha = Symbol('alpha', real=True) for order in ['fro', 2, -2]: # Zero Check assert zeros(3).norm(order) is S.Zero # Check Triangle Inequality for all Pairs of Matrices for X in L: for Y in L: dif = (X.norm(order) + Y.norm(order) - (X + Y).norm(order)) assert (dif >= 0) # Scalar multiplication linearity for M in [A, B, C, D]: dif = simplify((alpha*M).norm(order) - abs(alpha) * M.norm(order)) assert dif == 0 # Test Properties of Vector Norms # https://en.wikipedia.org/wiki/Vector_norm # Two column vectors a = Matrix([1, 1 - 1*I, -3]) b = Matrix([S.Half, 1*I, 1]) c = Matrix([-1, -1, -1]) d = Matrix([3, 2, I]) e = Matrix([Integer(1e2), Rational(1, 1e2), 1]) L = [a, b, c, d, e] alpha = Symbol('alpha', real=True) for order in [1, 2, -1, -2, S.Infinity, S.NegativeInfinity, pi]: # Zero Check if order > 0: assert Matrix([0, 0, 0]).norm(order) is S.Zero # Triangle inequality on all pairs if order >= 1: # Triangle InEq holds only for these norms for X in L: for Y in L: dif = (X.norm(order) + Y.norm(order) - (X + Y).norm(order)) assert simplify(dif >= 0) is S.true # Linear to scalar multiplication if order in [1, 2, -1, -2, S.Infinity, S.NegativeInfinity]: for X in L: dif = simplify((alpha*X).norm(order) - (abs(alpha) * X.norm(order))) assert dif == 0 # ord=1 M = Matrix(3, 3, [1, 3, 0, -2, -1, 0, 3, 9, 6]) assert M.norm(1) == 13 def test_condition_number(): x = Symbol('x', real=True) A = eye(3) A[0, 0] = 10 A[2, 2] = Rational(1, 10) assert A.condition_number() == 100 A[1, 1] = x assert A.condition_number() == Max(10, Abs(x)) / Min(Rational(1, 10), Abs(x)) M = Matrix([[cos(x), sin(x)], [-sin(x), cos(x)]]) Mc = M.condition_number() assert all(Float(1.).epsilon_eq(Mc.subs(x, val).evalf()) for val in [Rational(1, 5), S.Half, Rational(1, 10), pi/2, pi, pi*Rational(7, 4) ]) #issue 10782 assert Matrix([]).condition_number() == 0 def test_equality(): A = Matrix(((1, 2, 3), (4, 5, 6), (7, 8, 9))) B = Matrix(((9, 8, 7), (6, 5, 4), (3, 2, 1))) assert A == A[:, :] assert not A != A[:, :] assert not A == B assert A != B assert A != 10 assert not A == 10 # A SparseMatrix can be equal to a Matrix C = SparseMatrix(((1, 0, 0), (0, 1, 0), (0, 0, 1))) D = Matrix(((1, 0, 0), (0, 1, 0), (0, 0, 1))) assert C == D assert not C != D def test_col_join(): assert eye(3).col_join(Matrix([[7, 7, 7]])) == \ Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1], [7, 7, 7]]) def test_row_insert(): r4 = Matrix([[4, 4, 4]]) for i in range(-4, 5): l = [1, 0, 0] l.insert(i, 4) assert flatten(eye(3).row_insert(i, r4).col(0).tolist()) == l def test_col_insert(): c4 = Matrix([4, 4, 4]) for i in range(-4, 5): l = [0, 0, 0] l.insert(i, 4) assert flatten(zeros(3).col_insert(i, c4).row(0).tolist()) == l def test_normalized(): assert Matrix([3, 4]).normalized() == \ Matrix([Rational(3, 5), Rational(4, 5)]) # Zero vector trivial cases assert Matrix([0, 0, 0]).normalized() == Matrix([0, 0, 0]) # Machine precision error truncation trivial cases m = Matrix([0,0,1.e-100]) assert m.normalized( iszerofunc=lambda x: x.evalf(n=10, chop=True).is_zero ) == Matrix([0, 0, 0]) def test_print_nonzero(): assert capture(lambda: eye(3).print_nonzero()) == \ '[X ]\n[ X ]\n[ X]\n' assert capture(lambda: eye(3).print_nonzero('.')) == \ '[. ]\n[ . ]\n[ .]\n' def test_zeros_eye(): assert Matrix.eye(3) == eye(3) assert Matrix.zeros(3) == zeros(3) assert ones(3, 4) == Matrix(3, 4, [1]*12) i = Matrix([[1, 0], [0, 1]]) z = Matrix([[0, 0], [0, 0]]) for cls in classes: m = cls.eye(2) assert i == m # but m == i will fail if m is immutable assert i == eye(2, cls=cls) assert type(m) == cls m = cls.zeros(2) assert z == m assert z == zeros(2, cls=cls) assert type(m) == cls def test_is_zero(): assert Matrix().is_zero_matrix assert Matrix([[0, 0], [0, 0]]).is_zero_matrix assert zeros(3, 4).is_zero_matrix assert not eye(3).is_zero_matrix assert Matrix([[x, 0], [0, 0]]).is_zero_matrix == None assert SparseMatrix([[x, 0], [0, 0]]).is_zero_matrix == None assert ImmutableMatrix([[x, 0], [0, 0]]).is_zero_matrix == None assert ImmutableSparseMatrix([[x, 0], [0, 0]]).is_zero_matrix == None assert Matrix([[x, 1], [0, 0]]).is_zero_matrix == False a = Symbol('a', nonzero=True) assert Matrix([[a, 0], [0, 0]]).is_zero_matrix == False def test_rotation_matrices(): # This tests the rotation matrices by rotating about an axis and back. theta = pi/3 r3_plus = rot_axis3(theta) r3_minus = rot_axis3(-theta) r2_plus = rot_axis2(theta) r2_minus = rot_axis2(-theta) r1_plus = rot_axis1(theta) r1_minus = rot_axis1(-theta) assert r3_minus*r3_plus*eye(3) == eye(3) assert r2_minus*r2_plus*eye(3) == eye(3) assert r1_minus*r1_plus*eye(3) == eye(3) # Check the correctness of the trace of the rotation matrix assert r1_plus.trace() == 1 + 2*cos(theta) assert r2_plus.trace() == 1 + 2*cos(theta) assert r3_plus.trace() == 1 + 2*cos(theta) # Check that a rotation with zero angle doesn't change anything. assert rot_axis1(0) == eye(3) assert rot_axis2(0) == eye(3) assert rot_axis3(0) == eye(3) def test_DeferredVector(): assert str(DeferredVector("vector")[4]) == "vector[4]" assert sympify(DeferredVector("d")) == DeferredVector("d") raises(IndexError, lambda: DeferredVector("d")[-1]) assert str(DeferredVector("d")) == "d" assert repr(DeferredVector("test")) == "DeferredVector('test')" def test_DeferredVector_not_iterable(): assert not iterable(DeferredVector('X')) def test_DeferredVector_Matrix(): raises(TypeError, lambda: Matrix(DeferredVector("V"))) def test_GramSchmidt(): R = Rational m1 = Matrix(1, 2, [1, 2]) m2 = Matrix(1, 2, [2, 3]) assert GramSchmidt([m1, m2]) == \ [Matrix(1, 2, [1, 2]), Matrix(1, 2, [R(2)/5, R(-1)/5])] assert GramSchmidt([m1.T, m2.T]) == \ [Matrix(2, 1, [1, 2]), Matrix(2, 1, [R(2)/5, R(-1)/5])] # from wikipedia assert GramSchmidt([Matrix([3, 1]), Matrix([2, 2])], True) == [ Matrix([3*sqrt(10)/10, sqrt(10)/10]), Matrix([-sqrt(10)/10, 3*sqrt(10)/10])] def test_casoratian(): assert casoratian([1, 2, 3, 4], 1) == 0 assert casoratian([1, 2, 3, 4], 1, zero=False) == 0 def test_zero_dimension_multiply(): assert (Matrix()*zeros(0, 3)).shape == (0, 3) assert zeros(3, 0)*zeros(0, 3) == zeros(3, 3) assert zeros(0, 3)*zeros(3, 0) == Matrix() def test_slice_issue_2884(): m = Matrix(2, 2, range(4)) assert m[1, :] == Matrix([[2, 3]]) assert m[-1, :] == Matrix([[2, 3]]) assert m[:, 1] == Matrix([[1, 3]]).T assert m[:, -1] == Matrix([[1, 3]]).T raises(IndexError, lambda: m[2, :]) raises(IndexError, lambda: m[2, 2]) def test_slice_issue_3401(): assert zeros(0, 3)[:, -1].shape == (0, 1) assert zeros(3, 0)[0, :] == Matrix(1, 0, []) def test_copyin(): s = zeros(3, 3) s[3] = 1 assert s[:, 0] == Matrix([0, 1, 0]) assert s[3] == 1 assert s[3: 4] == [1] s[1, 1] = 42 assert s[1, 1] == 42 assert s[1, 1:] == Matrix([[42, 0]]) s[1, 1:] = Matrix([[5, 6]]) assert s[1, :] == Matrix([[1, 5, 6]]) s[1, 1:] = [[42, 43]] assert s[1, :] == Matrix([[1, 42, 43]]) s[0, 0] = 17 assert s[:, :1] == Matrix([17, 1, 0]) s[0, 0] = [1, 1, 1] assert s[:, 0] == Matrix([1, 1, 1]) s[0, 0] = Matrix([1, 1, 1]) assert s[:, 0] == Matrix([1, 1, 1]) s[0, 0] = SparseMatrix([1, 1, 1]) assert s[:, 0] == Matrix([1, 1, 1]) def test_invertible_check(): # sometimes a singular matrix will have a pivot vector shorter than # the number of rows in a matrix... assert Matrix([[1, 2], [1, 2]]).rref() == (Matrix([[1, 2], [0, 0]]), (0,)) raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inv()) m = Matrix([ [-1, -1, 0], [ x, 1, 1], [ 1, x, -1], ]) assert len(m.rref()[1]) != m.rows # in addition, unless simplify=True in the call to rref, the identity # matrix will be returned even though m is not invertible assert m.rref()[0] != eye(3) assert m.rref(simplify=signsimp)[0] != eye(3) raises(ValueError, lambda: m.inv(method="ADJ")) raises(ValueError, lambda: m.inv(method="GE")) raises(ValueError, lambda: m.inv(method="LU")) def test_issue_3959(): x, y = symbols('x, y') e = x*y assert e.subs(x, Matrix([3, 5, 3])) == Matrix([3, 5, 3])*y def test_issue_5964(): assert str(Matrix([[1, 2], [3, 4]])) == 'Matrix([[1, 2], [3, 4]])' def test_issue_7604(): x, y = symbols("x y") assert sstr(Matrix([[x, 2*y], [y**2, x + 3]])) == \ 'Matrix([\n[ x, 2*y],\n[y**2, x + 3]])' def test_is_Identity(): assert eye(3).is_Identity assert eye(3).as_immutable().is_Identity assert not zeros(3).is_Identity assert not ones(3).is_Identity # issue 6242 assert not Matrix([[1, 0, 0]]).is_Identity # issue 8854 assert SparseMatrix(3,3, {(0,0):1, (1,1):1, (2,2):1}).is_Identity assert not SparseMatrix(2,3, range(6)).is_Identity assert not SparseMatrix(3,3, {(0,0):1, (1,1):1}).is_Identity assert not SparseMatrix(3,3, {(0,0):1, (1,1):1, (2,2):1, (0,1):2, (0,2):3}).is_Identity def test_dot(): assert ones(1, 3).dot(ones(3, 1)) == 3 assert ones(1, 3).dot([1, 1, 1]) == 3 assert Matrix([1, 2, 3]).dot(Matrix([1, 2, 3])) == 14 assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I])) == -5 + I assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=False) == -5 + I assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=True) == 13 + I assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=True, conjugate_convention="physics") == 13 - I assert Matrix([1, 2, 3*I]).dot(Matrix([4, 5*I, 6]), hermitian=True, conjugate_convention="right") == 4 + 8*I assert Matrix([1, 2, 3*I]).dot(Matrix([4, 5*I, 6]), hermitian=True, conjugate_convention="left") == 4 - 8*I assert Matrix([I, 2*I]).dot(Matrix([I, 2*I]), hermitian=False, conjugate_convention="left") == -5 assert Matrix([I, 2*I]).dot(Matrix([I, 2*I]), conjugate_convention="left") == 5 raises(ValueError, lambda: Matrix([1, 2]).dot(Matrix([3, 4]), hermitian=True, conjugate_convention="test")) def test_dual(): B_x, B_y, B_z, E_x, E_y, E_z = symbols( 'B_x B_y B_z E_x E_y E_z', real=True) F = Matrix(( ( 0, E_x, E_y, E_z), (-E_x, 0, B_z, -B_y), (-E_y, -B_z, 0, B_x), (-E_z, B_y, -B_x, 0) )) Fd = Matrix(( ( 0, -B_x, -B_y, -B_z), (B_x, 0, E_z, -E_y), (B_y, -E_z, 0, E_x), (B_z, E_y, -E_x, 0) )) assert F.dual().equals(Fd) assert eye(3).dual().equals(zeros(3)) assert F.dual().dual().equals(-F) def test_anti_symmetric(): assert Matrix([1, 2]).is_anti_symmetric() is False m = Matrix(3, 3, [0, x**2 + 2*x + 1, y, -(x + 1)**2, 0, x*y, -y, -x*y, 0]) assert m.is_anti_symmetric() is True assert m.is_anti_symmetric(simplify=False) is False assert m.is_anti_symmetric(simplify=lambda x: x) is False # tweak to fail m[2, 1] = -m[2, 1] assert m.is_anti_symmetric() is False # untweak m[2, 1] = -m[2, 1] m = m.expand() assert m.is_anti_symmetric(simplify=False) is True m[0, 0] = 1 assert m.is_anti_symmetric() is False def test_normalize_sort_diogonalization(): A = Matrix(((1, 2), (2, 1))) P, Q = A.diagonalize(normalize=True) assert P*P.T == P.T*P == eye(P.cols) P, Q = A.diagonalize(normalize=True, sort=True) assert P*P.T == P.T*P == eye(P.cols) assert P*Q*P.inv() == A def test_issue_5321(): raises(ValueError, lambda: Matrix([[1, 2, 3], Matrix(0, 1, [])])) def test_issue_5320(): assert Matrix.hstack(eye(2), 2*eye(2)) == Matrix([ [1, 0, 2, 0], [0, 1, 0, 2] ]) assert Matrix.vstack(eye(2), 2*eye(2)) == Matrix([ [1, 0], [0, 1], [2, 0], [0, 2] ]) cls = SparseMatrix assert cls.hstack(cls(eye(2)), cls(2*eye(2))) == Matrix([ [1, 0, 2, 0], [0, 1, 0, 2] ]) def test_issue_11944(): A = Matrix([[1]]) AIm = sympify(A) assert Matrix.hstack(AIm, A) == Matrix([[1, 1]]) assert Matrix.vstack(AIm, A) == Matrix([[1], [1]]) def test_cross(): a = [1, 2, 3] b = [3, 4, 5] col = Matrix([-2, 4, -2]) row = col.T def test(M, ans): assert ans == M assert type(M) == cls for cls in classes: A = cls(a) B = cls(b) test(A.cross(B), col) test(A.cross(B.T), col) test(A.T.cross(B.T), row) test(A.T.cross(B), row) raises(ShapeError, lambda: Matrix(1, 2, [1, 1]).cross(Matrix(1, 2, [1, 1]))) def test_hash(): for cls in classes[-2:]: s = {cls.eye(1), cls.eye(1)} assert len(s) == 1 and s.pop() == cls.eye(1) # issue 3979 for cls in classes[:2]: assert not isinstance(cls.eye(1), Hashable) @XFAIL def test_issue_3979(): # when this passes, delete this and change the [1:2] # to [:2] in the test_hash above for issue 3979 cls = classes[0] raises(AttributeError, lambda: hash(cls.eye(1))) def test_adjoint(): dat = [[0, I], [1, 0]] ans = Matrix([[0, 1], [-I, 0]]) for cls in classes: assert ans == cls(dat).adjoint() def test_simplify_immutable(): from sympy import simplify, sin, cos assert simplify(ImmutableMatrix([[sin(x)**2 + cos(x)**2]])) == \ ImmutableMatrix([[1]]) def test_replace(): from sympy import symbols, Function, Matrix F, G = symbols('F, G', cls=Function) K = Matrix(2, 2, lambda i, j: G(i+j)) M = Matrix(2, 2, lambda i, j: F(i+j)) N = M.replace(F, G) assert N == K def test_replace_map(): from sympy import symbols, Function, Matrix F, G = symbols('F, G', cls=Function) K = Matrix(2, 2, [(G(0), {F(0): G(0)}), (G(1), {F(1): G(1)}), (G(1), {F(1)\ : G(1)}), (G(2), {F(2): G(2)})]) M = Matrix(2, 2, lambda i, j: F(i+j)) N = M.replace(F, G, True) assert N == K def test_atoms(): m = Matrix([[1, 2], [x, 1 - 1/x]]) assert m.atoms() == {S.One,S(2),S.NegativeOne, x} assert m.atoms(Symbol) == {x} def test_pinv(): # Pseudoinverse of an invertible matrix is the inverse. A1 = Matrix([[a, b], [c, d]]) assert simplify(A1.pinv(method="RD")) == simplify(A1.inv()) # Test the four properties of the pseudoinverse for various matrices. As = [Matrix([[13, 104], [2212, 3], [-3, 5]]), Matrix([[1, 7, 9], [11, 17, 19]]), Matrix([a, b])] for A in As: A_pinv = A.pinv(method="RD") AAp = A * A_pinv ApA = A_pinv * A assert simplify(AAp * A) == A assert simplify(ApA * A_pinv) == A_pinv assert AAp.H == AAp assert ApA.H == ApA # XXX Pinv with diagonalization makes expression too complicated. for A in As: A_pinv = simplify(A.pinv(method="ED")) AAp = A * A_pinv ApA = A_pinv * A assert simplify(AAp * A) == A assert simplify(ApA * A_pinv) == A_pinv assert AAp.H == AAp assert ApA.H == ApA # XXX Computing pinv using diagonalization makes an expression that # is too complicated to simplify. # A1 = Matrix([[a, b], [c, d]]) # assert simplify(A1.pinv(method="ED")) == simplify(A1.inv()) # so this is tested numerically at a fixed random point from sympy.core.numbers import comp q = A1.pinv(method="ED") w = A1.inv() reps = {a: -73633, b: 11362, c: 55486, d: 62570} assert all( comp(i.n(), j.n()) for i, j in zip(q.subs(reps), w.subs(reps)) ) @XFAIL def test_pinv_rank_deficient_when_diagonalization_fails(): # Test the four properties of the pseudoinverse for matrices when # diagonalization of A.H*A fails. As = [Matrix([ [61, 89, 55, 20, 71, 0], [62, 96, 85, 85, 16, 0], [69, 56, 17, 4, 54, 0], [10, 54, 91, 41, 71, 0], [ 7, 30, 10, 48, 90, 0], [0,0,0,0,0,0]])] for A in As: A_pinv = A.pinv(method="ED") AAp = A * A_pinv ApA = A_pinv * A assert simplify(AAp * A) == A assert simplify(ApA * A_pinv) == A_pinv assert AAp.H == AAp assert ApA.H == ApA def test_issue_7201(): assert ones(0, 1) + ones(0, 1) == Matrix(0, 1, []) assert ones(1, 0) + ones(1, 0) == Matrix(1, 0, []) def test_free_symbols(): for M in ImmutableMatrix, ImmutableSparseMatrix, Matrix, SparseMatrix: assert M([[x], [0]]).free_symbols == {x} def test_from_ndarray(): """See issue 7465.""" try: from numpy import array except ImportError: skip('NumPy must be available to test creating matrices from ndarrays') assert Matrix(array([1, 2, 3])) == Matrix([1, 2, 3]) assert Matrix(array([[1, 2, 3]])) == Matrix([[1, 2, 3]]) assert Matrix(array([[1, 2, 3], [4, 5, 6]])) == \ Matrix([[1, 2, 3], [4, 5, 6]]) assert Matrix(array([x, y, z])) == Matrix([x, y, z]) raises(NotImplementedError, lambda: Matrix(array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]))) assert Matrix([array([1, 2]), array([3, 4])]) == Matrix([[1, 2], [3, 4]]) assert Matrix([array([1, 2]), [3, 4]]) == Matrix([[1, 2], [3, 4]]) assert Matrix([array([]), array([])]) == Matrix([]) def test_17522_numpy(): from sympy.matrices.common import _matrixify try: from numpy import array, matrix except ImportError: skip('NumPy must be available to test indexing matrixified NumPy ndarrays and matrices') m = _matrixify(array([[1, 2], [3, 4]])) assert m[3] == 4 assert list(m) == [1, 2, 3, 4] m = _matrixify(matrix([[1, 2], [3, 4]])) assert m[3] == 4 assert list(m) == [1, 2, 3, 4] def test_17522_mpmath(): from sympy.matrices.common import _matrixify try: from mpmath import matrix except ImportError: skip('mpmath must be available to test indexing matrixified mpmath matrices') m = _matrixify(matrix([[1, 2], [3, 4]])) assert m[3] == 4 assert list(m) == [1, 2, 3, 4] def test_17522_scipy(): from sympy.matrices.common import _matrixify try: from scipy.sparse import csr_matrix except ImportError: skip('SciPy must be available to test indexing matrixified SciPy sparse matrices') m = _matrixify(csr_matrix([[1, 2], [3, 4]])) assert m[3] == 4 assert list(m) == [1, 2, 3, 4] def test_hermitian(): a = Matrix([[1, I], [-I, 1]]) assert a.is_hermitian a[0, 0] = 2*I assert a.is_hermitian is False a[0, 0] = x assert a.is_hermitian is None a[0, 1] = a[1, 0]*I assert a.is_hermitian is False def test_doit(): a = Matrix([[Add(x,x, evaluate=False)]]) assert a[0] != 2*x assert a.doit() == Matrix([[2*x]]) def test_issue_9457_9467_9876(): # for row_del(index) M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) M.row_del(1) assert M == Matrix([[1, 2, 3], [3, 4, 5]]) N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) N.row_del(-2) assert N == Matrix([[1, 2, 3], [3, 4, 5]]) O = Matrix([[1, 2, 3], [5, 6, 7], [9, 10, 11]]) O.row_del(-1) assert O == Matrix([[1, 2, 3], [5, 6, 7]]) P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) raises(IndexError, lambda: P.row_del(10)) Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) raises(IndexError, lambda: Q.row_del(-10)) # for col_del(index) M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) M.col_del(1) assert M == Matrix([[1, 3], [2, 4], [3, 5]]) N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) N.col_del(-2) assert N == Matrix([[1, 3], [2, 4], [3, 5]]) P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) raises(IndexError, lambda: P.col_del(10)) Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) raises(IndexError, lambda: Q.col_del(-10)) def test_issue_9422(): x, y = symbols('x y', commutative=False) a, b = symbols('a b') M = eye(2) M1 = Matrix(2, 2, [x, y, y, z]) assert y*x*M != x*y*M assert b*a*M == a*b*M assert x*M1 != M1*x assert a*M1 == M1*a assert y*x*M == Matrix([[y*x, 0], [0, y*x]]) def test_issue_10770(): M = Matrix([]) a = ['col_insert', 'row_join'], Matrix([9, 6, 3]) b = ['row_insert', 'col_join'], a[1].T c = ['row_insert', 'col_insert'], Matrix([[1, 2], [3, 4]]) for ops, m in (a, b, c): for op in ops: f = getattr(M, op) new = f(m) if 'join' in op else f(42, m) assert new == m and id(new) != id(m) def test_issue_10658(): A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert A.extract([0, 1, 2], [True, True, False]) == \ Matrix([[1, 2], [4, 5], [7, 8]]) assert A.extract([0, 1, 2], [True, False, False]) == Matrix([[1], [4], [7]]) assert A.extract([True, False, False], [0, 1, 2]) == Matrix([[1, 2, 3]]) assert A.extract([True, False, True], [0, 1, 2]) == \ Matrix([[1, 2, 3], [7, 8, 9]]) assert A.extract([0, 1, 2], [False, False, False]) == Matrix(3, 0, []) assert A.extract([False, False, False], [0, 1, 2]) == Matrix(0, 3, []) assert A.extract([True, False, True], [False, True, False]) == \ Matrix([[2], [8]]) def test_opportunistic_simplification(): # this test relates to issue #10718, #9480, #11434 # issue #9480 m = Matrix([[-5 + 5*sqrt(2), -5], [-5*sqrt(2)/2 + 5, -5*sqrt(2)/2]]) assert m.rank() == 1 # issue #10781 m = Matrix([[3+3*sqrt(3)*I, -9],[4,-3+3*sqrt(3)*I]]) assert simplify(m.rref()[0] - Matrix([[1, -9/(3 + 3*sqrt(3)*I)], [0, 0]])) == zeros(2, 2) # issue #11434 ax,ay,bx,by,cx,cy,dx,dy,ex,ey,t0,t1 = symbols('a_x a_y b_x b_y c_x c_y d_x d_y e_x e_y t_0 t_1') m = Matrix([[ax,ay,ax*t0,ay*t0,0],[bx,by,bx*t0,by*t0,0],[cx,cy,cx*t0,cy*t0,1],[dx,dy,dx*t0,dy*t0,1],[ex,ey,2*ex*t1-ex*t0,2*ey*t1-ey*t0,0]]) assert m.rank() == 4 def test_partial_pivoting(): # example from https://en.wikipedia.org/wiki/Pivot_element # partial pivoting with back substitution gives a perfect result # naive pivoting give an error ~1e-13, so anything better than # 1e-15 is good mm=Matrix([[0.003 ,59.14, 59.17],[ 5.291, -6.13,46.78]]) assert (mm.rref()[0] - Matrix([[1.0, 0, 10.0], [ 0, 1.0, 1.0]])).norm() < 1e-15 # issue #11549 m_mixed = Matrix([[6e-17, 1.0, 4],[ -1.0, 0, 8],[ 0, 0, 1]]) m_float = Matrix([[6e-17, 1.0, 4.],[ -1.0, 0., 8.],[ 0., 0., 1.]]) m_inv = Matrix([[ 0, -1.0, 8.0],[1.0, 6.0e-17, -4.0],[ 0, 0, 1]]) # this example is numerically unstable and involves a matrix with a norm >= 8, # this comparing the difference of the results with 1e-15 is numerically sound. assert (m_mixed.inv() - m_inv).norm() < 1e-15 assert (m_float.inv() - m_inv).norm() < 1e-15 def test_iszero_substitution(): """ When doing numerical computations, all elements that pass the iszerofunc test should be set to numerically zero if they aren't already. """ # Matrix from issue #9060 m = Matrix([[0.9, -0.1, -0.2, 0],[-0.8, 0.9, -0.4, 0],[-0.1, -0.8, 0.6, 0]]) m_rref = m.rref(iszerofunc=lambda x: abs(x)<6e-15)[0] m_correct = Matrix([[1.0, 0, -0.301369863013699, 0],[ 0, 1.0, -0.712328767123288, 0],[ 0, 0, 0, 0]]) m_diff = m_rref - m_correct assert m_diff.norm() < 1e-15 # if a zero-substitution wasn't made, this entry will be -1.11022302462516e-16 assert m_rref[2,2] == 0 def test_issue_11238(): from sympy import Point xx = 8*tan(pi*Rational(13, 45))/(tan(pi*Rational(13, 45)) + sqrt(3)) yy = (-8*sqrt(3)*tan(pi*Rational(13, 45))**2 + 24*tan(pi*Rational(13, 45)))/(-3 + tan(pi*Rational(13, 45))**2) p1 = Point(0, 0) p2 = Point(1, -sqrt(3)) p0 = Point(xx,yy) m1 = Matrix([p1 - simplify(p0), p2 - simplify(p0)]) m2 = Matrix([p1 - p0, p2 - p0]) m3 = Matrix([simplify(p1 - p0), simplify(p2 - p0)]) # This system has expressions which are zero and # cannot be easily proved to be such, so without # numerical testing, these assertions will fail. Z = lambda x: abs(x.n()) < 1e-20 assert m1.rank(simplify=True, iszerofunc=Z) == 1 assert m2.rank(simplify=True, iszerofunc=Z) == 1 assert m3.rank(simplify=True, iszerofunc=Z) == 1 def test_as_real_imag(): m1 = Matrix(2,2,[1,2,3,4]) m2 = m1*S.ImaginaryUnit m3 = m1 + m2 for kls in classes: a,b = kls(m3).as_real_imag() assert list(a) == list(m1) assert list(b) == list(m1) def test_deprecated(): # Maintain tests for deprecated functions. We must capture # the deprecation warnings. When the deprecated functionality is # removed, the corresponding tests should be removed. m = Matrix(3, 3, [0, 1, 0, -4, 4, 0, -2, 1, 2]) P, Jcells = m.jordan_cells() assert Jcells[1] == Matrix(1, 1, [2]) assert Jcells[0] == Matrix(2, 2, [2, 1, 0, 2]) with warns_deprecated_sympy(): assert Matrix([[1,2],[3,4]]).dot(Matrix([[1,3],[4,5]])) == [10, 19, 14, 28] def test_issue_14489(): from sympy import Mod A = Matrix([-1, 1, 2]) B = Matrix([10, 20, -15]) assert Mod(A, 3) == Matrix([2, 1, 2]) assert Mod(B, 4) == Matrix([2, 0, 1]) def test_issue_14943(): # Test that __array__ accepts the optional dtype argument try: from numpy import array except ImportError: skip('NumPy must be available to test creating matrices from ndarrays') M = Matrix([[1,2], [3,4]]) assert array(M, dtype=float).dtype.name == 'float64' def test_case_6913(): m = MatrixSymbol('m', 1, 1) a = Symbol("a") a = m[0, 0]>0 assert str(a) == 'm[0, 0] > 0' def test_issue_11948(): A = MatrixSymbol('A', 3, 3) a = Wild('a') assert A.match(a) == {a: A} def test_gramschmidt_conjugate_dot(): vecs = [Matrix([1, I]), Matrix([1, -I])] assert Matrix.orthogonalize(*vecs) == \ [Matrix([[1], [I]]), Matrix([[1], [-I]])] mat = Matrix([[1, I], [1, -I]]) Q, R = mat.QRdecomposition() assert Q * Q.H == Matrix.eye(2) def test_issue_8207(): a = Matrix(MatrixSymbol('a', 3, 1)) b = Matrix(MatrixSymbol('b', 3, 1)) c = a.dot(b) d = diff(c, a[0, 0]) e = diff(d, a[0, 0]) assert d == b[0, 0] assert e == 0 def test_func(): from sympy.simplify.simplify import nthroot A = Matrix([[1, 2],[0, 3]]) assert A.analytic_func(sin(x*t), x) == Matrix([[sin(t), sin(3*t) - sin(t)], [0, sin(3*t)]]) A = Matrix([[2, 1],[1, 2]]) assert (pi * A / 6).analytic_func(cos(x), x) == Matrix([[sqrt(3)/4, -sqrt(3)/4], [-sqrt(3)/4, sqrt(3)/4]]) raises(ValueError, lambda : zeros(5).analytic_func(log(x), x)) raises(ValueError, lambda : (A*x).analytic_func(log(x), x)) A = Matrix([[0, -1, -2, 3], [0, -1, -2, 3], [0, 1, 0, -1], [0, 0, -1, 1]]) assert A.analytic_func(exp(x), x) == A.exp() raises(ValueError, lambda : A.analytic_func(sqrt(x), x)) A = Matrix([[41, 12],[12, 34]]) assert simplify(A.analytic_func(sqrt(x), x)**2) == A A = Matrix([[3, -12, 4], [-1, 0, -2], [-1, 5, -1]]) assert simplify(A.analytic_func(nthroot(x, 3), x)**3) == A A = Matrix([[2, 0, 0, 0], [1, 2, 0, 0], [0, 1, 3, 0], [0, 0, 1, 3]]) assert A.analytic_func(exp(x), x) == A.exp() A = Matrix([[0, 2, 1, 6], [0, 0, 1, 2], [0, 0, 0, 3], [0, 0, 0, 0]]) assert A.analytic_func(exp(x*t), x) == expand(simplify((A*t).exp())) def test_issue_19809(): def f(): assert _dotprodsimp_state.state == False m = Matrix([[1]]) m = m * m return True with dotprodsimp(True): with concurrent.futures.ThreadPoolExecutor() as executor: future = executor.submit(f) assert future.result()
d70e6222385a7eacd8f488a3c271a18a480777d5e87e7352d31f8a61ee19d1d1
from sympy import Number from sympy.core import Mul, Basic, sympify, S from sympy.core.mul import mul from sympy.functions import adjoint from sympy.strategies import (rm_id, unpack, typed, flatten, exhaust, do_one, new) from sympy.matrices.common import ShapeError, NonInvertibleMatrixError from sympy.matrices.matrices import MatrixBase from .inverse import Inverse from .matexpr import MatrixExpr from .matpow import MatPow from .transpose import transpose from .permutation import PermutationMatrix from .special import ZeroMatrix, Identity, GenericIdentity, OneMatrix # XXX: MatMul should perhaps not subclass directly from Mul class MatMul(MatrixExpr, Mul): """ A product of matrix expressions Examples ======== >>> from sympy import MatMul, MatrixSymbol >>> A = MatrixSymbol('A', 5, 4) >>> B = MatrixSymbol('B', 4, 3) >>> C = MatrixSymbol('C', 3, 6) >>> MatMul(A, B, C) A*B*C """ is_MatMul = True identity = GenericIdentity() def __new__(cls, *args, evaluate=False, check=True, _sympify=True): if not args: return cls.identity # This must be removed aggressively in the constructor to avoid # TypeErrors from GenericIdentity().shape args = filter(lambda i: cls.identity != i, args) args = list(map(sympify, args)) obj = Basic.__new__(cls, *args) factor, matrices = obj.as_coeff_matrices() if check: validate(*matrices) if not matrices: # Should it be # # return Basic.__neq__(cls, factor, GenericIdentity()) ? return factor if evaluate: return canonicalize(obj) return obj @property def shape(self): matrices = [arg for arg in self.args if arg.is_Matrix] return (matrices[0].rows, matrices[-1].cols) def _entry(self, i, j, expand=True, **kwargs): from sympy import Dummy, Sum, Mul, ImmutableMatrix, Integer coeff, matrices = self.as_coeff_matrices() if len(matrices) == 1: # situation like 2*X, matmul is just X return coeff * matrices[0][i, j] indices = [None]*(len(matrices) + 1) ind_ranges = [None]*(len(matrices) - 1) indices[0] = i indices[-1] = j def f(): counter = 1 while True: yield Dummy("i_%i" % counter) counter += 1 dummy_generator = kwargs.get("dummy_generator", f()) for i in range(1, len(matrices)): indices[i] = next(dummy_generator) for i, arg in enumerate(matrices[:-1]): ind_ranges[i] = arg.shape[1] - 1 matrices = [arg._entry(indices[i], indices[i+1], dummy_generator=dummy_generator) for i, arg in enumerate(matrices)] expr_in_sum = Mul.fromiter(matrices) if any(v.has(ImmutableMatrix) for v in matrices): expand = True result = coeff*Sum( expr_in_sum, *zip(indices[1:-1], [0]*len(ind_ranges), ind_ranges) ) # Don't waste time in result.doit() if the sum bounds are symbolic if not any(isinstance(v, (Integer, int)) for v in ind_ranges): expand = False return result.doit() if expand else result def as_coeff_matrices(self): scalars = [x for x in self.args if not x.is_Matrix] matrices = [x for x in self.args if x.is_Matrix] coeff = Mul(*scalars) if coeff.is_commutative is False: raise NotImplementedError("noncommutative scalars in MatMul are not supported.") return coeff, matrices def as_coeff_mmul(self): coeff, matrices = self.as_coeff_matrices() return coeff, MatMul(*matrices) def _eval_transpose(self): """Transposition of matrix multiplication. Notes ===== The following rules are applied. Transposition for matrix multiplied with another matrix: `\\left(A B\\right)^{T} = B^{T} A^{T}` Transposition for matrix multiplied with scalar: `\\left(c A\\right)^{T} = c A^{T}` References ========== .. [1] https://en.wikipedia.org/wiki/Transpose """ coeff, matrices = self.as_coeff_matrices() return MatMul( coeff, *[transpose(arg) for arg in matrices[::-1]]).doit() def _eval_adjoint(self): return MatMul(*[adjoint(arg) for arg in self.args[::-1]]).doit() def _eval_trace(self): factor, mmul = self.as_coeff_mmul() if factor != 1: from .trace import trace return factor * trace(mmul.doit()) else: raise NotImplementedError("Can't simplify any further") def _eval_determinant(self): from sympy.matrices.expressions.determinant import Determinant factor, matrices = self.as_coeff_matrices() square_matrices = only_squares(*matrices) return factor**self.rows * Mul(*list(map(Determinant, square_matrices))) def _eval_inverse(self): try: return MatMul(*[ arg.inverse() if isinstance(arg, MatrixExpr) else arg**-1 for arg in self.args[::-1]]).doit() except ShapeError: return Inverse(self) def doit(self, **kwargs): deep = kwargs.get('deep', True) if deep: args = [arg.doit(**kwargs) for arg in self.args] else: args = self.args # treat scalar*MatrixSymbol or scalar*MatPow separately expr = canonicalize(MatMul(*args)) return expr # Needed for partial compatibility with Mul def args_cnc(self, **kwargs): coeff_c = [x for x in self.args if x.is_commutative] coeff_nc = [x for x in self.args if not x.is_commutative] return [coeff_c, coeff_nc] def _eval_derivative_matrix_lines(self, x): from .transpose import Transpose with_x_ind = [i for i, arg in enumerate(self.args) if arg.has(x)] lines = [] for ind in with_x_ind: left_args = self.args[:ind] right_args = self.args[ind+1:] if right_args: right_mat = MatMul.fromiter(right_args) else: right_mat = Identity(self.shape[1]) if left_args: left_rev = MatMul.fromiter([Transpose(i).doit() if i.is_Matrix else i for i in reversed(left_args)]) else: left_rev = Identity(self.shape[0]) d = self.args[ind]._eval_derivative_matrix_lines(x) for i in d: i.append_first(left_rev) i.append_second(right_mat) lines.append(i) return lines mul.register_handlerclass((Mul, MatMul), MatMul) def validate(*matrices): """ Checks for valid shapes for args of MatMul """ for i in range(len(matrices)-1): A, B = matrices[i:i+2] if A.cols != B.rows: raise ShapeError("Matrices %s and %s are not aligned"%(A, B)) # Rules def newmul(*args): if args[0] == 1: args = args[1:] return new(MatMul, *args) def any_zeros(mul): if any([arg.is_zero or (arg.is_Matrix and arg.is_ZeroMatrix) for arg in mul.args]): matrices = [arg for arg in mul.args if arg.is_Matrix] return ZeroMatrix(matrices[0].rows, matrices[-1].cols) return mul def merge_explicit(matmul): """ Merge explicit MatrixBase arguments >>> from sympy import MatrixSymbol, Matrix, MatMul, pprint >>> from sympy.matrices.expressions.matmul import merge_explicit >>> A = MatrixSymbol('A', 2, 2) >>> B = Matrix([[1, 1], [1, 1]]) >>> C = Matrix([[1, 2], [3, 4]]) >>> X = MatMul(A, B, C) >>> pprint(X) [1 1] [1 2] A*[ ]*[ ] [1 1] [3 4] >>> pprint(merge_explicit(X)) [4 6] A*[ ] [4 6] >>> X = MatMul(B, A, C) >>> pprint(X) [1 1] [1 2] [ ]*A*[ ] [1 1] [3 4] >>> pprint(merge_explicit(X)) [1 1] [1 2] [ ]*A*[ ] [1 1] [3 4] """ if not any(isinstance(arg, MatrixBase) for arg in matmul.args): return matmul newargs = [] last = matmul.args[0] for arg in matmul.args[1:]: if isinstance(arg, (MatrixBase, Number)) and isinstance(last, (MatrixBase, Number)): last = last * arg else: newargs.append(last) last = arg newargs.append(last) return MatMul(*newargs) def remove_ids(mul): """ Remove Identities from a MatMul This is a modified version of sympy.strategies.rm_id. This is necesssary because MatMul may contain both MatrixExprs and Exprs as args. See Also ======== sympy.strategies.rm_id """ # Separate Exprs from MatrixExprs in args factor, mmul = mul.as_coeff_mmul() # Apply standard rm_id for MatMuls result = rm_id(lambda x: x.is_Identity is True)(mmul) if result != mmul: return newmul(factor, *result.args) # Recombine and return else: return mul def factor_in_front(mul): factor, matrices = mul.as_coeff_matrices() if factor != 1: return newmul(factor, *matrices) return mul def combine_powers(mul): """Combine consecutive powers with the same base into one e.g. A*A**2 -> A**3 This also cancels out the possible matrix inverses using the knowledgebase of ``Inverse``. e.g. Y * X * X.I -> Y """ factor, args = mul.as_coeff_matrices() new_args = [args[0]] for B in args[1:]: A = new_args[-1] if A.is_square == False or B.is_square == False: new_args.append(B) continue if isinstance(A, MatPow): A_base, A_exp = A.args else: A_base, A_exp = A, S.One if isinstance(B, MatPow): B_base, B_exp = B.args else: B_base, B_exp = B, S.One if A_base == B_base: new_exp = A_exp + B_exp new_args[-1] = MatPow(A_base, new_exp).doit(deep=False) continue elif not isinstance(B_base, MatrixBase): try: B_base_inv = B_base.inverse() except NonInvertibleMatrixError: B_base_inv = None if B_base_inv is not None and A_base == B_base_inv: new_exp = A_exp - B_exp new_args[-1] = MatPow(A_base, new_exp).doit(deep=False) continue new_args.append(B) return newmul(factor, *new_args) def combine_permutations(mul): """Refine products of permutation matrices as the products of cycles. """ args = mul.args l = len(args) if l < 2: return mul result = [args[0]] for i in range(1, l): A = result[-1] B = args[i] if isinstance(A, PermutationMatrix) and \ isinstance(B, PermutationMatrix): cycle_1 = A.args[0] cycle_2 = B.args[0] result[-1] = PermutationMatrix(cycle_1 * cycle_2) else: result.append(B) return MatMul(*result) def combine_one_matrices(mul): """ Combine products of OneMatrix e.g. OneMatrix(2, 3) * OneMatrix(3, 4) -> 3 * OneMatrix(2, 4) """ factor, args = mul.as_coeff_matrices() new_args = [args[0]] for B in args[1:]: A = new_args[-1] if not isinstance(A, OneMatrix) or not isinstance(B, OneMatrix): new_args.append(B) continue new_args.pop() new_args.append(OneMatrix(A.shape[0], B.shape[1])) factor *= A.shape[1] return newmul(factor, *new_args) rules = ( any_zeros, remove_ids, combine_one_matrices, combine_powers, unpack, rm_id(lambda x: x == 1), merge_explicit, factor_in_front, flatten, combine_permutations) canonicalize = exhaust(typed({MatMul: do_one(*rules)})) def only_squares(*matrices): """factor matrices only if they are square""" if matrices[0].rows != matrices[-1].cols: raise RuntimeError("Invalid matrices being multiplied") out = [] start = 0 for i, M in enumerate(matrices): if M.cols == matrices[start].rows: out.append(MatMul(*matrices[start:i+1]).doit()) start = i+1 return out from sympy.assumptions.ask import ask, Q from sympy.assumptions.refine import handlers_dict def refine_MatMul(expr, assumptions): """ >>> from sympy import MatrixSymbol, Q, assuming, refine >>> X = MatrixSymbol('X', 2, 2) >>> expr = X * X.T >>> print(expr) X*X.T >>> with assuming(Q.orthogonal(X)): ... print(refine(expr)) I """ newargs = [] exprargs = [] for args in expr.args: if args.is_Matrix: exprargs.append(args) else: newargs.append(args) last = exprargs[0] for arg in exprargs[1:]: if arg == last.T and ask(Q.orthogonal(arg), assumptions): last = Identity(arg.shape[0]) elif arg == last.conjugate() and ask(Q.unitary(arg), assumptions): last = Identity(arg.shape[0]) else: newargs.append(last) last = arg newargs.append(last) return MatMul(*newargs) handlers_dict['MatMul'] = refine_MatMul
62353cd3a515eb8938368b0ef5fa9f8cb275edfc50d93ff3ffa9cde2e8e2af2b
from sympy.core.logic import FuzzyBool from functools import wraps, reduce import collections from sympy.core import S, Symbol, Integer, Basic, Expr, Mul, Add from sympy.core.decorators import call_highest_priority from sympy.core.compatibility import SYMPY_INTS, default_sort_key from sympy.core.symbol import Str from sympy.core.sympify import SympifyError, _sympify from sympy.functions import conjugate, adjoint from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.matrices.common import NonSquareMatrixError from sympy.simplify import simplify from sympy.utilities.misc import filldedent from sympy.multipledispatch import dispatch def _sympifyit(arg, retval=None): # This version of _sympifyit sympifies MutableMatrix objects def deco(func): @wraps(func) def __sympifyit_wrapper(a, b): try: b = _sympify(b) return func(a, b) except SympifyError: return retval return __sympifyit_wrapper return deco class MatrixExpr(Expr): """Superclass for Matrix Expressions MatrixExprs represent abstract matrices, linear transformations represented within a particular basis. Examples ======== >>> from sympy import MatrixSymbol >>> A = MatrixSymbol('A', 3, 3) >>> y = MatrixSymbol('y', 3, 1) >>> x = (A.T*A).I * A * y See Also ======== MatrixSymbol, MatAdd, MatMul, Transpose, Inverse """ # Should not be considered iterable by the # sympy.core.compatibility.iterable function. Subclass that actually are # iterable (i.e., explicit matrices) should set this to True. _iterable = False _op_priority = 11.0 is_Matrix = True # type: bool is_MatrixExpr = True # type: bool is_Identity = None # type: FuzzyBool is_Inverse = False is_Transpose = False is_ZeroMatrix = False is_MatAdd = False is_MatMul = False is_commutative = False is_number = False is_symbol = False is_scalar = False def __new__(cls, *args, **kwargs): args = map(_sympify, args) return Basic.__new__(cls, *args, **kwargs) # The following is adapted from the core Expr object @property def _add_handler(self): return MatAdd @property def _mul_handler(self): return MatMul def __neg__(self): return MatMul(S.NegativeOne, self).doit() def __abs__(self): raise NotImplementedError @_sympifyit('other', NotImplemented) @call_highest_priority('__radd__') def __add__(self, other): return MatAdd(self, other, check=True).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__add__') def __radd__(self, other): return MatAdd(other, self, check=True).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__rsub__') def __sub__(self, other): return MatAdd(self, -other, check=True).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__sub__') def __rsub__(self, other): return MatAdd(other, -self, check=True).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__rmul__') def __mul__(self, other): return MatMul(self, other).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__rmul__') def __matmul__(self, other): return MatMul(self, other).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__mul__') def __rmul__(self, other): return MatMul(other, self).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__mul__') def __rmatmul__(self, other): return MatMul(other, self).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__rpow__') def __pow__(self, other): return MatPow(self, other).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__pow__') def __rpow__(self, other): raise NotImplementedError("Matrix Power not defined") @_sympifyit('other', NotImplemented) @call_highest_priority('__rtruediv__') def __truediv__(self, other): return self * other**S.NegativeOne @_sympifyit('other', NotImplemented) @call_highest_priority('__truediv__') def __rtruediv__(self, other): raise NotImplementedError() #return MatMul(other, Pow(self, S.NegativeOne)) @property def rows(self): return self.shape[0] @property def cols(self): return self.shape[1] @property def is_square(self): return self.rows == self.cols def _eval_conjugate(self): from sympy.matrices.expressions.adjoint import Adjoint from sympy.matrices.expressions.transpose import Transpose return Adjoint(Transpose(self)) def as_real_imag(self, deep=True, **hints): from sympy import I real = S.Half * (self + self._eval_conjugate()) im = (self - self._eval_conjugate())/(2*I) return (real, im) def _eval_inverse(self): from sympy.matrices.expressions.inverse import Inverse return Inverse(self) def _eval_transpose(self): return Transpose(self) def _eval_power(self, exp): """ Override this in sub-classes to implement simplification of powers. The cases where the exponent is -1, 0, 1 are already covered in MatPow.doit(), so implementations can exclude these cases. """ return MatPow(self, exp) def _eval_simplify(self, **kwargs): if self.is_Atom: return self else: return self.func(*[simplify(x, **kwargs) for x in self.args]) def _eval_adjoint(self): from sympy.matrices.expressions.adjoint import Adjoint return Adjoint(self) def _eval_derivative_n_times(self, x, n): return Basic._eval_derivative_n_times(self, x, n) def _eval_derivative(self, x): # `x` is a scalar: if self.has(x): # See if there are other methods using it: return super(MatrixExpr, self)._eval_derivative(x) else: return ZeroMatrix(*self.shape) @classmethod def _check_dim(cls, dim): """Helper function to check invalid matrix dimensions""" from sympy.core.assumptions import check_assumptions ok = check_assumptions(dim, integer=True, nonnegative=True) if ok is False: raise ValueError( "The dimension specification {} should be " "a nonnegative integer.".format(dim)) def _entry(self, i, j, **kwargs): raise NotImplementedError( "Indexing not implemented for %s" % self.__class__.__name__) def adjoint(self): return adjoint(self) def as_coeff_Mul(self, rational=False): """Efficiently extract the coefficient of a product. """ return S.One, self def conjugate(self): return conjugate(self) def transpose(self): from sympy.matrices.expressions.transpose import transpose return transpose(self) @property def T(self): '''Matrix transposition''' return self.transpose() def inverse(self): if not self.is_square: raise NonSquareMatrixError('Inverse of non-square matrix') return self._eval_inverse() def inv(self): return self.inverse() @property def I(self): return self.inverse() def valid_index(self, i, j): def is_valid(idx): return isinstance(idx, (int, Integer, Symbol, Expr)) return (is_valid(i) and is_valid(j) and (self.rows is None or (0 <= i) != False and (i < self.rows) != False) and (0 <= j) != False and (j < self.cols) != False) def __getitem__(self, key): if not isinstance(key, tuple) and isinstance(key, slice): from sympy.matrices.expressions.slice import MatrixSlice return MatrixSlice(self, key, (0, None, 1)) if isinstance(key, tuple) and len(key) == 2: i, j = key if isinstance(i, slice) or isinstance(j, slice): from sympy.matrices.expressions.slice import MatrixSlice return MatrixSlice(self, i, j) i, j = _sympify(i), _sympify(j) if self.valid_index(i, j) != False: return self._entry(i, j) else: raise IndexError("Invalid indices (%s, %s)" % (i, j)) elif isinstance(key, (SYMPY_INTS, Integer)): # row-wise decomposition of matrix rows, cols = self.shape # allow single indexing if number of columns is known if not isinstance(cols, Integer): raise IndexError(filldedent(''' Single indexing is only supported when the number of columns is known.''')) key = _sympify(key) i = key // cols j = key % cols if self.valid_index(i, j) != False: return self._entry(i, j) else: raise IndexError("Invalid index %s" % key) elif isinstance(key, (Symbol, Expr)): raise IndexError(filldedent(''' Only integers may be used when addressing the matrix with a single index.''')) raise IndexError("Invalid index, wanted %s[i,j]" % self) def as_explicit(self): """ Returns a dense Matrix with elements represented explicitly Returns an object of type ImmutableDenseMatrix. Examples ======== >>> from sympy import Identity >>> I = Identity(3) >>> I I >>> I.as_explicit() Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) See Also ======== as_mutable: returns mutable Matrix type """ if (not isinstance(self.rows, (SYMPY_INTS, Integer)) or not isinstance(self.cols, (SYMPY_INTS, Integer))): raise ValueError( 'Matrix with symbolic shape ' 'cannot be represented explicitly.') from sympy.matrices.immutable import ImmutableDenseMatrix return ImmutableDenseMatrix([[self[i, j] for j in range(self.cols)] for i in range(self.rows)]) def as_mutable(self): """ Returns a dense, mutable matrix with elements represented explicitly Examples ======== >>> from sympy import Identity >>> I = Identity(3) >>> I I >>> I.shape (3, 3) >>> I.as_mutable() Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) See Also ======== as_explicit: returns ImmutableDenseMatrix """ return self.as_explicit().as_mutable() def __array__(self): from numpy import empty a = empty(self.shape, dtype=object) for i in range(self.rows): for j in range(self.cols): a[i, j] = self[i, j] return a def equals(self, other): """ Test elementwise equality between matrices, potentially of different types >>> from sympy import Identity, eye >>> Identity(3).equals(eye(3)) True """ return self.as_explicit().equals(other) def canonicalize(self): return self def as_coeff_mmul(self): return 1, MatMul(self) @staticmethod def from_index_summation(expr, first_index=None, last_index=None, dimensions=None): r""" Parse expression of matrices with explicitly summed indices into a matrix expression without indices, if possible. This transformation expressed in mathematical notation: `\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}` Optional parameter ``first_index``: specify which free index to use as the index starting the expression. Examples ======== >>> from sympy import MatrixSymbol, MatrixExpr, Sum >>> from sympy.abc import i, j, k, l, N >>> A = MatrixSymbol("A", N, N) >>> B = MatrixSymbol("B", N, N) >>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1)) >>> MatrixExpr.from_index_summation(expr) A*B Transposition is detected: >>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1)) >>> MatrixExpr.from_index_summation(expr) A.T*B Detect the trace: >>> expr = Sum(A[i, i], (i, 0, N-1)) >>> MatrixExpr.from_index_summation(expr) Trace(A) More complicated expressions: >>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1)) >>> MatrixExpr.from_index_summation(expr) A*B.T*A.T """ from sympy import Sum, Mul, Add, MatMul, transpose, trace from sympy.strategies.traverse import bottom_up def remove_matelement(expr, i1, i2): def repl_match(pos): def func(x): if not isinstance(x, MatrixElement): return False if x.args[pos] != i1: return False if x.args[3-pos] == 0: if x.args[0].shape[2-pos] == 1: return True else: return False return True return func expr = expr.replace(repl_match(1), lambda x: x.args[0]) expr = expr.replace(repl_match(2), lambda x: transpose(x.args[0])) # Make sure that all Mul are transformed to MatMul and that they # are flattened: rule = bottom_up(lambda x: reduce(lambda a, b: a*b, x.args) if isinstance(x, (Mul, MatMul)) else x) return rule(expr) def recurse_expr(expr, index_ranges={}): if expr.is_Mul: nonmatargs = [] pos_arg = [] pos_ind = [] dlinks = {} link_ind = [] counter = 0 args_ind = [] for arg in expr.args: retvals = recurse_expr(arg, index_ranges) assert isinstance(retvals, list) if isinstance(retvals, list): for i in retvals: args_ind.append(i) else: args_ind.append(retvals) for arg_symbol, arg_indices in args_ind: if arg_indices is None: nonmatargs.append(arg_symbol) continue if isinstance(arg_symbol, MatrixElement): arg_symbol = arg_symbol.args[0] pos_arg.append(arg_symbol) pos_ind.append(arg_indices) link_ind.append([None]*len(arg_indices)) for i, ind in enumerate(arg_indices): if ind in dlinks: other_i = dlinks[ind] link_ind[counter][i] = other_i link_ind[other_i[0]][other_i[1]] = (counter, i) dlinks[ind] = (counter, i) counter += 1 counter2 = 0 lines = {} while counter2 < len(link_ind): for i, e in enumerate(link_ind): if None in e: line_start_index = (i, e.index(None)) break cur_ind_pos = line_start_index cur_line = [] index1 = pos_ind[cur_ind_pos[0]][cur_ind_pos[1]] while True: d, r = cur_ind_pos if pos_arg[d] != 1: if r % 2 == 1: cur_line.append(transpose(pos_arg[d])) else: cur_line.append(pos_arg[d]) next_ind_pos = link_ind[d][1-r] counter2 += 1 # Mark as visited, there will be no `None` anymore: link_ind[d] = (-1, -1) if next_ind_pos is None: index2 = pos_ind[d][1-r] lines[(index1, index2)] = cur_line break cur_ind_pos = next_ind_pos lines = {k: MatMul.fromiter(v) if len(v) != 1 else v[0] for k, v in lines.items()} return [(Mul.fromiter(nonmatargs), None)] + [ (MatrixElement(a, i, j), (i, j)) for (i, j), a in lines.items() ] elif expr.is_Add: res = [recurse_expr(i) for i in expr.args] d = collections.defaultdict(list) for res_addend in res: scalar = 1 for elem, indices in res_addend: if indices is None: scalar = elem continue indices = tuple(sorted(indices, key=default_sort_key)) d[indices].append(scalar*remove_matelement(elem, *indices)) scalar = 1 return [(MatrixElement(Add.fromiter(v), *k), k) for k, v in d.items()] elif isinstance(expr, KroneckerDelta): i1, i2 = expr.args if dimensions is not None: identity = Identity(dimensions[0]) else: identity = S.One return [(MatrixElement(identity, i1, i2), (i1, i2))] elif isinstance(expr, MatrixElement): matrix_symbol, i1, i2 = expr.args if i1 in index_ranges: r1, r2 = index_ranges[i1] if r1 != 0 or matrix_symbol.shape[0] != r2+1: raise ValueError("index range mismatch: {} vs. (0, {})".format( (r1, r2), matrix_symbol.shape[0])) if i2 in index_ranges: r1, r2 = index_ranges[i2] if r1 != 0 or matrix_symbol.shape[1] != r2+1: raise ValueError("index range mismatch: {} vs. (0, {})".format( (r1, r2), matrix_symbol.shape[1])) if (i1 == i2) and (i1 in index_ranges): return [(trace(matrix_symbol), None)] return [(MatrixElement(matrix_symbol, i1, i2), (i1, i2))] elif isinstance(expr, Sum): return recurse_expr( expr.args[0], index_ranges={i[0]: i[1:] for i in expr.args[1:]} ) else: return [(expr, None)] retvals = recurse_expr(expr) factors, indices = zip(*retvals) retexpr = Mul.fromiter(factors) if len(indices) == 0 or list(set(indices)) == [None]: return retexpr if first_index is None: for i in indices: if i is not None: ind0 = i break return remove_matelement(retexpr, *ind0) else: return remove_matelement(retexpr, first_index, last_index) def applyfunc(self, func): from .applyfunc import ElementwiseApplyFunction return ElementwiseApplyFunction(func, self) @dispatch(MatrixExpr, Expr) def _eval_is_eq(lhs, rhs): # noqa:F811 return False @dispatch(MatrixExpr, MatrixExpr) def _eval_is_eq(lhs, rhs): # noqa:F811 if lhs.shape != rhs.shape: return False if (lhs - rhs).is_ZeroMatrix: return True def get_postprocessor(cls): def _postprocessor(expr): # To avoid circular imports, we can't have MatMul/MatAdd on the top level mat_class = {Mul: MatMul, Add: MatAdd}[cls] nonmatrices = [] matrices = [] for term in expr.args: if isinstance(term, MatrixExpr): matrices.append(term) else: nonmatrices.append(term) if not matrices: return cls._from_args(nonmatrices) if nonmatrices: if cls == Mul: for i in range(len(matrices)): if not matrices[i].is_MatrixExpr: # If one of the matrices explicit, absorb the scalar into it # (doit will combine all explicit matrices into one, so it # doesn't matter which) matrices[i] = matrices[i].__mul__(cls._from_args(nonmatrices)) nonmatrices = [] break else: # Maintain the ability to create Add(scalar, matrix) without # raising an exception. That way different algorithms can # replace matrix expressions with non-commutative symbols to # manipulate them like non-commutative scalars. return cls._from_args(nonmatrices + [mat_class(*matrices).doit(deep=False)]) if mat_class == MatAdd: return mat_class(*matrices).doit(deep=False) return mat_class(cls._from_args(nonmatrices), *matrices).doit(deep=False) return _postprocessor Basic._constructor_postprocessor_mapping[MatrixExpr] = { "Mul": [get_postprocessor(Mul)], "Add": [get_postprocessor(Add)], } def _matrix_derivative(expr, x): from sympy.tensor.array.array_derivatives import ArrayDerivative lines = expr._eval_derivative_matrix_lines(x) parts = [i.build() for i in lines] from sympy.codegen.array_utils import recognize_matrix_expression parts = [[recognize_matrix_expression(j).doit() for j in i] for i in parts] def _get_shape(elem): if isinstance(elem, MatrixExpr): return elem.shape return 1, 1 def get_rank(parts): return sum([j not in (1, None) for i in parts for j in _get_shape(i)]) ranks = [get_rank(i) for i in parts] rank = ranks[0] def contract_one_dims(parts): if len(parts) == 1: return parts[0] else: p1, p2 = parts[:2] if p2.is_Matrix: p2 = p2.T if p1 == Identity(1): pbase = p2 elif p2 == Identity(1): pbase = p1 else: pbase = p1*p2 if len(parts) == 2: return pbase else: # len(parts) > 2 if pbase.is_Matrix: raise ValueError("") return pbase*Mul.fromiter(parts[2:]) if rank <= 2: return Add.fromiter([contract_one_dims(i) for i in parts]) return ArrayDerivative(expr, x) class MatrixElement(Expr): parent = property(lambda self: self.args[0]) i = property(lambda self: self.args[1]) j = property(lambda self: self.args[2]) _diff_wrt = True is_symbol = True is_commutative = True def __new__(cls, name, n, m): n, m = map(_sympify, (n, m)) from sympy import MatrixBase if isinstance(name, (MatrixBase,)): if n.is_Integer and m.is_Integer: return name[n, m] if isinstance(name, str): name = Symbol(name) name = _sympify(name) obj = Expr.__new__(cls, name, n, m) return obj def doit(self, **kwargs): deep = kwargs.get('deep', True) if deep: args = [arg.doit(**kwargs) for arg in self.args] else: args = self.args return args[0][args[1], args[2]] @property def indices(self): return self.args[1:] def _eval_derivative(self, v): from sympy import Sum, symbols, Dummy if not isinstance(v, MatrixElement): from sympy import MatrixBase if isinstance(self.parent, MatrixBase): return self.parent.diff(v)[self.i, self.j] return S.Zero M = self.args[0] m, n = self.parent.shape if M == v.args[0]: return KroneckerDelta(self.args[1], v.args[1], (0, m-1)) * \ KroneckerDelta(self.args[2], v.args[2], (0, n-1)) if isinstance(M, Inverse): i, j = self.args[1:] i1, i2 = symbols("z1, z2", cls=Dummy) Y = M.args[0] r1, r2 = Y.shape return -Sum(M[i, i1]*Y[i1, i2].diff(v)*M[i2, j], (i1, 0, r1-1), (i2, 0, r2-1)) if self.has(v.args[0]): return None return S.Zero class MatrixSymbol(MatrixExpr): """Symbolic representation of a Matrix object Creates a SymPy Symbol to represent a Matrix. This matrix has a shape and can be included in Matrix Expressions Examples ======== >>> from sympy import MatrixSymbol, Identity >>> A = MatrixSymbol('A', 3, 4) # A 3 by 4 Matrix >>> B = MatrixSymbol('B', 4, 3) # A 4 by 3 Matrix >>> A.shape (3, 4) >>> 2*A*B + Identity(3) I + 2*A*B """ is_commutative = False is_symbol = True _diff_wrt = True def __new__(cls, name, n, m): n, m = _sympify(n), _sympify(m) cls._check_dim(m) cls._check_dim(n) if isinstance(name, str): name = Str(name) obj = Basic.__new__(cls, name, n, m) return obj @property def shape(self): return self.args[1], self.args[2] @property def name(self): return self.args[0].name def _entry(self, i, j, **kwargs): return MatrixElement(self, i, j) @property def free_symbols(self): return {self} def _eval_simplify(self, **kwargs): return self def _eval_derivative(self, x): # x is a scalar: return ZeroMatrix(self.shape[0], self.shape[1]) def _eval_derivative_matrix_lines(self, x): if self != x: first = ZeroMatrix(x.shape[0], self.shape[0]) if self.shape[0] != 1 else S.Zero second = ZeroMatrix(x.shape[1], self.shape[1]) if self.shape[1] != 1 else S.Zero return [_LeftRightArgs( [first, second], )] else: first = Identity(self.shape[0]) if self.shape[0] != 1 else S.One second = Identity(self.shape[1]) if self.shape[1] != 1 else S.One return [_LeftRightArgs( [first, second], )] def matrix_symbols(expr): return [sym for sym in expr.free_symbols if sym.is_Matrix] class _LeftRightArgs: r""" Helper class to compute matrix derivatives. The logic: when an expression is derived by a matrix `X_{mn}`, two lines of matrix multiplications are created: the one contracted to `m` (first line), and the one contracted to `n` (second line). Transposition flips the side by which new matrices are connected to the lines. The trace connects the end of the two lines. """ def __init__(self, lines, higher=S.One): self._lines = [i for i in lines] self._first_pointer_parent = self._lines self._first_pointer_index = 0 self._first_line_index = 0 self._second_pointer_parent = self._lines self._second_pointer_index = 1 self._second_line_index = 1 self.higher = higher @property def first_pointer(self): return self._first_pointer_parent[self._first_pointer_index] @first_pointer.setter def first_pointer(self, value): self._first_pointer_parent[self._first_pointer_index] = value @property def second_pointer(self): return self._second_pointer_parent[self._second_pointer_index] @second_pointer.setter def second_pointer(self, value): self._second_pointer_parent[self._second_pointer_index] = value def __repr__(self): built = [self._build(i) for i in self._lines] return "_LeftRightArgs(lines=%s, higher=%s)" % ( built, self.higher, ) def transpose(self): self._first_pointer_parent, self._second_pointer_parent = self._second_pointer_parent, self._first_pointer_parent self._first_pointer_index, self._second_pointer_index = self._second_pointer_index, self._first_pointer_index self._first_line_index, self._second_line_index = self._second_line_index, self._first_line_index return self @staticmethod def _build(expr): from sympy.core.expr import ExprBuilder if isinstance(expr, ExprBuilder): return expr.build() if isinstance(expr, list): if len(expr) == 1: return expr[0] else: return expr[0](*[_LeftRightArgs._build(i) for i in expr[1]]) else: return expr def build(self): data = [self._build(i) for i in self._lines] if self.higher != 1: data += [self._build(self.higher)] data = [i.doit() for i in data] return data def matrix_form(self): if self.first != 1 and self.higher != 1: raise ValueError("higher dimensional array cannot be represented") def _get_shape(elem): if isinstance(elem, MatrixExpr): return elem.shape return (None, None) if _get_shape(self.first)[1] != _get_shape(self.second)[1]: # Remove one-dimensional identity matrices: # (this is needed by `a.diff(a)` where `a` is a vector) if _get_shape(self.second) == (1, 1): return self.first*self.second[0, 0] if _get_shape(self.first) == (1, 1): return self.first[1, 1]*self.second.T raise ValueError("incompatible shapes") if self.first != 1: return self.first*self.second.T else: return self.higher def rank(self): """ Number of dimensions different from trivial (warning: not related to matrix rank). """ rank = 0 if self.first != 1: rank += sum([i != 1 for i in self.first.shape]) if self.second != 1: rank += sum([i != 1 for i in self.second.shape]) if self.higher != 1: rank += 2 return rank def _multiply_pointer(self, pointer, other): from sympy.core.expr import ExprBuilder from sympy.codegen.array_utils import CodegenArrayContraction, CodegenArrayTensorProduct subexpr = ExprBuilder( CodegenArrayContraction, [ ExprBuilder( CodegenArrayTensorProduct, [ pointer, other ] ), (1, 2) ], validator=CodegenArrayContraction._validate ) return subexpr def append_first(self, other): self.first_pointer *= other def append_second(self, other): self.second_pointer *= other def __hash__(self): return hash((self.first, self.second)) def __eq__(self, other): if not isinstance(other, _LeftRightArgs): return False return (self.first == other.first) and (self.second == other.second) def _make_matrix(x): from sympy import ImmutableDenseMatrix if isinstance(x, MatrixExpr): return x return ImmutableDenseMatrix([[x]]) from .matmul import MatMul from .matadd import MatAdd from .matpow import MatPow from .transpose import Transpose from .inverse import Inverse from .special import ZeroMatrix, Identity
07552cfac20502e023d9df6b75fc10e5aab14d35af5584a54f7ac5ce1c3a1d4f
"""Implementation of the Kronecker product""" from sympy.core import Mul, prod, sympify from sympy.functions import adjoint from sympy.matrices.common import ShapeError from sympy.matrices.expressions.matexpr import MatrixExpr from sympy.matrices.expressions.transpose import transpose from sympy.matrices.expressions.special import Identity from sympy.matrices.matrices import MatrixBase from sympy.strategies import ( canon, condition, distribute, do_one, exhaust, flatten, typed, unpack) from sympy.strategies.traverse import bottom_up from sympy.utilities import sift from .matadd import MatAdd from .matmul import MatMul from .matpow import MatPow def kronecker_product(*matrices): """ The Kronecker product of two or more arguments. This computes the explicit Kronecker product for subclasses of ``MatrixBase`` i.e. explicit matrices. Otherwise, a symbolic ``KroneckerProduct`` object is returned. Examples ======== For ``MatrixSymbol`` arguments a ``KroneckerProduct`` object is returned. Elements of this matrix can be obtained by indexing, or for MatrixSymbols with known dimension the explicit matrix can be obtained with ``.as_explicit()`` >>> from sympy.matrices import kronecker_product, MatrixSymbol >>> A = MatrixSymbol('A', 2, 2) >>> B = MatrixSymbol('B', 2, 2) >>> kronecker_product(A) A >>> kronecker_product(A, B) KroneckerProduct(A, B) >>> kronecker_product(A, B)[0, 1] A[0, 0]*B[0, 1] >>> kronecker_product(A, B).as_explicit() Matrix([ [A[0, 0]*B[0, 0], A[0, 0]*B[0, 1], A[0, 1]*B[0, 0], A[0, 1]*B[0, 1]], [A[0, 0]*B[1, 0], A[0, 0]*B[1, 1], A[0, 1]*B[1, 0], A[0, 1]*B[1, 1]], [A[1, 0]*B[0, 0], A[1, 0]*B[0, 1], A[1, 1]*B[0, 0], A[1, 1]*B[0, 1]], [A[1, 0]*B[1, 0], A[1, 0]*B[1, 1], A[1, 1]*B[1, 0], A[1, 1]*B[1, 1]]]) For explicit matrices the Kronecker product is returned as a Matrix >>> from sympy.matrices import Matrix, kronecker_product >>> sigma_x = Matrix([ ... [0, 1], ... [1, 0]]) ... >>> Isigma_y = Matrix([ ... [0, 1], ... [-1, 0]]) ... >>> kronecker_product(sigma_x, Isigma_y) Matrix([ [ 0, 0, 0, 1], [ 0, 0, -1, 0], [ 0, 1, 0, 0], [-1, 0, 0, 0]]) See Also ======== KroneckerProduct """ if not matrices: raise TypeError("Empty Kronecker product is undefined") validate(*matrices) if len(matrices) == 1: return matrices[0] else: return KroneckerProduct(*matrices).doit() class KroneckerProduct(MatrixExpr): """ The Kronecker product of two or more arguments. The Kronecker product is a non-commutative product of matrices. Given two matrices of dimension (m, n) and (s, t) it produces a matrix of dimension (m s, n t). This is a symbolic object that simply stores its argument without evaluating it. To actually compute the product, use the function ``kronecker_product()`` or call the the ``.doit()`` or ``.as_explicit()`` methods. >>> from sympy.matrices import KroneckerProduct, MatrixSymbol >>> A = MatrixSymbol('A', 5, 5) >>> B = MatrixSymbol('B', 5, 5) >>> isinstance(KroneckerProduct(A, B), KroneckerProduct) True """ is_KroneckerProduct = True def __new__(cls, *args, check=True): args = list(map(sympify, args)) if all(a.is_Identity for a in args): ret = Identity(prod(a.rows for a in args)) if all(isinstance(a, MatrixBase) for a in args): return ret.as_explicit() else: return ret if check: validate(*args) return super().__new__(cls, *args) @property def shape(self): rows, cols = self.args[0].shape for mat in self.args[1:]: rows *= mat.rows cols *= mat.cols return (rows, cols) def _entry(self, i, j, **kwargs): result = 1 for mat in reversed(self.args): i, m = divmod(i, mat.rows) j, n = divmod(j, mat.cols) result *= mat[m, n] return result def _eval_adjoint(self): return KroneckerProduct(*list(map(adjoint, self.args))).doit() def _eval_conjugate(self): return KroneckerProduct(*[a.conjugate() for a in self.args]).doit() def _eval_transpose(self): return KroneckerProduct(*list(map(transpose, self.args))).doit() def _eval_trace(self): from .trace import trace return prod(trace(a) for a in self.args) def _eval_determinant(self): from .determinant import det, Determinant if not all(a.is_square for a in self.args): return Determinant(self) m = self.rows return prod(det(a)**(m/a.rows) for a in self.args) def _eval_inverse(self): try: return KroneckerProduct(*[a.inverse() for a in self.args]) except ShapeError: from sympy.matrices.expressions.inverse import Inverse return Inverse(self) def structurally_equal(self, other): '''Determine whether two matrices have the same Kronecker product structure Examples ======== >>> from sympy import KroneckerProduct, MatrixSymbol, symbols >>> m, n = symbols(r'm, n', integer=True) >>> A = MatrixSymbol('A', m, m) >>> B = MatrixSymbol('B', n, n) >>> C = MatrixSymbol('C', m, m) >>> D = MatrixSymbol('D', n, n) >>> KroneckerProduct(A, B).structurally_equal(KroneckerProduct(C, D)) True >>> KroneckerProduct(A, B).structurally_equal(KroneckerProduct(D, C)) False >>> KroneckerProduct(A, B).structurally_equal(C) False ''' # Inspired by BlockMatrix return (isinstance(other, KroneckerProduct) and self.shape == other.shape and len(self.args) == len(other.args) and all(a.shape == b.shape for (a, b) in zip(self.args, other.args))) def has_matching_shape(self, other): '''Determine whether two matrices have the appropriate structure to bring matrix multiplication inside the KroneckerProdut Examples ======== >>> from sympy import KroneckerProduct, MatrixSymbol, symbols >>> m, n = symbols(r'm, n', integer=True) >>> A = MatrixSymbol('A', m, n) >>> B = MatrixSymbol('B', n, m) >>> KroneckerProduct(A, B).has_matching_shape(KroneckerProduct(B, A)) True >>> KroneckerProduct(A, B).has_matching_shape(KroneckerProduct(A, B)) False >>> KroneckerProduct(A, B).has_matching_shape(A) False ''' return (isinstance(other, KroneckerProduct) and self.cols == other.rows and len(self.args) == len(other.args) and all(a.cols == b.rows for (a, b) in zip(self.args, other.args))) def _eval_expand_kroneckerproduct(self, **hints): return flatten(canon(typed({KroneckerProduct: distribute(KroneckerProduct, MatAdd)}))(self)) def _kronecker_add(self, other): if self.structurally_equal(other): return self.__class__(*[a + b for (a, b) in zip(self.args, other.args)]) else: return self + other def _kronecker_mul(self, other): if self.has_matching_shape(other): return self.__class__(*[a*b for (a, b) in zip(self.args, other.args)]) else: return self * other def doit(self, **kwargs): deep = kwargs.get('deep', True) if deep: args = [arg.doit(**kwargs) for arg in self.args] else: args = self.args return canonicalize(KroneckerProduct(*args)) def validate(*args): if not all(arg.is_Matrix for arg in args): raise TypeError("Mix of Matrix and Scalar symbols") # rules def extract_commutative(kron): c_part = [] nc_part = [] for arg in kron.args: c, nc = arg.args_cnc() c_part.extend(c) nc_part.append(Mul._from_args(nc)) c_part = Mul(*c_part) if c_part != 1: return c_part*KroneckerProduct(*nc_part) return kron def matrix_kronecker_product(*matrices): """Compute the Kronecker product of a sequence of SymPy Matrices. This is the standard Kronecker product of matrices [1]. Parameters ========== matrices : tuple of MatrixBase instances The matrices to take the Kronecker product of. Returns ======= matrix : MatrixBase The Kronecker product matrix. Examples ======== >>> from sympy import Matrix >>> from sympy.matrices.expressions.kronecker import ( ... matrix_kronecker_product) >>> m1 = Matrix([[1,2],[3,4]]) >>> m2 = Matrix([[1,0],[0,1]]) >>> matrix_kronecker_product(m1, m2) Matrix([ [1, 0, 2, 0], [0, 1, 0, 2], [3, 0, 4, 0], [0, 3, 0, 4]]) >>> matrix_kronecker_product(m2, m1) Matrix([ [1, 2, 0, 0], [3, 4, 0, 0], [0, 0, 1, 2], [0, 0, 3, 4]]) References ========== [1] https://en.wikipedia.org/wiki/Kronecker_product """ # Make sure we have a sequence of Matrices if not all(isinstance(m, MatrixBase) for m in matrices): raise TypeError( 'Sequence of Matrices expected, got: %s' % repr(matrices) ) # Pull out the first element in the product. matrix_expansion = matrices[-1] # Do the kronecker product working from right to left. for mat in reversed(matrices[:-1]): rows = mat.rows cols = mat.cols # Go through each row appending kronecker product to. # running matrix_expansion. for i in range(rows): start = matrix_expansion*mat[i*cols] # Go through each column joining each item for j in range(cols - 1): start = start.row_join( matrix_expansion*mat[i*cols + j + 1] ) # If this is the first element, make it the start of the # new row. if i == 0: next = start else: next = next.col_join(start) matrix_expansion = next MatrixClass = max(matrices, key=lambda M: M._class_priority).__class__ if isinstance(matrix_expansion, MatrixClass): return matrix_expansion else: return MatrixClass(matrix_expansion) def explicit_kronecker_product(kron): # Make sure we have a sequence of Matrices if not all(isinstance(m, MatrixBase) for m in kron.args): return kron return matrix_kronecker_product(*kron.args) rules = (unpack, explicit_kronecker_product, flatten, extract_commutative) canonicalize = exhaust(condition(lambda x: isinstance(x, KroneckerProduct), do_one(*rules))) def _kronecker_dims_key(expr): if isinstance(expr, KroneckerProduct): return tuple(a.shape for a in expr.args) else: return (0,) def kronecker_mat_add(expr): from functools import reduce args = sift(expr.args, _kronecker_dims_key) nonkrons = args.pop((0,), None) if not args: return expr krons = [reduce(lambda x, y: x._kronecker_add(y), group) for group in args.values()] if not nonkrons: return MatAdd(*krons) else: return MatAdd(*krons) + nonkrons def kronecker_mat_mul(expr): # modified from block matrix code factor, matrices = expr.as_coeff_matrices() i = 0 while i < len(matrices) - 1: A, B = matrices[i:i+2] if isinstance(A, KroneckerProduct) and isinstance(B, KroneckerProduct): matrices[i] = A._kronecker_mul(B) matrices.pop(i+1) else: i += 1 return factor*MatMul(*matrices) def kronecker_mat_pow(expr): if isinstance(expr.base, KroneckerProduct) and all(a.is_square for a in expr.base.args): return KroneckerProduct(*[MatPow(a, expr.exp) for a in expr.base.args]) else: return expr def combine_kronecker(expr): """Combine KronekeckerProduct with expression. If possible write operations on KroneckerProducts of compatible shapes as a single KroneckerProduct. Examples ======== >>> from sympy.matrices.expressions import MatrixSymbol, KroneckerProduct, combine_kronecker >>> from sympy import symbols >>> m, n = symbols(r'm, n', integer=True) >>> A = MatrixSymbol('A', m, n) >>> B = MatrixSymbol('B', n, m) >>> combine_kronecker(KroneckerProduct(A, B)*KroneckerProduct(B, A)) KroneckerProduct(A*B, B*A) >>> combine_kronecker(KroneckerProduct(A, B)+KroneckerProduct(B.T, A.T)) KroneckerProduct(A + B.T, B + A.T) >>> C = MatrixSymbol('C', n, n) >>> D = MatrixSymbol('D', m, m) >>> combine_kronecker(KroneckerProduct(C, D)**m) KroneckerProduct(C**m, D**m) """ def haskron(expr): return isinstance(expr, MatrixExpr) and expr.has(KroneckerProduct) rule = exhaust( bottom_up(exhaust(condition(haskron, typed( {MatAdd: kronecker_mat_add, MatMul: kronecker_mat_mul, MatPow: kronecker_mat_pow}))))) result = rule(expr) doit = getattr(result, 'doit', None) if doit is not None: return doit() else: return result
11a386e94b15a2b85fa6eef8696c1035828044b3acd080b02cb961a99481eff8
from sympy.core import Mul, sympify from sympy.matrices.common import ShapeError from sympy.matrices.expressions.matexpr import MatrixExpr from sympy.matrices.expressions.special import ZeroMatrix, OneMatrix from sympy.strategies import ( unpack, flatten, condition, exhaust, rm_id, sort ) def hadamard_product(*matrices): """ Return the elementwise (aka Hadamard) product of matrices. Examples ======== >>> from sympy.matrices import hadamard_product, MatrixSymbol >>> A = MatrixSymbol('A', 2, 3) >>> B = MatrixSymbol('B', 2, 3) >>> hadamard_product(A) A >>> hadamard_product(A, B) HadamardProduct(A, B) >>> hadamard_product(A, B)[0, 1] A[0, 1]*B[0, 1] """ if not matrices: raise TypeError("Empty Hadamard product is undefined") validate(*matrices) if len(matrices) == 1: return matrices[0] else: matrices = [i for i in matrices if not i.is_Identity] return HadamardProduct(*matrices).doit() class HadamardProduct(MatrixExpr): """ Elementwise product of matrix expressions Examples ======== Hadamard product for matrix symbols: >>> from sympy.matrices import hadamard_product, HadamardProduct, MatrixSymbol >>> A = MatrixSymbol('A', 5, 5) >>> B = MatrixSymbol('B', 5, 5) >>> isinstance(hadamard_product(A, B), HadamardProduct) True Notes ===== This is a symbolic object that simply stores its argument without evaluating it. To actually compute the product, use the function ``hadamard_product()`` or ``HadamardProduct.doit`` """ is_HadamardProduct = True def __new__(cls, *args, evaluate=False, check=True): args = list(map(sympify, args)) if check: validate(*args) obj = super().__new__(cls, *args) if evaluate: obj = obj.doit(deep=False) return obj @property def shape(self): return self.args[0].shape def _entry(self, i, j, **kwargs): return Mul(*[arg._entry(i, j, **kwargs) for arg in self.args]) def _eval_transpose(self): from sympy.matrices.expressions.transpose import transpose return HadamardProduct(*list(map(transpose, self.args))) def doit(self, **ignored): expr = self.func(*[i.doit(**ignored) for i in self.args]) # Check for explicit matrices: from sympy import MatrixBase from sympy.matrices.immutable import ImmutableMatrix explicit = [i for i in expr.args if isinstance(i, MatrixBase)] if explicit: remainder = [i for i in expr.args if i not in explicit] expl_mat = ImmutableMatrix([ Mul.fromiter(i) for i in zip(*explicit) ]).reshape(*self.shape) expr = HadamardProduct(*([expl_mat] + remainder)) return canonicalize(expr) def _eval_derivative(self, x): from sympy import Add terms = [] args = list(self.args) for i in range(len(args)): factors = args[:i] + [args[i].diff(x)] + args[i+1:] terms.append(hadamard_product(*factors)) return Add.fromiter(terms) def _eval_derivative_matrix_lines(self, x): from sympy.core.expr import ExprBuilder from sympy.codegen.array_utils import CodegenArrayDiagonal, CodegenArrayTensorProduct from sympy.matrices.expressions.matexpr import _make_matrix with_x_ind = [i for i, arg in enumerate(self.args) if arg.has(x)] lines = [] for ind in with_x_ind: left_args = self.args[:ind] right_args = self.args[ind+1:] d = self.args[ind]._eval_derivative_matrix_lines(x) hadam = hadamard_product(*(right_args + left_args)) diagonal = [(0, 2), (3, 4)] diagonal = [e for j, e in enumerate(diagonal) if self.shape[j] != 1] for i in d: l1 = i._lines[i._first_line_index] l2 = i._lines[i._second_line_index] subexpr = ExprBuilder( CodegenArrayDiagonal, [ ExprBuilder( CodegenArrayTensorProduct, [ ExprBuilder(_make_matrix, [l1]), hadam, ExprBuilder(_make_matrix, [l2]), ] ), *diagonal], ) i._first_pointer_parent = subexpr.args[0].args[0].args i._first_pointer_index = 0 i._second_pointer_parent = subexpr.args[0].args[2].args i._second_pointer_index = 0 i._lines = [subexpr] lines.append(i) return lines def validate(*args): if not all(arg.is_Matrix for arg in args): raise TypeError("Mix of Matrix and Scalar symbols") A = args[0] for B in args[1:]: if A.shape != B.shape: raise ShapeError("Matrices %s and %s are not aligned" % (A, B)) # TODO Implement algorithm for rewriting Hadamard product as diagonal matrix # if matmul identy matrix is multiplied. def canonicalize(x): """Canonicalize the Hadamard product ``x`` with mathematical properties. Examples ======== >>> from sympy.matrices.expressions import MatrixSymbol, HadamardProduct >>> from sympy.matrices.expressions import OneMatrix, ZeroMatrix >>> from sympy.matrices.expressions.hadamard import canonicalize >>> from sympy import init_printing >>> init_printing(use_unicode=False) >>> A = MatrixSymbol('A', 2, 2) >>> B = MatrixSymbol('B', 2, 2) >>> C = MatrixSymbol('C', 2, 2) Hadamard product associativity: >>> X = HadamardProduct(A, HadamardProduct(B, C)) >>> X A.*(B.*C) >>> canonicalize(X) A.*B.*C Hadamard product commutativity: >>> X = HadamardProduct(A, B) >>> Y = HadamardProduct(B, A) >>> X A.*B >>> Y B.*A >>> canonicalize(X) A.*B >>> canonicalize(Y) A.*B Hadamard product identity: >>> X = HadamardProduct(A, OneMatrix(2, 2)) >>> X A.*1 >>> canonicalize(X) A Absorbing element of Hadamard product: >>> X = HadamardProduct(A, ZeroMatrix(2, 2)) >>> X A.*0 >>> canonicalize(X) 0 Rewriting to Hadamard Power >>> X = HadamardProduct(A, A, A) >>> X A.*A.*A >>> canonicalize(X) .3 A Notes ===== As the Hadamard product is associative, nested products can be flattened. The Hadamard product is commutative so that factors can be sorted for canonical form. A matrix of only ones is an identity for Hadamard product, so every matrices of only ones can be removed. Any zero matrix will make the whole product a zero matrix. Duplicate elements can be collected and rewritten as HadamardPower References ========== .. [1] https://en.wikipedia.org/wiki/Hadamard_product_(matrices) """ from sympy.core.compatibility import default_sort_key # Associativity rule = condition( lambda x: isinstance(x, HadamardProduct), flatten ) fun = exhaust(rule) x = fun(x) # Identity fun = condition( lambda x: isinstance(x, HadamardProduct), rm_id(lambda x: isinstance(x, OneMatrix)) ) x = fun(x) # Absorbing by Zero Matrix def absorb(x): if any(isinstance(c, ZeroMatrix) for c in x.args): return ZeroMatrix(*x.shape) else: return x fun = condition( lambda x: isinstance(x, HadamardProduct), absorb ) x = fun(x) # Rewriting with HadamardPower if isinstance(x, HadamardProduct): from collections import Counter tally = Counter(x.args) new_arg = [] for base, exp in tally.items(): if exp == 1: new_arg.append(base) else: new_arg.append(HadamardPower(base, exp)) x = HadamardProduct(*new_arg) # Commutativity fun = condition( lambda x: isinstance(x, HadamardProduct), sort(default_sort_key) ) x = fun(x) # Unpacking x = unpack(x) return x def hadamard_power(base, exp): base = sympify(base) exp = sympify(exp) if exp == 1: return base if not base.is_Matrix: return base**exp if exp.is_Matrix: raise ValueError("cannot raise expression to a matrix") return HadamardPower(base, exp) class HadamardPower(MatrixExpr): r""" Elementwise power of matrix expressions Parameters ========== base : scalar or matrix exp : scalar or matrix Notes ===== There are four definitions for the hadamard power which can be used. Let's consider `A, B` as `(m, n)` matrices, and `a, b` as scalars. Matrix raised to a scalar exponent: .. math:: A^{\circ b} = \begin{bmatrix} A_{0, 0}^b & A_{0, 1}^b & \cdots & A_{0, n-1}^b \\ A_{1, 0}^b & A_{1, 1}^b & \cdots & A_{1, n-1}^b \\ \vdots & \vdots & \ddots & \vdots \\ A_{m-1, 0}^b & A_{m-1, 1}^b & \cdots & A_{m-1, n-1}^b \end{bmatrix} Scalar raised to a matrix exponent: .. math:: a^{\circ B} = \begin{bmatrix} a^{B_{0, 0}} & a^{B_{0, 1}} & \cdots & a^{B_{0, n-1}} \\ a^{B_{1, 0}} & a^{B_{1, 1}} & \cdots & a^{B_{1, n-1}} \\ \vdots & \vdots & \ddots & \vdots \\ a^{B_{m-1, 0}} & a^{B_{m-1, 1}} & \cdots & a^{B_{m-1, n-1}} \end{bmatrix} Matrix raised to a matrix exponent: .. math:: A^{\circ B} = \begin{bmatrix} A_{0, 0}^{B_{0, 0}} & A_{0, 1}^{B_{0, 1}} & \cdots & A_{0, n-1}^{B_{0, n-1}} \\ A_{1, 0}^{B_{1, 0}} & A_{1, 1}^{B_{1, 1}} & \cdots & A_{1, n-1}^{B_{1, n-1}} \\ \vdots & \vdots & \ddots & \vdots \\ A_{m-1, 0}^{B_{m-1, 0}} & A_{m-1, 1}^{B_{m-1, 1}} & \cdots & A_{m-1, n-1}^{B_{m-1, n-1}} \end{bmatrix} Scalar raised to a scalar exponent: .. math:: a^{\circ b} = a^b """ def __new__(cls, base, exp): base = sympify(base) exp = sympify(exp) if base.is_scalar and exp.is_scalar: return base ** exp if base.is_Matrix and exp.is_Matrix and base.shape != exp.shape: raise ValueError( 'The shape of the base {} and ' 'the shape of the exponent {} do not match.' .format(base.shape, exp.shape) ) obj = super().__new__(cls, base, exp) return obj @property def base(self): return self._args[0] @property def exp(self): return self._args[1] @property def shape(self): if self.base.is_Matrix: return self.base.shape return self.exp.shape def _entry(self, i, j, **kwargs): base = self.base exp = self.exp if base.is_Matrix: a = base._entry(i, j, **kwargs) elif base.is_scalar: a = base else: raise ValueError( 'The base {} must be a scalar or a matrix.'.format(base)) if exp.is_Matrix: b = exp._entry(i, j, **kwargs) elif exp.is_scalar: b = exp else: raise ValueError( 'The exponent {} must be a scalar or a matrix.'.format(exp)) return a ** b def _eval_transpose(self): from sympy.matrices.expressions.transpose import transpose return HadamardPower(transpose(self.base), self.exp) def _eval_derivative(self, x): from sympy import log dexp = self.exp.diff(x) logbase = self.base.applyfunc(log) dlbase = logbase.diff(x) return hadamard_product( dexp*logbase + self.exp*dlbase, self ) def _eval_derivative_matrix_lines(self, x): from sympy.codegen.array_utils import CodegenArrayTensorProduct from sympy.codegen.array_utils import CodegenArrayDiagonal from sympy.core.expr import ExprBuilder from sympy.matrices.expressions.matexpr import _make_matrix lr = self.base._eval_derivative_matrix_lines(x) for i in lr: diagonal = [(1, 2), (3, 4)] diagonal = [e for j, e in enumerate(diagonal) if self.base.shape[j] != 1] l1 = i._lines[i._first_line_index] l2 = i._lines[i._second_line_index] subexpr = ExprBuilder( CodegenArrayDiagonal, [ ExprBuilder( CodegenArrayTensorProduct, [ ExprBuilder(_make_matrix, [l1]), self.exp*hadamard_power(self.base, self.exp-1), ExprBuilder(_make_matrix, [l2]), ] ), *diagonal], validator=CodegenArrayDiagonal._validate ) i._first_pointer_parent = subexpr.args[0].args[0].args i._first_pointer_index = 0 i._first_line_index = 0 i._second_pointer_parent = subexpr.args[0].args[2].args i._second_pointer_index = 0 i._second_line_index = 0 i._lines = [subexpr] return lr
371d82a07cc04241bc67fb7b49e790714fed74d962c32018c7aa5089ea8f8ebb
from sympy.core.compatibility import reduce import operator from sympy.core import Add, Basic, sympify from sympy.core.add import add from sympy.functions import adjoint from sympy.matrices.common import ShapeError from sympy.matrices.matrices import MatrixBase from sympy.matrices.expressions.transpose import transpose from sympy.strategies import (rm_id, unpack, flatten, sort, condition, exhaust, do_one, glom) from sympy.matrices.expressions.matexpr import MatrixExpr from sympy.matrices.expressions.special import ZeroMatrix, GenericZeroMatrix from sympy.utilities import default_sort_key, sift # XXX: MatAdd should perhaps not subclass directly from Add class MatAdd(MatrixExpr, Add): """A Sum of Matrix Expressions MatAdd inherits from and operates like SymPy Add Examples ======== >>> from sympy import MatAdd, MatrixSymbol >>> A = MatrixSymbol('A', 5, 5) >>> B = MatrixSymbol('B', 5, 5) >>> C = MatrixSymbol('C', 5, 5) >>> MatAdd(A, B, C) A + B + C """ is_MatAdd = True identity = GenericZeroMatrix() def __new__(cls, *args, evaluate=False, **kwargs): if not args: return cls.identity # This must be removed aggressively in the constructor to avoid # TypeErrors from GenericZeroMatrix().shape args = filter(lambda i: cls.identity != i, args) args = list(map(sympify, args)) check = kwargs.get('check', False) obj = Basic.__new__(cls, *args) if check: if all(not isinstance(i, MatrixExpr) for i in args): return Add.fromiter(args) validate(*args) if evaluate: if all(not isinstance(i, MatrixExpr) for i in args): return Add(*args, evaluate=True) obj = canonicalize(obj) return obj @property def shape(self): return self.args[0].shape def _entry(self, i, j, **kwargs): return Add(*[arg._entry(i, j, **kwargs) for arg in self.args]) def _eval_transpose(self): return MatAdd(*[transpose(arg) for arg in self.args]).doit() def _eval_adjoint(self): return MatAdd(*[adjoint(arg) for arg in self.args]).doit() def _eval_trace(self): from .trace import trace return Add(*[trace(arg) for arg in self.args]).doit() def doit(self, **kwargs): deep = kwargs.get('deep', True) if deep: args = [arg.doit(**kwargs) for arg in self.args] else: args = self.args return canonicalize(MatAdd(*args)) def _eval_derivative_matrix_lines(self, x): add_lines = [arg._eval_derivative_matrix_lines(x) for arg in self.args] return [j for i in add_lines for j in i] add.register_handlerclass((Add, MatAdd), MatAdd) def validate(*args): if not all(arg.is_Matrix for arg in args): raise TypeError("Mix of Matrix and Scalar symbols") A = args[0] for B in args[1:]: if A.shape != B.shape: raise ShapeError("Matrices %s and %s are not aligned"%(A, B)) factor_of = lambda arg: arg.as_coeff_mmul()[0] matrix_of = lambda arg: unpack(arg.as_coeff_mmul()[1]) def combine(cnt, mat): if cnt == 1: return mat else: return cnt * mat def merge_explicit(matadd): """ Merge explicit MatrixBase arguments Examples ======== >>> from sympy import MatrixSymbol, eye, Matrix, MatAdd, pprint >>> from sympy.matrices.expressions.matadd import merge_explicit >>> A = MatrixSymbol('A', 2, 2) >>> B = eye(2) >>> C = Matrix([[1, 2], [3, 4]]) >>> X = MatAdd(A, B, C) >>> pprint(X) [1 0] [1 2] A + [ ] + [ ] [0 1] [3 4] >>> pprint(merge_explicit(X)) [2 2] A + [ ] [3 5] """ groups = sift(matadd.args, lambda arg: isinstance(arg, MatrixBase)) if len(groups[True]) > 1: return MatAdd(*(groups[False] + [reduce(operator.add, groups[True])])) else: return matadd rules = (rm_id(lambda x: x == 0 or isinstance(x, ZeroMatrix)), unpack, flatten, glom(matrix_of, factor_of, combine), merge_explicit, sort(default_sort_key)) canonicalize = exhaust(condition(lambda x: isinstance(x, MatAdd), do_one(*rules)))
95f139a31470c0b780b9d57ade53179b6b8cbe20e73e9aaab56233c9020592bb
from sympy.matrices.expressions import MatrixSymbol, MatAdd, MatPow, MatMul from sympy.matrices.expressions.special import GenericZeroMatrix, ZeroMatrix from sympy.matrices import eye, ImmutableMatrix from sympy.core import Add, Basic, S from sympy.core.add import add from sympy.testing.pytest import XFAIL, raises X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) def test_evaluate(): assert MatAdd(X, X, evaluate=True) == add(X, X, evaluate=True) == MatAdd(X, X).doit() def test_sort_key(): assert MatAdd(Y, X).doit().args == add(Y, X).doit().args == (X, Y) def test_matadd_sympify(): assert isinstance(MatAdd(eye(1), eye(1)).args[0], Basic) assert isinstance(add(eye(1), eye(1)).args[0], Basic) def test_matadd_of_matrices(): assert MatAdd(eye(2), 4*eye(2), eye(2)).doit() == ImmutableMatrix(6*eye(2)) assert add(eye(2), 4*eye(2), eye(2)).doit() == ImmutableMatrix(6*eye(2)) def test_doit_args(): A = ImmutableMatrix([[1, 2], [3, 4]]) B = ImmutableMatrix([[2, 3], [4, 5]]) assert MatAdd(A, MatPow(B, 2)).doit() == A + B**2 assert MatAdd(A, MatMul(A, B)).doit() == A + A*B assert (MatAdd(A, X, MatMul(A, B), Y, MatAdd(2*A, B)).doit() == add(A, X, MatMul(A, B), Y, add(2*A, B)).doit() == MatAdd(3*A + A*B + B, X, Y)) def test_generic_identity(): assert MatAdd.identity == GenericZeroMatrix() assert MatAdd.identity != S.Zero def test_zero_matrix_add(): assert Add(ZeroMatrix(2, 2), ZeroMatrix(2, 2)) == ZeroMatrix(2, 2) @XFAIL def test_matrix_Add_with_scalar(): raises(TypeError, lambda: Add(0, ZeroMatrix(2, 2)))
2490411d90be8121955583c0b8c04a46419840b6c8ff673292d2c6c46bdf43e1
from sympy.core import I, symbols, Basic, Mul, S from sympy.core.mul import mul from sympy.functions import adjoint, transpose from sympy.matrices import (Identity, Inverse, Matrix, MatrixSymbol, ZeroMatrix, eye, ImmutableMatrix) from sympy.matrices.expressions import Adjoint, Transpose, det, MatPow from sympy.matrices.expressions.special import GenericIdentity from sympy.matrices.expressions.matmul import (factor_in_front, remove_ids, MatMul, combine_powers, any_zeros, unpack, only_squares) from sympy.strategies import null_safe from sympy import refine, Q, Symbol from sympy.testing.pytest import XFAIL n, m, l, k = symbols('n m l k', integer=True) x = symbols('x') A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) C = MatrixSymbol('C', n, n) D = MatrixSymbol('D', n, n) E = MatrixSymbol('E', m, n) def test_evaluate(): assert MatMul(C, C, evaluate=True) == MatMul(C, C).doit() def test_adjoint(): assert adjoint(A*B) == Adjoint(B)*Adjoint(A) assert adjoint(2*A*B) == 2*Adjoint(B)*Adjoint(A) assert adjoint(2*I*C) == -2*I*Adjoint(C) M = Matrix(2, 2, [1, 2 + I, 3, 4]) MA = Matrix(2, 2, [1, 3, 2 - I, 4]) assert adjoint(M) == MA assert adjoint(2*M) == 2*MA assert adjoint(MatMul(2, M)) == MatMul(2, MA).doit() def test_transpose(): assert transpose(A*B) == Transpose(B)*Transpose(A) assert transpose(2*A*B) == 2*Transpose(B)*Transpose(A) assert transpose(2*I*C) == 2*I*Transpose(C) M = Matrix(2, 2, [1, 2 + I, 3, 4]) MT = Matrix(2, 2, [1, 3, 2 + I, 4]) assert transpose(M) == MT assert transpose(2*M) == 2*MT assert transpose(x*M) == x*MT assert transpose(MatMul(2, M)) == MatMul(2, MT).doit() def test_factor_in_front(): assert factor_in_front(MatMul(A, 2, B, evaluate=False)) ==\ MatMul(2, A, B, evaluate=False) def test_remove_ids(): assert remove_ids(MatMul(A, Identity(m), B, evaluate=False)) == \ MatMul(A, B, evaluate=False) assert null_safe(remove_ids)(MatMul(Identity(n), evaluate=False)) == \ MatMul(Identity(n), evaluate=False) def test_combine_powers(): assert combine_powers(MatMul(D, Inverse(D), D, evaluate=False)) == \ MatMul(Identity(n), D, evaluate=False) def test_any_zeros(): assert any_zeros(MatMul(A, ZeroMatrix(m, k), evaluate=False)) == \ ZeroMatrix(n, k) def test_unpack(): assert unpack(MatMul(A, evaluate=False)) == A x = MatMul(A, B) assert unpack(x) == x def test_only_squares(): assert only_squares(C) == [C] assert only_squares(C, D) == [C, D] assert only_squares(C, A, A.T, D) == [C, A*A.T, D] def test_determinant(): assert det(2*C) == 2**n*det(C) assert det(2*C*D) == 2**n*det(C)*det(D) assert det(3*C*A*A.T*D) == 3**n*det(C)*det(A*A.T)*det(D) def test_doit(): assert MatMul(C, 2, D).args == (C, 2, D) assert MatMul(C, 2, D).doit().args == (2, C, D) assert MatMul(C, Transpose(D*C)).args == (C, Transpose(D*C)) assert MatMul(C, Transpose(D*C)).doit(deep=True).args == (C, C.T, D.T) def test_doit_drills_down(): X = ImmutableMatrix([[1, 2], [3, 4]]) Y = ImmutableMatrix([[2, 3], [4, 5]]) assert MatMul(X, MatPow(Y, 2)).doit() == X*Y**2 assert MatMul(C, Transpose(D*C)).doit().args == (C, C.T, D.T) def test_doit_deep_false_still_canonical(): assert (MatMul(C, Transpose(D*C), 2).doit(deep=False).args == (2, C, Transpose(D*C))) def test_matmul_scalar_Matrix_doit(): # Issue 9053 X = Matrix([[1, 2], [3, 4]]) assert MatMul(2, X).doit() == 2*X def test_matmul_sympify(): assert isinstance(MatMul(eye(1), eye(1)).args[0], Basic) def test_collapse_MatrixBase(): A = Matrix([[1, 1], [1, 1]]) B = Matrix([[1, 2], [3, 4]]) assert MatMul(A, B).doit() == ImmutableMatrix([[4, 6], [4, 6]]) def test_refine(): assert refine(C*C.T*D, Q.orthogonal(C)).doit() == D kC = k*C assert refine(kC*C.T, Q.orthogonal(C)).doit() == k*Identity(n) assert refine(kC* kC.T, Q.orthogonal(C)).doit() == (k**2)*Identity(n) def test_matmul_no_matrices(): assert MatMul(1) == 1 assert MatMul(n, m) == n*m assert not isinstance(MatMul(n, m), MatMul) def test_matmul_args_cnc(): assert MatMul(n, A, A.T).args_cnc() == [[n], [A, A.T]] assert MatMul(A, A.T).args_cnc() == [[], [A, A.T]] @XFAIL def test_matmul_args_cnc_symbols(): # Not currently supported a, b = symbols('a b', commutative=False) assert MatMul(n, a, b, A, A.T).args_cnc() == [[n], [a, b, A, A.T]] assert MatMul(n, a, A, b, A.T).args_cnc() == [[n], [a, A, b, A.T]] def test_issue_12950(): M = Matrix([[Symbol("x")]]) * MatrixSymbol("A", 1, 1) assert MatrixSymbol("A", 1, 1).as_explicit()[0]*Symbol('x') == M.as_explicit()[0] def test_construction_with_Mul(): assert Mul(C, D) == MatMul(C, D) assert Mul(D, C) == MatMul(D, C) def test_construction_with_mul(): assert mul(C, D) == MatMul(C, D) assert mul(D, C) == MatMul(D, C) assert mul(C, D) != MatMul(D, C) def test_generic_identity(): assert MatMul.identity == GenericIdentity() assert MatMul.identity != S.One
d72a00e4a4fc717374de7bdf3a70b33a2a02fa28e2815ee1e6140257c75e8bb2
""" Some examples have been taken from: http://www.math.uwaterloo.ca/~hwolkowi//matrixcookbook.pdf """ from sympy import (MatrixSymbol, Inverse, symbols, Determinant, Trace, sin, exp, cos, tan, log, S, sqrt, hadamard_product, DiagMatrix, OneMatrix, HadamardProduct, HadamardPower, KroneckerDelta, Sum, Rational) from sympy import MatAdd, Identity, MatMul, ZeroMatrix from sympy.tensor.array.array_derivatives import ArrayDerivative from sympy.matrices.expressions import hadamard_power k = symbols("k") i, j = symbols("i j") m, n = symbols("m n") X = MatrixSymbol("X", k, k) x = MatrixSymbol("x", k, 1) y = MatrixSymbol("y", k, 1) A = MatrixSymbol("A", k, k) B = MatrixSymbol("B", k, k) C = MatrixSymbol("C", k, k) D = MatrixSymbol("D", k, k) a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) c = MatrixSymbol("c", k, 1) d = MatrixSymbol("d", k, 1) KDelta = lambda i, j: KroneckerDelta(i, j, (0, k-1)) def _check_derivative_with_explicit_matrix(expr, x, diffexpr, dim=2): # TODO: this is commented because it slows down the tests. return expr = expr.xreplace({k: dim}) x = x.xreplace({k: dim}) diffexpr = diffexpr.xreplace({k: dim}) expr = expr.as_explicit() x = x.as_explicit() diffexpr = diffexpr.as_explicit() assert expr.diff(x).reshape(*diffexpr.shape).tomatrix() == diffexpr def test_matrix_derivative_by_scalar(): assert A.diff(i) == ZeroMatrix(k, k) assert (A*(X + B)*c).diff(i) == ZeroMatrix(k, 1) assert x.diff(i) == ZeroMatrix(k, 1) assert (x.T*y).diff(i) == ZeroMatrix(1, 1) assert (x*x.T).diff(i) == ZeroMatrix(k, k) assert (x + y).diff(i) == ZeroMatrix(k, 1) assert hadamard_power(x, 2).diff(i) == ZeroMatrix(k, 1) assert hadamard_power(x, i).diff(i).dummy_eq( HadamardProduct(x.applyfunc(log), HadamardPower(x, i))) assert hadamard_product(x, y).diff(i) == ZeroMatrix(k, 1) assert hadamard_product(i*OneMatrix(k, 1), x, y).diff(i) == hadamard_product(x, y) assert (i*x).diff(i) == x assert (sin(i)*A*B*x).diff(i) == cos(i)*A*B*x assert x.applyfunc(sin).diff(i) == ZeroMatrix(k, 1) assert Trace(i**2*X).diff(i) == 2*i*Trace(X) mu = symbols("mu") expr = (2*mu*x) assert expr.diff(x) == 2*mu*Identity(k) def test_matrix_derivative_non_matrix_result(): # This is a 4-dimensional array: assert A.diff(A) == ArrayDerivative(A, A) assert A.T.diff(A) == ArrayDerivative(A.T, A) assert (2*A).diff(A) == ArrayDerivative(2*A, A) assert MatAdd(A, A).diff(A) == ArrayDerivative(MatAdd(A, A), A) assert (A + B).diff(A) == ArrayDerivative(A + B, A) # TODO: `B` can be removed. def test_matrix_derivative_trivial_cases(): # Cookbook example 33: # TODO: find a way to represent a four-dimensional zero-array: assert X.diff(A) == ArrayDerivative(X, A) def test_matrix_derivative_with_inverse(): # Cookbook example 61: expr = a.T*Inverse(X)*b assert expr.diff(X) == -Inverse(X).T*a*b.T*Inverse(X).T # Cookbook example 62: expr = Determinant(Inverse(X)) # Not implemented yet: # assert expr.diff(X) == -Determinant(X.inv())*(X.inv()).T # Cookbook example 63: expr = Trace(A*Inverse(X)*B) assert expr.diff(X) == -(X**(-1)*B*A*X**(-1)).T # Cookbook example 64: expr = Trace(Inverse(X + A)) assert expr.diff(X) == -(Inverse(X + A)).T**2 def test_matrix_derivative_vectors_and_scalars(): assert x.diff(x) == Identity(k) assert x[i, 0].diff(x[m, 0]).doit() == KDelta(m, i) assert x.T.diff(x) == Identity(k) # Cookbook example 69: expr = x.T*a assert expr.diff(x) == a assert expr[0, 0].diff(x[m, 0]).doit() == a[m, 0] expr = a.T*x assert expr.diff(x) == a # Cookbook example 70: expr = a.T*X*b assert expr.diff(X) == a*b.T # Cookbook example 71: expr = a.T*X.T*b assert expr.diff(X) == b*a.T # Cookbook example 72: expr = a.T*X*a assert expr.diff(X) == a*a.T expr = a.T*X.T*a assert expr.diff(X) == a*a.T # Cookbook example 77: expr = b.T*X.T*X*c assert expr.diff(X) == X*b*c.T + X*c*b.T # Cookbook example 78: expr = (B*x + b).T*C*(D*x + d) assert expr.diff(x) == B.T*C*(D*x + d) + D.T*C.T*(B*x + b) # Cookbook example 81: expr = x.T*B*x assert expr.diff(x) == B*x + B.T*x # Cookbook example 82: expr = b.T*X.T*D*X*c assert expr.diff(X) == D.T*X*b*c.T + D*X*c*b.T # Cookbook example 83: expr = (X*b + c).T*D*(X*b + c) assert expr.diff(X) == D*(X*b + c)*b.T + D.T*(X*b + c)*b.T assert str(expr[0, 0].diff(X[m, n]).doit()) == \ 'b[n, 0]*Sum((c[_i_1, 0] + Sum(X[_i_1, _i_3]*b[_i_3, 0], (_i_3, 0, k - 1)))*D[_i_1, m], (_i_1, 0, k - 1)) + Sum((c[_i_2, 0] + Sum(X[_i_2, _i_4]*b[_i_4, 0], (_i_4, 0, k - 1)))*D[m, _i_2]*b[n, 0], (_i_2, 0, k - 1))' def test_matrix_derivatives_of_traces(): expr = Trace(A)*A assert expr.diff(A) == ArrayDerivative(Trace(A)*A, A) assert expr[i, j].diff(A[m, n]).doit() == ( KDelta(i, m)*KDelta(j, n)*Trace(A) + KDelta(m, n)*A[i, j] ) ## First order: # Cookbook example 99: expr = Trace(X) assert expr.diff(X) == Identity(k) assert expr.rewrite(Sum).diff(X[m, n]).doit() == KDelta(m, n) # Cookbook example 100: expr = Trace(X*A) assert expr.diff(X) == A.T assert expr.rewrite(Sum).diff(X[m, n]).doit() == A[n, m] # Cookbook example 101: expr = Trace(A*X*B) assert expr.diff(X) == A.T*B.T assert expr.rewrite(Sum).diff(X[m, n]).doit().dummy_eq((A.T*B.T)[m, n]) # Cookbook example 102: expr = Trace(A*X.T*B) assert expr.diff(X) == B*A # Cookbook example 103: expr = Trace(X.T*A) assert expr.diff(X) == A # Cookbook example 104: expr = Trace(A*X.T) assert expr.diff(X) == A # Cookbook example 105: # TODO: TensorProduct is not supported #expr = Trace(TensorProduct(A, X)) #assert expr.diff(X) == Trace(A)*Identity(k) ## Second order: # Cookbook example 106: expr = Trace(X**2) assert expr.diff(X) == 2*X.T # Cookbook example 107: expr = Trace(X**2*B) assert expr.diff(X) == (X*B + B*X).T expr = Trace(MatMul(X, X, B)) assert expr.diff(X) == (X*B + B*X).T # Cookbook example 108: expr = Trace(X.T*B*X) assert expr.diff(X) == B*X + B.T*X # Cookbook example 109: expr = Trace(B*X*X.T) assert expr.diff(X) == B*X + B.T*X # Cookbook example 110: expr = Trace(X*X.T*B) assert expr.diff(X) == B*X + B.T*X # Cookbook example 111: expr = Trace(X*B*X.T) assert expr.diff(X) == X*B.T + X*B # Cookbook example 112: expr = Trace(B*X.T*X) assert expr.diff(X) == X*B.T + X*B # Cookbook example 113: expr = Trace(X.T*X*B) assert expr.diff(X) == X*B.T + X*B # Cookbook example 114: expr = Trace(A*X*B*X) assert expr.diff(X) == A.T*X.T*B.T + B.T*X.T*A.T # Cookbook example 115: expr = Trace(X.T*X) assert expr.diff(X) == 2*X expr = Trace(X*X.T) assert expr.diff(X) == 2*X # Cookbook example 116: expr = Trace(B.T*X.T*C*X*B) assert expr.diff(X) == C.T*X*B*B.T + C*X*B*B.T # Cookbook example 117: expr = Trace(X.T*B*X*C) assert expr.diff(X) == B*X*C + B.T*X*C.T # Cookbook example 118: expr = Trace(A*X*B*X.T*C) assert expr.diff(X) == A.T*C.T*X*B.T + C*A*X*B # Cookbook example 119: expr = Trace((A*X*B + C)*(A*X*B + C).T) assert expr.diff(X) == 2*A.T*(A*X*B + C)*B.T # Cookbook example 120: # TODO: no support for TensorProduct. # expr = Trace(TensorProduct(X, X)) # expr = Trace(X)*Trace(X) # expr.diff(X) == 2*Trace(X)*Identity(k) # Higher Order # Cookbook example 121: expr = Trace(X**k) #assert expr.diff(X) == k*(X**(k-1)).T # Cookbook example 122: expr = Trace(A*X**k) #assert expr.diff(X) == # Needs indices # Cookbook example 123: expr = Trace(B.T*X.T*C*X*X.T*C*X*B) assert expr.diff(X) == C*X*X.T*C*X*B*B.T + C.T*X*B*B.T*X.T*C.T*X + C*X*B*B.T*X.T*C*X + C.T*X*X.T*C.T*X*B*B.T # Other # Cookbook example 124: expr = Trace(A*X**(-1)*B) assert expr.diff(X) == -Inverse(X).T*A.T*B.T*Inverse(X).T # Cookbook example 125: expr = Trace(Inverse(X.T*C*X)*A) # Warning: result in the cookbook is equivalent if B and C are symmetric: assert expr.diff(X) == - X.inv().T*A.T*X.inv()*C.inv().T*X.inv().T - X.inv().T*A*X.inv()*C.inv()*X.inv().T # Cookbook example 126: expr = Trace((X.T*C*X).inv()*(X.T*B*X)) assert expr.diff(X) == -2*C*X*(X.T*C*X).inv()*X.T*B*X*(X.T*C*X).inv() + 2*B*X*(X.T*C*X).inv() # Cookbook example 127: expr = Trace((A + X.T*C*X).inv()*(X.T*B*X)) # Warning: result in the cookbook is equivalent if B and C are symmetric: assert expr.diff(X) == B*X*Inverse(A + X.T*C*X) - C*X*Inverse(A + X.T*C*X)*X.T*B*X*Inverse(A + X.T*C*X) - C.T*X*Inverse(A.T + (C*X).T*X)*X.T*B.T*X*Inverse(A.T + (C*X).T*X) + B.T*X*Inverse(A.T + (C*X).T*X) def test_derivatives_of_complicated_matrix_expr(): expr = a.T*(A*X*(X.T*B + X*A) + B.T*X.T*(a*b.T*(X*D*X.T + X*(X.T*B + A*X)*D*B - X.T*C.T*A)*B + B*(X*D.T + B*A*X*A.T - 3*X*D))*B + 42*X*B*X.T*A.T*(X + X.T))*b result = (B*(B*A*X*A.T - 3*X*D + X*D.T) + a*b.T*(X*(A*X + X.T*B)*D*B + X*D*X.T - X.T*C.T*A)*B)*B*b*a.T*B.T + B**2*b*a.T*B.T*X.T*a*b.T*X*D + 42*A*X*B.T*X.T*a*b.T + B*D*B**3*b*a.T*B.T*X.T*a*b.T*X + B*b*a.T*A*X + 42*a*b.T*(X + X.T)*A*X*B.T + b*a.T*X*B*a*b.T*B.T**2*X*D.T + b*a.T*X*B*a*b.T*B.T**3*D.T*(B.T*X + X.T*A.T) + 42*b*a.T*X*B*X.T*A.T + 42*A.T*(X + X.T)*b*a.T*X*B + A.T*B.T**2*X*B*a*b.T*B.T*A + A.T*a*b.T*(A.T*X.T + B.T*X) + A.T*X.T*b*a.T*X*B*a*b.T*B.T**3*D.T + B.T*X*B*a*b.T*B.T*D - 3*B.T*X*B*a*b.T*B.T*D.T - C.T*A*B**2*b*a.T*B.T*X.T*a*b.T + X.T*A.T*a*b.T*A.T assert expr.diff(X) == result def test_mixed_deriv_mixed_expressions(): expr = 3*Trace(A) assert expr.diff(A) == 3*Identity(k) expr = k deriv = expr.diff(A) assert isinstance(deriv, ZeroMatrix) assert deriv == ZeroMatrix(k, k) expr = Trace(A)**2 assert expr.diff(A) == (2*Trace(A))*Identity(k) expr = Trace(A)*A # TODO: this is not yet supported: assert expr.diff(A) == ArrayDerivative(expr, A) expr = Trace(Trace(A)*A) assert expr.diff(A) == (2*Trace(A))*Identity(k) expr = Trace(Trace(Trace(A)*A)*A) assert expr.diff(A) == (3*Trace(A)**2)*Identity(k) def test_derivatives_matrix_norms(): expr = x.T*y assert expr.diff(x) == y assert expr[0, 0].diff(x[m, 0]).doit() == y[m, 0] expr = (x.T*y)**S.Half assert expr.diff(x) == y/(2*sqrt(x.T*y)) expr = (x.T*x)**S.Half assert expr.diff(x) == x*(x.T*x)**Rational(-1, 2) expr = (c.T*a*x.T*b)**S.Half assert expr.diff(x) == b/(2*sqrt(c.T*a*x.T*b))*c.T*a expr = (c.T*a*x.T*b)**Rational(1, 3) assert expr.diff(x) == b*(c.T*a*x.T*b)**Rational(-2, 3)*c.T*a/3 expr = (a.T*X*b)**S.Half assert expr.diff(X) == a/(2*sqrt(a.T*X*b))*b.T expr = d.T*x*(a.T*X*b)**S.Half*y.T*c assert expr.diff(X) == a*x.T*d/(2*sqrt(a.T*X*b))*y.T*c*b.T def test_derivatives_elementwise_applyfunc(): from sympy.matrices.expressions.diagonal import DiagMatrix expr = x.applyfunc(tan) assert expr.diff(x).dummy_eq( DiagMatrix(x.applyfunc(lambda x: tan(x)**2 + 1))) assert expr[i, 0].diff(x[m, 0]).doit() == (tan(x[i, 0])**2 + 1)*KDelta(i, m) _check_derivative_with_explicit_matrix(expr, x, expr.diff(x)) expr = (i**2*x).applyfunc(sin) assert expr.diff(i).dummy_eq( HadamardProduct((2*i)*x, (i**2*x).applyfunc(cos))) assert expr[i, 0].diff(i).doit() == 2*i*x[i, 0]*cos(i**2*x[i, 0]) _check_derivative_with_explicit_matrix(expr, i, expr.diff(i)) expr = (log(i)*A*B).applyfunc(sin) assert expr.diff(i).dummy_eq( HadamardProduct(A*B/i, (log(i)*A*B).applyfunc(cos))) _check_derivative_with_explicit_matrix(expr, i, expr.diff(i)) expr = A*x.applyfunc(exp) assert expr.diff(x).dummy_eq(DiagMatrix(x.applyfunc(exp))*A.T) _check_derivative_with_explicit_matrix(expr, x, expr.diff(x)) expr = x.T*A*x + k*y.applyfunc(sin).T*x assert expr.diff(x).dummy_eq(A.T*x + A*x + k*y.applyfunc(sin)) _check_derivative_with_explicit_matrix(expr, x, expr.diff(x)) expr = x.applyfunc(sin).T*y assert expr.diff(x).dummy_eq(DiagMatrix(x.applyfunc(cos))*y) _check_derivative_with_explicit_matrix(expr, x, expr.diff(x)) expr = (a.T * X * b).applyfunc(sin) assert expr.diff(X).dummy_eq(a*(a.T*X*b).applyfunc(cos)*b.T) _check_derivative_with_explicit_matrix(expr, X, expr.diff(X)) expr = a.T * X.applyfunc(sin) * b assert expr.diff(X).dummy_eq( DiagMatrix(a)*X.applyfunc(cos)*DiagMatrix(b)) _check_derivative_with_explicit_matrix(expr, X, expr.diff(X)) expr = a.T * (A*X*B).applyfunc(sin) * b assert expr.diff(X).dummy_eq( A.T*DiagMatrix(a)*(A*X*B).applyfunc(cos)*DiagMatrix(b)*B.T) _check_derivative_with_explicit_matrix(expr, X, expr.diff(X)) expr = a.T * (A*X*b).applyfunc(sin) * b.T # TODO: not implemented #assert expr.diff(X) == ... #_check_derivative_with_explicit_matrix(expr, X, expr.diff(X)) expr = a.T*A*X.applyfunc(sin)*B*b assert expr.diff(X).dummy_eq( DiagMatrix(A.T*a)*X.applyfunc(cos)*DiagMatrix(B*b)) expr = a.T * (A*X.applyfunc(sin)*B).applyfunc(log) * b # TODO: wrong # assert expr.diff(X) == A.T*DiagMatrix(a)*(A*X.applyfunc(sin)*B).applyfunc(Lambda(k, 1/k))*DiagMatrix(b)*B.T expr = a.T * (X.applyfunc(sin)).applyfunc(log) * b # TODO: wrong # assert expr.diff(X) == DiagMatrix(a)*X.applyfunc(sin).applyfunc(Lambda(k, 1/k))*DiagMatrix(b) def test_derivatives_of_hadamard_expressions(): # Hadamard Product expr = hadamard_product(a, x, b) assert expr.diff(x) == DiagMatrix(hadamard_product(b, a)) expr = a.T*hadamard_product(A, X, B)*b assert expr.diff(X) == DiagMatrix(a)*hadamard_product(B, A)*DiagMatrix(b) # Hadamard Power expr = hadamard_power(x, 2) assert expr.diff(x).doit() == 2*DiagMatrix(x) expr = hadamard_power(x.T, 2) assert expr.diff(x).doit() == 2*DiagMatrix(x) expr = hadamard_power(x, S.Half) assert expr.diff(x) == S.Half*DiagMatrix(hadamard_power(x, Rational(-1, 2))) expr = hadamard_power(a.T*X*b, 2) assert expr.diff(X) == 2*a*a.T*X*b*b.T expr = hadamard_power(a.T*X*b, S.Half) assert expr.diff(X) == a/2*hadamard_power(a.T*X*b, Rational(-1, 2))*b.T
d85a9e44a53fd8dac329c3c2a0d9f863c701b885788431c66a61083f452d753f
from sympy import (plot_implicit, cos, Symbol, symbols, Eq, sin, re, And, Or, exp, I, tan, pi) from sympy.plotting.plot import unset_show from tempfile import NamedTemporaryFile, mkdtemp from sympy.testing.pytest import skip, warns from sympy.external import import_module from sympy.testing.tmpfiles import TmpFileManager import os #Set plots not to show unset_show() def tmp_file(dir=None, name=''): return NamedTemporaryFile( suffix='.png', dir=dir, delete=False).name def plot_and_save(expr, *args, name='', dir=None, **kwargs): p = plot_implicit(expr, *args, **kwargs) p.save(tmp_file(dir=dir, name=name)) # Close the plot to avoid a warning from matplotlib p._backend.close() def plot_implicit_tests(name): temp_dir = mkdtemp() TmpFileManager.tmp_folder(temp_dir) x = Symbol('x') y = Symbol('y') #implicit plot tests plot_and_save(Eq(y, cos(x)), (x, -5, 5), (y, -2, 2), name=name, dir=temp_dir) plot_and_save(Eq(y**2, x**3 - x), (x, -5, 5), (y, -4, 4), name=name, dir=temp_dir) plot_and_save(y > 1 / x, (x, -5, 5), (y, -2, 2), name=name, dir=temp_dir) plot_and_save(y < 1 / tan(x), (x, -5, 5), (y, -2, 2), name=name, dir=temp_dir) plot_and_save(y >= 2 * sin(x) * cos(x), (x, -5, 5), (y, -2, 2), name=name, dir=temp_dir) plot_and_save(y <= x**2, (x, -3, 3), (y, -1, 5), name=name, dir=temp_dir) #Test all input args for plot_implicit plot_and_save(Eq(y**2, x**3 - x), dir=temp_dir) plot_and_save(Eq(y**2, x**3 - x), adaptive=False, dir=temp_dir) plot_and_save(Eq(y**2, x**3 - x), adaptive=False, points=500, dir=temp_dir) plot_and_save(y > x, (x, -5, 5), dir=temp_dir) plot_and_save(And(y > exp(x), y > x + 2), dir=temp_dir) plot_and_save(Or(y > x, y > -x), dir=temp_dir) plot_and_save(x**2 - 1, (x, -5, 5), dir=temp_dir) plot_and_save(x**2 - 1, dir=temp_dir) plot_and_save(y > x, depth=-5, dir=temp_dir) plot_and_save(y > x, depth=5, dir=temp_dir) plot_and_save(y > cos(x), adaptive=False, dir=temp_dir) plot_and_save(y < cos(x), adaptive=False, dir=temp_dir) plot_and_save(And(y > cos(x), Or(y > x, Eq(y, x))), dir=temp_dir) plot_and_save(y - cos(pi / x), dir=temp_dir) #Test plots which cannot be rendered using the adaptive algorithm with warns(UserWarning, match="Adaptive meshing could not be applied"): plot_and_save(Eq(y, re(cos(x) + I*sin(x))), name=name, dir=temp_dir) plot_and_save(x**2 - 1, title='An implicit plot', dir=temp_dir) def test_line_color(): x, y = symbols('x, y') p = plot_implicit(x**2 + y**2 - 1, line_color="green", show=False) assert p._series[0].line_color == "green" p = plot_implicit(x**2 + y**2 - 1, line_color='r', show=False) assert p._series[0].line_color == "r" def test_matplotlib(): matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) if matplotlib: try: plot_implicit_tests('test') test_line_color() finally: TmpFileManager.cleanup() else: skip("Matplotlib not the default backend") def test_region_and(): matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) if not matplotlib: skip("Matplotlib not the default backend") from matplotlib.testing.compare import compare_images test_directory = os.path.dirname(os.path.abspath(__file__)) try: temp_dir = mkdtemp() TmpFileManager.tmp_folder(temp_dir) x, y = symbols('x y') r1 = (x - 1)**2 + y**2 < 2 r2 = (x + 1)**2 + y**2 < 2 test_filename = tmp_file(dir=temp_dir, name="test_region_and") cmp_filename = os.path.join(test_directory, "test_region_and.png") p = plot_implicit(r1 & r2, x, y) p.save(test_filename) compare_images(cmp_filename, test_filename, 0.005) test_filename = tmp_file(dir=temp_dir, name="test_region_or") cmp_filename = os.path.join(test_directory, "test_region_or.png") p = plot_implicit(r1 | r2, x, y) p.save(test_filename) compare_images(cmp_filename, test_filename, 0.005) test_filename = tmp_file(dir=temp_dir, name="test_region_not") cmp_filename = os.path.join(test_directory, "test_region_not.png") p = plot_implicit(~r1, x, y) p.save(test_filename) compare_images(cmp_filename, test_filename, 0.005) test_filename = tmp_file(dir=temp_dir, name="test_region_xor") cmp_filename = os.path.join(test_directory, "test_region_xor.png") p = plot_implicit(r1 ^ r2, x, y) p.save(test_filename) compare_images(cmp_filename, test_filename, 0.005) finally: TmpFileManager.cleanup()
e170df905800b9241b5fc35226851d12fc93cc0bf394b9e2895b483b40c1e096
from __future__ import print_function, division from threading import RLock # it is sufficient to import "pyglet" here once try: import pyglet.gl as pgl except ImportError: raise ImportError("pyglet is required for plotting.\n " "visit http://www.pyglet.org/") from sympy.core.compatibility import is_sequence, SYMPY_INTS from sympy.core.numbers import Integer from sympy.geometry.entity import GeometryEntity from sympy.plotting.pygletplot.plot_axes import PlotAxes from sympy.plotting.pygletplot.plot_mode import PlotMode from sympy.plotting.pygletplot.plot_object import PlotObject from sympy.plotting.pygletplot.plot_window import PlotWindow from sympy.plotting.pygletplot.util import parse_option_string from sympy.utilities.decorator import doctest_depends_on from time import sleep from os import getcwd, listdir import ctypes @doctest_depends_on(modules=('pyglet',)) class PygletPlot(object): """ Plot Examples ============= See examples/advanced/pyglet_plotting.py for many more examples. >>> from sympy.plotting.pygletplot import PygletPlot as Plot >>> from sympy.abc import x, y, z >>> Plot(x*y**3-y*x**3) [0]: -x**3*y + x*y**3, 'mode=cartesian' >>> p = Plot() >>> p[1] = x*y >>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4) >>> p = Plot() >>> p[1] = x**2+y**2 >>> p[2] = -x**2-y**2 Variable Intervals ================== The basic format is [var, min, max, steps], but the syntax is flexible and arguments left out are taken from the defaults for the current coordinate mode: >>> Plot(x**2) # implies [x,-5,5,100] [0]: x**2, 'mode=cartesian' >>> Plot(x**2, [], []) # [x,-1,1,40], [y,-1,1,40] [0]: x**2, 'mode=cartesian' >>> Plot(x**2-y**2, [100], [100]) # [x,-1,1,100], [y,-1,1,100] [0]: x**2 - y**2, 'mode=cartesian' >>> Plot(x**2, [x,-13,13,100]) [0]: x**2, 'mode=cartesian' >>> Plot(x**2, [-13,13]) # [x,-13,13,100] [0]: x**2, 'mode=cartesian' >>> Plot(x**2, [x,-13,13]) # [x,-13,13,10] [0]: x**2, 'mode=cartesian' >>> Plot(1*x, [], [x], mode='cylindrical') ... # [unbound_theta,0,2*Pi,40], [x,-1,1,20] [0]: x, 'mode=cartesian' Coordinate Modes ================ Plot supports several curvilinear coordinate modes, and they independent for each plotted function. You can specify a coordinate mode explicitly with the 'mode' named argument, but it can be automatically determined for Cartesian or parametric plots, and therefore must only be specified for polar, cylindrical, and spherical modes. Specifically, Plot(function arguments) and Plot[n] = (function arguments) will interpret your arguments as a Cartesian plot if you provide one function and a parametric plot if you provide two or three functions. Similarly, the arguments will be interpreted as a curve if one variable is used, and a surface if two are used. Supported mode names by number of variables: 1: parametric, cartesian, polar 2: parametric, cartesian, cylindrical = polar, spherical >>> Plot(1, mode='spherical') Calculator-like Interface ========================= >>> p = Plot(visible=False) >>> f = x**2 >>> p[1] = f >>> p[2] = f.diff(x) >>> p[3] = f.diff(x).diff(x) >>> p [1]: x**2, 'mode=cartesian' [2]: 2*x, 'mode=cartesian' [3]: 2, 'mode=cartesian' >>> p.show() >>> p.clear() >>> p <blank plot> >>> p[1] = x**2+y**2 >>> p[1].style = 'solid' >>> p[2] = -x**2-y**2 >>> p[2].style = 'wireframe' >>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4) >>> p[1].style = 'both' >>> p[2].style = 'both' >>> p.close() Plot Window Keyboard Controls ============================= Screen Rotation: X,Y axis Arrow Keys, A,S,D,W, Numpad 4,6,8,2 Z axis Q,E, Numpad 7,9 Model Rotation: Z axis Z,C, Numpad 1,3 Zoom: R,F, PgUp,PgDn, Numpad +,- Reset Camera: X, Numpad 5 Camera Presets: XY F1 XZ F2 YZ F3 Perspective F4 Sensitivity Modifier: SHIFT Axes Toggle: Visible F5 Colors F6 Close Window: ESCAPE ============================= """ @doctest_depends_on(modules=('pyglet',)) def __init__(self, *fargs, **win_args): """ Positional Arguments ==================== Any given positional arguments are used to initialize a plot function at index 1. In other words... >>> from sympy.plotting.pygletplot import PygletPlot as Plot >>> from sympy.abc import x >>> p = Plot(x**2, visible=False) ...is equivalent to... >>> p = Plot(visible=False) >>> p[1] = x**2 Note that in earlier versions of the plotting module, you were able to specify multiple functions in the initializer. This functionality has been dropped in favor of better automatic plot plot_mode detection. Named Arguments =============== axes An option string of the form "key1=value1; key2 = value2" which can use the following options: style = ordinate none OR frame OR box OR ordinate stride = 0.25 val OR (val_x, val_y, val_z) overlay = True (draw on top of plot) True OR False colored = False (False uses Black, True uses colors R,G,B = X,Y,Z) True OR False label_axes = False (display axis names at endpoints) True OR False visible = True (show immediately True OR False The following named arguments are passed as arguments to window initialization: antialiasing = True True OR False ortho = False True OR False invert_mouse_zoom = False True OR False """ # Register the plot modes from . import plot_modes # noqa self._win_args = win_args self._window = None self._render_lock = RLock() self._functions = {} self._pobjects = [] self._screenshot = ScreenShot(self) axe_options = parse_option_string(win_args.pop('axes', '')) self.axes = PlotAxes(**axe_options) self._pobjects.append(self.axes) self[0] = fargs if win_args.get('visible', True): self.show() ## Window Interfaces def show(self): """ Creates and displays a plot window, or activates it (gives it focus) if it has already been created. """ if self._window and not self._window.has_exit: self._window.activate() else: self._win_args['visible'] = True self.axes.reset_resources() #if hasattr(self, '_doctest_depends_on'): # self._win_args['runfromdoctester'] = True self._window = PlotWindow(self, **self._win_args) def close(self): """ Closes the plot window. """ if self._window: self._window.close() def saveimage(self, outfile=None, format='', size=(600, 500)): """ Saves a screen capture of the plot window to an image file. If outfile is given, it can either be a path or a file object. Otherwise a png image will be saved to the current working directory. If the format is omitted, it is determined from the filename extension. """ self._screenshot.save(outfile, format, size) ## Function List Interfaces def clear(self): """ Clears the function list of this plot. """ self._render_lock.acquire() self._functions = {} self.adjust_all_bounds() self._render_lock.release() def __getitem__(self, i): """ Returns the function at position i in the function list. """ return self._functions[i] def __setitem__(self, i, args): """ Parses and adds a PlotMode to the function list. """ if not (isinstance(i, (SYMPY_INTS, Integer)) and i >= 0): raise ValueError("Function index must " "be an integer >= 0.") if isinstance(args, PlotObject): f = args else: if (not is_sequence(args)) or isinstance(args, GeometryEntity): args = [args] if len(args) == 0: return # no arguments given kwargs = dict(bounds_callback=self.adjust_all_bounds) f = PlotMode(*args, **kwargs) if f: self._render_lock.acquire() self._functions[i] = f self._render_lock.release() else: raise ValueError("Failed to parse '%s'." % ', '.join(str(a) for a in args)) def __delitem__(self, i): """ Removes the function in the function list at position i. """ self._render_lock.acquire() del self._functions[i] self.adjust_all_bounds() self._render_lock.release() def firstavailableindex(self): """ Returns the first unused index in the function list. """ i = 0 self._render_lock.acquire() while i in self._functions: i += 1 self._render_lock.release() return i def append(self, *args): """ Parses and adds a PlotMode to the function list at the first available index. """ self.__setitem__(self.firstavailableindex(), args) def __len__(self): """ Returns the number of functions in the function list. """ return len(self._functions) def __iter__(self): """ Allows iteration of the function list. """ return self._functions.itervalues() def __repr__(self): return str(self) def __str__(self): """ Returns a string containing a new-line separated list of the functions in the function list. """ s = "" if len(self._functions) == 0: s += "<blank plot>" else: self._render_lock.acquire() s += "\n".join(["%s[%i]: %s" % ("", i, str(self._functions[i])) for i in self._functions]) self._render_lock.release() return s def adjust_all_bounds(self): self._render_lock.acquire() self.axes.reset_bounding_box() for f in self._functions: self.axes.adjust_bounds(self._functions[f].bounds) self._render_lock.release() def wait_for_calculations(self): sleep(0) self._render_lock.acquire() for f in self._functions: a = self._functions[f]._get_calculating_verts b = self._functions[f]._get_calculating_cverts while a() or b(): sleep(0) self._render_lock.release() class ScreenShot: def __init__(self, plot): self._plot = plot self.screenshot_requested = False self.outfile = None self.format = '' self.invisibleMode = False self.flag = 0 def __bool__(self): return self.screenshot_requested def _execute_saving(self): if self.flag < 3: self.flag += 1 return size_x, size_y = self._plot._window.get_size() size = size_x*size_y*4*ctypes.sizeof(ctypes.c_ubyte) image = ctypes.create_string_buffer(size) pgl.glReadPixels(0, 0, size_x, size_y, pgl.GL_RGBA, pgl.GL_UNSIGNED_BYTE, image) from PIL import Image im = Image.frombuffer('RGBA', (size_x, size_y), image.raw, 'raw', 'RGBA', 0, 1) im.transpose(Image.FLIP_TOP_BOTTOM).save(self.outfile, self.format) self.flag = 0 self.screenshot_requested = False if self.invisibleMode: self._plot._window.close() def save(self, outfile=None, format='', size=(600, 500)): self.outfile = outfile self.format = format self.size = size self.screenshot_requested = True if not self._plot._window or self._plot._window.has_exit: self._plot._win_args['visible'] = False self._plot._win_args['width'] = size[0] self._plot._win_args['height'] = size[1] self._plot.axes.reset_resources() self._plot._window = PlotWindow(self._plot, **self._plot._win_args) self.invisibleMode = True if self.outfile is None: self.outfile = self._create_unique_path() print(self.outfile) def _create_unique_path(self): cwd = getcwd() l = listdir(cwd) path = '' i = 0 while True: if not 'plot_%s.png' % i in l: path = cwd + '/plot_%s.png' % i break i += 1 return path
e8bae3ed8e06010beeed5d12bfe3b19c99c9f9fd26e56718a2eb0bcb316b788a
from __future__ import print_function, division import pyglet.gl as pgl from sympy.core import S from sympy.core.compatibility import is_sequence from sympy.plotting.pygletplot.color_scheme import ColorScheme from sympy.plotting.pygletplot.plot_mode import PlotMode from time import sleep from threading import Thread, Event, RLock import warnings class PlotModeBase(PlotMode): """ Intended parent class for plotting modes. Provides base functionality in conjunction with its parent, PlotMode. """ ## ## Class-Level Attributes ## """ The following attributes are meant to be set at the class level, and serve as parameters to the plot mode registry (in PlotMode). See plot_modes.py for concrete examples. """ """ i_vars 'x' for Cartesian2D 'xy' for Cartesian3D etc. d_vars 'y' for Cartesian2D 'r' for Polar etc. """ i_vars, d_vars = '', '' """ intervals Default intervals for each i_var, and in the same order. Specified [min, max, steps]. No variable can be given (it is bound later). """ intervals = [] """ aliases A list of strings which can be used to access this mode. 'cartesian' for Cartesian2D and Cartesian3D 'polar' for Polar 'cylindrical', 'polar' for Cylindrical Note that _init_mode chooses the first alias in the list as the mode's primary_alias, which will be displayed to the end user in certain contexts. """ aliases = [] """ is_default Whether to set this mode as the default for arguments passed to PlotMode() containing the same number of d_vars as this mode and at most the same number of i_vars. """ is_default = False """ All of the above attributes are defined in PlotMode. The following ones are specific to PlotModeBase. """ """ A list of the render styles. Do not modify. """ styles = {'wireframe': 1, 'solid': 2, 'both': 3} """ style_override Always use this style if not blank. """ style_override = '' """ default_wireframe_color default_solid_color Can be used when color is None or being calculated. Used by PlotCurve and PlotSurface, but not anywhere in PlotModeBase. """ default_wireframe_color = (0.85, 0.85, 0.85) default_solid_color = (0.6, 0.6, 0.9) default_rot_preset = 'xy' ## ## Instance-Level Attributes ## ## 'Abstract' member functions def _get_evaluator(self): if self.use_lambda_eval: try: e = self._get_lambda_evaluator() return e except Exception: warnings.warn("\nWarning: creating lambda evaluator failed. " "Falling back on sympy subs evaluator.") return self._get_sympy_evaluator() def _get_sympy_evaluator(self): raise NotImplementedError() def _get_lambda_evaluator(self): raise NotImplementedError() def _on_calculate_verts(self): raise NotImplementedError() def _on_calculate_cverts(self): raise NotImplementedError() ## Base member functions def __init__(self, *args, bounds_callback=None, **kwargs): self.verts = [] self.cverts = [] self.bounds = [[S.Infinity, S.NegativeInfinity, 0], [S.Infinity, S.NegativeInfinity, 0], [S.Infinity, S.NegativeInfinity, 0]] self.cbounds = [[S.Infinity, S.NegativeInfinity, 0], [S.Infinity, S.NegativeInfinity, 0], [S.Infinity, S.NegativeInfinity, 0]] self._draw_lock = RLock() self._calculating_verts = Event() self._calculating_cverts = Event() self._calculating_verts_pos = 0.0 self._calculating_verts_len = 0.0 self._calculating_cverts_pos = 0.0 self._calculating_cverts_len = 0.0 self._max_render_stack_size = 3 self._draw_wireframe = [-1] self._draw_solid = [-1] self._style = None self._color = None self.predraw = [] self.postdraw = [] self.use_lambda_eval = self.options.pop('use_sympy_eval', None) is None self.style = self.options.pop('style', '') self.color = self.options.pop('color', 'rainbow') self.bounds_callback = bounds_callback self._on_calculate() def synchronized(f): def w(self, *args, **kwargs): self._draw_lock.acquire() try: r = f(self, *args, **kwargs) return r finally: self._draw_lock.release() return w @synchronized def push_wireframe(self, function): """ Push a function which performs gl commands used to build a display list. (The list is built outside of the function) """ assert callable(function) self._draw_wireframe.append(function) if len(self._draw_wireframe) > self._max_render_stack_size: del self._draw_wireframe[1] # leave marker element @synchronized def push_solid(self, function): """ Push a function which performs gl commands used to build a display list. (The list is built outside of the function) """ assert callable(function) self._draw_solid.append(function) if len(self._draw_solid) > self._max_render_stack_size: del self._draw_solid[1] # leave marker element def _create_display_list(self, function): dl = pgl.glGenLists(1) pgl.glNewList(dl, pgl.GL_COMPILE) function() pgl.glEndList() return dl def _render_stack_top(self, render_stack): top = render_stack[-1] if top == -1: return -1 # nothing to display elif callable(top): dl = self._create_display_list(top) render_stack[-1] = (dl, top) return dl # display newly added list elif len(top) == 2: if pgl.GL_TRUE == pgl.glIsList(top[0]): return top[0] # display stored list dl = self._create_display_list(top[1]) render_stack[-1] = (dl, top[1]) return dl # display regenerated list def _draw_solid_display_list(self, dl): pgl.glPushAttrib(pgl.GL_ENABLE_BIT | pgl.GL_POLYGON_BIT) pgl.glPolygonMode(pgl.GL_FRONT_AND_BACK, pgl.GL_FILL) pgl.glCallList(dl) pgl.glPopAttrib() def _draw_wireframe_display_list(self, dl): pgl.glPushAttrib(pgl.GL_ENABLE_BIT | pgl.GL_POLYGON_BIT) pgl.glPolygonMode(pgl.GL_FRONT_AND_BACK, pgl.GL_LINE) pgl.glEnable(pgl.GL_POLYGON_OFFSET_LINE) pgl.glPolygonOffset(-0.005, -50.0) pgl.glCallList(dl) pgl.glPopAttrib() @synchronized def draw(self): for f in self.predraw: if callable(f): f() if self.style_override: style = self.styles[self.style_override] else: style = self.styles[self._style] # Draw solid component if style includes solid if style & 2: dl = self._render_stack_top(self._draw_solid) if dl > 0 and pgl.GL_TRUE == pgl.glIsList(dl): self._draw_solid_display_list(dl) # Draw wireframe component if style includes wireframe if style & 1: dl = self._render_stack_top(self._draw_wireframe) if dl > 0 and pgl.GL_TRUE == pgl.glIsList(dl): self._draw_wireframe_display_list(dl) for f in self.postdraw: if callable(f): f() def _on_change_color(self, color): Thread(target=self._calculate_cverts).start() def _on_calculate(self): Thread(target=self._calculate_all).start() def _calculate_all(self): self._calculate_verts() self._calculate_cverts() def _calculate_verts(self): if self._calculating_verts.isSet(): return self._calculating_verts.set() try: self._on_calculate_verts() finally: self._calculating_verts.clear() if callable(self.bounds_callback): self.bounds_callback() def _calculate_cverts(self): if self._calculating_verts.isSet(): return while self._calculating_cverts.isSet(): sleep(0) # wait for previous calculation self._calculating_cverts.set() try: self._on_calculate_cverts() finally: self._calculating_cverts.clear() def _get_calculating_verts(self): return self._calculating_verts.isSet() def _get_calculating_verts_pos(self): return self._calculating_verts_pos def _get_calculating_verts_len(self): return self._calculating_verts_len def _get_calculating_cverts(self): return self._calculating_cverts.isSet() def _get_calculating_cverts_pos(self): return self._calculating_cverts_pos def _get_calculating_cverts_len(self): return self._calculating_cverts_len ## Property handlers def _get_style(self): return self._style @synchronized def _set_style(self, v): if v is None: return if v == '': step_max = 0 for i in self.intervals: if i.v_steps is None: continue step_max = max([step_max, int(i.v_steps)]) v = ['both', 'solid'][step_max > 40] if v not in self.styles: raise ValueError("v should be there in self.styles") if v == self._style: return self._style = v def _get_color(self): return self._color @synchronized def _set_color(self, v): try: if v is not None: if is_sequence(v): v = ColorScheme(*v) else: v = ColorScheme(v) if repr(v) == repr(self._color): return self._on_change_color(v) self._color = v except Exception as e: raise RuntimeError(("Color change failed. " "Reason: %s" % (str(e)))) style = property(_get_style, _set_style) color = property(_get_color, _set_color) calculating_verts = property(_get_calculating_verts) calculating_verts_pos = property(_get_calculating_verts_pos) calculating_verts_len = property(_get_calculating_verts_len) calculating_cverts = property(_get_calculating_cverts) calculating_cverts_pos = property(_get_calculating_cverts_pos) calculating_cverts_len = property(_get_calculating_cverts_len) ## String representations def __str__(self): f = ", ".join(str(d) for d in self.d_vars) o = "'mode=%s'" % (self.primary_alias) return ", ".join([f, o]) def __repr__(self): f = ", ".join(str(d) for d in self.d_vars) i = ", ".join(str(i) for i in self.intervals) d = [('mode', self.primary_alias), ('color', str(self.color)), ('style', str(self.style))] o = "'%s'" % (("; ".join("%s=%s" % (k, v) for k, v in d if v != 'None'))) return ", ".join([f, i, o])
26b6a884865e42aa43d84f60acb2e26b17e8208846ab6253abaa62687d2c9aa3
from __future__ import print_function, division from pyglet.window import key from pyglet.window.mouse import LEFT, RIGHT, MIDDLE from sympy.plotting.pygletplot.util import get_direction_vectors, get_basis_vectors class PlotController(object): normal_mouse_sensitivity = 4.0 modified_mouse_sensitivity = 1.0 normal_key_sensitivity = 160.0 modified_key_sensitivity = 40.0 keymap = { key.LEFT: 'left', key.A: 'left', key.NUM_4: 'left', key.RIGHT: 'right', key.D: 'right', key.NUM_6: 'right', key.UP: 'up', key.W: 'up', key.NUM_8: 'up', key.DOWN: 'down', key.S: 'down', key.NUM_2: 'down', key.Z: 'rotate_z_neg', key.NUM_1: 'rotate_z_neg', key.C: 'rotate_z_pos', key.NUM_3: 'rotate_z_pos', key.Q: 'spin_left', key.NUM_7: 'spin_left', key.E: 'spin_right', key.NUM_9: 'spin_right', key.X: 'reset_camera', key.NUM_5: 'reset_camera', key.NUM_ADD: 'zoom_in', key.PAGEUP: 'zoom_in', key.R: 'zoom_in', key.NUM_SUBTRACT: 'zoom_out', key.PAGEDOWN: 'zoom_out', key.F: 'zoom_out', key.RSHIFT: 'modify_sensitivity', key.LSHIFT: 'modify_sensitivity', key.F1: 'rot_preset_xy', key.F2: 'rot_preset_xz', key.F3: 'rot_preset_yz', key.F4: 'rot_preset_perspective', key.F5: 'toggle_axes', key.F6: 'toggle_axe_colors', key.F8: 'save_image' } def __init__(self, window, *, invert_mouse_zoom=False, **kwargs): self.invert_mouse_zoom = invert_mouse_zoom self.window = window self.camera = window.camera self.action = { # Rotation around the view Y (up) vector 'left': False, 'right': False, # Rotation around the view X vector 'up': False, 'down': False, # Rotation around the view Z vector 'spin_left': False, 'spin_right': False, # Rotation around the model Z vector 'rotate_z_neg': False, 'rotate_z_pos': False, # Reset to the default rotation 'reset_camera': False, # Performs camera z-translation 'zoom_in': False, 'zoom_out': False, # Use alternative sensitivity (speed) 'modify_sensitivity': False, # Rotation presets 'rot_preset_xy': False, 'rot_preset_xz': False, 'rot_preset_yz': False, 'rot_preset_perspective': False, # axes 'toggle_axes': False, 'toggle_axe_colors': False, # screenshot 'save_image': False } def update(self, dt): z = 0 if self.action['zoom_out']: z -= 1 if self.action['zoom_in']: z += 1 if z != 0: self.camera.zoom_relative(z/10.0, self.get_key_sensitivity()/10.0) dx, dy, dz = 0, 0, 0 if self.action['left']: dx -= 1 if self.action['right']: dx += 1 if self.action['up']: dy -= 1 if self.action['down']: dy += 1 if self.action['spin_left']: dz += 1 if self.action['spin_right']: dz -= 1 if not self.is_2D(): if dx != 0: self.camera.euler_rotate(dx*dt*self.get_key_sensitivity(), *(get_direction_vectors()[1])) if dy != 0: self.camera.euler_rotate(dy*dt*self.get_key_sensitivity(), *(get_direction_vectors()[0])) if dz != 0: self.camera.euler_rotate(dz*dt*self.get_key_sensitivity(), *(get_direction_vectors()[2])) else: self.camera.mouse_translate(0, 0, dx*dt*self.get_key_sensitivity(), -dy*dt*self.get_key_sensitivity()) rz = 0 if self.action['rotate_z_neg'] and not self.is_2D(): rz -= 1 if self.action['rotate_z_pos'] and not self.is_2D(): rz += 1 if rz != 0: self.camera.euler_rotate(rz*dt*self.get_key_sensitivity(), *(get_basis_vectors()[2])) if self.action['reset_camera']: self.camera.reset() if self.action['rot_preset_xy']: self.camera.set_rot_preset('xy') if self.action['rot_preset_xz']: self.camera.set_rot_preset('xz') if self.action['rot_preset_yz']: self.camera.set_rot_preset('yz') if self.action['rot_preset_perspective']: self.camera.set_rot_preset('perspective') if self.action['toggle_axes']: self.action['toggle_axes'] = False self.camera.axes.toggle_visible() if self.action['toggle_axe_colors']: self.action['toggle_axe_colors'] = False self.camera.axes.toggle_colors() if self.action['save_image']: self.action['save_image'] = False self.window.plot.saveimage() return True def get_mouse_sensitivity(self): if self.action['modify_sensitivity']: return self.modified_mouse_sensitivity else: return self.normal_mouse_sensitivity def get_key_sensitivity(self): if self.action['modify_sensitivity']: return self.modified_key_sensitivity else: return self.normal_key_sensitivity def on_key_press(self, symbol, modifiers): if symbol in self.keymap: self.action[self.keymap[symbol]] = True def on_key_release(self, symbol, modifiers): if symbol in self.keymap: self.action[self.keymap[symbol]] = False def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): if buttons & LEFT: if self.is_2D(): self.camera.mouse_translate(x, y, dx, dy) else: self.camera.spherical_rotate((x - dx, y - dy), (x, y), self.get_mouse_sensitivity()) if buttons & MIDDLE: self.camera.zoom_relative([1, -1][self.invert_mouse_zoom]*dy, self.get_mouse_sensitivity()/20.0) if buttons & RIGHT: self.camera.mouse_translate(x, y, dx, dy) def on_mouse_scroll(self, x, y, dx, dy): self.camera.zoom_relative([1, -1][self.invert_mouse_zoom]*dy, self.get_mouse_sensitivity()) def is_2D(self): functions = self.window.plot._functions for i in functions: if len(functions[i].i_vars) > 1 or len(functions[i].d_vars) > 2: return False return True
d974cccf37bb0bc76fa37a64bb43f8b4733e8599de3d8d7d75a7f2941a7b5cda
from __future__ import print_function, division import pyglet.gl as pgl from pyglet import font from sympy.core import S from sympy.core.compatibility import is_sequence from sympy.plotting.pygletplot.plot_object import PlotObject from sympy.plotting.pygletplot.util import billboard_matrix, dot_product, \ get_direction_vectors, strided_range, vec_mag, vec_sub class PlotAxes(PlotObject): def __init__(self, *args, style='', none=None, frame=None, box=None, ordinate=None, stride=0.25, visible='', overlay='', colored='', label_axes='', label_ticks='', tick_length=0.1, font_face='Arial', font_size=28, **kwargs): # initialize style parameter style = style.lower() # allow alias kwargs to override style kwarg if none is not None: style = 'none' if frame is not None: style = 'frame' if box is not None: style = 'box' if ordinate is not None: style = 'ordinate' if style in ['', 'ordinate']: self._render_object = PlotAxesOrdinate(self) elif style in ['frame', 'box']: self._render_object = PlotAxesFrame(self) elif style in ['none']: self._render_object = None else: raise ValueError(("Unrecognized axes style %s.") % (style)) # initialize stride parameter try: stride = eval(stride) except TypeError: pass if is_sequence(stride): if len(stride) != 3: raise ValueError("length should be equal to 3") self._stride = stride else: self._stride = [stride, stride, stride] self._tick_length = float(tick_length) # setup bounding box and ticks self._origin = [0, 0, 0] self.reset_bounding_box() def flexible_boolean(input, default): if input in [True, False]: return input if input in ['f', 'F', 'false', 'False']: return False if input in ['t', 'T', 'true', 'True']: return True return default # initialize remaining parameters self.visible = flexible_boolean(kwargs, True) self._overlay = flexible_boolean(overlay, True) self._colored = flexible_boolean(colored, False) self._label_axes = flexible_boolean(label_axes, False) self._label_ticks = flexible_boolean(label_ticks, True) # setup label font self.font_face = font_face self.font_size = font_size # this is also used to reinit the # font on window close/reopen self.reset_resources() def reset_resources(self): self.label_font = None def reset_bounding_box(self): self._bounding_box = [[None, None], [None, None], [None, None]] self._axis_ticks = [[], [], []] def draw(self): if self._render_object: pgl.glPushAttrib(pgl.GL_ENABLE_BIT | pgl.GL_POLYGON_BIT | pgl.GL_DEPTH_BUFFER_BIT) if self._overlay: pgl.glDisable(pgl.GL_DEPTH_TEST) self._render_object.draw() pgl.glPopAttrib() def adjust_bounds(self, child_bounds): b = self._bounding_box c = child_bounds for i in [0, 1, 2]: if abs(c[i][0]) is S.Infinity or abs(c[i][1]) is S.Infinity: continue b[i][0] = c[i][0] if b[i][0] is None else min([b[i][0], c[i][0]]) b[i][1] = c[i][1] if b[i][1] is None else max([b[i][1], c[i][1]]) self._bounding_box = b self._recalculate_axis_ticks(i) def _recalculate_axis_ticks(self, axis): b = self._bounding_box if b[axis][0] is None or b[axis][1] is None: self._axis_ticks[axis] = [] else: self._axis_ticks[axis] = strided_range(b[axis][0], b[axis][1], self._stride[axis]) def toggle_visible(self): self.visible = not self.visible def toggle_colors(self): self._colored = not self._colored class PlotAxesBase(PlotObject): def __init__(self, parent_axes): self._p = parent_axes def draw(self): color = [([0.2, 0.1, 0.3], [0.2, 0.1, 0.3], [0.2, 0.1, 0.3]), ([0.9, 0.3, 0.5], [0.5, 1.0, 0.5], [0.3, 0.3, 0.9])][self._p._colored] self.draw_background(color) self.draw_axis(2, color[2]) self.draw_axis(1, color[1]) self.draw_axis(0, color[0]) def draw_background(self, color): pass # optional def draw_axis(self, axis, color): raise NotImplementedError() def draw_text(self, text, position, color, scale=1.0): if len(color) == 3: color = (color[0], color[1], color[2], 1.0) if self._p.label_font is None: self._p.label_font = font.load(self._p.font_face, self._p.font_size, bold=True, italic=False) label = font.Text(self._p.label_font, text, color=color, valign=font.Text.BASELINE, halign=font.Text.CENTER) pgl.glPushMatrix() pgl.glTranslatef(*position) billboard_matrix() scale_factor = 0.005 * scale pgl.glScalef(scale_factor, scale_factor, scale_factor) pgl.glColor4f(0, 0, 0, 0) label.draw() pgl.glPopMatrix() def draw_line(self, v, color): o = self._p._origin pgl.glBegin(pgl.GL_LINES) pgl.glColor3f(*color) pgl.glVertex3f(v[0][0] + o[0], v[0][1] + o[1], v[0][2] + o[2]) pgl.glVertex3f(v[1][0] + o[0], v[1][1] + o[1], v[1][2] + o[2]) pgl.glEnd() class PlotAxesOrdinate(PlotAxesBase): def __init__(self, parent_axes): super(PlotAxesOrdinate, self).__init__(parent_axes) def draw_axis(self, axis, color): ticks = self._p._axis_ticks[axis] radius = self._p._tick_length / 2.0 if len(ticks) < 2: return # calculate the vector for this axis axis_lines = [[0, 0, 0], [0, 0, 0]] axis_lines[0][axis], axis_lines[1][axis] = ticks[0], ticks[-1] axis_vector = vec_sub(axis_lines[1], axis_lines[0]) # calculate angle to the z direction vector pos_z = get_direction_vectors()[2] d = abs(dot_product(axis_vector, pos_z)) d = d / vec_mag(axis_vector) # don't draw labels if we're looking down the axis labels_visible = abs(d - 1.0) > 0.02 # draw the ticks and labels for tick in ticks: self.draw_tick_line(axis, color, radius, tick, labels_visible) # draw the axis line and labels self.draw_axis_line(axis, color, ticks[0], ticks[-1], labels_visible) def draw_axis_line(self, axis, color, a_min, a_max, labels_visible): axis_line = [[0, 0, 0], [0, 0, 0]] axis_line[0][axis], axis_line[1][axis] = a_min, a_max self.draw_line(axis_line, color) if labels_visible: self.draw_axis_line_labels(axis, color, axis_line) def draw_axis_line_labels(self, axis, color, axis_line): if not self._p._label_axes: return axis_labels = [axis_line[0][::], axis_line[1][::]] axis_labels[0][axis] -= 0.3 axis_labels[1][axis] += 0.3 a_str = ['X', 'Y', 'Z'][axis] self.draw_text("-" + a_str, axis_labels[0], color) self.draw_text("+" + a_str, axis_labels[1], color) def draw_tick_line(self, axis, color, radius, tick, labels_visible): tick_axis = {0: 1, 1: 0, 2: 1}[axis] tick_line = [[0, 0, 0], [0, 0, 0]] tick_line[0][axis] = tick_line[1][axis] = tick tick_line[0][tick_axis], tick_line[1][tick_axis] = -radius, radius self.draw_line(tick_line, color) if labels_visible: self.draw_tick_line_label(axis, color, radius, tick) def draw_tick_line_label(self, axis, color, radius, tick): if not self._p._label_axes: return tick_label_vector = [0, 0, 0] tick_label_vector[axis] = tick tick_label_vector[{0: 1, 1: 0, 2: 1}[axis]] = [-1, 1, 1][ axis] * radius * 3.5 self.draw_text(str(tick), tick_label_vector, color, scale=0.5) class PlotAxesFrame(PlotAxesBase): def __init__(self, parent_axes): super(PlotAxesFrame, self).__init__(parent_axes) def draw_background(self, color): pass def draw_axis(self, axis, color): raise NotImplementedError()
7d39f3038a5a1219bf9dd31b00111ca6591ea88cea2b48d0fae9b729b663e521
""" Interval Arithmetic for plotting. This module does not implement interval arithmetic accurately and hence cannot be used for purposes other than plotting. If you want to use interval arithmetic, use mpmath's interval arithmetic. The module implements interval arithmetic using numpy and python floating points. The rounding up and down is not handled and hence this is not an accurate implementation of interval arithmetic. The module uses numpy for speed which cannot be achieved with mpmath. """ # Q: Why use numpy? Why not simply use mpmath's interval arithmetic? # A: mpmath's interval arithmetic simulates a floating point unit # and hence is slow, while numpy evaluations are orders of magnitude # faster. # Q: Why create a separate class for intervals? Why not use sympy's # Interval Sets? # A: The functionalities that will be required for plotting is quite # different from what Interval Sets implement. # Q: Why is rounding up and down according to IEEE754 not handled? # A: It is not possible to do it in both numpy and python. An external # library has to used, which defeats the whole purpose i.e., speed. Also # rounding is handled for very few functions in those libraries. # Q Will my plots be affected? # A It will not affect most of the plots. The interval arithmetic # module based suffers the same problems as that of floating point # arithmetic. from __future__ import print_function, division from sympy.core.logic import fuzzy_and from sympy.simplify.simplify import nsimplify from .interval_membership import intervalMembership class interval(object): """ Represents an interval containing floating points as start and end of the interval The is_valid variable tracks whether the interval obtained as the result of the function is in the domain and is continuous. - True: Represents the interval result of a function is continuous and in the domain of the function. - False: The interval argument of the function was not in the domain of the function, hence the is_valid of the result interval is False - None: The function was not continuous over the interval or the function's argument interval is partly in the domain of the function A comparison between an interval and a real number, or a comparison between two intervals may return ``intervalMembership`` of two 3-valued logic values. """ def __init__(self, *args, is_valid=True, **kwargs): self.is_valid = is_valid if len(args) == 1: if isinstance(args[0], interval): self.start, self.end = args[0].start, args[0].end else: self.start = float(args[0]) self.end = float(args[0]) elif len(args) == 2: if args[0] < args[1]: self.start = float(args[0]) self.end = float(args[1]) else: self.start = float(args[1]) self.end = float(args[0]) else: raise ValueError("interval takes a maximum of two float values " "as arguments") @property def mid(self): return (self.start + self.end) / 2.0 @property def width(self): return self.end - self.start def __repr__(self): return "interval(%f, %f)" % (self.start, self.end) def __str__(self): return "[%f, %f]" % (self.start, self.end) def __lt__(self, other): if isinstance(other, (int, float)): if self.end < other: return intervalMembership(True, self.is_valid) elif self.start > other: return intervalMembership(False, self.is_valid) else: return intervalMembership(None, self.is_valid) elif isinstance(other, interval): valid = fuzzy_and([self.is_valid, other.is_valid]) if self.end < other. start: return intervalMembership(True, valid) if self.start > other.end: return intervalMembership(False, valid) return intervalMembership(None, valid) else: return NotImplemented def __gt__(self, other): if isinstance(other, (int, float)): if self.start > other: return intervalMembership(True, self.is_valid) elif self.end < other: return intervalMembership(False, self.is_valid) else: return intervalMembership(None, self.is_valid) elif isinstance(other, interval): return other.__lt__(self) else: return NotImplemented def __eq__(self, other): if isinstance(other, (int, float)): if self.start == other and self.end == other: return intervalMembership(True, self.is_valid) if other in self: return intervalMembership(None, self.is_valid) else: return intervalMembership(False, self.is_valid) if isinstance(other, interval): valid = fuzzy_and([self.is_valid, other.is_valid]) if self.start == other.start and self.end == other.end: return intervalMembership(True, valid) elif self.__lt__(other)[0] is not None: return intervalMembership(False, valid) else: return intervalMembership(None, valid) else: return NotImplemented def __ne__(self, other): if isinstance(other, (int, float)): if self.start == other and self.end == other: return intervalMembership(False, self.is_valid) if other in self: return intervalMembership(None, self.is_valid) else: return intervalMembership(True, self.is_valid) if isinstance(other, interval): valid = fuzzy_and([self.is_valid, other.is_valid]) if self.start == other.start and self.end == other.end: return intervalMembership(False, valid) if not self.__lt__(other)[0] is None: return intervalMembership(True, valid) return intervalMembership(None, valid) else: return NotImplemented def __le__(self, other): if isinstance(other, (int, float)): if self.end <= other: return intervalMembership(True, self.is_valid) if self.start > other: return intervalMembership(False, self.is_valid) else: return intervalMembership(None, self.is_valid) if isinstance(other, interval): valid = fuzzy_and([self.is_valid, other.is_valid]) if self.end <= other.start: return intervalMembership(True, valid) if self.start > other.end: return intervalMembership(False, valid) return intervalMembership(None, valid) else: return NotImplemented def __ge__(self, other): if isinstance(other, (int, float)): if self.start >= other: return intervalMembership(True, self.is_valid) elif self.end < other: return intervalMembership(False, self.is_valid) else: return intervalMembership(None, self.is_valid) elif isinstance(other, interval): return other.__le__(self) def __add__(self, other): if isinstance(other, (int, float)): if self.is_valid: return interval(self.start + other, self.end + other) else: start = self.start + other end = self.end + other return interval(start, end, is_valid=self.is_valid) elif isinstance(other, interval): start = self.start + other.start end = self.end + other.end valid = fuzzy_and([self.is_valid, other.is_valid]) return interval(start, end, is_valid=valid) else: return NotImplemented __radd__ = __add__ def __sub__(self, other): if isinstance(other, (int, float)): start = self.start - other end = self.end - other return interval(start, end, is_valid=self.is_valid) elif isinstance(other, interval): start = self.start - other.end end = self.end - other.start valid = fuzzy_and([self.is_valid, other.is_valid]) return interval(start, end, is_valid=valid) else: return NotImplemented def __rsub__(self, other): if isinstance(other, (int, float)): start = other - self.end end = other - self.start return interval(start, end, is_valid=self.is_valid) elif isinstance(other, interval): return other.__sub__(self) else: return NotImplemented def __neg__(self): if self.is_valid: return interval(-self.end, -self.start) else: return interval(-self.end, -self.start, is_valid=self.is_valid) def __mul__(self, other): if isinstance(other, interval): if self.is_valid is False or other.is_valid is False: return interval(-float('inf'), float('inf'), is_valid=False) elif self.is_valid is None or other.is_valid is None: return interval(-float('inf'), float('inf'), is_valid=None) else: inters = [] inters.append(self.start * other.start) inters.append(self.end * other.start) inters.append(self.start * other.end) inters.append(self.end * other.end) start = min(inters) end = max(inters) return interval(start, end) elif isinstance(other, (int, float)): return interval(self.start*other, self.end*other, is_valid=self.is_valid) else: return NotImplemented __rmul__ = __mul__ def __contains__(self, other): if isinstance(other, (int, float)): return self.start <= other and self.end >= other else: return self.start <= other.start and other.end <= self.end def __rtruediv__(self, other): if isinstance(other, (int, float)): other = interval(other) return other.__truediv__(self) elif isinstance(other, interval): return other.__truediv__(self) else: return NotImplemented def __truediv__(self, other): # Both None and False are handled if not self.is_valid: # Don't divide as the value is not valid return interval(-float('inf'), float('inf'), is_valid=self.is_valid) if isinstance(other, (int, float)): if other == 0: # Divide by zero encountered. valid nowhere return interval(-float('inf'), float('inf'), is_valid=False) else: return interval(self.start / other, self.end / other) elif isinstance(other, interval): if other.is_valid is False or self.is_valid is False: return interval(-float('inf'), float('inf'), is_valid=False) elif other.is_valid is None or self.is_valid is None: return interval(-float('inf'), float('inf'), is_valid=None) else: # denominator contains both signs, i.e. being divided by zero # return the whole real line with is_valid = None if 0 in other: return interval(-float('inf'), float('inf'), is_valid=None) # denominator negative this = self if other.end < 0: this = -this other = -other # denominator positive inters = [] inters.append(this.start / other.start) inters.append(this.end / other.start) inters.append(this.start / other.end) inters.append(this.end / other.end) start = max(inters) end = min(inters) return interval(start, end) else: return NotImplemented def __pow__(self, other): # Implements only power to an integer. from .lib_interval import exp, log if not self.is_valid: return self if isinstance(other, interval): return exp(other * log(self)) elif isinstance(other, (float, int)): if other < 0: return 1 / self.__pow__(abs(other)) else: if int(other) == other: return _pow_int(self, other) else: return _pow_float(self, other) else: return NotImplemented def __rpow__(self, other): if isinstance(other, (float, int)): if not self.is_valid: #Don't do anything return self elif other < 0: if self.width > 0: return interval(-float('inf'), float('inf'), is_valid=False) else: power_rational = nsimplify(self.start) num, denom = power_rational.as_numer_denom() if denom % 2 == 0: return interval(-float('inf'), float('inf'), is_valid=False) else: start = -abs(other)**self.start end = start return interval(start, end) else: return interval(other**self.start, other**self.end) elif isinstance(other, interval): return other.__pow__(self) else: return NotImplemented def __hash__(self): return hash((self.is_valid, self.start, self.end)) def _pow_float(inter, power): """Evaluates an interval raised to a floating point.""" power_rational = nsimplify(power) num, denom = power_rational.as_numer_denom() if num % 2 == 0: start = abs(inter.start)**power end = abs(inter.end)**power if start < 0: ret = interval(0, max(start, end)) else: ret = interval(start, end) return ret elif denom % 2 == 0: if inter.end < 0: return interval(-float('inf'), float('inf'), is_valid=False) elif inter.start < 0: return interval(0, inter.end**power, is_valid=None) else: return interval(inter.start**power, inter.end**power) else: if inter.start < 0: start = -abs(inter.start)**power else: start = inter.start**power if inter.end < 0: end = -abs(inter.end)**power else: end = inter.end**power return interval(start, end, is_valid=inter.is_valid) def _pow_int(inter, power): """Evaluates an interval raised to an integer power""" power = int(power) if power & 1: return interval(inter.start**power, inter.end**power) else: if inter.start < 0 and inter.end > 0: start = 0 end = max(inter.start**power, inter.end**power) return interval(start, end) else: return interval(inter.start**power, inter.end**power)
10a8488c24740825db9c62ac1bd41be08cfa8da02984005d16b0e4f84669216e
#!/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 distutils.version import LooseVersion try: import mpmath if mpmath.__version__ < LooseVersion(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.benchmarks', 'sympy.calculus', 'sympy.categories', 'sympy.codegen', 'sympy.combinatorics', 'sympy.concrete', 'sympy.core', 'sympy.core.benchmarks', 'sympy.crypto', 'sympy.deprecated', '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.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.strategies', 'sympy.strategies.branch', 'sympy.tensor', 'sympy.tensor.array', '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): import os 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.deprecated.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.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.tests', 'sympy.strategies.branch.tests', 'sympy.strategies.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 )
9d4976addd946d8859745f17c3d6dbfb6bda959601b0cb32cb1ca671511263db
#!/usr/bin/env python # # Tests that a useful message is give in the ImportError when trying to import # sympy from Python 2. This is tested on Travis to ensure that we don't get a # Py2 SyntaxError from sympy/__init__.py import sys assert sys.version_info[:2] == (2, 7), "This test is for Python 2.7 only" import os thisdir = os.path.dirname(__file__) parentdir = os.path.normpath(os.path.join(thisdir, '..')) # Append the SymPy root directory to path sys.path.append(parentdir) try: import sympy except ImportError as exc: message = str(exc) # e.g. "Python version 3.5 or above is required for SymPy." assert message.startswith("Python version") assert message.endswith(" or above is required for SymPy.") else: raise AssertionError("import sympy should give ImportError on Python 2.7")
d16ec3ad49da027d768881bc7f305d671e7644af9a55f6d4c839045b5ec83f00
#!/usr/bin/env python3 from subprocess import check_output import sys import os.path def main(tarname, gitroot): """Run this as ./compare_tar_against_git.py TARFILE GITROOT Args ==== TARFILE: Path to the built sdist (sympy-xx.tar.gz) GITROOT: Path ro root of git (dir containing .git) """ compare_tar_against_git(tarname, gitroot) ## TARBALL WHITELISTS # If a file does not end up in the tarball that should, add it to setup.py if # it is Python, or MANIFEST.in if it is not. (There is a command at the top # of setup.py to gather all the things that should be there). # TODO: Also check that this whitelist isn't growing out of date from files # removed from git. # Files that are in git that should not be in the tarball git_whitelist = { # Git specific dotfiles '.gitattributes', '.gitignore', '.mailmap', # Travis and CI '.travis.yml', '.ci/durations.json', '.ci/generate_durations_log.sh', '.ci/parse_durations_log.py', '.ci/blacklisted.json', '.ci/README.rst', '.github/FUNDING.yml', '.editorconfig', '.coveragerc', 'CODEOWNERS', 'asv.conf.travis.json', 'coveragerc_travis', 'codecov.yml', 'pytest.ini', 'MANIFEST.in', # Code of conduct 'CODE_OF_CONDUCT.md', # Pull request template 'PULL_REQUEST_TEMPLATE.md', # Contributing guide 'CONTRIBUTING.md', # Nothing from bin/ should be shipped unless we intend to install it. Most # of this stuff is for development anyway. To run the tests from the # tarball, use setup.py test, or import sympy and run sympy.test() or # sympy.doctest(). 'bin/adapt_paths.py', 'bin/ask_update.py', 'bin/authors_update.py', 'bin/build_doc.sh', 'bin/coverage_doctest.py', 'bin/coverage_report.py', 'bin/deploy_doc.sh', 'bin/diagnose_imports', 'bin/doctest', 'bin/generate_module_list.py', 'bin/generate_test_list.py', 'bin/get_sympy.py', 'bin/mailmap_update.py', 'bin/py.bench', 'bin/strip_whitespace', 'bin/sympy_time.py', 'bin/sympy_time_cache.py', 'bin/test', 'bin/test_external_imports.py', 'bin/test_executable.py', 'bin/test_import', 'bin/test_import.py', 'bin/test_isolated', 'bin/test_py2_import.py', 'bin/test_setup.py', 'bin/test_submodule_imports.py', 'bin/test_travis.sh', # The notebooks are not ready for shipping yet. They need to be cleaned # up, and preferably doctested. See also # https://github.com/sympy/sympy/issues/6039. 'examples/advanced/identitysearch_example.ipynb', 'examples/beginner/plot_advanced.ipynb', 'examples/beginner/plot_colors.ipynb', 'examples/beginner/plot_discont.ipynb', 'examples/beginner/plot_gallery.ipynb', 'examples/beginner/plot_intro.ipynb', 'examples/intermediate/limit_examples_advanced.ipynb', 'examples/intermediate/schwarzschild.ipynb', 'examples/notebooks/density.ipynb', 'examples/notebooks/fidelity.ipynb', 'examples/notebooks/fresnel_integrals.ipynb', 'examples/notebooks/qubits.ipynb', 'examples/notebooks/sho1d_example.ipynb', 'examples/notebooks/spin.ipynb', 'examples/notebooks/trace.ipynb', 'examples/notebooks/Bezout_Dixon_resultant.ipynb', 'examples/notebooks/IntegrationOverPolytopes.ipynb', 'examples/notebooks/Macaulay_resultant.ipynb', 'examples/notebooks/Sylvester_resultant.ipynb', 'examples/notebooks/README.txt', # This stuff :) 'release/.gitignore', 'release/README.md', 'release/Vagrantfile', 'release/fabfile.py', 'release/Dockerfile', 'release/Dockerfile-base', 'release/release.sh', 'release/rever.xsh', 'release/pull_and_run_rever.sh', 'release/compare_tar_against_git.py', 'release/update_docs.py', # This is just a distribute version of setup.py. Used mainly for setup.py # develop, which we don't care about in the release tarball 'setupegg.py', # pytest stuff 'conftest.py', # Encrypted deploy key for deploying dev docs to GitHub 'github_deploy_key.enc', } # Files that should be in the tarball should not be in git tarball_whitelist = { # Generated by setup.py. Contains metadata for PyPI. "PKG-INFO", # Generated by setuptools. More metadata. 'setup.cfg', 'sympy.egg-info/PKG-INFO', 'sympy.egg-info/SOURCES.txt', 'sympy.egg-info/dependency_links.txt', 'sympy.egg-info/requires.txt', 'sympy.egg-info/top_level.txt', 'sympy.egg-info/not-zip-safe', 'sympy.egg-info/entry_points.txt', # Not sure where this is generated from... 'doc/commit_hash.txt', } def blue(text): return "\033[34m%s\033[0m" % text def red(text): return "\033[31m%s\033[0m" % text def run(*cmdline, cwd=None): """ Run command in subprocess and get lines of output """ return check_output(cmdline, encoding='utf-8', cwd=cwd).splitlines() def full_path_split(path): """ Function to do a full split on a path. """ # Based on https://stackoverflow.com/a/13505966/161801 rest, tail = os.path.split(path) if not rest or rest == os.path.sep: return (tail,) return full_path_split(rest) + (tail,) def compare_tar_against_git(tarname, gitroot): """ Compare the contents of the tarball against git ls-files See the bottom of the file for the whitelists. """ git_lsfiles = set(i.strip() for i in run('git', 'ls-files', cwd=gitroot)) tar_output_orig = set(run('tar', 'tf', tarname)) tar_output = set() for file in tar_output_orig: # The tar files are like sympy-0.7.3/sympy/__init__.py, and the git # files are like sympy/__init__.py. split_path = full_path_split(file) if split_path[-1]: # Exclude directories, as git ls-files does not include them tar_output.add(os.path.join(*split_path[1:])) # print tar_output # print git_lsfiles fail = False print() print(blue("Files in the tarball from git that should not be there:")) print() for line in sorted(tar_output.intersection(git_whitelist)): fail = True print(line) print() print(blue("Files in git but not in the tarball:")) print() for line in sorted(git_lsfiles - tar_output - git_whitelist): fail = True print(line) print() print(blue("Files in the tarball but not in git:")) print() for line in sorted(tar_output - git_lsfiles - tarball_whitelist): fail = True print(line) print() if fail: sys.exit(red("Non-whitelisted files found or not found in the tarball")) if __name__ == "__main__": main(*sys.argv[1:])
b42663da36b5d23aa0d5742e59116ae24286c665cabdb7a8d5ba19e4e27f34af
""" 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, 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, 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) 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, MutableDenseNDimArray, ImmutableDenseNDimArray, MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray, tensorproduct, tensorcontraction, 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() # This is slow to import: #import abc from .deprecated import C, ClassRegistry, class_registry __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', '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', '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', # 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', 'MutableDenseNDimArray', 'ImmutableDenseNDimArray', 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray', 'tensorproduct', 'tensorcontraction', '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', # sympy.deprecated: 'C', 'ClassRegistry', 'class_registry', ] #===========================================================================# # # # 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', 'deprecated', 'discrete', 'external', 'functions', 'geometry', 'interactive', 'multipledispatch', 'ntheory', 'parsing', 'plotting', 'polys', 'printing', 'release', 'strategies', 'tensor', 'utilities', ])